forked from ampproject/amphtml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gulpfile.js
1770 lines (1638 loc) · 56.1 KB
/
gulpfile.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
/**
* Copyright 2017 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* global require, process */
checkMinVersion();
const $$ = require('gulp-load-plugins')();
const babelify = require('babelify');
const browserify = require('browserify');
const buffer = require('vinyl-buffer');
const colors = require('ansi-colors');
const fs = require('fs-extra');
const gulp = $$.help(require('gulp'));
const lazypipe = require('lazypipe');
const log = require('fancy-log');
const minimatch = require('minimatch');
const minimist = require('minimist');
const path = require('path');
const rimraf = require('rimraf');
const source = require('vinyl-source-stream');
const touch = require('touch');
const watchify = require('watchify');
const wrappers = require('./build-system/compile-wrappers');
const {applyConfig, removeConfig} = require('./build-system/tasks/prepend-global/index.js');
const {cleanupBuildDir, closureCompile} = require('./build-system/tasks/compile');
const {createCtrlcHandler, exitCtrlcHandler} = require('./build-system/ctrlcHandler');
const {createModuleCompatibleES5Bundle} = require('./build-system/tasks/create-module-compatible-es5-bundle');
const {extensionBundles, aliasBundles} = require('./bundles.config');
const {jsifyCssAsync} = require('./build-system/tasks/jsify-css');
const {serve} = require('./build-system/tasks/serve.js');
const {transpileTs} = require('./build-system/typescript');
const {VERSION: internalRuntimeVersion} = require('./build-system/internal-version') ;
const argv = minimist(
process.argv.slice(2), {boolean: ['strictBabelTransform']});
require('./build-system/tasks');
const hostname = argv.hostname || 'cdn.ampproject.org';
const hostname3p = argv.hostname3p || '3p.ampproject.net';
// All declared extensions.
const extensions = {};
const extensionAliasFilePath = {};
// All extensions to build
let extensionsToBuild = null;
// All a4a extensions.
const adVendors = [];
const {green, red, cyan} = colors;
// Minified targets to which AMP_CONFIG must be written.
const minifiedRuntimeTarget = 'dist/v0.js';
const minifiedShadowRuntimeTarget = 'dist/shadow-v0.js';
const minifiedAdsTarget = 'dist/amp4ads-v0.js';
// TODO(#18934, erwinm): temporary fix.
//const minifiedRuntimeEsmTarget = 'dist/v0-esm.js';
const minified3pTarget = 'dist.3p/current-min/f.js';
// Unminified targets to which AMP_CONFIG must be written.
const unminifiedRuntimeTarget = 'dist/amp.js';
const unminifiedShadowRuntimeTarget = 'dist/amp-shadow.js';
const unminifiedAdsTarget = 'dist/amp-inabox.js';
const unminifiedRuntimeEsmTarget = 'dist/amp-esm.js';
const unminified3pTarget = 'dist.3p/current/integration.js';
const maybeUpdatePackages = process.env.TRAVIS ? [] : ['update-packages'];
extensionBundles.forEach(c => declareExtension(c.name, c.version, c.options));
aliasBundles.forEach(c => {
declareExtensionVersionAlias(c.name, c.version, c.latestVersion, c.options);
});
/**
* Tasks that should print the `--nobuild` help text.
* @private @const {!Set<string>}
*/
const NOBUILD_HELP_TASKS = new Set(['test', 'visual-diff']);
/**
* Extensions to build when `--extensions=minimal_set`.
* @private @const {!Array<string>}
*/
const MINIMAL_EXTENSION_SET = [
'amp-ad',
'amp-ad-network-adsense-impl',
'amp-analytics',
'amp-audio',
'amp-image-lightbox',
'amp-lightbox',
'amp-sidebar',
'amp-video',
];
/**
* Extensions that require `amp-video-service` to be built alongside them.
* @private @const {!Set<string>}
*/
// TODO(alanorozco): Determine dynamically?
const VIDEO_EXTENSIONS = new Set([
'amp-3q-player',
'amp-brid-player',
'amp-dailymotion',
'amp-delight-player',
'amp-gfycat',
'amp-ima-video',
'amp-nexxtv-player',
'amp-ooyala-player',
'amp-video',
'amp-wistia-player',
'amp-youtube',
]);
/**
* @typedef {{
* name: ?string,
* version: ?string,
* hasCss: ?boolean,
* loadPriority: ?string,
* cssBinaries: ?Array<string>,
* extraGlobs?Array<string>,
* bundleOnlyIfListedInFiles: ?boolean
* }}
*/
const ExtensionOption = {}; // eslint-disable-line no-unused-vars
/**
* @param {string} name
* @param {string|!Array<string>} version E.g. 0.1
* @param {!ExtensionOption} options extension options object.
*/
function declareExtension(name, version, options) {
const defaultOptions = {hasCss: false};
const versions = Array.isArray(version) ? version : [version];
versions.forEach(v => {
extensions[`${name}-${v}`] =
Object.assign({name, version: v}, defaultOptions, options);
});
if (name.startsWith('amp-ad-network-')) {
// Get the ad network name. All ad network extensions are named
// in the format `amp-ad-network-${name}-impl`
name = name.slice(15, -5);
adVendors.push(name);
}
}
/**
* This function is used for declaring deprecated extensions. It simply places
* the current version code in place of the latest versions. This has the
* ability to break an extension version, so please be sure that this is the
* correct one to use.
* @param {string} name
* @param {string} version E.g. 0.1
* @param {string} latestVersion
* @param {!ExtensionOption} options extension options object.
*/
function declareExtensionVersionAlias(name, version, latestVersion, options) {
extensionAliasFilePath[name + '-' + version + '.js'] = {
'name': name,
'file': name + '-' + latestVersion + '.js',
};
if (options.hasCss) {
extensionAliasFilePath[name + '-' + version + '.css'] = {
'name': name,
'file': name + '-' + latestVersion + '.css',
};
}
if (options.cssBinaries) {
options.cssBinaries.forEach(cssBinaryName => {
extensionAliasFilePath[cssBinaryName + '-' + version + '.css'] = {
'name': cssBinaryName,
'file': cssBinaryName + '-' + latestVersion + '.css',
};
});
}
}
/**
* Stops the timer for the given build step and prints the execution time,
* unless we are on Travis.
* @param {string} stepName Name of the action, like 'Compiled' or 'Minified'
* @param {string} targetName Name of the target, like a filename or path
* @param {DOMHighResTimeStamp} startTime Start time of build step
*/
function endBuildStep(stepName, targetName, startTime) {
const endTime = Date.now();
const executionTime = new Date(endTime - startTime);
const secs = executionTime.getSeconds();
const ms = ('000' + executionTime.getMilliseconds().toString()).slice(-3);
let timeString = '(';
if (secs === 0) {
timeString += ms + ' ms)';
} else {
timeString += secs + '.' + ms + ' s)';
}
if (!process.env.TRAVIS) {
log(stepName, cyan(targetName), green(timeString));
}
}
/**
* Build all the AMP extensions
*
* @param {!Object} options
* @return {!Promise}
*/
function buildExtensions(options) {
if (!!argv.noextensions && !options.compileAll) {
return Promise.resolve();
}
const extensionsToBuild = options.compileAll ?
[] : getExtensionsToBuild();
const results = [];
for (const key in extensions) {
if (extensionsToBuild.length > 0 &&
extensionsToBuild.indexOf(extensions[key].name) == -1) {
continue;
}
const e = extensions[key];
let o = Object.assign({}, options);
o = Object.assign(o, e);
results.push(buildExtension(e.name, e.version, e.hasCss, o, e.extraGlobs));
}
return Promise.all(results);
}
/**
* Process the command line arguments --extensions and --extensions_from
* and return a list of the referenced extensions.
* @return {!Array<string>}
*/
function getExtensionsToBuild() {
if (extensionsToBuild) {
return extensionsToBuild;
}
extensionsToBuild = [];
if (!!argv.extensions) {
if (argv.extensions === 'minimal_set') {
argv.extensions = MINIMAL_EXTENSION_SET.join(',');
}
extensionsToBuild = argv.extensions.split(',');
}
if (!!argv.extensions_from) {
const extensionsFrom = getExtensionsFromArg(argv.extensions_from);
extensionsToBuild = dedupe(extensionsToBuild.concat(extensionsFrom));
}
return extensionsToBuild;
}
/**
* Process the command line argument --extensions_from of example AMP documents
* into a single list of AMP extensions consumed by those documents.
* @param {string} examples A comma separated list of AMP documents
* @return {!Array<string>}
*/
function getExtensionsFromArg(examples) {
if (!examples) {
return;
}
const extensions = [];
examples.split(',').forEach(example => {
const html = fs.readFileSync(example, 'utf8');
const customElementTemplateRe = /custom-(element|template)="([^"]+)"/g;
const extensionNameMatchIndex = 2;
let hasAd = false;
let match;
while ((match = customElementTemplateRe.exec(html))) {
if (match[extensionNameMatchIndex] == 'amp-ad') {
hasAd = true;
}
extensions.push(match[extensionNameMatchIndex]);
}
if (hasAd) {
for (let i = 0; i < adVendors.length; i++) {
if (html.includes(`type="${adVendors[i]}"`)) {
extensions.push('amp-a4a');
extensions.push(`amp-ad-network-${adVendors[i]}-impl`);
}
}
}
});
return dedupe(extensions);
}
/**
* Remove duplicates from the given array.
* @param {!Array<string>} arr
* @return {!Array<string>}
*/
function dedupe(arr) {
const map = Object.create(null);
arr.forEach(item => map[item] = true);
return Object.keys(map);
}
/**
* Compile the polyfills script and drop it in the build folder
* @return {!Promise}
*/
function polyfillsForTests() {
return compileJs('./src/', 'polyfills.js', './build/');
}
/**
* Compile and optionally minify the stylesheets and the scripts
* and drop them in the dist folder
*
* @param {boolean} watch
* @param {boolean} shouldMinify
* @param {boolean=} opt_preventRemoveAndMakeDir
* @param {boolean=} opt_checkTypes
* @return {!Promise}
*/
function compile(watch, shouldMinify, opt_preventRemoveAndMakeDir,
opt_checkTypes) {
const promises = [
compileJs('./3p/', 'integration.js',
'./dist.3p/' + (shouldMinify ? internalRuntimeVersion : 'current'), {
minifiedName: 'f.js',
checkTypes: opt_checkTypes,
watch,
minify: shouldMinify,
preventRemoveAndMakeDir: opt_preventRemoveAndMakeDir,
externs: ['ads/ads.extern.js'],
include3pDirectories: true,
includePolyfills: true,
}),
compileJs('./3p/', 'ampcontext-lib.js',
'./dist.3p/' + (shouldMinify ? internalRuntimeVersion : 'current'), {
minifiedName: 'ampcontext-v0.js',
checkTypes: opt_checkTypes,
watch,
minify: shouldMinify,
preventRemoveAndMakeDir: opt_preventRemoveAndMakeDir,
externs: ['ads/ads.extern.js'],
include3pDirectories: true,
includePolyfills: false,
}),
compileJs('./3p/', 'iframe-transport-client-lib.js',
'./dist.3p/' + (shouldMinify ? internalRuntimeVersion : 'current'), {
minifiedName: 'iframe-transport-client-v0.js',
checkTypes: opt_checkTypes,
watch,
minify: shouldMinify,
preventRemoveAndMakeDir: opt_preventRemoveAndMakeDir,
externs: ['ads/ads.extern.js'],
include3pDirectories: true,
includePolyfills: false,
}),
compileJs('./3p/', 'recaptcha.js',
'./dist.3p/' + (shouldMinify ? internalRuntimeVersion : 'current'), {
minifiedName: 'recaptcha.js',
checkTypes: opt_checkTypes,
watch,
minify: shouldMinify,
preventRemoveAndMakeDir: opt_preventRemoveAndMakeDir,
externs: [],
include3pDirectories: true,
includePolyfills: true,
}),
compileJs('./src/', 'amp.js', './dist', {
toName: 'amp.js',
minifiedName: 'v0.js',
includePolyfills: true,
checkTypes: opt_checkTypes,
watch,
preventRemoveAndMakeDir: opt_preventRemoveAndMakeDir,
minify: shouldMinify,
wrapper: wrappers.mainBinary,
singlePassCompilation: argv.single_pass,
esmPassCompilation: argv.esm,
}),
compileJs('./extensions/amp-viewer-integration/0.1/examples/',
'amp-viewer-host.js', './dist/v0/examples', {
toName: 'amp-viewer-host.max.js',
minifiedName: 'amp-viewer-host.js',
incudePolyfills: true,
watch,
extraGlobs: ['extensions/amp-viewer-integration/**/*.js'],
compilationLevel: 'WHITESPACE_ONLY',
preventRemoveAndMakeDir: opt_preventRemoveAndMakeDir,
minify: false,
}),
];
// TODO(#18934, erwinm): temporarily commented out to unblock master builds.
// theres a race condition between the read to amp.js here, and on the
// main v0.js compile above.
/**
if (!argv.single_pass) {
promises.push(
compileJs('./src/', 'amp.js', './dist', {
toName: 'amp-esm.js',
minifiedName: 'v0-esm.js',
includePolyfills: true,
includeOnlyESMLevelPolyfills: true,
checkTypes: opt_checkTypes,
watch,
preventRemoveAndMakeDir: opt_preventRemoveAndMakeDir,
minify: shouldMinify,
wrapper: wrappers.mainBinary,
}));
}*/
// We don't rerun type check for the shadow entry point for now.
if (!opt_checkTypes) {
if (!argv.single_pass && (!watch || argv.with_shadow)) {
promises.push(
compileJs('./src/', 'amp-shadow.js', './dist', {
minifiedName: 'shadow-v0.js',
includePolyfills: true,
checkTypes: opt_checkTypes,
watch,
preventRemoveAndMakeDir: opt_preventRemoveAndMakeDir,
minify: shouldMinify,
})
);
}
if (!watch || argv.with_video_iframe_integration) {
promises.push(
compileJs('./src/', 'video-iframe-integration.js', './dist', {
minifiedName: 'video-iframe-integration-v0.js',
includePolyfills: false,
checkTypes: opt_checkTypes,
watch,
preventRemoveAndMakeDir: opt_preventRemoveAndMakeDir,
minify: shouldMinify,
}));
}
if (!watch || argv.with_inabox) {
if (!argv.single_pass) {
promises.push(
// Entry point for inabox runtime.
compileJs('./src/inabox/', 'amp-inabox.js', './dist', {
toName: 'amp-inabox.js',
minifiedName: 'amp4ads-v0.js',
includePolyfills: true,
extraGlobs: ['src/inabox/*.js', '3p/iframe-messaging-client.js'],
checkTypes: opt_checkTypes,
watch,
preventRemoveAndMakeDir: opt_preventRemoveAndMakeDir,
minify: shouldMinify,
}));
}
promises.push(
// inabox-host
compileJs('./ads/inabox/', 'inabox-host.js', './dist', {
toName: 'amp-inabox-host.js',
minifiedName: 'amp4ads-host-v0.js',
includePolyfills: false,
checkTypes: opt_checkTypes,
watch,
preventRemoveAndMakeDir: opt_preventRemoveAndMakeDir,
minify: shouldMinify,
})
);
}
if (argv.with_inabox_lite) {
promises.push(
// Entry point for inabox runtime.
compileJs('./src/inabox/', 'amp-inabox-lite.js', './dist', {
toName: 'amp-inabox-lite.js',
minifiedName: 'amp4ads-lite-v0.js',
includePolyfills: true,
extraGlobs: ['src/inabox/*.js', '3p/iframe-messaging-client.js'],
checkTypes: opt_checkTypes,
watch,
preventRemoveAndMakeDir: opt_preventRemoveAndMakeDir,
minify: shouldMinify,
}));
}
promises.push(
thirdPartyBootstrap(
'3p/frame.max.html', 'frame.html', shouldMinify),
thirdPartyBootstrap(
'3p/nameframe.max.html', 'nameframe.html', shouldMinify),
thirdPartyBootstrap(
'3p/recaptcha.max.html', 'recaptcha.html', shouldMinify)
);
if (watch) {
$$.watch('3p/nameframe.max.html', function() {
thirdPartyBootstrap(
'3p/nameframe.max.html', 'nameframe.html', shouldMinify);
});
$$.watch('3p/frame.max.html', function() {
thirdPartyBootstrap(
'3p/frame.max.html', 'frame.html', shouldMinify);
});
$$.watch('3p/recaptcha.max.html', function() {
thirdPartyBootstrap(
'3p/recaptcha.max.html', 'recaptcha.html', shouldMinify);
});
}
return Promise.all(promises);
}
}
/**
* Entry point for 'gulp css'
* @return {!Promise}
*/
function css() {
printNobuildHelp();
return compileCss();
}
const cssEntryPoints = [
{
path: 'amp.css',
outJs: 'css.js',
outCss: 'v0.css',
},
{
path: 'video-docking.css',
outJs: 'video-docking.css.js',
outCss: 'video-docking.css',
},
{
path: 'video-autoplay.css',
outJs: 'video-autoplay.css.js',
outCss: 'video-autoplay.css',
},
];
/**
* Compile all the css and drop in the build folder
* @param {boolean} watch
* @param {boolean=} opt_compileAll
* @return {!Promise}
*/
function compileCss(watch, opt_compileAll) {
if (watch) {
$$.watch('css/**/*.css', function() {
compileCss();
});
}
/**
* Writes CSS to build folder
*
* @param {string} css
* @param {string} originalCssFilename
* @param {string} jsFilename
* @param {string} cssFilename
* @return {Promise}
*/
function writeCss(css, originalCssFilename, jsFilename, cssFilename) {
return toPromise(gulp.src(`css/${originalCssFilename}`)
.pipe($$.file(jsFilename, 'export const cssText = ' +
JSON.stringify(css)))
.pipe(gulp.dest('build'))
.on('end', function() {
mkdirSync('build');
mkdirSync('build/css');
fs.writeFileSync(`build/css/${cssFilename}`, css);
}));
}
/**
* @param {string} path
* @param {string} outJs
* @param {string} outCss
*/
function writeCssEntryPoint(path, outJs, outCss) {
const startTime = Date.now();
return jsifyCssAsync(`css/${path}`)
.then(css => writeCss(css, path, outJs, outCss))
.then(() => {
endBuildStep('Recompiled CSS in', path, startTime);
});
}
// Used by `gulp test --local-changes` to map CSS files to JS files.
fs.writeFileSync('EXTENSIONS_CSS_MAP', JSON.stringify(extensions));
let promise = Promise.resolve();
cssEntryPoints.forEach(entryPoint => {
const {path, outJs, outCss} = entryPoint;
promise = promise.then(() => writeCssEntryPoint(path, outJs, outCss));
});
return promise.then(() => buildExtensions({
bundleOnlyIfListedInFiles: false,
compileOnlyCss: true,
compileAll: opt_compileAll,
}));
}
/**
* Copies the css from the build folder to the dist folder
* @return {!Promise}
*/
function copyCss() {
const startTime = Date.now();
cssEntryPoints.forEach(({outCss}) => {
fs.copySync(`build/css/${outCss}`, `dist/${outCss}`);
});
return toPromise(gulp.src('build/css/amp-*.css')
.pipe(gulp.dest('dist/v0')))
.then(() => {
endBuildStep('Copied', 'build/css/*.css to dist/*.css', startTime);
});
}
/**
* Copies extensions from
* extensions/$name/$version/$name.js
* to
* dist/v0/$name-$version.js
*
* Optionally copies the CSS at extensions/$name/$version/$name.css into
* a generated JS file that can be required from the extensions as
* `import {CSS} from '../../../build/$name-0.1.css';`
*
* @param {string} name Name of the extension. Must be the sub directory in
* the extensions directory and the name of the JS and optional CSS file.
* @param {string} version Version of the extension. Must be identical to
* the sub directory inside the extension directory
* @param {boolean} hasCss Whether there is a CSS file for this extension.
* @param {?Object} options
* @param {!Array=} opt_extraGlobs
* @return {!Promise}
*/
function buildExtension(name, version, hasCss, options, opt_extraGlobs) {
options = options || {};
options.extraGlobs = opt_extraGlobs;
if (options.compileOnlyCss && !hasCss) {
return Promise.resolve();
}
const path = 'extensions/' + name + '/' + version;
const jsPath = path + '/' + name + '.js';
const jsTestPath = path + '/test/test-' + name + '.js';
if (argv.files && options.bundleOnlyIfListedInFiles) {
const passedFiles = Array.isArray(argv.files) ? argv.files : [argv.files];
const shouldBundle = passedFiles.some(glob => {
return minimatch(jsPath, glob) || minimatch(jsTestPath, glob);
});
if (!shouldBundle) {
return Promise.resolve();
}
}
// Building extensions is a 2 step process because of the renaming
// and CSS inlining. This watcher watches the original file, copies
// it to the destination and adds the CSS.
if (options.watch) {
// Do not set watchers again when we get called by the watcher.
const copy = Object.create(options);
copy.watch = false;
$$.watch(path + '/*', function() {
buildExtension(name, version, hasCss, copy);
});
}
let promise = Promise.resolve();
if (hasCss) {
mkdirSync('build');
mkdirSync('build/css');
const startTime = Date.now();
promise = buildExtensionCss(path, name, version, options).then(() => {
endBuildStep('Recompiled CSS in', name, startTime);
});
if (options.compileOnlyCss) {
return promise;
}
}
return promise.then(() => {
if (argv.single_pass) {
return Promise.resolve();
} else {
return buildExtensionJs(path, name, version, options);
}
});
}
/**
* @param {string} path
* @param {string} name
* @param {string} version
* @param {!Object} options
*/
function buildExtensionCss(path, name, version, options) {
/**
* Writes CSS binaries
*
* @param {string} name
* @param {string} css
*/
function writeCssBinaries(name, css) {
const jsCss = 'export const CSS = ' + JSON.stringify(css) + ';\n';
const jsName = `build/${name}.js`;
const cssName = `build/css/${name}`;
fs.writeFileSync(jsName, jsCss, 'utf-8');
fs.writeFileSync(cssName, css, 'utf-8');
}
const promises = [];
const mainCssBinary = jsifyCssAsync(path + '/' + name + '.css')
.then(writeCssBinaries.bind(null, `${name}-${version}.css`));
if (Array.isArray(options.cssBinaries)) {
promises.push.apply(promises, options.cssBinaries.map(function(name) {
return jsifyCssAsync(`${path}/${name}.css`)
.then(css => writeCssBinaries(`${name}-${version}.css`, css));
}));
}
promises.push(mainCssBinary);
return Promise.all(promises);
}
/**
* Build the JavaScript for the extension specified
*
* @param {string} path Path to the extensions directory
* @param {string} name Name of the extension. Must be the sub directory in
* the extensions directory and the name of the JS and optional CSS file.
* @param {string} version Version of the extension. Must be identical to
* the sub directory inside the extension directory
* @param {!Object} options
* @return {!Promise}
*/
function buildExtensionJs(path, name, version, options) {
const filename = options.filename || name + '.js';
return compileJs(path + '/', filename, './dist/v0', Object.assign(options, {
toName: `${name}-${version}.max.js`,
minifiedName: `${name}-${version}.js`,
latestName: `${name}-latest.js`,
// Wrapper that either registers the extension or schedules it for
// execution after the main binary comes back.
// The `function` is wrapped in `()` to avoid lazy parsing it,
// since it will be immediately executed anyway.
// See https://github.com/ampproject/amphtml/issues/3977
wrapper: options.noWrapper ? ''
: wrappers.extension(name, options.loadPriority),
})).then(() => {
// Copy @ampproject/worker-dom/dist/worker.safe.js to the dist/ folder.
if (name === 'amp-script') {
// TODO(choumx): Compile this when worker-dom externs are available.
const dir = 'node_modules/@ampproject/worker-dom/dist/';
const file = `dist/v0/amp-script-worker-${version}`;
fs.copyFileSync(dir + 'worker.safe.js', `${file}.js`);
fs.copyFileSync(dir + 'unminified.worker.safe.js', `${file}.max.js`);
}
});
}
/**
* Prints a message that could help speed up local development.
*/
function printNobuildHelp() {
if (!process.env.TRAVIS) {
for (const task of NOBUILD_HELP_TASKS) { // eslint-disable-line amphtml-internal/no-for-of-statement
if (argv._.includes(task)) {
log(green('To skip building during future'), cyan(task),
green('runs, use'), cyan('--nobuild'), green('with your'),
cyan(`gulp ${task}`), green('command.'));
return;
}
}
}
}
/**
* Prints a helpful message that lets the developer know how to switch configs.
* @param {string} command Command being run.
*/
function printConfigHelp(command) {
if (!process.env.TRAVIS) {
log(green('Building the runtime for local testing with the'),
cyan((argv.config === 'canary') ? 'canary' : 'prod'),
green('AMP config.'));
log(green('⤷ Use'), cyan('--config={canary|prod}'), green('with your'),
cyan(command), green('command to specify which config to apply.'));
}
}
/**
* Parses the --extensions, --extensions_from, and the --noextensions flags,
* and prints a helpful message that lets the developer know how to build the
* runtime with a list of extensions, all the extensions used by a test file,
* or no extensions at all.
*/
function parseExtensionFlags() {
if (!process.env.TRAVIS) {
const noExtensionsMessage = green('⤷ Use ') +
cyan('--noextensions ') +
green('to skip building extensions.');
const extensionsMessage = green('⤷ Use ') +
cyan('--extensions=amp-foo,amp-bar ') +
green('to choose which extensions to build.');
const minimalSetMessage = green('⤷ Use ') +
cyan('--extensions=minimal_set ') +
green('to build just the extensions needed to load ') +
cyan('article.amp.html') + green('.');
const extensionsFromMessage = green('⤷ Use ') +
cyan('--extensions_from=examples/foo.amp.html ') +
green('to build extensions from example docs.');
if (argv.extensions) {
if (typeof (argv.extensions) !== 'string') {
log(red('ERROR:'), 'Missing list of extensions.');
log(noExtensionsMessage);
log(extensionsMessage);
log(minimalSetMessage);
log(extensionsFromMessage);
process.exit(1);
}
argv.extensions = argv.extensions.replace(/\s/g, '');
}
if (argv.extensions || argv.extensions_from) {
log(green('Building extension(s):'),
cyan(getExtensionsToBuild().join(', ')));
if (maybeAddVideoService()) {
log(green('⤷ Video component(s) being built, added'),
cyan('amp-video-service'), green('to extension set.'));
}
} else if (argv.noextensions) {
log(green('Not building any AMP extensions.'));
} else {
log(green('Building all AMP extensions.'));
}
log(noExtensionsMessage);
log(extensionsMessage);
log(minimalSetMessage);
log(extensionsFromMessage);
}
}
/**
* Adds `amp-video-service` to the extension set if a component requires it.
* @return {boolean}
*/
function maybeAddVideoService() {
if (!extensionsToBuild.find(ext => VIDEO_EXTENSIONS.has(ext))) {
return false;
}
extensionsToBuild.push('amp-video-service');
return true;
}
/**
* Enables runtime to be used for local testing by writing AMP_CONFIG to file.
* Called at the end of "gulp build" and "gulp dist --fortesting".
* @param {string} targetFile File to which the config is to be written.
*/
function enableLocalTesting(targetFile) {
const config = (argv.config === 'canary') ? 'canary' : 'prod';
const baseConfigFile =
'build-system/global-configs/' + config + '-config.json';
return removeConfig(targetFile).then(() => {
return applyConfig(
config, targetFile, baseConfigFile,
/* opt_localDev */ true, /* opt_localBranch */ true);
});
}
/**
* Performs the build steps for gulp build and gulp watch
* @param {boolean} watch
* @return {!Promise}
*/
function performBuild(watch) {
process.env.NODE_ENV = 'development';
printNobuildHelp();
printConfigHelp(watch ? 'gulp watch' : 'gulp build');
parseExtensionFlags();
return compileCss(watch).then(() => {
return Promise.all([
polyfillsForTests(),
buildAlp({watch}),
buildExaminer({watch}),
buildWebWorker({watch}),
buildExtensions({bundleOnlyIfListedInFiles: !watch, watch}),
compile(watch),
]);
});
}
/**
* Enables watching for file changes in css, extensions.
* @return {!Promise}
*/
function watch() {
const handlerProcess = createCtrlcHandler('watch');
return performBuild(true).then(() => exitCtrlcHandler(handlerProcess));
}
/**
* Main build
* @return {!Promise}
*/
function build() {
const handlerProcess = createCtrlcHandler('build');
return performBuild().then(() => exitCtrlcHandler(handlerProcess));
}
/**
* Dist Build
* @return {!Promise}
*/
function dist() {
const handlerProcess = createCtrlcHandler('dist');
process.env.NODE_ENV = 'production';
cleanupBuildDir();
if (argv.fortesting) {
let cmd = 'gulp dist --fortesting';
if (argv.single_pass) {
cmd = cmd + ' --single_pass';
}
printConfigHelp(cmd);
}
if (argv.single_pass) {
if (!process.env.TRAVIS) {
log(green('Not building any AMP extensions in'), cyan('single_pass'),
green('mode.'));
}
} else {
parseExtensionFlags();
}
return compileCss(/* watch */ undefined, /* opt_compileAll */ true)
.then(() => {
return Promise.all([
compile(false, true, true),
// NOTE: When adding a line here,
// consider whether you need to include polyfills
// and whether you need to init logging (initLogConstructor).
buildAlp({minify: true, watch: false, preventRemoveAndMakeDir: true}),
buildExaminer({
minify: true, watch: false, preventRemoveAndMakeDir: true}),
buildWebWorker({
minify: true, watch: false, preventRemoveAndMakeDir: true}),
buildExtensions({minify: true, preventRemoveAndMakeDir: true}),
buildExperiments({
minify: true, watch: false, preventRemoveAndMakeDir: true}),
buildLoginDone({
minify: true, watch: false, preventRemoveAndMakeDir: true}),
buildWebPushPublisherFiles({
minify: true, watch: false, preventRemoveAndMakeDir: true}),
copyCss(),
]);
}).then(() => {
if (process.env.TRAVIS) {
// New line after all the compilation progress dots on Travis.
console.log('\n');
}
}).then(() => {
return copyAliasExtensions();
}).then(() => {
if (argv.fortesting) {
return Promise.all([
enableLocalTesting(minifiedRuntimeTarget),
enableLocalTesting(minifiedAdsTarget),
enableLocalTesting(minifiedShadowRuntimeTarget),
]).then(() => {
if (!argv.single_pass) {
// TODO(#18934, erwinm): temporary fix.
//return enableLocalTesting(minifiedRuntimeEsmTarget)
return enableLocalTesting(minifiedShadowRuntimeTarget)
.then(() => {
return enableLocalTesting(minifiedAdsTarget);
});