@shware/analytics 16.2.2 → 16.2.3

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.
Files changed (41) hide show
  1. package/dist/schema/index.cjs +9 -7
  2. package/dist/schema/index.cjs.map +1 -1
  3. package/dist/schema/index.d.cts.map +1 -1
  4. package/dist/schema/index.d.mts.map +1 -1
  5. package/dist/schema/index.mjs +9 -7
  6. package/dist/schema/index.mjs.map +1 -1
  7. package/dist/server/event-time.cjs +14 -0
  8. package/dist/server/event-time.cjs.map +1 -0
  9. package/dist/server/event-time.d.cts +8 -0
  10. package/dist/server/event-time.d.cts.map +1 -0
  11. package/dist/server/event-time.d.mts +8 -0
  12. package/dist/server/event-time.d.mts.map +1 -0
  13. package/dist/server/event-time.mjs +13 -0
  14. package/dist/server/event-time.mjs.map +1 -0
  15. package/dist/server/meta-capi.cjs +4 -3
  16. package/dist/server/meta-capi.cjs.map +1 -1
  17. package/dist/server/meta-capi.d.cts.map +1 -1
  18. package/dist/server/meta-capi.d.mts.map +1 -1
  19. package/dist/server/meta-capi.mjs +4 -3
  20. package/dist/server/meta-capi.mjs.map +1 -1
  21. package/dist/server/microsoft-conversions-api.cjs +2 -1
  22. package/dist/server/microsoft-conversions-api.cjs.map +1 -1
  23. package/dist/server/microsoft-conversions-api.d.cts.map +1 -1
  24. package/dist/server/microsoft-conversions-api.d.mts.map +1 -1
  25. package/dist/server/microsoft-conversions-api.mjs +2 -1
  26. package/dist/server/microsoft-conversions-api.mjs.map +1 -1
  27. package/dist/server/reddit-conversions-api.cjs +2 -1
  28. package/dist/server/reddit-conversions-api.cjs.map +1 -1
  29. package/dist/server/reddit-conversions-api.d.cts.map +1 -1
  30. package/dist/server/reddit-conversions-api.d.mts.map +1 -1
  31. package/dist/server/reddit-conversions-api.mjs +2 -1
  32. package/dist/server/reddit-conversions-api.mjs.map +1 -1
  33. package/dist/visitor/id.cjs +5 -2
  34. package/dist/visitor/id.cjs.map +1 -1
  35. package/dist/visitor/id.d.cts +4 -1
  36. package/dist/visitor/id.d.cts.map +1 -1
  37. package/dist/visitor/id.d.mts +4 -1
  38. package/dist/visitor/id.d.mts.map +1 -1
  39. package/dist/visitor/id.mjs +6 -3
  40. package/dist/visitor/id.mjs.map +1 -1
  41. package/package.json +1 -1
@@ -161,22 +161,24 @@ const propertiesSchema = (0, zod_mini.optional)((0, zod_mini.pipe)((0, zod_mini.
161
161
  items
162
162
  ])), (0, zod_mini.transform)(takeProperties)));
163
163
  /**
164
- * How far an event's time may be from the server's before the client clock it was stamped with is
165
- * taken as wrong. A batch legitimately arrives late — a tab frozen in the background, a
164
+ * How far behind the server's an event's time may be before the client clock it was stamped with
165
+ * is taken as wrong. A batch legitimately arrives late — a tab frozen in the background, a
166
166
  * session_start held back after a failed batch — by hours, not days; a phone set to another year
167
- * writes its sessions into that year.
167
+ * writes its sessions into that year. Ahead of the server's is wrong by any amount: an event
168
+ * cannot have happened after it arrived, and a clock a few minutes fast is common enough that the
169
+ * conversions APIs, which reject a future event, turned its events away by the hundred.
168
170
  */
169
171
  const MAX_CLOCK_SKEW = 864e5;
170
172
  /**
171
173
  * Puts the events stamped by a wrong client clock onto the server's, where they are parsed. Only
172
- * the events outside `MAX_CLOCK_SKEW` move, so one bad event cannot drag the rest of its batch
173
- * along: they move together by their own latest one — the wrong clock at sending — keeping their
174
- * order and spacing, and one still out after that (a batch mixing two wrong clocks) is on no clock
174
+ * the events ahead of the server, or further behind it than `MAX_CLOCK_SKEW`, move, so one bad
175
+ * event cannot drag the rest of its batch along: they move together by their own latest one — the
176
+ * wrong clock at sending — keeping their order and spacing, and one still out after that (a batch mixing two wrong clocks) is on no clock
175
177
  * at all and takes the server's time. Corrected rather than rejected, for the same reason values
176
178
  * are truncated: a wrong clock should cost the event its time, not the batch its events.
177
179
  */
