zeno.id 0.6.0 → 0.8.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 +105 -126
- package/dist/index.cjs +2 -2
- package/dist/index.d.cts +27 -39
- package/dist/index.d.ts +27 -39
- package/dist/index.js +2 -2
- package/dist/server/index.cjs +1 -2
- package/dist/server/index.d.cts +328 -171
- package/dist/server/index.d.ts +328 -171
- package/dist/server/index.js +1 -2
- package/package.json +1 -14
- package/dist/server/node.cjs +0 -1
- package/dist/server/node.d.cts +0 -21
- package/dist/server/node.d.ts +0 -21
- package/dist/server/node.js +0 -1
- package/dist/server/proxy-CUZ-Jwgy.d.cts +0 -36
- package/dist/server/proxy-CUZ-Jwgy.d.ts +0 -36
package/dist/index.d.cts
CHANGED
|
@@ -10,7 +10,12 @@ declare class ZenoError extends Error {
|
|
|
10
10
|
type Metadata = Record<string, string | number | boolean>;
|
|
11
11
|
type IdentifyOptions = {
|
|
12
12
|
/**
|
|
13
|
-
*
|
|
13
|
+
* The path on this site your proxy route answers at (`createProxyResponse`), `/zeno` by default, without a query
|
|
14
|
+
* string or fragment. Pass the same one to `preload()`.
|
|
15
|
+
*/
|
|
16
|
+
path?: string;
|
|
17
|
+
/**
|
|
18
|
+
* Your own id for whoever is behind the browser, like a user id, to look visitors up by later. 1 to 256 bytes;
|
|
14
19
|
* anything else is refused with `invalid_options` before anything is sent.
|
|
15
20
|
*/
|
|
16
21
|
externalId?: string;
|
|
@@ -24,17 +29,11 @@ type IdentifyOptions = {
|
|
|
24
29
|
metadata?: Metadata;
|
|
25
30
|
};
|
|
26
31
|
type Identification = {
|
|
27
|
-
/** Left out when the project runs in zero trust mode: only your backend learns the visitor. */
|
|
28
|
-
visitorId?: string;
|
|
29
32
|
/**
|
|
30
33
|
* Send it to your server with the action, where `verify` from `zeno.id/server` says to allow, challenge or
|
|
31
|
-
* block.
|
|
34
|
+
* block, and gives the event with its visitor ID. The browser never learns the visitor ID.
|
|
32
35
|
*/
|
|
33
36
|
requestId: string;
|
|
34
|
-
/** Whether the api had seen this visitor before; left out in zero trust mode. */
|
|
35
|
-
returning?: boolean;
|
|
36
|
-
/** The event encrypted with the project's key, when the project seals results. */
|
|
37
|
-
sealedResult?: string;
|
|
38
37
|
error?: undefined;
|
|
39
38
|
} | {
|
|
40
39
|
/**
|
|
@@ -44,44 +43,33 @@ type Identification = {
|
|
|
44
43
|
requestId?: undefined;
|
|
45
44
|
/**
|
|
46
45
|
* Why, by its `code`: a failure, `stopped`, `not_in_browser` on the server, or `capped` (a spend limit you
|
|
47
|
-
* set, the
|
|
46
|
+
* set, the visitor ip's rate limit, or the month's free identifications used without billing details; not a
|
|
47
|
+
* bot).
|
|
48
48
|
*/
|
|
49
49
|
error: ZenoError;
|
|
50
|
-
visitorId?: undefined;
|
|
51
|
-
returning?: undefined;
|
|
52
|
-
sealedResult?: undefined;
|
|
53
|
-
};
|
|
54
|
-
type Zeno = {
|
|
55
|
-
/**
|
|
56
|
-
* Identifies the browser: sends the report through the proxy route and answers the request ID. It never rejects:
|
|
57
|
-
* when nothing was identified it resolves `{ requestId: undefined, error }`.
|
|
58
|
-
*/
|
|
59
|
-
identify(options?: IdentifyOptions): Promise<Identification>;
|
|
60
|
-
/**
|
|
61
|
-
* Stops identifying for good, as when the visitor withdraws consent: nothing more is collected or sent, an
|
|
62
|
-
* identify() in progress and every later one answer the `stopped` error, and the route is asked to clear its
|
|
63
|
-
* visitor cookie. A script still loading never starts. Call start() again to identify once consent is given again.
|
|
64
|
-
*/
|
|
65
|
-
stop(): void;
|
|
66
50
|
};
|
|
67
51
|
//#endregion
|
|
68
|
-
//#region src/browser/
|
|
52
|
+
//#region src/browser/index.d.ts
|
|
69
53
|
/**
|
|
70
|
-
*
|
|
71
|
-
*
|
|
72
|
-
*
|
|
54
|
+
* Loads Zeno's script from your proxy route and starts gathering signals, so a later `identify()` is quick; nothing is
|
|
55
|
+
* sent until `identify()`. Optional, and once a page: calling it again for the same path does nothing. On the server it
|
|
56
|
+
* does nothing.
|
|
73
57
|
*
|
|
74
|
-
* @param path The
|
|
58
|
+
* @param path The path on this site your proxy route answers at, like `/zeno` (the default), without a query string or
|
|
59
|
+
* fragment. Pass `identify()` the same one.
|
|
75
60
|
*/
|
|
76
|
-
declare const
|
|
77
|
-
//#endregion
|
|
78
|
-
//#region src/browser/index.d.ts
|
|
61
|
+
declare const preload: (path?: string) => void;
|
|
79
62
|
/**
|
|
80
|
-
*
|
|
81
|
-
*
|
|
82
|
-
*
|
|
83
|
-
|
|
63
|
+
* Identifies the browser: sends the report through your proxy route and answers the request ID, loading the script
|
|
64
|
+
* first when `preload()` didn't. It never rejects: when nothing was identified it resolves `{ requestId: undefined,
|
|
65
|
+
* error }`, with `not_in_browser` on the server.
|
|
66
|
+
*/
|
|
67
|
+
declare const identify: (options?: IdentifyOptions) => Promise<Identification>;
|
|
68
|
+
/**
|
|
69
|
+
* For a visitor who withdraws consent: stops the script (an `identify()` in progress answers `stopped`) and deletes the
|
|
70
|
+
* visitor ID this browser keeps, the `zeno_id` cookie. A later `preload()` or `identify()` starts again. On the server
|
|
71
|
+
* it does nothing.
|
|
84
72
|
*/
|
|
85
|
-
declare const
|
|
73
|
+
declare const forget: () => void;
|
|
86
74
|
//#endregion
|
|
87
|
-
export { type Identification, type IdentifyOptions, type Metadata,
|
|
75
|
+
export { type Identification, type IdentifyOptions, type Metadata, ZenoError, type ZenoErrorCode, forget, identify, preload };
|
package/dist/index.d.ts
CHANGED
|
@@ -10,7 +10,12 @@ declare class ZenoError extends Error {
|
|
|
10
10
|
type Metadata = Record<string, string | number | boolean>;
|
|
11
11
|
type IdentifyOptions = {
|
|
12
12
|
/**
|
|
13
|
-
*
|
|
13
|
+
* The path on this site your proxy route answers at (`createProxyResponse`), `/zeno` by default, without a query
|
|
14
|
+
* string or fragment. Pass the same one to `preload()`.
|
|
15
|
+
*/
|
|
16
|
+
path?: string;
|
|
17
|
+
/**
|
|
18
|
+
* Your own id for whoever is behind the browser, like a user id, to look visitors up by later. 1 to 256 bytes;
|
|
14
19
|
* anything else is refused with `invalid_options` before anything is sent.
|
|
15
20
|
*/
|
|
16
21
|
externalId?: string;
|
|
@@ -24,17 +29,11 @@ type IdentifyOptions = {
|
|
|
24
29
|
metadata?: Metadata;
|
|
25
30
|
};
|
|
26
31
|
type Identification = {
|
|
27
|
-
/** Left out when the project runs in zero trust mode: only your backend learns the visitor. */
|
|
28
|
-
visitorId?: string;
|
|
29
32
|
/**
|
|
30
33
|
* Send it to your server with the action, where `verify` from `zeno.id/server` says to allow, challenge or
|
|
31
|
-
* block.
|
|
34
|
+
* block, and gives the event with its visitor ID. The browser never learns the visitor ID.
|
|
32
35
|
*/
|
|
33
36
|
requestId: string;
|
|
34
|
-
/** Whether the api had seen this visitor before; left out in zero trust mode. */
|
|
35
|
-
returning?: boolean;
|
|
36
|
-
/** The event encrypted with the project's key, when the project seals results. */
|
|
37
|
-
sealedResult?: string;
|
|
38
37
|
error?: undefined;
|
|
39
38
|
} | {
|
|
40
39
|
/**
|
|
@@ -44,44 +43,33 @@ type Identification = {
|
|
|
44
43
|
requestId?: undefined;
|
|
45
44
|
/**
|
|
46
45
|
* Why, by its `code`: a failure, `stopped`, `not_in_browser` on the server, or `capped` (a spend limit you
|
|
47
|
-
* set, the
|
|
46
|
+
* set, the visitor ip's rate limit, or the month's free identifications used without billing details; not a
|
|
47
|
+
* bot).
|
|
48
48
|
*/
|
|
49
49
|
error: ZenoError;
|
|
50
|
-
visitorId?: undefined;
|
|
51
|
-
returning?: undefined;
|
|
52
|
-
sealedResult?: undefined;
|
|
53
|
-
};
|
|
54
|
-
type Zeno = {
|
|
55
|
-
/**
|
|
56
|
-
* Identifies the browser: sends the report through the proxy route and answers the request ID. It never rejects:
|
|
57
|
-
* when nothing was identified it resolves `{ requestId: undefined, error }`.
|
|
58
|
-
*/
|
|
59
|
-
identify(options?: IdentifyOptions): Promise<Identification>;
|
|
60
|
-
/**
|
|
61
|
-
* Stops identifying for good, as when the visitor withdraws consent: nothing more is collected or sent, an
|
|
62
|
-
* identify() in progress and every later one answer the `stopped` error, and the route is asked to clear its
|
|
63
|
-
* visitor cookie. A script still loading never starts. Call start() again to identify once consent is given again.
|
|
64
|
-
*/
|
|
65
|
-
stop(): void;
|
|
66
50
|
};
|
|
67
51
|
//#endregion
|
|
68
|
-
//#region src/browser/
|
|
52
|
+
//#region src/browser/index.d.ts
|
|
69
53
|
/**
|
|
70
|
-
*
|
|
71
|
-
*
|
|
72
|
-
*
|
|
54
|
+
* Loads Zeno's script from your proxy route and starts gathering signals, so a later `identify()` is quick; nothing is
|
|
55
|
+
* sent until `identify()`. Optional, and once a page: calling it again for the same path does nothing. On the server it
|
|
56
|
+
* does nothing.
|
|
73
57
|
*
|
|
74
|
-
* @param path The
|
|
58
|
+
* @param path The path on this site your proxy route answers at, like `/zeno` (the default), without a query string or
|
|
59
|
+
* fragment. Pass `identify()` the same one.
|
|
75
60
|
*/
|
|
76
|
-
declare const
|
|
77
|
-
//#endregion
|
|
78
|
-
//#region src/browser/index.d.ts
|
|
61
|
+
declare const preload: (path?: string) => void;
|
|
79
62
|
/**
|
|
80
|
-
*
|
|
81
|
-
*
|
|
82
|
-
*
|
|
83
|
-
|
|
63
|
+
* Identifies the browser: sends the report through your proxy route and answers the request ID, loading the script
|
|
64
|
+
* first when `preload()` didn't. It never rejects: when nothing was identified it resolves `{ requestId: undefined,
|
|
65
|
+
* error }`, with `not_in_browser` on the server.
|
|
66
|
+
*/
|
|
67
|
+
declare const identify: (options?: IdentifyOptions) => Promise<Identification>;
|
|
68
|
+
/**
|
|
69
|
+
* For a visitor who withdraws consent: stops the script (an `identify()` in progress answers `stopped`) and deletes the
|
|
70
|
+
* visitor ID this browser keeps, the `zeno_id` cookie. A later `preload()` or `identify()` starts again. On the server
|
|
71
|
+
* it does nothing.
|
|
84
72
|
*/
|
|
85
|
-
declare const
|
|
73
|
+
declare const forget: () => void;
|
|
86
74
|
//#endregion
|
|
87
|
-
export { type Identification, type IdentifyOptions, type Metadata,
|
|
75
|
+
export { type Identification, type IdentifyOptions, type Metadata, ZenoError, type ZenoErrorCode, forget, identify, preload };
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
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
|
|
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 by forget()`,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
2
|
/* @vite-ignore */
|
|
3
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=
|
|
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=>{let t=o(e??`/zeno`);if(!t)throw a(`The path is your proxy route's path on this site, like '/zeno'`);return t},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||new TextEncoder().encode(t).length>256))throw a(`externalId must be a string of 1 to 256 bytes`);if(t!==void 0&&/[\p{Cc}\p{Cs}]/u.test(t))throw a(`externalId can’t hold control 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=()=>{try{document.cookie=`zeno_id=; Max-Age=0; Path=/; SameSite=Lax`}catch{}},d=(e,t,n)=>{let r;return Promise.race([e,new Promise((e,i)=>{r=setTimeout(()=>i(n()),t)})]).finally(()=>clearTimeout(r))},f=e=>({requestId:void 0,error:n(e)}),p=e=>e.error?{...e,error:n(e.error)}:e,m=e=>async()=>{try{let t=await i(`${e}?challenge=${Date.now()}`);return s(t?.challengeToken)}catch{return}},h=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}},g=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 h(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:m(e)});return o(t),t}catch(e){throw n(e)}},_=/* @__PURE__ */ new Map,v=(e,n)=>{let r=!1,i,a=()=>{},o=new Promise((e,t)=>{a=t});o.catch(()=>{});let s=g(e,()=>r,e=>i=e);return s.catch(n),{identify:async e=>{let n=1e4,i=performance.now(),a=await d(Promise.race([s,o]),n,()=>new t(`client_timeout`)),c=Math.max(1,n-(performance.now()-i));if(r)throw new t(`stopped`);return p(await a.identify({...e,timeout:c}))},stop(){r=!0,a(new t(`stopped`)),i?.stop()}}},y=e=>{let t=_.get(e);if(t)return t;let n=v(e,()=>{_.get(e)===n&&_.delete(e)});return _.set(e,n),n},b=e=>{typeof document<`u`&&y(c(e))},x=async(e={})=>{try{if(typeof document>`u`)throw new t(`not_in_browser`);return l(e),await y(c(e.path)).identify(e)}catch(e){return f(e)}},S=()=>{for(let e of _.values())e.stop();_.clear(),typeof document<`u`&&u()};export{t as ZenoError,S as forget,x as identify,b as preload};
|
package/dist/server/index.cjs
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=e=>typeof e==`object`&&!!e&&!Array.isArray(e),t=(e,t,n=`https://api.zeno.id`)=>{if(!t)return{problem:`${e}'s apiKey is missing: pass your API key (ZENO_API_KEY in your environment)`};if(!n)return{problem:`${e}'s apiUrl is missing: this copy of zeno.id/server has no default, so pass the Zeno API's origin as apiUrl`};try{if([`http:`,`https:`].includes(new URL(n).protocol))return{apiKey:t,base:n.replace(/\/+$/,``)}}catch{}return{problem:`${e}'s apiUrl must be the Zeno API's http(s) origin, like https://api.example.com, not ${JSON.stringify(n)}`}},n=e=>{if(!e.includes(`:`))return e;let t=e.match(/^(?:::|(?:0{1,4}:){5})ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i);if(t)return t[1];let[n=``,r=``]=e.split(`::`),i=n?n.split(`:`):[],a=r?r.split(`:`):[],o=Math.max(0,8-i.length-a.length),s=[...i,...Array.from({length:o},()=>`0`),...a].map(e=>e.toLowerCase().replace(/^0+(?=\w)/,``));if(s.slice(0,5).every(e=>e===`0`)&&s[5]===`ffff`){let[e=0,t=0]=s.slice(6).map(e=>parseInt(e,16));return[e>>8,e&255,t>>8,t&255].join(`.`)}return s.slice(0,4).join(`:`)},r=(e,t)=>{let r=t.trim();return e.includes(`:`)===r.includes(`:`)&&n(e)!==n(r)},i=(e,t)=>{let n=0,r=!1;for(let i=0;i<e.length;i++){let a=e[i];if(r)a===`\\`?i++:a===`"`&&(r=!1);else if(a===`"`)r=!0;else if(a===`{`||a===`[`){if(++n>t)return!0}else(a===`}`||a===`]`)&&n--}return!1},a=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`),o=e=>{let t=e?.rawHeaders;return a(t)?t:void 0},s=`zeno_id`,c=1e4,l=(e,t,n={})=>new Response(JSON.stringify(t),{status:e,headers:{"content-type":`application/json; charset=utf-8`,"cache-control":`no-store`,...n}}),u=e=>l(400,{error:`invalid_request`,message:e}),d=(e,t=500)=>l(t,{error:`server_error`,message:e}),f=`Pass the IP address the request came from: zeno(request, ip)`,p=async(e,t)=>{if(Number(e.headers.get(`content-length`))>t)return;if(!e.body)return``;let n=e.body.getReader(),r=[],i=0;for(;;){let{done:e,value:a}=await n.read();if(e)break;if(i+=a.byteLength,i>t){await n.cancel();return}r.push(a)}let a=new Uint8Array(i),o=0;for(let e of r)a.set(e,o),o+=e.byteLength;return new TextDecoder().decode(a)},m=e=>{for(let t of e.split(`;`)){let e=t.indexOf(`=`);if(e!==-1&&t.slice(0,e).trim()===s)return t.slice(e+1).trim()}},h=(e,t)=>{if(!t)return Array.from(e.headers.entries());let n=[];for(let e=0;e+1<t.length;e+=2)n.push([t[e],t[e+1]]);return n},g=/* @__PURE__ */ new Set([`user-agent`,`origin`,`signature-agent`,`signature-input`]),_=e=>e.map(([e,t])=>[e,g.has(e.toLowerCase())?t:``]),v=e=>{for(let[t,n]of e){let e=t.toLowerCase()===`cookie`?m(n):void 0;if(e!==void 0)return/^[A-Za-z0-9]{20}$/.test(e)?e:void 0}},y=e=>e?.trim().replace(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i,`$1`)||void 0,b=(e,t,n,r=e.pathname)=>{let i=[`localhost`,`127.0.0.1`,`[::1]`].includes(e.hostname)||e.hostname.endsWith(`.localhost`),a=e.protocol===`http:`&&i?``:`; Secure`,o=r.replace(/[;,\s]/g,encodeURIComponent);return`${s}=${t}; Max-Age=${n}; Path=${o}; HttpOnly${a}; SameSite=Lax`},x=e=>(e.headers.get(`accept-encoding`)??``).split(`,`).some(e=>{let[t=``,...n]=e.split(`;`).map(e=>e.trim().toLowerCase()),r=n.find(e=>e.startsWith(`q=`));return(t===`gzip`||t===`*`)&&!(r&&Number(r.slice(2))===0)}),S=t=>e(t)?t.capped===!0||typeof t.requestId==`string`&&[`undefined`,`string`].includes(typeof t.visitorId)&&[`undefined`,`boolean`].includes(typeof t.returning)&&[`undefined`,`string`].includes(typeof t.sealedResult):!1,C=t=>{if(!e(t))return;let{value:n,maxAge:r}=t;return typeof n==`string`&&/^[A-Za-z0-9]{1,64}$/.test(n)&&typeof r==`number`&&Number.isInteger(r)&&r>=0?{value:n,maxAge:r}:void 0},w=e=>new Response(new Blob([e]).stream().pipeThrough(new CompressionStream(`gzip`))).arrayBuffer(),T=async(e,t,n)=>{let r={"content-type":`text/javascript; charset=utf-8`,"cache-control":n,vary:`accept-encoding`},i=typeof t==`string`?t:t.code;if(!x(e)||typeof CompressionStream!=`function`)return new Response(i,{headers:r});let a=typeof t==`string`?w(i):t.gzipped??=w(i);return new Response(await a,{headers:{...r,"content-encoding":`gzip`}})},E=(e,t)=>[`const code = await import(new URL(${JSON.stringify(`?${new URLSearchParams({v:e})}`)}, import.meta.url))`,`export const challengeToken = ${t}`,`const own = new URL(import.meta.url)`,`const refreshChallengeToken = () => import(new URL("?challenge=" + Date.now(), own)).then(module => module.challengeToken, () => undefined)`,`export const start = (path = own.pathname, options) => code.start(path, { challengeToken, refreshChallengeToken, ...options })`,``].join(`
|
|
2
|
-
`),D=(n,r={})=>{let{apiUrl:a,cookiePath:s,fetch:m=globalThis.fetch}=r,g,x=``,w=``,D=async(e,t)=>{try{return await m(`${w}${e}`,{...t,signal:AbortSignal.timeout(c)})}catch(t){let n=t instanceof Error&&t.name===`TimeoutError`?`no answer within ${c} ms`:String(t);console.error(`The proxy route couldn't reach Zeno at ${w}${e}: ${n}`);return}},O=async(t,n)=>{let r=await t.json().catch(()=>void 0),i=e(r)&&typeof r.error==`string`?r.error:void 0,a=e(r)&&typeof r.message==`string`?r.message:void 0;if(t.status===401)return console.error(`Zeno refused the proxy route's API key (401${i?` ${i}`:``}${a?`: ${a}`:``}): check createProxy's apiKey`),l(401,{error:`invalid_api_key`,message:`Zeno refused the proxy route's API key; the route's server log says more`});if(!i)return console.error(`Zeno answered the proxy route's ${n} call with ${t.status} without an error code`),d(`Zeno answered ${t.status}`,502);i===`account_closed`&&console.error(`Zeno closed this project's organization (402 account_closed): contact Zeno support`);let o=t.headers.get(`retry-after`);return l(t.status,{error:i,...a?{message:a}:{}},o?{"retry-after":o}:{})},k=()=>d(`Zeno could not be reached`,502),A=async e=>{let t=g,n=t?`/script?${new URLSearchParams({v:t.etag})}`:`/script`,r=await D(n,{headers:{"auth-api-key":x,...t?{"if-none-match":t.etag}:{},...e?{"zeno-visitor-ip":e}:{}}});if(!r)return{failed:k()};if(r.status!==304&&!r.ok)return{failed:await O(r,`/script`)};let i=r.headers.get(`zeno-challenge-token`),a=i?JSON.stringify(i):`undefined`;if(r.status===304)return t?{script:t,challengeToken:a}:{failed:d(`Zeno answered 304 for code this route never had`)};let o=await r.text().catch(()=>void 0);if(o===void 0)return{failed:k()};let s=r.headers.get(`etag`);return g=s?{etag:s,code:o}:void 0,{script:g??{code:o},challengeToken:a}},j=async(e,t)=>{let n=await A(t);if(n.failed)return n.failed;let{script:r,challengeToken:i}=n;return r.etag===void 0?T(e,`${r.code}\nexport const challengeToken = ${i}\n`,`private, max-age=60`):T(e,E(r.etag,i),`private, max-age=60`)},M=async(e,t)=>{let n=g;if(n?.etag!==t){let e=await A(void 0);if(e.failed)return e.failed;n=e.script}return T(e,n,n.etag===t?`private, max-age=31536000, immutable`:`no-store`)},N=(e,t)=>{let n=new URL(e.url).searchParams.get(`v`);return n===null?j(e,t):M(e,n)},P=async(t,n,r)=>{if(!/^application\/json\s*(;|$)/i.test(t.headers.get(`content-type`)??``))return u(`The body must be JSON`);if(t.headers.get(`sec-fetch-site`)?.toLowerCase()===`cross-site`)return u(`Cross-site requests are refused`);let a=await p(t,131072);if(a===void 0)return u(`The body is larger than 128 KB`);if(i(a,64))return u(`The body nests deeper than 64 levels`);let c;try{c=JSON.parse(a)}catch{return u(`The body is not valid JSON`)}if(!e(c)||!e(c.browserData))return u(`The body has no browserData`);if(!n)return console.error(`The proxy route got no IP address: ${f}, or nodeHandler(zeno) on Node`),d(f);let m=h(t,o(r)),g=v(m),y={...g?{visitorId:g}:{},ip:n,headers:_(m),payload:c},w=await D(`/identify`,{method:`POST`,headers:{"auth-api-key":x,"content-type":`application/json`},body:JSON.stringify(y)});if(!w)return k();if(!w.ok)return O(w,`/identify`);let T=await w.json().catch(()=>void 0);if(!e(T)||!S(T.result))return console.error(`Zeno's answer to the proxy route's identification couldn't be read`),d(`Zeno's answer couldn't be read`,502);let E=C(T.cookie);return l(200,T.result,E?{"set-cookie":b(new URL(t.url),E.value,E.maxAge,s)}:{})};return async(e,r,i)=>{let o=new URL(e.url);if(e.method===`POST`&&o.searchParams.has(`forget`))return new Response(null,{status:204,headers:{"set-cookie":b(o,``,0,s)}});if(![`GET`,`HEAD`,`POST`].includes(e.method))return l(405,{error:`method_not_allowed`,message:`Use GET or POST`},{allow:`GET, HEAD, POST`});let c=t(`createProxy`,n,a);if(c.problem!==void 0)return console.error(c.problem),d(`The proxy route isn't set up; its server log says what's missing`);x=c.apiKey,w=c.base;let u=y(r);if(e.method===`POST`)return P(e,u,i);let f=await N(e,u);return e.method===`HEAD`?(await f.body?.cancel(),new Response(null,{status:f.status,headers:f.headers})):f}},O=[`automation`,`headless`,`software-renderer`,`tampering`,`timezone-mismatch`,`privacy-settings`,`vpn`,`proxy`,`tor`,`datacenter`,`abusive-ip`,`incognito`,`virtual-machine`,`developer-tools`,`ai-agent`,`privacy-browser`,`high-activity`,`replayed`,`residential-proxy`,`private-relay`,`forged-payload`,`stored-id-rejected`,`storage-cleared`],k=1e4;var A=class extends Error{status;code;retryAfter;constructor(e,t,n,r){super(n??t),this.status=e,this.code=t,this.retryAfter=r,this.name=`ZenoError`}};const j=(e,t)=>{if(!e)throw TypeError(t);return e},M=e=>{if(e===null)return;let t=/^\d+$/.test(e.trim())?Number(e):(Date.parse(e)-Date.now())/1e3;return Number.isFinite(t)?Math.min(Math.max(t,0),60):void 0},N=e=>new Promise(t=>setTimeout(t,e*1e3)),P=(e,t)=>{if(typeof t!=`string`||!t||t===`.`||t===`..`)throw new A(0,`invalid_request`,`${e} must be a non-empty string`);return encodeURIComponent(t)},F=(t,n)=>n===`array`?Array.isArray(t):n===`object`?e(t):typeof t===n,I=(t,n)=>({name:t,is:t=>e(t)&&Object.entries(n).every(([e,n])=>F(t[e],n))}),L=I(`an event`,{requestId:`string`,visitorId:`string`,ip:`object`,createdAt:`string`,riskScore:`number`,signals:`object`,verdict:`object`}),ee=I(`a page of events`,{items:`array`}),te=I(`a visitor`,{visitorId:`string`,externalIds:`array`,externalIdCount:`number`,recentEvents:`array`}),R=I(`a reported outcome`,{requestId:`string`,outcome:`string`}),z=I(`an erasure`,{visitorId:`string`,deletedEvents:`number`}),B=I(`an erasure`,{externalId:`string`,deletedEvents:`number`}),V=I(`a relation`,{externalId:`string`,type:`string`,linkWrite:`boolean`}),H=I(`a removal`,{removed:`boolean`}),U=I(`a user's values`,{externalId:`string`,values:`array`,truncated:`boolean`}),W=I(`a page of users`,{items:`array`}),G=I(`related users`,{externalId:`string`,externalIds:`array`,connections:`array`}),K=I(`an embed`,{url:`string`,expiresAt:`string`}),q=I(`verify's answer`,{action:`string`,reasons:`array`}),J=(n,r={})=>{let{apiUrl:i,fetch:a=globalThis.fetch}=r,o=async(e,t,n,r,i)=>{try{let o=await a(`${t}${r}`,{method:n,headers:{"auth-api-key":e,...i?{"content-type":`application/json`}:{}},body:i,signal:AbortSignal.timeout(k)});return{response:o,text:await o.text()}}catch(e){throw new A(0,`network_error`,e instanceof Error&&e.name===`TimeoutError`?`Zeno didn't answer ${n} ${r.split(`?`)[0]} within ${k} ms`:`Zeno couldn't be reached at ${t}: ${e instanceof Error?e.message:String(e)}`)}},s=async(r,a,s,c,l=!1)=>{let u=t(`createClient`,n,i);if(u.problem!==void 0)throw TypeError(u.problem);let d=c&&JSON.stringify(c);for(let t=0;;t++){let n;try{n=await o(u.apiKey,u.base,r,a,d)}catch(e){if(l&&t<2){await N(1+Math.random()*.5);continue}throw e}let{response:i,text:c}=n,f;try{f=JSON.parse(c)}catch{}if(i.ok){if(f===void 0)throw new A(i.status,`request_failed`,`Zeno answered ${i.status} without JSON`);if(!s.is(f))throw new A(i.status,`request_failed`,`Zeno answered ${r} ${a.split(`?`)[0]} with something that isn't ${s.name}`);return f}let{error:p,message:m}=e(f)?f:{},h=typeof p==`string`?p:void 0,g=i.status===429||h===`search_unavailable`||l&&i.status>=500,_=g?M(i.headers.get(`retry-after`)):void 0;if(g&&t<2){let e=_??1;await N(e+Math.random()*e*.5)}else throw new A(i.status,h??`request_failed`,typeof m==`string`?m:void 0,_)}},c=(e,t)=>{for(let[n,r]of Object.entries(t))r!==void 0&&e.set(n,String(r));return e};return{verify:async(e,t={})=>{let{ip:n,externalId:r,maxAge:i,idempotencyKey:a=crypto.randomUUID()}=t;return s(`POST`,`/verify`,q,{requestId:e??void 0,ip:n||void 0,externalId:r,maxAge:i,idempotencyKey:a},!0)},getEvent:async e=>s(`GET`,`/events/${P(`requestId`,e)}`,L),searchEvents:(e={})=>{let t=new URLSearchParams;for(let[n,r]of Object.entries(e))for(let e of Array.isArray(r)?r:[r])e!==void 0&&t.append(n,e instanceof Date?e.toISOString():String(e));return s(`GET`,`/events?${t}`,ee)},getVisitor:async e=>s(`GET`,`/visitors/${P(`visitorId`,e)}`,te),reportOutcome:(e,t)=>s(`POST`,`/outcomes`,R,{requestId:e,outcome:t}),deleteVisitor:async e=>s(`DELETE`,`/visitors/${P(`visitorId`,e)}`,z),deleteExternalId:e=>{let t=new URLSearchParams({externalId:e});return s(`DELETE`,`/external-ids?${t}`,B)},addRelation:({at:e,...t})=>{let n=e instanceof Date||typeof e==`number`?new Date(e).toISOString():e;return s(`POST`,`/related`,V,{...t,...n===void 0?{}:{at:n}})},removeRelation:e=>{let t=new URLSearchParams(e);return s(`DELETE`,`/related?${t}`,H)},getRelatedValues:(e,{type:t}={})=>{let n=new URLSearchParams({externalId:e,...t?{type:t}:{}});return s(`GET`,`/related/values?${n}`,U)},lookupRelated:(e,t,n={})=>{let r=c(new URLSearchParams({type:e,value:t}),n);return s(`GET`,`/related/lookup?${r}`,W)},getRelated:(e,{type:t,depth:n=1}={})=>{let r=new URLSearchParams({externalId:e,...t?{type:t}:{},depth:String(n)});return s(`GET`,`/related?${r}`,G)},createEmbed:e=>s(`POST`,`/embeds`,K,e)}},Y=new TextEncoder,X=e=>{try{return Uint8Array.from(atob(e),e=>e.charCodeAt(0))}catch{return}},Z=e=>Array.from(new Uint8Array(e),e=>e.toString(16).padStart(2,`0`)).join(``),ne=(e,t)=>{if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0},re=async(e,t,n,{tolerance:r=300}={})=>{let i=j(n,`verifyWebhook needs the webhook secret, whsec_… (is it set in the environment?)`),a=(t??``).split(`,`).map(e=>{let[t,...n]=e.trim().split(`=`);return[t??``,n.join(`=`)]}),o=Number(a.find(([e])=>e===`t`)?.[1]),s=a.filter(([e,t])=>e===`v1`&&t).map(([,e])=>e);if(!Number.isInteger(o)||s.length===0||Math.abs(Date.now()/1e3-o)>r)return;let c=await crypto.subtle.importKey(`raw`,Y.encode(i),{name:`HMAC`,hash:`SHA-256`},!1,[`sign`]),l=Y.encode(Z(await crypto.subtle.sign(`HMAC`,c,Y.encode(`${o}.${e}`))));if(!s.map(e=>ne(Y.encode(e),l)).includes(!0))return;let u;try{u=JSON.parse(e)}catch{}if(!L.is(u))throw Error(`The webhook's body is signed but isn't an event; update zeno.id/server`);return u},Q=()=>({action:`block`,reasons:[`not-found`]}),$=`unsealResult needs the project's encryption key as key (is it set in the environment?)`,ie=e=>{let t=j(e,$).trim(),n=/^[A-Za-z0-9+/]+={0,2}$/.test(t)?X(t):void 0;if(!n)throw TypeError(`unsealResult's key isn't base64: pass the project's encryption key as the app shows it`);if(n.length!==32)throw TypeError(/^[0-9a-f]{64}$/i.test(t)?`unsealResult's key looks like hex: pass the project's encryption key as the app shows it, in base64`:`unsealResult's key is ${n.length} bytes, not 32: pass the project's encryption key as the app shows it`);return n},ae=async(e,t)=>{for(let n of e){let e=await crypto.subtle.importKey(`raw`,n,`AES-GCM`,!1,[`decrypt`]);try{return await crypto.subtle.decrypt({name:`AES-GCM`,iv:t.subarray(1,13),tagLength:128},e,t.subarray(13))}catch{}}},oe=async(e,t)=>{let n=(Array.isArray(t?.key)?t.key:[t?.key]).filter(e=>e);if(n.length===0)throw TypeError($);let i=n.map(ie);if(!e)return{action:`challenge`,reasons:[`no-request-id`]};if(typeof e!=`string`||!/^[A-Za-z0-9+/]+={0,2}$/.test(e.trim()))return Q();let a=X(e.trim());if(!a||a.length<30||a[0]!==1)return Q();let o=await ae(i,a);if(!o)return Q();let s;try{s=JSON.parse(new TextDecoder().decode(o))}catch{}if(!L.is(s))throw Error(`The sealed result opened but isn't an event; update zeno.id/server`);let c=[],l=t.maxAge??300;return t.ip&&r(s.ip.address,t.ip)&&c.push(`ip-mismatch`),Date.now()-Date.parse(s.createdAt)>l*1e3&&c.push(`too-old`),t.externalId!==void 0&&s.externalId!==void 0&&s.externalId!==t.externalId&&c.push(`external-id-mismatch`),c.length>0?{action:`block`,reasons:c,event:s}:{action:s.verdict.action,reasons:s.verdict.reasons,event:s}};exports.SIGNALS=O,exports.ZenoError=A,exports.createClient=J,exports.createProxy=D,exports.unsealResult=oe,exports.verifyWebhook=re;
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=e=>typeof e==`object`&&!!e&&!Array.isArray(e),t=(e,t,n=`https://api.zeno.id`)=>{if(!t)return{problem:`${e}'s apiKey is missing: pass your API key (ZENO_API_KEY in your environment)`};if(!n)return{problem:`${e}'s apiUrl is missing: this copy of zeno.id/server has no default, so pass the Zeno API's origin as apiUrl`};try{if([`http:`,`https:`].includes(new URL(n).protocol))return{apiKey:t,base:n.replace(/\/+$/,``)}}catch{}return{problem:`${e}'s apiUrl must be the Zeno API's http(s) origin, like https://api.example.com, not ${JSON.stringify(n)}`}},n=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`),r=e=>{let t=e.rawHeaders;return n(t)?t:void 0},i=1e4,a=[`user-agent`,`origin`,`signature-agent`,`signature-input`,`sec-fetch-site`],o=(e,t)=>new Response(JSON.stringify(t),{status:e,headers:{"content-type":`application/json; charset=utf-8`,"cache-control":`no-store`}}),s=(e,t=500)=>o(t,{error:`server_error`,message:e}),c=e=>{for(let t of e.split(`;`)){let e=t.indexOf(`=`);if(e!==-1&&t.slice(0,e).trim()===`zeno_id`)return t.slice(e+1).trim()}},l=(e,t)=>{if(!t)return Array.from(e.headers.entries());let n=[];for(let e=0;e+1<t.length;e+=2)n.push([t[e],t[e+1]]);return n},u=e=>{let t={"zeno-visitor-header-names":e.map(([e])=>e.toLowerCase()).join(`, `)};for(let[n,r]of e){let e=n.toLowerCase(),i=e===`cookie`?c(r):void 0;i&&!t[`zeno-visitor-token`]&&(t[`zeno-visitor-token`]=i),a.includes(e)&&!t[`zeno-visitor-${e}`]&&(t[`zeno-visitor-${e}`]=r)}return t},d=async e=>{if(e.status===401||e.status===402){let t=await e.clone().text().catch(()=>``);console.error(`Zeno answered the proxy route ${e.status}: ${t}`)}let t=new Headers;return e.headers.forEach((e,n)=>{n.startsWith(`zeno-browser-`)&&n.length>13&&t.append(n.slice(13),e)}),new Response(e.body?await e.arrayBuffer():null,{status:e.status,headers:t})},f=async e=>{let{request:n,ip:a,apiKey:o,apiUrl:c,fetch:f=globalThis.fetch,...p}=e,m=t(`createProxyResponse`,o,c);if(m.problem!==void 0)return console.error(m.problem),s(`The proxy route isn't set up; its server log says what's missing`);let h=`${m.base}/proxy${new URL(n.url).search}`,g=n.method!==`GET`&&n.method!==`HEAD`;try{let e=await f(h,{method:n.method,headers:{"auth-api-key":m.apiKey,...a?{"zeno-visitor-ip":a}:{},...g?{"content-type":`application/json`}:{},...u(l(n,r(p)))},...g?{body:await n.arrayBuffer()}:{},signal:AbortSignal.timeout(i)});return await d(e)}catch(e){let t=e instanceof Error&&e.name===`TimeoutError`?`no answer within ${i} ms`:String(e);return console.error(`The proxy route couldn't reach Zeno at ${h}: ${t}`),s(`Zeno could not be reached`,502)}},p=1048576,m=async e=>{let t=[],n=0;for await(let r of e){let e=typeof r==`string`?new TextEncoder().encode(r):r;n+=e.byteLength,n<=p&&t.push(e)}if(n>p)return null;let r=new Uint8Array(n),i=0;for(let e of t)r.set(e,i),i+=e.byteLength;return r},h=(e,t)=>{let n=new Headers;for(let t=0;t+1<e.rawHeaders.length;t+=2){let r=e.rawHeaders[t];r.startsWith(`:`)||n.append(r,e.rawHeaders[t+1])}let r=e.socket.encrypted?`https`:`http`,i=e.originalUrl??e.url??`/`,a=new URL(i,`${r}://${e.headers.host??`localhost`}`);return new Request(a,{method:e.method,headers:n,...t?{body:t}:{}})},g=async(e,t)=>{t.statusCode=e.status,e.headers.forEach((e,n)=>{n!==`set-cookie`&&t.setHeader(n,e)});let n=e.headers.getSetCookie();n.length>0&&t.setHeader(`set-cookie`,n),t.end(e.body?new Uint8Array(await e.arrayBuffer()):void 0)},_=e=>async(t,n)=>{let r=`raw`in t?t.raw:t,i=t.ip,a=typeof i==`string`?i:r.socket.remoteAddress,o;`hijack`in n?(n.hijack(),o=n.raw):o=n;let s=(e,t,n)=>g(new Response(JSON.stringify({error:t,message:n}),{status:e,headers:{"content-type":`application/json; charset=utf-8`,"cache-control":`no-store`}}),o);try{let t=r.method!==`GET`&&r.method!==`HEAD`;if(t&&r.readableEnded){console.error(`The proxy route found its body already read: mount nodeHandler before any body parser`),await s(500,`server_error`,`The proxy route isn't set up; its server log says what's wrong`);return}let n=t?await m(r):void 0;if(n===null){await s(413,`invalid_request`,`The body is larger than 1 MB`);return}let i={...e,request:h(r,n),ip:a,rawHeaders:r.rawHeaders};await g(await f(i),o)}catch(e){console.error(`The proxy route failed: ${e instanceof Error?e.message:String(e)}`),o.headersSent||await s(500,`server_error`,`The proxy route failed; its server log says why`)}},v=[`automation`,`headless`,`software-renderer`,`tampering`,`timezone-mismatch`,`privacy-settings`,`vpn`,`proxy`,`tor`,`datacenter`,`abusive-ip`,`incognito`,`virtual-machine`,`developer-tools`,`ai-agent`,`privacy-browser`,`high-activity`,`replayed`,`residential-proxy`,`private-relay`,`forged-payload`,`stored-id-rejected`,`storage-cleared`];var y=class extends Error{status;code;retryAfter;constructor(e,t,n,r){super(n??t),this.status=e,this.code=t,this.retryAfter=r,this.name=`ZenoError`}};const b=(e,t)=>{if(!e)throw TypeError(t);return e},x=e=>{if(e===null)return;let t=/^\d+$/.test(e.trim())?Number(e):(Date.parse(e)-Date.now())/1e3;return Number.isFinite(t)?Math.min(Math.max(t,0),60):void 0},S=e=>new Promise(t=>setTimeout(t,e*1e3)),C=(e,t)=>{if(typeof t!=`string`||!t||t===`.`||t===`..`)throw new y(0,`invalid_request`,`${e} must be a non-empty string`);return encodeURIComponent(t)},w=(t,n)=>n===`array`?Array.isArray(t):n===`object`?e(t):typeof t===n,T=(t,n)=>({name:t,is:t=>e(t)&&Object.entries(n).every(([e,n])=>w(t[e],n))}),E=T(`an event`,{requestId:`string`,visitorId:`string`,ip:`object`,createdAt:`string`,riskScore:`number`,signals:`object`,verdict:`object`}),D=T(`a page of events`,{items:`array`}),O=T(`a reported outcome`,{requestId:`string`,outcome:`string`}),k=T(`an erasure`,{visitorId:`string`,deletedEvents:`number`}),A=T(`an erasure`,{externalId:`string`,deletedEvents:`number`}),j=T(`a relation`,{externalId:`string`,type:`string`,created:`boolean`}),M=T(`a removal`,{removed:`boolean`}),N=T(`a user's values`,{externalId:`string`,values:`array`}),P=T(`a page of users`,{items:`array`}),F=T(`related users`,{externalId:`string`,externalIds:`array`,connections:`array`,sharedValues:`array`,pairs:`array`,truncated:`boolean`,widelyShared:`array`,stoppedAt:`array`}),I=T(`the weights`,{items:`array`}),L=T(`a weight`,{type:`string`,weight:`number`,defaultWeight:`number`}),R=T(`a user's group`,{externalId:`string`,size:`number`,externalIds:`array`}),z=T(`a group`,{groupId:`string`,size:`number`,externalIds:`array`}),B=T(`an embed`,{url:`string`,expiresAt:`string`}),V=T(`verify's answer`,{action:`string`,reasons:`array`}),H=(n,r={})=>{let{apiUrl:i,fetch:a=globalThis.fetch}=r,o=async({apiKey:e,base:t},n,r,i,o)=>{try{let s=await a(`${t}${r}`,{method:n,headers:{"auth-api-key":e,...o?{"content-type":`application/json`}:{}},body:o,signal:AbortSignal.timeout(i)});return{response:s,text:await s.text()}}catch(e){throw new y(0,`network_error`,e instanceof Error&&e.name===`TimeoutError`?`Zeno didn't answer ${n} ${r.split(`?`)[0]} within ${i} ms`:`Zeno couldn't be reached at ${t}: ${e instanceof Error?e.message:String(e)}`)}},s=async(r,a,s,c,l=!1)=>{let u=t(`createClient`,n,i);if(u.problem!==void 0)throw TypeError(u.problem);let d=c&&JSON.stringify(c),f=l?Date.now()+1e4:void 0,p=()=>f===void 0?1e4:Math.round(Math.min(5e3,f-Date.now())),m=e=>f===void 0||f-Date.now()-e*1e3>=1e3;for(let t=0;;t++){let n;try{n=await o(u,r,a,p(),d)}catch(e){let n=.5+Math.random()*.25;if(l&&t<2&&m(n)){await S(n);continue}throw e}let{response:i,text:c}=n,f;try{f=JSON.parse(c)}catch{}if(i.ok){if(f===void 0)throw new y(i.status,`request_failed`,`Zeno answered ${i.status} without JSON`);if(!s.is(f))throw new y(i.status,`request_failed`,`Zeno answered ${r} ${a.split(`?`)[0]} with something that isn't ${s.name}`);return f}let{error:h,message:g}=e(f)?f:{},_=typeof h==`string`?h:void 0,v=i.status===429||_===`search_unavailable`||l&&i.status>=500,b=v?x(i.headers.get(`retry-after`)):void 0,C=(b??1)*(1+Math.random()*.5);if(v&&t<2&&m(C))await S(C);else throw new y(i.status,_??`request_failed`,typeof g==`string`?g:void 0,b)}},c=e=>{let t=new URLSearchParams;for(let[n,r]of Object.entries(e))for(let e of Array.isArray(r)?r:[r])e!==void 0&&t.append(n,e instanceof Date?e.toISOString():String(e));return t};return{verify:async(e,t={})=>{let{ip:n,externalId:r,scope:i,maxAge:a,idempotencyKey:o=crypto.randomUUID()}=t;return s(`POST`,`/verify`,V,{requestId:e??void 0,ip:n||void 0,externalId:r,scope:i,maxAge:a,idempotencyKey:o},!0)},getEvent:async e=>s(`GET`,`/events/${C(`requestId`,e)}`,E),searchEvents:(e={})=>s(`GET`,`/events?${c(e)}`,D),reportOutcome:(e,t)=>s(`POST`,`/outcomes`,O,{requestId:e,outcome:t}),deleteVisitor:async e=>s(`DELETE`,`/visitors/${C(`visitorId`,e)}`,k),deleteExternalId:(e,{scope:t}={})=>s(`DELETE`,`/external-ids?${c({externalId:e,scope:t})}`,A),addRelation:({at:e,...t})=>{let n=e instanceof Date||typeof e==`number`?new Date(e).toISOString():e;return s(`POST`,`/related`,j,{...t,...n===void 0?{}:{at:n}})},removeRelation:e=>s(`DELETE`,`/related?${c(e)}`,M),getRelatedValues:(e,{scope:t,type:n,...r}={})=>{let i=c({externalId:e,scope:t,type:n,...r});return s(`GET`,`/related/values?${i}`,N)},lookupRelated:(e,t,{scope:n,...r}={})=>{let i=c({type:e,value:t,scope:n,...r});return s(`GET`,`/related/lookup?${i}`,P)},getRelated:(e,{scope:t,type:n,depth:r=1}={})=>{let i=c({externalId:e,scope:t,type:n,depth:r});return s(`GET`,`/related?${i}`,F)},getRelatedGroup:(e,{scope:t,...n}={})=>{let r=c({externalId:e,scope:t,...n});return s(`GET`,`/related/group?${r}`,R)},getGroup:async(e,t={})=>{let n=c(t).toString(),r=`/related/group/${C(`groupId`,e)}`;return s(`GET`,n?`${r}?${n}`:r,z)},getRelatedWeights:()=>s(`GET`,`/related/weights`,I),setRelatedType:(e,t)=>s(`POST`,`/related/weights`,L,{type:e,...t}),createEmbed:e=>s(`POST`,`/embeds`,B,e)}},U=new TextEncoder,W=e=>Array.from(new Uint8Array(e),e=>e.toString(16).padStart(2,`0`)).join(``),G=(e,t)=>{if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0},K=async(e,t,n,{tolerance:r=300}={})=>{let i=b(n,`verifyWebhook needs the webhook secret, whsec_… (is it set in the environment?)`);if(typeof e!=`string`)throw TypeError(`verifyWebhook needs the raw body as text, not a parsed one (in Express, express.text({ type: "application/json" }))`);let a=(t??``).split(`,`).map(e=>{let[t,...n]=e.trim().split(`=`);return[t??``,n.join(`=`)]}),o=Number(a.find(([e])=>e===`t`)?.[1]),s=a.filter(([e,t])=>e===`v1`&&t).map(([,e])=>e);if(!Number.isInteger(o)||s.length===0||Math.abs(Date.now()/1e3-o)>r)return;let c=await crypto.subtle.importKey(`raw`,U.encode(i),{name:`HMAC`,hash:`SHA-256`},!1,[`sign`]),l=U.encode(W(await crypto.subtle.sign(`HMAC`,c,U.encode(`${o}.${e}`))));if(!s.map(e=>G(U.encode(e),l)).includes(!0))return;let u;try{u=JSON.parse(e)}catch{}if(!E.is(u))throw Error(`The webhook's body is signed but isn't an event; update zeno.id/server`);return u};exports.SIGNALS=v,exports.ZenoError=y,exports.createClient=H,exports.createProxyResponse=f,exports.nodeHandler=_,exports.verifyWebhook=K;
|