@firebase/analytics 0.9.4 → 0.9.5-canary.0a27d2fbf

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/dist/index.cjs.js CHANGED
@@ -70,6 +70,66 @@ var logger = new logger$1.Logger('@firebase/analytics');
70
70
  * See the License for the specific language governing permissions and
71
71
  * limitations under the License.
72
72
  */
73
+ var _a;
74
+ var ERRORS = (_a = {},
75
+ _a["already-exists" /* AnalyticsError.ALREADY_EXISTS */] = 'A Firebase Analytics instance with the appId {$id} ' +
76
+ ' already exists. ' +
77
+ 'Only one Firebase Analytics instance can be created for each appId.',
78
+ _a["already-initialized" /* AnalyticsError.ALREADY_INITIALIZED */] = 'initializeAnalytics() cannot be called again with different options than those ' +
79
+ 'it was initially called with. It can be called again with the same options to ' +
80
+ 'return the existing instance, or getAnalytics() can be used ' +
81
+ 'to get a reference to the already-intialized instance.',
82
+ _a["already-initialized-settings" /* AnalyticsError.ALREADY_INITIALIZED_SETTINGS */] = 'Firebase Analytics has already been initialized.' +
83
+ 'settings() must be called before initializing any Analytics instance' +
84
+ 'or it will have no effect.',
85
+ _a["interop-component-reg-failed" /* AnalyticsError.INTEROP_COMPONENT_REG_FAILED */] = 'Firebase Analytics Interop Component failed to instantiate: {$reason}',
86
+ _a["invalid-analytics-context" /* AnalyticsError.INVALID_ANALYTICS_CONTEXT */] = 'Firebase Analytics is not supported in this environment. ' +
87
+ 'Wrap initialization of analytics in analytics.isSupported() ' +
88
+ 'to prevent initialization in unsupported environments. Details: {$errorInfo}',
89
+ _a["indexeddb-unavailable" /* AnalyticsError.INDEXEDDB_UNAVAILABLE */] = 'IndexedDB unavailable or restricted in this environment. ' +
90
+ 'Wrap initialization of analytics in analytics.isSupported() ' +
91
+ 'to prevent initialization in unsupported environments. Details: {$errorInfo}',
92
+ _a["fetch-throttle" /* AnalyticsError.FETCH_THROTTLE */] = 'The config fetch request timed out while in an exponential backoff state.' +
93
+ ' Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.',
94
+ _a["config-fetch-failed" /* AnalyticsError.CONFIG_FETCH_FAILED */] = 'Dynamic config fetch failed: [{$httpStatus}] {$responseMessage}',
95
+ _a["no-api-key" /* AnalyticsError.NO_API_KEY */] = 'The "apiKey" field is empty in the local Firebase config. Firebase Analytics requires this field to' +
96
+ 'contain a valid API key.',
97
+ _a["no-app-id" /* AnalyticsError.NO_APP_ID */] = 'The "appId" field is empty in the local Firebase config. Firebase Analytics requires this field to' +
98
+ 'contain a valid app ID.',
99
+ _a["no-client-id" /* AnalyticsError.NO_CLIENT_ID */] = 'The "client_id" field is empty.',
100
+ _a["invalid-gtag-resource" /* AnalyticsError.INVALID_GTAG_RESOURCE */] = 'Trusted Types detected an invalid gtag resource: {$gtagURL}.',
101
+ _a);
102
+ var ERROR_FACTORY = new util.ErrorFactory('analytics', 'Analytics', ERRORS);
103
+
104
+ /**
105
+ * @license
106
+ * Copyright 2019 Google LLC
107
+ *
108
+ * Licensed under the Apache License, Version 2.0 (the "License");
109
+ * you may not use this file except in compliance with the License.
110
+ * You may obtain a copy of the License at
111
+ *
112
+ * http://www.apache.org/licenses/LICENSE-2.0
113
+ *
114
+ * Unless required by applicable law or agreed to in writing, software
115
+ * distributed under the License is distributed on an "AS IS" BASIS,
116
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
117
+ * See the License for the specific language governing permissions and
118
+ * limitations under the License.
119
+ */
120
+ /**
121
+ * Verifies and creates a TrustedScriptURL.
122
+ */
123
+ function createGtagTrustedTypesScriptURL(url) {
124
+ if (!url.startsWith(GTAG_URL)) {
125
+ var err = ERROR_FACTORY.create("invalid-gtag-resource" /* AnalyticsError.INVALID_GTAG_RESOURCE */, {
126
+ gtagURL: url
127
+ });
128
+ logger.warn(err.message);
129
+ return '';
130
+ }
131
+ return url;
132
+ }
73
133
  /**
74
134
  * Makeshift polyfill for Promise.allSettled(). Resolves when all promises
75
135
  * have either resolved or rejected.
@@ -79,15 +139,37 @@ var logger = new logger$1.Logger('@firebase/analytics');
79
139
  function promiseAllSettled(promises) {
80
140
  return Promise.all(promises.map(function (promise) { return promise.catch(function (e) { return e; }); }));
81
141
  }
142
+ /**
143
+ * Creates a TrustedTypePolicy object that implements the rules passed as policyOptions.
144
+ *
145
+ * @param policyName A string containing the name of the policy
146
+ * @param policyOptions Object containing implementations of instance methods for TrustedTypesPolicy, see {@link https://developer.mozilla.org/en-US/docs/Web/API/TrustedTypePolicy#instance_methods
147
+ * | the TrustedTypePolicy reference documentation}.
148
+ */
149
+ function createTrustedTypesPolicy(policyName, policyOptions) {
150
+ // Create a TrustedTypes policy that we can use for updating src
151
+ // properties
152
+ var trustedTypesPolicy;
153
+ if (window.trustedTypes) {
154
+ trustedTypesPolicy = window.trustedTypes.createPolicy(policyName, policyOptions);
155
+ }
156
+ return trustedTypesPolicy;
157
+ }
82
158
  /**
83
159
  * Inserts gtag script tag into the page to asynchronously download gtag.
84
160
  * @param dataLayerName Name of datalayer (most often the default, "_dataLayer").
85
161
  */
