-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathindex.ts
141 lines (126 loc) · 4.31 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {
toMessageRelativeFilePath,
posixPath,
escapePath,
getFileLoaderUtils,
findAsyncSequential,
} from '@docusaurus/utils';
import visit from 'unist-util-visit';
import path from 'path';
import url from 'url';
import fs from 'fs-extra';
import escapeHtml from 'escape-html';
import type {Plugin, Transformer} from 'unified';
import type {Image, Literal} from 'mdast';
const {
loaders: {inlineMarkdownImageFileLoader},
} = getFileLoaderUtils();
interface PluginOptions {
filePath: string;
staticDirs: string[];
siteDir: string;
}
function toImageRequireNode(node: Image, imagePath: string, filePath: string) {
const jsxNode = node as Literal & Partial<Image>;
let relativeImagePath = posixPath(
path.relative(path.dirname(filePath), imagePath),
);
relativeImagePath = `./${relativeImagePath}`;
const parsedUrl = url.parse(node.url);
const hash = parsedUrl.hash ?? '';
const search = parsedUrl.search ?? '';
const alt = node.alt ? `alt={"${escapeHtml(node.alt)}"} ` : '';
const src = `require("${inlineMarkdownImageFileLoader}${
escapePath(relativeImagePath) + search
}").default${hash ? ` + '${hash}'` : ''}`;
const title = node.title ? ` title="${escapeHtml(node.title)}"` : '';
Object.keys(jsxNode).forEach(
(key) => delete jsxNode[key as keyof typeof jsxNode],
);
(jsxNode as Literal).type = 'jsx';
jsxNode.value = `<img ${alt}src={${src}}${title} />`;
}
async function ensureImageFileExist(imagePath: string, sourceFilePath: string) {
const imageExists = await fs.pathExists(imagePath);
if (!imageExists) {
throw new Error(
`Image ${toMessageRelativeFilePath(
imagePath,
)} used in ${toMessageRelativeFilePath(sourceFilePath)} not found.`,
);
}
}
async function getImageAbsolutePath(
imagePath: string,
{siteDir, filePath, staticDirs}: PluginOptions,
) {
if (imagePath.startsWith('@site/')) {
const imageFilePath = path.join(siteDir, imagePath.replace('@site/', ''));
await ensureImageFileExist(imageFilePath, filePath);
return imageFilePath;
} else if (path.isAbsolute(imagePath)) {
// absolute paths are expected to exist in the static folder
const possiblePaths = staticDirs.map((dir) => path.join(dir, imagePath));
const imageFilePath = await findAsyncSequential(
possiblePaths,
fs.pathExists,
);
if (!imageFilePath) {
throw new Error(
`Image ${possiblePaths
.map((p) => toMessageRelativeFilePath(p))
.join(' or ')} used in ${toMessageRelativeFilePath(
filePath,
)} not found.`,
);
}
return imageFilePath;
}
// We try to convert image urls without protocol to images with require calls
// going through webpack ensures that image assets exist at build time
else {
// relative paths are resolved against the source file's folder
const imageFilePath = path.join(path.dirname(filePath), imagePath);
await ensureImageFileExist(imageFilePath, filePath);
return imageFilePath;
}
}
async function processImageNode(node: Image, options: PluginOptions) {
if (!node.url) {
throw new Error(
`Markdown image URL is mandatory in "${toMessageRelativeFilePath(
options.filePath,
)}" file`,
);
}
const parsedUrl = url.parse(node.url);
if (parsedUrl.protocol || !parsedUrl.pathname) {
// pathname:// is an escape hatch,
// in case user does not want his images to be converted to require calls going through webpack loader
// we don't have to document this for now,
// it's mostly to make next release less risky (2.0.0-alpha.59)
if (parsedUrl.protocol === 'pathname:') {
node.url = node.url.replace('pathname://', '');
}
return;
}
const imagePath = await getImageAbsolutePath(parsedUrl.pathname, options);
toImageRequireNode(node, imagePath, options.filePath);
}
const plugin: Plugin<[PluginOptions]> = (options) => {
const transformer: Transformer = async (root) => {
const promises: Promise<void>[] = [];
visit(root, 'image', (node: Image) => {
promises.push(processImageNode(node, options));
});
await Promise.all(promises);
};
return transformer;
};
export default plugin;