forked from meteor/meteor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
compiler-plugin.js
1398 lines (1208 loc) · 44.8 KB
/
compiler-plugin.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
var archinfo = require('../utils/archinfo.js');
var buildmessage = require('../utils/buildmessage.js');
var buildPluginModule = require('./build-plugin.js');
var colonConverter = require('../utils/colon-converter.js');
var files = require('../fs/files.js');
var compiler = require('./compiler.js');
var linker = require('./linker.js');
var util = require('util');
var _ = require('underscore');
var Profile = require('../tool-env/profile.js').Profile;
import {sha1, readAndWatchFileWithHash} from '../fs/watch.js';
import LRU from 'lru-cache';
import Fiber from 'fibers';
import {sourceMapLength} from '../utils/utils.js';
import {Console} from '../console/console.js';
import ImportScanner from './import-scanner.js';
import {cssToCommonJS} from "./css-modules.js";
import Resolver from "./resolver.js";
import {
optimisticStatOrNull,
} from "../fs/optimistic.js";
import { isTestFilePath } from './test-files.js';
// This file implements the new compiler plugins added in Meteor 1.2, which are
// registered with the Plugin.registerCompiler API.
//
// Unlike legacy source handlers (Plugin.registerSourceHandler), compilers run
// in the context of an entire app. That is to say, they don't run when you run
// `meteor publish`; whenever they run, they have access to all the files of
// their type across all packages as well as the app. This allows them to
// implement cross-file and cross-package inclusion, or config files in the app
// that affect how packages are processed, among other possibilities.
//
// Compilers can specify which extensions or filenames they process. They only
// process files in packages (or the app) that directly use the plugin's package
// (or that use it indirectly via the "imply" directive); just because compiler
// plugins act on multiple packages at a time doesn't mean they automatically
// act on all packages in your app.
//
// The CompilerPluginProcessor is the main entry point to this file; it is used
// by the bundler to run all plugins on a target. It doesn't have much
// interesting state and perhaps could have just been a function.
//
// It receives an ordered list of unibuilds (essentially, packages) from the
// bundler. It turns them into an ordered list of PackageSourceBatch objects,
// each of which represents the source files in a single package. Each
// PackageSourceBatch consists of an ordered list of ResourceSlots representing
// the resources in that package. The idea here is that, because Meteor executes
// all JS files in the order produced by the bundler, we need to make sure to
// maintain the order of packages from the bundler and the order of source files
// within a package. Each ResourceSlot represents a resource (either a 'source'
// resource which will be processed by a compiler plugin, or something else like
// a static asset or some JavaScript produced by a legacy source handler), and
// when the compiler plugin calls something like `inputFile.addJavaScript` on a
// file, we replace that source file with the resource produced by the plugin.
//
// InputFile is a wrapper around ResourceSlot that is the object presented to
// the compiler in the plugin. It is part of the documented registerCompiler
// API.
// Cache the (slightly post-processed) results of linker.fullLink.
const CACHE_SIZE = process.env.METEOR_LINKER_CACHE_SIZE || 1024*1024*100;
const CACHE_DEBUG = !! process.env.METEOR_TEST_PRINT_LINKER_CACHE_DEBUG;
const LINKER_CACHE_SALT = 12; // Increment this number to force relinking.
const LINKER_CACHE = new LRU({
max: CACHE_SIZE,
// Cache is measured in bytes. We don't care about servePath.
// Key is JSONification of all options plus all hashes.
length: function (files) {
return files.reduce((soFar, current) => {
return soFar + current.data.length + sourceMapLength(current.sourceMap);
}, 0);
}
});
const serverLibPackages = {
// Make sure fibers is defined, if nothing else.
fibers: true
};
function populateServerLibPackages() {
const devBundlePath = files.getDevBundle();
const nodeModulesPath = files.pathJoin(
devBundlePath, "server-lib", "node_modules"
);
files.readdir(nodeModulesPath).forEach(packageName => {
const packagePath = files.pathJoin(nodeModulesPath, packageName);
const packageStat = files.statOrNull(packagePath);
if (packageStat && packageStat.isDirectory()) {
serverLibPackages[packageName] = true;
}
});
}
try {
populateServerLibPackages();
} catch (e) {
// At least we tried!
}
export class CompilerPluginProcessor {
constructor({
unibuilds,
arch,
sourceRoot,
isopackCache,
linkerCacheDir,
}) {
const self = this;
self.unibuilds = unibuilds;
self.arch = arch;
self.sourceRoot = sourceRoot;
self.isopackCache = isopackCache;
self.linkerCacheDir = linkerCacheDir;
if (self.linkerCacheDir) {
files.mkdir_p(self.linkerCacheDir);
}
}
runCompilerPlugins() {
const self = this;
buildmessage.assertInJob();
// plugin id -> {sourceProcessor, resourceSlots}
var sourceProcessorsWithSlots = {};
var sourceBatches = _.map(self.unibuilds, function (unibuild) {
const { pkg: { name }, arch } = unibuild;
const sourceRoot = name
&& self.isopackCache.getSourceRoot(name, arch)
|| self.sourceRoot;
return new PackageSourceBatch(unibuild, self, {
sourceRoot,
linkerCacheDir: self.linkerCacheDir
});
});
// If we failed to match sources with processors, we're done.
if (buildmessage.jobHasMessages()) {
return [];
}
// Find out which files go with which CompilerPlugins.
_.each(sourceBatches, function (sourceBatch) {
_.each(sourceBatch.resourceSlots, function (resourceSlot) {
var sourceProcessor = resourceSlot.sourceProcessor;
// Skip non-sources.
if (! sourceProcessor) {
return;
}
if (! _.has(sourceProcessorsWithSlots, sourceProcessor.id)) {
sourceProcessorsWithSlots[sourceProcessor.id] = {
sourceProcessor: sourceProcessor,
resourceSlots: []
};
}
sourceProcessorsWithSlots[sourceProcessor.id].resourceSlots.push(
resourceSlot);
});
});
// Now actually run the handlers.
_.each(sourceProcessorsWithSlots, function (data, id) {
var sourceProcessor = data.sourceProcessor;
var resourceSlots = data.resourceSlots;
var jobTitle = [
"processing files with ",
sourceProcessor.isopack.name,
" (for target ", self.arch, ")"
].join('');
Profile.time("plugin "+sourceProcessor.isopack.name, () => {
buildmessage.enterJob({
title: jobTitle
}, function () {
var inputFiles = _.map(resourceSlots, function (resourceSlot) {
return new InputFile(resourceSlot);
});
var markedMethod = buildmessage.markBoundary(
sourceProcessor.userPlugin.processFilesForTarget.bind(
sourceProcessor.userPlugin));
try {
markedMethod(inputFiles);
} catch (e) {
buildmessage.exception(e);
}
});
});
});
return sourceBatches;
}
}
class InputFile extends buildPluginModule.InputFile {
constructor(resourceSlot) {
super();
// We use underscored attributes here because this is user-visible
// code and we don't want users to be accessing anything that we don't
// document.
this._resourceSlot = resourceSlot;
// Map from absolute paths to stat objects (or null if the file does
// not exist).
this._statCache = Object.create(null);
// Map from control file names (e.g. package.json, .babelrc) to
// absolute paths, or null to indicate absence.
this._controlFileCache = Object.create(null);
// Map from imported module identifier strings (possibly relative) to
// fully require.resolve'd module identifiers.
this._resolveCache = Object.create(null);
}
getContentsAsBuffer() {
var self = this;
return self._resourceSlot.inputResource.data;
}
getPackageName() {
var self = this;
return self._resourceSlot.packageSourceBatch.unibuild.pkg.name;
}
isPackageFile() {
return !! this.getPackageName();
}
isApplicationFile() {
return ! this.getPackageName();
}
getSourceRoot() {
const sourceRoot = this._resourceSlot.packageSourceBatch.sourceRoot;
if (! _.isString(sourceRoot)) {
const name = this.getPackageName();
throw new Error(
"Unknown source root for " + (
name ? "package " + name : "app"));
}
return sourceRoot;
}
getPathInPackage() {
var self = this;
return self._resourceSlot.inputResource.path;
}
getFileOptions() {
var self = this;
// XXX fileOptions only exists on some resources (of type "source"). The JS
// resources might not have this property.
return self._resourceSlot.inputResource.fileOptions || {};
}
readAndWatchFileWithHash(path) {
const osPath = files.convertToOSPath(path);
const sourceRoot = this.getSourceRoot();
const relPath = files.pathRelative(sourceRoot, osPath);
if (relPath.startsWith("..")) {
throw new Error(
`Attempting to read file outside ${
this.getPackageName() || "the app"}: ${osPath}`
);
}
const sourceBatch = this._resourceSlot.packageSourceBatch;
return readAndWatchFileWithHash(
sourceBatch.unibuild.watchSet,
osPath
);
}
readAndWatchFile(path) {
return this.readAndWatchFileWithHash(path).contents;
}
_stat(absPath) {
return _.has(this._statCache, absPath)
? this._statCache[absPath]
: this._statCache[absPath] = optimisticStatOrNull(absPath);
}
// Search ancestor directories for control files (e.g. package.json,
// .babelrc), and return the absolute path of the first one found, or
// null if the search failed.
findControlFile(basename) {
let absPath = this._controlFileCache[basename];
if (typeof absPath === "string") {
return absPath;
}
const sourceRoot = this._resourceSlot.packageSourceBatch.sourceRoot;
if (! _.isString(sourceRoot)) {
return this._controlFileCache[basename] = null;
}
let dir = files.pathDirname(this.getPathInPackage());
while (true) {
absPath = files.pathJoin(sourceRoot, dir, basename);
const stat = this._stat(absPath);
if (stat && stat.isFile()) {
return this._controlFileCache[basename] = absPath;
}
if (files.pathBasename(dir) === "node_modules") {
// The search for control files should not escape node_modules.
return this._controlFileCache[basename] = null;
}
let parentDir = files.pathDirname(dir);
if (parentDir === dir) break;
dir = parentDir;
}
return this._controlFileCache[basename] = null;
}
_resolveCacheLookup(id, parentPath) {
const byId = this._resolveCache[id];
return byId && byId[parentPath];
}
_resolveCacheStore(id, parentPath, resolved) {
let byId = this._resolveCache[id];
if (! byId) {
byId = this._resolveCache[id] = Object.create(null);
}
return byId[parentPath] = resolved;
}
resolve(id, parentPath) {
const batch = this._resourceSlot.packageSourceBatch;
parentPath = parentPath || files.pathJoin(
batch.sourceRoot,
this.getPathInPackage()
);
const resId = this._resolveCacheLookup(id, parentPath);
if (resId) {
return resId;
}
const parentStat = files.statOrNull(parentPath);
if (! parentStat ||
! parentStat.isFile()) {
throw new Error("Not a file: " + parentPath);
}
const resolver = batch.getResolver();
const resolved = resolver.resolve(id, parentPath);
if (resolved === "missing") {
const error = new Error("Cannot find module '" + id + "'");
error.code = "MODULE_NOT_FOUND";
throw error;
}
return this._resolveCacheStore(id, parentPath, resolved.id);
}
require(id, parentPath) {
return require(this.resolve(id, parentPath));
}
getArch() {
return this._resourceSlot.packageSourceBatch.processor.arch;
}
getSourceHash() {
return this._resourceSlot.inputResource.hash;
}
/**
* @summary Returns the extension that matched the compiler plugin.
* The longest prefix is preferred.
* @returns {String}
*/
getExtension() {
return this._resourceSlot.inputResource.extension;
}
/**
* @summary Returns a list of symbols declared as exports in this target. The
* result of `api.export('symbol')` calls in target's control file such as
* package.js.
* @memberof InputFile
* @returns {String[]}
*/
getDeclaredExports() {
var self = this;
return self._resourceSlot.packageSourceBatch.unibuild.declaredExports;
}
/**
* @summary Returns a relative path that can be used to form error messages or
* other display properties. Can be used as an input to a source map.
* @memberof InputFile
* @returns {String}
*/
getDisplayPath() {
var self = this;
return self._resourceSlot.packageSourceBatch.unibuild.pkg._getServePath(self.getPathInPackage());
}
/**
* @summary Web targets only. Add a stylesheet to the document. Not available
* for linter build plugins.
* @param {Object} options
* @param {String} options.path The requested path for the added CSS, may not
* be satisfied if there are path conflicts.
* @param {String} options.data The content of the stylesheet that should be
* added.
* @param {String|Object} options.sourceMap A stringified JSON
* sourcemap, in case the stylesheet was generated from a different
* file.
* @memberOf InputFile
* @instance
*/
addStylesheet(options) {
var self = this;
if (options.sourceMap && typeof options.sourceMap === 'string') {
// XXX remove an anti-XSSI header? ")]}'\n"
options.sourceMap = JSON.parse(options.sourceMap);
}
self._resourceSlot.addStylesheet(options);
}
/**
* @summary Add JavaScript code. The code added will only see the
* namespaces imported by this package as runtime dependencies using
* ['api.use'](#PackageAPI-use). If the file being compiled was added
* with the bare flag, the resulting JavaScript won't be wrapped in a
* closure.
* @param {Object} options
* @param {String} options.path The path at which the JavaScript file
* should be inserted, may not be honored in case of path conflicts.
* @param {String} options.data The code to be added.
* @param {String|Object} options.sourceMap A stringified JSON
* sourcemap, in case the JavaScript file was generated from a
* different file.
* @memberOf InputFile
* @instance
*/
addJavaScript(options) {
var self = this;
if (options.sourceMap && typeof options.sourceMap === 'string') {
// XXX remove an anti-XSSI header? ")]}'\n"
options.sourceMap = JSON.parse(options.sourceMap);
}
self._resourceSlot.addJavaScript(options);
}
/**
* @summary Add a file to serve as-is to the browser or to include on
* the browser, depending on the target. On the web, it will be served
* at the exact path requested. For server targets, it can be retrieved
* using `Assets.getText` or `Assets.getBinary`.
* @param {Object} options
* @param {String} options.path The path at which to serve the asset.
* @param {Buffer|String} options.data The data that should be placed in the
* file.
* @param {String} [options.hash] Optionally, supply a hash for the output
* file.
* @memberOf InputFile
* @instance
*/
addAsset(options) {
var self = this;
self._resourceSlot.addAsset(options);
}
/**
* @summary Works in web targets only. Add markup to the `head` or `body`
* section of the document.
* @param {Object} options
* @param {String} options.section Which section of the document should
* be appended to. Can only be "head" or "body".
* @param {String} options.data The content to append.
* @memberOf InputFile
* @instance
*/
addHtml(options) {
var self = this;
self._resourceSlot.addHtml(options);
}
_reportError(message, info) {
if (this.getFileOptions().lazy === true) {
// Files with fileOptions.lazy === true were not explicitly added to
// the source batch via api.addFiles or api.mainModule, so any
// compilation errors should not be fatal until the files are
// actually imported by the ImportScanner. Attempting compilation is
// still important for lazy files that might end up being imported
// later, which is why we defang the error here, instead of avoiding
// compilation preemptively. Note also that exceptions thrown by the
// compiler will still cause build errors.
this._resourceSlot.addError(message, info);
} else {
super._reportError(message, info);
}
}
}
class ResourceSlot {
constructor(unibuildResourceInfo,
sourceProcessor,
packageSourceBatch) {
const self = this;
// XXX ideally this should be an classy object, but it's not.
self.inputResource = unibuildResourceInfo;
// Everything but JS.
self.outputResources = [];
// JS, which gets linked together at the end.
self.jsOutputResources = [];
self.sourceProcessor = sourceProcessor;
self.packageSourceBatch = packageSourceBatch;
if (self.inputResource.type === "source") {
if (sourceProcessor) {
// If we have a sourceProcessor, it will handle the adding of the
// final processed JavaScript.
} else if (self.inputResource.extension === "js") {
// If there is no sourceProcessor for a .js file, add the source
// directly to the output. #HardcodeJs
self.addJavaScript({
// XXX it's a shame to keep converting between Buffer and string, but
// files.convertToStandardLineEndings only works on strings for now
data: self.inputResource.data.toString('utf8'),
path: self.inputResource.path,
hash: self.inputResource.hash,
bare: self.inputResource.fileOptions &&
(self.inputResource.fileOptions.bare ||
// XXX eventually get rid of backward-compatibility "raw" name
// XXX COMPAT WITH 0.6.4
self.inputResource.fileOptions.raw)
});
}
} else {
if (sourceProcessor) {
throw Error("sourceProcessor for non-source? " +
JSON.stringify(unibuildResourceInfo));
}
// Any resource that isn't handled by compiler plugins just gets passed
// through.
if (self.inputResource.type === "js") {
let resource = self.inputResource;
if (! _.isString(resource.sourcePath)) {
resource.sourcePath = self.inputResource.path;
}
if (! _.isString(resource.targetPath)) {
resource.targetPath = resource.sourcePath;
}
self.jsOutputResources.push(resource);
} else {
self.outputResources.push(self.inputResource);
}
}
}
_getOption(name, options) {
if (options && _.has(options, name)) {
return options[name];
}
const fileOptions = this.inputResource.fileOptions;
return fileOptions && fileOptions[name];
}
_isLazy(options) {
let lazy = this._getOption("lazy", options);
if (typeof lazy === "boolean") {
return lazy;
}
// If file.lazy was not previously defined, mark the file lazy if
// it is contained by an imports directory. Note that any files
// contained by a node_modules directory will already have been
// marked lazy in PackageSource#_inferFileOptions. Same for
// non-test files if running (non-full-app) tests (`meteor test`)
if (!this.packageSourceBatch.useMeteorInstall) {
return false;
}
const splitPath = this.inputResource.path.split(files.pathSep);
const isInImports = splitPath.indexOf("imports") >= 0;
if (global.testCommandMetadata &&
(global.testCommandMetadata.isTest ||
global.testCommandMetadata.isAppTest)) {
// test files should always be included, if we're running app
// tests.
return isInImports && !isTestFilePath(this.inputResource.path);
} else {
return isInImports;
}
}
addStylesheet(options) {
const self = this;
if (! self.sourceProcessor) {
throw Error("addStylesheet on non-source ResourceSlot?");
}
const data = files.convertToStandardLineEndings(options.data);
const useMeteorInstall = self.packageSourceBatch.useMeteorInstall;
const sourcePath = this.inputResource.path;
const targetPath = options.path || sourcePath;
const resource = {
refreshable: true,
sourcePath,
targetPath,
servePath: self.packageSourceBatch.unibuild.pkg._getServePath(targetPath),
hash: sha1(data),
lazy: this._isLazy(options),
};
if (useMeteorInstall && resource.lazy) {
// If the current packageSourceBatch supports modules, and this CSS
// file is lazy, add it as a lazy JS module instead of adding it
// unconditionally as a CSS resource, so that it can be imported
// when needed.
resource.type = "js";
resource.data =
new Buffer(cssToCommonJS(data, resource.hash), "utf8");
self.jsOutputResources.push(resource);
} else {
// Eager CSS is added unconditionally to a combined <style> tag at
// the beginning of the <head>. If the corresponding module ever
// gets imported, its module.exports object should be an empty stub,
// rather than a <style> node added dynamically to the <head>.
self.jsOutputResources.push({
...resource,
type: "js",
data: new Buffer(
"// These styles have already been applied to the document.\n",
"utf8"),
// If a compiler plugin calls addJavaScript with the same
// sourcePath, that code should take precedence over this empty
// stub, so this property marks the resource as disposable.
emtpyStub: true,
lazy: true,
});
resource.type = "css";
resource.data = new Buffer(data, 'utf8'),
// XXX do we need to call convertSourceMapPaths here like we did
// in legacy handlers?
resource.sourceMap = options.sourceMap;
self.outputResources.push(resource);
}
}
addJavaScript(options) {
const self = this;
// #HardcodeJs this gets called by constructor in the "js" case
if (! self.sourceProcessor && self.inputResource.extension !== "js") {
throw Error("addJavaScript on non-source ResourceSlot?");
}
let sourcePath = self.inputResource.path;
if (_.has(options, "sourcePath") &&
typeof options.sourcePath === "string") {
sourcePath = options.sourcePath;
}
const targetPath = options.path || sourcePath;
var data = new Buffer(
files.convertToStandardLineEndings(options.data), 'utf8');
self.jsOutputResources.push({
type: "js",
data: data,
sourcePath,
targetPath,
servePath: self.packageSourceBatch.unibuild.pkg._getServePath(targetPath),
// XXX should we allow users to be trusted and specify a hash?
hash: sha1(data),
// XXX do we need to call convertSourceMapPaths here like we did
// in legacy handlers?
sourceMap: options.sourceMap,
// intentionally preserve a possible `undefined` value for files
// in apps, rather than convert it into `false` via `!!`
lazy: self._isLazy(options),
bare: !! self._getOption("bare", options),
mainModule: !! self._getOption("mainModule", options),
});
}
addAsset(options) {
const self = this;
if (! self.sourceProcessor) {
throw Error("addAsset on non-source ResourceSlot?");
}
if (! (options.data instanceof Buffer)) {
if (_.isString(options.data)) {
options.data = new Buffer(options.data);
} else {
throw new Error("'data' option to addAsset must be a Buffer or String.");
}
}
self.outputResources.push({
type: 'asset',
data: options.data,
path: options.path,
servePath: self.packageSourceBatch.unibuild.pkg._getServePath(
options.path),
hash: sha1(options.data),
lazy: self._isLazy(options),
});
}
addHtml(options) {
const self = this;
const unibuild = self.packageSourceBatch.unibuild;
if (! archinfo.matches(unibuild.arch, "web")) {
throw new Error("Document sections can only be emitted to " +
"web targets: " + self.inputResource.path);
}
if (options.section !== "head" && options.section !== "body") {
throw new Error("'section' must be 'head' or 'body': " +
self.inputResource.path);
}
if (typeof options.data !== "string") {
throw new Error("'data' option to appendDocument must be a string: " +
self.inputResource.path);
}
self.outputResources.push({
type: options.section,
data: new Buffer(files.convertToStandardLineEndings(options.data), 'utf8'),
lazy: self._isLazy(options),
});
}
addError(message, info) {
// If this file is ever actually imported, only then will we report
// the error. Use this.jsOutputResources because that's what the
// ImportScanner deals with.
this.jsOutputResources.push({
type: "js",
sourcePath: this.inputResource.path,
targetPath: this.inputResource.path,
servePath: this.inputResource.path,
data: new Buffer(
"throw new Error(" + JSON.stringify(message) + ");\n",
"utf8"),
lazy: true,
error: { message, info },
});
}
}
export class PackageSourceBatch {
constructor(unibuild, processor, {
sourceRoot,
linkerCacheDir,
}) {
const self = this;
buildmessage.assertInJob();
self.unibuild = unibuild;
self.processor = processor;
self.sourceRoot = sourceRoot;
self.linkerCacheDir = linkerCacheDir;
self.importExtensions = [".js", ".json"];
self._resolver = null;
var sourceProcessorSet = self._getSourceProcessorSet();
self.resourceSlots = [];
unibuild.resources.forEach(function (resource) {
let sourceProcessor = null;
if (resource.type === "source") {
var extension = resource.extension;
if (extension === null) {
const filename = files.pathBasename(resource.path);
sourceProcessor = sourceProcessorSet.getByFilename(filename);
if (! sourceProcessor) {
buildmessage.error(
`no plugin found for ${ resource.path } in ` +
`${ unibuild.pkg.displayName() }; a plugin for ${ filename } ` +
`was active when it was published but none is now`);
return;
// recover by ignoring
}
} else {
sourceProcessor = sourceProcessorSet.getByExtension(extension);
// If resource.extension === 'js', it's ok for there to be no
// sourceProcessor, since we #HardcodeJs in ResourceSlot.
if (! sourceProcessor && extension !== 'js') {
buildmessage.error(
`no plugin found for ${ resource.path } in ` +
`${ unibuild.pkg.displayName() }; a plugin for *.${ extension } ` +
`was active when it was published but none is now`);
return;
// recover by ignoring
}
self.addImportExtension(extension);
}
}
self.resourceSlots.push(new ResourceSlot(resource, sourceProcessor, self));
});
// Compute imports by merging the exports of all of the packages we
// use. Note that in the case of conflicting symbols, later packages get
// precedence.
//
// We don't get imports from unordered dependencies (since they
// may not be defined yet) or from
// weak/debugOnly/prodOnly/testOnly dependencies (because the
// meaning of a name shouldn't be affected by the non-local
// decision of whether or not an unrelated package in the target
// depends on something).
self.importedSymbolToPackageName = {}; // map from symbol to supplying package name
compiler.eachUsedUnibuild({
dependencies: self.unibuild.uses,
arch: self.processor.arch,
isopackCache: self.processor.isopackCache,
skipUnordered: true,
// don't import symbols from debugOnly, prodOnly and testOnly packages, because
// if the package is not linked it will cause a runtime error.
// the code must access them with `Package["my-package"].MySymbol`.
skipDebugOnly: true,
skipProdOnly: true,
skipTestOnly: true,
}, depUnibuild => {
_.each(depUnibuild.declaredExports, function (symbol) {
// Slightly hacky implementation of test-only exports.
if (! symbol.testOnly || self.unibuild.pkg.isTest) {
self.importedSymbolToPackageName[symbol.name] = depUnibuild.pkg.name;
}
});
});
self.useMeteorInstall =
_.isString(self.sourceRoot) &&
self.processor.isopackCache.uses(
self.unibuild.pkg,
"modules",
self.unibuild.arch
);
}
addImportExtension(extension) {
extension = extension.toLowerCase();
if (! extension.startsWith(".")) {
extension = "." + extension;
}
if (this.importExtensions.indexOf(extension) < 0) {
this.importExtensions.push(extension);
}
}
getResolver() {
if (this._resolver) {
return this._resolver;
}
const nmds = this.unibuild.nodeModulesDirectories;
const nodeModulesPaths = [];
_.each(nmds, (nmd, path) => {
if (! nmd.local) {
nodeModulesPaths.push(
files.convertToOSPath(path.replace(/\/$/g, "")));
}
});
return this._resolver = Resolver.getOrCreate({
caller: "PackageSourceBatch#getResolver",
sourceRoot: this.sourceRoot,
targetArch: this.processor.arch,
extensions: this.importExtensions,
nodeModulesPaths,
});
}
_getSourceProcessorSet() {
const self = this;
buildmessage.assertInJob();
var isopack = self.unibuild.pkg;
const activePluginPackages = compiler.getActivePluginPackages(isopack, {
uses: self.unibuild.uses,
isopackCache: self.processor.isopackCache
});
const sourceProcessorSet = new buildPluginModule.SourceProcessorSet(
isopack.displayName(), { hardcodeJs: true });
_.each(activePluginPackages, function (otherPkg) {
otherPkg.ensurePluginsInitialized();
sourceProcessorSet.merge(
otherPkg.sourceProcessors.compiler, {arch: self.processor.arch});
});
return sourceProcessorSet;
}
// Returns a map from package names to arrays of JS output files.
static computeJsOutputFilesMap(sourceBatches) {
const map = new Map;
sourceBatches.forEach(batch => {
const name = batch.unibuild.pkg.name || null;
const inputFiles = [];
batch.resourceSlots.forEach(slot => {
inputFiles.push(...slot.jsOutputResources);
});
map.set(name, {
files: inputFiles,
importExtensions: batch.importExtensions,
});
});
if (! map.has("modules")) {
// In the unlikely event that no package is using the modules
// package, then the map is already complete, and we don't need to
// do any import scanning.
return map;
}
// Append install(<name>) calls to the install-packages.js file in the
// modules package for every Meteor package name used.
map.get("modules").files.some(file => {
if (file.sourcePath !== "install-packages.js") {
return false;
}
const meteorPackageInstalls = [];
map.forEach((info, name) => {
if (! name) return;
let mainModule = _.find(info.files, file => file.mainModule);
mainModule = mainModule ?
`meteor/${name}/${mainModule.targetPath}` : false;
meteorPackageInstalls.push(
"install(" + JSON.stringify(name) +
(mainModule ? ", " + JSON.stringify(mainModule) : '') +
");\n"
);
});
if (meteorPackageInstalls.length === 0) {
return false;
}
file.data = new Buffer(
file.data.toString("utf8") + "\n" +
meteorPackageInstalls.join(""),
"utf8"
);
file.hash = sha1(file.data);
return true;
});
const allMissingNodeModules = Object.create(null);
// Records the subset of allMissingNodeModules that were successfully
// relocated to a source batch that could handle them.
const allRelocatedNodeModules = Object.create(null);
const scannerMap = new Map;
sourceBatches.forEach(batch => {
const name = batch.unibuild.pkg.name || null;
const isApp = ! name;
if (! batch.useMeteorInstall && ! isApp) {