@codecademy/tracking 1.0.1-alpha.fbd013345.0 → 1.0.1

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.
Files changed (38) hide show
  1. package/README.md +1 -0
  2. package/dist/events/index.d.ts +3 -0
  3. package/dist/events/index.js +3 -0
  4. package/dist/events/track.d.ts +12 -0
  5. package/dist/events/track.js +115 -0
  6. package/dist/events/types.d.ts +250 -0
  7. package/dist/events/types.js +1 -0
  8. package/dist/events/user.d.ts +2 -0
  9. package/dist/events/user.js +41 -0
  10. package/dist/index.d.ts +3 -0
  11. package/dist/index.js +3 -0
  12. package/dist/integrations/conditionallyLoadAnalytics.d.ts +9 -0
  13. package/dist/integrations/conditionallyLoadAnalytics.js +27 -0
  14. package/dist/integrations/consent.d.ts +9 -0
  15. package/dist/integrations/consent.js +11 -0
  16. package/dist/integrations/device.d.ts +13 -0
  17. package/dist/integrations/device.js +25 -0
  18. package/dist/integrations/fetchDestinationsForWriteKey.d.ts +6 -0
  19. package/dist/integrations/fetchDestinationsForWriteKey.js +88 -0
  20. package/dist/integrations/getConsentDecision.d.ts +8 -0
  21. package/dist/integrations/getConsentDecision.js +32 -0
  22. package/dist/integrations/index.d.ts +31 -0
  23. package/dist/integrations/index.js +90 -0
  24. package/dist/integrations/mapDestinations.d.ts +13 -0
  25. package/dist/integrations/mapDestinations.js +55 -0
  26. package/dist/integrations/onetrust.d.ts +6 -0
  27. package/dist/integrations/onetrust.js +53 -0
  28. package/dist/integrations/runSegmentSnippet.d.ts +7 -0
  29. package/dist/integrations/runSegmentSnippet.js +64 -0
  30. package/dist/integrations/types.d.ts +24 -0
  31. package/dist/integrations/types.js +1 -0
  32. package/package.json +6 -3
  33. package/.eslintrc.json +0 -33
  34. package/CHANGELOG.md +0 -318
  35. package/babel.config.js +0 -15
  36. package/project.json +0 -46
  37. package/tsconfig.json +0 -20
  38. package/tsconfig.spec.json +0 -9
package/README.md CHANGED
@@ -1,6 +1,7 @@
1
1
  # `@codecademy/tracking`
2
2
 
3
3
  This package contains our user "telemetry" (tracking metrics such as `click` and `visit`) integrations that are shared across multiple web properties.
4
+
4
5
  We've consolidated them here for a few reasons:
5
6
 
6
7
  - To standardize APIs around events like tracking user clicks
