📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
initial commit
Blue Mouse0cb1b0b92afd
diff --git a/.github/funding.yml b/.github/funding.ymlnew file mode 100644index 000000000..f7cbd9642--- /dev/null+++ b/.github/funding.yml@@ -0,0 +1,2 @@+github: swetrix+ko_fi: andriirdiff --git a/.gitignore b/.gitignorenew file mode 100644index 000000000..84eba26f5--- /dev/null+++ b/.gitignore@@ -0,0 +1,108 @@+# Logs+logs+*.log+npm-debug.log*+yarn-debug.log*+yarn-error.log*+lerna-debug.log*++# Diagnostic reports (https://nodejs.org/api/report.html)+report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json++# Runtime data+pids+*.pid+*.seed+*.pid.lock++# Directory for instrumented libs generated by jscoverage/JSCover+lib-cov++# Coverage directory used by tools like istanbul+coverage+*.lcov++# nyc test coverage+.nyc_output++# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)+.grunt++# Bower dependency directory (https://bower.io/)+bower_components++# node-waf configuration+.lock-wscript++# Compiled binary addons (https://nodejs.org/api/addons.html)+build/Release++# Dependency directories+node_modules/+jspm_packages/++# TypeScript v1 declaration files+typings/++# TypeScript cache+*.tsbuildinfo++# Optional npm cache directory+.npm++# Optional eslint cache+.eslintcache++# Microbundle cache+.rpt2_cache/+.rts2_cache_cjs/+.rts2_cache_es/+.rts2_cache_umd/++# Optional REPL history+.node_repl_history++# Output of 'npm pack'+*.tgz++# Yarn Integrity file+.yarn-integrity++# dotenv environment variables file+.env+.env.test++# parcel-bundler cache (https://parceljs.org/)+.cache++# Next.js build output+.next++# Nuxt.js build / generate output+.nuxt+# dist++# Gatsby files+.cache/+# Comment in the public line in if your project uses Gatsby and *not* Next.js+# https://nextjs.org/blog/next-9-1#public-directory-support+# public++# vuepress build output+.vuepress/dist++# Serverless directories+.serverless/++# FuseBox cache+.fusebox/++# DynamoDB Local files+.dynamodb/++# TernJS port file+.tern-port+package-lock.json++.DS_Store+pnpm-lock.yamldiff --git a/LICENSE b/LICENSEnew file mode 100644index 000000000..a28eb52ad--- /dev/null+++ b/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2023 Andrii Romasiun++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/README.md b/README.mdnew file mode 100644index 000000000..e982d1c70--- /dev/null+++ b/README.md@@ -0,0 +1,22 @@+<img src="https://swetrix.com/assets/logo_blue.svg" alt="" height="100" />++[](https://data.jsdelivr.com/v1/package/gh/Swetrix/swetrix-js/stats)+[](https://bundlephobia.com/api/size?package=swetrix)+[](https://github.com/swetrix/swetrix-js/issues)++# Swetrix Tracking Script++This repository contains the analytics script which is used at https://swetrix.com \+You can find the detailed documentation and use cases at our [docs page](https://swetrix.com/docs).++Feel free to contribute to the source code by opening a pull requests. \+For any questions, you can open an issue ticket, refer to our [FAQs](https://swetrix.com/#faq) page or reach us at [email protected]++The latest live versions of the script are located at [jsDelivr](https://swetrix.org/swetrix.js) and [NPM](https://www.npmjs.com/package/swetrix).++# Selfhosted API+If you are selfhosting the [Swetrix-API](https://github.com/Swetrix/swetrix-api), be sure to point the `apiUrl` parameter to: `https://yourapiinstance.com/log`++# Donate+You can support the project by donating us at https://ko-fi.com/andriir \+We can only run our services by once again asking for your financial support!diff --git a/dist/esnext/Lib.d.ts b/dist/esnext/Lib.d.tsnew file mode 100644index 000000000..a3d4c332f--- /dev/null+++ b/dist/esnext/Lib.d.ts@@ -0,0 +1,71 @@+export interface LibOptions {+ /**+ * When set to `true`, all tracking logs will be printed to console and localhost events will be sent to server.+ */+ debug?: boolean;+ /**+ * When set to `true`, the tracking library won't send any data to server.+ * Useful for development purposes when this value is set based on `.env` var.+ */+ disabled?: boolean;+ /**+ * By setting this flag to `true`, we will not collect ANY kind of data about the user with the DNT setting.+ */+ respectDNT?: boolean;+ /** Set a custom URL of the API server (for selfhosted variants of Swetrix). */+ apiURL?: string;+}+export interface TrackEventOptions {+ /** The custom event name. */+ ev: string;+ /** If set to `true`, only 1 event with the same ID will be saved per user session. */+ unique?: boolean;+}+/**+ * The object returned by `trackPageViews()`, used to stop tracking pages.+ */+export interface PageActions {+ /** Stops the tracking of pages. */+ stop: () => void;+}+export interface PageData {+ /** Current URL path. */+ path: string;+ /** The object returned by `trackPageViews()`, used to stop tracking pages. */+ actions: PageActions;+}+export interface PageViewsOptions {+ /**+ * If set to `true`, only unique events will be saved.+ * This param is useful when tracking single-page landing websites.+ */+ unique?: boolean;+ /** A list of Regular Expressions or string pathes to ignore. */+ ignore?: Array<string | RegExp>;+ /** Do not send Heartbeat requests to the server. */+ noHeartbeat?: boolean;+ /** Send Heartbeat requests when the website tab is not active in the browser. */+ heartbeatOnBackground?: boolean;+}+export declare const defaultPageActions: {+ stop(): void;+};+export declare class Lib {+ private projectID;+ private options?;+ private pageData;+ private pageViewsOptions;+ private perfStatsCollected;+ private activePage;+ constructor(projectID: string, options?: LibOptions | undefined);+ track(event: TrackEventOptions): void;+ trackPageViews(options?: PageViewsOptions): PageActions;+ getPerformanceStats(): object;+ private heartbeat;+ private checkIgnore;+ private trackPathChange;+ private trackPage;+ private debug;+ private canTrack;+ private sendRequest;+}diff --git a/dist/esnext/Lib.js b/dist/esnext/Lib.jsnew file mode 100644index 000000000..3fccb9d79--- /dev/null+++ b/dist/esnext/Lib.js@@ -0,0 +1,183 @@+import { isInBrowser, isLocalhost, isAutomated, getLocale, getTimezone, getReferrer, getUTMCampaign, getUTMMedium, getUTMSource, getPath, } from './utils';+export const defaultPageActions = {+ stop() { },+};+const DEFAULT_API_HOST = 'https://api.swetrix.com/log';+export class Lib {+ constructor(projectID, options) {+ this.projectID = projectID;+ this.options = options;+ this.pageData = null;+ this.pageViewsOptions = null;+ this.perfStatsCollected = false;+ this.activePage = null;+ this.trackPathChange = this.trackPathChange.bind(this);+ this.heartbeat = this.heartbeat.bind(this);+ }+ track(event) {+ if (!this.canTrack()) {+ return;+ }+ const data = {+ pid: this.projectID,+ pg: this.activePage,+ lc: getLocale(),+ tz: getTimezone(),+ ref: getReferrer(),+ so: getUTMSource(),+ me: getUTMMedium(),+ ca: getUTMCampaign(),+ ...event,+ };+ this.sendRequest('custom', data);+ }+ trackPageViews(options) {+ if (!this.canTrack()) {+ return defaultPageActions;+ }+ if (this.pageData) {+ return this.pageData.actions;+ }+ this.pageViewsOptions = options;+ let hbInterval, interval;+ if (!options?.unique) {+ interval = setInterval(this.trackPathChange, 2000);+ }+ if (!options?.noHeartbeat) {+ setTimeout(this.heartbeat, 3000);+ hbInterval = setInterval(this.heartbeat, 28000);+ }+ const path = getPath();+ this.pageData = {+ path,+ actions: {+ stop: () => {+ clearInterval(interval);+ clearInterval(hbInterval);+ },+ },+ };+ this.trackPage(path, options?.unique);+ return this.pageData.actions;+ }+ getPerformanceStats() {+ if (!this.canTrack() || this.perfStatsCollected || !window.performance?.getEntriesByType) {+ return {};+ }+ const perf = window.performance.getEntriesByType('navigation')[0];+ if (!perf) {+ return {};+ }+ this.perfStatsCollected = true;+ return {+ // Network+ // @ts-ignore+ dns: perf.domainLookupEnd - perf.domainLookupStart,+ // @ts-ignore+ tls: perf.secureConnectionStart ? perf.requestStart - perf.secureConnectionStart : 0,+ // @ts-ignore+ conn: perf.secureConnectionStart ? perf.secureConnectionStart - perf.connectStart : perf.connectEnd - perf.connectStart,+ // @ts-ignore+ response: perf.responseEnd - perf.responseStart,+ // Frontend+ // @ts-ignore+ render: perf.domComplete - perf.domContentLoadedEventEnd,+ // @ts-ignore+ dom_load: perf.domContentLoadedEventEnd - perf.responseEnd,+ // @ts-ignore+ page_load: perf.loadEventStart,+ // Backend+ // @ts-ignore+ ttfb: perf.responseStart - perf.requestStart,+ };+ }+ heartbeat() {+ if (!this.pageViewsOptions?.heartbeatOnBackground && document.visibilityState === 'hidden') {+ return;+ }+ const data = {+ pid: this.projectID,+ };+ this.sendRequest('hb', data);+ }+ checkIgnore(path) {+ const ignore = this.pageViewsOptions?.ignore;+ if (Array.isArray(ignore)) {+ for (let i = 0; i < ignore.length; ++i) {+ if (ignore[i] === path)+ return true;+ // @ts-ignore+ if (ignore[i] instanceof RegExp && ignore[i].test(path))+ return true;+ }+ }+ return false;+ }+ // Tracking path changes. If path changes -> calling this.trackPage method+ trackPathChange() {+ if (!this.pageData)+ return;+ const newPath = getPath();+ const { path } = this.pageData;+ if (path !== newPath) {+ this.trackPage(newPath, false);+ }+ }+ trackPage(pg, unique = false) {+ if (!this.pageData)+ return;+ this.pageData.path = pg;+ if (this.checkIgnore(pg))+ return;+ this.activePage = pg;+ const perf = this.getPerformanceStats();+ const data = {+ pid: this.projectID,+ lc: getLocale(),+ tz: getTimezone(),+ ref: getReferrer(),+ so: getUTMSource(),+ me: getUTMMedium(),+ ca: getUTMCampaign(),+ unique,+ pg,+ perf,+ };+ this.sendRequest('', data);+ }+ debug(message) {+ if (this.options?.debug) {+ console.log('[Swetrix]', message);+ }+ }+ canTrack() {+ if (this.options?.disabled) {+ this.debug('Tracking disabled: the \'disabled\' setting is set to true.');+ return false;+ }+ if (!isInBrowser()) {+ this.debug('Tracking disabled: script does not run in browser environment.');+ return false;+ }+ if (this.options?.respectDNT && window.navigator?.doNotTrack === '1') {+ this.debug('Tracking disabled: respecting user\'s \'Do Not Track\' preference.');+ return false;+ }+ if (!this.options?.debug && isLocalhost()) {+ return false;+ }+ if (isAutomated()) {+ this.debug('Tracking disabled: navigation is automated by WebDriver.');+ return false;+ }+ return true;+ }+ sendRequest(path, body) {+ const host = this.options?.apiURL || DEFAULT_API_HOST;+ const req = new XMLHttpRequest();+ req.open('POST', `${host}/${path}`, true);+ req.setRequestHeader('Content-Type', 'application/json');+ req.send(JSON.stringify(body));+ }+}+//# sourceMappingURL=Lib.js.map\ No newline at end of filediff --git a/dist/esnext/Lib.js.map b/dist/esnext/Lib.js.mapnew file mode 100644index 000000000..55469a4a5--- /dev/null+++ b/dist/esnext/Lib.js.map@@ -0,0 +1 @@+{"version":3,"file":"Lib.js","sourceRoot":"","sources":["../../src/Lib.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,WAAW,EAAE,WAAW,EAAE,WAAW,EAAE,SAAS,EAAE,WAAW,EAAE,WAAW,EAC1E,cAAc,EAAE,YAAY,EAAE,YAAY,EAAE,OAAO,GACpD,MAAM,SAAS,CAAA;AAgEhB,MAAM,CAAC,MAAM,kBAAkB,GAAG;IAChC,IAAI,KAAI,CAAC;CACV,CAAA;AAED,MAAM,gBAAgB,GAAG,6BAA6B,CAAA;AAEtD,MAAM,OAAO,GAAG;IAMd,YAAoB,SAAiB,EAAU,OAAoB;QAA/C,cAAS,GAAT,SAAS,CAAQ;QAAU,YAAO,GAAP,OAAO,CAAa;QAL3D,aAAQ,GAAoB,IAAI,CAAA;QAChC,qBAAgB,GAAwC,IAAI,CAAA;QAC5D,uBAAkB,GAAY,KAAK,CAAA;QACnC,eAAU,GAAkB,IAAI,CAAA;QAGtC,IAAI,CAAC,eAAe,GAAG,IAAI,CAAC,eAA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,KAAK,GAAG,EAAE;YACpE,IAAI,CAAC,KAAK,CAAC,oEAAoE,CAAC,CAAA;YAChF,OAAO,KAAK,CAAA;SACb;QAED,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,KAAK,IAAI,WAAW,EAAE,EAAE;YACzC,OAAO,KAAK,CAAA;SACb;QAED,IAAI,WAAW,EAAE,EAAE;YACjB,IAAI,CAAC,KAAK,CAAC,0DAA0D,CAAC,CAAA;YACtE,OAAO,KAAK,CAAA;SACb;QAED,OAAO,IAAI,CAAA;IACb,CAAC;IAEO,WAAW,CAAC,IAAY,EAAE,IAAY;QAC5C,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,EAAE,MAAM,IAAI,gBAAgB,CAAA;QACrD,MAAM,GAAG,GAAG,IAAI,cAAc,EAAE,CAAA;QAChC,GAAG,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,IAAI,IAAI,EAAE,EAAE,IAAI,CAAC,CAAA;QACzC,GAAG,CAAC,gBAAgB,CAAC,cAAc,EAAE,kBAAkB,CAAC,CAAA;QACxD,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAA;IAChC,CAAC;CACF"}\ No newline at end of filediff --git a/dist/esnext/index.d.ts b/dist/esnext/index.d.tsnew file mode 100644index 000000000..9c77fcbb3--- /dev/null+++ b/dist/esnext/index.d.ts@@ -0,0 +1,27 @@+import { Lib, LibOptions, TrackEventOptions, PageViewsOptions, PageActions } from './Lib';+export declare let LIB_INSTANCE: Lib | null;+/**+ * Initialise the tracking library instance (other methods won't work if the library is not initialised).+ *+ * @param {string} pid The Project ID to link the instance of Swetrix.js to.+ * @param {LibOptions} options Options related to the tracking.+ * @returns {Lib} Instance of the Swetrix.js.+ */+export declare function init(pid: string, options?: LibOptions): Lib;+/**+ * With this function you are able to track any custom events you want.+ * You should never send any identifiable data (like User ID, email, session cookie, etc.) as an event name.+ * The total number of track calls and their conversion rate will be saved.+ *+ * @param {TrackEventOptions} event The options related to the custom event.+ */+export declare function track(event: TrackEventOptions): void;+/**+ * With this function you are able to track any custom events you want.+ * You should never send any identifiable data (like User ID, email, session cookie, etc.) as an event name.+ * The total number of track calls and their conversion rate will be saved.+ *+ * @param {PageViewsOptions} options The options related to the custom event.+ * @returns {PageActions} The actions related to the tracking. Used to stop tracking pages.+ */+export declare function trackViews(options?: PageViewsOptions): Promise<PageActions>;diff --git a/dist/esnext/index.js b/dist/esnext/index.jsnew file mode 100644index 000000000..f96627acd--- /dev/null+++ b/dist/esnext/index.js@@ -0,0 +1,54 @@+import { Lib, defaultPageActions, } from './Lib';+export let LIB_INSTANCE = null;+/**+ * Initialise the tracking library instance (other methods won't work if the library is not initialised).+ *+ * @param {string} pid The Project ID to link the instance of Swetrix.js to.+ * @param {LibOptions} options Options related to the tracking.+ * @returns {Lib} Instance of the Swetrix.js.+ */+export function init(pid, options) {+ if (!LIB_INSTANCE) {+ LIB_INSTANCE = new Lib(pid, options);+ }+ return LIB_INSTANCE;+}+/**+ * With this function you are able to track any custom events you want.+ * You should never send any identifiable data (like User ID, email, session cookie, etc.) as an event name.+ * The total number of track calls and their conversion rate will be saved.+ *+ * @param {TrackEventOptions} event The options related to the custom event.+ */+export function track(event) {+ if (!LIB_INSTANCE)+ return;+ LIB_INSTANCE.track(event);+}+/**+ * With this function you are able to track any custom events you want.+ * You should never send any identifiable data (like User ID, email, session cookie, etc.) as an event name.+ * The total number of track calls and their conversion rate will be saved.+ *+ * @param {PageViewsOptions} options The options related to the custom event.+ * @returns {PageActions} The actions related to the tracking. Used to stop tracking pages.+ */+export function trackViews(options) {+ return new Promise((resolve) => {+ if (!LIB_INSTANCE) {+ resolve(defaultPageActions);+ return;+ }+ // We need to verify that document.readyState is complete for the performance stats to be collected correctly.+ if (typeof document === 'undefined' || document.readyState === 'complete') {+ resolve(LIB_INSTANCE.trackPageViews(options));+ }+ else {+ window.addEventListener('load', () => {+ // @ts-ignore+ resolve(LIB_INSTANCE.trackPageViews(options));+ });+ }+ });+}+//# sourceMappingURL=index.js.map\ No newline at end of filediff --git a/dist/esnext/index.js.map b/dist/esnext/index.js.mapnew file mode 100644index 000000000..26ac360fa--- /dev/null+++ b/dist/esnext/index.js.map@@ -0,0 +1 @@+{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,GAAG,EAAgE,kBAAkB,GACtF,MAAM,OAAO,CAAA;AAEd,MAAM,CAAC,IAAI,YAAY,GAAe,IAAI,CAAA;AAE1C;;;;;;GAMG;AACH,MAAM,UAAU,IAAI,CAAC,GAAW,EAAE,OAAoB;IACpD,IAAI,CAAC,YAAY,EAAE;QACjB,YAAY,GAAG,IAAI,GAAG,CAAC,GAAG,EAAE,OAAO,CAAC,CAAA;KACrC;IAED,OAAO,YAAY,CAAA;AACrB,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,KAAK,CAAC,KAAwB;IAC5C,IAAI,CAAC,YAAY;QAAE,OAAM;IAEzB,YAAY,CAAC,KAAK,CAAC,KAAK,CAAC,CAAA;AAC3B,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,UAAU,CAAC,OAA0B;IACnD,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;QAC7B,IAAI,CAAC,YAAY,EAAE;YACjB,OAAO,CAAC,kBAAkB,CAAC,CAAA;YAC3B,OAAM;SACP;QAED,8GAA8G;QAC9G,IAAI,OAAO,QAAQ,KAAK,WAAW,IAAI,QAAQ,CAAC,UAAU,KAAK,UAAU,EAAE;YACzE,OAAO,CAAC,YAAY,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC,CAAA;SAC9C;aAAM;YACL,MAAM,CAAC,gBAAgB,CAAC,MAAM,EAAE,GAAG,EAAE;gBACnC,aAAa;gBACb,OAAO,CAAC,YAAY,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC,CAAA;YAC/C,CAAC,CAAC,CAAA;SACH;IACH,CAAC,CAAC,CAAA;AACJ,CAAC"}\ No newline at end of filediff --git a/dist/esnext/utils.d.ts b/dist/esnext/utils.d.tsnew file mode 100644index 000000000..c65fe5217--- /dev/null+++ b/dist/esnext/utils.d.ts@@ -0,0 +1,10 @@+export declare const isInBrowser: () => boolean;+export declare const isLocalhost: () => boolean;+export declare const isAutomated: () => boolean;+export declare const getLocale: () => string;+export declare const getTimezone: () => string | undefined;+export declare const getReferrer: () => string | undefined;+export declare const getUTMSource: () => string | undefined;+export declare const getUTMMedium: () => string | undefined;+export declare const getUTMCampaign: () => string | undefined;+export declare const getPath: () => string;diff --git a/dist/esnext/utils.js b/dist/esnext/utils.jsnew file mode 100644index 000000000..f376b120c--- /dev/null+++ b/dist/esnext/utils.js@@ -0,0 +1,38 @@+const findInSearch = (exp) => {+ const res = location.search.match(exp);+ return (res && res[2]) || undefined;+};+const utmSourceRegex = /[?&](ref|source|utm_source)=([^?&]+)/;+const utmCampaignRegex = /[?&](utm_campaign)=([^?&]+)/;+const utmMediumRegex = /[?&](utm_medium)=([^?&]+)/;+export const isInBrowser = () => {+ return typeof window !== 'undefined';+};+export const isLocalhost = () => {+ return location?.hostname === 'localhost' || location?.hostname === '127.0.0.1' || location?.hostname === '';+};+export const isAutomated = () => {+ return navigator?.webdriver;+};+export const getLocale = () => {+ return typeof navigator.languages !== 'undefined' ? navigator.languages[0] : navigator.language;+};+export const getTimezone = () => {+ try {+ return Intl.DateTimeFormat().resolvedOptions().timeZone;+ }+ catch (e) {+ return;+ }+};+export const getReferrer = () => {+ return document.referrer || undefined;+};+export const getUTMSource = () => findInSearch(utmSourceRegex);+export const getUTMMedium = () => findInSearch(utmMediumRegex);+export const getUTMCampaign = () => findInSearch(utmCampaignRegex);+export const getPath = () => {+ // TODO: Maybe we should also include such data as location.hash or location.search+ return location.pathname || '';+};+//# sourceMappingURL=utils.js.map\ No newline at end of filediff --git a/dist/esnext/utils.js.map b/dist/esnext/utils.js.mapnew file mode 100644index 000000000..78db14da6--- /dev/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AM;KACP;AACH,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,WAAW,GAAG,GAAuB,EAAE;IAClD,OAAO,QAAQ,CAAC,QAAQ,IAAI,SAAS,CAAA;AACvC,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,YAAY,GAAG,GAAG,EAAE,CAAC,YAAY,CAAC,cAAc,CAAC,CAAA;AAE9D,MAAM,CAAC,MAAM,YAAY,GAAG,GAAG,EAAE,CAAC,YAAY,CAAC,cAAc,CAAC,CAAA;AAE9D,MAAM,CAAC,MAAM,cAAc,GAAG,GAAG,EAAE,CAAC,YAAY,CAAC,gBAAgB,CAAC,CAAA;AAElE,MAAM,CAAC,MAAM,OAAO,GAAG,GAAW,EAAE;IAClC,mFAAmF;IACnF,OAAO,QAAQ,CAAC,QAAQ,IAAI,EAAE,CAAA;AAChC,CAAC,CAAA"}\ No newline at end of filediff --git a/dist/swetrix.cjs.js b/dist/swetrix.cjs.jsnew file mode 100644index 000000000..353ee1d56--- /dev/null+++ b/dist/swetrix.cjs.js@@ -0,0 +1,304 @@+'use strict';++Object.defineProperty(exports, '__esModule', { value: true });++/******************************************************************************+Copyright (c) Microsoft Corporation.++Permission to use, copy, modify, and/or distribute this software for any+purpose with or without fee is hereby granted.++THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH+REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY+AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,+INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM+LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR+OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR+PERFORMANCE OF THIS SOFTWARE.+***************************************************************************** */++var __assign = function() {+ __assign = Object.assign || function __assign(t) {+ for (var s, i = 1, n = arguments.length; i < n; i++) {+ s = arguments[i];+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];+ }+ return t;+ };+ return __assign.apply(this, arguments);+};++var findInSearch = function (exp) {+ var res = location.search.match(exp);+ return (res && res[2]) || undefined;+};+var utmSourceRegex = /[?&](ref|source|utm_source)=([^?&]+)/;+var utmCampaignRegex = /[?&](utm_campaign)=([^?&]+)/;+var utmMediumRegex = /[?&](utm_medium)=([^?&]+)/;+var isInBrowser = function () {+ return typeof window !== 'undefined';+};+var isLocalhost = function () {+ return (location === null || location === void 0 ? void 0 : location.hostname) === 'localhost' || (location === null || location === void 0 ? void 0 : location.hostname) === '127.0.0.1' || (location === null || location === void 0 ? void 0 : location.hostname) === '';+};+var isAutomated = function () {+ return navigator === null || navigator === void 0 ? void 0 : navigator.webdriver;+};+var getLocale = function () {+ return typeof navigator.languages !== 'undefined' ? navigator.languages[0] : navigator.language;+};+var getTimezone = function () {+ try {+ return Intl.DateTimeFormat().resolvedOptions().timeZone;+ }+ catch (e) {+ return;+ }+};+var getReferrer = function () {+ return document.referrer || undefined;+};+var getUTMSource = function () { return findInSearch(utmSourceRegex); };+var getUTMMedium = function () { return findInSearch(utmMediumRegex); };+var getUTMCampaign = function () { return findInSearch(utmCampaignRegex); };+var getPath = function () {+ // TODO: Maybe we should also include such data as location.hash or location.search+ return location.pathname || '';+};++var defaultPageActions = {+ stop: function () { },+};+var DEFAULT_API_HOST = 'https://api.swetrix.com/log';+var Lib = /** @class */ (function () {+ function Lib(projectID, options) {+ this.projectID = projectID;+ this.options = options;+ this.pageData = null;+ this.pageViewsOptions = null;+ this.perfStatsCollected = false;+ this.activePage = null;+ this.trackPathChange = this.trackPathChange.bind(this);+ this.heartbeat = this.heartbeat.bind(this);+ }+ Lib.prototype.track = function (event) {+ if (!this.canTrack()) {+ return;+ }+ var data = __assign({ pid: this.projectID, pg: this.activePage, lc: getLocale(), tz: getTimezone(), ref: getReferrer(), so: getUTMSource(), me: getUTMMedium(), ca: getUTMCampaign() }, event);+ this.sendRequest('custom', data);+ };+ Lib.prototype.trackPageViews = function (options) {+ if (!this.canTrack()) {+ return defaultPageActions;+ }+ if (this.pageData) {+ return this.pageData.actions;+ }+ this.pageViewsOptions = options;+ var hbInterval, interval;+ if (!(options === null || options === void 0 ? void 0 : options.unique)) {+ interval = setInterval(this.trackPathChange, 2000);+ }+ if (!(options === null || options === void 0 ? void 0 : options.noHeartbeat)) {+ setTimeout(this.heartbeat, 3000);+ hbInterval = setInterval(this.heartbeat, 28000);+ }+ var path = getPath();+ this.pageData = {+ path: path,+ actions: {+ stop: function () {+ clearInterval(interval);+ clearInterval(hbInterval);+ },+ },+ };+ this.trackPage(path, options === null || options === void 0 ? void 0 : options.unique);+ return this.pageData.actions;+ };+ Lib.prototype.getPerformanceStats = function () {+ var _a;+ if (!this.canTrack() || this.perfStatsCollected || !((_a = window.performance) === null || _a === void 0 ? void 0 : _a.getEntriesByType)) {+ return {};+ }+ var perf = window.performance.getEntriesByType('navigation')[0];+ if (!perf) {+ return {};+ }+ this.perfStatsCollected = true;+ return {+ // Network+ // @ts-ignore+ dns: perf.domainLookupEnd - perf.domainLookupStart,+ // @ts-ignore+ tls: perf.secureConnectionStart ? perf.requestStart - perf.secureConnectionStart : 0,+ // @ts-ignore+ conn: perf.secureConnectionStart ? perf.secureConnectionStart - perf.connectStart : perf.connectEnd - perf.connectStart,+ // @ts-ignore+ response: perf.responseEnd - perf.responseStart,+ // Frontend+ // @ts-ignore+ render: perf.domComplete - perf.domContentLoadedEventEnd,+ // @ts-ignore+ dom_load: perf.domContentLoadedEventEnd - perf.responseEnd,+ // @ts-ignore+ page_load: perf.loadEventStart,+ // Backend+ // @ts-ignore+ ttfb: perf.responseStart - perf.requestStart,+ };+ };+ Lib.prototype.heartbeat = function () {+ var _a;+ if (!((_a = this.pageViewsOptions) === null || _a === void 0 ? void 0 : _a.heartbeatOnBackground) && document.visibilityState === 'hidden') {+ return;+ }+ var data = {+ pid: this.projectID,+ };+ this.sendRequest('hb', data);+ };+ Lib.prototype.checkIgnore = function (path) {+ var _a;+ var ignore = (_a = this.pageViewsOptions) === null || _a === void 0 ? void 0 : _a.ignore;+ if (Array.isArray(ignore)) {+ for (var i = 0; i < ignore.length; ++i) {+ if (ignore[i] === path)+ return true;+ // @ts-ignore+ if (ignore[i] instanceof RegExp && ignore[i].test(path))+ return true;+ }+ }+ return false;+ };+ // Tracking path changes. If path changes -> calling this.trackPage method+ Lib.prototype.trackPathChange = function () {+ if (!this.pageData)+ return;+ var newPath = getPath();+ var path = this.pageData.path;+ if (path !== newPath) {+ this.trackPage(newPath, false);+ }+ };+ Lib.prototype.trackPage = function (pg, unique) {+ if (unique === void 0) { unique = false; }+ if (!this.pageData)+ return;+ this.pageData.path = pg;+ if (this.checkIgnore(pg))+ return;+ this.activePage = pg;+ var perf = this.getPerformanceStats();+ var data = {+ pid: this.projectID,+ lc: getLocale(),+ tz: getTimezone(),+ ref: getReferrer(),+ so: getUTMSource(),+ me: getUTMMedium(),+ ca: getUTMCampaign(),+ unique: unique,+ pg: pg,+ perf: perf,+ };+ this.sendRequest('', data);+ };+ Lib.prototype.debug = function (message) {+ var _a;+ if ((_a = this.options) === null || _a === void 0 ? void 0 : _a.debug) {+ console.log('[Swetrix]', message);+ }+ };+ Lib.prototype.canTrack = function () {+ var _a, _b, _c, _d;+ if ((_a = this.options) === null || _a === void 0 ? void 0 : _a.disabled) {+ this.debug('Tracking disabled: the \'disabled\' setting is set to true.');+ return false;+ }+ if (!isInBrowser()) {+ this.debug('Tracking disabled: script does not run in browser environment.');+ return false;+ }+ if (((_b = this.options) === null || _b === void 0 ? void 0 : _b.respectDNT) && ((_c = window.navigator) === null || _c === void 0 ? void 0 : _c.doNotTrack) === '1') {+ this.debug('Tracking disabled: respecting user\'s \'Do Not Track\' preference.');+ return false;+ }+ if (!((_d = this.options) === null || _d === void 0 ? void 0 : _d.debug) && isLocalhost()) {+ return false;+ }+ if (isAutomated()) {+ this.debug('Tracking disabled: navigation is automated by WebDriver.');+ return false;+ }+ return true;+ };+ Lib.prototype.sendRequest = function (path, body) {+ var _a;+ var host = ((_a = this.options) === null || _a === void 0 ? void 0 : _a.apiURL) || DEFAULT_API_HOST;+ var req = new XMLHttpRequest();+ req.open('POST', "".concat(host, "/").concat(path), true);+ req.setRequestHeader('Content-Type', 'application/json');+ req.send(JSON.stringify(body));+ };+ return Lib;+}());++exports.LIB_INSTANCE = null;+/**+ * Initialise the tracking library instance (other methods won't work if the library is not initialised).+ *+ * @param {string} pid The Project ID to link the instance of Swetrix.js to.+ * @param {LibOptions} options Options related to the tracking.+ * @returns {Lib} Instance of the Swetrix.js.+ */+function init(pid, options) {+ if (!exports.LIB_INSTANCE) {+ exports.LIB_INSTANCE = new Lib(pid, options);+ }+ return exports.LIB_INSTANCE;+}+/**+ * With this function you are able to track any custom events you want.+ * You should never send any identifiable data (like User ID, email, session cookie, etc.) as an event name.+ * The total number of track calls and their conversion rate will be saved.+ *+ * @param {TrackEventOptions} event The options related to the custom event.+ */+function track(event) {+ if (!exports.LIB_INSTANCE)+ return;+ exports.LIB_INSTANCE.track(event);+}+/**+ * With this function you are able to track any custom events you want.+ * You should never send any identifiable data (like User ID, email, session cookie, etc.) as an event name.+ * The total number of track calls and their conversion rate will be saved.+ *+ * @param {PageViewsOptions} options The options related to the custom event.+ * @returns {PageActions} The actions related to the tracking. Used to stop tracking pages.+ */+function trackViews(options) {+ return new Promise(function (resolve) {+ if (!exports.LIB_INSTANCE) {+ resolve(defaultPageActions);+ return;+ }+ // We need to verify that document.readyState is complete for the performance stats to be collected correctly.+ if (typeof document === 'undefined' || document.readyState === 'complete') {+ resolve(exports.LIB_INSTANCE.trackPageViews(options));+ }+ else {+ window.addEventListener('load', function () {+ // @ts-ignore+ resolve(exports.LIB_INSTANCE.trackPageViews(options));+ });+ }+ });+}++exports.init = init;+exports.track = track;+exports.trackViews = trackViews;diff --git a/dist/swetrix.es5.js b/dist/swetrix.es5.jsnew file mode 100644index 000000000..6757b9e6f--- /dev/null+++ b/dist/swetrix.es5.js@@ -0,0 +1,298 @@+/******************************************************************************+Copyright (c) Microsoft Corporation.++Permission to use, copy, modify, and/or distribute this software for any+purpose with or without fee is hereby granted.++THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH+REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY+AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,+INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM+LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR+OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR+PERFORMANCE OF THIS SOFTWARE.+***************************************************************************** */++var __assign = function() {+ __assign = Object.assign || function __assign(t) {+ for (var s, i = 1, n = arguments.length; i < n; i++) {+ s = arguments[i];+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];+ }+ return t;+ };+ return __assign.apply(this, arguments);+};++var findInSearch = function (exp) {+ var res = location.search.match(exp);+ return (res && res[2]) || undefined;+};+var utmSourceRegex = /[?&](ref|source|utm_source)=([^?&]+)/;+var utmCampaignRegex = /[?&](utm_campaign)=([^?&]+)/;+var utmMediumRegex = /[?&](utm_medium)=([^?&]+)/;+var isInBrowser = function () {+ return typeof window !== 'undefined';+};+var isLocalhost = function () {+ return (location === null || location === void 0 ? void 0 : location.hostname) === 'localhost' || (location === null || location === void 0 ? void 0 : location.hostname) === '127.0.0.1' || (location === null || location === void 0 ? void 0 : location.hostname) === '';+};+var isAutomated = function () {+ return navigator === null || navigator === void 0 ? void 0 : navigator.webdriver;+};+var getLocale = function () {+ return typeof navigator.languages !== 'undefined' ? navigator.languages[0] : navigator.language;+};+var getTimezone = function () {+ try {+ return Intl.DateTimeFormat().resolvedOptions().timeZone;+ }+ catch (e) {+ return;+ }+};+var getReferrer = function () {+ return document.referrer || undefined;+};+var getUTMSource = function () { return findInSearch(utmSourceRegex); };+var getUTMMedium = function () { return findInSearch(utmMediumRegex); };+var getUTMCampaign = function () { return findInSearch(utmCampaignRegex); };+var getPath = function () {+ // TODO: Maybe we should also include such data as location.hash or location.search+ return location.pathname || '';+};++var defaultPageActions = {+ stop: function () { },+};+var DEFAULT_API_HOST = 'https://api.swetrix.com/log';+var Lib = /** @class */ (function () {+ function Lib(projectID, options) {+ this.projectID = projectID;+ this.options = options;+ this.pageData = null;+ this.pageViewsOptions = null;+ this.perfStatsCollected = false;+ this.activePage = null;+ this.trackPathChange = this.trackPathChange.bind(this);+ this.heartbeat = this.heartbeat.bind(this);+ }+ Lib.prototype.track = function (event) {+ if (!this.canTrack()) {+ return;+ }+ var data = __assign({ pid: this.projectID, pg: this.activePage, lc: getLocale(), tz: getTimezone(), ref: getReferrer(), so: getUTMSource(), me: getUTMMedium(), ca: getUTMCampaign() }, event);+ this.sendRequest('custom', data);+ };+ Lib.prototype.trackPageViews = function (options) {+ if (!this.canTrack()) {+ return defaultPageActions;+ }+ if (this.pageData) {+ return this.pageData.actions;+ }+ this.pageViewsOptions = options;+ var hbInterval, interval;+ if (!(options === null || options === void 0 ? void 0 : options.unique)) {+ interval = setInterval(this.trackPathChange, 2000);+ }+ if (!(options === null || options === void 0 ? void 0 : options.noHeartbeat)) {+ setTimeout(this.heartbeat, 3000);+ hbInterval = setInterval(this.heartbeat, 28000);+ }+ var path = getPath();+ this.pageData = {+ path: path,+ actions: {+ stop: function () {+ clearInterval(interval);+ clearInterval(hbInterval);+ },+ },+ };+ this.trackPage(path, options === null || options === void 0 ? void 0 : options.unique);+ return this.pageData.actions;+ };+ Lib.prototype.getPerformanceStats = function () {+ var _a;+ if (!this.canTrack() || this.perfStatsCollected || !((_a = window.performance) === null || _a === void 0 ? void 0 : _a.getEntriesByType)) {+ return {};+ }+ var perf = window.performance.getEntriesByType('navigation')[0];+ if (!perf) {+ return {};+ }+ this.perfStatsCollected = true;+ return {+ // Network+ // @ts-ignore+ dns: perf.domainLookupEnd - perf.domainLookupStart,+ // @ts-ignore+ tls: perf.secureConnectionStart ? perf.requestStart - perf.secureConnectionStart : 0,+ // @ts-ignore+ conn: perf.secureConnectionStart ? perf.secureConnectionStart - perf.connectStart : perf.connectEnd - perf.connectStart,+ // @ts-ignore+ response: perf.responseEnd - perf.responseStart,+ // Frontend+ // @ts-ignore+ render: perf.domComplete - perf.domContentLoadedEventEnd,+ // @ts-ignore+ dom_load: perf.domContentLoadedEventEnd - perf.responseEnd,+ // @ts-ignore+ page_load: perf.loadEventStart,+ // Backend+ // @ts-ignore+ ttfb: perf.responseStart - perf.requestStart,+ };+ };+ Lib.prototype.heartbeat = function () {+ var _a;+ if (!((_a = this.pageViewsOptions) === null || _a === void 0 ? void 0 : _a.heartbeatOnBackground) && document.visibilityState === 'hidden') {+ return;+ }+ var data = {+ pid: this.projectID,+ };+ this.sendRequest('hb', data);+ };+ Lib.prototype.checkIgnore = function (path) {+ var _a;+ var ignore = (_a = this.pageViewsOptions) === null || _a === void 0 ? void 0 : _a.ignore;+ if (Array.isArray(ignore)) {+ for (var i = 0; i < ignore.length; ++i) {+ if (ignore[i] === path)+ return true;+ // @ts-ignore+ if (ignore[i] instanceof RegExp && ignore[i].test(path))+ return true;+ }+ }+ return false;+ };+ // Tracking path changes. If path changes -> calling this.trackPage method+ Lib.prototype.trackPathChange = function () {+ if (!this.pageData)+ return;+ var newPath = getPath();+ var path = this.pageData.path;+ if (path !== newPath) {+ this.trackPage(newPath, false);+ }+ };+ Lib.prototype.trackPage = function (pg, unique) {+ if (unique === void 0) { unique = false; }+ if (!this.pageData)+ return;+ this.pageData.path = pg;+ if (this.checkIgnore(pg))+ return;+ this.activePage = pg;+ var perf = this.getPerformanceStats();+ var data = {+ pid: this.projectID,+ lc: getLocale(),+ tz: getTimezone(),+ ref: getReferrer(),+ so: getUTMSource(),+ me: getUTMMedium(),+ ca: getUTMCampaign(),+ unique: unique,+ pg: pg,+ perf: perf,+ };+ this.sendRequest('', data);+ };+ Lib.prototype.debug = function (message) {+ var _a;+ if ((_a = this.options) === null || _a === void 0 ? void 0 : _a.debug) {+ console.log('[Swetrix]', message);+ }+ };+ Lib.prototype.canTrack = function () {+ var _a, _b, _c, _d;+ if ((_a = this.options) === null || _a === void 0 ? void 0 : _a.disabled) {+ this.debug('Tracking disabled: the \'disabled\' setting is set to true.');+ return false;+ }+ if (!isInBrowser()) {+ this.debug('Tracking disabled: script does not run in browser environment.');+ return false;+ }+ if (((_b = this.options) === null || _b === void 0 ? void 0 : _b.respectDNT) && ((_c = window.navigator) === null || _c === void 0 ? void 0 : _c.doNotTrack) === '1') {+ this.debug('Tracking disabled: respecting user\'s \'Do Not Track\' preference.');+ return false;+ }+ if (!((_d = this.options) === null || _d === void 0 ? void 0 : _d.debug) && isLocalhost()) {+ return false;+ }+ if (isAutomated()) {+ this.debug('Tracking disabled: navigation is automated by WebDriver.');+ return false;+ }+ return true;+ };+ Lib.prototype.sendRequest = function (path, body) {+ var _a;+ var host = ((_a = this.options) === null || _a === void 0 ? void 0 : _a.apiURL) || DEFAULT_API_HOST;+ var req = new XMLHttpRequest();+ req.open('POST', "".concat(host, "/").concat(path), true);+ req.setRequestHeader('Content-Type', 'application/json');+ req.send(JSON.stringify(body));+ };+ return Lib;+}());++var LIB_INSTANCE = null;+/**+ * Initialise the tracking library instance (other methods won't work if the library is not initialised).+ *+ * @param {string} pid The Project ID to link the instance of Swetrix.js to.+ * @param {LibOptions} options Options related to the tracking.+ * @returns {Lib} Instance of the Swetrix.js.+ */+function init(pid, options) {+ if (!LIB_INSTANCE) {+ LIB_INSTANCE = new Lib(pid, options);+ }+ return LIB_INSTANCE;+}+/**+ * With this function you are able to track any custom events you want.+ * You should never send any identifiable data (like User ID, email, session cookie, etc.) as an event name.+ * The total number of track calls and their conversion rate will be saved.+ *+ * @param {TrackEventOptions} event The options related to the custom event.+ */+function track(event) {+ if (!LIB_INSTANCE)+ return;+ LIB_INSTANCE.track(event);+}+/**+ * With this function you are able to track any custom events you want.+ * You should never send any identifiable data (like User ID, email, session cookie, etc.) as an event name.+ * The total number of track calls and their conversion rate will be saved.+ *+ * @param {PageViewsOptions} options The options related to the custom event.+ * @returns {PageActions} The actions related to the tracking. Used to stop tracking pages.+ */+function trackViews(options) {+ return new Promise(function (resolve) {+ if (!LIB_INSTANCE) {+ resolve(defaultPageActions);+ return;+ }+ // We need to verify that document.readyState is complete for the performance stats to be collected correctly.+ if (typeof document === 'undefined' || document.readyState === 'complete') {+ resolve(LIB_INSTANCE.trackPageViews(options));+ }+ else {+ window.addEventListener('load', function () {+ // @ts-ignore+ resolve(LIB_INSTANCE.trackPageViews(options));+ });+ }+ });+}++export { LIB_INSTANCE, init, track, trackViews };diff --git a/dist/swetrix.js b/dist/swetrix.jsnew file mode 100644index 000000000..e479524d5--- /dev/null+++ b/dist/swetrix.js@@ -0,0 +1 @@+!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).swetrix={})}(this,function(n){"use strict";function t(t){return(t=location.search.match(t))&&t[2]||void 0}function o(){return void 0!==navigator.languages?navigator.languages[0]:navigator.language}function i(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch(t){}}function a(){return document.referrer||void 0}function r(){return t(d)}function s(){return t(l)}function c(){return t(p)}function u(){return location.pathname||""}var e=function(){return(e=Object.assign||function(t){for(var e,n=1,o=arguments.length;n<o;n++)for(var i in e=arguments[n])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t}).apply(this,arguments)},d=/[?&](ref|source|utm_source)=([^?&]+)/,p=/[?&](utm_campaign)=([^?&]+)/,l=/[?&](utm_medium)=([^?&]+)/,h={stop:function(){}},g=(f.prototype.track=function(t){this.canTrack()&&(t=e({pid:this.projectID,pg:this.activePage,lc:o(),tz:i(),ref:a(),so:r(),me:s(),ca:c()},t),this.sendRequest("custom",t))},f.prototype.trackPageViews=function(t){var e,n,o;return this.canTrack()?(this.pageData||(null!=(this.pageViewsOptions=t)&&t.unique||(n=setInterval(this.trackPathChange,2e3)),null!=t&&t.noHeartbeat||(setTimeout(this.heartbeat,3e3),e=setInterval(this.heartbeat,28e3)),o=u(),this.pageData={path:o,actions:{stop:function(){clearInterval(n),clearInterval(e)}}},this.trackPage(o,null==t?void 0:t.unique)),this.pageData.actions):h},f.prototype.getPerformanceStats=function(){var t;return this.canTrack()&&!this.perfStatsCollected&&null!=(t=window.performance)&&t.getEntriesByType&&(t=window.performance.getEntriesByType("navigation")[0])?(this.perfStatsCollected=!0,{dns:t.domainLookupEnd-t.domainLookupStart,tls:t.secureConnectionStart?t.requestStart-t.secureConnectionStart:0,conn:t.secureConnectionStart?t.secureConnectionStart-t.connectStart:t.connectEnd-t.connectStart,response:t.responseEnd-t.responseStart,render:t.domComplete-t.domContentLoadedEventEnd,dom_load:t.domContentLoadedEventEnd-t.responseEnd,page_load:t.loadEventStart,ttfb:t.responseStart-t.requestStart}):{}},f.prototype.heartbeat=function(){var t;(null!=(t=this.pageViewsOptions)&&t.heartbeatOnBackground||"hidden"!==document.visibilityState)&&(t={pid:this.projectID},this.sendRequest("hb",t))},f.prototype.checkIgnore=function(t){var e,n=null==(e=this.pageViewsOptions)?void 0:e.ignore;if(Array.isArray(n))for(var o=0;o<n.length;++o){if(n[o]===t)return!0;if(n[o]instanceof RegExp&&n[o].test(t))return!0}return!1},f.prototype.trackPathChange=function(){var t;this.pageData&&(t=u(),this.pageData.path!==t)&&this.trackPage(t,!1)},f.prototype.trackPage=function(t,e){var n;void 0===e&&(e=!1),this.pageData&&(this.pageData.path=t,this.checkIgnore(t)||(this.activePage=t,n=this.getPerformanceStats(),e={pid:this.projectID,lc:o(),tz:i(),ref:a(),so:r(),me:s(),ca:c(),unique:e,pg:t,perf:n},this.sendRequest("",e)))},f.prototype.debug=function(t){var e;null!=(e=this.options)&&e.debug&&console.log("[Swetrix]",t)},f.prototype.canTrack=function(){var t;return null!=(t=this.options)&&t.disabled?(this.debug("Tracking disabled: the 'disabled' setting is set to true."),!1):"undefined"==typeof window?(this.debug("Tracking disabled: script does not run in browser environment."),!1):null!=(t=this.options)&&t.respectDNT&&"1"===(null==(t=window.navigator)?void 0:t.doNotTrack)?(this.debug("Tracking disabled: respecting user's 'Do Not Track' preference."),!1):!(!(null!=(t=this.options)&&t.debug||"localhost"!==(null===location||void 0===location?void 0:location.hostname)&&"127.0.0.1"!==(null===location||void 0===location?void 0:location.hostname)&&""!==(null===location||void 0===location?void 0:location.hostname))||null!==navigator&&void 0!==navigator&&navigator.webdriver&&(this.debug("Tracking disabled: navigation is automated by WebDriver."),1))},f.prototype.sendRequest=function(t,e){var n=(null==(n=this.options)?void 0:n.apiURL)||"https://api.swetrix.com/log",o=new XMLHttpRequest;o.open("POST","".concat(n,"/").concat(t),!0),o.setRequestHeader("Content-Type","application/json"),o.send(JSON.stringify(e))},f);function f(t,e){this.projectID=t,this.options=e,this.pageData=null,this.pageViewsOptions=null,this.perfStatsCollected=!1,this.activePage=null,this.trackPathChange=this.trackPathChange.bind(this),this.heartbeat=this.heartbeat.bind(this)}n.LIB_INSTANCE=null,n.init=function(t,e){return n.LIB_INSTANCE||(n.LIB_INSTANCE=new g(t,e)),n.LIB_INSTANCE},n.track=function(t){n.LIB_INSTANCE&&n.LIB_INSTANCE.track(t)},n.trackViews=function(e){return new Promise(function(t){n.LIB_INSTANCE?"undefined"==typeof document||"complete"===document.readyState?t(n.LIB_INSTANCE.trackPageViews(e)):window.addEventListener("load",function(){t(n.LIB_INSTANCE.trackPageViews(e))}):t(h)})},Object.defineProperty(n,"__esModule",{value:!0})});diff --git a/dist/swetrix.orig.js b/dist/swetrix.orig.jsnew file mode 100644index 000000000..f53f97d0b--- /dev/null+++ b/dist/swetrix.orig.js@@ -0,0 +1,310 @@+(function (global, factory) {+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :+ typeof define === 'function' && define.amd ? define(['exports'], factory) :+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.swetrix = {}));+})(this, (function (exports) { 'use strict';++ /******************************************************************************+ Copyright (c) Microsoft Corporation.++ Permission to use, copy, modify, and/or distribute this software for any+ purpose with or without fee is hereby granted.++ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR+ PERFORMANCE OF THIS SOFTWARE.+ ***************************************************************************** */++ var __assign = function() {+ __assign = Object.assign || function __assign(t) {+ for (var s, i = 1, n = arguments.length; i < n; i++) {+ s = arguments[i];+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];+ }+ return t;+ };+ return __assign.apply(this, arguments);+ };++ var findInSearch = function (exp) {+ var res = location.search.match(exp);+ return (res && res[2]) || undefined;+ };+ var utmSourceRegex = /[?&](ref|source|utm_source)=([^?&]+)/;+ var utmCampaignRegex = /[?&](utm_campaign)=([^?&]+)/;+ var utmMediumRegex = /[?&](utm_medium)=([^?&]+)/;+ var isInBrowser = function () {+ return typeof window !== 'undefined';+ };+ var isLocalhost = function () {+ return (location === null || location === void 0 ? void 0 : location.hostname) === 'localhost' || (location === null || location === void 0 ? void 0 : location.hostname) === '127.0.0.1' || (location === null || location === void 0 ? void 0 : location.hostname) === '';+ };+ var isAutomated = function () {+ return navigator === null || navigator === void 0 ? void 0 : navigator.webdriver;+ };+ var getLocale = function () {+ return typeof navigator.languages !== 'undefined' ? navigator.languages[0] : navigator.language;+ };+ var getTimezone = function () {+ try {+ return Intl.DateTimeFormat().resolvedOptions().timeZone;+ }+ catch (e) {+ return;+ }+ };+ var getReferrer = function () {+ return document.referrer || undefined;+ };+ var getUTMSource = function () { return findInSearch(utmSourceRegex); };+ var getUTMMedium = function () { return findInSearch(utmMediumRegex); };+ var getUTMCampaign = function () { return findInSearch(utmCampaignRegex); };+ var getPath = function () {+ // TODO: Maybe we should also include such data as location.hash or location.search+ return location.pathname || '';+ };++ var defaultPageActions = {+ stop: function () { },+ };+ var DEFAULT_API_HOST = 'https://api.swetrix.com/log';+ var Lib = /** @class */ (function () {+ function Lib(projectID, options) {+ this.projectID = projectID;+ this.options = options;+ this.pageData = null;+ this.pageViewsOptions = null;+ this.perfStatsCollected = false;+ this.activePage = null;+ this.trackPathChange = this.trackPathChange.bind(this);+ this.heartbeat = this.heartbeat.bind(this);+ }+ Lib.prototype.track = function (event) {+ if (!this.canTrack()) {+ return;+ }+ var data = __assign({ pid: this.projectID, pg: this.activePage, lc: getLocale(), tz: getTimezone(), ref: getReferrer(), so: getUTMSource(), me: getUTMMedium(), ca: getUTMCampaign() }, event);+ this.sendRequest('custom', data);+ };+ Lib.prototype.trackPageViews = function (options) {+ if (!this.canTrack()) {+ return defaultPageActions;+ }+ if (this.pageData) {+ return this.pageData.actions;+ }+ this.pageViewsOptions = options;+ var hbInterval, interval;+ if (!(options === null || options === void 0 ? void 0 : options.unique)) {+ interval = setInterval(this.trackPathChange, 2000);+ }+ if (!(options === null || options === void 0 ? void 0 : options.noHeartbeat)) {+ setTimeout(this.heartbeat, 3000);+ hbInterval = setInterval(this.heartbeat, 28000);+ }+ var path = getPath();+ this.pageData = {+ path: path,+ actions: {+ stop: function () {+ clearInterval(interval);+ clearInterval(hbInterval);+ },+ },+ };+ this.trackPage(path, options === null || options === void 0 ? void 0 : options.unique);+ return this.pageData.actions;+ };+ Lib.prototype.getPerformanceStats = function () {+ var _a;+ if (!this.canTrack() || this.perfStatsCollected || !((_a = window.performance) === null || _a === void 0 ? void 0 : _a.getEntriesByType)) {+ return {};+ }+ var perf = window.performance.getEntriesByType('navigation')[0];+ if (!perf) {+ return {};+ }+ this.perfStatsCollected = true;+ return {+ // Network+ // @ts-ignore+ dns: perf.domainLookupEnd - perf.domainLookupStart,+ // @ts-ignore+ tls: perf.secureConnectionStart ? perf.requestStart - perf.secureConnectionStart : 0,+ // @ts-ignore+ conn: perf.secureConnectionStart ? perf.secureConnectionStart - perf.connectStart : perf.connectEnd - perf.connectStart,+ // @ts-ignore+ response: perf.responseEnd - perf.responseStart,+ // Frontend+ // @ts-ignore+ render: perf.domComplete - perf.domContentLoadedEventEnd,+ // @ts-ignore+ dom_load: perf.domContentLoadedEventEnd - perf.responseEnd,+ // @ts-ignore+ page_load: perf.loadEventStart,+ // Backend+ // @ts-ignore+ ttfb: perf.responseStart - perf.requestStart,+ };+ };+ Lib.prototype.heartbeat = function () {+ var _a;+ if (!((_a = this.pageViewsOptions) === null || _a === void 0 ? void 0 : _a.heartbeatOnBackground) && document.visibilityState === 'hidden') {+ return;+ }+ var data = {+ pid: this.projectID,+ };+ this.sendRequest('hb', data);+ };+ Lib.prototype.checkIgnore = function (path) {+ var _a;+ var ignore = (_a = this.pageViewsOptions) === null || _a === void 0 ? void 0 : _a.ignore;+ if (Array.isArray(ignore)) {+ for (var i = 0; i < ignore.length; ++i) {+ if (ignore[i] === path)+ return true;+ // @ts-ignore+ if (ignore[i] instanceof RegExp && ignore[i].test(path))+ return true;+ }+ }+ return false;+ };+ // Tracking path changes. If path changes -> calling this.trackPage method+ Lib.prototype.trackPathChange = function () {+ if (!this.pageData)+ return;+ var newPath = getPath();+ var path = this.pageData.path;+ if (path !== newPath) {+ this.trackPage(newPath, false);+ }+ };+ Lib.prototype.trackPage = function (pg, unique) {+ if (unique === void 0) { unique = false; }+ if (!this.pageData)+ return;+ this.pageData.path = pg;+ if (this.checkIgnore(pg))+ return;+ this.activePage = pg;+ var perf = this.getPerformanceStats();+ var data = {+ pid: this.projectID,+ lc: getLocale(),+ tz: getTimezone(),+ ref: getReferrer(),+ so: getUTMSource(),+ me: getUTMMedium(),+ ca: getUTMCampaign(),+ unique: unique,+ pg: pg,+ perf: perf,+ };+ this.sendRequest('', data);+ };+ Lib.prototype.debug = function (message) {+ var _a;+ if ((_a = this.options) === null || _a === void 0 ? void 0 : _a.debug) {+ console.log('[Swetrix]', message);+ }+ };+ Lib.prototype.canTrack = function () {+ var _a, _b, _c, _d;+ if ((_a = this.options) === null || _a === void 0 ? void 0 : _a.disabled) {+ this.debug('Tracking disabled: the \'disabled\' setting is set to true.');+ return false;+ }+ if (!isInBrowser()) {+ this.debug('Tracking disabled: script does not run in browser environment.');+ return false;+ }+ if (((_b = this.options) === null || _b === void 0 ? void 0 : _b.respectDNT) && ((_c = window.navigator) === null || _c === void 0 ? void 0 : _c.doNotTrack) === '1') {+ this.debug('Tracking disabled: respecting user\'s \'Do Not Track\' preference.');+ return false;+ }+ if (!((_d = this.options) === null || _d === void 0 ? void 0 : _d.debug) && isLocalhost()) {+ return false;+ }+ if (isAutomated()) {+ this.debug('Tracking disabled: navigation is automated by WebDriver.');+ return false;+ }+ return true;+ };+ Lib.prototype.sendRequest = function (path, body) {+ var _a;+ var host = ((_a = this.options) === null || _a === void 0 ? void 0 : _a.apiURL) || DEFAULT_API_HOST;+ var req = new XMLHttpRequest();+ req.open('POST', "".concat(host, "/").concat(path), true);+ req.setRequestHeader('Content-Type', 'application/json');+ req.send(JSON.stringify(body));+ };+ return Lib;+ }());++ exports.LIB_INSTANCE = null;+ /**+ * Initialise the tracking library instance (other methods won't work if the library is not initialised).+ *+ * @param {string} pid The Project ID to link the instance of Swetrix.js to.+ * @param {LibOptions} options Options related to the tracking.+ * @returns {Lib} Instance of the Swetrix.js.+ */+ function init(pid, options) {+ if (!exports.LIB_INSTANCE) {+ exports.LIB_INSTANCE = new Lib(pid, options);+ }+ return exports.LIB_INSTANCE;+ }+ /**+ * With this function you are able to track any custom events you want.+ * You should never send any identifiable data (like User ID, email, session cookie, etc.) as an event name.+ * The total number of track calls and their conversion rate will be saved.+ *+ * @param {TrackEventOptions} event The options related to the custom event.+ */+ function track(event) {+ if (!exports.LIB_INSTANCE)+ return;+ exports.LIB_INSTANCE.track(event);+ }+ /**+ * With this function you are able to track any custom events you want.+ * You should never send any identifiable data (like User ID, email, session cookie, etc.) as an event name.+ * The total number of track calls and their conversion rate will be saved.+ *+ * @param {PageViewsOptions} options The options related to the custom event.+ * @returns {PageActions} The actions related to the tracking. Used to stop tracking pages.+ */+ function trackViews(options) {+ return new Promise(function (resolve) {+ if (!exports.LIB_INSTANCE) {+ resolve(defaultPageActions);+ return;+ }+ // We need to verify that document.readyState is complete for the performance stats to be collected correctly.+ if (typeof document === 'undefined' || document.readyState === 'complete') {+ resolve(exports.LIB_INSTANCE.trackPageViews(options));+ }+ else {+ window.addEventListener('load', function () {+ // @ts-ignore+ resolve(exports.LIB_INSTANCE.trackPageViews(options));+ });+ }+ });+ }++ exports.init = init;+ exports.track = track;+ exports.trackViews = trackViews;++ Object.defineProperty(exports, '__esModule', { value: true });++}));diff --git a/package.json b/package.jsonnew file mode 100644index 000000000..5ad7365ce--- /dev/null+++ b/package.json@@ -0,0 +1,51 @@+{+ "name": "@swetrix/captcha-validator",+ "version": "1.0.0",+ "description": "Swetrix CAPTCHA token validator package.",+ "main": "dist/captcha-validator.cjs.js",+ "module": "dist/captcha-validator.es5.js",+ "browser": "dist/captcha-validator.js",+ "origbrowser": "dist/captcha-validator.orig.js",+ "esnext": "dist/esnext/index.js",+ "typings": "dist/esnext/index.d.ts",+ "scripts": {+ "prebuild": "rimraf dist",+ "prepublish": "npm run build",+ "build": "rollup -c && tsc -p tsconfig.esnext.json",+ "start": "rollup -c -w",+ "tsc": "tsc -p tsconfig.esnext.json"+ },+ "keywords": [+ "swetrix",+ "analytics",+ "monitoring",+ "metrics",+ "privacy"+ ],+ "repository": {+ "type": "git",+ "url": "git+https://github.com/Swetrix/captcha-vaildator.git"+ },+ "author": "Andrii Romasiun <[email protected]>",+ "funding": "https://ko-fi.com/andriir",+ "license": "MIT",+ "bugs": {+ "url": "https://github.com/Swetrix/captcha-vaildator/issues"+ },+ "homepage": "https://docs.swetrix.com",+ "dependencies": {+ "@types/node": "^18.13.0",+ "tslib": "^2.5.0"+ },+ "devDependencies": {+ "@rollup/plugin-commonjs": "^24.0.1",+ "@rollup/plugin-node-resolve": "^15.0.1",+ "rimraf": "^4.1.2",+ "rollup": "^2.79.1",+ "rollup-plugin-node-resolve": "^5.2.0",+ "rollup-plugin-sourcemaps": "^0.6.3",+ "rollup-plugin-typescript2": "^0.34.1",+ "rollup-plugin-uglify": "^6.0.4",+ "typescript": "^4.9.5"+ }+}diff --git a/rollup.config.js b/rollup.config.jsnew file mode 100644index 000000000..be90ab705--- /dev/null+++ b/rollup.config.js@@ -0,0 +1,29 @@+import { nodeResolve } from '@rollup/plugin-node-resolve'+import commonjs from '@rollup/plugin-commonjs'+import sourceMaps from 'rollup-plugin-sourcemaps'+import typescript from 'rollup-plugin-typescript2'+import { uglify } from 'rollup-plugin-uglify'+import pkg from './package.json'++export default [+ {+ input: 'src/index.ts',+ output: [+ { file: pkg.main, format: 'cjs' },+ { file: pkg.module, format: 'es' },+ { file: pkg.origbrowser, format: 'umd', name: 'captcha-validator' },+ ],+ plugins: [+ typescript(), nodeResolve(), commonjs(), sourceMaps(),+ ]+ },+ {+ input: 'src/index.ts',+ output: [+ { file: pkg.browser, format: 'umd', name: 'captcha-validator' },+ ],+ plugins: [+ typescript(), nodeResolve(), commonjs(), uglify(),+ ]+ }+]diff --git a/src/index.ts b/src/index.tsnew file mode 100644index 000000000..9f6235fd0--- /dev/null+++ b/src/index.ts@@ -0,0 +1,34 @@+import { makeAPIRequest, ENDPOINTS } from './utils'++/**+ * Function to validate the CAPTCHA token.+ *+ * @param {string} token The CAPTCHA token.+ * @param {string} secret The secret API key.+ * @param {number} timestamp The timestamp of the CAPTCHA pass.+ * @param {string | null} hash The hash of the CAPTCHA pass.+ * @param {string | null} apiURL The API URL to use (default: https://api.swetrix.com/captcha).+ * @returns {Promise<[boolean, object | null]>} The result of the validation.+ */+export async function validateToken(token: string, secret: string, timestamp: number, hash?: string, apiURL?: string): Promise<[boolean, object | string]> {+ let res++ try {+ res = await makeAPIRequest(ENDPOINTS.VALIDATE, 'POST', {+ token,+ secret,+ timestamp,+ hash,+ }, apiURL)+ } catch (e: any) {+ return [false, e]+ }++ const { success, data } = res++ if (!success) {+ return [false, 'CAPTCHA validation failed']+ }++ return [true, data]+}diff --git a/src/utils.ts b/src/utils.tsnew file mode 100644index 000000000..4d88ea713--- /dev/null+++ b/src/utils.ts@@ -0,0 +1,23 @@+const DEFAULT_API_HOST = 'https://api.swetrix.com/captcha'++export const ENDPOINTS = {+ VALIDATE: '/validate',+}++export const makeAPIRequest = async (path: string, method: string, body: object, apiURL?: string): Promise<any> => {+ let res++ try {+ res = await fetch(`${apiURL || DEFAULT_API_HOST}${path}`, {+ method,+ headers: {+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify(body),+ })+ } catch (e) {+ throw `Unable to make API request, error: ${e}`+ }++ return await res.json()+}diff --git a/tsconfig.esnext.json b/tsconfig.esnext.jsonnew file mode 100644index 000000000..901fb91ab--- /dev/null+++ b/tsconfig.esnext.json@@ -0,0 +1,17 @@+{+ "compilerOptions": {+ "moduleResolution": "node",+ "target": "es2020",+ "module": "es2015",+ "lib": ["dom"],+ "strict": true,+ "sourceMap": true,+ "declaration": true,+ "allowSyntheticDefaultImports": true,+ "experimentalDecorators": true,+ "emitDecoratorMetadata": true,+ "outDir": "dist/esnext",+ "typeRoots": ["node_modules/@types"]+ },+ "include": ["src"]+}diff --git a/tsconfig.json b/tsconfig.jsonnew file mode 100644index 000000000..3fe10f8db--- /dev/null+++ b/tsconfig.json@@ -0,0 +1,17 @@+{+ "compilerOptions": {+ "moduleResolution": "node",+ "target": "es5",+ "module": "es2015",+ "lib": ["es2015", "es2016", "es2017", "dom"],+ "strict": true,+ "allowSyntheticDefaultImports": true,+ "experimentalDecorators": true,+ "emitDecoratorMetadata": true,+ "sourceMap": true,+ "declaration": false,+ "outDir": "dist/lib",+ "typeRoots": ["node_modules/@types"]+ },+ "include": ["src"]+}