forked from parcel-bundler/parcel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAsset.js
268 lines (225 loc) · 6.62 KB
/
Asset.js
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
const URL = require('url');
const path = require('path');
const clone = require('clone');
const fs = require('./utils/fs');
const md5 = require('./utils/md5');
const isURL = require('./utils/is-url');
const config = require('./utils/config');
const syncPromise = require('./utils/syncPromise');
const logger = require('./Logger');
const Resolver = require('./Resolver');
const objectHash = require('./utils/objectHash');
/**
* An Asset represents a file in the dependency tree. Assets can have multiple
* parents that depend on it, and can be added to multiple output bundles.
* The base Asset class doesn't do much by itself, but sets up an interface
* for subclasses to implement.
*/
class Asset {
constructor(name, options) {
this.id = null;
this.name = name;
this.basename = path.basename(this.name);
this.relativeName = path.relative(options.rootDir, this.name);
this.options = options;
this.encoding = 'utf8';
this.type = path.extname(this.name).slice(1);
this.processed = false;
this.contents = options.rendition ? options.rendition.value : null;
this.ast = null;
this.generated = null;
this.hash = null;
this.parentDeps = new Set();
this.dependencies = new Map();
this.depAssets = new Map();
this.parentBundle = null;
this.bundles = new Set();
this.cacheData = {};
this.startTime = 0;
this.endTime = 0;
this.buildTime = 0;
this.bundledSize = 0;
this.resolver = new Resolver(options);
}
shouldInvalidate() {
return false;
}
async loadIfNeeded() {
if (this.contents == null) {
this.contents = await this.load();
}
}
async parseIfNeeded() {
await this.loadIfNeeded();
if (!this.ast) {
this.ast = await this.parse(this.contents);
}
}
async getDependencies() {
if (
this.options.rendition &&
this.options.rendition.hasDependencies === false
) {
return;
}
await this.loadIfNeeded();
if (this.contents && this.mightHaveDependencies()) {
await this.parseIfNeeded();
await this.collectDependencies();
}
}
addDependency(name, opts) {
this.dependencies.set(name, Object.assign({name}, opts));
}
addURLDependency(url, from = this.name, opts) {
if (!url || isURL(url)) {
return url;
}
if (typeof from === 'object') {
opts = from;
from = this.name;
}
const parsed = URL.parse(url);
let depName;
let resolved;
let dir = path.dirname(from);
const filename = decodeURIComponent(parsed.pathname);
if (filename[0] === '~' || filename[0] === '/') {
if (dir === '.') {
dir = this.options.rootDir;
}
depName = resolved = this.resolver.resolveFilename(filename, dir);
} else {
resolved = path.resolve(dir, filename);
depName = './' + path.relative(path.dirname(this.name), resolved);
}
this.addDependency(depName, Object.assign({dynamic: true}, opts));
parsed.pathname = this.options.parser
.getAsset(resolved, this.options)
.generateBundleName();
return URL.format(parsed);
}
get package() {
logger.warn(
'`asset.package` is deprecated. Please use `await asset.getPackage()` instead.'
);
return syncPromise(this.getPackage());
}
async getPackage() {
if (!this._package) {
this._package = await this.resolver.findPackage(path.dirname(this.name));
}
return this._package;
}
async getConfig(filenames, opts = {}) {
if (opts.packageKey) {
let pkg = await this.getPackage();
if (pkg && pkg[opts.packageKey]) {
return clone(pkg[opts.packageKey]);
}
}
// Resolve the config file
let conf = await config.resolve(opts.path || this.name, filenames);
if (conf) {
// Add as a dependency so it is added to the watcher and invalidates
// this asset when the config changes.
this.addDependency(conf, {includedInParent: true});
if (opts.load === false) {
return conf;
}
return await config.load(opts.path || this.name, filenames);
}
return null;
}
mightHaveDependencies() {
return true;
}
async load() {
return await fs.readFile(this.name, this.encoding);
}
parse() {
// do nothing by default
}
collectDependencies() {
// do nothing by default
}
async pretransform() {
// do nothing by default
}
async transform() {
// do nothing by default
}
async generate() {
return {
[this.type]: this.contents
};
}
async process() {
// Generate the id for this asset, unless it has already been set.
// We do this here rather than in the constructor to avoid unnecessary work in the main process.
// In development, the id is just the relative path to the file, for easy debugging and performance.
// In production, we use a short hash of the relative path.
if (!this.id) {
this.id =
this.options.production || this.options.scopeHoist
? md5(this.relativeName, 'base64').slice(0, 4)
: this.relativeName;
}
if (!this.generated) {
await this.loadIfNeeded();
await this.pretransform();
await this.getDependencies();
await this.transform();
this.generated = await this.generate();
}
return this.generated;
}
async postProcess(generated) {
return generated;
}
generateHash() {
return objectHash(this.generated);
}
invalidate() {
this.processed = false;
this.contents = null;
this.ast = null;
this.generated = null;
this.hash = null;
this.dependencies.clear();
this.depAssets.clear();
}
invalidateBundle() {
this.parentBundle = null;
this.bundles.clear();
this.parentDeps.clear();
}
generateBundleName() {
// Generate a unique name. This will be replaced with a nicer
// name later as part of content hashing.
return md5(this.name) + '.' + this.type;
}
replaceBundleNames(bundleNameMap) {
let copied = false;
for (let key in this.generated) {
let value = this.generated[key];
if (typeof value === 'string') {
// Replace temporary bundle names in the output with the final content-hashed names.
let newValue = value;
for (let [name, map] of bundleNameMap) {
newValue = newValue.split(name).join(map);
}
// Copy `this.generated` on write so we don't end up writing the final names to the cache.
if (newValue !== value && !copied) {
this.generated = Object.assign({}, this.generated);
copied = true;
}
this.generated[key] = newValue;
}
}
}
generateErrorMessage(err) {
return err;
}
}
module.exports = Asset;