@shware/analytics 9.0.0 → 9.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/hooks/use-web-analytics.cjs +5 -1
- package/dist/hooks/use-web-analytics.cjs.map +1 -1
- package/dist/hooks/use-web-analytics.d.cts.map +1 -1
- package/dist/hooks/use-web-analytics.d.mts.map +1 -1
- package/dist/hooks/use-web-analytics.mjs +6 -2
- package/dist/hooks/use-web-analytics.mjs.map +1 -1
- package/dist/index.cjs +1 -0
- package/dist/index.d.cts +2 -2
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +2 -2
- package/dist/server/google-data-manager.cjs +3 -3
- package/dist/server/google-data-manager.cjs.map +1 -1
- package/dist/server/google-data-manager.d.cts +15 -2
- package/dist/server/google-data-manager.d.cts.map +1 -1
- package/dist/server/google-data-manager.d.mts +15 -2
- package/dist/server/google-data-manager.d.mts.map +1 -1
- package/dist/server/google-data-manager.mjs +3 -3
- package/dist/server/google-data-manager.mjs.map +1 -1
- package/dist/server/index.d.cts +2 -2
- package/dist/server/index.d.mts +2 -2
- package/dist/server/linkedin-conversions-api.cjs +6 -1
- package/dist/server/linkedin-conversions-api.cjs.map +1 -1
- package/dist/server/linkedin-conversions-api.d.cts.map +1 -1
- package/dist/server/linkedin-conversions-api.d.mts.map +1 -1
- package/dist/server/linkedin-conversions-api.mjs +6 -1
- package/dist/server/linkedin-conversions-api.mjs.map +1 -1
- package/dist/server/meta-capi.cjs +7 -1
- package/dist/server/meta-capi.cjs.map +1 -1
- package/dist/server/meta-capi.d.cts.map +1 -1
- package/dist/server/meta-capi.d.mts.map +1 -1
- package/dist/server/meta-capi.mjs +7 -1
- package/dist/server/meta-capi.mjs.map +1 -1
- package/dist/server/meta-conversions-api.cjs +3 -1
- package/dist/server/meta-conversions-api.cjs.map +1 -1
- package/dist/server/meta-conversions-api.d.cts.map +1 -1
- package/dist/server/meta-conversions-api.d.mts.map +1 -1
- package/dist/server/meta-conversions-api.mjs +3 -1
- package/dist/server/meta-conversions-api.mjs.map +1 -1
- package/dist/server/microsoft-conversions-api.cjs +3 -1
- package/dist/server/microsoft-conversions-api.cjs.map +1 -1
- package/dist/server/microsoft-conversions-api.d.cts.map +1 -1
- package/dist/server/microsoft-conversions-api.d.mts.map +1 -1
- package/dist/server/microsoft-conversions-api.mjs +3 -1
- package/dist/server/microsoft-conversions-api.mjs.map +1 -1
- package/dist/server/openai-conversions-api.cjs +13 -12
- package/dist/server/openai-conversions-api.cjs.map +1 -1
- package/dist/server/openai-conversions-api.d.cts.map +1 -1
- package/dist/server/openai-conversions-api.d.mts.map +1 -1
- package/dist/server/openai-conversions-api.mjs +14 -13
- package/dist/server/openai-conversions-api.mjs.map +1 -1
- package/dist/server/reddit-conversions-api.cjs +6 -2
- package/dist/server/reddit-conversions-api.cjs.map +1 -1
- package/dist/server/reddit-conversions-api.d.cts +10 -1
- package/dist/server/reddit-conversions-api.d.cts.map +1 -1
- package/dist/server/reddit-conversions-api.d.mts +10 -1
- package/dist/server/reddit-conversions-api.d.mts.map +1 -1
- package/dist/server/reddit-conversions-api.mjs +6 -2
- package/dist/server/reddit-conversions-api.mjs.map +1 -1
- package/dist/setup/session.cjs +1 -1
- package/dist/setup/session.cjs.map +1 -1
- package/dist/setup/session.d.cts +6 -5
- package/dist/setup/session.d.cts.map +1 -1
- package/dist/setup/session.d.mts +6 -5
- package/dist/setup/session.d.mts.map +1 -1
- package/dist/setup/session.mjs +1 -1
- package/dist/setup/session.mjs.map +1 -1
- package/dist/third-parties/openai-pixel.cjs +29 -13
- package/dist/third-parties/openai-pixel.cjs.map +1 -1
- package/dist/third-parties/openai-pixel.d.cts +4 -3
- package/dist/third-parties/openai-pixel.d.cts.map +1 -1
- package/dist/third-parties/openai-pixel.d.mts +4 -3
- package/dist/third-parties/openai-pixel.d.mts.map +1 -1
- package/dist/third-parties/openai-pixel.mjs +30 -14
- package/dist/third-parties/openai-pixel.mjs.map +1 -1
- package/dist/track/index.cjs +156 -89
- package/dist/track/index.cjs.map +1 -1
- package/dist/track/index.d.cts +17 -0
- package/dist/track/index.d.cts.map +1 -1
- package/dist/track/index.d.mts +17 -0
- package/dist/track/index.d.mts.map +1 -1
- package/dist/track/index.mjs +156 -90
- package/dist/track/index.mjs.map +1 -1
- package/dist/track/oaiq.cjs +57 -9
- package/dist/track/oaiq.cjs.map +1 -1
- package/dist/track/oaiq.d.cts +33 -7
- package/dist/track/oaiq.d.cts.map +1 -1
- package/dist/track/oaiq.d.mts +33 -7
- package/dist/track/oaiq.d.mts.map +1 -1
- package/dist/track/oaiq.mjs +55 -10
- package/dist/track/oaiq.mjs.map +1 -1
- package/package.json +1 -1
|
@@ -3,6 +3,7 @@ const require_third_parties_ignored_events = require("../third-parties/ignored-e
|
|
|
3
3
|
const require_utils_field = require("../utils/field.cjs");
|
|
4
4
|
const require_server_action_source = require("./action-source.cjs");
|
|
5
5
|
const require_server_click_ids = require("./click-ids.cjs");
|
|
6
|
+
const require_server_page_location = require("./page-location.cjs");
|
|
6
7
|
const require_track_rdt = require("../track/rdt.cjs");
|
|
7
8
|
let _shware_utils = require("@shware/utils");
|
|
8
9
|
//#region src/server/reddit-conversions-api.ts
|
|
@@ -13,7 +14,8 @@ function getServerEvent(event, data, actionSource) {
|
|
|
13
14
|
return {
|
|
14
15
|
click_id: require_server_click_ids.redditClickId(tags),
|
|
15
16
|
event_at: new Date(created_at).getTime(),
|
|
16
|
-
action_source: source === "web" ? "WEBSITE" : source === "app" ? "APP" : "
|
|
17
|
+
action_source: source === "web" ? "WEBSITE" : source === "app" ? "APP" : "OTHER",
|
|
18
|
+
event_source_url: source === "web" ? require_server_page_location.pageLocation(tags) : void 0,
|
|
17
19
|
type: {
|
|
18
20
|
tracking_type: type === "Custom" ? "CUSTOM" : require_track_rdt.mapServerStandardEvent(type),
|
|
19
21
|
custom_event_name: type === "Custom" ? params.customEventName : void 0
|
|
@@ -41,10 +43,12 @@ function getServerEvent(event, data, actionSource) {
|
|
|
41
43
|
}
|
|
42
44
|
};
|
|
43
45
|
}
|
|
46
|
+
/** `event_at` "can't be older than seven days"; a minute's margin for the trip. */
|
|
47
|
+
const MAX_EVENT_AGE_MS = 60474e4;
|
|
44
48
|
async function sendEvents(accessToken, pixelId, events, data = {}, testId, actionSource) {
|
|
45
49
|
const dto = { data: {
|
|
46
50
|
test_id: testId,
|
|
47
|
-
events: events.filter((event) => !require_third_parties_ignored_events.IGNORED_EVENTS.includes(event.name)).map((event) => getServerEvent(event, data, actionSource))
|
|
51
|
+
events: events.filter((event) => !require_third_parties_ignored_events.IGNORED_EVENTS.includes(event.name)).filter((event) => Date.now() - Date.parse(event.created_at) <= MAX_EVENT_AGE_MS).map((event) => getServerEvent(event, data, actionSource))
|
|
48
52
|
} };
|
|
49
53
|
if (dto.data.events.length === 0) return;
|
|
50
54
|
try {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reddit-conversions-api.cjs","names":["mapRDTEvent","resolveActionSource","redditClickId","mapServerStandardEvent","getFirst","redditUuid","IGNORED_EVENTS","fetch"],"sources":["../../src/server/reddit-conversions-api.ts"],"sourcesContent":["import { fetch } from '@shware/utils';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { type ServerStandardEvent, mapRDTEvent, mapServerStandardEvent } from '../track/rdt';\nimport type { TrackEvent, UserProvidedData } from '../track/types';\nimport { getFirst } from '../utils/field';\nimport { type EventActionSource, resolveActionSource } from './action-source';\nimport { redditClickId, redditUuid } from './click-ids';\n\n/**\n * https://ads-api.reddit.com/docs/v3/operations/Post%20Conversion%20Events\n * https://business.reddithelp.com/s/article/map-a-catalog-to-a-signal-source\n */\nexport interface RedditEvent {\n /** Match keys: Share user identifiers to match conversions to a Reddit ad engagement. */\n click_id?: string;\n\n /** Unix epoch timestamp in milliseconds, event_at can't be older than seven days. */\n event_at: number;\n\n action_source: 'WEBSITE' | 'APP' |
|
|
1
|
+
{"version":3,"file":"reddit-conversions-api.cjs","names":["mapRDTEvent","resolveActionSource","redditClickId","pageLocation","mapServerStandardEvent","getFirst","redditUuid","IGNORED_EVENTS","fetch"],"sources":["../../src/server/reddit-conversions-api.ts"],"sourcesContent":["import { fetch } from '@shware/utils';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { type ServerStandardEvent, mapRDTEvent, mapServerStandardEvent } from '../track/rdt';\nimport type { TrackEvent, UserProvidedData } from '../track/types';\nimport { getFirst } from '../utils/field';\nimport { type EventActionSource, resolveActionSource } from './action-source';\nimport { redditClickId, redditUuid } from './click-ids';\nimport { pageLocation } from './page-location';\n\n/**\n * https://ads-api.reddit.com/docs/v3/operations/Post%20Conversion%20Events\n * https://business.reddithelp.com/s/article/map-a-catalog-to-a-signal-source\n */\nexport interface RedditEvent {\n /** Match keys: Share user identifiers to match conversions to a Reddit ad engagement. */\n click_id?: string;\n\n /** Unix epoch timestamp in milliseconds, event_at can't be older than seven days. */\n event_at: number;\n\n /**\n * Where the conversion happened. Pixel events are deduplicated only against `WEBSITE` ones.\n * https://business.reddithelp.com/s/article/Conversions-API#measure-impact-across-channels\n */\n action_source: 'WEBSITE' | 'APP' | 'PHYSICAL_STORE' | 'OTHER';\n\n /**\n * The page the event happened on, for `WEBSITE` events: Reddit reads the domain from it, and the\n * click id when `click_id` is missing.\n */\n event_source_url?: string;\n\n type: {\n tracking_type: ServerStandardEvent | 'CUSTOM';\n custom_event_name?: string;\n };\n\n /**\n * Event metadata\n * Share as much additional information about your conversion event as you'd like. If you're\n * using the Conversions API with the pixel, conversion_id is required for deduplication.\n */\n metadata?: {\n conversion_id?: string;\n currency?: string; // ISO 4217 3-letter currency code\n item_count?: number;\n value?: number;\n products?: { id: string; name?: string; category?: string }[];\n };\n\n user?: {\n email?: string;\n external_id?: string;\n ip_address?: string;\n phone_number?: string;\n user_agent?: string;\n\n /** The Identifier for Advertisers (IDFA) of the user's Apple device. */\n idfa?: string;\n\n /** The Android Advertising ID (AAID) of the user's Android device. */\n aaid?: string;\n /**\n * The value from the first-party Pixel _rdt_uuid cookie on your domain. Note that it is in\n * the {timestamp}.{uuid} format. You may use the full value or just the UUID portion.\n * Example: 1684189007728.7c73f2ae-a433-4d7b-9838-f467da98f48e\n */\n uuid?: string;\n\n screen_dimensions?: { width: number; height: number };\n\n /**\n * A structure of data processing options to specify the processing type for the event\n * https://business.reddithelp.com/s/article/Limited-Data-Use\n */\n data_processing_options?: {\n country: string;\n region: string;\n modes: string[] | ['LDU'];\n };\n };\n}\n\nexport interface CreateRedditEventDTO {\n data: { test_id?: string; events: RedditEvent[] };\n}\n\nexport function getServerEvent(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData,\n actionSource?: EventActionSource\n): RedditEvent {\n const { id, name, properties, tags, platform, created_at } = event;\n const [type, params] = mapRDTEvent(name, properties, id);\n // An offline conversion — in store, from a CRM, over the phone — is `OTHER` rather than\n // `PHYSICAL_STORE`, which only one of those is; so is an undeterminable platform.\n const source = resolveActionSource(platform, actionSource);\n\n return {\n click_id: redditClickId(tags),\n event_at: new Date(created_at).getTime(),\n action_source: source === 'web' ? 'WEBSITE' : source === 'app' ? 'APP' : 'OTHER',\n event_source_url: source === 'web' ? pageLocation(tags) : undefined,\n type: {\n tracking_type: type === 'Custom' ? 'CUSTOM' : mapServerStandardEvent(type),\n custom_event_name: type === 'Custom' ? params.customEventName : undefined,\n },\n metadata: {\n conversion_id: id,\n currency:\n 'currency' in params && typeof params.currency === 'string'\n ? params.currency.toUpperCase()\n : undefined,\n item_count:\n 'itemCount' in params && typeof params.itemCount === 'number'\n ? params.itemCount\n : undefined,\n value: 'value' in params && typeof params.value === 'number' ? params.value : undefined,\n products:\n 'products' in params && Array.isArray(params.products) && params.products.length > 0\n ? params.products\n : undefined,\n },\n user: {\n email: getFirst(data.email),\n external_id: data.user_id,\n ip_address: data.ip_address,\n phone_number: getFirst(data.phone_number),\n user_agent: data.user_agent,\n idfa: platform === 'ios' ? tags.advertising_id : undefined,\n aaid: platform === 'android' ? tags.advertising_id : undefined,\n uuid: redditUuid(tags),\n screen_dimensions:\n tags.screen_width && tags.screen_height\n ? { width: tags.screen_width, height: tags.screen_height }\n : undefined,\n },\n };\n}\n\n/** `event_at` \"can't be older than seven days\"; a minute's margin for the trip. */\nconst MAX_EVENT_AGE_MS = 7 * 24 * 60 * 60 * 1000 - 60 * 1000;\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 testId?: string,\n actionSource?: EventActionSource\n) {\n const dto: CreateRedditEventDTO = {\n data: {\n test_id: testId,\n events: 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) => getServerEvent(event, data, actionSource)),\n },\n };\n\n if (dto.data.events.length === 0) return;\n\n try {\n const response = await fetch(\n `https://ads-api.reddit.com/api/v3/pixels/${pixelId}/conversion_events`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n Authorization: `Bearer ${accessToken}`,\n },\n body: JSON.stringify(dto),\n }\n );\n if (response.ok) return;\n const { status } = response;\n const message = await response.text();\n console.error(`Failed to send Reddit conversion, status: ${status}, body: ${message}`);\n } catch (error) {\n console.error('Failed to send Reddit conversion, network error:', error);\n }\n}\n"],"mappings":";;;;;;;;;AAuFA,SAAgB,eAEd,OACA,MACA,cACa;CACb,MAAM,EAAE,IAAI,MAAM,YAAY,MAAM,UAAU,eAAe;CAC7D,MAAM,CAAC,MAAM,UAAUA,kBAAAA,YAAY,MAAM,YAAY,EAAE;CAGvD,MAAM,SAASC,6BAAAA,oBAAoB,UAAU,YAAY;CAEzD,OAAO;EACL,UAAUC,yBAAAA,cAAc,IAAI;EAC5B,UAAU,IAAI,KAAK,UAAU,CAAC,CAAC,QAAQ;EACvC,eAAe,WAAW,QAAQ,YAAY,WAAW,Q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,YAAY,CAAC;CAC7D,EACF;CAEA,IAAI,IAAI,KAAK,OAAO,WAAW,GAAG;CAElC,IAAI;EACF,MAAM,WAAW,OAAA,GAAMC,cAAAA,MAAAA,CACrB,4CAA4C,QAAQ,qBACpD;GACE,QAAQ;GACR,SAAS;IACP,gBAAgB;IAChB,QAAQ;IACR,eAAe,UAAU;GAC3B;GACA,MAAM,KAAK,UAAU,GAAG;EAC1B,CACF;EACA,IAAI,SAAS,IAAI;EACjB,MAAM,EAAE,WAAW;EACnB,MAAM,UAAU,MAAM,SAAS,KAAK;EACpC,QAAQ,MAAM,6CAA6C,OAAO,UAAU,SAAS;CACvF,SAAS,OAAO;EACd,QAAQ,MAAM,oDAAoD,KAAK;CACzE;AACF"}
|
|
@@ -11,7 +11,16 @@ export interface RedditEvent {
|
|
|
11
11
|
click_id?: string;
|
|
12
12
|
/** Unix epoch timestamp in milliseconds, event_at can't be older than seven days. */
|
|
13
13
|
event_at: number;
|
|
14
|
-
|
|
14
|
+
/**
|
|
15
|
+
* Where the conversion happened. Pixel events are deduplicated only against `WEBSITE` ones.
|
|
16
|
+
* https://business.reddithelp.com/s/article/Conversions-API#measure-impact-across-channels
|
|
17
|
+
*/
|
|
18
|
+
action_source: 'WEBSITE' | 'APP' | 'PHYSICAL_STORE' | 'OTHER';
|
|
19
|
+
/**
|
|
20
|
+
* The page the event happened on, for `WEBSITE` events: Reddit reads the domain from it, and the
|
|
21
|
+
* click id when `click_id` is missing.
|
|
22
|
+
*/
|
|
23
|
+
event_source_url?: string;
|
|
15
24
|
type: {
|
|
16
25
|
tracking_type: ServerStandardEvent | 'CUSTOM';
|
|
17
26
|
custom_event_name?: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reddit-conversions-api.d.cts","names":[],"sources":["../../src/server/reddit-conversions-api.ts"],"mappings":";;;;;;;;
|
|
1
|
+
{"version":3,"file":"reddit-conversions-api.d.cts","names":[],"sources":["../../src/server/reddit-conversions-api.ts"],"mappings":";;;;;;;;iBAaiB;;EAEf;;EAGA;;;;;EAMA;;;;;EAMA;EAEA;IACE,eAAe;IACf;;;;;;;EAQF;IACE;IACA;IACA;IACA;IACA;MAAa;MAAY;MAAe;;;EAG1C;IACE;IACA;IACA;IACA;IACA;;IAGA;;IAGA;;;;;;IAMA;IAEA;MAAsB;MAAe;;;;;;IAMrC;MACE;MACA;MACA;;;;iBAKW;EACf;IAAQ;IAAkB,QAAQ;;;wBAGpB,eAEd,OAAO,iBACP,MAAM,kBACN,eAAe,oBACd;wBAoDmB,WACpB,qBACA,iBAEA,QAAQ,mBACR,OAAM,kBACN,iBACA,eAAe,oBAAiB"}
|
|
@@ -11,7 +11,16 @@ export interface RedditEvent {
|
|
|
11
11
|
click_id?: string;
|
|
12
12
|
/** Unix epoch timestamp in milliseconds, event_at can't be older than seven days. */
|
|
13
13
|
event_at: number;
|
|
14
|
-
|
|
14
|
+
/**
|
|
15
|
+
* Where the conversion happened. Pixel events are deduplicated only against `WEBSITE` ones.
|
|
16
|
+
* https://business.reddithelp.com/s/article/Conversions-API#measure-impact-across-channels
|
|
17
|
+
*/
|
|
18
|
+
action_source: 'WEBSITE' | 'APP' | 'PHYSICAL_STORE' | 'OTHER';
|
|
19
|
+
/**
|
|
20
|
+
* The page the event happened on, for `WEBSITE` events: Reddit reads the domain from it, and the
|
|
21
|
+
* click id when `click_id` is missing.
|
|
22
|
+
*/
|
|
23
|
+
event_source_url?: string;
|
|
15
24
|
type: {
|
|
16
25
|
tracking_type: ServerStandardEvent | 'CUSTOM';
|
|
17
26
|
custom_event_name?: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reddit-conversions-api.d.mts","names":[],"sources":["../../src/server/reddit-conversions-api.ts"],"mappings":";;;;;;;;
|
|
1
|
+
{"version":3,"file":"reddit-conversions-api.d.mts","names":[],"sources":["../../src/server/reddit-conversions-api.ts"],"mappings":";;;;;;;;iBAaiB;;EAEf;;EAGA;;;;;EAMA;;;;;EAMA;EAEA;IACE,eAAe;IACf;;;;;;;EAQF;IACE;IACA;IACA;IACA;IACA;MAAa;MAAY;MAAe;;;EAG1C;IACE;IACA;IACA;IACA;IACA;;IAGA;;IAGA;;;;;;IAMA;IAEA;MAAsB;MAAe;;;;;;IAMrC;MACE;MACA;MACA;;;;iBAKW;EACf;IAAQ;IAAkB,QAAQ;;;wBAGpB,eAEd,OAAO,iBACP,MAAM,kBACN,eAAe,oBACd;wBAoDmB,WACpB,qBACA,iBAEA,QAAQ,mBACR,OAAM,kBACN,iBACA,eAAe,oBAAiB"}
|
|
@@ -2,6 +2,7 @@ import { IGNORED_EVENTS } from "../third-parties/ignored-events.mjs";
|
|
|
2
2
|
import { getFirst } from "../utils/field.mjs";
|
|
3
3
|
import { resolveActionSource } from "./action-source.mjs";
|
|
4
4
|
import { redditClickId, redditUuid } from "./click-ids.mjs";
|
|
5
|
+
import { pageLocation } from "./page-location.mjs";
|
|
5
6
|
import { mapRDTEvent, mapServerStandardEvent } from "../track/rdt.mjs";
|
|
6
7
|
import { fetch } from "@shware/utils";
|
|
7
8
|
//#region src/server/reddit-conversions-api.ts
|
|
@@ -12,7 +13,8 @@ function getServerEvent(event, data, actionSource) {
|
|
|
12
13
|
return {
|
|
13
14
|
click_id: redditClickId(tags),
|
|
14
15
|
event_at: new Date(created_at).getTime(),
|
|
15
|
-
action_source: source === "web" ? "WEBSITE" : source === "app" ? "APP" : "
|
|
16
|
+
action_source: source === "web" ? "WEBSITE" : source === "app" ? "APP" : "OTHER",
|
|
17
|
+
event_source_url: source === "web" ? pageLocation(tags) : void 0,
|
|
16
18
|
type: {
|
|
17
19
|
tracking_type: type === "Custom" ? "CUSTOM" : mapServerStandardEvent(type),
|
|
18
20
|
custom_event_name: type === "Custom" ? params.customEventName : void 0
|
|
@@ -40,10 +42,12 @@ function getServerEvent(event, data, actionSource) {
|
|
|
40
42
|
}
|
|
41
43
|
};
|
|
42
44
|
}
|
|
45
|
+
/** `event_at` "can't be older than seven days"; a minute's margin for the trip. */
|
|
46
|
+
const MAX_EVENT_AGE_MS = 60474e4;
|
|
43
47
|
async function sendEvents(accessToken, pixelId, events, data = {}, testId, actionSource) {
|
|
44
48
|
const dto = { data: {
|
|
45
49
|
test_id: testId,
|
|
46
|
-
events: events.filter((event) => !IGNORED_EVENTS.includes(event.name)).map((event) => getServerEvent(event, data, actionSource))
|
|
50
|
+
events: events.filter((event) => !IGNORED_EVENTS.includes(event.name)).filter((event) => Date.now() - Date.parse(event.created_at) <= MAX_EVENT_AGE_MS).map((event) => getServerEvent(event, data, actionSource))
|
|
47
51
|
} };
|
|
48
52
|
if (dto.data.events.length === 0) return;
|
|
49
53
|
try {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reddit-conversions-api.mjs","names":[],"sources":["../../src/server/reddit-conversions-api.ts"],"sourcesContent":["import { fetch } from '@shware/utils';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { type ServerStandardEvent, mapRDTEvent, mapServerStandardEvent } from '../track/rdt';\nimport type { TrackEvent, UserProvidedData } from '../track/types';\nimport { getFirst } from '../utils/field';\nimport { type EventActionSource, resolveActionSource } from './action-source';\nimport { redditClickId, redditUuid } from './click-ids';\n\n/**\n * https://ads-api.reddit.com/docs/v3/operations/Post%20Conversion%20Events\n * https://business.reddithelp.com/s/article/map-a-catalog-to-a-signal-source\n */\nexport interface RedditEvent {\n /** Match keys: Share user identifiers to match conversions to a Reddit ad engagement. */\n click_id?: string;\n\n /** Unix epoch timestamp in milliseconds, event_at can't be older than seven days. */\n event_at: number;\n\n action_source: 'WEBSITE' | 'APP' |
|
|
1
|
+
{"version":3,"file":"reddit-conversions-api.mjs","names":[],"sources":["../../src/server/reddit-conversions-api.ts"],"sourcesContent":["import { fetch } from '@shware/utils';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { type ServerStandardEvent, mapRDTEvent, mapServerStandardEvent } from '../track/rdt';\nimport type { TrackEvent, UserProvidedData } from '../track/types';\nimport { getFirst } from '../utils/field';\nimport { type EventActionSource, resolveActionSource } from './action-source';\nimport { redditClickId, redditUuid } from './click-ids';\nimport { pageLocation } from './page-location';\n\n/**\n * https://ads-api.reddit.com/docs/v3/operations/Post%20Conversion%20Events\n * https://business.reddithelp.com/s/article/map-a-catalog-to-a-signal-source\n */\nexport interface RedditEvent {\n /** Match keys: Share user identifiers to match conversions to a Reddit ad engagement. */\n click_id?: string;\n\n /** Unix epoch timestamp in milliseconds, event_at can't be older than seven days. */\n event_at: number;\n\n /**\n * Where the conversion happened. Pixel events are deduplicated only against `WEBSITE` ones.\n * https://business.reddithelp.com/s/article/Conversions-API#measure-impact-across-channels\n */\n action_source: 'WEBSITE' | 'APP' | 'PHYSICAL_STORE' | 'OTHER';\n\n /**\n * The page the event happened on, for `WEBSITE` events: Reddit reads the domain from it, and the\n * click id when `click_id` is missing.\n */\n event_source_url?: string;\n\n type: {\n tracking_type: ServerStandardEvent | 'CUSTOM';\n custom_event_name?: string;\n };\n\n /**\n * Event metadata\n * Share as much additional information about your conversion event as you'd like. If you're\n * using the Conversions API with the pixel, conversion_id is required for deduplication.\n */\n metadata?: {\n conversion_id?: string;\n currency?: string; // ISO 4217 3-letter currency code\n item_count?: number;\n value?: number;\n products?: { id: string; name?: string; category?: string }[];\n };\n\n user?: {\n email?: string;\n external_id?: string;\n ip_address?: string;\n phone_number?: string;\n user_agent?: string;\n\n /** The Identifier for Advertisers (IDFA) of the user's Apple device. */\n idfa?: string;\n\n /** The Android Advertising ID (AAID) of the user's Android device. */\n aaid?: string;\n /**\n * The value from the first-party Pixel _rdt_uuid cookie on your domain. Note that it is in\n * the {timestamp}.{uuid} format. You may use the full value or just the UUID portion.\n * Example: 1684189007728.7c73f2ae-a433-4d7b-9838-f467da98f48e\n */\n uuid?: string;\n\n screen_dimensions?: { width: number; height: number };\n\n /**\n * A structure of data processing options to specify the processing type for the event\n * https://business.reddithelp.com/s/article/Limited-Data-Use\n */\n data_processing_options?: {\n country: string;\n region: string;\n modes: string[] | ['LDU'];\n };\n };\n}\n\nexport interface CreateRedditEventDTO {\n data: { test_id?: string; events: RedditEvent[] };\n}\n\nexport function getServerEvent(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData,\n actionSource?: EventActionSource\n): RedditEvent {\n const { id, name, properties, tags, platform, created_at } = event;\n const [type, params] = mapRDTEvent(name, properties, id);\n // An offline conversion — in store, from a CRM, over the phone — is `OTHER` rather than\n // `PHYSICAL_STORE`, which only one of those is; so is an undeterminable platform.\n const source = resolveActionSource(platform, actionSource);\n\n return {\n click_id: redditClickId(tags),\n event_at: new Date(created_at).getTime(),\n action_source: source === 'web' ? 'WEBSITE' : source === 'app' ? 'APP' : 'OTHER',\n event_source_url: source === 'web' ? pageLocation(tags) : undefined,\n type: {\n tracking_type: type === 'Custom' ? 'CUSTOM' : mapServerStandardEvent(type),\n custom_event_name: type === 'Custom' ? params.customEventName : undefined,\n },\n metadata: {\n conversion_id: id,\n currency:\n 'currency' in params && typeof params.currency === 'string'\n ? params.currency.toUpperCase()\n : undefined,\n item_count:\n 'itemCount' in params && typeof params.itemCount === 'number'\n ? params.itemCount\n : undefined,\n value: 'value' in params && typeof params.value === 'number' ? params.value : undefined,\n products:\n 'products' in params && Array.isArray(params.products) && params.products.length > 0\n ? params.products\n : undefined,\n },\n user: {\n email: getFirst(data.email),\n external_id: data.user_id,\n ip_address: data.ip_address,\n phone_number: getFirst(data.phone_number),\n user_agent: data.user_agent,\n idfa: platform === 'ios' ? tags.advertising_id : undefined,\n aaid: platform === 'android' ? tags.advertising_id : undefined,\n uuid: redditUuid(tags),\n screen_dimensions:\n tags.screen_width && tags.screen_height\n ? { width: tags.screen_width, height: tags.screen_height }\n : undefined,\n },\n };\n}\n\n/** `event_at` \"can't be older than seven days\"; a minute's margin for the trip. */\nconst MAX_EVENT_AGE_MS = 7 * 24 * 60 * 60 * 1000 - 60 * 1000;\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 testId?: string,\n actionSource?: EventActionSource\n) {\n const dto: CreateRedditEventDTO = {\n data: {\n test_id: testId,\n events: 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) => getServerEvent(event, data, actionSource)),\n },\n };\n\n if (dto.data.events.length === 0) return;\n\n try {\n const response = await fetch(\n `https://ads-api.reddit.com/api/v3/pixels/${pixelId}/conversion_events`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n Authorization: `Bearer ${accessToken}`,\n },\n body: JSON.stringify(dto),\n }\n );\n if (response.ok) return;\n const { status } = response;\n const message = await response.text();\n console.error(`Failed to send Reddit conversion, status: ${status}, body: ${message}`);\n } catch (error) {\n console.error('Failed to send Reddit conversion, network error:', error);\n }\n}\n"],"mappings":";;;;;;;;AAuFA,SAAgB,eAEd,OACA,MACA,cACa;CACb,MAAM,EAAE,IAAI,MAAM,YAAY,MAAM,UAAU,eAAe;CAC7D,MAAM,CAAC,MAAM,UAAU,YAAY,MAAM,YAAY,EAAE;CAGvD,MAAM,SAAS,oBAAoB,UAAU,YAAY;CAEzD,OAAO;EACL,UAAU,cAAc,IAAI;EAC5B,UAAU,IAAI,KAAK,UAAU,CAAC,CAAC,QAAQ;EACvC,eAAe,WAAW,QAAQ,YAAY,WAAW,QAAQ,QAAQ;EACzE,kBAAkB,WAAW,QAAQ,aAAa,IAAI,IAAI,KAAA;EAC1D,MAAM;GACJ,eAAe,SAAS,WAAW,WAAW,uBAAuB,IAAI;GACzE,mBAAmB,SAAS,WAAW,OAAO,kBAAkB,KAAA;EAClE;EACA,UAAU;GACR,eAAe;GACf,UACE,cAAc,UAAU,OAAO,OAAO,aAAa,WAC/C,OAAO,SAAS,YAAY,IAC5B,KAAA;GACN,YACE,eAAe,UAAU,OA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,OAAO,UAAU,SAAS;CACvF,SAAS,OAAO;EACd,QAAQ,MAAM,oDAAoD,KAAK;CACzE;AACF"}
|
package/dist/setup/session.cjs
CHANGED
|
@@ -57,7 +57,7 @@ var Session = class {
|
|
|
57
57
|
};
|
|
58
58
|
this.extend = () => {
|
|
59
59
|
const stored = readSession();
|
|
60
|
-
if (!stored) return
|
|
60
|
+
if (!stored) return void 0;
|
|
61
61
|
const now = Date.now();
|
|
62
62
|
if (now - stored.lastEventTime <= 18e5) writeSession({
|
|
63
63
|
...stored,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session.cjs","names":["config","keys","uuidv7"],"sources":["../../src/setup/session.ts"],"sourcesContent":["import { v7 as uuidv7 } from 'uuid';\nimport { keys } from '../constants/storage';\nimport { config } from './index';\n\nexport const SESSION_TIMEOUT = 30 * 60 * 1000;\n\n/**\n * The part of a session that outlives the page: its identity, and the clock the timeout is\n * measured against. GA4 keeps these in its `_ga_<container>` cookie — alongside the engaged flag,\n * which arrives with `session_engaged` later — and rereads them for every event, which is what\n * makes a session survive a reload, span a whole multipage visit, and stay shared between two\n * tabs of the same site. Holding them in memory instead, as this did, starts a new session on\n * every full navigation and gives every tab one of its own.\n */\ninterface StoredSession {\n id: string;\n /** When the last event was sent. The timeout is measured from here, and only from here. */\n lastEventTime: number;\n}\n\n/** The session an event belongs to, and whether that event is the one that started it. */\ninterface SessionForEvent {\n id: string;\n started: boolean;\n}\n\n/**\n * `<version>.<id>.<lastEventTime>`, compact and cookie-safe rather than JSON: `{`, `\"`\n * and `,` all have to be percent-encoded in a cookie, and a host that wants one session across\n * its subdomains will hand `setupAnalytics` a cookie-backed `storage`, where this has to survive\n * unchanged. A uuidv7 contains no dots, so the record splits cleanly.\n *\n * The version guards a change the parser could not otherwise survive. A field appended to the end\n * does not need one — a short record simply leaves it undefined.\n */\nconst VERSION = '1';\n\nfunction readSession(): StoredSession | undefined {\n const raw = config.storage.getItem(keys.session);\n if (!raw) return undefined;\n\n const [version, id, lastEventTime] = raw.split('.');\n if (version !== VERSION || !id) return undefined;\n\n const parsed = { id, lastEventTime: Number(lastEventTime) };\n if (!Number.isFinite(parsed.lastEventTime)) return undefined;\n return parsed;\n}\n\nfunction writeSession({ id, lastEventTime }: StoredSession) {\n config.storage.setItem(keys.session, `${VERSION}.${id}.${lastEventTime}`);\n}\n\nclass Session {\n /**\n * Engagement is deliberately not stored: it is the time this page has accrued and not yet\n * reported, so it belongs to the page, not to the session. GA4 draws the same line — its cookie\n * carries the session, while the engagement timer lives and dies with the document.\n *\n * `lastTickTime` is where the accumulator last settled up, rewritten on every tick — it is not\n * when the session began, and nothing here needs to know that.\n */\n private lastTickTime: number;\n private accumulatedTime: number;\n\n private active: boolean;\n private visible: boolean;\n private focused: boolean;\n\n constructor() {\n this.lastTickTime = Date.now();\n this.accumulatedTime = 0;\n\n this.active = true;\n this.visible = typeof document !== 'undefined' ? document.visibilityState === 'visible' : true;\n this.focused = typeof document !== 'undefined' ? document.hasFocus() : true;\n }\n\n /**\n * The session a batch of events belongs to: read the stored one, start a new one if it has\n * timed out or there is none, stamp it with when those events happened and write it back. Every\n * event goes through here, exactly as GA4 rereads and rewrites its cookie per event — caching\n * the session in memory would put the tabs back out of step with each other.\n */\n touch = (eventTime: number, lastEventTime = eventTime): SessionForEvent => {\n const stored = readSession();\n\n if (stored && eventTime - stored.lastEventTime <= SESSION_TIMEOUT) {\n // `Math.max`, because a batch that waited in a frozen tab can be older than what another\n // tab has since written, and a session must never be shortened by a late arrival.\n writeSession({ ...stored, lastEventTime: Math.max(stored.lastEventTime, lastEventTime) });\n return { id: stored.id, started: false };\n }\n\n // Engagement the previous session accrued but never reported dies with it rather than being\n // handed to its successor. GA4 does the same on `session_start`.\n this.accumulatedTime = 0;\n // Wall clock, not `eventTime`: this anchors the engagement timer for the page in front of the\n // visitor now, which a batch describing something that happened an hour ago says nothing about.\n this.lastTickTime = Date.now();\n\n const session: StoredSession = { id: uuidv7(), lastEventTime };\n writeSession(session);\n return { id: session.id, started: true };\n };\n\n /**\n * The id for an event that must not start a session — the `pagehide` beacon, which reports what\n * the session now ending accrued. A live session is extended, as any event extends it; one\n * already past its timeout still owns that engagement, so its id comes back without being\n * revived into a session no `session_start` ever announced.\n */\n extend = (): string => {\n const stored = readSession();\n if (!stored) return this.touch(Date.now()).id;\n\n const now = Date.now();\n if (now - stored.lastEventTime <= SESSION_TIMEOUT) {\n writeSession({ ...stored, lastEventTime: now });\n }\n return stored.id;\n };\n\n isActive = () => this.active;\n\n updateActive = (active: boolean) => {\n this.active = active;\n };\n\n updateAccumulator = () => {\n const now = Date.now();\n if (this.focused && this.visible && this.active) {\n const delta = now - this.lastTickTime;\n if (delta > 0 && delta < SESSION_TIMEOUT) {\n this.accumulatedTime += delta;\n }\n }\n this.lastTickTime = now;\n };\n\n focus = () => {\n this.updateAccumulator();\n this.focused = true;\n };\n\n blur = () => {\n this.updateAccumulator();\n this.focused = false;\n };\n\n pageshow = () => {\n this.updateAccumulator();\n this.active = true;\n };\n\n pagehide = () => {\n this.updateAccumulator();\n this.active = false;\n };\n\n visibilitychange = (state: DocumentVisibilityState) => {\n this.updateAccumulator();\n this.visible = state === 'visible';\n };\n\n flush = () => {\n this.updateAccumulator();\n const engagementTime = this.accumulatedTime;\n this.accumulatedTime = 0;\n return engagementTime;\n };\n}\n\nlet session: Session | undefined;\n\n/**\n * The session, built the first time something asks for it.\n *\n * Deliberately not a module-scope `new Session()`. The constructor calls\n * `uuidv7()`, `uuid` draws its bytes from `crypto.getRandomValues`, and\n * Cloudflare Workers reject that outside a request handler:\n *\n * Disallowed operation called within global scope. Asynchronous I/O\n * (ex: fetch() or connect()), setting a timeout, and generating random\n * values are not allowed within global scope.\n *\n * Module scope in a Worker is evaluated once when the isolate boots and is\n * then shared by every request that isolate serves, so a random value drawn\n * there would be the same for all of them — which is why the runtime refuses\n * to produce one. A host that server-renders on Workers reaches this module\n * through `track()` on the server as well, and the throw happened as the\n * isolate booted, taking down every route before a component rendered.\n *\n * Everything here is per-visitor browser or app state, so deferring the\n * construction costs nothing and lets the server bundle be evaluated. It does\n * not make any of it safe to use there: this instance, `cache` and `config` are\n * module singletons, so calling `track()` on a server shares one session and one\n * visitor across every request the isolate serves. Import it there; do not track.\n */\nexport function getSession() {\n return (session ??= new Session());\n}\n"],"mappings":";;;;;AAIA,MAAa,kBAAkB;;;;;;;;;;AA+B/B,MAAM,UAAU;AAEhB,SAAS,cAAyC;CAChD,MAAM,MAAMA,oBAAAA,OAAO,QAAQ,QAAQC,0BAAAA,KAAK,OAAO;CAC/C,IAAI,CAAC,KAAK,OAAO,KAAA;CAEjB,MAAM,CAAC,SAAS,IAAI,iBAAiB,IAAI,MAAM,GAAG;CAClD,IAAI,YAAY,WAAW,CAAC,IAAI,OAAO,KAAA;CAEvC,MAAM,SAAS;EAAE;EAAI,eAAe,OAAO,aAAa;CAAE;CAC1D,IAAI,CAAC,OAAO,SAAS,OAAO,aAAa,GAAG,OAAO,KAAA;CACnD,OAAO;AACT;AAEA,SAAS,aAAa,EAAE,IAAI,iBAAgC;CAC1D,oBAAA,OAAO,QAAQ,QAAQA,0BAAAA,KAAK,SAAS,GAAG,QAAQ,GAAG,GAAG,GAAG,eAAe;AAC1E;AAEA,IAAM,UAAN,MAAc;CAgBZ,cAAc;EAeL,KAAA,SAAA,WAAmB,gBAAgB,cAA+B;GACzE,MAAM,SAAS,YAAY;GAE3B,IAAI,UAAU,YAAY,OAAO,iBAAA,MAAkC;IAGjE,aAAa;KAAE,GAAG;KAAQ,eAAe,KAAK,IAAI,OAAO,eAAe,aAAa;IAAE,CAAC;IACxF,OAAO;KAAE,IAAI,OAAO;KAAI,SAAS;IAAM;GACzC;GAIA,KAAK,kBAAkB;GAGvB,KAAK,eAAe,KAAK,IAAI;GAE7B,MAAM,UAAyB;IAAE,KAAA,GAAIC,KAAAA,GAAAA,CAAO;IAAG;GAAc;GAC7D,aAAa,OAAO;GACpB,OAAO;IAAE,IAAI,QAAQ;IAAI,SAAS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J,SAAgB,aAAa;CAC3B,OAAQ,YAAY,IAAI,QAAQ;AAClC"}
|
|
1
|
+
{"version":3,"file":"session.cjs","names":["config","keys","uuidv7"],"sources":["../../src/setup/session.ts"],"sourcesContent":["import { v7 as uuidv7 } from 'uuid';\nimport { keys } from '../constants/storage';\nimport { config } from './index';\n\nexport const SESSION_TIMEOUT = 30 * 60 * 1000;\n\n/**\n * The part of a session that outlives the page: its identity, and the clock the timeout is\n * measured against. GA4 keeps these in its `_ga_<container>` cookie — alongside the engaged flag,\n * which arrives with `session_engaged` later — and rereads them for every event, which is what\n * makes a session survive a reload, span a whole multipage visit, and stay shared between two\n * tabs of the same site. Holding them in memory instead, as this did, starts a new session on\n * every full navigation and gives every tab one of its own.\n */\ninterface StoredSession {\n id: string;\n /** When the last event was sent. The timeout is measured from here, and only from here. */\n lastEventTime: number;\n}\n\n/** The session an event belongs to, and whether that event is the one that started it. */\ninterface SessionForEvent {\n id: string;\n started: boolean;\n}\n\n/**\n * `<version>.<id>.<lastEventTime>`, compact and cookie-safe rather than JSON: `{`, `\"`\n * and `,` all have to be percent-encoded in a cookie, and a host that wants one session across\n * its subdomains will hand `setupAnalytics` a cookie-backed `storage`, where this has to survive\n * unchanged. A uuidv7 contains no dots, so the record splits cleanly.\n *\n * The version guards a change the parser could not otherwise survive. A field appended to the end\n * does not need one — a short record simply leaves it undefined.\n */\nconst VERSION = '1';\n\nfunction readSession(): StoredSession | undefined {\n const raw = config.storage.getItem(keys.session);\n if (!raw) return undefined;\n\n const [version, id, lastEventTime] = raw.split('.');\n if (version !== VERSION || !id) return undefined;\n\n const parsed = { id, lastEventTime: Number(lastEventTime) };\n if (!Number.isFinite(parsed.lastEventTime)) return undefined;\n return parsed;\n}\n\nfunction writeSession({ id, lastEventTime }: StoredSession) {\n config.storage.setItem(keys.session, `${VERSION}.${id}.${lastEventTime}`);\n}\n\nclass Session {\n /**\n * Engagement is deliberately not stored: it is the time this page has accrued and not yet\n * reported, so it belongs to the page, not to the session. GA4 draws the same line — its cookie\n * carries the session, while the engagement timer lives and dies with the document.\n *\n * `lastTickTime` is where the accumulator last settled up, rewritten on every tick — it is not\n * when the session began, and nothing here needs to know that.\n */\n private lastTickTime: number;\n private accumulatedTime: number;\n\n private active: boolean;\n private visible: boolean;\n private focused: boolean;\n\n constructor() {\n this.lastTickTime = Date.now();\n this.accumulatedTime = 0;\n\n this.active = true;\n this.visible = typeof document !== 'undefined' ? document.visibilityState === 'visible' : true;\n this.focused = typeof document !== 'undefined' ? document.hasFocus() : true;\n }\n\n /**\n * The session a batch of events belongs to: read the stored one, start a new one if it has\n * timed out or there is none, stamp it with when those events happened and write it back. Every\n * event goes through here, exactly as GA4 rereads and rewrites its cookie per event — caching\n * the session in memory would put the tabs back out of step with each other.\n */\n touch = (eventTime: number, lastEventTime = eventTime): SessionForEvent => {\n const stored = readSession();\n\n if (stored && eventTime - stored.lastEventTime <= SESSION_TIMEOUT) {\n // `Math.max`, because a batch that waited in a frozen tab can be older than what another\n // tab has since written, and a session must never be shortened by a late arrival.\n writeSession({ ...stored, lastEventTime: Math.max(stored.lastEventTime, lastEventTime) });\n return { id: stored.id, started: false };\n }\n\n // Engagement the previous session accrued but never reported dies with it rather than being\n // handed to its successor. GA4 does the same on `session_start`.\n this.accumulatedTime = 0;\n // Wall clock, not `eventTime`: this anchors the engagement timer for the page in front of the\n // visitor now, which a batch describing something that happened an hour ago says nothing about.\n this.lastTickTime = Date.now();\n\n const session: StoredSession = { id: uuidv7(), lastEventTime };\n writeSession(session);\n return { id: session.id, started: true };\n };\n\n /**\n * The id for an event that must not start a session — the engagement beacon, which reports what\n * the session accrued. A live session is extended, as any event extends it; one already past its\n * timeout still owns that engagement, so its id comes back without being revived into a session\n * no `session_start` ever announced. With nothing stored, no event was ever queued here, so\n * there is no session to report for, and none is started: it would never be announced.\n */\n extend = (): string | undefined => {\n const stored = readSession();\n if (!stored) return undefined;\n\n const now = Date.now();\n if (now - stored.lastEventTime <= SESSION_TIMEOUT) {\n writeSession({ ...stored, lastEventTime: now });\n }\n return stored.id;\n };\n\n isActive = () => this.active;\n\n updateActive = (active: boolean) => {\n this.active = active;\n };\n\n updateAccumulator = () => {\n const now = Date.now();\n if (this.focused && this.visible && this.active) {\n const delta = now - this.lastTickTime;\n if (delta > 0 && delta < SESSION_TIMEOUT) {\n this.accumulatedTime += delta;\n }\n }\n this.lastTickTime = now;\n };\n\n focus = () => {\n this.updateAccumulator();\n this.focused = true;\n };\n\n blur = () => {\n this.updateAccumulator();\n this.focused = false;\n };\n\n pageshow = () => {\n this.updateAccumulator();\n this.active = true;\n };\n\n pagehide = () => {\n this.updateAccumulator();\n this.active = false;\n };\n\n visibilitychange = (state: DocumentVisibilityState) => {\n this.updateAccumulator();\n this.visible = state === 'visible';\n };\n\n flush = () => {\n this.updateAccumulator();\n const engagementTime = this.accumulatedTime;\n this.accumulatedTime = 0;\n return engagementTime;\n };\n}\n\nlet session: Session | undefined;\n\n/**\n * The session, built the first time something asks for it.\n *\n * Deliberately not a module-scope `new Session()`. The constructor calls\n * `uuidv7()`, `uuid` draws its bytes from `crypto.getRandomValues`, and\n * Cloudflare Workers reject that outside a request handler:\n *\n * Disallowed operation called within global scope. Asynchronous I/O\n * (ex: fetch() or connect()), setting a timeout, and generating random\n * values are not allowed within global scope.\n *\n * Module scope in a Worker is evaluated once when the isolate boots and is\n * then shared by every request that isolate serves, so a random value drawn\n * there would be the same for all of them — which is why the runtime refuses\n * to produce one. A host that server-renders on Workers reaches this module\n * through `track()` on the server as well, and the throw happened as the\n * isolate booted, taking down every route before a component rendered.\n *\n * Everything here is per-visitor browser or app state, so deferring the\n * construction costs nothing and lets the server bundle be evaluated. It does\n * not make any of it safe to use there: this instance, `cache` and `config` are\n * module singletons, so calling `track()` on a server shares one session and one\n * visitor across every request the isolate serves. Import it there; do not track.\n */\nexport function getSession() {\n return (session ??= new Session());\n}\n"],"mappings":";;;;;AAIA,MAAa,kBAAkB;;;;;;;;;;AA+B/B,MAAM,UAAU;AAE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KAAA,gBAAA,WAAoB;GAClC,KAAK,SAAS;EAChB;EAE0B,KAAA,0BAAA;GACxB,MAAM,MAAM,KAAK,IAAI;GACrB,IAAI,KAAK,WAAW,KAAK,WAAW,KAAK,QAAQ;IAC/C,MAAM,QAAQ,MAAM,KAAK;IACzB,IAAI,QAAQ,KAAK,QAAA,MACf,KAAK,mBAAmB;GAE5B;GACA,KAAK,eAAe;EACtB;EAEc,KAAA,cAAA;GACZ,KAAK,kBAAkB;GACvB,KAAK,UAAU;EACjB;EAEa,KAAA,aAAA;GACX,KAAK,kBAAkB;GACvB,KAAK,UAAU;EACjB;EAEiB,KAAA,iBAAA;GACf,KAAK,kBAAkB;GACvB,KAAK,SAAS;EAChB;EAEiB,KAAA,iBAAA;GACf,KAAK,kBAAkB;GACvB,KAAK,SAAS;EAChB;EAEoB,KAAA,oBAAA,UAAmC;GACrD,KAAK,kBAAkB;GACvB,KAAK,UAAU,UAAU;EAC3B;EAEc,KAAA,cAAA;GACZ,KAAK,kBAAkB;GACvB,MAAM,iBAAiB,KAAK;GAC5B,KAAK,kBAAkB;GACvB,OAAO;EACT;EArGE,KAAK,eAAe,KAAK,IAAI;EAC7B,KAAK,kBAAkB;EAEvB,KAAK,SAAS;EACd,KAAK,UAAU,OAAO,aAAa,cAAc,SAAS,oBAAoB,YAAY;EAC1F,KAAK,UAAU,OAAO,aAAa,cAAc,SAAS,SAAS,IAAI;CACzE;AAgGF;AAEA,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;AA0BJ,SAAgB,aAAa;CAC3B,OAAQ,YAAY,IAAI,QAAQ;AAClC"}
|
package/dist/setup/session.d.cts
CHANGED
|
@@ -28,12 +28,13 @@ declare class Session {
|
|
|
28
28
|
*/
|
|
29
29
|
touch: (eventTime: number, lastEventTime?: number) => SessionForEvent;
|
|
30
30
|
/**
|
|
31
|
-
* The id for an event that must not start a session — the
|
|
32
|
-
* the session
|
|
33
|
-
*
|
|
34
|
-
*
|
|
31
|
+
* The id for an event that must not start a session — the engagement beacon, which reports what
|
|
32
|
+
* the session accrued. A live session is extended, as any event extends it; one already past its
|
|
33
|
+
* timeout still owns that engagement, so its id comes back without being revived into a session
|
|
34
|
+
* no `session_start` ever announced. With nothing stored, no event was ever queued here, so
|
|
35
|
+
* there is no session to report for, and none is started: it would never be announced.
|
|
35
36
|
*/
|
|
36
|
-
extend: () => string;
|
|
37
|
+
extend: () => string | undefined;
|
|
37
38
|
isActive: () => boolean;
|
|
38
39
|
updateActive: (active: boolean) => void;
|
|
39
40
|
updateAccumulator: () => void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session.d.cts","names":[],"sources":["../../src/setup/session.ts"],"mappings":";qBAIa;;UAiBH;EACR;EACA;;cA8BI;;;;;;;;;UASI;UACA;UAEA;UACA;UACA;EAER;;;;;;;EAeA,QAAK,mBAAqB,2BAA8B
|
|
1
|
+
{"version":3,"file":"session.d.cts","names":[],"sources":["../../src/setup/session.ts"],"mappings":";qBAIa;;UAiBH;EACR;EACA;;cA8BI;;;;;;;;;UASI;UACA;UAEA;UACA;UACA;EAER;;;;;;;EAeA,QAAK,mBAAqB,2BAA8B;;;;;;;;EA6BxD;EAWA;EAEA,eAAY;EAIZ;EAWA;EAKA;EAKA;EAKA;EAKA,mBAAgB,OAAW;EAK3B;;;;;;;;;;;;;;;;;;;;;;;;;;wBAkCc,cAAU"}
|
package/dist/setup/session.d.mts
CHANGED
|
@@ -28,12 +28,13 @@ declare class Session {
|
|
|
28
28
|
*/
|
|
29
29
|
touch: (eventTime: number, lastEventTime?: number) => SessionForEvent;
|
|
30
30
|
/**
|
|
31
|
-
* The id for an event that must not start a session — the
|
|
32
|
-
* the session
|
|
33
|
-
*
|
|
34
|
-
*
|
|
31
|
+
* The id for an event that must not start a session — the engagement beacon, which reports what
|
|
32
|
+
* the session accrued. A live session is extended, as any event extends it; one already past its
|
|
33
|
+
* timeout still owns that engagement, so its id comes back without being revived into a session
|
|
34
|
+
* no `session_start` ever announced. With nothing stored, no event was ever queued here, so
|
|
35
|
+
* there is no session to report for, and none is started: it would never be announced.
|
|
35
36
|
*/
|
|
36
|
-
extend: () => string;
|
|
37
|
+
extend: () => string | undefined;
|
|
37
38
|
isActive: () => boolean;
|
|
38
39
|
updateActive: (active: boolean) => void;
|
|
39
40
|
updateAccumulator: () => void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session.d.mts","names":[],"sources":["../../src/setup/session.ts"],"mappings":";qBAIa;;UAiBH;EACR;EACA;;cA8BI;;;;;;;;;UASI;UACA;UAEA;UACA;UACA;EAER;;;;;;;EAeA,QAAK,mBAAqB,2BAA8B
|
|
1
|
+
{"version":3,"file":"session.d.mts","names":[],"sources":["../../src/setup/session.ts"],"mappings":";qBAIa;;UAiBH;EACR;EACA;;cA8BI;;;;;;;;;UASI;UACA;UAEA;UACA;UACA;EAER;;;;;;;EAeA,QAAK,mBAAqB,2BAA8B;;;;;;;;EA6BxD;EAWA;EAEA,eAAY;EAIZ;EAWA;EAKA;EAKA;EAKA;EAKA,mBAAgB,OAAW;EAK3B;;;;;;;;;;;;;;;;;;;;;;;;;;wBAkCc,cAAU"}
|
package/dist/setup/session.mjs
CHANGED
|
@@ -56,7 +56,7 @@ var Session = class {
|
|
|
56
56
|
};
|
|
57
57
|
this.extend = () => {
|
|
58
58
|
const stored = readSession();
|
|
59
|
-
if (!stored) return
|
|
59
|
+
if (!stored) return void 0;
|
|
60
60
|
const now = Date.now();
|
|
61
61
|
if (now - stored.lastEventTime <= 18e5) writeSession({
|
|
62
62
|
...stored,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session.mjs","names":["uuidv7"],"sources":["../../src/setup/session.ts"],"sourcesContent":["import { v7 as uuidv7 } from 'uuid';\nimport { keys } from '../constants/storage';\nimport { config } from './index';\n\nexport const SESSION_TIMEOUT = 30 * 60 * 1000;\n\n/**\n * The part of a session that outlives the page: its identity, and the clock the timeout is\n * measured against. GA4 keeps these in its `_ga_<container>` cookie — alongside the engaged flag,\n * which arrives with `session_engaged` later — and rereads them for every event, which is what\n * makes a session survive a reload, span a whole multipage visit, and stay shared between two\n * tabs of the same site. Holding them in memory instead, as this did, starts a new session on\n * every full navigation and gives every tab one of its own.\n */\ninterface StoredSession {\n id: string;\n /** When the last event was sent. The timeout is measured from here, and only from here. */\n lastEventTime: number;\n}\n\n/** The session an event belongs to, and whether that event is the one that started it. */\ninterface SessionForEvent {\n id: string;\n started: boolean;\n}\n\n/**\n * `<version>.<id>.<lastEventTime>`, compact and cookie-safe rather than JSON: `{`, `\"`\n * and `,` all have to be percent-encoded in a cookie, and a host that wants one session across\n * its subdomains will hand `setupAnalytics` a cookie-backed `storage`, where this has to survive\n * unchanged. A uuidv7 contains no dots, so the record splits cleanly.\n *\n * The version guards a change the parser could not otherwise survive. A field appended to the end\n * does not need one — a short record simply leaves it undefined.\n */\nconst VERSION = '1';\n\nfunction readSession(): StoredSession | undefined {\n const raw = config.storage.getItem(keys.session);\n if (!raw) return undefined;\n\n const [version, id, lastEventTime] = raw.split('.');\n if (version !== VERSION || !id) return undefined;\n\n const parsed = { id, lastEventTime: Number(lastEventTime) };\n if (!Number.isFinite(parsed.lastEventTime)) return undefined;\n return parsed;\n}\n\nfunction writeSession({ id, lastEventTime }: StoredSession) {\n config.storage.setItem(keys.session, `${VERSION}.${id}.${lastEventTime}`);\n}\n\nclass Session {\n /**\n * Engagement is deliberately not stored: it is the time this page has accrued and not yet\n * reported, so it belongs to the page, not to the session. GA4 draws the same line — its cookie\n * carries the session, while the engagement timer lives and dies with the document.\n *\n * `lastTickTime` is where the accumulator last settled up, rewritten on every tick — it is not\n * when the session began, and nothing here needs to know that.\n */\n private lastTickTime: number;\n private accumulatedTime: number;\n\n private active: boolean;\n private visible: boolean;\n private focused: boolean;\n\n constructor() {\n this.lastTickTime = Date.now();\n this.accumulatedTime = 0;\n\n this.active = true;\n this.visible = typeof document !== 'undefined' ? document.visibilityState === 'visible' : true;\n this.focused = typeof document !== 'undefined' ? document.hasFocus() : true;\n }\n\n /**\n * The session a batch of events belongs to: read the stored one, start a new one if it has\n * timed out or there is none, stamp it with when those events happened and write it back. Every\n * event goes through here, exactly as GA4 rereads and rewrites its cookie per event — caching\n * the session in memory would put the tabs back out of step with each other.\n */\n touch = (eventTime: number, lastEventTime = eventTime): SessionForEvent => {\n const stored = readSession();\n\n if (stored && eventTime - stored.lastEventTime <= SESSION_TIMEOUT) {\n // `Math.max`, because a batch that waited in a frozen tab can be older than what another\n // tab has since written, and a session must never be shortened by a late arrival.\n writeSession({ ...stored, lastEventTime: Math.max(stored.lastEventTime, lastEventTime) });\n return { id: stored.id, started: false };\n }\n\n // Engagement the previous session accrued but never reported dies with it rather than being\n // handed to its successor. GA4 does the same on `session_start`.\n this.accumulatedTime = 0;\n // Wall clock, not `eventTime`: this anchors the engagement timer for the page in front of the\n // visitor now, which a batch describing something that happened an hour ago says nothing about.\n this.lastTickTime = Date.now();\n\n const session: StoredSession = { id: uuidv7(), lastEventTime };\n writeSession(session);\n return { id: session.id, started: true };\n };\n\n /**\n * The id for an event that must not start a session — the
|
|
1
|
+
{"version":3,"file":"session.mjs","names":["uuidv7"],"sources":["../../src/setup/session.ts"],"sourcesContent":["import { v7 as uuidv7 } from 'uuid';\nimport { keys } from '../constants/storage';\nimport { config } from './index';\n\nexport const SESSION_TIMEOUT = 30 * 60 * 1000;\n\n/**\n * The part of a session that outlives the page: its identity, and the clock the timeout is\n * measured against. GA4 keeps these in its `_ga_<container>` cookie — alongside the engaged flag,\n * which arrives with `session_engaged` later — and rereads them for every event, which is what\n * makes a session survive a reload, span a whole multipage visit, and stay shared between two\n * tabs of the same site. Holding them in memory instead, as this did, starts a new session on\n * every full navigation and gives every tab one of its own.\n */\ninterface StoredSession {\n id: string;\n /** When the last event was sent. The timeout is measured from here, and only from here. */\n lastEventTime: number;\n}\n\n/** The session an event belongs to, and whether that event is the one that started it. */\ninterface SessionForEvent {\n id: string;\n started: boolean;\n}\n\n/**\n * `<version>.<id>.<lastEventTime>`, compact and cookie-safe rather than JSON: `{`, `\"`\n * and `,` all have to be percent-encoded in a cookie, and a host that wants one session across\n * its subdomains will hand `setupAnalytics` a cookie-backed `storage`, where this has to survive\n * unchanged. A uuidv7 contains no dots, so the record splits cleanly.\n *\n * The version guards a change the parser could not otherwise survive. A field appended to the end\n * does not need one — a short record simply leaves it undefined.\n */\nconst VERSION = '1';\n\nfunction readSession(): StoredSession | undefined {\n const raw = config.storage.getItem(keys.session);\n if (!raw) return undefined;\n\n const [version, id, lastEventTime] = raw.split('.');\n if (version !== VERSION || !id) return undefined;\n\n const parsed = { id, lastEventTime: Number(lastEventTime) };\n if (!Number.isFinite(parsed.lastEventTime)) return undefined;\n return parsed;\n}\n\nfunction writeSession({ id, lastEventTime }: StoredSession) {\n config.storage.setItem(keys.session, `${VERSION}.${id}.${lastEventTime}`);\n}\n\nclass Session {\n /**\n * Engagement is deliberately not stored: it is the time this page has accrued and not yet\n * reported, so it belongs to the page, not to the session. GA4 draws the same line — its cookie\n * carries the session, while the engagement timer lives and dies with the document.\n *\n * `lastTickTime` is where the accumulator last settled up, rewritten on every tick — it is not\n * when the session began, and nothing here needs to know that.\n */\n private lastTickTime: number;\n private accumulatedTime: number;\n\n private active: boolean;\n private visible: boolean;\n private focused: boolean;\n\n constructor() {\n this.lastTickTime = Date.now();\n this.accumulatedTime = 0;\n\n this.active = true;\n this.visible = typeof document !== 'undefined' ? document.visibilityState === 'visible' : true;\n this.focused = typeof document !== 'undefined' ? document.hasFocus() : true;\n }\n\n /**\n * The session a batch of events belongs to: read the stored one, start a new one if it has\n * timed out or there is none, stamp it with when those events happened and write it back. Every\n * event goes through here, exactly as GA4 rereads and rewrites its cookie per event — caching\n * the session in memory would put the tabs back out of step with each other.\n */\n touch = (eventTime: number, lastEventTime = eventTime): SessionForEvent => {\n const stored = readSession();\n\n if (stored && eventTime - stored.lastEventTime <= SESSION_TIMEOUT) {\n // `Math.max`, because a batch that waited in a frozen tab can be older than what another\n // tab has since written, and a session must never be shortened by a late arrival.\n writeSession({ ...stored, lastEventTime: Math.max(stored.lastEventTime, lastEventTime) });\n return { id: stored.id, started: false };\n }\n\n // Engagement the previous session accrued but never reported dies with it rather than being\n // handed to its successor. GA4 does the same on `session_start`.\n this.accumulatedTime = 0;\n // Wall clock, not `eventTime`: this anchors the engagement timer for the page in front of the\n // visitor now, which a batch describing something that happened an hour ago says nothing about.\n this.lastTickTime = Date.now();\n\n const session: StoredSession = { id: uuidv7(), lastEventTime };\n writeSession(session);\n return { id: session.id, started: true };\n };\n\n /**\n * The id for an event that must not start a session — the engagement beacon, which reports what\n * the session accrued. A live session is extended, as any event extends it; one already past its\n * timeout still owns that engagement, so its id comes back without being revived into a session\n * no `session_start` ever announced. With nothing stored, no event was ever queued here, so\n * there is no session to report for, and none is started: it would never be announced.\n */\n extend = (): string | undefined => {\n const stored = readSession();\n if (!stored) return undefined;\n\n const now = Date.now();\n if (now - stored.lastEventTime <= SESSION_TIMEOUT) {\n writeSession({ ...stored, lastEventTime: now });\n }\n return stored.id;\n };\n\n isActive = () => this.active;\n\n updateActive = (active: boolean) => {\n this.active = active;\n };\n\n updateAccumulator = () => {\n const now = Date.now();\n if (this.focused && this.visible && this.active) {\n const delta = now - this.lastTickTime;\n if (delta > 0 && delta < SESSION_TIMEOUT) {\n this.accumulatedTime += delta;\n }\n }\n this.lastTickTime = now;\n };\n\n focus = () => {\n this.updateAccumulator();\n this.focused = true;\n };\n\n blur = () => {\n this.updateAccumulator();\n this.focused = false;\n };\n\n pageshow = () => {\n this.updateAccumulator();\n this.active = true;\n };\n\n pagehide = () => {\n this.updateAccumulator();\n this.active = false;\n };\n\n visibilitychange = (state: DocumentVisibilityState) => {\n this.updateAccumulator();\n this.visible = state === 'visible';\n };\n\n flush = () => {\n this.updateAccumulator();\n const engagementTime = this.accumulatedTime;\n this.accumulatedTime = 0;\n return engagementTime;\n };\n}\n\nlet session: Session | undefined;\n\n/**\n * The session, built the first time something asks for it.\n *\n * Deliberately not a module-scope `new Session()`. The constructor calls\n * `uuidv7()`, `uuid` draws its bytes from `crypto.getRandomValues`, and\n * Cloudflare Workers reject that outside a request handler:\n *\n * Disallowed operation called within global scope. Asynchronous I/O\n * (ex: fetch() or connect()), setting a timeout, and generating random\n * values are not allowed within global scope.\n *\n * Module scope in a Worker is evaluated once when the isolate boots and is\n * then shared by every request that isolate serves, so a random value drawn\n * there would be the same for all of them — which is why the runtime refuses\n * to produce one. A host that server-renders on Workers reaches this module\n * through `track()` on the server as well, and the throw happened as the\n * isolate booted, taking down every route before a component rendered.\n *\n * Everything here is per-visitor browser or app state, so deferring the\n * construction costs nothing and lets the server bundle be evaluated. It does\n * not make any of it safe to use there: this instance, `cache` and `config` are\n * module singletons, so calling `track()` on a server shares one session and one\n * visitor across every request the isolate serves. Import it there; do not track.\n */\nexport function getSession() {\n return (session ??= new Session());\n}\n"],"mappings":";;;;AAIA,MAAa,kBAAkB;;;;;;;;;;AA+B/B,MAAM,UAAU;AAEhB,SAAS,cAAyC;CAChD,MAAM,MAAM,OAAO,QAAQ,QAAQ,KAAK,OAAO;CAC/C,IAAI,CAAC,KAAK,OAAO,KAAA;CAEjB,MAAM,CAAC,SAAS,IAAI,iBAAiB,IAAI,MAAM,GAAG;CAClD,IAAI,YAAY,WAAW,CAAC,IAAI,OAAO,KAAA;CAEvC,MAAM,SAAS;EAAE;EAAI,eAAe,OAAO,aAAa;CAAE;CAC1D,IAAI,CAAC,OAAO,SAAS,OAAO,aAAa,GAAG,OAAO,KAAA;CACnD,OAAO;AACT;AAEA,SAAS,aAAa,EAAE,IAAI,iBAAgC;CAC1D,OAAO,QAAQ,QAAQ,KAAK,SAAS,GAAG,QAAQ,GAAG,GAAG,GAAG,eAAe;AAC1E;AAEA,IAAM,UAAN,MAAc;CAgBZ,cAAc;EAeL,KAAA,SAAA,WAAmB,gBAAgB,cAA+B;GACzE,MAAM,SAAS,YAAY;GAE3B,IAAI,UAAU,YAAY,OAAO,iBAAA,MAAkC;I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kB;GACvB,OAAO;EACT;EArGE,KAAK,eAAe,KAAK,IAAI;EAC7B,KAAK,kBAAkB;EAEvB,KAAK,SAAS;EACd,KAAK,UAAU,OAAO,aAAa,cAAc,SAAS,oBAAoB,YAAY;EAC1F,KAAK,UAAU,OAAO,aAAa,cAAc,SAAS,SAAS,IAAI;CACzE;AAgGF;AAEA,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;AA0BJ,SAAgB,aAAa;CAC3B,OAAQ,YAAY,IAAI,QAAQ;AAClC"}
|
|
@@ -21,16 +21,20 @@ function sendOpenAIEvent(name, properties, eventId) {
|
|
|
21
21
|
if (window.location.host.includes("127.0.0.1")) return;
|
|
22
22
|
if (window.location.host.includes("localhost")) return;
|
|
23
23
|
const { type, data } = require_track_oaiq.mapOAIEvent(name, properties);
|
|
24
|
-
if (type === "custom")
|
|
25
|
-
|
|
26
|
-
custom_event_name
|
|
27
|
-
|
|
28
|
-
|
|
24
|
+
if (type === "custom") {
|
|
25
|
+
const custom_event_name = require_track_oaiq.oaiCustomEventName(name);
|
|
26
|
+
if (!custom_event_name) return;
|
|
27
|
+
window.oaiq("measure", "custom", clean(data), {
|
|
28
|
+
event_id: eventId,
|
|
29
|
+
custom_event_name
|
|
30
|
+
});
|
|
31
|
+
} else window.oaiq("measure", type, clean(data), { event_id: eventId });
|
|
29
32
|
}
|
|
30
33
|
/**
|
|
31
|
-
* Re-initialize the pixel with hashed user identity for better conversion matching. Email
|
|
32
|
-
* external id are hashed client-side; geographic
|
|
33
|
-
* so the `init` call is deferred until the digests
|
|
34
|
+
* Re-initialize the pixel with hashed user identity for better conversion matching. Email, phone,
|
|
35
|
+
* external id and names are normalized as OpenAI documents and hashed client-side; geographic
|
|
36
|
+
* fields are sent raw. Hashing is asynchronous, so the `init` call is deferred until the digests
|
|
37
|
+
* resolve.
|
|
34
38
|
*/
|
|
35
39
|
function setOpenAIUser(pixelId) {
|
|
36
40
|
return ({ user_id, user_data }) => {
|
|
@@ -39,12 +43,14 @@ function setOpenAIUser(pixelId) {
|
|
|
39
43
|
return;
|
|
40
44
|
}
|
|
41
45
|
const oaiq = window.oaiq;
|
|
42
|
-
const email = require_utils_field.getFirst(user_data?.email)?.trim().toLowerCase();
|
|
46
|
+
const email = require_utils_field.getFirst(user_data?.email)?.trim().toLowerCase() || void 0;
|
|
47
|
+
const phone = require_utils_field.getFirst(user_data?.phone_number);
|
|
43
48
|
const address = require_utils_field.getFirst(user_data?.address);
|
|
44
49
|
const base = {
|
|
45
50
|
country: address?.country?.trim().toUpperCase(),
|
|
46
|
-
city: address?.city?.trim()
|
|
47
|
-
|
|
51
|
+
city: address?.city?.trim(),
|
|
52
|
+
region: address?.region?.trim(),
|
|
53
|
+
postal_code: address?.postal_code?.trim()
|
|
48
54
|
};
|
|
49
55
|
const init = (hashed) => {
|
|
50
56
|
oaiq("init", {
|
|
@@ -55,9 +61,19 @@ function setOpenAIUser(pixelId) {
|
|
|
55
61
|
})
|
|
56
62
|
});
|
|
57
63
|
};
|
|
58
|
-
|
|
64
|
+
const hash = (value) => value ? require_utils_sha256.sha256(value) : void 0;
|
|
65
|
+
Promise.all([
|
|
66
|
+
hash(email),
|
|
67
|
+
hash(phone ? require_track_oaiq.normalizeOAIPhone(phone) : void 0),
|
|
68
|
+
hash(user_id?.trim()),
|
|
69
|
+
hash(require_track_oaiq.normalizeOAIName(address?.first_name)),
|
|
70
|
+
hash(require_track_oaiq.normalizeOAIName(address?.last_name))
|
|
71
|
+
]).then(([email_sha256, phone_number_sha256, external_id_sha256, first, last]) => init({
|
|
59
72
|
email_sha256,
|
|
60
|
-
|
|
73
|
+
phone_number_sha256,
|
|
74
|
+
external_id_sha256,
|
|
75
|
+
first_name_sha256: first,
|
|
76
|
+
last_name_sha256: last
|
|
61
77
|
})).catch(() => init({}));
|
|
62
78
|
};
|
|
63
79
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openai-pixel.cjs","names":["NON_AD_EVENTS","mapOAIEvent","getFirst","sha256"],"sources":["../../src/third-parties/openai-pixel.ts"],"sourcesContent":["import type { UpdateVisitorDTO } from '../schema/index';\nimport {
|
|
1
|
+
{"version":3,"file":"openai-pixel.cjs","names":["NON_AD_EVENTS","mapOAIEvent","oaiCustomEventName","getFirst","sha256","normalizeOAIPhone","normalizeOAIName"],"sources":["../../src/third-parties/openai-pixel.ts"],"sourcesContent":["import type { UpdateVisitorDTO } from '../schema/index';\nimport {\n NON_AD_EVENTS,\n type OAIQ,\n type OAIQUser,\n mapOAIEvent,\n normalizeOAIName,\n normalizeOAIPhone,\n oaiCustomEventName,\n} from '../track/oaiq';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport { getFirst } from '../utils/field';\nimport { sha256 } from '../utils/sha256';\n\ndeclare global {\n interface Window {\n /** Undefined until the OpenAI pixel script has loaded. */\n oaiq?: OAIQ['oaiq'];\n }\n}\n\n/** Drop `undefined` fields so the SDK only receives populated values. */\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction clean(value: unknown): any {\n return JSON.parse(JSON.stringify(value));\n}\n\n/**\n * Forward an internal track event to the OpenAI measurement pixel.\n * `eventId` is reused as the OpenAI `event_id` so browser events deduplicate against the\n * Conversions API. https://developers.openai.com/ads/measurement-pixel\n */\nexport function sendOpenAIEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n eventId?: string\n) {\n if (typeof window === 'undefined' || !window.oaiq) {\n console.warn('oaiq has not been initialized');\n return;\n }\n if (NON_AD_EVENTS.includes(name)) return;\n if (window.location.host.includes('127.0.0.1')) return;\n if (window.location.host.includes('localhost')) return;\n\n const { type, data } = mapOAIEvent(name, properties);\n if (type === 'custom') {\n // Named as the Conversions API names it, so the two deduplicate; skipped when it cannot be.\n const custom_event_name = oaiCustomEventName(name);\n if (!custom_event_name) return;\n window.oaiq('measure', 'custom', clean(data), { event_id: eventId, custom_event_name });\n } else {\n window.oaiq('measure', type, clean(data), { event_id: eventId });\n }\n}\n\n/**\n * Re-initialize the pixel with hashed user identity for better conversion matching. Email, phone,\n * external id and names are normalized as OpenAI documents and hashed client-side; geographic\n * fields are sent raw. Hashing is asynchronous, so the `init` call is deferred until the digests\n * resolve.\n */\nexport function setOpenAIUser(pixelId: string) {\n return ({ user_id, user_data }: UpdateVisitorDTO) => {\n if (typeof window === 'undefined' || !window.oaiq) {\n console.warn('oaiq has not been initialized');\n return;\n }\n // Capture the narrowed reference so the deferred `init` closure keeps it non-optional.\n const oaiq = window.oaiq;\n\n const email = getFirst(user_data?.email)?.trim().toLowerCase() || undefined;\n const phone = getFirst(user_data?.phone_number);\n const address = getFirst(user_data?.address);\n\n const base: OAIQUser = {\n country: address?.country?.trim().toUpperCase(),\n city: address?.city?.trim(),\n region: address?.region?.trim(),\n postal_code: address?.postal_code?.trim(),\n };\n\n const init = (hashed: Partial<OAIQUser>) => {\n oaiq('init', { pixelId, user: clean({ ...base, ...hashed }) });\n };\n\n const hash = (value: string | undefined) => (value ? sha256(value) : undefined);\n Promise.all([\n hash(email),\n hash(phone ? normalizeOAIPhone(phone) : undefined),\n hash(user_id?.trim()),\n hash(normalizeOAIName(address?.first_name)),\n hash(normalizeOAIName(address?.last_name)),\n ])\n .then(([email_sha256, phone_number_sha256, external_id_sha256, first, last]) =>\n init({\n email_sha256,\n phone_number_sha256,\n external_id_sha256,\n first_name_sha256: first,\n last_name_sha256: last,\n })\n )\n .catch(() => init({}));\n };\n}\n"],"mappings":";;;;;;AAuBA,SAAS,MAAM,OAAqB;CAClC,OAAO,KAAK,MAAM,KAAK,UAAU,KAAK,CAAC;AACzC;;;;;;AAOA,SAAgB,gBACd,MACA,YACA,SACA;CACA,IAAI,OAAO,WAAW,eAAe,CAAC,OAAO,MAAM;EACjD,QAAQ,KAAK,+BAA+B;EAC5C;CACF;CACA,IAAIA,mBAAAA,cAAc,SAAS,IAAI,GAAG;CAClC,IAAI,OAAO,SAAS,KAAK,SAAS,WAAW,GAAG;CAChD,IAAI,OAAO,SAAS,KAAK,SAAS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AAC;GAC1C,KAAKA,mBAAAA,iBAAiB,SAAS,SAAS,CAAC;EAC3C,CAAC,CAAC,CACC,MAAM,CAAC,cAAc,qBAAqB,oBAAoB,OAAO,UACpE,KAAK;GACH;GACA;GACA;GACA,mBAAmB;GACnB,kBAAkB;EACpB,CAAC,CACH,CAAC,CACA,YAAY,KAAK,CAAC,CAAC,CAAC;CACzB;AACF"}
|
|
@@ -15,9 +15,10 @@ declare global {
|
|
|
15
15
|
*/
|
|
16
16
|
export declare function sendOpenAIEvent<T extends EventName>(name: TrackName<T>, properties?: TrackProperties<T>, eventId?: string): void;
|
|
17
17
|
/**
|
|
18
|
-
* Re-initialize the pixel with hashed user identity for better conversion matching. Email
|
|
19
|
-
* external id are hashed client-side; geographic
|
|
20
|
-
* so the `init` call is deferred until the digests
|
|
18
|
+
* Re-initialize the pixel with hashed user identity for better conversion matching. Email, phone,
|
|
19
|
+
* external id and names are normalized as OpenAI documents and hashed client-side; geographic
|
|
20
|
+
* fields are sent raw. Hashing is asynchronous, so the `init` call is deferred until the digests
|
|
21
|
+
* resolve.
|
|
21
22
|
*/
|
|
22
23
|
export declare function setOpenAIUser(pixelId: string): ({ user_id, user_data }: UpdateVisitorDTO) => void;
|
|
23
24
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openai-pixel.d.cts","names":[],"sources":["../../src/third-parties/openai-pixel.ts"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"openai-pixel.d.cts","names":[],"sources":["../../src/third-parties/openai-pixel.ts"],"mappings":";;;;QAcQ;YACI;;IAER,OAAO;;;;;;;;wBAeK,gBAAgB,UAAU,WACxC,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B;;;;;;;wBA2Bc,cAAc,qBAAe,SAAA,aACX"}
|
|
@@ -15,9 +15,10 @@ declare global {
|
|
|
15
15
|
*/
|
|
16
16
|
export declare function sendOpenAIEvent<T extends EventName>(name: TrackName<T>, properties?: TrackProperties<T>, eventId?: string): void;
|
|
17
17
|
/**
|
|
18
|
-
* Re-initialize the pixel with hashed user identity for better conversion matching. Email
|
|
19
|
-
* external id are hashed client-side; geographic
|
|
20
|
-
* so the `init` call is deferred until the digests
|
|
18
|
+
* Re-initialize the pixel with hashed user identity for better conversion matching. Email, phone,
|
|
19
|
+
* external id and names are normalized as OpenAI documents and hashed client-side; geographic
|
|
20
|
+
* fields are sent raw. Hashing is asynchronous, so the `init` call is deferred until the digests
|
|
21
|
+
* resolve.
|
|
21
22
|
*/
|
|
22
23
|
export declare function setOpenAIUser(pixelId: string): ({ user_id, user_data }: UpdateVisitorDTO) => void;
|
|
23
24
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openai-pixel.d.mts","names":[],"sources":["../../src/third-parties/openai-pixel.ts"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"openai-pixel.d.mts","names":[],"sources":["../../src/third-parties/openai-pixel.ts"],"mappings":";;;;QAcQ;YACI;;IAER,OAAO;;;;;;;;wBAeK,gBAAgB,UAAU,WACxC,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B;;;;;;;wBA2Bc,cAAc,qBAAe,SAAA,aACX"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { getFirst } from "../utils/field.mjs";
|
|
2
2
|
import { sha256 } from "../utils/sha256.mjs";
|
|
3
|
-
import { NON_AD_EVENTS, mapOAIEvent } from "../track/oaiq.mjs";
|
|
3
|
+
import { NON_AD_EVENTS, mapOAIEvent, normalizeOAIName, normalizeOAIPhone, oaiCustomEventName } from "../track/oaiq.mjs";
|
|
4
4
|
//#region src/third-parties/openai-pixel.ts
|
|
5
5
|
/** Drop `undefined` fields so the SDK only receives populated values. */
|
|
6
6
|
function clean(value) {
|
|
@@ -20,16 +20,20 @@ function sendOpenAIEvent(name, properties, eventId) {
|
|
|
20
20
|
if (window.location.host.includes("127.0.0.1")) return;
|
|
21
21
|
if (window.location.host.includes("localhost")) return;
|
|
22
22
|
const { type, data } = mapOAIEvent(name, properties);
|
|
23
|
-
if (type === "custom")
|
|
24
|
-
|
|
25
|
-
custom_event_name
|
|
26
|
-
|
|
27
|
-
|
|
23
|
+
if (type === "custom") {
|
|
24
|
+
const custom_event_name = oaiCustomEventName(name);
|
|
25
|
+
if (!custom_event_name) return;
|
|
26
|
+
window.oaiq("measure", "custom", clean(data), {
|
|
27
|
+
event_id: eventId,
|
|
28
|
+
custom_event_name
|
|
29
|
+
});
|
|
30
|
+
} else window.oaiq("measure", type, clean(data), { event_id: eventId });
|
|
28
31
|
}
|
|
29
32
|
/**
|
|
30
|
-
* Re-initialize the pixel with hashed user identity for better conversion matching. Email
|
|
31
|
-
* external id are hashed client-side; geographic
|
|
32
|
-
* so the `init` call is deferred until the digests
|
|
33
|
+
* Re-initialize the pixel with hashed user identity for better conversion matching. Email, phone,
|
|
34
|
+
* external id and names are normalized as OpenAI documents and hashed client-side; geographic
|
|
35
|
+
* fields are sent raw. Hashing is asynchronous, so the `init` call is deferred until the digests
|
|
36
|
+
* resolve.
|
|
33
37
|
*/
|
|
34
38
|
function setOpenAIUser(pixelId) {
|
|
35
39
|
return ({ user_id, user_data }) => {
|
|
@@ -38,12 +42,14 @@ function setOpenAIUser(pixelId) {
|
|
|
38
42
|
return;
|
|
39
43
|
}
|
|
40
44
|
const oaiq = window.oaiq;
|
|
41
|
-
const email = getFirst(user_data?.email)?.trim().toLowerCase();
|
|
45
|
+
const email = getFirst(user_data?.email)?.trim().toLowerCase() || void 0;
|
|
46
|
+
const phone = getFirst(user_data?.phone_number);
|
|
42
47
|
const address = getFirst(user_data?.address);
|
|
43
48
|
const base = {
|
|
44
49
|
country: address?.country?.trim().toUpperCase(),
|
|
45
|
-
city: address?.city?.trim()
|
|
46
|
-
|
|
50
|
+
city: address?.city?.trim(),
|
|
51
|
+
region: address?.region?.trim(),
|
|
52
|
+
postal_code: address?.postal_code?.trim()
|
|
47
53
|
};
|
|
48
54
|
const init = (hashed) => {
|
|
49
55
|
oaiq("init", {
|
|
@@ -54,9 +60,19 @@ function setOpenAIUser(pixelId) {
|
|
|
54
60
|
})
|
|
55
61
|
});
|
|
56
62
|
};
|
|
57
|
-
|
|
63
|
+
const hash = (value) => value ? sha256(value) : void 0;
|
|
64
|
+
Promise.all([
|
|
65
|
+
hash(email),
|
|
66
|
+
hash(phone ? normalizeOAIPhone(phone) : void 0),
|
|
67
|
+
hash(user_id?.trim()),
|
|
68
|
+
hash(normalizeOAIName(address?.first_name)),
|
|
69
|
+
hash(normalizeOAIName(address?.last_name))
|
|
70
|
+
]).then(([email_sha256, phone_number_sha256, external_id_sha256, first, last]) => init({
|
|
58
71
|
email_sha256,
|
|
59
|
-
|
|
72
|
+
phone_number_sha256,
|
|
73
|
+
external_id_sha256,
|
|
74
|
+
first_name_sha256: first,
|
|
75
|
+
last_name_sha256: last
|
|
60
76
|
})).catch(() => init({}));
|
|
61
77
|
};
|
|
62
78
|
}
|