-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathember-app.js
1912 lines (1635 loc) · 55.1 KB
/
ember-app.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
/* global require, module */
'use strict';
/**
@module ember-cli
*/
const fs = require('fs');
const path = require('path');
const p = require('ember-cli-preprocess-registry/preprocessors');
const chalk = require('chalk');
const resolve = require('resolve');
const Project = require('../models/project');
const SilentError = require('silent-error');
let preprocessJs = p.preprocessJs;
let isType = p.isType;
let preprocessTemplates = p.preprocessTemplates;
const concat = require('broccoli-concat');
const BroccoliDebug = require('broccoli-debug');
const ModuleNormalizer = require('broccoli-module-normalizer');
const AmdFunnel = require('broccoli-amd-funnel');
const ConfigReplace = require('broccoli-config-replace');
const mergeTrees = require('./merge-trees');
const WatchedDir = require('broccoli-source').WatchedDir;
const UnwatchedDir = require('broccoli-source').UnwatchedDir;
const BroccoliMergeTrees = require('broccoli-merge-trees');
const merge = require('ember-cli-lodash-subset').merge;
const defaultsDeep = require('ember-cli-lodash-subset').defaultsDeep;
const omitBy = require('ember-cli-lodash-subset').omitBy;
const isNull = require('ember-cli-lodash-subset').isNull;
const Funnel = require('broccoli-funnel');
const logger = require('heimdalljs-logger')('ember-cli:ember-app');
const emberAppUtils = require('../utilities/ember-app-utils');
const addonProcessTree = require('../utilities/addon-process-tree');
const lintAddonsByType = require('../utilities/lint-addons-by-type');
const emberCLIBabelConfigKey = require('../utilities/ember-cli-babel-config-key');
const { isExperimentEnabled } = require('../experiments');
const semver = require('semver');
const DefaultPackager = require('./default-packager');
const configReplacePatterns = emberAppUtils.configReplacePatterns;
let DEFAULT_CONFIG = {
storeConfigInMeta: true,
autoRun: true,
outputPaths: {
app: {
html: 'index.html',
},
tests: {
js: '/assets/tests.js',
},
vendor: {
css: '/assets/vendor.css',
js: '/assets/vendor.js',
},
testSupport: {
css: '/assets/test-support.css',
js: {
testSupport: '/assets/test-support.js',
testLoader: '/assets/test-loader.js',
},
},
},
minifyCSS: {
options: { relativeTo: 'assets' },
},
sourcemaps: {},
trees: {},
jshintrc: {},
addons: {},
};
class EmberApp {
/**
EmberApp is the main class Ember CLI uses to manage the Broccoli trees
for your application. It is very tightly integrated with Broccoli and has
a `toTree()` method you can use to get the entire tree for your application.
Available init options:
- storeConfigInMeta, defaults to `true`
- autoRun, defaults to `true`
- outputPaths, defaults to `{}`
- minifyCSS, defaults to `{enabled: !!isProduction,options: { relativeTo: 'assets' }}
- minifyJS, defaults to `{enabled: !!isProduction}
- sourcemaps, defaults to `{}`
- trees, defaults to `{}`
- jshintrc, defaults to `{}`
- vendorFiles, defaults to `{}`
- addons, defaults to `{ blacklist: [], whitelist: [] }`
@class EmberApp
@constructor
@param {Object} [defaults]
@param {Object} [options={}] Configuration options
*/
constructor(defaults, options) {
if (arguments.length === 0) {
options = {};
} else if (arguments.length === 1) {
options = defaults;
} else {
defaultsDeep(options, defaults);
}
this._initProject(options);
this.name = options.name || this.project.name();
this.env = EmberApp.env();
this.isProduction = this.env === 'production';
this.registry = options.registry || p.defaultRegistry(this);
this.bowerDirectory = this.project.bowerDirectory;
this._initTestsAndHinting(options);
this._initOptions(options);
this._initVendorFiles();
this._styleOutputFiles = {};
// ensure addon.css always gets concated
this._styleOutputFiles[this.options.outputPaths.vendor.css] = [];
this._scriptOutputFiles = {};
this._customTransformsMap = new Map();
this.otherAssetPaths = [];
this.legacyTestFilesToAppend = [];
this.vendorTestStaticStyles = [];
this._nodeModules = new Map();
this.trees = this.options.trees;
this.populateLegacyFiles();
this.initializeAddons();
this.project.addons.forEach(addon => (addon.app = this));
p.setupRegistry(this);
this._importAddonTransforms();
this._notifyAddonIncluded();
if (!this._addonInstalled('loader.js') && !this.options._ignoreMissingLoader) {
throw new SilentError('The loader.js addon is missing from your project, please add it to `package.json`.');
}
this._debugTree = BroccoliDebug.buildDebugCallback('ember-app');
this._defaultPackager = new DefaultPackager({
env: this.env,
name: this.name,
autoRun: this.options.autoRun,
project: this.project,
registry: this.registry,
sourcemaps: this.options.sourcemaps,
minifyCSS: this.options.minifyCSS,
areTestsEnabled: this.tests,
styleOutputFiles: this._styleOutputFiles,
scriptOutputFiles: this._scriptOutputFiles,
storeConfigInMeta: this.options.storeConfigInMeta,
customTransformsMap: this._customTransformsMap,
additionalAssetPaths: this.otherAssetPaths,
vendorTestStaticStyles: this.vendorTestStaticStyles,
legacyTestFilesToAppend: this.legacyTestFilesToAppend,
isModuleUnificationEnabled: isExperimentEnabled('MODULE_UNIFICATION') && !!this.trees.src,
distPaths: {
appJsFile: this.options.outputPaths.app.js,
appCssFile: this.options.outputPaths.app.css,
testJsFile: this.options.outputPaths.tests.js,
appHtmlFile: this.options.outputPaths.app.html,
vendorJsFile: this.options.outputPaths.vendor.js,
vendorCssFile: this.options.outputPaths.vendor.css,
testSupportJsFile: this.options.outputPaths.testSupport.js,
testSupportCssFile: this.options.outputPaths.testSupport.css,
},
});
this._isPackageHookSupplied = typeof this.options.package === 'function';
this._cachedAddonBundles = {};
}
/**
Initializes the `tests` and `hinting` properties.
Defaults to `false` unless `ember test` was used or this is *not* a production build.
@private
@method _initTestsAndHinting
@param {Object} options
*/
_initTestsAndHinting(options) {
let testsEnabledDefault = process.env.EMBER_CLI_TEST_COMMAND || !this.isProduction;
this.tests = options.hasOwnProperty('tests') ? options.tests : testsEnabledDefault;
this.hinting = options.hasOwnProperty('hinting') ? options.hinting : testsEnabledDefault;
}
/**
Initializes the `project` property from `options.project` or the
closest Ember CLI project from the current working directory.
@private
@method _initProject
@param {Object} options
*/
_initProject(options) {
let app = this;
this.project = options.project || Project.closestSync(process.cwd());
if (options.configPath) {
this.project.configPath = function() {
return app._resolveLocal(options.configPath);
};
}
}
/**
Initializes the `options` property from the `options` parameter and
a set of default values from Ember CLI.
@private
@method _initOptions
@param {Object} options
*/
_initOptions(options) {
let resolvePathFor = (defaultPath, specified) => {
let path = defaultPath;
if (specified && typeof specified === 'string') {
path = specified;
}
let resolvedPath = this._resolveLocal(path);
return resolvedPath;
};
let buildTreeFor = (defaultPath, specified, shouldWatch) => {
if (specified !== null && specified !== undefined && typeof specified !== 'string') {
return specified;
}
let tree = null;
let resolvedPath = resolvePathFor(defaultPath, specified);
if (fs.existsSync(resolvedPath)) {
if (shouldWatch !== false) {
tree = new WatchedDir(resolvedPath);
} else {
tree = new UnwatchedDir(resolvedPath);
}
}
return tree;
};
let trees = (options && options.trees) || {};
let srcTree = buildTreeFor('src', trees.src);
let appTree = buildTreeFor('app', trees.app);
let testsPath = typeof trees.tests === 'string' ? resolvePathFor('tests', trees.tests) : null;
let testsTree = buildTreeFor('tests', trees.tests, options.tests);
// these are contained within app/ no need to watch again
// (we should probably have the builder or the watcher dedup though)
if (isExperimentEnabled('MODULE_UNIFICATION')) {
let srcStylesPath = `${resolvePathFor('src', trees.src)}/ui/styles`;
this._stylesPath = fs.existsSync(srcStylesPath) ? srcStylesPath : resolvePathFor('app/styles', trees.styles);
} else {
this._stylesPath = resolvePathFor('app/styles', trees.styles);
}
let stylesTree = null;
if (fs.existsSync(this._stylesPath)) {
stylesTree = new UnwatchedDir(this._stylesPath);
}
let templatesTree = buildTreeFor('app/templates', trees.templates, false);
// do not watch bower's default directory by default
let bowerTree = buildTreeFor(this.bowerDirectory, null, !!this.project._watchmanInfo.enabled);
// Set the flag to make sure:
//
// - we do not blow up if there is no bower_components folder
// - we do not attempt to merge bower and vendor together if they are the
// same tree
this._bowerEnabled = this.bowerDirectory !== 'vendor' && fs.existsSync(this.bowerDirectory);
let vendorTree = buildTreeFor('vendor', trees.vendor);
let publicTree = buildTreeFor('public', trees.public);
let detectedDefaultOptions = {
babel: {},
jshintrc: {
app: this.project.root,
tests: testsPath,
},
minifyCSS: {
enabled: this.isProduction,
options: { processImport: false },
},
minifyJS: {
enabled: this.isProduction,
options: {
compress: {
// this is adversely affects heuristics for IIFE eval
// eslint-disable-next-line camelcase
negate_iife: false,
// limit sequences because of memory issues during parsing
sequences: 30,
},
output: {
// no difference in size and much easier to debug
semicolons: false,
},
},
},
outputPaths: {
app: {
css: {
app: `/assets/${this.name}.css`,
},
js: `/assets/${this.name}.js`,
},
},
sourcemaps: {
enabled: !this.isProduction,
extensions: ['js'],
},
trees: {
src: srcTree,
app: appTree,
tests: testsTree,
styles: stylesTree,
templates: templatesTree,
bower: bowerTree,
vendor: vendorTree,
public: publicTree,
},
};
let emberCLIBabelInstance = this.project.findAddonByName('ember-cli-babel');
if (emberCLIBabelInstance) {
let version = this.project.require('ember-cli-babel/package.json').version;
if (semver.lt(version, '6.0.0-alpha.1')) {
detectedDefaultOptions.babel = {
modules: 'amdStrict',
moduleIds: true,
resolveModuleSource: require('amd-name-resolver').moduleResolve,
};
}
let emberCLIBabelConfigKey = this._emberCLIBabelConfigKey();
detectedDefaultOptions[emberCLIBabelConfigKey] = detectedDefaultOptions[emberCLIBabelConfigKey] || {};
detectedDefaultOptions[emberCLIBabelConfigKey].compileModules = true;
}
this.options = defaultsDeep(options, detectedDefaultOptions, DEFAULT_CONFIG);
// For now we must disable Babel sourcemaps due to unforeseen
// performance regressions.
if (!('sourceMaps' in this.options.babel)) {
this.options.babel.sourceMaps = false;
}
// Add testem.js to excludes for broccoli-asset-rev.
// This will allow tests to run against the production builds.
this.options.fingerprint = this.options.fingerprint || {};
this.options.fingerprint.exclude = this.options.fingerprint.exclude || [];
this.options.fingerprint.exclude.push('testem');
}
_emberCLIBabelConfigKey() {
let emberCLIBabelInstance = this.project.findAddonByName('ember-cli-babel');
return emberCLIBabelConfigKey(emberCLIBabelInstance);
}
/**
Resolves a path relative to the project's root
@private
@method _resolveLocal
*/
_resolveLocal(to) {
return path.join(this.project.root, to);
}
/**
@private
@method _initVendorFiles
*/
_initVendorFiles() {
let bowerDeps = this.project.bowerDependencies();
let ember = this.project.findAddonByName('ember-source');
let addonEmberCliShims = this.project.findAddonByName('ember-cli-shims');
let bowerEmberCliShims = bowerDeps['ember-cli-shims'];
let developmentEmber;
let productionEmber;
let emberTesting;
let emberShims = null;
if (ember) {
developmentEmber = ember.paths.debug;
productionEmber = ember.paths.prod;
emberTesting = ember.paths.testing;
emberShims = ember.paths.shims;
} else {
if (bowerEmberCliShims) {
emberShims = `${this.bowerDirectory}/ember-cli-shims/app-shims.js`;
}
// in Ember 1.10 and higher `ember.js` is deprecated in favor of
// the more aptly named `ember.debug.js`.
productionEmber = `${this.bowerDirectory}/ember/ember.prod.js`;
developmentEmber = `${this.bowerDirectory}/ember/ember.debug.js`;
if (!fs.existsSync(this._resolveLocal(developmentEmber))) {
developmentEmber = `${this.bowerDirectory}/ember/ember.js`;
}
emberTesting = `${this.bowerDirectory}/ember/ember-testing.js`;
}
let handlebarsVendorFiles;
if ('handlebars' in bowerDeps) {
handlebarsVendorFiles = {
development: `${this.bowerDirectory}/handlebars/handlebars.js`,
production: `${this.bowerDirectory}/handlebars/handlebars.runtime.js`,
};
} else {
handlebarsVendorFiles = null;
}
this.vendorFiles = omitBy(
merge(
{
'handlebars.js': handlebarsVendorFiles,
'ember.js': {
development: developmentEmber,
production: productionEmber,
},
'ember-testing.js': [emberTesting, { type: 'test' }],
'app-shims.js': emberShims,
'ember-resolver.js': [
`${this.bowerDirectory}/ember-resolver/dist/modules/ember-resolver.js`,
{
exports: {
'ember/resolver': ['default'],
},
},
],
},
this.options.vendorFiles
),
isNull
);
this._addJqueryInLegacyEmber();
if (this._addonInstalled('ember-resolver') || !bowerDeps['ember-resolver']) {
// if the project is using `ember-resolver` as an addon
// remove it from `vendorFiles` (the npm version properly works
// without `app.import`s)
delete this.vendorFiles['ember-resolver.js'];
}
// Warn if ember-cli-shims is not included.
// certain versions of `ember-source` bundle them by default,
// so we must check if that is the load mechanism of ember
// before checking `bower`.
let emberCliShimsRequired = this._checkEmberCliBabel(this.project.addons);
if (!emberShims && !addonEmberCliShims && !bowerEmberCliShims && emberCliShimsRequired) {
this.project.ui.writeWarnLine(
"You have not included `ember-cli-shims` in your project's `bower.json` or `package.json`. This only works if you provide an alternative yourself and unset `app.vendorFiles['app-shims.js']`."
);
}
// If ember-testing.js is coming from Bower (not ember-source) and it does not
// exist, then we remove it from vendor files. This is needed to support versions
// of Ember older than 1.8.0 (when ember-testing.js was incldued in ember.js itself)
if (!ember && this.vendorFiles['ember-testing.js'] && !fs.existsSync(this.vendorFiles['ember-testing.js'][0])) {
delete this.vendorFiles['ember-testing.js'];
}
}
_addJqueryInLegacyEmber() {
if (this.project.findAddonByName('@ember/jquery')) {
return;
}
let ember = this.project.findAddonByName('ember-source');
let jqueryPath;
if (ember) {
let optionFeatures = this.project.findAddonByName('@ember/optional-features');
if (optionFeatures && !optionFeatures.isFeatureEnabled('jquery-integration')) {
return;
}
this.project.ui.writeDeprecateLine(
'The integration of jQuery into Ember has been deprecated and will be removed with Ember 4.0. You can either' +
' opt-out of using jQuery, or install the `@ember/jquery` addon to provide the jQuery integration. Please' +
' consult the deprecation guide for further details: https://emberjs.com/deprecations/v3.x#toc_jquery-apis'
);
jqueryPath = ember.paths.jquery;
} else {
jqueryPath = `${this.bowerDirectory}/jquery/dist/jquery.js`;
}
this.vendorFiles = merge({ 'jquery.js': jqueryPath }, this.vendorFiles);
}
/**
Returns the environment name
@public
@static
@method env
@return {String} Environment name
*/
static env() {
return process.env.EMBER_ENV || 'development';
}
/**
Delegates to `broccoli-concat` with the `sourceMapConfig` option set to `options.sourcemaps`.
@private
@method _concatFiles
@param tree
@param options
@return
*/
_concatFiles(tree, options) {
options.sourceMapConfig = this.options.sourcemaps;
return concat(tree, options);
}
/**
Checks the result of `addon.isEnabled()` if it exists, defaults to `true` otherwise.
@private
@method _addonEnabled
@param {Addon} addon
@return {Boolean}
*/
_addonEnabled(addon) {
return !addon.isEnabled || addon.isEnabled();
}
/**
@private
@method _addonDisabledByBlacklist
@param {Addon} addon
@return {Boolean}
*/
_addonDisabledByBlacklist(addon) {
let blacklist = this.options.addons.blacklist;
return !!blacklist && blacklist.indexOf(addon.name) !== -1;
}
/**
@private
@method _addonDisabledByWhitelist
@param {Addon} addon
@return {Boolean}
*/
_addonDisabledByWhitelist(addon) {
let whitelist = this.options.addons.whitelist;
return !!whitelist && whitelist.indexOf(addon.name) === -1;
}
/**
@private
@method _checkEmberCliBabel
@param {Addons} addons
@return {Boolean}
*/
_checkEmberCliBabel(addons, result, roots) {
addons = addons || [];
result = result || false;
roots = roots || {};
let babelInstance = addons.find(addon => addon.name === 'ember-cli-babel');
if (babelInstance) {
let version = babelInstance.pkg.version;
if (semver.lt(version, '6.6.0')) {
result = true;
}
if (semver.lt(version, '6.0.0') && !roots[babelInstance.root]) {
roots[babelInstance.root] = true;
this.project.ui.writeDeprecateLine(
`ember-cli-babel 5.x has been deprecated. Please upgrade to at least ember-cli-babel 6.6. Version ${version} located: ${
babelInstance.root
}`
);
}
}
return addons.some(addon => this._checkEmberCliBabel(addon.addons, result, roots)) || result;
}
/**
Returns whether an addon should be added to the project
@private
@method shouldIncludeAddon
@param {Addon} addon
@return {Boolean}
*/
shouldIncludeAddon(addon) {
if (!this._addonEnabled(addon)) {
return false;
}
return !this._addonDisabledByBlacklist(addon) && !this._addonDisabledByWhitelist(addon);
}
/**
Calls the included hook on addons.
@private
@method _notifyAddonIncluded
*/
_notifyAddonIncluded() {
let addonNames = this.project.addons.map(addon => addon.name);
if (this.options.addons.blacklist) {
this.options.addons.blacklist.forEach(addonName => {
if (addonNames.indexOf(addonName) === -1) {
throw new Error(`Addon "${addonName}" defined in blacklist is not found`);
}
});
}
if (this.options.addons.whitelist) {
this.options.addons.whitelist.forEach(addonName => {
if (addonNames.indexOf(addonName) === -1) {
throw new Error(`Addon "${addonName}" defined in whitelist is not found`);
}
});
}
// the addons must be filtered before the `included` hook is called
// in case an addon caches the project.addons list
this.project.addons = this.project.addons.filter(addon => this.shouldIncludeAddon(addon));
this.project.addons.forEach(addon => {
if (addon.included) {
addon.included(this);
}
});
}
/**
Calls the importTransforms hook on addons.
@private
@method _importAddonTransforms
*/
_importAddonTransforms() {
this.project.addons.forEach(addon => {
if (this.shouldIncludeAddon(addon)) {
if (addon.importTransforms) {
let transforms = addon.importTransforms();
if (!transforms) {
throw new Error(`Addon "${addon.name}" did not return a transform map from importTransforms function`);
}
Object.keys(transforms).forEach(transformName => {
let transformConfig = {
files: [],
options: {},
};
// store the transform info
if (typeof transforms[transformName] === 'object') {
transformConfig['callback'] = transforms[transformName].transform;
transformConfig['processOptions'] = transforms[transformName].processOptions;
} else if (typeof transforms[transformName] === 'function') {
transformConfig['callback'] = transforms[transformName];
transformConfig['processOptions'] = (assetPath, entry, options) => options;
} else {
throw new Error(
`Addon "${addon.name}" did not return a callback function correctly for transform "${transformName}".`
);
}
if (this._customTransformsMap.has(transformName)) {
// there is already a transform with a same name, therefore we warn the user
this.project.ui.writeWarnLine(
`Addon "${
addon.name
}" is defining a transform name: ${transformName} that is already being defined. Using transform from addon: "${
addon.name
}".`
);
}
this._customTransformsMap.set(transformName, transformConfig);
});
}
}
});
}
/**
Loads and initializes addons for this project.
Calls initializeAddons on the Project.
@private
@method initializeAddons
*/
initializeAddons() {
this.project.initializeAddons();
}
_addonTreesFor(type) {
return this.project.addons.reduce((sum, addon) => {
if (addon.treeFor) {
let tree = addon.treeFor(type);
if (tree && !mergeTrees.isEmptyTree(tree)) {
sum.push({
name: addon.name,
tree,
root: addon.root,
});
}
}
return sum;
}, []);
}
/**
Returns a list of trees for a given type, returned by all addons.
@private
@method addonTreesFor
@param {String} type Type of tree
@return {Array} List of trees
*/
addonTreesFor(type) {
return this._addonTreesFor(type).map(addonBundle => addonBundle.tree);
}
_getDefaultPluginForType(type) {
let plugins = this.registry.load(type);
let defaultsForType = plugins.filter(plugin => plugin.isDefaultForType);
if (defaultsForType.length > 1) {
throw new Error(
`There are multiple preprocessor plugins marked as default for '${type}': ${defaultsForType
.map(p => p.name)
.join(', ')}`
);
}
return defaultsForType[0];
}
_compileAddonTemplates(tree) {
let defaultPluginForType = this._getDefaultPluginForType('template');
let options = {
annotation: `_compileAddonTemplates`,
registry: this.registry,
};
if (defaultPluginForType) {
tree = defaultPluginForType.toTree(tree, options);
} else {
tree = preprocessTemplates(tree, options);
}
return tree;
}
_compileAddonJs(tree) {
let defaultPluginForType = this._getDefaultPluginForType('js');
let options = {
annotation: '_compileAddonJs',
registry: this.registry,
};
if (defaultPluginForType) {
tree = defaultPluginForType.toTree(tree, options);
} else {
tree = preprocessJs(tree, '/', '/', options);
}
return tree;
}
_compileAddonTree(tree, skipTemplates) {
if (!skipTemplates) {
tree = this._compileAddonTemplates(tree);
}
tree = this._compileAddonJs(tree);
return tree;
}
_precompileAppJsTree(tree) {
let emberCLIBabelConfigKey = this._emberCLIBabelConfigKey();
let original = this.options[emberCLIBabelConfigKey];
// the app will handle transpilation after it tree-shakes
// do it here instead of the constructor because
// ember-data and others do their own compilation in their
// treeForAddon without calling super
// they need the original params preserved because they call
// babel themselves and expect compilation the old way
this.options[emberCLIBabelConfigKey] = Object.assign({}, original, {
compileModules: false,
disablePresetEnv: true,
disableDebugTooling: true,
disableEmberModulesAPIPolyfill: true,
});
tree = preprocessJs(tree, '/', '/', {
annotation: `_precompileAppJsTree`,
registry: this.registry,
});
// return the original params because there are multiple
// entrances to preprocessJs
this.options[emberCLIBabelConfigKey] = original;
return tree;
}
/**
Runs addon post-processing on a given tree and returns the processed tree.
This enables addons to do process immediately **after** the preprocessor for a
given type is run, but before concatenation occurs. If an addon wishes to
apply a transform before the preprocessors run, they can instead implement the
preprocessTree hook.
To utilize this addons implement `postprocessTree` hook.
An example, would be to apply some broccoli transform on all JS files, but
only after the existing pre-processors have run.
```js
module.exports = {
name: 'my-cool-addon',
postprocessTree(type, tree) {
if (type === 'js') {
return someBroccoliTransform(tree);
}
return tree;
}
}
```
@private
@method addonPostprocessTree
@param {String} type Type of tree
@param {Tree} tree Tree to process
@return {Tree} Processed tree
*/
addonPostprocessTree(type, tree) {
return addonProcessTree(this.project, 'postprocessTree', type, tree);
}
/**
Runs addon pre-processing on a given tree and returns the processed tree.
This enables addons to do process immediately **before** the preprocessor for a
given type is run. If an addon wishes to apply a transform after the
preprocessors run, they can instead implement the postprocessTree hook.
To utilize this addons implement `preprocessTree` hook.
An example, would be to remove some set of files before the preprocessors run.
```js
var stew = require('broccoli-stew');
module.exports = {
name: 'my-cool-addon',
preprocessTree(type, tree) {
if (type === 'js' && type === 'template') {
return stew.rm(tree, someGlobPattern);
}
return tree;
}
}
```
@private
@method addonPreprocessTree
@param {String} type Type of tree
@param {Tree} tree Tree to process
@return {Tree} Processed tree
*/
addonPreprocessTree(type, tree) {
return addonProcessTree(this.project, 'preprocessTree', type, tree);
}
/**
Runs addon lintTree hooks and returns a single tree containing all
their output.
@private
@method addonLintTree
@param {String} type Type of tree
@param {Tree} tree Tree to process
@return {Tree} Processed tree
*/
addonLintTree(type, tree) {
let output = lintAddonsByType(this.project.addons, type, tree);
return mergeTrees(output, {
overwrite: true,
annotation: `TreeMerger (lint ${type})`,
});
}
/**
Imports legacy imports in this.vendorFiles
@private
@method populateLegacyFiles
*/
populateLegacyFiles() {
let name;
for (name in this.vendorFiles) {
let args = this.vendorFiles[name];
if (args === null) {
continue;
}
this.import.apply(this, [].concat(args));
}
}
podTemplates() {
return new Funnel(this.trees.app, {
include: this._podTemplatePatterns(),
exclude: ['templates/**/*'],
destDir: this.name,
annotation: 'Funnel: Pod Templates',
});
}
_templatesTree() {
if (!this._cachedTemplateTree) {
let trees = [];
if (this.trees.templates) {
let standardTemplates = new Funnel(this.trees.templates, {
srcDir: '/',
destDir: `${this.name}/templates`,
annotation: 'Funnel: Templates',
});
trees.push(standardTemplates);
}
if (this.trees.app) {
trees.push(this.podTemplates());
}
this._cachedTemplateTree = mergeTrees(trees, {
annotation: 'TreeMerge (templates)',
});
}
return this._cachedTemplateTree;
}
/**
Returns the tree for /tests/index.html
@private
@method testIndex
@return {Tree} Tree for /tests/index.html
*/
testIndex() {
let index = new Funnel(this.trees.tests, {
srcDir: '/',
files: ['index.html'],
destDir: '/tests',
annotation: 'Funnel (test index)',
});
let patterns = configReplacePatterns({
addons: this.project.addons,
autoRun: this.options.autoRun,
storeConfigInMeta: this.options.storeConfigInMeta,
isModuleUnification: isExperimentEnabled('MODULE_UNIFICATION') && !!this.trees.src,
});
return new ConfigReplace(index, this._defaultPackager.packageConfig(this.tests), {
configPath: path.join(this.name, 'config', 'environments', 'test.json'),