178
180
  function alignClock(events, now = Date.now()) {
179
- const within = (time) => Math.abs(now - time) <= MAX_CLOCK_SKEW;
181
+ const within = (time) => time <= now && now - time <= MAX_CLOCK_SKEW;
180
182
  const times = events.map((event) => Date.parse(event.timestamp));
181
183
  const wrong = times.filter((time) => !within(time));
182
184
  if (wrong.length === 0) return events;
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["pipe","string","transform","array","record","union","number","boolean","_null","object","optional","trim","minLength","maxLength","regex","uuid","_enum","iso","toLowerCase","email","e164","toUpperCase","url"],"sources":["../../src/schema/index.ts"],"sourcesContent":["import {\n enum as _enum,\n null as _null,\n array,\n boolean,\n e164,\n email,\n iso,\n maxLength,\n minLength,\n number,\n object,\n optional,\n pipe,\n record,\n regex,\n string,\n toLowerCase,\n toUpperCase,\n transform,\n trim,\n union,\n url,\n uuid,\n type z,\n} from 'zod/mini';\nimport type { Environment, Platform } from '../track/types';\n\nconst MAX_KEY_LENGTH = 128;\nconst MAX_VALUE_LENGTH = 512;\nconst MAX_PROPERTIES = 64;\n\n/**\n * Truncated rather than rejected. These schemas validate a whole batch at once, so refusing one\n * oversized value costs every event that traveled with it — and the values that overrun are the\n * ones derived from the page (a link's text, a URL carrying a long query), which no client can\n * bound in advance. A shortened value is worth more than a lost batch.\n */\nconst propertyText = pipe(\n string(),\n transform((value) => value.slice(0, MAX_VALUE_LENGTH))\n);\n\n/**\n * Tags are truncated for the same reason property values are, and they are stored more than once\n * (on the event, the session and the visitor), so an unbounded one costs several times over.\n * 1024 sits just above what GA4 itself keeps (1000 characters of page_location, 420 of\n * page_referrer, 300 of page_title). Real tags stay under ~500 characters; the rare longer ones\n * are page_referrer values from search and ad redirect URLs, where the kept prefix — host and\n * path — is the part that matters.\n */\nconst MAX_TAG_LENGTH = 1024;\n\nconst tagText = pipe(\n string(),\n transform((value) => value.slice(0, MAX_TAG_LENGTH))\n);\n\n/**\n * Keys are written by hand in instrumentation code, so an unusable one is a mistake in the host\n * rather than something the visitor typed. It is still dropped rather than rejected, for the same\n * reason: the mistake should cost that property, not the batch it happens to be in. Truncating a\n * key is not an option — two long keys would silently become one field.\n *\n * The key schema below is deliberately permissive so that this transform is reached at all; the\n * trimming it used to do happens here instead. `MAX_PROPERTIES` keeps the first N in insertion\n * order.\n */\nfunction takeProperties<T>(data: Record<string, T>): Record<string, T> {\n const result: Record<string, T> = {};\n let count = 0;\n for (const [rawKey, value] of Object.entries(data)) {\n if (count >= MAX_PROPERTIES) break;\n const key = rawKey.trim();\n if (!key || key.length > MAX_KEY_LENGTH) continue;\n result[key] = value;\n count++;\n }\n return result;\n}\n\n/**\n * Capped at GA4's own item-list limit, and truncated rather than rejected like every other\n * property limit here: an unbounded array is the one field a caller could still blow a batch\n * up with after the value and key limits.\n */\nconst MAX_ITEMS = 200;\n\nconst items = pipe(\n array(\n pipe(\n record(string(), union([propertyText, number(), boolean(), _null()])),\n transform(takeProperties)\n )\n ),\n transform((list) => list.slice(0, MAX_ITEMS))\n);\n\nexport const ALL_PLATFORMS = [\n 'ios',\n 'android',\n 'web',\n 'macos',\n 'windows',\n 'linux',\n 'unknown',\n] as const satisfies Platform[];\n\nexport const ALL_ENVIRONMENTS = ['development', 'production'] as const satisfies Environment[];\n\nexport const tagsSchema = object({\n os: optional(tagText),\n os_name: optional(tagText),\n os_version: optional(tagText),\n browser: optional(tagText),\n browser_name: optional(tagText),\n browser_version: optional(tagText),\n device: optional(tagText),\n device_id: optional(string().check(trim(), minLength(1), maxLength(36))),\n device_type: optional(tagText),\n device_vendor: optional(tagText),\n device_pixel_ratio: optional(number()),\n screen_width: optional(number()),\n screen_height: optional(number()),\n screen_resolution: optional(\n pipe(\n string().check(regex(/^\\d+x\\d+$/)),\n transform((v) => v as `${number}x${number}`)\n )\n ),\n webdriver: optional(boolean()),\n release: optional(tagText),\n language: optional(tagText),\n time_zone: optional(tagText),\n page_location: optional(tagText),\n page_referrer: optional(tagText),\n page_title: optional(tagText),\n page_load_id: optional(tagText),\n /**\n * @deprecated Renamed to `page_location` in 7.0.0. Accepted so that events from clients\n * still on an older SDK are not stripped of their page URL at this boundary — a browser\n * bundle stays cached long after a backend deploys. Remove once those clients are gone;\n * `pageLocation` in `server/page-location.ts` is the only reader.\n */\n // oxlint-disable-next-line typescript/no-deprecated -- Legacy input from pre-7.0 clients must survive validation.\n source_url: optional(tagText),\n // app info\n advertising_id: optional(tagText),\n install_referrer: optional(tagText),\n // Ad click ids (URL parameters) and ad platform cookies (underscore names); see AdvertisingInfo.\n // Meta Ads\n fbclid: optional(tagText),\n ad_id: optional(tagText),\n ad_name: optional(tagText),\n adset_id: optional(tagText),\n adset_name: optional(tagText),\n campaign_id: optional(tagText),\n campaign_name: optional(tagText),\n placement: optional(tagText),\n _fbc: optional(tagText),\n _fbp: optional(tagText),\n /**\n * @deprecated `fbc` / `fbp` / `rdt_uuid` were renamed to `_fbc` / `_fbp` / `_rdt_uuid` in 9.0.0.\n * Accepted so that conversions from clients still on an older SDK keep their match keys; the\n * senders read them only as a fallback (`server/click-ids.ts`). Remove once those clients are\n * gone.\n */\n // oxlint-disable-next-line typescript/no-deprecated -- Legacy pre-9.0 click-id fields must survive validation.\n fbc: optional(tagText),\n fbp: optional(tagText),\n rdt_uuid: optional(tagText),\n // Google Ads\n gclid: optional(tagText),\n gclsrc: optional(tagText),\n gad_source: optional(tagText),\n gad_campaignid: optional(tagText),\n network: optional(tagText),\n match_type: optional(tagText),\n wbraid: optional(tagText),\n gbraid: optional(tagText),\n dclid: optional(tagText),\n _gcl_aw: optional(tagText),\n _gcl_gb: optional(tagText),\n // Microsoft Ads\n msclkid: optional(tagText),\n _uetmsclkid: optional(tagText),\n // Reddit Ads\n rdt_cid: optional(tagText),\n _rdt_cid: optional(tagText),\n _rdt_uuid: optional(tagText),\n // LinkedIn Ads\n li_fat_id: optional(tagText),\n _li_fat_id: optional(tagText),\n // OpenAI Ads\n oppref: optional(tagText),\n __oppref: optional(tagText),\n __obref: optional(tagText),\n // other click ids\n ko_click_id: optional(tagText),\n ScCid: optional(tagText),\n ttclid: optional(tagText),\n twclid: optional(tagText),\n yclid: optional(tagText),\n epik: optional(tagText),\n // utm params\n utm_source: optional(tagText),\n utm_medium: optional(tagText),\n utm_campaign: optional(tagText),\n utm_term: optional(tagText),\n utm_content: optional(tagText),\n utm_id: optional(tagText),\n utm_source_platform: optional(tagText),\n utm_creative_format: optional(tagText),\n utm_marketing_tactic: optional(tagText),\n});\n\nexport const propertiesSchema = optional(\n pipe(\n record(string(), union([propertyText, number(), boolean(), _null(), items])),\n transform(takeProperties)\n )\n);\n\n/**\n * How far an event's time may be from the server's before the client clock it was stamped with is\n * taken as wrong. A batch legitimately arrives late — a tab frozen in the background, a\n * session_start held back after a failed batch — by hours, not days; a phone set to another year\n * writes its sessions into that year.\n */\nconst MAX_CLOCK_SKEW = 24 * 60 * 60 * 1000;\n\n/**\n * Puts the events stamped by a wrong client clock onto the server's, where they are parsed. Only\n * the events outside `MAX_CLOCK_SKEW` move, so one bad event cannot drag the rest of its batch\n * along: they move together by their own latest one — the wrong clock at sending — keeping their\n * order and spacing, and one still out after that (a batch mixing two wrong clocks) is on no clock\n * at all and takes the server's time. Corrected rather than rejected, for the same reason values\n * are truncated: a wrong clock should cost the event its time, not the batch its events.\n */\nfunction alignClock<T extends { timestamp: string }>(events: T[], now = Date.now()): T[] {\n const within = (time: number) => Math.abs(now - time) <= MAX_CLOCK_SKEW;\n const times = events.map((event) => Date.parse(event.timestamp));\n const wrong = times.filter((time) => !within(time));\n if (wrong.length === 0) return events;\n const offset = now - Math.max(...wrong);\n return events.map((event, i) => {\n if (within(times[i])) return event;\n const shifted = times[i] + offset;\n return { ...event, timestamp: new Date(within(shifted) ? shifted : now).toISOString() };\n });\n}\n\nexport const createTrackEventSchema = pipe(\n array(\n object({\n /**\n * The event's id, generated by the client when the event was tracked (12.1) and given to\n * the browser pixels as their deduplication id. Store the event under it with\n * `on conflict (id) do nothing`: a batch retried after the server committed it then\n * stores nothing twice. Optional for clients before 12.1, which send none — generate one\n * on the server for those.\n */\n id: optional(uuid({ version: 'v7' })),\n name: string().check(trim(), minLength(1), maxLength(64)),\n // Generated by the SDK, like `id` (`visitorId()`, `Session`): uuidv7 as well, so the\n // constraint is checked here once and the server need not check it again.\n visitor_id: uuid({ version: 'v7' }),\n session_id: uuid({ version: 'v7' }),\n platform: _enum(ALL_PLATFORMS),\n environment: _enum(ALL_ENVIRONMENTS),\n timestamp: iso.datetime(),\n tags: tagsSchema,\n properties: propertiesSchema,\n })\n ).check(minLength(1), maxLength(100)),\n transform((events) => alignClock(events))\n);\n\n/**\n * `POST /visitors`, what clients before 11.0 create their visitor with; 11.0 generates the id\n * itself and the server creates the visitor from its first events (README, \"Visitors\").\n * Kept for servers that still serve older clients.\n */\nexport const createVisitorSchema = object({\n device_id: string().check(trim(), minLength(1), maxLength(36)),\n platform: _enum(ALL_PLATFORMS),\n environment: _enum(ALL_ENVIRONMENTS),\n tags: tagsSchema,\n});\n\nconst emailValue = pipe(string().check(trim(), toLowerCase(), maxLength(320)), email());\n\n/** E.164: a plus sign (+) prefix, country code, then digits only, no dashes/parens/spaces. */\nconst phoneValue = pipe(string().check(trim()), e164());\n\nconst addressValue = object({\n first_name: optional(string().check(trim(), maxLength(128))),\n last_name: optional(string().check(trim(), maxLength(128))),\n street: optional(string().check(trim(), maxLength(256))),\n city: optional(string().check(trim(), maxLength(128))),\n /** User province, state, or region. Example: `Hampshire` */\n region: optional(string().check(trim(), maxLength(128))),\n postal_code: optional(string().check(trim(), maxLength(32))),\n /** 2-letter country code, per the ISO 3166-1 alpha-2 standard. Example: `UK` */\n country: optional(string().check(trim(), toUpperCase(), regex(/^[A-Z]{2}$/))),\n});\n\n/**\n * User-provided data (UPD) used for enhanced conversions, Customer Match, and demographics.\n * Values are sent unhashed; Google normalizes and hashes them before they reach its servers.\n *\n * Multiple values may be sent to increase the match rate: up to 3 emails, 3 phone numbers, and\n * 2 addresses.\n *\n * @see https://support.google.com/analytics/answer/14078702\n * @see https://support.google.com/google-ads/answer/13258081\n */\nexport const userProvidedDataSchema = object({\n email: optional(union([emailValue, array(emailValue).check(minLength(1), maxLength(3))])),\n phone_number: optional(union([phoneValue, array(phoneValue).check(minLength(1), maxLength(3))])),\n address: optional(union([addressValue, array(addressValue).check(minLength(1), maxLength(2))])),\n});\n\nexport const updateVisitorSchema = object({\n user_id: optional(uuid()),\n user_data: optional(userProvidedDataSchema),\n /**\n * Sent by clients before 11.1, which PATCHed their tags on every page load. From 11.1 the\n * server refreshes `visitor.tags` from each `session_start` — the moment the visit arrives —\n * and `identify` sends none: at sign-in the page is no longer where the visit came in.\n */\n tags: optional(tagsSchema),\n});\n\nexport const createFeedbackSchema = object({\n name: string().check(minLength(1), maxLength(256)),\n // Trimmed and lower-cased like every other email the SDK accepts, so a host stores the\n // normalized form without wrapping the schema.\n email: emailValue,\n message: string().check(minLength(1), maxLength(65536)),\n /**\n * The Cloudflare Turnstile token the host verifies before storing the feedback (the same field\n * `@shware/security`'s email-code request carries). Required: without it `POST /feedback` is an\n * open free-text write that only a rate limit protects. Single-use: Turnstile spends the token\n * at verification, so the caller resets the widget after every submit, success or failure.\n */\n turnstileToken: string().check(minLength(1), maxLength(2048)),\n});\n\nconst noEmptyString = pipe(\n string().check(maxLength(256)),\n transform((v) => (v ? v : undefined))\n);\n\n/**\n * The schema for creating a link.\n * @see https://support.google.com/analytics/answer/10917952\n * */\nexport const createLinkSchema = object({\n /** The URL that the user is redirected to. */\n url: url().check(minLength(1), maxLength(1024)), // required\n\n /**\n * Campaign ID. Used to identify a specific campaign or promotion. This is a required key for GA4\n * data import. Use the same IDs that you use when uploading campaign cost data.\n */\n utm_id: optional(noEmptyString),\n\n /** Referrer, for example: google, newsletter4, billboard */\n utm_source: string().check(minLength(1), maxLength(256)), // required\n\n /** Marketing medium, for example: cpc, banner, email */\n utm_medium: string().check(minLength(1), maxLength(256)), // required\n\n /** Product, slogan, promo code, for example, spring_sale */\n utm_campaign: string().check(minLength(1), maxLength(256)), // required\n\n /** Paid keyword */\n utm_term: optional(noEmptyString),\n\n /**\n * Use to differentiate creatives. For example, if you have two call-to-action links within the\n * same email message, you can use utm_content and set different values for each so you can tell\n * which version is more effective.\n */\n utm_content: optional(noEmptyString),\n\n /**\n * The platform responsible for directing traffic to a given Analytics property (such as a buying\n * platform that sets budgets and targeting criteria or a platform that manages organic traffic\n * data). For example, Search Ads 360 or Display & Video 360.\n */\n utm_source_platform: optional(noEmptyString),\n\n /**\n * Type of creative, for example, display, native, video, search, utm_creative_format is not\n * currently reported in Google Analytics 4 properties.\n */\n utm_creative_format: optional(noEmptyString),\n\n /**\n * Targeting criteria applied to a campaign, for example, remarketing, prospecting,\n * utm_marketing_tactic is not currently reported in Google Analytics 4 properties.\n * */\n utm_marketing_tactic: optional(noEmptyString),\n});\n\nexport type CreateTrackEventDTO = z.output<typeof createTrackEventSchema>;\nexport type CreateFeedbackDTO = z.output<typeof createFeedbackSchema>;\nexport type CreateLinkDTO = z.output<typeof createLinkSchema>;\nexport type CreateVisitorDTO = z.output<typeof createVisitorSchema>;\nexport type UserProvidedDataDTO = z.output<typeof userProvidedDataSchema>;\nexport type UpdateVisitorDTO = z.output<typeof updateVisitorSchema>;\n"],"mappings":";;;AA4BA,MAAM,iBAAiB;AACvB,MAAM,mBAAmB;AACzB,MAAM,iBAAiB;;;;;;;AAQvB,MAAM,gBAAA,GAAeA,SAAAA,KAAAA,EAAAA,GACnBC,SAAAA,OAAAA,CAAO,IAAA,GACPC,SAAAA,UAAAA,EAAW,UAAU,MAAM,MAAM,GAAG,gBAAgB,CAAC,CACvD;;;;;;;;;AAUA,MAAM,iBAAiB;AAEvB,MAAM,WAAA,GAAUF,SAAAA,KAAAA,EAAAA,GACdC,SAAAA,OAAAA,CAAO,IAAA,GACPC,SAAAA,UAAAA,EAAW,UAAU,MAAM,MAAM,GAAG,cAAc,CAAC,CACrD;;;;;;;;;;;AAYA,SAAS,eAAkB,MAA4C;CACrE,MAAM,SAA4B,CAAC;CACnC,IAAI,QAAQ;CACZ,KAAK,MAAM,CAAC,QAAQ,UAAU,OAAO,QAAQ,IAAI,GAAG;EAClD,IAAI,SAAS,gBAAgB;EAC7B,MAAM,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index.cjs","names":["pipe","string","transform","array","record","union","number","boolean","_null","object","optional","trim","minLength","maxLength","regex","uuid","_enum","iso","toLowerCase","email","e164","toUpperCase","url"],"sources":["../../src/schema/index.ts"],"sourcesContent":["import {\n enum as _enum,\n null as _null,\n array,\n boolean,\n e164,\n email,\n iso,\n maxLength,\n minLength,\n number,\n object,\n optional,\n pipe,\n record,\n regex,\n string,\n toLowerCase,\n toUpperCase,\n transform,\n trim,\n union,\n url,\n uuid,\n type z,\n} from 'zod/mini';\nimport type { Environment, Platform } from '../track/types';\n\nconst MAX_KEY_LENGTH = 128;\nconst MAX_VALUE_LENGTH = 512;\nconst MAX_PROPERTIES = 64;\n\n/**\n * Truncated rather than rejected. These schemas validate a whole batch at once, so refusing one\n * oversized value costs every event that traveled with it — and the values that overrun are the\n * ones derived from the page (a link's text, a URL carrying a long query), which no client can\n * bound in advance. A shortened value is worth more than a lost batch.\n */\nconst propertyText = pipe(\n string(),\n transform((value) => value.slice(0, MAX_VALUE_LENGTH))\n);\n\n/**\n * Tags are truncated for the same reason property values are, and they are stored more than once\n * (on the event, the session and the visitor), so an unbounded one costs several times over.\n * 1024 sits just above what GA4 itself keeps (1000 characters of page_location, 420 of\n * page_referrer, 300 of page_title). Real tags stay under ~500 characters; the rare longer ones\n * are page_referrer values from search and ad redirect URLs, where the kept prefix — host and\n * path — is the part that matters.\n */\nconst MAX_TAG_LENGTH = 1024;\n\nconst tagText = pipe(\n string(),\n transform((value) => value.slice(0, MAX_TAG_LENGTH))\n);\n\n/**\n * Keys are written by hand in instrumentation code, so an unusable one is a mistake in the host\n * rather than something the visitor typed. It is still dropped rather than rejected, for the same\n * reason: the mistake should cost that property, not the batch it happens to be in. Truncating a\n * key is not an option — two long keys would silently become one field.\n *\n * The key schema below is deliberately permissive so that this transform is reached at all; the\n * trimming it used to do happens here instead. `MAX_PROPERTIES` keeps the first N in insertion\n * order.\n */\nfunction takeProperties<T>(data: Record<string, T>): Record<string, T> {\n const result: Record<string, T> = {};\n let count = 0;\n for (const [rawKey, value] of Object.entries(data)) {\n if (count >= MAX_PROPERTIES) break;\n const key = rawKey.trim();\n if (!key || key.length > MAX_KEY_LENGTH) continue;\n result[key] = value;\n count++;\n }\n return result;\n}\n\n/**\n * Capped at GA4's own item-list limit, and truncated rather than rejected like every other\n * property limit here: an unbounded array is the one field a caller could still blow a batch\n * up with after the value and key limits.\n */\nconst MAX_ITEMS = 200;\n\nconst items = pipe(\n array(\n pipe(\n record(string(), union([propertyText, number(), boolean(), _null()])),\n transform(takeProperties)\n )\n ),\n transform((list) => list.slice(0, MAX_ITEMS))\n);\n\nexport const ALL_PLATFORMS = [\n 'ios',\n 'android',\n 'web',\n 'macos',\n 'windows',\n 'linux',\n 'unknown',\n] as const satisfies Platform[];\n\nexport const ALL_ENVIRONMENTS = ['development', 'production'] as const satisfies Environment[];\n\nexport const tagsSchema = object({\n os: optional(tagText),\n os_name: optional(tagText),\n os_version: optional(tagText),\n browser: optional(tagText),\n browser_name: optional(tagText),\n browser_version: optional(tagText),\n device: optional(tagText),\n device_id: optional(string().check(trim(), minLength(1), maxLength(36))),\n device_type: optional(tagText),\n device_vendor: optional(tagText),\n device_pixel_ratio: optional(number()),\n screen_width: optional(number()),\n screen_height: optional(number()),\n screen_resolution: optional(\n pipe(\n string().check(regex(/^\\d+x\\d+$/)),\n transform((v) => v as `${number}x${number}`)\n )\n ),\n webdriver: optional(boolean()),\n release: optional(tagText),\n language: optional(tagText),\n time_zone: optional(tagText),\n page_location: optional(tagText),\n page_referrer: optional(tagText),\n page_title: optional(tagText),\n page_load_id: optional(tagText),\n /**\n * @deprecated Renamed to `page_location` in 7.0.0. Accepted so that events from clients\n * still on an older SDK are not stripped of their page URL at this boundary — a browser\n * bundle stays cached long after a backend deploys. Remove once those clients are gone;\n * `pageLocation` in `server/page-location.ts` is the only reader.\n */\n // oxlint-disable-next-line typescript/no-deprecated -- Legacy input from pre-7.0 clients must survive validation.\n source_url: optional(tagText),\n // app info\n advertising_id: optional(tagText),\n install_referrer: optional(tagText),\n // Ad click ids (URL parameters) and ad platform cookies (underscore names); see AdvertisingInfo.\n // Meta Ads\n fbclid: optional(tagText),\n ad_id: optional(tagText),\n ad_name: optional(tagText),\n adset_id: optional(tagText),\n adset_name: optional(tagText),\n campaign_id: optional(tagText),\n campaign_name: optional(tagText),\n placement: optional(tagText),\n _fbc: optional(tagText),\n _fbp: optional(tagText),\n /**\n * @deprecated `fbc` / `fbp` / `rdt_uuid` were renamed to `_fbc` / `_fbp` / `_rdt_uuid` in 9.0.0.\n * Accepted so that conversions from clients still on an older SDK keep their match keys; the\n * senders read them only as a fallback (`server/click-ids.ts`). Remove once those clients are\n * gone.\n */\n // oxlint-disable-next-line typescript/no-deprecated -- Legacy pre-9.0 click-id fields must survive validation.\n fbc: optional(tagText),\n fbp: optional(tagText),\n rdt_uuid: optional(tagText),\n // Google Ads\n gclid: optional(tagText),\n gclsrc: optional(tagText),\n gad_source: optional(tagText),\n gad_campaignid: optional(tagText),\n network: optional(tagText),\n match_type: optional(tagText),\n wbraid: optional(tagText),\n gbraid: optional(tagText),\n dclid: optional(tagText),\n _gcl_aw: optional(tagText),\n _gcl_gb: optional(tagText),\n // Microsoft Ads\n msclkid: optional(tagText),\n _uetmsclkid: optional(tagText),\n // Reddit Ads\n rdt_cid: optional(tagText),\n _rdt_cid: optional(tagText),\n _rdt_uuid: optional(tagText),\n // LinkedIn Ads\n li_fat_id: optional(tagText),\n _li_fat_id: optional(tagText),\n // OpenAI Ads\n oppref: optional(tagText),\n __oppref: optional(tagText),\n __obref: optional(tagText),\n // other click ids\n ko_click_id: optional(tagText),\n ScCid: optional(tagText),\n ttclid: optional(tagText),\n twclid: optional(tagText),\n yclid: optional(tagText),\n epik: optional(tagText),\n // utm params\n utm_source: optional(tagText),\n utm_medium: optional(tagText),\n utm_campaign: optional(tagText),\n utm_term: optional(tagText),\n utm_content: optional(tagText),\n utm_id: optional(tagText),\n utm_source_platform: optional(tagText),\n utm_creative_format: optional(tagText),\n utm_marketing_tactic: optional(tagText),\n});\n\nexport const propertiesSchema = optional(\n pipe(\n record(string(), union([propertyText, number(), boolean(), _null(), items])),\n transform(takeProperties)\n )\n);\n\n/**\n * How far behind the server's an event's time may be before the client clock it was stamped with\n * is taken as wrong. A batch legitimately arrives late — a tab frozen in the background, a\n * session_start held back after a failed batch — by hours, not days; a phone set to another year\n * writes its sessions into that year. Ahead of the server's is wrong by any amount: an event\n * cannot have happened after it arrived, and a clock a few minutes fast is common enough that the\n * conversions APIs, which reject a future event, turned its events away by the hundred.\n */\nconst MAX_CLOCK_SKEW = 24 * 60 * 60 * 1000;\n\n/**\n * Puts the events stamped by a wrong client clock onto the server's, where they are parsed. Only\n * the events ahead of the server, or further behind it than `MAX_CLOCK_SKEW`, move, so one bad\n * event cannot drag the rest of its batch along: they move together by their own latest one — the\n * wrong clock at sending — keeping their order and spacing, and one still out after that (a batch mixing two wrong clocks) is on no clock\n * at all and takes the server's time. Corrected rather than rejected, for the same reason values\n * are truncated: a wrong clock should cost the event its time, not the batch its events.\n */\nfunction alignClock<T extends { timestamp: string }>(events: T[], now = Date.now()): T[] {\n const within = (time: number) => time <= now && now - time <= MAX_CLOCK_SKEW;\n const times = events.map((event) => Date.parse(event.timestamp));\n const wrong = times.filter((time) => !within(time));\n if (wrong.length === 0) return events;\n const offset = now - Math.max(...wrong);\n return events.map((event, i) => {\n if (within(times[i])) return event;\n const shifted = times[i] + offset;\n return { ...event, timestamp: new Date(within(shifted) ? shifted : now).toISOString() };\n });\n}\n\nexport const createTrackEventSchema = pipe(\n array(\n object({\n /**\n * The event's id, generated by the client when the event was tracked (12.1) and given to\n * the browser pixels as their deduplication id. Store the event under it with\n * `on conflict (id) do nothing`: a batch retried after the server committed it then\n * stores nothing twice. Optional for clients before 12.1, which send none — generate one\n * on the server for those.\n */\n id: optional(uuid({ version: 'v7' })),\n name: string().check(trim(), minLength(1), maxLength(64)),\n // Generated by the SDK, like `id` (`visitorId()`, `Session`): uuidv7 as well, so the\n // constraint is checked here once and the server need not check it again.\n visitor_id: uuid({ version: 'v7' }),\n session_id: uuid({ version: 'v7' }),\n platform: _enum(ALL_PLATFORMS),\n environment: _enum(ALL_ENVIRONMENTS),\n timestamp: iso.datetime(),\n tags: tagsSchema,\n properties: propertiesSchema,\n })\n ).check(minLength(1), maxLength(100)),\n transform((events) => alignClock(events))\n);\n\n/**\n * `POST /visitors`, what clients before 11.0 create their visitor with; 11.0 generates the id\n * itself and the server creates the visitor from its first events (README, \"Visitors\").\n * Kept for servers that still serve older clients.\n */\nexport const createVisitorSchema = object({\n device_id: string().check(trim(), minLength(1), maxLength(36)),\n platform: _enum(ALL_PLATFORMS),\n environment: _enum(ALL_ENVIRONMENTS),\n tags: tagsSchema,\n});\n\nconst emailValue = pipe(string().check(trim(), toLowerCase(), maxLength(320)), email());\n\n/** E.164: a plus sign (+) prefix, country code, then digits only, no dashes/parens/spaces. */\nconst phoneValue = pipe(string().check(trim()), e164());\n\nconst addressValue = object({\n first_name: optional(string().check(trim(), maxLength(128))),\n last_name: optional(string().check(trim(), maxLength(128))),\n street: optional(string().check(trim(), maxLength(256))),\n city: optional(string().check(trim(), maxLength(128))),\n /** User province, state, or region. Example: `Hampshire` */\n region: optional(string().check(trim(), maxLength(128))),\n postal_code: optional(string().check(trim(), maxLength(32))),\n /** 2-letter country code, per the ISO 3166-1 alpha-2 standard. Example: `UK` */\n country: optional(string().check(trim(), toUpperCase(), regex(/^[A-Z]{2}$/))),\n});\n\n/**\n * User-provided data (UPD) used for enhanced conversions, Customer Match, and demographics.\n * Values are sent unhashed; Google normalizes and hashes them before they reach its servers.\n *\n * Multiple values may be sent to increase the match rate: up to 3 emails, 3 phone numbers, and\n * 2 addresses.\n *\n * @see https://support.google.com/analytics/answer/14078702\n * @see https://support.google.com/google-ads/answer/13258081\n */\nexport const userProvidedDataSchema = object({\n email: optional(union([emailValue, array(emailValue).check(minLength(1), maxLength(3))])),\n phone_number: optional(union([phoneValue, array(phoneValue).check(minLength(1), maxLength(3))])),\n address: optional(union([addressValue, array(addressValue).check(minLength(1), maxLength(2))])),\n});\n\nexport const updateVisitorSchema = object({\n user_id: optional(uuid()),\n user_data: optional(userProvidedDataSchema),\n /**\n * Sent by clients before 11.1, which PATCHed their tags on every page load. From 11.1 the\n * server refreshes `visitor.tags` from each `session_start` — the moment the visit arrives —\n * and `identify` sends none: at sign-in the page is no longer where the visit came in.\n */\n tags: optional(tagsSchema),\n});\n\nexport const createFeedbackSchema = object({\n name: string().check(minLength(1), maxLength(256)),\n // Trimmed and lower-cased like every other email the SDK accepts, so a host stores the\n // normalized form without wrapping the schema.\n email: emailValue,\n message: string().check(minLength(1), maxLength(65536)),\n /**\n * The Cloudflare Turnstile token the host verifies before storing the feedback (the same field\n * `@shware/security`'s email-code request carries). Required: without it `POST /feedback` is an\n * open free-text write that only a rate limit protects. Single-use: Turnstile spends the token\n * at verification, so the caller resets the widget after every submit, success or failure.\n */\n turnstileToken: string().check(minLength(1), maxLength(2048)),\n});\n\nconst noEmptyString = pipe(\n string().check(maxLength(256)),\n transform((v) => (v ? v : undefined))\n);\n\n/**\n * The schema for creating a link.\n * @see https://support.google.com/analytics/answer/10917952\n * */\nexport const createLinkSchema = object({\n /** The URL that the user is redirected to. */\n url: url().check(minLength(1), maxLength(1024)), // required\n\n /**\n * Campaign ID. Used to identify a specific campaign or promotion. This is a required key for GA4\n * data import. Use the same IDs that you use when uploading campaign cost data.\n */\n utm_id: optional(noEmptyString),\n\n /** Referrer, for example: google, newsletter4, billboard */\n utm_source: string().check(minLength(1), maxLength(256)), // required\n\n /** Marketing medium, for example: cpc, banner, email */\n utm_medium: string().check(minLength(1), maxLength(256)), // required\n\n /** Product, slogan, promo code, for example, spring_sale */\n utm_campaign: string().check(minLength(1), maxLength(256)), // required\n\n /** Paid keyword */\n utm_term: optional(noEmptyString),\n\n /**\n * Use to differentiate creatives. For example, if you have two call-to-action links within the\n * same email message, you can use utm_content and set different values for each so you can tell\n * which version is more effective.\n */\n utm_content: optional(noEmptyString),\n\n /**\n * The platform responsible for directing traffic to a given Analytics property (such as a buying\n * platform that sets budgets and targeting criteria or a platform that manages organic traffic\n * data). For example, Search Ads 360 or Display & Video 360.\n */\n utm_source_platform: optional(noEmptyString),\n\n /**\n * Type of creative, for example, display, native, video, search, utm_creative_format is not\n * currently reported in Google Analytics 4 properties.\n */\n utm_creative_format: optional(noEmptyString),\n\n /**\n * Targeting criteria applied to a campaign, for example, remarketing, prospecting,\n * utm_marketing_tactic is not currently reported in Google Analytics 4 properties.\n * */\n utm_marketing_tactic: optional(noEmptyString),\n});\n\nexport type CreateTrackEventDTO = z.output<typeof createTrackEventSchema>;\nexport type CreateFeedbackDTO = z.output<typeof createFeedbackSchema>;\nexport type CreateLinkDTO = z.output<typeof createLinkSchema>;\nexport type CreateVisitorDTO = z.output<typeof createVisitorSchema>;\nexport type UserProvidedDataDTO = z.output<typeof userProvidedDataSchema>;\nexport type UpdateVisitorDTO = z.output<typeof updateVisitorSchema>;\n"],"mappings":";;;AA4BA,MAAM,iBAAiB;AACvB,MAAM,mBAAmB;AACzB,MAAM,iBAAiB;;;;;;;AAQvB,MAAM,gBAAA,GAAeA,SAAAA,KAAAA,EAAAA,GACnBC,SAAAA,OAAAA,CAAO,IAAA,GACPC,SAAAA,UAAAA,EAAW,UAAU,MAAM,MAAM,GAAG,gBAAgB,CAAC,CACvD;;;;;;;;;AAUA,MAAM,iBAAiB;AAEvB,MAAM,WAAA,GAAUF,SAAAA,KAAAA,EAAAA,GACdC,SAAAA,OAAAA,CAAO,IAAA,GACPC,SAAAA,UAAAA,EAAW,UAAU,MAAM,MAAM,GAAG,cAAc,CAAC,CACrD;;;;;;;;;;;AAYA,SAAS,eAAkB,MAA4C;CACrE,MAAM,SAA4B,CAAC;CACnC,IAAI,QAAQ;CACZ,KAAK,MAAM,CAAC,QAAQ,UAAU,OAAO,QAAQ,IAAI,GAAG;EAClD,IAAI,SAAS,gBAAgB;EAC7B,MAAM,MAAM,OAAO,KAAK;EACxB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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAS9B,EAAA,KAAA;qBAEW,sBAAoB,EAAA;;;;;GAa/B,EAAA,KAAA;;;;;qBAWW,kBAAgB,EAAA;;;;;;;;;;;GA+C3B,EAAA,KAAA;YAEU,sBAAsB,EAAE,cAAc;YACtC,oBAAoB,EAAE,cAAc;YACpC,gBAAgB,EAAE,cAAc;YAChC,mBAAmB,EAAE,cAAc;YACnC,sBAAsB,EAAE,cAAc;YACtC,mBAAmB,EAAE,cAAc"}
@@ -160,22 +160,24 @@ const propertiesSchema = optional(pipe(record(string(), union([
160
160
  items
161
161
  ])), transform(takeProperties)));
