@firebase/analytics 0.9.4 → 0.9.5-canary.0832dcac2

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.
@@ -65,6 +65,65 @@ const logger = new Logger('@firebase/analytics');
65
65
  * See the License for the specific language governing permissions and
66
66
  * limitations under the License.
67
67
  */
68
+ const ERRORS = {
69
+ ["already-exists" /* AnalyticsError.ALREADY_EXISTS */]: 'A Firebase Analytics instance with the appId {$id} ' +
70
+ ' already exists. ' +
71
+ 'Only one Firebase Analytics instance can be created for each appId.',
72
+ ["already-initialized" /* AnalyticsError.ALREADY_INITIALIZED */]: 'initializeAnalytics() cannot be called again with different options than those ' +
73
+ 'it was initially called with. It can be called again with the same options to ' +
74
+ 'return the existing instance, or getAnalytics() can be used ' +
75
+ 'to get a reference to the already-intialized instance.',
76
+ ["already-initialized-settings" /* AnalyticsError.ALREADY_INITIALIZED_SETTINGS */]: 'Firebase Analytics has already been initialized.' +
77
+ 'settings() must be called before initializing any Analytics instance' +
78
+ 'or it will have no effect.',
79
+ ["interop-component-reg-failed" /* AnalyticsError.INTEROP_COMPONENT_REG_FAILED */]: 'Firebase Analytics Interop Component failed to instantiate: {$reason}',
80
+ ["invalid-analytics-context" /* AnalyticsError.INVALID_ANALYTICS_CONTEXT */]: 'Firebase Analytics is not supported in this environment. ' +
81
+ 'Wrap initialization of analytics in analytics.isSupported() ' +
82
+ 'to prevent initialization in unsupported environments. Details: {$errorInfo}',
83
+ ["indexeddb-unavailable" /* AnalyticsError.INDEXEDDB_UNAVAILABLE */]: 'IndexedDB unavailable or restricted in this environment. ' +
84
+ 'Wrap initialization of analytics in analytics.isSupported() ' +
85
+ 'to prevent initialization in unsupported environments. Details: {$errorInfo}',
86
+ ["fetch-throttle" /* AnalyticsError.FETCH_THROTTLE */]: 'The config fetch request timed out while in an exponential backoff state.' +
87
+ ' Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.',
88
+ ["config-fetch-failed" /* AnalyticsError.CONFIG_FETCH_FAILED */]: 'Dynamic config fetch failed: [{$httpStatus}] {$responseMessage}',
89
+ ["no-api-key" /* AnalyticsError.NO_API_KEY */]: 'The "apiKey" field is empty in the local Firebase config. Firebase Analytics requires this field to' +
90
+ 'contain a valid API key.',
91
+ ["no-app-id" /* AnalyticsError.NO_APP_ID */]: 'The "appId" field is empty in the local Firebase config. Firebase Analytics requires this field to' +
92
+ 'contain a valid app ID.',
93
+ ["no-client-id" /* AnalyticsError.NO_CLIENT_ID */]: 'The "client_id" field is empty.',
94
+ ["invalid-gtag-resource" /* AnalyticsError.INVALID_GTAG_RESOURCE */]: 'Trusted Types detected an invalid gtag resource: {$gtagURL}.'
95
+ };
96
+ const ERROR_FACTORY = new ErrorFactory('analytics', 'Analytics', ERRORS);
97
+
98
+ /**
99
+ * @license
100
+ * Copyright 2019 Google LLC
101
+ *
102
+ * Licensed under the Apache License, Version 2.0 (the "License");
103
+ * you may not use this file except in compliance with the License.
104
+ * You may obtain a copy of the License at
105
+ *
106
+ * http://www.apache.org/licenses/LICENSE-2.0
107
+ *
108
+ * Unless required by applicable law or agreed to in writing, software
109
+ * distributed under the License is distributed on an "AS IS" BASIS,
110
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
111
+ * See the License for the specific language governing permissions and
112
+ * limitations under the License.
113
+ */
114
+ /**
115
+ * Verifies and creates a TrustedScriptURL.
116
+ */
117
+ function createGtagTrustedTypesScriptURL(url) {
118
+ if (!url.startsWith(GTAG_URL)) {
119
+ const err = ERROR_FACTORY.create("invalid-gtag-resource" /* AnalyticsError.INVALID_GTAG_RESOURCE */, {
120
+ gtagURL: url
121
+ });
122
+ logger.warn(err.message);
123
+ return '';
124
+ }
125
+ return url;
126
+ }
68
127
  /**
69
128
  * Makeshift polyfill for Promise.allSettled(). Resolves when all promises
70
129
  * have either resolved or rejected.
@@ -74,15 +133,37 @@ const logger = new Logger('@firebase/analytics');
74
133
  function promiseAllSettled(promises) {
75
134
  return Promise.all(promises.map(promise => promise.catch(e => e)));
76
135
  }
136
+ /**
137
+ * Creates a TrustedTypePolicy object that implements the rules passed as policyOptions.
138
+ *
139
+ * @param policyName A string containing the name of the policy
140
+ * @param policyOptions Object containing implementations of instance methods for TrustedTypesPolicy, see {@link https://developer.mozilla.org/en-US/docs/Web/API/TrustedTypePolicy#instance_methods
141
+ * | the TrustedTypePolicy reference documentation}.
142
+ */
143
+ function createTrustedTypesPolicy(policyName, policyOptions) {
144
+ // Create a TrustedTypes policy that we can use for updating src
145
+ // properties
146
+ let trustedTypesPolicy;
147
+ if (window.trustedTypes) {
148
+ trustedTypesPolicy = window.trustedTypes.createPolicy(policyName, policyOptions);
149
+ }
150
+ return trustedTypesPolicy;
151
+ }
77
152
  /**
78
153
  * Inserts gtag script tag into the page to asynchronously download gtag.
79
154
  * @param dataLayerName Name of datalayer (most often the default, "_dataLayer").
80
155
  */
