@imtbl/metrics
Advanced tools
Comparing version 2.0.0-alpha.6 to 2.0.0-alpha.7
@@ -1,9 +0,447 @@ | ||
import st from 'axios'; | ||
import axios from 'axios'; | ||
import { memorise } from 'lru-memorise'; | ||
import { getGlobalisedValue } from 'global-const'; | ||
import { getGlobalisedValue as getGlobalisedValue$1 } from 'global-const'; | ||
var q=Object.defineProperty;var tt=(t,e)=>{for(var r in e)q(t,r,{get:e[r],enumerable:!0});};var D={};tt(D,{deleteItem:()=>nt,getItem:()=>y,setItem:()=>T});var g=()=>typeof window>"u",I=()=>!g();var et="__IMX-",S=()=>I()&&window.localStorage,rt=t=>{if(t!==null)try{return JSON.parse(t)}catch{return t}},ot=t=>typeof t=="string"?t:JSON.stringify(t),v=t=>`${et}${t}`;function y(t){if(S())return rt(window.localStorage.getItem(v(t)))}var T=(t,e)=>S()?(window.localStorage.setItem(v(t),ot(e)),!0):!1,nt=t=>S()?(window.localStorage.removeItem(v(t)),!0):!1;var h=0,M=t=>{let e=parseInt(t,10)*1e3,r=new Date(e),o=new Date;return h=r.getTime()-o.getTime(),h},O=()=>{let t=new Date().getTime()+h;return new Date(t).toISOString()};var w=(s=>(s.RUNTIME_ID="rid",s.PASSPORT_CLIENT_ID="passportClientId",s.ENVIRONMENT="env",s.PUBLISHABLE_API_KEY="pak",s.IDENTITY="uid",s.DOMAIN="domain",s.SDK_VERSION="sdkVersion",s))(w||{});var it="https://api.immutable.com";async function k(t,e){let r=st.create({baseURL:it}),o=JSON.stringify(e),c={payload:Buffer.from(o).toString("base64")};return (await r.post(t,c)).data}var m,d,at=()=>{m=y("metrics-events")||[],d=y("metrics-runtime")||{};};at();var a=(t,e)=>{d={...d,[t]:e},T("metrics-runtime",d);},E=t=>{if(d[t]!==void 0)return d[t]},$=()=>d,C=()=>m,L=t=>{m.push(t),T("metrics-events",m);},V=t=>{m=m.slice(t),T("metrics-events",m);},P=t=>{let e=[];return Object.entries(t).forEach(([r,o])=>{(typeof r=="string"||typeof o=="string"||typeof o=="number"||typeof o=="boolean")&&e.push([r,o.toString()]);}),e};var b="2.0.0-alpha.6",ct=()=>g()?"":window.location.ancestorOrigins&&window.location.ancestorOrigins.length>0?new URL(window.location.ancestorOrigins[0]).hostname:document.referrer?new URL(window.document.referrer).hostname:"",pt=()=>{if(g())return "";let t;try{window.self!==window.top&&(t=ct());}catch{}return t||(t=window.location.hostname),t},lt=()=>{if(a("sdkVersion",b),g())return {browser:"nodejs",sdkVersion:b};let t=pt();return t&&a("domain",t),{sdkVersion:b,browser:window.navigator.userAgent,domain:t,tz:Intl.DateTimeFormat().resolvedOptions().timeZone,screen:`${window.screen.width}x${window.screen.height}`}},N=!1,B=()=>N,U=async()=>{N=!0;try{let t=P(lt()),e=E("rid"),r=E("uid"),c=await k("/v1/sdk/initialise",{version:1,data:{runtimeDetails:t,runtimeId:e,uId:r}}),{runtimeId:i,sTime:p}=c;a("rid",i),M(p);}catch{N=!1;}};function n(t,e){return (...r)=>{try{let o=t(...r);return o instanceof Promise?o.catch(()=>e):o}catch{return e}}}function mt(){return I()||typeof process>"u"?!1:process.env.JEST_WORKER_ID!==void 0}var K=n(mt,!1);var Y="imtbl__metrics",ft=5e3,ut=1e3,f=(t,e)=>getGlobalisedValue(Y,t,e),J=(t,e)=>{let r=memorise(e,{lruOptions:{ttl:ft,max:ut}});return getGlobalisedValue(Y,t,r)};var gt=5e3,Tt=(t,e,r)=>{let o={event:`${t}.${e}`,time:O(),...r&&{properties:P(r)}};L(o);},u=n(J("track",Tt)),wt=async()=>{if(B()===!1){await U();return}let t=C();if(t.length===0)return;let e=t.length,r=$();await k("/v1/sdk/metrics",{version:1,data:{events:t,details:r}})instanceof Error||V(e);},Et=n(wt),H=async()=>{await Et(),setTimeout(H,gt);},z=!1,It=()=>{z||(z=!0,H());};K()||n(f("startFlushing",It))();var R=(t,e,r,o)=>u(t,e,{...o||{},duration:Math.round(r)});var j=()=>{let t=()=>Math.floor((1+Math.random())*65536).toString(16).substring(1);return `${t()}${t()}-${t()}-${t()}-${t()}-${t()}${t()}${t()}`};var yt=(...t)=>{if(!t.some(o=>!!o))return {};let r={};return t.forEach(o=>{o&&(r={...r,...o});}),r},kt=t=>t.replace(/[^a-zA-Z0-9\s\-_]/g,""),Pt=(t,e)=>`${t}_${kt(e)}`,xt=(t,e,r)=>{let o=j(),c=Date.now(),i=0,p=0,s={},x=(...l)=>yt(s,...l,{flowId:o,flowName:e});s=x(r);let X=l=>{l&&(s=x(l));},A=(l,Z)=>{let Q=Pt(e,l),F=0,_=performance.now();i>0&&(F=_-p);let W=x(Z,{flowEventName:l,flowStep:i});R(t,Q,F,W),i++,p=_;};return A("Start"),{details:{moduleName:t,flowName:e,flowId:o,flowStartTime:c},addEvent:n(A),addFlowProperties:n(X)}},St=n(xt);var vt=(t,e,r,o)=>{let{message:c}=r,i=r.stack||"",{cause:p}=r;p instanceof Error&&(i=`${i} | ||
Cause: ${p.message} | ||
${p.stack}`),u(t,`trackError_${e}`,{...o||{},errorMessage:c,errorStack:i,isTrackError:!0});},Dt=n(vt);var ht=t=>{if(t.passportId)return `passport:${t.passportId.toLowerCase()}`;if(t.ethAddress)return `ethAddress:${t.ethAddress.toLowerCase()}`;throw new Error("invalid_identity")},bt=t=>{let e=ht(t);e&&(a("uid",e),u("metrics","identify",t.traits));},Nt=n(bt);var Rt=t=>{a("env",t);},At=n(f("setEnvironment",Rt)),Ft=t=>{a("passportClientId",t);},_t=n(f("setPassportClientId",Ft)),Mt=t=>{a("pak",t);},Ot=n(f("setPublishableApiKey",Mt)),$t=n(f("getDetail",E));var Oe={localStorage:D}; | ||
var __defProp = Object.defineProperty; | ||
var __export = (target, all) => { | ||
for (var name in all) | ||
__defProp(target, name, { get: all[name], enumerable: true }); | ||
}; | ||
export { w as Detail, $t as getDetail, Nt as identify, At as setEnvironment, _t as setPassportClientId, Ot as setPublishableApiKey, u as track, R as trackDuration, Dt as trackError, St as trackFlow, Oe as utils }; | ||
// src/utils/localStorage.ts | ||
var localStorage_exports = {}; | ||
__export(localStorage_exports, { | ||
deleteItem: () => deleteItem, | ||
getItem: () => getItem, | ||
setItem: () => setItem | ||
}); | ||
// src/utils/browser.ts | ||
var isNode = () => typeof window === "undefined"; | ||
var isBrowser = () => !isNode(); | ||
// src/utils/localStorage.ts | ||
var localStoragePrefix = "__IMX-"; | ||
var hasLocalstorage = () => isBrowser() && window.localStorage; | ||
var parseItem = (payload) => { | ||
if (payload === null) return void 0; | ||
try { | ||
return JSON.parse(payload); | ||
} catch (error) { | ||
return payload; | ||
} | ||
}; | ||
var serialiseItem = (payload) => { | ||
if (typeof payload === "string") { | ||
return payload; | ||
} | ||
return JSON.stringify(payload); | ||
}; | ||
var genKey = (key) => `${localStoragePrefix}${key}`; | ||
function getItem(key) { | ||
if (hasLocalstorage()) { | ||
return parseItem(window.localStorage.getItem(genKey(key))); | ||
} | ||
return void 0; | ||
} | ||
var setItem = (key, payload) => { | ||
if (hasLocalstorage()) { | ||
window.localStorage.setItem(genKey(key), serialiseItem(payload)); | ||
return true; | ||
} | ||
return false; | ||
}; | ||
var deleteItem = (key) => { | ||
if (hasLocalstorage()) { | ||
window.localStorage.removeItem(genKey(key)); | ||
return true; | ||
} | ||
return false; | ||
}; | ||
// src/utils/clock.ts | ||
var clockSkew = 0; | ||
var setClockSkew = (serverUnixTime) => { | ||
const sTime = parseInt(serverUnixTime, 10) * 1e3; | ||
const serverTime = new Date(sTime); | ||
const now = /* @__PURE__ */ new Date(); | ||
clockSkew = serverTime.getTime() - now.getTime(); | ||
return clockSkew; | ||
}; | ||
var getCorrectedTime = () => { | ||
const now = (/* @__PURE__ */ new Date()).getTime() + clockSkew; | ||
const fixedDate = new Date(now).toISOString(); | ||
return fixedDate; | ||
}; | ||
// src/utils/constants.ts | ||
var Detail = /* @__PURE__ */ ((Detail2) => { | ||
Detail2["RUNTIME_ID"] = "rid"; | ||
Detail2["PASSPORT_CLIENT_ID"] = "passportClientId"; | ||
Detail2["ENVIRONMENT"] = "env"; | ||
Detail2["PUBLISHABLE_API_KEY"] = "pak"; | ||
Detail2["IDENTITY"] = "uid"; | ||
Detail2["DOMAIN"] = "domain"; | ||
Detail2["SDK_VERSION"] = "sdkVersion"; | ||
return Detail2; | ||
})(Detail || {}); | ||
var IMTBL_API = "https://api.immutable.com"; | ||
async function post(path, data) { | ||
const client = axios.create({ | ||
baseURL: IMTBL_API | ||
}); | ||
const payload = JSON.stringify(data); | ||
const body = { | ||
payload: Buffer.from(payload).toString("base64") | ||
}; | ||
const response = await client.post(path, body); | ||
return response.data; | ||
} | ||
// src/utils/state.ts | ||
var EVENT_STORE; | ||
var RUNTIME_DETAILS; | ||
var initialise = () => { | ||
EVENT_STORE = getItem("metrics-events" /* EVENTS */) || []; | ||
RUNTIME_DETAILS = getItem("metrics-runtime" /* RUNTIME */) || {}; | ||
}; | ||
initialise(); | ||
var storeDetail = (key, value) => { | ||
RUNTIME_DETAILS = { | ||
...RUNTIME_DETAILS, | ||
[key]: value | ||
}; | ||
setItem("metrics-runtime" /* RUNTIME */, RUNTIME_DETAILS); | ||
}; | ||
var getDetail = (key) => { | ||
if (RUNTIME_DETAILS[key] === void 0) { | ||
return void 0; | ||
} | ||
return RUNTIME_DETAILS[key]; | ||
}; | ||
var getAllDetails = () => RUNTIME_DETAILS; | ||
var getEvents = () => EVENT_STORE; | ||
var addEvent = (event) => { | ||
EVENT_STORE.push(event); | ||
setItem("metrics-events" /* EVENTS */, EVENT_STORE); | ||
}; | ||
var removeSentEvents = (numberOfEvents) => { | ||
EVENT_STORE = EVENT_STORE.slice(numberOfEvents); | ||
setItem("metrics-events" /* EVENTS */, EVENT_STORE); | ||
}; | ||
var flattenProperties = (properties) => { | ||
const propertyMap = []; | ||
Object.entries(properties).forEach(([key, value]) => { | ||
if (typeof key === "string" || typeof value === "string" || typeof value === "number" || typeof value === "boolean") { | ||
propertyMap.push([key, value.toString()]); | ||
} | ||
}); | ||
return propertyMap; | ||
}; | ||
// src/initialise.ts | ||
var SDK_VERSION = "2.0.0-alpha.7"; | ||
var getFrameParentDomain = () => { | ||
if (isNode()) { | ||
return ""; | ||
} | ||
if (window.location.ancestorOrigins && window.location.ancestorOrigins.length > 0) { | ||
return new URL(window.location.ancestorOrigins[0]).hostname; | ||
} | ||
return document.referrer ? new URL(window.document.referrer).hostname : ""; | ||
}; | ||
var runtimeHost = () => { | ||
if (isNode()) { | ||
return ""; | ||
} | ||
let domain; | ||
try { | ||
if (window.self !== window.top) { | ||
domain = getFrameParentDomain(); | ||
} | ||
} catch (error) { | ||
} | ||
if (!domain) { | ||
domain = window.location.hostname; | ||
} | ||
return domain; | ||
}; | ||
var getRuntimeDetails = () => { | ||
storeDetail("sdkVersion" /* SDK_VERSION */, SDK_VERSION); | ||
if (isNode()) { | ||
return { browser: "nodejs", sdkVersion: SDK_VERSION }; | ||
} | ||
const domain = runtimeHost(); | ||
if (domain) { | ||
storeDetail("domain" /* DOMAIN */, domain); | ||
} | ||
return { | ||
sdkVersion: SDK_VERSION, | ||
browser: window.navigator.userAgent, | ||
domain, | ||
tz: Intl.DateTimeFormat().resolvedOptions().timeZone, | ||
screen: `${window.screen.width}x${window.screen.height}` | ||
}; | ||
}; | ||
var initialised = false; | ||
var isInitialised = () => initialised; | ||
var initialise2 = async () => { | ||
initialised = true; | ||
try { | ||
const runtimeDetails = flattenProperties(getRuntimeDetails()); | ||
const existingRuntimeId = getDetail("rid" /* RUNTIME_ID */); | ||
const existingIdentity = getDetail("uid" /* IDENTITY */); | ||
const body = { | ||
version: 1, | ||
data: { | ||
runtimeDetails, | ||
runtimeId: existingRuntimeId, | ||
uId: existingIdentity | ||
} | ||
}; | ||
const response = await post("/v1/sdk/initialise", body); | ||
const { runtimeId, sTime } = response; | ||
storeDetail("rid" /* RUNTIME_ID */, runtimeId); | ||
setClockSkew(sTime); | ||
} catch (error) { | ||
initialised = false; | ||
} | ||
}; | ||
// src/utils/errorBoundary.ts | ||
function errorBoundary(fn, fallbackResult) { | ||
return (...args) => { | ||
try { | ||
const result = fn(...args); | ||
if (result instanceof Promise) { | ||
return result.catch(() => fallbackResult); | ||
} | ||
return result; | ||
} catch (error) { | ||
return fallbackResult; | ||
} | ||
}; | ||
} | ||
// src/utils/checkEnv.ts | ||
function isTestEnvironmentFn() { | ||
if (isBrowser()) { | ||
return false; | ||
} | ||
if (typeof process === "undefined") { | ||
return false; | ||
} | ||
return process.env.JEST_WORKER_ID !== void 0; | ||
} | ||
var isTestEnvironment = errorBoundary(isTestEnvironmentFn, false); | ||
var GLOBALISE_KEY = "imtbl__metrics"; | ||
var MEMORISE_TIMEFRAME = 5e3; | ||
var MEMORISE_MAX = 1e3; | ||
var getGlobalisedValue = (key, value) => getGlobalisedValue$1(GLOBALISE_KEY, key, value); | ||
var getGlobalisedCachedFunction = (key, fn) => { | ||
const memorisedFn = memorise(fn, { | ||
lruOptions: { ttl: MEMORISE_TIMEFRAME, max: MEMORISE_MAX } | ||
}); | ||
return getGlobalisedValue$1(GLOBALISE_KEY, key, memorisedFn); | ||
}; | ||
// src/track.ts | ||
var POLLING_FREQUENCY = 5e3; | ||
var trackFn = (moduleName, eventName, properties) => { | ||
const event = { | ||
event: `${moduleName}.${eventName}`, | ||
time: getCorrectedTime(), | ||
...properties && { properties: flattenProperties(properties) } | ||
}; | ||
addEvent(event); | ||
}; | ||
var track = errorBoundary( | ||
getGlobalisedCachedFunction("track", trackFn) | ||
); | ||
var flushFn = async () => { | ||
if (isInitialised() === false) { | ||
await initialise2(); | ||
return; | ||
} | ||
const events = getEvents(); | ||
if (events.length === 0) { | ||
return; | ||
} | ||
const numEvents = events.length; | ||
const details = getAllDetails(); | ||
const metricsPayload = { | ||
version: 1, | ||
data: { | ||
events, | ||
details | ||
} | ||
}; | ||
const response = await post("/v1/sdk/metrics", metricsPayload); | ||
if (response instanceof Error) { | ||
return; | ||
} | ||
removeSentEvents(numEvents); | ||
}; | ||
var flush = errorBoundary(flushFn); | ||
var flushPoll = async () => { | ||
await flush(); | ||
setTimeout(flushPoll, POLLING_FREQUENCY); | ||
}; | ||
var flushingStarted = false; | ||
var startFlushing = () => { | ||
if (flushingStarted) { | ||
return; | ||
} | ||
flushingStarted = true; | ||
flushPoll(); | ||
}; | ||
if (!isTestEnvironment()) { | ||
errorBoundary(getGlobalisedValue("startFlushing", startFlushing))(); | ||
} | ||
// src/performance.ts | ||
var trackDuration = (moduleName, eventName, duration, properties) => track(moduleName, eventName, { | ||
...properties || {}, | ||
duration: Math.round(duration) | ||
}); | ||
// src/utils/id.ts | ||
var generateFlowId = () => { | ||
const s4 = () => Math.floor((1 + Math.random()) * 65536).toString(16).substring(1); | ||
return `${s4()}${s4()}-${s4()}-${s4()}-${s4()}-${s4()}${s4()}${s4()}`; | ||
}; | ||
// src/flow.ts | ||
var mergeProperties = (...args) => { | ||
const hasProperties = args.some((arg) => !!arg); | ||
if (!hasProperties) { | ||
return {}; | ||
} | ||
let finalProperties = {}; | ||
args.forEach((arg) => { | ||
if (arg) { | ||
finalProperties = { | ||
...finalProperties, | ||
...arg | ||
}; | ||
} | ||
}); | ||
return finalProperties; | ||
}; | ||
var cleanEventName = (eventName) => eventName.replace(/[^a-zA-Z0-9\s\-_]/g, ""); | ||
var getEventName = (flowName, eventName) => `${flowName}_${cleanEventName(eventName)}`; | ||
var trackFlowFn = (moduleName, flowName, properties) => { | ||
const flowId = generateFlowId(); | ||
const flowStartTime = Date.now(); | ||
let currentStepCount = 0; | ||
let previousStepTime = 0; | ||
let flowProperties = {}; | ||
const mergeFlowProps = (...args) => mergeProperties(flowProperties, ...args, { | ||
flowId, | ||
flowName | ||
}); | ||
flowProperties = mergeFlowProps(properties); | ||
const addFlowProperties = (newProperties) => { | ||
if (newProperties) { | ||
flowProperties = mergeFlowProps(newProperties); | ||
} | ||
}; | ||
const addEvent2 = (eventName, eventProperties) => { | ||
const event = getEventName(flowName, eventName); | ||
let duration = 0; | ||
const currentTime = performance.now(); | ||
if (currentStepCount > 0) { | ||
duration = currentTime - previousStepTime; | ||
} | ||
const mergedProps = mergeFlowProps(eventProperties, { | ||
flowEventName: eventName, | ||
flowStep: currentStepCount | ||
}); | ||
trackDuration(moduleName, event, duration, mergedProps); | ||
currentStepCount++; | ||
previousStepTime = currentTime; | ||
}; | ||
addEvent2("Start"); | ||
return { | ||
details: { | ||
moduleName, | ||
flowName, | ||
flowId, | ||
flowStartTime | ||
}, | ||
addEvent: errorBoundary(addEvent2), | ||
addFlowProperties: errorBoundary(addFlowProperties) | ||
}; | ||
}; | ||
var trackFlow = errorBoundary(trackFlowFn); | ||
// src/error.ts | ||
var trackErrorFn = (moduleName, eventName, error, properties) => { | ||
const { message } = error; | ||
let stack = error.stack || ""; | ||
const { cause } = error; | ||
if (cause instanceof Error) { | ||
stack = `${stack} | ||
Cause: ${cause.message} | ||
${cause.stack}`; | ||
} | ||
track(moduleName, `trackError_${eventName}`, { | ||
...properties || {}, | ||
errorMessage: message, | ||
errorStack: stack, | ||
isTrackError: true | ||
}); | ||
}; | ||
var trackError = errorBoundary(trackErrorFn); | ||
// src/identify.ts | ||
var parseIdentity = (params) => { | ||
if (params.passportId) { | ||
const key = `passport:${params.passportId.toLowerCase()}`; | ||
return key; | ||
} | ||
if (params.ethAddress) { | ||
const key = `ethAddress:${params.ethAddress.toLowerCase()}`; | ||
return key; | ||
} | ||
throw new Error("invalid_identity"); | ||
}; | ||
var identifyFn = (params) => { | ||
const identity = parseIdentity(params); | ||
if (!identity) { | ||
return; | ||
} | ||
storeDetail("uid" /* IDENTITY */, identity); | ||
track("metrics", "identify", params.traits); | ||
}; | ||
var identify = errorBoundary(identifyFn); | ||
// src/details.ts | ||
var setEnvironmentFn = (env) => { | ||
storeDetail("env" /* ENVIRONMENT */, env); | ||
}; | ||
var setEnvironment = errorBoundary( | ||
getGlobalisedValue("setEnvironment", setEnvironmentFn) | ||
); | ||
var setPassportClientIdFn = (passportClientId) => { | ||
storeDetail("passportClientId" /* PASSPORT_CLIENT_ID */, passportClientId); | ||
}; | ||
var setPassportClientId = errorBoundary( | ||
getGlobalisedValue("setPassportClientId", setPassportClientIdFn) | ||
); | ||
var setPublishableApiKeyFn = (publishableApiKey) => { | ||
storeDetail("pak" /* PUBLISHABLE_API_KEY */, publishableApiKey); | ||
}; | ||
var setPublishableApiKey = errorBoundary( | ||
getGlobalisedValue("setPublishableApiKey", setPublishableApiKeyFn) | ||
); | ||
var getDetail2 = errorBoundary( | ||
getGlobalisedValue("getDetail", getDetail) | ||
); | ||
// src/index.ts | ||
var utils = { | ||
localStorage: localStorage_exports | ||
}; | ||
export { Detail, getDetail2 as getDetail, identify, setEnvironment, setPassportClientId, setPublishableApiKey, track, trackDuration, trackError, trackFlow, utils }; |
{ | ||
"name": "@imtbl/metrics", | ||
"description": "Metrics module for Immutable SDK", | ||
"version": "2.0.0-alpha.6", | ||
"version": "2.0.0-alpha.7", | ||
"author": "Immutable", | ||
@@ -6,0 +6,0 @@ "bugs": "https://github.com/immutable/ts-immutable-sdk/issues", |
Sorry, the diff of this file is too big to display
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
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 1 instance in 1 package
121025
3471
1
4
1