162
162
  /**
163
- * How far an event's time may be from the server's before the client clock it was stamped with is
164
- * taken as wrong. A batch legitimately arrives late — a tab frozen in the background, a
163
+ * How far behind the server's an event's time may be before the client clock it was stamped with
164
+ * is taken as wrong. A batch legitimately arrives late — a tab frozen in the background, a
165
165
  * session_start held back after a failed batch — by hours, not days; a phone set to another year
166
- * writes its sessions into that year.
166
+ * writes its sessions into that year. Ahead of the server's is wrong by any amount: an event
167
+ * cannot have happened after it arrived, and a clock a few minutes fast is common enough that the
168
+ * conversions APIs, which reject a future event, turned its events away by the hundred.
167
169
  */
168
170
  const MAX_CLOCK_SKEW = 864e5;
169
171
  /**
170
172
  * Puts the events stamped by a wrong client clock onto the server's, where they are parsed. Only
171
- * the events outside `MAX_CLOCK_SKEW` move, so one bad event cannot drag the rest of its batch
172
- * along: they move together by their own latest one — the wrong clock at sending — keeping their
173
- * order and spacing, and one still out after that (a batch mixing two wrong clocks) is on no clock
173
+ * the events ahead of the server, or further behind it than `MAX_CLOCK_SKEW`, move, so one bad
174
+ * event cannot drag the rest of its batch along: they move together by their own latest one — the
175
+ * wrong clock at sending — keeping their order and spacing, and one still out after that (a batch mixing two wrong clocks) is on no clock
174
176
  * at all and takes the server's time. Corrected rather than rejected, for the same reason values
175
177
  * are truncated: a wrong clock should cost the event its time, not the batch its events.
176
178
  */
