npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

Iโ€™ve always been into building performant and accessible sites, but lately Iโ€™ve been taking it extremely seriously. So much so that Iโ€™ve been building a tool to help me optimize and monitor the sites that I build to make sure that Iโ€™m making an attempt to offer the best experience to those who visit them. If youโ€™re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, ๐Ÿ‘‹, Iโ€™m Ryan Hefnerย  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If youโ€™re interested in other things Iโ€™m working on, follow me on Twitter or check out the open source projects Iโ€™ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soonโ€“ish.

Open Software & Tools

This site wouldnโ€™t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you ๐Ÿ™

ยฉ 2024 โ€“ย Pkg Stats / Ryan Hefner

coveo.analytics

v2.30.42

Published

๐Ÿ“ˆ Coveo analytics client (node and browser compatible)

Downloads

100,775

Readme

coveo.analytics

Build Status Coverage Status TypeScript

Coveo Analytics JavaScript client

The Coveo analytics javascript client, also called coveo.analytics.js or coveoua for short, is responsible for logging analytics events to the Coveo platform. Analytics events may include basic Coveo web events such as clicks or searches. For specific usecases, such as commerce and service, dedicated events may be defined and logged.

The analytics library is bundled with all Coveo provided UI components. Integrations which exclusively rely on these components, generally don't have to interact with coveoua directly. For Coveo integrations which integrate with an already existing UI and do not use headless, coveoua will be required to ensure events are logged correctly.

Loading and initializing the library in the browser

In order to ensure the tracking code is available on your webpage, the following code snippet needs to be added to the top of each page on which analytics are required. This will load the latest major version of coveo.analytics.js from a Coveo CDN. As of writing, the current major version is 2.

<script>
    (function (c, o, v, e, O, u, a) {
        a = 'coveoua';
        c[a] =
            c[a] ||
            function () {
                (c[a].q = c[a].q || []).push(arguments);
            };
        c[a].t = Date.now();
        u = o.createElement(v);
        u.async = 1;
        u.src = e;
        O = o.getElementsByTagName(v)[0];
        O.parentNode.insertBefore(u, O);
    })(window, document, 'script', 'https://static.cloud.coveo.com/coveo.analytics.js/2/coveoua.js');
</script>

