var A1=Object.defineProperty;var F1=(Z)=>Z;function O1(Z,$){this[Z]=F1.bind(null,$)}var g1=(Z,$)=>{for(var G in $)A1(Z,G,{get:$[G],enumerable:!0,configurable:!0,set:O1.bind($,G)})};var J1=(Z,$)=>()=>(Z&&($=Z(Z=0)),$);var H1=()=>{};var Q1={};g1(Q1,{wrapPublicKey:()=>n,unwrapPublicKey:()=>E1,sign:()=>L1,generateKeyPair:()=>Y1,browserFingerprint:()=>u});function C1(Z,$){let G=new Uint8Array(Z.length+$.length);return G.set(Z),G.set($,Z.length),G}function x(Z){let $="";for(let G=0;G<Z.length;G++)$+=String.fromCharCode(Z[G]);return btoa($)}function X1(Z){let $=atob(Z),G=new Uint8Array($.length);for(let J=0;J<$.length;J++)G[J]=$.charCodeAt(J);return G}function K1(Z){return Array.from(Z).map(($)=>$.toString(16).padStart(2,"0")).join("")}function n(Z){return C1(W1,Z)}function E1(Z){return Z.slice(W1.length)}async function Y1(){let Z=(void 0).randomSecretKey(),$=await(void 0)(Z),G=n($),J=await u(x(G));return{publicKeyBase64:x(G),privateKeyBase64:x(Z),fingerprint:J}}async function L1(Z,$){let G=X1($),J=new TextEncoder().encode(Z),z=await(void 0)(J,G);return x(z)}async function u(Z){let $=X1(Z),G=new ArrayBuffer($.byteLength);new Uint8Array(G).set($);let J=await crypto.subtle.digest("SHA-256",G);return K1(new Uint8Array(J))}var W1,t1;var y=J1(()=>{H1();W1=new Uint8Array([48,42,48,5,6,3,43,101,112,3,33,0]),t1=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32])});var F=1;function z1(Z){let $=Z.lastIndexOf("/");return $>=0?Z.slice($+1):Z}function h(Z){let $="";for(let G=0;G<Z.length;G++)$+=String.fromCharCode(Z[G]);return btoa($)}function x1(Z){let $=atob(Z),G=new Uint8Array($.length);for(let J=0;J<$.length;J++)G[J]=$.charCodeAt(J);return G}function P1(){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 i{url=P1();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 i,...Z},this.reconnectDelay=this.options.reconnectInterval,this.auth=new f(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),W=await this.send("auth-verify",{publicKey:this.options.keyAuth.publicKey,signature:z,nonce:J.nonce});this._authToken=W.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 W=z.indexOf(":"),X=z.slice(0,W),Y=z.slice(W+1),Q=X.endsWith("-shallow"),T=Q?X.slice(0,-8):X;return{path:Y,event:T,...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,W]=this.splitStreamKey(J);await this.send("stream-sub",{path:z,groupId:W})}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 P(z.path,z.data,z.updatedAt),Y=this.valueCbs.get(z.path);if(Y)for(let T of Y)T(X);let Q=this.valueCbs.get(`${z.path}\x00shallow`);if(Q)for(let T of Q)T(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 T of Y)T(X);let Q=this.childCbs.get(`${z.path}\x00shallow`);if(Q)for(let T of Q)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 W=this.pending.get(z.id);if(W)if(this.pending.delete(z.id),z.ok)W.resolve(z);else W.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 W=this._offlineQueue.findIndex((X)=>X.dedupKey===z);if(W!==-1)this._offlineQueue[W].resolve({ok:!0,data:null}),this._offlineQueue.splice(W,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 W=this.nextId(),X=null,Y=()=>{if(X)clearTimeout(X),X=null};if(this.pending.set(W,{resolve:(Q)=>{Y(),J(Q)},reject:(Q)=>{Y(),z(Q)}}),this.options.requestTimeout>0)X=setTimeout(()=>{this.pending.delete(W),z(Error(`Request timeout after ${this.options.requestTimeout}ms`))},this.options.requestTimeout);this._recPush("send",{id:W,op:Z,...$}),this.ws.send(JSON.stringify({id:W,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 P(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 c(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}`,W=J?`${Z}\x00shallow`:Z;if(!this.valueCbs.has(W))this.valueCbs.set(W,new Set);if(this.valueCbs.get(W).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(W)?.delete($),this.valueCbs.get(W)?.size===0){if(this.valueCbs.delete(W),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}`,W=J?`${Z}\x00shallow`:Z;if(!this.childCbs.has(W))this.childCbs.set(W,new Set);if(this.childCbs.get(W).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(W)?.delete($),this.childCbs.get(W)?.size===0){if(this.childCbs.delete(W),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 d(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 T1(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(),Q1));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:(W)=>Z.sign(W,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 f{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 P{path;data;updatedAt;constructor(Z,$,G){this.path=Z;this.data=$;this.updatedAt=G}val(){return this.data}get key(){return z1(this.path)}exists(){return this.data!==null&&this.data!==void 0}}class d{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 c{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}`,W=await(await fetch(J,{method:"POST",body:new Blob([$]),headers:{"Content-Type":G||"application/octet-stream"}})).json();if(!W.ok)throw Error(W.error||"Upload failed");return W.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=h($),W=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 W=setTimeout(()=>{X(),z(Error("Download timeout"))},30000),X=this.client._onDownloadChunk($.transferId,(Y)=>{if(G[Y.seq]=Y.data,Y.done)clearTimeout(W),X(),J(x1(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),T=$.slice(Y,Q),U=h(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}),W=z.receivedBytes,X=z.totalSize;while(W<X){let Y=Math.min(W+J,X),Q=$.slice(W,Y),T=h(Q);W=(await this.client._send("vfs-resumable-chunk",{sessionId:Z,offset:W,data:T})).receivedBytes,G?.onProgress?.(W,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 T1{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 I1(Z){let $=2166136261;for(let G=0;G<Z.length;G++)$^=Z.charCodeAt(G),$=$+(($<<1)+($<<4)+($<<7)+($<<8)+($<<24))>>>0;return $>>>0}function M1(Z,$,G){return I1(`${Z}::${$??G}`)%1e4}function k1(Z){return Z.sticky??Z.userId??Z.accountId??""}function B1(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=M1($,Z.salt,G)%J,W=0;for(let X of Z.variants)if(W+=X.weight,z<W)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 m1(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 b1(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 W=m1($.targeting,G);if(W){let{value:X,variant:Y}=b1(Z,$.targeting);return{key:J,value:X,...Y?{variant:Y}:{},reason:W==="email"?"targeting_email":"targeting_tag"}}}if(z&&$.value!==void 0)return{key:J,value:$.value,reason:"override_value"};if(z&&$.rollout){let W=k1(G);if(Z.kind==="variant"&&$.rollout.variants?.length){let X=B1($.rollout,W,Z.key);if(X)return{key:J,value:o(Z,X.variantKey),variant:X.variantKey,reason:"rollout"}}else if(Z.kind==="boolean"){let X=M1(W,$.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,j=new Map,w=new Map,N=new Set,q=null,b=null,Z1=null,q1=new Map,_1=60000,_="bodify.flags.override",V1="bodify_anon_id",s="bodify_session_id",v1=1800000,g=!1,A,$1,S,v=[],G1=null,B=[],V={};function D1(){return crypto.randomUUID?.()??Math.random().toString(36).slice(2)+Date.now().toString(36)}function n1(){try{let $=localStorage.getItem(V1);if($)return $}catch{}let Z=D1();try{localStorage.setItem(V1,Z)}catch{}return Z}var j1="bodify_anon_uid";function u1(){try{let G=localStorage.getItem(j1);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(j1,$)}catch{}return $}var t=null,a=null;function N1(Z){if(L)L.userId=Z;for(let $ of N)$()}function R1(){try{let $=sessionStorage.getItem(s);if($){let{id:G,ts:J}=JSON.parse($);if(Date.now()-J<v1)return sessionStorage.setItem(s,JSON.stringify({id:G,ts:Date.now()})),G}}catch{}let Z=D1();try{sessionStorage.setItem(s,JSON.stringify({id:Z,ts:Date.now()}))}catch{}return Z}function S1(){if(!L)return"";return`${L.ingestUrl.replace(/\/apps\/[^/]+\/ingest$/,"")}/analytics/${L.appId}`}function C(Z,$,G){let J=Object.keys(V).length?{...V,...G}:G;return{anonymousId:S,sessionId:R1(),userId:$1,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),$=`${S1()}/events`,G=JSON.stringify({events:Z}),J={"Content-Type":"application/json"};if(A)J["x-analytics-token"]=A;if(!A&&typeof navigator<"u"&&navigator.sendBeacon){if(navigator.sendBeacon($,new Blob([G],{type:"application/json"})))return}fetch($,{method:"POST",headers:J,body:G,keepalive:!0}).catch(()=>{})}function E(Z){if(v.push(Z),v.length>=10)K()}function y1(Z){let $=typeof Z.analytics==="object"?Z.analytics:{};if(g=!0,A=$.secret,S=n1(),G1=setInterval(K,5000),!$.disableAutoPageViews){let X=()=>E(C("$pageview","page_view",{path:location.pathname,title:document.title}));X();let Y=history.pushState.bind(history),Q=history.replaceState.bind(history);history.pushState=function(...U){Y(...U),X()},history.replaceState=function(...U){Q(...U),X()};let T=()=>X();window.addEventListener("popstate",T),B.push(()=>{history.pushState=Y,history.replaceState=Q,window.removeEventListener("popstate",T)})}let G=(X)=>E(C("$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(C("$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()},W=()=>K();document.addEventListener("visibilitychange",z),window.addEventListener("beforeunload",W),B.push(()=>{document.removeEventListener("visibilitychange",z),window.removeEventListener("beforeunload",W)})}function h1(){if(typeof document>"u")return;let Z=document.cookie.split(";").map(($)=>$.trim()).find(($)=>$.startsWith(`${_}=`));if(!Z)return;try{let $=decodeURIComponent(Z.slice(_.length+1));return JSON.parse($).flags}catch{return}}function i1(Z){if(!Z)return;for(let $ of Z.definitions??[])if($?.key)j.set($.key,$);for(let $ of Z.overrides??[])if($?.key)w.set($.key,$)}function f1(Z){try{let $=new URL(Z,typeof location<"u"?location.href:void 0);return`${$.protocol==="https:"?"wss:":"ws:"}//${$.host}/db`}catch{return null}}function w1(){if(q)return q;if(!L)throw Error("Bodify SDK not initialized");let Z=f1(L.ingestUrl);if(!Z)throw Error("Cannot derive DB WS URL from ingestUrl");return q=new I({url:Z,reconnect:!0,offlineQueue:!0,offlineQueueCap:100,auth:()=>H.auth._token??""}),q.connect().catch(()=>{}),q}function d1(){if(b||!L)return;let Z;try{Z=w1()}catch{return}let $=L.appId,G=`flags/${$}/definitions`,J=`flags/${$}/overrides`;b=Z.on(G,(z)=>{let W=z.val();if(!W&&j.size>0)return;let X=new Map;if(W){for(let Y of Object.values(W))if(Y?.key)X.set(Y.key,Y)}j=X;for(let Y of N)Y(void 0)},{deep:!0}),Z1=Z.on(J,(z)=>{let W=z.val();if(!W&&w.size>0)return;let X=new Map;if(W){for(let Y of Object.values(W))if(Y?.key)X.set(Y.key,Y)}w=X;for(let Y of N)Y(void 0)},{deep:!0})}function c1(){b?.(),Z1?.(),b=null,Z1=null}function e(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:h1()}}function U1(Z,$,G,J,z){if(!L)return;let W=z.sticky??z.userId??z.accountId??"",X=`${Z}::${$??String(G)}::${W}`,Y=Date.now(),Q=q1.get(X);if(Q&&Y-Q<_1)return;q1.set(X,Y),M({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});if(!L.apiKey&&typeof navigator<"u"&&navigator.sendBeacon)navigator.sendBeacon(L.ingestUrl,new Blob([G],{type:"application/json"}));else fetch(L.ingestUrl,{method:"POST",headers:$,body:G,keepalive:!0}).catch(()=>{})}function l1(Z){if(m.push(Z),L&&m.length>=(L.maxBatchSize??20))R()}function M(Z){l1({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 H={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)=>{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")R()}),window.addEventListener("beforeunload",R),H.auth.restore(),i1(Z.flags),d1(),Z.analytics!==!1)y1(Z)},event(Z,$){let G=g?{anonymousId:S,sessionId:R1(),userId:$1,...V,...$}:{...V,...$};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(!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=H.storage._baseUrl(),J=$?.path??Z.name,z=await fetch(`${G}/upload`,{method:"POST",headers:H.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 W=await z.json();if(W.uploadUrl){let Y=await fetch(W.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/${W.fileId}?sessionId=${W.sessionId}`,{method:"PUT",body:Z,headers:{...H.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/${W.fileId}/finalize`,{method:"POST",headers:H.storage._headers(),body:JSON.stringify({sessionId:W.sessionId})});if(!X.ok)throw Error(`Finalize failed: ${X.status}`);return await X.json().catch(()=>({})),{fileId:W.fileId}},async getUrl(Z){let $=await fetch(`${H.storage._baseUrl()}/files/${Z}/url`,{headers:H.storage._headers()});if(!$.ok)throw Error(`Get URL failed: ${$.status}`);return(await $.json()).url},async delete(Z){let $=await fetch(`${H.storage._baseUrl()}/files/${Z}`,{method:"DELETE",headers:H.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(`${H.storage._baseUrl()}/files?${$}`,{headers:H.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(H.auth._token)G.Authorization=`Bearer ${H.auth._token}`;return fetch(`${H.auth._baseUrl()}${Z}`,{...$,headers:G})},_setToken(Z){if(H.auth._token=Z,Z)localStorage.setItem("bodify_auth_token",Z);else localStorage.removeItem("bodify_auth_token")},_notify(){H.auth._listeners.forEach((Z)=>Z(H.auth._user,H.auth._pendingVerification))},_handleAuthResponse(Z){if(H.auth._setToken(Z.token),Z.emailVerificationRequired)H.auth._user=null,H.auth._pendingVerification=Z.user;else H.auth._user=Z.user,H.auth._pendingVerification=null;H.auth._notify()},async signUp(Z){let $=await H.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 H.auth._handleAuthResponse(G),G},async signIn(Z){let $=await H.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 H.auth._handleAuthResponse(G),G},signInWithOAuth(Z){window.location.href=`${H.auth._baseUrl()}/oauth/${Z}`},adoptAnonIdentity(){if(H.auth._user?.isAnonymous)return H.auth._user.id;let Z=u1();if(!H.auth._user)H.auth._user={id:Z,isAnonymous:!0},N1(Z),H.auth._notify();return Z},whenTokenReady(){if(H.auth._token)return Promise.resolve();return t??Promise.resolve()},async signInAnonymously(){let Z=H.auth.adoptAnonIdentity();if(!H.auth._token&&!t)t=new Promise((J)=>{a=J});let $=await H.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 H.auth._setToken(G.token),H.auth._user=G.user,H.auth._pendingVerification=null,N1(G.user.id),H.auth._notify(),a?.(),a=null,G},async attachEmail(Z){let $=await H.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 H.auth._user=G,H.auth._notify(),G},async linkEmail(Z,$){let G=await H.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 H.auth._user=J,H.auth._notify(),J},async linkPhone(Z,$){let G=await H.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 H.auth._user=J,H.auth._notify(),J},async startPhoneSignIn(Z){let $=await H.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 H.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 H.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 H.auth._fetch("/audit");if(!Z.ok)throw Error("Audit list failed");return Z.json()},async signInWithPhone(Z,$){let G=await H.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 H.auth._setToken(J.token),H.auth._user=J.user,H.auth._pendingVerification=null,H.auth._notify(),J},async signOut(){await H.auth._fetch("/logout",{method:"POST"}).catch(()=>{}),H.auth._setToken(null),H.auth._user=null,H.auth._pendingVerification=null,H.auth._notify()},async verifyEmail(Z){let $=await H.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 H.auth._setToken(G.token),H.auth._user=G.user,H.auth._pendingVerification=null,H.auth._notify(),G},async resendVerification(){let Z=await H.auth._fetch("/resend-verification",{method:"POST"});if(!Z.ok){let $=await Z.json().catch(()=>({}));throw Error($.error??"Resend failed")}},async signInWithMagicLink(Z){let $=await H.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 H.auth._setToken(G.token),H.auth._user=G.user,H.auth._pendingVerification=null,H.auth._notify(),G},async getProviders(){return(await fetch(`${H.auth._baseUrl()}/providers`)).json()},async getUser(){if(!H.auth._token)return null;let Z=3;for(let $=0;$<Z;$++){let G=null;try{G=await H.auth._fetch("/me")}catch{}if(G){if(G.ok){let J=await G.json();return H.auth._user=J,J}if(G.status===401)return H.auth._user=null,null}if($<Z-1)await new Promise((J)=>setTimeout(J,400*($+1)))}return H.auth._user},async updateProfile(Z){let $=await H.auth._fetch("/me",{method:"PATCH",body:JSON.stringify(Z)});if(!$.ok)throw Error("Update failed");let G=await $.json();return H.auth._user=G,H.auth._notify(),G},onAuthStateChange(Z){return H.auth._listeners.push(Z),()=>{H.auth._listeners=H.auth._listeners.filter(($)=>$!==Z)}},restore(){let Z=localStorage.getItem("bodify_auth_token");if(Z)H.auth._token=Z}},flags:{get(Z,$){let G=e($),J=j.get(Z),z=w.get(Z),W=k(J,z,G);return U1(Z,W.variant,W.value,W.reason,G),W.value},isEnabled(Z,$){return H.flags.get(Z,$)===!0},variant(Z,$){let G=e($),J=j.get(Z),z=w.get(Z),W=k(J,z,G);return U1(Z,W.variant,W.value,W.reason,G),W.variant??""},all(Z){let $=e(Z),G={};for(let[J,z]of j){let W=w.get(J),X=k(z,W,$);G[J]=X.value}return G},subscribe(Z){return N.add(Z),()=>N.delete(Z)},keys(){return[...j.keys()].sort()},setCookieOverride(Z,$){if(typeof document>"u")return;let G=encodeURIComponent(JSON.stringify({flags:Z})),J=$?.maxAgeSec??86400;document.cookie=`${_}=${G}; path=/; max-age=${J}; samesite=lax`;for(let z of N)z()},clearCookieOverride(){if(typeof document>"u")return;document.cookie=`${_}=; path=/; max-age=0`;for(let Z of N)Z()}},analytics:{identify(Z,$){if($1=Z||void 0,!g||!S)return;let G=`${S1()}/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(!g)return;E(C(Z,"custom",$))},page(Z){if(!g)return;E(C("$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 w1()},flush:R,destroy(){if(r)clearInterval(r);if(G1)clearInterval(G1);B.forEach((Z)=>Z()),K(),c1(),q?.disconnect(),q=null,R()}};if(typeof window<"u"){let Z=window.__BODIFY_CONFIG__;if(Z)H.init(Z);else{let $=document.currentScript;if($?.dataset.appId&&$?.dataset.ingestUrl){let G=window.__BODIFY_FLAGS__;H.init({appId:$.dataset.appId,ingestUrl:$.dataset.ingestUrl,apiKey:$.dataset.apiKey,deployId:$.dataset.deployId,branch:$.dataset.branch,userId:$.dataset.userId,flags:G,analytics:$.dataset.analytics==="false"?!1:!0})}}}window.Bodify=H;