var x1=Object.defineProperty;var I1=(Z)=>Z;function k1(Z,$){this[Z]=I1.bind(null,$)}var B1=(Z,$)=>{for(var G in $)x1(Z,G,{get:$[G],enumerable:!0,configurable:!0,set:k1.bind($,G)})};var W1=(Z,$)=>()=>(Z&&($=Z(Z=0)),$);var Y1=()=>{};var j1={};B1(j1,{wrapPublicKey:()=>n,unwrapPublicKey:()=>b1,sign:()=>M1,generateKeyPair:()=>T1,browserFingerprint:()=>u});function m1(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 L1(Z){let $=atob(Z),G=new Uint8Array($.length);for(let J=0;J<$.length;J++)G[J]=$.charCodeAt(J);return G}function _1(Z){return Array.from(Z).map(($)=>$.toString(16).padStart(2,"0")).join("")}function n(Z){return m1(Q1,Z)}function b1(Z){return Z.slice(Q1.length)}async function T1(){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 M1(Z,$){let G=L1($),J=new TextEncoder().encode(Z),z=await(void 0)(J,G);return P(z)}async function u(Z){let $=L1(Z),G=new ArrayBuffer($.byteLength);new Uint8Array(G).set($);let J=await crypto.subtle.digest("SHA-256",G);return _1(new Uint8Array(J))}var Q1,LZ;var y=W1(()=>{Y1();Q1=new Uint8Array([48,42,48,5,6,3,43,101,112,3,33,0]),LZ=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 v1(Z){let $=atob(Z),G=new Uint8Array($.length);for(let J=0;J<$.length;J++)G[J]=$.charCodeAt(J);return G}function n1(){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=n1();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 i(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),L=X.endsWith("-shallow"),T=L?X.slice(0,-8):X;return{path:Y,event:T,...L?{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 T of Y)T(X);let L=this.valueCbs.get(`${z.path}\x00shallow`);if(L)for(let T of L)T(X);return}if(z.type==="stream"){let X=`${z.path}:${z.groupId}`,Y=this.streamCbs.get(X);if(Y)for(let L of Y)L(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 T of Y)T(X);let L=this.childCbs.get(`${z.path}\x00shallow`);if(L)for(let T of L)T(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:(L)=>{Y(),J(L)},reject:(L)=>{Y(),z(L)}}),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 l(this,Z)}_mqSend(Z,$){return this.send(Z,$)}stream(Z,$){return new c(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 p(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 i{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 c{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 p{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 L=z.slice(Y*48000,(Y+1)*48000);await this.client._send("vfs-upload-chunk",{transferId:J,data:L,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(v1(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 L=Math.min(Y+J,z),T=$.slice(Y,L),U=f(T);Y=(await this.client._send("vfs-resumable-chunk",{sessionId:X,offset:Y,data:U})).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),L=$.slice(H,Y),T=f(L);H=(await this.client._send("vfs-resumable-chunk",{sessionId:Z,offset:H,data:T})).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 l{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 u1(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 u1(`${Z}::${$??G}`)%1e4}function y1(Z){return Z.sticky??Z.userId??Z.accountId??""}function f1(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 h1(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 i1(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=h1($.targeting,G);if(H){let{value:X,variant:Y}=i1(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=y1(G);if(Z.kind==="variant"&&$.rollout.variants?.length){let X=f1($.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=[],Q=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 N=new Map,w=new Map,D=new Set,V=null,_=null,J1=null,U1=new Map,d1=60000,b="bodify.flags.override",R1="bodify_anon_id",t="bodify_session_id",p1=1800000,C=!1,A,z1,j,v=[],H1=null,B=[],q={};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 o1(){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(Q)Q.userId=Z;for(let $ of D)$()}function g1(){try{let $=sessionStorage.getItem(t);if($){let{id:G,ts:J}=JSON.parse($);if(Date.now()-J<p1)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(!Q)return"";return`${Q.ingestUrl.replace(/\/apps\/[^/]+\/ingest$/,"")}/analytics/${Q.appId}`}function g(Z,$,G){let J=Object.keys(q).length?{...q,...G}:G;return{anonymousId:j,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 r1(Z){let $=typeof Z.analytics==="object"?Z.analytics:{};if(C=!0,A=$.secret,j=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),L=history.replaceState.bind(history);history.pushState=function(...U){Y(...U),X()},history.replaceState=function(...U){L(...U),X()};let T=()=>X();window.addEventListener("popstate",T),B.push(()=>{history.pushState=Y,history.replaceState=L,window.removeEventListener("popstate",T)})}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 s1(){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 t1(Z){if(!Z)return;for(let $ of Z.definitions??[])if($?.key)N.set($.key,$);for(let $ of Z.overrides??[])if($?.key)w.set($.key,$)}function a1(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(V)return V;if(!Q)throw Error("Bodify SDK not initialized");let Z=a1(Q.ingestUrl);if(!Z)throw Error("Cannot derive DB WS URL from ingestUrl");return V=new I({url:Z,reconnect:!0,offlineQueue:!0,offlineQueueCap:100,auth:()=>W.auth._token??""}),V.connect().catch(()=>{}),V}function e1(){if(_||!Q)return;let Z;try{Z=E1()}catch{return}let $=Q.appId,G=`flags/${$}/definitions`,J=`flags/${$}/overrides`;_=Z.on(G,(z)=>{let H=z.val();if(!H&&N.size>0)return;let X=new Map;if(H){for(let Y of Object.values(H))if(Y?.key)X.set(Y.key,Y)}N=X;for(let Y of D)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 D)Y(void 0)},{deep:!0})}function ZZ(){_?.(),J1?.(),_=null,J1=null}function Z1(Z){return{userId:Z?.userId??Q?.userId,accountId:Z?.accountId,email:Z?.email??Q?.email,tags:Z?.tags??Q?.tags,branch:Z?.branch??Q?.branch,sticky:Z?.sticky,cookieOverrides:s1()}}function A1(Z,$,G,J,z){if(!Q)return;let H=z.sticky??z.userId??z.accountId??"",X=`${Z}::${$??String(G)}::${H}`,Y=Date.now(),L=U1.get(X);if(L&&Y-L<d1)return;U1.set(X,Y),M({kind:"event",event:"flag.exposure",message:`flag.exposure ${Z}=${$??String(G)}`,meta:{flagKey:Z,value:G,variant:$,reason:J,branch:z.branch,...j?{anonymousId:j}:{},...z.userId?{userId:z.userId}:{}}})}function S(){if(!Q||m.length===0)return;let Z=m.splice(0),$={"Content-Type":"application/json"};if(Q.apiKey)$.Authorization=`Bearer ${Q.apiKey}`;let G=JSON.stringify({signals:Z});O1(Q.ingestUrl,G,$,!Q.apiKey)}function $Z(Z){if(m.push(Z),Q&&m.length>=(Q.maxBatchSize??20))S()}function M(Z){$Z({kind:Z.kind,level:Z.level??"info",source:"sdk",message:Z.message,ts:Date.now(),deployId:Q?.deployId,event:Z.event,metric:Z.metric,value:Z.value,unit:Z.unit,meta:{...Q?.userId?{userId:Q.userId}:{},...Z.meta}})}var W={init(Z){Q=Z;let $={errors:!0,rejections:!0,console:!1,...Z.capture};if(r=setInterval(S,Z.flushIntervalMs??2000),$.errors)window.addEventListener("error",(G)=>{M({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));M({kind:"log",level:"error",message:J.message,meta:{stack:J.stack}})});if(document.addEventListener("visibilitychange",()=>{if(document.visibilityState==="hidden")S()}),window.addEventListener("beforeunload",S),W.auth.restore(),t1(Z.flags),e1(),!N1&&typeof window<"u")window.addEventListener("online",()=>{D1()}),N1=!0;if(D1(),Z.analytics!==!1&&!GZ(Z.ingestUrl)&&!zZ())r1(Z)},event(Z,$){let G=C?{anonymousId:j,sessionId:g1(),userId:z1,...q,...$}:{...q,...$};M({kind:"event",message:Z,event:Z,meta:G})},metric(Z,$,G){let{unit:J,...z}=G??{};M({kind:"metric",message:`${Z}=${$}`,metric:Z,value:$,unit:J,meta:Object.keys(z).length>0?z:void 0})},log:{debug:(Z,$)=>M({kind:"log",level:"debug",message:Z,meta:$}),info:(Z,$)=>M({kind:"log",level:"info",message:Z,meta:$}),warn:(Z,$)=>M({kind:"log",level:"warn",message:Z,meta:$}),error:(Z,$)=>M({kind:"log",level:"error",message:Z,meta:$})},leads:{async collect(Z){if(!Q)throw Error("Bodify SDK not initialized");let G=`${Q.ingestUrl.replace(/\/apps\/[^/]+\/ingest$/,"")}/leads/${Q.appId}/collect`,J={"Content-Type":"application/json"};if(Q.apiKey)J.Authorization=`Bearer ${Q.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(!Q)throw Error("Bodify SDK not initialized");return Q.ingestUrl.replace(/\/apps\/[^/]+\/ingest$/,"")+`/apps/${Q.appId}/storage`},_headers(){let Z={"Content-Type":"application/json"};if(Q?.apiKey)Z.Authorization=`Bearer ${Q.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(!Q)throw Error("Bodify SDK not initialized");return`${Q.ingestUrl.replace(/\/apps\/[^/]+\/ingest$/,"")}/apps/${Q.appId}/storage/public/${Z}`}},auth:{_token:null,_user:null,_pendingVerification:null,_listeners:[],_baseUrl(){if(!Q)throw Error("Bodify SDK not initialized");return Q.ingestUrl.replace(/\/apps\/[^/]+\/ingest$/,"")+`/apps/${Q.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=o1();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=N.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=N.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 N){let H=w.get(J),X=k(z,H,$);G[J]=X.value}return G},subscribe(Z){return D.add(Z),()=>D.delete(Z)},keys(){return[...N.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 D)z()},clearCookieOverride(){if(typeof document>"u")return;document.cookie=`${b}=; path=/; max-age=0`;for(let Z of D)Z()}},analytics:{identify(Z,$){if(z1=Z||void 0,!C||!j)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:j,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 j??""},register(Z){q={...q,...Z}},unregister(...Z){for(let $ of Z)delete q[$]}},get db(){return E1()},flush:S,destroy(){if(r)clearInterval(r);if(H1)clearInterval(H1);B.forEach((Z)=>Z()),K(),ZZ(),V?.disconnect(),V=null,S()}};function GZ(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 P1(){if(typeof location>"u")return!1;try{return new URL(location.href).searchParams.get("__bodify_render")==="1"}catch{return!1}}var JZ=P1();function zZ(){return JZ||P1()}function HZ(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||HZ($,$.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;