highseat 0.1.0 → 0.3.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 CHANGED
@@ -13,8 +13,8 @@ npm install highseat
13
13
  | Import | Contents | Needs |
14
14
  | --- | --- | --- |
15
15
  | `highseat` | `track()`, `identify()`, `getAttributionId()` and `inject()` | Nothing |
16
- | `highseat/react` | `<Highseat />` | React |
17
- | `highseat/next` | `<Highseat />`, `createProxy()` and `withHighseat()` for Next.js | Next.js |
16
+ | `highseat/react` | `<Highseat />` and `useIdentify()` | React |
17
+ | `highseat/next` | `<Highseat />`, `useIdentify()`, `createProxy()` and `withHighseat()` for Next.js | Next.js |
18
18
  | `highseat/proxy` | `createProxy()`, a first-party proxy for any runtime with `fetch` | Nothing |
19
19
 
20
20
  Each entry point loads on its own and imports no framework it does not name, so `highseat/proxy` runs in a Cloudflare Worker without React installed.
@@ -62,6 +62,12 @@ import { Highseat } from "highseat/react"
62
62
 
63
63
  Without React, `inject({ site })` from `highseat` adds the same script tag.
64
64
 
65
+ ## Debugging
66
+
67
+ In development, the package logs every `track()` and `identify()` call to the console, with its properties or id, and says whether the call went to the tracker or waits in the queue for it to load. It also warns once per page when nothing can reach Highseat: the page has no tracker script, or the script failed to load, as one an ad blocker stopped does.
68
+
69
+ Logging is on when `process.env.NODE_ENV` is `development`, so a production build logs nothing. Pass `debug={false}` to `<Highseat />` to turn it off, or `debug` to turn it on in any build. `inject({ site, debug })` takes the same option.
70
+
65
71
  ## Events
66
72
 
67
73
  ```ts
@@ -90,6 +96,43 @@ declare module "highseat" {
90
96
 
91
97
  Without `strict: true`, any other name still compiles as a custom event. The declarations are types only and add nothing to your bundle.
92
98
 
99
+ ### Identify users
100
+
101
+ `identify()` links the visitor to a user id from your own system, on every later event and across visits. Pass your own database id, never an email or other personal data. `identify(null)` clears the id, and an empty or `undefined` id changes nothing.
102
+
103
+ Most sites never call `identify()` directly. They pass the signed-in user's id instead, and the package calls `identify()` each time the value changes. A string or a number identifies the visitor. `null` means signed out, so a sign-out or an expired session clears the id. A sign-out in another tab clears it too once your auth library updates the session in this tab. `undefined` means the session is still loading, and changes nothing. The same id on every render calls `identify()` once.
104
+
105
+ When the server already knows the user, pass the id to `<Highseat />`:
106
+
107
+ ```tsx
108
+ <Highseat site="site_…" userId={user?.id ?? null} />
109
+ ```
110
+
111
+ When the session comes from a client hook, call `useIdentify()` in any client component. It needs no `<Highseat />` nearby, so a Next.js App Router site keeps `<Highseat />` in its server layout and every page static. `highseat/next` and `highseat/react` both export it:
112
+
113
+ ```tsx
114
+ "use client"
115
+
116
+ import { useIdentify } from "highseat/next"
117
+ import { useSession } from "~/lib/auth-client"
118
+
119
+ export function IdentifyUser() {
120
+ const { data, isPending } = useSession()
121
+ useIdentify(isPending ? undefined : (data?.user.id ?? null))
122
+ return null
123
+ }
124
+ ```
125
+
126
+ The value has to tell loading apart from signed out. `useIdentify(session?.user.id)` passes `undefined` after sign-out too, so it never clears the id. `useIdentify(session?.user.id ?? null)` clears the id while the session loads, so the first page view has no user. Each auth library marks loading its own way:
127
+
128
+ | Library | Hook | Value |
129
+ | --- | --- | --- |
130
+ | Better Auth | `const { data, isPending } = useSession()` | `isPending ? undefined : (data?.user.id ?? null)` |
131
+ | Auth.js (NextAuth) | `const { data, status } = useSession()` | `status === "loading" ? undefined : (data?.user?.id ?? null)` |
132
+ | Clerk | `const { user, isLoaded } = useUser()` | `isLoaded ? (user?.id ?? null) : undefined` |
133
+
134
+ Without React, call `identify()` from `highseat` after each sign-in and sign-out.
135
+
93
136
  ## Revenue attribution
94
137
 
95
138
  `getAttributionId()` resolves to the id that joins a payment to the visit. Pass it to your checkout as `attribution_id` metadata. It resolves to `undefined` if the tracker has not loaded within three seconds, so a checkout that awaits it never hangs.
package/env.js ADDED
@@ -0,0 +1,51 @@
1
+ //#region src/env.ts
2
+ /**
3
+ * The variables the package reads from a customer's environment. Each is named in full, never
4
+ * looked up by a computed key: Next.js inlines a `NEXT_PUBLIC_` variable into browser code only
5
+ * where the source spells out `process.env.NEXT_PUBLIC_…`. The server variables return
6
+ * `undefined` where the runtime has no `process`: a Cloudflare Worker without `nodejs_compat`,
7
+ * whose options carry the values instead.
8
+ */
9
+ /** The site id for `<Highseat />` in Next.js. Public, so it reaches the browser. */
10
+ function findNextSite() {
11
+ return process.env.NEXT_PUBLIC_HIGHSEAT_SITE;
12
+ }
13
+ /**
14
+ * The site's proxy path: `option` when given, else `HIGHSEAT_PATH`, a server variable shared by
15
+ * `<Highseat />`, `withHighseat()` and the proxy handler. A value written without its leading
16
+ * slash gets one, as Installation settings shows it (`/3f9a0c1e2b`). An empty value counts as
17
+ * unset.
18
+ */
19
+ function findProxyPath(option) {
20
+ const path = option ?? (typeof process === "undefined" ? void 0 : process.env.HIGHSEAT_PATH);
21
+ if (!path) return;
22
+ return path.startsWith("/") ? path : `/${path}`;
23
+ }
24
+ /** The site secret for the proxy handler. */
25
+ function findSecret() {
26
+ if (typeof process === "undefined") return;
27
+ return process.env.HIGHSEAT_SECRET;
28
+ }
29
+ /**
30
+ * Whether this runs inside `next build`, which loads every route without serving one. Set in the
31
+ * build's route workers only: `next.config.ts` receives the phase as an argument instead.
32
+ */
33
+ function isNextBuild() {
34
+ if (typeof process === "undefined") return false;
35
+ return process.env.NEXT_PHASE === "phase-production-build";
36
+ }
37
+ /**
38
+ * Whether the build runs in development. A bundler replaces `process.env.NODE_ENV` with a
39
+ * literal. A browser without that replacement has no `process`, so the read throws.
40
+ */
41
+ function isDevelopment() {
42
+ try {
43
+ return process.env.NODE_ENV === "development";
44
+ } catch {
45
+ return false;
46
+ }
47
+ }
48
+ //#endregion
49
+ export { findNextSite, findProxyPath, findSecret, isDevelopment, isNextBuild };
50
+
51
+ //# sourceMappingURL=env.js.map
package/env.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"env.js","names":[],"sources":["../src/env.ts"],"sourcesContent":["/**\n * The variables the package reads from a customer's environment. Each is named in full, never\n * looked up by a computed key: Next.js inlines a `NEXT_PUBLIC_` variable into browser code only\n * where the source spells out `process.env.NEXT_PUBLIC_…`. The server variables return\n * `undefined` where the runtime has no `process`: a Cloudflare Worker without `nodejs_compat`,\n * whose options carry the values instead.\n */\n\n/** The site id for `<Highseat />` in Next.js. Public, so it reaches the browser. */\nexport function findNextSite(): string | undefined {\n return process.env.NEXT_PUBLIC_HIGHSEAT_SITE\n}\n\n/**\n * The site's proxy path: `option` when given, else `HIGHSEAT_PATH`, a server variable shared by\n * `<Highseat />`, `withHighseat()` and the proxy handler. A value written without its leading\n * slash gets one, as Installation settings shows it (`/3f9a0c1e2b`). An empty value counts as\n * unset.\n */\nexport function findProxyPath(option?: string): string | undefined {\n const path = option ?? (typeof process === \"undefined\" ? undefined : process.env.HIGHSEAT_PATH)\n if (!path) return\n return path.startsWith(\"/\") ? path : `/${path}`\n}\n\n/** The site secret for the proxy handler. */\nexport function findSecret(): string | undefined {\n if (typeof process === \"undefined\") return\n return process.env.HIGHSEAT_SECRET\n}\n\n/**\n * Whether this runs inside `next build`, which loads every route without serving one. Set in the\n * build's route workers only: `next.config.ts` receives the phase as an argument instead.\n */\nexport function isNextBuild(): boolean {\n if (typeof process === \"undefined\") return false\n return process.env.NEXT_PHASE === \"phase-production-build\"\n}\n\n/**\n * Whether the build runs in development. A bundler replaces `process.env.NODE_ENV` with a\n * literal. A browser without that replacement has no `process`, so the read throws.\n */\nexport function isDevelopment(): boolean {\n try {\n return process.env.NODE_ENV === \"development\"\n } catch {\n return false\n }\n}\n"],"mappings":";;;;;;;;;AASA,SAAgB,eAAmC;CACjD,OAAO,QAAQ,IAAI;AACrB;;;;;;;AAQA,SAAgB,cAAc,QAAqC;CACjE,MAAM,OAAO,WAAW,OAAO,YAAY,cAAc,KAAA,IAAY,QAAQ,IAAI;CACjF,IAAI,CAAC,MAAM;CACX,OAAO,KAAK,WAAW,GAAG,IAAI,OAAO,IAAI;AAC3C;;AAGA,SAAgB,aAAiC;CAC/C,IAAI,OAAO,YAAY,aAAa;CACpC,OAAO,QAAQ,IAAI;AACrB;;;;;AAMA,SAAgB,cAAuB;CACrC,IAAI,OAAO,YAAY,aAAa,OAAO;CAC3C,OAAO,QAAQ,IAAI,eAAe;AACpC;;;;;AAMA,SAAgB,gBAAyB;CACvC,IAAI;EACF,OAAO,QAAQ,IAAI,aAAa;CAClC,QAAQ;EACN,OAAO;CACT;AACF"}
package/identity.js ADDED
@@ -0,0 +1,16 @@
1
+ import { identify } from "./index.js";
2
+ //#region src/identity.ts
3
+ /**
4
+ * Identifies `userId` when it differs from `previous`, the id identified last, and returns the id
5
+ * identified now. `undefined` means the session has not loaded, so it changes nothing and keeps
6
+ * `previous`: a session that reloads with the same user calls `identify` once, not twice.
7
+ */
8
+ function syncIdentity(previous, userId) {
9
+ if (userId === void 0 || userId === previous) return previous;
10
+ identify(userId);
11
+ return userId;
12
+ }
13
+ //#endregion
14
+ export { syncIdentity };
15
+
16
+ //# sourceMappingURL=identity.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"identity.js","names":[],"sources":["../src/identity.ts"],"sourcesContent":["import { identify, type UserId } from \"./index\"\n\n/**\n * Identifies `userId` when it differs from `previous`, the id identified last, and returns the id\n * identified now. `undefined` means the session has not loaded, so it changes nothing and keeps\n * `previous`: a session that reloads with the same user calls `identify` once, not twice.\n */\nexport function syncIdentity(previous: UserId, userId: UserId): UserId {\n if (userId === undefined || userId === previous) return previous\n identify(userId)\n return userId\n}\n"],"mappings":";;;;;;;AAOA,SAAgB,aAAa,UAAkB,QAAwB;CACrE,IAAI,WAAW,KAAA,KAAa,WAAW,UAAU,OAAO;CACxD,SAAS,MAAM;CACf,OAAO;AACT"}
package/index.d.ts CHANGED
@@ -98,12 +98,18 @@ export type TrackName = Register extends {
98
98
  * names is checked as a whole rather than name by name.
99
99
  */
100
100
  export type TrackArgs<Name extends string> = [Name] extends [EventName] ? {} extends KnownEvents[Name] ? [properties?: KnownEvents[Name]] : [properties: KnownEvents[Name]] : [properties?: Properties];
101
+ /**
102
+ * A user id from your own system, as {@link identify} takes it. A string or a number identifies
103
+ * the visitor, `null` clears the id, and `undefined` or an empty string changes nothing. Pass your
104
+ * own database id, never an email or other personal data.
105
+ */
106
+ export type UserId = string | number | null | undefined;
101
107
  /** The tracker's API on `window.highseat`, or the queue that stands in for it until it loads. */
102
108
  export interface HighseatGlobal {
103
109
  /** Records an event. */
104
110
  track?: (name: string, properties?: Properties) => void;
105
111
  /** Sets or clears the visitor's user id. */
106
- identify?: (id: string | number | null | undefined) => void;
112
+ identify?: (id: UserId) => void;
107
113
  /** The id that joins a payment to this tab's visit. */
108
114
  getAttributionId?: () => string | undefined;
109
115
  /** Calls made before the tracker loaded, drained in order when it starts. */
@@ -130,6 +136,12 @@ export interface InjectOptions {
130
136
  downloads?: boolean;
131
137
  /** Counts a change of `#/route` as a page view, for an app that routes by hash. */