@@ -0,0 +1,3 @@
1
+ export * from './track';
2
+ export * from './user';
3
+ export * from './types';
@@ -0,0 +1,3 @@
1
+ export * from './track';
2
+ export * from './user';
3
+ export * from './types';
@@ -0,0 +1,12 @@
1
+ import type { BaseEventData, EventDataTypes, TrackingOptions, UserClickData, UserImpressionData, UserVisitData } from './types';
2
+ export declare type TrackerOptions = {
3
+ apiBaseUrl: string;
4
+ verbose?: boolean;
5
+ };
6
+ export declare const createTracker: ({ apiBaseUrl, verbose }: TrackerOptions) => {
7
+ event: <Category extends keyof EventDataTypes, Event_1 extends string & keyof EventDataTypes[Category], Data extends EventDataTypes[Category][Event_1] & BaseEventData>(category: Category, event: Event_1, userData: Data, options?: TrackingOptions) => void;
8
+ click: (data: UserClickData) => void;
9
+ impression: (data: UserImpressionData) => void;
10
+ visit: (data: UserVisitData) => void;
11
+ pushDataLayerEvent: (eventName: string) => void;
12
+ };
@@ -0,0 +1,115 @@
1
+ function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
2
+
3
+ function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
4
+
5
+ function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
6
+
7
+ function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
8
+
9
+ function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
10
+
11
+ function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
12
+
13
+ function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
14
+
15
+ function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
16
+
17
+ function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
18
+
19
+ import { getClientType } from '../integrations/device';
20
+
21
+ var browserSupportsKeepalive = function browserSupportsKeepalive() {
22
+ return 'keepalive' in window.Request.prototype;
23
+ };
24
+
25
+ export var createTracker = function createTracker(_ref) {
26
+ var apiBaseUrl = _ref.apiBaseUrl,
27
+ verbose = _ref.verbose;
28
+
29
+ var beacon = function beacon(endpoint, data) {
30
+ var uri = new URL(endpoint, apiBaseUrl).toString();
31
+ var form = new FormData();
32
+
33
+ for (var _i2 = 0, _Object$entries = Object.entries(data); _i2 < _Object$entries.length; _i2++) {
34
+ var _ref4 = _Object$entries[_i2];
35
+
36
+ var _ref3 = _slicedToArray(_ref4, 2);
37
+
38
+ var k = _ref3[0];
39
+ var v = _ref3[1];
40
+ form.append(k, v.toString());
41
+ }
42
+
43
+ try {
44
+ // Firefox allows users to disable navigator.sendBeacon, and very old Safari versions don't have it.
45
+ // [WEB-1700]: Additionally, Chrome 79-80 gives "Illegal invocation" with ?., so through 2022 we should support them.
46
+ // It seems similar to this: https://github.com/vercel/next.js/issues/23856
47
+ if (navigator.sendBeacon && navigator.sendBeacon(uri, form)) {
48
+ return;
49
+ }
50
+ } catch (_unused) {// Even with the proper scoping, Chrome 79-80 still gives "Illegal invocation" crashes. Sigh.
51
+ } // Either way, we fall back to standard fetch if sendBeacon fails.
52
+ // We don't mind this rejecting with an error because it's tracking, and we'll know if that starts to fail.
53
+
54
+
55
+ window.fetch(uri, _objectSpread({
56
+ method: 'POST',
57
+ body: form
58
+ }, browserSupportsKeepalive() && {
59
+ keepalive: true
60
+ }));
61
+ };
62
+
63
+ var event = function event(category, _event, userData) {
64
+ var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
65
+
66
+ var properties = _objectSpread(_objectSpread({}, userData), {}, {
67
+ fullpath: window.location.pathname + window.location.search,
68
+ search: window.location.search,
69
+ path: window.location.pathname,
70
+ title: window.document.title,
71
+ url: window.location.href,
72
+ referrer: userData.referrer || window.document.referrer,
73
+ client: getClientType()
74
+ });
75
+
76
+ if (verbose) {
77
+ console.groupCollapsed("%cTracking Event Fired: ".concat(category, ":").concat(_event), 'color: #4b35ef; font-style: italic;');
78
+ console.log({
79
+ category: category,
80
+ event: _event,
81
+ properties: properties
82
+ });
83
+ console.groupEnd();
84
+ } // This allows the UTM query params to get registered in the user session.
85
+
86
+
87
+ var queryParams = window.location.search;
88
+ beacon("/analytics/".concat(category).concat(queryParams), {
89
+ category: category,
90
+ event: _event,
91
+ properties: JSON.stringify(properties),
92
+ gdpr_safe: "".concat(options.gdprSafe)
93
+ });
94
+ };
95
+
96
+ return {
97
+ event: event,
98
+ click: function click(data) {
99
+ return event('user', 'click', data);
100
+ },
101
+ impression: function impression(data) {
102
+ return event('user', 'impression', data);
103
+ },
104
+ visit: function visit(data) {
105
+ return event('user', 'visit', data);
106
+ },
107
+ pushDataLayerEvent: function pushDataLayerEvent(eventName) {
108
+ var _ref5;
109
+
110
+ ((_ref5 = window).dataLayer || (_ref5.dataLayer = [])).push({
111
+ event: eventName
112
+ });
113
+ }
114
+ };
115
+ };
@@ -0,0 +1,250 @@
1
+ /**
2
+ * The Data types for all of our events.
3
+ * Follows the format EventDataTypes[Category].[Event].EventData
4
+ * Category + Event gives the corresponding event table in redshift
5
+ */
6
+ export declare type EventDataTypes = {
7
+ user: {
8
+ click: UserClickData;
9
+ visit: UserVisitData;
10
+ impression: UserImpressionData;
11
+ email_trigger: BaseEventAnyData;
12
+ content_completed: BaseEventAnyData;
13
+ submit: BaseEventAnyData;
14
+ workspace_init: BaseEventAnyData;
15
+ meaningful_content_loaded: BaseEventAnyData;
16
+ practice_completed: BaseEventAnyData;
17
+ };
18
+ ad: {
19
+ click: BaseEventAnyData;
20
+ impression: BaseEventAnyData;
21
+ };
22
+ calendar: {
23
+ reminder: BaseEventAnyData;
24
+ };
25
+ notification: {
26
+ clicked: BaseEventAnyData;
27
+ ion: BaseEventAnyData;
28
+ };
29
+ form: {
30
+ submit: BaseEventAnyData;
31
+ };
32
+ sorting_quiz: {
33
+ result: BaseEventAnyData;
34
+ impression: BaseEventAnyData;
35
+ answer: EventAnswerData;
36
+ };
37
+ onboarding_survey: {
38
+ answer: BaseEventAnyData;
39
+ recommendation: BaseEventAnyData;
40
+ user_selected_recommendation: BaseEventAnyData;
41
+ };
42
+ exercise: {
43
+ force_pass: BaseEventAnyData;
44
+ };
45
+ experiment: {
46
+ contentful_experiment_assignment_event: BaseEventAnyData;
47
+ };
48
+ payments: {
49
+ cancel_survey: BaseEventAnyData;
50
+ };
51
+ search: {
52
+ visit: BaseEventAnyData;
53
+ click: BaseEventAnyData;
54
+ query: BaseEventAnyData;
55
+ result: BaseEventAnyData;
56
+ };
57
+ page: {
58
+ career_path_visited: PagePathVisitedData;
59
+ skill_path_visited: PagePathVisitedData;
60
+ course_page_visited: CoursePageVisitedData;
61
+ };
62
+ business: {
63
+ filter_event: BusinessFilterData;
64
+ search_event: BusinessSearchData;
65
+ };
66
+ };
67
+ /**
68
+ * Base event data shared by all events
69
+ */
70
+ export declare type BaseEventData = {
71
+ fullpath?: null;
72
+ search?: null;
73
+ path?: null;
74
+ title?: null;
75
+ url?: null;
76
+ referrer?: string | null;
77
+ id?: null;
78
+ };
79
+ /**
80
+ * Generic type to use for event data not typed yet
81
+ */
82
+ export declare type BaseEventAnyData = BaseEventData & {
83
+ [key: string]: any;
84
+ };
85
+ /**
86
+ * Options to pass to the tracking function
87
+ */
88
+ export declare type TrackingOptions = {
89
+ /** tells backend not to merge user-identifying data onto the event payload */
90
+ gdprSafe?: boolean;
91
+ };
92
+ /**
93
+ * The Content IDs related to the current event, to help build the content context of the event.
94
+ * These IDs get hashed into a single value and overwrite content_id before they are sent to
95
+ * redshift in lib/content_group_id.rb
96
+ */
97
+ export declare type TrackingContentIds = {
98
+ assessment_id?: string;
99
+ content_item_id?: string;
100
+ exercise_id?: string;
101
+ learning_standard_id?: string;
102
+ module_id?: string;
103
+ path_id?: string;
104
+ program_id?: string;
105
+ program_unit_id?: string;
106
+ review_card_id?: string;
107
+ track_id?: string;
108
+ journey_id?: string;
109
+ };
110
+ /**
111
+ * Shared data relevant for all user events
112
+ */
113
+ export declare type UserSharedData = BaseEventData & {
114
+ /** the click target of the event */
115
+ target?: string;
116
+ /** the page the event is coming from */
117
+ page_name?: string;
118
+ /** a context id for the event, for events that occur in more than one place */
119
+ context?: string;
120
+ /** the link being clicked on */
121
+ href?: string;
122
+ /** a version id for the element (ex. different version ids for redesigns) */
123
+ version?: string;
124
+ /** an object of content ids related to this event */
125
+ content_ids?: TrackingContentIds;
126
+ /** the repo that this event is being fired from */
127
+ source_codebase?: string;
128
+ /** Should be used for arbitrary JSON that has been passed through JSON.stringify. */
129
+ misc?: string;
130
+ };
131
+ /**
132
+ * Data sent to user click event table
133
+ * NOTE: avoid adding additional properties to these objects
134
+ * Instead, reuse existing properties, or make any additional properties generic so that they can be reused.
135
+ * https://www.notion.so/codecademy/Guide-to-Event-Tracking-Schema-5d40b09a297743f7a30a2690208194c8#800bbf6cdf2e44de9823cd75bcc574e5
136
+ */
137
+ export declare type UserClickData = UserSharedData & {
138
+ target: string;
139
+ id?: string;
140
+ distinct_id?: string;
141
+ content_id?: string;
142
+ slug?: string;
143
+ name?: string;
144
+ action?: string;
145
+ type?: string;
146
+ location?: string;
147
+ element?: string;
148
+ weekly_goal?: string | number;
149
+ complete?: string;
150
+ video_url?: string;
151
+ path_id?: string;
152
+ path_slug?: string;
153
+ event_name?: string;
154
+ onboarding_entrypoint?: string;
155
+ content_slug?: string;
156
+ module_id?: string;
157
+ track_slug?: string;
158
+ module_slug?: string;
159
+ button?: string;
160
+ current_challenge_day?: string | number;
161
+ track_id?: string;
162
+ course?: string;
163
+ path_name?: string;
164
+ event_id?: string;
165
+ unit?: string;
166
+ lesson?: string;
167
+ community_prompt?: string;
168
+ contentItem?: any;
169
+ unit_slug?: string;
170
+ course_slug?: string;
171
+ course_progress?: number;
172
+ assessment_id?: string;
173
+ container_slugs?: string[];
174
+ search_id?: string;
175
+ is_ugc?: boolean;
176
+ business_user?: BaseEventAnyData;
177
+ };
178
+ /**
179
+ * Data sent to user visit event table
180
+ * NOTE: avoid adding additional properties to these objects
181
+ * Instead, reuse existing properties, or make any additional properties generic so that they can be reused.
182
+ * https://www.notion.so/codecademy/Guide-to-Event-Tracking-Schema-5d40b09a297743f7a30a2690208194c8#800bbf6cdf2e44de9823cd75bcc574e5
183
+ */
184
+ export declare type UserVisitData = UserSharedData & {
185
+ page_name: string;
186
+ category?: string;
187
+ distinct_id?: string;
188
+ type?: string;
189
+ target?: string;
190
+ section?: string;
191
+ plan?: string;
192
+ path_id?: string;
193
+ post?: string;
194
+ story_type?: string;
195
+ path_title?: string;
196
+ onboarding_entrypoint?: string;
197
+ course_slug?: string;
198
+ course?: string;
199
+ interstitial_name?: string;
200
+ content_id?: string;
201
+ story_slug?: string;
202
+ unit?: string;
203
+ lesson?: string;
204
+ is_ugc?: boolean;
205
+ };
206
+ export declare type UserImpressionData = Pick<UserSharedData, 'context' | 'source_codebase' | 'content_ids'> & {
207
+ page_name: string;
208
+ target: string;
209
+ slug?: string;
210
+ is_ugc?: boolean;
211
+ };
212
+ export declare type EventAnswerData = BaseEventData & {
213
+ question_index: number;
214
+ answer_index: number;
215
+ answer: any;
216
+ answer_slug: string;
217
+ };
218
+ export declare type User = {
219
+ id?: string;
220
+ auth_token: string;
221
+ profile_image_url?: string;
222
+ email?: string;
223
+ is_pro?: boolean;
224
+ username?: string;
225
+ location: {
226
+ in_eu: boolean;
227
+ geo_country: string;
228
+ };
229
+ features: string[];
230
+ };
231
+ export declare type UseUserResponse = {
232
+ user?: User;
233
+ status: string;
234
+ };
235
+ export declare type PagePathVisitedData = BaseEventData & {
236
+ path_id: string;
237
+ path_full_title: string;
238
+ };
239
+ export declare type CoursePageVisitedData = BaseEventData & {
240
+ course_id: string;
241
+ course_full_title: string;
242
+ };
243
+ export declare type FilterType = string | string[] | number | boolean;
244
+ export declare type BusinessFilterData = BaseEventData & {
245
+ filter_key: string;
246
+ filter_value: FilterType;
247
+ };
248
+ export declare type BusinessSearchData = BaseEventData & {
249
+ search_query: string;
250
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,2 @@
1
+ import { User } from './types';
2
+ export declare const fetchUser: (apiBaseUrl: string) => Promise<User>;
@@ -0,0 +1,41 @@
1
+ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
2
+
3
+ function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return generator._invoke = function (innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; }(innerFn, self, context), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; this._invoke = function (method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); }; } function maybeInvokeDelegate(delegate, context) { var method = delegate.iterator[context.method]; if (undefined === method) { if (context.delegate = null, "throw" === context.method) { if (delegate.iterator.return && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method)) return ContinueSentinel; context.method = "throw", context.arg = new TypeError("The iterator does not provide a 'throw' method"); } return ContinueSentinel; } var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) { if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; } return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, define(Gp, "constructor", GeneratorFunctionPrototype), define(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (object) { var keys = []; for (var key in object) { keys.push(key); } return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) { "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); } }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, catch: function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; }
4
+
5
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
6
+
7
+ function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
8
+
9
+ export var fetchUser = /*#__PURE__*/function () {
10
+ var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(apiBaseUrl) {
11
+ var response;
12
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
13
+ while (1) {
14
+ switch (_context.prev = _context.next) {
15
+ case 0:
16
+ _context.next = 2;
17
+ return fetch("".concat(apiBaseUrl, "/users/web"), {
18
+ method: 'GET',
19
+ headers: {
20
+ 'Content-type': 'application/json',
21
+ Accept: 'application/json'
22
+ },
23
+ credentials: 'include'
24
+ });
25
+
26
+ case 2:
27
+ response = _context.sent;
28
+ return _context.abrupt("return", response.json());
29
+
30
+ case 4:
31
+ case "end":
32
+ return _context.stop();
33
+ }
34
+ }
35
+ }, _callee);
36
+ }));
37
+
38
+ return function fetchUser(_x) {
39
+ return _ref.apply(this, arguments);
40
+ };
41
+ }();
@@ -0,0 +1,3 @@
1
+ export * from './integrations';
2
+ export type { TrackingWindow } from './integrations/types';
3
+ export * from './events';
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export * from './integrations';
2
+ export * from './events';
3
+ export {};
@@ -0,0 +1,9 @@
1
+ import { SegmentAnalytics, UserIntegrationSummary } from './types';
2
+ export declare type AnalyticsLoadOptions = {
3
+ analytics: SegmentAnalytics;
4
+ destinationPreferences: Record<string, boolean>;
5
+ identifyPreferences: Record<string, boolean>;
6
+ user?: UserIntegrationSummary;
7
+ writeKey: string;
8
+ };
9
+ export declare const conditionallyLoadAnalytics: ({ analytics, destinationPreferences, identifyPreferences, user, writeKey, }: AnalyticsLoadOptions) => void;
@@ -0,0 +1,27 @@
1
+ import { getClientType } from './device';
2
+ export var conditionallyLoadAnalytics = function conditionallyLoadAnalytics(_ref) {
3
+ var analytics = _ref.analytics,
4
+ destinationPreferences = _ref.destinationPreferences,
5
+ identifyPreferences = _ref.identifyPreferences,
6
+ user = _ref.user,
7
+ writeKey = _ref.writeKey;
8
+
9
+ if (analytics.initialize) {
10
+ return;
11
+ }
12
+
13
+ analytics.load(writeKey, {
14
+ integrations: destinationPreferences
15
+ });
16
+ analytics.page();
17
+
18
+ if (user) {
19
+ var identifyParams = {
20
+ email: user.email,
21
+ client: getClientType()
22
+ };
23
+ analytics.identify(user.id, identifyParams, {
24
+ integrations: identifyPreferences
25
+ });
26
+ }
27
+ };
@@ -0,0 +1,9 @@
1
+ /**
2
+ * @see https://www.notion.so/codecademy/GDPR-Compliance-141ebcc7ffa542daa0da56e35f482b41
3
+ */
4
+ export declare enum Consent {
5
+ Functional = "C0003",
6
+ Performance = "C0002",
7
+ StrictlyNecessary = "C0001",
8
+ Targeting = "C0004"
9
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * @see https://www.notion.so/codecademy/GDPR-Compliance-141ebcc7ffa542daa0da56e35f482b41
3
+ */
4
+ export var Consent;
5
+
6
+ (function (Consent) {
7
+ Consent["Functional"] = "C0003";
8
+ Consent["Performance"] = "C0002";
9
+ Consent["StrictlyNecessary"] = "C0001";
10
+ Consent["Targeting"] = "C0004";
11
+ })(Consent || (Consent = {}));
@@ -0,0 +1,13 @@
1
+ /**
2
+ * @returns Whether the site is running both in ChromeOS and in PWA mode.
3
+ */
4
+ export declare const isChromeOSPWA: () => boolean;
5
+ /**
6
+ * @returns Whether the site is running in ChromeOS
7
+ */
8
+ export declare const isChromeOS: () => boolean;
9
+ export declare enum ClientTypes {
10
+ PWA = "pwa",
11
+ Default = "default"
12
+ }
13
+ export declare const getClientType: () => ClientTypes;
@@ -0,0 +1,25 @@
1
+ /**
2
+ * @returns Whether the site is running both in ChromeOS and in PWA mode.
3
+ */
4
+ export var isChromeOSPWA = function isChromeOSPWA() {
5
+ return isChromeOS() && 'getDigitalGoodsService' in window && // https://stackoverflow.com/questions/41742390/javascript-to-check-if-pwa-or-mobile-web
6
+ window.matchMedia('(display-mode: standalone)').matches;
7
+ };
8
+ /**
9
+ * @returns Whether the site is running in ChromeOS
10
+ */
11
+
12
+ export var isChromeOS = function isChromeOS() {
13
+ return typeof navigator !== 'undefined' && // https://stackoverflow.com/questions/29657165/detecting-chrome-os-with-javascript
14
+ /\bCrOS\b/.test(navigator.userAgent);
15
+ };
16
+ export var ClientTypes;
17
+
18
+ (function (ClientTypes) {
19
+ ClientTypes["PWA"] = "pwa";
20
+ ClientTypes["Default"] = "default";
21
+ })(ClientTypes || (ClientTypes = {}));
22
+
23
+ export var getClientType = function getClientType() {
24
+ return isChromeOSPWA() ? ClientTypes.PWA : ClientTypes.Default;
25
+ };
@@ -0,0 +1,6 @@
1
+ import { SegmentDestination } from './types';
2
+ export declare type FetchDestinationsSettings = {
3
+ onError: (message: string) => void;
4
+ writeKey: string;
5
+ };
6
+ export declare const fetchDestinationsForWriteKey: ({ writeKey, onError, }: FetchDestinationsSettings) => Promise<SegmentDestination[] | undefined>;