forked from meteor/meteor
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpackage-source.js
More file actions
1672 lines (1482 loc) · 63 KB
/
package-source.js
File metadata and controls
1672 lines (1482 loc) · 63 KB
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 fs = require('fs');
var path = require('path');
var _ = require('underscore');
var semver = require('semver');
var sourcemap = require('source-map');
var files = require('./files.js');
var utils = require('./utils.js');
var watch = require('./watch.js');
var buildmessage = require('./buildmessage.js');
var meteorNpm = require('./meteor-npm.js');
var Builder = require('./builder.js');
var archinfo = require('./archinfo.js');
var release = require('./release.js');
var catalog = require('./catalog.js');
var semver = require('semver');
// XXX: This is a medium-term hack, to avoid having the user set a package name
// & test-name in package.describe. We will change this in the new control file
// world in some way.
var AUTO_TEST_PREFIX = "local-test:";
var isTestName = function (name) {
var nameStart = name.slice(0, AUTO_TEST_PREFIX.length);
return nameStart === AUTO_TEST_PREFIX;
};
var genTestName = function (name) {
return AUTO_TEST_PREFIX + name;
};
// Given a semver version string, return the earliest semver for which
// we are a replacement. This is used to compute the default
// earliestCompatibleVersion.
// XXX: move to utils?
var earliestCompatible = function (version) {
// This is not the place to check to see if version parses as
// semver. That should have been done when we first received it from
// the user.
var parsed = semver.parse(version);
if (! parsed)
throw new Error("not a valid version: " + version);
return parsed.major + ".0.0";
};
// Returns a sort comparator to order files into load order.
// templateExtensions should be a list of extensions like 'html'
// which should be loaded before other extensions.
var loadOrderSort = function (templateExtensions) {
var templateExtnames = {};
_.each(templateExtensions, function (extension) {
templateExtnames['.' + extension] = true;
});
return function (a, b) {
// XXX MODERATELY SIZED HACK --
// push template files ahead of everything else. this is
// important because the user wants to be able to say
// Template.foo.events = { ... }
// in a JS file and not have to worry about ordering it
// before the corresponding .html file.
//
// maybe all of the templates should go in one file?
var isTemplate_a = _.has(templateExtnames, path.extname(a));
var isTemplate_b = _.has(templateExtnames, path.extname(b));
if (isTemplate_a !== isTemplate_b) {
return (isTemplate_a ? -1 : 1);
}
// main.* loaded last
var ismain_a = (path.basename(a).indexOf('main.') === 0);
var ismain_b = (path.basename(b).indexOf('main.') === 0);
if (ismain_a !== ismain_b) {
return (ismain_a ? 1 : -1);
}
// /lib/ loaded first
var islib_a = (a.indexOf(path.sep + 'lib' + path.sep) !== -1 ||
a.indexOf('lib' + path.sep) === 0);
var islib_b = (b.indexOf(path.sep + 'lib' + path.sep) !== -1 ||
b.indexOf('lib' + path.sep) === 0);
if (islib_a !== islib_b) {
return (islib_a ? -1 : 1);
}
// deeper paths loaded first.
var len_a = a.split(path.sep).length;
var len_b = b.split(path.sep).length;
if (len_a !== len_b) {
return (len_a < len_b ? 1 : -1);
}
// otherwise alphabetical
return (a < b ? -1 : 1);
};
};
// We currently have a 1 to 1 mapping between 'where' and 'arch'.
// 'client' -> 'web'
// 'server' -> 'os'
// '*' -> '*'
var mapWhereToArch = function (where) {
if (where === 'server') {
return 'os';
} else if (where === 'client') {
return 'web';
} else {
return where;
}
};
///////////////////////////////////////////////////////////////////////////////
// SourceArch
///////////////////////////////////////////////////////////////////////////////
// Options:
// - name [required]
// - arch [required]
// - uses
// - implies
// - getSourcesFunc
// - declaredExports
// - watchSet
//
// Do not include the source files in watchSet. They will be
// added at compile time when the sources are actually read.
var SourceArch = function (pkg, options) {
var self = this;
options = options || {};
self.pkg = pkg;
// Name for this sourceArchitecture. At the moment, there are really two
// options -- main and plugin. We use these in linking
self.archName = options.name;
// The architecture (fully or partially qualified) that can use this
// unibuild.
self.arch = options.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
// - constraint: the constraint on the version of the package to use,
// as a string (may be null)
// - 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, instead of using 'uses' directly, you want to use
// something like compiler.eachUsedUnibuild so you also take into
// account implied packages.
self.uses = options.uses || [];
// Packages which are "implied" by using this package. If a unibuild X
// uses this unibuild 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 architecture. 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;
// Symbols that this architecture should export. List of symbols (as
// strings).
self.declaredExports = options.declaredExports || null;
// Files and directories that we want to monitor for changes in
// development mode, as a watch.WatchSet. In the latest refactoring
// of the code, this does not include source files or directories,
// but only control files such as package.js and .meteor/packages,
// since the rest are not determined until compile time.
self.watchSet = options.watchSet || new watch.WatchSet;
// See the field of the same name in PackageSource.
self.noSources = false;
};
///////////////////////////////////////////////////////////////////////////////
// PackageSource
///////////////////////////////////////////////////////////////////////////////
var PackageSource = function (catalog) {
var self = this;
// Which catalog this PackageSource works with.
if (!catalog)
throw Error("Must provide catalog");
self.catalog = catalog;
// 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).
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-web 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).
self.serveRoot = null;
// Package metadata. Keys are 'summary' and 'git'. Currently all of these are
// optional.
self.metadata = {};
// Package version as a semver string. Optional; not all packages
// (for example, the app) have versions.
// XXX when we have names, maybe we want to say that all packages
// with names have versions? certainly the reverse is true
self.version = null;
// The earliest version for which this package is supposed to be a
// compatible replacement. Set if and only if version is set.
self.earliestCompatibleVersion = null;
// Available architectures of this package. Array of SourceArch.
self.architectures = [];
// 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 = {};
// Analogous to watchSet in SourceArch but for plugins. At this
// stage will typically contain just 'package.js'.
self.pluginWatchSet = new watch.WatchSet;
// npm packages used by this package (on os.* architectures only).
// Map from npm package name to the required version of the package
// as a string.
self.npmDependencies = {};
// Absolute path to a directory on disk that serves as a cache for
// the npm dependencies, so we don't have to fetch them on every
// build. Required not just if we have npmDependencies, but if we
// ever could have had them in the past.
self.npmCacheDirectory = null;
// cordova plugins used by this package (on os.* architectures only).
// Map from cordova plugin name to the required version of the package
// as a string.
self.cordovaDependencies = {};
// Dependency versions that we used last time that we built this package. If
// the constraint solver thinks that they are still a valid set of
// dependencies, we will use them again to build this package. This makes
// building packages slightly more efficient and ensures repeatable builds.
self.dependencyVersions = {dependencies: {}, pluginDependencies: {}};
// If this package has a corresponding test package (for example,
// underscore-test), defined in the same package.js file, store its value
// here.
self.testName = null;
// Test packages are dealt with differently in the linker (and not published
// to the catalog), so we need to keep track of them.
self.isTest = false;
// If this is set, we will take the currently running git checkout and bundle
// the meteor tool from it inside this package as a tool. We will include
// built unipackages for all the packages in uniload.ROOT_PACKAGES as well as
// their transitive (strong) dependencies.
self.includeTool = false;
// If this is true, then this package has no source files. (But the converse
// is not true: this is only set to true by one particular constructor.) This
// is specifically so that a few pieces of code can detect the wrapper "load"
// package that uniload uses and not do extra work that doesn't make sense in
// the uniload context.
self.noSources = false;
// If this is true, the package source comes from the package server, and
// should be treated as immutable. The only reason that we have it is so we
// can build it, and we should expect to use exactly the same inputs
// (package.js and version lock file) as we did when it was created. If we
// ever need to modify it, we should throw instead.
self.immutable = false;
// Is this a core package? Core packages don't record version files, because
// core packages are only ever run from checkout. For the preview release,
// core packages do not need to specify their versions at publication (since
// there isn't likely to be any exciting version skew yet), but we will
// specify the correct restrictions at 0.90.
// XXX: 0.90 package versions.
self.isCore = false;
// Alternatively, we can also specify noVersionFile directly. Useful for not
// recording version files for js images of plugins, since those go into the
// overall package versions file (if one exists). In the future, we can make
// this option transparent to the user in package.js.
self.noVersionFile = false;
// The list of archs that we can target. Doesn't include 'web' because
// it is expanded into 'web.*'.
self.allArchs = ['os', 'web.browser', 'web.cordova'];
};
_.extend(PackageSource.prototype, {
// Make a dummy (empty) packageSource that contains nothing of interest.
// XXX: Do we need this
initEmpty: function (name) {
var self = this;
self.name = name;
},
// Programmatically initialize a PackageSource from scratch.
//
// Unlike user-facing methods of creating a package
// (initFromPackageDir, initFromAppDir) this does not implicitly add
// a dependency on the 'meteor' package. If you want such a
// dependency then you must add it yourself.
//
// If called inside a buildmessage job, it will keep going if things
// go wrong. Be sure to call jobHasMessages to see if it actually
// succeeded.
//
// The architecture is hardcoded to be "os".
//
// Note that this does not set a version on the package!
//
// Options:
// - sourceRoot (required if sources present)
// - serveRoot (required if sources present)
// - use
// - sources (array of paths or relPath/fileOptions objects)
// - npmDependencies
// - cordovaDependencies
// - npmDir
// - dependencyVersions
initFromOptions: function (name, options) {
var self = this;
self.name = name;
if (options.sources && ! _.isEmpty(options.sources) &&
(! options.sourceRoot || ! options.serveRoot))
throw new Error("When source files are given, sourceRoot and " +
"serveRoot must be specified");
self.sourceRoot = options.sourceRoot || path.sep;
self.serveRoot = options.serveRoot || path.sep;
var nodeModulesPath = null;
utils.ensureOnlyExactVersions(options.npmDependencies);
self.npmDependencies = options.npmDependencies;
self.npmCacheDirectory = options.npmDir;
utils.ensureOnlyExactVersions(options.cordovaDependencies);
self.cordovaDependencies = options.cordovaDependencies;
var sources = _.map(options.sources, function (source) {
if (typeof source === "string")
return {relPath: source};
return source;
});
var sourceArch = new SourceArch(self, {
name: options.archName,
arch: "os",
uses: _.map(options.use, utils.splitConstraint),
getSourcesFunc: function () { return sources; },
nodeModulesPath: nodeModulesPath
});
if (!sources.length) {
self.noSources = true;
sourceArch.noSources = true;
}
self.architectures.push(sourceArch);
if (! self._checkCrossUnibuildVersionConstraints())
throw new Error("only one unibuild, so how can consistency check fail?");
self.dependencyVersions = options.dependencyVersions ||
{dependencies: {}, pluginDependencies: {}};
self.noVersionFile = options.noVersionFile;
},
// Initialize a PackageSource from a package.js-style package directory. Uses
// the name field provided and the name/test fields in the package.js file to
// figre out if this is a test package (load from on_test) or a use package
// (load from on_use).
//
// name: name of the package.
// dir: location of directory on disk.
// options:
// -requireVersion: This is a package that is going in a catalog or being
// published to the server. It must have a version. (as opposed to, for
// example, a program)
// -defaultVersion: The default version if none is specified. Only assigned
// if the version is required.
// -immutable: This package source is immutable. Do not write anything,
// including version files. Instead, its only purpose is to be used as
// guideline for a repeatable build.
// -name: override the name of this package with a different name.
initFromPackageDir: function (dir, options) {
var self = this;
buildmessage.assertInCapture();
var isPortable = true;
options = options || {};
// If we know what package we are initializing, we pass in a
// name. Otherwise, we are intializing the base package specified by 'name:'
// field in Package.Describe. In that case, it is clearly not a test
// package. (Though we could be initializing a specific package without it
// being a test, for a variety of reasons).
if (options.name) {
self.isTest = isTestName(options.name);
self.name = options.name;
}
self.sourceRoot = dir;
// If we are running from checkout we may be looking at a core package. If
// we are, let's remember this for things like not recording version files.
if (files.inCheckout()) {
var packDir = path.join(files.getCurrentToolsDir(), 'packages');
if (path.dirname(self.sourceRoot) === packDir) {
self.isCore = true;
}
}
if (! fs.existsSync(self.sourceRoot))
throw new Error("putative package directory " + dir + " doesn't exist?");
var fileAndDepLoader = null;
var npmDependencies = null;
var cordovaDependencies = null;
var packageJsPath = path.join(self.sourceRoot, 'package.js');
var code = fs.readFileSync(packageJsPath);
var packageJsHash = Builder.sha1(code);
var releaseRecord = null;
var hasTests = false;
// Any package that depends on us needs to be rebuilt if our package.js file
// changes, because a change to package.js might add or remove a plugin,
// which could change a file from being handled by extension vs treated as
// an asset.
self.pluginWatchSet.addFile(packageJsPath, packageJsHash);
// == 'Package' object visible in package.js ==
var Package = {
// Set package metadata. Options:
// - summary: for 'meteor list' & package server
// - version: package version string (semver)
// - earliestCompatibleVersion: version string
// There used to be a third option documented here,
// 'environments', but it was never implemented and no package
// ever used it.
describe: function (options) {
_.each(options, function (value, key) {
if (key === "summary" ||
key === "git") {
self.metadata[key] = value;
} else if (key === "version") {
// XXX validate that version parses -- and that it doesn't
// contain a +!
self.version = value;
} else if (key === "earliestCompatibleVersion") {
self.earliestCompatibleVersion = value;
} else if (key === "name" && !self.isTest) {
if (!self.name) {
self.name = value;
} else if (self.name !== value) {
// Woah, so we requested a non-test package by name, and it is not
// the name that we find inside. That's super weird.
buildmessage.error(
"trying to initialize a nonexistent base package " + value);
}
}
else {
// Do nothing. We might want to add some keys later, and we should err on
// the side of backwards compatibility.
}
});
},
onUse: function (f) {
if (!self.isTest) {
if (fileAndDepLoader) {
buildmessage.error("duplicate onUse handler; a package may have " +
"only one", { useMyCaller: true });
// Recover by ignoring the duplicate
return;
}
fileAndDepLoader = f;
}
},
// Backwards compatibility for old interfaces.
on_use: function (f) {
this.onUse(f);
},
onTest: function (f) {
// If we are not initializing the test package, then we are initializing
// the normal package and have now noticed that it has tests. So, let's
// register the test. This is a medium-length hack until we have new
// control files.
if (!self.isTest) {
hasTests = true;
return;
}
// We are initializing the test, so proceed as normal.
if (self.isTest) {
if (fileAndDepLoader) {
buildmessage.error("duplicate onTest handler; a package may have " +
"only one", { useMyCaller: true });
// Recover by ignoring the duplicate
return;
}
fileAndDepLoader = f;
}
},
// Backwards compatibility for old interfaces.
on_test: function (f) {
this.onTest(f);
},
// Define a plugin. A plugin extends the build process for
// targets that use this package. For example, a Coffeescript
// compiler would be a plugin. A plugin is its own little
// program, with its own set of source files, used packages, and
// npm dependencies.
//
// This is an experimental API and for now you should assume
// that it will change frequently and radically (thus the
// '_transitional_'). For maximum R&D velocity and for the good
// of the platform, we will push changes that break your
// packages that use this API. You've been warned.
//
// Options:
// - name: a name for this plugin. required (cosmetic -- string)
// - use: package to use for the plugin (names, as strings)
// - sources: sources for the plugin (array of string)
// - npmDependencies: map from npm package name to required
// version (string)
_transitional_registerBuildPlugin: function (options) {
// Tests don't have plugins; plugins initialized in the control file
// belong to the package and not to the test. (This will be less
// confusing in the new control file format).
if (self.isTest) {
return;
}
if (! ('name' in options)) {
buildmessage.error("build plugins require a name",
{ useMyCaller: true });
// recover by ignoring plugin
return;
}
if (options.name in self.pluginInfo) {
buildmessage.error("this package already has a plugin named '" +
options.name + "'",
{ useMyCaller: true });
// recover by ignoring plugin
return;
}
if (options.name.match(/\.\./) || options.name.match(/[\\\/]/)) {
buildmessage.error("bad plugin name", { useMyCaller: true });
// recover by ignoring plugin
return;
}
// XXX probably want further type checking
self.pluginInfo[options.name] = options;
},
includeTool: function () {
if (!files.inCheckout()) {
buildmessage.error("Package.includeTool() can only be used with a " +
"checkout of meteor");
} else if (self.includeTool) {
buildmessage.error("Duplicate includeTool call");
} else {
self.includeTool = true;
}
}
};
// == 'Npm' object visible in package.js ==
var Npm = {
depends: function (_npmDependencies) {
// XXX make npmDependencies be separate between use and test, so that
// production doesn't have to ship all of the npm modules used by test
// code
if (npmDependencies) {
buildmessage.error("Npm.depends may only be called once per package",
{ useMyCaller: true });
// recover by ignoring the Npm.depends line
return;
}
if (typeof _npmDependencies !== 'object') {
buildmessage.error("the argument to Npm.depends should be an " +
"object, like this: {gcd: '0.0.0'}",
{ useMyCaller: true });
// recover by ignoring the Npm.depends line
return;
}
// don't allow npm fuzzy versions so that there is complete
// consistency when deploying a meteor app
//
// XXX use something like seal or lockdown to have *complete*
// confidence we're running the same code?
try {
utils.ensureOnlyExactVersions(_npmDependencies);
} catch (e) {
buildmessage.error(e.message, { useMyCaller: true, downcase: true });
// recover by ignoring the Npm.depends line
return;
}
npmDependencies = _npmDependencies;
},
require: function (name) {
var nodeModuleDir = path.join(self.sourceRoot,
'.npm', 'package', 'node_modules', name);
if (fs.existsSync(nodeModuleDir)) {
return require(nodeModuleDir);
} else {
try {
return require(name); // from the dev bundle
} catch (e) {
buildmessage.error("can't find npm module '" + name +
"'. Did you forget to call 'Npm.depends'?",
{ useMyCaller: true });
// recover by, uh, returning undefined, which is likely to
// have some knock-on effects
return undefined;
}
}
}
};
// == 'Cordova' object visible in package.js ==
var Cordova = {
depends: function (_cordovaDependencies) {
// XXX make cordovaDependencies be separate between use and test, so that
// production doesn't have to ship all of the npm modules used by test
// code
if (cordovaDependencies) {
buildmessage.error("Cordova.depends may only be called once per package",
{ useMyCaller: true });
// recover by ignoring the Cordova.depends line
return;
}
if (typeof _cordovaDependencies !== 'object') {
buildmessage.error("the argument to Cordova.depends should be an " +
"object, like this: {gcd: '0.0.0'}",
{ useMyCaller: true });
// recover by ignoring the Cordova.depends line
return;
}
// don't allow cordova fuzzy versions so that there is complete
// consistency when deploying a meteor app
//
// XXX use something like seal or lockdown to have *complete*
// confidence we're running the same code?
try {
utils.ensureOnlyExactVersions(_cordovaDependencies);
} catch (e) {
buildmessage.error(e.message, { useMyCaller: true, downcase: true });
// recover by ignoring the Npm.depends line
return;
}
cordovaDependencies = _cordovaDependencies;
},
};
try {
files.runJavaScript(code.toString('utf8'), {
filename: 'package.js',
symbols: { Package: Package, Npm: Npm, Cordova: Cordova }
});
} catch (e) {
console.log(e.stack); // XXX should we keep this here -- or do we want broken
// packages to fail silently?
buildmessage.exception(e);
// Could be a syntax error or an exception. Recover by
// continuing as if package.js is empty. (Pressing on with
// whatever handlers were registered before the exception turns
// out to feel pretty disconcerting -- definitely violates the
// principle of least surprise.) Leave the metadata if we have
// it, though.
fileAndDepLoader = null;
self.pluginInfo = {};
npmDependencies = null;
cordovaDependencies = null;
}
// In the past, we did not require a Package.Describe.name field. So, it is
// possible that we are initializing a package that doesn't use it and
// expects us to be implicit about it.
if (!self.name) {
// For backwards-compatibility, we will take the package name from the
// directory of the package. That was what we used to do: in fact, we used
// to only do that.
self.name = path.basename(dir);
}
// Check to see if our name is valid.
try {
utils.validatePackageName(self.name);
} catch (e) {
if (!e.versionParserError)
throw e;
buildmessage.error(e.message);
// recover by ignoring
}
if (self.version === null && options.requireVersion) {
if (options.defaultVersion) {
self.version = options.defaultVersion;
} else if (! buildmessage.jobHasMessages()) {
// Only write the error if there have been no errors so
// far. (Otherwise if there is a parse error we'll always get
// this message, because we won't have been able to run any
// code.)
buildmessage.error("A version must be specified for the package. " +
"Set it with Package.describe.");
}
// Recover by leaving the version unset. This is sort of
// unfortunate (it means that whereever we work with Package
// objects, we need to consider the possibility that their
// version is not set) but short of failing the build we have no
// alternative. Using a dummy version like "1.0.0" would cause
// endless confusion and a fake version like "unknown" wouldn't
// parse as semver. Anyway, apps don't have versions, so it's
// not like we didn't already have to think about this case.
}
if (self.version !== null && typeof(self.version) !== "string") {
if (!buildmessage.jobHasMessages()) {
buildmessage.error("The package version (specified with "
+ "Package.describe) must be a string.");
}
// Recover by pretending there was no version (see above).
self.version = null;
}
if (self.version !== null) {
var parsedVersion = semver.parse(self.version);
if (!parsedVersion) {
if (!buildmessage.jobHasMessages()) {
buildmessage.error(
"The package version (specified with Package.describe) must be "
+ "valid semver (see http://semver.org/).");
}
// Recover by pretending there was no version (see above).
self.version = null;
} else if (parsedVersion.build.length) {
if (!buildmessage.jobHasMessages()) {
buildmessage.error(
"The package version (specified with Package.describe) may not "
+ "contain a plus-separated build ID.");
}
// Recover by pretending there was no version (see above).
self.version = null;
}
}
if (self.version !== null && ! self.earliestCompatibleVersion) {
self.earliestCompatibleVersion =
earliestCompatible(self.version);
}
// source files used
var sources = {};
// symbols exported
var exports = {};
// packages used and implied (keys are 'package', 'unordered', and
// 'weak'). an "implied" package is a package that will be used by a unibuild
// which uses us.
var uses = {};
var implies = {};
_.each(self.allArchs, function (arch) {
sources[arch] = [];
exports[arch] = [];
uses[arch] = [];
implies[arch] = [];
});
// Iterates over the list of target archs and calls f(arch) for all archs
// that match an element of self.allarchs.
var forAllMatchingArchs = function (archs, f) {
_.each(archs, function (arch) {
_.each(self.allArchs, function (matchArch) {
if (archinfo.matches(matchArch, arch)) {
f(matchArch);
}
});
});
};
// For this old-style, on_use/on_test/where-based package, figure
// out its dependencies by calling its on_xxx functions and seeing
// what it does.
//
// We have a simple strategy. Call its on_xxx handler with no
// 'where', which is what happens when the package is added
// directly to an app, and see what files it adds to the client
// and the server. When a package is used, include it in both the client
// and the server by default. This simple strategy doesn't capture even
// 10% of the complexity possible with on_use, on_test, and where, but
// probably is sufficient for virtually all packages that actually
// exist in the field, if not every single one. #OldStylePackageSupport
if (fileAndDepLoader) {
var toArray = function (x) {
if (x instanceof Array)
return x;
return x ? [x] : [];
};
var toArchArray = function (arch) {
if (!(arch instanceof Array)) {
arch = arch ? [arch] : self.allArchs;
}
arch = _.uniq(arch);
arch = _.map(arch, mapWhereToArch);
_.each(arch, function (inputArch) {
var isMatch = _.any(_.map(self.allArchs, function (actualArch) {
return archinfo.matches(actualArch, inputArch);
}));
if (! isMatch) {
buildmessage.error(
"Invalid 'where' argument: '" + inputArch + "'",
// skip toArchArray in addition to the actual API function
{useMyCaller: 2});
}
});
return arch;
};
var api = {
// Called when this package wants to make another package be
// used. Can also take literal package objects, if you have
// anonymous packages you want to use (eg, app packages)
//
// @param arch 'web', 'web.browser', 'web.cordova', 'server',
// or an array of those.
// The default is ['web', 'server'].
//
// options can include:
//
// - unordered: if true, don't require this package to load
// before us -- just require it to be loaded anytime. Also
// don't bring this package's imports into our
// namespace. If false, override a true value specified in
// a previous call to use for this package name. (A
// limitation of the current implementation is that this
// flag is not tracked per-environment or per-role.) This
// option can be used to resolve circular dependencies in
// exceptional circumstances, eg, the 'meteor' package
// depends on 'handlebars', but all packages (including
// 'handlebars') have an implicit dependency on
// 'meteor'. Internal use only -- future support of this
// is not guaranteed. #UnorderedPackageReferences
//
// - weak: if true, don't require this package to load at all, but if
// it's going to load, load it before us. Don't bring this
// package's imports into our namespace and don't allow us to use
// its plugins. (Has the same limitation as "unordered" that this
// flag is not tracked per-environment or per-role; this may
// change.)
use: function (names, arch, options) {
// Support `api.use(package, {weak: true})` without arch.
if (_.isObject(arch) && !_.isArray(arch) && !options) {
options = arch;
arch = null;
}
options = options || {};
names = toArray(names);
arch = toArchArray(arch);
// A normal dependency creates an ordering constraint and a "if I'm
// used, use that" constraint. Unordered dependencies lack the
// former; weak dependencies lack the latter. There's no point to a
// dependency that lacks both!
if (options.unordered && options.weak) {
buildmessage.error(
"A dependency may not be both unordered and weak.",
{ useMyCaller: true });
// recover by ignoring
return;
}
// using for loop rather than underscore to help with useMyCaller
for (var i = 0; i < names.length; ++i) {
var name = names[i];
try {
var parsed = utils.parseConstraint(name);
} catch (e) {
if (!e.versionParserError)
throw e;
buildmessage.error(e.message, {useMyCaller: true});
// recover by ignoring
continue;
}
forAllMatchingArchs(arch, function (a) {
uses[a].push({
package: parsed.name,
constraint: parsed.constraintString,
unordered: options.unordered || false,
weak: options.weak || false
});
});
}
},
// Called when this package wants packages using it to also use
// another package. eg, for umbrella packages which want packages
// using them to also get symbols or plugins from their components.
imply: function (names, arch) {
names = toArray(names);
arch = toArchArray(arch);
// using for loop rather than underscore to help with useMyCaller
for (var i = 0; i < names.length; ++i) {
var name = names[i];
try {
var parsed = utils.parseConstraint(name);
} catch (e) {
if (!e.versionParserError)
throw e;
buildmessage.error(e.message, {useMyCaller: true});
// recover by ignoring
continue;
}
forAllMatchingArchs(arch, function (a) {
// We don't allow weak or unordered implies, since the main
// purpose of imply is to provide imports and plugins.
implies[a].push({
package: parsed.name,
constraint: parsed.constraintString
});
});
}
},
// Top-level call to add a source file to a package. It will
// be processed according to its extension (eg, *.coffee
// files will be compiled to JavaScript).
addFiles: function (paths, arch, fileOptions) {
paths = toArray(paths);
arch = toArchArray(arch);
_.each(paths, function (path) {
forAllMatchingArchs(arch, function (a) {
var source = {relPath: path};
if (fileOptions)
source.fileOptions = fileOptions;
sources[a].push(source);
});