-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
amp-ad-network-doubleclick-impl.js
1979 lines (1839 loc) · 62.9 KB
/
amp-ad-network-doubleclick-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 2016 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.
*/
// Because AdSense and DoubleClick are both operated by Google and their A4A
// implementations share some behavior in common, part of the logic for this
// implementation is located in the ads/google/a4a directory rather than here.
// Most other ad networks will want to put their A4A code entirely in the
// extensions/amp-ad-network-${NETWORK_NAME}-impl directory.
import '../../amp-a4a/0.1/real-time-config-manager';
import {
AmpA4A,
ConsentTupleDef,
DEFAULT_SAFEFRAME_VERSION,
XORIGIN_MODE,
assignAdUrlToError,
} from '../../amp-a4a/0.1/amp-a4a';
import {
AmpAnalyticsConfigDef,
QQID_HEADER,
SANDBOX_HEADER,
ValidAdContainerTypes,
addCsiSignalsToAmpAnalyticsConfig,
extractAmpAnalyticsConfig,
getCsiAmpAnalyticsConfig,
getCsiAmpAnalyticsVariables,
getEnclosingContainerTypes,
getIdentityToken,
googleAdUrl,
googleBlockParameters,
googlePageParameters,
groupAmpAdsByType,
isCdnProxy,
isReportingEnabled,
maybeAppendErrorParameter,
truncAndTimeUrl,
} from '../../../ads/google/a4a/utils';
import {CONSENT_POLICY_STATE} from '../../../src/consent-state';
import {Deferred} from '../../../src/utils/promise';
import {
FlexibleAdSlotDataTypeDef,
getFlexibleAdSlotData,
} from './flexible-ad-slot-utils';
import {Layout, isLayoutSizeDefined} from '../../../src/layout';
import {Navigation} from '../../../src/service/navigation';
import {RTC_VENDORS} from '../../amp-a4a/0.1/callout-vendors';
import {
RefreshManager, // eslint-disable-line no-unused-vars
getRefreshManager,
} from '../../amp-a4a/0.1/refresh-manager';
import {SafeframeHostApi} from './safeframe-host';
import {Services} from '../../../src/services';
import {
TFCD,
constructSRABlockParameters,
serializeTargeting,
sraBlockCallbackHandler,
} from './sra-utils';
import {WindowInterface} from '../../../src/window-interface';
import {
assertDoesNotContainDisplay,
setImportantStyles,
setStyles,
} from '../../../src/style';
import {
createElementWithAttributes,
isRTL,
removeElement,
} from '../../../src/dom';
import {deepMerge, dict} from '../../../src/utils/object';
import {dev, devAssert, user} from '../../../src/log';
import {domFingerprintPlain} from '../../../src/utils/dom-fingerprint';
import {escapeCssSelectorIdent} from '../../../src/css';
import {
extractUrlExperimentId,
isInManualExperiment,
} from '../../../ads/google/a4a/traffic-experiments';
import {
getAmpAdRenderOutsideViewport,
incrementLoadingAds,
is3pThrottled,
waitFor3pThrottle,
} from '../../amp-ad/0.1/concurrent-load';
import {getCryptoRandomBytesArray, utf8Decode} from '../../../src/utils/bytes';
import {getMode} from '../../../src/mode';
import {getMultiSizeDimensions} from '../../../ads/google/utils';
import {getOrCreateAdCid} from '../../../src/ad-cid';
import {
isExperimentOn,
randomlySelectUnsetExperiments,
} from '../../../src/experiments';
import {insertAnalyticsElement} from '../../../src/extension-analytics';
import {isArray} from '../../../src/types';
import {isCancellation} from '../../../src/error';
import {
lineDelimitedStreamer,
metaJsonCreativeGrouper,
} from '../../../ads/google/a4a/line-delimited-response-handler';
import {parseQueryString} from '../../../src/url';
import {stringHash32} from '../../../src/string';
import {tryParseJson} from '../../../src/json';
/** @type {string} */
const TAG = 'amp-ad-network-doubleclick-impl';
/** @const {string} */
const DOUBLECLICK_BASE_URL =
'https://securepubads.g.doubleclick.net/gampad/ads';
/** @const {string} */
const RTC_SUCCESS = '2';
/** @const {string} */
const DOUBLECLICK_SRA_EXP = 'doubleclickSraExp';
/** @const @enum{string} */
const DOUBLECLICK_SRA_EXP_BRANCHES = {
SRA_CONTROL: '117152666',
SRA: '117152667',
SRA_NO_RECOVER: '21062235',
};
/** @const {string} */
const ZINDEX_EXP = 'zIndexExp';
/**@const @enum{string} */
const ZINDEX_EXP_BRANCHES = {
NO_ZINDEX: '21065356',
HOLDBACK: '21065357',
};
/**
* Required size to be sent with fluid requests.
* @const {string}
*/
const DUMMY_FLUID_SIZE = '320x50';
/** @const @private {string} attribute indicating if lazy fetch is enabled.*/
const LAZY_FETCH_ATTRIBUTE = 'data-lazy-fetch';
/**
* Macros that can be expanded in json targeting attribute.
*/
const TARGETING_MACRO_ALLOWLIST = {
'CLIENT_ID': true,
};
/**
* Map of pageview tokens to the instances they belong to.
* @private {!Object<string, !AmpAdNetworkDoubleclickImpl>}
*/
let tokensToInstances = {};
/** @private {?Promise} */
let sraRequests = null;
/**
* The random subdomain to load SafeFrame from, if SafeFrame is
* being loaded from a random subdomain and if the subdomain
* has been generated.
* @private {?string}
*/
let safeFrameRandomSubdomain = null;
/** @typedef {{
adUrl: !Promise<string>,
lineItemId: string,
creativeId: string,
slotId: string,
slotIndex: string,
}} */
let TroubleshootDataDef;
/** @private {?JsonObject} */
let windowLocationQueryParameters;
/** @typedef {{width: number, height: number}} */
let SizeDef;
/** @typedef {(SizeDef|../../../src/layout-rect.LayoutRectDef)} */
let LayoutRectOrDimsDef;
/** @final */
export class AmpAdNetworkDoubleclickImpl extends AmpA4A {
/**
* @param {!Element} element
*/
constructor(element) {
super(element);
/**
* Config to generate amp-analytics element for active view reporting.
* @type {?JsonObject}
* @private
*/
this.ampAnalyticsConfig_ = null;
/** @private {!../../../src/service/extensions-impl.Extensions} */
this.extensions_ = Services.extensionsFor(this.win);
/** @private {?string} */
this.qqid_ = null;
/** @private {?LayoutRectOrDimsDef} */
this.initialSize_ = null;
/** @type {?string} */
this.parameterSize = null;
/** @private {?{width: number, height: number}} */
this.returnedSize_ = null;
/** @private {?Element} */
this.ampAnalyticsElement_ = null;
/** @type {?JsonObject|Object} */
this.jsonTargeting = null;
/** @type {string} */
this.adKey = '0';
/** @type {!Array<string>} */
this.experimentIds = [];
/** @protected {boolean} */
this.useSra = false;
/** @protected {?Deferred<?Response>} */
this.sraDeferred = null;
/** @private {?RefreshManager} */
this.refreshManager_ = null;
/** @private {number} */
this.refreshCount_ = 0;
/** @private {number} */
this.ifi_ = 0;
/** @private {boolean} */
this.isFluidRequest_ = false;
/**
* @private {boolean}
* Indicates that the primary size of the slot is fluid.
*/
this.isFluidPrimaryRequest_ = false;
/** @private {?string} */
this.fluidImpressionUrl_ = null;
/** @private {?Promise<!../../../ads/google/a4a/utils.IdentityToken>} */
this.identityTokenPromise_ = null;
/** @type {?../../../ads/google/a4a/utils.IdentityToken} */
this.identityToken = null;
/** @private {!TroubleshootDataDef} */
this.troubleshootData_ = /** @type {!TroubleshootDataDef} */ ({});
/**
* @private {?boolean} whether preferential rendered AMP creative, null
* indicates no creative render.
*/
this.isAmpCreative_ = null;
/** @private {boolean} */
this.isIdleRender_ = false;
/** @private {?./safeframe-host.SafeframeHostApi} */
this.safeframeApi_ = null;
/** @type {boolean} whether safeframe forced via tag */
this.forceSafeframe = false;
if ('forceSafeframe' in this.element.dataset) {
if (!/^(1|(true))$/i.test(this.element.dataset['forceSafeframe'])) {
user().warn(
TAG,
'Ignoring invalid data-force-safeframe attribute: ' +
this.element.dataset['forceSafeframe']
);
} else {
this.forceSafeframe = true;
}
}
/** @protected {ConsentTupleDef} */
this.consentTuple = {};
/** @protected {!Deferred<string>} */
this.getAdUrlDeferred = new Deferred();
/**
* @private {boolean}
* Set to true when initial expansion effort fails. If true, the slot will
* attempt to expand again when outside of the viewport.
*/
this.reattemptToExpandFluidCreative_ = false;
/**
* Whether or not the iframe containing the ad should be sandboxed via the
* "sandbox" attribute.
* @private {boolean}
*/
this.shouldSandbox_ = false;
/**
* Set after the ad request is built.
* @private {?FlexibleAdSlotDataTypeDef}
*/
this.flexibleAdSlotData_ = null;
/**
* If true, will add a z-index to flex ad slots upon expansion.
* @private {boolean}
*/
this.inZIndexHoldBack_ = false;
}
/**
* @return {number|boolean} render on idle configuration with false
* indicating disabled.
* @private
*/
getIdleRenderEnabled_() {
if (this.isIdleRender_) {
return this.isIdleRender_;
}
// Disable if publisher has indicated a non-default loading strategy.
if (this.element.getAttribute('data-loading-strategy')) {
return false;
}
const expVal = this.postAdResponseExperimentFeatures['render-idle-vp'];
const vpRange = parseInt(expVal, 10);
if (expVal && isNaN(vpRange)) {
// holdback branch sends non-numeric value.
return false;
}
return vpRange || 12;
}
/** @override */
idleRenderOutsideViewport() {
const vpRange = this.getIdleRenderEnabled_();
if (vpRange === false) {
return vpRange;
}
const renderOutsideViewport = this.renderOutsideViewport();
// False will occur when throttle in effect.
if (typeof renderOutsideViewport === 'boolean') {
return renderOutsideViewport;
}
this.isIdleRender_ = true;
// NOTE(keithwrightbos): handle race condition where previous
// idleRenderOutsideViewport marked slot as idle render despite never
// being schedule due to being beyond viewport max offset. If slot
// comes within standard outside viewport range, then ensure throttling
// will not be applied.
this.getResource()
.whenWithinViewport(renderOutsideViewport)
.then(() => (this.isIdleRender_ = false));
return vpRange;
}
/** @override */
isLayoutSupported(layout) {
this.isFluidPrimaryRequest_ = layout == Layout.FLUID;
this.isFluidRequest_ = this.isFluidRequest_ || this.isFluidPrimaryRequest_;
return this.isFluidPrimaryRequest_ || isLayoutSizeDefined(layout);
}
/** @override */
isValidElement() {
return this.isAmpAdElement();
}
/**
* Executes page level experiment diversion and pushes any experiment IDs
* onto this.experimentIds.
* @param {?string} urlExperimentId
* @visibleForTesting
*/
setPageLevelExperiments(urlExperimentId) {
let forcedExperimentId;
if (urlExperimentId) {
forcedExperimentId = {
// SRA
'7': DOUBLECLICK_SRA_EXP_BRANCHES.SRA_CONTROL,
'8': DOUBLECLICK_SRA_EXP_BRANCHES.SRA,
'9': DOUBLECLICK_SRA_EXP_BRANCHES.SRA_NO_RECOVER,
}[urlExperimentId];
if (forcedExperimentId) {
this.experimentIds.push(forcedExperimentId);
}
}
const experimentInfoList = /** @type {!Array<!../../../src/experiments.ExperimentInfo>} */ ([
{
experimentId: DOUBLECLICK_SRA_EXP,
isTrafficEligible: () =>
!forcedExperimentId &&
!this.win.document./*OK*/ querySelector(
'meta[name=amp-ad-enable-refresh], ' +
'amp-ad[type=doubleclick][data-enable-refresh], ' +
'meta[name=amp-ad-doubleclick-sra]'
),
branches: Object.keys(DOUBLECLICK_SRA_EXP_BRANCHES).map(
(key) => DOUBLECLICK_SRA_EXP_BRANCHES[key]
),
},
{
experimentId: ZINDEX_EXP,
isTrafficEligible: () => true,
branches: Object.values(ZINDEX_EXP_BRANCHES),
},
]);
const setExps = this.randomlySelectUnsetExperiments_(experimentInfoList);
Object.keys(setExps).forEach(
(expName) => setExps[expName] && this.experimentIds.push(setExps[expName])
);
const moduleNomoduleExpId = this.getModuleNomoduleExpIds_();
if (moduleNomoduleExpId) {
this.experimentIds.push(moduleNomoduleExpId);
}
if (setExps[ZINDEX_EXP] == ZINDEX_EXP_BRANCHES.HOLDBACK) {
this.inZIndexHoldBack_ = true;
}
}
/**
* For easier unit testing.
* @param {!Array<!../../../src/experiments.ExperimentInfo>} experimentInfoList
* @return {!Object<string, string>}
*/
randomlySelectUnsetExperiments_(experimentInfoList) {
return randomlySelectUnsetExperiments(this.win, experimentInfoList);
}
/**
* For easier unit testing.
* @return {?string}
*/
extractUrlExperimentId_() {
return extractUrlExperimentId(this.win, this.element);
}
/** @private */
maybeDeprecationWarn_() {
const warnDeprecation = (feature) =>
user().warn(
TAG,
`${feature} is no longer supported for DoubleClick.` +
'Please refer to ' +
'https://github.com/ampproject/amphtml/issues/11834 ' +
'for more information'
);
const usdrd = 'useSameDomainRenderingUntilDeprecated';
const hasUSDRD =
usdrd in this.element.dataset ||
(tryParseJson(this.element.getAttribute('json')) || {})[usdrd];
if (hasUSDRD) {
warnDeprecation(usdrd);
}
const useRemoteHtml =
this.getAmpDoc().getMetaByName('amp-3p-iframe-src') !== null;
if (useRemoteHtml) {
warnDeprecation('remote.html');
}
}
/** @override */
delayAdRequestEnabled() {
if (this.element.getAttribute(LAZY_FETCH_ATTRIBUTE) !== 'true') {
return false;
}
return getAmpAdRenderOutsideViewport(this.element) || 3;
}
/** @override */
buildCallback() {
super.buildCallback();
this.maybeDeprecationWarn_();
this.setPageLevelExperiments(this.extractUrlExperimentId_());
const pubEnabledSra = !!this.win.document.querySelector(
'meta[name=amp-ad-doubleclick-sra]'
);
const delayFetchEnabled = !!this.win.document.querySelector(
`amp-ad[type=doubleclick][${escapeCssSelectorIdent(
LAZY_FETCH_ATTRIBUTE
)}=true]`
);
if (pubEnabledSra && delayFetchEnabled) {
user().warn(
TAG,
'SRA is not compatible with lazy fetching, disabling SRA'
);
}
this.useSra =
!delayFetchEnabled &&
((getMode().localDev &&
/(\?|&)force_sra=true(&|$)/.test(this.win.location.search)) ||
pubEnabledSra ||
[
DOUBLECLICK_SRA_EXP_BRANCHES.SRA,
DOUBLECLICK_SRA_EXP_BRANCHES.SRA_NO_RECOVER,
].some((eid) => this.experimentIds.indexOf(eid) >= 0));
this.identityTokenPromise_ = this.getAmpDoc()
.whenFirstVisible()
.then(() =>
getIdentityToken(this.win, this.getAmpDoc(), super.getConsentPolicy())
);
this.troubleshootData_.slotId = this.element.getAttribute('data-slot');
this.troubleshootData_.slotIndex = this.element.getAttribute(
'data-amp-slot-index'
);
if (!this.isFluidRequest_) {
const multiSizeStr = this.element.getAttribute('data-multi-size');
this.isFluidRequest_ =
!!multiSizeStr && multiSizeStr.indexOf('fluid') != -1;
}
}
/** @override */
shouldPreferentialRenderWithoutCrypto() {
devAssert(!isCdnProxy(this.win));
return true;
}
/**
* @param {?ConsentTupleDef} consentTuple
* @param {!Array<!AmpAdNetworkDoubleclickImpl>=} instances
* @return {!Object<string,string|boolean|number>}
* @visibleForTesting
*/
getPageParameters(consentTuple, instances) {
instances = instances || [this];
const tokens = getPageviewStateTokensForAdRequest(instances);
const {consentString, gdprApplies} = consentTuple;
return {
'npa':
consentTuple.consentState == CONSENT_POLICY_STATE.INSUFFICIENT ||
consentTuple.consentState == CONSENT_POLICY_STATE.UNKNOWN
? 1
: null,
'gdfp_req': '1',
'sfv': DEFAULT_SAFEFRAME_VERSION,
'u_sd': WindowInterface.getDevicePixelRatio(),
'gct': this.getLocationQueryParameterValue('google_preview') || null,
'psts': tokens.length ? tokens : null,
'gdpr': gdprApplies === true ? '1' : gdprApplies === false ? '0' : null,
'gdpr_consent': consentString,
};
}
/**
* Constructs block-level url parameters.
* @return {!Object<string,string|boolean|number>}
*/
getBlockParameters_() {
devAssert(this.initialSize_);
devAssert(this.jsonTargeting);
const tfcd = this.jsonTargeting && this.jsonTargeting[TFCD];
this.win['ampAdGoogleIfiCounter'] = this.win['ampAdGoogleIfiCounter'] || 1;
this.ifi_ =
(this.isRefreshing && this.ifi_) || this.win['ampAdGoogleIfiCounter']++;
const pageLayoutBox = this.isSinglePageStoryAd
? this.element.getPageLayoutBox()
: null;
let msz = null;
let psz = null;
let fws = null;
this.flexibleAdSlotData_ = getFlexibleAdSlotData(
this.win,
this.element.parentElement
);
const {fwSignal, slotWidth, parentWidth} = this.flexibleAdSlotData_;
// If slotWidth is -1, that means its width must be determined by its
// parent container, and so should have the same value as parentWidth.
msz = `${slotWidth == -1 ? parentWidth : slotWidth}x-1`;
psz = `${parentWidth}x-1`;
fws = fwSignal ? fwSignal : '0';
return {
'iu': this.element.getAttribute('data-slot'),
'co':
this.jsonTargeting && this.jsonTargeting['cookieOptOut'] ? '1' : null,
'adk': this.adKey,
'sz': this.isSinglePageStoryAd ? '1x1' : this.parameterSize,
'output': 'html',
'impl': 'ifr',
'tfcd': tfcd == undefined ? null : tfcd,
'adtest': isInManualExperiment(this.element) ? 'on' : null,
'ifi': this.ifi_,
'rc': this.refreshCount_ || null,
'frc': Number(this.fromResumeCallback) || null,
'fluid': this.isFluidRequest_ ? 'height' : null,
'fsf': this.forceSafeframe ? '1' : null,
'msz': msz,
'psz': psz,
'fws': fws,
'scp': serializeTargeting(
(this.jsonTargeting && this.jsonTargeting['targeting']) || null,
(this.jsonTargeting && this.jsonTargeting['categoryExclusions']) ||
null,
null
),
'spsa': this.isSinglePageStoryAd
? `${pageLayoutBox.width}x${pageLayoutBox.height}`
: null,
...googleBlockParameters(this),
};
}
/**
* Populate's block-level state for ad URL construction.
* Sets initialSize_ , jsonTargeting, and adKey member fields.
* @param {ConsentTupleDef} consentTuple
* @visibleForTesting
*/
populateAdUrlState(consentTuple) {
this.consentTuple = consentTuple;
// Allow for pub to override height/width via override attribute.
const width =
Number(this.element.getAttribute('data-override-width')) ||
Number(this.element.getAttribute('width'));
const height =
Number(this.element.getAttribute('data-override-height')) ||
Number(this.element.getAttribute('height'));
this.initialSize_ = this.isFluidPrimaryRequest_
? {width: 0, height: 0}
: width && height
? // width/height could be 'auto' in which case we fallback to measured.
{width, height}
: this.getIntersectionElementLayoutBox();
this.jsonTargeting = tryParseJson(this.element.getAttribute('json')) || {};
this.adKey = this.generateAdKey_(
`${this.initialSize_.width}x${this.initialSize_.height}`
);
this.parameterSize = this.getParameterSize_();
}
/** @override */
getConsentPolicy() {
// Ensure that build is not blocked by need for consent (delay will occur
// prior to RTC & ad URL construction).
return null;
}
/** @override */
getAdUrl(opt_consentTuple, opt_rtcResponsesPromise) {
if (this.useSra) {
this.sraDeferred = this.sraDeferred || new Deferred();
}
const consentTuple = opt_consentTuple || {};
if (
consentTuple.consentState == CONSENT_POLICY_STATE.UNKNOWN &&
this.element.getAttribute('data-npa-on-unknown-consent') != 'true'
) {
user().info(TAG, 'Ad request suppressed due to unknown consent');
this.getAdUrlDeferred.resolve('');
return Promise.resolve('');
}
if (this.iframe && !this.isRefreshing) {
dev().warn(TAG, `Frame already exists, sra: ${this.useSra}`);
this.getAdUrlDeferred.resolve('');
return Promise.resolve('');
}
opt_rtcResponsesPromise = opt_rtcResponsesPromise || Promise.resolve();
// TODO(keithwrightbos): SRA blocks currently unnecessarily generate full
// ad url. This could be optimized however non-SRA ad url is required to
// fallback to non-SRA if single block.
this.populateAdUrlState(consentTuple);
// TODO: Check for required and allowed parameters. Probably use
// validateData, from 3p/3p/js, after moving it someplace common.
const startTime = Date.now();
const timerService = Services.timerFor(this.win);
const identityPromise = timerService
.timeoutPromise(1000, this.identityTokenPromise_)
.catch(() => {
// On error/timeout, proceed.
return /**@type {!../../../ads/google/a4a/utils.IdentityToken}*/ ({});
});
const checkStillCurrent = this.verifyStillCurrent();
const rtcParamsPromise = opt_rtcResponsesPromise.then((results) => {
checkStillCurrent();
return this.mergeRtcResponses_(results);
});
const targetingExpansionPromise = timerService
.timeoutPromise(1000, this.expandJsonTargeting_(rtcParamsPromise))
.catch(() => {
dev().warn(TAG, 'JSON Targeting expansion failed/timed out.');
});
Promise.all([
rtcParamsPromise,
identityPromise,
targetingExpansionPromise,
]).then((results) => {
checkStillCurrent();
const rtcParams = results[0];
this.identityToken = results[1];
googleAdUrl(
this,
DOUBLECLICK_BASE_URL,
startTime,
Object.assign(
this.getBlockParameters_(),
this.buildIdentityParams(),
this.getPageParameters(consentTuple, /* instances= */ undefined),
rtcParams
),
this.experimentIds
).then((adUrl) => this.getAdUrlDeferred.resolve(adUrl));
});
this.troubleshootData_.adUrl = this.getAdUrlDeferred.promise;
return this.getAdUrlDeferred.promise;
}
/**
* Waits for RTC to complete, then overwrites json attr targeting values
* with expanded vars.
* @param {!Promise} rtcMergedPromise
* @return {!Promise}
*/
expandJsonTargeting_(rtcMergedPromise) {
return rtcMergedPromise.then(() => {
const targeting = this.jsonTargeting['targeting'];
if (!targeting) {
return Promise.resolve();
}
const expansionPromises = Object.keys(targeting).map((key) =>
this.expandValue_(targeting[key]).then((expanded) => {
targeting[key] = expanded;
})
);
return Promise.all(expansionPromises);
});
}
/**
* Expands json targeting values.
* @param {string|Array<string>|null} value
* @return {!Promise<string>|!Promise<Array<string>>}
*/
expandValue_(value) {
if (!value) {
return Promise.resolve(value);
}
if (isArray(value)) {
return Promise.all(
value.map((arrVal) => this.expandString_(dev().assertString(arrVal)))
);
}
return this.expandString_(dev().assertString(value));
}
/**
* Expands macros in strings.
* @param {string} string
* @return {!Promise<string>}
*/
expandString_(string) {
return Services.urlReplacementsForDoc(
this.element
)./*OK*/ expandStringAsync(
string,
undefined /*opt_bindings*/,
TARGETING_MACRO_ALLOWLIST
);
}
/**
* Converts identity token response to ad request parameters.
* @return {!Object<string,string>}
*/
buildIdentityParams() {
return this.identityToken
? {
adsid: this.identityToken.token || null,
jar: this.identityToken.jar || null,
pucrd: this.identityToken.pucrd || null,
}
: {};
}
/**
* Merges all of the rtcResponses into the JSON targeting and
* category exclusions.
* @param {?Array<!rtcResponseDef>} rtcResponseArray
* @return {?Object|undefined}
* @private
*/
mergeRtcResponses_(rtcResponseArray) {
if (!rtcResponseArray) {
return null;
}
const artc = [];
const ati = [];
const ard = [];
let exclusions;
rtcResponseArray.forEach((rtcResponse) => {
if (!rtcResponse) {
return;
}
artc.push(rtcResponse.rtcTime);
ati.push(rtcResponse.error || RTC_SUCCESS);
ard.push(rtcResponse.callout);
if (rtcResponse.response) {
if (rtcResponse.response['targeting']) {
const rewrittenResponse = this.rewriteRtcKeys_(
rtcResponse.response['targeting'],
rtcResponse.callout
);
this.jsonTargeting['targeting'] = !!this.jsonTargeting['targeting']
? deepMerge(this.jsonTargeting['targeting'], rewrittenResponse)
: rewrittenResponse;
}
if (rtcResponse.response['categoryExclusions']) {
if (!exclusions) {
exclusions = {};
if (this.jsonTargeting['categoryExclusions']) {
/** @type {!Array} */ (this.jsonTargeting[
'categoryExclusions'
]).forEach((exclusion) => {
exclusions[exclusion] = true;
});
}
}
/** @type {!Array} */ (rtcResponse.response[
'categoryExclusions'
]).forEach((exclusion) => {
exclusions[exclusion] = true;
});
}
}
});
if (exclusions) {
this.jsonTargeting['categoryExclusions'] = Object.keys(exclusions);
}
return {'artc': artc.join() || null, 'ati': ati.join(), 'ard': ard.join()};
}
/** @override */
getCustomRealTimeConfigMacros_() {
/**
* This lists allowed attributes on the amp-ad element to be used as
* macros for constructing the RTC URL. Add attributes here, in lowercase,
* to make them available.
*/
const allowlist = {
'height': true,
'width': true,
'data-slot': true,
'data-multi-size': true,
'data-multi-size-validation': true,
'data-override-width': true,
'data-override-height': true,
'data-amp-slot-index': true,
};
return {
PAGEVIEWID: () => Services.documentInfoForDoc(this.element).pageViewId,
PAGEVIEWID_64: () =>
Services.documentInfoForDoc(this.element).pageViewId64,
HREF: () => this.win.location.href,
REFERRER: (opt_timeout) => this.getReferrer_(opt_timeout),
TGT: () =>
JSON.stringify(
(tryParseJson(this.element.getAttribute('json')) || {})['targeting']
),
ADCID: (opt_timeout) =>
getOrCreateAdCid(
this.getAmpDoc(),
'AMP_ECID_GOOGLE',
'_ga',
parseInt(opt_timeout, 10)
),
ATTR: (name) => {
if (!allowlist[name.toLowerCase()]) {
dev().warn('TAG', `Invalid attribute ${name}`);
} else {
return this.element.getAttribute(name);
}
},
ELEMENT_POS: () => this.element.getPageLayoutBox().top,
SCROLL_TOP: () =>
Services.viewportForDoc(this.getAmpDoc()).getScrollTop(),
PAGE_HEIGHT: () =>
Services.viewportForDoc(this.getAmpDoc()).getScrollHeight(),
BKG_STATE: () => (this.getAmpDoc().isVisible() ? 'visible' : 'hidden'),
CANONICAL_URL: () =>
Services.documentInfoForDoc(this.element).canonicalUrl,
};
}
/**
* Returns the referrer or undefined if the referrer is not resolved
* before the given timeout
* @param {number=} opt_timeout
* @return {!(Promise<string>|Promise<undefined>)} A promise with a referrer or undefined
* if timed out
* @private
*/
getReferrer_(opt_timeout) {
const timeoutInt = parseInt(opt_timeout, 10);
const referrerPromise = Services.viewerForDoc(
this.getAmpDoc()
).getReferrerUrl();
if (isNaN(timeoutInt) || timeoutInt < 0) {
return referrerPromise;
}
return Services.timerFor(this.win)
.timeoutPromise(timeoutInt, referrerPromise)
.catch(() => undefined);
}
/**
* Appends the callout value to the keys of response to prevent a collision
* case caused by multiple vendors returning the same keys.
* @param {!Object<string, string>} response
* @param {string} callout
* @return {!Object<string, string>}
* @private
*/
rewriteRtcKeys_(response, callout) {
// Only perform this substitution for vendor-defined URLs.
if (!RTC_VENDORS[callout] || RTC_VENDORS[callout].disableKeyAppend) {
return response;
}
const newResponse = {};
Object.keys(response).forEach((key) => {
newResponse[`${key}_${callout}`] = response[key];
});
return newResponse;
}
/** @override */
onNetworkFailure(error, adUrl) {
dev().info(TAG, 'network error, attempt adding of error parameter', error);
return {adUrl: maybeAppendErrorParameter(adUrl, 'n')};
}
/** @override */
maybeValidateAmpCreative(bytes, headers) {
if (headers.get('AMP-Verification-Checksum-Algorithm') !== 'djb2a-32') {
return super.maybeValidateAmpCreative(bytes, headers);
}
const checksum = headers.get('AMP-Verification-Checksum');
return Promise.resolve(
checksum && stringHash32(utf8Decode(bytes)) == checksum ? bytes : null
);
}
/** @override */
extractSize(responseHeaders) {
this.ampAnalyticsConfig_ = extractAmpAnalyticsConfig(this, responseHeaders);
this.qqid_ = responseHeaders.get(QQID_HEADER);
this.shouldSandbox_ = responseHeaders.get(SANDBOX_HEADER) == 'true';
this.troubleshootData_.creativeId = dev().assertString(
responseHeaders.get('google-creative-id') || '-1'
);
this.troubleshootData_.lineItemId = dev().assertString(
responseHeaders.get('google-lineitem-id') || '-1'
);
if (this.ampAnalyticsConfig_) {
// Load amp-analytics extensions
this.extensions_./*OK*/ installExtensionForDoc(
this.getAmpDoc(),
'amp-analytics'
);
}
// If the server returned a size, use that, otherwise use the size that we
// sent in the ad request.
let size = super.extractSize(responseHeaders);
if (size) {
this.returnedSize_ = size;
this.handleResize_(size.width, size.height);
} else {
size = this.getSlotSize();
}
// If this is a multi-size creative, fire delayed impression now. If it's
// fluid, wait until after resize happens.
if (this.isFluidRequest_ && !this.returnedSize_) {
this.fluidImpressionUrl_ = responseHeaders.get('X-AmpImps');