177
179
  function alignClock(events, now = Date.now()) {
178
- const within = (time) => Math.abs(now - time) <= MAX_CLOCK_SKEW;
180
+ const within = (time) => time <= now && now - time <= MAX_CLOCK_SKEW;
179
181
  const times = events.map((event) => Date.parse(event.timestamp));
180
182
  const wrong = times.filter((time) => !within(time));
181
183
  if (wrong.length === 0) return events;
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["_null","_enum"],"sources":["../../src/schema/index.ts"],"sourcesContent":["import {\n enum as _enum,\n null as _null,\n array,\n boolean,\n e164,\n email,\n iso,\n maxLength,\n minLength,\n number,\n object,\n optional,\n pipe,\n record,\n regex,\n string,\n toLowerCase,\n toUpperCase,\n transform,\n trim,\n union,\n url,\n uuid,\n type z,\n} from 'zod/mini';\nimport type { Environment, Platform } from '../track/types';\n\nconst MAX_KEY_LENGTH = 128;\nconst MAX_VALUE_LENGTH = 512;\nconst MAX_PROPERTIES = 64;\n\n/**\n * Truncated rather than rejected. These schemas validate a whole batch at once, so refusing one\n * oversized value costs every event that traveled with it — and the values that overrun are the\n * ones derived from the page (a link's text, a URL carrying a long query), which no client can\n * bound in advance. A shortened value is worth more than a lost batch.\n */\nconst propertyText = pipe(\n string(),\n transform((value) => value.slice(0, MAX_VALUE_LENGTH))\n);\n\n/**\n * Tags are truncated for the same reason property values are, and they are stored more than once\n * (on the event, the session and the visitor), so an unbounded one costs several times over.\n * 1024 sits just above what GA4 itself keeps (1000 characters of page_location, 420 of\n * page_referrer, 300 of page_title). Real tags stay under ~500 characters; the rare longer ones\n * are page_referrer values from search and ad redirect URLs, where the kept prefix — host and\n * path — is the part that matters.\n */\nconst MAX_TAG_LENGTH = 1024;\n\nconst tagText = pipe(\n string(),\n transform((value) => value.slice(0, MAX_TAG_LENGTH))\n);\n\n/**\n * Keys are written by hand in instrumentation code, so an unusable one is a mistake in the host\n * rather than something the visitor typed. It is still dropped rather than rejected, for the same\n * reason: the mistake should cost that property, not the batch it happens to be in. Truncating a\n * key is not an option — two long keys would silently become one field.\n *\n * The key schema below is deliberately permissive so that this transform is reached at all; the\n * trimming it used to do happens here instead. `MAX_PROPERTIES` keeps the first N in insertion\n * order.\n */\nfunction takeProperties<T>(data: Record<string, T>): Record<string, T> {\n const result: Record<string, T> = {};\n let count = 0;\n for (const [rawKey, value] of Object.entries(data)) {\n if (count >= MAX_PROPERTIES) break;\n const key = rawKey.trim();\n if (!key || key.length > MAX_KEY_LENGTH) continue;\n result[key] = value;\n count++;\n }\n return result;\n}\n\n/**\n * Capped at GA4's own item-list limit, and truncated rather than rejected like every other\n * property limit here: an unbounded array is the one field a caller could still blow a batch\n * up with after the value and key limits.\n */\nconst MAX_ITEMS = 200;\n\nconst items = pipe(\n array(\n pipe(\n record(string(), union([propertyText, number(), boolean(), _null()])),\n transform(takeProperties)\n )\n ),\n transform((list) => list.slice(0, MAX_ITEMS))\n);\n\nexport const ALL_PLATFORMS = [\n 'ios',\n 'android',\n 'web',\n 'macos',\n 'windows',\n 'linux',\n 'unknown',\n] as const satisfies Platform[];\n\nexport const ALL_ENVIRONMENTS = ['development', 'production'] as const satisfies Environment[];\n\nexport const tagsSchema = object({\n os: optional(tagText),\n os_name: optional(tagText),\n os_version: optional(tagText),\n browser: optional(tagText),\n browser_name: optional(tagText),\n browser_version: optional(tagText),\n device: optional(tagText),\n device_id: optional(string().check(trim(), minLength(1), maxLength(36))),\n device_type: optional(tagText),\n device_vendor: optional(tagText),\n device_pixel_ratio: optional(number()),\n screen_width: optional(number()),\n screen_height: optional(number()),\n screen_resolution: optional(\n pipe(\n string().check(regex(/^\\d+x\\d+$/)),\n transform((v) => v as `${number}x${number}`)\n )\n ),\n webdriver: optional(boolean()),\n release: optional(tagText),\n language: optional(tagText),\n time_zone: optional(tagText),\n page_location: optional(tagText),\n page_referrer: optional(tagText),\n page_title: optional(tagText),\n page_load_id: optional(tagText),\n /**\n * @deprecated Renamed to `page_location` in 7.0.0. Accepted so that events from clients\n * still on an older SDK are not stripped of their page URL at this boundary — a browser\n * bundle stays cached long after a backend deploys. Remove once those clients are gone;\n * `pageLocation` in `server/page-location.ts` is the only reader.\n */\n // oxlint-disable-next-line typescript/no-deprecated -- Legacy input from pre-7.0 clients must survive validation.\n source_url: optional(tagText),\n // app info\n advertising_id: optional(tagText),\n install_referrer: optional(tagText),\n // Ad click ids (URL parameters) and ad platform cookies (underscore names); see AdvertisingInfo.\n // Meta Ads\n fbclid: optional(tagText),\n ad_id: optional(tagText),\n ad_name: optional(tagText),\n adset_id: optional(tagText),\n adset_name: optional(tagText),\n campaign_id: optional(tagText),\n campaign_name: optional(tagText),\n placement: optional(tagText),\n _fbc: optional(tagText),\n _fbp: optional(tagText),\n /**\n * @deprecated `fbc` / `fbp` / `rdt_uuid` were renamed to `_fbc` / `_fbp` / `_rdt_uuid` in 9.0.0.\n * Accepted so that conversions from clients still on an older SDK keep their match keys; the\n * senders read them only as a fallback (`server/click-ids.ts`). Remove once those clients are\n * gone.\n */\n // oxlint-disable-next-line typescript/no-deprecated -- Legacy pre-9.0 click-id fields must survive validation.\n fbc: optional(tagText),\n fbp: optional(tagText),\n rdt_uuid: optional(tagText),\n // Google Ads\n gclid: optional(tagText),\n gclsrc: optional(tagText),\n gad_source: optional(tagText),\n gad_campaignid: optional(tagText),\n network: optional(tagText),\n match_type: optional(tagText),\n wbraid: optional(tagText),\n gbraid: optional(tagText),\n dclid: optional(tagText),\n _gcl_aw: optional(tagText),\n _gcl_gb: optional(tagText),\n // Microsoft Ads\n msclkid: optional(tagText),\n _uetmsclkid: optional(tagText),\n // Reddit Ads\n rdt_cid: optional(tagText),\n _rdt_cid: optional(tagText),\n _rdt_uuid: optional(tagText),\n // LinkedIn Ads\n li_fat_id: optional(tagText),\n _li_fat_id: optional(tagText),\n // OpenAI Ads\n oppref: optional(tagText),\n __oppref: optional(tagText),\n __obref: optional(tagText),\n // other click ids\n ko_click_id: optional(tagText),\n ScCid: optional(tagText),\n ttclid: optional(tagText),\n twclid: optional(tagText),\n yclid: optional(tagText),\n epik: optional(tagText),\n // utm params\n utm_source: optional(tagText),\n utm_medium: optional(tagText),\n utm_campaign: optional(tagText),\n utm_term: optional(tagText),\n utm_content: optional(tagText),\n utm_id: optional(tagText),\n utm_source_platform: optional(tagText),\n utm_creative_format: optional(tagText),\n utm_marketing_tactic: optional(tagText),\n});\n\nexport const propertiesSchema = optional(\n pipe(\n record(string(), union([propertyText, number(), boolean(), _null(), items])),\n transform(takeProperties)\n )\n);\n\n/**\n * How far an event's time may be from the server's before the client clock it was stamped with is\n * taken as wrong. A batch legitimately arrives late — a tab frozen in the background, a\n * session_start held back after a failed batch — by hours, not days; a phone set to another year\n * writes its sessions into that year.\n */\nconst MAX_CLOCK_SKEW = 24 * 60 * 60 * 1000;\n\n/**\n * Puts the events stamped by a wrong client clock onto the server's, where they are parsed. Only\n * the events outside `MAX_CLOCK_SKEW` move, so one bad event cannot drag the rest of its batch\n * along: they move together by their own latest one — the wrong clock at sending — keeping their\n * order and spacing, and one still out after that (a batch mixing two wrong clocks) is on no clock\n * at all and takes the server's time. Corrected rather than rejected, for the same reason values\n * are truncated: a wrong clock should cost the event its time, not the batch its events.\n */\nfunction alignClock<T extends { timestamp: string }>(events: T[], now = Date.now()): T[] {\n const within = (time: number) => Math.abs(now - time) <= MAX_CLOCK_SKEW;\n const times = events.map((event) => Date.parse(event.timestamp));\n const wrong = times.filter((time) => !within(time));\n if (wrong.length === 0) return events;\n const offset = now - Math.max(...wrong);\n return events.map((event, i) => {\n if (within(times[i])) return event;\n const shifted = times[i] + offset;\n return { ...event, timestamp: new Date(within(shifted) ? shifted : now).toISOString() };\n });\n}\n\nexport const createTrackEventSchema = pipe(\n array(\n object({\n /**\n * The event's id, generated by the client when the event was tracked (12.1) and given to\n * the browser pixels as their deduplication id. Store the event under it with\n * `on conflict (id) do nothing`: a batch retried after the server committed it then\n * stores nothing twice. Optional for clients before 12.1, which send none — generate one\n * on the server for those.\n */\n id: optional(uuid({ version: 'v7' })),\n name: string().check(trim(), minLength(1), maxLength(64)),\n // Generated by the SDK, like `id` (`visitorId()`, `Session`): uuidv7 as well, so the\n // constraint is checked here once and the server need not check it again.\n visitor_id: uuid({ version: 'v7' }),\n session_id: uuid({ version: 'v7' }),\n platform: _enum(ALL_PLATFORMS),\n environment: _enum(ALL_ENVIRONMENTS),\n timestamp: iso.datetime(),\n tags: tagsSchema,\n properties: propertiesSchema,\n })\n ).check(minLength(1), maxLength(100)),\n transform((events) => alignClock(events))\n);\n\n/**\n * `POST /visitors`, what clients before 11.0 create their visitor with; 11.0 generates the id\n * itself and the server creates the visitor from its first events (README, \"Visitors\").\n * Kept for servers that still serve older clients.\n */\nexport const createVisitorSchema = object({\n device_id: string().check(trim(), minLength(1), maxLength(36)),\n platform: _enum(ALL_PLATFORMS),\n environment: _enum(ALL_ENVIRONMENTS),\n tags: tagsSchema,\n});\n\nconst emailValue = pipe(string().check(trim(), toLowerCase(), maxLength(320)), email());\n\n/** E.164: a plus sign (+) prefix, country code, then digits only, no dashes/parens/spaces. */\nconst phoneValue = pipe(string().check(trim()), e164());\n\nconst addressValue = object({\n first_name: optional(string().check(trim(), maxLength(128))),\n last_name: optional(string().check(trim(), maxLength(128))),\n street: optional(string().check(trim(), maxLength(256))),\n city: optional(string().check(trim(), maxLength(128))),\n /** User province, state, or region. Example: `Hampshire` */\n region: optional(string().check(trim(), maxLength(128))),\n postal_code: optional(string().check(trim(), maxLength(32))),\n /** 2-letter country code, per the ISO 3166-1 alpha-2 standard. Example: `UK` */\n country: optional(string().check(trim(), toUpperCase(), regex(/^[A-Z]{2}$/))),\n});\n\n/**\n * User-provided data (UPD) used for enhanced conversions, Customer Match, and demographics.\n * Values are sent unhashed; Google normalizes and hashes them before they reach its servers.\n *\n * Multiple values may be sent to increase the match rate: up to 3 emails, 3 phone numbers, and\n * 2 addresses.\n *\n * @see https://support.google.com/analytics/answer/14078702\n * @see https://support.google.com/google-ads/answer/13258081\n */\nexport const userProvidedDataSchema = object({\n email: optional(union([emailValue, array(emailValue).check(minLength(1), maxLength(3))])),\n phone_number: optional(union([phoneValue, array(phoneValue).check(minLength(1), maxLength(3))])),\n address: optional(union([addressValue, array(addressValue).check(minLength(1), maxLength(2))])),\n});\n\nexport const updateVisitorSchema = object({\n user_id: optional(uuid()),\n user_data: optional(userProvidedDataSchema),\n /**\n * Sent by clients before 11.1, which PATCHed their tags on every page load. From 11.1 the\n * server refreshes `visitor.tags` from each `session_start` — the moment the visit arrives —\n * and `identify` sends none: at sign-in the page is no longer where the visit came in.\n */\n tags: optional(tagsSchema),\n});\n\nexport const createFeedbackSchema = object({\n name: string().check(minLength(1), maxLength(256)),\n // Trimmed and lower-cased like every other email the SDK accepts, so a host stores the\n // normalized form without wrapping the schema.\n email: emailValue,\n message: string().check(minLength(1), maxLength(65536)),\n /**\n * The Cloudflare Turnstile token the host verifies before storing the feedback (the same field\n * `@shware/security`'s email-code request carries). Required: without it `POST /feedback` is an\n * open free-text write that only a rate limit protects. Single-use: Turnstile spends the token\n * at verification, so the caller resets the widget after every submit, success or failure.\n */\n turnstileToken: string().check(minLength(1), maxLength(2048)),\n});\n\nconst noEmptyString = pipe(\n string().check(maxLength(256)),\n transform((v) => (v ? v : undefined))\n);\n\n/**\n * The schema for creating a link.\n * @see https://support.google.com/analytics/answer/10917952\n * */\nexport const createLinkSchema = object({\n /** The URL that the user is redirected to. */\n url: url().check(minLength(1), maxLength(1024)), // required\n\n /**\n * Campaign ID. Used to identify a specific campaign or promotion. This is a required key for GA4\n * data import. Use the same IDs that you use when uploading campaign cost data.\n */\n utm_id: optional(noEmptyString),\n\n /** Referrer, for example: google, newsletter4, billboard */\n utm_source: string().check(minLength(1), maxLength(256)), // required\n\n /** Marketing medium, for example: cpc, banner, email */\n utm_medium: string().check(minLength(1), maxLength(256)), // required\n\n /** Product, slogan, promo code, for example, spring_sale */\n utm_campaign: string().check(minLength(1), maxLength(256)), // required\n\n /** Paid keyword */\n utm_term: optional(noEmptyString),\n\n /**\n * Use to differentiate creatives. For example, if you have two call-to-action links within the\n * same email message, you can use utm_content and set different values for each so you can tell\n * which version is more effective.\n */\n utm_content: optional(noEmptyString),\n\n /**\n * The platform responsible for directing traffic to a given Analytics property (such as a buying\n * platform that sets budgets and targeting criteria or a platform that manages organic traffic\n * data). For example, Search Ads 360 or Display & Video 360.\n */\n utm_source_platform: optional(noEmptyString),\n\n /**\n * Type of creative, for example, display, native, video, search, utm_creative_format is not\n * currently reported in Google Analytics 4 properties.\n */\n utm_creative_format: optional(noEmptyString),\n\n /**\n * Targeting criteria applied to a campaign, for example, remarketing, prospecting,\n * utm_marketing_tactic is not currently reported in Google Analytics 4 properties.\n * */\n utm_marketing_tactic: optional(noEmptyString),\n});\n\nexport type CreateTrackEventDTO = z.output<typeof createTrackEventSchema>;\nexport type CreateFeedbackDTO = z.output<typeof createFeedbackSchema>;\nexport type CreateLinkDTO = z.output<typeof createLinkSchema>;\nexport type CreateVisitorDTO = z.output<typeof createVisitorSchema>;\nexport type UserProvidedDataDTO = z.output<typeof userProvidedDataSchema>;\nexport type UpdateVisitorDTO = z.output<typeof updateVisitorSchema>;\n"],"mappings":";;AA4BA,MAAM,iBAAiB;AACvB,MAAM,mBAAmB;AACzB,MAAM,iBAAiB;;;;;;;AAQvB,MAAM,eAAe,KACnB,OAAO,GACP,WAAW,UAAU,MAAM,MAAM,GAAG,gBAAgB,CAAC,CACvD;;;;;;;;;AAUA,MAAM,iBAAiB;AAEvB,MAAM,UAAU,KACd,OAAO,GACP,WAAW,UAAU,MAAM,MAAM,GAAG,cAAc,CAAC,CACrD;;;;;;;;;;;AAYA,SAAS,eAAkB,MAA4C;CACrE,MAAM,SAA4B,CAAC;CACnC,IAAI,QAAQ;CACZ,KAAK,MAAM,CAAC,QAAQ,UAAU,OAAO,QAAQ,IAAI,GAAG;EAClD,IAAI,SAAS,gBAAgB;EAC7B,MAAM,MAAM,OAAO,KAAK;EACxB,IAAI,CAAC,OAAO,IAAI,SAAS,gBAAgB;EACzC,OAAO,OAAO;EACd;CACF;CACA,OAAO;AAC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.ts"],"sourcesContent":["import {\n enum as _enum,\n null as _null,\n array,\n boolean,\n e164,\n email,\n iso,\n maxLength,\n minLength,\n number,\n object,\n optional,\n pipe,\n record,\n regex,\n string,\n toLowerCase,\n toUpperCase,\n transform,\n trim,\n union,\n url,\n uuid,\n type z,\n} from 'zod/mini';\nimport type { Environment, Platform } from '../track/types';\n\nconst MAX_KEY_LENGTH = 128;\nconst MAX_VALUE_LENGTH = 512;\nconst MAX_PROPERTIES = 64;\n\n/**\n * Truncated rather than rejected. These schemas validate a whole batch at once, so refusing one\n * oversized value costs every event that traveled with it — and the values that overrun are the\n * ones derived from the page (a link's text, a URL carrying a long query), which no client can\n * bound in advance. A shortened value is worth more than a lost batch.\n */\nconst propertyText = pipe(\n string(),\n transform((value) => value.slice(0, MAX_VALUE_LENGTH))\n);\n\n/**\n * Tags are truncated for the same reason property values are, and they are stored more than once\n * (on the event, the session and the visitor), so an unbounded one costs several times over.\n * 1024 sits just above what GA4 itself keeps (1000 characters of page_location, 420 of\n * page_referrer, 300 of page_title). Real tags stay under ~500 characters; the rare longer ones\n * are page_referrer values from search and ad redirect URLs, where the kept prefix — host and\n * path — is the part that matters.\n */\nconst MAX_TAG_LENGTH = 1024;\n\nconst tagText = pipe(\n string(),\n transform((value) => value.slice(0, MAX_TAG_LENGTH))\n);\n\n/**\n * Keys are written by hand in instrumentation code, so an unusable one is a mistake in the host\n * rather than something the visitor typed. It is still dropped rather than rejected, for the same\n * reason: the mistake should cost that property, not the batch it happens to be in. Truncating a\n * key is not an option — two long keys would silently become one field.\n *\n * The key schema below is deliberately permissive so that this transform is reached at all; the\n * trimming it used to do happens here instead. `MAX_PROPERTIES` keeps the first N in insertion\n * order.\n */\nfunction takeProperties<T>(data: Record<string, T>): Record<string, T> {\n const result: Record<string, T> = {};\n let count = 0;\n for (const [rawKey, value] of Object.entries(data)) {\n if (count >= MAX_PROPERTIES) break;\n const key = rawKey.trim();\n if (!key || key.length > MAX_KEY_LENGTH) continue;\n result[key] = value;\n count++;\n }\n return result;\n}\n\n/**\n * Capped at GA4's own item-list limit, and truncated rather than rejected like every other\n * property limit here: an unbounded array is the one field a caller could still blow a batch\n * up with after the value and key limits.\n */\nconst MAX_ITEMS = 200;\n\nconst items = pipe(\n array(\n pipe(\n record(string(), union([propertyText, number(), boolean(), _null()])),\n transform(takeProperties)\n )\n ),\n transform((list) => list.slice(0, MAX_ITEMS))\n);\n\nexport const ALL_PLATFORMS = [\n 'ios',\n 'android',\n 'web',\n 'macos',\n 'windows',\n 'linux',\n 'unknown',\n] as const satisfies Platform[];\n\nexport const ALL_ENVIRONMENTS = ['development', 'production'] as const satisfies Environment[];\n\nexport const tagsSchema = object({\n os: optional(tagText),\n os_name: optional(tagText),\n os_version: optional(tagText),\n browser: optional(tagText),\n browser_name: optional(tagText),\n browser_version: optional(tagText),\n device: optional(tagText),\n device_id: optional(string().check(trim(), minLength(1), maxLength(36))),\n device_type: optional(tagText),\n device_vendor: optional(tagText),\n device_pixel_ratio: optional(number()),\n screen_width: optional(number()),\n screen_height: optional(number()),\n screen_resolution: optional(\n pipe(\n string().check(regex(/^\\d+x\\d+$/)),\n transform((v) => v as `${number}x${number}`)\n )\n ),\n webdriver: optional(boolean()),\n release: optional(tagText),\n language: optional(tagText),\n time_zone: optional(tagText),\n page_location: optional(tagText),\n page_referrer: optional(tagText),\n page_title: optional(tagText),\n page_load_id: optional(tagText),\n /**\n * @deprecated Renamed to `page_location` in 7.0.0. Accepted so that events from clients\n * still on an older SDK are not stripped of their page URL at this boundary — a browser\n * bundle stays cached long after a backend deploys. Remove once those clients are gone;\n * `pageLocation` in `server/page-location.ts` is the only reader.\n */\n // oxlint-disable-next-line typescript/no-deprecated -- Legacy input from pre-7.0 clients must survive validation.\n source_url: optional(tagText),\n // app info\n advertising_id: optional(tagText),\n install_referrer: optional(tagText),\n // Ad click ids (URL parameters) and ad platform cookies (underscore names); see AdvertisingInfo.\n // Meta Ads\n fbclid: optional(tagText),\n ad_id: optional(tagText),\n ad_name: optional(tagText),\n adset_id: optional(tagText),\n adset_name: optional(tagText),\n campaign_id: optional(tagText),\n campaign_name: optional(tagText),\n placement: optional(tagText),\n _fbc: optional(tagText),\n _fbp: optional(tagText),\n /**\n * @deprecated `fbc` / `fbp` / `rdt_uuid` were renamed to `_fbc` / `_fbp` / `_rdt_uuid` in 9.0.0.\n * Accepted so that conversions from clients still on an older SDK keep their match keys; the\n * senders read them only as a fallback (`server/click-ids.ts`). Remove once those clients are\n * gone.\n */\n // oxlint-disable-next-line typescript/no-deprecated -- Legacy pre-9.0 click-id fields must survive validation.\n fbc: optional(tagText),\n fbp: optional(tagText),\n rdt_uuid: optional(tagText),\n // Google Ads\n gclid: optional(tagText),\n gclsrc: optional(tagText),\n gad_source: optional(tagText),\n gad_campaignid: optional(tagText),\n network: optional(tagText),\n match_type: optional(tagText),\n wbraid: optional(tagText),\n gbraid: optional(tagText),\n dclid: optional(tagText),\n _gcl_aw: optional(tagText),\n _gcl_gb: optional(tagText),\n // Microsoft Ads\n msclkid: optional(tagText),\n _uetmsclkid: optional(tagText),\n // Reddit Ads\n rdt_cid: optional(tagText),\n _rdt_cid: optional(tagText),\n _rdt_uuid: optional(tagText),\n // LinkedIn Ads\n li_fat_id: optional(tagText),\n _li_fat_id: optional(tagText),\n // OpenAI Ads\n oppref: optional(tagText),\n __oppref: optional(tagText),\n __obref: optional(tagText),\n // other click ids\n ko_click_id: optional(tagText),\n ScCid: optional(tagText),\n ttclid: optional(tagText),\n twclid: optional(tagText),\n yclid: optional(tagText),\n epik: optional(tagText),\n // utm params\n utm_source: optional(tagText),\n utm_medium: optional(tagText),\n utm_campaign: optional(tagText),\n utm_term: optional(tagText),\n utm_content: optional(tagText),\n utm_id: optional(tagText),\n utm_source_platform: optional(tagText),\n utm_creative_format: optional(tagText),\n utm_marketing_tactic: optional(tagText),\n});\n\nexport const propertiesSchema = optional(\n pipe(\n record(string(), union([propertyText, number(), boolean(), _null(), items])),\n transform(takeProperties)\n )\n);\n\n/**\n * How far behind the server's an event's time may be before the client clock it was stamped with\n * is taken as wrong. A batch legitimately arrives late — a tab frozen in the background, a\n * session_start held back after a failed batch — by hours, not days; a phone set to another year\n * writes its sessions into that year. Ahead of the server's is wrong by any amount: an event\n * cannot have happened after it arrived, and a clock a few minutes fast is common enough that the\n * conversions APIs, which reject a future event, turned its events away by the hundred.\n */\nconst MAX_CLOCK_SKEW = 24 * 60 * 60 * 1000;\n\n/**\n * Puts the events stamped by a wrong client clock onto the server's, where they are parsed. Only\n * the events ahead of the server, or further behind it than `MAX_CLOCK_SKEW`, move, so one bad\n * event cannot drag the rest of its batch along: they move together by their own latest one — the\n * wrong clock at sending — keeping their order and spacing, and one still out after that (a batch mixing two wrong clocks) is on no clock\n * at all and takes the server's time. Corrected rather than rejected, for the same reason values\n * are truncated: a wrong clock should cost the event its time, not the batch its events.\n */\nfunction alignClock<T extends { timestamp: string }>(events: T[], now = Date.now()): T[] {\n const within = (time: number) => time <= now && now - time <= MAX_CLOCK_SKEW;\n const times = events.map((event) => Date.parse(event.timestamp));\n const wrong = times.filter((time) => !within(time));\n if (wrong.length === 0) return events;\n const offset = now - Math.max(...wrong);\n return events.map((event, i) => {\n if (within(times[i])) return event;\n const shifted = times[i] + offset;\n return { ...event, timestamp: new Date(within(shifted) ? shifted : now).toISOString() };\n });\n}\n\nexport const createTrackEventSchema = pipe(\n array(\n object({\n /**\n * The event's id, generated by the client when the event was tracked (12.1) and given to\n * the browser pixels as their deduplication id. Store the event under it with\n * `on conflict (id) do nothing`: a batch retried after the server committed it then\n * stores nothing twice. Optional for clients before 12.1, which send none — generate one\n * on the server for those.\n */\n id: optional(uuid({ version: 'v7' })),\n name: string().check(trim(), minLength(1), maxLength(64)),\n // Generated by the SDK, like `id` (`visitorId()`, `Session`): uuidv7 as well, so the\n // constraint is checked here once and the server need not check it again.\n visitor_id: uuid({ version: 'v7' }),\n session_id: uuid({ version: 'v7' }),\n platform: _enum(ALL_PLATFORMS),\n environment: _enum(ALL_ENVIRONMENTS),\n timestamp: iso.datetime(),\n tags: tagsSchema,\n properties: propertiesSchema,\n })\n ).check(minLength(1), maxLength(100)),\n transform((events) => alignClock(events))\n);\n\n/**\n * `POST /visitors`, what clients before 11.0 create their visitor with; 11.0 generates the id\n * itself and the server creates the visitor from its first events (README, \"Visitors\").\n * Kept for servers that still serve older clients.\n */\nexport const createVisitorSchema = object({\n device_id: string().check(trim(), minLength(1), maxLength(36)),\n platform: _enum(ALL_PLATFORMS),\n environment: _enum(ALL_ENVIRONMENTS),\n tags: tagsSchema,\n});\n\nconst emailValue = pipe(string().check(trim(), toLowerCase(), maxLength(320)), email());\n\n/** E.164: a plus sign (+) prefix, country code, then digits only, no dashes/parens/spaces. */\nconst phoneValue = pipe(string().check(trim()), e164());\n\nconst addressValue = object({\n first_name: optional(string().check(trim(), maxLength(128))),\n last_name: optional(string().check(trim(), maxLength(128))),\n street: optional(string().check(trim(), maxLength(256))),\n city: optional(string().check(trim(), maxLength(128))),\n /** User province, state, or region. Example: `Hampshire` */\n region: optional(string().check(trim(), maxLength(128))),\n postal_code: optional(string().check(trim(), maxLength(32))),\n /** 2-letter country code, per the ISO 3166-1 alpha-2 standard. Example: `UK` */\n country: optional(string().check(trim(), toUpperCase(), regex(/^[A-Z]{2}$/))),\n});\n\n/**\n * User-provided data (UPD) used for enhanced conversions, Customer Match, and demographics.\n * Values are sent unhashed; Google normalizes and hashes them before they reach its servers.\n *\n * Multiple values may be sent to increase the match rate: up to 3 emails, 3 phone numbers, and\n * 2 addresses.\n *\n * @see https://support.google.com/analytics/answer/14078702\n * @see https://support.google.com/google-ads/answer/13258081\n */\nexport const userProvidedDataSchema = object({\n email: optional(union([emailValue, array(emailValue).check(minLength(1), maxLength(3))])),\n phone_number: optional(union([phoneValue, array(phoneValue).check(minLength(1), maxLength(3))])),\n address: optional(union([addressValue, array(addressValue).check(minLength(1), maxLength(2))])),\n});\n\nexport const updateVisitorSchema = object({\n user_id: optional(uuid()),\n user_data: optional(userProvidedDataSchema),\n /**\n * Sent by clients before 11.1, which PATCHed their tags on every page load. From 11.1 the\n * server refreshes `visitor.tags` from each `session_start` — the moment the visit arrives —\n * and `identify` sends none: at sign-in the page is no longer where the visit came in.\n */\n tags: optional(tagsSchema),\n});\n\nexport const createFeedbackSchema = object({\n name: string().check(minLength(1), maxLength(256)),\n // Trimmed and lower-cased like every other email the SDK accepts, so a host stores the\n // normalized form without wrapping the schema.\n email: emailValue,\n message: string().check(minLength(1), maxLength(65536)),\n /**\n * The Cloudflare Turnstile token the host verifies before storing the feedback (the same field\n * `@shware/security`'s email-code request carries). Required: without it `POST /feedback` is an\n * open free-text write that only a rate limit protects. Single-use: Turnstile spends the token\n * at verification, so the caller resets the widget after every submit, success or failure.\n */\n turnstileToken: string().check(minLength(1), maxLength(2048)),\n});\n\nconst noEmptyString = pipe(\n string().check(maxLength(256)),\n transform((v) => (v ? v : undefined))\n);\n\n/**\n * The schema for creating a link.\n * @see https://support.google.com/analytics/answer/10917952\n * */\nexport const createLinkSchema = object({\n /** The URL that the user is redirected to. */\n url: url().check(minLength(1), maxLength(1024)), // required\n\n /**\n * Campaign ID. Used to identify a specific campaign or promotion. This is a required key for GA4\n * data import. Use the same IDs that you use when uploading campaign cost data.\n */\n utm_id: optional(noEmptyString),\n\n /** Referrer, for example: google, newsletter4, billboard */\n utm_source: string().check(minLength(1), maxLength(256)), // required\n\n /** Marketing medium, for example: cpc, banner, email */\n utm_medium: string().check(minLength(1), maxLength(256)), // required\n\n /** Product, slogan, promo code, for example, spring_sale */\n utm_campaign: string().check(minLength(1), maxLength(256)), // required\n\n /** Paid keyword */\n utm_term: optional(noEmptyString),\n\n /**\n * Use to differentiate creatives. For example, if you have two call-to-action links within the\n * same email message, you can use utm_content and set different values for each so you can tell\n * which version is more effective.\n */\n utm_content: optional(noEmptyString),\n\n /**\n * The platform responsible for directing traffic to a given Analytics property (such as a buying\n * platform that sets budgets and targeting criteria or a platform that manages organic traffic\n * data). For example, Search Ads 360 or Display & Video 360.\n */\n utm_source_platform: optional(noEmptyString),\n\n /**\n * Type of creative, for example, display, native, video, search, utm_creative_format is not\n * currently reported in Google Analytics 4 properties.\n */\n utm_creative_format: optional(noEmptyString),\n\n /**\n * Targeting criteria applied to a campaign, for example, remarketing, prospecting,\n * utm_marketing_tactic is not currently reported in Google Analytics 4 properties.\n * */\n utm_marketing_tactic: optional(noEmptyString),\n});\n\nexport type CreateTrackEventDTO = z.output<typeof createTrackEventSchema>;\nexport type CreateFeedbackDTO = z.output<typeof createFeedbackSchema>;\nexport type CreateLinkDTO = z.output<typeof createLinkSchema>;\nexport type CreateVisitorDTO = z.output<typeof createVisitorSchema>;\nexport type UserProvidedDataDTO = z.output<typeof userProvidedDataSchema>;\nexport type UpdateVisitorDTO = z.output<typeof updateVisitorSchema>;\n"],"mappings":";;AA4BA,MAAM,iBAAiB;AACvB,MAAM,mBAAmB;AACzB,MAAM,iBAAiB;;;;;;;AAQvB,MAAM,eAAe,KACnB,OAAO,GACP,WAAW,UAAU,MAAM,MAAM,GAAG,gBAAgB,CAAC,CACvD;;;;;;;;;AAUA,MAAM,iBAAiB;AAEvB,MAAM,UAAU,KACd,OAAO,GACP,WAAW,UAAU,MAAM,MAAM,GAAG,cAAc,CAAC,CACrD;;;;;;;;;;;AAYA,SAAS,eAAkB,MAA4C;CACrE,MAAM,SAA4B,CAAC;CACnC,IAAI,QAAQ;CACZ,KAAK,MAAM,CAAC,QAAQ,UAAU,OAAO,QAAQ,IAAI,GAAG;EAClD,IAAI,SAAS,gBAAgB;EAC7B,MAAM,MAAM,OAAO,KAAK;EACxB,IAAI,CAAC,OAAO,IAAI,SAAS,gBAAgB;EACzC,OAAO,OAAO;EACd;CACF;CACA,OAAO;AACT;;;;;;AAOA,MAAM,YAAY;AAElB,MAAM,QAAQ,KACZ,MACE,KACE,OAAO,OAAO,GAAG,MAAM;CAAC;CAAc,OAAO;CAAG,QAAQ;CAAGA,OAAM;AAAC,CAAC,CAAC,GACpE,UAAU,cAAc,CAC1B,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K,CAAC;CACxB,WAAW,SAAS,sBAAsB;;;;;;CAM1C,MAAM,SAAS,UAAU;AAC3B,CAAC;AAED,MAAa,uBAAuB,OAAO;CACzC,MAAM,OAAO,CAAC,CAAC,MAAM,UAAU,CAAC,GAAG,UAAU,GAAG,CAAC;CAGjD,OAAO;CACP,SAAS,OAAO,CAAC,CAAC,MAAM,UAAU,CAAC,GAAG,UAAU,KAAK,CAAC;;;;;;;CAOtD,gBAAgB,OAAO,CAAC,CAAC,MAAM,UAAU,CAAC,GAAG,UAAU,IAAI,CAAC;AAC9D,CAAC;AAED,MAAM,gBAAgB,KACpB,OAAO,CAAC,CAAC,MAAM,UAAU,GAAG,CAAC,GAC7B,WAAW,MAAO,IAAI,IAAI,KAAA,CAAU,CACtC;;;;;AAMA,MAAa,mBAAmB,OAAO;;CAErC,KAAK,IAAI,CAAC,CAAC,MAAM,UAAU,CAAC,GAAG,UAAU,IAAI,CAAC;;;;;CAM9C,QAAQ,SAAS,aAAa;;CAG9B,YAAY,OAAO,CAAC,CAAC,MAAM,UAAU,CAAC,GAAG,UAAU,GAAG,CAAC;;CAGvD,YAAY,OAAO,CAAC,CAAC,MAAM,UAAU,CAAC,GAAG,UAAU,GAAG,CAAC;;CAGvD,cAAc,OAAO,CAAC,CAAC,MAAM,UAAU,CAAC,GAAG,UAAU,GAAG,CAAC;;CAGzD,UAAU,SAAS,aAAa;;;;;;CAOhC,aAAa,SAAS,aAAa;;;;;;CAOnC,qBAAqB,SAAS,aAAa;;;;;CAM3C,qBAAqB,SAAS,aAAa;;;;;CAM3C,sBAAsB,SAAS,aAAa;AAC9C,CAAC"}
@@ -0,0 +1,14 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ // src/server/event-time.ts
3
+ /**
4
+ * When an event happened, as a conversions API is told: its stored time, but never later than
5
+ * now. Microsoft, Reddit and Meta reject an event stamped in the future, and fail the whole
6
+ * request with it; a browser clock running a few minutes fast stamps exactly that, and an event
7
+ * cannot have happened after the moment it is sent.
8
+ */
9
+ function eventTimeMs(createdAt) {
10
+ return Math.min(Date.parse(createdAt), Date.now());
11
+ }
12
+ exports.eventTimeMs = eventTimeMs;
13
+
14
+ //# sourceMappingURL=event-time.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"event-time.cjs","names":[],"sources":["../../src/server/event-time.ts"],"sourcesContent":["/**\n * When an event happened, as a conversions API is told: its stored time, but never later than\n * now. Microsoft, Reddit and Meta reject an event stamped in the future, and fail the whole\n * request with it; a browser clock running a few minutes fast stamps exactly that, and an event\n * cannot have happened after the moment it is sent.\n */\nexport function eventTimeMs(createdAt: string): number {\n return Math.min(Date.parse(createdAt), Date.now());\n}\n"],"mappings":";;;;;;;;AAMA,SAAgB,YAAY,WAA2B;CACrD,OAAO,KAAK,IAAI,KAAK,MAAM,SAAS,GAAG,KAAK,IAAI,CAAC;AACnD"}
@@ -0,0 +1,8 @@
1
+ /**
2
+ * When an event happened, as a conversions API is told: its stored time, but never later than
3
+ * now. Microsoft, Reddit and Meta reject an event stamped in the future, and fail the whole
4
+ * request with it; a browser clock running a few minutes fast stamps exactly that, and an event
5
+ * cannot have happened after the moment it is sent.
6
+ */
7
+ export declare function eventTimeMs(createdAt: string): number;
8
+ //# sourceMappingURL=event-time.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"event-time.d.cts","names":[],"sources":["../../src/server/event-time.ts"],"mappings":";;;;;;wBAMgB,YAAY"}
@@ -0,0 +1,8 @@
1
+ /**
2
+ * When an event happened, as a conversions API is told: its stored time, but never later than
3
+ * now. Microsoft, Reddit and Meta reject an event stamped in the future, and fail the whole
4
+ * request with it; a browser clock running a few minutes fast stamps exactly that, and an event
5
+ * cannot have happened after the moment it is sent.
6
+ */
7
+ export declare function eventTimeMs(createdAt: string): number;
8
+ //# sourceMappingURL=event-time.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"event-time.d.mts","names":[],"sources":["../../src/server/event-time.ts"],"mappings":";;;;;;wBAMgB,YAAY"}
@@ -0,0 +1,13 @@
1
+ // src/server/event-time.ts
2
+ /**
3
+ * When an event happened, as a conversions API is told: its stored time, but never later than
4
+ * now. Microsoft, Reddit and Meta reject an event stamped in the future, and fail the whole
5
+ * request with it; a browser clock running a few minutes fast stamps exactly that, and an event
6
+ * cannot have happened after the moment it is sent.
7
+ */
8
+ function eventTimeMs(createdAt) {
9
+ return Math.min(Date.parse(createdAt), Date.now());
10
+ }
11
+ export { eventTimeMs };
12
+
13
+ //# sourceMappingURL=event-time.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"event-time.mjs","names":[],"sources":["../../src/server/event-time.ts"],"sourcesContent":["/**\n * When an event happened, as a conversions API is told: its stored time, but never later than\n * now. Microsoft, Reddit and Meta reject an event stamped in the future, and fail the whole\n * request with it; a browser clock running a few minutes fast stamps exactly that, and an event\n * cannot have happened after the moment it is sent.\n */\nexport function eventTimeMs(createdAt: string): number {\n return Math.min(Date.parse(createdAt), Date.now());\n}\n"],"mappings":";;;;;;;AAMA,SAAgB,YAAY,WAA2B;CACrD,OAAO,KAAK,IAAI,KAAK,MAAM,SAAS,GAAG,KAAK,IAAI,CAAC;AACnD"}
@@ -5,6 +5,7 @@ const require_track_fbq = require("../track/fbq.cjs");
5
5
  const require_server_action_source = require("./action-source.cjs");
