@crimson-education/browser-logger 5.0.1 → 5.0.3

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 (66) hide show
  1. package/README.md +72 -94
  2. package/lib/index.d.ts +1 -1
  3. package/lib/index.d.ts.map +1 -1
  4. package/lib/index.js +23 -46
  5. package/lib/index.js.map +1 -1
  6. package/lib/logger/consoleTransport.d.ts +1 -1
  7. package/lib/logger/consoleTransport.d.ts.map +1 -1
  8. package/lib/logger/consoleTransport.js +16 -22
  9. package/lib/logger/consoleTransport.js.map +1 -1
  10. package/lib/logger/datadogTransport.d.ts +1 -1
  11. package/lib/logger/datadogTransport.d.ts.map +1 -1
  12. package/lib/logger/datadogTransport.js +4 -8
  13. package/lib/logger/datadogTransport.js.map +1 -1
  14. package/lib/logger/index.js +29 -49
  15. package/lib/logger/index.js.map +1 -1
  16. package/lib/logger/index.test.js +16 -18
  17. package/lib/logger/index.test.js.map +1 -1
  18. package/lib/logger/utils.js +4 -9
  19. package/lib/logger/utils.js.map +1 -1
  20. package/lib/reporters/datadogReporter.d.ts +13 -1
  21. package/lib/reporters/datadogReporter.d.ts.map +1 -1
  22. package/lib/reporters/datadogReporter.js +122 -49
  23. package/lib/reporters/datadogReporter.js.map +1 -1
  24. package/lib/reporters/gtmReporter.d.ts +1 -1
  25. package/lib/reporters/gtmReporter.d.ts.map +1 -1
  26. package/lib/reporters/gtmReporter.js +1 -5
  27. package/lib/reporters/gtmReporter.js.map +1 -1
  28. package/lib/reporters/index.js +46 -71
  29. package/lib/reporters/index.js.map +1 -1
  30. package/lib/reporters/logReporter.js +24 -34
  31. package/lib/reporters/logReporter.js.map +1 -1
  32. package/lib/reporters/posthogReporter.d.ts +1 -1
  33. package/lib/reporters/posthogReporter.d.ts.map +1 -1
  34. package/lib/reporters/posthogReporter.js +46 -55
  35. package/lib/reporters/posthogReporter.js.map +1 -1
  36. package/lib/reporters/posthogReporter.test.js +21 -23
  37. package/lib/reporters/posthogReporter.test.js.map +1 -1
  38. package/lib/types/index.js +2 -18
  39. package/lib/types/index.js.map +1 -1
  40. package/lib/types/logger.d.ts +3 -3
  41. package/lib/types/logger.d.ts.map +1 -1
  42. package/lib/types/logger.js +2 -5
  43. package/lib/types/logger.js.map +1 -1
  44. package/lib/types/reporter.d.ts +6 -12
  45. package/lib/types/reporter.d.ts.map +1 -1
  46. package/lib/types/reporter.js +1 -2
  47. package/lib/utils.js +1 -5
  48. package/lib/utils.js.map +1 -1
  49. package/lib/utils.test.js +2 -4
  50. package/lib/utils.test.js.map +1 -1
  51. package/package.json +16 -16
  52. package/src/index.ts +0 -6
  53. package/src/reporters/datadogReporter.ts +133 -22
  54. package/src/reporters/posthogReporter.test.ts +6 -1
  55. package/src/reporters/posthogReporter.ts +6 -1
  56. package/src/types/reporter.ts +0 -7
  57. package/lib/reporters/amplifyReporter.d.ts +0 -86
  58. package/lib/reporters/amplifyReporter.d.ts.map +0 -1
  59. package/lib/reporters/amplifyReporter.js +0 -225
  60. package/lib/reporters/amplifyReporter.js.map +0 -1
  61. package/lib/reporters/amplifyReporter.test.d.ts +0 -2
  62. package/lib/reporters/amplifyReporter.test.d.ts.map +0 -1
  63. package/lib/reporters/amplifyReporter.test.js +0 -51
  64. package/lib/reporters/amplifyReporter.test.js.map +0 -1
  65. package/src/reporters/amplifyReporter.test.ts +0 -61
  66. package/src/reporters/amplifyReporter.ts +0 -344