132
138
  hashRouting?: boolean;
139
+ /**
140
+ * Logs every `track()` and `identify()` call to the console, and warns once when no tracker
141
+ * script is on the page or the script failed to load. Defaults to `true` when
142
+ * `process.env.NODE_ENV` is `development`, so a production build logs nothing.
143
+ */
144
+ debug?: boolean;
133
145
  }
134
146
  declare global {
135
147
  interface Window {
@@ -149,7 +161,7 @@ export declare function track<Name extends TrackName>(name: Name, ...args: Track
149
161
  * visits. `null` clears it at sign-out. An empty or `undefined` id is ignored, so
150
162
  * `identify(user?.id)` before a session loads does not sign the visitor out.
151
163
  */
152
- export declare function identify(id: string | number | null | undefined): void;
164
+ export declare function identify(id: UserId): void;
153
165
  /**
154
166
  * The id that joins a payment to this tab's visit. Pass it to the checkout as metadata
155
167
  * (`attribution_id`), and the payment provider's webhook credits the sale to the visit's source.
@@ -160,7 +172,8 @@ export declare function identify(id: string | number | null | undefined): void;
160
172
  export declare function getAttributionId(options?: AttributionOptions): Promise<string | undefined>;
161
173
  /**
162
174
  * Adds the tracker's script tag to the page, once. A second call for the same site, such as a
163
- * component mounting again, finds the tag and does nothing. Does nothing on a server.
175
+ * component mounting again, finds the tag and adds nothing, but its `debug` option still applies.
176
+ * Does nothing on a server.
164
177
  */
165
178
  export declare function inject(options: InjectOptions): void;
166
179
  //#endregion
package/index.js CHANGED
@@ -1,13 +1,19 @@
1
+ import { isDevelopment } from "./env.js";
1
2
  //#region src/index.ts
2
3
  /** Where the tracker loads from when the site has no proxy path. */
3
4
  const SCRIPT_URL = "https://cdn.highseat.com/script.js";
4
5
  const LIVE = Symbol.for("highseat");
5
6
  const SCRIPT_HOST = new URL(SCRIPT_URL).host;
6
7
  const PROXY_PATH = /^\/[0-9a-f]{10}$/;
7
- const ATTRIBUTION_TIMEOUT = 3e3;
8
- const ATTRIBUTION_POLL_INTERVAL = 50;
8
+ const TRACKER_TIMEOUT = 3e3;
9
+ const TRACKER_POLL_INTERVAL = 50;
10
+ const MISSING_SCRIPT_WARNING = ["highseat: no tracker script on this page, so no event reaches Highseat.", "Render <Highseat />, call inject({ site }), or add the script tag from the site's Installation settings."].join(" ");
11
+ const FAILED_SCRIPT_WARNING = ["highseat: the tracker script failed to load, so no event reaches Highseat.", "An ad blocker may have stopped it: load the tracker from the site's proxy path instead."].join(" ");
12
+ const SLOW_SCRIPT_WARNING = [`highseat: the tracker script has not loaded after ${TRACKER_TIMEOUT / 1e3} seconds,`, "so every call waits in the queue. Check the network panel for a blocked or failed request."].join(" ");
9
13
  const injectedScripts = /* @__PURE__ */ new WeakSet();
10
14
  const failedScripts = /* @__PURE__ */ new WeakSet();
15
+ let debugOption;
16
+ const watchedWindows = /* @__PURE__ */ new WeakSet();
11
17
  function findGlobal() {
12
18
  if (typeof window === "undefined") return;
13
19
  return window.highseat ??= {};
@@ -34,8 +40,55 @@ function isTrackerScript(script) {
34
40
  return false;
35
41
  }
36
42
  }
43
+ /** The page's tracker scripts, each one listened to from now on for a failed load. */
37
44
  function findTrackerScripts() {
38
- return Array.from(document.scripts).filter(isTrackerScript);
45
+ const scripts = Array.from(document.scripts).filter(isTrackerScript);
46
+ for (const script of scripts) script.addEventListener("error", markFailed);
47
+ return scripts;
48
+ }
49
+ function isDebug() {
50
+ return debugOption ?? isDevelopment();
51
+ }
52
+ /**
53
+ * Warns once per page when the tracker cannot arrive: no tracker script, or only failed ones. A
54
+ * missing script is judged at the timeout, because `<Highseat />` adds its tag in an effect that
55
+ * runs after the effects of the components inside it.
56
+ */
57
+ function watchTracker() {
58
+ if (typeof window === "undefined" || typeof document === "undefined") return;
59
+ if (watchedWindows.has(window)) return;
60
+ watchedWindows.add(window);
61
+ const page = window;
62
+ const deadline = Date.now() + TRACKER_TIMEOUT;
63
+ function check() {
64
+ if (window !== page || isLive(page.highseat)) return;
65
+ const scripts = findTrackerScripts();
66
+ if (scripts.length > 0 && scripts.every((script) => failedScripts.has(script))) {
67
+ console.warn(FAILED_SCRIPT_WARNING);
68
+ return;
69
+ }
70
+ if (Date.now() < deadline) {
71
+ setTimeout(check, TRACKER_POLL_INTERVAL);
72
+ return;
73
+ }
74
+ console.warn(scripts.length === 0 ? MISSING_SCRIPT_WARNING : SLOW_SCRIPT_WARNING);
75
+ }
76
+ setTimeout(check, TRACKER_POLL_INTERVAL);
77
+ }
78
+ /**
79
+ * Logs a call when debugging is on. The check waits a microtask, so a `debug` option that
80
+ * `<Highseat />` passes in its effect applies to the calls its children make in theirs.
81
+ */
82
+ function logCall(method, args, isQueued) {
83
+ queueMicrotask(() => {
84
+ if (!isDebug()) return;
85
+ const status = isQueued ? "queued until the tracker loads" : "sent to the tracker";
86
+ const [value, properties] = args;
87
+ const message = `highseat: ${method} ${String(JSON.stringify(value))}, ${status}`;
88
+ if (properties === void 0) console.info(message);
89
+ else console.info(message, properties);
90
+ watchTracker();
91
+ });
39
92
  }
40
93
  function call(method, args) {
41
94
  const api = findGlobal();
@@ -44,8 +97,10 @@ function call(method, args) {
44
97
  if (typeof handler !== "function") {
45
98
  api.q ??= [];
46
99
  api.q.push([method, args]);
100
+ logCall(method, args, true);
47
101
  return;
48
102
  }
103
+ logCall(method, args, false);
49
104
  try {
50
105
  handler(...args);
51
106
  } catch {}
@@ -76,14 +131,12 @@ function identify(id) {
76
131
  */
77
132
  async function getAttributionId(options = {}) {
78
133
  if (typeof window === "undefined" || typeof document === "undefined") return;
79
- const deadline = Date.now() + (options.timeout ?? ATTRIBUTION_TIMEOUT);
134
+ const deadline = Date.now() + (options.timeout ?? TRACKER_TIMEOUT);
80
135
  let api = window.highseat;
81
136
  while (!isLive(api)) {
82
137
  if (Date.now() >= deadline) return;
83
- const scripts = findTrackerScripts();
84
- for (const script of scripts) script.addEventListener("error", markFailed);
85
- if (scripts.every((script) => failedScripts.has(script))) return;
86
- await new Promise((resolve) => setTimeout(resolve, ATTRIBUTION_POLL_INTERVAL));
138
+ if (findTrackerScripts().every((script) => failedScripts.has(script))) return;
139
+ await new Promise((resolve) => setTimeout(resolve, TRACKER_POLL_INTERVAL));
87
140
  api = window.highseat;
88
141
  }
89
142
  try {
@@ -94,11 +147,14 @@ async function getAttributionId(options = {}) {
94
147
  }
95
148
  /**
96
149
  * Adds the tracker's script tag to the page, once. A second call for the same site, such as a
97
- * component mounting again, finds the tag and does nothing. Does nothing on a server.
150
+ * component mounting again, finds the tag and adds nothing, but its `debug` option still applies.
151
+ * Does nothing on a server.
98
152
  */
99
153
  function inject(options) {
100
154
  if (typeof document === "undefined") return;
101
- const { site, src = SCRIPT_URL, outbound, downloads, hashRouting } = options;
155
+ const { site, src = SCRIPT_URL, outbound, downloads, hashRouting, debug } = options;
156
+ debugOption = debug;
157
+ if (isDebug()) watchTracker();
102
158
  if (Array.from(document.scripts).some((script) => script.dataset.site === site)) return;
103
159
  const script = document.createElement("script");
104
160
  script.addEventListener("error", markFailed);
package/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * The browser client. Every call goes to the hosted tracker on `window.highseat`; before the\n * tracker has loaded, calls wait in a queue the tracker drains on startup. Nothing here throws:\n * on a server, with the tracker blocked, or with tracking off, a call does nothing.\n */\n\n/** A value an event property can hold. A `null` or `undefined` value is left out of the event. */\nexport type PropertyValue = string | number | boolean | null | undefined\n\n/**\n * Money attached to an event. `amount` is an integer in the currency's smallest unit, so\n * `{ amount: 4999, currency: \"USD\" }` is $49.99 and `{ amount: 5000, currency: \"JPY\" }` is ¥5000.\n */\nexport interface Revenue {\n /** An integer in minor units: 4999 for $49.99. An amount with decimals is rejected. */\n amount: number\n /** An ISO 4217 code, such as `USD` or `EUR`. */\n currency: string\n}\n\n/** The properties of an event with no declared shape: any string keys, plus optional revenue. */\nexport interface Properties {\n /** Money the event brought in. */\n revenue?: Revenue\n [key: string]: PropertyValue | Revenue\n}\n\n/**\n * The events Highseat knows by name. A site extends it, or overrides an entry, through\n * {@link Register}. Type-only: it adds nothing to the bundle.\n */\nexport interface BuiltInEvents {\n /** A visitor created an account. */\n signup: Properties\n /** A visitor signed in. */\n login: Properties\n /**\n * A sale. With a payment provider connected, leave `revenue` out: the provider's webhook\n * records the money, and revenue sent here as well would count the sale twice. Send `revenue`\n * only for a checkout no provider reports, and then with an `order_id`, so a provider sale\n * added later for the same order is not counted again.\n */\n purchase: Properties\n /** A paid subscription began. */\n subscription_started: Properties\n /** A free trial began. */\n trial_started: Properties\n /** A file download. The tracker records links to files on its own. */\n file_download: { url: string }\n /** A click on a link to another site. The tracker records these on its own. */\n outbound_link_click: { url: string }\n /** A visit to a missing page. Call it from a single-page app's not-found route. */\n \"404\": Properties\n}\n\n/**\n * Declares a site's own events. Augment it from any file the compiler sees:\n *\n * ```ts\n * declare module \"highseat\" {\n * interface Register {\n * events: {\n * signup: { plan: \"free\" | \"pro\" }\n * }\n * strict: true\n * }\n * }\n * ```\n *\n * `events` adds names, or replaces a built-in one's properties. `strict: true` makes `track`\n * accept only built-in and registered names, so a misspelt name is a type error.\n */\nexport interface Register {}\n\n/**\n * A registered event's properties as `track` accepts them. A shape with no properties takes none,\n * and a property whose type an event cannot carry becomes `never`, so a call passing it fails\n * instead of sending `\"[object Object]\"`. The shape is not rejected at registration, where a\n * failed check would silently drop every registered event at once.\n */\ntype CheckedProperties<Shape> = [keyof Shape] extends [never]\n ? Record<string, never>\n : { [Key in keyof Shape]: Shape[Key] extends PropertyValue | Revenue ? Shape[Key] : never }\n\ntype RegisteredEvents = Register extends { events: infer Registered }\n ? { [Name in keyof Registered]: CheckedProperties<Registered[Name]> }\n : {}\n\ntype KnownEvents = Omit<BuiltInEvents, keyof RegisteredEvents> & RegisteredEvents\n\n/** Every event name `track` knows, built-in or registered. */\nexport type EventName = Extract<keyof KnownEvents, string>\n\n/**\n * The names `track` accepts: known names, and any other string unless the site is strict.\n * `string & {}` keeps the known names in the editor's suggestions, which a plain `string` in the\n * union would absorb.\n */\nexport type TrackName = Register extends { strict: true } ? EventName : EventName | (string & {})\n\n/**\n * The arguments after an event's name. A known name takes its declared properties, required\n * when any of them is; any other name takes {@link Properties}. Wrapped in tuples so a union of\n * names is checked as a whole rather than name by name.\n */\nexport type TrackArgs<Name extends string> = [Name] extends [EventName]\n ? {} extends KnownEvents[Name]\n ? [properties?: KnownEvents[Name]]\n : [properties: KnownEvents[Name]]\n : [properties?: Properties]\n\n/** The tracker's API on `window.highseat`, or the queue that stands in for it until it loads. */\nexport interface HighseatGlobal {\n /** Records an event. */\n track?: (name: string, properties?: Properties) => void\n /** Sets or clears the visitor's user id. */\n identify?: (id: string | number | null | undefined) => void\n /** The id that joins a payment to this tab's visit. */\n getAttributionId?: () => string | undefined\n /** Calls made before the tracker loaded, drained in order when it starts. */\n q?: [string, unknown[]][]\n}\n\n/** How long {@link getAttributionId} waits for the tracker. */\nexport interface AttributionOptions {\n /** Milliseconds to wait for the tracker to load. Defaults to 3000. */\n timeout?: number\n}\n\n/** How the tracker is loaded. Each option maps to an attribute on its script tag. */\nexport interface InjectOptions {\n /** The site id, `site_…`, from the site's Installation settings. */\n site: string\n /**\n * Where the script loads from: the site's proxy path (`/3f9a0c1e2b`) for first-party\n * delivery, or a full URL. Defaults to Highseat's own host. The tracker posts its events back\n * to the same place.\n */\n src?: string\n /** Records clicks on links to other sites as `outbound_link_click`. Defaults to `true`. */\n outbound?: boolean\n /** Records clicks on links to files as `file_download`. Defaults to `true`. */\n downloads?: boolean\n /** Counts a change of `#/route` as a page view, for an app that routes by hash. */\n hashRouting?: boolean\n}\n\ndeclare global {\n interface Window {\n highseat?: HighseatGlobal\n }\n}\n\n/** Where the tracker loads from when the site has no proxy path. */\nexport const SCRIPT_URL = \"https://cdn.highseat.com/script.js\"\n\n// The tracker marks its own API with this symbol. A site's own stub can define methods too, so\n// only the symbol proves the tracker is running.\nconst LIVE = Symbol.for(\"highseat\")\n\nconst SCRIPT_HOST = new URL(SCRIPT_URL).host\n// A site's proxy path: `/` and ten hex characters.\nconst PROXY_PATH = /^\\/[0-9a-f]{10}$/\n\nconst ATTRIBUTION_TIMEOUT = 3000\nconst ATTRIBUTION_POLL_INTERVAL = 50\n\n// The script tags `inject` added, and every tracker script whose request failed, such as one an\n// ad blocker stopped. A browser keeps no record of a failed script, so a failure is only known\n// to a listener attached before it happened.\nconst injectedScripts = new WeakSet<HTMLScriptElement>()\nconst failedScripts = new WeakSet<HTMLScriptElement>()\n\nfunction findGlobal(): HighseatGlobal | undefined {\n if (typeof window === \"undefined\") return\n return (window.highseat ??= {})\n}\n\nfunction isLive(api: HighseatGlobal | undefined): api is HighseatGlobal {\n return !!api && (api as Record<symbol, unknown>)[LIVE] === true\n}\n\n// One function for every script, so attaching it on each poll adds no second listener.\nfunction markFailed(event: Event) {\n failedScripts.add(event.currentTarget as HTMLScriptElement)\n}\n\n/**\n * Whether a script tag loads the tracker, judged as the tracker judges itself. Fathom's snippet\n * carries a `data-site` too, so a tag is matched by a `site_` id, or by a `src` on a proxy path\n * or on Highseat's host: an older site's id is a UUID, which any tool could use.\n */\nfunction isTrackerScript(script: HTMLScriptElement) {\n const { site } = script.dataset\n if (injectedScripts.has(script) || site?.startsWith(\"site_\")) return true\n if (site === undefined) return false\n\n try {\n // A browser hands back `src` resolved; the base only matters to a relative one.\n const url = new URL(script.src, \"http://localhost\")\n return url.host === SCRIPT_HOST || PROXY_PATH.test(url.pathname)\n } catch {\n return false\n }\n}\n\nfunction findTrackerScripts() {\n return Array.from(document.scripts).filter(isTrackerScript)\n}\n\nfunction call(method: \"track\" | \"identify\", args: unknown[]) {\n const api = findGlobal()\n if (!api) return\n\n const handler = api[method] as ((...values: unknown[]) => void) | undefined\n if (typeof handler !== \"function\") {\n api.q ??= []\n api.q.push([method, args])\n return\n }\n\n try {\n handler(...args)\n } catch {}\n}\n\n/**\n * Records an event. A known name autocompletes and checks its properties; any other name is a\n * custom event, unless {@link Register} sets `strict`. Names are stored exactly as written, so\n * `Purchase` and `purchase` are two events.\n */\nexport function track<Name extends TrackName>(name: Name, ...args: TrackArgs<Name>): void {\n const [properties] = args\n call(\"track\", properties === undefined ? [name] : [name, properties])\n}\n\n/**\n * Links the visitor to a user id from your own system, on this event and every later one, across\n * visits. `null` clears it at sign-out. An empty or `undefined` id is ignored, so\n * `identify(user?.id)` before a session loads does not sign the visitor out.\n */\nexport function identify(id: string | number | null | undefined): void {\n call(\"identify\", [id])\n}\n\n/**\n * The id that joins a payment to this tab's visit. Pass it to the checkout as metadata\n * (`attribution_id`), and the payment provider's webhook credits the sale to the visit's source.\n * Resolves to `undefined`, so a checkout that awaits it never hangs: at once when the page has\n * no tracker script or its script fails to load (an ad blocker stopping it), after the timeout\n * when the script is still loading, and on a server or with tracking off.\n */\nexport async function getAttributionId(\n options: AttributionOptions = {},\n): Promise<string | undefined> {\n if (typeof window === \"undefined\" || typeof document === \"undefined\") return\n\n const deadline = Date.now() + (options.timeout ?? ATTRIBUTION_TIMEOUT)\n let api = window.highseat\n\n while (!isLive(api)) {\n if (Date.now() >= deadline) return\n\n const scripts = findTrackerScripts()\n for (const script of scripts) script.addEventListener(\"error\", markFailed)\n // No tracker script at all, or only failed ones: the tracker cannot arrive.\n if (scripts.every(script => failedScripts.has(script))) return\n\n await new Promise(resolve => setTimeout(resolve, ATTRIBUTION_POLL_INTERVAL))\n api = window.highseat\n }\n\n try {\n return api.getAttributionId?.()\n } catch {\n return\n }\n}\n\n/**\n * Adds the tracker's script tag to the page, once. A second call for the same site, such as a\n * component mounting again, finds the tag and does nothing. Does nothing on a server.\n */\nexport function inject(options: InjectOptions): void {\n if (typeof document === \"undefined\") return\n\n const { site, src = SCRIPT_URL, outbound, downloads, hashRouting } = options\n if (Array.from(document.scripts).some(script => script.dataset.site === site)) return\n\n const script = document.createElement(\"script\")\n script.addEventListener(\"error\", markFailed)\n injectedScripts.add(script)\n script.src = src\n script.dataset.site = site\n if (outbound === false) script.dataset.outbound = \"false\"\n if (downloads === false) script.dataset.downloads = \"false\"\n if (hashRouting) script.dataset.hashRouting = \"\"\n document.head.append(script)\n}\n"],"mappings":";;AA0JA,MAAa,aAAa;AAI1B,MAAM,OAAO,OAAO,IAAI,UAAU;AAElC,MAAM,cAAc,IAAI,IAAI,UAAU,CAAC,CAAC;AAExC,MAAM,aAAa;AAEnB,MAAM,sBAAsB;AAC5B,MAAM,4BAA4B;AAKlC,MAAM,kCAAkB,IAAI,QAA2B;AACvD,MAAM,gCAAgB,IAAI,QAA2B;AAErD,SAAS,aAAyC;CAChD,IAAI,OAAO,WAAW,aAAa;CACnC,OAAQ,OAAO,aAAa,CAAC;AAC/B;AAEA,SAAS,OAAO,KAAwD;CACtE,OAAO,CAAC,CAAC,OAAQ,IAAgC,UAAU;AAC7D;AAGA,SAAS,WAAW,OAAc;CAChC,cAAc,IAAI,MAAM,aAAkC;AAC5D;;;;;;AAOA,SAAS,gBAAgB,QAA2B;CAClD,MAAM,EAAE,SAAS,OAAO;CACxB,IAAI,gBAAgB,IAAI,MAAM,KAAK,MAAM,WAAW,OAAO,GAAG,OAAO;CACrE,IAAI,SAAS,KAAA,GAAW,OAAO;CAE/B,IAAI;EAEF,MAAM,MAAM,IAAI,IAAI,OAAO,KAAK,kBAAkB;EAClD,OAAO,IAAI,SAAS,eAAe,WAAW,KAAK,IAAI,QAAQ;C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,MAAM,EAAE,MAAM,MAAM,YAAY,UAAU,WAAW,gBAAgB;CACrE,IAAI,MAAM,KAAK,SAAS,OAAO,CAAC,CAAC,MAAK,WAAU,OAAO,QAAQ,SAAS,IAAI,GAAG;CAE/E,MAAM,SAAS,SAAS,cAAc,QAAQ;CAC9C,OAAO,iBAAiB,SAAS,UAAU;CAC3C,gBAAgB,IAAI,MAAM;CAC1B,OAAO,MAAM;CACb,OAAO,QAAQ,OAAO;CACtB,IAAI,aAAa,OAAO,OAAO,QAAQ,WAAW;CAClD,IAAI,cAAc,OAAO,OAAO,QAAQ,YAAY;CACpD,IAAI,aAAa,OAAO,QAAQ,cAAc;CAC9C,SAAS,KAAK,OAAO,MAAM;AAC7B"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["import { isDevelopment } from \"./env\"\n\n/**\n * The browser client. Every call goes to the hosted tracker on `window.highseat`; before the\n * tracker has loaded, calls wait in a queue the tracker drains on startup. Nothing here throws:\n * on a server, with the tracker blocked, or with tracking off, a call does nothing.\n */\n\n/** A value an event property can hold. A `null` or `undefined` value is left out of the event. */\nexport type PropertyValue = string | number | boolean | null | undefined\n\n/**\n * Money attached to an event. `amount` is an integer in the currency's smallest unit, so\n * `{ amount: 4999, currency: \"USD\" }` is $49.99 and `{ amount: 5000, currency: \"JPY\" }` is ¥5000.\n */\nexport interface Revenue {\n /** An integer in minor units: 4999 for $49.99. An amount with decimals is rejected. */\n amount: number\n /** An ISO 4217 code, such as `USD` or `EUR`. */\n currency: string\n}\n\n/** The properties of an event with no declared shape: any string keys, plus optional revenue. */\nexport interface Properties {\n /** Money the event brought in. */\n revenue?: Revenue\n [key: string]: PropertyValue | Revenue\n}\n\n/**\n * The events Highseat knows by name. A site extends it, or overrides an entry, through\n * {@link Register}. Type-only: it adds nothing to the bundle.\n */\nexport interface BuiltInEvents {\n /** A visitor created an account. */\n signup: Properties\n /** A visitor signed in. */\n login: Properties\n /**\n * A sale. With a payment provider connected, leave `revenue` out: the provider's webhook\n * records the money, and revenue sent here as well would count the sale twice. Send `revenue`\n * only for a checkout no provider reports, and then with an `order_id`, so a provider sale\n * added later for the same order is not counted again.\n */\n purchase: Properties\n /** A paid subscription began. */\n subscription_started: Properties\n /** A free trial began. */\n trial_started: Properties\n /** A file download. The tracker records links to files on its own. */\n file_download: { url: string }\n /** A click on a link to another site. The tracker records these on its own. */\n outbound_link_click: { url: string }\n /** A visit to a missing page. Call it from a single-page app's not-found route. */\n \"404\": Properties\n}\n\n/**\n * Declares a site's own events. Augment it from any file the compiler sees:\n *\n * ```ts\n * declare module \"highseat\" {\n * interface Register {\n * events: {\n * signup: { plan: \"free\" | \"pro\" }\n * }\n * strict: true\n * }\n * }\n * ```\n *\n * `events` adds names, or replaces a built-in one's properties. `strict: true` makes `track`\n * accept only built-in and registered names, so a misspelt name is a type error.\n */\nexport interface Register {}\n\n/**\n * A registered event's properties as `track` accepts them. A shape with no properties takes none,\n * and a property whose type an event cannot carry becomes `never`, so a call passing it fails\n * instead of sending `\"[object Object]\"`. The shape is not rejected at registration, where a\n * failed check would silently drop every registered event at once.\n */\ntype CheckedProperties<Shape> = [keyof Shape] extends [never]\n ? Record<string, never>\n : { [Key in keyof Shape]: Shape[Key] extends PropertyValue | Revenue ? Shape[Key] : never }\n\ntype RegisteredEvents = Register extends { events: infer Registered }\n ? { [Name in keyof Registered]: CheckedProperties<Registered[Name]> }\n : {}\n\ntype KnownEvents = Omit<BuiltInEvents, keyof RegisteredEvents> & RegisteredEvents\n\n/** Every event name `track` knows, built-in or registered. */\nexport type EventName = Extract<keyof KnownEvents, string>\n\n/**\n * The names `track` accepts: known names, and any other string unless the site is strict.\n * `string & {}` keeps the known names in the editor's suggestions, which a plain `string` in the\n * union would absorb.\n */\nexport type TrackName = Register extends { strict: true } ? EventName : EventName | (string & {})\n\n/**\n * The arguments after an event's name. A known name takes its declared properties, required\n * when any of them is; any other name takes {@link Properties}. Wrapped in tuples so a union of\n * names is checked as a whole rather than name by name.\n */\nexport type TrackArgs<Name extends string> = [Name] extends [EventName]\n ? {} extends KnownEvents[Name]\n ? [properties?: KnownEvents[Name]]\n : [properties: KnownEvents[Name]]\n : [properties?: Properties]\n\n/**\n * A user id from your own system, as {@link identify} takes it. A string or a number identifies\n * the visitor, `null` clears the id, and `undefined` or an empty string changes nothing. Pass your\n * own database id, never an email or other personal data.\n */\nexport type UserId = string | number | null | undefined\n\n/** The tracker's API on `window.highseat`, or the queue that stands in for it until it loads. */\nexport interface HighseatGlobal {\n /** Records an event. */\n track?: (name: string, properties?: Properties) => void\n /** Sets or clears the visitor's user id. */\n identify?: (id: UserId) => void\n /** The id that joins a payment to this tab's visit. */\n getAttributionId?: () => string | undefined\n /** Calls made before the tracker loaded, drained in order when it starts. */\n q?: [string, unknown[]][]\n}\n\n/** How long {@link getAttributionId} waits for the tracker. */\nexport interface AttributionOptions {\n /** Milliseconds to wait for the tracker to load. Defaults to 3000. */\n timeout?: number\n}\n\n/** How the tracker is loaded. Each option maps to an attribute on its script tag. */\nexport interface InjectOptions {\n /** The site id, `site_…`, from the site's Installation settings. */\n site: string\n /**\n * Where the script loads from: the site's proxy path (`/3f9a0c1e2b`) for first-party\n * delivery, or a full URL. Defaults to Highseat's own host. The tracker posts its events back\n * to the same place.\n */\n src?: string\n /** Records clicks on links to other sites as `outbound_link_click`. Defaults to `true`. */\n outbound?: boolean\n /** Records clicks on links to files as `file_download`. Defaults to `true`. */\n downloads?: boolean\n /** Counts a change of `#/route` as a page view, for an app that routes by hash. */\n hashRouting?: boolean\n /**\n * Logs every `track()` and `identify()` call to the console, and warns once when no tracker\n * script is on the page or the script failed to load. Defaults to `true` when\n * `process.env.NODE_ENV` is `development`, so a production build logs nothing.\n */\n debug?: boolean\n}\n\ndeclare global {\n interface Window {\n highseat?: HighseatGlobal\n }\n}\n\n/** Where the tracker loads from when the site has no proxy path. */\nexport const SCRIPT_URL = \"https://cdn.highseat.com/script.js\"\n\n// The tracker marks its own API with this symbol. A site's own stub can define methods too, so\n// only the symbol proves the tracker is running.\nconst LIVE = Symbol.for(\"highseat\")\n\nconst SCRIPT_HOST = new URL(SCRIPT_URL).host\n// A site's proxy path: `/` and ten hex characters.\nconst PROXY_PATH = /^\\/[0-9a-f]{10}$/\n\nconst TRACKER_TIMEOUT = 3000\nconst TRACKER_POLL_INTERVAL = 50\n\nconst MISSING_SCRIPT_WARNING = [\n \"highseat: no tracker script on this page, so no event reaches Highseat.\",\n \"Render <Highseat />, call inject({ site }), or add the script tag from the site's Installation settings.\",\n].join(\" \")\nconst FAILED_SCRIPT_WARNING = [\n \"highseat: the tracker script failed to load, so no event reaches Highseat.\",\n \"An ad blocker may have stopped it: load the tracker from the site's proxy path instead.\",\n].join(\" \")\nconst SLOW_SCRIPT_WARNING = [\n `highseat: the tracker script has not loaded after ${TRACKER_TIMEOUT / 1000} seconds,`,\n \"so every call waits in the queue. Check the network panel for a blocked or failed request.\",\n].join(\" \")\n\n// The script tags `inject` added, and every tracker script whose request failed, such as one an\n// ad blocker stopped. A browser keeps no record of a failed script, so a failure is only known\n// to a listener attached before it happened.\nconst injectedScripts = new WeakSet<HTMLScriptElement>()\nconst failedScripts = new WeakSet<HTMLScriptElement>()\n\n// The `debug` option of the last `inject` call. Unset falls back to the build's environment.\nlet debugOption: boolean | undefined\n// The windows whose tracker is being watched, so a page warns about its script once.\nconst watchedWindows = new WeakSet<Window>()\n\nfunction findGlobal(): HighseatGlobal | undefined {\n if (typeof window === \"undefined\") return\n return (window.highseat ??= {})\n}\n\nfunction isLive(api: HighseatGlobal | undefined): api is HighseatGlobal {\n return !!api && (api as Record<symbol, unknown>)[LIVE] === true\n}\n\n// One function for every script, so attaching it on each poll adds no second listener.\nfunction markFailed(event: Event) {\n failedScripts.add(event.currentTarget as HTMLScriptElement)\n}\n\n/**\n * Whether a script tag loads the tracker, judged as the tracker judges itself. Fathom's snippet\n * carries a `data-site` too, so a tag is matched by a `site_` id, or by a `src` on a proxy path\n * or on Highseat's host: an older site's id is a UUID, which any tool could use.\n */\nfunction isTrackerScript(script: HTMLScriptElement) {\n const { site } = script.dataset\n if (injectedScripts.has(script) || site?.startsWith(\"site_\")) return true\n if (site === undefined) return false\n\n try {\n // A browser hands back `src` resolved; the base only matters to a relative one.\n const url = new URL(script.src, \"http://localhost\")\n return url.host === SCRIPT_HOST || PROXY_PATH.test(url.pathname)\n } catch {\n return false\n }\n}\n\n/** The page's tracker scripts, each one listened to from now on for a failed load. */\nfunction findTrackerScripts() {\n const scripts = Array.from(document.scripts).filter(isTrackerScript)\n for (const script of scripts) script.addEventListener(\"error\", markFailed)\n return scripts\n}\n\nfunction isDebug() {\n return debugOption ?? isDevelopment()\n}\n\n/**\n * Warns once per page when the tracker cannot arrive: no tracker script, or only failed ones. A\n * missing script is judged at the timeout, because `<Highseat />` adds its tag in an effect that\n * runs after the effects of the components inside it.\n */\nfunction watchTracker() {\n if (typeof window === \"undefined\" || typeof document === \"undefined\") return\n if (watchedWindows.has(window)) return\n watchedWindows.add(window)\n\n const page = window\n const deadline = Date.now() + TRACKER_TIMEOUT\n\n function check() {\n // A replaced global window, as a test sets up for each case, is another page.\n if (window !== page || isLive(page.highseat)) return\n\n const scripts = findTrackerScripts()\n\n if (scripts.length > 0 && scripts.every(script => failedScripts.has(script))) {\n console.warn(FAILED_SCRIPT_WARNING)\n return\n }\n if (Date.now() < deadline) {\n setTimeout(check, TRACKER_POLL_INTERVAL)\n return\n }\n console.warn(scripts.length === 0 ? MISSING_SCRIPT_WARNING : SLOW_SCRIPT_WARNING)\n }\n\n setTimeout(check, TRACKER_POLL_INTERVAL)\n}\n\n/**\n * Logs a call when debugging is on. The check waits a microtask, so a `debug` option that\n * `<Highseat />` passes in its effect applies to the calls its children make in theirs.\n */\nfunction logCall(method: \"track\" | \"identify\", args: unknown[], isQueued: boolean) {\n queueMicrotask(() => {\n if (!isDebug()) return\n\n const status = isQueued ? \"queued until the tracker loads\" : \"sent to the tracker\"\n const [value, properties] = args\n // `JSON.stringify` quotes a name or a string id, and returns `undefined` for an unset id.\n const message = `highseat: ${method} ${String(JSON.stringify(value))}, ${status}`\n\n if (properties === undefined) console.info(message)\n else console.info(message, properties)\n watchTracker()\n })\n}\n\nfunction call(method: \"track\" | \"identify\", args: unknown[]) {\n const api = findGlobal()\n if (!api) return\n\n const handler = api[method] as ((...values: unknown[]) => void) | undefined\n if (typeof handler !== \"function\") {\n api.q ??= []\n api.q.push([method, args])\n logCall(method, args, true)\n return\n }\n\n logCall(method, args, false)\n try {\n handler(...args)\n } catch {}\n}\n\n/**\n * Records an event. A known name autocompletes and checks its properties; any other name is a\n * custom event, unless {@link Register} sets `strict`. Names are stored exactly as written, so\n * `Purchase` and `purchase` are two events.\n */\nexport function track<Name extends TrackName>(name: Name, ...args: TrackArgs<Name>): void {\n const [properties] = args\n call(\"track\", properties === undefined ? [name] : [name, properties])\n}\n\n/**\n * Links the visitor to a user id from your own system, on this event and every later one, across\n * visits. `null` clears it at sign-out. An empty or `undefined` id is ignored, so\n * `identify(user?.id)` before a session loads does not sign the visitor out.\n */\nexport function identify(id: UserId): void {\n call(\"identify\", [id])\n}\n\n/**\n * The id that joins a payment to this tab's visit. Pass it to the checkout as metadata\n * (`attribution_id`), and the payment provider's webhook credits the sale to the visit's source.\n * Resolves to `undefined`, so a checkout that awaits it never hangs: at once when the page has\n * no tracker script or its script fails to load (an ad blocker stopping it), after the timeout\n * when the script is still loading, and on a server or with tracking off.\n */\nexport async function getAttributionId(\n options: AttributionOptions = {},\n): Promise<string | undefined> {\n if (typeof window === \"undefined\" || typeof document === \"undefined\") return\n\n const deadline = Date.now() + (options.timeout ?? TRACKER_TIMEOUT)\n let api = window.highseat\n\n while (!isLive(api)) {\n if (Date.now() >= deadline) return\n\n const scripts = findTrackerScripts()\n // No tracker script at all, or only failed ones: the tracker cannot arrive.\n if (scripts.every(script => failedScripts.has(script))) return\n\n await new Promise(resolve => setTimeout(resolve, TRACKER_POLL_INTERVAL))\n api = window.highseat\n }\n\n try {\n return api.getAttributionId?.()\n } catch {\n return\n }\n}\n\n/**\n * Adds the tracker's script tag to the page, once. A second call for the same site, such as a\n * component mounting again, finds the tag and adds nothing, but its `debug` option still applies.\n * Does nothing on a server.\n */\nexport function inject(options: InjectOptions): void {\n if (typeof document === \"undefined\") return\n\n const { site, src = SCRIPT_URL, outbound, downloads, hashRouting, debug } = options\n debugOption = debug\n if (isDebug()) watchTracker()\n if (Array.from(document.scripts).some(script => script.dataset.site === site)) return\n\n const script = document.createElement(\"script\")\n script.addEventListener(\"error\", markFailed)\n injectedScripts.add(script)\n script.src = src\n script.dataset.site = site\n if (outbound === false) script.dataset.outbound = \"false\"\n if (downloads === false) script.dataset.downloads = \"false\"\n if (hashRouting) script.dataset.hashRouting = \"\"\n document.head.append(script)\n}\n"],"mappings":";;;AAyKA,MAAa,aAAa;AAI1B,MAAM,OAAO,OAAO,IAAI,UAAU;AAElC,MAAM,cAAc,IAAI,IAAI,UAAU,CAAC,CAAC;AAExC,MAAM,aAAa;AAEnB,MAAM,kBAAkB;AACxB,MAAM,wBAAwB;AAE9B,MAAM,yBAAyB,CAC7B,2EACA,0GACF,CAAC,CAAC,KAAK,GAAG;AACV,MAAM,wBAAwB,CAC5B,8EACA,yFACF,CAAC,CAAC,KAAK,GAAG;AACV,MAAM,sBAAsB,CAC1B,qDAAqD,kBAAkB,IAAK,YAC5E,4FACF,CAAC,CAAC,KAAK,GAAG;AAKV,MAAM,kCAAkB,IAAI,QAA2B;AACvD,MAAM,gCAAgB,IAAI,QAA2B;AAGrD,IAAI;AAEJ,MAAM,iCAAiB,IAAI,QAAgB;AAE3C,SAAS,aAAyC;CAChD,IAAI,OAAO,WAAW,aAAa;CACnC,OAAQ,OAAO,aAAa,CAAC;AAC/B;AAEA,SAAS,OAAO,KAAwD;CACtE,OAAO,CAAC,CAAC,OAAQ,IAAgC,UAAU;AAC7D;AAGA,SAAS,WAAW,OAAc;CAChC,cAAc,IAAI,MAAM,aAAkC;AAC5D;;;;;;AAOA,SAAS,gBAAg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;;;;;;AAOA,SAAgB,OAAO,SAA8B;CACnD,IAAI,OAAO,aAAa,aAAa;CAErC,MAAM,EAAE,MAAM,MAAM,YAAY,UAAU,WAAW,aAAa,UAAU;CAC5E,cAAc;CACd,IAAI,QAAQ,GAAG,aAAa;CAC5B,IAAI,MAAM,KAAK,SAAS,OAAO,CAAC,CAAC,MAAK,WAAU,OAAO,QAAQ,SAAS,IAAI,GAAG;CAE/E,MAAM,SAAS,SAAS,cAAc,QAAQ;CAC9C,OAAO,iBAAiB,SAAS,UAAU;CAC3C,gBAAgB,IAAI,MAAM;CAC1B,OAAO,MAAM;CACb,OAAO,QAAQ,OAAO;CACtB,IAAI,aAAa,OAAO,OAAO,QAAQ,WAAW;CAClD,IAAI,cAAc,OAAO,OAAO,QAAQ,YAAY;CACpD,IAAI,aAAa,OAAO,QAAQ,cAAc;CAC9C,SAAS,KAAK,OAAO,MAAM;AAC7B"}
package/next.d.ts CHANGED
@@ -1,13 +1,15 @@
1
- import { InjectOptions } from "./index.js";
1
+ import { HighseatProps as HighseatProps$1, useIdentify } from "./react.js";
2
2
  import { ClientIp, ClientIpPreset, ProxyHandler, ProxyOptions, createProxy } from "./proxy.js";
3
3
  import { ReactElement } from "react";
4
4
  //#region src/next.d.ts
5
- export interface HighseatProps extends Partial<InjectOptions> {}
5
+ export interface HighseatProps extends Partial<HighseatProps$1> {}
6
6
  /**
7
7
  * Loads the Highseat tracker in a Next.js app. Render it once, in the root layout. The site id
8
8
  * comes from `NEXT_PUBLIC_HIGHSEAT_SITE`, and the script loads from the site's proxy path in
9
9
  * `HIGHSEAT_PATH` when one is set. `HIGHSEAT_PATH` is a server variable, so in the Pages Router,
10
10
  * where the layout also renders in the browser, pass `src` instead. A prop wins over its variable.
11
+ * `userId` takes an id the server already knows. For a session read in the browser, call
12
+ * `useIdentify` in a client component instead.
11
13
  */
12
14
  export declare function Highseat(props: HighseatProps): ReactElement | null;
13
15
  /** A Next.js rewrite: the subset of its fields this package writes and reads. */
@@ -56,5 +58,5 @@ export interface WithHighseatOptions {
56
58
  */
57
59
  export declare function withHighseat<Config extends object>(config: Config, options?: WithHighseatOptions): WithHighseatConfig<Config>;
58
60
  //#endregion
59
- export { type ClientIp, type ClientIpPreset, type ProxyHandler, type ProxyOptions, createProxy };
61
+ export { type ClientIp, type ClientIpPreset, type ProxyHandler, type ProxyOptions, createProxy, useIdentify };
60
62
  //# sourceMappingURL=next.d.ts.map
package/next.js CHANGED
@@ -1,5 +1,6 @@
1
- import { Highseat as Highseat$1 } from "./react.js";
2
- import { n as findNextSite, r as findProxyPath, t as createProxy } from "./proxy2.js";
1
+ import { findNextSite, findProxyPath } from "./env.js";
2
+ import { Highseat as Highseat$1, useIdentify } from "./react.js";
3
+ import { createProxy } from "./proxy.js";
3
4
  import { createElement } from "react";
4
5
  //#region src/next.ts
5
6
  /**
@@ -7,6 +8,8 @@ import { createElement } from "react";
7
8
  * comes from `NEXT_PUBLIC_HIGHSEAT_SITE`, and the script loads from the site's proxy path in
8
9
  * `HIGHSEAT_PATH` when one is set. `HIGHSEAT_PATH` is a server variable, so in the Pages Router,
9
10
  * where the layout also renders in the browser, pass `src` instead. A prop wins over its variable.
11
+ * `userId` takes an id the server already knows. For a session read in the browser, call
12
+ * `useIdentify` in a client component instead.
10
13
  */
11
14
  function Highseat(props) {
12
15
  const site = props.site ?? findNextSite();
@@ -74,6 +77,6 @@ function withHighseat(config, options = {}) {
74
77
  };
75
78
  }
76
79
  //#endregion
77
- export { Highseat, createProxy, withHighseat };
80
+ export { Highseat, createProxy, useIdentify, withHighseat };
78
81
 
79
82
  //# sourceMappingURL=next.js.map
package/next.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"next.js","names":["ReactHighseat"],"sources":["../src/next.ts"],"sourcesContent":["import { createElement, type ReactElement } from \"react\"\nimport { findNextSite, findProxyPath } from \"./env\"\nimport type { InjectOptions } from \"./index\"\nimport { Highseat as ReactHighseat } from \"./react\"\n\nexport { createProxy } from \"./proxy\"\nexport type { ClientIp, ClientIpPreset, ProxyHandler, ProxyOptions } from \"./proxy\"\n\nexport interface HighseatProps extends Partial<InjectOptions> {}\n\n/**\n * Loads the Highseat tracker in a Next.js app. Render it once, in the root layout. The site id\n * comes from `NEXT_PUBLIC_HIGHSEAT_SITE`, and the script loads from the site's proxy path in\n * `HIGHSEAT_PATH` when one is set. `HIGHSEAT_PATH` is a server variable, so in the Pages Router,\n * where the layout also renders in the browser, pass `src` instead. A prop wins over its variable.\n */\nexport function Highseat(props: HighseatProps): ReactElement | null {\n const site = props.site ?? findNextSite()\n const src = props.src ?? findProxyPath()\n\n if (!site) {\n console.warn(\"highseat: set NEXT_PUBLIC_HIGHSEAT_SITE, or pass `site` to <Highseat />\")\n return null\n }\n\n return createElement(ReactHighseat, { ...props, site, src })\n}\n\n/** A Next.js rewrite: the subset of its fields this package writes and reads. */\ninterface Rewrite {\n source: string\n destination: string\n}\n\n/** The phases Next.js applies rewrites in, when `rewrites()` returns an object. */\ninterface RewritePhases {\n beforeFiles?: Rewrite[]\n afterFiles?: Rewrite[]\n fallback?: Rewrite[]\n}\n\n/** The part of a Next.js config `withHighseat` reads. */\ninterface NextConfigWithRewrites {\n rewrites?: () => Promise<Rewrite[] | RewritePhases>\n}\n\n/** A Next.js config with the proxy's rewrite added, or its own rewrites when there is no path. */\nexport type WithHighseatConfig<Config> = Config & {\n rewrites: () => Promise<Rewrite[] | RewritePhases>\n}\n\nexport interface WithHighseatOptions {\n /**\n * The site's proxy path from Installation settings. Defaults to the `HIGHSEAT_PATH`\n * environment variable, the one `createProxy()` reads, so rotating the path is an\n * environment change and a redeploy.\n */\n path?: string\n /**\n * Where the app's proxy route handler lives. Defaults to `/api/highseat`, the route of\n * `app/api/highseat/route.ts`.\n */\n route?: string\n}\n\nconst DEFAULT_ROUTE = \"/api/highseat\"\n\n// A dev session can ask for the rewrites more than once, so the warning is printed once.\nlet hasWarnedNoPath = false\n\n/**\n * Adds a rewrite from the site's proxy path to the app's proxy route handler, ahead of every\n * other route. The rewrite stays inside the app, so the handler still sees the visitor's IP, and\n * the route file never moves when the path rotates.\n *\n * The proxy is optional. Without a path, `next dev` and `next build` warn once and leave the\n * rewrite out, and `<Highseat />` loads the tracker from Highseat's host. Nothing here throws,\n * so `next typegen` runs without the variable too. The build writes the rewrite, so a path set\n * only at runtime points a dynamically rendered `<Highseat />` at a route that is not there.\n *\n * ```ts\n * // next.config.ts\n * import { withHighseat } from \"highseat/next\"\n * export default withHighseat({ reactStrictMode: true })\n * ```\n */\nexport function withHighseat<Config extends object>(\n config: Config,\n options: WithHighseatOptions = {},\n): WithHighseatConfig<Config> {\n const path = findProxyPath(options.path)\n\n // Typed loosely so any Next.js version's config fits; only `rewrites` is read.\n const { rewrites: ownRewrites } = config as NextConfigWithRewrites\n\n async function passRewritesThrough(): Promise<Rewrite[] | RewritePhases> {\n if (!hasWarnedNoPath) {\n hasWarnedNoPath = true\n console.warn(\n \"highseat/next: no HIGHSEAT_PATH, so this build has no proxy rewrite and the tracker loads from Highseat's host. For first-party delivery, set it to the path from the site's Installation settings, or pass `path`, for the build as well as at runtime: a path set only at runtime points the tracker at a route this build does not have.\",\n )\n }\n return (await ownRewrites?.()) ?? []\n }\n\n if (!path) return { ...config, rewrites: passRewritesThrough }\n\n const rewrite = { source: path, destination: options.route ?? DEFAULT_ROUTE }\n\n async function rewrites(): Promise<RewritePhases> {\n const existing = (await ownRewrites?.()) ?? []\n\n // A plain array is Next.js shorthand for the `afterFiles` phase.\n if (Array.isArray(existing)) return { beforeFiles: [rewrite], afterFiles: existing }\n return { ...existing, beforeFiles: [rewrite, ...(existing.beforeFiles ?? [])] }\n }\n\n return { ...config, rewrites }\n}\n"],"mappings":";;;;;;;;;;AAgBA,SAAgB,SAAS,OAA2C;CAClE,MAAM,OAAO,MAAM,QAAQ,aAAa;CACxC,MAAM,MAAM,MAAM,OAAO,cAAc;CAEvC,IAAI,CAAC,MAAM;EACT,QAAQ,KAAK,yEAAyE;EACtF,OAAO;CACT;CAEA,OAAO,cAAcA,YAAe;EAAE,GAAG;EAAO;EAAM;CAAI,CAAC;AAC7D;AAuCA,MAAM,gBAAgB;AAGtB,IAAI,kBAAkB;;;;;;;;;;;;;;;;;AAkBtB,SAAgB,aACd,QACA,UAA+B,CAAC,GACJ;CAC5B,MAAM,OAAO,cAAc,QAAQ,IAAI;CAGvC,MAAM,EAAE,UAAU,gBAAgB;CAElC,eAAe,sBAA0D;EACvE,IAAI,CAAC,iBAAiB;GACpB,kBAAkB;GAClB,QAAQ,KACN,6UACF;EACF;EACA,OAAQ,MAAM,cAAc,KAAM,CAAC;CACrC;CAEA,IAAI,CAAC,MAAM,OAAO;EAAE,GAAG;EAAQ,UAAU;CAAoB;CAE7D,MAAM,UAAU;EAAE,QAAQ;EAAM,aAAa,QAAQ,SAAS;CAAc;CAE5E,eAAe,WAAmC;EAChD,MAAM,WAAY,MAAM,cAAc,KAAM,CAAC;EAG7C,IAAI,MAAM,QAAQ,QAAQ,GAAG,OAAO;GAAE,aAAa,CAAC,OAAO;GAAG,YAAY;EAAS;EACnF,OAAO;GAAE,GAAG;GAAU,aAAa,CAAC,SAAS,GAAI,SAAS,eAAe,CAAC,CAAE;EAAE;CAChF;CAEA,OAAO;EAAE,GAAG;EAAQ;CAAS;AAC/B"}
1
+ {"version":3,"file":"next.js","names":["ReactHighseat"],"sources":["../src/next.ts"],"sourcesContent":["import { createElement, type ReactElement } from \"react\"\nimport { findNextSite, findProxyPath } from \"./env\"\nimport { Highseat as ReactHighseat, type HighseatProps as ReactHighseatProps } from \"./react\"\n\nexport { createProxy } from \"./proxy\"\nexport { useIdentify } from \"./react\"\nexport type { ClientIp, ClientIpPreset, ProxyHandler, ProxyOptions } from \"./proxy\"\n\nexport interface HighseatProps extends Partial<ReactHighseatProps> {}\n\n/**\n * Loads the Highseat tracker in a Next.js app. Render it once, in the root layout. The site id\n * comes from `NEXT_PUBLIC_HIGHSEAT_SITE`, and the script loads from the site's proxy path in\n * `HIGHSEAT_PATH` when one is set. `HIGHSEAT_PATH` is a server variable, so in the Pages Router,\n * where the layout also renders in the browser, pass `src` instead. A prop wins over its variable.\n * `userId` takes an id the server already knows. For a session read in the browser, call\n * `useIdentify` in a client component instead.\n */\nexport function Highseat(props: HighseatProps): ReactElement | null {\n const site = props.site ?? findNextSite()\n const src = props.src ?? findProxyPath()\n\n if (!site) {\n console.warn(\"highseat: set NEXT_PUBLIC_HIGHSEAT_SITE, or pass `site` to <Highseat />\")\n return null\n }\n\n return createElement(ReactHighseat, { ...props, site, src })\n}\n\n/** A Next.js rewrite: the subset of its fields this package writes and reads. */\ninterface Rewrite {\n source: string\n destination: string\n}\n\n/** The phases Next.js applies rewrites in, when `rewrites()` returns an object. */\ninterface RewritePhases {\n beforeFiles?: Rewrite[]\n afterFiles?: Rewrite[]\n fallback?: Rewrite[]\n}\n\n/** The part of a Next.js config `withHighseat` reads. */\ninterface NextConfigWithRewrites {\n rewrites?: () => Promise<Rewrite[] | RewritePhases>\n}\n\n/** A Next.js config with the proxy's rewrite added, or its own rewrites when there is no path. */\nexport type WithHighseatConfig<Config> = Config & {\n rewrites: () => Promise<Rewrite[] | RewritePhases>\n}\n\nexport interface WithHighseatOptions {\n /**\n * The site's proxy path from Installation settings. Defaults to the `HIGHSEAT_PATH`\n * environment variable, the one `createProxy()` reads, so rotating the path is an\n * environment change and a redeploy.\n */\n path?: string\n /**\n * Where the app's proxy route handler lives. Defaults to `/api/highseat`, the route of\n * `app/api/highseat/route.ts`.\n */\n route?: string\n}\n\nconst DEFAULT_ROUTE = \"/api/highseat\"\n\n// A dev session can ask for the rewrites more than once, so the warning is printed once.\nlet hasWarnedNoPath = false\n\n/**\n * Adds a rewrite from the site's proxy path to the app's proxy route handler, ahead of every\n * other route. The rewrite stays inside the app, so the handler still sees the visitor's IP, and\n * the route file never moves when the path rotates.\n *\n * The proxy is optional. Without a path, `next dev` and `next build` warn once and leave the\n * rewrite out, and `<Highseat />` loads the tracker from Highseat's host. Nothing here throws,\n * so `next typegen` runs without the variable too. The build writes the rewrite, so a path set\n * only at runtime points a dynamically rendered `<Highseat />` at a route that is not there.\n *\n * ```ts\n * // next.config.ts\n * import { withHighseat } from \"highseat/next\"\n * export default withHighseat({ reactStrictMode: true })\n * ```\n */\nexport function withHighseat<Config extends object>(\n config: Config,\n options: WithHighseatOptions = {},\n): WithHighseatConfig<Config> {\n const path = findProxyPath(options.path)\n\n // Typed loosely so any Next.js version's config fits; only `rewrites` is read.\n const { rewrites: ownRewrites } = config as NextConfigWithRewrites\n\n async function passRewritesThrough(): Promise<Rewrite[] | RewritePhases> {\n if (!hasWarnedNoPath) {\n hasWarnedNoPath = true\n console.warn(\n \"highseat/next: no HIGHSEAT_PATH, so this build has no proxy rewrite and the tracker loads from Highseat's host. For first-party delivery, set it to the path from the site's Installation settings, or pass `path`, for the build as well as at runtime: a path set only at runtime points the tracker at a route this build does not have.\",\n )\n }\n return (await ownRewrites?.()) ?? []\n }\n\n if (!path) return { ...config, rewrites: passRewritesThrough }\n\n const rewrite = { source: path, destination: options.route ?? DEFAULT_ROUTE }\n\n async function rewrites(): Promise<RewritePhases> {\n const existing = (await ownRewrites?.()) ?? []\n\n // A plain array is Next.js shorthand for the `afterFiles` phase.\n if (Array.isArray(existing)) return { beforeFiles: [rewrite], afterFiles: existing }\n return { ...existing, beforeFiles: [rewrite, ...(existing.beforeFiles ?? [])] }\n }\n\n return { ...config, rewrites }\n}\n"],"mappings":";;;;;;;;;;;;;AAkBA,SAAgB,SAAS,OAA2C;CAClE,MAAM,OAAO,MAAM,QAAQ,aAAa;CACxC,MAAM,MAAM,MAAM,OAAO,cAAc;CAEvC,IAAI,CAAC,MAAM;EACT,QAAQ,KAAK,yEAAyE;EACtF,OAAO;CACT;CAEA,OAAO,cAAcA,YAAe;EAAE,GAAG;EAAO;EAAM;CAAI,CAAC;AAC7D;AAuCA,MAAM,gBAAgB;AAGtB,IAAI,kBAAkB;;;;;;;;;;;;;;;;;AAkBtB,SAAgB,aACd,QACA,UAA+B,CAAC,GACJ;CAC5B,MAAM,OAAO,cAAc,QAAQ,IAAI;CAGvC,MAAM,EAAE,UAAU,gBAAgB;CAElC,eAAe,sBAA0D;EACvE,IAAI,CAAC,iBAAiB;GACpB,kBAAkB;GAClB,QAAQ,KACN,6UACF;EACF;EACA,OAAQ,MAAM,cAAc,KAAM,CAAC;CACrC;CAEA,IAAI,CAAC,MAAM,OAAO;EAAE,GAAG;EAAQ,UAAU;CAAoB;CAE7D,MAAM,UAAU;EAAE,QAAQ;EAAM,aAAa,QAAQ,SAAS;CAAc;CAE5E,eAAe,WAAmC;EAChD,MAAM,WAAY,MAAM,cAAc,KAAM,CAAC;EAG7C,IAAI,MAAM,QAAQ,QAAQ,GAAG,OAAO;GAAE,aAAa,CAAC,OAAO;GAAG,YAAY;EAAS;EACnF,OAAO;GAAE,GAAG;GAAU,aAAa,CAAC,SAAS,GAAI,SAAS,eAAe,CAAC,CAAE;EAAE;CAChF;CAEA,OAAO;EAAE,GAAG;EAAQ;CAAS;AAC/B"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "highseat",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "Highseat analytics for JavaScript: typed tracking, a first-party proxy and framework components.",
5
5
  "keywords": [
6
6
  "analytics",
package/proxy.js CHANGED
@@ -1 +1,199 @@
1
- export { t as createProxy } from "./proxy2.js";
1
+ import { findProxyPath, findSecret, isNextBuild } from "./env.js";
2
+ //#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
+ const SCRIPT_REQUEST_HEADERS = ["user-agent", "if-none-match"];
16
+ const EVENT_REQUEST_HEADERS = [
17
+ "content-type",
18
+ "user-agent",
19
+ "origin"
20
+ ];
21
+ const RESPONSE_HEADERS = [
22
+ "content-type",
23
+ "etag",
24
+ "cache-control",
25
+ "vary",
26
+ "retry-after",
27
+ "x-hs-ip",
28
+ "x-hs-ip-source"
29
+ ];
30
+ const NULL_BODY_STATUSES = /* @__PURE__ */ new Set([
31
+ 101,
32
+ 204,
33
+ 205,
34
+ 304
35
+ ]);
36
+ const UPSTREAM_TIMEOUT_MS = 1e4;
37
+ 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
+ function copyHeaders(from, to, names) {
51
+ for (const name of names) {
52
+ const value = from.get(name);
53
+ if (value !== null) to.set(name, value);
54
+ }
55
+ }
56
+ function answerError(status, error) {
57
+ return Response.json({ error }, {
58
+ status,
59
+ headers: { "cache-control": "no-store" }
60
+ });
61
+ }
62
+ function answerOtherPath() {
63
+ return answerError(404, "Not the proxy path. The Highseat proxy answers on its own path only.");
64
+ }
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
+ let hasWarnedMissing = false;
73
+ /**
74
+ * The handler for a proxy missing a variable: every request goes to `fallback`, or the proxy
75
+ * path answers 503 naming what is missing.
76
+ */
77
+ function createDisabledProxy(missing, path, fallback) {
78
+ const names = missing.join(" and ");
79
+ if (!hasWarnedMissing && !isNextBuild()) {
80
+ hasWarnedMissing = true;
81
+ console.warn(`highseat/proxy: ${names} not set, so the proxy is off and ${fallback ? "every request goes to `fallback`" : "the proxy path answers 503"}.`);
82
+ }
83
+ return async function proxy(request) {
84
+ if (fallback) return fallback(request);
85
+ if (path !== void 0 && new URL(request.url).pathname !== path) return answerOtherPath();
86
+ return answerError(503, `The Highseat proxy is off: set ${names}.`);
87
+ };
88
+ }
89
+ /** The request body, or `undefined` once it passes `MAX_EVENT_BYTES`. */
90
+ async function readEventBody(request) {
91
+ if (Number(request.headers.get("content-length")) > MAX_EVENT_BYTES) return;
92
+ if (!request.body) return /* @__PURE__ */ new Uint8Array();
93
+ const reader = request.body.getReader();
94
+ const chunks = [];
95
+ let size = 0;
96
+ for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) {
97
+ size += chunk.value.byteLength;
98
+ if (size > MAX_EVENT_BYTES) {
99
+ reader.cancel();
100
+ return;
101
+ }
102
+ chunks.push(chunk.value);
103
+ }
104
+ const body = new Uint8Array(size);
105
+ let offset = 0;
106
+ for (const chunk of chunks) {
107
+ body.set(chunk, offset);
108
+ offset += chunk.byteLength;
109
+ }
110
+ return body;
111
+ }
112
+ /**
113
+ * Creates the first-party proxy handler for a site. A GET serves the tracker script and a POST
114
+ * forwards its events, both to the ingest host, with the site secret and the visitor's IP. The
115
+ * returned function takes a `Request` and returns a `Response`, so it mounts as a Next.js route
116
+ * handler, a Cloudflare Worker, a Pages Function, a Netlify or Vercel function, an Astro
117
+ * endpoint or a Hono route.
118
+ *
119
+ * A missing path or secret never throws: the handler passes every request to `fallback`, or
120
+ * answers the proxy path with a 503 naming the variable, and warns once. A value that is not a
121
+ * site secret throws, since that is a copying mistake rather than a variable left unset.
122
+ */
123
+ function createProxy(options) {
124
+ const path = findProxyPath(options.path);
125
+ const { fallback } = options;
126
+ let foundSecret;
127
+ try {
128
+ foundSecret = findValidSecret(options.secret);
129
+ } catch (error) {
130
+ if (!isNextBuild()) throw error;
131
+ return () => Promise.reject(error);
132
+ }
133
+ const upstream = new URL(options.upstream ?? DEFAULT_UPSTREAM).origin;
134
+ const missing = [...fallback && path === void 0 ? ["HIGHSEAT_PATH"] : [], ...foundSecret ? [] : ["HIGHSEAT_SECRET"]];
135
+ if (!foundSecret || missing.length) return createDisabledProxy(missing, path, fallback);
136
+ const secret = foundSecret;
137
+ const clientIpReader = getClientIpReader(options.clientIp);
138
+ let hasWarnedNoIp = false;
139
+ function readClientIp(request) {
140
+ const ip = clientIpReader.read(request);
141
+ if (!ip && !hasWarnedNoIp) {
142
+ hasWarnedNoIp = true;
143
+ console.warn(`highseat/proxy: no visitor IP in ${clientIpReader.source}, so Highseat refuses every event. Set clientIp to the outermost proxy in front of this server.`);
144
+ }
145
+ return ip;
146
+ }
147
+ function buildUpstreamHeaders(request, names) {
148
+ const headers = new Headers({
149
+ "accept-encoding": "identity",
150
+ "x-hs-secret": secret,
151
+ "x-hs-client-ip": readClientIp(request)
152
+ });
153
+ copyHeaders(request.headers, headers, names);
154
+ return headers;
155
+ }
156
+ async function forward(url, init) {
157
+ let response;
158
+ try {
159
+ response = await fetch(url, {
160
+ ...init,
161
+ signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS)
162
+ });
163
+ } catch {
164
+ return answerError(502, "Highseat is unreachable from this proxy.");
165
+ }
166
+ const headers = new Headers();
167
+ copyHeaders(response.headers, headers, RESPONSE_HEADERS);
168
+ if (init.method === "POST") headers.set("cache-control", "no-store");
169
+ const body = NULL_BODY_STATUSES.has(response.status) ? null : response.body;
170
+ return new Response(body, {
171
+ status: response.status,
172
+ headers
173
+ });
174
+ }
175
+ return async function proxy(request) {
176
+ if (path !== void 0 && new URL(request.url).pathname !== path) return fallback ? fallback(request) : answerOtherPath();
177
+ if (request.method === "GET" || request.method === "HEAD") return forward(`${upstream}/script.js`, {
178
+ method: request.method,
179
+ headers: buildUpstreamHeaders(request, SCRIPT_REQUEST_HEADERS)
180
+ });
181
+ if (request.method === "POST") {
182
+ const body = await readEventBody(request);
183
+ if (!body) return answerError(413, "The event batch is too large.");
184
+ return forward(`${upstream}/api/event`, {
185
+ method: "POST",
186
+ headers: buildUpstreamHeaders(request, EVENT_REQUEST_HEADERS),
187
+ body
188
+ });
189
+ }
190
+ return new Response(null, {
191
+ status: 405,
192
+ headers: { allow: "GET, HEAD, POST" }
193
+ });
194
+ };
195
+ }
196
+ //#endregion
197
+ export { createProxy };
198
+
199
+ //# sourceMappingURL=proxy.js.map
package/proxy.js.map ADDED
@@ -0,0 +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,GAAG;CAC7F,OAAO;EACL,OAAM,YAAW,QAAQ,QAAQ,IAAI,MAAM,CAAC,EAAE,KAAK,KAAK;EACxD,QAAQ,QAAQ,SAAS,aAAa,OAAO;CAC/C;AACF;AAEA,SAAS,YAAY,MAAe,IAAa,OAAiB;CAChE,KAAK,MAAM,QAAQ,OAAO;EACxB,MAAM,QAAQ,KAAK,IAAI,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ts
3
- export interface HighseatProps extends InjectOptions {}
3
+ export interface HighseatProps extends InjectOptions {
4
+ /**
5
+ * The signed-in user's id from your own system, never an email or other personal data. Pass
6
+ * `null` once the visitor is signed out, and `undefined` while the session is still loading.
7
+ * See {@link useIdentify}.
8
+ */
9
+ userId?: UserId;
10
+ }
11
+ /**
12
+ * Keeps the visitor's user id in step with a session. Each new value is passed to `identify`
13
+ * once: an id identifies the visitor, `null` clears the id at sign-out or session expiry, and
14
+ * `undefined`, a session still loading, changes nothing. Works in any client component, with or
15
+ * without `<Highseat />` on the page, and before the tracker has loaded.
16
+ *
17
+ * Tell loading apart from signed out: `useIdentify(session?.user.id)` passes `undefined` after
18
+ * sign-out too, so it never clears the id.
19
+ *
20
+ * ```tsx
21
+ * const { data, isPending } = useSession()
22
+ * useIdentify(isPending ? undefined : (data?.user.id ?? null))
23
+ * ```
24
+ */
25
+ export declare function useIdentify(userId: UserId): void;
4
26
  /**
5
27
  * Loads the Highseat tracker. Render it once, in the root layout. It adds the script tag after
6
28
  * the page mounts and renders nothing; mounting it again adds no second tag, and the tracker
7
- * counts client-side navigation on its own.
29
+ * counts client-side navigation on its own. With `userId`, it also identifies the visitor, as
30
+ * {@link useIdentify} does.
8
31
  */
9
- export declare function Highseat({ site, src, outbound, downloads, hashRouting }: HighseatProps): null;
32
+ export declare function Highseat({ site, src, outbound, downloads, hashRouting, debug, userId }: HighseatProps): null;
10
33
  //#endregion
11
34
  //# sourceMappingURL=react.d.ts.map
package/react.js CHANGED
@@ -1,31 +1,56 @@
1
1
  "use client";
2
2
  import { inject } from "./index.js";
3
- import { useEffect } from "react";
3
+ import { syncIdentity } from "./identity.js";
4
+ import { useEffect, useRef } from "react";
4
5
  //#region src/react.ts
5
6
  /**
7
+ * Keeps the visitor's user id in step with a session. Each new value is passed to `identify`
8
+ * once: an id identifies the visitor, `null` clears the id at sign-out or session expiry, and
9
+ * `undefined`, a session still loading, changes nothing. Works in any client component, with or
10
+ * without `<Highseat />` on the page, and before the tracker has loaded.
11
+ *
12
+ * Tell loading apart from signed out: `useIdentify(session?.user.id)` passes `undefined` after
13
+ * sign-out too, so it never clears the id.
14
+ *
15
+ * ```tsx
16
+ * const { data, isPending } = useSession()
17
+ * useIdentify(isPending ? undefined : (data?.user.id ?? null))
18
+ * ```
19
+ */
20
+ function useIdentify(userId) {
21
+ const identified = useRef(void 0);
22
+ useEffect(() => {
23
+ identified.current = syncIdentity(identified.current, userId);
24
+ }, [userId]);
25
+ }
26
+ /**
6
27
  * Loads the Highseat tracker. Render it once, in the root layout. It adds the script tag after
7
28
  * the page mounts and renders nothing; mounting it again adds no second tag, and the tracker
8
- * counts client-side navigation on its own.
29
+ * counts client-side navigation on its own. With `userId`, it also identifies the visitor, as
30
+ * {@link useIdentify} does.
9
31
  */
10
- function Highseat({ site, src, outbound, downloads, hashRouting }) {
32
+ function Highseat({ site, src, outbound, downloads, hashRouting, debug, userId }) {
11
33
  useEffect(() => {
12
34
  inject({
13
35
  site,
14
36
  src,
15
37
  outbound,
16
38
  downloads,
17
- hashRouting
39
+ hashRouting,
40
+ debug
18
41
  });
19
42
  }, [
20
43
  site,
21
44
  src,
22
45
  outbound,
23
46
  downloads,
24
- hashRouting
47
+ hashRouting,
48
+ debug
25
49
  ]);
50
+ useIdentify(userId);
26
51
  return null;
27
52
  }
28
53
  //#endregion
29
- export { Highseat };
54
+ export { Highseat, useIdentify };
30
55
 
31
56
  //# 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 } from \"react\"\nimport { inject, type InjectOptions } from \"./index\"\n\nexport interface HighseatProps extends InjectOptions {}\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.\n */\nexport function Highseat({ site, src, outbound, downloads, hashRouting }: HighseatProps): null {\n useEffect(() => {\n inject({ site, src, outbound, downloads, hashRouting })\n }, [site, src, outbound, downloads, hashRouting])\n\n return null\n}\n"],"mappings":";;;;;;;;;AAYA,SAAgB,SAAS,EAAE,MAAM,KAAK,UAAU,WAAW,eAAoC;CAC7F,gBAAgB;EACd,OAAO;GAAE;GAAM;GAAK;GAAU;GAAW;EAAY,CAAC;CACxD,GAAG;EAAC;EAAM;EAAK;EAAU;EAAW;CAAW,CAAC;CAEhD,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, 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"}
package/proxy2.js DELETED
@@ -1,235 +0,0 @@
1
- //#region src/env.ts
2
- /**
3
- * The variables the package reads from a customer's environment. Each is named in full, never
4
- * looked up by a computed key: Next.js inlines a `NEXT_PUBLIC_` variable into browser code only
5
- * where the source spells out `process.env.NEXT_PUBLIC_…`. The server variables return
6
- * `undefined` where the runtime has no `process`: a Cloudflare Worker without `nodejs_compat`,
7
- * whose options carry the values instead.
8
- */
9
- /** The site id for `<Highseat />` in Next.js. Public, so it reaches the browser. */
10
- function findNextSite() {
11
- return process.env.NEXT_PUBLIC_HIGHSEAT_SITE;
12
- }
13
- /**
14
- * The site's proxy path: `option` when given, else `HIGHSEAT_PATH`, a server variable shared by
15
- * `<Highseat />`, `withHighseat()` and the proxy handler. A value written without its leading
16
- * slash gets one, as Installation settings shows it (`/3f9a0c1e2b`). An empty value counts as
17
- * unset.
18
- */
19
- function findProxyPath(option) {
20
- const path = option ?? (typeof process === "undefined" ? void 0 : process.env.HIGHSEAT_PATH);
21
- if (!path) return;
22
- return path.startsWith("/") ? path : `/${path}`;
23
- }
24
- /** The site secret for the proxy handler. */
25
- function findSecret() {
26
- if (typeof process === "undefined") return;
27
- return process.env.HIGHSEAT_SECRET;
28
- }
29
- /**
30
- * Whether this runs inside `next build`, which loads every route without serving one. Set in the
31
- * build's route workers only: `next.config.ts` receives the phase as an argument instead.
32
- */
33
- function isNextBuild() {
34
- if (typeof process === "undefined") return false;
35
- return process.env.NEXT_PHASE === "phase-production-build";
36
- }
37
- //#endregion
38
- //#region src/proxy.ts
39
- const DEFAULT_UPSTREAM = "https://cdn.highseat.com";
40
- const SECRET_PREFIXES = [
41
- "hs_secret_",
42
- "hs_proxy_",
43
- "ana_proxy_"
44
- ];
45
- const CLIENT_IP_HEADERS = {
46
- vercel: "x-real-ip",
47
- cloudflare: "cf-connecting-ip",
48
- netlify: "x-nf-client-connection-ip",
49
- nginx: "x-real-ip"
50
- };
51
- const SCRIPT_REQUEST_HEADERS = ["user-agent", "if-none-match"];
52
- const EVENT_REQUEST_HEADERS = [
53
- "content-type",
54
- "user-agent",
55
- "origin"
56
- ];
57
- const RESPONSE_HEADERS = [
58
- "content-type",
59
- "etag",
60
- "cache-control",
61
- "vary",
62
- "retry-after",
63
- "x-hs-ip",
64
- "x-hs-ip-source"
65
- ];
66
- const NULL_BODY_STATUSES = /* @__PURE__ */ new Set([
67
- 101,
68
- 204,
69
- 205,
70
- 304
71
- ]);
72
- const UPSTREAM_TIMEOUT_MS = 1e4;
73
- const MAX_EVENT_BYTES = 524288;
74
- function getClientIpReader(clientIp) {
75
- if (typeof clientIp === "function") return {
76
- read: (request) => clientIp(request)?.trim() ?? "",
77
- source: "the clientIp function"
78
- };
79
- const header = CLIENT_IP_HEADERS[clientIp];
80
- if (!header) throw new Error(`highseat/proxy: unknown clientIp preset "${String(clientIp)}".`);
81
- return {
82
- read: (request) => request.headers.get(header)?.trim() ?? "",
83
- source: `the "${clientIp}" preset's ${header} header`
84
- };
85
- }
86
- function copyHeaders(from, to, names) {
87
- for (const name of names) {
88
- const value = from.get(name);
89
- if (value !== null) to.set(name, value);
90
- }
91
- }
92
- function answerError(status, error) {
93
- return Response.json({ error }, {
94
- status,
95
- headers: { "cache-control": "no-store" }
96
- });
97
- }
98
- function answerOtherPath() {
99
- return answerError(404, "Not the proxy path. The Highseat proxy answers on its own path only.");
100
- }
101
- /** The site secret, or `undefined` when none is set. Throws on a value that is not one. */
102
- function findValidSecret(option) {
103
- const secret = option ?? findSecret();
104
- if (!secret) return;
105
- 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]}".`);
106
- return secret;
107
- }
108
- let hasWarnedMissing = false;
109
- /**
110
- * The handler for a proxy missing a variable: every request goes to `fallback`, or the proxy
111
- * path answers 503 naming what is missing.
112
- */
113
- function createDisabledProxy(missing, path, fallback) {
114
- const names = missing.join(" and ");
115
- if (!hasWarnedMissing && !isNextBuild()) {
116
- hasWarnedMissing = true;
117
- console.warn(`highseat/proxy: ${names} not set, so the proxy is off and ${fallback ? "every request goes to `fallback`" : "the proxy path answers 503"}.`);
118
- }
119
- return async function proxy(request) {
120
- if (fallback) return fallback(request);
121
- if (path !== void 0 && new URL(request.url).pathname !== path) return answerOtherPath();
122
- return answerError(503, `The Highseat proxy is off: set ${names}.`);
123
- };
124
- }
125
- /** The request body, or `undefined` once it passes `MAX_EVENT_BYTES`. */
126
- async function readEventBody(request) {
127
- if (Number(request.headers.get("content-length")) > MAX_EVENT_BYTES) return;
128
- if (!request.body) return /* @__PURE__ */ new Uint8Array();
129
- const reader = request.body.getReader();
130
- const chunks = [];
131
- let size = 0;
132
- for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) {
133
- size += chunk.value.byteLength;
134
- if (size > MAX_EVENT_BYTES) {
135
- reader.cancel();
136
- return;
137
- }
138
- chunks.push(chunk.value);
139
- }
140
- const body = new Uint8Array(size);
141
- let offset = 0;
142
- for (const chunk of chunks) {
143
- body.set(chunk, offset);
144
- offset += chunk.byteLength;
145
- }
146
- return body;
147
- }
148
- /**
149
- * Creates the first-party proxy handler for a site. A GET serves the tracker script and a POST
150
- * forwards its events, both to the ingest host, with the site secret and the visitor's IP. The
151
- * returned function takes a `Request` and returns a `Response`, so it mounts as a Next.js route
152
- * handler, a Cloudflare Worker, a Pages Function, a Netlify or Vercel function, an Astro
153
- * endpoint or a Hono route.
154
- *
155
- * A missing path or secret never throws: the handler passes every request to `fallback`, or
156
- * answers the proxy path with a 503 naming the variable, and warns once. A value that is not a
157
- * site secret throws, since that is a copying mistake rather than a variable left unset.
158
- */
159
- function createProxy(options) {
160
- const path = findProxyPath(options.path);
161
- const { fallback } = options;
162
- let foundSecret;
163
- try {
164
- foundSecret = findValidSecret(options.secret);
165
- } catch (error) {
166
- if (!isNextBuild()) throw error;
167
- return () => Promise.reject(error);
168
- }
169
- const upstream = new URL(options.upstream ?? DEFAULT_UPSTREAM).origin;
170
- const missing = [...fallback && path === void 0 ? ["HIGHSEAT_PATH"] : [], ...foundSecret ? [] : ["HIGHSEAT_SECRET"]];
171
- if (!foundSecret || missing.length) return createDisabledProxy(missing, path, fallback);
172
- const secret = foundSecret;
173
- const clientIpReader = getClientIpReader(options.clientIp);
174
- let hasWarnedNoIp = false;
175
- function readClientIp(request) {
176
- const ip = clientIpReader.read(request);
177
- if (!ip && !hasWarnedNoIp) {
178
- hasWarnedNoIp = true;
179
- console.warn(`highseat/proxy: no visitor IP in ${clientIpReader.source}, so Highseat refuses every event. Set clientIp to the outermost proxy in front of this server.`);
180
- }
181
- return ip;
182
- }
183
- function buildUpstreamHeaders(request, names) {
184
- const headers = new Headers({
185
- "accept-encoding": "identity",
186
- "x-hs-secret": secret,
187
- "x-hs-client-ip": readClientIp(request)
188
- });
189
- copyHeaders(request.headers, headers, names);
190
- return headers;
191
- }
192
- async function forward(url, init) {
193
- let response;
194
- try {
195
- response = await fetch(url, {
196
- ...init,
197
- signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS)
198
- });
199
- } catch {
200
- return answerError(502, "Highseat is unreachable from this proxy.");
201
- }
202
- const headers = new Headers();
203
- copyHeaders(response.headers, headers, RESPONSE_HEADERS);
204
- if (init.method === "POST") headers.set("cache-control", "no-store");
205
- const body = NULL_BODY_STATUSES.has(response.status) ? null : response.body;
206
- return new Response(body, {
207
- status: response.status,
208
- headers
209
- });
210
- }
211
- return async function proxy(request) {
212
- if (path !== void 0 && new URL(request.url).pathname !== path) return fallback ? fallback(request) : answerOtherPath();
213
- if (request.method === "GET" || request.method === "HEAD") return forward(`${upstream}/script.js`, {
214
- method: request.method,
215
- headers: buildUpstreamHeaders(request, SCRIPT_REQUEST_HEADERS)
216
- });
217
- if (request.method === "POST") {
218
- const body = await readEventBody(request);
219
- if (!body) return answerError(413, "The event batch is too large.");
220
- return forward(`${upstream}/api/event`, {
221
- method: "POST",
222
- headers: buildUpstreamHeaders(request, EVENT_REQUEST_HEADERS),
223
- body
224
- });
225
- }
226
- return new Response(null, {
227
- status: 405,
228
- headers: { allow: "GET, HEAD, POST" }
229
- });
230
- };
231
- }
232
- //#endregion
233
- export { findNextSite as n, findProxyPath as r, createProxy as t };
234
-
235
- //# sourceMappingURL=proxy2.js.map
package/proxy2.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"proxy2.js","names":[],"sources":["../src/env.ts","../src/proxy.ts"],"sourcesContent":["/**\n * The variables the package reads from a customer's environment. Each is named in full, never\n * looked up by a computed key: Next.js inlines a `NEXT_PUBLIC_` variable into browser code only\n * where the source spells out `process.env.NEXT_PUBLIC_…`. The server variables return\n * `undefined` where the runtime has no `process`: a Cloudflare Worker without `nodejs_compat`,\n * whose options carry the values instead.\n */\n\n/** The site id for `<Highseat />` in Next.js. Public, so it reaches the browser. */\nexport function findNextSite(): string | undefined {\n return process.env.NEXT_PUBLIC_HIGHSEAT_SITE\n}\n\n/**\n * The site's proxy path: `option` when given, else `HIGHSEAT_PATH`, a server variable shared by\n * `<Highseat />`, `withHighseat()` and the proxy handler. A value written without its leading\n * slash gets one, as Installation settings shows it (`/3f9a0c1e2b`). An empty value counts as\n * unset.\n */\nexport function findProxyPath(option?: string): string | undefined {\n const path = option ?? (typeof process === \"undefined\" ? undefined : process.env.HIGHSEAT_PATH)\n if (!path) return\n return path.startsWith(\"/\") ? path : `/${path}`\n}\n\n/** The site secret for the proxy handler. */\nexport function findSecret(): string | undefined {\n if (typeof process === \"undefined\") return\n return process.env.HIGHSEAT_SECRET\n}\n\n/**\n * Whether this runs inside `next build`, which loads every route without serving one. Set in the\n * build's route workers only: `next.config.ts` receives the phase as an argument instead.\n */\nexport function isNextBuild(): boolean {\n if (typeof process === \"undefined\") return false\n return process.env.NEXT_PHASE === \"phase-production-build\"\n}\n","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":";;;;;;;;;AASA,SAAgB,eAAmC;CACjD,OAAO,QAAQ,IAAI;AACrB;;;;;;;AAQA,SAAgB,cAAc,QAAqC;CACjE,MAAM,OAAO,WAAW,OAAO,YAAY,cAAc,KAAA,IAAY,QAAQ,IAAI;CACjF,IAAI,CAAC,MAAM;CACX,OAAO,KAAK,WAAW,GAAG,IAAI,OAAO,IAAI;AAC3C;;AAGA,SAAgB,aAAiC;CAC/C,IAAI,OAAO,YAAY,aAAa;CACpC,OAAO,QAAQ,IAAI;AACrB;;;;;AAMA,SAAgB,cAAuB;CACrC,IAAI,OAAO,YAAY,aAAa,OAAO;CAC3C,OAAO,QAAQ,IAAI,eAAe;AACpC;;;ACaA,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,O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