@getvitops/astro 8.2.0-alpha.0 → 8.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/CHANGELOG.md +485 -26
- package/dist/config-adapters-CbTywgEY.mjs +71 -0
- package/dist/config-adapters-CbTywgEY.mjs.map +1 -0
- package/dist/exports/tracking.d.mts +1 -1
- package/dist/exports/tracking.mjs +1 -1
- package/dist/index.d.mts +33 -43
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +90 -18
- package/dist/index.mjs.map +1 -1
- package/dist/middleware.d.mts +0 -2
- package/dist/middleware.d.mts.map +1 -1
- package/dist/middleware.mjs +1 -2
- package/dist/routes/conversion.d.mts +71 -15
- package/dist/routes/conversion.d.mts.map +1 -1
- package/dist/routes/conversion.mjs +79 -68
- package/dist/routes/conversion.mjs.map +1 -1
- package/dist/{tracking-M2PqlMpw.mjs → tracking-Cb3A0BrC.mjs} +2 -3
- package/dist/tracking-Cb3A0BrC.mjs.map +1 -0
- package/dist/{tracking-BNKKBqOe.d.mts → tracking-D2xOzjFD.d.mts} +5 -25
- package/dist/tracking-D2xOzjFD.d.mts.map +1 -0
- package/package.json +7 -6
- package/src/ads.ts +15 -22
- package/src/components/CookieConsent.astro +2 -1
- package/src/components/ReviewCardBody.astro +5 -2
- package/src/schemas/Article.astro +2 -1
- package/src/schemas/BookActions.astro +2 -1
- package/src/schemas/Breadcrumb.astro +2 -1
- package/src/schemas/Carousel.astro +2 -1
- package/src/schemas/CourseList.astro +2 -1
- package/src/schemas/Dataset.astro +2 -1
- package/src/schemas/DiscussionForum.astro +2 -1
- package/src/schemas/EducationQA.astro +2 -1
- package/src/schemas/EmployerAggregateRating.astro +2 -1
- package/src/schemas/Event.astro +2 -1
- package/src/schemas/FAQ.astro +2 -1
- package/src/schemas/FactCheck.astro +2 -1
- package/src/schemas/ImageMetadata.astro +2 -1
- package/src/schemas/JobPosting.astro +2 -1
- package/src/schemas/LocalBusiness.astro +2 -1
- package/src/schemas/MathSolver.astro +2 -1
- package/src/schemas/MovieCarousel.astro +2 -1
- package/src/schemas/Organization.astro +2 -1
- package/src/schemas/Product.astro +2 -1
- package/src/schemas/ProfilePage.astro +2 -1
- package/src/schemas/QAPage.astro +2 -1
- package/src/schemas/Recipe.astro +2 -1
- package/src/schemas/Review.astro +2 -1
- package/src/schemas/SoftwareApp.astro +2 -1
- package/src/seo.ts +6 -5
- package/src/tracking.ts +5 -9
- package/dist/tracking-BNKKBqOe.d.mts.map +0 -1
- package/dist/tracking-M2PqlMpw.mjs.map +0 -1
package/dist/middleware.d.mts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { MiddlewareHandler } from "astro";
|
|
2
|
-
//#region src/middleware.d.ts
|
|
3
2
|
export interface AbTestingExperiment {
|
|
4
3
|
/** The cookie this experiment is assigned/pinned through. */
|
|
5
4
|
cookieName: string;
|
|
@@ -21,5 +20,4 @@ export interface VitopsAbTestingOptions {
|
|
|
21
20
|
*/
|
|
22
21
|
export declare function assignVariant(experiment: Pick<AbTestingExperiment, 'splitRatio' | 'variants'>, random?: () => number): string;
|
|
23
22
|
export declare function vitopsAbTesting(opts: VitopsAbTestingOptions): MiddlewareHandler;
|
|
24
|
-
//#endregion
|
|
25
23
|
//# sourceMappingURL=middleware.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"middleware.d.mts","names":[],"sources":["../src/middleware.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"middleware.d.mts","names":[],"sources":["../src/middleware.ts"],"mappings":";iBAqCiB;;EAEf;;EAEA;;EAEA;;EAEA;;iBAGe;;EAEf,aAAa,eAAe;;;;;;;wBAQd,cACd,YAAY,KAAK,iDACjB;wBAOc,gBAAgB,MAAM,yBAAyB"}
|
package/dist/middleware.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/middleware.ts
|
|
2
2
|
/**
|
|
3
3
|
* Picks `variants[1]` with probability `splitRatio`, else `variants[0]`.
|
|
4
4
|
* Exported so the assignment policy itself — not just its wiring — is
|
|
@@ -30,6 +30,5 @@ function vitopsAbTesting(opts) {
|
|
|
30
30
|
return handler;
|
|
31
31
|
}
|
|
32
32
|
|
|
33
|
-
//#endregion
|
|
34
33
|
export { assignVariant, vitopsAbTesting };
|
|
35
34
|
//# sourceMappingURL=middleware.mjs.map
|
|
@@ -1,7 +1,24 @@
|
|
|
1
1
|
import { Config } from "@getvitops/generator";
|
|
2
|
+
import { AdPropertySetup } from "@getvitops/utils/ads";
|
|
3
|
+
import { Localizable } from "@getvitops/utils/content";
|
|
2
4
|
import { CrmConfig, CrmCredentials, CrmResult } from "@getvitops/utils/crm";
|
|
3
|
-
import { EmailBinding, NotifyContext, notify } from "@getvitops/utils/notify";
|
|
4
|
-
|
|
5
|
+
import { EmailBinding, GoogleAdsCredentials, GoogleAdsUploadResult, NotifyContext, notify } from "@getvitops/utils/notify";
|
|
6
|
+
/**
|
|
7
|
+
* The slice of a `Config` that `resolveOrganizationName` reads. Structural on
|
|
8
|
+
* purpose: `import config from './site.json'` types its literals widened
|
|
9
|
+
* (`colors.utilities` becomes `string[]`, not the schema's union), so it is not
|
|
10
|
+
* assignable to the full `Config`, and every scaffolded site calls this with
|
|
11
|
+
* exactly such an import. A resolved `Config` still satisfies it.
|
|
12
|
+
*/
|
|
13
|
+
interface OrganizationNameSource {
|
|
14
|
+
organization?: {
|
|
15
|
+
name?: Localizable | undefined;
|
|
16
|
+
legalName?: string | undefined;
|
|
17
|
+
} | undefined;
|
|
18
|
+
site: {
|
|
19
|
+
defaultLocale: string;
|
|
20
|
+
};
|
|
21
|
+
}
|
|
5
22
|
/**
|
|
6
23
|
* Resolves the one display name for a site's organization — `organization.name`
|
|
7
24
|
* (localizable; `locale` picks which one, defaulting to `site.defaultLocale`,
|
|
@@ -20,7 +37,7 @@ import { EmailBinding, NotifyContext, notify } from "@getvitops/utils/notify";
|
|
|
20
37
|
* needing a name in `astro.config.mjs` has one real source instead of a third
|
|
21
38
|
* hardcoded string.
|
|
22
39
|
*/
|
|
23
|
-
export declare function resolveOrganizationName(config:
|
|
40
|
+
export declare function resolveOrganizationName(config: OrganizationNameSource, locale?: string): string | undefined;
|
|
24
41
|
/**
|
|
25
42
|
* Builds the `context` option `createConversionRoute()` expects, straight from a
|
|
26
43
|
* resolved `Config` — instead of every consumer hand-writing a `NotifyContext`
|
|
@@ -32,14 +49,23 @@ export declare function resolveOrganizationName(config: Config, locale?: string)
|
|
|
32
49
|
*/
|
|
33
50
|
export declare function toNotifyContext(config: Config, locale?: string): NotifyContext;
|
|
34
51
|
/**
|
|
35
|
-
* `site.crm`
|
|
36
|
-
*
|
|
37
|
-
*
|
|
38
|
-
*
|
|
52
|
+
* `site.crm` IS `CrmConfig` — both are the schema's inferred type from `@getvitops/config` — so
|
|
53
|
+
* this returns its argument's field unchanged.
|
|
54
|
+
*
|
|
55
|
+
* @deprecated Pass `config.site.crm` directly. Kept so existing callers keep compiling; it
|
|
56
|
+
* stopped being an adapter when the type stopped being a copy.
|
|
39
57
|
*/
|
|
40
58
|
export declare function toCrmConfig(config: Config): CrmConfig | undefined;
|
|
41
|
-
|
|
42
|
-
|
|
59
|
+
/**
|
|
60
|
+
* `site.ads.google`'s three server-side-relevant fields, for
|
|
61
|
+
* `createConversionRoute`'s `googleAdsOffline.config`. Undefined when the site has no Google Ads
|
|
62
|
+
* property configured at all, which `createConversionRoute` reads the same way `crm` being
|
|
63
|
+
* omitted does: the upload never runs.
|
|
64
|
+
*
|
|
65
|
+
* @deprecated Pass `config.site.ads?.google` directly — it is already assignable. Kept so existing
|
|
66
|
+
* callers keep compiling.
|
|
67
|
+
*/
|
|
68
|
+
export declare function toGoogleAdsConfig(config: Config): Pick<AdPropertySetup, 'accountId' | 'conversionActionId' | 'reporting'> | undefined;
|
|
43
69
|
/** The subset of Astro's `APIContext` this needs — typed structurally so the
|
|
44
70
|
* factory does not pin an Astro version. */
|
|
45
71
|
export interface ConversionRequestContext {
|
|
@@ -83,6 +109,25 @@ export interface ConversionRouteOptions {
|
|
|
83
109
|
fetch?: typeof fetch;
|
|
84
110
|
timeoutMs?: number;
|
|
85
111
|
};
|
|
112
|
+
/**
|
|
113
|
+
* Upload the conversion to Google Ads server-side instead of relying on the
|
|
114
|
+
* visitor's browser to fire `gtag.js` — see `site.ads.google.reporting` and
|
|
115
|
+
* `conversionActionId`. Credentials arrive as a function of `locals`, same
|
|
116
|
+
* shape as `crm.credentials` and `binding` above.
|
|
117
|
+
*
|
|
118
|
+
* Only fires for an action whose `conversionActionId` is actually set (via
|
|
119
|
+
* `toGoogleAdsConfig(config)`, or hand-built the same shape) **and** whose
|
|
120
|
+
* event carries a Google click id (`gclid`/`gbraid`/`wbraid` on `_ac`) —
|
|
121
|
+
* an organic conversion has nothing for the Ads API to attribute, so it's
|
|
122
|
+
* silently skipped rather than reported as a failure. A failed upload never
|
|
123
|
+
* fails the request, matching `crm` above; the outcome folds into the same
|
|
124
|
+
* "Delivery" section via `describeGoogleAdsOfflineResult`.
|
|
125
|
+
*/
|
|
126
|
+
googleAdsOffline?: {
|
|
127
|
+
config: Pick<AdPropertySetup, 'accountId' | 'conversionActionId' | 'reporting'>;
|
|
128
|
+
credentials?: (locals: unknown) => GoogleAdsCredentials | undefined;
|
|
129
|
+
fetch?: typeof fetch;
|
|
130
|
+
};
|
|
86
131
|
/**
|
|
87
132
|
* Reject a submission before anything is sent. Return a message to refuse.
|
|
88
133
|
* This is where a consumer puts required-field checks.
|
|
@@ -119,10 +164,19 @@ export interface ConversionRouteOptions {
|
|
|
119
164
|
/**
|
|
120
165
|
* Reject a submission whose `Content-Length` exceeds this many bytes. Default
|
|
121
166
|
* 25_000 — generous for a contact form with no file upload, tiny for anything
|
|
122
|
-
* meant to relay large payloads.
|
|
123
|
-
*
|
|
167
|
+
* meant to relay large payloads. The header is only a fast path: a chunked
|
|
168
|
+
* request carries none, so the body is also read through a byte-capped
|
|
169
|
+
* reader and refused the moment it passes the cap.
|
|
124
170
|
*/
|
|
125
171
|
maxBodyBytes?: number;
|
|
172
|
+
/**
|
|
173
|
+
* Fall back to the first `X-Forwarded-For` hop as the client IP when
|
|
174
|
+
* `CF-Connecting-IP` is absent. Default `false`: off Cloudflare the header is
|
|
175
|
+
* whatever the client sent, so honouring it lets a script mint a fresh
|
|
176
|
+
* rate-limit bucket per request. Turn on only behind a proxy that overwrites
|
|
177
|
+
* it. With neither header trusted there is no IP, and rate limiting is skipped.
|
|
178
|
+
*/
|
|
179
|
+
trustForwardedFor?: boolean;
|
|
126
180
|
/**
|
|
127
181
|
* Reject a submission whose `Origin` header doesn't match this origin.
|
|
128
182
|
* Defaults to `context.canonical`'s origin. Pass `false` to disable.
|
|
@@ -166,11 +220,13 @@ export interface ConversionRouteOptions {
|
|
|
166
220
|
required?: boolean;
|
|
167
221
|
};
|
|
168
222
|
}
|
|
169
|
-
/** `notify()`'s own result, plus the CRM
|
|
170
|
-
*
|
|
171
|
-
* `
|
|
223
|
+
/** `notify()`'s own result, plus the CRM and Google Ads offline-upload
|
|
224
|
+
* outcomes when those are configured. Additive over
|
|
225
|
+
* `Awaited<ReturnType<typeof notify>>` — a consumer's existing `onResult`
|
|
226
|
+
* reading `.results`/`.delivered` keeps compiling unchanged. */
|
|
172
227
|
export interface ConversionResult extends Awaited<ReturnType<typeof notify>> {
|
|
173
228
|
crm?: CrmResult | undefined;
|
|
229
|
+
googleAds?: GoogleAdsUploadResult | undefined;
|
|
174
230
|
}
|
|
175
231
|
/**
|
|
176
232
|
* Build a POST handler for conversions.
|
|
@@ -186,5 +242,5 @@ export interface ConversionResult extends Awaited<ReturnType<typeof notify>> {
|
|
|
186
242
|
* notification into a lost conversion. Failures are reported through `onResult`.
|
|
187
243
|
*/
|
|
188
244
|
export declare function createConversionRoute(options: ConversionRouteOptions): ({ request, locals }: ConversionRequestContext) => Promise<Response>;
|
|
189
|
-
|
|
245
|
+
export {};
|
|
190
246
|
//# sourceMappingURL=conversion.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"conversion.d.mts","names":[],"sources":["../../src/routes/config-adapters.ts","../../src/routes/conversion.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"conversion.d.mts","names":[],"sources":["../../src/routes/config-adapters.ts","../../src/routes/conversion.ts"],"mappings":";;;;;;;;;;;;UA6BiB;EACf;IAAiB,OAAO;IAAyB;;EACjD;IAAQ;;;;;;;;;;;;;;;;;;;;;wBAqBM,wBACd,QAAQ,wBACR;;;;;;;;;;wBAoBc,gBAAgB,QAAQ,QAAQ,kBAAkB;;;;;;;;wBAuBlD,YAAY,QAAQ,SAAS;;;;;;;;;;wBAa7B,kBACd,QAAQ,SACP,KAAK;;;iBCVS;EACf,SAAS;EACT;;;;;;;iBAQe;EACf,IAAI,YAAY,aAAa;;iBAkBd;;EAEf,SAAS;;;;;;;;;EAST,WAAW,oBAAoB;;;;;;;;;;;;EAY/B;IACE,QAAQ;IACR,eAAe,oBAAoB;IACnC,eAAe;IACf;;;;;;;;;;;;;;;;EAgBF;IACE,QAAQ,KAAK;IACb,eAAe,oBAAoB;IACnC,eAAe;;;;;;EAMjB,YAAY,MAAM;;;EAGlB,YAAY,QAAQ;;EAEpB;;;;;;;EAOA;;;;;;EAMA;;;;;;;;;;EAUA;;;;;;;;EAQA;;;;;;;;EAQA;;;;;;;;;;;EAWA;;;;;;;EAOA;IAAc;IAAmB,QAAQ;;;;;;;;EAOzC;IACE;;;IAGA;;;;;;;;;IASA;;;;;;;iBAQa,yBAAyB,QAAQ,kBAAkB;EAClE,MAAM;EACN,YAAY;;;;;;;;;;;;;;;wBA2GE,sBAAsB,SAAS,4BAyB/B,SAAA,UAAqB,6BAA2B,QAAQ"}
|
|
@@ -1,65 +1,11 @@
|
|
|
1
|
-
import { t } from "
|
|
1
|
+
import { i as toNotifyContext, n as toCrmConfig, r as toGoogleAdsConfig, t as resolveOrganizationName } from "../config-adapters-CbTywgEY.mjs";
|
|
2
|
+
import { AD_PLATFORMS, normalizeConversionActionIds } from "@getvitops/utils/ads";
|
|
2
3
|
import { deliverToCrm, describeCrmResult } from "@getvitops/utils/crm";
|
|
3
|
-
import { notify } from "@getvitops/utils/notify";
|
|
4
|
+
import { describeGoogleAdsOfflineResult, notify, uploadClickConversion } from "@getvitops/utils/notify";
|
|
4
5
|
import { verifyTurnstileToken } from "@getvitops/utils/security";
|
|
5
6
|
import { parseTrackingCookie, readCookie } from "@getvitops/utils/tracking";
|
|
6
7
|
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
* Resolves the one display name for a site's organization — `organization.name`
|
|
10
|
-
* (localizable; `locale` picks which one, defaulting to `site.defaultLocale`,
|
|
11
|
-
* which is also the fallback if the pick has no entry), falling back to
|
|
12
|
-
* `legalName` when `name` isn't set at all, and to `undefined` (never `''`)
|
|
13
|
-
* when neither resolves to anything — `t()` returns `''` for a genuinely
|
|
14
|
-
* missing translation, and an empty name is worse than none.
|
|
15
|
-
*
|
|
16
|
-
* This is the one place that fallback chain is written. An EmDash site's own
|
|
17
|
-
* `getSiteSettings().title` is a separate, runtime-only fact (EmDash's
|
|
18
|
-
* settings aren't readable at Astro build/config time at all — see
|
|
19
|
-
* AGENTS.md's "EmDash plugin as the design-system editing surface") and stays
|
|
20
|
-
* authoritative for what it drives (the rendered page chrome); this helper is
|
|
21
|
-
* for the build-time-only consumers that can't reach EmDash at all — favicon
|
|
22
|
-
* generation, generated legal documents, notification emails — so a scaffold
|
|
23
|
-
* needing a name in `astro.config.mjs` has one real source instead of a third
|
|
24
|
-
* hardcoded string.
|
|
25
|
-
*/
|
|
26
|
-
function resolveOrganizationName(config, locale) {
|
|
27
|
-
const org = config.organization;
|
|
28
|
-
const resolvedLocale = locale ?? config.site.defaultLocale;
|
|
29
|
-
return (org?.name != null ? t(org.name, resolvedLocale, config.site.defaultLocale) || void 0 : void 0) ?? org?.legalName;
|
|
30
|
-
}
|
|
31
|
-
/**
|
|
32
|
-
* Builds the `context` option `createConversionRoute()` expects, straight from a
|
|
33
|
-
* resolved `Config` — instead of every consumer hand-writing a `NotifyContext`
|
|
34
|
-
* literal.
|
|
35
|
-
*
|
|
36
|
-
* `locationEmails` is primary-first, then every other location with an `email`,
|
|
37
|
-
* in `organization.locations`' own key order — `planNotifications` picks the
|
|
38
|
-
* first that's set, so order here is the whole precedence.
|
|
39
|
-
*/
|
|
40
|
-
function toNotifyContext(config, locale) {
|
|
41
|
-
const org = config.organization;
|
|
42
|
-
const primaryKey = org?.primaryLocation;
|
|
43
|
-
const locationEmails = Object.entries(org?.locations ?? {}).sort(([a], [b]) => a === primaryKey ? -1 : b === primaryKey ? 1 : 0).map(([, loc]) => loc.email).filter((email) => !!email);
|
|
44
|
-
return {
|
|
45
|
-
notifications: config.site.notifications,
|
|
46
|
-
canonical: config.site.domains?.canonical,
|
|
47
|
-
organizationName: resolveOrganizationName(config, locale),
|
|
48
|
-
locationEmails
|
|
49
|
-
};
|
|
50
|
-
}
|
|
51
|
-
/**
|
|
52
|
-
* `site.crm` is already field-for-field identical to `CrmConfig` (see that
|
|
53
|
-
* interface's own docblock — it's deliberately kept in lockstep) — this is a
|
|
54
|
-
* type-narrowing pass-through, not a remap. Named rather than inlined at each
|
|
55
|
-
* call site so a future divergence between the two shapes has one place to fix.
|
|
56
|
-
*/
|
|
57
|
-
function toCrmConfig(config) {
|
|
58
|
-
return config.site.crm;
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
//#endregion
|
|
62
|
-
//#region src/routes/conversion.ts
|
|
8
|
+
// src/routes/conversion.ts
|
|
63
9
|
/**
|
|
64
10
|
* The conversion endpoint, as a factory.
|
|
65
11
|
*
|
|
@@ -151,6 +97,22 @@ var MemoryRateLimitStore = class {
|
|
|
151
97
|
return prev === void 0 ? null : at - prev;
|
|
152
98
|
}
|
|
153
99
|
};
|
|
100
|
+
/** The click id to report to Google Ads, checked in the same order as
|
|
101
|
+
* `AD_PLATFORMS.google.clickIdParams` rather than `getPrimaryClickId()` —
|
|
102
|
+
* that helper returns whichever platform's click id happens to appear first
|
|
103
|
+
* in the *cross-platform* precedence table, which may not be Google's even
|
|
104
|
+
* when a `gclid` is present. */
|
|
105
|
+
function googleClickId(tracking) {
|
|
106
|
+
if (!tracking) return null;
|
|
107
|
+
for (const param of AD_PLATFORMS.google.clickIdParams) {
|
|
108
|
+
const value = tracking[param];
|
|
109
|
+
if (value) return {
|
|
110
|
+
param,
|
|
111
|
+
value: String(value)
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
return null;
|
|
115
|
+
}
|
|
154
116
|
/** Fields that are never part of a submission's meaning. `cf-turnstile-response`
|
|
155
117
|
* is excluded unconditionally, matching `render.ts`'s `OMIT_FIELDS` — the field
|
|
156
118
|
* carries a verification token, not something the visitor wrote. */
|
|
@@ -159,12 +121,44 @@ const CONTROL_FIELDS = /* @__PURE__ */ new Set([
|
|
|
159
121
|
"phone",
|
|
160
122
|
"cf-turnstile-response"
|
|
161
123
|
]);
|
|
124
|
+
/** The capture script sends `link.href` as-is: `tel:` + digits and the punctuation people type
|
|
125
|
+
* (a space arrives as `%20`). Not free text. */
|
|
126
|
+
const PHONE_RE = /^(?:tel:)?\+?[\d\s().%-]{3,40}$/i;
|
|
127
|
+
/** `mailto:` + an address, with an optional `?subject=…` query. A shape check, not deliverability. */
|
|
128
|
+
const EMAIL_RE = /^(?:mailto:)?[^\s@<>"?]{1,64}@[^\s@<>"?]{1,255}(?:\?[^\s<>"]{0,256})?$/i;
|
|
162
129
|
const DEFAULT_HONEYPOT_FIELDS = [
|
|
163
130
|
"website",
|
|
164
131
|
"_honeypot",
|
|
165
132
|
"honeypot"
|
|
166
133
|
];
|
|
167
134
|
const DEFAULT_MAX_BODY_BYTES = 25e3;
|
|
135
|
+
/**
|
|
136
|
+
* Read a request body, giving up as soon as it exceeds `max` bytes. Returns `null` when over
|
|
137
|
+
* the cap. `Content-Length` is optional on chunked requests, so it cannot be the only guard.
|
|
138
|
+
*/
|
|
139
|
+
async function readCapped(request, max) {
|
|
140
|
+
if (!request.body) return /* @__PURE__ */ new Uint8Array();
|
|
141
|
+
const reader = request.body.getReader();
|
|
142
|
+
const chunks = [];
|
|
143
|
+
let total = 0;
|
|
144
|
+
for (;;) {
|
|
145
|
+
const { done, value } = await reader.read();
|
|
146
|
+
if (done) break;
|
|
147
|
+
total += value.byteLength;
|
|
148
|
+
if (total > max) {
|
|
149
|
+
await reader.cancel();
|
|
150
|
+
return null;
|
|
151
|
+
}
|
|
152
|
+
chunks.push(value);
|
|
153
|
+
}
|
|
154
|
+
const bytes = new Uint8Array(total);
|
|
155
|
+
let offset = 0;
|
|
156
|
+
for (const chunk of chunks) {
|
|
157
|
+
bytes.set(chunk, offset);
|
|
158
|
+
offset += chunk.byteLength;
|
|
159
|
+
}
|
|
160
|
+
return bytes;
|
|
161
|
+
}
|
|
168
162
|
const DEFAULT_RATE_LIMIT_WINDOW_MS = 1e4;
|
|
169
163
|
function toFormData(body, honeypotFields) {
|
|
170
164
|
const out = {};
|
|
@@ -211,7 +205,7 @@ function redirectTo(location, status = 303) {
|
|
|
211
205
|
* notification into a lost conversion. Failures are reported through `onResult`.
|
|
212
206
|
*/
|
|
213
207
|
function createConversionRoute(options) {
|
|
214
|
-
const { context, binding, validate, onResult, now = Date.now, redirectTo: successRedirect, errorRedirectTo = successRedirect, honeypotFields = DEFAULT_HONEYPOT_FIELDS, maxBodyBytes = DEFAULT_MAX_BODY_BYTES } = options;
|
|
208
|
+
const { context, binding, validate, onResult, now = Date.now, redirectTo: successRedirect, errorRedirectTo = successRedirect, honeypotFields = DEFAULT_HONEYPOT_FIELDS, maxBodyBytes = DEFAULT_MAX_BODY_BYTES, trustForwardedFor = false } = options;
|
|
215
209
|
const allowedOrigin = options.allowedOrigin === false ? null : options.allowedOrigin ?? originOf(context.canonical);
|
|
216
210
|
const rateLimit = options.rateLimit === false ? null : {
|
|
217
211
|
windowMs: options.rateLimit?.windowMs ?? DEFAULT_RATE_LIMIT_WINDOW_MS,
|
|
@@ -229,21 +223,23 @@ function createConversionRoute(options) {
|
|
|
229
223
|
const requestOrigin = request.headers.get("origin");
|
|
230
224
|
if (requestOrigin && requestOrigin !== allowedOrigin) return respondError("Origin not allowed.", 403);
|
|
231
225
|
}
|
|
226
|
+
const bytes = await readCapped(request, maxBodyBytes);
|
|
227
|
+
if (!bytes) return respondError("Request too large.", 413);
|
|
232
228
|
let body;
|
|
233
229
|
try {
|
|
234
230
|
if (isFormPost) {
|
|
235
|
-
const formData = await
|
|
231
|
+
const formData = await new Response(bytes, { headers: { "content-type": contentType } }).formData();
|
|
236
232
|
body = {};
|
|
237
233
|
for (const [key, value] of formData.entries()) if (typeof value === "string") body[key] = value;
|
|
238
234
|
} else {
|
|
239
|
-
const parsed =
|
|
235
|
+
const parsed = JSON.parse(new TextDecoder().decode(bytes));
|
|
240
236
|
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return respondError("Malformed request.", 400);
|
|
241
237
|
body = parsed;
|
|
242
238
|
}
|
|
243
239
|
} catch {
|
|
244
240
|
return respondError("Malformed request.", 400);
|
|
245
241
|
}
|
|
246
|
-
const ip = request.headers.get("cf-connecting-ip") ?? request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? void 0;
|
|
242
|
+
const ip = request.headers.get("cf-connecting-ip") ?? (trustForwardedFor ? request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() : null) ?? void 0;
|
|
247
243
|
const isCall = body["event"] === "call";
|
|
248
244
|
const isEmailClick = body["event"] === "email";
|
|
249
245
|
if (rateLimit && ip) {
|
|
@@ -251,8 +247,8 @@ function createConversionRoute(options) {
|
|
|
251
247
|
const sinceLastHit = await rateLimit.store.hit(rlKey, now());
|
|
252
248
|
if (sinceLastHit !== null && sinceLastHit < rateLimit.windowMs) return respondError("Too many requests.", 429);
|
|
253
249
|
}
|
|
254
|
-
if (isCall && typeof body["phone"]
|
|
255
|
-
if (isEmailClick && typeof body["email"]
|
|
250
|
+
if (isCall && !(typeof body["phone"] === "string" && PHONE_RE.test(body["phone"]))) return respondError("Missing phone.", 400);
|
|
251
|
+
if (isEmailClick && !(typeof body["email"] === "string" && EMAIL_RE.test(body["email"]))) return respondError("Missing email.", 400);
|
|
256
252
|
const isBeacon = isCall || isEmailClick;
|
|
257
253
|
const spam = !isBeacon && hasHoneypot(body, honeypotFields);
|
|
258
254
|
if (!isBeacon && !spam && options.turnstile) {
|
|
@@ -297,19 +293,34 @@ function createConversionRoute(options) {
|
|
|
297
293
|
}
|
|
298
294
|
});
|
|
299
295
|
const crmNote = describeCrmResult(crmResult);
|
|
296
|
+
let googleAdsResult = null;
|
|
297
|
+
const adsCfg = options.googleAdsOffline?.config;
|
|
298
|
+
if (adsCfg?.reporting === "server" && adsCfg.accountId) {
|
|
299
|
+
const actionId = normalizeConversionActionIds(adsCfg.conversionActionId)[event.type];
|
|
300
|
+
const clickId = googleClickId(event.tracking);
|
|
301
|
+
const credentials = options.googleAdsOffline?.credentials?.(locals);
|
|
302
|
+
if (actionId && clickId && credentials) googleAdsResult = await uploadClickConversion({
|
|
303
|
+
customerId: adsCfg.accountId,
|
|
304
|
+
conversionActionId: actionId,
|
|
305
|
+
clickId,
|
|
306
|
+
at: event.at
|
|
307
|
+
}, credentials, options.googleAdsOffline?.fetch);
|
|
308
|
+
}
|
|
309
|
+
const googleAdsNote = describeGoogleAdsOfflineResult(googleAdsResult);
|
|
300
310
|
const result = {
|
|
301
|
-
...await notify(event, context, { email: binding?.(locals) },
|
|
302
|
-
...crmResult ? { crm: crmResult } : {}
|
|
311
|
+
...await notify(event, context, { email: binding?.(locals) }, { notes: [crmNote, googleAdsNote].filter((n) => n != null) }),
|
|
312
|
+
...crmResult ? { crm: crmResult } : {},
|
|
313
|
+
...googleAdsResult ? { googleAds: googleAdsResult } : {}
|
|
303
314
|
};
|
|
304
315
|
if (onResult) onResult(result);
|
|
305
316
|
else {
|
|
306
317
|
for (const r of result.results) if (!r.sent) console.warn(`[vitops] notification not sent (${r.channel}): ${r.reason}`);
|
|
307
318
|
if (crmResult && !crmResult.ok) console.warn(`[vitops] CRM write not delivered (${crmResult.provider}): ${crmResult.reason}`);
|
|
319
|
+
if (googleAdsResult && !googleAdsResult.ok) console.warn(`[vitops] Google Ads offline upload not delivered: ${googleAdsResult.reason}`);
|
|
308
320
|
}
|
|
309
321
|
return respondSuccess();
|
|
310
322
|
};
|
|
311
323
|
}
|
|
312
324
|
|
|
313
|
-
|
|
314
|
-
export { createConversionRoute, resolveOrganizationName, toCrmConfig, toNotifyContext };
|
|
325
|
+
export { createConversionRoute, resolveOrganizationName, toCrmConfig, toGoogleAdsConfig, toNotifyContext };
|
|
315
326
|
//# sourceMappingURL=conversion.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"conversion.mjs","names":[],"sources":["../../src/routes/config-adapters.ts","../../src/routes/conversion.ts"],"sourcesContent":["/**\n * Adapts a resolved `Config` (`@getvitops/generator`) into the structural shapes\n * `createConversionRoute()` expects — `context: NotifyContext` and `crm.config:\n * CrmConfig`. Neither of those types can import `Config` themselves (they live in\n * `@getvitops/utils`, which the generator already depends on — importing back\n * would be a cycle), which is why `conversion.ts`'s own docblock used to describe\n * `toNotifyContext(config)` as a helper that \"does not exist.\" This package\n * already depends on both the generator and utils, so it's the one place the\n * adapter can live.\n *\n * `import type` only — erased at build, so pulling in `Config`'s type costs\n * nothing at runtime and doesn't drag the generator's `node:fs`/lightningcss\n * entry point into a Worker bundle.\n */\nimport type { Config } from '@getvitops/generator';\nimport { t } from '@getvitops/utils';\nimport type { CrmConfig } from '@getvitops/utils/crm';\nimport type { NotifyContext } from '@getvitops/utils/notify';\n\n/**\n * Resolves the one display name for a site's organization — `organization.name`\n * (localizable; `locale` picks which one, defaulting to `site.defaultLocale`,\n * which is also the fallback if the pick has no entry), falling back to\n * `legalName` when `name` isn't set at all, and to `undefined` (never `''`)\n * when neither resolves to anything — `t()` returns `''` for a genuinely\n * missing translation, and an empty name is worse than none.\n *\n * This is the one place that fallback chain is written. An EmDash site's own\n * `getSiteSettings().title` is a separate, runtime-only fact (EmDash's\n * settings aren't readable at Astro build/config time at all — see\n * AGENTS.md's \"EmDash plugin as the design-system editing surface\") and stays\n * authoritative for what it drives (the rendered page chrome); this helper is\n * for the build-time-only consumers that can't reach EmDash at all — favicon\n * generation, generated legal documents, notification emails — so a scaffold\n * needing a name in `astro.config.mjs` has one real source instead of a third\n * hardcoded string.\n */\nexport function resolveOrganizationName(config: Config, locale?: string): string | undefined {\n const org = config.organization;\n const resolvedLocale = locale ?? config.site.defaultLocale;\n const name =\n org?.name != null\n ? t(org.name, resolvedLocale, config.site.defaultLocale) || undefined\n : undefined;\n return name ?? org?.legalName;\n}\n\n/**\n * Builds the `context` option `createConversionRoute()` expects, straight from a\n * resolved `Config` — instead of every consumer hand-writing a `NotifyContext`\n * literal.\n *\n * `locationEmails` is primary-first, then every other location with an `email`,\n * in `organization.locations`' own key order — `planNotifications` picks the\n * first that's set, so order here is the whole precedence.\n */\nexport function toNotifyContext(config: Config, locale?: string): NotifyContext {\n const org = config.organization;\n const primaryKey = org?.primaryLocation;\n const locationEmails = Object.entries(org?.locations ?? {})\n .sort(([a], [b]) => (a === primaryKey ? -1 : b === primaryKey ? 1 : 0))\n .map(([, loc]) => loc.email)\n .filter((email): email is string => !!email);\n\n return {\n notifications: config.site.notifications,\n canonical: config.site.domains?.canonical,\n organizationName: resolveOrganizationName(config, locale),\n locationEmails,\n };\n}\n\n/**\n * `site.crm` is already field-for-field identical to `CrmConfig` (see that\n * interface's own docblock — it's deliberately kept in lockstep) — this is a\n * type-narrowing pass-through, not a remap. Named rather than inlined at each\n * call site so a future divergence between the two shapes has one place to fix.\n */\nexport function toCrmConfig(config: Config): CrmConfig | undefined {\n return config.site.crm;\n}\n","/**\n * The conversion endpoint, as a factory.\n *\n * A site's contact form and its `tel:`/`mailto:` beacons all mean the same\n * thing — someone got in touch — and all want the same treatment: read the\n * attribution cookie off the request, build the event, notify whoever the\n * config says. That is the same three lines in every project, so it ships\n * here.\n *\n * What deliberately does **not** ship here is field-level validation and business\n * rules — a consumer's form has its own required fields and its own response\n * shape, and baking a guess at those in would make the factory something to\n * fight rather than mount. The handler takes the parsed body and an optional\n * `validate`; that part is the caller's. What **does** ship here is generic abuse\n * resistance (honeypot, origin, rate limit, body size): this is a public,\n * unauthenticated endpoint that sends email, so leaving it wide open makes it a\n * relay and a cost amplifier regardless of whose form is behind it.\n *\n * The path matters: the capture script beacons `tel:`/`mailto:` conversions at\n * `TRACKING_ENDPOINT` (`/api/track`, exported from `@getvitops/astro/tracking`),\n * and the integration warns at build if no route answers it.\n *\n * ```ts\n * // src/pages/api/track.ts\n * export const prerender = false;\n * import { env } from 'cloudflare:workers';\n * import { createConversionRoute } from '@getvitops/astro/routes';\n *\n * export const POST = createConversionRoute({\n * context: {\n * // A bare address is shorthand for `{ provider: 'cloudflare', to }`.\n * notifications: { email: 'sales@acme.ca' },\n * canonical: 'https://acme.ca',\n * organizationName: 'Acme',\n * },\n * binding: () => env.EMAIL,\n * // A no-JS <form method=\"post\"> submission never sees a JSON response body —\n * // it's a full navigation, so send it somewhere real.\n * redirectTo: '/thanks',\n * });\n * ```\n *\n * Cloudflare Turnstile is a separate, opt-in layer on top of the checks above —\n * pass `turnstile: { secretKey }` and a submission carrying a\n * `cf-turnstile-response` token gets it verified server-side via\n * `verifyTurnstileToken` (`@getvitops/utils/security`). The widget itself is the\n * consumer's own markup (`<script src=\"https://challenges.cloudflare.com/\n * turnstile/v0/api.js\" async defer></script>` + `<div class=\"cf-turnstile\"\n * data-sitekey=\"…\">` on their form) — there is no `FormRenderer` for this to hook\n * into generically, matching how the rest of the form is already hand-written.\n * `site.security.turnstile.siteKey` is what the generated privacy policy reads to\n * name Turnstile as a processor; wiring this option up is what makes that true\n * rather than an assertion nothing checks.\n *\n * Two things this example used to get wrong, both of which cost a consumer real\n * time. It read the binding off `locals.runtime.env`, which Astro removed in v6\n * — and because the resulting throw precedes the response, Astro re-reads the\n * request and reports a misleading \"Body has already been used\" instead of the\n * actual error. This package peers on `astro >= 7`, so that form could not work\n * for any supported consumer; `import { env } from 'cloudflare:workers'` is the\n * current one. It also called a `toNotifyContext(config)` helper that used to\n * not exist — `context` can now be built with `toNotifyContext(config)` (also\n * exported from this module), rather than every consumer hand-writing a\n * `NotifyContext` literal:\n *\n * ```ts\n * import config from '../../site.json' with { type: 'json' };\n * import { createConversionRoute, toNotifyContext, toCrmConfig } from '@getvitops/astro/routes';\n *\n * export const POST = createConversionRoute({\n * context: toNotifyContext(config),\n * crm: toCrmConfig(config) && { config: toCrmConfig(config)!, credentials: () => ({ ... }) },\n * binding: () => env.EMAIL,\n * redirectTo: '/thanks',\n * });\n * ```\n */\nimport { deliverToCrm, describeCrmResult } from '@getvitops/utils/crm';\nimport type { CrmConfig, CrmCredentials, CrmResult } from '@getvitops/utils/crm';\nimport { type EmailBinding, notify, type NotifyContext } from '@getvitops/utils/notify';\nimport { verifyTurnstileToken } from '@getvitops/utils/security';\nimport { parseTrackingCookie, readCookie } from '@getvitops/utils/tracking';\nimport type { ConversionEvent } from '@getvitops/utils/tracking';\nexport { resolveOrganizationName, toCrmConfig, toNotifyContext } from './config-adapters.ts';\n\n/** The subset of Astro's `APIContext` this needs — typed structurally so the\n * factory does not pin an Astro version. */\nexport interface ConversionRequestContext {\n request: Request;\n locals?: unknown;\n}\n\n/**\n * Records a hit for `id` at time `at` (ms) and returns the ms since the previous\n * hit for that `id`, or `null` if this is the first. Pure interface — a store\n * decides nothing, it only remembers.\n */\nexport interface RateLimitStore {\n hit(id: string, at: number): Promise<number | null> | number | null;\n}\n\n/**\n * Per-isolate, in-memory default. Good enough for a single Worker instance\n * fielding occasional contact-form spam; not durable across a fleet, and not\n * shared with other routes. Inject a KV- or Durable-Object-backed `store` for\n * real cross-instance limiting — the interface is one method wide on purpose.\n */\nclass MemoryRateLimitStore implements RateLimitStore {\n private lastHit = new Map<string, number>();\n hit(id: string, at: number): number | null {\n const prev = this.lastHit.get(id);\n this.lastHit.set(id, at);\n return prev === undefined ? null : at - prev;\n }\n}\n\nexport interface ConversionRouteOptions {\n /** Where notifications go. Build it from your site config. */\n context: NotifyContext;\n /**\n * The Workers `send_email` binding for this request, e.g. `() => env.EMAIL`\n * with `env` imported from `cloudflare:workers`. Omit it in dev and the\n * notification is printed instead of sent.\n *\n * Not `(locals) => locals.runtime.env.EMAIL` — Astro removed `locals.runtime`\n * in v6, and this package peers on `>= 7`.\n */\n binding?: (locals: unknown) => EmailBinding | undefined;\n /**\n * Push the submission into a CRM (HubSpot, Zoho Bigin or Jobber) before notifying.\n * Credentials arrive as a function of `locals`, exactly like `binding` above\n * — the consumer reads them from `import { env } from 'cloudflare:workers'`.\n * Credentials are never config; that rule is absolute in this toolchain.\n *\n * A failed CRM write never fails the request and never blocks the honeypot/\n * Turnstile gates above it — those run first, so a bot never reaches the\n * CRM. The outcome is folded into the notification email's \"Delivery\"\n * section (via `describeCrmResult`) so a failed write is never silent.\n */\n crm?: {\n config: CrmConfig;\n credentials?: (locals: unknown) => CrmCredentials | undefined;\n fetch?: typeof fetch;\n timeoutMs?: number;\n };\n /**\n * Reject a submission before anything is sent. Return a message to refuse.\n * This is where a consumer puts required-field checks.\n */\n validate?: (body: Record<string, unknown>) => string | null;\n /** Called with every channel outcome, delivered or not, plus the CRM\n * outcome when `crm` is configured. Defaults to console. */\n onResult?: (result: ConversionResult) => void;\n /** Injected in tests. */\n now?: () => number;\n /**\n * Where to send a no-JS `<form method=\"post\">` submission on success. Without\n * this, that visitor's browser navigates to the raw `{\"success\":true}` JSON\n * body as its next page — functional, but not a page anyone should see. Has\n * no effect on the beacon/fetch (JSON) path, which always gets a JSON response.\n */\n redirectTo?: string;\n /**\n * Where to send a refused no-JS submission (validation, spam checks, malformed\n * body). Falls back to `redirectTo` if omitted, and to the JSON error response\n * if neither is set.\n */\n errorRedirectTo?: string;\n /**\n * Field names treated as honeypots: a bot fills every input it finds, a person\n * never sees these (hidden by CSS in the form markup). A non-empty value is\n * silently treated as spam — the response looks identical to a real success,\n * denying the bot the signal it needs to know the trick worked, but nothing is\n * notified and the field never reaches `notify()`. Defaults to the same names\n * `render.ts`'s `OMIT_FIELDS` already knows about (`website`, `_honeypot`,\n * `honeypot`), so the two lists don't need to be kept in sync by hand.\n */\n honeypotFields?: string[];\n /**\n * Reject a submission whose `Content-Length` exceeds this many bytes. Default\n * 25_000 — generous for a contact form with no file upload, tiny for anything\n * meant to relay large payloads. Best-effort: `Content-Length` can be absent\n * or spoofed, same caveat as the origin check below.\n */\n maxBodyBytes?: number;\n /**\n * Reject a submission whose `Origin` header doesn't match this origin.\n * Defaults to `context.canonical`'s origin. Pass `false` to disable.\n *\n * Best-effort, not a CSRF guard: browsers omit `Origin` on plenty of\n * legitimate same-origin requests, so its *absence* is never treated as a\n * mismatch — only a present-and-different value is rejected. That still stops\n * the common case (a script hitting the endpoint directly from elsewhere)\n * without breaking real submissions from older or privacy-hardened browsers.\n */\n allowedOrigin?: string | false;\n /**\n * Minimum interval between accepted submissions from the same IP. Pass\n * `false` to disable. `windowMs` defaults to 10 seconds — enough to blunt a\n * script firing in a loop without troubling someone who fat-fingers a form\n * and resubmits.\n */\n rateLimit?: { windowMs?: number; store?: RateLimitStore } | false;\n /**\n * Verify a Cloudflare Turnstile token server-side. The **secret** key —\n * unlike `site.security.turnstile.siteKey`, which is public config — must come\n * from an env var, never a config file (the same rule as every other\n * credential in this toolchain).\n */\n turnstile?: {\n secretKey: string;\n /** The submitted field carrying the token. Default `cf-turnstile-response`\n * — the name Cloudflare's widget submits under. */\n fieldName?: string;\n /**\n * Reject a submission with no token at all, rather than only a present-and-\n * invalid one. Default `false`: an absent token is the ordinary shape of a\n * visitor with JS disabled, and this factory is built around that path\n * staying usable. Set `true` only for a form where verified-human matters\n * enough to accept that trade-off — doing so means that form no longer\n * works without JS, on purpose.\n */\n required?: boolean;\n };\n}\n\n/** `notify()`'s own result, plus the CRM outcome when `crm` is configured.\n * Additive over `Awaited<ReturnType<typeof notify>>` — a consumer's existing\n * `onResult` reading `.results`/`.delivered` keeps compiling unchanged. */\nexport interface ConversionResult extends Awaited<ReturnType<typeof notify>> {\n crm?: CrmResult | undefined;\n}\n\n/** Fields that are never part of a submission's meaning. `cf-turnstile-response`\n * is excluded unconditionally, matching `render.ts`'s `OMIT_FIELDS` — the field\n * carries a verification token, not something the visitor wrote. */\nconst CONTROL_FIELDS = new Set(['event', 'phone', 'cf-turnstile-response']);\nconst DEFAULT_HONEYPOT_FIELDS = ['website', '_honeypot', 'honeypot'];\nconst DEFAULT_MAX_BODY_BYTES = 25_000;\nconst DEFAULT_RATE_LIMIT_WINDOW_MS = 10_000;\n\nfunction toFormData(\n body: Record<string, unknown>,\n honeypotFields: string[],\n): Record<string, string> {\n const out: Record<string, string> = {};\n for (const [key, value] of Object.entries(body)) {\n if (CONTROL_FIELDS.has(key) || honeypotFields.includes(key)) continue;\n if (value === undefined || value === null) continue;\n out[key] = String(value);\n }\n return out;\n}\n\nfunction hasHoneypot(body: Record<string, unknown>, honeypotFields: string[]): boolean {\n return honeypotFields.some((field) => {\n const value = body[field];\n return typeof value === 'string' && value.trim() !== '';\n });\n}\n\nfunction originOf(url: string | undefined): string | null {\n if (!url) return null;\n try {\n return new URL(url).origin;\n } catch {\n return null;\n }\n}\n\n/** A `Location` header response — used for the no-JS form path instead of\n * `Response.redirect()`, which requires a base URL this factory doesn't have. */\nfunction redirectTo(location: string, status = 303): Response {\n return new Response(null, { status, headers: { Location: location } });\n}\n\n/**\n * Build a POST handler for conversions.\n *\n * Returns 204 for a beacon and 200 with `{ success }` for a JSON (fetch-based)\n * form submission, matching what `navigator.sendBeacon` and a fetch-submitting\n * form each expect. A no-JS `<form method=\"post\">` — `application/\n * x-www-form-urlencoded` or `multipart/form-data` — is parsed the same way and,\n * on success, redirected to `redirectTo` if one is configured.\n *\n * **A failed notification does not fail the request.** The visitor has already\n * submitted; refusing them because our mail did not go out turns a lost\n * notification into a lost conversion. Failures are reported through `onResult`.\n */\nexport function createConversionRoute(options: ConversionRouteOptions) {\n const {\n context,\n binding,\n validate,\n onResult,\n now = Date.now,\n redirectTo: successRedirect,\n errorRedirectTo = successRedirect,\n honeypotFields = DEFAULT_HONEYPOT_FIELDS,\n maxBodyBytes = DEFAULT_MAX_BODY_BYTES,\n } = options;\n\n const allowedOrigin =\n options.allowedOrigin === false ? null : (options.allowedOrigin ?? originOf(context.canonical));\n\n const rateLimit =\n options.rateLimit === false\n ? null\n : {\n windowMs: options.rateLimit?.windowMs ?? DEFAULT_RATE_LIMIT_WINDOW_MS,\n store: options.rateLimit?.store ?? new MemoryRateLimitStore(),\n };\n\n return async ({ request, locals }: ConversionRequestContext): Promise<Response> => {\n const contentType = request.headers.get('content-type') ?? '';\n const isFormPost =\n contentType.includes('multipart/form-data') ||\n contentType.includes('application/x-www-form-urlencoded');\n\n const respondError = (error: string, status: number): Response =>\n isFormPost && errorRedirectTo\n ? redirectTo(errorRedirectTo)\n : Response.json({ success: false, error }, { status });\n\n const contentLength = Number(request.headers.get('content-length') ?? 0);\n if (contentLength > maxBodyBytes) {\n return respondError('Request too large.', 413);\n }\n\n if (allowedOrigin) {\n const requestOrigin = request.headers.get('origin');\n if (requestOrigin && requestOrigin !== allowedOrigin) {\n return respondError('Origin not allowed.', 403);\n }\n }\n\n let body: Record<string, unknown>;\n try {\n if (isFormPost) {\n const formData = await request.formData();\n body = {};\n for (const [key, value] of formData.entries()) {\n if (typeof value === 'string') body[key] = value;\n }\n } else {\n // Not just `application/json`: `navigator.sendBeacon` sends a bare\n // string as `text/plain`, and this must keep accepting that body.\n const parsed: unknown = await request.json();\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n return respondError('Malformed request.', 400);\n }\n body = parsed as Record<string, unknown>;\n }\n } catch {\n return respondError('Malformed request.', 400);\n }\n\n const ip =\n request.headers.get('cf-connecting-ip') ??\n request.headers.get('x-forwarded-for')?.split(',')[0]?.trim() ??\n undefined;\n\n // Classified before rate limiting, not read raw off the client — see the key\n // below. `phone`/`email` presence is still checked after limiting, since that\n // check just rejects a malformed beacon rather than deciding the bucket.\n const isCall = body['event'] === 'call';\n const isEmailClick = body['event'] === 'email';\n\n // Keyed on IP *and* the server's own classification (`call` | `email` |\n // `form`), never the raw `event` string the client sent. A call beacon and an\n // email-click beacon from the same visitor are two distinct, legitimate\n // conversions, not a repeat of one, so they need separate buckets — but\n // trusting the raw string for that also let a client dodge the form rate\n // limit entirely by varying `event` on every request (any value other than\n // exactly `'call'`/`'email'` used to get its own bucket). Collapsing\n // everything else to `'form'` closes that without losing the call/email split.\n if (rateLimit && ip) {\n const rlKey = `${ip}:${isCall ? 'call' : isEmailClick ? 'email' : 'form'}`;\n const sinceLastHit = await rateLimit.store.hit(rlKey, now());\n if (sinceLastHit !== null && sinceLastHit < rateLimit.windowMs) {\n return respondError('Too many requests.', 429);\n }\n }\n\n if (isCall && typeof body['phone'] !== 'string') {\n return respondError('Missing phone.', 400);\n }\n\n if (isEmailClick && typeof body['email'] !== 'string') {\n return respondError('Missing email.', 400);\n }\n\n // A call and an email-click beacon are the same shape of thing: a fire-and-\n // forget ping with no form fields to validate, honeypot, verify or map into\n // a CRM — both skip every check below that exists for a form submission.\n const isBeacon = isCall || isEmailClick;\n\n const spam = !isBeacon && hasHoneypot(body, honeypotFields);\n\n if (!isBeacon && !spam && options.turnstile) {\n const {\n secretKey,\n fieldName = 'cf-turnstile-response',\n required = false,\n } = options.turnstile;\n const token = body[fieldName];\n if (typeof token === 'string' && token) {\n const verification = await verifyTurnstileToken(token, secretKey, ip);\n if (!verification.success) return respondError('Verification failed.', 400);\n } else if (required) {\n return respondError('Verification required.', 400);\n }\n }\n\n const refusal = !spam && validate?.(body);\n if (refusal) return respondError(refusal, 400);\n\n const respondSuccess = (): Response =>\n isBeacon\n ? new Response(null, { status: 204 })\n : isFormPost && successRedirect\n ? redirectTo(successRedirect)\n : Response.json({ success: true });\n\n // A honeypot trip never reaches `notify()` — the response is identical to a\n // real success, so a bot gets no signal that it was caught.\n if (spam) {\n onResult?.({\n results: [{ channel: 'email', sent: false, reason: 'Skipped: honeypot triggered.' }],\n delivered: false,\n });\n return respondSuccess();\n }\n\n const turnstileFieldName = options.turnstile?.fieldName;\n const excludedFields = turnstileFieldName\n ? [...honeypotFields, turnstileFieldName]\n : honeypotFields;\n\n const event: ConversionEvent = {\n type: isCall ? 'call' : isEmailClick ? 'email' : 'form',\n ...(isCall\n ? { phone: String(body['phone']).replace(/^tel:/, '') }\n : isEmailClick\n ? { email: String(body['email']).replace(/^mailto:/, '') }\n : { formData: toFormData(body, excludedFields) }),\n tracking: parseTrackingCookie(request.headers.get('cookie')),\n userAgent: request.headers.get('user-agent') ?? undefined,\n ip,\n at: now(),\n };\n\n // CRM before notify: the notification email states the CRM outcome, which\n // is only possible once it's known. Never attempted for a `tel:`/`mailto:`\n // beacon — a CRM contact comes from submitted form fields, and neither\n // event has any to map.\n let crmResult: CrmResult | null = null;\n if (!isBeacon && options.crm) {\n crmResult = await deliverToCrm(event, options.crm.config, {\n credentials: options.crm.credentials?.(locals),\n fetch: options.crm.fetch,\n timeoutMs: options.crm.timeoutMs,\n // Provider-neutral: HubSpot reads `hutk` to stitch the submission to\n // its own tracking; Jobber reads `pageUri` for its note body. Neither\n // is HubSpot-specific to build, so this is passed unconditionally\n // rather than gated on `options.crm.config.provider`.\n pageContext: {\n hutk: readCookie(request.headers.get('cookie'), 'hubspotutk') ?? undefined,\n pageUri: request.headers.get('referer') ?? undefined,\n },\n });\n }\n const crmNote = describeCrmResult(crmResult);\n\n const result: ConversionResult = {\n ...(await notify(\n event,\n context,\n { email: binding?.(locals) },\n crmNote ? { notes: [crmNote] } : {},\n )),\n ...(crmResult ? { crm: crmResult } : {}),\n };\n\n if (onResult) onResult(result);\n else {\n for (const r of result.results) {\n if (!r.sent) console.warn(`[vitops] notification not sent (${r.channel}): ${r.reason}`);\n }\n if (crmResult && !crmResult.ok) {\n console.warn(\n `[vitops] CRM write not delivered (${crmResult.provider}): ${crmResult.reason}`,\n );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AE;GACnD,UAAU,oBAAoB,QAAQ,QAAQ,IAAI,QAAQ,CAAC;GAC3D,WAAW,QAAQ,QAAQ,IAAI,YAAY,KAAK;GAChD;GACA,IAAI,IAAI;EACV;EAMA,IAAI,YAA8B;EAClC,IAAI,CAAC,YAAY,QAAQ,KACvB,YAAY,MAAM,aAAa,OAAO,QAAQ,IAAI,QAAQ;GACxD,aAAa,QAAQ,IAAI,cAAc,MAAM;GAC7C,OAAO,QAAQ,IAAI;GACnB,WAAW,QAAQ,IAAI;GAKvB,aAAa;IACX,MAAM,WAAW,QAAQ,QAAQ,IAAI,QAAQ,GAAG,YAAY,KAAK;IACjE,SAAS,QAAQ,QAAQ,IAAI,SAAS,KAAK;GAC7C;EACF,CAAC;EAEH,MAAM,UAAU,kBAAkB,SAAS;EAE3C,MAAM,SAA2B;GAC/B,GAAI,MAAM,OACR,OACA,SACA,EAAE,OAAO,UAAU,MAAM,EAAE,GAC3B,UAAU,EAAE,OAAO,CAAC,OAAO,EAAE,IAAI,CAAC,CACpC;GACA,GAAI,YAAY,EAAE,KAAK,UAAU,IAAI,CAAC;EACxC;EAEA,IAAI,UAAU,SAAS,MAAM;OACxB;GACH,KAAK,MAAM,KAAK,OAAO,SACrB,IAAI,CAAC,EAAE,MAAM,QAAQ,KAAK,mCAAmC,EAAE,QAAQ,KAAK,EAAE,QAAQ;GAExF,IAAI,aAAa,CAAC,UAAU,IAC1B,QAAQ,KACN,qCAAqC,UAAU,SAAS,KAAK,UAAU,QACzE;EAEJ;EAEA,OAAO,eAAe;CACxB;AACF"}
|
|
1
|
+
{"version":3,"file":"conversion.mjs","names":[],"sources":["../../src/routes/conversion.ts"],"sourcesContent":["/**\n * The conversion endpoint, as a factory.\n *\n * A site's contact form and its `tel:`/`mailto:` beacons all mean the same\n * thing — someone got in touch — and all want the same treatment: read the\n * attribution cookie off the request, build the event, notify whoever the\n * config says. That is the same three lines in every project, so it ships\n * here.\n *\n * What deliberately does **not** ship here is field-level validation and business\n * rules — a consumer's form has its own required fields and its own response\n * shape, and baking a guess at those in would make the factory something to\n * fight rather than mount. The handler takes the parsed body and an optional\n * `validate`; that part is the caller's. What **does** ship here is generic abuse\n * resistance (honeypot, origin, rate limit, body size): this is a public,\n * unauthenticated endpoint that sends email, so leaving it wide open makes it a\n * relay and a cost amplifier regardless of whose form is behind it.\n *\n * The path matters: the capture script beacons `tel:`/`mailto:` conversions at\n * `TRACKING_ENDPOINT` (`/api/track`, exported from `@getvitops/astro/tracking`),\n * and the integration warns at build if no route answers it.\n *\n * ```ts\n * // src/pages/api/track.ts\n * export const prerender = false;\n * import { env } from 'cloudflare:workers';\n * import { createConversionRoute } from '@getvitops/astro/routes';\n *\n * export const POST = createConversionRoute({\n * context: {\n * // A bare address is shorthand for `{ provider: 'cloudflare', to }`.\n * notifications: { email: 'sales@acme.ca' },\n * canonical: 'https://acme.ca',\n * organizationName: 'Acme',\n * },\n * binding: () => env.EMAIL,\n * // A no-JS <form method=\"post\"> submission never sees a JSON response body —\n * // it's a full navigation, so send it somewhere real.\n * redirectTo: '/thanks',\n * });\n * ```\n *\n * Cloudflare Turnstile is a separate, opt-in layer on top of the checks above —\n * pass `turnstile: { secretKey }` and a submission carrying a\n * `cf-turnstile-response` token gets it verified server-side via\n * `verifyTurnstileToken` (`@getvitops/utils/security`). The widget itself is the\n * consumer's own markup (`<script src=\"https://challenges.cloudflare.com/\n * turnstile/v0/api.js\" async defer></script>` + `<div class=\"cf-turnstile\"\n * data-sitekey=\"…\">` on their form) — there is no `FormRenderer` for this to hook\n * into generically, matching how the rest of the form is already hand-written.\n * `site.security.turnstile.siteKey` is what the generated privacy policy reads to\n * name Turnstile as a processor; wiring this option up is what makes that true\n * rather than an assertion nothing checks.\n *\n * Two things this example used to get wrong, both of which cost a consumer real\n * time. It read the binding off `locals.runtime.env`, which Astro removed in v6\n * — and because the resulting throw precedes the response, Astro re-reads the\n * request and reports a misleading \"Body has already been used\" instead of the\n * actual error. This package peers on `astro >= 7`, so that form could not work\n * for any supported consumer; `import { env } from 'cloudflare:workers'` is the\n * current one. It also called a `toNotifyContext(config)` helper that used to\n * not exist — `context` can now be built with `toNotifyContext(config)` (also\n * exported from this module), rather than every consumer hand-writing a\n * `NotifyContext` literal:\n *\n * ```ts\n * import config from '../../site.json' with { type: 'json' };\n * import { createConversionRoute, toNotifyContext, toCrmConfig } from '@getvitops/astro/routes';\n *\n * export const POST = createConversionRoute({\n * context: toNotifyContext(config),\n * crm: toCrmConfig(config) && { config: toCrmConfig(config)!, credentials: () => ({ ... }) },\n * binding: () => env.EMAIL,\n * redirectTo: '/thanks',\n * });\n * ```\n */\nimport { AD_PLATFORMS, normalizeConversionActionIds } from '@getvitops/utils/ads';\nimport type { AdPropertySetup } from '@getvitops/utils/ads';\nimport { deliverToCrm, describeCrmResult } from '@getvitops/utils/crm';\nimport type { CrmConfig, CrmCredentials, CrmResult } from '@getvitops/utils/crm';\nimport {\n describeGoogleAdsOfflineResult,\n type EmailBinding,\n notify,\n type NotifyContext,\n uploadClickConversion,\n type GoogleAdsCredentials,\n type GoogleAdsUploadResult,\n} from '@getvitops/utils/notify';\nimport { verifyTurnstileToken } from '@getvitops/utils/security';\nimport { parseTrackingCookie, readCookie } from '@getvitops/utils/tracking';\nimport type { ConversionEvent, TrackingData } from '@getvitops/utils/tracking';\nexport {\n resolveOrganizationName,\n toCrmConfig,\n toGoogleAdsConfig,\n toNotifyContext,\n} from './config-adapters.ts';\n\n/** The subset of Astro's `APIContext` this needs — typed structurally so the\n * factory does not pin an Astro version. */\nexport interface ConversionRequestContext {\n request: Request;\n locals?: unknown;\n}\n\n/**\n * Records a hit for `id` at time `at` (ms) and returns the ms since the previous\n * hit for that `id`, or `null` if this is the first. Pure interface — a store\n * decides nothing, it only remembers.\n */\nexport interface RateLimitStore {\n hit(id: string, at: number): Promise<number | null> | number | null;\n}\n\n/**\n * Per-isolate, in-memory default. Good enough for a single Worker instance\n * fielding occasional contact-form spam; not durable across a fleet, and not\n * shared with other routes. Inject a KV- or Durable-Object-backed `store` for\n * real cross-instance limiting — the interface is one method wide on purpose.\n */\nclass MemoryRateLimitStore implements RateLimitStore {\n private lastHit = new Map<string, number>();\n hit(id: string, at: number): number | null {\n const prev = this.lastHit.get(id);\n this.lastHit.set(id, at);\n return prev === undefined ? null : at - prev;\n }\n}\n\nexport interface ConversionRouteOptions {\n /** Where notifications go. Build it from your site config. */\n context: NotifyContext;\n /**\n * The Workers `send_email` binding for this request, e.g. `() => env.EMAIL`\n * with `env` imported from `cloudflare:workers`. Omit it in dev and the\n * notification is printed instead of sent.\n *\n * Not `(locals) => locals.runtime.env.EMAIL` — Astro removed `locals.runtime`\n * in v6, and this package peers on `>= 7`.\n */\n binding?: (locals: unknown) => EmailBinding | undefined;\n /**\n * Push the submission into a CRM (HubSpot, Zoho Bigin or Jobber) before notifying.\n * Credentials arrive as a function of `locals`, exactly like `binding` above\n * — the consumer reads them from `import { env } from 'cloudflare:workers'`.\n * Credentials are never config; that rule is absolute in this toolchain.\n *\n * A failed CRM write never fails the request and never blocks the honeypot/\n * Turnstile gates above it — those run first, so a bot never reaches the\n * CRM. The outcome is folded into the notification email's \"Delivery\"\n * section (via `describeCrmResult`) so a failed write is never silent.\n */\n crm?: {\n config: CrmConfig;\n credentials?: (locals: unknown) => CrmCredentials | undefined;\n fetch?: typeof fetch;\n timeoutMs?: number;\n };\n /**\n * Upload the conversion to Google Ads server-side instead of relying on the\n * visitor's browser to fire `gtag.js` — see `site.ads.google.reporting` and\n * `conversionActionId`. Credentials arrive as a function of `locals`, same\n * shape as `crm.credentials` and `binding` above.\n *\n * Only fires for an action whose `conversionActionId` is actually set (via\n * `toGoogleAdsConfig(config)`, or hand-built the same shape) **and** whose\n * event carries a Google click id (`gclid`/`gbraid`/`wbraid` on `_ac`) —\n * an organic conversion has nothing for the Ads API to attribute, so it's\n * silently skipped rather than reported as a failure. A failed upload never\n * fails the request, matching `crm` above; the outcome folds into the same\n * \"Delivery\" section via `describeGoogleAdsOfflineResult`.\n */\n googleAdsOffline?: {\n config: Pick<AdPropertySetup, 'accountId' | 'conversionActionId' | 'reporting'>;\n credentials?: (locals: unknown) => GoogleAdsCredentials | undefined;\n fetch?: typeof fetch;\n };\n /**\n * Reject a submission before anything is sent. Return a message to refuse.\n * This is where a consumer puts required-field checks.\n */\n validate?: (body: Record<string, unknown>) => string | null;\n /** Called with every channel outcome, delivered or not, plus the CRM\n * outcome when `crm` is configured. Defaults to console. */\n onResult?: (result: ConversionResult) => void;\n /** Injected in tests. */\n now?: () => number;\n /**\n * Where to send a no-JS `<form method=\"post\">` submission on success. Without\n * this, that visitor's browser navigates to the raw `{\"success\":true}` JSON\n * body as its next page — functional, but not a page anyone should see. Has\n * no effect on the beacon/fetch (JSON) path, which always gets a JSON response.\n */\n redirectTo?: string;\n /**\n * Where to send a refused no-JS submission (validation, spam checks, malformed\n * body). Falls back to `redirectTo` if omitted, and to the JSON error response\n * if neither is set.\n */\n errorRedirectTo?: string;\n /**\n * Field names treated as honeypots: a bot fills every input it finds, a person\n * never sees these (hidden by CSS in the form markup). A non-empty value is\n * silently treated as spam — the response looks identical to a real success,\n * denying the bot the signal it needs to know the trick worked, but nothing is\n * notified and the field never reaches `notify()`. Defaults to the same names\n * `render.ts`'s `OMIT_FIELDS` already knows about (`website`, `_honeypot`,\n * `honeypot`), so the two lists don't need to be kept in sync by hand.\n */\n honeypotFields?: string[];\n /**\n * Reject a submission whose `Content-Length` exceeds this many bytes. Default\n * 25_000 — generous for a contact form with no file upload, tiny for anything\n * meant to relay large payloads. The header is only a fast path: a chunked\n * request carries none, so the body is also read through a byte-capped\n * reader and refused the moment it passes the cap.\n */\n maxBodyBytes?: number;\n /**\n * Fall back to the first `X-Forwarded-For` hop as the client IP when\n * `CF-Connecting-IP` is absent. Default `false`: off Cloudflare the header is\n * whatever the client sent, so honouring it lets a script mint a fresh\n * rate-limit bucket per request. Turn on only behind a proxy that overwrites\n * it. With neither header trusted there is no IP, and rate limiting is skipped.\n */\n trustForwardedFor?: boolean;\n /**\n * Reject a submission whose `Origin` header doesn't match this origin.\n * Defaults to `context.canonical`'s origin. Pass `false` to disable.\n *\n * Best-effort, not a CSRF guard: browsers omit `Origin` on plenty of\n * legitimate same-origin requests, so its *absence* is never treated as a\n * mismatch — only a present-and-different value is rejected. That still stops\n * the common case (a script hitting the endpoint directly from elsewhere)\n * without breaking real submissions from older or privacy-hardened browsers.\n */\n allowedOrigin?: string | false;\n /**\n * Minimum interval between accepted submissions from the same IP. Pass\n * `false` to disable. `windowMs` defaults to 10 seconds — enough to blunt a\n * script firing in a loop without troubling someone who fat-fingers a form\n * and resubmits.\n */\n rateLimit?: { windowMs?: number; store?: RateLimitStore } | false;\n /**\n * Verify a Cloudflare Turnstile token server-side. The **secret** key —\n * unlike `site.security.turnstile.siteKey`, which is public config — must come\n * from an env var, never a config file (the same rule as every other\n * credential in this toolchain).\n */\n turnstile?: {\n secretKey: string;\n /** The submitted field carrying the token. Default `cf-turnstile-response`\n * — the name Cloudflare's widget submits under. */\n fieldName?: string;\n /**\n * Reject a submission with no token at all, rather than only a present-and-\n * invalid one. Default `false`: an absent token is the ordinary shape of a\n * visitor with JS disabled, and this factory is built around that path\n * staying usable. Set `true` only for a form where verified-human matters\n * enough to accept that trade-off — doing so means that form no longer\n * works without JS, on purpose.\n */\n required?: boolean;\n };\n}\n\n/** `notify()`'s own result, plus the CRM and Google Ads offline-upload\n * outcomes when those are configured. Additive over\n * `Awaited<ReturnType<typeof notify>>` — a consumer's existing `onResult`\n * reading `.results`/`.delivered` keeps compiling unchanged. */\nexport interface ConversionResult extends Awaited<ReturnType<typeof notify>> {\n crm?: CrmResult | undefined;\n googleAds?: GoogleAdsUploadResult | undefined;\n}\n\n/** The click id to report to Google Ads, checked in the same order as\n * `AD_PLATFORMS.google.clickIdParams` rather than `getPrimaryClickId()` —\n * that helper returns whichever platform's click id happens to appear first\n * in the *cross-platform* precedence table, which may not be Google's even\n * when a `gclid` is present. */\nfunction googleClickId(tracking: TrackingData | null): { param: string; value: string } | null {\n if (!tracking) return null;\n for (const param of AD_PLATFORMS.google.clickIdParams) {\n const value = tracking[param];\n if (value) return { param, value: String(value) };\n }\n return null;\n}\n\n/** Fields that are never part of a submission's meaning. `cf-turnstile-response`\n * is excluded unconditionally, matching `render.ts`'s `OMIT_FIELDS` — the field\n * carries a verification token, not something the visitor wrote. */\nconst CONTROL_FIELDS = new Set(['event', 'phone', 'cf-turnstile-response']);\n/** The capture script sends `link.href` as-is: `tel:` + digits and the punctuation people type\n * (a space arrives as `%20`). Not free text. */\nconst PHONE_RE = /^(?:tel:)?\\+?[\\d\\s().%-]{3,40}$/i;\n/** `mailto:` + an address, with an optional `?subject=…` query. A shape check, not deliverability. */\nconst EMAIL_RE = /^(?:mailto:)?[^\\s@<>\"?]{1,64}@[^\\s@<>\"?]{1,255}(?:\\?[^\\s<>\"]{0,256})?$/i;\n\nconst DEFAULT_HONEYPOT_FIELDS = ['website', '_honeypot', 'honeypot'];\nconst DEFAULT_MAX_BODY_BYTES = 25_000;\n\n/**\n * Read a request body, giving up as soon as it exceeds `max` bytes. Returns `null` when over\n * the cap. `Content-Length` is optional on chunked requests, so it cannot be the only guard.\n */\nasync function readCapped(request: Request, max: number): Promise<Uint8Array<ArrayBuffer> | null> {\n if (!request.body) return new Uint8Array();\n const reader = request.body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.byteLength;\n if (total > max) {\n await reader.cancel();\n return null;\n }\n chunks.push(value);\n }\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return bytes;\n}\nconst DEFAULT_RATE_LIMIT_WINDOW_MS = 10_000;\n\nfunction toFormData(\n body: Record<string, unknown>,\n honeypotFields: string[],\n): Record<string, string> {\n const out: Record<string, string> = {};\n for (const [key, value] of Object.entries(body)) {\n if (CONTROL_FIELDS.has(key) || honeypotFields.includes(key)) continue;\n if (value === undefined || value === null) continue;\n out[key] = String(value);\n }\n return out;\n}\n\nfunction hasHoneypot(body: Record<string, unknown>, honeypotFields: string[]): boolean {\n return honeypotFields.some((field) => {\n const value = body[field];\n return typeof value === 'string' && value.trim() !== '';\n });\n}\n\nfunction originOf(url: string | undefined): string | null {\n if (!url) return null;\n try {\n return new URL(url).origin;\n } catch {\n return null;\n }\n}\n\n/** A `Location` header response — used for the no-JS form path instead of\n * `Response.redirect()`, which requires a base URL this factory doesn't have. */\nfunction redirectTo(location: string, status = 303): Response {\n return new Response(null, { status, headers: { Location: location } });\n}\n\n/**\n * Build a POST handler for conversions.\n *\n * Returns 204 for a beacon and 200 with `{ success }` for a JSON (fetch-based)\n * form submission, matching what `navigator.sendBeacon` and a fetch-submitting\n * form each expect. A no-JS `<form method=\"post\">` — `application/\n * x-www-form-urlencoded` or `multipart/form-data` — is parsed the same way and,\n * on success, redirected to `redirectTo` if one is configured.\n *\n * **A failed notification does not fail the request.** The visitor has already\n * submitted; refusing them because our mail did not go out turns a lost\n * notification into a lost conversion. Failures are reported through `onResult`.\n */\nexport function createConversionRoute(options: ConversionRouteOptions) {\n const {\n context,\n binding,\n validate,\n onResult,\n now = Date.now,\n redirectTo: successRedirect,\n errorRedirectTo = successRedirect,\n honeypotFields = DEFAULT_HONEYPOT_FIELDS,\n maxBodyBytes = DEFAULT_MAX_BODY_BYTES,\n trustForwardedFor = false,\n } = options;\n\n const allowedOrigin =\n options.allowedOrigin === false ? null : (options.allowedOrigin ?? originOf(context.canonical));\n\n const rateLimit =\n options.rateLimit === false\n ? null\n : {\n windowMs: options.rateLimit?.windowMs ?? DEFAULT_RATE_LIMIT_WINDOW_MS,\n store: options.rateLimit?.store ?? new MemoryRateLimitStore(),\n };\n\n return async ({ request, locals }: ConversionRequestContext): Promise<Response> => {\n const contentType = request.headers.get('content-type') ?? '';\n const isFormPost =\n contentType.includes('multipart/form-data') ||\n contentType.includes('application/x-www-form-urlencoded');\n\n const respondError = (error: string, status: number): Response =>\n isFormPost && errorRedirectTo\n ? redirectTo(errorRedirectTo)\n : Response.json({ success: false, error }, { status });\n\n const contentLength = Number(request.headers.get('content-length') ?? 0);\n if (contentLength > maxBodyBytes) {\n return respondError('Request too large.', 413);\n }\n\n if (allowedOrigin) {\n const requestOrigin = request.headers.get('origin');\n if (requestOrigin && requestOrigin !== allowedOrigin) {\n return respondError('Origin not allowed.', 403);\n }\n }\n\n // A chunked request has no Content-Length to check above, so cap the stream itself.\n const bytes = await readCapped(request, maxBodyBytes);\n if (!bytes) return respondError('Request too large.', 413);\n\n let body: Record<string, unknown>;\n try {\n if (isFormPost) {\n const formData = await new Response(bytes, {\n headers: { 'content-type': contentType },\n }).formData();\n body = {};\n for (const [key, value] of formData.entries()) {\n if (typeof value === 'string') body[key] = value;\n }\n } else {\n // Not just `application/json`: `navigator.sendBeacon` sends a bare\n // string as `text/plain`, and this must keep accepting that body.\n const parsed: unknown = JSON.parse(new TextDecoder().decode(bytes));\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n return respondError('Malformed request.', 400);\n }\n body = parsed as Record<string, unknown>;\n }\n } catch {\n return respondError('Malformed request.', 400);\n }\n\n const ip =\n request.headers.get('cf-connecting-ip') ??\n (trustForwardedFor ? request.headers.get('x-forwarded-for')?.split(',')[0]?.trim() : null) ??\n undefined;\n\n // Classified before rate limiting, not read raw off the client — see the key\n // below. `phone`/`email` presence is still checked after limiting, since that\n // check just rejects a malformed beacon rather than deciding the bucket.\n const isCall = body['event'] === 'call';\n const isEmailClick = body['event'] === 'email';\n\n // Keyed on IP *and* the server's own classification (`call` | `email` |\n // `form`), never the raw `event` string the client sent. A call beacon and an\n // email-click beacon from the same visitor are two distinct, legitimate\n // conversions, not a repeat of one, so they need separate buckets — but\n // trusting the raw string for that also let a client dodge the form rate\n // limit entirely by varying `event` on every request (any value other than\n // exactly `'call'`/`'email'` used to get its own bucket). Collapsing\n // everything else to `'form'` closes that without losing the call/email split.\n if (rateLimit && ip) {\n const rlKey = `${ip}:${isCall ? 'call' : isEmailClick ? 'email' : 'form'}`;\n const sinceLastHit = await rateLimit.store.hit(rlKey, now());\n if (sinceLastHit !== null && sinceLastHit < rateLimit.windowMs) {\n return respondError('Too many requests.', 429);\n }\n }\n\n // A beacon skips every form check, so its one payload field is format-checked instead:\n // the value is interpolated into a notification someone reads, and an unauthenticated\n // caller should not be able to put arbitrary text there.\n if (isCall && !(typeof body['phone'] === 'string' && PHONE_RE.test(body['phone']))) {\n return respondError('Missing phone.', 400);\n }\n\n if (isEmailClick && !(typeof body['email'] === 'string' && EMAIL_RE.test(body['email']))) {\n return respondError('Missing email.', 400);\n }\n\n // A call and an email-click beacon are the same shape of thing: a fire-and-\n // forget ping with no form fields to validate, honeypot, verify or map into\n // a CRM — both skip every check below that exists for a form submission.\n const isBeacon = isCall || isEmailClick;\n\n const spam = !isBeacon && hasHoneypot(body, honeypotFields);\n\n if (!isBeacon && !spam && options.turnstile) {\n const {\n secretKey,\n fieldName = 'cf-turnstile-response',\n required = false,\n } = options.turnstile;\n const token = body[fieldName];\n if (typeof token === 'string' && token) {\n const verification = await verifyTurnstileToken(token, secretKey, ip);\n if (!verification.success) return respondError('Verification failed.', 400);\n } else if (required) {\n return respondError('Verification required.', 400);\n }\n }\n\n const refusal = !spam && validate?.(body);\n if (refusal) return respondError(refusal, 400);\n\n const respondSuccess = (): Response =>\n isBeacon\n ? new Response(null, { status: 204 })\n : isFormPost && successRedirect\n ? redirectTo(successRedirect)\n : Response.json({ success: true });\n\n // A honeypot trip never reaches `notify()` — the response is identical to a\n // real success, so a bot gets no signal that it was caught.\n if (spam) {\n onResult?.({\n results: [{ channel: 'email', sent: false, reason: 'Skipped: honeypot triggered.' }],\n delivered: false,\n });\n return respondSuccess();\n }\n\n const turnstileFieldName = options.turnstile?.fieldName;\n const excludedFields = turnstileFieldName\n ? [...honeypotFields, turnstileFieldName]\n : honeypotFields;\n\n const event: ConversionEvent = {\n type: isCall ? 'call' : isEmailClick ? 'email' : 'form',\n ...(isCall\n ? { phone: String(body['phone']).replace(/^tel:/, '') }\n : isEmailClick\n ? { email: String(body['email']).replace(/^mailto:/, '') }\n : { formData: toFormData(body, excludedFields) }),\n tracking: parseTrackingCookie(request.headers.get('cookie')),\n userAgent: request.headers.get('user-agent') ?? undefined,\n ip,\n at: now(),\n };\n\n // CRM before notify: the notification email states the CRM outcome, which\n // is only possible once it's known. Never attempted for a `tel:`/`mailto:`\n // beacon — a CRM contact comes from submitted form fields, and neither\n // event has any to map.\n let crmResult: CrmResult | null = null;\n if (!isBeacon && options.crm) {\n crmResult = await deliverToCrm(event, options.crm.config, {\n credentials: options.crm.credentials?.(locals),\n fetch: options.crm.fetch,\n timeoutMs: options.crm.timeoutMs,\n // Provider-neutral: HubSpot reads `hutk` to stitch the submission to\n // its own tracking; Jobber reads `pageUri` for its note body. Neither\n // is HubSpot-specific to build, so this is passed unconditionally\n // rather than gated on `options.crm.config.provider`.\n pageContext: {\n hutk: readCookie(request.headers.get('cookie'), 'hubspotutk') ?? undefined,\n pageUri: request.headers.get('referer') ?? undefined,\n },\n });\n }\n const crmNote = describeCrmResult(crmResult);\n\n // Unlike CRM, this runs for a `tel:`/`mailto:` beacon too — those are\n // exactly the actions the client-side gtag handler would otherwise fire\n // for. Skipped, not failed, when there's no click id to attribute, no\n // `conversionActionId` configured for this action, or no credentials for\n // this environment (e.g. local dev) — none of those is a real failure.\n let googleAdsResult: GoogleAdsUploadResult | null = null;\n const adsCfg = options.googleAdsOffline?.config;\n if (adsCfg?.reporting === 'server' && adsCfg.accountId) {\n const actionId = normalizeConversionActionIds(adsCfg.conversionActionId)[event.type];\n const clickId = googleClickId(event.tracking);\n const credentials = options.googleAdsOffline?.credentials?.(locals);\n if (actionId && clickId && credentials) {\n googleAdsResult = await uploadClickConversion(\n { customerId: adsCfg.accountId, conversionActionId: actionId, clickId, at: event.at },\n credentials,\n options.googleAdsOffline?.fetch,\n );\n }\n }\n const googleAdsNote = describeGoogleAdsOfflineResult(googleAdsResult);\n\n const result: ConversionResult = {\n ...(await notify(\n event,\n context,\n { email: binding?.(locals) },\n {\n notes: [crmNote, googleAdsNote].filter((n): n is string => n != null),\n },\n )),\n ...(crmResult ? { crm: crmResult } : {}),\n ...(googleAdsResult ? { googleAds: googleAdsResult } : {}),\n };\n\n if (onResult) onResult(result);\n else {\n for (const r of result.results) {\n if (!r.sent) console.warn(`[vitops] notification not sent (${r.channel}): ${r.reason}`);\n }\n if (crmResult && !crmResult.ok) {\n console.warn(\n `[vitops] CRM write not delivered (${crmResult.provider}): ${crmResult.reason}`,\n );\n }\n if (googleAdsResult && !googleAdsResult.ok) {\n console.warn(`[vitops] Google Ads offline upload not delivered: ${googleAdsResult.reason}`);\n }\n }\n\n return respondSuccess();\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0HA,IAAM,uBAAN,MAAqD;CACnD,AAAQ,0BAAU,IAAI,IAAoB;CAC1C,IAAI,IAAY,IAA2B;EACzC,MAAM,OAAO,KAAK,QAAQ,IAAI,EAAE;EAChC,KAAK,QAAQ,IAAI,IAAI,EAAE;EACvB,OAAO,SAAS,SAAY,OAAO,KAAK;CAC1C;AACF;;;;;;AA0JA,SAAS,cAAc,UAAwE;CAC7F,IAAI,CAAC,UAAU,OAAO;CACtB,KAAK,MAAM,SAAS,aAAa,OAAO,eAAe;EACrD,MAAM,QAAQ,SAAS;EACvB,IAAI,OAAO,OAAO;GAAE;GAAO,OAAO,OAAO,KAAK;EAAE;CAClD;CACA,OAAO;AACT;;;;AAKA,MAAM,iCAAiB,IAAI,IAAI;CAAC;CAAS;CAAS;AAAuB,CAAC;;;AAG1E,MAAM,WAAW;;AAEjB,MAAM,WAAW;AAEjB,MAAM,0BAA0B;CAAC;CAAW;CAAa;AAAU;AACnE,MAAM,yBAAyB;;;;;AAM/B,eAAe,WAAW,SAAkB,KA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KIE = "_ac";
|
|
4
4
|
/**
|
|
@@ -42,6 +42,5 @@ function resolveTracking(opts, ctx = {}) {
|
|
|
42
42
|
};
|
|
43
43
|
}
|
|
44
44
|
|
|
45
|
-
//#endregion
|
|
46
45
|
export { TRACKING_ENDPOINT as n, resolveTracking as r, TRACKING_COOKIE as t };
|
|
47
|
-
//# sourceMappingURL=tracking-
|
|
46
|
+
//# sourceMappingURL=tracking-Cb3A0BrC.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tracking-Cb3A0BrC.mjs","names":[],"sources":["../src/tracking.ts"],"sourcesContent":["/**\n * The `<Tracking />` resolution layer — tracking config in, what to emit out.\n *\n * Separate from `Tracking.astro` for the same reason `analytics.ts` is separate\n * from `Analytics.astro`: everything decidable is a pure function asserted in\n * `tracking.test.ts`, and the component only renders what this returns.\n *\n * The one decision here is **which consent category the `_ac` cookie waits on**,\n * and it is stated rather than inferred. `_ac` is a 90-day identifier tying a\n * visitor to the ad that brought them, so `marketing` is the default — but a site\n * using click IDs purely for its own campaign reporting may reasonably file it\n * under `analytics`, and that is the consumer's call to make, not ours to guess.\n */\n\nimport type { TrackingConfig } from '@getvitops/config';\n\n/** Which consent category the attribution cookie waits on. */\nexport type TrackingCategory = NonNullable<TrackingConfig['category']>;\n\n/** The `site.tracking` block — the schema's own type from `@getvitops/config`, not a copy. */\nexport type GetvitopsTrackingOptions = TrackingConfig;\n\n/** The cookie the capture script writes. Mirrors `TRACKING_COOKIE` in utils. */\nexport const TRACKING_COOKIE = '_ac';\n\n/**\n * Where the capture script sends its `tel:`/`mailto:` conversion beacons.\n *\n * The route itself is the consumer's to write (`createConversionRoute()` in\n * `@getvitops/astro/routes`), so this is the one place the two halves agree on\n * a path. It was a bare literal inside the inlined script: a consumer who named\n * the file anything else got a silent 404 on every beacon and lost conversions\n * with no error anywhere to explain it. Exported so a consumer can assert\n * against it, mirrored in `scripts/tracking.ts` because that file is inlined\n * into the document and cannot import, and pinned by `tracking.test.ts`.\n */\nexport const TRACKING_ENDPOINT = '/api/track';\n\nexport interface ResolvedTracking {\n enabled: boolean;\n category: TrackingCategory;\n /** Cookie names to clear on revoke — rides on `data-consent-cookies`. */\n cookies: string[];\n /** Configuration problems, as prose. The integration logs these. */\n warnings: string[];\n}\n\nexport interface ResolveTrackingContext {\n /** Is the consent gate enabled on this site (`vitops({ consent })`)? */\n consent?: boolean;\n /** Categories the banner offers, so we can catch a demand with no row. */\n consentCategories?: readonly string[];\n}\n\n/**\n * Resolve the tracking config into what the component emits.\n *\n * Two warnings, both about the same failure — a persistent identifier written\n * with no way for the visitor to decline, or a permission asked for with no way\n * to answer. Returned as data rather than logged here so the check is a test\n * rather than a line someone might scroll past, exactly as `resolveAnalytics`\n * does.\n */\nexport function resolveTracking(\n opts: GetvitopsTrackingOptions | undefined,\n ctx: ResolveTrackingContext = {},\n): ResolvedTracking {\n const warnings: string[] = [];\n const category: TrackingCategory = opts?.category ?? 'marketing';\n const enabled = opts?.enabled === true;\n\n if (!enabled) return { enabled: false, category, cookies: [], warnings };\n\n if (!ctx.consent) {\n warnings.push(\n `tracking is on, so this site writes the \\`${TRACKING_COOKIE}\\` cookie — a 90-day ` +\n 'identifier tying a visitor to the ad that brought them — and `consent` is off, so it ' +\n 'is written for every visitor with no way to decline. Set `consent: true`.',\n );\n } else if (ctx.consentCategories && !ctx.consentCategories.includes(category)) {\n // The banner would be raised for a category it renders no row for: the\n // visitor is asked a question the form does not show them.\n warnings.push(\n `tracking demands the \\`${category}\\` consent category, but the banner offers ` +\n `${ctx.consentCategories.join(', ') || 'nothing'}. Add \\`${category}\\` to ` +\n '`consent.categories`, or the visitor is asked about something the banner never names.',\n );\n }\n\n return { enabled, category, cookies: [TRACKING_COOKIE], warnings };\n}\n"],"mappings":";;AAuBA,MAAa,kBAAkB;;;;;;;;;;;;AAa/B,MAAa,oBAAoB;;;;;;;;;;AA2BjC,SAAgB,gBACd,MACA,MAA8B,CAAC,GACb;CAClB,MAAM,WAAqB,CAAC;CAC5B,MAAM,WAA6B,MAAM,YAAY;CACrD,MAAM,UAAU,MAAM,YAAY;CAElC,IAAI,CAAC,SAAS,OAAO;EAAE,SAAS;EAAO;EAAU,SAAS,CAAC;EAAG;CAAS;CAEvE,IAAI,CAAC,IAAI,SACP,SAAS,KACP,mDAA6D,wLAG/D;MACK,IAAI,IAAI,qBAAqB,CAAC,IAAI,kBAAkB,SAAS,QAAQ,GAG1E,SAAS,KACP,0BAA0B,SAAS,6CAC9B,IAAI,kBAAkB,KAAK,IAAI,KAAK,UAAU,UAAU,SAAS,8FAExE;CAGF,OAAO;EAAE;EAAS;EAAU,SAAS,MAAgB;EAAG;CAAS;AACnE"}
|
|
@@ -1,27 +1,8 @@
|
|
|
1
|
-
|
|
2
|
-
/**
|
|
3
|
-
* The `<Tracking />` resolution layer — tracking config in, what to emit out.
|
|
4
|
-
*
|
|
5
|
-
* Separate from `Tracking.astro` for the same reason `analytics.ts` is separate
|
|
6
|
-
* from `Analytics.astro`: everything decidable is a pure function asserted in
|
|
7
|
-
* `tracking.test.ts`, and the component only renders what this returns.
|
|
8
|
-
*
|
|
9
|
-
* The one decision here is **which consent category the `_ac` cookie waits on**,
|
|
10
|
-
* and it is stated rather than inferred. `_ac` is a 90-day identifier tying a
|
|
11
|
-
* visitor to the ad that brought them, so `marketing` is the default — but a site
|
|
12
|
-
* using click IDs purely for its own campaign reporting may reasonably file it
|
|
13
|
-
* under `analytics`, and that is the consumer's call to make, not ours to guess.
|
|
14
|
-
*/
|
|
1
|
+
import { TrackingConfig } from "@getvitops/config";
|
|
15
2
|
/** Which consent category the attribution cookie waits on. */
|
|
16
|
-
type TrackingCategory = '
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
enabled?: boolean;
|
|
20
|
-
/** Default `marketing`. */
|
|
21
|
-
category?: TrackingCategory;
|
|
22
|
-
/** Informational; capture recognises every known click-ID parameter regardless. */
|
|
23
|
-
platforms?: string[];
|
|
24
|
-
}
|
|
3
|
+
type TrackingCategory = NonNullable<TrackingConfig['category']>;
|
|
4
|
+
/** The `site.tracking` block — the schema's own type from `@getvitops/config`, not a copy. */
|
|
5
|
+
type GetvitopsTrackingOptions = TrackingConfig;
|
|
25
6
|
/** The cookie the capture script writes. Mirrors `TRACKING_COOKIE` in utils. */
|
|
26
7
|
declare const TRACKING_COOKIE = "_ac";
|
|
27
8
|
/**
|
|
@@ -60,6 +41,5 @@ interface ResolveTrackingContext {
|
|
|
60
41
|
* does.
|
|
61
42
|
*/
|
|
62
43
|
declare function resolveTracking(opts: GetvitopsTrackingOptions | undefined, ctx?: ResolveTrackingContext): ResolvedTracking;
|
|
63
|
-
//#endregion
|
|
64
44
|
export { TRACKING_ENDPOINT as a, TRACKING_COOKIE as i, ResolveTrackingContext as n, TrackingCategory as o, ResolvedTracking as r, resolveTracking as s, GetvitopsTrackingOptions as t };
|
|
65
|
-
//# sourceMappingURL=tracking-
|
|
45
|
+
//# sourceMappingURL=tracking-D2xOzjFD.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tracking-D2xOzjFD.d.mts","names":[],"sources":["../src/tracking.ts"],"mappings":";;KAiBY,mBAAmB,YAAY;;KAG/B,2BAA2B;;cAG1B;;;;;;;;;;;;cAaA;UAEI;EACf;EACA,UAAU;;EAEV;;EAEA;;UAGe;;EAEf;;EAEA;;;;;;;;;;;iBAYc,gBACd,MAAM,sCACN,MAAK,yBACJ"}
|