Skip to content

Commit

Permalink
feat(intergration/vercel): convert analytics to ts and support inr edge
Browse files Browse the repository at this point in the history
  • Loading branch information
jsun969 committed Feb 7, 2023
1 parent 95f776d commit 8f66dbc
Show file tree
Hide file tree
Showing 6 changed files with 81 additions and 70 deletions.
2 changes: 1 addition & 1 deletion packages/integrations/vercel/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ export default defineConfig({
### analytics
> **Type:** `boolean`
> **Available for:** Serverless
> **Available for:** Serverless, Edge
Use this property to enable Vercel Analytics (including Web Vitals and Audiences).
Expand Down
63 changes: 0 additions & 63 deletions packages/integrations/vercel/analytics.js

This file was deleted.

1 change: 1 addition & 0 deletions packages/integrations/vercel/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
"./serverless": "./dist/serverless/adapter.js",
"./serverless/entrypoint": "./dist/serverless/entrypoint.js",
"./static": "./dist/static/adapter.js",
"./analytics": "./dist/analytics.js",
"./package.json": "./package.json"
},
"typesVersions": {
Expand Down
69 changes: 69 additions & 0 deletions packages/integrations/vercel/src/analytics.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { inject } from '@vercel/analytics';
import type { Metric } from 'web-vitals';
import { getCLS, getFCP, getFID, getLCP, getTTFB } from 'web-vitals';

const vitalsUrl = 'https://vitals.vercel-analytics.com/v1/vitals';

type Options = { path: string; analyticsId: string; debug?: boolean };

const getConnectionSpeed = () => {
return 'connection' in navigator &&
navigator['connection'] &&
'effectiveType' in (navigator['connection'] as unknown as { effectiveType: string })
? (navigator['connection'] as unknown as { effectiveType: string })['effectiveType']
: '';
};

const sendToAnalytics = (metric: Metric, options: Options) => {
const body = {
dsn: options.analyticsId,
id: metric.id,
page: options.path,
href: location.href,
event_name: metric.name,
value: metric.value.toString(),
speed: getConnectionSpeed(),
};

if (options.debug) {
// eslint-disable-next-line no-console
console.log('[Analytics]', metric.name, JSON.stringify(body, null, 2));
}

const blob = new Blob([new URLSearchParams(body).toString()], {
// This content type is necessary for `sendBeacon`
type: 'application/x-www-form-urlencoded',
});
if (navigator.sendBeacon) {
navigator.sendBeacon(vitalsUrl, blob);
} else
fetch(vitalsUrl, {
body: blob,
method: 'POST',
credentials: 'omit',
keepalive: true,
});
};

function webVitals() {
const options = {
path: window.location.pathname,
analyticsId: (import.meta as any).env.PUBLIC_VERCEL_ANALYTICS_ID,
};
try {
getFID((metric) => sendToAnalytics(metric, options));
getTTFB((metric) => sendToAnalytics(metric, options));
getLCP((metric) => sendToAnalytics(metric, options));
getCLS((metric) => sendToAnalytics(metric, options));
getFCP((metric) => sendToAnalytics(metric, options));
} catch (err) {
console.error('[Analytics]', err);
}
}

const mode = (import.meta as any).env.MODE as 'development' | 'production';

inject({ mode });
if (mode === 'production') {
webVitals();
}
11 changes: 9 additions & 2 deletions packages/integrations/vercel/src/edge/adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,13 @@ function getAdapter(): AstroAdapter {

export interface VercelEdgeConfig {
includeFiles?: string[];
analytics?: boolean;
}

export default function vercelEdge({ includeFiles = [] }: VercelEdgeConfig = {}): AstroIntegration {
export default function vercelEdge({
includeFiles = [],
analytics,
}: VercelEdgeConfig = {}): AstroIntegration {
let _config: AstroConfig;
let buildTempFolder: URL;
let functionFolder: URL;
Expand All @@ -35,7 +39,10 @@ export default function vercelEdge({ includeFiles = [] }: VercelEdgeConfig = {})
return {
name: PACKAGE_NAME,
hooks: {
'astro:config:setup': ({ config, updateConfig }) => {
'astro:config:setup': ({ config, updateConfig, injectScript }) => {
if (analytics) {
injectScript('page', 'import "@astrojs/vercel/analytics"');
}
const outDir = getVercelOutput(config.root);
updateConfig({
outDir,
Expand Down
5 changes: 1 addition & 4 deletions packages/integrations/vercel/src/serverless/adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,7 @@ export default function vercelServerless({
hooks: {
'astro:config:setup': ({ config, updateConfig, injectScript }) => {
if (analytics) {
injectScript(
'page',
readFileSync(new URL('../../analytics.js', import.meta.url), { encoding: 'utf-8' })
);
injectScript('page', 'import "@astrojs/vercel/analytics"');
}
const outDir = getVercelOutput(config.root);
updateConfig({
Expand Down

0 comments on commit 8f66dbc

Please sign in to comment.