diff --git a/ads/google/a4a/performance.js b/ads/google/a4a/performance.js index cfd9ef3d6eea..545717ed5ddb 100644 --- a/ads/google/a4a/performance.js +++ b/ads/google/a4a/performance.js @@ -20,10 +20,8 @@ import {dev} from '../../../src/log'; import {dict} from '../../../src/utils/object'; import {serializeQueryString} from '../../../src/url'; import {getTimingDataSync} from '../../../src/service/variable-source'; -import {urlReplacementsForDoc} from '../../../src/services'; -import {viewerForDoc} from '../../../src/services'; +import {Services} from '../../../src/services'; import {CommonSignals} from '../../../src/common-signals'; -import {analyticsForDoc} from '../../../src/services'; /** * This module provides a fairly crude form of performance monitoring (or @@ -174,10 +172,10 @@ export class GoogleAdLifecycleReporter extends BaseLifecycleReporter { * @private {!../../../src/service/url-replacements-impl.UrlReplacements} * @const */ - this.urlReplacer_ = urlReplacementsForDoc(element); + this.urlReplacer_ = Services.urlReplacementsForDoc(element); /** @const @private {!../../../src/service/viewer-impl.Viewer} */ - this.viewer_ = viewerForDoc(element); + this.viewer_ = Services.viewerForDoc(element); } /** @@ -275,7 +273,7 @@ export class GoogleAdLifecycleReporter extends BaseLifecycleReporter { * @override */ addPingsForVisibility(element) { - analyticsForDoc(element, true).then(analytics => { + Services.analyticsForDoc(element, true).then(analytics => { const signals = element.signals(); const readyPromise = Promise.race([ signals.whenSignal(CommonSignals.INI_LOAD), diff --git a/ads/google/a4a/test/test-google-ads-a4a-config.js b/ads/google/a4a/test/test-google-ads-a4a-config.js index 674e300c353b..ca8d9eab829f 100644 --- a/ads/google/a4a/test/test-google-ads-a4a-config.js +++ b/ads/google/a4a/test/test-google-ads-a4a-config.js @@ -14,7 +14,7 @@ * limitations under the License. */ -import {ampdocServiceFor} from '../../../../src/services'; +import {Services} from '../../../../src/services'; import {installDocService} from '../../../../src/service/ampdoc-impl'; import { googleAdsIsA4AEnabled, @@ -118,7 +118,7 @@ describe('a4a_config', () => { }; win.document.defaultView = win; installDocService(win, /* isSingleDoc */ true); - const ampdoc = ampdocServiceFor(win).getAmpDoc(); + const ampdoc = Services.ampdocServiceFor(win).getAmpDoc(); events = {}; installDocumentStateService(win); installPlatformService(win); @@ -340,7 +340,7 @@ describe('a4a_config hash param parsing', () => { }; win.document.defaultView = win; installDocService(win, /* isSingleDoc */ true); - ampdoc = ampdocServiceFor(win).getAmpDoc(); + ampdoc = Services.ampdocServiceFor(win).getAmpDoc(); events = {}; installPlatformService(win); installDocumentStateService(win); diff --git a/ads/google/a4a/test/test-performance.js b/ads/google/a4a/test/test-performance.js index e9e7bfa0f220..8e1be1c430f8 100644 --- a/ads/google/a4a/test/test-performance.js +++ b/ads/google/a4a/test/test-performance.js @@ -19,7 +19,7 @@ import { BaseLifecycleReporter, } from '../performance'; import {createIframePromise} from '../../../../testing/iframe'; -import {viewerForDoc} from '../../../../src/services'; +import {Services} from '../../../../src/services'; import * as sinon from 'sinon'; /** @@ -80,7 +80,7 @@ describe('GoogleAdLifecycleReporter', () => { iframe = createIframePromise(false).then(iframeFixture => { const win = iframeFixture.win; const doc = iframeFixture.doc; - const viewer = viewerForDoc(doc); + const viewer = Services.viewerForDoc(doc); const elem = doc.createElement('div'); doc.body.appendChild(elem); const reporter = new GoogleAdLifecycleReporter(win, elem, 42); diff --git a/ads/google/a4a/test/test-traffic-experiments.js b/ads/google/a4a/test/test-traffic-experiments.js index 9af4d360a0bb..6e7899bb4f85 100644 --- a/ads/google/a4a/test/test-traffic-experiments.js +++ b/ads/google/a4a/test/test-traffic-experiments.js @@ -14,7 +14,7 @@ * limitations under the License. */ -import {ampdocServiceFor} from '../../../../src/services'; +import {Services} from '../../../../src/services'; import {installDocService} from '../../../../src/service/ampdoc-impl'; import { addExperimentIdToElement, @@ -322,7 +322,7 @@ describe('all-traffic-experiments-tests', () => { }; win.document.defaultView = win; installDocService(win, /* isSingleDoc */ true); - const ampdoc = ampdocServiceFor(win).getAmpDoc(); + const ampdoc = Services.ampdocServiceFor(win).getAmpDoc(); events = {}; installDocumentStateService(win); installPlatformService(win); diff --git a/ads/google/a4a/traffic-experiments.js b/ads/google/a4a/traffic-experiments.js index ea349192a3c2..e185bbc5b3fc 100644 --- a/ads/google/a4a/traffic-experiments.js +++ b/ads/google/a4a/traffic-experiments.js @@ -34,10 +34,7 @@ import { randomlySelectUnsetExperiments, } from '../../../src/experiments'; import {dev} from '../../../src/log'; -import { - viewerForDoc, - performanceForOrNull, -} from '../../../src/services'; +import {Services} from '../../../src/services'; import {parseQueryString} from '../../../src/url'; /** @typedef {{ @@ -115,7 +112,7 @@ export function googleAdsIsA4AEnabled(win, element, experimentName, const selectedBranch = getExperimentBranch(win, experimentName); if (selectedBranch) { addExperimentIdToElement(selectedBranch, element); - const perf = performanceForOrNull(win); + const perf = Services.performanceForOrNull(win); if (perf) { perf.addEnabledExperiment(experimentName + '-' + selectedBranch); } @@ -146,7 +143,7 @@ export function googleAdsIsA4AEnabled(win, element, experimentName, * @return {?string} experiment extracted from page url. */ export function extractUrlExperimentId(win, element) { - const expParam = viewerForDoc(element).getParam('exp') || + const expParam = Services.viewerForDoc(element).getParam('exp') || parseQueryString(win.location.search)['exp']; if (!expParam) { return null; diff --git a/ads/google/a4a/utils.js b/ads/google/a4a/utils.js index 64e9652d2f26..61d27e1db55f 100644 --- a/ads/google/a4a/utils.js +++ b/ads/google/a4a/utils.js @@ -14,21 +14,16 @@ * limitations under the License. */ +import {Services} from '../../../src/services'; import {buildUrl} from './url-builder'; import {makeCorrelator} from '../correlator'; import {isCanary} from '../../../src/experiments'; import {getOrCreateAdCid} from '../../../src/ad-cid'; -import {documentInfoForDoc} from '../../../src/services'; import {dev} from '../../../src/log'; import {dict} from '../../../src/utils/object'; import {getMode} from '../../../src/mode'; import {isProxyOrigin, parseUrl} from '../../../src/url'; import {parseJson} from '../../../src/json'; -import { - resourcesForDoc, - viewerForDoc, - viewportForDoc, -} from '../../../src/services'; import {domFingerprint} from '../../../src/utils/dom-fingerprint'; import { isExperimentOn, @@ -177,7 +172,7 @@ export function googleBlockParameters(a4a, opt_experimentIds) { * @return {!Promise>>>} */ export function groupAmpAdsByType(win, type, groupFn) { - return resourcesForDoc(win.document).getMeasuredResources(win, + return Services.resourcesForDoc(win.document).getMeasuredResources(win, r => r.element.tagName == 'AMP-AD' && r.element.getAttribute('type') == type) .then(resources => { @@ -198,15 +193,15 @@ export function groupAmpAdsByType(win, type, groupFn) { * @return {!Promise>} */ export function googlePageParameters(win, doc, startTime, output = 'html') { - const referrerPromise = viewerForDoc(doc).getReferrerUrl(); + const referrerPromise = Services.viewerForDoc(doc).getReferrerUrl(); return getOrCreateAdCid(doc, 'AMP_ECID_GOOGLE', '_ga') .then(clientId => referrerPromise.then(referrer => { - const documentInfo = documentInfoForDoc(doc); + const documentInfo = Services.documentInfoForDoc(doc); // Read by GPT for GA/GPT integration. win.gaGlobal = win.gaGlobal || {cid: clientId, hid: documentInfo.pageViewId}; const screen = win.screen; - const viewport = viewportForDoc(doc); + const viewport = Services.viewportForDoc(doc); const viewportRect = viewport.getRect(); const viewportSize = viewport.getSize(); return { @@ -368,7 +363,8 @@ function elapsedTimeWithCeiling(time, start) { export function getCorrelator(win, opt_cid, opt_nodeOrDoc) { if (!win.ampAdPageCorrelator) { win.ampAdPageCorrelator = makeCorrelator( - opt_cid, documentInfoForDoc(opt_nodeOrDoc || win.document).pageViewId); + opt_cid, + Services.documentInfoForDoc(opt_nodeOrDoc || win.document).pageViewId); } return win.ampAdPageCorrelator; } diff --git a/builtins/amp-pixel.js b/builtins/amp-pixel.js index addebf6f4089..e7a52e4b5aae 100644 --- a/builtins/amp-pixel.js +++ b/builtins/amp-pixel.js @@ -18,9 +18,7 @@ import {BaseElement} from '../src/base-element'; import {dev, user} from '../src/log'; import {dict} from '../src/utils/object'; import {registerElement} from '../src/custom-element'; -import {timerFor} from '../src/services'; -import {urlReplacementsForDoc} from '../src/services'; -import {viewerForDoc} from '../src/services'; +import {Services} from '../src/services'; import {createElementWithAttributes} from '../src/dom'; const TAG = 'amp-pixel'; @@ -61,7 +59,7 @@ export class AmpPixel extends BaseElement { + ' Only "no-referrer" is supported'); } // Trigger, but only when visible. - const viewer = viewerForDoc(this.getAmpDoc()); + const viewer = Services.viewerForDoc(this.getAmpDoc()); viewer.whenFirstVisible().then(this.trigger_.bind(this)); } @@ -77,12 +75,12 @@ export class AmpPixel extends BaseElement { } // Delay(1) provides a rudimentary "idle" signal. // TODO(dvoytenko): use an improved idle signal when available. - this.triggerPromise_ = timerFor(this.win).promise(1).then(() => { + this.triggerPromise_ = Services.timerFor(this.win).promise(1).then(() => { const src = this.element.getAttribute('src'); if (!src) { return; } - return urlReplacementsForDoc(this.element) + return Services.urlReplacementsForDoc(this.element) .expandAsync(this.assertSource_(src)) .then(src => { const pixel = this.referrerPolicy_ diff --git a/extensions/amp-3q-player/0.1/amp-3q-player.js b/extensions/amp-3q-player/0.1/amp-3q-player.js index 9e05e0733a4b..bfa541f1b616 100644 --- a/extensions/amp-3q-player/0.1/amp-3q-player.js +++ b/extensions/amp-3q-player/0.1/amp-3q-player.js @@ -24,7 +24,7 @@ import { import {isObject} from '../../../src/types'; import {listen, getData} from '../../../src/event-helper'; import {VideoEvents} from '../../../src/video-interface'; -import {videoManagerForDoc} from '../../../src/services'; +import {Services} from '../../../src/services'; /** * @implements {../../../src/video-interface.VideoInterface} @@ -71,7 +71,7 @@ class Amp3QPlayer extends AMP.BaseElement { }); installVideoManagerForDoc(this.element); - videoManagerForDoc(this.element).register(this); + Services.videoManagerForDoc(this.element).register(this); } /** @override */ diff --git a/extensions/amp-3q-player/0.1/test/test-amp-3q-player.js b/extensions/amp-3q-player/0.1/test/test-amp-3q-player.js index 9bda7e6b435e..cb8996f4e811 100644 --- a/extensions/amp-3q-player/0.1/test/test-amp-3q-player.js +++ b/extensions/amp-3q-player/0.1/test/test-amp-3q-player.js @@ -21,7 +21,7 @@ import { import '../amp-3q-player'; import {listenOncePromise} from '../../../../src/event-helper'; import {adopt} from '../../../../src/runtime'; -import {timerFor} from '../../../../src/services'; +import {Services} from '../../../../src/services'; import {VideoEvents} from '../../../../src/video-interface'; import * as sinon from 'sinon'; @@ -30,7 +30,7 @@ adopt(window); describe('amp-3q-player', function() { this.timeout(10000); let sandbox; - const timer = timerFor(window); + const timer = Services.timerFor(window); beforeEach(() => { sandbox = sinon.sandbox.create(); diff --git a/extensions/amp-a4a/0.1/a4a-variable-source.js b/extensions/amp-a4a/0.1/a4a-variable-source.js index 46a2ea894a49..86e7b652b0d0 100644 --- a/extensions/amp-a4a/0.1/a4a-variable-source.js +++ b/extensions/amp-a4a/0.1/a4a-variable-source.js @@ -14,7 +14,7 @@ * limitations under the License. */ -import {urlReplacementsForDoc} from '../../../src/services'; +import {Services} from '../../../src/services'; import { VariableSource, getNavigationData, @@ -76,7 +76,7 @@ export class A4AVariableSource extends VariableSource { constructor(ampdoc, embedWin) { super(); /** @private {VariableSource} global variable source for fallback. */ - this.globalVariableSource_ = urlReplacementsForDoc(ampdoc) + this.globalVariableSource_ = Services.urlReplacementsForDoc(ampdoc) .getVariableSource(); /** @private {!Window} */ diff --git a/extensions/amp-a4a/0.1/amp-a4a.js b/extensions/amp-a4a/0.1/amp-a4a.js index ecc386388c0a..ce5645e0b730 100644 --- a/extensions/amp-a4a/0.1/amp-a4a.js +++ b/extensions/amp-a4a/0.1/amp-a4a.js @@ -14,6 +14,7 @@ * limitations under the License. */ +import {Services} from '../../../src/services'; import { verifyHashVersion, LegacySignatureVerifier, @@ -43,10 +44,7 @@ import {isArray, isObject, isEnumValue} from '../../../src/types'; import {some} from '../../../src/utils/promise'; import {base64UrlDecodeToBytes} from '../../../src/utils/base64'; import {utf8Decode} from '../../../src/utils/bytes'; -import {viewerForDoc} from '../../../src/services'; -import {xhrFor} from '../../../src/services'; import {endsWith} from '../../../src/string'; -import {platformFor} from '../../../src/services'; import {isExperimentOn} from '../../../src/experiments'; import {setStyle} from '../../../src/style'; import {assertHttpsUrl} from '../../../src/url'; @@ -59,7 +57,6 @@ import { import { installUrlReplacementsForEmbed, } from '../../../src/service/url-replacements-impl'; -import {extensionsFor} from '../../../src/services'; import {A4AVariableSource} from './a4a-variable-source'; // TODO(tdrl): Temporary. Remove when we migrate to using amp-analytics. import {getTimingDataAsync} from '../../../src/service/variable-source'; @@ -289,7 +286,7 @@ export class AmpA4A extends AMP.BaseElement { * @private {?XORIGIN_MODE} */ this.experimentalNonAmpCreativeRenderMethod_ = - platformFor(this.win).isIos() ? XORIGIN_MODE.SAFEFRAME : null; + Services.platformFor(this.win).isIos() ? XORIGIN_MODE.SAFEFRAME : null; /** * Gets a notion of current time, in ms. The value is not necessarily @@ -572,7 +569,7 @@ export class AmpA4A extends AMP.BaseElement { // - Rendering fails => return false // - Chain cancelled => don't return; drop error // - Uncaught error otherwise => don't return; percolate error up - this.adPromise_ = viewerForDoc(this.getAmpDoc()).whenFirstVisible() + this.adPromise_ = Services.viewerForDoc(this.getAmpDoc()).whenFirstVisible() .then(() => { checkStillCurrent(); // See if experiment that delays request until slot is within @@ -739,7 +736,7 @@ export class AmpA4A extends AMP.BaseElement { this.updatePriority(0); // Load any extensions; do not wait on their promises as this // is just to prefetch. - const extensions = extensionsFor(this.win); + const extensions = Services.extensionsFor(this.win); creativeMetaDataDef.customElementExtensions.forEach( extensionId => extensions.loadExtension(extensionId)); return creativeMetaDataDef; @@ -1018,7 +1015,7 @@ export class AmpA4A extends AMP.BaseElement { this.isVerifiedAmpCreative_ = false; this.fromResumeCallback = false; this.experimentalNonAmpCreativeRenderMethod_ = - platformFor(this.win).isIos() ? XORIGIN_MODE.SAFEFRAME : null; + Services.platformFor(this.win).isIos() ? XORIGIN_MODE.SAFEFRAME : null; if (this.xOriginIframeHandler_) { this.xOriginIframeHandler_.freeXOriginIframe(); this.xOriginIframeHandler_ = null; @@ -1176,7 +1173,7 @@ export class AmpA4A extends AMP.BaseElement { method: 'GET', credentials: 'include', }; - return xhrFor(this.win) + return Services.xhrFor(this.win) .fetch(adUrl, xhrInit) .catch(unusedReason => { // If an error occurs, let the ad be rendered via iframe after delay. @@ -1214,8 +1211,8 @@ export class AmpA4A extends AMP.BaseElement { const currServiceName = serviceName; if (url) { // Delay request until document is not in a prerender state. - return viewerForDoc(this.getAmpDoc()).whenFirstVisible() - .then(() => xhrFor(this.win).fetchJson(url, { + return Services.viewerForDoc(this.getAmpDoc()).whenFirstVisible() + .then(() => Services.xhrFor(this.win).fetchJson(url, { mode: 'cors', method: 'GET', // Set ampCors false so that __amp_source_origin is not @@ -1444,7 +1441,7 @@ export class AmpA4A extends AMP.BaseElement { renderViaCachedContentIframe_(adUrl) { this.protectedEmitLifecycleEvent_('renderCrossDomainStart'); return this.iframeRenderHelper_(dict({ - 'src': xhrFor(this.win).getCorsUrl(this.win, adUrl), + 'src': Services.xhrFor(this.win).getCorsUrl(this.win, adUrl), 'name': JSON.stringify( getContextMetadata(this.win, this.element, this.sentinel)), })); @@ -1599,7 +1596,7 @@ export class AmpA4A extends AMP.BaseElement { } iframeWin.document.documentElement.addEventListener('click', event => { handleClick(event, url => { - viewerForDoc(this.getAmpDoc()).navigateTo(url, 'a4a'); + Services.viewerForDoc(this.getAmpDoc()).navigateTo(url, 'a4a'); }); }); } diff --git a/extensions/amp-a4a/0.1/legacy-signature-verifier.js b/extensions/amp-a4a/0.1/legacy-signature-verifier.js index 4b63840a0cbe..874431fef118 100644 --- a/extensions/amp-a4a/0.1/legacy-signature-verifier.js +++ b/extensions/amp-a4a/0.1/legacy-signature-verifier.js @@ -14,7 +14,7 @@ * limitations under the License. */ -import {cryptoFor} from '../../../src/services'; +import {Services} from '../../../src/services'; import {base64UrlDecodeToBytes} from '../../../src/utils/base64'; /** @@ -36,7 +36,7 @@ export class LegacySignatureVerifier { /** @param {!Window} win */ constructor(win) { /** @private @const {!../../../src/service/crypto-impl.Crypto} */ - this.crypto_ = cryptoFor(win); + this.crypto_ = Services.cryptoFor(win); } /** diff --git a/extensions/amp-a4a/0.1/test/test-amp-a4a.js b/extensions/amp-a4a/0.1/test/test-amp-a4a.js index 107bb519d65d..bea156461fff 100644 --- a/extensions/amp-a4a/0.1/test/test-amp-a4a.js +++ b/extensions/amp-a4a/0.1/test/test-amp-a4a.js @@ -39,12 +39,8 @@ import {FetchResponseHeaders} from '../../../../src/service/xhr-impl'; import {base64UrlDecodeToBytes} from '../../../../src/utils/base64'; import {utf8Encode} from '../../../../src/utils/bytes'; import {resetScheduledElementForTesting} from '../../../../src/custom-element'; -import { - ampdocServiceFor, - urlReplacementsForDoc, -} from '../../../../src/services'; +import {Services} from '../../../../src/services'; import {incrementLoadingAds} from '../../../amp-ad/0.1/concurrent-load'; -import {platformFor, timerFor} from '../../../../src/services'; import '../../../../extensions/amp-ad/0.1/amp-ad-xorigin-iframe-handler'; import {dev, user} from '../../../../src/log'; import {createElementWithAttributes} from '../../../../src/dom'; @@ -125,7 +121,7 @@ describe('amp-a4a', () => { 'type': 'adsense', }); element.getAmpDoc = () => { - const ampdocService = ampdocServiceFor(doc.defaultView); + const ampdocService = Services.ampdocServiceFor(doc.defaultView); return ampdocService.getAmpDoc(element); }; element.isBuilt = () => {return true;}; @@ -271,7 +267,7 @@ describe('amp-a4a', () => { }); it('for ios defaults to SafeFrame rendering', () => { - const platform = platformFor(fixture.win); + const platform = Services.platformFor(fixture.win); sandbox.stub(platform, 'isIos').returns(true); a4a = new MockA4AImpl(a4aElement); // Make sure there's no signature, so that we go down the 3p iframe path. @@ -1178,7 +1174,7 @@ describe('amp-a4a', () => { expect(unlayoutUISpy).to.be.calledOnce; expect(a4a.originalSlotSize_).to.be.ok; attemptChangeSizeResolver(); - return timerFor(a4a.win).promise(1).then(() => { + return Services.timerFor(a4a.win).promise(1).then(() => { expect(a4a.originalSlotSize_).to.not.be.ok; }); }); @@ -1232,7 +1228,7 @@ describe('amp-a4a', () => { a4a.unlayoutCallback(); expect(a4a.originalSlotSize_).to.be.ok; attemptChangeSizeResolver(); - return timerFor(a4a.win).promise(1).then(() => { + return Services.timerFor(a4a.win).promise(1).then(() => { expect(a4a.originalSlotSize_).to.not.be.ok; }); }); @@ -1309,7 +1305,7 @@ describe('amp-a4a', () => { a4a.onLayoutMeasure(); expect(a4a.adPromise_); // Delay to all getAdUrl to potentially execute. - return timerFor(a4a.win).promise(1).then(() => { + return Services.timerFor(a4a.win).promise(1).then(() => { expect(getAdUrlSpy).to.not.be.called; whenWithinRenderOutsideViewportResolve(); return a4a.adPromise_.then(() => { @@ -1527,8 +1523,8 @@ describe('amp-a4a', () => { }), 'Some style is "background: green"').to.be.true; expect(frameDoc.body.innerHTML.trim()).to.equal('

some text

'); - expect(urlReplacementsForDoc(frameDoc)) - .to.not.equal(urlReplacementsForDoc(a4aElement)); + expect(Services.urlReplacementsForDoc(frameDoc)) + .to.not.equal(Services.urlReplacementsForDoc(a4aElement)); }); }); diff --git a/extensions/amp-access-laterpay/0.1/amp-access-laterpay.js b/extensions/amp-access-laterpay/0.1/amp-access-laterpay.js index f33f4a7a1e21..bced009dd2fa 100644 --- a/extensions/amp-access-laterpay/0.1/amp-access-laterpay.js +++ b/extensions/amp-access-laterpay/0.1/amp-access-laterpay.js @@ -15,14 +15,14 @@ */ import {LaterpayVendor} from './laterpay-impl'; -import {accessServiceForDoc} from '../../../src/services'; +import {Services} from '../../../src/services'; AMP.extension('amp-access-laterpay', '0.1', function(AMP) { AMP.registerServiceForDoc( 'laterpay', function(ampdoc) { - return accessServiceForDoc(ampdoc).then(accessService => { + return Services.accessServiceForDoc(ampdoc).then(accessService => { const vendor = new LaterpayVendor(accessService); accessService.registerVendor('laterpay', vendor); return vendor; diff --git a/extensions/amp-access-laterpay/0.1/laterpay-impl.js b/extensions/amp-access-laterpay/0.1/laterpay-impl.js index 96e075f19e8d..32675f210f84 100644 --- a/extensions/amp-access-laterpay/0.1/laterpay-impl.js +++ b/extensions/amp-access-laterpay/0.1/laterpay-impl.js @@ -22,10 +22,7 @@ import {getMode} from '../../../src/mode'; import {dict} from '../../../src/utils/object'; import {listen} from '../../../src/event-helper'; import {removeChildren} from '../../../src/dom'; -import {timerFor} from '../../../src/services'; -import {viewportForDoc} from '../../../src/services'; -import {vsyncFor} from '../../../src/services'; -import {xhrFor} from '../../../src/services'; +import {Services} from '../../../src/services'; const TAG = 'amp-access-laterpay'; const CONFIG_URL = 'https://connector.laterpay.net'; @@ -100,7 +97,7 @@ export class LaterpayVendor { this.accessService_ = accessService; /** @private @const {!../../../src/service/viewport-impl.Viewport} */ - this.viewport_ = viewportForDoc(this.ampdoc); + this.viewport_ = Services.viewportForDoc(this.ampdoc); /** @const @private {!JsonObject} For shape see LaterpayConfigDef */ this.laterpayConfig_ = this.accessService_.getAdapterConfig(); @@ -145,13 +142,13 @@ export class LaterpayVendor { } /** @const @private {!../../../src/service/timer-impl.Timer} */ - this.timer_ = timerFor(this.ampdoc.win); + this.timer_ = Services.timerFor(this.ampdoc.win); /** @const @private {!../../../src/service/vsync-impl.Vsync} */ - this.vsync_ = vsyncFor(this.ampdoc.win); + this.vsync_ = Services.vsyncFor(this.ampdoc.win); /** @const @private {!../../../src/service/xhr-impl.Xhr} */ - this.xhr_ = xhrFor(this.ampdoc.win); + this.xhr_ = Services.xhrFor(this.ampdoc.win); // Install styles. if (this.ampdoc.isSingleDoc()) { diff --git a/extensions/amp-access/0.1/amp-access-client.js b/extensions/amp-access/0.1/amp-access-client.js index e50bb6fe5b34..6756ac0e47c7 100644 --- a/extensions/amp-access/0.1/amp-access-client.js +++ b/extensions/amp-access/0.1/amp-access-client.js @@ -16,8 +16,7 @@ import {assertHttpsUrl} from '../../../src/url'; import {dev, user} from '../../../src/log'; -import {timerFor} from '../../../src/services'; -import {xhrFor} from '../../../src/services'; +import {Services} from '../../../src/services'; import {getMode} from '../../../src/mode'; /** @const {string} */ @@ -62,10 +61,10 @@ export class AccessClientAdapter { configJson); /** @const @private {!../../../src/service/xhr-impl.Xhr} */ - this.xhr_ = xhrFor(ampdoc.win); + this.xhr_ = Services.xhrFor(ampdoc.win); /** @const @private {!../../../src/service/timer-impl.Timer} */ - this.timer_ = timerFor(ampdoc.win); + this.timer_ = Services.timerFor(ampdoc.win); } /** diff --git a/extensions/amp-access/0.1/amp-access-server-jwt.js b/extensions/amp-access/0.1/amp-access-server-jwt.js index fbf519fbb1a1..ca45c2bf5844 100644 --- a/extensions/amp-access/0.1/amp-access-server-jwt.js +++ b/extensions/amp-access/0.1/amp-access-server-jwt.js @@ -27,10 +27,7 @@ import { serializeQueryString, } from '../../../src/url'; import {dev, user} from '../../../src/log'; -import {timerFor} from '../../../src/services'; -import {viewerForDoc} from '../../../src/services'; -import {vsyncFor} from '../../../src/services'; -import {xhrFor} from '../../../src/services'; +import {Services} from '../../../src/services'; /** @const {string} */ const TAG = 'amp-access-server-jwt'; @@ -93,16 +90,16 @@ export class AccessServerJwtAdapter { this.clientAdapter_ = new AccessClientAdapter(ampdoc, configJson, context); /** @private @const {!../../../src/service/viewer-impl.Viewer} */ - this.viewer_ = viewerForDoc(ampdoc); + this.viewer_ = Services.viewerForDoc(ampdoc); /** @const @private {!../../../src/service/xhr-impl.Xhr} */ - this.xhr_ = xhrFor(ampdoc.win); + this.xhr_ = Services.xhrFor(ampdoc.win); /** @const @private {!../../../src/service/timer-impl.Timer} */ - this.timer_ = timerFor(ampdoc.win); + this.timer_ = Services.timerFor(ampdoc.win); /** @const @private {!../../../src/service/vsync-impl.Vsync} */ - this.vsync_ = vsyncFor(ampdoc.win); + this.vsync_ = Services.vsyncFor(ampdoc.win); const stateElement = ampdoc.getRootNode().querySelector( 'meta[name="i-amphtml-access-state"]'); diff --git a/extensions/amp-access/0.1/amp-access-server.js b/extensions/amp-access/0.1/amp-access-server.js index d2094d7eb4d4..1458d3a47e31 100644 --- a/extensions/amp-access/0.1/amp-access-server.js +++ b/extensions/amp-access/0.1/amp-access-server.js @@ -20,10 +20,7 @@ import {isProxyOrigin, removeFragment} from '../../../src/url'; import {dev} from '../../../src/log'; import {dict} from '../../../src/utils/object'; import {parseJson} from '../../../src/json'; -import {timerFor} from '../../../src/services'; -import {viewerForDoc} from '../../../src/services'; -import {vsyncFor} from '../../../src/services'; -import {xhrFor} from '../../../src/services'; +import {Services} from '../../../src/services'; /** @const {string} */ const TAG = 'amp-access-server'; @@ -76,16 +73,16 @@ export class AccessServerAdapter { this.clientAdapter_ = new AccessClientAdapter(ampdoc, configJson, context); /** @private @const {!../../../src/service/viewer-impl.Viewer} */ - this.viewer_ = viewerForDoc(ampdoc); + this.viewer_ = Services.viewerForDoc(ampdoc); /** @const @private {!../../../src/service/xhr-impl.Xhr} */ - this.xhr_ = xhrFor(ampdoc.win); + this.xhr_ = Services.xhrFor(ampdoc.win); /** @const @private {!../../../src/service/timer-impl.Timer} */ - this.timer_ = timerFor(ampdoc.win); + this.timer_ = Services.timerFor(ampdoc.win); /** @const @private {!../../../src/service/vsync-impl.Vsync} */ - this.vsync_ = vsyncFor(ampdoc.win); + this.vsync_ = Services.vsyncFor(ampdoc.win); const stateElement = ampdoc.getRootNode().querySelector( 'meta[name="i-amphtml-access-state"]'); diff --git a/extensions/amp-access/0.1/amp-access.js b/extensions/amp-access/0.1/amp-access.js index 3a76e0301a14..15f3d7728ab7 100644 --- a/extensions/amp-access/0.1/amp-access.js +++ b/extensions/amp-access/0.1/amp-access.js @@ -21,11 +21,10 @@ import {AccessServerJwtAdapter} from './amp-access-server-jwt'; import {AccessVendorAdapter} from './amp-access-vendor'; import {CSS} from '../../../build/amp-access-0.1.css'; import {SignInProtocol} from './signin'; -import {actionServiceForDoc} from '../../../src/services'; +import {Services} from '../../../src/services'; import {triggerAnalyticsEvent} from '../../../src/analytics'; import {assertHttpsUrl, getSourceOrigin} from '../../../src/url'; import {cancellation} from '../../../src/error'; -import {cidForDoc} from '../../../src/services'; import {evaluateAccessExpr} from './access-expr'; import {getValueForExpr, tryParseJson} from '../../../src/json'; import {installStyles} from '../../../src/style-installer'; @@ -37,14 +36,6 @@ import {dev, user} from '../../../src/log'; import {dict} from '../../../src/utils/object'; import {getLoginUrl, openLoginDialog} from './login-dialog'; import {parseQueryString} from '../../../src/url'; -import {performanceForOrNull} from '../../../src/services'; -import {resourcesForDoc} from '../../../src/services'; -import {templatesFor} from '../../../src/services'; -import {timerFor} from '../../../src/services'; -import {urlReplacementsForDoc} from '../../../src/services'; -import {viewerForDoc} from '../../../src/services'; -import {viewportForDoc} from '../../../src/services'; -import {vsyncFor} from '../../../src/services'; import {startsWith} from '../../../src/string'; @@ -129,33 +120,33 @@ export class AccessService { this.pubOrigin_ = getSourceOrigin(ampdoc.win.location); /** @const @private {!../../../src/service/timer-impl.Timer} */ - this.timer_ = timerFor(ampdoc.win); + this.timer_ = Services.timerFor(ampdoc.win); /** @const @private {!../../../src/service/vsync-impl.Vsync} */ - this.vsync_ = vsyncFor(ampdoc.win); + this.vsync_ = Services.vsyncFor(ampdoc.win); /** @const @private {!../../../src/service/url-replacements-impl.UrlReplacements} */ - this.urlReplacements_ = urlReplacementsForDoc(ampdoc); + this.urlReplacements_ = Services.urlReplacementsForDoc(ampdoc); // TODO(dvoytenko, #3742): This will refer to the ampdoc once AccessService // is migrated to ampdoc as well. /** @private @const {!Promise} */ - this.cid_ = cidForDoc(ampdoc); + this.cid_ = Services.cidForDoc(ampdoc); /** @private @const {!../../../src/service/viewer-impl.Viewer} */ - this.viewer_ = viewerForDoc(ampdoc); + this.viewer_ = Services.viewerForDoc(ampdoc); /** @private @const {!../../../src/service/viewport-impl.Viewport} */ - this.viewport_ = viewportForDoc(ampdoc); + this.viewport_ = Services.viewportForDoc(ampdoc); /** @private @const {!../../../src/service/template-impl.Templates} */ - this.templates_ = templatesFor(ampdoc.win); + this.templates_ = Services.templatesFor(ampdoc.win); /** @private @const {!../../../src/service/resources-impl.Resources} */ - this.resources_ = resourcesForDoc(ampdoc); + this.resources_ = Services.resourcesForDoc(ampdoc); /** @private @const {?../../../src/service/performance-impl.Performance} */ - this.performance_ = performanceForOrNull(ampdoc.win); + this.performance_ = Services.performanceForOrNull(ampdoc.win); /** @private @const {function(string):Promise} */ this.openLoginDialog_ = openLoginDialog.bind(null, ampdoc); @@ -349,7 +340,7 @@ export class AccessService { // TODO(dvoytenko, #3742): This will refer to the ampdoc once AccessService // is migrated to ampdoc as well. - actionServiceForDoc(this.ampdoc).installActionHandler( + Services.actionServiceForDoc(this.ampdoc).installActionHandler( this.accessElement_, this.handleAction_.bind(this)); // Calculate login URLs right away. diff --git a/extensions/amp-access/0.1/login-dialog.js b/extensions/amp-access/0.1/login-dialog.js index cd33cf7d4d3b..54c61d42f2e3 100644 --- a/extensions/amp-access/0.1/login-dialog.js +++ b/extensions/amp-access/0.1/login-dialog.js @@ -19,7 +19,7 @@ import {getData, listen} from '../../../src/event-helper'; import {dev, user} from '../../../src/log'; import {openWindowDialog} from '../../../src/dom'; import {parseUrl} from '../../../src/url'; -import {viewerForDoc} from '../../../src/services'; +import {Services} from '../../../src/services'; import {urls} from '../../../src/config'; import {dict} from '../../../src/utils/object'; @@ -35,7 +35,7 @@ const RETURN_URL_REGEX = new RegExp('RETURN_URL'); * @return {!WebLoginDialog|!ViewerLoginDialog} */ export function createLoginDialog(ampdoc, urlOrPromise) { - const viewer = viewerForDoc(ampdoc); + const viewer = Services.viewerForDoc(ampdoc); const overrideDialog = parseInt(viewer.getParam('dialog'), 10); if (overrideDialog) { return new ViewerLoginDialog(viewer, urlOrPromise); diff --git a/extensions/amp-access/0.1/test/test-login-dialog.js b/extensions/amp-access/0.1/test/test-login-dialog.js index 85e0eadbdaa4..17f02998e2e9 100644 --- a/extensions/amp-access/0.1/test/test-login-dialog.js +++ b/extensions/amp-access/0.1/test/test-login-dialog.js @@ -18,7 +18,7 @@ import { WebLoginDialog, openLoginDialog, } from '../login-dialog'; -import {ampdocServiceFor} from '../../../../src/services'; +import {Services} from '../../../../src/services'; import {installDocService} from '../../../../src/service/ampdoc-impl'; import * as sinon from 'sinon'; @@ -69,7 +69,7 @@ describes.sandboxed('ViewerLoginDialog', {}, () => { }; windowApi.document.defaultView = windowApi; installDocService(windowApi, /* isSingleDoc */ true); - ampdoc = ampdocServiceFor(windowApi).getAmpDoc(); + ampdoc = Services.ampdocServiceFor(windowApi).getAmpDoc(); }); it('should delegate to viewer with url', () => { @@ -193,7 +193,7 @@ describes.sandboxed('WebLoginDialog', {}, () => { windowApi.document.defaultView = windowApi; windowMock = sandbox.mock(windowApi); installDocService(windowApi, /* isSingleDoc */ true); - ampdoc = ampdocServiceFor(windowApi).getAmpDoc(); + ampdoc = Services.ampdocServiceFor(windowApi).getAmpDoc(); dialogUrl = null; dialog = { diff --git a/extensions/amp-ad-exit/0.1/amp-ad-exit.js b/extensions/amp-ad-exit/0.1/amp-ad-exit.js index 0580efa1c002..5502de14c697 100644 --- a/extensions/amp-ad-exit/0.1/amp-ad-exit.js +++ b/extensions/amp-ad-exit/0.1/amp-ad-exit.js @@ -18,7 +18,7 @@ import {makeClickDelaySpec} from './filters/click-delay'; import {assertConfig, TransportMode} from './config'; import {createFilter} from './filters/factory'; import {isJsonScriptTag, openWindowDialog} from '../../../src/dom'; -import {urlReplacementsForDoc} from '../../../src/services'; +import {Services} from '../../../src/services'; import {user} from '../../../src/log'; import {parseJson} from '../../../src/json'; @@ -106,7 +106,7 @@ export class AmpAdExit extends AMP.BaseElement { } } } - const replacements = urlReplacementsForDoc(this.getAmpDoc()); + const replacements = Services.urlReplacementsForDoc(this.getAmpDoc()); return url => replacements.expandUrlSync( url, vars, undefined /* opt_collectVars */, whitelist); } diff --git a/extensions/amp-ad-network-adsense-impl/0.1/amp-ad-network-adsense-impl.js b/extensions/amp-ad-network-adsense-impl/0.1/amp-ad-network-adsense-impl.js index f30389a3ecac..a963a752d7de 100644 --- a/extensions/amp-ad-network-adsense-impl/0.1/amp-ad-network-adsense-impl.js +++ b/extensions/amp-ad-network-adsense-impl/0.1/amp-ad-network-adsense-impl.js @@ -43,13 +43,12 @@ import {removeElement} from '../../../src/dom'; import {getMode} from '../../../src/mode'; import {stringHash32} from '../../../src/string'; import {dev} from '../../../src/log'; -import {extensionsFor} from '../../../src/services'; +import {Services} from '../../../src/services'; import {domFingerprintPlain} from '../../../src/utils/dom-fingerprint'; import { computedStyle, setStyles, } from '../../../src/style'; -import {viewerForDoc} from '../../../src/services'; import {AdsenseSharedState} from './adsense-shared-state'; import {insertAnalyticsElement} from '../../../src/extension-analytics'; import { @@ -112,7 +111,7 @@ export class AmpAdNetworkAdsenseImpl extends AmpA4A { this.ampAnalyticsConfig_ = null; /** @private {!../../../src/service/extensions-impl.Extensions} */ - this.extensions_ = extensionsFor(this.win); + this.extensions_ = Services.extensionsFor(this.win); /** @private {?({width, height}|../../../src/layout-rect.LayoutRectDef)} */ this.size_ = null; @@ -147,7 +146,7 @@ export class AmpAdNetworkAdsenseImpl extends AmpA4A { if (adClientId.substring(0, 3) != 'ca-') { adClientId = 'ca-' + adClientId; } - const visibilityState = viewerForDoc(this.getAmpDoc()) + const visibilityState = Services.viewerForDoc(this.getAmpDoc()) .getVisibilityState(); const adTestOn = this.element.getAttribute('data-adtest') || isInManualExperiment(this.element); diff --git a/extensions/amp-ad-network-adsense-impl/0.1/test/test-amp-ad-network-adsense-impl.js b/extensions/amp-ad-network-adsense-impl/0.1/test/test-amp-ad-network-adsense-impl.js index e4dfbcac3980..b5551f9ebd84 100644 --- a/extensions/amp-ad-network-adsense-impl/0.1/test/test-amp-ad-network-adsense-impl.js +++ b/extensions/amp-ad-network-adsense-impl/0.1/test/test-amp-ad-network-adsense-impl.js @@ -22,7 +22,7 @@ import { import { installExtensionsService, } from '../../../../src/service/extensions-impl'; -import {extensionsFor} from '../../../../src/services'; +import {Services} from '../../../../src/services'; import {AmpAdUIHandler} from '../../../amp-ad/0.1/amp-ad-ui'; // eslint-disable-line no-unused-vars import { AmpAdXOriginIframeHandler, // eslint-disable-line no-unused-vars @@ -323,7 +323,7 @@ describes.sandboxed('amp-ad-network-adsense-impl', {}, () => { }); impl = new AmpAdNetworkAdsenseImpl(element); installExtensionsService(impl.win); - const extensions = extensionsFor(impl.win); + const extensions = Services.extensionsFor(impl.win); loadExtensionSpy = sandbox.spy(extensions, 'loadExtension'); }); }); diff --git a/extensions/amp-ad-network-doubleclick-impl/0.1/amp-ad-network-doubleclick-impl.js b/extensions/amp-ad-network-doubleclick-impl/0.1/amp-ad-network-doubleclick-impl.js index 6ccff470e603..e13b38e54c46 100644 --- a/extensions/amp-ad-network-doubleclick-impl/0.1/amp-ad-network-doubleclick-impl.js +++ b/extensions/amp-ad-network-doubleclick-impl/0.1/amp-ad-network-doubleclick-impl.js @@ -61,7 +61,7 @@ import {removeElement} from '../../../src/dom'; import {tryParseJson} from '../../../src/json'; import {dev, user} from '../../../src/log'; import {getMode} from '../../../src/mode'; -import {extensionsFor, xhrFor} from '../../../src/services'; +import {Services} from '../../../src/services'; import {domFingerprintPlain} from '../../../src/utils/dom-fingerprint'; import {insertAnalyticsElement} from '../../../src/extension-analytics'; import {setStyles} from '../../../src/style'; @@ -193,7 +193,7 @@ export class AmpAdNetworkDoubleclickImpl extends AmpA4A { this.ampAnalyticsConfig_ = null; /** @private {!../../../src/service/extensions-impl.Extensions} */ - this.extensions_ = extensionsFor(this.win); + this.extensions_ = Services.extensionsFor(this.win); /** @private {?string} */ this.qqid_ = null; @@ -599,7 +599,7 @@ export class AmpAdNetworkDoubleclickImpl extends AmpA4A { .then(sraUrlIn => { checkStillCurrent(); sraUrl = sraUrlIn; - return xhrFor(this.win).fetch(sraUrl, { + return Services.xhrFor(this.win).fetch(sraUrl, { mode: 'cors', method: 'GET', credentials: 'include', diff --git a/extensions/amp-ad-network-doubleclick-impl/0.1/test/test-amp-ad-network-doubleclick-impl.js b/extensions/amp-ad-network-doubleclick-impl/0.1/test/test-amp-ad-network-doubleclick-impl.js index f201568199b0..bfe2a3b44790 100644 --- a/extensions/amp-ad-network-doubleclick-impl/0.1/test/test-amp-ad-network-doubleclick-impl.js +++ b/extensions/amp-ad-network-doubleclick-impl/0.1/test/test-amp-ad-network-doubleclick-impl.js @@ -25,7 +25,7 @@ import {createIframePromise} from '../../../../testing/iframe'; import { installExtensionsService, } from '../../../../src/service/extensions-impl'; -import {ampdocServiceFor, extensionsFor} from '../../../../src/services'; +import {Services} from '../../../../src/services'; import { AmpAdNetworkDoubleclickImpl, getNetworkId, @@ -150,7 +150,7 @@ describes.sandboxed('amp-ad-network-doubleclick-impl', {}, () => { impl = new AmpAdNetworkDoubleclickImpl(element); impl.size_ = size; installExtensionsService(impl.win); - const extensions = extensionsFor(impl.win); + const extensions = Services.extensionsFor(impl.win); loadExtensionSpy = sandbox.spy(extensions, 'loadExtension'); }); }); @@ -700,7 +700,7 @@ describes.sandboxed('amp-ad-network-doubleclick-impl', {}, () => { 'data-slot': `/${networkId}/abc/def`, }); element.getAmpDoc = () => { - const ampdocService = ampdocServiceFor(doc.defaultView); + const ampdocService = Services.ampdocServiceFor(doc.defaultView); return ampdocService.getAmpDoc(element); }; element.isBuilt = () => {return true;}; diff --git a/extensions/amp-ad/0.1/a2a-listener.js b/extensions/amp-ad/0.1/a2a-listener.js index 8fb1ecdabc58..29b0ebb41a39 100644 --- a/extensions/amp-ad/0.1/a2a-listener.js +++ b/extensions/amp-ad/0.1/a2a-listener.js @@ -17,7 +17,7 @@ import {closestByTag} from '../../../src/dom'; import {isExperimentOn} from '../../../src/experiments'; import {getData} from '../../../src/event-helper'; import {user} from '../../../src/log'; -import {viewerForDoc} from '../../../src/services'; +import {Services} from '../../../src/services'; import {isProxyOrigin} from '../../../src/url'; import {parseJson} from '../../../src/json'; @@ -80,5 +80,5 @@ export function handleMessageEvent(win, event) { // We only allow AMP shaped URLs. user().assert(isProxyOrigin(url), 'Invalid ad A2A URL %s %s', url, origin); - viewerForDoc(win.document).navigateTo(url, 'ad-' + origin); + Services.viewerForDoc(win.document).navigateTo(url, 'ad-' + origin); } diff --git a/extensions/amp-ad/0.1/amp-ad-custom.js b/extensions/amp-ad/0.1/amp-ad-custom.js index 1b3f11a5efdf..2cd1f099a14e 100644 --- a/extensions/amp-ad/0.1/amp-ad-custom.js +++ b/extensions/amp-ad/0.1/amp-ad-custom.js @@ -16,8 +16,7 @@ import {isLayoutSizeDefined} from '../../../src/layout'; import {user} from '../../../src/log'; -import {templatesFor} from '../../../src/services'; -import {xhrFor} from '../../../src/services'; +import {Services} from '../../../src/services'; import {addParamToUrl} from '../../../src/url'; import {ancestorElementsByTag} from '../../../src/dom'; import {removeChildren} from '../../../src/dom'; @@ -85,8 +84,8 @@ export class AmpAdCustom extends AMP.BaseElement { // If this promise has no URL yet, create one for it. if (!(fullUrl in ampCustomadXhrPromises)) { // Here is a promise that will return the data for this URL - ampCustomadXhrPromises[fullUrl] = xhrFor(this.win).fetchJson(fullUrl) - .then(res => res.json()); + ampCustomadXhrPromises[fullUrl] = + Services.xhrFor(this.win).fetchJson(fullUrl).then(res => res.json()); } return ampCustomadXhrPromises[fullUrl].then(data => { const element = this.element; @@ -99,10 +98,11 @@ export class AmpAdCustom extends AMP.BaseElement { // Set UI state if (templateData !== null && typeof templateData == 'object') { this.renderStarted(); - templatesFor(this.win).findAndRenderTemplate(element, templateData) + Services.templatesFor(this.win) + .findAndRenderTemplate(element, templateData) .then(renderedElement => { - // Get here when the template has been rendered - // Clear out the template and replace it by the rendered version + // Get here when the template has been rendered + // Clear out the template and replace it by the rendered version removeChildren(element); element.appendChild(renderedElement); }); diff --git a/extensions/amp-ad/0.1/amp-ad-xorigin-iframe-handler.js b/extensions/amp-ad/0.1/amp-ad-xorigin-iframe-handler.js index 16a2adde1278..5e77476b2907 100644 --- a/extensions/amp-ad/0.1/amp-ad-xorigin-iframe-handler.js +++ b/extensions/amp-ad/0.1/amp-ad-xorigin-iframe-handler.js @@ -24,10 +24,9 @@ import { listenForOncePromise, postMessageToWindows, } from '../../../src/iframe-helper'; -import {viewerForDoc} from '../../../src/services'; +import {Services} from '../../../src/services'; import {dev} from '../../../src/log'; import {dict} from '../../../src/utils/object'; -import {timerFor} from '../../../src/services'; import {setStyle} from '../../../src/style'; import {getData, loadPromise} from '../../../src/event-helper'; import {getHtml} from '../../../src/get-html'; @@ -81,7 +80,7 @@ export class AmpAdXOriginIframeHandler { this.unlisteners_ = []; /** @private @const {!../../../src/service/viewer-impl.Viewer} */ - this.viewer_ = viewerForDoc(this.baseInstance_.getAmpDoc()); + this.viewer_ = Services.viewerForDoc(this.baseInstance_.getAmpDoc()); } /** @@ -96,7 +95,7 @@ export class AmpAdXOriginIframeHandler { this.iframe = iframe; this.iframe.setAttribute('scrolling', 'no'); this.baseInstance_.applyFillContent(this.iframe); - const timer = timerFor(this.baseInstance_.win); + const timer = Services.timerFor(this.baseInstance_.win); // Init IntersectionObserver service. this.intersectionObserver_ = new IntersectionObserver( diff --git a/extensions/amp-ad/0.1/amp-ad.js b/extensions/amp-ad/0.1/amp-ad.js index 992d9ccc4ac4..a0e751dbca6e 100644 --- a/extensions/amp-ad/0.1/amp-ad.js +++ b/extensions/amp-ad/0.1/amp-ad.js @@ -20,8 +20,7 @@ import {AmpAdCustom} from './amp-ad-custom'; import {a4aRegistry} from '../../../ads/_a4a-config'; import {adConfig} from '../../../ads/_config'; import {user} from '../../../src/log'; -import {extensionsFor} from '../../../src/services'; -import {userNotificationManagerFor} from '../../../src/services'; +import {Services} from '../../../src/services'; import {isExperimentOn} from '../../../src/experiments'; import {hasOwn} from '../../../src/utils/object'; @@ -54,7 +53,7 @@ export class AmpAd extends AMP.BaseElement { /** @const {string} */ const consentId = this.element.getAttribute('data-consent-notification-id'); const consent = consentId - ? userNotificationManagerFor(this.win) + ? Services.userNotificationManagerFor(this.win) .then(service => service.get(consentId)) : Promise.resolve(); @@ -90,7 +89,7 @@ export class AmpAd extends AMP.BaseElement { const extensionTagName = networkImplementationTag(type); this.element.setAttribute('data-a4a-upgrade-type', extensionTagName); - return extensionsFor(this.win).loadElementClass(extensionTagName) + return Services.extensionsFor(this.win).loadElementClass(extensionTagName) .then(ctor => new ctor(this.element)) .catch(error => { // Work around presubmit restrictions. diff --git a/extensions/amp-ad/0.1/concurrent-load.js b/extensions/amp-ad/0.1/concurrent-load.js index f63e4e9ee84f..49de580cb1da 100644 --- a/extensions/amp-ad/0.1/concurrent-load.js +++ b/extensions/amp-ad/0.1/concurrent-load.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import {timerFor} from '../../../src/services'; +import {Services} from '../../../src/services'; import {user} from '../../../src/log'; /** @@ -65,7 +65,7 @@ export function incrementLoadingAds(win, opt_loadingPromise) { win[LOADING_ADS_WIN_ID_] = 0; } win[LOADING_ADS_WIN_ID_]++; - timerFor(win) + Services.timerFor(win) .timeoutPromise(1000, opt_loadingPromise) .catch(() => {}) .then(() => { diff --git a/extensions/amp-ad/0.1/test/test-amp-ad-xorigin-iframe-handler.js b/extensions/amp-ad/0.1/test/test-amp-ad-xorigin-iframe-handler.js index 954446dca429..873629686004 100644 --- a/extensions/amp-ad/0.1/test/test-amp-ad-xorigin-iframe-handler.js +++ b/extensions/amp-ad/0.1/test/test-amp-ad-xorigin-iframe-handler.js @@ -22,7 +22,7 @@ import { expectPostMessage, } from '../../../../testing/iframe'; import {AmpAdUIHandler} from '../amp-ad-ui'; -import {ampdocServiceFor, timerFor} from '../../../../src/services'; +import {Services} from '../../../../src/services'; import * as sinon from 'sinon'; describe('amp-ad-xorigin-iframe-handler', () => { @@ -36,7 +36,7 @@ describe('amp-ad-xorigin-iframe-handler', () => { beforeEach(() => { sandbox = sinon.sandbox.create(); - const ampdocService = ampdocServiceFor(window); + const ampdocService = Services.ampdocServiceFor(window); const ampdoc = ampdocService.getAmpDoc(); const adElement = document.createElement('container-element'); adElement.getAmpDoc = () => ampdoc; @@ -191,7 +191,7 @@ describe('amp-ad-xorigin-iframe-handler', () => { const clock = sandbox.useFakeTimers(); clock.tick(0); const timeoutPromise = - timerFor(window).timeoutPromise(2000, initPromise); + Services.timerFor(window).timeoutPromise(2000, initPromise); clock.tick(2001); return expect(timeoutPromise).to.eventually .be.rejectedWith(/timeout/); diff --git a/extensions/amp-ad/0.1/test/test-amp-ad.js b/extensions/amp-ad/0.1/test/test-amp-ad.js index 922d41d66273..5a9771f1e70f 100644 --- a/extensions/amp-ad/0.1/test/test-amp-ad.js +++ b/extensions/amp-ad/0.1/test/test-amp-ad.js @@ -19,9 +19,8 @@ import {a4aRegistry} from '../../../../ads/_a4a-config'; import {adConfig} from '../../../../ads/_config'; import {AmpAd} from '../amp-ad'; import {AmpAd3PImpl} from '../amp-ad-3p-impl'; -import {extensionsFor} from '../../../../src/services'; +import {Services} from '../../../../src/services'; import {stubService} from '../../../../testing/test-helper'; -import {timerFor} from '../../../../src/services'; import * as sinon from 'sinon'; describe('Ad loader', () => { @@ -95,7 +94,7 @@ describe('Ad loader', () => { throw new Error('upgradeCallback should not resolve without ' + 'notification dismissal'); }), - timerFor(fixture.win).promise(25), + Services.timerFor(fixture.win).promise(25), ]); }); }); @@ -133,7 +132,7 @@ describe('Ad loader', () => { return true; }; ampAdElement.setAttribute('type', 'zort'); - const extensions = extensionsFor(fixture.win); + const extensions = Services.extensionsFor(fixture.win); const extensionsStub = sandbox.stub(extensions, 'loadElementClass') .withArgs('amp-ad-network-zort-impl') .returns(Promise.reject(new Error('I failed!'))); @@ -175,7 +174,7 @@ describe('Ad loader', () => { ampAdElement.setAttribute('type', 'zort'); const zortInstance = {}; const zortConstructor = function() { return zortInstance; }; - const extensions = extensionsFor(fixture.win); + const extensions = Services.extensionsFor(fixture.win); const extensionsStub = sandbox.stub(extensions, 'loadElementClass') .withArgs('amp-ad-network-zort-impl') .returns(Promise.resolve(zortConstructor)); @@ -197,7 +196,7 @@ describe('Ad loader', () => { ampAdElement.setAttribute('type', 'zort'); const zortInstance = {}; const zortConstructor = function() { return zortInstance; }; - const extensions = extensionsFor(fixture.win); + const extensions = Services.extensionsFor(fixture.win); const extensionsStub = sandbox.stub(extensions, 'loadElementClass') .withArgs('amp-ad-network-zort-impl') .returns(Promise.resolve(zortConstructor)); diff --git a/extensions/amp-analytics/0.1/activity-impl.js b/extensions/amp-analytics/0.1/activity-impl.js index 571e2d981f37..f8a53c967f43 100644 --- a/extensions/amp-analytics/0.1/activity-impl.js +++ b/extensions/amp-analytics/0.1/activity-impl.js @@ -19,8 +19,7 @@ * has performed on the page. */ -import {viewerForDoc} from '../../../src/services'; -import {viewportForDoc} from '../../../src/services'; +import {Services} from '../../../src/services'; import {listen} from '../../../src/event-helper'; import {registerServiceBuilderForDoc} from '../../../src/service'; @@ -177,10 +176,10 @@ export class Activity { this.activityHistory_ = new ActivityHistory(); /** @private @const {!../../../src/service/viewer-impl.Viewer} */ - this.viewer_ = viewerForDoc(this.ampdoc); + this.viewer_ = Services.viewerForDoc(this.ampdoc); /** @private @const {!../../../src/service/viewport-impl.Viewport} */ - this.viewport_ = viewportForDoc(this.ampdoc); + this.viewport_ = Services.viewportForDoc(this.ampdoc); this.viewer_.whenFirstVisible().then(this.start_.bind(this)); } diff --git a/extensions/amp-analytics/0.1/amp-analytics.js b/extensions/amp-analytics/0.1/amp-analytics.js index def454521259..4aec916b3c8f 100644 --- a/extensions/amp-analytics/0.1/amp-analytics.js +++ b/extensions/amp-analytics/0.1/amp-analytics.js @@ -21,14 +21,7 @@ import {expandTemplate} from '../../../src/string'; import {isArray, isObject} from '../../../src/types'; import {dict, hasOwn, map} from '../../../src/utils/object'; import {sendRequest, sendRequestUsingIframe} from './transport'; -import { - cryptoFor, - timerFor, - urlReplacementsForDoc, - userNotificationManagerFor, - viewerForDoc, - xhrFor, -} from '../../../src/services'; +import {Services} from '../../../src/services'; import {toggle} from '../../../src/style'; import {isEnumValue} from '../../../src/types'; import {parseJson} from '../../../src/json'; @@ -116,7 +109,7 @@ export class AmpAnalytics extends AMP.BaseElement { this.variableService_ = variableServiceFor(this.win); /** @private {!../../../src/service/crypto-impl.Crypto} */ - this.cryptoService_ = cryptoFor(this.win); + this.cryptoService_ = Services.cryptoFor(this.win); /** @private {?Promise} */ this.iniPromise_ = null; @@ -148,7 +141,7 @@ export class AmpAnalytics extends AMP.BaseElement { .getAttribute('data-consent-notification-id'); if (this.consentNotificationId_ != null) { - this.consentPromise_ = userNotificationManagerFor(this.win) + this.consentPromise_ = Services.userNotificationManagerFor(this.win) .then(service => service.get(dev().assertString( this.consentNotificationId_))); } @@ -183,9 +176,9 @@ export class AmpAnalytics extends AMP.BaseElement { } toggle(this.element, false); this.iniPromise_ = - viewerForDoc(this.getAmpDoc()).whenFirstVisible() + Services.viewerForDoc(this.getAmpDoc()).whenFirstVisible() // Rudimentary "idle" signal. - .then(() => timerFor(this.win).promise(1)) + .then(() => Services.timerFor(this.win).promise(1)) .then(() => this.consentPromise_) .then(this.fetchRemoteConfig_.bind(this)) .then(() => instrumentationServicePromiseForDoc(this.getAmpDoc())) @@ -358,10 +351,12 @@ export class AmpAnalytics extends AMP.BaseElement { fetchConfig.credentials = this.element.getAttribute('data-credentials'); } const ampdoc = this.getAmpDoc(); - return urlReplacementsForDoc(this.element).expandAsync(remoteConfigUrl) + return Services.urlReplacementsForDoc(this.element) + .expandAsync(remoteConfigUrl) .then(expandedUrl => { remoteConfigUrl = expandedUrl; - return xhrFor(ampdoc.win).fetchJson(remoteConfigUrl, fetchConfig); + return Services.xhrFor(ampdoc.win).fetchJson( + remoteConfigUrl, fetchConfig); }) .then(res => res.json()) .then(jsonValue => { @@ -572,7 +567,7 @@ export class AmpAnalytics extends AMP.BaseElement { this.isSandbox_ ? SANDBOX_AVAILABLE_VARS : undefined; // For consistency with amp-pixel we also expand any url // replacements. - return urlReplacementsForDoc(this.element).expandAsync( + return Services.urlReplacementsForDoc(this.element).expandAsync( request, undefined, whiteList); }) .then(request => { @@ -689,7 +684,8 @@ export class AmpAnalytics extends AMP.BaseElement { */ expandTemplateWithUrlParams_(spec, expansionOptions) { return this.variableService_.expandTemplate(spec, expansionOptions) - .then(key => urlReplacementsForDoc(this.element).expandUrlAsync(key)); + .then(key => Services.urlReplacementsForDoc( + this.element).expandUrlAsync(key)); } /** diff --git a/extensions/amp-analytics/0.1/analytics-root.js b/extensions/amp-analytics/0.1/analytics-root.js index b79012c47d23..267e079e09d5 100644 --- a/extensions/amp-analytics/0.1/analytics-root.js +++ b/extensions/amp-analytics/0.1/analytics-root.js @@ -27,10 +27,7 @@ import {dev, user} from '../../../src/log'; import {getMode} from '../../../src/mode'; import {layoutRectLtwh} from '../../../src/layout-rect'; import {map} from '../../../src/utils/object'; -import { - viewerForDoc, - viewportForDoc, -} from '../../../src/services'; +import {Services} from '../../../src/services'; import {whenContentIniLoad} from '../../../src/friendly-iframe-embed'; const TAG = 'amp-analytics'; @@ -96,7 +93,7 @@ export class AnalyticsRoot { * @return {!../../../src/service/viewer-impl.Viewer} */ getViewer() { - return viewerForDoc(this.ampdoc); + return Services.viewerForDoc(this.ampdoc); } /** @@ -363,7 +360,7 @@ export class AmpdocAnalyticsRoot extends AnalyticsRoot { /** @override */ whenIniLoaded() { - const viewport = viewportForDoc(this.ampdoc); + const viewport = Services.viewportForDoc(this.ampdoc); let rect; if (getMode(this.ampdoc.win).runtime == 'inabox') { // TODO(dvoytenko, #7971): This is currently addresses incorrect position diff --git a/extensions/amp-analytics/0.1/instrumentation.js b/extensions/amp-analytics/0.1/instrumentation.js index 5d96421ec6c3..17e938dd969d 100644 --- a/extensions/amp-analytics/0.1/instrumentation.js +++ b/extensions/amp-analytics/0.1/instrumentation.js @@ -40,9 +40,7 @@ import { } from '../../../src/service'; import {isEnumValue} from '../../../src/types'; import {startsWith} from '../../../src/string'; -import {timerFor} from '../../../src/services'; -import {viewerForDoc} from '../../../src/services'; -import {viewportForDoc} from '../../../src/services'; +import {Services} from '../../../src/services'; const MIN_TIMER_INTERVAL_SECONDS_ = 0.5; const DEFAULT_MAX_TIMER_LENGTH_SECONDS_ = 7200; @@ -146,13 +144,13 @@ export class InstrumentationService { this.ampdocRoot_ = new AmpdocAnalyticsRoot(this.ampdoc); /** @const {!../../../src/service/timer-impl.Timer} */ - this.timer_ = timerFor(this.ampdoc.win); + this.timer_ = Services.timerFor(this.ampdoc.win); /** @private @const {!../../../src/service/viewer-impl.Viewer} */ - this.viewer_ = viewerForDoc(this.ampdoc); + this.viewer_ = Services.viewerForDoc(this.ampdoc); /** @const {!../../../src/service/viewport-impl.Viewport} */ - this.viewport_ = viewportForDoc(this.ampdoc); + this.viewport_ = Services.viewportForDoc(this.ampdoc); /** @private {boolean} */ this.scrollHandlerRegistered_ = false; diff --git a/extensions/amp-analytics/0.1/test/test-amp-analytics.js b/extensions/amp-analytics/0.1/test/test-amp-analytics.js index 39dc30063421..f1e065053565 100644 --- a/extensions/amp-analytics/0.1/test/test-amp-analytics.js +++ b/extensions/amp-analytics/0.1/test/test-amp-analytics.js @@ -29,9 +29,6 @@ import { import { installUserNotificationManager, } from '../../../amp-user-notification/0.1/amp-user-notification'; -import { - userNotificationManagerFor, -} from '../../../../src/services'; import {adopt} from '../../../../src/runtime'; import {createIframePromise} from '../../../../testing/iframe'; import { @@ -43,7 +40,7 @@ import {markElementScheduledForTesting} from '../../../../src/custom-element'; import {map} from '../../../../src/utils/object'; import {cidServiceForDocForTesting} from '../../../../src/service/cid-impl'; -import {urlReplacementsForDoc} from '../../../../src/services'; +import {Services} from '../../../../src/services'; import * as sinon from 'sinon'; import {AmpDocSingle} from '../../../../src/service/ampdoc-impl'; @@ -114,7 +111,7 @@ describe('amp-analytics', function() { ins = instrumentationServiceForDocForTesting(ampdoc); installVariableService(iframe.win); installUserNotificationManager(iframe.win); - return userNotificationManagerFor(iframe.win).then(manager => { + return Services.userNotificationManagerFor(iframe.win).then(manager => { uidService = manager; }); }); @@ -216,7 +213,8 @@ describe('amp-analytics', function() { const analytics = getAnalyticsTag(clearVendorOnlyConfig(config)); analytics.createdCallback(); analytics.buildCallback(); - const urlReplacements = urlReplacementsForDoc(analytics.element); + const urlReplacements = + Services.urlReplacementsForDoc(analytics.element); sandbox.stub(urlReplacements.getVariableSource(), 'get', function(name) { expect(this.replacements_).to.have.property(name); @@ -688,7 +686,7 @@ describe('amp-analytics', function() { 'qp_foo': '${queryParam(foo)}', }, }]}); - const urlReplacements = urlReplacementsForDoc(analytics.element); + const urlReplacements = Services.urlReplacementsForDoc(analytics.element); sandbox.stub(urlReplacements.getVariableSource(), 'get', function(name) { return {sync: param => { @@ -968,7 +966,7 @@ describe('amp-analytics', function() { config.triggers.sampled.sampleSpec.sampleOn = '${pageViewId}'; const analytics = getAnalyticsTag(config); - const urlReplacements = urlReplacementsForDoc(analytics.element); + const urlReplacements = Services.urlReplacementsForDoc(analytics.element); sandbox.stub(urlReplacements.getVariableSource(), 'get').returns(0); sandbox.stub(crypto, 'uniform') .withArgs('0').returns(Promise.resolve(0.005)); @@ -1088,7 +1086,7 @@ describe('amp-analytics', function() { config.triggers.conditional.enabled = '${pageViewId}'; const analytics = getAnalyticsTag(config); - const urlReplacements = urlReplacementsForDoc(analytics.element); + const urlReplacements = Services.urlReplacementsForDoc(analytics.element); sandbox.stub(urlReplacements.getVariableSource(), 'get') .returns({sync: 1}); return waitForSendRequest(analytics).then(() => { @@ -1121,7 +1119,7 @@ describe('amp-analytics', function() { config.triggers.conditional.enabled = '${queryParam(undefinedParam)}'; const analytics = getAnalyticsTag(config); - const urlReplacements = urlReplacementsForDoc(analytics.element); + const urlReplacements = Services.urlReplacementsForDoc(analytics.element); sandbox.stub(urlReplacements.getVariableSource(), 'get') .returns(null); @@ -1136,7 +1134,7 @@ describe('amp-analytics', function() { config.triggers.conditional.enabled = '${queryParam(undefinedParam)}'; const analytics = getAnalyticsTag(config); - const urlReplacements = urlReplacementsForDoc(analytics.element); + const urlReplacements = Services.urlReplacementsForDoc(analytics.element); sandbox.stub(urlReplacements.getVariableSource(), 'get') .returns({sync: 0}); @@ -1151,7 +1149,7 @@ describe('amp-analytics', function() { config.triggers.conditional.enabled = '${queryParam(undefinedParam)}'; const analytics = getAnalyticsTag(config); - const urlReplacements = urlReplacementsForDoc(analytics.element); + const urlReplacements = Services.urlReplacementsForDoc(analytics.element); sandbox.stub(urlReplacements.getVariableSource(), 'get') .returns({sync: false}); @@ -1166,7 +1164,7 @@ describe('amp-analytics', function() { config.triggers.conditional.enabled = '${queryParam(undefinedParam)}'; const analytics = getAnalyticsTag(config); - const urlReplacements = urlReplacementsForDoc(analytics.element); + const urlReplacements = Services.urlReplacementsForDoc(analytics.element); sandbox.stub(urlReplacements.getVariableSource(), 'get') .returns({sync: null}); @@ -1181,7 +1179,7 @@ describe('amp-analytics', function() { config.triggers.conditional.enabled = '${queryParam(undefinedParam)}'; const analytics = getAnalyticsTag(config); - const urlReplacements = urlReplacementsForDoc(analytics.element); + const urlReplacements = Services.urlReplacementsForDoc(analytics.element); sandbox.stub(urlReplacements.getVariableSource(), 'get') .returns({sync: NaN}); @@ -1196,7 +1194,7 @@ describe('amp-analytics', function() { config.triggers.conditional.enabled = '${queryParam(undefinedParam)}'; const analytics = getAnalyticsTag(config); - const urlReplacements = urlReplacementsForDoc(analytics.element); + const urlReplacements = Services.urlReplacementsForDoc(analytics.element); sandbox.stub(urlReplacements.getVariableSource(), 'get') .returns({sync: undefined}); @@ -1222,7 +1220,7 @@ describe('amp-analytics', function() { config.enabled = '${pageViewId}'; const analytics = getAnalyticsTag(config); - const urlReplacements = urlReplacementsForDoc(analytics.element); + const urlReplacements = Services.urlReplacementsForDoc(analytics.element); sandbox.stub(urlReplacements.getVariableSource(), 'get') .returns({sync: 1}); return waitForSendRequest(analytics).then(() => { @@ -1257,7 +1255,7 @@ describe('amp-analytics', function() { config.enabled = '${queryParam(undefinedParam)}'; const analytics = getAnalyticsTag(config); - const urlReplacements = urlReplacementsForDoc(analytics.element); + const urlReplacements = Services.urlReplacementsForDoc(analytics.element); sandbox.stub(urlReplacements.getVariableSource(), 'get').returns(null); return waitForNoSendRequest(analytics).then(() => { @@ -1274,7 +1272,7 @@ describe('amp-analytics', function() { const analytics = getAnalyticsTag(config); - const urlReplacements = urlReplacementsForDoc(analytics.element); + const urlReplacements = Services.urlReplacementsForDoc(analytics.element); sandbox.stub(urlReplacements.getVariableSource(), 'get').returns(null); return waitForNoSendRequest(analytics).then(() => { @@ -1289,7 +1287,7 @@ describe('amp-analytics', function() { config.triggers.conditional.enabled = '${foo}'; const analytics = getAnalyticsTag(config); - const urlReplacements = urlReplacementsForDoc(analytics.element); + const urlReplacements = Services.urlReplacementsForDoc(analytics.element); sandbox.stub(urlReplacements.getVariableSource(), 'get').returns('page'); return waitForNoSendRequest(analytics).then(() => { @@ -1567,7 +1565,7 @@ describe('amp-analytics', function() { 'sandbox': 'true', }, true); - const urlReplacements = urlReplacementsForDoc(analytics.element); + const urlReplacements = Services.urlReplacementsForDoc(analytics.element); sandbox.stub(urlReplacements.getVariableSource(), 'get').returns(0); sandbox.stub(crypto, 'uniform') .withArgs('0').returns(Promise.resolve(0.005)) diff --git a/extensions/amp-analytics/0.1/test/test-instrumentation.js b/extensions/amp-analytics/0.1/test/test-instrumentation.js index 5d9067e1c46f..8db9118e53f9 100644 --- a/extensions/amp-analytics/0.1/test/test-instrumentation.js +++ b/extensions/amp-analytics/0.1/test/test-instrumentation.js @@ -33,7 +33,7 @@ import {installPlatformService} from '../../../../src/service/platform-impl'; import { installResourcesServiceForDoc, } from '../../../../src/service/resources-impl'; -import {documentStateFor} from '../../../../src/services'; +import {Services} from '../../../../src/services'; describes.realWin('InstrumentationService', {amp: 1}, env => { let win; @@ -291,7 +291,7 @@ describe('amp-analytics.instrumentation OLD', function() { beforeEach(() => { sandbox = sinon.sandbox.create(); clock = sandbox.useFakeTimers(); - const docState = documentStateFor(window); + const docState = Services.documentStateFor(window); sandbox.stub(docState, 'isHidden', () => false); ampdoc = new AmpDocSingle(window); installResourcesServiceForDoc(ampdoc); diff --git a/extensions/amp-analytics/0.1/test/test-visibility-manager.js b/extensions/amp-analytics/0.1/test/test-visibility-manager.js index 7d9093fa55e7..832f6fbc692b 100644 --- a/extensions/amp-analytics/0.1/test/test-visibility-manager.js +++ b/extensions/amp-analytics/0.1/test/test-visibility-manager.js @@ -23,7 +23,7 @@ import { VisibilityManagerForEmbed, } from '../visibility-manager'; import {VisibilityState} from '../../../../src/visibility-state'; -import {documentStateFor} from '../../../../src/services'; +import {Services} from '../../../../src/services'; import {layoutRectLtwh, rectIntersection} from '../../../../src/layout-rect'; class IntersectionObserverStub { @@ -833,7 +833,7 @@ describes.realWin('VisibilityManager integrated', {amp: true}, env => { eventResolver2 = resolve; }); - const docState = documentStateFor(win); + const docState = Services.documentStateFor(win); sandbox.stub(docState, 'isHidden', () => false); sandbox.stub(viewer, 'getFirstVisibleTime', () => startTime); diff --git a/extensions/amp-analytics/0.1/transport.js b/extensions/amp-analytics/0.1/transport.js index 5fcaea7de516..27c4a4cfd614 100644 --- a/extensions/amp-analytics/0.1/transport.js +++ b/extensions/amp-analytics/0.1/transport.js @@ -21,7 +21,7 @@ import { } from '../../../src/url'; import {dev, user} from '../../../src/log'; import {loadPromise} from '../../../src/event-helper'; -import {timerFor} from '../../../src/services'; +import {Services} from '../../../src/services'; import {removeElement} from '../../../src/dom'; import {setStyle} from '../../../src/style'; @@ -134,7 +134,7 @@ export function sendRequestUsingIframe(win, request) { const iframe = win.document.createElement('iframe'); setStyle(iframe, 'display', 'none'); iframe.onload = iframe.onerror = () => { - timerFor(win).delay(() => { + Services.timerFor(win).delay(() => { removeElement(iframe); }, 5000); }; diff --git a/extensions/amp-analytics/0.1/variables.js b/extensions/amp-analytics/0.1/variables.js index 651c3a76a917..5b5116a937d5 100644 --- a/extensions/amp-analytics/0.1/variables.js +++ b/extensions/amp-analytics/0.1/variables.js @@ -15,7 +15,7 @@ */ import {isExperimentOn} from '../../../src/experiments'; -import {cryptoFor} from '../../../src/services'; +import {Services} from '../../../src/services'; import {dev, user} from '../../../src/log'; import {getService, registerServiceBuilder} from '../../../src/service'; import {isArray, isFiniteNumber} from '../../../src/types'; @@ -291,7 +291,7 @@ export class VariableService { * @return {!Promise} */ hashFilter_(value) { - return cryptoFor(this.win_).sha384Base64(value); + return Services.cryptoFor(this.win_).sha384Base64(value); } isFilterExperimentOn_() { diff --git a/extensions/amp-analytics/0.1/visibility-manager.js b/extensions/amp-analytics/0.1/visibility-manager.js index 3648b6d69ba3..dca32b772640 100644 --- a/extensions/amp-analytics/0.1/visibility-manager.js +++ b/extensions/amp-analytics/0.1/visibility-manager.js @@ -23,9 +23,7 @@ import {VisibilityModel} from './visibility-model'; import {dev} from '../../../src/log'; import {getMode} from '../../../src/mode'; import {map} from '../../../src/utils/object'; -import {resourcesForDoc} from '../../../src/services'; -import {viewerForDoc} from '../../../src/services'; -import {viewportForDoc} from '../../../src/services'; +import {Services} from '../../../src/services'; const VISIBILITY_ID_PROP = '__AMP_VIS_ID'; @@ -67,7 +65,7 @@ export class VisibilityManager { this.ampdoc = ampdoc; /** @const @private */ - this.resources_ = resourcesForDoc(ampdoc); + this.resources_ = Services.resourcesForDoc(ampdoc); /** @private {number} */ this.rootVisibility_ = 0; @@ -338,10 +336,10 @@ export class VisibilityManagerForDoc extends VisibilityManager { super(/* parent */ null, ampdoc); /** @const @private */ - this.viewer_ = viewerForDoc(ampdoc); + this.viewer_ = Services.viewerForDoc(ampdoc); /** @const @private */ - this.viewport_ = viewportForDoc(ampdoc); + this.viewport_ = Services.viewportForDoc(ampdoc); /** @private {boolean} */ this.backgrounded_ = !this.viewer_.isVisible(); diff --git a/extensions/amp-animation/0.1/amp-animation.js b/extensions/amp-animation/0.1/amp-animation.js index fa8eee7141a0..23b8274b23fc 100644 --- a/extensions/amp-animation/0.1/amp-animation.js +++ b/extensions/amp-animation/0.1/amp-animation.js @@ -29,7 +29,7 @@ import {listen} from '../../../src/event-helper'; import {setStyles} from '../../../src/style'; import {tryParseJson} from '../../../src/json'; import {user, dev} from '../../../src/log'; -import {viewerForDoc} from '../../../src/services'; +import {Services} from '../../../src/services'; const TAG = 'amp-animation'; const POLYFILLED = '__AMP_WA'; @@ -125,7 +125,7 @@ export class AmpAnimation extends AMP.BaseElement { }); listen(this.embed_.win, 'resize', () => this.onResize_()); } else { - const viewer = viewerForDoc(ampdoc); + const viewer = Services.viewerForDoc(ampdoc); this.setVisible_(viewer.isVisible()); viewer.onVisibilityChanged(() => { this.setVisible_(viewer.isVisible()); diff --git a/extensions/amp-apester-media/0.1/amp-apester-media.js b/extensions/amp-apester-media/0.1/amp-apester-media.js index d238981e2e6f..9108edd848ad 100644 --- a/extensions/amp-apester-media/0.1/amp-apester-media.js +++ b/extensions/amp-apester-media/0.1/amp-apester-media.js @@ -17,8 +17,7 @@ import {CSS} from '../../../build/amp-apester-media-0.1.css'; import {user, dev} from '../../../src/log'; import {getLengthNumeral, isLayoutSizeDefined} from '../../../src/layout'; import {removeElement} from '../../../src/dom'; -import {vsyncFor} from '../../../src/services'; -import {xhrFor} from '../../../src/services'; +import {Services} from '../../../src/services'; /** @const */ @@ -134,7 +133,7 @@ class AmpApesterMedia extends AMP.BaseElement { **/ queryMedia_() { const url = this.buildUrl_(); - return xhrFor(this.win).fetchJson(url, { + return Services.xhrFor(this.win).fetchJson(url, { requireAmpResponseSourceOrigin: false, }).then(res => res.json()); } @@ -247,7 +246,7 @@ class AmpApesterMedia extends AMP.BaseElement { this.element.appendChild(overflow); this.element.appendChild(iframe); return this.iframePromise_ = this.loadPromise(iframe).then(() => { - vsyncFor(this.win).runPromise({mutate}, state); + Services.vsyncFor(this.win).runPromise({mutate}, state); return media; }); }, error => { diff --git a/extensions/amp-apester-media/0.1/test/test-amp-apester-media.js b/extensions/amp-apester-media/0.1/test/test-amp-apester-media.js index c98ddadac91b..f6117f831588 100644 --- a/extensions/amp-apester-media/0.1/test/test-amp-apester-media.js +++ b/extensions/amp-apester-media/0.1/test/test-amp-apester-media.js @@ -19,7 +19,7 @@ import { } from '../../../../testing/iframe'; import '../amp-apester-media'; import {adopt} from '../../../../src/runtime'; -import {xhrFor} from '../../../../src/services'; +import {Services} from '../../../../src/services'; import * as sinon from 'sinon'; adopt(window); @@ -66,7 +66,7 @@ describe('amp-apester-media', () => { media.implementation_, 'changeHeight'); attemptChangeSizeSpy = sandbox.spy( media.implementation_, 'attemptChangeHeight'); - xhrMock = sandbox.mock(xhrFor(iframe.win)); + xhrMock = sandbox.mock(Services.xhrFor(iframe.win)); xhrMock.expects('fetchJson').returns(Promise.resolve({ json() { return Promise.resolve(response); diff --git a/extensions/amp-app-banner/0.1/amp-app-banner.js b/extensions/amp-app-banner/0.1/amp-app-banner.js index 05b721cd5074..fb25903100f8 100644 --- a/extensions/amp-app-banner/0.1/amp-app-banner.js +++ b/extensions/amp-app-banner/0.1/amp-app-banner.js @@ -17,15 +17,10 @@ import {Layout} from '../../../src/layout'; import {dict} from '../../../src/utils/object'; import {user, dev, rethrowAsync} from '../../../src/log'; -import {platformFor} from '../../../src/services'; -import {viewerForDoc} from '../../../src/services'; +import {Services} from '../../../src/services'; import {CSS} from '../../../build/amp-app-banner-0.1.css'; -import {documentInfoForDoc} from '../../../src/services'; -import {xhrFor} from '../../../src/services'; import {assertHttpsUrl} from '../../../src/url'; import {removeElement, openWindowDialog} from '../../../src/dom'; -import {storageForDoc} from '../../../src/services'; -import {timerFor} from '../../../src/services'; import {parseUrl} from '../../../src/url'; import {isProxyOrigin, isProtocolValid} from '../../../src/url'; @@ -99,7 +94,7 @@ export class AbstractAppBanner extends AMP.BaseElement { }, { element: this.element, viewport: this.getViewport(), - storagePromise: storageForDoc(this.getAmpDoc()), + storagePromise: Services.storageForDoc(this.getAmpDoc()), storageKey: this.getStorageKey_(), }); } @@ -113,7 +108,7 @@ export class AbstractAppBanner extends AMP.BaseElement { /** @protected */ isDismissed() { - return storageForDoc(this.getAmpDoc()) + return Services.storageForDoc(this.getAmpDoc()) .then(storage => storage.get(this.getStorageKey_())) .then(persistedValue => !!persistedValue, reason => { dev().error(TAG, 'Failed to read storage', reason); @@ -169,7 +164,7 @@ export class AmpAppBanner extends AbstractAppBanner { /** @override */ upgradeCallback() { - const platform = platformFor(this.win); + const platform = Services.platformFor(this.win); if (platform.isIos()) { return new AmpIosAppBanner(this.element); } else if (platform.isAndroid()) { @@ -195,7 +190,7 @@ export class AmpIosAppBanner extends AbstractAppBanner { super(element); /** @private @const {!../../../src/service/viewer-impl.Viewer} */ - this.viewer_ = viewerForDoc(this.getAmpDoc()); + this.viewer_ = Services.viewerForDoc(this.getAmpDoc()); /** @private {?Element} */ this.metaTag_ = null; @@ -216,7 +211,7 @@ export class AmpIosAppBanner extends AbstractAppBanner { /** @override */ buildCallback() { // We want to fallback to browser builtin mechanism when possible. - const platform = platformFor(this.win); + const platform = Services.platformFor(this.win); this.canShowBuiltinBanner_ = !this.viewer_.isEmbedded() && platform.isSafari(); if (this.canShowBuiltinBanner_) { @@ -263,12 +258,12 @@ export class AmpIosAppBanner extends AbstractAppBanner { /** @override */ openButtonClicked(openInAppUrl, installAppUrl) { if (!this.viewer_.isEmbedded()) { - timerFor(this.win).delay(() => { + Services.timerFor(this.win).delay(() => { openWindowDialog(this.win, installAppUrl, '_top'); }, OPEN_LINK_TIMEOUT); openWindowDialog(this.win, openInAppUrl, '_top'); } else { - timerFor(this.win).delay(() => { + Services.timerFor(this.win).delay(() => { this.viewer_.sendMessage('navigateTo', dict({'url': installAppUrl})); }, OPEN_LINK_TIMEOUT); this.viewer_.sendMessage('navigateTo', dict({'url': openInAppUrl})); @@ -338,11 +333,11 @@ export class AmpAndroidAppBanner extends AbstractAppBanner { /** @override */ buildCallback() { - const viewer = viewerForDoc(this.getAmpDoc()); + const viewer = Services.viewerForDoc(this.getAmpDoc()); this.manifestLink_ = this.win.document.head.querySelector( 'link[rel=manifest],link[rel=origin-manifest]'); - const platform = platformFor(this.win); + const platform = Services.platformFor(this.win); // We want to fallback to browser builtin mechanism when possible. const isChromeAndroid = platform.isAndroid() && platform.isChrome(); this.canShowBuiltinBanner_ = !isProxyOrigin(this.win.location) && @@ -382,7 +377,7 @@ export class AmpAndroidAppBanner extends AbstractAppBanner { return Promise.resolve(); } - return xhrFor(this.win).fetchJson(this.manifestHref_, { + return Services.xhrFor(this.win).fetchJson(this.manifestHref_, { requireAmpResponseSourceOrigin: false, }).then(res => res.json()) .then(json => this.parseManifest_(json)) @@ -394,7 +389,7 @@ export class AmpAndroidAppBanner extends AbstractAppBanner { /** @override */ openButtonClicked(openInAppUrl, installAppUrl) { - timerFor(this.win).delay(() => { + Services.timerFor(this.win).delay(() => { this.redirectTopLocation_(installAppUrl); }, OPEN_LINK_TIMEOUT); openWindowDialog(this.win, openInAppUrl, '_top'); @@ -435,7 +430,7 @@ export class AmpAndroidAppBanner extends AbstractAppBanner { /** @private */ getAndroidIntentForUrl_(appId) { - const canonicalUrl = documentInfoForDoc(this.element).canonicalUrl; + const canonicalUrl = Services.documentInfoForDoc(this.element).canonicalUrl; const parsedUrl = parseUrl(canonicalUrl); const cleanProtocol = parsedUrl.protocol.replace(':', ''); const host = parsedUrl.host; diff --git a/extensions/amp-app-banner/0.1/test/test-amp-app-banner.js b/extensions/amp-app-banner/0.1/test/test-amp-app-banner.js index 195bc018fa76..2c992969865b 100644 --- a/extensions/amp-app-banner/0.1/test/test-amp-app-banner.js +++ b/extensions/amp-app-banner/0.1/test/test-amp-app-banner.js @@ -15,17 +15,14 @@ */ import {createIframePromise} from '../../../../testing/iframe'; -import {platformFor} from '../../../../src/services'; -import {vsyncFor} from '../../../../src/services'; +import {Services} from '../../../../src/services'; import { AmpAppBanner, AbstractAppBanner, AmpIosAppBanner, AmpAndroidAppBanner, } from '../amp-app-banner'; -import {xhrFor} from '../../../../src/services'; import {AmpDocSingle} from '../../../../src/service/ampdoc-impl'; -import {viewerForDoc} from '../../../../src/services'; describes.realWin('amp-app-banner', {amp: true}, () => { @@ -69,10 +66,10 @@ describes.realWin('amp-app-banner', {amp: true}, () => { function getTestFrame() { return createIframePromise(true).then(iframe => { const ampdoc = new AmpDocSingle(iframe.win); - const viewer = viewerForDoc(ampdoc); + const viewer = Services.viewerForDoc(ampdoc); sandbox.stub(viewer, 'isEmbedded', () => isEmbedded); sandbox.stub(viewer, 'hasCapability', () => hasNavigateToCapability); - platform = platformFor(iframe.win); + platform = Services.platformFor(iframe.win); sandbox.stub(platform, 'isIos', () => isIos); sandbox.stub(platform, 'isAndroid', () => isAndroid); sandbox.stub(platform, 'isChrome', () => isChrome); @@ -80,7 +77,7 @@ describes.realWin('amp-app-banner', {amp: true}, () => { sandbox.stub(platform, 'isFirefox', () => isFirefox); sandbox.stub(platform, 'isEdge', () => isEdge); - vsync = vsyncFor(iframe.win); + vsync = Services.vsyncFor(iframe.win); sandbox.stub(vsync, 'runPromise', (task, state) => { runTask(task, state); return Promise.resolve(); @@ -111,7 +108,7 @@ describes.realWin('amp-app-banner', {amp: true}, () => { manifest.setAttribute('rel', rel); manifest.setAttribute('href', manifestObj.href); iframe.doc.head.appendChild(manifest); - sandbox.mock(xhrFor(iframe.win)).expects('fetchJson') + sandbox.mock(Services.xhrFor(iframe.win)).expects('fetchJson') .returns(Promise.resolve({ json() { return Promise.resolve(manifestObj.content); @@ -523,7 +520,7 @@ describes.realWin('amp-app-banner', {amp: true}, () => { return createIframePromise(true).then(iframe => { const win = iframe.win; const doc = iframe.doc; - vsync = vsyncFor(win); + vsync = Services.vsyncFor(win); sandbox.stub(vsync, 'run', runTask); const element = doc.createElement('div'); element.id = 'banner1'; diff --git a/extensions/amp-auto-ads/0.1/ad-network-config.js b/extensions/amp-auto-ads/0.1/ad-network-config.js index ede899d56e6b..6240830f4d5f 100644 --- a/extensions/amp-auto-ads/0.1/ad-network-config.js +++ b/extensions/amp-auto-ads/0.1/ad-network-config.js @@ -20,9 +20,8 @@ import { } from '../../../ads/google/adsense-amp-auto-ads'; import {buildUrl} from '../../../ads/google/a4a/url-builder'; import {dict} from '../../../src/utils/object'; -import {documentInfoForDoc} from '../../../src/services'; +import {Services} from '../../../src/services'; import {parseUrl} from '../../../src/url'; -import {viewportForDoc} from '../../../src/services'; /** @@ -92,7 +91,7 @@ class AdSenseNetworkConfig { /** @override */ getConfigUrl() { - const docInfo = documentInfoForDoc(this.autoAmpAdsElement_); + const docInfo = Services.documentInfoForDoc(this.autoAmpAdsElement_); const canonicalHostname = parseUrl(docInfo.canonicalUrl).hostname; return buildUrl('//pagead2.googlesyndication.com/getconfig/ama', { 'client': this.autoAmpAdsElement_.getAttribute('data-ad-client'), @@ -112,7 +111,7 @@ class AdSenseNetworkConfig { /** @override */ getAdConstraints() { const viewportHeight = - viewportForDoc(this.autoAmpAdsElement_).getSize().height; + Services.viewportForDoc(this.autoAmpAdsElement_).getSize().height; return { initialMinSpacing: viewportHeight, subsequentMinSpacing: [ diff --git a/extensions/amp-auto-ads/0.1/ad-tracker.js b/extensions/amp-auto-ads/0.1/ad-tracker.js index c9082d61a396..30c32e5e4add 100644 --- a/extensions/amp-auto-ads/0.1/ad-tracker.js +++ b/extensions/amp-auto-ads/0.1/ad-tracker.js @@ -14,7 +14,7 @@ * limitations under the License. */ -import {resourcesForDoc} from '../../../src/services'; +import {Services} from '../../../src/services'; /** * Structure for defining contraints about the placement of ads. @@ -129,7 +129,7 @@ export class AdTracker { * @private */ getDistanceFromAd_(yPosition, ad) { - return resourcesForDoc(ad).getElementLayoutBox(ad).then(box => { + return Services.resourcesForDoc(ad).getElementLayoutBox(ad).then(box => { if (yPosition >= box.top && yPosition <= box.bottom) { return 0; } else { diff --git a/extensions/amp-auto-ads/0.1/amp-auto-ads.js b/extensions/amp-auto-ads/0.1/amp-auto-ads.js index c6f66c54e6a6..bd86e758dafc 100644 --- a/extensions/amp-auto-ads/0.1/amp-auto-ads.js +++ b/extensions/amp-auto-ads/0.1/amp-auto-ads.js @@ -18,7 +18,7 @@ import {AdTracker, getExistingAds} from './ad-tracker'; import {AdStrategy} from './ad-strategy'; import {AnchorAdStrategy} from './anchor-ad-strategy'; import {user} from '../../../src/log'; -import {xhrFor} from '../../../src/services'; +import {Services} from '../../../src/services'; import {getAdNetworkConfig} from './ad-network-config'; import {isExperimentOn} from '../../../src/experiments'; import {getAttributesFromConfigObj} from './attributes'; @@ -83,7 +83,7 @@ export class AmpAutoAds extends AMP.BaseElement { credentials: 'omit', requireAmpResponseSourceOrigin: false, }; - return xhrFor(this.win) + return Services.xhrFor(this.win) .fetchJson(configUrl, xhrInit) .then(res => res.json()) .catch(reason => { diff --git a/extensions/amp-auto-ads/0.1/anchor-ad-strategy.js b/extensions/amp-auto-ads/0.1/anchor-ad-strategy.js index 6af262b0bdda..c1512a74a400 100644 --- a/extensions/amp-auto-ads/0.1/anchor-ad-strategy.js +++ b/extensions/amp-auto-ads/0.1/anchor-ad-strategy.js @@ -16,7 +16,7 @@ import {createElementWithAttributes} from '../../../src/dom'; import {user} from '../../../src/log'; import {dict} from '../../../src/utils/object'; -import {viewportForDoc} from '../../../src/services'; +import {Services} from '../../../src/services'; /** @const */ const TAG = 'amp-auto-ads'; @@ -83,7 +83,8 @@ export class AnchorAdStrategy { } placeStickyAd_() { - const viewportWidth = viewportForDoc(this.win_.document).getWidth(); + const viewportWidth = + Services.viewportForDoc(this.win_.document).getWidth(); const attributes = /** @type {!JsonObject} */ ( Object.assign(dict(), this.baseAttributes_, dict({ 'width': String(viewportWidth), diff --git a/extensions/amp-auto-ads/0.1/placement.js b/extensions/amp-auto-ads/0.1/placement.js index 5068e9674e58..2ce34a8dd2bc 100644 --- a/extensions/amp-auto-ads/0.1/placement.js +++ b/extensions/amp-auto-ads/0.1/placement.js @@ -17,7 +17,7 @@ import {dev, user} from '../../../src/log'; import {dict} from '../../../src/utils/object'; import {getAttributesFromConfigObj} from './attributes'; -import {resourcesForDoc} from '../../../src/services'; +import {Services} from '../../../src/services'; import { closestByTag, createElementWithAttributes, @@ -268,7 +268,7 @@ function getPlacementsFromObject(win, placementObj, placements) { return; } const attributes = getAttributesFromConfigObj(placementObj); - placements.push(new Placement(win, resourcesForDoc(anchorElement), + placements.push(new Placement(win, Services.resourcesForDoc(anchorElement), anchorElement, placementObj['pos'], injector, attributes, margins)); }); } diff --git a/extensions/amp-auto-ads/0.1/test/test-ad-network-config.js b/extensions/amp-auto-ads/0.1/test/test-ad-network-config.js index 5ca2b169e442..fb9eedf5a253 100644 --- a/extensions/amp-auto-ads/0.1/test/test-ad-network-config.js +++ b/extensions/amp-auto-ads/0.1/test/test-ad-network-config.js @@ -19,7 +19,7 @@ import { toggleExperiment, forceExperimentBranch, } from '../../../../src/experiments'; -import {viewportForDoc} from '../../../../src/services'; +import {Services} from '../../../../src/services'; import { ADSENSE_AMP_AUTO_ADS_HOLDOUT_EXPERIMENT_NAME, AdSenseAmpAutoAdsHoldoutBranches, @@ -95,7 +95,8 @@ describes.realWin('ad-network-config', { }); it('should get the ad constraints', () => { - const viewportMock = sandbox.mock(viewportForDoc(env.win.document)); + const viewportMock = + sandbox.mock(Services.viewportForDoc(env.win.document)); viewportMock.expects('getSize').returns( {width: 320, height: 500}).atLeast(1); diff --git a/extensions/amp-auto-ads/0.1/test/test-ad-tracker.js b/extensions/amp-auto-ads/0.1/test/test-ad-tracker.js index aaaf9868b849..23d95f71ed65 100644 --- a/extensions/amp-auto-ads/0.1/test/test-ad-tracker.js +++ b/extensions/amp-auto-ads/0.1/test/test-ad-tracker.js @@ -17,7 +17,7 @@ import {AdTracker, getExistingAds} from '../ad-tracker'; import {layoutRectLtwh} from '../../../../src/layout-rect'; -import {resourcesForDoc} from '../../../../src/services'; +import {Services} from '../../../../src/services'; import * as sinon from 'sinon'; describe('ad-tracker', () => { @@ -30,7 +30,7 @@ describe('ad-tracker', () => { doc = window.document; sandbox = sinon.sandbox.create(); - resources = resourcesForDoc(doc); + resources = Services.resourcesForDoc(doc); sandbox.stub(resources, 'getElementLayoutBox', element => { return Promise.resolve(element.layoutBox); }); diff --git a/extensions/amp-auto-ads/0.1/test/test-amp-auto-ads.js b/extensions/amp-auto-ads/0.1/test/test-amp-auto-ads.js index 1a369c847cfe..bf8e14f68ed2 100644 --- a/extensions/amp-auto-ads/0.1/test/test-amp-auto-ads.js +++ b/extensions/amp-auto-ads/0.1/test/test-amp-auto-ads.js @@ -20,9 +20,8 @@ import { toggleExperiment, forceExperimentBranch, } from '../../../../src/experiments'; -import {xhrFor} from '../../../../src/services'; +import {Services} from '../../../../src/services'; import {waitForChild} from '../../../../src/dom'; -import {viewportForDoc} from '../../../../src/services'; import { ADSENSE_AMP_AUTO_ADS_HOLDOUT_EXPERIMENT_NAME, AdSenseAmpAutoAdsHoldoutBranches, @@ -64,7 +63,8 @@ describes.realWin('amp-auto-ads', { toggleExperiment(env.win, 'amp-auto-ads', true); sandbox = env.sandbox; - const viewportMock = sandbox.mock(viewportForDoc(env.win.document)); + const viewportMock = + sandbox.mock(Services.viewportForDoc(env.win.document)); viewportMock.expects('getSize').returns( {width: 320, height: 500}).atLeast(1); @@ -136,7 +136,7 @@ describes.realWin('amp-auto-ads', { optInStatus: [1], }; - xhr = xhrFor(env.win); + xhr = Services.xhrFor(env.win); xhr.fetchJson = () => { return Promise.resolve({ json() { diff --git a/extensions/amp-auto-ads/0.1/test/test-anchor-ad-strategy.js b/extensions/amp-auto-ads/0.1/test/test-anchor-ad-strategy.js index 367fd84b6fd6..8ca62db9405c 100644 --- a/extensions/amp-auto-ads/0.1/test/test-anchor-ad-strategy.js +++ b/extensions/amp-auto-ads/0.1/test/test-anchor-ad-strategy.js @@ -16,7 +16,7 @@ import '../../../amp-ad/0.1/amp-ad'; import {waitForChild} from '../../../../src/dom'; -import {viewportForDoc} from '../../../../src/services'; +import {Services} from '../../../../src/services'; import {AnchorAdStrategy} from '../anchor-ad-strategy'; describes.realWin('anchor-ad-strategy', { @@ -32,7 +32,8 @@ describes.realWin('anchor-ad-strategy', { beforeEach(() => { sandbox = env.sandbox; - const viewportMock = sandbox.mock(viewportForDoc(env.win.document)); + const viewportMock = + sandbox.mock(Services.viewportForDoc(env.win.document)); viewportMock.expects('getWidth').returns(360).atLeast(1); configObj = { diff --git a/extensions/amp-auto-ads/0.1/test/test-placement.js b/extensions/amp-auto-ads/0.1/test/test-placement.js index 0b62ca13f1b4..a32d55e704c2 100644 --- a/extensions/amp-auto-ads/0.1/test/test-placement.js +++ b/extensions/amp-auto-ads/0.1/test/test-placement.js @@ -15,7 +15,7 @@ */ import {AdTracker} from '../ad-tracker'; -import {resourcesForDoc} from '../../../../src/services'; +import {Services} from '../../../../src/services'; import {PlacementState, getPlacementsFromConfigObj} from '../placement'; describes.realWin('placement', { @@ -517,7 +517,7 @@ describes.realWin('placement', { anchor.id = 'anId'; container.appendChild(anchor); - const resource = resourcesForDoc(anchor); + const resource = Services.resourcesForDoc(anchor); sandbox.stub(resource, 'attemptChangeSize', () => { return Promise.resolve(); }); @@ -557,7 +557,7 @@ describes.realWin('placement', { anchor.id = 'anId'; container.appendChild(anchor); - const resource = resourcesForDoc(anchor); + const resource = Services.resourcesForDoc(anchor); sandbox.stub(resource, 'attemptChangeSize', () => { return Promise.reject(new Error('Resize failed')); }); diff --git a/extensions/amp-bind/0.1/amp-state.js b/extensions/amp-bind/0.1/amp-state.js index f6678b5fb25a..dbc8185251cd 100644 --- a/extensions/amp-bind/0.1/amp-state.js +++ b/extensions/amp-bind/0.1/amp-state.js @@ -14,7 +14,7 @@ * limitations under the License. */ -import {bindForDoc, viewerForDoc} from '../../../src/services'; +import {Services} from '../../../src/services'; import {fetchBatchedJsonFor} from '../../../src/batched-json'; import {isJsonScriptTag} from '../../../src/dom'; import {toggle} from '../../../src/style'; @@ -53,13 +53,13 @@ export class AmpState extends AMP.BaseElement { this.element.setAttribute('aria-hidden', 'true'); // Don't parse or fetch in prerender mode. - const viewer = viewerForDoc(this.getAmpDoc()); + const viewer = Services.viewerForDoc(this.getAmpDoc()); viewer.whenFirstVisible().then(() => this.initialize_()); } /** @override */ mutatedAttributesCallback(mutations) { - const viewer = viewerForDoc(this.getAmpDoc()); + const viewer = Services.viewerForDoc(this.getAmpDoc()); if (!viewer.isVisible()) { const TAG = this.getName_(); dev().error(TAG, 'Viewer must be visible before mutation.'); @@ -148,7 +148,7 @@ export class AmpState extends AMP.BaseElement { const id = user().assert(this.element.id, ' must have an id.'); const state = Object.create(null); state[id] = json; - bindForDoc(this.element).then(bind => { + Services.bindForDoc(this.element).then(bind => { bind.setState(state, /* opt_skipEval */ isInit, /* opt_isAmpStateMutation */ !isInit); }); diff --git a/extensions/amp-bind/0.1/bind-impl.js b/extensions/amp-bind/0.1/bind-impl.js index 5c0ef44c3016..4ed0acb26b26 100644 --- a/extensions/amp-bind/0.1/bind-impl.js +++ b/extensions/amp-bind/0.1/bind-impl.js @@ -17,10 +17,7 @@ import {BindExpressionResultDef} from './bind-expression'; import {BindingDef} from './bind-evaluator'; import {BindValidator} from './bind-validator'; -import { - resourcesForDoc, - viewerForDoc, -} from '../../../src/services'; +import {Services} from '../../../src/services'; import {chunk, ChunkPriority} from '../../../src/chunk'; import {dev, user} from '../../../src/log'; import {dict, deepMerge} from '../../../src/utils/object'; @@ -131,10 +128,10 @@ export class Bind { this.scope_ = dict(); /** @const @private {!../../../src/service/resources-impl.Resources} */ - this.resources_ = resourcesForDoc(ampdoc); + this.resources_ = Services.resourcesForDoc(ampdoc); /** @const @private {!../../../src/service/viewer-impl.Viewer} */ - this.viewer_ = viewerForDoc(this.ampdoc); + this.viewer_ = Services.viewerForDoc(this.ampdoc); const bodyPromise = (opt_win) ? waitForBodyPromise(opt_win.document) diff --git a/extensions/amp-bind/0.1/test/test-amp-state.js b/extensions/amp-bind/0.1/test/test-amp-state.js index 1de74fb33bd2..9ce711f579c9 100644 --- a/extensions/amp-bind/0.1/test/test-amp-state.js +++ b/extensions/amp-bind/0.1/test/test-amp-state.js @@ -15,7 +15,7 @@ */ import '../amp-bind'; -import {viewerForDoc} from '../../../../src/services'; +import {Services} from '../../../../src/services'; describes.realWin('AmpState', { amp: { @@ -43,7 +43,7 @@ describes.realWin('AmpState', { } beforeEach(() => { - viewer = viewerForDoc(env.win.document); + viewer = Services.viewerForDoc(env.win.document); whenFirstVisiblePromise = new Promise(resolve => { whenFirstVisiblePromiseResolve = resolve; }); diff --git a/extensions/amp-brid-player/0.1/amp-brid-player.js b/extensions/amp-brid-player/0.1/amp-brid-player.js index 0ec331536b99..45228e614eff 100644 --- a/extensions/amp-brid-player/0.1/amp-brid-player.js +++ b/extensions/amp-brid-player/0.1/amp-brid-player.js @@ -20,7 +20,7 @@ import { installVideoManagerForDoc, } from '../../../src/service/video-manager-impl'; import {VideoEvents} from '../../../src/video-interface'; -import {videoManagerForDoc} from '../../../src/services'; +import {Services} from '../../../src/services'; import {assertAbsoluteHttpOrHttpsUrl} from '../../../src/url'; import {removeElement} from '../../../src/dom'; import {getData, listen} from '../../../src/event-helper'; @@ -125,7 +125,7 @@ class AmpBridPlayer extends AMP.BaseElement { }); installVideoManagerForDoc(this.element); - videoManagerForDoc(this.element).register(this); + Services.videoManagerForDoc(this.element).register(this); } /** @override */ diff --git a/extensions/amp-brid-player/0.1/test/test-amp-brid-player.js b/extensions/amp-brid-player/0.1/test/test-amp-brid-player.js index 3095d3f76099..e9f11c9ce85f 100644 --- a/extensions/amp-brid-player/0.1/test/test-amp-brid-player.js +++ b/extensions/amp-brid-player/0.1/test/test-amp-brid-player.js @@ -21,7 +21,7 @@ import { import '../amp-brid-player'; import {listenOncePromise} from '../../../../src/event-helper'; import {adopt} from '../../../../src/runtime'; -import {timerFor} from '../../../../src/services'; +import {Services} from '../../../../src/services'; import {VideoEvents} from '../../../../src/video-interface'; import * as sinon from 'sinon'; @@ -30,7 +30,7 @@ adopt(window); describe('amp-brid-player', () => { let sandbox; - const timer = timerFor(window); + const timer = Services.timerFor(window); beforeEach(() => { sandbox = sinon.sandbox.create(); diff --git a/extensions/amp-call-tracking/0.1/amp-call-tracking.js b/extensions/amp-call-tracking/0.1/amp-call-tracking.js index 930dfc7110ec..3d80331cc691 100644 --- a/extensions/amp-call-tracking/0.1/amp-call-tracking.js +++ b/extensions/amp-call-tracking/0.1/amp-call-tracking.js @@ -16,9 +16,8 @@ import {assertHttpsUrl} from '../../../src/url'; import {Layout, isLayoutSizeDefined} from '../../../src/layout'; -import {urlReplacementsForDoc} from '../../../src/services'; +import {Services} from '../../../src/services'; import {user} from '../../../src/log'; -import {xhrFor} from '../../../src/services'; /** @@ -36,7 +35,7 @@ let cachedResponsePromises_ = {}; */ function fetch_(win, url) { if (!(url in cachedResponsePromises_)) { - cachedResponsePromises_[url] = xhrFor(win).fetchJson(url) + cachedResponsePromises_[url] = Services.xhrFor(win).fetchJson(url) .then(res => res.json()); } return cachedResponsePromises_[url]; @@ -81,7 +80,7 @@ export class AmpCallTracking extends AMP.BaseElement { /** @override */ layoutCallback() { - return urlReplacementsForDoc(this.getAmpDoc()) + return Services.urlReplacementsForDoc(this.getAmpDoc()) .expandAsync(user().assertString(this.configUrl_)) .then(url => fetch_(this.win, url)) .then(data => { diff --git a/extensions/amp-call-tracking/0.1/test/test-amp-call-tracking.js b/extensions/amp-call-tracking/0.1/test/test-amp-call-tracking.js index c1327de51fb0..573534b44765 100644 --- a/extensions/amp-call-tracking/0.1/test/test-amp-call-tracking.js +++ b/extensions/amp-call-tracking/0.1/test/test-amp-call-tracking.js @@ -17,7 +17,7 @@ import '../amp-call-tracking'; import {clearResponseCache} from '../amp-call-tracking'; import {createIframePromise} from '../../../../testing/iframe'; -import {xhrFor} from '../../../../src/services'; +import {Services} from '../../../../src/services'; import * as sinon from 'sinon'; @@ -27,7 +27,7 @@ describe('amp-call-tracking', () => { function getTestIframe() { return createIframePromise().then(iframe => { - xhrMock = sandbox.mock(xhrFor(iframe.win)); + xhrMock = sandbox.mock(Services.xhrFor(iframe.win)); return iframe; }); } diff --git a/extensions/amp-carousel/0.1/base-carousel.js b/extensions/amp-carousel/0.1/base-carousel.js index c543acd7995e..4dab99c43624 100644 --- a/extensions/amp-carousel/0.1/base-carousel.js +++ b/extensions/amp-carousel/0.1/base-carousel.js @@ -14,7 +14,7 @@ * limitations under the License. */ import {KeyCodes} from '../../../src/utils/key-codes'; -import {timerFor} from '../../../src/services'; +import {Services} from '../../../src/services'; /** * @abstract @@ -182,7 +182,7 @@ export class BaseCarousel extends AMP.BaseElement { this.getVsync().mutate(() => { const className = 'i-amphtml-carousel-button-start-hint'; this.element.classList.add(className); - timerFor(this.win).delay(() => { + Services.timerFor(this.win).delay(() => { this.deferMutate(() => this.element.classList.remove(className)); }, 4000); }); diff --git a/extensions/amp-carousel/0.1/base-slides.js b/extensions/amp-carousel/0.1/base-slides.js index 186d63ac648d..67e7b1fe64ae 100644 --- a/extensions/amp-carousel/0.1/base-slides.js +++ b/extensions/amp-carousel/0.1/base-slides.js @@ -14,7 +14,7 @@ * limitations under the License. */ -import {timerFor} from '../../../src/services'; +import {Services} from '../../../src/services'; import {BaseCarousel} from './base-carousel'; export class BaseSlides extends BaseCarousel { @@ -141,7 +141,7 @@ export class BaseSlides extends BaseCarousel { return; } this.clearAutoplay(); - this.autoplayTimeoutId_ = timerFor(this.win).delay( + this.autoplayTimeoutId_ = Services.timerFor(this.win).delay( this.go.bind( this, /* dir */ 1, /* animate */ true, /* autoplay */ true), this.autoplayDelay_); @@ -153,7 +153,7 @@ export class BaseSlides extends BaseCarousel { */ clearAutoplay() { if (this.autoplayTimeoutId_ !== null) { - timerFor(this.win).cancel(this.autoplayTimeoutId_); + Services.timerFor(this.win).cancel(this.autoplayTimeoutId_); this.autoplayTimeoutId_ = null; } } diff --git a/extensions/amp-carousel/0.1/scrollable-carousel.js b/extensions/amp-carousel/0.1/scrollable-carousel.js index aaf44f05e578..c3d0f56f611d 100644 --- a/extensions/amp-carousel/0.1/scrollable-carousel.js +++ b/extensions/amp-carousel/0.1/scrollable-carousel.js @@ -17,7 +17,7 @@ import {Animation} from '../../../src/animation'; import {BaseCarousel} from './base-carousel'; import {Layout} from '../../../src/layout'; -import {timerFor} from '../../../src/services'; +import {Services} from '../../../src/services'; import {numeric} from '../../../src/transition'; import {dev} from '../../../src/log'; @@ -128,7 +128,7 @@ export class AmpScrollableCarousel extends BaseCarousel { * @private */ waitForScroll_(startingScrollLeft) { - this.scrollTimerId_ = timerFor(this.win).delay(() => { + this.scrollTimerId_ = Services.timerFor(this.win).delay(() => { // TODO(yuxichen): test out the threshold for identifying fast scrolling if (Math.abs(startingScrollLeft - this.pos_) < 30) { dev().fine(TAG, 'slow scrolling: ' + startingScrollLeft + ' - ' diff --git a/extensions/amp-carousel/0.1/slidescroll.js b/extensions/amp-carousel/0.1/slidescroll.js index eb967a7080e1..0c88325944fa 100644 --- a/extensions/amp-carousel/0.1/slidescroll.js +++ b/extensions/amp-carousel/0.1/slidescroll.js @@ -17,7 +17,7 @@ import {ActionTrust} from '../../../src/action-trust'; import {Animation} from '../../../src/animation'; import {BaseSlides} from './base-slides'; -import {actionServiceForDoc} from '../../../src/services'; +import {Services} from '../../../src/services'; import {bezierCurve} from '../../../src/curve'; import {createCustomEvent} from '../../../src/event-helper'; import {dev, user} from '../../../src/log'; @@ -25,8 +25,6 @@ import {isConnectedNode} from '../../../src/dom'; import {isLayoutSizeDefined} from '../../../src/layout'; import {getStyle, setStyle} from '../../../src/style'; import {numeric} from '../../../src/transition'; -import {platformFor} from '../../../src/services'; -import {timerFor} from '../../../src/services'; import {triggerAnalyticsEvent} from '../../../src/analytics'; import {isExperimentOn} from '../../../src/experiments'; import {startsWith} from '../../../src/string'; @@ -116,7 +114,7 @@ export class AmpSlideScroll extends BaseSlides { /** @private {!Array} */ this.dataSlideIdArr_ = []; - const platform = platformFor(this.win); + const platform = Services.platformFor(this.win); /** @private @const {boolean} */ this.isIos_ = platform.isIos(); @@ -127,7 +125,8 @@ export class AmpSlideScroll extends BaseSlides { /** @private {boolean} */ this.shouldDisableCssSnap_ = isExperimentOn(this.win, 'slidescroll-disable-css-snap') && - startsWith(platformFor(this.win).getIosVersionString(), '10.3'); + startsWith( + Services.platformFor(this.win).getIosVersionString(), '10.3'); } /** @override */ @@ -138,7 +137,7 @@ export class AmpSlideScroll extends BaseSlides { /** @override */ buildSlides() { this.vsync_ = this.getVsync(); - this.action_ = actionServiceForDoc(this.element); + this.action_ = Services.actionServiceForDoc(this.element); this.hasNativeSnapPoints_ = ( getStyle(this.element, 'scrollSnapType') != undefined); @@ -238,7 +237,7 @@ export class AmpSlideScroll extends BaseSlides { } this.hasTouchMoved_ = true; if (this.touchEndTimeout_) { - timerFor(this.win).cancel(this.touchEndTimeout_); + Services.timerFor(this.win).cancel(this.touchEndTimeout_); } } @@ -249,12 +248,12 @@ export class AmpSlideScroll extends BaseSlides { touchEndHandler_() { if (this.hasTouchMoved_) { if (this.scrollTimeout_) { - timerFor(this.win).cancel(this.scrollTimeout_); + Services.timerFor(this.win).cancel(this.scrollTimeout_); } const timeout = this.shouldDisableCssSnap_ ? IOS_TOUCH_TIMEOUT : NATIVE_TOUCH_TIMEOUT; // Timer that detects scroll end and/or end of snap scroll. - this.touchEndTimeout_ = timerFor(this.win).delay(() => { + this.touchEndTimeout_ = Services.timerFor(this.win).delay(() => { const currentScrollLeft = this.slidesContainer_./*OK*/scrollLeft; if (this.snappingInProgress_) { @@ -341,7 +340,7 @@ export class AmpSlideScroll extends BaseSlides { */ scrollHandler_(unusedEvent) { if (this.scrollTimeout_) { - timerFor(this.win).cancel(this.scrollTimeout_); + Services.timerFor(this.win).cancel(this.scrollTimeout_); } const currentScrollLeft = this.slidesContainer_./*OK*/scrollLeft; @@ -353,7 +352,7 @@ export class AmpSlideScroll extends BaseSlides { const timeout = this.hasNativeSnapPoints_ ? NATIVE_SNAP_TIMEOUT : ( this.isIos_ ? IOS_CUSTOM_SNAP_TIMEOUT : CUSTOM_SNAP_TIMEOUT); // Timer that detects scroll end and/or end of snap scroll. - this.scrollTimeout_ = timerFor(this.win).delay(() => { + this.scrollTimeout_ = Services.timerFor(this.win).delay(() => { if (this.snappingInProgress_) { return; diff --git a/extensions/amp-dailymotion/0.1/amp-dailymotion.js b/extensions/amp-dailymotion/0.1/amp-dailymotion.js index 327958b347dd..2f02e6df3224 100644 --- a/extensions/amp-dailymotion/0.1/amp-dailymotion.js +++ b/extensions/amp-dailymotion/0.1/amp-dailymotion.js @@ -22,7 +22,7 @@ import { installVideoManagerForDoc, } from '../../../src/service/video-manager-impl'; import {getData, listen} from '../../../src/event-helper'; -import {videoManagerForDoc} from '../../../src/services'; +import {Services} from '../../../src/services'; import { parseQueryString, addParamsToUrl, @@ -142,7 +142,7 @@ class AmpDailymotion extends AMP.BaseElement { this.element); installVideoManagerForDoc(this.element); - videoManagerForDoc(this.element).register(this); + Services.videoManagerForDoc(this.element).register(this); this.playerReadyPromise_ = new Promise(resolve => { this.playerReadyResolver_ = resolve; }); diff --git a/extensions/amp-dynamic-css-classes/0.1/amp-dynamic-css-classes.js b/extensions/amp-dynamic-css-classes/0.1/amp-dynamic-css-classes.js index 860dad80a340..334f28ae2c16 100644 --- a/extensions/amp-dynamic-css-classes/0.1/amp-dynamic-css-classes.js +++ b/extensions/amp-dynamic-css-classes/0.1/amp-dynamic-css-classes.js @@ -15,8 +15,7 @@ */ import {parseUrl} from '../../../src/url'; -import {viewerForDoc} from '../../../src/services'; -import {vsyncFor} from '../../../src/services'; +import {Services} from '../../../src/services'; /** @@ -25,7 +24,7 @@ import {vsyncFor} from '../../../src/services'; * @returns {string} */ function referrerDomain(ampdoc) { - const referrer = viewerForDoc(ampdoc).getUnconfirmedReferrerUrl(); + const referrer = Services.viewerForDoc(ampdoc).getUnconfirmedReferrerUrl(); if (referrer) { return parseUrl(referrer).hostname; } @@ -123,7 +122,7 @@ function addReferrerClasses(ampdoc) { return `amp-referrer-${referrer.replace(/\./g, '-')}`; }); - vsyncFor(ampdoc.win).mutate(() => { + Services.vsyncFor(ampdoc.win).mutate(() => { addDynamicCssClasses(ampdoc, classes); }); } @@ -134,9 +133,9 @@ function addReferrerClasses(ampdoc) { * @param {!../../../src/service/ampdoc-impl.AmpDoc} ampdoc */ function addViewerClass(ampdoc) { - const viewer = viewerForDoc(ampdoc); + const viewer = Services.viewerForDoc(ampdoc); if (viewer.isEmbedded()) { - vsyncFor(ampdoc.win).mutate(() => { + Services.vsyncFor(ampdoc.win).mutate(() => { addDynamicCssClasses(ampdoc, ['amp-viewer']); }); } diff --git a/extensions/amp-dynamic-css-classes/0.1/test/test-runtime-classes.js b/extensions/amp-dynamic-css-classes/0.1/test/test-runtime-classes.js index 692840073f2c..d133b457c309 100644 --- a/extensions/amp-dynamic-css-classes/0.1/test/test-runtime-classes.js +++ b/extensions/amp-dynamic-css-classes/0.1/test/test-runtime-classes.js @@ -14,7 +14,7 @@ * limitations under the License. */ -import {ampdocServiceFor, viewerForDoc} from '../../../../src/services'; +import {Services} from '../../../../src/services'; import {installDocService} from '../../../../src/service/ampdoc-impl'; import { installDocumentStateService, @@ -66,7 +66,7 @@ describe('dynamic classes are inserted at runtime', () => { function setup(embeded, userAgent, referrer) { installDocService(mockWin, /* isSingleDoc */ true); installDocumentStateService(mockWin); - const ampdocService = ampdocServiceFor(mockWin); + const ampdocService = Services.ampdocServiceFor(mockWin); const ampdoc = ampdocService.getAmpDoc(); installPlatformService(mockWin); @@ -76,7 +76,7 @@ describe('dynamic classes are inserted at runtime', () => { }; installViewerServiceForDoc(ampdoc); - viewer = viewerForDoc(ampdoc); + viewer = Services.viewerForDoc(ampdoc); viewer.isEmbedded = () => !!embeded; if (userAgent !== undefined) { diff --git a/extensions/amp-experiment/0.1/test/test-amp-experiment.js b/extensions/amp-experiment/0.1/test/test-amp-experiment.js index bbb473d57cc8..adf7592847a5 100644 --- a/extensions/amp-experiment/0.1/test/test-amp-experiment.js +++ b/extensions/amp-experiment/0.1/test/test-amp-experiment.js @@ -17,7 +17,7 @@ import {createIframePromise} from '../../../../testing/iframe'; import {AmpExperiment} from '../amp-experiment'; import * as variant from '../variant'; -import {variantForOrNull} from '../../../../src/services'; +import {Services} from '../../../../src/services'; import * as sinon from 'sinon'; describe('amp-experiment', () => { @@ -131,7 +131,7 @@ describe('amp-experiment', () => { .returns(Promise.resolve(null)); experiment.buildCallback(); - return variantForOrNull(win).then(variants => { + return Services.variantForOrNull(win).then(variants => { expect(variants).to.jsonEqual({ 'experiment-1': 'variant-a', 'experiment-2': 'variant-d', diff --git a/extensions/amp-experiment/0.1/variant.js b/extensions/amp-experiment/0.1/variant.js index 44bb58bb9e3b..1c4e0beac3e5 100644 --- a/extensions/amp-experiment/0.1/variant.js +++ b/extensions/amp-experiment/0.1/variant.js @@ -16,12 +16,7 @@ import {isObject} from '../../../src/types'; import {dev, user} from '../../../src/log'; -import { - cidForDoc, - cryptoFor, - viewerForDoc, - userNotificationManagerFor, -} from '../../../src/services'; +import {Services} from '../../../src/services'; const ATTR_PREFIX = 'amp-x-'; const nameValidator = /^[\w-]+$/; @@ -39,7 +34,7 @@ export function allocateVariant(ampdoc, experimentName, config) { validateConfig(config); // Variant can be overridden from URL fragment. - const viewer = viewerForDoc(ampdoc); + const viewer = Services.viewerForDoc(ampdoc); const override = viewer.getParam(ATTR_PREFIX + experimentName); if (override && config['variants'].hasOwnProperty(override)) { return Promise.resolve(/** @type {?string} */ (override)); @@ -51,7 +46,7 @@ export function allocateVariant(ampdoc, experimentName, config) { let hasConsentPromise = Promise.resolve(true); if (sticky && config['consentNotificationId']) { - hasConsentPromise = userNotificationManagerFor(ampdoc.win) + hasConsentPromise = Services.userNotificationManagerFor(ampdoc.win) .then(manager => manager.getNotification( config['consentNotificationId'])) .then(userNotification => { @@ -127,12 +122,13 @@ function getBucketTicket(ampdoc, group, opt_cidScope) { return Promise.resolve(ampdoc.win.Math.random() * 100); } - const cidPromise = cidForDoc(ampdoc).then(cidService => cidService.get({ - scope: dev().assertString(opt_cidScope), - createCookieIfNotPresent: true, - }, Promise.resolve())); + const cidPromise = Services.cidForDoc(ampdoc).then(cidService => + cidService.get({ + scope: dev().assertString(opt_cidScope), + createCookieIfNotPresent: true, + }, Promise.resolve())); - return Promise.all([cidPromise, cryptoFor(ampdoc.win)]) + return Promise.all([cidPromise, Services.cryptoFor(ampdoc.win)]) .then(results => results[1].uniform(group + ':' + results[0])) .then(hash => hash * 100); } diff --git a/extensions/amp-fit-text/0.1/test/test-amp-fit-text.js b/extensions/amp-fit-text/0.1/test/test-amp-fit-text.js index 5c44bda34c8e..0fd2baf717aa 100644 --- a/extensions/amp-fit-text/0.1/test/test-amp-fit-text.js +++ b/extensions/amp-fit-text/0.1/test/test-amp-fit-text.js @@ -14,7 +14,7 @@ * limitations under the License. */ -import {timerFor} from '../../../../src/services'; +import {Services} from '../../../../src/services'; import {createIframePromise} from '../../../../testing/iframe'; import '../amp-fit-text'; import { @@ -45,7 +45,7 @@ describe('amp-fit-text component', () => { } ft.textContent = text; iframe.doc.body.appendChild(ft); - return timerFor(window).promise(16).then(() => { + return Services.timerFor(window).promise(16).then(() => { ft.implementation_.layoutCallback(); return ft; }); diff --git a/extensions/amp-font/0.1/amp-font.js b/extensions/amp-font/0.1/amp-font.js index 4675f502207e..4c5ca2bcc6ea 100644 --- a/extensions/amp-font/0.1/amp-font.js +++ b/extensions/amp-font/0.1/amp-font.js @@ -35,7 +35,7 @@ */ import {FontLoader} from './fontloader'; -import {timerFor} from '../../../src/services'; +import {Services} from '../../../src/services'; import {isFiniteNumber} from '../../../src/types'; import {user} from '../../../src/log'; @@ -203,7 +203,7 @@ export class AmpFont extends AMP.BaseElement { timeoutInMs = !isFiniteNumber(timeoutInMs) || timeoutInMs < 0 ? DEFAULT_TIMEOUT_ : timeoutInMs; timeoutInMs = Math.max( - (timeoutInMs - timerFor(this.win).timeSinceStart()), + (timeoutInMs - Services.timerFor(this.win).timeSinceStart()), CACHED_FONT_LOAD_TIME_ ); return timeoutInMs; diff --git a/extensions/amp-font/0.1/fontloader.js b/extensions/amp-font/0.1/fontloader.js index 5dd1ff3cd3ed..02766b793939 100644 --- a/extensions/amp-font/0.1/fontloader.js +++ b/extensions/amp-font/0.1/fontloader.js @@ -38,8 +38,7 @@ const TOLERANCE_ = 2; import {removeElement} from '../../../src/dom'; -import {timerFor} from '../../../src/services'; -import {vsyncFor} from '../../../src/services'; +import {Services} from '../../../src/services'; import * as style from '../../../src/style'; @@ -75,7 +74,7 @@ export class FontLoader { */ load(fontConfig, timeout) { this.fontConfig_ = fontConfig; - return timerFor(this.win_) + return Services.timerFor(this.win_) .timeoutPromise(timeout, this.load_()) .then(() => { this.fontLoadResolved_ = true; @@ -150,7 +149,7 @@ export class FontLoader { */ loadWithPolyfill_() { return new Promise((resolve, reject) => { - const vsync = vsyncFor(this.win_); + const vsync = Services.vsyncFor(this.win_); // Create font comparators const comparators = this.createFontComparators_(); // Measure until timeout (or font load). diff --git a/extensions/amp-form/0.1/amp-form.js b/extensions/amp-form/0.1/amp-form.js index f74a31a13f1d..8ecbb71a0a4b 100644 --- a/extensions/amp-form/0.1/amp-form.js +++ b/extensions/amp-form/0.1/amp-form.js @@ -31,9 +31,8 @@ import { } from '../../../src/url'; import {dev, user} from '../../../src/log'; import {getMode} from '../../../src/mode'; -import {xhrFor} from '../../../src/services'; +import {Services} from '../../../src/services'; import {toArray} from '../../../src/types'; -import {templatesFor} from '../../../src/services'; import { removeElement, childElementByAttr, @@ -41,11 +40,6 @@ import { } from '../../../src/dom'; import {installStyles} from '../../../src/style-installer'; import {CSS} from '../../../build/amp-form-0.1.css'; -import {vsyncFor} from '../../../src/services'; -import {actionServiceForDoc} from '../../../src/services'; -import {timerFor} from '../../../src/services'; -import {urlReplacementsForDoc} from '../../../src/services'; -import {resourcesForDoc} from '../../../src/services'; import { getFormValidator, isCheckValiditySupported, @@ -116,10 +110,10 @@ export class AmpForm { this.win_ = element.ownerDocument.defaultView; /** @const @private {!../../../src/service/timer-impl.Timer} */ - this.timer_ = timerFor(this.win_); + this.timer_ = Services.timerFor(this.win_); /** @const @private {!../../../src/service/url-replacements-impl.UrlReplacements} */ - this.urlReplacement_ = urlReplacementsForDoc(element); + this.urlReplacement_ = Services.urlReplacementsForDoc(element); /** @private {?Promise} */ this.dependenciesPromise_ = null; @@ -128,19 +122,19 @@ export class AmpForm { this.form_ = element; /** @const @private {!../../../src/service/vsync-impl.Vsync} */ - this.vsync_ = vsyncFor(this.win_); + this.vsync_ = Services.vsyncFor(this.win_); /** @const @private {!../../../src/service/template-impl.Templates} */ - this.templates_ = templatesFor(this.win_); + this.templates_ = Services.templatesFor(this.win_); /** @const @private {!../../../src/service/xhr-impl.Xhr} */ - this.xhr_ = xhrFor(this.win_); + this.xhr_ = Services.xhrFor(this.win_); /** @const @private {!../../../src/service/action-impl.ActionService} */ - this.actions_ = actionServiceForDoc(this.form_); + this.actions_ = Services.actionServiceForDoc(this.form_); /** @const @private {!../../../src/service/resources-impl.Resources} */ - this.resources_ = resourcesForDoc(this.form_); + this.resources_ = Services.resourcesForDoc(this.form_); /** @const @private {string} */ this.method_ = (this.form_.getAttribute('method') || 'GET').toUpperCase(); diff --git a/extensions/amp-form/0.1/test/test-amp-form.js b/extensions/amp-form/0.1/test/test-amp-form.js index 049ec319ad1e..13e86ecfc8d6 100644 --- a/extensions/amp-form/0.1/test/test-amp-form.js +++ b/extensions/amp-form/0.1/test/test-amp-form.js @@ -32,11 +32,7 @@ import '../../../amp-mustache/0.1/amp-mustache'; import { cidServiceForDocForTesting, } from '../../../../src/service/cid-impl'; -import { - actionServiceForDoc, - documentInfoForDoc, - timerFor, -} from '../../../../src/services'; +import {Services} from '../../../../src/services'; import '../../../amp-selector/0.1/amp-selector'; import {toggleExperiment} from '../../../../src/experiments'; import {user} from '../../../../src/log'; @@ -57,11 +53,11 @@ describes.repeated('', { }, env => { let sandbox; - const timer = timerFor(window); + const timer = Services.timerFor(window); function getAmpForm(form, canonical = 'https://example.com/amps.html') { new AmpFormService(env.ampdoc); - documentInfoForDoc(env.ampdoc).canonicalUrl = canonical; + Services.documentInfoForDoc(env.ampdoc).canonicalUrl = canonical; cidServiceForDocForTesting(env.ampdoc); env.ampdoc.getBody().appendChild(form); const ampForm = new AmpForm(form, 'amp-form-test-id'); @@ -1253,7 +1249,7 @@ describes.repeated('', { it('should install action handler and handle submit action', () => { const form = getForm(); document.body.appendChild(form); - const actions = actionServiceForDoc(form.ownerDocument); + const actions = Services.actionServiceForDoc(form.ownerDocument); sandbox.stub(actions, 'installActionHandler'); const ampForm = new AmpForm(form); diff --git a/extensions/amp-form/0.1/validation-bubble.js b/extensions/amp-form/0.1/validation-bubble.js index eeb3599c9950..21b82fe138f0 100644 --- a/extensions/amp-form/0.1/validation-bubble.js +++ b/extensions/amp-form/0.1/validation-bubble.js @@ -14,8 +14,7 @@ * limitations under the License. */ -import {vsyncFor} from '../../../src/services'; -import {viewportForDoc} from '../../../src/services'; +import {Services} from '../../../src/services'; import {setStyles} from '../../../src/style'; import {removeChildren} from '../../../src/dom'; @@ -34,10 +33,10 @@ export class ValidationBubble { this.id_ = id; /** @private @const {!../../../src/service/viewport-impl.Viewport} */ - this.viewport_ = viewportForDoc(ampdoc); + this.viewport_ = Services.viewportForDoc(ampdoc); /** @private @const {!../../../src/service/vsync-impl.Vsync} */ - this.vsync_ = vsyncFor(ampdoc.win); + this.vsync_ = Services.vsyncFor(ampdoc.win); /** @private {?Element} */ this.currentTargetElement_ = null; diff --git a/extensions/amp-fresh/0.1/amp-fresh-manager.js b/extensions/amp-fresh/0.1/amp-fresh-manager.js index 1fe577f0a033..4138b4ca203e 100644 --- a/extensions/amp-fresh/0.1/amp-fresh-manager.js +++ b/extensions/amp-fresh/0.1/amp-fresh-manager.js @@ -21,7 +21,7 @@ import { } from '../../../src/service'; import {isExperimentOn} from '../../../src/experiments'; import {user} from '../../../src/log'; -import {xhrFor} from '../../../src/services'; +import {Services} from '../../../src/services'; /** @const */ @@ -81,7 +81,7 @@ export class AmpFreshManager { const url = addParamToUrl(this.ampdoc.win.location.href, 'amp-fresh', String(Date.now())); return Promise.all([ - xhrFor(this.ampdoc.win).fetchDocument(url, { + Services.xhrFor(this.ampdoc.win).fetchDocument(url, { requireAmpResponseSourceOrigin: false, }), this.ampdoc.whenReady(), diff --git a/extensions/amp-fx-flying-carpet/0.1/test/test-amp-fx-flying-carpet.js b/extensions/amp-fx-flying-carpet/0.1/test/test-amp-fx-flying-carpet.js index b191f4274ecc..b6147ddb39d2 100644 --- a/extensions/amp-fx-flying-carpet/0.1/test/test-amp-fx-flying-carpet.js +++ b/extensions/amp-fx-flying-carpet/0.1/test/test-amp-fx-flying-carpet.js @@ -17,7 +17,7 @@ import {adopt} from '../../../../src/runtime'; import {createIframePromise} from '../../../../testing/iframe'; import {installImg} from '../../../../builtins/amp-img'; -import {viewportForDoc} from '../../../../src/services'; +import {Services} from '../../../../src/services'; import * as sinon from 'sinon'; import '../amp-fx-flying-carpet'; @@ -48,7 +48,7 @@ describe('amp-fx-flying-carpet', () => { iframe.doc.body.appendChild(bodyResizer); iframe.doc.body.style.position = 'relative'; - viewport = viewportForDoc(iframe.win.document); + viewport = Services.viewportForDoc(iframe.win.document); viewport.resize_(); const parent = iframe.doc.querySelector('#parent'); diff --git a/extensions/amp-fx-parallax/0.1/amp-fx-parallax.js b/extensions/amp-fx-parallax/0.1/amp-fx-parallax.js index db1e06c9dee1..079e42788d9a 100644 --- a/extensions/amp-fx-parallax/0.1/amp-fx-parallax.js +++ b/extensions/amp-fx-parallax/0.1/amp-fx-parallax.js @@ -14,11 +14,11 @@ * limitations under the License. */ -import {ampdocServiceFor} from '../../../src/services'; +import {Services} from '../../../src/services'; import {installParallaxForDoc} from '../../../src/service/parallax-impl'; import {onDocumentReady} from '../../../src/document-ready'; -const ampdoc = ampdocServiceFor(AMP.win).getAmpDoc(); +const ampdoc = Services.ampdocServiceFor(AMP.win).getAmpDoc(); onDocumentReady(ampdoc.win.document, () => { installParallaxForDoc(ampdoc.getRootNode()); }); diff --git a/extensions/amp-fx-parallax/0.1/test/test-amp-fx-parallax.js b/extensions/amp-fx-parallax/0.1/test/test-amp-fx-parallax.js index e61de01da2f3..0fc761a24d4f 100644 --- a/extensions/amp-fx-parallax/0.1/test/test-amp-fx-parallax.js +++ b/extensions/amp-fx-parallax/0.1/test/test-amp-fx-parallax.js @@ -14,12 +14,10 @@ * limitations under the License. */ +import {Services} from '../../../../src/services'; import {createIframePromise} from '../../../../testing/iframe'; import {installParallaxForDoc} from '../../../../src/service/parallax-impl'; -import {parallaxForDoc} from '../../../../src/services'; import {toggleExperiment} from '../../../../src/experiments'; -import {viewportForDoc} from '../../../../src/services'; -import {vsyncFor} from '../../../../src/services'; describes.sandboxed('amp-fx-parallax', {}, () => { const DEFAULT_FACTOR = 1.7; @@ -40,7 +38,7 @@ describes.sandboxed('amp-fx-parallax', {}, () => { bodyResizer.style.width = '1px'; iframe.doc.body.appendChild(bodyResizer); - viewport = viewportForDoc(iframe.win.document); + viewport = Services.viewportForDoc(iframe.win.document); viewport.resize_(); toggleExperiment(iframe.win, 'amp-fx-parallax', true); @@ -59,7 +57,7 @@ describes.sandboxed('amp-fx-parallax', {}, () => { installParallaxForDoc(iframe.doc); return new Promise(resolve => { - vsyncFor(iframe.win).mutate(() => { + Services.vsyncFor(iframe.win).mutate(() => { resolve({ element: parallaxElement, iframe, @@ -79,7 +77,7 @@ describes.sandboxed('amp-fx-parallax', {}, () => { return getAmpParallaxElement(addTextChildren) .then(({element, iframe, viewport}) => { - const parallaxService = parallaxForDoc(iframe.doc); + const parallaxService = Services.parallaxForDoc(iframe.doc); const top = element.getBoundingClientRect().top; expect(top).to.equal(viewport.getScrollTop()); @@ -100,7 +98,7 @@ describes.sandboxed('amp-fx-parallax', {}, () => { return getAmpParallaxElement(addTextChildren, DEFAULT_FACTOR) .then(({element, iframe, viewport}) => { - const parallaxService = parallaxForDoc(iframe.doc); + const parallaxService = Services.parallaxForDoc(iframe.doc); return new Promise(resolve => { parallaxService.addScrollListener_(() => { @@ -119,7 +117,7 @@ describes.sandboxed('amp-fx-parallax', {}, () => { return getAmpParallaxElement(addTextChildren, DEFAULT_FACTOR) .then(({element, iframe, viewport}) => { - const parallaxService = parallaxForDoc(iframe.doc); + const parallaxService = Services.parallaxForDoc(iframe.doc); return new Promise(resolve => { parallaxService.addScrollListener_(() => { const top = element.getBoundingClientRect().top; @@ -138,7 +136,7 @@ describes.sandboxed('amp-fx-parallax', {}, () => { return getAmpParallaxElement(addTextChildren, factor) .then(({element, iframe, viewport}) => { - const parallaxService = parallaxForDoc(iframe.doc); + const parallaxService = Services.parallaxForDoc(iframe.doc); return new Promise(resolve => { parallaxService.addScrollListener_(afterFirstScroll); viewport.setScrollTop(scroll); @@ -163,7 +161,7 @@ describes.sandboxed('amp-fx-parallax', {}, () => { return getAmpParallaxElement(addTextChildren, factor) .then(({element, iframe, viewport}) => { - const parallaxService = parallaxForDoc(iframe.doc); + const parallaxService = Services.parallaxForDoc(iframe.doc); return new Promise(resolve => { parallaxService.addScrollListener_(afterFirstScroll); viewport.setScrollTop(10); diff --git a/extensions/amp-iframe/0.1/amp-iframe.js b/extensions/amp-iframe/0.1/amp-iframe.js index 1123491fb7ad..a902d6a985ba 100644 --- a/extensions/amp-iframe/0.1/amp-iframe.js +++ b/extensions/amp-iframe/0.1/amp-iframe.js @@ -24,7 +24,7 @@ import {endsWith} from '../../../src/string'; import {listenFor} from '../../../src/iframe-helper'; import {removeElement} from '../../../src/dom'; import {removeFragment, parseUrl, isSecureUrl} from '../../../src/url'; -import {timerFor} from '../../../src/services'; +import {Services} from '../../../src/services'; import {user, dev} from '../../../src/log'; import {utf8EncodeSync} from '../../../src/utils/bytes.js'; import {urls} from '../../../src/config'; @@ -357,7 +357,7 @@ export class AmpIframe extends AMP.BaseElement { // Prevent this iframe from ever being recreated. this.iframeSrc = null; - timerFor(this.win).promise(trackingIframeTimeout).then(() => { + Services.timerFor(this.win).promise(trackingIframeTimeout).then(() => { removeElement(iframe); this.element.setAttribute('amp-removed', ''); this.iframe_ = null; @@ -380,7 +380,7 @@ export class AmpIframe extends AMP.BaseElement { // container. To avoid this problem, we set the `overflow:auto` property // 1s later via `amp-active` class. if (this.container_ != this.element) { - timerFor(this.win).delay(() => { + Services.timerFor(this.win).delay(() => { this.deferMutate(() => { this.container_.classList.add('amp-active'); }); diff --git a/extensions/amp-iframe/0.1/test/test-amp-iframe.js b/extensions/amp-iframe/0.1/test/test-amp-iframe.js index 154822364b39..5b43ee6c3be4 100644 --- a/extensions/amp-iframe/0.1/test/test-amp-iframe.js +++ b/extensions/amp-iframe/0.1/test/test-amp-iframe.js @@ -14,7 +14,7 @@ * limitations under the License. */ -import {timerFor} from '../../../../src/services'; +import {Services} from '../../../../src/services'; import { AmpIframe, isAdLike, @@ -25,7 +25,6 @@ import { createIframePromise, poll, } from '../../../../testing/iframe'; -import {viewportForDoc} from '../../../../src/services'; import * as sinon from 'sinon'; adopt(window); @@ -37,7 +36,7 @@ describe('amp-iframe', () => { const clickableIframeSrc = 'http://iframe.localhost:' + location.port + '/test/fixtures/served/iframe-clicktoplay.html'; - const timer = timerFor(window); + const timer = Services.timerFor(window); let ranJs = 0; let content = ''; let sandbox; @@ -80,7 +79,7 @@ describe('amp-iframe', () => { iframe.iframe.style.height = opt_height; } const top = opt_top || '600px'; - const viewport = viewportForDoc(iframe.win.document); + const viewport = Services.viewportForDoc(iframe.win.document); viewport.resize_(); i.style.position = 'absolute'; if (attributes.position) { diff --git a/extensions/amp-ima-video/0.1/amp-ima-video.js b/extensions/amp-ima-video/0.1/amp-ima-video.js index 8d4ff2e381f9..6947b9201456 100644 --- a/extensions/amp-ima-video/0.1/amp-ima-video.js +++ b/extensions/amp-ima-video/0.1/amp-ima-video.js @@ -33,7 +33,7 @@ import {dict} from '../../../src/utils/object'; import {removeElement} from '../../../src/dom'; import {user} from '../../../src/log'; import {VideoEvents} from '../../../src/video-interface'; -import {videoManagerForDoc} from '../../../src/services'; +import {Services} from '../../../src/services'; /** @const */ const TAG = 'amp-ima-video'; @@ -140,7 +140,7 @@ class AmpImaVideo extends AMP.BaseElement { this.element.appendChild(iframe); installVideoManagerForDoc(this.element); - videoManagerForDoc(this.win.document).register(this); + Services.videoManagerForDoc(this.win.document).register(this); return this.loadPromise(iframe).then(() => this.playerReadyPromise_); } diff --git a/extensions/amp-image-lightbox/0.1/amp-image-lightbox.js b/extensions/amp-image-lightbox/0.1/amp-image-lightbox.js index 0ea668fbc611..f32c423344a6 100644 --- a/extensions/amp-image-lightbox/0.1/amp-image-lightbox.js +++ b/extensions/amp-image-lightbox/0.1/amp-image-lightbox.js @@ -27,7 +27,7 @@ import {KeyCodes} from '../../../src/utils/key-codes'; import {Layout} from '../../../src/layout'; import {bezierCurve} from '../../../src/curve'; import {continueMotion} from '../../../src/motion'; -import {historyForDoc} from '../../../src/services'; +import {Services} from '../../../src/services'; import {isLoaded} from '../../../src/event-helper'; import { layoutRectFromDomRect, @@ -35,7 +35,6 @@ import { moveLayoutRect, } from '../../../src/layout-rect'; import {srcsetFromElement} from '../../../src/srcset'; -import {timerFor, platformFor} from '../../../src/services'; import {user, dev} from '../../../src/log'; import {startsWith} from '../../../src/string'; import * as dom from '../../../src/dom'; @@ -314,7 +313,7 @@ export class ImageViewer { // Notice that we will wait until the next event cycle to set the "src". // This ensures that the already available image will show immediately // and then naturally upgrade to a higher quality image. - return timerFor(this.win).promise(1).then(() => { + return Services.timerFor(this.win).promise(1).then(() => { this.image_.setAttribute('src', src); return this.loadPromise_(this.image_); }); @@ -807,8 +806,9 @@ class AmpImageLightbox extends AMP.BaseElement { // element size depends on window size directly and the measurement // happens in window.resize event. Adding a timeout for correct // measurement. See https://github.com/ampproject/amphtml/issues/8479 - if (startsWith(platformFor(this.win).getIosVersionString(), '10.3')) { - timerFor(this.win).delay(() => { + if (startsWith( + Services.platformFor(this.win).getIosVersionString(), '10.3')) { + Services.timerFor(this.win).delay(() => { this.imageViewer_.measure(); }, 500); } else { @@ -1094,7 +1094,7 @@ class AmpImageLightbox extends AMP.BaseElement { /** @private @return {!../../../src/service/history-impl.History} */ getHistory_() { - return historyForDoc(this.getAmpDoc()); + return Services.historyForDoc(this.getAmpDoc()); } } diff --git a/extensions/amp-image-lightbox/0.1/test/test-amp-image-lightbox.js b/extensions/amp-image-lightbox/0.1/test/test-amp-image-lightbox.js index f7770cd9b075..554a05509327 100644 --- a/extensions/amp-image-lightbox/0.1/test/test-amp-image-lightbox.js +++ b/extensions/amp-image-lightbox/0.1/test/test-amp-image-lightbox.js @@ -15,7 +15,7 @@ */ import {KeyCodes} from '../../../../src/utils/key-codes'; -import {timerFor} from '../../../../src/services'; +import {Services} from '../../../../src/services'; import {createIframePromise} from '../../../../testing/iframe'; import '../amp-image-lightbox'; import { @@ -35,7 +35,7 @@ describe('amp-image-lightbox component', () => { const el = iframe.doc.createElement('amp-image-lightbox'); el.setAttribute('layout', 'nodisplay'); iframe.doc.body.appendChild(el); - return timerFor(window).promise(16).then(() => { + return Services.timerFor(window).promise(16).then(() => { return el; }); }); @@ -234,7 +234,8 @@ describe('amp-image-lightbox image viewer', () => { lightboxMock = sandbox.mock(lightbox); loadPromiseStub = sandbox.stub().returns(Promise.resolve()); - sandbox.stub(timerFor(window), 'promise').returns(Promise.resolve()); + sandbox.stub(Services.timerFor(window), 'promise') + .returns(Promise.resolve()); imageViewer = new ImageViewer(lightbox, window, loadPromiseStub); document.body.appendChild(imageViewer.getElement()); }); diff --git a/extensions/amp-install-serviceworker/0.1/amp-install-serviceworker.js b/extensions/amp-install-serviceworker/0.1/amp-install-serviceworker.js index 94d606fc1384..294d6598eee8 100644 --- a/extensions/amp-install-serviceworker/0.1/amp-install-serviceworker.js +++ b/extensions/amp-install-serviceworker/0.1/amp-install-serviceworker.js @@ -24,12 +24,10 @@ import { } from '../../../src/url'; import {closestByTag, removeElement} from '../../../src/dom'; import {dev, user} from '../../../src/log'; -import {documentInfoForDoc} from '../../../src/services'; +import {Services} from '../../../src/services'; import {getMode} from '../../../src/mode'; import {listen} from '../../../src/event-helper'; -import {timerFor} from '../../../src/services'; import {toggle} from '../../../src/style'; -import {viewerForDoc} from '../../../src/services'; import {setStyle} from '../../../src/style'; /** @private @const {string} */ @@ -68,7 +66,7 @@ export class AmpInstallServiceWorker extends AMP.BaseElement { if (iframeSrc) { assertHttpsUrl(iframeSrc, this.element); const origin = parseUrl(iframeSrc).origin; - const docInfo = documentInfoForDoc(this.element); + const docInfo = Services.documentInfoForDoc(this.element); const sourceUrl = parseUrl(docInfo.sourceUrl); const canonicalUrl = parseUrl(docInfo.canonicalUrl); user().assert( @@ -96,12 +94,12 @@ export class AmpInstallServiceWorker extends AMP.BaseElement { /** @private */ scheduleIframeLoad_() { - viewerForDoc(this.getAmpDoc()).whenFirstVisible().then(() => { + Services.viewerForDoc(this.getAmpDoc()).whenFirstVisible().then(() => { // If the user is longer than 20 seconds on this page, load // the external iframe to install the ServiceWorker. The wait is // introduced to avoid installing SWs for content that the user // only engaged with superficially. - timerFor(this.win).delay(() => { + Services.timerFor(this.win).delay(() => { this.deferMutate(this.insertIframe_.bind(this)); }, 10000); }); @@ -111,7 +109,7 @@ export class AmpInstallServiceWorker extends AMP.BaseElement { insertIframe_() { // If we are no longer visible, we will not do a SW registration on this // page view. - if (!viewerForDoc(this.getAmpDoc()).isVisible()) { + if (!Services.viewerForDoc(this.getAmpDoc()).isVisible()) { return; } // The iframe will stil be loaded. @@ -176,7 +174,8 @@ export class AmpInstallServiceWorker extends AMP.BaseElement { waitToPreloadShell_(shellUrl) { // Ensure that document is loaded and visible first. const whenReady = this.loadPromise(this.win); - const whenVisible = viewerForDoc(this.getAmpDoc()).whenFirstVisible(); + const whenVisible = + Services.viewerForDoc(this.getAmpDoc()).whenFirstVisible(); return Promise.all([whenReady, whenVisible]).then(() => { this.deferMutate(() => this.preloadShell_(shellUrl)); }); diff --git a/extensions/amp-install-serviceworker/0.1/test/test-amp-install-serviceworker.js b/extensions/amp-install-serviceworker/0.1/test/test-amp-install-serviceworker.js index 26604be34345..f6a136586c65 100644 --- a/extensions/amp-install-serviceworker/0.1/test/test-amp-install-serviceworker.js +++ b/extensions/amp-install-serviceworker/0.1/test/test-amp-install-serviceworker.js @@ -15,7 +15,7 @@ */ import {AmpInstallServiceWorker} from '../amp-install-serviceworker'; -import {ampdocServiceFor} from '../../../../src/services'; +import {Services} from '../../../../src/services'; import { registerServiceBuilder, registerServiceBuilderForDoc, @@ -44,7 +44,7 @@ describes.realWin('amp-install-serviceworker', { doc = env.win.document; sandbox = env.sandbox; clock = sandbox.useFakeTimers(); - ampdoc = ampdocServiceFor(env.win).getAmpDoc(); + ampdoc = Services.ampdocServiceFor(env.win).getAmpDoc(); container = doc.createElement('div'); env.win.document.body.appendChild(container); maybeInstallUrlRewriteStub = sandbox.stub( diff --git a/extensions/amp-lightbox-viewer/0.1/amp-lightbox-viewer.js b/extensions/amp-lightbox-viewer/0.1/amp-lightbox-viewer.js index dd8bd172efcb..c3801db28f5e 100644 --- a/extensions/amp-lightbox-viewer/0.1/amp-lightbox-viewer.js +++ b/extensions/amp-lightbox-viewer/0.1/amp-lightbox-viewer.js @@ -17,7 +17,7 @@ import {CSS} from '../../../build/amp-lightbox-viewer-0.1.css'; import {KeyCodes} from '../../../src/utils/key-codes'; -import {ampdocServiceFor, extensionsFor} from '../../../src/services'; +import {Services} from '../../../src/services'; import {isExperimentOn} from '../../../src/experiments'; import {Layout} from '../../../src/layout'; import {user, dev} from '../../../src/log'; @@ -141,7 +141,7 @@ export class AmpLightboxViewer extends AMP.BaseElement { buildCarousel_() { if (!this.carousel_) { dev().assert(this.container_); - extensionsFor(this.win).loadExtension('amp-carousel'); + Services.extensionsFor(this.win).loadExtension('amp-carousel'); this.carousel_ = this.win.document.createElement('amp-carousel'); this.carousel_.setAttribute('type', 'slides'); this.carousel_.setAttribute('layout', 'fill'); @@ -547,7 +547,7 @@ export function installLightboxManager(win) { if (isExperimentOn(win, TAG)) { // TODO(aghassemi): This only works for singleDoc mode. We will move // installation of LightboxManager to core after the experiment, okay for now. - const ampdoc = ampdocServiceFor(win).getAmpDoc(); + const ampdoc = Services.ampdocServiceFor(win).getAmpDoc(); manager_ = new LightboxManager(ampdoc); } } diff --git a/extensions/amp-lightbox-viewer/0.1/service/lightbox-manager-impl.js b/extensions/amp-lightbox-viewer/0.1/service/lightbox-manager-impl.js index 6dcfbbea8aeb..b88c9e3ccad7 100644 --- a/extensions/amp-lightbox-viewer/0.1/service/lightbox-manager-impl.js +++ b/extensions/amp-lightbox-viewer/0.1/service/lightbox-manager-impl.js @@ -18,7 +18,7 @@ import {whenDocumentReady} from '../../../../src/document-ready'; import {isExperimentOn} from '../../../../src/experiments'; import {autoDiscoverLightboxables} from './lightbox-manager-discovery'; import {dev} from '../../../../src/log'; -import {timerFor} from '../../../../src/services'; +import {Services} from '../../../../src/services'; /** @@ -61,7 +61,7 @@ export class LightboxManager { // any time, if a method call comes in before this timer initializes, we // are still fine since manager will be initialized at that point and method // call will go through. - timerFor(ampdoc.win).delay(() => { + Services.timerFor(ampdoc.win).delay(() => { this.maybeInit_(); }, 500); } diff --git a/extensions/amp-lightbox/0.1/amp-lightbox.js b/extensions/amp-lightbox/0.1/amp-lightbox.js index 3a8145f669a0..2170dad8b6b0 100644 --- a/extensions/amp-lightbox/0.1/amp-lightbox.js +++ b/extensions/amp-lightbox/0.1/amp-lightbox.js @@ -20,9 +20,7 @@ import {KeyCodes} from '../../../src/utils/key-codes'; import {Layout} from '../../../src/layout'; import {SwipeXYRecognizer} from '../../../src/gesture-recognizers'; import {dev} from '../../../src/log'; -import {historyForDoc} from '../../../src/services'; -import {vsyncFor} from '../../../src/services'; -import {timerFor} from '../../../src/services'; +import {Services} from '../../../src/services'; import * as st from '../../../src/style'; /** @const {string} */ @@ -141,7 +139,7 @@ class AmpLightbox extends AMP.BaseElement { // TODO(dvoytenko): use new animations support instead. transition: 'opacity 0.1s ease-in', }); - vsyncFor(this.win).mutate(() => { + Services.vsyncFor(this.win).mutate(() => { st.setStyle(this.element, 'opacity', ''); }); }).then(() => { @@ -227,7 +225,7 @@ class AmpLightbox extends AMP.BaseElement { * @private */ waitForScroll_(startingScrollTop) { - this.scrollTimerId_ = timerFor(this.win).delay(() => { + this.scrollTimerId_ = Services.timerFor(this.win).delay(() => { if (Math.abs(startingScrollTop - this.pos_) < 30) { dev().fine(TAG, 'slow scrolling: ' + startingScrollTop + ' - ' + this.pos_); @@ -309,7 +307,7 @@ class AmpLightbox extends AMP.BaseElement { } getHistory_() { - return historyForDoc(this.getAmpDoc()); + return Services.historyForDoc(this.getAmpDoc()); } } diff --git a/extensions/amp-list/0.1/amp-list.js b/extensions/amp-list/0.1/amp-list.js index edc853651bb2..ca40105d3572 100644 --- a/extensions/amp-list/0.1/amp-list.js +++ b/extensions/amp-list/0.1/amp-list.js @@ -20,7 +20,7 @@ import {fetchBatchedJsonFor} from '../../../src/batched-json'; import {isArray} from '../../../src/types'; import {isLayoutSizeDefined} from '../../../src/layout'; import {removeChildren} from '../../../src/dom'; -import {templatesFor} from '../../../src/services'; +import {Services} from '../../../src/services'; import {dev, user} from '../../../src/log'; /** @@ -90,7 +90,7 @@ export class AmpList extends AMP.BaseElement { this.populateList_(); } else if (state != undefined) { const items = isArray(state) ? state : [state]; - templatesFor(this.win).findAndRenderTemplateArray( + Services.templatesFor(this.win).findAndRenderTemplateArray( this.element, items).then(this.rendered_.bind(this)); } if (src != undefined && state != undefined) { @@ -131,7 +131,7 @@ export class AmpList extends AMP.BaseElement { user().assert(isArray(items), 'Response must contain an array at "%s". %s', itemsExpr, this.element); - return templatesFor(this.win).findAndRenderTemplateArray( + return Services.templatesFor(this.win).findAndRenderTemplateArray( this.element, items).then(this.rendered_.bind(this)); }, error => { throw user().createError('Error fetching amp-list', error); diff --git a/extensions/amp-list/0.1/test/test-amp-list.js b/extensions/amp-list/0.1/test/test-amp-list.js index c78c2f735a2b..43bb81243524 100644 --- a/extensions/amp-list/0.1/test/test-amp-list.js +++ b/extensions/amp-list/0.1/test/test-amp-list.js @@ -16,7 +16,7 @@ import {AmpEvents} from '../../../../src/amp-events'; import {AmpList} from '../amp-list'; -import {ampdocServiceFor, templatesFor} from '../../../../src/services'; +import {Services} from '../../../../src/services'; import * as sinon from 'sinon'; describe('amp-list component', () => { @@ -29,10 +29,10 @@ describe('amp-list component', () => { beforeEach(() => { sandbox = sinon.sandbox.create(); - const templates = templatesFor(window); + const templates = Services.templatesFor(window); templatesMock = sandbox.mock(templates); - const ampdoc = ampdocServiceFor(window).getAmpDoc(); + const ampdoc = Services.ampdocServiceFor(window).getAmpDoc(); element = document.createElement('div'); element.setAttribute('src', 'https://data.com/list.json'); diff --git a/extensions/amp-live-list/0.1/live-list-manager.js b/extensions/amp-live-list/0.1/live-list-manager.js index 7fe599794692..f6f9c656f9bd 100644 --- a/extensions/amp-live-list/0.1/live-list-manager.js +++ b/extensions/amp-live-list/0.1/live-list-manager.js @@ -22,8 +22,7 @@ import { registerServiceBuilderForDoc, } from '../../../src/service'; import {user} from '../../../src/log'; -import {viewerForDoc} from '../../../src/services'; -import {xhrFor} from '../../../src/services'; +import {Services} from '../../../src/services'; const SERVICE_ID = 'liveListManager'; @@ -47,7 +46,7 @@ export class LiveListManager { this.liveLists_ = Object.create(null); /** @private @const {!../../../src/service/viewer-impl.Viewer} */ - this.viewer_ = viewerForDoc(this.ampdoc); + this.viewer_ = Services.viewerForDoc(this.ampdoc); /** @private {number} */ this.interval_ = 15000; @@ -127,7 +126,7 @@ export class LiveListManager { url = addParamToUrl(url, 'amp_latest_update_time', String(this.latestUpdateTime_)); } - return xhrFor(this.ampdoc.win) + return Services.xhrFor(this.ampdoc.win) // TODO(erwinm): add update time here when possible. .fetchDocument(url, { requireAmpResponseSourceOrigin: false, diff --git a/extensions/amp-live-list/0.1/poller.js b/extensions/amp-live-list/0.1/poller.js index 35af8aab6cd0..b823efde676f 100644 --- a/extensions/amp-live-list/0.1/poller.js +++ b/extensions/amp-live-list/0.1/poller.js @@ -17,7 +17,7 @@ import {exponentialBackoffClock, getJitter} from '../../../src/exponential-backoff'; -import {timerFor} from '../../../src/services'; +import {Services} from '../../../src/services'; /** @@ -101,7 +101,7 @@ export class Poller { */ clear_() { if (this.lastTimeoutId_) { - timerFor(this.win).cancel(this.lastTimeoutId_); + Services.timerFor(this.win).cancel(this.lastTimeoutId_); this.lastTimeoutId_ = null; } } @@ -140,7 +140,8 @@ export class Poller { if (opt_immediate) { work(); } else { - this.lastTimeoutId_ = timerFor(this.win).delay(work, this.getTimeout_()); + this.lastTimeoutId_ = + Services.timerFor(this.win).delay(work, this.getTimeout_()); } } } diff --git a/extensions/amp-live-list/0.1/test/test-live-list-manager.js b/extensions/amp-live-list/0.1/test/test-live-list-manager.js index bdc54f5bc64c..275cf5e391e0 100644 --- a/extensions/amp-live-list/0.1/test/test-live-list-manager.js +++ b/extensions/amp-live-list/0.1/test/test-live-list-manager.js @@ -15,7 +15,7 @@ */ import {liveListManagerForDoc, LiveListManager} from '../live-list-manager'; -import {viewerForDoc} from '../../../../src/services'; +import {Services} from '../../../../src/services'; describes.fakeWin('LiveListManager', {amp: true}, env => { @@ -42,7 +42,7 @@ describes.fakeWin('LiveListManager', {amp: true}, env => { mockXhr.onCreate = function(xhr) { requests.push(xhr); }; - viewer = viewerForDoc(ampdoc); + viewer = Services.viewerForDoc(ampdoc); manager = liveListManagerForDoc(ampdoc); liveList = getLiveList({'data-sort-time': '1111'}); sandbox.stub(liveList, 'getInterval', () => 5000); diff --git a/extensions/amp-live-list/0.1/test/test-poller.js b/extensions/amp-live-list/0.1/test/test-poller.js index 05dd6567e07b..fb1f4d237b55 100644 --- a/extensions/amp-live-list/0.1/test/test-poller.js +++ b/extensions/amp-live-list/0.1/test/test-poller.js @@ -17,7 +17,7 @@ import * as sinon from 'sinon'; import {Poller} from '../poller'; -import {timerFor} from '../../../../src/services'; +import {Services} from '../../../../src/services'; describe('Poller', () => { @@ -25,7 +25,7 @@ describe('Poller', () => { let clock; let poller; let workStub; - const timer = timerFor(window); + const timer = Services.timerFor(window); beforeEach(() => { sandbox = sinon.sandbox.create(); diff --git a/extensions/amp-nexxtv-player/0.1/amp-nexxtv-player.js b/extensions/amp-nexxtv-player/0.1/amp-nexxtv-player.js index e444152d2ba7..13d1c9a4bfc6 100644 --- a/extensions/amp-nexxtv-player/0.1/amp-nexxtv-player.js +++ b/extensions/amp-nexxtv-player/0.1/amp-nexxtv-player.js @@ -26,7 +26,7 @@ import {removeElement} from '../../../src/dom'; import {getData, listen} from '../../../src/event-helper'; import {isObject} from '../../../src/types'; import {VideoEvents} from '../../../src/video-interface'; -import {videoManagerForDoc} from '../../../src/services'; +import {Services} from '../../../src/services'; /** * @implements {../../../src/video-interface.VideoInterface} @@ -73,7 +73,7 @@ class AmpNexxtvPlayer extends AMP.BaseElement { }); installVideoManagerForDoc(this.element); - videoManagerForDoc(this.element).register(this); + Services.videoManagerForDoc(this.element).register(this); } getVideoIframeSrc_() { diff --git a/extensions/amp-nexxtv-player/0.1/test/test-amp-nexxtv-player.js b/extensions/amp-nexxtv-player/0.1/test/test-amp-nexxtv-player.js index b8b3ecc4c501..92c618a72d88 100644 --- a/extensions/amp-nexxtv-player/0.1/test/test-amp-nexxtv-player.js +++ b/extensions/amp-nexxtv-player/0.1/test/test-amp-nexxtv-player.js @@ -20,7 +20,7 @@ import { import '../amp-nexxtv-player'; import {listenOncePromise} from '../../../../src/event-helper'; import {adopt} from '../../../../src/runtime'; -import {timerFor} from '../../../../src/services'; +import {Services} from '../../../../src/services'; import {VideoEvents} from '../../../../src/video-interface'; import * as sinon from 'sinon'; @@ -29,7 +29,7 @@ adopt(window); describe('amp-nexxtv-player', () => { let sandbox; - const timer = timerFor(window); + const timer = Services.timerFor(window); beforeEach(() => { sandbox = sinon.sandbox.create(); diff --git a/extensions/amp-ooyala-player/0.1/amp-ooyala-player.js b/extensions/amp-ooyala-player/0.1/amp-ooyala-player.js index 349b754d574d..2941a30ffc94 100644 --- a/extensions/amp-ooyala-player/0.1/amp-ooyala-player.js +++ b/extensions/amp-ooyala-player/0.1/amp-ooyala-player.js @@ -24,7 +24,7 @@ import { import {isObject} from '../../../src/types'; import {getData, listen} from '../../../src/event-helper'; import {VideoEvents} from '../../../src/video-interface'; -import {videoManagerForDoc} from '../../../src/services'; +import {Services} from '../../../src/services'; /** * @implements {../../../src/video-interface.VideoInterface} @@ -63,7 +63,7 @@ class AmpOoyalaPlayer extends AMP.BaseElement { }); installVideoManagerForDoc(this.element); - videoManagerForDoc(this.element).register(this); + Services.videoManagerForDoc(this.element).register(this); } /** @override */ diff --git a/extensions/amp-pinterest/0.1/pin-widget.js b/extensions/amp-pinterest/0.1/pin-widget.js index c02ac9908abc..f0ff5e5ffd17 100644 --- a/extensions/amp-pinterest/0.1/pin-widget.js +++ b/extensions/amp-pinterest/0.1/pin-widget.js @@ -17,7 +17,7 @@ import {assertHttpsUrl} from '../../../src/url'; import {openWindowDialog} from '../../../src/dom'; import {user} from '../../../src/log'; -import {xhrFor} from '../../../src/services'; +import {Services} from '../../../src/services'; import {Util} from './util'; @@ -37,7 +37,7 @@ export class PinWidget { user().assert(rootElement.getAttribute('data-url'), 'The data-url attribute is required for Pin widgets'); this.element = rootElement; - this.xhr = xhrFor(rootElement.ownerDocument.defaultView); + this.xhr = Services.xhrFor(rootElement.ownerDocument.defaultView); this.pinId = ''; this.pinUrl = ''; this.width = ''; diff --git a/extensions/amp-pinterest/0.1/pinit-button.js b/extensions/amp-pinterest/0.1/pinit-button.js index 826539c09743..3d2bac52ec4c 100644 --- a/extensions/amp-pinterest/0.1/pinit-button.js +++ b/extensions/amp-pinterest/0.1/pinit-button.js @@ -15,7 +15,7 @@ */ import {openWindowDialog} from '../../../src/dom'; import {dev, user} from '../../../src/log'; -import {xhrFor} from '../../../src/services'; +import {Services} from '../../../src/services'; import {Util} from './util'; @@ -48,7 +48,7 @@ export class PinItButton { user().assert(rootElement.getAttribute('data-description'), 'The data-description attribute is required for Pin It buttons'); this.element = rootElement; - this.xhr = xhrFor(rootElement.ownerDocument.defaultView); + this.xhr = Services.xhrFor(rootElement.ownerDocument.defaultView); this.color = rootElement.getAttribute('data-color'); this.count = rootElement.getAttribute('data-count'); this.lang = rootElement.getAttribute('data-lang'); diff --git a/extensions/amp-selector/0.1/amp-selector.js b/extensions/amp-selector/0.1/amp-selector.js index 36bf1dd873ea..0577e8bef0b1 100644 --- a/extensions/amp-selector/0.1/amp-selector.js +++ b/extensions/amp-selector/0.1/amp-selector.js @@ -17,7 +17,7 @@ import {ActionTrust} from '../../../src/action-trust'; import {CSS} from '../../../build/amp-selector-0.1.css'; import {KeyCodes} from '../../../src/utils/key-codes'; -import {actionServiceForDoc} from '../../../src/services'; +import {Services} from '../../../src/services'; import {closestBySelector, tryFocus} from '../../../src/dom'; import {createCustomEvent} from '../../../src/event-helper'; import {dev, user} from '../../../src/log'; @@ -77,7 +77,7 @@ export class AmpSelector extends AMP.BaseElement { /** @override */ buildCallback() { - this.action_ = actionServiceForDoc(this.element); + this.action_ = Services.actionServiceForDoc(this.element); this.isMultiple_ = this.element.hasAttribute('multiple'); this.isDisabled_ = this.element.hasAttribute('disabled'); diff --git a/extensions/amp-share-tracking/0.1/amp-share-tracking.js b/extensions/amp-share-tracking/0.1/amp-share-tracking.js index e1e7505df169..55dee70541f1 100644 --- a/extensions/amp-share-tracking/0.1/amp-share-tracking.js +++ b/extensions/amp-share-tracking/0.1/amp-share-tracking.js @@ -15,8 +15,7 @@ */ import {isExperimentOn} from '../../../src/experiments'; -import {xhrFor} from '../../../src/services'; -import {historyForDoc} from '../../../src/services'; +import {Services} from '../../../src/services'; import {registerServiceBuilder} from '../../../src/service'; import {Layout} from '../../../src/layout'; import {base64UrlEncodeFromBytes} from '../../../src/utils/base64'; @@ -143,7 +142,7 @@ export class AmpShareTracking extends AMP.BaseElement { credentials: 'include', body: dict(), }; - return xhrFor(this.win).fetchJson(vendorUrl, postReq) + return Services.xhrFor(this.win).fetchJson(vendorUrl, postReq) .then(res => res.json()) .then(json => { if (json.fragment) { @@ -209,7 +208,7 @@ export class AmpShareTracking extends AMP.BaseElement { /** @private @return {!../../../src/service/history-impl.History} */ getHistory_() { - return historyForDoc(this.getAmpDoc()); + return Services.historyForDoc(this.getAmpDoc()); } } diff --git a/extensions/amp-share-tracking/0.1/test/test-amp-share-tracking.js b/extensions/amp-share-tracking/0.1/test/test-amp-share-tracking.js index afedb93942f7..5036bff2f3cb 100644 --- a/extensions/amp-share-tracking/0.1/test/test-amp-share-tracking.js +++ b/extensions/amp-share-tracking/0.1/test/test-amp-share-tracking.js @@ -17,7 +17,7 @@ import {AmpShareTracking} from '../amp-share-tracking'; import {History} from '../../../../src/service/history-impl'; import {Xhr} from '../../../../src/service/xhr-impl'; -import {shareTrackingForOrNull} from '../../../../src/services'; +import {Services} from '../../../../src/services'; import {toggleExperiment} from '../../../../src/experiments'; import * as bytes from '../../../../src/utils/bytes'; @@ -63,10 +63,11 @@ describes.fakeWin('amp-share-tracking', { it('should get incoming fragment starting with dot', () => { historyGetFragmentStub.onFirstCall().returns(Promise.resolve('.12345')); const ampShareTracking = getAmpShareTracking(); - return shareTrackingForOrNull(ampShareTracking.win).then(fragments => { - expect(historyGetFragmentStub).to.be.calledOnce; - expect(fragments.incomingFragment).to.equal('12345'); - }); + return Services.shareTrackingForOrNull(ampShareTracking.win) + .then(fragments => { + expect(historyGetFragmentStub).to.be.calledOnce; + expect(fragments.incomingFragment).to.equal('12345'); + }); }); it('should get incoming fragment starting with dot and ignore ' + @@ -74,28 +75,31 @@ describes.fakeWin('amp-share-tracking', { historyGetFragmentStub.onFirstCall() .returns(Promise.resolve('.12345&key=value')); const ampShareTracking = getAmpShareTracking(); - return shareTrackingForOrNull(ampShareTracking.win).then(fragments => { - expect(historyGetFragmentStub).to.be.calledOnce; - expect(fragments.incomingFragment).to.equal('12345'); - }); + return Services.shareTrackingForOrNull(ampShareTracking.win) + .then(fragments => { + expect(historyGetFragmentStub).to.be.calledOnce; + expect(fragments.incomingFragment).to.equal('12345'); + }); }); it('should ignore incoming fragment if it is empty', () => { historyGetFragmentStub.onFirstCall().returns(Promise.resolve('')); const ampShareTracking = getAmpShareTracking(); - return shareTrackingForOrNull(ampShareTracking.win).then(fragments => { - expect(historyGetFragmentStub).to.be.calledOnce; - expect(fragments.incomingFragment).to.equal(''); - }); + return Services.shareTrackingForOrNull(ampShareTracking.win) + .then(fragments => { + expect(historyGetFragmentStub).to.be.calledOnce; + expect(fragments.incomingFragment).to.equal(''); + }); }); it('should ignore incoming fragment if it does not start with dot', () => { historyGetFragmentStub.onFirstCall().returns(Promise.resolve('12345')); const ampShareTracking = getAmpShareTracking(); - return shareTrackingForOrNull(ampShareTracking.win).then(fragments => { - expect(historyGetFragmentStub).to.be.calledOnce; - expect(fragments.incomingFragment).to.equal(''); - }); + return Services.shareTrackingForOrNull(ampShareTracking.win) + .then(fragments => { + expect(historyGetFragmentStub).to.be.calledOnce; + expect(fragments.incomingFragment).to.equal(''); + }); }); it('should get outgoing fragment randomly if no vendor url is provided ' + @@ -104,13 +108,14 @@ describes.fakeWin('amp-share-tracking', { historyGetFragmentStub.onFirstCall().returns(Promise.resolve('')); randomBytesStub.onFirstCall().returns(new Uint8Array([1, 2, 3, 4, 5, 6])); const ampShareTracking = getAmpShareTracking(); - return shareTrackingForOrNull(ampShareTracking.win).then(fragments => { - expect(historyGetFragmentStub).to.be.calledOnce; - // the base64url of byte array [1, 2, 3, 4, 5, 6] - expect(fragments.outgoingFragment).to.equal('AQIDBAUG'); - expect(historyUpdateFragmentStub.withArgs('.AQIDBAUG')).to.be - .calledOnce; - }); + return Services.shareTrackingForOrNull(ampShareTracking.win) + .then(fragments => { + expect(historyGetFragmentStub).to.be.calledOnce; + // the base64url of byte array [1, 2, 3, 4, 5, 6] + expect(fragments.outgoingFragment).to.equal('AQIDBAUG'); + expect(historyUpdateFragmentStub.withArgs('.AQIDBAUG')).to.be + .calledOnce; + }); }); it('should get outgoing fragment randomly if no vendor url is provided ' + @@ -119,13 +124,14 @@ describes.fakeWin('amp-share-tracking', { historyGetFragmentStub.onFirstCall().returns(Promise.resolve('.12345')); randomBytesStub.onFirstCall().returns(new Uint8Array([1, 2, 3, 4, 5, 6])); const ampShareTracking = getAmpShareTracking(); - return shareTrackingForOrNull(ampShareTracking.win).then(fragments => { - expect(historyGetFragmentStub).to.be.calledOnce; - // the base64url of byte array [1, 2, 3, 4, 5, 6] - expect(fragments.outgoingFragment).to.equal('AQIDBAUG'); - expect(historyUpdateFragmentStub.withArgs('.AQIDBAUG')).to.be - .calledOnce; - }); + return Services.shareTrackingForOrNull(ampShareTracking.win) + .then(fragments => { + expect(historyGetFragmentStub).to.be.calledOnce; + // the base64url of byte array [1, 2, 3, 4, 5, 6] + expect(fragments.outgoingFragment).to.equal('AQIDBAUG'); + expect(historyUpdateFragmentStub.withArgs('.AQIDBAUG')).to.be + .calledOnce; + }); }); it('should get outgoing fragment randomly if no vendor url is provided ' + @@ -136,13 +142,14 @@ describes.fakeWin('amp-share-tracking', { '.12345&key=value')); randomBytesStub.onFirstCall().returns(new Uint8Array([1, 2, 3, 4, 5, 6])); const ampShareTracking = getAmpShareTracking(); - return shareTrackingForOrNull(ampShareTracking.win).then(fragments => { - expect(historyGetFragmentStub).to.be.calledOnce; - // the base64url of byte array [1, 2, 3, 4, 5, 6] - expect(fragments.outgoingFragment).to.equal('AQIDBAUG'); - expect(historyUpdateFragmentStub.withArgs('.AQIDBAUG&key=value')) - .to.be.calledOnce; - }); + return Services.shareTrackingForOrNull(ampShareTracking.win) + .then(fragments => { + expect(historyGetFragmentStub).to.be.calledOnce; + // the base64url of byte array [1, 2, 3, 4, 5, 6] + expect(fragments.outgoingFragment).to.equal('AQIDBAUG'); + expect(historyUpdateFragmentStub.withArgs('.AQIDBAUG&key=value')) + .to.be.calledOnce; + }); }); it('should get outgoing fragment randomly if no vendor url ' + @@ -151,12 +158,13 @@ describes.fakeWin('amp-share-tracking', { sandbox.stub(Math, 'random').returns(0.123456789123456789); randomBytesStub.onFirstCall().returns(null); const ampShareTracking = getAmpShareTracking(); - return shareTrackingForOrNull(ampShareTracking.win).then(fragments => { - expect(historyGetFragmentStub).to.be.calledOnce; - expect(fragments.outgoingFragment).to.equal('H5rdN8Eh'); - expect(historyUpdateFragmentStub.withArgs('.H5rdN8Eh')).to.be - .calledOnce; - }); + return Services.shareTrackingForOrNull(ampShareTracking.win) + .then(fragments => { + expect(historyGetFragmentStub).to.be.calledOnce; + expect(fragments.outgoingFragment).to.equal('H5rdN8Eh'); + expect(historyUpdateFragmentStub.withArgs('.H5rdN8Eh')).to.be + .calledOnce; + }); }); it('should get outgoing fragment from vendor if vendor url is provided ' + @@ -169,11 +177,12 @@ describes.fakeWin('amp-share-tracking', { }, })); const ampShareTracking = getAmpShareTracking('http://foo.bar'); - return shareTrackingForOrNull(ampShareTracking.win).then(fragments => { - expect(historyGetFragmentStub).to.be.calledOnce; - expect(fragments.outgoingFragment).to.equal('54321'); - expect(historyUpdateFragmentStub.withArgs('.54321')).to.be.calledOnce; - }); + return Services.shareTrackingForOrNull(ampShareTracking.win) + .then(fragments => { + expect(historyGetFragmentStub).to.be.calledOnce; + expect(fragments.outgoingFragment).to.equal('54321'); + expect(historyUpdateFragmentStub.withArgs('.54321')).to.be.calledOnce; + }); }); it('should get empty outgoing fragment if vendor url is provided ' + @@ -185,11 +194,12 @@ describes.fakeWin('amp-share-tracking', { }, })); const ampShareTracking = getAmpShareTracking('http://foo.bar'); - return shareTrackingForOrNull(ampShareTracking.win).then(fragments => { - expect(historyGetFragmentStub).to.be.calledOnce; - expect(historyUpdateFragmentStub).to.not.be.called; - expect(fragments.outgoingFragment).to.equal(''); - }); + return Services.shareTrackingForOrNull(ampShareTracking.win) + .then(fragments => { + expect(historyGetFragmentStub).to.be.calledOnce; + expect(historyUpdateFragmentStub).to.not.be.called; + expect(fragments.outgoingFragment).to.equal(''); + }); }); it('should call fetchJson with correct request when getting outgoing' + @@ -208,11 +218,12 @@ describes.fakeWin('amp-share-tracking', { credentials: 'include', body: {}, }); - return shareTrackingForOrNull(ampShareTracking.win).then(fragments => { - expect(historyGetFragmentStub).to.be.calledOnce; - expect(historyUpdateFragmentStub.withArgs('.54321')).to.be.calledOnce; - expect(fragments.outgoingFragment).to.equal('54321'); - }); + return Services.shareTrackingForOrNull(ampShareTracking.win) + .then(fragments => { + expect(historyGetFragmentStub).to.be.calledOnce; + expect(historyUpdateFragmentStub.withArgs('.54321')).to.be.calledOnce; + expect(fragments.outgoingFragment).to.equal('54321'); + }); }); it('should get empty outgoing fragment if vendor url is provided ' + @@ -225,10 +236,11 @@ describes.fakeWin('amp-share-tracking', { }, })); const ampShareTracking = getAmpShareTracking('http://foo.bar'); - return shareTrackingForOrNull(ampShareTracking.win).then(fragments => { - expect(historyGetFragmentStub).to.be.calledOnce; - expect(historyUpdateFragmentStub).to.not.be.called; - expect(fragments.outgoingFragment).to.equal(''); - }); + return Services.shareTrackingForOrNull(ampShareTracking.win) + .then(fragments => { + expect(historyGetFragmentStub).to.be.calledOnce; + expect(historyUpdateFragmentStub).to.not.be.called; + expect(fragments.outgoingFragment).to.equal(''); + }); }); }); diff --git a/extensions/amp-sidebar/0.1/amp-sidebar.js b/extensions/amp-sidebar/0.1/amp-sidebar.js index 571d606d7698..a44362d359b6 100644 --- a/extensions/amp-sidebar/0.1/amp-sidebar.js +++ b/extensions/amp-sidebar/0.1/amp-sidebar.js @@ -19,12 +19,9 @@ import {KeyCodes} from '../../../src/utils/key-codes'; import {closestByTag, tryFocus} from '../../../src/dom'; import {Layout} from '../../../src/layout'; import {dev} from '../../../src/log'; -import {historyForDoc} from '../../../src/services'; -import {platformFor} from '../../../src/services'; +import {Services} from '../../../src/services'; import {setStyles, toggle} from '../../../src/style'; import {removeFragment, parseUrl} from '../../../src/url'; -import {vsyncFor} from '../../../src/services'; -import {timerFor} from '../../../src/services'; /** @const */ const ANIMATION_TIMEOUT = 550; @@ -41,7 +38,7 @@ export class AmpSidebar extends AMP.BaseElement { this.viewport_ = null; /** @const @private {!../../../src/service/vsync-impl.Vsync} */ - this.vsync_ = vsyncFor(this.win); + this.vsync_ = Services.vsyncFor(this.win); /** @private {?Element} */ this.maskElement_ = null; @@ -55,7 +52,7 @@ export class AmpSidebar extends AMP.BaseElement { /** @private {?string} */ this.side_ = null; - const platform = platformFor(this.win); + const platform = Services.platformFor(this.win); /** @private @const {boolean} */ this.isIos_ = platform.isIos(); @@ -70,7 +67,7 @@ export class AmpSidebar extends AMP.BaseElement { this.bottomBarCompensated_ = false; /** @private @const {!../../../src/service/timer-impl.Timer} */ - this.timer_ = timerFor(this.win); + this.timer_ = Services.timerFor(this.win); /** @private {number|string|null} */ this.openOrCloseTimeOut_ = null; @@ -325,7 +322,7 @@ export class AmpSidebar extends AMP.BaseElement { * @private @return {!../../../src/service/history-impl.History} */ getHistory_() { - return historyForDoc(this.getAmpDoc()); + return Services.historyForDoc(this.getAmpDoc()); } } diff --git a/extensions/amp-sidebar/0.1/test/test-amp-sidebar.js b/extensions/amp-sidebar/0.1/test/test-amp-sidebar.js index 8c03ba174ff6..d27d190102f0 100644 --- a/extensions/amp-sidebar/0.1/test/test-amp-sidebar.js +++ b/extensions/amp-sidebar/0.1/test/test-amp-sidebar.js @@ -18,8 +18,7 @@ import {KeyCodes} from '../../../../src/utils/key-codes'; import {adopt} from '../../../../src/runtime'; import {createIframePromise} from '../../../../testing/iframe'; -import {platformFor} from '../../../../src/services'; -import {timerFor} from '../../../../src/services'; +import {Services} from '../../../../src/services'; import {assertScreenReaderElement} from '../../../../testing/test-helper'; import * as sinon from 'sinon'; import '../amp-sidebar'; @@ -68,7 +67,7 @@ describes.realWin('amp-sidebar 0.1 version', { ampSidebar.setAttribute('id', 'sidebar1'); ampSidebar.setAttribute('layout', 'nodisplay'); return iframe.addElement(ampSidebar).then(() => { - timer = timerFor(iframe.win); + timer = Services.timerFor(iframe.win); return {iframe, ampSidebar}; }); }); @@ -87,7 +86,7 @@ describes.realWin('amp-sidebar 0.1 version', { beforeEach(() => { sandbox = sinon.sandbox.create(); - platform = platformFor(window); + platform = Services.platformFor(window); }); afterEach(() => { diff --git a/extensions/amp-sidebar/1.0/amp-sidebar.js b/extensions/amp-sidebar/1.0/amp-sidebar.js index e92fe6c6ebdb..7d716fc16885 100644 --- a/extensions/amp-sidebar/1.0/amp-sidebar.js +++ b/extensions/amp-sidebar/1.0/amp-sidebar.js @@ -20,12 +20,9 @@ import {dev, user} from '../../../src/log'; import {isExperimentOn} from '../../../src/experiments'; import {KeyCodes} from '../../../src/utils/key-codes'; import {closestByTag, tryFocus} from '../../../src/dom'; -import {historyForDoc} from '../../../src/services'; -import {platformFor} from '../../../src/services'; +import {Services} from '../../../src/services'; import {setStyles, toggle} from '../../../src/style'; import {removeFragment, parseUrl} from '../../../src/url'; -import {vsyncFor} from '../../../src/services'; -import {timerFor} from '../../../src/services'; import {Toolbar} from './toolbar'; /** @const */ @@ -46,7 +43,7 @@ export class AmpSidebar extends AMP.BaseElement { this.viewport_ = null; /** @const @private {!../../../src/service/vsync-impl.Vsync} */ - this.vsync_ = vsyncFor(this.win); + this.vsync_ = Services.vsyncFor(this.win); /** @private {?Element} */ this.maskElement_ = null; @@ -63,7 +60,7 @@ export class AmpSidebar extends AMP.BaseElement { /** @private {Array} */ this.toolbars_ = []; - const platform = platformFor(this.win); + const platform = Services.platformFor(this.win); /** @private @const {boolean} */ this.isIosSafari_ = platform.isIos() && platform.isSafari(); @@ -75,7 +72,7 @@ export class AmpSidebar extends AMP.BaseElement { this.bottomBarCompensated_ = false; /** @private @const {!../../../src/service/timer-impl.Timer} */ - this.timer_ = timerFor(this.win); + this.timer_ = Services.timerFor(this.win); /** @private {number|string|null} */ this.openOrCloseTimeOut_ = null; @@ -361,7 +358,7 @@ export class AmpSidebar extends AMP.BaseElement { * @private @return {!../../../src/service/history-impl.History} */ getHistory_() { - return historyForDoc(this.getAmpDoc()); + return Services.historyForDoc(this.getAmpDoc()); } } diff --git a/extensions/amp-sidebar/1.0/test/test-amp-sidebar.js b/extensions/amp-sidebar/1.0/test/test-amp-sidebar.js index 9052c687aa4b..8a43e17179b1 100644 --- a/extensions/amp-sidebar/1.0/test/test-amp-sidebar.js +++ b/extensions/amp-sidebar/1.0/test/test-amp-sidebar.js @@ -18,8 +18,7 @@ import {KeyCodes} from '../../../../src/utils/key-codes'; import {adopt} from '../../../../src/runtime'; import {createIframePromise} from '../../../../testing/iframe'; - import {platformFor} from '../../../../src/services'; - import {timerFor} from '../../../../src/services'; + import {Services} from '../../../../src/services'; import {assertScreenReaderElement} from '../../../../testing/test-helper'; import {toggleExperiment} from '../../../../src/experiments'; import * as sinon from 'sinon'; @@ -100,7 +99,7 @@ ampSidebar.setAttribute('id', 'sidebar1'); ampSidebar.setAttribute('layout', 'nodisplay'); return iframe.addElement(ampSidebar).then(() => { - timer = timerFor(iframe.win); + timer = Services.timerFor(iframe.win); if (options.toolbars) { sandbox.stub(timer, 'delay', function(callback) { callback(); @@ -124,7 +123,7 @@ beforeEach(() => { sandbox = sinon.sandbox.create(); - platform = platformFor(window); + platform = Services.platformFor(window); toggleExperiment(window, 'amp-sidebar 1.0', true); }); diff --git a/extensions/amp-sidebar/1.0/test/test-toolbar.js b/extensions/amp-sidebar/1.0/test/test-toolbar.js index 8caca15d2776..49f345b00246 100644 --- a/extensions/amp-sidebar/1.0/test/test-toolbar.js +++ b/extensions/amp-sidebar/1.0/test/test-toolbar.js @@ -17,7 +17,7 @@ import {adopt} from '../../../../src/runtime'; import {createIframePromise} from '../../../../testing/iframe'; - import {timerFor, vsyncFor} from '../../../../src/services'; + import {Services} from '../../../../src/services'; import * as sinon from 'sinon'; import {Toolbar} from '../toolbar'; @@ -41,8 +41,8 @@ const toolbarContainerElement = iframe.doc.createElement('div'); const toolbars = []; iframe.win.document.body.appendChild(toolbarContainerElement); - vsync = vsyncFor(iframe.win); - timer = timerFor(iframe.win); + vsync = Services.vsyncFor(iframe.win); + timer = Services.timerFor(iframe.win); // Stub our toolbar operations, doing this here as it will // Ease testing our media queries sandbox.stub(vsync, diff --git a/extensions/amp-social-share/0.1/amp-social-share.js b/extensions/amp-social-share/0.1/amp-social-share.js index cbb803833747..330d64858832 100644 --- a/extensions/amp-social-share/0.1/amp-social-share.js +++ b/extensions/amp-social-share/0.1/amp-social-share.js @@ -23,9 +23,8 @@ import {isLayoutSizeDefined} from '../../../src/layout'; import {dev, user} from '../../../src/log'; import {dict} from '../../../src/utils/object'; import {openWindowDialog} from '../../../src/dom'; -import {urlReplacementsForDoc} from '../../../src/services'; +import {Services} from '../../../src/services'; import {CSS} from '../../../build/amp-social-share-0.1.css'; -import {platformFor} from '../../../src/services'; class AmpSocialShare extends AMP.BaseElement { @@ -84,10 +83,10 @@ class AmpSocialShare extends AMP.BaseElement { 'The data-share-endpoint attribute is required. %s', this.element); Object.assign(this.params_, typeConfig['defaultParams'], getDataParamsFromAttributes(this.element)); - this.platform_ = platformFor(this.win); + this.platform_ = Services.platformFor(this.win); const hrefWithVars = addParamsToUrl(this.shareEndpoint_, this.params_); - const urlReplacements = urlReplacementsForDoc(this.getAmpDoc()); + const urlReplacements = Services.urlReplacementsForDoc(this.getAmpDoc()); urlReplacements.expandAsync(hrefWithVars).then(href => { this.href_ = href; // mailto:, whatsapp: protocols breaks when opened in _blank on iOS Safari diff --git a/extensions/amp-social-share/0.1/test/test-amp-social-share.js b/extensions/amp-social-share/0.1/test/test-amp-social-share.js index 50489dc27430..022175973784 100644 --- a/extensions/amp-social-share/0.1/test/test-amp-social-share.js +++ b/extensions/amp-social-share/0.1/test/test-amp-social-share.js @@ -19,7 +19,7 @@ import {adopt} from '../../../../src/runtime'; import {createIframePromise} from '../../../../testing/iframe'; import * as sinon from 'sinon'; import '../amp-social-share'; -import {platformFor} from '../../../../src/services'; +import {Services} from '../../../../src/services'; adopt(window); @@ -61,7 +61,7 @@ describe('amp-social-share', () => { function getCustomShare(modifier) { return createIframePromise().then(iframe => { - platform = platformFor(iframe.win); + platform = Services.platformFor(iframe.win); sandbox.stub(platform, 'isIos', () => isIos); sandbox.stub(platform, 'isSafari', () => isSafari); const canonical = iframe.doc.createElement('link'); diff --git a/extensions/amp-user-notification/0.1/amp-user-notification.js b/extensions/amp-user-notification/0.1/amp-user-notification.js index 2a10bfa0cae6..d4e0d21e9f67 100644 --- a/extensions/amp-user-notification/0.1/amp-user-notification.js +++ b/extensions/amp-user-notification/0.1/amp-user-notification.js @@ -16,14 +16,10 @@ import {CSS} from '../../../build/amp-user-notification-0.1.css'; import {assertHttpsUrl, addParamsToUrl} from '../../../src/url'; -import {cidForDoc} from '../../../src/services'; +import {Services} from '../../../src/services'; import {registerServiceBuilder, getService} from '../../../src/service'; import {dev, user, rethrowAsync} from '../../../src/log'; -import {storageForDoc} from '../../../src/services'; -import {urlReplacementsForDoc} from '../../../src/services'; -import {viewerForDoc} from '../../../src/services'; import {whenDocumentReady} from '../../../src/document-ready'; -import {xhrFor} from '../../../src/services'; import {setStyle} from '../../../src/style'; @@ -130,8 +126,8 @@ export class AmpUserNotification extends AMP.BaseElement { /** @override */ buildCallback() { const ampdoc = this.getAmpDoc(); - this.urlReplacements_ = urlReplacementsForDoc(ampdoc); - this.storagePromise_ = storageForDoc(ampdoc); + this.urlReplacements_ = Services.urlReplacementsForDoc(ampdoc); + this.storagePromise_ = Services.storageForDoc(ampdoc); if (!this.userNotificationManager_) { installUserNotificationManager(window); this.userNotificationManager_ = getService(window, @@ -204,7 +200,8 @@ export class AmpUserNotification extends AMP.BaseElement { credentials: 'include', requireAmpResponseSourceOrigin: false, }; - return xhrFor(this.win).fetchJson(href, getReq).then(res => res.json()); + return Services.xhrFor(this.win) + .fetchJson(href, getReq).then(res => res.json()); }); } @@ -214,15 +211,17 @@ export class AmpUserNotification extends AMP.BaseElement { * @return {!Promise} */ postDismissEnpoint_() { - return xhrFor(this.win).fetchJson(dev().assertString(this.dismissHref_), { - method: 'POST', - credentials: 'include', - requireAmpResponseSourceOrigin: false, - body: /** @type {!JsonObject} */({ - 'elementId': this.elementId_, - 'ampUserId': this.ampUserId_, - }), - }); + return Services.xhrFor(this.win).fetchJson( + dev().assertString(this.dismissHref_), + { + method: 'POST', + credentials: 'include', + requireAmpResponseSourceOrigin: false, + body: /** @type {!JsonObject} */({ + 'elementId': this.elementId_, + 'ampUserId': this.ampUserId_, + }), + }); } /** @@ -287,7 +286,7 @@ export class AmpUserNotification extends AMP.BaseElement { * @private */ getCidService_() { - return cidForDoc(this.element); + return Services.cidForDoc(this.element); } /** @override */ @@ -390,7 +389,7 @@ export class UserNotificationManager { this.deferRegistry_ = Object.create(null); /** @private @const {!../../../src/service/viewer-impl.Viewer} */ - this.viewer_ = viewerForDoc(this.win.document); + this.viewer_ = Services.viewerForDoc(this.win.document); /** @private @const {!Promise} */ this.documentReadyPromise_ = whenDocumentReady(this.win.document); diff --git a/extensions/amp-video/0.1/amp-video.js b/extensions/amp-video/0.1/amp-video.js index 65d41060bce8..937588323396 100644 --- a/extensions/amp-video/0.1/amp-video.js +++ b/extensions/amp-video/0.1/amp-video.js @@ -23,7 +23,7 @@ import { installVideoManagerForDoc, } from '../../../src/service/video-manager-impl'; import {VideoEvents} from '../../../src/video-interface'; -import {videoManagerForDoc} from '../../../src/services'; +import {Services} from '../../../src/services'; import {assertHttpsUrl} from '../../../src/url'; const TAG = 'amp-video'; @@ -115,7 +115,7 @@ class AmpVideo extends AMP.BaseElement { this.element.appendChild(this.video_); installVideoManagerForDoc(this.element); - videoManagerForDoc(this.element).register(this); + Services.videoManagerForDoc(this.element).register(this); } /** @override */ diff --git a/extensions/amp-video/0.1/test/test-amp-video.js b/extensions/amp-video/0.1/test/test-amp-video.js index a1e1c4c532b7..455131e6d6d0 100644 --- a/extensions/amp-video/0.1/test/test-amp-video.js +++ b/extensions/amp-video/0.1/test/test-amp-video.js @@ -16,7 +16,7 @@ import {createIframePromise} from '../../../../testing/iframe'; import {listenOncePromise} from '../../../../src/event-helper'; -import {timerFor} from '../../../../src/services'; +import {Services} from '../../../../src/services'; import {VideoEvents} from '../../../../src/video-interface'; import '../amp-video'; import * as sinon from 'sinon'; @@ -26,7 +26,7 @@ const TAG = 'amp-video'; describe(TAG, () => { let sandbox; - const timer = timerFor(window); + const timer = Services.timerFor(window); beforeEach(() => { sandbox = sinon.sandbox.create(); diff --git a/extensions/amp-viewer-integration/0.1/amp-viewer-integration.js b/extensions/amp-viewer-integration/0.1/amp-viewer-integration.js index 8541584639df..cee15862a4f1 100644 --- a/extensions/amp-viewer-integration/0.1/amp-viewer-integration.js +++ b/extensions/amp-viewer-integration/0.1/amp-viewer-integration.js @@ -27,7 +27,7 @@ import {dev} from '../../../src/log'; import {dict} from '../../../src/utils/object'; import {getData} from '../../../src/event-helper'; import {getSourceUrl} from '../../../src/url'; -import {viewerForDoc} from '../../../src/services'; +import {Services} from '../../../src/services'; const TAG = 'amp-viewer-integration'; const APP = '__AMPHTML__'; @@ -68,7 +68,7 @@ export class AmpViewerIntegration { */ init() { dev().fine(TAG, 'handshake init()'); - const viewer = viewerForDoc(this.win.document); + const viewer = Services.viewerForDoc(this.win.document); this.isWebView_ = viewer.getParam('webview') == '1'; this.isHandShakePoll_ = viewer.hasCapability('handshakepoll'); const origin = viewer.getParam('origin') || ''; diff --git a/extensions/amp-viz-vega/0.1/amp-viz-vega.js b/extensions/amp-viz-vega/0.1/amp-viz-vega.js index 7337d01eddeb..661d4b13610a 100644 --- a/extensions/amp-viz-vega/0.1/amp-viz-vega.js +++ b/extensions/amp-viz-vega/0.1/amp-viz-vega.js @@ -22,8 +22,7 @@ import {isLayoutSizeDefined} from '../../../src/layout'; import {dev, user} from '../../../src/log'; import {isObject, isFiniteNumber} from '../../../src/types'; import {assertHttpsUrl} from '../../../src/url'; -import {vsyncFor} from '../../../src/services'; -import {xhrFor} from '../../../src/services'; +import {Services} from '../../../src/services'; /** @const */ const EXPERIMENT = 'amp-viz-vega'; @@ -158,11 +157,13 @@ export class AmpVizVega extends AMP.BaseElement { // calls. We may want to intercept all "urls" in spec and do the loading // and parsing ourselves. - return xhrFor(this.win).fetchJson(dev().assertString(this.src_), { - requireAmpResponseSourceOrigin: false, - }).then(res => res.json()).then(data => { - this.data_ = data; - }); + return Services.xhrFor(this.win).fetchJson( + dev().assertString(this.src_), + { + requireAmpResponseSourceOrigin: false, + }).then(res => res.json()).then(data => { + this.data_ = data; + }); } } @@ -201,7 +202,7 @@ export class AmpVizVega extends AMP.BaseElement { }); return parsePromise.then(chartFactory => { - return vsyncFor(this.win).mutatePromise(() => { + return Services.vsyncFor(this.win).mutatePromise(() => { dom.removeChildren(dev().assertElement(this.container_)); this.chart_ = chartFactory({el: this.container_}); if (!this.useDataWidth_) { diff --git a/extensions/amp-youtube/0.1/amp-youtube.js b/extensions/amp-youtube/0.1/amp-youtube.js index bcfcadc8047f..17d7fdf73777 100644 --- a/extensions/amp-youtube/0.1/amp-youtube.js +++ b/extensions/amp-youtube/0.1/amp-youtube.js @@ -28,7 +28,7 @@ import {addParamsToUrl} from '../../../src/url'; import {isObject} from '../../../src/types'; import {dict} from '../../../src/utils/object'; import {VideoEvents} from '../../../src/video-interface'; -import {videoManagerForDoc} from '../../../src/services'; +import {Services} from '../../../src/services'; import {startsWith} from '../../../src/string'; /** @@ -139,7 +139,7 @@ class AmpYoutube extends AMP.BaseElement { } installVideoManagerForDoc(this.element); - videoManagerForDoc(this.element).register(this); + Services.videoManagerForDoc(this.element).register(this); } /** @return {string} */ diff --git a/extensions/amp-youtube/0.1/test/test-amp-youtube.js b/extensions/amp-youtube/0.1/test/test-amp-youtube.js index ff26aa38728c..86256ace17af 100644 --- a/extensions/amp-youtube/0.1/test/test-amp-youtube.js +++ b/extensions/amp-youtube/0.1/test/test-amp-youtube.js @@ -21,7 +21,7 @@ import { import '../amp-youtube'; import {listenOncePromise} from '../../../../src/event-helper'; import {adopt} from '../../../../src/runtime'; -import {timerFor} from '../../../../src/services'; +import {Services} from '../../../../src/services'; import {VideoEvents} from '../../../../src/video-interface'; import * as sinon from 'sinon'; @@ -30,7 +30,7 @@ adopt(window); describe('amp-youtube', function() { this.timeout(5000); let sandbox; - const timer = timerFor(window); + const timer = Services.timerFor(window); beforeEach(() => { sandbox = sinon.sandbox.create(); diff --git a/src/ad-cid.js b/src/ad-cid.js index 31ded3b054cd..2b6c5bdff2dc 100644 --- a/src/ad-cid.js +++ b/src/ad-cid.js @@ -14,7 +14,7 @@ * limitations under the License. */ -import {cidForDoc, timerFor} from './services'; +import {Services} from './services'; import {adConfig} from '../ads/_config'; import {dev} from '../src/log'; @@ -41,7 +41,7 @@ export function getAdCid(adElement) { */ export function getOrCreateAdCid( ampDoc, clientIdScope, opt_clientIdCookieName) { - const cidPromise = cidForDoc(ampDoc).then(cidService => { + const cidPromise = Services.cidForDoc(ampDoc).then(cidService => { if (!cidService) { return; } @@ -57,7 +57,7 @@ export function getOrCreateAdCid( }); // The CID should never be crucial for an ad. If it does not come within // 1 second, assume it will never arrive. - return timerFor(ampDoc.win) + return Services.timerFor(ampDoc.win) .timeoutPromise(1000, cidPromise, 'cid timeout').catch(error => { // Timeout is not fatal. dev().warn('AD-CID', error); diff --git a/src/amp.js b/src/amp.js index 327258ad8142..e0124fdf1c71 100644 --- a/src/amp.js +++ b/src/amp.js @@ -19,12 +19,10 @@ */ import './polyfills'; +import {Services} from './services'; import {startupChunk} from './chunk'; import {fontStylesheetTimeout} from './font-stylesheet-timeout'; -import { - installPerformanceService, - performanceFor, -} from './service/performance-impl'; +import {installPerformanceService} from './service/performance-impl'; import {installPullToRefreshBlocker} from './pull-to-refresh'; import {installStyles, makeBodyVisible} from './style-installer'; import {installErrorReporting} from './error'; @@ -40,7 +38,6 @@ import { import {cssText} from '../build/css'; import {maybeValidate} from './validator-integration'; import {maybeTrackImpression} from './impression'; -import {ampdocServiceFor, resourcesForDoc} from './services'; // Store the originalHash as early as possible. Trying to debug: // https://github.com/ampproject/amphtml/issues/6070 @@ -60,7 +57,7 @@ try { // Declare that this runtime will support a single root doc. Should happen // as early as possible. installDocService(self, /* isSingleDoc */ true); - ampdocService = ampdocServiceFor(self); + ampdocService = Services.ampdocServiceFor(self); } catch (e) { // In case of an error call this. makeBodyVisible(self.document); @@ -71,7 +68,7 @@ startupChunk(self.document, function initial() { const ampdoc = ampdocService.getAmpDoc(self.document); installPerformanceService(self); /** @const {!./service/performance-impl.Performance} */ - const perf = performanceFor(self); + const perf = Services.performanceFor(self); fontStylesheetTimeout(self); perf.tick('is'); installStyles(self.document, cssText, () => { @@ -102,7 +99,7 @@ startupChunk(self.document, function initial() { }); startupChunk(self.document, function finalTick() { perf.tick('e_is'); - resourcesForDoc(ampdoc).ampInitComplete(); + Services.resourcesForDoc(ampdoc).ampInitComplete(); // TODO(erwinm): move invocation of the `flush` method when we have the // new ticks in place to batch the ticks properly. perf.flush(); diff --git a/src/analytics.js b/src/analytics.js index 9a121a848a82..7e3648e1a5d0 100644 --- a/src/analytics.js +++ b/src/analytics.js @@ -14,7 +14,7 @@ * limitations under the License. */ -import {analyticsForDocOrNull} from './services'; +import {Services} from './services'; /** * Helper method to trigger analytics event if amp-analytics is available. @@ -24,7 +24,7 @@ import {analyticsForDocOrNull} from './services'; * @param {!Object=} opt_vars A map of vars and their values. */ export function triggerAnalyticsEvent(target, eventType, opt_vars) { - analyticsForDocOrNull(target).then(analytics => { + Services.analyticsForDocOrNull(target).then(analytics => { if (!analytics) { return; } diff --git a/src/anchor-click-interceptor.js b/src/anchor-click-interceptor.js index 544a6aedcb9b..0ffa470ec2a5 100644 --- a/src/anchor-click-interceptor.js +++ b/src/anchor-click-interceptor.js @@ -18,7 +18,7 @@ import { closestByTag, } from './dom'; import {dev} from './log'; -import {urlReplacementsForDoc} from './services'; +import {Services} from './services'; /** @private @const {string} */ const ORIG_HREF_ATTRIBUTE = 'data-a4a-orig-href'; @@ -60,7 +60,7 @@ function maybeExpandUrlParams(ampdoc, e) { return e.pageY; }, }; - const newHref = urlReplacementsForDoc(ampdoc).expandSync( + const newHref = Services.urlReplacementsForDoc(ampdoc).expandSync( hrefToExpand, vars, undefined, /* opt_whitelist */ { // For now we only allow to replace the click location vars // and nothing else. diff --git a/src/animation.js b/src/animation.js index 9498bf1d58c8..67f5e822d3c7 100644 --- a/src/animation.js +++ b/src/animation.js @@ -16,7 +16,7 @@ import {getCurve} from './curve'; import {dev} from './log'; -import {vsyncFor} from './services'; +import {Services} from './services'; const TAG_ = 'Animation'; @@ -58,7 +58,7 @@ export class Animation { this.contextNode_ = contextNode; /** @private @const {!./service/vsync-impl.Vsync} */ - this.vsync_ = opt_vsync || vsyncFor(self); + this.vsync_ = opt_vsync || Services.vsyncFor(self); /** @private {?./curve.CurveDef} */ this.curve_ = null; diff --git a/src/base-element.js b/src/base-element.js index c1f2ed9e4120..bef76c940778 100644 --- a/src/base-element.js +++ b/src/base-element.js @@ -20,8 +20,7 @@ import {getData} from './event-helper'; import {loadPromise} from './event-helper'; import {preconnectForElement} from './preconnect'; import {isArray} from './types'; -import {viewportForDoc} from './services'; -import {vsyncFor} from './services'; +import {Services} from './services'; import {user} from './log'; /** @@ -235,7 +234,7 @@ export class BaseElement { /** @public @return {!./service/vsync-impl.Vsync} */ getVsync() { - return vsyncFor(this.win); + return Services.vsyncFor(this.win); } /** @@ -731,7 +730,7 @@ export class BaseElement { * @return {!./service/viewport-impl.Viewport} */ getViewport() { - return viewportForDoc(this.getAmpDoc()); + return Services.viewportForDoc(this.getAmpDoc()); } /** diff --git a/src/batched-json.js b/src/batched-json.js index 2f208431c388..2733aa91584a 100644 --- a/src/batched-json.js +++ b/src/batched-json.js @@ -15,7 +15,7 @@ */ import {assertHttpsUrl} from './url'; -import {batchedXhrFor, urlReplacementsForDoc} from './services'; +import {Services} from './services'; import {getValueForExpr} from './json'; /** @@ -32,14 +32,14 @@ import {getValueForExpr} from './json'; */ export function fetchBatchedJsonFor(ampdoc, element, opt_expr) { const url = assertHttpsUrl(element.getAttribute('src'), element); - return urlReplacementsForDoc(ampdoc).expandAsync(url).then(src => { + return Services.urlReplacementsForDoc(ampdoc).expandAsync(url).then(src => { const opts = {}; if (element.hasAttribute('credentials')) { opts.credentials = element.getAttribute('credentials'); } else { opts.requireAmpResponseSourceOrigin = false; } - return batchedXhrFor(ampdoc.win).fetchJson(src, opts); + return Services.batchedXhrFor(ampdoc.win).fetchJson(src, opts); }).then(res => res.json()).then(data => { if (data == null) { throw new Error('Response is undefined.'); diff --git a/src/chunk.js b/src/chunk.js index 9229ff2b40e0..392360007369 100644 --- a/src/chunk.js +++ b/src/chunk.js @@ -19,7 +19,7 @@ import {dev} from './log'; import {getData} from './event-helper'; import {registerServiceBuilderForDoc, getServiceForDoc} from './service'; import {makeBodyVisible} from './style-installer'; -import {viewerPromiseForDoc} from './services'; +import {Services} from './services'; /** * @const {string} @@ -315,7 +315,7 @@ class Chunks { this.boundExecute_ = this.execute_.bind(this); /** @private @const {!Promise} */ - this.viewerPromise_ = viewerPromiseForDoc(ampDoc); + this.viewerPromise_ = Services.viewerPromiseForDoc(ampDoc); this.win_.addEventListener('message', e => { if (getData(e) == 'amp-macro-task') { diff --git a/src/custom-element.js b/src/custom-element.js index 4e08aad1e69d..3c552111dea4 100644 --- a/src/custom-element.js +++ b/src/custom-element.js @@ -20,6 +20,7 @@ import {Layout, getLayoutClass, getLengthNumeral, getLengthUnits, parseLayout, parseLength, getNaturalDimensions, hasNaturalDimensions} from './layout'; import {ElementStub, stubbedElements} from './element-stub'; +import {Services} from './services'; import {Signals} from './utils/signals'; import {createLoaderElement} from '../src/loader'; import {dev, rethrowAsync, user} from './log'; @@ -29,14 +30,6 @@ import { import {getMode} from './mode'; import {parseSizeList} from './size-list'; import {reportError} from './error'; -import { - ampdocServiceFor, - documentStateFor, - performanceForOrNull, - resourcesForDoc, - timerFor, - vsyncFor, -} from './services'; import * as dom from './dom'; import {setStyle, setStyles} from './style'; import {LayoutDelayMeter} from './layout-delay-meter'; @@ -172,7 +165,7 @@ export function stubElements(win) { } // Repeat stubbing when HEAD is complete. if (!win.document.body) { - const docState = documentStateFor(win); + const docState = Services.documentStateFor(win); docState.onBodyAvailable(() => stubElements(win)); } } @@ -592,7 +585,7 @@ function createBaseCustomElementClass(win) { /** @private @const */ this.signals_ = new Signals(); - const perf = performanceForOrNull(win); + const perf = Services.performanceForOrNull(win); /** @private {boolean} */ this.perfOn_ = perf && perf.isPerformanceTrackingOn(); @@ -777,7 +770,7 @@ function createBaseCustomElementClass(win) { if (this.actionQueue_) { // Only schedule when the queue is not empty, which should be // the case 99% of the time. - timerFor(this.ownerDocument.defaultView) + Services.timerFor(this.ownerDocument.defaultView) .delay(this.dequeueActions_.bind(this), 1); } if (!this.getPlaceholder()) { @@ -801,7 +794,7 @@ function createBaseCustomElementClass(win) { // If we do early preconnects we delay them a bit. This is kind of // an unfortunate trade off, but it seems faster, because the DOM // operations themselves are not free and might delay - timerFor(this.ownerDocument.defaultView).delay(() => { + Services.timerFor(this.ownerDocument.defaultView).delay(() => { this.implementation_.preconnectCallback(onLayout); }, 1); } @@ -988,12 +981,13 @@ function createBaseCustomElementClass(win) { } if (!this.ampdoc_) { // Ampdoc can now be initialized. - const ampdocService = ampdocServiceFor(this.ownerDocument.defaultView); + const ampdocService = Services.ampdocServiceFor( + this.ownerDocument.defaultView); this.ampdoc_ = ampdocService.getAmpDoc(this); } if (!this.resources_) { // Resources can now be initialized since the ampdoc is now available. - this.resources_ = resourcesForDoc(this.ampdoc_); + this.resources_ = Services.resourcesForDoc(this.ampdoc_); } this.getResources().add(this); @@ -1312,7 +1306,7 @@ function createBaseCustomElementClass(win) { } else { // Set a minimum delay in case the element loads very fast or if it // leaves the viewport. - timerFor(this.ownerDocument.defaultView).delay(() => { + Services.timerFor(this.ownerDocument.defaultView).delay(() => { // TODO(dvoytenko, #9177): cleanup `this.ownerDocument.defaultView` // once investigation is complete. It appears that we get a lot of // errors here once the iframe is destroyed due to timer. @@ -1903,7 +1897,7 @@ function assertNotTemplate(element) { function getVsync(element) { // TODO(dvoytenko, #9177): consider removing this and always resolving via // `createCustomElementClass(win)` object. - return vsyncFor(element.ownerDocument.defaultView); + return Services.vsyncFor(element.ownerDocument.defaultView); }; /** diff --git a/src/document-submit.js b/src/document-submit.js index 4092d89cafd1..771c2e160399 100644 --- a/src/document-submit.js +++ b/src/document-submit.js @@ -15,7 +15,7 @@ */ import {ActionTrust} from './action-trust'; -import {actionServiceForDoc} from './services'; +import {Services} from './services'; import {dev, user} from './log'; import { assertHttpsUrl, @@ -130,7 +130,7 @@ export function onDocumentFormSubmit_(e) { // to deliver the submission event. e.stopImmediatePropagation(); - const actions = actionServiceForDoc(form); + const actions = Services.actionServiceForDoc(form); // TODO(choumx, #9699): HIGH. actions.execute(form, 'submit', /*args*/ null, form, e, ActionTrust.MEDIUM); } diff --git a/src/element-service.js b/src/element-service.js index 9c2cd2e2bb38..d01ceadba405 100644 --- a/src/element-service.js +++ b/src/element-service.js @@ -31,7 +31,7 @@ import * as dom from './dom'; * an element that has the actual implementation. The promise resolves when * the implementation loaded. * Users should typically wrap this as a special purpose function (e.g. - * viewportForDoc(...)) for type safety and because the factory should not be + * Services.viewportForDoc(...)) for type safety and because the factory should not be * passed around. * @param {!Window} win * @param {string} id of the service. @@ -84,7 +84,7 @@ function isElementScheduled(win, elementName) { * an element that has the actual implementation. The promise resolves when * the implementation loaded. * Users should typically wrap this as a special purpose function (e.g. - * viewportForDoc(...)) for type safety and because the factory should not be + * Services.viewportForDoc(...)) for type safety and because the factory should not be * passed around. * @param {!Node|!./service/ampdoc-impl.AmpDoc} nodeOrDoc * @param {string} id of the service. diff --git a/src/element-stub.js b/src/element-stub.js index ccfb009a6fe5..7348b059a8fe 100644 --- a/src/element-stub.js +++ b/src/element-stub.js @@ -16,7 +16,7 @@ import {BaseElement} from './base-element'; import {dev} from './log'; -import {extensionsFor} from './services'; +import {Services} from './services'; /** @type {!Array} */ export const stubbedElements = []; @@ -32,7 +32,8 @@ export class ElementStub extends BaseElement { const name = element.tagName.toLowerCase(); if (!loadingChecked[name]) { loadingChecked[name] = true; - extensionsFor(this.win).loadExtension(name, /* stubElement */ false); + Services.extensionsFor(this.win).loadExtension( + name, /* stubElement */ false); } stubbedElements.push(this); } diff --git a/src/extension-analytics.js b/src/extension-analytics.js index 81a490ab6e37..35b1f39ab0d9 100644 --- a/src/extension-analytics.js +++ b/src/extension-analytics.js @@ -15,6 +15,7 @@ */ import {CommonSignals} from './common-signals'; +import {Services} from './services'; import { createElementWithAttributes, removeElement, @@ -22,9 +23,7 @@ import { import {dev} from './log'; import {dict} from './utils/object'; import {isArray} from './types'; -import {analyticsForDocOrNull} from './services'; import {triggerAnalyticsEvent} from './analytics'; -import {extensionsFor} from './services'; /** * Method to create scoped analytics element for any element. @@ -55,10 +54,11 @@ export function insertAnalyticsElement( // Force load analytics extension if script not included in page. if (loadAnalytics) { // Get Extensions service and force load analytics extension. - const extensions = extensionsFor(parentElement.ownerDocument.defaultView); + const extensions = + Services.extensionsFor(parentElement.ownerDocument.defaultView); extensions./*OK*/loadExtension('amp-analytics'); } else { - analyticsForDocOrNull(parentElement).then(analytics => { + Services.analyticsForDocOrNull(parentElement).then(analytics => { dev().assert(analytics); }); } diff --git a/src/focus-history.js b/src/focus-history.js index 6da4054a7b22..c3ffe3c24c80 100644 --- a/src/focus-history.js +++ b/src/focus-history.js @@ -15,7 +15,7 @@ */ import {Observable} from './observable'; -import {timerFor} from './services'; +import {Services} from './services'; import {dev} from './log'; @@ -52,7 +52,7 @@ export class FocusHistory { // IFrame elements do not receive `focus` event. An alternative way is // implemented here. We wait for a blur to arrive on the main window // and after a short time check which element is active. - timerFor(win).delay(() => { + Services.timerFor(win).delay(() => { this.pushFocus_(this.win.document.activeElement); }, 500); }; diff --git a/src/friendly-iframe-embed.js b/src/friendly-iframe-embed.js index 81daa48645a7..145b3cec0c64 100644 --- a/src/friendly-iframe-embed.js +++ b/src/friendly-iframe-embed.js @@ -20,14 +20,12 @@ import {Signals} from './utils/signals'; import {dev, rethrowAsync} from './log'; import {disposeServicesForEmbed, getTopWindow} from './service'; import {escapeHtml} from './dom'; -import {extensionsFor} from './services'; +import {Services} from './services'; import {getFixedContainer} from './full-overlay-frame-child-helper'; import {isDocumentReady} from './document-ready'; import {layoutRectLtwh} from './layout-rect'; import {loadPromise} from './event-helper'; import {px, resetStyles, setStyle, setStyles} from './style'; -import {resourcesForDoc} from './services'; -import {vsyncFor} from './services'; /** @const {string} */ @@ -123,7 +121,7 @@ export function installFriendlyIframeEmbed(iframe, container, spec, /** @const {!Window} */ const win = getTopWindow(iframe.ownerDocument.defaultView); /** @const {!./service/extensions-impl.Extensions} */ - const extensions = extensionsFor(win); + const extensions = Services.extensionsFor(win); setStyle(iframe, 'visibility', 'hidden'); iframe.setAttribute('referrerpolicy', 'unsafe-url'); @@ -338,7 +336,7 @@ export class FriendlyIframeEmbed { * Ensures that all resources from this iframe have been released. */ destroy() { - resourcesForDoc(this.iframe).removeForChildWindow(this.win); + Services.resourcesForDoc(this.iframe).removeForChildWindow(this.win); disposeServicesForEmbed(this.win); } @@ -470,7 +468,7 @@ export class FriendlyIframeEmbed { * @visibleForTesting */ getVsync() { - return vsyncFor(this.win); + return Services.vsyncFor(this.win); } /** @@ -478,7 +476,7 @@ export class FriendlyIframeEmbed { * @visibleForTesting */ getResources() { - return resourcesForDoc(this.iframe); + return Services.resourcesForDoc(this.iframe); } /** @@ -604,7 +602,7 @@ export class FriendlyIframeEmbed { * @return {!Promise} */ export function whenContentIniLoad(context, hostWin, rect) { - return resourcesForDoc(context) + return Services.resourcesForDoc(context) .getResourcesInRect(hostWin, rect) .then(resources => { const promises = []; diff --git a/src/iframe-attributes.js b/src/iframe-attributes.js index 6e84215a6991..d4b7bf2d9d9f 100644 --- a/src/iframe-attributes.js +++ b/src/iframe-attributes.js @@ -14,9 +14,8 @@ * limitations under the License. */ import {urls} from './config'; -import {documentInfoForDoc} from './services'; +import {Services} from './services'; import {experimentToggles, isCanary} from './experiments'; -import {viewerForDoc} from './services'; import {getLengthNumeral} from './layout'; import {getModeObject} from './mode-object'; import {domFingerprint} from './utils/dom-fingerprint'; @@ -46,8 +45,8 @@ export function getContextMetadata( locationHref = parentWindow.parent.location.href; } - const docInfo = documentInfoForDoc(element); - const viewer = viewerForDoc(element); + const docInfo = Services.documentInfoForDoc(element); + const viewer = Services.viewerForDoc(element); const referrer = viewer.getUnconfirmedReferrerUrl(); // TODO(alanorozco): Redesign data structure so that fields not exposed by diff --git a/src/impression.js b/src/impression.js index 2cdb773f2fd9..a5b3895f1212 100644 --- a/src/impression.js +++ b/src/impression.js @@ -16,15 +16,13 @@ import {dev, user} from './log'; import {isExperimentOn} from './experiments'; -import {viewerForDoc} from './services'; -import {xhrFor} from './services'; +import {Services} from './services'; import { isProxyOrigin, parseUrl, parseQueryString, addParamsToUrl, } from './url'; -import {timerFor} from './services'; import {getMode} from './mode'; const TIMEOUT_VALUE = 8000; @@ -64,7 +62,7 @@ export function maybeTrackImpression(win) { return; } - const viewer = viewerForDoc(win.document); + const viewer = Services.viewerForDoc(win.document); /** @const {string|undefined} */ const clickUrl = viewer.getParam('click'); @@ -93,8 +91,8 @@ export function maybeTrackImpression(win) { }); // Timeout invoke promise after 8s and resolve trackImpressionPromise. - resolveImpression(timerFor(win).timeoutPromise(TIMEOUT_VALUE, promise, - 'timeout waiting for ad server response').catch(() => {})); + resolveImpression(Services.timerFor(win).timeoutPromise(TIMEOUT_VALUE, + promise, 'timeout waiting for ad server response').catch(() => {})); }); } @@ -115,7 +113,7 @@ function invoke(win, clickUrl) { if (getMode().localDev && !getMode().test) { clickUrl = 'http://localhost:8000/impression-proxy?url=' + clickUrl; } - return xhrFor(win).fetchJson(clickUrl, { + return Services.xhrFor(win).fetchJson(clickUrl, { credentials: 'include', }).then(res => res.json()); } diff --git a/src/inabox/amp-inabox.js b/src/inabox/amp-inabox.js index dd003f54585e..603209efeec8 100644 --- a/src/inabox/amp-inabox.js +++ b/src/inabox/amp-inabox.js @@ -20,14 +20,11 @@ import '../../third_party/babel/custom-babel-helpers'; import '../polyfills'; -import {ampdocServiceFor, resourcesForDoc} from '../services'; +import {Services} from '../services'; import {startupChunk} from '../chunk'; import {fontStylesheetTimeout} from '../font-stylesheet-timeout'; import {installIframeMessagingClient} from './inabox-iframe-messaging-client'; -import { - installPerformanceService, - performanceFor, -} from '../service/performance-impl'; +import {installPerformanceService} from '../service/performance-impl'; import {installStyles, makeBodyVisible} from '../style-installer'; import {installErrorReporting} from '../error'; import {installDocService} from '../service/ampdoc-impl'; @@ -63,7 +60,7 @@ try { // Declare that this runtime will support a single root doc. Should happen // as early as possible. installDocService(self, /* isSingleDoc */ true); - ampdocService = ampdocServiceFor(self); + ampdocService = Services.ampdocServiceFor(self); } catch (e) { // In case of an error call this. makeBodyVisible(self.document); @@ -74,7 +71,7 @@ startupChunk(self.document, function initial() { const ampdoc = ampdocService.getAmpDoc(self.document); installPerformanceService(self); /** @const {!../service/performance-impl.Performance} */ - const perf = performanceFor(self); + const perf = Services.performanceFor(self); perf.tick('is'); self.document.documentElement.classList.add('i-amphtml-inabox'); @@ -116,7 +113,7 @@ startupChunk(self.document, function initial() { }); startupChunk(self.document, function finalTick() { perf.tick('e_is'); - resourcesForDoc(ampdoc).ampInitComplete(); + Services.resourcesForDoc(ampdoc).ampInitComplete(); // TODO(erwinm): move invocation of the `flush` method when we have the // new ticks in place to batch the ticks properly. perf.flush(); diff --git a/src/inabox/inabox-viewport.js b/src/inabox/inabox-viewport.js index 873ceb401a20..f7ece6c8724e 100644 --- a/src/inabox/inabox-viewport.js +++ b/src/inabox/inabox-viewport.js @@ -16,10 +16,9 @@ import {getFixedContainer} from '../../src/full-overlay-frame-child-helper'; import {iframeMessagingClientFor} from './inabox-iframe-messaging-client'; -import {viewerForDoc} from '../services'; +import {Services} from '../services'; import {Viewport, ViewportBindingDef} from '../service/viewport-impl'; import {registerServiceBuilderForDoc} from '../service'; -import {resourcesForDoc} from '../services'; import { nativeIntersectionObserverSupported, } from '../../src/intersection-observer-polyfill'; @@ -27,7 +26,6 @@ import {layoutRectLtwh} from '../layout-rect'; import {Observable} from '../observable'; import {MessageType} from '../../src/3p-frame-messaging'; import {dev} from '../log'; -import {vsyncFor} from '../../src/services'; import {px, setStyles} from '../../src/style'; @@ -37,7 +35,7 @@ const TAG = 'inabox-viewport'; /** @visibleForTesting */ export function prepareFixedContainer(win, fixedContainer) { - return vsyncFor(win).runPromise({ + return Services.vsyncFor(win).runPromise({ measure: state => { state.boundingRect = fixedContainer./*OK*/getBoundingClientRect(); }, @@ -64,7 +62,7 @@ export function prepareFixedContainer(win, fixedContainer) { /** @visibleForTesting */ export function resetFixedContainer(win, fixedContainer) { - return vsyncFor(win).mutatePromise(() => { + return Services.vsyncFor(win).mutatePromise(() => { setStyles(dev().assertElement(win.document.body), { 'background': 'transparent', }); @@ -229,7 +227,7 @@ export class ViewportBindingInabox { * @visibleForTesting */ getChildResources() { - return resourcesForDoc(this.win.document).get(); + return Services.resourcesForDoc(this.win.document).get(); } /** @private */ @@ -357,7 +355,7 @@ export class ViewportBindingInabox { */ export function installInaboxViewportService(ampdoc) { const binding = new ViewportBindingInabox(ampdoc.win); - const viewer = viewerForDoc(ampdoc); + const viewer = Services.viewerForDoc(ampdoc); registerServiceBuilderForDoc(ampdoc, 'viewport', function() { diff --git a/src/input.js b/src/input.js index 34a86721f931..2b6baa9fc64f 100644 --- a/src/input.js +++ b/src/input.js @@ -16,7 +16,7 @@ import {Observable} from './observable'; import {dev} from './log'; -import {timerFor} from './services'; +import {Services} from './services'; import {listenOnce, listenOncePromise} from './event-helper'; import {registerServiceBuilder} from './service'; @@ -221,7 +221,8 @@ export class Input { /* capture */ undefined, unlistener => { unlisten = unlistener; }); - return timerFor(this.win).timeoutPromise(CLICK_TIMEOUT_, listenPromise) + return Services.timerFor(this.win) + .timeoutPromise(CLICK_TIMEOUT_, listenPromise) .then(this.boundMouseCanceled_, () => { if (unlisten) { unlisten(); diff --git a/src/intersection-observer.js b/src/intersection-observer.js index 1979197e9f91..02034b1d0c50 100644 --- a/src/intersection-observer.js +++ b/src/intersection-observer.js @@ -18,7 +18,7 @@ import {dev} from './log'; import {dict} from './utils/object'; import {layoutRectLtwh, rectIntersection, moveLayoutRect} from './layout-rect'; import {SubscriptionApi} from './iframe-helper'; -import {timerFor} from './services'; +import {Services} from './services'; /** * The structure that defines the rectangle used in intersection observers. @@ -123,7 +123,7 @@ export class IntersectionObserver { /** @private @const {!AMP.BaseElement} */ this.baseElement_ = baseElement; /** @private @const {!./service/timer-impl.Timer} */ - this.timer_ = timerFor(baseElement.win); + this.timer_ = Services.timerFor(baseElement.win); /** @private {boolean} */ this.shouldSendIntersectionChanges_ = false; /** @private {boolean} */ diff --git a/src/layout-delay-meter.js b/src/layout-delay-meter.js index 892d07b2d374..1ae249253a03 100644 --- a/src/layout-delay-meter.js +++ b/src/layout-delay-meter.js @@ -14,7 +14,7 @@ * limitations under the License. */ -import {performanceForOrNull} from './services'; +import {Services} from './services'; import {dev} from './log'; const LABEL_MAP = { @@ -36,7 +36,7 @@ export class LayoutDelayMeter { /** @private {!Window} */ this.win_ = win; /** @private {?./service/performance-impl.Performance} */ - this.performance_ = performanceForOrNull(win); + this.performance_ = Services.performanceForOrNull(win); /** @private {?number} */ this.firstInViewportTime_ = null; /** @private {?number} */ diff --git a/src/motion.js b/src/motion.js index b251ce02a608..d09068670ef5 100644 --- a/src/motion.js +++ b/src/motion.js @@ -14,7 +14,7 @@ * limitations under the License. */ -import {vsyncFor} from './services'; +import {Services} from './services'; /** @const {function()} */ const NOOP_CALLBACK_ = function() {}; @@ -107,7 +107,7 @@ export class Motion { */ constructor(contextNode, startX, startY, veloX, veloY, callback, opt_vsync) { /** @private @const {!./service/vsync-impl.Vsync} */ - this.vsync_ = opt_vsync || vsyncFor(self); + this.vsync_ = opt_vsync || Services.vsyncFor(self); /** @private @const {!Node} */ this.contextNode_ = contextNode; diff --git a/src/pass.js b/src/pass.js index 430b41194580..ec599a817a30 100644 --- a/src/pass.js +++ b/src/pass.js @@ -14,7 +14,7 @@ * limitations under the License. */ -import {timerFor} from './services'; +import {Services} from './services'; /** @@ -32,7 +32,7 @@ export class Pass { * is called without one. */ constructor(win, handler, opt_defaultDelay) { - this.timer_ = timerFor(win); + this.timer_ = Services.timerFor(win); /** @private @const {function()} */ this.handler_ = handler; diff --git a/src/preconnect.js b/src/preconnect.js index a314c81a1fc5..117356687832 100644 --- a/src/preconnect.js +++ b/src/preconnect.js @@ -22,9 +22,7 @@ import {getService, registerServiceBuilder} from './service'; import {parseUrl} from './url'; -import {timerFor} from './services'; -import {platformFor} from './services'; -import {viewerForDoc} from './services'; +import {Services} from './services'; import {dev} from './log'; import {startsWith} from './string'; @@ -98,7 +96,7 @@ class PreconnectService { */ this.urls_ = {}; /** @private @const {!./service/platform-impl.Platform} */ - this.platform_ = platformFor(win); + this.platform_ = Services.platformFor(win); // Mark current origin as preconnected. this.origins_[parseUrl(win.location.href).origin] = true; @@ -111,7 +109,7 @@ class PreconnectService { this.features_ = getPreconnectFeatures(win); /** @private @const {!./service/timer-impl.Timer} */ - this.timer_ = timerFor(win); + this.timer_ = Services.timerFor(win); } /** @@ -320,7 +318,7 @@ export class Preconnect { */ getViewer_() { if (!this.viewer_) { - this.viewer_ = viewerForDoc(this.element_); + this.viewer_ = Services.viewerForDoc(this.element_); } return this.viewer_; } diff --git a/src/pull-to-refresh.js b/src/pull-to-refresh.js index 7c44357d620a..fd0489d96035 100644 --- a/src/pull-to-refresh.js +++ b/src/pull-to-refresh.js @@ -14,9 +14,7 @@ * limitations under the License. */ -import {platformFor} from './services'; -import {viewerForDoc} from './services'; -import {viewportForDoc} from './services'; +import {Services} from './services'; /** @@ -28,9 +26,10 @@ import {viewportForDoc} from './services'; export function installPullToRefreshBlocker(win) { // Only do when requested and don't even try it on Safari! // This mode is only executed in the single-doc mode. - if (viewerForDoc(win.document).getParam('p2r') == '0' && - platformFor(win).isChrome()) { - new PullToRefreshBlocker(win.document, viewportForDoc(win.document)); + if (Services.viewerForDoc(win.document).getParam('p2r') == '0' && + Services.platformFor(win).isChrome()) { + new PullToRefreshBlocker( + win.document, Services.viewportForDoc(win.document)); } } diff --git a/src/render-delaying-services.js b/src/render-delaying-services.js index bd6fff350dee..91d9b7bf5259 100644 --- a/src/render-delaying-services.js +++ b/src/render-delaying-services.js @@ -16,7 +16,7 @@ import {dev} from './log'; import {getServicePromise} from './service'; -import {timerFor} from './services'; +import {Services} from './services'; /** * A map of services that delay rendering. The key is the name of the service @@ -56,7 +56,7 @@ const LOAD_TIMEOUT = 3000; */ export function waitForServices(win) { const promises = includedServices(win).map(service => { - return timerFor(win).timeoutPromise( + return Services.timerFor(win).timeoutPromise( LOAD_TIMEOUT, getServicePromise(win, service), `Render timeout waiting for service ${service} to be ready.` diff --git a/src/runtime.js b/src/runtime.js index e90fd73d8a28..84ff87388adc 100644 --- a/src/runtime.js +++ b/src/runtime.js @@ -35,7 +35,7 @@ import { registerExtension, stubLegacyElements, } from './service/extensions-impl'; -import {ampdocServiceFor, platformFor} from './services'; +import {Services} from './services'; import {startupChunk} from './chunk'; import {cssText} from '../build/css'; import {dev, user, initLogConstructor, setReportError} from './log'; @@ -57,7 +57,6 @@ import {installDocumentInfoServiceForDoc} from './service/document-info-impl'; import {installDocumentStateService} from './service/document-state'; import {installGlobalClickListenerForDoc} from './service/document-click'; import {installGlobalSubmitListenerForDoc} from './document-submit'; -import {extensionsFor} from './services'; import {installHistoryServiceForDoc} from './service/history-impl'; import {installPlatformService} from './service/platform-impl'; import {installResourcesServiceForDoc} from './service/resources-impl'; @@ -86,11 +85,7 @@ import { import {parseUrl} from './url'; import {registerElement} from './custom-element'; import {registerExtendedElement} from './extended-element'; -import {resourcesForDoc} from './services'; import {setStyle} from './style'; -import {timerFor} from './services'; -import {viewerForDoc} from './services'; -import {viewportForDoc} from './services'; import {waitForBody} from './dom'; import * as config from './config'; @@ -182,7 +177,7 @@ function adoptShared(global, opts, callback) { installExtensionsService(global); /** @const {!./service/extensions-impl.Extensions} */ - const extensions = extensionsFor(global); + const extensions = Services.extensionsFor(global); installRuntimeServices(global); stubLegacyElements(global); @@ -300,7 +295,7 @@ function adoptShared(global, opts, callback) { */ function installAutoLoadExtensions() { if (!getMode().test && isExperimentOn(global, 'amp-lightbox-viewer-auto')) { - extensionsFor(global).loadExtension('amp-lightbox-viewer'); + Services.extensionsFor(global).loadExtension('amp-lightbox-viewer'); } } @@ -366,7 +361,7 @@ function adoptShared(global, opts, callback) { // For iOS we need to set `cursor:pointer` to ensure that click events are // delivered. - if (platformFor(global).isIos()) { + if (Services.platformFor(global).isIos()) { setStyle(global.document.documentElement, 'cursor', 'pointer'); } } @@ -382,16 +377,16 @@ export function adopt(global) { registerElement: prepareAndRegisterElement, registerServiceForDoc: prepareAndRegisterServiceForDoc, }, global => { - const viewer = viewerForDoc(global.document); + const viewer = Services.viewerForDoc(global.document); global.AMP.viewer = viewer; if (getMode().development) { global.AMP.toggleRuntime = viewer.toggleRuntime.bind(viewer); - global.AMP.resources = resourcesForDoc(global.document); + global.AMP.resources = Services.resourcesForDoc(global.document); } - const viewport = viewportForDoc(global.document); + const viewport = Services.viewportForDoc(global.document); global.AMP.viewport = {}; global.AMP.viewport.getScrollLeft = viewport.getScrollLeft.bind(viewport); @@ -413,9 +408,9 @@ export function adoptShadowMode(global) { const manager = new MultidocManager( global, - ampdocServiceFor(global), + Services.ampdocServiceFor(global), extensions, - timerFor(global)); + Services.timerFor(global)); /** * Registers a shadow root document via a fully fetched document. @@ -516,7 +511,7 @@ function prepareAndRegisterServiceForDoc(global, extensions, name, opt_ctor, opt_factory) { // TODO(kmh287, #9292): Refactor to remove opt_factory param and require ctor // once #9212 has been in prod for two releases. - const ampdocService = ampdocServiceFor(global); + const ampdocService = Services.ampdocServiceFor(global); const ampdoc = ampdocService.getAmpDoc(); registerServiceForDoc(ampdoc, name, opt_ctor, opt_factory); @@ -630,7 +625,7 @@ class MultidocManager { // Instal doc services. installAmpdocServices(ampdoc, initParams || Object.create(null)); - const viewer = viewerForDoc(ampdoc); + const viewer = Services.viewerForDoc(ampdoc); /** * Sets the document's visibility state. @@ -684,7 +679,7 @@ class MultidocManager { if (getMode().development) { amp.toggleRuntime = viewer.toggleRuntime.bind(viewer); - amp.resources = resourcesForDoc(ampdoc); + amp.resources = Services.resourcesForDoc(ampdoc); } // Start building the shadow doc DOM. @@ -933,7 +928,7 @@ class MultidocManager { return; } // Broadcast message asynchronously. - const viewer = viewerForDoc(shadowRoot.AMP.ampdoc); + const viewer = Services.viewerForDoc(shadowRoot.AMP.ampdoc); this.timer_.delay(() => { viewer.receiveMessage('broadcast', /** @type {!JsonObject} */ (data), @@ -951,7 +946,8 @@ class MultidocManager { const amp = shadowRoot.AMP; delete shadowRoot.AMP; const ampdoc = /** @type {!./service/ampdoc-impl.AmpDoc} */ (amp.ampdoc); - setViewerVisibilityState(viewerForDoc(ampdoc), VisibilityState.INACTIVE); + setViewerVisibilityState( + Services.viewerForDoc(ampdoc), VisibilityState.INACTIVE); disposeServicesForDoc(ampdoc); } @@ -1079,7 +1075,7 @@ function maybeLoadCorrectVersion(win, fnOrStruct) { // assumes it as not-present. scriptInHead.removeAttribute('custom-element'); scriptInHead.setAttribute('i-amphtml-loaded-new-version', fnOrStruct.n); - extensionsFor(win).loadExtension(fnOrStruct.n, + Services.extensionsFor(win).loadExtension(fnOrStruct.n, /* stubbing not needed, should have already happened. */ false); return true; } @@ -1106,5 +1102,5 @@ function maybePumpEarlyFrame(win, cb) { cb(); return; } - timerFor(win).delay(cb, 1); + Services.timerFor(win).delay(cb, 1); } diff --git a/src/service-worker/install.js b/src/service-worker/install.js index 053017bae452..bf730c80ceb1 100644 --- a/src/service-worker/install.js +++ b/src/service-worker/install.js @@ -18,7 +18,7 @@ import {calculateEntryPointScriptUrl} from '../service/extension-location'; import {isExperimentOn} from '../experiments'; import {dev} from '../log'; import {getMode} from '../mode'; -import {timerFor} from '../services'; +import {Services} from '../services'; import {parseUrl} from '../url'; import {urls} from '../config'; @@ -29,7 +29,7 @@ const TAG = 'cache-service-worker'; * Registers the Google AMP Cache service worker if the browser supports SWs. */ export function installCacheServiceWorker(win) { - timerFor(win).delay(() => { + Services.timerFor(win).delay(() => { if (!isExperimentOn(win, TAG)) { return; } diff --git a/src/service.js b/src/service.js index d9ad8c4821b4..aeea5dcce9ad 100644 --- a/src/service.js +++ b/src/service.js @@ -198,7 +198,7 @@ export function registerServiceBuilderForDoc(nodeOrDoc, /** * Returns a service for the given id and window (a per-window singleton). * Users should typically wrap this as a special purpose function (e.g. - * `vsyncFor(win)`) for type safety and because the factory should not be + * `Services.vsyncFor(win)`) for type safety and because the factory should not be * passed around. * @param {!Window} win * @param {string} id of the service. @@ -216,7 +216,7 @@ export function getService(win, id) { * an element that has the actual implementation. The promise resolves when * the implementation loaded. * Users should typically wrap this as a special purpose function (e.g. - * `vsyncFor(win)`) for type safety and because the factory should not be + * `Services.vsyncFor(win)`) for type safety and because the factory should not be * passed around. * @param {!Window} win * @param {string} id of the service. diff --git a/src/service/action-impl.js b/src/service/action-impl.js index 2cc008cca2de..5f0da6f9e77b 100644 --- a/src/service/action-impl.js +++ b/src/service/action-impl.js @@ -26,8 +26,7 @@ import {getMode} from '../mode'; import {getValueForExpr} from '../json'; import {isArray, isFiniteNumber} from '../types'; import {map} from '../utils/object'; -import {timerFor} from '../services'; -import {vsyncFor} from '../services'; +import {Services} from '../services'; /** * ActionInfoDef args key that maps to the an unparsed object literal string. @@ -177,7 +176,7 @@ export class ActionService { this.globalMethodHandlers_ = map(); /** @private {!./vsync-impl.Vsync} */ - this.vsync_ = vsyncFor(ampdoc.win); + this.vsync_ = Services.vsyncFor(ampdoc.win); // Add core events. this.addEvent('tap'); @@ -354,7 +353,7 @@ export class ActionService { // Dequeue the current queue. if (isArray(currentQueue)) { - timerFor(target.ownerDocument.defaultView).delay(() => { + Services.timerFor(target.ownerDocument.defaultView).delay(() => { // TODO(dvoytenko, #1260): dedupe actions. currentQueue.forEach(invocation => { try { diff --git a/src/service/cid-impl.js b/src/service/cid-impl.js index 65f87b548ad3..1ecb2ce5050b 100644 --- a/src/service/cid-impl.js +++ b/src/service/cid-impl.js @@ -35,7 +35,7 @@ import { import {dict} from '../utils/object'; import {isIframed} from '../dom'; import {getCryptoRandomBytesArray} from '../utils/bytes'; -import {cryptoFor, viewerForDoc, storageForDoc, timerFor} from '../services'; +import {Services} from '../services'; import {parseJson, tryParseJson} from '../json'; import {user, rethrowAsync} from '../log'; @@ -123,7 +123,7 @@ export class Cid { getCidStruct.scope); return consent.then(() => { - return viewerForDoc(this.ampdoc).whenFirstVisible(); + return Services.viewerForDoc(this.ampdoc).whenFirstVisible(); }).then(() => { // Check if user has globally opted out of CID, we do this after // consent check since user can optout during consent process. @@ -135,7 +135,7 @@ export class Cid { const cidPromise = this.getExternalCid_( getCidStruct, opt_persistenceConsent || consent); // Getting the CID might involve an HTTP request. We timeout after 10s. - return timerFor(this.ampdoc.win) + return Services.timerFor(this.ampdoc.win) .timeoutPromise(10000, cidPromise, `Getting cid for "${getCidStruct.scope}" timed out`) .catch(error => { @@ -168,13 +168,13 @@ export class Cid { if (!isProxyOrigin(url)) { return getOrCreateCookie(this, getCidStruct, persistenceConsent); } - const viewer = viewerForDoc(this.ampdoc); + const viewer = Services.viewerForDoc(this.ampdoc); if (viewer.hasCapability('cid')) { return this.getScopedCidFromViewer_(getCidStruct.scope); } return getBaseCid(this, persistenceConsent) .then(baseCid => { - return cryptoFor(this.ampdoc.win).sha384Base64( + return Services.cryptoFor(this.ampdoc.win).sha384Base64( baseCid + getProxySourceOrigin(url) + getCidStruct.scope); }); } @@ -184,7 +184,7 @@ export class Cid { * @return {!Promise} */ getScopedCidFromViewer_(scope) { - const viewer = viewerForDoc(this.ampdoc); + const viewer = Services.viewerForDoc(this.ampdoc); return viewer.isTrustedViewer().then(trusted => { if (!trusted) { rethrowAsync('Ignore CID API from Untrustful Viewer.'); @@ -205,10 +205,11 @@ export class Cid { export function optOutOfCid(ampdoc) { // Tell the viewer that user has opted out. - viewerForDoc(ampdoc)./*OK*/sendMessage(CID_OPTOUT_VIEWER_MESSAGE, dict()); + Services.viewerForDoc(ampdoc)./*OK*/sendMessage( + CID_OPTOUT_VIEWER_MESSAGE, dict()); // Store the optout bit in storage - return storageForDoc(ampdoc).then(storage => { + return Services.storageForDoc(ampdoc).then(storage => { return storage.set(CID_OPTOUT_STORAGE_KEY, true); }); } @@ -221,7 +222,7 @@ export function optOutOfCid(ampdoc) { * @visibleForTesting */ export function isOptedOutOfCid(ampdoc) { - return storageForDoc(ampdoc).then(storage => { + return Services.storageForDoc(ampdoc).then(storage => { return storage.get(CID_OPTOUT_STORAGE_KEY).then(val => !!val); }).catch(() => { // If we fail to read the flag, assume not opted out. @@ -274,7 +275,7 @@ function getOrCreateCookie(cid, getCidStruct, persistenceConsent) { Promise.resolve(existingCookie)); } - const newCookiePromise = cryptoFor(win).sha384Base64(getEntropy(win)) + const newCookiePromise = Services.cryptoFor(win).sha384Base64(getEntropy(win)) // Create new cookie, always prefixed with "amp-", so that we can see from // the value whether we created it. .then(randomStr => 'amp-' + randomStr); @@ -335,7 +336,7 @@ function getBaseCid(cid, persistenceConsent) { } } else { // We need to make a new one. - baseCid = cryptoFor(win).sha384Base64(getEntropy(win)); + baseCid = Services.cryptoFor(win).sha384Base64(getEntropy(win)); needsToStore = true; } @@ -385,7 +386,7 @@ function store(ampdoc, persistenceConsent, cidString) { * @return {!Promise} */ export function viewerBaseCid(ampdoc, opt_data) { - const viewer = viewerForDoc(ampdoc); + const viewer = Services.viewerForDoc(ampdoc); return viewer.isTrustedViewer().then(trusted => { if (!trusted) { return undefined; diff --git a/src/service/crypto-impl.js b/src/service/crypto-impl.js index 816248dfebee..820579cf5b43 100644 --- a/src/service/crypto-impl.js +++ b/src/service/crypto-impl.js @@ -16,7 +16,7 @@ import {registerServiceBuilder, getService} from '../service'; import {dev} from '../log'; -import {extensionsFor} from '../services'; +import {Services} from '../services'; import {stringToBytes, utf8EncodeSync} from '../utils/bytes'; import {base64UrlEncodeFromBytes} from '../utils/base64'; @@ -117,7 +117,7 @@ export class Crypto { if (this.polyfillPromise_) { return this.polyfillPromise_; } - return this.polyfillPromise_ = extensionsFor(this.win_) + return this.polyfillPromise_ = Services.extensionsFor(this.win_) .loadExtension('amp-crypto-polyfill') .then(() => getService(this.win_, 'crypto-polyfill')); } diff --git a/src/service/document-click.js b/src/service/document-click.js index 602ede35b32f..b955d90e4c80 100644 --- a/src/service/document-click.js +++ b/src/service/document-click.js @@ -26,14 +26,7 @@ import { } from '../service'; import {dev} from '../log'; import {getMode} from '../mode'; -import { - historyForDoc, - platformFor, - timerFor, - urlReplacementsForDoc, - viewerForDoc, - viewportForDoc, -} from '../services'; +import {Services} from '../services'; import {parseUrl, parseUrlWithA} from '../url'; const TAG = 'clickhandler'; @@ -72,15 +65,15 @@ export class ClickHandler { this.rootNode_ = opt_rootNode || ampdoc.getRootNode(); /** @private @const {!./viewport-impl.Viewport} */ - this.viewport_ = viewportForDoc(this.ampdoc); + this.viewport_ = Services.viewportForDoc(this.ampdoc); /** @private @const {!./viewer-impl.Viewer} */ - this.viewer_ = viewerForDoc(this.ampdoc); + this.viewer_ = Services.viewerForDoc(this.ampdoc); /** @private @const {!./history-impl.History} */ - this.history_ = historyForDoc(this.ampdoc); + this.history_ = Services.historyForDoc(this.ampdoc); - const platform = platformFor(this.ampdoc.win); + const platform = Services.platformFor(this.ampdoc.win); /** @private @const {boolean} */ this.isIosSafari_ = platform.isIos() && platform.isSafari(); @@ -139,7 +132,7 @@ export class ClickHandler { if (!target || !target.href) { return; } - urlReplacementsForDoc(target).maybeExpandLink(target); + Services.urlReplacementsForDoc(target).maybeExpandLink(target); const tgtLoc = this.parseUrl_(target.href); @@ -268,8 +261,8 @@ export class ClickHandler { // Without the first call there will be a visual jump due to browser scroll. // See https://github.com/ampproject/amphtml/issues/5334 for more details. this.viewport_./*OK*/scrollIntoView(elem); - timerFor(this.ampdoc.win).delay(() => this.viewport_./*OK*/scrollIntoView( - dev().assertElement(elem)), 1); + Services.timerFor(this.ampdoc.win).delay(() => + this.viewport_./*OK*/scrollIntoView(dev().assertElement(elem)), 1); } else { dev().warn(TAG, `failed to find element with id=${hash} or a[name=${hash}]`); diff --git a/src/service/fixed-layer.js b/src/service/fixed-layer.js index 6e5fc140064e..7f45c60f89c4 100644 --- a/src/service/fixed-layer.js +++ b/src/service/fixed-layer.js @@ -16,7 +16,7 @@ import {dev, user} from '../log'; import {endsWith} from '../string'; -import {platformFor} from '../services'; +import {Services} from '../services'; import {getStyle, setStyle, setStyles, computedStyle} from '../style'; const TAG = 'FixedLayer'; @@ -116,7 +116,7 @@ export class FixedLayer { // Sort in document order. this.sortInDomOrder_(); - const platform = platformFor(this.ampdoc.win); + const platform = Services.platformFor(this.ampdoc.win); if (this.elements_.length > 0 && !this.transfer_ && platform.isIos()) { user().warn(TAG, 'Please test this page inside of an AMP Viewer such' + ' as Google\'s because the fixed or sticky positioning might have' + diff --git a/src/service/history-impl.js b/src/service/history-impl.js index 5df77eb71e38..af5a87583865 100644 --- a/src/service/history-impl.js +++ b/src/service/history-impl.js @@ -22,8 +22,7 @@ import { import {getMode} from '../mode'; import {dev} from '../log'; import {dict, map} from '../utils/object'; -import {timerFor} from '../services'; -import {viewerForDoc} from '../services'; +import {Services} from '../services'; /** @private @const */ const TAG_ = 'History'; @@ -46,7 +45,7 @@ export class History { this.ampdoc_ = ampdoc; /** @private @const {!../service/timer-impl.Timer} */ - this.timer_ = timerFor(ampdoc.win); + this.timer_ = Services.timerFor(ampdoc.win); /** @private @const {!HistoryBindingInterface} */ this.binding_ = binding; @@ -329,7 +328,7 @@ export class HistoryBindingNatural_ { this.win = win; /** @private @const {!../service/timer-impl.Timer} */ - this.timer_ = timerFor(win); + this.timer_ = Services.timerFor(win); const history = this.win.history; @@ -842,7 +841,7 @@ export class HistoryBindingVirtual_ { * @private */ function createHistory(ampdoc) { - const viewer = viewerForDoc(ampdoc); + const viewer = Services.viewerForDoc(ampdoc); let binding; if (viewer.isOvertakeHistory() || getMode(ampdoc.win).test || ampdoc.win.AMP_TEST_IFRAME) { diff --git a/src/service/ie-media-bug.js b/src/service/ie-media-bug.js index d9bb2f632232..2543cb920876 100644 --- a/src/service/ie-media-bug.js +++ b/src/service/ie-media-bug.js @@ -15,7 +15,7 @@ */ import {dev} from '../log'; -import {platformFor} from '../services'; +import {Services} from '../services'; const TAG = 'ie-media-bug'; @@ -31,7 +31,7 @@ const TAG = 'ie-media-bug'; * @package */ export function checkAndFix(win, opt_platform) { - const platform = opt_platform || platformFor(win); + const platform = opt_platform || Services.platformFor(win); if (!platform.isIe() || matchMediaIeQuite(win)) { return null; } diff --git a/src/service/ios-scrollfreeze-bug.js b/src/service/ios-scrollfreeze-bug.js index fe698e0f46b2..579c11165dd3 100644 --- a/src/service/ios-scrollfreeze-bug.js +++ b/src/service/ios-scrollfreeze-bug.js @@ -14,9 +14,7 @@ * limitations under the License. */ -import {platformFor} from '../services'; -import {viewerForDoc} from '../services'; -import {vsyncFor} from '../services'; +import {Services} from '../services'; import {setStyle} from '../style'; @@ -42,11 +40,11 @@ export function checkAndFix(ampdoc, opt_platform, opt_viewer, opt_vsync) { /** @const {!Window} */ const win = ampdoc.win; /** @const {!./platform-impl.Platform} */ - const platform = opt_platform || platformFor(win); + const platform = opt_platform || Services.platformFor(win); /** @const {!./viewer-impl.Viewer} */ - const viewer = opt_viewer || viewerForDoc(ampdoc); + const viewer = opt_viewer || Services.viewerForDoc(ampdoc); /** @const {!./vsync-impl.Vsync} */ - const vsync = opt_vsync || vsyncFor(win); + const vsync = opt_vsync || Services.vsyncFor(win); if (!platform.isIos() || !platform.isSafari() || platform.getMajorVersion() > 8 || viewer.getParam('b29185497') != '1') { diff --git a/src/service/jank-meter.js b/src/service/jank-meter.js index d85820b0051a..37114b65e579 100644 --- a/src/service/jank-meter.js +++ b/src/service/jank-meter.js @@ -15,7 +15,7 @@ */ import {isExperimentOn} from '../experiments'; -import {performanceForOrNull} from '../services'; +import {Services} from '../services'; import {dev, user} from '../log'; /** @const {number} */ @@ -40,7 +40,7 @@ export class JankMeter { /** @private {?number} */ this.scheduledTime_ = null; /** @private {?./performance-impl.Performance} */ - this.perf_ = performanceForOrNull(win); + this.perf_ = Services.performanceForOrNull(win); /** @private {?BatteryManager} */ this.batteryManager_ = null; diff --git a/src/service/parallax-impl.js b/src/service/parallax-impl.js index fd2aaacfce08..7036b2c2d670 100644 --- a/src/service/parallax-impl.js +++ b/src/service/parallax-impl.js @@ -20,7 +20,7 @@ import {registerServiceBuilderForDoc} from '../service'; import {setStyles} from '../style'; import {toArray} from '../types'; import {user} from '../log'; -import {viewportForDoc, vsyncFor} from '../services'; +import {Services} from '../services'; const ATTR = 'amp-fx-parallax'; const EXPERIMENT = ATTR; @@ -52,8 +52,8 @@ export class ParallaxService { */ installParallaxHandlers_(global) { const doc = global.document; - const viewport = viewportForDoc(doc); - const vsync = vsyncFor(global); + const viewport = Services.viewportForDoc(doc); + const vsync = Services.vsyncFor(global); const elements = toArray(doc.querySelectorAll(`[${ATTR}]`)); const parallaxElements = elements.map( diff --git a/src/service/performance-impl.js b/src/service/performance-impl.js index b0b8f11f7fc8..a1b8d2fd30a5 100644 --- a/src/service/performance-impl.js +++ b/src/service/performance-impl.js @@ -16,9 +16,7 @@ import {layoutRectLtwh} from '../layout-rect'; import {registerServiceBuilder, getService} from '../service'; -import {resourcesForDoc} from '../services'; -import {viewerForDoc} from '../services'; -import {viewportForDoc} from '../services'; +import {Services} from '../services'; import {whenDocumentComplete} from '../document-ready'; import {getMode} from '../mode'; import {isCanary} from '../experiments'; @@ -119,8 +117,8 @@ export class Performance { * @return {!Promise} */ coreServicesAvailable() { - this.viewer_ = viewerForDoc(this.win.document); - this.resources_ = resourcesForDoc(this.win.document); + this.viewer_ = Services.viewerForDoc(this.win.document); + this.resources_ = Services.resourcesForDoc(this.win.document); this.isPerformanceTrackingOn_ = this.viewer_.isEmbedded() && this.viewer_.getParam('csi') === '1'; @@ -266,7 +264,7 @@ export class Performance { * @private */ whenViewportLayoutComplete_() { - const size = viewportForDoc(this.win.document).getSize(); + const size = Services.viewportForDoc(this.win.document).getSize(); const rect = layoutRectLtwh(0, 0, size.width, size.height); return this.resources_.getResourcesInRect( this.win, rect, /* isInPrerender */ true) diff --git a/src/service/position-observer-impl.js b/src/service/position-observer-impl.js index dea6c3bf0eae..e9f3102ba504 100644 --- a/src/service/position-observer-impl.js +++ b/src/service/position-observer-impl.js @@ -15,7 +15,7 @@ */ import {registerServiceBuilderForDoc} from '../service'; -import {viewportForDoc, vsyncFor} from '../services'; +import {Services} from '../services'; import {getMode} from '../mode'; import {dev} from '../log'; import { @@ -71,10 +71,10 @@ class AbstractPositionObserver { this.entries_ = []; /** @private {!./vsync-impl.Vsync} */ - this.vsync_ = vsyncFor(ampdoc.win); + this.vsync_ = Services.vsyncFor(ampdoc.win); /** @private {!./viewport-impl.Viewport} */ - this.viewport_ = viewportForDoc(ampdoc); + this.viewport_ = Services.viewportForDoc(ampdoc); } diff --git a/src/service/resources-impl.js b/src/service/resources-impl.js index dfcf3209d7a7..b820e52ba6ff 100644 --- a/src/service/resources-impl.js +++ b/src/service/resources-impl.js @@ -19,18 +19,11 @@ import {FiniteStateMachine} from '../finite-state-machine'; import {FocusHistory} from '../focus-history'; import {Pass} from '../pass'; import {Resource, ResourceState} from './resource'; +import {Services} from '../services'; import {TaskQueue} from './task-queue'; import {VisibilityState} from '../visibility-state'; import {checkAndFix as ieMediaCheckAndFix} from './ie-media-bug'; import {closest, hasNextNodeInDocumentOrder} from '../dom'; -import { - documentInfoForDoc, - inputFor, - timerFor, - viewerForDoc, - viewportForDoc, - vsyncFor, -} from '../services'; import {expandLayoutRect} from '../layout-rect'; import {installInputService} from '../input'; import {loadPromise} from '../event-helper'; @@ -92,7 +85,7 @@ export class Resources { this.win = ampdoc.win; /** @const @private {!./viewer-impl.Viewer} */ - this.viewer_ = viewerForDoc(ampdoc); + this.viewer_ = Services.viewerForDoc(ampdoc); /** @private {boolean} */ this.isRuntimeOn_ = this.viewer_.isRuntimeOn(); @@ -191,10 +184,10 @@ export class Resources { this.isCurrentlyBuildingPendingResources_ = false; /** @private @const {!./viewport-impl.Viewport} */ - this.viewport_ = viewportForDoc(this.ampdoc); + this.viewport_ = Services.viewportForDoc(this.ampdoc); /** @private @const {!./vsync-impl.Vsync} */ - this.vsync_ = vsyncFor(this.win); + this.vsync_ = Services.vsyncFor(this.win); /** @private @const {!FocusHistory} */ this.activeHistory_ = new FocusHistory(this.win, FOCUS_HISTORY_TIMEOUT_); @@ -271,7 +264,7 @@ export class Resources { // See https://bugs.webkit.org/show_bug.cgi?id=174031 for more details. Promise.race([ loadPromise(this.win), - timerFor(this.win).promise(3100), + Services.timerFor(this.win).promise(3100), ]).then(remeasure); // Remeasure the document when all fonts loaded. @@ -359,7 +352,7 @@ export class Resources { /** @private */ monitorInput_() { installInputService(this.win); - const input = inputFor(this.win); + const input = Services.inputFor(this.win); input.onTouchDetected(detected => { this.toggleInputClass_('amp-mode-touch', detected); }, true); @@ -1027,7 +1020,7 @@ export class Resources { 'title': doc.title, 'sourceUrl': getSourceUrl(this.ampdoc.getUrl()), 'serverLayout': doc.documentElement.hasAttribute('i-amphtml-element'), - 'linkRels': documentInfoForDoc(this.ampdoc).linkRels, + 'linkRels': Services.documentInfoForDoc(this.ampdoc).linkRels, }), /* cancelUnsent */true); this.scrollHeight_ = this.viewport_.getScrollHeight(); diff --git a/src/service/standard-actions-impl.js b/src/service/standard-actions-impl.js index 32c7bc83e924..853933ebf127 100644 --- a/src/service/standard-actions-impl.js +++ b/src/service/standard-actions-impl.js @@ -17,15 +17,11 @@ import {ActionTrust} from '../action-trust'; import {OBJECT_STRING_ARGS_KEY} from '../service/action-impl'; import {Layout, getLayoutClass} from '../layout'; -import {actionServiceForDoc, urlReplacementsForDoc} from '../services'; -import {bindForDoc} from '../services'; +import {Services} from '../services'; import {computedStyle, getStyle, toggle} from '../style'; import {dev, user} from '../log'; -import {historyForDoc} from '../services'; import {isProtocolValid} from '../url'; import {registerServiceBuilderForDoc} from '../service'; -import {resourcesForDoc} from '../services'; -import {vsyncFor} from '../services'; /** * @param {!Element} element @@ -54,20 +50,20 @@ export class StandardActions { this.ampdoc = ampdoc; /** @const @private {!./action-impl.ActionService} */ - this.actions_ = actionServiceForDoc(ampdoc); + this.actions_ = Services.actionServiceForDoc(ampdoc); /** @const @private {!./resources-impl.Resources} */ - this.resources_ = resourcesForDoc(ampdoc); + this.resources_ = Services.resourcesForDoc(ampdoc); /** @const @private {!./url-replacements-impl.UrlReplacements} */ - this.urlReplacements_ = urlReplacementsForDoc(ampdoc); + this.urlReplacements_ = Services.urlReplacementsForDoc(ampdoc); this.installActions_(this.actions_); } /** @override */ adoptEmbedWindow(embedWin) { - this.installActions_(actionServiceForDoc(embedWin.document)); + this.installActions_(Services.actionServiceForDoc(embedWin.document)); } /** @@ -115,7 +111,7 @@ export class StandardActions { if (!invocation.satisfiesTrust(ActionTrust.MEDIUM)) { return; } - bindForDoc(invocation.target).then(bind => { + Services.bindForDoc(invocation.target).then(bind => { const args = invocation.args; const objectString = args[OBJECT_STRING_ARGS_KEY]; if (objectString) { @@ -162,7 +158,7 @@ export class StandardActions { if (!invocation.satisfiesTrust(ActionTrust.MEDIUM)) { return; } - historyForDoc(this.ampdoc).goBack(); + Services.historyForDoc(this.ampdoc).goBack(); } /** @@ -213,7 +209,7 @@ export class StandardActions { return; } - vsyncFor(ownerWindow).measure(() => { + Services.vsyncFor(ownerWindow).measure(() => { if (computedStyle(ownerWindow, target).display == 'none' && !isShowable(target)) { diff --git a/src/service/storage-impl.js b/src/service/storage-impl.js index cc5a44071822..ffe4a5d12d8b 100644 --- a/src/service/storage-impl.js +++ b/src/service/storage-impl.js @@ -19,7 +19,7 @@ import {getSourceOrigin} from '../url'; import {dev} from '../log'; import {dict} from '../utils/object'; import {parseJson, recreateNonProtoObject} from '../json'; -import {viewerForDoc} from '../services'; +import {Services} from '../services'; /** @const */ const TAG = 'Storage'; @@ -388,7 +388,7 @@ export function installStorageServiceForDoc(ampdoc) { ampdoc, 'storage', function() { - const viewer = viewerForDoc(ampdoc); + const viewer = Services.viewerForDoc(ampdoc); const overrideStorage = parseInt(viewer.getParam('storage'), 10); const binding = overrideStorage ? new ViewerStorageBinding(viewer) : diff --git a/src/service/url-replacements-impl.js b/src/service/url-replacements-impl.js index 657c192aede5..b00029c80e99 100644 --- a/src/service/url-replacements-impl.js +++ b/src/service/url-replacements-impl.js @@ -14,22 +14,14 @@ * limitations under the License. */ -import {accessServiceForDocOrNull} from '../services'; -import {cidForDoc} from '../services'; -import {variantForOrNull} from '../services'; -import {shareTrackingForOrNull} from '../services'; +import {Services} from '../services'; import {dev, user, rethrowAsync} from '../log'; -import {documentInfoForDoc} from '../services'; import { installServiceInEmbedScope, registerServiceBuilderForDoc, } from '../service'; import {parseUrl, removeFragment, parseQueryString, addParamsToUrl} from '../url'; -import {viewerForDoc} from '../services'; -import {viewportForDoc} from '../services'; -import {userNotificationManagerFor} from '../services'; -import {activityForDoc} from '../services'; import {getTrackImpressionPromise} from '../impression.js'; import { VariableSource, @@ -77,7 +69,7 @@ export class GlobalVariableSource extends VariableSource { * @const {function(!./ampdoc-impl.AmpDoc): * !Promise} */ - this.getAccessService_ = accessServiceForDocOrNull; + this.getAccessService_ = Services.accessServiceForDocOrNull; /** @private {?Promise>} */ this.variants_ = null; @@ -107,7 +99,7 @@ export class GlobalVariableSource extends VariableSource { initialize() { /** @const {!./viewport-impl.Viewport} */ - const viewport = viewportForDoc(this.ampdoc); + const viewport = Services.viewportForDoc(this.ampdoc); // Returns a random value for cache busters. this.set('RANDOM', () => { @@ -151,7 +143,7 @@ export class GlobalVariableSource extends VariableSource { // Returns the referrer URL. this.setAsync('DOCUMENT_REFERRER', /** @type {AsyncResolverDef} */(() => { - return viewerForDoc(this.ampdoc).getReferrerUrl(); + return Services.viewerForDoc(this.ampdoc).getReferrerUrl(); })); // Returns the title of this AMP document. @@ -239,12 +231,12 @@ export class GlobalVariableSource extends VariableSource { // If no `opt_userNotificationId` argument is provided then // assume consent is given by default. if (opt_userNotificationId) { - consent = userNotificationManagerFor(this.ampdoc.win) + consent = Services.userNotificationManagerFor(this.ampdoc.win) .then(service => { return service.get(opt_userNotificationId); }); } - return cidForDoc(this.ampdoc).then(cid => { + return Services.cidForDoc(this.ampdoc).then(cid => { return cid.get({ scope: dev().assertString(scope), createCookieIfNotPresent: true, @@ -419,14 +411,15 @@ export class GlobalVariableSource extends VariableSource { // Returns an identifier for the viewer. this.setAsync('VIEWER', () => { - return viewerForDoc(this.ampdoc).getViewerOrigin().then(viewer => { - return viewer == undefined ? '' : 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 activityForDoc(this.ampdoc).then(activity => { + return Services.activityForDoc(this.ampdoc).then(activity => { return activity.getTotalEngagedTime(); }); }); @@ -460,7 +453,7 @@ export class GlobalVariableSource extends VariableSource { this.set('AMP_VERSION', () => '$internalRuntimeVersion$'); this.set('BACKGROUND_STATE', () => { - return viewerForDoc(this.ampdoc).isVisible() ? '0' : '1'; + return Services.viewerForDoc(this.ampdoc).isVisible() ? '0' : '1'; }); } @@ -471,7 +464,7 @@ export class GlobalVariableSource extends VariableSource { * @template T */ getDocInfoValue_(getter) { - return getter(documentInfoForDoc(this.ampdoc)); + return getter(Services.documentInfoForDoc(this.ampdoc)); } /** @@ -523,7 +516,7 @@ export class GlobalVariableSource extends VariableSource { */ getVairiantsValue_(getter, expr) { if (!this.variants_) { - this.variants_ = variantForOrNull(this.ampdoc.win); + this.variants_ = Services.variantForOrNull(this.ampdoc.win); } return this.variants_.then(variants => { user().assert(variants, @@ -543,7 +536,8 @@ export class GlobalVariableSource extends VariableSource { */ getShareTrackingValue_(getter, expr) { if (!this.shareTrackingFragments_) { - this.shareTrackingFragments_ = shareTrackingForOrNull(this.ampdoc.win); + this.shareTrackingFragments_ = + Services.shareTrackingForOrNull(this.ampdoc.win); } return this.shareTrackingFragments_.then(fragments => { user().assert(fragments, 'To use variable %s, ' + @@ -752,7 +746,7 @@ export class UrlReplacements { * @return {boolean} */ isAllowedOrigin_(url) { - const docInfo = documentInfoForDoc(this.ampdoc); + const docInfo = Services.documentInfoForDoc(this.ampdoc); if (url.origin == parseUrl(docInfo.canonicalUrl).origin || url.origin == parseUrl(docInfo.sourceUrl).origin) { diff --git a/src/service/video-manager-impl.js b/src/service/video-manager-impl.js index 99347f2f5ae8..eae62bafcbf1 100644 --- a/src/service/video-manager-impl.js +++ b/src/service/video-manager-impl.js @@ -30,12 +30,7 @@ import { VideoAttributes, VideoEvents, } from '../video-interface'; -import { - viewerForDoc, - viewportForDoc, - vsyncFor, - platformFor, -} from '../services'; +import {Services} from '../services'; import { installPositionObserverServiceForDoc, PositionObserverFidelity, @@ -175,7 +170,7 @@ export class VideoManager { this.entries_[i].updateVisibility(); } }; - const viewport = viewportForDoc(this.ampdoc_); + const viewport = Services.viewportForDoc(this.ampdoc_); viewport.onScroll(scrollListener); viewport.onChanged(scrollListener); this.scrollListenerInstalled_ = true; @@ -282,7 +277,7 @@ class VideoEntry { this.isVisible_ = false; /** @private @const {!../service/vsync-impl.Vsync} */ - this.vsync_ = vsyncFor(ampdoc.win); + this.vsync_ = Services.vsyncFor(ampdoc.win); /** @private @const */ this.actionSessionManager_ = new VideoSessionManager(); @@ -437,7 +432,7 @@ class VideoEntry { * @private */ loadedVideoVisibilityChanged_() { - if (!viewerForDoc(this.ampdoc_).isVisible()) { + if (!Services.viewerForDoc(this.ampdoc_).isVisible()) { return; } @@ -817,7 +812,7 @@ class VideoEntry { } anim.appendChild(column); } - const platform = platformFor(this.ampdoc_.win); + const platform = Services.platformFor(this.ampdoc_.win); if (platform.isIos()) { // iOS can not pause hardware accelerated animations. anim.setAttribute('unpausable', ''); diff --git a/src/service/viewer-impl.js b/src/service/viewer-impl.js index ea58717d3a19..34a84df1f9c3 100644 --- a/src/service/viewer-impl.js +++ b/src/service/viewer-impl.js @@ -17,7 +17,7 @@ import {Observable} from '../observable'; import {findIndex} from '../utils/array'; import {dict, map} from '../utils/object'; -import {documentStateFor, timerFor} from '../services'; +import {Services} from '../services'; import {registerServiceBuilderForDoc} from '../service'; import {dev, duplicateErrorIfNecessary} from '../log'; import {isIframed} from '../dom'; @@ -94,7 +94,7 @@ export class Viewer { this.isIframed_ = isIframed(this.win); /** @const {!./document-state.DocumentState} */ - this.docState_ = documentStateFor(this.win); + this.docState_ = Services.documentStateFor(this.win); /** @private {boolean} */ this.isRuntimeOn_ = true; @@ -246,7 +246,7 @@ export class Viewer { * @private @const {?Promise} */ this.messagingReadyPromise_ = this.isEmbedded_ ? - timerFor(this.win).timeoutPromise( + Services.timerFor(this.win).timeoutPromise( 20000, new Promise(resolve => { this.messagingReadyResolver_ = resolve; @@ -305,7 +305,8 @@ export class Viewer { resolve(this.win.location.ancestorOrigins[0]); } else { // Race to resolve with a timer. - timerFor(this.win).delay(() => resolve(''), VIEWER_ORIGIN_TIMEOUT_); + Services.timerFor(this.win).delay( + () => resolve(''), VIEWER_ORIGIN_TIMEOUT_); this.viewerOriginResolver_ = resolve; } }); diff --git a/src/service/viewport-impl.js b/src/service/viewport-impl.js index 079d64ac1231..67758f905ecb 100644 --- a/src/service/viewport-impl.js +++ b/src/service/viewport-impl.js @@ -31,11 +31,8 @@ import {getFriendlyIframeEmbedOptional} from '../friendly-iframe-embed'; import {isExperimentOn} from '../experiments'; import {numeric} from '../transition'; import {onDocumentReady, whenDocumentReady} from '../document-ready'; -import {platformFor} from '../services'; +import {Services} from '../services'; import {px, setStyle, setStyles, computedStyle} from '../style'; -import {timerFor} from '../services'; -import {vsyncFor} from '../services'; -import {viewerForDoc} from '../services'; import {waitForBody, isIframed} from '../dom'; import {getMode} from '../mode'; @@ -126,10 +123,10 @@ export class Viewport { this.lastPaddingTop_ = 0; /** @private {!./timer-impl.Timer} */ - this.timer_ = timerFor(this.ampdoc.win); + this.timer_ = Services.timerFor(this.ampdoc.win); /** @private {!./vsync-impl.Vsync} */ - this.vsync_ = vsyncFor(this.ampdoc.win); + this.vsync_ = Services.vsyncFor(this.ampdoc.win); /** @private {boolean} */ this.scrollTracking_ = false; @@ -1076,7 +1073,7 @@ export class ViewportBindingNatural_ { this.win = ampdoc.win; /** @const {!../service/platform-impl.Platform} */ - this.platform_ = platformFor(this.win); + this.platform_ = Services.platformFor(this.win); /** @private @const {!./viewer-impl.Viewer} */ this.viewer_ = viewer; @@ -1475,7 +1472,7 @@ export class ViewportBindingNaturalIosEmbed_ { // implementation. return new Promise(resolve => { onDocumentReady(this.win.document, doc => { - vsyncFor(this.win).mutatePromise(() => { + Services.vsyncFor(this.win).mutatePromise(() => { setStyle(doc.body, 'borderTopStyle', lightboxMode ? 'none' : 'solid'); }).then(resolve); }); @@ -1941,13 +1938,13 @@ export function updateViewportMetaString(currentValue, updateParams) { * @private */ function createViewport(ampdoc) { - const viewer = viewerForDoc(ampdoc); + const viewer = Services.viewerForDoc(ampdoc); let binding; if (ampdoc.isSingleDoc() && getViewportType(ampdoc.win, viewer) == ViewportType.NATURAL_IOS_EMBED) { // The overriding of document.body fails in iOS7. // Also, iOS8 sometimes freezes scrolling. - if (platformFor(ampdoc.win).getIosMajorVersion() > 8) { + if (Services.platformFor(ampdoc.win).getIosMajorVersion() > 8) { binding = new ViewportBindingIosEmbedWrapper_(ampdoc.win); } else { binding = new ViewportBindingNaturalIosEmbed_(ampdoc.win, ampdoc); @@ -1987,7 +1984,8 @@ const ViewportType = { */ function getViewportType(win, viewer) { const viewportType = viewer.getParam('viewportType') || ViewportType.NATURAL; - if (!platformFor(win).isIos() || viewportType != ViewportType.NATURAL) { + if (!Services.platformFor(win).isIos() || + viewportType != ViewportType.NATURAL) { return viewportType; } // Enable iOS Embedded mode so that it's easy to test against a more diff --git a/src/service/vsync-impl.js b/src/service/vsync-impl.js index bd2cf9af8852..856df2b2fb0c 100644 --- a/src/service/vsync-impl.js +++ b/src/service/vsync-impl.js @@ -15,12 +15,7 @@ */ import {Pass} from '../pass'; -import { - ampdocServiceFor, - documentStateFor, - viewerForDoc, - viewerPromiseForDoc, -} from '../services'; +import {Services} from '../services'; import {cancellation} from '../error'; import {dev, rethrowAsync} from '../log'; import {registerServiceBuilder, getService} from '../service'; @@ -63,10 +58,10 @@ export class Vsync { this.win = win; /** @private @const {!./ampdoc-impl.AmpDocService} */ - this.ampdocService_ = ampdocServiceFor(this.win); + this.ampdocService_ = Services.ampdocServiceFor(this.win); /** @private @const {!./document-state.DocumentState} */ - this.docState_ = documentStateFor(this.win); + this.docState_ = Services.documentStateFor(this.win); /** @private @const {function(function())} */ this.raf_ = this.getRaf_(); @@ -141,10 +136,11 @@ export class Vsync { if (this.ampdocService_.isSingleDoc()) { // In a single-doc mode, the visibility of the doc == global visibility. // Thus, it's more efficient to only listen to it once. - viewerPromiseForDoc(this.ampdocService_.getAmpDoc()).then(viewer => { - this.singleDocViewer_ = viewer; - viewer.onVisibilityChanged(boundOnVisibilityChanged); - }); + Services.viewerPromiseForDoc(this.ampdocService_.getAmpDoc()) + .then(viewer => { + this.singleDocViewer_ = viewer; + viewer.onVisibilityChanged(boundOnVisibilityChanged); + }); } else { // In multi-doc mode, we track separately the global visibility and // per-doc visibility when necessary. @@ -285,7 +281,7 @@ export class Vsync { // Multi-doc: animations depend on the state of the relevant doc. if (opt_contextNode) { const ampdoc = this.ampdocService_.getAmpDoc(opt_contextNode); - return viewerForDoc(ampdoc).isVisible(); + return Services.viewerForDoc(ampdoc).isVisible(); } return true; diff --git a/src/service/xhr-impl.js b/src/service/xhr-impl.js index 8c5679e4c1c0..4656d7fdaf25 100644 --- a/src/service/xhr-impl.js +++ b/src/service/xhr-impl.js @@ -14,7 +14,7 @@ * limitations under the License. */ -import {ampdocServiceFor, viewerForDoc} from '../services'; +import {Services} from '../services'; import {dev, user} from '../log'; import {registerServiceBuilder, getService} from '../service'; import { @@ -93,7 +93,7 @@ export class Xhr { /** @private {?./ampdoc-impl.AmpDoc} */ this.ampdocSingle_ = null; if (!getMode().test) { - const ampdocService = ampdocServiceFor(win); + const ampdocService = Services.ampdocServiceFor(win); this.ampdocSingle_ = ampdocService.isSingleDoc() ? ampdocService.getAmpDoc() : null; @@ -113,7 +113,7 @@ export class Xhr { if (this.ampdocSingle_ && Math.random() < 0.01 && parseUrl(input).origin != this.win.location.origin && - !viewerForDoc(this.ampdocSingle_).hasBeenVisible()) { + !Services.viewerForDoc(this.ampdocSingle_).hasBeenVisible()) { dev().error('XHR', 'attempted to fetch %s before viewer was visible', input); } diff --git a/src/services.js b/src/services.js index f22c08ac748f..b786f0d5664e 100644 --- a/src/services.js +++ b/src/services.js @@ -30,335 +30,336 @@ import { getElementServiceIfAvailableForDoc, } from './element-service'; +export class Services { + /** + * Returns a promise for the Access service. + * @param {!Node|!./service/ampdoc-impl.AmpDoc} nodeOrDoc + * @return {!Promise} + */ + static accessServiceForDoc(nodeOrDoc) { + return (/** @type {!Promise< + !../extensions/amp-access/0.1/amp-access.AccessService>} */ ( + getElementServiceForDoc(nodeOrDoc, 'access', 'amp-access'))); + } -/** - * Returns a promise for the Access service. - * @param {!Node|!./service/ampdoc-impl.AmpDoc} nodeOrDoc - * @return {!Promise} - */ -export function accessServiceForDoc(nodeOrDoc) { - return (/** @type {!Promise< - !../extensions/amp-access/0.1/amp-access.AccessService>} */ ( - getElementServiceForDoc(nodeOrDoc, 'access', 'amp-access'))); -} - -/** - * Returns a promise for the Access service or a promise for null if the service - * is not available on the current page. - * @param {!Node|!./service/ampdoc-impl.AmpDoc} nodeOrDoc - * @return {!Promise} - */ -export function accessServiceForDocOrNull(nodeOrDoc) { - return (/** @type { - !Promise} */ ( - getElementServiceIfAvailableForDoc(nodeOrDoc, 'access', 'amp-access'))); -} - -/** - * @param {!Node|!./service/ampdoc-impl.AmpDoc} nodeOrDoc - * @return {!./service/action-impl.ActionService} - */ -export function actionServiceForDoc(nodeOrDoc) { - return /** @type {!./service/action-impl.ActionService} */ ( - getExistingServiceForDocInEmbedScope( - nodeOrDoc, 'action', /* opt_fallbackToTopWin */ true)); -} + /** + * Returns a promise for the Access service or a promise for null if the service + * is not available on the current page. + * @param {!Node|!./service/ampdoc-impl.AmpDoc} nodeOrDoc + * @return {!Promise} + */ + static accessServiceForDocOrNull(nodeOrDoc) { + return (/** @type { + !Promise} */ ( + getElementServiceIfAvailableForDoc(nodeOrDoc, 'access', 'amp-access'))); + } -/** - * @param {!Node|!./service/ampdoc-impl.AmpDoc} nodeOrDoc - * @return {!Promise} - */ -export function activityForDoc(nodeOrDoc) { - return /** @type {!Promise} */ ( - getElementServiceForDoc(nodeOrDoc, 'activity', 'amp-analytics')); -} + /** + * @param {!Node|!./service/ampdoc-impl.AmpDoc} nodeOrDoc + * @return {!./service/action-impl.ActionService} + */ + static actionServiceForDoc(nodeOrDoc) { + return /** @type {!./service/action-impl.ActionService} */ ( + getExistingServiceForDocInEmbedScope( + nodeOrDoc, 'action', /* opt_fallbackToTopWin */ true)); + } -/** - * Returns the global instance of the `AmpDocService` service that can be - * used to resolve an ampdoc for any node: either in the single-doc or - * shadow-doc environment. - * @param {!Window} window - * @return {!./service/ampdoc-impl.AmpDocService} - */ -export function ampdocServiceFor(window) { - return /** @type {!./service/ampdoc-impl.AmpDocService} */ ( - getService(window, 'ampdoc')); -} + /** + * @param {!Node|!./service/ampdoc-impl.AmpDoc} nodeOrDoc + * @return {!Promise} + */ + static activityForDoc(nodeOrDoc) { + return /** @type {!Promise} */ ( + getElementServiceForDoc(nodeOrDoc, 'activity', 'amp-analytics')); + } -/** - * @param {!Window} window - * @return {!./service/batched-xhr-impl.BatchedXhr} - */ -export function batchedXhrFor(window) { - return /** @type {!./service/batched-xhr-impl.BatchedXhr} */ ( - getService(window, 'batched-xhr')); -} + /** + * Returns the global instance of the `AmpDocService` service that can be + * used to resolve an ampdoc for any node: either in the single-doc or + * shadow-doc environment. + * @param {!Window} window + * @return {!./service/ampdoc-impl.AmpDocService} + */ + static ampdocServiceFor(window) { + return /** @type {!./service/ampdoc-impl.AmpDocService} */ ( + getService(window, 'ampdoc')); + } -/** - * @param {!Node|!./service/ampdoc-impl.AmpDoc} nodeOrDoc - * @return {!Promise} - */ -export function bindForDoc(nodeOrDoc) { - return /** @type {!Promise} */ ( - getElementServiceForDocInEmbedScope(nodeOrDoc, 'bind', 'amp-bind')); -} + /** + * @param {!Node|!./service/ampdoc-impl.AmpDoc} nodeOrDoc + * @param {boolean=} loadAnalytics + * @return {!Promise} + */ + static analyticsForDoc(nodeOrDoc, loadAnalytics = false) { + if (loadAnalytics) { + // Get Extensions service and force load analytics extension. + const ampdoc = getAmpdoc(nodeOrDoc); + Services.extensionsFor(ampdoc.win)./*OK*/loadExtension('amp-analytics'); + } + return (/** @type {!Promise< + !../extensions/amp-analytics/0.1/instrumentation.InstrumentationService + >} */ (getElementServiceForDoc( + nodeOrDoc, 'amp-analytics-instrumentation', 'amp-analytics'))); + } -/** - * @param {!Node|!./service/ampdoc-impl.AmpDoc} nodeOrDoc - * @return {!Promise} - */ -export function cidForDoc(nodeOrDoc) { - return /** @type {!Promise} */ ( // eslint-disable-line max-len - getServicePromiseForDoc(nodeOrDoc, 'cid')); -} + /** + * @param {!Node|!./service/ampdoc-impl.AmpDoc} nodeOrDoc + * @return {!Promise} + */ + static analyticsForDocOrNull(nodeOrDoc) { + return (/** @type {!Promise< + ?../extensions/amp-analytics/0.1/instrumentation.InstrumentationService + >} */ (getElementServiceIfAvailableForDoc( + nodeOrDoc, 'amp-analytics-instrumentation', 'amp-analytics'))); + } -/** - * @param {!Window} window - * @return {!./service/crypto-impl.Crypto} - */ -export function cryptoFor(window) { - return (/** @type {!./service/crypto-impl.Crypto} */ ( - getService(window, 'crypto'))); -} + /** + * @param {!Window} window + * @return {!./service/batched-xhr-impl.BatchedXhr} + */ + static batchedXhrFor(window) { + return /** @type {!./service/batched-xhr-impl.BatchedXhr} */ ( + getService(window, 'batched-xhr')); + } -/** - * @param {!Node|!./service/ampdoc-impl.AmpDoc} nodeOrDoc - * @return {!./service/document-info-impl.DocumentInfoDef} Info about the doc - */ -export function documentInfoForDoc(nodeOrDoc) { - return /** @type {!./service/document-info-impl.DocInfo} */ ( - getServiceForDoc(nodeOrDoc, 'documentInfo')).get(); -} + /** + * @param {!Node|!./service/ampdoc-impl.AmpDoc} nodeOrDoc + * @return {!Promise} + */ + static bindForDoc(nodeOrDoc) { + return /** @type {!Promise} */ ( + getElementServiceForDocInEmbedScope(nodeOrDoc, 'bind', 'amp-bind')); + } -/** - * @param {!Window} window - * @return {!./service/document-state.DocumentState} - */ -export function documentStateFor(window) { - return getService(window, 'documentState'); -} + /** + * @param {!Node|!./service/ampdoc-impl.AmpDoc} nodeOrDoc + * @return {!Promise} + */ + static cidForDoc(nodeOrDoc) { + return /** @type {!Promise} */ ( + getServicePromiseForDoc(nodeOrDoc, 'cid')); + } -/** - * @param {!Window} window - * @return {!./service/extensions-impl.Extensions} - */ -export function extensionsFor(window) { - return /** @type {!./service/extensions-impl.Extensions} */ ( - getService(window, 'extensions')); -} + /** + * @param {!Window} window + * @return {!./service/crypto-impl.Crypto} + */ + static cryptoFor(window) { + return (/** @type {!./service/crypto-impl.Crypto} */ ( + getService(window, 'crypto'))); + } -/** - * Returns service implemented in service/history-impl. - * @param {!Node|!./service/ampdoc-impl.AmpDoc} nodeOrDoc - * @return {!./service/history-impl.History} - */ -export function historyForDoc(nodeOrDoc) { - return /** @type {!./service/history-impl.History} */ ( - getServiceForDoc(nodeOrDoc, 'history')); -} + /** + * @param {!Node|!./service/ampdoc-impl.AmpDoc} nodeOrDoc + * @return {!./service/document-info-impl.DocumentInfoDef} Info about the doc + */ + static documentInfoForDoc(nodeOrDoc) { + return /** @type {!./service/document-info-impl.DocInfo} */ ( + getServiceForDoc(nodeOrDoc, 'documentInfo')).get(); + } -/** - * @param {!Window} win - * @return {!./input.Input} - */ -export function inputFor(win) { - return getService(win, 'input'); -}; + /** + * @param {!Window} window + * @return {!./service/document-state.DocumentState} + */ + static documentStateFor(window) { + return getService(window, 'documentState'); + } -/** - * @param {!Node|!./service/ampdoc-impl.AmpDoc} nodeOrDoc - * @return {!./service/parallax-impl.ParallaxService} - */ -export function parallaxForDoc(nodeOrDoc) { - return /** @type {!./service/parallax-impl.ParallaxService} */ ( - getServiceForDoc(nodeOrDoc, 'amp-fx-parallax')); -} + /** + * @param {!Window} window + * @return {!./service/extensions-impl.Extensions} + */ + static extensionsFor(window) { + return /** @type {!./service/extensions-impl.Extensions} */ ( + getService(window, 'extensions')); + } -/** - * @param {!Window} window - * @return {!./service/performance-impl.Performance} - */ -export function performanceFor(window) { - return /** @type {!./service/performance-impl.Performance}*/ ( - getService(window, 'performance')); -} + /** + * Returns service implemented in service/history-impl. + * @param {!Node|!./service/ampdoc-impl.AmpDoc} nodeOrDoc + * @return {!./service/history-impl.History} + */ + static historyForDoc(nodeOrDoc) { + return /** @type {!./service/history-impl.History} */ ( + getServiceForDoc(nodeOrDoc, 'history')); + } -/** - * @param {!Window} window - * @return {!./service/performance-impl.Performance} - */ -export function performanceForOrNull(window) { - return /** @type {!./service/performance-impl.Performance}*/ ( - getExistingServiceOrNull(window, 'performance')); -} + /** + * @param {!Window} win + * @return {!./input.Input} + */ + static inputFor(win) { + return getService(win, 'input'); + }; + + /** + * @param {!Node|!./service/ampdoc-impl.AmpDoc} nodeOrDoc + * @return {!./service/parallax-impl.ParallaxService} + */ + static parallaxForDoc(nodeOrDoc) { + return /** @type {!./service/parallax-impl.ParallaxService} */ ( + getServiceForDoc(nodeOrDoc, 'amp-fx-parallax')); + } -/** - * @param {!Window} window - * @return {!./service/platform-impl.Platform} - */ -export function platformFor(window) { - return /** @type {!./service/platform-impl.Platform} */ ( - getService(window, 'platform')); -} + /** + * @param {!Window} window + * @return {!./service/performance-impl.Performance} + */ + static performanceFor(window) { + return /** @type {!./service/performance-impl.Performance}*/ ( + getService(window, 'performance')); + } -/** - * @param {!Node|!./service/ampdoc-impl.AmpDoc} nodeOrDoc - * @return {!./service/resources-impl.Resources} - */ -export function resourcesForDoc(nodeOrDoc) { - return /** @type {!./service/resources-impl.Resources} */ ( - getServiceForDoc(nodeOrDoc, 'resources')); -} + /** + * @param {!Window} window + * @return {!./service/performance-impl.Performance} + */ + static performanceForOrNull(window) { + return /** @type {!./service/performance-impl.Performance}*/ ( + getExistingServiceOrNull(window, 'performance')); + } -/** - * @param {!Window} win - * @return {?Promise} - */ -export function shareTrackingForOrNull(win) { - return (/** @type { - !Promise} */ ( - getElementServiceIfAvailable(win, 'share-tracking', 'amp-share-tracking', - true))); -} + /** + * @param {!Window} window + * @return {!./service/platform-impl.Platform} + */ + static platformFor(window) { + return /** @type {!./service/platform-impl.Platform} */ ( + getService(window, 'platform')); + } -/** - * @param {!Node|!./service/ampdoc-impl.AmpDoc} nodeOrDoc - * @return {!Promise} - */ -export function storageForDoc(nodeOrDoc) { - return /** @type {!Promise} */ ( - getServicePromiseForDoc(nodeOrDoc, 'storage')); -} + /** + * @param {!Node|!./service/ampdoc-impl.AmpDoc} nodeOrDoc + * @return {!./service/resources-impl.Resources} + */ + static resourcesForDoc(nodeOrDoc) { + return /** @type {!./service/resources-impl.Resources} */ ( + getServiceForDoc(nodeOrDoc, 'resources')); + } -/** - * @param {!Window} window - * @return {!./service/template-impl.Templates} - */ -export function templatesFor(window) { - return /** @type {!./service/template-impl.Templates} */ ( - getService(window, 'templates')); -} + /** + * @param {!Window} win + * @return {?Promise} + */ + static shareTrackingForOrNull(win) { + return (/** @type { + !Promise} */ ( + getElementServiceIfAvailable(win, 'share-tracking', 'amp-share-tracking', + true))); + } -/** - * @param {!Window} window - * @return {!./service/timer-impl.Timer} - */ -export function timerFor(window) { - return /** @type {!./service/timer-impl.Timer} */ ( - getService(window, 'timer')); -} + /** + * @param {!Node|!./service/ampdoc-impl.AmpDoc} nodeOrDoc + * @return {!Promise} + */ + static storageForDoc(nodeOrDoc) { + return /** @type {!Promise} */ ( + getServicePromiseForDoc(nodeOrDoc, 'storage')); + } -/** - * @param {!Node|!./service/ampdoc-impl.AmpDoc} nodeOrDoc - * @return {!./service/url-replacements-impl.UrlReplacements} - */ -export function urlReplacementsForDoc(nodeOrDoc) { - return /** @type {!./service/url-replacements-impl.UrlReplacements} */ ( - getExistingServiceForDocInEmbedScope( - nodeOrDoc, 'url-replace', /* opt_fallbackToTopWin */ true)); -} + /** + * @param {!Window} window + * @return {!./service/template-impl.Templates} + */ + static templatesFor(window) { + return /** @type {!./service/template-impl.Templates} */ ( + getService(window, 'templates')); + } -/** - * @param {!Window} window - * @return {!Promise} - */ -export function userNotificationManagerFor(window) { - return (/** @type {!Promise} */ - (getElementService(window, 'userNotificationManager', - 'amp-user-notification'))); -} + /** + * @param {!Window} window + * @return {!./service/timer-impl.Timer} + */ + static timerFor(window) { + return /** @type {!./service/timer-impl.Timer} */ ( + getService(window, 'timer')); + } -/** - * Returns a promise for the experiment variants or a promise for null if it is - * not available on the current page. - * @param {!Window} win - * @return {!Promise>} - */ -export function variantForOrNull(win) { - return /** @type {!Promise>} */ ( - getElementServiceIfAvailable(win, 'variant', 'amp-experiment', true)); -} + /** + * @param {!Node|!./service/ampdoc-impl.AmpDoc} nodeOrDoc + * @return {!./service/url-replacements-impl.UrlReplacements} + */ + static urlReplacementsForDoc(nodeOrDoc) { + return /** @type {!./service/url-replacements-impl.UrlReplacements} */ ( + getExistingServiceForDocInEmbedScope( + nodeOrDoc, 'url-replace', /* opt_fallbackToTopWin */ true)); + } -/** - * @param {!Node|!./service/ampdoc-impl.AmpDoc} nodeOrDoc - * @return {!./service/video-manager-impl.VideoManager} - */ -export function videoManagerForDoc(nodeOrDoc) { - return /** @type {!./service/video-manager-impl.VideoManager} */ ( - getServiceForDoc(nodeOrDoc, 'video-manager')); -} + /** + * @param {!Window} window + * @return {!Promise} + */ + static userNotificationManagerFor(window) { + return (/** @type {!Promise} */ + (getElementService(window, 'userNotificationManager', + 'amp-user-notification'))); + } -/** - * @param {!Node|!./service/ampdoc-impl.AmpDoc} nodeOrDoc - * @return {!./service/viewer-impl.Viewer} - */ -export function viewerForDoc(nodeOrDoc) { - return /** @type {!./service/viewer-impl.Viewer} */ ( - getServiceForDoc(nodeOrDoc, 'viewer')); -} + /** + * Returns a promise for the experiment variants or a promise for null if it is + * not available on the current page. + * @param {!Window} win + * @return {!Promise>} + */ + static variantForOrNull(win) { + return /** @type {!Promise>} */ ( + getElementServiceIfAvailable(win, 'variant', 'amp-experiment', true)); + } -/** - * Returns promise for the viewer. This is an unusual case and necessary only - * for services that need reference to the viewer before it has been - * initialized. Most of the code, however, just should use `viewerForDoc`. - * @param {!Node|!./service/ampdoc-impl.AmpDoc} nodeOrDoc - * @return {!Promise} - */ -export function viewerPromiseForDoc(nodeOrDoc) { - return /** @type {!Promise} */ ( - getServicePromiseForDoc(nodeOrDoc, 'viewer')); -} + /** + * @param {!Node|!./service/ampdoc-impl.AmpDoc} nodeOrDoc + * @return {!./service/video-manager-impl.VideoManager} + */ + static videoManagerForDoc(nodeOrDoc) { + return /** @type {!./service/video-manager-impl.VideoManager} */ ( + getServiceForDoc(nodeOrDoc, 'video-manager')); + } -/** - * @param {!Window} window - * @return {!./service/vsync-impl.Vsync} - */ -export function vsyncFor(window) { - return /** @type {!./service/vsync-impl.Vsync} */ ( - getService(window, 'vsync')); -} + /** + * @param {!Node|!./service/ampdoc-impl.AmpDoc} nodeOrDoc + * @return {!./service/viewer-impl.Viewer} + */ + static viewerForDoc(nodeOrDoc) { + return /** @type {!./service/viewer-impl.Viewer} */ ( + getServiceForDoc(nodeOrDoc, 'viewer')); + } -/** - * @param {!Node|!./service/ampdoc-impl.AmpDoc} nodeOrDoc - * @return {!./service/viewport-impl.Viewport} - */ -export function viewportForDoc(nodeOrDoc) { - return /** @type {!./service/viewport-impl.Viewport} */ ( - getServiceForDoc(nodeOrDoc, 'viewport')); -} + /** + * Returns promise for the viewer. This is an unusual case and necessary only + * for services that need reference to the viewer before it has been + * initialized. Most of the code, however, just should use `viewerForDoc`. + * @param {!Node|!./service/ampdoc-impl.AmpDoc} nodeOrDoc + * @return {!Promise} + */ + static viewerPromiseForDoc(nodeOrDoc) { + return /** @type {!Promise} */ ( + getServicePromiseForDoc(nodeOrDoc, 'viewer')); + } -/** - * @param {!Window} window - * @return {!./service/xhr-impl.Xhr} - */ -export function xhrFor(window) { - return /** @type {!./service/xhr-impl.Xhr} */ (getService(window, 'xhr')); -} + /** + * @param {!Window} window + * @return {!./service/vsync-impl.Vsync} + */ + static vsyncFor(window) { + return /** @type {!./service/vsync-impl.Vsync} */ ( + getService(window, 'vsync')); + } -/** - * @param {!Node|!./service/ampdoc-impl.AmpDoc} nodeOrDoc - * @param {boolean=} loadAnalytics - * @return {!Promise} - */ -export function analyticsForDoc(nodeOrDoc, loadAnalytics = false) { - if (loadAnalytics) { - // Get Extensions service and force load analytics extension. - const ampdoc = getAmpdoc(nodeOrDoc); - extensionsFor(ampdoc.win)./*OK*/loadExtension('amp-analytics'); - } - return (/** @type {!Promise< - !../extensions/amp-analytics/0.1/instrumentation.InstrumentationService - >} */ (getElementServiceForDoc( - nodeOrDoc, 'amp-analytics-instrumentation', 'amp-analytics'))); -} + /** + * @param {!Node|!./service/ampdoc-impl.AmpDoc} nodeOrDoc + * @return {!./service/viewport-impl.Viewport} + */ + static viewportForDoc(nodeOrDoc) { + return /** @type {!./service/viewport-impl.Viewport} */ ( + getServiceForDoc(nodeOrDoc, 'viewport')); + } -/** - * @param {!Node|!./service/ampdoc-impl.AmpDoc} nodeOrDoc - * @return {!Promise} - */ -export function analyticsForDocOrNull(nodeOrDoc) { - return (/** @type {!Promise< - ?../extensions/amp-analytics/0.1/instrumentation.InstrumentationService - >} */ (getElementServiceIfAvailableForDoc( - nodeOrDoc, 'amp-analytics-instrumentation', 'amp-analytics'))); + /** + * @param {!Window} window + * @return {!./service/xhr-impl.Xhr} + */ + static xhrFor(window) { + return /** @type {!./service/xhr-impl.Xhr} */ (getService(window, 'xhr')); + } } diff --git a/src/shadow-embed.js b/src/shadow-embed.js index bb8a1dd89771..1ca4120be56f 100644 --- a/src/shadow-embed.js +++ b/src/shadow-embed.js @@ -14,13 +14,8 @@ * limitations under the License. */ +import {Services} from './services'; import {ShadowCSS} from '../third_party/webcomponentsjs/ShadowCSS'; -import { - ampdocServiceFor, - extensionsFor, - platformFor, - vsyncFor, -} from './services'; import {dev} from './log'; import {closestNode, escapeCssSelectorIdent} from './dom'; import {insertStyleElement} from './style-installer'; @@ -174,8 +169,8 @@ export function createShadowEmbedRoot(hostElement, extensionIds) { const win = hostElement.ownerDocument.defaultView; /** @const {!./service/extensions-impl.Extensions} */ - const extensions = extensionsFor(win); - const ampdocService = ampdocServiceFor(win); + const extensions = Services.extensionsFor(win); + const ampdocService = Services.ampdocServiceFor(win); const ampdoc = ampdocService.getAmpDoc(hostElement); // Instal runtime CSS. @@ -408,7 +403,7 @@ function calcShadowDomStreamingSupported(win) { } // Firefox does not support DOM streaming. // See: https://bugzilla.mozilla.org/show_bug.cgi?id=867102 - if (platformFor(win).isFirefox()) { + if (Services.platformFor(win).isFirefox()) { return false; } // Assume full streaming support. @@ -491,7 +486,7 @@ export class ShadowDomWriterStreamer { this.parser_.open(); /** @const @private */ - this.vsync_ = vsyncFor(win); + this.vsync_ = Services.vsyncFor(win); /** @private @const */ this.boundMerge_ = this.merge_.bind(this); @@ -613,7 +608,7 @@ export class ShadowDomWriterBulk { this.fullHtml_ = []; /** @const @private */ - this.vsync_ = vsyncFor(win); + this.vsync_ = Services.vsyncFor(win); /** @private {?function(!Document):!Element} */ this.onBody_ = null; diff --git a/src/style-installer.js b/src/style-installer.js index 91c7967cce46..b8ca2c7d183e 100644 --- a/src/style-installer.js +++ b/src/style-installer.js @@ -15,7 +15,7 @@ */ import {dev, rethrowAsync} from './log'; -import {documentStateFor, performanceFor, resourcesForDoc} from './services'; +import {Services} from './services'; import {setStyles} from './style'; import {waitForServices} from './render-delaying-services'; @@ -143,7 +143,7 @@ export function makeBodyVisible(doc, opt_waitForServices) { renderStartedNoInline(doc); }; try { - documentStateFor(win).onBodyAvailable(() => { + Services.documentStateFor(win).onBodyAvailable(() => { if (win[bodyVisibleSentinel]) { return; } @@ -155,10 +155,11 @@ export function makeBodyVisible(doc, opt_waitForServices) { }).then(services => { set(); if (services.length > 0) { - resourcesForDoc(doc)./*OK*/schedulePass(1, /* relayoutAll */ true); + Services.resourcesForDoc(doc)./*OK*/schedulePass( + 1, /* relayoutAll */ true); } try { - const perf = performanceFor(win); + const perf = Services.performanceFor(win); perf.tick('mbv'); perf.flush(); } catch (e) {} @@ -183,7 +184,7 @@ export function makeBodyVisible(doc, opt_waitForServices) { */ function renderStartedNoInline(doc) { try { - resourcesForDoc(doc).renderStarted(); + Services.resourcesForDoc(doc).renderStarted(); } catch (e) { // `makeBodyVisible` is called in the error-processing cycle and thus // could be triggered when runtime's initialization is incomplete which diff --git a/src/web-worker/amp-worker.js b/src/web-worker/amp-worker.js index 3255007ecff7..4baed5c95e91 100644 --- a/src/web-worker/amp-worker.js +++ b/src/web-worker/amp-worker.js @@ -19,7 +19,7 @@ import {calculateEntryPointScriptUrl} from '../service/extension-location'; import {dev} from '../log'; import {getService, registerServiceBuilder} from '../service'; import {getMode} from '../mode'; -import {xhrFor} from '../services'; +import {Services} from '../services'; const TAG = 'web-worker'; @@ -75,7 +75,7 @@ class AmpWorker { this.win_ = win; /** @const @private {!../service/xhr-impl.Xhr} */ - this.xhr_ = xhrFor(win); + this.xhr_ = Services.xhrFor(win); // Use `testLocation` for testing with iframes. @see testing/iframe.js. let loc = win.location; diff --git a/test/_init_tests.js b/test/_init_tests.js index b3b2604fa81c..51c89f96a86c 100644 --- a/test/_init_tests.js +++ b/test/_init_tests.js @@ -17,7 +17,7 @@ // This must load before all other tests. import '../third_party/babel/custom-babel-helpers'; import '../src/polyfills'; -import {ampdocServiceFor, platformFor, resourcesForDoc} from '../src/services'; +import {Services} from '../src/services'; import {removeElement} from '../src/dom'; import {setReportError} from '../src/log'; import { @@ -99,7 +99,7 @@ class TestConfig { */ this.configTasks = []; - this.platform = platformFor(window); + this.platform = Services.platformFor(window); } skipChrome() { @@ -249,10 +249,10 @@ function beforeTest() { }; window.AMP_TEST = true; installDocService(window, /* isSingleDoc */ true); - const ampdoc = ampdocServiceFor(window).getAmpDoc(); + const ampdoc = Services.ampdocServiceFor(window).getAmpDoc(); installRuntimeServices(window); installAmpdocServices(ampdoc); - resourcesForDoc(ampdoc).ampInitComplete(); + Services.resourcesForDoc(ampdoc).ampInitComplete(); } // Global cleanup of tags added during tests. Cool to add more @@ -260,7 +260,7 @@ function beforeTest() { afterEach(function() { this.timeout(BEFORE_AFTER_TIMEOUT); const cleanupTagNames = ['link', 'meta']; - if (!platformFor(window).isSafari()) { + if (!Services.platformFor(window).isSafari()) { cleanupTagNames.push('iframe'); } const cleanup = document.querySelectorAll(cleanupTagNames.join(',')); diff --git a/test/functional/3p/test-3p-messaging.js b/test/functional/3p/test-3p-messaging.js index 0741becaafa3..48394bc40b40 100644 --- a/test/functional/3p/test-3p-messaging.js +++ b/test/functional/3p/test-3p-messaging.js @@ -17,13 +17,13 @@ import {createIframePromise} from '../../../testing/iframe'; import {listenParent} from '../../../3p/messaging'; import {postMessage} from '../../../src/iframe-helper'; -import {timerFor} from '../../../src/services'; +import {Services} from '../../../src/services'; describe('3p messaging', () => { let testWin; let iframe; - const timer = timerFor(window); + const timer = Services.timerFor(window); beforeEach(() => { return createIframePromise(true).then(i => { diff --git a/test/functional/inabox/test-inabox-viewport.js b/test/functional/inabox/test-inabox-viewport.js index fe64fd257c45..ea46c726c78e 100644 --- a/test/functional/inabox/test-inabox-viewport.js +++ b/test/functional/inabox/test-inabox-viewport.js @@ -15,7 +15,7 @@ */ import {layoutRectLtwh} from '../../../src/layout-rect'; -import {resourcesForDoc} from '../../../src/services'; +import {Services} from '../../../src/services'; import { prepareFixedContainer, resetFixedContainer, @@ -75,7 +75,8 @@ describes.fakeWin('inabox-viewport', {amp: {}}, env => { }, measure: measureSpy, }; - sandbox.stub(resourcesForDoc(win.document), 'get').returns([element]); + sandbox.stub( + Services.resourcesForDoc(win.document), 'get').returns([element]); }); afterEach(() => { diff --git a/test/functional/test-3p-environment.js b/test/functional/test-3p-environment.js index 03e363699159..4031a3facbe4 100644 --- a/test/functional/test-3p-environment.js +++ b/test/functional/test-3p-environment.js @@ -19,7 +19,7 @@ import { setInViewportForTesting, } from '../../3p/environment'; import {createIframePromise} from '../../testing/iframe'; -import {timerFor} from '../../src/services'; +import {Services} from '../../src/services'; import {loadPromise} from '../../src/event-helper'; import * as lolex from 'lolex'; @@ -27,7 +27,7 @@ describe('3p environment', () => { let testWin; let iframeCount; - const timer = timerFor(window); + const timer = Services.timerFor(window); beforeEach(() => { iframeCount = 0; diff --git a/test/functional/test-3p-frame.js b/test/functional/test-3p-frame.js index e2e36cfeb44b..81a8450590c1 100644 --- a/test/functional/test-3p-frame.js +++ b/test/functional/test-3p-frame.js @@ -28,12 +28,11 @@ import { deserializeMessage, } from '../../src/3p-frame-messaging'; import {dev} from '../../src/log'; -import {documentInfoForDoc} from '../../src/services'; +import {Services} from '../../src/services'; import {loadPromise} from '../../src/event-helper'; import {toggleExperiment} from '../../src/experiments'; import {preconnectForElement} from '../../src/preconnect'; import {validateData} from '../../3p/3p'; -import {viewerForDoc} from '../../src/services'; import * as sinon from 'sinon'; describe('3p-frame', () => { @@ -163,7 +162,7 @@ describe('3p-frame', () => { const height = window.innerHeight; setupElementFunctions(div); - const viewer = viewerForDoc(window.document); + const viewer = Services.viewerForDoc(window.document); const viewerMock = sandbox.mock(viewer); viewerMock.expects('getUnconfirmedReferrerUrl') .returns('http://acme.org/') @@ -174,7 +173,7 @@ describe('3p-frame', () => { const src = iframe.src; const locationHref = location.href; expect(locationHref).to.not.be.empty; - const docInfo = documentInfoForDoc(window.document); + const docInfo = Services.documentInfoForDoc(window.document); expect(docInfo.pageViewId).to.not.be.empty; const name = JSON.parse(decodeURIComponent(iframe.name)); const sentinel = name.attributes._context['sentinel']; @@ -362,7 +361,7 @@ describe('3p-frame', () => { }); it('uses a unique name based on domain', () => { - const viewerMock = sandbox.mock(viewerForDoc(window.document)); + const viewerMock = sandbox.mock(Services.viewerForDoc(window.document)); viewerMock.expects('getUnconfirmedReferrerUrl') .returns('http://acme.org/').twice(); diff --git a/test/functional/test-activity.js b/test/functional/test-activity.js index 030f6b3890a0..95b529013ccd 100644 --- a/test/functional/test-activity.js +++ b/test/functional/test-activity.js @@ -18,7 +18,7 @@ import {AmpDocSingle} from '../../src/service/ampdoc-impl'; import { installActivityServiceForTesting, } from '../../extensions/amp-analytics/0.1/activity-impl'; -import {activityForDoc, viewerForDoc, viewportForDoc} from '../../src/services'; +import {Services} from '../../src/services'; import {installDocumentStateService} from '../../src/service/document-state'; import {installPlatformService} from '../../src/service/platform-impl'; import {installViewerServiceForDoc} from '../../src/service/viewer-impl'; @@ -103,7 +103,7 @@ describe('Activity getTotalEngagedTime', () => { installVsyncService(fakeWin); installPlatformService(fakeWin); installViewerServiceForDoc(ampdoc); - viewer = viewerForDoc(ampdoc); + viewer = Services.viewerForDoc(ampdoc); const whenFirstVisiblePromise = new Promise(resolve => { whenFirstVisibleResolve = resolve; @@ -114,7 +114,7 @@ describe('Activity getTotalEngagedTime', () => { }); installViewportServiceForDoc(ampdoc); - viewport = viewportForDoc(ampdoc); + viewport = Services.viewportForDoc(ampdoc); sandbox.stub(viewport, 'onScroll', handler => { scrollObservable.add(handler); @@ -123,7 +123,7 @@ describe('Activity getTotalEngagedTime', () => { markElementScheduledForTesting(fakeWin, 'amp-analytics'); installActivityServiceForTesting(ampdoc); - return activityForDoc(ampdoc).then(a => { + return Services.activityForDoc(ampdoc).then(a => { activity = a; }); }); diff --git a/test/functional/test-ad-cid.js b/test/functional/test-ad-cid.js index 6112197f2ba0..4f6eff6e0c30 100644 --- a/test/functional/test-ad-cid.js +++ b/test/functional/test-ad-cid.js @@ -15,7 +15,7 @@ */ import {adConfig} from '../../ads/_config'; -import {ampdocServiceFor, timerFor} from '../../src/services'; +import {Services} from '../../src/services'; import { cidServiceForDocForTesting, } from '../../src/service/cid-impl'; @@ -43,7 +43,7 @@ describes.realWin('ad-cid', {}, env => { element.setAttribute('type', '_ping_'); installDocService(win, /* isSingleDoc */ true); installTimerService(win); - const ampdoc = ampdocServiceFor(win).getAmpDoc(); + const ampdoc = Services.ampdocServiceFor(win).getAmpDoc(); cidService = cidServiceForDocForTesting(ampdoc); adElement = { getAmpDoc: () => ampdoc, @@ -92,7 +92,7 @@ describes.realWin('ad-cid', {}, env => { it('should return on timeout', () => { config.clientIdScope = cidScope; sandbox.stub(cidService, 'get', () => { - return timerFor(win).promise(2000); + return Services.timerFor(win).promise(2000); }); const p = getAdCid(adElement).then(cid => { expect(cid).to.be.undefined; diff --git a/test/functional/test-amp-img.js b/test/functional/test-amp-img.js index 8245212bf958..4524ccc051c2 100644 --- a/test/functional/test-amp-img.js +++ b/test/functional/test-amp-img.js @@ -17,7 +17,7 @@ import {createIframePromise} from '../../testing/iframe'; import {BaseElement} from '../../src/base-element'; import {installImg, AmpImg} from '../../builtins/amp-img'; -import {resourcesForDoc} from '../../src/services'; +import {Services} from '../../src/services'; import * as sinon from 'sinon'; describe('amp-img', () => { @@ -137,7 +137,7 @@ describe('amp-img', () => { el.setAttribute('src', 'test.jpg'); el.setAttribute('width', 100); el.setAttribute('height', 100); - el.getResources = () => resourcesForDoc(document); + el.getResources = () => Services.resourcesForDoc(document); impl = new AmpImg(el); impl.createdCallback(); sandbox.stub(impl, 'getLayoutWidth').returns(100); diff --git a/test/functional/test-analytics.js b/test/functional/test-analytics.js index 77c574775853..edec71e1984d 100644 --- a/test/functional/test-analytics.js +++ b/test/functional/test-analytics.js @@ -22,7 +22,7 @@ import { import { triggerAnalyticsEvent, } from '../../src/analytics'; -import {timerFor} from '../../src/services'; +import {Services} from '../../src/services'; import * as sinon from 'sinon'; @@ -44,7 +44,7 @@ describes.realWin('analytics', { beforeEach(() => { sandbox = sinon.sandbox.create(); - timer = timerFor(env.win); + timer = Services.timerFor(env.win); ampdoc = env.ampdoc; triggerEventSpy = sandbox.spy(); resetServiceForTesting(window, 'amp-analytics-instrumentation'); diff --git a/test/functional/test-base-element.js b/test/functional/test-base-element.js index 608a827233fb..cf10307c6d44 100644 --- a/test/functional/test-base-element.js +++ b/test/functional/test-base-element.js @@ -19,7 +19,7 @@ import {Resource} from '../../src/service/resource'; import {createAmpElementProto} from '../../src/custom-element'; import {layoutRectLtwh} from '../../src/layout-rect'; import {listenOncePromise} from '../../src/event-helper'; -import {timerFor} from '../../src/services'; +import {Services} from '../../src/services'; import * as sinon from 'sinon'; @@ -174,7 +174,7 @@ describe('BaseElement', () => { let event2Promise; beforeEach(() => { - const timer = timerFor(element.win); + const timer = Services.timerFor(element.win); target = document.createElement('div'); event1 = document.createEvent('Event'); diff --git a/test/functional/test-chunk.js b/test/functional/test-chunk.js index de78af68325d..051fcce175ed 100644 --- a/test/functional/test-chunk.js +++ b/test/functional/test-chunk.js @@ -22,7 +22,7 @@ import { startupChunk, } from '../../src/chunk'; import {installDocService} from '../../src/service/ampdoc-impl'; -import {viewerForDoc, viewerPromiseForDoc} from '../../src/services'; +import {Services} from '../../src/services'; import * as sinon from 'sinon'; @@ -46,7 +46,7 @@ describe('chunk', () => { // If there is a viewer, wait for it, so we run with it being // installed. if (env.win.services.viewer) { - return viewerPromiseForDoc(env.win.document).then(() => { + return Services.viewerPromiseForDoc(env.win.document).then(() => { // Make sure we make a chunk instance, so all runs // have a viewer. chunkInstanceForTesting(env.win.document); @@ -138,7 +138,7 @@ describe('chunk', () => { describe('visible', () => { beforeEach(() => { - const viewer = viewerForDoc(env.win.document); + const viewer = Services.viewerForDoc(env.win.document); env.sandbox.stub(viewer, 'isVisible', () => { return true; }); @@ -158,7 +158,7 @@ describe('chunk', () => { beforeEach(() => { fakeWin = env.win; - const viewer = viewerForDoc(env.win.document); + const viewer = Services.viewerForDoc(env.win.document); env.sandbox.stub(viewer, 'isVisible', () => { return true; }); @@ -181,7 +181,7 @@ describe('chunk', () => { describe('invisible', () => { beforeEach(() => { - const viewer = viewerForDoc(env.win.document); + const viewer = Services.viewerForDoc(env.win.document); env.sandbox.stub(viewer, 'isVisible', () => { return false; }); @@ -200,7 +200,7 @@ describe('chunk', () => { describe('invisible but deactivated', () => { beforeEach(() => { deactivateChunking(); - const viewer = viewerForDoc(env.win.document); + const viewer = Services.viewerForDoc(env.win.document); env.sandbox.stub(viewer, 'isVisible', () => { return false; }); @@ -215,7 +215,7 @@ describe('chunk', () => { describe('invisible via document.hidden', () => { beforeEach(() => { - const viewer = viewerForDoc(env.win.document); + const viewer = Services.viewerForDoc(env.win.document); env.sandbox.stub(viewer, 'isVisible', () => { return false; }); @@ -234,7 +234,7 @@ describe('chunk', () => { describe('invisible to visible', () => { beforeEach(() => { env.win.location.resetHref('test#visibilityState=hidden'); - const viewer = viewerForDoc(env.win.document); + const viewer = Services.viewerForDoc(env.win.document); let visible = false; env.sandbox.stub(viewer, 'isVisible', () => { return visible; @@ -252,7 +252,7 @@ describe('chunk', () => { describe('invisible to visible', () => { beforeEach(() => { env.win.location.resetHref('test#visibilityState=prerender'); - const viewer = viewerForDoc(env.win.document); + const viewer = Services.viewerForDoc(env.win.document); let visible = false; env.sandbox.stub(viewer, 'isVisible', () => { return visible; @@ -270,7 +270,7 @@ describe('chunk', () => { describe('invisible to visible after a while', () => { beforeEach(() => { env.win.location.resetHref('test#visibilityState=hidden'); - const viewer = viewerForDoc(env.win.document); + const viewer = Services.viewerForDoc(env.win.document); let visible = false; env.sandbox.stub(viewer, 'isVisible', () => { return visible; @@ -305,7 +305,7 @@ describe('chunk', () => { beforeEach(() => { env.win.requestIdleCallback = null; expect(env.win.requestIdleCallback).to.be.null; - const viewer = viewerForDoc(env.win.document); + const viewer = Services.viewerForDoc(env.win.document); env.sandbox.stub(viewer, 'isVisible', () => { return false; }); diff --git a/test/functional/test-cid.js b/test/functional/test-cid.js index fcb130801372..f1813b7ace5e 100644 --- a/test/functional/test-cid.js +++ b/test/functional/test-cid.js @@ -14,13 +14,7 @@ * limitations under the License. */ -import { - ampdocServiceFor, - cryptoFor, - extensionsFor, - timerFor, - viewerForDoc, -} from '../../src/services'; +import {Services} from '../../src/services'; import { cidServiceForDocForTesting, getProxySourceOrigin, @@ -67,7 +61,7 @@ describe('cid', () => { let storageGetStub; const hasConsent = Promise.resolve(); - const timer = timerFor(window); + const timer = Services.timerFor(window); beforeEach(() => { let call = 1; @@ -112,12 +106,12 @@ describe('cid', () => { fakeWin.document.defaultView = fakeWin; installDocService(fakeWin, /* isSingleDoc */ true); installDocumentStateService(fakeWin); - ampdoc = ampdocServiceFor(fakeWin).getAmpDoc(); + ampdoc = Services.ampdocServiceFor(fakeWin).getAmpDoc(); installTimerService(fakeWin); installPlatformService(fakeWin); installExtensionsService(fakeWin); - const extensions = extensionsFor(fakeWin); + const extensions = Services.extensionsFor(fakeWin); // stub extensions service to provide crypto-polyfill sandbox.stub(extensions, 'loadExtension', extensionId => { expect(extensionId).to.equal('amp-crypto-polyfill'); @@ -127,7 +121,7 @@ describe('cid', () => { installViewerServiceForDoc(ampdoc); storageGetStub = stubServiceForDoc(sandbox, ampdoc, 'storage', 'get'); - viewer = viewerForDoc(ampdoc); + viewer = Services.viewerForDoc(ampdoc); sandbox.stub(viewer, 'whenFirstVisible', function() { return whenFirstVisible; }); @@ -149,7 +143,7 @@ describe('cid', () => { cid = cidServiceForDocForTesting(ampdoc); installCryptoService(fakeWin); - crypto = cryptoFor(fakeWin); + crypto = Services.cryptoFor(fakeWin); }); afterEach(() => { diff --git a/test/functional/test-crypto.js b/test/functional/test-crypto.js index 704f7a4c258f..5a84e2089c3a 100644 --- a/test/functional/test-crypto.js +++ b/test/functional/test-crypto.js @@ -22,7 +22,7 @@ import { import { installExtensionsService, } from '../../src/service/extensions-impl'; -import {extensionsFor} from '../../src/services'; +import {Services} from '../../src/services'; describes.realWin('crypto-impl', {}, env => { @@ -94,7 +94,7 @@ describes.realWin('crypto-impl', {}, env => { function createCrypto(win) { installExtensionsService(win); - const extensions = extensionsFor(win); + const extensions = Services.extensionsFor(win); sandbox.stub(extensions, 'loadExtension', extensionId => { expect(extensionId).to.equal('amp-crypto-polyfill'); installCryptoPolyfill(win); diff --git a/test/functional/test-custom-element.js b/test/functional/test-custom-element.js index 3718a0752b25..b9aff05f3dd0 100644 --- a/test/functional/test-custom-element.js +++ b/test/functional/test-custom-element.js @@ -23,8 +23,7 @@ import {installDocumentStateService} from '../../src/service/document-state'; import {installResourcesServiceForDoc} from '../../src/service/resources-impl'; import {poll} from '../../testing/iframe'; import {ResourceState} from '../../src/service/resource'; -import {resourcesForDoc} from '../../src/services'; -import {vsyncFor} from '../../src/services'; +import {Services} from '../../src/services'; import { copyElementToChildWindow, createAmpElementProto, @@ -151,7 +150,7 @@ describes.realWin('CustomElement', {amp: true}, env => { win = env.win; doc = win.document; clock = lolex.install(win); - resources = resourcesForDoc(doc); + resources = Services.resourcesForDoc(doc); resources.isBuildOn_ = true; resourcesMock = sandbox.mock(resources); container = doc.createElement('div'); @@ -1452,7 +1451,7 @@ describes.realWin('CustomElement Loading Indicator', {amp: true}, env => { prototype: createAmpElementProto(win, 'amp-test-loader', TestElement), }); LOADING_ELEMENTS_['amp-test-loader'.toUpperCase()] = true; - resources = resourcesForDoc(doc); + resources = Services.resourcesForDoc(doc); resources.isBuildOn_ = true; resourcesMock = sandbox.mock(resources); element = new ElementClass(); @@ -1460,7 +1459,7 @@ describes.realWin('CustomElement Loading Indicator', {amp: true}, env => { element.layout_ = Layout.FIXED; element.setAttribute('layout', 'fixed'); element.resources_ = resources; - vsync = vsyncFor(win); + vsync = Services.vsyncFor(win); vsyncTasks = []; sandbox.stub(vsync, 'mutate', mutator => { vsyncTasks.push(mutator); @@ -1750,7 +1749,7 @@ describes.realWin('CustomElement Overflow Element', {amp: true}, env => { ElementClass = doc.registerElement('amp-test-overflow', { prototype: createAmpElementProto(win, 'amp-test-overflow', TestElement), }); - resources = resourcesForDoc(doc); + resources = Services.resourcesForDoc(doc); resourcesMock = sandbox.mock(resources); element = new ElementClass(); element.layoutWidth_ = 300; @@ -1759,7 +1758,7 @@ describes.realWin('CustomElement Overflow Element', {amp: true}, env => { overflowElement = doc.createElement('div'); overflowElement.setAttribute('overflow', ''); element.appendChild(overflowElement); - vsync = vsyncFor(win); + vsync = Services.vsyncFor(win); vsyncTasks = []; sandbox.stub(vsync, 'mutate', mutator => { vsyncTasks.push(mutator); diff --git a/test/functional/test-document-info.js b/test/functional/test-document-info.js index 4f390d8088a6..4142f6129d66 100644 --- a/test/functional/test-document-info.js +++ b/test/functional/test-document-info.js @@ -15,7 +15,7 @@ */ import {createIframePromise} from '../../testing/iframe'; -import {documentInfoForDoc} from '../../src/services'; +import {Services} from '../../src/services'; import {installDocumentInfoServiceForDoc} from '../../src/service/document-info-impl'; import {installDocService} from '../../src/service/ampdoc-impl'; @@ -55,7 +55,7 @@ describe('document-info', () => { it('should provide the canonicalUrl', () => { return getWin({'canonical': ['https://twitter.com/']}).then(win => { - expect(documentInfoForDoc(win.document).canonicalUrl).to.equal( + expect(Services.documentInfoForDoc(win.document).canonicalUrl).to.equal( 'https://twitter.com/'); }); }); @@ -74,7 +74,7 @@ describe('document-info', () => { win.document.defaultView = win; installDocService(win, /* isSingleDoc */ true); installDocumentInfoServiceForDoc(win.document); - expect(documentInfoForDoc(win.document).sourceUrl).to.equal( + expect(Services.documentInfoForDoc(win.document).sourceUrl).to.equal( 'http://www.origin.com/foo/?f=0'); }); @@ -92,23 +92,25 @@ describe('document-info', () => { win.document.defaultView = win; installDocService(win, /* isSingleDoc */ true); installDocumentInfoServiceForDoc(win.document); - expect(documentInfoForDoc(win.document).sourceUrl).to.equal( + expect(Services.documentInfoForDoc(win.document).sourceUrl).to.equal( 'http://www.origin.com/foo/?f=0'); win.location.href = 'https://cdn.ampproject.org/v/www.origin.com/foo/?f=1'; - expect(documentInfoForDoc(win.document).sourceUrl).to.equal( + expect(Services.documentInfoForDoc(win.document).sourceUrl).to.equal( 'http://www.origin.com/foo/?f=1'); }); it('should provide the pageViewId', () => { return getWin({'canonical': ['https://twitter.com/']}).then(win => { - expect(documentInfoForDoc(win.document).pageViewId).to.equal('1234'); - expect(documentInfoForDoc(win.document).pageViewId).to.equal('1234'); + expect(Services.documentInfoForDoc(win.document).pageViewId) + .to.equal('1234'); + expect(Services.documentInfoForDoc(win.document).pageViewId) + .to.equal('1234'); }); }); it('should provide the relative canonicalUrl as absolute', () => { return getWin({'canonical': ['./foo.html']}).then(win => { - expect(documentInfoForDoc(win.document).canonicalUrl).to.equal( + expect(Services.documentInfoForDoc(win.document).canonicalUrl).to.equal( 'http://localhost:' + location.port + '/foo.html'); }); }); @@ -118,16 +120,16 @@ describe('document-info', () => { 'canonical': ['https://twitter.com/'], 'icon': ['https://foo.html/bar.gif'], }).then(win => { - expect(documentInfoForDoc(win.document).linkRels['canonical']) + expect(Services.documentInfoForDoc(win.document).linkRels['canonical']) .to.equal('https://twitter.com/'); - expect(documentInfoForDoc(win.document).linkRels['icon']) + expect(Services.documentInfoForDoc(win.document).linkRels['icon']) .to.equal('https://foo.html/bar.gif'); }); }); it('should provide empty linkRels if there are no link tags', () => { return getWin().then(win => { - expect(documentInfoForDoc(win.document).linkRels).to.be.empty; + expect(Services.documentInfoForDoc(win.document).linkRels).to.be.empty; }); }); @@ -136,9 +138,9 @@ describe('document-info', () => { 'canonical': ['./foo.html'], 'icon': ['./bar.gif'], }).then(win => { - expect(documentInfoForDoc(win.document).linkRels['canonical']) + expect(Services.documentInfoForDoc(win.document).linkRels['canonical']) .to.equal('http://localhost:' + location.port + '/foo.html'); - expect(documentInfoForDoc(win.document).linkRels['icon']) + expect(Services.documentInfoForDoc(win.document).linkRels['icon']) .to.equal('http://localhost:' + location.port + '/bar.gif'); }); }); @@ -149,11 +151,11 @@ describe('document-info', () => { 'sharelink canonical': ['https://twitter.com/'], 'icon': ['https://foo.html/bar.gif'], }).then(win => { - expect(documentInfoForDoc(win.document).linkRels['sharelink']) + expect(Services.documentInfoForDoc(win.document).linkRels['sharelink']) .to.equal('https://twitter.com/'); - expect(documentInfoForDoc(win.document).linkRels['canonical']) + expect(Services.documentInfoForDoc(win.document).linkRels['canonical']) .to.equal('https://twitter.com/'); - expect(documentInfoForDoc(win.document).linkRels['icon']) + expect(Services.documentInfoForDoc(win.document).linkRels['icon']) .to.equal('https://foo.html/bar.gif'); }); }); @@ -168,15 +170,16 @@ describe('document-info', () => { 'https://foo.html/style2.css', ], }).then(win => { - expect(documentInfoForDoc(win.document).linkRels['canonical']) + const documentInfo = Services.documentInfoForDoc(win.document); + expect(documentInfo.linkRels['canonical']) .to.equal('https://twitter.com/'); - expect(documentInfoForDoc(win.document).linkRels['icon']) + expect(documentInfo.linkRels['icon']) .to.equal('https://foo.html/bar.gif'); - expect(documentInfoForDoc(win.document).linkRels['stylesheet'].length) + expect(documentInfo.linkRels['stylesheet'].length) .to.equal(2); - expect(documentInfoForDoc(win.document).linkRels['stylesheet'][0]) + expect(documentInfo.linkRels['stylesheet'][0]) .to.equal('https://foo.html/style1.css'); - expect(documentInfoForDoc(win.document).linkRels['stylesheet'][1]) + expect(documentInfo.linkRels['stylesheet'][1]) .to.equal('https://foo.html/style2.css'); }); }); @@ -190,15 +193,15 @@ describe('document-info', () => { 'preload': ['https://foo2.com'], 'preconnect': ['https://foo3.com'], }).then(win => { - expect(documentInfoForDoc(win.document).linkRels['canonical']) + expect(Services.documentInfoForDoc(win.document).linkRels['canonical']) .to.equal('https://twitter.com/'); - expect(documentInfoForDoc(win.document).linkRels['icon']) + expect(Services.documentInfoForDoc(win.document).linkRels['icon']) .to.equal('https://foo.html/bar.gif'); - expect(documentInfoForDoc(win.document).linkRels['prefetch']) + expect(Services.documentInfoForDoc(win.document).linkRels['prefetch']) .to.be.undefined; - expect(documentInfoForDoc(win.document).linkRels['preload']) + expect(Services.documentInfoForDoc(win.document).linkRels['preload']) .to.be.undefined; - expect(documentInfoForDoc(win.document).linkRels['preconnect']) + expect(Services.documentInfoForDoc(win.document).linkRels['preconnect']) .to.be.undefined; }); }); diff --git a/test/functional/test-document-ready.js b/test/functional/test-document-ready.js index a4201fca1d0f..9c2bab9d17ba 100644 --- a/test/functional/test-document-ready.js +++ b/test/functional/test-document-ready.js @@ -19,7 +19,7 @@ import {isDocumentReady, whenDocumentReady, whenDocumentComplete, } from '../../src/document-ready'; -import {timerFor} from '../../src/services'; +import {Services} from '../../src/services'; import * as sinon from 'sinon'; @@ -28,7 +28,7 @@ describe('documentReady', () => { let sandbox; let testDoc; let eventListeners; - const timer = timerFor(window); + const timer = Services.timerFor(window); beforeEach(() => { sandbox = sinon.sandbox.create(); diff --git a/test/functional/test-document-submit.js b/test/functional/test-document-submit.js index ef8c7c649fcd..93baa3804b41 100644 --- a/test/functional/test-document-submit.js +++ b/test/functional/test-document-submit.js @@ -14,7 +14,7 @@ * limitations under the License. */ -import {actionServiceForDoc} from '../../src/services'; +import {Services} from '../../src/services'; import {onDocumentFormSubmit_} from '../../src/document-submit'; import * as sinon from 'sinon'; @@ -163,7 +163,7 @@ describe('test-document-submit onDocumentFormSubmit_', () => { it('should delegate xhr submit through action service', () => { evt.target.setAttribute('action-xhr', 'https://example.com'); - const actionService = actionServiceForDoc(tgt); + const actionService = Services.actionServiceForDoc(tgt); sandbox.stub(actionService, 'execute'); onDocumentFormSubmit_(evt); expect(actionService.execute).to.have.been.calledOnce; @@ -174,7 +174,7 @@ describe('test-document-submit onDocumentFormSubmit_', () => { }); it('should not delegate non-XHR submit through action service', () => { - const actionService = actionServiceForDoc(tgt); + const actionService = Services.actionServiceForDoc(tgt); sandbox.stub(actionService, 'execute'); onDocumentFormSubmit_(evt); expect(actionService.execute).to.have.not.been.called; diff --git a/test/functional/test-experiments.js b/test/functional/test-experiments.js index 787ea3d7c9ee..81386a3cc9fd 100644 --- a/test/functional/test-experiments.js +++ b/test/functional/test-experiments.js @@ -22,7 +22,7 @@ import { tokenWithBadSignature, tokenWithExpiredExperiment, } from './testdata-experiments'; -import {cryptoFor} from '../../src/services'; +import {Services} from '../../src/services'; import {installCryptoService} from '../../src/service/crypto-impl'; import { enableExperimentsForOriginTrials, @@ -825,15 +825,15 @@ describes.realWin('isExperimentOnForOriginTrial', {amp: true}, env => { sandbox = env.sandbox; installCryptoService(win); - crypto = cryptoFor(win); + crypto = Services.cryptoFor(win); warnStub = sandbox.stub(user(), 'warn'); // Ensure that tests don't appear to pass because fake window object // doesn't have crypto when the window actually has it. installCryptoService(env.win); - expect(cryptoFor(env.win).isPkcsAvailable()) - .to.equal(cryptoFor(win).isPkcsAvailable()); + expect(Services.cryptoFor(env.win).isPkcsAvailable()) + .to.equal(Services.cryptoFor(win).isPkcsAvailable()); }); afterEach(() => { diff --git a/test/functional/test-extension-analytics.js b/test/functional/test-extension-analytics.js index 129e57afbd42..1fe36673441a 100644 --- a/test/functional/test-extension-analytics.js +++ b/test/functional/test-extension-analytics.js @@ -25,7 +25,7 @@ import { CustomEventReporterBuilder, } from '../../src/extension-analytics'; import {createAmpElementProto} from '../../src/custom-element'; -import {timerFor} from '../../src/services'; +import {Services} from '../../src/services'; import {BaseElement} from '../../src/base-element'; import {macroTask} from '../../testing/yield'; import * as sinon from 'sinon'; @@ -40,10 +40,10 @@ describes.realWin('extension-analytics', { describe('insertAnalyticsElement', () => { class MockInstrumentation { - }; + }; beforeEach(() => { - timer = timerFor(env.win); + timer = Services.timerFor(env.win); ampdoc = env.ampdoc; win = env.win; }); diff --git a/test/functional/test-extensions.js b/test/functional/test-extensions.js index 64d90e6d92df..385814e5c801 100644 --- a/test/functional/test-extensions.js +++ b/test/functional/test-extensions.js @@ -26,7 +26,7 @@ import { installExtensionsService, registerExtension, } from '../../src/service/extensions-impl'; -import {extensionsFor} from '../../src/services'; +import {Services} from '../../src/services'; import {registerServiceBuilder} from '../../src/service'; import {resetScheduledElementForTesting} from '../../src/custom-element'; import {loadPromise} from '../../src/event-helper'; @@ -394,7 +394,7 @@ describes.sandboxed('Extensions', {}, () => { parentWin = env.win; resetScheduledElementForTesting(parentWin, 'amp-test'); installExtensionsService(parentWin); - extensions = extensionsFor(parentWin); + extensions = Services.extensionsFor(parentWin); extensionsMock = sandbox.mock(extensions); iframe = parentWin.document.createElement('iframe'); diff --git a/test/functional/test-friendly-iframe-embed.js b/test/functional/test-friendly-iframe-embed.js index 77f2d3a47d37..34e1fce77bfc 100644 --- a/test/functional/test-friendly-iframe-embed.js +++ b/test/functional/test-friendly-iframe-embed.js @@ -25,11 +25,10 @@ import { } from '../../src/friendly-iframe-embed'; import {Signals} from '../../src/utils/signals'; import {getStyle} from '../../src/style'; -import {extensionsFor} from '../../src/services'; +import {Services} from '../../src/services'; import {installServiceInEmbedScope} from '../../src/service'; import {layoutRectLtwh} from '../../src/layout-rect'; import {loadPromise} from '../../src/event-helper'; -import {resourcesForDoc} from '../../src/services'; import * as sinon from 'sinon'; @@ -43,8 +42,8 @@ describe('friendly-iframe-embed', () => { beforeEach(() => { sandbox = sinon.sandbox.create(); - const extensions = extensionsFor(window); - const resources = resourcesForDoc(window.document); + const extensions = Services.extensionsFor(window); + const resources = Services.resourcesForDoc(window.document); extensionsMock = sandbox.mock(extensions); resourcesMock = sandbox.mock(resources); diff --git a/test/functional/test-history.js b/test/functional/test-history.js index ce44262ebda3..bd654c198237 100644 --- a/test/functional/test-history.js +++ b/test/functional/test-history.js @@ -21,10 +21,9 @@ import { HistoryBindingVirtual_, installHistoryServiceForDoc, } from '../../src/service/history-impl'; -import {historyForDoc} from '../../src/services'; +import {Services} from '../../src/services'; import {listenOncePromise} from '../../src/event-helper'; import {installTimerService} from '../../src/service/timer-impl'; -import {timerFor} from '../../src/services'; import {parseUrl} from '../../src/url'; import * as sinon from 'sinon'; @@ -191,7 +190,7 @@ describes.sandboxed('History install', {}, () => { win = { services: { 'viewer': {obj: viewer}, - 'timer': {obj: timerFor(window)}, + 'timer': {obj: Services.timerFor(window)}, }, history: { length: 0, @@ -208,7 +207,7 @@ describes.sandboxed('History install', {}, () => { }); it('should create natural binding and make it singleton', () => { - const history = historyForDoc(ampdoc); + const history = Services.historyForDoc(ampdoc); expect(history.binding_).to.be.instanceOf(HistoryBindingNatural_); expect(win.services.history.obj).to.equal(history); // Ensure that binding is installed as a singleton. @@ -218,7 +217,7 @@ describes.sandboxed('History install', {}, () => { it('should create virtual binding', () => { viewer.isOvertakeHistory = () => true; - const history = historyForDoc(ampdoc); + const history = Services.historyForDoc(ampdoc); expect(history.binding_).to.be.instanceOf(HistoryBindingVirtual_); expect(win.services.history.obj).to.equal(history); // Ensure that the global singleton has not been created. diff --git a/test/functional/test-impression.js b/test/functional/test-impression.js index 4fcc7b46dfd9..fb0884a75797 100644 --- a/test/functional/test-impression.js +++ b/test/functional/test-impression.js @@ -20,8 +20,7 @@ import { resetTrackImpressionPromiseForTesting, } from '../../src/impression'; import {toggleExperiment} from '../../src/experiments'; -import {viewerForDoc} from '../../src/services'; -import {xhrFor} from '../../src/services'; +import {Services} from '../../src/services'; import * as sinon from 'sinon'; describe('impression', () => { @@ -32,9 +31,9 @@ describe('impression', () => { beforeEach(() => { sandbox = sinon.sandbox.create(); - viewer = viewerForDoc(window.document); + viewer = Services.viewerForDoc(window.document); sandbox.stub(viewer, 'getParam'); - xhr = xhrFor(window); + xhr = Services.xhrFor(window); expect(xhr.fetchJson).to.be.defined; const stub = sandbox.stub(xhr, 'fetchJson'); stub.returns(Promise.resolve({ diff --git a/test/functional/test-layout-delay-meter.js b/test/functional/test-layout-delay-meter.js index 716e3875d49e..8dcccbb6dc18 100644 --- a/test/functional/test-layout-delay-meter.js +++ b/test/functional/test-layout-delay-meter.js @@ -15,10 +15,8 @@ */ import {LayoutDelayMeter} from '../../src/layout-delay-meter'; -import { - installPerformanceService, - performanceFor, -} from '../../src/service/performance-impl'; +import {Services} from '../../src/services'; +import {installPerformanceService} from '../../src/service/performance-impl'; import * as lolex from 'lolex'; describes.realWin('layout-delay-meter', { @@ -37,7 +35,7 @@ describes.realWin('layout-delay-meter', { sandbox = env.sandbox; win = env.win; installPerformanceService(win); - const perf = performanceFor(win); + const perf = Services.performanceFor(win); sandbox.stub(perf, 'isPerformanceTrackingOn', () => true); clock = lolex.install(win, 0, ['Date', 'setTimeout', 'clearTimeout']); tickSpy = sandbox.spy(perf, 'tickDelta'); diff --git a/test/functional/test-pass.js b/test/functional/test-pass.js index d84b73e4d4f3..771b3bf9f7a7 100644 --- a/test/functional/test-pass.js +++ b/test/functional/test-pass.js @@ -15,7 +15,7 @@ */ import {Pass} from '../../src/pass'; -import {timerFor} from '../../src/services'; +import {Services} from '../../src/services'; import * as sinon from 'sinon'; describe('Pass', () => { @@ -27,7 +27,7 @@ describe('Pass', () => { beforeEach(() => { sandbox = sinon.sandbox.create(); - timerMock = sandbox.mock(timerFor(window)); + timerMock = sandbox.mock(Services.timerFor(window)); handlerCalled = 0; pass = new Pass(window, () => { handlerCalled++; diff --git a/test/functional/test-performance.js b/test/functional/test-performance.js index e74ce88b40fc..68216da2094b 100644 --- a/test/functional/test-performance.js +++ b/test/functional/test-performance.js @@ -14,13 +14,9 @@ * limitations under the License. */ +import {Services} from '../../src/services'; import {getMode} from '../../src/mode'; -import { - installPerformanceService, - performanceFor, -} from '../../src/service/performance-impl'; -import {resourcesForDoc} from '../../src/services'; -import {viewerForDoc} from '../../src/services'; +import {installPerformanceService} from '../../src/service/performance-impl'; import * as lolex from 'lolex'; import * as sinon from 'sinon'; @@ -38,7 +34,7 @@ describes.realWin('performance', {amp: true}, env => { ampdoc = env.ampdoc; clock = lolex.install(win, 0, ['Date', 'setTimeout', 'clearTimeout']); installPerformanceService(env.win); - perf = performanceFor(env.win); + perf = Services.performanceFor(env.win); }); describe('when viewer is not ready', () => { @@ -151,7 +147,7 @@ describes.realWin('performance', {amp: true}, env => { let viewerSendMessageStub; beforeEach(() => { - viewer = viewerForDoc(ampdoc); + viewer = Services.viewerForDoc(ampdoc); viewerSendMessageStub = sandbox.stub(viewer, 'sendMessage'); }); @@ -454,7 +450,7 @@ describes.realWin('performance', {amp: true}, env => { return res; } - const resources = resourcesForDoc(ampdoc); + const resources = Services.resourcesForDoc(ampdoc); const resourcesMock = sandbox.mock(resources); perf.resources_ = resources; @@ -495,7 +491,7 @@ describes.realWin('performance', {amp: true}, env => { } beforeEach(() => { - viewer = viewerForDoc(ampdoc); + viewer = Services.viewerForDoc(ampdoc); sandbox.stub(viewer, 'whenMessagingReady') .returns(Promise.resolve()); viewerSendMessageStub = sandbox.stub(viewer, @@ -635,13 +631,13 @@ describes.realWin('performance with experiment', {amp: true}, env => { beforeEach(() => { win = env.win; sandbox = env.sandbox; - const viewer = viewerForDoc(env.ampdoc); + const viewer = Services.viewerForDoc(env.ampdoc); viewerSendMessageStub = sandbox.stub(viewer, 'sendMessage'); sandbox.stub(viewer, 'whenMessagingReady').returns(Promise.resolve()); sandbox.stub(viewer, 'getParam').withArgs('csi').returns('1'); sandbox.stub(viewer, 'isEmbedded').returns(true); installPerformanceService(win); - perf = performanceFor(win); + perf = Services.performanceFor(win); }); it('rtvVersion experiment', () => { diff --git a/test/functional/test-resource.js b/test/functional/test-resource.js index 5d618f6255c1..48605e414bc2 100644 --- a/test/functional/test-resource.js +++ b/test/functional/test-resource.js @@ -18,7 +18,7 @@ import {AmpDocSingle} from '../../src/service/ampdoc-impl'; import {Resources} from '../../src/service/resources-impl'; import {Resource, ResourceState} from '../../src/service/resource'; import {layoutRectLtwh} from '../../src/layout-rect'; -import {viewerForDoc} from '../../src/services'; +import {Services} from '../../src/services'; import * as sinon from 'sinon'; @@ -71,7 +71,7 @@ describe('Resource', () => { }; elementMock = sandbox.mock(element); - const viewer = viewerForDoc(document); + const viewer = Services.viewerForDoc(document); sandbox.stub(viewer, 'isRuntimeOn', () => false); resources = new Resources(new AmpDocSingle(window)); resource = new Resource(1, element, resources); diff --git a/test/functional/test-resources.js b/test/functional/test-resources.js index 7e6c1f731a0f..567e9e675ca1 100644 --- a/test/functional/test-resources.js +++ b/test/functional/test-resources.js @@ -20,7 +20,7 @@ import {Resource, ResourceState} from '../../src/service/resource'; import {VisibilityState} from '../../src/visibility-state'; import {layoutRectLtwh} from '../../src/layout-rect'; import {loadPromise} from '../../src/event-helper'; -import {resourcesForDoc} from '../../src/services'; +import {Services} from '../../src/services'; import * as sinon from 'sinon'; /*eslint "google-camelcase/google-camelcase": 0*/ @@ -555,7 +555,7 @@ describes.fakeWin('Resources startup', { beforeEach(() => { win = env.win; clock = sandbox.useFakeTimers(); - resources = resourcesForDoc(win.document.body); + resources = Services.resourcesForDoc(win.document.body); resources.relayoutAll_ = false; schedulePassStub = sandbox.stub(resources, 'schedulePass'); }); diff --git a/test/functional/test-runtime.js b/test/functional/test-runtime.js index 7ad0e5008859..3701ca4caf27 100644 --- a/test/functional/test-runtime.js +++ b/test/functional/test-runtime.js @@ -32,10 +32,9 @@ import {installDocumentStateService} from '../../src/service/document-state'; import {installPlatformService} from '../../src/service/platform-impl'; import {installTimerService} from '../../src/service/timer-impl'; import {vsyncForTesting} from '../../src/service/vsync-impl'; -import {platformFor} from '../../src/services'; +import {Services} from '../../src/services'; import {runChunksForTesting} from '../../src/chunk'; import {toggleExperiment} from '../../src/experiments'; -import {extensionsFor} from '../../src/services'; import * as ext from '../../src/service/extensions-impl'; import * as extel from '../../src/extended-element'; import * as styles from '../../src/style-installer'; @@ -126,21 +125,21 @@ describes.fakeWin('runtime', { }); it('should NOT set cursor:pointer on document element on non-IOS', () => { - const platform = platformFor(win); + const platform = Services.platformFor(win); sandbox.stub(platform, 'isIos').returns(false); adopt(win); expect(win.document.documentElement.style.cursor).to.not.be.ok; }); it('should set cursor:pointer on document element on IOS', () => { - const platform = platformFor(win); + const platform = Services.platformFor(win); sandbox.stub(platform, 'isIos').returns(true); adopt(win); expect(win.document.documentElement.style.cursor).to.equal('pointer'); }); it('should set cursor:pointer on IOS in shadow-doc', () => { - const platform = platformFor(win); + const platform = Services.platformFor(win); sandbox.stub(platform, 'isIos').returns(true); adoptShadowMode(win); expect(win.document.documentElement.style.cursor).to.equal('pointer'); @@ -315,7 +314,7 @@ describes.fakeWin('runtime', { expect(progress).to.equal('1HIGHAB2'); ext.installExtensionsService(win); - const extensions = extensionsFor(win); + const extensions = Services.extensionsFor(win); const ext1 = extensions.waitForExtension('ext1'); const ext2 = extensions.waitForExtension('ext2'); return Promise.all([ext1, ext2]); @@ -458,7 +457,7 @@ describes.fakeWin('runtime', { beforeEach(() => { adopt(win); ext.installExtensionsService(win); - extensions = extensionsFor(win); + extensions = Services.extensionsFor(win); registerStub = sandbox.stub(extel, 'registerExtendedElement'); }); @@ -612,7 +611,7 @@ describes.fakeWin('runtime', { beforeEach(() => { adoptShadowMode(win); ext.installExtensionsService(win); - extensions = extensionsFor(win); + extensions = Services.extensionsFor(win); registerStub = sandbox.stub(extel, 'registerExtendedElement'); }); diff --git a/test/functional/test-shadow-embed.js b/test/functional/test-shadow-embed.js index 6ea90e436072..9cb6b457d121 100644 --- a/test/functional/test-shadow-embed.js +++ b/test/functional/test-shadow-embed.js @@ -29,7 +29,7 @@ import { scopeShadowCss, setShadowDomStreamingSupportedForTesting, } from '../../src/shadow-embed'; -import {ampdocServiceFor, extensionsFor} from '../../src/services'; +import {Services} from '../../src/services'; import { setShadowDomSupportedVersionForTesting, ShadowDomVersion, @@ -291,7 +291,7 @@ describes.sandboxed('shadow-embed', {}, () => { let hostElement; beforeEach(() => { - const extensions = extensionsFor(window); + const extensions = Services.extensionsFor(window); extensionsMock = sandbox.mock(extensions); hostElement = document.createElement('div'); @@ -309,7 +309,7 @@ describes.sandboxed('shadow-embed', {}, () => { style.setAttribute('amp-runtime', ''); root.appendChild(style); const ampdoc = new AmpDocShadow(window, 'https://a.org/', root); - const ampdocService = ampdocServiceFor(window); + const ampdocService = Services.ampdocServiceFor(window); sandbox.stub(ampdocService, 'getAmpDoc', () => ampdoc); }); diff --git a/test/functional/test-standard-actions.js b/test/functional/test-standard-actions.js index eb5976331524..57b416483e22 100644 --- a/test/functional/test-standard-actions.js +++ b/test/functional/test-standard-actions.js @@ -17,7 +17,7 @@ import {AmpDocSingle} from '../../src/service/ampdoc-impl'; import {OBJECT_STRING_ARGS_KEY} from '../../src/service/action-impl'; import {StandardActions} from '../../src/service/standard-actions-impl'; -import {bindForDoc, historyForDoc} from '../../src/services'; +import {Services} from '../../src/services'; import {installHistoryServiceForDoc} from '../../src/service/history-impl'; import {setParentWindow} from '../../src/service'; @@ -203,7 +203,7 @@ describes.sandboxed('StandardActions', {}, () => { it('should implement goBack', () => { installHistoryServiceForDoc(ampdoc); - const history = historyForDoc(ampdoc); + const history = Services.historyForDoc(ampdoc); const goBackStub = sandbox.stub(history, 'goBack'); const invocation = {method: 'goBack', satisfiesTrust: () => true}; standardActions.handleAmpTarget(invocation); @@ -228,7 +228,7 @@ describes.sandboxed('StandardActions', {}, () => { satisfiesTrust: () => true, }; standardActions.handleAmpTarget(invocation); - return bindForDoc(ampdoc).then(() => { + return Services.bindForDoc(ampdoc).then(() => { expect(spy).to.be.calledOnce; expect(spy).to.be.calledWith('{foo: 123}'); }); diff --git a/test/functional/test-style-installer.js b/test/functional/test-style-installer.js index fd8af0ae33e4..0161f666885d 100644 --- a/test/functional/test-style-installer.js +++ b/test/functional/test-style-installer.js @@ -16,13 +16,10 @@ import {getStyle} from '../../src/style'; import * as rds from '../../src/render-delaying-services'; -import { - installPerformanceService, - performanceFor, -} from '../../src/service/performance-impl'; +import {installPerformanceService} from '../../src/service/performance-impl'; import {createIframePromise} from '../../testing/iframe'; import {installResourcesServiceForDoc} from '../../src/service/resources-impl'; -import {resourcesForDoc} from '../../src/services'; +import {Services} from '../../src/services'; import * as sinon from 'sinon'; import * as styles from '../../src/style-installer'; @@ -44,10 +41,10 @@ describe('Styles', () => { win = iframe.win; doc = win.document; installPerformanceService(doc.defaultView); - const perf = performanceFor(doc.defaultView); + const perf = Services.performanceFor(doc.defaultView); tickSpy = sandbox.spy(perf, 'tick'); installResourcesServiceForDoc(doc); - resources = resourcesForDoc(doc); + resources = Services.resourcesForDoc(doc); ampdoc = resources.ampdoc; schedulePassSpy = sandbox.spy(resources, 'schedulePass'); waitForServicesStub = sandbox.stub(rds, 'waitForServices'); diff --git a/test/functional/test-template.js b/test/functional/test-template.js index 92fcb5b25cb6..cf08498a144f 100644 --- a/test/functional/test-template.js +++ b/test/functional/test-template.js @@ -20,7 +20,7 @@ import { registerExtendedTemplate, } from '../../src/service/template-impl'; import {resetServiceForTesting} from '../../src/service'; -import {templatesFor} from '../../src/services'; +import {Services} from '../../src/services'; describes.fakeWin('Template', {}, env => { let templates; @@ -30,7 +30,7 @@ describes.fakeWin('Template', {}, env => { beforeEach(() => { win = env.win; installTemplatesService(win); - templates = templatesFor(win); + templates = Services.templatesFor(win); doc = win.document; }); diff --git a/test/functional/test-url-replacements.js b/test/functional/test-url-replacements.js index 8fe66fdcde7f..face6b152485 100644 --- a/test/functional/test-url-replacements.js +++ b/test/functional/test-url-replacements.js @@ -15,11 +15,7 @@ */ import {Observable} from '../../src/observable'; -import { - ampdocServiceFor, - urlReplacementsForDoc, - viewerForDoc, -} from '../../src/services'; +import {Services} from '../../src/services'; import {createIframePromise} from '../../testing/iframe'; import {user} from '../../src/log'; import { @@ -101,8 +97,8 @@ describes.sandboxed('UrlReplacements', {}, () => { }); } } - viewerService = viewerForDoc(iframe.ampdoc); - replacements = urlReplacementsForDoc(iframe.ampdoc); + viewerService = Services.viewerForDoc(iframe.ampdoc); + replacements = Services.urlReplacementsForDoc(iframe.ampdoc); return replacements; }); } @@ -155,7 +151,7 @@ describes.sandboxed('UrlReplacements', {}, () => { }; win.document.defaultView = win; installDocService(win, /* isSingleDoc */ true); - const ampdoc = ampdocServiceFor(win).getAmpDoc(); + const ampdoc = Services.ampdocServiceFor(win).getAmpDoc(); installDocumentInfoServiceForDoc(ampdoc); win.ampdoc = ampdoc; installUrlReplacementsServiceForDoc(ampdoc); @@ -259,7 +255,7 @@ describes.sandboxed('UrlReplacements', {}, () => { resolve(); }); }); - return urlReplacementsForDoc(win.ampdoc) + return Services.urlReplacementsForDoc(win.ampdoc) .expandAsync('?url=SOURCE_URL') .then(res => { expect(res).to.contain('example.com'); @@ -430,7 +426,7 @@ describes.sandboxed('UrlReplacements', {}, () => { it('should reject protocol changes', () => { const win = getFakeWindow(); - const urlReplacements = urlReplacementsForDoc(win.ampdoc); + const urlReplacements = Services.urlReplacementsForDoc(win.ampdoc); return urlReplacements.expandAsync( 'PROTOCOL://example.com/?r=RANDOM', { 'PROTOCOL': Promise.resolve('abc'), @@ -444,7 +440,7 @@ describes.sandboxed('UrlReplacements', {}, () => { win.services.viewer = { obj: {isVisible: () => true}, }; - return urlReplacementsForDoc(win.ampdoc) + return Services.urlReplacementsForDoc(win.ampdoc) .expandAsync('?sh=BACKGROUND_STATE') .then(res => { expect(res).to.equal('?sh=0'); @@ -456,7 +452,7 @@ describes.sandboxed('UrlReplacements', {}, () => { win.services.viewer = { obj: {isVisible: () => false}, }; - return urlReplacementsForDoc(win.ampdoc) + return Services.urlReplacementsForDoc(win.ampdoc) .expandAsync('?sh=BACKGROUND_STATE') .then(res => { expect(res).to.equal('?sh=1'); @@ -482,7 +478,7 @@ describes.sandboxed('UrlReplacements', {}, () => { it('is replaced if timing info is not available', () => { win.document.readyState = 'complete'; - return urlReplacementsForDoc(win.ampdoc) + return Services.urlReplacementsForDoc(win.ampdoc) .expandAsync('?sh=PAGE_LOAD_TIME&s') .then(res => { expect(res).to.match(/sh=&s/); @@ -490,7 +486,7 @@ describes.sandboxed('UrlReplacements', {}, () => { }); it('is replaced if PAGE_LOAD_TIME is available within a delay', () => { - const urlReplacements = urlReplacementsForDoc(win.ampdoc); + const urlReplacements = Services.urlReplacementsForDoc(win.ampdoc); const validMetric = urlReplacements.expandAsync('?sh=PAGE_LOAD_TIME&s'); urlReplacements.ampdoc.win.performance.timing.loadEventStart = 109; win.document.readyState = 'complete'; @@ -649,7 +645,7 @@ describes.sandboxed('UrlReplacements', {}, () => { }); it('should replace new substitutions', () => { - const replacements = urlReplacementsForDoc(window.document); + const replacements = Services.urlReplacementsForDoc(window.document); replacements.getVariableSource().set('ONE', () => 'a'); expect(replacements.expandAsync('?a=ONE')).to.eventually.equal('?a=a'); replacements.getVariableSource().set('ONE', () => 'b'); @@ -660,7 +656,7 @@ describes.sandboxed('UrlReplacements', {}, () => { it('should report errors & replace them with empty string (sync)', () => { const clock = sandbox.useFakeTimers(); - const replacements = urlReplacementsForDoc(window.document); + const replacements = Services.urlReplacementsForDoc(window.document); replacements.getVariableSource().set('ONE', () => { throw new Error('boom'); }); @@ -674,7 +670,7 @@ describes.sandboxed('UrlReplacements', {}, () => { it('should report errors & replace them with empty string (promise)', () => { const clock = sandbox.useFakeTimers(); - const replacements = urlReplacementsForDoc(window.document); + const replacements = Services.urlReplacementsForDoc(window.document); replacements.getVariableSource().set('ONE', () => { return Promise.reject(new Error('boom')); }); @@ -687,14 +683,14 @@ describes.sandboxed('UrlReplacements', {}, () => { }); it('should support positional arguments', () => { - const replacements = urlReplacementsForDoc(window.document); + const replacements = Services.urlReplacementsForDoc(window.document); replacements.getVariableSource().set('FN', one => one); return expect(replacements.expandAsync('?a=FN(xyz1)')).to .eventually.equal('?a=xyz1'); }); it('should support multiple positional arguments', () => { - const replacements = urlReplacementsForDoc(window.document); + const replacements = Services.urlReplacementsForDoc(window.document); replacements.getVariableSource().set('FN', (one, two) => { return one + '-' + two; }); @@ -703,7 +699,7 @@ describes.sandboxed('UrlReplacements', {}, () => { }); it('should support multiple positional arguments with dots', () => { - const replacements = urlReplacementsForDoc(window.document); + const replacements = Services.urlReplacementsForDoc(window.document); replacements.getVariableSource().set('FN', (one, two) => { return one + '-' + two; }); @@ -712,7 +708,7 @@ describes.sandboxed('UrlReplacements', {}, () => { }); it('should support promises as replacements', () => { - const replacements = urlReplacementsForDoc(window.document); + const replacements = Services.urlReplacementsForDoc(window.document); replacements.getVariableSource().set('P1', () => Promise.resolve('abc ')); replacements.getVariableSource().set('P2', () => Promise.resolve('xyz')); replacements.getVariableSource().set('P3', () => Promise.resolve('123')); @@ -816,7 +812,7 @@ describes.sandboxed('UrlReplacements', {}, () => { resolve(); }); }); - return urlReplacementsForDoc(win.ampdoc) + return Services.urlReplacementsForDoc(win.ampdoc) .expandAsync('?sh=QUERY_PARAM(query_string_param1)&s') .then(res => { expect(res).to.match(/sh=foo&s/); @@ -829,7 +825,7 @@ describes.sandboxed('UrlReplacements', {}, () => { sandbox.stub(trackPromise, 'getTrackImpressionPromise', () => { return Promise.resolve(); }); - return urlReplacementsForDoc(win.ampdoc) + return Services.urlReplacementsForDoc(win.ampdoc) .expandAsync('?sh=QUERY_PARAM(query_string_param1)&s') .then(res => { expect(res).to.match(/sh=&s/); @@ -842,7 +838,7 @@ describes.sandboxed('UrlReplacements', {}, () => { sandbox.stub(trackPromise, 'getTrackImpressionPromise', () => { return Promise.resolve(); }); - return urlReplacementsForDoc(win.ampdoc) + return Services.urlReplacementsForDoc(win.ampdoc) .expandAsync('?sh=QUERY_PARAM(query_string_param1,default_value)&s') .then(res => { expect(res).to.match(/sh=default_value&s/); @@ -855,7 +851,7 @@ describes.sandboxed('UrlReplacements', {}, () => { sandbox.stub(trackPromise, 'getTrackImpressionPromise', () => { return Promise.resolve(); }); - return urlReplacementsForDoc(win.ampdoc) + return Services.urlReplacementsForDoc(win.ampdoc) .collectVars('?SOURCE_HOST&QUERY_PARAM(p1)&SIMPLE&FUNC&PROMISE', { 'SIMPLE': 21, 'FUNC': () => 22, @@ -874,7 +870,7 @@ describes.sandboxed('UrlReplacements', {}, () => { it('should reject javascript protocol', () => { const win = getFakeWindow(); - const urlReplacements = urlReplacementsForDoc(win.ampdoc); + const urlReplacements = Services.urlReplacementsForDoc(win.ampdoc); /*eslint no-script-url: 0*/ return urlReplacements.expandAsync('javascript://example.com/?r=RANDOM') .then( @@ -888,7 +884,7 @@ describes.sandboxed('UrlReplacements', {}, () => { describe('sync expansion', () => { it('should expand w/ collect vars (skip async macro)', () => { const win = getFakeWindow(); - const urlReplacements = urlReplacementsForDoc(win.ampdoc); + const urlReplacements = Services.urlReplacementsForDoc(win.ampdoc); urlReplacements.ampdoc.win.performance.timing.loadEventStart = 109; const collectVars = {}; const expanded = urlReplacements.expandSync( @@ -910,7 +906,7 @@ describes.sandboxed('UrlReplacements', {}, () => { it('should reject protocol changes', () => { const win = getFakeWindow(); - const urlReplacements = urlReplacementsForDoc(win.ampdoc); + const urlReplacements = Services.urlReplacementsForDoc(win.ampdoc); let expanded = urlReplacements.expandSync( 'PROTOCOL://example.com/?r=RANDOM', { 'PROTOCOL': 'abc', @@ -925,7 +921,7 @@ describes.sandboxed('UrlReplacements', {}, () => { it('should reject javascript protocol', () => { const win = getFakeWindow(); - const urlReplacements = urlReplacementsForDoc(win.ampdoc); + const urlReplacements = Services.urlReplacementsForDoc(win.ampdoc); expect(() => { /*eslint no-script-url: 0*/ urlReplacements.expandSync('javascript://example.com/?r=RANDOM'); @@ -935,7 +931,7 @@ describes.sandboxed('UrlReplacements', {}, () => { it('should expand sync and respect white list', () => { const win = getFakeWindow(); - const urlReplacements = urlReplacementsForDoc(win.ampdoc); + const urlReplacements = Services.urlReplacementsForDoc(win.ampdoc); const expanded = urlReplacements.expandSync( 'r=RANDOM&c=CONST&f=FUNCT(hello,world)&a=b&d=PROM&e=PAGE_LOAD_TIME', { @@ -975,7 +971,7 @@ describes.sandboxed('UrlReplacements', {}, () => { link.setAttribute('rel', 'canonical'); iframe.doc.head.appendChild(link); - const replacements = urlReplacementsForDoc(iframe.ampdoc); + const replacements = Services.urlReplacementsForDoc(iframe.ampdoc); replacements.getVariableSource().getAccessService_ = ampdoc => { expect(ampdoc.isSingleDoc).to.be.function; if (opt_disabled) { @@ -1028,7 +1024,7 @@ describes.sandboxed('UrlReplacements', {}, () => { a = document.createElement('a'); win = getFakeWindow(); win.location = parseUrl('https://example.com/base?foo=bar&bar=abc'); - urlReplacements = urlReplacementsForDoc(win.ampdoc); + urlReplacements = Services.urlReplacementsForDoc(win.ampdoc); }); it('should replace href', () => { @@ -1185,7 +1181,7 @@ describes.sandboxed('UrlReplacements', {}, () => { describe('Expanding String', () => { it('should not reject protocol changes with expandStringSync', () => { const win = getFakeWindow(); - const urlReplacements = urlReplacementsForDoc(win.ampdoc); + const urlReplacements = Services.urlReplacementsForDoc(win.ampdoc); let expanded = urlReplacements.expandStringSync( 'PROTOCOL://example.com/?r=RANDOM', { 'PROTOCOL': 'abc', @@ -1200,7 +1196,7 @@ describes.sandboxed('UrlReplacements', {}, () => { it('should not check protocol changes with expandStringAsync', () => { const win = getFakeWindow(); - const urlReplacements = urlReplacementsForDoc(win.ampdoc); + const urlReplacements = Services.urlReplacementsForDoc(win.ampdoc); return urlReplacements.expandStringAsync( 'RANDOM:X:Y', { 'RANDOM': Promise.resolve('abc'), @@ -1213,7 +1209,7 @@ describes.sandboxed('UrlReplacements', {}, () => { describe('Expanding Input Value', () => { it('should fail for non-inputs', () => { const win = getFakeWindow(); - const urlReplacements = urlReplacementsForDoc(win.ampdoc); + const urlReplacements = Services.urlReplacementsForDoc(win.ampdoc); const input = document.createElement('textarea'); input.value = 'RANDOM'; input.setAttribute('data-amp-replace', 'RANDOM'); @@ -1224,7 +1220,7 @@ describes.sandboxed('UrlReplacements', {}, () => { it('should fail for non-hidden inputs', () => { const win = getFakeWindow(); - const urlReplacements = urlReplacementsForDoc(win.ampdoc); + const urlReplacements = Services.urlReplacementsForDoc(win.ampdoc); const input = document.createElement('input'); input.value = 'RANDOM'; input.setAttribute('data-amp-replace', 'RANDOM'); @@ -1235,7 +1231,7 @@ describes.sandboxed('UrlReplacements', {}, () => { it('should not replace not whitelisted vars', () => { const win = getFakeWindow(); - const urlReplacements = urlReplacementsForDoc(win.ampdoc); + const urlReplacements = Services.urlReplacementsForDoc(win.ampdoc); const input = document.createElement('input'); input.value = 'RANDOM'; input.type = 'hidden'; @@ -1251,7 +1247,7 @@ describes.sandboxed('UrlReplacements', {}, () => { it('should replace input value with var subs - sync', () => { const win = getFakeWindow(); - const urlReplacements = urlReplacementsForDoc(win.ampdoc); + const urlReplacements = Services.urlReplacementsForDoc(win.ampdoc); const input = document.createElement('input'); input.value = 'RANDOM'; input.type = 'hidden'; @@ -1271,7 +1267,7 @@ describes.sandboxed('UrlReplacements', {}, () => { it('should replace input value with var subs - sync', () => { const win = getFakeWindow(); - const urlReplacements = urlReplacementsForDoc(win.ampdoc); + const urlReplacements = Services.urlReplacementsForDoc(win.ampdoc); const input = document.createElement('input'); input.value = 'RANDOM'; input.type = 'hidden'; diff --git a/test/functional/test-video-manager.js b/test/functional/test-video-manager.js index 817375e9d806..88016237b1ab 100644 --- a/test/functional/test-video-manager.js +++ b/test/functional/test-video-manager.js @@ -15,11 +15,7 @@ */ import {listenOncePromise} from '../../src/event-helper'; -import { - ampdocServiceFor, - videoManagerForDoc, - viewerForDoc, -} from '../../src/services'; +import {Services} from '../../src/services'; import {isLayoutSizeDefined} from '../../src/layout'; import {PlayingStates, VideoEvents} from '../../src/video-interface'; import { @@ -99,7 +95,8 @@ describes.fakeWin('VideoManager', { video.setAttribute('autoplay', ''); videoManager.register(impl); - const visibilityStub = sandbox.stub(viewerForDoc(env.ampdoc), 'isVisible'); + const visibilityStub = sandbox.stub( + Services.viewerForDoc(env.ampdoc), 'isVisible'); visibilityStub.onFirstCall().returns(true); const entry = videoManager.getEntryForVideo_(impl); @@ -120,7 +117,8 @@ describes.fakeWin('VideoManager', { video.setAttribute('autoplay', ''); videoManager.register(impl); - const visibilityStub = sandbox.stub(viewerForDoc(env.ampdoc), 'isVisible'); + const visibilityStub = sandbox.stub( + Services.viewerForDoc(env.ampdoc), 'isVisible'); visibilityStub.onFirstCall().returns(true); const entry = videoManager.getEntryForVideo_(impl); @@ -183,7 +181,8 @@ describes.fakeWin('VideoManager', { videoManager.register(impl); - const visibilityStub = sandbox.stub(viewerForDoc(env.ampdoc), 'isVisible'); + const visibilityStub = sandbox.stub( + Services.viewerForDoc(env.ampdoc), 'isVisible'); visibilityStub.onFirstCall().returns(true); const entry = videoManager.getEntryForVideo_(impl); @@ -235,7 +234,7 @@ describes.fakeWin('VideoManager', { video = env.createAmpElement('amp-test-fake-videoplayer', klass); impl = video.implementation_; installVideoManagerForDoc(env.ampdoc); - videoManager = videoManagerForDoc(env.ampdoc); + videoManager = Services.videoManagerForDoc(env.ampdoc); }); afterEach(() => { @@ -400,9 +399,9 @@ function createFakeVideoPlayerClass(win) { /** @override */ buildCallback() { - const ampdoc = ampdocServiceFor(this.win).getAmpDoc(); + const ampdoc = Services.ampdocServiceFor(this.win).getAmpDoc(); installVideoManagerForDoc(ampdoc); - videoManagerForDoc(this.win.document).register(this); + Services.videoManagerForDoc(this.win.document).register(this); } /** @override */ diff --git a/test/functional/test-viewer.js b/test/functional/test-viewer.js index 49ea21d0f4e3..835f911622bb 100644 --- a/test/functional/test-viewer.js +++ b/test/functional/test-viewer.js @@ -15,7 +15,7 @@ */ import {Viewer} from '../../src/service/viewer-impl'; -import {ampdocServiceFor} from '../../src/services'; +import {Services} from '../../src/services'; import {dev} from '../../src/log'; import {installDocService} from '../../src/service/ampdoc-impl'; import {installDocumentStateService} from '../../src/service/document-state'; @@ -85,7 +85,7 @@ describe('Viewer', () => { }); installDocService(windowApi, /* isSingleDoc */ true); installDocumentStateService(windowApi); - ampdoc = ampdocServiceFor(windowApi).getAmpDoc(); + ampdoc = Services.ampdocServiceFor(windowApi).getAmpDoc(); installPlatformService(windowApi); installTimerService(windowApi); events = {}; diff --git a/test/functional/test-viewport.js b/test/functional/test-viewport.js index 7c3909384c17..b162aba9edc0 100644 --- a/test/functional/test-viewport.js +++ b/test/functional/test-viewport.js @@ -15,13 +15,7 @@ */ import {AmpDocSingle, installDocService} from '../../src/service/ampdoc-impl'; -import { - ampdocServiceFor, - platformFor, - viewerForDoc, - viewportForDoc, - vsyncFor, -} from '../../src/services'; +import {Services} from '../../src/services'; import { installViewportServiceForDoc, Viewport, @@ -99,7 +93,7 @@ describes.fakeWin('Viewport', {}, env => { installPlatformService(windowApi); installDocService(windowApi, /* isSingleDoc */ true); installDocumentStateService(windowApi); - ampdoc = ampdocServiceFor(windowApi).getAmpDoc(); + ampdoc = Services.ampdocServiceFor(windowApi).getAmpDoc(); installViewerServiceForDoc(ampdoc); binding = new ViewportBindingDef(); @@ -123,7 +117,7 @@ describes.fakeWin('Viewport', {}, env => { viewport.getSize(); // Use window since Animation by default will use window. - const vsync = vsyncFor(window); + const vsync = Services.vsyncFor(window); vsyncTasks = []; sandbox.stub(vsync, 'canAnimate').returns(true); sandbox.stub(vsync, 'createAnimTask', (unusedContextNode, task) => { @@ -205,7 +199,7 @@ describes.fakeWin('Viewport', {}, env => { } return null; }); - const platform = platformFor(ampdoc.win); + const platform = Services.platformFor(ampdoc.win); isIos = true; sandbox.stub(platform, 'isIos', () => isIos); }); @@ -1151,7 +1145,7 @@ describe('Viewport META', () => { installPlatformService(windowApi); installDocService(windowApi, /* isSingleDoc */ true); installDocumentStateService(windowApi); - ampdoc = ampdocServiceFor(windowApi).getAmpDoc(); + ampdoc = Services.ampdocServiceFor(windowApi).getAmpDoc(); installViewerServiceForDoc(ampdoc); binding = new ViewportBindingDef(); viewport = new Viewport(ampdoc, binding, viewer); @@ -1255,7 +1249,7 @@ describes.realWin('ViewportBindingNatural', {ampCss: true}, env => { installVsyncService(win); installDocService(win, /* isSingleDoc */ true); installDocumentStateService(win); - ampdoc = ampdocServiceFor(win).getAmpDoc(); + ampdoc = Services.ampdocServiceFor(win).getAmpDoc(); binding = new ViewportBindingNatural_(ampdoc, viewer); binding.connect(); }); @@ -1410,7 +1404,7 @@ describes.realWin('ViewportBindingNaturalIosEmbed', {ampCss: true}, env => { installDocService(win, /* isSingleDoc */ true); installDocumentStateService(win); installVsyncService(win); - const ampdoc = ampdocServiceFor(win).getAmpDoc(); + const ampdoc = Services.ampdocServiceFor(win).getAmpDoc(); installPlatformService(win); installViewerServiceForDoc(ampdoc); @@ -1866,10 +1860,10 @@ describe('createViewport', () => { win.parent = win; installDocService(win, /* isSingleDoc */ true); installDocumentStateService(win); - const ampDoc = ampdocServiceFor(win).getAmpDoc(); + const ampDoc = Services.ampdocServiceFor(win).getAmpDoc(); installViewerServiceForDoc(ampDoc); installViewportServiceForDoc(ampDoc); - const viewport = viewportForDoc(ampDoc); + const viewport = Services.viewportForDoc(ampDoc); expect(viewport.binding_).to.be.instanceof(ViewportBindingNatural_); }); @@ -1877,10 +1871,10 @@ describe('createViewport', () => { win.parent = {}; installDocService(win, /* isSingleDoc */ true); installDocumentStateService(win); - const ampDoc = ampdocServiceFor(win).getAmpDoc(); + const ampDoc = Services.ampdocServiceFor(win).getAmpDoc(); installViewerServiceForDoc(ampDoc); installViewportServiceForDoc(ampDoc); - const viewport = viewportForDoc(ampDoc); + const viewport = Services.viewportForDoc(ampDoc); expect(viewport.binding_).to.be.instanceof(ViewportBindingNatural_); }); }); @@ -1899,15 +1893,15 @@ describe('createViewport', () => { installVsyncService(win); installDocService(win, /* isSingleDoc */ true); installDocumentStateService(win); - ampDoc = ampdocServiceFor(win).getAmpDoc(); + ampDoc = Services.ampdocServiceFor(win).getAmpDoc(); installViewerServiceForDoc(ampDoc); - viewer = viewerForDoc(ampDoc); + viewer = Services.viewerForDoc(ampDoc); }); it('should bind to "natural" when not iframed', () => { win.parent = win; installViewportServiceForDoc(ampDoc); - const viewport = viewportForDoc(ampDoc); + const viewport = Services.viewportForDoc(ampDoc); expect(viewport.binding_).to.be.instanceof(ViewportBindingNatural_); }); @@ -1915,7 +1909,7 @@ describe('createViewport', () => { win.parent = {}; sandbox.stub(viewer, 'isEmbedded', () => true); installViewportServiceForDoc(ampDoc); - const viewport = viewportForDoc(ampDoc); + const viewport = Services.viewportForDoc(ampDoc); expect(viewport.binding_).to .be.instanceof(ViewportBindingNaturalIosEmbed_); }); @@ -1924,7 +1918,7 @@ describe('createViewport', () => { win.parent = {}; sandbox.stub(viewer, 'isEmbedded', () => false); installViewportServiceForDoc(ampDoc); - const viewport = viewportForDoc(ampDoc); + const viewport = Services.viewportForDoc(ampDoc); expect(viewport.binding_).to .be.instanceof(ViewportBindingNatural_); }); @@ -1933,7 +1927,7 @@ describe('createViewport', () => { getMode(win).development = true; sandbox.stub(viewer, 'isEmbedded', () => false); installViewportServiceForDoc(ampDoc); - const viewport = viewportForDoc(ampDoc); + const viewport = Services.viewportForDoc(ampDoc); expect(viewport.binding_).to .be.instanceof(ViewportBindingNaturalIosEmbed_); }); @@ -1943,7 +1937,7 @@ describe('createViewport', () => { getMode(win).test = true; sandbox.stub(viewer, 'isEmbedded', () => false); installViewportServiceForDoc(ampDoc); - const viewport = viewportForDoc(ampDoc); + const viewport = Services.viewportForDoc(ampDoc); expect(viewport.binding_).to .be.instanceof(ViewportBindingNaturalIosEmbed_); }); @@ -1953,7 +1947,7 @@ describe('createViewport', () => { getMode(win).development = true; sandbox.stub(viewer, 'isEmbedded', () => false); installViewportServiceForDoc(ampDoc); - const viewport = viewportForDoc(ampDoc); + const viewport = Services.viewportForDoc(ampDoc); expect(viewport.binding_).to .be.instanceof(ViewportBindingNatural_); }); diff --git a/test/functional/test-vsync.js b/test/functional/test-vsync.js index e09f6c5ed3e3..ecb847923b5a 100644 --- a/test/functional/test-vsync.js +++ b/test/functional/test-vsync.js @@ -16,7 +16,7 @@ import {Vsync} from '../../src/service/vsync-impl'; import {AmpDocShadow, installDocService} from '../../src/service/ampdoc-impl'; -import {ampdocServiceFor, viewerPromiseForDoc} from '../../src/services'; +import {Services} from '../../src/services'; import {installTimerService} from '../../src/service/timer-impl'; import * as sinon from 'sinon'; @@ -83,10 +83,10 @@ describe('vsync', () => { beforeEach(() => { installDocService(win, /* isSingleDoc */ true); - ampdoc = ampdocServiceFor(win).getAmpDoc(); + ampdoc = Services.ampdocServiceFor(win).getAmpDoc(); win.services['viewer'] = {obj: viewer}; vsync = new Vsync(win); - return viewerPromiseForDoc(ampdoc); + return Services.viewerPromiseForDoc(ampdoc); }); afterEach(() => { diff --git a/test/functional/web-worker/test-amp-worker.js b/test/functional/web-worker/test-amp-worker.js index 6beb00fc1cfa..a032daafa473 100644 --- a/test/functional/web-worker/test-amp-worker.js +++ b/test/functional/web-worker/test-amp-worker.js @@ -20,7 +20,7 @@ import { ampWorkerForTesting, } from '../../../src/web-worker/amp-worker'; import {installXhrService} from '../../../src/service/xhr-impl'; -import {xhrFor} from '../../../src/services'; +import {Services} from '../../../src/services'; import * as sinon from 'sinon'; describe('invokeWebWorker', () => { @@ -50,7 +50,7 @@ describe('invokeWebWorker', () => { // Stub xhr.fetchText() to return a resolved promise. installXhrService(fakeWin); - sandbox.stub(xhrFor(fakeWin), 'fetchText', () => Promise.resolve({ + sandbox.stub(Services.xhrFor(fakeWin), 'fetchText', () => Promise.resolve({ text() { return Promise.resolve(); }, diff --git a/test/integration/test-amp-ad-3p.js b/test/integration/test-amp-ad-3p.js index 917a6b16c8c6..3675823dba36 100644 --- a/test/integration/test-amp-ad-3p.js +++ b/test/integration/test-amp-ad-3p.js @@ -19,7 +19,7 @@ import { pollForLayout, poll, } from '../../testing/iframe'; -import {platformFor} from '../../src/services'; +import {Services} from '../../src/services'; import {installPlatformService} from '../../src/service/platform-impl'; import {toggleExperiment} from '../../src/experiments'; @@ -30,7 +30,7 @@ function createIframeWithApis(fixture) { let iframe; let ampAd; let lastIO = null; - const platform = platformFor(fixture.win); + const platform = Services.platformFor(fixture.win); return pollForLayout(fixture.win, 1, 5500).then(() => { // test amp-ad will create an iframe return poll('frame to be in DOM', () => { diff --git a/test/integration/test-amp-bind.js b/test/integration/test-amp-bind.js index 3829586f96da..84c7ec8eb3be 100644 --- a/test/integration/test-amp-bind.js +++ b/test/integration/test-amp-bind.js @@ -16,8 +16,8 @@ import {AmpEvents} from '../../src/amp-events'; import {BindEvents} from '../../extensions/amp-bind/0.1/bind-events'; import {FormEvents} from '../../extensions/amp-form/0.1/form-events'; +import {Services} from '../../src/services'; import {createFixtureIframe} from '../../testing/iframe'; -import {batchedXhrFor} from '../../src/services'; import * as sinon from 'sinon'; describe.configure().skipSauceLabs().run('amp-bind', function() { @@ -570,7 +570,7 @@ describe.configure().skipSauceLabs().run('amp-bind', function() { const triggerBindApplicationButton = fixture.doc.getElementById('triggerBindApplicationButton'); const ampState = fixture.doc.getElementById('ampState'); - const batchedXhr = batchedXhrFor(fixture.win); + const batchedXhr = Services.batchedXhrFor(fixture.win); // Stub XHR for endpoint such that it returns state that would point // the amp-state element back to its original source. sandbox.stub(batchedXhr, 'fetchJson') diff --git a/test/integration/test-video-players-helper.js b/test/integration/test-video-players-helper.js index 0f34b8cda234..7d732389f94e 100644 --- a/test/integration/test-video-players-helper.js +++ b/test/integration/test-video-players-helper.js @@ -15,7 +15,7 @@ */ import {getData, listen, listenOncePromise} from '../../src/event-helper'; -import {timerFor} from '../../src/services'; +import {Services} from '../../src/services'; import {removeElement} from '../../src/dom'; import {toggleExperiment} from '../../src/experiments'; import { @@ -266,7 +266,7 @@ export function runVideoPlayerIntegrationTests( } ).then(r => { video = r.video; - timer = timerFor(r.video.implementation_.win); + timer = Services.timerFor(r.video.implementation_.win); playButton = createButton(r, 'play'); pauseButton = createButton(r, 'pause'); return listenOncePromise(video, VideoEvents.LOAD); @@ -495,7 +495,7 @@ export function runVideoPlayerIntegrationTests( it('should not play when not in view port initially', () => { return getVideoPlayer({outsideView: true, autoplay: true}).then(r => { - const timer = timerFor(r.video.implementation_.win); + const timer = Services.timerFor(r.video.implementation_.win); const p = listenOncePromise(r.video, VideoEvents.PLAYING).then(() => { return Promise.reject('should not have autoplayed'); }); diff --git a/test/integration/test-visibility-states.js b/test/integration/test-visibility-states.js index 9a331c7b1737..200b8370bfde 100644 --- a/test/integration/test-visibility-states.js +++ b/test/integration/test-visibility-states.js @@ -14,11 +14,7 @@ * limitations under the License. */ -import { - documentStateFor, - resourcesForDoc, - viewerPromiseForDoc, -} from '../../src/services'; +import {Services} from '../../src/services'; import {VisibilityState} from '../../src/visibility-state'; import {getVendorJsPropertyName} from '../../src/style'; import {whenUpgradedToCustomElement} from '../../src/dom'; @@ -93,12 +89,12 @@ describe.configure().skipSauceLabs().run('Viewer Visibility State', () => { notifyPass = noop; shouldPass = false; - return viewerPromiseForDoc(win.document).then(v => { + return Services.viewerPromiseForDoc(win.document).then(v => { viewer = v; - const docState = documentStateFor(win); + const docState = Services.documentStateFor(win); docHidden = sandbox.stub(docState, 'isHidden').returns(false); - resources = resourcesForDoc(win.document); + resources = Services.resourcesForDoc(win.document); doPass_ = resources.doPass; sandbox.stub(resources, 'doPass', doPass); unselect = sandbox.stub(resources, 'unselectText'); diff --git a/testing/describes.js b/testing/describes.js index 67eafdb5c435..95d9e839896b 100644 --- a/testing/describes.js +++ b/testing/describes.js @@ -90,11 +90,7 @@ import { } from './fake-dom'; import {installFriendlyIframeEmbed} from '../src/friendly-iframe-embed'; import {doNotLoadExternalResourcesInTest} from './iframe'; -import { - ampdocServiceFor, - extensionsFor, - resourcesForDoc, -} from '../src/services'; +import {Services} from '../src/services'; import { adopt, adoptShadowMode, @@ -611,10 +607,10 @@ class AmpFixture { const ampdocType = spec.ampdoc || 'single'; const singleDoc = ampdocType == 'single' || ampdocType == 'fie'; installDocService(win, singleDoc); - const ampdocService = ampdocServiceFor(win); + const ampdocService = Services.ampdocServiceFor(win); env.ampdocService = ampdocService; installExtensionsService(win); - env.extensions = extensionsFor(win); + env.extensions = Services.extensionsFor(win); installBuiltinElements(win); installRuntimeServices(win); env.flushVsync = function() { @@ -627,7 +623,7 @@ class AmpFixture { env.ampdoc = ampdoc; installAmpdocServices(ampdoc, spec.params); adopt(win); - resourcesForDoc(ampdoc).ampInitComplete(); + Services.resourcesForDoc(ampdoc).ampInitComplete(); } else if (ampdocType == 'multi' || ampdocType == 'shadow') { adoptShadowMode(win); // Notice that ampdoc's themselves install runtime styles in shadow roots. diff --git a/testing/iframe.js b/testing/iframe.js index 128c4f17a0ce..9d6d57991cfa 100644 --- a/testing/iframe.js +++ b/testing/iframe.js @@ -18,7 +18,7 @@ import {AmpEvents} from '../src/amp-events'; import {BindEvents} from '../extensions/amp-bind/0.1/bind-events'; import {FakeLocation} from './fake-dom'; import {FormEvents} from '../extensions/amp-form/0.1/form-events'; -import {ampdocServiceFor, resourcesForDoc} from '../src/services'; +import {Services, resourcesForDoc} from '../src/services'; import {cssText} from '../build/css'; import {deserializeMessage, isAmpMessage} from '../src/3p-frame-messaging'; import {parseIfNeeded} from '../src/iframe-helper'; @@ -227,13 +227,13 @@ export function createIframePromise(opt_runtimeOff, opt_beforeLayoutCallback) { iframe.contentWindow.name = '__AMP__off=1'; } installDocService(iframe.contentWindow, /* isSingleDoc */ true); - const ampdoc = ampdocServiceFor(iframe.contentWindow).getAmpDoc(); + const ampdoc = Services.ampdocServiceFor(iframe.contentWindow).getAmpDoc(); installExtensionsService(iframe.contentWindow); installRuntimeServices(iframe.contentWindow); installCustomElements(iframe.contentWindow); installAmpdocServices(ampdoc); registerForUnitTest(iframe.contentWindow); - resourcesForDoc(ampdoc).ampInitComplete(); + Services.resourcesForDoc(ampdoc).ampInitComplete(); // Act like no other elements were loaded by default. installStyles(iframe.contentWindow.document, cssText, () => { resolve({