zeno.id 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2026 Creative Code Solutions B.V.
3
+ Copyright (c) 2026 Zeno
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -112,7 +112,7 @@ The script's code uses no `eval` or `new Function`, so `'unsafe-eval'` isn't nee
112
112
  | `action` | What the visitor is doing, like `login`, `signup` or `checkout`, up to 1,024 characters. Returned with the event. |
113
113
  | `metadata` | Your own key-values kept with the event, like `{ orderId: 'A-1042', plan: 'pro' }`: up to 20 keys of 1 to 40 letters, digits, `_`, `.` or `-`, each a string up to 256 characters, a number or a boolean, 2 KB in all. Returned with the event, never used for detection. |
114
114
 
115
- The script keeps no visitor id itself. The route keeps it in the `zeno_id` cookie (`HttpOnly`, `SameSite=Lax`, `Secure` on https, a year), on the route's own path, so two routes on one site, like a site's own login and a demo, keep separate ids. Zeno reuses it while it's still the same device, so the id survives browser updates. The script keeps nothing in the browser's storage, and every `identify()` identifies again.
115
+ The script keeps no visitor id itself. The route keeps it in the `zeno_id` cookie (`HttpOnly`, `SameSite=Lax`, `Secure` on https, 400 days from the last identification), on the route's own path, so two routes on one site, like a site's own login and a demo, keep separate ids. The script keeps a copy in the site's `localStorage` (`zeno:id:` and the route's path), used only when the cookie is gone. Zeno reuses either while it's still the same device, so the id survives browser updates. Every `identify()` identifies again.
116
116
 
117
117
  ### Stop and forget
118
118
 
@@ -202,7 +202,7 @@ That `start()` takes the path it was imported from unless you pass another, and
202
202
  The browser SDK never talks to Zeno directly. It loads its script from a route on your own site and sends its identifications there, and the route passes them on with your API key and the visitor's IP.
203
203
 
204
204
  - Ad and tracker blockers block requests to identification services. A path on your own site looks like any other request your pages make.
205
- - The route keeps the visitor id in a first-party `HttpOnly` cookie (`zeno_id`) that it sets itself, which Safari keeps for a year where it would delete a script's storage after 7 days.
205
+ - The route keeps the visitor id in a first-party `HttpOnly` cookie (`zeno_id`) that it sets itself, which Safari keeps for 400 days where it deletes a script's storage after 7 days without a visit; the script's `localStorage` copy covers a browser that cleared only its cookies.
206
206
  - Your API key stays on your server, and the route refuses a browser's cross-site request, so there's no allow list of origins to keep.
207
207
 
208
208
  `createProxy(apiKey, options?)` returns the route's handler: `zeno(request, ip)` takes a standard `Request` and the IP address it came from, and returns a `Response`, using web APIs only. The browser SDK calls it with two methods on one path: `GET` loads the script (gzipped when the browser takes it; `HEAD` too), and `POST` identifies, or, as `forget()`, clears the visitor id for withdrawn consent.
@@ -343,7 +343,6 @@ await client.addRelation({
343
343
  externalId: user.id,
344
344
  type: 'phone',
345
345
  value: order.phone,
346
- action: 'checkout',
347
346
  })
