var We=Object.defineProperty;var ze=(i,e,t)=>e in i?We(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var h=(i,e,t)=>ze(i,typeof e!="symbol"?e+"":e,t);var ae=Object.defineProperty,le=i=>i;function ce(i,e){this[i]=le.bind(null,e)}var ue=(i,e)=>{for(var t in e)ae(i,t,{get:e[t],enumerable:!0,configurable:!0,set:ce.bind(e,t)})},St=(i,e)=>()=>(i&&(e=i(i=0)),e),At=()=>{},Rt={};ue(Rt,{browserFingerprint:()=>W,generateKeyPair:()=>Et,sign:()=>xt,unwrapPublicKey:()=>ge,wrapPublicKey:()=>z});function de(i,e){let t=new Uint8Array(i.length+e.length);return t.set(i),t.set(e,i.length),t}function K(i){let e="";for(let t=0;t<i.length;t++)e+=String.fromCharCode(i[t]);return btoa(e)}function It(i){let e=atob(i),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}function he(i){return Array.from(i).map(e=>e.toString(16).padStart(2,"0")).join("")}function z(i){return de(Ct,i)}function ge(i){return i.slice(Ct.length)}async function Et(){let i=(void 0).randomSecretKey(),e=await(void 0)(i),t=z(e),n=await W(K(t));return{publicKeyBase64:K(t),privateKeyBase64:K(i),fingerprint:n}}async function xt(i,e){let t=It(e),n=new TextEncoder().encode(i),r=await(void 0)(n,t);return K(r)}async function W(i){let e=It(i),t=new ArrayBuffer(e.byteLength);new Uint8Array(t).set(e);let n=await crypto.subtle.digest("SHA-256",t);return he(new Uint8Array(n))}var Ct,qe,Q=St(()=>{At(),Ct=new Uint8Array([48,42,48,5,6,3,43,101,112,3,33,0]),qe=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32])}),U=1;function Pt(i){let e=i.lastIndexOf("/");return e>=0?i.slice(e+1):i}function J(i){let e="";for(let t=0;t<i.length;t++)e+=String.fromCharCode(i[t]);return btoa(e)}function fe(i){let e=atob(i),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}function pe(){var e;if(typeof window<"u"&&window.location)return`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/db`;let i=globalThis.process;return(e=i==null?void 0:i.env)!=null&&e.BODDB_URL?i.env.BODDB_URL.replace(/^http/,"ws"):"ws://localhost:4460"}function Ot(){try{return typeof localStorage<"u"?localStorage:null}catch{return null}}class Y{constructor(){h(this,"url",pe());h(this,"auth");h(this,"keyAuth");h(this,"autoAuth");h(this,"reconnect",!0);h(this,"reconnectInterval",1e3);h(this,"maxReconnectInterval",3e4);h(this,"requestTimeout",3e4);h(this,"onVersionMismatch");h(this,"offlineQueue",!1);h(this,"offlineQueueCap",100)}}class L{constructor(e){h(this,"options");h(this,"ws",null);h(this,"msgId",0);h(this,"pending",new Map);h(this,"valueCbs",new Map);h(this,"lastValue",new Map);h(this,"childCbs",new Map);h(this,"activeSubs",new Map);h(this,"_subErrorListeners",new Set);h(this,"_connGen",0);h(this,"streamCbs",new Map);h(this,"activeStreamSubs",new Set);h(this,"vfsDownloadCbs",new Map);h(this,"closed",!1);h(this,"_browserAuth",null);h(this,"reconnectTimer",null);h(this,"reconnectDelay");h(this,"connectPromise",null);h(this,"_sock",null);h(this,"_authToken",null);h(this,"_deviceFingerprint",null);h(this,"_welcomeListeners",new Set);h(this,"_pendingWelcome",null);h(this,"_authComplete",!1);h(this,"_offlineQueue",[]);h(this,"_rec",null);h(this,"_recCap",5e3);h(this,"serverInfo",null);h(this,"onOfflineQueue");h(this,"onOfflineFlush");h(this,"auth");h(this,"onStatusChange");h(this,"onConnect");h(this,"_memStorage",null);this.options={...new Y,...e},this.reconnectDelay=this.options.reconnectInterval,this.auth=new G(this);let t=Ot();if(t)try{let n=t.getItem("BOD_WS_RECORD");if(n){let r=Number(n);this._recCap=Number.isFinite(r)&&r>0?r:5e3,this._rec=[]}}catch{}}_recPush(e,t,n=!1){this._rec&&(this._rec.push(n?{t:Date.now(),dir:e,data:t,parseError:n}:{t:Date.now(),dir:e,data:t}),this._rec.length>this._recCap&&this._rec.splice(0,this._rec.length-this._recCap))}startRecording(e=5e3){var t;this._recCap=e,this._rec=(t=this._rec)!=null?t:[]}stopRecording(){var t;let e=(t=this._rec)!=null?t:[];return this._rec=null,e}getRecording(){var e;return(e=this._rec)!=null?e:[]}clearRecording(){this._rec&&(this._rec.length=0)}dumpRecording(e="array"){let t=this.getRecording();return e==="json"?JSON.stringify(t,null,2):t}onWelcome(e){return this._welcomeListeners.add(e),()=>{this._welcomeListeners.delete(e)}}get deviceFingerprint(){return this._deviceFingerprint}get authToken(){return this._authToken}async connect(){var e;if(((e=this.ws)==null?void 0:e.readyState)!==WebSocket.OPEN)return this.connectPromise?this.connectPromise:(this.closed=!1,this.connectPromise=new Promise((t,n)=>{let r=new WebSocket(this.options.url);this._sock=r;let l=()=>this._sock!==r;r.onopen=async()=>{var s,a;if(l()){r.close();return}this._recPush("open",{url:this.options.url}),this.ws=r,this.reconnectDelay=this.options.reconnectInterval,(s=this.onStatusChange)==null||s.call(this,!0);try{if(await((a=this.onConnect)==null?void 0:a.call(this)),this.options.autoAuth&&!this.options.keyAuth){let u=await this._ensureDeviceKeys();this.options.keyAuth={publicKey:u.publicKey,signFn:u.signFn},await this.send("auth-register-device",{publicKey:u.publicKey,displayName:typeof this.options.autoAuth=="object"?this.options.autoAuth.displayName:void 0})}if(this.options.keyAuth){if(this._authToken)try{await this.send("auth",{token:this._authToken})}catch{this._authToken=null}if(!this._authToken){let u=await this.send("auth-challenge",{}),d=await this.options.keyAuth.signFn(u.nonce),f=await this.send("auth-verify",{publicKey:this.options.keyAuth.publicKey,signature:d,nonce:u.nonce});this._authToken=f.token}}else if(this.options.auth){let u=await this.options.auth();u&&await this.send("auth",{token:u})}if(this._authComplete=!0,this._pendingWelcome){this.serverInfo=this._pendingWelcome;for(let u of this._welcomeListeners)u(this.serverInfo);this._pendingWelcome=null}if(this._connGen++,this.activeSubs.size>0)try{await this.send("batch-sub",{subscriptions:[...this.activeSubs.values()]})}catch{for(let[u,d]of this.activeSubs)this._subscribe(u,d)}for(let u of this.activeStreamSubs){let[d,f]=this.splitStreamKey(u);await this.send("stream-sub",{path:d,groupId:f})}await this._flushOfflineQueue(),this.connectPromise=null,t()}catch(u){this.connectPromise=null,n(u)}},r.onmessage=s=>{var d,f;if(l())return;let a;try{a=JSON.parse(typeof s.data=="string"?s.data:s.data.toString()),this._recPush("recv",a)}catch(p){throw this._recPush("recv",s.data,!0),p}if(a.type==="welcome"){let p={protocolVersion:a.protocolVersion,serverVersion:a.serverVersion};if(this._authComplete){this.serverInfo=p;for(let $ of this._welcomeListeners)$(this.serverInfo)}else this._pendingWelcome=p;a.protocolVersion!==U&&(console.warn(`[BodClient] Protocol mismatch: client=${U} server=${a.protocolVersion} (v${a.serverVersion})`),(f=(d=this.options).onVersionMismatch)==null||f.call(d,{clientProtocol:U,serverProtocol:a.protocolVersion,serverVersion:a.serverVersion}));return}if(a.type==="value"){let p=new F(a.path,a.data,a.updatedAt);for(let $ of[a.path,`${a.path}\0shallow`]){let je=this.valueCbs.get($);if(je){this.lastValue.set($,p);for(let Ne of[...je])Ne(p)}}return}if(a.type==="stream"){let p=`${a.path}:${a.groupId}`,$=this.streamCbs.get(p);if($)for(let je of $)je(a.events);return}if(a.type==="child"){let p={type:a.event,key:a.key,path:a.path+"/"+a.key,val:()=>a.data},$=this.childCbs.get(a.path);if($)for(let Ne of $)Ne(p);let je=this.childCbs.get(`${a.path}\0shallow`);if(je)for(let Ne of je)Ne(p);return}if(a.type==="vfs-download-chunk"){let p=this.vfsDownloadCbs.get(a.transferId);if(p)for(let $ of p)$(a);return}let u=this.pending.get(a.id);u&&(this.pending.delete(a.id),a.ok?u.resolve(a):u.reject(Object.assign(Error(a.error||"Unknown error"),{code:a.code,retryAfterSec:a.retryAfterSec})))},r.onclose=s=>{var a;if(l()){n(Error("Client disconnected"));return}this._sock=null,this._recPush("close",{code:s==null?void 0:s.code,reason:s==null?void 0:s.reason}),this.ws=null,this.serverInfo=null,this._pendingWelcome=null,this._authComplete=!1,(a=this.onStatusChange)==null||a.call(this,!1);for(let[,u]of this.pending)u.reject(Error("Connection closed"));this.pending.clear(),!this.closed&&this.options.reconnect&&this.scheduleReconnect(),this.connectPromise&&(this.connectPromise=null,n(Error(`WebSocket connection failed (${this.options.url})`)))},r.onerror=()=>{this._recPush("error","ws error")}}),this.connectPromise)}disconnect(){var t;this.closed=!0,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null);let e=(t=this._sock)!=null?t:this.ws;this._sock=null,this.ws=null,this.connectPromise=null,e==null||e.close();for(let[,n]of this.pending)n.reject(Error("Client disconnected"));this.pending.clear();for(let n of this._offlineQueue)n.reject(Error("Client disconnected"));this._offlineQueue=[]}scheduleReconnect(){this.closed||(this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connect().catch(()=>{this.reconnectDelay=Math.min(this.reconnectDelay*2,this.options.maxReconnectInterval)})},this.reconnectDelay))}_enqueueWrite(e,t){return new Promise((n,r)=>{var s;let l=this._writeDedupKey(e,t);if(l){let a=this._offlineQueue.findIndex(u=>u.dedupKey===l);a!==-1&&(this._offlineQueue[a].resolve({ok:!0,data:null}),this._offlineQueue.splice(a,1))}this._offlineQueue.length>=this.options.offlineQueueCap&&this._offlineQueue.shift().reject(Error("Offline queue full \u2014 dropped")),this._offlineQueue.push({op:e,params:t,resolve:n,reject:r,dedupKey:l}),(s=this.onOfflineQueue)==null||s.call(this,this._offlineQueue.length)})}_writeDedupKey(e,t){if(e==="push"||e==="batch"||e==="update"&&t.updates)return null;let n=t.path;return n?`${e}:${n}`:null}async _flushOfflineQueue(){var t;if(this._offlineQueue.length===0)return;let e=this._offlineQueue.splice(0);(t=this.onOfflineFlush)==null||t.call(this,e.length);for(let n of e)try{let r=await this.sendRaw(n.op,n.params);n.resolve(r)}catch(r){n.reject(r instanceof Error?r:Error(String(r)))}}nextId(){return String(++this.msgId)}async sendRaw(e,t={},n=!1){if(n&&this.options.offlineQueue&&(!this.ws||this.ws.readyState!==WebSocket.OPEN)&&!this.closed)return this._enqueueWrite(e,t);if(this.closed)throw Error("Client disconnected");return(!this.ws||this.ws.readyState!==WebSocket.OPEN)&&await this.connect(),new Promise((r,l)=>{if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return l(Error("Not connected"));let s=this.nextId(),a=null,u=()=>{a&&(clearTimeout(a),a=null)};this.pending.set(s,{resolve:d=>{u(),r(d)},reject:d=>{u(),l(d)}}),this.options.requestTimeout>0&&(a=setTimeout(()=>{this.pending.delete(s),l(Error(`Request timeout after ${this.options.requestTimeout}ms (op=${e}${t.path?` path=${String(t.path)}`:""})`))},this.options.requestTimeout)),this._recPush("send",{id:s,op:e,...t}),this.ws.send(JSON.stringify({id:s,op:e,...t}))})}async send(e,t={},n=!1){var r;return(r=(await this.sendRaw(e,t,n)).data)!=null?r:null}async get(e){return this.send("get",{path:e})}async getSnapshot(e){var n;let t=await this.sendRaw("get",{path:e});return new F(e,(n=t.data)!=null?n:null,t.updatedAt)}async getShallow(e,t,n,r){return this.send("get",{path:e!=null?e:"",shallow:!0,...t!==void 0?{limit:t}:{},...n!==void 0?{offset:n}:{},...(r==null?void 0:r.values)===!1?{values:!1}:{},...(r==null?void 0:r.counts)===!1?{counts:!1}:{}})}async stats(e){return this.send("stats",{path:e})}async statsChildren(e){return this.send("stats-children",{path:e})}async set(e,t,n){await this.send("set",{path:e,value:t,...n!=null&&n.ttl?{ttl:n.ttl}:{},...(n==null?void 0:n.flatten)!==void 0?{flatten:n.flatten}:{}},!0)}async update(e,t,n){await this.send("update",{path:e,value:t,...n!=null&&n.ttl?{ttl:n.ttl}:{},...(n==null?void 0:n.flatten)!==void 0?{flatten:n.flatten}:{}},!0)}async updateMulti(e){await this.send("update",{updates:e},!0)}async delete(e){await this.send("delete",{path:e},!0)}async increment(e,t=1){return Number(await this.send("transform",{path:e,type:"increment",value:t}))}async batch(e){return this.send("batch",{operations:e},!0)}async push(e,t,n){return this.send("push",{path:e,value:t,idempotencyKey:n==null?void 0:n.idempotencyKey,ttl:n==null?void 0:n.ttl},!0)}query(e){return new X(this,e)}_query(e,t,n,r,l){return this.send("query",{path:e,filters:t,order:n,limit:r,offset:l})}onSubscribeError(e){return this._subErrorListeners.add(e),()=>{this._subErrorListeners.delete(e)}}_subscribe(e,t,n=0){let r=this._connGen;this.send("sub",t).catch(l=>{var d,f;if(this.activeSubs.get(e)!==t||this.closed)return;let s=l.code==="RATE_LIMITED",a=s?Math.min(3e4,Math.max(250,((d=l.retryAfterSec)!=null?d:1)*1e3)*2**Math.min(n,4)+Math.random()*250):void 0,u={path:String(t.path),event:String(t.event),code:l.code,message:l.message,retryInMs:a};if(this._subErrorListeners.size)for(let p of this._subErrorListeners)p(u);else console.warn(`[BodClient] subscribe ${u.event} ${u.path} refused: ${(f=u.code)!=null?f:u.message}${s?` - retrying in ${Math.round(a)} ms`:""}`);s&&setTimeout(()=>{var p;this.activeSubs.get(e)!==t||r!==this._connGen||((p=this.ws)==null?void 0:p.readyState)!==WebSocket.OPEN||this._subscribe(e,t,n+1)},a)})}on(e,t,n){var u,d;let r=!((u=n==null?void 0:n.deep)!=null&&u),l=`value${r?"-shallow":""}:${e}`,s=r?`${e}\0shallow`:e;this.valueCbs.has(s)||this.valueCbs.set(s,new Set),this.valueCbs.get(s).add(t);let a=this.lastValue.get(s);if(a&&queueMicrotask(()=>{var f;this.lastValue.get(s)===a&&((f=this.valueCbs.get(s))!=null&&f.has(t))&&t(a)}),!this.activeSubs.has(l)){let f={path:e,event:"value",...r?{shallow:!0}:{}};this.activeSubs.set(l,f),((d=this.ws)==null?void 0:d.readyState)===WebSocket.OPEN&&this._subscribe(l,f)}return()=>{var f,p,$;(f=this.valueCbs.get(s))==null||f.delete(t),((p=this.valueCbs.get(s))==null?void 0:p.size)===0&&(this.valueCbs.delete(s),this.lastValue.delete(s),this.activeSubs.delete(l),(($=this.ws)==null?void 0:$.readyState)===WebSocket.OPEN&&this.send("unsub",{path:e,event:"value",...r?{shallow:!0}:{}}).catch(()=>{}))}}onChild(e,t,n){var u,d;let r=!((u=n==null?void 0:n.deep)!=null&&u),l=(n==null?void 0:n.values)===!1,s=`child${r?"-shallow":""}${l?"-novalues":""}:${e}`,a=r?`${e}\0shallow`:e;if(this.childCbs.has(a)||this.childCbs.set(a,new Set),this.childCbs.get(a).add(t),!this.activeSubs.has(s)){let f={path:e,event:"child",...r?{shallow:!0}:{},...l?{values:!1}:{}};this.activeSubs.set(s,f),((d=this.ws)==null?void 0:d.readyState)===WebSocket.OPEN&&this._subscribe(s,f)}return()=>{var f,p,$;(f=this.childCbs.get(a))==null||f.delete(t),((p=this.childCbs.get(a))==null?void 0:p.size)===0&&(this.childCbs.delete(a),this.activeSubs.delete(s),(($=this.ws)==null?void 0:$.readyState)===WebSocket.OPEN&&this.send("unsub",{path:e,event:"child",...r?{shallow:!0}:{},...l?{values:!1}:{}}).catch(()=>{}))}}mq(e){return new tt(this,e)}_mqSend(e,t){return this.send(e,t)}stream(e,t){return new H(this,e,t)}_streamOn(e,t,n){var l;let r=`${e}:${t}`;return this.streamCbs.has(r)||this.streamCbs.set(r,new Set),this.streamCbs.get(r).add(n),!this.activeStreamSubs.has(r)&&(this.activeStreamSubs.add(r),((l=this.ws)==null?void 0:l.readyState)===WebSocket.OPEN&&this.send("stream-sub",{path:e,groupId:t}).catch(()=>{})),()=>{var s,a,u;(s=this.streamCbs.get(r))==null||s.delete(n),((a=this.streamCbs.get(r))==null?void 0:a.size)===0&&(this.streamCbs.delete(r),this.activeStreamSubs.delete(r),((u=this.ws)==null?void 0:u.readyState)===WebSocket.OPEN&&this.send("stream-unsub",{path:e,groupId:t}).catch(()=>{}))}}_streamRead(e,t,n){return this.send("stream-read",{path:e,groupId:t,limit:n})}_streamAck(e,t,n){return this.send("stream-ack",{path:e,groupId:t,key:n})}splitStreamKey(e){let t=e.lastIndexOf(":");return[e.slice(0,t),e.slice(t+1)]}async search(e){return this.send("fts-search",e)}async index(e,t){let n={path:e};Array.isArray(t)?n.fields=t:n.content=t,await this.send("fts-index",n)}async vectorSearch(e){return this.send("vector-search",e)}async vectorStore(e,t){await this.send("vector-store",{path:e,embedding:t})}async streamSnapshot(e){return this.send("stream-snapshot",{path:e})}async streamMaterialize(e,t){return this.send("stream-materialize",{path:e,...t})}async streamCompact(e,t){return this.send("stream-compact",{path:e,...t})}async streamReset(e){await this.send("stream-reset",{path:e})}get connected(){var e;return((e=this.ws)==null?void 0:e.readyState)===WebSocket.OPEN}onDisconnect(e){return new Ut(this,e)}reconnect(){this.closed=!1,this.connect()}_sendRaw(e,t={}){return this.sendRaw(e,t)}get httpUrl(){return this.options.url.replace(/^ws(s?):\/\//,"http$1://")}vfs(){return new Z(this)}_send(e,t={}){return this.send(e,t)}_onDownloadChunk(e,t){return this.vfsDownloadCbs.has(e)||this.vfsDownloadCbs.set(e,new Set),this.vfsDownloadCbs.get(e).add(t),()=>{var n,r;(n=this.vfsDownloadCbs.get(e))==null||n.delete(t),((r=this.vfsDownloadCbs.get(e))==null?void 0:r.size)===0&&this.vfsDownloadCbs.delete(e)}}async _ensureDeviceKeys(){var l,s;(l=this._browserAuth)!=null||(this._browserAuth=await Promise.resolve().then(()=>(Q(),Rt)));let e=this._browserAuth,t=this._getStorage(),n=t.get("boddb-device-pubkey");if(n){let a=t.get("boddb-device-privkey");return this._deviceFingerprint=(s=t.get("boddb-device-fp"))!=null?s:null,{publicKey:n,signFn:u=>e.sign(u,a)}}let r=await e.generateKeyPair();return t.set("boddb-device-pubkey",r.publicKeyBase64),t.set("boddb-device-privkey",r.privateKeyBase64),t.set("boddb-device-fp",r.fingerprint),this._deviceFingerprint=r.fingerprint,{publicKey:r.publicKeyBase64,signFn:a=>e.sign(a,r.privateKeyBase64)}}_getStorage(){if(typeof this.options.autoAuth=="object"&&this.options.autoAuth.storage)return this.options.autoAuth.storage;let e=Ot();return e?{get:t=>e.getItem(t),set:(t,n)=>e.setItem(t,n),remove:t=>e.removeItem(t)}:(this._memStorage||(this._memStorage=new Map),{get:t=>{var n;return(n=this._memStorage.get(t))!=null?n:null},set:(t,n)=>this._memStorage.set(t,n),remove:t=>this._memStorage.delete(t)})}}class G{constructor(e){h(this,"client");this.client=e}async registerDevice(e,t){return this.client._send("auth-register-device",{publicKey:e,displayName:t})}async authenticate(e,t){let n=await this.client._send("auth-challenge",{}),r=await t(n.nonce);return this.client._send("auth-verify",{publicKey:e,signature:r,nonce:n.nonce})}async linkDevice(e,t,n,r){return this.client._send("auth-link-device",{accountFingerprint:e,password:t,devicePublicKey:n,deviceName:r})}async linkDeviceByName(e,t,n,r){return this.client._send("auth-link-device",{displayName:e,password:t,devicePublicKey:n,deviceName:r})}async revokeSession(e){await this.client._send("auth-revoke-session",{sid:e})}async revokeDevice(e,t){await this.client._send("auth-revoke-device",{accountFingerprint:e,deviceFingerprint:t})}async changePassword(e,t,n){await this.client._send("auth-change-password",{fingerprint:e,oldPassword:t,newPassword:n})}async createAccount(e,t,n,r){return this.client._send("auth-create-account",{password:e,roles:t,displayName:n,devicePublicKey:r})}async createRole(e){await this.client._send("auth-create-role",{role:e})}async deleteRole(e){await this.client._send("auth-delete-role",{roleId:e})}async updateRoles(e,t){await this.client._send("auth-update-roles",{accountFingerprint:e,roles:t})}async listAccounts(){return this.client._send("auth-list-accounts",{})}async listRoles(){return this.client._send("auth-list-roles",{})}async listDevices(e){return this.client._send("auth-list-devices",{accountFingerprint:e})}async listSessions(e){return this.client._send("auth-list-sessions",{accountFingerprint:e})}async requestApproval(e){return this.client._send("auth-request-approval",{publicKey:e})}async approveDevice(e){return this.client._send("auth-approve-device",{requestId:e})}async listAccountFingerprints(){return this.client._send("auth-list-account-fingerprints",{})}async hasAccounts(){return(await this.client._send("auth-has-accounts",{})).hasAccounts}async getAccountInfo(e){return this.client._send("auth-account-info",{accountFingerprint:e})}async pollApproval(e){return this.client._send("auth-poll-approval",{requestId:e})}}class F{constructor(e,t,n){h(this,"path");h(this,"data");h(this,"updatedAt");this.path=e,this.data=t,this.updatedAt=n}val(){return this.data}get key(){return Pt(this.path)}exists(){return this.data!==null&&this.data!==void 0}}class H{constructor(e,t,n){h(this,"client");h(this,"path");h(this,"groupId");this.client=e,this.path=t,this.groupId=n}on(e){return this.client._streamOn(this.path,this.groupId,t=>{e(t.map(n=>({key:n.key,val:()=>n.data})))})}async read(e){return(await this.client._streamRead(this.path,this.groupId,e)).map(t=>({key:t.key,val:()=>t.data}))}async ack(e){return this.client._streamAck(this.path,this.groupId,e)}}class X{constructor(e,t){h(this,"client");h(this,"basePath");h(this,"filters",[]);h(this,"orderClause");h(this,"limitVal");h(this,"offsetVal");this.client=e,this.basePath=t}where(e,t,n){return this.filters.push({field:e,op:t,value:n}),this}order(e,t="asc"){return this.orderClause={field:e,dir:t},this}limit(e){return this.limitVal=e,this}offset(e){return this.offsetVal=e,this}get(){return this.client._query(this.basePath,this.filters.length?this.filters:void 0,this.orderClause,this.limitVal,this.offsetVal)}}class D{constructor(e,t,n,r,l){h(this,"key");h(this,"path");h(this,"deliveryCount");h(this,"status");h(this,"data");this.key=e,this.path=t,this.deliveryCount=n,this.status=r,this.data=l}val(){return this.data}exists(){return this.data!==null&&this.data!==void 0}}class Z{constructor(e){h(this,"client");this.client=e}async upload(e,t,n){let r=`${this.client.httpUrl}/files/${e}`,l=await(await fetch(r,{method:"POST",body:new Blob([t]),headers:{"Content-Type":n||"application/octet-stream"}})).json();if(!l.ok)throw Error(l.error||"Upload failed");return l.data}async download(e){let t=`${this.client.httpUrl}/files/${e}`,n=await fetch(t);if(!n.ok)throw Error("Download failed");return new Uint8Array(await n.arrayBuffer())}async uploadWS(e,t,n){let r=await this.client._send("vfs-upload-init",{path:e,size:t.byteLength,mime:n}),l=J(t),s=48e3,a=Math.ceil(l.length/48e3)||1;for(let u=0;u<a;u++){let d=l.slice(u*48e3,(u+1)*48e3);await this.client._send("vfs-upload-chunk",{transferId:r,data:d,seq:u})}return await this.client._send("vfs-upload-done",{transferId:r})}async downloadWS(e){let t=await this.client._send("vfs-download-init",{path:e}),n=[];return new Promise((r,l)=>{let s=setTimeout(()=>{a(),l(Error("Download timeout"))},3e4),a=this.client._onDownloadChunk(t.transferId,u=>{n[u.seq]=u.data,u.done&&(clearTimeout(s),a(),r(fe(n.join(""))))})})}async stat(e){return await this.client._send("vfs-stat",{path:e})}async list(e){return await this.client._send("vfs-list",{path:e})}async tree(e,t){return await this.client._send("vfs-tree",{path:e,...t})}async delete(e){await this.client._send("vfs-delete",{path:e})}async mkdir(e){return await this.client._send("vfs-mkdir",{path:e})}async move(e,t){return await this.client._send("vfs-move",{path:e,dst:t})}async uploadResumable(e,t,n){var u;let r=(n==null?void 0:n.chunkSize)||262144,l=t.byteLength,s=(await this.client._send("vfs-resumable-init",{path:e,totalSize:l,mime:n==null?void 0:n.mime})).sessionId,a=0;for(;a<l;){let d=Math.min(a+r,l),f=t.slice(a,d),p=J(f);a=(await this.client._send("vfs-resumable-chunk",{sessionId:s,offset:a,data:p})).receivedBytes,(u=n==null?void 0:n.onProgress)==null||u.call(n,a,l)}return await this.client._send("vfs-resumable-done",{sessionId:s})}async resumeUpload(e,t,n){var u;let r=(n==null?void 0:n.chunkSize)||262144,l=await this.client._send("vfs-resumable-status",{sessionId:e}),s=l.receivedBytes,a=l.totalSize;for(;s<a;){let d=Math.min(s+r,a),f=t.slice(s,d),p=J(f);s=(await this.client._send("vfs-resumable-chunk",{sessionId:e,offset:s,data:p})).receivedBytes,(u=n==null?void 0:n.onProgress)==null||u.call(n,s,a)}return await this.client._send("vfs-resumable-done",{sessionId:e})}async getUploadStatus(e){return await this.client._send("vfs-resumable-status",{sessionId:e})}async updateMetadata(e,t){return await this.client._send("vfs-update-metadata",{path:e,...t})}async presign(e,t){let n=(t==null?void 0:t.method)||"GET",r=await this.client._send("vfs-presign",{path:e,expiresIn:t==null?void 0:t.expiresIn,method:n});return`${this.client.httpUrl}/files/${e}?sig=${r.sig}&exp=${r.exp}`}}class tt{constructor(e,t){h(this,"client");h(this,"queue");this.client=e,this.queue=t}async push(e,t){return this.client._mqSend("mq-push",{path:this.queue,value:e,idempotencyKey:t==null?void 0:t.idempotencyKey})}async fetch(e){return(await this.client._mqSend("mq-fetch",{path:this.queue,count:e})).map(t=>new D(t.key,t.path,t.deliveryCount,t.status,t.data))}async ack(e){await this.client._mqSend("mq-ack",{path:this.queue,key:e})}async nack(e){await this.client._mqSend("mq-nack",{path:this.queue,key:e})}async peek(e){return(await this.client._mqSend("mq-peek",{path:this.queue,count:e})).map(t=>new D(t.key,t.path,t.deliveryCount,t.status,t.data))}async dlq(){return(await this.client._mqSend("mq-dlq",{path:this.queue})).map(e=>new D(e.key,e.path,e.deliveryCount,e.status,e.data))}async purge(e){return this.client._mqSend("mq-purge",{path:this.queue,all:e==null?void 0:e.all})}}class Ut{constructor(e,t){h(this,"client");h(this,"path");this.client=e,this.path=t}async set(e){await this.client._send("on-disconnect-set",{path:this.path,value:e})}async update(e){await this.client._send("on-disconnect-update",{path:this.path,value:e})}async delete(){await this.client._send("on-disconnect-delete",{path:this.path})}async cancel(){await this.client._send("on-disconnect-cancel",{path:this.path})}}Q();function et(i,e="/db"){try{let t=new URL(i,typeof location<"u"?location.href:void 0);return`${t.protocol==="https:"?"wss:":"ws:"}//${t.host}${e}`}catch{return null}}function me(i){let e=2166136261;for(let t=0;t<i.length;t++)e^=i.charCodeAt(t),e=e+((e<<1)+(e<<4)+(e<<7)+(e<<8)+(e<<24))>>>0;return e>>>0}function $t(i,e,t){return me(`${i}::${e!=null?e:t}`)%1e4}function ye(i){var e,t,n;return(n=(t=(e=i.sticky)!=null?e:i.userId)!=null?t:i.accountId)!=null?n:""}function ve(i,e,t){if(!i.variants||i.variants.length===0)return null;let n=i.variants.reduce((s,a)=>s+a.weight,0);if(n<=0)return null;let r=$t(e,i.salt,t)%n,l=0;for(let s of i.variants)if(l+=s.weight,r<l)return{variantKey:s.key};return{variantKey:i.variants[i.variants.length-1].key}}function nt(i,e){var n;let t=(n=i.variants)==null?void 0:n.find(r=>r.key===e);return t?t.value:i.defaultValue}function we(i,e){var t,n,r;if((t=i.emails)!=null&&t.length&&e.email){let l=e.email.toLowerCase();if(i.emails.some(s=>s.toLowerCase()===l))return"email"}if((n=i.tags)!=null&&n.length&&((r=e.tags)!=null&&r.length)){let l=new Set(e.tags);if(i.tags.some(s=>l.has(s)))return"tag"}return null}function be(i,e){var n;if(e.variant)return{value:nt(i,e.variant),variant:e.variant};if(e.value!==void 0)return i.kind==="variant"&&typeof e.value=="string"?{value:nt(i,e.value),variant:e.value}:{value:e.value};if(i.kind==="boolean")return{value:!0};let t=(n=i.variants)==null?void 0:n[0];return t?{value:t.value,variant:t.key}:{value:i.defaultValue}}function B(i,e,t){var l,s,a;let n=(s=(l=i==null?void 0:i.key)!=null?l:e==null?void 0:e.key)!=null?s:"";if(t.cookieOverrides&&n in t.cookieOverrides)return{key:n,value:t.cookieOverrides[n],reason:"cookie_override"};if(!i)return{key:n,value:void 0,reason:"unregistered"};if(e&&e.enabled===!1)return{key:n,value:i.defaultValue,reason:"kill_switch"};let r=e&&(!e.branch||e.branch===t.branch);if(r&&e.targeting){let u=we(e.targeting,t);if(u){let{value:d,variant:f}=be(i,e.targeting);return{key:n,value:d,...f?{variant:f}:{},reason:u==="email"?"targeting_email":"targeting_tag"}}}if(r&&e.value!==void 0)return{key:n,value:e.value,reason:"override_value"};if(r&&e.rollout){let u=ye(t);if(i.kind==="variant"&&((a=e.rollout.variants)!=null&&a.length)){let d=ve(e.rollout,u,i.key);if(d)return{key:n,value:nt(i,d.variantKey),variant:d.variantKey,reason:"rollout"}}else if(i.kind==="boolean"){let d=$t(u,e.rollout.salt,i.key),f=Math.max(0,Math.min(1e4,Math.round(e.rollout.percent*100)));return{key:n,value:d<f,reason:"rollout"}}}return{key:n,value:i.defaultValue,reason:"default",...i.kind==="variant"&&typeof i.defaultValue=="string"?{variant:i.defaultValue}:{}}}var ke=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","utm_id"],_e=["gclid","gbraid","wbraid","dclid","fbclid","ttclid","twclid","msclkid","li_fat_id","rdt_cid","sccid","epik"],an=new Set([...ke,..._e]);function Dt(i){return i?/android/i.test(i)?"android":/iphone|ipad|ipod/i.test(i)?"ios":"web":"web"}function it(){var i;try{let e=globalThis;if((i=e.__APPWRAP__)!=null&&i.native||e.appwrap||e.nativeKit||e.nsWebViewBridge||e.Capacitor||typeof navigator<"u"&&/Appwrap|NativeScript|Capacitor/i.test(navigator.userAgent))return"native";if(typeof navigator<"u"&&navigator.standalone===!0||typeof matchMedia=="function"&&matchMedia("(display-mode: standalone)").matches)return"pwa"}catch{}return"web"}function rt(){var i;try{let e=(i=globalThis.__APPWRAP__)==null?void 0:i.platform;return e==="ios"||e==="android"?e:void 0}catch{return}}function Kt(i){var e;if(i)return i;try{return((e=document.querySelector('meta[name="app-version"]'))==null?void 0:e.getAttribute("content"))||void 0}catch{return}}function Lt(i){try{return localStorage.getItem(i)}catch{return null}}function Tt(i,e){try{localStorage.setItem(i,e)}catch{}}function Ft(i={}){let e=it(),t=rt(),n=Kt(i.version),r=[],l=!Lt("bodify_installed_at");if(l){Tt("bodify_installed_at",String(Date.now()));let a;try{a=document.referrer||void 0}catch{}r.push({name:"$install",type:"lifecycle",properties:{platform:e,nativePlatform:t,version:n,referrer:a}})}let s=Lt("bodify_app_version");return n&&s!==n&&(Tt("bodify_app_version",n),s&&r.push({name:"$app_update",type:"lifecycle",properties:{platform:e,nativePlatform:t,from:s,to:n}})),i.newSession&&r.push({name:"$session_start",type:"lifecycle",properties:{platform:e,nativePlatform:t,version:n}}),r.push({name:"$app_open",type:"lifecycle",properties:{platform:e,nativePlatform:t,version:n,firstOpen:l}}),r}function Bt(){return{name:"$pwa_install",type:"lifecycle",properties:{platform:it(),nativePlatform:rt()}}}function Se(i){try{let e=new URL(i,typeof location<"u"?location.href:void 0).hostname;return/(^|\.)(apps|itunes)\.apple\.com$/i.test(e)?"ios":/(^|\.)play\.google\.com$/i.test(e)?"android":null}catch{return null}}function Vt(i,e){for(let t of i!=null?i:[]){let n=t==null?void 0:t.href;if(typeof n!="string"||!n)continue;let r=Se(n);return r?{name:"$store_click",type:"lifecycle",properties:{platform:it(),nativePlatform:rt(),store:r,target:n,version:Kt(e)}}:null}return null}var N=[],c=null,st=null,Yt="bodify_outbox",Pe=100,Nt=!1;function gt(){try{return JSON.parse(localStorage.getItem(Yt)||"[]")}catch{return[]}}function ft(i){try{localStorage.setItem(Yt,JSON.stringify(i.slice(-Pe)))}catch{}}function ot(i){let e=gt();e.push(i),ft(e)}function kt(i,e){return fetch(i,{...e,keepalive:!0}).catch(()=>fetch(i,e))}async function jt(){if(typeof navigator<"u"&&navigator.onLine===!1)return;let i=gt();if(!i.length)return;ft([]);let e=[];for(let t of i)try{(await kt(t.url,{method:"POST",headers:t.headers,body:t.body})).ok||e.push(t)}catch{e.push(t)}e.length&&ft([...gt(),...e])}function Gt(i,e,t,n){let r=typeof navigator<"u"&&navigator.onLine===!1;if(!r&&n&&typeof navigator<"u"&&navigator.sendBeacon)try{if(navigator.sendBeacon(i,new Blob([e],{type:"application/json"})))return}catch{}if(r){ot({url:i,body:e,headers:t});return}kt(i,{method:"POST",headers:t,body:e}).then(l=>{l.ok||ot({url:i,body:e,headers:t})}).catch(()=>ot({url:i,body:e,headers:t}))}var S=new Map,x=new Map,w=new Set,b=null,k=null,T=null,pt=null,Mt=new Map,Ae=6e4,j="bodify.flags.override",mt="bodify_anon_id",at="bodify_session_id",Ce=18e5,R=!1,O,q,Ht=!1,g,M=[],yt=null,A=[],_={};function Xt(){var i,e;return(e=(i=crypto.randomUUID)==null?void 0:i.call(crypto))!=null?e:Math.random().toString(36).slice(2)+Date.now().toString(36)}function Zt(){try{let e=localStorage.getItem(mt);if(e)return e}catch{}let i=Xt();try{localStorage.setItem(mt,i)}catch{}return i}var qt="bodify_anon_uid";function Ie(){var e,t;try{let n=localStorage.getItem(qt);if(n)return n}catch{}let i="anon_"+((t=(e=crypto.randomUUID)==null?void 0:e.call(crypto).replace(/-/g,""))!=null?t:Math.random().toString(16).slice(2)+Date.now().toString(16)).slice(0,32);try{localStorage.setItem(qt,i)}catch{}return i}var lt=null,ct=null;function zt(i){c&&(c.userId=i);for(let e of w)e()}function _t(){try{let e=sessionStorage.getItem(at);if(e){let{id:t,ts:n}=JSON.parse(e);if(Date.now()-n<Ce)return sessionStorage.setItem(at,JSON.stringify({id:t,ts:Date.now()})),t}}catch{}let i=Xt();vt=!0;try{sessionStorage.setItem(at,JSON.stringify({id:i,ts:Date.now()}))}catch{}return i}function Ee(){let i=vt;return vt=!1,i}var vt=!1;function te(i,e){if(q=i||void 0,!R||!g||!i)return Promise.resolve(!1);let t={"Content-Type":"application/json"};return O&&(t["x-analytics-token"]=O),kt(`${re()}/identify`,{method:"POST",headers:t,body:JSON.stringify({anonymousId:g,userId:i,traits:e})}).then(n=>(n.ok||console.warn(`[bodify] analytics identify failed: HTTP ${n.status}`),n.ok)).catch(n=>(console.warn("[bodify] analytics identify failed",n),!1))}var ee="bodify_identify_explicit";function ne(){if(Ht)return!0;try{return localStorage.getItem(ee)==="1"}catch{return!1}}var I,wt,V;function ut(i){if(ne())return;let e=i&&!i.isAnonymous&&i.id||void 0;if(I&&e!==I){try{localStorage.removeItem(mt)}catch{}g&&(g=Zt()),q=void 0,I=wt=V=void 0}e&&(I=e,ie())}function ie(){let i=I;if(!i||wt===i||V===i||!R||ne())return;V=i;let e=g;te(i).then(t=>{I!==i||g!==e||(V=void 0,t&&(wt=i))})}function re(){return c?`${c.ingestUrl.replace(/\/apps\/[^/]+\/ingest$/,"")}/analytics/${c.appId}`:""}function y(i,e,t){let n=Object.keys(_).length?{..._,...t}:t;return{anonymousId:g,sessionId:_t(),userId:q,name:i,type:e,properties:n,source:{url:location.href,referrer:document.referrer||void 0,userAgent:navigator.userAgent},ts:Date.now()}}function E(){if(M.length===0)return;let i=M.splice(0),e=`${re()}/events`,t=JSON.stringify({events:i}),n={"Content-Type":"application/json"};O&&(n["x-analytics-token"]=O),Gt(e,t,n,!O)}function v(i){M.push(i),M.length>=10&&E()}function xe(i){let e=typeof i.analytics=="object"?i.analytics:{};if(R=!0,O=e.secret,g=Zt(),yt=setInterval(E,5e3),ie(),!e.disableLifecycleEvents){_t();let s=Ee();for(let d of Ft({version:e.appVersion,newSession:s}))v(y(d.name,d.type,d.properties));let a=()=>{let d=Bt();v(y(d.name,d.type,d.properties))};window.addEventListener("appinstalled",a),A.push(()=>window.removeEventListener("appinstalled",a));let u=d=>{var p;let f=Vt((p=d.composedPath)==null?void 0:p.call(d),e.appVersion);f&&(v(y(f.name,f.type,f.properties)),E())};document.addEventListener("click",u,!0),A.push(()=>document.removeEventListener("click",u,!0))}if(!e.disableAutoPageViews){let s=()=>{try{let $=new URL(location.href);return $.searchParams.sort(),`${$.pathname}${$.search}${$.hash}`}catch{return`${Math.random()}`}},a=null,u=()=>{let $=s();$!==a&&(a=$,v(y("$pageview","page_view",{path:location.pathname,title:document.title})))};u();let d=history.pushState.bind(history),f=history.replaceState.bind(history);history.pushState=function(...$){d(...$),u()},history.replaceState=function(...$){f(...$),u()};let p=()=>u();window.addEventListener("popstate",p),window.addEventListener("hashchange",p),A.push(()=>{history.pushState=d,history.replaceState=f,window.removeEventListener("popstate",p),window.removeEventListener("hashchange",p)})}let t=s=>{var a;return v(y("$error","error",{message:s.message,filename:s.filename,line:s.lineno,col:s.colno,stack:(a=s.error)==null?void 0:a.stack}))},n=s=>{let a=s.reason instanceof Error?s.reason:Error(String(s.reason));v(y("$error","error",{message:a.message,stack:a.stack}))};window.addEventListener("error",t),window.addEventListener("unhandledrejection",n),A.push(()=>{window.removeEventListener("error",t),window.removeEventListener("unhandledrejection",n)});let r=()=>{document.visibilityState==="hidden"&&E()},l=()=>E();document.addEventListener("visibilitychange",r),window.addEventListener("beforeunload",l),A.push(()=>{document.removeEventListener("visibilitychange",r),window.removeEventListener("beforeunload",l)})}function Re(){if(typeof document>"u")return;let i=document.cookie.split(";").map(e=>e.trim()).find(e=>e.startsWith(`${j}=`));if(i)try{let e=decodeURIComponent(i.slice(j.length+1));return JSON.parse(e).flags}catch{return}}function se(i){var e,t;if(i){for(let n of(e=i.definitions)!=null?e:[])n!=null&&n.key&&S.set(n.key,n);for(let n of(t=i.overrides)!=null?t:[])n!=null&&n.key&&x.set(n.key,n)}}function Oe(){if(b)return b;if(!c)throw Error("Bodify SDK not initialized");let i=et(c.ingestUrl);if(!i)throw Error("Cannot derive DB WS URL from ingestUrl");return b=new L({url:i,reconnect:!0,offlineQueue:!0,offlineQueueCap:100,auth:()=>{var e;return(e=o.auth._token)!=null?e:""}}),b.connect().catch(()=>{}),b}function Ue(){if(k)return k;if(!c)throw Error("Bodify SDK not initialized");let i=et(c.ingestUrl,"/_bodify/db");if(!i)throw Error("Cannot derive flags WS URL from ingestUrl");return k=new L({url:i,reconnect:!0}),k.connect().catch(()=>{}),k}var bt=0;function $e(){if(T||!c)return;let i=++bt,e=c,t;try{t=`${new URL(e.ingestUrl,typeof location<"u"?location.href:void 0).origin}/api/apps/${encodeURIComponent(e.appId)}/flags/snapshot`}catch{t=""}let n=r=>{var l,s;if(!(i!==bt||c!==e)){if(r!=null&&r.definitions||r!=null&&r.overrides){se({definitions:(l=r.definitions)!=null?l:[],overrides:(s=r.overrides)!=null?s:[]});for(let a of w)a(void 0)}De((r==null?void 0:r.appId)||e.appId)}};if(!t||typeof fetch>"u")return n();fetch(t).then(r=>r.ok?r.json():void 0).then(n,r=>{console.warn("[bodify] flags snapshot failed",r),n()})}function De(i){if(T)return;let e;try{e=Ue()}catch{return}let t=`flags/${i}/definitions`,n=`flags/${i}/overrides`;T=e.on(t,r=>{let l=r.val();if(!l&&S.size>0)return;let s=new Map;if(l)for(let a of Object.values(l))a!=null&&a.key&&s.set(a.key,a);S=s;for(let a of w)a(void 0)},{deep:!0}),pt=e.on(n,r=>{let l=r.val();if(!l&&x.size>0)return;let s=new Map;if(l)for(let a of Object.values(l))a!=null&&a.key&&s.set(a.key,a);x=s;for(let a of w)a(void 0)},{deep:!0})}function Le(){bt++,T==null||T(),pt==null||pt(),T=null,pt=null}function dt(i){var e,t,n,r;return{userId:(e=i==null?void 0:i.userId)!=null?e:c==null?void 0:c.userId,accountId:i==null?void 0:i.accountId,email:(t=i==null?void 0:i.email)!=null?t:c==null?void 0:c.email,tags:(n=i==null?void 0:i.tags)!=null?n:c==null?void 0:c.tags,branch:(r=i==null?void 0:i.branch)!=null?r:c==null?void 0:c.branch,sticky:i==null?void 0:i.sticky,cookieOverrides:Re()}}function Wt(i,e,t,n,r){var d,f,p;if(!c)return;let l=(p=(f=(d=r.sticky)!=null?d:r.userId)!=null?f:r.accountId)!=null?p:"",s=`${i}::${e!=null?e:String(t)}::${l}`,a=Date.now(),u=Mt.get(s);u&&a-u<Ae||(Mt.set(s,a),m({kind:"event",event:"flag.exposure",message:`flag.exposure ${i}=${e!=null?e:String(t)}`,meta:{flagKey:i,value:t,variant:e,reason:n,branch:r.branch,...g?{anonymousId:g}:{},...r.userId?{userId:r.userId}:{}}}))}function C(){if(!c||N.length===0)return;let i=N.splice(0),e={"Content-Type":"application/json"};c.apiKey&&(e.Authorization=`Bearer ${c.apiKey}`);let t=JSON.stringify({signals:i});Gt(c.ingestUrl,t,e,!c.apiKey)}function Te(i){var e;N.push(i),c&&N.length>=((e=c.maxBatchSize)!=null?e:20)&&C()}function m(i){var e;Te({kind:i.kind,level:(e=i.level)!=null?e:"info",source:"sdk",message:i.message,ts:Date.now(),deployId:c==null?void 0:c.deployId,event:i.event,metric:i.metric,value:i.value,unit:i.unit,meta:{...c!=null&&c.userId?{userId:c.userId}:{},...i.meta}})}var Qt="bodify_install_link",ht="bodify_install_link_fails",Jt=3,o={init(i){var t;c=i;let e={errors:!0,rejections:!0,console:!1,...i.capture};st=setInterval(C,(t=i.flushIntervalMs)!=null?t:2e3),e.errors&&window.addEventListener("error",n=>{var r;m({kind:"log",level:"error",message:n.message||"Unknown error",meta:{filename:n.filename,lineno:n.lineno,colno:n.colno,stack:(r=n.error)==null?void 0:r.stack}})}),e.rejections&&window.addEventListener("unhandledrejection",n=>{let r=n.reason instanceof Error?n.reason:Error(String(n.reason));m({kind:"log",level:"error",message:r.message,meta:{stack:r.stack}})}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&C()}),window.addEventListener("beforeunload",C),o.auth.restore(),se(i.flags),$e(),!Nt&&typeof window<"u"&&(window.addEventListener("online",()=>{jt()}),Nt=!0),jt(),i.analytics!==!1&&!Ke(i.ingestUrl)&&!Be()&&xe(i)},event(i,e){let t=R?{anonymousId:g,sessionId:_t(),userId:q,..._,...e}:{..._,...e};m({kind:"event",message:i,event:i,meta:t})},metric(i,e,t){let{unit:n,...r}=t!=null?t:{};m({kind:"metric",message:`${i}=${e}`,metric:i,value:e,unit:n,meta:Object.keys(r).length>0?r:void 0})},log:{debug:(i,e)=>m({kind:"log",level:"debug",message:i,meta:e}),info:(i,e)=>m({kind:"log",level:"info",message:i,meta:e}),warn:(i,e)=>m({kind:"log",level:"warn",message:i,meta:e}),error:(i,e)=>m({kind:"log",level:"error",message:i,meta:e})},leads:{async collect(i){if(!c)throw Error("Bodify SDK not initialized");let e=`${c.ingestUrl.replace(/\/apps\/[^/]+\/ingest$/,"")}/leads/${c.appId}/collect`,t={"Content-Type":"application/json"};c.apiKey&&(t.Authorization=`Bearer ${c.apiKey}`);let n=await fetch(e,{method:"POST",headers:t,body:JSON.stringify(i)});if(!n.ok)throw Error(`Leads collect failed: ${n.status}`);return n.json()}},links:{_listeners:[],_inflight:null,_read(){try{let i=JSON.parse(localStorage.getItem(Qt)||"null");if(i&&i.done)return i}catch{}return{done:!1,result:null}},_write(i){try{localStorage.setItem(Qt,JSON.stringify(i))}catch{}},_fails(){try{return Number(localStorage.getItem(ht))||0}catch{return 0}},_setFails(i){try{i?localStorage.setItem(ht,String(i)):localStorage.removeItem(ht)}catch{}},_emit(i,e){for(let t of o.links._listeners)try{t({url:i,source:e})}catch(n){console.warn("[bodify] onLink listener failed",n)}},installLink(i={}){var t,n;let e=o.links._read();return e.done?Promise.resolve(e.result):(n=(t=o.links)._inflight)!=null?n:t._inflight=o.links._claim(i).finally(()=>{o.links._inflight=null})},async _claim(i){var d,f,p,$,je;if(!c)throw Error("Bodify SDK not initialized");let e={},t=i.kit,n=!1;if(t){try{await((d=t.ready)==null?void 0:d.call(t)),(f=t.is)!=null&&f.native&&(n=!0),(t.platform==="ios"||t.platform==="android")&&(e.os=t.platform)}catch(P){console.warn("[bodify] native-kit not ready",P)}let Ne=!1;try{Ne=t.capability("attribution")==="native"}catch(P){console.warn("[bodify] native-kit capability read failed",P)}if(Ne){n=!0;try{let P=await t.invoke("attribution.fetch",void 0,{timeoutMs:3e4});((P==null?void 0:P.platform)==="ios"||(P==null?void 0:P.platform)==="android")&&(e.os=P.platform),(P==null?void 0:P.status)==="ok"&&P.platform==="android"&&(e.referrer=P.referrer),(P==null?void 0:P.status)==="ok"&&P.platform==="ios"&&(e.adServicesToken=P.token),o.links._setFails(0)}catch(P){let Me=o.links._fails()+1;if(o.links._setFails(Me),Me<Jt)return console.warn(`[bodify] native attribution read failed (${Me}/${Jt}) \u2014 retrying next launch`,P),null;console.warn("[bodify] native attribution read keeps failing \u2014 falling back to IP+OS",P)}}}let r=Dt(typeof navigator<"u"?navigator.userAgent:"");if(e.os=($=(p=i.os)!=null?p:e.os)!=null?$:r==="web"?void 0:r,!n&&!i.web||!e.os)return null;g&&(e.anonymousId=g),i.consent&&(e.consent=!0);let l=c.ingestUrl.replace(/\/apps\/[^/]+\/ingest$/,""),s=await fetch(`${l}/apps/${c.appId}/links/claim`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!s.ok)throw Error(`Install link claim failed: ${s.status}`);let a=await s.json();if(a.retry)return null;let u=null;return a.match&&(u={url:(je=a.url)!=null?je:null,match:a.match,...a.claimId?{claimId:a.claimId}:{},...a.linkSlug?{linkSlug:a.linkSlug}:{},...a.asa?{asa:a.asa}:{},...a.referrer?{referrer:a.referrer}:{}}),o.links._write({done:!0,result:u}),u!=null&&u.url&&o.links._emit(u.url,"install"),u},consumeInstallLink(){let i=o.links._read();return i.result&&o.links._write({done:!0,result:null}),i.result},onLink(i){return o.links._listeners.push(i),()=>{o.links._listeners=o.links._listeners.filter(e=>e!==i)}},async handleLink(i,e){var r;if(!i)return;let t=e!=null&&e.linkPath&&/^[a-z0-9-]+$/.test(e.linkPath)?`|\\/${e.linkPath}`:"",n=i.match(new RegExp(`^[a-z][a-z0-9+.-]*:\\/\\/[^/?#]+(?:\\/_bodify\\/l|\\/l\\/[^/?#]+${t})\\/([^/?#]+)\\/?(\\?[^#]*)?`,"i"));if(n&&c)try{let l=c.ingestUrl.replace(/\/apps\/[^/]+\/ingest$/,""),s=await fetch(`${l}/apps/${c.appId}/links/resolve/${n[1]}${(r=n[2])!=null?r:""}`);if(s.ok){let a=await s.json();if(a.url)return o.links._emit(a.url,"warm")}else console.warn(`[bodify] link resolve ${s.status} \u2014 passing the raw URL`)}catch(l){console.warn("[bodify] link resolve failed \u2014 passing the raw URL",l)}o.links._emit(i,"warm")}},storage:{_baseUrl(){if(!c)throw Error("Bodify SDK not initialized");return c.ingestUrl.replace(/\/apps\/[^/]+\/ingest$/,"")+`/apps/${c.appId}/storage`},_headers(){let i={"Content-Type":"application/json"};return c!=null&&c.apiKey&&(i.Authorization=`Bearer ${c.apiKey}`),i},async upload(i,e){var a;let t=o.storage._baseUrl(),n=(a=e==null?void 0:e.path)!=null?a:i.name,r=await fetch(`${t}/upload`,{method:"POST",headers:o.storage._headers(),body:JSON.stringify({path:n,contentType:i.type||"application/octet-stream",size:i.size,public:e==null?void 0:e.public})});if(!r.ok)throw Error(`Upload init failed: ${r.status}`);let l=await r.json();if(l.uploadUrl){let u=await fetch(l.uploadUrl,{method:"PUT",body:i,headers:{"Content-Type":i.type||"application/octet-stream"}});if(!u.ok)throw Error(`Upload to storage failed: ${u.status}`)}else{let u=await fetch(`${t}/upload/${l.fileId}?sessionId=${l.sessionId}`,{method:"PUT",body:i,headers:{...o.storage._headers(),"Content-Type":i.type||"application/octet-stream"}});if(!u.ok)throw Error(`Local upload failed: ${u.status}`)}let s=await fetch(`${t}/upload/${l.fileId}/finalize`,{method:"POST",headers:o.storage._headers(),body:JSON.stringify({sessionId:l.sessionId})});if(!s.ok)throw Error(`Finalize failed: ${s.status}`);return await s.json().catch(()=>({})),{fileId:l.fileId}},async getUrl(i){let e=await fetch(`${o.storage._baseUrl()}/files/${i}/url`,{headers:o.storage._headers()});if(!e.ok)throw Error(`Get URL failed: ${e.status}`);return(await e.json()).url},async delete(i){let e=await fetch(`${o.storage._baseUrl()}/files/${i}`,{method:"DELETE",headers:o.storage._headers()});if(!e.ok)throw Error(`Delete failed: ${e.status}`)},async list(i){let e=new URLSearchParams;i!=null&&i.prefix&&e.set("prefix",i.prefix),i!=null&&i.limit&&e.set("limit",String(i.limit));let t=await fetch(`${o.storage._baseUrl()}/files?${e}`,{headers:o.storage._headers()});if(!t.ok)throw Error(`List failed: ${t.status}`);return t.json()},publicUrl(i){if(!c)throw Error("Bodify SDK not initialized");return`${c.ingestUrl.replace(/\/apps\/[^/]+\/ingest$/,"")}/apps/${c.appId}/storage/public/${i}`}},auth:{_token:null,_user:null,_pendingVerification:null,_listeners:[],_baseUrl(){if(!c)throw Error("Bodify SDK not initialized");return c.ingestUrl.replace(/\/apps\/[^/]+\/ingest$/,"")+`/apps/${c.appId}/auth`},async _fetch(i,e){let t={"Content-Type":"application/json",...e==null?void 0:e.headers};return o.auth._token&&(t.Authorization=`Bearer ${o.auth._token}`),fetch(`${o.auth._baseUrl()}${i}`,{...e,headers:t})},_setToken(i){o.auth._token=i,i?localStorage.setItem("bodify_auth_token",i):localStorage.removeItem("bodify_auth_token")},_notify(){ut(o.auth._user),o.auth._listeners.forEach(i=>i(o.auth._user,o.auth._pendingVerification))},_handleAuthResponse(i){o.auth._setToken(i.token),i.emailVerificationRequired?(o.auth._user=null,o.auth._pendingVerification=i.user):(o.auth._user=i.user,o.auth._pendingVerification=null),o.auth._notify()},async signUp(i){var n;let e=await o.auth._fetch("/signup",{method:"POST",body:JSON.stringify(i)});if(!e.ok){let r=await e.json().catch(()=>({}));throw Error((n=r.error)!=null?n:`Signup failed: ${e.status}`)}let t=await e.json();return o.auth._handleAuthResponse(t),t},async signIn(i){var n;let e=await o.auth._fetch("/login",{method:"POST",body:JSON.stringify(i)});if(!e.ok){let r=await e.json().catch(()=>({}));throw Error((n=r.error)!=null?n:`Login failed: ${e.status}`)}let t=await e.json();return o.auth._handleAuthResponse(t),t},signInWithOAuth(i,e){var n;let t=(n=e==null?void 0:e.returnTo)!=null?n:window.location.href;window.location.href=`${o.auth._baseUrl()}/oauth/${i}?returnTo=${encodeURIComponent(t)}`},adoptAnonIdentity(){var e;if((e=o.auth._user)!=null&&e.isAnonymous)return o.auth._user.id;let i=Ie();return o.auth._user||(o.auth._user={id:i,isAnonymous:!0},zt(i),o.auth._notify()),i},whenTokenReady(){return o.auth._token?Promise.resolve():lt!=null?lt:Promise.resolve()},async signInAnonymously(){var n;let i=o.auth.adoptAnonIdentity();!o.auth._token&&!lt&&(lt=new Promise(r=>{ct=r}));let e=await o.auth._fetch("/anonymous",{method:"POST",body:JSON.stringify({uid:i})});if(!e.ok){let r=await e.json().catch(()=>({}));throw Error((n=r.error)!=null?n:`Anonymous signin failed: ${e.status}`)}let t=await e.json();return o.auth._setToken(t.token),o.auth._user=t.user,o.auth._pendingVerification=null,zt(t.user.id),o.auth._notify(),ct==null||ct(),ct=null,t},async attachEmail(i){var n;let e=await o.auth._fetch("/email/attach",{method:"POST",body:JSON.stringify({email:i})});if(!e.ok){let r=await e.json().catch(()=>({}));throw Error((n=r.error)!=null?n:"Attach failed")}let{user:t}=await e.json();return o.auth._user=t,o.auth._notify(),t},async linkEmail(i,e){var r;let t=await o.auth._fetch("/link",{method:"POST",body:JSON.stringify({provider:"email",email:i,password:e})});if(!t.ok){let l=await t.json().catch(()=>({}));throw Error((r=l.error)!=null?r:"Link failed")}let{user:n}=await t.json();return o.auth._user=n,o.auth._notify(),n},async linkPhone(i,e){var r;let t=await o.auth._fetch("/link",{method:"POST",body:JSON.stringify({provider:"phone",phone:i,otp:e})});if(!t.ok){let l=await t.json().catch(()=>({}));throw Error((r=l.error)!=null?r:"Link failed")}let{user:n}=await t.json();return o.auth._user=n,o.auth._notify(),n},async startPhoneSignIn(i){var t;let e=await o.auth._fetch("/phone/start",{method:"POST",body:JSON.stringify({phone:i})});if(!e.ok){let n=await e.json().catch(()=>({}));throw Error((t=n.error)!=null?t:"Failed to send OTP")}return e.json()},async linkOAuth(i,e){var l,s;let t=(l=e==null?void 0:e.returnTo)!=null?l:window.location.href,n=await o.auth._fetch(`/link-oauth/${i}`,{method:"POST",body:JSON.stringify({returnTo:t})});if(!n.ok){let a=await n.json().catch(()=>({}));throw Error((s=a.error)!=null?s:"Link failed")}let{redirectUrl:r}=await n.json();window.location.href=r},async mergeFromAnonymous(i){var t;let e=await o.auth._fetch("/merge",{method:"POST",body:JSON.stringify({sourceId:i})});if(!e.ok){let n=await e.json().catch(()=>({}));throw Error((t=n.error)!=null?t:"Merge failed")}return e.json()},async listAudit(){let i=await o.auth._fetch("/audit");if(!i.ok)throw Error("Audit list failed");return i.json()},async signInWithPhone(i,e){var r;let t=await o.auth._fetch("/phone/verify",{method:"POST",body:JSON.stringify({phone:i,code:e})});if(!t.ok){let l=await t.json().catch(()=>({}));throw Error((r=l.error)!=null?r:"Phone verify failed")}let n=await t.json();return o.auth._setToken(n.token),o.auth._user=n.user,o.auth._pendingVerification=null,o.auth._notify(),n},async signOut(){await o.auth._fetch("/logout",{method:"POST"}).catch(()=>{}),o.auth._setToken(null),o.auth._user=null,o.auth._pendingVerification=null,o.auth._notify()},async verifyEmail(i){var n;let e=await o.auth._fetch("/verify-email",{method:"POST",body:JSON.stringify({code:i})});if(!e.ok){let r=await e.json().catch(()=>({}));throw Error((n=r.error)!=null?n:"Verification failed")}let t=await e.json();return o.auth._setToken(t.token),o.auth._user=t.user,o.auth._pendingVerification=null,o.auth._notify(),t},async resendVerification(){var e;let i=await o.auth._fetch("/resend-verification",{method:"POST"});if(!i.ok){let t=await i.json().catch(()=>({}));throw Error((e=t.error)!=null?e:"Resend failed")}},async signInWithMagicLink(i){var n;let e=await o.auth._fetch("/magic-link/verify",{method:"POST",body:JSON.stringify({token:i})});if(!e.ok){let r=await e.json().catch(()=>({}));throw Error((n=r.error)!=null?n:"Invalid or expired link")}let t=await e.json();return o.auth._setToken(t.token),o.auth._user=t.user,o.auth._pendingVerification=null,o.auth._notify(),t},async getProviders(){return(await fetch(`${o.auth._baseUrl()}/providers`)).json()},async getUser(){if(!o.auth._token)return null;let i=3;for(let e=0;e<i;e++){let t=null;try{t=await o.auth._fetch("/me")}catch{}if(t){if(t.ok){let n=await t.json();return o.auth._user=n,ut(n),n}if(t.status===401)return o.auth._user=null,ut(null),null}e<i-1&&await new Promise(n=>setTimeout(n,400*(e+1)))}return o.auth._user},async updateProfile(i){let e=await o.auth._fetch("/me",{method:"PATCH",body:JSON.stringify(i)});if(!e.ok)throw Error("Update failed");let t=await e.json();return o.auth._user=t,o.auth._notify(),t},onAuthStateChange(i){return o.auth._listeners.push(i),()=>{o.auth._listeners=o.auth._listeners.filter(e=>e!==i)}},restore(){let i=localStorage.getItem("bodify_auth_token");i&&(o.auth._token=i)}},flags:{get(i,e){let t=dt(e),n=S.get(i),r=x.get(i),l=B(n,r,t);return Wt(i,l.variant,l.value,l.reason,t),l.value},isEnabled(i,e){return o.flags.get(i,e)===!0},variant(i,e){var s;let t=dt(e),n=S.get(i),r=x.get(i),l=B(n,r,t);return Wt(i,l.variant,l.value,l.reason,t),(s=l.variant)!=null?s:""},all(i){let e=dt(i),t={};for(let[n,r]of S){let l=x.get(n),s=B(r,l,e);t[n]=s.value}return t},subscribe(i){return w.add(i),()=>w.delete(i)},keys(){return[...S.keys()].sort()},setCookieOverride(i,e){var r;if(typeof document>"u")return;let t=encodeURIComponent(JSON.stringify({flags:i})),n=(r=e==null?void 0:e.maxAgeSec)!=null?r:86400;document.cookie=`${j}=${t}; path=/; max-age=${n}; samesite=lax`;for(let l of w)l()},clearCookieOverride(){if(!(typeof document>"u")){document.cookie=`${j}=; path=/; max-age=0`;for(let i of w)i()}}},analytics:{identify(i,e){if(i){Ht=!0;try{localStorage.setItem(ee,"1")}catch{}}te(i,e)},track(i,e){R&&v(y(i,"custom",e))},page(i){R&&v(y("$pageview","page_view",{path:location.pathname,title:document.title,...i}))},getAnonymousId(){return g!=null?g:""},register(i){_={..._,...i}},unregister(...i){for(let e of i)delete _[e]}},get db(){return Oe()},flush:C,destroy(){st&&clearInterval(st),yt&&clearInterval(yt),A.forEach(i=>i()),E(),Le(),b==null||b.disconnect(),b=null,k==null||k.disconnect(),k=null,C()}};function Ke(i){try{let e=new URL(i,typeof location<"u"?location.href:void 0).hostname;return e==="localhost"||e==="0.0.0.0"||e==="::1"||e==="[::1]"||e.endsWith(".local")||/^127\./.test(e)||/^10\./.test(e)||/^192\.168\./.test(e)||/^172\.(1[6-9]|2\d|3[01])\./.test(e)||/^169\.254\./.test(e)}catch{return!1}}function oe(){if(typeof location>"u")return!1;try{return new URL(location.href).searchParams.get("__bodify_render")==="1"}catch{return!1}}var Fe=oe();function Be(){return Fe||oe()}function Ve(i,e){let t=typeof location<"u"?location.origin:"";try{if(i!=null&&i.src){let n=new URL(i.src,typeof location<"u"?location.href:void 0);(n.protocol==="http:"||n.protocol==="https:")&&(t=n.origin)}}catch{}return`${t}/api/apps/${e}/ingest`}if(typeof window<"u"){let i=window.__BODIFY_CONFIG__;if(i)o.init(i);else{let e=document.currentScript;if(e!=null&&e.dataset.appId){let t=window.__BODIFY_FLAGS__;o.init({appId:e.dataset.appId,ingestUrl:e.dataset.ingestUrl||Ve(e,e.dataset.appId),apiKey:e.dataset.apiKey,deployId:e.dataset.deployId,branch:e.dataset.branch,userId:e.dataset.userId,flags:t,analytics:e.dataset.analytics!=="false"})}}}window.Bodify=o;

//# bodify-sdk 6d0503dd77ec7510