var P1=Object.defineProperty;var x1=(Z)=>Z;function I1(Z,$){this[Z]=x1.bind(null,$)}var k1=(Z,$)=>{for(var G in $)P1(Z,G,{get:$[G],enumerable:!0,configurable:!0,set:I1.bind($,G)})};var W1=(Z,$)=>()=>(Z&&($=Z(Z=0)),$);var Y1=()=>{};var j1={};k1(j1,{wrapPublicKey:()=>n,unwrapPublicKey:()=>_1,sign:()=>T1,generateKeyPair:()=>M1,browserFingerprint:()=>u});function B1(Z,$){let G=new Uint8Array(Z.length+$.length);return G.set(Z),G.set($,Z.length),G}function P(Z){let $="";for(let G=0;G<Z.length;G++)$+=String.fromCharCode(Z[G]);return btoa($)}function Q1(Z){let $=atob(Z),G=new Uint8Array($.length);for(let J=0;J<$.length;J++)G[J]=$.charCodeAt(J);return G}function m1(Z){return Array.from(Z).map(($)=>$.toString(16).padStart(2,"0")).join("")}function n(Z){return B1(L1,Z)}function _1(Z){return Z.slice(L1.length)}async function M1(){let Z=(void 0).randomSecretKey(),$=await(void 0)(Z),G=n($),J=await u(P(G));return{publicKeyBase64:P(G),privateKeyBase64:P(Z),fingerprint:J}}async function T1(Z,$){let G=Q1($),J=new TextEncoder().encode(Z),z=await(void 0)(J,G);return P(z)}async function u(Z){let $=Q1(Z),G=new ArrayBuffer($.byteLength);new Uint8Array(G).set($);let J=await crypto.subtle.digest("SHA-256",G);return m1(new Uint8Array(J))}var L1,XZ;var y=W1(()=>{Y1();L1=new Uint8Array([48,42,48,5,6,3,43,101,112,3,33,0]),XZ=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32])});var F=1;function X1(Z){let $=Z.lastIndexOf("/");return $>=0?Z.slice($+1):Z}function f(Z){let $="";for(let G=0;G<Z.length;G++)$+=String.fromCharCode(Z[G]);return btoa($)}function b1(Z){let $=atob(Z),G=new Uint8Array($.length);for(let J=0;J<$.length;J++)G[J]=$.charCodeAt(J);return G}function v1(){if(typeof window<"u"&&window.location)return`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/db`;let Z=globalThis.process;if(Z?.env?.BODDB_URL)return Z.env.BODDB_URL.replace(/^http/,"ws");return"ws://localhost:4460"}class h{url=v1();auth;keyAuth;autoAuth;reconnect=!0;reconnectInterval=1000;maxReconnectInterval=30000;requestTimeout=30000;onVersionMismatch;offlineQueue=!1;offlineQueueCap=100}class I{options;ws=null;msgId=0;pending=new Map;valueCbs=new Map;childCbs=new Map;activeSubs=new Set;streamCbs=new Map;activeStreamSubs=new Set;vfsDownloadCbs=new Map;closed=!1;_browserAuth=null;reconnectTimer=null;reconnectDelay;connectPromise=null;_authToken=null;_deviceFingerprint=null;_welcomeListeners=new Set;_pendingWelcome=null;_authComplete=!1;_offlineQueue=[];_rec=null;_recCap=5000;serverInfo=null;onOfflineQueue;onOfflineFlush;auth;constructor(Z){if(this.options={...new h,...Z},this.reconnectDelay=this.options.reconnectInterval,this.auth=new c(this),typeof localStorage<"u")try{let $=localStorage.getItem("BOD_WS_RECORD");if($){let G=Number($);this._recCap=Number.isFinite(G)&&G>0?G:5000,this._rec=[]}}catch{}}_recPush(Z,$,G=!1){if(!this._rec)return;if(this._rec.push(G?{t:Date.now(),dir:Z,data:$,parseError:G}:{t:Date.now(),dir:Z,data:$}),this._rec.length>this._recCap)this._rec.splice(0,this._rec.length-this._recCap)}startRecording(Z=5000){this._recCap=Z,this._rec=this._rec??[]}stopRecording(){let Z=this._rec??[];return this._rec=null,Z}getRecording(){return this._rec??[]}clearRecording(){if(this._rec)this._rec.length=0}dumpRecording(Z="array"){let $=this.getRecording();return Z==="json"?JSON.stringify($,null,2):$}onWelcome(Z){return this._welcomeListeners.add(Z),()=>{this._welcomeListeners.delete(Z)}}get deviceFingerprint(){return this._deviceFingerprint}get authToken(){return this._authToken}async connect(){if(this.ws?.readyState===WebSocket.OPEN)return;if(this.connectPromise)return this.connectPromise;return this.closed=!1,this.connectPromise=new Promise((Z,$)=>{let G=new WebSocket(this.options.url);G.onopen=async()=>{this._recPush("open",{url:this.options.url}),this.ws=G,this.reconnectDelay=this.options.reconnectInterval,this.onStatusChange?.(!0);try{if(await this.onConnect?.(),this.options.autoAuth&&!this.options.keyAuth){let J=await this._ensureDeviceKeys();this.options.keyAuth={publicKey:J.publicKey,signFn:J.signFn},await this.send("auth-register-device",{publicKey:J.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 J=await this.send("auth-challenge",{}),z=await this.options.keyAuth.signFn(J.nonce),H=await this.send("auth-verify",{publicKey:this.options.keyAuth.publicKey,signature:z,nonce:J.nonce});this._authToken=H.token}}else if(this.options.auth){let J=await this.options.auth();if(J)await this.send("auth",{token:J})}if(this._authComplete=!0,this._pendingWelcome){this.serverInfo=this._pendingWelcome;for(let J of this._welcomeListeners)J(this.serverInfo);this._pendingWelcome=null}if(this.activeSubs.size>0){let J=[...this.activeSubs].map((z)=>{let H=z.indexOf(":"),X=z.slice(0,H),Y=z.slice(H+1),Q=X.endsWith("-shallow"),M=Q?X.slice(0,-8):X;return{path:Y,event:M,...Q?{shallow:!0}:{}}});try{await this.send("batch-sub",{subscriptions:J})}catch{for(let z of J)await this.send("sub",z)}}for(let J of this.activeStreamSubs){let[z,H]=this.splitStreamKey(J);await this.send("stream-sub",{path:z,groupId:H})}await this._flushOfflineQueue(),this.connectPromise=null,Z()}catch(J){this.connectPromise=null,$(J)}},G.onmessage=(J)=>{let z;try{z=JSON.parse(typeof J.data==="string"?J.data:J.data.toString()),this._recPush("recv",z)}catch(X){throw this._recPush("recv",J.data,!0),X}if(z.type==="welcome"){let X={protocolVersion:z.protocolVersion,serverVersion:z.serverVersion};if(this._authComplete){this.serverInfo=X;for(let Y of this._welcomeListeners)Y(this.serverInfo)}else this._pendingWelcome=X;if(z.protocolVersion!==F)console.warn(`[BodClient] Protocol mismatch: client=${F} server=${z.protocolVersion} (v${z.serverVersion})`),this.options.onVersionMismatch?.({clientProtocol:F,serverProtocol:z.protocolVersion,serverVersion:z.serverVersion});return}if(z.type==="value"){let X=new x(z.path,z.data,z.updatedAt),Y=this.valueCbs.get(z.path);if(Y)for(let M of Y)M(X);let Q=this.valueCbs.get(`${z.path}\x00shallow`);if(Q)for(let M of Q)M(X);return}if(z.type==="stream"){let X=`${z.path}:${z.groupId}`,Y=this.streamCbs.get(X);if(Y)for(let Q of Y)Q(z.events);return}if(z.type==="child"){let X={type:z.event,key:z.key,path:z.path+"/"+z.key,val:()=>z.data},Y=this.childCbs.get(z.path);if(Y)for(let M of Y)M(X);let Q=this.childCbs.get(`${z.path}\x00shallow`);if(Q)for(let M of Q)M(X);return}if(z.type==="vfs-download-chunk"){let X=this.vfsDownloadCbs.get(z.transferId);if(X)for(let Y of X)Y(z);return}let H=this.pending.get(z.id);if(H)if(this.pending.delete(z.id),z.ok)H.resolve(z);else H.reject(Error(z.error||"Unknown error"))},G.onclose=(J)=>{this._recPush("close",{code:J?.code,reason:J?.reason}),this.ws=null,this.serverInfo=null,this._pendingWelcome=null,this._authComplete=!1,this.onStatusChange?.(!1);for(let[,z]of this.pending)z.reject(Error("Connection closed"));if(this.pending.clear(),!this.closed&&this.options.reconnect)this.scheduleReconnect();if(this.connectPromise)this.connectPromise=null,$(Error(`WebSocket connection failed (${this.options.url})`))},G.onerror=()=>{this._recPush("error","ws error")}}),this.connectPromise}disconnect(){if(this.closed=!0,this.reconnectTimer)clearTimeout(this.reconnectTimer),this.reconnectTimer=null;this.ws?.close(),this.ws=null,this.pending.clear();for(let Z of this._offlineQueue)Z.reject(Error("Client disconnected"));this._offlineQueue=[]}scheduleReconnect(){if(this.closed)return;this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connect().catch(()=>{this.reconnectDelay=Math.min(this.reconnectDelay*2,this.options.maxReconnectInterval)})},this.reconnectDelay)}_enqueueWrite(Z,$){return new Promise((G,J)=>{let z=this._writeDedupKey(Z,$);if(z){let H=this._offlineQueue.findIndex((X)=>X.dedupKey===z);if(H!==-1)this._offlineQueue[H].resolve({ok:!0,data:null}),this._offlineQueue.splice(H,1)}if(this._offlineQueue.length>=this.options.offlineQueueCap)this._offlineQueue.shift().reject(Error("Offline queue full — dropped"));this._offlineQueue.push({op:Z,params:$,resolve:G,reject:J,dedupKey:z}),this.onOfflineQueue?.(this._offlineQueue.length)})}_writeDedupKey(Z,$){if(Z==="push"||Z==="batch")return null;if(Z==="update"&&$.updates)return null;let G=$.path;if(!G)return null;return`${Z}:${G}`}async _flushOfflineQueue(){if(this._offlineQueue.length===0)return;let Z=this._offlineQueue.splice(0);this.onOfflineFlush?.(Z.length);for(let $ of Z)try{let G=await this.sendRaw($.op,$.params);$.resolve(G)}catch(G){$.reject(G instanceof Error?G:Error(String(G)))}}nextId(){return String(++this.msgId)}async sendRaw(Z,$={},G=!1){if(G&&this.options.offlineQueue&&(!this.ws||this.ws.readyState!==WebSocket.OPEN)&&!this.closed)return this._enqueueWrite(Z,$);if(!this.ws||this.ws.readyState!==WebSocket.OPEN)await this.connect();return new Promise((J,z)=>{if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return z(Error("Not connected"));let H=this.nextId(),X=null,Y=()=>{if(X)clearTimeout(X),X=null};if(this.pending.set(H,{resolve:(Q)=>{Y(),J(Q)},reject:(Q)=>{Y(),z(Q)}}),this.options.requestTimeout>0)X=setTimeout(()=>{this.pending.delete(H),z(Error(`Request timeout after ${this.options.requestTimeout}ms`))},this.options.requestTimeout);this._recPush("send",{id:H,op:Z,...$}),this.ws.send(JSON.stringify({id:H,op:Z,...$}))})}async send(Z,$={},G=!1){return(await this.sendRaw(Z,$,G)).data??null}async get(Z){return this.send("get",{path:Z})}async getSnapshot(Z){let $=await this.sendRaw("get",{path:Z});return new x(Z,$.data??null,$.updatedAt)}async getShallow(Z,$,G){return this.send("get",{path:Z??"",shallow:!0,...$!==void 0?{limit:$}:{},...G!==void 0?{offset:G}:{}})}async set(Z,$,G){await this.send("set",{path:Z,value:$,...G?.ttl?{ttl:G.ttl}:{},...G?.flatten!==void 0?{flatten:G.flatten}:{}},!0)}async update(Z,$,G){await this.send("update",{path:Z,value:$,...G?.ttl?{ttl:G.ttl}:{},...G?.flatten!==void 0?{flatten:G.flatten}:{}},!0)}async updateMulti(Z){await this.send("update",{updates:Z},!0)}async delete(Z){await this.send("delete",{path:Z},!0)}async batch(Z){return this.send("batch",{operations:Z},!0)}async push(Z,$,G){return this.send("push",{path:Z,value:$,idempotencyKey:G?.idempotencyKey,ttl:G?.ttl},!0)}query(Z){return new d(this,Z)}_query(Z,$,G,J,z){return this.send("query",{path:Z,filters:$,order:G,limit:J,offset:z})}on(Z,$,G){let J=!(G?.deep??!1),z=`value${J?"-shallow":""}:${Z}`,H=J?`${Z}\x00shallow`:Z;if(!this.valueCbs.has(H))this.valueCbs.set(H,new Set);if(this.valueCbs.get(H).add($),!this.activeSubs.has(z)){if(this.activeSubs.add(z),this.ws?.readyState===WebSocket.OPEN)this.send("sub",{path:Z,event:"value",...J?{shallow:!0}:{}}).catch(()=>{})}return()=>{if(this.valueCbs.get(H)?.delete($),this.valueCbs.get(H)?.size===0){if(this.valueCbs.delete(H),this.activeSubs.delete(z),this.ws?.readyState===WebSocket.OPEN)this.send("unsub",{path:Z,event:"value",...J?{shallow:!0}:{}}).catch(()=>{})}}}onChild(Z,$,G){let J=!(G?.deep??!1),z=`child${J?"-shallow":""}:${Z}`,H=J?`${Z}\x00shallow`:Z;if(!this.childCbs.has(H))this.childCbs.set(H,new Set);if(this.childCbs.get(H).add($),!this.activeSubs.has(z)){if(this.activeSubs.add(z),this.ws?.readyState===WebSocket.OPEN)this.send("sub",{path:Z,event:"child",...J?{shallow:!0}:{}}).catch(()=>{})}return()=>{if(this.childCbs.get(H)?.delete($),this.childCbs.get(H)?.size===0){if(this.childCbs.delete(H),this.activeSubs.delete(z),this.ws?.readyState===WebSocket.OPEN)this.send("unsub",{path:Z,event:"child",...J?{shallow:!0}:{}}).catch(()=>{})}}}mq(Z){return new p(this,Z)}_mqSend(Z,$){return this.send(Z,$)}stream(Z,$){return new i(this,Z,$)}_streamOn(Z,$,G){let J=`${Z}:${$}`;if(!this.streamCbs.has(J))this.streamCbs.set(J,new Set);if(this.streamCbs.get(J).add(G),!this.activeStreamSubs.has(J)){if(this.activeStreamSubs.add(J),this.ws?.readyState===WebSocket.OPEN)this.send("stream-sub",{path:Z,groupId:$}).catch(()=>{})}return()=>{if(this.streamCbs.get(J)?.delete(G),this.streamCbs.get(J)?.size===0){if(this.streamCbs.delete(J),this.activeStreamSubs.delete(J),this.ws?.readyState===WebSocket.OPEN)this.send("stream-unsub",{path:Z,groupId:$}).catch(()=>{})}}}_streamRead(Z,$,G){return this.send("stream-read",{path:Z,groupId:$,limit:G})}_streamAck(Z,$,G){return this.send("stream-ack",{path:Z,groupId:$,key:G})}splitStreamKey(Z){let $=Z.lastIndexOf(":");return[Z.slice(0,$),Z.slice($+1)]}async search(Z){return this.send("fts-search",Z)}async index(Z,$){let G={path:Z};if(Array.isArray($))G.fields=$;else G.content=$;await this.send("fts-index",G)}async vectorSearch(Z){return this.send("vector-search",Z)}async vectorStore(Z,$){await this.send("vector-store",{path:Z,embedding:$})}async streamSnapshot(Z){return this.send("stream-snapshot",{path:Z})}async streamMaterialize(Z,$){return this.send("stream-materialize",{path:Z,...$})}async streamCompact(Z,$){return this.send("stream-compact",{path:Z,...$})}async streamReset(Z){await this.send("stream-reset",{path:Z})}get connected(){return this.ws?.readyState===WebSocket.OPEN}onStatusChange;onConnect;onDisconnect(Z){return new V1(this,Z)}reconnect(){this.closed=!1,this.connect()}_sendRaw(Z,$={}){return this.sendRaw(Z,$)}get httpUrl(){return this.options.url.replace(/^ws(s?):\/\//,"http$1://")}vfs(){return new l(this)}_send(Z,$={}){return this.send(Z,$)}_onDownloadChunk(Z,$){if(!this.vfsDownloadCbs.has(Z))this.vfsDownloadCbs.set(Z,new Set);return this.vfsDownloadCbs.get(Z).add($),()=>{if(this.vfsDownloadCbs.get(Z)?.delete($),this.vfsDownloadCbs.get(Z)?.size===0)this.vfsDownloadCbs.delete(Z)}}async _ensureDeviceKeys(){this._browserAuth??=await Promise.resolve().then(() => (y(),j1));let Z=this._browserAuth,$=this._getStorage(),G=$.get("boddb-device-pubkey");if(G){let z=$.get("boddb-device-privkey");return this._deviceFingerprint=$.get("boddb-device-fp")??null,{publicKey:G,signFn:(H)=>Z.sign(H,z)}}let J=await Z.generateKeyPair();return $.set("boddb-device-pubkey",J.publicKeyBase64),$.set("boddb-device-privkey",J.privateKeyBase64),$.set("boddb-device-fp",J.fingerprint),this._deviceFingerprint=J.fingerprint,{publicKey:J.publicKeyBase64,signFn:(z)=>Z.sign(z,J.privateKeyBase64)}}_getStorage(){if(typeof this.options.autoAuth==="object"&&this.options.autoAuth.storage)return this.options.autoAuth.storage;if(typeof localStorage<"u")return{get:(Z)=>localStorage.getItem(Z),set:(Z,$)=>localStorage.setItem(Z,$),remove:(Z)=>localStorage.removeItem(Z)};if(!this._memStorage)this._memStorage=new Map;return{get:(Z)=>this._memStorage.get(Z)??null,set:(Z,$)=>this._memStorage.set(Z,$),remove:(Z)=>this._memStorage.delete(Z)}}_memStorage=null}class c{client;constructor(Z){this.client=Z}async registerDevice(Z,$){return this.client._send("auth-register-device",{publicKey:Z,displayName:$})}async authenticate(Z,$){let G=await this.client._send("auth-challenge",{}),J=await $(G.nonce);return this.client._send("auth-verify",{publicKey:Z,signature:J,nonce:G.nonce})}async linkDevice(Z,$,G,J){return this.client._send("auth-link-device",{accountFingerprint:Z,password:$,devicePublicKey:G,deviceName:J})}async linkDeviceByName(Z,$,G,J){return this.client._send("auth-link-device",{displayName:Z,password:$,devicePublicKey:G,deviceName:J})}async revokeSession(Z){await this.client._send("auth-revoke-session",{sid:Z})}async revokeDevice(Z,$){await this.client._send("auth-revoke-device",{accountFingerprint:Z,deviceFingerprint:$})}async changePassword(Z,$,G){await this.client._send("auth-change-password",{fingerprint:Z,oldPassword:$,newPassword:G})}async createAccount(Z,$,G,J){return this.client._send("auth-create-account",{password:Z,roles:$,displayName:G,devicePublicKey:J})}async createRole(Z){await this.client._send("auth-create-role",{role:Z})}async deleteRole(Z){await this.client._send("auth-delete-role",{roleId:Z})}async updateRoles(Z,$){await this.client._send("auth-update-roles",{accountFingerprint:Z,roles:$})}async listAccounts(){return this.client._send("auth-list-accounts",{})}async listRoles(){return this.client._send("auth-list-roles",{})}async listDevices(Z){return this.client._send("auth-list-devices",{accountFingerprint:Z})}async listSessions(Z){return this.client._send("auth-list-sessions",{accountFingerprint:Z})}async requestApproval(Z){return this.client._send("auth-request-approval",{publicKey:Z})}async approveDevice(Z){return this.client._send("auth-approve-device",{requestId:Z})}async listAccountFingerprints(){return this.client._send("auth-list-account-fingerprints",{})}async hasAccounts(){return(await this.client._send("auth-has-accounts",{})).hasAccounts}async getAccountInfo(Z){return this.client._send("auth-account-info",{accountFingerprint:Z})}async pollApproval(Z){return this.client._send("auth-poll-approval",{requestId:Z})}}class x{path;data;updatedAt;constructor(Z,$,G){this.path=Z;this.data=$;this.updatedAt=G}val(){return this.data}get key(){return X1(this.path)}exists(){return this.data!==null&&this.data!==void 0}}class i{client;path;groupId;constructor(Z,$,G){this.client=Z;this.path=$;this.groupId=G}on(Z){return this.client._streamOn(this.path,this.groupId,($)=>{Z($.map((G)=>({key:G.key,val:()=>G.data})))})}async read(Z){return(await this.client._streamRead(this.path,this.groupId,Z)).map((G)=>({key:G.key,val:()=>G.data}))}async ack(Z){return this.client._streamAck(this.path,this.groupId,Z)}}class d{client;basePath;filters=[];orderClause;limitVal;offsetVal;constructor(Z,$){this.client=Z;this.basePath=$}where(Z,$,G){return this.filters.push({field:Z,op:$,value:G}),this}order(Z,$="asc"){return this.orderClause={field:Z,dir:$},this}limit(Z){return this.limitVal=Z,this}offset(Z){return this.offsetVal=Z,this}get(){return this.client._query(this.basePath,this.filters.length?this.filters:void 0,this.orderClause,this.limitVal,this.offsetVal)}}class O{key;path;deliveryCount;status;data;constructor(Z,$,G,J,z){this.key=Z;this.path=$;this.deliveryCount=G;this.status=J;this.data=z}val(){return this.data}exists(){return this.data!==null&&this.data!==void 0}}class l{client;constructor(Z){this.client=Z}async upload(Z,$,G){let J=`${this.client.httpUrl}/files/${Z}`,H=await(await fetch(J,{method:"POST",body:new Blob([$]),headers:{"Content-Type":G||"application/octet-stream"}})).json();if(!H.ok)throw Error(H.error||"Upload failed");return H.data}async download(Z){let $=`${this.client.httpUrl}/files/${Z}`,G=await fetch($);if(!G.ok)throw Error("Download failed");return new Uint8Array(await G.arrayBuffer())}async uploadWS(Z,$,G){let J=await this.client._send("vfs-upload-init",{path:Z,size:$.byteLength,mime:G}),z=f($),H=48000,X=Math.ceil(z.length/48000)||1;for(let Y=0;Y<X;Y++){let Q=z.slice(Y*48000,(Y+1)*48000);await this.client._send("vfs-upload-chunk",{transferId:J,data:Q,seq:Y})}return await this.client._send("vfs-upload-done",{transferId:J})}async downloadWS(Z){let $=await this.client._send("vfs-download-init",{path:Z}),G=[];return new Promise((J,z)=>{let H=setTimeout(()=>{X(),z(Error("Download timeout"))},30000),X=this.client._onDownloadChunk($.transferId,(Y)=>{if(G[Y.seq]=Y.data,Y.done)clearTimeout(H),X(),J(b1(G.join("")))})})}async stat(Z){return await this.client._send("vfs-stat",{path:Z})}async list(Z){return await this.client._send("vfs-list",{path:Z})}async tree(Z,$){return await this.client._send("vfs-tree",{path:Z,...$})}async delete(Z){await this.client._send("vfs-delete",{path:Z})}async mkdir(Z){return await this.client._send("vfs-mkdir",{path:Z})}async move(Z,$){return await this.client._send("vfs-move",{path:Z,dst:$})}async uploadResumable(Z,$,G){let J=G?.chunkSize||262144,z=$.byteLength,X=(await this.client._send("vfs-resumable-init",{path:Z,totalSize:z,mime:G?.mime})).sessionId,Y=0;while(Y<z){let Q=Math.min(Y+J,z),M=$.slice(Y,Q),D=f(M);Y=(await this.client._send("vfs-resumable-chunk",{sessionId:X,offset:Y,data:D})).receivedBytes,G?.onProgress?.(Y,z)}return await this.client._send("vfs-resumable-done",{sessionId:X})}async resumeUpload(Z,$,G){let J=G?.chunkSize||262144,z=await this.client._send("vfs-resumable-status",{sessionId:Z}),H=z.receivedBytes,X=z.totalSize;while(H<X){let Y=Math.min(H+J,X),Q=$.slice(H,Y),M=f(Q);H=(await this.client._send("vfs-resumable-chunk",{sessionId:Z,offset:H,data:M})).receivedBytes,G?.onProgress?.(H,X)}return await this.client._send("vfs-resumable-done",{sessionId:Z})}async getUploadStatus(Z){return await this.client._send("vfs-resumable-status",{sessionId:Z})}async updateMetadata(Z,$){return await this.client._send("vfs-update-metadata",{path:Z,...$})}async presign(Z,$){let G=$?.method||"GET",J=await this.client._send("vfs-presign",{path:Z,expiresIn:$?.expiresIn,method:G});return`${this.client.httpUrl}/files/${Z}?sig=${J.sig}&exp=${J.exp}`}}class p{client;queue;constructor(Z,$){this.client=Z;this.queue=$}async push(Z,$){return this.client._mqSend("mq-push",{path:this.queue,value:Z,idempotencyKey:$?.idempotencyKey})}async fetch(Z){return(await this.client._mqSend("mq-fetch",{path:this.queue,count:Z})).map((G)=>new O(G.key,G.path,G.deliveryCount,G.status,G.data))}async ack(Z){await this.client._mqSend("mq-ack",{path:this.queue,key:Z})}async nack(Z){await this.client._mqSend("mq-nack",{path:this.queue,key:Z})}async peek(Z){return(await this.client._mqSend("mq-peek",{path:this.queue,count:Z})).map((G)=>new O(G.key,G.path,G.deliveryCount,G.status,G.data))}async dlq(){return(await this.client._mqSend("mq-dlq",{path:this.queue})).map(($)=>new O($.key,$.path,$.deliveryCount,$.status,$.data))}async purge(Z){return this.client._mqSend("mq-purge",{path:this.queue,all:Z?.all})}}class V1{client;path;constructor(Z,$){this.client=Z;this.path=$}async set(Z){await this.client._send("on-disconnect-set",{path:this.path,value:Z})}async update(Z){await this.client._send("on-disconnect-update",{path:this.path,value:Z})}async delete(){await this.client._send("on-disconnect-delete",{path:this.path})}async cancel(){await this.client._send("on-disconnect-cancel",{path:this.path})}}y();function n1(Z){let $=2166136261;for(let G=0;G<Z.length;G++)$^=Z.charCodeAt(G),$=$+(($<<1)+($<<4)+($<<7)+($<<8)+($<<24))>>>0;return $>>>0}function q1(Z,$,G){return n1(`${Z}::${$??G}`)%1e4}function u1(Z){return Z.sticky??Z.userId??Z.accountId??""}function y1(Z,$,G){if(!Z.variants||Z.variants.length===0)return null;let J=Z.variants.reduce((X,Y)=>X+Y.weight,0);if(J<=0)return null;let z=q1($,Z.salt,G)%J,H=0;for(let X of Z.variants)if(H+=X.weight,z<H)return{variantKey:X.key};return{variantKey:Z.variants[Z.variants.length-1].key}}function o(Z,$){let G=Z.variants?.find((J)=>J.key===$);return G?G.value:Z.defaultValue}function f1(Z,$){if(Z.emails?.length&&$.email){let G=$.email.toLowerCase();if(Z.emails.some((J)=>J.toLowerCase()===G))return"email"}if(Z.tags?.length&&$.tags?.length){let G=new Set($.tags);if(Z.tags.some((J)=>G.has(J)))return"tag"}return null}function h1(Z,$){if($.variant)return{value:o(Z,$.variant),variant:$.variant};if($.value!==void 0){if(Z.kind==="variant"&&typeof $.value==="string")return{value:o(Z,$.value),variant:$.value};return{value:$.value}}if(Z.kind==="boolean")return{value:!0};let G=Z.variants?.[0];return G?{value:G.value,variant:G.key}:{value:Z.defaultValue}}function k(Z,$,G){let J=Z?.key??$?.key??"";if(G.cookieOverrides&&J in G.cookieOverrides)return{key:J,value:G.cookieOverrides[J],reason:"cookie_override"};if(!Z)return{key:J,value:void 0,reason:"unregistered"};if($&&$.enabled===!1)return{key:J,value:Z.defaultValue,reason:"kill_switch"};let z=$&&(!$.branch||$.branch===G.branch);if(z&&$.targeting){let H=f1($.targeting,G);if(H){let{value:X,variant:Y}=h1(Z,$.targeting);return{key:J,value:X,...Y?{variant:Y}:{},reason:H==="email"?"targeting_email":"targeting_tag"}}}if(z&&$.value!==void 0)return{key:J,value:$.value,reason:"override_value"};if(z&&$.rollout){let H=u1(G);if(Z.kind==="variant"&&$.rollout.variants?.length){let X=y1($.rollout,H,Z.key);if(X)return{key:J,value:o(Z,X.variantKey),variant:X.variantKey,reason:"rollout"}}else if(Z.kind==="boolean"){let X=q1(H,$.rollout.salt,Z.key),Y=Math.max(0,Math.min(1e4,Math.round($.rollout.percent*100)));return{key:J,value:X<Y,reason:"rollout"}}}return{key:J,value:Z.defaultValue,reason:"default",...Z.kind==="variant"&&typeof Z.defaultValue==="string"?{variant:Z.defaultValue}:{}}}var m=[],L=null,r=null,F1="bodify_outbox",c1=100,N1=!1;function $1(){try{return JSON.parse(localStorage.getItem(F1)||"[]")}catch{return[]}}function G1(Z){try{localStorage.setItem(F1,JSON.stringify(Z.slice(-c1)))}catch{}}function s(Z){let $=$1();$.push(Z),G1($)}async function D1(){if(typeof navigator<"u"&&navigator.onLine===!1)return;let Z=$1();if(!Z.length)return;G1([]);let $=[];for(let G of Z)try{if(!(await fetch(G.url,{method:"POST",headers:G.headers,body:G.body,keepalive:!0})).ok)$.push(G)}catch{$.push(G)}if($.length)G1([...$1(),...$])}function O1(Z,$,G,J){let z=typeof navigator<"u"&&navigator.onLine===!1;if(!z&&J&&typeof navigator<"u"&&navigator.sendBeacon){if(navigator.sendBeacon(Z,new Blob([$],{type:"application/json"})))return}if(z){s({url:Z,body:$,headers:G});return}fetch(Z,{method:"POST",headers:G,body:$,keepalive:!0}).then((H)=>{if(!H.ok)s({url:Z,body:$,headers:G})}).catch(()=>s({url:Z,body:$,headers:G}))}var q=new Map,w=new Map,N=new Set,j=null,_=null,J1=null,U1=new Map,i1=60000,b="bodify.flags.override",R1="bodify_anon_id",t="bodify_session_id",d1=1800000,C=!1,A,z1,S,v=[],H1=null,B=[],V={};function C1(){return crypto.randomUUID?.()??Math.random().toString(36).slice(2)+Date.now().toString(36)}function l1(){try{let $=localStorage.getItem(R1);if($)return $}catch{}let Z=C1();try{localStorage.setItem(R1,Z)}catch{}return Z}var S1="bodify_anon_uid";function p1(){try{let G=localStorage.getItem(S1);if(G)return G}catch{}let $="anon_"+(crypto.randomUUID?.().replace(/-/g,"")??Math.random().toString(16).slice(2)+Date.now().toString(16)).slice(0,32);try{localStorage.setItem(S1,$)}catch{}return $}var a=null,e=null;function w1(Z){if(L)L.userId=Z;for(let $ of N)$()}function g1(){try{let $=sessionStorage.getItem(t);if($){let{id:G,ts:J}=JSON.parse($);if(Date.now()-J<d1)return sessionStorage.setItem(t,JSON.stringify({id:G,ts:Date.now()})),G}}catch{}let Z=C1();try{sessionStorage.setItem(t,JSON.stringify({id:Z,ts:Date.now()}))}catch{}return Z}function K1(){if(!L)return"";return`${L.ingestUrl.replace(/\/apps\/[^/]+\/ingest$/,"")}/analytics/${L.appId}`}function g(Z,$,G){let J=Object.keys(V).length?{...V,...G}:G;return{anonymousId:S,sessionId:g1(),userId:z1,name:Z,type:$,properties:J,source:{url:location.href,referrer:document.referrer||void 0,userAgent:navigator.userAgent},ts:Date.now()}}function K(){if(v.length===0)return;let Z=v.splice(0),$=`${K1()}/events`,G=JSON.stringify({events:Z}),J={"Content-Type":"application/json"};if(A)J["x-analytics-token"]=A;O1($,G,J,!A)}function E(Z){if(v.push(Z),v.length>=10)K()}function o1(Z){let $=typeof Z.analytics==="object"?Z.analytics:{};if(C=!0,A=$.secret,S=l1(),H1=setInterval(K,5000),!$.disableAutoPageViews){let X=()=>E(g("$pageview","page_view",{path:location.pathname,title:document.title}));X();let Y=history.pushState.bind(history),Q=history.replaceState.bind(history);history.pushState=function(...D){Y(...D),X()},history.replaceState=function(...D){Q(...D),X()};let M=()=>X();window.addEventListener("popstate",M),B.push(()=>{history.pushState=Y,history.replaceState=Q,window.removeEventListener("popstate",M)})}let G=(X)=>E(g("$error","error",{message:X.message,filename:X.filename,line:X.lineno,col:X.colno,stack:X.error?.stack})),J=(X)=>{let Y=X.reason instanceof Error?X.reason:Error(String(X.reason));E(g("$error","error",{message:Y.message,stack:Y.stack}))};window.addEventListener("error",G),window.addEventListener("unhandledrejection",J),B.push(()=>{window.removeEventListener("error",G),window.removeEventListener("unhandledrejection",J)});let z=()=>{if(document.visibilityState==="hidden")K()},H=()=>K();document.addEventListener("visibilitychange",z),window.addEventListener("beforeunload",H),B.push(()=>{document.removeEventListener("visibilitychange",z),window.removeEventListener("beforeunload",H)})}function r1(){if(typeof document>"u")return;let Z=document.cookie.split(";").map(($)=>$.trim()).find(($)=>$.startsWith(`${b}=`));if(!Z)return;try{let $=decodeURIComponent(Z.slice(b.length+1));return JSON.parse($).flags}catch{return}}function s1(Z){if(!Z)return;for(let $ of Z.definitions??[])if($?.key)q.set($.key,$);for(let $ of Z.overrides??[])if($?.key)w.set($.key,$)}function t1(Z){try{let $=new URL(Z,typeof location<"u"?location.href:void 0);return`${$.protocol==="https:"?"wss:":"ws:"}//${$.host}/db`}catch{return null}}function E1(){if(j)return j;if(!L)throw Error("Bodify SDK not initialized");let Z=t1(L.ingestUrl);if(!Z)throw Error("Cannot derive DB WS URL from ingestUrl");return j=new I({url:Z,reconnect:!0,offlineQueue:!0,offlineQueueCap:100,auth:()=>W.auth._token??""}),j.connect().catch(()=>{}),j}function a1(){if(_||!L)return;let Z;try{Z=E1()}catch{return}let $=L.appId,G=`flags/${$}/definitions`,J=`flags/${$}/overrides`;_=Z.on(G,(z)=>{let H=z.val();if(!H&&q.size>0)return;let X=new Map;if(H){for(let Y of Object.values(H))if(Y?.key)X.set(Y.key,Y)}q=X;for(let Y of N)Y(void 0)},{deep:!0}),J1=Z.on(J,(z)=>{let H=z.val();if(!H&&w.size>0)return;let X=new Map;if(H){for(let Y of Object.values(H))if(Y?.key)X.set(Y.key,Y)}w=X;for(let Y of N)Y(void 0)},{deep:!0})}function e1(){_?.(),J1?.(),_=null,J1=null}function Z1(Z){return{userId:Z?.userId??L?.userId,accountId:Z?.accountId,email:Z?.email??L?.email,tags:Z?.tags??L?.tags,branch:Z?.branch??L?.branch,sticky:Z?.sticky,cookieOverrides:r1()}}function A1(Z,$,G,J,z){if(!L)return;let H=z.sticky??z.userId??z.accountId??"",X=`${Z}::${$??String(G)}::${H}`,Y=Date.now(),Q=U1.get(X);if(Q&&Y-Q<i1)return;U1.set(X,Y),T({kind:"event",event:"flag.exposure",message:`flag.exposure ${Z}=${$??String(G)}`,meta:{flagKey:Z,value:G,variant:$,reason:J,userId:z.userId,branch:z.branch}})}function R(){if(!L||m.length===0)return;let Z=m.splice(0),$={"Content-Type":"application/json"};if(L.apiKey)$.Authorization=`Bearer ${L.apiKey}`;let G=JSON.stringify({signals:Z});O1(L.ingestUrl,G,$,!L.apiKey)}function ZZ(Z){if(m.push(Z),L&&m.length>=(L.maxBatchSize??20))R()}function T(Z){ZZ({kind:Z.kind,level:Z.level??"info",source:"sdk",message:Z.message,ts:Date.now(),deployId:L?.deployId,event:Z.event,metric:Z.metric,value:Z.value,unit:Z.unit,meta:{...L?.userId?{userId:L.userId}:{},...Z.meta}})}var W={init(Z){L=Z;let $={errors:!0,rejections:!0,console:!1,...Z.capture};if(r=setInterval(R,Z.flushIntervalMs??2000),$.errors)window.addEventListener("error",(G)=>{T({kind:"log",level:"error",message:G.message||"Unknown error",meta:{filename:G.filename,lineno:G.lineno,colno:G.colno,stack:G.error?.stack}})});if($.rejections)window.addEventListener("unhandledrejection",(G)=>{let J=G.reason instanceof Error?G.reason:Error(String(G.reason));T({kind:"log",level:"error",message:J.message,meta:{stack:J.stack}})});if(document.addEventListener("visibilitychange",()=>{if(document.visibilityState==="hidden")R()}),window.addEventListener("beforeunload",R),W.auth.restore(),s1(Z.flags),a1(),!N1&&typeof window<"u")window.addEventListener("online",()=>{D1()}),N1=!0;if(D1(),Z.analytics!==!1&&!$Z(Z.ingestUrl))o1(Z)},event(Z,$){let G=C?{anonymousId:S,sessionId:g1(),userId:z1,...V,...$}:{...V,...$};T({kind:"event",message:Z,event:Z,meta:G})},metric(Z,$,G){let{unit:J,...z}=G??{};T({kind:"metric",message:`${Z}=${$}`,metric:Z,value:$,unit:J,meta:Object.keys(z).length>0?z:void 0})},log:{debug:(Z,$)=>T({kind:"log",level:"debug",message:Z,meta:$}),info:(Z,$)=>T({kind:"log",level:"info",message:Z,meta:$}),warn:(Z,$)=>T({kind:"log",level:"warn",message:Z,meta:$}),error:(Z,$)=>T({kind:"log",level:"error",message:Z,meta:$})},leads:{async collect(Z){if(!L)throw Error("Bodify SDK not initialized");let G=`${L.ingestUrl.replace(/\/apps\/[^/]+\/ingest$/,"")}/leads/${L.appId}/collect`,J={"Content-Type":"application/json"};if(L.apiKey)J.Authorization=`Bearer ${L.apiKey}`;let z=await fetch(G,{method:"POST",headers:J,body:JSON.stringify(Z)});if(!z.ok)throw Error(`Leads collect failed: ${z.status}`);return z.json()}},storage:{_baseUrl(){if(!L)throw Error("Bodify SDK not initialized");return L.ingestUrl.replace(/\/apps\/[^/]+\/ingest$/,"")+`/apps/${L.appId}/storage`},_headers(){let Z={"Content-Type":"application/json"};if(L?.apiKey)Z.Authorization=`Bearer ${L.apiKey}`;return Z},async upload(Z,$){let G=W.storage._baseUrl(),J=$?.path??Z.name,z=await fetch(`${G}/upload`,{method:"POST",headers:W.storage._headers(),body:JSON.stringify({path:J,contentType:Z.type||"application/octet-stream",size:Z.size,public:$?.public})});if(!z.ok)throw Error(`Upload init failed: ${z.status}`);let H=await z.json();if(H.uploadUrl){let Y=await fetch(H.uploadUrl,{method:"PUT",body:Z,headers:{"Content-Type":Z.type||"application/octet-stream"}});if(!Y.ok)throw Error(`Upload to storage failed: ${Y.status}`)}else{let Y=await fetch(`${G}/upload/${H.fileId}?sessionId=${H.sessionId}`,{method:"PUT",body:Z,headers:{...W.storage._headers(),"Content-Type":Z.type||"application/octet-stream"}});if(!Y.ok)throw Error(`Local upload failed: ${Y.status}`)}let X=await fetch(`${G}/upload/${H.fileId}/finalize`,{method:"POST",headers:W.storage._headers(),body:JSON.stringify({sessionId:H.sessionId})});if(!X.ok)throw Error(`Finalize failed: ${X.status}`);return await X.json().catch(()=>({})),{fileId:H.fileId}},async getUrl(Z){let $=await fetch(`${W.storage._baseUrl()}/files/${Z}/url`,{headers:W.storage._headers()});if(!$.ok)throw Error(`Get URL failed: ${$.status}`);return(await $.json()).url},async delete(Z){let $=await fetch(`${W.storage._baseUrl()}/files/${Z}`,{method:"DELETE",headers:W.storage._headers()});if(!$.ok)throw Error(`Delete failed: ${$.status}`)},async list(Z){let $=new URLSearchParams;if(Z?.prefix)$.set("prefix",Z.prefix);if(Z?.limit)$.set("limit",String(Z.limit));let G=await fetch(`${W.storage._baseUrl()}/files?${$}`,{headers:W.storage._headers()});if(!G.ok)throw Error(`List failed: ${G.status}`);return G.json()},publicUrl(Z){if(!L)throw Error("Bodify SDK not initialized");return`${L.ingestUrl.replace(/\/apps\/[^/]+\/ingest$/,"")}/apps/${L.appId}/storage/public/${Z}`}},auth:{_token:null,_user:null,_pendingVerification:null,_listeners:[],_baseUrl(){if(!L)throw Error("Bodify SDK not initialized");return L.ingestUrl.replace(/\/apps\/[^/]+\/ingest$/,"")+`/apps/${L.appId}/auth`},async _fetch(Z,$){let G={"Content-Type":"application/json",...$?.headers};if(W.auth._token)G.Authorization=`Bearer ${W.auth._token}`;return fetch(`${W.auth._baseUrl()}${Z}`,{...$,headers:G})},_setToken(Z){if(W.auth._token=Z,Z)localStorage.setItem("bodify_auth_token",Z);else localStorage.removeItem("bodify_auth_token")},_notify(){W.auth._listeners.forEach((Z)=>Z(W.auth._user,W.auth._pendingVerification))},_handleAuthResponse(Z){if(W.auth._setToken(Z.token),Z.emailVerificationRequired)W.auth._user=null,W.auth._pendingVerification=Z.user;else W.auth._user=Z.user,W.auth._pendingVerification=null;W.auth._notify()},async signUp(Z){let $=await W.auth._fetch("/signup",{method:"POST",body:JSON.stringify(Z)});if(!$.ok){let J=await $.json().catch(()=>({}));throw Error(J.error??`Signup failed: ${$.status}`)}let G=await $.json();return W.auth._handleAuthResponse(G),G},async signIn(Z){let $=await W.auth._fetch("/login",{method:"POST",body:JSON.stringify(Z)});if(!$.ok){let J=await $.json().catch(()=>({}));throw Error(J.error??`Login failed: ${$.status}`)}let G=await $.json();return W.auth._handleAuthResponse(G),G},signInWithOAuth(Z){window.location.href=`${W.auth._baseUrl()}/oauth/${Z}`},adoptAnonIdentity(){if(W.auth._user?.isAnonymous)return W.auth._user.id;let Z=p1();if(!W.auth._user)W.auth._user={id:Z,isAnonymous:!0},w1(Z),W.auth._notify();return Z},whenTokenReady(){if(W.auth._token)return Promise.resolve();return a??Promise.resolve()},async signInAnonymously(){let Z=W.auth.adoptAnonIdentity();if(!W.auth._token&&!a)a=new Promise((J)=>{e=J});let $=await W.auth._fetch("/anonymous",{method:"POST",body:JSON.stringify({uid:Z})});if(!$.ok){let J=await $.json().catch(()=>({}));throw Error(J.error??`Anonymous signin failed: ${$.status}`)}let G=await $.json();return W.auth._setToken(G.token),W.auth._user=G.user,W.auth._pendingVerification=null,w1(G.user.id),W.auth._notify(),e?.(),e=null,G},async attachEmail(Z){let $=await W.auth._fetch("/email/attach",{method:"POST",body:JSON.stringify({email:Z})});if(!$.ok){let J=await $.json().catch(()=>({}));throw Error(J.error??"Attach failed")}let{user:G}=await $.json();return W.auth._user=G,W.auth._notify(),G},async linkEmail(Z,$){let G=await W.auth._fetch("/link",{method:"POST",body:JSON.stringify({provider:"email",email:Z,password:$})});if(!G.ok){let z=await G.json().catch(()=>({}));throw Error(z.error??"Link failed")}let{user:J}=await G.json();return W.auth._user=J,W.auth._notify(),J},async linkPhone(Z,$){let G=await W.auth._fetch("/link",{method:"POST",body:JSON.stringify({provider:"phone",phone:Z,otp:$})});if(!G.ok){let z=await G.json().catch(()=>({}));throw Error(z.error??"Link failed")}let{user:J}=await G.json();return W.auth._user=J,W.auth._notify(),J},async startPhoneSignIn(Z){let $=await W.auth._fetch("/phone/start",{method:"POST",body:JSON.stringify({phone:Z})});if(!$.ok){let G=await $.json().catch(()=>({}));throw Error(G.error??"Failed to send OTP")}return $.json()},async linkOAuth(Z){let $=await W.auth._fetch(`/link-oauth/${Z}`,{method:"POST"});if(!$.ok){let J=await $.json().catch(()=>({}));throw Error(J.error??"Link failed")}let{redirectUrl:G}=await $.json();window.location.href=G},async mergeFromAnonymous(Z){let $=await W.auth._fetch("/merge",{method:"POST",body:JSON.stringify({sourceId:Z})});if(!$.ok){let G=await $.json().catch(()=>({}));throw Error(G.error??"Merge failed")}return $.json()},async listAudit(){let Z=await W.auth._fetch("/audit");if(!Z.ok)throw Error("Audit list failed");return Z.json()},async signInWithPhone(Z,$){let G=await W.auth._fetch("/phone/verify",{method:"POST",body:JSON.stringify({phone:Z,code:$})});if(!G.ok){let z=await G.json().catch(()=>({}));throw Error(z.error??"Phone verify failed")}let J=await G.json();return W.auth._setToken(J.token),W.auth._user=J.user,W.auth._pendingVerification=null,W.auth._notify(),J},async signOut(){await W.auth._fetch("/logout",{method:"POST"}).catch(()=>{}),W.auth._setToken(null),W.auth._user=null,W.auth._pendingVerification=null,W.auth._notify()},async verifyEmail(Z){let $=await W.auth._fetch("/verify-email",{method:"POST",body:JSON.stringify({code:Z})});if(!$.ok){let J=await $.json().catch(()=>({}));throw Error(J.error??"Verification failed")}let G=await $.json();return W.auth._setToken(G.token),W.auth._user=G.user,W.auth._pendingVerification=null,W.auth._notify(),G},async resendVerification(){let Z=await W.auth._fetch("/resend-verification",{method:"POST"});if(!Z.ok){let $=await Z.json().catch(()=>({}));throw Error($.error??"Resend failed")}},async signInWithMagicLink(Z){let $=await W.auth._fetch("/magic-link/verify",{method:"POST",body:JSON.stringify({token:Z})});if(!$.ok){let J=await $.json().catch(()=>({}));throw Error(J.error??"Invalid or expired link")}let G=await $.json();return W.auth._setToken(G.token),W.auth._user=G.user,W.auth._pendingVerification=null,W.auth._notify(),G},async getProviders(){return(await fetch(`${W.auth._baseUrl()}/providers`)).json()},async getUser(){if(!W.auth._token)return null;let Z=3;for(let $=0;$<Z;$++){let G=null;try{G=await W.auth._fetch("/me")}catch{}if(G){if(G.ok){let J=await G.json();return W.auth._user=J,J}if(G.status===401)return W.auth._user=null,null}if($<Z-1)await new Promise((J)=>setTimeout(J,400*($+1)))}return W.auth._user},async updateProfile(Z){let $=await W.auth._fetch("/me",{method:"PATCH",body:JSON.stringify(Z)});if(!$.ok)throw Error("Update failed");let G=await $.json();return W.auth._user=G,W.auth._notify(),G},onAuthStateChange(Z){return W.auth._listeners.push(Z),()=>{W.auth._listeners=W.auth._listeners.filter(($)=>$!==Z)}},restore(){let Z=localStorage.getItem("bodify_auth_token");if(Z)W.auth._token=Z}},flags:{get(Z,$){let G=Z1($),J=q.get(Z),z=w.get(Z),H=k(J,z,G);return A1(Z,H.variant,H.value,H.reason,G),H.value},isEnabled(Z,$){return W.flags.get(Z,$)===!0},variant(Z,$){let G=Z1($),J=q.get(Z),z=w.get(Z),H=k(J,z,G);return A1(Z,H.variant,H.value,H.reason,G),H.variant??""},all(Z){let $=Z1(Z),G={};for(let[J,z]of q){let H=w.get(J),X=k(z,H,$);G[J]=X.value}return G},subscribe(Z){return N.add(Z),()=>N.delete(Z)},keys(){return[...q.keys()].sort()},setCookieOverride(Z,$){if(typeof document>"u")return;let G=encodeURIComponent(JSON.stringify({flags:Z})),J=$?.maxAgeSec??86400;document.cookie=`${b}=${G}; path=/; max-age=${J}; samesite=lax`;for(let z of N)z()},clearCookieOverride(){if(typeof document>"u")return;document.cookie=`${b}=; path=/; max-age=0`;for(let Z of N)Z()}},analytics:{identify(Z,$){if(z1=Z||void 0,!C||!S)return;let G=`${K1()}/identify`,J={"Content-Type":"application/json"};if(A)J["x-analytics-token"]=A;fetch(G,{method:"POST",headers:J,body:JSON.stringify({anonymousId:S,userId:Z,traits:$}),keepalive:!0}).catch(()=>{})},track(Z,$){if(!C)return;E(g(Z,"custom",$))},page(Z){if(!C)return;E(g("$pageview","page_view",{path:location.pathname,title:document.title,...Z}))},getAnonymousId(){return S??""},register(Z){V={...V,...Z}},unregister(...Z){for(let $ of Z)delete V[$]}},get db(){return E1()},flush:R,destroy(){if(r)clearInterval(r);if(H1)clearInterval(H1);B.forEach((Z)=>Z()),K(),e1(),j?.disconnect(),j=null,R()}};function $Z(Z){try{let $=new URL(Z,typeof location<"u"?location.href:void 0).hostname;return $==="localhost"||$==="0.0.0.0"||$==="::1"||$==="[::1]"||$.endsWith(".local")||/^127\./.test($)||/^10\./.test($)||/^192\.168\./.test($)||/^172\.(1[6-9]|2\d|3[01])\./.test($)||/^169\.254\./.test($)}catch{return!1}}function GZ(Z,$){let G=typeof location<"u"?location.origin:"";try{if(Z?.src){let J=new URL(Z.src,typeof location<"u"?location.href:void 0);if(J.protocol==="http:"||J.protocol==="https:")G=J.origin}}catch{}return`${G}/api/apps/${$}/ingest`}if(typeof window<"u"){let Z=window.__BODIFY_CONFIG__;if(Z)W.init(Z);else{let $=document.currentScript;if($?.dataset.appId){let G=window.__BODIFY_FLAGS__;W.init({appId:$.dataset.appId,ingestUrl:$.dataset.ingestUrl||GZ($,$.dataset.appId),apiKey:$.dataset.apiKey,deployId:$.dataset.deployId,branch:$.dataset.branch,userId:$.dataset.userId,flags:G,analytics:$.dataset.analytics==="false"?!1:!0})}}}window.Bodify=W;