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

+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