workbox-offline-ga.dev.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. this.workbox = this.workbox || {};
  2. this.workbox.googleAnalytics = (function (exports, BackgroundSyncPlugin_js, cacheNames_js, getFriendlyURL_js, logger_js, Route_js, Router_js, NetworkFirst_js, NetworkOnly_js) {
  3. 'use strict';
  4. try {
  5. self['workbox:google-analytics:5.1.4'] && _();
  6. } catch (e) {}
  7. /*
  8. Copyright 2018 Google LLC
  9. Use of this source code is governed by an MIT-style
  10. license that can be found in the LICENSE file or at
  11. https://opensource.org/licenses/MIT.
  12. */
  13. const QUEUE_NAME = 'workbox-google-analytics';
  14. const MAX_RETENTION_TIME = 60 * 48; // Two days in minutes
  15. const GOOGLE_ANALYTICS_HOST = 'www.google-analytics.com';
  16. const GTM_HOST = 'www.googletagmanager.com';
  17. const ANALYTICS_JS_PATH = '/analytics.js';
  18. const GTAG_JS_PATH = '/gtag/js';
  19. const GTM_JS_PATH = '/gtm.js';
  20. // endpoints. Most of the time the default path (/collect) is used, but
  21. // occasionally an experimental endpoint is used when testing new features,
  22. // (e.g. /r/collect or /j/collect)
  23. const COLLECT_PATHS_REGEX = /^\/(\w+\/)?collect/;
  24. /*
  25. Copyright 2018 Google LLC
  26. Use of this source code is governed by an MIT-style
  27. license that can be found in the LICENSE file or at
  28. https://opensource.org/licenses/MIT.
  29. */
  30. /**
  31. * Creates the requestWillDequeue callback to be used with the background
  32. * sync plugin. The callback takes the failed request and adds the
  33. * `qt` param based on the current time, as well as applies any other
  34. * user-defined hit modifications.
  35. *
  36. * @param {Object} config See {@link module:workbox-google-analytics.initialize}.
  37. * @return {Function} The requestWillDequeue callback function.
  38. *
  39. * @private
  40. */
  41. const createOnSyncCallback = config => {
  42. return async ({
  43. queue
  44. }) => {
  45. let entry;
  46. while (entry = await queue.shiftRequest()) {
  47. const {
  48. request,
  49. timestamp
  50. } = entry;
  51. const url = new URL(request.url);
  52. try {
  53. // Measurement protocol requests can set their payload parameters in
  54. // either the URL query string (for GET requests) or the POST body.
  55. const params = request.method === 'POST' ? new URLSearchParams(await request.clone().text()) : url.searchParams; // Calculate the qt param, accounting for the fact that an existing
  56. // qt param may be present and should be updated rather than replaced.
  57. const originalHitTime = timestamp - (Number(params.get('qt')) || 0);
  58. const queueTime = Date.now() - originalHitTime; // Set the qt param prior to applying hitFilter or parameterOverrides.
  59. params.set('qt', String(queueTime)); // Apply `parameterOverrides`, if set.
  60. if (config.parameterOverrides) {
  61. for (const param of Object.keys(config.parameterOverrides)) {
  62. const value = config.parameterOverrides[param];
  63. params.set(param, value);
  64. }
  65. } // Apply `hitFilter`, if set.
  66. if (typeof config.hitFilter === 'function') {
  67. config.hitFilter.call(null, params);
  68. } // Retry the fetch. Ignore URL search params from the URL as they're
  69. // now in the post body.
  70. await fetch(new Request(url.origin + url.pathname, {
  71. body: params.toString(),
  72. method: 'POST',
  73. mode: 'cors',
  74. credentials: 'omit',
  75. headers: {
  76. 'Content-Type': 'text/plain'
  77. }
  78. }));
  79. if ("dev" !== 'production') {
  80. logger_js.logger.log(`Request for '${getFriendlyURL_js.getFriendlyURL(url.href)}'` + `has been replayed`);
  81. }
  82. } catch (err) {
  83. await queue.unshiftRequest(entry);
  84. {
  85. logger_js.logger.log(`Request for '${getFriendlyURL_js.getFriendlyURL(url.href)}'` + `failed to replay, putting it back in the queue.`);
  86. }
  87. throw err;
  88. }
  89. }
  90. {
  91. logger_js.logger.log(`All Google Analytics request successfully replayed; ` + `the queue is now empty!`);
  92. }
  93. };
  94. };
  95. /**
  96. * Creates GET and POST routes to catch failed Measurement Protocol hits.
  97. *
  98. * @param {BackgroundSyncPlugin} bgSyncPlugin
  99. * @return {Array<Route>} The created routes.
  100. *
  101. * @private
  102. */
  103. const createCollectRoutes = bgSyncPlugin => {
  104. const match = ({
  105. url
  106. }) => url.hostname === GOOGLE_ANALYTICS_HOST && COLLECT_PATHS_REGEX.test(url.pathname);
  107. const handler = new NetworkOnly_js.NetworkOnly({
  108. plugins: [bgSyncPlugin]
  109. });
  110. return [new Route_js.Route(match, handler, 'GET'), new Route_js.Route(match, handler, 'POST')];
  111. };
  112. /**
  113. * Creates a route with a network first strategy for the analytics.js script.
  114. *
  115. * @param {string} cacheName
  116. * @return {Route} The created route.
  117. *
  118. * @private
  119. */
  120. const createAnalyticsJsRoute = cacheName => {
  121. const match = ({
  122. url
  123. }) => url.hostname === GOOGLE_ANALYTICS_HOST && url.pathname === ANALYTICS_JS_PATH;
  124. const handler = new NetworkFirst_js.NetworkFirst({
  125. cacheName
  126. });
  127. return new Route_js.Route(match, handler, 'GET');
  128. };
  129. /**
  130. * Creates a route with a network first strategy for the gtag.js script.
  131. *
  132. * @param {string} cacheName
  133. * @return {Route} The created route.
  134. *
  135. * @private
  136. */
  137. const createGtagJsRoute = cacheName => {
  138. const match = ({
  139. url
  140. }) => url.hostname === GTM_HOST && url.pathname === GTAG_JS_PATH;
  141. const handler = new NetworkFirst_js.NetworkFirst({
  142. cacheName
  143. });
  144. return new Route_js.Route(match, handler, 'GET');
  145. };
  146. /**
  147. * Creates a route with a network first strategy for the gtm.js script.
  148. *
  149. * @param {string} cacheName
  150. * @return {Route} The created route.
  151. *
  152. * @private
  153. */
  154. const createGtmJsRoute = cacheName => {
  155. const match = ({
  156. url
  157. }) => url.hostname === GTM_HOST && url.pathname === GTM_JS_PATH;
  158. const handler = new NetworkFirst_js.NetworkFirst({
  159. cacheName
  160. });
  161. return new Route_js.Route(match, handler, 'GET');
  162. };
  163. /**
  164. * @param {Object=} [options]
  165. * @param {Object} [options.cacheName] The cache name to store and retrieve
  166. * analytics.js. Defaults to the cache names provided by `workbox-core`.
  167. * @param {Object} [options.parameterOverrides]
  168. * [Measurement Protocol parameters](https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters),
  169. * expressed as key/value pairs, to be added to replayed Google Analytics
  170. * requests. This can be used to, e.g., set a custom dimension indicating
  171. * that the request was replayed.
  172. * @param {Function} [options.hitFilter] A function that allows you to modify
  173. * the hit parameters prior to replaying
  174. * the hit. The function is invoked with the original hit's URLSearchParams
  175. * object as its only argument.
  176. *
  177. * @memberof module:workbox-google-analytics
  178. */
  179. const initialize = (options = {}) => {
  180. const cacheName = cacheNames_js.cacheNames.getGoogleAnalyticsName(options.cacheName);
  181. const bgSyncPlugin = new BackgroundSyncPlugin_js.BackgroundSyncPlugin(QUEUE_NAME, {
  182. maxRetentionTime: MAX_RETENTION_TIME,
  183. onSync: createOnSyncCallback(options)
  184. });
  185. const routes = [createGtmJsRoute(cacheName), createAnalyticsJsRoute(cacheName), createGtagJsRoute(cacheName), ...createCollectRoutes(bgSyncPlugin)];
  186. const router = new Router_js.Router();
  187. for (const route of routes) {
  188. router.registerRoute(route);
  189. }
  190. router.addFetchListener();
  191. };
  192. exports.initialize = initialize;
  193. return exports;
  194. }({}, workbox.backgroundSync, workbox.core._private, workbox.core._private, workbox.core._private, workbox.routing, workbox.routing, workbox.strategies, workbox.strategies));
  195. //# sourceMappingURL=workbox-offline-ga.dev.js.map