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

@klevu/core

v5.2.1

Published

Typescript SDK that simplifies development on Klevu backend. Klevu provides advanced AI-powered search and discovery solutions for online retailers.

Downloads

6,829

Readme

Klevu

npm version Bundle size npm total downloads npm weekly downloads github stars github issues

Come and chat with us:

@klevu/core

Klevu core is a library that helps developers to interact with Klevu API. It includes a fetching function, easy-to-use functions to perform queries, state management for filters, data transformations and event tracking for easier usage.

The library can run its code in browsers and Node.js.

Api Reference can be found from here

Getting started

> npm install @klevu/core

Initialization

Before making any request it is required to provide the Klevu API key and the search server you are targeting. This should be done in the index of the application or the initialization of your app.

import { KlevuConfig } from "@klevu/core"

KlevuConfig.init({
  url: "https://<your-server>.ksearchnet.com/cs/v2/search",
  apiKey: "klevu-xxxxxxxxxxxxx",
})

If you wish to use Axios to enable SSR or you wish to support old IE browser you can use axios npm package with the library.

First you need to install it into to your project with

> npm install axios

Then import and add it to your configuration.

import { KlevuConfig } from "@klevu/core"
import axios from "axios"

KlevuConfig.init({
  url: "https://<your-server>.ksearchnet.com/cs/v2/search",
  apiKey: "klevu-xxxxxxxxxxxxx",
  axios,
})

Then axios will be used for fetching data.

KlevuFetch

Function queries are inserted into a KlevuFetch() function where functions are processed and sent to the backend.

Here is the most minimal example where we are making a "hoodies" search from the API.

import { KlevuFetch, search } from "@klevu/core"

const result = await KlevuFetch(search("hoodies"))
console.log(result.getQueriesById("search")?.records)

Typical example

The following example finds results based on a term and suggestions what the user could search for next

import { KlevuFetch, search } from "@klevu/core"

// search string coming from a textfield
const term = "hoodies"

const result = await KlevuFetch(
  search(
    // term to search
    term,
    // search parameters
    {},
    // and lastly list of modifiers for the query.
    // In this example we are fetching all filters that are related to the search
    listFilters()
    // More modifiers can be added as parameters to search.
  ),
  // In same fetch we want to fetch all search suggestions also
  suggestion(term)
  // in here we could add more queries to fetch
)

// Prints records that are found from the search
console.log(result.getQueriesById("search")?.records)

Result object

KlevuFetch() result object contains raw API response and handy helpers to get results. Use getSuggestionsById() to fetch suggestions results and getQueriesById() for search results.

getQueriesById() result contains metadata for query, the result records and possible event functions for providing click events to search, category merchandising and recommendations. It also includes next() function. It is a nice helper to fetch the next results set with the same query and modifiers. next() is defined only if there are more results available.

Calling event functions returns a function to use to send events to Klevu. See definition these functions from here

Platform-specific guides

Queries

Queries implement the KlevuFetchFunction interface. Multiple queries can be passed onto KlevuFetch. For example its possible to get suggestions and multiple search results for typed letters in one request.

Detailed information in API reference.

| Klevu Function | Description | Type | | ---------------------------- | -------------------------------------------------------------------------------- | -------------- | | search() | Most basic query to find items based on a term | Search | | suggestions() | Fetches suggestions based on a term. | Search | | trendingProducts() | Find all products that are trending right now in results | Search | | categoryMerchandising() | Products to display on category page | Search | | searchCategory() | Search categories based on term | Search | | searchCms() | Search CMS pages based on term | Search | | products() | Fetches products by id from Klevu | Search | | raw | Write raw request to Klevu api. For expert use | Search | | recentlyViewedProducts() | List of products user has recently viewed | Search | | kmcRecommendation() | Fetches predefined recommendation by id from KMC and creates query automatically | Recommendation | | newArrivals() | Recommendation list of new arrivals for the current user | Recommendation | | trendingCategoryProducts() | Trending recommendation based for current user | Recommendation | | similarProducts() | Fetch similar products based on given ids | Recommendation | | alsoViewed() | Product recommendations what user should also check out | Recommendation | | boughtTogether() | On checkout page check what products are recommended to current cart products | Recommendation |

Modifiers

Some of the functions can be modified with modifier functions. Any number of them can be added to end of query functions

| Modifier | Description | | ------------------------------- | ---------------------------------------------------------------------------------------------------- | | listFilters() | List all filters that given search result has | | applyFilters() | Applies selected filters to query | | applyFiltersWithManager() | Applies filters that's state is managed by FilterManager | | fallback() | When query returns less results than fallback treshold then additional fallback query is sent | | boostWithKeywords() | Boost or deboost results with keywords | | boostWithRecords() | Boost or deboost certain products in the result by id | | boostWithFilters() | Boost or deboost results based on a filters | | boostWithFilterManager() | Boost or deboost results based in selection in filter manager | | personalisation() | Enable personalisation to the query. Automatically applies last visited products | | include() | Force include given id's in the result | | top() | Force return given id's as first items on results | | sendSearchEvent() | When user takes action to search something this should be used | | sendMerchandisingViewEvent() | Should be used with categoryMerchandising() query to send view event of merchandising | | sendRecommendationViewEvent() | Should be used with all recommendation queries. Send a analytical data about recommendation to Klevu | | debug() | Prints query results to console | | abTest() | Enable A/B testing for the category merchandising | | overrideSettings() | Allows to override any setting in query. ⚠️ Use with caution! |

Filter Manager

Filter Manager is a helper class that takes care of the state of filters. What filters are currently selected and what should be sent. It can be passed to listFilters() and then the result is automatically applied to the state. Modifier applyFiltersWithManager() can base used to apply the current state of filters to query.