86
162
  function insertScriptTag(dataLayerName, measurementId) {
163
+ var trustedTypesPolicy = createTrustedTypesPolicy('firebase-js-sdk-policy', {
164
+ createScriptURL: createGtagTrustedTypesScriptURL
165
+ });
87
166
  var script = document.createElement('script');
88
167
  // We are not providing an analyticsId in the URL because it would trigger a `page_view`
89
168
  // without fid. We will initialize ga-id using gtag (config) command together with fid.
90
- script.src = "".concat(GTAG_URL, "?l=").concat(dataLayerName, "&id=").concat(measurementId);
169
+ var gtagScriptURL = "".concat(GTAG_URL, "?l=").concat(dataLayerName, "&id=").concat(measurementId);
170
+ script.src = trustedTypesPolicy
171
+ ? trustedTypesPolicy === null || trustedTypesPolicy === void 0 ? void 0 : trustedTypesPolicy.createScriptURL(gtagScriptURL)
172
+ : gtagScriptURL;
91
173
  script.async = true;
92
174
  document.head.appendChild(script);
93
175
  }
@@ -258,36 +340,50 @@ measurementIdToAppId) {
258
340
  * @param idOrNameOrParams Measurement ID if command is EVENT/CONFIG, params if command is SET.
259
341
  * @param gtagParams Params if event is EVENT/CONFIG.
260
342
  */
261
- function gtagWrapper(command, idOrNameOrParams, gtagParams) {
343
+ function gtagWrapper(command) {
344
+ var args = [];
345
+ for (var _i = 1; _i < arguments.length; _i++) {
346
+ args[_i - 1] = arguments[_i];
347
+ }
262
348
  return tslib.__awaiter(this, void 0, void 0, function () {
263
- var e_3;
349
+ var measurementId, gtagParams, measurementId, gtagParams, gtagParams, measurementId, fieldName, callback, customParams, e_3;
264
350
  return tslib.__generator(this, function (_a) {
265
351
  switch (_a.label) {
266
352
  case 0:
267
353
  _a.trys.push([0, 6, , 7]);
268
354
  if (!(command === "event" /* GtagCommand.EVENT */)) return [3 /*break*/, 2];
355
+ measurementId = args[0], gtagParams = args[1];
269
356
  // If EVENT, second arg must be measurementId.
270
- return [4 /*yield*/, gtagOnEvent(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, idOrNameOrParams, gtagParams)];
357
+ return [4 /*yield*/, gtagOnEvent(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, measurementId, gtagParams)];
271
358
  case 1:
272
359
  // If EVENT, second arg must be measurementId.
273
360
  _a.sent();
274
361
  return [3 /*break*/, 5];
275
362
  case 2:
276
363
  if (!(command === "config" /* GtagCommand.CONFIG */)) return [3 /*break*/, 4];
364
+ measurementId = args[0], gtagParams = args[1];
277
365
  // If CONFIG, second arg must be measurementId.
278
- return [4 /*yield*/, gtagOnConfig(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, measurementIdToAppId, idOrNameOrParams, gtagParams)];
366
+ return [4 /*yield*/, gtagOnConfig(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, measurementIdToAppId, measurementId, gtagParams)];
279
367
  case 3:
280
368
  // If CONFIG, second arg must be measurementId.
281
369
  _a.sent();
282
370
  return [3 /*break*/, 5];
283
371
  case 4:
284
372
  if (command === "consent" /* GtagCommand.CONSENT */) {
285
- // If CONFIG, second arg must be measurementId.
373
+ gtagParams = args[0];
286
374
  gtagCore("consent" /* GtagCommand.CONSENT */, 'update', gtagParams);
287
375
  }
288
- else {
376
+ else if (command === "get" /* GtagCommand.GET */) {
377
+ measurementId = args[0], fieldName = args[1], callback = args[2];
378
+ gtagCore("get" /* GtagCommand.GET */, measurementId, fieldName, callback);
379
+ }
380
+ else if (command === "set" /* GtagCommand.SET */) {
381
+ customParams = args[0];
289
382
  // If SET, second arg must be params.
290
- gtagCore("set" /* GtagCommand.SET */, idOrNameOrParams);
383
+ gtagCore("set" /* GtagCommand.SET */, customParams);
384
+ }
385
+ else {
386
+ gtagCore.apply(void 0, tslib.__spreadArray([command], args, false));
291
387
  }
292
388
  _a.label = 5;
293
389
  case 5: return [3 /*break*/, 7];
@@ -348,51 +444,6 @@ function findGtagScriptOnPage(dataLayerName) {
348
444
  return null;
349
445
  }
350
446
 
351
- /**
352
- * @license
353
- * Copyright 2019 Google LLC
354
- *
355
- * Licensed under the Apache License, Version 2.0 (the "License");
356
- * you may not use this file except in compliance with the License.
357
- * You may obtain a copy of the License at
358
- *
359
- * http://www.apache.org/licenses/LICENSE-2.0
360
- *
361
- * Unless required by applicable law or agreed to in writing, software
362
- * distributed under the License is distributed on an "AS IS" BASIS,
363
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
364
- * See the License for the specific language governing permissions and
365
- * limitations under the License.
366
- */
367
- var _a;
368
- var ERRORS = (_a = {},
369
- _a["already-exists" /* AnalyticsError.ALREADY_EXISTS */] = 'A Firebase Analytics instance with the appId {$id} ' +
370
- ' already exists. ' +
371
- 'Only one Firebase Analytics instance can be created for each appId.',
372
- _a["already-initialized" /* AnalyticsError.ALREADY_INITIALIZED */] = 'initializeAnalytics() cannot be called again with different options than those ' +
373
- 'it was initially called with. It can be called again with the same options to ' +
374
- 'return the existing instance, or getAnalytics() can be used ' +
375
- 'to get a reference to the already-intialized instance.',
376
- _a["already-initialized-settings" /* AnalyticsError.ALREADY_INITIALIZED_SETTINGS */] = 'Firebase Analytics has already been initialized.' +
377
- 'settings() must be called before initializing any Analytics instance' +
378
- 'or it will have no effect.',
379
- _a["interop-component-reg-failed" /* AnalyticsError.INTEROP_COMPONENT_REG_FAILED */] = 'Firebase Analytics Interop Component failed to instantiate: {$reason}',
380
- _a["invalid-analytics-context" /* AnalyticsError.INVALID_ANALYTICS_CONTEXT */] = 'Firebase Analytics is not supported in this environment. ' +
381
- 'Wrap initialization of analytics in analytics.isSupported() ' +
382
- 'to prevent initialization in unsupported environments. Details: {$errorInfo}',
383
- _a["indexeddb-unavailable" /* AnalyticsError.INDEXEDDB_UNAVAILABLE */] = 'IndexedDB unavailable or restricted in this environment. ' +
384
- 'Wrap initialization of analytics in analytics.isSupported() ' +
385
- 'to prevent initialization in unsupported environments. Details: {$errorInfo}',
386
- _a["fetch-throttle" /* AnalyticsError.FETCH_THROTTLE */] = 'The config fetch request timed out while in an exponential backoff state.' +
387
- ' Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.',
388
- _a["config-fetch-failed" /* AnalyticsError.CONFIG_FETCH_FAILED */] = 'Dynamic config fetch failed: [{$httpStatus}] {$responseMessage}',
389
- _a["no-api-key" /* AnalyticsError.NO_API_KEY */] = 'The "apiKey" field is empty in the local Firebase config. Firebase Analytics requires this field to' +
390
- 'contain a valid API key.',
391
- _a["no-app-id" /* AnalyticsError.NO_APP_ID */] = 'The "appId" field is empty in the local Firebase config. Firebase Analytics requires this field to' +
392
- 'contain a valid app ID.',
393
- _a);
394
- var ERROR_FACTORY = new util.ErrorFactory('analytics', 'Analytics', ERRORS);
395
-
396
447
  /**
397
448
  * @license
398
449
  * Copyright 2020 Google LLC
@@ -811,6 +862,32 @@ function setUserProperties$1(gtagFunction, initializationPromise, properties, op
811
862
  });
812
863
  });
813
864
  }
865
+ /**
866
+ * Retrieves a unique Google Analytics identifier for the web client.
867
+ * See {@link https://developers.google.com/analytics/devguides/collection/ga4/reference/config#client_id | client_id}.
868
+ *
869
+ * @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event
870
+ */
871
+ function internalGetGoogleAnalyticsClientId(gtagFunction, initializationPromise) {
872
+ return tslib.__awaiter(this, void 0, void 0, function () {
873
+ var measurementId;
874
+ return tslib.__generator(this, function (_a) {
875
+ switch (_a.label) {
876
+ case 0: return [4 /*yield*/, initializationPromise];
877
+ case 1:
878
+ measurementId = _a.sent();
879
+ return [2 /*return*/, new Promise(function (resolve, reject) {
880
+ gtagFunction("get" /* GtagCommand.GET */, measurementId, 'client_id', function (clientId) {
881
+ if (!clientId) {
882
+ reject(ERROR_FACTORY.create("no-client-id" /* AnalyticsError.NO_CLIENT_ID */));
883
+ }
884
+ resolve(clientId);
885
+ });
886
+ })];
887
+ }
888
+ });
889
+ });
890
+ }
814
891
  /**
815
892
  * Set whether collection is enabled for this ID.
816
893
  *
@@ -1241,6 +1318,22 @@ function setCurrentScreen(analyticsInstance, screenName, options) {
1241
1318
  analyticsInstance = util.getModularInstance(analyticsInstance);
1242
1319
  setCurrentScreen$1(wrappedGtagFunction, initializationPromisesMap[analyticsInstance.app.options.appId], screenName, options).catch(function (e) { return logger.error(e); });
1243
1320
  }
1321
+ /**
1322
+ * Retrieves a unique Google Analytics identifier for the web client.
1323
+ * See {@link https://developers.google.com/analytics/devguides/collection/ga4/reference/config#client_id | client_id}.
1324
+ *
1325
+ * @public
1326
+ *
1327
+ * @param app - The {@link @firebase/app#FirebaseApp} to use.
1328
+ */
1329
+ function getGoogleAnalyticsClientId(analyticsInstance) {
1330
+ return tslib.__awaiter(this, void 0, void 0, function () {
1331
+ return tslib.__generator(this, function (_a) {
1332
+ analyticsInstance = util.getModularInstance(analyticsInstance);
1333
+ return [2 /*return*/, internalGetGoogleAnalyticsClientId(wrappedGtagFunction, initializationPromisesMap[analyticsInstance.app.options.appId])];
1334
+ });
1335
+ });
1336
+ }
1244
1337
  /**
1245
1338
  * Use gtag `config` command to set `user_id`.
1246
1339
  *
@@ -1326,7 +1419,7 @@ function setConsent(consentSettings) {
1326
1419
  }
1327
1420
 
1328
1421
  var name = "@firebase/analytics";
1329
- var version = "0.9.4";
1422
+ var version = "0.9.5-canary.0a27d2fbf";
1330
1423
 
1331
1424
  /**
1332
1425
  * Firebase Analytics
@@ -1364,6 +1457,7 @@ function registerAnalytics() {
1364
1457
  registerAnalytics();
1365
1458
 
1366
1459
  exports.getAnalytics = getAnalytics;
1460
+ exports.getGoogleAnalyticsClientId = getGoogleAnalyticsClientId;
1367
1461
  exports.initializeAnalytics = initializeAnalytics;
1368
1462
  exports.isSupported = isSupported;
1369
1463
  exports.logEvent = logEvent;