6
6
  const require_server_click_ids = require("./click-ids.cjs");
7
7
  const require_server_conversions_api_error = require("./conversions-api-error.cjs");
8
+ const require_server_event_time = require("./event-time.cjs");
8
9
  const require_server_setup_conversions = require("./setup-conversions.cjs");
9
10
  const require_server_page_location = require("./page-location.cjs");
10
11
  let _shware_utils = require("@shware/utils");
@@ -219,7 +220,7 @@ function getAppData(tags, appPackageName, version) {
219
220
  * sender put an explicit `'offline'` too.
220
221
  */
221
222
  function getCapiEvent(event, data, appPackageName) {
222
- const eventTimeMs = new Date(event.created_at).getTime();
223
+ const eventTime = require_server_event_time.eventTimeMs(event.created_at);
223
224
  const [_, eventName] = require_track_fbq.mapFBEvent(event.name, event.properties);
224
225
  const source = require_server_action_source.resolveActionSource(event.platform);
225
226
  const version = metaExtinfoVersion(event.tags);
@@ -229,10 +230,10 @@ function getCapiEvent(event, data, appPackageName) {
229
230
  } : void 0;
230
231
  const capiEvent = {
231
232
  event_name: eventName,
232
- event_time: Math.round(eventTimeMs / 1e3),
233
+ event_time: Math.round(eventTime / 1e3),
233
234
  event_id: event.tags.idempotency_key ?? event.id,
234
235
  action_source: app ? "app" : source === "web" ? "website" : "other",
235
- user_data: getUserData(event.tags, data, eventTimeMs),
236
+ user_data: getUserData(event.tags, data, eventTime),
236
237
  custom_data: getCustomData(event)
237
238
  };
238
239
  if (app) capiEvent.app_data = getAppData(event.tags, app.packageName, app.version);
@@ -1 +1 @@
1
- {"version":3,"file":"meta-capi.cjs","names":["ParamBuilder","createHash","PII_DATA_TYPE","metaFbc","metaFbp","mapFBEvent","resolveActionSource","pageLocation","IGNORED_EVENTS","fetch","ConversionsApiError","conversionDestination","adEvents","isStandardFBEvent"],"sources":["../../src/server/meta-capi.ts"],"sourcesContent":["/**\n * Meta Conversions API sender built on `capi-param-builder-nodejs` and plain `fetch`, which\n * replaced the sender built on the 31MB `facebook-nodejs-business-sdk`, since removed, with\n * ~0.5MB of parameter building.\n *\n * The wire payload is byte-identical to what the business SDK's `ServerEvent.normalize()`\n * produces — enforced by a differential test that runs both builders over the same events.\n * Where the two libraries normalize differently (the business SDK keeps punctuation in names,\n * spaces in multi-word last names, accents in cities; the param builder strips them per the\n * current documented rules), this module follows the business SDK so that switching senders\n * cannot change a single hash Meta receives. The param builder is used where the two provably\n * agree — email, phone, gender, country — and its adoption-tracking appendix (`<hash>.<token>`)\n * is stripped for the same reason.\n *\n * Two deliberate behavior differences from the business SDK, both on invalid input only:\n * an invalid field (malformed email, non-ISO country, letters in a phone) is dropped from\n * user_data instead of throwing inside `execute()` and costing the whole batch; an invalid\n * currency is uppercased and forwarded instead of rejected. Valid input is unaffected.\n *\n * https://developers.facebook.com/docs/marketing-api/conversions-api/using-the-api\n * https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/customer-information-parameters\n */\nimport { createHash } from 'node:crypto';\nimport { fetch } from '@shware/utils';\nimport { PII_DATA_TYPE, ParamBuilder } from 'capi-param-builder-nodejs';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { adEvents } from '../third-parties/integration';\nimport type { MetaAdsOptions } from '../third-parties/meta-pixel';\nimport { isStandardFBEvent, mapFBEvent } from '../track/fbq';\nimport type { TrackEvent, TrackTags, UserProvidedData } from '../track/types';\nimport { resolveActionSource } from './action-source';\nimport { metaFbc, metaFbp } from './click-ids';\nimport { ConversionsApiError } from './conversions-api-error';\nimport { pageLocation } from './page-location';\nimport { type ConversionDestination, conversionDestination } from './setup-conversions';\n\n/** Matches the Graph API version the pinned business SDK speaks (`FacebookAdsApi.VERSION`). */\nconst API_VERSION = 'v24.0';\n\nconst USER_ASSIGNED_COUNTRIES: string[] = ['xk'];\nfunction normalizeCountry(input: string | undefined): string | undefined {\n const country = input?.split(/[-_]/).at(0)?.toLowerCase();\n if (!country) return undefined;\n return USER_ASSIGNED_COUNTRIES.includes(country) ? undefined : country;\n}\n\n/**\n * Lazy for the same reason as the session and the token bucket (see setup/session.ts):\n * Cloudflare Workers refuse some work in module scope, and nothing here is per-request state.\n */\nlet paramBuilder: ParamBuilder | undefined;\n\n/**\n * Normalize and hash one PII value through the param builder, stripped to the bare SHA-256 the\n * business SDK sends: the builder appends a `.<language-token>` adoption marker that Meta's\n * endpoint tolerates but the business SDK never produced. Pre-hashed input passes through, as\n * it does in the business SDK.\n */\nfunction pii(value: string | undefined, dataType: string): string | undefined {\n if (!value) return undefined;\n const built = (paramBuilder ??= new ParamBuilder()).getNormalizedAndHashedPII(value, dataType);\n return built?.split('.').at(0) ?? undefined;\n}\n\nconst SHA256_OR_MD5 = /^[a-f0-9]{64}$|^[a-f0-9]{32}$/;\n\n/**\n * The business SDK's `normalizeAndHash` for the fields where the param builder normalizes\n * differently (names, city, state, zip): trim + lowercase, pass a pre-hashed value through,\n * apply the field rule, SHA-256. Field rules are copied from `ServerSideUtils` verbatim so the\n * differential test can hold the outputs equal.\n */\nfunction hashed(\n input: string | undefined,\n rule: (lowered: string) => string | undefined\n): string | undefined {\n if (!input) return undefined;\n const lowered = input.trim().toLowerCase();\n if (!lowered) return undefined;\n if (SHA256_OR_MD5.test(lowered)) return lowered;\n const normalized = rule(lowered);\n if (normalized === undefined) return undefined;\n return createHash('sha256').update(normalized).digest('hex');\n}\n\nconst nameRule = (v: string) => v;\nconst f5Rule = (v: string) => (v.length <= 5 ? v : v.slice(0, 5));\nconst cityStateRule = (v: string) => v.replace(/[0-9\\s().-]/g, '');\nconst zipRule = (v: string) => {\n const zip = v.replace(/\\s/g, '').split('-', 1)[0];\n return zip.length < 2 ? undefined : zip;\n};\n\n/**\n * Every multi-value field is deduplicated after hashing, order preserved — the SDK runs each\n * through `dedupArray` (a Set), `external_id` included.\n */\nconst dedupe = (hashes: (string | undefined)[]) =>\n Array.from(new Set(hashes.filter((hash): hash is string => hash !== undefined)));\n\nconst list = (hashes: (string | undefined)[]) => {\n const deduped = dedupe(hashes);\n return deduped.length > 0 ? deduped : undefined;\n};\n\ninterface CapiUserData {\n em?: string[];\n ph?: string[];\n ge?: string[];\n fn?: string[];\n ln?: string[];\n ct?: string[];\n st?: string[];\n zp?: string[];\n country?: string[];\n external_id?: string[];\n client_ip_address?: string;\n client_user_agent?: string;\n fbc?: string;\n fbp?: string;\n fb_login_id?: string;\n page_id?: string;\n f5first?: string;\n f5last?: string;\n dobd?: string;\n dobm?: string;\n doby?: string;\n madid?: string;\n}\n\nfunction getUserData(tags: TrackTags, data: UserProvidedData, eventTimeMs: number): CapiUserData {\n const userData: CapiUserData = {};\n\n if (data.email) {\n const emails = Array.isArray(data.email) ? data.email : [data.email];\n userData.em = list(emails.map((email) => pii(email, PII_DATA_TYPE.EMAIL)));\n }\n if (data.phone_number) {\n const phones = Array.isArray(data.phone_number) ? data.phone_number : [data.phone_number];\n userData.ph = list(phones.map((phone) => pii(phone, PII_DATA_TYPE.PHONE)));\n }\n if (data.gender === 'female' || data.gender === 'male') {\n userData.ge = list([pii(data.gender === 'female' ? 'f' : 'm', PII_DATA_TYPE.GENDER)]);\n }\n if (data.address) {\n if (Array.isArray(data.address)) {\n // The SDK sets these lists unconditionally in the multi-address branch, so an all-empty\n // column still goes out as `[]` — kept for byte-equality with the current sender.\n userData.fn = dedupe(data.address.map((a) => hashed(a.first_name, nameRule)));\n userData.ln = dedupe(data.address.map((a) => hashed(a.last_name, nameRule)));\n userData.ct = dedupe(data.address.map((a) => hashed(a.city, cityStateRule)));\n userData.st = dedupe(data.address.map((a) => hashed(a.region, cityStateRule)));\n userData.zp = dedupe(data.address.map((a) => hashed(a.postal_code, zipRule)));\n userData.country = dedupe(\n data.address.map((a) => pii(normalizeCountry(a.country), PII_DATA_TYPE.COUNTRY))\n );\n } else {\n userData.fn = list([hashed(data.address.first_name, nameRule)]);\n userData.ln = list([hashed(data.address.last_name, nameRule)]);\n userData.ct = list([hashed(data.address.city, cityStateRule)]);\n userData.st = list([hashed(data.address.region, cityStateRule)]);\n userData.zp = list([hashed(data.address.postal_code, zipRule)]);\n userData.country = list([pii(normalizeCountry(data.address.country), PII_DATA_TYPE.COUNTRY)]);\n // The 5-character prefixes, exactly as the current sender builds them: sliced first, then\n // normalized. Only the single-address branch sets them, as before.\n userData.f5first = hashed(data.address.first_name?.slice(0, 5), f5Rule);\n userData.f5last = hashed(data.address.last_name?.slice(0, 5), f5Rule);\n }\n }\n if (data.birthday) {\n const { year, month, day } = data.birthday;\n if (/^\\d{4}$/.test(year.toString())) {\n userData.doby = createHash('sha256').update(year.toString()).digest('hex');\n }\n if (month >= 1 && month <= 12) {\n userData.dobm = createHash('sha256').update(month.toString().padStart(2, '0')).digest('hex');\n }\n if (day >= 1 && day <= 31) {\n userData.dobd = createHash('sha256').update(day.toString().padStart(2, '0')).digest('hex');\n }\n }\n if (data.user_id && data.user_id.length !== 0) {\n // Unhashed, as the business SDK sends it. Meta documents hashing as recommended, not\n // required; changing it here would break continuity with every event sent so far.\n userData.external_id = [data.user_id];\n }\n if (data.ip_address) {\n userData.client_ip_address = data.ip_address;\n }\n if (data.user_agent) {\n userData.client_user_agent = data.user_agent;\n }\n if (data.fb_login_id) {\n userData.fb_login_id = data.fb_login_id;\n }\n if (data.fb_page_id) {\n userData.page_id = data.fb_page_id;\n }\n\n const fbc = metaFbc(tags, eventTimeMs);\n if (fbc) {\n userData.fbc = fbc;\n }\n const fbp = metaFbp(tags);\n if (fbp) {\n userData.fbp = fbp;\n }\n if (tags.advertising_id) {\n userData.madid = tags.advertising_id;\n }\n if (tags.ip_address && typeof tags.ip_address === 'string') {\n userData.client_ip_address = tags.ip_address;\n }\n\n return userData;\n}\n\nconst DELIVERY_CATEGORIES = ['in_store', 'curbside', 'home_delivery'];\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getCustomData({ name, properties }: TrackEvent<any>): Record<string, unknown> {\n const [_, _name, fbEventProperties] = mapFBEvent(name, properties);\n const {\n value,\n currency,\n content_name,\n content_category,\n content_ids,\n contents,\n content_type,\n predicted_ltv,\n num_items,\n search_string,\n status,\n delivery_category,\n ...custom_properties\n } = fbEventProperties;\n\n const customData: Record<string, unknown> = {};\n // oxlint-disable-next-line typescript/no-unnecessary-condition -- custom event properties may carry `value: null` at runtime despite the declared type\n if (value !== undefined && value !== null && Number.isFinite(Number.parseFloat(String(value)))) {\n customData.value = Number.parseFloat(String(value));\n }\n if (currency) {\n // The business SDK also validates against the ISO 4217 list and throws; here an unknown\n // code is forwarded uppercased rather than costing the batch.\n customData.currency = currency\n .trim()\n .toUpperCase()\n .replace(/[^A-Z]/g, '');\n }\n if (content_name) customData.content_name = content_name;\n if (content_category) customData.content_category = content_category;\n if (content_ids) customData.content_ids = content_ids;\n if (contents) {\n customData.contents = contents.map((c) => {\n const content: Record<string, unknown> = {};\n if (c.id) content.id = c.id;\n if (c.quantity) content.quantity = c.quantity;\n if (c.item_price) content.item_price = c.item_price;\n if (c.title) content.title = c.title;\n if (c.description) content.description = c.description;\n if (c.brand) content.brand = c.brand;\n if (c.category) content.category = c.category;\n const delivery = c.delivery_category?.trim().toLowerCase();\n if (delivery && DELIVERY_CATEGORIES.includes(delivery)) content.delivery_category = delivery;\n return content;\n });\n }\n if (content_type) customData.content_type = content_type;\n if (predicted_ltv) customData.predicted_ltv = predicted_ltv;\n if (num_items) customData.num_items = num_items;\n if (search_string) customData.search_string = search_string;\n if (status) customData.status = status.toString();\n const delivery = delivery_category?.trim().toLowerCase();\n if (delivery && DELIVERY_CATEGORIES.includes(delivery)) customData.delivery_category = delivery;\n\n return { ...customData, ...custom_properties };\n}\n\n/**\n * `extinfo` is keyed by field index. The business SDK builds the same object and leaves unset\n * indexes out when it serializes; the documented 16-element array is what the Graph endpoint\n * decodes this into. Indexes: 0 version, 1 package, 2 short version, 3 long version, 4 OS\n * version, 5 device model, 6 locale, 9 screen width, 10 height, 11 density.\n */\n/**\n * The `extinfo` version of an app event's OS — `i2` for iOS, `a2` for Android, the only two Meta\n * documents. Undefined for any other OS (a desktop app): such an event cannot carry the\n * `app_data` an app event requires, and is sent as `other`.\n * https://developers.facebook.com/docs/marketing-api/conversions-api/app-events\n */\nexport function metaExtinfoVersion(tags: TrackTags): 'i2' | 'a2' | undefined {\n if (tags.os_name === 'iOS' || tags.os_name === 'iPadOS') return 'i2';\n if (tags.os_name === 'Android') return 'a2';\n return undefined;\n}\n\nfunction getAppData(\n tags: TrackTags,\n appPackageName: string,\n version: 'i2' | 'a2'\n): Record<string, unknown> {\n const extinfo: Record<number, string | number> = {};\n extinfo[0] = version;\n extinfo[1] = appPackageName;\n const shortVersion = tags.release?.split('.').at(0);\n if (shortVersion) extinfo[2] = shortVersion;\n if (tags.release) extinfo[3] = tags.release;\n if (tags.os_version) extinfo[4] = tags.os_version;\n if (tags.device_model_id) extinfo[5] = tags.device_model_id;\n if (tags.language) extinfo[6] = tags.language;\n if (tags.screen_width) extinfo[9] = tags.screen_width;\n if (tags.screen_height) extinfo[10] = tags.screen_height;\n if (tags.device_pixel_ratio) extinfo[11] = tags.device_pixel_ratio.toString();\n\n // Required on every app event. An advertising id is only readable once the user allowed\n // tracking (ATT on iOS, the ad id setting on Android), so its presence is the answer.\n const appData: Record<string, unknown> = {\n extinfo,\n advertiser_tracking_enabled: !!tags.advertising_id,\n };\n if (tags.install_referrer) appData.install_referrer = tags.install_referrer;\n return appData;\n}\n\n/** One entry of the `data` array POSTed to `/{pixel_id}/events`. */\nexport interface CapiEvent {\n event_name: string;\n event_time: number;\n event_id: string;\n event_source_url?: string;\n action_source: 'app' | 'website' | 'other';\n user_data: CapiUserData;\n custom_data: Record<string, unknown>;\n app_data?: Record<string, unknown>;\n}\n\n/**\n * `action_source` is derived from `event.platform` alone: an OS platform is an app, `web` is a\n * website, and everything else — including a backend-built offline conversion, which should\n * declare `platform: 'unknown'` — lands in Meta's `other`, exactly where the business-SDK\n * sender put an explicit `'offline'` too.\n */\nexport function getCapiEvent(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData,\n appPackageName?: string\n): CapiEvent {\n const eventTimeMs = new Date(event.created_at).getTime();\n const [_, eventName] = mapFBEvent(event.name, event.properties);\n const source = resolveActionSource(event.platform);\n const version = metaExtinfoVersion(event.tags);\n const app =\n source === 'app' && appPackageName && version\n ? { packageName: appPackageName, version }\n : undefined;\n\n const capiEvent: CapiEvent = {\n event_name: eventName,\n event_time: Math.round(eventTimeMs / 1000),\n event_id: event.tags.idempotency_key ?? event.id,\n // `action_source` is required; an offline conversion and an undeterminable platform both\n // land in Meta's catch-all, exactly as in the business-SDK sender. So does an app event that\n // cannot carry the `app_data` Meta requires of one: no package name, or a desktop OS.\n action_source: app ? 'app' : source === 'web' ? 'website' : 'other',\n user_data: getUserData(event.tags, data, eventTimeMs),\n custom_data: getCustomData(event),\n };\n if (app) {\n capiEvent.app_data = getAppData(event.tags, app.packageName, app.version);\n }\n const eventSourceUrl = pageLocation(event.tags);\n if (eventSourceUrl) {\n capiEvent.event_source_url = eventSourceUrl;\n }\n return capiEvent;\n}\n\nexport interface MetaConversionsOptions {\n /** Attaches `app_data`/extinfo to events whose platform resolves to an app. */\n appPackageName?: string;\n /** Routes the batch to Events Manager's Test Events tab instead of production. */\n testEventCode?: string;\n /** Graph API version, e.g. 'v24.0'. */\n apiVersion?: string;\n}\n\nexport interface MetaConversionsResponse {\n events_received?: number;\n messages?: string[];\n fbtrace_id?: string;\n}\n\n/**\n * An `event_time` over 7 days old fails the whole request — \"we return an error for the entire\n * request and process no events\" — so such an event is left out; a minute's margin for the trip.\n * https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/server-event\n */\nconst MAX_EVENT_AGE_MS = 7 * 24 * 60 * 60 * 1000 - 60 * 1000;\n\n/**\n * Sends the events to Meta's Conversions API. Rejects on a failed request — a\n * `ConversionsApiError`, or the fetch error — for the caller to handle. The token travels in the\n * JSON body, never in the URL, and is in neither error.\n */\nexport async function sendEvents(\n accessToken: string,\n pixelId: string,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n events: TrackEvent<any>[],\n data: UserProvidedData = {},\n options: MetaConversionsOptions = {}\n): Promise<MetaConversionsResponse | undefined> {\n const capiEvents = events\n .filter((event) => !IGNORED_EVENTS.includes(event.name))\n .filter((event) => Date.now() - Date.parse(event.created_at) <= MAX_EVENT_AGE_MS)\n .map((event) => getCapiEvent(event, data, options.appPackageName));\n if (capiEvents.length === 0) return undefined;\n // \"The client_user_agent is required for website events\" — sent from `data.user_agent`.\n if (!data.user_agent && capiEvents.some((event) => event.action_source === 'website')) {\n console.warn(\n 'Meta conversion: website events sent without client_user_agent (data.user_agent)'\n );\n }\n\n const version = options.apiVersion ?? API_VERSION;\n const response = await fetch(`https://graph.facebook.com/${version}/${pixelId}/events`, {\n method: 'POST',\n // Retried although a POST: the platform deduplicates on the `event_id` each event carries.\n retries: 3,\n headers: { 'Content-Type': 'application/json', Accept: 'application/json' },\n body: JSON.stringify({\n data: capiEvents,\n test_event_code: options.testEventCode,\n access_token: accessToken,\n }),\n });\n if (response.ok) return (await response.json()) as MetaConversionsResponse;\n throw new ConversionsApiError('meta', response.status, await response.text());\n}\n\n/**\n * Meta's Conversions API, sent the same events as `metaAds` in the browser: the ones Meta maps to\n * a standard event, and `customEvents`.\n */\nexport function metaConversions(\n options: MetaAdsOptions & MetaConversionsOptions & { accessToken: string }\n): ConversionDestination {\n return conversionDestination(adEvents(isStandardFBEvent, options.customEvents), (events, data) =>\n sendEvents(options.accessToken, options.pixelId, events, data, options)\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,MAAM,cAAc;AAEpB,MAAM,0BAAoC,CAAC,IAAI;AAC/C,SAAS,iBAAiB,OAA+C;CACvE,MAAM,UAAU,OAAO,MAAM,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,EAAE,YAAY;CACxD,IAAI,CAAC,SAAS,OAAO,KAAA;CACrB,OAAO,wBAAwB,SAAS,OAAO,IAAI,KAAA,IAAY;AACjE;;;;;AAMA,IAAI;;;;;;;AAQJ,SAAS,IAAI,OAA2B,UAAsC;CAC5E,IAAI,CAAC,OAAO,OAAO,KAAA;CAEnB,QADe,iBAAiB,IAAIA,0BAAAA,aAAa,EAAA,CAAG,0BAA0B,OAAO,QAC1E,CAAC,EAAE,MAAM,GAAG,CAAC,CAAC,GAAG,CAAC,KAAK,KAAA;AACpC;AAEA,MAAM,gBAAgB;;;;;;;AAQtB,SAAS,OACP,OACA,MACoB;CACpB,IAAI,CAAC,OAAO,OAAO,KAAA;CACnB,MAAM,UAAU,MAAM,KAAK,CAAC,CAAC,YAAY;CACzC,IAAI,CAAC,SAAS,OAAO,KAAA;CACrB,IAAI,cAAc,KAAK,OAAO,GAAG,OAAO;CACxC,MAAM,aAAa,KAAK,OAAO;CAC/B,IAAI,eAAe,KAAA,GAAW,OAAO,KA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AS,KAAK;CAC7C,MAAM,IAAIC,qCAAAA,oBAAoB,QAAQ,SAAS,QAAQ,MAAM,SAAS,KAAK,CAAC;AAC9E;;;;;AAMA,SAAgB,gBACd,SACuB;CACvB,OAAOC,iCAAAA,sBAAsBC,kCAAAA,SAASC,kBAAAA,mBAAmB,QAAQ,YAAY,IAAI,QAAQ,SACvF,WAAW,QAAQ,aAAa,QAAQ,SAAS,QAAQ,MAAM,OAAO,CACxE;AACF"}
1
+ {"version":3,"file":"meta-capi.cjs","names":["ParamBuilder","createHash","PII_DATA_TYPE","metaFbc","metaFbp","mapFBEvent","eventTimeMs","resolveActionSource","pageLocation","IGNORED_EVENTS","fetch","ConversionsApiError","conversionDestination","adEvents","isStandardFBEvent"],"sources":["../../src/server/meta-capi.ts"],"sourcesContent":["/**\n * Meta Conversions API sender built on `capi-param-builder-nodejs` and plain `fetch`, which\n * replaced the sender built on the 31MB `facebook-nodejs-business-sdk`, since removed, with\n * ~0.5MB of parameter building.\n *\n * The wire payload is byte-identical to what the business SDK's `ServerEvent.normalize()`\n * produces — enforced by a differential test that runs both builders over the same events.\n * Where the two libraries normalize differently (the business SDK keeps punctuation in names,\n * spaces in multi-word last names, accents in cities; the param builder strips them per the\n * current documented rules), this module follows the business SDK so that switching senders\n * cannot change a single hash Meta receives. The param builder is used where the two provably\n * agree — email, phone, gender, country — and its adoption-tracking appendix (`<hash>.<token>`)\n * is stripped for the same reason.\n *\n * Two deliberate behavior differences from the business SDK, both on invalid input only:\n * an invalid field (malformed email, non-ISO country, letters in a phone) is dropped from\n * user_data instead of throwing inside `execute()` and costing the whole batch; an invalid\n * currency is uppercased and forwarded instead of rejected. Valid input is unaffected.\n *\n * https://developers.facebook.com/docs/marketing-api/conversions-api/using-the-api\n * https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/customer-information-parameters\n */\nimport { createHash } from 'node:crypto';\nimport { fetch } from '@shware/utils';\nimport { PII_DATA_TYPE, ParamBuilder } from 'capi-param-builder-nodejs';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { adEvents } from '../third-parties/integration';\nimport type { MetaAdsOptions } from '../third-parties/meta-pixel';\nimport { isStandardFBEvent, mapFBEvent } from '../track/fbq';\nimport type { TrackEvent, TrackTags, UserProvidedData } from '../track/types';\nimport { resolveActionSource } from './action-source';\nimport { metaFbc, metaFbp } from './click-ids';\nimport { ConversionsApiError } from './conversions-api-error';\nimport { eventTimeMs } from './event-time';\nimport { pageLocation } from './page-location';\nimport { type ConversionDestination, conversionDestination } from './setup-conversions';\n\n/** Matches the Graph API version the pinned business SDK speaks (`FacebookAdsApi.VERSION`). */\nconst API_VERSION = 'v24.0';\n\nconst USER_ASSIGNED_COUNTRIES: string[] = ['xk'];\nfunction normalizeCountry(input: string | undefined): string | undefined {\n const country = input?.split(/[-_]/).at(0)?.toLowerCase();\n if (!country) return undefined;\n return USER_ASSIGNED_COUNTRIES.includes(country) ? undefined : country;\n}\n\n/**\n * Lazy for the same reason as the session and the token bucket (see setup/session.ts):\n * Cloudflare Workers refuse some work in module scope, and nothing here is per-request state.\n */\nlet paramBuilder: ParamBuilder | undefined;\n\n/**\n * Normalize and hash one PII value through the param builder, stripped to the bare SHA-256 the\n * business SDK sends: the builder appends a `.<language-token>` adoption marker that Meta's\n * endpoint tolerates but the business SDK never produced. Pre-hashed input passes through, as\n * it does in the business SDK.\n */\nfunction pii(value: string | undefined, dataType: string): string | undefined {\n if (!value) return undefined;\n const built = (paramBuilder ??= new ParamBuilder()).getNormalizedAndHashedPII(value, dataType);\n return built?.split('.').at(0) ?? undefined;\n}\n\nconst SHA256_OR_MD5 = /^[a-f0-9]{64}$|^[a-f0-9]{32}$/;\n\n/**\n * The business SDK's `normalizeAndHash` for the fields where the param builder normalizes\n * differently (names, city, state, zip): trim + lowercase, pass a pre-hashed value through,\n * apply the field rule, SHA-256. Field rules are copied from `ServerSideUtils` verbatim so the\n * differential test can hold the outputs equal.\n */\nfunction hashed(\n input: string | undefined,\n rule: (lowered: string) => string | undefined\n): string | undefined {\n if (!input) return undefined;\n const lowered = input.trim().toLowerCase();\n if (!lowered) return undefined;\n if (SHA256_OR_MD5.test(lowered)) return lowered;\n const normalized = rule(lowered);\n if (normalized === undefined) return undefined;\n return createHash('sha256').update(normalized).digest('hex');\n}\n\nconst nameRule = (v: string) => v;\nconst f5Rule = (v: string) => (v.length <= 5 ? v : v.slice(0, 5));\nconst cityStateRule = (v: string) => v.replace(/[0-9\\s().-]/g, '');\nconst zipRule = (v: string) => {\n const zip = v.replace(/\\s/g, '').split('-', 1)[0];\n return zip.length < 2 ? undefined : zip;\n};\n\n/**\n * Every multi-value field is deduplicated after hashing, order preserved — the SDK runs each\n * through `dedupArray` (a Set), `external_id` included.\n */\nconst dedupe = (hashes: (string | undefined)[]) =>\n Array.from(new Set(hashes.filter((hash): hash is string => hash !== undefined)));\n\nconst list = (hashes: (string | undefined)[]) => {\n const deduped = dedupe(hashes);\n return deduped.length > 0 ? deduped : undefined;\n};\n\ninterface CapiUserData {\n em?: string[];\n ph?: string[];\n ge?: string[];\n fn?: string[];\n ln?: string[];\n ct?: string[];\n st?: string[];\n zp?: string[];\n country?: string[];\n external_id?: string[];\n client_ip_address?: string;\n client_user_agent?: string;\n fbc?: string;\n fbp?: string;\n fb_login_id?: string;\n page_id?: string;\n f5first?: string;\n f5last?: string;\n dobd?: string;\n dobm?: string;\n doby?: string;\n madid?: string;\n}\n\nfunction getUserData(tags: TrackTags, data: UserProvidedData, eventTimeMs: number): CapiUserData {\n const userData: CapiUserData = {};\n\n if (data.email) {\n const emails = Array.isArray(data.email) ? data.email : [data.email];\n userData.em = list(emails.map((email) => pii(email, PII_DATA_TYPE.EMAIL)));\n }\n if (data.phone_number) {\n const phones = Array.isArray(data.phone_number) ? data.phone_number : [data.phone_number];\n userData.ph = list(phones.map((phone) => pii(phone, PII_DATA_TYPE.PHONE)));\n }\n if (data.gender === 'female' || data.gender === 'male') {\n userData.ge = list([pii(data.gender === 'female' ? 'f' : 'm', PII_DATA_TYPE.GENDER)]);\n }\n if (data.address) {\n if (Array.isArray(data.address)) {\n // The SDK sets these lists unconditionally in the multi-address branch, so an all-empty\n // column still goes out as `[]` — kept for byte-equality with the current sender.\n userData.fn = dedupe(data.address.map((a) => hashed(a.first_name, nameRule)));\n userData.ln = dedupe(data.address.map((a) => hashed(a.last_name, nameRule)));\n userData.ct = dedupe(data.address.map((a) => hashed(a.city, cityStateRule)));\n userData.st = dedupe(data.address.map((a) => hashed(a.region, cityStateRule)));\n userData.zp = dedupe(data.address.map((a) => hashed(a.postal_code, zipRule)));\n userData.country = dedupe(\n data.address.map((a) => pii(normalizeCountry(a.country), PII_DATA_TYPE.COUNTRY))\n );\n } else {\n userData.fn = list([hashed(data.address.first_name, nameRule)]);\n userData.ln = list([hashed(data.address.last_name, nameRule)]);\n userData.ct = list([hashed(data.address.city, cityStateRule)]);\n userData.st = list([hashed(data.address.region, cityStateRule)]);\n userData.zp = list([hashed(data.address.postal_code, zipRule)]);\n userData.country = list([pii(normalizeCountry(data.address.country), PII_DATA_TYPE.COUNTRY)]);\n // The 5-character prefixes, exactly as the current sender builds them: sliced first, then\n // normalized. Only the single-address branch sets them, as before.\n userData.f5first = hashed(data.address.first_name?.slice(0, 5), f5Rule);\n userData.f5last = hashed(data.address.last_name?.slice(0, 5), f5Rule);\n }\n }\n if (data.birthday) {\n const { year, month, day } = data.birthday;\n if (/^\\d{4}$/.test(year.toString())) {\n userData.doby = createHash('sha256').update(year.toString()).digest('hex');\n }\n if (month >= 1 && month <= 12) {\n userData.dobm = createHash('sha256').update(month.toString().padStart(2, '0')).digest('hex');\n }\n if (day >= 1 && day <= 31) {\n userData.dobd = createHash('sha256').update(day.toString().padStart(2, '0')).digest('hex');\n }\n }\n if (data.user_id && data.user_id.length !== 0) {\n // Unhashed, as the business SDK sends it. Meta documents hashing as recommended, not\n // required; changing it here would break continuity with every event sent so far.\n userData.external_id = [data.user_id];\n }\n if (data.ip_address) {\n userData.client_ip_address = data.ip_address;\n }\n if (data.user_agent) {\n userData.client_user_agent = data.user_agent;\n }\n if (data.fb_login_id) {\n userData.fb_login_id = data.fb_login_id;\n }\n if (data.fb_page_id) {\n userData.page_id = data.fb_page_id;\n }\n\n const fbc = metaFbc(tags, eventTimeMs);\n if (fbc) {\n userData.fbc = fbc;\n }\n const fbp = metaFbp(tags);\n if (fbp) {\n userData.fbp = fbp;\n }\n if (tags.advertising_id) {\n userData.madid = tags.advertising_id;\n }\n if (tags.ip_address && typeof tags.ip_address === 'string') {\n userData.client_ip_address = tags.ip_address;\n }\n\n return userData;\n}\n\nconst DELIVERY_CATEGORIES = ['in_store', 'curbside', 'home_delivery'];\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getCustomData({ name, properties }: TrackEvent<any>): Record<string, unknown> {\n const [_, _name, fbEventProperties] = mapFBEvent(name, properties);\n const {\n value,\n currency,\n content_name,\n content_category,\n content_ids,\n contents,\n content_type,\n predicted_ltv,\n num_items,\n search_string,\n status,\n delivery_category,\n ...custom_properties\n } = fbEventProperties;\n\n const customData: Record<string, unknown> = {};\n // oxlint-disable-next-line typescript/no-unnecessary-condition -- custom event properties may carry `value: null` at runtime despite the declared type\n if (value !== undefined && value !== null && Number.isFinite(Number.parseFloat(String(value)))) {\n customData.value = Number.parseFloat(String(value));\n }\n if (currency) {\n // The business SDK also validates against the ISO 4217 list and throws; here an unknown\n // code is forwarded uppercased rather than costing the batch.\n customData.currency = currency\n .trim()\n .toUpperCase()\n .replace(/[^A-Z]/g, '');\n }\n if (content_name) customData.content_name = content_name;\n if (content_category) customData.content_category = content_category;\n if (content_ids) customData.content_ids = content_ids;\n if (contents) {\n customData.contents = contents.map((c) => {\n const content: Record<string, unknown> = {};\n if (c.id) content.id = c.id;\n if (c.quantity) content.quantity = c.quantity;\n if (c.item_price) content.item_price = c.item_price;\n if (c.title) content.title = c.title;\n if (c.description) content.description = c.description;\n if (c.brand) content.brand = c.brand;\n if (c.category) content.category = c.category;\n const delivery = c.delivery_category?.trim().toLowerCase();\n if (delivery && DELIVERY_CATEGORIES.includes(delivery)) content.delivery_category = delivery;\n return content;\n });\n }\n if (content_type) customData.content_type = content_type;\n if (predicted_ltv) customData.predicted_ltv = predicted_ltv;\n if (num_items) customData.num_items = num_items;\n if (search_string) customData.search_string = search_string;\n if (status) customData.status = status.toString();\n const delivery = delivery_category?.trim().toLowerCase();\n if (delivery && DELIVERY_CATEGORIES.includes(delivery)) customData.delivery_category = delivery;\n\n return { ...customData, ...custom_properties };\n}\n\n/**\n * `extinfo` is keyed by field index. The business SDK builds the same object and leaves unset\n * indexes out when it serializes; the documented 16-element array is what the Graph endpoint\n * decodes this into. Indexes: 0 version, 1 package, 2 short version, 3 long version, 4 OS\n * version, 5 device model, 6 locale, 9 screen width, 10 height, 11 density.\n */\n/**\n * The `extinfo` version of an app event's OS — `i2` for iOS, `a2` for Android, the only two Meta\n * documents. Undefined for any other OS (a desktop app): such an event cannot carry the\n * `app_data` an app event requires, and is sent as `other`.\n * https://developers.facebook.com/docs/marketing-api/conversions-api/app-events\n */\nexport function metaExtinfoVersion(tags: TrackTags): 'i2' | 'a2' | undefined {\n if (tags.os_name === 'iOS' || tags.os_name === 'iPadOS') return 'i2';\n if (tags.os_name === 'Android') return 'a2';\n return undefined;\n}\n\nfunction getAppData(\n tags: TrackTags,\n appPackageName: string,\n version: 'i2' | 'a2'\n): Record<string, unknown> {\n const extinfo: Record<number, string | number> = {};\n extinfo[0] = version;\n extinfo[1] = appPackageName;\n const shortVersion = tags.release?.split('.').at(0);\n if (shortVersion) extinfo[2] = shortVersion;\n if (tags.release) extinfo[3] = tags.release;\n if (tags.os_version) extinfo[4] = tags.os_version;\n if (tags.device_model_id) extinfo[5] = tags.device_model_id;\n if (tags.language) extinfo[6] = tags.language;\n if (tags.screen_width) extinfo[9] = tags.screen_width;\n if (tags.screen_height) extinfo[10] = tags.screen_height;\n if (tags.device_pixel_ratio) extinfo[11] = tags.device_pixel_ratio.toString();\n\n // Required on every app event. An advertising id is only readable once the user allowed\n // tracking (ATT on iOS, the ad id setting on Android), so its presence is the answer.\n const appData: Record<string, unknown> = {\n extinfo,\n advertiser_tracking_enabled: !!tags.advertising_id,\n };\n if (tags.install_referrer) appData.install_referrer = tags.install_referrer;\n return appData;\n}\n\n/** One entry of the `data` array POSTed to `/{pixel_id}/events`. */\nexport interface CapiEvent {\n event_name: string;\n event_time: number;\n event_id: string;\n event_source_url?: string;\n action_source: 'app' | 'website' | 'other';\n user_data: CapiUserData;\n custom_data: Record<string, unknown>;\n app_data?: Record<string, unknown>;\n}\n\n/**\n * `action_source` is derived from `event.platform` alone: an OS platform is an app, `web` is a\n * website, and everything else — including a backend-built offline conversion, which should\n * declare `platform: 'unknown'` — lands in Meta's `other`, exactly where the business-SDK\n * sender put an explicit `'offline'` too.\n */\nexport function getCapiEvent(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData,\n appPackageName?: string\n): CapiEvent {\n const eventTime = eventTimeMs(event.created_at);\n const [_, eventName] = mapFBEvent(event.name, event.properties);\n const source = resolveActionSource(event.platform);\n const version = metaExtinfoVersion(event.tags);\n const app =\n source === 'app' && appPackageName && version\n ? { packageName: appPackageName, version }\n : undefined;\n\n const capiEvent: CapiEvent = {\n event_name: eventName,\n event_time: Math.round(eventTime / 1000),\n event_id: event.tags.idempotency_key ?? event.id,\n // `action_source` is required; an offline conversion and an undeterminable platform both\n // land in Meta's catch-all, exactly as in the business-SDK sender. So does an app event that\n // cannot carry the `app_data` Meta requires of one: no package name, or a desktop OS.\n action_source: app ? 'app' : source === 'web' ? 'website' : 'other',\n user_data: getUserData(event.tags, data, eventTime),\n custom_data: getCustomData(event),\n };\n if (app) {\n capiEvent.app_data = getAppData(event.tags, app.packageName, app.version);\n }\n const eventSourceUrl = pageLocation(event.tags);\n if (eventSourceUrl) {\n capiEvent.event_source_url = eventSourceUrl;\n }\n return capiEvent;\n}\n\nexport interface MetaConversionsOptions {\n /** Attaches `app_data`/extinfo to events whose platform resolves to an app. */\n appPackageName?: string;\n /** Routes the batch to Events Manager's Test Events tab instead of production. */\n testEventCode?: string;\n /** Graph API version, e.g. 'v24.0'. */\n apiVersion?: string;\n}\n\nexport interface MetaConversionsResponse {\n events_received?: number;\n messages?: string[];\n fbtrace_id?: string;\n}\n\n/**\n * An `event_time` over 7 days old fails the whole request — \"we return an error for the entire\n * request and process no events\" — so such an event is left out; a minute's margin for the trip.\n * https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/server-event\n */\nconst MAX_EVENT_AGE_MS = 7 * 24 * 60 * 60 * 1000 - 60 * 1000;\n\n/**\n * Sends the events to Meta's Conversions API. Rejects on a failed request — a\n * `ConversionsApiError`, or the fetch error — for the caller to handle. The token travels in the\n * JSON body, never in the URL, and is in neither error.\n */\nexport async function sendEvents(\n accessToken: string,\n pixelId: string,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n events: TrackEvent<any>[],\n data: UserProvidedData = {},\n options: MetaConversionsOptions = {}\n): Promise<MetaConversionsResponse | undefined> {\n const capiEvents = events\n .filter((event) => !IGNORED_EVENTS.includes(event.name))\n .filter((event) => Date.now() - Date.parse(event.created_at) <= MAX_EVENT_AGE_MS)\n .map((event) => getCapiEvent(event, data, options.appPackageName));\n if (capiEvents.length === 0) return undefined;\n // \"The client_user_agent is required for website events\" — sent from `data.user_agent`.\n if (!data.user_agent && capiEvents.some((event) => event.action_source === 'website')) {\n console.warn(\n 'Meta conversion: website events sent without client_user_agent (data.user_agent)'\n );\n }\n\n const version = options.apiVersion ?? API_VERSION;\n const response = await fetch(`https://graph.facebook.com/${version}/${pixelId}/events`, {\n method: 'POST',\n // Retried although a POST: the platform deduplicates on the `event_id` each event carries.\n retries: 3,\n headers: { 'Content-Type': 'application/json', Accept: 'application/json' },\n body: JSON.stringify({\n data: capiEvents,\n test_event_code: options.testEventCode,\n access_token: accessToken,\n }),\n });\n if (response.ok) return (await response.json()) as MetaConversionsResponse;\n throw new ConversionsApiError('meta', response.status, await response.text());\n}\n\n/**\n * Meta's Conversions API, sent the same events as `metaAds` in the browser: the ones Meta maps to\n * a standard event, and `customEvents`.\n */\nexport function metaConversions(\n options: MetaAdsOptions & MetaConversionsOptions & { accessToken: string }\n): ConversionDestination {\n return conversionDestination(adEvents(isStandardFBEvent, options.customEvents), (events, data) =>\n sendEvents(options.accessToken, options.pixelId, events, data, options)\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,MAAM,cAAc;AAEpB,MAAM,0BAAoC,CAAC,IAAI;AAC/C,SAAS,iBAAiB,OAA+C;CACvE,MAAM,UAAU,OAAO,MAAM,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,EAAE,YAAY;CACxD,IAAI,CAAC,SAAS,OAAO,KAAA;CACrB,OAAO,wBAAwB,SAAS,OAAO,IAAI,KAAA,IAAY;AACjE;;;;;AAMA,IAAI;;;;;;;AAQJ,SAAS,IAAI,OAA2B,UAAsC;CAC5E,IAAI,CAAC,OAAO,OAAO,KAAA;CAEnB,QADe,iBAAiB,IAAIA,0BAAAA,aAAa,EAAA,CAAG,0BAA0B,OAAO,QAC1E,CAAC,EAAE,MAAM,GAAG,CAAC,CAAC,GAAG,CAAC,KAAK,KAAA;AACpC;AAEA,MAAM,gBAAgB;;;;;;;AAQtB,SAAS,OACP,OACA,MACoB;CACpB,IAAI,CAAC,OAAO,OAAO,KAAA;CACnB,MAAM,UAAU,MAAM,KAAK,CAAC,CAAC,YAAY;CACzC,IAAI,CAAC,SAAS,OAAO,KAAA;CACrB,IAAI,cAAc,KAAK,OAAO,GAAG,OAAO;CACxC,MAAM,aAAa,KAAK,OAAO;CAC/B,IAAI,eAAe,KAAA,GAAW,OAAO,KAAA;CACrC,QAAA,GAAOC,YAAAA,WAAAA,CAAW,QAAQ,CAAC,CAAC,OAAO,UAAU,CAAC,CAAC,OAAO,KAAK;AAC7D;AAEA,MAAM,YAAY,MAAc;AAChC,MAAM,UAAU,MAA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A,SAASC,kBAAAA,mBAAmB,QAAQ,YAAY,IAAI,QAAQ,SACvF,WAAW,QAAQ,aAAa,QAAQ,SAAS,QAAQ,MAAM,OAAO,CACxE;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"meta-capi.d.cts","names":[],"sources":["../../src/server/meta-capi.ts"],"mappings":";;;UAyGU;EACR;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;;;;;;;;;;;;;wBAqKc,mBAAmB,MAAM;;iBAmCxB;EACf;EACA;EACA;EACA;EACA;EACA,WAAW;EACX,aAAa;EACb,WAAW;;;;;;;;wBASG,aAEd,OAAO,iBACP,MAAM,kBACN,0BACC;iBA+Bc;;EAEf;;EAEA;;EAEA;;iBAGe;EACf;EACA;EACA;;;;;;;wBAeoB,WACpB,qBACA,iBAEA,QAAQ,mBACR,OAAM,kBACN,UAAS,yBACR,QAAQ;;;;;wBAiCK,gBACd,SAAS,iBAAiB;EAA2B;IACpD"}
1
+ {"version":3,"file":"meta-capi.d.cts","names":[],"sources":["../../src/server/meta-capi.ts"],"mappings":";;;UA0GU;EACR;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;;;;;;;;;;;;;wBAqKc,mBAAmB,MAAM;;iBAmCxB;EACf;EACA;EACA;EACA;EACA;EACA,WAAW;EACX,aAAa;EACb,WAAW;;;;;;;;wBASG,aAEd,OAAO,iBACP,MAAM,kBACN,0BACC;iBA+Bc;;EAEf;;EAEA;;EAEA;;iBAGe;EACf;EACA;EACA;;;;;;;wBAeoB,WACpB,qBACA,iBAEA,QAAQ,mBACR,OAAM,kBACN,UAAS,yBACR,QAAQ;;;;;wBAiCK,gBACd,SAAS,iBAAiB;EAA2B;IACpD"}
@@ -1 +1 @@
1
- {"version":3,"file":"meta-capi.d.mts","names":[],"sources":["../../src/server/meta-capi.ts"],"mappings":";;;UAyGU;EACR;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;;;;;;;;;;;;;wBAqKc,mBAAmB,MAAM;;iBAmCxB;EACf;EACA;EACA;EACA;EACA;EACA,WAAW;EACX,aAAa;EACb,WAAW;;;;;;;;wBASG,aAEd,OAAO,iBACP,MAAM,kBACN,0BACC;iBA+Bc;;EAEf;;EAEA;;EAEA;;iBAGe;EACf;EACA;EACA;;;;;;;wBAeoB,WACpB,qBACA,iBAEA,QAAQ,mBACR,OAAM,kBACN,UAAS,yBACR,QAAQ;;;;;wBAiCK,gBACd,SAAS,iBAAiB;EAA2B;IACpD"}
1
+ {"version":3,"file":"meta-capi.d.mts","names":[],"sources":["../../src/server/meta-capi.ts"],"mappings":";;;UA0GU;EACR;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;;;;;;;;;;;;;wBAqKc,mBAAmB,MAAM;;iBAmCxB;EACf;EACA;EACA;EACA;EACA;EACA,WAAW;EACX,aAAa;EACb,WAAW;;;;;;;;wBASG,aAEd,OAAO,iBACP,MAAM,kBACN,0BACC;iBA+Bc;;EAEf;;EAEA;;EAEA;;iBAGe;EACf;EACA;EACA;;;;;;;wBAeoB,WACpB,qBACA,iBAEA,QAAQ,mBACR,OAAM,kBACN,UAAS,yBACR,QAAQ;;;;;wBAiCK,gBACd,SAAS,iBAAiB;EAA2B;IACpD"}