348
347
  await client.addRelation({
349
348
  externalId: user.id,
@@ -361,22 +360,21 @@ const { url } = await client.createEmbed({
361
360
  })
362
361
  ```
363
362
 
364
- | Method | Call |
365
- | ----------------------------------------------------------------------------- | -------------------------------------------------------------------------- |
366
- | `verify(requestId, { ip?, externalId?, maxAge?, idempotencyKey? }?)` | `POST /verify` |
367
- | `getEvent(requestId)` | `GET /events/{requestId}` |
368
- | `searchEvents(filters)` | `GET /events?...` |
369
- | `getVisitor(visitorId)` | `GET /visitors/{visitorId}` |
370
- | `deleteVisitor(visitorId)` | `DELETE /visitors/{visitorId}` |
371
- | `deleteExternalId(externalId)` | `DELETE /external-ids?externalId=...` |
372
- | `reportOutcome(requestId, outcome)` | `POST /outcomes`, `fraud` or `legitimate`, the latest counts |
373
- | `addRelation({ externalId, type, value or relatedExternalId, action?, at? })` | `POST /related` |
374
- | `removeRelation({ externalId, type, value or relatedExternalId })` | `DELETE /related?externalId=...&type=...`, `{ removed }`, free |
375
- | `getRelated(externalId, { type?, depth? })` | `GET /related?externalId=...`, every type unless `type` names one |
376
- | `getRelatedValues(externalId, { type? })` | `GET /related/values?externalId=...` |
377
- | `lookupRelated(type, value, { limit?, cursor? })` | `GET /related/lookup?type=...&value=...`, 20 a page by default (up to 100) |
378
- | `getSharedValues(type, { limit?, cursor? })` | `GET /related/shared?type=...` |
379
- | `createEmbed({ externalId, origin, ttl? })` | `POST /embeds` |
363
+ | Method | Call |
364
+ | -------------------------------------------------------------------- | -------------------------------------------------------------------------- |
365
+ | `verify(requestId, { ip?, externalId?, maxAge?, idempotencyKey? }?)` | `POST /verify` |
366
+ | `getEvent(requestId)` | `GET /events/{requestId}` |
367
+ | `searchEvents(filters)` | `GET /events?...` |
368
+ | `getVisitor(visitorId)` | `GET /visitors/{visitorId}` |
369
+ | `deleteVisitor(visitorId)` | `DELETE /visitors/{visitorId}` |
370
+ | `deleteExternalId(externalId)` | `DELETE /external-ids?externalId=...` |
371
+ | `reportOutcome(requestId, outcome)` | `POST /outcomes`, `fraud` or `legitimate`, the latest counts |
372
+ | `addRelation({ externalId, type, value or relatedExternalId, at? })` | `POST /related` |
373
+ | `removeRelation({ externalId, type, value or relatedExternalId })` | `DELETE /related?externalId=...&type=...`, `{ removed }`, free |
374
+ | `getRelated(externalId, { type?, depth? })` | `GET /related?externalId=...`, every type unless `type` names one |
375
+ | `getRelatedValues(externalId, { type? })` | `GET /related/values?externalId=...` |
376
+ | `lookupRelated(type, value, { limit?, cursor? })` | `GET /related/lookup?type=...&value=...`, 20 a page by default (up to 100) |
377
+ | `createEmbed({ externalId, origin, ttl? })` | `POST /embeds` |
380
378
 
381
379
  A list filter (`apiKeyId`, `country`, `origin`, `asn`, `browser`, `os`, `action`, `signal`, `bot`) takes an array and matches any of its values. Visitor ids and ips relate your users by themselves for events with an external id; `addRelation` adds what only you know: an ip seen elsewhere, a value of a type of your own, or a relation between two users. Make a `createEmbed` link for each view of your admin panel's page.
382
380
 
@@ -386,7 +384,7 @@ The SDK's own codes: `network_error` (status `0`) when the API can't be reached
386
384
 
387
385
  `addRelation` is the one billed call: each is billed like an identification and counts toward the free monthly identifications and the spend limits (reads, `createEmbed` and what events relate by themselves are free). Once a spend limit you set for the project, its organization or the key is reached it throws a `402` `spend_limit_reached` and adds nothing. Every call answers `402` `account_closed` while Zeno has closed the organization's account (for unpaid invoices); contact support to reopen it.
388
386
 
389
- `addRelation`'s `at` takes a `Date`, epoch milliseconds or an ISO string. A type's first call fixes whether it holds values or relations. The project's settings hold each type's weight (`visitor-id` 0.8, `ip` 0.4, a type of your own 0.5 by default), applied when relations are read, so a change re-scores every relation. The reads answer each value's `weight` and each related user's (what the two share combined as `1 - Π(1 - weight)`, so two shared ips make 0.64 and a browser and an ip 0.88, multiplied along the path); `duplicate` means they share one value weighing 0.5 or more with another user. `createEmbed` answers `{ url, expiresAt }`: put the url in an iframe on `origin`, the only page allowed to frame it, before `expiresAt` (`ttl`, 5 to 60 minutes, 15 by default).
387
+ `addRelation`'s `at` takes a `Date`, epoch milliseconds or an ISO string. A type's first call fixes whether it holds values or relations. The project's settings hold each type's weight (`visitor-id` 0.9, `residential-ip` 0.7, `ip` 0.25, `broad-visitor-id` 0.25, a type of your own 0.5 by default), applied when relations are read, so a change re-scores every relation. The reads answer each value's `weight` and each related user's (what the two share combined as `1 - Π(1 - weight)`, so two shared ips make 0.44 and a browser and an ip 0.93, multiplied along the path); `duplicate` means they share one value weighing 0.5 or more with another user. `createEmbed` answers `{ url, expiresAt }`: put the url in an iframe on `origin`, the only page allowed to frame it, before `expiresAt` (`ttl`, 5 to 60 minutes, 15 by default).
390
388
 
391
389
  ## Webhooks
392
390
 
package/dist/index.cjs CHANGED
@@ -1,233 +1,4 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const IDENTIFY_TIMEOUT = 1e4;
3
- //#endregion
4
- //#region src/browser/error.ts
5
- const messages = {
6
- client_timeout: "Client timeout",
7
- network_connection: "Network connection error",
8
- csp_block: "Blocked by the Content Security Policy",
9
- insecure_context: "Zeno needs a secure context (https)",
10
- collection_failed: "Collecting the browser data failed",
11
- invalid_options: "The options are invalid",
12
- server_error: "The identification api failed",
13
- account_closed: "The project's organization is closed; contact Zeno support to reopen it",
14
- script_load_failed: "The script couldn't be loaded from the endpoint",
15
- stopped: "Identification was stopped; call start() again to identify",
16
- capped: "Nothing was identified: a spend limit or rate limit was reached",
17
- not_in_browser: "Zeno identifies in the browser only; this ran on the server"
18
- };
19
- const REFUSED_KEY = "The proxy route's API key was refused: check the API key the route on your server is set up with";
20
- var ZenoError = class extends Error {
21
- code;
22
- constructor(code, message) {
23
- super(message ?? messages[code]);
24
- this.code = code;
25
- this.name = "ZenoError";
26
- }
27
- };
28
- const toZenoError = (error) => {
29
- if (error instanceof ZenoError) return error;
30
- const { name, code, message } = typeof error === "object" && error !== null ? error : {};
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
- };
34
- //#endregion
35
- //#region src/browser/csp.ts
36
- const watchCsp = (origin) => {
37
- let isBlocked = false;
38
- const listener = (event) => {
39
- if (event.blockedURI.startsWith(origin)) isBlocked = true;
40
- };
41
- globalThis.document?.addEventListener("securitypolicyviolation", listener);
42
- return {
43
- errorFor: async (fallback, blockedMessage) => {
44
- await new Promise((resolve) => setTimeout(resolve, 0));
45
- return isBlocked ? new ZenoError("csp_block", blockedMessage) : fallback;
46
- },
47
- stop: () => globalThis.document?.removeEventListener("securitypolicyviolation", listener)
48
- };
49
- };
50
- //#endregion
51
- //#region src/browser/import.ts
52
- const importModule = (url) => import(
53
- /* @vite-ignore */
54
- /* webpackIgnore: true */
55
- url
56
- );
57
- //#endregion
58
- //#region src/browser/options.ts
59
- const invalidOptions = (message) => new ZenoError("invalid_options", message);
60
- const resolveEndpoint = (value) => {
61
- if (typeof value !== "string" || !/^\/(?![/\\])[^?#\\]*$/.test(value)) return;
62
- try {
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
- } catch {
67
- return;
68
- }
69
- };
70
- const toChallengeToken = (value) => typeof value === "string" && value.length > 0 && value.length <= 200 ? value : void 0;
71
- const checkProxyEndpoint = (path, call = "start") => {
72
- const url = resolveEndpoint(path ?? "/zeno");
73
- if (!url) throw invalidOptions(`${call}() takes your proxy route's path on this site, like ${call}('/zeno')`);
74
- return url;
75
- };
76
- const checkIdentifyOptions = (options) => {
77
- if (typeof options !== "object" || options === null) throw invalidOptions("Pass the identify() options as an object: identify({ externalId, action })");
78
- const { externalId, action, metadata } = options;
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
- };
84
- //#endregion
85
- //#region src/browser/storage.ts
86
- const clearVisitorCookie = (endpoint) => {
87
- return fetch(`${endpoint}?forget`, {
88
- method: "POST",
89
- credentials: "same-origin",
90
- keepalive: true
91
- });
92
- };
93
- //#endregion
94
- //#region src/browser/forget.ts
95
- /**
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
- *
100
- * @param path The same path on this site you pass to `start()`, `/zeno` by default.
101
- */
102
- const forget = async (path) => {
103
- if (typeof document === "undefined") throw new ZenoError("not_in_browser");
104
- const endpoint = checkProxyEndpoint(path, "forget");
105
- const cspWatcher = watchCsp(new URL(endpoint).origin);
106
- let response;
107
- try {
108
- response = await clearVisitorCookie(endpoint);
109
- } catch {
110
- throw await cspWatcher.errorFor(new ZenoError("network_connection"));
111
- } finally {
112
- cspWatcher.stop();
113
- }
114
- if (!response.ok) throw new ZenoError("server_error", `The route answered ${response.status} when asked to clear its cookie`);
115
- };
116
- //#endregion
117
- //#region src/browser/index.ts
118
- const withTimeout = (promise, ms, makeError) => {
119
- let timer;
120
- return Promise.race([promise, new Promise((_, reject) => {
121
- timer = setTimeout(() => reject(makeError()), ms);
122
- })]).finally(() => clearTimeout(timer));
123
- };
124
- const toFailedIdentification = (error) => ({
125
- requestId: void 0,
126
- error: toZenoError(error)
127
- });
128
- const withOwnError = (identification) => {
129
- return identification.error ? {
130
- ...identification,
131
- error: toZenoError(identification.error)
132
- } : identification;
133
- };
134
- const makeServerStub = () => ({
135
- identify: () => Promise.resolve(toFailedIdentification(new ZenoError("not_in_browser"))),
136
- stop() {}
137
- });
138
- const makeChallengeTokenRefresh = (endpoint) => async () => {
139
- try {
140
- const module = await importModule(`${endpoint}?challenge=${Date.now()}`);
141
- return toChallengeToken(module?.challengeToken);
142
- } catch {
143
- return;
144
- }
145
- };
146
- const explainLoadFailure = async (endpoint) => {
147
- const fallback = new ZenoError("script_load_failed", `The script couldn't be loaded from ${endpoint}: check that your proxy route answers there`);
148
- try {
149
- const response = await fetch(endpoint, { credentials: "same-origin" });
150
- if (response.ok) {
151
- await response.body?.cancel();
152
- return /javascript/i.test(response.headers.get("content-type") ?? "") ? fallback : new ZenoError("script_load_failed", `${endpoint} didn't answer with the script; check the endpoint`);
153
- }
154
- const body = await response.json().catch(() => void 0);
155
- const code = typeof body?.error === "string" ? body.error : void 0;
156
- if (code === "invalid_api_key") return new ZenoError("server_error", REFUSED_KEY);
157
- if (code === "account_closed") return new ZenoError("account_closed");
158
- return code || response.status >= 500 ? new ZenoError("server_error", `The route at ${endpoint} answered ${response.status}${code ? ` ${code}` : ""} for the script`) : new ZenoError("script_load_failed", `The route at ${endpoint} answered ${response.status}: check that your proxy route answers there`);
159
- } catch {
160
- return fallback;
161
- }
162
- };
163
- const loadAgent = async (endpoint, isStopped, onStarted) => {
164
- const cspWatcher = watchCsp(new URL(endpoint).origin);
165
- let module;
166
- try {
167
- module = await importModule(endpoint);
168
- } catch {
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
- } finally {
172
- cspWatcher.stop();
173
- }
174
- if (isStopped()) throw new ZenoError("stopped");
175
- if (typeof module?.start !== "function") throw new ZenoError("script_load_failed", `${endpoint} didn't answer with the script; check the endpoint`);
176
- try {
177
- const agent = module.start(new URL(endpoint).pathname, {
178
- challengeToken: toChallengeToken(module.challengeToken),
179
- refreshChallengeToken: makeChallengeTokenRefresh(endpoint)
180
- });
181
- onStarted(agent);
182
- return agent;
183
- } catch (error) {
184
- throw toZenoError(error);
185
- }
186
- };
187
- /**
188
- * Loads Zeno's script from your proxy route and starts gathering signals; nothing is sent until `identify()`.
189
- *
190
- * @param path The path on this site you mounted `createProxy` at, `/zeno` by default, without a query string or
191
- * fragment. The script loads from it and identifies through it.
192
- */
193
- const start = (path) => {
194
- if (typeof document === "undefined") return makeServerStub();
195
- const endpoint = checkProxyEndpoint(path);
196
- let isStopped = false;
197
- let runningAgent;
198
- let rejectOnStop = () => {};
199
- const stopSignal = new Promise((_, reject) => {
200
- rejectOnStop = reject;
201
- });
202
- stopSignal.catch(() => {});
203
- const agentLoading = loadAgent(endpoint, () => isStopped, (agent) => runningAgent = agent);
204
- agentLoading.catch(() => {});
205
- const identify = async (identifyOptions) => {
206
- if (isStopped) throw new ZenoError("stopped");
207
- checkIdentifyOptions(identifyOptions);
208
- const timeout = IDENTIFY_TIMEOUT;
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
- ...identifyOptions,
215
- timeout: timeLeft
216
- }));
217
- };
218
- return {
219
- identify: (identifyOptions = {}) => identify(identifyOptions).catch(toFailedIdentification),
220
- stop() {
221
- if (!isStopped) {
222
- isStopped = true;
223
- rejectOnStop(new ZenoError("stopped"));
224
- }
225
- if (runningAgent) runningAgent.stop();
226
- else clearVisitorCookie(endpoint).catch(() => {});
227
- }
228
- };
229
- };
230
- //#endregion
231
- exports.ZenoError = ZenoError;
232
- exports.forget = forget;
233
- exports.start = start;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e={client_timeout:`Client timeout`,network_connection:`Network connection error`,csp_block:`Blocked by the Content Security Policy`,insecure_context:`Zeno needs a secure context (https)`,collection_failed:`Collecting the browser data failed`,invalid_options:`The options are invalid`,server_error:`The identification api failed`,account_closed:`The project's organization is closed; contact Zeno support to reopen it`,script_load_failed:`The script couldn't be loaded from the endpoint`,stopped:`Identification was stopped; call start() again to identify`,capped:`Nothing was identified: a spend limit or rate limit was reached`,not_in_browser:`Zeno identifies in the browser only; this ran on the server`};var t=class extends Error{code;constructor(t,n){super(n??e[t]),this.code=t,this.name=`ZenoError`}};const n=n=>{if(n instanceof t)return n;let{name:r,code:i,message:a}=typeof n==`object`&&n?n:{},o=typeof a==`string`?a:void 0;return r===`ZenoError`&&typeof i==`string`&&i in e?new t(i,o):new t(`collection_failed`,o)},r=e=>{let n=!1,r=t=>{t.blockedURI.startsWith(e)&&(n=!0)};return globalThis.document?.addEventListener(`securitypolicyviolation`,r),{errorFor:async(e,r)=>(await new Promise(e=>setTimeout(e,0)),n?new t(`csp_block`,r):e),stop:()=>globalThis.document?.removeEventListener(`securitypolicyviolation`,r)}},i=e=>import(
2
+ /* @vite-ignore */
3
+ /* webpackIgnore: true */
4
+ e),a=e=>new t(`invalid_options`,e),o=e=>{if(typeof e==`string`&&/^\/(?![/\\])[^?#\\]*$/.test(e))try{let t=new URL(globalThis.location.href),n=new URL(e,t);return n.origin===t.origin?`${n.origin}${n.pathname}`:void 0}catch{return}},s=e=>typeof e==`string`&&e.length>0&&e.length<=200?e:void 0,c=(e,t=`start`)=>{let n=o(e??`/zeno`);if(!n)throw a(`${t}() takes your proxy route's path on this site, like ${t}('/zeno')`);return n},l=e=>{if(typeof e!=`object`||!e)throw a(`Pass the identify() options as an object: identify({ externalId, action })`);let{externalId:t,action:n,metadata:r}=e;if(t!==void 0&&(typeof t!=`string`||!t||t.length>256))throw a(`externalId must be a string of 1 to 256 characters`);if(t===`.`||t===`..`)throw a(`externalId can’t be . or ..`);if(n!==void 0&&(typeof n!=`string`||n.length>1024))throw a(`action must be a string of at most 1,024 characters`);if(r!==void 0&&(typeof r!=`object`||!r||Array.isArray(r)))throw a(`metadata must be an object of keys and values, like { orderId: 'A-1042' }`)},u=e=>`zeno:id:${new URL(e).pathname}`,d=()=>{try{return globalThis.localStorage??void 0}catch{return}},f=e=>{try{d()?.removeItem(u(e))}catch{}return fetch(`${e}?forget`,{method:`POST`,credentials:`same-origin`,keepalive:!0})},p=async e=>{if(typeof document>`u`)throw new t(`not_in_browser`);let n=c(e,`forget`),i=r(new URL(n).origin),a;try{a=await f(n)}catch{throw await i.errorFor(new t(`network_connection`))}finally{i.stop()}if(!a.ok)throw new t(`server_error`,`The route answered ${a.status} when asked to clear its cookie`)},m=(e,t,n)=>{let r;return Promise.race([e,new Promise((e,i)=>{r=setTimeout(()=>i(n()),t)})]).finally(()=>clearTimeout(r))},h=e=>({requestId:void 0,error:n(e)}),g=e=>e.error?{...e,error:n(e.error)}:e,_=()=>({identify:()=>Promise.resolve(h(new t(`not_in_browser`))),stop(){}}),v=e=>async()=>{try{let t=await i(`${e}?challenge=${Date.now()}`);return s(t?.challengeToken)}catch{return}},y=async e=>{let n=new t(`script_load_failed`,`The script couldn't be loaded from ${e}: check that your proxy route answers there`);try{let r=await fetch(e,{credentials:`same-origin`});if(r.ok)return await r.body?.cancel(),/javascript/i.test(r.headers.get(`content-type`)??``)?n:new t(`script_load_failed`,`${e} didn't answer with the script; check the endpoint`);let i=await r.json().catch(()=>void 0),a=typeof i?.error==`string`?i.error:void 0;return a===`invalid_api_key`?new t(`server_error`,`The proxy route's API key was refused: check the API key the route on your server is set up with`):a===`account_closed`?new t(`account_closed`):a||r.status>=500?new t(`server_error`,`The route at ${e} answered ${r.status}${a?` ${a}`:``} for the script`):new t(`script_load_failed`,`The route at ${e} answered ${r.status}: check that your proxy route answers there`)}catch{return n}},b=async(e,a,o)=>{let c=r(new URL(e).origin),l;try{l=await i(e)}catch{let n=await c.errorFor(new t(`script_load_failed`),`The page's Content Security Policy blocked loading the script from ${e}: allow it in script-src`);throw n.code===`csp_block`?n:await y(e)}finally{c.stop()}if(a())throw new t(`stopped`);if(typeof l?.start!=`function`)throw new t(`script_load_failed`,`${e} didn't answer with the script; check the endpoint`);try{let t=l.start(new URL(e).pathname,{challengeToken:s(l.challengeToken),refreshChallengeToken:v(e)});return o(t),t}catch(e){throw n(e)}},x=e=>{if(typeof document>`u`)return _();let n=c(e),r=!1,i,a=()=>{},o=new Promise((e,t)=>{a=t});o.catch(()=>{});let s=b(n,()=>r,e=>i=e);s.catch(()=>{});let u=async e=>{if(r)throw new t(`stopped`);l(e);let n=1e4,i=performance.now(),a=await m(Promise.race([s,o]),n,()=>new t(`client_timeout`)),c=Math.max(1,n-(performance.now()-i));if(r)throw new t(`stopped`);return g(await a.identify({...e,timeout:c}))};return{identify:(e={})=>u(e).catch(h),stop(){r||(r=!0,a(new t(`stopped`))),i?i.stop():f(n).catch(()=>{})}}};exports.ZenoError=t,exports.forget=p,exports.start=x;
package/dist/index.js CHANGED
@@ -1,230 +1,4 @@
1
- const IDENTIFY_TIMEOUT = 1e4;
2
- //#endregion
3
- //#region src/browser/error.ts
4
- const messages = {
5
- client_timeout: "Client timeout",
6
- network_connection: "Network connection error",
7
- csp_block: "Blocked by the Content Security Policy",
8
- insecure_context: "Zeno needs a secure context (https)",
9
- collection_failed: "Collecting the browser data failed",
10
- invalid_options: "The options are invalid",
11
- server_error: "The identification api failed",
12
- account_closed: "The project's organization is closed; contact Zeno support to reopen it",
13
- script_load_failed: "The script couldn't be loaded from the endpoint",
14
- stopped: "Identification was stopped; call start() again to identify",
15
- capped: "Nothing was identified: a spend limit or rate limit was reached",
16
- not_in_browser: "Zeno identifies in the browser only; this ran on the server"
17
- };
18
- const REFUSED_KEY = "The proxy route's API key was refused: check the API key the route on your server is set up with";
19
- var ZenoError = class extends Error {
20
- code;
21
- constructor(code, message) {
22
- super(message ?? messages[code]);
23
- this.code = code;
24
- this.name = "ZenoError";
25
- }
26
- };
27
- const toZenoError = (error) => {
28
- if (error instanceof ZenoError) return error;
29
- const { name, code, message } = typeof error === "object" && error !== null ? error : {};
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
- };
33
- //#endregion
34
- //#region src/browser/csp.ts
35
- const watchCsp = (origin) => {
36
- let isBlocked = false;
37
- const listener = (event) => {
38
- if (event.blockedURI.startsWith(origin)) isBlocked = true;
39
- };
40
- globalThis.document?.addEventListener("securitypolicyviolation", listener);
41
- return {
42
- errorFor: async (fallback, blockedMessage) => {
43
- await new Promise((resolve) => setTimeout(resolve, 0));
44
- return isBlocked ? new ZenoError("csp_block", blockedMessage) : fallback;
45
- },
46
- stop: () => globalThis.document?.removeEventListener("securitypolicyviolation", listener)
47
- };
48
- };
49
- //#endregion
50
- //#region src/browser/import.ts
51
- const importModule = (url) => import(
52
- /* @vite-ignore */
53
- /* webpackIgnore: true */
54
- url
55
- );
56
- //#endregion
57
- //#region src/browser/options.ts
58
- const invalidOptions = (message) => new ZenoError("invalid_options", message);
59
- const resolveEndpoint = (value) => {
60
- if (typeof value !== "string" || !/^\/(?![/\\])[^?#\\]*$/.test(value)) return;
61
- try {
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
- } catch {
66
- return;
67
- }
68
- };
69
- const toChallengeToken = (value) => typeof value === "string" && value.length > 0 && value.length <= 200 ? value : void 0;
70
- const checkProxyEndpoint = (path, call = "start") => {
71
- const url = resolveEndpoint(path ?? "/zeno");
72
- if (!url) throw invalidOptions(`${call}() takes your proxy route's path on this site, like ${call}('/zeno')`);
73
- return url;
74
- };
75
- const checkIdentifyOptions = (options) => {
76
- if (typeof options !== "object" || options === null) throw invalidOptions("Pass the identify() options as an object: identify({ externalId, action })");
77
- const { externalId, action, metadata } = options;
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
- };
83
- //#endregion
84
- //#region src/browser/storage.ts
85
- const clearVisitorCookie = (endpoint) => {
86
- return fetch(`${endpoint}?forget`, {
87
- method: "POST",
88
- credentials: "same-origin",
89
- keepalive: true
90
- });
91
- };
92
- //#endregion
93
- //#region src/browser/forget.ts
94
- /**
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
- *
99
- * @param path The same path on this site you pass to `start()`, `/zeno` by default.
100
- */
101
- const forget = async (path) => {
102
- if (typeof document === "undefined") throw new ZenoError("not_in_browser");
103
- const endpoint = checkProxyEndpoint(path, "forget");
104
- const cspWatcher = watchCsp(new URL(endpoint).origin);
105
- let response;
106
- try {
107
- response = await clearVisitorCookie(endpoint);
108
- } catch {
109
- throw await cspWatcher.errorFor(new ZenoError("network_connection"));
110
- } finally {
111
- cspWatcher.stop();
112
- }
113
- if (!response.ok) throw new ZenoError("server_error", `The route answered ${response.status} when asked to clear its cookie`);
114
- };
115
- //#endregion
116
- //#region src/browser/index.ts
117
- const withTimeout = (promise, ms, makeError) => {
118
- let timer;
119
- return Promise.race([promise, new Promise((_, reject) => {
120
- timer = setTimeout(() => reject(makeError()), ms);
121
- })]).finally(() => clearTimeout(timer));
122
- };
123
- const toFailedIdentification = (error) => ({
124
- requestId: void 0,
125
- error: toZenoError(error)
126
- });
127
- const withOwnError = (identification) => {
128
- return identification.error ? {
129
- ...identification,
130
- error: toZenoError(identification.error)
131
- } : identification;
132
- };
133
- const makeServerStub = () => ({
134
- identify: () => Promise.resolve(toFailedIdentification(new ZenoError("not_in_browser"))),
135
- stop() {}
136
- });
137
- const makeChallengeTokenRefresh = (endpoint) => async () => {
138
- try {
139
- const module = await importModule(`${endpoint}?challenge=${Date.now()}`);
140
- return toChallengeToken(module?.challengeToken);
141
- } catch {
142
- return;
143
- }
144
- };
145
- const explainLoadFailure = async (endpoint) => {
146
- const fallback = new ZenoError("script_load_failed", `The script couldn't be loaded from ${endpoint}: check that your proxy route answers there`);
147
- try {
148
- const response = await fetch(endpoint, { credentials: "same-origin" });
149
- if (response.ok) {
150
- await response.body?.cancel();
151
- return /javascript/i.test(response.headers.get("content-type") ?? "") ? fallback : new ZenoError("script_load_failed", `${endpoint} didn't answer with the script; check the endpoint`);
152
- }
153
- const body = await response.json().catch(() => void 0);
154
- const code = typeof body?.error === "string" ? body.error : void 0;
155
- if (code === "invalid_api_key") return new ZenoError("server_error", REFUSED_KEY);
156
- if (code === "account_closed") return new ZenoError("account_closed");
157
- return code || response.status >= 500 ? new ZenoError("server_error", `The route at ${endpoint} answered ${response.status}${code ? ` ${code}` : ""} for the script`) : new ZenoError("script_load_failed", `The route at ${endpoint} answered ${response.status}: check that your proxy route answers there`);
158
- } catch {
159
- return fallback;
160
- }
161
- };
162
- const loadAgent = async (endpoint, isStopped, onStarted) => {
163
- const cspWatcher = watchCsp(new URL(endpoint).origin);
164
- let module;
165
- try {
166
- module = await importModule(endpoint);
167
- } catch {
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
- } finally {
171
- cspWatcher.stop();
172
- }
173
- if (isStopped()) throw new ZenoError("stopped");
174
- if (typeof module?.start !== "function") throw new ZenoError("script_load_failed", `${endpoint} didn't answer with the script; check the endpoint`);
175
- try {
176
- const agent = module.start(new URL(endpoint).pathname, {
177
- challengeToken: toChallengeToken(module.challengeToken),
178
- refreshChallengeToken: makeChallengeTokenRefresh(endpoint)
179
- });
180
- onStarted(agent);
181
- return agent;
182
- } catch (error) {
183
- throw toZenoError(error);
184
- }
185
- };
186
- /**
187
- * Loads Zeno's script from your proxy route and starts gathering signals; nothing is sent until `identify()`.
188
- *
189
- * @param path The path on this site you mounted `createProxy` at, `/zeno` by default, without a query string or
190
- * fragment. The script loads from it and identifies through it.
191
- */
192
- const start = (path) => {
193
- if (typeof document === "undefined") return makeServerStub();
194
- const endpoint = checkProxyEndpoint(path);
195
- let isStopped = false;
196
- let runningAgent;
197
- let rejectOnStop = () => {};
198
- const stopSignal = new Promise((_, reject) => {
199
- rejectOnStop = reject;
200
- });
201
- stopSignal.catch(() => {});
202
- const agentLoading = loadAgent(endpoint, () => isStopped, (agent) => runningAgent = agent);
203
- agentLoading.catch(() => {});
204
- const identify = async (identifyOptions) => {
205
- if (isStopped) throw new ZenoError("stopped");
206
- checkIdentifyOptions(identifyOptions);
207
- const timeout = IDENTIFY_TIMEOUT;
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
- ...identifyOptions,
214
- timeout: timeLeft
215
- }));
216
- };
217
- return {
218
- identify: (identifyOptions = {}) => identify(identifyOptions).catch(toFailedIdentification),
219
- stop() {
220
- if (!isStopped) {
221
- isStopped = true;
222
- rejectOnStop(new ZenoError("stopped"));
223
- }
224
- if (runningAgent) runningAgent.stop();
225
- else clearVisitorCookie(endpoint).catch(() => {});
226
- }
227
- };
228
- };
229
- //#endregion
230
- export { ZenoError, forget, start };
1
+ const e={client_timeout:`Client timeout`,network_connection:`Network connection error`,csp_block:`Blocked by the Content Security Policy`,insecure_context:`Zeno needs a secure context (https)`,collection_failed:`Collecting the browser data failed`,invalid_options:`The options are invalid`,server_error:`The identification api failed`,account_closed:`The project's organization is closed; contact Zeno support to reopen it`,script_load_failed:`The script couldn't be loaded from the endpoint`,stopped:`Identification was stopped; call start() again to identify`,capped:`Nothing was identified: a spend limit or rate limit was reached`,not_in_browser:`Zeno identifies in the browser only; this ran on the server`};var t=class extends Error{code;constructor(t,n){super(n??e[t]),this.code=t,this.name=`ZenoError`}};const n=n=>{if(n instanceof t)return n;let{name:r,code:i,message:a}=typeof n==`object`&&n?n:{},o=typeof a==`string`?a:void 0;return r===`ZenoError`&&typeof i==`string`&&i in e?new t(i,o):new t(`collection_failed`,o)},r=e=>{let n=!1,r=t=>{t.blockedURI.startsWith(e)&&(n=!0)};return globalThis.document?.addEventListener(`securitypolicyviolation`,r),{errorFor:async(e,r)=>(await new Promise(e=>setTimeout(e,0)),n?new t(`csp_block`,r):e),stop:()=>globalThis.document?.removeEventListener(`securitypolicyviolation`,r)}},i=e=>import(
2
+ /* @vite-ignore */
3
+ /* webpackIgnore: true */
4
+ e),a=e=>new t(`invalid_options`,e),o=e=>{if(typeof e==`string`&&/^\/(?![/\\])[^?#\\]*$/.test(e))try{let t=new URL(globalThis.location.href),n=new URL(e,t);return n.origin===t.origin?`${n.origin}${n.pathname}`:void 0}catch{return}},s=e=>typeof e==`string`&&e.length>0&&e.length<=200?e:void 0,c=(e,t=`start`)=>{let n=o(e??`/zeno`);if(!n)throw a(`${t}() takes your proxy route's path on this site, like ${t}('/zeno')`);return n},l=e=>{if(typeof e!=`object`||!e)throw a(`Pass the identify() options as an object: identify({ externalId, action })`);let{externalId:t,action:n,metadata:r}=e;if(t!==void 0&&(typeof t!=`string`||!t||t.length>256))throw a(`externalId must be a string of 1 to 256 characters`);if(t===`.`||t===`..`)throw a(`externalId can’t be . or ..`);if(n!==void 0&&(typeof n!=`string`||n.length>1024))throw a(`action must be a string of at most 1,024 characters`);if(r!==void 0&&(typeof r!=`object`||!r||Array.isArray(r)))throw a(`metadata must be an object of keys and values, like { orderId: 'A-1042' }`)},u=e=>`zeno:id:${new URL(e).pathname}`,d=()=>{try{return globalThis.localStorage??void 0}catch{return}},f=e=>{try{d()?.removeItem(u(e))}catch{}return fetch(`${e}?forget`,{method:`POST`,credentials:`same-origin`,keepalive:!0})},p=async e=>{if(typeof document>`u`)throw new t(`not_in_browser`);let n=c(e,`forget`),i=r(new URL(n).origin),a;try{a=await f(n)}catch{throw await i.errorFor(new t(`network_connection`))}finally{i.stop()}if(!a.ok)throw new t(`server_error`,`The route answered ${a.status} when asked to clear its cookie`)},m=(e,t,n)=>{let r;return Promise.race([e,new Promise((e,i)=>{r=setTimeout(()=>i(n()),t)})]).finally(()=>clearTimeout(r))},h=e=>({requestId:void 0,error:n(e)}),g=e=>e.error?{...e,error:n(e.error)}:e,_=()=>({identify:()=>Promise.resolve(h(new t(`not_in_browser`))),stop(){}}),v=e=>async()=>{try{let t=await i(`${e}?challenge=${Date.now()}`);return s(t?.challengeToken)}catch{return}},y=async e=>{let n=new t(`script_load_failed`,`The script couldn't be loaded from ${e}: check that your proxy route answers there`);try{let r=await fetch(e,{credentials:`same-origin`});if(r.ok)return await r.body?.cancel(),/javascript/i.test(r.headers.get(`content-type`)??``)?n:new t(`script_load_failed`,`${e} didn't answer with the script; check the endpoint`);let i=await r.json().catch(()=>void 0),a=typeof i?.error==`string`?i.error:void 0;return a===`invalid_api_key`?new t(`server_error`,`The proxy route's API key was refused: check the API key the route on your server is set up with`):a===`account_closed`?new t(`account_closed`):a||r.status>=500?new t(`server_error`,`The route at ${e} answered ${r.status}${a?` ${a}`:``} for the script`):new t(`script_load_failed`,`The route at ${e} answered ${r.status}: check that your proxy route answers there`)}catch{return n}},b=async(e,a,o)=>{let c=r(new URL(e).origin),l;try{l=await i(e)}catch{let n=await c.errorFor(new t(`script_load_failed`),`The page's Content Security Policy blocked loading the script from ${e}: allow it in script-src`);throw n.code===`csp_block`?n:await y(e)}finally{c.stop()}if(a())throw new t(`stopped`);if(typeof l?.start!=`function`)throw new t(`script_load_failed`,`${e} didn't answer with the script; check the endpoint`);try{let t=l.start(new URL(e).pathname,{challengeToken:s(l.challengeToken),refreshChallengeToken:v(e)});return o(t),t}catch(e){throw n(e)}},x=e=>{if(typeof document>`u`)return _();let n=c(e),r=!1,i,a=()=>{},o=new Promise((e,t)=>{a=t});o.catch(()=>{});let s=b(n,()=>r,e=>i=e);s.catch(()=>{});let u=async e=>{if(r)throw new t(`stopped`);l(e);let n=1e4,i=performance.now(),a=await m(Promise.race([s,o]),n,()=>new t(`client_timeout`)),c=Math.max(1,n-(performance.now()-i));if(r)throw new t(`stopped`);return g(await a.identify({...e,timeout:c}))};return{identify:(e={})=>u(e).catch(h),stop(){r||(r=!0,a(new t(`stopped`))),i?i.stop():f(n).catch(()=>{})}}};export{t as ZenoError,p as forget,x as start};