coveoua('init', #COVEO_API_KEY); // Replace #COVEO_API_KEY with your api key

Since calls to the coveo analytics service need to be authenticated, the library needs to be initialized with a Coveo api key which has push access to the Analytics Data Domain. You can create an API key from the administration console selecting the Push option box for the Analytics Data domain (see Adding and Managing API Keys).

Available actions

After the library has loaded sucessfully, you can interact with coveoua through the global coveoua function. Any interaction with the library happens through this function by supplying both a action name, followed by an optional series of action arguments. The following actions are available:

Initialization

  • coveoua('version'): Returns the current version of the tracking library.
  • coveoua('init', <COVEO_API_KEY>, <ENDPOINT>): Initializes the library with the given api key and endpoint. The following parameters are accepted
    • COVEO_API_KEY (mandatory): A valid api key.
    • ENDPOINT (optional): A string specifying the desired analytics endpoint. The default value is https://analytics.cloud.coveo.com/rest/ua. In case your organization is HIPAA enabled, you should override with https://analyticshipaa.cloud.coveo.com/rest/ua.
  • coveoua('init', <COVEO_API_KEY>, {endpoint: <ENDPOINT>, isCustomEndpoint: <IS_CUSTOM_ENDPOINT>, plugins: <PLUGINS>}): Initializes the library with the given api key, endpoint, isCustomEndpoint option and plugins. The following parameters are accepted
    • COVEO_API_KEY (mandatory): A valid api key.
    • ENDPOINT (optional): An object string specifying the desired analytics endpoint. The default value is https://analytics.cloud.coveo.com/rest/ua. In case your organization is HIPAA enabled, you should override with https://analyticshipaa.cloud.coveo.com/rest/ua.
    • IS_CUSTOM_ENDPOINT (optional): An boolean specifying if the desired analytics endpoint is custom. This means the library will not try to add any prefix logic like /rest/ua at the end of the provided endpoint. This can be useful when implementing analytics through a reverse-proxy solution like cloudfront.
    • PLUGINS (optional): An array of known plugin names. See plugins for more information.
  • coveoua('set', <NAME>, <VALUE>): Attempts to inject an attribute with given name and value on every logged event, overriding any existing value. Some payloads may reject attributes they do not support.
  • coveoua('set', <OBJECT>): Attempts to inject all attributes and values of the given object on every logged event, overriding any existing value. Some payloads may reject attributes they do not support.
  • coveoua('set', 'custom', <OBJECT>): Attempts to inject all attributes and values of the given object in the custom section of an object, overriding any existing value. Use this call to pass customer specific parameters on the payload.
  • coveoua('onLoad', <CALLBACK>): Calls the specified function immediately, library initialization is not required.
  • coveoua('reset'): Resets the state of the logger to the state before initialization.

Sending events

  • coveoua('send', <EVENT_NAME>, <EVENT_PAYLOAD>): Sends an event with a given name and payload to the analytics endpoint.

Plugin control

  • coveoua('provide', <PLUGIN_NAME>, <PLUGINCLASS>): Registers a given pluginClass with the analytics library under the provided name.
  • coveoua('require', <PLUGIN_NAME>): Explicitly loads the plugin with the given name.
  • coveoua('callPlugin', <PLUGIN_NAME>, <FUNCTION>, <PARAMS>): Executes the specified function with given arguments on the given plugin name. Can be shorthanded using a plugin action prefix coveoua(<PLUGINNAME>:<FUNCTION>, <PARAMS>).

Plugins

Coveoua is set up in a modular way with different plugins providing functionality that may be specific to a given usecase. This allows you to customize some of its behavior dynamically. By default, the following plugins are loaded at library initialization:

  • ec: eCommerce plugin which takes care of sending eCommerce specific events.
  • svc: Service plugin which takes care of sending customer service specific events.

Plugin actions extend the set of available actions. They can be executed either via the callPlugin action above, or via the shorthand. For example, to call the function addImpression on the ec plugin, you'd specify coveoua('ec:addImpression', ...).

It is possible to disable loading of any plugins by explicitly initializing the library with an empty list of plugins using coveoua('init', <API_KEY>, {plugins:[]}).

Sending basic usage analytics events

In most common integration usecases, you will be using Coveo pre-wired components (e.g. jsui, headless or atomic) to handle communication with the Coveo backend. These components have their own specific apis to handle event logging.

When you are not using any specific Coveo web component, you need to send these events payloads explicitly, use the send action to transmit an assembled payload to the usage analytics backend. See the Usage Analytics Events documentation for description of the payload contents. The following event types are supported in coveoua:

For example, in order to send a click event after a user has interacted with a Coveo provided result, first initialize the library with an api key and then send a click event with the appropriate payload. Refer to the click event documentation for up to date information on event payloads.

coveoua('send', 'click', {...});

You should be able to observe the click event being transmitted to the Coveo backend at https://analytics.cloud.coveo.com/rest/ua/click in the Developer tool's Network tab of your browser of choice.

Sending commerce specific events

Commerce specific events such as product selections, shopping cart modifications and transactions are sent to Coveo in the compact collect protocol. Rather than explicitly assembling these payloads by hand, the eCommerce plugin provides APIs to assemble and transmit the payloads. The event is specific to the eCommerce plugin:

  • event: An event, which has been assembled through different plugin actions.

The eCommerce plugin supports adding product data (ec:addProduct) as well as setting the appropriate event action through ec:setAction. These calls can be used in series to assemble different types of payloads:

As a sample, here is how a cart modification event is assembled:

  1. First use the ec:addProduct action to include the relevant product data in the event youโ€™re about to send
    coveoua('ec:addProduct', <PRODUCT_DATA>);
  2. Then use the ec:setAction action to specify that the action done on this data is an addition to the cart.
    coveoua('ec:setAction', 'add');
  3. Finally, use the send action to send the generic event to Coveo Usage Analytics. The payload is implicit in this case, and has been generated by the plugin.
    coveoua('send', 'event');

Linking clientIds across different domains using a URL parameter

To help track a visitor across different domains, the library offers functionality to initialize a clientId from a URL query parameter. The query parameter is named cvo_cid with value <clientid>.<timestamp>. The clientId is encoded without dashes and the timestamp is encoded in seconds since epoch, both to save space in the url. Both are separated by a period. A sample parameter could be cvo_cid=c0b48880743e484f8044d7c37910c55b.1676298678. This query parameter will be picked up by the target page if the following conditions hold:

  • The target page has a equal or greater version of coveo.analytics.js loaded.
  • The current URL contains a cvo_cid query parameter
  • The parameter contains a valid uuid.
  • The parameter contains a valid timestamp, and that timestamp is no more than 120 seconds in the past.
  • The receiving page has specified a list of valid referrers and the current referrer host matches that list, using wildcards, including ports, specified using coveoua('link:acceptFrom', [<referrers>]).

Given that you want to ensure the clientId remains consistent when you navigate from a source page on http://foo.com/index.html to a target page http://bar.com/index.html, the following steps are needed.

  1. Ensure coveo.analytics.js is loaded on the source page.
  2. Modify the source page such that whenever a link to the target page is clicked, its href is replaced by coveoua('link:decorate', 'http://bar.com/index.html'). For example, by creating an onClick event listener on the element or on the page. It's important that the decorated link is generated at the moment the link is clicked, as it will be valid only for a short time after generation.
<script>
    async function decorate(element) {
        element.href = await coveoua('link:decorate', element.href);
    }
</script>
<a onclick="decorate(this)" href="http://bar.com/index.html">Navigate</a>>
  1. Ensure coveo.analytics.js is loaded on the target page.
  2. Ensure that the target page allows reception of links from the source page by adding coveoua('link:acceptFrom', ['foo.com']); immediately after script load.

Developer information

Information for contributors or Coveo developers developing or integrating coveoua.

Setup

git clone
npm install
npm run build

Running and observing the code

There are two ways to run your code locally:

  1. Run npm run start and open your browser on http://localhost:9001

  2. Debugging through VSCode debugger with the Debug: Start Debugging command, using the Launch Chrome configuration.

To test out your changes, add coveoua function calls in the public/index.html file and check the payload in the Developer Console section of your browser.

Running tests

  1. From the command line through npm run test.
  2. Debugging through VSCode debugger with the Debug: Start Debugging command, using the Jest All configuration.

Storage and persistence

Coveo.analytics.js tracks interactions from the same browser client, through a client side provided uuid called a clientId. This clientId is initialized on first use and there are multiple options for persisting it's value:

  • Cookie storage, which supports top level domain storage. This means that the clientId for a.foo.com will be identical to the one on b.foo.com.
  • Local storage, which allows to store much more information client side, but has the drawback of not being able to access data across multiple top level domains.
  • Session storage, which has roughly the same limitation and capability as Local storage, except that it is cleared when the web browser tab is closed.

By default, coveoua will use both local storage and cookie storage to persist its clientId. If your environment does not support local persistence, it's possible to write your own storage abstraction.

Using coveo.analytics.js with React Native

Since React Native does not run inside a browser, it cannot use cookies or the local/session storage that modern browsers provide. You must provide your own Storage implementation. Thankfully, there exist multiple packages to store data:

A sample React native storage class implementation could look as follows

import {CoveoAnalyticsClient, ReactNativeRuntime} from 'coveo.analytics/react-native';
// Use any React native storage library or implement your own.
import AsyncStorage from '@react-native-async-storage/async-storage';

// Sample storage class
class ReactNativeStorage implements WebStorage {
    async getItem(key: string) {
        return AsyncStorage.getItem(key);
    }
    async setItem(key: string, data: string) {
        return AsyncStorage.setItem(key, data);
    }
    async removeItem(key: string) {
        AsyncStorage.removeItem(key);
    }
}

// Create an API client with a specific runtime
const client = new CoveoAnalyticsClient({
    token: 'YOUR_API_KEY',
    runtimeEnvironment: new ReactNativeRuntime({
        token: 'YOUR_API_KEY',
        storage: new ReactNativeStorage(),
    }),
});

// Send your event
client.sendCustomEvent({
    eventType: 'dog',
    eventValue: 'Hello! Yes! This is Dog!',
    language: 'en',
});

Conformance

Chrome, Firefox, Safari, Edge. IE11 support on a reasonable-effort basis.

Contributing

See CONTRIBUTING.md

License

MIT license (see LICENSE).

forthebadge coveo