Internal DOM events

Core sends a DOM events that any browser library could listen and act on the events. All events are attached to document. KlevuDomEvents enumeration is exposed from the library and it's quite simple to listen. For example:

import { KlevuDomEvents, KlevuListenDomEvent } from "@klevu/core"

// Function to run when filter selection is updated
const handleFilterUpdate = () => {
  console.log("Filter updated")
}

// Attach event listener
const stop = KlevuListenDomEvent(KlevuDomEvents.FilterSelectionUpdate, handleFilterUpdate)

// Don't forget remove event listener in your component destructor
stop()

Or as React example

import React, { useEffect } from "react";
import { KlevuDomEvents, KlevuListenDomEvent } from "@klevu/core";


function MyComponent() {
  const handleFilterUpdate = (event) => {
    console.log(event.detail)
  }

  useEffect(() => {
    const stop = KlevuListenDomEvent(
      KlevuDomEvents.FilterSelectionUpdate,
      handleFilterUpdate
    )

    // cleanup this component
    return () => {
      stop()
    }
  }, [])

  return ...
}

Read more from MDN documentation about Custom Events.

See the list of events from KlevuDomEvents

Events

Klevu requires data for machine learning to work better. KlevuEvents class is low level solution to pass events to Klevu backend.

KlevuEvents.productClick()

| Method | Description | | ------------------------------------- | -------------------------------------------------------------- | | buy() | When products are bought | | searchProductClick() | When product is clicked on search results | | search() | When search is made. This is automatically sent in the queries | | categoryMerchandisingView() | When category is displayed. Should be called on paging too | | categoryMerchandisingProductClick() | When product is clicked in category page | | recommendationClick() | When product is clicked on list of recommended products | | recommendationView() | When recommendations are shown |

Klevu Merchant Center settings

Users of Klevu can change settings in the Klevu Merchant Center. These settings can be easily fetched with KlevuKMCSettings function.

const result = await KlevuKMCSettings()

Last searches

To get the list of last searches you can use the KlevuLastSearches class.

To get the list of last searches call KlevuLastSearches.get() and if you wish to store a search use KlevuLastSearches.save('user search string')

A/B Testing

Currently A/B testing is supported only in the category merchandising. To enable A/B testing add abTest() modifier to categoryMerchandising() query function.

For A/B testing to work correctly you need to provide correct event data to Klevu. Best way is to use getCategoryMerchandisingClickSendEvent() send event helper from result object .

SSR request packing and hydration

Typically SSR frameworks (Next, Nuxt, Remix, etc) will transfer data from backend to frontend in JSON format. Passing KlevuFetch result object to frontend won't work as it is filled with functions that help the usage of results.

There is an option to just pass raw JSON with result.apiResponse and build your logic on top of that.

If you wish to keep using helper functions provided in results you can use KlevuPackFetchResult() function to pack result like:

const result = await KlevuFetch(search("hello world"))
const dataToTransferFrontend = KlevuPackFetchResult(result)

And then you can hydrate it in frontend with KlevuHydratePackedFetchResult() function.

const resultObject = KlevuHydratePackedFetchResult(dataToTransferFrontend, [search("hello world")])

It's important to note that the second parameter of KlevuHydratePackedFetchResult() has to be the same as in backend call. You can create query functions in a separate file that can be called both in frontend and backend. For example:

// file: myquery.ts
// a bit more compilicated query. Search term can be read in backend
// from request parameters and in frontend it could be in url parameters
const myQuery = (searchTerm: string, manager: FilterManager) => [search(searchTerm, {}, listFilters(), applyFilterwithManager(manager), boostWithKeyword({ keyword: "foobar", weight: 1.2 })), suggestions(searchTerm)]

// file: backend.ts
// in backend manager is not used to set anything so it can be just instanciated as param
const result = await KlevuFetch(myQuery("hello world", new FilterManager()))
const dataToTransferFrontend = KlevuPackFetchResult(result)

// file: frontend.ts
// in frontend we usually want to change and set filters with manager so it's used as separate variable
const manager = new FilterManager()
const resultObject = KlevuHydratePackedFetchResult(dataToTransferFrontend, myQuery("hello world", manager))
console.log(manager.options)

Data Protection

For customers who need to comply with data protection rules, you can enable data protection in the SDK by setting the useConsent to true and then setting the consentGiven value to true when you receive the consent from the user. By default, the data protection is turned off. You can use the following code snippet as an example to set it up

KlevuConfig.init({
  url: "https://eucs23v2.ksearchnet.com/cs/v2/search",
  apiKey: "klevu-160320037354512854",
  useConsent: true, //Either set it to true during initialization
  consentGiven: true, //Either set it to true during initialization
})
// or
KlevuConfig.getDefault().setUseConsent(true)
KlevuConfig.getDefault().setConsentGiven(true) // When you receive the user consent

If useConsent is enabled, then no user data will be used by Klevu till the consentGiven is enabled.

Using Klaviyo for segmentation

To enable Klaviyo integration for segemntation in Recommendations, set enableKlaviyoConnector to true.

KlevuConfig.init({
  url: "https://eucs23v2.ksearchnet.com/cs/v2/search",
  apiKey: "klevu-160320037354512854",
  enableKlaviyoConnector: true, //To enable Klaviyo integration for segmentation in Recommendations
})

Setitng enableKlaviyoConnector to true will make all the necessary internal configuration changes for Klevu Recommendations to work with Klaviyo segments.

You should consider using this feature with Data protection settings if there is a need to meet any legal requirements. If Data Protection is enabled, then no user data will be stored unless the consent is given.

Check above for more information.