dolphin-client 1.0.5 → 1.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,26 +1,37 @@
1
- var DolphinModule=(()=>{var P=Object.defineProperty;var Y=Object.getOwnPropertyDescriptor;var Z=Object.getOwnPropertyNames;var G=Object.prototype.hasOwnProperty;var tt=(m,t)=>{for(var e in t)P(m,e,{get:t[e],enumerable:!0})},et=(m,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Z(t))!G.call(m,r)&&r!==e&&P(m,r,{get:()=>t[r],enumerable:!(n=Y(t,r))||n.enumerable});return m};var nt=m=>et(P({},"__esModule",{value:!0}),m);var it={};tt(it,{DolphinClient:()=>k});var x=class{client;constructor(t){return this.client=t,this._createProxy([])}_createProxy(t){let e=t.join("/"),n=i=>this.request("GET",e,null,i);n.get=(i,o)=>typeof i=="string"?this.request("GET",i,null,o):this.request("GET",e,null,i),n.post=(i,o,u)=>typeof i=="string"?this.request("POST",i,o,u):this.request("POST",e,i,o),n.put=(i,o,u)=>typeof i=="string"?this.request("PUT",i,o,u):this.request("PUT",e,i,o),n.patch=(i,o,u)=>typeof i=="string"?this.request("PATCH",i,o,u):this.request("PATCH",e,i,o),n.del=(i,o)=>typeof i=="string"?this.request("DELETE",i,null,o):this.request("DELETE",e,null,i),n.request=(i,o,u,S)=>{let D=o?`${e}/${o.startsWith("/")?o.slice(1):o}`:e;return this.request(i,D,u,S)},n.requestDirect=(i,o,u,S)=>this.requestDirect(i,o,u,S);let r=["get","post","put","patch","del","request","requestDirect"];return new Proxy(n,{get:(i,o)=>typeof o=="string"&&!r.includes(o)?this._createProxy([...t,o]):i[o]})}async request(t,e,n=null,r={}){if(this.client.offline){let i=this.client.offline.isOnline,o=`${t.toUpperCase()}:${e}`;if(t.toUpperCase()==="GET")if(i)try{let u=await this.requestDirect(t,e,n,r);return await this.client.offline.setCache(o,u),u}catch(u){let S=await this.client.offline.getCache(o);if(S!=null)return S;throw u}else{let u=await this.client.offline.getCache(o);if(u!=null)return u;throw{status:503,data:{error:"Offline, no cache available"}}}else return i?this.requestDirect(t,e,n,r):(await this.client.offline.queueMutation(t,e,n),this.client._dispatch("offline:queued",{method:t,path:e,body:n}),{success:!0,offline:!0,message:"Mutation queued offline"})}return this.requestDirect(t,e,n,r)}async requestDirect(t,e,n=null,r={}){let i=r._isRetry===!0,o=e.startsWith("http://")||e.startsWith("https://")?e:`${this.client.httpUrl}${e.startsWith("/")?e:"/"+e}`;this.client.options.debug&&console.log("%c\u{1F680} [Dolphin API Request]:","color: #3b82f6; font-weight: bold;",t.toUpperCase(),e,n||"");let u=new AbortController,S=setTimeout(()=>u.abort(),this.client.options.timeout),D={"Content-Type":"application/json",...r.headers||{}};this.client.accessToken&&(D.Authorization=`Bearer ${this.client.accessToken}`);let g={...r};delete g._isRetry;try{let c=await fetch(o,{method:t,headers:D,signal:u.signal,...n?{body:JSON.stringify(n)}:{},...g});if(clearTimeout(S),c.status===401&&!i&&this.client.options.autoRefreshToken&&await this.client.auth._silentRefresh())return this.request(t,e,n,{...r,_isRetry:!0});let s=(c.headers.get("content-type")||"").includes("application/json")?await c.json():await c.text();if(!c.ok)throw{status:c.status,data:s};if(this.client.options.debug&&console.log("%c\u2705 [Dolphin API Success]:","color: #10b981; font-weight: bold;",t.toUpperCase(),e,s),s&&typeof s=="object"&&s.accessToken&&(this.client.setToken(s.accessToken),s.user&&(this.client.auth.user=s.user)),this.client.options.autoBroadcast&&["POST","PUT","PATCH","DELETE"].includes(t.toUpperCase())){let a=e.startsWith("/")?e.substring(1):e;this.client.publish(a,{method:t.toUpperCase(),payload:n,result:s})}return s}catch(c){throw clearTimeout(S),this.client.options.debug&&console.error("%c\u274C [Dolphin API Error]:","color: #ef4444; font-weight: bold;",t.toUpperCase(),e,c),c.name==="AbortError"?{status:408,data:{error:"Request timed out"}}:c}}};var C=class{client;user;_refreshing;constructor(t){this.client=t,this.user=null,this._refreshing=!1}async login(t,e){let n=await this.client.api.post("/api/auth/login",{email:t,password:e});return n.accessToken&&(this.client.setToken(n.accessToken),this.user=n.user||null),n}async register(t){return this.client.api.post("/api/auth/register",t)}async me(){let t=await this.client.api.get("/api/auth/me");return t.success&&(this.user=t.data),t}async logout(){try{await this.client.api.post("/api/auth/logout")}catch{}this.client.setToken(null),this.user=null}async refresh(){return this._silentRefresh()}async _silentRefresh(){if(this._refreshing)return!1;this._refreshing=!0;try{let t=await this.client.api.post("/api/auth/refresh",null,{_isRetry:!0});return t.accessToken?(this.client.setToken(t.accessToken),!0):!1}catch{return this.client.setToken(null),!1}finally{this._refreshing=!1}}async verify2FA(t,e){let n={code:t,email:e||this.user?.email},r=await this.client.api.post("/api/auth/2fa/verify",n);return r.accessToken&&(this.client.setToken(r.accessToken),r.user&&(this.user=r.user)),r}async enable2FA(){return this.client.api.post("/api/auth/2fa/enable")}async disable2FA(t){return this.client.api.post("/api/auth/2fa/disable",{code:t})}async forgotPassword(t){return this.client.api.post("/api/auth/forgot-password",{email:t})}async resetPassword(t,e){return this.client.api.post("/api/auth/reset-password",{token:t,newPassword:e})}};var M=class{client;data;listeners;subscribed;constructor(t){return this.client=t,this.data=new Map,this.listeners=new Set,this.subscribed=new Set,new Proxy(this,{get:(e,n)=>{if(n in e)return e[n];if(typeof n=="string")return this._getCollection(n)}})}_getCollection(t){if(!this.data.has(t)){let e={_rawItems:[],items:[],loading:!0,error:null,success:!1,_filter:null,_sort:null,where:n=>(e._filter=n,this._applyTransform(e),e),orderBy:(n,r="asc")=>(e._sort={key:n,direction:r},this._applyTransform(e),e),reset:()=>(e._filter=null,e._sort=null,this._applyTransform(e),e)};this.data.set(t,e),this._fetchAndSync(t)}return this.data.get(t)}async _fetchAndSync(t){let e=this.data.get(t);try{let n=await this.client.api.get(`/${t.toLowerCase()}`);e._rawItems=Array.isArray(n)?n:n.data||[],e.loading=!1,e.success=!0,e.error=null,this._applyTransform(e),this.subscribed.has(t)||(this.client.subscribe(`db:sync/${t.toLowerCase()}`,r=>{this._handleRemoteUpdate(t,r)}),this.subscribed.add(t))}catch(n){e.loading=!1,e.success=!1,e.error=n.data?.error||n.message||"Fetch failed",this._notify()}}_applyTransform(t){let e=[...t._rawItems];if(t._filter&&(e=e.filter(t._filter)),t._sort){let{key:n,direction:r}=t._sort;e.sort((i,o)=>i[n]===o[n]?0:(i[n]>o[n]?1:-1)*(r==="asc"?1:-1))}t.items=e,this._notify()}_handleRemoteUpdate(t,e){let n=this.data.get(t);if(!n)return;let{type:r,data:i}=e,o=n._rawItems;r==="create"?o=[...o,i]:r==="update"?o=o.map(u=>u.id===i.id||u._id===i._id?{...u,...i}:u):r==="delete"&&(o=o.filter(u=>!(i.id!=null&&u.id===i.id||i._id!=null&&u._id===i._id))),n._rawItems=o,this._applyTransform(n)}subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}getSnapshot(t){return this.data.get(t)||{items:[],loading:!1,error:null,success:!1}}_notify(){this.listeners.forEach(t=>t())}};var k=class{host;httpUrl;deviceId;options;socket;storage;accessToken;api;auth;store;handlers;signalHandlers;fileHandlers;_offlineQueue;reconnectAttempts;_attachedListeners;constructor(t="",e="",n={}){!t&&typeof window<"u"&&(t=window.location.host);let r="http:";t.startsWith("https://")?r="https:":t.startsWith("http://")?r="http:":typeof window<"u"&&(r=window.location.protocol),this.host=(t||"localhost").replace(/\/$/,"").replace(/^https?:\/\//,""),this.httpUrl=`${r}//${this.host}`,this.deviceId=e||"web_"+Math.random().toString(36).substr(2,8),this.options={timeout:15e3,chunkSize:65536,maxReconnect:5,autoRefreshToken:!0,debug:!1,...n},this.socket=null,this.storage=typeof localStorage<"u"?localStorage:{getItem:()=>null,setItem:()=>{},removeItem:()=>{}},this.accessToken=this.storage.getItem("dolphin_token"),this.api=new x(this),this.auth=new C(this),this.store=new M(this),this.handlers=new Map,this.signalHandlers=new Set,this.fileHandlers=new Set,this._offlineQueue=[],this.reconnectAttempts=0,this._attachedListeners=[],typeof window<"u"&&typeof this._initDOMBinding=="function"&&this._initDOMBinding(),typeof this._initOffline=="function"&&this._initOffline(),typeof this._initA11y=="function"&&this._initA11y(),typeof this._initI18n=="function"&&this._initI18n(),typeof this._initDragDrop=="function"&&this._initDragDrop(),typeof this._initCollab=="function"&&this._initCollab()}setToken(t){this.accessToken=t,t?this.storage.setItem("dolphin_token",t):this.storage.removeItem("dolphin_token")}async connect(){return new Promise((t,e)=>{let r=`${this.httpUrl.startsWith("https")?"wss:":"ws:"}//${this.host}/realtime?deviceId=${this.deviceId}`;console.log(`[Dolphin] Connecting to ${r}...`),this.socket=new WebSocket(r),this.socket.onopen=()=>{console.log(`[Dolphin] Connected as "${this.deviceId}" \u{1F42C}`),this.reconnectAttempts=0,this._flushOfflineQueue(),t()},this.socket.onmessage=i=>this._handleMessage(i.data),this.socket.onclose=()=>{console.warn("[Dolphin] Connection closed"),this._maybeReconnect()},this.socket.onerror=i=>{console.error("[Dolphin] WebSocket error:",i),e(i)}})}disconnect(){this.socket&&(this.socket.onclose=null,this.socket.close(),this.socket=null),this.cleanupDomListeners()}_handleMessage(t){try{let e=JSON.parse(t);this.options.debug&&console.log("%c\u{1F4E5} [Dolphin WS Incoming]:","color: #eab308; font-weight: bold;",e),e.type&&e.from&&(e.to===this.deviceId||e.to==="all")&&(e.msgId&&e.type!=="ACK"&&this._sendAck(e.from,e.msgId),this.signalHandlers.forEach(n=>n(e))),e.type==="FILE_AVAILABLE"&&this.fileHandlers.forEach(n=>n(e)),e.type==="FILE_CHUNK"&&(this.saveFileProgress(e.fileId,e.chunkIndex),this._dispatch("file:chunk",e),this._dispatch(`file:chunk/${e.fileId}`,e)),e.type==="FILE_UPLOAD_ACK"&&this._dispatch(`file:upload:ack/${e.fileId}`,e),e.type==="PULL_RESPONSE"&&(this._dispatch("pull:response",e.payload,e.topic),this._dispatch(`pull:response/${e.topic}`,e.payload,e.topic)),e.topic&&e.payload!==void 0&&this.handlers.forEach((n,r)=>{this._matchTopic(r,e.topic)&&n.forEach(i=>i(e.payload,e.topic))})}catch{this._dispatch("raw",t)}}_dispatch(t,e,n){let r=this.handlers.get(t);r&&r.forEach(i=>i(e,n||t))}_sendRaw(t){this.options.debug&&console.log("%c\u{1F4E4} [Dolphin WS Outgoing]:","color: #8b5cf6; font-weight: bold;",t);let e=typeof t=="string"?t:JSON.stringify(t);this.socket&&this.socket.readyState===WebSocket.OPEN?this.socket.send(e):this._offlineQueue.length<100&&this._offlineQueue.push(e)}_flushOfflineQueue(){for(;this._offlineQueue.length>0;){let t=this._offlineQueue.shift();this.socket&&this.socket.readyState===WebSocket.OPEN&&this.socket.send(t)}}_sendAck(t,e){this._sendRaw({type:"ACK",from:this.deviceId,to:t,data:{ackId:e},timestamp:Date.now()})}_matchTopic(t,e){if(t===e||t==="#")return!0;let n=t.split("/"),r=e.split("/");if(n.length!==r.length&&!t.includes("#"))return!1;for(let i=0;i<n.length;i++){if(n[i]==="#")return!0;if(n[i]!=="+"&&n[i]!==r[i])return!1}return n.length===r.length}_maybeReconnect(){if(this.reconnectAttempts<this.options.maxReconnect){this.reconnectAttempts++;let t=Math.pow(2,this.reconnectAttempts)*1e3;console.log(`[Dolphin] Reconnecting in ${t/1e3}s (attempt ${this.reconnectAttempts})...`),setTimeout(()=>this.connect().catch(()=>{}),t)}else console.error("[Dolphin] Max reconnect attempts reached.")}subscribe(t,e){this.handlers.has(t)||(this.handlers.set(t,new Set),this._sendRaw({type:"sub",topic:t})),this.handlers.get(t).add(e)}unsubscribe(t,e){if(this.handlers.has(t)){let n=this.handlers.get(t);n.delete(e),n.size===0&&(this.handlers.delete(t),this._sendRaw({type:"unsub",topic:t}))}}publish(t,e){this._sendRaw({topic:t,payload:e})}pubPush(t,e){this._sendRaw({type:"pub",topic:t,payload:e})}subPull(t,e=10){this._sendRaw({type:"PULL_REQUEST",topic:t,count:e})}async pubFile(t,e,n="",r){let i;e instanceof Blob?i=await e.arrayBuffer():e instanceof ArrayBuffer?i=e:i=e.buffer||e;let o=new Uint8Array(i),u=this.options.chunkSize,S=Math.ceil(o.length/u);this._sendRaw({type:"FILE_UPLOAD_START",fileId:t,name:n,size:o.length,totalChunks:S,chunkSize:u});for(let D=0;D<S;D++){let g=o.slice(D*u,(D+1)*u),c=this._uint8ToBase64(g);this._sendRaw({type:"FILE_UPLOAD_CHUNK",fileId:t,chunkIndex:D,totalChunks:S,data:c}),r&&r(Math.round((D+1)/S*100)),D%10===0&&await new Promise(l=>setTimeout(l,0))}this._sendRaw({type:"FILE_UPLOAD_DONE",fileId:t})}_uint8ToBase64(t){let e="";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return typeof btoa<"u"?btoa(e):Buffer.from(e,"binary").toString("base64")}subFile(t,e=0){this._sendRaw({type:"FILE_REQUEST",fileId:t,startChunk:e})}resumeFile(t){let e=parseInt(this.storage.getItem(`dolphin_file_${t}`)||"-1");this.subFile(t,e+1)}saveFileProgress(t,e){this.storage.setItem(`dolphin_file_${t}`,e.toString())}onSignal(t){this.signalHandlers.add(t)}offSignal(t){this.signalHandlers.delete(t)}onFileAvailable(t){this.fileHandlers.add(t)}offFileAvailable(t){this.fileHandlers.delete(t)}addDomListener(t,e,n){t&&(t.addEventListener(e,n),this._attachedListeners=this._attachedListeners||[],this._attachedListeners.push({target:t,event:e,cb:n}))}cleanupDomListeners(){this._attachedListeners&&(this._attachedListeners.forEach(({target:t,event:e,cb:n})=>{try{t.removeEventListener(e,n)}catch{}}),this._attachedListeners=[])}};function O(m){function t(g){return g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function e(g){let c=g.getAttribute("data-rt-template");if(!c)return null;if(typeof document<"u"&&!c.includes("<"))try{let l=document.querySelector(c);if(l)return l.innerHTML}catch{}return c}function n(g,c){if(!g.includes("{#if")&&!g.includes("{#each")){let l=g;for(let s in c){let a=s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");l=l.replace(new RegExp(`\\{\\{${a}\\}\\}`,"g"),c[s]!==void 0&&c[s]!==null?c[s]:"")}return l}try{let l=p=>p.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t"),s=`let out = "";
2
- `,a=0,y=/(\{\{([\s\S]*?)\}\}|\{#if\s+([\s\S]*?)\}|\{:else\s+if\s+([\s\S]*?)\}|\{:else\}|\{\/if\}|\{#each\s+([\s\S]*?)\s+as\s+([a-zA-Z_$][a-zA-Z0-9_$]*)(?:\s*,\s*([a-zA-Z_$][a-zA-Z0-9_$]*))?\}|\{\/each\}|\{([^{}]+?)\})/g,b=[],d;for(;(d=y.exec(g))!==null;){let p=g.slice(a,d.index);p&&(s+=`out += "${l(p)}";
3
- `);let A=d[0];if(A.startsWith("{{")){let _=d[2];s+=`out += (${_} !== undefined && ${_} !== null ? ${_} : "");
4
- `}else if(A.startsWith("{#if")){let _=d[3];s+=`if (${_}) {
5
- `}else if(A.startsWith("{:else if")){let _=d[4];s+=`} else if (${_}) {
6
- `}else if(A.startsWith("{:else}"))s+=`} else {
7
- `;else if(A.startsWith("{/if}"))s+=`}
8
- `;else if(A.startsWith("{#each")){let _=d[5],T=d[6],v=d[7];b.push({indexVar:v}),s+=`if (typeof ${_} !== "undefined" && ${_} !== null && Array.isArray(${_})) {
9
- `,v&&(s+=` let ${v} = 0;
10
- `),s+=` for (let ${T} of ${_}) {
11
- `}else if(A.startsWith("{/each}")){let _=b.pop();_&&_.indexVar&&(s+=` ${_.indexVar}++;
12
- `),s+=` }
1
+ var DolphinModule=(()=>{var R=Object.defineProperty;var Y=Object.getOwnPropertyDescriptor;var Z=Object.getOwnPropertyNames;var tt=Object.prototype.hasOwnProperty;var et=(A,t)=>{for(var e in t)R(A,e,{get:t[e],enumerable:!0})},nt=(A,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Z(t))!tt.call(A,s)&&s!==e&&R(A,s,{get:()=>t[s],enumerable:!(n=Y(t,s))||n.enumerable});return A};var st=A=>nt(R({},"__esModule",{value:!0}),A);var rt={};et(rt,{DolphinClient:()=>C});var x=class{client;constructor(t){return this.client=t,this._createProxy([])}_createProxy(t){let e=t.join("/"),n=i=>this.request("GET",e,null,i);n.get=(i,a)=>typeof i=="string"?this.request("GET",i,null,a):this.request("GET",e,null,i),n.post=(i,a,l)=>typeof i=="string"?this.request("POST",i,a,l):this.request("POST",e,i,a),n.put=(i,a,l)=>typeof i=="string"?this.request("PUT",i,a,l):this.request("PUT",e,i,a),n.patch=(i,a,l)=>typeof i=="string"?this.request("PATCH",i,a,l):this.request("PATCH",e,i,a),n.del=(i,a)=>typeof i=="string"?this.request("DELETE",i,null,a):this.request("DELETE",e,null,i),n.request=(i,a,l,_)=>{let v=a?`${e}/${a.startsWith("/")?a.slice(1):a}`:e;return this.request(i,v,l,_)},n.requestDirect=(i,a,l,_)=>this.requestDirect(i,a,l,_),n._findCSRFToken=()=>this._findCSRFToken(),n._resolveBaseUrl=i=>this._resolveBaseUrl(i),n._normalizeValidationErrors=i=>this._normalizeValidationErrors(i);let s=["get","post","put","patch","del","request","requestDirect","_findCSRFToken","_resolveBaseUrl","_normalizeValidationErrors"];return new Proxy(n,{get:(i,a)=>typeof a=="string"&&!s.includes(a)?this._createProxy([...t,a]):i[a]})}_findCSRFToken(){if(typeof document>"u")return null;let t=["csrf-token","_csrf","xsrf-token","csrf_token"];for(let i of t){let a=document.querySelector(`meta[name="${i}"], meta[content][name$="${i}"]`);if(a){let l=a.getAttribute("content");if(l)return l}}let e=["_csrfToken","_token","_csrf","csrf_token"];for(let i of e){let a=document.querySelector(`input[type="hidden"][name="${i}"]`);if(a&&a.value)return a.value}let n=["csrfToken","XSRF-TOKEN","_csrf","csrf_token"];for(let i of n){let a=document.cookie.match(new RegExp("(^|;\\s*)"+i+"=([^;]*)"));if(a)return decodeURIComponent(a[2])}let s=typeof window<"u"&&window.wpApiSettings?.nonce;return s||null}_resolveBaseUrl(t){if(t.startsWith("http://")||t.startsWith("https://"))return t;let e=this.client.httpUrl;if(typeof document<"u"){let s=document.querySelector("base[href]");if(s){let i=s.getAttribute("href")||"";if(i&&i!=="/"){let a=i.endsWith("/")?i.slice(0,-1):i;e=`${this.client.httpUrl}${a.startsWith("/")?a:"/"+a}`}}else{let i=document.querySelector('meta[name="base-path"]');if(i){let a=i.getAttribute("content")||"";if(a&&a!=="/"){let l=a.endsWith("/")?a.slice(0,-1):a;e=`${this.client.httpUrl}${l.startsWith("/")?l:"/"+l}`}}}}let n=t.startsWith("/")?t:"/"+t;return`${e}${n}`}_normalizeValidationErrors(t){let e={};if(!t||typeof t!="object")return e;let n=t.errors||t.validationErrors||t;if(Array.isArray(n)){for(let s of n)if(s&&typeof s=="object"){let i=s.path||s.param||s.field||s.property,a=s.msg||s.message||s.error;i&&a&&(e[i]=Array.isArray(a)?a[0]:a)}return e}if(typeof n=="object"&&n!==null)for(let s in n){let i=n[s];if(i)if(Array.isArray(i))i.length>0&&(e[s]=String(i[0]));else if(typeof i=="object"){let a=Object.keys(i);if(a.length>0){let l=a[0];e[s]=String(i[l])}}else e[s]=String(i)}return e}async request(t,e,n=null,s={}){if(this.client.offline){let i=this.client.offline.isOnline,a=`${t.toUpperCase()}:${e}`;if(t.toUpperCase()==="GET")if(i)try{let l=await this.requestDirect(t,e,n,s);return await this.client.offline.setCache(a,l),l}catch(l){let _=await this.client.offline.getCache(a);if(_!=null)return _;throw l}else{let l=await this.client.offline.getCache(a);if(l!=null)return l;throw{status:503,data:{error:"Offline, no cache available"}}}else return i?this.requestDirect(t,e,n,s):(await this.client.offline.queueMutation(t,e,n),this.client._dispatch("offline:queued",{method:t,path:e,body:n}),{success:!0,offline:!0,message:"Mutation queued offline"})}return this.requestDirect(t,e,n,s)}async requestDirect(t,e,n=null,s={}){let i=s._isRetry===!0,a=t.toUpperCase(),l=n,_={"Content-Type":"application/json",...s.headers||{}};["PUT","PATCH","DELETE"].includes(a)&&(this.client.options.methodSpoofing||s.methodSpoofing)&&(_["X-HTTP-Method-Override"]=a,l instanceof FormData?l.append("_method",a):l&&typeof l=="object"?l={...l,_method:a}:l||(l={_method:a}),a="POST");let v=this._resolveBaseUrl(e);this.client.options.debug&&console.log("%c\u{1F680} [Dolphin API Request]:","color: #3b82f6; font-weight: bold;",t.toUpperCase(),e,l||"");let k=new AbortController,h=setTimeout(()=>k.abort(),this.client.options.timeout);if(this.client.accessToken&&(_.Authorization=`Bearer ${this.client.accessToken}`),["POST","PUT","PATCH","DELETE"].includes(t.toUpperCase())){let c=this._findCSRFToken();c&&(_["X-CSRF-Token"]=c,_["X-XSRF-TOKEN"]=c,_["X-CSRFToken"]=c,_["X-WP-Nonce"]=c,l&&typeof l=="object"&&!l._csrfToken&&!l._token&&!l._csrf&&(l={...l,_csrfToken:c,_token:c,_csrf:c}))}let d={...s};delete d._isRetry,delete d.methodSpoofing;try{let c=await fetch(v,{method:a,headers:_,signal:k.signal,...l?{body:JSON.stringify(l)}:{},...d});if(clearTimeout(h),c.status===401&&!i&&this.client.options.autoRefreshToken&&await this.client.auth._silentRefresh())return this.request(t,e,n,{...s,_isRetry:!0});let o=(c.headers.get("content-type")||"").includes("application/json")?await c.json():await c.text();if(!c.ok)throw{status:c.status,data:o};if(this.client.options.debug&&console.log("%c\u2705 [Dolphin API Success]:","color: #10b981; font-weight: bold;",t.toUpperCase(),e,o),o&&typeof o=="object"&&o.accessToken&&(this.client.setToken(o.accessToken),o.user&&(this.client.auth.user=o.user)),this.client.options.autoBroadcast&&["POST","PUT","PATCH","DELETE"].includes(t.toUpperCase())){let u=e.startsWith("/")?e.substring(1):e;this.client.publish(u,{method:t.toUpperCase(),payload:n,result:o})}return o}catch(c){if(clearTimeout(h),this.client.options.debug&&console.error("%c\u274C [Dolphin API Error]:","color: #ef4444; font-weight: bold;",t.toUpperCase(),e,c),c&&typeof c=="object"&&c.data){let r=this._normalizeValidationErrors(c.data);if(Object.keys(r).length>0)for(let o in r)this.client.publish(`errors/${o}`,r[o])}throw c.name==="AbortError"?{status:408,data:{error:"Request timed out"}}:c}}};var $=class{client;user;_refreshing;constructor(t){this.client=t,this.user=null,this._refreshing=!1}async login(t,e){let n=await this.client.api.post("/api/auth/login",{email:t,password:e});return n.accessToken&&(this.client.setToken(n.accessToken),this.user=n.user||null),n}async register(t){return this.client.api.post("/api/auth/register",t)}async me(){let t=await this.client.api.get("/api/auth/me");return t.success&&(this.user=t.data),t}async logout(){try{await this.client.api.post("/api/auth/logout")}catch{}this.client.setToken(null),this.user=null}async refresh(){return this._silentRefresh()}async _silentRefresh(){if(this._refreshing)return!1;this._refreshing=!0;try{let t=await this.client.api.post("/api/auth/refresh",null,{_isRetry:!0});return t.accessToken?(this.client.setToken(t.accessToken),!0):!1}catch{return this.client.setToken(null),!1}finally{this._refreshing=!1}}async verify2FA(t,e){let n={code:t,email:e||this.user?.email},s=await this.client.api.post("/api/auth/2fa/verify",n);return s.accessToken&&(this.client.setToken(s.accessToken),s.user&&(this.user=s.user)),s}async enable2FA(){return this.client.api.post("/api/auth/2fa/enable")}async disable2FA(t){return this.client.api.post("/api/auth/2fa/disable",{code:t})}async forgotPassword(t){return this.client.api.post("/api/auth/forgot-password",{email:t})}async resetPassword(t,e){return this.client.api.post("/api/auth/reset-password",{token:t,newPassword:e})}};var P=class{client;data;listeners;subscribed;_unsubscribers;constructor(t){return this.client=t,this.data=new Map,this.listeners=new Set,this.subscribed=new Set,this._unsubscribers=new Map,new Proxy(this,{get:(e,n)=>{if(n in e)return e[n];if(typeof n=="string")return this._getCollection(n)}})}_getCollection(t){if(!this.data.has(t)){let e={_rawItems:[],items:[],loading:!0,error:null,success:!1,_filter:null,_sort:null,where:n=>(e._filter=n,this._applyTransform(e),e),orderBy:(n,s="asc")=>(e._sort={key:n,direction:s},this._applyTransform(e),e),reset:()=>(e._filter=null,e._sort=null,this._applyTransform(e),e)};this.data.set(t,e),this._fetchAndSync(t)}return this.data.get(t)}async _fetchAndSync(t){let e=this.data.get(t);try{let n=await this.client.api.get(`/${t.toLowerCase()}`);if(e._rawItems=Array.isArray(n)?n:n.data||[],e.loading=!1,e.success=!0,e.error=null,this._applyTransform(e),!this.subscribed.has(t)){let s=()=>this.client.unsubscribe(`db:sync/${t.toLowerCase()}`,i),i=a=>{this._handleRemoteUpdate(t,a)};this.client.subscribe(`db:sync/${t.toLowerCase()}`,i),this._unsubscribers.set(t,s),this.subscribed.add(t)}}catch(n){e.loading=!1,e.success=!1,e.error=n.data?.error||n.message||"Fetch failed",this._notify()}}_applyTransform(t){let e=[...t._rawItems];if(t._filter&&(e=e.filter(t._filter)),t._sort){let{key:n,direction:s}=t._sort;e.sort((i,a)=>i[n]===a[n]?0:(i[n]>a[n]?1:-1)*(s==="asc"?1:-1))}t.items=e,this._notify()}_handleRemoteUpdate(t,e){let n=this.data.get(t);if(!n)return;let{type:s,data:i}=e,a=n._rawItems;s==="create"?a=[...a,i]:s==="update"?a=a.map(l=>l.id===i.id||l._id===i._id?{...l,...i}:l):s==="delete"&&(a=a.filter(l=>!(i.id!=null&&l.id===i.id||i._id!=null&&l._id===i._id))),n._rawItems=a,this._applyTransform(n)}subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}getSnapshot(t){return this.data.get(t)||{items:[],loading:!1,error:null,success:!1}}_notify(){this.listeners.forEach(t=>t())}destroy(){this._unsubscribers.forEach(t=>{try{t()}catch{}}),this._unsubscribers.clear(),this.subscribed.clear(),this.listeners.clear(),this.data.clear()}};var C=class{host;httpUrl;deviceId;options;socket;storage;accessToken;api;auth;store;handlers;signalHandlers;fileHandlers;_offlineQueue;reconnectAttempts;_reconnectTimer;_attachedListeners;constructor(t="",e="",n={}){!t&&typeof window<"u"&&(t=window.location.host);let s="http:";t.startsWith("https://")?s="https:":t.startsWith("http://")?s="http:":typeof window<"u"&&(s=window.location.protocol),this.host=(t||"localhost").replace(/\/$/,"").replace(/^https?:\/\//,""),this.httpUrl=`${s}//${this.host}`,this.deviceId=e||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?"web_"+crypto.randomUUID().replace(/-/g,"").slice(0,8):"web_"+Math.random().toString(36).slice(2,10)),this.options={timeout:15e3,chunkSize:65536,maxReconnect:5,autoRefreshToken:!0,debug:!1,methodSpoofing:!1,routerViewport:"main, #viewport, body",routerTransitions:!0,...n},this.socket=null,this.storage=typeof localStorage<"u"?localStorage:{getItem:()=>null,setItem:()=>{},removeItem:()=>{}},this.accessToken=this.storage.getItem("dolphin_token"),this.api=new x(this),this.auth=new $(this),this.store=new P(this),this.handlers=new Map,this.signalHandlers=new Set,this.fileHandlers=new Set,this._offlineQueue=[],this.reconnectAttempts=0,this._reconnectTimer=null,this._attachedListeners=[],typeof window<"u"&&typeof this._initDOMBinding=="function"&&this._initDOMBinding(),typeof this._initOffline=="function"&&this._initOffline(),typeof this._initA11y=="function"&&this._initA11y(),typeof this._initI18n=="function"&&this._initI18n(),typeof this._initDragDrop=="function"&&this._initDragDrop(),typeof this._initCollab=="function"&&this._initCollab()}setToken(t){this.accessToken=t,t?this.storage.setItem("dolphin_token",t):this.storage.removeItem("dolphin_token")}async connect(){return this.socket&&(this.socket.readyState===WebSocket.OPEN||this.socket.readyState===WebSocket.CONNECTING)?Promise.resolve():new Promise((t,e)=>{let s=`${this.httpUrl.startsWith("https")?"wss:":"ws:"}//${this.host}/realtime?deviceId=${this.deviceId}`;console.log(`[Dolphin] Connecting to ${s}...`),this.socket=new WebSocket(s),this.socket.onopen=()=>{console.log(`[Dolphin] Connected as "${this.deviceId}" \u{1F42C}`),this.reconnectAttempts=0,this._flushOfflineQueue(),t()},this.socket.onmessage=i=>this._handleMessage(i.data),this.socket.onclose=()=>{console.warn("[Dolphin] Connection closed"),this._maybeReconnect()},this.socket.onerror=i=>{console.error("[Dolphin] WebSocket error:",i),e(i)}})}disconnect(){this._reconnectTimer!==null&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this.socket&&(this.socket.onclose=null,this.socket.close(),this.socket=null),typeof this._collabCleanup=="function"&&this._collabCleanup(),this.cleanupDomListeners()}_handleMessage(t){try{let e=JSON.parse(t);this.options.debug&&console.log("%c\u{1F4E5} [Dolphin WS Incoming]:","color: #eab308; font-weight: bold;",e),e.type&&e.from&&(e.to===this.deviceId||e.to==="all")&&(e.msgId&&e.type!=="ACK"&&this._sendAck(e.from,e.msgId),this.signalHandlers.forEach(n=>n(e))),e.type==="FILE_AVAILABLE"&&this.fileHandlers.forEach(n=>n(e)),e.type==="FILE_CHUNK"&&(this.saveFileProgress(e.fileId,e.chunkIndex),this._dispatch("file:chunk",e),this._dispatch(`file:chunk/${e.fileId}`,e)),e.type==="FILE_UPLOAD_ACK"&&this._dispatch(`file:upload:ack/${e.fileId}`,e),e.type==="PULL_RESPONSE"&&(this._dispatch("pull:response",e.payload,e.topic),this._dispatch(`pull:response/${e.topic}`,e.payload,e.topic)),e.topic&&e.payload!==void 0&&this.handlers.forEach((n,s)=>{this._matchTopic(s,e.topic)&&n.forEach(i=>i(e.payload,e.topic))})}catch{this._dispatch("raw",t)}}_dispatch(t,e,n){let s=this.handlers.get(t);s&&s.forEach(i=>i(e,n||t))}_sendRaw(t){this.options.debug&&console.log("%c\u{1F4E4} [Dolphin WS Outgoing]:","color: #8b5cf6; font-weight: bold;",t);let e=typeof t=="string"?t:JSON.stringify(t);this.socket&&this.socket.readyState===WebSocket.OPEN?this.socket.send(e):this._offlineQueue.length<100&&this._offlineQueue.push(e)}_flushOfflineQueue(){for(;this._offlineQueue.length>0;){let t=this._offlineQueue.shift();this.socket&&this.socket.readyState===WebSocket.OPEN&&this.socket.send(t)}}_sendAck(t,e){this._sendRaw({type:"ACK",from:this.deviceId,to:t,data:{ackId:e},timestamp:Date.now()})}_matchTopic(t,e){if(t===e||t==="#")return!0;let n=t.split("/"),s=e.split("/");if(n.length!==s.length&&!t.includes("#"))return!1;for(let i=0;i<n.length;i++){if(n[i]==="#")return!0;if(n[i]!=="+"&&n[i]!==s[i])return!1}return n.length===s.length}_maybeReconnect(){if(this.reconnectAttempts<this.options.maxReconnect){this.reconnectAttempts++;let t=Math.pow(2,this.reconnectAttempts)*1e3;console.log(`[Dolphin] Reconnecting in ${t/1e3}s (attempt ${this.reconnectAttempts})...`),this._reconnectTimer=setTimeout(()=>{this._reconnectTimer=null,this.connect().catch(()=>{})},t)}else console.error("[Dolphin] Max reconnect attempts reached.")}subscribe(t,e){this.handlers.has(t)||(this.handlers.set(t,new Set),this._sendRaw({type:"sub",topic:t})),this.handlers.get(t).add(e)}unsubscribe(t,e){if(this.handlers.has(t)){let n=this.handlers.get(t);n.delete(e),n.size===0&&(this.handlers.delete(t),this._sendRaw({type:"unsub",topic:t}))}}publish(t,e){this._sendRaw({topic:t,payload:e})}pubPush(t,e){this._sendRaw({type:"pub",topic:t,payload:e})}subPull(t,e=10){this._sendRaw({type:"PULL_REQUEST",topic:t,count:e})}async pubFile(t,e,n="",s){let i;e instanceof Blob?i=await e.arrayBuffer():e instanceof ArrayBuffer?i=e:i=e.buffer||e;let a=new Uint8Array(i),l=this.options.chunkSize,_=Math.ceil(a.length/l);this._sendRaw({type:"FILE_UPLOAD_START",fileId:t,name:n,size:a.length,totalChunks:_,chunkSize:l});for(let v=0;v<_;v++){let k=a.slice(v*l,(v+1)*l),h=this._uint8ToBase64(k);this._sendRaw({type:"FILE_UPLOAD_CHUNK",fileId:t,chunkIndex:v,totalChunks:_,data:h}),s&&s(Math.round((v+1)/_*100)),v%10===0&&await new Promise(d=>setTimeout(d,0))}this._sendRaw({type:"FILE_UPLOAD_DONE",fileId:t})}_uint8ToBase64(t){let e="";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return typeof btoa<"u"?btoa(e):Buffer.from(e,"binary").toString("base64")}subFile(t,e=0){this._sendRaw({type:"FILE_REQUEST",fileId:t,startChunk:e})}resumeFile(t){let e=parseInt(this.storage.getItem(`dolphin_file_${t}`)||"-1");this.subFile(t,e+1)}saveFileProgress(t,e){this.storage.setItem(`dolphin_file_${t}`,e.toString())}onSignal(t){this.signalHandlers.add(t)}offSignal(t){this.signalHandlers.delete(t)}onFileAvailable(t){this.fileHandlers.add(t)}offFileAvailable(t){this.fileHandlers.delete(t)}addDomListener(t,e,n){t&&(t.addEventListener(e,n),this._attachedListeners=this._attachedListeners||[],this._attachedListeners.push({target:t,event:e,cb:n}))}cleanupDomListeners(){this._attachedListeners&&(this._attachedListeners.forEach(({target:t,event:e,cb:n})=>{try{t.removeEventListener(e,n)}catch{}}),this._attachedListeners=[])}};function U(A){let t=new Map;function e(h){return h.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function n(h){let d=h.getAttribute("data-rt-template");if(!d)return null;if(typeof document<"u"&&!d.includes("<"))try{let c=document.querySelector(d);if(c)return c.innerHTML}catch{}return d}function s(h,d){if(!h.includes("{#if")&&!h.includes("{#each")){let c=h;for(let r in d){let o=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");c=c.replace(new RegExp(`\\{\\{${o}\\}\\}`,"g"),d[r]!==void 0&&d[r]!==null?d[r]:"")}return c}try{let c=p=>p.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t"),r=`let out = "";
2
+ `,o=0,u=/(\{\{([\s\S]*?)\}\}|\{#if\s+([\s\S]*?)\}|\{:else\s+if\s+([\s\S]*?)\}|\{:else\}|\{\/if\}|\{#each\s+([\s\S]*?)\s+as\s+([a-zA-Z_$][a-zA-Z0-9_$]*)(?:\s*,\s*([a-zA-Z_$][a-zA-Z0-9_$]*))?\}|\{\/each\}|\{([^{}]+?)\})/g,b=[],f;for(;(f=u.exec(h))!==null;){let p=h.slice(o,f.index);p&&(r+=`out += "${c(p)}";
3
+ `);let y=f[0];if(y.startsWith("{{")){let T=f[2];r+=`out += (${T} !== undefined && ${T} !== null ? ${T} : "");
4
+ `}else if(y.startsWith("{#if")){let T=f[3];r+=`if (${T}) {
5
+ `}else if(y.startsWith("{:else if")){let T=f[4];r+=`} else if (${T}) {
6
+ `}else if(y.startsWith("{:else}"))r+=`} else {
7
+ `;else if(y.startsWith("{/if}"))r+=`}
8
+ `;else if(y.startsWith("{#each")){let T=f[5],D=f[6],E=f[7];b.push({indexVar:E}),r+=`if (typeof ${T} !== "undefined" && ${T} !== null && Array.isArray(${T})) {
9
+ `,E&&(r+=` let ${E} = 0;
10
+ `),r+=` for (let ${D} of ${T}) {
11
+ `}else if(y.startsWith("{/each}")){let T=b.pop();T&&T.indexVar&&(r+=` ${T.indexVar}++;
12
+ `),r+=` }
13
13
  }
14
- `}else if(A.startsWith("{")){let _=d[8];_&&(s+=`out += (${_} !== undefined && ${_} !== null ? ${_} : "");
15
- `)}a=y.lastIndex}let f=g.slice(a);f&&(s+=`out += "${l(f)}";
16
- `),s+=`return out;
14
+ `}else if(y.startsWith("{")){let T=f[8];T&&(r+=`out += (${T} !== undefined && ${T} !== null ? ${T} : "");
15
+ `)}o=u.lastIndex}let m=h.slice(o);m&&(r+=`out += "${c(m)}";
16
+ `),r+=`return out;
17
17
  `;let w=`
18
18
  with (context) {
19
19
  try {
20
- ${s}
20
+ ${r}
21
21
  } catch (innerErr) {
22
22
  console.warn('[Dolphin Template Eval Warning]:', innerErr);
23
23
  return '';
24
24
  }
25
25
  }
26
- `,E=c;return typeof Proxy<"u"&&c!==null&&typeof c=="object"&&(E=new Proxy(c,{has(p,A){return typeof A!="symbol"},get(p,A){if(A!==Symbol.unscopables){if(A in p)return p[A];if(typeof globalThis<"u"&&A in globalThis)return globalThis[A];if(typeof window<"u"&&A in window)return window[A]}}})),new Function("context",w)(E)}catch(l){console.error("[Dolphin Template Compiler Error]:",l);let s=g;for(let a in c){let y=a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");s=s.replace(new RegExp(`\\{\\{${y}\\}\\}`,"g"),c[a]!==void 0&&c[a]!==null?c[a]:"")}return s}}function r(g){if(typeof document>"u")return g;try{let s=new DOMParser().parseFromString(g,"text/html").body,a=y=>{let b=y.tagName.toLowerCase();if(["script","iframe","object","embed","link","style","meta","applet","svg"].includes(b)){y.parentNode?.removeChild(y);return}let d=y.attributes;for(let f=d.length-1;f>=0;f--){let w=d[f].name.toLowerCase(),E=d[f].value.toLowerCase();(w.startsWith("on")||["src","href","data"].includes(w)&&(E.includes("javascript:")||E.includes("data:text/html")))&&y.removeAttribute(d[f].name)}Array.from(y.children).forEach(a)};return Array.from(s.children).forEach(a),s.innerHTML}catch{return g}}function i(g,c){if(g.nodeType!==c.nodeType){g.parentNode?.replaceChild(c.cloneNode(!0),g);return}if(g.nodeType===Node.TEXT_NODE){g.textContent!==c.textContent&&(g.textContent=c.textContent);return}if(g.nodeType===Node.ELEMENT_NODE){let l=g,s=c;if(l.tagName!==s.tagName){l.parentNode?.replaceChild(s.cloneNode(!0),l);return}let a=l.attributes,y=s.attributes;for(let h=a.length-1;h>=0;h--){let p=a[h].name;s.hasAttribute(p)||l.removeAttribute(p)}for(let h=0;h<y.length;h++){let p=y[h].name,A=y[h].value;l.getAttribute(p)!==A&&l.setAttribute(p,A)}l.tagName==="INPUT"||l.tagName==="TEXTAREA"?(l.value!==s.value&&(l.value=s.value),l.checked!==s.checked&&(l.checked=s.checked)):l.tagName==="SELECT"&&l.value!==s.value&&(l.value=s.value);let b=Array.from(l.childNodes),d=Array.from(s.childNodes),f=b.length,w=d.length,E=Math.max(f,w);for(let h=0;h<E;h++)h>=f?l.appendChild(d[h].cloneNode(!0)):h>=w?l.removeChild(b[h]):i(b[h],d[h])}}function o(g,c){if(typeof document>"u")return;let l=document.createElement(g.tagName);l.innerHTML=c;let s=Array.from(g.childNodes),a=Array.from(l.childNodes),y=s.length,b=a.length,d=Math.max(y,b);for(let f=0;f<d;f++)f>=y?g.appendChild(a[f].cloneNode(!0)):f>=b?g.removeChild(s[f]):i(s[f],a[f])}let u=new Map,S=!1;function D(g,c){u.set(g,c),S||(S=!0,(typeof requestAnimationFrame<"u"?requestAnimationFrame:s=>setTimeout(s,0))(()=>{u.forEach((s,a)=>{o(a,s)}),u.clear(),S=!1}))}m.setStoreState=function(g,c,l){this.uiStores=this.uiStores||new Map,this.uiStores.has(g)||this.uiStores.set(g,{});let s=this.uiStores.get(g);s[c]=l,this.options.debug&&console.log("%c\u{1F4BE} [Dolphin Store Update]:","color: #ec4899; font-weight: bold;",`${g}.${c}`,"=",l),typeof document<"u"&&document.querySelectorAll(`[data-store-read="${g}.${c}"]`).forEach(y=>{y.tagName==="INPUT"||y.tagName==="TEXTAREA"?y.type==="checkbox"?y.checked=!!l:y.value=l??"":y.textContent=l??""}),this.publish(`store/${g}`,s),typeof this._updateDOM=="function"&&this._updateDOM(`store/${g}`,s)},m.getStoreState=function(g,c){this.uiStores=this.uiStores||new Map;let l=this.uiStores.get(g);return l?l[c]:void 0},m._scanStoreBinds=function(){if(typeof document>"u")return;document.querySelectorAll("[data-store-write]").forEach(l=>{let s=l.getAttribute("data-store-write");if(s){let a=s.split(".");if(a.length===2){let y=a[0],b=a[1],d=l.type==="checkbox"?l.checked:l.value;this.uiStores=this.uiStores||new Map,this.uiStores.has(y)||this.uiStores.set(y,{});let f=this.uiStores.get(y);f[b]===void 0&&(f[b]=d)}}}),document.querySelectorAll("[data-store-read]").forEach(l=>{let s=l.getAttribute("data-store-read");if(s){let a=s.split(".");if(a.length===2){let y=a[0],b=a[1],d=this.getStoreState(y,b);d!=null&&(l.tagName==="INPUT"||l.tagName==="TEXTAREA"?l.type==="checkbox"?l.checked=!!d:l.value=d:l.textContent=d)}}})},m.getClosestContext=function(g,c){let l=g;for(;l;){if(l._rtContext){let s=l._rtContext;return c?s[c]:s}l=l.parentElement}return null},m._executeStoreAction=function(g,c){this.uiStores=this.uiStores||new Map;let l=new Proxy({},{has:(s,a)=>!0,get:(s,a)=>{if(typeof a=="string")return new Proxy({},{get:(y,b)=>{if(typeof b=="string")return this.getStoreState(a,b)},set:(y,b,d)=>typeof b=="string"?(this.setStoreState(a,b,d),!0):!1})}});try{new Function("ctx",`with(ctx) { ${g} }`)(l)}catch(s){console.error("%c[Dolphin Store Action Error]:","color: #ef4444; font-weight: bold;",s),c&&console.error("%cFailed Element:","color: #f97316; font-weight: bold;",c),console.error("%cFailed Expression:","color: #3b82f6; font-style: italic;",g)}},m._initDOMBinding=function(){if(this._domInitialized)return;this._domInitialized=!0;let g=["input","change","keyup","paste","blur"],c=new Map;g.forEach(s=>{this.addDomListener(document,s,a=>{if(!a.target||!a.target.getAttribute)return;let y=a.target.getAttribute("data-store-write");if(y){let w=y.split(".");if(w.length===2){let E=w[0],h=w[1],p=a.target.type==="checkbox"?a.target.checked:a.target.value;this.setStoreState(E,h,p)}}let b=a.target.getAttribute("data-rt-validate"),d=a.target.name;if(b&&d&&typeof this.validateField=="function"){let w=a.target.closest("form"),E=w?Object.fromEntries(new FormData(w).entries()):{},h=this.validateField(a.target.value,b,E);h?(a.target.classList.add("invalid"),this.publish(`errors/${d}`,h)):(a.target.classList.remove("invalid"),this.publish(`errors/${d}`,""))}let f=a.target.getAttribute("data-rt-push");if(f){let w=a.target.getAttribute("data-rt-debounce"),E=w?parseInt(w,10):0,h=()=>{let p={name:a.target.name,value:a.target.value};this.pubPush(f,p)};if(E>0){c.has(a.target)&&clearTimeout(c.get(a.target));let p=setTimeout(h,E);c.set(a.target,p)}else h()}})}),this.addDomListener(document,"submit",async s=>{if(!s.target||!s.target.getAttribute)return;let a=s.target.getAttribute("data-rt-submit"),y=s.target.getAttribute("data-api-submit");if(a||y){let b=s.target.querySelectorAll("[data-rt-validate]"),d=!0;if(b.length>0&&typeof this.validateField=="function"){let h=Object.fromEntries(new FormData(s.target).entries());b.forEach(p=>{let A=p.getAttribute("data-rt-validate"),_=p.name;if(A&&_){let T=this.validateField(p.value,A,h);T?(d=!1,p.classList.add("invalid"),this.publish(`errors/${_}`,T)):(p.classList.remove("invalid"),this.publish(`errors/${_}`,""))}})}if(!d){s.preventDefault(),s.stopPropagation();return}s.preventDefault();let f=this.getClosestContext(s.target)||{},w=new FormData(s.target),E=Object.fromEntries(w.entries());if(a){let h=a;for(let p in f){let A=t(p);h=h.replace(new RegExp(`\\{\\{${A}\\}\\}`,"g"),f[p]!==void 0&&f[p]!==null?f[p]:"")}this.publish(h,E)}else if(y){let h=y;for(let T in f){let v=t(T);h=h.replace(new RegExp(`\\{\\{${v}\\}\\}`,"g"),f[T]!==void 0&&f[T]!==null?f[T]:"")}let p=h.trim().split(" "),A=p.length>1?p[0].toUpperCase():"POST",_=p.length>1?p[1]:p[0];try{let T=await this.api.request(A,_,E),v=s.target.getAttribute("data-api-result");v&&this._updateDOM(v,T);let L=s.target.getAttribute("data-api-redirect");L&&(window.location.href=L),s.target.hasAttribute("data-api-reload")&&window.location.reload()}catch(T){console.error("[Dolphin] API Submit Error:",T)}}}}),["click","change","submit","input","keydown","keyup","dblclick","focus","blur","mouseenter","mouseleave"].forEach(s=>{this.addDomListener(document,s,async a=>{if(!a.target||!a.target.closest)return;let y=a.target.closest(`[data-rt-${s}]`),b=a.target.closest(`[data-api-${s}]`);if(y){s==="submit"&&a.preventDefault();let f=y.getAttribute(`data-rt-${s}`),w=y.getAttribute("data-rt-payload"),E=this.getClosestContext(y)||{},h={};if(w){let p=w;for(let A in E){let _=t(A);p=p.replace(new RegExp(`\\{\\{${_}\\}\\}`,"g"),E[A]!==void 0&&E[A]!==null?E[A]:"")}try{h=JSON.parse(p)}catch{h={}}}this.publish(f,h)}if(b){s==="submit"&&a.preventDefault();let f=b.getAttribute(`data-api-${s}`),w=b.getAttribute("data-api-payload"),E=this.getClosestContext(b)||{},h=f.trim().split(" "),p=h.length>1?h[0].toUpperCase():"POST",A=h.length>1?h[1]:h[0],_=null;if(w){let T=w;for(let v in E){let L=t(v);T=T.replace(new RegExp(`\\{\\{${L}\\}\\}`,"g"),E[v]!==void 0&&E[v]!==null?E[v]:"")}try{_=JSON.parse(T)}catch{_=null}}try{let T=await this.api.request(p,A,_),v=b.getAttribute("data-api-result");v&&this._updateDOM(v,T);let L=b.getAttribute("data-api-redirect");L&&(window.location.href=L),b.hasAttribute("data-api-reload")&&window.location.reload()}catch(T){console.error(`[Dolphin] API ${s} Error:`,T)}}let d=a.target.closest(`[data-store-${s}]`);if(d){s==="submit"&&a.preventDefault();let f=d.getAttribute(`data-store-${s}`);f&&this._executeStoreAction(f,d)}})}),this.subscribe("#",(s,a)=>{this._updateDOM(a,s)}),this._scanAndFetchAPIBinds(),this._scanStoreBinds()},m._scanAndFetchAPIBinds=async function(){if(typeof document>"u")return;let g=document.querySelectorAll("[data-api-get]");for(let c of Array.from(g)){let l=c.getAttribute("data-api-get");if(l)try{let s=await this.api.get(l),a=c.getAttribute("data-api-store");if(a){let b=a.split(".");b.length===2&&this.setStoreState(b[0],b[1],s)}let y=c.getAttribute("data-rt-bind");if(y&&!a)this._updateDOM(y,s);else if(!a){let b=e(c);if(b&&typeof s=="object"&&s!==null){let d=this._applyDeclarativeDirectives(c,s);if(Array.isArray(d)){let f="";for(let w of d)f+=n(b,w);D(c,f)}else D(c,n(b,d))}else c.tagName==="INPUT"||c.tagName==="TEXTAREA"?c.value=typeof s=="object"?s.value!==void 0?s.value:"":s:c.innerHTML=typeof s=="object"?s.html||s.text||JSON.stringify(s):s}}catch(s){console.error("[Dolphin] API Get Error:",s)}}},m._applyDeclarativeDirectives=function(g,c){let l=c;if(typeof c=="object"&&c!==null){let s=a=>{let y=[...a],b=g.getAttribute("data-rt-filter");if(b){let w=b.split("==");if(w.length===2){let E=w[0].trim(),h=w[1].trim(),p,A=h.split(".");A.length===2?p=this.getStoreState(A[0],A[1]):p=c[h]!==void 0?c[h]:this.getStoreState("app",h),p!=null&&p!==""&&(y=y.filter(_=>_[E]===p))}}let d=g.getAttribute("data-rt-search");if(d){let w=d.split("==");if(w.length===2){let E=w[0].trim(),h=w[1].trim(),p,A=h.split(".");if(A.length===2?p=this.getStoreState(A[0],A[1]):p=c[h]!==void 0?c[h]:this.getStoreState("app",h),p!=null&&p!==""){let _=String(p).toLowerCase();y=y.filter(T=>{let v=T[E];return v!=null&&String(v).toLowerCase().includes(_)})}}}let f=g.getAttribute("data-rt-sort");if(f){let w,E=f.split(".");if(E.length===2?w=this.getStoreState(E[0],E[1]):w=c[f]!==void 0?c[f]:this.getStoreState("app",f),w&&w!=="")if(w==="popular")y.sort((h,p)=>{let A=h.rating?.rate||h.rate||0;return(p.rating?.rate||p.rate||0)-A});else{let h="",p="asc";w.endsWith("-low")||w.endsWith("-asc")?(h=w.replace("-low","").replace("-asc",""),p="asc"):(w.endsWith("-high")||w.endsWith("-desc"))&&(h=w.replace("-high","").replace("-desc",""),p="desc"),h&&y.sort((A,_)=>{let T=(J,Q)=>Q.split(".").reduce((N,X)=>N&&N[X],J),v=T(A,h),L=T(_,h);if(v===void 0&&(v=A[h]),L===void 0&&(L=_[h]),typeof v=="string"&&typeof L=="string")return p==="asc"?v.localeCompare(L):L.localeCompare(v);let $=Number(v),I=Number(L);return!isNaN($)&&!isNaN(I)?p==="asc"?$-I:I-$:0})}}return y};if(Array.isArray(c))l=s(c);else{let a="";for(let y in c)if(Array.isArray(c[y])){a=y;break}if(a){let y=s(c[a]);l={...c,[a]:y}}}}return l},m._updateDOM=function(g,c){if(typeof document>"u")return;document.querySelectorAll(`[data-rt-bind="${g}"]`).forEach(s=>{let a=this._applyDeclarativeDirectives(s,c);if(s.getAttribute("data-rt-type")==="context"&&typeof a=="object"&&a!==null){s._rtContext=a;let b=d=>{if(d.hasAttribute("data-rt-text")){let f=d.getAttribute("data-rt-text");f&&a[f]!==void 0&&a[f]!==null&&(d.textContent=a[f])}if(d.hasAttribute("data-rt-html")){let f=d.getAttribute("data-rt-html");f&&a[f]!==void 0&&a[f]!==null&&(d.innerHTML=r(a[f]))}if(d.hasAttribute("data-rt-attr")){let f=d.getAttribute("data-rt-attr");f&&f.split(",").forEach(w=>{let E=w.split(":");if(E.length===2){let h=E[0].trim(),p=E[1].trim();h&&p&&a[p]!==void 0&&a[p]!==null&&d.setAttribute(h,a[p])}})}if(d.hasAttribute("data-rt-class")){let f=d.getAttribute("data-rt-class");f&&f.split(",").forEach(w=>{let E=w.split(":");if(E.length===2){let h=E[0].trim(),p=E[1].trim(),A=h.split(/\s+/).filter(Boolean);a[p]?A.forEach(_=>d.classList.add(_)):A.forEach(_=>d.classList.remove(_))}})}if(d.hasAttribute("data-rt-if")){let f=d.getAttribute("data-rt-if");f&&(a[f]?d.style.display="":d.style.display="none")}if(d.hasAttribute("data-rt-hide")){let f=d.getAttribute("data-rt-hide");f&&(a[f]?d.style.display="none":d.style.display="")}};b(s),s.querySelectorAll("[data-rt-text], [data-rt-html], [data-rt-attr], [data-rt-class], [data-rt-if], [data-rt-hide]").forEach(b);return}let y=e(s);if(y&&typeof a=="object"&&a!==null){if(Array.isArray(a)){let b="";for(let d of a)b+=n(y,d);D(s,b)}else D(s,n(y,a));return}s.tagName==="INPUT"||s.tagName==="TEXTAREA"?s.value=typeof a=="object"?a.value!==void 0?a.value:"":a:s.innerHTML=typeof a=="object"?a.html||a.text||JSON.stringify(a):a})}}var R=class{client;db;isOnline;memoryCache=new Map;memoryMutations=[];constructor(t){this.client=t,this.isOnline=typeof window<"u"&&typeof navigator<"u"?navigator.onLine:!0,this.initDB(),this.setupNetworkListeners()}initDB(){if(!(typeof indexedDB>"u"))try{let t=indexedDB.open("dolphin_offline",1);t.onupgradeneeded=e=>{let n=e.target.result;n.objectStoreNames.contains("cache")||n.createObjectStore("cache"),n.objectStoreNames.contains("mutations")||n.createObjectStore("mutations",{keyPath:"id",autoIncrement:!0})},t.onsuccess=e=>{this.db=e.target.result,this.isOnline&&this.syncMutations()}}catch(t){console.warn("[Dolphin Offline] Failed to initialize IndexedDB:",t)}}setupNetworkListeners(){typeof window>"u"||(this.client.addDomListener(window,"online",()=>{this.isOnline=!0,this.client._dispatch("network:status",{online:!0}),this.syncMutations()}),this.client.addDomListener(window,"offline",()=>{this.isOnline=!1,this.client._dispatch("network:status",{online:!1})}))}async getCache(t){return this.db?new Promise(e=>{try{let i=this.db.transaction("cache","readonly").objectStore("cache").get(t);i.onsuccess=()=>e(i.result?i.result.data:null),i.onerror=()=>e(null)}catch{e(null)}}):this.memoryCache.get(t)}async setCache(t,e){if(!this.db){this.memoryCache.set(t,e);return}return new Promise(n=>{try{let r=this.db.transaction("cache","readwrite");r.objectStore("cache").put({data:e,timestamp:Date.now()},t),r.oncomplete=()=>n()}catch{n()}})}async queueMutation(t,e,n){let r={method:t,path:e,payload:n,timestamp:Date.now()};if(!this.db){this.memoryMutations.push(r);return}return new Promise(i=>{try{let o=this.db.transaction("mutations","readwrite");o.objectStore("mutations").add(r),o.oncomplete=()=>i()}catch{i()}})}async getMutations(){return this.db?new Promise(t=>{try{let r=this.db.transaction("mutations","readonly").objectStore("mutations").getAll();r.onsuccess=()=>t(r.result||[]),r.onerror=()=>t([])}catch{t([])}}):[...this.memoryMutations]}async removeMutation(t){if(!this.db){this.memoryMutations=this.memoryMutations.filter(e=>e.id!==t);return}return new Promise(e=>{try{let n=this.db.transaction("mutations","readwrite");n.objectStore("mutations").delete(t),n.oncomplete=()=>e()}catch{e()}})}async syncMutations(){let t=await this.getMutations();if(t.length!==0){console.log(`[Dolphin Offline] Syncing ${t.length} queued mutations...`);for(let e of t)try{await this.client.api.requestDirect(e.method,e.path,e.payload),e.id!==void 0?await this.removeMutation(e.id):this.memoryMutations.shift()}catch(n){if(console.error(`[Dolphin Offline] Sync failed for mutation ${e.method} ${e.path}:`,n),n&&n.status&&n.status>=400&&n.status<500)console.warn("[Dolphin Offline] Discarding invalid mutation."),e.id!==void 0?await this.removeMutation(e.id):this.memoryMutations.shift();else break}}}};function U(m){m._initOffline=function(){this.offline=new R(this)}}function st(m,t,e){let n=t.split(",");for(let r of n){let i=r.trim().split(":"),o=i[0],u=i[1];if(o==="required"){if(!m||m.trim()==="")return"This field is required"}else if(o==="email"){if(m&&m.trim()!==""&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(m))return"Please enter a valid email address"}else if(o==="min"){let S=parseInt(u,10);if(!m||m.length<S)return`Must be at least ${S} characters`}else if(o==="match"&&e&&m!==e[u])return`Must match ${u}`}return null}function W(m){m.validateField=st}function F(m){m.animateElement=function(t,e,n=300){if(typeof t.animate!="function"){t.classList.add(e),setTimeout(()=>t.classList.remove(e),n);return}e==="fade-in"?t.animate([{opacity:0,transform:"translateY(10px)"},{opacity:1,transform:"translateY(0)"}],{duration:n,easing:"ease-out"}):e==="fade-out"&&t.animate([{opacity:1,transform:"translateY(0)"},{opacity:0,transform:"translateY(10px)"}],{duration:n,easing:"ease-in"})},m.staggerListItems=function(t,e,n=50){if(typeof document>"u")return;t.querySelectorAll(e).forEach((i,o)=>{i.style.animationDelay=`${o*n}ms`,i.classList.add("staggered-item")})}}function H(m){m._initA11y=function(){typeof document>"u"||(this.addDomListener(document,"keydown",t=>{if(t.key!=="Tab")return;document.querySelectorAll("[data-rt-a11y-focus-trap]").forEach(n=>{if(n.style.display==="none"||n.hasAttribute("aria-hidden")&&n.getAttribute("aria-hidden")==="true")return;let i=Array.from(n.querySelectorAll('a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, [tabindex="0"], [contenteditable]'));if(i.length===0)return;let o=i[0],u=i[i.length-1];t.shiftKey?document.activeElement===o&&(u.focus(),t.preventDefault()):document.activeElement===u&&(o.focus(),t.preventDefault())})}),this.addDomListener(document,"keydown",t=>{if(!["ArrowUp","ArrowDown","Enter"].includes(t.key))return;document.querySelectorAll("[data-rt-keynav]").forEach(n=>{let r=Array.from(n.children);if(r.length===0)return;let i=r.findIndex(o=>o.classList.contains("active")||document.activeElement===o);t.key==="ArrowDown"?(i=(i+1)%r.length,r[i].focus(),r.forEach((o,u)=>{u===i?o.classList.add("active"):o.classList.remove("active")}),t.preventDefault()):t.key==="ArrowUp"?(i=(i-1+r.length)%r.length,r[i].focus(),r.forEach((o,u)=>{u===i?o.classList.add("active"):o.classList.remove("active")}),t.preventDefault()):t.key==="Enter"&&i!==-1&&(r[i].click(),t.preventDefault())})}))},m.autoAriaModal=function(t,e){e?(t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-hidden","false"),t.focus()):t.setAttribute("aria-hidden","true")}}function j(m){m._initI18n=function(){if(this.i18n=this.i18n||{locale:"en",dicts:{}},typeof document>"u")return;if(document.querySelectorAll("[data-i18n-dict]").forEach(e=>{let n=e.getAttribute("data-i18n-dict");if(n)try{let r=JSON.parse(e.textContent||"{}");this.i18n.dicts[n]={...this.i18n.dicts[n]||{},...r}}catch(r){console.warn("[Dolphin i18n] Failed to parse dictionary for locale:",n,r)}}),!this.i18n.locale&&typeof navigator<"u"){let e=navigator.language.split("-")[0];this.i18n.dicts[e]&&(this.i18n.locale=e)}this.addDomListener(document,"click",e=>{let n=e.target.closest("[data-i18n-switch]");if(n){let r=n.getAttribute("data-i18n-switch");r&&this.setLocale(r)}}),this.translateDOM()},m.setLocale=function(t){this.i18n=this.i18n||{locale:"en",dicts:{}},this.i18n.locale=t,this.translateDOM(),this.publish("i18n/locale",t)},m.translateDOM=function(){if(typeof document>"u")return;this.i18n=this.i18n||{locale:"en",dicts:{}};let t=this.i18n.locale||"en",e=this.i18n.dicts[t]||{};document.querySelectorAll("[data-i18n-key]").forEach(r=>{let i=r.getAttribute("data-i18n-key");if(!i)return;let o=i.split(".").reduce((S,D)=>S?S[D]:null,e);o==null&&(o=i);let u=r.getAttribute("data-i18n-params");if(u)try{let S=JSON.parse(u),D=g=>g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");for(let g in S){let c=D(g);o=o.replace(new RegExp(`\\{\\{${c}\\}\\}`,"g"),S[g])}}catch{}r.tagName==="INPUT"||r.tagName==="TEXTAREA"?r.placeholder=o:r.textContent=o})}}function B(m){m._initDragDrop=function(){typeof document>"u"||(this.addDomListener(document,"dragstart",t=>{let e=t.target.closest("[data-drag]");if(!e)return;let n=e.getAttribute("data-drag");n&&(t.dataTransfer.setData("text/plain",n),t.dataTransfer.effectAllowed="move",e.classList.add("dragging"))}),this.addDomListener(document,"dragend",t=>{let e=t.target.closest("[data-drag]");e&&e.classList.remove("dragging")}),this.addDomListener(document,"dragover",t=>{let e=t.target.closest("[data-drop]");e&&(t.preventDefault(),e.classList.add("drag-over"))}),this.addDomListener(document,"dragleave",t=>{let e=t.target.closest("[data-drop]");e&&e.classList.remove("drag-over")}),this.addDomListener(document,"drop",t=>{let e=t.target.closest("[data-drop]");if(!e)return;t.preventDefault(),e.classList.remove("drag-over");let n=e.getAttribute("data-drop"),r=t.dataTransfer.getData("text/plain");if(n&&r)try{let i=JSON.parse(r);this.publish(n,i)}catch{this.publish(n,{value:r})}}),this.addDomListener(document,"dragover",t=>{let e=t.target.closest("[data-sortable]");if(!e)return;t.preventDefault();let n=e.querySelector(".dragging");if(!n)return;let i=Array.from(e.querySelectorAll("[data-drag]:not(.dragging)")).find(o=>{let u=o.getBoundingClientRect();return t.clientY-u.top-u.height/2<0});i?e.insertBefore(n,i):e.appendChild(n)}),this.addDomListener(document,"drop",t=>{let e=t.target.closest("[data-sortable]");if(!e)return;let n=e.getAttribute("data-sortable");if(!n)return;let i=Array.from(e.querySelectorAll("[data-drag]")).map((o,u)=>{let S=o.getAttribute("data-drag");try{return{index:u,payload:JSON.parse(S||"{}")}}catch{return{index:u,payload:S}}});this.publish(n,i)}))}}function V(m){m._initCollab=function(){typeof document>"u"||(this.addDomListener(document,"mousemove",t=>{document.querySelectorAll("[data-rt-cursor-share]").forEach(n=>{let r=n.getAttribute("data-rt-cursor-share");if(!r)return;let i=n.getBoundingClientRect(),o=(t.clientX-i.left)/i.width,u=(t.clientY-i.top)/i.height,S=Date.now();(!n._lastSent||S-n._lastSent>50)&&(n._lastSent=S,this.pubPush(`collab/${r}/cursor/${this.deviceId}`,{deviceId:this.deviceId,x:o,y:u}))})}),this.addDomListener(document,"input",t=>{let e=t.target.getAttribute("data-rt-typing");if(!e)return;let n=e,r=i=>{this.pubPush(`collab/${n}/typing/${this.deviceId}`,{deviceId:this.deviceId,typing:i})};t.target._isTyping||(t.target._isTyping=!0,r(!0)),t.target._typingTimer&&clearTimeout(t.target._typingTimer),t.target._typingTimer=setTimeout(()=>{t.target._isTyping=!1,r(!1)},2e3)}),this.addDomListener(document,"input",t=>{let e=t.target.getAttribute("data-rt-crdt");if(!e)return;let n=e,r=t.target.value,i=Date.now();this.publish(`collab/${n}/crdt`,{deviceId:this.deviceId,value:r,timestamp:i,cursorPos:t.target.selectionStart})}),this.subscribe("collab/+/cursor/+",(t,e)=>{let n=e.split("/"),r=n[1],i=n[3];if(i===this.deviceId)return;let o=document.querySelector(`[data-rt-cursor-share="${r}"]`);if(!o)return;let u=o.querySelector(`.rt-cursor-${i}`);u||(u=document.createElement("div"),u.className=`rt-cursor rt-cursor-${i}`,u.style.position="absolute",u.style.width="10px",u.style.height="10px",u.style.borderRadius="50%",u.style.backgroundColor="#"+Math.floor(Math.random()*16777215).toString(16),u.style.pointerEvents="none",o.appendChild(u));let S=o.getBoundingClientRect();u.style.left=t.x*S.width+"px",u.style.top=t.y*S.height+"px"}),this.subscribe("collab/+/crdt",(t,e)=>{if(t.deviceId===this.deviceId)return;let r=e.split("/")[1];document.querySelectorAll(`[data-rt-crdt="${r}"]`).forEach(o=>{if(!o._lastUpdate||t.timestamp>o._lastUpdate){o._lastUpdate=t.timestamp;let u=o.selectionStart;o.value=t.value,document.activeElement===o&&o.setSelectionRange(u,u)}})}))}}function z(m){m.registerServiceWorker=async function(t="/sw.js"){if(typeof navigator>"u"||!("serviceWorker"in navigator))return console.warn("[Dolphin PWA] Service Workers are not supported in this browser."),null;try{let e=await navigator.serviceWorker.register(t);return console.log("[Dolphin PWA] Service Worker registered successfully with scope:",e.scope),e}catch(e){return console.error("[Dolphin PWA] Service Worker registration failed:",e),null}},m.subscribePushNotifications=async function(t){if(typeof window>"u"||!("serviceWorker"in navigator)||!("PushManager"in window))return console.warn("[Dolphin PWA] Push notifications are not supported in this browser."),null;try{let e=await navigator.serviceWorker.ready,n=await e.pushManager.getSubscription();if(!n){let r="=".repeat((4-t.length%4)%4),i=(t+r).replace(/\-/g,"+").replace(/_/g,"/"),o=window.atob(i),u=new Uint8Array(o.length);for(let S=0;S<o.length;++S)u[S]=o.charCodeAt(S);n=await e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:u})}return console.log("[Dolphin PWA] Subscribed to push notifications:",n),n}catch(e){return console.error("[Dolphin PWA] Push notification subscription failed:",e),null}}}var q=class{static render(t){if(typeof document>"u")throw new Error("DolphinTestUtils.render requires a DOM document environment to execute.");let e=document.createElement("div");return e.innerHTML=t,document.body.appendChild(e),{container:e,find:n=>e.querySelector(n),fireEvent:(n,r)=>{let i=document.createEvent("Event");i.initEvent(r,!0,!0),n.dispatchEvent(i)}}}static mockWebSocket(){let t=[],e={readyState:1,send:n=>{t.push(n)},close:jest.fn(),onopen:jest.fn(),onmessage:jest.fn(),onclose:jest.fn(),onerror:jest.fn(),sentMessages:t};return global.WebSocket=class{static OPEN=1;readyState=e.readyState;send=e.send;close=e.close;set onopen(n){e.onopen=n}get onopen(){return e.onopen}set onmessage(n){e.onmessage=n}get onmessage(){return e.onmessage}set onclose(n){e.onclose=n}get getonclose(){return e.onclose}constructor(){setTimeout(()=>e.onopen&&e.onopen(),0)}},e}static simulateClick(t){let e={target:t,preventDefault:jest.fn(),stopPropagation:jest.fn()};(global.document._listeners?.click||[]).forEach(r=>r(e))}static simulateChange(t,e){t.value=e;let n={target:t,preventDefault:jest.fn(),stopPropagation:jest.fn()};(global.document._listeners?.change||[]).forEach(i=>i(n))}};function K(m){m.testing=q}O(k.prototype);U(k.prototype);W(k.prototype);F(k.prototype);H(k.prototype);j(k.prototype);B(k.prototype);V(k.prototype);z(k.prototype);K(k.prototype);typeof window<"u"&&(window.DolphinClient=k,document.addEventListener("DOMContentLoaded",()=>{if(!window.dolphin){let m=document.querySelector('script[src*="dolphin-client"]'),t=m?m.getAttribute("data-debug")==="true":!1,e=new k(void 0,void 0,{debug:t});window.dolphin=e,t&&(console.log("%c\u{1F42C} [Dolphin Client] Auto-initialized local reactive engine!","color: #06b6d4; font-weight: bold; font-size: 14px;"),console.log('%c\u{1F449} Tip: You can access the client instance via "window.dolphin" in console.',"color: #94a3b8; font-style: italic;")),document.querySelector('[data-store-write="app.username"]')&&e.setStoreState("app","username","\u0928\u092E\u0938\u094D\u0924\u0947 \u0938\u093E\u0925\u0940!")}}));return nt(it);})();
26
+ `,S=d;return typeof Proxy<"u"&&d!==null&&typeof d=="object"&&(S=new Proxy(d,{has(p,y){return typeof y!="symbol"},get(p,y){if(y!==Symbol.unscopables){if(y in p)return p[y];if(typeof globalThis<"u"&&y in globalThis)return globalThis[y];if(typeof window<"u"&&y in window)return window[y]}}})),new Function("context",w)(S)}catch(c){console.error("[Dolphin Template Compiler Error]:",c);let r=h;for(let o in d){let u=o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");r=r.replace(new RegExp(`\\{\\{${u}\\}\\}`,"g"),d[o]!==void 0&&d[o]!==null?d[o]:"")}return r}}function i(h){if(typeof document>"u")return h;try{let r=new DOMParser().parseFromString(h,"text/html").body,o=u=>{let b=u.tagName.toLowerCase();if(["script","iframe","object","embed","link","style","meta","applet","svg"].includes(b)){u.parentNode?.removeChild(u);return}let f=u.attributes;for(let m=f.length-1;m>=0;m--){let w=f[m].name.toLowerCase(),S=f[m].value.toLowerCase();(w.startsWith("on")||["src","href","data"].includes(w)&&(S.includes("javascript:")||S.includes("data:text/html")))&&u.removeAttribute(f[m].name)}Array.from(u.children).forEach(o)};return Array.from(r.children).forEach(o),r.innerHTML}catch{return h}}function a(h,d){if(h.nodeType!==d.nodeType){h.parentNode?.replaceChild(d.cloneNode(!0),h);return}if(h.nodeType===Node.TEXT_NODE){h.textContent!==d.textContent&&(h.textContent=d.textContent);return}if(h.nodeType===Node.ELEMENT_NODE){let c=h,r=d;if(c.tagName!==r.tagName){c.parentNode?.replaceChild(r.cloneNode(!0),c);return}let o=c.attributes,u=r.attributes;for(let g=o.length-1;g>=0;g--){let p=o[g].name;r.hasAttribute(p)||c.removeAttribute(p)}for(let g=0;g<u.length;g++){let p=u[g].name,y=u[g].value;c.getAttribute(p)!==y&&c.setAttribute(p,y)}c.tagName==="INPUT"||c.tagName==="TEXTAREA"?(c.value!==r.value&&(c.value=r.value),c.checked!==r.checked&&(c.checked=r.checked)):c.tagName==="SELECT"&&c.value!==r.value&&(c.value=r.value);let b=Array.from(c.childNodes),f=Array.from(r.childNodes),m=b.length,w=f.length,S=Math.max(m,w);for(let g=0;g<S;g++)g>=m?c.appendChild(f[g].cloneNode(!0)):g>=w?c.removeChild(b[g]):a(b[g],f[g])}}function l(h,d){if(typeof document>"u")return;let c=document.createElement(h.tagName);c.innerHTML=d;let r=Array.from(h.childNodes),o=Array.from(c.childNodes),u=r.length,b=o.length,f=Math.max(u,b);for(let m=0;m<f;m++)m>=u?h.appendChild(o[m].cloneNode(!0)):m>=b?h.removeChild(r[m]):a(r[m],o[m])}let _=new Map,v=!1;function k(h,d){_.set(h,d),v||(v=!0,(typeof requestAnimationFrame<"u"?requestAnimationFrame:r=>setTimeout(r,0))(()=>{_.forEach((r,o)=>{o.isConnected!==!1&&l(o,r)}),_.clear(),v=!1}))}A.setStoreState=function(h,d,c){this.uiStores=this.uiStores||new Map,this.uiStores.has(h)||this.uiStores.set(h,{});let r=this.uiStores.get(h);r[d]=c,this.options.debug&&console.log("%c\u{1F4BE} [Dolphin Store Update]:","color: #ec4899; font-weight: bold;",`${h}.${d}`,"=",c),typeof document<"u"&&document.querySelectorAll(`[data-store-read="${h}.${d}"]`).forEach(u=>{u.tagName==="INPUT"||u.tagName==="TEXTAREA"?u.type==="checkbox"?u.checked=!!c:u.value=c??"":u.textContent=c??""}),this.publish(`store/${h}`,r),typeof this._updateDOM=="function"&&this._updateDOM(`store/${h}`,r)},A.getStoreState=function(h,d){this.uiStores=this.uiStores||new Map;let c=this.uiStores.get(h);return c?c[d]:void 0},A._scanStoreBinds=function(){if(typeof document>"u")return;document.querySelectorAll("[data-store-write]").forEach(c=>{let r=c.getAttribute("data-store-write");if(r){let o=r.split(".");if(o.length===2){let u=o[0],b=o[1],f=c.type==="checkbox"?c.checked:c.value;this.uiStores=this.uiStores||new Map,this.uiStores.has(u)||this.uiStores.set(u,{});let m=this.uiStores.get(u);m[b]===void 0&&(m[b]=f)}}}),document.querySelectorAll("[data-store-read]").forEach(c=>{let r=c.getAttribute("data-store-read");if(r){let o=r.split(".");if(o.length===2){let u=o[0],b=o[1],f=this.getStoreState(u,b);f!=null&&(c.tagName==="INPUT"||c.tagName==="TEXTAREA"?c.type==="checkbox"?c.checked=!!f:c.value=f:c.textContent=f)}}})},A.getClosestContext=function(h,d){let c=h;for(;c;){if(c._rtContext){let r=c._rtContext;return d?r[d]:r}c=c.parentElement}return null},A._executeStoreAction=function(h,d){this.uiStores=this.uiStores||new Map;let c=new Proxy({},{has:(r,o)=>!0,get:(r,o)=>{if(typeof o=="string")return new Proxy({},{get:(u,b)=>{if(typeof b=="string")return this.getStoreState(o,b)},set:(u,b,f)=>typeof b=="string"?(this.setStoreState(o,b,f),!0):!1})}});try{new Function("ctx",`with(ctx) { ${h} }`)(c)}catch(r){console.error("%c[Dolphin Store Action Error]:","color: #ef4444; font-weight: bold;",r),d&&console.error("%cFailed Element:","color: #f97316; font-weight: bold;",d),console.error("%cFailed Expression:","color: #3b82f6; font-style: italic;",h)}},A._initDOMBinding=function(){if(this._domInitialized)return;this._domInitialized=!0;let h=["input","change","keyup","paste","blur"],d=new WeakMap;h.forEach(r=>{this.addDomListener(document,r,o=>{if(!o.target||!o.target.getAttribute)return;let u=o.target.getAttribute("data-store-write");if(u){let w=u.split(".");if(w.length===2){let S=w[0],g=w[1],p=o.target.type==="checkbox"?o.target.checked:o.target.value;this.setStoreState(S,g,p)}}let b=o.target.getAttribute("data-rt-validate"),f=o.target.name;if(b&&f&&typeof this.validateField=="function"){let w=o.target.closest("form"),S=w?Object.fromEntries(new FormData(w).entries()):{},g=this.validateField(o.target.value,b,S);g?(o.target.classList.add("invalid"),this.publish(`errors/${f}`,g)):(o.target.classList.remove("invalid"),this.publish(`errors/${f}`,""))}let m=o.target.getAttribute("data-rt-push");if(m){let w=o.target.getAttribute("data-rt-debounce"),S=w?parseInt(w,10):0,g=()=>{let p={name:o.target.name,value:o.target.value};this.pubPush(m,p)};if(S>0){d.has(o.target)&&clearTimeout(d.get(o.target));let p=setTimeout(g,S);d.set(o.target,p)}else g()}})}),this.addDomListener(document,"submit",async r=>{if(!r.target||!r.target.getAttribute)return;let o=r.target.getAttribute("data-rt-submit"),u=r.target.getAttribute("data-api-submit");if(o||u){r.target.querySelectorAll("[name]").forEach(p=>{let y=p.name;y&&(this.publish(`errors/${y}`,""),p.classList.remove("invalid"))});let f=r.target.querySelectorAll("[data-rt-validate]"),m=!0;if(f.length>0&&typeof this.validateField=="function"){let p=Object.fromEntries(new FormData(r.target).entries());f.forEach(y=>{let T=y.getAttribute("data-rt-validate"),D=y.name;if(T&&D){let E=this.validateField(y.value,T,p);E&&(m=!1,y.classList.add("invalid"),this.publish(`errors/${D}`,E))}})}if(!m){r.preventDefault(),r.stopPropagation();return}r.preventDefault();let w=this.getClosestContext(r.target)||{},S=new FormData(r.target),g=Object.fromEntries(S.entries());if(o){let p=o;for(let y in w){let T=e(y);p=p.replace(new RegExp(`\\{\\{${T}\\}\\}`,"g"),w[y]!==void 0&&w[y]!==null?w[y]:"")}this.publish(p,g)}else if(u){let p=u;for(let E in w){let L=e(E);p=p.replace(new RegExp(`\\{\\{${L}\\}\\}`,"g"),w[E]!==void 0&&w[E]!==null?w[E]:"")}let y=p.trim().split(" "),T=y.length>1?y[0].toUpperCase():"POST",D=y.length>1?y[1]:y[0];g._method&&(T=String(g._method).toUpperCase());try{let E=await this.api.request(T,D,g),L=r.target.getAttribute("data-api-result");L&&this._updateDOM(L,E);let M=r.target.getAttribute("data-api-redirect");M&&(window.location.href=M),r.target.hasAttribute("data-api-reload")&&window.location.reload()}catch(E){console.error("[Dolphin] API Submit Error:",E)}}}}),["click","change","submit","input","keydown","keyup","dblclick","focus","blur","mouseenter","mouseleave"].forEach(r=>{this.addDomListener(document,r,async o=>{if(!o.target||!o.target.closest)return;let u=o.target.closest(`[data-rt-${r}]`),b=o.target.closest(`[data-api-${r}]`);if(u){r==="submit"&&o.preventDefault();let m=u.getAttribute(`data-rt-${r}`),w=u.getAttribute("data-rt-payload"),S=this.getClosestContext(u)||{},g={};if(w){let p=w;for(let y in S){let T=e(y);p=p.replace(new RegExp(`\\{\\{${T}\\}\\}`,"g"),S[y]!==void 0&&S[y]!==null?S[y]:"")}try{g=JSON.parse(p)}catch{g={}}}this.publish(m,g)}if(b){r==="submit"&&o.preventDefault();let m=b.getAttribute(`data-api-${r}`),w=b.getAttribute("data-api-payload"),S=this.getClosestContext(b)||{},g=m.trim().split(" "),p=g.length>1?g[0].toUpperCase():"POST",y=g.length>1?g[1]:g[0],T=null;if(w){let D=w;for(let E in S){let L=e(E);D=D.replace(new RegExp(`\\{\\{${L}\\}\\}`,"g"),S[E]!==void 0&&S[E]!==null?S[E]:"")}try{T=JSON.parse(D)}catch{T=null}}try{let D=await this.api.request(p,y,T),E=b.getAttribute("data-api-result");E&&this._updateDOM(E,D);let L=b.getAttribute("data-api-redirect");L&&(window.location.href=L),b.hasAttribute("data-api-reload")&&window.location.reload()}catch(D){console.error(`[Dolphin] API ${r} Error:`,D)}}let f=o.target.closest(`[data-store-${r}]`);if(f){r==="submit"&&o.preventDefault();let m=f.getAttribute(`data-store-${r}`);m&&this._executeStoreAction(m,f)}})}),this.subscribe("#",(r,o)=>{this._updateDOM(o,r)}),this._scanAndFetchAPIBinds(),this._scanStoreBinds(),this._resolveImports(),this._initSPARouter()},A._scanAndFetchAPIBinds=async function(){if(typeof document>"u")return;let h=document.querySelectorAll("[data-api-get]");for(let d of Array.from(h)){let c=d.getAttribute("data-api-get");if(c&&!(typeof d.hasAttribute=="function"&&d.hasAttribute("data-api-initialized"))){typeof d.setAttribute=="function"&&d.setAttribute("data-api-initialized","true");try{let r=await this.api.get(c),o=d.getAttribute("data-api-store");if(o){let b=o.split(".");b.length===2&&this.setStoreState(b[0],b[1],r)}let u=d.getAttribute("data-rt-bind");if(u&&!o)this._updateDOM(u,r);else if(!o){let b=n(d);if(b&&typeof r=="object"&&r!==null){let f=this._applyDeclarativeDirectives(d,r);if(Array.isArray(f)){let m="";for(let w of f)m+=s(b,w);k(d,m)}else k(d,s(b,f))}else if(d.tagName==="INPUT"||d.tagName==="TEXTAREA")d.value=typeof r=="object"?r.value!==void 0?r.value:"":r;else{let f=typeof r=="object"?r.html||r.text||JSON.stringify(r):String(r);d.innerHTML=i(f)}}}catch(r){console.error("[Dolphin] API Get Error:",r)}}}},A._applyDeclarativeDirectives=function(h,d){let c=d;if(typeof d=="object"&&d!==null){let r=o=>{let u=[...o],b=h.getAttribute("data-rt-filter");if(b){let w=b.split("==");if(w.length===2){let S=w[0].trim(),g=w[1].trim(),p,y=g.split(".");y.length===2?p=this.getStoreState(y[0],y[1]):p=d[g]!==void 0?d[g]:this.getStoreState("app",g),p!=null&&p!==""&&(u=u.filter(T=>T[S]===p))}}let f=h.getAttribute("data-rt-search");if(f){let w=f.split("==");if(w.length===2){let S=w[0].trim(),g=w[1].trim(),p,y=g.split(".");if(y.length===2?p=this.getStoreState(y[0],y[1]):p=d[g]!==void 0?d[g]:this.getStoreState("app",g),p!=null&&p!==""){let T=String(p).toLowerCase();u=u.filter(D=>{let E=D[S];return E!=null&&String(E).toLowerCase().includes(T)})}}}let m=h.getAttribute("data-rt-sort");if(m){let w,S=m.split(".");if(S.length===2?w=this.getStoreState(S[0],S[1]):w=d[m]!==void 0?d[m]:this.getStoreState("app",m),w&&w!=="")if(w==="popular")u.sort((g,p)=>{let y=g.rating?.rate||g.rate||0;return(p.rating?.rate||p.rate||0)-y});else{let g="",p="asc";w.endsWith("-low")||w.endsWith("-asc")?(g=w.replace("-low","").replace("-asc",""),p="asc"):(w.endsWith("-high")||w.endsWith("-desc"))&&(g=w.replace("-high","").replace("-desc",""),p="desc"),g&&u.sort((y,T)=>{let D=(J,Q)=>Q.split(".").reduce((q,G)=>q&&q[G],J),E=D(y,g),L=D(T,g);if(E===void 0&&(E=y[g]),L===void 0&&(L=T[g]),typeof E=="string"&&typeof L=="string")return p==="asc"?E.localeCompare(L):L.localeCompare(E);let M=Number(E),I=Number(L);return!isNaN(M)&&!isNaN(I)?p==="asc"?M-I:I-M:0})}}return u};if(Array.isArray(d))c=r(d);else{let o="";for(let u in d)if(Array.isArray(d[u])){o=u;break}if(o){let u=r(d[o]);c={...d,[o]:u}}}}return c},A._updateDOM=function(h,d){if(typeof document>"u")return;document.querySelectorAll(`[data-rt-bind="${h}"]`).forEach(r=>{let o=this._applyDeclarativeDirectives(r,d);if(r.getAttribute("data-rt-type")==="context"&&typeof o=="object"&&o!==null){r._rtContext=o;let b=f=>{if(f.hasAttribute("data-rt-text")){let m=f.getAttribute("data-rt-text");m&&o[m]!==void 0&&o[m]!==null&&(f.textContent=o[m])}if(f.hasAttribute("data-rt-html")){let m=f.getAttribute("data-rt-html");m&&o[m]!==void 0&&o[m]!==null&&(f.innerHTML=i(o[m]))}if(f.hasAttribute("data-rt-attr")){let m=f.getAttribute("data-rt-attr");m&&m.split(",").forEach(w=>{let S=w.split(":");if(S.length===2){let g=S[0].trim(),p=S[1].trim();g&&p&&o[p]!==void 0&&o[p]!==null&&f.setAttribute(g,o[p])}})}if(f.hasAttribute("data-rt-class")){let m=f.getAttribute("data-rt-class");m&&m.split(",").forEach(w=>{let S=w.split(":");if(S.length===2){let g=S[0].trim(),p=S[1].trim(),y=g.split(/\s+/).filter(Boolean);o[p]?y.forEach(T=>f.classList.add(T)):y.forEach(T=>f.classList.remove(T))}})}if(f.hasAttribute("data-rt-if")){let m=f.getAttribute("data-rt-if");m&&(o[m]?f.style.display="":f.style.display="none")}if(f.hasAttribute("data-rt-hide")){let m=f.getAttribute("data-rt-hide");m&&(o[m]?f.style.display="none":f.style.display="")}};b(r),r.querySelectorAll("[data-rt-text], [data-rt-html], [data-rt-attr], [data-rt-class], [data-rt-if], [data-rt-hide]").forEach(b);return}let u=n(r);if(u&&typeof o=="object"&&o!==null){if(Array.isArray(o)){let b="";for(let f of o)b+=s(u,f);k(r,b)}else k(r,s(u,o));return}if(r.tagName==="INPUT"||r.tagName==="TEXTAREA")r.value=typeof o=="object"?o.value!==void 0?o.value:"":o;else if(u)r.innerHTML=typeof o=="object"?o.html||o.text||JSON.stringify(o):String(o);else{let b=typeof o=="object"?o.html||o.text||JSON.stringify(o):String(o);r.innerHTML=i(b)}})},A._resolveImports=async function(h){if(typeof document>"u")return;let d=h||document.body||document;if(!d||typeof d.querySelectorAll!="function")return;let c=d.querySelectorAll("[data-import]");if(c.length===0)return;let r=async(u,b)=>{let f=u.getAttribute("data-import");if(!f)return;if(b.has(f)){console.warn(`[Dolphin Component Warning]: Circular import detected for "${f}". Skipping resolving.`),u.innerHTML=`<span style="color:red;font-weight:bold;">Circular import: ${f}</span>`;return}b.add(f);let m=t.get(f);m||(m=fetch(f).then(g=>{if(!g.ok)throw new Error(`HTTP ${g.status}`);return g.text()}),m.catch(()=>t.delete(f)),t.set(f,m));let w="";try{w=await m}catch(g){console.error(`[Dolphin Component Error]: Failed to fetch component "${f}":`,g),w=`<span style="color:red;font-weight:bold;">Failed to import ${f}</span>`}u.innerHTML=i(w),u.removeAttribute("data-import");let S=u.querySelectorAll("[data-import]");if(S.length>0){let g=Array.from(S).map(p=>r(p,new Set(b)));await Promise.all(g)}this._scanStoreBinds(),this._scanAndFetchAPIBinds()},o=Array.from(c).map(u=>r(u,new Set));await Promise.all(o)},A._initSPARouter=function(){if(typeof window>"u"||typeof document>"u"||this._routerInitialized)return;this._routerInitialized=!0;let h=null,d=()=>{let o=(this.options.routerViewport||"main, #viewport, body").split(",").map(u=>u.trim());for(let u of o){let b=document.querySelector(u);if(b)return b}return document.body},c=async(r,o=!0)=>{try{this.options.debug&&console.log(`%c\u{1F6E3}\uFE0F [Dolphin Router]: Navigating to ${r}...`,"color: #3b82f6; font-weight: bold;"),h&&h.abort(),h=new AbortController;let u=h.signal,b=d();this.options.routerTransitions&&b&&(b.classList.add("dolphin-fade-out"),await new Promise(y=>setTimeout(y,150)));let f=await fetch(r,{signal:u});if(!f.ok)throw new Error(`HTTP ${f.status}`);let m=await f.text();h=null;let S=new DOMParser().parseFromString(m,"text/html");S.title&&(document.title=S.title);let g=S.querySelector(this.options.routerViewport||"main, #viewport, body"),p=d();g&&p?(p.innerHTML=g.innerHTML,Array.from(g.attributes).forEach(y=>{p.setAttribute(y.name,y.value)})):p&&(p.innerHTML=S.body.innerHTML),o&&window.history.pushState({dolphinSpa:!0,url:r},"",r),this.options.routerTransitions&&p&&(p.classList.remove("dolphin-fade-out"),p.classList.add("dolphin-fade-in"),setTimeout(()=>p.classList.remove("dolphin-fade-in"),300)),await this._resolveImports(p),this._scanStoreBinds(),this._scanAndFetchAPIBinds()}catch(u){if(u&&u.name==="AbortError")return;console.error("[Dolphin Router Error]: Failed to route page:",u),window.location.href=r}};if(this.addDomListener(document,"click",r=>{let o=r.target.closest("a");if(!o||!o.hasAttribute("data-spa")&&o.getAttribute("data-spa")!=="true")return;let u=o.getAttribute("href");!u||u.startsWith("#")||u.startsWith("javascript:")||u.startsWith("mailto:")||u.startsWith("tel:")||new URL(u,window.location.href).origin!==window.location.origin||(r.preventDefault(),c(u))}),this.addDomListener(window,"popstate",r=>{r.state&&r.state.dolphinSpa?c(r.state.url,!1):r.state===null&&c(window.location.pathname,!1)}),this.options.routerTransitions){let r=document.createElement("style");r.innerHTML=`
27
+ .dolphin-fade-out {
28
+ opacity: 0;
29
+ transition: opacity 0.15s ease-in-out;
30
+ }
31
+ .dolphin-fade-in {
32
+ opacity: 0;
33
+ }
34
+ main, #viewport, body {
35
+ transition: opacity 0.15s ease-in-out;
36
+ }
37
+ `,document.head.appendChild(r)}}}var N=class{client;db;isOnline;memoryCache=new Map;memoryMutations=[];constructor(t){this.client=t,this.isOnline=typeof window<"u"&&typeof navigator<"u"?navigator.onLine:!0,this.initDB(),this.setupNetworkListeners()}initDB(){if(!(typeof indexedDB>"u"))try{let t=indexedDB.open("dolphin_offline",1);t.onupgradeneeded=e=>{let n=e.target.result;n.objectStoreNames.contains("cache")||n.createObjectStore("cache"),n.objectStoreNames.contains("mutations")||n.createObjectStore("mutations",{keyPath:"id",autoIncrement:!0})},t.onsuccess=e=>{this.db=e.target.result,this.isOnline&&this.syncMutations()}}catch(t){console.warn("[Dolphin Offline] Failed to initialize IndexedDB:",t)}}setupNetworkListeners(){typeof window>"u"||(this.client.addDomListener(window,"online",()=>{this.isOnline=!0,this.client._dispatch("network:status",{online:!0}),this.syncMutations()}),this.client.addDomListener(window,"offline",()=>{this.isOnline=!1,this.client._dispatch("network:status",{online:!1})}))}async getCache(t){return this.db?new Promise(e=>{try{let i=this.db.transaction("cache","readonly").objectStore("cache").get(t);i.onsuccess=()=>e(i.result?i.result.data:null),i.onerror=()=>e(null)}catch{e(null)}}):this.memoryCache.get(t)}async setCache(t,e){if(!this.db){this.memoryCache.set(t,e);return}return new Promise(n=>{try{let s=this.db.transaction("cache","readwrite");s.objectStore("cache").put({data:e,timestamp:Date.now()},t),s.oncomplete=()=>n(),s.onerror=()=>{console.warn("[Dolphin Offline] setCache write failed for key:",t),n()}}catch{n()}})}async queueMutation(t,e,n){let s={method:t,path:e,payload:n,timestamp:Date.now()};if(!this.db){this.memoryMutations.push(s);return}return new Promise(i=>{try{let a=this.db.transaction("mutations","readwrite");a.objectStore("mutations").add(s),a.oncomplete=()=>i(),a.onerror=()=>{console.warn("[Dolphin Offline] queueMutation write failed:",t,e),this.memoryMutations.push(s),i()}}catch{i()}})}async getMutations(){return this.db?new Promise(t=>{try{let s=this.db.transaction("mutations","readonly").objectStore("mutations").getAll();s.onsuccess=()=>t(s.result||[]),s.onerror=()=>t([])}catch{t([])}}):[...this.memoryMutations]}async removeMutation(t){if(!this.db){this.memoryMutations=this.memoryMutations.filter(e=>e.id!==t);return}return new Promise(e=>{try{let n=this.db.transaction("mutations","readwrite");n.objectStore("mutations").delete(t),n.oncomplete=()=>e(),n.onerror=()=>{console.warn("[Dolphin Offline] removeMutation failed for id:",t),e()}}catch{e()}})}async syncMutations(){let t=await this.getMutations();if(t.length!==0){console.log(`[Dolphin Offline] Syncing ${t.length} queued mutations...`);for(let e of t)try{await this.client.api.requestDirect(e.method,e.path,e.payload),e.id!==void 0?await this.removeMutation(e.id):this.memoryMutations.shift()}catch(n){if(console.error(`[Dolphin Offline] Sync failed for mutation ${e.method} ${e.path}:`,n),n&&n.status&&n.status>=400&&n.status<500)console.warn("[Dolphin Offline] Discarding invalid mutation."),e.id!==void 0?await this.removeMutation(e.id):this.memoryMutations.shift();else break}}}};function H(A){A._initOffline=function(){this.offline=new N(this)}}function it(A,t,e){let n=t.split(",");for(let s of n){let i=s.trim().split(":"),a=i[0],l=i[1];if(a==="required"){if(!A||A.trim()==="")return"This field is required"}else if(a==="email"){if(A&&A.trim()!==""&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(A))return"Please enter a valid email address"}else if(a==="min"){let _=parseInt(l,10);if(!A||A.length<_)return`Must be at least ${_} characters`}else if(a==="match"&&e&&A!==e[l])return`Must match ${l}`}return null}function F(A){A.validateField=it}function W(A){A.animateElement=function(t,e,n=300){if(typeof t.animate!="function"){t.classList.add(e),setTimeout(()=>t.classList.remove(e),n);return}e==="fade-in"?t.animate([{opacity:0,transform:"translateY(10px)"},{opacity:1,transform:"translateY(0)"}],{duration:n,easing:"ease-out"}):e==="fade-out"&&t.animate([{opacity:1,transform:"translateY(0)"},{opacity:0,transform:"translateY(10px)"}],{duration:n,easing:"ease-in"})},A.staggerListItems=function(t,e,n=50){if(typeof document>"u")return;t.querySelectorAll(e).forEach((i,a)=>{i.style.animationDelay=`${a*n}ms`,i.classList.add("staggered-item")})}}function j(A){A._initA11y=function(){typeof document>"u"||(this.addDomListener(document,"keydown",t=>{if(t.key!=="Tab")return;document.querySelectorAll("[data-rt-a11y-focus-trap]").forEach(n=>{if(n.style.display==="none"||n.hasAttribute("aria-hidden")&&n.getAttribute("aria-hidden")==="true")return;let i=Array.from(n.querySelectorAll('a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, [tabindex="0"], [contenteditable]'));if(i.length===0)return;let a=i[0],l=i[i.length-1];t.shiftKey?document.activeElement===a&&(l.focus(),t.preventDefault()):document.activeElement===l&&(a.focus(),t.preventDefault())})}),this.addDomListener(document,"keydown",t=>{if(!["ArrowUp","ArrowDown","Enter"].includes(t.key))return;document.querySelectorAll("[data-rt-keynav]").forEach(n=>{let s=Array.from(n.children);if(s.length===0)return;let i=s.findIndex(a=>a.classList.contains("active")||document.activeElement===a);t.key==="ArrowDown"?(i=(i+1)%s.length,s[i].focus(),s.forEach((a,l)=>{l===i?a.classList.add("active"):a.classList.remove("active")}),t.preventDefault()):t.key==="ArrowUp"?(i=(i-1+s.length)%s.length,s[i].focus(),s.forEach((a,l)=>{l===i?a.classList.add("active"):a.classList.remove("active")}),t.preventDefault()):t.key==="Enter"&&i!==-1&&(s[i].click(),t.preventDefault())})}))},A.autoAriaModal=function(t,e){e?(t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-hidden","false"),t.focus()):t.setAttribute("aria-hidden","true")}}function B(A){A._initI18n=function(){if(this.i18n=this.i18n||{locale:"en",dicts:{}},typeof document>"u")return;if(document.querySelectorAll("[data-i18n-dict]").forEach(e=>{let n=e.getAttribute("data-i18n-dict");if(n)try{let s=JSON.parse(e.textContent||"{}");this.i18n.dicts[n]={...this.i18n.dicts[n]||{},...s}}catch(s){console.warn("[Dolphin i18n] Failed to parse dictionary for locale:",n,s)}}),!this.i18n.locale&&typeof navigator<"u"){let e=navigator.language.split("-")[0];this.i18n.dicts[e]&&(this.i18n.locale=e)}this.addDomListener(document,"click",e=>{let n=e.target.closest("[data-i18n-switch]");if(n){let s=n.getAttribute("data-i18n-switch");s&&this.setLocale(s)}}),this.translateDOM()},A.setLocale=function(t){this.i18n=this.i18n||{locale:"en",dicts:{}},this.i18n.locale=t,this.translateDOM(),this.publish("i18n/locale",t)},A.translateDOM=function(){if(typeof document>"u")return;this.i18n=this.i18n||{locale:"en",dicts:{}};let t=this.i18n.locale||"en",e=this.i18n.dicts[t]||{};document.querySelectorAll("[data-i18n-key]").forEach(s=>{let i=s.getAttribute("data-i18n-key");if(!i)return;let a=i.split(".").reduce((_,v)=>_?_[v]:null,e);a==null&&(a=i);let l=s.getAttribute("data-i18n-params");if(l)try{let _=JSON.parse(l),v=k=>k.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");for(let k in _){let h=v(k);a=a.replace(new RegExp(`\\{\\{${h}\\}\\}`,"g"),_[k])}}catch{}s.tagName==="INPUT"||s.tagName==="TEXTAREA"?s.placeholder=a:s.textContent=a})}}function V(A){A._initDragDrop=function(){typeof document>"u"||(this.addDomListener(document,"dragstart",t=>{let e=t.target.closest("[data-drag]");if(!e)return;let n=e.getAttribute("data-drag");n&&(t.dataTransfer.setData("text/plain",n),t.dataTransfer.effectAllowed="move",e.classList.add("dragging"))}),this.addDomListener(document,"dragend",t=>{let e=t.target.closest("[data-drag]");e&&e.classList.remove("dragging")}),this.addDomListener(document,"dragover",t=>{let e=t.target.closest("[data-drop]");e&&(t.preventDefault(),e.classList.add("drag-over"))}),this.addDomListener(document,"dragleave",t=>{let e=t.target.closest("[data-drop]");e&&e.classList.remove("drag-over")}),this.addDomListener(document,"drop",t=>{let e=t.target.closest("[data-drop]");if(!e)return;t.preventDefault(),e.classList.remove("drag-over");let n=e.getAttribute("data-drop"),s=t.dataTransfer.getData("text/plain");if(n&&s)try{let i=JSON.parse(s);this.publish(n,i)}catch{this.publish(n,{value:s})}}),this.addDomListener(document,"dragover",t=>{let e=t.target.closest("[data-sortable]");if(!e)return;t.preventDefault();let n=e.querySelector(".dragging");if(!n)return;let i=Array.from(e.querySelectorAll("[data-drag]:not(.dragging)")).find(a=>{let l=a.getBoundingClientRect();return t.clientY-l.top-l.height/2<0});i?e.insertBefore(n,i):e.appendChild(n)}),this.addDomListener(document,"drop",t=>{let e=t.target.closest("[data-sortable]");if(!e)return;let n=e.getAttribute("data-sortable");if(!n)return;let i=Array.from(e.querySelectorAll("[data-drag]")).map((a,l)=>{let _=a.getAttribute("data-drag");try{return{index:l,payload:JSON.parse(_||"{}")}}catch{return{index:l,payload:_}}});this.publish(n,i)}))}}function z(A){A._initCollab=function(){if(typeof document>"u")return;let t=new Map,e=new Map,n=5e3;this.addDomListener(document,"mousemove",s=>{document.querySelectorAll("[data-rt-cursor-share]").forEach(a=>{let l=a.getAttribute("data-rt-cursor-share");if(!l)return;let _=a.getBoundingClientRect(),v=(s.clientX-_.left)/_.width,k=(s.clientY-_.top)/_.height,h=Date.now();(!a._lastSent||h-a._lastSent>50)&&(a._lastSent=h,this.pubPush(`collab/${l}/cursor/${this.deviceId}`,{deviceId:this.deviceId,x:v,y:k}))})}),this.addDomListener(document,"input",s=>{let i=s.target.getAttribute("data-rt-typing");if(!i)return;let a=i,l=_=>{this.pubPush(`collab/${a}/typing/${this.deviceId}`,{deviceId:this.deviceId,typing:_})};s.target._isTyping||(s.target._isTyping=!0,l(!0)),s.target._typingTimer&&clearTimeout(s.target._typingTimer),s.target._typingTimer=setTimeout(()=>{s.target._isTyping=!1,s.target._typingTimer=null,l(!1)},2e3)}),this.addDomListener(document,"input",s=>{let i=s.target.getAttribute("data-rt-crdt");if(!i)return;let a=i,l=s.target.value,_=Date.now();this.publish(`collab/${a}/crdt`,{deviceId:this.deviceId,value:l,timestamp:_,cursorPos:s.target.selectionStart})}),this.subscribe("collab/+/cursor/+",(s,i)=>{let a=i.split("/"),l=a[1],_=a[3];if(_===this.deviceId)return;let v=document.querySelector(`[data-rt-cursor-share="${l}"]`);if(!v)return;let k=`${l}::${_}`,h=t.get(k);(!h||!document.contains(h))&&(h=document.createElement("div"),h.className=`rt-cursor rt-cursor-${_}`,h.style.position="absolute",h.style.width="10px",h.style.height="10px",h.style.borderRadius="50%",h.style.backgroundColor="#"+Math.floor(Math.random()*16777215).toString(16).padStart(6,"0"),h.style.pointerEvents="none",v.appendChild(h),t.set(k,h));let d=v.getBoundingClientRect();h.style.left=s.x*d.width+"px",h.style.top=s.y*d.height+"px",e.has(k)&&clearTimeout(e.get(k)),e.set(k,setTimeout(()=>{let c=t.get(k);c&&c.parentNode&&c.parentNode.removeChild(c),t.delete(k),e.delete(k)},n))}),this.subscribe("collab/+/crdt",(s,i)=>{if(s.deviceId===this.deviceId)return;let l=i.split("/")[1];document.querySelectorAll(`[data-rt-crdt="${l}"]`).forEach(v=>{if(!v._lastUpdate||s.timestamp>v._lastUpdate){v._lastUpdate=s.timestamp;let k=v.selectionStart;v.value=s.value,document.activeElement===v&&v.setSelectionRange(k,k)}})}),this._collabCleanup=()=>{e.forEach(s=>clearTimeout(s)),e.clear(),t.forEach(s=>{s&&s.parentNode&&s.parentNode.removeChild(s)}),t.clear()}}}function K(A){A.registerServiceWorker=async function(t="/sw.js"){if(typeof navigator>"u"||!("serviceWorker"in navigator))return console.warn("[Dolphin PWA] Service Workers are not supported in this browser."),null;try{let e=await navigator.serviceWorker.register(t);return console.log("[Dolphin PWA] Service Worker registered successfully with scope:",e.scope),e}catch(e){return console.error("[Dolphin PWA] Service Worker registration failed:",e),null}},A.subscribePushNotifications=async function(t){if(typeof window>"u"||!("serviceWorker"in navigator)||!("PushManager"in window))return console.warn("[Dolphin PWA] Push notifications are not supported in this browser."),null;try{let e=await navigator.serviceWorker.ready,n=await e.pushManager.getSubscription();if(!n){let s="=".repeat((4-t.length%4)%4),i=(t+s).replace(/\-/g,"+").replace(/_/g,"/"),a=window.atob(i),l=new Uint8Array(a.length);for(let _=0;_<a.length;++_)l[_]=a.charCodeAt(_);n=await e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:l})}return console.log("[Dolphin PWA] Subscribed to push notifications:",n),n}catch(e){return console.error("[Dolphin PWA] Push notification subscription failed:",e),null}}}var O=class{static render(t){if(typeof document>"u")throw new Error("DolphinTestUtils.render requires a DOM document environment to execute.");let e=document.createElement("div");return e.innerHTML=t,document.body.appendChild(e),{container:e,find:n=>e.querySelector(n),fireEvent:(n,s)=>{let i=document.createEvent("Event");i.initEvent(s,!0,!0),n.dispatchEvent(i)}}}static mockWebSocket(){let t=[],e={readyState:1,send:n=>{t.push(n)},close:jest.fn(),onopen:jest.fn(),onmessage:jest.fn(),onclose:jest.fn(),onerror:jest.fn(),sentMessages:t};return global.WebSocket=class{static OPEN=1;readyState=e.readyState;send=e.send;close=e.close;set onopen(n){e.onopen=n}get onopen(){return e.onopen}set onmessage(n){e.onmessage=n}get onmessage(){return e.onmessage}set onclose(n){e.onclose=n}get getonclose(){return e.onclose}constructor(){setTimeout(()=>e.onopen&&e.onopen(),0)}},e}static simulateClick(t){let e={target:t,preventDefault:jest.fn(),stopPropagation:jest.fn()};(global.document._listeners?.click||[]).forEach(s=>s(e))}static simulateChange(t,e){t.value=e;let n={target:t,preventDefault:jest.fn(),stopPropagation:jest.fn()};(global.document._listeners?.change||[]).forEach(i=>i(n))}};function X(A){A.testing=O}U(C.prototype);H(C.prototype);F(C.prototype);W(C.prototype);j(C.prototype);B(C.prototype);V(C.prototype);z(C.prototype);K(C.prototype);X(C.prototype);typeof window<"u"&&(window.DolphinClient=C,document.addEventListener("DOMContentLoaded",()=>{if(!window.dolphin){let A=document.querySelector('script[src*="dolphin-client"]'),t=A?A.getAttribute("data-debug")==="true":!1,e=new C(void 0,void 0,{debug:t});window.dolphin=e,t&&(console.log("%c\u{1F42C} [Dolphin Client] Auto-initialized local reactive engine!","color: #06b6d4; font-weight: bold; font-size: 14px;"),console.log('%c\u{1F449} Tip: You can access the client instance via "window.dolphin" in console.',"color: #94a3b8; font-style: italic;")),document.querySelector('[data-store-write="app.username"]')&&e.setStoreState("app","username","\u0928\u092E\u0938\u094D\u0924\u0947 \u0938\u093E\u0925\u0940!")}}));return st(rt);})();