@buildbase/sdk 0.0.70 → 0.0.73
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/AGENTS.md +5 -2
- package/CHANGELOG.md +114 -0
- package/README.md +141 -4
- package/dist/cli.mjs +2 -0
- package/dist/css/styles.css +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +589 -14
- package/dist/index.mjs +1 -1
- package/dist/mcp/index.cjs +1 -1
- package/dist/mcp/index.d.ts +102 -0
- package/dist/mcp/index.mjs +1 -1
- package/dist/react/chunks/SettingsDialog-CvBSuMf-.mjs +2 -0
- package/dist/react/chunks/SettingsDialog-DdOUkwIi.cjs +2 -0
- package/dist/react/chunks/SubscriptionDialog-CdZzF5eK.cjs +2 -0
- package/dist/react/chunks/SubscriptionDialog-D8_frxHc.mjs +2 -0
- package/dist/react/chunks/ar-CRVhjpVE.cjs +2 -0
- package/dist/react/chunks/ar-DFPDdu2U.mjs +2 -0
- package/dist/react/chunks/de-BGhzn711.cjs +2 -0
- package/dist/react/chunks/de-Bqi8scew.mjs +2 -0
- package/dist/react/chunks/es-D_Eqhob3.mjs +2 -0
- package/dist/react/chunks/es-DyrMaeUp.cjs +2 -0
- package/dist/react/chunks/fr-C0SkloRr.cjs +2 -0
- package/dist/react/chunks/fr-DkZpFQ1Q.mjs +2 -0
- package/dist/react/chunks/hi-B9TK87T8.cjs +2 -0
- package/dist/react/chunks/hi-DrTcPkiY.mjs +2 -0
- package/dist/react/chunks/ja-Dgahn--0.mjs +2 -0
- package/dist/react/chunks/ja-LjzlAhAT.cjs +2 -0
- package/dist/react/chunks/react-BSHCN-ZU.mjs +2 -0
- package/dist/react/chunks/react-DQqr117G.cjs +2 -0
- package/dist/react/chunks/zh-BezRHDHs.mjs +2 -0
- package/dist/react/chunks/zh-CcodKi4U.cjs +2 -0
- package/dist/react/index.cjs +1 -1
- package/dist/react/index.d.ts +826 -25
- package/dist/react/index.mjs +1 -1
- package/dist/server/browser.cjs +1 -0
- package/dist/server/browser.mjs +1 -0
- package/dist/server/index.cjs +1 -0
- package/dist/server/index.d.ts +556 -0
- package/dist/server/index.mjs +1 -0
- package/dist/server/next/index.cjs +1 -0
- package/dist/server/next/index.d.ts +156 -0
- package/dist/server/next/index.mjs +1 -0
- package/dist/tracking/index.cjs +1 -1
- package/dist/tracking/index.d.ts +205 -8
- package/dist/tracking/index.mjs +1 -1
- package/docs/ERROR_CODES.md +24 -0
- package/docs/SERVER-CONTENT.md +297 -0
- package/docs/UI-CONFIG.md +1 -0
- package/package.json +66 -5
- package/dist/react/chunks/SettingsDialog-VKPguQBs.mjs +0 -2
- package/dist/react/chunks/SettingsDialog-_kfJ6j25.cjs +0 -2
- package/dist/react/chunks/SubscriptionDialog-C_1ipsC2.cjs +0 -2
- package/dist/react/chunks/SubscriptionDialog-Cbk3EGBr.mjs +0 -2
- package/dist/react/chunks/ar-CHTRXlXt.mjs +0 -2
- package/dist/react/chunks/ar-DPJVNHJV.cjs +0 -2
- package/dist/react/chunks/de-CdPeKWZ2.mjs +0 -2
- package/dist/react/chunks/de-DPd09yf-.cjs +0 -2
- package/dist/react/chunks/es-BWGnjJKJ.mjs +0 -2
- package/dist/react/chunks/es-WdOYGt6G.cjs +0 -2
- package/dist/react/chunks/fr-Big5DFPB.mjs +0 -2
- package/dist/react/chunks/fr-LIbCvYeh.cjs +0 -2
- package/dist/react/chunks/hi-BoCY3pFe.cjs +0 -2
- package/dist/react/chunks/hi-jArNRknR.mjs +0 -2
- package/dist/react/chunks/ja-Cwdz0hCu.mjs +0 -2
- package/dist/react/chunks/ja-E0jqCiVq.cjs +0 -2
- package/dist/react/chunks/react-B0MFoaXI.mjs +0 -2
- package/dist/react/chunks/react-DSRfaDnZ.cjs +0 -2
- package/dist/react/chunks/zh-glRKcdia.mjs +0 -2
- package/dist/react/chunks/zh-tU-AqFYI.cjs +0 -2
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function t(t={}){const e=Math.max(1,t.maxEntries??1e3),n=new Map,o=new Map,a=t=>{const e=n.get(t);e&&(n.delete(t),((t,e)=>{for(const n of e.tags){const e=o.get(n);e&&(e.delete(t),0===e.size&&o.delete(n))}})(t,e.entry))};return{async get(t){const e=n.get(t);if(e){if(!(e.expiresAt<=Date.now()))return n.delete(t),n.set(t,e),e.entry;a(t)}},async set(t,s,r){a(t),n.set(t,{entry:s,expiresAt:Date.now()+1e3*r});for(const e of s.tags){let n=o.get(e);n||o.set(e,n=new Set),n.add(t)}for(;n.size>e;){const t=n.keys().next().value;if(void 0===t)break;a(t)}},async delete(t){a(t)},async deleteByTag(t){const e=o.get(t);if(e)for(const t of[...e])a(t)}}}function e(t,e={}){const n=e.prefix??"buildbase:sdk:",o="function"==typeof t.sAdd&&"function"==typeof t.sMembers,a=t=>`${n}e:${t}`,s=t=>`${n}t:${t}`,r=(e,n)=>o?t.sAdd(e,n):t.sadd(e,n),i=e=>0===e.length?Promise.resolve():o?t.del(e):t.del(...e);if(!o&&("function"!=typeof t.sadd||"function"!=typeof t.smembers))throw new Error("redisCache: the client needs set commands (sadd/smembers or sAdd/sMembers)");return{async get(e){const n=await t.get(a(e));if(n)try{return JSON.parse(n)}catch{return}},async set(e,n,i){const c=Math.max(1,Math.ceil(i));await((e,n,a)=>o?t.set(e,n,{EX:a}):t.set(e,n,"EX",a))(a(e),JSON.stringify(n),c);for(const o of n.tags)await r(s(o),e),"function"==typeof t.expire&&await t.expire(s(o),c)},async delete(t){await i([a(t)])},async deleteByTag(e){const n=await(r=s(e),o?t.sMembers(r):t.smembers(r));var r;await i([...n.map(a),s(e)])}}}function n(t,e={}){const n=e.prefix??"buildbase:sdk:",o=t=>`${n}e:${t}`,a=t=>`${n}t:${t}`,s=t=>Math.max(60,Math.ceil(t)),r=async e=>{const n=await t.get(e);if(null!=n){if("string"==typeof n)try{return JSON.parse(n)}catch{return}return n}},i=async(e,n,o)=>{const a=JSON.stringify(n);if("function"==typeof t.put)await t.put(e,a,{expirationTtl:s(o)});else{if("function"!=typeof t.set)throw new Error("kvCache: the binding needs put() or set()");await t.set(e,a,{ex:s(o)})}},c=async e=>{"function"==typeof t.delete?await t.delete(e):"function"==typeof t.del&&await t.del(e)};return{get:async t=>r(o(t)),async set(t,e,n){await i(o(t),e,n);for(const o of e.tags){const e=await r(a(o))??[];e.includes(t)||e.push(t),await i(a(o),e,n)}},async delete(t){await c(o(t))},async deleteByTag(t){const e=await r(a(t))??[];await Promise.all(e.map(t=>c(o(t)))),await c(a(t))}}}function o(t,e,n){if(null!=n)if(Array.isArray(n))n.forEach((n,a)=>o(t,`${e}[${a}]`,n));else if("object"!=typeof n)t.append(e,String(n));else for(const[a,s]of Object.entries(n))o(t,`${e}[${a}]`,s)}function a(t){if(!t)return"";const e=new URLSearchParams;for(const n of Object.keys(t).sort())o(e,n,t[n]);e.sort();const n=e.toString();return n?`?${n}`:""}const s=["blog","doc","faq","faq_collection","testimonial","rich_content","collection"],r="buildbase:all",i={module:t=>`buildbase:${t}`,slug:(t,e)=>`buildbase:${t}:${e}`,id:(t,e)=>`buildbase:${t}:id:${e}`,collection:t=>`buildbase:collection:${t}`,all:r},c=["blog.published","blog.updated","blog.unpublished","blog.deleted","doc.published","doc.updated","doc.unpublished","doc.deleted","faq.updated","faq_collection.updated","testimonial.updated","testimonial.deleted","rich_content.updated","rich_content.deleted","collection.version_published","collection.record_created","collection.record_updated","collection.record_deleted"],l=new Set(c);function u(t){return l.has(t)}function d(t,e){if(e&&Array.isArray(e.tags)&&e.tags.length>0)return[...new Set(e.tags.filter(t=>"string"==typeof t))];const n=e?.module??t.split(".")[0];if(!s.includes(n))return[];const o=[i.module(n)];return e?.slug&&o.push(i.slug(n,e.slug)),e?.id&&o.push(i.id(n,e.id)),"faq.updated"===t&&o.push(i.module("faq_collection")),o}const f="@buildbase/sdk/server holds your org API token and must only run on a server. Import it from server code (an API route, a server component, a build script), never from code that ships to the browser.";class h extends Error{constructor(t,e,n,o){super(t),this.status=e,this.url=n,this.body=o,this.name="BuildBaseContentError"}}const g=/^[0-9a-f]{24}$/i,p=new WeakMap;function y(t){return t&&"object"==typeof t?p.get(t)??[]:[]}function w(t){return Array.isArray(t)?t:t&&"object"==typeof t&&Array.isArray(t.docs)?t.docs:[]}function m(t){const e=t.split("/").filter(Boolean);return e[e.length-1]??t}function b(t={},e={}){const n={...e,...t.filter};return{$page:t.page,$limit:t.limit,filter:Object.keys(n).length>0?n:void 0,sort:t.sort}}function v(e){if("undefined"!=typeof window&&"undefined"!=typeof document)throw new Error(f);if(!e||"string"!=typeof e.serverUrl||!e.serverUrl)throw new Error("createServerClient: `serverUrl` is required");if("string"!=typeof e.apiToken||!e.apiToken.includes(":"))throw new Error("createServerClient: `apiToken` must be an org API token of the form <orgId>:<secret> (console, Settings, API tokens)");const n=e.serverUrl.replace(/\/+$/,""),o=e.apiToken,s=o.slice(0,o.indexOf(":")),c=!1===e.cache?null:e.cache??t(),l=e.fetch??((t,e)=>globalThis.fetch(t,e)),u=e.timeoutMs??1e4,d=e.defaultTtlSeconds??60,y=Math.max(e.retainSeconds??86400,1),v=e.staleOnError??!0,$=new Map,q=(t,e)=>(t&&"object"==typeof t&&p.set(t,e),t);async function A(t,a,s){const r="function"==typeof e.requestInit?e.requestInit({path:t,tags:a}):e.requestInit??{},i=new Headers(r.headers);i.set("Authorization",`Bearer ${o}`),i.set("Accept","application/json"),s&&i.set("If-None-Match",s);const c=new AbortController,d=setTimeout(()=>c.abort(),u);try{return await l(`${n}${t}`,{...r,method:"GET",headers:i,signal:r.signal??c.signal})}finally{clearTimeout(d)}}async function x(t){const e=`${t.path}${a(t.query)}`,o=`${s}:${e}`,i=c?await c.get(o):void 0,l=Date.now();if(i&&i.freshUntil>l)return q(i.data,i.tags);const u=()=>{const a=async function(){let a;try{a=await A(e,t.tags,i?.etag),304!==a.status||i||(a=await A(e,t.tags))}catch(t){if(v&&i)return q(i.data,i.tags);throw new h(`BuildBase request failed: ${t instanceof Error?t.message:String(t)}`,0,`${n}${e}`)}const s=function(t,e){const n=t.headers.get("cache-control");if(!n)return e;const o=n.toLowerCase().split(",").map(t=>t.trim());if(o.includes("no-store"))return null;if(o.includes("no-cache"))return 0;const a=o.find(t=>t.startsWith("max-age="));if(a){const t=Number(a.slice(8));if(Number.isFinite(t)&&t>=0)return t}return e}(a,d),l=function(t){const e=t.headers.get("cache-control");if(!e)return 0;const n=e.toLowerCase().split(",").map(t=>t.trim()).find(t=>t.startsWith("stale-while-revalidate=")),o=n?Number(n.slice(23)):0;return Number.isFinite(o)&&o>0?o:0}(a);if(304===a.status&&i){const t={...i,etag:a.headers.get("etag")??i.etag,freshUntil:Date.now()+1e3*(s??0),staleUntil:l>0?Date.now()+1e3*((s??0)+l):void 0};return c&&await c.set(o,t,y),q(i.data,i.tags)}if(404===a.status&&t.nullOnNotFound)return null;if(!a.ok){const o=await a.text().catch(()=>"");let s=o;try{s=o?JSON.parse(o):void 0}catch{}if(v&&i&&401!==a.status&&403!==a.status)return q(i.data,i.tags);const r=s?.message??`BuildBase responded ${a.status} for ${t.path}`;throw new h(r,a.status,`${n}${e}`,s)}const u=(f=await a.json().catch(()=>null),f&&"object"==typeof f&&!Array.isArray(f)&&"data"in f&&"success"in f&&!("docs"in f)?f.data:f);var f;if(null==u&&t.nullOnNotFound)return null;const g=t.transform?t.transform(u):u,p=[...new Set([...t.tags,...t.tagsFrom?t.tagsFrom(g):[],r])];c&&null!==s&&await c.set(o,{data:g,etag:a.headers.get("etag")??void 0,freshUntil:Date.now()+1e3*s,staleUntil:l>0?Date.now()+1e3*(s+l):void 0,tags:p},Math.max(y,s));return q(g,p)}();return $.set(o,a),a.then(()=>$.delete(o),()=>$.delete(o)),a};if(i&&void 0!==i.staleUntil&&i.staleUntil>l)return $.has(o)||u().catch(()=>{}),q(i.data,i.tags);const f=$.get(o);return f||u()}const U=t=>e=>{const n=[];return e?._id&&n.push(i.id(t,e._id)),e?.slug&&n.push(i.slug(t,e.slug)),n};function S(t,e){const n=i.module(e);return{list:(e={})=>x({path:`/api/${t}`,query:b(e,e.includeDrafts?{}:{published:!0}),tags:[n]}),get:n=>x({path:`/api/${t}/${encodeURIComponent(n)}`,tags:[i.id(e,n)],tagsFrom:U(e),nullOnNotFound:!0}),byPath:(n,o={})=>x({path:`/api/${t}/path`,query:{path:n,draftPreview:!!o.draftPreview||void 0},tags:[i.slug(e,m(n))],tagsFrom:U(e),nullOnNotFound:!0}),tree:(e={})=>x({path:`/api/${t}/folders/tree`,query:{folder:e.folder},tags:[n]}),tags:(e={})=>x({path:`/api/${t}/tags`,query:b(e),tags:[n]}),authors:(e={})=>x({path:`/api/${t}/authors`,query:b(e),tags:[n]})}}const N=i.module("faq_collection");async function O(t){const e=g.test(t);return x({path:e?`/api/faqs/collections/${encodeURIComponent(t)}`:`/api/faqs/collections/slug/${encodeURIComponent(t)}`,tags:[e?i.id("faq_collection",t):i.slug("faq_collection",t)],tagsFrom:U("faq_collection"),nullOnNotFound:!0})}return{blogs:S("blogs","blog"),docs:S("docs","doc"),faqs:{collections:(t={})=>x({path:"/api/faqs/collections",query:b(t,{archived:!1}),tags:[N]}),collection:O,async questions(t){const e=g.test(t);if(e&&!await O(t))return[];return await x({path:e?`/api/faqs/collections/${encodeURIComponent(t)}/faqs`:`/api/faqs/collections/slug/${encodeURIComponent(t)}/faqs`,query:{pagination:!1},tags:[i.module("faq"),e?i.id("faq_collection",t):i.slug("faq_collection",t)],transform:t=>w(t).filter(t=>!t.archived),nullOnNotFound:!0})??[]}},testimonials:{list:(t={})=>x({path:"/api/testimonials",query:b(t,t.includeUnpublished?{archived:!1}:{published:!0,archived:!1}),tags:[i.module("testimonial")]}),get:t=>x({path:`/api/testimonials/${encodeURIComponent(t)}`,tags:[i.id("testimonial",t)],nullOnNotFound:!0})},richContent:{get:t=>x({path:`/api/rich-content/slug/${encodeURIComponent(t)}`,tags:[i.slug("rich_content",t)],tagsFrom:U("rich_content"),nullOnNotFound:!0}),list:(t={})=>x({path:"/api/rich-content",query:b(t,{archived:!1}),tags:[i.module("rich_content")]})},collections:{list:(t={})=>x({path:"/api/collections",query:b(t,{archived:!1}),tags:[i.module("collection")]}),data(t,e={}){const n=void 0===e.version;return x({path:`/api/collections/data/${encodeURIComponent(t)}`,query:n?{latest:!0}:{version:e.version},tags:[i.collection(t)],transform:t=>w(t).filter(t=>!t.archived)})}},async revalidate(t){c&&await c.deleteByTag(t)},async revalidateAll(){c&&await c.deleteByTag(r)},cache:c}}const $=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),q=(t,e)=>t>>>e|t<<32-e;function A(t){let e=1779033703,n=3144134277,o=1013904242,a=2773480762,s=1359893119,r=2600822924,i=528734635,c=1541459225;const l=t.length,u=l+1,d=u+(56-u%64+64)%64+8,f=new Uint8Array(d);f.set(t,0),f[l]=128;const h=8*l,g=Math.floor(h/4294967296),p=h>>>0;f[d-8]=g>>>24&255,f[d-7]=g>>>16&255,f[d-6]=g>>>8&255,f[d-5]=255&g,f[d-4]=p>>>24&255,f[d-3]=p>>>16&255,f[d-2]=p>>>8&255,f[d-1]=255&p;const y=new Uint32Array(64);for(let t=0;t<d;t+=64){for(let e=0;e<16;e++){const n=t+4*e;y[e]=f[n]<<24|f[n+1]<<16|f[n+2]<<8|f[n+3]}for(let t=16;t<64;t++){const e=q(y[t-15],7)^q(y[t-15],18)^y[t-15]>>>3,n=q(y[t-2],17)^q(y[t-2],19)^y[t-2]>>>10;y[t]=y[t-16]+e+y[t-7]+n>>>0}let l=e,u=n,d=o,h=a,g=s,p=r,w=i,m=c;for(let t=0;t<64;t++){const e=m+(q(g,6)^q(g,11)^q(g,25))+(g&p^~g&w)+$[t]+y[t]>>>0,n=l&u^l&d^u&d;m=w,w=p,p=g,g=h+e>>>0,h=d,d=u,u=l,l=e+((q(l,2)^q(l,13)^q(l,22))+n>>>0)>>>0}e=e+l>>>0,n=n+u>>>0,o=o+d>>>0,a=a+h>>>0,s=s+g>>>0,r=r+p>>>0,i=i+w>>>0,c=c+m>>>0}const w=new Uint8Array(32),m=[e,n,o,a,s,r,i,c];for(let t=0;t<8;t++)w[4*t]=m[t]>>>24&255,w[4*t+1]=m[t]>>>16&255,w[4*t+2]=m[t]>>>8&255,w[4*t+3]=255&m[t];return w}function x(t){return(new TextEncoder).encode(t)}function U(t,e){const n=new Uint8Array(t.length+e.length);return n.set(t,0),n.set(e,t.length),n}function S(t){const{body:e,signature:n,timestamp:o,secret:a,maxAgeSeconds:s=300}=t;if(!(n&&o&&a&&e))return!1;const r="sha256=";if(!n.startsWith(r))return!1;const i=n.slice(7);if(s>0){const t=parseInt(o,10);if(isNaN(t))return!1;if(Math.abs(Math.floor(Date.now()/1e3)-t)>s)return!1}const c=function(t){if(t.length%2!=0)return null;const e=new Uint8Array(t.length/2);for(let n=0;n<e.length;n++){const o=parseInt(t.slice(2*n,2*n+2),16);if(Number.isNaN(o))return null;e[n]=o}return e}(i);if(!c)return!1;const l=function(t,e){let n=t;n.length>64&&(n=A(n));const o=new Uint8Array(64),a=new Uint8Array(64);for(let t=0;t<64;t++){const e=t<n.length?n[t]:0;o[t]=54^e,a[t]=92^e}const s=A(U(o,e));return A(U(a,s))}(x(a),x(`${o}.${e}`));return c.length===l.length&&function(t,e){if(t.length!==e.length)return!1;let n=0;for(let o=0;o<t.length;o++)n|=t[o]^e[o];return 0===n}(c,l)}const N=(t,e)=>new Response(JSON.stringify(e),{status:t,headers:{"Content-Type":"application/json"}});async function O(t,e){if("POST"!==t.method)return N(405,{error:"method_not_allowed"});const n=function(t){if(!S(t))return null;try{return JSON.parse(t.body)}catch{return null}}({body:await t.text(),signature:t.headers.get("x-buildbase-signature"),timestamp:t.headers.get("x-buildbase-timestamp"),secret:e.secret,maxAgeSeconds:e.maxAgeSeconds??300});if(!n)return N(401,{error:"invalid_signature"});if(!u(n.event))return N(200,{ignored:!0,event:n.event});const o=d(n.event,n.data);return e.cache&&await Promise.all(o.map(t=>e.cache.deleteByTag(t))),e.revalidate&&await e.revalidate(o),e.onEvent&&await e.onEvent(n,o),N(200,{revalidated:o})}function E(t){return e=>O(e,t)}function T(t){return t instanceof Uint8Array}function _(t){return async(e,n)=>{let o;try{const n=await async function(t){for(const e of[t.rawBody,t.body]){if("string"==typeof e)return e;if(T(e))return(new TextDecoder).decode(e)}if(t.body&&"object"==typeof t.body)throw new Error("toNodeHandler: the body was already parsed as JSON. Mount the webhook route with a raw body (Express: express.raw({ type: 'application/json' }); Fastify: a raw-body content-type parser).");return!t.on||t.readableEnded?"":new Promise((e,n)=>{const o=[];t.on("data",t=>o.push("string"==typeof t?(new TextEncoder).encode(t):t)),t.on("end",()=>{const t=o.reduce((t,e)=>t+e.length,0),n=new Uint8Array(t);let a=0;for(const t of o)n.set(t,a),a+=t.length;e((new TextDecoder).decode(n))}),t.on("error",n)})}(e),a=new Headers;for(const[t,n]of Object.entries(e.headers))void 0!==n&&a.set(t,Array.isArray(n)?n.join(", "):n);const s=a.get("host")??"localhost",r=e.method??"POST";o=await t(new Request(`http://${s}${e.originalUrl??e.url??"/"}`,{method:r,headers:a,body:"GET"===r||"HEAD"===r?void 0:n}))}catch(t){o=new Response(JSON.stringify({error:t instanceof Error?t.message:String(t)}),{status:400,headers:{"Content-Type":"application/json"}})}n.statusCode=o.status,o.headers.forEach((t,e)=>n.setHeader(e,t)),n.end(new Uint8Array(await o.arrayBuffer()))}}const C=["blogs","docs","faqs","testimonials","richContent","collections"];async function I(t){const e=[];for(let n=1;n<=1e4;n++){const o=await t(n);e.push(...o.docs);if(!(o.hasNextPage??(void 0!==o.totalPages&&n<o.totalPages))||0===o.docs.length)break}return e}async function M(t,e={}){const n=new Set(e.modules??C),o=e.pageSize??100,a={generatedAt:(new Date).toISOString()};if(n.has("blogs")&&(a.blogs=await I(e=>t.blogs.list({page:e,limit:o}))),n.has("docs")&&(a.docs=await I(e=>t.docs.list({page:e,limit:o}))),n.has("faqs")){const e=await I(e=>t.faqs.collections({page:e,limit:o}));a.faqs=[];for(const n of e)a.faqs.push({...n,questions:await t.faqs.questions(n._id)})}if(n.has("testimonials")&&(a.testimonials=await I(e=>t.testimonials.list({page:e,limit:o}))),n.has("richContent")&&(a.richContent=await I(e=>t.richContent.list({page:e,limit:o}))),n.has("collections")){const n=e.collections??(await I(e=>t.collections.list({page:e,limit:o}))).map(t=>t.slug);a.collections={};for(const e of n)a.collections[e]=await t.collections.data(e)}return a}export{r as ALL_TAG,h as BuildBaseContentError,s as CONTENT_MODULES,c as CONTENT_WEBHOOK_EVENTS,C as PULL_MODULES,f as SERVER_ONLY_MESSAGE,i as contentTags,E as createContentWebhookHandler,v as createServerClient,a as encodeQuery,y as getContentTags,O as handleContentWebhook,u as isContentWebhookEvent,n as kvCache,t as memoryCache,M as pullContent,e as redisCache,d as tagsForContentEvent,_ as toNodeHandler};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";const t=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),e=(t,e)=>t>>>e|t<<32-e;function n(n){let r=1779033703,o=3144134277,i=1013904242,a=2773480762,s=1359893119,c=2600822924,l=528734635,u=1541459225;const d=n.length,f=d+1,h=f+(56-f%64+64)%64+8,g=new Uint8Array(h);g.set(n,0),g[d]=128;const p=8*d,b=Math.floor(p/4294967296),w=p>>>0;g[h-8]=b>>>24&255,g[h-7]=b>>>16&255,g[h-6]=b>>>8&255,g[h-5]=255&b,g[h-4]=w>>>24&255,g[h-3]=w>>>16&255,g[h-2]=w>>>8&255,g[h-1]=255&w;const y=new Uint32Array(64);for(let n=0;n<h;n+=64){for(let t=0;t<16;t++){const e=n+4*t;y[t]=g[e]<<24|g[e+1]<<16|g[e+2]<<8|g[e+3]}for(let t=16;t<64;t++){const n=e(y[t-15],7)^e(y[t-15],18)^y[t-15]>>>3,r=e(y[t-2],17)^e(y[t-2],19)^y[t-2]>>>10;y[t]=y[t-16]+n+y[t-7]+r>>>0}let d=r,f=o,h=i,p=a,b=s,w=c,m=l,v=u;for(let n=0;n<64;n++){const r=v+(e(b,6)^e(b,11)^e(b,25))+(b&w^~b&m)+t[n]+y[n]>>>0,o=d&f^d&h^f&h;v=m,m=w,w=b,b=p+r>>>0,p=h,h=f,f=d,d=r+((e(d,2)^e(d,13)^e(d,22))+o>>>0)>>>0}r=r+d>>>0,o=o+f>>>0,i=i+h>>>0,a=a+p>>>0,s=s+b>>>0,c=c+w>>>0,l=l+m>>>0,u=u+v>>>0}const m=new Uint8Array(32),v=[r,o,i,a,s,c,l,u];for(let t=0;t<8;t++)m[4*t]=v[t]>>>24&255,m[4*t+1]=v[t]>>>16&255,m[4*t+2]=v[t]>>>8&255,m[4*t+3]=255&v[t];return m}function r(t){return(new TextEncoder).encode(t)}function o(t,e){const n=new Uint8Array(t.length+e.length);return n.set(t,0),n.set(e,t.length),n}function i(t){const{body:e,signature:i,timestamp:a,secret:s,maxAgeSeconds:c=300}=t;if(!(i&&a&&s&&e))return!1;const l="sha256=";if(!i.startsWith(l))return!1;const u=i.slice(7);if(c>0){const t=parseInt(a,10);if(isNaN(t))return!1;if(Math.abs(Math.floor(Date.now()/1e3)-t)>c)return!1}const d=function(t){if(t.length%2!=0)return null;const e=new Uint8Array(t.length/2);for(let n=0;n<e.length;n++){const r=parseInt(t.slice(2*n,2*n+2),16);if(Number.isNaN(r))return null;e[n]=r}return e}(u);if(!d)return!1;const f=function(t,e){let r=t;r.length>64&&(r=n(r));const i=new Uint8Array(64),a=new Uint8Array(64);for(let t=0;t<64;t++){const e=t<r.length?r[t]:0;i[t]=54^e,a[t]=92^e}const s=n(o(i,e));return n(o(a,s))}(r(s),r(`${a}.${e}`));return d.length===f.length&&function(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t[r]^e[r];return 0===n}(d,f)}const a=["blog","doc","faq","faq_collection","testimonial","rich_content","collection"],s=t=>`buildbase:${t}`,c=(t,e)=>`buildbase:${t}:${e}`,l=(t,e)=>`buildbase:${t}:id:${e}`,u=new Set(["blog.published","blog.updated","blog.unpublished","blog.deleted","doc.published","doc.updated","doc.unpublished","doc.deleted","faq.updated","faq_collection.updated","testimonial.updated","testimonial.deleted","rich_content.updated","rich_content.deleted","collection.version_published","collection.record_created","collection.record_updated","collection.record_deleted"]);const d=(t,e)=>new Response(JSON.stringify(e),{status:t,headers:{"Content-Type":"application/json"}});async function f(t,e){if("POST"!==t.method)return d(405,{error:"method_not_allowed"});const n=function(t){if(!i(t))return null;try{return JSON.parse(t.body)}catch{return null}}({body:await t.text(),signature:t.headers.get("x-buildbase-signature"),timestamp:t.headers.get("x-buildbase-timestamp"),secret:e.secret,maxAgeSeconds:e.maxAgeSeconds??300});if(!n)return d(401,{error:"invalid_signature"});if(!function(t){return u.has(t)}(n.event))return d(200,{ignored:!0,event:n.event});const r=function(t,e){if(e&&Array.isArray(e.tags)&&e.tags.length>0)return[...new Set(e.tags.filter(t=>"string"==typeof t))];const n=e?.module??t.split(".")[0];if(!a.includes(n))return[];const r=[s(n)];return e?.slug&&r.push(c(n,e.slug)),e?.id&&r.push(l(n,e.id)),"faq.updated"===t&&r.push(s("faq_collection")),r}(n.event,n.data);return e.cache&&await Promise.all(r.map(t=>e.cache.deleteByTag(t))),e.revalidate&&await e.revalidate(r),e.onEvent&&await e.onEvent(n,r),d(200,{revalidated:r})}function h(t,e){return{next:void 0===e?{tags:t}:{tags:t,revalidate:e}}}exports.createNextWebhookHandler=function(t){return e=>f(e,{...t,async revalidate(t){const{revalidateTag:e}=await import("next/cache");for(const n of t)e(n)}})},exports.nextFetchOptions=h,exports.withNextCache=function(t={}){const e=t.revalidate??300;return{cache:!1,requestInit:t=>h(t.tags,e)}};
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cache stores for the server content client.
|
|
3
|
+
*
|
|
4
|
+
* One small interface, so the same client caches in process memory, Redis,
|
|
5
|
+
* Cloudflare KV or Upstash without the client knowing which. Every store keeps
|
|
6
|
+
* a tag index so a webhook can drop what changed without scanning.
|
|
7
|
+
*/
|
|
8
|
+
/** What the client stores per read. */
|
|
9
|
+
interface CacheEntry<T = unknown> {
|
|
10
|
+
/** The parsed response body. */
|
|
11
|
+
data: T;
|
|
12
|
+
/** The platform's ETag, sent back as `If-None-Match` on revalidation. */
|
|
13
|
+
etag?: string;
|
|
14
|
+
/** Epoch ms after which the entry must be revalidated before use. */
|
|
15
|
+
freshUntil: number;
|
|
16
|
+
/**
|
|
17
|
+
* Epoch ms until which a stale entry may still be served while one
|
|
18
|
+
* background request revalidates it (`Cache-Control: stale-while-revalidate`).
|
|
19
|
+
*/
|
|
20
|
+
staleUntil?: number;
|
|
21
|
+
/** Tags this entry answers to (see `contentTags`). */
|
|
22
|
+
tags: string[];
|
|
23
|
+
}
|
|
24
|
+
interface CacheStore {
|
|
25
|
+
get(key: string): Promise<CacheEntry | undefined>;
|
|
26
|
+
/** `ttlSeconds` is how long the store keeps the entry at all (beyond `freshUntil`, for ETag revalidation). */
|
|
27
|
+
set(key: string, entry: CacheEntry, ttlSeconds: number): Promise<void>;
|
|
28
|
+
delete(key: string): Promise<void>;
|
|
29
|
+
/** Drop every entry carrying `tag`. */
|
|
30
|
+
deleteByTag(tag: string): Promise<void>;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Server-only client for BuildBase content: blogs, docs, FAQs, testimonials,
|
|
35
|
+
* rich content and collection data.
|
|
36
|
+
*
|
|
37
|
+
* It authenticates with an org API token (`<orgId>:<secret>`), which must never
|
|
38
|
+
* reach a browser, so it refuses to run in one. It uses only the standard
|
|
39
|
+
* `fetch` API: Node 18+, Bun, Deno, Cloudflare Workers and edge runtimes all
|
|
40
|
+
* work unchanged.
|
|
41
|
+
*
|
|
42
|
+
* Every read is cached (see `CacheStore`) and revalidated with `If-None-Match`,
|
|
43
|
+
* so a page render costs nothing while the entry is fresh and a single
|
|
44
|
+
* `304 Not Modified` once it is not. Content webhooks drop entries by tag the
|
|
45
|
+
* moment something changes (see `handleContentWebhook`).
|
|
46
|
+
*/
|
|
47
|
+
|
|
48
|
+
interface RequestContext {
|
|
49
|
+
/** Path including the query string, e.g. `/api/blogs?filter[published]=true`. */
|
|
50
|
+
path: string;
|
|
51
|
+
/** Cache tags the read will be stored under. */
|
|
52
|
+
tags: string[];
|
|
53
|
+
}
|
|
54
|
+
interface ServerClientOptions {
|
|
55
|
+
/** e.g. `https://api.console.buildbase.app`. */
|
|
56
|
+
serverUrl: string;
|
|
57
|
+
/** Org API token, `<orgId>:<secret>` (console, Settings, API tokens). Pass it from your server's environment. */
|
|
58
|
+
apiToken: string;
|
|
59
|
+
/** Where reads are cached. Default: `memoryCache()`. `false` disables caching (every call hits the API). */
|
|
60
|
+
cache?: CacheStore | false;
|
|
61
|
+
/** A `fetch` implementation. Default: the global `fetch`. */
|
|
62
|
+
fetch?: typeof fetch;
|
|
63
|
+
/** Per-request timeout. Default 10 000 ms. */
|
|
64
|
+
timeoutMs?: number;
|
|
65
|
+
/** Freshness when the response carries no `Cache-Control: max-age`. Default 60 s. */
|
|
66
|
+
defaultTtlSeconds?: number;
|
|
67
|
+
/** How long a stale entry is kept for ETag revalidation and error fallback. Default 86 400 s. */
|
|
68
|
+
retainSeconds?: number;
|
|
69
|
+
/** Serve the last good copy when the API errors or is unreachable. Default true. 401/403 always throw. */
|
|
70
|
+
staleOnError?: boolean;
|
|
71
|
+
/**
|
|
72
|
+
* Extra `fetch` init, merged into every request. A function gets the read's
|
|
73
|
+
* path and tags; this is how framework caches plug in, for example Next.js
|
|
74
|
+
* `{ next: { tags, revalidate } }` (see `@buildbase/sdk/server/next`).
|
|
75
|
+
*/
|
|
76
|
+
requestInit?: RequestInit | ((ctx: RequestContext) => RequestInit);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Cache-tag vocabulary shared with the platform's content webhook events.
|
|
81
|
+
*
|
|
82
|
+
* A webhook for a content change carries `data.tags`, built from the same
|
|
83
|
+
* strings, so a server that cached a read under these tags can drop exactly
|
|
84
|
+
* what changed:
|
|
85
|
+
*
|
|
86
|
+
* - `buildbase:<module>` every list of that module
|
|
87
|
+
* - `buildbase:<module>:<slug>` one item, by slug
|
|
88
|
+
* - `buildbase:<module>:id:<id>` one item, by id
|
|
89
|
+
* - `buildbase:collection:<slug>` any record change in that collection
|
|
90
|
+
* (record events also carry `buildbase:collection:id:<collectionId>`)
|
|
91
|
+
* - `buildbase:all` everything this SDK cached (added to every entry)
|
|
92
|
+
*/
|
|
93
|
+
type ContentModule = 'blog' | 'doc' | 'faq' | 'faq_collection' | 'testimonial' | 'rich_content' | 'collection';
|
|
94
|
+
/** The data every content webhook event carries. */
|
|
95
|
+
interface ContentWebhookData {
|
|
96
|
+
module: ContentModule;
|
|
97
|
+
id?: string | null;
|
|
98
|
+
slug?: string | null;
|
|
99
|
+
path?: string | null;
|
|
100
|
+
tags?: string[];
|
|
101
|
+
[key: string]: unknown;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
interface ContentWebhookEventPayload {
|
|
105
|
+
event: string;
|
|
106
|
+
timestamp: number;
|
|
107
|
+
data: ContentWebhookData;
|
|
108
|
+
}
|
|
109
|
+
interface HandleContentWebhookOptions {
|
|
110
|
+
/** The endpoint's signing secret (console, Settings, Webhooks). */
|
|
111
|
+
secret: string;
|
|
112
|
+
/** Drop matching entries from this store (pass `client.cache`). */
|
|
113
|
+
cache?: Pick<CacheStore, 'deleteByTag'> | null;
|
|
114
|
+
/** Or drop them however your framework caches, e.g. Next.js `revalidateTag`. */
|
|
115
|
+
revalidate?: (tags: string[]) => void | Promise<void>;
|
|
116
|
+
/** Called after invalidation, for logging or rebuild triggers. */
|
|
117
|
+
onEvent?: (event: ContentWebhookEventPayload, tags: string[]) => void | Promise<void>;
|
|
118
|
+
/** Signature age window. Default 300 s. */
|
|
119
|
+
maxAgeSeconds?: number;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* @buildbase/sdk/server/next - optional Next.js helpers.
|
|
124
|
+
*
|
|
125
|
+
* Next.js has its own data cache keyed by tags, so under Next the SDK hands
|
|
126
|
+
* caching to it: every read is issued with `{ next: { tags, revalidate } }`,
|
|
127
|
+
* and the content webhook calls `revalidateTag` for what changed. `next` stays
|
|
128
|
+
* an optional peer and is only loaded when the webhook handler runs.
|
|
129
|
+
*/
|
|
130
|
+
|
|
131
|
+
/** `fetch` options for a read under the given tags. */
|
|
132
|
+
declare function nextFetchOptions(tags: string[], revalidateSeconds?: number | false): RequestInit & {
|
|
133
|
+
next: {
|
|
134
|
+
tags: string[];
|
|
135
|
+
revalidate?: number | false;
|
|
136
|
+
};
|
|
137
|
+
};
|
|
138
|
+
/**
|
|
139
|
+
* Options to spread into `createServerClient` so Next's data cache does the
|
|
140
|
+
* caching: `createServerClient({ serverUrl, apiToken, ...withNextCache({ revalidate: 300 }) })`.
|
|
141
|
+
*/
|
|
142
|
+
declare function withNextCache(options?: {
|
|
143
|
+
revalidate?: number | false;
|
|
144
|
+
}): Pick<ServerClientOptions, 'cache' | 'requestInit'>;
|
|
145
|
+
/**
|
|
146
|
+
* A route handler that verifies BuildBase's content webhook and calls
|
|
147
|
+
* `revalidateTag` for every tag it names:
|
|
148
|
+
*
|
|
149
|
+
* ```ts
|
|
150
|
+
* // app/api/webhooks/buildbase/route.ts
|
|
151
|
+
* export const POST = createNextWebhookHandler({ secret: process.env.BUILDBASE_WEBHOOK_SECRET! });
|
|
152
|
+
* ```
|
|
153
|
+
*/
|
|
154
|
+
declare function createNextWebhookHandler(options: Omit<HandleContentWebhookOptions, 'revalidate'>): (request: Request) => Promise<Response>;
|
|
155
|
+
|
|
156
|
+
export { createNextWebhookHandler, nextFetchOptions, withNextCache };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const t=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),e=(t,e)=>t>>>e|t<<32-e;function n(n){let r=1779033703,o=3144134277,i=1013904242,a=2773480762,s=1359893119,c=2600822924,l=528734635,u=1541459225;const d=n.length,f=d+1,g=f+(56-f%64+64)%64+8,h=new Uint8Array(g);h.set(n,0),h[d]=128;const p=8*d,b=Math.floor(p/4294967296),y=p>>>0;h[g-8]=b>>>24&255,h[g-7]=b>>>16&255,h[g-6]=b>>>8&255,h[g-5]=255&b,h[g-4]=y>>>24&255,h[g-3]=y>>>16&255,h[g-2]=y>>>8&255,h[g-1]=255&y;const m=new Uint32Array(64);for(let n=0;n<g;n+=64){for(let t=0;t<16;t++){const e=n+4*t;m[t]=h[e]<<24|h[e+1]<<16|h[e+2]<<8|h[e+3]}for(let t=16;t<64;t++){const n=e(m[t-15],7)^e(m[t-15],18)^m[t-15]>>>3,r=e(m[t-2],17)^e(m[t-2],19)^m[t-2]>>>10;m[t]=m[t-16]+n+m[t-7]+r>>>0}let d=r,f=o,g=i,p=a,b=s,y=c,w=l,v=u;for(let n=0;n<64;n++){const r=v+(e(b,6)^e(b,11)^e(b,25))+(b&y^~b&w)+t[n]+m[n]>>>0,o=d&f^d&g^f&g;v=w,w=y,y=b,b=p+r>>>0,p=g,g=f,f=d,d=r+((e(d,2)^e(d,13)^e(d,22))+o>>>0)>>>0}r=r+d>>>0,o=o+f>>>0,i=i+g>>>0,a=a+p>>>0,s=s+b>>>0,c=c+y>>>0,l=l+w>>>0,u=u+v>>>0}const w=new Uint8Array(32),v=[r,o,i,a,s,c,l,u];for(let t=0;t<8;t++)w[4*t]=v[t]>>>24&255,w[4*t+1]=v[t]>>>16&255,w[4*t+2]=v[t]>>>8&255,w[4*t+3]=255&v[t];return w}function r(t){return(new TextEncoder).encode(t)}function o(t,e){const n=new Uint8Array(t.length+e.length);return n.set(t,0),n.set(e,t.length),n}function i(t){const{body:e,signature:i,timestamp:a,secret:s,maxAgeSeconds:c=300}=t;if(!(i&&a&&s&&e))return!1;const l="sha256=";if(!i.startsWith(l))return!1;const u=i.slice(7);if(c>0){const t=parseInt(a,10);if(isNaN(t))return!1;if(Math.abs(Math.floor(Date.now()/1e3)-t)>c)return!1}const d=function(t){if(t.length%2!=0)return null;const e=new Uint8Array(t.length/2);for(let n=0;n<e.length;n++){const r=parseInt(t.slice(2*n,2*n+2),16);if(Number.isNaN(r))return null;e[n]=r}return e}(u);if(!d)return!1;const f=function(t,e){let r=t;r.length>64&&(r=n(r));const i=new Uint8Array(64),a=new Uint8Array(64);for(let t=0;t<64;t++){const e=t<r.length?r[t]:0;i[t]=54^e,a[t]=92^e}const s=n(o(i,e));return n(o(a,s))}(r(s),r(`${a}.${e}`));return d.length===f.length&&function(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t[r]^e[r];return 0===n}(d,f)}const a=["blog","doc","faq","faq_collection","testimonial","rich_content","collection"],s=t=>`buildbase:${t}`,c=(t,e)=>`buildbase:${t}:${e}`,l=(t,e)=>`buildbase:${t}:id:${e}`,u=new Set(["blog.published","blog.updated","blog.unpublished","blog.deleted","doc.published","doc.updated","doc.unpublished","doc.deleted","faq.updated","faq_collection.updated","testimonial.updated","testimonial.deleted","rich_content.updated","rich_content.deleted","collection.version_published","collection.record_created","collection.record_updated","collection.record_deleted"]);const d=(t,e)=>new Response(JSON.stringify(e),{status:t,headers:{"Content-Type":"application/json"}});async function f(t,e){if("POST"!==t.method)return d(405,{error:"method_not_allowed"});const n=function(t){if(!i(t))return null;try{return JSON.parse(t.body)}catch{return null}}({body:await t.text(),signature:t.headers.get("x-buildbase-signature"),timestamp:t.headers.get("x-buildbase-timestamp"),secret:e.secret,maxAgeSeconds:e.maxAgeSeconds??300});if(!n)return d(401,{error:"invalid_signature"});if(!function(t){return u.has(t)}(n.event))return d(200,{ignored:!0,event:n.event});const r=function(t,e){if(e&&Array.isArray(e.tags)&&e.tags.length>0)return[...new Set(e.tags.filter(t=>"string"==typeof t))];const n=e?.module??t.split(".")[0];if(!a.includes(n))return[];const r=[s(n)];return e?.slug&&r.push(c(n,e.slug)),e?.id&&r.push(l(n,e.id)),"faq.updated"===t&&r.push(s("faq_collection")),r}(n.event,n.data);return e.cache&&await Promise.all(r.map(t=>e.cache.deleteByTag(t))),e.revalidate&&await e.revalidate(r),e.onEvent&&await e.onEvent(n,r),d(200,{revalidated:r})}function g(t,e){return{next:void 0===e?{tags:t}:{tags:t,revalidate:e}}}function h(t={}){const e=t.revalidate??300;return{cache:!1,requestInit:t=>g(t.tags,e)}}function p(t){return e=>f(e,{...t,async revalidate(t){const{revalidateTag:e}=await import("next/cache");for(const n of t)e(n)}})}export{p as createNextWebhookHandler,g as nextFetchOptions,h as withNextCache};
|
package/dist/tracking/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";var e=require("react/jsx-runtime"),t=require("react");const n="__buildbaseBeforeLeave",r=globalThis,i=r[n]??(r[n]=new Set);const o="bb_attr",a=["gclid","gbraid","wbraid","dclid","fbclid","msclkid","li_fat_id","twclid","ttclid","rdt_cid","epik","irclickid","utm_source","utm_medium","utm_campaign","utm_term","utm_content","utm_id"],s=/^[\w.~-]{1,200}$/;function c(){return"undefined"==typeof window?null:window}function d(e,t){if(!e||!e.includes("."))return"";if(/^\d{1,3}(\.\d{1,3}){3}$/.test(e))return"";const n=t??c()?.document;if(!n)return"";const r=e.split(".");for(let e=r.length-2;e>=0;e--){const t="."+r.slice(e).join("."),i=`__bb_probe_${Date.now()}`;n.cookie=`${i}=1; domain=${t}; path=/; SameSite=Lax`;const o=n.cookie.includes(`${i}=1`);if(n.cookie=`${i}=; domain=${t}; path=/; max-age=0; SameSite=Lax`,o)return t}return""}function l(e){const t=e.cookie.split("; ").find(e=>e.startsWith(`${o}=`));if(!t)return{};try{const e=JSON.parse(decodeURIComponent(t.slice(8)));return"object"==typeof e&&e?e:{}}catch{return{}}}const u=a.filter(e=>!e.startsWith("utm_")),p=e=>u.some(t=>!!e[t]);function g(){const e=c();if(!e)return{};const t=e.document,n=l(t),r=function(e){const t=new URLSearchParams(e),n={};for(const e of a){const r=t.get(e);r&&(r.length>200||s.test(r)&&(n[e]=r))}return n}(e.location.search),i=Object.keys(r).length>0&&(p(r)||!p(n)),u=i?r:n;return 0===Object.keys(u).length?{}:(i&&!function(e,t){const n=new Set([...Object.keys(e),...Object.keys(t)]);for(const r of n)if(e[r]!==t[r])return!1;return!0}(r,n)&&function(e,t,n){const r=encodeURIComponent(JSON.stringify(t));e.cookie=`${o}=${r}; path=/; max-age=7776000; SameSite=Lax`+(n?`; domain=${n}`:"")}(t,u,d(e.location.hostname,t)),u)}function f(e){try{const t=new URLSearchParams(e);return t.has("code")&&t.has("state")}catch{return!1}}const m="bb_pending_checkout";function h(){try{return"undefined"==typeof window?null:window.sessionStorage}catch{return null}}const y="bb_co";function w(){try{return"undefined"==typeof window?null:window.document??null}catch{return null}}function v(){const e=w();if(e)try{const t=d(window.location?.hostname??"",e);e.cookie=`${y}=; path=/; max-age=0; SameSite=Lax`+(t?`; domain=${t}`:"")}catch{}}function _(e,t){if(!e)return null;try{const n=JSON.parse(e);return n&&"string"==typeof n.eventId&&n.eventId?"number"!=typeof n.startedAt||t-n.startedAt>216e5?null:n:null}catch{return null}}function k(e=Date.now()){const t=h();if(!t)return null;let n=null;try{n=t.getItem(m),t.removeItem(m)}catch{return null}const r=_(n,e);return r&&v(),r}function b(e){try{return _(h()?.getItem(m)??null,e)}catch{return null}}function I(e,t=Date.now()){let n=null;try{n=new URLSearchParams(e).get("session_id")}catch{return null}if(!n)return null;const r=b(t);if(r?.sessionId===n)return k(t);const i=function(e){const t=w();if(!t||"string"!=typeof t.cookie)return null;const n=t.cookie.split("; ").find(e=>e.startsWith(`${y}=`));return n?_(decodeURIComponent(n.slice(6)),e):null}(t);return i?.sessionId!==n?null:(v(),i)}function C(e,t=Date.now()){return function(e){let t=null;try{t=new URLSearchParams(e).get("bb")}catch{return!1}if(!t)return!1;const n={};for(const e of t.split(",")){const t=e.indexOf(":");if(-1!==t)try{n[decodeURIComponent(e.slice(0,t))]=decodeURIComponent(e.slice(t+1))}catch{}}return"checkout"===n.action&&"cancel"===n.status}(e)&&b(t)?k(t):null}const x=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","ugx","vnd","vuv","xaf","xof","xpf"]),$=new Set(["bhd","jod","kwd","omr","tnd"]);function j(e,t){if("number"!=typeof e||!Number.isFinite(e))return;const n=(t??"").toLowerCase();return x.has(n)?e:e/($.has(n)?1e3:100)}function A(){return"undefined"==typeof window?null:window}function S(e){const t=A();if(!t)return;t.gtag?.("consent","update",{ad_storage:e.marketing?"granted":"denied",ad_user_data:e.marketing?"granted":"denied",ad_personalization:e.marketing?"granted":"denied",analytics_storage:e.analytics?"granted":"denied"});const n=t.fbq;n?.("consent",e.marketing?"grant":"revoke")}const q={gtm:{title:"Google Tag Manager",vendor:"Google LLC",privacyUrl:"https://policies.google.com/privacy",idLabel:"Container ID",idPattern:"^GTM-[A-Z0-9]{4,10}$",idExample:"GTM-ABC1234",scriptOrigin:"https://www.googletagmanager.com",defaultConsentCategory:"analytics",supportsConsentMode:!0,needsConversionIds:!1},ga4:{title:"Google Analytics 4",vendor:"Google LLC",privacyUrl:"https://policies.google.com/privacy",idLabel:"Measurement ID",idPattern:"^G-[A-Z0-9]{8,12}$",idExample:"G-ABCD123456",scriptOrigin:"https://www.googletagmanager.com",defaultConsentCategory:"analytics",supportsConsentMode:!0,needsConversionIds:!1},google_ads:{title:"Google Ads",vendor:"Google LLC",privacyUrl:"https://policies.google.com/privacy",idLabel:"Conversion ID",idPattern:"^AW-[0-9]{9,12}$",idExample:"AW-123456789",scriptOrigin:"https://www.googletagmanager.com",defaultConsentCategory:"marketing",supportsConsentMode:!0,needsConversionIds:!0},meta_pixel:{title:"Meta Pixel",vendor:"Meta Platforms Ireland Limited",privacyUrl:"https://www.facebook.com/privacy/policy",idLabel:"Pixel ID",idPattern:"^[0-9]{15,16}$",idExample:"123456789012345",scriptOrigin:"https://connect.facebook.net",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!1,multiInstance:!0},x_pixel:{title:"X (Twitter) Pixel",vendor:"X Corp.",privacyUrl:"https://x.com/en/privacy",idLabel:"Pixel ID",idPattern:"^o[a-z0-9]{4,6}$",idExample:"o1a2b3",scriptOrigin:"https://static.ads-twitter.com",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!0,multiInstance:!0},linkedin:{title:"LinkedIn Insight Tag",vendor:"LinkedIn Ireland Unlimited Company",privacyUrl:"https://www.linkedin.com/legal/privacy-policy",idLabel:"Partner ID",idPattern:"^[0-9]{6,9}$",idExample:"1234567",scriptOrigin:"https://snap.licdn.com",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!0,multiInstance:!0},tiktok:{title:"TikTok Pixel",vendor:"TikTok Information Technologies UK Limited",privacyUrl:"https://www.tiktok.com/legal/privacy-policy",idLabel:"Pixel ID",idPattern:"^[A-Z0-9]{20}$",idExample:"C4A1B2C3D4E5F6G7H8I9",scriptOrigin:"https://analytics.tiktok.com",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!1,multiInstance:!0},reddit:{title:"Reddit Pixel",vendor:"Reddit, Inc.",privacyUrl:"https://www.reddit.com/policies/privacy-policy",idLabel:"Advertiser ID",idPattern:"^t2_[a-z0-9]{4,12}$",idExample:"t2_abc123",scriptOrigin:"https://www.redditstatic.com",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!1,multiInstance:!0},bing_uet:{title:"Microsoft Advertising (UET)",vendor:"Microsoft Corporation",privacyUrl:"https://privacy.microsoft.com/en-us/privacystatement",idLabel:"Tag ID",idPattern:"^[0-9]{7,9}$",idExample:"12345678",scriptOrigin:"https://bat.bing.com",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!1,multiInstance:!0},clarity:{title:"Microsoft Clarity",vendor:"Microsoft Corporation",privacyUrl:"https://privacy.microsoft.com/en-us/privacystatement",idLabel:"Project ID",idPattern:"^[a-z0-9]{10}$",idExample:"ab12cd34ef",scriptOrigin:"https://www.clarity.ms",defaultConsentCategory:"analytics",supportsConsentMode:!1,needsConversionIds:!1},hotjar:{title:"Hotjar",vendor:"Hotjar Limited",privacyUrl:"https://www.hotjar.com/legal/policies/privacy/",idLabel:"Site ID",idPattern:"^[0-9]{6,9}$",idExample:"1234567",scriptOrigin:"https://static.hotjar.com",defaultConsentCategory:"analytics",supportsConsentMode:!1,needsConversionIds:!1},posthog:{title:"PostHog",vendor:"PostHog, Inc.",privacyUrl:"https://posthog.com/privacy",idLabel:"Project API key",idPattern:"^phc_[A-Za-z0-9]{32,48}$",idExample:"phc_abcdefghijklmnopqrstuvwxyz012345",scriptOrigin:"https://us-assets.i.posthog.com",defaultConsentCategory:"analytics",supportsConsentMode:!1,needsConversionIds:!1,hosts:["us.i.posthog.com","eu.i.posthog.com"]},plausible:{title:"Plausible Analytics",vendor:"Plausible Insights OÜ",privacyUrl:"https://plausible.io/privacy",idLabel:"Domain",idPattern:"^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$",idExample:"example.com",scriptOrigin:"https://plausible.io",defaultConsentCategory:"analytics",supportsConsentMode:!1,needsConversionIds:!1},ahrefs:{title:"Ahrefs Analytics",vendor:"Ahrefs Pte. Ltd.",privacyUrl:"https://ahrefs.com/privacy",idLabel:"Analytics key",idPattern:"^[A-Za-z0-9+/=]{20,64}$",idExample:"AbCdEfGhIjKlMnOpQrStUv==",scriptOrigin:"https://analytics.ahrefs.com",defaultConsentCategory:"analytics",supportsConsentMode:!1,needsConversionIds:!1}},P=Object.keys(q);function E(e){return"string"==typeof e&&Object.prototype.hasOwnProperty.call(q,e)}function O(e,t){return!!E(e)&&("string"==typeof t&&0!==t.length&&new RegExp(q[e].idPattern).test(t))}const T=/^[a-z][a-z0-9-]{0,40}$/,U=/^[\w.:/@+=-]{1,200}$/;function L(e){return function(e){if("string"!=typeof e)return!1;if(0===e.length||e.length>300)return!1;let t;try{t=new URL(e)}catch{return!1}return!("https:"!==t.protocol||!t.hostname||!t.hostname.includes(".")||e.includes("?")||e.includes("#")||t.username||t.password)}(e.src)&&function(e){if(null==e)return!0;if("object"!=typeof e||Array.isArray(e))return!1;const t=Object.entries(e);return!(t.length>12)&&t.every(([e,t])=>T.test(e)&&"string"==typeof t&&U.test(t))}(e.dataAttributes)}const R=Array.from(new Set(P.map(e=>q[e].scriptOrigin))).sort(),M={sign_up:{ga4:"sign_up",meta:"CompleteRegistration",tiktok:"CompleteRegistration",reddit:"SignUp"},login:{ga4:"login",meta:null,tiktok:null,reddit:null},trial_started:{ga4:"begin_checkout",meta:"StartTrial",tiktok:"StartTrial",reddit:"Lead"},checkout_started:{ga4:"begin_checkout",meta:"InitiateCheckout",tiktok:"InitiateCheckout",reddit:"AddToCart"},purchase:{ga4:"purchase",meta:"Purchase",tiktok:"CompletePayment",reddit:"Purchase"},subscription_created:{ga4:"purchase",meta:"Subscribe",tiktok:"Subscribe",reddit:"Purchase"},subscription_upgraded:{ga4:"subscription_upgraded",meta:null,tiktok:null,reddit:null},lead:{ga4:"generate_lead",meta:"Lead",tiktok:"SubmitForm",reddit:"Lead"},workspace_created:{ga4:"workspace_created",meta:null,tiktok:null,reddit:null}},D=Object.keys(M);function N(e){return D.includes(e)}function B(){return"undefined"==typeof window?null:window}const G={gtm:"dataLayer",ga4:"gtag",google_ads:"gtag",meta_pixel:"fbq",x_pixel:"twq",linkedin:"lintrk",tiktok:"ttq",reddit:"rdt",bing_uet:"uetq",clarity:"clarity",hotjar:"hj",posthog:"posthog",plausible:"plausible",ahrefs:"__ahrefs_loaded"};function V(){return"undefined"==typeof window?null:window}function z(e,t={}){const n=V();if(!n)return null;const r=n.document.createElement("script");r.async=!0,r.src=e;for(const[e,n]of Object.entries(t))r.setAttribute(e,n);return n.document.head.appendChild(r),r}function F(e){const t=V();if(!t)return;const n=t.document.createElement("script");n.text=e,t.document.head.appendChild(n)}function H(e){const t=V();t&&(Array.isArray(t[e])||(t[e]=[]),"function"!=typeof t.gtag&&(t.gtag=function(){t[e].push(arguments)}))}const W=new Set;function Z(e){for(const t of W)if(t.slice(0,t.indexOf(":"))===e)return!0;return!1}function J(e,t){const n=V();if(!n)return!1;if("gtm"===e||"ga4"===e||"google_ads"===e){const e=n.google_tag_manager;return!(!e||"object"!=typeof e)&&Object.prototype.hasOwnProperty.call(e,t)}const r=G[e];if(!r)return!1;if(void 0===n[r])return!1;if(W.has(`${e}:${t}`))return!0;return!q[e].multiInstance||!Z(e)}const K={meta_pixel:e=>`fbq('init','${e}');fbq('track','PageView');`,x_pixel:e=>`twq('config','${e}');`,tiktok:e=>`ttq.load('${e}');ttq.page();`,reddit:e=>`rdt('init','${e}');rdt('track','PageVisit');`,bing_uet:e=>`window.uetq=window.uetq||[];window.uetq.push({ti:'${e}',enableAutoSpaTracking:false});`,linkedin:e=>`window._linkedin_data_partner_ids=window._linkedin_data_partner_ids||[];window._linkedin_data_partner_ids.push('${e}');`};function Q(e,t,n){const r=function(e,t,n){const r=V();if(!r)return!1;if("external"===e.provider){if(!e.src)return!1;const t={};for(const[n,r]of Object.entries(e.dataAttributes??{}))t[`data-${n}`]=r;return z(e.src,t),!0}const i=e.provider,o=q[i];if(!o)return!1;const a=e.providerId;if(!a)return!1;const s=K[i];if(s&&Z(i))return F(s(a)),!0;switch(i){case"gtm":{H(t),r[t].push({"gtm.start":Date.now(),event:"gtm.js"});const e="dataLayer"===t?"":`&l=${t}`;return z(`${o.scriptOrigin}/gtm.js?id=${a}${e}`),!0}case"ga4":case"google_ads":{H(t),z(`${o.scriptOrigin}/gtag/js?id=${a}`);const e=r.gtag;e("js",new Date);const s="ga4"===i&&n?.gaClientId?{client_id:n.gaClientId}:void 0;return s?e("config",a,s):e("config",a),!0}case"meta_pixel":return F(`!function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,document,'script','${o.scriptOrigin}/en_US/fbevents.js');fbq('init','${a}');fbq('track','PageView');`),!0;case"x_pixel":return F(`!function(e,t,n,s,u,a){e.twq||(s=e.twq=function(){s.exe?s.exe.apply(s,arguments):s.queue.push(arguments)},s.version='1.1',s.queue=[],u=t.createElement(n),u.async=!0,u.src='${o.scriptOrigin}/uwt.js',a=t.getElementsByTagName(n)[0],a.parentNode.insertBefore(u,a))}(window,document,'script');twq('config','${a}');`),!0;case"linkedin":return F(`window._linkedin_partner_id='${a}';window._linkedin_data_partner_ids=window._linkedin_data_partner_ids||[];window._linkedin_data_partner_ids.push('${a}');window.lintrk=window.lintrk||function(a,b){(window.lintrk.q=window.lintrk.q||[]).push([a,b])};window.lintrk.q=window.lintrk.q||[];`),z(`${o.scriptOrigin}/li.lms-analytics/insight.min.js`),!0;case"tiktok":return F(`!function(w,d,t){w.TiktokAnalyticsObject=t;var ttq=w[t]=w[t]||[];ttq.methods=['page','track','identify','instances','debug','on','off','once','ready','alias','group','enableCookie','disableCookie'];ttq.setAndDefer=function(t,e){t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}};for(var i=0;i<ttq.methods.length;i++)ttq.setAndDefer(ttq,ttq.methods[i]);ttq.load=function(e,n){var r='${o.scriptOrigin}/i18n/pixel/events.js';ttq._i=ttq._i||{};ttq._i[e]=[];ttq._i[e]._u=r;ttq._t=ttq._t||{};ttq._t[e]=+new Date;ttq._o=ttq._o||{};ttq._o[e]=n||{};var o=d.createElement('script');o.type='text/javascript';o.async=!0;o.src=r+'?sdkid='+e+'&lib='+t;var a=d.getElementsByTagName('script')[0];a.parentNode.insertBefore(o,a)};ttq.load('${a}');ttq.page()}(window,document,'ttq');`),!0;case"reddit":return F(`!function(w,d){if(!w.rdt){var p=w.rdt=function(){p.sendEvent?p.sendEvent.apply(p,arguments):p.callQueue.push(arguments)};p.callQueue=[];var t=d.createElement('script');t.src='${o.scriptOrigin}/ads/pixel.js';t.async=!0;var s=d.getElementsByTagName('script')[0];s.parentNode.insertBefore(t,s)}}(window,document);rdt('init','${a}');rdt('track','PageVisit');`),!0;case"bing_uet":return F(`(function(w,d,t,r,u){w[u]=w[u]||[];w[u].push({ti:'${a}',enableAutoSpaTracking:false});var o=d.createElement(t);o.src='${o.scriptOrigin}/bat.js';o.async=1;var i=d.getElementsByTagName(t)[0];i.parentNode.insertBefore(o,i)})(window,document,'script',0,'uetq');`),!0;case"clarity":return F(`(function(c,l,a,r,i,t,y){c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)};t=l.createElement(r);t.async=1;t.src='${o.scriptOrigin}/tag/'+i;y=l.getElementsByTagName(r)[0];y.parentNode.insertBefore(t,y)})(window,document,'clarity','script','${a}');`),!0;case"hotjar":return F(`(function(h,o,t,j,a,r){h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)};h._hjSettings={hjid:${a},hjsv:6};a=o.getElementsByTagName('head')[0];r=o.createElement('script');r.async=1;r.src='${o.scriptOrigin}/hotjar-'+h._hjSettings.hjid+'.js?sv='+h._hjSettings.hjsv;a.appendChild(r)})(window,document);`),!0;case"posthog":{const t=o.hosts,n=t?.includes(e.host??"")?e.host:t?.[0]??"us.i.posthog.com";return F(`!function(t,e){var o,n,p,r;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split('.');2==o.length&&(t=t[o[0]],e=o[1]);t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement('script')).type='text/javascript',p.async=!0,p.src='${o.scriptOrigin}/static/array.js',(r=t.getElementsByTagName('script')[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a='posthog',u.people=u.people||[],u.toString=function(t){var e='posthog';return'posthog'!==a&&(e+='.'+a),t||(e+=' (stub)'),e},u.people.toString=function(){return u.toString(1)+'.people (stub)'},o='init capture register register_once identify alias people.set people.set_once set_config get_distinct_id getFeatureFlag isFeatureEnabled onFeatureFlags reloadFeatureFlags group reset'.split(' '),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);posthog.init('${a}',{api_host:'https://${n}'});`),!0}case"plausible":return F("window.plausible=window.plausible||function(){(window.plausible.q=window.plausible.q||[]).push(arguments)};"),z(`${o.scriptOrigin}/js/script.js`,{"data-domain":a,defer:"true"}),!0;case"ahrefs":return z(`${o.scriptOrigin}/analytics.js`,{"data-key":a}),r.__ahrefs_loaded=!0,!0;default:return!1}}(e,t,n);return r&&"external"!==e.provider&&e.providerId&&W.add(`${e.provider}:${e.providerId}`),r}const X=Symbol.for("@buildbase/sdk.tracking.context"),Y=globalThis,ee=Y[X]??(Y[X]=t.createContext(null)),te={consent:{manifest:[],state:null,set:()=>{}},track:()=>{},setUser:()=>{},setProperties:()=>{},getProperties:()=>({}),completeCheckout:async()=>{},installed:{},ready:!0,attribution:{}};function ne(){return t.useContext(ee)??te}const re=({serverUrl:n,orgId:r,clientId:o,enabled:a=!0,consent:s="auto",autoPageview:c=!0,events:d,onEvent:l,properties:u,enrich:p,identity:m,debug:h=!1,children:y})=>{const w=t.useRef(m);w.current=m;const[v,_]=t.useState(null),[k,b]=t.useState(!1),[x,$]=t.useState(!1),P="granted"===s?{analytics:!0,marketing:!0}:"denied"===s?{analytics:!1,marketing:!1}:null,[T,U]=t.useState(P),R=t.useRef(null),D=t.useRef(l);D.current=l;const G=t.useRef(p);G.current=p;const V=t.useRef({});V.current=u??{};const z=t.useRef({}),F=t.useCallback(()=>({...V.current,...z.current}),[]),W=t.useCallback(e=>{const t={...z.current,...e};for(const[e,n]of Object.entries(t))void 0===n&&delete t[e];z.current=t},[]),[Z,K]=t.useState({}),X=t.useRef({}),[Y,te]=t.useState(0),ne=v?.dataLayerName??"dataLayer",re=t.useCallback((...e)=>{h&&console.info("[buildbase:tracking]",...e)},[h]);t.useEffect(()=>{return e=()=>{0!==Object.keys(X.current).length&&window.dispatchEvent("function"==typeof PageTransitionEvent?new PageTransitionEvent("pagehide",{persisted:!1}):new Event("pagehide"))},i.add(e),()=>{i.delete(e)};var e},[]),t.useEffect(()=>{if(!(a&&n&&r&&o))return void b(!0);let e=!1;const t=`${n.replace(/\/$/,"")}/api/v1/public/${r}/tracking?clientId=${encodeURIComponent(o)}`;return fetch(t).then(e=>e.ok?e.json():null).then(t=>{if(e||!t)return;const n=t.data??t;n&&Array.isArray(n.scripts)&&_(n)}).catch(()=>{re("config fetch failed; nothing installed")}).finally(()=>{e||b(!0)}),()=>{e=!0}},[a,n,r,o,re]),t.useEffect(()=>{a&&K(g())},[a]),t.useEffect(()=>{a&&v?.enabled&&(H(ne),function(e,t){const n=A();if(!n)return;Array.isArray(n[e])||(n[e]=[]),"function"!=typeof n.gtag&&(n.gtag=function(){n[e].push(arguments)});const r="granted"===t?"granted":"denied";n.gtag("consent","default",{ad_storage:r,ad_user_data:r,ad_personalization:r,analytics_storage:r,wait_for_update:500})}(ne,s),R.current&&S(R.current))},[a,v?.enabled,ne,s]);const ie=t.useMemo(()=>v?.enabled?v.scripts.filter(e=>{const t=E(e.provider)&&q[e.provider].supportsConsentMode;return function(e,t,n,r){return"denied"!==r&&("granted"===r||(n?"marketing"===e?n.marketing:n.analytics:t&&"analytics"===e))}(e.consentCategory,t,T,s)}):[],[v,T,s]),[oe,ae]=t.useState(()=>"undefined"==typeof window||!f(window.location.search));t.useEffect(()=>{if(oe)return;const e=setInterval(()=>{f(window.location.search)||ae(!0)},50),t=setTimeout(()=>ae(!0),5e3);return()=>{clearInterval(e),clearTimeout(t)}},[oe]),t.useEffect(()=>{if(!oe)return;if(!a||!v?.enabled)return void(k&&$(!0));let e=0;for(const t of ie)if(!X.current[t.key]){if("external"===t.provider){if(!L({src:t.src,dataAttributes:t.dataAttributes})){re("rejected external script",t.key);continue}}else{if(!E(t.provider)){re("rejected unknown provider",t.provider);continue}if(!O(t.provider,t.providerId)){re("rejected id for",t.provider);continue}if(J(t.provider,t.providerId??"")){re(`${t.provider} ${t.providerId} is already on the page; skipping. Configure each tag in exactly one place.`);continue}}Q(t,ne,w.current)&&(X.current[t.key]=t.providerId??t.src??"",e+=1,re("installed",t.key))}e&&te(e=>e+1);const t=window;t.__buildbase=t.__buildbase??{},t.__buildbase.tracking={installed:{...X.current},dataLayerName:ne,clientId:o};const n=Object.keys(X.current).length>0,r=null!==T||0===v.scripts.length;(n||r)&&$(!0)},[a,v,ie,k,T,ne,re,oe,o]),t.useEffect(()=>{if(!a||!c||!v?.enabled)return;if("undefined"==typeof window)return;if(!oe)return;let e=null;const t=()=>{e&&clearTimeout(e),e=setTimeout(()=>function(e,t){const n=B();if(!n)return;const r=n[t];Array.isArray(r)&&r.push({event:"page_view",page_path:n.location.pathname,page_location:n.location.href,page_title:n.document.title});for(const t of e)switch(t.provider){case"ga4":n.gtag?.("event","page_view",{send_to:t.providerId,page_path:n.location.pathname,page_location:n.location.href,page_title:n.document.title});break;case"meta_pixel":n.fbq?.("track","PageView");break;case"tiktok":{const e=n.ttq;e?.page?.();break}case"reddit":n.rdt?.("track","PageVisit")}}(ie,ne),50)},n=window.history,r=n.pushState,i=n.replaceState;return n.pushState=function(...e){const n=r.apply(this,e);return t(),n},n.replaceState=function(...e){const n=i.apply(this,e);return t(),n},window.addEventListener("popstate",t),()=>{n.pushState=r,n.replaceState=i,window.removeEventListener("popstate",t),e&&clearTimeout(e)}},[a,c,v?.enabled,ie,ne,oe]),t.useEffect(()=>{if(!a)return;const e=function(e,t){const n=e?.mode??"auto",r=e?.overrides??{};if(("manual"===n||Object.values(r).some(e=>"manual"===e))&&!t)return'[buildbase:tracking] events are set to "manual" but no onEvent handler was provided, so those events would never fire anywhere. Pass onEvent, or use mode "auto".';for(const e of Object.keys(r))if(!N(e))return`[buildbase:tracking] unknown event "${e}" in events.overrides. Overrides only apply to the events the SDK fires itself.`;return null}(d,!!l);if(e)throw new Error(e)},[a,d,l]);const se=t.useCallback((e,t={},n)=>{if(!a)return;const r=n?.eventId||function(){const e=globalThis.crypto;return e?.randomUUID?e.randomUUID():`${Date.now().toString(16)}-${Math.random().toString(16).slice(2,10)}`}(),i=d?.mode??"auto",o=(N(e)?d?.overrides?.[e]:void 0)??i,s={...V.current,...z.current,...Z,...t},c=G.current?.({name:e,params:s})??{},l={...s,...c},u=D.current?.({name:e,params:l,eventId:r,handledBy:o});"manual"!==o&&!0!==u?(!function(e,t,n,r,i){const o=B();if(!o)return;const a=o[i];Array.isArray(a)&&a.push({event:e,...t,event_id:n});const s=N(e)?M[e]:{ga4:e,meta:null,tiktok:null,reddit:null};for(const i of r){const r=i.provider,a=q[r];if(a){if(a.needsConversionIds){const a=i.conversionIds?.[e];if(!a)continue;"google_ads"===r?o.gtag?.("event","conversion",{send_to:`${i.providerId}/${a}`,transaction_id:n,...t}):"x_pixel"===r?o.twq?.("event",a,{...t,conversion_id:n}):"linkedin"===r&&o.lintrk?.("track",{conversion_id:a});continue}switch(r){case"ga4":s.ga4&&o.gtag?.("event",s.ga4,{...t,send_to:i.providerId,event_id:n});break;case"meta_pixel":s.meta&&o.fbq?.("track",s.meta,t,{eventID:n});break;case"tiktok":if(s.tiktok){const e=o.ttq;e?.track?.(s.tiktok,{...t,event_id:n})}break;case"reddit":s.reddit&&o.rdt?.("track",s.reddit,{...t,conversionId:n});break;case"bing_uet":{const r=o.uetq;r?.push?.("event",s.ga4??e,{...t,event_id:n});break}case"clarity":o.clarity?.("event",e);break;case"hotjar":{const t=o.hj;t?.("event",e);break}case"posthog":{const r=o.posthog;r?.capture?.(e,{...t,event_id:n});break}case"plausible":o.plausible?.(e,{props:t})}}}}(e,l,r,ie,ne),re("event fired:",e,r)):re("event handled by app:",e)},[a,d,ie,ne,Z,re]),ce=t.useCallback(async(e,t={})=>{const i=function(e){return{name:"trial_started"===e.kind?"trial_started":"purchase",params:{...e.workspaceId?{workspace_id:e.workspaceId}:{},...e.planVersionId?{plan_version_id:e.planVersionId}:{},...e.creditPackageId?{credit_package_id:e.creditPackageId}:{},...e.billingInterval?{billing_interval:e.billingInterval}:{},...e.currency?{currency:e.currency.toUpperCase()}:{},..."number"==typeof e.value?{value:e.value}:{},...e.sessionId?{transaction_id:e.sessionId}:{}}}}(e);let o=i.params;if(e.sessionId&&n&&r){const t=await async function(e,t){try{const n=e.serverUrl.replace(/\/$/,""),r=await fetch(`${n}/api/v1/public/${encodeURIComponent(e.orgId)}/checkout/${encodeURIComponent(t)}`,{credentials:"omit",..."undefined"!=typeof AbortSignal&&AbortSignal.timeout?{signal:AbortSignal.timeout(2e3)}:{}});if(!r.ok)return null;const i=await r.json(),o=i?.data??i;return"number"!=typeof o?.amount?null:{value:j(o.amount,o.currency),currency:"string"==typeof o.currency?o.currency:void 0,...Array.isArray(o.items)&&o.items.length?{items:o.items}:{}}}catch{return null}}({serverUrl:n,orgId:r},e.sessionId);t&&"number"==typeof t.value&&(o={...o,value:t.value,...t.currency?{currency:t.currency.toUpperCase()}:{},...t.items?.length?{items:t.items}:{}})}if(se(i.name,{...o,...t},{eventId:e.eventId}),"purchase"===i.name&&e.sessionId&&n&&r){const t=(v?.scripts??[]).find(e=>"ga4"===e.provider&&e.providerId);t&&J("ga4",t.providerId??"")&&function(e,t,n){try{const r=e.serverUrl.replace(/\/$/,"");fetch(`${r}/api/v1/public/${encodeURIComponent(e.orgId)}/checkout/${encodeURIComponent(t)}/reported`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:n}),keepalive:!0,credentials:"omit"}).catch(()=>{})}catch{}}({serverUrl:n,orgId:r},e.sessionId,"ga4")}},[n,r,se,v]),[de]=t.useState(()=>"undefined"==typeof window?"":window.location.search);t.useEffect(()=>{if(!a||!x)return;if("undefined"==typeof window)return;const e=I(window.location.search);if(e)return void ce(e);const t=C(de);t&&se("checkout_abandoned",{...t.workspaceId?{workspace_id:t.workspaceId}:{},...t.planVersionId?{plan_version_id:t.planVersionId}:{},...t.creditPackageId?{credit_package_id:t.creditPackageId}:{},...t.billingInterval?{billing_interval:t.billingInterval}:{},...t.currency?{currency:t.currency.toUpperCase()}:{},..."number"==typeof t.value?{value:t.value}:{},seconds_at_checkout:Math.max(0,Math.round((Date.now()-t.startedAt)/1e3))})},[a,x,ce,de,se]);const le=t.useCallback(e=>{R.current=e,U(e),S(e)},[]),ue=t.useCallback((e,t)=>function(e,t,n){const r=B();if(!r)return;const i=!!n&&Object.keys(n).length>0;for(const o of t)switch(o.provider){case"ga4":case"google_ads":r.gtag?.("set",{user_id:e}),i&&r.gtag?.("set",{user_properties:n});break;case"meta_pixel":o.providerId&&r.fbq?.("init",o.providerId,{external_id:e});break;case"posthog":r.posthog?.identify?.(e,i?n:void 0);break;case"clarity":if(r.clarity?.("identify",e),i)for(const[e,t]of Object.entries(n))r.clarity?.("set",e,String(t));break;case"hotjar":r.hj?.("identify",e,{});break;case"tiktok":{const t=r.ttq;t?.identify?.({external_id:e});break}}}(e,ie,t),[ie]),pe=t.useMemo(()=>({consent:{manifest:v?.consent?.manifest??[],state:T,set:le},track:se,setUser:ue,setProperties:W,getProperties:F,completeCheckout:ce,installed:{...X.current},ready:x,attribution:Z}),[v,T,le,se,ue,W,F,ce,x,Y,Z]);return e.jsx(ee.Provider,{value:pe,children:y})};re.displayName="BuildBaseTracking";exports.ATTRIBUTION_PARAMS=a,exports.BuildBaseTracking=re,exports.EVENT_MAPPINGS=M,exports.FUNNEL_EVENTS={sign_in_started:"The sign-in / sign-up button was pressed.",pricing_viewed:"A <PricingPage> finished loading its plans.",pricing_plan_selected:"A plan was chosen on a <PricingPage>.",workspace_switcher_opened:"The workspace switcher was opened.",workspace_settings_opened:"The workspace settings modal was opened.",workspace_settings_section_viewed:"A different section of the settings modal was opened.",plan_picker_opened:"The plan picker was shown.",billing_interval_changed:"Monthly / quarterly / yearly was switched in the plan picker.",plan_selected:"A plan was chosen in the plan picker.",plan_picker_dismissed:"The plan picker was closed without choosing a plan.",checkout_abandoned:"The customer came back from Stripe without paying.",billing_portal_opened:"Stripe’s billing portal was opened.",subscription_cancel_started:"The cancel-subscription confirmation was opened.",subscription_cancelled:"A subscription was cancelled.",subscription_resumed:"A cancelled subscription was resumed.",feature_gate_shown:'A feature gate rendered its "not on your plan" side.',quota_limit_reached:"A quota gate rendered because a quota is used up.",quota_threshold_reached:"A usage-threshold gate rendered.",plan_gate_shown:'A plan gate rendered its "needs another plan" side.',subscription_notice_shown:"A billing notice (trial ending, payment failed…) was shown.",sdk_error:"An SDK operation failed (component, action and code only)."},exports.TAG_PROVIDERS=q,exports.TAG_PROVIDER_IDS=P,exports.TAG_SCRIPT_ORIGINS=R,exports.captureAttribution=g,exports.getAttribution=function(){const e=c();return e?l(e.document):{}},exports.isCanonicalEvent=N,exports.isTagProviderId=E,exports.isValidProviderId=O,exports.useCheckoutCompleted=function(e={}){const{completeCheckout:n,ready:r}=ne(),i=t.useRef(e);i.current=e;const o=t.useRef(!1);t.useEffect(()=>{if(!r)return;if(o.current)return;const e=I(window.location.search)??k();e&&(o.current=!0,n(e,i.current))},[r,n])},exports.useTracking=ne;
|
|
2
|
+
"use strict";var e=require("react/jsx-runtime"),t=require("react");const n="__buildbaseBeforeLeave",r=globalThis,i=r[n]??(r[n]=new Set);const o="bb_attr",a=["gclid","gbraid","wbraid","dclid","fbclid","msclkid","li_fat_id","twclid","ttclid","rdt_cid","epik","irclickid","utm_source","utm_medium","utm_campaign","utm_term","utm_content","utm_id"],s=/^[\w.~-]{1,200}$/;function c(){return"undefined"==typeof window?null:window}function d(e,t){if(!e||!e.includes("."))return"";if(/^\d{1,3}(\.\d{1,3}){3}$/.test(e))return"";const n=t??c()?.document;if(!n)return"";const r=e.split(".");for(let e=r.length-2;e>=0;e--){const t="."+r.slice(e).join("."),i=`__bb_probe_${Date.now()}`;n.cookie=`${i}=1; domain=${t}; path=/; SameSite=Lax`;const o=n.cookie.includes(`${i}=1`);if(n.cookie=`${i}=; domain=${t}; path=/; max-age=0; SameSite=Lax`,o)return t}return""}const l="$t",u="$l";function p(e){return function(e){const t=e.cookie.split("; ").find(e=>e.startsWith(`${o}=`));if(!t)return{params:{}};try{const e=JSON.parse(decodeURIComponent(t.slice(8)));if("object"!=typeof e||!e)return{params:{}};const{[l]:n,[u]:r,...i}=e;return{params:i,..."number"==typeof n&&n>0?{capturedAt:n}:{},..."string"==typeof r&&r?{landingUrl:r}:{}}}catch{return{params:{}}}}(e).params}function g(e){try{const{origin:t,pathname:n}=e.location;return t&&"null"!==t?`${t}${n}`.slice(0,300):void 0}catch{return}}const f=a.filter(e=>!e.startsWith("utm_")),m=e=>f.some(t=>!!e[t]);function h(){const e=c();if(!e)return{};const t=e.document,n=p(t),r=function(e){const t=new URLSearchParams(e),n={};for(const e of a){const r=t.get(e);r&&(r.length>200||s.test(r)&&(n[e]=r))}return n}(e.location.search),i=Object.keys(r).length>0&&(m(r)||!m(n)),f=i?r:n;return 0===Object.keys(f).length?{}:(i&&!function(e,t){const n=new Set([...Object.keys(e),...Object.keys(t)]);for(const r of n)if(e[r]!==t[r])return!1;return!0}(r,n)&&function(e,t,n,r){const i=encodeURIComponent(JSON.stringify({...t,[l]:r.capturedAt,...r.landingUrl?{[u]:r.landingUrl}:{}}));e.cookie=`${o}=${i}; path=/; max-age=7776000; SameSite=Lax`+(n?`; domain=${n}`:"")}(t,f,d(e.location.hostname,t),{capturedAt:Date.now(),landingUrl:g(e)}),f)}function y(e){try{const t=new URLSearchParams(e);return t.has("code")&&t.has("state")}catch{return!1}}const w="bb_pending_checkout";function v(){try{return"undefined"==typeof window?null:window.sessionStorage}catch{return null}}const _="bb_co";function b(){try{return"undefined"==typeof window?null:window.document??null}catch{return null}}function k(){const e=b();if(e)try{const t=d(window.location?.hostname??"",e);e.cookie=`${_}=; path=/; max-age=0; SameSite=Lax`+(t?`; domain=${t}`:"")}catch{}}function I(e,t){if(!e)return null;try{const n=JSON.parse(e);return n&&"string"==typeof n.eventId&&n.eventId?"number"!=typeof n.startedAt||t-n.startedAt>216e5?null:n:null}catch{return null}}function C(e=Date.now()){const t=v();if(!t)return null;let n=null;try{n=t.getItem(w),t.removeItem(w)}catch{return null}const r=I(n,e);return r&&k(),r}function S(e){try{return I(v()?.getItem(w)??null,e)}catch{return null}}function $(e,t=Date.now()){let n=null;try{n=new URLSearchParams(e).get("session_id")}catch{return null}if(!n)return null;const r=S(t);if(r?.sessionId===n)return C(t);const i=function(e){const t=b();if(!t||"string"!=typeof t.cookie)return null;const n=t.cookie.split("; ").find(e=>e.startsWith(`${_}=`));return n?I(decodeURIComponent(n.slice(6)),e):null}(t);return i?.sessionId!==n?null:(k(),i)}function x(e,t=Date.now()){return function(e){let t=null;try{t=new URLSearchParams(e).get("bb")}catch{return!1}if(!t)return!1;const n={};for(const e of t.split(",")){const t=e.indexOf(":");if(-1!==t)try{n[decodeURIComponent(e.slice(0,t))]=decodeURIComponent(e.slice(t+1))}catch{}}return"checkout"===n.action&&"cancel"===n.status}(e)&&S(t)?C(t):null}const A=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","ugx","vnd","vuv","xaf","xof","xpf"]),E=new Set(["bhd","jod","kwd","omr","tnd"]);function j(e,t){if("number"!=typeof e||!Number.isFinite(e))return;const n=(t??"").toLowerCase();return A.has(n)?e:e/(E.has(n)?1e3:100)}const P=["AT","BE","BG","HR","CY","CZ","DK","EE","FI","FR","DE","GR","HU","IE","IT","LV","LT","LU","MT","NL","PL","PT","RO","SK","SI","ES","SE","IS","LI","NO"],O=/^[A-Z]{2}(-[A-Z0-9]{1,3})?$/;function q(e){const t=new Set;for(const n of e??[]){const e=String(n).trim().toUpperCase();if("EEA"===e)for(const e of P)t.add(e);else O.test(e)&&t.add(e)}return[...t]}function U(e,t,n){return e.includes(t)}function T(e,t,n){const r=(t??"").trim().toUpperCase();if(!/^[A-Z]{2}$/.test(r)||"XX"===r||"T1"===r)return"denied";const i=(n??"").trim().toUpperCase()||void 0,o=q(e.regions?.denied),a=q(e.regions?.granted);if(i){if(o.includes(`${r}-${i}`))return"denied";if(a.includes(`${r}-${i}`))return"granted"}return U(o,r)?"denied":U(a,r)||"granted"===e.default?"granted":"denied"}function L(){return"undefined"==typeof window?null:window}const R=["ad_storage","ad_user_data","ad_personalization","analytics_storage"];function M(e){const t={};for(const n of R)t[n]=e;return t}function N(e){const t=L();if(!t)return;const n=t.gtag;n?.("consent","update",{ad_storage:e.marketing?"granted":"denied",ad_user_data:e.marketing?"granted":"denied",ad_personalization:e.marketing?"granted":"denied",analytics_storage:e.analytics?"granted":"denied"}),n?.("set","ads_data_redaction",!e.marketing);const r=t.fbq;r?.("consent",e.marketing?"grant":"revoke")}const D="bb_cid";function B(){if("undefined"!=typeof document&&"undefined"!=typeof window)try{const e=document.cookie.split("; ").find(e=>e.startsWith(`${D}=`)),t=e?.slice(7);if(t&&/^[\w-]{16,64}$/.test(t))return t;const n=function(){const e=globalThis.crypto;if(e&&"function"==typeof e.randomUUID)return e.randomUUID();const t=new Uint8Array(16);if(e&&"function"==typeof e.getRandomValues)e.getRandomValues(t);else for(let e=0;e<t.length;e++)t[e]=Math.floor(256*Math.random());return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}(),r=d(window.location.hostname,document);return document.cookie=`${D}=${n}; path=/; max-age=34128000; SameSite=Lax`+(r?`; domain=${r}`:""),n}catch{return}}const V="bb_consent_recorded";function H(e){if("function"!=typeof fetch||!e.serverUrl||!e.orgId||!e.clientId)return;const t=JSON.stringify([e.orgId,e.clientId,!!e.state.analytics,!!e.state.marketing,e.manifestVersion??"",e.consentString??"",e.headers?.["x-session-id"]?"account":"anonymous"]);if(!e.source&&function(e){try{return window.localStorage.getItem(V)===e}catch{return!1}}(t))return;!function(e){try{window.localStorage.setItem(V,e)}catch{}}(t);const n=B();if(!n)return;const r=`${e.serverUrl.replace(/\/$/,"")}/api/v1/public/${e.orgId}/consent`;try{fetch(r,{method:"POST",keepalive:!0,headers:{"content-type":"application/json",...e.headers??{}},body:JSON.stringify({clientId:e.clientId,visitorId:n,choices:{analytics:!!e.state.analytics,marketing:!!e.state.marketing},...e.manifestVersion?{manifestVersion:e.manifestVersion}:{},...e.source?{source:e.source.slice(0,40)}:{},...e.consentString?{consentString:e.consentString.slice(0,2e3)}:{}})}).catch(()=>{})}catch{}}const G=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),z=(e,t)=>e>>>t|e<<32-t;function F(e){return function(e){let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t}(function(e){let t=1779033703,n=3144134277,r=1013904242,i=2773480762,o=1359893119,a=2600822924,s=528734635,c=1541459225;const d=e.length,l=d+1,u=l+(56-l%64+64)%64+8,p=new Uint8Array(u);p.set(e,0),p[d]=128;const g=8*d,f=Math.floor(g/4294967296),m=g>>>0;p[u-8]=f>>>24&255,p[u-7]=f>>>16&255,p[u-6]=f>>>8&255,p[u-5]=255&f,p[u-4]=m>>>24&255,p[u-3]=m>>>16&255,p[u-2]=m>>>8&255,p[u-1]=255&m;const h=new Uint32Array(64);for(let e=0;e<u;e+=64){for(let t=0;t<16;t++){const n=e+4*t;h[t]=p[n]<<24|p[n+1]<<16|p[n+2]<<8|p[n+3]}for(let e=16;e<64;e++){const t=z(h[e-15],7)^z(h[e-15],18)^h[e-15]>>>3,n=z(h[e-2],17)^z(h[e-2],19)^h[e-2]>>>10;h[e]=h[e-16]+t+h[e-7]+n>>>0}let d=t,l=n,u=r,g=i,f=o,m=a,y=s,w=c;for(let e=0;e<64;e++){const t=w+(z(f,6)^z(f,11)^z(f,25))+(f&m^~f&y)+G[e]+h[e]>>>0,n=d&l^d&u^l&u;w=y,y=m,m=f,f=g+t>>>0,g=u,u=l,l=d,d=t+((z(d,2)^z(d,13)^z(d,22))+n>>>0)>>>0}t=t+d>>>0,n=n+l>>>0,r=r+u>>>0,i=i+g>>>0,o=o+f>>>0,a=a+m>>>0,s=s+y>>>0,c=c+w>>>0}const y=new Uint8Array(32),w=[t,n,r,i,o,a,s,c];for(let e=0;e<8;e++)y[4*e]=w[e]>>>24&255,y[4*e+1]=w[e]>>>16&255,y[4*e+2]=w[e]>>>8&255,y[4*e+3]=255&w[e];return y}(e))}function J(e){const t=String(e??"").trim().toLowerCase(),n=t.lastIndexOf("@");if(n<1||n===t.length-1)return"";let r=t.slice(0,n);const i=t.slice(n+1);return"gmail.com"!==i&&"googlemail.com"!==i||(r=r.replace(/\./g,"")),`${r}@${i}`}function Z(e){const t=String(e??"").trim();if(!t.startsWith("+"))return"";const n=t.replace(/[^\d]/g,"");return n.length>=8&&n.length<=15?`+${n}`:""}async function W(e){const t=globalThis.crypto?.subtle;if(t&&"function"==typeof t.digest)try{const n=await t.digest("SHA-256",(new TextEncoder).encode(e));return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,"0")).join("")}catch{}return F((n=e,(new TextEncoder).encode(n)));var n}async function K(e){const t=J(e.email),n=Z(e.phone),r={};return t&&(r.emailHash=await W(t)),n&&(r.phoneHash=await W(n)),r}function X(e,t){if("undefined"==typeof window)return;if(!t.emailHash&&!t.phoneHash)return;const n=window;e.some(e=>"google_ads"===e.provider||"ga4"===e.provider||"gtm"===e.provider)&&n.gtag?.("set","user_data",{...t.emailHash?{sha256_email_address:t.emailHash}:{},...t.phoneHash?{sha256_phone_number:t.phoneHash}:{}});for(const r of e)"meta_pixel"===r.provider&&r.providerId&&n.fbq?.("init",r.providerId,{...t.emailHash?{em:t.emailHash}:{},...t.phoneHash?{ph:t.phoneHash}:{}})}const Q={gtm:{title:"Google Tag Manager",vendor:"Google LLC",privacyUrl:"https://policies.google.com/privacy",idLabel:"Container ID",idPattern:"^GTM-[A-Z0-9]{4,10}$",idExample:"GTM-ABC1234",scriptOrigin:"https://www.googletagmanager.com",defaultConsentCategory:"analytics",supportsConsentMode:!0,needsConversionIds:!1},ga4:{title:"Google Analytics 4",vendor:"Google LLC",privacyUrl:"https://policies.google.com/privacy",idLabel:"Measurement ID",idPattern:"^G-[A-Z0-9]{8,12}$",idExample:"G-ABCD123456",scriptOrigin:"https://www.googletagmanager.com",defaultConsentCategory:"analytics",supportsConsentMode:!0,needsConversionIds:!1},google_ads:{title:"Google Ads",vendor:"Google LLC",privacyUrl:"https://policies.google.com/privacy",idLabel:"Conversion ID",idPattern:"^AW-[0-9]{9,12}$",idExample:"AW-123456789",scriptOrigin:"https://www.googletagmanager.com",defaultConsentCategory:"marketing",supportsConsentMode:!0,needsConversionIds:!0},meta_pixel:{title:"Meta Pixel",vendor:"Meta Platforms Ireland Limited",privacyUrl:"https://www.facebook.com/privacy/policy",idLabel:"Pixel ID",idPattern:"^[0-9]{15,16}$",idExample:"123456789012345",scriptOrigin:"https://connect.facebook.net",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!1,multiInstance:!0},x_pixel:{title:"X (Twitter) Pixel",vendor:"X Corp.",privacyUrl:"https://x.com/en/privacy",idLabel:"Pixel ID",idPattern:"^o[a-z0-9]{4,6}$",idExample:"o1a2b3",scriptOrigin:"https://static.ads-twitter.com",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!0,multiInstance:!0},linkedin:{title:"LinkedIn Insight Tag",vendor:"LinkedIn Ireland Unlimited Company",privacyUrl:"https://www.linkedin.com/legal/privacy-policy",idLabel:"Partner ID",idPattern:"^[0-9]{6,9}$",idExample:"1234567",scriptOrigin:"https://snap.licdn.com",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!0,multiInstance:!0},tiktok:{title:"TikTok Pixel",vendor:"TikTok Information Technologies UK Limited",privacyUrl:"https://www.tiktok.com/legal/privacy-policy",idLabel:"Pixel ID",idPattern:"^[A-Z0-9]{20}$",idExample:"C4A1B2C3D4E5F6G7H8I9",scriptOrigin:"https://analytics.tiktok.com",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!1,multiInstance:!0},reddit:{title:"Reddit Pixel",vendor:"Reddit, Inc.",privacyUrl:"https://www.reddit.com/policies/privacy-policy",idLabel:"Advertiser ID",idPattern:"^t2_[a-z0-9]{4,12}$",idExample:"t2_abc123",scriptOrigin:"https://www.redditstatic.com",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!1,multiInstance:!0},bing_uet:{title:"Microsoft Advertising (UET)",vendor:"Microsoft Corporation",privacyUrl:"https://privacy.microsoft.com/en-us/privacystatement",idLabel:"Tag ID",idPattern:"^[0-9]{7,9}$",idExample:"12345678",scriptOrigin:"https://bat.bing.com",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!1,multiInstance:!0},clarity:{title:"Microsoft Clarity",vendor:"Microsoft Corporation",privacyUrl:"https://privacy.microsoft.com/en-us/privacystatement",idLabel:"Project ID",idPattern:"^[a-z0-9]{10}$",idExample:"ab12cd34ef",scriptOrigin:"https://www.clarity.ms",defaultConsentCategory:"analytics",supportsConsentMode:!1,needsConversionIds:!1},hotjar:{title:"Hotjar",vendor:"Hotjar Limited",privacyUrl:"https://www.hotjar.com/legal/policies/privacy/",idLabel:"Site ID",idPattern:"^[0-9]{6,9}$",idExample:"1234567",scriptOrigin:"https://static.hotjar.com",defaultConsentCategory:"analytics",supportsConsentMode:!1,needsConversionIds:!1},posthog:{title:"PostHog",vendor:"PostHog, Inc.",privacyUrl:"https://posthog.com/privacy",idLabel:"Project API key",idPattern:"^phc_[A-Za-z0-9]{32,48}$",idExample:"phc_abcdefghijklmnopqrstuvwxyz012345",scriptOrigin:"https://us-assets.i.posthog.com",defaultConsentCategory:"analytics",supportsConsentMode:!1,needsConversionIds:!1,hosts:["us.i.posthog.com","eu.i.posthog.com"]},plausible:{title:"Plausible Analytics",vendor:"Plausible Insights OÜ",privacyUrl:"https://plausible.io/privacy",idLabel:"Domain",idPattern:"^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$",idExample:"example.com",scriptOrigin:"https://plausible.io",defaultConsentCategory:"analytics",supportsConsentMode:!1,needsConversionIds:!1},ahrefs:{title:"Ahrefs Analytics",vendor:"Ahrefs Pte. Ltd.",privacyUrl:"https://ahrefs.com/privacy",idLabel:"Analytics key",idPattern:"^[A-Za-z0-9+/=]{20,64}$",idExample:"AbCdEfGhIjKlMnOpQrStUv==",scriptOrigin:"https://analytics.ahrefs.com",defaultConsentCategory:"analytics",supportsConsentMode:!1,needsConversionIds:!1}},Y=Object.keys(Q);function ee(e){return"string"==typeof e&&Object.prototype.hasOwnProperty.call(Q,e)}function te(e,t){return!!ee(e)&&("string"==typeof t&&0!==t.length&&new RegExp(Q[e].idPattern).test(t))}const ne=/^[a-z][a-z0-9-]{0,40}$/,re=/^[\w.:/@+=-]{1,200}$/;function ie(e){return function(e){if("string"!=typeof e)return!1;if(0===e.length||e.length>300)return!1;let t;try{t=new URL(e)}catch{return!1}return!("https:"!==t.protocol||!t.hostname||!t.hostname.includes(".")||e.includes("?")||e.includes("#")||t.username||t.password)}(e.src)&&function(e){if(null==e)return!0;if("object"!=typeof e||Array.isArray(e))return!1;const t=Object.entries(e);return!(t.length>12)&&t.every(([e,t])=>ne.test(e)&&"string"==typeof t&&re.test(t))}(e.dataAttributes)}const oe=Array.from(new Set(Y.map(e=>Q[e].scriptOrigin))).sort(),ae={sign_up:{ga4:"sign_up",meta:"CompleteRegistration",tiktok:"CompleteRegistration",reddit:"SignUp"},login:{ga4:"login",meta:null,tiktok:null,reddit:null},trial_started:{ga4:"begin_checkout",meta:"StartTrial",tiktok:"StartTrial",reddit:"Lead"},checkout_started:{ga4:"begin_checkout",meta:"InitiateCheckout",tiktok:"InitiateCheckout",reddit:"AddToCart"},purchase:{ga4:"purchase",meta:"Purchase",tiktok:"CompletePayment",reddit:"Purchase"},subscription_created:{ga4:"purchase",meta:"Subscribe",tiktok:"Subscribe",reddit:"Purchase"},subscription_upgraded:{ga4:"subscription_upgraded",meta:null,tiktok:null,reddit:null},lead:{ga4:"generate_lead",meta:"Lead",tiktok:"SubmitForm",reddit:"Lead"},workspace_created:{ga4:"workspace_created",meta:null,tiktok:null,reddit:null}},se=Object.keys(ae);function ce(e){return se.includes(e)}function de(){return"undefined"==typeof window?null:window}const le={gtm:"dataLayer",ga4:"gtag",google_ads:"gtag",meta_pixel:"fbq",x_pixel:"twq",linkedin:"lintrk",tiktok:"ttq",reddit:"rdt",bing_uet:"uetq",clarity:"clarity",hotjar:"hj",posthog:"posthog",plausible:"plausible",ahrefs:"__ahrefs_loaded"};function ue(){return"undefined"==typeof window?null:window}function pe(e,t={}){const n=ue();if(!n)return null;const r=n.document.createElement("script");r.async=!0,r.src=e;for(const[e,n]of Object.entries(t))r.setAttribute(e,n);return n.document.head.appendChild(r),r}function ge(e){const t=ue();if(!t)return;const n=t.document.createElement("script");n.text=e,t.document.head.appendChild(n)}function fe(e){const t=ue();t&&(Array.isArray(t[e])||(t[e]=[]),"function"!=typeof t.gtag&&(t.gtag=function(){t[e].push(arguments)}))}const me=new Set;function he(e){for(const t of me)if(t.slice(0,t.indexOf(":"))===e)return!0;return!1}function ye(e,t){const n=ue();if(!n)return!1;if("gtm"===e||"ga4"===e||"google_ads"===e){const e=n.google_tag_manager;return!(!e||"object"!=typeof e)&&Object.prototype.hasOwnProperty.call(e,t)}const r=le[e];if(!r)return!1;if(void 0===n[r])return!1;if(me.has(`${e}:${t}`))return!0;return!Q[e].multiInstance||!he(e)}const we={meta_pixel:e=>`fbq('init','${e}');fbq('track','PageView');`,x_pixel:e=>`twq('config','${e}');`,tiktok:e=>`ttq.load('${e}');ttq.page();`,reddit:e=>`rdt('init','${e}');rdt('track','PageVisit');`,bing_uet:e=>`window.uetq=window.uetq||[];window.uetq.push({ti:'${e}',enableAutoSpaTracking:false});`,linkedin:e=>`window._linkedin_data_partner_ids=window._linkedin_data_partner_ids||[];window._linkedin_data_partner_ids.push('${e}');`};function ve(e,t,n){const r=function(e,t,n){const r=ue();if(!r)return!1;if("external"===e.provider){if(!e.src)return!1;const t={};for(const[n,r]of Object.entries(e.dataAttributes??{}))t[`data-${n}`]=r;return pe(e.src,t),!0}const i=e.provider,o=Q[i];if(!o)return!1;const a=e.providerId;if(!a)return!1;const s=we[i];if(s&&he(i))return ge(s(a)),!0;switch(i){case"gtm":{fe(t),r[t].push({"gtm.start":Date.now(),event:"gtm.js"});const e="dataLayer"===t?"":`&l=${t}`;return pe(`${o.scriptOrigin}/gtm.js?id=${a}${e}`),!0}case"ga4":case"google_ads":{fe(t),pe(`${o.scriptOrigin}/gtag/js?id=${a}`);const e=r.gtag;e("js",new Date);const s="ga4"===i&&n?.gaClientId?{client_id:n.gaClientId}:void 0;return s?e("config",a,s):e("config",a),!0}case"meta_pixel":return ge(`!function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,document,'script','${o.scriptOrigin}/en_US/fbevents.js');fbq('init','${a}');fbq('track','PageView');`),!0;case"x_pixel":return ge(`!function(e,t,n,s,u,a){e.twq||(s=e.twq=function(){s.exe?s.exe.apply(s,arguments):s.queue.push(arguments)},s.version='1.1',s.queue=[],u=t.createElement(n),u.async=!0,u.src='${o.scriptOrigin}/uwt.js',a=t.getElementsByTagName(n)[0],a.parentNode.insertBefore(u,a))}(window,document,'script');twq('config','${a}');`),!0;case"linkedin":return ge(`window._linkedin_partner_id='${a}';window._linkedin_data_partner_ids=window._linkedin_data_partner_ids||[];window._linkedin_data_partner_ids.push('${a}');window.lintrk=window.lintrk||function(a,b){(window.lintrk.q=window.lintrk.q||[]).push([a,b])};window.lintrk.q=window.lintrk.q||[];`),pe(`${o.scriptOrigin}/li.lms-analytics/insight.min.js`),!0;case"tiktok":return ge(`!function(w,d,t){w.TiktokAnalyticsObject=t;var ttq=w[t]=w[t]||[];ttq.methods=['page','track','identify','instances','debug','on','off','once','ready','alias','group','enableCookie','disableCookie'];ttq.setAndDefer=function(t,e){t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}};for(var i=0;i<ttq.methods.length;i++)ttq.setAndDefer(ttq,ttq.methods[i]);ttq.load=function(e,n){var r='${o.scriptOrigin}/i18n/pixel/events.js';ttq._i=ttq._i||{};ttq._i[e]=[];ttq._i[e]._u=r;ttq._t=ttq._t||{};ttq._t[e]=+new Date;ttq._o=ttq._o||{};ttq._o[e]=n||{};var o=d.createElement('script');o.type='text/javascript';o.async=!0;o.src=r+'?sdkid='+e+'&lib='+t;var a=d.getElementsByTagName('script')[0];a.parentNode.insertBefore(o,a)};ttq.load('${a}');ttq.page()}(window,document,'ttq');`),!0;case"reddit":return ge(`!function(w,d){if(!w.rdt){var p=w.rdt=function(){p.sendEvent?p.sendEvent.apply(p,arguments):p.callQueue.push(arguments)};p.callQueue=[];var t=d.createElement('script');t.src='${o.scriptOrigin}/ads/pixel.js';t.async=!0;var s=d.getElementsByTagName('script')[0];s.parentNode.insertBefore(t,s)}}(window,document);rdt('init','${a}');rdt('track','PageVisit');`),!0;case"bing_uet":return ge(`(function(w,d,t,r,u){w[u]=w[u]||[];w[u].push({ti:'${a}',enableAutoSpaTracking:false});var o=d.createElement(t);o.src='${o.scriptOrigin}/bat.js';o.async=1;var i=d.getElementsByTagName(t)[0];i.parentNode.insertBefore(o,i)})(window,document,'script',0,'uetq');`),!0;case"clarity":return ge(`(function(c,l,a,r,i,t,y){c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)};t=l.createElement(r);t.async=1;t.src='${o.scriptOrigin}/tag/'+i;y=l.getElementsByTagName(r)[0];y.parentNode.insertBefore(t,y)})(window,document,'clarity','script','${a}');`),!0;case"hotjar":return ge(`(function(h,o,t,j,a,r){h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)};h._hjSettings={hjid:${a},hjsv:6};a=o.getElementsByTagName('head')[0];r=o.createElement('script');r.async=1;r.src='${o.scriptOrigin}/hotjar-'+h._hjSettings.hjid+'.js?sv='+h._hjSettings.hjsv;a.appendChild(r)})(window,document);`),!0;case"posthog":{const t=o.hosts,n=t?.includes(e.host??"")?e.host:t?.[0]??"us.i.posthog.com";return ge(`!function(t,e){var o,n,p,r;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split('.');2==o.length&&(t=t[o[0]],e=o[1]);t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement('script')).type='text/javascript',p.async=!0,p.src='${o.scriptOrigin}/static/array.js',(r=t.getElementsByTagName('script')[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a='posthog',u.people=u.people||[],u.toString=function(t){var e='posthog';return'posthog'!==a&&(e+='.'+a),t||(e+=' (stub)'),e},u.people.toString=function(){return u.toString(1)+'.people (stub)'},o='init capture register register_once identify alias people.set people.set_once set_config get_distinct_id getFeatureFlag isFeatureEnabled onFeatureFlags reloadFeatureFlags group reset'.split(' '),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);posthog.init('${a}',{api_host:'https://${n}'});`),!0}case"plausible":return ge("window.plausible=window.plausible||function(){(window.plausible.q=window.plausible.q||[]).push(arguments)};"),pe(`${o.scriptOrigin}/js/script.js`,{"data-domain":a,defer:"true"}),!0;case"ahrefs":return pe(`${o.scriptOrigin}/analytics.js`,{"data-key":a}),r.__ahrefs_loaded=!0,!0;default:return!1}}(e,t,n);return r&&"external"!==e.provider&&e.providerId&&me.add(`${e.provider}:${e.providerId}`),r}const _e=Symbol.for("@buildbase/sdk.tracking.context"),be=globalThis,ke=be[_e]??(be[_e]=t.createContext(null)),Ie={consent:{manifest:[],state:null,effective:null,default:null,country:null,set:()=>{}},track:()=>{},setUser:()=>{},setIdentity:()=>{},setConsentRecordHeaders:()=>{},setProperties:()=>{},getProperties:()=>({}),completeCheckout:async()=>{},installed:{},ready:!0,attribution:{}};function Ce(){return t.useContext(ke)??Ie}const Se=({serverUrl:n,orgId:r,clientId:o,enabled:a=!0,consent:s="auto",autoPageview:c=!0,events:d,onEvent:l,properties:u,enrich:p,identity:g,debug:f=!1,children:m})=>{const w=t.useRef(g);w.current=g;const[v,_]=t.useState(null),[b,k]=t.useState(!1),[I,C]=t.useState(!1),S="object"==typeof s?JSON.stringify(s):"",A=t.useMemo(()=>S?function(e){if(!e||"object"!=typeof e)return null;const t=e;if("granted"!==t.default&&"denied"!==t.default)return null;const n=e=>Array.isArray(e)?e.filter(e=>"string"==typeof e):void 0;return{default:t.default,regions:{...n(t.regions?.denied)?{denied:n(t.regions?.denied)}:{},...n(t.regions?.granted)?{granted:n(t.regions?.granted)}:{}}}}(JSON.parse(S)):null,[S]),E="string"==typeof s?s:"auto",P="granted"===E?{analytics:!0,marketing:!0}:"denied"===E?{analytics:!1,marketing:!1}:null,[O,U]=t.useState(P),R=t.useRef(null),D=t.useRef(l);D.current=l;const B=t.useRef(p);B.current=p;const V=t.useRef({});V.current=u??{};const G=t.useRef({}),z=t.useCallback(()=>({...V.current,...G.current}),[]),F=t.useCallback(e=>{const t={...G.current,...e};for(const[e,n]of Object.entries(t))void 0===n&&delete t[e];G.current=t},[]),[J,Z]=t.useState({}),W=t.useRef({}),[Y,ne]=t.useState(0),re=t.useRef(null),[oe,se]=t.useState(0),le=t.useRef({}),ue=t.useRef(null);ue.current=v;const pe=v?.dataLayerName??"dataLayer",ge=t.useCallback((...e)=>{f&&console.info("[buildbase:tracking]",...e)},[f]);t.useEffect(()=>{return e=()=>{0!==Object.keys(W.current).length&&window.dispatchEvent("function"==typeof PageTransitionEvent?new PageTransitionEvent("pagehide",{persisted:!1}):new Event("pagehide"))},i.add(e),()=>{i.delete(e)};var e},[]),t.useEffect(()=>{if(!(a&&n&&r&&o))return void k(!0);let e=!1;const t=`${n.replace(/\/$/,"")}/api/v1/public/${r}/tracking?clientId=${encodeURIComponent(o)}`;return fetch(t).then(e=>e.ok?e.json():null).then(t=>{if(e||!t)return;const n=t.data??t;n&&Array.isArray(n.scripts)&&_(n)}).catch(()=>{ge("config fetch failed; nothing installed")}).finally(()=>{e||k(!0)}),()=>{e=!0}},[a,n,r,o,ge]),t.useEffect(()=>{a&&Z(h())},[a]);const me="auto"===E?A??v?.consent?.defaults??null:null,he=t.useMemo(()=>v?"auto"!==E?E:A?T(A,v.country,v.region):v.consent?.defaults?v.resolvedConsentDefault??T(v.consent.defaults,v.country,v.region):"denied":null,[v,E,A]),we=O??("granted"===he?{analytics:!0,marketing:!0}:null),_e=!!v?.enhancedConversions&&!!we?.marketing,be=!!v?.scripts?.some(e=>"ga4"===e.provider||"google_ads"===e.provider||"gtm"===e.provider),Ie=me?JSON.stringify(me):"";t.useEffect(()=>{a&&v?.enabled&&(fe(pe),function(e,t,n={}){const r=L();if(!r)return;Array.isArray(r[e])||(r[e]=[]),"function"!=typeof r.gtag&&(r.gtag=function(){r[e].push(arguments)});const i=r.gtag,o="auto"===t?n.regional:null;let a="granted"===t?"granted":"denied";if(o){const e=q(o.regions?.denied),t=q(o.regions?.granted).filter(t=>!e.includes(t));e.length&&i("consent","default",{...M("denied"),region:e,wait_for_update:500}),t.length&&i("consent","default",{...M("granted"),region:t}),a=o.default}i("consent","default",{...M(a),..."denied"===a?{wait_for_update:500}:{}}),n.google&&(i("set","url_passthrough",!0),i("set","ads_data_redaction","granted"!==(n.resolved??a)))}(pe,E,{regional:Ie?JSON.parse(Ie):null,resolved:he,google:be}),R.current&&N(R.current))},[a,v?.enabled,pe,E,Ie,be]);const Ce=t.useMemo(()=>v?.enabled?v.scripts.filter(e=>{const t=ee(e.provider)&&Q[e.provider].supportsConsentMode;return function(e,t,n,r){return"denied"!==r&&("granted"===r||!!t||!!n&&("marketing"===e?n.marketing:n.analytics))}(e.consentCategory,t,we,E)}):[],[v,O,he,E]),[Se,$e]=t.useState(()=>"undefined"==typeof window||!y(window.location.search));t.useEffect(()=>{if(Se)return;const e=setInterval(()=>{y(window.location.search)||$e(!0)},50),t=setTimeout(()=>$e(!0),5e3);return()=>{clearInterval(e),clearTimeout(t)}},[Se]),t.useEffect(()=>{if(!Se)return;if(!a||!v?.enabled)return void(b&&C(!0));let e=0;for(const t of Ce)if(!W.current[t.key]){if("external"===t.provider){if(!ie({src:t.src,dataAttributes:t.dataAttributes})){ge("rejected external script",t.key);continue}}else{if(!ee(t.provider)){ge("rejected unknown provider",t.provider);continue}if(!te(t.provider,t.providerId)){ge("rejected id for",t.provider);continue}if(ye(t.provider,t.providerId??"")){ge(`${t.provider} ${t.providerId} is already on the page; skipping. Configure each tag in exactly one place.`);continue}}ve(t,pe,w.current)&&(W.current[t.key]=t.providerId??t.src??"",e+=1,ge("installed",t.key))}e&&ne(e=>e+1);const t=window;t.__buildbase=t.__buildbase??{},t.__buildbase.tracking={installed:{...W.current},dataLayerName:pe,clientId:o};const n=Object.keys(W.current).length>0,r=null!==we||0===v.scripts.length;(n||r)&&C(!0)},[a,v,Ce,b,O,he,pe,ge,Se,o]),t.useEffect(()=>{if(!a||!c||!v?.enabled)return;if("undefined"==typeof window)return;if(!Se)return;let e=null;const t=()=>{e&&clearTimeout(e),e=setTimeout(()=>function(e,t){const n=de();if(!n)return;const r=n[t];Array.isArray(r)&&r.push({event:"page_view",page_path:n.location.pathname,page_location:n.location.href,page_title:n.document.title});for(const t of e)switch(t.provider){case"ga4":n.gtag?.("event","page_view",{send_to:t.providerId,page_path:n.location.pathname,page_location:n.location.href,page_title:n.document.title});break;case"meta_pixel":n.fbq?.("track","PageView");break;case"tiktok":{const e=n.ttq;e?.page?.();break}case"reddit":n.rdt?.("track","PageVisit")}}(Ce,pe),50)},n=window.history,r=n.pushState,i=n.replaceState;return n.pushState=function(...e){const n=r.apply(this,e);return t(),n},n.replaceState=function(...e){const n=i.apply(this,e);return t(),n},window.addEventListener("popstate",t),()=>{n.pushState=r,n.replaceState=i,window.removeEventListener("popstate",t),e&&clearTimeout(e)}},[a,c,v?.enabled,Ce,pe,Se]),t.useEffect(()=>{if(!a)return;const e=function(e,t){const n=e?.mode??"auto",r=e?.overrides??{};if(("manual"===n||Object.values(r).some(e=>"manual"===e))&&!t)return'[buildbase:tracking] events are set to "manual" but no onEvent handler was provided, so those events would never fire anywhere. Pass onEvent, or use mode "auto".';for(const e of Object.keys(r))if(!ce(e))return`[buildbase:tracking] unknown event "${e}" in events.overrides. Overrides only apply to the events the SDK fires itself.`;return null}(d,!!l);if(e)throw new Error(e)},[a,d,l]);const xe=t.useCallback((e,t={},n)=>{if(!a)return;const r=n?.eventId||function(){const e=globalThis.crypto;return e?.randomUUID?e.randomUUID():`${Date.now().toString(16)}-${Math.random().toString(16).slice(2,10)}`}(),i=d?.mode??"auto",o=(ce(e)?d?.overrides?.[e]:void 0)??i,s={...V.current,...G.current,...J,...t},c=B.current?.({name:e,params:s})??{},l={...s,...c},u=D.current?.({name:e,params:l,eventId:r,handledBy:o});"manual"!==o&&!0!==u?(_e&&re.current&&X(Ce,re.current),function(e,t,n,r,i){const o=de();if(!o)return;const a=o[i];Array.isArray(a)&&a.push({event:e,...t,event_id:n});const s=ce(e)?ae[e]:{ga4:e,meta:null,tiktok:null,reddit:null};for(const i of r){const r=i.provider,a=Q[r];if(a){if(a.needsConversionIds){const a=i.conversionIds?.[e];if(!a)continue;"google_ads"===r?o.gtag?.("event","conversion",{send_to:`${i.providerId}/${a}`,transaction_id:n,...t}):"x_pixel"===r?o.twq?.("event",a,{...t,conversion_id:n}):"linkedin"===r&&o.lintrk?.("track",{conversion_id:a});continue}switch(r){case"ga4":s.ga4&&o.gtag?.("event",s.ga4,{...t,send_to:i.providerId,event_id:n});break;case"meta_pixel":s.meta&&o.fbq?.("track",s.meta,t,{eventID:n});break;case"tiktok":if(s.tiktok){const e=o.ttq;e?.track?.(s.tiktok,{...t,event_id:n})}break;case"reddit":s.reddit&&o.rdt?.("track",s.reddit,{...t,conversionId:n});break;case"bing_uet":{const r=o.uetq;r?.push?.("event",s.ga4??e,{...t,event_id:n});break}case"clarity":o.clarity?.("event",e);break;case"hotjar":{const t=o.hj;t?.("event",e);break}case"posthog":{const r=o.posthog;r?.capture?.(e,{...t,event_id:n});break}case"plausible":o.plausible?.(e,{props:t})}}}}(e,l,r,Ce,pe),ge("event fired:",e,r)):ge("event handled by app:",e)},[a,d,Ce,pe,J,ge,_e]),Ae=t.useCallback(async(e,t={})=>{const i=function(e){return{name:"trial_started"===e.kind?"trial_started":"purchase",params:{...e.workspaceId?{workspace_id:e.workspaceId}:{},...e.planVersionId?{plan_version_id:e.planVersionId}:{},...e.creditPackageId?{credit_package_id:e.creditPackageId}:{},...e.billingInterval?{billing_interval:e.billingInterval}:{},...e.currency?{currency:e.currency.toUpperCase()}:{},..."number"==typeof e.value?{value:e.value}:{},...e.sessionId?{transaction_id:e.sessionId}:{}}}}(e);let o=i.params;if(e.sessionId&&n&&r){const t=await async function(e,t){try{const n=e.serverUrl.replace(/\/$/,""),r=await fetch(`${n}/api/v1/public/${encodeURIComponent(e.orgId)}/checkout/${encodeURIComponent(t)}`,{credentials:"omit",..."undefined"!=typeof AbortSignal&&AbortSignal.timeout?{signal:AbortSignal.timeout(2e3)}:{}});if(!r.ok)return null;const i=await r.json(),o=i?.data??i;return"number"!=typeof o?.amount?null:{value:j(o.amount,o.currency),currency:"string"==typeof o.currency?o.currency:void 0,...Array.isArray(o.items)&&o.items.length?{items:o.items}:{}}}catch{return null}}({serverUrl:n,orgId:r},e.sessionId);t&&"number"==typeof t.value&&(o={...o,value:t.value,...t.currency?{currency:t.currency.toUpperCase()}:{},...t.items?.length?{items:t.items}:{}})}if(xe(i.name,{...o,...t},{eventId:e.eventId}),"purchase"===i.name&&e.sessionId&&n&&r){const t=(v?.scripts??[]).find(e=>"ga4"===e.provider&&e.providerId);t&&ye("ga4",t.providerId??"")&&function(e,t,n){try{const r=e.serverUrl.replace(/\/$/,"");fetch(`${r}/api/v1/public/${encodeURIComponent(e.orgId)}/checkout/${encodeURIComponent(t)}/reported`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:n}),keepalive:!0,credentials:"omit"}).catch(()=>{})}catch{}}({serverUrl:n,orgId:r},e.sessionId,"ga4")}},[n,r,xe,v]),[Ee]=t.useState(()=>"undefined"==typeof window?"":window.location.search);t.useEffect(()=>{if(!a||!I)return;if("undefined"==typeof window)return;const e=$(window.location.search);if(e)return void Ae(e);const t=x(Ee);t&&xe("checkout_abandoned",{...t.workspaceId?{workspace_id:t.workspaceId}:{},...t.planVersionId?{plan_version_id:t.planVersionId}:{},...t.creditPackageId?{credit_package_id:t.creditPackageId}:{},...t.billingInterval?{billing_interval:t.billingInterval}:{},...t.currency?{currency:t.currency.toUpperCase()}:{},..."number"==typeof t.value?{value:t.value}:{},seconds_at_checkout:Math.max(0,Math.round((Date.now()-t.startedAt)/1e3))})},[a,I,Ae,Ee,xe]);const je=t.useCallback((e,t)=>{R.current=e,U(e),N(e),a&&H({serverUrl:n,orgId:r,clientId:o,state:e,manifestVersion:ue.current?.consent?.manifestVersion,source:t?.source,consentString:t?.consentString,headers:le.current})},[a,n,r,o]),Pe=t.useCallback(e=>{le.current={...e}},[]),Oe=t.useCallback(e=>{if(!e)return re.current=null,void se(e=>e+1);K(e).then(e=>{re.current=e.emailHash||e.phoneHash?e:null,se(e=>e+1)})},[]),qe=t.useCallback((e,t)=>{const n=function(e){if(!e)return{traits:e,identity:null};const{email:t,phone:n,...r}=e,i={};return"string"==typeof t&&t&&(i.email=t),"string"==typeof n&&n&&(i.phone=n),{traits:r,identity:i.email||i.phone?i:null}}(t);n.identity&&Oe(n.identity),function(e,t,n){const r=de();if(!r)return;const i=!!n&&Object.keys(n).length>0;for(const o of t)switch(o.provider){case"ga4":case"google_ads":r.gtag?.("set",{user_id:e}),i&&r.gtag?.("set",{user_properties:n});break;case"meta_pixel":o.providerId&&r.fbq?.("init",o.providerId,{external_id:e});break;case"posthog":r.posthog?.identify?.(e,i?n:void 0);break;case"clarity":if(r.clarity?.("identify",e),i)for(const[e,t]of Object.entries(n))r.clarity?.("set",e,String(t));break;case"hotjar":r.hj?.("identify",e,{});break;case"tiktok":{const t=r.ttq;t?.identify?.({external_id:e});break}}}(e,Ce,n.traits)},[Ce,Oe]);t.useEffect(()=>{_e&&re.current&&0!==Object.keys(W.current).length&&X(Ce,re.current)},[_e,Ce,oe,Y]);const Ue=t.useMemo(()=>({consent:{manifest:v?.consent?.manifest??[],state:O,effective:we,default:he,country:v?.country??null,set:je},track:xe,setUser:qe,setIdentity:Oe,setConsentRecordHeaders:Pe,setProperties:F,getProperties:z,completeCheckout:Ae,installed:{...W.current},ready:I,attribution:J}),[v,O,he,je,xe,qe,Oe,Pe,F,z,Ae,I,Y,J]);return e.jsx(ke.Provider,{value:Ue,children:m})};Se.displayName="BuildBaseTracking";exports.ATTRIBUTION_PARAMS=a,exports.BuildBaseTracking=Se,exports.EEA_COUNTRIES=P,exports.EVENT_MAPPINGS=ae,exports.FUNNEL_EVENTS={sign_in_started:"The sign-in / sign-up button was pressed.",pricing_viewed:"A <PricingPage> finished loading its plans.",pricing_plan_selected:"A plan was chosen on a <PricingPage>.",workspace_switcher_opened:"The workspace switcher was opened.",workspace_settings_opened:"The workspace settings modal was opened.",workspace_settings_section_viewed:"A different section of the settings modal was opened.",plan_picker_opened:"The plan picker was shown.",billing_interval_changed:"Monthly / quarterly / yearly was switched in the plan picker.",plan_selected:"A plan was chosen in the plan picker.",plan_picker_dismissed:"The plan picker was closed without choosing a plan.",checkout_abandoned:"The customer came back from Stripe without paying.",billing_portal_opened:"Stripe’s billing portal was opened.",subscription_cancel_started:"The cancel-subscription confirmation was opened.",subscription_cancelled:"A subscription was cancelled.",subscription_resumed:"A cancelled subscription was resumed.",feature_gate_shown:'A feature gate rendered its "not on your plan" side.',quota_limit_reached:"A quota gate rendered because a quota is used up.",quota_threshold_reached:"A usage-threshold gate rendered.",plan_gate_shown:'A plan gate rendered its "needs another plan" side.',subscription_notice_shown:"A billing notice (trial ending, payment failed…) was shown.",sdk_error:"An SDK operation failed (component, action and code only)."},exports.SAFE_REGIONAL_CONSENT={default:"granted",regions:{denied:["EEA","GB","CH"]}},exports.TAG_PROVIDERS=Q,exports.TAG_PROVIDER_IDS=Y,exports.TAG_SCRIPT_ORIGINS=oe,exports.captureAttribution=h,exports.expandRegions=q,exports.getAttribution=function(){const e=c();return e?p(e.document):{}},exports.hashIdentity=K,exports.isCanonicalEvent=ce,exports.isTagProviderId=ee,exports.isValidProviderId=te,exports.normalizeEmail=J,exports.normalizePhone=Z,exports.resolveConsentDefault=T,exports.useCheckoutCompleted=function(e={}){const{completeCheckout:n,ready:r}=Ce(),i=t.useRef(e);i.current=e;const o=t.useRef(!1);t.useEffect(()=>{if(!r)return;if(o.current)return;const e=$(window.location.search)??C();e&&(o.current=!0,n(e,i.current))},[r,n])},exports.useTracking=Ce;
|