forked from meteor/meteor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bundler.js
2961 lines (2567 loc) · 99.1 KB
/
bundler.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
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// == Site Archive (*.star) file layout (subject to rapid change) ==
//
// /star.json
//
// - format: "site-archive-pre1" for this version
//
// - builtBy: human readable banner (eg, "Meteor 0.6.0")
//
// - programs: array of programs in the star, each an object:
// - name: short, unique name for program, for referring to it
// programmatically
// - arch: architecture that this program targets. Something like
// "os", "os.linux.x86_64", or "browser.w3c".
// - path: directory (relative to star.json) containing this program
//
// XXX in the future this will also contain instructions for
// mounting packages into the namespace of each program, and
// possibly for mounting programs on top of each other (this would
// be the principled mechanism by which a server program could read
// a client program so it can server it)
//
// - plugins: array of plugins in the star, each an object:
// - name: short, unique name for plugin, for referring to it
// programmatically
// - arch: typically 'os' (for a portable plugin) or eg
// 'os.linux.x86_64' for one that include native node_modules
// - path: path (relative to star.json) to the control file (eg,
// program.json) for this plugin
//
// - meteorRelease: the value used in Meteor.release for programs inside the
// star, or "none"
//
// /README: human readable instructions
//
// /main.js: script that can be run in node.js to start the site
// running in standalone mode (after setting appropriate environment
// variables as documented in README)
//
// /server/.bundle_version.txt: contains the dev_bundle version that the meteor
// deploy server reads in order to set NODE_PATH to point to arch-specific
// builds of binary node modules
//
// XXX in the future one program (which must be a server-type
// architecture) will be designated as the 'init' program. The
// container will call it with arguments to signal app lifecycle
// events like 'start' and 'stop'.
//
//
// Conventionally programs will be located at /programs/<name>, but
// really the build tool can lay out the star however it wants.
//
//
// == Format of a program when arch is "web.*" ==
//
// Standard:
//
// /program.json
//
// - format: "web-program-pre1" for this version
//
// - manifest: array of resources to serve with HTTP, each an object:
// - path: path of file relative to program.json
// - where: "client"
// - type: "js", "css", or "asset"
// - cacheable: is it safe to ask the client to cache this file (boolean)
// - url: relative url to download the resource, includes cache busting
// parameter when used
// - size: size of file in bytes
// - hash: sha1 hash of the file contents
// - sourceMap: optional path to source map file (relative to program.json)
//
// Additionally there may be a manifest entry with where equal to
// "internal", type "head" or "body", and a path and hash. These contain
// chunks of HTML which should be inserted in the boilerplate HTML page's
// <head> or <body> respectively.
//
//
// == Format of a program when arch is "os.*" ==
//
// Standard:
//
// /server.js: script to run inside node.js to start the program
//
// XXX Subject to change! This will likely change to a shell script
// (allowing us to represent types of programs that don't use or
// depend on node) -- or in fact, rather than have anything fixed here
// at all, star.json just contains a path to a program to run, which
// can be anything than can be exec()'d.
//
// Convention:
//
// /program.json:
//
// - load: array with each item describing a JS file to load at startup:
// - path: path of file, relative to program.json
// - node_modules: if Npm.require is called from this file, this is
// the path (relative to program.json) of the directory that should
// be search for npm modules
// - assets: map from path (the argument to Assets.getText and
// Assets.getBinary) to path on disk (relative to program.json)
// of the asset
// - sourceMap: if present, path of a file that contains a source
// map for this file, relative to program.json
//
// /config.json:
//
// - client: the client program that should be served up by HTTP,
// expressed as a path (relative to program.json) to the *client's*
// program.json.
//
// - meteorRelease: the value to use for Meteor.release, if any
//
//
// /app/*: source code of the (server part of the) app
// /packages/foo.js: the (linked) source code for package foo
// /package-tests/foo.js: the (linked) source code for foo's tests
// /npm/foo/node_modules: node_modules for package foo. may be symlinked
// if developing locally.
//
// /node_modules: node_modules needed for server.js. omitted if
// deploying (see .bundle_version.txt above), copied if bundling,
// symlinked if developing locally.
//
//
// == Format of a program that is to be used as a plugin ==
//
// /program.json:
// - format: "javascript-image-pre1" for this version
// - arch: the architecture that this build requires
// - load: array with each item describing a JS file to load, in load order:
// - path: path of file, relative to program.json
// - node_modules: if Npm.require is called from this file, this is
// the path (relative to program.json) of the directory that should
// be search for npm modules
//
// It's a little odd that architecture is stored twice (in both the
// top-level star control file and in the plugin control file) but
// it's fine and it's probably actually cleaner, because it means that
// the plugin can be treated as a self-contained unit.
//
// Note that while the spec for "os.*" is going to change to
// represent an arbitrary POSIX (or Windows) process rather than
// assuming a nodejs host, these plugins will always refer to
// JavaScript code (that potentially might be a plugin to be loaded
// into an existing JS VM). But this seems to be a concern that is
// somewhat orthogonal to arch (these plugins can still use packages
// of arch "os.*"). There is probably a missing abstraction here
// somewhere (decoupling target type from architecture) but it can
// wait until later.
var assert = require('assert');
var util = require('util');
var Fiber = require('fibers');
var _ = require('underscore');
var compiler = require('./compiler.js');
var PackageSource = require('./package-source.js');
import Builder from './builder.js';
var compilerPluginModule = require('./compiler-plugin.js');
import { JsFile, CssFile } from './minifier-plugin.js';
var meteorNpm = require('./meteor-npm.js');
var files = require('../fs/files.js');
var archinfo = require('../utils/archinfo.js');
var buildmessage = require('../utils/buildmessage.js');
var watch = require('../fs/watch.js');
var colonConverter = require('../utils/colon-converter.js');
var Profile = require('../tool-env/profile.js').Profile;
var packageVersionParser = require('../packaging/package-version-parser.js');
var release = require('../packaging/release.js');
import { load as loadIsopacket } from '../tool-env/isopackets.js';
import { CORDOVA_PLATFORM_VERSIONS } from '../cordova';
// files to ignore when bundling. node has no globs, so use regexps
exports.ignoreFiles = [
/~$/, /^\.#/,
/^(\.meteor\/|\.git\/|Thumbs\.db|\.DS_Store\/?|Icon\r|ehthumbs\.db|\..*\.sw.|#.*#)$/,
/* .meteor => avoids scanning N^2 files when bundling all packages
.git => often has too many files to watch
....sw(.) => vim swap files
#.*# => emacs swap files
*/
];
function rejectBadPath(p) {
if (p.startsWith("..")) {
throw new Error("bad path: " + p);
}
}
var stripLeadingSlash = function (p) {
if (p.charAt(0) === '/') {
return p.slice(1);
}
return p;
};
// Contents of main.js in bundles. Exported for use by the bundler
// tests.
exports._mainJsContents = [
"",
"// The debugger pauses here when you run `meteor debug`, because this is ",
"// the very first code to be executed by the server process. If you have ",
"// not already added any `debugger` statements to your code, feel free to ",
"// do so now, wait for the server to restart, then reload this page and ",
"// click the |\u25b6 button to continue.",
"process.argv.splice(2, 0, 'program.json');",
"process.chdir(require('path').join(__dirname, 'programs', 'server'));",
"require('./programs/server/boot.js');",
].join("\n");
///////////////////////////////////////////////////////////////////////////////
// NodeModulesDirectory
///////////////////////////////////////////////////////////////////////////////
// Represents a node_modules directory that we need to copy into the
// bundle or otherwise make available at runtime.
export class NodeModulesDirectory {
constructor({
packageName,
sourceRoot,
sourcePath,
preferredBundlePath,
local = false,
npmDiscards = null,
}) {
// Name of the package this node_modules directory belongs to, or null
// if it belongs to an application.
assert.ok(typeof packageName === "string" || packageName === null);
this.packageName = packageName;
// The absolute path of the root directory of the app or package that
// contains this node_modules directory.
assert.strictEqual(typeof sourceRoot, "string");
this.sourceRoot = sourceRoot;
// The absolute path (on local disk) to a directory that contains
// the built node_modules to use.
assert.strictEqual(typeof sourcePath, "string");
this.sourcePath = sourcePath;
// The path (relative to the bundle root) where we would preferably
// like the node_modules to be output.
this.preferredBundlePath = preferredBundlePath;
// Boolean indicating whether the node_modules directory is locally
// accessible from other modules in the app or package.
this.local = !! local;
// A test package often shares its .sourcePath with the non-test
// package, so it's important to be able to tell them apart,
// especially when we'd like to treat .sourcePath as a unique key.
this.isTestPackage =
typeof packageName === "string" &&
/^local-test[:_]/.test(packageName);
// Optionally, files to discard.
this.npmDiscards = npmDiscards;
}
copy() {
return new this.constructor(this);
}
isPortable() {
return meteorNpm.dependenciesArePortable(this.sourcePath);
}
rebuildIfNonPortable() {
return meteorNpm.rebuildIfNonPortable(this.sourcePath);
}
getPreferredBundlePath(kind) {
assert.ok(kind === "bundle" ||
kind === "isopack",
kind);
let relPath = files.pathRelative(this.sourceRoot, this.sourcePath);
rejectBadPath(relPath);
const isApp = ! this.packageName;
if (! isApp) {
const relParts = relPath.split(files.pathSep);
const name = colonConverter.convert(
this.packageName.replace(/^local-test[:_]/, ""));
if (relParts[0] === ".npm") {
// Normalize .npm/package/node_modules/... paths so that they get
// copied into the bundle as if they were in the top-level local
// node_modules directory of the package.
if (relParts[1] === "package") {
relParts.splice(0, 2);
} else if (relParts[1] === "plugin") {
relParts.splice(0, 3);
}
} else if (relParts[0] === "npm") {
// The npm/ at the beginning of the relPath was probably added by
// a previous call to getPreferredBundlePath, so we remove it here
// to avoid duplication.
let spliceCount = 1;
if (relParts[1] === "node_modules" &&
relParts[2] === "meteor" &&
relParts[3] === name) {
// Same with node_modules/meteor/<package name>/, which was
// almost certainly added by the code immediately below.
spliceCount += 3;
}
relParts.splice(0, spliceCount);
}
if (kind === "bundle") {
relParts.unshift("node_modules", "meteor", name);
}
let lastPart = relParts.pop();
if (lastPart !== "node_modules") {
// Sometimes when building an app bundle for a different
// architecture, the isopacket source directory ends up with
// different npm/node_modules directories for each architecture,
// distinguished by numerical suffixes (e.g. npm/node_modules1).
// While this is important to keep the built binary files
// distinct, we definitely don't want node_modules1 to show up in
// the final build.
assert.ok(lastPart.startsWith("node_modules"), lastPart);
lastPart = "node_modules";
}
relParts.push(lastPart);
relPath = files.pathJoin(...relParts);
}
// It's important not to put node_modules at the top level, so that it
// will not be visible from within plugins.
return files.pathJoin("npm", relPath);
}
toJSON() {
return {
packageName: this.packageName,
local: this.local,
};
}
// Returns an object mapping from relative bundle paths to the kind of
// objects returned by the toJSON method above. Note that this works
// even if the node_modules parameter is a string, though that will only
// be the case for bundles built before Meteor 1.3.
static readDirsFromJSON(node_modules, {
rebuildBinaries = false,
// Options consumed by readDirsFromJSON are listed above. Any other
// options will be passed on to NodeModulesDirectory constructor via
// this callerInfo object:
...callerInfo,
}) {
assert.strictEqual(typeof callerInfo.sourceRoot, "string");
const nodeModulesDirectories = Object.create(null);
function add(moreInfo, path) {
const info = {
...callerInfo,
...moreInfo,
};
if (! info.packageName) {
const parts = path.split("/");
if (parts[0] === "npm" &&
parts[1] === "node_modules" &&
parts[2] === "meteor") {
info.packageName = parts[3];
} else if (parts.length === 3 &&
parts[0] === "npm" &&
parts[2] === "node_modules") {
info.packageName = parts[1];
} else {
parts.some(function (part, i) {
if (i > 0 && part === ".npm") {
if (parts[i + 1] === "package") {
info.packageName = parts[i - 1];
return true;
}
if (parts[i + 1] === "plugin") {
info.packageName = parts[i + 2];
return true;
}
}
});
}
if (! info.packageName) {
throw new Error("No package name inferred from " + path);
}
}
if (files.pathIsAbsolute(path)) {
info.sourcePath = path;
} else {
rejectBadPath(path);
info.sourcePath = files.pathJoin(callerInfo.sourceRoot, path);
}
nodeModulesDirectories[info.sourcePath] =
new NodeModulesDirectory(info);
}
if (typeof node_modules === "string") {
// Old-style node_modules strings were only ever for
// .npm/package/node_modules directories, which are non-local.
add({ local: false }, node_modules);
} else if (node_modules) {
_.each(node_modules, add);
}
if (rebuildBinaries) {
_.each(nodeModulesDirectories, (info, path) => {
meteorNpm.rebuildIfNonPortable(path);
});
}
return nodeModulesDirectories;
}
// Returns a predicate function that determines if a given directory is
// contained by a production package directory in this.sourcePath.
getProdPackagePredicate() {
if (this._prodPackagePredicate) {
return this._prodPackagePredicate;
}
const sourcePath = this.sourcePath;
const prodPackageNames = meteorNpm.getProdPackageNames(sourcePath);
if (! prodPackageNames) {
// Indicates that no directories should be excluded from the set of
// production packages. Equivalent to returning dir => true.
return null;
}
const prodPackageTree = Object.create(null);
const complete = Symbol();
let maxPartCount = 0;
Object.keys(prodPackageNames).forEach(name => {
const parts = name.split("/");
let tree = prodPackageTree;
parts.forEach(part => {
tree = tree[part] || (tree[part] = Object.create(null));
});
tree[complete] = true;
maxPartCount = Math.max(parts.length, maxPartCount);
});
return this._prodPackagePredicate = function isWithinProdPackage(dir) {
const parts = files.pathRelative(sourcePath, dir)
.split(files.pathSep);
let start = parts.lastIndexOf("node_modules") + 1;
if (parts.length - start > maxPartCount) {
// We're deep enough inside node_modules that it's safe to
// say we should have returned false earlier.
return true;
}
let tree = prodPackageTree;
for (let pos = start; pos < parts.length; ++pos) {
const part = parts[pos];
const branch = tree[part];
if (! branch) {
// This dir is not prefixed by a production package name.
return false;
}
if (branch[complete]) {
// This dir is prefixed by a complete production package name.
break;
}
tree = branch;
}
return true;
};
}
}
///////////////////////////////////////////////////////////////////////////////
// File
///////////////////////////////////////////////////////////////////////////////
// Allowed options:
// - sourcePath: path to file on disk that will provide our contents
// - data: contents of the file as a Buffer
// - hash: optional, sha1 hash of the file contents, if known
// - sourceMap: if 'data' is given, can be given instead of
// sourcePath. a string or a JS Object. Will be stored as Object.
// - cacheable
class File {
constructor (options) {
if (options.data && ! (options.data instanceof Buffer)) {
throw new Error('File contents must be provided as a Buffer');
}
if (! options.sourcePath && ! options.data) {
throw new Error("Must provide either sourcePath or data");
}
// The absolute path in the filesystem from which we loaded (or will
// load) this file (null if the file does not correspond to one on
// disk).
this.sourcePath = options.sourcePath;
// info is just for help with debugging the tool; it isn't written to disk or
// anything.
this.info = options.info || '?';
// If this file was generated, a sourceMap (as a string) with debugging
// information, as well as the "root" that paths in it should be resolved
// against. Set with setSourceMap.
this.sourceMap = null;
this.sourceMapRoot = null;
// Where this file is intended to reside within the target's
// filesystem.
this.targetPath = null;
// The URL at which this file is intended to be served, relative to
// the base URL at which the target is being served (ignored if this
// file is not intended to be served over HTTP).
this.url = null;
// Is this file guaranteed to never change, so that we can let it be
// cached forever? Only makes sense of self.url is set.
this.cacheable = options.cacheable || false;
// The node_modules directories that Npm.require() should search when
// called from inside this file. Only includes non-local node_modules
// directories (e.g. .npm/package/node_modules), and only works on the
// server architecture.
this.nodeModulesDirectories = Object.create(null);
// For server JS only. Assets associated with this slice; map from the path
// that is the argument to Assets.getBinary, to a Buffer that is its contents.
this.assets = null;
this._contents = options.data || null; // contents, if known, as a Buffer
this._hashOfContents = options.hash || null;
this._hash = null;
}
toString() {
return `File: [info=${this.info}]`;
}
static _salt() {
// Increment this number to force rehashing.
return 1;
}
hash() {
if (! this._hash) {
if (! this._hashOfContents) {
this._hashOfContents = watch.sha1(this.contents());
}
this._hash = watch.sha1(
String(File._salt()),
this._hashOfContents,
);
}
return this._hash;
}
// Omit encoding to get a buffer, or provide something like 'utf8'
// to get a string
contents(encoding) {
if (! this._contents) {
if (! this.sourcePath) {
throw new Error("Have neither contents nor sourcePath for file");
} else {
this._contents = files.readFile(this.sourcePath);
}
}
return encoding ? this._contents.toString(encoding) : this._contents;
}
setContents(b) {
if (!(b instanceof Buffer)) {
throw new Error("Must set contents to a Buffer");
}
this._contents = b;
// Un-cache hash.
this._hashOfContents = this._hash = null;
}
size() {
return this.contents().length;
}
// Set the URL (and target path) of this file to "/<hash><suffix>". suffix
// will typically be used to pick a reasonable extension. Also set cacheable
// to true, since the file's name is now derived from its contents.
// Also allow a special second suffix that will *only* be postpended to the
// url, useful for query parameters.
setUrlToHash(fileAndUrlSuffix, urlSuffix) {
urlSuffix = urlSuffix || "";
this.url = "/" + this.hash() + fileAndUrlSuffix + urlSuffix;
this.cacheable = true;
this.targetPath = this.hash() + fileAndUrlSuffix;
}
// Append "?<hash>" to the URL and mark the file as cacheable.
addCacheBuster() {
if (! this.url) {
throw new Error("File must have a URL");
}
if (this.cacheable) {
// eg, already got setUrlToHash
return;
}
if (/\?/.test(this.url)) {
throw new Error("URL already has a query string");
}
this.url += "?hash=" + this.hash();
this.cacheable = true;
}
// Given a relative path like 'a/b/c' (where '/' is this system's
// path component separator), produce a URL that always starts with
// a forward slash and that uses a literal forward slash as the
// component separator.
setUrlFromRelPath(relPath) {
var url = relPath;
if (url.charAt(0) !== '/') {
url = '/' + url;
}
// XXX replacing colons with underscores as colon is hard to escape later
// on different targets and generally is not a good separator for web.
url = url.replace(/:/g, '_');
this.url = url;
}
setTargetPathFromRelPath(relPath) {
// XXX hack
if (relPath.match(/^packages\//) || relPath.match(/^assets\//)) {
this.targetPath = relPath;
} else {
this.targetPath = files.pathJoin('app', relPath);
}
// XXX same as in setUrlFromRelPath, we replace colons with a different
// separator to avoid difficulties further. E.g.: on Windows it is not a
// valid char in filename, Cordova also rejects it, etc.
this.targetPath = this.targetPath.replace(/:/g, '_');
}
// Set a source map for this File. sourceMap is given as a string.
setSourceMap(sourceMap, root) {
if (sourceMap === null || ['object', 'string'].indexOf(typeof sourceMap) === -1) {
throw new Error("sourceMap must be given as a string or an object");
}
if (typeof sourceMap === 'string') {
sourceMap = JSON.parse(sourceMap);
}
this.sourceMap = sourceMap;
this.sourceMapRoot = root;
}
// note: this assets object may be shared among multiple files!
setAssets(assets) {
if (!_.isEmpty(assets)) {
this.assets = assets;
}
}
}
///////////////////////////////////////////////////////////////////////////////
// Target
///////////////////////////////////////////////////////////////////////////////
class Target {
constructor({
// for resolving package dependencies
packageMap,
isopackCache,
// Path to the root source directory for this Target.
sourceRoot,
// the architecture to build
arch,
// projectContextModule.CordovaPluginsFile object
cordovaPluginsFile,
// 'development', 'production' or 'test'; determines whether
// debugOnly, prodOnly and testOnly packages are included;
// defaults to 'production'
buildMode,
// directory on disk where to store the cache for things like linker
bundlerCacheDir,
// ... see subclasses for additional options
}) {
this.packageMap = packageMap;
this.isopackCache = isopackCache;
this.sourceRoot = sourceRoot;
// Something like "web.browser" or "os" or "os.osx.x86_64"
this.arch = arch;
// All of the Unibuilds that are to go into this target, in the order
// that they are to be loaded.
this.unibuilds = [];
// JavaScript files. List of File. They will be loaded at startup in
// the order given.
this.js = [];
// On-disk dependencies of this target.
this.watchSet = new watch.WatchSet();
// List of all package names used in this target.
this.usedPackages = {};
// node_modules directories that we need to copy into the target (or
// otherwise make available at runtime). A map from an absolute path
// on disk (NodeModulesDirectory.sourcePath) to a
// NodeModulesDirectory object that we have created to represent it.
//
// The NodeModulesDirectory objects in this map are de-duplicated
// aliases to the objects in the nodeModulesDirectory fields of
// the File objects in this.js.
this.nodeModulesDirectories = Object.create(null);
// Static assets to include in the bundle. List of File.
// For client targets, these are served over HTTP.
this.asset = [];
// The project's cordova plugins file (which lists plugins used directly by
// the project).
this.cordovaPluginsFile = cordovaPluginsFile;
// A mapping from Cordova plugin name to Cordova plugin version number.
this.cordovaDependencies = this.cordovaPluginsFile ? {} : null;
this.buildMode = buildMode || 'production';
this.bundlerCacheDir = bundlerCacheDir;
}
// Top-level entry point for building a target. Generally to build a
// target, you create with 'new', call make() to specify its sources
// and build options and actually do the work of buliding the
// target, and finally you retrieve the build product with a
// target-type-dependent function such as write() or toJsImage().
//
// options
// - packages: packages to include (Isopack or 'foo'), per
// _determineLoadOrder
// - minifyMode: 'development'/'production'
// - addCacheBusters: if true, make all files cacheable by adding
// unique query strings to their URLs. unlikely to be of much use
// on server targets.
make({packages, minifyMode, addCacheBusters, minifiers}) {
buildmessage.assertInCapture();
buildmessage.enterJob("building for " + this.arch, () => {
// Populate the list of unibuilds to load
this._determineLoadOrder({
packages: packages || []
});
const sourceBatches = this._runCompilerPlugins();
// Link JavaScript and set up this.js, etc.
this._emitResources(sourceBatches);
// Add top-level Cordova dependencies, which override Cordova
// dependencies from packages.
this._addDirectCordovaDependencies();
// Minify, with mode requested.
// Why do we only minify in client targets?
// (a) CSS only exists in client targets, so we definitely shouldn't
// minify CSS in server targets.
// (b) We don't know of a use case for standard minification on server
// targets (though we could imagine wanting to do other
// post-processing using this API).
// (c) On the server, JS files have extra metadata associated like
// static assets and npm modules. We'd have to support merging
// the npm modules from multiple js resources (generally 1 per
// package) together. This isn't impossible, but not worth
// the implementation complexity without a use case.
// We can always extend registerMinifier to allow server targets
// later!
if (this instanceof ClientTarget) {
var minifiersByExt = {};
['js', 'css'].forEach(function (ext) {
minifiersByExt[ext] = _.find(minifiers, function (minifier) {
return minifier && _.contains(minifier.extensions, ext);
});
});
if (minifiersByExt.js) {
this.minifyJs(minifiersByExt.js, minifyMode);
}
if (minifiersByExt.css) {
this.minifyCss(minifiersByExt.css, minifyMode);
}
}
this.rewriteSourceMaps();
if (addCacheBusters) {
// Make client-side CSS and JS assets cacheable forever, by
// adding a query string with a cache-busting hash.
this._addCacheBusters("js");
this._addCacheBusters("css");
}
});
}
// Determine the packages to load, create Unibuilds for
// them, put them in load order, save in unibuilds.
//
// options include:
// - packages: an array of packages (or, properly speaking, unibuilds)
// to include. Each element should either be a Isopack object or a
// package name as a string
_determineLoadOrder({packages}) {
buildmessage.assertInCapture();
const isopackCache = this.isopackCache;
buildmessage.enterJob('linking the program', () => {
// Find the roots
const rootUnibuilds = [];
packages.forEach((p) => {
if (typeof p === 'string') {
p = isopackCache.getIsopack(p);
}
// `debugOnly` packages work with "debug" and "test" build
// modes.
if (p.debugOnly && this.buildMode === 'production') {
return;
}
if (p.prodOnly && this.buildMode !== 'production') {
return;
}
if (p.testOnly && this.buildMode !== 'test') {
return;
}
const unibuild = p.getUnibuildAtArch(this.arch);
unibuild && rootUnibuilds.push(unibuild);
});
if (buildmessage.jobHasMessages()) {
return;
}
// PHASE 1: Which unibuilds will be used?
//
// Figure out which unibuilds are going to be used in the target,
// regardless of order. We ignore weak dependencies here, because they
// don't actually create a "must-use" constraint, just an ordering
// constraint.
// What unibuilds will be used in the target? Built in Phase 1, read in
// Phase 2.
const usedUnibuilds = {}; // Map from unibuild.id to Unibuild.
this.usedPackages = {}; // Map from package name to true;
const addToGetsUsed = function (unibuild) {
if (_.has(usedUnibuilds, unibuild.id)) {
return;
}
usedUnibuilds[unibuild.id] = unibuild;
if (unibuild.kind === 'main') {
// Only track real packages, not plugin pseudo-packages.
this.usedPackages[unibuild.pkg.name] = true;
}
compiler.eachUsedUnibuild({
dependencies: unibuild.uses,
arch: this.arch,
isopackCache: isopackCache,
// in both "development" and "test" build modes we should
// include `debugOnly` packages.
skipDebugOnly: this.buildMode === 'production',
skipProdOnly: this.buildMode !== 'production',
skipTestOnly: this.buildMode !== 'test',
}, addToGetsUsed);
}.bind(this);
rootUnibuilds.forEach(addToGetsUsed);
if (buildmessage.jobHasMessages()) {
return;
}
// PHASE 2: In what order should we load the unibuilds?
//
// Set this.unibuilds to be all of the roots, plus all of their non-weak
// dependencies, in the correct load order. "Load order" means that if X
// depends on (uses) Y, and that relationship is not marked as unordered,
// Y appears before X in the ordering. Raises an exception iff there is no
// such ordering (due to circular dependency).
//
// The topological sort code here is similar to code in isopack-cache.js,
// though they do serve slightly different purposes: that one determines
// build order dependencies and this one determines load order
// dependencies.
// What unibuilds have not yet been added to this.unibuilds?
const needed = _.clone(usedUnibuilds); // Map from unibuild.id to Unibuild.
// Unibuilds that we are in the process of adding; used to detect circular
// ordered dependencies.
const onStack = {}; // Map from unibuild.id to true.
// This helper recursively adds unibuild's ordered dependencies to
// this.unibuilds, then adds unibuild itself.
const add = function (unibuild) {
// If this has already been added, there's nothing to do.
if (!_.has(needed, unibuild.id)) {
return;
}
// Process each ordered dependency. (If we have an unordered dependency
// `u`, then there's no reason to add it *now*, and for all we know, `u`
// will depend on `unibuild` and need to be added after it. So we ignore
// those edge. Because we did follow those edges in Phase 1, any
// unordered unibuilds were at some point in `needed` and will not be
// left out).
//
// eachUsedUnibuild does follow weak edges (ie, they affect the
// ordering), but only if they point to a package in usedPackages (ie, a
// package that SOMETHING uses strongly).
var processUnibuild = function (usedUnibuild) {
if (onStack[usedUnibuild.id]) {
buildmessage.error(
"circular dependency between packages " +
unibuild.pkg.name + " and " + usedUnibuild.pkg.name);
// recover by not enforcing one of the depedencies
return;
}
onStack[usedUnibuild.id] = true;
add(usedUnibuild);
delete onStack[usedUnibuild.id];
};
compiler.eachUsedUnibuild({
dependencies: unibuild.uses,
arch: this.arch,
isopackCache: isopackCache,
skipUnordered: true,
acceptableWeakPackages: this.usedPackages,
// in both "development" and "test" build modes we should
// include `debugOnly` packages.
skipDebugOnly: this.buildMode === 'production',
skipProdOnly: this.buildMode !== 'production',
skipTestOnly: this.buildMode !== 'test',
}, processUnibuild);
this.unibuilds.push(unibuild);
delete needed[unibuild.id];
}.bind(this);
while (true) {
// Get an arbitrary unibuild from those that remain, or break if none
// remain.
let first = null;
for (first in needed) {
break;
}
if (! first) {
break;
}
// Now add it, after its ordered dependencies.
add(needed[first]);
}
});
}
// Run all the compiler plugins on all source files in the project. Returns an
// array of PackageSourceBatches which contain the results of this processing.
_runCompilerPlugins() {
buildmessage.assertInJob();
const processor = new compilerPluginModule.CompilerPluginProcessor({