@shware/analytics 13.0.4 → 13.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/README.md +3 -1
- package/dist/native/index.cjs +1 -1
- package/dist/native/index.mjs +1 -1
- package/dist/react-router/index.cjs +1 -1
- package/dist/react-router/index.mjs +1 -1
- package/dist/tanstack/analytics.cjs +1 -1
- package/dist/tanstack/analytics.mjs +1 -1
- package/dist/third-parties/google-analytics.cjs +1 -1
- package/dist/third-parties/google-analytics.cjs.map +1 -1
- package/dist/third-parties/google-analytics.mjs +1 -1
- package/dist/third-parties/google-analytics.mjs.map +1 -1
- package/dist/third-parties/meta-pixel.cjs +1 -1
- package/dist/third-parties/meta-pixel.mjs +1 -1
- package/dist/third-parties/posthog.cjs +7 -2
- package/dist/third-parties/posthog.cjs.map +1 -1
- package/dist/third-parties/posthog.d.cts +3 -0
- package/dist/third-parties/posthog.d.cts.map +1 -1
- package/dist/third-parties/posthog.d.mts +3 -0
- package/dist/third-parties/posthog.d.mts.map +1 -1
- package/dist/third-parties/posthog.mjs +7 -2
- package/dist/third-parties/posthog.mjs.map +1 -1
- package/dist/track/gtag.cjs.map +1 -1
- package/dist/track/gtag.d.cts +2 -2
- package/dist/track/gtag.d.mts +2 -2
- package/dist/track/gtag.mjs.map +1 -1
- package/dist/track/index.cjs +4 -1
- package/dist/track/index.cjs.map +1 -1
- package/dist/track/index.d.cts +6 -2
- package/dist/track/index.d.cts.map +1 -1
- package/dist/track/index.d.mts +6 -2
- package/dist/track/index.d.mts.map +1 -1
- package/dist/track/index.mjs +4 -1
- package/dist/track/index.mjs.map +1 -1
- package/dist/track/once.cjs +11 -1
- package/dist/track/once.cjs.map +1 -1
- package/dist/track/once.d.cts +7 -1
- package/dist/track/once.d.cts.map +1 -1
- package/dist/track/once.d.mts +7 -1
- package/dist/track/once.d.mts.map +1 -1
- package/dist/track/once.mjs +11 -1
- package/dist/track/once.mjs.map +1 -1
- package/dist/visitor/id.cjs.map +1 -1
- package/dist/visitor/id.mjs.map +1 -1
- package/dist/visitor/index.cjs +13 -4
- package/dist/visitor/index.cjs.map +1 -1
- package/dist/visitor/index.d.cts +6 -1
- package/dist/visitor/index.d.cts.map +1 -1
- package/dist/visitor/index.d.mts +6 -1
- package/dist/visitor/index.d.mts.map +1 -1
- package/dist/visitor/index.mjs +13 -4
- package/dist/visitor/index.mjs.map +1 -1
- package/dist/web/index.cjs +1 -1
- package/dist/web/index.mjs +1 -1
- package/package.json +1 -1
package/dist/track/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["TokenBucket","config","cache","IGNORED_EVENTS","getSession","uuidv7","visitorId","fetch"],"sources":["../../src/track/index.ts"],"sourcesContent":["import { TokenBucket, fetch } from '@shware/utils';\nimport { v7 as uuidv7 } from 'uuid';\nimport type { CreateTrackEventDTO } from '../schema/index';\nimport { cache, config } from '../setup/index';\nimport { getSession } from '../setup/session';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { visitorId } from '../visitor/id';\nimport type {\n EventName,\n ThirdPartyTracker,\n TrackEventResponse,\n TrackName,\n TrackProperties,\n TrackTags,\n} from './types';\n\nexport interface TrackOptions {\n enableThirdPartyTracking?: boolean;\n /**\n * Called once the server (or a beacon) has taken the event, with the event's id: the one\n * generated when it was tracked, which the third-party trackers were given too.\n */\n onSucceed?: (response?: TrackEventResponse[number]) => void;\n onError?: (error: unknown) => void;\n}\n\nconst defaultOptions: TrackOptions = {};\n\nlet tokenBucket: TokenBucket | undefined;\n\n/**\n * The rate limiter, built on the first send rather than at module scope: its\n * constructor starts a refill `setInterval`, and Cloudflare Workers refuse to\n * set a timer outside a request handler for the same reason they refuse to\n * generate random values there — see `setup/session.ts`.\n */\nfunction getTokenBucket() {\n return (tokenBucket ??= new TokenBucket({ rate: 1, capacity: 20, requested: 2 }));\n}\n\ntype Item = {\n /**\n * The event's id, a uuidv7 generated when it is tracked. The server stores the event under it\n * (`on conflict (id) do nothing`, so a batch `fetch` retries is not stored twice), and the\n * third-party trackers are given it at once as their deduplication id — the id the server's\n * conversions API sends again for the same event.\n */\n id: string;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n name: TrackName<any>;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n properties: TrackProperties<any>;\n tags: Promise<TrackTags>;\n /** `tags` once settled: a page being hidden can await nothing, and sends what it has. */\n settled?: TrackTags;\n /** Decided when the event happens, as GA4 and PostHog decide it, never when it is sent. */\n session_id: string;\n timestamp: string;\n options: TrackOptions;\n};\n\n/**\n * How an event is created, for the SDK's own callers (`trackOnce`); not exported from the\n * package. `id` carries over the id of an earlier attempt at the same occurrence, and\n * `pixels: false` skips the third-party trackers that attempt has already fired.\n */\nexport interface EventInit {\n id?: string;\n pixels?: boolean;\n}\n\n/**\n * Tags belong to the moment the event happened, not to the moment its batch goes out: a queued\n * event waits up to `delay` ms, and a single page app can navigate in that window, which would\n * stamp every pending event with the URL of the page the user has already left.\n *\n * The promise then sits in the queue with nothing awaiting it, so a failure has to be absorbed\n * here — an unhandled rejection would surface as a global error long before `sendEvents` could\n * catch it. Falling back to the last built tags keeps the event, minus whatever changed since.\n */\nasync function captureTags(): Promise<TrackTags> {\n try {\n return await config.getTags();\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n return cache.tags ?? {};\n }\n}\n\n/**\n * The events not yet sent, and the only place they are: a batch leaves it at the moment it is\n * handed to `fetch` or to a beacon, never earlier. So when the page is hidden or left,\n * everything still unsent is right here for `sendPendingEvents`.\n */\nconst list: Item[] = [];\nconst batchSize = 10;\nconst delay = 2000;\nlet timer: ReturnType<typeof setTimeout> | null = null;\n\n/**\n * Hands the event to the third-party trackers now, as it is tracked, under its own id — not once\n * the server has answered. An event followed by a full-page navigation (an outbound link,\n * `begin_checkout` before the redirect to the payment page, a landing page left at once) reaches\n * the pixels before the page goes, and the server's conversions API, sending the same id, still\n * deduplicates against the browser event. A server that is down no longer takes the pixels down\n * with it either.\n *\n * A tracker that returns `false` is not ready — its pixel's global is not on the page yet, the\n * snippet still loading (the first `page_view` of a visit is tracked right as the page mounts).\n * Those trackers, and only those, are called once more on the next macrotask, with the same event\n * and id, after the inline snippets have had their turn; a tracker still not ready then is given\n * up on, as it was when it ran after the server's answer. Never more than once: a pixel's global\n * either exists by then or the script is blocked.\n */\nfunction firePixels(event: Item) {\n // An explicit false, not falsiness: a caller passing `{ onSucceed }` replaces the options\n // object wholesale, and leaving the flag out must not silently switch forwarding off.\n if (event.options.enableThirdPartyTracking === false || IGNORED_EVENTS.includes(event.name)) {\n return;\n }\n const notReady = callTrackers(config.thirdPartyTrackers, event);\n if (notReady.length === 0) return;\n setTimeout(() => callTrackers(notReady, event), 0);\n}\n\n/** Calls each tracker with the event; returns the ones that said they were not ready. */\nfunction callTrackers(trackers: ThirdPartyTracker[], event: Item): ThirdPartyTracker[] {\n return trackers.filter((tracker) => {\n try {\n return tracker(event.name, event.properties, event.id) === false;\n } catch (e: unknown) {\n // A third-party script does not get to take the tracking call, or the other trackers, with it.\n if (e instanceof Error) console.log(e.message);\n return false;\n }\n });\n}\n\n/**\n * Queues an event, preceded by a `session_start` when it is the one that opens a session, and\n * fires its third-party trackers.\n *\n * The session is decided here, when the event happens, as GA4 and PostHog decide it: the\n * `session_start` then sits in the queue right before the event that opened the session, so\n * wherever that event goes — a batch, a beacon, a retry — its announcement has gone ahead of it.\n * It carries that event's tags and time, as GA4 derives it from the hit that started the\n * session: the landing page is where the session began, whatever the page has navigated to by\n * the time the batch goes out.\n */\nfunction enqueue(\n name: Item['name'],\n properties: Item['properties'],\n options: TrackOptions,\n init: EventInit = {}\n): Item {\n const timestamp = new Date().toISOString();\n const tags = captureTags();\n const { id: session_id, started } = getSession().touch(Date.parse(timestamp));\n const item = (fields: Pick<Item, 'id' | 'name' | 'properties' | 'options'>): Item => {\n const result: Item = { ...fields, tags, timestamp, session_id };\n void tags.then((settled) => (result.settled = settled));\n return result;\n };\n if (started) {\n const options = { enableThirdPartyTracking: false };\n list.push(item({ id: uuidv7(), name: 'session_start', properties: {}, options }));\n }\n const event = item({ id: init.id ?? uuidv7(), name, properties, options });\n list.push(event);\n if (init.pixels !== false) firePixels(event);\n return event;\n}\n\nfunction toDTO(event: Item, visitor_id: string, tags: TrackTags): CreateTrackEventDTO[number] {\n return {\n id: event.id,\n name: event.name,\n properties: event.properties,\n tags,\n visitor_id,\n session_id: event.session_id,\n platform: config.platform,\n environment: config.environment,\n timestamp: event.timestamp,\n };\n}\n\n/**\n * Sends the queue. Everything that has to be awaited is awaited first, and only then are the\n * events taken off the queue and handed to `fetch` in the same synchronous step — so there is\n * no moment at which an event is neither queued nor sent.\n */\nasync function flush() {\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n if (list.length === 0) return;\n\n let events: Item[] = [];\n try {\n await getTokenBucket().removeTokens();\n const visitor_id = visitorId();\n const headers = await config.getHeaders();\n // Settled before the events leave the queue; those queued meanwhile are a microtask away.\n await Promise.all(list.map((event) => event.tags));\n\n events = list.splice(0);\n if (events.length === 0) return;\n const dto: CreateTrackEventDTO = await Promise.all(\n events.map(async (event) => toDTO(event, visitor_id, await event.tags))\n );\n\n const body = JSON.stringify(dto);\n const response = await fetch(`${config.endpoint}/events`, {\n method: 'POST',\n credentials: 'include',\n // Retried although a POST: every event carries its client-generated id, and the server stores\n // a batch it already has `on conflict (id) do nothing`.\n retries: 3,\n // keepalive lets the request survive the page being unloaded mid-flight, within a 64KB\n // budget shared by every such request of the page; a body that could not fit goes as a\n // plain POST rather than failing outright.\n keepalive: body.length < 60_000,\n headers,\n body,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to send track event: ${response.status} ${await response.text()}`);\n }\n\n // The body is not read. Every event has had its id since it was tracked, and its trackers\n // were fired with it then. Servers still answer one `{ id }` per event (`TrackEventResponse`),\n // which a server predating client ids fills with ids of its own; neither is needed here, and\n // an answer that is not even JSON does not turn a stored batch into a failure.\n events.forEach((event) => event.options.onSucceed?.({ id: event.id }));\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n // `fetch` has already retried the transient failures by the time a batch fails here; what\n // remains is a batch the server rejected outright — one invalid event fails the whole batch\n // — or a network that stayed down past the retries. The other events are reported lost;\n // `session_start` alone goes back on the queue for the next send, because it is the\n // session's only attribution record: a session without one has no channel, and its every\n // later event drops out of an attribution join.\n const starts = events.filter((event) => event.name === 'session_start');\n list.unshift(...starts);\n events\n .filter((event) => event.name !== 'session_start')\n .forEach((event) => event.options.onError?.(e));\n }\n}\n\n/** `track`, with the `EventInit` only the SDK itself passes. */\nexport function queueEvent<T extends EventName = EventName>(\n name: TrackName<T>,\n properties: TrackProperties<T> | undefined,\n options: TrackOptions,\n init?: EventInit\n) {\n enqueue(name, properties, options, init);\n if (list.length >= batchSize) {\n void flush();\n return;\n }\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => void flush(), delay);\n}\n\n/**\n * Queues the event for the next batch — up to 2 s away, at once when the batch is full — and\n * hands it to the third-party trackers now, under the id it is sent with.\n */\nexport function track<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n options: TrackOptions = defaultOptions\n) {\n queueEvent(name, properties, options);\n}\n\nfunction beacon(dto: CreateTrackEventDTO): boolean {\n // Not every runtime with a `navigator` has it: React Native has neither beacons nor pages.\n if (typeof navigator === 'undefined' || !('sendBeacon' in navigator)) return false;\n // text/plain keeps a cross-origin beacon a CORS simple request: as application/json it needs a\n // preflight, which a page being closed often cannot complete, and the beacon is then dropped.\n // The server reads it as JSON (`zBeaconJson` in @shware/http).\n const blob = new Blob([JSON.stringify(dto)], { type: 'text/plain;charset=UTF-8' });\n return navigator.sendBeacon(`${config.endpoint}/events`, blob);\n}\n\n/**\n * Sends the queue by beacon, now: for when the page is hidden or left, the last moment its\n * script is sure to run — what PostHog's `requestQueue.unload()` and GA4 do on the same events.\n * Call it before the engagement beacon: a new session's `session_start` is in this queue.\n *\n * Nothing can be awaited here, so the events go with the tags they have settled on (the last\n * built ones otherwise). Each goes with the id it was tracked with, and its third-party trackers\n * were fired then, under that id: none is fired again here. The visitor id is local\n * (`visitorId`), so a first visit left within a second is sent like any other; when no beacon\n * can take them — no `sendBeacon`, a refused body — they stay queued for the usual send.\n */\nexport function sendPendingEvents() {\n if (list.length === 0) return;\n const visitor_id = visitorId();\n const dto: CreateTrackEventDTO = list.map((event) =>\n toDTO(event, visitor_id, event.settled ?? cache.tags ?? {})\n );\n if (!beacon(dto)) {\n void flush();\n return;\n }\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n list.splice(0).forEach((event) => event.options.onSucceed?.({ id: event.id }));\n}\n\nexport function sendBeacon<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n const visitor_id = visitorId();\n // No stored session means no event was ever queued from this storage, so there is no session\n // to report for — and one started here could never be announced. See `Session.extend`.\n const session_id = getSession().extend();\n if (!session_id) return;\n\n const dto: CreateTrackEventDTO = [\n {\n id: uuidv7(),\n name,\n properties,\n // Tags are worth less than the event carrying them: an empty set still reports the\n // engagement, and every field in `tagsSchema` is optional.\n tags: cache.tags ?? {},\n visitor_id,\n session_id,\n platform: config.platform,\n environment: config.environment,\n timestamp: new Date().toISOString(),\n },\n ];\n if (beacon(dto)) return;\n console.warn('Failed to send beacon', name, properties);\n}\n"],"mappings":";;;;;;;;AA0BA,MAAM,iBAA+B,CAAC;AAEtC,IAAI;;;;;;;AAQJ,SAAS,iBAAiB;CACxB,OAAQ,gBAAgB,IAAIA,cAAAA,YAAY;EAAE,MAAM;EAAG,UAAU;EAAI,WAAW;CAAE,CAAC;AACjF;;;;;;;;;;AA0CA,eAAe,cAAkC;CAC/C,IAAI;EACF,OAAO,MAAMC,oBAAAA,OAAO,QAAQ;CAC9B,SAAS,GAAY;EACnB,IAAI,aAAa,OAAO,QAAQ,IAAI,EAAE,OAAO;EAC7C,OAAOC,oBAAAA,MAAM,QAAQ,CAAC;CACxB;AACF;;;;;;AAOA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AAW,CAAC,CAAC,OAAO;CACvC,IAAI,CAAC,YAAY;CAiBjB,IAAI,OAAO,CAdT;EACE,KAAA,GAAIC,KAAAA,GAAAA,CAAO;EACX;EACA;EAGA,MAAMH,oBAAAA,MAAM,QAAQ,CAAC;EACrB;EACA;EACA,UAAUD,oBAAAA,OAAO;EACjB,aAAaA,oBAAAA,OAAO;EACpB,4BAAW,IAAI,KAAK,EAAA,CAAE,YAAY;CACpC,CAEW,CAAC,GAAG;CACjB,QAAQ,KAAK,yBAAyB,MAAM,UAAU;AACxD"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["TokenBucket","config","cache","IGNORED_EVENTS","getSession","uuidv7","visitorId","fetch"],"sources":["../../src/track/index.ts"],"sourcesContent":["import { TokenBucket, fetch } from '@shware/utils';\nimport { v7 as uuidv7 } from 'uuid';\nimport type { CreateTrackEventDTO } from '../schema/index';\nimport { cache, config } from '../setup/index';\nimport { getSession } from '../setup/session';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { visitorId } from '../visitor/id';\nimport type {\n EventName,\n ThirdPartyTracker,\n TrackEventResponse,\n TrackName,\n TrackProperties,\n TrackTags,\n} from './types';\n\nexport interface TrackOptions {\n enableThirdPartyTracking?: boolean;\n /**\n * Called once the server (or a beacon) has taken the event, with the event's id: the one\n * generated when it was tracked, which the third-party trackers were given too. `beacon` is\n * set when the event went by `sendPendingEvents`: the browser queued it, but a beacon cannot\n * tell delivered from dropped, so it is taken, not confirmed.\n */\n onSucceed?: (response?: TrackEventResponse[number] & { beacon?: true }) => void;\n onError?: (error: unknown) => void;\n}\n\nconst defaultOptions: TrackOptions = {};\n\nlet tokenBucket: TokenBucket | undefined;\n\n/**\n * The rate limiter, built on the first send rather than at module scope: its\n * constructor starts a refill `setInterval`, and Cloudflare Workers refuse to\n * set a timer outside a request handler for the same reason they refuse to\n * generate random values there — see `setup/session.ts`.\n */\nfunction getTokenBucket() {\n return (tokenBucket ??= new TokenBucket({ rate: 1, capacity: 20, requested: 2 }));\n}\n\ntype Item = {\n /**\n * The event's id, a uuidv7 generated when it is tracked. The server stores the event under it\n * (`on conflict (id) do nothing`, so a batch `fetch` retries is not stored twice), and the\n * third-party trackers are given it at once as their deduplication id — the id the server's\n * conversions API sends again for the same event.\n */\n id: string;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n name: TrackName<any>;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n properties: TrackProperties<any>;\n tags: Promise<TrackTags>;\n /** `tags` once settled: a page being hidden can await nothing, and sends what it has. */\n settled?: TrackTags;\n /** Decided when the event happens, as GA4 and PostHog decide it, never when it is sent. */\n session_id: string;\n timestamp: string;\n options: TrackOptions;\n};\n\n/**\n * How an event is created, for the SDK's own callers (`trackOnce`); not exported from the\n * package. `id` carries over the id of an earlier attempt at the same occurrence, and\n * `pixels: false` skips the third-party trackers that attempt has already fired.\n */\nexport interface EventInit {\n id?: string;\n pixels?: boolean;\n}\n\n/**\n * Tags belong to the moment the event happened, not to the moment its batch goes out: a queued\n * event waits up to `delay` ms, and a single page app can navigate in that window, which would\n * stamp every pending event with the URL of the page the user has already left.\n *\n * The promise then sits in the queue with nothing awaiting it, so a failure has to be absorbed\n * here — an unhandled rejection would surface as a global error long before `sendEvents` could\n * catch it. Falling back to the last built tags keeps the event, minus whatever changed since.\n */\nasync function captureTags(): Promise<TrackTags> {\n try {\n return await config.getTags();\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n return cache.tags ?? {};\n }\n}\n\n/**\n * The events not yet sent, and the only place they are: a batch leaves it at the moment it is\n * handed to `fetch` or to a beacon, never earlier. So when the page is hidden or left,\n * everything still unsent is right here for `sendPendingEvents`.\n */\nconst list: Item[] = [];\nconst batchSize = 10;\nconst delay = 2000;\nlet timer: ReturnType<typeof setTimeout> | null = null;\n\n/**\n * Hands the event to the third-party trackers now, as it is tracked, under its own id — not once\n * the server has answered. An event followed by a full-page navigation (an outbound link,\n * `begin_checkout` before the redirect to the payment page, a landing page left at once) reaches\n * the pixels before the page goes, and the server's conversions API, sending the same id, still\n * deduplicates against the browser event. A server that is down no longer takes the pixels down\n * with it either.\n *\n * A tracker that returns `false` is not ready — its pixel's global is not on the page yet, the\n * snippet still loading (the first `page_view` of a visit is tracked right as the page mounts).\n * Those trackers, and only those, are called once more on the next macrotask, with the same event\n * and id, after the inline snippets have had their turn; a tracker still not ready then is given\n * up on, as it was when it ran after the server's answer. Never more than once: a pixel's global\n * either exists by then or the script is blocked.\n */\nfunction firePixels(event: Item) {\n // An explicit false, not falsiness: a caller passing `{ onSucceed }` replaces the options\n // object wholesale, and leaving the flag out must not silently switch forwarding off.\n if (event.options.enableThirdPartyTracking === false || IGNORED_EVENTS.includes(event.name)) {\n return;\n }\n const notReady = callTrackers(config.thirdPartyTrackers, event);\n if (notReady.length === 0) return;\n setTimeout(() => callTrackers(notReady, event), 0);\n}\n\n/** Calls each tracker with the event; returns the ones that said they were not ready. */\nfunction callTrackers(trackers: ThirdPartyTracker[], event: Item): ThirdPartyTracker[] {\n return trackers.filter((tracker) => {\n try {\n return tracker(event.name, event.properties, event.id) === false;\n } catch (e: unknown) {\n // A third-party script does not get to take the tracking call, or the other trackers, with it.\n if (e instanceof Error) console.log(e.message);\n return false;\n }\n });\n}\n\n/**\n * Queues an event, preceded by a `session_start` when it is the one that opens a session, and\n * fires its third-party trackers.\n *\n * The session is decided here, when the event happens, as GA4 and PostHog decide it: the\n * `session_start` then sits in the queue right before the event that opened the session, so\n * wherever that event goes — a batch, a beacon, a retry — its announcement has gone ahead of it.\n * It carries that event's tags and time, as GA4 derives it from the hit that started the\n * session: the landing page is where the session began, whatever the page has navigated to by\n * the time the batch goes out.\n */\nfunction enqueue(\n name: Item['name'],\n properties: Item['properties'],\n options: TrackOptions,\n init: EventInit = {}\n): Item {\n const timestamp = new Date().toISOString();\n const tags = captureTags();\n const { id: session_id, started } = getSession().touch(Date.parse(timestamp));\n const item = (fields: Pick<Item, 'id' | 'name' | 'properties' | 'options'>): Item => {\n const result: Item = { ...fields, tags, timestamp, session_id };\n void tags.then((settled) => (result.settled = settled));\n return result;\n };\n if (started) {\n const options = { enableThirdPartyTracking: false };\n list.push(item({ id: uuidv7(), name: 'session_start', properties: {}, options }));\n }\n const event = item({ id: init.id ?? uuidv7(), name, properties, options });\n list.push(event);\n if (init.pixels !== false) firePixels(event);\n return event;\n}\n\nfunction toDTO(event: Item, visitor_id: string, tags: TrackTags): CreateTrackEventDTO[number] {\n return {\n id: event.id,\n name: event.name,\n properties: event.properties,\n tags,\n visitor_id,\n session_id: event.session_id,\n platform: config.platform,\n environment: config.environment,\n timestamp: event.timestamp,\n };\n}\n\n/**\n * Sends the queue. Everything that has to be awaited is awaited first, and only then are the\n * events taken off the queue and handed to `fetch` in the same synchronous step — so there is\n * no moment at which an event is neither queued nor sent.\n */\nasync function flush() {\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n if (list.length === 0) return;\n\n let events: Item[] = [];\n try {\n await getTokenBucket().removeTokens();\n const visitor_id = visitorId();\n const headers = await config.getHeaders();\n // Settled before the events leave the queue; those queued meanwhile are a microtask away.\n await Promise.all(list.map((event) => event.tags));\n\n events = list.splice(0);\n if (events.length === 0) return;\n const dto: CreateTrackEventDTO = await Promise.all(\n events.map(async (event) => toDTO(event, visitor_id, await event.tags))\n );\n\n const body = JSON.stringify(dto);\n const response = await fetch(`${config.endpoint}/events`, {\n method: 'POST',\n credentials: 'include',\n // Retried although a POST: every event carries its client-generated id, and the server stores\n // a batch it already has `on conflict (id) do nothing`.\n retries: 3,\n // keepalive lets the request survive the page being unloaded mid-flight, within a 64KB\n // budget shared by every such request of the page; a body that could not fit goes as a\n // plain POST rather than failing outright.\n keepalive: body.length < 60_000,\n headers,\n body,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to send track event: ${response.status} ${await response.text()}`);\n }\n\n // The body is not read. Every event has had its id since it was tracked, and its trackers\n // were fired with it then. Servers still answer one `{ id }` per event (`TrackEventResponse`),\n // which a server predating client ids fills with ids of its own; neither is needed here, and\n // an answer that is not even JSON does not turn a stored batch into a failure.\n events.forEach((event) => event.options.onSucceed?.({ id: event.id }));\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n // `fetch` has already retried the transient failures by the time a batch fails here; what\n // remains is a batch the server rejected outright — one invalid event fails the whole batch\n // — or a network that stayed down past the retries. The other events are reported lost;\n // `session_start` alone goes back on the queue for the next send, because it is the\n // session's only attribution record: a session without one has no channel, and its every\n // later event drops out of an attribution join.\n const starts = events.filter((event) => event.name === 'session_start');\n list.unshift(...starts);\n events\n .filter((event) => event.name !== 'session_start')\n .forEach((event) => event.options.onError?.(e));\n }\n}\n\n/** `track`, with the `EventInit` only the SDK itself passes. */\nexport function queueEvent<T extends EventName = EventName>(\n name: TrackName<T>,\n properties: TrackProperties<T> | undefined,\n options: TrackOptions,\n init?: EventInit\n) {\n enqueue(name, properties, options, init);\n if (list.length >= batchSize) {\n void flush();\n return;\n }\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => void flush(), delay);\n}\n\n/**\n * Queues the event for the next batch — up to 2 s away, at once when the batch is full — and\n * hands it to the third-party trackers now, under the id it is sent with.\n */\nexport function track<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n options: TrackOptions = defaultOptions\n) {\n queueEvent(name, properties, options);\n}\n\nfunction beacon(dto: CreateTrackEventDTO): boolean {\n // Not every runtime with a `navigator` has it: React Native has neither beacons nor pages.\n if (typeof navigator === 'undefined' || !('sendBeacon' in navigator)) return false;\n // text/plain keeps a cross-origin beacon a CORS simple request: as application/json it needs a\n // preflight, which a page being closed often cannot complete, and the beacon is then dropped.\n // The server reads it as JSON (`zBeaconJson` in @shware/http).\n const blob = new Blob([JSON.stringify(dto)], { type: 'text/plain;charset=UTF-8' });\n return navigator.sendBeacon(`${config.endpoint}/events`, blob);\n}\n\n/**\n * Sends the queue by beacon, now: for when the page is hidden or left, the last moment its\n * script is sure to run — what PostHog's `requestQueue.unload()` and GA4 do on the same events.\n * Call it before the engagement beacon: a new session's `session_start` is in this queue.\n *\n * Nothing can be awaited here, so the events go with the tags they have settled on (the last\n * built ones otherwise). Each goes with the id it was tracked with, and its third-party trackers\n * were fired then, under that id: none is fired again here. The visitor id is local\n * (`visitorId`), so a first visit left within a second is sent like any other; when no beacon\n * can take them — no `sendBeacon`, a refused body — they stay queued for the usual send.\n */\nexport function sendPendingEvents() {\n if (list.length === 0) return;\n const visitor_id = visitorId();\n const dto: CreateTrackEventDTO = list.map((event) =>\n toDTO(event, visitor_id, event.settled ?? cache.tags ?? {})\n );\n if (!beacon(dto)) {\n void flush();\n return;\n }\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n list.splice(0).forEach((event) => event.options.onSucceed?.({ id: event.id, beacon: true }));\n}\n\nexport function sendBeacon<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n const visitor_id = visitorId();\n // No stored session means no event was ever queued from this storage, so there is no session\n // to report for — and one started here could never be announced. See `Session.extend`.\n const session_id = getSession().extend();\n if (!session_id) return;\n\n const dto: CreateTrackEventDTO = [\n {\n id: uuidv7(),\n name,\n properties,\n // Tags are worth less than the event carrying them: an empty set still reports the\n // engagement, and every field in `tagsSchema` is optional.\n tags: cache.tags ?? {},\n visitor_id,\n session_id,\n platform: config.platform,\n environment: config.environment,\n timestamp: new Date().toISOString(),\n },\n ];\n if (beacon(dto)) return;\n console.warn('Failed to send beacon', name, properties);\n}\n"],"mappings":";;;;;;;;AA4BA,MAAM,iBAA+B,CAAC;AAEtC,IAAI;;;;;;;AAQJ,SAAS,iBAAiB;CACxB,OAAQ,gBAAgB,IAAIA,cAAAA,YAAY;EAAE,MAAM;EAAG,UAAU;EAAI,WAAW;CAAE,CAAC;AACjF;;;;;;;;;;AA0CA,eAAe,cAAkC;CAC/C,IAAI;EACF,OAAO,MAAMC,oBAAAA,OAAO,QAAQ;CAC9B,SAAS,GAAY;EACnB,IAAI,aAAa,OAAO,QAAQ,IAAI,E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EA,SAAgB,WACd,MACA,YACA;CACA,MAAM,aAAaI,mBAAAA,UAAU;CAG7B,MAAM,aAAaF,sBAAAA,WAAW,CAAC,CAAC,OAAO;CACvC,IAAI,CAAC,YAAY;CAiBjB,IAAI,OAAO,CAdT;EACE,KAAA,GAAIC,KAAAA,GAAAA,CAAO;EACX;EACA;EAGA,MAAMH,oBAAAA,MAAM,QAAQ,CAAC;EACrB;EACA;EACA,UAAUD,oBAAAA,OAAO;EACjB,aAAaA,oBAAAA,OAAO;EACpB,4BAAW,IAAI,KAAK,EAAA,CAAE,YAAY;CACpC,CAEW,CAAC,GAAG;CACjB,QAAQ,KAAK,yBAAyB,MAAM,UAAU;AACxD"}
|
package/dist/track/index.d.cts
CHANGED
|
@@ -4,9 +4,13 @@ export interface TrackOptions {
|
|
|
4
4
|
enableThirdPartyTracking?: boolean;
|
|
5
5
|
/**
|
|
6
6
|
* Called once the server (or a beacon) has taken the event, with the event's id: the one
|
|
7
|
-
* generated when it was tracked, which the third-party trackers were given too.
|
|
7
|
+
* generated when it was tracked, which the third-party trackers were given too. `beacon` is
|
|
8
|
+
* set when the event went by `sendPendingEvents`: the browser queued it, but a beacon cannot
|
|
9
|
+
* tell delivered from dropped, so it is taken, not confirmed.
|
|
8
10
|
*/
|
|
9
|
-
onSucceed?: (response?: TrackEventResponse[number]
|
|
11
|
+
onSucceed?: (response?: TrackEventResponse[number] & {
|
|
12
|
+
beacon?: true;
|
|
13
|
+
}) => void;
|
|
10
14
|
onError?: (error: unknown) => void;
|
|
11
15
|
}
|
|
12
16
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.cts","names":[],"sources":["../../src/track/index.ts"],"mappings":";;iBAgBiB;EACf
|
|
1
|
+
{"version":3,"file":"index.d.cts","names":[],"sources":["../../src/track/index.ts"],"mappings":";;iBAgBiB;EACf;;;;;;;EAOA,aAAa,WAAW;IAA+B;;EACvD,WAAW;;;;;;;iBA2CI;EACf;EACA;;;wBA0Lc,WAAW,UAAU,YAAY,WAC/C,MAAM,UAAU,IAChB,YAAY,gBAAgB,gBAC5B,SAAS,cACT,OAAO;;;;;wBAeO,MAAM,UAAU,YAAY,WAC1C,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B,UAAS;;;;;;;;;;;;wBA0BK;wBAiBA,WAAW,UAAU,YAAY,WAC/C,MAAM,UAAU,IAChB,aAAa,gBAAgB"}
|
package/dist/track/index.d.mts
CHANGED
|
@@ -4,9 +4,13 @@ export interface TrackOptions {
|
|
|
4
4
|
enableThirdPartyTracking?: boolean;
|
|
5
5
|
/**
|
|
6
6
|
* Called once the server (or a beacon) has taken the event, with the event's id: the one
|
|
7
|
-
* generated when it was tracked, which the third-party trackers were given too.
|
|
7
|
+
* generated when it was tracked, which the third-party trackers were given too. `beacon` is
|
|
8
|
+
* set when the event went by `sendPendingEvents`: the browser queued it, but a beacon cannot
|
|
9
|
+
* tell delivered from dropped, so it is taken, not confirmed.
|
|
8
10
|
*/
|
|
9
|
-
onSucceed?: (response?: TrackEventResponse[number]
|
|
11
|
+
onSucceed?: (response?: TrackEventResponse[number] & {
|
|
12
|
+
beacon?: true;
|
|
13
|
+
}) => void;
|
|
10
14
|
onError?: (error: unknown) => void;
|
|
11
15
|
}
|
|
12
16
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/track/index.ts"],"mappings":";;iBAgBiB;EACf
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/track/index.ts"],"mappings":";;iBAgBiB;EACf;;;;;;;EAOA,aAAa,WAAW;IAA+B;;EACvD,WAAW;;;;;;;iBA2CI;EACf;EACA;;;wBA0Lc,WAAW,UAAU,YAAY,WAC/C,MAAM,UAAU,IAChB,YAAY,gBAAgB,gBAC5B,SAAS,cACT,OAAO;;;;;wBAeO,MAAM,UAAU,YAAY,WAC1C,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B,UAAS;;;;;;;;;;;;wBA0BK;wBAiBA,WAAW,UAAU,YAAY,WAC/C,MAAM,UAAU,IAChB,aAAa,gBAAgB"}
|
package/dist/track/index.mjs
CHANGED
|
@@ -214,7 +214,10 @@ function sendPendingEvents() {
|
|
|
214
214
|
clearTimeout(timer);
|
|
215
215
|
timer = null;
|
|
216
216
|
}
|
|
217
|
-
list.splice(0).forEach((event) => event.options.onSucceed?.({
|
|
217
|
+
list.splice(0).forEach((event) => event.options.onSucceed?.({
|
|
218
|
+
id: event.id,
|
|
219
|
+
beacon: true
|
|
220
|
+
}));
|
|
218
221
|
}
|
|
219
222
|
function sendBeacon(name, properties) {
|
|
220
223
|
const visitor_id = visitorId();
|
package/dist/track/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["uuidv7"],"sources":["../../src/track/index.ts"],"sourcesContent":["import { TokenBucket, fetch } from '@shware/utils';\nimport { v7 as uuidv7 } from 'uuid';\nimport type { CreateTrackEventDTO } from '../schema/index';\nimport { cache, config } from '../setup/index';\nimport { getSession } from '../setup/session';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { visitorId } from '../visitor/id';\nimport type {\n EventName,\n ThirdPartyTracker,\n TrackEventResponse,\n TrackName,\n TrackProperties,\n TrackTags,\n} from './types';\n\nexport interface TrackOptions {\n enableThirdPartyTracking?: boolean;\n /**\n * Called once the server (or a beacon) has taken the event, with the event's id: the one\n * generated when it was tracked, which the third-party trackers were given too.\n */\n onSucceed?: (response?: TrackEventResponse[number]) => void;\n onError?: (error: unknown) => void;\n}\n\nconst defaultOptions: TrackOptions = {};\n\nlet tokenBucket: TokenBucket | undefined;\n\n/**\n * The rate limiter, built on the first send rather than at module scope: its\n * constructor starts a refill `setInterval`, and Cloudflare Workers refuse to\n * set a timer outside a request handler for the same reason they refuse to\n * generate random values there — see `setup/session.ts`.\n */\nfunction getTokenBucket() {\n return (tokenBucket ??= new TokenBucket({ rate: 1, capacity: 20, requested: 2 }));\n}\n\ntype Item = {\n /**\n * The event's id, a uuidv7 generated when it is tracked. The server stores the event under it\n * (`on conflict (id) do nothing`, so a batch `fetch` retries is not stored twice), and the\n * third-party trackers are given it at once as their deduplication id — the id the server's\n * conversions API sends again for the same event.\n */\n id: string;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n name: TrackName<any>;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n properties: TrackProperties<any>;\n tags: Promise<TrackTags>;\n /** `tags` once settled: a page being hidden can await nothing, and sends what it has. */\n settled?: TrackTags;\n /** Decided when the event happens, as GA4 and PostHog decide it, never when it is sent. */\n session_id: string;\n timestamp: string;\n options: TrackOptions;\n};\n\n/**\n * How an event is created, for the SDK's own callers (`trackOnce`); not exported from the\n * package. `id` carries over the id of an earlier attempt at the same occurrence, and\n * `pixels: false` skips the third-party trackers that attempt has already fired.\n */\nexport interface EventInit {\n id?: string;\n pixels?: boolean;\n}\n\n/**\n * Tags belong to the moment the event happened, not to the moment its batch goes out: a queued\n * event waits up to `delay` ms, and a single page app can navigate in that window, which would\n * stamp every pending event with the URL of the page the user has already left.\n *\n * The promise then sits in the queue with nothing awaiting it, so a failure has to be absorbed\n * here — an unhandled rejection would surface as a global error long before `sendEvents` could\n * catch it. Falling back to the last built tags keeps the event, minus whatever changed since.\n */\nasync function captureTags(): Promise<TrackTags> {\n try {\n return await config.getTags();\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n return cache.tags ?? {};\n }\n}\n\n/**\n * The events not yet sent, and the only place they are: a batch leaves it at the moment it is\n * handed to `fetch` or to a beacon, never earlier. So when the page is hidden or left,\n * everything still unsent is right here for `sendPendingEvents`.\n */\nconst list: Item[] = [];\nconst batchSize = 10;\nconst delay = 2000;\nlet timer: ReturnType<typeof setTimeout> | null = null;\n\n/**\n * Hands the event to the third-party trackers now, as it is tracked, under its own id — not once\n * the server has answered. An event followed by a full-page navigation (an outbound link,\n * `begin_checkout` before the redirect to the payment page, a landing page left at once) reaches\n * the pixels before the page goes, and the server's conversions API, sending the same id, still\n * deduplicates against the browser event. A server that is down no longer takes the pixels down\n * with it either.\n *\n * A tracker that returns `false` is not ready — its pixel's global is not on the page yet, the\n * snippet still loading (the first `page_view` of a visit is tracked right as the page mounts).\n * Those trackers, and only those, are called once more on the next macrotask, with the same event\n * and id, after the inline snippets have had their turn; a tracker still not ready then is given\n * up on, as it was when it ran after the server's answer. Never more than once: a pixel's global\n * either exists by then or the script is blocked.\n */\nfunction firePixels(event: Item) {\n // An explicit false, not falsiness: a caller passing `{ onSucceed }` replaces the options\n // object wholesale, and leaving the flag out must not silently switch forwarding off.\n if (event.options.enableThirdPartyTracking === false || IGNORED_EVENTS.includes(event.name)) {\n return;\n }\n const notReady = callTrackers(config.thirdPartyTrackers, event);\n if (notReady.length === 0) return;\n setTimeout(() => callTrackers(notReady, event), 0);\n}\n\n/** Calls each tracker with the event; returns the ones that said they were not ready. */\nfunction callTrackers(trackers: ThirdPartyTracker[], event: Item): ThirdPartyTracker[] {\n return trackers.filter((tracker) => {\n try {\n return tracker(event.name, event.properties, event.id) === false;\n } catch (e: unknown) {\n // A third-party script does not get to take the tracking call, or the other trackers, with it.\n if (e instanceof Error) console.log(e.message);\n return false;\n }\n });\n}\n\n/**\n * Queues an event, preceded by a `session_start` when it is the one that opens a session, and\n * fires its third-party trackers.\n *\n * The session is decided here, when the event happens, as GA4 and PostHog decide it: the\n * `session_start` then sits in the queue right before the event that opened the session, so\n * wherever that event goes — a batch, a beacon, a retry — its announcement has gone ahead of it.\n * It carries that event's tags and time, as GA4 derives it from the hit that started the\n * session: the landing page is where the session began, whatever the page has navigated to by\n * the time the batch goes out.\n */\nfunction enqueue(\n name: Item['name'],\n properties: Item['properties'],\n options: TrackOptions,\n init: EventInit = {}\n): Item {\n const timestamp = new Date().toISOString();\n const tags = captureTags();\n const { id: session_id, started } = getSession().touch(Date.parse(timestamp));\n const item = (fields: Pick<Item, 'id' | 'name' | 'properties' | 'options'>): Item => {\n const result: Item = { ...fields, tags, timestamp, session_id };\n void tags.then((settled) => (result.settled = settled));\n return result;\n };\n if (started) {\n const options = { enableThirdPartyTracking: false };\n list.push(item({ id: uuidv7(), name: 'session_start', properties: {}, options }));\n }\n const event = item({ id: init.id ?? uuidv7(), name, properties, options });\n list.push(event);\n if (init.pixels !== false) firePixels(event);\n return event;\n}\n\nfunction toDTO(event: Item, visitor_id: string, tags: TrackTags): CreateTrackEventDTO[number] {\n return {\n id: event.id,\n name: event.name,\n properties: event.properties,\n tags,\n visitor_id,\n session_id: event.session_id,\n platform: config.platform,\n environment: config.environment,\n timestamp: event.timestamp,\n };\n}\n\n/**\n * Sends the queue. Everything that has to be awaited is awaited first, and only then are the\n * events taken off the queue and handed to `fetch` in the same synchronous step — so there is\n * no moment at which an event is neither queued nor sent.\n */\nasync function flush() {\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n if (list.length === 0) return;\n\n let events: Item[] = [];\n try {\n await getTokenBucket().removeTokens();\n const visitor_id = visitorId();\n const headers = await config.getHeaders();\n // Settled before the events leave the queue; those queued meanwhile are a microtask away.\n await Promise.all(list.map((event) => event.tags));\n\n events = list.splice(0);\n if (events.length === 0) return;\n const dto: CreateTrackEventDTO = await Promise.all(\n events.map(async (event) => toDTO(event, visitor_id, await event.tags))\n );\n\n const body = JSON.stringify(dto);\n const response = await fetch(`${config.endpoint}/events`, {\n method: 'POST',\n credentials: 'include',\n // Retried although a POST: every event carries its client-generated id, and the server stores\n // a batch it already has `on conflict (id) do nothing`.\n retries: 3,\n // keepalive lets the request survive the page being unloaded mid-flight, within a 64KB\n // budget shared by every such request of the page; a body that could not fit goes as a\n // plain POST rather than failing outright.\n keepalive: body.length < 60_000,\n headers,\n body,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to send track event: ${response.status} ${await response.text()}`);\n }\n\n // The body is not read. Every event has had its id since it was tracked, and its trackers\n // were fired with it then. Servers still answer one `{ id }` per event (`TrackEventResponse`),\n // which a server predating client ids fills with ids of its own; neither is needed here, and\n // an answer that is not even JSON does not turn a stored batch into a failure.\n events.forEach((event) => event.options.onSucceed?.({ id: event.id }));\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n // `fetch` has already retried the transient failures by the time a batch fails here; what\n // remains is a batch the server rejected outright — one invalid event fails the whole batch\n // — or a network that stayed down past the retries. The other events are reported lost;\n // `session_start` alone goes back on the queue for the next send, because it is the\n // session's only attribution record: a session without one has no channel, and its every\n // later event drops out of an attribution join.\n const starts = events.filter((event) => event.name === 'session_start');\n list.unshift(...starts);\n events\n .filter((event) => event.name !== 'session_start')\n .forEach((event) => event.options.onError?.(e));\n }\n}\n\n/** `track`, with the `EventInit` only the SDK itself passes. */\nexport function queueEvent<T extends EventName = EventName>(\n name: TrackName<T>,\n properties: TrackProperties<T> | undefined,\n options: TrackOptions,\n init?: EventInit\n) {\n enqueue(name, properties, options, init);\n if (list.length >= batchSize) {\n void flush();\n return;\n }\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => void flush(), delay);\n}\n\n/**\n * Queues the event for the next batch — up to 2 s away, at once when the batch is full — and\n * hands it to the third-party trackers now, under the id it is sent with.\n */\nexport function track<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n options: TrackOptions = defaultOptions\n) {\n queueEvent(name, properties, options);\n}\n\nfunction beacon(dto: CreateTrackEventDTO): boolean {\n // Not every runtime with a `navigator` has it: React Native has neither beacons nor pages.\n if (typeof navigator === 'undefined' || !('sendBeacon' in navigator)) return false;\n // text/plain keeps a cross-origin beacon a CORS simple request: as application/json it needs a\n // preflight, which a page being closed often cannot complete, and the beacon is then dropped.\n // The server reads it as JSON (`zBeaconJson` in @shware/http).\n const blob = new Blob([JSON.stringify(dto)], { type: 'text/plain;charset=UTF-8' });\n return navigator.sendBeacon(`${config.endpoint}/events`, blob);\n}\n\n/**\n * Sends the queue by beacon, now: for when the page is hidden or left, the last moment its\n * script is sure to run — what PostHog's `requestQueue.unload()` and GA4 do on the same events.\n * Call it before the engagement beacon: a new session's `session_start` is in this queue.\n *\n * Nothing can be awaited here, so the events go with the tags they have settled on (the last\n * built ones otherwise). Each goes with the id it was tracked with, and its third-party trackers\n * were fired then, under that id: none is fired again here. The visitor id is local\n * (`visitorId`), so a first visit left within a second is sent like any other; when no beacon\n * can take them — no `sendBeacon`, a refused body — they stay queued for the usual send.\n */\nexport function sendPendingEvents() {\n if (list.length === 0) return;\n const visitor_id = visitorId();\n const dto: CreateTrackEventDTO = list.map((event) =>\n toDTO(event, visitor_id, event.settled ?? cache.tags ?? {})\n );\n if (!beacon(dto)) {\n void flush();\n return;\n }\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n list.splice(0).forEach((event) => event.options.onSucceed?.({ id: event.id }));\n}\n\nexport function sendBeacon<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n const visitor_id = visitorId();\n // No stored session means no event was ever queued from this storage, so there is no session\n // to report for — and one started here could never be announced. See `Session.extend`.\n const session_id = getSession().extend();\n if (!session_id) return;\n\n const dto: CreateTrackEventDTO = [\n {\n id: uuidv7(),\n name,\n properties,\n // Tags are worth less than the event carrying them: an empty set still reports the\n // engagement, and every field in `tagsSchema` is optional.\n tags: cache.tags ?? {},\n visitor_id,\n session_id,\n platform: config.platform,\n environment: config.environment,\n timestamp: new Date().toISOString(),\n },\n ];\n if (beacon(dto)) return;\n console.warn('Failed to send beacon', name, properties);\n}\n"],"mappings":";;;;;;;AA0BA,MAAM,iBAA+B,CAAC;AAEtC,IAAI;;;;;;;AAQJ,SAAS,iBAAiB;CACxB,OAAQ,gBAAgB,IAAI,YAAY;EAAE,MAAM;EAAG,UAAU;EAAI,WAAW;CAAE,CAAC;AACjF;;;;;;;;;;AA0CA,eAAe,cAAkC;CAC/C,IAAI;EACF,OAAO,MAAM,OAAO,QAAQ;CAC9B,SAAS,GAAY;EACnB,IAAI,aAAa,OAAO,QAAQ,IAAI,EAAE,OAAO;EAC7C,OAAO,MAAM,Q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OAAO;EACjB,aAAa,OAAO;EACpB,4BAAW,IAAI,KAAK,EAAA,CAAE,YAAY;CACpC,CAEW,CAAC,GAAG;CACjB,QAAQ,KAAK,yBAAyB,MAAM,UAAU;AACxD"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["uuidv7"],"sources":["../../src/track/index.ts"],"sourcesContent":["import { TokenBucket, fetch } from '@shware/utils';\nimport { v7 as uuidv7 } from 'uuid';\nimport type { CreateTrackEventDTO } from '../schema/index';\nimport { cache, config } from '../setup/index';\nimport { getSession } from '../setup/session';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { visitorId } from '../visitor/id';\nimport type {\n EventName,\n ThirdPartyTracker,\n TrackEventResponse,\n TrackName,\n TrackProperties,\n TrackTags,\n} from './types';\n\nexport interface TrackOptions {\n enableThirdPartyTracking?: boolean;\n /**\n * Called once the server (or a beacon) has taken the event, with the event's id: the one\n * generated when it was tracked, which the third-party trackers were given too. `beacon` is\n * set when the event went by `sendPendingEvents`: the browser queued it, but a beacon cannot\n * tell delivered from dropped, so it is taken, not confirmed.\n */\n onSucceed?: (response?: TrackEventResponse[number] & { beacon?: true }) => void;\n onError?: (error: unknown) => void;\n}\n\nconst defaultOptions: TrackOptions = {};\n\nlet tokenBucket: TokenBucket | undefined;\n\n/**\n * The rate limiter, built on the first send rather than at module scope: its\n * constructor starts a refill `setInterval`, and Cloudflare Workers refuse to\n * set a timer outside a request handler for the same reason they refuse to\n * generate random values there — see `setup/session.ts`.\n */\nfunction getTokenBucket() {\n return (tokenBucket ??= new TokenBucket({ rate: 1, capacity: 20, requested: 2 }));\n}\n\ntype Item = {\n /**\n * The event's id, a uuidv7 generated when it is tracked. The server stores the event under it\n * (`on conflict (id) do nothing`, so a batch `fetch` retries is not stored twice), and the\n * third-party trackers are given it at once as their deduplication id — the id the server's\n * conversions API sends again for the same event.\n */\n id: string;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n name: TrackName<any>;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n properties: TrackProperties<any>;\n tags: Promise<TrackTags>;\n /** `tags` once settled: a page being hidden can await nothing, and sends what it has. */\n settled?: TrackTags;\n /** Decided when the event happens, as GA4 and PostHog decide it, never when it is sent. */\n session_id: string;\n timestamp: string;\n options: TrackOptions;\n};\n\n/**\n * How an event is created, for the SDK's own callers (`trackOnce`); not exported from the\n * package. `id` carries over the id of an earlier attempt at the same occurrence, and\n * `pixels: false` skips the third-party trackers that attempt has already fired.\n */\nexport interface EventInit {\n id?: string;\n pixels?: boolean;\n}\n\n/**\n * Tags belong to the moment the event happened, not to the moment its batch goes out: a queued\n * event waits up to `delay` ms, and a single page app can navigate in that window, which would\n * stamp every pending event with the URL of the page the user has already left.\n *\n * The promise then sits in the queue with nothing awaiting it, so a failure has to be absorbed\n * here — an unhandled rejection would surface as a global error long before `sendEvents` could\n * catch it. Falling back to the last built tags keeps the event, minus whatever changed since.\n */\nasync function captureTags(): Promise<TrackTags> {\n try {\n return await config.getTags();\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n return cache.tags ?? {};\n }\n}\n\n/**\n * The events not yet sent, and the only place they are: a batch leaves it at the moment it is\n * handed to `fetch` or to a beacon, never earlier. So when the page is hidden or left,\n * everything still unsent is right here for `sendPendingEvents`.\n */\nconst list: Item[] = [];\nconst batchSize = 10;\nconst delay = 2000;\nlet timer: ReturnType<typeof setTimeout> | null = null;\n\n/**\n * Hands the event to the third-party trackers now, as it is tracked, under its own id — not once\n * the server has answered. An event followed by a full-page navigation (an outbound link,\n * `begin_checkout` before the redirect to the payment page, a landing page left at once) reaches\n * the pixels before the page goes, and the server's conversions API, sending the same id, still\n * deduplicates against the browser event. A server that is down no longer takes the pixels down\n * with it either.\n *\n * A tracker that returns `false` is not ready — its pixel's global is not on the page yet, the\n * snippet still loading (the first `page_view` of a visit is tracked right as the page mounts).\n * Those trackers, and only those, are called once more on the next macrotask, with the same event\n * and id, after the inline snippets have had their turn; a tracker still not ready then is given\n * up on, as it was when it ran after the server's answer. Never more than once: a pixel's global\n * either exists by then or the script is blocked.\n */\nfunction firePixels(event: Item) {\n // An explicit false, not falsiness: a caller passing `{ onSucceed }` replaces the options\n // object wholesale, and leaving the flag out must not silently switch forwarding off.\n if (event.options.enableThirdPartyTracking === false || IGNORED_EVENTS.includes(event.name)) {\n return;\n }\n const notReady = callTrackers(config.thirdPartyTrackers, event);\n if (notReady.length === 0) return;\n setTimeout(() => callTrackers(notReady, event), 0);\n}\n\n/** Calls each tracker with the event; returns the ones that said they were not ready. */\nfunction callTrackers(trackers: ThirdPartyTracker[], event: Item): ThirdPartyTracker[] {\n return trackers.filter((tracker) => {\n try {\n return tracker(event.name, event.properties, event.id) === false;\n } catch (e: unknown) {\n // A third-party script does not get to take the tracking call, or the other trackers, with it.\n if (e instanceof Error) console.log(e.message);\n return false;\n }\n });\n}\n\n/**\n * Queues an event, preceded by a `session_start` when it is the one that opens a session, and\n * fires its third-party trackers.\n *\n * The session is decided here, when the event happens, as GA4 and PostHog decide it: the\n * `session_start` then sits in the queue right before the event that opened the session, so\n * wherever that event goes — a batch, a beacon, a retry — its announcement has gone ahead of it.\n * It carries that event's tags and time, as GA4 derives it from the hit that started the\n * session: the landing page is where the session began, whatever the page has navigated to by\n * the time the batch goes out.\n */\nfunction enqueue(\n name: Item['name'],\n properties: Item['properties'],\n options: TrackOptions,\n init: EventInit = {}\n): Item {\n const timestamp = new Date().toISOString();\n const tags = captureTags();\n const { id: session_id, started } = getSession().touch(Date.parse(timestamp));\n const item = (fields: Pick<Item, 'id' | 'name' | 'properties' | 'options'>): Item => {\n const result: Item = { ...fields, tags, timestamp, session_id };\n void tags.then((settled) => (result.settled = settled));\n return result;\n };\n if (started) {\n const options = { enableThirdPartyTracking: false };\n list.push(item({ id: uuidv7(), name: 'session_start', properties: {}, options }));\n }\n const event = item({ id: init.id ?? uuidv7(), name, properties, options });\n list.push(event);\n if (init.pixels !== false) firePixels(event);\n return event;\n}\n\nfunction toDTO(event: Item, visitor_id: string, tags: TrackTags): CreateTrackEventDTO[number] {\n return {\n id: event.id,\n name: event.name,\n properties: event.properties,\n tags,\n visitor_id,\n session_id: event.session_id,\n platform: config.platform,\n environment: config.environment,\n timestamp: event.timestamp,\n };\n}\n\n/**\n * Sends the queue. Everything that has to be awaited is awaited first, and only then are the\n * events taken off the queue and handed to `fetch` in the same synchronous step — so there is\n * no moment at which an event is neither queued nor sent.\n */\nasync function flush() {\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n if (list.length === 0) return;\n\n let events: Item[] = [];\n try {\n await getTokenBucket().removeTokens();\n const visitor_id = visitorId();\n const headers = await config.getHeaders();\n // Settled before the events leave the queue; those queued meanwhile are a microtask away.\n await Promise.all(list.map((event) => event.tags));\n\n events = list.splice(0);\n if (events.length === 0) return;\n const dto: CreateTrackEventDTO = await Promise.all(\n events.map(async (event) => toDTO(event, visitor_id, await event.tags))\n );\n\n const body = JSON.stringify(dto);\n const response = await fetch(`${config.endpoint}/events`, {\n method: 'POST',\n credentials: 'include',\n // Retried although a POST: every event carries its client-generated id, and the server stores\n // a batch it already has `on conflict (id) do nothing`.\n retries: 3,\n // keepalive lets the request survive the page being unloaded mid-flight, within a 64KB\n // budget shared by every such request of the page; a body that could not fit goes as a\n // plain POST rather than failing outright.\n keepalive: body.length < 60_000,\n headers,\n body,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to send track event: ${response.status} ${await response.text()}`);\n }\n\n // The body is not read. Every event has had its id since it was tracked, and its trackers\n // were fired with it then. Servers still answer one `{ id }` per event (`TrackEventResponse`),\n // which a server predating client ids fills with ids of its own; neither is needed here, and\n // an answer that is not even JSON does not turn a stored batch into a failure.\n events.forEach((event) => event.options.onSucceed?.({ id: event.id }));\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n // `fetch` has already retried the transient failures by the time a batch fails here; what\n // remains is a batch the server rejected outright — one invalid event fails the whole batch\n // — or a network that stayed down past the retries. The other events are reported lost;\n // `session_start` alone goes back on the queue for the next send, because it is the\n // session's only attribution record: a session without one has no channel, and its every\n // later event drops out of an attribution join.\n const starts = events.filter((event) => event.name === 'session_start');\n list.unshift(...starts);\n events\n .filter((event) => event.name !== 'session_start')\n .forEach((event) => event.options.onError?.(e));\n }\n}\n\n/** `track`, with the `EventInit` only the SDK itself passes. */\nexport function queueEvent<T extends EventName = EventName>(\n name: TrackName<T>,\n properties: TrackProperties<T> | undefined,\n options: TrackOptions,\n init?: EventInit\n) {\n enqueue(name, properties, options, init);\n if (list.length >= batchSize) {\n void flush();\n return;\n }\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => void flush(), delay);\n}\n\n/**\n * Queues the event for the next batch — up to 2 s away, at once when the batch is full — and\n * hands it to the third-party trackers now, under the id it is sent with.\n */\nexport function track<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n options: TrackOptions = defaultOptions\n) {\n queueEvent(name, properties, options);\n}\n\nfunction beacon(dto: CreateTrackEventDTO): boolean {\n // Not every runtime with a `navigator` has it: React Native has neither beacons nor pages.\n if (typeof navigator === 'undefined' || !('sendBeacon' in navigator)) return false;\n // text/plain keeps a cross-origin beacon a CORS simple request: as application/json it needs a\n // preflight, which a page being closed often cannot complete, and the beacon is then dropped.\n // The server reads it as JSON (`zBeaconJson` in @shware/http).\n const blob = new Blob([JSON.stringify(dto)], { type: 'text/plain;charset=UTF-8' });\n return navigator.sendBeacon(`${config.endpoint}/events`, blob);\n}\n\n/**\n * Sends the queue by beacon, now: for when the page is hidden or left, the last moment its\n * script is sure to run — what PostHog's `requestQueue.unload()` and GA4 do on the same events.\n * Call it before the engagement beacon: a new session's `session_start` is in this queue.\n *\n * Nothing can be awaited here, so the events go with the tags they have settled on (the last\n * built ones otherwise). Each goes with the id it was tracked with, and its third-party trackers\n * were fired then, under that id: none is fired again here. The visitor id is local\n * (`visitorId`), so a first visit left within a second is sent like any other; when no beacon\n * can take them — no `sendBeacon`, a refused body — they stay queued for the usual send.\n */\nexport function sendPendingEvents() {\n if (list.length === 0) return;\n const visitor_id = visitorId();\n const dto: CreateTrackEventDTO = list.map((event) =>\n toDTO(event, visitor_id, event.settled ?? cache.tags ?? {})\n );\n if (!beacon(dto)) {\n void flush();\n return;\n }\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n list.splice(0).forEach((event) => event.options.onSucceed?.({ id: event.id, beacon: true }));\n}\n\nexport function sendBeacon<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n const visitor_id = visitorId();\n // No stored session means no event was ever queued from this storage, so there is no session\n // to report for — and one started here could never be announced. See `Session.extend`.\n const session_id = getSession().extend();\n if (!session_id) return;\n\n const dto: CreateTrackEventDTO = [\n {\n id: uuidv7(),\n name,\n properties,\n // Tags are worth less than the event carrying them: an empty set still reports the\n // engagement, and every field in `tagsSchema` is optional.\n tags: cache.tags ?? {},\n visitor_id,\n session_id,\n platform: config.platform,\n environment: config.environment,\n timestamp: new Date().toISOString(),\n },\n ];\n if (beacon(dto)) return;\n console.warn('Failed to send beacon', name, properties);\n}\n"],"mappings":";;;;;;;AA4BA,MAAM,iBAA+B,CAAC;AAEtC,IAAI;;;;;;;AAQJ,SAAS,iBAAiB;CACxB,OAAQ,gBAAgB,IAAI,YAAY;EAAE,MAAM;EAAG,UAAU;EAAI,WAAW;CAAE,CAAC;AACjF;;;;;;;;;;AA0CA,eAAe,cAAkC;CAC/C,IAAI;EACF,OAAO,MAAM,OAAO,QAAQ;CAC9B,SAAS,GAAY;EACnB,IAAI,aAAa,OAAO,QAAQ,IAAI,EAAE,OAAO;EAC7C,OAAO,MAAM,QAAQ,CAAC;CACxB;AACF;;;;;;AAOA,MAAM,OAAe,CAAC;AACtB,MAAM,YAAY;AAClB,MAAM,QAAQ;AACd,IAAI,QAA8C;;;;;;;;;;;;;;;;AAiBlD,SAAS,WAAW,OAAa;CAG/B,IAAI,MAAM,QAAQ,6BAA6B,SAAS,eAAe,SAAS,MAAM,IAAI,GACxF;CAEF,MAAM,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sent in `config.storage` only once the event has been sent (`onSucceed`), so a
|
|
102
102
|
* send that fails is tried again by the next call instead of being lost — under the same event id,
|
|
103
103
|
* so the third-party trackers fired by the first call are not fired again (see `VERSION`); within
|
|
104
|
-
* one page a key already queued is not queued twice.
|
|
104
|
+
* one page a key already queued is not queued twice.
|
|
105
|
+
*
|
|
106
|
+
* An event that leaves by beacon (`sendPendingEvents`, the page hidden or left) is not marked
|
|
107
|
+
* sent: a beacon cannot tell delivered from dropped, so it counts as unconfirmed and the entry
|
|
108
|
+
* stays unsent with its id. The next call for the key — the result page opened again — sends the
|
|
109
|
+
* event once more under that id and without pixels, which the server ignores when the beacon did
|
|
110
|
+
* arrive (it drops an event id it already has): one idempotent request more, against a lost one. When the storage cannot be read or written
|
|
105
111
|
* the event is tracked anyway: a rare duplicate is better than a lost conversion.
|
|
106
112
|
*
|
|
107
113
|
* Deduplication is per device and storage. A second device still reports its own occurrence, so
|
|
@@ -131,6 +137,10 @@ function trackOnce(name, properties, { key, ttl = DEFAULT_TTL, ...options }) {
|
|
|
131
137
|
...options,
|
|
132
138
|
onSucceed: (response) => {
|
|
133
139
|
clearPending(name, key);
|
|
140
|
+
if (response?.beacon) {
|
|
141
|
+
options.onSucceed?.(response);
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
134
144
|
try {
|
|
135
145
|
write(name, [...live(read(name), Date.now()).filter((entry) => entry.key !== key), {
|
|
136
146
|
key,
|
package/dist/track/once.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"once.cjs","names":["config","uuidv7"],"sources":["../../src/track/once.ts"],"sourcesContent":["import { v7 as uuidv7 } from 'uuid';\nimport { config } from '../setup/index';\nimport { type TrackOptions, queueEvent } from './index';\nimport type { EventName, TrackName, TrackProperties } from './types';\n\nexport interface TrackOnceOptions extends TrackOptions {\n /**\n * What makes this occurrence the same one again: a checkout session id for `purchase`, an order\n * id, a transaction id. Required, never derived from the properties, so the caller decides what\n * \"once\" means. The same key under another event name is a different occurrence.\n */\n key: string;\n /** How long a sent key is remembered, in milliseconds. 90 days by default. */\n ttl?: number;\n}\n\nconst DEFAULT_TTL = 90 * 24 * 60 * 60 * 1000;\n/** Keys remembered per event name; the oldest are forgotten first. */\nconst MAX_ENTRIES = 20;\n\n/**\n * `{\"v\":2,\"entries\":[[key, id, expiresAt, sent], …]}`, oldest first. Entries are tuples in an\n * array rather than an object keyed by `key`: an object would move integer-like keys (\"123\") to\n * the front and lose the order the oldest are dropped by. Escaping the value for the medium is the\n * storage's job, so this is plain JSON.\n *\n * `id` is the event id the key goes out under, decided by the first call and kept while `sent`\n * is false — a send that failed, or a page reloaded before its batch went out. The third-party\n * trackers fire when the event is tracked, not when it is sent, so that first call has already\n * reported the occurrence to them: the next call reuses the id, fires none of them again, and\n * the server (`on conflict (id) do nothing`) stores the event once even if the failed send had in\n * fact arrived.\n *\n * Version 1 records (`[key, expiresAt]`, written before the id was kept) are read as sent: that\n * is all a v1 record ever held, and dropping them would report every remembered occurrence again.\n */\nconst VERSION = 2;\n\ntype Entry = { key: string; id: string; expiresAt: number; sent: boolean };\n\nfunction storageKey(name: string) {\n return `track_once.${name}`;\n}\n\n/** The stored entries, or none for a record that is missing, of another version or malformed. */\nfunction read(name: string): Entry[] {\n const raw = config.storage.getItem(storageKey(name));\n if (!raw) return [];\n let record: unknown;\n try {\n record = JSON.parse(raw);\n } catch {\n return [];\n }\n if (typeof record !== 'object' || record === null) return [];\n const { v, entries } = record as { v?: unknown; entries?: unknown };\n if (!Array.isArray(entries)) return [];\n if (v === 1) {\n return entries.flatMap((entry: unknown) => {\n if (!Array.isArray(entry)) return [];\n const [key, expiresAt] = entry as unknown[];\n if (typeof key !== 'string' || typeof expiresAt !== 'number') return [];\n // Sent is all v1 remembered; the id it went out under is gone, and no longer needed.\n return [{ key, id: '', expiresAt, sent: true }];\n });\n }\n if (v !== VERSION) return [];\n return entries.flatMap((entry: unknown) => {\n if (!Array.isArray(entry)) return [];\n const [key, id, expiresAt, sent] = entry as unknown[];\n if (typeof key !== 'string' || typeof id !== 'string' || typeof expiresAt !== 'number') {\n return [];\n }\n if (typeof sent !== 'boolean') return [];\n return [{ key, id, expiresAt, sent }];\n });\n}\n\nfunction write(name: string, entries: Entry[]) {\n const record = {\n v: VERSION,\n entries: entries.slice(-MAX_ENTRIES).map((e) => [e.key, e.id, e.expiresAt, e.sent]),\n };\n config.storage.setItem(storageKey(name), JSON.stringify(record));\n}\n\nfunction live(entries: Entry[], now: number) {\n return entries.filter((entry) => entry.expiresAt > now);\n}\n\n/** Keys queued in this page (or app process) but not confirmed sent yet, per event name. */\nconst pending = new Map<string, Set<string>>();\n\nfunction isPending(name: string, key: string) {\n return pending.get(name)?.has(key) ?? false;\n}\n\nfunction markPending(name: string, key: string) {\n const keys = pending.get(name);\n if (keys) keys.add(key);\n else pending.set(name, new Set([key]));\n}\n\nfunction clearPending(name: string, key: string) {\n const keys = pending.get(name);\n if (!keys) return;\n keys.delete(key);\n if (keys.size === 0) pending.delete(name);\n}\n\n/**\n * Tracks an event at most once per `key`: a reloaded or revisited payment result page, a\n * re-delivered store transaction, a confirmation screen opened twice. Returns whether the event\n * was queued.\n *\n * The key is marked sent in `config.storage` only once the event has been sent (`onSucceed`), so a\n * send that fails is tried again by the next call instead of being lost — under the same event id,\n * so the third-party trackers fired by the first call are not fired again (see `VERSION`); within\n * one page a key already queued is not queued twice. When the storage cannot be read or written\n * the event is tracked anyway: a rare duplicate is better than a lost conversion.\n *\n * Deduplication is per device and storage. A second device still reports its own occurrence, so\n * figures that must be exact (revenue) belong to server-side records.\n */\nexport function trackOnce<T extends EventName = EventName>(\n name: TrackName<T>,\n properties: TrackProperties<T> | undefined,\n { key, ttl = DEFAULT_TTL, ...options }: TrackOnceOptions\n): boolean {\n if (isPending(name, key)) return false;\n\n const now = Date.now();\n // An earlier call that failed to send: its id, and its pixels already fired.\n let earlier: Entry | undefined;\n let id = uuidv7();\n try {\n const entries = live(read(name), now);\n earlier = entries.find((entry) => entry.key === key);\n if (earlier?.sent) return false;\n if (earlier) id = earlier.id;\n else write(name, [...entries, { key, id, expiresAt: now + ttl, sent: false }]);\n } catch (e: unknown) {\n // Unrecorded, a failed send would fire the pixels again on the next call: a rare duplicate\n // there beats not tracking.\n if (e instanceof Error) console.log(e.message);\n }\n\n markPending(name, key);\n queueEvent(\n name,\n properties,\n {\n ...options,\n onSucceed: (response) => {\n clearPending(name, key);\n try {\n const entries = live(read(name), Date.now()).filter((entry) => entry.key !== key);\n write(name, [...entries, { key, id, expiresAt: Date.now() + ttl, sent: true }]);\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n }\n options.onSucceed?.(response);\n },\n onError: (error) => {\n // Not sent: the entry stays unsent, with its id, so a later call can try again.\n clearPending(name, key);\n options.onError?.(error);\n },\n },\n earlier ? { id, pixels: false } : { id }\n );\n return true;\n}\n"],"mappings":";;;;;AAgBA,MAAM,cAAc;;;;;;;;;;;;;;;;;AAoBpB,MAAM,UAAU;AAIhB,SAAS,WAAW,MAAc;CAChC,OAAO,cAAc;AACvB;;AAGA,SAAS,KAAK,MAAuB;CACnC,MAAM,MAAMA,oBAAAA,OAAO,QAAQ,QAAQ,WAAW,IAAI,CAAC;CACnD,IAAI,CAAC,KAAK,OAAO,CAAC;CAClB,IAAI;CACJ,IAAI;EACF,SAAS,KAAK,MAAM,GAAG;CACzB,QAAQ;EACN,OAAO,CAAC;CACV;CACA,IAAI,OAAO,WAAW,YAAY,WAAW,MAAM,OAAO,CAAC;CAC3D,MAAM,EAAE,GAAG,YAAY;CACvB,IAAI,CAAC,MAAM,QAAQ,OAAO,GAAG,OAAO,CAAC;CACrC,IAAI,MAAM,GACR,OAAO,QAAQ,SAAS,UAAmB;EACzC,IAAI,CAAC,MAAM,QAAQ,KAAK,GAAG,OAAO,CAAC;EACnC,MAAM,CAAC,KAAK,aAAa;EACzB,IAAI,OAAO,QAAQ,YAAY,OAAO,cAAc,UAAU,OAAO,CAAC;EAEtE,OAAO,CAAC;GA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uuidv7 } from 'uuid';\nimport { config } from '../setup/index';\nimport { type TrackOptions, queueEvent } from './index';\nimport type { EventName, TrackName, TrackProperties } from './types';\n\nexport interface TrackOnceOptions extends TrackOptions {\n /**\n * What makes this occurrence the same one again: a checkout session id for `purchase`, an order\n * id, a transaction id. Required, never derived from the properties, so the caller decides what\n * \"once\" means. The same key under another event name is a different occurrence.\n */\n key: string;\n /** How long a sent key is remembered, in milliseconds. 90 days by default. */\n ttl?: number;\n}\n\nconst DEFAULT_TTL = 90 * 24 * 60 * 60 * 1000;\n/** Keys remembered per event name; the oldest are forgotten first. */\nconst MAX_ENTRIES = 20;\n\n/**\n * `{\"v\":2,\"entries\":[[key, id, expiresAt, sent], …]}`, oldest first. Entries are tuples in an\n * array rather than an object keyed by `key`: an object would move integer-like keys (\"123\") to\n * the front and lose the order the oldest are dropped by. Escaping the value for the medium is the\n * storage's job, so this is plain JSON.\n *\n * `id` is the event id the key goes out under, decided by the first call and kept while `sent`\n * is false — a send that failed, or a page reloaded before its batch went out. The third-party\n * trackers fire when the event is tracked, not when it is sent, so that first call has already\n * reported the occurrence to them: the next call reuses the id, fires none of them again, and\n * the server (`on conflict (id) do nothing`) stores the event once even if the failed send had in\n * fact arrived.\n *\n * Version 1 records (`[key, expiresAt]`, written before the id was kept) are read as sent: that\n * is all a v1 record ever held, and dropping them would report every remembered occurrence again.\n */\nconst VERSION = 2;\n\ntype Entry = { key: string; id: string; expiresAt: number; sent: boolean };\n\nfunction storageKey(name: string) {\n return `track_once.${name}`;\n}\n\n/** The stored entries, or none for a record that is missing, of another version or malformed. */\nfunction read(name: string): Entry[] {\n const raw = config.storage.getItem(storageKey(name));\n if (!raw) return [];\n let record: unknown;\n try {\n record = JSON.parse(raw);\n } catch {\n return [];\n }\n if (typeof record !== 'object' || record === null) return [];\n const { v, entries } = record as { v?: unknown; entries?: unknown };\n if (!Array.isArray(entries)) return [];\n if (v === 1) {\n return entries.flatMap((entry: unknown) => {\n if (!Array.isArray(entry)) return [];\n const [key, expiresAt] = entry as unknown[];\n if (typeof key !== 'string' || typeof expiresAt !== 'number') return [];\n // Sent is all v1 remembered; the id it went out under is gone, and no longer needed.\n return [{ key, id: '', expiresAt, sent: true }];\n });\n }\n if (v !== VERSION) return [];\n return entries.flatMap((entry: unknown) => {\n if (!Array.isArray(entry)) return [];\n const [key, id, expiresAt, sent] = entry as unknown[];\n if (typeof key !== 'string' || typeof id !== 'string' || typeof expiresAt !== 'number') {\n return [];\n }\n if (typeof sent !== 'boolean') return [];\n return [{ key, id, expiresAt, sent }];\n });\n}\n\nfunction write(name: string, entries: Entry[]) {\n const record = {\n v: VERSION,\n entries: entries.slice(-MAX_ENTRIES).map((e) => [e.key, e.id, e.expiresAt, e.sent]),\n };\n config.storage.setItem(storageKey(name), JSON.stringify(record));\n}\n\nfunction live(entries: Entry[], now: number) {\n return entries.filter((entry) => entry.expiresAt > now);\n}\n\n/** Keys queued in this page (or app process) but not confirmed sent yet, per event name. */\nconst pending = new Map<string, Set<string>>();\n\nfunction isPending(name: string, key: string) {\n return pending.get(name)?.has(key) ?? false;\n}\n\nfunction markPending(name: string, key: string) {\n const keys = pending.get(name);\n if (keys) keys.add(key);\n else pending.set(name, new Set([key]));\n}\n\nfunction clearPending(name: string, key: string) {\n const keys = pending.get(name);\n if (!keys) return;\n keys.delete(key);\n if (keys.size === 0) pending.delete(name);\n}\n\n/**\n * Tracks an event at most once per `key`: a reloaded or revisited payment result page, a\n * re-delivered store transaction, a confirmation screen opened twice. Returns whether the event\n * was queued.\n *\n * The key is marked sent in `config.storage` only once the event has been sent (`onSucceed`), so a\n * send that fails is tried again by the next call instead of being lost — under the same event id,\n * so the third-party trackers fired by the first call are not fired again (see `VERSION`); within\n * one page a key already queued is not queued twice.\n *\n * An event that leaves by beacon (`sendPendingEvents`, the page hidden or left) is not marked\n * sent: a beacon cannot tell delivered from dropped, so it counts as unconfirmed and the entry\n * stays unsent with its id. The next call for the key — the result page opened again — sends the\n * event once more under that id and without pixels, which the server ignores when the beacon did\n * arrive (it drops an event id it already has): one idempotent request more, against a lost one. When the storage cannot be read or written\n * the event is tracked anyway: a rare duplicate is better than a lost conversion.\n *\n * Deduplication is per device and storage. A second device still reports its own occurrence, so\n * figures that must be exact (revenue) belong to server-side records.\n */\nexport function trackOnce<T extends EventName = EventName>(\n name: TrackName<T>,\n properties: TrackProperties<T> | undefined,\n { key, ttl = DEFAULT_TTL, ...options }: TrackOnceOptions\n): boolean {\n if (isPending(name, key)) return false;\n\n const now = Date.now();\n // An earlier call that failed to send: its id, and its pixels already fired.\n let earlier: Entry | undefined;\n let id = uuidv7();\n try {\n const entries = live(read(name), now);\n earlier = entries.find((entry) => entry.key === key);\n if (earlier?.sent) return false;\n if (earlier) id = earlier.id;\n else write(name, [...entries, { key, id, expiresAt: now + ttl, sent: false }]);\n } catch (e: unknown) {\n // Unrecorded, a failed send would fire the pixels again on the next call: a rare duplicate\n // there beats not tracking.\n if (e instanceof Error) console.log(e.message);\n }\n\n markPending(name, key);\n queueEvent(\n name,\n properties,\n {\n ...options,\n onSucceed: (response) => {\n clearPending(name, key);\n // A beacon was only queued by the browser: the entry stays unsent, so a later call\n // sends it again under the same id.\n if (response?.beacon) {\n options.onSucceed?.(response);\n return;\n }\n try {\n const entries = live(read(name), Date.now()).filter((entry) => entry.key !== key);\n write(name, [...entries, { key, id, expiresAt: Date.now() + ttl, sent: true }]);\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n }\n options.onSucceed?.(response);\n },\n onError: (error) => {\n // Not sent: the entry stays unsent, with its id, so a later call can try again.\n clearPending(name, key);\n options.onError?.(error);\n },\n },\n earlier ? { id, pixels: false } : { id }\n );\n return true;\n}\n"],"mappings":";;;;;AAgBA,MAAM,cAAc;;;;;;;;;;;;;;;;;AAoBpB,MAAM,UAAU;AAIhB,SAAS,WAAW,MAAc;CAChC,OAAO,cAAc;AACvB;;AAGA,SAAS,KAAK,MAAuB;CACnC,MAAM,MAAMA,oBAAAA,OAAO,QAAQ,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,YAAY,QAAQ;IAC5B;GACF;GACA,IAAI;IAEF,MAAM,MAAM,CAAC,GADG,KAAK,KAAK,IAAI,GAAG,KAAK,IAAI,CAAC,CAAC,CAAC,QAAQ,UAAU,MAAM,QAAQ,GACvD,GAAG;KAAE;KAAK;KAAI,WAAW,KAAK,IAAI,IAAI;KAAK,MAAM;IAAK,CAAC,CAAC;GAChF,SAAS,GAAY;IACnB,IAAI,aAAa,OAAO,QAAQ,IAAI,EAAE,OAAO;GAC/C;GACA,QAAQ,YAAY,QAAQ;EAC9B;EACA,UAAU,UAAU;GAElB,aAAa,MAAM,GAAG;GACtB,QAAQ,UAAU,KAAK;EACzB;CACF,GACA,UAAU;EAAE;EAAI,QAAQ;CAAM,IAAI,EAAE,GAAG,CACzC;CACA,OAAO;AACT"}
|
package/dist/track/once.d.cts
CHANGED
|
@@ -19,7 +19,13 @@ export interface TrackOnceOptions extends TrackOptions {
|
|
|
19
19
|
* The key is marked sent in `config.storage` only once the event has been sent (`onSucceed`), so a
|
|
20
20
|
* send that fails is tried again by the next call instead of being lost — under the same event id,
|
|
21
21
|
* so the third-party trackers fired by the first call are not fired again (see `VERSION`); within
|
|
22
|
-
* one page a key already queued is not queued twice.
|
|
22
|
+
* one page a key already queued is not queued twice.
|
|
23
|
+
*
|
|
24
|
+
* An event that leaves by beacon (`sendPendingEvents`, the page hidden or left) is not marked
|
|
25
|
+
* sent: a beacon cannot tell delivered from dropped, so it counts as unconfirmed and the entry
|
|
26
|
+
* stays unsent with its id. The next call for the key — the result page opened again — sends the
|
|
27
|
+
* event once more under that id and without pixels, which the server ignores when the beacon did
|
|
28
|
+
* arrive (it drops an event id it already has): one idempotent request more, against a lost one. When the storage cannot be read or written
|
|
23
29
|
* the event is tracked anyway: a rare duplicate is better than a lost conversion.
|
|
24
30
|
*
|
|
25
31
|
* Deduplication is per device and storage. A second device still reports its own occurrence, so
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"once.d.cts","names":[],"sources":["../../src/track/once.ts"],"mappings":";;;iBAKiB,yBAAyB;;;;;;EAMxC;;EAEA
|
|
1
|
+
{"version":3,"file":"once.d.cts","names":[],"sources":["../../src/track/once.ts"],"mappings":";;;iBAKiB,yBAAyB;;;;;;EAMxC;;EAEA;;;;;;;;;;;;;;;;;;;;;;wBAqHc,UAAU,UAAU,YAAY,WAC9C,MAAM,UAAU,IAChB,YAAY,gBAAgB,kBAC1B,KAAK,QAAsB,WAAW"}
|
package/dist/track/once.d.mts
CHANGED
|
@@ -19,7 +19,13 @@ export interface TrackOnceOptions extends TrackOptions {
|
|
|
19
19
|
* The key is marked sent in `config.storage` only once the event has been sent (`onSucceed`), so a
|
|
20
20
|
* send that fails is tried again by the next call instead of being lost — under the same event id,
|
|
21
21
|
* so the third-party trackers fired by the first call are not fired again (see `VERSION`); within
|
|
22
|
-
* one page a key already queued is not queued twice.
|
|
22
|
+
* one page a key already queued is not queued twice.
|
|
23
|
+
*
|
|
24
|
+
* An event that leaves by beacon (`sendPendingEvents`, the page hidden or left) is not marked
|
|
25
|
+
* sent: a beacon cannot tell delivered from dropped, so it counts as unconfirmed and the entry
|
|
26
|
+
* stays unsent with its id. The next call for the key — the result page opened again — sends the
|
|
27
|
+
* event once more under that id and without pixels, which the server ignores when the beacon did
|
|
28
|
+
* arrive (it drops an event id it already has): one idempotent request more, against a lost one. When the storage cannot be read or written
|
|
23
29
|
* the event is tracked anyway: a rare duplicate is better than a lost conversion.
|
|
24
30
|
*
|
|
25
31
|
* Deduplication is per device and storage. A second device still reports its own occurrence, so
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"once.d.mts","names":[],"sources":["../../src/track/once.ts"],"mappings":";;;iBAKiB,yBAAyB;;;;;;EAMxC;;EAEA
|
|
1
|
+
{"version":3,"file":"once.d.mts","names":[],"sources":["../../src/track/once.ts"],"mappings":";;;iBAKiB,yBAAyB;;;;;;EAMxC;;EAEA;;;;;;;;;;;;;;;;;;;;;;wBAqHc,UAAU,UAAU,YAAY,WAC9C,MAAM,UAAU,IAChB,YAAY,gBAAgB,kBAC1B,KAAK,QAAsB,WAAW"}
|
package/dist/track/once.mjs
CHANGED
|
@@ -100,7 +100,13 @@ function clearPending(name, key) {
|
|
|
100
100
|
* The key is marked sent in `config.storage` only once the event has been sent (`onSucceed`), so a
|
|
101
101
|
* send that fails is tried again by the next call instead of being lost — under the same event id,
|
|
102
102
|
* so the third-party trackers fired by the first call are not fired again (see `VERSION`); within
|
|
103
|
-
* one page a key already queued is not queued twice.
|
|
103
|
+
* one page a key already queued is not queued twice.
|
|
104
|
+
*
|
|
105
|
+
* An event that leaves by beacon (`sendPendingEvents`, the page hidden or left) is not marked
|
|
106
|
+
* sent: a beacon cannot tell delivered from dropped, so it counts as unconfirmed and the entry
|
|
107
|
+
* stays unsent with its id. The next call for the key — the result page opened again — sends the
|
|
108
|
+
* event once more under that id and without pixels, which the server ignores when the beacon did
|
|
109
|
+
* arrive (it drops an event id it already has): one idempotent request more, against a lost one. When the storage cannot be read or written
|
|
104
110
|
* the event is tracked anyway: a rare duplicate is better than a lost conversion.
|
|
105
111
|
*
|
|
106
112
|
* Deduplication is per device and storage. A second device still reports its own occurrence, so
|
|
@@ -130,6 +136,10 @@ function trackOnce(name, properties, { key, ttl = DEFAULT_TTL, ...options }) {
|
|
|
130
136
|
...options,
|
|
131
137
|
onSucceed: (response) => {
|
|
132
138
|
clearPending(name, key);
|
|
139
|
+
if (response?.beacon) {
|
|
140
|
+
options.onSucceed?.(response);
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
133
143
|
try {
|
|
134
144
|
write(name, [...live(read(name), Date.now()).filter((entry) => entry.key !== key), {
|
|
135
145
|
key,
|
package/dist/track/once.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"once.mjs","names":["uuidv7"],"sources":["../../src/track/once.ts"],"sourcesContent":["import { v7 as uuidv7 } from 'uuid';\nimport { config } from '../setup/index';\nimport { type TrackOptions, queueEvent } from './index';\nimport type { EventName, TrackName, TrackProperties } from './types';\n\nexport interface TrackOnceOptions extends TrackOptions {\n /**\n * What makes this occurrence the same one again: a checkout session id for `purchase`, an order\n * id, a transaction id. Required, never derived from the properties, so the caller decides what\n * \"once\" means. The same key under another event name is a different occurrence.\n */\n key: string;\n /** How long a sent key is remembered, in milliseconds. 90 days by default. */\n ttl?: number;\n}\n\nconst DEFAULT_TTL = 90 * 24 * 60 * 60 * 1000;\n/** Keys remembered per event name; the oldest are forgotten first. */\nconst MAX_ENTRIES = 20;\n\n/**\n * `{\"v\":2,\"entries\":[[key, id, expiresAt, sent], …]}`, oldest first. Entries are tuples in an\n * array rather than an object keyed by `key`: an object would move integer-like keys (\"123\") to\n * the front and lose the order the oldest are dropped by. Escaping the value for the medium is the\n * storage's job, so this is plain JSON.\n *\n * `id` is the event id the key goes out under, decided by the first call and kept while `sent`\n * is false — a send that failed, or a page reloaded before its batch went out. The third-party\n * trackers fire when the event is tracked, not when it is sent, so that first call has already\n * reported the occurrence to them: the next call reuses the id, fires none of them again, and\n * the server (`on conflict (id) do nothing`) stores the event once even if the failed send had in\n * fact arrived.\n *\n * Version 1 records (`[key, expiresAt]`, written before the id was kept) are read as sent: that\n * is all a v1 record ever held, and dropping them would report every remembered occurrence again.\n */\nconst VERSION = 2;\n\ntype Entry = { key: string; id: string; expiresAt: number; sent: boolean };\n\nfunction storageKey(name: string) {\n return `track_once.${name}`;\n}\n\n/** The stored entries, or none for a record that is missing, of another version or malformed. */\nfunction read(name: string): Entry[] {\n const raw = config.storage.getItem(storageKey(name));\n if (!raw) return [];\n let record: unknown;\n try {\n record = JSON.parse(raw);\n } catch {\n return [];\n }\n if (typeof record !== 'object' || record === null) return [];\n const { v, entries } = record as { v?: unknown; entries?: unknown };\n if (!Array.isArray(entries)) return [];\n if (v === 1) {\n return entries.flatMap((entry: unknown) => {\n if (!Array.isArray(entry)) return [];\n const [key, expiresAt] = entry as unknown[];\n if (typeof key !== 'string' || typeof expiresAt !== 'number') return [];\n // Sent is all v1 remembered; the id it went out under is gone, and no longer needed.\n return [{ key, id: '', expiresAt, sent: true }];\n });\n }\n if (v !== VERSION) return [];\n return entries.flatMap((entry: unknown) => {\n if (!Array.isArray(entry)) return [];\n const [key, id, expiresAt, sent] = entry as unknown[];\n if (typeof key !== 'string' || typeof id !== 'string' || typeof expiresAt !== 'number') {\n return [];\n }\n if (typeof sent !== 'boolean') return [];\n return [{ key, id, expiresAt, sent }];\n });\n}\n\nfunction write(name: string, entries: Entry[]) {\n const record = {\n v: VERSION,\n entries: entries.slice(-MAX_ENTRIES).map((e) => [e.key, e.id, e.expiresAt, e.sent]),\n };\n config.storage.setItem(storageKey(name), JSON.stringify(record));\n}\n\nfunction live(entries: Entry[], now: number) {\n return entries.filter((entry) => entry.expiresAt > now);\n}\n\n/** Keys queued in this page (or app process) but not confirmed sent yet, per event name. */\nconst pending = new Map<string, Set<string>>();\n\nfunction isPending(name: string, key: string) {\n return pending.get(name)?.has(key) ?? false;\n}\n\nfunction markPending(name: string, key: string) {\n const keys = pending.get(name);\n if (keys) keys.add(key);\n else pending.set(name, new Set([key]));\n}\n\nfunction clearPending(name: string, key: string) {\n const keys = pending.get(name);\n if (!keys) return;\n keys.delete(key);\n if (keys.size === 0) pending.delete(name);\n}\n\n/**\n * Tracks an event at most once per `key`: a reloaded or revisited payment result page, a\n * re-delivered store transaction, a confirmation screen opened twice. Returns whether the event\n * was queued.\n *\n * The key is marked sent in `config.storage` only once the event has been sent (`onSucceed`), so a\n * send that fails is tried again by the next call instead of being lost — under the same event id,\n * so the third-party trackers fired by the first call are not fired again (see `VERSION`); within\n * one page a key already queued is not queued twice. When the storage cannot be read or written\n * the event is tracked anyway: a rare duplicate is better than a lost conversion.\n *\n * Deduplication is per device and storage. A second device still reports its own occurrence, so\n * figures that must be exact (revenue) belong to server-side records.\n */\nexport function trackOnce<T extends EventName = EventName>(\n name: TrackName<T>,\n properties: TrackProperties<T> | undefined,\n { key, ttl = DEFAULT_TTL, ...options }: TrackOnceOptions\n): boolean {\n if (isPending(name, key)) return false;\n\n const now = Date.now();\n // An earlier call that failed to send: its id, and its pixels already fired.\n let earlier: Entry | undefined;\n let id = uuidv7();\n try {\n const entries = live(read(name), now);\n earlier = entries.find((entry) => entry.key === key);\n if (earlier?.sent) return false;\n if (earlier) id = earlier.id;\n else write(name, [...entries, { key, id, expiresAt: now + ttl, sent: false }]);\n } catch (e: unknown) {\n // Unrecorded, a failed send would fire the pixels again on the next call: a rare duplicate\n // there beats not tracking.\n if (e instanceof Error) console.log(e.message);\n }\n\n markPending(name, key);\n queueEvent(\n name,\n properties,\n {\n ...options,\n onSucceed: (response) => {\n clearPending(name, key);\n try {\n const entries = live(read(name), Date.now()).filter((entry) => entry.key !== key);\n write(name, [...entries, { key, id, expiresAt: Date.now() + ttl, sent: true }]);\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n }\n options.onSucceed?.(response);\n },\n onError: (error) => {\n // Not sent: the entry stays unsent, with its id, so a later call can try again.\n clearPending(name, key);\n options.onError?.(error);\n },\n },\n earlier ? { id, pixels: false } : { id }\n );\n return true;\n}\n"],"mappings":";;;;AAgBA,MAAM,cAAc;;;;;;;;;;;;;;;;;AAoBpB,MAAM,UAAU;AAIhB,SAAS,WAAW,MAAc;CAChC,OAAO,cAAc;AACvB;;AAGA,SAAS,KAAK,MAAuB;CACnC,MAAM,MAAM,OAAO,QAAQ,QAAQ,WAAW,IAAI,CAAC;CACnD,IAAI,CAAC,KAAK,OAAO,CAAC;CAClB,IAAI;CACJ,IAAI;EACF,SAAS,KAAK,MAAM,GAAG;CACzB,QAAQ;EACN,OAAO,CAAC;CACV;CACA,IAAI,OAAO,WAAW,YAAY,WAAW,MAAM,OAAO,CAAC;CAC3D,MAAM,EAAE,GAAG,YAAY;CACvB,IAAI,CAAC,MAAM,QAAQ,OAAO,GAAG,OAAO,CAAC;CACrC,IAAI,MAAM,GACR,OAAO,QAAQ,SAAS,UAAmB;EACzC,IAAI,CAAC,MAA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AG,CACzC;CACA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"once.mjs","names":["uuidv7"],"sources":["../../src/track/once.ts"],"sourcesContent":["import { v7 as uuidv7 } from 'uuid';\nimport { config } from '../setup/index';\nimport { type TrackOptions, queueEvent } from './index';\nimport type { EventName, TrackName, TrackProperties } from './types';\n\nexport interface TrackOnceOptions extends TrackOptions {\n /**\n * What makes this occurrence the same one again: a checkout session id for `purchase`, an order\n * id, a transaction id. Required, never derived from the properties, so the caller decides what\n * \"once\" means. The same key under another event name is a different occurrence.\n */\n key: string;\n /** How long a sent key is remembered, in milliseconds. 90 days by default. */\n ttl?: number;\n}\n\nconst DEFAULT_TTL = 90 * 24 * 60 * 60 * 1000;\n/** Keys remembered per event name; the oldest are forgotten first. */\nconst MAX_ENTRIES = 20;\n\n/**\n * `{\"v\":2,\"entries\":[[key, id, expiresAt, sent], …]}`, oldest first. Entries are tuples in an\n * array rather than an object keyed by `key`: an object would move integer-like keys (\"123\") to\n * the front and lose the order the oldest are dropped by. Escaping the value for the medium is the\n * storage's job, so this is plain JSON.\n *\n * `id` is the event id the key goes out under, decided by the first call and kept while `sent`\n * is false — a send that failed, or a page reloaded before its batch went out. The third-party\n * trackers fire when the event is tracked, not when it is sent, so that first call has already\n * reported the occurrence to them: the next call reuses the id, fires none of them again, and\n * the server (`on conflict (id) do nothing`) stores the event once even if the failed send had in\n * fact arrived.\n *\n * Version 1 records (`[key, expiresAt]`, written before the id was kept) are read as sent: that\n * is all a v1 record ever held, and dropping them would report every remembered occurrence again.\n */\nconst VERSION = 2;\n\ntype Entry = { key: string; id: string; expiresAt: number; sent: boolean };\n\nfunction storageKey(name: string) {\n return `track_once.${name}`;\n}\n\n/** The stored entries, or none for a record that is missing, of another version or malformed. */\nfunction read(name: string): Entry[] {\n const raw = config.storage.getItem(storageKey(name));\n if (!raw) return [];\n let record: unknown;\n try {\n record = JSON.parse(raw);\n } catch {\n return [];\n }\n if (typeof record !== 'object' || record === null) return [];\n const { v, entries } = record as { v?: unknown; entries?: unknown };\n if (!Array.isArray(entries)) return [];\n if (v === 1) {\n return entries.flatMap((entry: unknown) => {\n if (!Array.isArray(entry)) return [];\n const [key, expiresAt] = entry as unknown[];\n if (typeof key !== 'string' || typeof expiresAt !== 'number') return [];\n // Sent is all v1 remembered; the id it went out under is gone, and no longer needed.\n return [{ key, id: '', expiresAt, sent: true }];\n });\n }\n if (v !== VERSION) return [];\n return entries.flatMap((entry: unknown) => {\n if (!Array.isArray(entry)) return [];\n const [key, id, expiresAt, sent] = entry as unknown[];\n if (typeof key !== 'string' || typeof id !== 'string' || typeof expiresAt !== 'number') {\n return [];\n }\n if (typeof sent !== 'boolean') return [];\n return [{ key, id, expiresAt, sent }];\n });\n}\n\nfunction write(name: string, entries: Entry[]) {\n const record = {\n v: VERSION,\n entries: entries.slice(-MAX_ENTRIES).map((e) => [e.key, e.id, e.expiresAt, e.sent]),\n };\n config.storage.setItem(storageKey(name), JSON.stringify(record));\n}\n\nfunction live(entries: Entry[], now: number) {\n return entries.filter((entry) => entry.expiresAt > now);\n}\n\n/** Keys queued in this page (or app process) but not confirmed sent yet, per event name. */\nconst pending = new Map<string, Set<string>>();\n\nfunction isPending(name: string, key: string) {\n return pending.get(name)?.has(key) ?? false;\n}\n\nfunction markPending(name: string, key: string) {\n const keys = pending.get(name);\n if (keys) keys.add(key);\n else pending.set(name, new Set([key]));\n}\n\nfunction clearPending(name: string, key: string) {\n const keys = pending.get(name);\n if (!keys) return;\n keys.delete(key);\n if (keys.size === 0) pending.delete(name);\n}\n\n/**\n * Tracks an event at most once per `key`: a reloaded or revisited payment result page, a\n * re-delivered store transaction, a confirmation screen opened twice. Returns whether the event\n * was queued.\n *\n * The key is marked sent in `config.storage` only once the event has been sent (`onSucceed`), so a\n * send that fails is tried again by the next call instead of being lost — under the same event id,\n * so the third-party trackers fired by the first call are not fired again (see `VERSION`); within\n * one page a key already queued is not queued twice.\n *\n * An event that leaves by beacon (`sendPendingEvents`, the page hidden or left) is not marked\n * sent: a beacon cannot tell delivered from dropped, so it counts as unconfirmed and the entry\n * stays unsent with its id. The next call for the key — the result page opened again — sends the\n * event once more under that id and without pixels, which the server ignores when the beacon did\n * arrive (it drops an event id it already has): one idempotent request more, against a lost one. When the storage cannot be read or written\n * the event is tracked anyway: a rare duplicate is better than a lost conversion.\n *\n * Deduplication is per device and storage. A second device still reports its own occurrence, so\n * figures that must be exact (revenue) belong to server-side records.\n */\nexport function trackOnce<T extends EventName = EventName>(\n name: TrackName<T>,\n properties: TrackProperties<T> | undefined,\n { key, ttl = DEFAULT_TTL, ...options }: TrackOnceOptions\n): boolean {\n if (isPending(name, key)) return false;\n\n const now = Date.now();\n // An earlier call that failed to send: its id, and its pixels already fired.\n let earlier: Entry | undefined;\n let id = uuidv7();\n try {\n const entries = live(read(name), now);\n earlier = entries.find((entry) => entry.key === key);\n if (earlier?.sent) return false;\n if (earlier) id = earlier.id;\n else write(name, [...entries, { key, id, expiresAt: now + ttl, sent: false }]);\n } catch (e: unknown) {\n // Unrecorded, a failed send would fire the pixels again on the next call: a rare duplicate\n // there beats not tracking.\n if (e instanceof Error) console.log(e.message);\n }\n\n markPending(name, key);\n queueEvent(\n name,\n properties,\n {\n ...options,\n onSucceed: (response) => {\n clearPending(name, key);\n // A beacon was only queued by the browser: the entry stays unsent, so a later call\n // sends it again under the same id.\n if (response?.beacon) {\n options.onSucceed?.(response);\n return;\n }\n try {\n const entries = live(read(name), Date.now()).filter((entry) => entry.key !== key);\n write(name, [...entries, { key, id, expiresAt: Date.now() + ttl, sent: true }]);\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n }\n options.onSucceed?.(response);\n },\n onError: (error) => {\n // Not sent: the entry stays unsent, with its id, so a later call can try again.\n clearPending(name, key);\n options.onError?.(error);\n },\n },\n earlier ? { id, pixels: false } : { id }\n );\n return true;\n}\n"],"mappings":";;;;AAgBA,MAAM,cAAc;;;;;;;;;;;;;;;;;AAoBpB,MAAM,UAAU;AAIhB,S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;GACvB,aAAa,MAAM,GAAG;GAGtB,IAAI,UAAU,QAAQ;IACpB,QAAQ,YAAY,QAAQ;IAC5B;GACF;GACA,IAAI;IAEF,MAAM,MAAM,CAAC,GADG,KAAK,KAAK,IAAI,GAAG,KAAK,IAAI,CAAC,CAAC,CAAC,QAAQ,UAAU,MAAM,QAAQ,GACvD,GAAG;KAAE;KAAK;KAAI,WAAW,KAAK,IAAI,IAAI;KAAK,MAAM;IAAK,CAAC,CAAC;GAChF,SAAS,GAAY;IACnB,IAAI,aAAa,OAAO,QAAQ,IAAI,EAAE,OAAO;GAC/C;GACA,QAAQ,YAAY,QAAQ;EAC9B;EACA,UAAU,UAAU;GAElB,aAAa,MAAM,GAAG;GACtB,QAAQ,UAAU,KAAK;EACzB;CACF,GACA,UAAU;EAAE;EAAI,QAAQ;CAAM,IAAI,EAAE,GAAG,CACzC;CACA,OAAO;AACT"}
|
package/dist/visitor/id.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"id.cjs","names":["config","keys","uuidv7"],"sources":["../../src/visitor/id.ts"],"sourcesContent":["import { v7 as uuidv7 } from 'uuid';\nimport { keys } from '../constants/storage';\nimport { config } from '../setup/index';\n\n/**\n * This visitor's id: generated here on the first visit (uuidv7) and kept in `config.storage`, so\n * it exists the moment the page loads. The first events, and the beacon of a visit left within a\n * second, go out without waiting for a round trip; the server creates the visitor from its first\n * events. An id a server issued to an older client is kept as it is: the visitor continues.\n *\n * Needs a server that creates visitors from events (see the README, \"Visitors\"); one that still\n * only creates them on `POST /visitors` rejects the events of a new visitor.\n */\nexport function visitorId(): string {\n const stored = config.storage.getItem(keys.visitor_id);\n if (stored && stored !== 'undefined') return stored;\n const id = uuidv7();\n config.storage.setItem(keys.visitor_id, id);\n return id;\n}\n"],"mappings":";;;;;;;;;;;;;;AAaA,SAAgB,YAAoB;CAClC,MAAM,SAASA,oBAAAA,OAAO,QAAQ,QAAQC,0BAAAA,KAAK,UAAU;
|
|
1
|
+
{"version":3,"file":"id.cjs","names":["config","keys","uuidv7"],"sources":["../../src/visitor/id.ts"],"sourcesContent":["import { v7 as uuidv7 } from 'uuid';\nimport { keys } from '../constants/storage';\nimport { config } from '../setup/index';\n\n/**\n * This visitor's id: generated here on the first visit (uuidv7) and kept in `config.storage`, so\n * it exists the moment the page loads. The first events, and the beacon of a visit left within a\n * second, go out without waiting for a round trip; the server creates the visitor from its first\n * events. An id a server issued to an older client is kept as it is: the visitor continues.\n *\n * Needs a server that creates visitors from events (see the README, \"Visitors\"); one that still\n * only creates them on `POST /visitors` rejects the events of a new visitor.\n */\nexport function visitorId(): string {\n const stored = config.storage.getItem(keys.visitor_id);\n // An old client stored the string 'undefined' as the id (it wrote an unset id): not an id, so it\n // is replaced below with a new one, which also clears the bad value from storage for good.\n if (stored && stored !== 'undefined') return stored;\n const id = uuidv7();\n config.storage.setItem(keys.visitor_id, id);\n return id;\n}\n"],"mappings":";;;;;;;;;;;;;;AAaA,SAAgB,YAAoB;CAClC,MAAM,SAASA,oBAAAA,OAAO,QAAQ,QAAQC,0BAAAA,KAAK,UAAU;CAGrD,IAAI,UAAU,WAAW,aAAa,OAAO;CAC7C,MAAM,MAAA,GAAKC,KAAAA,GAAAA,CAAO;CAClB,oBAAA,OAAO,QAAQ,QAAQD,0BAAAA,KAAK,YAAY,EAAE;CAC1C,OAAO;AACT"}
|
package/dist/visitor/id.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"id.mjs","names":["uuidv7"],"sources":["../../src/visitor/id.ts"],"sourcesContent":["import { v7 as uuidv7 } from 'uuid';\nimport { keys } from '../constants/storage';\nimport { config } from '../setup/index';\n\n/**\n * This visitor's id: generated here on the first visit (uuidv7) and kept in `config.storage`, so\n * it exists the moment the page loads. The first events, and the beacon of a visit left within a\n * second, go out without waiting for a round trip; the server creates the visitor from its first\n * events. An id a server issued to an older client is kept as it is: the visitor continues.\n *\n * Needs a server that creates visitors from events (see the README, \"Visitors\"); one that still\n * only creates them on `POST /visitors` rejects the events of a new visitor.\n */\nexport function visitorId(): string {\n const stored = config.storage.getItem(keys.visitor_id);\n if (stored && stored !== 'undefined') return stored;\n const id = uuidv7();\n config.storage.setItem(keys.visitor_id, id);\n return id;\n}\n"],"mappings":";;;;;;;;;;;;;AAaA,SAAgB,YAAoB;CAClC,MAAM,SAAS,OAAO,QAAQ,QAAQ,KAAK,UAAU;
|
|
1
|
+
{"version":3,"file":"id.mjs","names":["uuidv7"],"sources":["../../src/visitor/id.ts"],"sourcesContent":["import { v7 as uuidv7 } from 'uuid';\nimport { keys } from '../constants/storage';\nimport { config } from '../setup/index';\n\n/**\n * This visitor's id: generated here on the first visit (uuidv7) and kept in `config.storage`, so\n * it exists the moment the page loads. The first events, and the beacon of a visit left within a\n * second, go out without waiting for a round trip; the server creates the visitor from its first\n * events. An id a server issued to an older client is kept as it is: the visitor continues.\n *\n * Needs a server that creates visitors from events (see the README, \"Visitors\"); one that still\n * only creates them on `POST /visitors` rejects the events of a new visitor.\n */\nexport function visitorId(): string {\n const stored = config.storage.getItem(keys.visitor_id);\n // An old client stored the string 'undefined' as the id (it wrote an unset id): not an id, so it\n // is replaced below with a new one, which also clears the bad value from storage for good.\n if (stored && stored !== 'undefined') return stored;\n const id = uuidv7();\n config.storage.setItem(keys.visitor_id, id);\n return id;\n}\n"],"mappings":";;;;;;;;;;;;;AAaA,SAAgB,YAAoB;CAClC,MAAM,SAAS,OAAO,QAAQ,QAAQ,KAAK,UAAU;CAGrD,IAAI,UAAU,WAAW,aAAa,OAAO;CAC7C,MAAM,KAAKA,GAAO;CAClB,OAAO,QAAQ,QAAQ,KAAK,YAAY,EAAE;CAC1C,OAAO;AACT"}
|
package/dist/visitor/index.cjs
CHANGED
|
@@ -9,7 +9,10 @@ const require_track_index = require("../track/index.cjs");
|
|
|
9
9
|
* batch — which also creates the visitor when it is new, so the binding can never arrive before it.
|
|
10
10
|
*/
|
|
11
11
|
const IDENTIFY_EVENT = "identify";
|
|
12
|
-
/**
|
|
12
|
+
/**
|
|
13
|
+
* The user this page has identified the visitor as: identify once per user, not per call. Cleared
|
|
14
|
+
* on sign-out, so the same user signing back in on this page is identified again.
|
|
15
|
+
*/
|
|
13
16
|
let identified;
|
|
14
17
|
/**
|
|
15
18
|
* Hands the signed-in user to the analytics: the third-party user setters (gtag, the pixels) now,
|
|
@@ -18,16 +21,22 @@ let identified;
|
|
|
18
21
|
* event it goes with the next batch or the page-hide beacon; `user_data` is handed to the setters
|
|
19
22
|
* only, never stored with the event.
|
|
20
23
|
*
|
|
21
|
-
*
|
|
24
|
+
* Without a `user_id` (missing, or `''`) it signs the visitor out: `setVisitor({})` is
|
|
25
|
+
* sign-out. Nothing goes to the server, the setters get `distinct_id: null` (PostHog resets its
|
|
26
|
+
* identity on it), and the next sign-in is identified again even if it is the same user. Still
|
|
27
|
+
* `track('logout')` as usual — that is an ordinary event, and resets nothing.
|
|
28
|
+
*
|
|
29
|
+
* Synchronous and never throws: sign-in and sign-out must not fail on analytics.
|
|
22
30
|
*/
|
|
23
31
|
function setVisitor(dto) {
|
|
24
|
-
if (dto.user_id
|
|
32
|
+
if (!dto.user_id) identified = void 0;
|
|
33
|
+
else if (dto.user_id !== identified) {
|
|
25
34
|
identified = dto.user_id;
|
|
26
35
|
require_track_index.track(IDENTIFY_EVENT, { user_id: dto.user_id }, { enableThirdPartyTracking: false });
|
|
27
36
|
}
|
|
28
37
|
const identity = {
|
|
29
38
|
...dto,
|
|
30
|
-
distinct_id: dto.user_id
|
|
39
|
+
distinct_id: dto.user_id || null
|
|
31
40
|
};
|
|
32
41
|
require_setup_index.config.thirdPartyUserSetters.forEach((setter) => {
|
|
33
42
|
try {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":[],"sources":["../../src/visitor/index.ts"],"sourcesContent":["import type { UpdateVisitorDTO } from '../schema/index';\nimport { config } from '../setup/index';\nimport { track } from '../track/index';\n\nexport { visitorId } from './id';\n\n/**\n * The event that binds the visitor to the user who signed in on it: the server sets the visitor's\n * `user_id` and `distinct_id` from its `user_id` property, in the transaction that stores the\n * batch — which also creates the visitor when it is new, so the binding can never arrive before it.\n */\nexport const IDENTIFY_EVENT = 'identify';\n\n
|
|
1
|
+
{"version":3,"file":"index.cjs","names":[],"sources":["../../src/visitor/index.ts"],"sourcesContent":["import type { UpdateVisitorDTO } from '../schema/index';\nimport { config } from '../setup/index';\nimport { track } from '../track/index';\n\nexport { visitorId } from './id';\n\n/**\n * The event that binds the visitor to the user who signed in on it: the server sets the visitor's\n * `user_id` and `distinct_id` from its `user_id` property, in the transaction that stores the\n * batch — which also creates the visitor when it is new, so the binding can never arrive before it.\n */\nexport const IDENTIFY_EVENT = 'identify';\n\n/**\n * The user this page has identified the visitor as: identify once per user, not per call. Cleared\n * on sign-out, so the same user signing back in on this page is identified again.\n */\nlet identified: string | undefined;\n\n/**\n * Hands the signed-in user to the analytics: the third-party user setters (gtag, the pixels) now,\n * and the server through an `identify` event, sent when the user differs from the one this page\n * last identified — a host calls this on every page load once someone is signed in. Like any\n * event it goes with the next batch or the page-hide beacon; `user_data` is handed to the setters\n * only, never stored with the event.\n *\n * Without a `user_id` (missing, or `''`) it signs the visitor out: `setVisitor({})` is\n * sign-out. Nothing goes to the server, the setters get `distinct_id: null` (PostHog resets its\n * identity on it), and the next sign-in is identified again even if it is the same user. Still\n * `track('logout')` as usual — that is an ordinary event, and resets nothing.\n *\n * Synchronous and never throws: sign-in and sign-out must not fail on analytics.\n */\nexport function setVisitor(dto: Omit<UpdateVisitorDTO, 'tags'>) {\n if (!dto.user_id) {\n identified = undefined;\n } else if (dto.user_id !== identified) {\n identified = dto.user_id;\n track(IDENTIFY_EVENT, { user_id: dto.user_id }, { enableThirdPartyTracking: false });\n }\n\n // Once bound, the server's person key for the visitor is the user's id, so the setters are told\n // that rather than waiting for the server to say it.\n const identity = { ...dto, distinct_id: dto.user_id || null };\n config.thirdPartyUserSetters.forEach((setter) => {\n try {\n setter(identity);\n } catch (e: unknown) {\n // One third-party script does not get to stop the others.\n if (e instanceof Error) console.log(e.message);\n }\n });\n}\n"],"mappings":";;;;;;;;;;AAWA,MAAa,iBAAiB;;;;;AAM9B,IAAI;;;;;;;;;;;;;;;AAgBJ,SAAgB,WAAW,KAAqC;CAC9D,IAAI,CAAC,IAAI,SACP,aAAa,KAAA;MACR,IAAI,IAAI,YAAY,YAAY;EACrC,aAAa,IAAI;EACjB,oBAAA,MAAM,gBAAgB,EAAE,SAAS,IAAI,QAAQ,GAAG,EAAE,0BAA0B,MAAM,CAAC;CACrF;CAIA,MAAM,WAAW;EAAE,GAAG;EAAK,aAAa,IAAI,WAAW;CAAK;CAC5D,oBAAA,OAAO,sBAAsB,SAAS,WAAW;EAC/C,IAAI;GACF,OAAO,QAAQ;EACjB,SAAS,GAAY;GAEnB,IAAI,aAAa,OAAO,QAAQ,IAAI,EAAE,OAAO;EAC/C;CACF,CAAC;AACH"}
|
package/dist/visitor/index.d.cts
CHANGED
|
@@ -14,7 +14,12 @@ export declare const IDENTIFY_EVENT = "identify";
|
|
|
14
14
|
* event it goes with the next batch or the page-hide beacon; `user_data` is handed to the setters
|
|
15
15
|
* only, never stored with the event.
|
|
16
16
|
*
|
|
17
|
-
*
|
|
17
|
+
* Without a `user_id` (missing, or `''`) it signs the visitor out: `setVisitor({})` is
|
|
18
|
+
* sign-out. Nothing goes to the server, the setters get `distinct_id: null` (PostHog resets its
|
|
19
|
+
* identity on it), and the next sign-in is identified again even if it is the same user. Still
|
|
20
|
+
* `track('logout')` as usual — that is an ordinary event, and resets nothing.
|
|
21
|
+
*
|
|
22
|
+
* Synchronous and never throws: sign-in and sign-out must not fail on analytics.
|
|
18
23
|
*/
|
|
19
24
|
export declare function setVisitor(dto: Omit<UpdateVisitorDTO, 'tags'>): void;
|
|
20
25
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.cts","names":[],"sources":["../../src/visitor/index.ts"],"mappings":";;;;;;;;qBAWa
|
|
1
|
+
{"version":3,"file":"index.d.cts","names":[],"sources":["../../src/visitor/index.ts"],"mappings":";;;;;;;;qBAWa;;;;;;;;;;;;;;;wBAsBG,WAAW,KAAK,KAAK"}
|
package/dist/visitor/index.d.mts
CHANGED
|
@@ -14,7 +14,12 @@ export declare const IDENTIFY_EVENT = "identify";
|
|
|
14
14
|
* event it goes with the next batch or the page-hide beacon; `user_data` is handed to the setters
|
|
15
15
|
* only, never stored with the event.
|
|
16
16
|
*
|
|
17
|
-
*
|
|
17
|
+
* Without a `user_id` (missing, or `''`) it signs the visitor out: `setVisitor({})` is
|
|
18
|
+
* sign-out. Nothing goes to the server, the setters get `distinct_id: null` (PostHog resets its
|
|
19
|
+
* identity on it), and the next sign-in is identified again even if it is the same user. Still
|
|
20
|
+
* `track('logout')` as usual — that is an ordinary event, and resets nothing.
|
|
21
|
+
*
|
|
22
|
+
* Synchronous and never throws: sign-in and sign-out must not fail on analytics.
|
|
18
23
|
*/
|
|
19
24
|
export declare function setVisitor(dto: Omit<UpdateVisitorDTO, 'tags'>): void;
|
|
20
25
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/visitor/index.ts"],"mappings":";;;;;;;;qBAWa
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/visitor/index.ts"],"mappings":";;;;;;;;qBAWa;;;;;;;;;;;;;;;wBAsBG,WAAW,KAAK,KAAK"}
|
package/dist/visitor/index.mjs
CHANGED
|
@@ -8,7 +8,10 @@ import { track } from "../track/index.mjs";
|
|
|
8
8
|
* batch — which also creates the visitor when it is new, so the binding can never arrive before it.
|
|
9
9
|
*/
|
|
10
10
|
const IDENTIFY_EVENT = "identify";
|
|
11
|
-
/**
|
|
11
|
+
/**
|
|
12
|
+
* The user this page has identified the visitor as: identify once per user, not per call. Cleared
|
|
13
|
+
* on sign-out, so the same user signing back in on this page is identified again.
|
|
14
|
+
*/
|
|
12
15
|
let identified;
|
|
13
16
|
/**
|
|
14
17
|
* Hands the signed-in user to the analytics: the third-party user setters (gtag, the pixels) now,
|
|
@@ -17,16 +20,22 @@ let identified;
|
|
|
17
20
|
* event it goes with the next batch or the page-hide beacon; `user_data` is handed to the setters
|
|
18
21
|
* only, never stored with the event.
|
|
19
22
|
*
|
|
20
|
-
*
|
|
23
|
+
* Without a `user_id` (missing, or `''`) it signs the visitor out: `setVisitor({})` is
|
|
24
|
+
* sign-out. Nothing goes to the server, the setters get `distinct_id: null` (PostHog resets its
|
|
25
|
+
* identity on it), and the next sign-in is identified again even if it is the same user. Still
|
|
26
|
+
* `track('logout')` as usual — that is an ordinary event, and resets nothing.
|
|
27
|
+
*
|
|
28
|
+
* Synchronous and never throws: sign-in and sign-out must not fail on analytics.
|
|
21
29
|
*/
|
|
22
30
|
function setVisitor(dto) {
|
|
23
|
-
if (dto.user_id
|
|
31
|
+
if (!dto.user_id) identified = void 0;
|
|
32
|
+
else if (dto.user_id !== identified) {
|
|
24
33
|
identified = dto.user_id;
|
|
25
34
|
track(IDENTIFY_EVENT, { user_id: dto.user_id }, { enableThirdPartyTracking: false });
|
|
26
35
|
}
|
|
27
36
|
const identity = {
|
|
28
37
|
...dto,
|
|
29
|
-
distinct_id: dto.user_id
|
|
38
|
+
distinct_id: dto.user_id || null
|
|
30
39
|
};
|
|
31
40
|
config.thirdPartyUserSetters.forEach((setter) => {
|
|
32
41
|
try {
|