@tbdhdev/beacon-sdk 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +586 -2
- package/dist/astro.d.ts +10 -0
- package/dist/astro.js +26 -0
- package/dist/astro.js.map +1 -0
- package/dist/index-t-jJl5-d.d.ts +40 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -0
- package/dist/nuxt.d.ts +10 -0
- package/dist/nuxt.js +42 -0
- package/dist/nuxt.js.map +1 -0
- package/dist/react.d.ts +6 -0
- package/dist/react.js +15 -0
- package/dist/react.js.map +1 -0
- package/dist/server.d.ts +58 -0
- package/dist/server.js +102 -0
- package/dist/server.js.map +1 -0
- package/dist/solid.d.ts +7 -0
- package/dist/solid.js +44 -0
- package/dist/solid.js.map +1 -0
- package/dist/src-DaAShSXp.js +300 -0
- package/dist/src-DaAShSXp.js.map +1 -0
- package/dist/sveltekit.d.ts +7 -0
- package/dist/sveltekit.js +20 -0
- package/dist/sveltekit.js.map +1 -0
- package/dist/tanstack-router.d.ts +12 -0
- package/dist/tanstack-router.js +18 -0
- package/dist/tanstack-router.js.map +1 -0
- package/dist/vue.d.ts +20 -0
- package/dist/vue.js +31 -0
- package/dist/vue.js.map +1 -0
- package/package.json +113 -3
- package/src/astro.ts +29 -0
- package/src/core.ts +542 -0
- package/src/index.ts +58 -0
- package/src/nuxt.ts +50 -0
- package/src/react.ts +13 -0
- package/src/server.ts +219 -0
- package/src/solid.ts +63 -0
- package/src/sveltekit.ts +16 -0
- package/src/tanstack-router.ts +24 -0
- package/src/vue.ts +55 -0
package/src/server.ts
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
// Server-side events, and a first-party proxy for browser events, for any runtime with `fetch`:
|
|
2
|
+
// Node, Bun, Deno, edge functions, CI. Authenticated with an API key, so never import this into
|
|
3
|
+
// browser code.
|
|
4
|
+
// Same shape as the browser entry's BeaconProps. Defined here so the server entry never pulls in
|
|
5
|
+
// the DOM-based core, even for type checking.
|
|
6
|
+
export type BeaconProps = Record<string, string | number | boolean>;
|
|
7
|
+
|
|
8
|
+
export interface BeaconServerConfig {
|
|
9
|
+
/** Website id from the Beacon dashboard. */
|
|
10
|
+
websiteId: string;
|
|
11
|
+
/** Full event URL: your Beacon origin + ingest prefix + event path, e.g. `https://beacon.example.com/x/e`. */
|
|
12
|
+
endpoint: string;
|
|
13
|
+
/** API key with the `write:events` scope. Keep it in a server-only env var. */
|
|
14
|
+
apiKey: string;
|
|
15
|
+
/** Give up on a request (and reject) after this many milliseconds. Default `5000`. */
|
|
16
|
+
timeoutMs?: number;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Optional request details. Forward `ip` and `userAgent` to count the event toward the end user's visit. */
|
|
20
|
+
export interface BeaconEventContext {
|
|
21
|
+
/** Page the event belongs to (absolute URL). */
|
|
22
|
+
url?: string;
|
|
23
|
+
title?: string;
|
|
24
|
+
referrer?: string;
|
|
25
|
+
/** The end user's IP, e.g. from `x-forwarded-for`. Used for the visitor hash and country, never stored. */
|
|
26
|
+
ip?: string;
|
|
27
|
+
/** The end user's `user-agent` header. */
|
|
28
|
+
userAgent?: string;
|
|
29
|
+
/** Your own user id, like `identify()` in the browser. */
|
|
30
|
+
distinctId?: string;
|
|
31
|
+
language?: string;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface BeaconServer {
|
|
35
|
+
/** Send a custom event. Rejects if Beacon refuses it (bad key, unknown website, invalid payload). */
|
|
36
|
+
track(
|
|
37
|
+
name: string,
|
|
38
|
+
props?: BeaconProps,
|
|
39
|
+
context?: BeaconEventContext,
|
|
40
|
+
): Promise<void>;
|
|
41
|
+
/** Send an identify event for `distinctId`, with optional traits. */
|
|
42
|
+
identify(
|
|
43
|
+
distinctId: string,
|
|
44
|
+
traits?: BeaconProps,
|
|
45
|
+
context?: BeaconEventContext,
|
|
46
|
+
): Promise<void>;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function createBeaconServer(config: BeaconServerConfig): BeaconServer {
|
|
50
|
+
const send = async (
|
|
51
|
+
type: string,
|
|
52
|
+
name: string,
|
|
53
|
+
props: BeaconProps | undefined,
|
|
54
|
+
{
|
|
55
|
+
url,
|
|
56
|
+
title,
|
|
57
|
+
referrer,
|
|
58
|
+
ip,
|
|
59
|
+
userAgent,
|
|
60
|
+
distinctId,
|
|
61
|
+
language,
|
|
62
|
+
}: BeaconEventContext = {},
|
|
63
|
+
) => {
|
|
64
|
+
// Without a key, ingest would treat this as a browser event and answer an unhelpful 403.
|
|
65
|
+
// Trimmed: a key read from a secrets file often ends in a newline, which no header may hold.
|
|
66
|
+
const apiKey = config.apiKey?.trim();
|
|
67
|
+
const websiteId = config.websiteId?.trim();
|
|
68
|
+
|
|
69
|
+
for (const [field, value] of Object.entries({ apiKey, websiteId })) {
|
|
70
|
+
if (!value) {
|
|
71
|
+
throw new Error(`Beacon did not send "${name}": ${field} is missing`);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const response = await fetch(config.endpoint, {
|
|
76
|
+
method: "POST",
|
|
77
|
+
headers: {
|
|
78
|
+
Authorization: `Bearer ${apiKey}`,
|
|
79
|
+
"Content-Type": "application/json",
|
|
80
|
+
},
|
|
81
|
+
// Fields picked one by one: extra keys on a context object can't replace the event's own.
|
|
82
|
+
body: JSON.stringify({
|
|
83
|
+
website: websiteId,
|
|
84
|
+
type,
|
|
85
|
+
name,
|
|
86
|
+
props,
|
|
87
|
+
url,
|
|
88
|
+
title,
|
|
89
|
+
referrer,
|
|
90
|
+
ip,
|
|
91
|
+
language,
|
|
92
|
+
user_agent: userAgent,
|
|
93
|
+
id: distinctId,
|
|
94
|
+
}),
|
|
95
|
+
signal: AbortSignal.timeout(config.timeoutMs ?? 5000),
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
// The status is the whole answer: free the connection instead of leaving the body unread.
|
|
99
|
+
await response.body?.cancel().catch(() => undefined);
|
|
100
|
+
|
|
101
|
+
if (!response.ok) {
|
|
102
|
+
throw new Error(`Beacon rejected "${name}": HTTP ${response.status}`);
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
return {
|
|
107
|
+
track: (name, props, context) => send("event", name, props, context),
|
|
108
|
+
identify: (distinctId, traits, context) =>
|
|
109
|
+
send("identify", "identify", traits, { ...context, distinctId }),
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export interface BeaconProxyConfig {
|
|
114
|
+
/** Full event URL: your Beacon origin + ingest prefix + event path, e.g. `https://beacon.example.com/x/e`. */
|
|
115
|
+
endpoint: string;
|
|
116
|
+
/** API key with the `write:events` scope. It vouches for the visitor IP the proxy forwards. */
|
|
117
|
+
apiKey: string;
|
|
118
|
+
/**
|
|
119
|
+
* The visitor's IP, from a source your host guarantees: `forwardedFor(request)` behind a proxy that
|
|
120
|
+
* sets `x-forwarded-for` (Vercel, Caddy), Cloudflare's `cf-connecting-ip`, ... Without one, Beacon
|
|
121
|
+
* tells visitors apart only by user agent, with no country, and they share one rate limit.
|
|
122
|
+
*/
|
|
123
|
+
// `| undefined`: lookups like `forwardedFor()` return it, which exactOptionalPropertyTypes refuses.
|
|
124
|
+
clientIp?: string | null | undefined;
|
|
125
|
+
/** Give up on Beacon after this many milliseconds and answer 502. Default `5000`. */
|
|
126
|
+
timeoutMs?: number;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// The browser headers ingest reads. Cookies and everything else stay on your server.
|
|
130
|
+
const PROXIED_HEADERS = [
|
|
131
|
+
"content-type",
|
|
132
|
+
"user-agent",
|
|
133
|
+
"accept-language",
|
|
134
|
+
"origin",
|
|
135
|
+
"dnt",
|
|
136
|
+
"sec-gpc",
|
|
137
|
+
];
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* The last `x-forwarded-for` entry: the visitor's IP behind a proxy that sets or appends to the header
|
|
141
|
+
* (Vercel, Caddy, Nginx with `$proxy_add_x_forwarded_for`). With nothing in front, visitors write
|
|
142
|
+
* their own, so don't use it there.
|
|
143
|
+
*/
|
|
144
|
+
export function forwardedFor(request: Request): string | undefined {
|
|
145
|
+
return (
|
|
146
|
+
request.headers.get("x-forwarded-for")?.split(",").at(-1)?.trim() ||
|
|
147
|
+
undefined
|
|
148
|
+
);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
let warnedNoIp = false;
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Forwards a browser event, posted by `@tbdhdev/beacon-sdk` to a route on your own site, to Beacon. Ad
|
|
155
|
+
* blockers that refuse requests to analytics hosts let a same-site request through. Answers with
|
|
156
|
+
* Beacon's status and no body. Point the browser SDK's `endpoint` at the route, e.g. `/api/e`.
|
|
157
|
+
*/
|
|
158
|
+
export async function proxyBeacon(
|
|
159
|
+
request: Request,
|
|
160
|
+
config: BeaconProxyConfig,
|
|
161
|
+
): Promise<Response> {
|
|
162
|
+
const apiKey = config.apiKey?.trim();
|
|
163
|
+
|
|
164
|
+
for (const [field, value] of Object.entries({
|
|
165
|
+
endpoint: config.endpoint,
|
|
166
|
+
apiKey,
|
|
167
|
+
})) {
|
|
168
|
+
if (!value) {
|
|
169
|
+
return new Response(`Beacon proxy: ${field} is missing`, { status: 500 });
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
const ip = config.clientIp?.trim();
|
|
174
|
+
|
|
175
|
+
if (!ip && !warnedNoIp) {
|
|
176
|
+
warnedNoIp = true;
|
|
177
|
+
console.warn(
|
|
178
|
+
"Beacon proxy: no visitor IP, so visitors are told apart only by user agent and share one rate limit. Pass clientIp.",
|
|
179
|
+
);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const headers = new Headers({
|
|
183
|
+
Authorization: `Bearer ${apiKey}`,
|
|
184
|
+
// Ingest's ProxyHeader. "unknown" still marks the request as proxied, so browser rules apply.
|
|
185
|
+
"Beacon-Forwarded-For": ip || "unknown",
|
|
186
|
+
// Left out, the runtime sends its own ("node", "*"), which Beacon would take for the visitor's.
|
|
187
|
+
"User-Agent": "",
|
|
188
|
+
"Accept-Language": "",
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
for (const name of PROXIED_HEADERS) {
|
|
192
|
+
const value = request.headers.get(name);
|
|
193
|
+
|
|
194
|
+
if (value !== null) {
|
|
195
|
+
headers.set(name, value);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// Streamed, not buffered: Beacon stops reading past its 16 KiB cap, so a huge upload never sits in
|
|
200
|
+
// your server's memory. `duplex` is required for a stream body but missing from the DOM types.
|
|
201
|
+
const init: RequestInit & { duplex: "half" } = {
|
|
202
|
+
method: "POST",
|
|
203
|
+
headers,
|
|
204
|
+
body: request.body,
|
|
205
|
+
duplex: "half",
|
|
206
|
+
signal: AbortSignal.timeout(config.timeoutMs ?? 5000),
|
|
207
|
+
};
|
|
208
|
+
|
|
209
|
+
try {
|
|
210
|
+
const response = await fetch(config.endpoint, init);
|
|
211
|
+
|
|
212
|
+
await response.body?.cancel().catch(() => undefined);
|
|
213
|
+
|
|
214
|
+
return new Response(null, { status: response.status });
|
|
215
|
+
} catch {
|
|
216
|
+
// Unreachable, timed out, or a malformed endpoint: the visitor's page must not care.
|
|
217
|
+
return new Response(null, { status: 502 });
|
|
218
|
+
}
|
|
219
|
+
}
|
package/src/solid.ts
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { useIsRouting, useLocation } from "@solidjs/router";
|
|
2
|
+
import * as Solid from "solid-js";
|
|
3
|
+
import { type BeaconConfig, init, page } from "./index.js";
|
|
4
|
+
|
|
5
|
+
const { createReaction, untrack } = Solid;
|
|
6
|
+
// Solid 2 only (Solid 1 has no onSettled): runs once the enclosing <Loading> boundary shows its
|
|
7
|
+
// content, so the first pageview gets the first route's title even when that route is async.
|
|
8
|
+
const { onSettled } = Solid as { onSettled?: typeof Solid.onSettled };
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Starts Beacon in the browser and records a pageview per Solid Router location change. Render
|
|
12
|
+
* it once inside the router, e.g. in the root layout. Works on Solid 1 (SolidStart) and Solid 2.
|
|
13
|
+
* Nothing runs during SSR.
|
|
14
|
+
*/
|
|
15
|
+
export function Beacon(props: Omit<BeaconConfig, "autoPageviews">): null {
|
|
16
|
+
const location = useLocation();
|
|
17
|
+
const isRouting = useIsRouting();
|
|
18
|
+
const url = () => location.pathname + location.search;
|
|
19
|
+
// <Title> (Solid's head registry) writes in a microtask queued by the same pass.
|
|
20
|
+
const record = () => setTimeout(() => page(), 0);
|
|
21
|
+
// createReaction works the same in Solid 1 and 2 (createEffect and onMount don't). It fires once
|
|
22
|
+
// per change, after the new route rendered, so it re-arms itself each time. Its callbacks keep
|
|
23
|
+
// block bodies: Solid 2 treats a returned value as a cleanup.
|
|
24
|
+
const track = createReaction(() => {
|
|
25
|
+
record();
|
|
26
|
+
track(url);
|
|
27
|
+
});
|
|
28
|
+
// The first page waits out a navigation in flight: a <Beacon> in a layout mounts while the
|
|
29
|
+
// router is still loading that route, and a redirect on load is not a page of its own.
|
|
30
|
+
const settled = createReaction(() => {
|
|
31
|
+
if (untrack(isRouting)) {
|
|
32
|
+
settled(isRouting);
|
|
33
|
+
} else {
|
|
34
|
+
record();
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
// Read once, like init() itself: later prop changes are ignored.
|
|
39
|
+
init(untrack(() => ({ ...props, autoPageviews: false })));
|
|
40
|
+
track(url);
|
|
41
|
+
|
|
42
|
+
// init() and page() do nothing during SSR, but skip the timer there too.
|
|
43
|
+
if (typeof window !== "undefined") {
|
|
44
|
+
const first = () =>
|
|
45
|
+
setTimeout(() => {
|
|
46
|
+
if (untrack(isRouting)) {
|
|
47
|
+
settled(isRouting);
|
|
48
|
+
} else {
|
|
49
|
+
page();
|
|
50
|
+
}
|
|
51
|
+
}, 0);
|
|
52
|
+
|
|
53
|
+
if (onSettled) {
|
|
54
|
+
onSettled(() => {
|
|
55
|
+
first();
|
|
56
|
+
});
|
|
57
|
+
} else {
|
|
58
|
+
first();
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
return null;
|
|
63
|
+
}
|
package/src/sveltekit.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/// <reference types="@sveltejs/kit" />
|
|
2
|
+
|
|
3
|
+
import { afterNavigate } from "$app/navigation";
|
|
4
|
+
import { type BeaconConfig, init, page } from "./index.js";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Starts Beacon in the browser and records a pageview after the first render and every
|
|
8
|
+
* navigation. Call it from the root `+layout.svelte` script: like `afterNavigate`, it must run
|
|
9
|
+
* during component initialization. Does nothing during SSR.
|
|
10
|
+
*/
|
|
11
|
+
export function initBeacon(config: Omit<BeaconConfig, "autoPageviews">): void {
|
|
12
|
+
afterNavigate(() => {
|
|
13
|
+
init({ ...config, autoPageviews: false });
|
|
14
|
+
page();
|
|
15
|
+
});
|
|
16
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { type BeaconConfig, init, page } from "./index.js";
|
|
2
|
+
|
|
3
|
+
/** The part of a TanStack Router instance (React, Solid or Vue) that Beacon uses. */
|
|
4
|
+
interface TanStackRouter {
|
|
5
|
+
subscribe(event: "onRendered", listener: () => void): unknown;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Starts Beacon in the browser and records a pageview each time the router renders a new
|
|
10
|
+
* location, including hydration in TanStack Start. Call it where you create the router; on the
|
|
11
|
+
* server it does nothing.
|
|
12
|
+
*/
|
|
13
|
+
export function initBeacon(
|
|
14
|
+
router: TanStackRouter,
|
|
15
|
+
config: Omit<BeaconConfig, "autoPageviews">,
|
|
16
|
+
): void {
|
|
17
|
+
if (typeof window === "undefined") {
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
init({ ...config, autoPageviews: false });
|
|
22
|
+
// onRendered runs after the new route (and its <title>) is on screen.
|
|
23
|
+
router.subscribe("onRendered", () => page());
|
|
24
|
+
}
|
package/src/vue.ts
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { nextTick, type Plugin } from "vue";
|
|
2
|
+
import { type BeaconConfig, identify, init, page, track } from "./index.js";
|
|
3
|
+
|
|
4
|
+
/** The parts of a Vue Router instance that Beacon uses. */
|
|
5
|
+
interface VueRouter {
|
|
6
|
+
afterEach(
|
|
7
|
+
hook: (to: unknown, from: unknown, failure?: unknown) => void,
|
|
8
|
+
): () => void;
|
|
9
|
+
isReady(): Promise<unknown>;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface BeaconVueOptions extends BeaconConfig {
|
|
13
|
+
/** Record a pageview after each Vue Router navigation instead of watching the History API. */
|
|
14
|
+
router?: VueRouter;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Vue plugin: `app.use(beacon, { websiteId, endpoint, router })`. Safe during SSR. */
|
|
18
|
+
export const beacon: Plugin<[BeaconVueOptions]> = {
|
|
19
|
+
install(app, { router, ...config }) {
|
|
20
|
+
// Nothing to record during SSR.
|
|
21
|
+
if (typeof window === "undefined") {
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
if (!router) {
|
|
26
|
+
init(config);
|
|
27
|
+
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
init({ ...config, autoPageviews: false });
|
|
32
|
+
|
|
33
|
+
// After nextTick the new route has rendered and every afterEach hook (e.g. one setting
|
|
34
|
+
// document.title) has run.
|
|
35
|
+
const record = () => void nextTick(() => page());
|
|
36
|
+
|
|
37
|
+
// A failed navigation never rendered. A back/forward one a guard aborted still shows the
|
|
38
|
+
// refused URL until the router's history.go() undoes it.
|
|
39
|
+
app.onUnmount(
|
|
40
|
+
router.afterEach((_to, _from, failure) => {
|
|
41
|
+
if (!failure) {
|
|
42
|
+
record();
|
|
43
|
+
}
|
|
44
|
+
}),
|
|
45
|
+
);
|
|
46
|
+
// Covers an initial navigation that finished before the plugin was installed. If it failed (a
|
|
47
|
+
// guard threw), the app handles that error: it must not become an unhandled rejection here.
|
|
48
|
+
void router.isReady().then(record, () => undefined);
|
|
49
|
+
},
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
/** `track`, `identify` and `page` for `<script setup>` and composables. */
|
|
53
|
+
export function useBeacon() {
|
|
54
|
+
return { track, identify, page };
|
|
55
|
+
}
|