vercel analytics script on both pages; disable project SSO protection (was 404-ing visitors)

This commit is contained in:
E committed 2026-09-30 15:08:10 -04:00
1 parent cc6a660729
commit 632d053de9
68 files changed
+5662

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2026 Vercel, Inc.
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.
+36
View File
@@ -0,0 +1,36 @@
![Analytics](https://github.com/vercel/analytics/blob/main/.github/banner.png)
<div align="center"><strong>Vercel Web Analytics</strong></div>
<div align="center">Privacy-friendly, real-time traffic insights</div>
<br />
<div align="center">
<a href="https://vercel.com/analytics">Website</a>
<span> · </span>
<a href="https://vercel.com/docs/concepts/analytics/package">Documentation</a>
<span> · </span>
<a href="https://twitter.com/vercel">Twitter</a>
</div>
## Overview
`@vercel/analytics` allows you to track page views and custom events in your Next.js app or any other website that is deployed to Vercel.
All page views are automatically tracked in your app.
This package does **not** track data in development mode.
## Quickstart
1. Enable Vercel Web Analytics for a project in the [Vercel Dashboard](https://vercel.com/dashboard).
2. Add the `@vercel/analytics` package to your project
3. Inject the Analytics script to your app
- If you are using **Next.js** or **React**, you can use the `<Analytics />` component to inject the script into your app.
- To add the tracking script for other frameworks, use the `inject` function.
- If you want to use Vercel Web Analytics on a static site without npm, follow the instructions in the [documentation](https://vercel.com/docs/analytics/quickstart).
4. Deploy your app to Vercel and see data flowing in.
## Documentation
Find more details about this package in our [documentation](https://vercel.com/docs/analytics/quickstart).
+7
View File
@@ -0,0 +1,7 @@
export type {
AnalyticsProps,
BeforeSend,
BeforeSendEvent,
// @ts-expect-error this filed is copied to dist, so it's ok to reference the generated index.d.ts
} from '../index.d.ts';
export { default } from './index.astro';
+69
View File
@@ -0,0 +1,69 @@
---
// Since this file will not be bundled by Tsup, it is referencing bundled files relative to dist/astro/
import type { AnalyticsProps } from '../index.d.ts';
type Props = Omit<AnalyticsProps, 'framework' | 'beforeSend'>;
const propsStr = JSON.stringify(Astro.props);
const paramsStr = JSON.stringify(Astro.params);
---
<vercel-analytics
data-props={propsStr}
data-params={paramsStr}
data-pathname={Astro.url.pathname}></vercel-analytics>
<script>
import { inject, pageview, computeRoute } from '../index.mjs';
// !! important !!
// do not access env variables using import.meta.env[varname]
// some bundles won't replace the value at build time.
function getBasePath(): string | undefined {
try {
return import.meta.env.PUBLIC_VERCEL_OBSERVABILITY_BASEPATH as
| string
| undefined;
} catch {
// do nothing
}
}
function getConfigString(): string | undefined {
// !! important !!
// do not access env variables using import.meta.env[varname]
// some bundles won't replace the value at build time.
try {
return import.meta.env.PUBLIC_VERCEL_OBSERVABILITY_CLIENT_CONFIG as
| string
| undefined;
} catch {
// do nothing
}
}
customElements.define(
'vercel-analytics',
class VercelAnalytics extends HTMLElement {
constructor() {
super();
try {
const props = JSON.parse(this.dataset.props ?? '{}');
const params = JSON.parse(this.dataset.params ?? '{}');
inject({
...props,
disableAutoTrack: true,
framework: 'astro',
basePath: getBasePath(),
beforeSend: window.webAnalyticsBeforeSend,
}, getConfigString());
const path = this.dataset.pathname;
pageview({ route: computeRoute(path ?? '', params), path });
} catch (err) {
throw new Error(`Failed to parse WebAnalytics properties: ${err}`);
}
}
},
);
</script>
+78
View File
@@ -0,0 +1,78 @@
interface PageViewEvent {
type: 'pageview';
url: string;
}
interface CustomEvent {
type: 'event';
url: string;
}
type BeforeSendEvent = PageViewEvent | CustomEvent;
type Mode = 'auto' | 'development' | 'production';
type AllowedPropertyValues = string | number | boolean | null | undefined;
type BeforeSend = (event: BeforeSendEvent) => BeforeSendEvent | null;
interface AnalyticsProps {
beforeSend?: BeforeSend;
debug?: boolean;
mode?: Mode;
scriptSrc?: string;
dsn?: string;
eventEndpoint?: string;
viewEndpoint?: string;
sessionEndpoint?: string;
endpoint?: string;
}
type InjectProps = AnalyticsProps & {
framework?: string;
disableAutoTrack?: boolean;
basePath?: string;
};
declare global {
interface Window {
va?: (event: 'beforeSend' | 'event' | 'pageview', properties?: unknown) => void;
vaq?: [string, unknown?][];
vai?: boolean;
vam?: Mode;
/** used by Astro component only */
webAnalyticsBeforeSend?: BeforeSend;
}
}
type PlainFlags = Record<string, unknown>;
type FlagsDataInput = (string | PlainFlags)[] | PlainFlags;
declare function computeRoute(pathname: string | null, pathParams: Record<string, string | string[]> | null): string | null;
/**
* Injects the Vercel Web Analytics script into the page head and starts tracking page views. Read more in our [documentation](https://vercel.com/docs/concepts/analytics/package).
* @param props - Analytics options.
* @param [props.mode] - The mode to use for the analytics script. Defaults to `auto`.
* - `auto` - Automatically detect the environment. Uses `production` if the environment cannot be determined.
* - `production` - Always use the production script. (Sends events to the server)
* - `development` - Always use the development script. (Logs events to the console)
* @param [props.debug] - Whether to enable debug logging in development. Defaults to `true`.
* @param [props.beforeSend] - A middleware function to modify events before they are sent. Should return the event object or `null` to cancel the event.
* @param [props.dsn] - The DSN of the project to send events to. Only required when self-hosting.
* @param [props.disableAutoTrack] - Whether the injected script should track page views from pushState events. Disable if route is updated after pushState, a manually call page pageview().
* @param [confString] - an optional JSON string (InjectProps) containing the default configuration. Explicit props will take over any provided default.
*/
declare function inject(props?: InjectProps, confString?: string): void;
/**
* Tracks a custom event. Please refer to the [documentation](https://vercel.com/docs/concepts/analytics/custom-events) for more information on custom events.
* @param name - The name of the event.
* * Examples: `Purchase`, `Click Button`, or `Play Video`.
* @param [properties] - Additional properties of the event. Nested objects are not supported. Allowed values are `string`, `number`, `boolean`, and `null`.
*/
declare function track(name: string, properties?: Record<string, AllowedPropertyValues>, options?: {
flags?: FlagsDataInput;
}): void;
declare function pageview({ route, path, }: {
route?: string | null;
path?: string;
}): void;
declare const _default: {
inject: typeof inject;
track: typeof track;
computeRoute: typeof computeRoute;
};
export { type AnalyticsProps, type BeforeSend, type BeforeSendEvent, computeRoute, _default as default, inject, pageview, track };
+78
View File
@@ -0,0 +1,78 @@
interface PageViewEvent {
type: 'pageview';
url: string;
}
interface CustomEvent {
type: 'event';
url: string;
}
type BeforeSendEvent = PageViewEvent | CustomEvent;
type Mode = 'auto' | 'development' | 'production';
type AllowedPropertyValues = string | number | boolean | null | undefined;
type BeforeSend = (event: BeforeSendEvent) => BeforeSendEvent | null;
interface AnalyticsProps {
beforeSend?: BeforeSend;
debug?: boolean;
mode?: Mode;
scriptSrc?: string;
dsn?: string;
eventEndpoint?: string;
viewEndpoint?: string;
sessionEndpoint?: string;
endpoint?: string;
}
type InjectProps = AnalyticsProps & {
framework?: string;
disableAutoTrack?: boolean;
basePath?: string;
};
declare global {
interface Window {
va?: (event: 'beforeSend' | 'event' | 'pageview', properties?: unknown) => void;
vaq?: [string, unknown?][];
vai?: boolean;
vam?: Mode;
/** used by Astro component only */
webAnalyticsBeforeSend?: BeforeSend;
}
}
type PlainFlags = Record<string, unknown>;
type FlagsDataInput = (string | PlainFlags)[] | PlainFlags;
declare function computeRoute(pathname: string | null, pathParams: Record<string, string | string[]> | null): string | null;
/**
* Injects the Vercel Web Analytics script into the page head and starts tracking page views. Read more in our [documentation](https://vercel.com/docs/concepts/analytics/package).
* @param props - Analytics options.
* @param [props.mode] - The mode to use for the analytics script. Defaults to `auto`.
* - `auto` - Automatically detect the environment. Uses `production` if the environment cannot be determined.
* - `production` - Always use the production script. (Sends events to the server)
* - `development` - Always use the development script. (Logs events to the console)
* @param [props.debug] - Whether to enable debug logging in development. Defaults to `true`.
* @param [props.beforeSend] - A middleware function to modify events before they are sent. Should return the event object or `null` to cancel the event.
* @param [props.dsn] - The DSN of the project to send events to. Only required when self-hosting.
* @param [props.disableAutoTrack] - Whether the injected script should track page views from pushState events. Disable if route is updated after pushState, a manually call page pageview().
* @param [confString] - an optional JSON string (InjectProps) containing the default configuration. Explicit props will take over any provided default.
*/
declare function inject(props?: InjectProps, confString?: string): void;
/**
* Tracks a custom event. Please refer to the [documentation](https://vercel.com/docs/concepts/analytics/custom-events) for more information on custom events.
* @param name - The name of the event.
* * Examples: `Purchase`, `Click Button`, or `Play Video`.
* @param [properties] - Additional properties of the event. Nested objects are not supported. Allowed values are `string`, `number`, `boolean`, and `null`.
*/
declare function track(name: string, properties?: Record<string, AllowedPropertyValues>, options?: {
flags?: FlagsDataInput;
}): void;
declare function pageview({ route, path, }: {
route?: string | null;
path?: string;
}): void;
declare const _default: {
inject: typeof inject;
track: typeof track;
computeRoute: typeof computeRoute;
};
export { type AnalyticsProps, type BeforeSend, type BeforeSendEvent, computeRoute, _default as default, inject, pageview, track };
+271
View File
@@ -0,0 +1,271 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name2 in all)
__defProp(target, name2, { get: all[name2], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/generic.ts
var generic_exports = {};
__export(generic_exports, {
computeRoute: () => computeRoute,
default: () => generic_default,
inject: () => inject,
pageview: () => pageview,
track: () => track
});
module.exports = __toCommonJS(generic_exports);
// src/queue.ts
var initQueue = () => {
if (window.va) return;
window.va = function a(...params) {
if (!window.vaq) window.vaq = [];
window.vaq.push(params);
};
};
// package.json
var name = "@vercel/analytics";
var version = "2.0.1";
// src/utils.ts
function isBrowser() {
return typeof window !== "undefined";
}
function detectEnvironment() {
try {
const env = process.env.NODE_ENV;
if (env === "development" || env === "test") {
return "development";
}
} catch {
}
return "production";
}
function setMode(mode = "auto") {
if (mode === "auto") {
window.vam = detectEnvironment();
return;
}
window.vam = mode;
}
function getMode() {
const mode = isBrowser() ? window.vam : detectEnvironment();
return mode || "production";
}
function isProduction() {
return getMode() === "production";
}
function isDevelopment() {
return getMode() === "development";
}
function removeKey(key, { [key]: _, ...rest }) {
return rest;
}
function parseProperties(properties, options) {
if (!properties) return void 0;
let props = properties;
const errorProperties = [];
for (const [key, value] of Object.entries(properties)) {
if (typeof value === "object" && value !== null) {
if (options.strip) {
props = removeKey(key, props);
} else {
errorProperties.push(key);
}
}
}
if (errorProperties.length > 0 && !options.strip) {
throw Error(
`The following properties are not valid: ${errorProperties.join(
", "
)}. Only strings, numbers, booleans, and null are allowed.`
);
}
return props;
}
function computeRoute(pathname, pathParams) {
if (!pathname || !pathParams) {
return pathname;
}
let result = pathname;
try {
const entries = Object.entries(pathParams);
for (const [key, value] of entries) {
if (!Array.isArray(value)) {
const matcher = turnValueToRegExp(value);
if (matcher.test(result)) {
result = result.replace(matcher, `/[${key}]`);
}
}
}
for (const [key, value] of entries) {
if (Array.isArray(value)) {
const matcher = turnValueToRegExp(value.join("/"));
if (matcher.test(result)) {
result = result.replace(matcher, `/[...${key}]`);
}
}
}
return result;
} catch {
return pathname;
}
}
function turnValueToRegExp(value) {
return new RegExp(`/${escapeRegExp(value)}(?=[/?#]|$)`);
}
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function getScriptSrc(props) {
if (props.scriptSrc) {
return makeAbsolute(props.scriptSrc);
}
if (isDevelopment()) {
return "https://va.vercel-scripts.com/v1/script.debug.js";
}
if (props.basePath) {
return makeAbsolute(`${props.basePath}/insights/script.js`);
}
return "/_vercel/insights/script.js";
}
function loadProps(explicitProps, confString) {
var _a;
let props = explicitProps;
if (confString) {
try {
props = {
...(_a = JSON.parse(confString)) == null ? void 0 : _a.analytics,
...explicitProps
};
} catch {
}
}
setMode(props.mode);
const dataset = {
sdkn: name + (props.framework ? `/${props.framework}` : ""),
sdkv: version
};
if (props.disableAutoTrack) {
dataset.disableAutoTrack = "1";
}
if (props.viewEndpoint) {
dataset.viewEndpoint = makeAbsolute(props.viewEndpoint);
}
if (props.eventEndpoint) {
dataset.eventEndpoint = makeAbsolute(props.eventEndpoint);
}
if (props.sessionEndpoint) {
dataset.sessionEndpoint = makeAbsolute(props.sessionEndpoint);
}
if (isDevelopment() && props.debug === false) {
dataset.debug = "false";
}
if (props.dsn) {
dataset.dsn = props.dsn;
}
if (props.endpoint) {
dataset.endpoint = props.endpoint;
} else if (props.basePath) {
dataset.endpoint = makeAbsolute(`${props.basePath}/insights`);
}
return {
beforeSend: props.beforeSend,
src: getScriptSrc(props),
dataset
};
}
function makeAbsolute(url) {
return url.startsWith("http://") || url.startsWith("https://") || url.startsWith("/") ? url : `/${url}`;
}
// src/generic.ts
function inject(props = {
debug: true
}, confString) {
var _a;
if (!isBrowser()) return;
const { beforeSend, src, dataset } = loadProps(props, confString);
initQueue();
if (beforeSend) {
(_a = window.va) == null ? void 0 : _a.call(window, "beforeSend", beforeSend);
}
if (document.head.querySelector(`script[src*="${src}"]`)) return;
const script = document.createElement("script");
script.src = src;
for (const [key, value] of Object.entries(dataset)) {
script.dataset[key] = value;
}
script.defer = true;
script.onerror = () => {
const errorMessage = isDevelopment() ? "Please check if any ad blockers are enabled and try again." : "Be sure to enable Web Analytics for your project and deploy again. See https://vercel.com/docs/analytics/quickstart for more information.";
console.log(
`[Vercel Web Analytics] Failed to load script from ${src}. ${errorMessage}`
);
};
document.head.appendChild(script);
}
function track(name2, properties, options) {
var _a, _b;
if (!isBrowser()) {
const msg = "[Vercel Web Analytics] Please import `track` from `@vercel/analytics/server` when using this function in a server environment";
if (isProduction()) {
console.warn(msg);
} else {
throw new Error(msg);
}
return;
}
if (!properties) {
(_a = window.va) == null ? void 0 : _a.call(window, "event", { name: name2, options });
return;
}
try {
const props = parseProperties(properties, {
strip: isProduction()
});
(_b = window.va) == null ? void 0 : _b.call(window, "event", {
name: name2,
data: props,
options
});
} catch (err) {
if (err instanceof Error && isDevelopment()) {
console.error(err);
}
}
}
function pageview({
route,
path
}) {
var _a;
(_a = window.va) == null ? void 0 : _a.call(window, "pageview", { route, path });
}
var generic_default = {
inject,
track,
computeRoute
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
computeRoute,
inject,
pageview,
track
});
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../src/generic.ts","../src/queue.ts","../package.json","../src/utils.ts"],"sourcesContent":["import { initQueue } from './queue';\nimport type {\n AllowedPropertyValues,\n AnalyticsProps,\n BeforeSend,\n BeforeSendEvent,\n FlagsDataInput,\n InjectProps,\n} from './types';\nimport {\n computeRoute,\n isBrowser,\n isDevelopment,\n isProduction,\n loadProps,\n parseProperties,\n} from './utils';\n\n/**\n * Injects the Vercel Web Analytics script into the page head and starts tracking page views. Read more in our [documentation](https://vercel.com/docs/concepts/analytics/package).\n * @param props - Analytics options.\n * @param [props.mode] - The mode to use for the analytics script. Defaults to `auto`.\n * - `auto` - Automatically detect the environment. Uses `production` if the environment cannot be determined.\n * - `production` - Always use the production script. (Sends events to the server)\n * - `development` - Always use the development script. (Logs events to the console)\n * @param [props.debug] - Whether to enable debug logging in development. Defaults to `true`.\n * @param [props.beforeSend] - A middleware function to modify events before they are sent. Should return the event object or `null` to cancel the event.\n * @param [props.dsn] - The DSN of the project to send events to. Only required when self-hosting.\n * @param [props.disableAutoTrack] - Whether the injected script should track page views from pushState events. Disable if route is updated after pushState, a manually call page pageview().\n * @param [confString] - an optional JSON string (InjectProps) containing the default configuration. Explicit props will take over any provided default.\n */\nfunction inject(\n props: InjectProps = {\n debug: true,\n },\n confString?: string,\n): void {\n if (!isBrowser()) return;\n\n const { beforeSend, src, dataset } = loadProps(props, confString);\n initQueue();\n\n if (beforeSend) {\n window.va?.('beforeSend', beforeSend);\n }\n if (document.head.querySelector(`script[src*=\"${src}\"]`)) return;\n\n const script = document.createElement('script');\n script.src = src;\n for (const [key, value] of Object.entries(dataset)) {\n script.dataset[key] = value;\n }\n script.defer = true;\n script.onerror = (): void => {\n const errorMessage = isDevelopment()\n ? 'Please check if any ad blockers are enabled and try again.'\n : 'Be sure to enable Web Analytics for your project and deploy again. See https://vercel.com/docs/analytics/quickstart for more information.';\n\n console.log(\n `[Vercel Web Analytics] Failed to load script from ${src}. ${errorMessage}`,\n );\n };\n\n document.head.appendChild(script);\n}\n\n/**\n * Tracks a custom event. Please refer to the [documentation](https://vercel.com/docs/concepts/analytics/custom-events) for more information on custom events.\n * @param name - The name of the event.\n * * Examples: `Purchase`, `Click Button`, or `Play Video`.\n * @param [properties] - Additional properties of the event. Nested objects are not supported. Allowed values are `string`, `number`, `boolean`, and `null`.\n */\nfunction track(\n name: string,\n properties?: Record<string, AllowedPropertyValues>,\n options?: {\n flags?: FlagsDataInput;\n },\n): void {\n if (!isBrowser()) {\n const msg =\n '[Vercel Web Analytics] Please import `track` from `@vercel/analytics/server` when using this function in a server environment';\n\n if (isProduction()) {\n console.warn(msg);\n } else {\n throw new Error(msg);\n }\n\n return;\n }\n\n if (!properties) {\n window.va?.('event', { name, options });\n return;\n }\n\n try {\n const props = parseProperties(properties, {\n strip: isProduction(),\n });\n\n window.va?.('event', {\n name,\n data: props,\n options,\n });\n } catch (err) {\n if (err instanceof Error && isDevelopment()) {\n console.error(err);\n }\n }\n}\n\nfunction pageview({\n route,\n path,\n}: {\n route?: string | null;\n path?: string;\n}): void {\n window.va?.('pageview', { route, path });\n}\n\nexport { inject, track, pageview, computeRoute };\nexport type { AnalyticsProps, BeforeSend, BeforeSendEvent };\n\nexport default {\n inject,\n track,\n computeRoute,\n};\n","export const initQueue = (): void => {\n // initialize va until script is loaded\n if (window.va) return;\n\n window.va = function a(...params): void {\n if (!window.vaq) window.vaq = [];\n window.vaq.push(params);\n };\n};\n","{\n \"name\": \"@vercel/analytics\",\n \"version\": \"2.0.1\",\n \"description\": \"Gain real-time traffic insights with Vercel Web Analytics\",\n \"keywords\": [\n \"analytics\",\n \"vercel\"\n ],\n \"repository\": {\n \"url\": \"github:vercel/analytics\",\n \"directory\": \"packages/web\"\n },\n \"license\": \"MIT\",\n \"exports\": {\n \"./package.json\": \"./package.json\",\n Line truncated
+241
View File
@@ -0,0 +1,241 @@
// src/queue.ts
var initQueue = () => {
if (window.va) return;
window.va = function a(...params) {
if (!window.vaq) window.vaq = [];
window.vaq.push(params);
};
};
// package.json
var name = "@vercel/analytics";
var version = "2.0.1";
// src/utils.ts
function isBrowser() {
return typeof window !== "undefined";
}
function detectEnvironment() {
try {
const env = process.env.NODE_ENV;
if (env === "development" || env === "test") {
return "development";
}
} catch {
}
return "production";
}
function setMode(mode = "auto") {
if (mode === "auto") {
window.vam = detectEnvironment();
return;
}
window.vam = mode;
}
function getMode() {
const mode = isBrowser() ? window.vam : detectEnvironment();
return mode || "production";
}
function isProduction() {
return getMode() === "production";
}
function isDevelopment() {
return getMode() === "development";
}
function removeKey(key, { [key]: _, ...rest }) {
return rest;
}
function parseProperties(properties, options) {
if (!properties) return void 0;
let props = properties;
const errorProperties = [];
for (const [key, value] of Object.entries(properties)) {
if (typeof value === "object" && value !== null) {
if (options.strip) {
props = removeKey(key, props);
} else {
errorProperties.push(key);
}
}
}
if (errorProperties.length > 0 && !options.strip) {
throw Error(
`The following properties are not valid: ${errorProperties.join(
", "
)}. Only strings, numbers, booleans, and null are allowed.`
);
}
return props;
}
function computeRoute(pathname, pathParams) {
if (!pathname || !pathParams) {
return pathname;
}
let result = pathname;
try {
const entries = Object.entries(pathParams);
for (const [key, value] of entries) {
if (!Array.isArray(value)) {
const matcher = turnValueToRegExp(value);
if (matcher.test(result)) {
result = result.replace(matcher, `/[${key}]`);
}
}
}
for (const [key, value] of entries) {
if (Array.isArray(value)) {
const matcher = turnValueToRegExp(value.join("/"));
if (matcher.test(result)) {
result = result.replace(matcher, `/[...${key}]`);
}
}
}
return result;
} catch {
return pathname;
}
}
function turnValueToRegExp(value) {
return new RegExp(`/${escapeRegExp(value)}(?=[/?#]|$)`);
}
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function getScriptSrc(props) {
if (props.scriptSrc) {
return makeAbsolute(props.scriptSrc);
}
if (isDevelopment()) {
return "https://va.vercel-scripts.com/v1/script.debug.js";
}
if (props.basePath) {
return makeAbsolute(`${props.basePath}/insights/script.js`);
}
return "/_vercel/insights/script.js";
}
function loadProps(explicitProps, confString) {
var _a;
let props = explicitProps;
if (confString) {
try {
props = {
...(_a = JSON.parse(confString)) == null ? void 0 : _a.analytics,
...explicitProps
};
} catch {
}
}
setMode(props.mode);
const dataset = {
sdkn: name + (props.framework ? `/${props.framework}` : ""),
sdkv: version
};
if (props.disableAutoTrack) {
dataset.disableAutoTrack = "1";
}
if (props.viewEndpoint) {
dataset.viewEndpoint = makeAbsolute(props.viewEndpoint);
}
if (props.eventEndpoint) {
dataset.eventEndpoint = makeAbsolute(props.eventEndpoint);
}
if (props.sessionEndpoint) {
dataset.sessionEndpoint = makeAbsolute(props.sessionEndpoint);
}
if (isDevelopment() && props.debug === false) {
dataset.debug = "false";
}
if (props.dsn) {
dataset.dsn = props.dsn;
}
if (props.endpoint) {
dataset.endpoint = props.endpoint;
} else if (props.basePath) {
dataset.endpoint = makeAbsolute(`${props.basePath}/insights`);
}
return {
beforeSend: props.beforeSend,
src: getScriptSrc(props),
dataset
};
}
function makeAbsolute(url) {
return url.startsWith("http://") || url.startsWith("https://") || url.startsWith("/") ? url : `/${url}`;
}
// src/generic.ts
function inject(props = {
debug: true
}, confString) {
var _a;
if (!isBrowser()) return;
const { beforeSend, src, dataset } = loadProps(props, confString);
initQueue();
if (beforeSend) {
(_a = window.va) == null ? void 0 : _a.call(window, "beforeSend", beforeSend);
}
if (document.head.querySelector(`script[src*="${src}"]`)) return;
const script = document.createElement("script");
script.src = src;
for (const [key, value] of Object.entries(dataset)) {
script.dataset[key] = value;
}
script.defer = true;
script.onerror = () => {
const errorMessage = isDevelopment() ? "Please check if any ad blockers are enabled and try again." : "Be sure to enable Web Analytics for your project and deploy again. See https://vercel.com/docs/analytics/quickstart for more information.";
console.log(
`[Vercel Web Analytics] Failed to load script from ${src}. ${errorMessage}`
);
};
document.head.appendChild(script);
}
function track(name2, properties, options) {
var _a, _b;
if (!isBrowser()) {
const msg = "[Vercel Web Analytics] Please import `track` from `@vercel/analytics/server` when using this function in a server environment";
if (isProduction()) {
console.warn(msg);
} else {
throw new Error(msg);
}
return;
}
if (!properties) {
(_a = window.va) == null ? void 0 : _a.call(window, "event", { name: name2, options });
return;
}
try {
const props = parseProperties(properties, {
strip: isProduction()
});
(_b = window.va) == null ? void 0 : _b.call(window, "event", {
name: name2,
data: props,
options
});
} catch (err) {
if (err instanceof Error && isDevelopment()) {
console.error(err);
}
}
}
function pageview({
route,
path
}) {
var _a;
(_a = window.va) == null ? void 0 : _a.call(window, "pageview", { route, path });
}
var generic_default = {
inject,
track,
computeRoute
};
export {
computeRoute,
generic_default as default,
inject,
pageview,
track
};
//# sourceMappingURL=index.mjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../src/queue.ts","../package.json","../src/utils.ts","../src/generic.ts"],"sourcesContent":["export const initQueue = (): void => {\n // initialize va until script is loaded\n if (window.va) return;\n\n window.va = function a(...params): void {\n if (!window.vaq) window.vaq = [];\n window.vaq.push(params);\n };\n};\n","{\n \"name\": \"@vercel/analytics\",\n \"version\": \"2.0.1\",\n \"description\": \"Gain real-time traffic insights with Vercel Web Analytics\",\n \"keywords\": [\n \"analytics\",\n \"vercel\"\n ],\n \"repository\": {\n \"url\": \"github:vercel/analytics\",\n \"directory\": \"packages/web\"\n },\n \"license\": \"MIT\",\n \"exports\": {\n \"./package.json\": \"./package.json\",\n \".\": {\n \"browser\": \"./dist/index.mjs\",\n \"import\": \"./dist/index.mjs\",\n \"require\": \"./dist/index.js\"\n },\n \"./astro\": {\n \"import\": \"./dist/astro/component.ts\"\n },\n \"./next\": {\n \"browser\": \"./dist/next/index.mjs\",\n \"import\": \"./dist/next/index.mjs\",\n \"require\": \"./dist/next/index.js\"\n },\n \"./nuxt\": {\n \"import\": \"./dist/nuxt/index.mjs\",\n \"require\": \"./dist/nuxt/index.js\"\n },\n \"./nuxt/runtime\": {\n \"browser\": \"./dist/nuxt/runtime/index.mjs\",\n \"import\": \"./dist/nuxt/runtime/index.mjs\",\n \"require\": \"./dist/nuxt/runtime/index.js\"\n },\n \"./react\": {\n \"browser\": \"./dist/react/index.mjs\",\n \"import\": \"./dist/react/index.mjs\",\n \"require\": \"./dist/react/index.js\"\n },\n \"./remix\": {\n \"browser\": \"./dist/remix/index.mjs\",\n \"import\": \"./dist/remix/index.mjs\",\n \"require\": \"./dist/remix/index.js\"\n },\n \"./server\": {\n \"node\": \"./dist/server/index.mjs\",\n \"edge-light\": \"./dist/server/index.mjs\",\n \"import\": \"./dist/server/index.mjs\",\n \"require\": \"./dist/server/index.js\",\n \"default\": \"./dist/server/index.js\"\n },\n \"./sveltekit\": {\n \"svelte\": \"./dist/sveltekit/index.mjs\",\n \"types\": \"./dist/sveltekit/index.d.ts\"\n },\n \"./vue\": {\n \"browser\": \"./dist/vue/index.mjs\",\n \"import\": \"./dist/vue/index.mjs\",\n \"require\": \"./dist/vue/index.js\"\n }\n },\n \"main\": \"./dist/index.mjs\",\n \"types\": \"./dist/index.d.ts\",\n \"typesVersions\": {\n \"*\": {\n \"*\": [\n \"dist/index.d.ts\"\n ],\n \"next\": [\n \"dist/next/index.d.ts\"\n ],\n \"nuxt\": [\n \"dist/nuxt/index.d.ts\"\n ],\n \"nuxt/runtime\": [\n \"dist/nuxt/runtime/index.d.ts\"\n ],\n \"react\": [\n \"dist/react/index.d.ts\"\n ],\n \"remix\": [\n \"dist/remix/index.d.ts\"\n ],\n \"server\": [\n \"dist/server/index.d.ts\"\n ],\n \"sveltekit\": [\n \"dist/sveltekit/index.d.ts\"\n ],\n \"vue\": [\n \"dist/vue/index.d.ts\"\n ]\n }\n },\n \"scripts\": {\n \"build\": \"tsup && pnpm copy-astro\",\n \"copy-astro\": \"cp -R src/astro dist/\",\n \"dev\": \"pnpm copy-astro && tsup --watch\",\n \"test\": \"vitest\"\n },\n \"devDependencies\": {\n \"@nuxt/kit\": \"^4.2.0\",\n \"@nuxt/schema\": \"^4.2.0\",\n \"@swc/core\": \"^1.9.2\",\n \"@testing-library/jest-dom\": \"^6.9.1\",\n \"@testing-library/react\": \"^16.3.1\",\n \"@types/node\": \"^22.9.0\",\n \"@types/react\": \"^18.3.12\",\n \"server-only\": \"^0.0.1\",\n \"svelte\": \"^5.1.10\",\n \"tsup\": \"8.3.5\",\n \"vitest\": \"^4.0.16\",\n \"vue\": \"^3.5.12\",\n \"vue-router\": \"^4.4.5\"\n },\n \"peerDependencies\": {\n \"@remix-run/react\": \"^2\",\n \"@sveltejs/kit\": \"^1 || ^2\",\n \"next\": \">= 13\",\n \"nuxt\": \">= 3\",\n \"react\": \"^18 || ^19 || ^19.0.0-rc\",\n \"svelte\": \">= 4\",\n \"vue\": \"^3\",\n \"vue-router\": \"^4\"\n },\n \"peerDependenciesMeta\": {\n \"@remix-run/react\": {\n \"optional\": true\n },\n \"@sveltejs/kit\": {\n \"optional\": true\n },\n \"next\": {\n \"optional\": true\n },\n \"nuxt\": {\n \"optional\": true\n },\n \"react\": {\n \"optional\": true\n },\n \"svelte\": {\n \"optional\": true\n },\n \"vue\": {\n \"optional\": true\n },\n \"vue-router\": {\n \"optional\": true\n }\n }\n}\n","import { name as packageName, version } from '../package.json';\nimport type {\n AllowedPropertyValues,\n AnalyticsProps,\n BeforeSend,\n InjectProps,\n Mode,\n} from './types';\n\nexport function isBrowser(): boolean {\n return typeof window !== 'undefined';\n}\n\nfunction detectEnvironment(): 'development' | 'production' {\n try {\n const env = process.env.NODE_ENV;\n if (env === 'development' || env === 'test') {\n return 'development';\n }\n } catch {\n /Line truncated
+37
View File
@@ -0,0 +1,37 @@
interface PageViewEvent {
type: 'pageview';
url: string;
}
interface CustomEvent {
type: 'event';
url: string;
}
type BeforeSendEvent = PageViewEvent | CustomEvent;
type Mode = 'auto' | 'development' | 'production';
type BeforeSend = (event: BeforeSendEvent) => BeforeSendEvent | null;
interface AnalyticsProps {
beforeSend?: BeforeSend;
debug?: boolean;
mode?: Mode;
scriptSrc?: string;
dsn?: string;
eventEndpoint?: string;
viewEndpoint?: string;
sessionEndpoint?: string;
endpoint?: string;
}
declare global {
interface Window {
va?: (event: 'beforeSend' | 'event' | 'pageview', properties?: unknown) => void;
vaq?: [string, unknown?][];
vai?: boolean;
vam?: Mode;
/** used by Astro component only */
webAnalyticsBeforeSend?: BeforeSend;
}
}
type Props = Omit<AnalyticsProps, 'route' | 'disableAutoTrack'>;
declare function Analytics(props: Props): null;
export { Analytics, type AnalyticsProps, type BeforeSend, type BeforeSendEvent };
+37
View File
@@ -0,0 +1,37 @@
interface PageViewEvent {
type: 'pageview';
url: string;
}
interface CustomEvent {
type: 'event';
url: string;
}
type BeforeSendEvent = PageViewEvent | CustomEvent;
type Mode = 'auto' | 'development' | 'production';
type BeforeSend = (event: BeforeSendEvent) => BeforeSendEvent | null;
interface AnalyticsProps {
beforeSend?: BeforeSend;
debug?: boolean;
mode?: Mode;
scriptSrc?: string;
dsn?: string;
eventEndpoint?: string;
viewEndpoint?: string;
sessionEndpoint?: string;
endpoint?: string;
}
declare global {
interface Window {
va?: (event: 'beforeSend' | 'event' | 'pageview', properties?: unknown) => void;
vaq?: [string, unknown?][];
vai?: boolean;
vam?: Mode;
/** used by Astro component only */
webAnalyticsBeforeSend?: BeforeSend;
}
}
type Props = Omit<AnalyticsProps, 'route' | 'disableAutoTrack'>;
declare function Analytics(props: Props): null;
export { Analytics, type AnalyticsProps, type BeforeSend, type BeforeSendEvent };
+301
View File
@@ -0,0 +1,301 @@
"use strict";
"use client";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name2 in all)
__defProp(target, name2, { get: all[name2], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/nextjs/index.tsx
var nextjs_exports = {};
__export(nextjs_exports, {
Analytics: () => Analytics2
});
module.exports = __toCommonJS(nextjs_exports);
var import_react2 = __toESM(require("react"));
// src/react/index.tsx
var import_react = require("react");
// src/queue.ts
var initQueue = () => {
if (window.va) return;
window.va = function a(...params) {
if (!window.vaq) window.vaq = [];
window.vaq.push(params);
};
};
// package.json
var name = "@vercel/analytics";
var version = "2.0.1";
// src/utils.ts
function isBrowser() {
return typeof window !== "undefined";
}
function detectEnvironment() {
try {
const env = process.env.NODE_ENV;
if (env === "development" || env === "test") {
return "development";
}
} catch {
}
return "production";
}
function setMode(mode = "auto") {
if (mode === "auto") {
window.vam = detectEnvironment();
return;
}
window.vam = mode;
}
function getMode() {
const mode = isBrowser() ? window.vam : detectEnvironment();
return mode || "production";
}
function isDevelopment() {
return getMode() === "development";
}
function computeRoute(pathname, pathParams) {
if (!pathname || !pathParams) {
return pathname;
}
let result = pathname;
try {
const entries = Object.entries(pathParams);
for (const [key, value] of entries) {
if (!Array.isArray(value)) {
const matcher = turnValueToRegExp(value);
if (matcher.test(result)) {
result = result.replace(matcher, `/[${key}]`);
}
}
}
for (const [key, value] of entries) {
if (Array.isArray(value)) {
const matcher = turnValueToRegExp(value.join("/"));
if (matcher.test(result)) {
result = result.replace(matcher, `/[...${key}]`);
}
}
}
return result;
} catch {
return pathname;
}
}
function turnValueToRegExp(value) {
return new RegExp(`/${escapeRegExp(value)}(?=[/?#]|$)`);
}
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function getScriptSrc(props) {
if (props.scriptSrc) {
return makeAbsolute(props.scriptSrc);
}
if (isDevelopment()) {
return "https://va.vercel-scripts.com/v1/script.debug.js";
}
if (props.basePath) {
return makeAbsolute(`${props.basePath}/insights/script.js`);
}
return "/_vercel/insights/script.js";
}
function loadProps(explicitProps, confString) {
var _a;
let props = explicitProps;
if (confString) {
try {
props = {
...(_a = JSON.parse(confString)) == null ? void 0 : _a.analytics,
...explicitProps
};
} catch {
}
}
setMode(props.mode);
const dataset = {
sdkn: name + (props.framework ? `/${props.framework}` : ""),
sdkv: version
};
if (props.disableAutoTrack) {
dataset.disableAutoTrack = "1";
}
if (props.viewEndpoint) {
dataset.viewEndpoint = makeAbsolute(props.viewEndpoint);
}
if (props.eventEndpoint) {
dataset.eventEndpoint = makeAbsolute(props.eventEndpoint);
}
if (props.sessionEndpoint) {
dataset.sessionEndpoint = makeAbsolute(props.sessionEndpoint);
}
if (isDevelopment() && props.debug === false) {
dataset.debug = "false";
}
if (props.dsn) {
dataset.dsn = props.dsn;
}
if (props.endpoint) {
dataset.endpoint = props.endpoint;
} else if (props.basePath) {
dataset.endpoint = makeAbsolute(`${props.basePath}/insights`);
}
return {
beforeSend: props.beforeSend,
src: getScriptSrc(props),
dataset
};
}
function makeAbsolute(url) {
return url.startsWith("http://") || url.startsWith("https://") || url.startsWith("/") ? url : `/${url}`;
}
// src/generic.ts
function inject(props = {
debug: true
}, confString) {
var _a;
if (!isBrowser()) return;
const { beforeSend, src, dataset } = loadProps(props, confString);
initQueue();
if (beforeSend) {
(_a = window.va) == null ? void 0 : _a.call(window, "beforeSend", beforeSend);
}
if (document.head.querySelector(`script[src*="${src}"]`)) return;
const script = document.createElement("script");
script.src = src;
for (const [key, value] of Object.entries(dataset)) {
script.dataset[key] = value;
}
script.defer = true;
script.onerror = () => {
const errorMessage = isDevelopment() ? "Please check if any ad blockers are enabled and try again." : "Be sure to enable Web Analytics for your project and deploy again. See https://vercel.com/docs/analytics/quickstart for more information.";
console.log(
`[Vercel Web Analytics] Failed to load script from ${src}. ${errorMessage}`
);
};
document.head.appendChild(script);
}
function pageview({
route,
path
}) {
var _a;
(_a = window.va) == null ? void 0 : _a.call(window, "pageview", { route, path });
}
// src/react/utils.ts
function getBasePath() {
if (typeof process === "undefined" || typeof process.env === "undefined") {
return void 0;
}
return process.env.REACT_APP_VERCEL_OBSERVABILITY_BASEPATH;
}
function getConfigString() {
if (typeof process === "undefined" || typeof process.env === "undefined") {
return void 0;
}
return process.env.REACT_APP_VERCEL_OBSERVABILITY_CLIENT_CONFIG;
}
// src/react/index.tsx
function Analytics(props) {
(0, import_react.useEffect)(() => {
var _a;
if (props.beforeSend) {
(_a = window.va) == null ? void 0 : _a.call(window, "beforeSend", props.beforeSend);
}
}, [props.beforeSend]);
(0, import_react.useEffect)(() => {
inject(
{
framework: props.framework || "react",
basePath: props.basePath ?? getBasePath(),
...props.route !== void 0 && { disableAutoTrack: true },
...props
},
props.configString ?? getConfigString()
);
}, []);
(0, import_react.useEffect)(() => {
if (props.route && props.path) {
pageview({ route: props.route, path: props.path });
}
}, [props.route, props.path]);
return null;
}
// src/nextjs/utils.ts
var import_navigation = require("next/navigation.js");
var useRoute = () => {
const params = (0, import_navigation.useParams)();
const searchParams = (0, import_navigation.useSearchParams)();
const path = (0, import_navigation.usePathname)();
if (!params) {
return { route: null, path };
}
const finalParams = Object.keys(params).length ? params : Object.fromEntries(searchParams.entries());
return { route: computeRoute(path, finalParams), path };
};
function getBasePath2() {
if (typeof process === "undefined" || typeof process.env === "undefined") {
return void 0;
}
return process.env.NEXT_PUBLIC_VERCEL_OBSERVABILITY_BASEPATH;
}
function getConfigString2() {
if (typeof process === "undefined" || typeof process.env === "undefined") {
return void 0;
}
return process.env.NEXT_PUBLIC_VERCEL_OBSERVABILITY_CLIENT_CONFIG;
}
// src/nextjs/index.tsx
function AnalyticsComponent(props) {
const { route, path } = useRoute();
return /* @__PURE__ */ import_react2.default.createElement(
Analytics,
{
path,
route,
...props,
basePath: getBasePath2(),
configString: getConfigString2(),
framework: "next"
}
);
}
function Analytics2(props) {
return /* @__PURE__ */ import_react2.default.createElement(import_react2.Suspense, { fallback: null }, /* @__PURE__ */ import_react2.default.createElement(AnalyticsComponent, { ...props }));
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Analytics
});
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../src/nextjs/index.tsx","../../src/react/index.tsx","../../src/queue.ts","../../package.json","../../src/utils.ts","../../src/generic.ts","../../src/react/utils.ts","../../src/nextjs/utils.ts"],"sourcesContent":["'use client';\nimport React, { type ReactNode, Suspense } from 'react';\nimport { Analytics as AnalyticsScript } from '../react';\nimport type { AnalyticsProps, BeforeSend, BeforeSendEvent } from '../types';\nimport { getBasePath, getConfigString, useRoute } from './utils';\n\ntype Props = Omit<AnalyticsProps, 'route' | 'disableAutoTrack'>;\n\nfunction AnalyticsComponent(props: Props): ReactNode {\n const { route, path } = useRoute();\n return (\n <AnalyticsScript\n path={path}\n route={route}\n {...props}\n basePath={getBasePath()}\n configString={getConfigString()}\n framework=\"next\"\n />\n );\n}\n\nexport function Analytics(props: Props): null {\n // Because of incompatible types between ReactNode in React 19 and React 18 we return null (which is also what we render)\n return (\n <Suspense fallback={null}>\n <AnalyticsComponent {...props} />\n </Suspense>\n ) as never;\n}\n\nexport type { AnalyticsProps, BeforeSend, BeforeSendEvent };\n","'use client';\nimport { useEffect } from 'react';\nimport { inject, pageview, track } from '../generic';\nimport type { AnalyticsProps, BeforeSend, BeforeSendEvent } from '../types';\nimport { getBasePath, getConfigString } from './utils';\n\n/**\n * Injects the Vercel Web Analytics script into the page head and starts tracking page views. Read more in our [documentation](https://vercel.com/docs/concepts/analytics/package).\n * @param [props] - Analytics options.\n * @param [props.mode] - The mode to use for the analytics script. Defaults to `auto`.\n * - `auto` - Automatically detect the environment. Uses `production` if the environment cannot be determined.\n * - `production` - Always use the production script. (Sends events to the server)\n * - `development` - Always use the development script. (Logs events to the console)\n * @param [props.debug] - Whether to enable debug logging in development. Defaults to `true`.\n * @param [props.beforeSend] - A middleware function to modify events before they are sent. Should return the event object or `null` to cancel the event.\n * @example\n * ```js\n * import { Analytics } from '@vercel/analytics/react';\n *\n * export default function App() {\n * return (\n * <div>\n * <Analytics />\n * <h1>My App</h1>\n * </div>\n * );\n * }\n * ```\n */\nfunction Analytics(\n props: AnalyticsProps & {\n framework?: string;\n route?: string | null;\n path?: string | null;\n basePath?: string;\n configString?: string;\n },\n): null {\n useEffect(() => {\n if (props.beforeSend) {\n window.va?.('beforeSend', props.beforeSend);\n }\n }, [props.beforeSend]);\n\n // biome-ignore lint/correctness/useExhaustiveDependencies: only run once\n useEffect(() => {\n inject(\n {\n framework: props.framework || 'react',\n basePath: props.basePath ?? getBasePath(),\n ...(props.route !== undefined && { disableAutoTrack: true }),\n ...props,\n },\n props.configString ?? getConfigString(),\n );\n }, []);\n\n useEffect(() => {\n // explicitely track page view, since we disabled auto tracking\n if (props.route && props.path) {\n pageview({ route: props.route, path: props.path });\n }\n }, [props.route, props.path]);\n\n return null;\n}\n\nexport { track, Analytics };\nexport type { AnalyticsProps, BeforeSend, BeforeSendEvent };\n","export const initQueue = (): void => {\n // initialize va until script is loaded\n if (window.va) return;\n\n window.va = function a(...params): void {\n if (!window.vaq) window.vaq = [];\n window.vaq.push(params);\n };\n};\n","{\n \"name\": \"@vercel/analytics\",\n \"version\": \"2.0.1\",\n \"description\": \"Gain real-time traffic insights with Vercel Web Analytics\",\n \"keywords\": [\n \"analytics\",\n \"vercel\"\n ],\n \"repository\": {\n \"url\": \"github:vercel/analytics\",\n \"directory\": \"packages/web\"\n },\n \"license\": \"MIT\",\n \"exports\": {\n \"./package.json\": \"./package.json\",\n \".\": {\n \"browser\": \"./dist/index.mjs\",\n \"import\": \"./dist/index.mjs\",\n \"require\": \"./dist/index.js\"\n },\n \"./astro\": {\n \"import\": \"./dist/astro/component.ts\"\n },\n \"./next\": {\n \"browser\": \"./dist/next/index.mjs\",\n \"import\": \"./dist/next/index.mjs\",\n \"require\": \"./dist/next/index.js\"\n },\n \"./nuxt\": {\n \"import\": \"./dist/nuxt/index.mjs\",\n \"require\": \"./dist/nuxt/index.js\"\n },\n \"./nuxt/runtime\": {\n \"browser\": \"./dist/nuxt/runtime/index.mjs\",\n \"import\": \"./dist/nuxt/runtime/index.mjs\",\n \"require\": \"./dist/nuxt/runtime/index.js\"\n },\n \"./Line truncated
+267
View File
@@ -0,0 +1,267 @@
"use client";
// src/nextjs/index.tsx
import React, { Suspense } from "react";
// src/react/index.tsx
import { useEffect } from "react";
// src/queue.ts
var initQueue = () => {
if (window.va) return;
window.va = function a(...params) {
if (!window.vaq) window.vaq = [];
window.vaq.push(params);
};
};
// package.json
var name = "@vercel/analytics";
var version = "2.0.1";
// src/utils.ts
function isBrowser() {
return typeof window !== "undefined";
}
function detectEnvironment() {
try {
const env = process.env.NODE_ENV;
if (env === "development" || env === "test") {
return "development";
}
} catch {
}
return "production";
}
function setMode(mode = "auto") {
if (mode === "auto") {
window.vam = detectEnvironment();
return;
}
window.vam = mode;
}
function getMode() {
const mode = isBrowser() ? window.vam : detectEnvironment();
return mode || "production";
}
function isDevelopment() {
return getMode() === "development";
}
function computeRoute(pathname, pathParams) {
if (!pathname || !pathParams) {
return pathname;
}
let result = pathname;
try {
const entries = Object.entries(pathParams);
for (const [key, value] of entries) {
if (!Array.isArray(value)) {
const matcher = turnValueToRegExp(value);
if (matcher.test(result)) {
result = result.replace(matcher, `/[${key}]`);
}
}
}
for (const [key, value] of entries) {
if (Array.isArray(value)) {
const matcher = turnValueToRegExp(value.join("/"));
if (matcher.test(result)) {
result = result.replace(matcher, `/[...${key}]`);
}
}
}
return result;
} catch {
return pathname;
}
}
function turnValueToRegExp(value) {
return new RegExp(`/${escapeRegExp(value)}(?=[/?#]|$)`);
}
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function getScriptSrc(props) {
if (props.scriptSrc) {
return makeAbsolute(props.scriptSrc);
}
if (isDevelopment()) {
return "https://va.vercel-scripts.com/v1/script.debug.js";
}
if (props.basePath) {
return makeAbsolute(`${props.basePath}/insights/script.js`);
}
return "/_vercel/insights/script.js";
}
function loadProps(explicitProps, confString) {
var _a;
let props = explicitProps;
if (confString) {
try {
props = {
...(_a = JSON.parse(confString)) == null ? void 0 : _a.analytics,
...explicitProps
};
} catch {
}
}
setMode(props.mode);
const dataset = {
sdkn: name + (props.framework ? `/${props.framework}` : ""),
sdkv: version
};
if (props.disableAutoTrack) {
dataset.disableAutoTrack = "1";
}
if (props.viewEndpoint) {
dataset.viewEndpoint = makeAbsolute(props.viewEndpoint);
}
if (props.eventEndpoint) {
dataset.eventEndpoint = makeAbsolute(props.eventEndpoint);
}
if (props.sessionEndpoint) {
dataset.sessionEndpoint = makeAbsolute(props.sessionEndpoint);
}
if (isDevelopment() && props.debug === false) {
dataset.debug = "false";
}
if (props.dsn) {
dataset.dsn = props.dsn;
}
if (props.endpoint) {
dataset.endpoint = props.endpoint;
} else if (props.basePath) {
dataset.endpoint = makeAbsolute(`${props.basePath}/insights`);
}
return {
beforeSend: props.beforeSend,
src: getScriptSrc(props),
dataset
};
}
function makeAbsolute(url) {
return url.startsWith("http://") || url.startsWith("https://") || url.startsWith("/") ? url : `/${url}`;
}
// src/generic.ts
function inject(props = {
debug: true
}, confString) {
var _a;
if (!isBrowser()) return;
const { beforeSend, src, dataset } = loadProps(props, confString);
initQueue();
if (beforeSend) {
(_a = window.va) == null ? void 0 : _a.call(window, "beforeSend", beforeSend);
}
if (document.head.querySelector(`script[src*="${src}"]`)) return;
const script = document.createElement("script");
script.src = src;
for (const [key, value] of Object.entries(dataset)) {
script.dataset[key] = value;
}
script.defer = true;
script.onerror = () => {
const errorMessage = isDevelopment() ? "Please check if any ad blockers are enabled and try again." : "Be sure to enable Web Analytics for your project and deploy again. See https://vercel.com/docs/analytics/quickstart for more information.";
console.log(
`[Vercel Web Analytics] Failed to load script from ${src}. ${errorMessage}`
);
};
document.head.appendChild(script);
}
function pageview({
route,
path
}) {
var _a;
(_a = window.va) == null ? void 0 : _a.call(window, "pageview", { route, path });
}
// src/react/utils.ts
function getBasePath() {
if (typeof process === "undefined" || typeof process.env === "undefined") {
return void 0;
}
return process.env.REACT_APP_VERCEL_OBSERVABILITY_BASEPATH;
}
function getConfigString() {
if (typeof process === "undefined" || typeof process.env === "undefined") {
return void 0;
}
return process.env.REACT_APP_VERCEL_OBSERVABILITY_CLIENT_CONFIG;
}
// src/react/index.tsx
function Analytics(props) {
useEffect(() => {
var _a;
if (props.beforeSend) {
(_a = window.va) == null ? void 0 : _a.call(window, "beforeSend", props.beforeSend);
}
}, [props.beforeSend]);
useEffect(() => {
inject(
{
framework: props.framework || "react",
basePath: props.basePath ?? getBasePath(),
...props.route !== void 0 && { disableAutoTrack: true },
...props
},
props.configString ?? getConfigString()
);
}, []);
useEffect(() => {
if (props.route && props.path) {
pageview({ route: props.route, path: props.path });
}
}, [props.route, props.path]);
return null;
}
// src/nextjs/utils.ts
import { useParams, usePathname, useSearchParams } from "next/navigation.js";
var useRoute = () => {
const params = useParams();
const searchParams = useSearchParams();
const path = usePathname();
if (!params) {
return { route: null, path };
}
const finalParams = Object.keys(params).length ? params : Object.fromEntries(searchParams.entries());
return { route: computeRoute(path, finalParams), path };
};
function getBasePath2() {
if (typeof process === "undefined" || typeof process.env === "undefined") {
return void 0;
}
return process.env.NEXT_PUBLIC_VERCEL_OBSERVABILITY_BASEPATH;
}
function getConfigString2() {
if (typeof process === "undefined" || typeof process.env === "undefined") {
return void 0;
}
return process.env.NEXT_PUBLIC_VERCEL_OBSERVABILITY_CLIENT_CONFIG;
}
// src/nextjs/index.tsx
function AnalyticsComponent(props) {
const { route, path } = useRoute();
return /* @__PURE__ */ React.createElement(
Analytics,
{
path,
route,
...props,
basePath: getBasePath2(),
configString: getConfigString2(),
framework: "next"
}
);
}
function Analytics2(props) {
return /* @__PURE__ */ React.createElement(Suspense, { fallback: null }, /* @__PURE__ */ React.createElement(AnalyticsComponent, { ...props }));
}
export {
Analytics2 as Analytics
};
//# sourceMappingURL=index.mjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../src/nextjs/index.tsx","../../src/react/index.tsx","../../src/queue.ts","../../package.json","../../src/utils.ts","../../src/generic.ts","../../src/react/utils.ts","../../src/nextjs/utils.ts"],"sourcesContent":["'use client';\nimport React, { type ReactNode, Suspense } from 'react';\nimport { Analytics as AnalyticsScript } from '../react';\nimport type { AnalyticsProps, BeforeSend, BeforeSendEvent } from '../types';\nimport { getBasePath, getConfigString, useRoute } from './utils';\n\ntype Props = Omit<AnalyticsProps, 'route' | 'disableAutoTrack'>;\n\nfunction AnalyticsComponent(props: Props): ReactNode {\n const { route, path } = useRoute();\n return (\n <AnalyticsScript\n path={path}\n route={route}\n {...props}\n basePath={getBasePath()}\n configString={getConfigString()}\n framework=\"next\"\n />\n );\n}\n\nexport function Analytics(props: Props): null {\n // Because of incompatible types between ReactNode in React 19 and React 18 we return null (which is also what we render)\n return (\n <Suspense fallback={null}>\n <AnalyticsComponent {...props} />\n </Suspense>\n ) as never;\n}\n\nexport type { AnalyticsProps, BeforeSend, BeforeSendEvent };\n","'use client';\nimport { useEffect } from 'react';\nimport { inject, pageview, track } from '../generic';\nimport type { AnalyticsProps, BeforeSend, BeforeSendEvent } from '../types';\nimport { getBasePath, getConfigString } from './utils';\n\n/**\n * Injects the Vercel Web Analytics script into the page head and starts tracking page views. Read more in our [documentation](https://vercel.com/docs/concepts/analytics/package).\n * @param [props] - Analytics options.\n * @param [props.mode] - The mode to use for the analytics script. Defaults to `auto`.\n * - `auto` - Automatically detect the environment. Uses `production` if the environment cannot be determined.\n * - `production` - Always use the production script. (Sends events to the server)\n * - `development` - Always use the development script. (Logs events to the console)\n * @param [props.debug] - Whether to enable debug logging in development. Defaults to `true`.\n * @param [props.beforeSend] - A middleware function to modify events before they are sent. Should return the event object or `null` to cancel the event.\n * @example\n * ```js\n * import { Analytics } from '@vercel/analytics/react';\n *\n * export default function App() {\n * return (\n * <div>\n * <Analytics />\n * <h1>My App</h1>\n * </div>\n * );\n * }\n * ```\n */\nfunction Analytics(\n props: AnalyticsProps & {\n framework?: string;\n route?: string | null;\n path?: string | null;\n basePath?: string;\n configString?: string;\n },\n): null {\n useEffect(() => {\n if (props.beforeSend) {\n window.va?.('beforeSend', props.beforeSend);\n }\n }, [props.beforeSend]);\n\n // biome-ignore lint/correctness/useExhaustiveDependencies: only run once\n useEffect(() => {\n inject(\n {\n framework: props.framework || 'react',\n basePath: props.basePath ?? getBasePath(),\n ...(props.route !== undefined && { disableAutoTrack: true }),\n ...props,\n },\n props.configString ?? getConfigString(),\n );\n }, []);\n\n useEffect(() => {\n // explicitely track page view, since we disabled auto tracking\n if (props.route && props.path) {\n pageview({ route: props.route, path: props.path });\n }\n }, [props.route, props.path]);\n\n return null;\n}\n\nexport { track, Analytics };\nexport type { AnalyticsProps, BeforeSend, BeforeSendEvent };\n","export const initQueue = (): void => {\n // initialize va until script is loaded\n if (window.va) return;\n\n window.va = function a(...params): void {\n if (!window.vaq) window.vaq = [];\n window.vaq.push(params);\n };\n};\n","{\n \"name\": \"@vercel/analytics\",\n \"version\": \"2.0.1\",\n \"description\": \"Gain real-time traffic insights with Vercel Web Analytics\",\n \"keywords\": [\n \"analytics\",\n \"vercel\"\n ],\n \"repository\": {\n \"url\": \"github:vercel/analytics\",\n \"directory\": \"packages/web\"\n },\n \"license\": \"MIT\",\n \"exports\": {\n \"./package.json\": \"./package.json\",\n \".\": {\n \"browser\": \"./dist/index.mjs\",\n \"import\": \"./dist/index.mjs\",\n \"require\": \"./dist/index.js\"\n },\n \"./astro\": {\n \"import\": \"./dist/astro/component.ts\"\n },\n \"./next\": {\n \"browser\": \"./dist/next/index.mjs\",\n \"import\": \"./dist/next/index.mjs\",\n \"require\": \"./dist/next/index.js\"\n },\n \"./nuxt\": {\n \"import\": \"./dist/nuxt/index.mjs\",\n \"require\": \"./dist/nuxt/index.js\"\n },\n \"./nuxt/runtime\": {\n \"browser\": \"./dist/nuxt/runtime/index.mjs\",\n \"import\": \"./dist/nuxt/runtime/index.mjs\",\n \"require\": \"./dist/nuxt/runtime/index.js\"\n },\n \"./Line truncated
+5
View File
@@ -0,0 +1,5 @@
import { NuxtModule } from '@nuxt/schema';
declare const _default: NuxtModule;
export { _default as default };
+5
View File
@@ -0,0 +1,5 @@
import { NuxtModule } from '@nuxt/schema';
declare const _default: NuxtModule;
export { _default as default };
+51
View File
@@ -0,0 +1,51 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/nuxt/module.ts
var module_exports = {};
__export(module_exports, {
default: () => module_default
});
module.exports = __toCommonJS(module_exports);
var import_kit = require("@nuxt/kit");
var module_default = (0, import_kit.defineNuxtModule)({
meta: {
name: "@vercel/analytics",
configKey: "analytics",
docs: "https://vercel.com/docs/analytics/quickstart"
},
setup() {
const template = (0, import_kit.addTemplate)({
filename: "vercel-analytics.client.ts",
getContents: () => `
import { injectAnalytics } from '@vercel/analytics/nuxt/runtime'
import { defineNuxtPlugin } from '#imports'
export default defineNuxtPlugin(() => {
injectAnalytics()
})
`
});
(0, import_kit.addPlugin)({
src: template.dst,
mode: "client"
});
}
});
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../src/nuxt/module.ts"],"sourcesContent":["import { addPlugin, addTemplate, defineNuxtModule } from '@nuxt/kit';\nimport type { NuxtModule } from '@nuxt/schema';\n\nexport default defineNuxtModule({\n meta: {\n name: '@vercel/analytics',\n configKey: 'analytics',\n docs: 'https://vercel.com/docs/analytics/quickstart',\n },\n setup() {\n const template = addTemplate({\n filename: 'vercel-analytics.client.ts',\n getContents: () => `\nimport { injectAnalytics } from '@vercel/analytics/nuxt/runtime'\nimport { defineNuxtPlugin } from '#imports'\n\nexport default defineNuxtPlugin(() => {\n injectAnalytics()\n})\n`,\n });\n\n addPlugin({\n src: template.dst,\n mode: 'client',\n });\n },\n}) as NuxtModule;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,iBAAyD;AAGzD,IAAO,qBAAQ,6BAAiB;AAAA,EAC9B,MAAM;AAAA,IACJ,MAAM;AAAA,IACN,WAAW;AAAA,IACX,MAAM;AAAA,EACR;AAAA,EACA,QAAQ;AACN,UAAM,eAAW,wBAAY;AAAA,MAC3B,UAAU;AAAA,MACV,aAAa,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAQrB,CAAC;AAED,8BAAU;AAAA,MACR,KAAK,SAAS;AAAA,MACd,MAAM;AAAA,IACR,CAAC;AAAA,EACH;AACF,CAAC;","names":[]}
+30
View File
@@ -0,0 +1,30 @@
// src/nuxt/module.ts
import { addPlugin, addTemplate, defineNuxtModule } from "@nuxt/kit";
var module_default = defineNuxtModule({
meta: {
name: "@vercel/analytics",
configKey: "analytics",
docs: "https://vercel.com/docs/analytics/quickstart"
},
setup() {
const template = addTemplate({
filename: "vercel-analytics.client.ts",
getContents: () => `
import { injectAnalytics } from '@vercel/analytics/nuxt/runtime'
import { defineNuxtPlugin } from '#imports'
export default defineNuxtPlugin(() => {
injectAnalytics()
})
`
});
addPlugin({
src: template.dst,
mode: "client"
});
}
});
export {
module_default as default
};
//# sourceMappingURL=index.mjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../src/nuxt/module.ts"],"sourcesContent":["import { addPlugin, addTemplate, defineNuxtModule } from '@nuxt/kit';\nimport type { NuxtModule } from '@nuxt/schema';\n\nexport default defineNuxtModule({\n meta: {\n name: '@vercel/analytics',\n configKey: 'analytics',\n docs: 'https://vercel.com/docs/analytics/quickstart',\n },\n setup() {\n const template = addTemplate({\n filename: 'vercel-analytics.client.ts',\n getContents: () => `\nimport { injectAnalytics } from '@vercel/analytics/nuxt/runtime'\nimport { defineNuxtPlugin } from '#imports'\n\nexport default defineNuxtPlugin(() => {\n injectAnalytics()\n})\n`,\n });\n\n addPlugin({\n src: template.dst,\n mode: 'client',\n });\n },\n}) as NuxtModule;\n"],"mappings":";AAAA,SAAS,WAAW,aAAa,wBAAwB;AAGzD,IAAO,iBAAQ,iBAAiB;AAAA,EAC9B,MAAM;AAAA,IACJ,MAAM;AAAA,IACN,WAAW;AAAA,IACX,MAAM;AAAA,EACR;AAAA,EACA,QAAQ;AACN,UAAM,WAAW,YAAY;AAAA,MAC3B,UAAU;AAAA,MACV,aAAa,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAQrB,CAAC;AAED,cAAU;AAAA,MACR,KAAK,SAAS;AAAA,MACd,MAAM;AAAA,IACR,CAAC;AAAA,EACH;AACF,CAAC;","names":[]}
+51
View File
@@ -0,0 +1,51 @@
interface PageViewEvent {
type: 'pageview';
url: string;
}
interface CustomEvent {
type: 'event';
url: string;
}
type BeforeSendEvent = PageViewEvent | CustomEvent;
type Mode = 'auto' | 'development' | 'production';
type AllowedPropertyValues = string | number | boolean | null | undefined;
type BeforeSend = (event: BeforeSendEvent) => BeforeSendEvent | null;
interface AnalyticsProps {
beforeSend?: BeforeSend;
debug?: boolean;
mode?: Mode;
scriptSrc?: string;
dsn?: string;
eventEndpoint?: string;
viewEndpoint?: string;
sessionEndpoint?: string;
endpoint?: string;
}
declare global {
interface Window {
va?: (event: 'beforeSend' | 'event' | 'pageview', properties?: unknown) => void;
vaq?: [string, unknown?][];
vai?: boolean;
vam?: Mode;
/** used by Astro component only */
webAnalyticsBeforeSend?: BeforeSend;
}
}
type PlainFlags = Record<string, unknown>;
type FlagsDataInput = (string | PlainFlags)[] | PlainFlags;
/**
* Tracks a custom event. Please refer to the [documentation](https://vercel.com/docs/concepts/analytics/custom-events) for more information on custom events.
* @param name - The name of the event.
* * Examples: `Purchase`, `Click Button`, or `Play Video`.
* @param [properties] - Additional properties of the event. Nested objects are not supported. Allowed values are `string`, `number`, `boolean`, and `null`.
*/
declare function track(name: string, properties?: Record<string, AllowedPropertyValues>, options?: {
flags?: FlagsDataInput;
}): void;
declare const Analytics: any;
declare function injectAnalytics(props?: Omit<AnalyticsProps, 'framework'>): void;
export { Analytics, type AnalyticsProps, type BeforeSend, type BeforeSendEvent, injectAnalytics, track };
+51
View File
@@ -0,0 +1,51 @@
interface PageViewEvent {
type: 'pageview';
url: string;
}
interface CustomEvent {
type: 'event';
url: string;
}
type BeforeSendEvent = PageViewEvent | CustomEvent;
type Mode = 'auto' | 'development' | 'production';
type AllowedPropertyValues = string | number | boolean | null | undefined;
type BeforeSend = (event: BeforeSendEvent) => BeforeSendEvent | null;
interface AnalyticsProps {
beforeSend?: BeforeSend;
debug?: boolean;
mode?: Mode;
scriptSrc?: string;
dsn?: string;
eventEndpoint?: string;
viewEndpoint?: string;
sessionEndpoint?: string;
endpoint?: string;
}
declare global {
interface Window {
va?: (event: 'beforeSend' | 'event' | 'pageview', properties?: unknown) => void;
vaq?: [string, unknown?][];
vai?: boolean;
vam?: Mode;
/** used by Astro component only */
webAnalyticsBeforeSend?: BeforeSend;
}
}
type PlainFlags = Record<string, unknown>;
type FlagsDataInput = (string | PlainFlags)[] | PlainFlags;
/**
* Tracks a custom event. Please refer to the [documentation](https://vercel.com/docs/concepts/analytics/custom-events) for more information on custom events.
* @param name - The name of the event.
* * Examples: `Purchase`, `Click Button`, or `Play Video`.
* @param [properties] - Additional properties of the event. Nested objects are not supported. Allowed values are `string`, `number`, `boolean`, and `null`.
*/
declare function track(name: string, properties?: Record<string, AllowedPropertyValues>, options?: {
flags?: FlagsDataInput;
}): void;
declare const Analytics: any;
declare function injectAnalytics(props?: Omit<AnalyticsProps, 'framework'>): void;
export { Analytics, type AnalyticsProps, type BeforeSend, type BeforeSendEvent, injectAnalytics, track };
+365
View File
@@ -0,0 +1,365 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name2 in all)
__defProp(target, name2, { get: all[name2], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/nuxt/runtime/index.ts
var runtime_exports = {};
__export(runtime_exports, {
Analytics: () => Analytics,
injectAnalytics: () => injectAnalytics,
track: () => track
});
module.exports = __toCommonJS(runtime_exports);
var import_app = require("nuxt/app");
// src/queue.ts
var initQueue = () => {
if (window.va) return;
window.va = function a(...params) {
if (!window.vaq) window.vaq = [];
window.vaq.push(params);
};
};
// package.json
var name = "@vercel/analytics";
var version = "2.0.1";
// src/utils.ts
function isBrowser() {
return typeof window !== "undefined";
}
function detectEnvironment() {
try {
const env = process.env.NODE_ENV;
if (env === "development" || env === "test") {
return "development";
}
} catch {
}
return "production";
}
function setMode(mode = "auto") {
if (mode === "auto") {
window.vam = detectEnvironment();
return;
}
window.vam = mode;
}
function getMode() {
const mode = isBrowser() ? window.vam : detectEnvironment();
return mode || "production";
}
function isProduction() {
return getMode() === "production";
}
function isDevelopment() {
return getMode() === "development";
}
function removeKey(key, { [key]: _, ...rest }) {
return rest;
}
function parseProperties(properties, options) {
if (!properties) return void 0;
let props = properties;
const errorProperties = [];
for (const [key, value] of Object.entries(properties)) {
if (typeof value === "object" && value !== null) {
if (options.strip) {
props = removeKey(key, props);
} else {
errorProperties.push(key);
}
}
}
if (errorProperties.length > 0 && !options.strip) {
throw Error(
`The following properties are not valid: ${errorProperties.join(
", "
)}. Only strings, numbers, booleans, and null are allowed.`
);
}
return props;
}
function computeRoute(pathname, pathParams) {
if (!pathname || !pathParams) {
return pathname;
}
let result = pathname;
try {
const entries = Object.entries(pathParams);
for (const [key, value] of entries) {
if (!Array.isArray(value)) {
const matcher = turnValueToRegExp(value);
if (matcher.test(result)) {
result = result.replace(matcher, `/[${key}]`);
}
}
}
for (const [key, value] of entries) {
if (Array.isArray(value)) {
const matcher = turnValueToRegExp(value.join("/"));
if (matcher.test(result)) {
result = result.replace(matcher, `/[...${key}]`);
}
}
}
return result;
} catch {
return pathname;
}
}
function turnValueToRegExp(value) {
return new RegExp(`/${escapeRegExp(value)}(?=[/?#]|$)`);
}
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function getScriptSrc(props) {
if (props.scriptSrc) {
return makeAbsolute(props.scriptSrc);
}
if (isDevelopment()) {
return "https://va.vercel-scripts.com/v1/script.debug.js";
}
if (props.basePath) {
return makeAbsolute(`${props.basePath}/insights/script.js`);
}
return "/_vercel/insights/script.js";
}
function loadProps(explicitProps, confString) {
var _a;
let props = explicitProps;
if (confString) {
try {
props = {
...(_a = JSON.parse(confString)) == null ? void 0 : _a.analytics,
...explicitProps
};
} catch {
}
}
setMode(props.mode);
const dataset = {
sdkn: name + (props.framework ? `/${props.framework}` : ""),
sdkv: version
};
if (props.disableAutoTrack) {
dataset.disableAutoTrack = "1";
}
if (props.viewEndpoint) {
dataset.viewEndpoint = makeAbsolute(props.viewEndpoint);
}
if (props.eventEndpoint) {
dataset.eventEndpoint = makeAbsolute(props.eventEndpoint);
}
if (props.sessionEndpoint) {
dataset.sessionEndpoint = makeAbsolute(props.sessionEndpoint);
}
if (isDevelopment() && props.debug === false) {
dataset.debug = "false";
}
if (props.dsn) {
dataset.dsn = props.dsn;
}
if (props.endpoint) {
dataset.endpoint = props.endpoint;
} else if (props.basePath) {
dataset.endpoint = makeAbsolute(`${props.basePath}/insights`);
}
return {
beforeSend: props.beforeSend,
src: getScriptSrc(props),
dataset
};
}
function makeAbsolute(url) {
return url.startsWith("http://") || url.startsWith("https://") || url.startsWith("/") ? url : `/${url}`;
}
// src/generic.ts
function inject(props = {
debug: true
}, confString) {
var _a;
if (!isBrowser()) return;
const { beforeSend, src, dataset } = loadProps(props, confString);
initQueue();
if (beforeSend) {
(_a = window.va) == null ? void 0 : _a.call(window, "beforeSend", beforeSend);
}
if (document.head.querySelector(`script[src*="${src}"]`)) return;
const script = document.createElement("script");
script.src = src;
for (const [key, value] of Object.entries(dataset)) {
script.dataset[key] = value;
}
script.defer = true;
script.onerror = () => {
const errorMessage = isDevelopment() ? "Please check if any ad blockers are enabled and try again." : "Be sure to enable Web Analytics for your project and deploy again. See https://vercel.com/docs/analytics/quickstart for more information.";
console.log(
`[Vercel Web Analytics] Failed to load script from ${src}. ${errorMessage}`
);
};
document.head.appendChild(script);
}
function track(name2, properties, options) {
var _a, _b;
if (!isBrowser()) {
const msg = "[Vercel Web Analytics] Please import `track` from `@vercel/analytics/server` when using this function in a server environment";
if (isProduction()) {
console.warn(msg);
} else {
throw new Error(msg);
}
return;
}
if (!properties) {
(_a = window.va) == null ? void 0 : _a.call(window, "event", { name: name2, options });
return;
}
try {
const props = parseProperties(properties, {
strip: isProduction()
});
(_b = window.va) == null ? void 0 : _b.call(window, "event", {
name: name2,
data: props,
options
});
} catch (err) {
if (err instanceof Error && isDevelopment()) {
console.error(err);
}
}
}
function pageview({
route,
path
}) {
var _a;
(_a = window.va) == null ? void 0 : _a.call(window, "pageview", { route, path });
}
// src/vue/create-component.ts
var import_vue = require("vue");
var import_vue_router = require("vue-router");
// src/vue/utils.ts
var import_meta = {};
function getBasePath() {
try {
return import_meta.env.VITE_VERCEL_OBSERVABILITY_BASEPATH;
} catch {
}
}
function getConfigString() {
try {
return import_meta.env.VITE_VERCEL_OBSERVABILITY_CLIENT_CONFIG;
} catch {
}
}
// src/vue/create-component.ts
function createComponent(framework = "vue") {
return (0, import_vue.defineComponent)({
props: ["dsn", "beforeSend", "debug", "scriptSrc", "endpoint", "mode"],
setup(props) {
const route = (0, import_vue_router.useRoute)();
inject(
{
// trim out undefined values to avoid overriding config values
...Object.fromEntries(
Object.entries(props).filter(([_, v]) => v !== void 0)
),
basePath: getBasePath(),
// keep auto-tracking unless we have route support (Nuxt or vue-router).
disableAutoTrack: Boolean(route),
framework
},
getConfigString()
);
if (route && typeof window !== "undefined") {
const changeRoute = () => {
pageview({
route: computeRoute(route.path, route.params),
path: route.path
});
};
changeRoute();
(0, import_vue.watch)(route, changeRoute);
}
},
// Vue component must have a render function, or a template.
render() {
return null;
}
});
}
// src/nuxt/runtime/utils.ts
var import_meta2 = {};
function getBasePath2() {
try {
return import_meta2.env.VITE_VERCEL_OBSERVABILITY_BASEPATH;
} catch {
}
}
function getConfigString2() {
try {
return import_meta2.env.VITE_VERCEL_OBSERVABILITY_CLIENT_CONFIG;
} catch {
}
}
// src/nuxt/runtime/index.ts
var Analytics = createComponent("nuxt");
function injectAnalytics(props = {}) {
if (isBrowser()) {
const router = (0, import_app.useRouter)();
(0, import_app.onNuxtReady)(() => {
inject(
{
...props,
framework: "nuxt",
disableAutoTrack: true,
basePath: getBasePath2()
},
getConfigString2()
);
const route = (0, import_app.useRoute)();
pageview({
route: computeRoute(route.path, route.params),
path: route.path
});
});
router.afterEach((to) => {
pageview({
route: computeRoute(to.path, to.params),
path: to.path
});
});
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Analytics,
injectAnalytics,
track
});
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/nuxt/runtime/index.ts","../../../src/queue.ts","../../../package.json","../../../src/utils.ts","../../../src/generic.ts","../../../src/vue/create-component.ts","../../../src/vue/utils.ts","../../../src/nuxt/runtime/utils.ts"],"sourcesContent":["import { onNuxtReady, useRoute, useRouter } from 'nuxt/app';\nimport { inject, pageview, track } from '../../generic';\nimport type { AnalyticsProps, BeforeSend, BeforeSendEvent } from '../../types';\nimport { computeRoute, isBrowser } from '../../utils';\nimport { createComponent } from '../../vue/create-component';\nimport { getBasePath, getConfigString } from './utils';\n\n// Export the Analytics component\n// Not recommended as must be used in both app.vue and error.vue\nexport const Analytics = createComponent('nuxt');\nexport type { AnalyticsProps, BeforeSend, BeforeSendEvent };\n\n// Export the injectAnalytics script with automatic tracking on page changes\nfunction injectAnalytics(props: Omit<AnalyticsProps, 'framework'> = {}): void {\n if (isBrowser()) {\n const router = useRouter();\n\n onNuxtReady(() => {\n inject(\n {\n ...props,\n framework: 'nuxt',\n disableAutoTrack: true,\n basePath: getBasePath(),\n },\n getConfigString(),\n );\n const route = useRoute();\n pageview({\n route: computeRoute(route.path, route.params),\n path: route.path,\n });\n });\n // On navigation to a new page\n router.afterEach((to) => {\n pageview({\n route: computeRoute(to.path, to.params),\n path: to.path,\n });\n });\n }\n}\n\nexport { injectAnalytics, track };\n","export const initQueue = (): void => {\n // initialize va until script is loaded\n if (window.va) return;\n\n window.va = function a(...params): void {\n if (!window.vaq) window.vaq = [];\n window.vaq.push(params);\n };\n};\n","{\n \"name\": \"@vercel/analytics\",\n \"version\": \"2.0.1\",\n \"description\": \"Gain real-time traffic insights with Vercel Web Analytics\",\n \"keywords\": [\n \"analytics\",\n \"vercel\"\n ],\n \"repository\": {\n \"url\": \"github:vercel/analytics\",\n \"directory\": \"packages/web\"\n },\n \"license\": \"MIT\",\n \"exports\": {\n \"./package.json\": \"./package.json\",\n \".\": {\n \"browser\": \"./dist/index.mjs\",\n \"import\": \"./dist/index.mjs\",\n \"require\": \"./dist/index.js\"\n },\n \"./astro\": {\n \"import\": \"./dist/astro/component.ts\"\n },\n \"./next\": {\n \"browser\": \"./dist/next/index.mjs\",\n \"import\": \"./dist/next/index.mjs\",\n \"require\": \"./dist/next/index.js\"\n },\n \"./nuxt\": {\n \"import\": \"./dist/nuxt/index.mjs\",\n \"require\": \"./dist/nuxt/index.js\"\n },\n \"./nuxt/runtime\": {\n \"browser\": \"./dist/nuxt/runtime/index.mjs\",\n \"import\": \"./dist/nuxt/runtime/index.mjs\",\n \"require\": \"./dist/nuxt/runtime/index.js\"\n },\n \"./react\": {\n \"browser\": \"./dist/react/index.mjs\",\n \"import\": \"./dist/react/index.mjs\",\n \"require\": \"./dist/react/index.js\"\n },\n \"./remix\": {\n \"browser\": \"./dist/remix/index.mjs\",\n \"import\": \"./dist/remix/index.mjs\",\n \"require\": \"./dist/remix/index.js\"\n },\n \"./server\": {\n \"node\": \"./dist/server/index.mjs\",\n \"edge-light\": \"./dist/server/index.mjs\",\n \"import\": \"./dist/server/index.mjs\",\n \"require\": \"./dist/server/index.js\",\n \"default\": \"./dist/server/index.js\"\n },\n \"./sveltekit\": {\n \"svelte\": \"./dist/sveltekit/index.mjs\",\n \"types\": \"./dist/sveltekit/index.d.ts\"\n },\n \"./vue\": {\n \"browser\": \"./dist/vue/index.mjs\",\n \"import\": \"./dist/vue/index.mjs\",\n \"require\": \"./dist/vue/index.js\"\n }\n },\n \"main\": \"./dist/index.mjs\",\n \"types\": \"./dist/index.d.ts\",\n \"typesVersions\": {\n \"*\": {\n \"*\": [\n \"dist/index.d.ts\"\n ],\n \"next\": [\n \"dist/next/index.d.ts\"\n ],\n \"nuxt\": [\n \"dist/nuxt/index.d.ts\"\n ],\n \"nuxt/runtime\": [\n \"dist/nuxt/runtime/index.d.ts\"\n ],\n \"react\": [\n \"dist/react/index.d.ts\"\n ],\n \"remix\": [\n \"dist/remix/index.d.ts\"\n ],\n \"server\": [\n \"dist/server/index.d.ts\"\n ],\n \"sveltekit\": [\n \"dist/sveltekit/index.d.ts\"\n ],\n \"vue\": [\n \"dist/vue/index.d.ts\"\n ]\n }\n },\n \"scripts\": {\n \"build\": \"tsup && pnpm copy-astro\",\n \"copy-astro\": \"cp -R src/astro dist/\",\n \"dev\": \"pnpm copy-astro && tsup --watch\",\n \"test\": \"vitest\"\n },\n \"devDependencies\": {\n \"@nuxt/kit\": \"^4.2.0\",\n \"@nuxt/schema\": \"^4.2.0\",\n \"@swc/core\": \"^1.9.2\",\n \"@testing-Line truncated
+336
View File
@@ -0,0 +1,336 @@
// src/nuxt/runtime/index.ts
import { onNuxtReady, useRoute as useRoute2, useRouter } from "nuxt/app";
// src/queue.ts
var initQueue = () => {
if (window.va) return;
window.va = function a(...params) {
if (!window.vaq) window.vaq = [];
window.vaq.push(params);
};
};
// package.json
var name = "@vercel/analytics";
var version = "2.0.1";
// src/utils.ts
function isBrowser() {
return typeof window !== "undefined";
}
function detectEnvironment() {
try {
const env = process.env.NODE_ENV;
if (env === "development" || env === "test") {
return "development";
}
} catch {
}
return "production";
}
function setMode(mode = "auto") {
if (mode === "auto") {
window.vam = detectEnvironment();
return;
}
window.vam = mode;
}
function getMode() {
const mode = isBrowser() ? window.vam : detectEnvironment();
return mode || "production";
}
function isProduction() {
return getMode() === "production";
}
function isDevelopment() {
return getMode() === "development";
}
function removeKey(key, { [key]: _, ...rest }) {
return rest;
}
function parseProperties(properties, options) {
if (!properties) return void 0;
let props = properties;
const errorProperties = [];
for (const [key, value] of Object.entries(properties)) {
if (typeof value === "object" && value !== null) {
if (options.strip) {
props = removeKey(key, props);
} else {
errorProperties.push(key);
}
}
}
if (errorProperties.length > 0 && !options.strip) {
throw Error(
`The following properties are not valid: ${errorProperties.join(
", "
)}. Only strings, numbers, booleans, and null are allowed.`
);
}
return props;
}
function computeRoute(pathname, pathParams) {
if (!pathname || !pathParams) {
return pathname;
}
let result = pathname;
try {
const entries = Object.entries(pathParams);
for (const [key, value] of entries) {
if (!Array.isArray(value)) {
const matcher = turnValueToRegExp(value);
if (matcher.test(result)) {
result = result.replace(matcher, `/[${key}]`);
}
}
}
for (const [key, value] of entries) {
if (Array.isArray(value)) {
const matcher = turnValueToRegExp(value.join("/"));
if (matcher.test(result)) {
result = result.replace(matcher, `/[...${key}]`);
}
}
}
return result;
} catch {
return pathname;
}
}
function turnValueToRegExp(value) {
return new RegExp(`/${escapeRegExp(value)}(?=[/?#]|$)`);
}
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function getScriptSrc(props) {
if (props.scriptSrc) {
return makeAbsolute(props.scriptSrc);
}
if (isDevelopment()) {
return "https://va.vercel-scripts.com/v1/script.debug.js";
}
if (props.basePath) {
return makeAbsolute(`${props.basePath}/insights/script.js`);
}
return "/_vercel/insights/script.js";
}
function loadProps(explicitProps, confString) {
var _a;
let props = explicitProps;
if (confString) {
try {
props = {
...(_a = JSON.parse(confString)) == null ? void 0 : _a.analytics,
...explicitProps
};
} catch {
}
}
setMode(props.mode);
const dataset = {
sdkn: name + (props.framework ? `/${props.framework}` : ""),
sdkv: version
};
if (props.disableAutoTrack) {
dataset.disableAutoTrack = "1";
}
if (props.viewEndpoint) {
dataset.viewEndpoint = makeAbsolute(props.viewEndpoint);
}
if (props.eventEndpoint) {
dataset.eventEndpoint = makeAbsolute(props.eventEndpoint);
}
if (props.sessionEndpoint) {
dataset.sessionEndpoint = makeAbsolute(props.sessionEndpoint);
}
if (isDevelopment() && props.debug === false) {
dataset.debug = "false";
}
if (props.dsn) {
dataset.dsn = props.dsn;
}
if (props.endpoint) {
dataset.endpoint = props.endpoint;
} else if (props.basePath) {
dataset.endpoint = makeAbsolute(`${props.basePath}/insights`);
}
return {
beforeSend: props.beforeSend,
src: getScriptSrc(props),
dataset
};
}
function makeAbsolute(url) {
return url.startsWith("http://") || url.startsWith("https://") || url.startsWith("/") ? url : `/${url}`;
}
// src/generic.ts
function inject(props = {
debug: true
}, confString) {
var _a;
if (!isBrowser()) return;
const { beforeSend, src, dataset } = loadProps(props, confString);
initQueue();
if (beforeSend) {
(_a = window.va) == null ? void 0 : _a.call(window, "beforeSend", beforeSend);
}
if (document.head.querySelector(`script[src*="${src}"]`)) return;
const script = document.createElement("script");
script.src = src;
for (const [key, value] of Object.entries(dataset)) {
script.dataset[key] = value;
}
script.defer = true;
script.onerror = () => {
const errorMessage = isDevelopment() ? "Please check if any ad blockers are enabled and try again." : "Be sure to enable Web Analytics for your project and deploy again. See https://vercel.com/docs/analytics/quickstart for more information.";
console.log(
`[Vercel Web Analytics] Failed to load script from ${src}. ${errorMessage}`
);
};
document.head.appendChild(script);
}
function track(name2, properties, options) {
var _a, _b;
if (!isBrowser()) {
const msg = "[Vercel Web Analytics] Please import `track` from `@vercel/analytics/server` when using this function in a server environment";
if (isProduction()) {
console.warn(msg);
} else {
throw new Error(msg);
}
return;
}
if (!properties) {
(_a = window.va) == null ? void 0 : _a.call(window, "event", { name: name2, options });
return;
}
try {
const props = parseProperties(properties, {
strip: isProduction()
});
(_b = window.va) == null ? void 0 : _b.call(window, "event", {
name: name2,
data: props,
options
});
} catch (err) {
if (err instanceof Error && isDevelopment()) {
console.error(err);
}
}
}
function pageview({
route,
path
}) {
var _a;
(_a = window.va) == null ? void 0 : _a.call(window, "pageview", { route, path });
}
// src/vue/create-component.ts
import { defineComponent, watch } from "vue";
import { useRoute } from "vue-router";
// src/vue/utils.ts
function getBasePath() {
try {
return import.meta.env.VITE_VERCEL_OBSERVABILITY_BASEPATH;
} catch {
}
}
function getConfigString() {
try {
return import.meta.env.VITE_VERCEL_OBSERVABILITY_CLIENT_CONFIG;
} catch {
}
}
// src/vue/create-component.ts
function createComponent(framework = "vue") {
return defineComponent({
props: ["dsn", "beforeSend", "debug", "scriptSrc", "endpoint", "mode"],
setup(props) {
const route = useRoute();
inject(
{
// trim out undefined values to avoid overriding config values
...Object.fromEntries(
Object.entries(props).filter(([_, v]) => v !== void 0)
),
basePath: getBasePath(),
// keep auto-tracking unless we have route support (Nuxt or vue-router).
disableAutoTrack: Boolean(route),
framework
},
getConfigString()
);
if (route && typeof window !== "undefined") {
const changeRoute = () => {
pageview({
route: computeRoute(route.path, route.params),
path: route.path
});
};
changeRoute();
watch(route, changeRoute);
}
},
// Vue component must have a render function, or a template.
render() {
return null;
}
});
}
// src/nuxt/runtime/utils.ts
function getBasePath2() {
try {
return import.meta.env.VITE_VERCEL_OBSERVABILITY_BASEPATH;
} catch {
}
}
function getConfigString2() {
try {
return import.meta.env.VITE_VERCEL_OBSERVABILITY_CLIENT_CONFIG;
} catch {
}
}
// src/nuxt/runtime/index.ts
var Analytics = createComponent("nuxt");
function injectAnalytics(props = {}) {
if (isBrowser()) {
const router = useRouter();
onNuxtReady(() => {
inject(
{
...props,
framework: "nuxt",
disableAutoTrack: true,
basePath: getBasePath2()
},
getConfigString2()
);
const route = useRoute2();
pageview({
route: computeRoute(route.path, route.params),
path: route.path
});
});
router.afterEach((to) => {
pageview({
route: computeRoute(to.path, to.params),
path: to.path
});
});
}
}
export {
Analytics,
injectAnalytics,
track
};
//# sourceMappingURL=index.mjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/nuxt/runtime/index.ts","../../../src/queue.ts","../../../package.json","../../../src/utils.ts","../../../src/generic.ts","../../../src/vue/create-component.ts","../../../src/vue/utils.ts","../../../src/nuxt/runtime/utils.ts"],"sourcesContent":["import { onNuxtReady, useRoute, useRouter } from 'nuxt/app';\nimport { inject, pageview, track } from '../../generic';\nimport type { AnalyticsProps, BeforeSend, BeforeSendEvent } from '../../types';\nimport { computeRoute, isBrowser } from '../../utils';\nimport { createComponent } from '../../vue/create-component';\nimport { getBasePath, getConfigString } from './utils';\n\n// Export the Analytics component\n// Not recommended as must be used in both app.vue and error.vue\nexport const Analytics = createComponent('nuxt');\nexport type { AnalyticsProps, BeforeSend, BeforeSendEvent };\n\n// Export the injectAnalytics script with automatic tracking on page changes\nfunction injectAnalytics(props: Omit<AnalyticsProps, 'framework'> = {}): void {\n if (isBrowser()) {\n const router = useRouter();\n\n onNuxtReady(() => {\n inject(\n {\n ...props,\n framework: 'nuxt',\n disableAutoTrack: true,\n basePath: getBasePath(),\n },\n getConfigString(),\n );\n const route = useRoute();\n pageview({\n route: computeRoute(route.path, route.params),\n path: route.path,\n });\n });\n // On navigation to a new page\n router.afterEach((to) => {\n pageview({\n route: computeRoute(to.path, to.params),\n path: to.path,\n });\n });\n }\n}\n\nexport { injectAnalytics, track };\n","export const initQueue = (): void => {\n // initialize va until script is loaded\n if (window.va) return;\n\n window.va = function a(...params): void {\n if (!window.vaq) window.vaq = [];\n window.vaq.push(params);\n };\n};\n","{\n \"name\": \"@vercel/analytics\",\n \"version\": \"2.0.1\",\n \"description\": \"Gain real-time traffic insights with Vercel Web Analytics\",\n \"keywords\": [\n \"analytics\",\n \"vercel\"\n ],\n \"repository\": {\n \"url\": \"github:vercel/analytics\",\n \"directory\": \"packages/web\"\n },\n \"license\": \"MIT\",\n \"exports\": {\n \"./package.json\": \"./package.json\",\n \".\": {\n \"browser\": \"./dist/index.mjs\",\n \"import\": \"./dist/index.mjs\",\n \"require\": \"./dist/index.js\"\n },\n \"./astro\": {\n \"import\": \"./dist/astro/component.ts\"\n },\n \"./next\": {\n \"browser\": \"./dist/next/index.mjs\",\n \"import\": \"./dist/next/index.mjs\",\n \"require\": \"./dist/next/index.js\"\n },\n \"./nuxt\": {\n \"import\": \"./dist/nuxt/index.mjs\",\n \"require\": \"./dist/nuxt/index.js\"\n },\n \"./nuxt/runtime\": {\n \"browser\": \"./dist/nuxt/runtime/index.mjs\",\n \"import\": \"./dist/nuxt/runtime/index.mjs\",\n \"require\": \"./dist/nuxt/runtime/index.js\"\n },\n \"./react\": {\n \"browser\": \"./dist/react/index.mjs\",\n \"import\": \"./dist/react/index.mjs\",\n \"require\": \"./dist/react/index.js\"\n },\n \"./remix\": {\n \"browser\": \"./dist/remix/index.mjs\",\n \"import\": \"./dist/remix/index.mjs\",\n \"require\": \"./dist/remix/index.js\"\n },\n \"./server\": {\n \"node\": \"./dist/server/index.mjs\",\n \"edge-light\": \"./dist/server/index.mjs\",\n \"import\": \"./dist/server/index.mjs\",\n \"require\": \"./dist/server/index.js\",\n \"default\": \"./dist/server/index.js\"\n },\n \"./sveltekit\": {\n \"svelte\": \"./dist/sveltekit/index.mjs\",\n \"types\": \"./dist/sveltekit/index.d.ts\"\n },\n \"./vue\": {\n \"browser\": \"./dist/vue/index.mjs\",\n \"import\": \"./dist/vue/index.mjs\",\n \"require\": \"./dist/vue/index.js\"\n }\n },\n \"main\": \"./dist/index.mjs\",\n \"types\": \"./dist/index.d.ts\",\n \"typesVersions\": {\n \"*\": {\n \"*\": [\n \"dist/index.d.ts\"\n ],\n \"next\": [\n \"dist/next/index.d.ts\"\n ],\n \"nuxt\": [\n \"dist/nuxt/index.d.ts\"\n ],\n \"nuxt/runtime\": [\n \"dist/nuxt/runtime/index.d.ts\"\n ],\n \"react\": [\n \"dist/react/index.d.ts\"\n ],\n \"remix\": [\n \"dist/remix/index.d.ts\"\n ],\n \"server\": [\n \"dist/server/index.d.ts\"\n ],\n \"sveltekit\": [\n \"dist/sveltekit/index.d.ts\"\n ],\n \"vue\": [\n \"dist/vue/index.d.ts\"\n ]\n }\n },\n \"scripts\": {\n \"build\": \"tsup && pnpm copy-astro\",\n \"copy-astro\": \"cp -R src/astro dist/\",\n \"dev\": \"pnpm copy-astro && tsup --watch\",\n \"test\": \"vitest\"\n },\n \"devDependencies\": {\n \"@nuxt/kit\": \"^4.2.0\",\n \"@nuxt/schema\": \"^4.2.0\",\n \"@swc/core\": \"^1.9.2\",\n \"@testing-Line truncated
+78
View File
@@ -0,0 +1,78 @@
interface PageViewEvent {
type: 'pageview';
url: string;
}
interface CustomEvent {
type: 'event';
url: string;
}
type BeforeSendEvent = PageViewEvent | CustomEvent;
type Mode = 'auto' | 'development' | 'production';
type AllowedPropertyValues = string | number | boolean | null | undefined;
type BeforeSend = (event: BeforeSendEvent) => BeforeSendEvent | null;
interface AnalyticsProps {
beforeSend?: BeforeSend;
debug?: boolean;
mode?: Mode;
scriptSrc?: string;
dsn?: string;
eventEndpoint?: string;
viewEndpoint?: string;
sessionEndpoint?: string;
endpoint?: string;
}
declare global {
interface Window {
va?: (event: 'beforeSend' | 'event' | 'pageview', properties?: unknown) => void;
vaq?: [string, unknown?][];
vai?: boolean;
vam?: Mode;
/** used by Astro component only */
webAnalyticsBeforeSend?: BeforeSend;
}
}
type PlainFlags = Record<string, unknown>;
type FlagsDataInput = (string | PlainFlags)[] | PlainFlags;
/**
* Tracks a custom event. Please refer to the [documentation](https://vercel.com/docs/concepts/analytics/custom-events) for more information on custom events.
* @param name - The name of the event.
* * Examples: `Purchase`, `Click Button`, or `Play Video`.
* @param [properties] - Additional properties of the event. Nested objects are not supported. Allowed values are `string`, `number`, `boolean`, and `null`.
*/
declare function track(name: string, properties?: Record<string, AllowedPropertyValues>, options?: {
flags?: FlagsDataInput;
}): void;
/**
* Injects the Vercel Web Analytics script into the page head and starts tracking page views. Read more in our [documentation](https://vercel.com/docs/concepts/analytics/package).
* @param [props] - Analytics options.
* @param [props.mode] - The mode to use for the analytics script. Defaults to `auto`.
* - `auto` - Automatically detect the environment. Uses `production` if the environment cannot be determined.
* - `production` - Always use the production script. (Sends events to the server)
* - `development` - Always use the development script. (Logs events to the console)
* @param [props.debug] - Whether to enable debug logging in development. Defaults to `true`.
* @param [props.beforeSend] - A middleware function to modify events before they are sent. Should return the event object or `null` to cancel the event.
* @example
* ```js
* import { Analytics } from '@vercel/analytics/react';
*
* export default function App() {
* return (
* <div>
* <Analytics />
* <h1>My App</h1>
* </div>
* );
* }
* ```
*/
declare function Analytics(props: AnalyticsProps & {
framework?: string;
route?: string | null;
path?: string | null;
basePath?: string;
configString?: string;
}): null;
export { Analytics, type AnalyticsProps, type BeforeSend, type BeforeSendEvent, track };
+78
View File
@@ -0,0 +1,78 @@
interface PageViewEvent {
type: 'pageview';
url: string;
}
interface CustomEvent {
type: 'event';
url: string;
}
type BeforeSendEvent = PageViewEvent | CustomEvent;
type Mode = 'auto' | 'development' | 'production';
type AllowedPropertyValues = string | number | boolean | null | undefined;
type BeforeSend = (event: BeforeSendEvent) => BeforeSendEvent | null;
interface AnalyticsProps {
beforeSend?: BeforeSend;
debug?: boolean;
mode?: Mode;
scriptSrc?: string;
dsn?: string;
eventEndpoint?: string;
viewEndpoint?: string;
sessionEndpoint?: string;
endpoint?: string;
}
declare global {
interface Window {
va?: (event: 'beforeSend' | 'event' | 'pageview', properties?: unknown) => void;
vaq?: [string, unknown?][];
vai?: boolean;
vam?: Mode;
/** used by Astro component only */
webAnalyticsBeforeSend?: BeforeSend;
}
}
type PlainFlags = Record<string, unknown>;
type FlagsDataInput = (string | PlainFlags)[] | PlainFlags;
/**
* Tracks a custom event. Please refer to the [documentation](https://vercel.com/docs/concepts/analytics/custom-events) for more information on custom events.
* @param name - The name of the event.
* * Examples: `Purchase`, `Click Button`, or `Play Video`.
* @param [properties] - Additional properties of the event. Nested objects are not supported. Allowed values are `string`, `number`, `boolean`, and `null`.
*/
declare function track(name: string, properties?: Record<string, AllowedPropertyValues>, options?: {
flags?: FlagsDataInput;
}): void;
/**
* Injects the Vercel Web Analytics script into the page head and starts tracking page views. Read more in our [documentation](https://vercel.com/docs/concepts/analytics/package).
* @param [props] - Analytics options.
* @param [props.mode] - The mode to use for the analytics script. Defaults to `auto`.
* - `auto` - Automatically detect the environment. Uses `production` if the environment cannot be determined.
* - `production` - Always use the production script. (Sends events to the server)
* - `development` - Always use the development script. (Logs events to the console)
* @param [props.debug] - Whether to enable debug logging in development. Defaults to `true`.
* @param [props.beforeSend] - A middleware function to modify events before they are sent. Should return the event object or `null` to cancel the event.
* @example
* ```js
* import { Analytics } from '@vercel/analytics/react';
*
* export default function App() {
* return (
* <div>
* <Analytics />
* <h1>My App</h1>
* </div>
* );
* }
* ```
*/
declare function Analytics(props: AnalyticsProps & {
framework?: string;
route?: string | null;
path?: string | null;
basePath?: string;
configString?: string;
}): null;
export { Analytics, type AnalyticsProps, type BeforeSend, type BeforeSendEvent, track };
+270
View File
@@ -0,0 +1,270 @@
"use strict";
"use client";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name2 in all)
__defProp(target, name2, { get: all[name2], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/react/index.tsx
var react_exports = {};
__export(react_exports, {
Analytics: () => Analytics,
track: () => track
});
module.exports = __toCommonJS(react_exports);
var import_react = require("react");
// src/queue.ts
var initQueue = () => {
if (window.va) return;
window.va = function a(...params) {
if (!window.vaq) window.vaq = [];
window.vaq.push(params);
};
};
// package.json
var name = "@vercel/analytics";
var version = "2.0.1";
// src/utils.ts
function isBrowser() {
return typeof window !== "undefined";
}
function detectEnvironment() {
try {
const env = process.env.NODE_ENV;
if (env === "development" || env === "test") {
return "development";
}
} catch {
}
return "production";
}
function setMode(mode = "auto") {
if (mode === "auto") {
window.vam = detectEnvironment();
return;
}
window.vam = mode;
}
function getMode() {
const mode = isBrowser() ? window.vam : detectEnvironment();
return mode || "production";
}
function isProduction() {
return getMode() === "production";
}
function isDevelopment() {
return getMode() === "development";
}
function removeKey(key, { [key]: _, ...rest }) {
return rest;
}
function parseProperties(properties, options) {
if (!properties) return void 0;
let props = properties;
const errorProperties = [];
for (const [key, value] of Object.entries(properties)) {
if (typeof value === "object" && value !== null) {
if (options.strip) {
props = removeKey(key, props);
} else {
errorProperties.push(key);
}
}
}
if (errorProperties.length > 0 && !options.strip) {
throw Error(
`The following properties are not valid: ${errorProperties.join(
", "
)}. Only strings, numbers, booleans, and null are allowed.`
);
}
return props;
}
function getScriptSrc(props) {
if (props.scriptSrc) {
return makeAbsolute(props.scriptSrc);
}
if (isDevelopment()) {
return "https://va.vercel-scripts.com/v1/script.debug.js";
}
if (props.basePath) {
return makeAbsolute(`${props.basePath}/insights/script.js`);
}
return "/_vercel/insights/script.js";
}
function loadProps(explicitProps, confString) {
var _a;
let props = explicitProps;
if (confString) {
try {
props = {
...(_a = JSON.parse(confString)) == null ? void 0 : _a.analytics,
...explicitProps
};
} catch {
}
}
setMode(props.mode);
const dataset = {
sdkn: name + (props.framework ? `/${props.framework}` : ""),
sdkv: version
};
if (props.disableAutoTrack) {
dataset.disableAutoTrack = "1";
}
if (props.viewEndpoint) {
dataset.viewEndpoint = makeAbsolute(props.viewEndpoint);
}
if (props.eventEndpoint) {
dataset.eventEndpoint = makeAbsolute(props.eventEndpoint);
}
if (props.sessionEndpoint) {
dataset.sessionEndpoint = makeAbsolute(props.sessionEndpoint);
}
if (isDevelopment() && props.debug === false) {
dataset.debug = "false";
}
if (props.dsn) {
dataset.dsn = props.dsn;
}
if (props.endpoint) {
dataset.endpoint = props.endpoint;
} else if (props.basePath) {
dataset.endpoint = makeAbsolute(`${props.basePath}/insights`);
}
return {
beforeSend: props.beforeSend,
src: getScriptSrc(props),
dataset
};
}
function makeAbsolute(url) {
return url.startsWith("http://") || url.startsWith("https://") || url.startsWith("/") ? url : `/${url}`;
}
// src/generic.ts
function inject(props = {
debug: true
}, confString) {
var _a;
if (!isBrowser()) return;
const { beforeSend, src, dataset } = loadProps(props, confString);
initQueue();
if (beforeSend) {
(_a = window.va) == null ? void 0 : _a.call(window, "beforeSend", beforeSend);
}
if (document.head.querySelector(`script[src*="${src}"]`)) return;
const script = document.createElement("script");
script.src = src;
for (const [key, value] of Object.entries(dataset)) {
script.dataset[key] = value;
}
script.defer = true;
script.onerror = () => {
const errorMessage = isDevelopment() ? "Please check if any ad blockers are enabled and try again." : "Be sure to enable Web Analytics for your project and deploy again. See https://vercel.com/docs/analytics/quickstart for more information.";
console.log(
`[Vercel Web Analytics] Failed to load script from ${src}. ${errorMessage}`
);
};
document.head.appendChild(script);
}
function track(name2, properties, options) {
var _a, _b;
if (!isBrowser()) {
const msg = "[Vercel Web Analytics] Please import `track` from `@vercel/analytics/server` when using this function in a server environment";
if (isProduction()) {
console.warn(msg);
} else {
throw new Error(msg);
}
return;
}
if (!properties) {
(_a = window.va) == null ? void 0 : _a.call(window, "event", { name: name2, options });
return;
}
try {
const props = parseProperties(properties, {
strip: isProduction()
});
(_b = window.va) == null ? void 0 : _b.call(window, "event", {
name: name2,
data: props,
options
});
} catch (err) {
if (err instanceof Error && isDevelopment()) {
console.error(err);
}
}
}
function pageview({
route,
path
}) {
var _a;
(_a = window.va) == null ? void 0 : _a.call(window, "pageview", { route, path });
}
// src/react/utils.ts
function getBasePath() {
if (typeof process === "undefined" || typeof process.env === "undefined") {
return void 0;
}
return process.env.REACT_APP_VERCEL_OBSERVABILITY_BASEPATH;
}
function getConfigString() {
if (typeof process === "undefined" || typeof process.env === "undefined") {
return void 0;
}
return process.env.REACT_APP_VERCEL_OBSERVABILITY_CLIENT_CONFIG;
}
// src/react/index.tsx
function Analytics(props) {
(0, import_react.useEffect)(() => {
var _a;
if (props.beforeSend) {
(_a = window.va) == null ? void 0 : _a.call(window, "beforeSend", props.beforeSend);
}
}, [props.beforeSend]);
(0, import_react.useEffect)(() => {
inject(
{
framework: props.framework || "react",
basePath: props.basePath ?? getBasePath(),
...props.route !== void 0 && { disableAutoTrack: true },
...props
},
props.configString ?? getConfigString()
);
}, []);
(0, import_react.useEffect)(() => {
if (props.route && props.path) {
pageview({ route: props.route, path: props.path });
}
}, [props.route, props.path]);
return null;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Analytics,
track
});
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../src/react/index.tsx","../../src/queue.ts","../../package.json","../../src/utils.ts","../../src/generic.ts","../../src/react/utils.ts"],"sourcesContent":["'use client';\nimport { useEffect } from 'react';\nimport { inject, pageview, track } from '../generic';\nimport type { AnalyticsProps, BeforeSend, BeforeSendEvent } from '../types';\nimport { getBasePath, getConfigString } from './utils';\n\n/**\n * Injects the Vercel Web Analytics script into the page head and starts tracking page views. Read more in our [documentation](https://vercel.com/docs/concepts/analytics/package).\n * @param [props] - Analytics options.\n * @param [props.mode] - The mode to use for the analytics script. Defaults to `auto`.\n * - `auto` - Automatically detect the environment. Uses `production` if the environment cannot be determined.\n * - `production` - Always use the production script. (Sends events to the server)\n * - `development` - Always use the development script. (Logs events to the console)\n * @param [props.debug] - Whether to enable debug logging in development. Defaults to `true`.\n * @param [props.beforeSend] - A middleware function to modify events before they are sent. Should return the event object or `null` to cancel the event.\n * @example\n * ```js\n * import { Analytics } from '@vercel/analytics/react';\n *\n * export default function App() {\n * return (\n * <div>\n * <Analytics />\n * <h1>My App</h1>\n * </div>\n * );\n * }\n * ```\n */\nfunction Analytics(\n props: AnalyticsProps & {\n framework?: string;\n route?: string | null;\n path?: string | null;\n basePath?: string;\n configString?: string;\n },\n): null {\n useEffect(() => {\n if (props.beforeSend) {\n window.va?.('beforeSend', props.beforeSend);\n }\n }, [props.beforeSend]);\n\n // biome-ignore lint/correctness/useExhaustiveDependencies: only run once\n useEffect(() => {\n inject(\n {\n framework: props.framework || 'react',\n basePath: props.basePath ?? getBasePath(),\n ...(props.route !== undefined && { disableAutoTrack: true }),\n ...props,\n },\n props.configString ?? getConfigString(),\n );\n }, []);\n\n useEffect(() => {\n // explicitely track page view, since we disabled auto tracking\n if (props.route && props.path) {\n pageview({ route: props.route, path: props.path });\n }\n }, [props.route, props.path]);\n\n return null;\n}\n\nexport { track, Analytics };\nexport type { AnalyticsProps, BeforeSend, BeforeSendEvent };\n","export const initQueue = (): void => {\n // initialize va until script is loaded\n if (window.va) return;\n\n window.va = function a(...params): void {\n if (!window.vaq) window.vaq = [];\n window.vaq.push(params);\n };\n};\n","{\n \"name\": \"@vercel/analytics\",\n \"version\": \"2.0.1\",\n \"description\": \"Gain real-time traffic insights with Vercel Web Analytics\",\n \"keywords\": [\n \"analytics\",\n \"vercel\"\n ],\n \"repository\": {\n \"url\": \"github:vercel/analytics\",\n \"directory\": \"packages/web\"\n },\n \"license\": \"MIT\",\n \"exports\": {\n \"./package.json\": \"./package.json\",\n \".\": {\n \"browser\": \"./dist/index.mjs\",\n \"import\": \"./dist/index.mjs\",\n \"require\": \"./dist/index.js\"\n },\n \"./astro\": {\n \"import\": \"./dist/astro/component.ts\"\n },\n \"./next\": {\n \"browser\": \"./dist/next/index.mjs\",\n \"import\": \"./dist/next/index.mjs\",\n \"require\": \"./dist/next/index.js\"\n },\n \"./nuxt\": {\n \"import\": \"./dist/nuxt/index.mjs\",\n \"require\": \"./dist/nuxt/index.js\"\n },\n \"./nuxt/runtime\": {\n \"browser\": \"./dist/nuxt/runtime/index.mjs\",\n \"import\": \"./dist/nuxt/runtime/index.mjs\",\n \"require\": \"./dist/nuxt/runtime/index.js\"\n },\n \"./react\": {\n \"browser\": \"./dist/react/index.mjs\",\n \"import\": \"./dist/react/index.mjs\",\n \"require\": \"./dist/react/index.js\"\n },\n \"./remix\": {\n \"browser\": \"./dist/remix/index.mjs\",\n \"import\": \"./dist/remix/index.mjs\",\n \"require\": \"./dist/remix/index.js\"\n },\n \"./server\": {\n \"node\": \"./dist/server/index.mjs\",\n \"edge-light\": \"./dist/server/index.mjs\",\n \"import\": \"./dist/server/index.mjs\",\n \"require\": \"./dist/server/index.js\",\n \"default\": \"./dist/server/index.js\"\n },\n \"./sveltekit\": {\n \"svelte\": \"./dist/sveltekit/index.mjs\",\n \"types\": \"./dist/sveltekit/index.d.ts\"\n },\n \"./vue\": {\n \"browser\": \"./dist/vue/index.mjs\",\n \"import\": \"./dist/vue/index.mjs\",\n \"require\": \"./dist/vue/index.js\"\n }\n },\n \"main\": \"./dist/index.mjs\",\n \"types\": \"./dist/index.d.ts\",\n \"typesVersions\": {\n \"*\": {\n \"*\": [\n \"dist/index.d.ts\"\n ],\n Line truncated
+245
View File
@@ -0,0 +1,245 @@
"use client";
// src/react/index.tsx
import { useEffect } from "react";
// src/queue.ts
var initQueue = () => {
if (window.va) return;
window.va = function a(...params) {
if (!window.vaq) window.vaq = [];
window.vaq.push(params);
};
};
// package.json
var name = "@vercel/analytics";
var version = "2.0.1";
// src/utils.ts
function isBrowser() {
return typeof window !== "undefined";
}
function detectEnvironment() {
try {
const env = process.env.NODE_ENV;
if (env === "development" || env === "test") {
return "development";
}
} catch {
}
return "production";
}
function setMode(mode = "auto") {
if (mode === "auto") {
window.vam = detectEnvironment();
return;
}
window.vam = mode;
}
function getMode() {
const mode = isBrowser() ? window.vam : detectEnvironment();
return mode || "production";
}
function isProduction() {
return getMode() === "production";
}
function isDevelopment() {
return getMode() === "development";
}
function removeKey(key, { [key]: _, ...rest }) {
return rest;
}
function parseProperties(properties, options) {
if (!properties) return void 0;
let props = properties;
const errorProperties = [];
for (const [key, value] of Object.entries(properties)) {
if (typeof value === "object" && value !== null) {
if (options.strip) {
props = removeKey(key, props);
} else {
errorProperties.push(key);
}
}
}
if (errorProperties.length > 0 && !options.strip) {
throw Error(
`The following properties are not valid: ${errorProperties.join(
", "
)}. Only strings, numbers, booleans, and null are allowed.`
);
}
return props;
}
function getScriptSrc(props) {
if (props.scriptSrc) {
return makeAbsolute(props.scriptSrc);
}
if (isDevelopment()) {
return "https://va.vercel-scripts.com/v1/script.debug.js";
}
if (props.basePath) {
return makeAbsolute(`${props.basePath}/insights/script.js`);
}
return "/_vercel/insights/script.js";
}
function loadProps(explicitProps, confString) {
var _a;
let props = explicitProps;
if (confString) {
try {
props = {
...(_a = JSON.parse(confString)) == null ? void 0 : _a.analytics,
...explicitProps
};
} catch {
}
}
setMode(props.mode);
const dataset = {
sdkn: name + (props.framework ? `/${props.framework}` : ""),
sdkv: version
};
if (props.disableAutoTrack) {
dataset.disableAutoTrack = "1";
}
if (props.viewEndpoint) {
dataset.viewEndpoint = makeAbsolute(props.viewEndpoint);
}
if (props.eventEndpoint) {
dataset.eventEndpoint = makeAbsolute(props.eventEndpoint);
}
if (props.sessionEndpoint) {
dataset.sessionEndpoint = makeAbsolute(props.sessionEndpoint);
}
if (isDevelopment() && props.debug === false) {
dataset.debug = "false";
}
if (props.dsn) {
dataset.dsn = props.dsn;
}
if (props.endpoint) {
dataset.endpoint = props.endpoint;
} else if (props.basePath) {
dataset.endpoint = makeAbsolute(`${props.basePath}/insights`);
}
return {
beforeSend: props.beforeSend,
src: getScriptSrc(props),
dataset
};
}
function makeAbsolute(url) {
return url.startsWith("http://") || url.startsWith("https://") || url.startsWith("/") ? url : `/${url}`;
}
// src/generic.ts
function inject(props = {
debug: true
}, confString) {
var _a;
if (!isBrowser()) return;
const { beforeSend, src, dataset } = loadProps(props, confString);
initQueue();
if (beforeSend) {
(_a = window.va) == null ? void 0 : _a.call(window, "beforeSend", beforeSend);
}
if (document.head.querySelector(`script[src*="${src}"]`)) return;
const script = document.createElement("script");
script.src = src;
for (const [key, value] of Object.entries(dataset)) {
script.dataset[key] = value;
}
script.defer = true;
script.onerror = () => {
const errorMessage = isDevelopment() ? "Please check if any ad blockers are enabled and try again." : "Be sure to enable Web Analytics for your project and deploy again. See https://vercel.com/docs/analytics/quickstart for more information.";
console.log(
`[Vercel Web Analytics] Failed to load script from ${src}. ${errorMessage}`
);
};
document.head.appendChild(script);
}
function track(name2, properties, options) {
var _a, _b;
if (!isBrowser()) {
const msg = "[Vercel Web Analytics] Please import `track` from `@vercel/analytics/server` when using this function in a server environment";
if (isProduction()) {
console.warn(msg);
} else {
throw new Error(msg);
}
return;
}
if (!properties) {
(_a = window.va) == null ? void 0 : _a.call(window, "event", { name: name2, options });
return;
}
try {
const props = parseProperties(properties, {
strip: isProduction()
});
(_b = window.va) == null ? void 0 : _b.call(window, "event", {
name: name2,
data: props,
options
});
} catch (err) {
if (err instanceof Error && isDevelopment()) {
console.error(err);
}
}
}
function pageview({
route,
path
}) {
var _a;
(_a = window.va) == null ? void 0 : _a.call(window, "pageview", { route, path });
}
// src/react/utils.ts
function getBasePath() {
if (typeof process === "undefined" || typeof process.env === "undefined") {
return void 0;
}
return process.env.REACT_APP_VERCEL_OBSERVABILITY_BASEPATH;
}
function getConfigString() {
if (typeof process === "undefined" || typeof process.env === "undefined") {
return void 0;
}
return process.env.REACT_APP_VERCEL_OBSERVABILITY_CLIENT_CONFIG;
}
// src/react/index.tsx
function Analytics(props) {
useEffect(() => {
var _a;
if (props.beforeSend) {
(_a = window.va) == null ? void 0 : _a.call(window, "beforeSend", props.beforeSend);
}
}, [props.beforeSend]);
useEffect(() => {
inject(
{
framework: props.framework || "react",
basePath: props.basePath ?? getBasePath(),
...props.route !== void 0 && { disableAutoTrack: true },
...props
},
props.configString ?? getConfigString()
);
}, []);
useEffect(() => {
if (props.route && props.path) {
pageview({ route: props.route, path: props.path });
}
}, [props.route, props.path]);
return null;
}
export {
Analytics,
track
};
//# sourceMappingURL=index.mjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../src/react/index.tsx","../../src/queue.ts","../../package.json","../../src/utils.ts","../../src/generic.ts","../../src/react/utils.ts"],"sourcesContent":["'use client';\nimport { useEffect } from 'react';\nimport { inject, pageview, track } from '../generic';\nimport type { AnalyticsProps, BeforeSend, BeforeSendEvent } from '../types';\nimport { getBasePath, getConfigString } from './utils';\n\n/**\n * Injects the Vercel Web Analytics script into the page head and starts tracking page views. Read more in our [documentation](https://vercel.com/docs/concepts/analytics/package).\n * @param [props] - Analytics options.\n * @param [props.mode] - The mode to use for the analytics script. Defaults to `auto`.\n * - `auto` - Automatically detect the environment. Uses `production` if the environment cannot be determined.\n * - `production` - Always use the production script. (Sends events to the server)\n * - `development` - Always use the development script. (Logs events to the console)\n * @param [props.debug] - Whether to enable debug logging in development. Defaults to `true`.\n * @param [props.beforeSend] - A middleware function to modify events before they are sent. Should return the event object or `null` to cancel the event.\n * @example\n * ```js\n * import { Analytics } from '@vercel/analytics/react';\n *\n * export default function App() {\n * return (\n * <div>\n * <Analytics />\n * <h1>My App</h1>\n * </div>\n * );\n * }\n * ```\n */\nfunction Analytics(\n props: AnalyticsProps & {\n framework?: string;\n route?: string | null;\n path?: string | null;\n basePath?: string;\n configString?: string;\n },\n): null {\n useEffect(() => {\n if (props.beforeSend) {\n window.va?.('beforeSend', props.beforeSend);\n }\n }, [props.beforeSend]);\n\n // biome-ignore lint/correctness/useExhaustiveDependencies: only run once\n useEffect(() => {\n inject(\n {\n framework: props.framework || 'react',\n basePath: props.basePath ?? getBasePath(),\n ...(props.route !== undefined && { disableAutoTrack: true }),\n ...props,\n },\n props.configString ?? getConfigString(),\n );\n }, []);\n\n useEffect(() => {\n // explicitely track page view, since we disabled auto tracking\n if (props.route && props.path) {\n pageview({ route: props.route, path: props.path });\n }\n }, [props.route, props.path]);\n\n return null;\n}\n\nexport { track, Analytics };\nexport type { AnalyticsProps, BeforeSend, BeforeSendEvent };\n","export const initQueue = (): void => {\n // initialize va until script is loaded\n if (window.va) return;\n\n window.va = function a(...params): void {\n if (!window.vaq) window.vaq = [];\n window.vaq.push(params);\n };\n};\n","{\n \"name\": \"@vercel/analytics\",\n \"version\": \"2.0.1\",\n \"description\": \"Gain real-time traffic insights with Vercel Web Analytics\",\n \"keywords\": [\n \"analytics\",\n \"vercel\"\n ],\n \"repository\": {\n \"url\": \"github:vercel/analytics\",\n \"directory\": \"packages/web\"\n },\n \"license\": \"MIT\",\n \"exports\": {\n \"./package.json\": \"./package.json\",\n \".\": {\n \"browser\": \"./dist/index.mjs\",\n \"import\": \"./dist/index.mjs\",\n \"require\": \"./dist/index.js\"\n },\n \"./astro\": {\n \"import\": \"./dist/astro/component.ts\"\n },\n \"./next\": {\n \"browser\": \"./dist/next/index.mjs\",\n \"import\": \"./dist/next/index.mjs\",\n \"require\": \"./dist/next/index.js\"\n },\n \"./nuxt\": {\n \"import\": \"./dist/nuxt/index.mjs\",\n \"require\": \"./dist/nuxt/index.js\"\n },\n \"./nuxt/runtime\": {\n \"browser\": \"./dist/nuxt/runtime/index.mjs\",\n \"import\": \"./dist/nuxt/runtime/index.mjs\",\n \"require\": \"./dist/nuxt/runtime/index.js\"\n },\n \"./react\": {\n \"browser\": \"./dist/react/index.mjs\",\n \"import\": \"./dist/react/index.mjs\",\n \"require\": \"./dist/react/index.js\"\n },\n \"./remix\": {\n \"browser\": \"./dist/remix/index.mjs\",\n \"import\": \"./dist/remix/index.mjs\",\n \"require\": \"./dist/remix/index.js\"\n },\n \"./server\": {\n \"node\": \"./dist/server/index.mjs\",\n \"edge-light\": \"./dist/server/index.mjs\",\n \"import\": \"./dist/server/index.mjs\",\n \"require\": \"./dist/server/index.js\",\n \"default\": \"./dist/server/index.js\"\n },\n \"./sveltekit\": {\n \"svelte\": \"./dist/sveltekit/index.mjs\",\n \"types\": \"./dist/sveltekit/index.d.ts\"\n },\n \"./vue\": {\n \"browser\": \"./dist/vue/index.mjs\",\n \"import\": \"./dist/vue/index.mjs\",\n \"require\": \"./dist/vue/index.js\"\n }\n },\n \"main\": \"./dist/index.mjs\",\n \"types\": \"./dist/index.d.ts\",\n \"typesVersions\": {\n \"*\": {\n \"*\": [\n \"dist/index.d.ts\"\n ],\n Line truncated
+36
View File
@@ -0,0 +1,36 @@
interface PageViewEvent {
type: 'pageview';
url: string;
}
interface CustomEvent {
type: 'event';
url: string;
}
type BeforeSendEvent = PageViewEvent | CustomEvent;
type Mode = 'auto' | 'development' | 'production';
type BeforeSend = (event: BeforeSendEvent) => BeforeSendEvent | null;
interface AnalyticsProps {
beforeSend?: BeforeSend;
debug?: boolean;
mode?: Mode;
scriptSrc?: string;
dsn?: string;
eventEndpoint?: string;
viewEndpoint?: string;
sessionEndpoint?: string;
endpoint?: string;
}
declare global {
interface Window {
va?: (event: 'beforeSend' | 'event' | 'pageview', properties?: unknown) => void;
vaq?: [string, unknown?][];
vai?: boolean;
vam?: Mode;
/** used by Astro component only */
webAnalyticsBeforeSend?: BeforeSend;
}
}
declare function Analytics(props: Omit<AnalyticsProps, 'route'>): JSX.Element;
export { Analytics, type AnalyticsProps, type BeforeSend, type BeforeSendEvent };
+36
View File
@@ -0,0 +1,36 @@
interface PageViewEvent {
type: 'pageview';
url: string;
}
interface CustomEvent {
type: 'event';
url: string;
}
type BeforeSendEvent = PageViewEvent | CustomEvent;
type Mode = 'auto' | 'development' | 'production';
type BeforeSend = (event: BeforeSendEvent) => BeforeSendEvent | null;
interface AnalyticsProps {
beforeSend?: BeforeSend;
debug?: boolean;
mode?: Mode;
scriptSrc?: string;
dsn?: string;
eventEndpoint?: string;
viewEndpoint?: string;
sessionEndpoint?: string;
endpoint?: string;
}
declare global {
interface Window {
va?: (event: 'beforeSend' | 'event' | 'pageview', properties?: unknown) => void;
vaq?: [string, unknown?][];
vai?: boolean;
vam?: Mode;
/** used by Astro component only */
webAnalyticsBeforeSend?: BeforeSend;
}
}
declare function Analytics(props: Omit<AnalyticsProps, 'route'>): JSX.Element;
export { Analytics, type AnalyticsProps, type BeforeSend, type BeforeSendEvent };
+291
View File
@@ -0,0 +1,291 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name2 in all)
__defProp(target, name2, { get: all[name2], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/remix/index.tsx
var remix_exports = {};
__export(remix_exports, {
Analytics: () => Analytics2
});
module.exports = __toCommonJS(remix_exports);
var import_react3 = __toESM(require("react"));
// src/react/index.tsx
var import_react = require("react");
// src/queue.ts
var initQueue = () => {
if (window.va) return;
window.va = function a(...params) {
if (!window.vaq) window.vaq = [];
window.vaq.push(params);
};
};
// package.json
var name = "@vercel/analytics";
var version = "2.0.1";
// src/utils.ts
function isBrowser() {
return typeof window !== "undefined";
}
function detectEnvironment() {
try {
const env = process.env.NODE_ENV;
if (env === "development" || env === "test") {
return "development";
}
} catch {
}
return "production";
}
function setMode(mode = "auto") {
if (mode === "auto") {
window.vam = detectEnvironment();
return;
}
window.vam = mode;
}
function getMode() {
const mode = isBrowser() ? window.vam : detectEnvironment();
return mode || "production";
}
function isDevelopment() {
return getMode() === "development";
}
function computeRoute(pathname, pathParams) {
if (!pathname || !pathParams) {
return pathname;
}
let result = pathname;
try {
const entries = Object.entries(pathParams);
for (const [key, value] of entries) {
if (!Array.isArray(value)) {
const matcher = turnValueToRegExp(value);
if (matcher.test(result)) {
result = result.replace(matcher, `/[${key}]`);
}
}
}
for (const [key, value] of entries) {
if (Array.isArray(value)) {
const matcher = turnValueToRegExp(value.join("/"));
if (matcher.test(result)) {
result = result.replace(matcher, `/[...${key}]`);
}
}
}
return result;
} catch {
return pathname;
}
}
function turnValueToRegExp(value) {
return new RegExp(`/${escapeRegExp(value)}(?=[/?#]|$)`);
}
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function getScriptSrc(props) {
if (props.scriptSrc) {
return makeAbsolute(props.scriptSrc);
}
if (isDevelopment()) {
return "https://va.vercel-scripts.com/v1/script.debug.js";
}
if (props.basePath) {
return makeAbsolute(`${props.basePath}/insights/script.js`);
}
return "/_vercel/insights/script.js";
}
function loadProps(explicitProps, confString) {
var _a;
let props = explicitProps;
if (confString) {
try {
props = {
...(_a = JSON.parse(confString)) == null ? void 0 : _a.analytics,
...explicitProps
};
} catch {
}
}
setMode(props.mode);
const dataset = {
sdkn: name + (props.framework ? `/${props.framework}` : ""),
sdkv: version
};
if (props.disableAutoTrack) {
dataset.disableAutoTrack = "1";
}
if (props.viewEndpoint) {
dataset.viewEndpoint = makeAbsolute(props.viewEndpoint);
}
if (props.eventEndpoint) {
dataset.eventEndpoint = makeAbsolute(props.eventEndpoint);
}
if (props.sessionEndpoint) {
dataset.sessionEndpoint = makeAbsolute(props.sessionEndpoint);
}
if (isDevelopment() && props.debug === false) {
dataset.debug = "false";
}
if (props.dsn) {
dataset.dsn = props.dsn;
}
if (props.endpoint) {
dataset.endpoint = props.endpoint;
} else if (props.basePath) {
dataset.endpoint = makeAbsolute(`${props.basePath}/insights`);
}
return {
beforeSend: props.beforeSend,
src: getScriptSrc(props),
dataset
};
}
function makeAbsolute(url) {
return url.startsWith("http://") || url.startsWith("https://") || url.startsWith("/") ? url : `/${url}`;
}
// src/generic.ts
function inject(props = {
debug: true
}, confString) {
var _a;
if (!isBrowser()) return;
const { beforeSend, src, dataset } = loadProps(props, confString);
initQueue();
if (beforeSend) {
(_a = window.va) == null ? void 0 : _a.call(window, "beforeSend", beforeSend);
}
if (document.head.querySelector(`script[src*="${src}"]`)) return;
const script = document.createElement("script");
script.src = src;
for (const [key, value] of Object.entries(dataset)) {
script.dataset[key] = value;
}
script.defer = true;
script.onerror = () => {
const errorMessage = isDevelopment() ? "Please check if any ad blockers are enabled and try again." : "Be sure to enable Web Analytics for your project and deploy again. See https://vercel.com/docs/analytics/quickstart for more information.";
console.log(
`[Vercel Web Analytics] Failed to load script from ${src}. ${errorMessage}`
);
};
document.head.appendChild(script);
}
function pageview({
route,
path
}) {
var _a;
(_a = window.va) == null ? void 0 : _a.call(window, "pageview", { route, path });
}
// src/react/utils.ts
function getBasePath() {
if (typeof process === "undefined" || typeof process.env === "undefined") {
return void 0;
}
return process.env.REACT_APP_VERCEL_OBSERVABILITY_BASEPATH;
}
function getConfigString() {
if (typeof process === "undefined" || typeof process.env === "undefined") {
return void 0;
}
return process.env.REACT_APP_VERCEL_OBSERVABILITY_CLIENT_CONFIG;
}
// src/react/index.tsx
function Analytics(props) {
(0, import_react.useEffect)(() => {
var _a;
if (props.beforeSend) {
(_a = window.va) == null ? void 0 : _a.call(window, "beforeSend", props.beforeSend);
}
}, [props.beforeSend]);
(0, import_react.useEffect)(() => {
inject(
{
framework: props.framework || "react",
basePath: props.basePath ?? getBasePath(),
...props.route !== void 0 && { disableAutoTrack: true },
...props
},
props.configString ?? getConfigString()
);
}, []);
(0, import_react.useEffect)(() => {
if (props.route && props.path) {
pageview({ route: props.route, path: props.path });
}
}, [props.route, props.path]);
return null;
}
// src/remix/utils.ts
var import_react2 = require("@remix-run/react");
var import_meta = {};
var useRoute = () => {
const params = (0, import_react2.useParams)();
const { pathname: path } = (0, import_react2.useLocation)();
return { route: computeRoute(path, params), path };
};
function getBasePath2() {
try {
return import_meta.env.VITE_VERCEL_OBSERVABILITY_BASEPATH;
} catch {
}
}
function getConfigString2() {
try {
return import_meta.env.VITE_VERCEL_OBSERVABILITY_CLIENT_CONFIG;
} catch {
}
}
// src/remix/index.tsx
function Analytics2(props) {
return /* @__PURE__ */ import_react3.default.createElement(
Analytics,
{
...useRoute(),
...props,
basePath: getBasePath2(),
configString: getConfigString2(),
framework: "remix"
}
);
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Analytics
});
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../src/remix/index.tsx","../../src/react/index.tsx","../../src/queue.ts","../../package.json","../../src/utils.ts","../../src/generic.ts","../../src/react/utils.ts","../../src/remix/utils.ts"],"sourcesContent":["import React from 'react';\nimport { Analytics as AnalyticsScript } from '../react';\nimport type { AnalyticsProps, BeforeSend, BeforeSendEvent } from '../types';\nimport { getBasePath, getConfigString, useRoute } from './utils';\n\nexport function Analytics(props: Omit<AnalyticsProps, 'route'>): JSX.Element {\n return (\n <AnalyticsScript\n {...useRoute()}\n {...props}\n basePath={getBasePath()}\n configString={getConfigString()}\n framework=\"remix\"\n />\n );\n}\nexport type { AnalyticsProps, BeforeSend, BeforeSendEvent };\n","'use client';\nimport { useEffect } from 'react';\nimport { inject, pageview, track } from '../generic';\nimport type { AnalyticsProps, BeforeSend, BeforeSendEvent } from '../types';\nimport { getBasePath, getConfigString } from './utils';\n\n/**\n * Injects the Vercel Web Analytics script into the page head and starts tracking page views. Read more in our [documentation](https://vercel.com/docs/concepts/analytics/package).\n * @param [props] - Analytics options.\n * @param [props.mode] - The mode to use for the analytics script. Defaults to `auto`.\n * - `auto` - Automatically detect the environment. Uses `production` if the environment cannot be determined.\n * - `production` - Always use the production script. (Sends events to the server)\n * - `development` - Always use the development script. (Logs events to the console)\n * @param [props.debug] - Whether to enable debug logging in development. Defaults to `true`.\n * @param [props.beforeSend] - A middleware function to modify events before they are sent. Should return the event object or `null` to cancel the event.\n * @example\n * ```js\n * import { Analytics } from '@vercel/analytics/react';\n *\n * export default function App() {\n * return (\n * <div>\n * <Analytics />\n * <h1>My App</h1>\n * </div>\n * );\n * }\n * ```\n */\nfunction Analytics(\n props: AnalyticsProps & {\n framework?: string;\n route?: string | null;\n path?: string | null;\n basePath?: string;\n configString?: string;\n },\n): null {\n useEffect(() => {\n if (props.beforeSend) {\n window.va?.('beforeSend', props.beforeSend);\n }\n }, [props.beforeSend]);\n\n // biome-ignore lint/correctness/useExhaustiveDependencies: only run once\n useEffect(() => {\n inject(\n {\n framework: props.framework || 'react',\n basePath: props.basePath ?? getBasePath(),\n ...(props.route !== undefined && { disableAutoTrack: true }),\n ...props,\n },\n props.configString ?? getConfigString(),\n );\n }, []);\n\n useEffect(() => {\n // explicitely track page view, since we disabled auto tracking\n if (props.route && props.path) {\n pageview({ route: props.route, path: props.path });\n }\n }, [props.route, props.path]);\n\n return null;\n}\n\nexport { track, Analytics };\nexport type { AnalyticsProps, BeforeSend, BeforeSendEvent };\n","export const initQueue = (): void => {\n // initialize va until script is loaded\n if (window.va) return;\n\n window.va = function a(...params): void {\n if (!window.vaq) window.vaq = [];\n window.vaq.push(params);\n };\n};\n","{\n \"name\": \"@vercel/analytics\",\n \"version\": \"2.0.1\",\n \"description\": \"Gain real-time traffic insights with Vercel Web Analytics\",\n \"keywords\": [\n \"analytics\",\n \"vercel\"\n ],\n \"repository\": {\n \"url\": \"github:vercel/analytics\",\n \"directory\": \"packages/web\"\n },\n \"license\": \"MIT\",\n \"exports\": {\n \"./package.json\": \"./package.json\",\n \".\": {\n \"browser\": \"./dist/index.mjs\",\n \"import\": \"./dist/index.mjs\",\n \"require\": \"./dist/index.js\"\n },\n \"./astro\": {\n \"import\": \"./dist/astro/component.ts\"\n },\n \"./next\": {\n \"browser\": \"./dist/next/index.mjs\",\n \"import\": \"./dist/next/index.mjs\",\n \"require\": \"./dist/next/index.js\"\n },\n \"./nuxt\": {\n \"import\": \"./dist/nuxt/index.mjs\",\n \"require\": \"./dist/nuxt/index.js\"\n },\n \"./nuxt/runtime\": {\n \"browser\": \"./dist/nuxt/runtime/index.mjs\",\n \"import\": \"./dist/nuxt/runtime/index.mjs\",\n \"require\": \"./dist/nuxt/runtime/index.js\"\n },\n \"./react\": {\n \"browser\": \"./dist/react/index.mjs\",\n \"import\": \"./dist/react/index.mjs\",\n \"require\": \"./dist/react/index.js\"\n },\n \"./remix\": {\n \"browser\": \"./dist/remix/index.mjs\",\n \"import\": \"./dist/remix/index.mjs\",\n \"require\": \"./dist/remix/index.js\"\n },\n \"./server\": {\n \"node\": \"./dist/server/index.mjs\",\n \"edge-light\": \"./dist/server/index.mjsLine truncated
+255
View File
@@ -0,0 +1,255 @@
// src/remix/index.tsx
import React from "react";
// src/react/index.tsx
import { useEffect } from "react";
// src/queue.ts
var initQueue = () => {
if (window.va) return;
window.va = function a(...params) {
if (!window.vaq) window.vaq = [];
window.vaq.push(params);
};
};
// package.json
var name = "@vercel/analytics";
var version = "2.0.1";
// src/utils.ts
function isBrowser() {
return typeof window !== "undefined";
}
function detectEnvironment() {
try {
const env = process.env.NODE_ENV;
if (env === "development" || env === "test") {
return "development";
}
} catch {
}
return "production";
}
function setMode(mode = "auto") {
if (mode === "auto") {
window.vam = detectEnvironment();
return;
}
window.vam = mode;
}
function getMode() {
const mode = isBrowser() ? window.vam : detectEnvironment();
return mode || "production";
}
function isDevelopment() {
return getMode() === "development";
}
function computeRoute(pathname, pathParams) {
if (!pathname || !pathParams) {
return pathname;
}
let result = pathname;
try {
const entries = Object.entries(pathParams);
for (const [key, value] of entries) {
if (!Array.isArray(value)) {
const matcher = turnValueToRegExp(value);
if (matcher.test(result)) {
result = result.replace(matcher, `/[${key}]`);
}
}
}
for (const [key, value] of entries) {
if (Array.isArray(value)) {
const matcher = turnValueToRegExp(value.join("/"));
if (matcher.test(result)) {
result = result.replace(matcher, `/[...${key}]`);
}
}
}
return result;
} catch {
return pathname;
}
}
function turnValueToRegExp(value) {
return new RegExp(`/${escapeRegExp(value)}(?=[/?#]|$)`);
}
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function getScriptSrc(props) {
if (props.scriptSrc) {
return makeAbsolute(props.scriptSrc);
}
if (isDevelopment()) {
return "https://va.vercel-scripts.com/v1/script.debug.js";
}
if (props.basePath) {
return makeAbsolute(`${props.basePath}/insights/script.js`);
}
return "/_vercel/insights/script.js";
}
function loadProps(explicitProps, confString) {
var _a;
let props = explicitProps;
if (confString) {
try {
props = {
...(_a = JSON.parse(confString)) == null ? void 0 : _a.analytics,
...explicitProps
};
} catch {
}
}
setMode(props.mode);
const dataset = {
sdkn: name + (props.framework ? `/${props.framework}` : ""),
sdkv: version
};
if (props.disableAutoTrack) {
dataset.disableAutoTrack = "1";
}
if (props.viewEndpoint) {
dataset.viewEndpoint = makeAbsolute(props.viewEndpoint);
}
if (props.eventEndpoint) {
dataset.eventEndpoint = makeAbsolute(props.eventEndpoint);
}
if (props.sessionEndpoint) {
dataset.sessionEndpoint = makeAbsolute(props.sessionEndpoint);
}
if (isDevelopment() && props.debug === false) {
dataset.debug = "false";
}
if (props.dsn) {
dataset.dsn = props.dsn;
}
if (props.endpoint) {
dataset.endpoint = props.endpoint;
} else if (props.basePath) {
dataset.endpoint = makeAbsolute(`${props.basePath}/insights`);
}
return {
beforeSend: props.beforeSend,
src: getScriptSrc(props),
dataset
};
}
function makeAbsolute(url) {
return url.startsWith("http://") || url.startsWith("https://") || url.startsWith("/") ? url : `/${url}`;
}
// src/generic.ts
function inject(props = {
debug: true
}, confString) {
var _a;
if (!isBrowser()) return;
const { beforeSend, src, dataset } = loadProps(props, confString);
initQueue();
if (beforeSend) {
(_a = window.va) == null ? void 0 : _a.call(window, "beforeSend", beforeSend);
}
if (document.head.querySelector(`script[src*="${src}"]`)) return;
const script = document.createElement("script");
script.src = src;
for (const [key, value] of Object.entries(dataset)) {
script.dataset[key] = value;
}
script.defer = true;
script.onerror = () => {
const errorMessage = isDevelopment() ? "Please check if any ad blockers are enabled and try again." : "Be sure to enable Web Analytics for your project and deploy again. See https://vercel.com/docs/analytics/quickstart for more information.";
console.log(
`[Vercel Web Analytics] Failed to load script from ${src}. ${errorMessage}`
);
};
document.head.appendChild(script);
}
function pageview({
route,
path
}) {
var _a;
(_a = window.va) == null ? void 0 : _a.call(window, "pageview", { route, path });
}
// src/react/utils.ts
function getBasePath() {
if (typeof process === "undefined" || typeof process.env === "undefined") {
return void 0;
}
return process.env.REACT_APP_VERCEL_OBSERVABILITY_BASEPATH;
}
function getConfigString() {
if (typeof process === "undefined" || typeof process.env === "undefined") {
return void 0;
}
return process.env.REACT_APP_VERCEL_OBSERVABILITY_CLIENT_CONFIG;
}
// src/react/index.tsx
function Analytics(props) {
useEffect(() => {
var _a;
if (props.beforeSend) {
(_a = window.va) == null ? void 0 : _a.call(window, "beforeSend", props.beforeSend);
}
}, [props.beforeSend]);
useEffect(() => {
inject(
{
framework: props.framework || "react",
basePath: props.basePath ?? getBasePath(),
...props.route !== void 0 && { disableAutoTrack: true },
...props
},
props.configString ?? getConfigString()
);
}, []);
useEffect(() => {
if (props.route && props.path) {
pageview({ route: props.route, path: props.path });
}
}, [props.route, props.path]);
return null;
}
// src/remix/utils.ts
import { useLocation, useParams } from "@remix-run/react";
var useRoute = () => {
const params = useParams();
const { pathname: path } = useLocation();
return { route: computeRoute(path, params), path };
};
function getBasePath2() {
try {
return import.meta.env.VITE_VERCEL_OBSERVABILITY_BASEPATH;
} catch {
}
}
function getConfigString2() {
try {
return import.meta.env.VITE_VERCEL_OBSERVABILITY_CLIENT_CONFIG;
} catch {
}
}
// src/remix/index.tsx
function Analytics2(props) {
return /* @__PURE__ */ React.createElement(
Analytics,
{
...useRoute(),
...props,
basePath: getBasePath2(),
configString: getConfigString2(),
framework: "remix"
}
);
}
export {
Analytics2 as Analytics
};
//# sourceMappingURL=index.mjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../src/remix/index.tsx","../../src/react/index.tsx","../../src/queue.ts","../../package.json","../../src/utils.ts","../../src/generic.ts","../../src/react/utils.ts","../../src/remix/utils.ts"],"sourcesContent":["import React from 'react';\nimport { Analytics as AnalyticsScript } from '../react';\nimport type { AnalyticsProps, BeforeSend, BeforeSendEvent } from '../types';\nimport { getBasePath, getConfigString, useRoute } from './utils';\n\nexport function Analytics(props: Omit<AnalyticsProps, 'route'>): JSX.Element {\n return (\n <AnalyticsScript\n {...useRoute()}\n {...props}\n basePath={getBasePath()}\n configString={getConfigString()}\n framework=\"remix\"\n />\n );\n}\nexport type { AnalyticsProps, BeforeSend, BeforeSendEvent };\n","'use client';\nimport { useEffect } from 'react';\nimport { inject, pageview, track } from '../generic';\nimport type { AnalyticsProps, BeforeSend, BeforeSendEvent } from '../types';\nimport { getBasePath, getConfigString } from './utils';\n\n/**\n * Injects the Vercel Web Analytics script into the page head and starts tracking page views. Read more in our [documentation](https://vercel.com/docs/concepts/analytics/package).\n * @param [props] - Analytics options.\n * @param [props.mode] - The mode to use for the analytics script. Defaults to `auto`.\n * - `auto` - Automatically detect the environment. Uses `production` if the environment cannot be determined.\n * - `production` - Always use the production script. (Sends events to the server)\n * - `development` - Always use the development script. (Logs events to the console)\n * @param [props.debug] - Whether to enable debug logging in development. Defaults to `true`.\n * @param [props.beforeSend] - A middleware function to modify events before they are sent. Should return the event object or `null` to cancel the event.\n * @example\n * ```js\n * import { Analytics } from '@vercel/analytics/react';\n *\n * export default function App() {\n * return (\n * <div>\n * <Analytics />\n * <h1>My App</h1>\n * </div>\n * );\n * }\n * ```\n */\nfunction Analytics(\n props: AnalyticsProps & {\n framework?: string;\n route?: string | null;\n path?: string | null;\n basePath?: string;\n configString?: string;\n },\n): null {\n useEffect(() => {\n if (props.beforeSend) {\n window.va?.('beforeSend', props.beforeSend);\n }\n }, [props.beforeSend]);\n\n // biome-ignore lint/correctness/useExhaustiveDependencies: only run once\n useEffect(() => {\n inject(\n {\n framework: props.framework || 'react',\n basePath: props.basePath ?? getBasePath(),\n ...(props.route !== undefined && { disableAutoTrack: true }),\n ...props,\n },\n props.configString ?? getConfigString(),\n );\n }, []);\n\n useEffect(() => {\n // explicitely track page view, since we disabled auto tracking\n if (props.route && props.path) {\n pageview({ route: props.route, path: props.path });\n }\n }, [props.route, props.path]);\n\n return null;\n}\n\nexport { track, Analytics };\nexport type { AnalyticsProps, BeforeSend, BeforeSendEvent };\n","export const initQueue = (): void => {\n // initialize va until script is loaded\n if (window.va) return;\n\n window.va = function a(...params): void {\n if (!window.vaq) window.vaq = [];\n window.vaq.push(params);\n };\n};\n","{\n \"name\": \"@vercel/analytics\",\n \"version\": \"2.0.1\",\n \"description\": \"Gain real-time traffic insights with Vercel Web Analytics\",\n \"keywords\": [\n \"analytics\",\n \"vercel\"\n ],\n \"repository\": {\n \"url\": \"github:vercel/analytics\",\n \"directory\": \"packages/web\"\n },\n \"license\": \"MIT\",\n \"exports\": {\n \"./package.json\": \"./package.json\",\n \".\": {\n \"browser\": \"./dist/index.mjs\",\n \"import\": \"./dist/index.mjs\",\n \"require\": \"./dist/index.js\"\n },\n \"./astro\": {\n \"import\": \"./dist/astro/component.ts\"\n },\n \"./next\": {\n \"browser\": \"./dist/next/index.mjs\",\n \"import\": \"./dist/next/index.mjs\",\n \"require\": \"./dist/next/index.js\"\n },\n \"./nuxt\": {\n \"import\": \"./dist/nuxt/index.mjs\",\n \"require\": \"./dist/nuxt/index.js\"\n },\n \"./nuxt/runtime\": {\n \"browser\": \"./dist/nuxt/runtime/index.mjs\",\n \"import\": \"./dist/nuxt/runtime/index.mjs\",\n \"require\": \"./dist/nuxt/runtime/index.js\"\n },\n \"./react\": {\n \"browser\": \"./dist/react/index.mjs\",\n \"import\": \"./dist/react/index.mjs\",\n \"require\": \"./dist/react/index.js\"\n },\n \"./remix\": {\n \"browser\": \"./dist/remix/index.mjs\",\n \"import\": \"./dist/remix/index.mjs\",\n \"require\": \"./dist/remix/index.js\"\n },\n \"./server\": {\n \"node\": \"./dist/server/index.mjs\",\n \"edge-light\": \"./dist/server/index.mjsLine truncated
+37
View File
@@ -0,0 +1,37 @@
interface PageViewEvent {
type: 'pageview';
url: string;
}
interface CustomEvent {
type: 'event';
url: string;
}
type BeforeSendEvent = PageViewEvent | CustomEvent;
type Mode = 'auto' | 'development' | 'production';
type AllowedPropertyValues = string | number | boolean | null | undefined;
type BeforeSend = (event: BeforeSendEvent) => BeforeSendEvent | null;
declare global {
interface Window {
va?: (event: 'beforeSend' | 'event' | 'pageview', properties?: unknown) => void;
vaq?: [string, unknown?][];
vai?: boolean;
vam?: Mode;
/** used by Astro component only */
webAnalyticsBeforeSend?: BeforeSend;
}
}
type PlainFlags = Record<string, unknown>;
type FlagsDataInput = (string | PlainFlags)[] | PlainFlags;
type HeadersObject = Record<string, string | string[] | undefined>;
type AllowedHeaders = Headers | HeadersObject;
interface Options {
flags?: FlagsDataInput;
headers?: AllowedHeaders;
request?: {
headers: AllowedHeaders;
};
}
declare function track(eventName: string, properties?: Record<string, AllowedPropertyValues>, options?: Options): Promise<void>;
export { track };
+37
View File
@@ -0,0 +1,37 @@
interface PageViewEvent {
type: 'pageview';
url: string;
}
interface CustomEvent {
type: 'event';
url: string;
}
type BeforeSendEvent = PageViewEvent | CustomEvent;
type Mode = 'auto' | 'development' | 'production';
type AllowedPropertyValues = string | number | boolean | null | undefined;
type BeforeSend = (event: BeforeSendEvent) => BeforeSendEvent | null;
declare global {
interface Window {
va?: (event: 'beforeSend' | 'event' | 'pageview', properties?: unknown) => void;
vaq?: [string, unknown?][];
vai?: boolean;
vam?: Mode;
/** used by Astro component only */
webAnalyticsBeforeSend?: BeforeSend;
}
}
type PlainFlags = Record<string, unknown>;
type FlagsDataInput = (string | PlainFlags)[] | PlainFlags;
type HeadersObject = Record<string, string | string[] | undefined>;
type AllowedHeaders = Headers | HeadersObject;
interface Options {
flags?: FlagsDataInput;
headers?: AllowedHeaders;
request?: {
headers: AllowedHeaders;
};
}
declare function track(eventName: string, properties?: Record<string, AllowedPropertyValues>, options?: Options): Promise<void>;
export { track };
+204
View File
@@ -0,0 +1,204 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name2 in all)
__defProp(target, name2, { get: all[name2], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/server/index.ts
var server_exports = {};
__export(server_exports, {
track: () => track
});
module.exports = __toCommonJS(server_exports);
// package.json
var name = "@vercel/analytics";
var version = "2.0.1";
// src/utils.ts
function isBrowser() {
return typeof window !== "undefined";
}
function detectEnvironment() {
try {
const env = process.env.NODE_ENV;
if (env === "development" || env === "test") {
return "development";
}
} catch {
}
return "production";
}
function getMode() {
const mode = isBrowser() ? window.vam : detectEnvironment();
return mode || "production";
}
function isProduction() {
return getMode() === "production";
}
function removeKey(key, { [key]: _, ...rest }) {
return rest;
}
function parseProperties(properties, options) {
if (!properties) return void 0;
let props = properties;
const errorProperties = [];
for (const [key, value] of Object.entries(properties)) {
if (typeof value === "object" && value !== null) {
if (options.strip) {
props = removeKey(key, props);
} else {
errorProperties.push(key);
}
}
}
if (errorProperties.length > 0 && !options.strip) {
throw Error(
`The following properties are not valid: ${errorProperties.join(
", "
)}. Only strings, numbers, booleans, and null are allowed.`
);
}
return props;
}
// src/server/index.ts
function isHeaders(headers) {
if (!headers) return false;
return typeof headers.entries === "function";
}
var symbol = Symbol.for("@vercel/request-context");
var logPrefix = "[Vercel Web Analytics]";
async function track(eventName, properties, options) {
var _a;
const ENDPOINT = process.env.VERCEL_WEB_ANALYTICS_ENDPOINT || process.env.VERCEL_URL;
const DISABLE_LOGS = Boolean(process.env.VERCEL_WEB_ANALYTICS_DISABLE_LOGS);
const BYPASS_SECRET = process.env.VERCEL_AUTOMATION_BYPASS_SECRET;
if (typeof window !== "undefined") {
if (!isProduction()) {
throw new Error(
`${logPrefix} It seems like you imported the \`track\` function from \`@vercel/web-analytics/server\` in a browser environment. This function is only meant to be used in a server environment.`
);
}
return;
}
const props = parseProperties(properties, {
strip: isProduction()
});
if (!ENDPOINT) {
if (isProduction()) {
console.log(
`${logPrefix} Can't find VERCEL_URL in environment variables.`
);
} else if (!DISABLE_LOGS) {
console.log(
`${logPrefix} Track "${eventName}" ${props ? `with data ${JSON.stringify(props)}` : ""}`
);
}
return;
}
try {
const requestContext = (_a = globalThis[symbol]) == null ? void 0 : _a.get();
let headers;
if (options && "headers" in options) {
headers = options.headers;
} else if (options == null ? void 0 : options.request) {
headers = options.request.headers;
} else if (requestContext == null ? void 0 : requestContext.headers) {
headers = requestContext.headers;
}
let tmp = {};
if (headers && isHeaders(headers)) {
headers.forEach((value, key) => {
tmp[key] = value;
});
} else if (headers) {
tmp = headers;
}
const url = ENDPOINT.startsWith("http") ? ENDPOINT : new URL("/_vercel/insights/event", `https://${ENDPOINT}`).toString();
const body = {
o: (requestContext == null ? void 0 : requestContext.url) || tmp.referer || new URL(url).origin,
ts: Date.now(),
sdkn: `${name}/server`,
sdkv: version,
r: "",
en: eventName,
ed: props,
f: safeGetFlags(options == null ? void 0 : options.flags, requestContext)
};
const hasHeaders = Boolean(headers);
if (!hasHeaders) {
throw new Error(
"No session context found. Pass `request` or `headers` to the `track` function."
);
}
const promise = fetch(url, {
headers: {
"content-type": "application/json",
...hasHeaders ? {
"user-agent": tmp["user-agent"],
"x-vercel-ip": tmp["x-forwarded-for"],
"x-va-server": "1",
cookie: tmp.cookie
} : {
"x-va-server": "2"
},
...BYPASS_SECRET ? { "x-vercel-protection-bypass": BYPASS_SECRET } : {}
},
body: JSON.stringify(body),
method: "POST"
}).then((response) => response.text()).catch((err) => {
if (err instanceof Error && "response" in err) {
console.error(err.response);
} else {
console.error(err);
}
});
if (requestContext == null ? void 0 : requestContext.waitUntil) {
requestContext.waitUntil(promise);
} else {
await promise;
}
return void 0;
} catch (err) {
console.error(err);
}
}
function safeGetFlags(flags, requestContext) {
var _a;
try {
if (flags && !Array.isArray(flags)) {
return { p: flags };
}
if (!requestContext || !flags) return;
const plainFlags = {};
const resolvedPlainFlags = ((_a = requestContext.flags) == null ? void 0 : _a.getValues()) ?? {};
for (const flag of flags) {
if (typeof flag === "string") {
plainFlags[flag] = resolvedPlainFlags[flag];
} else {
Object.assign(plainFlags, flag);
}
}
return { p: plainFlags };
} catch {
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
track
});
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../src/server/index.ts","../../package.json","../../src/utils.ts"],"sourcesContent":["import { name as packageName, version } from '../../package.json';\nimport type {\n AllowedPropertyValues,\n FlagsDataInput,\n PlainFlags,\n} from '../types';\nimport { isProduction, parseProperties } from '../utils';\n\ntype HeadersObject = Record<string, string | string[] | undefined>;\ntype AllowedHeaders = Headers | HeadersObject;\n\nfunction isHeaders(headers?: AllowedHeaders): headers is Headers {\n if (!headers) return false;\n return typeof (headers as HeadersObject).entries === 'function';\n}\n\ninterface Options {\n flags?: FlagsDataInput;\n headers?: AllowedHeaders;\n request?: { headers: AllowedHeaders };\n}\n\ninterface RequestContext {\n get: () => {\n headers: Record<string, string | undefined>;\n url: string;\n waitUntil?: (promise: Promise<unknown>) => void;\n flags?: {\n getValues: () => PlainFlags;\n reportValue: (key: string, value: unknown) => void;\n };\n };\n}\n\nconst symbol = Symbol.for('@vercel/request-context');\nconst logPrefix = '[Vercel Web Analytics]';\n\nexport async function track(\n eventName: string,\n properties?: Record<string, AllowedPropertyValues>,\n options?: Options,\n): Promise<void> {\n const ENDPOINT =\n process.env.VERCEL_WEB_ANALYTICS_ENDPOINT || process.env.VERCEL_URL;\n const DISABLE_LOGS = Boolean(process.env.VERCEL_WEB_ANALYTICS_DISABLE_LOGS);\n const BYPASS_SECRET = process.env.VERCEL_AUTOMATION_BYPASS_SECRET;\n\n if (typeof window !== 'undefined') {\n if (!isProduction()) {\n throw new Error(\n `${logPrefix} It seems like you imported the \\`track\\` function from \\`@vercel/web-analytics/server\\` in a browser environment. This function is only meant to be used in a server environment.`,\n );\n }\n\n return;\n }\n\n const props = parseProperties(properties, {\n strip: isProduction(),\n });\n\n if (!ENDPOINT) {\n if (isProduction()) {\n console.log(\n `${logPrefix} Can't find VERCEL_URL in environment variables.`,\n );\n } else if (!DISABLE_LOGS) {\n console.log(\n `${logPrefix} Track \"${eventName}\" ${\n props ? `with data ${JSON.stringify(props)}` : ''\n }`,\n );\n }\n return;\n }\n try {\n const requestContext = (\n (globalThis as never)[symbol] as RequestContext | undefined\n )?.get();\n\n let headers: AllowedHeaders | undefined;\n\n if (options && 'headers' in options) {\n headers = options.headers;\n } else if (options?.request) {\n headers = options.request.headers;\n } else if (requestContext?.headers) {\n // not explicitly passed in context, so take it from async storage\n headers = requestContext.headers;\n }\n\n let tmp: HeadersObject = {};\n if (headers && isHeaders(headers)) {\n headers.forEach((value, key) => {\n tmp[key] = value;\n });\n } else if (headers) {\n tmp = headers;\n }\n\n const url = ENDPOINT.startsWith('http')\n ? ENDPOINT\n : new URL('/_vercel/insights/event', `https://${ENDPOINT}`).toString();\n\n const body = {\n o: requestContext?.url || (tmp.referer as string) || new URL(url).origin,\n ts: Date.now(),\n sdkn: `${packageName}/server`,\n sdkv: version,\n r: '',\n en: eventName,\n ed: props,\n f: safeGetFlags(options?.flags, requestContext),\n };\n\n const hasHeaders = Boolean(headers);\n\n if (!hasHeaders) {\n throw new Error(\n 'No session context found. Pass `request` or `headers` to the `track` function.',\n );\n }\n\n const promise = fetch(url, {\n headers: {\n 'content-type': 'application/json',\n ...(hasHeaders\n ? {\n 'user-agent': tmp['user-agent'] as string,\n 'x-vercel-ip': tmp['x-forwarded-for'] as string,\n 'x-va-server': '1',\n cookie: tmp.cookie as string,\n }\n : {\n 'x-va-server': '2',\n }),\n ...(BYPASS_SECRET\n ? { 'x-vercel-protection-bypass': BYPASS_SECRET }\n : {}),\n },\n body: JSON.stringify(body),\n method: 'POST',\n })\n // We want to always consume the body; some cloud providers track fetch concurrency\n // and may not release the connection until the body is consumed.\n .then((response) => response.text())\n .catch((err: unknown) => {\n if (err instanceof Error && 'response' in err) {\n console.error(err.response);\n } else {\n console.error(err);\n }\n });\n\n if (requestContext?.waitUntil) {\n requestContext.waitUntil(promise);\n } else {\n await promise;\n }\n\n return void 0;\n } catch (err) {\n console.error(err);\n }\n}\n\nfunction safeGetFlags(\n flags: Options['flags'],\n requestContext?: ReturnType<RequestContext['geLine truncated
+177
View File
@@ -0,0 +1,177 @@
// package.json
var name = "@vercel/analytics";
var version = "2.0.1";
// src/utils.ts
function isBrowser() {
return typeof window !== "undefined";
}
function detectEnvironment() {
try {
const env = process.env.NODE_ENV;
if (env === "development" || env === "test") {
return "development";
}
} catch {
}
return "production";
}
function getMode() {
const mode = isBrowser() ? window.vam : detectEnvironment();
return mode || "production";
}
function isProduction() {
return getMode() === "production";
}
function removeKey(key, { [key]: _, ...rest }) {
return rest;
}
function parseProperties(properties, options) {
if (!properties) return void 0;
let props = properties;
const errorProperties = [];
for (const [key, value] of Object.entries(properties)) {
if (typeof value === "object" && value !== null) {
if (options.strip) {
props = removeKey(key, props);
} else {
errorProperties.push(key);
}
}
}
if (errorProperties.length > 0 && !options.strip) {
throw Error(
`The following properties are not valid: ${errorProperties.join(
", "
)}. Only strings, numbers, booleans, and null are allowed.`
);
}
return props;
}
// src/server/index.ts
function isHeaders(headers) {
if (!headers) return false;
return typeof headers.entries === "function";
}
var symbol = Symbol.for("@vercel/request-context");
var logPrefix = "[Vercel Web Analytics]";
async function track(eventName, properties, options) {
var _a;
const ENDPOINT = process.env.VERCEL_WEB_ANALYTICS_ENDPOINT || process.env.VERCEL_URL;
const DISABLE_LOGS = Boolean(process.env.VERCEL_WEB_ANALYTICS_DISABLE_LOGS);
const BYPASS_SECRET = process.env.VERCEL_AUTOMATION_BYPASS_SECRET;
if (typeof window !== "undefined") {
if (!isProduction()) {
throw new Error(
`${logPrefix} It seems like you imported the \`track\` function from \`@vercel/web-analytics/server\` in a browser environment. This function is only meant to be used in a server environment.`
);
}
return;
}
const props = parseProperties(properties, {
strip: isProduction()
});
if (!ENDPOINT) {
if (isProduction()) {
console.log(
`${logPrefix} Can't find VERCEL_URL in environment variables.`
);
} else if (!DISABLE_LOGS) {
console.log(
`${logPrefix} Track "${eventName}" ${props ? `with data ${JSON.stringify(props)}` : ""}`
);
}
return;
}
try {
const requestContext = (_a = globalThis[symbol]) == null ? void 0 : _a.get();
let headers;
if (options && "headers" in options) {
headers = options.headers;
} else if (options == null ? void 0 : options.request) {
headers = options.request.headers;
} else if (requestContext == null ? void 0 : requestContext.headers) {
headers = requestContext.headers;
}
let tmp = {};
if (headers && isHeaders(headers)) {
headers.forEach((value, key) => {
tmp[key] = value;
});
} else if (headers) {
tmp = headers;
}
const url = ENDPOINT.startsWith("http") ? ENDPOINT : new URL("/_vercel/insights/event", `https://${ENDPOINT}`).toString();
const body = {
o: (requestContext == null ? void 0 : requestContext.url) || tmp.referer || new URL(url).origin,
ts: Date.now(),
sdkn: `${name}/server`,
sdkv: version,
r: "",
en: eventName,
ed: props,
f: safeGetFlags(options == null ? void 0 : options.flags, requestContext)
};
const hasHeaders = Boolean(headers);
if (!hasHeaders) {
throw new Error(
"No session context found. Pass `request` or `headers` to the `track` function."
);
}
const promise = fetch(url, {
headers: {
"content-type": "application/json",
...hasHeaders ? {
"user-agent": tmp["user-agent"],
"x-vercel-ip": tmp["x-forwarded-for"],
"x-va-server": "1",
cookie: tmp.cookie
} : {
"x-va-server": "2"
},
...BYPASS_SECRET ? { "x-vercel-protection-bypass": BYPASS_SECRET } : {}
},
body: JSON.stringify(body),
method: "POST"
}).then((response) => response.text()).catch((err) => {
if (err instanceof Error && "response" in err) {
console.error(err.response);
} else {
console.error(err);
}
});
if (requestContext == null ? void 0 : requestContext.waitUntil) {
requestContext.waitUntil(promise);
} else {
await promise;
}
return void 0;
} catch (err) {
console.error(err);
}
}
function safeGetFlags(flags, requestContext) {
var _a;
try {
if (flags && !Array.isArray(flags)) {
return { p: flags };
}
if (!requestContext || !flags) return;
const plainFlags = {};
const resolvedPlainFlags = ((_a = requestContext.flags) == null ? void 0 : _a.getValues()) ?? {};
for (const flag of flags) {
if (typeof flag === "string") {
plainFlags[flag] = resolvedPlainFlags[flag];
} else {
Object.assign(plainFlags, flag);
}
}
return { p: plainFlags };
} catch {
}
}
export {
track
};
//# sourceMappingURL=index.mjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../package.json","../../src/utils.ts","../../src/server/index.ts"],"sourcesContent":["{\n \"name\": \"@vercel/analytics\",\n \"version\": \"2.0.1\",\n \"description\": \"Gain real-time traffic insights with Vercel Web Analytics\",\n \"keywords\": [\n \"analytics\",\n \"vercel\"\n ],\n \"repository\": {\n \"url\": \"github:vercel/analytics\",\n \"directory\": \"packages/web\"\n },\n \"license\": \"MIT\",\n \"exports\": {\n \"./package.json\": \"./package.json\",\n \".\": {\n \"browser\": \"./dist/index.mjs\",\n \"import\": \"./dist/index.mjs\",\n \"require\": \"./dist/index.js\"\n },\n \"./astro\": {\n \"import\": \"./dist/astro/component.ts\"\n },\n \"./next\": {\n \"browser\": \"./dist/next/index.mjs\",\n \"import\": \"./dist/next/index.mjs\",\n \"require\": \"./dist/next/index.js\"\n },\n \"./nuxt\": {\n \"import\": \"./dist/nuxt/index.mjs\",\n \"require\": \"./dist/nuxt/index.js\"\n },\n \"./nuxt/runtime\": {\n \"browser\": \"./dist/nuxt/runtime/index.mjs\",\n \"import\": \"./dist/nuxt/runtime/index.mjs\",\n \"require\": \"./dist/nuxt/runtime/index.js\"\n },\n \"./react\": {\n \"browser\": \"./dist/react/index.mjs\",\n \"import\": \"./dist/react/index.mjs\",\n \"require\": \"./dist/react/index.js\"\n },\n \"./remix\": {\n \"browser\": \"./dist/remix/index.mjs\",\n \"import\": \"./dist/remix/index.mjs\",\n \"require\": \"./dist/remix/index.js\"\n },\n \"./server\": {\n \"node\": \"./dist/server/index.mjs\",\n \"edge-light\": \"./dist/server/index.mjs\",\n \"import\": \"./dist/server/index.mjs\",\n \"require\": \"./dist/server/index.js\",\n \"default\": \"./dist/server/index.js\"\n },\n \"./sveltekit\": {\n \"svelte\": \"./dist/sveltekit/index.mjs\",\n \"types\": \"./dist/sveltekit/index.d.ts\"\n },\n \"./vue\": {\n \"browser\": \"./dist/vue/index.mjs\",\n \"import\": \"./dist/vue/index.mjs\",\n \"require\": \"./dist/vue/index.js\"\n }\n },\n \"main\": \"./dist/index.mjs\",\n \"types\": \"./dist/index.d.ts\",\n \"typesVersions\": {\n \"*\": {\n \"*\": [\n \"dist/index.d.ts\"\n ],\n \"next\": [\n \"dist/next/index.d.ts\"\n ],\n \"nuxt\": [\n \"dist/nuxt/index.d.ts\"\n ],\n \"nuxt/runtime\": [\n \"dist/nuxt/runtime/index.d.ts\"\n ],\n \"react\": [\n \"dist/react/index.d.ts\"\n ],\n \"remix\": [\n \"dist/remix/index.d.ts\"\n ],\n \"server\": [\n \"dist/server/index.d.ts\"\n ],\n \"sveltekit\": [\n \"dist/sveltekit/index.d.ts\"\n ],\n \"vue\": [\n \"dist/vue/index.d.ts\"\n ]\n }\n },\n \"scripts\": {\n \"build\": \"tsup && pnpm copy-astro\",\n \"copy-astro\": \"cp -R src/astro dist/\",\n \"dev\": \"pnpm copy-astro && tsup --watch\",\n \"test\": \"vitest\"\n },\n \"devDependencies\": {\n \"@nuxt/kit\": \"^4.2.0\",\n \"@nuxt/schema\": \"^4.2.0\",\n \"@swc/core\": \"^1.9.2\",\n \"@testing-library/jest-dom\": \"^6.9.1\",\n \"@testing-library/react\": \"^16.3.1\",\n \"@types/node\": \"^22.9.0\",\n \"@types/react\": \"^18.3.12\",\n \"server-only\": \"^0.0.1\",\n \"svelte\": \"^5.1.10\",\n \"tsup\": \"8.3.5\",\n \"vitest\": \"^4.0.16\",\n \"vue\": \"^3.5.12\",\n \"vue-router\": \"^4.4.5\"\n },\n \"peerDependencies\": {\n \"@remix-run/react\": \"^2\",\n \"@sveltejs/kit\": \"^1 || ^2\",\n \"next\": \">= 13\",\n \"nuxt\": \">= 3\",\n \"react\": \"^18 || ^19 || ^19.0.0-rc\",\n \"svelte\": \">= 4\",\n \"vue\": \"^3\",\n \"vue-router\": \"^4\"\n },\n \"peerDependenciesMeta\": {\n \"@remix-run/react\": {\n \"optional\": true\n },\n \"@sveltejs/kit\": {\n \"optional\": true\n },\n \"next\": {\n \"optional\": true\n },\n \"nuxt\": {\n \"optional\": true\n },\n \"react\": {\n \"optional\": true\n },\n \"svelte\": {\n \"optional\": true\n },\n \"vue\": {\n \"optional\": true\n },\n \"vue-router\": {\n \"optional\": true\n }\n }\n}\n","import { name as packageName, version } from '../package.json';\nimport type {\n AllowedPropertyValues,\n AnalyticsProps,\n BeforeSend,\n InjectProps,\n Mode,\n} from './types';\n\nexport function isBrowser(): boolean {\n return typeof window !== 'undefined';\n}\n\nfunction detectEnvironment(): 'development' | 'production' {\n try {\n const env = process.env.NODE_ENV;\n if (env === 'development' || env === 'test') {\n return 'development';\n }\n } catch {\n // do nothing, this is okay\n }\n return 'production';\n}\n\nexport function setMode(mode: Mode = 'auto'): void {\n if (mode === 'auto') {\n window.vam = detectEnvironment();\n return;\n }\n\n window.vam = mode;\n}\n\nexport functioLine truncated
+49
View File
@@ -0,0 +1,49 @@
interface PageViewEvent {
type: 'pageview';
url: string;
}
interface CustomEvent {
type: 'event';
url: string;
}
type BeforeSendEvent = PageViewEvent | CustomEvent;
type Mode = 'auto' | 'development' | 'production';
type AllowedPropertyValues = string | number | boolean | null | undefined;
type BeforeSend = (event: BeforeSendEvent) => BeforeSendEvent | null;
interface AnalyticsProps {
beforeSend?: BeforeSend;
debug?: boolean;
mode?: Mode;
scriptSrc?: string;
dsn?: string;
eventEndpoint?: string;
viewEndpoint?: string;
sessionEndpoint?: string;
endpoint?: string;
}
declare global {
interface Window {
va?: (event: 'beforeSend' | 'event' | 'pageview', properties?: unknown) => void;
vaq?: [string, unknown?][];
vai?: boolean;
vam?: Mode;
/** used by Astro component only */
webAnalyticsBeforeSend?: BeforeSend;
}
}
type PlainFlags = Record<string, unknown>;
type FlagsDataInput = (string | PlainFlags)[] | PlainFlags;
/**
* Tracks a custom event. Please refer to the [documentation](https://vercel.com/docs/concepts/analytics/custom-events) for more information on custom events.
* @param name - The name of the event.
* * Examples: `Purchase`, `Click Button`, or `Play Video`.
* @param [properties] - Additional properties of the event. Nested objects are not supported. Allowed values are `string`, `number`, `boolean`, and `null`.
*/
declare function track(name: string, properties?: Record<string, AllowedPropertyValues>, options?: {
flags?: FlagsDataInput;
}): void;
declare function injectAnalytics(props?: Omit<AnalyticsProps, 'framework'>): void;
export { type AnalyticsProps, type BeforeSend, type BeforeSendEvent, injectAnalytics, track };
+49
View File
@@ -0,0 +1,49 @@
interface PageViewEvent {
type: 'pageview';
url: string;
}
interface CustomEvent {
type: 'event';
url: string;
}
type BeforeSendEvent = PageViewEvent | CustomEvent;
type Mode = 'auto' | 'development' | 'production';
type AllowedPropertyValues = string | number | boolean | null | undefined;
type BeforeSend = (event: BeforeSendEvent) => BeforeSendEvent | null;
interface AnalyticsProps {
beforeSend?: BeforeSend;
debug?: boolean;
mode?: Mode;
scriptSrc?: string;
dsn?: string;
eventEndpoint?: string;
viewEndpoint?: string;
sessionEndpoint?: string;
endpoint?: string;
}
declare global {
interface Window {
va?: (event: 'beforeSend' | 'event' | 'pageview', properties?: unknown) => void;
vaq?: [string, unknown?][];
vai?: boolean;
vam?: Mode;
/** used by Astro component only */
webAnalyticsBeforeSend?: BeforeSend;
}
}
type PlainFlags = Record<string, unknown>;
type FlagsDataInput = (string | PlainFlags)[] | PlainFlags;
/**
* Tracks a custom event. Please refer to the [documentation](https://vercel.com/docs/concepts/analytics/custom-events) for more information on custom events.
* @param name - The name of the event.
* * Examples: `Purchase`, `Click Button`, or `Play Video`.
* @param [properties] - Additional properties of the event. Nested objects are not supported. Allowed values are `string`, `number`, `boolean`, and `null`.
*/
declare function track(name: string, properties?: Record<string, AllowedPropertyValues>, options?: {
flags?: FlagsDataInput;
}): void;
declare function injectAnalytics(props?: Omit<AnalyticsProps, 'framework'>): void;
export { type AnalyticsProps, type BeforeSend, type BeforeSendEvent, injectAnalytics, track };
+264
View File
@@ -0,0 +1,264 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name2 in all)
__defProp(target, name2, { get: all[name2], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/sveltekit/index.ts
var sveltekit_exports = {};
__export(sveltekit_exports, {
injectAnalytics: () => injectAnalytics,
track: () => track
});
module.exports = __toCommonJS(sveltekit_exports);
var import_environment = require("$app/environment");
var import_stores = require("$app/stores");
// src/queue.ts
var initQueue = () => {
if (window.va) return;
window.va = function a(...params) {
if (!window.vaq) window.vaq = [];
window.vaq.push(params);
};
};
// package.json
var name = "@vercel/analytics";
var version = "2.0.1";
// src/utils.ts
function isBrowser() {
return typeof window !== "undefined";
}
function detectEnvironment() {
try {
const env = process.env.NODE_ENV;
if (env === "development" || env === "test") {
return "development";
}
} catch {
}
return "production";
}
function setMode(mode = "auto") {
if (mode === "auto") {
window.vam = detectEnvironment();
return;
}
window.vam = mode;
}
function getMode() {
const mode = isBrowser() ? window.vam : detectEnvironment();
return mode || "production";
}
function isProduction() {
return getMode() === "production";
}
function isDevelopment() {
return getMode() === "development";
}
function removeKey(key, { [key]: _, ...rest }) {
return rest;
}
function parseProperties(properties, options) {
if (!properties) return void 0;
let props = properties;
const errorProperties = [];
for (const [key, value] of Object.entries(properties)) {
if (typeof value === "object" && value !== null) {
if (options.strip) {
props = removeKey(key, props);
} else {
errorProperties.push(key);
}
}
}
if (errorProperties.length > 0 && !options.strip) {
throw Error(
`The following properties are not valid: ${errorProperties.join(
", "
)}. Only strings, numbers, booleans, and null are allowed.`
);
}
return props;
}
function getScriptSrc(props) {
if (props.scriptSrc) {
return makeAbsolute(props.scriptSrc);
}
if (isDevelopment()) {
return "https://va.vercel-scripts.com/v1/script.debug.js";
}
if (props.basePath) {
return makeAbsolute(`${props.basePath}/insights/script.js`);
}
return "/_vercel/insights/script.js";
}
function loadProps(explicitProps, confString) {
var _a;
let props = explicitProps;
if (confString) {
try {
props = {
...(_a = JSON.parse(confString)) == null ? void 0 : _a.analytics,
...explicitProps
};
} catch {
}
}
setMode(props.mode);
const dataset = {
sdkn: name + (props.framework ? `/${props.framework}` : ""),
sdkv: version
};
if (props.disableAutoTrack) {
dataset.disableAutoTrack = "1";
}
if (props.viewEndpoint) {
dataset.viewEndpoint = makeAbsolute(props.viewEndpoint);
}
if (props.eventEndpoint) {
dataset.eventEndpoint = makeAbsolute(props.eventEndpoint);
}
if (props.sessionEndpoint) {
dataset.sessionEndpoint = makeAbsolute(props.sessionEndpoint);
}
if (isDevelopment() && props.debug === false) {
dataset.debug = "false";
}
if (props.dsn) {
dataset.dsn = props.dsn;
}
if (props.endpoint) {
dataset.endpoint = props.endpoint;
} else if (props.basePath) {
dataset.endpoint = makeAbsolute(`${props.basePath}/insights`);
}
return {
beforeSend: props.beforeSend,
src: getScriptSrc(props),
dataset
};
}
function makeAbsolute(url) {
return url.startsWith("http://") || url.startsWith("https://") || url.startsWith("/") ? url : `/${url}`;
}
// src/generic.ts
function inject(props = {
debug: true
}, confString) {
var _a;
if (!isBrowser()) return;
const { beforeSend, src, dataset } = loadProps(props, confString);
initQueue();
if (beforeSend) {
(_a = window.va) == null ? void 0 : _a.call(window, "beforeSend", beforeSend);
}
if (document.head.querySelector(`script[src*="${src}"]`)) return;
const script = document.createElement("script");
script.src = src;
for (const [key, value] of Object.entries(dataset)) {
script.dataset[key] = value;
}
script.defer = true;
script.onerror = () => {
const errorMessage = isDevelopment() ? "Please check if any ad blockers are enabled and try again." : "Be sure to enable Web Analytics for your project and deploy again. See https://vercel.com/docs/analytics/quickstart for more information.";
console.log(
`[Vercel Web Analytics] Failed to load script from ${src}. ${errorMessage}`
);
};
document.head.appendChild(script);
}
function track(name2, properties, options) {
var _a, _b;
if (!isBrowser()) {
const msg = "[Vercel Web Analytics] Please import `track` from `@vercel/analytics/server` when using this function in a server environment";
if (isProduction()) {
console.warn(msg);
} else {
throw new Error(msg);
}
return;
}
if (!properties) {
(_a = window.va) == null ? void 0 : _a.call(window, "event", { name: name2, options });
return;
}
try {
const props = parseProperties(properties, {
strip: isProduction()
});
(_b = window.va) == null ? void 0 : _b.call(window, "event", {
name: name2,
data: props,
options
});
} catch (err) {
if (err instanceof Error && isDevelopment()) {
console.error(err);
}
}
}
function pageview({
route,
path
}) {
var _a;
(_a = window.va) == null ? void 0 : _a.call(window, "pageview", { route, path });
}
// src/sveltekit/utils.ts
var import_meta = {};
function getBasePath() {
try {
return import_meta.env.VITE_VERCEL_OBSERVABILITY_BASEPATH;
} catch {
}
}
function getConfigString() {
try {
return import_meta.env.VITE_VERCEL_OBSERVABILITY_CLIENT_CONFIG;
} catch {
}
}
// src/sveltekit/index.ts
function injectAnalytics(props = {}) {
if (import_environment.browser) {
inject(
{
...props,
basePath: getBasePath(),
disableAutoTrack: true,
framework: "sveltekit"
},
getConfigString()
);
import_stores.page.subscribe(({ route, url }) => {
if (route == null ? void 0 : route.id) {
pageview({ route: route.id, path: url.pathname });
}
});
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
injectAnalytics,
track
});
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../src/sveltekit/index.ts","../../src/queue.ts","../../package.json","../../src/utils.ts","../../src/generic.ts","../../src/sveltekit/utils.ts"],"sourcesContent":["import type {} from '@sveltejs/kit';\nimport { browser } from '$app/environment';\nimport { page } from '$app/stores';\nimport { inject, pageview, track } from '../generic';\nimport type { AnalyticsProps, BeforeSend, BeforeSendEvent } from '../types';\nimport { getBasePath, getConfigString } from './utils';\n\nfunction injectAnalytics(props: Omit<AnalyticsProps, 'framework'> = {}): void {\n if (browser) {\n inject(\n {\n ...props,\n basePath: getBasePath(),\n disableAutoTrack: true,\n framework: 'sveltekit',\n },\n getConfigString(),\n );\n\n page.subscribe(({ route, url }) => {\n if (route?.id) {\n pageview({ route: route.id, path: url.pathname });\n }\n });\n }\n}\n\nexport { injectAnalytics, track };\nexport type { AnalyticsProps, BeforeSend, BeforeSendEvent };\n","export const initQueue = (): void => {\n // initialize va until script is loaded\n if (window.va) return;\n\n window.va = function a(...params): void {\n if (!window.vaq) window.vaq = [];\n window.vaq.push(params);\n };\n};\n","{\n \"name\": \"@vercel/analytics\",\n \"version\": \"2.0.1\",\n \"description\": \"Gain real-time traffic insights with Vercel Web Analytics\",\n \"keywords\": [\n \"analytics\",\n \"vercel\"\n ],\n \"repository\": {\n \"url\": \"github:vercel/analytics\",\n \"directory\": \"packages/web\"\n },\n \"license\": \"MIT\",\n \"exports\": {\n \"./package.json\": \"./package.json\",\n \".\": {\n \"browser\": \"./dist/index.mjs\",\n \"import\": \"./dist/index.mjs\",\n \"require\": \"./dist/index.js\"\n },\n \"./astro\": {\n \"import\": \"./dist/astro/component.ts\"\n },\n \"./next\": {\n \"browser\": \"./dist/next/index.mjs\",\n \"import\": \"./dist/next/index.mjs\",\n \"require\": \"./dist/next/index.js\"\n },\n \"./nuxt\": {\n \"import\": \"./dist/nuxt/index.mjs\",\n \"require\": \"./dist/nuxt/index.js\"\n },\n \"./nuxt/runtime\": {\n \"browser\": \"./dist/nuxt/runtime/index.mjs\",\n \"import\": \"./dist/nuxt/runtime/index.mjs\",\n \"require\": \"./dist/nuxt/runtime/index.js\"\n },\n \"./react\": {\n \"browser\": \"./dist/react/index.mjs\",\n \"import\": \"./dist/react/index.mjs\",\n \"require\": \"./dist/react/index.js\"\n },\n \"./remix\": {\n \"browser\": \"./dist/remix/index.mjs\",\n \"import\": \"./dist/remix/index.mjs\",\n \"require\": \"./dist/remix/index.js\"\n },\n \"./server\": {\n \"node\": \"./dist/server/index.mjs\",\n \"edge-light\": \"./dist/server/index.mjs\",\n \"import\": \"./dist/server/index.mjs\",\n \"require\": \"./dist/server/index.js\",\n \"default\": \"./dist/server/index.js\"\n },\n \"./sveltekit\": {\n \"svelte\": \"./dist/sveltekit/index.mjs\",\n \"types\": \"./dist/sveltekit/index.d.ts\"\n },\n \"./vue\": {\n \"browser\": \"./dist/vue/index.mjs\",\n \"import\": \"./dist/vue/index.mjs\",\n \"require\": \"./dist/vue/index.js\"\n }\n },\n \"main\": \"./dist/index.mjs\",\n \"types\": \"./dist/index.d.ts\",\n \"typesVersions\": {\n \"*\": {\n \"*\": [\n \"dist/index.d.ts\"\n ],\n \"next\": [\n \"dist/next/index.d.ts\"\n ],\n \"nuxt\": [\n \"dist/nuxt/index.d.ts\"\n ],\n \"nuxt/runtime\": [\n \"dist/nuxt/runtime/index.d.ts\"\n ],\n \"react\": [\n \"dist/react/index.d.ts\"\n ],\n \"remix\": [\n \"dist/remix/index.d.ts\"\n ],\n \"server\": [\n \"dist/server/index.d.ts\"\n ],\n \"sveltekit\": [\n \"dist/sveltekit/index.d.ts\"\n ],\n \"vue\": [\n \"dist/vue/index.d.ts\"\n ]\n }\n },\n \"scripts\": {\n \"build\": \"tsup && pnpm copy-astro\",\n \"copy-astro\": \"cp -R src/astro dist/\",\n \"dev\": \"pnpm copy-astro && tsup --watch\",\n \"test\": \"vitest\"\n },\n \"devDependencies\": {\n \"@nuxt/kit\": \"^4.2.0\",\n \"@nuxt/schema\": \"^4.2.0\",\n \"@swc/core\": \"^1.9.2\",\n \"@testing-library/jest-dom\": \"^6.9.1\",\n \"@testing-library/react\": \"^16.3.1\",\n \"@types/node\": \"^22.9.0\",\n \"@types/react\": \"^18.3.12\",\n \"server-only\": \"^0.0.1\",\n \"svelte\": \"^5.1.10\",\n \"tsup\": \"8.3.5\",\n \"vitest\": \"^4.0.16\",\n \"vue\": \"^3.5.12\",\n \"vue-router\": \"^4.4.5\"\n },\n \"peerDependencies\": {\n \"@remix-run/react\": \"^2\",\n \"@sveltejs/kit\": \"^1 || ^2\",\n \"next\": \">= 13\",\n \"nuxt\": \">= 3\",\n \"react\": \"^18 || ^19 || ^19.0.0-rc\",\n \"svelte\": \">= 4\",\n \"vue\": \"^3\",\n \"vue-router\": \"^4\"\n },\n \"peerDependenciesMeta\": {\n \"@rLine truncated
+237
View File
@@ -0,0 +1,237 @@
// src/sveltekit/index.ts
import { browser } from "$app/environment";
import { page } from "$app/stores";
// src/queue.ts
var initQueue = () => {
if (window.va) return;
window.va = function a(...params) {
if (!window.vaq) window.vaq = [];
window.vaq.push(params);
};
};
// package.json
var name = "@vercel/analytics";
var version = "2.0.1";
// src/utils.ts
function isBrowser() {
return typeof window !== "undefined";
}
function detectEnvironment() {
try {
const env = process.env.NODE_ENV;
if (env === "development" || env === "test") {
return "development";
}
} catch {
}
return "production";
}
function setMode(mode = "auto") {
if (mode === "auto") {
window.vam = detectEnvironment();
return;
}
window.vam = mode;
}
function getMode() {
const mode = isBrowser() ? window.vam : detectEnvironment();
return mode || "production";
}
function isProduction() {
return getMode() === "production";
}
function isDevelopment() {
return getMode() === "development";
}
function removeKey(key, { [key]: _, ...rest }) {
return rest;
}
function parseProperties(properties, options) {
if (!properties) return void 0;
let props = properties;
const errorProperties = [];
for (const [key, value] of Object.entries(properties)) {
if (typeof value === "object" && value !== null) {
if (options.strip) {
props = removeKey(key, props);
} else {
errorProperties.push(key);
}
}
}
if (errorProperties.length > 0 && !options.strip) {
throw Error(
`The following properties are not valid: ${errorProperties.join(
", "
)}. Only strings, numbers, booleans, and null are allowed.`
);
}
return props;
}
function getScriptSrc(props) {
if (props.scriptSrc) {
return makeAbsolute(props.scriptSrc);
}
if (isDevelopment()) {
return "https://va.vercel-scripts.com/v1/script.debug.js";
}
if (props.basePath) {
return makeAbsolute(`${props.basePath}/insights/script.js`);
}
return "/_vercel/insights/script.js";
}
function loadProps(explicitProps, confString) {
var _a;
let props = explicitProps;
if (confString) {
try {
props = {
...(_a = JSON.parse(confString)) == null ? void 0 : _a.analytics,
...explicitProps
};
} catch {
}
}
setMode(props.mode);
const dataset = {
sdkn: name + (props.framework ? `/${props.framework}` : ""),
sdkv: version
};
if (props.disableAutoTrack) {
dataset.disableAutoTrack = "1";
}
if (props.viewEndpoint) {
dataset.viewEndpoint = makeAbsolute(props.viewEndpoint);
}
if (props.eventEndpoint) {
dataset.eventEndpoint = makeAbsolute(props.eventEndpoint);
}
if (props.sessionEndpoint) {
dataset.sessionEndpoint = makeAbsolute(props.sessionEndpoint);
}
if (isDevelopment() && props.debug === false) {
dataset.debug = "false";
}
if (props.dsn) {
dataset.dsn = props.dsn;
}
if (props.endpoint) {
dataset.endpoint = props.endpoint;
} else if (props.basePath) {
dataset.endpoint = makeAbsolute(`${props.basePath}/insights`);
}
return {
beforeSend: props.beforeSend,
src: getScriptSrc(props),
dataset
};
}
function makeAbsolute(url) {
return url.startsWith("http://") || url.startsWith("https://") || url.startsWith("/") ? url : `/${url}`;
}
// src/generic.ts
function inject(props = {
debug: true
}, confString) {
var _a;
if (!isBrowser()) return;
const { beforeSend, src, dataset } = loadProps(props, confString);
initQueue();
if (beforeSend) {
(_a = window.va) == null ? void 0 : _a.call(window, "beforeSend", beforeSend);
}
if (document.head.querySelector(`script[src*="${src}"]`)) return;
const script = document.createElement("script");
script.src = src;
for (const [key, value] of Object.entries(dataset)) {
script.dataset[key] = value;
}
script.defer = true;
script.onerror = () => {
const errorMessage = isDevelopment() ? "Please check if any ad blockers are enabled and try again." : "Be sure to enable Web Analytics for your project and deploy again. See https://vercel.com/docs/analytics/quickstart for more information.";
console.log(
`[Vercel Web Analytics] Failed to load script from ${src}. ${errorMessage}`
);
};
document.head.appendChild(script);
}
function track(name2, properties, options) {
var _a, _b;
if (!isBrowser()) {
const msg = "[Vercel Web Analytics] Please import `track` from `@vercel/analytics/server` when using this function in a server environment";
if (isProduction()) {
console.warn(msg);
} else {
throw new Error(msg);
}
return;
}
if (!properties) {
(_a = window.va) == null ? void 0 : _a.call(window, "event", { name: name2, options });
return;
}
try {
const props = parseProperties(properties, {
strip: isProduction()
});
(_b = window.va) == null ? void 0 : _b.call(window, "event", {
name: name2,
data: props,
options
});
} catch (err) {
if (err instanceof Error && isDevelopment()) {
console.error(err);
}
}
}
function pageview({
route,
path
}) {
var _a;
(_a = window.va) == null ? void 0 : _a.call(window, "pageview", { route, path });
}
// src/sveltekit/utils.ts
function getBasePath() {
try {
return import.meta.env.VITE_VERCEL_OBSERVABILITY_BASEPATH;
} catch {
}
}
function getConfigString() {
try {
return import.meta.env.VITE_VERCEL_OBSERVABILITY_CLIENT_CONFIG;
} catch {
}
}
// src/sveltekit/index.ts
function injectAnalytics(props = {}) {
if (browser) {
inject(
{
...props,
basePath: getBasePath(),
disableAutoTrack: true,
framework: "sveltekit"
},
getConfigString()
);
page.subscribe(({ route, url }) => {
if (route == null ? void 0 : route.id) {
pageview({ route: route.id, path: url.pathname });
}
});
}
}
export {
injectAnalytics,
track
};
//# sourceMappingURL=index.mjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../src/sveltekit/index.ts","../../src/queue.ts","../../package.json","../../src/utils.ts","../../src/generic.ts","../../src/sveltekit/utils.ts"],"sourcesContent":["import type {} from '@sveltejs/kit';\nimport { browser } from '$app/environment';\nimport { page } from '$app/stores';\nimport { inject, pageview, track } from '../generic';\nimport type { AnalyticsProps, BeforeSend, BeforeSendEvent } from '../types';\nimport { getBasePath, getConfigString } from './utils';\n\nfunction injectAnalytics(props: Omit<AnalyticsProps, 'framework'> = {}): void {\n if (browser) {\n inject(\n {\n ...props,\n basePath: getBasePath(),\n disableAutoTrack: true,\n framework: 'sveltekit',\n },\n getConfigString(),\n );\n\n page.subscribe(({ route, url }) => {\n if (route?.id) {\n pageview({ route: route.id, path: url.pathname });\n }\n });\n }\n}\n\nexport { injectAnalytics, track };\nexport type { AnalyticsProps, BeforeSend, BeforeSendEvent };\n","export const initQueue = (): void => {\n // initialize va until script is loaded\n if (window.va) return;\n\n window.va = function a(...params): void {\n if (!window.vaq) window.vaq = [];\n window.vaq.push(params);\n };\n};\n","{\n \"name\": \"@vercel/analytics\",\n \"version\": \"2.0.1\",\n \"description\": \"Gain real-time traffic insights with Vercel Web Analytics\",\n \"keywords\": [\n \"analytics\",\n \"vercel\"\n ],\n \"repository\": {\n \"url\": \"github:vercel/analytics\",\n \"directory\": \"packages/web\"\n },\n \"license\": \"MIT\",\n \"exports\": {\n \"./package.json\": \"./package.json\",\n \".\": {\n \"browser\": \"./dist/index.mjs\",\n \"import\": \"./dist/index.mjs\",\n \"require\": \"./dist/index.js\"\n },\n \"./astro\": {\n \"import\": \"./dist/astro/component.ts\"\n },\n \"./next\": {\n \"browser\": \"./dist/next/index.mjs\",\n \"import\": \"./dist/next/index.mjs\",\n \"require\": \"./dist/next/index.js\"\n },\n \"./nuxt\": {\n \"import\": \"./dist/nuxt/index.mjs\",\n \"require\": \"./dist/nuxt/index.js\"\n },\n \"./nuxt/runtime\": {\n \"browser\": \"./dist/nuxt/runtime/index.mjs\",\n \"import\": \"./dist/nuxt/runtime/index.mjs\",\n \"require\": \"./dist/nuxt/runtime/index.js\"\n },\n \"./react\": {\n \"browser\": \"./dist/react/index.mjs\",\n \"import\": \"./dist/react/index.mjs\",\n \"require\": \"./dist/react/index.js\"\n },\n \"./remix\": {\n \"browser\": \"./dist/remix/index.mjs\",\n \"import\": \"./dist/remix/index.mjs\",\n \"require\": \"./dist/remix/index.js\"\n },\n \"./server\": {\n \"node\": \"./dist/server/index.mjs\",\n \"edge-light\": \"./dist/server/index.mjs\",\n \"import\": \"./dist/server/index.mjs\",\n \"require\": \"./dist/server/index.js\",\n \"default\": \"./dist/server/index.js\"\n },\n \"./sveltekit\": {\n \"svelte\": \"./dist/sveltekit/index.mjs\",\n \"types\": \"./dist/sveltekit/index.d.ts\"\n },\n \"./vue\": {\n \"browser\": \"./dist/vue/index.mjs\",\n \"import\": \"./dist/vue/index.mjs\",\n \"require\": \"./dist/vue/index.js\"\n }\n },\n \"main\": \"./dist/index.mjs\",\n \"types\": \"./dist/index.d.ts\",\n \"typesVersions\": {\n \"*\": {\n \"*\": [\n \"dist/index.d.ts\"\n ],\n \"next\": [\n \"dist/next/index.d.ts\"\n ],\n \"nuxt\": [\n \"dist/nuxt/index.d.ts\"\n ],\n \"nuxt/runtime\": [\n \"dist/nuxt/runtime/index.d.ts\"\n ],\n \"react\": [\n \"dist/react/index.d.ts\"\n ],\n \"remix\": [\n \"dist/remix/index.d.ts\"\n ],\n \"server\": [\n \"dist/server/index.d.ts\"\n ],\n \"sveltekit\": [\n \"dist/sveltekit/index.d.ts\"\n ],\n \"vue\": [\n \"dist/vue/index.d.ts\"\n ]\n }\n },\n \"scripts\": {\n \"build\": \"tsup && pnpm copy-astro\",\n \"copy-astro\": \"cp -R src/astro dist/\",\n \"dev\": \"pnpm copy-astro && tsup --watch\",\n \"test\": \"vitest\"\n },\n \"devDependencies\": {\n \"@nuxt/kit\": \"^4.2.0\",\n \"@nuxt/schema\": \"^4.2.0\",\n \"@swc/core\": \"^1.9.2\",\n \"@testing-library/jest-dom\": \"^6.9.1\",\n \"@testing-library/react\": \"^16.3.1\",\n \"@types/node\": \"^22.9.0\",\n \"@types/react\": \"^18.3.12\",\n \"server-only\": \"^0.0.1\",\n \"svelte\": \"^5.1.10\",\n \"tsup\": \"8.3.5\",\n \"vitest\": \"^4.0.16\",\n \"vue\": \"^3.5.12\",\n \"vue-router\": \"^4.4.5\"\n },\n \"peerDependencies\": {\n \"@remix-run/react\": \"^2\",\n \"@sveltejs/kit\": \"^1 || ^2\",\n \"next\": \">= 13\",\n \"nuxt\": \">= 3\",\n \"react\": \"^18 || ^19 || ^19.0.0-rc\",\n \"svelte\": \">= 4\",\n \"vue\": \"^3\",\n \"vue-router\": \"^4\"\n },\n \"peerDependenciesMeta\": {\n \"@rLine truncated
+36
View File
@@ -0,0 +1,36 @@
interface PageViewEvent {
type: 'pageview';
url: string;
}
interface CustomEvent {
type: 'event';
url: string;
}
type BeforeSendEvent = PageViewEvent | CustomEvent;
type Mode = 'auto' | 'development' | 'production';
type BeforeSend = (event: BeforeSendEvent) => BeforeSendEvent | null;
interface AnalyticsProps {
beforeSend?: BeforeSend;
debug?: boolean;
mode?: Mode;
scriptSrc?: string;
dsn?: string;
eventEndpoint?: string;
viewEndpoint?: string;
sessionEndpoint?: string;
endpoint?: string;
}
declare global {
interface Window {
va?: (event: 'beforeSend' | 'event' | 'pageview', properties?: unknown) => void;
vaq?: [string, unknown?][];
vai?: boolean;
vam?: Mode;
/** used by Astro component only */
webAnalyticsBeforeSend?: BeforeSend;
}
}
declare const Analytics: any;
export { Analytics, type AnalyticsProps, type BeforeSend, type BeforeSendEvent };
+36
View File
@@ -0,0 +1,36 @@
interface PageViewEvent {
type: 'pageview';
url: string;
}
interface CustomEvent {
type: 'event';
url: string;
}
type BeforeSendEvent = PageViewEvent | CustomEvent;
type Mode = 'auto' | 'development' | 'production';
type BeforeSend = (event: BeforeSendEvent) => BeforeSendEvent | null;
interface AnalyticsProps {
beforeSend?: BeforeSend;
debug?: boolean;
mode?: Mode;
scriptSrc?: string;
dsn?: string;
eventEndpoint?: string;
viewEndpoint?: string;
sessionEndpoint?: string;
endpoint?: string;
}
declare global {
interface Window {
va?: (event: 'beforeSend' | 'event' | 'pageview', properties?: unknown) => void;
vaq?: [string, unknown?][];
vai?: boolean;
vam?: Mode;
/** used by Astro component only */
webAnalyticsBeforeSend?: BeforeSend;
}
}
declare const Analytics: any;
export { Analytics, type AnalyticsProps, type BeforeSend, type BeforeSendEvent };
+260
View File
@@ -0,0 +1,260 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name2 in all)
__defProp(target, name2, { get: all[name2], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/vue/index.ts
var vue_exports = {};
__export(vue_exports, {
Analytics: () => Analytics
});
module.exports = __toCommonJS(vue_exports);
// src/vue/create-component.ts
var import_vue = require("vue");
var import_vue_router = require("vue-router");
// src/queue.ts
var initQueue = () => {
if (window.va) return;
window.va = function a(...params) {
if (!window.vaq) window.vaq = [];
window.vaq.push(params);
};
};
// package.json
var name = "@vercel/analytics";
var version = "2.0.1";
// src/utils.ts
function isBrowser() {
return typeof window !== "undefined";
}
function detectEnvironment() {
try {
const env = process.env.NODE_ENV;
if (env === "development" || env === "test") {
return "development";
}
} catch {
}
return "production";
}
function setMode(mode = "auto") {
if (mode === "auto") {
window.vam = detectEnvironment();
return;
}
window.vam = mode;
}
function getMode() {
const mode = isBrowser() ? window.vam : detectEnvironment();
return mode || "production";
}
function isDevelopment() {
return getMode() === "development";
}
function computeRoute(pathname, pathParams) {
if (!pathname || !pathParams) {
return pathname;
}
let result = pathname;
try {
const entries = Object.entries(pathParams);
for (const [key, value] of entries) {
if (!Array.isArray(value)) {
const matcher = turnValueToRegExp(value);
if (matcher.test(result)) {
result = result.replace(matcher, `/[${key}]`);
}
}
}
for (const [key, value] of entries) {
if (Array.isArray(value)) {
const matcher = turnValueToRegExp(value.join("/"));
if (matcher.test(result)) {
result = result.replace(matcher, `/[...${key}]`);
}
}
}
return result;
} catch {
return pathname;
}
}
function turnValueToRegExp(value) {
return new RegExp(`/${escapeRegExp(value)}(?=[/?#]|$)`);
}
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function getScriptSrc(props) {
if (props.scriptSrc) {
return makeAbsolute(props.scriptSrc);
}
if (isDevelopment()) {
return "https://va.vercel-scripts.com/v1/script.debug.js";
}
if (props.basePath) {
return makeAbsolute(`${props.basePath}/insights/script.js`);
}
return "/_vercel/insights/script.js";
}
function loadProps(explicitProps, confString) {
var _a;
let props = explicitProps;
if (confString) {
try {
props = {
...(_a = JSON.parse(confString)) == null ? void 0 : _a.analytics,
...explicitProps
};
} catch {
}
}
setMode(props.mode);
const dataset = {
sdkn: name + (props.framework ? `/${props.framework}` : ""),
sdkv: version
};
if (props.disableAutoTrack) {
dataset.disableAutoTrack = "1";
}
if (props.viewEndpoint) {
dataset.viewEndpoint = makeAbsolute(props.viewEndpoint);
}
if (props.eventEndpoint) {
dataset.eventEndpoint = makeAbsolute(props.eventEndpoint);
}
if (props.sessionEndpoint) {
dataset.sessionEndpoint = makeAbsolute(props.sessionEndpoint);
}
if (isDevelopment() && props.debug === false) {
dataset.debug = "false";
}
if (props.dsn) {
dataset.dsn = props.dsn;
}
if (props.endpoint) {
dataset.endpoint = props.endpoint;
} else if (props.basePath) {
dataset.endpoint = makeAbsolute(`${props.basePath}/insights`);
}
return {
beforeSend: props.beforeSend,
src: getScriptSrc(props),
dataset
};
}
function makeAbsolute(url) {
return url.startsWith("http://") || url.startsWith("https://") || url.startsWith("/") ? url : `/${url}`;
}
// src/generic.ts
function inject(props = {
debug: true
}, confString) {
var _a;
if (!isBrowser()) return;
const { beforeSend, src, dataset } = loadProps(props, confString);
initQueue();
if (beforeSend) {
(_a = window.va) == null ? void 0 : _a.call(window, "beforeSend", beforeSend);
}
if (document.head.querySelector(`script[src*="${src}"]`)) return;
const script = document.createElement("script");
script.src = src;
for (const [key, value] of Object.entries(dataset)) {
script.dataset[key] = value;
}
script.defer = true;
script.onerror = () => {
const errorMessage = isDevelopment() ? "Please check if any ad blockers are enabled and try again." : "Be sure to enable Web Analytics for your project and deploy again. See https://vercel.com/docs/analytics/quickstart for more information.";
console.log(
`[Vercel Web Analytics] Failed to load script from ${src}. ${errorMessage}`
);
};
document.head.appendChild(script);
}
function pageview({
route,
path
}) {
var _a;
(_a = window.va) == null ? void 0 : _a.call(window, "pageview", { route, path });
}
// src/vue/utils.ts
var import_meta = {};
function getBasePath() {
try {
return import_meta.env.VITE_VERCEL_OBSERVABILITY_BASEPATH;
} catch {
}
}
function getConfigString() {
try {
return import_meta.env.VITE_VERCEL_OBSERVABILITY_CLIENT_CONFIG;
} catch {
}
}
// src/vue/create-component.ts
function createComponent(framework = "vue") {
return (0, import_vue.defineComponent)({
props: ["dsn", "beforeSend", "debug", "scriptSrc", "endpoint", "mode"],
setup(props) {
const route = (0, import_vue_router.useRoute)();
inject(
{
// trim out undefined values to avoid overriding config values
...Object.fromEntries(
Object.entries(props).filter(([_, v]) => v !== void 0)
),
basePath: getBasePath(),
// keep auto-tracking unless we have route support (Nuxt or vue-router).
disableAutoTrack: Boolean(route),
framework
},
getConfigString()
);
if (route && typeof window !== "undefined") {
const changeRoute = () => {
pageview({
route: computeRoute(route.path, route.params),
path: route.path
});
};
changeRoute();
(0, import_vue.watch)(route, changeRoute);
}
},
// Vue component must have a render function, or a template.
render() {
return null;
}
});
}
// src/vue/index.ts
var Analytics = createComponent();
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Analytics
});
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../src/vue/index.ts","../../src/vue/create-component.ts","../../src/queue.ts","../../package.json","../../src/utils.ts","../../src/generic.ts","../../src/vue/utils.ts"],"sourcesContent":["import type { AnalyticsProps, BeforeSend, BeforeSendEvent } from '../types';\nimport { createComponent } from './create-component';\n\nexport const Analytics = createComponent();\nexport type { AnalyticsProps, BeforeSend, BeforeSendEvent };\n","import { defineComponent, watch } from 'vue';\n// for barebone vue project, vite will issue a warning since 'vue-router' import can't be resolved,\nimport { useRoute } from 'vue-router';\nimport { type AnalyticsProps, inject, pageview } from '../generic';\nimport { computeRoute } from '../utils';\nimport { getBasePath, getConfigString } from './utils';\n\nexport function createComponent(\n framework = 'vue',\n): ReturnType<typeof defineComponent> {\n return defineComponent({\n props: ['dsn', 'beforeSend', 'debug', 'scriptSrc', 'endpoint', 'mode'],\n setup(props: Omit<AnalyticsProps, 'framework'>) {\n const route = useRoute();\n inject(\n {\n // trim out undefined values to avoid overriding config values\n ...Object.fromEntries(\n Object.entries(props).filter(([_, v]) => v !== undefined),\n ),\n basePath: getBasePath(),\n // keep auto-tracking unless we have route support (Nuxt or vue-router).\n disableAutoTrack: Boolean(route),\n framework,\n },\n getConfigString(),\n );\n if (route && typeof window !== 'undefined') {\n const changeRoute = (): void => {\n pageview({\n route: computeRoute(route.path, route.params),\n path: route.path,\n });\n };\n changeRoute();\n watch(route, changeRoute);\n }\n },\n // Vue component must have a render function, or a template.\n render() {\n return null;\n },\n });\n}\n","export const initQueue = (): void => {\n // initialize va until script is loaded\n if (window.va) return;\n\n window.va = function a(...params): void {\n if (!window.vaq) window.vaq = [];\n window.vaq.push(params);\n };\n};\n","{\n \"name\": \"@vercel/analytics\",\n \"version\": \"2.0.1\",\n \"description\": \"Gain real-time traffic insights with Vercel Web Analytics\",\n \"keywords\": [\n \"analytics\",\n \"vercel\"\n ],\n \"repository\": {\n \"url\": \"github:vercel/analytics\",\n \"directory\": \"packages/web\"\n },\n \"license\": \"MIT\",\n \"exports\": {\n \"./package.json\": \"./package.json\",\n \".\": {\n \"browser\": \"./dist/index.mjs\",\n \"import\": \"./dist/index.mjs\",\n \"require\": \"./dist/index.js\"\n },\n \"./astro\": {\n \"import\": \"./dist/astro/component.ts\"\n },\n \"./next\": {\n \"browser\": \"./dist/next/index.mjs\",\n \"import\": \"./dist/next/index.mjs\",\n \"require\": \"./dist/next/index.js\"\n },\n \"./nuxt\": {\n \"import\": \"./dist/nuxt/index.mjs\",\n \"require\": \"./dist/nuxt/index.js\"\n },\n \"./nuxt/runtime\": {\n \"browser\": \"./dist/nuxt/runtime/index.mjs\",\n \"import\": \"./dist/nuxt/runtime/index.mjs\",\n \"require\": \"./dist/nuxt/runtime/index.js\"\n },\n \"./react\": {\n \"browser\": \"./dist/react/index.mjs\",\n \"import\": \"./dist/react/index.mjs\",\n \"require\": \"./dist/react/index.js\"\n },\n \"./remix\": {\n \"browser\": \"./dist/remix/index.mjs\",\n \"import\": \"./dist/remix/index.mjs\",\n \"require\": \"./dist/remix/index.js\"\n },\n \"./server\": {\n \"node\": \"./dist/server/index.mjs\",\n \"edge-light\": \"./dist/server/index.mjs\",\n \"import\": \"./dist/server/index.mjs\",\n \"require\": \"./dist/server/index.js\",\n \"default\": \"./dist/server/index.js\"\n },\n \"./sveltekit\": {\n \"svelte\": \"./dist/sveltekit/index.mjs\",\n \"types\": \"./dist/sveltekit/index.d.ts\"\n },\n \"./vue\": {\n \"browser\": \"./dist/vue/index.mjs\",\n \"import\": \"./dist/vue/index.mjs\",\n \"require\": \"./dist/vue/index.js\"\n }\n },\n \"main\": \"./dist/index.mjs\",\n \"types\": \"./dist/index.d.ts\",\n \"typesVersions\": {\n \"*\": {\n \"*\": [\n \"dist/index.d.ts\"\n ],\n \"next\": [\n \"dist/next/index.d.ts\"\n ],\n \"nuxt\": [\n \"dist/nuxt/index.d.ts\"\n ],\n \"nuxt/runtime\": [\n \"dist/nuxt/runtime/index.d.ts\"\n ],\n \"react\": [\n \"dist/react/index.d.ts\"\n ],\n \"remix\": [\n \"dist/remix/index.d.ts\"\n ],\n \"server\": [\n \"dist/server/index.d.ts\"\n ],\n \"sveltekit\": [\n \"dist/sveltekit/index.d.ts\"\n ],\n \"vue\": [\n \"dist/vue/index.d.ts\"\n ]\n }\n },\n \"scripts\": {\n \"build\":Line truncated
+232
View File
@@ -0,0 +1,232 @@
// src/vue/create-component.ts
import { defineComponent, watch } from "vue";
import { useRoute } from "vue-router";
// src/queue.ts
var initQueue = () => {
if (window.va) return;
window.va = function a(...params) {
if (!window.vaq) window.vaq = [];
window.vaq.push(params);
};
};
// package.json
var name = "@vercel/analytics";
var version = "2.0.1";
// src/utils.ts
function isBrowser() {
return typeof window !== "undefined";
}
function detectEnvironment() {
try {
const env = process.env.NODE_ENV;
if (env === "development" || env === "test") {
return "development";
}
} catch {
}
return "production";
}
function setMode(mode = "auto") {
if (mode === "auto") {
window.vam = detectEnvironment();
return;
}
window.vam = mode;
}
function getMode() {
const mode = isBrowser() ? window.vam : detectEnvironment();
return mode || "production";
}
function isDevelopment() {
return getMode() === "development";
}
function computeRoute(pathname, pathParams) {
if (!pathname || !pathParams) {
return pathname;
}
let result = pathname;
try {
const entries = Object.entries(pathParams);
for (const [key, value] of entries) {
if (!Array.isArray(value)) {
const matcher = turnValueToRegExp(value);
if (matcher.test(result)) {
result = result.replace(matcher, `/[${key}]`);
}
}
}
for (const [key, value] of entries) {
if (Array.isArray(value)) {
const matcher = turnValueToRegExp(value.join("/"));
if (matcher.test(result)) {
result = result.replace(matcher, `/[...${key}]`);
}
}
}
return result;
} catch {
return pathname;
}
}
function turnValueToRegExp(value) {
return new RegExp(`/${escapeRegExp(value)}(?=[/?#]|$)`);
}
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function getScriptSrc(props) {
if (props.scriptSrc) {
return makeAbsolute(props.scriptSrc);
}
if (isDevelopment()) {
return "https://va.vercel-scripts.com/v1/script.debug.js";
}
if (props.basePath) {
return makeAbsolute(`${props.basePath}/insights/script.js`);
}
return "/_vercel/insights/script.js";
}
function loadProps(explicitProps, confString) {
var _a;
let props = explicitProps;
if (confString) {
try {
props = {
...(_a = JSON.parse(confString)) == null ? void 0 : _a.analytics,
...explicitProps
};
} catch {
}
}
setMode(props.mode);
const dataset = {
sdkn: name + (props.framework ? `/${props.framework}` : ""),
sdkv: version
};
if (props.disableAutoTrack) {
dataset.disableAutoTrack = "1";
}
if (props.viewEndpoint) {
dataset.viewEndpoint = makeAbsolute(props.viewEndpoint);
}
if (props.eventEndpoint) {
dataset.eventEndpoint = makeAbsolute(props.eventEndpoint);
}
if (props.sessionEndpoint) {
dataset.sessionEndpoint = makeAbsolute(props.sessionEndpoint);
}
if (isDevelopment() && props.debug === false) {
dataset.debug = "false";
}
if (props.dsn) {
dataset.dsn = props.dsn;
}
if (props.endpoint) {
dataset.endpoint = props.endpoint;
} else if (props.basePath) {
dataset.endpoint = makeAbsolute(`${props.basePath}/insights`);
}
return {
beforeSend: props.beforeSend,
src: getScriptSrc(props),
dataset
};
}
function makeAbsolute(url) {
return url.startsWith("http://") || url.startsWith("https://") || url.startsWith("/") ? url : `/${url}`;
}
// src/generic.ts
function inject(props = {
debug: true
}, confString) {
var _a;
if (!isBrowser()) return;
const { beforeSend, src, dataset } = loadProps(props, confString);
initQueue();
if (beforeSend) {
(_a = window.va) == null ? void 0 : _a.call(window, "beforeSend", beforeSend);
}
if (document.head.querySelector(`script[src*="${src}"]`)) return;
const script = document.createElement("script");
script.src = src;
for (const [key, value] of Object.entries(dataset)) {
script.dataset[key] = value;
}
script.defer = true;
script.onerror = () => {
const errorMessage = isDevelopment() ? "Please check if any ad blockers are enabled and try again." : "Be sure to enable Web Analytics for your project and deploy again. See https://vercel.com/docs/analytics/quickstart for more information.";
console.log(
`[Vercel Web Analytics] Failed to load script from ${src}. ${errorMessage}`
);
};
document.head.appendChild(script);
}
function pageview({
route,
path
}) {
var _a;
(_a = window.va) == null ? void 0 : _a.call(window, "pageview", { route, path });
}
// src/vue/utils.ts
function getBasePath() {
try {
return import.meta.env.VITE_VERCEL_OBSERVABILITY_BASEPATH;
} catch {
}
}
function getConfigString() {
try {
return import.meta.env.VITE_VERCEL_OBSERVABILITY_CLIENT_CONFIG;
} catch {
}
}
// src/vue/create-component.ts
function createComponent(framework = "vue") {
return defineComponent({
props: ["dsn", "beforeSend", "debug", "scriptSrc", "endpoint", "mode"],
setup(props) {
const route = useRoute();
inject(
{
// trim out undefined values to avoid overriding config values
...Object.fromEntries(
Object.entries(props).filter(([_, v]) => v !== void 0)
),
basePath: getBasePath(),
// keep auto-tracking unless we have route support (Nuxt or vue-router).
disableAutoTrack: Boolean(route),
framework
},
getConfigString()
);
if (route && typeof window !== "undefined") {
const changeRoute = () => {
pageview({
route: computeRoute(route.path, route.params),
path: route.path
});
};
changeRoute();
watch(route, changeRoute);
}
},
// Vue component must have a render function, or a template.
render() {
return null;
}
});
}
// src/vue/index.ts
var Analytics = createComponent();
export {
Analytics
};
//# sourceMappingURL=index.mjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../src/vue/create-component.ts","../../src/queue.ts","../../package.json","../../src/utils.ts","../../src/generic.ts","../../src/vue/utils.ts","../../src/vue/index.ts"],"sourcesContent":["import { defineComponent, watch } from 'vue';\n// for barebone vue project, vite will issue a warning since 'vue-router' import can't be resolved,\nimport { useRoute } from 'vue-router';\nimport { type AnalyticsProps, inject, pageview } from '../generic';\nimport { computeRoute } from '../utils';\nimport { getBasePath, getConfigString } from './utils';\n\nexport function createComponent(\n framework = 'vue',\n): ReturnType<typeof defineComponent> {\n return defineComponent({\n props: ['dsn', 'beforeSend', 'debug', 'scriptSrc', 'endpoint', 'mode'],\n setup(props: Omit<AnalyticsProps, 'framework'>) {\n const route = useRoute();\n inject(\n {\n // trim out undefined values to avoid overriding config values\n ...Object.fromEntries(\n Object.entries(props).filter(([_, v]) => v !== undefined),\n ),\n basePath: getBasePath(),\n // keep auto-tracking unless we have route support (Nuxt or vue-router).\n disableAutoTrack: Boolean(route),\n framework,\n },\n getConfigString(),\n );\n if (route && typeof window !== 'undefined') {\n const changeRoute = (): void => {\n pageview({\n route: computeRoute(route.path, route.params),\n path: route.path,\n });\n };\n changeRoute();\n watch(route, changeRoute);\n }\n },\n // Vue component must have a render function, or a template.\n render() {\n return null;\n },\n });\n}\n","export const initQueue = (): void => {\n // initialize va until script is loaded\n if (window.va) return;\n\n window.va = function a(...params): void {\n if (!window.vaq) window.vaq = [];\n window.vaq.push(params);\n };\n};\n","{\n \"name\": \"@vercel/analytics\",\n \"version\": \"2.0.1\",\n \"description\": \"Gain real-time traffic insights with Vercel Web Analytics\",\n \"keywords\": [\n \"analytics\",\n \"vercel\"\n ],\n \"repository\": {\n \"url\": \"github:vercel/analytics\",\n \"directory\": \"packages/web\"\n },\n \"license\": \"MIT\",\n \"exports\": {\n \"./package.json\": \"./package.json\",\n \".\": {\n \"browser\": \"./dist/index.mjs\",\n \"import\": \"./dist/index.mjs\",\n \"require\": \"./dist/index.js\"\n },\n \"./astro\": {\n \"import\": \"./dist/astro/component.ts\"\n },\n \"./next\": {\n \"browser\": \"./dist/next/index.mjs\",\n \"import\": \"./dist/next/index.mjs\",\n \"require\": \"./dist/next/index.js\"\n },\n \"./nuxt\": {\n \"import\": \"./dist/nuxt/index.mjs\",\n \"require\": \"./dist/nuxt/index.js\"\n },\n \"./nuxt/runtime\": {\n \"browser\": \"./dist/nuxt/runtime/index.mjs\",\n \"import\": \"./dist/nuxt/runtime/index.mjs\",\n \"require\": \"./dist/nuxt/runtime/index.js\"\n },\n \"./react\": {\n \"browser\": \"./dist/react/index.mjs\",\n \"import\": \"./dist/react/index.mjs\",\n \"require\": \"./dist/react/index.js\"\n },\n \"./remix\": {\n \"browser\": \"./dist/remix/index.mjs\",\n \"import\": \"./dist/remix/index.mjs\",\n \"require\": \"./dist/remix/index.js\"\n },\n \"./server\": {\n \"node\": \"./dist/server/index.mjs\",\n \"edge-light\": \"./dist/server/index.mjs\",\n \"import\": \"./dist/server/index.mjs\",\n \"require\": \"./dist/server/index.js\",\n \"default\": \"./dist/server/index.js\"\n },\n \"./sveltekit\": {\n \"svelte\": \"./dist/sveltekit/index.mjs\",\n \"types\": \"./dist/sveltekit/index.d.ts\"\n },\n \"./vue\": {\n \"browser\": \"./dist/vue/index.mjs\",\n \"import\": \"./dist/vue/index.mjs\",\n \"require\": \"./dist/vue/index.js\"\n }\n },\n \"main\": \"./dist/index.mjs\",\n \"types\": \"./dist/index.d.ts\",\n \"typesVersions\": {\n \"*\": {\n \"*\": [\n \"dist/index.d.ts\"\n ],\n \"next\": [\n \"dist/next/index.d.ts\"\n ],\n \"nuxt\": [\n \"dist/nuxt/index.d.ts\"\n ],\n \"nuxt/runtime\": [\n \"dist/nuxt/runtime/index.d.ts\"\n ],\n \"react\": [\n \"dist/react/index.d.ts\"\n ],\n \"remix\": [\n \"dist/remix/index.d.ts\"\n ],\n \"server\": [\n \"dist/server/index.d.ts\"\n ],\n \"sveltekit\": [\n \"dist/sveltekit/index.d.ts\"\n ],\n \"vue\": [\n \"dist/vue/index.d.ts\"\n ]\n }\n },\n \"scripts\": {\n \"build\": \"tsup && pnpm copy-astro\",\n \"copy-astro\": \"cp -R src/astro dist/\",\n \"dev\": \"pnpm copy-astro && tsup --watch\",\n \"test\": \"vitest\"\n },\n \"devDependencies\": {\n \"@nuxt/kit\": \"^4.2.0\",\n \"@nuxt/schema\": \"^Line truncated
+155
View File
@@ -0,0 +1,155 @@
{
"name": "@vercel/analytics",
"version": "2.0.1",
"description": "Gain real-time traffic insights with Vercel Web Analytics",
"keywords": [
"analytics",
"vercel"
],
"repository": {
"url": "github:vercel/analytics",
"directory": "packages/web"
},
"license": "MIT",
"exports": {
"./package.json": "./package.json",
".": {
"browser": "./dist/index.mjs",
"import": "./dist/index.mjs",
"require": "./dist/index.js"
},
"./astro": {
"import": "./dist/astro/component.ts"
},
"./next": {
"browser": "./dist/next/index.mjs",
"import": "./dist/next/index.mjs",
"require": "./dist/next/index.js"
},
"./nuxt": {
"import": "./dist/nuxt/index.mjs",
"require": "./dist/nuxt/index.js"
},
"./nuxt/runtime": {
"browser": "./dist/nuxt/runtime/index.mjs",
"import": "./dist/nuxt/runtime/index.mjs",
"require": "./dist/nuxt/runtime/index.js"
},
"./react": {
"browser": "./dist/react/index.mjs",
"import": "./dist/react/index.mjs",
"require": "./dist/react/index.js"
},
"./remix": {
"browser": "./dist/remix/index.mjs",
"import": "./dist/remix/index.mjs",
"require": "./dist/remix/index.js"
},
"./server": {
"node": "./dist/server/index.mjs",
"edge-light": "./dist/server/index.mjs",
"import": "./dist/server/index.mjs",
"require": "./dist/server/index.js",
"default": "./dist/server/index.js"
},
"./sveltekit": {
"svelte": "./dist/sveltekit/index.mjs",
"types": "./dist/sveltekit/index.d.ts"
},
"./vue": {
"browser": "./dist/vue/index.mjs",
"import": "./dist/vue/index.mjs",
"require": "./dist/vue/index.js"
}
},
"main": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"typesVersions": {
"*": {
"*": [
"dist/index.d.ts"
],
"next": [
"dist/next/index.d.ts"
],
"nuxt": [
"dist/nuxt/index.d.ts"
],
"nuxt/runtime": [
"dist/nuxt/runtime/index.d.ts"
],
"react": [
"dist/react/index.d.ts"
],
"remix": [
"dist/remix/index.d.ts"
],
"server": [
"dist/server/index.d.ts"
],
"sveltekit": [
"dist/sveltekit/index.d.ts"
],
"vue": [
"dist/vue/index.d.ts"
]
}
},
"devDependencies": {
"@nuxt/kit": "^4.2.0",
"@nuxt/schema": "^4.2.0",
"@swc/core": "^1.9.2",
"@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.1",
"@types/node": "^22.9.0",
"@types/react": "^18.3.12",
"server-only": "^0.0.1",
"svelte": "^5.1.10",
"tsup": "8.3.5",
"vitest": "^4.0.16",
"vue": "^3.5.12",
"vue-router": "^4.4.5"
},
"peerDependencies": {
"@remix-run/react": "^2",
"@sveltejs/kit": "^1 || ^2",
"next": ">= 13",
"nuxt": ">= 3",
"react": "^18 || ^19 || ^19.0.0-rc",
"svelte": ">= 4",
"vue": "^3",
"vue-router": "^4"
},
"peerDependenciesMeta": {
"@remix-run/react": {
"optional": true
},
"@sveltejs/kit": {
"optional": true
},
"next": {
"optional": true
},
"nuxt": {
"optional": true
},
"react": {
"optional": true
},
"svelte": {
"optional": true
},
"vue": {
"optional": true
},
"vue-router": {
"optional": true
}
},
"scripts": {
"build": "tsup && pnpm copy-astro",
"copy-astro": "cp -R src/astro dist/",
"dev": "pnpm copy-astro && tsup --watch",
"test": "vitest"
}
}
+13
View File
@@ -0,0 +1,13 @@
import { beforeEach } from 'vitest';
import '@testing-library/jest-dom/vitest';
beforeEach(() => {
if (typeof document === 'undefined') {
return;
}
// reset dom before each test
const html = document.getElementsByTagName('html')[0];
if (html) {
html.innerHTML = '';
}
});
+7
View File
@@ -0,0 +1,7 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"module": "esnext"
},
"include": ["src", "./test.setup.ts"]
}
+90
View File
@@ -0,0 +1,90 @@
import { defineConfig } from 'tsup';
const cfg = {
splitting: false,
sourcemap: true,
clean: true,
treeshake: false,
dts: true,
format: ['esm', 'cjs'],
};
export default defineConfig([
{
...cfg,
entry: {
index: 'src/generic.ts',
},
outDir: 'dist',
},
{
...cfg,
entry: {
index: 'src/nextjs/index.tsx',
},
external: ['react', 'next'],
outDir: 'dist/next',
},
{
...cfg,
entry: {
index: 'src/nuxt/module.ts',
},
external: [
'vue',
'vue-router',
'nuxt',
'@nuxt/kit',
'@nuxt/schema',
'#imports',
],
outDir: 'dist/nuxt',
},
{
...cfg,
entry: {
index: 'src/nuxt/runtime/index.ts',
},
external: ['vue', 'vue-router', 'nuxt'],
outDir: 'dist/nuxt/runtime',
},
{
...cfg,
entry: {
index: 'src/react/index.tsx',
},
external: ['react'],
outDir: 'dist/react',
},
{
...cfg,
entry: {
index: 'src/remix/index.tsx',
},
external: ['react', '@remix-run/react', 'react-router'],
outDir: 'dist/remix',
},
{
...cfg,
entry: {
index: 'src/server/index.ts',
},
outDir: 'dist/server',
},
{
...cfg,
entry: {
index: 'src/sveltekit/index.ts',
},
external: ['svelte', '@sveltejs/kit', '$app'],
outDir: 'dist/sveltekit',
},
{
...cfg,
entry: {
index: 'src/vue/index.ts',
},
external: ['vue', 'vue-router'],
outDir: 'dist/vue',
},
]);
+9
View File
@@ -0,0 +1,9 @@
/// <reference types="vitest" />
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
environment: 'jsdom',
setupFiles: './test.setup.ts',
},
});