-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
url-replacements-impl.js
1350 lines (1223 loc) · 40.9 KB
/
url-replacements-impl.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 2015 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.
*/
import {
AsyncResolverDef,
ResolverReturnDef,
SyncResolverDef,
VariableSource,
getNavigationData,
getTimingDataAsync,
getTimingDataSync,
} from './variable-source';
import {Expander} from './url-expander/expander';
import {Services} from '../services';
import {WindowInterface} from '../window-interface';
import {
addMissingParamsToUrl,
addParamsToUrl,
getSourceUrl,
isProtocolValid,
parseQueryString,
parseUrlDeprecated,
removeAmpJsParamsFromUrl,
removeFragment,
} from '../url';
import {dev, devAssert, user, userAssert} from '../log';
import {getMode} from '../mode';
import {getTrackImpressionPromise} from '../impression.js';
import {hasOwn} from '../utils/object';
import {
installServiceInEmbedScope,
registerServiceBuilderForDoc,
} from '../service';
import {internalRuntimeVersion} from '../internal-version';
import {tryResolve} from '../utils/promise';
/** @private @const {string} */
const TAG = 'UrlReplacements';
const EXPERIMENT_DELIMITER = '!';
const VARIANT_DELIMITER = '.';
const GEO_DELIM = ',';
const ORIGINAL_HREF_PROPERTY = 'amp-original-href';
const ORIGINAL_VALUE_PROPERTY = 'amp-original-value';
/**
* Returns a function that executes method on a new Date instance. This is a
* byte saving hack.
*
* @param {string} method
* @return {!SyncResolverDef}
*/
function dateMethod(method) {
return () => new Date()[method]();
}
/**
* Returns a function that returns property of screen. This is a byte saving
* hack.
*
* @param {!Screen} screen
* @param {string} property
* @return {!SyncResolverDef}
*/
function screenProperty(screen, property) {
return () => screen[property];
}
/**
* Class to provide variables that pertain to top level AMP window.
*/
export class GlobalVariableSource extends VariableSource {
/**
* @param {!./ampdoc-impl.AmpDoc} ampdoc
*/
constructor(ampdoc) {
super(ampdoc);
/** @private {?Promise<?ShareTrackingFragmentsDef>} */
this.shareTrackingFragments_ = null;
}
/**
* Utility function for setting resolver for timing data that supports
* sync and async.
* @param {string} varName
* @param {string} startEvent
* @param {string=} endEvent
* @return {!VariableSource}
* @private
*/
setTimingResolver_(varName, startEvent, endEvent) {
return this.setBoth(
varName,
() => {
return getTimingDataSync(this.ampdoc.win, startEvent, endEvent);
},
() => {
return getTimingDataAsync(this.ampdoc.win, startEvent, endEvent);
}
);
}
/** @override */
initialize() {
const {win} = this.ampdoc;
const element = this.ampdoc.getHeadNode();
/** @const {!./viewport/viewport-impl.Viewport} */
const viewport = Services.viewportForDoc(this.ampdoc);
// Returns a random value for cache busters.
this.set('RANDOM', () => Math.random());
// Provides a counter starting at 1 per given scope.
const counterStore = Object.create(null);
this.set('COUNTER', scope => {
return (counterStore[scope] = (counterStore[scope] | 0) + 1);
});
// Returns the canonical URL for this AMP document.
this.set('CANONICAL_URL', () => this.getDocInfo_().canonicalUrl);
// Returns the host of the canonical URL for this AMP document.
this.set(
'CANONICAL_HOST',
() => parseUrlDeprecated(this.getDocInfo_().canonicalUrl).host
);
// Returns the hostname of the canonical URL for this AMP document.
this.set(
'CANONICAL_HOSTNAME',
() => parseUrlDeprecated(this.getDocInfo_().canonicalUrl).hostname
);
// Returns the path of the canonical URL for this AMP document.
this.set(
'CANONICAL_PATH',
() => parseUrlDeprecated(this.getDocInfo_().canonicalUrl).pathname
);
// Returns the referrer URL.
this.setAsync(
'DOCUMENT_REFERRER',
/** @type {AsyncResolverDef} */ (() => {
return Services.viewerForDoc(this.ampdoc).getReferrerUrl();
})
);
// Like DOCUMENT_REFERRER, but returns null if the referrer is of
// same domain or the corresponding CDN proxy.
this.setAsync(
'EXTERNAL_REFERRER',
/** @type {AsyncResolverDef} */ (() => {
return Services.viewerForDoc(this.ampdoc)
.getReferrerUrl()
.then(referrer => {
if (!referrer) {
return null;
}
const referrerHostname = parseUrlDeprecated(getSourceUrl(referrer))
.hostname;
const currentHostname = WindowInterface.getHostname(win);
return referrerHostname === currentHostname ? null : referrer;
});
})
);
// Returns the title of this AMP document.
this.set('TITLE', () => {
// The environment may override the title and set originalTitle. Prefer
// that if available.
const doc = win.document;
return doc['originalTitle'] || doc.title;
});
// Returns the URL for this AMP document.
this.set('AMPDOC_URL', () => {
return removeFragment(this.addReplaceParamsIfMissing_(win.location.href));
});
// Returns the host of the URL for this AMP document.
this.set('AMPDOC_HOST', () => {
const url = parseUrlDeprecated(win.location.href);
return url && url.host;
});
// Returns the hostname of the URL for this AMP document.
this.set('AMPDOC_HOSTNAME', () => {
const url = parseUrlDeprecated(win.location.href);
return url && url.hostname;
});
// Returns the Source URL for this AMP document.
const expandSourceUrl = () => {
const docInfo = this.getDocInfo_();
return removeFragment(this.addReplaceParamsIfMissing_(docInfo.sourceUrl));
};
this.setBoth(
'SOURCE_URL',
() => expandSourceUrl(),
() => getTrackImpressionPromise().then(() => expandSourceUrl())
);
// Returns the host of the Source URL for this AMP document.
this.set(
'SOURCE_HOST',
() => parseUrlDeprecated(this.getDocInfo_().sourceUrl).host
);
// Returns the hostname of the Source URL for this AMP document.
this.set(
'SOURCE_HOSTNAME',
() => parseUrlDeprecated(this.getDocInfo_().sourceUrl).hostname
);
// Returns the path of the Source URL for this AMP document.
this.set(
'SOURCE_PATH',
() => parseUrlDeprecated(this.getDocInfo_().sourceUrl).pathname
);
// Returns a random string that will be the constant for the duration of
// single page view. It should have sufficient entropy to be unique for
// all the page views a single user is making at a time.
this.set('PAGE_VIEW_ID', () => this.getDocInfo_().pageViewId);
this.setBoth(
'QUERY_PARAM',
(param, defaultValue = '') => {
return this.getQueryParamData_(param, defaultValue);
},
(param, defaultValue = '') => {
return getTrackImpressionPromise().then(() => {
return this.getQueryParamData_(param, defaultValue);
});
}
);
// Returns the value of the given field name in the fragment query string.
// Second parameter is an optional default value.
// For example, if location is 'pub.com/amp.html?x=1#y=2' then
// FRAGMENT_PARAM(y) returns '2' and FRAGMENT_PARAM(z, 3) returns 3.
this.setAsync(
'FRAGMENT_PARAM',
this.getViewerIntegrationValue_('fragmentParam', 'FRAGMENT_PARAM')
);
// Returns the first item in the ancestorOrigins array, if available.
this.setAsync(
'ANCESTOR_ORIGIN',
this.getViewerIntegrationValue_('ancestorOrigin', 'ANCESTOR_ORIGIN')
);
/**
* Stores client ids that were generated during this page view
* indexed by scope.
* @type {?Object<string, string>}
*/
let clientIds = null;
// Synchronous alternative. Only works for scopes that were previously
// requested using the async method.
this.setBoth(
'CLIENT_ID',
scope => {
if (!clientIds) {
return null;
}
return clientIds[scope];
},
(scope, opt_userNotificationId, opt_cookieName) => {
userAssert(
scope,
'The first argument to CLIENT_ID, the fallback' +
/*OK*/ ' Cookie name, is required'
);
if (getMode().runtime == 'inabox') {
return /** @type {!Promise<ResolverReturnDef>} */ (Promise.resolve(
null
));
}
let consent = Promise.resolve();
// If no `opt_userNotificationId` argument is provided then
// assume consent is given by default.
if (opt_userNotificationId) {
consent = Services.userNotificationManagerForDoc(element).then(
service => {
return service.get(opt_userNotificationId);
}
);
}
return Services.cidForDoc(this.ampdoc)
.then(cid => {
return cid.get(
{
/** @type {string} */ scope,
createCookieIfNotPresent: true,
cookieName: opt_cookieName,
},
consent
);
})
.then(cid => {
if (!clientIds) {
clientIds = Object.create(null);
}
// A temporary work around to extract Client ID from _ga cookie. #5761
// TODO: replace with "filter" when it's in place. #2198
const cookieName = opt_cookieName || scope;
if (cid && cookieName == '_ga') {
if (typeof cid === 'string') {
cid = extractClientIdFromGaCookie(cid);
} else {
// TODO(@jridgewell, #11120): remove once #11120 is figured out.
// Do not log the CID directly, that's PII.
dev().error(
TAG,
'non-string cid, what is it?',
Object.keys(cid)
);
}
}
clientIds[scope] = cid;
return cid;
});
}
);
// Returns assigned variant name for the given experiment.
this.setAsync(
'VARIANT',
/** @type {AsyncResolverDef} */ (experiment => {
return this.getVariantsValue_(variants => {
const variant = variants[/** @type {string} */ (experiment)];
userAssert(
variant !== undefined,
'The value passed to VARIANT() is not a valid experiment name:' +
experiment
);
// When no variant assigned, use reserved keyword 'none'.
return variant === null ? 'none' : /** @type {string} */ (variant);
}, 'VARIANT');
})
);
// Returns all assigned experiment variants in a serialized form.
this.setAsync(
'VARIANTS',
/** @type {AsyncResolverDef} */ (() => {
return this.getVariantsValue_(variants => {
const experiments = [];
for (const experiment in variants) {
const variant = variants[experiment];
experiments.push(
experiment + VARIANT_DELIMITER + (variant || 'none')
);
}
return experiments.join(EXPERIMENT_DELIMITER);
}, 'VARIANTS');
})
);
// Returns assigned geo value for geoType or all groups.
this.setAsync(
'AMP_GEO',
/** @type {AsyncResolverDef} */ (geoType => {
return this.getGeo_(geos => {
if (geoType) {
userAssert(
geoType === 'ISOCountry',
'The value passed to AMP_GEO() is not valid name:' + geoType
);
return /** @type {string} */ (geos[geoType] || 'unknown');
}
return /** @type {string} */ (geos.matchedISOCountryGroups.join(
GEO_DELIM
));
}, 'AMP_GEO');
})
);
// Attempt to returns user location data if available, otherwise null.
this.setAsync(
'AMP_USER_LOCATION',
/** @type {AsyncResolverDef} */ (type => {
// Type may be "","lat","lon", and undefined
return this.getUserLocation_(userLocationService => {
return userLocationService.getReplacementLocation(
'AMP_USER_LOCATION',
type
);
}, 'AMP_USER_LOCATION');
})
);
// Returns user location data only if available,
// and waits for the user to approve.
this.setAsync(
'AMP_USER_LOCATION_POLL',
/** @type {AsyncResolverDef} */ (type => {
// Type may be "","lat","lon", and undefined
return this.getUserLocation_(userLocationService => {
return userLocationService.getReplacementLocation(
'AMP_USER_LOCATION_POLL',
type,
/*opt_poll*/ true
);
}, 'AMP_USER_LOCATION_POLL');
})
);
// Returns incoming share tracking fragment.
this.setAsync(
'SHARE_TRACKING_INCOMING',
/** @type {AsyncResolverDef} */ (() => {
return this.getShareTrackingValue_(fragments => {
return fragments.incomingFragment;
}, 'SHARE_TRACKING_INCOMING');
})
);
// Returns outgoing share tracking fragment.
this.setAsync(
'SHARE_TRACKING_OUTGOING',
/** @type {AsyncResolverDef} */ (() => {
return this.getShareTrackingValue_(fragments => {
return fragments.outgoingFragment;
}, 'SHARE_TRACKING_OUTGOING');
})
);
// Returns the number of milliseconds since 1 Jan 1970 00:00:00 UTC.
this.set('TIMESTAMP', dateMethod('getTime'));
// Returns the human readable timestamp in format of
// 2011-01-01T11:11:11.612Z.
this.set('TIMESTAMP_ISO', dateMethod('toISOString'));
// Returns the user's time-zone offset from UTC, in minutes.
this.set('TIMEZONE', dateMethod('getTimezoneOffset'));
// Returns the IANA timezone code
this.set('TIMEZONE_CODE', () => {
let tzCode;
if ('Intl' in win && 'DateTimeFormat' in win.Intl) {
// It could be undefined (i.e. IE11)
tzCode = new Intl.DateTimeFormat().resolvedOptions().timeZone;
}
return tzCode || '';
});
// Returns a promise resolving to viewport.getScrollTop.
this.set('SCROLL_TOP', () => viewport.getScrollTop());
// Returns a promise resolving to viewport.getScrollLeft.
this.set('SCROLL_LEFT', () => viewport.getScrollLeft());
// Returns a promise resolving to viewport.getScrollHeight.
this.set('SCROLL_HEIGHT', () => viewport.getScrollHeight());
// Returns a promise resolving to viewport.getScrollWidth.
this.set('SCROLL_WIDTH', () => viewport.getScrollWidth());
// Returns the viewport height.
this.set('VIEWPORT_HEIGHT', () => viewport.getHeight());
// Returns the viewport width.
this.set('VIEWPORT_WIDTH', () => viewport.getWidth());
const {screen} = win;
// Returns screen.width.
this.set('SCREEN_WIDTH', screenProperty(screen, 'width'));
// Returns screen.height.
this.set('SCREEN_HEIGHT', screenProperty(screen, 'height'));
// Returns screen.availHeight.
this.set('AVAILABLE_SCREEN_HEIGHT', screenProperty(screen, 'availHeight'));
// Returns screen.availWidth.
this.set('AVAILABLE_SCREEN_WIDTH', screenProperty(screen, 'availWidth'));
// Returns screen.ColorDepth.
this.set('SCREEN_COLOR_DEPTH', screenProperty(screen, 'colorDepth'));
// Returns document characterset.
this.set('DOCUMENT_CHARSET', () => {
const doc = win.document;
return doc.characterSet || doc.charset;
});
// Returns the browser language.
this.set('BROWSER_LANGUAGE', () => {
const nav = win.navigator;
return (
nav.language ||
nav.userLanguage ||
nav.browserLanguage ||
''
).toLowerCase();
});
// Returns the user agent.
this.set('USER_AGENT', () => {
return win.navigator.userAgent;
});
// Returns the time it took to load the whole page. (excludes amp-* elements
// that are not rendered by the system yet.)
this.setTimingResolver_(
'PAGE_LOAD_TIME',
'navigationStart',
'loadEventStart'
);
// Returns the time it took to perform DNS lookup for the domain.
this.setTimingResolver_(
'DOMAIN_LOOKUP_TIME',
'domainLookupStart',
'domainLookupEnd'
);
// Returns the time it took to connect to the server.
this.setTimingResolver_('TCP_CONNECT_TIME', 'connectStart', 'connectEnd');
// Returns the time it took for server to start sending a response to the
// request.
this.setTimingResolver_(
'SERVER_RESPONSE_TIME',
'requestStart',
'responseStart'
);
// Returns the time it took to download the page.
this.setTimingResolver_(
'PAGE_DOWNLOAD_TIME',
'responseStart',
'responseEnd'
);
// Returns the time it took for redirects to complete.
this.setTimingResolver_('REDIRECT_TIME', 'navigationStart', 'fetchStart');
// Returns the time it took for DOM to become interactive.
this.setTimingResolver_(
'DOM_INTERACTIVE_TIME',
'navigationStart',
'domInteractive'
);
// Returns the time it took for content to load.
this.setTimingResolver_(
'CONTENT_LOAD_TIME',
'navigationStart',
'domContentLoadedEventStart'
);
// Access: Reader ID.
this.setAsync(
'ACCESS_READER_ID',
/** @type {AsyncResolverDef} */ (() => {
return this.getAccessValue_(accessService => {
return accessService.getAccessReaderId();
}, 'ACCESS_READER_ID');
})
);
// Access: data from the authorization response.
this.setAsync(
'AUTHDATA',
/** @type {AsyncResolverDef} */ (field => {
userAssert(
field,
'The first argument to AUTHDATA, the field, is required'
);
return this.getAccessValue_(accessService => {
return accessService.getAuthdataField(field);
}, 'AUTHDATA');
})
);
// Returns an identifier for the viewer.
this.setAsync('VIEWER', () => {
return Services.viewerForDoc(this.ampdoc)
.getViewerOrigin()
.then(viewer => {
return viewer == undefined ? '' : viewer;
});
});
// Returns the total engaged time since the content became viewable.
this.setAsync('TOTAL_ENGAGED_TIME', () => {
return Services.activityForDoc(element).then(activity => {
return activity.getTotalEngagedTime();
});
});
// Returns the incremental engaged time since the last push under the
// same name.
this.setAsync('INCREMENTAL_ENGAGED_TIME', (name, reset) => {
return Services.activityForDoc(element).then(activity => {
return activity.getIncrementalEngagedTime(
/** @type {string} */ (name),
reset !== 'false'
);
});
});
this.set('NAV_TIMING', (startAttribute, endAttribute) => {
userAssert(
startAttribute,
'The first argument to NAV_TIMING, the ' +
'start attribute name, is required'
);
return getTimingDataSync(
win,
/**@type {string}*/ (startAttribute),
/**@type {string}*/ (endAttribute)
);
});
this.setAsync('NAV_TIMING', (startAttribute, endAttribute) => {
userAssert(
startAttribute,
'The first argument to NAV_TIMING, the ' +
'start attribute name, is required'
);
return getTimingDataAsync(
win,
/**@type {string}*/ (startAttribute),
/**@type {string}*/ (endAttribute)
);
});
this.set('NAV_TYPE', () => {
return getNavigationData(win, 'type');
});
this.set('NAV_REDIRECT_COUNT', () => {
return getNavigationData(win, 'redirectCount');
});
// returns the AMP version number
this.set('AMP_VERSION', () => internalRuntimeVersion());
this.set('BACKGROUND_STATE', () => {
return Services.viewerForDoc(this.ampdoc).isVisible() ? '0' : '1';
});
this.setAsync('VIDEO_STATE', (id, property) => {
const root = this.ampdoc.getRootNode();
const video = user().assertElement(
root.getElementById(/** @type {string} */ (id)),
`Could not find an element with id="${id}" for VIDEO_STATE`
);
return Services.videoManagerForDoc(this.ampdoc)
.getAnalyticsDetails(video)
.then(details => (details ? details[property] : ''));
});
this.setAsync(
'STORY_PAGE_INDEX',
this.getStoryValue_('pageIndex', 'STORY_PAGE_INDEX')
);
this.setAsync(
'STORY_PAGE_ID',
this.getStoryValue_('pageId', 'STORY_PAGE_ID')
);
this.setAsync('FIRST_CONTENTFUL_PAINT', () => {
return tryResolve(() =>
Services.performanceFor(win).getFirstContentfulPaint()
);
});
this.setAsync('FIRST_VIEWPORT_READY', () => {
return tryResolve(() =>
Services.performanceFor(win).getFirstViewportReady()
);
});
this.setAsync('MAKE_BODY_VISIBLE', () => {
return tryResolve(() =>
Services.performanceFor(win).getMakeBodyVisible()
);
});
this.setAsync('AMP_STATE', key => {
// This is safe since AMP_STATE is not an A4A whitelisted variable.
const root = this.ampdoc.getRootNode();
const element =
/** @type {!Element|!ShadowRoot} */ (root.documentElement || root);
return Services.bindForDocOrNull(element).then(bind => {
if (!bind) {
return '';
}
return bind.getStateValue(/** @type {string} */ (key));
});
});
}
/**
* Merges any replacement parameters into a given URL's query string,
* preferring values set in the original query string.
* @param {string} orig The original URL
* @return {string} The resulting URL
* @private
*/
addReplaceParamsIfMissing_(orig) {
const {replaceParams} = /** @type {!Object} */ (this.getDocInfo_());
if (!replaceParams) {
return orig;
}
return addMissingParamsToUrl(removeAmpJsParamsFromUrl(orig), replaceParams);
}
/**
* Return the document info for the current ampdoc.
* @return {./document-info-impl.DocumentInfoDef}
*/
getDocInfo_() {
return Services.documentInfoForDoc(this.ampdoc);
}
/**
* Resolves the value via access service. If access service is not configured,
* the resulting value is `null`.
* @param {function(!../../extensions/amp-access/0.1/access-vars.AccessVars):(T|!Promise<T>)} getter
* @param {string} expr
* @return {T|null}
* @template T
* @private
*/
getAccessValue_(getter, expr) {
const element = this.ampdoc.getHeadNode();
return Promise.all([
Services.accessServiceForDocOrNull(element),
Services.subscriptionsServiceForDocOrNull(element),
]).then(services => {
const service =
/** @type {?../../extensions/amp-access/0.1/access-vars.AccessVars} */ (services[0] ||
services[1]);
if (!service) {
// Access/subscriptions service is not installed.
user().error(
TAG,
'Access or subsciptions service is not installed to access: ',
expr
);
return null;
}
return getter(service);
});
}
/**
* Return the QUERY_PARAM from the current location href
* @param {string} param
* @param {string} defaultValue
* @return {string}
* @private
*/
getQueryParamData_(param, defaultValue) {
userAssert(
param,
'The first argument to QUERY_PARAM, the query string ' +
'param is required'
);
const url = parseUrlDeprecated(
removeAmpJsParamsFromUrl(this.ampdoc.win.location.href)
);
const params = parseQueryString(url.search);
const {replaceParams} = this.getDocInfo_();
if (typeof params[param] !== 'undefined') {
return params[param];
}
if (replaceParams && typeof replaceParams[param] !== 'undefined') {
return /** @type {string} */ (replaceParams[param]);
}
return defaultValue;
}
/**
* Resolves the value via amp-experiment's variants service.
* @param {function(!Object<string, string>):(?string)} getter
* @param {string} expr
* @return {!Promise<?string>}
* @template T
* @private
*/
getVariantsValue_(getter, expr) {
return Services.variantsForDocOrNull(this.ampdoc.getHeadNode())
.then(variants => {
userAssert(
variants,
'To use variable %s, amp-experiment should be configured',
expr
);
return variants.getVariants();
})
.then(variantsMap => getter(variantsMap));
}
/**
* Resolves the value via geo service.
* @param {function(Object<string, string>)} getter
* @param {string} expr
* @return {!Promise<Object<string,(string|Array<string>)>>}
* @template T
* @private
*/
getGeo_(getter, expr) {
const element = this.ampdoc.getHeadNode();
return Services.geoForDocOrNull(element).then(geo => {
userAssert(geo, 'To use variable %s, amp-geo should be configured', expr);
return getter(geo);
});
}
/**
* Resolves the value via the user location service.
* @param {function(Object<string, string>)} getter
* @param {string} expr
* @return {!Promise<Object<string,(string|Array<string>)>>}
* @template T
* @private
*/
getUserLocation_(getter, expr) {
const element = this.ampdoc.getHeadNode();
return Services.userLocationForDocOrNull(element).then(
userLocationService => {
userAssert(
userLocationService,
'To use variable %s, amp-user-location should be configured',
expr
);
return getter(userLocationService);
}
);
}
/**
* Resolves the value via amp-share-tracking's service.
* @param {function(!ShareTrackingFragmentsDef):T} getter
* @param {string} expr
* @return {!Promise<T>}
* @template T
* @private
*/
getShareTrackingValue_(getter, expr) {
if (!this.shareTrackingFragments_) {
this.shareTrackingFragments_ = Services.shareTrackingForOrNull(
this.ampdoc.win
);
}
return this.shareTrackingFragments_.then(fragments => {
userAssert(
fragments,
'To use variable %s, amp-share-tracking should be configured',
expr
);
return getter(/** @type {!ShareTrackingFragmentsDef} */ (fragments));
});
}
/**
* Resolves the value via amp-story's service.
* @param {string} property
* @param {string} name
* @return {!AsyncResolverDef}
* @private
*/
getStoryValue_(property, name) {
return () => {
const service = Services.storyVariableServiceForOrNull(this.ampdoc.win);
return service.then(storyVariables => {
userAssert(
storyVariables,
'To use variable %s amp-story should be configured',
name
);
return storyVariables[property];
});
};
}
/**
* Resolves the value via amp-viewer-integration's service.
* @param {string} property
* @param {string} name
* @return {!AsyncResolverDef}
* @private
*/
getViewerIntegrationValue_(property, name) {
return /** @type {!AsyncResolverDef} */ ((param, defaultValue = '') => {
const service = Services.viewerIntegrationVariableServiceForOrNull(
this.ampdoc.win
);
return service.then(viewerIntegrationVariables => {
userAssert(
viewerIntegrationVariables,
'To use variable %s amp-viewer-integration must be installed',
name
);
return viewerIntegrationVariables[property](param, defaultValue);
});
});
}
}
/**
* This class replaces substitution variables with their values.
* Document new values in ../spec/amp-var-substitutions.md
* @package For export
*/
export class UrlReplacements {
/**
* @param {!./ampdoc-impl.AmpDoc} ampdoc
* @param {!VariableSource} variableSource
*/
constructor(ampdoc, variableSource) {
/** @const {!./ampdoc-impl.AmpDoc} */
this.ampdoc = ampdoc;
/** @type {VariableSource} */
this.variableSource_ = variableSource;
}
/**
* Synchronously expands the provided source by replacing all known variables
* with their resolved values. Optional `opt_bindings` can be used to add new
* variables or override existing ones. Any async bindings are ignored.
* @param {string} source
* @param {!Object<string, (ResolverReturnDef|!SyncResolverDef)>=} opt_bindings
* @param {!Object<string, ResolverReturnDef>=} opt_collectVars
* @param {!Object<string, boolean>=} opt_whiteList Optional white list of
* names that can be substituted.
* @return {string}
*/
expandStringSync(source, opt_bindings, opt_collectVars, opt_whiteList) {
return /** @type {string} */ (new Expander(
this.variableSource_,
opt_bindings,
opt_collectVars,
/* opt_sync */ true,
opt_whiteList,
/* opt_noEncode */ true
)./*OK*/ expand(source));
}
/**
* Expands the provided source by replacing all known variables with their
* resolved values. Optional `opt_bindings` can be used to add new variables
* or override existing ones.
* @param {string} source
* @param {!Object<string, *>=} opt_bindings
* @param {!Object<string, boolean>=} opt_whiteList
* @return {!Promise<string>}
*/
expandStringAsync(source, opt_bindings, opt_whiteList) {
return /** @type {!Promise<string>} */ (new Expander(
this.variableSource_,
opt_bindings,
/* opt_collectVars */ undefined,
/* opt_sync */ undefined,
opt_whiteList,
/* opt_noEncode */ true
)./*OK*/ expand(source));
}
/**
* Synchronously expands the provided URL by replacing all known variables
* with their resolved values. Optional `opt_bindings` can be used to add new
* variables or override existing ones. Any async bindings are ignored.
* @param {string} url
* @param {!Object<string, (ResolverReturnDef|!SyncResolverDef)>=} opt_bindings
* @param {!Object<string, ResolverReturnDef>=} opt_collectVars
* @param {!Object<string, boolean>=} opt_whiteList Optional white list of
* names that can be substituted.
* @return {string}
*/
expandUrlSync(url, opt_bindings, opt_collectVars, opt_whiteList) {