@snowplow/node-tracker
Advanced tools
Comparing version 3.24.2 to 3.24.3-dev.0
@@ -1,32 +0,31 @@ | ||
import { Payload, TrackerCore } from "@snowplow/tracker-core"; | ||
import { Response, RequestError, Agents, RequiredRetryOptions, ToughCookieJar, PromiseCookieJar } from "got"; | ||
interface Emitter { | ||
flush: () => void; | ||
input: (payload: Payload) => void; | ||
/** Set if the requests from the emitter should be anonymized. Read more about anonymization used at https://docs.snowplow.io/docs/collecting-data/collecting-from-own-applications/snowplow-tracker-protocol/going-deeper/http-headers/. */ | ||
setAnonymization?: (shouldAnonymize: boolean) => void; | ||
} | ||
declare enum HttpProtocol { | ||
HTTP = "http", | ||
HTTPS = "https" | ||
} | ||
declare enum HttpMethod { | ||
GET = "get", | ||
POST = "post" | ||
} | ||
/** | ||
* Create an emitter object, which uses the `got` library, that will send events to a collector | ||
* | ||
* @param endpoint - The collector to which events will be sent | ||
* @param protocol - http or https | ||
* @param port - The port for requests to use | ||
* @param method - get or post | ||
* @param bufferSize - Number of events which can be queued before flush is called | ||
* @param retry - Configure the retry policy for `got` - https://github.com/sindresorhus/got/blob/v11.5.2/readme.md#retry | ||
* @param cookieJar - Add a cookieJar to `got` - https://github.com/sindresorhus/got/blob/v11.5.2/readme.md#cookiejar | ||
* @param callback - Callback called after a `got` request following retries - called with ErrorRequest (https://github.com/sindresorhus/got/blob/v11.5.2/readme.md#errors) and Response (https://github.com/sindresorhus/got/blob/v11.5.2/readme.md#response) | ||
* @param agents - Set new http.Agent and https.Agent objects on `got` requests - https://github.com/sindresorhus/got/blob/v11.5.2/readme.md#agent | ||
* @param serverAnonymization - If the request should undergo server anonymization. | ||
*/ | ||
declare function gotEmitter(endpoint: string, protocol?: HttpProtocol, port?: number, method?: HttpMethod, bufferSize?: number, retry?: number | Partial<RequiredRetryOptions>, cookieJar?: PromiseCookieJar | ToughCookieJar, callback?: (error?: RequestError, response?: Response<string>) => void, agents?: Agents, serverAnonymization?: boolean): Emitter; | ||
/* | ||
* Copyright (c) 2022 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. | ||
*/ | ||
import { TrackerCore, Emitter, EmitterConfiguration } from "@snowplow/tracker-core"; | ||
interface Tracker extends TrackerCore { | ||
@@ -57,13 +56,23 @@ /** | ||
setSessionIndex: (sessionIndex: string | number) => void; | ||
/** | ||
* Calls flush on all emitters in order to send all queued events to the collector | ||
* @returns Promise<void> - Promise that resolves when all emitters have flushed | ||
*/ | ||
flush: () => Promise<void>; | ||
} | ||
/** | ||
* Snowplow Node.js Tracker | ||
* | ||
* @param string - or array emitters The emitter or emitters to which events will be sent | ||
* @param string - namespace The namespace of the tracker | ||
* @param string - appId The application ID | ||
* @param boolean - encodeBase64 Whether unstructured events and custom contexts should be base 64 encoded | ||
*/ | ||
declare function tracker(emitters: Emitter | Array<Emitter>, namespace: string, appId: string, encodeBase64: boolean): Tracker; | ||
export { Emitter, HttpMethod, HttpProtocol, gotEmitter, tracker, Tracker }; | ||
export { version, buildAdClick, buildAdConversion, buildAdImpression, buildAddToCart, buildConsentGranted, buildConsentWithdrawn, buildEcommerceTransaction, buildEcommerceTransactionItem, buildFormFocusOrChange, buildFormSubmission, buildLinkClick, buildPagePing, buildPageView, buildRemoveFromCart, buildScreenView, buildSelfDescribingEvent, buildSiteSearch, buildSocialInteraction, buildStructEvent, AdClickEvent, ContextEvent, PagePingEvent, PageViewEvent, AddToCartEvent, LinkClickEvent, ScreenViewEvent, SiteSearchEvent, StructuredEvent, AdConversionEvent, AdImpressionEvent, ConsentGrantedEvent, FormSubmissionEvent, RemoveFromCartEvent, SelfDescribingEvent, ConsentWithdrawnEvent, FormFocusOrChangeEvent, SocialInteractionEvent, EcommerceTransactionEvent, EcommerceTransactionItemEvent, SelfDescribingJson, Timestamp, PayloadBuilder, Payload, CorePlugin, CoreConfiguration, ContextGenerator, ContextFilter, EventPayloadAndContext } from '@snowplow/tracker-core'; | ||
interface TrackerConfiguration { | ||
/* The namespace of the tracker */ | ||
namespace: string; | ||
/* The application ID */ | ||
appId: string; | ||
/* Whether unstructured events and custom contexts should be base64 encoded. */ | ||
encodeBase64: boolean; | ||
} | ||
type CustomEmitter = { | ||
/* Function returning custom Emitter or Emitter[] to be used. If set, other options are irrelevant */ | ||
customEmitter: () => Emitter | Array<Emitter>; | ||
}; | ||
type NodeEmitterConfiguration = CustomEmitter | EmitterConfiguration; | ||
declare function newTracker(trackerConfiguration: TrackerConfiguration, emitterConfiguration: NodeEmitterConfiguration | NodeEmitterConfiguration[]): Tracker; | ||
export { newTracker, Tracker, TrackerConfiguration, NodeEmitterConfiguration, CustomEmitter }; | ||
export { version, buildAdClick, buildAdConversion, buildAdImpression, buildAddToCart, buildConsentGranted, buildConsentWithdrawn, buildEcommerceTransaction, buildEcommerceTransactionItem, buildFormFocusOrChange, buildFormSubmission, buildLinkClick, buildPagePing, buildPageView, buildRemoveFromCart, buildScreenView, buildSelfDescribingEvent, buildSiteSearch, buildSocialInteraction, buildStructEvent, AdClickEvent, ContextEvent, PagePingEvent, PageViewEvent, AddToCartEvent, LinkClickEvent, ScreenViewEvent, SiteSearchEvent, StructuredEvent, AdConversionEvent, AdImpressionEvent, ConsentGrantedEvent, FormSubmissionEvent, RemoveFromCartEvent, SelfDescribingEvent, ConsentWithdrawnEvent, FormFocusOrChangeEvent, SocialInteractionEvent, EcommerceTransactionEvent, EcommerceTransactionItemEvent, SelfDescribingJson, Timestamp, PayloadBuilder, Payload, CorePlugin, CoreConfiguration, ContextGenerator, ContextFilter, EventPayloadAndContext, EventStore, EventStoreConfiguration, EventStoreIterator, EventStorePayload, TrackerCore, Logger, FormElement, EmitterConfiguration, EmitterConfigurationBase, EventJson, JsonProcessor, TrueTimestamp, DeviceTimestamp, EventMethod, RequestFailure, EventBatch, EventJsonWithKeys, LOG_LEVEL, ConditionalContextProvider, ContextPrimitive, CorePluginConfiguration, Emitter, FilterProvider, RuleSetProvider, RuleSet } from '@snowplow/tracker-core'; |
/*! | ||
* Node tracker for Snowplow v3.24.2 (https://docs.snowplowanalytics.com/docs/collecting-data/collecting-from-own-applications/node-js-tracker/) | ||
* Node tracker for Snowplow v3.24.3-dev.0 (https://docs.snowplowanalytics.com/docs/collecting-data/collecting-from-own-applications/node-js-tracker/) | ||
* Copyright 2022 Snowplow Analytics Ltd | ||
@@ -11,159 +11,4 @@ * Licensed under BSD-3-Clause | ||
var util = require('util'); | ||
var got = require('got'); | ||
var trackerCore = require('@snowplow/tracker-core'); | ||
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } | ||
var util__default = /*#__PURE__*/_interopDefaultLegacy(util); | ||
var got__default = /*#__PURE__*/_interopDefaultLegacy(got); | ||
exports.HttpProtocol = void 0; | ||
(function (HttpProtocol) { | ||
HttpProtocol["HTTP"] = "http"; | ||
HttpProtocol["HTTPS"] = "https"; | ||
})(exports.HttpProtocol || (exports.HttpProtocol = {})); | ||
exports.HttpMethod = void 0; | ||
(function (HttpMethod) { | ||
HttpMethod["GET"] = "get"; | ||
HttpMethod["POST"] = "post"; | ||
})(exports.HttpMethod || (exports.HttpMethod = {})); | ||
/** | ||
* Convert all fields in a payload dictionary to strings | ||
* | ||
* @param payload - Payload on which the new dictionary is based | ||
*/ | ||
const preparePayload = (payload) => { | ||
const stringifiedPayload = {}; | ||
const finalPayload = addDeviceSentTimestamp(payload); | ||
for (const key in finalPayload) { | ||
if (Object.prototype.hasOwnProperty.call(finalPayload, key)) { | ||
stringifiedPayload[key] = String(finalPayload[key]); | ||
} | ||
} | ||
return stringifiedPayload; | ||
}; | ||
/** | ||
* Adds the 'stm' paramater with the current time to the payload | ||
* @param payload - The payload which will be mutated | ||
*/ | ||
const addDeviceSentTimestamp = (payload) => { | ||
payload['stm'] = new Date().getTime().toString(); | ||
return payload; | ||
}; | ||
/** | ||
* Create an emitter object, which uses the `got` library, that will send events to a collector | ||
* | ||
* @param endpoint - The collector to which events will be sent | ||
* @param protocol - http or https | ||
* @param port - The port for requests to use | ||
* @param method - get or post | ||
* @param bufferSize - Number of events which can be queued before flush is called | ||
* @param retry - Configure the retry policy for `got` - https://github.com/sindresorhus/got/blob/v11.5.2/readme.md#retry | ||
* @param cookieJar - Add a cookieJar to `got` - https://github.com/sindresorhus/got/blob/v11.5.2/readme.md#cookiejar | ||
* @param callback - Callback called after a `got` request following retries - called with ErrorRequest (https://github.com/sindresorhus/got/blob/v11.5.2/readme.md#errors) and Response (https://github.com/sindresorhus/got/blob/v11.5.2/readme.md#response) | ||
* @param agents - Set new http.Agent and https.Agent objects on `got` requests - https://github.com/sindresorhus/got/blob/v11.5.2/readme.md#agent | ||
* @param serverAnonymization - If the request should undergo server anonymization. | ||
*/ | ||
function gotEmitter(endpoint, protocol = exports.HttpProtocol.HTTPS, port, method, bufferSize, retry, cookieJar, callback, agents, serverAnonymization = false) { | ||
const maxBufferLength = bufferSize !== null && bufferSize !== void 0 ? bufferSize : (method === exports.HttpMethod.GET ? 0 : 10); | ||
const path = method === exports.HttpMethod.GET ? '/i' : '/com.snowplowanalytics.snowplow/tp2'; | ||
const targetUrl = protocol + '://' + endpoint + (port ? ':' + port : '') + path; | ||
const debuglog = util__default["default"].debuglog('snowplow'); | ||
let buffer = []; | ||
/** | ||
* Handles the callback on a successful response if the callback is present | ||
* @param response - The got response object | ||
*/ | ||
const handleSuccess = (response) => { | ||
if (callback) { | ||
try { | ||
callback(undefined, response); | ||
} | ||
catch (e) { | ||
debuglog('Error in callback after failure', e); | ||
} | ||
} | ||
}; | ||
/** | ||
* Handles the callback on a failed request if the callback is present | ||
* @param error - The got error object | ||
*/ | ||
const handleFailure = (error) => { | ||
if (callback) { | ||
try { | ||
callback(error); | ||
} | ||
catch (e) { | ||
debuglog('Error in callback after failure', e); | ||
} | ||
} | ||
}; | ||
/** | ||
* Flushes all events currently stored in buffer | ||
*/ | ||
const flush = () => { | ||
const bufferCopy = buffer; | ||
buffer = []; | ||
if (bufferCopy.length === 0) { | ||
return; | ||
} | ||
const headers = { | ||
'user-agent': `snowplow-nodejs-tracker/${trackerCore.version}`, | ||
...(serverAnonymization && { 'SP-Anonymous': '*' }), | ||
...(method === exports.HttpMethod.POST && { 'content-type': 'application/json; charset=utf-8' }), | ||
}; | ||
if (method === exports.HttpMethod.POST) { | ||
const postJson = { | ||
schema: 'iglu:com.snowplowanalytics.snowplow/payload_data/jsonschema/1-0-4', | ||
data: bufferCopy.map(preparePayload), | ||
}; | ||
got__default["default"] | ||
.post(targetUrl, { | ||
json: postJson, | ||
agent: agents, | ||
headers, | ||
retry, | ||
cookieJar, | ||
}) | ||
.then(handleSuccess, handleFailure); | ||
} | ||
else { | ||
for (let i = 0; i < bufferCopy.length; i++) { | ||
got__default["default"] | ||
.get(targetUrl, { | ||
searchParams: preparePayload(bufferCopy[i]), | ||
agent: agents, | ||
headers, | ||
retry, | ||
cookieJar, | ||
}) | ||
.then(handleSuccess, handleFailure); | ||
} | ||
} | ||
}; | ||
/** | ||
* Adds a payload to the internal buffer and sends if buffer >= bufferSize | ||
* @param payload - Payload to add to buffer | ||
*/ | ||
const input = (payload) => { | ||
buffer.push(payload); | ||
if (buffer.length >= maxBufferLength) { | ||
flush(); | ||
} | ||
}; | ||
const setAnonymization = (shouldAnonymize) => { | ||
serverAnonymization = shouldAnonymize; | ||
}; | ||
return { | ||
/** | ||
* Send all events queued in the buffer to the collector | ||
*/ | ||
flush, | ||
input, | ||
setAnonymization, | ||
}; | ||
} | ||
/* | ||
@@ -199,10 +44,22 @@ * Copyright (c) 2022 Snowplow Analytics Ltd | ||
/** | ||
* Snowplow Node.js Tracker | ||
* | ||
* @param string - or array emitters The emitter or emitters to which events will be sent | ||
* @param string - namespace The namespace of the tracker | ||
* @param string - appId The application ID | ||
* @param boolean - encodeBase64 Whether unstructured events and custom contexts should be base 64 encoded | ||
* Updates the defaults for the emitter configuration | ||
*/ | ||
function tracker(emitters, namespace, appId, encodeBase64) { | ||
function newNodeEmitters(configuration) { | ||
if (configuration.hasOwnProperty('customEmitter')) { | ||
const customEmitters = configuration.customEmitter(); | ||
return Array.isArray(customEmitters) ? customEmitters : [customEmitters]; | ||
} | ||
else { | ||
configuration = configuration; | ||
// Set the default buffer size to 10 instead of 1 | ||
if (configuration.bufferSize === undefined) { | ||
configuration.bufferSize = 10; | ||
} | ||
return [trackerCore.newEmitter(configuration)]; | ||
} | ||
} | ||
function newTracker(trackerConfiguration, emitterConfiguration) { | ||
const { namespace, appId, encodeBase64 = true } = trackerConfiguration; | ||
const configs = Array.isArray(emitterConfiguration) ? emitterConfiguration : [emitterConfiguration]; | ||
const allEmitters = configs.flatMap(newNodeEmitters); | ||
let domainUserId; | ||
@@ -212,10 +69,2 @@ let networkUserId; | ||
let sessionIndex; | ||
let allEmitters; | ||
if (Array.isArray(emitters)) { | ||
allEmitters = emitters; | ||
} | ||
else { | ||
allEmitters = [emitters]; | ||
} | ||
encodeBase64 = encodeBase64 !== false; | ||
const addUserInformation = (payload) => { | ||
@@ -256,2 +105,5 @@ payload.add('duid', domainUserId); | ||
}; | ||
const flush = () => { | ||
return Promise.allSettled(allEmitters.map((emitter) => emitter.flush())).then(() => { }); | ||
}; | ||
return { | ||
@@ -262,2 +114,3 @@ setDomainUserId, | ||
setSessionIndex, | ||
flush, | ||
...core, | ||
@@ -267,2 +120,6 @@ }; | ||
Object.defineProperty(exports, 'LOG_LEVEL', { | ||
enumerable: true, | ||
get: function () { return trackerCore.LOG_LEVEL; } | ||
}); | ||
Object.defineProperty(exports, 'buildAdClick', { | ||
@@ -348,4 +205,3 @@ enumerable: true, | ||
}); | ||
exports.gotEmitter = gotEmitter; | ||
exports.tracker = tracker; | ||
exports.newTracker = newTracker; | ||
//# sourceMappingURL=index.cjs.js.map |
@@ -1,32 +0,31 @@ | ||
import { Payload, TrackerCore } from "@snowplow/tracker-core"; | ||
import { Response, RequestError, Agents, RequiredRetryOptions, ToughCookieJar, PromiseCookieJar } from "got"; | ||
interface Emitter { | ||
flush: () => void; | ||
input: (payload: Payload) => void; | ||
/** Set if the requests from the emitter should be anonymized. Read more about anonymization used at https://docs.snowplow.io/docs/collecting-data/collecting-from-own-applications/snowplow-tracker-protocol/going-deeper/http-headers/. */ | ||
setAnonymization?: (shouldAnonymize: boolean) => void; | ||
} | ||
declare enum HttpProtocol { | ||
HTTP = "http", | ||
HTTPS = "https" | ||
} | ||
declare enum HttpMethod { | ||
GET = "get", | ||
POST = "post" | ||
} | ||
/** | ||
* Create an emitter object, which uses the `got` library, that will send events to a collector | ||
* | ||
* @param endpoint - The collector to which events will be sent | ||
* @param protocol - http or https | ||
* @param port - The port for requests to use | ||
* @param method - get or post | ||
* @param bufferSize - Number of events which can be queued before flush is called | ||
* @param retry - Configure the retry policy for `got` - https://github.com/sindresorhus/got/blob/v11.5.2/readme.md#retry | ||
* @param cookieJar - Add a cookieJar to `got` - https://github.com/sindresorhus/got/blob/v11.5.2/readme.md#cookiejar | ||
* @param callback - Callback called after a `got` request following retries - called with ErrorRequest (https://github.com/sindresorhus/got/blob/v11.5.2/readme.md#errors) and Response (https://github.com/sindresorhus/got/blob/v11.5.2/readme.md#response) | ||
* @param agents - Set new http.Agent and https.Agent objects on `got` requests - https://github.com/sindresorhus/got/blob/v11.5.2/readme.md#agent | ||
* @param serverAnonymization - If the request should undergo server anonymization. | ||
*/ | ||
declare function gotEmitter(endpoint: string, protocol?: HttpProtocol, port?: number, method?: HttpMethod, bufferSize?: number, retry?: number | Partial<RequiredRetryOptions>, cookieJar?: PromiseCookieJar | ToughCookieJar, callback?: (error?: RequestError, response?: Response<string>) => void, agents?: Agents, serverAnonymization?: boolean): Emitter; | ||
/* | ||
* Copyright (c) 2022 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. | ||
*/ | ||
import { TrackerCore, Emitter, EmitterConfiguration } from "@snowplow/tracker-core"; | ||
interface Tracker extends TrackerCore { | ||
@@ -57,13 +56,23 @@ /** | ||
setSessionIndex: (sessionIndex: string | number) => void; | ||
/** | ||
* Calls flush on all emitters in order to send all queued events to the collector | ||
* @returns Promise<void> - Promise that resolves when all emitters have flushed | ||
*/ | ||
flush: () => Promise<void>; | ||
} | ||
/** | ||
* Snowplow Node.js Tracker | ||
* | ||
* @param string - or array emitters The emitter or emitters to which events will be sent | ||
* @param string - namespace The namespace of the tracker | ||
* @param string - appId The application ID | ||
* @param boolean - encodeBase64 Whether unstructured events and custom contexts should be base 64 encoded | ||
*/ | ||
declare function tracker(emitters: Emitter | Array<Emitter>, namespace: string, appId: string, encodeBase64: boolean): Tracker; | ||
export { Emitter, HttpMethod, HttpProtocol, gotEmitter, tracker, Tracker }; | ||
export { version, buildAdClick, buildAdConversion, buildAdImpression, buildAddToCart, buildConsentGranted, buildConsentWithdrawn, buildEcommerceTransaction, buildEcommerceTransactionItem, buildFormFocusOrChange, buildFormSubmission, buildLinkClick, buildPagePing, buildPageView, buildRemoveFromCart, buildScreenView, buildSelfDescribingEvent, buildSiteSearch, buildSocialInteraction, buildStructEvent, AdClickEvent, ContextEvent, PagePingEvent, PageViewEvent, AddToCartEvent, LinkClickEvent, ScreenViewEvent, SiteSearchEvent, StructuredEvent, AdConversionEvent, AdImpressionEvent, ConsentGrantedEvent, FormSubmissionEvent, RemoveFromCartEvent, SelfDescribingEvent, ConsentWithdrawnEvent, FormFocusOrChangeEvent, SocialInteractionEvent, EcommerceTransactionEvent, EcommerceTransactionItemEvent, SelfDescribingJson, Timestamp, PayloadBuilder, Payload, CorePlugin, CoreConfiguration, ContextGenerator, ContextFilter, EventPayloadAndContext } from '@snowplow/tracker-core'; | ||
interface TrackerConfiguration { | ||
/* The namespace of the tracker */ | ||
namespace: string; | ||
/* The application ID */ | ||
appId: string; | ||
/* Whether unstructured events and custom contexts should be base64 encoded. */ | ||
encodeBase64: boolean; | ||
} | ||
type CustomEmitter = { | ||
/* Function returning custom Emitter or Emitter[] to be used. If set, other options are irrelevant */ | ||
customEmitter: () => Emitter | Array<Emitter>; | ||
}; | ||
type NodeEmitterConfiguration = CustomEmitter | EmitterConfiguration; | ||
declare function newTracker(trackerConfiguration: TrackerConfiguration, emitterConfiguration: NodeEmitterConfiguration | NodeEmitterConfiguration[]): Tracker; | ||
export { newTracker, Tracker, TrackerConfiguration, NodeEmitterConfiguration, CustomEmitter }; | ||
export { version, buildAdClick, buildAdConversion, buildAdImpression, buildAddToCart, buildConsentGranted, buildConsentWithdrawn, buildEcommerceTransaction, buildEcommerceTransactionItem, buildFormFocusOrChange, buildFormSubmission, buildLinkClick, buildPagePing, buildPageView, buildRemoveFromCart, buildScreenView, buildSelfDescribingEvent, buildSiteSearch, buildSocialInteraction, buildStructEvent, AdClickEvent, ContextEvent, PagePingEvent, PageViewEvent, AddToCartEvent, LinkClickEvent, ScreenViewEvent, SiteSearchEvent, StructuredEvent, AdConversionEvent, AdImpressionEvent, ConsentGrantedEvent, FormSubmissionEvent, RemoveFromCartEvent, SelfDescribingEvent, ConsentWithdrawnEvent, FormFocusOrChangeEvent, SocialInteractionEvent, EcommerceTransactionEvent, EcommerceTransactionItemEvent, SelfDescribingJson, Timestamp, PayloadBuilder, Payload, CorePlugin, CoreConfiguration, ContextGenerator, ContextFilter, EventPayloadAndContext, EventStore, EventStoreConfiguration, EventStoreIterator, EventStorePayload, TrackerCore, Logger, FormElement, EmitterConfiguration, EmitterConfigurationBase, EventJson, JsonProcessor, TrueTimestamp, DeviceTimestamp, EventMethod, RequestFailure, EventBatch, EventJsonWithKeys, LOG_LEVEL, ConditionalContextProvider, ContextPrimitive, CorePluginConfiguration, Emitter, FilterProvider, RuleSetProvider, RuleSet } from '@snowplow/tracker-core'; |
/*! | ||
* Node tracker for Snowplow v3.24.2 (https://docs.snowplowanalytics.com/docs/collecting-data/collecting-from-own-applications/node-js-tracker/) | ||
* Node tracker for Snowplow v3.24.3-dev.0 (https://docs.snowplowanalytics.com/docs/collecting-data/collecting-from-own-applications/node-js-tracker/) | ||
* Copyright 2022 Snowplow Analytics Ltd | ||
@@ -7,155 +7,5 @@ * Licensed under BSD-3-Clause | ||
import util from 'util'; | ||
import got from 'got'; | ||
import { version, trackerCore } from '@snowplow/tracker-core'; | ||
export { buildAdClick, buildAdConversion, buildAdImpression, buildAddToCart, buildConsentGranted, buildConsentWithdrawn, buildEcommerceTransaction, buildEcommerceTransactionItem, buildFormFocusOrChange, buildFormSubmission, buildLinkClick, buildPagePing, buildPageView, buildRemoveFromCart, buildScreenView, buildSelfDescribingEvent, buildSiteSearch, buildSocialInteraction, buildStructEvent, version } from '@snowplow/tracker-core'; | ||
import { trackerCore, version, newEmitter } from '@snowplow/tracker-core'; | ||
export { LOG_LEVEL, buildAdClick, buildAdConversion, buildAdImpression, buildAddToCart, buildConsentGranted, buildConsentWithdrawn, buildEcommerceTransaction, buildEcommerceTransactionItem, buildFormFocusOrChange, buildFormSubmission, buildLinkClick, buildPagePing, buildPageView, buildRemoveFromCart, buildScreenView, buildSelfDescribingEvent, buildSiteSearch, buildSocialInteraction, buildStructEvent, version } from '@snowplow/tracker-core'; | ||
var HttpProtocol; | ||
(function (HttpProtocol) { | ||
HttpProtocol["HTTP"] = "http"; | ||
HttpProtocol["HTTPS"] = "https"; | ||
})(HttpProtocol || (HttpProtocol = {})); | ||
var HttpMethod; | ||
(function (HttpMethod) { | ||
HttpMethod["GET"] = "get"; | ||
HttpMethod["POST"] = "post"; | ||
})(HttpMethod || (HttpMethod = {})); | ||
/** | ||
* Convert all fields in a payload dictionary to strings | ||
* | ||
* @param payload - Payload on which the new dictionary is based | ||
*/ | ||
const preparePayload = (payload) => { | ||
const stringifiedPayload = {}; | ||
const finalPayload = addDeviceSentTimestamp(payload); | ||
for (const key in finalPayload) { | ||
if (Object.prototype.hasOwnProperty.call(finalPayload, key)) { | ||
stringifiedPayload[key] = String(finalPayload[key]); | ||
} | ||
} | ||
return stringifiedPayload; | ||
}; | ||
/** | ||
* Adds the 'stm' paramater with the current time to the payload | ||
* @param payload - The payload which will be mutated | ||
*/ | ||
const addDeviceSentTimestamp = (payload) => { | ||
payload['stm'] = new Date().getTime().toString(); | ||
return payload; | ||
}; | ||
/** | ||
* Create an emitter object, which uses the `got` library, that will send events to a collector | ||
* | ||
* @param endpoint - The collector to which events will be sent | ||
* @param protocol - http or https | ||
* @param port - The port for requests to use | ||
* @param method - get or post | ||
* @param bufferSize - Number of events which can be queued before flush is called | ||
* @param retry - Configure the retry policy for `got` - https://github.com/sindresorhus/got/blob/v11.5.2/readme.md#retry | ||
* @param cookieJar - Add a cookieJar to `got` - https://github.com/sindresorhus/got/blob/v11.5.2/readme.md#cookiejar | ||
* @param callback - Callback called after a `got` request following retries - called with ErrorRequest (https://github.com/sindresorhus/got/blob/v11.5.2/readme.md#errors) and Response (https://github.com/sindresorhus/got/blob/v11.5.2/readme.md#response) | ||
* @param agents - Set new http.Agent and https.Agent objects on `got` requests - https://github.com/sindresorhus/got/blob/v11.5.2/readme.md#agent | ||
* @param serverAnonymization - If the request should undergo server anonymization. | ||
*/ | ||
function gotEmitter(endpoint, protocol = HttpProtocol.HTTPS, port, method, bufferSize, retry, cookieJar, callback, agents, serverAnonymization = false) { | ||
const maxBufferLength = bufferSize !== null && bufferSize !== void 0 ? bufferSize : (method === HttpMethod.GET ? 0 : 10); | ||
const path = method === HttpMethod.GET ? '/i' : '/com.snowplowanalytics.snowplow/tp2'; | ||
const targetUrl = protocol + '://' + endpoint + (port ? ':' + port : '') + path; | ||
const debuglog = util.debuglog('snowplow'); | ||
let buffer = []; | ||
/** | ||
* Handles the callback on a successful response if the callback is present | ||
* @param response - The got response object | ||
*/ | ||
const handleSuccess = (response) => { | ||
if (callback) { | ||
try { | ||
callback(undefined, response); | ||
} | ||
catch (e) { | ||
debuglog('Error in callback after failure', e); | ||
} | ||
} | ||
}; | ||
/** | ||
* Handles the callback on a failed request if the callback is present | ||
* @param error - The got error object | ||
*/ | ||
const handleFailure = (error) => { | ||
if (callback) { | ||
try { | ||
callback(error); | ||
} | ||
catch (e) { | ||
debuglog('Error in callback after failure', e); | ||
} | ||
} | ||
}; | ||
/** | ||
* Flushes all events currently stored in buffer | ||
*/ | ||
const flush = () => { | ||
const bufferCopy = buffer; | ||
buffer = []; | ||
if (bufferCopy.length === 0) { | ||
return; | ||
} | ||
const headers = { | ||
'user-agent': `snowplow-nodejs-tracker/${version}`, | ||
...(serverAnonymization && { 'SP-Anonymous': '*' }), | ||
...(method === HttpMethod.POST && { 'content-type': 'application/json; charset=utf-8' }), | ||
}; | ||
if (method === HttpMethod.POST) { | ||
const postJson = { | ||
schema: 'iglu:com.snowplowanalytics.snowplow/payload_data/jsonschema/1-0-4', | ||
data: bufferCopy.map(preparePayload), | ||
}; | ||
got | ||
.post(targetUrl, { | ||
json: postJson, | ||
agent: agents, | ||
headers, | ||
retry, | ||
cookieJar, | ||
}) | ||
.then(handleSuccess, handleFailure); | ||
} | ||
else { | ||
for (let i = 0; i < bufferCopy.length; i++) { | ||
got | ||
.get(targetUrl, { | ||
searchParams: preparePayload(bufferCopy[i]), | ||
agent: agents, | ||
headers, | ||
retry, | ||
cookieJar, | ||
}) | ||
.then(handleSuccess, handleFailure); | ||
} | ||
} | ||
}; | ||
/** | ||
* Adds a payload to the internal buffer and sends if buffer >= bufferSize | ||
* @param payload - Payload to add to buffer | ||
*/ | ||
const input = (payload) => { | ||
buffer.push(payload); | ||
if (buffer.length >= maxBufferLength) { | ||
flush(); | ||
} | ||
}; | ||
const setAnonymization = (shouldAnonymize) => { | ||
serverAnonymization = shouldAnonymize; | ||
}; | ||
return { | ||
/** | ||
* Send all events queued in the buffer to the collector | ||
*/ | ||
flush, | ||
input, | ||
setAnonymization, | ||
}; | ||
} | ||
/* | ||
@@ -191,10 +41,22 @@ * Copyright (c) 2022 Snowplow Analytics Ltd | ||
/** | ||
* Snowplow Node.js Tracker | ||
* | ||
* @param string - or array emitters The emitter or emitters to which events will be sent | ||
* @param string - namespace The namespace of the tracker | ||
* @param string - appId The application ID | ||
* @param boolean - encodeBase64 Whether unstructured events and custom contexts should be base 64 encoded | ||
* Updates the defaults for the emitter configuration | ||
*/ | ||
function tracker(emitters, namespace, appId, encodeBase64) { | ||
function newNodeEmitters(configuration) { | ||
if (configuration.hasOwnProperty('customEmitter')) { | ||
const customEmitters = configuration.customEmitter(); | ||
return Array.isArray(customEmitters) ? customEmitters : [customEmitters]; | ||
} | ||
else { | ||
configuration = configuration; | ||
// Set the default buffer size to 10 instead of 1 | ||
if (configuration.bufferSize === undefined) { | ||
configuration.bufferSize = 10; | ||
} | ||
return [newEmitter(configuration)]; | ||
} | ||
} | ||
function newTracker(trackerConfiguration, emitterConfiguration) { | ||
const { namespace, appId, encodeBase64 = true } = trackerConfiguration; | ||
const configs = Array.isArray(emitterConfiguration) ? emitterConfiguration : [emitterConfiguration]; | ||
const allEmitters = configs.flatMap(newNodeEmitters); | ||
let domainUserId; | ||
@@ -204,10 +66,2 @@ let networkUserId; | ||
let sessionIndex; | ||
let allEmitters; | ||
if (Array.isArray(emitters)) { | ||
allEmitters = emitters; | ||
} | ||
else { | ||
allEmitters = [emitters]; | ||
} | ||
encodeBase64 = encodeBase64 !== false; | ||
const addUserInformation = (payload) => { | ||
@@ -248,2 +102,5 @@ payload.add('duid', domainUserId); | ||
}; | ||
const flush = () => { | ||
return Promise.allSettled(allEmitters.map((emitter) => emitter.flush())).then(() => { }); | ||
}; | ||
return { | ||
@@ -254,2 +111,3 @@ setDomainUserId, | ||
setSessionIndex, | ||
flush, | ||
...core, | ||
@@ -259,3 +117,3 @@ }; | ||
export { HttpMethod, HttpProtocol, gotEmitter, tracker }; | ||
export { newTracker }; | ||
//# sourceMappingURL=index.module.js.map |
{ | ||
"name": "@snowplow/node-tracker", | ||
"version": "3.24.2", | ||
"version": "3.24.3-dev.0", | ||
"description": "Node tracker for Snowplow", | ||
@@ -40,5 +40,4 @@ "keywords": [ | ||
"dependencies": { | ||
"@snowplow/tracker-core": "3.24.2", | ||
"got": "^11.8.5", | ||
"tslib": "^2.3.1" | ||
"tslib": "^2.3.1", | ||
"@snowplow/tracker-core": "3.24.3-dev.0" | ||
}, | ||
@@ -48,13 +47,10 @@ "devDependencies": { | ||
"@types/node": "~14.6.0", | ||
"@types/sinon": "~10.0.11", | ||
"@typescript-eslint/eslint-plugin": "~5.15.0", | ||
"@typescript-eslint/parser": "~5.15.0", | ||
"ava": "~4.1.0", | ||
"ava": "~5.1.1", | ||
"eslint": "~8.11.0", | ||
"eslint-plugin-ava": "~13.2.0", | ||
"nock": "~13.2.4", | ||
"rollup": "~2.70.1", | ||
"rollup-plugin-license": "~2.6.1", | ||
"rollup-plugin-ts": "~2.0.5", | ||
"sinon": "~13.0.1", | ||
"ts-node": "~10.9.1", | ||
@@ -66,4 +62,3 @@ "typescript": "~4.6.2" | ||
"test": "ava" | ||
}, | ||
"readme": "# Snowplow Node Tracker\n\n[![npm version][npm-image]][npm-url]\n[![License][license-image]](LICENSE)\n\nAdd Snowplow Tracking to your Node.js Application with `@snowplow/node-tracker`. \n\n## Maintainer quick start\n\nPart of the Snowplow JavaScript Tracker monorepo. \nBuild with [Node.js](https://nodejs.org/en/) (14 or 16) and [Rush](https://rushjs.io/).\n\n### Setup repository\n\n```bash\nnpm install -g @microsoft/rush \ngit clone https://github.com/snowplow/snowplow-javascript-tracker.git\nrush update\n```\n\n## Package Installation\n\nWith npm:\n\n```bash\nnpm install @snowplow/node-tracker\n```\n\n## Usage\n\nInitialize your tracker with your desired configuration:\n\n```js\nimport { tracker, gotEmitter } from '@snowplow/node-tracker';\n\nconst e = gotEmitter(\n 'collector.mydomain.net', // Collector endpoint\n snowplow.HttpProtocol.HTTPS, // Optionally specify a method - https is the default\n 8080, // Optionally specify a port\n snowplow.HttpMethod.POST, // Method - defaults to GET\n 5 // Only send events once n are buffered. Defaults to 1 for GET requests and 10 for POST requests.\n);\n\nconst t = tracker(e, 'myTracker', 'myApp', false);\n```\n\nThen use the `track` function from this package, along with the `buildX` functions to send events to your configured emitters:\n\n```js\nimport {\n buildSelfDescribingEvent,\n buildPageView\n} from '@snowplow/node-tracker';\n\nconst context = [\n {\n schema: 'iglu:com.acme/user/jsonschema/1-0-0',\n data: {\n type: 'tester',\n },\n },\n];\n\nt.track(\n buildPageView({ pageUrl: 'http://www.example.com', pageTitle: 'example page', referrer: 'http://google.com' }),\n context\n);\n\nconst eventJson = {\n schema: 'iglu:com.acme/viewed_product/jsonschema/1-0-0',\n data: {\n price: 20,\n },\n};\n\ntrack.track(buildSelfDescribingEvent({ event: eventJson }), context);\n```\n\nTo enable success and failure callback debugging, run your application with `NODE_DEBUG=snowplow`.\n\n## Copyright and license\n\nLicensed and distributed under the [BSD 3-Clause License](LICENSE) ([An OSI Approved License][osi]).\n\nCopyright (c) 2022 Snowplow Analytics Ltd.\n\nAll rights reserved.\n\n[osi]: https://opensource.org/licenses/BSD-3-Clause\n[license-image]: https://img.shields.io/npm/l/@snowplow/node-tracker\n[npm-url]: https://www.npmjs.com/package/@snowplow/node-tracker\n[npm-image]: https://img.shields.io/npm/v/@snowplow/node-tracker\n" | ||
} | ||
} |
@@ -34,13 +34,7 @@ # Snowplow Node Tracker | ||
```js | ||
import { tracker, gotEmitter } from '@snowplow/node-tracker'; | ||
const e = gotEmitter( | ||
'collector.mydomain.net', // Collector endpoint | ||
snowplow.HttpProtocol.HTTPS, // Optionally specify a method - https is the default | ||
8080, // Optionally specify a port | ||
snowplow.HttpMethod.POST, // Method - defaults to GET | ||
5 // Only send events once n are buffered. Defaults to 1 for GET requests and 10 for POST requests. | ||
import { newTracker } from '@snowplow/node-tracker'; | ||
const t = newTracker( | ||
{ namespace: 'myTracker', appId: 'myApp', encodeBase64: false }, | ||
{ endpoint: 'collector.mydomain.net', port: 8080, bufferSize: 5 } | ||
); | ||
const t = tracker(e, 'myTracker', 'myApp', false); | ||
``` | ||
@@ -77,3 +71,3 @@ | ||
track.track(buildSelfDescribingEvent({ event: eventJson }), context); | ||
t.track(buildSelfDescribingEvent({ event: eventJson }), context); | ||
``` | ||
@@ -80,0 +74,0 @@ |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
Found 1 instance in 1 package
2
12
59308
9
470
2
87
1
+ Added@snowplow/tracker-core@3.24.3-dev.0(transitive)
+ Addeduuid@8.3.2(transitive)
- Removedgot@^11.8.5
- Removed@sindresorhus/is@4.6.0(transitive)
- Removed@snowplow/tracker-core@3.24.2(transitive)
- Removed@szmarczak/http-timer@4.0.6(transitive)
- Removed@types/cacheable-request@6.0.3(transitive)
- Removed@types/http-cache-semantics@4.0.4(transitive)
- Removed@types/keyv@3.1.4(transitive)
- Removed@types/node@22.13.5(transitive)
- Removed@types/responselike@1.0.3(transitive)
- Removedcacheable-lookup@5.0.4(transitive)
- Removedcacheable-request@7.0.4(transitive)
- Removedclone-response@1.0.3(transitive)
- Removeddecompress-response@6.0.0(transitive)
- Removeddefer-to-connect@2.0.1(transitive)
- Removedend-of-stream@1.4.4(transitive)
- Removedget-stream@5.2.0(transitive)
- Removedgot@11.8.6(transitive)
- Removedhttp-cache-semantics@4.1.1(transitive)
- Removedhttp2-wrapper@1.0.3(transitive)
- Removedjson-buffer@3.0.1(transitive)
- Removedkeyv@4.5.4(transitive)
- Removedlowercase-keys@2.0.0(transitive)
- Removedmimic-response@1.0.13.1.0(transitive)
- Removednormalize-url@6.1.0(transitive)
- Removedonce@1.4.0(transitive)
- Removedp-cancelable@2.1.1(transitive)
- Removedpump@3.0.2(transitive)
- Removedquick-lru@5.1.1(transitive)
- Removedresolve-alpn@1.2.1(transitive)
- Removedresponselike@2.0.1(transitive)
- Removedundici-types@6.20.0(transitive)
- Removeduuid@3.4.0(transitive)
- Removedwrappy@1.0.2(transitive)