forked from meteor/meteor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
packages.js
2271 lines (2028 loc) · 88.4 KB
/
packages.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 path = require('path');
var os = require('os');
var _ = require('underscore');
var files = require('./files.js');
var watch = require('./watch.js');
var bundler = require('./bundler.js');
var Builder = require('./builder.js');
var project = require('./project.js');
var buildmessage = require('./buildmessage.js');
var meteorNpm = require('./meteor_npm.js');
var archinfo = require(path.join(__dirname, 'archinfo.js'));
var linker = require(path.join(__dirname, 'linker.js'));
var unipackage = require('./unipackage.js');
var fs = require('fs');
var sourcemap = require('source-map');
// Whenever you change anything about the code that generates unipackages, bump
// this version number. The idea is that the "format" field of the unipackage
// JSON file only changes when the actual specified structure of the
// unipackage/slice changes, but this version (which is build-tool-specific) can
// change when the the contents (not structure) of the built output changes. So
// eg, if we improve the linker's static analysis, this should be bumped.
//
// You should also update this whenever you update any of the packages used
// directly by the unipackage creation process (eg js-analyze) since they do not
// end up as watched dependencies. (At least for now, packages only used in
// target creation (eg minifiers and dev-bundle-fetcher) don't require you to
// update BUILT_BY, though you will need to quit and rerun "meteor run".)
exports.BUILT_BY = 'meteor/10';
// Like Perl's quotemeta: quotes all regexp metacharacters. See
// https://github.com/substack/quotemeta/blob/master/index.js
var quotemeta = function (str) {
return String(str).replace(/(\W)/g, '\\$1');
};
var rejectBadPath = function (p) {
if (p.match(/\.\./))
throw new Error("bad path: " + p);
};
var parseSpec = function (spec) {
var parts = spec.split(':');
if (parts.length > 2 || parts.length === 0)
throw new Error("Bad package spec: " + spec);
var ret = {package: parts[0]};
if (parts.length === 2)
ret.slice = parts[1];
return ret;
};
///////////////////////////////////////////////////////////////////////////////
// Slice
///////////////////////////////////////////////////////////////////////////////
// Options:
// - name [required]
// - arch [required]
// - uses
// - implies
// - getSourcesFunc
// - exports
// - watchSet
// - nodeModulesPath
//
// Do not include the source files in watchSet. They will be
// added at compile time when the sources are actually read.
var Slice = function (pkg, options) {
var self = this;
options = options || {};
self.pkg = pkg;
// Name for this slice. For example, the "client" in "ddp.client"
// (which, NB, we might load on server arches.)
self.sliceName = options.name;
// The architecture (fully or partially qualified) that can use this
// slice.
self.arch = options.arch;
// Unique ID for this slice. Unique across all slices of all
// packages, but constant across reloads of this slice.
self.id = pkg.id + "." + options.name + "@" + self.arch;
// Packages used. The ordering is significant only for determining
// import symbol priority (it doesn't affect load order), and a
// given package could appear more than once in the list, so code
// that consumes this value will need to guard appropriately. Each
// element in the array has keys:
// - package: the package name
// - slice: the slice name (optional)
// - unordered: If true, we don't want the package's imports and we
// don't want to force the package to load before us. We just want
// to ensure that it loads if we load.
// - weak: If true, we don't *need* to load the other package, but
// if the other package ends up loaded in the target, it must
// be forced to load before us. We will not get its imports
// or plugins.
// It is an error for both unordered and weak to be true, because
// such a dependency would have no effect.
//
// In most places, you want to use slice.eachUsedSlice() instead of
// slice.uses, which also takes into account implied packages.
self.uses = options.uses;
// Packages which are "implied" by using this package. If a slice X uses this
// slice Y, and Y implies Z, then X will effectively use Z as well (and get
// its imports and plugins). An array of objects of the same type as the
// elements of self.uses (although for now unordered and weak are not
// allowed).
self.implies = options.implies || [];
// A function that returns the source files for this slice. Array of objects
// with keys "relPath" and "fileOptions". Null if loaded from unipackage.
//
// fileOptions is optional and represents arbitrary options passed to
// "api.add_files"; they are made available on to the plugin as
// compileStep.fileOptions.
//
// This is a function rather than a literal array because for an
// app, we need to know the file extensions registered by the
// plugins in order to compute the sources list, so we have to wait
// until build time (after we have loaded any plugins, including
// local plugins in this package) to compute this.
self.getSourcesFunc = options.getSourcesFunc || null;
// True if this slice is not permitted to have any exports, and in fact should
// not even define `Package.name` (ie, test slices).
self.noExports = options.noExports || false;
// Symbols that this slice should export. List of symbols (as strings). Null
// on built packages (see packageVariables instead), or in packages where
// noExports is set.
self.declaredExports = options.declaredExports || null;
// Files and directories that we want to monitor for changes in
// development mode, such as source files and package.js, as a watch.WatchSet.
self.watchSet = options.watchSet || new watch.WatchSet();
// Has this slice been compiled?
self.isBuilt = false;
// Prelink output.
//
// 'prelinkFiles' is the partially linked JavaScript code (an
// array of objects with keys 'source' and 'servePath', both strings -- see
// prelink() in linker.js)
//
// 'packageVariables' are are variables that are syntactically globals in our
// input files and which we capture with a package-scope closure. A list of
// objects with keys 'name' (required) and 'export' (true, 'tests', or falsy).
//
// Both of these are saved into slices on disk, and are inputs into the final
// link phase, which inserts the final JavaScript resources into
// 'resources'. Set only when isBuilt is true.
self.prelinkFiles = null;
self.packageVariables = null;
// All of the data provided for eventual inclusion in the bundle,
// other than JavaScript that still needs to be fed through the
// final link stage. A list of objects with these keys:
//
// type: "js", "css", "head", "body", "asset"
//
// data: The contents of this resource, as a Buffer. For example,
// for "head", the data to insert in <head>; for "js", the
// JavaScript source code (which may be subject to further
// processing such as minification); for "asset", the contents of a
// static resource such as an image.
//
// servePath: The (absolute) path at which the resource would prefer
// to be served. Interpretation varies by type. For example, always
// honored for "asset", ignored for "head" and "body", sometimes
// honored for CSS but ignored if we are concatenating.
//
// sourceMap: Allowed only for "js". If present, a string.
//
// Set only when isBuilt is true.
self.resources = null;
// Absolute path to the node_modules directory to use at runtime to
// resolve Npm.require() calls in this slice. null if this slice
// does not have a node_modules.
self.nodeModulesPath = options.nodeModulesPath;
};
_.extend(Slice.prototype, {
// Move the slice to the 'built' state. Process all source files
// through the appropriate handlers and run the prelink phase on any
// resulting JavaScript. Also add all provided source files to the
// package dependencies. Sets fields such as dependencies, exports,
// prelinkFiles, packageVariables, and resources.
build: function () {
var self = this;
var isApp = ! self.pkg.name;
if (self.isBuilt)
throw new Error("slice built twice?");
var resources = [];
var js = [];
// Preemptively check to make sure that each of the packages we
// reference actually exist. If we find a package that doesn't
// exist, emit an error and remove it from the package list. That
// way we get one error about it instead of a new error at each
// stage in the build process in which we try to retrieve the
// package.
_.each(['uses', 'implies'], function (field) {
var scrubbed = [];
_.each(self[field], function (u) {
var pkg = self.pkg.library.get(u.package, /* throwOnError */ false);
if (! pkg) {
buildmessage.error("no such package: '" + u.package + "'");
// recover by omitting this package from the field
} else
scrubbed.push(u);
});
self[field] = scrubbed;
});
var addAsset = function (contents, relPath) {
// XXX hack
if (!self.pkg.name)
relPath = relPath.replace(/^(private|public)\//, '');
resources.push({
type: "asset",
data: contents,
path: relPath,
servePath: path.join(self.pkg.serveRoot, relPath)
});
};
_.each(self.getSourcesFunc(), function (source) {
var relPath = source.relPath;
var fileOptions = _.clone(source.fileOptions) || {};
var absPath = path.resolve(self.pkg.sourceRoot, relPath);
var filename = path.basename(relPath);
var handler = !fileOptions.isAsset && self._getSourceHandler(filename);
var contents = watch.readAndWatchFile(self.watchSet, absPath);
if (contents === null) {
buildmessage.error("File not found: " + source.relPath);
// recover by ignoring
return;
}
if (! handler) {
// If we don't have an extension handler, serve this file as a
// static resource on the client, or ignore it on the server.
//
// XXX This is pretty confusing, especially if you've
// accidentally forgotten a plugin -- revisit?
addAsset(contents, relPath);
return;
}
// This object is called a #CompileStep and it's the interface
// to plugins that define new source file handlers (eg,
// Coffeescript.)
//
// Fields on CompileStep:
//
// - arch: the architecture for which we are building
// - inputSize: total number of bytes in the input file
// - inputPath: the filename and (relative) path of the input
// file, eg, "foo.js". We don't provide a way to get the full
// path because you're not supposed to read the file directly
// off of disk. Instead you should call read(). That way we
// can ensure that the version of the file that you use is
// exactly the one that is recorded in the dependency
// information.
// - pathForSourceMap: If this file is to be included in a source map,
// this is the name you should use for it in the map.
// - rootOutputPath: on browser targets, for resources such as
// stylesheet and static assets, this is the root URL that
// will get prepended to the paths you pick for your output
// files so that you get your own namespace, for example
// '/packages/foo'. null on non-browser targets
// - fileOptions: any options passed to "api.add_files"; for
// use by the plugin. The built-in "js" plugin uses the "bare"
// option for files that shouldn't be wrapped in a closure.
// - declaredExports: An array of symbols exported by this slice, or null
// if it may not export any symbols (eg, test slices). This is used by
// CoffeeScript to ensure that it doesn't close over those symbols, eg.
// - read(n): read from the input file. If n is given it should
// be an integer, and you will receive the next n bytes of the
// file as a Buffer. If n is omitted you get the rest of the
// file.
// - appendDocument({ section: "head", data: "my markup" })
// Browser targets only. Add markup to the "head" or "body"
// section of the document.
// - addStylesheet({ path: "my/stylesheet.css", data: "my css" })
// Browser targets only. Add a stylesheet to the
// document. 'path' is a requested URL for the stylesheet that
// may or may not ultimately be honored. (Meteor will add
// appropriate tags to cause the stylesheet to be loaded. It
// will be subject to any stylesheet processing stages in
// effect, such as minification.)
// - addJavaScript({ path: "my/program.js", data: "my code",
// sourcePath: "src/my/program.js",
// bare: true })
// Add JavaScript code, which will be namespaced into this
// package's environment (eg, it will see only the exports of
// this package's imports), and which will be subject to
// minification and so forth. Again, 'path' is merely a hint
// that may or may not be honored. 'sourcePath' is the path
// that will be used in any error messages generated (eg,
// "foo.js:4:1: syntax error"). It must be present and should
// be relative to the project root. Typically 'inputPath' will
// do handsomely. "bare" means to not wrap the file in
// a closure, so that its vars are shared with other files
// in the module.
// - addAsset({ path: "my/image.png", data: Buffer })
// Add a file to serve as-is over HTTP (browser targets) or
// to include as-is in the bundle (os targets).
// This time `data` is a Buffer rather than a string. For
// browser targets, it will be served at the exact path you
// request (concatenated with rootOutputPath). For server
// targets, the file can be retrieved by passing path to
// Assets.getText or Assets.getBinary.
// - error({ message: "There's a problem in your source file",
// sourcePath: "src/my/program.ext", line: 12,
// column: 20, func: "doStuff" })
// Flag an error -- at a particular location in a source
// file, if you like (you can even indicate a function name
// to show in the error, like in stack traces.) sourcePath,
// line, column, and func are all optional.
//
// XXX for now, these handlers must only generate portable code
// (code that isn't dependent on the arch, other than 'browser'
// vs 'os') -- they can look at the arch that is provided
// but they can't rely on the running on that particular arch
// (in the end, an arch-specific slice will be emitted only if
// there are native node modules.) Obviously this should
// change. A first step would be a setOutputArch() function
// analogous to what we do with native node modules, but maybe
// what we want is the ability to ask the plugin ahead of time
// how specific it would like to force builds to be.
//
// XXX we handle encodings in a rather cavalier way and I
// suspect we effectively end up assuming utf8. We can do better
// than that!
//
// XXX addAsset probably wants to be able to set MIME type and
// also control any manifest field we deem relevant (if any)
//
// XXX Some handlers process languages that have the concept of
// include files. These are problematic because we need to
// somehow instrument them to get the names and hashs of all of
// the files that they read for dependency tracking purposes. We
// don't have an API for that yet, so for now we provide a
// workaround, which is that _fullInputPath contains the full
// absolute path to the input files, which allows such a plugin
// to set up its include search path. It's then on its own for
// registering dependencies (for now..)
//
// XXX in the future we should give plugins an easy and clean
// way to return errors (that could go in an overall list of
// errors experienced across all files)
var readOffset = 0;
var compileStep = {
inputSize: contents.length,
inputPath: relPath,
_fullInputPath: absPath, // avoid, see above..
// XXX duplicates _pathForSourceMap() in linker
pathForSourceMap: (
self.pkg.name
? self.pkg.name + "/" + relPath
: path.basename(relPath)),
// null if this is an app. intended to be used for the sources
// dictionary for source maps.
packageName: self.pkg.name,
rootOutputPath: self.pkg.serveRoot,
arch: self.arch,
archMatches: function (pattern) {
return archinfo.matches(self.arch, pattern);
},
fileOptions: fileOptions,
declaredExports: _.pluck(self.declaredExports, 'name'),
read: function (n) {
if (n === undefined || readOffset + n > contents.length)
n = contents.length - readOffset;
var ret = contents.slice(readOffset, readOffset + n);
readOffset += n;
return ret;
},
appendDocument: function (options) {
if (! archinfo.matches(self.arch, "browser"))
throw new Error("Document sections can only be emitted to " +
"browser targets");
if (options.section !== "head" && options.section !== "body")
throw new Error("'section' must be 'head' or 'body'");
if (typeof options.data !== "string")
throw new Error("'data' option to appendDocument must be a string");
resources.push({
type: options.section,
data: new Buffer(options.data, 'utf8')
});
},
addStylesheet: function (options) {
if (! archinfo.matches(self.arch, "browser"))
throw new Error("Stylesheets can only be emitted to " +
"browser targets");
if (typeof options.data !== "string")
throw new Error("'data' option to addStylesheet must be a string");
resources.push({
type: "css",
data: new Buffer(options.data, 'utf8'),
servePath: path.join(self.pkg.serveRoot, options.path)
});
},
addJavaScript: function (options) {
if (typeof options.data !== "string")
throw new Error("'data' option to addJavaScript must be a string");
if (typeof options.sourcePath !== "string")
throw new Error("'sourcePath' option must be supplied to addJavaScript. Consider passing inputPath.");
if (options.bare && ! archinfo.matches(self.arch, "browser"))
throw new Error("'bare' option may only be used for browser targets");
js.push({
source: options.data,
sourcePath: options.sourcePath,
servePath: path.join(self.pkg.serveRoot, options.path),
bare: !!options.bare,
sourceMap: options.sourceMap
});
},
addAsset: function (options) {
if (! (options.data instanceof Buffer))
throw new Error("'data' option to addAsset must be a Buffer");
addAsset(options.data, options.path);
},
error: function (options) {
buildmessage.error(options.message || ("error building " + relPath), {
file: options.sourcePath,
line: options.line ? options.line : undefined,
column: options.column ? options.column : undefined,
func: options.func ? options.func : undefined
});
}
};
try {
(buildmessage.markBoundary(handler))(compileStep);
} catch (e) {
e.message = e.message + " (compiling " + relPath + ")";
buildmessage.exception(e);
// Recover by ignoring this source file (as best we can -- the
// handler might already have emitted resources)
}
});
// Phase 1 link
// Load jsAnalyze from the js-analyze package... unless we are the
// js-analyze package, in which case never mind. (The js-analyze package's
// default slice is not allowed to depend on anything!)
var jsAnalyze = null;
if (! _.isEmpty(js) && self.pkg.name !== "js-analyze") {
jsAnalyze = unipackage.load({
library: self.pkg.library,
packages: ["js-analyze"]
})["js-analyze"].JSAnalyze;
}
var results = linker.prelink({
inputFiles: js,
useGlobalNamespace: isApp,
combinedServePath: isApp ? null :
"/packages/" + self.pkg.name +
(self.sliceName === "main" ? "" : (":" + self.sliceName)) + ".js",
name: self.pkg.name || null,
declaredExports: _.pluck(self.declaredExports, 'name'),
jsAnalyze: jsAnalyze
});
// Add dependencies on the source code to any plugins that we could have
// used. We need to depend even on plugins that we didn't use, because if
// they were changed they might become relevant to us. This means that we
// end up depending on every source file contributing to all plugins in the
// packages we use (including source files from other packages that the
// plugin program itself uses), as well as the package.js file from every
// package we directly use (since changing the package.js may add or remove
// a plugin).
_.each(self._activePluginPackages(), function (otherPkg) {
self.watchSet.merge(otherPkg.pluginWatchSet);
// XXX this assumes this is not overwriting something different
self.pkg.pluginProviderPackageDirs[otherPkg.name] =
otherPkg.packageDirectoryForBuildInfo;
});
self.prelinkFiles = results.files;
self.packageVariables = [];
var packageVariableNames = {};
_.each(self.declaredExports, function (symbol) {
if (_.has(packageVariableNames, symbol.name))
return;
self.packageVariables.push({
name: symbol.name,
export: symbol.testOnly? "tests" : true
});
packageVariableNames[symbol.name] = true;
});
_.each(results.assignedVariables, function (name) {
if (_.has(packageVariableNames, name))
return;
self.packageVariables.push({
name: name
});
packageVariableNames[name] = true;
});
// Forget about the *declared* exports; what matters is packageVariables
// now.
self.declaredExports = null;
self.resources = resources;
self.isBuilt = true;
},
// Get the resources that this function contributes to a bundle, in
// the same format as self.resources as documented above. This
// includes static assets and fully linked JavaScript.
//
// @param bundleArch The architecture targeted by the bundle. Might
// be more specific than self.arch.
//
// It is when you call this function that we read our dependent
// packages and commit to whatever versions of them we currently
// have in the library -- at least for the purpose of imports, which
// is resolved at bundle time. (On the other hand, when it comes to
// the extension handlers we'll use, we previously commited to those
// versions at package build ('compile') time.)
getResources: function (bundleArch) {
var self = this;
var library = self.pkg.library;
if (! self.isBuilt)
throw new Error("getting resources of unbuilt slice?" + self.pkg.name + " " + self.sliceName + " " + self.arch);
if (! archinfo.matches(bundleArch, self.arch))
throw new Error("slice of arch '" + self.arch + "' does not support '" +
bundleArch + "'?");
// 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 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).
var imports = {}; // map from symbol to supplying package name
self.eachUsedSlice(
bundleArch, {skipWeak: true, skipUnordered: true}, function (otherSlice) {
if (! otherSlice.isBuilt)
throw new Error("dependency wasn't built?");
_.each(otherSlice.packageVariables, function (symbol) {
// Slightly hacky implementation of test-only exports.
if (symbol.export === true ||
(symbol.export === "tests" && self.sliceName === "tests"))
imports[symbol.name] = otherSlice.pkg.name;
});
});
// Phase 2 link
var isApp = ! self.pkg.name;
var files = linker.link({
imports: imports,
useGlobalNamespace: isApp,
// XXX report an error if there is a package called global-imports
importStubServePath: isApp && '/packages/global-imports.js',
prelinkFiles: self.prelinkFiles,
noExports: self.noExports,
packageVariables: self.packageVariables,
includeSourceMapInstructions: archinfo.matches(self.arch, "browser"),
name: self.pkg.name || null
});
// Add each output as a resource
var jsResources = _.map(files, function (file) {
return {
type: "js",
data: new Buffer(file.source, 'utf8'), // XXX encoding
servePath: file.servePath,
sourceMap: file.sourceMap
};
});
return _.union(self.resources, jsResources); // union preserves order
},
// Calls `callback` with each slice (of architecture matching `arch`) that is
// "used" by this slice. This includes directly used slices, and slices that
// are transitively "implied" by used slices. (But not slices that are used by
// slices that we use!) Options are skipWeak and skipUnordered, meaning to
// ignore direct "uses" that are weak or unordered.
eachUsedSlice: function (arch, options, callback) {
var self = this;
if (typeof options === "function") {
callback = options;
options = {};
}
var processedSliceId = {};
var usesToProcess = [];
_.each(self.uses, function (use) {
if (options.skipUnordered && use.unordered)
return;
if (options.skipWeak && use.weak)
return;
usesToProcess.push(use);
});
while (!_.isEmpty(usesToProcess)) {
var use = usesToProcess.shift();
var slices =
self.pkg.library.getSlices(_.pick(use, 'package', 'spec'), arch);
_.each(slices, function (slice) {
if (_.has(processedSliceId, slice.id))
return;
processedSliceId[slice.id] = true;
callback(slice, {
unordered: !!use.unordered,
weak: !!use.weak
});
_.each(slice.implies, function (implied) {
usesToProcess.push(implied);
});
});
}
},
// Return an array of all plugins that are active in this slice, as
// a list of Packages.
_activePluginPackages: function () {
var self = this;
// XXX we used to include our own extensions only if we were the
// "use" role. now we include them everywhere because we don't
// have a special "use" role anymore. it's not totally clear to me
// what the correct behavior should be -- we need to resolve
// whether we think about extensions as being global to a package
// or particular to a slice.
// (there's also some weirdness here with handling implies, because
// the implies field is on the target slice, but we really only care
// about packages.)
var ret = [self.pkg];
// We don't use plugins from weak dependencies, because the ability to
// compile a certain type of file shouldn't depend on whether or not some
// unrelated package in the target has a dependency.
//
// We pass archinfo.host here, not self.arch, because it may be more
// specific, and because plugins always have to run on the host
// architecture.
self.eachUsedSlice(archinfo.host(), {skipWeak: true}, function (usedSlice) {
ret.push(usedSlice.pkg);
});
// Only need one copy of each package.
ret = _.uniq(ret);
_.each(ret, function (pkg) {
pkg._ensurePluginsInitialized();
});
return ret;
},
// Get all extensions handlers registered in this slice, as a map
// from extension (no leading dot) to handler function. Throws an
// exception if two packages are registered for the same extension.
_allHandlers: function () {
var self = this;
var ret = {};
// We provide a hardcoded handler for *.js files.. since plugins
// are written in JavaScript we have to start somewhere.
_.extend(ret, {
js: function (compileStep) {
compileStep.addJavaScript({
data: compileStep.read().toString('utf8'),
path: compileStep.inputPath,
sourcePath: compileStep.inputPath,
// XXX eventually get rid of backward-compatibility "raw" name
// XXX COMPAT WITH 0.6.4
bare: compileStep.fileOptions.bare || compileStep.fileOptions.raw
});
}
});
_.each(self._activePluginPackages(), function (otherPkg) {
_.each(otherPkg.sourceHandlers, function (handler, ext) {
if (ext in ret && ret[ext] !== handler) {
buildmessage.error(
"conflict: two packages included in " +
(self.pkg.name || "the app") + ", " +
(ret[ext].pkg.name || "the app") + " and " +
(otherPkg.name || "the app") + ", " +
"are both trying to handle ." + ext);
// Recover by just going with the first handler we saw
} else {
ret[ext] = handler;
}
});
});
return ret;
},
// Return a list of all of the extension that indicate source files
// for this slice, not including leading dots. Computed based on
// this.uses, so should only be called once that has been set.
registeredExtensions: function () {
var self = this;
return _.keys(self._allHandlers());
},
// Find the function that should be used to handle a source file for
// this slice, or return null if there isn't one. We'll use handlers
// that are defined in this package and in its immediate dependencies.
_getSourceHandler: function (filename) {
var self = this;
var handlers = self._allHandlers();
var parts = filename.split('.');
for (var i = 0; i < parts.length; i++) {
var extension = parts.slice(i).join('.');
if (_.has(handlers, extension))
return handlers[extension];
}
return null;
}
});
///////////////////////////////////////////////////////////////////////////////
// Packages
///////////////////////////////////////////////////////////////////////////////
// XXX This object conflates two things that now seem to be almost
// totally separate: source code for a package, and an actual built
// package that is ready to be used. In fact it contains a list of
// Slice objects about which the same thing can be said. To see the
// distinction, ask yourself, what fields are set when the package is
// initialized via initFromUnipackage?
//
// Package and Slice should each be split into two objects, eg
// PackageSource and SliceSource versus BuiltPackage and BuiltSlice
// (find better names, though.)
var nextPackageId = 1;
var Package = function (library, packageDirectoryForBuildInfo) {
var self = this;
// A unique ID (guaranteed to not be reused in this process -- if
// the package is reloaded, it will get a different id the second
// time)
self.id = nextPackageId++;
// The name of the package, or null for an app pseudo-package or
// collection. The package's exports will reside in Package.<name>.
// When it is null it is linked like an application instead of like
// a package.
self.name = null;
// The path relative to which all source file paths are interpreted
// in this package. Also used to compute the location of the
// package's .npm directory (npm shrinkwrap state.) null if loaded
// from unipackage.
self.sourceRoot = null;
// Path that will be prepended to the URLs of all resources emitted
// by this package (assuming they don't end up getting
// concatenated.) For non-browser targets, the only effect this will
// have is to change the actual on-disk paths of the files in the
// bundle, for those that care to open up the bundle and look (but
// it's still nice to get it right.) null if loaded from unipackage.
self.serveRoot = null;
// The package's directory. This is used only by other packages that use this
// package in their buildinfo.json (to detect that they need to be rebuilt if
// the library's resolution of the package name changes); it is not used to
// read files or anything else. Notably, it should be the same if a package is
// read from a source tree or read from the .build unipackage inside that
// source tree.
self.packageDirectoryForBuildInfo = packageDirectoryForBuildInfo;
// Package library that should be used to resolve this package's
// dependencies
self.library = library;
// Package metadata. Keys are 'summary' and 'internal'.
self.metadata = {};
// Available editions/subpackages ("slices") of this package. Array
// of Slice.
self.slices = [];
// Map from an arch to the list of slice names that should be
// included by default if this package is used without specifying a
// slice (eg, as "ddp" rather than "ddp.server"). The most specific
// arch will be used.
self.defaultSlices = {};
// Map from an arch to the list of slice names that should be
// included when this package is tested. The most specific arch will
// be used.
self.testSlices = {};
// The information necessary to build the plugins in this
// package. Map from plugin name to object with keys 'name', 'use',
// 'sources', and 'npmDependencies'.
self.pluginInfo = {};
// Plugins in this package. Map from plugin name to JsImage. Present only when
// pluginsBuilt is true.
self.plugins = {};
// A WatchSet for the full transitive dependencies for all plugins in this
// package, as well as this package's package.js. If any of these dependencies
// change, our plugins need to be rebuilt... but also, any package that
// directly uses this package needs to be rebuilt in case the change to
// plugins affected compilation.
//
// Complete only when pluginsBuilt is true.
self.pluginWatchSet = new watch.WatchSet();
// Map from package name to packageDirectoryForBuildInfo of packages that are
// directly used by this package. We use this to figure out that we need to
// rebuild if the resolution of the package changes (eg, an app package is
// added that overshadows a warehouse package, or the release changes).
self.pluginProviderPackageDirs = {};
// True if plugins have been initialized (if _ensurePluginsInitialized has
// been called)
self._pluginsInitialized = false;
// Source file handlers registered by plugins. Map from extension
// (without a dot) to a handler function that takes a
// CompileStep. Valid only when _pluginsInitialized is true.
self.sourceHandlers = null;
// Is this package in a built state? If not (if you created it by
// means that doesn't create it in a build state to start with) you
// will need to call build() before you can use it. We break down
// the two phases of the build process, plugin building and
// slice building, into two flags.
self.pluginsBuilt = false;
self.slicesBuilt = false;
};
_.extend(Package.prototype, {
// Make a dummy (empty) package that contains nothing of interest.
initEmpty: function (name) {
var self = this;
self.name = name;
self.defaultSlices = {'': []};
self.testSlices = {'': []};
},
// Return the slice of the package to use for a given slice name
// (eg, 'main' or 'test') and target architecture (eg,
// 'os.linux.x86_64' or 'browser'), or throw an exception if
// that packages can't be loaded under these circumstances.
getSingleSlice: function (name, arch) {
var self = this;
var chosenArch = archinfo.mostSpecificMatch(
arch, _.pluck(_.where(self.slices, { sliceName: name }), 'arch'));
if (! chosenArch) {
// XXX need improvement. The user should get a graceful error
// message, not an exception, and all of this talk of slices an
// architectures is likely to be confusing/overkill in many
// contexts.
throw new Error((self.name || "this app") +
" does not have a slice named '" + name +
"' that runs on architecture '" + arch + "'");
}
return _.where(self.slices, { sliceName: name, arch: chosenArch })[0];
},
// Return the slices that should be used on a given arch if the
// package is named without any qualifiers (eg, 'ddp' rather than
// 'ddp.client').
//
// On error, throw an exception, or if inside
// buildmessage.capture(), log a build error and return [].
getDefaultSlices: function (arch) {
var self = this;
var chosenArch = archinfo.mostSpecificMatch(arch,
_.keys(self.defaultSlices));
if (! chosenArch) {
buildmessage.error(
(self.name || "this app") +
" is not compatible with architecture '" + arch + "'",
{ secondary: true });
// recover by returning by no slices
return [];
}
return _.map(self.defaultSlices[chosenArch], function (name) {
return self.getSingleSlice(name, arch);
});
},
// Return the slices that should be used to test the package on a
// given arch.
getTestSlices: function (arch) {
var self = this;
var chosenArch = archinfo.mostSpecificMatch(arch,
_.keys(self.testSlices));
if (! chosenArch) {
buildmessage.error(
(self.name || "this app") +
" does not have tests for architecture " + arch + "'",
{ secondary: true });
// recover by returning by no slices
return [];
}
return _.map(self.testSlices[chosenArch], function (name) {
return self.getSingleSlice(name, arch);
});
},
// This is called on all packages at Meteor install time so they can
// do any prep work necessary for the user's first Meteor run to be
// fast, for example fetching npm dependencies. Currently thanks to
// refactorings there's nothing to do here.
// XXX remove?
preheat: function () {
},
// If this package has plugins, initialize them (run the startup
// code in them so that they register their extensions.) Idempotent.
_ensurePluginsInitialized: function () {
var self = this;
if (! self.pluginsBuilt)
throw new Error("running plugins of unbuilt package?");
if (self._pluginsInitialized)
return;
var Plugin = {
// 'extension' is a file extension without the separation dot
// (eg 'js', 'coffee', 'coffee.md')
//
// 'handler' is a function that takes a single argument, a
// CompileStep (#CompileStep)
registerSourceHandler: function (extension, handler) {
if (_.has(self.sourceHandlers, extension)) {
buildmessage.error("duplicate handler for '*." +
extension + "'; may only have one per Plugin",
{ useMyCaller: true });
// recover by ignoring all but the first
return;
}
self.sourceHandlers[extension] = handler;
}
};
self.sourceHandlers = {};
_.each(self.plugins, function (plugin, name) {
buildmessage.enterJob({
title: "loading plugin `" + name +
"` from package `" + self.name + "`"
// don't necessarily have rootPath anymore
// (XXX we do, if the unipackage was locally built, which is
// the important case for debugging. it'd be nice to get this
// case right.)
}, function () {
plugin.load({Plugin: Plugin});
});
});
self._pluginsInitialized = true;
},
// Move a package to the built state (by running its source files
// through the appropriate compiler plugins.) Once build has
// completed, any errors detected in the package will have been
// emitted to buildmessage.
//
// build() may retrieve the package's dependencies from the library,
// so it is illegal to call build() from library.get() (until the
// package has actually been put in the loaded package list.)
build: function () {
var self = this;
if (self.pluginsBuilt || self.slicesBuilt)