highseat 0.3.1 → 0.5.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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "highseat",
3
- "version": "0.3.1",
4
- "description": "Highseat analytics for JavaScript: typed tracking, a first-party proxy and framework components.",
3
+ "version": "0.5.0",
4
+ "description": "Highseat analytics for JavaScript: typed tracking in the browser and on the server, a first-party proxy and framework components.",
5
5
  "keywords": [
6
6
  "analytics",
7
7
  "cookieless",
@@ -38,6 +38,10 @@
38
38
  "./proxy": {
39
39
  "types": "./proxy.d.ts",
40
40
  "default": "./proxy.js"
41
+ },
42
+ "./server": {
43
+ "types": "./server.d.ts",
44
+ "default": "./server.js"
41
45
  }
42
46
  },
43
47
  "publishConfig": {
package/proxy.d.ts CHANGED
@@ -1,11 +1,5 @@
1
+ import { ClientIp, ClientIpPreset } from "./ingest.js";
1
2
  //#region src/proxy.d.ts
2
- /** A host whose own header carries the visitor's IP. */
3
- export type ClientIpPreset = "vercel" | "cloudflare" | "netlify" | "nginx";
4
- /**
5
- * Where the proxy reads the visitor's IP: a host preset, or a function for any other setup. A
6
- * function returns the IP, or nothing when the request carries none.
7
- */
8
- export type ClientIp = ClientIpPreset | ((request: Request) => string | null | undefined);
9
3
  export interface ProxyOptions {
10
4
  /**
11
5
  * The site's proxy path from Installation settings, such as `/3f9a0c1e2b`, with or without its
@@ -57,4 +51,5 @@ export type ProxyHandler = (request: Request) => Promise<Response>;
57
51
  */
58
52
  export declare function createProxy(options: ProxyOptions): ProxyHandler;
59
53
  //#endregion
54
+ export type { ClientIp, ClientIpPreset };
60
55
  //# sourceMappingURL=proxy.d.ts.map
package/proxy.js CHANGED
@@ -1,17 +1,6 @@
1
- import { findProxyPath, findSecret, isNextBuild } from "./env.js";
1
+ import { findProxyPath, isNextBuild } from "./env.js";
2
+ import { findValidSecret, getClientIpReader } from "./ingest.js";
2
3
  //#region src/proxy.ts
3
- const DEFAULT_UPSTREAM = "https://cdn.highseat.com";
4
- const SECRET_PREFIXES = [
5
- "hs_secret_",
6
- "hs_proxy_",
7
- "ana_proxy_"
8
- ];
9
- const CLIENT_IP_HEADERS = {
10
- vercel: "x-real-ip",
11
- cloudflare: "cf-connecting-ip",
12
- netlify: "x-nf-client-connection-ip",
13
- nginx: "x-real-ip"
14
- };
15
4
  const SCRIPT_REQUEST_HEADERS = ["user-agent", "if-none-match"];
16
5
  const EVENT_REQUEST_HEADERS = [
17
6
  "content-type",
@@ -35,18 +24,6 @@ const NULL_BODY_STATUSES = /* @__PURE__ */ new Set([
35
24
  ]);
36
25
  const UPSTREAM_TIMEOUT_MS = 1e4;
37
26
  const MAX_EVENT_BYTES = 524288;
38
- function getClientIpReader(clientIp) {
39
- if (typeof clientIp === "function") return {
40
- read: (request) => clientIp(request)?.trim() ?? "",
41
- source: "the clientIp function"
42
- };
43
- const header = CLIENT_IP_HEADERS[clientIp];
44
- if (!header) throw new Error(`highseat/proxy: unknown clientIp preset "${String(clientIp)}".`);
45
- return {
46
- read: (request) => request.headers.get(header)?.trim() ?? "",
47
- source: `the "${clientIp}" preset's ${header} header`
48
- };
49
- }
50
27
  function copyHeaders(from, to, names) {
51
28
  for (const name of names) {
52
29
  const value = from.get(name);
@@ -62,13 +39,6 @@ function answerError(status, error) {
62
39
  function answerOtherPath() {
63
40
  return answerError(404, "Not the proxy path. The Highseat proxy answers on its own path only.");
64
41
  }
65
- /** The site secret, or `undefined` when none is set. Throws on a value that is not one. */
66
- function findValidSecret(option) {
67
- const secret = option ?? findSecret();
68
- if (!secret) return;
69
- if (!SECRET_PREFIXES.some((prefix) => secret.startsWith(prefix))) throw new Error(`highseat/proxy: not a site secret. Copy it from the site's Installation settings; it starts with "${SECRET_PREFIXES[0]}".`);
70
- return secret;
71
- }
72
42
  let hasWarnedMissing = false;
73
43
  /**
74
44
  * The handler for a proxy missing a variable: every request goes to `fallback`, or the proxy
@@ -125,16 +95,16 @@ function createProxy(options) {
125
95
  const { fallback } = options;
126
96
  let foundSecret;
127
97
  try {
128
- foundSecret = findValidSecret(options.secret);
98
+ foundSecret = findValidSecret(options.secret, "highseat/proxy");
129
99
  } catch (error) {
130
100
  if (!isNextBuild()) throw error;
131
101
  return () => Promise.reject(error);
132
102
  }
133
- const upstream = new URL(options.upstream ?? DEFAULT_UPSTREAM).origin;
103
+ const upstream = new URL(options.upstream ?? "https://cdn.highseat.com").origin;
134
104
  const missing = [...fallback && path === void 0 ? ["HIGHSEAT_PATH"] : [], ...foundSecret ? [] : ["HIGHSEAT_SECRET"]];
135
105
  if (!foundSecret || missing.length) return createDisabledProxy(missing, path, fallback);
136
106
  const secret = foundSecret;
137
- const clientIpReader = getClientIpReader(options.clientIp);
107
+ const clientIpReader = getClientIpReader(options.clientIp, "highseat/proxy");
138
108
  let hasWarnedNoIp = false;
139
109
  function readClientIp(request) {
140
110
  const ip = clientIpReader.read(request);
package/proxy.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"proxy.js","names":[],"sources":["../src/proxy.ts"],"sourcesContent":["import { findProxyPath, findSecret, isNextBuild } from \"./env\"\n\n/** A host whose own header carries the visitor's IP. */\nexport type ClientIpPreset = \"vercel\" | \"cloudflare\" | \"netlify\" | \"nginx\"\n\n/**\n * Where the proxy reads the visitor's IP: a host preset, or a function for any other setup. A\n * function returns the IP, or nothing when the request carries none.\n */\nexport type ClientIp = ClientIpPreset | ((request: Request) => string | null | undefined)\n\nexport interface ProxyOptions {\n /**\n * The site's proxy path from Installation settings, such as `/3f9a0c1e2b`, with or without its\n * leading slash. A request on any\n * other path is answered 404, or handed to `fallback`. Defaults to the `HIGHSEAT_PATH`\n * environment variable. Leave both unset on a host whose router already sends only the proxy\n * path here, such as a file named after the path.\n */\n path?: string\n /**\n * The site secret, `hs_secret_…`, or an older one that starts `hs_proxy_` or `ana_proxy_`.\n * Defaults to the `HIGHSEAT_SECRET` environment variable. Without one the proxy is off: the\n * proxy path answers 503, or every request goes to `fallback`.\n */\n secret?: string\n /**\n * Where the visitor's IP comes from: `vercel`, `cloudflare`, `netlify`, `nginx` (the\n * `X-Real-IP` header your nginx sets), or a function. A visitor can write any header the host\n * does not overwrite, so there is no default.\n *\n * The outermost proxy that sets the header decides the preset. Behind a proxied Cloudflare\n * record, use `cloudflare` on any origin, not only a Worker or a Pages Function: a Next.js,\n * TanStack Start or Node server behind Cloudflare, with or without Traefik or nginx in between,\n * sees a Cloudflare edge address in `X-Real-IP`, and the visitor's IP in `cf-connecting-ip`.\n */\n clientIp: ClientIp\n /** The ingest origin the proxy forwards to. Defaults to `https://cdn.highseat.com`. */\n upstream?: string\n /**\n * Answers a request on any path other than `path`, for a handler that sees every request on\n * the site: `fetch` in a Cloudflare Worker routed on the whole site, `next` in a Pages\n * Function. Needs `path`: without it, or without the secret, the proxy is off and every\n * request goes here, so the site still serves in a development setup without the variables.\n */\n fallback?: (request: Request) => Response | Promise<Response>\n}\n\n/** A fetch handler, the shape every supported runtime and framework route accepts. */\nexport type ProxyHandler = (request: Request) => Promise<Response>\n\nconst DEFAULT_UPSTREAM = \"https://cdn.highseat.com\"\n// The current prefix first. Ingest still accepts the secrets minted under the older two, so a\n// site keeps its secret when it moves to this handler.\nconst SECRET_PREFIXES = [\"hs_secret_\", \"hs_proxy_\", \"ana_proxy_\"]\n\nconst CLIENT_IP_HEADERS: Record<ClientIpPreset, string> = {\n vercel: \"x-real-ip\",\n // Read from the inbound request: Cloudflare overwrites it on the Worker's own subrequest.\n cloudflare: \"cf-connecting-ip\",\n netlify: \"x-nf-client-connection-ip\",\n nginx: \"x-real-ip\",\n}\n\n// The visitor headers each direction forwards. Copied by name, so a cookie, an `Authorization`\n// header or a visitor's own `x-hs-*` header never reaches ingest.\nconst SCRIPT_REQUEST_HEADERS = [\"user-agent\", \"if-none-match\"]\nconst EVENT_REQUEST_HEADERS = [\"content-type\", \"user-agent\", \"origin\"]\n\n// The upstream headers the response keeps. Rebuilt by name because Node, Bun and Deno hand back\n// a decompressed body under the original `content-encoding` and `content-length`, which would\n// describe bytes this handler no longer has. `x-hs-ip` and `x-hs-ip-source` show which IP\n// ingest resolved, for `curl -i` against the proxy path.\nconst RESPONSE_HEADERS = [\n \"content-type\",\n \"etag\",\n \"cache-control\",\n \"vary\",\n \"retry-after\",\n \"x-hs-ip\",\n \"x-hs-ip-source\",\n]\n\n// Statuses whose response must not carry a body, which the Response constructor enforces.\nconst NULL_BODY_STATUSES = new Set([101, 204, 205, 304])\n\nconst UPSTREAM_TIMEOUT_MS = 10_000\n\n// Ingest refuses a larger batch, so a bigger body is answered here without buffering the rest.\nconst MAX_EVENT_BYTES = 512 * 1024\n\ninterface ClientIpReader {\n read: (request: Request) => string\n /** Where `read` looks, for the warning about an empty IP. */\n source: string\n}\n\nfunction getClientIpReader(clientIp: ClientIp): ClientIpReader {\n if (typeof clientIp === \"function\") {\n return { read: request => clientIp(request)?.trim() ?? \"\", source: \"the clientIp function\" }\n }\n\n const header = CLIENT_IP_HEADERS[clientIp]\n if (!header) throw new Error(`highseat/proxy: unknown clientIp preset \"${String(clientIp)}\".`)\n return {\n read: request => request.headers.get(header)?.trim() ?? \"\",\n source: `the \"${clientIp}\" preset's ${header} header`,\n }\n}\n\nfunction copyHeaders(from: Headers, to: Headers, names: string[]) {\n for (const name of names) {\n const value = from.get(name)\n if (value !== null) to.set(name, value)\n }\n}\n\nfunction answerError(status: number, error: string) {\n return Response.json({ error }, { status, headers: { \"cache-control\": \"no-store\" } })\n}\n\n// A JSON body rather than an empty 404, so `curl -i` on the route handler's own URL tells this\n// answer apart from ingest's.\nfunction answerOtherPath() {\n return answerError(404, \"Not the proxy path. The Highseat proxy answers on its own path only.\")\n}\n\n/** The site secret, or `undefined` when none is set. Throws on a value that is not one. */\nfunction findValidSecret(option: string | undefined): string | undefined {\n const secret = option ?? findSecret()\n if (!secret) return\n\n if (!SECRET_PREFIXES.some(prefix => secret.startsWith(prefix))) {\n throw new Error(\n `highseat/proxy: not a site secret. Copy it from the site's Installation settings; it starts with \"${SECRET_PREFIXES[0]}\".`,\n )\n }\n return secret\n}\n\n// The handler can be created per request (a Worker that reads its options from `env`), so a\n// missing variable is reported once per process rather than once per handler.\nlet hasWarnedMissing = false\n\n/**\n * The handler for a proxy missing a variable: every request goes to `fallback`, or the proxy\n * path answers 503 naming what is missing.\n */\nfunction createDisabledProxy(\n missing: string[],\n path: string | undefined,\n fallback: ProxyOptions[\"fallback\"],\n): ProxyHandler {\n const names = missing.join(\" and \")\n\n // A Next.js build loads every route without serving one, often without the runtime variables.\n if (!hasWarnedMissing && !isNextBuild()) {\n hasWarnedMissing = true\n const outcome = fallback ? \"every request goes to `fallback`\" : \"the proxy path answers 503\"\n console.warn(`highseat/proxy: ${names} not set, so the proxy is off and ${outcome}.`)\n }\n\n return async function proxy(request) {\n if (fallback) return fallback(request)\n if (path !== undefined && new URL(request.url).pathname !== path) return answerOtherPath()\n return answerError(503, `The Highseat proxy is off: set ${names}.`)\n }\n}\n\n/** The request body, or `undefined` once it passes `MAX_EVENT_BYTES`. */\nasync function readEventBody(request: Request): Promise<Uint8Array<ArrayBuffer> | undefined> {\n if (Number(request.headers.get(\"content-length\")) > MAX_EVENT_BYTES) return\n if (!request.body) return new Uint8Array()\n\n const reader = request.body.getReader()\n const chunks: Uint8Array[] = []\n let size = 0\n\n for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) {\n size += chunk.value.byteLength\n if (size > MAX_EVENT_BYTES) {\n void reader.cancel()\n return\n }\n chunks.push(chunk.value)\n }\n\n const body = new Uint8Array(size)\n let offset = 0\n for (const chunk of chunks) {\n body.set(chunk, offset)\n offset += chunk.byteLength\n }\n return body\n}\n\n/**\n * Creates the first-party proxy handler for a site. A GET serves the tracker script and a POST\n * forwards its events, both to the ingest host, with the site secret and the visitor's IP. The\n * returned function takes a `Request` and returns a `Response`, so it mounts as a Next.js route\n * handler, a Cloudflare Worker, a Pages Function, a Netlify or Vercel function, an Astro\n * endpoint or a Hono route.\n *\n * A missing path or secret never throws: the handler passes every request to `fallback`, or\n * answers the proxy path with a 503 naming the variable, and warns once. A value that is not a\n * site secret throws, since that is a copying mistake rather than a variable left unset.\n */\nexport function createProxy(options: ProxyOptions): ProxyHandler {\n const path = findProxyPath(options.path)\n const { fallback } = options\n let foundSecret: string | undefined\n\n try {\n foundSecret = findValidSecret(options.secret)\n } catch (error) {\n // Next.js loads every route while it builds, so there the error waits for the first request\n // rather than failing a build that never serves one.\n if (!isNextBuild()) throw error\n return () => Promise.reject(error)\n }\n\n const upstream = new URL(options.upstream ?? DEFAULT_UPSTREAM).origin\n\n // Without a secret, ingest would read every visitor as this server and drop it as datacenter\n // traffic. Without a path, a handler that sees every request cannot tell the proxy's apart.\n const missing = [\n ...(fallback && path === undefined ? [\"HIGHSEAT_PATH\"] : []),\n ...(foundSecret ? [] : [\"HIGHSEAT_SECRET\"]),\n ]\n if (!foundSecret || missing.length) return createDisabledProxy(missing, path, fallback)\n\n const secret = foundSecret\n\n const clientIpReader = getClientIpReader(options.clientIp)\n let hasWarnedNoIp = false\n\n // Ingest answers 400 to every event without a visitor IP and says nothing about the preset,\n // so the first request without one names the source it read.\n function readClientIp(request: Request) {\n const ip = clientIpReader.read(request)\n\n if (!ip && !hasWarnedNoIp) {\n hasWarnedNoIp = true\n console.warn(\n `highseat/proxy: no visitor IP in ${clientIpReader.source}, so Highseat refuses every event. Set clientIp to the outermost proxy in front of this server.`,\n )\n }\n return ip\n }\n\n function buildUpstreamHeaders(request: Request, names: string[]) {\n const headers = new Headers({\n // The response never copies `content-encoding`, so ingest is asked for a plain body.\n \"accept-encoding\": \"identity\",\n \"x-hs-secret\": secret,\n \"x-hs-client-ip\": readClientIp(request),\n })\n copyHeaders(request.headers, headers, names)\n return headers\n }\n\n async function forward(url: string, init: RequestInit) {\n let response: Response\n\n try {\n response = await fetch(url, { ...init, signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS) })\n } catch {\n return answerError(502, \"Highseat is unreachable from this proxy.\")\n }\n\n const headers = new Headers()\n copyHeaders(response.headers, headers, RESPONSE_HEADERS)\n if (init.method === \"POST\") headers.set(\"cache-control\", \"no-store\")\n\n const body = NULL_BODY_STATUSES.has(response.status) ? null : response.body\n return new Response(body, { status: response.status, headers })\n }\n\n return async function proxy(request) {\n if (path !== undefined && new URL(request.url).pathname !== path) {\n return fallback ? fallback(request) : answerOtherPath()\n }\n\n if (request.method === \"GET\" || request.method === \"HEAD\") {\n return forward(`${upstream}/script.js`, {\n method: request.method,\n headers: buildUpstreamHeaders(request, SCRIPT_REQUEST_HEADERS),\n })\n }\n\n if (request.method === \"POST\") {\n const body = await readEventBody(request)\n if (!body) return answerError(413, \"The event batch is too large.\")\n\n return forward(`${upstream}/api/event`, {\n method: \"POST\",\n headers: buildUpstreamHeaders(request, EVENT_REQUEST_HEADERS),\n body,\n })\n }\n\n return new Response(null, { status: 405, headers: { allow: \"GET, HEAD, POST\" } })\n }\n}\n"],"mappings":";;AAmDA,MAAM,mBAAmB;AAGzB,MAAM,kBAAkB;CAAC;CAAc;CAAa;AAAY;AAEhE,MAAM,oBAAoD;CACxD,QAAQ;CAER,YAAY;CACZ,SAAS;CACT,OAAO;AACT;AAIA,MAAM,yBAAyB,CAAC,cAAc,eAAe;AAC7D,MAAM,wBAAwB;CAAC;CAAgB;CAAc;AAAQ;AAMrE,MAAM,mBAAmB;CACvB;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAGA,MAAM,qCAAqB,IAAI,IAAI;CAAC;CAAK;CAAK;CAAK;AAAG,CAAC;AAEvD,MAAM,sBAAsB;AAG5B,MAAM,kBAAkB;AAQxB,SAAS,kBAAkB,UAAoC;CAC7D,IAAI,OAAO,aAAa,YACtB,OAAO;EAAE,OAAM,YAAW,SAAS,OAAO,CAAC,EAAE,KAAK,KAAK;EAAI,QAAQ;CAAwB;CAG7F,MAAM,SAAS,kBAAkB;CACjC,IAAI,CAAC,QAAQ,MAAM,IAAI,MAAM,4CAA4C,OAAO,QAAQ,EAAE,GAA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B;IAC5D;GACF,CAAC;EACH;EAEA,OAAO,IAAI,SAAS,MAAM;GAAE,QAAQ;GAAK,SAAS,EAAE,OAAO,kBAAkB;EAAE,CAAC;CAClF;AACF"}
1
+ {"version":3,"file":"proxy.js","names":[],"sources":["../src/proxy.ts"],"sourcesContent":["import { findProxyPath, isNextBuild } from \"./env\"\nimport { type ClientIp, DEFAULT_UPSTREAM, findValidSecret, getClientIpReader } from \"./ingest\"\n\nexport type { ClientIp, ClientIpPreset } from \"./ingest\"\n\nexport interface ProxyOptions {\n /**\n * The site's proxy path from Installation settings, such as `/3f9a0c1e2b`, with or without its\n * leading slash. A request on any\n * other path is answered 404, or handed to `fallback`. Defaults to the `HIGHSEAT_PATH`\n * environment variable. Leave both unset on a host whose router already sends only the proxy\n * path here, such as a file named after the path.\n */\n path?: string\n /**\n * The site secret, `hs_secret_…`, or an older one that starts `hs_proxy_` or `ana_proxy_`.\n * Defaults to the `HIGHSEAT_SECRET` environment variable. Without one the proxy is off: the\n * proxy path answers 503, or every request goes to `fallback`.\n */\n secret?: string\n /**\n * Where the visitor's IP comes from: `vercel`, `cloudflare`, `netlify`, `nginx` (the\n * `X-Real-IP` header your nginx sets), or a function. A visitor can write any header the host\n * does not overwrite, so there is no default.\n *\n * The outermost proxy that sets the header decides the preset. Behind a proxied Cloudflare\n * record, use `cloudflare` on any origin, not only a Worker or a Pages Function: a Next.js,\n * TanStack Start or Node server behind Cloudflare, with or without Traefik or nginx in between,\n * sees a Cloudflare edge address in `X-Real-IP`, and the visitor's IP in `cf-connecting-ip`.\n */\n clientIp: ClientIp\n /** The ingest origin the proxy forwards to. Defaults to `https://cdn.highseat.com`. */\n upstream?: string\n /**\n * Answers a request on any path other than `path`, for a handler that sees every request on\n * the site: `fetch` in a Cloudflare Worker routed on the whole site, `next` in a Pages\n * Function. Needs `path`: without it, or without the secret, the proxy is off and every\n * request goes here, so the site still serves in a development setup without the variables.\n */\n fallback?: (request: Request) => Response | Promise<Response>\n}\n\n/** A fetch handler, the shape every supported runtime and framework route accepts. */\nexport type ProxyHandler = (request: Request) => Promise<Response>\n\n// The visitor headers each direction forwards. Copied by name, so a cookie, an `Authorization`\n// header or a visitor's own `x-hs-*` header never reaches ingest.\nconst SCRIPT_REQUEST_HEADERS = [\"user-agent\", \"if-none-match\"]\nconst EVENT_REQUEST_HEADERS = [\"content-type\", \"user-agent\", \"origin\"]\n\n// The upstream headers the response keeps. Rebuilt by name because Node, Bun and Deno hand back\n// a decompressed body under the original `content-encoding` and `content-length`, which would\n// describe bytes this handler no longer has. `x-hs-ip` and `x-hs-ip-source` show which IP\n// ingest resolved, for `curl -i` against the proxy path.\nconst RESPONSE_HEADERS = [\n \"content-type\",\n \"etag\",\n \"cache-control\",\n \"vary\",\n \"retry-after\",\n \"x-hs-ip\",\n \"x-hs-ip-source\",\n]\n\n// Statuses whose response must not carry a body, which the Response constructor enforces.\nconst NULL_BODY_STATUSES = new Set([101, 204, 205, 304])\n\nconst UPSTREAM_TIMEOUT_MS = 10_000\n\n// Ingest refuses a larger batch, so a bigger body is answered here without buffering the rest.\nconst MAX_EVENT_BYTES = 512 * 1024\n\nfunction copyHeaders(from: Headers, to: Headers, names: string[]) {\n for (const name of names) {\n const value = from.get(name)\n if (value !== null) to.set(name, value)\n }\n}\n\nfunction answerError(status: number, error: string) {\n return Response.json({ error }, { status, headers: { \"cache-control\": \"no-store\" } })\n}\n\n// A JSON body rather than an empty 404, so `curl -i` on the route handler's own URL tells this\n// answer apart from ingest's.\nfunction answerOtherPath() {\n return answerError(404, \"Not the proxy path. The Highseat proxy answers on its own path only.\")\n}\n\n// The handler can be created per request (a Worker that reads its options from `env`), so a\n// missing variable is reported once per process rather than once per handler.\nlet hasWarnedMissing = false\n\n/**\n * The handler for a proxy missing a variable: every request goes to `fallback`, or the proxy\n * path answers 503 naming what is missing.\n */\nfunction createDisabledProxy(\n missing: string[],\n path: string | undefined,\n fallback: ProxyOptions[\"fallback\"],\n): ProxyHandler {\n const names = missing.join(\" and \")\n\n // A Next.js build loads every route without serving one, often without the runtime variables.\n if (!hasWarnedMissing && !isNextBuild()) {\n hasWarnedMissing = true\n const outcome = fallback ? \"every request goes to `fallback`\" : \"the proxy path answers 503\"\n console.warn(`highseat/proxy: ${names} not set, so the proxy is off and ${outcome}.`)\n }\n\n return async function proxy(request) {\n if (fallback) return fallback(request)\n if (path !== undefined && new URL(request.url).pathname !== path) return answerOtherPath()\n return answerError(503, `The Highseat proxy is off: set ${names}.`)\n }\n}\n\n/** The request body, or `undefined` once it passes `MAX_EVENT_BYTES`. */\nasync function readEventBody(request: Request): Promise<Uint8Array<ArrayBuffer> | undefined> {\n if (Number(request.headers.get(\"content-length\")) > MAX_EVENT_BYTES) return\n if (!request.body) return new Uint8Array()\n\n const reader = request.body.getReader()\n const chunks: Uint8Array[] = []\n let size = 0\n\n for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) {\n size += chunk.value.byteLength\n if (size > MAX_EVENT_BYTES) {\n void reader.cancel()\n return\n }\n chunks.push(chunk.value)\n }\n\n const body = new Uint8Array(size)\n let offset = 0\n for (const chunk of chunks) {\n body.set(chunk, offset)\n offset += chunk.byteLength\n }\n return body\n}\n\n/**\n * Creates the first-party proxy handler for a site. A GET serves the tracker script and a POST\n * forwards its events, both to the ingest host, with the site secret and the visitor's IP. The\n * returned function takes a `Request` and returns a `Response`, so it mounts as a Next.js route\n * handler, a Cloudflare Worker, a Pages Function, a Netlify or Vercel function, an Astro\n * endpoint or a Hono route.\n *\n * A missing path or secret never throws: the handler passes every request to `fallback`, or\n * answers the proxy path with a 503 naming the variable, and warns once. A value that is not a\n * site secret throws, since that is a copying mistake rather than a variable left unset.\n */\nexport function createProxy(options: ProxyOptions): ProxyHandler {\n const path = findProxyPath(options.path)\n const { fallback } = options\n let foundSecret: string | undefined\n\n try {\n foundSecret = findValidSecret(options.secret, \"highseat/proxy\")\n } catch (error) {\n // Next.js loads every route while it builds, so there the error waits for the first request\n // rather than failing a build that never serves one.\n if (!isNextBuild()) throw error\n return () => Promise.reject(error)\n }\n\n const upstream = new URL(options.upstream ?? DEFAULT_UPSTREAM).origin\n\n // Without a secret, ingest would read every visitor as this server and drop it as datacenter\n // traffic. Without a path, a handler that sees every request cannot tell the proxy's apart.\n const missing = [\n ...(fallback && path === undefined ? [\"HIGHSEAT_PATH\"] : []),\n ...(foundSecret ? [] : [\"HIGHSEAT_SECRET\"]),\n ]\n if (!foundSecret || missing.length) return createDisabledProxy(missing, path, fallback)\n\n const secret = foundSecret\n\n const clientIpReader = getClientIpReader(options.clientIp, \"highseat/proxy\")\n let hasWarnedNoIp = false\n\n // Ingest answers 400 to every event without a visitor IP and says nothing about the preset,\n // so the first request without one names the source it read.\n function readClientIp(request: Request) {\n const ip = clientIpReader.read(request)\n\n if (!ip && !hasWarnedNoIp) {\n hasWarnedNoIp = true\n console.warn(\n `highseat/proxy: no visitor IP in ${clientIpReader.source}, so Highseat refuses every event. Set clientIp to the outermost proxy in front of this server.`,\n )\n }\n return ip\n }\n\n function buildUpstreamHeaders(request: Request, names: string[]) {\n const headers = new Headers({\n // The response never copies `content-encoding`, so ingest is asked for a plain body.\n \"accept-encoding\": \"identity\",\n \"x-hs-secret\": secret,\n \"x-hs-client-ip\": readClientIp(request),\n })\n copyHeaders(request.headers, headers, names)\n return headers\n }\n\n async function forward(url: string, init: RequestInit) {\n let response: Response\n\n try {\n response = await fetch(url, { ...init, signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS) })\n } catch {\n return answerError(502, \"Highseat is unreachable from this proxy.\")\n }\n\n const headers = new Headers()\n copyHeaders(response.headers, headers, RESPONSE_HEADERS)\n if (init.method === \"POST\") headers.set(\"cache-control\", \"no-store\")\n\n const body = NULL_BODY_STATUSES.has(response.status) ? null : response.body\n return new Response(body, { status: response.status, headers })\n }\n\n return async function proxy(request) {\n if (path !== undefined && new URL(request.url).pathname !== path) {\n return fallback ? fallback(request) : answerOtherPath()\n }\n\n if (request.method === \"GET\" || request.method === \"HEAD\") {\n return forward(`${upstream}/script.js`, {\n method: request.method,\n headers: buildUpstreamHeaders(request, SCRIPT_REQUEST_HEADERS),\n })\n }\n\n if (request.method === \"POST\") {\n const body = await readEventBody(request)\n if (!body) return answerError(413, \"The event batch is too large.\")\n\n return forward(`${upstream}/api/event`, {\n method: \"POST\",\n headers: buildUpstreamHeaders(request, EVENT_REQUEST_HEADERS),\n body,\n })\n }\n\n return new Response(null, { status: 405, headers: { allow: \"GET, HEAD, POST\" } })\n }\n}\n"],"mappings":";;;AA+CA,MAAM,yBAAyB,CAAC,cAAc,eAAe;AAC7D,MAAM,wBAAwB;CAAC;CAAgB;CAAc;AAAQ;AAMrE,MAAM,mBAAmB;CACvB;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAGA,MAAM,qCAAqB,IAAI,IAAI;CAAC;CAAK;CAAK;CAAK;AAAG,CAAC;AAEvD,MAAM,sBAAsB;AAG5B,MAAM,kBAAkB;AAExB,SAAS,YAAY,MAAe,IAAa,OAAiB;CAChE,KAAK,MAAM,QAAQ,OAAO;EACxB,MAAM,QAAQ,KAAK,IAAI,IAAI;EAC3B,IAAI,UAAU,MAAM,GAAG,IAAI,MAAM,KAAK;CACxC;AACF;AAEA,SAAS,YAAY,QAAgB,OAAe;CAClD,OAAO,SAAS,KAAK,EAAE,MAAM,GAAG;EAAE;EAAQ,SAAS,EAAE,iBAAiB,WAAW;CAAE,CAAC;AACtF;AAIA,SAAS,kBAAkB;CACzB,OAAO,YAAY,KAAK,sEAAsE;AAChG;AAIA,IAAI,mBAAmB;;;;;AAMvB,SAAS,oBACP,SACA,MACA,UACc;CACd,MAAM,QAAQ,QAAQ,KAAK,OAAO;CAGlC,IAAI,CAAC,oBAAoB,CAAC,YAAY,GAAG;EACvC,mBAAmB;EAEnB,QAAQ,KAAK,mBAAmB,MAAM,oCADtB,WAAW,qCAAqC,6BACkB,EAAE;CACtF;CAEA,OAAO,eAAe,MAAM,SAAS;EACnC,IAAI,UAAU,OAAO,SAAS,OAAO;EACrC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qBAAqB,SAAS,sBAAsB;EAC/D,CAAC;EAGH,IAAI,QAAQ,WAAW,QAAQ;GAC7B,MAAM,OAAO,MAAM,cAAc,OAAO;GACxC,IAAI,CAAC,MAAM,OAAO,YAAY,KAAK,+BAA+B;GAElE,OAAO,QAAQ,GAAG,SAAS,aAAa;IACtC,QAAQ;IACR,SAAS,qBAAqB,SAAS,qBAAqB;IAC5D;GACF,CAAC;EACH;EAEA,OAAO,IAAI,SAAS,MAAM;GAAE,QAAQ;GAAK,SAAS,EAAE,OAAO,kBAAkB;EAAE,CAAC;CAClF;AACF"}
package/react.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { InjectOptions, UserId } from "./index.js";
1
+ import { BeforeSend, InjectOptions, UserId } from "./index.js";
2
2
  //#region src/react.d.ts
3
3
  export interface HighseatProps extends InjectOptions {
4
4
  /**
@@ -23,12 +23,28 @@ export interface HighseatProps extends InjectOptions {
23
23
  * ```
24
24
  */
25
25
  export declare function useIdentify(userId: UserId): void;
26
+ /**
27
+ * Sets the {@link BeforeSend} hook while the component is mounted, and clears it on unmount.
28
+ * `undefined` leaves the current hook alone. Use it in a client component when the tracker loads
29
+ * from a server component, such as `<Highseat />` in a Next.js App Router layout, where a
30
+ * function cannot be passed as a prop. Effects run before the tracker's script loads, so the
31
+ * first page view already passes through the hook.
32
+ *
33
+ * ```tsx
34
+ * "use client"
35
+ * export function Redact() {
36
+ * useBeforeSend(event => (event.url.includes("/admin/") ? null : event))
37
+ * return null
38
+ * }
39
+ * ```
40
+ */
41
+ export declare function useBeforeSend(beforeSend: BeforeSend | undefined): void;
26
42
  /**
27
43
  * Loads the Highseat tracker. Render it once, in the root layout. It adds the script tag after
28
44
  * the page mounts and renders nothing; mounting it again adds no second tag, and the tracker
29
45
  * counts client-side navigation on its own. With `userId`, it also identifies the visitor, as
30
- * {@link useIdentify} does.
46
+ * {@link useIdentify} does, and with `beforeSend` it sets the hook, as {@link useBeforeSend} does.
31
47
  */
32
- export declare function Highseat({ site, src, outbound, downloads, hashRouting, debug, userId }: HighseatProps): null;
48
+ export declare function Highseat({ site, src, outbound, downloads, hashRouting, beforeSend, debug, userId }: HighseatProps): null;
33
49
  //#endregion
34
50
  //# sourceMappingURL=react.d.ts.map
package/react.js CHANGED
@@ -1,5 +1,5 @@
1
1
  "use client";
2
- import { inject } from "./index.js";
2
+ import { inject, setBeforeSend } from "./index.js";
3
3
  import { syncIdentity } from "./identity.js";
4
4
  import { useEffect, useRef } from "react";
5
5
  //#region src/react.ts
@@ -24,12 +24,37 @@ function useIdentify(userId) {
24
24
  }, [userId]);
25
25
  }
26
26
  /**
27
+ * Sets the {@link BeforeSend} hook while the component is mounted, and clears it on unmount.
28
+ * `undefined` leaves the current hook alone. Use it in a client component when the tracker loads
29
+ * from a server component, such as `<Highseat />` in a Next.js App Router layout, where a
30
+ * function cannot be passed as a prop. Effects run before the tracker's script loads, so the
31
+ * first page view already passes through the hook.
32
+ *
33
+ * ```tsx
34
+ * "use client"
35
+ * export function Redact() {
36
+ * useBeforeSend(event => (event.url.includes("/admin/") ? null : event))
37
+ * return null
38
+ * }
39
+ * ```
40
+ */
41
+ function useBeforeSend(beforeSend) {
42
+ useEffect(() => {
43
+ if (!beforeSend) return;
44
+ setBeforeSend(beforeSend);
45
+ return () => {
46
+ if (window.highseat?.beforeSend === beforeSend) setBeforeSend(void 0);
47
+ };
48
+ }, [beforeSend]);
49
+ }
50
+ /**
27
51
  * Loads the Highseat tracker. Render it once, in the root layout. It adds the script tag after
28
52
  * the page mounts and renders nothing; mounting it again adds no second tag, and the tracker
29
53
  * counts client-side navigation on its own. With `userId`, it also identifies the visitor, as
30
- * {@link useIdentify} does.
54
+ * {@link useIdentify} does, and with `beforeSend` it sets the hook, as {@link useBeforeSend} does.
31
55
  */
32
- function Highseat({ site, src, outbound, downloads, hashRouting, debug, userId }) {
56
+ function Highseat({ site, src, outbound, downloads, hashRouting, beforeSend, debug, userId }) {
57
+ useBeforeSend(beforeSend);
33
58
  useEffect(() => {
34
59
  inject({
35
60
  site,
@@ -51,6 +76,6 @@ function Highseat({ site, src, outbound, downloads, hashRouting, debug, userId }
51
76
  return null;
52
77
  }
53
78
  //#endregion
54
- export { Highseat, useIdentify };
79
+ export { Highseat, useBeforeSend, useIdentify };
55
80
 
56
81
  //# sourceMappingURL=react.js.map
package/react.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"react.js","names":[],"sources":["../src/react.ts"],"sourcesContent":["\"use client\"\n\nimport { useEffect, useRef } from \"react\"\nimport { syncIdentity } from \"./identity\"\nimport { inject, type InjectOptions, type UserId } from \"./index\"\n\nexport interface HighseatProps extends InjectOptions {\n /**\n * The signed-in user's id from your own system, never an email or other personal data. Pass\n * `null` once the visitor is signed out, and `undefined` while the session is still loading.\n * See {@link useIdentify}.\n */\n userId?: UserId\n}\n\n/**\n * Keeps the visitor's user id in step with a session. Each new value is passed to `identify`\n * once: an id identifies the visitor, `null` clears the id at sign-out or session expiry, and\n * `undefined`, a session still loading, changes nothing. Works in any client component, with or\n * without `<Highseat />` on the page, and before the tracker has loaded.\n *\n * Tell loading apart from signed out: `useIdentify(session?.user.id)` passes `undefined` after\n * sign-out too, so it never clears the id.\n *\n * ```tsx\n * const { data, isPending } = useSession()\n * useIdentify(isPending ? undefined : (data?.user.id ?? null))\n * ```\n */\nexport function useIdentify(userId: UserId): void {\n // The id this component identified last. A ref survives Strict Mode's second effect run, so\n // the same id is never sent twice.\n const identified = useRef<UserId>(undefined)\n\n useEffect(() => {\n identified.current = syncIdentity(identified.current, userId)\n }, [userId])\n}\n\n/**\n * Loads the Highseat tracker. Render it once, in the root layout. It adds the script tag after\n * the page mounts and renders nothing; mounting it again adds no second tag, and the tracker\n * counts client-side navigation on its own. With `userId`, it also identifies the visitor, as\n * {@link useIdentify} does.\n */\nexport function Highseat({\n site,\n src,\n outbound,\n downloads,\n hashRouting,\n debug,\n userId,\n}: HighseatProps): null {\n useEffect(() => {\n inject({ site, src, outbound, downloads, hashRouting, debug })\n }, [site, src, outbound, downloads, hashRouting, debug])\n\n useIdentify(userId)\n\n return null\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA6BA,SAAgB,YAAY,QAAsB;CAGhD,MAAM,aAAa,OAAe,KAAA,CAAS;CAE3C,gBAAgB;EACd,WAAW,UAAU,aAAa,WAAW,SAAS,MAAM;CAC9D,GAAG,CAAC,MAAM,CAAC;AACb;;;;;;;AAQA,SAAgB,SAAS,EACvB,MACA,KACA,UACA,WACA,aACA,OACA,UACsB;CACtB,gBAAgB;EACd,OAAO;GAAE;GAAM;GAAK;GAAU;GAAW;GAAa;EAAM,CAAC;CAC/D,GAAG;EAAC;EAAM;EAAK;EAAU;EAAW;EAAa;CAAK,CAAC;CAEvD,YAAY,MAAM;CAElB,OAAO;AACT"}
1
+ {"version":3,"file":"react.js","names":[],"sources":["../src/react.ts"],"sourcesContent":["\"use client\"\n\nimport { useEffect, useRef } from \"react\"\nimport { syncIdentity } from \"./identity\"\nimport { inject, setBeforeSend, type BeforeSend, type InjectOptions, type UserId } from \"./index\"\n\nexport interface HighseatProps extends InjectOptions {\n /**\n * The signed-in user's id from your own system, never an email or other personal data. Pass\n * `null` once the visitor is signed out, and `undefined` while the session is still loading.\n * See {@link useIdentify}.\n */\n userId?: UserId\n}\n\n/**\n * Keeps the visitor's user id in step with a session. Each new value is passed to `identify`\n * once: an id identifies the visitor, `null` clears the id at sign-out or session expiry, and\n * `undefined`, a session still loading, changes nothing. Works in any client component, with or\n * without `<Highseat />` on the page, and before the tracker has loaded.\n *\n * Tell loading apart from signed out: `useIdentify(session?.user.id)` passes `undefined` after\n * sign-out too, so it never clears the id.\n *\n * ```tsx\n * const { data, isPending } = useSession()\n * useIdentify(isPending ? undefined : (data?.user.id ?? null))\n * ```\n */\nexport function useIdentify(userId: UserId): void {\n // The id this component identified last. A ref survives Strict Mode's second effect run, so\n // the same id is never sent twice.\n const identified = useRef<UserId>(undefined)\n\n useEffect(() => {\n identified.current = syncIdentity(identified.current, userId)\n }, [userId])\n}\n\n/**\n * Sets the {@link BeforeSend} hook while the component is mounted, and clears it on unmount.\n * `undefined` leaves the current hook alone. Use it in a client component when the tracker loads\n * from a server component, such as `<Highseat />` in a Next.js App Router layout, where a\n * function cannot be passed as a prop. Effects run before the tracker's script loads, so the\n * first page view already passes through the hook.\n *\n * ```tsx\n * \"use client\"\n * export function Redact() {\n * useBeforeSend(event => (event.url.includes(\"/admin/\") ? null : event))\n * return null\n * }\n * ```\n */\nexport function useBeforeSend(beforeSend: BeforeSend | undefined): void {\n useEffect(() => {\n if (!beforeSend) return\n setBeforeSend(beforeSend)\n return () => {\n // Another component may have set its own hook since.\n if (window.highseat?.beforeSend === beforeSend) setBeforeSend(undefined)\n }\n }, [beforeSend])\n}\n\n/**\n * Loads the Highseat tracker. Render it once, in the root layout. It adds the script tag after\n * the page mounts and renders nothing; mounting it again adds no second tag, and the tracker\n * counts client-side navigation on its own. With `userId`, it also identifies the visitor, as\n * {@link useIdentify} does, and with `beforeSend` it sets the hook, as {@link useBeforeSend} does.\n */\nexport function Highseat({\n site,\n src,\n outbound,\n downloads,\n hashRouting,\n beforeSend,\n debug,\n userId,\n}: HighseatProps): null {\n // Declared first, so its effect sets the hook before the next one adds the script tag.\n useBeforeSend(beforeSend)\n\n useEffect(() => {\n inject({ site, src, outbound, downloads, hashRouting, debug })\n }, [site, src, outbound, downloads, hashRouting, debug])\n\n useIdentify(userId)\n\n return null\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA6BA,SAAgB,YAAY,QAAsB;CAGhD,MAAM,aAAa,OAAe,KAAA,CAAS;CAE3C,gBAAgB;EACd,WAAW,UAAU,aAAa,WAAW,SAAS,MAAM;CAC9D,GAAG,CAAC,MAAM,CAAC;AACb;;;;;;;;;;;;;;;;AAiBA,SAAgB,cAAc,YAA0C;CACtE,gBAAgB;EACd,IAAI,CAAC,YAAY;EACjB,cAAc,UAAU;EACxB,aAAa;GAEX,IAAI,OAAO,UAAU,eAAe,YAAY,cAAc,KAAA,CAAS;EACzE;CACF,GAAG,CAAC,UAAU,CAAC;AACjB;;;;;;;AAQA,SAAgB,SAAS,EACvB,MACA,KACA,UACA,WACA,aACA,YACA,OACA,UACsB;CAEtB,cAAc,UAAU;CAExB,gBAAgB;EACd,OAAO;GAAE;GAAM;GAAK;GAAU;GAAW;GAAa;EAAM,CAAC;CAC/D,GAAG;EAAC;EAAM;EAAK;EAAU;EAAW;EAAa;CAAK,CAAC;CAEvD,YAAY,MAAM;CAElB,OAAO;AACT"}
package/server.d.ts ADDED
@@ -0,0 +1,171 @@
1
+ import { TrackArgs, TrackName } from "./index.js";
2
+ import { ClientIp, ClientIpPreset } from "./ingest.js";
3
+ //#region src/server.d.ts
4
+ /**
5
+ * Server-side events, sent from your own backend with the site secret: a server action, a route
6
+ * handler, a webhook handler or a job. Events are batched and sent in the background, retried
7
+ * when Highseat is busy or unreachable, and nothing here throws: a failure goes to `onError`.
8
+ */
9
+ /**
10
+ * Request headers in any shape a server hands them over: a `Headers` object, what Next.js's
11
+ * `headers()` returns, or Node's `request.headers` record.
12
+ */
13
+ export type HeadersLike = {
14
+ get: (name: string) => string | null;
15
+ } | Record<string, string | string[] | undefined>;
16
+ /**
17
+ * Keeps a serverless function alive until a promise settles: `waitUntil` from
18
+ * `@vercel/functions`, or `ctx.waitUntil` in a Cloudflare Worker and `context.waitUntil` in a
19
+ * Netlify function, bound to their object.
20
+ */
21
+ export type WaitUntil = (promise: Promise<unknown>) => void;
22
+ /** Who an event belongs to and where it happened, given with each `track()` call. */
23
+ export interface ServerEventOptions {
24
+ /**
25
+ * The request being handled. The visitor's IP (see `clientIp`), their user agent and the
26
+ * hostname are read from it, and a `pageview` takes its URL and referrer too.
27
+ */
28
+ request?: Request;
29
+ /** The request's headers, when there is no `Request`: `await headers()` in a server action. */
30
+ headers?: HeadersLike;
31
+ /** The visitor's IP. Wins over the one read from `request` or `headers`. */
32
+ ip?: string;
33
+ /** The visitor's user agent. Wins over the one read from `request` or `headers`. */
34
+ userAgent?: string;
35
+ /**
36
+ * A user id from your own system. An event with no visitor (no IP and no user agent, as from
37
+ * a job) counts as this user, and without one as a visitor of its own.
38
+ */
39
+ userId?: string | number;
40
+ /** A hostname of the site. Defaults to the tracker's `hostname`, then the request's host. */
41
+ hostname?: string;
42
+ /** The page's URL. A `pageview` defaults to the request's URL. */
43
+ url?: string;
44
+ /** The page the visitor came from. A `pageview` defaults to the request's `Referer`. */
45
+ referrer?: string;
46
+ /**
47
+ * The event's id, any string up to 255 characters. Defaults to a new UUID. Pass an id your
48
+ * system already holds (a job id, a webhook event id), and a retry of the same event within
49
+ * three days is stored once.
50
+ */
51
+ eventId?: string;
52
+ /** When the event happened, up to a day ago. Defaults to the moment `track()` is called. */
53
+ timestamp?: Date;
54
+ /**
55
+ * Sends this event at once and keeps the function alive until it lands. Wins over the
56
+ * tracker's `waitUntil`.
57
+ */
58
+ waitUntil?: WaitUntil;
59
+ }
60
+ /** An event Highseat did not store, as `onError` reports it. */
61
+ export interface TrackErrorEvent {
62
+ /** The event's name. */
63
+ name: string;
64
+ /** The event's id: the one passed to `track()`, or the UUID it was given. */
65
+ eventId: string;
66
+ /** Why Highseat refused or dropped it, such as `revenue.amount_not_integer` or `bot`. */
67
+ reason?: string;
68
+ }
69
+ /** A failure `track()` never throws, handed to `onError`. */
70
+ export interface TrackError {
71
+ /**
72
+ * `rejected`: refused as invalid, for good. `dropped`: accepted but not stored, for a `reason`
73
+ * of `foreign_hostname`, `bot` or `excluded` (a recognised retry is never reported). `failed`:
74
+ * never landed, after every retry or at `close()`'s deadline, or refused whole (a wrong secret).
75
+ */
76
+ type: "rejected" | "dropped" | "failed";
77
+ /** What happened, in a sentence. */
78
+ message: string;
79
+ /** The HTTP status Highseat answered, when it answered. */
80
+ status?: number;
81
+ /** The events concerned. */
82
+ events: TrackErrorEvent[];
83
+ }
84
+ export interface TrackerOptions {
85
+ /** The site id, `site_…`. Defaults to `HIGHSEAT_SITE`, then `NEXT_PUBLIC_HIGHSEAT_SITE`. */
86
+ site?: string;
87
+ /**
88
+ * The site secret, `hs_secret_…`, from the site's Installation settings. Defaults to
89
+ * `HIGHSEAT_SECRET`. Keep it on the server: it lets a caller name any visitor.
90
+ */
91
+ secret?: string;
92
+ /** The hostname every event is filed under unless it names its own. */
93
+ hostname?: string;
94
+ /**
95
+ * Where the visitor's IP is read from a request: `vercel`, `cloudflare`, `netlify`, `nginx`
96
+ * or a function, as for `createProxy()`. Defaults to `cloudflare` in a Worker, `vercel` on
97
+ * Vercel and `netlify` on Netlify. Anywhere else, set it, or pass `ip` with each event.
98
+ */
99
+ clientIp?: ClientIp;
100
+ /** The ingest origin. Defaults to `https://cdn.highseat.com`. */
101
+ upstream?: string;
102
+ /** The `fetch` events are sent with. Defaults to the global one. */
103
+ fetch?: typeof fetch;
104
+ /** Receives every failure. Defaults to a `console.warn`. */
105
+ onError?: (error: TrackError) => void;
106
+ /**
107
+ * Sends every event at once and keeps the function alive until it lands. Pass it in a
108
+ * serverless function, which may stop as soon as it answers.
109
+ */
110
+ waitUntil?: WaitUntil;
111
+ /** Milliseconds an event waits for others to share its request. Defaults to 1000. */
112
+ flushInterval?: number;
113
+ /**
114
+ * Retries of a batch Highseat answered 429 or 5xx, or never answered. Defaults to 4. Batches
115
+ * go one at a time, so a retry's wait holds back every event behind it.
116
+ */
117
+ maxRetries?: number;
118
+ /** Milliseconds one request may take. Defaults to 10000. */
119
+ timeout?: number;
120
+ }
121
+ /**
122
+ * The arguments after an event's name: its properties, typed by `Register` as for the browser's
123
+ * `track()`, then the options that say who it belongs to.
124
+ */
125
+ export type ServerTrackArgs<Name extends string> = [...TrackArgs<Name>, options?: ServerEventOptions];
126
+ export interface Tracker {
127
+ /** Records an event, queued and sent in the background. Returns at once and never throws. */
128
+ track: <Name extends TrackName>(name: Name, ...args: ServerTrackArgs<Name>) => void;
129
+ /** Sends every queued event, and resolves once each has landed or failed. Never rejects. */
130
+ flush: () => Promise<void>;
131
+ /**
132
+ * Sends what is queued and stops: a later `track()` sends nothing. Call it at shutdown, with a
133
+ * `timeout` shorter than the shutdown's grace period.
134
+ */
135
+ close: (options?: CloseOptions) => Promise<void>;
136
+ }
137
+ export interface CloseOptions {
138
+ /**
139
+ * Milliseconds to wait for the queue to drain. Past it, sending stops, the events still
140
+ * unsent go to `onError` as `failed`, and `close()` resolves. Without one, `close()` waits for
141
+ * every retry, which during an outage can take minutes.
142
+ */
143
+ timeout?: number;
144
+ }
145
+ /**
146
+ * Creates a tracker for a site's backend. Credentials come from the options or from
147
+ * `HIGHSEAT_SITE` and `HIGHSEAT_SECRET`. Without them the tracker warns once and sends nothing,
148
+ * and a value that is not a site secret throws, since that is a copying mistake.
149
+ *
150
+ * ```ts
151
+ * const tracker = createTracker({ hostname: "example.com" })
152
+ * tracker.track("signup", { plan: "pro" }, { request, userId: user.id })
153
+ * ```
154
+ */
155
+ export declare function createTracker(options?: TrackerOptions): Tracker;
156
+ /**
157
+ * Records an event with the tracker made from `HIGHSEAT_SITE` and `HIGHSEAT_SECRET`. A known
158
+ * name checks its properties, as in the browser. Never throws.
159
+ *
160
+ * ```ts
161
+ * track("signup", { plan: "pro" }, { request, userId: user.id })
162
+ * ```
163
+ */
164
+ export declare function track<Name extends TrackName>(name: Name, ...args: ServerTrackArgs<Name>): void;
165
+ /** Sends every event `track()` has queued. Await it before a short-lived script exits. */
166
+ export declare function flush(): Promise<void>;
167
+ /** Sends what `track()` has queued and stops sending. Call it at shutdown. See `CloseOptions`. */
168
+ export declare function close(options?: CloseOptions): Promise<void>;
169
+ //#endregion
170
+ export type { ClientIp, ClientIpPreset };
171
+ //# sourceMappingURL=server.d.ts.map