tracklane 0.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 +23 -0
- package/dist/browser-BQNJ4qUq.d.ts +124 -0
- package/dist/browser.d.ts +2 -0
- package/dist/browser.js +141 -0
- package/dist/browser.js.map +1 -0
- package/dist/dispatch-DK2GBnkt.js +51 -0
- package/dist/dispatch-DK2GBnkt.js.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +0 -0
- package/dist/server-cNxLsKhl.d.ts +152 -0
- package/dist/server.d.ts +2 -0
- package/dist/server.js +190 -0
- package/dist/server.js.map +1 -0
- package/dist/vocabulary-ByyXHVWd.d.ts +107 -0
- package/package.json +71 -0
package/README.md
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# tracklane
|
|
2
|
+
|
|
3
|
+
> TODO: one-line description of the library.
|
|
4
|
+
|
|
5
|
+
ESM-only TypeScript library. Documentation: https://brunobertolini.github.io/tracklane
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pnpm add tracklane
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Usage
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { format } from 'tracklane';
|
|
17
|
+
|
|
18
|
+
format(' hello ', { prefix: '> ' }); // '> hello'
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## License
|
|
22
|
+
|
|
23
|
+
MIT © Bruno Bertolini
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { c as UserData, i as EventData, n as ConsentState, o as ProviderDefault, r as EventBinding, s as TrackingError } from "./vocabulary-ByyXHVWd.js";
|
|
2
|
+
//#region src/providers/ga4.browser.d.ts
|
|
3
|
+
/** Optional configuration for the GA4 browser provider. */
|
|
4
|
+
interface Ga4BrowserConfig {
|
|
5
|
+
/**
|
|
6
|
+
* How this property spells each canonical event. Rarely needed: the
|
|
7
|
+
* canonical vocabulary already is GA4's.
|
|
8
|
+
*/
|
|
9
|
+
events?: Record<string, EventBinding<string>>;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Google Analytics 4 in the browser, through `gtag.js`.
|
|
13
|
+
*
|
|
14
|
+
* **This provider does not load Google's tag.** The tag belongs on the page,
|
|
15
|
+
* installed the way Google documents it — a snippet in the HTML, or a tag
|
|
16
|
+
* manager. This library talks to the tag that is already there; it never
|
|
17
|
+
* injects a third-party script into your page, and it never issues the
|
|
18
|
+
* property configuration that would emit a second page view.
|
|
19
|
+
*
|
|
20
|
+
* Which also means the initial consent declaration is not ours to make:
|
|
21
|
+
* Google requires it before the property is configured, and the snippet that
|
|
22
|
+
* configures the property is yours. Use {@link ConsentState} through
|
|
23
|
+
* `consent()` for changes after that.
|
|
24
|
+
*
|
|
25
|
+
* @param measurementId - The `G-` id of the data stream, matching the tag on
|
|
26
|
+
* the page.
|
|
27
|
+
* @param config - Rarely needed event name overrides.
|
|
28
|
+
* @returns A provider for `createTracking` from `tracklane/browser`.
|
|
29
|
+
*
|
|
30
|
+
* @example
|
|
31
|
+
* ```ts
|
|
32
|
+
* import { createTracking, ga4 } from 'tracklane/browser';
|
|
33
|
+
*
|
|
34
|
+
* // Google's own snippet is already in the page.
|
|
35
|
+
* const { track } = createTracking({ providers: [ga4('G-XXXXXXX')] });
|
|
36
|
+
*
|
|
37
|
+
* track('purchase', { transaction_id: 'T-1', value: 49.9, currency: 'BRL' });
|
|
38
|
+
* ```
|
|
39
|
+
*/
|
|
40
|
+
declare function ga4(measurementId: string, config?: Ga4BrowserConfig): BrowserProvider;
|
|
41
|
+
//#endregion
|
|
42
|
+
//#region src/browser.d.ts
|
|
43
|
+
/**
|
|
44
|
+
* Everything the browser needs beyond the event itself.
|
|
45
|
+
*
|
|
46
|
+
* There is one field, and that is the point: in the browser each vendor tag
|
|
47
|
+
* reads its own cookies and holds its own session, so the only thing left
|
|
48
|
+
* for the host to supply is the value that ties this hit to a server-side
|
|
49
|
+
* one.
|
|
50
|
+
*/
|
|
51
|
+
interface TrackOptions {
|
|
52
|
+
/**
|
|
53
|
+
* The value that lets a vendor recognise this hit and a server-side hit as
|
|
54
|
+
* one event. The library never invents it — the browser and the server do
|
|
55
|
+
* not share a process, so only a value the host already owns (an order id)
|
|
56
|
+
* can match on both sides.
|
|
57
|
+
*/
|
|
58
|
+
dedupId?: string;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* A destination for browser events.
|
|
62
|
+
*
|
|
63
|
+
* This is the whole contract, and it is what a provider written outside this
|
|
64
|
+
* package implements — the ones shipped here get no shortcut.
|
|
65
|
+
*/
|
|
66
|
+
interface BrowserProvider<Target = string> {
|
|
67
|
+
/** The vendor's fixed name. Registering one twice is an error. */
|
|
68
|
+
name: string;
|
|
69
|
+
/** What happens to a canonical event this vendor has no binding for. */
|
|
70
|
+
default: ProviderDefault;
|
|
71
|
+
/** How this vendor spells each canonical event. */
|
|
72
|
+
events?: Record<string, EventBinding<Target>>;
|
|
73
|
+
/** Loads the vendor tag. Runs once, at creation. */
|
|
74
|
+
install?(): void | Promise<void>;
|
|
75
|
+
track(name: Target, data: EventData, options: TrackOptions): void;
|
|
76
|
+
/** Absent where the vendor keeps no user of its own. */
|
|
77
|
+
identify?(user: UserData, traits?: Record<string, unknown>): void;
|
|
78
|
+
/** Absent where the vendor documents no consent command. */
|
|
79
|
+
consent?(command: "default" | "update", state: ConsentState): void;
|
|
80
|
+
}
|
|
81
|
+
/** Options accepted by {@link createTracking}. */
|
|
82
|
+
interface BrowserTrackingOptions {
|
|
83
|
+
providers: readonly BrowserProvider[];
|
|
84
|
+
/**
|
|
85
|
+
* The one diagnostic channel. Without it the library is silent, exactly as
|
|
86
|
+
* a hand-written vendor call is.
|
|
87
|
+
*/
|
|
88
|
+
onError?: (error: TrackingError) => void;
|
|
89
|
+
}
|
|
90
|
+
/** What {@link createTracking} returns. */
|
|
91
|
+
interface BrowserTracking {
|
|
92
|
+
/** Sends one event to every configured vendor. Never throws. */
|
|
93
|
+
track(name: string, data?: EventData, options?: TrackOptions): void;
|
|
94
|
+
/** Forwards the user to the vendors that hold one, and to nobody else. */
|
|
95
|
+
identify(user: UserData, traits?: Record<string, unknown>): void;
|
|
96
|
+
/**
|
|
97
|
+
* Forwards a consent declaration to every vendor that documents a command
|
|
98
|
+
* for it. It never decides, stores or withholds anything.
|
|
99
|
+
*/
|
|
100
|
+
consent(command: "default" | "update", state: ConsentState): void;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Creates the browser tracking surface.
|
|
104
|
+
*
|
|
105
|
+
* Providers install eagerly, which is what pasting a vendor snippet does and
|
|
106
|
+
* what lets each vendor record its own initial page view. Every vendor
|
|
107
|
+
* shipped here queues its own commands until its script lands, so nothing is
|
|
108
|
+
* lost to loading and this library needs no queue of its own.
|
|
109
|
+
*
|
|
110
|
+
* @param options - The providers to send to, and an optional error channel.
|
|
111
|
+
* @returns The `track`, `identify` and `consent` calls.
|
|
112
|
+
*
|
|
113
|
+
* @example
|
|
114
|
+
* ```ts
|
|
115
|
+
* import { createTracking, ga4 } from 'tracklane/browser';
|
|
116
|
+
*
|
|
117
|
+
* const { track } = createTracking({ providers: [ga4('G-XXXXXXX')] });
|
|
118
|
+
* track('purchase', { transaction_id: 'T-1', value: 49.9, currency: 'BRL' });
|
|
119
|
+
* ```
|
|
120
|
+
*/
|
|
121
|
+
declare function createTracking(options: BrowserTrackingOptions): BrowserTracking;
|
|
122
|
+
//#endregion
|
|
123
|
+
export { createTracking as a, TrackOptions as i, BrowserTracking as n, Ga4BrowserConfig as o, BrowserTrackingOptions as r, ga4 as s, BrowserProvider as t };
|
|
124
|
+
//# sourceMappingURL=browser-BQNJ4qUq.d.ts.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { a as createTracking, i as TrackOptions, n as BrowserTracking, o as Ga4BrowserConfig, r as BrowserTrackingOptions, s as ga4, t as BrowserProvider } from "./browser-BQNJ4qUq.js";
|
|
2
|
+
export { BrowserProvider, BrowserTracking, BrowserTrackingOptions, type Ga4BrowserConfig, TrackOptions, createTracking, ga4 };
|
package/dist/browser.js
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { i as resolveEvent, n as makeReporter, r as messageOf, t as assertUniqueProviders } from "./dispatch-DK2GBnkt.js";
|
|
2
|
+
//#region src/providers/ga4.browser.ts
|
|
3
|
+
function gtagWindow() {
|
|
4
|
+
return typeof window === "undefined" ? void 0 : window;
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Sends a command, or fails the way a hand-written call would.
|
|
8
|
+
*
|
|
9
|
+
* Writing `gtag(…)` on a page without Google's snippet throws, and this
|
|
10
|
+
* library replicates that rather than swallowing it: a silent no-op is how a
|
|
11
|
+
* host ends up believing it is measuring something.
|
|
12
|
+
*/
|
|
13
|
+
function push(...args) {
|
|
14
|
+
const gtag = gtagWindow()?.gtag;
|
|
15
|
+
if (!gtag) throw new Error("ga4: window.gtag is not defined — add Google's tag to the page before creating tracking");
|
|
16
|
+
gtag(...args);
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Google Analytics 4 in the browser, through `gtag.js`.
|
|
20
|
+
*
|
|
21
|
+
* **This provider does not load Google's tag.** The tag belongs on the page,
|
|
22
|
+
* installed the way Google documents it — a snippet in the HTML, or a tag
|
|
23
|
+
* manager. This library talks to the tag that is already there; it never
|
|
24
|
+
* injects a third-party script into your page, and it never issues the
|
|
25
|
+
* property configuration that would emit a second page view.
|
|
26
|
+
*
|
|
27
|
+
* Which also means the initial consent declaration is not ours to make:
|
|
28
|
+
* Google requires it before the property is configured, and the snippet that
|
|
29
|
+
* configures the property is yours. Use {@link ConsentState} through
|
|
30
|
+
* `consent()` for changes after that.
|
|
31
|
+
*
|
|
32
|
+
* @param measurementId - The `G-` id of the data stream, matching the tag on
|
|
33
|
+
* the page.
|
|
34
|
+
* @param config - Rarely needed event name overrides.
|
|
35
|
+
* @returns A provider for `createTracking` from `tracklane/browser`.
|
|
36
|
+
*
|
|
37
|
+
* @example
|
|
38
|
+
* ```ts
|
|
39
|
+
* import { createTracking, ga4 } from 'tracklane/browser';
|
|
40
|
+
*
|
|
41
|
+
* // Google's own snippet is already in the page.
|
|
42
|
+
* const { track } = createTracking({ providers: [ga4('G-XXXXXXX')] });
|
|
43
|
+
*
|
|
44
|
+
* track('purchase', { transaction_id: 'T-1', value: 49.9, currency: 'BRL' });
|
|
45
|
+
* ```
|
|
46
|
+
*/
|
|
47
|
+
function ga4(measurementId, config = {}) {
|
|
48
|
+
const { events } = config;
|
|
49
|
+
return {
|
|
50
|
+
name: "ga4",
|
|
51
|
+
default: "passthrough",
|
|
52
|
+
...events ? { events } : {},
|
|
53
|
+
track(name, data, _options) {
|
|
54
|
+
push("event", name, {
|
|
55
|
+
...data,
|
|
56
|
+
send_to: measurementId
|
|
57
|
+
});
|
|
58
|
+
},
|
|
59
|
+
identify(user, traits) {
|
|
60
|
+
if (user.userId !== void 0) push("set", { user_id: user.userId });
|
|
61
|
+
if (traits) push("set", "user_properties", traits);
|
|
62
|
+
},
|
|
63
|
+
consent(command, state) {
|
|
64
|
+
push("consent", command, state);
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
//#endregion
|
|
69
|
+
//#region src/browser.ts
|
|
70
|
+
/**
|
|
71
|
+
* Creates the browser tracking surface.
|
|
72
|
+
*
|
|
73
|
+
* Providers install eagerly, which is what pasting a vendor snippet does and
|
|
74
|
+
* what lets each vendor record its own initial page view. Every vendor
|
|
75
|
+
* shipped here queues its own commands until its script lands, so nothing is
|
|
76
|
+
* lost to loading and this library needs no queue of its own.
|
|
77
|
+
*
|
|
78
|
+
* @param options - The providers to send to, and an optional error channel.
|
|
79
|
+
* @returns The `track`, `identify` and `consent` calls.
|
|
80
|
+
*
|
|
81
|
+
* @example
|
|
82
|
+
* ```ts
|
|
83
|
+
* import { createTracking, ga4 } from 'tracklane/browser';
|
|
84
|
+
*
|
|
85
|
+
* const { track } = createTracking({ providers: [ga4('G-XXXXXXX')] });
|
|
86
|
+
* track('purchase', { transaction_id: 'T-1', value: 49.9, currency: 'BRL' });
|
|
87
|
+
* ```
|
|
88
|
+
*/
|
|
89
|
+
function createTracking(options) {
|
|
90
|
+
const { providers } = options;
|
|
91
|
+
assertUniqueProviders(providers);
|
|
92
|
+
const report = makeReporter(options.onError);
|
|
93
|
+
const fail = (provider, event, cause) => {
|
|
94
|
+
report({
|
|
95
|
+
provider,
|
|
96
|
+
event,
|
|
97
|
+
severity: "error",
|
|
98
|
+
message: messageOf(cause),
|
|
99
|
+
cause
|
|
100
|
+
});
|
|
101
|
+
};
|
|
102
|
+
for (const provider of providers) try {
|
|
103
|
+
const installing = provider.install?.();
|
|
104
|
+
Promise.resolve(installing).catch((cause) => {
|
|
105
|
+
fail(provider.name, "install", cause);
|
|
106
|
+
});
|
|
107
|
+
} catch (cause) {
|
|
108
|
+
fail(provider.name, "install", cause);
|
|
109
|
+
}
|
|
110
|
+
return {
|
|
111
|
+
track(name, data = {}, trackOptions = {}) {
|
|
112
|
+
for (const provider of providers) {
|
|
113
|
+
const target = resolveEvent(provider, name);
|
|
114
|
+
if (target === void 0) continue;
|
|
115
|
+
try {
|
|
116
|
+
provider.track(target, data, trackOptions);
|
|
117
|
+
} catch (cause) {
|
|
118
|
+
fail(provider.name, name, cause);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
},
|
|
122
|
+
identify(user, traits) {
|
|
123
|
+
for (const provider of providers) try {
|
|
124
|
+
provider.identify?.(user, traits);
|
|
125
|
+
} catch (cause) {
|
|
126
|
+
fail(provider.name, "identify", cause);
|
|
127
|
+
}
|
|
128
|
+
},
|
|
129
|
+
consent(command, state) {
|
|
130
|
+
for (const provider of providers) try {
|
|
131
|
+
provider.consent?.(command, state);
|
|
132
|
+
} catch (cause) {
|
|
133
|
+
fail(provider.name, "consent", cause);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
//#endregion
|
|
139
|
+
export { createTracking, ga4 };
|
|
140
|
+
|
|
141
|
+
//# sourceMappingURL=browser.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"browser.js","names":[],"sources":["../src/providers/ga4.browser.ts","../src/browser.ts"],"sourcesContent":["import type { BrowserProvider, TrackOptions } from '../browser.js';\nimport type { ConsentState, EventBinding, EventData, UserData } from '../vocabulary.js';\n\ninterface GtagWindow {\n gtag?: (...args: unknown[]) => void;\n}\n\n/** Optional configuration for the GA4 browser provider. */\nexport interface Ga4BrowserConfig {\n /**\n * How this property spells each canonical event. Rarely needed: the\n * canonical vocabulary already is GA4's.\n */\n events?: Record<string, EventBinding<string>>;\n}\n\n// Server rendering reaches this module with no browser at all, where\n// `window` is a ReferenceError rather than `undefined`.\nfunction gtagWindow(): GtagWindow | undefined {\n return typeof window === 'undefined' ? undefined : (window as unknown as GtagWindow);\n}\n\n/**\n * Sends a command, or fails the way a hand-written call would.\n *\n * Writing `gtag(…)` on a page without Google's snippet throws, and this\n * library replicates that rather than swallowing it: a silent no-op is how a\n * host ends up believing it is measuring something.\n */\nfunction push(...args: unknown[]): void {\n const gtag = gtagWindow()?.gtag;\n\n if (!gtag) {\n throw new Error(\n \"ga4: window.gtag is not defined — add Google's tag to the page before creating tracking\",\n );\n }\n\n gtag(...args);\n}\n\n/**\n * Google Analytics 4 in the browser, through `gtag.js`.\n *\n * **This provider does not load Google's tag.** The tag belongs on the page,\n * installed the way Google documents it — a snippet in the HTML, or a tag\n * manager. This library talks to the tag that is already there; it never\n * injects a third-party script into your page, and it never issues the\n * property configuration that would emit a second page view.\n *\n * Which also means the initial consent declaration is not ours to make:\n * Google requires it before the property is configured, and the snippet that\n * configures the property is yours. Use {@link ConsentState} through\n * `consent()` for changes after that.\n *\n * @param measurementId - The `G-` id of the data stream, matching the tag on\n * the page.\n * @param config - Rarely needed event name overrides.\n * @returns A provider for `createTracking` from `tracklane/browser`.\n *\n * @example\n * ```ts\n * import { createTracking, ga4 } from 'tracklane/browser';\n *\n * // Google's own snippet is already in the page.\n * const { track } = createTracking({ providers: [ga4('G-XXXXXXX')] });\n *\n * track('purchase', { transaction_id: 'T-1', value: 49.9, currency: 'BRL' });\n * ```\n */\nexport function ga4(measurementId: string, config: Ga4BrowserConfig = {}): BrowserProvider {\n const { events } = config;\n\n return {\n name: 'ga4',\n // The canonical names already are GA4's, so every event passes through\n // under its own name unless the host says otherwise.\n default: 'passthrough',\n ...(events ? { events } : {}),\n\n track(name: string, data: EventData, _options: TrackOptions): void {\n // GA4 documents no browser-to-server deduplication, so `dedupId` maps\n // to nothing here. That is the exact translation of \"this concept does\n // not exist in this vendor\" — inventing a param would imply a merge\n // the platform never performs.\n //\n // `send_to` is written after the host's data on purpose: without it,\n // gtag sends to every configured property on the page, so the\n // addressing is the adapter's to own and not the host's to override.\n push('event', name, { ...data, send_to: measurementId });\n },\n\n identify(user: UserData, traits?: Record<string, unknown>): void {\n // GA4 documents no browser slot for email, phone or names. They map to\n // nothing, which is what \"this concept does not exist here\" means.\n if (user.userId !== undefined) push('set', { user_id: user.userId });\n if (traits) push('set', 'user_properties', traits);\n },\n\n consent(command: 'default' | 'update', state: ConsentState): void {\n // Verbatim: the library's consent vocabulary is Google's own spelling,\n // so there is nothing to translate and no chance to expand a signal\n // the host did not declare.\n push('consent', command, state);\n },\n };\n}\n","import { assertUniqueProviders, makeReporter, messageOf, resolveEvent } from './dispatch.js';\n\nexport { type Ga4BrowserConfig, ga4 } from './providers/ga4.browser.js';\n\nimport type {\n ConsentState,\n EventBinding,\n EventData,\n ProviderDefault,\n TrackingError,\n UserData,\n} from './vocabulary.js';\n\n/**\n * Everything the browser needs beyond the event itself.\n *\n * There is one field, and that is the point: in the browser each vendor tag\n * reads its own cookies and holds its own session, so the only thing left\n * for the host to supply is the value that ties this hit to a server-side\n * one.\n */\nexport interface TrackOptions {\n /**\n * The value that lets a vendor recognise this hit and a server-side hit as\n * one event. The library never invents it — the browser and the server do\n * not share a process, so only a value the host already owns (an order id)\n * can match on both sides.\n */\n dedupId?: string;\n}\n\n/**\n * A destination for browser events.\n *\n * This is the whole contract, and it is what a provider written outside this\n * package implements — the ones shipped here get no shortcut.\n */\nexport interface BrowserProvider<Target = string> {\n /** The vendor's fixed name. Registering one twice is an error. */\n name: string;\n /** What happens to a canonical event this vendor has no binding for. */\n default: ProviderDefault;\n /** How this vendor spells each canonical event. */\n events?: Record<string, EventBinding<Target>>;\n /** Loads the vendor tag. Runs once, at creation. */\n install?(): void | Promise<void>;\n track(name: Target, data: EventData, options: TrackOptions): void;\n /** Absent where the vendor keeps no user of its own. */\n identify?(user: UserData, traits?: Record<string, unknown>): void;\n /** Absent where the vendor documents no consent command. */\n consent?(command: 'default' | 'update', state: ConsentState): void;\n}\n\n/** Options accepted by {@link createTracking}. */\nexport interface BrowserTrackingOptions {\n providers: readonly BrowserProvider[];\n /**\n * The one diagnostic channel. Without it the library is silent, exactly as\n * a hand-written vendor call is.\n */\n onError?: (error: TrackingError) => void;\n}\n\n/** What {@link createTracking} returns. */\nexport interface BrowserTracking {\n /** Sends one event to every configured vendor. Never throws. */\n track(name: string, data?: EventData, options?: TrackOptions): void;\n /** Forwards the user to the vendors that hold one, and to nobody else. */\n identify(user: UserData, traits?: Record<string, unknown>): void;\n /**\n * Forwards a consent declaration to every vendor that documents a command\n * for it. It never decides, stores or withholds anything.\n */\n consent(command: 'default' | 'update', state: ConsentState): void;\n}\n\n/**\n * Creates the browser tracking surface.\n *\n * Providers install eagerly, which is what pasting a vendor snippet does and\n * what lets each vendor record its own initial page view. Every vendor\n * shipped here queues its own commands until its script lands, so nothing is\n * lost to loading and this library needs no queue of its own.\n *\n * @param options - The providers to send to, and an optional error channel.\n * @returns The `track`, `identify` and `consent` calls.\n *\n * @example\n * ```ts\n * import { createTracking, ga4 } from 'tracklane/browser';\n *\n * const { track } = createTracking({ providers: [ga4('G-XXXXXXX')] });\n * track('purchase', { transaction_id: 'T-1', value: 49.9, currency: 'BRL' });\n * ```\n */\nexport function createTracking(options: BrowserTrackingOptions): BrowserTracking {\n const { providers } = options;\n assertUniqueProviders(providers);\n\n const report = makeReporter(options.onError);\n\n const fail = (provider: string, event: string, cause: unknown): void => {\n report({ provider, event, severity: 'error', message: messageOf(cause), cause });\n };\n\n for (const provider of providers) {\n try {\n const installing = provider.install?.();\n // An async loader that rejects would otherwise become an unhandled\n // rejection — the silent failure this channel exists to prevent.\n void Promise.resolve(installing).catch((cause: unknown) => {\n fail(provider.name, 'install', cause);\n });\n } catch (cause) {\n fail(provider.name, 'install', cause);\n }\n }\n\n return {\n track(name, data = {}, trackOptions = {}) {\n for (const provider of providers) {\n const target = resolveEvent(provider, name);\n if (target === undefined) continue;\n\n try {\n provider.track(target, data, trackOptions);\n } catch (cause) {\n fail(provider.name, name, cause);\n }\n }\n },\n\n identify(user, traits) {\n for (const provider of providers) {\n try {\n provider.identify?.(user, traits);\n } catch (cause) {\n fail(provider.name, 'identify', cause);\n }\n }\n },\n\n consent(command, state) {\n for (const provider of providers) {\n try {\n provider.consent?.(command, state);\n } catch (cause) {\n fail(provider.name, 'consent', cause);\n }\n }\n },\n };\n}\n"],"mappings":";;AAkBA,SAAS,aAAqC;CAC5C,OAAO,OAAO,WAAW,cAAc,KAAA,IAAa;AACtD;;;;;;;;AASA,SAAS,KAAK,GAAG,MAAuB;CACtC,MAAM,OAAO,WAAW,CAAC,EAAE;CAE3B,IAAI,CAAC,MACH,MAAM,IAAI,MACR,yFACF;CAGF,KAAK,GAAG,IAAI;AACd;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,SAAgB,IAAI,eAAuB,SAA2B,CAAC,GAAoB;CACzF,MAAM,EAAE,WAAW;CAEnB,OAAO;EACL,MAAM;EAGN,SAAS;EACT,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;EAE3B,MAAM,MAAc,MAAiB,UAA8B;GASjE,KAAK,SAAS,MAAM;IAAE,GAAG;IAAM,SAAS;GAAc,CAAC;EACzD;EAEA,SAAS,MAAgB,QAAwC;GAG/D,IAAI,KAAK,WAAW,KAAA,GAAW,KAAK,OAAO,EAAE,SAAS,KAAK,OAAO,CAAC;GACnE,IAAI,QAAQ,KAAK,OAAO,mBAAmB,MAAM;EACnD;EAEA,QAAQ,SAA+B,OAA2B;GAIhE,KAAK,WAAW,SAAS,KAAK;EAChC;CACF;AACF;;;;;;;;;;;;;;;;;;;;;;ACXA,SAAgB,eAAe,SAAkD;CAC/E,MAAM,EAAE,cAAc;CACtB,sBAAsB,SAAS;CAE/B,MAAM,SAAS,aAAa,QAAQ,OAAO;CAE3C,MAAM,QAAQ,UAAkB,OAAe,UAAyB;EACtE,OAAO;GAAE;GAAU;GAAO,UAAU;GAAS,SAAS,UAAU,KAAK;GAAG;EAAM,CAAC;CACjF;CAEA,KAAK,MAAM,YAAY,WACrB,IAAI;EACF,MAAM,aAAa,SAAS,UAAU;EAGtC,QAAa,QAAQ,UAAU,CAAC,CAAC,OAAO,UAAmB;GACzD,KAAK,SAAS,MAAM,WAAW,KAAK;EACtC,CAAC;CACH,SAAS,OAAO;EACd,KAAK,SAAS,MAAM,WAAW,KAAK;CACtC;CAGF,OAAO;EACL,MAAM,MAAM,OAAO,CAAC,GAAG,eAAe,CAAC,GAAG;GACxC,KAAK,MAAM,YAAY,WAAW;IAChC,MAAM,SAAS,aAAa,UAAU,IAAI;IAC1C,IAAI,WAAW,KAAA,GAAW;IAE1B,IAAI;KACF,SAAS,MAAM,QAAQ,MAAM,YAAY;IAC3C,SAAS,OAAO;KACd,KAAK,SAAS,MAAM,MAAM,KAAK;IACjC;GACF;EACF;EAEA,SAAS,MAAM,QAAQ;GACrB,KAAK,MAAM,YAAY,WACrB,IAAI;IACF,SAAS,WAAW,MAAM,MAAM;GAClC,SAAS,OAAO;IACd,KAAK,SAAS,MAAM,YAAY,KAAK;GACvC;EAEJ;EAEA,QAAQ,SAAS,OAAO;GACtB,KAAK,MAAM,YAAY,WACrB,IAAI;IACF,SAAS,UAAU,SAAS,KAAK;GACnC,SAAS,OAAO;IACd,KAAK,SAAS,MAAM,WAAW,KAAK;GACtC;EAEJ;CACF;AACF"}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
//#region src/dispatch.ts
|
|
2
|
+
/**
|
|
3
|
+
* Registering one vendor twice is a hard error rather than a merge: there is
|
|
4
|
+
* nothing a second registration could say that the first cannot, and
|
|
5
|
+
* accepting both would double every event to that vendor — a defect that
|
|
6
|
+
* surfaces weeks later as inflated conversions.
|
|
7
|
+
*/
|
|
8
|
+
function assertUniqueProviders(providers) {
|
|
9
|
+
const seen = /* @__PURE__ */ new Set();
|
|
10
|
+
for (const provider of providers) {
|
|
11
|
+
if (seen.has(provider.name)) throw new Error(`tracklane: provider "${provider.name}" is registered twice. One configuration per vendor.`);
|
|
12
|
+
seen.add(provider.name);
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Resolves how a vendor spells a canonical event, or `undefined` when
|
|
17
|
+
* nothing should be sent.
|
|
18
|
+
*
|
|
19
|
+
* Not sending is a legitimate outcome rather than a failure: `null` is the
|
|
20
|
+
* host saying "never send this event here", and `ignore` is a vendor whose
|
|
21
|
+
* event identity is minted per account in its own dashboard, so there is no
|
|
22
|
+
* name that could possibly be guessed.
|
|
23
|
+
*/
|
|
24
|
+
function resolveEvent(provider, name) {
|
|
25
|
+
const events = provider.events;
|
|
26
|
+
const binding = events && Object.hasOwn(events, name) ? events[name] : void 0;
|
|
27
|
+
if (binding === null) return void 0;
|
|
28
|
+
if (binding !== void 0) return binding;
|
|
29
|
+
if (provider.default === "ignore") return void 0;
|
|
30
|
+
return name;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Builds the reporting channel. A host that passes no `onError` gets
|
|
34
|
+
* silence, which is what a hand-written vendor call gives it.
|
|
35
|
+
*/
|
|
36
|
+
function makeReporter(onError) {
|
|
37
|
+
if (!onError) return () => {};
|
|
38
|
+
return (error) => {
|
|
39
|
+
try {
|
|
40
|
+
onError(error);
|
|
41
|
+
} catch {}
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
/** Normalises whatever a provider threw into a reportable message. */
|
|
45
|
+
function messageOf(cause) {
|
|
46
|
+
return cause instanceof Error ? cause.message : String(cause);
|
|
47
|
+
}
|
|
48
|
+
//#endregion
|
|
49
|
+
export { resolveEvent as i, makeReporter as n, messageOf as r, assertUniqueProviders as t };
|
|
50
|
+
|
|
51
|
+
//# sourceMappingURL=dispatch-DK2GBnkt.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"dispatch-DK2GBnkt.js","names":[],"sources":["../src/dispatch.ts"],"sourcesContent":["import type { EventBinding, ProviderDefault, TrackingError } from './vocabulary.js';\n\n/** The part of a provider both libraries resolve event names against. */\ninterface Resolvable<Target> {\n name: string;\n default: ProviderDefault;\n events?: Record<string, EventBinding<Target>>;\n}\n\n/**\n * Registering one vendor twice is a hard error rather than a merge: there is\n * nothing a second registration could say that the first cannot, and\n * accepting both would double every event to that vendor — a defect that\n * surfaces weeks later as inflated conversions.\n */\nexport function assertUniqueProviders(providers: readonly { name: string }[]): void {\n const seen = new Set<string>();\n\n for (const provider of providers) {\n if (seen.has(provider.name)) {\n throw new Error(\n `tracklane: provider \"${provider.name}\" is registered twice. One configuration per vendor.`,\n );\n }\n seen.add(provider.name);\n }\n}\n\n/**\n * Resolves how a vendor spells a canonical event, or `undefined` when\n * nothing should be sent.\n *\n * Not sending is a legitimate outcome rather than a failure: `null` is the\n * host saying \"never send this event here\", and `ignore` is a vendor whose\n * event identity is minted per account in its own dashboard, so there is no\n * name that could possibly be guessed.\n */\nexport function resolveEvent<Target>(\n provider: Resolvable<Target>,\n name: string,\n): Target | undefined {\n const events = provider.events;\n // `hasOwn`, not a plain lookup: every object inherits `constructor` and\n // `toString`, so an event named either would otherwise resolve to a\n // function off the prototype chain.\n const binding = events && Object.hasOwn(events, name) ? events[name] : undefined;\n\n if (binding === null) return undefined;\n if (binding !== undefined) return binding;\n if (provider.default === 'ignore') return undefined;\n\n return name as Target;\n}\n\n/**\n * Builds the reporting channel. A host that passes no `onError` gets\n * silence, which is what a hand-written vendor call gives it.\n */\nexport function makeReporter(\n onError: ((error: TrackingError) => void) | undefined,\n): (error: TrackingError) => void {\n if (!onError) return () => {};\n\n return (error) => {\n // A throwing reporter must not take the dispatch down with it, or a\n // host's broken logger becomes a broken checkout.\n try {\n onError(error);\n } catch {\n /* the reporter is the last line; there is nowhere left to report to */\n }\n };\n}\n\n/** Normalises whatever a provider threw into a reportable message. */\nexport function messageOf(cause: unknown): string {\n return cause instanceof Error ? cause.message : String(cause);\n}\n"],"mappings":";;;;;;;AAeA,SAAgB,sBAAsB,WAA8C;CAClF,MAAM,uBAAO,IAAI,IAAY;CAE7B,KAAK,MAAM,YAAY,WAAW;EAChC,IAAI,KAAK,IAAI,SAAS,IAAI,GACxB,MAAM,IAAI,MACR,wBAAwB,SAAS,KAAK,qDACxC;EAEF,KAAK,IAAI,SAAS,IAAI;CACxB;AACF;;;;;;;;;;AAWA,SAAgB,aACd,UACA,MACoB;CACpB,MAAM,SAAS,SAAS;CAIxB,MAAM,UAAU,UAAU,OAAO,OAAO,QAAQ,IAAI,IAAI,OAAO,QAAQ,KAAA;CAEvE,IAAI,YAAY,MAAM,OAAO,KAAA;CAC7B,IAAI,YAAY,KAAA,GAAW,OAAO;CAClC,IAAI,SAAS,YAAY,UAAU,OAAO,KAAA;CAE1C,OAAO;AACT;;;;;AAMA,SAAgB,aACd,SACgC;CAChC,IAAI,CAAC,SAAS,aAAa,CAAC;CAE5B,QAAQ,UAAU;EAGhB,IAAI;GACF,QAAQ,KAAK;EACf,QAAQ,CAER;CACF;AACF;;AAGA,SAAgB,UAAU,OAAwB;CAChD,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { a as EventItem, c as UserData, i as EventData, n as ConsentState, o as ProviderDefault, r as EventBinding, s as TrackingError, t as ActionSource } from "./vocabulary-ByyXHVWd.js";
|
|
2
|
+
import { i as TrackOptions, n as BrowserTracking, r as BrowserTrackingOptions, t as BrowserProvider } from "./browser-BQNJ4qUq.js";
|
|
3
|
+
import { a as ServerTrackingOptions, i as ServerTracking, n as ResolvedContext, r as ServerProvider, t as EventContext } from "./server-cNxLsKhl.js";
|
|
4
|
+
export type { ActionSource, BrowserProvider, BrowserTracking, BrowserTrackingOptions, ConsentState, EventBinding, EventContext, EventData, EventItem, ProviderDefault, ResolvedContext, ServerProvider, ServerTracking, ServerTrackingOptions, TrackOptions, TrackingError, UserData };
|
package/dist/index.js
ADDED
|
File without changes
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { c as UserData, i as EventData, n as ConsentState, o as ProviderDefault, r as EventBinding, s as TrackingError, t as ActionSource } from "./vocabulary-ByyXHVWd.js";
|
|
2
|
+
//#region src/providers/ga4.server.d.ts
|
|
3
|
+
/** Credentials for the GA4 Measurement Protocol. */
|
|
4
|
+
interface Ga4ServerCredentials {
|
|
5
|
+
/** The `G-` id of the data stream. */
|
|
6
|
+
measurementId: string;
|
|
7
|
+
/** Created under Admin → Data Streams → Measurement Protocol. */
|
|
8
|
+
apiSecret: string;
|
|
9
|
+
}
|
|
10
|
+
/** Optional configuration for the GA4 server provider. */
|
|
11
|
+
interface Ga4ServerConfig {
|
|
12
|
+
events?: Record<string, EventBinding<string>>;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Google Analytics 4 on the server, through the Measurement Protocol.
|
|
16
|
+
*
|
|
17
|
+
* @param credentials - The measurement id and API secret.
|
|
18
|
+
* @param config - Rarely needed event name overrides.
|
|
19
|
+
* @returns A provider for `createTracking` from `tracklane/server`.
|
|
20
|
+
*
|
|
21
|
+
* @example
|
|
22
|
+
* ```ts
|
|
23
|
+
* import { createTracking, ga4 } from 'tracklane/server';
|
|
24
|
+
*
|
|
25
|
+
* const { track } = createTracking({
|
|
26
|
+
* providers: [ga4({ measurementId: 'G-XXXXXXX', apiSecret: process.env.GA4_SECRET! })],
|
|
27
|
+
* });
|
|
28
|
+
*
|
|
29
|
+
* await track('purchase', order, { cookies: request.headers.get('cookie') });
|
|
30
|
+
* ```
|
|
31
|
+
*/
|
|
32
|
+
declare function ga4(credentials: Ga4ServerCredentials, config?: Ga4ServerConfig): ServerProvider;
|
|
33
|
+
//#endregion
|
|
34
|
+
//#region src/server.d.ts
|
|
35
|
+
/**
|
|
36
|
+
* Everything a conversion API needs beyond the event itself: who the person
|
|
37
|
+
* is, when it happened, and where it was observed.
|
|
38
|
+
*
|
|
39
|
+
* None of this is "what happened", which is why it does not travel in the
|
|
40
|
+
* event data — putting it there would leak identity into the pass-through
|
|
41
|
+
* event params of the vendors that forward the payload as-is.
|
|
42
|
+
*/
|
|
43
|
+
interface EventContext {
|
|
44
|
+
user?: UserData;
|
|
45
|
+
/**
|
|
46
|
+
* The request's raw `Cookie` header, or an already-parsed map.
|
|
47
|
+
*
|
|
48
|
+
* These are cookies the vendors' own browser tags set — this library never
|
|
49
|
+
* writes one. On the server each adapter reads the cookies belonging to
|
|
50
|
+
* its own vendor: Meta forwards its value as-is, Google's holds several
|
|
51
|
+
* things at once and has to be opened. That knowledge lives in the
|
|
52
|
+
* adapters; the core only splits `name=value; name=value` into pairs.
|
|
53
|
+
*
|
|
54
|
+
* **It splits, it does not interpret.** Values are handed over exactly as
|
|
55
|
+
* they appear, with no percent-decoding. The cookies these vendors set do
|
|
56
|
+
* not need it; a host reading some other cookie should decode it itself.
|
|
57
|
+
*/
|
|
58
|
+
cookies?: string | Record<string, string> | null;
|
|
59
|
+
/** Ties this send to a browser hit. Never invented by the library. */
|
|
60
|
+
dedupId?: string;
|
|
61
|
+
/**
|
|
62
|
+
* When the conversion actually happened. Defaults to now.
|
|
63
|
+
*
|
|
64
|
+
* A webhook arrives after the fact and LinkedIn rejects conversions older
|
|
65
|
+
* than 90 days, so reporting "now" for everything would quietly distort
|
|
66
|
+
* attribution.
|
|
67
|
+
*/
|
|
68
|
+
timestamp?: number | Date;
|
|
69
|
+
/** Overrides the factory default. Meta requires it on every event. */
|
|
70
|
+
source?: ActionSource;
|
|
71
|
+
url?: string;
|
|
72
|
+
ip?: string;
|
|
73
|
+
userAgent?: string;
|
|
74
|
+
/** What is known *about* the person: GA4 user properties, PostHog `$set`. */
|
|
75
|
+
traits?: Record<string, unknown>;
|
|
76
|
+
/**
|
|
77
|
+
* Travels inside the event, for the vendors that document such a field.
|
|
78
|
+
* Today that is GA4's Measurement Protocol, and it reads two of the
|
|
79
|
+
* signals; the others have no slot and ignore it.
|
|
80
|
+
*/
|
|
81
|
+
consent?: ConsentState;
|
|
82
|
+
}
|
|
83
|
+
/** The context an adapter receives, with the ambiguity resolved. */
|
|
84
|
+
interface ResolvedContext extends Omit<EventContext, "cookies" | "timestamp"> {
|
|
85
|
+
cookies: Record<string, string>;
|
|
86
|
+
/** Epoch milliseconds. Adapters convert to their vendor's spelling. */
|
|
87
|
+
timestamp: number;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* A destination for server events.
|
|
91
|
+
*
|
|
92
|
+
* `track` may throw — on a non-2xx, or where a vendor documents a
|
|
93
|
+
* precondition the event cannot meet. The dispatcher isolates and reports
|
|
94
|
+
* it, so adapters stay honest and loud.
|
|
95
|
+
*
|
|
96
|
+
* `report` is for a caveat about a request that already succeeded. It is
|
|
97
|
+
* never a throw: by then the send happened, and throwing would tell a host's
|
|
98
|
+
* retry logic to resend a delivered conversion.
|
|
99
|
+
*/
|
|
100
|
+
interface ServerProvider<Target = string> {
|
|
101
|
+
name: string;
|
|
102
|
+
default: ProviderDefault;
|
|
103
|
+
events?: Record<string, EventBinding<Target>>;
|
|
104
|
+
track(name: Target, data: EventData, context: ResolvedContext, report: (message: string) => void): Promise<void>;
|
|
105
|
+
}
|
|
106
|
+
/** Options accepted by {@link createTracking}. */
|
|
107
|
+
interface ServerTrackingOptions {
|
|
108
|
+
providers: readonly ServerProvider[];
|
|
109
|
+
onError?: (error: TrackingError) => void;
|
|
110
|
+
}
|
|
111
|
+
/** What {@link createTracking} returns. */
|
|
112
|
+
interface ServerTracking {
|
|
113
|
+
/**
|
|
114
|
+
* Sends one event to every configured conversion API.
|
|
115
|
+
*
|
|
116
|
+
* Resolves once every provider has settled and never rejects: one vendor
|
|
117
|
+
* being down is not the caller's failure to handle. Awaiting is about the
|
|
118
|
+
* request surviving a serverless runtime, not about delivery being
|
|
119
|
+
* guaranteed.
|
|
120
|
+
*/
|
|
121
|
+
track(name: string, data?: EventData, context?: EventContext): Promise<void>;
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Creates the server tracking surface.
|
|
125
|
+
*
|
|
126
|
+
* There is no `identify` here and nothing is held between calls: a server
|
|
127
|
+
* instance is shared by every request, so a retained identity would attach
|
|
128
|
+
* one visitor to another visitor's conversion. Identity travels with the
|
|
129
|
+
* call, which is also what every conversion API expects.
|
|
130
|
+
*
|
|
131
|
+
* There is no `consent` call either — consent commands are properties of a
|
|
132
|
+
* vendor's on-page tag, and a server request has no tag. The one vendor that
|
|
133
|
+
* accepts consent server-side reads it from the context.
|
|
134
|
+
*
|
|
135
|
+
* @param options - The providers to send to, and an optional error channel.
|
|
136
|
+
* @returns The `track` call.
|
|
137
|
+
*
|
|
138
|
+
* @example
|
|
139
|
+
* ```ts
|
|
140
|
+
* import { createTracking, ga4 } from 'tracklane/server';
|
|
141
|
+
*
|
|
142
|
+
* const { track } = createTracking({
|
|
143
|
+
* providers: [ga4({ measurementId: 'G-XXXXXXX', apiSecret })],
|
|
144
|
+
* });
|
|
145
|
+
*
|
|
146
|
+
* await track('purchase', order, { cookies: request.headers.get('cookie') });
|
|
147
|
+
* ```
|
|
148
|
+
*/
|
|
149
|
+
declare function createTracking(options: ServerTrackingOptions): ServerTracking;
|
|
150
|
+
//#endregion
|
|
151
|
+
export { ServerTrackingOptions as a, Ga4ServerCredentials as c, ServerTracking as i, ga4 as l, ResolvedContext as n, createTracking as o, ServerProvider as r, Ga4ServerConfig as s, EventContext as t };
|
|
152
|
+
//# sourceMappingURL=server-cNxLsKhl.d.ts.map
|
package/dist/server.d.ts
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { a as ServerTrackingOptions, c as Ga4ServerCredentials, i as ServerTracking, l as ga4, n as ResolvedContext, o as createTracking, r as ServerProvider, s as Ga4ServerConfig, t as EventContext } from "./server-cNxLsKhl.js";
|
|
2
|
+
export { EventContext, type Ga4ServerConfig, type Ga4ServerCredentials, ResolvedContext, ServerProvider, ServerTracking, ServerTrackingOptions, createTracking, ga4 };
|
package/dist/server.js
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import { i as resolveEvent, n as makeReporter, r as messageOf, t as assertUniqueProviders } from "./dispatch-DK2GBnkt.js";
|
|
2
|
+
//#region src/providers/ga4.server.ts
|
|
3
|
+
const ENDPOINT = "https://www.google-analytics.com/mp/collect";
|
|
4
|
+
/**
|
|
5
|
+
* The visitor cookie holds `GA1.<depth>.<client_id>`, and the client id
|
|
6
|
+
* itself contains a dot — so the identifier is the last two segments, which
|
|
7
|
+
* is what survives Google's varying prefix depth.
|
|
8
|
+
*
|
|
9
|
+
* The value must be the cookie as the browser wrote it. A host passing a
|
|
10
|
+
* parsed map passes cookie values, not values it took apart itself.
|
|
11
|
+
*/
|
|
12
|
+
function visitorId(cookies) {
|
|
13
|
+
const raw = cookies._ga;
|
|
14
|
+
if (!raw) return void 0;
|
|
15
|
+
const parts = raw.split(".");
|
|
16
|
+
if (parts.length < 4) return void 0;
|
|
17
|
+
return parts.slice(-2).join(".");
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* The per-container cookie carries the session, in one of two layouts.
|
|
21
|
+
*
|
|
22
|
+
* Verified against Google's live tag on 2026-07-31 rather than assumed:
|
|
23
|
+
*
|
|
24
|
+
* - `GS2.1.s1785511401$o1$g0$t1785511401$j60$l0$h0` — the current one. The
|
|
25
|
+
* third dot-segment packs several fields joined by `$`, and the session is
|
|
26
|
+
* the first of them, prefixed with `s`.
|
|
27
|
+
* - `GS1.1.1785511401.1.1.…` — the older one, where the third dot-segment is
|
|
28
|
+
* the session on its own.
|
|
29
|
+
*
|
|
30
|
+
* Reading the third segment blindly works for the old layout and returns the
|
|
31
|
+
* whole `s…$o1$g0$…` blob for the new one — which the vendor would accept and
|
|
32
|
+
* silently fail to match. Hence the two shapes, and hence `undefined` rather
|
|
33
|
+
* than a guess when neither fits.
|
|
34
|
+
*/
|
|
35
|
+
function sessionId(cookies, measurementId) {
|
|
36
|
+
const segment = cookies[`_ga_${measurementId.replace(/^G-/, "")}`]?.split(".")[2];
|
|
37
|
+
if (!segment) return void 0;
|
|
38
|
+
const packed = /^s(\d+)/.exec(segment);
|
|
39
|
+
if (packed) return packed[1];
|
|
40
|
+
return /^\d+$/.test(segment) ? segment : void 0;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* The Measurement Protocol documents exactly two consent fields, and spells
|
|
44
|
+
* their values in upper case where the browser spells them in lower — one of
|
|
45
|
+
* the small asymmetries an adapter absorbs so nobody else has to.
|
|
46
|
+
*/
|
|
47
|
+
function consentBody(state) {
|
|
48
|
+
if (!state) return void 0;
|
|
49
|
+
const body = {};
|
|
50
|
+
if (state.ad_user_data) body.ad_user_data = state.ad_user_data.toUpperCase();
|
|
51
|
+
if (state.ad_personalization) body.ad_personalization = state.ad_personalization.toUpperCase();
|
|
52
|
+
return Object.keys(body).length > 0 ? body : void 0;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Google Analytics 4 on the server, through the Measurement Protocol.
|
|
56
|
+
*
|
|
57
|
+
* @param credentials - The measurement id and API secret.
|
|
58
|
+
* @param config - Rarely needed event name overrides.
|
|
59
|
+
* @returns A provider for `createTracking` from `tracklane/server`.
|
|
60
|
+
*
|
|
61
|
+
* @example
|
|
62
|
+
* ```ts
|
|
63
|
+
* import { createTracking, ga4 } from 'tracklane/server';
|
|
64
|
+
*
|
|
65
|
+
* const { track } = createTracking({
|
|
66
|
+
* providers: [ga4({ measurementId: 'G-XXXXXXX', apiSecret: process.env.GA4_SECRET! })],
|
|
67
|
+
* });
|
|
68
|
+
*
|
|
69
|
+
* await track('purchase', order, { cookies: request.headers.get('cookie') });
|
|
70
|
+
* ```
|
|
71
|
+
*/
|
|
72
|
+
function ga4(credentials, config = {}) {
|
|
73
|
+
const { measurementId, apiSecret } = credentials;
|
|
74
|
+
return {
|
|
75
|
+
name: "ga4",
|
|
76
|
+
default: "passthrough",
|
|
77
|
+
...config.events ? { events: config.events } : {},
|
|
78
|
+
async track(name, data, context, report) {
|
|
79
|
+
const clientId = visitorId(context.cookies);
|
|
80
|
+
if (!clientId) throw new Error("ga4: cannot build client_id — no _ga cookie among the cookies passed in context");
|
|
81
|
+
const session = sessionId(context.cookies, measurementId);
|
|
82
|
+
if (!session) report("no session cookie (_ga_<container>): Google will accept this event and it will not appear in any report");
|
|
83
|
+
const params = { ...data };
|
|
84
|
+
if (session) {
|
|
85
|
+
params.session_id = session;
|
|
86
|
+
params.engagement_time_msec = 1;
|
|
87
|
+
}
|
|
88
|
+
const body = {
|
|
89
|
+
client_id: clientId,
|
|
90
|
+
timestamp_micros: context.timestamp * 1e3,
|
|
91
|
+
events: [{
|
|
92
|
+
name,
|
|
93
|
+
params
|
|
94
|
+
}]
|
|
95
|
+
};
|
|
96
|
+
if (context.user?.userId !== void 0) body.user_id = context.user.userId;
|
|
97
|
+
if (context.traits) body.user_properties = Object.fromEntries(Object.entries(context.traits).map(([name, value]) => [name, { value }]));
|
|
98
|
+
const consent = consentBody(context.consent);
|
|
99
|
+
if (consent) body.consent = consent;
|
|
100
|
+
const url = `${ENDPOINT}?measurement_id=${encodeURIComponent(measurementId)}&api_secret=${encodeURIComponent(apiSecret)}`;
|
|
101
|
+
const response = await fetch(url, {
|
|
102
|
+
method: "POST",
|
|
103
|
+
headers: { "content-type": "application/json" },
|
|
104
|
+
body: JSON.stringify(body)
|
|
105
|
+
});
|
|
106
|
+
if (!response.ok) throw new Error(`ga4: the Measurement Protocol answered ${response.status}`);
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
//#endregion
|
|
111
|
+
//#region src/server.ts
|
|
112
|
+
/** `name=value; name=value` — the shape of a `Cookie` header. */
|
|
113
|
+
function parseCookies(cookies) {
|
|
114
|
+
if (!cookies) return {};
|
|
115
|
+
if (typeof cookies !== "string") return cookies;
|
|
116
|
+
const parsed = {};
|
|
117
|
+
for (const pair of cookies.split(";")) {
|
|
118
|
+
const separator = pair.indexOf("=");
|
|
119
|
+
if (separator < 1) continue;
|
|
120
|
+
const name = pair.slice(0, separator).trim();
|
|
121
|
+
if (name) parsed[name] = pair.slice(separator + 1).trim();
|
|
122
|
+
}
|
|
123
|
+
return parsed;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Creates the server tracking surface.
|
|
127
|
+
*
|
|
128
|
+
* There is no `identify` here and nothing is held between calls: a server
|
|
129
|
+
* instance is shared by every request, so a retained identity would attach
|
|
130
|
+
* one visitor to another visitor's conversion. Identity travels with the
|
|
131
|
+
* call, which is also what every conversion API expects.
|
|
132
|
+
*
|
|
133
|
+
* There is no `consent` call either — consent commands are properties of a
|
|
134
|
+
* vendor's on-page tag, and a server request has no tag. The one vendor that
|
|
135
|
+
* accepts consent server-side reads it from the context.
|
|
136
|
+
*
|
|
137
|
+
* @param options - The providers to send to, and an optional error channel.
|
|
138
|
+
* @returns The `track` call.
|
|
139
|
+
*
|
|
140
|
+
* @example
|
|
141
|
+
* ```ts
|
|
142
|
+
* import { createTracking, ga4 } from 'tracklane/server';
|
|
143
|
+
*
|
|
144
|
+
* const { track } = createTracking({
|
|
145
|
+
* providers: [ga4({ measurementId: 'G-XXXXXXX', apiSecret })],
|
|
146
|
+
* });
|
|
147
|
+
*
|
|
148
|
+
* await track('purchase', order, { cookies: request.headers.get('cookie') });
|
|
149
|
+
* ```
|
|
150
|
+
*/
|
|
151
|
+
function createTracking(options) {
|
|
152
|
+
const { providers } = options;
|
|
153
|
+
assertUniqueProviders(providers);
|
|
154
|
+
const report = makeReporter(options.onError);
|
|
155
|
+
return { async track(name, data = {}, context = {}) {
|
|
156
|
+
const { cookies, timestamp, ...rest } = context;
|
|
157
|
+
const resolved = {
|
|
158
|
+
...rest,
|
|
159
|
+
cookies: parseCookies(cookies),
|
|
160
|
+
timestamp: timestamp instanceof Date ? timestamp.getTime() : timestamp ?? Date.now()
|
|
161
|
+
};
|
|
162
|
+
const sends = providers.map(async (provider) => {
|
|
163
|
+
const target = resolveEvent(provider, name);
|
|
164
|
+
if (target === void 0) return;
|
|
165
|
+
try {
|
|
166
|
+
await provider.track(target, data, resolved, (message) => {
|
|
167
|
+
report({
|
|
168
|
+
provider: provider.name,
|
|
169
|
+
event: name,
|
|
170
|
+
severity: "warning",
|
|
171
|
+
message
|
|
172
|
+
});
|
|
173
|
+
});
|
|
174
|
+
} catch (cause) {
|
|
175
|
+
report({
|
|
176
|
+
provider: provider.name,
|
|
177
|
+
event: name,
|
|
178
|
+
severity: "error",
|
|
179
|
+
message: messageOf(cause),
|
|
180
|
+
cause
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
});
|
|
184
|
+
await Promise.all(sends);
|
|
185
|
+
} };
|
|
186
|
+
}
|
|
187
|
+
//#endregion
|
|
188
|
+
export { createTracking, ga4 };
|
|
189
|
+
|
|
190
|
+
//# sourceMappingURL=server.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"server.js","names":[],"sources":["../src/providers/ga4.server.ts","../src/server.ts"],"sourcesContent":["import type { ResolvedContext, ServerProvider } from '../server.js';\nimport type { ConsentState, EventBinding, EventData } from '../vocabulary.js';\n\nconst ENDPOINT = 'https://www.google-analytics.com/mp/collect';\n\n/** Credentials for the GA4 Measurement Protocol. */\nexport interface Ga4ServerCredentials {\n /** The `G-` id of the data stream. */\n measurementId: string;\n /** Created under Admin → Data Streams → Measurement Protocol. */\n apiSecret: string;\n}\n\n/** Optional configuration for the GA4 server provider. */\nexport interface Ga4ServerConfig {\n events?: Record<string, EventBinding<string>>;\n}\n\n/**\n * The visitor cookie holds `GA1.<depth>.<client_id>`, and the client id\n * itself contains a dot — so the identifier is the last two segments, which\n * is what survives Google's varying prefix depth.\n *\n * The value must be the cookie as the browser wrote it. A host passing a\n * parsed map passes cookie values, not values it took apart itself.\n */\nfunction visitorId(cookies: Record<string, string>): string | undefined {\n const raw = cookies._ga;\n if (!raw) return undefined;\n\n const parts = raw.split('.');\n if (parts.length < 4) return undefined;\n\n return parts.slice(-2).join('.');\n}\n\n/**\n * The per-container cookie carries the session, in one of two layouts.\n *\n * Verified against Google's live tag on 2026-07-31 rather than assumed:\n *\n * - `GS2.1.s1785511401$o1$g0$t1785511401$j60$l0$h0` — the current one. The\n * third dot-segment packs several fields joined by `$`, and the session is\n * the first of them, prefixed with `s`.\n * - `GS1.1.1785511401.1.1.…` — the older one, where the third dot-segment is\n * the session on its own.\n *\n * Reading the third segment blindly works for the old layout and returns the\n * whole `s…$o1$g0$…` blob for the new one — which the vendor would accept and\n * silently fail to match. Hence the two shapes, and hence `undefined` rather\n * than a guess when neither fits.\n */\nfunction sessionId(cookies: Record<string, string>, measurementId: string): string | undefined {\n // Scoped to *this* property's cookie. A page with two GA4 properties has two\n // `_ga_*` cookies, and taking whichever came first would attach another\n // property's session to our event — which Google accepts and never matches.\n const value = cookies[`_ga_${measurementId.replace(/^G-/, '')}`];\n const segment = value?.split('.')[2];\n if (!segment) return undefined;\n\n const packed = /^s(\\d+)/.exec(segment);\n if (packed) return packed[1];\n\n // The older layout: a bare session id, nothing packed around it.\n return /^\\d+$/.test(segment) ? segment : undefined;\n}\n\n/**\n * The Measurement Protocol documents exactly two consent fields, and spells\n * their values in upper case where the browser spells them in lower — one of\n * the small asymmetries an adapter absorbs so nobody else has to.\n */\nfunction consentBody(state: ConsentState | undefined): Record<string, string> | undefined {\n if (!state) return undefined;\n\n const body: Record<string, string> = {};\n if (state.ad_user_data) body.ad_user_data = state.ad_user_data.toUpperCase();\n if (state.ad_personalization) body.ad_personalization = state.ad_personalization.toUpperCase();\n\n return Object.keys(body).length > 0 ? body : undefined;\n}\n\n/**\n * Google Analytics 4 on the server, through the Measurement Protocol.\n *\n * @param credentials - The measurement id and API secret.\n * @param config - Rarely needed event name overrides.\n * @returns A provider for `createTracking` from `tracklane/server`.\n *\n * @example\n * ```ts\n * import { createTracking, ga4 } from 'tracklane/server';\n *\n * const { track } = createTracking({\n * providers: [ga4({ measurementId: 'G-XXXXXXX', apiSecret: process.env.GA4_SECRET! })],\n * });\n *\n * await track('purchase', order, { cookies: request.headers.get('cookie') });\n * ```\n */\nexport function ga4(\n credentials: Ga4ServerCredentials,\n config: Ga4ServerConfig = {},\n): ServerProvider {\n const { measurementId, apiSecret } = credentials;\n\n return {\n name: 'ga4',\n default: 'passthrough',\n ...(config.events ? { events: config.events } : {}),\n\n async track(\n name: string,\n data: EventData,\n context: ResolvedContext,\n report: (message: string) => void,\n ): Promise<void> {\n const clientId = visitorId(context.cookies);\n if (!clientId) {\n // Not withholding on policy grounds: the protocol requires this and\n // it cannot be invented. The endpoint answers success even to\n // invalid payloads, so sending anyway would look like it worked.\n // Naming the vendor's own field, so that searching Google's docs\n // for the error leads somewhere.\n throw new Error(\n 'ga4: cannot build client_id — no _ga cookie among the cookies passed in context',\n );\n }\n\n const session = sessionId(context.cookies, measurementId);\n if (!session) {\n report(\n 'no session cookie (_ga_<container>): Google will accept this event and it will not appear in any report',\n );\n }\n\n const params: Record<string, unknown> = { ...data };\n if (session) {\n params.session_id = session;\n // Google drops sessions with no engagement from its reports, so the\n // event would arrive and still be invisible without this.\n params.engagement_time_msec = 1;\n }\n\n // The dedup id maps nowhere: GA4 documents no browser-to-server\n // deduplication. `transaction_id` — business data — travels in params\n // and is the duplicate control this vendor does have.\n const body: Record<string, unknown> = {\n client_id: clientId,\n timestamp_micros: context.timestamp * 1000,\n events: [{ name, params }],\n };\n\n if (context.user?.userId !== undefined) body.user_id = context.user.userId;\n\n if (context.traits) {\n // Each property is an object with a `value` key here, where the\n // browser takes the bare value. Sending the bare value is rejected\n // by Google's validation endpoint and **accepted with 204 by the\n // collection endpoint**, which then drops it — verified on\n // 2026-07-31. One of several places where this vendor fails by\n // accepting.\n body.user_properties = Object.fromEntries(\n Object.entries(context.traits).map(([name, value]) => [name, { value }]),\n );\n }\n\n const consent = consentBody(context.consent);\n if (consent) body.consent = consent;\n\n // Credentials go in the query because the protocol offers no\n // alternative. Query strings land in proxy and APM logs; that\n // exposure is Google's design, not a choice made here.\n const url = `${ENDPOINT}?measurement_id=${encodeURIComponent(measurementId)}&api_secret=${encodeURIComponent(apiSecret)}`;\n\n const response = await fetch(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n // The status only. The event carries raw personal data, and no\n // library-owned surface re-emits it into a host's logs.\n throw new Error(`ga4: the Measurement Protocol answered ${response.status}`);\n }\n },\n };\n}\n","import { assertUniqueProviders, makeReporter, messageOf, resolveEvent } from './dispatch.js';\n\nexport {\n type Ga4ServerConfig,\n type Ga4ServerCredentials,\n ga4,\n} from './providers/ga4.server.js';\n\nimport type {\n ActionSource,\n ConsentState,\n EventBinding,\n EventData,\n ProviderDefault,\n TrackingError,\n UserData,\n} from './vocabulary.js';\n\n/**\n * Everything a conversion API needs beyond the event itself: who the person\n * is, when it happened, and where it was observed.\n *\n * None of this is \"what happened\", which is why it does not travel in the\n * event data — putting it there would leak identity into the pass-through\n * event params of the vendors that forward the payload as-is.\n */\nexport interface EventContext {\n user?: UserData;\n /**\n * The request's raw `Cookie` header, or an already-parsed map.\n *\n * These are cookies the vendors' own browser tags set — this library never\n * writes one. On the server each adapter reads the cookies belonging to\n * its own vendor: Meta forwards its value as-is, Google's holds several\n * things at once and has to be opened. That knowledge lives in the\n * adapters; the core only splits `name=value; name=value` into pairs.\n *\n * **It splits, it does not interpret.** Values are handed over exactly as\n * they appear, with no percent-decoding. The cookies these vendors set do\n * not need it; a host reading some other cookie should decode it itself.\n */\n cookies?: string | Record<string, string> | null;\n /** Ties this send to a browser hit. Never invented by the library. */\n dedupId?: string;\n /**\n * When the conversion actually happened. Defaults to now.\n *\n * A webhook arrives after the fact and LinkedIn rejects conversions older\n * than 90 days, so reporting \"now\" for everything would quietly distort\n * attribution.\n */\n timestamp?: number | Date;\n /** Overrides the factory default. Meta requires it on every event. */\n source?: ActionSource;\n url?: string;\n ip?: string;\n userAgent?: string;\n /** What is known *about* the person: GA4 user properties, PostHog `$set`. */\n traits?: Record<string, unknown>;\n /**\n * Travels inside the event, for the vendors that document such a field.\n * Today that is GA4's Measurement Protocol, and it reads two of the\n * signals; the others have no slot and ignore it.\n */\n consent?: ConsentState;\n}\n\n/** The context an adapter receives, with the ambiguity resolved. */\nexport interface ResolvedContext extends Omit<EventContext, 'cookies' | 'timestamp'> {\n cookies: Record<string, string>;\n /** Epoch milliseconds. Adapters convert to their vendor's spelling. */\n timestamp: number;\n}\n\n/**\n * A destination for server events.\n *\n * `track` may throw — on a non-2xx, or where a vendor documents a\n * precondition the event cannot meet. The dispatcher isolates and reports\n * it, so adapters stay honest and loud.\n *\n * `report` is for a caveat about a request that already succeeded. It is\n * never a throw: by then the send happened, and throwing would tell a host's\n * retry logic to resend a delivered conversion.\n */\nexport interface ServerProvider<Target = string> {\n name: string;\n default: ProviderDefault;\n events?: Record<string, EventBinding<Target>>;\n track(\n name: Target,\n data: EventData,\n context: ResolvedContext,\n report: (message: string) => void,\n ): Promise<void>;\n}\n\n/** Options accepted by {@link createTracking}. */\nexport interface ServerTrackingOptions {\n providers: readonly ServerProvider[];\n onError?: (error: TrackingError) => void;\n}\n\n/** What {@link createTracking} returns. */\nexport interface ServerTracking {\n /**\n * Sends one event to every configured conversion API.\n *\n * Resolves once every provider has settled and never rejects: one vendor\n * being down is not the caller's failure to handle. Awaiting is about the\n * request surviving a serverless runtime, not about delivery being\n * guaranteed.\n */\n track(name: string, data?: EventData, context?: EventContext): Promise<void>;\n}\n\n/** `name=value; name=value` — the shape of a `Cookie` header. */\nfunction parseCookies(\n cookies: string | Record<string, string> | null | undefined,\n): Record<string, string> {\n if (!cookies) return {};\n if (typeof cookies !== 'string') return cookies;\n\n const parsed: Record<string, string> = {};\n\n for (const pair of cookies.split(';')) {\n const separator = pair.indexOf('=');\n if (separator < 1) continue;\n\n const name = pair.slice(0, separator).trim();\n // Cookie values may contain `=`, so only the first one separates.\n if (name) parsed[name] = pair.slice(separator + 1).trim();\n }\n\n return parsed;\n}\n\n/**\n * Creates the server tracking surface.\n *\n * There is no `identify` here and nothing is held between calls: a server\n * instance is shared by every request, so a retained identity would attach\n * one visitor to another visitor's conversion. Identity travels with the\n * call, which is also what every conversion API expects.\n *\n * There is no `consent` call either — consent commands are properties of a\n * vendor's on-page tag, and a server request has no tag. The one vendor that\n * accepts consent server-side reads it from the context.\n *\n * @param options - The providers to send to, and an optional error channel.\n * @returns The `track` call.\n *\n * @example\n * ```ts\n * import { createTracking, ga4 } from 'tracklane/server';\n *\n * const { track } = createTracking({\n * providers: [ga4({ measurementId: 'G-XXXXXXX', apiSecret })],\n * });\n *\n * await track('purchase', order, { cookies: request.headers.get('cookie') });\n * ```\n */\nexport function createTracking(options: ServerTrackingOptions): ServerTracking {\n const { providers } = options;\n assertUniqueProviders(providers);\n\n const report = makeReporter(options.onError);\n\n return {\n async track(name, data = {}, context = {}) {\n const { cookies, timestamp, ...rest } = context;\n const resolved: ResolvedContext = {\n ...rest,\n cookies: parseCookies(cookies),\n timestamp: timestamp instanceof Date ? timestamp.getTime() : (timestamp ?? Date.now()),\n };\n\n const sends = providers.map(async (provider) => {\n const target = resolveEvent(provider, name);\n if (target === undefined) return;\n\n try {\n await provider.track(target, data, resolved, (message) => {\n report({ provider: provider.name, event: name, severity: 'warning', message });\n });\n } catch (cause) {\n report({\n provider: provider.name,\n event: name,\n severity: 'error',\n message: messageOf(cause),\n cause,\n });\n }\n });\n\n await Promise.all(sends);\n },\n };\n}\n"],"mappings":";;AAGA,MAAM,WAAW;;;;;;;;;AAuBjB,SAAS,UAAU,SAAqD;CACtE,MAAM,MAAM,QAAQ;CACpB,IAAI,CAAC,KAAK,OAAO,KAAA;CAEjB,MAAM,QAAQ,IAAI,MAAM,GAAG;CAC3B,IAAI,MAAM,SAAS,GAAG,OAAO,KAAA;CAE7B,OAAO,MAAM,MAAM,EAAE,CAAC,CAAC,KAAK,GAAG;AACjC;;;;;;;;;;;;;;;;;AAkBA,SAAS,UAAU,SAAiC,eAA2C;CAK7F,MAAM,UADQ,QAAQ,OAAO,cAAc,QAAQ,OAAO,EAAE,IACvC,EAAE,MAAM,GAAG,CAAC,CAAC;CAClC,IAAI,CAAC,SAAS,OAAO,KAAA;CAErB,MAAM,SAAS,UAAU,KAAK,OAAO;CACrC,IAAI,QAAQ,OAAO,OAAO;CAG1B,OAAO,QAAQ,KAAK,OAAO,IAAI,UAAU,KAAA;AAC3C;;;;;;AAOA,SAAS,YAAY,OAAqE;CACxF,IAAI,CAAC,OAAO,OAAO,KAAA;CAEnB,MAAM,OAA+B,CAAC;CACtC,IAAI,MAAM,cAAc,KAAK,eAAe,MAAM,aAAa,YAAY;CAC3E,IAAI,MAAM,oBAAoB,KAAK,qBAAqB,MAAM,mBAAmB,YAAY;CAE7F,OAAO,OAAO,KAAK,IAAI,CAAC,CAAC,SAAS,IAAI,OAAO,KAAA;AAC/C;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,IACd,aACA,SAA0B,CAAC,GACX;CAChB,MAAM,EAAE,eAAe,cAAc;CAErC,OAAO;EACL,MAAM;EACN,SAAS;EACT,GAAI,OAAO,SAAS,EAAE,QAAQ,OAAO,OAAO,IAAI,CAAC;EAEjD,MAAM,MACJ,MACA,MACA,SACA,QACe;GACf,MAAM,WAAW,UAAU,QAAQ,OAAO;GAC1C,IAAI,CAAC,UAMH,MAAM,IAAI,MACR,iFACF;GAGF,MAAM,UAAU,UAAU,QAAQ,SAAS,aAAa;GACxD,IAAI,CAAC,SACH,OACE,yGACF;GAGF,MAAM,SAAkC,EAAE,GAAG,KAAK;GAClD,IAAI,SAAS;IACX,OAAO,aAAa;IAGpB,OAAO,uBAAuB;GAChC;GAKA,MAAM,OAAgC;IACpC,WAAW;IACX,kBAAkB,QAAQ,YAAY;IACtC,QAAQ,CAAC;KAAE;KAAM;IAAO,CAAC;GAC3B;GAEA,IAAI,QAAQ,MAAM,WAAW,KAAA,GAAW,KAAK,UAAU,QAAQ,KAAK;GAEpE,IAAI,QAAQ,QAOV,KAAK,kBAAkB,OAAO,YAC5B,OAAO,QAAQ,QAAQ,MAAM,CAAC,CAAC,KAAK,CAAC,MAAM,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CACzE;GAGF,MAAM,UAAU,YAAY,QAAQ,OAAO;GAC3C,IAAI,SAAS,KAAK,UAAU;GAK5B,MAAM,MAAM,GAAG,SAAS,kBAAkB,mBAAmB,aAAa,EAAE,cAAc,mBAAmB,SAAS;GAEtH,MAAM,WAAW,MAAM,MAAM,KAAK;IAChC,QAAQ;IACR,SAAS,EAAE,gBAAgB,mBAAmB;IAC9C,MAAM,KAAK,UAAU,IAAI;GAC3B,CAAC;GAED,IAAI,CAAC,SAAS,IAGZ,MAAM,IAAI,MAAM,0CAA0C,SAAS,QAAQ;EAE/E;CACF;AACF;;;;ACvEA,SAAS,aACP,SACwB;CACxB,IAAI,CAAC,SAAS,OAAO,CAAC;CACtB,IAAI,OAAO,YAAY,UAAU,OAAO;CAExC,MAAM,SAAiC,CAAC;CAExC,KAAK,MAAM,QAAQ,QAAQ,MAAM,GAAG,GAAG;EACrC,MAAM,YAAY,KAAK,QAAQ,GAAG;EAClC,IAAI,YAAY,GAAG;EAEnB,MAAM,OAAO,KAAK,MAAM,GAAG,SAAS,CAAC,CAAC,KAAK;EAE3C,IAAI,MAAM,OAAO,QAAQ,KAAK,MAAM,YAAY,CAAC,CAAC,CAAC,KAAK;CAC1D;CAEA,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,SAAgB,eAAe,SAAgD;CAC7E,MAAM,EAAE,cAAc;CACtB,sBAAsB,SAAS;CAE/B,MAAM,SAAS,aAAa,QAAQ,OAAO;CAE3C,OAAO,EACL,MAAM,MAAM,MAAM,OAAO,CAAC,GAAG,UAAU,CAAC,GAAG;EACzC,MAAM,EAAE,SAAS,WAAW,GAAG,SAAS;EACxC,MAAM,WAA4B;GAChC,GAAG;GACH,SAAS,aAAa,OAAO;GAC7B,WAAW,qBAAqB,OAAO,UAAU,QAAQ,IAAK,aAAa,KAAK,IAAI;EACtF;EAEA,MAAM,QAAQ,UAAU,IAAI,OAAO,aAAa;GAC9C,MAAM,SAAS,aAAa,UAAU,IAAI;GAC1C,IAAI,WAAW,KAAA,GAAW;GAE1B,IAAI;IACF,MAAM,SAAS,MAAM,QAAQ,MAAM,WAAW,YAAY;KACxD,OAAO;MAAE,UAAU,SAAS;MAAM,OAAO;MAAM,UAAU;MAAW;KAAQ,CAAC;IAC/E,CAAC;GACH,SAAS,OAAO;IACd,OAAO;KACL,UAAU,SAAS;KACnB,OAAO;KACP,UAAU;KACV,SAAS,UAAU,KAAK;KACxB;IACF,CAAC;GACH;EACF,CAAC;EAED,MAAM,QAAQ,IAAI,KAAK;CACzB,EACF;AACF"}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
//#region src/vocabulary.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* The vocabulary shared by the browser and server libraries.
|
|
4
|
+
*
|
|
5
|
+
* These two libraries never talk to each other — no runtime, no state, no
|
|
6
|
+
* instance in common. What they share is this: the names of events and the
|
|
7
|
+
* shape of the data that travels with them, so that `purchase` means the
|
|
8
|
+
* same thing on both sides. It is the only sharing with a reason to exist.
|
|
9
|
+
*/
|
|
10
|
+
/** One item inside an ecommerce event, spelled the way GA4 spells it. */
|
|
11
|
+
interface EventItem {
|
|
12
|
+
item_id?: string;
|
|
13
|
+
item_name?: string;
|
|
14
|
+
price?: number;
|
|
15
|
+
quantity?: number;
|
|
16
|
+
[key: string]: unknown;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* The business payload of an event.
|
|
20
|
+
*
|
|
21
|
+
* The named fields are the ones adapters read to build vendor-specific value
|
|
22
|
+
* and content slots. The index signature is deliberate: a business measures
|
|
23
|
+
* things this vocabulary does not name, and closing the bag would make the
|
|
24
|
+
* library the arbiter of what may be measured.
|
|
25
|
+
*/
|
|
26
|
+
interface EventData {
|
|
27
|
+
transaction_id?: string;
|
|
28
|
+
value?: number;
|
|
29
|
+
currency?: string;
|
|
30
|
+
items?: EventItem[];
|
|
31
|
+
[key: string]: unknown;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Who the person is.
|
|
35
|
+
*
|
|
36
|
+
* One identifier for the person, which every vendor receives under its own
|
|
37
|
+
* name. Values are always raw — hashing and normalisation are field formats
|
|
38
|
+
* each vendor defines, applied inside the adapter that owns the field.
|
|
39
|
+
*
|
|
40
|
+
* Everything else that identifies someone arrives through cookies on the
|
|
41
|
+
* server, read by whichever adapter knows the format.
|
|
42
|
+
*/
|
|
43
|
+
interface UserData {
|
|
44
|
+
/** One id for the person, translated per vendor. */
|
|
45
|
+
userId?: string;
|
|
46
|
+
email?: string;
|
|
47
|
+
phone?: string;
|
|
48
|
+
firstName?: string;
|
|
49
|
+
lastName?: string;
|
|
50
|
+
/** From the URL rather than a cookie, which is why it is named here. */
|
|
51
|
+
twclid?: string;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Consent signals, in Google's own spelling.
|
|
55
|
+
*
|
|
56
|
+
* Google's is the most granular surface any of the five vendors exposes, so
|
|
57
|
+
* every other vendor receives a *collapse* of it. Carrying the finest
|
|
58
|
+
* resolution and reducing per vendor means a projection never claims more
|
|
59
|
+
* than the host declared — expanding a coarse answer into fine signals would
|
|
60
|
+
* invent information, and this library never does that.
|
|
61
|
+
*
|
|
62
|
+
* An absent signal produces no key: silence is not a denial, and converting
|
|
63
|
+
* it into one would put words in the visitor's mouth just as a grant would.
|
|
64
|
+
*/
|
|
65
|
+
interface ConsentState {
|
|
66
|
+
ad_storage?: "granted" | "denied";
|
|
67
|
+
analytics_storage?: "granted" | "denied";
|
|
68
|
+
ad_user_data?: "granted" | "denied";
|
|
69
|
+
ad_personalization?: "granted" | "denied";
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Where a conversion happened.
|
|
73
|
+
*
|
|
74
|
+
* Meta's vocabulary, adopted verbatim — it is the only vendor of the five
|
|
75
|
+
* that documents the concept, and it requires the field on every server
|
|
76
|
+
* event. Inventing a taxonomy and translating it would be both incomplete
|
|
77
|
+
* for Meta and meaningless to everyone else.
|
|
78
|
+
*/
|
|
79
|
+
type ActionSource = "website" | "app" | "email" | "phone_call" | "chat" | "physical_store" | "system_generated" | "business_messaging" | "other";
|
|
80
|
+
/**
|
|
81
|
+
* How a canonical event name is spelled for one vendor, or `null` to say
|
|
82
|
+
* "never send this event here".
|
|
83
|
+
*/
|
|
84
|
+
type EventBinding<Target> = Target | null;
|
|
85
|
+
/** What a provider does with a canonical event it has no binding for. */
|
|
86
|
+
type ProviderDefault = "passthrough" | "ignore";
|
|
87
|
+
/**
|
|
88
|
+
* Reported out of band, never thrown at the call site.
|
|
89
|
+
*
|
|
90
|
+
* Fanning out to N vendors means no single call site can catch anything, so
|
|
91
|
+
* this is the replica of the `try/catch` a host would have written around a
|
|
92
|
+
* hand-made call. `severity` separates "this did not arrive" from "this
|
|
93
|
+
* arrived, and here is something you should know".
|
|
94
|
+
*
|
|
95
|
+
* It never carries event contents: the payload holds raw personal data by
|
|
96
|
+
* design, and no library-owned surface re-emits it into a host's logs.
|
|
97
|
+
*/
|
|
98
|
+
interface TrackingError {
|
|
99
|
+
provider: string;
|
|
100
|
+
event: string;
|
|
101
|
+
severity: "error" | "warning";
|
|
102
|
+
message: string;
|
|
103
|
+
cause?: unknown;
|
|
104
|
+
}
|
|
105
|
+
//#endregion
|
|
106
|
+
export { EventItem as a, UserData as c, EventData as i, ConsentState as n, ProviderDefault as o, EventBinding as r, TrackingError as s, ActionSource as t };
|
|
107
|
+
//# sourceMappingURL=vocabulary-ByyXHVWd.d.ts.map
|
package/package.json
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "tracklane",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "One interface between your application and every tool that receives events — GA4, Meta, LinkedIn, PostHog, X, browser and server.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"analytics",
|
|
7
|
+
"tracking",
|
|
8
|
+
"conversions-api",
|
|
9
|
+
"ga4",
|
|
10
|
+
"meta-pixel",
|
|
11
|
+
"posthog",
|
|
12
|
+
"linkedin",
|
|
13
|
+
"typescript",
|
|
14
|
+
"esm"
|
|
15
|
+
],
|
|
16
|
+
"license": "MIT",
|
|
17
|
+
"author": "Bruno Bertolini <dev@brunobertolini.com>",
|
|
18
|
+
"homepage": "https://github.com/brunobertolini/tracklane#readme",
|
|
19
|
+
"repository": {
|
|
20
|
+
"type": "git",
|
|
21
|
+
"url": "git+https://github.com/brunobertolini/tracklane.git",
|
|
22
|
+
"directory": "packages/tracklane"
|
|
23
|
+
},
|
|
24
|
+
"bugs": "https://github.com/brunobertolini/tracklane/issues",
|
|
25
|
+
"type": "module",
|
|
26
|
+
"sideEffects": false,
|
|
27
|
+
"main": "./dist/index.js",
|
|
28
|
+
"types": "./dist/index.d.ts",
|
|
29
|
+
"exports": {
|
|
30
|
+
".": {
|
|
31
|
+
"types": "./dist/index.d.ts",
|
|
32
|
+
"default": "./dist/index.js"
|
|
33
|
+
},
|
|
34
|
+
"./browser": {
|
|
35
|
+
"types": "./dist/browser.d.ts",
|
|
36
|
+
"default": "./dist/browser.js"
|
|
37
|
+
},
|
|
38
|
+
"./server": {
|
|
39
|
+
"types": "./dist/server.d.ts",
|
|
40
|
+
"default": "./dist/server.js"
|
|
41
|
+
},
|
|
42
|
+
"./package.json": "./package.json"
|
|
43
|
+
},
|
|
44
|
+
"files": [
|
|
45
|
+
"dist"
|
|
46
|
+
],
|
|
47
|
+
"engines": {
|
|
48
|
+
"node": ">=22.14.0"
|
|
49
|
+
},
|
|
50
|
+
"publishConfig": {
|
|
51
|
+
"access": "public",
|
|
52
|
+
"provenance": true
|
|
53
|
+
},
|
|
54
|
+
"scripts": {
|
|
55
|
+
"build": "tsdown",
|
|
56
|
+
"dev": "tsdown --watch",
|
|
57
|
+
"test": "vitest run",
|
|
58
|
+
"test:coverage": "vitest run --coverage",
|
|
59
|
+
"typecheck": "tsc --noEmit",
|
|
60
|
+
"package:check": "publint --strict && attw --pack . --profile esm-only"
|
|
61
|
+
},
|
|
62
|
+
"devDependencies": {
|
|
63
|
+
"@arethetypeswrong/cli": "0.18.5",
|
|
64
|
+
"@types/node": "catalog:",
|
|
65
|
+
"@vitest/coverage-v8": "4.1.10",
|
|
66
|
+
"publint": "0.3.22",
|
|
67
|
+
"tsdown": "0.22.14",
|
|
68
|
+
"typescript": "catalog:",
|
|
69
|
+
"vitest": "4.1.10"
|
|
70
|
+
}
|
|
71
|
+
}
|