@shware/analytics 12.0.0 → 12.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.md +63 -1
  2. package/dist/index.d.cts +2 -2
  3. package/dist/index.d.mts +2 -2
  4. package/dist/native/firebase.cjs +7 -1
  5. package/dist/native/firebase.cjs.map +1 -1
  6. package/dist/native/firebase.d.cts +7 -1
  7. package/dist/native/firebase.d.cts.map +1 -1
  8. package/dist/native/firebase.d.mts +7 -1
  9. package/dist/native/firebase.d.mts.map +1 -1
  10. package/dist/native/firebase.mjs +7 -1
  11. package/dist/native/firebase.mjs.map +1 -1
  12. package/dist/schema/index.cjs +10 -2
  13. package/dist/schema/index.cjs.map +1 -1
  14. package/dist/schema/index.d.cts +3 -0
  15. package/dist/schema/index.d.cts.map +1 -1
  16. package/dist/schema/index.d.mts +3 -0
  17. package/dist/schema/index.d.mts.map +1 -1
  18. package/dist/schema/index.mjs +10 -2
  19. package/dist/schema/index.mjs.map +1 -1
  20. package/dist/third-parties/google-analytics.cjs +1 -1
  21. package/dist/third-parties/google-analytics.cjs.map +1 -1
  22. package/dist/third-parties/google-analytics.d.cts +1 -1
  23. package/dist/third-parties/google-analytics.d.mts +1 -1
  24. package/dist/third-parties/google-analytics.mjs +1 -1
  25. package/dist/third-parties/google-analytics.mjs.map +1 -1
  26. package/dist/third-parties/linkedin-insight-tag.cjs +1 -1
  27. package/dist/third-parties/linkedin-insight-tag.cjs.map +1 -1
  28. package/dist/third-parties/linkedin-insight-tag.d.cts +1 -1
  29. package/dist/third-parties/linkedin-insight-tag.d.mts +1 -1
  30. package/dist/third-parties/linkedin-insight-tag.mjs +1 -1
  31. package/dist/third-parties/linkedin-insight-tag.mjs.map +1 -1
  32. package/dist/third-parties/meta-pixel.cjs +1 -1
  33. package/dist/third-parties/meta-pixel.cjs.map +1 -1
  34. package/dist/third-parties/meta-pixel.d.cts +1 -1
  35. package/dist/third-parties/meta-pixel.d.mts +1 -1
  36. package/dist/third-parties/meta-pixel.mjs +1 -1
  37. package/dist/third-parties/meta-pixel.mjs.map +1 -1
  38. package/dist/third-parties/microsoft-uet.cjs +1 -1
  39. package/dist/third-parties/microsoft-uet.cjs.map +1 -1
  40. package/dist/third-parties/microsoft-uet.d.cts +1 -1
  41. package/dist/third-parties/microsoft-uet.d.mts +1 -1
  42. package/dist/third-parties/microsoft-uet.mjs +1 -1
  43. package/dist/third-parties/microsoft-uet.mjs.map +1 -1
  44. package/dist/third-parties/openai-pixel.cjs +1 -1
  45. package/dist/third-parties/openai-pixel.cjs.map +1 -1
  46. package/dist/third-parties/openai-pixel.d.cts +1 -1
  47. package/dist/third-parties/openai-pixel.d.mts +1 -1
  48. package/dist/third-parties/openai-pixel.mjs +1 -1
  49. package/dist/third-parties/openai-pixel.mjs.map +1 -1
  50. package/dist/third-parties/reddit-pixel.cjs +1 -1
  51. package/dist/third-parties/reddit-pixel.cjs.map +1 -1
  52. package/dist/third-parties/reddit-pixel.d.cts +1 -1
  53. package/dist/third-parties/reddit-pixel.d.mts +1 -1
  54. package/dist/third-parties/reddit-pixel.mjs +1 -1
  55. package/dist/third-parties/reddit-pixel.mjs.map +1 -1
  56. package/dist/track/index.cjs +77 -42
  57. package/dist/track/index.cjs.map +1 -1
  58. package/dist/track/index.d.cts +28 -4
  59. package/dist/track/index.d.cts.map +1 -1
  60. package/dist/track/index.d.mts +28 -4
  61. package/dist/track/index.d.mts.map +1 -1
  62. package/dist/track/index.mjs +77 -43
  63. package/dist/track/index.mjs.map +1 -1
  64. package/dist/track/once.cjs +65 -17
  65. package/dist/track/once.cjs.map +1 -1
  66. package/dist/track/once.d.cts +5 -4
  67. package/dist/track/once.d.cts.map +1 -1
  68. package/dist/track/once.d.mts +5 -4
  69. package/dist/track/once.d.mts.map +1 -1
  70. package/dist/track/once.mjs +66 -18
  71. package/dist/track/once.mjs.map +1 -1
  72. package/dist/track/types.d.cts +58 -5
  73. package/dist/track/types.d.cts.map +1 -1
  74. package/dist/track/types.d.mts +58 -5
  75. package/dist/track/types.d.mts.map +1 -1
  76. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../src/track/index.ts"],"sourcesContent":["import { TokenBucket, fetch } from '@shware/utils';\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 { EventName, TrackEventResponse, TrackName, TrackProperties, TrackTags } from './types';\n\nexport interface TrackOptions {\n enableThirdPartyTracking?: boolean;\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 // 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 * 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 * Queues an event, preceded by a `session_start` when it is the one that opens a session.\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(name: Item['name'], properties: Item['properties'], options: TrackOptions): 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, '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({ name: 'session_start', properties: {}, options }));\n }\n const event = item({ name, properties, options });\n list.push(event);\n return event;\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) => ({\n name: event.name,\n properties: event.properties,\n tags: await event.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 const body = JSON.stringify(dto);\n const response = await fetch(`${config.endpoint}/events`, {\n method: 'POST',\n credentials: 'include',\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 const data = (await response.json()) as TrackEventResponse;\n\n events.forEach((event, index) => {\n const eventId = data.at(index)?.id;\n event.options.onSucceed?.(eventId ? { id: eventId } : undefined);\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 config.thirdPartyTrackers.forEach((tracker) => {\n try {\n tracker(event.name, event.properties, eventId);\n } catch (e: unknown) {\n // A third-party script does not get to take the rest of the batch with it.\n if (e instanceof Error) console.log(e.message);\n }\n });\n });\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\nexport function track<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n options: TrackOptions = defaultOptions\n) {\n enqueue(name, properties, options);\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 * Sends the event now, with whatever is queued, and resolves once it has been sent or lost — or,\n * when the send could not start (its headers or rate limit threw), at once, the event left queued\n * for the next send. It never rejects: tracking must not fail the step that awaits it.\n */\nexport async function trackAsync<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n options: TrackOptions = defaultOptions\n) {\n let settle!: () => void;\n const settled = new Promise<void>((resolve) => {\n settle = resolve;\n });\n const event = enqueue(name, properties, {\n ...options,\n onSucceed: (response) => {\n options.onSucceed?.(response);\n settle();\n },\n onError: (error) => {\n options.onError?.(error);\n settle();\n },\n });\n await flush();\n // Still queued: this send failed before taking it. It waits for the next send, but the caller,\n // who may be holding a navigation on this, does not.\n if (list.includes(event)) return;\n await settled;\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), and without the server's ids: their third-party trackers are not fired,\n * as an id-less browser event could not be deduplicated against the server's. The visitor id is\n * local (`visitorId`), so a first visit left within a second is sent like any other; when no\n * beacon 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 name: event.name,\n properties: event.properties,\n tags: event.settled ?? cache.tags ?? {},\n visitor_id,\n session_id: event.session_id,\n platform: config.platform,\n environment: config.environment,\n timestamp: event.timestamp,\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?.(undefined));\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 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":";;;;;;AAcA,MAAM,iBAA+B,CAAC;AAEtC,IAAI;;;;;;;AAQJ,SAAS,iBAAiB;CACxB,OAAQ,gBAAgB,IAAI,YAAY;EAAE,MAAM;EAAG,UAAU;EAAI,WAAW;CAAE,CAAC;AACjF;;;;;;;;;;AAyBA,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;;;;;;;;;;;AAYlD,SAAS,QAAQ,MAAoB,YAAgC,SAA6B;CAChG,MAAM,6BAAY,IAAI,KAAK,EAAA,CAAE,YAAY;CACzC,MAAM,OAAO,YAAY;CACzB,MAAM,EAAE,IAAI,Y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T;CACF,CAAC;CACD,MAAM,MAAM;CAGZ,IAAI,KAAK,SAAS,KAAK,GAAG;CAC1B,MAAM;AACR;AAEA,SAAS,OAAO,KAAmC;CAEjD,IAAI,OAAO,cAAc,eAAe,EAAE,gBAAgB,YAAY,OAAO;CAI7E,MAAM,OAAO,IAAI,KAAK,CAAC,KAAK,UAAU,GAAG,CAAC,GAAG,EAAE,MAAM,2BAA2B,CAAC;CACjF,OAAO,UAAU,WAAW,GAAG,OAAO,SAAS,UAAU,IAAI;AAC/D;;;;;;;;;;;;AAaA,SAAgB,oBAAoB;CAClC,IAAI,KAAK,WAAW,GAAG;CACvB,MAAM,aAAa,UAAU;CAW7B,IAAI,CAAC,OAV4B,KAAK,KAAK,WAAW;EACpD,MAAM,MAAM;EACZ,YAAY,MAAM;EAClB,MAAM,MAAM,WAAW,MAAM,QAAQ,CAAC;EACtC;EACA,YAAY,MAAM;EAClB,UAAU,OAAO;EACjB,aAAa,OAAO;EACpB,WAAW,MAAM;CACnB,EACc,CAAC,GAAG;EAChB,MAAW;EACX;CACF;CACA,IAAI,OAAO;EACT,aAAa,KAAK;EAClB,QAAQ;CACV;CACA,KAAK,OAAO,CAAC,CAAC,CAAC,SAAS,UAAU,MAAM,QAAQ,YAAY,KAAA,CAAS,CAAC;AACxE;AAEA,SAAgB,WACd,MACA,YACA;CACA,MAAM,aAAa,UAAU;CAG7B,MAAM,aAAa,WAAW,CAAC,CAAC,OAAO;CACvC,IAAI,CAAC,YAAY;CAgBjB,IAAI,OAAO,CAbT;EACE;EACA;EAGA,MAAM,MAAM,QAAQ,CAAC;EACrB;EACA;EACA,UAAU,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.\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 // 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\n/**\n * Sends the event now, with whatever is queued, and resolves once it has been sent or lost — or,\n * when the send could not start (its headers or rate limit threw), at once, the event left queued\n * for the next send. It never rejects: tracking must not fail the step that awaits it.\n *\n * The third-party trackers are not what it waits for: as with `track`, they are fired at once.\n * Await it when the next step needs the event stored by the server; a page about to navigate\n * away needs no more than `track` to have its event reach the pixels, and `sendPendingEvents`\n * on `pagehide` to have it reach the server.\n */\nexport async function trackAsync<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n options: TrackOptions = defaultOptions\n) {\n let settle!: () => void;\n const settled = new Promise<void>((resolve) => {\n settle = resolve;\n });\n const event = enqueue(name, properties, {\n ...options,\n onSucceed: (response) => {\n options.onSucceed?.(response);\n settle();\n },\n onError: (error) => {\n options.onError?.(error);\n settle();\n },\n });\n await flush();\n // Still queued: this send failed before taking it. It waits for the next send, but the caller,\n // who may be holding a navigation on this, does not.\n if (list.includes(event)) return;\n await settled;\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,QAAQ,CAAC;CACxB;AACF;;;;;;AAOA,MAA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AAK,OAAO,CAAC,CAAC,CAAC,SAAS,UAAU,MAAM,QAAQ,YAAY,EAAE,IAAI,MAAM,GAAG,CAAC,CAAC;AAC/E;AAEA,SAAgB,WACd,MACA,YACA;CACA,MAAM,aAAa,UAAU;CAG7B,MAAM,aAAa,WAAW,CAAC,CAAC,OAAO;CACvC,IAAI,CAAC,YAAY;CAiBjB,IAAI,OAAO,CAdT;EACE,IAAIA,GAAO;EACX;EACA;EAGA,MAAM,MAAM,QAAQ,CAAC;EACrB;EACA;EACA,UAAU,OAAO;EACjB,aAAa,OAAO;EACpB,4BAAW,IAAI,KAAK,EAAA,CAAE,YAAY;CACpC,CAEW,CAAC,GAAG;CACjB,QAAQ,KAAK,yBAAyB,MAAM,UAAU;AACxD"}
@@ -1,15 +1,26 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_setup_index = require("../setup/index.cjs");
3
3
  const require_track_index = require("./index.cjs");
4
+ let uuid = require("uuid");
4
5
  //#region src/track/once.ts
5
6
  const DEFAULT_TTL = 7776e6;
6
7
  /**
7
- * `{"v":1,"entries":[[key, expiresAt], …]}`, oldest first. Entries are tuples in an array rather
8
- * than an object keyed by `key`: an object would move integer-like keys ("123") to the front and
9
- * lose the order the oldest are dropped by. Escaping the value for the medium is the storage's
10
- * job, so this is plain JSON.
8
+ * `{"v":2,"entries":[[key, id, expiresAt, sent], …]}`, oldest first. Entries are tuples in an
9
+ * array rather than an object keyed by `key`: an object would move integer-like keys ("123") to
10
+ * the front and lose the order the oldest are dropped by. Escaping the value for the medium is the
11
+ * storage's job, so this is plain JSON.
12
+ *
13
+ * `id` is the event id the key goes out under, decided by the first call and kept while `sent`
14
+ * is false — a send that failed, or a page reloaded before its batch went out. The third-party
15
+ * trackers fire when the event is tracked, not when it is sent, so that first call has already
16
+ * reported the occurrence to them: the next call reuses the id, fires none of them again, and
17
+ * the server (`on conflict (id) do nothing`) stores the event once even if the failed send had in
18
+ * fact arrived.
19
+ *
20
+ * Version 1 records (`[key, expiresAt]`, written before the id was kept) are read as sent: that
21
+ * is all a v1 record ever held, and dropping them would report every remembered occurrence again.
11
22
  */
12
- const VERSION = 1;
23
+ const VERSION = 2;
13
24
  function storageKey(name) {
14
25
  return `track_once.${name}`;
15
26
  }
@@ -25,21 +36,41 @@ function read(name) {
25
36
  }
26
37
  if (typeof record !== "object" || record === null) return [];
27
38
  const { v, entries } = record;
28
- if (v !== VERSION || !Array.isArray(entries)) return [];
29
- return entries.flatMap((entry) => {
39
+ if (!Array.isArray(entries)) return [];
40
+ if (v === 1) return entries.flatMap((entry) => {
30
41
  if (!Array.isArray(entry)) return [];
31
42
  const [key, expiresAt] = entry;
32
43
  if (typeof key !== "string" || typeof expiresAt !== "number") return [];
33
44
  return [{
34
45
  key,
35
- expiresAt
46
+ id: "",
47
+ expiresAt,
48
+ sent: true
49
+ }];
50
+ });
51
+ if (v !== VERSION) return [];
52
+ return entries.flatMap((entry) => {
53
+ if (!Array.isArray(entry)) return [];
54
+ const [key, id, expiresAt, sent] = entry;
55
+ if (typeof key !== "string" || typeof id !== "string" || typeof expiresAt !== "number") return [];
56
+ if (typeof sent !== "boolean") return [];
57
+ return [{
58
+ key,
59
+ id,
60
+ expiresAt,
61
+ sent
36
62
  }];
37
63
  });
38
64
  }
39
65
  function write(name, entries) {
40
66
  const record = {
41
67
  v: VERSION,
42
- entries: entries.slice(-20).map((entry) => [entry.key, entry.expiresAt])
68
+ entries: entries.slice(-20).map((e) => [
69
+ e.key,
70
+ e.id,
71
+ e.expiresAt,
72
+ e.sent
73
+ ])
43
74
  };
44
75
  require_setup_index.config.storage.setItem(storageKey(name), JSON.stringify(record));
45
76
  }
@@ -67,10 +98,11 @@ function clearPending(name, key) {
67
98
  * re-delivered store transaction, a confirmation screen opened twice. Returns whether the event
68
99
  * was queued.
69
100
  *
70
- * The key is remembered in `config.storage` only once the event has been sent (`onSucceed`), so a
71
- * send that fails is tried again by the next call instead of being lost; within one page a key
72
- * already queued is not queued twice. When the storage cannot be read or written the event is
73
- * tracked anyway: a rare duplicate is better than a lost conversion.
101
+ * The key is marked sent in `config.storage` only once the event has been sent (`onSucceed`), so a
102
+ * send that fails is tried again by the next call instead of being lost — under the same event id,
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. When the storage cannot be read or written
105
+ * the event is tracked anyway: a rare duplicate is better than a lost conversion.
74
106
  *
75
107
  * Deduplication is per device and storage. A second device still reports its own occurrence, so
76
108
  * figures that must be exact (revenue) belong to server-side records.
@@ -78,20 +110,33 @@ function clearPending(name, key) {
78
110
  function trackOnce(name, properties, { key, ttl = DEFAULT_TTL, ...options }) {
79
111
  if (isPending(name, key)) return false;
80
112
  const now = Date.now();
113
+ let earlier;
114
+ let id = (0, uuid.v7)();
81
115
  try {
82
- if (live(read(name), now).some((entry) => entry.key === key)) return false;
116
+ const entries = live(read(name), now);
117
+ earlier = entries.find((entry) => entry.key === key);
118
+ if (earlier?.sent) return false;
119
+ if (earlier) id = earlier.id;
120
+ else write(name, [...entries, {
121
+ key,
122
+ id,
123
+ expiresAt: now + ttl,
124
+ sent: false
125
+ }]);
83
126
  } catch (e) {
84
127
  if (e instanceof Error) console.log(e.message);
85
128
  }
86
129
  markPending(name, key);
87
- require_track_index.track(name, properties, {
130
+ require_track_index.queueEvent(name, properties, {
88
131
  ...options,
89
132
  onSucceed: (response) => {
90
133
  clearPending(name, key);
91
134
  try {
92
135
  write(name, [...live(read(name), Date.now()).filter((entry) => entry.key !== key), {
93
136
  key,
94
- expiresAt: Date.now() + ttl
137
+ id,
138
+ expiresAt: Date.now() + ttl,
139
+ sent: true
95
140
  }]);
96
141
  } catch (e) {
97
142
  if (e instanceof Error) console.log(e.message);
@@ -102,7 +147,10 @@ function trackOnce(name, properties, { key, ttl = DEFAULT_TTL, ...options }) {
102
147
  clearPending(name, key);
103
148
  options.onError?.(error);
104
149
  }
105
- });
150
+ }, earlier ? {
151
+ id,
152
+ pixels: false
153
+ } : { id });
106
154
  return true;
107
155
  }
108
156
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"once.cjs","names":["config"],"sources":["../../src/track/once.ts"],"sourcesContent":["import { config } from '../setup/index';\nimport { type TrackOptions, track } 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\":1,\"entries\":[[key, expiresAt], …]}`, oldest first. Entries are tuples in an array rather\n * than an object keyed by `key`: an object would move integer-like keys (\"123\") to the front and\n * lose the order the oldest are dropped by. Escaping the value for the medium is the storage's\n * job, so this is plain JSON.\n */\nconst VERSION = 1;\n\ntype Entry = { key: string; expiresAt: number };\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 (v !== VERSION || !Array.isArray(entries)) return [];\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 return [{ key, expiresAt }];\n });\n}\n\nfunction write(name: string, entries: Entry[]) {\n const record = {\n v: VERSION,\n entries: entries.slice(-MAX_ENTRIES).map((entry) => [entry.key, entry.expiresAt]),\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 remembered 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; within one page a key\n * already queued is not queued twice. When the storage cannot be read or written the event is\n * 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 try {\n if (live(read(name), now).some((entry) => entry.key === key)) return false;\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n }\n\n markPending(name, key);\n track(name, properties, {\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, expiresAt: Date.now() + ttl }]);\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: forget it here so a later call can try again.\n clearPending(name, key);\n options.onError?.(error);\n },\n });\n return true;\n}\n"],"mappings":";;;;AAeA,MAAM,cAAc;;;;;;;A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AI,GAAG;MACjB,QAAQ,IAAI,sBAAM,IAAI,IAAI,CAAC,GAAG,CAAC,CAAC;AACvC;AAEA,SAAS,aAAa,MAAc,KAAa;CAC/C,MAAM,OAAO,QAAQ,IAAI,IAAI;CAC7B,IAAI,CAAC,MAAM;CACX,KAAK,OAAO,GAAG;CACf,IAAI,KAAK,SAAS,GAAG,QAAQ,OAAO,IAAI;AAC1C;;;;;;;;;;;;;;AAeA,SAAgB,UACd,MACA,YACA,EAAE,KAAK,MAAM,aAAa,GAAG,WACpB;CACT,IAAI,UAAU,MAAM,GAAG,GAAG,OAAO;CAEjC,MAAM,MAAM,KAAK,IAAI;CACrB,IAAI;EACF,IAAI,KAAK,KAAK,IAAI,GAAG,GAAG,CAAC,CAAC,MAAM,UAAU,MAAM,QAAQ,GAAG,GAAG,OAAO;CACvE,SAAS,GAAY;EACnB,IAAI,aAAa,OAAO,QAAQ,IAAI,EAAE,OAAO;CAC/C;CAEA,YAAY,MAAM,GAAG;CACrB,oBAAA,MAAM,MAAM,YAAY;EACtB,GAAG;EACH,YAAY,aAAa;GACvB,aAAa,MAAM,GAAG;GACtB,IAAI;IAEF,MAAM,MAAM,CAAC,GADG,KAAK,KAAK,IAAI,GAAG,KAAK,IAAI,CAAC,CAAC,CAAC,QAAQ,UAAU,MAAM,QAAQ,GACvD,GAAG;KAAE;KAAK,WAAW,KAAK,IAAI,IAAI;IAAI,CAAC,CAAC;GAChE,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,CAAC;CACD,OAAO;AACT"}
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,CAA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;EAAE;EAAI,QAAQ;CAAM,IAAI,EAAE,GAAG,CACzC;CACA,OAAO;AACT"}
@@ -16,10 +16,11 @@ export interface TrackOnceOptions extends TrackOptions {
16
16
  * re-delivered store transaction, a confirmation screen opened twice. Returns whether the event
17
17
  * was queued.
18
18
  *
19
- * The key is remembered in `config.storage` only once the event has been sent (`onSucceed`), so a
20
- * send that fails is tried again by the next call instead of being lost; within one page a key
21
- * already queued is not queued twice. When the storage cannot be read or written the event is
22
- * tracked anyway: a rare duplicate is better than a lost conversion.
19
+ * The key is marked sent in `config.storage` only once the event has been sent (`onSucceed`), so a
20
+ * send that fails is tried again by the next call instead of being lost — under the same event id,
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. When the storage cannot be read or written
23
+ * the event is tracked anyway: a rare duplicate is better than a lost conversion.
23
24
  *
24
25
  * Deduplication is per device and storage. A second device still reports its own occurrence, so
25
26
  * figures that must be exact (revenue) belong to server-side records.
@@ -1 +1 @@
1
- {"version":3,"file":"once.d.cts","names":[],"sources":["../../src/track/once.ts"],"mappings":";;;iBAIiB,yBAAyB;;;;;;EAMxC;;EAEA;;;;;;;;;;;;;;;wBAuFc,UAAU,UAAU,YAAY,WAC9C,MAAM,UAAU,IAChB,YAAY,gBAAgB,kBAC1B,KAAK,QAAsB,WAAW"}
1
+ {"version":3,"file":"once.d.cts","names":[],"sources":["../../src/track/once.ts"],"mappings":";;;iBAKiB,yBAAyB;;;;;;EAMxC;;EAEA;;;;;;;;;;;;;;;;wBA+Gc,UAAU,UAAU,YAAY,WAC9C,MAAM,UAAU,IAChB,YAAY,gBAAgB,kBAC1B,KAAK,QAAsB,WAAW"}
@@ -16,10 +16,11 @@ export interface TrackOnceOptions extends TrackOptions {
16
16
  * re-delivered store transaction, a confirmation screen opened twice. Returns whether the event
17
17
  * was queued.
18
18
  *
19
- * The key is remembered in `config.storage` only once the event has been sent (`onSucceed`), so a
20
- * send that fails is tried again by the next call instead of being lost; within one page a key
21
- * already queued is not queued twice. When the storage cannot be read or written the event is
22
- * tracked anyway: a rare duplicate is better than a lost conversion.
19
+ * The key is marked sent in `config.storage` only once the event has been sent (`onSucceed`), so a
20
+ * send that fails is tried again by the next call instead of being lost — under the same event id,
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. When the storage cannot be read or written
23
+ * the event is tracked anyway: a rare duplicate is better than a lost conversion.
23
24
  *
24
25
  * Deduplication is per device and storage. A second device still reports its own occurrence, so
25
26
  * figures that must be exact (revenue) belong to server-side records.
@@ -1 +1 @@
1
- {"version":3,"file":"once.d.mts","names":[],"sources":["../../src/track/once.ts"],"mappings":";;;iBAIiB,yBAAyB;;;;;;EAMxC;;EAEA;;;;;;;;;;;;;;;wBAuFc,UAAU,UAAU,YAAY,WAC9C,MAAM,UAAU,IAChB,YAAY,gBAAgB,kBAC1B,KAAK,QAAsB,WAAW"}
1
+ {"version":3,"file":"once.d.mts","names":[],"sources":["../../src/track/once.ts"],"mappings":";;;iBAKiB,yBAAyB;;;;;;EAMxC;;EAEA;;;;;;;;;;;;;;;;wBA+Gc,UAAU,UAAU,YAAY,WAC9C,MAAM,UAAU,IAChB,YAAY,gBAAgB,kBAC1B,KAAK,QAAsB,WAAW"}
@@ -1,14 +1,25 @@
1
1
  import { config } from "../setup/index.mjs";
2
- import { track } from "./index.mjs";
2
+ import { queueEvent } from "./index.mjs";
3
+ import { v7 } from "uuid";
3
4
  //#region src/track/once.ts
4
5
  const DEFAULT_TTL = 7776e6;
5
6
  /**
6
- * `{"v":1,"entries":[[key, expiresAt], …]}`, oldest first. Entries are tuples in an array rather
7
- * than an object keyed by `key`: an object would move integer-like keys ("123") to the front and
8
- * lose the order the oldest are dropped by. Escaping the value for the medium is the storage's
9
- * job, so this is plain JSON.
7
+ * `{"v":2,"entries":[[key, id, expiresAt, sent], …]}`, oldest first. Entries are tuples in an
8
+ * array rather than an object keyed by `key`: an object would move integer-like keys ("123") to
9
+ * the front and lose the order the oldest are dropped by. Escaping the value for the medium is the
10
+ * storage's job, so this is plain JSON.
11
+ *
12
+ * `id` is the event id the key goes out under, decided by the first call and kept while `sent`
13
+ * is false — a send that failed, or a page reloaded before its batch went out. The third-party
14
+ * trackers fire when the event is tracked, not when it is sent, so that first call has already
15
+ * reported the occurrence to them: the next call reuses the id, fires none of them again, and
16
+ * the server (`on conflict (id) do nothing`) stores the event once even if the failed send had in
17
+ * fact arrived.
18
+ *
19
+ * Version 1 records (`[key, expiresAt]`, written before the id was kept) are read as sent: that
20
+ * is all a v1 record ever held, and dropping them would report every remembered occurrence again.
10
21
  */
11
- const VERSION = 1;
22
+ const VERSION = 2;
12
23
  function storageKey(name) {
13
24
  return `track_once.${name}`;
14
25
  }
@@ -24,21 +35,41 @@ function read(name) {
24
35
  }
25
36
  if (typeof record !== "object" || record === null) return [];
26
37
  const { v, entries } = record;
27
- if (v !== VERSION || !Array.isArray(entries)) return [];
28
- return entries.flatMap((entry) => {
38
+ if (!Array.isArray(entries)) return [];
39
+ if (v === 1) return entries.flatMap((entry) => {
29
40
  if (!Array.isArray(entry)) return [];
30
41
  const [key, expiresAt] = entry;
31
42
  if (typeof key !== "string" || typeof expiresAt !== "number") return [];
32
43
  return [{
33
44
  key,
34
- expiresAt
45
+ id: "",
46
+ expiresAt,
47
+ sent: true
48
+ }];
49
+ });
50
+ if (v !== VERSION) return [];
51
+ return entries.flatMap((entry) => {
52
+ if (!Array.isArray(entry)) return [];
53
+ const [key, id, expiresAt, sent] = entry;
54
+ if (typeof key !== "string" || typeof id !== "string" || typeof expiresAt !== "number") return [];
55
+ if (typeof sent !== "boolean") return [];
56
+ return [{
57
+ key,
58
+ id,
59
+ expiresAt,
60
+ sent
35
61
  }];
36
62
  });
37
63
  }
38
64
  function write(name, entries) {
39
65
  const record = {
40
66
  v: VERSION,
41
- entries: entries.slice(-20).map((entry) => [entry.key, entry.expiresAt])
67
+ entries: entries.slice(-20).map((e) => [
68
+ e.key,
69
+ e.id,
70
+ e.expiresAt,
71
+ e.sent
72
+ ])
42
73
  };
43
74
  config.storage.setItem(storageKey(name), JSON.stringify(record));
44
75
  }
@@ -66,10 +97,11 @@ function clearPending(name, key) {
66
97
  * re-delivered store transaction, a confirmation screen opened twice. Returns whether the event
67
98
  * was queued.
68
99
  *
69
- * The key is remembered in `config.storage` only once the event has been sent (`onSucceed`), so a
70
- * send that fails is tried again by the next call instead of being lost; within one page a key
71
- * already queued is not queued twice. When the storage cannot be read or written the event is
72
- * tracked anyway: a rare duplicate is better than a lost conversion.
100
+ * The key is marked sent in `config.storage` only once the event has been sent (`onSucceed`), so a
101
+ * send that fails is tried again by the next call instead of being lost — under the same event id,
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. When the storage cannot be read or written
104
+ * the event is tracked anyway: a rare duplicate is better than a lost conversion.
73
105
  *
74
106
  * Deduplication is per device and storage. A second device still reports its own occurrence, so
75
107
  * figures that must be exact (revenue) belong to server-side records.
@@ -77,20 +109,33 @@ function clearPending(name, key) {
77
109
  function trackOnce(name, properties, { key, ttl = DEFAULT_TTL, ...options }) {
78
110
  if (isPending(name, key)) return false;
79
111
  const now = Date.now();
112
+ let earlier;
113
+ let id = v7();
80
114
  try {
81
- if (live(read(name), now).some((entry) => entry.key === key)) return false;
115
+ const entries = live(read(name), now);
116
+ earlier = entries.find((entry) => entry.key === key);
117
+ if (earlier?.sent) return false;
118
+ if (earlier) id = earlier.id;
119
+ else write(name, [...entries, {
120
+ key,
121
+ id,
122
+ expiresAt: now + ttl,
123
+ sent: false
124
+ }]);
82
125
  } catch (e) {
83
126
  if (e instanceof Error) console.log(e.message);
84
127
  }
85
128
  markPending(name, key);
86
- track(name, properties, {
129
+ queueEvent(name, properties, {
87
130
  ...options,
88
131
  onSucceed: (response) => {
89
132
  clearPending(name, key);
90
133
  try {
91
134
  write(name, [...live(read(name), Date.now()).filter((entry) => entry.key !== key), {
92
135
  key,
93
- expiresAt: Date.now() + ttl
136
+ id,
137
+ expiresAt: Date.now() + ttl,
138
+ sent: true
94
139
  }]);
95
140
  } catch (e) {
96
141
  if (e instanceof Error) console.log(e.message);
@@ -101,7 +146,10 @@ function trackOnce(name, properties, { key, ttl = DEFAULT_TTL, ...options }) {
101
146
  clearPending(name, key);
102
147
  options.onError?.(error);
103
148
  }
104
- });
149
+ }, earlier ? {
150
+ id,
151
+ pixels: false
152
+ } : { id });
105
153
  return true;
106
154
  }
107
155
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"once.mjs","names":[],"sources":["../../src/track/once.ts"],"sourcesContent":["import { config } from '../setup/index';\nimport { type TrackOptions, track } 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\":1,\"entries\":[[key, expiresAt], …]}`, oldest first. Entries are tuples in an array rather\n * than an object keyed by `key`: an object would move integer-like keys (\"123\") to the front and\n * lose the order the oldest are dropped by. Escaping the value for the medium is the storage's\n * job, so this is plain JSON.\n */\nconst VERSION = 1;\n\ntype Entry = { key: string; expiresAt: number };\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 (v !== VERSION || !Array.isArray(entries)) return [];\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 return [{ key, expiresAt }];\n });\n}\n\nfunction write(name: string, entries: Entry[]) {\n const record = {\n v: VERSION,\n entries: entries.slice(-MAX_ENTRIES).map((entry) => [entry.key, entry.expiresAt]),\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 remembered 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; within one page a key\n * already queued is not queued twice. When the storage cannot be read or written the event is\n * 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 try {\n if (live(read(name), now).some((entry) => entry.key === key)) return false;\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n }\n\n markPending(name, key);\n track(name, properties, {\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, expiresAt: Date.now() + ttl }]);\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: forget it here so a later call can try again.\n clearPending(name, key);\n options.onError?.(error);\n },\n });\n return true;\n}\n"],"mappings":";;;AAeA,MAAM,cAAc;;;;;;;AAUpB,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,MAAM,WAAW,CAAC,MAAM,QAAQ,OAAO,GAAG,OAAO,CAAC;CACtD,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;EACtE,OAAO,CAAC;GAAE;GAAK;EAAU,CAAC;CAC5B,CAAC;AACH;AAEA,SAAS,MAAM,MAAc,SAAkB;CAC7C,MAAM,SAAS;EACb,GAAG;EACH,SAAS,QAAQ,MAAM,GAAY,CAAC,CAAC,KAAK,UAAU,CAAC,MAAM,KAAK,MAAM,SAAS,CAAC;CAClF;CACA,OAAO,QAAQ,QAAQ,WAAW,IAAI,GAAG,KAAK,UAAU,MAAM,CAAC;AACjE;AAEA,SAAS,KAAK,SAAkB,KAAa;CAC3C,OAAO,QAAQ,QAAQ,UAAU,MAAM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A,UAAU,UAAU;GAElB,aAAa,MAAM,GAAG;GACtB,QAAQ,UAAU,KAAK;EACzB;CACF,CAAC;CACD,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. 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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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"}
@@ -2,14 +2,50 @@ import { StandardEvents, UserProvidedData as UserProvidedData$1 } from "./gtag.c
2
2
  //#region src/track/types.d.ts
3
3
  export type AllowedPropertyValues = string | number | boolean | null;
4
4
  export type EventName = Lowercase<string> | 'CLS' | 'FCP' | 'INP' | 'LCP' | 'TTFB';
5
- export type TrackName<T extends EventName = EventName> = T extends keyof StandardEvents ? T : EventName;
5
+ /**
6
+ * Type-level switches an application turns on by declaration merging, the way it fills
7
+ * `CustomEventProperties` — usually in the same file:
8
+ *
9
+ * ```ts
10
+ * declare module '@shware/analytics' {
11
+ * interface AnalyticsOptions {
12
+ * strict: true;
13
+ * }
14
+ * }
15
+ * ```
16
+ *
17
+ * - `strict: true` — strict events: every function that takes an event name (`track`, `trackOnce`,
18
+ * `trackAsync`, `sendBeacon`, `useTrackImpression`, the third-party senders) accepts only
19
+ * GA4's standard events and the events declared in `CustomEventProperties`: a misspelled or
20
+ * undeclared name (`'purchse'`, `'begin_checkout '`) is a compile error instead of a new event.
21
+ *
22
+ * Empty by default, so nothing changes for an application that never merges into it.
23
+ */
24
+ export interface AnalyticsOptions {}
25
+ /** Whether the application turned on `AnalyticsOptions['strict']`. */
26
+ type Strict = AnalyticsOptions extends {
27
+ strict: true;
28
+ } ? true : false;
29
+ /**
30
+ * The names `track` accepts with `strict` on: GA4's standard events and the events
31
+ * the application declared. Only declared keys that are themselves valid event names, so the
32
+ * set stays within `EventName`.
33
+ */
34
+ export type DeclaredEventName = keyof StandardEvents | Extract<keyof CustomEventProperties, EventName>;
35
+ /**
36
+ * The type of an event-name parameter. `T` is inferred from the argument through both branches;
37
+ * the false branch is what the argument is checked against when it is not a known event — any
38
+ * event name by default, only a declared one with `strict` on.
39
+ */
40
+ export type TrackName<T extends EventName = EventName> = Strict extends true ? T extends DeclaredEventName ? T : DeclaredEventName : T extends keyof StandardEvents ? T : EventName;
6
41
  /**
7
42
  * Properties an application defines for its own events, keyed by event name.
8
43
  *
9
44
  * Empty here on purpose. Applications fill it by declaration merging, and it does two jobs:
10
45
  * it adds custom properties to GA4's standard events, which are otherwise closed shapes and
11
46
  * would need a cast; and it gives an application's own events a real type instead of the
12
- * open record they fall back to.
47
+ * open record they fall back to. With `AnalyticsOptions['strict']` on, it is also the
48
+ * list of the custom event names `track` accepts.
13
49
  *
14
50
  * ```ts
15
51
  * declare module '@shware/analytics' {
@@ -37,7 +73,7 @@ export interface CustomEventProperties {}
37
73
  * no declaration intersects to exactly the type it had before.
38
74
  */
39
75
  type CustomPropertiesFor<T> = T extends keyof CustomEventProperties ? CustomEventProperties[T] : unknown;
40
- export type TrackProperties<T extends EventName = EventName> = T extends keyof StandardEvents ? StandardEvents[T] & CustomPropertiesFor<T> : T extends keyof CustomEventProperties ? CustomEventProperties[T] : Record<Lowercase<string>, AllowedPropertyValues>;
76
+ export type TrackProperties<T extends EventName = EventName> = T extends keyof StandardEvents ? StandardEvents[T] & CustomPropertiesFor<T> : T extends keyof CustomEventProperties ? CustomEventProperties[T] : Strict extends true ? never : Record<Lowercase<string>, AllowedPropertyValues>;
41
77
  export type Platform = 'ios' | 'android' | 'web' | 'macos' | 'windows' | 'linux' | 'unknown';
42
78
  export type Environment = 'development' | 'production';
43
79
  export interface UserData {
@@ -66,7 +102,16 @@ export interface UserProvidedData extends UserProvidedData$1 {
66
102
  fb_login_id?: string;
67
103
  fb_page_id?: string;
68
104
  }
69
- export type ThirdPartyTracker = <T extends EventName>(name: TrackName<T>, properties?: TrackProperties<T>, event_id?: string) => void;
105
+ /**
106
+ * A browser pixel or app SDK an event is forwarded to. Called synchronously when the event is
107
+ * tracked, before it is sent, with `event_id` — the client-generated id the event is stored and
108
+ * sent to the conversions APIs under — as the platform's deduplication id.
109
+ *
110
+ * Returning `false` means "not ready": the pixel's global (`fbq`, `rdt`, `gtag`, …) is not on the
111
+ * page yet, its snippet still loading. The SDK then calls the tracker once more, with the same
112
+ * event and id, on the next macrotask. Any other return value (`void` included) is a handled call.
113
+ */
114
+ export type ThirdPartyTracker = <T extends EventName>(name: TrackName<T>, properties?: TrackProperties<T>, event_id?: string) => void | boolean;
70
115
  export interface PlatformInfo {
71
116
  os?: string;
72
117
  os_name?: string;
@@ -263,8 +308,16 @@ export interface TrackEvent<T extends EventName = EventName> {
263
308
  properties?: TrackProperties<T>;
264
309
  created_at: string;
265
310
  }
311
+ /**
312
+ * What `POST /events` answers: one `{ id }` per event, in the order sent.
313
+ *
314
+ * Since 12.1 the client generates each event's id and sends it in the DTO; the SDK no longer
315
+ * reads this answer, and `onSucceed` reports the client's id. Servers keep answering it for
316
+ * clients before 12.1, which fire their pixels with the id found here. To be removed in the next
317
+ * major.
318
+ */
266
319
  export type TrackEventResponse = {
267
- /** track event id: Meta Pixel will use event_id and event_name for deduplication */
320
+ /** The event's id, the one the pixels and the conversions APIs deduplicate on. */
268
321
  id: string;
269
322
  }[];
270
323
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.cts","names":["GAUserProvidedData"],"sources":["../../src/track/types.ts"],"mappings":";;YAEY;YACA,YAAY;YAEZ,UAAU,UAAU,YAAY,aAAa,gBAAgB,iBACrE,IACA;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA+Ba;;;;;;;KAQZ,oBAAoB,KAAK,gBAAgB,wBAC1C,sBAAsB;YAGd,gBAAgB,UAAU,YAAY,aAAa,gBAAgB,iBAC3E,eAAe,KAAK,oBAAoB,KACxC,gBAAgB,wBACd,sBAAsB,KACtB,OAAO,mBAAmB;YAEpB;YACA;iBAEK;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;iBAGe,yBAAyBA;EACxC;EACA;EACA;EACA;EACA;IAAa;IAAc;IAAe;;EAE1C;EACA;;YAGU,qBAAqB,UAAU,WACzC,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B;iBAGe;EACf;EACA;EACA;EACA;EACA;EACA;;iBAGe;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;EAEA;;iBAGe;;EAEf;EACA;;iBAGe;EACf;EACA;EACA;;;;;;;;;;iBAWe;EACf;EACA;EACA;;;;;;;EAOA;;;;;;EAMA;;;;;;;;;;;;;iBAce;EAEf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;;;;;EAMA;;EAEA;;EAEA;;EAEA;EAEA;EACA;EACA;EACA;;;;;;;;EAQA;;;;;;EAMA;EACA;EACA;EACA;;EAEA;;EAEA;EAEA;;EAEA;EAEA;;EAEA;;EAEA;;EAEA;EAEA;;;;;EAKA;EAEA;;EAEA;;EAEA;EAEA;EACA;EACA;EACA;EACA;EACA;;;;;;;iBAQe;;EAEf;;;;;;;;;;;;EAqCA;;;;;;EAuDA;;EAMA;;EAEA;;EAEA;;EAEA;;EAUA;;EAEA;;iBAGe,kBACP,cAAc,YAAY,SAAS,iBAAiB,UAAU,iBAAiB;EACvF;GACC;;iBAGc,WAAW,UAAU,YAAY;EAChD;EACA,MAAM,UAAU;EAChB,MAAM;EACN;EACA;EACA,UAAU;EACV,aAAa;EACb,aAAa,gBAAgB;EAC7B;;YAGU;;EAEV"}
1
+ {"version":3,"file":"types.d.cts","names":["GAUserProvidedData"],"sources":["../../src/track/types.ts"],"mappings":";;YAEY;YACA,YAAY;;;;;;;;;;;;;;;;;;;;iBAsBP;;KAGZ,SAAS;EAA2B;;;;;;;YAO7B,0BACF,iBACN,cAAc,uBAAuB;;;;;;YAO7B,UAAU,UAAU,YAAY,aAAa,sBACrD,UAAU,oBACR,IACA,oBACF,gBAAgB,iBACd,IACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAgCW;;;;;;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