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
1893 lines (1682 loc) · 67.3 KB
/
package-source.js
File metadata and controls
1893 lines (1682 loc) · 67.3 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 _ = require('underscore');
var sourcemap = require('source-map');
var files = require('../fs/files.js');
var utils = require('../utils/utils.js');
var watch = require('../fs/watch.js');
var buildmessage = require('../utils/buildmessage.js');
var meteorNpm = require('./meteor-npm.js');
var NpmDiscards = require('./npm-discards.js');
import Builder from './builder.js';
var archinfo = require('../utils/archinfo.js');
var catalog = require('../packaging/catalog/catalog.js');
var packageVersionParser = require('../packaging/package-version-parser.js');
var compiler = require('./compiler.js');
var packageAPIModule = require('./package-api.js');
var Profile = require('../tool-env/profile.js').Profile;
import SourceArch from './source-arch.js';
import {
TEST_FILENAME_REGEXPS,
APP_TEST_FILENAME_REGEXPS,
isTestFilePath } from './test-files.js';
// 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;
};
// Returns a sort comparator to order files into load order.
var loadOrderSort = function (sourceProcessorSet, arch) {
const isTemplate = _.memoize((filename) => {
const classification = sourceProcessorSet.classifyFilename(filename, arch);
switch (classification.type) {
case 'extension':
case 'filename':
if (! classification.sourceProcessors) {
// This is *.js, not a template. #HardcodeJs
return false;
}
if (classification.sourceProcessors.length > 1) {
throw Error("conflicts in compiler?");
}
return classification.sourceProcessors[0].isTemplate;
case 'legacy-handler':
return classification.legacyIsTemplate;
case 'wrong-arch':
case 'unmatched':
return false;
default:
throw Error(`surprising type ${classification.type} for ${filename}`);
}
});
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 = isTemplate(files.pathBasename(a));
var isTemplate_b = isTemplate(files.pathBasename(b));
if (isTemplate_a !== isTemplate_b) {
return (isTemplate_a ? -1 : 1);
}
// main.* loaded last
var ismain_a = (files.pathBasename(a).indexOf('main.') === 0);
var ismain_b = (files.pathBasename(b).indexOf('main.') === 0);
if (ismain_a !== ismain_b) {
return (ismain_a ? 1 : -1);
}
// /lib/ loaded first
var islib_a = (a.indexOf(files.pathSep + 'lib' + files.pathSep) !== -1 ||
a.indexOf('lib' + files.pathSep) === 0);
var islib_b = (b.indexOf(files.pathSep + 'lib' + files.pathSep) !== -1 ||
b.indexOf('lib' + files.pathSep) === 0);
if (islib_a !== islib_b) {
return (islib_a ? -1 : 1);
}
var a_parts = a.split(files.pathSep);
var b_parts = b.split(files.pathSep);
// deeper paths loaded first.
var len_a = a_parts.length;
var len_b = b_parts.length;
if (len_a < len_b) {
return 1;
}
if (len_b < len_a) {
return -1;
}
// Otherwise compare path components lexicographically.
for (var i = 0; i < len_a; ++i) {
var a_part = a_parts[i];
var b_part = b_parts[i];
if (a_part < b_part) {
return -1;
}
if (b_part < a_part) {
return 1;
}
}
// Never reached unless there are somehow duplicate paths.
return 0;
};
};
var splitConstraint = function (c) {
// XXX print error better (w/ buildmessage?)?
var parsed = utils.parsePackageConstraint(c);
return { package: parsed.package,
constraint: parsed.constraintString || null };
};
// Given the text of a README.md file, excerpts the text between the first and
// second heading.
//
// Specifically - if there is text between the document name, and the first
// subheading, it will take that text. If there is no text there, and only text
// after the first subheading, it will take that text. It won't look any deeper
// than that (in case the user intentionally wants to leave the section blank
// for some reason). Skips lines that start with an exclamation point.
var getExcerptFromReadme = function (text) {
// Don't waste time parsing if the document is empty.
if (! text) {
return "";
}
// Split into lines with Commonmark.
var commonmark = require('commonmark');
var reader = new commonmark.DocParser();
var parsed = reader.parse(text);
// Commonmark will parse the Markdown into an array of nodes. These are the
// nodes that represent the text between the first and second heading.
var relevantNodes = [];
// Go through the document until we get the nodes that we are looking for,
// then stop.
_.any(parsed.children, function (child) {
var isHeader = (child.t === "Header");
// Don't excerpt anything before the first header.
if (! isHeader) {
// If we are currently in the middle of excerpting, continue doing that
// until we hit hit a header (and this is not a header). Otherwise, if
// this is text, we should begin to excerpt it.
relevantNodes.push(child);
} else if (! _.isEmpty(relevantNodes) && isHeader) {
// We have been excerpting, and came across a header. That means
// that we are done.
return true;
}
return false;
});
// If we have not found anything, we are done.
if (_.isEmpty(relevantNodes)) {
return "";
}
// For now, we will do the simple thing of just taking the raw markdown from
// the start of the excerpt to the end.
var textLines = text.split("\n");
var start = relevantNodes[0].start_line - 1;
var stop = _.last(relevantNodes).end_line;
// XXX: There is a bug in commonmark that happens when processing the last
// node in the document. Here is the github issue:
// https://github.com/jgm/CommonMark/issues/276
// Remove this workaround when the issue is fixed.
if (stop === _.last(parsed.children).end_line) {
stop++;
}
var excerpt = textLines.slice(start, stop).join("\n");
// Strip the preceeding and trailing new lines.
return excerpt.replace(/^\n+|\n+$/g, "");
};
class SymlinkLoopChecker {
constructor(sourceRoot) {
this.sourceRoot = sourceRoot;
this._seenPaths = {};
this._realpathCache = {};
}
check(relDir, quietly = true) {
const absPath = files.pathJoin(this.sourceRoot, relDir);
try {
var realPath = files.realpath(absPath, this._realpathCache);
} catch (e) {
if (!e || e.code !== 'ELOOP') {
throw e;
}
// else leave realPath undefined
}
if (! realPath || _.has(this._seenPaths, realPath)) {
if (! quietly) {
buildmessage.error("Symlink cycle detected at " + relDir);
}
return true;
}
this._seenPaths[realPath] = true;
return false;
}
}
///////////////////////////////////////////////////////////////////////////////
// PackageSource
///////////////////////////////////////////////////////////////////////////////
var PackageSource = function () {
var self = this;
// 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', 'git' and 'documentation'. Currently
// all of these are optional.
self.metadata = {};
self.docsExplicitlyProvided = false;
// Package version as a meteor-version 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;
self.versionExplicitlyProvided = false;
// 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 = {};
// Files to be stripped from the installed NPM dependency tree. See the
// Npm.strip comment below for further usage information.
self.npmDiscards = new NpmDiscards;
// 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 = {};
// 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;
// Some packages belong to a test framework and should never be bundled into
// production. A package with this flag should not be picked up by the bundler
// for production builds.
self.debugOnly = false;
// A package marked prodOnly is ONLY picked up by the bundler for production
// builds.
self.prodOnly = false;
// A package marked testOnly is ONLY picked up by the bundler as
// part of the `meteor test` command.
self.testOnly = 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 copies of all known isopackets.
self.includeTool = 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;
};
_.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), note that this
// doesn't support assets at this time. If you want to pass assets here, you
// should add a new option to this function called `assets`.
// - npmDependencies
// - cordovaDependencies
// - npmDir
// - localNodeModulesDirs
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");
}
// sourceRoot is a relative file system path, one slash identifies a root
// relative to some starting location
self.sourceRoot = options.sourceRoot || files.pathSep;
// serveRoot is actually a part of a url path, root here is a forward slash
self.serveRoot = options.serveRoot || '/';
utils.ensureOnlyValidVersions(options.npmDependencies, {forCordova: false});
self.npmDependencies = options.npmDependencies;
self.npmCacheDirectory = options.npmDir;
utils.ensureOnlyValidVersions(options.cordovaDependencies, {forCordova: true});
self.cordovaDependencies = options.cordovaDependencies;
const sources = options.sources.map((source) => {
if (typeof source === "string") {
return {
relPath: source
};
}
return source;
});
const sourceArch = new SourceArch(self, {
kind: options.kind,
arch: "os",
sourceRoot: self.sourceRoot,
uses: _.map(options.use, splitConstraint),
getFiles() {
return {
sources: sources
}
}
});
if (options.localNodeModulesDirs) {
_.extend(sourceArch.localNodeModulesDirs,
options.localNodeModulesDirs);
}
self.architectures.push(sourceArch);
if (! self._checkCrossUnibuildVersionConstraints()) {
throw new Error("only one unibuild, so how can consistency check fail?");
}
},
// 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 onTest) or a use package
// (load from onUse).
//
// name: name of the package.
// dir: location of directory on disk.
// options:
// - name: override the name of this package with a different name.
// - buildingIsopackets: true if this is being scanned in the process
// of building isopackets
initFromPackageDir: function (dir, options) {
var self = this;
buildmessage.assertInCapture();
var isPortable = true;
options = options || {};
var initFromPackageDirOptions = 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;
}
// Give the package a default version. We do not set
// versionExplicitlyProvided unless the package configuration file actually
// sets a version.
self.version = "0.0.0";
// To make the transition to using README.md files in Isobuild easier, we
// initialize the documentation directory to README.md by default.
self.metadata.documentation = "README.md";
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 = files.pathJoin(files.getCurrentToolsDir(), 'packages');
if (files.pathDirname(self.sourceRoot) === packDir) {
self.isCore = true;
}
}
if (! files.exists(self.sourceRoot)) {
throw new Error("putative package directory " + dir + " doesn't exist?");
}
var fileAndDepLoader = null;
var npmDependencies = null;
var cordovaDependencies = null;
var packageJsPath = files.pathJoin(self.sourceRoot, 'package.js');
var code = files.readFile(packageJsPath);
var packageJsHash = watch.sha1(code);
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 plugin vs treated as
// an asset.
self.pluginWatchSet.addFile(packageJsPath, packageJsHash);
// == 'Package' object visible in package.js ==
/**
* @global
* @name Package
* @summary The Package object in package.js
* @namespace
* @locus package.js
*/
var Package = {
// Set package metadata. Options:
// - summary: for 'meteor list' & package server
// - version: package version string
// There used to be a third option documented here,
// 'environments', but it was never implemented and no package
// ever used it.
/**
* @summary Provide basic package information.
* @locus package.js
* @memberOf Package
* @param {Object} options
* @param {String} options.summary A concise 1-2 sentence description of
* the package, required for publication.
* @param {String} options.version The (extended)
* [semver](http://www.semver.org) version for your package. Additionally,
* Meteor allows a wrap number: a positive integer that follows the
* version number. If you are porting another package that uses semver
* versioning, you may want to use the original version, postfixed with
* `_wrapnumber`. For example, `1.2.3_1` or `2.4.5-rc1_4`. Wrap numbers
* sort after the original numbers: `1.2.3` < `1.2.3_1` < `1.2.3_2` <
* `1.2.4-rc.0`. If no version is specified, this field defaults to
* `0.0.0`. If you want to publish your package to the package server, you
* must specify a version.
* @param {String} options.name Optional name override. By default, the
* package name comes from the name of its directory.
* @param {String} options.git Optional Git URL to the source repository.
* @param {String} options.documentation Optional Filepath to
* documentation. Set to 'README.md' by default. Set this to null to submit
* no documentation.
* @param {Boolean} options.debugOnly A package with this flag set to true
* will not be bundled into production builds. This is useful for packages
* meant to be used in development only.
* @param {Boolean} options.prodOnly A package with this flag set to true
* will ONLY be bundled into production builds.
* @param {Boolean} options.testOnly A package with this flag set to true
* will ONLY be bundled as part of `meteor test`.
*/
describe: function (options) {
_.each(options, function (value, key) {
if (key === "summary" ||
key === "git") {
self.metadata[key] = value;
} else if (key === "documentation") {
self.metadata[key] = value;
self.docsExplicitlyProvided = true;
} else if (key === "version") {
if (typeof(value) !== "string") {
buildmessage.error("The package version (specified with "
+ "Package.describe) must be a string.");
// Recover by pretending that version was not set.
} else {
var goodVersion = true;
try {
var parsedVersion = packageVersionParser.getValidServerVersion(
value);
} catch (e) {
if (!e.versionParserError) {
throw e;
}
buildmessage.error(
"The package version " + value + " (specified with Package.describe) "
+ "is not a valid Meteor package version.\n"
+ "Valid package versions are semver (see http://semver.org/), "
+ "optionally followed by '_' and an integer greater or equal to 1.");
goodVersion = false;
}
// Recover by pretending that the version was not set.
}
if (goodVersion && parsedVersion !== value) {
buildmessage.error(
"The package version (specified with Package.describe) may not "
+ "contain a plus-separated build ID.");
// Recover by pretending that the version was not set.
goodVersion = false;
}
if (goodVersion) {
self.version = value;
self.versionExplicitlyProvided = true;
}
} 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);
}
// `debugOnly`, `prodOnly` and `testOnly` are boolean
// flags you can put on a package, currently undocumented.
// when set to true, they cause a package's code to be
// only included (i.e. linked into the bundle) in dev
// mode, prod mode (`meteor --production`) or app tests
// (`meteor test`), and excluded otherwise.
//
// Notes:
//
// * These flags do not affect which packages or which versions are
// are selected by the version solver.
//
// * When you use a debugOnly, prodOnly or testOnly
// package, its exports are not imported for you. You
// have to access them using
// `Package["my-package"].MySymbol`.
//
// * These flags CAN cause different package load orders in
// development and production! We should probably fix this.
// Basically, packages that are excluded from the build using
// these flags are also excluded fro the build order calculation,
// and that's the problem
//
// * We should consider publicly documenting these flags, since they
// are effectively part of the public API.
} else if (key === "debugOnly") {
self.debugOnly = !!value;
} else if (key === "prodOnly") {
self.prodOnly = !!value;
} else if (key === "testOnly") {
self.testOnly = !!value;
} else {
// Do nothing. We might want to add some keys later, and we should err
// on the side of backwards compatibility.
}
if (_.size(_.compact([self.debugOnly, self.prodOnly, self.testOnly])) > 1) {
buildmessage.error(
"Package can't have more than one of: debugOnly, prodOnly, testOnly.");
}
});
},
/**
* @summary Define package dependencies and expose package methods.
* @locus package.js
* @memberOf Package
* @param {Function} func A function that takes in the package control `api` object, which keeps track of dependencies and exports.
*/
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;
}
},
/**
* @deprecated in 0.9.0
*/
on_use: function (f) {
this.onUse(f);
},
/**
* @summary Define dependencies and expose package methods for unit tests.
* @locus package.js
* @memberOf Package
* @param {Function} func A function that takes in the package control 'api' object, which keeps track of dependencies and exports.
*/
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;
}
},
/**
* @deprecated in 0.9.0
*/
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)
/**
* @summary Define a build plugin. A build plugin extends the build
* process for apps and packages that use this package. For example,
* the `coffeescript` package uses a build plugin to compile CoffeeScript
* source files into JavaScript.
* @param {Object} [options]
* @param {String} options.name A cosmetic name, must be unique in the
* package.
* @param {String|String[]} options.use Meteor packages that this
* plugin uses, independent of the packages specified in
* [api.onUse](#pack_onUse).
* @param {String[]} options.sources The source files that make up the
* build plugin, independent from [api.addFiles](#pack_addFiles).
* @param {Object} options.npmDependencies An object where the keys
* are NPM package names, and the values are the version numbers of
* required NPM packages, just like in [Npm.depends](#Npm-depends).
* @memberOf Package
* @locus package.js
*/
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;
},
/**
* @deprecated in 0.9.4
*/
_transitional_registerBuildPlugin: function (options) {
this.registerBuildPlugin(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 ==
/**
* @namespace Npm
* @global
* @summary The Npm object in package.js and package source files.
*/
var Npm = {
/**
* @summary Specify which [NPM](https://www.npmjs.org/) packages
* your Meteor package depends on.
* @param {Object} dependencies An object where the keys are package
* names and the values are one of:
* 1. Version numbers in string form
* 2. Http(s) URLs to a git commit by SHA.
* 3. Git URLs in the format described [here](https://docs.npmjs.com/files/package.json#git-urls-as-dependencies)
*
* Https URL example:
*
* ```js
* Npm.depends({
* moment: "2.8.3",
* async: "https://github.com/caolan/async/archive/71fa2638973dafd8761fa5457c472a312cc820fe.tar.gz"
* });
* ```
*
* Git URL example:
*
* ```js
* Npm.depends({
* moment: "2.8.3",
* async: "git+https://github.com/caolan/async#master"
* });
* ```
* @locus package.js
* @memberOf 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.ensureOnlyValidVersions(_npmDependencies, {forCordova: false});
} catch (e) {
buildmessage.error(e.message, { useMyCaller: true, downcase: true });
// recover by ignoring the Npm.depends line
return;
}
npmDependencies = _npmDependencies;
},
// The `Npm.strip` method makes up for packages that have missing
// or incomplete .npmignore files by telling the bundler to strip out
// certain unnecessary files and/or directories during `meteor build`.
//
// The `discards` parameter should be an object whose keys are
// top-level package names and whose values are arrays of strings
// (or regular expressions) that match paths in that package's
// directory that should be stripped before installation. For
// example:
//
// Npm.strip({
// connect: [/*\.wmv$/],
// useragent: ["tests/"]
// });
//
// This means (1) "remove any files with the `.wmv` extension from
// the 'connect' package directory" and (2) "remove the 'tests'
// directory from the 'useragent' package directory."
strip: function(discards) {
self.npmDiscards.merge(discards);
},
require: function (name) {
try {
return require(name); // from the dev bundle
} catch (e) {
buildmessage.error(
"can't find npm module '" + name +
"'. In package.js, Npm.require can only find built-in modules.",
{ useMyCaller: true });
// recover by, uh, returning undefined, which is likely to
// have some knock-on effects
return undefined;
}
}
};
// == 'Cordova' object visible in package.js ==
/**
* @namespace Cordova
* @global
* @summary The Cordova object in package.js.
*/
var Cordova = {
/**
* @summary Specify which [Cordova / PhoneGap](http://cordova.apache.org/)
* plugins your Meteor package depends on.
*
* Plugins are installed from
* [plugins.cordova.io](http://plugins.cordova.io/), so the plugins and
* versions specified must exist there. Alternatively, the version
* can be replaced with a GitHub tarball URL as described in the
* [Cordova](https://github.com/meteor/meteor/wiki/Meteor-Cordova-integration#meteor-packages-with-cordova-dependencies)
* page of the Meteor wiki on GitHub.
* @param {Object} dependencies An object where the keys are plugin
* names and the values are version numbers or GitHub tarball URLs
* in string form.
* Example:
*
* ```js
* Cordova.depends({
* "org.apache.cordova.camera": "0.3.0"
* });
* ```
*
* Alternatively, with a GitHub URL:
*
* ```js
* Cordova.depends({
* "org.apache.cordova.camera":
* "https://github.com/apache/cordova-plugin-camera/tarball/d84b875c449d68937520a1b352e09f6d39044fbf"
* });
* ```
*
* @locus package.js
* @memberOf 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.ensureOnlyValidVersions(_cordovaDependencies, {forCordova: true});
} 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) {
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 = files.pathBasename(dir);
}
// Check to see if our name is valid.