Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add browser-plugin-web-vitals to track Web Vitals metrics #1190

Merged
merged 1 commit into from
Jun 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"changes": [
{
"packageName": "@snowplow/browser-plugin-web-vitals",
"comment": "Create browser-plugin-web-vitals",
"type": "none"
}
],
"packageName": "@snowplow/browser-plugin-web-vitals"
}
10 changes: 9 additions & 1 deletion common/config/rush/browser-approved-packages.json
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,10 @@
"name": "@snowplow/browser-plugin-timezone",
"allowedCategories": [ "trackers" ]
},
{
"name": "@snowplow/browser-plugin-web-vitals",
"allowedCategories": [ "trackers" ]
},
{
"name": "@snowplow/browser-plugin-youtube-tracking",
"allowedCategories": [ "trackers" ]
Expand Down Expand Up @@ -320,7 +324,7 @@
},
{
"name": "rollup-plugin-filesize",
"allowedCategories": [ "trackers" ]
"allowedCategories": [ "plugins", "trackers" ]
},
{
"name": "rollup-plugin-license",
Expand Down Expand Up @@ -374,6 +378,10 @@
"name": "wdio-chromedriver-service",
"allowedCategories": [ "trackers" ]
},
{
"name": "web-vitals",
"allowedCategories": [ "plugins" ]
},
{
"name": "webdriverio",
"allowedCategories": [ "trackers" ]
Expand Down
55 changes: 55 additions & 0 deletions common/config/rush/pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion common/config/rush/repo-state.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// DO NOT MODIFY THIS FILE MANUALLY BUT DO COMMIT IT. It is generated and used by Rush.
{
"pnpmShrinkwrapHash": "5484bd61ddb42855b5228699721d75c1d5b9cb25",
"pnpmShrinkwrapHash": "1a9deb48a8d2843fb67d9c93ff618d8373ca31c8",
"preferredVersionsHash": "bf21a9e8fbc5a3846fb05b4fa0859e0917b2202f"
}
29 changes: 29 additions & 0 deletions plugins/browser-plugin-web-vitals/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
BSD 3-Clause License

Copyright (c) 2023 Snowplow Analytics Ltd
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
68 changes: 68 additions & 0 deletions plugins/browser-plugin-web-vitals/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# Snowplow Web Vitals Tracking

[![npm version][npm-image]][npm-url]
[![License][license-image]](LICENSE)

Browser Plugin to be used with `@snowplow/browser-tracker`.

The plugin adds the capability to track web performance metrics categorized as [Web Vitals](https://web.dev/vitals/). These metrics are tracked with an event based on the [web_vitals schema](https://github.com/snowplow/iglu-central/blob/master/schemas/com.snowplowanalytics.snowplow/web_vitals/jsonschema/).

## Maintainer quick start

Part of the Snowplow JavaScript Tracker monorepo.
Build with [Node.js](https://nodejs.org/en/) (14 or 16) and [Rush](https://rushjs.io/).

### Setup repository

```bash
npm install -g @microsoft/rush
git clone https://github.com/snowplow/snowplow-javascript-tracker.git
rush update
```

## Package Installation

With npm:

```bash
npm install @snowplow/browser-plugin-web-vitals
```

## Usage

Initialize your tracker with the `WebVitalsPlugin`:

```js
import { newTracker } from '@snowplow/browser-tracker';
import { WebVitalsPlugin } from '@snowplow/browser-plugin-web-vitals';

newTracker('sp1', '{{collector}}', { plugins: [ WebVitalsPlugin(/* pluginOptions */) ] });

/*
* Available plugin options `WebVitalsPluginOptions`:
* {
* loadWebVitalsScript: Should the plugin immediately load the Core Web Vitals measurement script from UNPKG CDN.
* webVitalsSource: The URL endpoint the Web Vitals script should be loaded from. Defaults to the UNPKG CDN.
* }
*/
```

### Choosing a Web Vitals measurement source

The default Web Vitals measurement script is loaded from the [UNPKG](https://www.unpkg.com/) CDN. This choice is chosen as a default but you should consider your own setup when choosing the script source. Selecting a script source from a CDN which might already be used in your website might save you from yet another connection startup time (_Queueing_,_DNS lookup_,_TCP_, _SSL_).

Another reasonable choice could be [jsDelivr](https://cdn.jsdelivr.net/npm/web-vitals@3/dist/web-vitals.iife.js).

## Copyright and license

Licensed and distributed under the [BSD 3-Clause License](LICENSE) ([An OSI Approved License][osi]).

Copyright (c) 2023 Snowplow Analytics Ltd.

All rights reserved.

[npm-url]: https://www.npmjs.com/package/@snowplow/browser-plugin-web-vitals
[npm-image]: https://img.shields.io/npm/v/@snowplow/browser-plugin-web-vitals
[docs]: https://docs.snowplowanalytics.com/docs/collecting-data/collecting-from-own-applications/javascript-tracker/
[osi]: https://opensource.org/licenses/BSD-3-Clause
[license-image]: https://img.shields.io/npm/l/@snowplow/browser-plugin-web-vitals
5 changes: 5 additions & 0 deletions plugins/browser-plugin-web-vitals/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module.exports = {
preset: 'ts-jest',
reporters: ['jest-standard-reporter'],
testEnvironment: 'jest-environment-jsdom-global',
};
54 changes: 54 additions & 0 deletions plugins/browser-plugin-web-vitals/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
{
"name": "@snowplow/browser-plugin-web-vitals",
"version": "3.11.0",
"description": "Adds the capability to track web performance metrics categorized as Web Vitals.",
"homepage": "https://github.com/snowplow/snowplow-javascript-tracker",
"bugs": "https://github.com/snowplow/snowplow-javascript-tracker/issues",
"repository": {
"type": "git",
"url": "https://github.com/snowplow/snowplow-javascript-tracker.git"
},
"license": "BSD-3-Clause",
"author": "Snowplow Analytics Ltd (https://snowplow.io/)",
"sideEffects": false,
"main": "./dist/index.umd.js",
"module": "./dist/index.module.js",
"types": "./dist/index.module.d.ts",
"files": [
"dist"
],
"scripts": {
"build": "rollup -c --silent --failAfterWarnings",
"test": "jest"
},
"dependencies": {
"@snowplow/browser-tracker-core": "workspace:*",
"@snowplow/tracker-core": "workspace:*",
"tslib": "^2.3.1",
"web-vitals": "~3.3.2"
matus-tomlein marked this conversation as resolved.
Show resolved Hide resolved
},
"devDependencies": {
"@ampproject/rollup-plugin-closure-compiler": "~0.27.0",
"@rollup/plugin-commonjs": "~21.0.2",
"@rollup/plugin-node-resolve": "~13.1.3",
"@types/jest": "~27.4.1",
"@types/jsdom": "~16.2.14",
"@typescript-eslint/eslint-plugin": "~5.15.0",
"@typescript-eslint/parser": "~5.15.0",
"eslint": "~8.11.0",
"jest": "~27.5.1",
"jest-environment-jsdom": "~27.5.1",
"jest-environment-jsdom-global": "~3.0.0",
"jest-standard-reporter": "~2.0.0",
"rollup": "~2.70.1",
"rollup-plugin-cleanup": "~3.2.1",
"rollup-plugin-license": "~2.6.1",
"rollup-plugin-terser": "~7.0.2",
"rollup-plugin-ts": "~2.0.5",
"ts-jest": "~27.1.3",
"typescript": "~4.6.2"
},
"peerDependencies": {
"@snowplow/browser-tracker": "~3.11.0"
}
}
37 changes: 37 additions & 0 deletions plugins/browser-plugin-web-vitals/rollup.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { nodeResolve } from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import ts from 'rollup-plugin-ts'; // Preferred over @rollup/plugin-typescript as it bundles .d.ts files
import { banner } from '../../banner';
import compiler from '@ampproject/rollup-plugin-closure-compiler';
import { terser } from 'rollup-plugin-terser';
import cleanup from 'rollup-plugin-cleanup';
import pkg from './package.json';
import { builtinModules } from 'module';

const umdPlugins = [nodeResolve({ browser: true }), commonjs(), ts()];
const umdName = 'snowplowWebVitals';

export default [
// CommonJS (for Node) and ES module (for bundlers) build.
{
input: './src/index.ts',
plugins: [...umdPlugins, banner()],
treeshake: { moduleSideEffects: ['sha1'] },
output: [{ file: pkg.main, format: 'umd', sourcemap: true, name: umdName }],
},
{
input: './src/index.ts',
plugins: [...umdPlugins, compiler(), terser(), cleanup({ comments: 'none' }), banner()],
treeshake: { moduleSideEffects: ['sha1'] },
output: [{ file: pkg.main.replace('.js', '.min.js'), format: 'umd', sourcemap: true, name: umdName }],
},
{
input: './src/index.ts',
external: [...builtinModules, ...Object.keys(pkg.dependencies), ...Object.keys(pkg.devDependencies)],
plugins: [
ts(), // so Rollup can convert TypeScript to JavaScript
banner(),
],
output: [{ file: pkg.module, format: 'es', sourcemap: true }],
},
];
74 changes: 74 additions & 0 deletions plugins/browser-plugin-web-vitals/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import { BrowserPlugin, BrowserTracker, dispatchToTrackersInCollection } from '@snowplow/browser-tracker-core';
import { buildSelfDescribingEvent } from '@snowplow/tracker-core';
import { WEB_VITALS_SCHEMA } from './schemata';
import { attachWebVitalsPageListeners, createWebVitalsScript, webVitalsListener } from './utils';

const _trackers: Record<string, BrowserTracker> = {};
const WEB_VITALS_SOURCE = 'https://unpkg.com/web-vitals@3/dist/web-vitals.iife.js';
jethron marked this conversation as resolved.
Show resolved Hide resolved
igneel64 marked this conversation as resolved.
Show resolved Hide resolved
let listenersAttached = false;

interface WebVitalsPluginOptions {
loadWebVitalsScript?: boolean;
webVitalsSource?: string;
}

const defaultPluginOptions = {
loadWebVitalsScript: true,
webVitalsSource: WEB_VITALS_SOURCE,
};

/**
* Adds Web Vitals measurement events
*
* @param pluginOptions.loadWebVitalsScript - Should the plugin immediately load the Core Web Vitals measurement script from UNPKG CDN.
* @param pluginOptions.webVitalsSource - The URL endpoint the Web Vitals script should be loaded from. Defaults to the UNPKG CDN.
* @remarks
*/
export function WebVitalsPlugin(pluginOptions: WebVitalsPluginOptions = defaultPluginOptions): BrowserPlugin {
const webVitalsObject: Record<string, unknown> = {};
Copy link
Contributor

@jethron jethron May 18, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should the type of this be more explicit, like at least Record<string, string | number>?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Slightly funkier, but probably not worth it:

export type WebVitalsPayload = {
  navigationType: Metric["navigationType"];
} & {
  [f in Lowercase<Metric["name"]>]: Metric["value"];
};

const options = { ...defaultPluginOptions, ...pluginOptions };
let trackerId: string;
let webVitalsScript: HTMLScriptElement | undefined;
return {
activateBrowserPlugin: (tracker) => {
trackerId = tracker.id;
_trackers[trackerId] = tracker;

function sendWebVitals() {
if (!Object.keys(webVitalsObject).length) {
return;
}
dispatchToTrackersInCollection(Object.keys(_trackers), _trackers, (t) => {
t.core.track(
buildSelfDescribingEvent({
event: {
schema: WEB_VITALS_SCHEMA,
data: webVitalsObject,
igneel64 marked this conversation as resolved.
Show resolved Hide resolved
},
})
);
});
}

if (options.loadWebVitalsScript) {
webVitalsScript = createWebVitalsScript(options.webVitalsSource);
}

/*
* Attach page listeners only once per page.
* Prevent multiple trackers from attaching listeners multiple times.
*/
if (!listenersAttached) {
if (webVitalsScript) {
webVitalsScript.addEventListener('load', () => webVitalsListener(webVitalsObject));
} else {
webVitalsListener(webVitalsObject);
}
attachWebVitalsPageListeners(sendWebVitals);
listenersAttached = true;
}

return;
},
};
}
1 change: 1 addition & 0 deletions plugins/browser-plugin-web-vitals/src/schemata.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const WEB_VITALS_SCHEMA = 'iglu:com.snowplowanalytics.snowplow/web_vitals/jsonschema/1-0-0';
Loading