@proto-kit/remark-code-import 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,18 @@
1
+ Copyright (c) 2020, Kai Hao
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
4
+ this software and associated documentation files (the "Software"), to deal in
5
+ the Software without restriction, including without limitation the rights to
6
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
7
+ the Software, and to permit persons to whom the Software is furnished to do so,
8
+ subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all
11
+ copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
15
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
16
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
17
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
18
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,109 @@
1
+ # `remark-code-import`
2
+
3
+ 📝 Populate code blocks from files.
4
+
5
+ [![npm version](https://badge.fury.io/js/remark-code-import.svg)](https://badge.fury.io/js/remark-code-import)
6
+
7
+ **Starting from v1.0.0, the plugin is now [ESM only](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c). Node 12+ is needed to use it and it must be `import`ed instead of `require`d.**
8
+
9
+ ## Installation
10
+
11
+ ```sh
12
+ npm install -D @proto-kit/remark-code-import
13
+ ```
14
+
15
+ ## Setup
16
+
17
+ The plugin can be imported via named export, there's no default export.
18
+
19
+ ```js
20
+ import codeImport from 'remark-code-import';
21
+ ```
22
+
23
+ See [**Using plugins**](https://github.com/remarkjs/remark/blob/master/doc/plugins.md#using-plugins) for more instructions in the official documentation.
24
+
25
+ It can also be used in various of libraries: `remark`: [MDX](https://mdxjs.com/advanced/plugins#using-remark-and-rehype-plugins), [Gatsby `gatsby-plugin-mdx`](https://www.gatsbyjs.org/docs/mdx/plugins/#remark-plugins), [Storybook docs](https://github.com/storybookjs/storybook/tree/master/addons/docs#manual-configuration).
26
+
27
+ ## Usage
28
+
29
+ Transform:
30
+
31
+ ````md
32
+ ```js file=./say-hi.js
33
+ ```
34
+ ````
35
+
36
+ into:
37
+
38
+ ````md
39
+ ```js file=./say-hi.js
40
+ console.log('Hello remark-code-import!');
41
+ ```
42
+ ````
43
+
44
+ The file path is relative to the markdown file path. You can use `<rootDir>` at the start of the path to import files relatively from the [`rootDir`](#options):
45
+
46
+ ````md
47
+ ```js file=<rootDir>/file-under-root-directory.js
48
+ ```
49
+ ````
50
+
51
+ You may also specify lines or ranges:
52
+
53
+ ````md
54
+ Only line 3:
55
+ ```js file=./say-hi.js#L3
56
+ ```
57
+
58
+ Line 3 to line 6:
59
+ ```js file=./say-hi.js#L3-L6
60
+ ```
61
+
62
+ Line 3 to the end of the file
63
+ ```js file=./say-hi.js#L3-
64
+ ```
65
+ ````
66
+
67
+ File paths with spaces should be escaped with `\`:
68
+
69
+ ````md
70
+ ```js file=./file\ with\ spaces.js
71
+ ```
72
+ ````
73
+
74
+ ## Options
75
+
76
+ - `async: boolean`: By default, this plugin uses `readFileSync` to read the contents of the files. Set this to `true` if you want to use `readFile` for non-blocking IO.
77
+ - `rootDir: string`: Change what `<rootDir>` refers to. Defaults to `process.cwd()`.
78
+ - `preserveTrailingNewline: boolean`: By default, this plugin will trim the trailing newline of the file when importing the code. You can preserve the trailing new line in the code block by setting this option to `true`.
79
+ - `removeRedundantIndentations: boolean`: Set to `true` to remove redundant indentations for each line. For instance, the imported code of:
80
+ ```
81
+ First line
82
+ Second line
83
+ ```
84
+ will become...
85
+ ```
86
+ First line
87
+ Second line
88
+ ```
89
+ - `allowImportingFromOutside: boolean`: For security reasons, by default this plugin doesn't allow importing files from outside the root directory (`rootDir`). Set this option to `true` to bypass this limit.
90
+
91
+ ## Use as a Gatsby remark plugin
92
+
93
+ Use the `/gatsby` endpoint. It's possible through [`to-gatsby-remark-plugin`](https://github.com/kevin940726/to-gatsby-remark-plugin).
94
+
95
+ ```js
96
+ {
97
+ resolve: 'remark-code-import/gatsby',
98
+ options: {}
99
+ }
100
+ ```
101
+
102
+ ## Testing
103
+
104
+ After installing dependencies with `npm install`, the tests can be run with: `npm test`
105
+
106
+ ## License
107
+
108
+ Kai Hao
109
+ [MIT](LICENSE)
@@ -0,0 +1,12 @@
1
+ import type { Root } from 'mdast';
2
+ import type { VFile } from 'vfile';
3
+ interface CodeImportOptions {
4
+ async?: boolean;
5
+ preserveTrailingNewline?: boolean;
6
+ removeRedundantIndentations?: boolean;
7
+ rootDir?: string;
8
+ allowImportingFromOutside?: boolean;
9
+ }
10
+ declare function codeImport(options?: CodeImportOptions): (tree: Root, file: VFile) => Promise<void[]> | undefined;
11
+ export { codeImport };
12
+ export default codeImport;
package/dist/index.js ADDED
@@ -0,0 +1,165 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { EOL } from 'node:os';
4
+ import { visit } from 'unist-util-visit';
5
+ import stripIndent from 'strip-indent';
6
+ function getGroup(input) {
7
+ var _a;
8
+ const result = /group (?<group>[\w\-_]*)/.exec(input);
9
+ return (_a = result === null || result === void 0 ? void 0 : result.groups) === null || _a === void 0 ? void 0 : _a.group;
10
+ }
11
+ function extractElements(input) {
12
+ return input.split(EOL).map(line => {
13
+ if (line.includes("group")) {
14
+ const group = getGroup(line);
15
+ if (group === undefined) {
16
+ return {
17
+ type: "text",
18
+ text: line
19
+ };
20
+ }
21
+ else {
22
+ return {
23
+ type: "group",
24
+ group
25
+ };
26
+ }
27
+ }
28
+ else {
29
+ return {
30
+ type: "text",
31
+ text: line
32
+ };
33
+ }
34
+ });
35
+ }
36
+ function extractGroups(content) {
37
+ const map = {};
38
+ content.forEach(((line, index) => {
39
+ var _a;
40
+ if (line.includes("group")) {
41
+ const group = getGroup(line);
42
+ if (group !== undefined) {
43
+ ((_a = map[group]) !== null && _a !== void 0 ? _a : (map[group] = [])).push(index);
44
+ }
45
+ }
46
+ }));
47
+ return map;
48
+ }
49
+ function transformDoc(content, elements) {
50
+ const groups = extractGroups(content);
51
+ return elements.flatMap(el => {
52
+ if (el.type === "text") {
53
+ return [el.text];
54
+ }
55
+ else {
56
+ const array = groups[el.group];
57
+ if (array && array.length < 2) {
58
+ console.error(`Group ${el.group} not found in document`);
59
+ }
60
+ const group = content.slice(array.shift() + 1, array.shift());
61
+ // Not sure if that is necessary
62
+ groups[el.group] = array;
63
+ return group;
64
+ }
65
+ }).join("\n");
66
+ }
67
+ function extractLines(mode, content, fromLine, hasDash, toLine, oldValue, preserveTrailingNewline = false) {
68
+ const lines = content.split(EOL);
69
+ if (mode === "classic") {
70
+ const start = fromLine || 1;
71
+ let end;
72
+ if (!hasDash) {
73
+ end = start;
74
+ }
75
+ else if (toLine) {
76
+ end = toLine;
77
+ }
78
+ else if (lines[lines.length - 1] === '' && !preserveTrailingNewline) {
79
+ end = lines.length - 1;
80
+ }
81
+ else {
82
+ end = lines.length;
83
+ }
84
+ return lines.slice(start - 1, end).join('\n');
85
+ }
86
+ else {
87
+ const elements = extractElements(oldValue);
88
+ return transformDoc(lines, elements);
89
+ }
90
+ }
91
+ function codeImport(options = {}) {
92
+ const rootDir = options.rootDir || process.cwd();
93
+ if (!path.isAbsolute(rootDir)) {
94
+ throw new Error(`"rootDir" has to be an absolute path`);
95
+ }
96
+ return function transformer(tree, file) {
97
+ const codes = [];
98
+ const promises = [];
99
+ visit(tree, 'code', (node, index, parent) => {
100
+ codes.push([node, index, parent]);
101
+ });
102
+ for (const [node] of codes) {
103
+ const fileMeta = (node.meta || '')
104
+ // Allow escaping spaces
105
+ .split(/(?<!\\) /g)
106
+ .find((meta) => meta.startsWith('file='));
107
+ if (!fileMeta) {
108
+ continue;
109
+ }
110
+ if (!file.dirname) {
111
+ throw new Error('"file" should be an instance of VFile');
112
+ }
113
+ const res = /^file=(?<path>.+?)(?:(?:#(?:L(?<from>\d+)(?<dash>-)?)?)(?:L(?<to>\d+))?)?$/.exec(fileMeta);
114
+ if (!res || !res.groups || !res.groups.path) {
115
+ throw new Error(`Unable to parse file path ${fileMeta}`);
116
+ }
117
+ const filePath = res.groups.path;
118
+ const fromLine = res.groups.from
119
+ ? parseInt(res.groups.from, 10)
120
+ : undefined;
121
+ const hasDash = !!res.groups.dash || fromLine === undefined;
122
+ const toLine = res.groups.to ? parseInt(res.groups.to, 10) : undefined;
123
+ const normalizedFilePath = filePath
124
+ .replace(/^<rootDir>/, rootDir)
125
+ .replace(/\\ /g, ' ');
126
+ const fileAbsPath = path.resolve(file.dirname, normalizedFilePath);
127
+ const mode = (node.meta || '').includes("inline") ? "inline" : "classic";
128
+ if (!options.allowImportingFromOutside) {
129
+ const relativePathFromRootDir = path.relative(rootDir, fileAbsPath);
130
+ if (!rootDir ||
131
+ relativePathFromRootDir.startsWith(`..${path.sep}`) ||
132
+ path.isAbsolute(relativePathFromRootDir)) {
133
+ throw new Error(`Attempted to import code from "${fileAbsPath}", which is outside from the rootDir "${rootDir}"`);
134
+ }
135
+ }
136
+ if (options.async) {
137
+ promises.push(new Promise((resolve, reject) => {
138
+ fs.readFile(fileAbsPath, 'utf8', (err, fileContent) => {
139
+ if (err) {
140
+ reject(err);
141
+ return;
142
+ }
143
+ node.value = extractLines(mode, fileContent, fromLine, hasDash, toLine, node.value, options.preserveTrailingNewline);
144
+ if (options.removeRedundantIndentations) {
145
+ node.value = stripIndent(node.value);
146
+ }
147
+ resolve();
148
+ });
149
+ }));
150
+ }
151
+ else {
152
+ const fileContent = fs.readFileSync(fileAbsPath, 'utf8');
153
+ node.value = extractLines(mode, fileContent, fromLine, hasDash, toLine, node.value, options.preserveTrailingNewline);
154
+ if (options.removeRedundantIndentations) {
155
+ node.value = stripIndent(node.value);
156
+ }
157
+ }
158
+ }
159
+ if (promises.length) {
160
+ return Promise.all(promises);
161
+ }
162
+ };
163
+ }
164
+ export { codeImport };
165
+ export default codeImport;
@@ -0,0 +1,4 @@
1
+ const toGatsbyRemarkPlugin = require('to-gatsby-remark-plugin');
2
+ const codeImport = require('../');
3
+
4
+ module.exports = toGatsbyRemarkPlugin(codeImport);
@@ -0,0 +1,3 @@
1
+ {
2
+ "main": "index.js"
3
+ }
package/package.json ADDED
@@ -0,0 +1,63 @@
1
+ {
2
+ "name": "@proto-kit/remark-code-import",
3
+ "description": "📝 Populate code blocks from files",
4
+ "version": "1.2.0",
5
+ "engines": {
6
+ "node": ">= 12"
7
+ },
8
+ "type": "module",
9
+ "exports": "./dist/index.js",
10
+ "types": "./dist/index.d.ts",
11
+ "author": "Protokit & Kai Hao",
12
+ "license": "MIT",
13
+ "homepage": "https://github.com/kevin940726/remark-code-import#readme",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/kevin940726/remark-code-import.git"
17
+ },
18
+ "files": [
19
+ "dist",
20
+ "gatsby"
21
+ ],
22
+ "keywords": [
23
+ "remark",
24
+ "remark-plugin",
25
+ "markdown",
26
+ "code-block",
27
+ "code-fence",
28
+ "file-system",
29
+ "import-code",
30
+ "gatsby",
31
+ "gatsby-plugin"
32
+ ],
33
+ "scripts": {
34
+ "build": "tsc",
35
+ "test": "vitest",
36
+ "prepare": "npm run build && npm test -- run",
37
+ "publish": "npm publish --access public"
38
+ },
39
+ "dependencies": {
40
+ "strip-indent": "^4.0.0",
41
+ "to-gatsby-remark-plugin": "^0.1.0",
42
+ "unist-util-visit": "^4.1.0"
43
+ },
44
+ "devDependencies": {
45
+ "mdast": "^3.0.0",
46
+ "prettier": "2.5.1",
47
+ "remark": "^14.0.2",
48
+ "typescript": "4.4.4",
49
+ "vfile": "^5.3.0",
50
+ "vitest": "^0.31.0"
51
+ },
52
+ "prettier": {
53
+ "singleQuote": true,
54
+ "trailingComma": "es5"
55
+ },
56
+ "main": "index.js",
57
+ "directories": {
58
+ "test": "test"
59
+ },
60
+ "bugs": {
61
+ "url": "https://github.com/kevin940726/remark-code-import/issues"
62
+ }
63
+ }