@serwist/google-analytics 8.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2018 Google LLC, 2019 ShadowWalker w@weiw.io https://weiw.io, 2023 Serwist
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1 @@
1
+ This module's documentation can be found at https://developers.google.com/web/tools/workbox/modules/workbox-google-analytics
@@ -0,0 +1,5 @@
1
+ import type { GoogleAnalyticsInitializeOptions } from "./initialize.js";
2
+ import { initialize } from "./initialize.js";
3
+ export { initialize };
4
+ export type { GoogleAnalyticsInitializeOptions };
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,gCAAgC,EAAE,MAAM,iBAAiB,CAAC;AACxE,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAE7C,OAAO,EAAE,UAAU,EAAE,CAAC;AACtB,YAAY,EAAE,gCAAgC,EAAE,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,166 @@
1
+ import { BackgroundSyncPlugin } from '@serwist/background-sync';
2
+ import { privateCacheNames, logger, getFriendlyURL } from '@serwist/core/internal';
3
+ import { Router, Route } from '@serwist/routing';
4
+ import { NetworkOnly, NetworkFirst } from '@serwist/strategies';
5
+
6
+ /*
7
+ Copyright 2018 Google LLC
8
+
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
+ */ const QUEUE_NAME = "serwist-google-analytics";
13
+ const MAX_RETENTION_TIME = 60 * 48; // Two days in minutes
14
+ const GOOGLE_ANALYTICS_HOST = "www.google-analytics.com";
15
+ const GTM_HOST = "www.googletagmanager.com";
16
+ const ANALYTICS_JS_PATH = "/analytics.js";
17
+ const GTAG_JS_PATH = "/gtag/js";
18
+ const GTM_JS_PATH = "/gtm.js";
19
+ // This RegExp matches all known Measurement Protocol single-hit collect
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
+ /**
26
+ * Creates the requestWillDequeue callback to be used with the background
27
+ * sync plugin. The callback takes the failed request and adds the
28
+ * `qt` param based on the current time, as well as applies any other
29
+ * user-defined hit modifications.
30
+ *
31
+ * @param config
32
+ * @returns The requestWillDequeue callback function.
33
+ * @private
34
+ */ const createOnSyncCallback = (config)=>{
35
+ return async ({ queue })=>{
36
+ let entry;
37
+ while(entry = await queue.shiftRequest()){
38
+ const { request, timestamp } = entry;
39
+ const url = new URL(request.url);
40
+ try {
41
+ // Measurement protocol requests can set their payload parameters in
42
+ // either the URL query string (for GET requests) or the POST body.
43
+ const params = request.method === "POST" ? new URLSearchParams(await request.clone().text()) : url.searchParams;
44
+ // Calculate the qt param, accounting for the fact that an existing
45
+ // qt param may be present and should be updated rather than replaced.
46
+ const originalHitTime = timestamp - (Number(params.get("qt")) || 0);
47
+ const queueTime = Date.now() - originalHitTime;
48
+ // Set the qt param prior to applying hitFilter or parameterOverrides.
49
+ params.set("qt", String(queueTime));
50
+ // Apply `parameterOverrides`, if set.
51
+ if (config.parameterOverrides) {
52
+ for (const param of Object.keys(config.parameterOverrides)){
53
+ const value = config.parameterOverrides[param];
54
+ params.set(param, value);
55
+ }
56
+ }
57
+ // Apply `hitFilter`, if set.
58
+ if (typeof config.hitFilter === "function") {
59
+ config.hitFilter.call(null, params);
60
+ }
61
+ // Retry the fetch. Ignore URL search params from the URL as they're
62
+ // now in the post body.
63
+ await fetch(new Request(url.origin + url.pathname, {
64
+ body: params.toString(),
65
+ method: "POST",
66
+ mode: "cors",
67
+ credentials: "omit",
68
+ headers: {
69
+ "Content-Type": "text/plain"
70
+ }
71
+ }));
72
+ if (process.env.NODE_ENV !== "production") {
73
+ logger.log(`Request for '${getFriendlyURL(url.href)}' ` + `has been replayed`);
74
+ }
75
+ } catch (err) {
76
+ await queue.unshiftRequest(entry);
77
+ if (process.env.NODE_ENV !== "production") {
78
+ logger.log(`Request for '${getFriendlyURL(url.href)}' ` + `failed to replay, putting it back in the queue.`);
79
+ }
80
+ throw err;
81
+ }
82
+ }
83
+ if (process.env.NODE_ENV !== "production") {
84
+ logger.log(`All Google Analytics request successfully replayed; ` + `the queue is now empty!`);
85
+ }
86
+ };
87
+ };
88
+ /**
89
+ * Creates GET and POST routes to catch failed Measurement Protocol hits.
90
+ *
91
+ * @param bgSyncPlugin
92
+ * @returns The created routes.
93
+ * @private
94
+ */ const createCollectRoutes = (bgSyncPlugin)=>{
95
+ const match = ({ url })=>url.hostname === GOOGLE_ANALYTICS_HOST && COLLECT_PATHS_REGEX.test(url.pathname);
96
+ const handler = new NetworkOnly({
97
+ plugins: [
98
+ bgSyncPlugin
99
+ ]
100
+ });
101
+ return [
102
+ new Route(match, handler, "GET"),
103
+ new Route(match, handler, "POST")
104
+ ];
105
+ };
106
+ /**
107
+ * Creates a route with a network first strategy for the analytics.js script.
108
+ *
109
+ * @param cacheName
110
+ * @returns The created route.
111
+ * @private
112
+ */ const createAnalyticsJsRoute = (cacheName)=>{
113
+ const match = ({ url })=>url.hostname === GOOGLE_ANALYTICS_HOST && url.pathname === ANALYTICS_JS_PATH;
114
+ const handler = new NetworkFirst({
115
+ cacheName
116
+ });
117
+ return new Route(match, handler, "GET");
118
+ };
119
+ /**
120
+ * Creates a route with a network first strategy for the gtag.js script.
121
+ *
122
+ * @param cacheName
123
+ * @returns The created route.
124
+ * @private
125
+ */ const createGtagJsRoute = (cacheName)=>{
126
+ const match = ({ url })=>url.hostname === GTM_HOST && url.pathname === GTAG_JS_PATH;
127
+ const handler = new NetworkFirst({
128
+ cacheName
129
+ });
130
+ return new Route(match, handler, "GET");
131
+ };
132
+ /**
133
+ * Creates a route with a network first strategy for the gtm.js script.
134
+ *
135
+ * @param cacheName
136
+ * @returns The created route.
137
+ * @private
138
+ */ const createGtmJsRoute = (cacheName)=>{
139
+ const match = ({ url })=>url.hostname === GTM_HOST && url.pathname === GTM_JS_PATH;
140
+ const handler = new NetworkFirst({
141
+ cacheName
142
+ });
143
+ return new Route(match, handler, "GET");
144
+ };
145
+ /**
146
+ * @param options
147
+ */ const initialize = (options = {})=>{
148
+ const cacheName = privateCacheNames.getGoogleAnalyticsName(options.cacheName);
149
+ const bgSyncPlugin = new BackgroundSyncPlugin(QUEUE_NAME, {
150
+ maxRetentionTime: MAX_RETENTION_TIME,
151
+ onSync: createOnSyncCallback(options)
152
+ });
153
+ const routes = [
154
+ createGtmJsRoute(cacheName),
155
+ createAnalyticsJsRoute(cacheName),
156
+ createGtagJsRoute(cacheName),
157
+ ...createCollectRoutes(bgSyncPlugin)
158
+ ];
159
+ const router = new Router();
160
+ for (const route of routes){
161
+ router.registerRoute(route);
162
+ }
163
+ router.addFetchListener();
164
+ };
165
+
166
+ export { initialize };
@@ -0,0 +1,168 @@
1
+ 'use strict';
2
+
3
+ var backgroundSync = require('@serwist/background-sync');
4
+ var internal = require('@serwist/core/internal');
5
+ var routing = require('@serwist/routing');
6
+ var strategies = require('@serwist/strategies');
7
+
8
+ /*
9
+ Copyright 2018 Google LLC
10
+
11
+ Use of this source code is governed by an MIT-style
12
+ license that can be found in the LICENSE file or at
13
+ https://opensource.org/licenses/MIT.
14
+ */ const QUEUE_NAME = "serwist-google-analytics";
15
+ const MAX_RETENTION_TIME = 60 * 48; // Two days in minutes
16
+ const GOOGLE_ANALYTICS_HOST = "www.google-analytics.com";
17
+ const GTM_HOST = "www.googletagmanager.com";
18
+ const ANALYTICS_JS_PATH = "/analytics.js";
19
+ const GTAG_JS_PATH = "/gtag/js";
20
+ const GTM_JS_PATH = "/gtm.js";
21
+ // This RegExp matches all known Measurement Protocol single-hit collect
22
+ // endpoints. Most of the time the default path (/collect) is used, but
23
+ // occasionally an experimental endpoint is used when testing new features,
24
+ // (e.g. /r/collect or /j/collect)
25
+ const COLLECT_PATHS_REGEX = /^\/(\w+\/)?collect/;
26
+
27
+ /**
28
+ * Creates the requestWillDequeue callback to be used with the background
29
+ * sync plugin. The callback takes the failed request and adds the
30
+ * `qt` param based on the current time, as well as applies any other
31
+ * user-defined hit modifications.
32
+ *
33
+ * @param config
34
+ * @returns The requestWillDequeue callback function.
35
+ * @private
36
+ */ const createOnSyncCallback = (config)=>{
37
+ return async ({ queue })=>{
38
+ let entry;
39
+ while(entry = await queue.shiftRequest()){
40
+ const { request, timestamp } = entry;
41
+ const url = new URL(request.url);
42
+ try {
43
+ // Measurement protocol requests can set their payload parameters in
44
+ // either the URL query string (for GET requests) or the POST body.
45
+ const params = request.method === "POST" ? new URLSearchParams(await request.clone().text()) : url.searchParams;
46
+ // Calculate the qt param, accounting for the fact that an existing
47
+ // qt param may be present and should be updated rather than replaced.
48
+ const originalHitTime = timestamp - (Number(params.get("qt")) || 0);
49
+ const queueTime = Date.now() - originalHitTime;
50
+ // Set the qt param prior to applying hitFilter or parameterOverrides.
51
+ params.set("qt", String(queueTime));
52
+ // Apply `parameterOverrides`, if set.
53
+ if (config.parameterOverrides) {
54
+ for (const param of Object.keys(config.parameterOverrides)){
55
+ const value = config.parameterOverrides[param];
56
+ params.set(param, value);
57
+ }
58
+ }
59
+ // Apply `hitFilter`, if set.
60
+ if (typeof config.hitFilter === "function") {
61
+ config.hitFilter.call(null, params);
62
+ }
63
+ // Retry the fetch. Ignore URL search params from the URL as they're
64
+ // now in the post body.
65
+ await fetch(new Request(url.origin + url.pathname, {
66
+ body: params.toString(),
67
+ method: "POST",
68
+ mode: "cors",
69
+ credentials: "omit",
70
+ headers: {
71
+ "Content-Type": "text/plain"
72
+ }
73
+ }));
74
+ if (process.env.NODE_ENV !== "production") {
75
+ internal.logger.log(`Request for '${internal.getFriendlyURL(url.href)}' ` + `has been replayed`);
76
+ }
77
+ } catch (err) {
78
+ await queue.unshiftRequest(entry);
79
+ if (process.env.NODE_ENV !== "production") {
80
+ internal.logger.log(`Request for '${internal.getFriendlyURL(url.href)}' ` + `failed to replay, putting it back in the queue.`);
81
+ }
82
+ throw err;
83
+ }
84
+ }
85
+ if (process.env.NODE_ENV !== "production") {
86
+ internal.logger.log(`All Google Analytics request successfully replayed; ` + `the queue is now empty!`);
87
+ }
88
+ };
89
+ };
90
+ /**
91
+ * Creates GET and POST routes to catch failed Measurement Protocol hits.
92
+ *
93
+ * @param bgSyncPlugin
94
+ * @returns The created routes.
95
+ * @private
96
+ */ const createCollectRoutes = (bgSyncPlugin)=>{
97
+ const match = ({ url })=>url.hostname === GOOGLE_ANALYTICS_HOST && COLLECT_PATHS_REGEX.test(url.pathname);
98
+ const handler = new strategies.NetworkOnly({
99
+ plugins: [
100
+ bgSyncPlugin
101
+ ]
102
+ });
103
+ return [
104
+ new routing.Route(match, handler, "GET"),
105
+ new routing.Route(match, handler, "POST")
106
+ ];
107
+ };
108
+ /**
109
+ * Creates a route with a network first strategy for the analytics.js script.
110
+ *
111
+ * @param cacheName
112
+ * @returns The created route.
113
+ * @private
114
+ */ const createAnalyticsJsRoute = (cacheName)=>{
115
+ const match = ({ url })=>url.hostname === GOOGLE_ANALYTICS_HOST && url.pathname === ANALYTICS_JS_PATH;
116
+ const handler = new strategies.NetworkFirst({
117
+ cacheName
118
+ });
119
+ return new routing.Route(match, handler, "GET");
120
+ };
121
+ /**
122
+ * Creates a route with a network first strategy for the gtag.js script.
123
+ *
124
+ * @param cacheName
125
+ * @returns The created route.
126
+ * @private
127
+ */ const createGtagJsRoute = (cacheName)=>{
128
+ const match = ({ url })=>url.hostname === GTM_HOST && url.pathname === GTAG_JS_PATH;
129
+ const handler = new strategies.NetworkFirst({
130
+ cacheName
131
+ });
132
+ return new routing.Route(match, handler, "GET");
133
+ };
134
+ /**
135
+ * Creates a route with a network first strategy for the gtm.js script.
136
+ *
137
+ * @param cacheName
138
+ * @returns The created route.
139
+ * @private
140
+ */ const createGtmJsRoute = (cacheName)=>{
141
+ const match = ({ url })=>url.hostname === GTM_HOST && url.pathname === GTM_JS_PATH;
142
+ const handler = new strategies.NetworkFirst({
143
+ cacheName
144
+ });
145
+ return new routing.Route(match, handler, "GET");
146
+ };
147
+ /**
148
+ * @param options
149
+ */ const initialize = (options = {})=>{
150
+ const cacheName = internal.privateCacheNames.getGoogleAnalyticsName(options.cacheName);
151
+ const bgSyncPlugin = new backgroundSync.BackgroundSyncPlugin(QUEUE_NAME, {
152
+ maxRetentionTime: MAX_RETENTION_TIME,
153
+ onSync: createOnSyncCallback(options)
154
+ });
155
+ const routes = [
156
+ createGtmJsRoute(cacheName),
157
+ createAnalyticsJsRoute(cacheName),
158
+ createGtagJsRoute(cacheName),
159
+ ...createCollectRoutes(bgSyncPlugin)
160
+ ];
161
+ const router = new routing.Router();
162
+ for (const route of routes){
163
+ router.registerRoute(route);
164
+ }
165
+ router.addFetchListener();
166
+ };
167
+
168
+ exports.initialize = initialize;
@@ -0,0 +1,27 @@
1
+ export interface GoogleAnalyticsInitializeOptions {
2
+ /**
3
+ * The cache name to store and retrieve analytics.js. Defaults to the cache names provided by `@serwist/core`.
4
+ */
5
+ cacheName?: string;
6
+ /**
7
+ * [Measurement Protocol parameters](https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters),
8
+ * expressed as key/value pairs, to be added to replayed Google Analytics
9
+ * requests. This can be used to, e.g., set a custom dimension indicating
10
+ * that the request was replayed.
11
+ */
12
+ parameterOverrides?: {
13
+ [paramName: string]: string;
14
+ };
15
+ /**
16
+ * A function that allows you to modify the hit parameters prior to replaying
17
+ * the hit. The function is invoked with the original hit's URLSearchParams
18
+ * object as its only argument.
19
+ */
20
+ hitFilter?: (params: URLSearchParams) => void;
21
+ }
22
+ /**
23
+ * @param options
24
+ */
25
+ declare const initialize: (options?: GoogleAnalyticsInitializeOptions) => void;
26
+ export { initialize };
27
+ //# sourceMappingURL=initialize.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"initialize.d.ts","sourceRoot":"","sources":["../src/initialize.ts"],"names":[],"mappings":"AA0BA,MAAM,WAAW,gCAAgC;IAC/C;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;;;OAKG;IACH,kBAAkB,CAAC,EAAE;QAAE,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAAA;KAAE,CAAC;IACrD;;;;OAIG;IACH,SAAS,CAAC,EAAE,CAAC,MAAM,EAAE,eAAe,KAAK,IAAI,CAAC;CAC/C;AAyID;;GAEG;AACH,QAAA,MAAM,UAAU,aAAa,gCAAgC,KAAQ,IAgBpE,CAAC;AAEF,OAAO,EAAE,UAAU,EAAE,CAAC"}
@@ -0,0 +1,166 @@
1
+ import { BackgroundSyncPlugin } from '@serwist/background-sync';
2
+ import { privateCacheNames, logger, getFriendlyURL } from '@serwist/core/internal';
3
+ import { Router, Route } from '@serwist/routing';
4
+ import { NetworkOnly, NetworkFirst } from '@serwist/strategies';
5
+
6
+ /*
7
+ Copyright 2018 Google LLC
8
+
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
+ */ const QUEUE_NAME = "serwist-google-analytics";
13
+ const MAX_RETENTION_TIME = 60 * 48; // Two days in minutes
14
+ const GOOGLE_ANALYTICS_HOST = "www.google-analytics.com";
15
+ const GTM_HOST = "www.googletagmanager.com";
16
+ const ANALYTICS_JS_PATH = "/analytics.js";
17
+ const GTAG_JS_PATH = "/gtag/js";
18
+ const GTM_JS_PATH = "/gtm.js";
19
+ // This RegExp matches all known Measurement Protocol single-hit collect
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
+ /**
26
+ * Creates the requestWillDequeue callback to be used with the background
27
+ * sync plugin. The callback takes the failed request and adds the
28
+ * `qt` param based on the current time, as well as applies any other
29
+ * user-defined hit modifications.
30
+ *
31
+ * @param config
32
+ * @returns The requestWillDequeue callback function.
33
+ * @private
34
+ */ const createOnSyncCallback = (config)=>{
35
+ return async ({ queue })=>{
36
+ let entry;
37
+ while(entry = await queue.shiftRequest()){
38
+ const { request, timestamp } = entry;
39
+ const url = new URL(request.url);
40
+ try {
41
+ // Measurement protocol requests can set their payload parameters in
42
+ // either the URL query string (for GET requests) or the POST body.
43
+ const params = request.method === "POST" ? new URLSearchParams(await request.clone().text()) : url.searchParams;
44
+ // Calculate the qt param, accounting for the fact that an existing
45
+ // qt param may be present and should be updated rather than replaced.
46
+ const originalHitTime = timestamp - (Number(params.get("qt")) || 0);
47
+ const queueTime = Date.now() - originalHitTime;
48
+ // Set the qt param prior to applying hitFilter or parameterOverrides.
49
+ params.set("qt", String(queueTime));
50
+ // Apply `parameterOverrides`, if set.
51
+ if (config.parameterOverrides) {
52
+ for (const param of Object.keys(config.parameterOverrides)){
53
+ const value = config.parameterOverrides[param];
54
+ params.set(param, value);
55
+ }
56
+ }
57
+ // Apply `hitFilter`, if set.
58
+ if (typeof config.hitFilter === "function") {
59
+ config.hitFilter.call(null, params);
60
+ }
61
+ // Retry the fetch. Ignore URL search params from the URL as they're
62
+ // now in the post body.
63
+ await fetch(new Request(url.origin + url.pathname, {
64
+ body: params.toString(),
65
+ method: "POST",
66
+ mode: "cors",
67
+ credentials: "omit",
68
+ headers: {
69
+ "Content-Type": "text/plain"
70
+ }
71
+ }));
72
+ if (process.env.NODE_ENV !== "production") {
73
+ logger.log(`Request for '${getFriendlyURL(url.href)}' ` + `has been replayed`);
74
+ }
75
+ } catch (err) {
76
+ await queue.unshiftRequest(entry);
77
+ if (process.env.NODE_ENV !== "production") {
78
+ logger.log(`Request for '${getFriendlyURL(url.href)}' ` + `failed to replay, putting it back in the queue.`);
79
+ }
80
+ throw err;
81
+ }
82
+ }
83
+ if (process.env.NODE_ENV !== "production") {
84
+ logger.log(`All Google Analytics request successfully replayed; ` + `the queue is now empty!`);
85
+ }
86
+ };
87
+ };
88
+ /**
89
+ * Creates GET and POST routes to catch failed Measurement Protocol hits.
90
+ *
91
+ * @param bgSyncPlugin
92
+ * @returns The created routes.
93
+ * @private
94
+ */ const createCollectRoutes = (bgSyncPlugin)=>{
95
+ const match = ({ url })=>url.hostname === GOOGLE_ANALYTICS_HOST && COLLECT_PATHS_REGEX.test(url.pathname);
96
+ const handler = new NetworkOnly({
97
+ plugins: [
98
+ bgSyncPlugin
99
+ ]
100
+ });
101
+ return [
102
+ new Route(match, handler, "GET"),
103
+ new Route(match, handler, "POST")
104
+ ];
105
+ };
106
+ /**
107
+ * Creates a route with a network first strategy for the analytics.js script.
108
+ *
109
+ * @param cacheName
110
+ * @returns The created route.
111
+ * @private
112
+ */ const createAnalyticsJsRoute = (cacheName)=>{
113
+ const match = ({ url })=>url.hostname === GOOGLE_ANALYTICS_HOST && url.pathname === ANALYTICS_JS_PATH;
114
+ const handler = new NetworkFirst({
115
+ cacheName
116
+ });
117
+ return new Route(match, handler, "GET");
118
+ };
119
+ /**
120
+ * Creates a route with a network first strategy for the gtag.js script.
121
+ *
122
+ * @param cacheName
123
+ * @returns The created route.
124
+ * @private
125
+ */ const createGtagJsRoute = (cacheName)=>{
126
+ const match = ({ url })=>url.hostname === GTM_HOST && url.pathname === GTAG_JS_PATH;
127
+ const handler = new NetworkFirst({
128
+ cacheName
129
+ });
130
+ return new Route(match, handler, "GET");
131
+ };
132
+ /**
133
+ * Creates a route with a network first strategy for the gtm.js script.
134
+ *
135
+ * @param cacheName
136
+ * @returns The created route.
137
+ * @private
138
+ */ const createGtmJsRoute = (cacheName)=>{
139
+ const match = ({ url })=>url.hostname === GTM_HOST && url.pathname === GTM_JS_PATH;
140
+ const handler = new NetworkFirst({
141
+ cacheName
142
+ });
143
+ return new Route(match, handler, "GET");
144
+ };
145
+ /**
146
+ * @param options
147
+ */ const initialize = (options = {})=>{
148
+ const cacheName = privateCacheNames.getGoogleAnalyticsName(options.cacheName);
149
+ const bgSyncPlugin = new BackgroundSyncPlugin(QUEUE_NAME, {
150
+ maxRetentionTime: MAX_RETENTION_TIME,
151
+ onSync: createOnSyncCallback(options)
152
+ });
153
+ const routes = [
154
+ createGtmJsRoute(cacheName),
155
+ createAnalyticsJsRoute(cacheName),
156
+ createGtagJsRoute(cacheName),
157
+ ...createCollectRoutes(bgSyncPlugin)
158
+ ];
159
+ const router = new Router();
160
+ for (const route of routes){
161
+ router.registerRoute(route);
162
+ }
163
+ router.addFetchListener();
164
+ };
165
+
166
+ export { initialize };
@@ -0,0 +1,168 @@
1
+ 'use strict';
2
+
3
+ var backgroundSync = require('@serwist/background-sync');
4
+ var internal = require('@serwist/core/internal');
5
+ var routing = require('@serwist/routing');
6
+ var strategies = require('@serwist/strategies');
7
+
8
+ /*
9
+ Copyright 2018 Google LLC
10
+
11
+ Use of this source code is governed by an MIT-style
12
+ license that can be found in the LICENSE file or at
13
+ https://opensource.org/licenses/MIT.
14
+ */ const QUEUE_NAME = "serwist-google-analytics";
15
+ const MAX_RETENTION_TIME = 60 * 48; // Two days in minutes
16
+ const GOOGLE_ANALYTICS_HOST = "www.google-analytics.com";
17
+ const GTM_HOST = "www.googletagmanager.com";
18
+ const ANALYTICS_JS_PATH = "/analytics.js";
19
+ const GTAG_JS_PATH = "/gtag/js";
20
+ const GTM_JS_PATH = "/gtm.js";
21
+ // This RegExp matches all known Measurement Protocol single-hit collect
22
+ // endpoints. Most of the time the default path (/collect) is used, but
23
+ // occasionally an experimental endpoint is used when testing new features,
24
+ // (e.g. /r/collect or /j/collect)
25
+ const COLLECT_PATHS_REGEX = /^\/(\w+\/)?collect/;
26
+
27
+ /**
28
+ * Creates the requestWillDequeue callback to be used with the background
29
+ * sync plugin. The callback takes the failed request and adds the
30
+ * `qt` param based on the current time, as well as applies any other
31
+ * user-defined hit modifications.
32
+ *
33
+ * @param config
34
+ * @returns The requestWillDequeue callback function.
35
+ * @private
36
+ */ const createOnSyncCallback = (config)=>{
37
+ return async ({ queue })=>{
38
+ let entry;
39
+ while(entry = await queue.shiftRequest()){
40
+ const { request, timestamp } = entry;
41
+ const url = new URL(request.url);
42
+ try {
43
+ // Measurement protocol requests can set their payload parameters in
44
+ // either the URL query string (for GET requests) or the POST body.
45
+ const params = request.method === "POST" ? new URLSearchParams(await request.clone().text()) : url.searchParams;
46
+ // Calculate the qt param, accounting for the fact that an existing
47
+ // qt param may be present and should be updated rather than replaced.
48
+ const originalHitTime = timestamp - (Number(params.get("qt")) || 0);
49
+ const queueTime = Date.now() - originalHitTime;
50
+ // Set the qt param prior to applying hitFilter or parameterOverrides.
51
+ params.set("qt", String(queueTime));
52
+ // Apply `parameterOverrides`, if set.
53
+ if (config.parameterOverrides) {
54
+ for (const param of Object.keys(config.parameterOverrides)){
55
+ const value = config.parameterOverrides[param];
56
+ params.set(param, value);
57
+ }
58
+ }
59
+ // Apply `hitFilter`, if set.
60
+ if (typeof config.hitFilter === "function") {
61
+ config.hitFilter.call(null, params);
62
+ }
63
+ // Retry the fetch. Ignore URL search params from the URL as they're
64
+ // now in the post body.
65
+ await fetch(new Request(url.origin + url.pathname, {
66
+ body: params.toString(),
67
+ method: "POST",
68
+ mode: "cors",
69
+ credentials: "omit",
70
+ headers: {
71
+ "Content-Type": "text/plain"
72
+ }
73
+ }));
74
+ if (process.env.NODE_ENV !== "production") {
75
+ internal.logger.log(`Request for '${internal.getFriendlyURL(url.href)}' ` + `has been replayed`);
76
+ }
77
+ } catch (err) {
78
+ await queue.unshiftRequest(entry);
79
+ if (process.env.NODE_ENV !== "production") {
80
+ internal.logger.log(`Request for '${internal.getFriendlyURL(url.href)}' ` + `failed to replay, putting it back in the queue.`);
81
+ }
82
+ throw err;
83
+ }
84
+ }
85
+ if (process.env.NODE_ENV !== "production") {
86
+ internal.logger.log(`All Google Analytics request successfully replayed; ` + `the queue is now empty!`);
87
+ }
88
+ };
89
+ };
90
+ /**
91
+ * Creates GET and POST routes to catch failed Measurement Protocol hits.
92
+ *
93
+ * @param bgSyncPlugin
94
+ * @returns The created routes.
95
+ * @private
96
+ */ const createCollectRoutes = (bgSyncPlugin)=>{
97
+ const match = ({ url })=>url.hostname === GOOGLE_ANALYTICS_HOST && COLLECT_PATHS_REGEX.test(url.pathname);
98
+ const handler = new strategies.NetworkOnly({
99
+ plugins: [
100
+ bgSyncPlugin
101
+ ]
102
+ });
103
+ return [
104
+ new routing.Route(match, handler, "GET"),
105
+ new routing.Route(match, handler, "POST")
106
+ ];
107
+ };
108
+ /**
109
+ * Creates a route with a network first strategy for the analytics.js script.
110
+ *
111
+ * @param cacheName
112
+ * @returns The created route.
113
+ * @private
114
+ */ const createAnalyticsJsRoute = (cacheName)=>{
115
+ const match = ({ url })=>url.hostname === GOOGLE_ANALYTICS_HOST && url.pathname === ANALYTICS_JS_PATH;
116
+ const handler = new strategies.NetworkFirst({
117
+ cacheName
118
+ });
119
+ return new routing.Route(match, handler, "GET");
120
+ };
121
+ /**
122
+ * Creates a route with a network first strategy for the gtag.js script.
123
+ *
124
+ * @param cacheName
125
+ * @returns The created route.
126
+ * @private
127
+ */ const createGtagJsRoute = (cacheName)=>{
128
+ const match = ({ url })=>url.hostname === GTM_HOST && url.pathname === GTAG_JS_PATH;
129
+ const handler = new strategies.NetworkFirst({
130
+ cacheName
131
+ });
132
+ return new routing.Route(match, handler, "GET");
133
+ };
134
+ /**
135
+ * Creates a route with a network first strategy for the gtm.js script.
136
+ *
137
+ * @param cacheName
138
+ * @returns The created route.
139
+ * @private
140
+ */ const createGtmJsRoute = (cacheName)=>{
141
+ const match = ({ url })=>url.hostname === GTM_HOST && url.pathname === GTM_JS_PATH;
142
+ const handler = new strategies.NetworkFirst({
143
+ cacheName
144
+ });
145
+ return new routing.Route(match, handler, "GET");
146
+ };
147
+ /**
148
+ * @param options
149
+ */ const initialize = (options = {})=>{
150
+ const cacheName = internal.privateCacheNames.getGoogleAnalyticsName(options.cacheName);
151
+ const bgSyncPlugin = new backgroundSync.BackgroundSyncPlugin(QUEUE_NAME, {
152
+ maxRetentionTime: MAX_RETENTION_TIME,
153
+ onSync: createOnSyncCallback(options)
154
+ });
155
+ const routes = [
156
+ createGtmJsRoute(cacheName),
157
+ createAnalyticsJsRoute(cacheName),
158
+ createGtagJsRoute(cacheName),
159
+ ...createCollectRoutes(bgSyncPlugin)
160
+ ];
161
+ const router = new routing.Router();
162
+ for (const route of routes){
163
+ router.registerRoute(route);
164
+ }
165
+ router.addFetchListener();
166
+ };
167
+
168
+ exports.initialize = initialize;
@@ -0,0 +1,10 @@
1
+ export declare const QUEUE_NAME = "serwist-google-analytics";
2
+ export declare const MAX_RETENTION_TIME: number;
3
+ export declare const GOOGLE_ANALYTICS_HOST = "www.google-analytics.com";
4
+ export declare const GTM_HOST = "www.googletagmanager.com";
5
+ export declare const ANALYTICS_JS_PATH = "/analytics.js";
6
+ export declare const GTAG_JS_PATH = "/gtag/js";
7
+ export declare const GTM_JS_PATH = "/gtm.js";
8
+ export declare const COLLECT_DEFAULT_PATH = "/collect";
9
+ export declare const COLLECT_PATHS_REGEX: RegExp;
10
+ //# sourceMappingURL=constants.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../src/utils/constants.ts"],"names":[],"mappings":"AAQA,eAAO,MAAM,UAAU,6BAA6B,CAAC;AACrD,eAAO,MAAM,kBAAkB,QAAU,CAAC;AAC1C,eAAO,MAAM,qBAAqB,6BAA6B,CAAC;AAChE,eAAO,MAAM,QAAQ,6BAA6B,CAAC;AACnD,eAAO,MAAM,iBAAiB,kBAAkB,CAAC;AACjD,eAAO,MAAM,YAAY,aAAa,CAAC;AACvC,eAAO,MAAM,WAAW,YAAY,CAAC;AACrC,eAAO,MAAM,oBAAoB,aAAa,CAAC;AAM/C,eAAO,MAAM,mBAAmB,QAAuB,CAAC"}
package/package.json ADDED
@@ -0,0 +1,55 @@
1
+ {
2
+ "name": "@serwist/google-analytics",
3
+ "version": "8.0.0",
4
+ "type": "module",
5
+ "description": "Queues failed requests and uses the Background Sync API to replay them when the network is available",
6
+ "files": [
7
+ "dist",
8
+ "!dist/**/dts"
9
+ ],
10
+ "keywords": [
11
+ "serwist",
12
+ "serwistjs",
13
+ "service worker",
14
+ "sw",
15
+ "offline",
16
+ "google",
17
+ "analytics"
18
+ ],
19
+ "author": "Google's Web DevRel Team, Serwist's Team",
20
+ "license": "MIT",
21
+ "repository": "serwist/serwist",
22
+ "bugs": "https://github.com/serwist/serwist/issues",
23
+ "homepage": "https://ducanh-next-pwa.vercel.app",
24
+ "module": "./dist/index.js",
25
+ "main": "./dist/index.old.cjs",
26
+ "types": "./dist/index.d.ts",
27
+ "exports": {
28
+ ".": {
29
+ "import": "./dist/index.js",
30
+ "require": "./dist/index.old.cjs",
31
+ "types": "./dist/index.d.ts"
32
+ },
33
+ "./initialize": {
34
+ "import": "./dist/initialize.js",
35
+ "require": "./dist/initialize.old.cjs",
36
+ "types": "./dist/initialize.d.ts"
37
+ },
38
+ "./package.json": "./package.json"
39
+ },
40
+ "dependencies": {
41
+ "@serwist/background-sync": "8.0.0",
42
+ "@serwist/core": "8.0.0",
43
+ "@serwist/routing": "8.0.0",
44
+ "@serwist/strategies": "8.0.0"
45
+ },
46
+ "devDependencies": {
47
+ "rollup": "3.28.1",
48
+ "@serwist/constants": "8.0.0"
49
+ },
50
+ "scripts": {
51
+ "build": "rimraf dist && cross-env NODE_ENV=production rollup --config rollup.config.js",
52
+ "lint": "eslint src --ext ts,tsx,js,jsx,cjs,mjs",
53
+ "typecheck": "tsc"
54
+ }
55
+ }