zeno.id 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/dist/index.cjs CHANGED
@@ -1,7 +1,7 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const IDENTIFY_TIMEOUT = 1e4;
3
3
  //#endregion
4
- //#region src/error.ts
4
+ //#region src/browser/error.ts
5
5
  const messages = {
6
6
  client_timeout: "Client timeout",
7
7
  network_connection: "Network connection error",
@@ -28,41 +28,41 @@ var ZenoError = class extends Error {
28
28
  const toZenoError = (error) => {
29
29
  if (error instanceof ZenoError) return error;
30
30
  const { name, code, message } = typeof error === "object" && error !== null ? error : {};
31
- const text = typeof message === "string" ? message : void 0;
32
- return name === "ZenoError" && typeof code === "string" && code in messages ? new ZenoError(code, text) : new ZenoError("collection_failed", text);
31
+ const messageText = typeof message === "string" ? message : void 0;
32
+ return name === "ZenoError" && typeof code === "string" && code in messages ? new ZenoError(code, messageText) : new ZenoError("collection_failed", messageText);
33
33
  };
34
34
  //#endregion
35
- //#region src/csp.ts
35
+ //#region src/browser/csp.ts
36
36
  const watchCsp = (origin) => {
37
- let blocked = false;
37
+ let isBlocked = false;
38
38
  const listener = (event) => {
39
- if (event.blockedURI.startsWith(origin)) blocked = true;
39
+ if (event.blockedURI.startsWith(origin)) isBlocked = true;
40
40
  };
41
41
  globalThis.document?.addEventListener("securitypolicyviolation", listener);
42
42
  return {
43
- failure: async (otherwise, blockedMessage) => {
43
+ errorFor: async (fallback, blockedMessage) => {
44
44
  await new Promise((resolve) => setTimeout(resolve, 0));
45
- return blocked ? new ZenoError("csp_block", blockedMessage) : otherwise;
45
+ return isBlocked ? new ZenoError("csp_block", blockedMessage) : fallback;
46
46
  },
47
47
  stop: () => globalThis.document?.removeEventListener("securitypolicyviolation", listener)
48
48
  };
49
49
  };
50
50
  //#endregion
51
- //#region src/import.ts
51
+ //#region src/browser/import.ts
52
52
  const importModule = (url) => import(
53
53
  /* @vite-ignore */
54
54
  /* webpackIgnore: true */
55
55
  url
56
56
  );
57
57
  //#endregion
58
- //#region src/options.ts
59
- const invalid = (message) => new ZenoError("invalid_options", message);
58
+ //#region src/browser/options.ts
59
+ const invalidOptions = (message) => new ZenoError("invalid_options", message);
60
60
  const resolveEndpoint = (value) => {
61
61
  if (typeof value !== "string" || !/^\/(?![/\\])[^?#\\]*$/.test(value)) return;
62
62
  try {
63
- const page = new URL(globalThis.location.href);
64
- const url = new URL(value, page);
65
- return url.origin === page.origin ? `${url.origin}${url.pathname}` : void 0;
63
+ const pageUrl = new URL(globalThis.location.href);
64
+ const url = new URL(value, pageUrl);
65
+ return url.origin === pageUrl.origin ? `${url.origin}${url.pathname}` : void 0;
66
66
  } catch {
67
67
  return;
68
68
  }
@@ -70,20 +70,20 @@ const resolveEndpoint = (value) => {
70
70
  const toChallengeToken = (value) => typeof value === "string" && value.length > 0 && value.length <= 200 ? value : void 0;
71
71
  const checkProxyEndpoint = (path, call = "start") => {
72
72
  const url = resolveEndpoint(path ?? "/zeno");
73
- if (!url) throw invalid(`${call}() takes your proxy route's path on this site, like ${call}('/zeno')`);
73
+ if (!url) throw invalidOptions(`${call}() takes your proxy route's path on this site, like ${call}('/zeno')`);
74
74
  return url;
75
75
  };
76
76
  const checkIdentifyOptions = (options) => {
77
- if (typeof options !== "object" || options === null) throw invalid("Pass the identify() options as an object: identify({ externalId, action })");
77
+ if (typeof options !== "object" || options === null) throw invalidOptions("Pass the identify() options as an object: identify({ externalId, action })");
78
78
  const { externalId, action, metadata } = options;
79
- if (externalId !== void 0 && (typeof externalId !== "string" || !externalId || externalId.length > 256)) throw invalid("externalId must be a string of 1 to 256 characters");
80
- if (externalId === "." || externalId === "..") throw invalid("externalId can’t be . or ..");
81
- if (action !== void 0 && (typeof action !== "string" || action.length > 1024)) throw invalid("action must be a string of at most 1,024 characters");
82
- if (metadata !== void 0 && (typeof metadata !== "object" || metadata === null || Array.isArray(metadata))) throw invalid("metadata must be an object of keys and values, like { orderId: 'A-1042' }");
79
+ if (externalId !== void 0 && (typeof externalId !== "string" || !externalId || externalId.length > 256)) throw invalidOptions("externalId must be a string of 1 to 256 characters");
80
+ if (externalId === "." || externalId === "..") throw invalidOptions("externalId can’t be . or ..");
81
+ if (action !== void 0 && (typeof action !== "string" || action.length > 1024)) throw invalidOptions("action must be a string of at most 1,024 characters");
82
+ if (metadata !== void 0 && (typeof metadata !== "object" || metadata === null || Array.isArray(metadata))) throw invalidOptions("metadata must be an object of keys and values, like { orderId: 'A-1042' }");
83
83
  };
84
84
  //#endregion
85
- //#region src/storage.ts
86
- const forgetStored = (endpoint) => {
85
+ //#region src/browser/storage.ts
86
+ const clearVisitorCookie = (endpoint) => {
87
87
  return fetch(`${endpoint}?forget`, {
88
88
  method: "POST",
89
89
  credentials: "same-origin",
@@ -91,51 +91,51 @@ const forgetStored = (endpoint) => {
91
91
  });
92
92
  };
93
93
  //#endregion
94
- //#region src/forget.ts
94
+ //#region src/browser/forget.ts
95
95
  /**
96
- * Has the route clear its visitor cookie, without loading or starting anything: for a visitor who withdraws consent, or
97
- * withdrew it on an earlier visit, on a page that never called `start()`. `stop()` on a started one does the same and
98
- * stops it. Resolves once the route cleared the cookie; on the server it rejects with `not_in_browser`.
96
+ * Has the route clear its visitor cookie without loading or starting anything, for a visitor who withdraws consent on a
97
+ * page that never called `start()` (`stop()` on a started one does the same and stops it). Resolves once the route
98
+ * cleared the cookie; on the server it rejects with `not_in_browser`.
99
99
  *
100
100
  * @param path The same path on this site you pass to `start()`, `/zeno` by default.
101
101
  */
102
102
  const forget = async (path) => {
103
103
  if (typeof document === "undefined") throw new ZenoError("not_in_browser");
104
104
  const endpoint = checkProxyEndpoint(path, "forget");
105
- const csp = watchCsp(new URL(endpoint).origin);
105
+ const cspWatcher = watchCsp(new URL(endpoint).origin);
106
106
  let response;
107
107
  try {
108
- response = await forgetStored(endpoint);
108
+ response = await clearVisitorCookie(endpoint);
109
109
  } catch {
110
- throw await csp.failure(new ZenoError("network_connection"));
110
+ throw await cspWatcher.errorFor(new ZenoError("network_connection"));
111
111
  } finally {
112
- csp.stop();
112
+ cspWatcher.stop();
113
113
  }
114
114
  if (!response.ok) throw new ZenoError("server_error", `The route answered ${response.status} when asked to clear its cookie`);
115
115
  };
116
116
  //#endregion
117
- //#region src/index.ts
118
- const withTimeout = (promise, ms, error) => {
117
+ //#region src/browser/index.ts
118
+ const withTimeout = (promise, ms, makeError) => {
119
119
  let timer;
120
120
  return Promise.race([promise, new Promise((_, reject) => {
121
- timer = setTimeout(() => reject(error()), ms);
121
+ timer = setTimeout(() => reject(makeError()), ms);
122
122
  })]).finally(() => clearTimeout(timer));
123
123
  };
124
- const failed = (error) => ({
124
+ const toFailedIdentification = (error) => ({
125
125
  requestId: void 0,
126
126
  error: toZenoError(error)
127
127
  });
128
- const ownAnswer = (identification) => {
128
+ const withOwnError = (identification) => {
129
129
  return identification.error ? {
130
130
  ...identification,
131
131
  error: toZenoError(identification.error)
132
132
  } : identification;
133
133
  };
134
- const onServer = () => ({
135
- identify: () => Promise.resolve(failed(new ZenoError("not_in_browser"))),
134
+ const makeServerStub = () => ({
135
+ identify: () => Promise.resolve(toFailedIdentification(new ZenoError("not_in_browser"))),
136
136
  stop() {}
137
137
  });
138
- const refreshChallengeToken = (endpoint) => async () => {
138
+ const makeChallengeTokenRefresh = (endpoint) => async () => {
139
139
  try {
140
140
  const module = await importModule(`${endpoint}?challenge=${Date.now()}`);
141
141
  return toChallengeToken(module?.challengeToken);
@@ -143,7 +143,7 @@ const refreshChallengeToken = (endpoint) => async () => {
143
143
  return;
144
144
  }
145
145
  };
146
- const loadFailure = async (endpoint) => {
146
+ const explainLoadFailure = async (endpoint) => {
147
147
  const fallback = new ZenoError("script_load_failed", `The script couldn't be loaded from ${endpoint}: check that your proxy route answers there`);
148
148
  try {
149
149
  const response = await fetch(endpoint, { credentials: "same-origin" });
@@ -160,25 +160,25 @@ const loadFailure = async (endpoint) => {
160
160
  return fallback;
161
161
  }
162
162
  };
163
- const loadAgent = async (endpoint, stopped, started) => {
164
- const csp = watchCsp(new URL(endpoint).origin);
163
+ const loadAgent = async (endpoint, isStopped, onStarted) => {
164
+ const cspWatcher = watchCsp(new URL(endpoint).origin);
165
165
  let module;
166
166
  try {
167
167
  module = await importModule(endpoint);
168
168
  } catch {
169
- const blocked = await csp.failure(new ZenoError("script_load_failed"), `The page's Content Security Policy blocked loading the script from ${endpoint}: allow it in script-src`);
170
- throw blocked.code === "csp_block" ? blocked : await loadFailure(endpoint);
169
+ const importError = await cspWatcher.errorFor(new ZenoError("script_load_failed"), `The page's Content Security Policy blocked loading the script from ${endpoint}: allow it in script-src`);
170
+ throw importError.code === "csp_block" ? importError : await explainLoadFailure(endpoint);
171
171
  } finally {
172
- csp.stop();
172
+ cspWatcher.stop();
173
173
  }
174
- if (stopped()) throw new ZenoError("stopped");
174
+ if (isStopped()) throw new ZenoError("stopped");
175
175
  if (typeof module?.start !== "function") throw new ZenoError("script_load_failed", `${endpoint} didn't answer with the script; check the endpoint`);
176
176
  try {
177
177
  const agent = module.start(new URL(endpoint).pathname, {
178
178
  challengeToken: toChallengeToken(module.challengeToken),
179
- refreshChallengeToken: refreshChallengeToken(endpoint)
179
+ refreshChallengeToken: makeChallengeTokenRefresh(endpoint)
180
180
  });
181
- started(agent);
181
+ onStarted(agent);
182
182
  return agent;
183
183
  } catch (error) {
184
184
  throw toZenoError(error);
@@ -191,39 +191,39 @@ const loadAgent = async (endpoint, stopped, started) => {
191
191
  * fragment. The script loads from it and identifies through it.
192
192
  */
193
193
  const start = (path) => {
194
- if (typeof document === "undefined") return onServer();
194
+ if (typeof document === "undefined") return makeServerStub();
195
195
  const endpoint = checkProxyEndpoint(path);
196
- let stopped = false;
197
- let running;
198
- let rejectStopped = () => {};
199
- const stopping = new Promise((_, reject) => {
200
- rejectStopped = reject;
196
+ let isStopped = false;
197
+ let runningAgent;
198
+ let rejectOnStop = () => {};
199
+ const stopSignal = new Promise((_, reject) => {
200
+ rejectOnStop = reject;
201
201
  });
202
- stopping.catch(() => {});
203
- const loaded = loadAgent(endpoint, () => stopped, (agent) => running = agent);
204
- loaded.catch(() => {});
202
+ stopSignal.catch(() => {});
203
+ const agentLoading = loadAgent(endpoint, () => isStopped, (agent) => runningAgent = agent);
204
+ agentLoading.catch(() => {});
205
205
  const identify = async (identifyOptions) => {
206
- if (stopped) throw new ZenoError("stopped");
206
+ if (isStopped) throw new ZenoError("stopped");
207
207
  checkIdentifyOptions(identifyOptions);
208
208
  const timeout = IDENTIFY_TIMEOUT;
209
- const started = performance.now();
210
- const agent = await withTimeout(Promise.race([loaded, stopping]), timeout, () => new ZenoError("client_timeout"));
211
- const left = Math.max(1, timeout - (performance.now() - started));
212
- if (stopped) throw new ZenoError("stopped");
213
- return ownAnswer(await agent.identify({
209
+ const startedAt = performance.now();
210
+ const agent = await withTimeout(Promise.race([agentLoading, stopSignal]), timeout, () => new ZenoError("client_timeout"));
211
+ const timeLeft = Math.max(1, timeout - (performance.now() - startedAt));
212
+ if (isStopped) throw new ZenoError("stopped");
213
+ return withOwnError(await agent.identify({
214
214
  ...identifyOptions,
215
- timeout: left
215
+ timeout: timeLeft
216
216
  }));
217
217
  };
218
218
  return {
219
- identify: (identifyOptions = {}) => identify(identifyOptions).catch(failed),
219
+ identify: (identifyOptions = {}) => identify(identifyOptions).catch(toFailedIdentification),
220
220
  stop() {
221
- if (!stopped) {
222
- stopped = true;
223
- rejectStopped(new ZenoError("stopped"));
221
+ if (!isStopped) {
222
+ isStopped = true;
223
+ rejectOnStop(new ZenoError("stopped"));
224
224
  }
225
- if (running) running.stop();
226
- else forgetStored(endpoint).catch(() => {});
225
+ if (runningAgent) runningAgent.stop();
226
+ else clearVisitorCookie(endpoint).catch(() => {});
227
227
  }
228
228
  };
229
229
  };
package/dist/index.d.cts CHANGED
@@ -1,11 +1,11 @@
1
- //#region src/error.d.ts
1
+ //#region src/browser/error.d.ts
2
2
  type ZenoErrorCode = 'client_timeout' | 'network_connection' | 'csp_block' | 'insecure_context' | 'collection_failed' | 'invalid_options' | 'server_error' | 'account_closed' | 'script_load_failed' | 'stopped' | 'capped' | 'not_in_browser';
3
3
  declare class ZenoError extends Error {
4
4
  readonly code: ZenoErrorCode;
5
5
  constructor(code: ZenoErrorCode, message?: string);
6
6
  }
7
7
  //#endregion
8
- //#region src/types.d.ts
8
+ //#region src/browser/types.d.ts
9
9
  /** Values a metadata key can hold; nothing nested. */
10
10
  type Metadata = Record<string, string | number | boolean>;
11
11
  type IdentifyOptions = {
@@ -27,7 +27,7 @@ type Identification = {
27
27
  /** Left out when the project runs in zero trust mode: only your backend learns the visitor. */
28
28
  visitorId?: string;
29
29
  /**
30
- * Send it to your server with the action, where `verify` from `@zeno.id/server` says to allow, challenge or
30
+ * Send it to your server with the action, where `verify` from `zeno.id/server` says to allow, challenge or
31
31
  * block.
32
32
  */
33
33
  requestId: string;
@@ -65,17 +65,17 @@ type Zeno = {
65
65
  stop(): void;
66
66
  };
67
67
  //#endregion
68
- //#region src/forget.d.ts
68
+ //#region src/browser/forget.d.ts
69
69
  /**
70
- * Has the route clear its visitor cookie, without loading or starting anything: for a visitor who withdraws consent, or
71
- * withdrew it on an earlier visit, on a page that never called `start()`. `stop()` on a started one does the same and
72
- * stops it. Resolves once the route cleared the cookie; on the server it rejects with `not_in_browser`.
70
+ * Has the route clear its visitor cookie without loading or starting anything, for a visitor who withdraws consent on a
71
+ * page that never called `start()` (`stop()` on a started one does the same and stops it). Resolves once the route
72
+ * cleared the cookie; on the server it rejects with `not_in_browser`.
73
73
  *
74
74
  * @param path The same path on this site you pass to `start()`, `/zeno` by default.
75
75
  */
76
76
  declare const forget: (path?: string) => Promise<void>;
77
77
  //#endregion
78
- //#region src/index.d.ts
78
+ //#region src/browser/index.d.ts
79
79
  /**
80
80
  * Loads Zeno's script from your proxy route and starts gathering signals; nothing is sent until `identify()`.
81
81
  *
package/dist/index.d.ts CHANGED
@@ -1,11 +1,11 @@
1
- //#region src/error.d.ts
1
+ //#region src/browser/error.d.ts
2
2
  type ZenoErrorCode = 'client_timeout' | 'network_connection' | 'csp_block' | 'insecure_context' | 'collection_failed' | 'invalid_options' | 'server_error' | 'account_closed' | 'script_load_failed' | 'stopped' | 'capped' | 'not_in_browser';
3
3
  declare class ZenoError extends Error {
4
4
  readonly code: ZenoErrorCode;
5
5
  constructor(code: ZenoErrorCode, message?: string);
6
6
  }
7
7
  //#endregion
8
- //#region src/types.d.ts
8
+ //#region src/browser/types.d.ts
9
9
  /** Values a metadata key can hold; nothing nested. */
10
10
  type Metadata = Record<string, string | number | boolean>;
11
11
  type IdentifyOptions = {
@@ -27,7 +27,7 @@ type Identification = {
27
27
  /** Left out when the project runs in zero trust mode: only your backend learns the visitor. */
28
28
  visitorId?: string;
29
29
  /**
30
- * Send it to your server with the action, where `verify` from `@zeno.id/server` says to allow, challenge or
30
+ * Send it to your server with the action, where `verify` from `zeno.id/server` says to allow, challenge or
31
31
  * block.
32
32
  */
33
33
  requestId: string;
@@ -65,17 +65,17 @@ type Zeno = {
65
65
  stop(): void;
66
66
  };
67
67
  //#endregion
68
- //#region src/forget.d.ts
68
+ //#region src/browser/forget.d.ts
69
69
  /**
70
- * Has the route clear its visitor cookie, without loading or starting anything: for a visitor who withdraws consent, or
71
- * withdrew it on an earlier visit, on a page that never called `start()`. `stop()` on a started one does the same and
72
- * stops it. Resolves once the route cleared the cookie; on the server it rejects with `not_in_browser`.
70
+ * Has the route clear its visitor cookie without loading or starting anything, for a visitor who withdraws consent on a
71
+ * page that never called `start()` (`stop()` on a started one does the same and stops it). Resolves once the route
72
+ * cleared the cookie; on the server it rejects with `not_in_browser`.
73
73
  *
74
74
  * @param path The same path on this site you pass to `start()`, `/zeno` by default.
75
75
  */
76
76
  declare const forget: (path?: string) => Promise<void>;
77
77
  //#endregion
78
- //#region src/index.d.ts
78
+ //#region src/browser/index.d.ts
79
79
  /**
80
80
  * Loads Zeno's script from your proxy route and starts gathering signals; nothing is sent until `identify()`.
81
81
  *
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  const IDENTIFY_TIMEOUT = 1e4;
2
2
  //#endregion
3
- //#region src/error.ts
3
+ //#region src/browser/error.ts
4
4
  const messages = {
5
5
  client_timeout: "Client timeout",
6
6
  network_connection: "Network connection error",
@@ -27,41 +27,41 @@ var ZenoError = class extends Error {
27
27
  const toZenoError = (error) => {
28
28
  if (error instanceof ZenoError) return error;
29
29
  const { name, code, message } = typeof error === "object" && error !== null ? error : {};
30
- const text = typeof message === "string" ? message : void 0;
31
- return name === "ZenoError" && typeof code === "string" && code in messages ? new ZenoError(code, text) : new ZenoError("collection_failed", text);
30
+ const messageText = typeof message === "string" ? message : void 0;
31
+ return name === "ZenoError" && typeof code === "string" && code in messages ? new ZenoError(code, messageText) : new ZenoError("collection_failed", messageText);
32
32
  };
33
33
  //#endregion
34
- //#region src/csp.ts
34
+ //#region src/browser/csp.ts
35
35
  const watchCsp = (origin) => {
36
- let blocked = false;
36
+ let isBlocked = false;
37
37
  const listener = (event) => {
38
- if (event.blockedURI.startsWith(origin)) blocked = true;
38
+ if (event.blockedURI.startsWith(origin)) isBlocked = true;
39
39
  };
40
40
  globalThis.document?.addEventListener("securitypolicyviolation", listener);
41
41
  return {
42
- failure: async (otherwise, blockedMessage) => {
42
+ errorFor: async (fallback, blockedMessage) => {
43
43
  await new Promise((resolve) => setTimeout(resolve, 0));
44
- return blocked ? new ZenoError("csp_block", blockedMessage) : otherwise;
44
+ return isBlocked ? new ZenoError("csp_block", blockedMessage) : fallback;
45
45
  },
46
46
  stop: () => globalThis.document?.removeEventListener("securitypolicyviolation", listener)
47
47
  };
48
48
  };
49
49
  //#endregion
50
- //#region src/import.ts
50
+ //#region src/browser/import.ts
51
51
  const importModule = (url) => import(
52
52
  /* @vite-ignore */
53
53
  /* webpackIgnore: true */
54
54
  url
55
55
  );
56
56
  //#endregion
57
- //#region src/options.ts
58
- const invalid = (message) => new ZenoError("invalid_options", message);
57
+ //#region src/browser/options.ts
58
+ const invalidOptions = (message) => new ZenoError("invalid_options", message);
59
59
  const resolveEndpoint = (value) => {
60
60
  if (typeof value !== "string" || !/^\/(?![/\\])[^?#\\]*$/.test(value)) return;
61
61
  try {
62
- const page = new URL(globalThis.location.href);
63
- const url = new URL(value, page);
64
- return url.origin === page.origin ? `${url.origin}${url.pathname}` : void 0;
62
+ const pageUrl = new URL(globalThis.location.href);
63
+ const url = new URL(value, pageUrl);
64
+ return url.origin === pageUrl.origin ? `${url.origin}${url.pathname}` : void 0;
65
65
  } catch {
66
66
  return;
67
67
  }
@@ -69,20 +69,20 @@ const resolveEndpoint = (value) => {
69
69
  const toChallengeToken = (value) => typeof value === "string" && value.length > 0 && value.length <= 200 ? value : void 0;
70
70
  const checkProxyEndpoint = (path, call = "start") => {
71
71
  const url = resolveEndpoint(path ?? "/zeno");
72
- if (!url) throw invalid(`${call}() takes your proxy route's path on this site, like ${call}('/zeno')`);
72
+ if (!url) throw invalidOptions(`${call}() takes your proxy route's path on this site, like ${call}('/zeno')`);
73
73
  return url;
74
74
  };
75
75
  const checkIdentifyOptions = (options) => {
76
- if (typeof options !== "object" || options === null) throw invalid("Pass the identify() options as an object: identify({ externalId, action })");
76
+ if (typeof options !== "object" || options === null) throw invalidOptions("Pass the identify() options as an object: identify({ externalId, action })");
77
77
  const { externalId, action, metadata } = options;
78
- if (externalId !== void 0 && (typeof externalId !== "string" || !externalId || externalId.length > 256)) throw invalid("externalId must be a string of 1 to 256 characters");
79
- if (externalId === "." || externalId === "..") throw invalid("externalId can’t be . or ..");
80
- if (action !== void 0 && (typeof action !== "string" || action.length > 1024)) throw invalid("action must be a string of at most 1,024 characters");
81
- if (metadata !== void 0 && (typeof metadata !== "object" || metadata === null || Array.isArray(metadata))) throw invalid("metadata must be an object of keys and values, like { orderId: 'A-1042' }");
78
+ if (externalId !== void 0 && (typeof externalId !== "string" || !externalId || externalId.length > 256)) throw invalidOptions("externalId must be a string of 1 to 256 characters");
79
+ if (externalId === "." || externalId === "..") throw invalidOptions("externalId can’t be . or ..");
80
+ if (action !== void 0 && (typeof action !== "string" || action.length > 1024)) throw invalidOptions("action must be a string of at most 1,024 characters");
81
+ if (metadata !== void 0 && (typeof metadata !== "object" || metadata === null || Array.isArray(metadata))) throw invalidOptions("metadata must be an object of keys and values, like { orderId: 'A-1042' }");
82
82
  };
83
83
  //#endregion
84
- //#region src/storage.ts
85
- const forgetStored = (endpoint) => {
84
+ //#region src/browser/storage.ts
85
+ const clearVisitorCookie = (endpoint) => {
86
86
  return fetch(`${endpoint}?forget`, {
87
87
  method: "POST",
88
88
  credentials: "same-origin",
@@ -90,51 +90,51 @@ const forgetStored = (endpoint) => {
90
90
  });
91
91
  };
92
92
  //#endregion
93
- //#region src/forget.ts
93
+ //#region src/browser/forget.ts
94
94
  /**
95
- * Has the route clear its visitor cookie, without loading or starting anything: for a visitor who withdraws consent, or
96
- * withdrew it on an earlier visit, on a page that never called `start()`. `stop()` on a started one does the same and
97
- * stops it. Resolves once the route cleared the cookie; on the server it rejects with `not_in_browser`.
95
+ * Has the route clear its visitor cookie without loading or starting anything, for a visitor who withdraws consent on a
96
+ * page that never called `start()` (`stop()` on a started one does the same and stops it). Resolves once the route
97
+ * cleared the cookie; on the server it rejects with `not_in_browser`.
98
98
  *
99
99
  * @param path The same path on this site you pass to `start()`, `/zeno` by default.
100
100
  */
101
101
  const forget = async (path) => {
102
102
  if (typeof document === "undefined") throw new ZenoError("not_in_browser");
103
103
  const endpoint = checkProxyEndpoint(path, "forget");
104
- const csp = watchCsp(new URL(endpoint).origin);
104
+ const cspWatcher = watchCsp(new URL(endpoint).origin);
105
105
  let response;
106
106
  try {
107
- response = await forgetStored(endpoint);
107
+ response = await clearVisitorCookie(endpoint);
108
108
  } catch {
109
- throw await csp.failure(new ZenoError("network_connection"));
109
+ throw await cspWatcher.errorFor(new ZenoError("network_connection"));
110
110
  } finally {
111
- csp.stop();
111
+ cspWatcher.stop();
112
112
  }
113
113
  if (!response.ok) throw new ZenoError("server_error", `The route answered ${response.status} when asked to clear its cookie`);
114
114
  };
115
115
  //#endregion
116
- //#region src/index.ts
117
- const withTimeout = (promise, ms, error) => {
116
+ //#region src/browser/index.ts
117
+ const withTimeout = (promise, ms, makeError) => {
118
118
  let timer;
119
119
  return Promise.race([promise, new Promise((_, reject) => {
120
- timer = setTimeout(() => reject(error()), ms);
120
+ timer = setTimeout(() => reject(makeError()), ms);
121
121
  })]).finally(() => clearTimeout(timer));
122
122
  };
123
- const failed = (error) => ({
123
+ const toFailedIdentification = (error) => ({
124
124
  requestId: void 0,
125
125
  error: toZenoError(error)
126
126
  });
127
- const ownAnswer = (identification) => {
127
+ const withOwnError = (identification) => {
128
128
  return identification.error ? {
129
129
  ...identification,
130
130
  error: toZenoError(identification.error)
131
131
  } : identification;
132
132
  };
133
- const onServer = () => ({
134
- identify: () => Promise.resolve(failed(new ZenoError("not_in_browser"))),
133
+ const makeServerStub = () => ({
134
+ identify: () => Promise.resolve(toFailedIdentification(new ZenoError("not_in_browser"))),
135
135
  stop() {}
136
136
  });
137
- const refreshChallengeToken = (endpoint) => async () => {
137
+ const makeChallengeTokenRefresh = (endpoint) => async () => {
138
138
  try {
139
139
  const module = await importModule(`${endpoint}?challenge=${Date.now()}`);
140
140
  return toChallengeToken(module?.challengeToken);
@@ -142,7 +142,7 @@ const refreshChallengeToken = (endpoint) => async () => {
142
142
  return;
143
143
  }
144
144
  };
145
- const loadFailure = async (endpoint) => {
145
+ const explainLoadFailure = async (endpoint) => {
146
146
  const fallback = new ZenoError("script_load_failed", `The script couldn't be loaded from ${endpoint}: check that your proxy route answers there`);
147
147
  try {
148
148
  const response = await fetch(endpoint, { credentials: "same-origin" });
@@ -159,25 +159,25 @@ const loadFailure = async (endpoint) => {
159
159
  return fallback;
160
160
  }
161
161
  };
162
- const loadAgent = async (endpoint, stopped, started) => {
163
- const csp = watchCsp(new URL(endpoint).origin);
162
+ const loadAgent = async (endpoint, isStopped, onStarted) => {
163
+ const cspWatcher = watchCsp(new URL(endpoint).origin);
164
164
  let module;
165
165
  try {
166
166
  module = await importModule(endpoint);
167
167
  } catch {
168
- const blocked = await csp.failure(new ZenoError("script_load_failed"), `The page's Content Security Policy blocked loading the script from ${endpoint}: allow it in script-src`);
169
- throw blocked.code === "csp_block" ? blocked : await loadFailure(endpoint);
168
+ const importError = await cspWatcher.errorFor(new ZenoError("script_load_failed"), `The page's Content Security Policy blocked loading the script from ${endpoint}: allow it in script-src`);
169
+ throw importError.code === "csp_block" ? importError : await explainLoadFailure(endpoint);
170
170
  } finally {
171
- csp.stop();
171
+ cspWatcher.stop();
172
172
  }
173
- if (stopped()) throw new ZenoError("stopped");
173
+ if (isStopped()) throw new ZenoError("stopped");
174
174
  if (typeof module?.start !== "function") throw new ZenoError("script_load_failed", `${endpoint} didn't answer with the script; check the endpoint`);
175
175
  try {
176
176
  const agent = module.start(new URL(endpoint).pathname, {
177
177
  challengeToken: toChallengeToken(module.challengeToken),
178
- refreshChallengeToken: refreshChallengeToken(endpoint)
178
+ refreshChallengeToken: makeChallengeTokenRefresh(endpoint)
179
179
  });
180
- started(agent);
180
+ onStarted(agent);
181
181
  return agent;
182
182
  } catch (error) {
183
183
  throw toZenoError(error);
@@ -190,39 +190,39 @@ const loadAgent = async (endpoint, stopped, started) => {
190
190
  * fragment. The script loads from it and identifies through it.
191
191
  */
192
192
  const start = (path) => {
193
- if (typeof document === "undefined") return onServer();
193
+ if (typeof document === "undefined") return makeServerStub();
194
194
  const endpoint = checkProxyEndpoint(path);
195
- let stopped = false;
196
- let running;
197
- let rejectStopped = () => {};
198
- const stopping = new Promise((_, reject) => {
199
- rejectStopped = reject;
195
+ let isStopped = false;
196
+ let runningAgent;
197
+ let rejectOnStop = () => {};
198
+ const stopSignal = new Promise((_, reject) => {
199
+ rejectOnStop = reject;
200
200
  });
201
- stopping.catch(() => {});
202
- const loaded = loadAgent(endpoint, () => stopped, (agent) => running = agent);
203
- loaded.catch(() => {});
201
+ stopSignal.catch(() => {});
202
+ const agentLoading = loadAgent(endpoint, () => isStopped, (agent) => runningAgent = agent);
203
+ agentLoading.catch(() => {});
204
204
  const identify = async (identifyOptions) => {
205
- if (stopped) throw new ZenoError("stopped");
205
+ if (isStopped) throw new ZenoError("stopped");
206
206
  checkIdentifyOptions(identifyOptions);
207
207
  const timeout = IDENTIFY_TIMEOUT;
208
- const started = performance.now();
209
- const agent = await withTimeout(Promise.race([loaded, stopping]), timeout, () => new ZenoError("client_timeout"));
210
- const left = Math.max(1, timeout - (performance.now() - started));
211
- if (stopped) throw new ZenoError("stopped");
212
- return ownAnswer(await agent.identify({
208
+ const startedAt = performance.now();
209
+ const agent = await withTimeout(Promise.race([agentLoading, stopSignal]), timeout, () => new ZenoError("client_timeout"));
210
+ const timeLeft = Math.max(1, timeout - (performance.now() - startedAt));
211
+ if (isStopped) throw new ZenoError("stopped");
212
+ return withOwnError(await agent.identify({
213
213
  ...identifyOptions,
214
- timeout: left
214
+ timeout: timeLeft
215
215
  }));
216
216
  };
217
217
  return {
218
- identify: (identifyOptions = {}) => identify(identifyOptions).catch(failed),
218
+ identify: (identifyOptions = {}) => identify(identifyOptions).catch(toFailedIdentification),
219
219
  stop() {
220
- if (!stopped) {
221
- stopped = true;
222
- rejectStopped(new ZenoError("stopped"));
220
+ if (!isStopped) {
221
+ isStopped = true;
222
+ rejectOnStop(new ZenoError("stopped"));
223
223
  }
224
- if (running) running.stop();
225
- else forgetStored(endpoint).catch(() => {});
224
+ if (runningAgent) runningAgent.stop();
225
+ else clearVisitorCookie(endpoint).catch(() => {});
226
226
  }
227
227
  };
228
228
  };