@vercel/speed-insights 0.0.1 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- ![Speed Insights](https://github.com/vercel/analytics/blob/main/.github/banner.png)
1
+ ![Speed Insights](https://github.com/vercel/speed-insights/blob/main/.github/banner.png)
2
2
 
3
3
  <div align="center"><strong>Vercel Speed Insights</strong></div>
4
4
  <div align="center">Performance insights for your website</div>
package/dist/index.cjs ADDED
@@ -0,0 +1,113 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name2 in all)
8
+ __defProp(target, name2, { get: all[name2], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/generic.ts
21
+ var generic_exports = {};
22
+ __export(generic_exports, {
23
+ default: () => generic_default,
24
+ inject: () => inject
25
+ });
26
+ module.exports = __toCommonJS(generic_exports);
27
+
28
+ // package.json
29
+ var name = "@vercel/speed-insights";
30
+ var version = "0.0.2";
31
+
32
+ // src/queue.ts
33
+ var initQueue = () => {
34
+ if (window.si)
35
+ return;
36
+ window.si = function a(...params) {
37
+ (window.siq = window.siq || []).push(params);
38
+ };
39
+ };
40
+
41
+ // src/utils.ts
42
+ function isBrowser() {
43
+ return typeof window !== "undefined";
44
+ }
45
+ function detectEnvironment() {
46
+ try {
47
+ const env = process.env.NODE_ENV;
48
+ if (env === "development" || env === "test") {
49
+ return "development";
50
+ }
51
+ } catch (e) {
52
+ }
53
+ return "production";
54
+ }
55
+ function isDevelopment() {
56
+ return detectEnvironment() === "development";
57
+ }
58
+
59
+ // src/generic.ts
60
+ var DEV_SCRIPT_URL = `https://va.vercel-scripts.com/v1/speed-insights/script.debug.js`;
61
+ var SCRIPT_URL = `/_vercel/speed-insights/script.js`;
62
+ function inject(props) {
63
+ var _a;
64
+ if (!isBrowser() || props.route === null)
65
+ return null;
66
+ initQueue();
67
+ if (props.beforeSend) {
68
+ (_a = window.si) == null ? void 0 : _a.call(window, "beforeSend", props.beforeSend);
69
+ }
70
+ const src = props.scriptSrc || (isDevelopment() ? DEV_SCRIPT_URL : SCRIPT_URL);
71
+ if (document.head.querySelector(`script[src*="${src}"]`))
72
+ return null;
73
+ const script = document.createElement("script");
74
+ script.src = src;
75
+ script.defer = true;
76
+ script.dataset.sdkn = name;
77
+ script.dataset.sdkv = version;
78
+ if (props.sampleRate) {
79
+ script.dataset.sampleRate = props.sampleRate.toString();
80
+ }
81
+ if (props.route) {
82
+ script.dataset.route = props.route;
83
+ }
84
+ if (props.endpoint) {
85
+ script.dataset.endpoint = props.endpoint;
86
+ }
87
+ if (props.token) {
88
+ script.dataset.token = props.token;
89
+ }
90
+ if (isDevelopment() && props.debug === false) {
91
+ script.dataset.debug = "false";
92
+ }
93
+ script.onerror = () => {
94
+ const errorMessage = isDevelopment() ? "Please check if any ad blockers are enabled and try again." : "Be sure to enable Speed Insights for your project and deploy again. See https://vercel.com/docs/speed-insights for more information.";
95
+ console.log(
96
+ `[Vercel Speed Insights] Failed to load script from ${src}. ${errorMessage}`
97
+ );
98
+ };
99
+ document.head.appendChild(script);
100
+ return {
101
+ setRoute: (route) => {
102
+ script.dataset.route = route;
103
+ }
104
+ };
105
+ }
106
+ var generic_default = {
107
+ inject
108
+ };
109
+ // Annotate the CommonJS export names for ESM import in node:
110
+ 0 && (module.exports = {
111
+ inject
112
+ });
113
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/generic.ts","../package.json","../src/queue.ts","../src/utils.ts"],"sourcesContent":["import { name as packageName, version } from '../package.json';\nimport { initQueue } from './queue';\nimport type { SpeedInsightsProps } from './types';\nimport { isBrowser, isDevelopment } from './utils';\n\nconst DEV_SCRIPT_URL = `https://va.vercel-scripts.com/v1/speed-insights/script.debug.js`;\nconst SCRIPT_URL = `/_vercel/speed-insights/script.js`;\n\n/**\n * Injects the Vercel Speed Insights script into the page head and starts tracking page views. Read more in our [documentation](https://vercel.com/docs/speed-insights).\n * @param [props] - Speed Insights options.\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 */\nfunction inject(props: SpeedInsightsProps): {\n setRoute: (route: string) => void;\n} | null {\n // When route is null, it means that pages router is not ready yet. Will resolve soon\n if (!isBrowser() || props.route === null) return null;\n\n initQueue();\n\n if (props.beforeSend) {\n window.si?.('beforeSend', props.beforeSend);\n }\n const src =\n props.scriptSrc || (isDevelopment() ? DEV_SCRIPT_URL : SCRIPT_URL);\n\n if (document.head.querySelector(`script[src*=\"${src}\"]`)) return null;\n\n const script = document.createElement('script');\n script.src = src;\n script.defer = true;\n script.dataset.sdkn = packageName;\n script.dataset.sdkv = version;\n\n if (props.sampleRate) {\n script.dataset.sampleRate = props.sampleRate.toString();\n }\n if (props.route) {\n script.dataset.route = props.route;\n }\n if (props.endpoint) {\n script.dataset.endpoint = props.endpoint;\n }\n if (props.token) {\n script.dataset.token = props.token;\n }\n if (isDevelopment() && props.debug === false) {\n script.dataset.debug = 'false';\n }\n\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 Speed Insights for your project and deploy again. See https://vercel.com/docs/speed-insights for more information.';\n\n // eslint-disable-next-line no-console -- Logging is okay here\n console.log(\n `[Vercel Speed Insights] Failed to load script from ${src}. ${errorMessage}`,\n );\n };\n\n document.head.appendChild(script);\n\n return {\n setRoute: (route: string): void => {\n script.dataset.route = route;\n },\n };\n}\n\nexport { inject };\nexport type { SpeedInsightsProps };\n\n// eslint-disable-next-line import/no-default-export -- Allow default export\nexport default {\n inject,\n};\n","{\n \"name\": \"@vercel/speed-insights\",\n \"version\": \"0.0.2\",\n \"description\": \"Speed Insights is a tool for measuring web performance and providing suggestions for improvement.\",\n \"keywords\": [\n \"speed-insights\",\n \"vercel\"\n ],\n \"repository\": {\n \"url\": \"github:vercel/speed-insights\",\n \"directory\": \"packages/web\"\n },\n \"license\": \"MPL-2.0\",\n \"type\": \"module\",\n \"exports\": {\n \"./package.json\": \"./package.json\",\n \".\": {\n \"browser\": \"./dist/index.js\",\n \"import\": \"./dist/index.js\",\n \"require\": \"./dist/index.cjs\"\n },\n \"./next\": {\n \"browser\": \"./dist/next/index.js\",\n \"import\": \"./dist/next/index.js\",\n \"require\": \"./dist/next/index.cjs\"\n },\n \"./remix\": {\n \"browser\": \"./dist/remix/index.js\",\n \"import\": \"./dist/remix/index.js\",\n \"require\": \"./dist/remix/index.cjs\"\n }\n },\n \"main\": \"dist/index.js\",\n \"types\": \"dist/index.d.ts\",\n \"typesVersions\": {\n \"*\": {\n \"*\": [\n \"dist/index.d.ts\"\n ],\n \"react\": [\n \"dist/react/index.d.ts\"\n ],\n \"next\": [\n \"dist/next/index.d.ts\"\n ],\n \"remix\": [\n \"dist/remix/index.d.ts\"\n ]\n }\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"postinstall\": \"node scripts/postinstall.js\",\n \"lint\": \"eslint .\",\n \"lint-fix\": \"eslint . --fix\",\n \"test\": \"jest\",\n \"type-check\": \"tsc --noEmit\"\n },\n \"devDependencies\": {\n \"@remix-run/react\": \"^2.0.1\",\n \"@swc/core\": \"^1.3.82\",\n \"@swc/jest\": \"^0.2.29\",\n \"@testing-library/jest-dom\": \"^6.1.2\",\n \"@testing-library/react\": \"^14.0.0\",\n \"@types/jest\": \"^29.5.4\",\n \"@types/node\": \"^20.5.9\",\n \"@types/react\": \"^18.2.21\",\n \"jest\": \"^29.6.4\",\n \"jest-environment-jsdom\": \"^29.6.4\",\n \"next\": \"^13.4.19\",\n \"react\": \"^18.2.0\",\n \"react-dom\": \"^18.2.0\",\n \"tsup\": \"7.2.0\"\n }\n}\n","export const initQueue = (): void => {\n // initialize va until script is loaded\n if (window.si) return;\n\n window.si = function a(...params): void {\n (window.siq = window.siq || []).push(params);\n };\n};\n","export 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 (e) {\n // do nothing, this is okay\n }\n return 'production';\n}\n\nexport function isProduction(): boolean {\n return detectEnvironment() === 'production';\n}\n\nexport function isDevelopment(): boolean {\n return detectEnvironment() === 'development';\n}\n\nexport function computeRoute(\n pathname: string | null,\n pathParams: Record<string, string | string[]> | null,\n): string | null {\n if (!pathname || !pathParams) {\n return pathname;\n }\n\n let result = pathname;\n\n for (const [key, valueOrArray] of Object.entries(pathParams)) {\n const isValueArray = Array.isArray(valueOrArray);\n const value = isValueArray ? valueOrArray.join('/') : valueOrArray;\n const expr = isValueArray ? `...${key}` : key;\n\n const matcher = new RegExp(`/${value}(?=[/?#]|$)`);\n if (matcher.test(result)) {\n result = result.replace(matcher, `/[${expr}]`);\n }\n }\n\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCE,WAAQ;AACR,cAAW;;;ACFN,IAAM,YAAY,MAAY;AAEnC,MAAI,OAAO;AAAI;AAEf,SAAO,KAAK,SAAS,KAAK,QAAc;AACtC,KAAC,OAAO,MAAM,OAAO,OAAO,CAAC,GAAG,KAAK,MAAM;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AAY;AAAA,IAC5E;AAAA,EACF;AAEA,WAAS,KAAK,YAAY,MAAM;AAEhC,SAAO;AAAA,IACL,UAAU,CAAC,UAAwB;AACjC,aAAO,QAAQ,QAAQ;AAAA,IACzB;AAAA,EACF;AACF;AAMA,IAAO,kBAAQ;AAAA,EACb;AACF;","names":[]}
@@ -0,0 +1,47 @@
1
+ interface SpeedInsightsProps {
2
+ token?: string;
3
+ sampleRate?: number;
4
+ route?: string | null;
5
+ beforeSend?: BeforeSendMiddleware;
6
+ debug?: boolean;
7
+ scriptSrc?: string;
8
+ endpoint?: string;
9
+ }
10
+ type EventTypes = 'vital';
11
+ interface Event {
12
+ type: EventTypes;
13
+ url: string;
14
+ }
15
+ type BeforeSendMiddleware = (data: Event) => Event | null | undefined | false;
16
+ interface Functions {
17
+ beforeSend?: BeforeSendMiddleware;
18
+ }
19
+ interface SpeedInsights<T extends keyof Functions = keyof Functions> {
20
+ queue: [T, Functions[T]][];
21
+ addAction: (action: T, data: Functions[T]) => void;
22
+ }
23
+ declare global {
24
+ interface Window {
25
+ /** Base interface to track events */
26
+ si?: SpeedInsights['addAction'];
27
+ /** Queue for speed insights datapoints, before the library is loaded */
28
+ siq?: SpeedInsights['queue'];
29
+ sil?: boolean;
30
+ }
31
+ }
32
+
33
+ /**
34
+ * Injects the Vercel Speed Insights script into the page head and starts tracking page views. Read more in our [documentation](https://vercel.com/docs/speed-insights).
35
+ * @param [props] - Speed Insights options.
36
+ * @param [props.debug] - Whether to enable debug logging in development. Defaults to `true`.
37
+ * @param [props.beforeSend] - A middleware function to modify events before they are sent. Should return the event object or `null` to cancel the event.
38
+ */
39
+ declare function inject(props: SpeedInsightsProps): {
40
+ setRoute: (route: string) => void;
41
+ } | null;
42
+
43
+ declare const _default: {
44
+ inject: typeof inject;
45
+ };
46
+
47
+ export { SpeedInsightsProps, _default as default, inject };
@@ -0,0 +1,47 @@
1
+ interface SpeedInsightsProps {
2
+ token?: string;
3
+ sampleRate?: number;
4
+ route?: string | null;
5
+ beforeSend?: BeforeSendMiddleware;
6
+ debug?: boolean;
7
+ scriptSrc?: string;
8
+ endpoint?: string;
9
+ }
10
+ type EventTypes = 'vital';
11
+ interface Event {
12
+ type: EventTypes;
13
+ url: string;
14
+ }
15
+ type BeforeSendMiddleware = (data: Event) => Event | null | undefined | false;
16
+ interface Functions {
17
+ beforeSend?: BeforeSendMiddleware;
18
+ }
19
+ interface SpeedInsights<T extends keyof Functions = keyof Functions> {
20
+ queue: [T, Functions[T]][];
21
+ addAction: (action: T, data: Functions[T]) => void;
22
+ }
23
+ declare global {
24
+ interface Window {
25
+ /** Base interface to track events */
26
+ si?: SpeedInsights['addAction'];
27
+ /** Queue for speed insights datapoints, before the library is loaded */
28
+ siq?: SpeedInsights['queue'];
29
+ sil?: boolean;
30
+ }
31
+ }
32
+
33
+ /**
34
+ * Injects the Vercel Speed Insights script into the page head and starts tracking page views. Read more in our [documentation](https://vercel.com/docs/speed-insights).
35
+ * @param [props] - Speed Insights options.
36
+ * @param [props.debug] - Whether to enable debug logging in development. Defaults to `true`.
37
+ * @param [props.beforeSend] - A middleware function to modify events before they are sent. Should return the event object or `null` to cancel the event.
38
+ */
39
+ declare function inject(props: SpeedInsightsProps): {
40
+ setRoute: (route: string) => void;
41
+ } | null;
42
+
43
+ declare const _default: {
44
+ inject: typeof inject;
45
+ };
46
+
47
+ export { SpeedInsightsProps, _default as default, inject };
package/dist/index.js ADDED
@@ -0,0 +1,86 @@
1
+ // package.json
2
+ var name = "@vercel/speed-insights";
3
+ var version = "0.0.2";
4
+
5
+ // src/queue.ts
6
+ var initQueue = () => {
7
+ if (window.si)
8
+ return;
9
+ window.si = function a(...params) {
10
+ (window.siq = window.siq || []).push(params);
11
+ };
12
+ };
13
+
14
+ // src/utils.ts
15
+ function isBrowser() {
16
+ return typeof window !== "undefined";
17
+ }
18
+ function detectEnvironment() {
19
+ try {
20
+ const env = process.env.NODE_ENV;
21
+ if (env === "development" || env === "test") {
22
+ return "development";
23
+ }
24
+ } catch (e) {
25
+ }
26
+ return "production";
27
+ }
28
+ function isDevelopment() {
29
+ return detectEnvironment() === "development";
30
+ }
31
+
32
+ // src/generic.ts
33
+ var DEV_SCRIPT_URL = `https://va.vercel-scripts.com/v1/speed-insights/script.debug.js`;
34
+ var SCRIPT_URL = `/_vercel/speed-insights/script.js`;
35
+ function inject(props) {
36
+ var _a;
37
+ if (!isBrowser() || props.route === null)
38
+ return null;
39
+ initQueue();
40
+ if (props.beforeSend) {
41
+ (_a = window.si) == null ? void 0 : _a.call(window, "beforeSend", props.beforeSend);
42
+ }
43
+ const src = props.scriptSrc || (isDevelopment() ? DEV_SCRIPT_URL : SCRIPT_URL);
44
+ if (document.head.querySelector(`script[src*="${src}"]`))
45
+ return null;
46
+ const script = document.createElement("script");
47
+ script.src = src;
48
+ script.defer = true;
49
+ script.dataset.sdkn = name;
50
+ script.dataset.sdkv = version;
51
+ if (props.sampleRate) {
52
+ script.dataset.sampleRate = props.sampleRate.toString();
53
+ }
54
+ if (props.route) {
55
+ script.dataset.route = props.route;
56
+ }
57
+ if (props.endpoint) {
58
+ script.dataset.endpoint = props.endpoint;
59
+ }
60
+ if (props.token) {
61
+ script.dataset.token = props.token;
62
+ }
63
+ if (isDevelopment() && props.debug === false) {
64
+ script.dataset.debug = "false";
65
+ }
66
+ script.onerror = () => {
67
+ const errorMessage = isDevelopment() ? "Please check if any ad blockers are enabled and try again." : "Be sure to enable Speed Insights for your project and deploy again. See https://vercel.com/docs/speed-insights for more information.";
68
+ console.log(
69
+ `[Vercel Speed Insights] Failed to load script from ${src}. ${errorMessage}`
70
+ );
71
+ };
72
+ document.head.appendChild(script);
73
+ return {
74
+ setRoute: (route) => {
75
+ script.dataset.route = route;
76
+ }
77
+ };
78
+ }
79
+ var generic_default = {
80
+ inject
81
+ };
82
+ export {
83
+ generic_default as default,
84
+ inject
85
+ };
86
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../package.json","../src/queue.ts","../src/utils.ts","../src/generic.ts"],"sourcesContent":["{\n \"name\": \"@vercel/speed-insights\",\n \"version\": \"0.0.2\",\n \"description\": \"Speed Insights is a tool for measuring web performance and providing suggestions for improvement.\",\n \"keywords\": [\n \"speed-insights\",\n \"vercel\"\n ],\n \"repository\": {\n \"url\": \"github:vercel/speed-insights\",\n \"directory\": \"packages/web\"\n },\n \"license\": \"MPL-2.0\",\n \"type\": \"module\",\n \"exports\": {\n \"./package.json\": \"./package.json\",\n \".\": {\n \"browser\": \"./dist/index.js\",\n \"import\": \"./dist/index.js\",\n \"require\": \"./dist/index.cjs\"\n },\n \"./next\": {\n \"browser\": \"./dist/next/index.js\",\n \"import\": \"./dist/next/index.js\",\n \"require\": \"./dist/next/index.cjs\"\n },\n \"./remix\": {\n \"browser\": \"./dist/remix/index.js\",\n \"import\": \"./dist/remix/index.js\",\n \"require\": \"./dist/remix/index.cjs\"\n }\n },\n \"main\": \"dist/index.js\",\n \"types\": \"dist/index.d.ts\",\n \"typesVersions\": {\n \"*\": {\n \"*\": [\n \"dist/index.d.ts\"\n ],\n \"react\": [\n \"dist/react/index.d.ts\"\n ],\n \"next\": [\n \"dist/next/index.d.ts\"\n ],\n \"remix\": [\n \"dist/remix/index.d.ts\"\n ]\n }\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"postinstall\": \"node scripts/postinstall.js\",\n \"lint\": \"eslint .\",\n \"lint-fix\": \"eslint . --fix\",\n \"test\": \"jest\",\n \"type-check\": \"tsc --noEmit\"\n },\n \"devDependencies\": {\n \"@remix-run/react\": \"^2.0.1\",\n \"@swc/core\": \"^1.3.82\",\n \"@swc/jest\": \"^0.2.29\",\n \"@testing-library/jest-dom\": \"^6.1.2\",\n \"@testing-library/react\": \"^14.0.0\",\n \"@types/jest\": \"^29.5.4\",\n \"@types/node\": \"^20.5.9\",\n \"@types/react\": \"^18.2.21\",\n \"jest\": \"^29.6.4\",\n \"jest-environment-jsdom\": \"^29.6.4\",\n \"next\": \"^13.4.19\",\n \"react\": \"^18.2.0\",\n \"react-dom\": \"^18.2.0\",\n \"tsup\": \"7.2.0\"\n }\n}\n","export const initQueue = (): void => {\n // initialize va until script is loaded\n if (window.si) return;\n\n window.si = function a(...params): void {\n (window.siq = window.siq || []).push(params);\n };\n};\n","export 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 (e) {\n // do nothing, this is okay\n }\n return 'production';\n}\n\nexport function isProduction(): boolean {\n return detectEnvironment() === 'production';\n}\n\nexport function isDevelopment(): boolean {\n return detectEnvironment() === 'development';\n}\n\nexport function computeRoute(\n pathname: string | null,\n pathParams: Record<string, string | string[]> | null,\n): string | null {\n if (!pathname || !pathParams) {\n return pathname;\n }\n\n let result = pathname;\n\n for (const [key, valueOrArray] of Object.entries(pathParams)) {\n const isValueArray = Array.isArray(valueOrArray);\n const value = isValueArray ? valueOrArray.join('/') : valueOrArray;\n const expr = isValueArray ? `...${key}` : key;\n\n const matcher = new RegExp(`/${value}(?=[/?#]|$)`);\n if (matcher.test(result)) {\n result = result.replace(matcher, `/[${expr}]`);\n }\n }\n\n return result;\n}\n","import { name as packageName, version } from '../package.json';\nimport { initQueue } from './queue';\nimport type { SpeedInsightsProps } from './types';\nimport { isBrowser, isDevelopment } from './utils';\n\nconst DEV_SCRIPT_URL = `https://va.vercel-scripts.com/v1/speed-insights/script.debug.js`;\nconst SCRIPT_URL = `/_vercel/speed-insights/script.js`;\n\n/**\n * Injects the Vercel Speed Insights script into the page head and starts tracking page views. Read more in our [documentation](https://vercel.com/docs/speed-insights).\n * @param [props] - Speed Insights options.\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 */\nfunction inject(props: SpeedInsightsProps): {\n setRoute: (route: string) => void;\n} | null {\n // When route is null, it means that pages router is not ready yet. Will resolve soon\n if (!isBrowser() || props.route === null) return null;\n\n initQueue();\n\n if (props.beforeSend) {\n window.si?.('beforeSend', props.beforeSend);\n }\n const src =\n props.scriptSrc || (isDevelopment() ? DEV_SCRIPT_URL : SCRIPT_URL);\n\n if (document.head.querySelector(`script[src*=\"${src}\"]`)) return null;\n\n const script = document.createElement('script');\n script.src = src;\n script.defer = true;\n script.dataset.sdkn = packageName;\n script.dataset.sdkv = version;\n\n if (props.sampleRate) {\n script.dataset.sampleRate = props.sampleRate.toString();\n }\n if (props.route) {\n script.dataset.route = props.route;\n }\n if (props.endpoint) {\n script.dataset.endpoint = props.endpoint;\n }\n if (props.token) {\n script.dataset.token = props.token;\n }\n if (isDevelopment() && props.debug === false) {\n script.dataset.debug = 'false';\n }\n\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 Speed Insights for your project and deploy again. See https://vercel.com/docs/speed-insights for more information.';\n\n // eslint-disable-next-line no-console -- Logging is okay here\n console.log(\n `[Vercel Speed Insights] Failed to load script from ${src}. ${errorMessage}`,\n );\n };\n\n document.head.appendChild(script);\n\n return {\n setRoute: (route: string): void => {\n script.dataset.route = route;\n },\n };\n}\n\nexport { inject };\nexport type { SpeedInsightsProps };\n\n// eslint-disable-next-line import/no-default-export -- Allow default export\nexport default {\n inject,\n};\n"],"mappings":";AACE,WAAQ;AACR,cAAW;;;ACFN,IAAM,YAAY,MAAY;AAEnC,MAAI,OAAO;AAAI;AAEf,SAAO,KAAK,SAAS,KAAK,QAAc;AACtC,KAAC,OAAO,MAAM,OAAO,OAAO,CAAC,GAAG,KAAK,MAAM;AAAA,EAC7C;AACF;;;ACPO,SAAS,YAAqB;AACnC,SAAO,OAAO,WAAW;AAC3B;AAEA,SAAS,oBAAkD;AACzD,MAAI;AACF,UAAM,MAAM,QAAQ,IAAI;AACxB,QAAI,QAAQ,iBAAiB,QAAQ,QAAQ;A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AAAA,EACb;AACF;","names":[]}
@@ -1,12 +1,14 @@
1
1
  "use client";
2
2
  "use strict";
3
+ var __create = Object.create;
3
4
  var __defProp = Object.defineProperty;
4
5
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
6
  var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
6
8
  var __hasOwnProp = Object.prototype.hasOwnProperty;
7
9
  var __export = (target, all) => {
8
- for (var name in all)
9
- __defProp(target, name, { get: all[name], enumerable: true });
10
+ for (var name2 in all)
11
+ __defProp(target, name2, { get: all[name2], enumerable: true });
10
12
  };
11
13
  var __copyProps = (to, from, except, desc) => {
12
14
  if (from && typeof from === "object" || typeof from === "function") {
@@ -16,167 +18,160 @@ var __copyProps = (to, from, except, desc) => {
16
18
  }
17
19
  return to;
18
20
  };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
19
29
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
30
 
21
31
  // src/nextjs/index.tsx
22
32
  var nextjs_exports = {};
23
33
  __export(nextjs_exports, {
24
- SpeedInsights: () => SpeedInsights
34
+ SpeedInsights: () => SpeedInsights2
25
35
  });
26
36
  module.exports = __toCommonJS(nextjs_exports);
37
+ var import_react3 = __toESM(require("react"), 1);
38
+
39
+ // src/react/index.tsx
27
40
  var import_react = require("react");
28
41
 
29
- // src/generic/index.ts
30
- var import_attribution = require("web-vitals/attribution");
42
+ // package.json
43
+ var name = "@vercel/speed-insights";
44
+ var version = "0.0.2";
45
+
46
+ // src/queue.ts
47
+ var initQueue = () => {
48
+ if (window.si)
49
+ return;
50
+ window.si = function a(...params) {
51
+ (window.siq = window.siq || []).push(params);
52
+ };
53
+ };
31
54
 
32
55
  // src/utils.ts
33
- function getConnectionSpeed() {
34
- let speed = "";
35
- if ("connection" in navigator) {
36
- const connection = navigator.connection;
37
- if (connection == null ? void 0 : connection.effectiveType) {
38
- speed = connection.effectiveType;
39
- }
40
- }
41
- return speed;
56
+ function isBrowser() {
57
+ return typeof window !== "undefined";
42
58
  }
43
- var ENDPOINT = "https://vitals.vercel-insights.com/v1/vitals";
44
- function sendBeacon(data) {
45
- const encodedData = new URLSearchParams(data).toString();
46
- const blob = new Blob([encodedData], {
47
- type: "application/x-www-form-urlencoded"
48
- });
59
+ function detectEnvironment() {
49
60
  try {
50
- if ("keepalive" in Request.prototype) {
51
- void fetch(ENDPOINT, {
52
- method: "POST",
53
- body: blob,
54
- keepalive: true,
55
- mode: "no-cors",
56
- credentials: "omit"
57
- });
58
- } else if ("sendBeacon" in navigator) {
59
- navigator.sendBeacon(ENDPOINT, blob);
61
+ const env = process.env.NODE_ENV;
62
+ if (env === "development" || env === "test") {
63
+ return "development";
60
64
  }
61
65
  } catch (e) {
62
66
  }
67
+ return "production";
68
+ }
69
+ function isDevelopment() {
70
+ return detectEnvironment() === "development";
63
71
  }
64
- function cutDecimal(number, decimals) {
65
- if (Number.isInteger(number)) {
66
- return number;
72
+ function computeRoute(pathname, pathParams) {
73
+ if (!pathname || !pathParams) {
74
+ return pathname;
75
+ }
76
+ let result = pathname;
77
+ for (const [key, valueOrArray] of Object.entries(pathParams)) {
78
+ const isValueArray = Array.isArray(valueOrArray);
79
+ const value = isValueArray ? valueOrArray.join("/") : valueOrArray;
80
+ const expr = isValueArray ? `...${key}` : key;
81
+ const matcher = new RegExp(`/${value}(?=[/?#]|$)`);
82
+ if (matcher.test(result)) {
83
+ result = result.replace(matcher, `/[${expr}]`);
84
+ }
67
85
  }
68
- const multiplier = Math.pow(10, decimals);
69
- return Math.floor(number * multiplier) / multiplier;
86
+ return result;
70
87
  }
71
88
 
72
- // src/generic/index.ts
73
- function sendVitals(metrics, dsn) {
74
- const speed = getConnectionSpeed();
75
- for (const metric of metrics) {
76
- const value = cutDecimal(metric.value, metric.name === "CLS" ? 4 : 0);
77
- const vital = {
78
- dsn,
79
- speed,
80
- id: metric.id,
81
- event_name: metric.name,
82
- value,
83
- href: window.location.href.replace("http://", "https://"),
84
- // TODO: remove this
85
- ...metric.dynamicPath && { dynamicPath: metric.dynamicPath }
86
- };
87
- sendBeacon(vital);
89
+ // src/generic.ts
90
+ var DEV_SCRIPT_URL = `https://va.vercel-scripts.com/v1/speed-insights/script.debug.js`;
91
+ var SCRIPT_URL = `/_vercel/speed-insights/script.js`;
92
+ function inject(props) {
93
+ var _a;
94
+ if (!isBrowser() || props.route === null)
95
+ return null;
96
+ initQueue();
97
+ if (props.beforeSend) {
98
+ (_a = window.si) == null ? void 0 : _a.call(window, "beforeSend", props.beforeSend);
99
+ }
100
+ const src = props.scriptSrc || (isDevelopment() ? DEV_SCRIPT_URL : SCRIPT_URL);
101
+ if (document.head.querySelector(`script[src*="${src}"]`))
102
+ return null;
103
+ const script = document.createElement("script");
104
+ script.src = src;
105
+ script.defer = true;
106
+ script.dataset.sdkn = name;
107
+ script.dataset.sdkv = version;
108
+ if (props.sampleRate) {
109
+ script.dataset.sampleRate = props.sampleRate.toString();
110
+ }
111
+ if (props.route) {
112
+ script.dataset.route = props.route;
113
+ }
114
+ if (props.endpoint) {
115
+ script.dataset.endpoint = props.endpoint;
88
116
  }
117
+ if (props.token) {
118
+ script.dataset.token = props.token;
119
+ }
120
+ if (isDevelopment() && props.debug === false) {
121
+ script.dataset.debug = "false";
122
+ }
123
+ script.onerror = () => {
124
+ const errorMessage = isDevelopment() ? "Please check if any ad blockers are enabled and try again." : "Be sure to enable Speed Insights for your project and deploy again. See https://vercel.com/docs/speed-insights for more information.";
125
+ console.log(
126
+ `[Vercel Speed Insights] Failed to load script from ${src}. ${errorMessage}`
127
+ );
128
+ };
129
+ document.head.appendChild(script);
130
+ return {
131
+ setRoute: (route) => {
132
+ script.dataset.route = route;
133
+ }
134
+ };
89
135
  }
90
- function watchMetrics(callback) {
91
- (0, import_attribution.onCLS)(callback);
92
- (0, import_attribution.onFID)(callback);
93
- (0, import_attribution.onLCP)(callback);
94
- (0, import_attribution.onFCP)(callback);
95
- (0, import_attribution.onINP)(callback);
96
- (0, import_attribution.onTTFB)(callback);
136
+
137
+ // src/react/index.tsx
138
+ function SpeedInsights(props) {
139
+ const setScriptRoute = (0, import_react.useRef)(null);
140
+ (0, import_react.useEffect)(() => {
141
+ if (!setScriptRoute.current) {
142
+ const script = inject(props);
143
+ if (script) {
144
+ setScriptRoute.current = script.setRoute;
145
+ }
146
+ } else if (props.route) {
147
+ setScriptRoute.current(props.route);
148
+ }
149
+ }, [props.route]);
150
+ return null;
97
151
  }
98
152
 
99
153
  // src/nextjs/utils.ts
100
154
  var import_navigation = require("next/navigation");
101
- var useDynamicPath = () => {
155
+ var import_react2 = require("react");
156
+ var useRoute = () => {
102
157
  const params = (0, import_navigation.useParams)();
158
+ const searchParams = (0, import_navigation.useSearchParams)();
103
159
  const path = (0, import_navigation.usePathname)();
104
- return computePathname(path, params);
105
- };
106
- function computePathname(pathname, pathParams) {
107
- if (pathname === null) {
108
- return null;
109
- }
110
- if (pathname === "" || !pathParams) {
111
- return pathname;
112
- }
113
- let result = pathname;
114
- for (const [key, valueOrArray] of Object.entries(pathParams)) {
115
- let value;
116
- let expr;
117
- if (Array.isArray(valueOrArray)) {
118
- expr = `...${key}`;
119
- value = valueOrArray.join("/");
120
- } else {
121
- expr = key;
122
- value = valueOrArray;
123
- }
124
- if (!value) {
125
- continue;
160
+ const finalParams = (0, import_react2.useMemo)(() => {
161
+ if (!params)
162
+ return null;
163
+ if (Object.keys(params).length !== 0) {
164
+ return params;
126
165
  }
127
- let start = 0;
128
- while (start !== -1) {
129
- start = result.indexOf(`/${value}`, start);
130
- if (start !== -1) {
131
- const end = start + value.length + 2;
132
- if (end >= result.length || result[end] === "/" || result[end] === "?" || result[end] === "#") {
133
- result = `${result.substring(
134
- 0,
135
- start + 1
136
- )}[${expr}]${result.substring(end)}`;
137
- break;
138
- }
139
- start += value.length + 1;
140
- }
141
- }
142
- }
143
- return result;
144
- }
166
+ return { ...Object.fromEntries(searchParams.entries()) };
167
+ }, [params, searchParams]);
168
+ return computeRoute(path, finalParams);
169
+ };
145
170
 
146
171
  // src/nextjs/index.tsx
147
- function SpeedInsights({ token, sampleRate }) {
148
- const dynamicPath = useDynamicPath();
149
- const vitals = (0, import_react.useRef)([]);
150
- const flush = (0, import_react.useCallback)(() => {
151
- if (vitals.current.length > 0) {
152
- if (sampleRate && Math.random() > sampleRate) {
153
- return;
154
- }
155
- const body = vitals.current;
156
- console.log("flushing", body);
157
- sendVitals(body, token);
158
- vitals.current = [];
159
- }
160
- }, [sampleRate, vitals.current]);
161
- (0, import_react.useEffect)(() => {
162
- addEventListener("visibilitychange", flush);
163
- addEventListener("pagehide", flush);
164
- return () => {
165
- removeEventListener("visibilitychange", flush);
166
- removeEventListener("pagehide", flush);
167
- };
168
- }, [flush]);
169
- const reportVital = (0, import_react.useCallback)(
170
- (metric) => {
171
- console.log(metric);
172
- vitals.current.push({ ...metric, dynamicPath });
173
- },
174
- [dynamicPath]
175
- );
176
- (0, import_react.useEffect)(() => {
177
- watchMetrics(reportVital);
178
- }, []);
179
- return null;
172
+ function SpeedInsights2(props) {
173
+ const route = useRoute();
174
+ return /* @__PURE__ */ import_react3.default.createElement(SpeedInsights, { route, ...props });
180
175
  }
181
176
  // Annotate the CommonJS export names for ESM import in node:
182
177
  0 && (module.exports = {