-
Notifications
You must be signed in to change notification settings - Fork 921
/
file-builder.ts
336 lines (318 loc) · 11 KB
/
file-builder.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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
import {InstallTarget} from 'esinstall';
import {promises as fs} from 'fs';
import mkdirp from 'mkdirp';
import path from 'path';
import url from 'url';
import {EsmHmrEngine} from '../hmr-server-engine';
import {
scanCodeImportsExports,
transformEsmImports,
transformFileImports,
} from '../rewrite-imports';
import {matchDynamicImportValue, scanImportsFromFiles} from '../scan-imports';
import {getPackageSource} from '../sources/util';
import {
ImportMap,
SnowpackBuildMap,
SnowpackBuildResultFileManifest,
SnowpackBuiltFile,
SnowpackConfig,
} from '../types';
import {createInstallTarget, isRemoteUrl, relativeURL, replaceExtension} from '../util';
import {
getMetaUrlPath,
SRI_CLIENT_HMR_SNOWPACK,
SRI_ERROR_HMR_SNOWPACK,
wrapHtmlResponse,
wrapImportMeta,
wrapImportProxy,
} from './build-import-proxy';
import {buildFile} from './build-pipeline';
import {getUrlsForFile} from './file-urls';
import {createImportResolver} from './import-resolver';
/**
* FileBuilder - This class is responsible for building a file. It is broken into
* individual stages so that the entire application build process can be tackled
* in stages (build -> resolve -> get response).
*/
export class FileBuilder {
buildOutput: SnowpackBuildMap = {};
resolvedOutput: SnowpackBuildMap = {};
isDev: boolean;
isHMR: boolean;
isSSR: boolean;
buildPromise: Promise<SnowpackBuildMap> | undefined;
readonly loc: string;
readonly urls: string[];
readonly config: SnowpackConfig;
hmrEngine: EsmHmrEngine | null = null;
constructor({
loc,
isDev,
isHMR,
isSSR,
config,
hmrEngine,
}: {
loc: string;
isDev: boolean;
isHMR: boolean;
isSSR: boolean;
config: SnowpackConfig;
hmrEngine?: EsmHmrEngine | null;
}) {
this.loc = loc;
this.isDev = isDev;
this.isHMR = isHMR;
this.isSSR = isSSR;
this.config = config;
this.hmrEngine = hmrEngine || null;
this.urls = getUrlsForFile(loc, config);
}
private verifyRequestFromBuild(type: string): SnowpackBuiltFile {
// Verify that the requested file exists in the build output map.
if (!this.resolvedOutput[type] || !Object.keys(this.resolvedOutput)) {
throw new Error(
`${this.loc} - Requested content "${type}" but built ${Object.keys(this.resolvedOutput)}`,
);
}
return this.resolvedOutput[type];
}
/**
* Resolve Imports: Resolved imports are based on the state of the file
* system, so they can't be cached long-term with the build.
*/
async resolveImports(
isResolveBareImports: boolean,
hmrParam?: string | false,
importMap?: ImportMap,
): Promise<InstallTarget[]> {
const urlPathDirectory = path.posix.dirname(this.urls[0]!);
const pkgSource = getPackageSource(this.config.packageOptions.source);
const resolvedImports: InstallTarget[] = [];
for (const [type, outputResult] of Object.entries(this.buildOutput)) {
if (!(type === '.js' || type === '.html' || type === '.css')) {
continue;
}
let contents =
typeof outputResult.code === 'string'
? outputResult.code
: outputResult.code.toString('utf8');
// Handle attached CSS.
if (type === '.js' && this.buildOutput['.css']) {
const relativeCssImport = `./${replaceExtension(
path.posix.basename(this.urls[0]!),
'.js',
'.css',
)}`;
contents = `import '${relativeCssImport}';\n` + contents;
}
// Finalize the response
contents = this.finalizeResult(type, contents);
// resolve all imports
const resolveImportSpecifier = createImportResolver({
fileLoc: this.loc,
config: this.config,
});
const resolveImport = async (spec) => {
// Try to resolve the specifier to a known URL in the project
let resolvedImportUrl = resolveImportSpecifier(spec);
if (!isResolveBareImports) {
return resolvedImportUrl || spec;
}
// Handle a package import
if (!resolvedImportUrl && importMap) {
if (importMap.imports[spec]) {
const PACKAGE_PATH_PREFIX = path.posix.join(
this.config.buildOptions.metaUrlPath,
'pkg/',
);
return path.posix.join(PACKAGE_PATH_PREFIX, importMap.imports[spec]);
}
throw new Error(`Unexpected: spec ${spec} not included in import map.`);
}
// Ignore packages marked as external
if (this.config.packageOptions.external?.includes(spec)) {
return spec;
}
if (isRemoteUrl(spec)) {
return spec;
}
if (!resolvedImportUrl) {
resolvedImportUrl = await pkgSource.resolvePackageImport(this.loc, spec, this.config);
}
return resolvedImportUrl || spec;
};
const scannedImports = await scanImportsFromFiles(
[
{
baseExt: type,
root: this.config.root,
locOnDisk: this.loc,
contents,
},
],
this.config,
);
contents = await transformFileImports({type, contents}, async (spec) => {
let resolvedImportUrl = await resolveImport(spec);
// Handle normal "./" & "../" import specifiers
const importExtName = path.posix.extname(resolvedImportUrl);
const isProxyImport = importExtName && importExtName !== '.js' && importExtName !== '.mjs';
const isAbsoluteUrlPath = path.posix.isAbsolute(resolvedImportUrl);
if (isAbsoluteUrlPath) {
if (this.config.buildOptions.resolveProxyImports && isProxyImport) {
resolvedImportUrl = resolvedImportUrl + '.proxy.js';
}
resolvedImports.push(createInstallTarget(resolvedImportUrl));
} else {
resolvedImports.push(
...scannedImports
.filter(({specifier}) => specifier === spec)
.map((installTarget) => {
installTarget.specifier = resolvedImportUrl;
return installTarget;
}),
);
}
if (isAbsoluteUrlPath) {
// When dealing with an absolute import path, we need to honor the baseUrl
// proxy modules may attach code to the root HTML (like style) so don't resolve
resolvedImportUrl = relativeURL(urlPathDirectory, resolvedImportUrl);
}
return resolvedImportUrl;
});
// This is a hack since we can't currently scan "script" `src=` tags as imports.
// Either move these to inline JavaScript in the script body, or add support for
// `script.src=` and `link.href` scanning & resolving in transformFileImports().
if (type === '.html' && this.isHMR) {
if (contents.includes(SRI_CLIENT_HMR_SNOWPACK)) {
resolvedImports.push(createInstallTarget(getMetaUrlPath('hmr-client.js', this.config)));
}
if (contents.includes(SRI_ERROR_HMR_SNOWPACK)) {
resolvedImports.push(
createInstallTarget(getMetaUrlPath('hmr-error-overlay.js', this.config)),
);
}
}
if (type === '.js' && hmrParam) {
contents = await transformEsmImports(contents as string, (imp) => {
const importUrl = path.posix.resolve(urlPathDirectory, imp);
const node = this.hmrEngine?.getEntry(importUrl);
if (node && node.needsReplacement) {
this.hmrEngine?.markEntryForReplacement(node, false);
return `${imp}?${hmrParam}`;
}
return imp;
});
}
if (type === '.js') {
const isHmrEnabled = contents.includes('import.meta.hot');
const rawImports = await scanCodeImportsExports(contents);
const resolvedImports = rawImports.map((imp) => {
let spec = contents.substring(imp.s, imp.e);
if (imp.d > -1) {
spec = matchDynamicImportValue(spec) || '';
}
spec = spec.replace(/\?mtime=[0-9]+$/, '');
return path.posix.resolve(urlPathDirectory, spec);
});
this.hmrEngine?.setEntry(this.urls[0], resolvedImports, isHmrEnabled);
}
// Update the output with the new resolved imports
this.resolvedOutput[type].code = contents;
this.resolvedOutput[type].map = undefined;
}
return resolvedImports;
}
/**
* Given a file, build it. Building a file sends it through our internal
* file builder pipeline, and outputs a build map representing the final
* build. A Build Map is used because one source file can result in multiple
* built files (Example: .svelte -> .js & .css).
*/
async build(isStatic: boolean) {
if (this.buildPromise) {
return this.buildPromise;
}
const fileBuilderPromise = (async () => {
if (isStatic) {
return {
[path.extname(this.loc)]: {
code: await fs.readFile(this.loc),
map: undefined,
},
};
}
const builtFileOutput = await buildFile(url.pathToFileURL(this.loc), {
config: this.config,
isDev: this.isDev,
isSSR: this.isSSR,
isPackage: false,
isHmrEnabled: this.isHMR,
});
return builtFileOutput;
})();
this.buildPromise = fileBuilderPromise;
try {
this.resolvedOutput = {};
this.buildOutput = await fileBuilderPromise;
for (const [outputKey, {code, map}] of Object.entries(this.buildOutput)) {
this.resolvedOutput[outputKey] = {code, map};
}
} finally {
this.buildPromise = undefined;
}
}
private finalizeResult(type: string, content: string): string {
// Wrap the response.
switch (type) {
case '.html': {
content = wrapHtmlResponse({
code: content as string,
hmr: this.isHMR,
hmrPort: this.hmrEngine ? this.hmrEngine.port : undefined,
isDev: this.isDev,
config: this.config,
mode: this.isDev ? 'development' : 'production',
});
break;
}
case '.css': {
break;
}
case '.js':
{
content = wrapImportMeta({
code: content as string,
env: true,
hmr: this.isHMR,
config: this.config,
});
}
break;
}
// Return the finalized response.
return content;
}
getResult(type: string): string | Buffer {
const {code /*, map */} = this.verifyRequestFromBuild(type);
return code;
}
getSourceMap(type: string): string | undefined {
return this.resolvedOutput[type].map;
}
async getProxy(_url: string, type: string) {
const code = this.resolvedOutput[type].code;
const url = path.posix.join(this.config.buildOptions.baseUrl, _url);
return await wrapImportProxy({url, code, hmr: this.isHMR, config: this.config});
}
async writeToDisk(dir: string, results: SnowpackBuildResultFileManifest) {
await mkdirp(path.dirname(path.join(dir, this.urls[0])));
for (const outUrl of this.urls) {
const buildOutput = results[outUrl].contents;
const encoding = typeof buildOutput === 'string' ? 'utf8' : undefined;
await fs.writeFile(path.join(dir, outUrl), buildOutput, encoding);
}
}
}