@@ -1,344 +0,0 @@
1
- import { Auth } from '@aws-amplify/auth';
2
- import { Analytics } from '@aws-amplify/analytics';
3
- import { Endpoint, FinalizeRequestMiddleware } from '@aws-sdk/types';
4
- import { HttpRequest } from '@aws-sdk/protocol-http';
5
- import { PinpointClient, ServiceInputTypes, ServiceOutputTypes } from '@aws-sdk/client-pinpoint';
6
-
7
- import {
8
- IReporter,
9
- Metadata,
10
- ReporterBreadcrumb,
11
- ReporterConfigBase,
12
- ReporterEvent,
13
- ReportUser,
14
- ServiceInfo,
15
- } from '../types';
16
- import { logger } from '../logger';
17
-
18
- /* eslint-disable @typescript-eslint/no-unused-vars */
19
- type AttributeMap = Record<string, string[] | string | null>;
20
-
21
- type AmplifyAutoTrackSource = 'pageView' | 'event' | 'session';
22
-
23
- export interface AmplifyReporterConfig extends ReporterConfigBase {
24
- /**
25
- * AWS Region for Amplify.
26
- */
27
- region: string;
28
- /**
29
- * The Identity Pool Id to use for reporting, if set to false, Auth.configure is not called.
30
- * This must be called manually for the reporter to work.
31
- */
32
- identityPoolId: string | false;
33
- /**
34
- * The Pinpoint App Id to report to.
35
- */
36
- analyticsAppId: string;
37
- /** Optional proxy URL */
38
- proxyUrl?: string;
39
- /**
40
- * The Cognito User Pool to configure in Auth.configure.
41
- * If you are using Cognito, it is better to set identityPoolId to false and configure Auth manually.
42
- */
43
- userPoolId?: string;
44
- /**
45
- * The Cognito Web Client Id to configure in Auth.configure.
46
- * If you are using Cognito, it is better to set identityPoolId to false and configure Auth manually.
47
- */
48
- userPoolWebClientId?: string;
49
-
50
- /**
51
- * If you want to track which page/url in your webapp is the most frequently viewed one, you can use this feature.
52
- * It will automatically send events containing url information when the page is visited.
53
- */
54
- autoTrackPageViews?: boolean;
55
- /**
56
- * If you want to track user interactions with elements on the page, you can use this feature.
57
- * All you need to do is attach the specified selectors to your dom element and turn on the auto tracking.
58
- */
59
- autoTrackEvents?: boolean;
60
- /**
61
- * A web session can be defined in different ways.
62
- * To keep it simple we define that the web session is active when the page is not hidden and inactive when the page is hidden.
63
- */
64
- autoTrackSessions?: boolean;
65
- /**
66
- * Optional function to run before autotracked analytics events are sent out.
67
- * The returned metadata is attached to the event.
68
- */
69
- beforeAutoTrack?(source: AmplifyAutoTrackSource): Metadata | undefined;
70
-
71
- /**
72
- * The data tag prefix to use for attributing HTML elements. Defaults to data-analytics-
73
- */
74
- selectorPrefix?: string;
75
-
76
- /**
77
- * Modify how the reporter sends events to Amplify.
78
- */
79
- buffering?: AmplifyReporterBufferingConfig;
80
- }
81
-
82
- /**
83
- * Configuration options for the buffering behavior of Pinpoint's event tracker.
84
- *
85
- * @see https://docs.amplify.aws/lib/analytics/getting-started/q/platform/js/#set-up-existing-analytics-backend
86
- */
87
- type AmplifyReporterBufferingConfig = {
88
- /** Number of items to buffer for sending. */
89
- bufferSize?: number;
90
- /** Number of events sent each time Pinpoint flushes. */
91
- flushSize?: number;
92
- /** Interval Pinpoint flushes analytics events. Measured in milliseconds. */
93
- flushInterval?: number;
94
- /** The maximum number of times Pinpoint will retry to send an event. */
95
- resendLimit?: number;
96
- };
97
-
98
- export function amplifyReporter(info: ServiceInfo, config: AmplifyReporterConfig): IReporter {
99
- if (config.identityPoolId !== false) {
100
- Auth.configure({
101
- region: config.region,
102
- identityPoolId: config.identityPoolId,
103
- userPoolId: config.userPoolId,
104
- userPoolWebClientId: config.userPoolWebClientId,
105
- });
106
- }
107
-
108
- const wrapAutoTrackMiddleware = (source: AmplifyAutoTrackSource) => {
109
- const { beforeAutoTrack } = config;
110
- return typeof beforeAutoTrack === 'function' ? () => beforeAutoTrack(source) ?? {} : undefined;
111
- };
112
-
113
- const allMetadata = asAttributeMap({
114
- appName: info.service,
115
- service: info.service,
116
- domain: window.location.host,
117
- environment: info.environment,
118
- version: info.version,
119
- });
120
-
121
- Analytics.configure({
122
- region: config.region,
123
- appId: config.analyticsAppId,
124
- endpoint: {
125
- attributes: allMetadata,
126
- },
127
- ...config.buffering,
128
- });
129
-
130
- // Session autotracking is enabled by default for backwards compatibility reasons, so we _must_
131
- // call this unconditionally to ensure we opt out of session tracking when `autoTrackSessions` isn't set
132
- // See: https://docs.amplify.aws/lib/analytics/autotrack/q/platform/js/#session-tracking
133
- Analytics.autoTrack('session', {
134
- enable: config.autoTrackSessions === true,
135
- attributes: wrapAutoTrackMiddleware('session'),
136
- });
137
-
138
- if (config.autoTrackPageViews) {
139
- Analytics.autoTrack('pageView', {
140
- enable: true,
141
- eventName: 'pageView',
142
- type: 'SPA',
143
- provider: 'AWSPinpoint',
144
- attributes: wrapAutoTrackMiddleware('pageView'),
145
- });
146
- }
147
-
148
- if (config.autoTrackEvents) {
149
- Analytics.autoTrack('event', {
150
- enable: true,
151
- selectorPrefix: config.selectorPrefix ?? 'data-analytics-',
152
- attributes: wrapAutoTrackMiddleware('event'),
153
- });
154
- }
155
-
156
- if (config.proxyUrl) {
157
- installPinpointProxy(new URL(config.proxyUrl));
158
- }
159
-
160
- const reporter: IReporter = {
161
- trackEvent: function (event: ReporterEvent): void {
162
- Analytics.record({
163
- name: event.message,
164
- attributes: asAttributeMap(
165
- {
166
- ...event.metadata,
167
- ...event.tags,
168
- },
169
- false,
170
- ) as Record<string, string>,
171
- metrics: event.metrics,
172
- }).catch(() => {
173
- // Swallow; see: https://crimsonhq.slack.com/archives/G4UN6Q4KF/p1648599302847539
174
- });
175
- },
176
- addBreadcrumb: function (breadcrumb: ReporterBreadcrumb): void {
177
- reporter.trackEvent({
178
- message: breadcrumb.message,
179
- metadata: {
180
- category: breadcrumb.category,
181
- ...breadcrumb.metadata,
182
- },
183
- });
184
- },
185
- addMetadata: function (metadata: Metadata): void {
186
- Object.assign(allMetadata, asAttributeMap(metadata, true));
187
- Analytics.updateEndpoint({
188
- attributes: allMetadata,
189
- }).catch(() => {
190
- // Swallow; see: https://crimsonhq.slack.com/archives/G4UN6Q4KF/p1648599302847539
191
- });
192
- },
193
- setUser: function (user: ReportUser | null): void {
194
- const userMetadata = user
195
- ? asAttributeMap({
196
- userId: user.id,
197
- })
198
- : {};
199
- Object.assign(allMetadata, asAttributeMap(userMetadata, true));
200
- Analytics.updateEndpoint({
201
- userId: user?.id ?? '',
202
- attributes: allMetadata,
203
- userAttributes: user
204
- ? asAttributeMap({
205
- id: user.id,
206
- email: user.email,
207
- name: user.name ?? user.email,
208
- username: user.username,
209
- })
210
- : {},
211
- }).catch(() => {
212
- // Swallow; see: https://crimsonhq.slack.com/archives/G4UN6Q4KF/p1648599302847539
213
- });
214
- },
215
- setRouteName: function (routeName: string): void {
216
- reporter.addMetadata({ routeName });
217
- },
218
- setPageName: function (pageName: string): void {
219
- reporter.addMetadata({ pageName });
220
- },
221
- };
222
-
223
- return reporter;
224
- }
225
-
226
- /**
227
- * Pinpoint has strict attribute name and value length limits
228
- */
229
- export function asAttributeMap(values: Record<string, unknown>, groupValues = true): AttributeMap {
230
- const attributeMap = buildAttributeMap(values, undefined, groupValues);
231
-
232
- const checkedEntries = Object.entries(attributeMap).map(([key, value]) => {
233
- const truncatedKey = key.length > 50 ? `___${key.slice(-47)}` : key;
234
- const truncatedValue = Array.isArray(value)
235
- ? value?.map((val) => val.slice(0, 100)) ?? null
236
- : value?.slice(0, 100) ?? null;
237
-
238
- return [truncatedKey, truncatedValue];
239
- });
240
-
241
- // Pinpoint only accepts 40 attributes
242
- if (checkedEntries.length > 40) {
243
- logger.error(`Amplify only allows 40 attributes per event, truncating to 40 attributes`, {
244
- attributes: checkedEntries,
245
- });
246
- checkedEntries.length = 40;
247
- }
248
-
249
- return Object.fromEntries(checkedEntries);
250
- }
251
-
252
- /**
253
- * Pinpoint expects `endpoint.attributes` and `endpoint.userAttributes` to have
254
- * values which are string arrays. This function takes in an object and ensures
255
- * all of its values are of type `string[]` to appease Pinpoint.
256
- */
257
- export function buildAttributeMap(
258
- values: Record<string, any>,
259
- parentKey: string | undefined = undefined,
260
- groupValues = true,
261
- ): AttributeMap {
262
- const valuesWithStringArrays: AttributeMap = {};
263
-
264
- Object.entries(values).forEach(([key, value]) => {
265
- const combinedKey = parentKey ? [parentKey, key].join('.') : key;
266
-
267
- if (!value) {
268
- valuesWithStringArrays[combinedKey] = null;
269
- } else if (groupValues && Array.isArray(value)) {
270
- valuesWithStringArrays[combinedKey] = value.map((element) =>
271
- typeof element === 'string' ? element : JSON.stringify(element),
272
- );
273
- } else if (typeof value === 'object') {
274
- const flattenedAttribute = buildAttributeMap(value, combinedKey, groupValues);
275
- Object.assign(valuesWithStringArrays, flattenedAttribute);
276
- } else {
277
- const stringValue = typeof value === 'string' ? value : JSON.stringify(value);
278
- valuesWithStringArrays[combinedKey] = groupValues ? [stringValue] : stringValue;
279
- }
280
- });
281
-
282
- return valuesWithStringArrays;
283
- }
284
-
285
- function installPinpointProxy(proxyUrl: URL) {
286
- // No public API for overriding where the Pinpoint client sends events to... 🤮
287
- // In theory you can pass in an `endpoint` to the Pinpoint client's constructor like any other AWS
288
- // client, but Amplify's analytics doesn't expose anything we can use to get an endpoint threaded
289
- // down to the Pinpoint client's constructor.
290
- //
291
- // The Pinpoint client _also_ isn't available synchronously because it is instantiated when events
292
- // get sent out, and then reconfigured whenever the API credentials change. We need to hook `_initClients`
293
- // to ensure that the Pinpoint client being used is always patched with our custom endpoint.
294
- const provider = Analytics.getPluggable('AWSPinpoint') as any;
295
- if (!provider || typeof provider._initClients !== 'function') {
296
- logger.error(
297
- 'Installation of the Pinpoint proxy failed. This likely means the internals of the @aws-amplify/analytics package have changed.',
298
- );
299
- return;
300
- }
301
-
302
- const originalInitClients = provider._initClients;
303
- const requestMiddleware: FinalizeRequestMiddleware<ServiceInputTypes, ServiceOutputTypes> =
304
- (next) => async (args) => {
305
- const pinpointClient = provider.pinpointClient as PinpointClient | undefined;
306
-
307
- if (pinpointClient && proxyUrl.pathname !== '/' && HttpRequest.isInstance(args.request)) {
308
- // Add proxyUrl.pathname to final request url if it was provided
309
- const shouldStripSlash = proxyUrl.pathname.endsWith('/');
310
- args.request.path = `${proxyUrl.pathname}${args.request.path.slice(shouldStripSlash ? 1 : 0)}`;
311
-
312
- // Wrap request body so the proxy has signing info
313
- if (typeof args.request.body === 'string') {
314
- const credentials = await pinpointClient.config.credentials();
315
- args.request.body = JSON.stringify({
316
- credentials,
317
- data: JSON.parse(args.request.body),
318
- });
319
- }
320
- }
321
-
322
- return next(args);
323
- };
324
-
325
- provider._initClients = async (credentials: unknown) => {
326
- const result = await originalInitClients.call(provider, credentials);
327
- const pinpointClient = provider.pinpointClient as PinpointClient | undefined;
328
-
329
- if (pinpointClient) {
330
- pinpointClient.config.endpoint = (): Promise<Endpoint> =>
331
- Promise.resolve({
332
- hostname: proxyUrl.hostname,
333
- // Passing proxyUrl.pathname here doesn't work; it gets overridden
334
- path: '/',
335
- port: undefined,
336
- protocol: proxyUrl.protocol,
337
- });
338
-
339
- pinpointClient.middlewareStack.remove(requestMiddleware);
340
- pinpointClient.middlewareStack.add(requestMiddleware, { step: 'finalizeRequest' });
341
- }
342
- return result;
343
- };
344
- }