forked from ampproject/amphtml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gulpfile.js
1588 lines (1483 loc) · 52 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 applyConfig = require('./build-system/tasks/prepend-global/index.js').applyConfig;
const babel = require('babelify');
const browserify = require('browserify');
const buffer = require('vinyl-buffer');
const cleanupBuildDir = require('./build-system/tasks/compile').cleanupBuildDir;
const closureCompile = require('./build-system/tasks/compile').closureCompile;
const colors = require('ansi-colors');
const createCtrlcHandler = require('./build-system/ctrlcHandler').createCtrlcHandler;
const exitCtrlcHandler = require('./build-system/ctrlcHandler').exitCtrlcHandler;
const fs = require('fs-extra');
const gulp = $$.help(require('gulp'));
const internalRuntimeToken = require('./build-system/internal-version').TOKEN;
const internalRuntimeVersion = require('./build-system/internal-version').VERSION;
const jsifyCssAsync = require('./build-system/tasks/jsify-css').jsifyCssAsync;
const lazypipe = require('lazypipe');
const log = require('fancy-log');
const minimatch = require('minimatch');
const minimist = require('minimist');
const path = require('path');
const removeConfig = require('./build-system/tasks/prepend-global/index.js').removeConfig;
const rimraf = require('rimraf');
const serve = require('./build-system/tasks/serve.js').serve;
const source = require('vinyl-source-stream');
const touch = require('touch');
const transpileTs = require('./build-system/typescript').transpileTs;
const watchify = require('watchify');
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 = {};
const green = colors.green;
const red = colors.red;
const cyan = colors.cyan;
const minifiedRuntimeTarget = 'dist/v0.js';
const minified3pTarget = 'dist.3p/current-min/f.js';
const unminifiedRuntimeTarget = 'dist/amp.js';
const unminified3pTarget = 'dist.3p/current/integration.js';
// Each extension and version must be listed individually here.
declareExtension('amp-3q-player', '0.1');
declareExtension('amp-access', '0.1', {hasCss: true});
declareExtension('amp-access-laterpay', '0.1', {hasCss: true});
declareExtension('amp-access-scroll', '0.1', {hasCss: true});
declareExtension('amp-accordion', '0.1');
declareExtension('amp-ad', '0.1', {hasCss: true});
declareExtension('amp-ad-network-adsense-impl', 0.1);
declareExtension('amp-ad-network-adzerk-impl', 0.1);
declareExtension('amp-ad-network-doubleclick-impl', 0.1);
declareExtension('amp-ad-network-fake-impl', 0.1);
declareExtension('amp-ad-network-triplelift-impl', 0.1);
declareExtension('amp-ad-network-cloudflare-impl', 0.1);
declareExtension('amp-ad-network-gmossp-impl', 0.1);
declareExtension('amp-ad-exit', 0.1);
declareExtension('amp-analytics', '0.1');
declareExtension('amp-anim', '0.1');
declareExtension('amp-animation', '0.1');
declareExtension('amp-apester-media', '0.1', {hasCss: true});
declareExtension('amp-app-banner', '0.1', {hasCss: true});
declareExtension('amp-audio', '0.1');
declareExtension('amp-auto-ads', '0.1');
declareExtension('amp-bind', '0.1');
declareExtension('amp-bodymovin-animation', '0.1', {hasCss: false});
declareExtension('amp-brid-player', '0.1');
declareExtension('amp-brightcove', '0.1');
declareExtension('amp-byside-content', '0.1', {hasCss: true});
declareExtension('amp-kaltura-player', '0.1');
declareExtension('amp-call-tracking', '0.1');
declareExtension('amp-carousel', '0.1', {hasCss: true});
declareExtension('amp-compare-slider', '0.1');
declareExtension('amp-consent', '0.1', {hasCss: true});
declareExtension('amp-crypto-polyfill', '0.1');
declareExtension('amp-dailymotion', '0.1');
declareExtension('amp-document-recommendations', '0.1', {hasCss: true});
declareExtension('amp-dynamic-css-classes', '0.1');
declareExtension('amp-experiment', '0.1');
declareExtension('amp-facebook', '0.1');
declareExtension('amp-facebook-comments', '0.1');
declareExtension('amp-facebook-like', '0.1');
declareExtension('amp-facebook-page', '0.1');
declareExtension('amp-fit-text', '0.1', {hasCss: true});
declareExtension('amp-font', '0.1');
declareExtension('amp-form', '0.1', {hasCss: true});
declareExtension('amp-fx-collection', '0.1');
declareExtension('amp-fx-flying-carpet', '0.1', {hasCss: true});
declareExtension('amp-gfycat', '0.1');
declareExtension('amp-gist', '0.1');
declareExtension('amp-gwd-animation', '0.1', {hasCss: true});
declareExtension('amp-hulu', '0.1');
declareExtension('amp-iframe', '0.1');
declareExtension('amp-ima-video', '0.1');
declareExtension('amp-image-lightbox', '0.1', {hasCss: true});
declareExtension('amp-imgur', '0.1');
declareExtension('amp-instagram', '0.1', {hasCss: true});
declareExtension('amp-install-serviceworker', '0.1');
declareExtension('amp-izlesene', '0.1');
declareExtension('amp-jwplayer', '0.1');
declareExtension('amp-lightbox', '0.1', {hasCss: true});
declareExtension('amp-lightbox-gallery', '0.1', {hasCss: true});
declareExtension('amp-list', '0.1');
declareExtension('amp-live-list', '0.1', {hasCss: true});
declareExtension('amp-mathml', '0.1', {hasCss: true});
declareExtension('amp-mustache', '0.1');
declareExtension('amp-nexxtv-player', '0.1');
declareExtension('amp-o2-player', '0.1');
declareExtension('amp-ooyala-player', '0.1');
declareExtension('amp-pinterest', '0.1', {hasCss: true});
declareExtension('amp-playbuzz', '0.1', {hasCss: true});
declareExtension('amp-reach-player', '0.1');
declareExtension('amp-reddit', '0.1');
declareExtension('amp-riddle-quiz', '0.1');
declareExtension('amp-share-tracking', '0.1');
declareExtension('amp-sidebar', '0.1', {hasCss: true});
declareExtension('amp-soundcloud', '0.1');
declareExtension('amp-springboard-player', '0.1');
declareExtension('amp-sticky-ad', '1.0', {hasCss: true});
declareExtension('amp-story', '0.1', {
hasCss: true,
cssBinaries: [
'amp-story-bookend',
'amp-story-share',
'amp-story-system-layer',
],
});
declareExtension('amp-story-auto-ads', '0.1', {hasCss: false});
declareExtension('amp-selector', '0.1', {hasCss: true});
declareExtension('amp-web-push', '0.1', {hasCss: true});
declareExtension('amp-wistia-player', '0.1');
declareExtension('amp-position-observer', '0.1');
declareExtension('amp-date-picker', '0.1', {hasCss: true});
declareExtension('amp-image-viewer', '0.1', {hasCss: true});
declareExtension('amp-subscriptions', '0.1', {hasCss: true});
declareExtension('amp-subscriptions-google', '0.1');
/**
* @deprecated `amp-slides` is deprecated and will be deleted before 1.0.
* Please see {@link AmpCarousel} with `type=slides` attribute instead.
*/
declareExtension('amp-slides', '0.1');
declareExtension('amp-social-share', '0.1', {hasCss: true});
declareExtension('amp-timeago', '0.1');
declareExtension('amp-twitter', '0.1');
declareExtension('amp-user-notification', '0.1', {hasCss: true});
declareExtension('amp-vimeo', '0.1');
declareExtension('amp-vine', '0.1');
declareExtension('amp-viz-vega', '0.1', {hasCss: true});
declareExtension('amp-google-vrview-image', '0.1');
declareExtension('amp-viewer-integration', '0.1', {
// The viewer integration code needs to run asap, so that viewers
// can influence document state asap. Otherwise the document may take
// a long time to learn that it should start process other extensions
// faster.
loadPriority: 'high',
});
declareExtension('amp-video', '0.1');
declareExtension('amp-video-service', '0.1', {
// `amp-video-service` provides analytics and autoplay for all videos. We need
// those to be available asap. This service replaces a runtime-level provider,
// so loadPriority is set to high in lieu of delivering it as part of the core
// binary.
loadPriority: 'high',
});
declareExtension('amp-vk', '0.1');
declareExtension('amp-youtube', '0.1');
declareExtensionVersionAlias(
'amp-sticky-ad', '0.1', /* lastestVersion */ '1.0', /* hasCss */ true);
/**
* Extensions to build when `--extensions=minimal_set`.
* @private @const {!Set<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-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} version E.g. 0.1
* @param {!ExtensionOption} options extension options object.
*/
function declareExtension(name, version, options) {
const defaultOptions = {hasCss: false};
const extensionKey = `${name}-${version}`;
extensions[extensionKey] = Object.assign(
{name, version}, defaultOptions, options);
}
/**
* 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 verison, so please be sure that this is
* the correct one to use.
* @param {string} name
* @param {string} version E.g. 0.1
* @param {string} lastestVersion
* @param {boolean} hasCss
*/
function declareExtensionVersionAlias(name, version, lastestVersion, hasCss) {
extensionAliasFilePath[name + '-' + version + '.js'] = {
'name': name,
'file': name + '-' + lastestVersion + '.js',
};
if (hasCss) {
extensionAliasFilePath[name + '-' + version + '.css'] = {
'name': name,
'file': name + '-' + lastestVersion + '.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();
}
let extensionsToBuild = [];
if (!!argv.extensions && !options.compileAll) {
extensionsToBuild = argv.extensions.split(',');
}
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);
}
/**
* 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('./src/', 'amp.js', './dist', {
minifiedName: 'v0.js',
includePolyfills: true,
checkTypes: opt_checkTypes,
watch,
preventRemoveAndMakeDir: opt_preventRemoveAndMakeDir,
minify: shouldMinify,
// If there is a sync JS error during initial load,
// at least try to unhide the body.
wrapper: 'try{(function(){<%= contents %>})()}catch(e){' +
'setTimeout(function(){' +
'var s=document.body.style;' +
's.opacity=1;' +
's.visibility="visible";' +
's.animation="none";' +
's.WebkitAnimation="none;"},1000);throw e};',
}),
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,
}),
];
// We don't rerun type check for the shadow entry point for now.
if (!opt_checkTypes) {
if (!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_inabox) {
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,
}),
// 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,
})
);
}
promises.push(
thirdPartyBootstrap(
'3p/frame.max.html', 'frame.html', shouldMinify),
thirdPartyBootstrap(
'3p/nameframe.max.html', 'nameframe.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);
});
}
return Promise.all(promises);
}
}
/**
* Entry point for 'gulp css'
* @return {!Promise}
*/
function css() {
printNobuildHelp();
return compileCss();
}
/**
* 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();
});
}
const startTime = Date.now();
return jsifyCssAsync('css/amp.css')
.then(function(css) {
return toPromise(gulp.src('css/**.css')
.pipe($$.file('css.js', 'export const cssText = ' +
JSON.stringify(css)))
.pipe(gulp.dest('build'))
.on('end', function() {
mkdirSync('build');
mkdirSync('build/css');
fs.writeFileSync('build/css/v0.css', css);
}));
})
.then(() => {
endBuildStep('Recompiled CSS in', 'amp.css', startTime);
})
.then(() => {
return 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();
fs.copySync('build/css/v0.css', 'dist/v0.css');
return toPromise(gulp.src('build/css/amp-*.css')
.pipe(gulp.dest('dist/v0')))
.then(() => {
endBuildStep('Copied', 'build/css/v0.css to dist/v0.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(() => buildExtensionJs(path, name, version, options));
}
/**
* @param {string} path
* @param {string} css
* @param {string} version
* @param {!Object} options
*/
function buildExtensionCss(path, name, version, options) {
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';
if (options.loadPriority && options.loadPriority != 'high') {
throw new Error('Unsupported loadPriority: ' + options.loadPriority);
}
const priority = options.loadPriority ? 'p:"high",' : '';
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 ? ''
: `(self.AMP=self.AMP||[]).push({n:"${name}",${priority}` +
`v:"${internalRuntimeVersion}",f:(function(AMP){<%= contents %>\n})});`,
}));
}
/**
* Prints a message that could help speed up local development.
*/
function printNobuildHelp() {
if (!process.env.TRAVIS && argv['_'].indexOf('test') != -1) {
log(green('To skip building during future test runs, use'),
cyan('--nobuild'), green('with your'), cyan('gulp test'),
green('command.'));
}
}
/**
* 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.'));
}
}
/**
* Parse the --extensions or the --noextensions flag and
* prints a helpful message that lets the developer know how to build
* a list of extensions or without any extensions.
*/
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('.');
if (argv.extensions) {
if (typeof (argv.extensions) !== 'string') {
log(red('ERROR:'), 'Missing list of extensions.');
log(noExtensionsMessage);
log(extensionsMessage);
log(minimalSetMessage);
process.exit(1);
}
argv.extensions = argv.extensions.replace(/\s/g, '');
if (argv.extensions === 'minimal_set') {
argv.extensions = MINIMAL_EXTENSION_SET.join(',');
}
log(green('Building extension(s):'),
cyan(argv.extensions.replace(/,/g, ', ')));
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);
}
}
/**
* Adds `amp-video-service` to the extension set if a component requires it.
* @return {boolean}
*/
function maybeAddVideoService() {
if (!argv.extensions.split(',').find(ext => VIDEO_EXTENSIONS.has(ext))) {
return false;
}
argv.extensions += ',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}),
buildSw({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) {
printConfigHelp('gulp dist --fortesting');
}
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}),
buildSw({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(() => {
copyAliasExtensions();
}).then(() => {
if (argv.fortesting) {
return enableLocalTesting(minifiedRuntimeTarget);
}
}).then(() => {
if (argv.fortesting) {
return enableLocalTesting(minified3pTarget);
}
}).then(() => exitCtrlcHandler(handlerProcess));
}
/**
* Copy built extension to alias extension
*/
function copyAliasExtensions() {
if (argv.noextensions) {
return;
}
let extensionsToBuild = [];
if (!!argv.extensions) {
extensionsToBuild = argv.extensions.split(',');
}
for (const key in extensionAliasFilePath) {
if (extensionsToBuild.length > 0 &&
extensionsToBuild.indexOf(extensionAliasFilePath[key]['name']) == -1) {
continue;
}
fs.copySync('dist/v0/' + extensionAliasFilePath[key]['file'],
'dist/v0/' + key);
}
}
/**
* Dedicated type check path.
* @return {!Promise}
*/
function checkTypes() {
const handlerProcess = createCtrlcHandler('check-types');
process.env.NODE_ENV = 'production';
cleanupBuildDir();
// Disabled to improve type check performance, since this provides
// little incremental value.
/*buildExperiments({
minify: true,
checkTypes: true,
preventRemoveAndMakeDir: true,
});*/
const compileSrcs = [
'./src/amp.js',
'./src/amp-shadow.js',
'./src/inabox/amp-inabox.js',
'./ads/alp/install-alp.js',
'./ads/inabox/inabox-host.js',
'./src/service-worker/shell.js',
'./src/service-worker/core.js',
'./src/service-worker/kill.js',
'./src/web-worker/web-worker.js',
];
const extensionValues = Object.keys(extensions).map(function(key) {
return extensions[key];
});
const extensionSrcs = extensionValues.filter(function(extension) {
return !extension.noTypeCheck;
}).map(function(extension) {
return './extensions/' + extension.name + '/' +
extension.version + '/' + extension.name + '.js';
}).sort();
return compileCss().then(() => {
return Promise.all([
closureCompile(compileSrcs.concat(extensionSrcs), './dist',
'check-types.js', {
include3pDirectories: true,
includePolyfills: true,
extraGlobs: ['src/inabox/*.js'],
checkTypes: true,
}),
// Type check 3p/ads code.
closureCompile(['./3p/integration.js'], './dist',
'integration-check-types.js', {
externs: ['ads/ads.extern.js'],
include3pDirectories: true,
includePolyfills: true,
checkTypes: true,
}),
closureCompile(['./3p/ampcontext-lib.js'], './dist',
'ampcontext-check-types.js', {
externs: ['ads/ads.extern.js'],
include3pDirectories: true,
includePolyfills: true,
checkTypes: true,
}),
closureCompile(['./3p/iframe-transport-client-lib.js'], './dist',
'iframe-transport-client-check-types.js', {
externs: ['ads/ads.extern.js'],
include3pDirectories: true,
includePolyfills: true,
checkTypes: true,
}),
]);
}).then(() => {
if (process.env.TRAVIS) {
// New line after all the compilation progress dots on Travis.
console.log('\n');
}
}).then(() => exitCtrlcHandler(handlerProcess));
}
/**
* Copies frame.html to output folder, replaces js references to minified
* copies, and generates symlink to it.
*
* @param {string} input
* @param {string} outputName
* @param {boolean} shouldMinify
* @return {!Promise}
*/
function thirdPartyBootstrap(input, outputName, shouldMinify) {
const startTime = Date.now();
if (!shouldMinify) {
return toPromise(gulp.src(input)
.pipe(gulp.dest('dist.3p/current')))
.then(() => {
endBuildStep('Processed', input, startTime);
});
}
// By default we use an absolute URL, that is independent of the
// actual frame host for the JS inside the frame.
// But during testing we need a relative reference because the
// version is not available on the absolute path.
const integrationJs = argv.fortesting
? './f.js'
: `https://${hostname3p}/${internalRuntimeVersion}/f.js`;
// Convert default relative URL to absolute min URL.
const html = fs.readFileSync(input, 'utf8')
.replace(/\.\/integration\.js/g, integrationJs);
return toPromise($$.file(outputName, html, {src: true})
.pipe(gulp.dest('dist.3p/' + internalRuntimeVersion))
.on('end', function() {
const aliasToLatestBuild = 'dist.3p/current-min';
if (fs.existsSync(aliasToLatestBuild)) {
fs.unlinkSync(aliasToLatestBuild);
}
fs.symlinkSync(
'./' + internalRuntimeVersion,
aliasToLatestBuild,
'dir');
}))
.then(() => {