@vulcantech/analytics 0.1.1 → 0.2.0
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 +113 -2
- package/dist/index.d.mts +145 -9
- package/dist/index.d.ts +145 -9
- package/dist/index.js +132 -3
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +133 -6
- package/dist/index.mjs.map +1 -1
- package/dist/route.d.mts +27 -0
- package/dist/route.d.ts +27 -0
- package/dist/route.js +4 -1
- package/dist/route.js.map +1 -1
- package/dist/route.mjs +4 -1
- package/dist/route.mjs.map +1 -1
- package/dist/tags.d.mts +100 -16
- package/dist/tags.d.ts +100 -16
- package/dist/tags.js +42 -3
- package/dist/tags.js.map +1 -1
- package/dist/tags.mjs +42 -3
- package/dist/tags.mjs.map +1 -1
- package/package.json +8 -7
- package/src/AnalyticsTracker.tsx +13 -3
- package/src/PhoneLink.tsx +69 -0
- package/src/index.tsx +2 -0
- package/src/route.ts +30 -0
- package/src/tags.tsx +179 -16
- package/src/tracker.ts +345 -17
package/dist/route.d.mts
CHANGED
|
@@ -11,9 +11,36 @@ import { NextResponse, NextRequest } from 'next/server';
|
|
|
11
11
|
* VULCANTECH_CMS_URL — CMS base URL (defaults to https://cms.vulcantech.io)
|
|
12
12
|
* VULCANTECH_PROJECT_ID — project ID for this site
|
|
13
13
|
* VULCANTECH_API_KEY — API key for this site
|
|
14
|
+
*
|
|
15
|
+
* The API key must carry the `analytics:write` scope — the scope the CMS's
|
|
16
|
+
* POST /api/analytics enforces. This is a DIFFERENT scope from the
|
|
17
|
+
* `analytics:read` that CMSTags needs for tag config; a site doing both needs
|
|
18
|
+
* both on the one key. A key missing `analytics:write` drops every event while
|
|
19
|
+
* this route still answers 204 (see POST below), so the misconfiguration is
|
|
20
|
+
* invisible from the browser — verify ingestion in the CMS dashboard.
|
|
14
21
|
*/
|
|
15
22
|
|
|
16
23
|
declare function OPTIONS(): Promise<NextResponse<unknown>>;
|
|
24
|
+
/**
|
|
25
|
+
* Forward one tracker event to the CMS, stamped with this site's project ID,
|
|
26
|
+
* API key, any CDN-provided geo headers, and the visitor's User-Agent.
|
|
27
|
+
*
|
|
28
|
+
* Without the visitor's UA the CMS sees this server's Node fetch UA, buckets
|
|
29
|
+
* every proxied visit as browser/OS "Other", and its bot filter never fires
|
|
30
|
+
* (BL-704). It is sent twice: as the outbound `User-Agent` header (what CMS
|
|
31
|
+
* builds before BL-704 read, and what the hand-rolled app proxies send) and as
|
|
32
|
+
* `ua` in the body, which the CMS prefers and trusts only on a validated key.
|
|
33
|
+
*
|
|
34
|
+
* Status contract:
|
|
35
|
+
* 503 — VULCANTECH_PROJECT_ID or VULCANTECH_API_KEY is unset.
|
|
36
|
+
* 400 — the request body is not parseable JSON.
|
|
37
|
+
* 204 — EVERYTHING else, including when the CMS was unreachable, rejected
|
|
38
|
+
* the event, or dropped it (bad scope, bot user agent, rate limit).
|
|
39
|
+
*
|
|
40
|
+
* So a 204 is not evidence of ingestion. This is deliberate: the forward is
|
|
41
|
+
* awaited but its result is discarded, because analytics must never block or
|
|
42
|
+
* break a page.
|
|
43
|
+
*/
|
|
17
44
|
declare function POST(req: NextRequest): Promise<NextResponse<unknown>>;
|
|
18
45
|
|
|
19
46
|
export { OPTIONS, POST };
|
package/dist/route.d.ts
CHANGED
|
@@ -11,9 +11,36 @@ import { NextResponse, NextRequest } from 'next/server';
|
|
|
11
11
|
* VULCANTECH_CMS_URL — CMS base URL (defaults to https://cms.vulcantech.io)
|
|
12
12
|
* VULCANTECH_PROJECT_ID — project ID for this site
|
|
13
13
|
* VULCANTECH_API_KEY — API key for this site
|
|
14
|
+
*
|
|
15
|
+
* The API key must carry the `analytics:write` scope — the scope the CMS's
|
|
16
|
+
* POST /api/analytics enforces. This is a DIFFERENT scope from the
|
|
17
|
+
* `analytics:read` that CMSTags needs for tag config; a site doing both needs
|
|
18
|
+
* both on the one key. A key missing `analytics:write` drops every event while
|
|
19
|
+
* this route still answers 204 (see POST below), so the misconfiguration is
|
|
20
|
+
* invisible from the browser — verify ingestion in the CMS dashboard.
|
|
14
21
|
*/
|
|
15
22
|
|
|
16
23
|
declare function OPTIONS(): Promise<NextResponse<unknown>>;
|
|
24
|
+
/**
|
|
25
|
+
* Forward one tracker event to the CMS, stamped with this site's project ID,
|
|
26
|
+
* API key, any CDN-provided geo headers, and the visitor's User-Agent.
|
|
27
|
+
*
|
|
28
|
+
* Without the visitor's UA the CMS sees this server's Node fetch UA, buckets
|
|
29
|
+
* every proxied visit as browser/OS "Other", and its bot filter never fires
|
|
30
|
+
* (BL-704). It is sent twice: as the outbound `User-Agent` header (what CMS
|
|
31
|
+
* builds before BL-704 read, and what the hand-rolled app proxies send) and as
|
|
32
|
+
* `ua` in the body, which the CMS prefers and trusts only on a validated key.
|
|
33
|
+
*
|
|
34
|
+
* Status contract:
|
|
35
|
+
* 503 — VULCANTECH_PROJECT_ID or VULCANTECH_API_KEY is unset.
|
|
36
|
+
* 400 — the request body is not parseable JSON.
|
|
37
|
+
* 204 — EVERYTHING else, including when the CMS was unreachable, rejected
|
|
38
|
+
* the event, or dropped it (bad scope, bot user agent, rate limit).
|
|
39
|
+
*
|
|
40
|
+
* So a 204 is not evidence of ingestion. This is deliberate: the forward is
|
|
41
|
+
* awaited but its result is discarded, because analytics must never block or
|
|
42
|
+
* break a page.
|
|
43
|
+
*/
|
|
17
44
|
declare function POST(req: NextRequest): Promise<NextResponse<unknown>>;
|
|
18
45
|
|
|
19
46
|
export { OPTIONS, POST };
|
package/dist/route.js
CHANGED
|
@@ -35,18 +35,21 @@ async function POST(req) {
|
|
|
35
35
|
return new server.NextResponse(null, { status: 400, headers: corsHeaders });
|
|
36
36
|
}
|
|
37
37
|
const geo = extractGeo(req);
|
|
38
|
+
const ua = req.headers.get("user-agent") || "";
|
|
38
39
|
try {
|
|
39
40
|
await fetch(`${CMS_URL}/api/analytics`, {
|
|
40
41
|
method: "POST",
|
|
41
42
|
headers: {
|
|
42
43
|
"Content-Type": "application/json",
|
|
44
|
+
"User-Agent": ua,
|
|
43
45
|
"X-Forwarded-For": req.headers.get("x-forwarded-for") || req.headers.get("x-real-ip") || ""
|
|
44
46
|
},
|
|
45
47
|
body: JSON.stringify({
|
|
46
48
|
event,
|
|
47
49
|
projectId: PROJECT_ID,
|
|
48
50
|
apiKey: API_KEY,
|
|
49
|
-
geo
|
|
51
|
+
geo,
|
|
52
|
+
ua
|
|
50
53
|
}),
|
|
51
54
|
cache: "no-store"
|
|
52
55
|
});
|
package/dist/route.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/route.ts"],"names":["NextResponse"],"mappings":";;;;;
|
|
1
|
+
{"version":3,"sources":["../src/route.ts"],"names":["NextResponse"],"mappings":";;;;;AAsBA,IAAM,WAAA,GAAc;AAAA,EAClB,6BAAA,EAA+B,GAAA;AAAA,EAC/B,8BAAA,EAAgC,eAAA;AAAA,EAChC,8BAAA,EAAgC;AAClC,CAAA;AAGA,SAAS,WAAW,GAAA,EAA0C;AAC5D,EAAA,MAAM,MAA8B,EAAC;AACrC,EAAA,MAAM,OAAA,GACJ,IAAI,OAAA,CAAQ,GAAA,CAAI,cAAc,CAAA,IAC9B,GAAA,CAAI,OAAA,CAAQ,GAAA,CAAI,qBAAqB,CAAA;AACvC,EAAA,MAAM,IAAA,GACJ,IAAI,OAAA,CAAQ,GAAA,CAAI,WAAW,CAAA,IAAK,GAAA,CAAI,OAAA,CAAQ,GAAA,CAAI,kBAAkB,CAAA;AACpE,EAAA,MAAM,MAAA,GACJ,IAAI,OAAA,CAAQ,GAAA,CAAI,WAAW,CAAA,IAC3B,GAAA,CAAI,OAAA,CAAQ,GAAA,CAAI,4BAA4B,CAAA;AAC9C,EAAA,IAAI,OAAA,MAAa,OAAA,GAAU,OAAA;AAC3B,EAAA,IAAI,IAAA,EAAM,GAAA,CAAI,IAAA,GAAO,kBAAA,CAAmB,IAAI,CAAA;AAC5C,EAAA,IAAI,MAAA,EAAQ,GAA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,KACjC,GAAA,CAAI,OAAA,CAAQ,GAAA,CAAI,WAAW,CAAA,IAC3B;AAAA,OACJ;AAAA,MACA,IAAA,EAAM,KAAK,SAAA,CAAU;AAAA,QACnB,KAAA;AAAA,QACA,SAAA,EAAW,UAAA;AAAA,QACX,MAAA,EAAQ,OAAA;AAAA,QACR,GAAA;AAAA,QACA;AAAA,OACD,CAAA;AAAA,MACD,KAAA,EAAO;AAAA,KACR,CAAA;AAAA,EACH,CAAA,CAAA,MAAQ;AAAA,EAER;AAEA,EAAA,OAAO,IAAIA,oBAAa,IAAA,EAAM,EAAE,QAAQ,GAAA,EAAK,OAAA,EAAS,aAAa,CAAA;AACrE","file":"route.js","sourcesContent":["/**\n * Next.js App Router analytics proxy route handler.\n *\n * Re-export from your app's /api/a/route.ts:\n *\n * export { POST, OPTIONS } from \"@vulcantech/analytics/route\";\n *\n * Required env vars:\n * VULCANTECH_CMS_URL — CMS base URL (defaults to https://cms.vulcantech.io)\n * VULCANTECH_PROJECT_ID — project ID for this site\n * VULCANTECH_API_KEY — API key for this site\n *\n * The API key must carry the `analytics:write` scope — the scope the CMS's\n * POST /api/analytics enforces. This is a DIFFERENT scope from the\n * `analytics:read` that CMSTags needs for tag config; a site doing both needs\n * both on the one key. A key missing `analytics:write` drops every event while\n * this route still answers 204 (see POST below), so the misconfiguration is\n * invisible from the browser — verify ingestion in the CMS dashboard.\n */\n\nimport { NextRequest, NextResponse } from \"next/server\";\n\nconst corsHeaders = {\n \"Access-Control-Allow-Origin\": \"*\",\n \"Access-Control-Allow-Methods\": \"POST, OPTIONS\",\n \"Access-Control-Allow-Headers\": \"Content-Type\",\n};\n\n/** Extract geo data from Cloudflare/Vercel headers if available. */\nfunction extractGeo(req: NextRequest): Record<string, string> {\n const geo: Record<string, string> = {};\n const country =\n req.headers.get(\"cf-ipcountry\") ||\n req.headers.get(\"x-vercel-ip-country\");\n const city =\n req.headers.get(\"cf-ipcity\") || req.headers.get(\"x-vercel-ip-city\");\n const region =\n req.headers.get(\"cf-region\") ||\n req.headers.get(\"x-vercel-ip-country-region\");\n if (country) geo.country = country;\n if (city) geo.city = decodeURIComponent(city);\n if (region) geo.region = decodeURIComponent(region);\n return geo;\n}\n\nexport async function OPTIONS() {\n return new NextResponse(null, { status: 204, headers: corsHeaders });\n}\n\n/**\n * Forward one tracker event to the CMS, stamped with this site's project ID,\n * API key, any CDN-provided geo headers, and the visitor's User-Agent.\n *\n * Without the visitor's UA the CMS sees this server's Node fetch UA, buckets\n * every proxied visit as browser/OS \"Other\", and its bot filter never fires\n * (BL-704). It is sent twice: as the outbound `User-Agent` header (what CMS\n * builds before BL-704 read, and what the hand-rolled app proxies send) and as\n * `ua` in the body, which the CMS prefers and trusts only on a validated key.\n *\n * Status contract:\n * 503 — VULCANTECH_PROJECT_ID or VULCANTECH_API_KEY is unset.\n * 400 — the request body is not parseable JSON.\n * 204 — EVERYTHING else, including when the CMS was unreachable, rejected\n * the event, or dropped it (bad scope, bot user agent, rate limit).\n *\n * So a 204 is not evidence of ingestion. This is deliberate: the forward is\n * awaited but its result is discarded, because analytics must never block or\n * break a page.\n */\nexport async function POST(req: NextRequest) {\n const CMS_URL =\n process.env.VULCANTECH_CMS_URL || \"https://cms.vulcantech.io\";\n const PROJECT_ID = process.env.VULCANTECH_PROJECT_ID;\n const API_KEY = process.env.VULCANTECH_API_KEY;\n\n if (!PROJECT_ID || !API_KEY) {\n return new NextResponse(null, { status: 503, headers: corsHeaders });\n }\n\n let event: unknown;\n try {\n event = await req.json();\n } catch {\n return new NextResponse(null, { status: 400, headers: corsHeaders });\n }\n\n const geo = extractGeo(req);\n const ua = req.headers.get(\"user-agent\") || \"\";\n\n try {\n await fetch(`${CMS_URL}/api/analytics`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"User-Agent\": ua,\n \"X-Forwarded-For\":\n req.headers.get(\"x-forwarded-for\") ||\n req.headers.get(\"x-real-ip\") ||\n \"\",\n },\n body: JSON.stringify({\n event,\n projectId: PROJECT_ID,\n apiKey: API_KEY,\n geo,\n ua,\n }),\n cache: \"no-store\",\n });\n } catch {\n // Silent fail — analytics should never break the app\n }\n\n return new NextResponse(null, { status: 204, headers: corsHeaders });\n}\n"]}
|
package/dist/route.mjs
CHANGED
|
@@ -33,18 +33,21 @@ async function POST(req) {
|
|
|
33
33
|
return new NextResponse(null, { status: 400, headers: corsHeaders });
|
|
34
34
|
}
|
|
35
35
|
const geo = extractGeo(req);
|
|
36
|
+
const ua = req.headers.get("user-agent") || "";
|
|
36
37
|
try {
|
|
37
38
|
await fetch(`${CMS_URL}/api/analytics`, {
|
|
38
39
|
method: "POST",
|
|
39
40
|
headers: {
|
|
40
41
|
"Content-Type": "application/json",
|
|
42
|
+
"User-Agent": ua,
|
|
41
43
|
"X-Forwarded-For": req.headers.get("x-forwarded-for") || req.headers.get("x-real-ip") || ""
|
|
42
44
|
},
|
|
43
45
|
body: JSON.stringify({
|
|
44
46
|
event,
|
|
45
47
|
projectId: PROJECT_ID,
|
|
46
48
|
apiKey: API_KEY,
|
|
47
|
-
geo
|
|
49
|
+
geo,
|
|
50
|
+
ua
|
|
48
51
|
}),
|
|
49
52
|
cache: "no-store"
|
|
50
53
|
});
|
package/dist/route.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/route.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"sources":["../src/route.ts"],"names":[],"mappings":";;;AAsBA,IAAM,WAAA,GAAc;AAAA,EAClB,6BAAA,EAA+B,GAAA;AAAA,EAC/B,8BAAA,EAAgC,eAAA;AAAA,EAChC,8BAAA,EAAgC;AAClC,CAAA;AAGA,SAAS,WAAW,GAAA,EAA0C;AAC5D,EAAA,MAAM,MAA8B,EAAC;AACrC,EAAA,MAAM,OAAA,GACJ,IAAI,OAAA,CAAQ,GAAA,CAAI,cAAc,CAAA,IAC9B,GAAA,CAAI,OAAA,CAAQ,GAAA,CAAI,qBAAqB,CAAA;AACvC,EAA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AEA,EAAA,MAAM,GAAA,GAAM,WAAW,GAAG,CAAA;AAC1B,EAAA,MAAM,EAAA,GAAK,GAAA,CAAI,OAAA,CAAQ,GAAA,CAAI,YAAY,CAAA,IAAK,EAAA;AAE5C,EAAA,IAAI;AACF,IAAA,MAAM,KAAA,CAAM,CAAA,EAAG,OAAO,CAAA,cAAA,CAAA,EAAkB;AAAA,MACtC,MAAA,EAAQ,MAAA;AAAA,MACR,OAAA,EAAS;AAAA,QACP,cAAA,EAAgB,kBAAA;AAAA,QAChB,YAAA,EAAc,EAAA;AAAA,QACd,iBAAA,EACE,GAAA,CAAI,OAAA,CAAQ,GAAA,CAAI,iBAAiB,KACjC,GAAA,CAAI,OAAA,CAAQ,GAAA,CAAI,WAAW,CAAA,IAC3B;AAAA,OACJ;AAAA,MACA,IAAA,EAAM,KAAK,SAAA,CAAU;AAAA,QACnB,KAAA;AAAA,QACA,SAAA,EAAW,UAAA;AAAA,QACX,MAAA,EAAQ,OAAA;AAAA,QACR,GAAA;AAAA,QACA;AAAA,OACD,CAAA;AAAA,MACD,KAAA,EAAO;AAAA,KACR,CAAA;AAAA,EACH,CAAA,CAAA,MAAQ;AAAA,EAER;AAEA,EAAA,OAAO,IAAI,aAAa,IAAA,EAAM,EAAE,QAAQ,GAAA,EAAK,OAAA,EAAS,aAAa,CAAA;AACrE","file":"route.mjs","sourcesContent":["/**\n * Next.js App Router analytics proxy route handler.\n *\n * Re-export from your app's /api/a/route.ts:\n *\n * export { POST, OPTIONS } from \"@vulcantech/analytics/route\";\n *\n * Required env vars:\n * VULCANTECH_CMS_URL — CMS base URL (defaults to https://cms.vulcantech.io)\n * VULCANTECH_PROJECT_ID — project ID for this site\n * VULCANTECH_API_KEY — API key for this site\n *\n * The API key must carry the `analytics:write` scope — the scope the CMS's\n * POST /api/analytics enforces. This is a DIFFERENT scope from the\n * `analytics:read` that CMSTags needs for tag config; a site doing both needs\n * both on the one key. A key missing `analytics:write` drops every event while\n * this route still answers 204 (see POST below), so the misconfiguration is\n * invisible from the browser — verify ingestion in the CMS dashboard.\n */\n\nimport { NextRequest, NextResponse } from \"next/server\";\n\nconst corsHeaders = {\n \"Access-Control-Allow-Origin\": \"*\",\n \"Access-Control-Allow-Methods\": \"POST, OPTIONS\",\n \"Access-Control-Allow-Headers\": \"Content-Type\",\n};\n\n/** Extract geo data from Cloudflare/Vercel headers if available. */\nfunction extractGeo(req: NextRequest): Record<string, string> {\n const geo: Record<string, string> = {};\n const country =\n req.headers.get(\"cf-ipcountry\") ||\n req.headers.get(\"x-vercel-ip-country\");\n const city =\n req.headers.get(\"cf-ipcity\") || req.headers.get(\"x-vercel-ip-city\");\n const region =\n req.headers.get(\"cf-region\") ||\n req.headers.get(\"x-vercel-ip-country-region\");\n if (country) geo.country = country;\n if (city) geo.city = decodeURIComponent(city);\n if (region) geo.region = decodeURIComponent(region);\n return geo;\n}\n\nexport async function OPTIONS() {\n return new NextResponse(null, { status: 204, headers: corsHeaders });\n}\n\n/**\n * Forward one tracker event to the CMS, stamped with this site's project ID,\n * API key, any CDN-provided geo headers, and the visitor's User-Agent.\n *\n * Without the visitor's UA the CMS sees this server's Node fetch UA, buckets\n * every proxied visit as browser/OS \"Other\", and its bot filter never fires\n * (BL-704). It is sent twice: as the outbound `User-Agent` header (what CMS\n * builds before BL-704 read, and what the hand-rolled app proxies send) and as\n * `ua` in the body, which the CMS prefers and trusts only on a validated key.\n *\n * Status contract:\n * 503 — VULCANTECH_PROJECT_ID or VULCANTECH_API_KEY is unset.\n * 400 — the request body is not parseable JSON.\n * 204 — EVERYTHING else, including when the CMS was unreachable, rejected\n * the event, or dropped it (bad scope, bot user agent, rate limit).\n *\n * So a 204 is not evidence of ingestion. This is deliberate: the forward is\n * awaited but its result is discarded, because analytics must never block or\n * break a page.\n */\nexport async function POST(req: NextRequest) {\n const CMS_URL =\n process.env.VULCANTECH_CMS_URL || \"https://cms.vulcantech.io\";\n const PROJECT_ID = process.env.VULCANTECH_PROJECT_ID;\n const API_KEY = process.env.VULCANTECH_API_KEY;\n\n if (!PROJECT_ID || !API_KEY) {\n return new NextResponse(null, { status: 503, headers: corsHeaders });\n }\n\n let event: unknown;\n try {\n event = await req.json();\n } catch {\n return new NextResponse(null, { status: 400, headers: corsHeaders });\n }\n\n const geo = extractGeo(req);\n const ua = req.headers.get(\"user-agent\") || \"\";\n\n try {\n await fetch(`${CMS_URL}/api/analytics`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"User-Agent\": ua,\n \"X-Forwarded-For\":\n req.headers.get(\"x-forwarded-for\") ||\n req.headers.get(\"x-real-ip\") ||\n \"\",\n },\n body: JSON.stringify({\n event,\n projectId: PROJECT_ID,\n apiKey: API_KEY,\n geo,\n ua,\n }),\n cache: \"no-store\",\n });\n } catch {\n // Silent fail — analytics should never break the app\n }\n\n return new NextResponse(null, { status: 204, headers: corsHeaders });\n}\n"]}
|
package/dist/tags.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import * as
|
|
1
|
+
import * as react from 'react';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* CMS-driven third-party tracking-tag injection (server-side).
|
|
@@ -16,29 +16,92 @@ import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
|
16
16
|
* VULCANTECH_API_KEY — API key for this site (needs the analytics:read scope)
|
|
17
17
|
*
|
|
18
18
|
* Optional env fallbacks (used only when the CMS omits a field):
|
|
19
|
-
* NEXT_PUBLIC_GA_ID
|
|
20
|
-
* NEXT_PUBLIC_GOOGLE_ADS_ID
|
|
21
|
-
* NEXT_PUBLIC_META_PIXEL_ID
|
|
19
|
+
* NEXT_PUBLIC_GA_ID → ga4Id
|
|
20
|
+
* NEXT_PUBLIC_GOOGLE_ADS_ID → googleAdsId
|
|
21
|
+
* NEXT_PUBLIC_META_PIXEL_ID → metaPixelId
|
|
22
|
+
* NEXT_PUBLIC_FORM_CONVERSION_SEND_TO → formConversionSendTo
|
|
23
|
+
* NEXT_PUBLIC_PHONE_CONVERSION_SEND_TO → phoneConversionSendTo
|
|
24
|
+
* NEXT_PUBLIC_CALL_CONVERSION_SEND_TO → callConversionSendTo
|
|
25
|
+
* NEXT_PUBLIC_CALL_CONVERSION_NUMBER → callConversionNumber
|
|
26
|
+
* NEXT_PUBLIC_ENHANCED_CONVERSIONS=true → enhancedConversions
|
|
27
|
+
*
|
|
28
|
+
* All four of the last are CMS dashboard fields too (BL-1059). Note that
|
|
29
|
+
* enhancedConversions is ON when either source says so — an env `true`
|
|
30
|
+
* cannot be switched off from the CMS; unset the env var for that.
|
|
31
|
+
*/
|
|
32
|
+
/**
|
|
33
|
+
* Tracking tag IDs resolved for a project (CMS value wins, else env fallback).
|
|
34
|
+
*
|
|
35
|
+
* Public IDs only — the CMS strips its internal `enabled` and `updatedAt`
|
|
36
|
+
* fields before returning the config to a consumer site.
|
|
37
|
+
*
|
|
38
|
+
* The documented formats are validated CMS-side when a staff user saves the
|
|
39
|
+
* config in the dashboard. Values arriving from the NEXT_PUBLIC_* env
|
|
40
|
+
* fallbacks are NOT validated by this package and are injected verbatim.
|
|
22
41
|
*/
|
|
23
|
-
/** Tracking tag IDs resolved for a project (CMS value wins, else env fallback). */
|
|
24
42
|
interface TrackingTags {
|
|
25
|
-
/** GA4 measurement ID
|
|
43
|
+
/** GA4 measurement ID. CMS-validated against /^G-[A-Z0-9]{4,14}$/. */
|
|
26
44
|
ga4Id?: string;
|
|
27
|
-
/** Google Ads conversion ID
|
|
45
|
+
/** Google Ads conversion ID. CMS-validated against /^AW-\d{6,12}$/. */
|
|
28
46
|
googleAdsId?: string;
|
|
29
|
-
/** Meta (Facebook) Pixel ID. */
|
|
47
|
+
/** Meta (Facebook) Pixel ID — numeric string. CMS-validated against /^\d{6,20}$/. */
|
|
30
48
|
metaPixelId?: string;
|
|
49
|
+
/**
|
|
50
|
+
* Site-wide Google Ads `send_to` label fired when a `@vulcantech/forms`
|
|
51
|
+
* form submits successfully, e.g. `"AW-18321257894/AbC-D3fGhIjKlmNoP"`.
|
|
52
|
+
* CMS-validated against /^AW-\d{6,12}\/[A-Za-z0-9_-]{6,64}$/.
|
|
53
|
+
*
|
|
54
|
+
* Not a tag loader: {@link CMSTags} publishes it on
|
|
55
|
+
* `window.__vtFormConversionSendTo`, where the forms package reads it. A
|
|
56
|
+
* form's own `submitConfig.conversion.sendTo` overrides it.
|
|
57
|
+
*/
|
|
58
|
+
formConversionSendTo?: string;
|
|
59
|
+
/**
|
|
60
|
+
* Google Ads `send_to` label fired on every `tel:` link tap. Published on
|
|
61
|
+
* `window.__vtPhoneConversionSendTo`, where `trackPhoneClick` reads it.
|
|
62
|
+
*/
|
|
63
|
+
phoneConversionSendTo?: string;
|
|
64
|
+
/**
|
|
65
|
+
* Google forwarding-number ("website call conversion") label, e.g.
|
|
66
|
+
* `"AW-123/AbC"`. With {@link callConversionNumber} set, CMSTags configures
|
|
67
|
+
* Google's number swap; render numbers through `PhoneLink` so the swapped
|
|
68
|
+
* number survives React re-renders.
|
|
69
|
+
*/
|
|
70
|
+
callConversionSendTo?: string;
|
|
71
|
+
/**
|
|
72
|
+
* The phone number exactly as the page displays it (e.g. `"602.904.9109"`).
|
|
73
|
+
* Google only swaps a number that matches this string.
|
|
74
|
+
*/
|
|
75
|
+
callConversionNumber?: string;
|
|
76
|
+
/**
|
|
77
|
+
* Opt into Google Ads enhanced conversions: `@vulcantech/forms` sends the
|
|
78
|
+
* lead's email/phone (hashed by gtag) with the form conversion. The site's
|
|
79
|
+
* privacy policy must disclose it.
|
|
80
|
+
*/
|
|
81
|
+
enhancedConversions?: boolean;
|
|
31
82
|
}
|
|
32
83
|
/**
|
|
33
84
|
* Fetch the tracking-tag config for this project from the CMS, merging in
|
|
34
85
|
* env fallbacks per field (CMS value wins when present).
|
|
35
86
|
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
38
|
-
*
|
|
87
|
+
* Server-only: reads VULCANTECH_API_KEY, so never call it from client code.
|
|
88
|
+
*
|
|
89
|
+
* Never throws — tags must never break a page build. CMS errors (unreachable,
|
|
90
|
+
* non-2xx, missing env, key lacking the `analytics:read` scope) are swallowed
|
|
91
|
+
* and the env fallbacks apply instead. Returns `null` — NOT `{}` — when all
|
|
92
|
+
* three tag IDs end up empty, otherwise a {@link TrackingTags} object.
|
|
93
|
+
*
|
|
94
|
+
* ⚠ Turning tracking tags OFF in the CMS does not necessarily disable them.
|
|
95
|
+
* The CMS returns `config: null` for "disabled" and "never configured" alike,
|
|
96
|
+
* and this function then fills every field from NEXT_PUBLIC_GA_ID /
|
|
97
|
+
* NEXT_PUBLIC_GOOGLE_ADS_ID / NEXT_PUBLIC_META_PIXEL_ID. A site with those env
|
|
98
|
+
* vars set keeps firing its tags after the CMS switch is off; disabling it
|
|
99
|
+
* there requires unsetting the env vars and redeploying. Sites with no
|
|
100
|
+
* NEXT_PUBLIC_* fallbacks honor the toggle as expected.
|
|
39
101
|
*
|
|
40
102
|
* The fetch is ISR-cached (`revalidate: 60`) and tagged
|
|
41
|
-
* `tracking-tags:{projectId}` so the CMS can purge it on config change
|
|
103
|
+
* `tracking-tags:{projectId}` so the CMS can purge it on config change — so a
|
|
104
|
+
* CMS value change reaches the site within ~60s with no redeploy.
|
|
42
105
|
*/
|
|
43
106
|
declare function fetchTrackingTags(): Promise<TrackingTags | null>;
|
|
44
107
|
/**
|
|
@@ -49,10 +112,31 @@ declare function fetchTrackingTags(): Promise<TrackingTags | null>;
|
|
|
49
112
|
* import { CMSTags } from "@vulcantech/analytics/tags";
|
|
50
113
|
* // <body> ... <CMSTags /> ... </body>
|
|
51
114
|
*
|
|
52
|
-
*
|
|
53
|
-
*
|
|
54
|
-
*
|
|
115
|
+
* Async React Server Component — do NOT wrap it in a "use client" component.
|
|
116
|
+
*
|
|
117
|
+
* Renders, via next/script with `strategy="afterInteractive"`:
|
|
118
|
+
* - ONE shared gtag.js loader keyed to the FIRST present Google ID, plus an
|
|
119
|
+
* inline init that gtag('config', …)s every present Google ID. Google Ads
|
|
120
|
+
* rides the GA4 loader — there is no separate gtag/js?id=AW-… request.
|
|
121
|
+
* The same inline script publishes `formConversionSendTo` (when set) on
|
|
122
|
+
* `window.__vtFormConversionSendTo`, which is where `@vulcantech/forms`
|
|
123
|
+
* looks for the Ads label to fire on a successful submission. Likewise
|
|
124
|
+
* `phoneConversionSendTo` → `window.__vtPhoneConversionSendTo` and
|
|
125
|
+
* `enhancedConversions` → `window.__vtEnhancedConversions`. With a
|
|
126
|
+
* `callConversionSendTo` + `callConversionNumber`, it also configures
|
|
127
|
+
* Google's forwarding-number swap; the callback stores the number on
|
|
128
|
+
* `window.__vtPhone` and dispatches `vt-phone` for `PhoneLink`.
|
|
129
|
+
* - The standard inline Meta Pixel bootstrap with fbq('track','PageView')
|
|
130
|
+
* and a <noscript> tracking-pixel <img>.
|
|
131
|
+
* - `null` when nothing is configured (see {@link fetchTrackingTags}).
|
|
132
|
+
*
|
|
133
|
+
* Because it uses next/script, mounting it in <body> is correct; it does not
|
|
134
|
+
* need to be in <head>.
|
|
135
|
+
*
|
|
136
|
+
* ⚠ NO CONSENT GATING. Tags load as soon as the page hydrates. This component
|
|
137
|
+
* provides no CMP/GDPR gate and must not be mounted unconditionally on a site
|
|
138
|
+
* that requires consent before loading third-party trackers.
|
|
55
139
|
*/
|
|
56
|
-
declare function CMSTags(): Promise<
|
|
140
|
+
declare function CMSTags(): Promise<react.JSX.Element | null>;
|
|
57
141
|
|
|
58
142
|
export { CMSTags, type TrackingTags, fetchTrackingTags };
|
package/dist/tags.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import * as
|
|
1
|
+
import * as react from 'react';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* CMS-driven third-party tracking-tag injection (server-side).
|
|
@@ -16,29 +16,92 @@ import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
|
16
16
|
* VULCANTECH_API_KEY — API key for this site (needs the analytics:read scope)
|
|
17
17
|
*
|
|
18
18
|
* Optional env fallbacks (used only when the CMS omits a field):
|
|
19
|
-
* NEXT_PUBLIC_GA_ID
|
|
20
|
-
* NEXT_PUBLIC_GOOGLE_ADS_ID
|
|
21
|
-
* NEXT_PUBLIC_META_PIXEL_ID
|
|
19
|
+
* NEXT_PUBLIC_GA_ID → ga4Id
|
|
20
|
+
* NEXT_PUBLIC_GOOGLE_ADS_ID → googleAdsId
|
|
21
|
+
* NEXT_PUBLIC_META_PIXEL_ID → metaPixelId
|
|
22
|
+
* NEXT_PUBLIC_FORM_CONVERSION_SEND_TO → formConversionSendTo
|
|
23
|
+
* NEXT_PUBLIC_PHONE_CONVERSION_SEND_TO → phoneConversionSendTo
|
|
24
|
+
* NEXT_PUBLIC_CALL_CONVERSION_SEND_TO → callConversionSendTo
|
|
25
|
+
* NEXT_PUBLIC_CALL_CONVERSION_NUMBER → callConversionNumber
|
|
26
|
+
* NEXT_PUBLIC_ENHANCED_CONVERSIONS=true → enhancedConversions
|
|
27
|
+
*
|
|
28
|
+
* All four of the last are CMS dashboard fields too (BL-1059). Note that
|
|
29
|
+
* enhancedConversions is ON when either source says so — an env `true`
|
|
30
|
+
* cannot be switched off from the CMS; unset the env var for that.
|
|
31
|
+
*/
|
|
32
|
+
/**
|
|
33
|
+
* Tracking tag IDs resolved for a project (CMS value wins, else env fallback).
|
|
34
|
+
*
|
|
35
|
+
* Public IDs only — the CMS strips its internal `enabled` and `updatedAt`
|
|
36
|
+
* fields before returning the config to a consumer site.
|
|
37
|
+
*
|
|
38
|
+
* The documented formats are validated CMS-side when a staff user saves the
|
|
39
|
+
* config in the dashboard. Values arriving from the NEXT_PUBLIC_* env
|
|
40
|
+
* fallbacks are NOT validated by this package and are injected verbatim.
|
|
22
41
|
*/
|
|
23
|
-
/** Tracking tag IDs resolved for a project (CMS value wins, else env fallback). */
|
|
24
42
|
interface TrackingTags {
|
|
25
|
-
/** GA4 measurement ID
|
|
43
|
+
/** GA4 measurement ID. CMS-validated against /^G-[A-Z0-9]{4,14}$/. */
|
|
26
44
|
ga4Id?: string;
|
|
27
|
-
/** Google Ads conversion ID
|
|
45
|
+
/** Google Ads conversion ID. CMS-validated against /^AW-\d{6,12}$/. */
|
|
28
46
|
googleAdsId?: string;
|
|
29
|
-
/** Meta (Facebook) Pixel ID. */
|
|
47
|
+
/** Meta (Facebook) Pixel ID — numeric string. CMS-validated against /^\d{6,20}$/. */
|
|
30
48
|
metaPixelId?: string;
|
|
49
|
+
/**
|
|
50
|
+
* Site-wide Google Ads `send_to` label fired when a `@vulcantech/forms`
|
|
51
|
+
* form submits successfully, e.g. `"AW-18321257894/AbC-D3fGhIjKlmNoP"`.
|
|
52
|
+
* CMS-validated against /^AW-\d{6,12}\/[A-Za-z0-9_-]{6,64}$/.
|
|
53
|
+
*
|
|
54
|
+
* Not a tag loader: {@link CMSTags} publishes it on
|
|
55
|
+
* `window.__vtFormConversionSendTo`, where the forms package reads it. A
|
|
56
|
+
* form's own `submitConfig.conversion.sendTo` overrides it.
|
|
57
|
+
*/
|
|
58
|
+
formConversionSendTo?: string;
|
|
59
|
+
/**
|
|
60
|
+
* Google Ads `send_to` label fired on every `tel:` link tap. Published on
|
|
61
|
+
* `window.__vtPhoneConversionSendTo`, where `trackPhoneClick` reads it.
|
|
62
|
+
*/
|
|
63
|
+
phoneConversionSendTo?: string;
|
|
64
|
+
/**
|
|
65
|
+
* Google forwarding-number ("website call conversion") label, e.g.
|
|
66
|
+
* `"AW-123/AbC"`. With {@link callConversionNumber} set, CMSTags configures
|
|
67
|
+
* Google's number swap; render numbers through `PhoneLink` so the swapped
|
|
68
|
+
* number survives React re-renders.
|
|
69
|
+
*/
|
|
70
|
+
callConversionSendTo?: string;
|
|
71
|
+
/**
|
|
72
|
+
* The phone number exactly as the page displays it (e.g. `"602.904.9109"`).
|
|
73
|
+
* Google only swaps a number that matches this string.
|
|
74
|
+
*/
|
|
75
|
+
callConversionNumber?: string;
|
|
76
|
+
/**
|
|
77
|
+
* Opt into Google Ads enhanced conversions: `@vulcantech/forms` sends the
|
|
78
|
+
* lead's email/phone (hashed by gtag) with the form conversion. The site's
|
|
79
|
+
* privacy policy must disclose it.
|
|
80
|
+
*/
|
|
81
|
+
enhancedConversions?: boolean;
|
|
31
82
|
}
|
|
32
83
|
/**
|
|
33
84
|
* Fetch the tracking-tag config for this project from the CMS, merging in
|
|
34
85
|
* env fallbacks per field (CMS value wins when present).
|
|
35
86
|
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
38
|
-
*
|
|
87
|
+
* Server-only: reads VULCANTECH_API_KEY, so never call it from client code.
|
|
88
|
+
*
|
|
89
|
+
* Never throws — tags must never break a page build. CMS errors (unreachable,
|
|
90
|
+
* non-2xx, missing env, key lacking the `analytics:read` scope) are swallowed
|
|
91
|
+
* and the env fallbacks apply instead. Returns `null` — NOT `{}` — when all
|
|
92
|
+
* three tag IDs end up empty, otherwise a {@link TrackingTags} object.
|
|
93
|
+
*
|
|
94
|
+
* ⚠ Turning tracking tags OFF in the CMS does not necessarily disable them.
|
|
95
|
+
* The CMS returns `config: null` for "disabled" and "never configured" alike,
|
|
96
|
+
* and this function then fills every field from NEXT_PUBLIC_GA_ID /
|
|
97
|
+
* NEXT_PUBLIC_GOOGLE_ADS_ID / NEXT_PUBLIC_META_PIXEL_ID. A site with those env
|
|
98
|
+
* vars set keeps firing its tags after the CMS switch is off; disabling it
|
|
99
|
+
* there requires unsetting the env vars and redeploying. Sites with no
|
|
100
|
+
* NEXT_PUBLIC_* fallbacks honor the toggle as expected.
|
|
39
101
|
*
|
|
40
102
|
* The fetch is ISR-cached (`revalidate: 60`) and tagged
|
|
41
|
-
* `tracking-tags:{projectId}` so the CMS can purge it on config change
|
|
103
|
+
* `tracking-tags:{projectId}` so the CMS can purge it on config change — so a
|
|
104
|
+
* CMS value change reaches the site within ~60s with no redeploy.
|
|
42
105
|
*/
|
|
43
106
|
declare function fetchTrackingTags(): Promise<TrackingTags | null>;
|
|
44
107
|
/**
|
|
@@ -49,10 +112,31 @@ declare function fetchTrackingTags(): Promise<TrackingTags | null>;
|
|
|
49
112
|
* import { CMSTags } from "@vulcantech/analytics/tags";
|
|
50
113
|
* // <body> ... <CMSTags /> ... </body>
|
|
51
114
|
*
|
|
52
|
-
*
|
|
53
|
-
*
|
|
54
|
-
*
|
|
115
|
+
* Async React Server Component — do NOT wrap it in a "use client" component.
|
|
116
|
+
*
|
|
117
|
+
* Renders, via next/script with `strategy="afterInteractive"`:
|
|
118
|
+
* - ONE shared gtag.js loader keyed to the FIRST present Google ID, plus an
|
|
119
|
+
* inline init that gtag('config', …)s every present Google ID. Google Ads
|
|
120
|
+
* rides the GA4 loader — there is no separate gtag/js?id=AW-… request.
|
|
121
|
+
* The same inline script publishes `formConversionSendTo` (when set) on
|
|
122
|
+
* `window.__vtFormConversionSendTo`, which is where `@vulcantech/forms`
|
|
123
|
+
* looks for the Ads label to fire on a successful submission. Likewise
|
|
124
|
+
* `phoneConversionSendTo` → `window.__vtPhoneConversionSendTo` and
|
|
125
|
+
* `enhancedConversions` → `window.__vtEnhancedConversions`. With a
|
|
126
|
+
* `callConversionSendTo` + `callConversionNumber`, it also configures
|
|
127
|
+
* Google's forwarding-number swap; the callback stores the number on
|
|
128
|
+
* `window.__vtPhone` and dispatches `vt-phone` for `PhoneLink`.
|
|
129
|
+
* - The standard inline Meta Pixel bootstrap with fbq('track','PageView')
|
|
130
|
+
* and a <noscript> tracking-pixel <img>.
|
|
131
|
+
* - `null` when nothing is configured (see {@link fetchTrackingTags}).
|
|
132
|
+
*
|
|
133
|
+
* Because it uses next/script, mounting it in <body> is correct; it does not
|
|
134
|
+
* need to be in <head>.
|
|
135
|
+
*
|
|
136
|
+
* ⚠ NO CONSENT GATING. Tags load as soon as the page hydrates. This component
|
|
137
|
+
* provides no CMP/GDPR gate and must not be mounted unconditionally on a site
|
|
138
|
+
* that requires consent before loading third-party trackers.
|
|
55
139
|
*/
|
|
56
|
-
declare function CMSTags(): Promise<
|
|
140
|
+
declare function CMSTags(): Promise<react.JSX.Element | null>;
|
|
57
141
|
|
|
58
142
|
export { CMSTags, type TrackingTags, fetchTrackingTags };
|
package/dist/tags.js
CHANGED
|
@@ -8,6 +8,12 @@ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
|
8
8
|
var Script__default = /*#__PURE__*/_interopDefault(Script);
|
|
9
9
|
|
|
10
10
|
// src/tags.tsx
|
|
11
|
+
var FORM_CONVERSION_SEND_TO_GLOBAL = "__vtFormConversionSendTo";
|
|
12
|
+
var ENHANCED_CONVERSIONS_GLOBAL = "__vtEnhancedConversions";
|
|
13
|
+
var PHONE_CONVERSION_SEND_TO_GLOBAL = "__vtPhoneConversionSendTo";
|
|
14
|
+
function js(value) {
|
|
15
|
+
return JSON.stringify(value).replace(/</g, "\\u003c");
|
|
16
|
+
}
|
|
11
17
|
async function fetchTrackingTags() {
|
|
12
18
|
const CMS_URL = process.env.VULCANTECH_CMS_URL || "https://cms.vulcantech.io";
|
|
13
19
|
const PROJECT_ID = process.env.VULCANTECH_PROJECT_ID;
|
|
@@ -34,7 +40,12 @@ async function fetchTrackingTags() {
|
|
|
34
40
|
const merged = {
|
|
35
41
|
ga4Id: cms?.ga4Id || process.env.NEXT_PUBLIC_GA_ID || void 0,
|
|
36
42
|
googleAdsId: cms?.googleAdsId || process.env.NEXT_PUBLIC_GOOGLE_ADS_ID || void 0,
|
|
37
|
-
metaPixelId: cms?.metaPixelId || process.env.NEXT_PUBLIC_META_PIXEL_ID || void 0
|
|
43
|
+
metaPixelId: cms?.metaPixelId || process.env.NEXT_PUBLIC_META_PIXEL_ID || void 0,
|
|
44
|
+
formConversionSendTo: cms?.formConversionSendTo || process.env.NEXT_PUBLIC_FORM_CONVERSION_SEND_TO || void 0,
|
|
45
|
+
phoneConversionSendTo: cms?.phoneConversionSendTo || process.env.NEXT_PUBLIC_PHONE_CONVERSION_SEND_TO || void 0,
|
|
46
|
+
callConversionSendTo: cms?.callConversionSendTo || process.env.NEXT_PUBLIC_CALL_CONVERSION_SEND_TO || void 0,
|
|
47
|
+
callConversionNumber: cms?.callConversionNumber || process.env.NEXT_PUBLIC_CALL_CONVERSION_NUMBER || void 0,
|
|
48
|
+
enhancedConversions: cms?.enhancedConversions === true || process.env.NEXT_PUBLIC_ENHANCED_CONVERSIONS === "true"
|
|
38
49
|
};
|
|
39
50
|
if (!merged.ga4Id && !merged.googleAdsId && !merged.metaPixelId) {
|
|
40
51
|
return null;
|
|
@@ -44,9 +55,35 @@ async function fetchTrackingTags() {
|
|
|
44
55
|
async function CMSTags() {
|
|
45
56
|
const tags = await fetchTrackingTags();
|
|
46
57
|
if (!tags) return null;
|
|
47
|
-
const {
|
|
58
|
+
const {
|
|
59
|
+
ga4Id,
|
|
60
|
+
googleAdsId,
|
|
61
|
+
metaPixelId,
|
|
62
|
+
formConversionSendTo,
|
|
63
|
+
phoneConversionSendTo,
|
|
64
|
+
callConversionSendTo,
|
|
65
|
+
callConversionNumber,
|
|
66
|
+
enhancedConversions
|
|
67
|
+
} = tags;
|
|
48
68
|
const googleIds = [ga4Id, googleAdsId].filter(Boolean);
|
|
49
69
|
const firstGoogleId = googleIds[0];
|
|
70
|
+
const sendToLine = formConversionSendTo ? `window.${FORM_CONVERSION_SEND_TO_GLOBAL} = ${JSON.stringify(
|
|
71
|
+
formConversionSendTo
|
|
72
|
+
).replace(/</g, "\\u003c")};` : "";
|
|
73
|
+
const extraLines = [
|
|
74
|
+
phoneConversionSendTo ? `window.${PHONE_CONVERSION_SEND_TO_GLOBAL} = ${js(phoneConversionSendTo)};` : "",
|
|
75
|
+
enhancedConversions ? `window.${ENHANCED_CONVERSIONS_GLOBAL} = true;` : "",
|
|
76
|
+
// Google's forwarding-number swap. Runs once per page load, after the
|
|
77
|
+
// plain configs — never re-run on route changes (each config call on a
|
|
78
|
+
// GA4 id would send another page view).
|
|
79
|
+
callConversionSendTo && callConversionNumber ? `gtag('config', ${js(callConversionSendTo)}, {
|
|
80
|
+
phone_conversion_number: ${js(callConversionNumber)},
|
|
81
|
+
phone_conversion_callback: function (formatted, mobile) {
|
|
82
|
+
window.__vtPhone = { formatted: formatted, mobile: mobile };
|
|
83
|
+
window.dispatchEvent(new Event('vt-phone'));
|
|
84
|
+
}
|
|
85
|
+
});` : ""
|
|
86
|
+
].filter(Boolean).join("\n");
|
|
50
87
|
return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
|
|
51
88
|
firstGoogleId && /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
|
|
52
89
|
/* @__PURE__ */ jsxRuntime.jsx(
|
|
@@ -61,7 +98,9 @@ async function CMSTags() {
|
|
|
61
98
|
/* @__PURE__ */ jsxRuntime.jsx(Script__default.default, { id: "vt-gtag-init", strategy: "afterInteractive", children: `window.dataLayer = window.dataLayer || [];
|
|
62
99
|
function gtag(){dataLayer.push(arguments);}
|
|
63
100
|
gtag('js', new Date());
|
|
64
|
-
${googleIds.map((id) => `gtag('config', '${id}');`).join("\n")}
|
|
101
|
+
${googleIds.map((id) => `gtag('config', '${id}');`).join("\n")}
|
|
102
|
+
${sendToLine}
|
|
103
|
+
${extraLines}` })
|
|
65
104
|
] }),
|
|
66
105
|
metaPixelId && /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
|
|
67
106
|
/* @__PURE__ */ jsxRuntime.jsx(Script__default.default, { id: "vt-meta-pixel", strategy: "afterInteractive", children: `!function(f,b,e,v,n,t,s)
|
package/dist/tags.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/tags.tsx"],"names":["jsxs","Fragment","jsx","Script"],"mappings":";;;;;;;;;;AA2DA,eAAsB,iBAAA,GAAkD;AACtE,EAAA,MAAM,OAAA,GAAU,OAAA,CAAQ,GAAA,CAAI,kBAAA,IAAsB,2BAAA;AAClD,EAAA,MAAM,UAAA,GAAa,QAAQ,GAAA,CAAI,qBAAA;AAC/B,EAAA,MAAM,OAAA,GAAU,QAAQ,GAAA,CAAI,kBAAA;AAE5B,EAAA,IAAI,G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MAAA,EAAO,GAAA;AAAA,UACP,KAAA,EAAM,GAAA;AAAA,UACN,KAAA,EAAO,EAAE,OAAA,EAAS,MAAA,EAAO;AAAA,UACzB,GAAA,EAAK,kCAAkC,WAAW,CAAA,uBAAA,CAAA;AAAA,UAClD,GAAA,EAAI;AAAA;AAAA,OACN,EACF;AAAA,KAAA,EACF;AAAA,GAAA,EAEJ,CAAA;AAEJ","file":"tags.js","sourcesContent":["/**\n * CMS-driven third-party tracking-tag injection (server-side).\n *\n * Fetches tag IDs (GA4 / Google Ads / Meta Pixel) configured for this\n * project in vulcantech-cms and renders the corresponding third-party\n * <Script> loaders — giving consumer sites \"codeless\" tag setup with no\n * hand-rolled gtag/fbq wiring in their own layout.\n *\n * This module is a React Server Component — do NOT add \"use client\".\n *\n * Required env vars:\n * VULCANTECH_CMS_URL — CMS base URL (defaults to https://cms.vulcantech.io)\n * VULCANTECH_PROJECT_ID — project ID for this site\n * VULCANTECH_API_KEY — API key for this site (needs the analytics:read scope)\n *\n * Optional env fallbacks (used only when the CMS omits a field):\n * NEXT_PUBLIC_GA_ID → ga4Id\n * NEXT_PUBLIC_GOOGLE_ADS_ID → googleAdsId\n * NEXT_PUBLIC_META_PIXEL_ID → metaPixelId\n */\n\nimport Script from \"next/script\";\n\n/** Tracking tag IDs resolved for a project (CMS value wins, else env fallback). */\nexport interface TrackingTags {\n /** GA4 measurement ID, e.g. \"G-XXXXXXXXXX\". */\n ga4Id?: string;\n /** Google Ads conversion ID, e.g. \"AW-XXXXXXXXX\". */\n googleAdsId?: string;\n /** Meta (Facebook) Pixel ID. */\n metaPixelId?: string;\n}\n\n/** Shape returned by GET {CMS_URL}/api/analytics/config. */\ninterface ConfigResponse {\n config: TrackingTags | null;\n}\n\n/**\n * fetch init with Next's ISR options. Passed as a typed variable (not an\n * object literal) so TS won't excess-property-check the `next` key — this\n * package doesn't load Next's global RequestInit augmentation. Mirrors the\n * collections/blog packages.\n */\ntype IsrFetchInit = RequestInit & {\n next?: { revalidate?: number; tags?: string[] };\n};\n\n/**\n * Fetch the tracking-tag config for this project from the CMS, merging in\n * env fallbacks per field (CMS value wins when present).\n *\n * Never throws — tags must never break a page build. Returns `null` when\n * all three tag IDs end up empty (nothing configured anywhere), otherwise a\n * {@link TrackingTags} object.\n *\n * The fetch is ISR-cached (`revalidate: 60`) and tagged\n * `tracking-tags:{projectId}` so the CMS can purge it on config change.\n */\nexport async function fetchTrackingTags(): Promise<TrackingTags | null> {\n const CMS_URL = process.env.VULCANTECH_CMS_URL || \"https://cms.vulcantech.io\";\n const PROJECT_ID = process.env.VULCANTECH_PROJECT_ID;\n const API_KEY = process.env.VULCANTECH_API_KEY;\n\n let cms: TrackingTags | null = null;\n\n if (PROJECT_ID && API_KEY) {\n try {\n const params = new URLSearchParams({\n projectId: PROJECT_ID,\n apiKey: API_KEY,\n });\n const init: IsrFetchInit = {\n next: { revalidate: 60, tags: [`tracking-tags:${PROJECT_ID}`] },\n };\n const res = await fetch(`${CMS_URL}/api/analytics/config?${params}`, init);\n if (res.ok) {\n const json = (await res.json()) as ConfigResponse;\n cms = json.config ?? null;\n }\n } catch {\n // Silent fail — fall through to env fallbacks below.\n cms = null;\n }\n }\n\n // CMS value wins per field; fill any gap from public env vars.\n const merged: TrackingTags = {\n ga4Id: cms?.ga4Id || process.env.NEXT_PUBLIC_GA_ID || undefined,\n googleAdsId:\n cms?.googleAdsId || process.env.NEXT_PUBLIC_GOOGLE_ADS_ID || undefined,\n metaPixelId:\n cms?.metaPixelId || process.env.NEXT_PUBLIC_META_PIXEL_ID || undefined,\n };\n\n if (!merged.ga4Id && !merged.googleAdsId && !merged.metaPixelId) {\n return null;\n }\n return merged;\n}\n\n/**\n * Drop-in server component that injects the project's tracking tags.\n *\n * Place once in your root layout's `<body>`:\n *\n * import { CMSTags } from \"@vulcantech/analytics/tags\";\n * // <body> ... <CMSTags /> ... </body>\n *\n * Renders one shared gtag.js loader + init (config'd for every present\n * Google ID: GA4 and/or Google Ads), the standard Meta Pixel bootstrap +\n * <noscript> fallback, or `null` when nothing is configured.\n */\nexport async function CMSTags() {\n const tags = await fetchTrackingTags();\n if (!tags) return null;\n\n const { ga4Id, googleAdsId, metaPixelId } = tags;\n const googleIds = [ga4Id, googleAdsId].filter(Boolean) as string[];\n const firstGoogleId = googleIds[0];\n\n return (\n <>\n {firstGoogleId && (\n <>\n <Script\n id=\"vt-gtag\"\n async\n src={`https://www.googletagmanager.com/gtag/js?id=${firstGoogleId}`}\n strategy=\"afterInteractive\"\n />\n <Script id=\"vt-gtag-init\" strategy=\"afterInteractive\">\n {`window.dataLayer = window.dataLayer || [];\nfunction gtag(){dataLayer.push(arguments);}\ngtag('js', new Date());\n${googleIds.map((id) => `gtag('config', '${id}');`).join(\"\\n\")}`}\n </Script>\n </>\n )}\n {metaPixelId && (\n <>\n <Script id=\"vt-meta-pixel\" strategy=\"afterInteractive\">\n {`!function(f,b,e,v,n,t,s)\n{if(f.fbq)return;n=f.fbq=function(){n.callMethod?\nn.callMethod.apply(n,arguments):n.queue.push(arguments)};\nif(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';\nn.queue=[];t=b.createElement(e);t.async=!0;\nt.src=v;s=b.getElementsByTagName(e)[0];\ns.parentNode.insertBefore(t,s)}(window, document,'script',\n'https://connect.facebook.net/en_US/fbevents.js');\nfbq('init', '${metaPixelId}');\nfbq('track', 'PageView');`}\n </Script>\n <noscript>\n <img\n height=\"1\"\n width=\"1\"\n style={{ display: \"none\" }}\n src={`https://www.facebook.com/tr?id=${metaPixelId}&ev=PageView&noscript=1`}\n alt=\"\"\n />\n </noscript>\n </>\n )}\n </>\n );\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/tags.tsx"],"names":["jsxs","Fragment","jsx","Script"],"mappings":";;;;;;;;;;AAyFA,IAAM,8BAAA,GAAiC,0BAAA;AAGvC,IAAM,2BAAA,GAA8B,yBAAA;AAGpC,IAAM,+BAAA,GAAkC,2BAAA;AAGxC,SAAS,GAAG,K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CAAA;AAAA,IAED,+BACCH,eAAA,CAAAC,mBAAA,EAAA,EACE,QAAA,EAAA;AAAA,sBAAAC,cAAA,CAACC,uBAAA,EAAA,EAAO,EAAA,EAAG,eAAA,EAAgB,QAAA,EAAS,kBAAA,EACjC,QAAA,EAAA,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,aAAA,EAQE,WAAW,CAAA;AAAA,yBAAA,CAAA,EAEhB,CAAA;AAAA,qCACC,UAAA,EAAA,EACC,QAAA,kBAAAD,cAAA;AAAA,QAAC,KAAA;AAAA,QAAA;AAAA,UACC,MAAA,EAAO,GAAA;AAAA,UACP,KAAA,EAAM,GAAA;AAAA,UACN,KAAA,EAAO,EAAE,OAAA,EAAS,MAAA,EAAO;AAAA,UACzB,GAAA,EAAK,kCAAkC,WAAW,CAAA,uBAAA,CAAA;AAAA,UAClD,GAAA,EAAI;AAAA;AAAA,OACN,EACF;AAAA,KAAA,EACF;AAAA,GAAA,EAEJ,CAAA;AAEJ","file":"tags.js","sourcesContent":["/**\n * CMS-driven third-party tracking-tag injection (server-side).\n *\n * Fetches tag IDs (GA4 / Google Ads / Meta Pixel) configured for this\n * project in vulcantech-cms and renders the corresponding third-party\n * <Script> loaders — giving consumer sites \"codeless\" tag setup with no\n * hand-rolled gtag/fbq wiring in their own layout.\n *\n * This module is a React Server Component — do NOT add \"use client\".\n *\n * Required env vars:\n * VULCANTECH_CMS_URL — CMS base URL (defaults to https://cms.vulcantech.io)\n * VULCANTECH_PROJECT_ID — project ID for this site\n * VULCANTECH_API_KEY — API key for this site (needs the analytics:read scope)\n *\n * Optional env fallbacks (used only when the CMS omits a field):\n * NEXT_PUBLIC_GA_ID → ga4Id\n * NEXT_PUBLIC_GOOGLE_ADS_ID → googleAdsId\n * NEXT_PUBLIC_META_PIXEL_ID → metaPixelId\n * NEXT_PUBLIC_FORM_CONVERSION_SEND_TO → formConversionSendTo\n * NEXT_PUBLIC_PHONE_CONVERSION_SEND_TO → phoneConversionSendTo\n * NEXT_PUBLIC_CALL_CONVERSION_SEND_TO → callConversionSendTo\n * NEXT_PUBLIC_CALL_CONVERSION_NUMBER → callConversionNumber\n * NEXT_PUBLIC_ENHANCED_CONVERSIONS=true → enhancedConversions\n *\n * All four of the last are CMS dashboard fields too (BL-1059). Note that\n * enhancedConversions is ON when either source says so — an env `true`\n * cannot be switched off from the CMS; unset the env var for that.\n */\n\nimport Script from \"next/script\";\n\n/**\n * Tracking tag IDs resolved for a project (CMS value wins, else env fallback).\n *\n * Public IDs only — the CMS strips its internal `enabled` and `updatedAt`\n * fields before returning the config to a consumer site.\n *\n * The documented formats are validated CMS-side when a staff user saves the\n * config in the dashboard. Values arriving from the NEXT_PUBLIC_* env\n * fallbacks are NOT validated by this package and are injected verbatim.\n */\nexport interface TrackingTags {\n /** GA4 measurement ID. CMS-validated against /^G-[A-Z0-9]{4,14}$/. */\n ga4Id?: string;\n /** Google Ads conversion ID. CMS-validated against /^AW-\\d{6,12}$/. */\n googleAdsId?: string;\n /** Meta (Facebook) Pixel ID — numeric string. CMS-validated against /^\\d{6,20}$/. */\n metaPixelId?: string;\n /**\n * Site-wide Google Ads `send_to` label fired when a `@vulcantech/forms`\n * form submits successfully, e.g. `\"AW-18321257894/AbC-D3fGhIjKlmNoP\"`.\n * CMS-validated against /^AW-\\d{6,12}\\/[A-Za-z0-9_-]{6,64}$/.\n *\n * Not a tag loader: {@link CMSTags} publishes it on\n * `window.__vtFormConversionSendTo`, where the forms package reads it. A\n * form's own `submitConfig.conversion.sendTo` overrides it.\n */\n formConversionSendTo?: string;\n /**\n * Google Ads `send_to` label fired on every `tel:` link tap. Published on\n * `window.__vtPhoneConversionSendTo`, where `trackPhoneClick` reads it.\n */\n phoneConversionSendTo?: string;\n /**\n * Google forwarding-number (\"website call conversion\") label, e.g.\n * `\"AW-123/AbC\"`. With {@link callConversionNumber} set, CMSTags configures\n * Google's number swap; render numbers through `PhoneLink` so the swapped\n * number survives React re-renders.\n */\n callConversionSendTo?: string;\n /**\n * The phone number exactly as the page displays it (e.g. `\"602.904.9109\"`).\n * Google only swaps a number that matches this string.\n */\n callConversionNumber?: string;\n /**\n * Opt into Google Ads enhanced conversions: `@vulcantech/forms` sends the\n * lead's email/phone (hashed by gtag) with the form conversion. The site's\n * privacy policy must disclose it.\n */\n enhancedConversions?: boolean;\n}\n\n/**\n * `window` key the site-wide form-conversion label is published on. Must stay\n * in sync with `FORM_CONVERSION_SEND_TO_GLOBAL` in `@vulcantech/forms` — the\n * two packages are independent, so this is a mirrored constant, not an import.\n */\nconst FORM_CONVERSION_SEND_TO_GLOBAL = \"__vtFormConversionSendTo\";\n\n/** Mirrors `ENHANCED_CONVERSIONS_GLOBAL` in `@vulcantech/forms`. */\nconst ENHANCED_CONVERSIONS_GLOBAL = \"__vtEnhancedConversions\";\n\n/** Read by `trackPhoneClick` in ./tracker. */\nconst PHONE_CONVERSION_SEND_TO_GLOBAL = \"__vtPhoneConversionSendTo\";\n\n/** Serialize a value into inline script source; `<` can never close the tag. */\nfunction js(value: unknown): string {\n return JSON.stringify(value).replace(/</g, \"\\\\u003c\");\n}\n\n/** Shape returned by GET {CMS_URL}/api/analytics/config. */\ninterface ConfigResponse {\n config: TrackingTags | null;\n}\n\n/**\n * fetch init with Next's ISR options. Passed as a typed variable (not an\n * object literal) so TS won't excess-property-check the `next` key — this\n * package doesn't load Next's global RequestInit augmentation. Mirrors the\n * collections/blog packages.\n */\ntype IsrFetchInit = RequestInit & {\n next?: { revalidate?: number; tags?: string[] };\n};\n\n/**\n * Fetch the tracking-tag config for this project from the CMS, merging in\n * env fallbacks per field (CMS value wins when present).\n *\n * Server-only: reads VULCANTECH_API_KEY, so never call it from client code.\n *\n * Never throws — tags must never break a page build. CMS errors (unreachable,\n * non-2xx, missing env, key lacking the `analytics:read` scope) are swallowed\n * and the env fallbacks apply instead. Returns `null` — NOT `{}` — when all\n * three tag IDs end up empty, otherwise a {@link TrackingTags} object.\n *\n * ⚠ Turning tracking tags OFF in the CMS does not necessarily disable them.\n * The CMS returns `config: null` for \"disabled\" and \"never configured\" alike,\n * and this function then fills every field from NEXT_PUBLIC_GA_ID /\n * NEXT_PUBLIC_GOOGLE_ADS_ID / NEXT_PUBLIC_META_PIXEL_ID. A site with those env\n * vars set keeps firing its tags after the CMS switch is off; disabling it\n * there requires unsetting the env vars and redeploying. Sites with no\n * NEXT_PUBLIC_* fallbacks honor the toggle as expected.\n *\n * The fetch is ISR-cached (`revalidate: 60`) and tagged\n * `tracking-tags:{projectId}` so the CMS can purge it on config change — so a\n * CMS value change reaches the site within ~60s with no redeploy.\n */\nexport async function fetchTrackingTags(): Promise<TrackingTags | null> {\n const CMS_URL = process.env.VULCANTECH_CMS_URL || \"https://cms.vulcantech.io\";\n const PROJECT_ID = process.env.VULCANTECH_PROJECT_ID;\n const API_KEY = process.env.VULCANTECH_API_KEY;\n\n let cms: TrackingTags | null = null;\n\n if (PROJECT_ID && API_KEY) {\n try {\n const params = new URLSearchParams({\n projectId: PROJECT_ID,\n apiKey: API_KEY,\n });\n const init: IsrFetchInit = {\n next: { revalidate: 60, tags: [`tracking-tags:${PROJECT_ID}`] },\n };\n const res = await fetch(`${CMS_URL}/api/analytics/config?${params}`, init);\n if (res.ok) {\n const json = (await res.json()) as ConfigResponse;\n cms = json.config ?? null;\n }\n } catch {\n // Silent fail — fall through to env fallbacks below.\n cms = null;\n }\n }\n\n // CMS value wins per field; fill any gap from public env vars.\n const merged: TrackingTags = {\n ga4Id: cms?.ga4Id || process.env.NEXT_PUBLIC_GA_ID || undefined,\n googleAdsId:\n cms?.googleAdsId || process.env.NEXT_PUBLIC_GOOGLE_ADS_ID || undefined,\n metaPixelId:\n cms?.metaPixelId || process.env.NEXT_PUBLIC_META_PIXEL_ID || undefined,\n formConversionSendTo:\n cms?.formConversionSendTo ||\n process.env.NEXT_PUBLIC_FORM_CONVERSION_SEND_TO ||\n undefined,\n phoneConversionSendTo:\n cms?.phoneConversionSendTo ||\n process.env.NEXT_PUBLIC_PHONE_CONVERSION_SEND_TO ||\n undefined,\n callConversionSendTo:\n cms?.callConversionSendTo ||\n process.env.NEXT_PUBLIC_CALL_CONVERSION_SEND_TO ||\n undefined,\n callConversionNumber:\n cms?.callConversionNumber ||\n process.env.NEXT_PUBLIC_CALL_CONVERSION_NUMBER ||\n undefined,\n enhancedConversions:\n cms?.enhancedConversions === true ||\n process.env.NEXT_PUBLIC_ENHANCED_CONVERSIONS === \"true\",\n };\n\n // A `send_to` label on its own is not enough to render anything — it needs\n // the Google tag that `googleAdsId`/`ga4Id` loads — so it does not count\n // towards \"something is configured\".\n if (!merged.ga4Id && !merged.googleAdsId && !merged.metaPixelId) {\n return null;\n }\n return merged;\n}\n\n/**\n * Drop-in server component that injects the project's tracking tags.\n *\n * Place once in your root layout's `<body>`:\n *\n * import { CMSTags } from \"@vulcantech/analytics/tags\";\n * // <body> ... <CMSTags /> ... </body>\n *\n * Async React Server Component — do NOT wrap it in a \"use client\" component.\n *\n * Renders, via next/script with `strategy=\"afterInteractive\"`:\n * - ONE shared gtag.js loader keyed to the FIRST present Google ID, plus an\n * inline init that gtag('config', …)s every present Google ID. Google Ads\n * rides the GA4 loader — there is no separate gtag/js?id=AW-… request.\n * The same inline script publishes `formConversionSendTo` (when set) on\n * `window.__vtFormConversionSendTo`, which is where `@vulcantech/forms`\n * looks for the Ads label to fire on a successful submission. Likewise\n * `phoneConversionSendTo` → `window.__vtPhoneConversionSendTo` and\n * `enhancedConversions` → `window.__vtEnhancedConversions`. With a\n * `callConversionSendTo` + `callConversionNumber`, it also configures\n * Google's forwarding-number swap; the callback stores the number on\n * `window.__vtPhone` and dispatches `vt-phone` for `PhoneLink`.\n * - The standard inline Meta Pixel bootstrap with fbq('track','PageView')\n * and a <noscript> tracking-pixel <img>.\n * - `null` when nothing is configured (see {@link fetchTrackingTags}).\n *\n * Because it uses next/script, mounting it in <body> is correct; it does not\n * need to be in <head>.\n *\n * ⚠ NO CONSENT GATING. Tags load as soon as the page hydrates. This component\n * provides no CMP/GDPR gate and must not be mounted unconditionally on a site\n * that requires consent before loading third-party trackers.\n */\nexport async function CMSTags() {\n const tags = await fetchTrackingTags();\n if (!tags) return null;\n\n const {\n ga4Id,\n googleAdsId,\n metaPixelId,\n formConversionSendTo,\n phoneConversionSendTo,\n callConversionSendTo,\n callConversionNumber,\n enhancedConversions,\n } = tags;\n const googleIds = [ga4Id, googleAdsId].filter(Boolean) as string[];\n const firstGoogleId = googleIds[0];\n // Published for @vulcantech/forms to read on submit success. Serialized\n // rather than interpolated raw because the NEXT_PUBLIC_* fallback is not\n // CMS-validated; `<` is escaped so a value can never close the <script>.\n const sendToLine = formConversionSendTo\n ? `window.${FORM_CONVERSION_SEND_TO_GLOBAL} = ${JSON.stringify(\n formConversionSendTo,\n ).replace(/</g, \"\\\\u003c\")};`\n : \"\";\n const extraLines = [\n phoneConversionSendTo\n ? `window.${PHONE_CONVERSION_SEND_TO_GLOBAL} = ${js(phoneConversionSendTo)};`\n : \"\",\n enhancedConversions ? `window.${ENHANCED_CONVERSIONS_GLOBAL} = true;` : \"\",\n // Google's forwarding-number swap. Runs once per page load, after the\n // plain configs — never re-run on route changes (each config call on a\n // GA4 id would send another page view).\n callConversionSendTo && callConversionNumber\n ? `gtag('config', ${js(callConversionSendTo)}, {\n phone_conversion_number: ${js(callConversionNumber)},\n phone_conversion_callback: function (formatted, mobile) {\n window.__vtPhone = { formatted: formatted, mobile: mobile };\n window.dispatchEvent(new Event('vt-phone'));\n }\n});`\n : \"\",\n ]\n .filter(Boolean)\n .join(\"\\n\");\n\n return (\n <>\n {firstGoogleId && (\n <>\n <Script\n id=\"vt-gtag\"\n async\n src={`https://www.googletagmanager.com/gtag/js?id=${firstGoogleId}`}\n strategy=\"afterInteractive\"\n />\n <Script id=\"vt-gtag-init\" strategy=\"afterInteractive\">\n {`window.dataLayer = window.dataLayer || [];\nfunction gtag(){dataLayer.push(arguments);}\ngtag('js', new Date());\n${googleIds.map((id) => `gtag('config', '${id}');`).join(\"\\n\")}\n${sendToLine}\n${extraLines}`}\n </Script>\n </>\n )}\n {metaPixelId && (\n <>\n <Script id=\"vt-meta-pixel\" strategy=\"afterInteractive\">\n {`!function(f,b,e,v,n,t,s)\n{if(f.fbq)return;n=f.fbq=function(){n.callMethod?\nn.callMethod.apply(n,arguments):n.queue.push(arguments)};\nif(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';\nn.queue=[];t=b.createElement(e);t.async=!0;\nt.src=v;s=b.getElementsByTagName(e)[0];\ns.parentNode.insertBefore(t,s)}(window, document,'script',\n'https://connect.facebook.net/en_US/fbevents.js');\nfbq('init', '${metaPixelId}');\nfbq('track', 'PageView');`}\n </Script>\n <noscript>\n <img\n height=\"1\"\n width=\"1\"\n style={{ display: \"none\" }}\n src={`https://www.facebook.com/tr?id=${metaPixelId}&ev=PageView&noscript=1`}\n alt=\"\"\n />\n </noscript>\n </>\n )}\n </>\n );\n}\n"]}
|