Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Umami tags and revenue tracking #124

Merged
merged 5 commits into from
Nov 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "nuxt-umami",
"type": "module",
"version": "3.0.2",
"packageManager": "pnpm@9.14.2",
"packageManager": "pnpm@9.14.4",
"description": "Integrate Umami Analytics into Nuxt",
"author": "Moses Laurence <me@ijkml.dev>",
"license": "MIT",
Expand Down Expand Up @@ -42,10 +42,10 @@
"request-ip": "^3.3.0"
},
"devDependencies": {
"@antfu/eslint-config": "^3.9.2",
"@antfu/eslint-config": "^3.11.2",
"@nuxt/module-builder": "^0.8.4",
"@nuxt/schema": "^3.14.1592",
"@types/node": "^22.9.3",
"@types/node": "^22.10.1",
"@types/request-ip": "^0.0.41",
"bumpp": "^9.8.1",
"eslint": "^9.15.0",
Expand Down
1 change: 1 addition & 0 deletions playground/nuxt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export default defineNuxtConfig({
excludeQueryParams: false,
trailingSlash: 'always',
proxy: 'cloak',
tag: 'gondor',
},

appConfig: {
Expand Down
296 changes: 175 additions & 121 deletions pnpm-lock.yaml

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ export default defineNuxtModule<ModuleOptions>({

const envHost = ENV.NUXT_UMAMI_HOST || ENV.NUXT_PUBLIC_UMAMI_HOST;
const envId = ENV.NUXT_UMAMI_ID || ENV.NUXT_PUBLIC_UMAMI_ID;
const envTag = ENV.NUXT_UMAMI_TAG || ENV.NUXT_PUBLIC_UMAMI_TAG;

const {
enabled,
Expand All @@ -52,6 +53,7 @@ export default defineNuxtModule<ModuleOptions>({
...options,
...(isValidString(envId) && { id: envId }),
...(isValidString(envHost) && { host: envHost }),
...(isValidString(envTag) && { tag: envTag }),
});

const endpoint = host ? new URL(host).origin + (customEndpoint || '/api/send') : '';
Expand Down
42 changes: 41 additions & 1 deletion src/runtime/composables.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type {
CurrencyCode,
EventData,
EventPayload,
FetchResult,
Expand Down Expand Up @@ -51,10 +52,13 @@ function getStaticPayload(): StaticPayload {
navigator: { language },
} = window;

const tag = window.localStorage.getItem('umami.tag') || config.tag;

staticPayload = {
hostname,
language,
screen: `${width}x${height}`,
...(tag ? { tag } : null),
};

return staticPayload;
Expand Down Expand Up @@ -180,4 +184,40 @@ function umIdentify(sessionData?: EventData): FetchResult {
});
}

export { umIdentify, umTrackEvent, umTrackView };
/**
* Tracks financial performance
* @see [Umami Docs](https://umami.is/docs/reports/report-revenue)
*
* @param eventName [revenue] event name
* @param revenue revenue / amount
* @param currency currency code (defaults to USD)
* ([ISO 4217](https://en.wikipedia.org/wiki/ISO_4217#List_of_ISO_4217_currency_codes))
*/
function umTrackRevenue(
eventName: string,
revenue: number,
currency: CurrencyCode = 'USD',
): FetchResult {
const $rev = typeof revenue === 'number' ? revenue : Number(revenue);

if (Number.isNaN($rev) || !Number.isFinite(revenue)) {
// if you ever run into troubles with isFinite (or not),
// please buy me a coffee ;) bmc.link/ijkml
logger('revenue', revenue);
return earlyPromise(false);
}

let $cur: string | null = null;

if (typeof currency === 'string' && /^[A-Z]{3}$/i.test(currency.trim()))
$cur = currency.trim();
else
logger('currency', `Got: ${currency}`);

return umTrackEvent(eventName, {
revenue: $rev,
...($cur ? { currency: $cur } : null),
});
}

export { umIdentify, umTrackEvent, umTrackRevenue, umTrackView };
7 changes: 5 additions & 2 deletions src/runtime/logger.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import type { PreflightResult } from '../types';

type PreflightErrId = Exclude<PreflightResult, 'ssr' | true>
| 'collect' | 'directive' | 'event-name' | 'endpoint' | 'id' | 'enabled';
| 'collect' | 'directive' | 'event-name' | 'endpoint' | 'id'
| 'enabled' | 'currency' | 'revenue';
type LogLevel = 'info' | 'warn' | 'error';
interface ErrorObj {
level: LogLevel;
Expand All @@ -16,8 +17,10 @@ const warnings: Record<PreflightErrId, ErrorObj> = {
'localhost': { level: 'info', text: 'Tracking disabled on localhost' },
'local-storage': { level: 'info', text: 'Tracking disabled via local-storage' },
'collect': { level: 'error', text: 'Uhm... Something went wrong and I have no clue.' },
'directive': { level: 'error', text: 'Invalid v-umami directive value. Expected string or object with {key:value} pairs. See https://github.com/ijkml/nuxt-umami#available-methods' },
'directive': { level: 'error', text: 'Invalid v-umami directive value. Expected string or object with {key:value} pairs. See https://umami.nuxt.dev/api/usage#directive' },
'event-name': { level: 'warn', text: 'An Umami track event was fired without a name. `#unknown-event` will be used as event name.' },
'currency': { level: 'warn', text: 'Invalid currency passed. Expected ISO 4217 format. See https://en.wikipedia.org/wiki/ISO_4217#List_of_ISO_4217_currency_codes' },
'revenue': { level: 'error', text: 'Revenue is not a number. Expected number, got: ' },
};

function logger(id: PreflightErrId, raw?: unknown) {
Expand Down
9 changes: 9 additions & 0 deletions src/runtime/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ function normalizeConfig(options: ModuleOptions = {}): NormalizedModuleOptions {
logErrors = false,
enabled = true,
trailingSlash = 'any',
tag = undefined,
} = options;

return {
Expand Down Expand Up @@ -72,6 +73,7 @@ function normalizeConfig(options: ModuleOptions = {}): NormalizedModuleOptions {
}
return 'any';
})(),
tag: isValidString(tag) ? tag.trim() : null,
ignoreLocalhost: ignoreLocalhost === true,
autoTrack: autoTrack !== false,
useDirective: useDirective === true,
Expand Down Expand Up @@ -123,6 +125,7 @@ const _payloadProps: Record<keyof Payload, PropertyValidator> = {
url: 'nonempty',
referrer: 'string',
title: 'string',
tag: 'skip', // optional property
name: 'skip', // optional, 'nonempty' in EventPayload
data: 'skip', // optional, 'data' in EventPayload & IdentifyPayload
} as const;
Expand Down Expand Up @@ -159,6 +162,12 @@ function isValidPayload(obj: object): obj is Payload {
validators.data = 'data';
}

// optional property is present, update validators
if (objKeys.includes('tag')) {
validatorKeys.push('tag');
validators.tag = 'string';
}

// check: all keys are present, no more, no less
if (
objKeys.length !== validatorKeys.length
Expand Down
21 changes: 19 additions & 2 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ type ModuleOptions = Partial<{
*
* @required true
* @example 'https://ijkml.xyz/'
* @see [How to find?](https://umami.nuxt.dev/api/configuration#finding-config-options).
*/
host: string;
/**
Expand Down Expand Up @@ -46,9 +47,15 @@ type ModuleOptions = Partial<{
* Self-hosted Umami lets you set a COLLECT_API_ENDPOINT, which is:
* - `/api/collect` by default in Umami v1
* - `/api/send` by default in Umami v2.
* See Umami [Docs](https://umami.is/docs/environment-variables).
* See [Umami Docs](https://umami.is/docs/environment-variables).
*/
customEndpoint: string | null;
/**
* Use Umami tags for A/B testing or to group events.
*
* See [Documentation](https://umami.nuxt.dev/api/configuration#umami-tag).
*/
tag: string | null;
/**
* Exclude query/search params from tracked urls
*
Expand All @@ -72,7 +79,9 @@ type ModuleOptions = Partial<{
*/
logErrors: boolean;
/**
* API proxy mode (see docs)
* API proxy mode
*
* @see [Documentation](https://umami.nuxt.dev/api/configuration#proxy-mode).
*
* @default false
*/
Expand Down Expand Up @@ -116,6 +125,7 @@ interface StaticPayload {
screen: string;
language: string;
hostname: string;
tag?: string;
}

interface ViewPayload extends StaticPayload {
Expand Down Expand Up @@ -143,8 +153,15 @@ type FetchResult = Promise<{ ok: boolean }>;
type FetchFn = (load: ServerPayload) => FetchResult;
type BuildPathUrlFn = () => string;

type _Letter = `${'A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G' | 'H'
| 'I' | 'J' | 'K' | 'M' | 'L' | 'N' | 'O' | 'P' | 'Q' | 'R' | 'S'
| 'T' | 'U' | 'V' | 'W' | 'X' | 'Y' | 'Z'}`;

type CurrencyCode = Uppercase<`${_Letter}${_Letter}${_Letter}`>;

export type {
BuildPathUrlFn,
CurrencyCode,
EventData,
EventPayload,
FetchFn,
Expand Down