-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
bundle.ts
250 lines (215 loc) · 6.68 KB
/
bundle.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
import type { AstroConfig, ValidExtensionPlugins } from '../@types/astro';
import type { ImportDeclaration } from '@babel/types';
import type { InputOptions, OutputOptions } from 'rollup';
import type { AstroRuntime } from '../runtime';
import esbuild from 'esbuild';
import { promises as fsPromises } from 'fs';
import { parse } from '../parser/index.js';
import { walk } from 'estree-walker';
import babelParser from '@babel/parser';
import path from 'path';
import { rollup } from 'rollup';
import { terser } from 'rollup-plugin-terser';
const { transformSync } = esbuild;
const { readFile } = fsPromises;
type DynamicImportMap = Map<'vue' | 'react' | 'react-dom' | 'preact', string>;
async function acquireDynamicComponentImports(plugins: Set<ValidExtensionPlugins>, resolve: (s: string) => Promise<string>): Promise<DynamicImportMap> {
const importMap: DynamicImportMap = new Map();
for (let plugin of plugins) {
switch (plugin) {
case 'vue': {
importMap.set('vue', await resolve('vue'));
break;
}
case 'react': {
importMap.set('react', await resolve('react'));
importMap.set('react-dom', await resolve('react-dom'));
break;
}
case 'preact': {
importMap.set('preact', await resolve('preact'));
break;
}
}
}
return importMap;
}
function compileExpressionSafe(raw: string): string {
let { code } = transformSync(raw, {
loader: 'tsx',
jsxFactory: 'h',
jsxFragment: 'Fragment',
charset: 'utf8',
});
return code;
}
const defaultExtensions: Readonly<Record<string, ValidExtensionPlugins>> = {
'.jsx': 'react',
'.svelte': 'svelte',
'.vue': 'vue',
};
export async function collectDynamicImports(filename: URL, astroConfig: AstroConfig, resolve: (s: string) => Promise<string>) {
const imports = new Set<string>();
// No markdown for now
if (filename.pathname.endsWith('md')) {
return imports;
}
const extensions = astroConfig.extensions || defaultExtensions;
const source = await readFile(filename, 'utf-8');
const ast = parse(source, {
filename,
});
if (!ast.module) {
return imports;
}
const componentImports: ImportDeclaration[] = [];
const components: Record<string, { plugin: ValidExtensionPlugins; type: string; specifier: string }> = {};
const plugins = new Set<ValidExtensionPlugins>();
const program = babelParser.parse(ast.module.content, {
sourceType: 'module',
plugins: ['jsx', 'typescript', 'topLevelAwait'],
}).program;
const { body } = program;
let i = body.length;
while (--i >= 0) {
const node = body[i];
if (node.type === 'ImportDeclaration') {
componentImports.push(node);
}
}
for (const componentImport of componentImports) {
const importUrl = componentImport.source.value;
const componentType = path.posix.extname(importUrl);
const componentName = path.posix.basename(importUrl, componentType);
const plugin = extensions[componentType] || defaultExtensions[componentType];
plugins.add(plugin);
components[componentName] = {
plugin,
type: componentType,
specifier: importUrl,
};
}
const dynamic = await acquireDynamicComponentImports(plugins, resolve);
function appendImports(rawName: string, filename: URL, astroConfig: AstroConfig) {
const [componentName, componentType] = rawName.split(':');
if (!componentType) {
return;
}
if (!components[componentName]) {
throw new Error(`Unknown Component: ${componentName}`);
}
const defn = components[componentName];
const fileUrl = new URL(defn.specifier, filename);
let rel = path.posix.relative(astroConfig.astroRoot.pathname, fileUrl.pathname);
switch (defn.plugin) {
case 'preact': {
imports.add(dynamic.get('preact')!);
rel = rel.replace(/\.[^.]+$/, '.js');
break;
}
case 'react': {
imports.add(dynamic.get('react')!);
imports.add(dynamic.get('react-dom')!);
rel = rel.replace(/\.[^.]+$/, '.js');
break;
}
case 'vue': {
imports.add(dynamic.get('vue')!);
rel = rel.replace(/\.[^.]+$/, '.vue.js');
break;
}
}
imports.add(`/_astro/${rel}`);
}
walk(ast.html, {
enter(node) {
switch (node.type) {
case 'MustacheTag': {
let code: string;
try {
code = compileExpressionSafe(node.content);
} catch {
return;
}
let matches: RegExpExecArray[] = [];
let match: RegExpExecArray | null | undefined;
const H_COMPONENT_SCANNER = /h\(['"]?([A-Z].*?)['"]?,/gs;
const regex = new RegExp(H_COMPONENT_SCANNER);
while ((match = regex.exec(code))) {
matches.push(match);
}
for (const match of matches.reverse()) {
const name = match[1];
appendImports(name, filename, astroConfig);
}
break;
}
case 'InlineComponent': {
if (/^[A-Z]/.test(node.name)) {
appendImports(node.name, filename, astroConfig);
return;
}
break;
}
}
},
});
return imports;
}
interface BundleOptions {
runtime: AstroRuntime;
dist: URL;
astroConfig: AstroConfig;
}
export async function bundle(imports: Set<string>, { runtime, dist }: BundleOptions) {
const ROOT = 'astro:root';
const root = `
${[...imports].map((url) => `import '${url}';`).join('\n')}
`;
const inputOptions: InputOptions = {
input: [...imports],
plugins: [
{
name: 'astro:build',
resolveId(source: string, imported?: string) {
if (source === ROOT) {
return source;
}
if (source.startsWith('/')) {
return source;
}
if (imported) {
const outUrl = new URL(source, 'http:https://example.com' + imported);
return outUrl.pathname;
}
return null;
},
async load(id: string) {
if (id === ROOT) {
return root;
}
const result = await runtime.load(id);
if (result.statusCode !== 200) {
return null;
}
return result.contents.toString('utf-8');
},
},
],
};
const build = await rollup(inputOptions);
const outputOptions: OutputOptions = {
dir: dist.pathname,
format: 'esm',
exports: 'named',
entryFileNames(chunk) {
return chunk.facadeModuleId!.substr(1);
},
plugins: [
// We are using terser for the demo, but might switch to something else long term
// Look into that rather than adding options here.
terser(),
],
};
await build.write(outputOptions);
}