forked from withastro/astro
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
269 lines (241 loc) · 9.45 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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
import { renderMarkdown } from '@astrojs/markdown-remark';
import ancestor from 'common-ancestor-path';
import esbuild from 'esbuild';
import fs from 'fs';
import matter from 'gray-matter';
import { fileURLToPath } from 'url';
import type { Plugin, ViteDevServer } from 'vite';
import type { AstroSettings } from '../@types/astro';
import { pagesVirtualModuleId } from '../core/app/index.js';
import { cachedCompilation, CompileProps } from '../core/compile/index.js';
import { collectErrorMetadata } from '../core/errors.js';
import type { LogOptions } from '../core/logger/core.js';
import { isMarkdownFile } from '../core/util.js';
import type { PluginMetadata as AstroPluginMetadata } from '../vite-plugin-astro/types';
import { getFileInfo } from '../vite-plugin-utils/index.js';
import {
createTransformStyles,
createViteStyleTransformer,
ViteStyleTransformer,
} from '../vite-style-transform/index.js';
interface AstroPluginOptions {
settings: AstroSettings;
logging: LogOptions;
}
const MARKDOWN_IMPORT_FLAG = '?mdImport';
const MARKDOWN_CONTENT_FLAG = '?content';
function safeMatter(source: string, id: string) {
try {
return matter(source);
} catch (e) {
(e as any).id = id;
throw collectErrorMetadata(e);
}
}
// TODO: Clean up some of the shared logic between this Markdown plugin and the Astro plugin.
// Both end up connecting a `load()` hook to the Astro compiler, and share some copy-paste
// logic in how that is done.
export default function markdown({ settings }: AstroPluginOptions): Plugin {
const { config } = settings;
function normalizeFilename(filename: string) {
if (filename.startsWith('/@fs')) {
filename = filename.slice('/@fs'.length);
} else if (filename.startsWith('/') && !ancestor(filename, config.root.pathname)) {
filename = new URL('.' + filename, config.root).pathname;
}
return filename;
}
// Weird Vite behavior: Vite seems to use a fake "index.html" importer when you
// have `enforce: pre`. This can probably be removed once the vite issue is fixed.
// see: https://github.com/vitejs/vite/issues/5981
const fakeRootImporter = fileURLToPath(new URL('index.html', config.root));
function isRootImport(importer: string | undefined) {
if (!importer) {
return true;
}
if (importer === fakeRootImporter) {
return true;
}
if (importer === '\0' + pagesVirtualModuleId) {
return true;
}
return false;
}
let styleTransformer: ViteStyleTransformer;
let viteDevServer: ViteDevServer | undefined;
return {
name: 'astro:markdown',
enforce: 'pre',
configResolved(_resolvedConfig) {
styleTransformer = createViteStyleTransformer(_resolvedConfig);
},
configureServer(server) {
styleTransformer.viteDevServer = server;
},
async resolveId(id, importer, options) {
// Resolve any .md (or alternative extensions of markdown files like .markdown) files with the `?content` cache buster. This should only come from
// an already-resolved JS module wrapper. Needed to prevent infinite loops in Vite.
// Unclear if this is expected or if cache busting is just working around a Vite bug.
if (isMarkdownFile(id, { criteria: 'endsWith', suffix: MARKDOWN_CONTENT_FLAG })) {
const resolvedId = await this.resolve(id, importer, { skipSelf: true, ...options });
return resolvedId?.id.replace(MARKDOWN_CONTENT_FLAG, '');
}
// If the markdown file is imported from another file via ESM, resolve a JS representation
// that defers the markdown -> HTML rendering until it is needed. This is especially useful
// when fetching and then filtering many markdown files, like with import.meta.glob() or Astro.glob().
// Otherwise, resolve directly to the actual component.
if (isMarkdownFile(id, { criteria: 'endsWith' }) && !isRootImport(importer)) {
const resolvedId = await this.resolve(id, importer, { skipSelf: true, ...options });
if (resolvedId) {
return resolvedId.id + MARKDOWN_IMPORT_FLAG;
}
}
// In all other cases, we do nothing and rely on normal Vite resolution.
return undefined;
},
async load(id, opts) {
// A markdown file has been imported via ESM!
// Return the file's JS representation, including all Markdown
// frontmatter and a deferred `import() of the compiled markdown content.
if (isMarkdownFile(id, { criteria: 'endsWith', suffix: MARKDOWN_IMPORT_FLAG })) {
const { fileId, fileUrl } = getFileInfo(id, config);
const source = await fs.promises.readFile(fileId, 'utf8');
const { data: frontmatter, content: rawContent } = safeMatter(source, fileId);
return {
code: `
// Static
export const frontmatter = ${escapeViteEnvReferences(JSON.stringify(frontmatter))};
export const file = ${JSON.stringify(fileId)};
export const url = ${JSON.stringify(fileUrl)};
export function rawContent() {
return ${escapeViteEnvReferences(JSON.stringify(rawContent))};
}
export async function compiledContent() {
return load().then((m) => m.compiledContent());
}
// Deferred
export default async function load() {
return (await import(${JSON.stringify(fileId + MARKDOWN_CONTENT_FLAG)}));
}
export function Content(...args) {
return load().then((m) => m.default(...args));
}
Content.isAstroComponentFactory = true;
export function getHeadings() {
return load().then((m) => m.metadata.headings);
}
export function getHeaders() {
console.warn('getHeaders() have been deprecated. Use getHeadings() function instead.');
return load().then((m) => m.metadata.headings);
};`,
map: null,
};
}
// A markdown file is being rendered! This markdown file was either imported
// directly as a page in Vite, or it was a deferred render from a JS module.
// This returns the compiled markdown -> astro component that renders to HTML.
if (isMarkdownFile(id, { criteria: 'endsWith' })) {
const filename = normalizeFilename(id);
const source = await fs.promises.readFile(filename, 'utf8');
const renderOpts = config.markdown;
const fileUrl = new URL(`file://${filename}`);
// Extract special frontmatter keys
let { data: frontmatter, content: markdownContent } = safeMatter(source, filename);
// Turn HTML comments into JS comments while preventing nested `*/` sequences
// from ending the JS comment by injecting a zero-width space
// Inside code blocks, this is removed during renderMarkdown by the remark-escape plugin.
markdownContent = markdownContent.replace(
/<\s*!--([^-->]*)(.*?)-->/gs,
(whole) => `{/*${whole.replace(/\*\//g, '*\u200b/')}*/}`
);
let renderResult = await renderMarkdown(markdownContent, {
...renderOpts,
fileURL: fileUrl,
isAstroFlavoredMd: true,
} as any);
let { code: astroResult, metadata } = renderResult;
const { layout = '', components = '', setup = '', ...content } = frontmatter;
content.astro = metadata;
content.url = getFileInfo(id, config).fileUrl;
content.file = filename;
const prelude = `---
import Slugger from 'github-slugger';
${layout ? `import Layout from '${layout}';` : ''}
${components ? `import * from '${components}';` : ''}
${setup}
const slugger = new Slugger();
function $$slug(value) {
return slugger.slug(value);
}
const $$content = ${JSON.stringify(content)};
Object.defineProperty($$content.astro, 'headers', {
get() {
console.warn('[${JSON.stringify(id)}] content.astro.headers is now content.astro.headings.');
return this.headings;
}
});
---`;
const imports = `${layout ? `import Layout from '${layout}';` : ''}
${setup}`.trim();
// If the user imported "Layout", wrap the content in a Layout
if (/\bLayout\b/.test(imports)) {
astroResult = `${prelude}\n<Layout content={$$content}>\n\n${astroResult}\n\n</Layout>`;
} else {
// Note: without a Layout, we need to inject `head` manually so `maybeRenderHead` runs
astroResult = `${prelude}\n<head></head>${astroResult}`;
}
// Transform from `.astro` to valid `.ts`
const compileProps: CompileProps = {
config,
filename,
source: astroResult,
transformStyle: createTransformStyles(
styleTransformer,
filename,
Boolean(opts?.ssr),
this
),
};
let transformResult = await cachedCompilation(compileProps);
let { code: tsResult } = transformResult;
tsResult = `\nexport const metadata = ${JSON.stringify(metadata)};
export const frontmatter = ${JSON.stringify(content)};
export function rawContent() {
return ${JSON.stringify(markdownContent)};
}
export function compiledContent() {
return ${JSON.stringify(renderResult.metadata.html)};
}
${tsResult}`;
// Compile from `.ts` to `.js`
const { code } = await esbuild.transform(tsResult, {
loader: 'ts',
sourcemap: false,
sourcefile: id,
});
const astroMetadata: AstroPluginMetadata['astro'] = {
clientOnlyComponents: transformResult.clientOnlyComponents,
hydratedComponents: transformResult.hydratedComponents,
scripts: transformResult.scripts,
};
return {
code: escapeViteEnvReferences(code),
map: null,
meta: {
astro: astroMetadata,
vite: {
lang: 'ts',
},
},
};
}
return null;
},
};
}
// Converts the first dot in `import.meta.env` to its Unicode escape sequence,
// which prevents Vite from replacing strings like `import.meta.env.SITE`
// in our JS representation of loaded Markdown files
function escapeViteEnvReferences(code: string) {
return code.replace(/import\.meta\.env/g, 'import\\u002Emeta.env');
}