81
156
  function insertScriptTag(dataLayerName, measurementId) {
157
+ const trustedTypesPolicy = createTrustedTypesPolicy('firebase-js-sdk-policy', {
158
+ createScriptURL: createGtagTrustedTypesScriptURL
159
+ });
82
160
  const script = document.createElement('script');
83
161
  // We are not providing an analyticsId in the URL because it would trigger a `page_view`
84
162
  // without fid. We will initialize ga-id using gtag (config) command together with fid.
85
- script.src = `${GTAG_URL}?l=${dataLayerName}&id=${measurementId}`;
163
+ const gtagScriptURL = `${GTAG_URL}?l=${dataLayerName}&id=${measurementId}`;
164
+ script.src = trustedTypesPolicy
165
+ ? trustedTypesPolicy === null || trustedTypesPolicy === void 0 ? void 0 : trustedTypesPolicy.createScriptURL(gtagScriptURL)
166
+ : gtagScriptURL;
86
167
  script.async = true;
87
168
  document.head.appendChild(script);
88
169
  }
@@ -223,24 +304,34 @@ measurementIdToAppId) {
223
304
  * @param idOrNameOrParams Measurement ID if command is EVENT/CONFIG, params if command is SET.
224
305
  * @param gtagParams Params if event is EVENT/CONFIG.
225
306
  */
226
- async function gtagWrapper(command, idOrNameOrParams, gtagParams) {
307
+ async function gtagWrapper(command, ...args) {
227
308
  try {
228
309
  // If event, check that relevant initialization promises have completed.
229
310
  if (command === "event" /* GtagCommand.EVENT */) {
311
+ const [measurementId, gtagParams] = args;
230
312
  // If EVENT, second arg must be measurementId.
231
- await gtagOnEvent(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, idOrNameOrParams, gtagParams);
313
+ await gtagOnEvent(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, measurementId, gtagParams);
232
314
  }
233
315
  else if (command === "config" /* GtagCommand.CONFIG */) {
316
+ const [measurementId, gtagParams] = args;
234
317
  // If CONFIG, second arg must be measurementId.
235
- await gtagOnConfig(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, measurementIdToAppId, idOrNameOrParams, gtagParams);
318
+ await gtagOnConfig(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, measurementIdToAppId, measurementId, gtagParams);
236
319
  }
237
320
  else if (command === "consent" /* GtagCommand.CONSENT */) {
238
- // If CONFIG, second arg must be measurementId.
321
+ const [gtagParams] = args;
239
322
  gtagCore("consent" /* GtagCommand.CONSENT */, 'update', gtagParams);
240
323
  }
241
- else {
324
+ else if (command === "get" /* GtagCommand.GET */) {
325
+ const [measurementId, fieldName, callback] = args;
326
+ gtagCore("get" /* GtagCommand.GET */, measurementId, fieldName, callback);
327
+ }
328
+ else if (command === "set" /* GtagCommand.SET */) {
329
+ const [customParams] = args;
242
330
  // If SET, second arg must be params.
243
- gtagCore("set" /* GtagCommand.SET */, idOrNameOrParams);
331
+ gtagCore("set" /* GtagCommand.SET */, customParams);
332
+ }
333
+ else {
334
+ gtagCore(command, ...args);
244
335
  }
245
336
  }
246
337
  catch (e) {
@@ -294,50 +385,6 @@ function findGtagScriptOnPage(dataLayerName) {
294
385
  return null;
295
386
  }
296
387
 
297
- /**
298
- * @license
299
- * Copyright 2019 Google LLC
300
- *
301
- * Licensed under the Apache License, Version 2.0 (the "License");
302
- * you may not use this file except in compliance with the License.
303
- * You may obtain a copy of the License at
304
- *
305
- * http://www.apache.org/licenses/LICENSE-2.0
306
- *
307
- * Unless required by applicable law or agreed to in writing, software
308
- * distributed under the License is distributed on an "AS IS" BASIS,
309
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
310
- * See the License for the specific language governing permissions and
311
- * limitations under the License.
312
- */
313
- const ERRORS = {
314
- ["already-exists" /* AnalyticsError.ALREADY_EXISTS */]: 'A Firebase Analytics instance with the appId {$id} ' +
315
- ' already exists. ' +
316
- 'Only one Firebase Analytics instance can be created for each appId.',
317
- ["already-initialized" /* AnalyticsError.ALREADY_INITIALIZED */]: 'initializeAnalytics() cannot be called again with different options than those ' +
318
- 'it was initially called with. It can be called again with the same options to ' +
319
- 'return the existing instance, or getAnalytics() can be used ' +
320
- 'to get a reference to the already-intialized instance.',
321
- ["already-initialized-settings" /* AnalyticsError.ALREADY_INITIALIZED_SETTINGS */]: 'Firebase Analytics has already been initialized.' +
322
- 'settings() must be called before initializing any Analytics instance' +
323
- 'or it will have no effect.',
324
- ["interop-component-reg-failed" /* AnalyticsError.INTEROP_COMPONENT_REG_FAILED */]: 'Firebase Analytics Interop Component failed to instantiate: {$reason}',
325
- ["invalid-analytics-context" /* AnalyticsError.INVALID_ANALYTICS_CONTEXT */]: 'Firebase Analytics is not supported in this environment. ' +
326
- 'Wrap initialization of analytics in analytics.isSupported() ' +
327
- 'to prevent initialization in unsupported environments. Details: {$errorInfo}',
328
- ["indexeddb-unavailable" /* AnalyticsError.INDEXEDDB_UNAVAILABLE */]: 'IndexedDB unavailable or restricted in this environment. ' +
329
- 'Wrap initialization of analytics in analytics.isSupported() ' +
330
- 'to prevent initialization in unsupported environments. Details: {$errorInfo}',
331
- ["fetch-throttle" /* AnalyticsError.FETCH_THROTTLE */]: 'The config fetch request timed out while in an exponential backoff state.' +
332
- ' Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.',
333
- ["config-fetch-failed" /* AnalyticsError.CONFIG_FETCH_FAILED */]: 'Dynamic config fetch failed: [{$httpStatus}] {$responseMessage}',
334
- ["no-api-key" /* AnalyticsError.NO_API_KEY */]: 'The "apiKey" field is empty in the local Firebase config. Firebase Analytics requires this field to' +
335
- 'contain a valid API key.',
336
- ["no-app-id" /* AnalyticsError.NO_APP_ID */]: 'The "appId" field is empty in the local Firebase config. Firebase Analytics requires this field to' +
337
- 'contain a valid app ID.'
338
- };
339
- const ERROR_FACTORY = new ErrorFactory('analytics', 'Analytics', ERRORS);
340
-
341
388
  /**
342
389
  * @license
343
390
  * Copyright 2020 Google LLC
@@ -678,6 +725,23 @@ async function setUserProperties$1(gtagFunction, initializationPromise, properti
678
725
  });
679
726
  }
680
727
  }
728
+ /**
729
+ * Retrieves a unique Google Analytics identifier for the web client.
730
+ * See {@link https://developers.google.com/analytics/devguides/collection/ga4/reference/config#client_id | client_id}.
731
+ *
732
+ * @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event
733
+ */
734
+ async function internalGetGoogleAnalyticsClientId(gtagFunction, initializationPromise) {
735
+ const measurementId = await initializationPromise;
736
+ return new Promise((resolve, reject) => {
737
+ gtagFunction("get" /* GtagCommand.GET */, measurementId, 'client_id', (clientId) => {
738
+ if (!clientId) {
739
+ reject(ERROR_FACTORY.create("no-client-id" /* AnalyticsError.NO_CLIENT_ID */));
740
+ }
741
+ resolve(clientId);
742
+ });
743
+ });
744
+ }
681
745
  /**
682
746
  * Set whether collection is enabled for this ID.
683
747
  *
@@ -1067,6 +1131,18 @@ function setCurrentScreen(analyticsInstance, screenName, options) {
1067
1131
  analyticsInstance = getModularInstance(analyticsInstance);
1068
1132
  setCurrentScreen$1(wrappedGtagFunction, initializationPromisesMap[analyticsInstance.app.options.appId], screenName, options).catch(e => logger.error(e));
1069
1133
  }
1134
+ /**
1135
+ * Retrieves a unique Google Analytics identifier for the web client.
1136
+ * See {@link https://developers.google.com/analytics/devguides/collection/ga4/reference/config#client_id | client_id}.
1137
+ *
1138
+ * @public
1139
+ *
1140
+ * @param app - The {@link @firebase/app#FirebaseApp} to use.
1141
+ */
1142
+ async function getGoogleAnalyticsClientId(analyticsInstance) {
1143
+ analyticsInstance = getModularInstance(analyticsInstance);
1144
+ return internalGetGoogleAnalyticsClientId(wrappedGtagFunction, initializationPromisesMap[analyticsInstance.app.options.appId]);
1145
+ }
1070
1146
  /**
1071
1147
  * Use gtag `config` command to set `user_id`.
1072
1148
  *
@@ -1152,7 +1228,7 @@ function setConsent(consentSettings) {
1152
1228
  }
1153
1229
 
1154
1230
  const name = "@firebase/analytics";
1155
- const version = "0.9.4";
1231
+ const version = "0.9.5-canary.0832dcac2";
1156
1232
 
1157
1233
  /**
1158
1234
  * Firebase Analytics
@@ -1188,5 +1264,5 @@ function registerAnalytics() {
1188
1264
  }
1189
1265
  registerAnalytics();
1190
1266
 
1191
- export { getAnalytics, initializeAnalytics, isSupported, logEvent, setAnalyticsCollectionEnabled, setConsent, setCurrentScreen, setDefaultEventParameters, setUserId, setUserProperties, settings };
1267
+ export { getAnalytics, getGoogleAnalyticsClientId, initializeAnalytics, isSupported, logEvent, setAnalyticsCollectionEnabled, setConsent, setCurrentScreen, setDefaultEventParameters, setUserId, setUserProperties, settings };
1192
1268
  //# sourceMappingURL=index.esm2017.js.map