entity-client 1.0.27 → 1.0.28

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.
package/dist/react.js CHANGED
@@ -1,2 +1,2 @@
1
- import{useCallback as O,useEffect as Ce,useMemo as Ne,useRef as xe,useState as Ee}from"react";function _(r,n){let{singleton:e=!0,tokenResolver:t,baseUrl:s,token:i,resumeSession:o}=r,[a,u]=Ee(!1),[m,g]=Ee(null),h=xe(!0);Ce(()=>(h.current=!0,()=>{h.current=!1}),[]);let k=Ne(()=>{let p=e?n.singletonInstance:new n.ClientClass({baseUrl:s,token:i});e&&p.configure({baseUrl:s,token:i});let d=t?.();return typeof d=="string"&&p.setToken(d),p},[e,t,s,i,n.ClientClass,n.singletonInstance]),R=xe(o);Ce(()=>{if(R.current){if(k.checkHealth){k.checkHealth(!0).catch(()=>{});return}k.refreshToken(R.current).catch(()=>{})}},[k]);let T=O(async p=>{h.current&&(u(!0),g(null));try{return await p()}catch(d){let y=d instanceof Error?d:new Error(String(d));throw h.current&&g(y),y}finally{h.current&&u(!1)}},[]),S=O((p,d,y)=>T(()=>k.submit(p,d,y)),[k,T]),F=O((p,d,y)=>T(()=>k.delete(p,d,y)),[k,T]),D=O((p,d)=>T(()=>k.query(p,d)),[k,T]),j=O(()=>{u(!1),g(null)},[]);return{client:k,isPending:a,error:m,reset:j,submit:S,del:F,query:D}}function V(r){let n=import.meta;if(n?.env?.[r]!=null)return n.env[r];let e=globalThis.process;if(e?.env?.[r]!=null)return e.env[r]}function l(r){return Object.entries(r).filter(([,n])=>n!=null).map(([n,e])=>`${encodeURIComponent(n==="orderBy"?"order_by":n)}=${encodeURIComponent(String(e))}`).join("&")}import{xchacha20poly1305 as Ae}from"@noble/ciphers/chacha";import{sha256 as Ve}from"@noble/hashes/sha2";import{hkdf as We}from"@noble/hashes/hkdf";var W=32,z=2,Q=14,x=24,ze=16,Qe="entity-server:hkdf:v1",Xe="entity-server:packet-encryption";function U(r){return r instanceof Uint8Array?r:new Uint8Array(r)}function Be(r,n=Xe){return We(Ve,new TextEncoder().encode(r),new TextEncoder().encode(Qe),new TextEncoder().encode(n),W)}function qe(r,n=z,e=Q){let t=U(r);return t.length<W?n:n+t[W-1]%e}function $e(r,n,e=z,t=Q){let s=U(r),i=U(n),o=qe(i,e,t),a=crypto.getRandomValues(new Uint8Array(o)),u=crypto.getRandomValues(new Uint8Array(x)),g=Ae(i,u).encrypt(s),h=new Uint8Array(o+x+g.length);return h.set(a,0),h.set(u,o),h.set(g,o+x),h}function Oe(r,n,e=z,t=Q){let s=U(r),i=U(n),o=qe(i,e,t);if(s.length<o+x+ze)throw new Error("Encrypted packet too short");let a=s.slice(o,o+x),u=s.slice(o+x);return Ae(i,a).decrypt(u)}function M(r,n){return Be(r||n)}function Ue(r,n){return $e(r,n)}function I(r,n){let e=Oe(r,n);return JSON.parse(new TextDecoder().decode(e))}function Me(r,n,e,t){let s=n.toLowerCase().includes("application/octet-stream");if(e&&!s)throw new Error("Encrypted request required: Content-Type must be application/octet-stream");if(s){if(r==null)throw new Error("Encrypted request body is empty");if(r instanceof ArrayBuffer)return I(r,t);if(r instanceof Uint8Array){let i=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength);return I(i,t)}throw new Error("Encrypted request body must be ArrayBuffer or Uint8Array")}return r==null||r===""?{}:typeof r=="string"?JSON.parse(r):r}import{sha256 as Je}from"@noble/hashes/sha2";import{hmac as Ye}from"@noble/hashes/hmac";function Le(r,n,e,t,s){let i=String(Math.floor(Date.now()/1e3)),o=crypto.randomUUID(),a=new TextEncoder().encode(`${r}|${n}|${i}|${o}|`),u=new Uint8Array(a.length+e.length);u.set(a,0),u.set(e,a.length);let g=[...Ye(Je,new TextEncoder().encode(s),u)].map(h=>h.toString(16).padStart(2,"0")).join("");return{"X-API-Key":t,"X-Timestamp":i,"X-Nonce":o,"X-Signature":g}}function Ze(r){switch(r.toUpperCase()){case"POST":case"PUT":case"PATCH":case"DELETE":return!0;default:return!1}}function et(r,n,e){if(e.autoAbortKey===!1)return null;if(typeof e.autoAbortKey=="string"){let t=e.autoAbortKey.trim();return t||null}return typeof window>"u"?null:Ze(r)?`${r.toUpperCase()} ${n}`:null}function tt(r){let n=r.filter(s=>!!s);if(n.length===0)return;if(n.length===1)return n[0];if(typeof AbortSignal.any=="function")return AbortSignal.any(n);let e=new AbortController,t=()=>e.abort();for(let s of n){if(s.aborted){e.abort();break}s.addEventListener("abort",t,{once:!0})}return e.signal}function nt(r,n,e,t){let s=et(n,e,t);if(!s)return{signal:t.signal,abortKey:null,controller:null};r.requestAbortControllers.get(s)?.abort();let i=new AbortController;return r.requestAbortControllers.set(s,i),{signal:tt([t.signal,i.signal]),abortKey:s,controller:i}}function rt(r,n,e){!n||!e||r.requestAbortControllers.get(n)===e&&r.requestAbortControllers.delete(n)}function st(r){return r.hmacSecret||r.token||r.anonymousPacketToken}function it(r,n,e){return r.hmacSecret?r.hmacSecret:n&&r.token||e}function ot(r){return r?r.length<=8?`${r.slice(0,2)}...${r.slice(-2)}`:`${r.slice(0,4)}...${r.slice(-4)}`:""}function at(r){typeof console>"u"||typeof console.error!="function"||console.error("[entity-client] packet decrypt failed",{method:r.method,path:r.path,withAuth:r.withAuth,status:r.status,contentType:r.contentType,responsePacketSource:ot(r.responsePacketSource),tokenPresent:r.tokenPresent,anonymousPacketTokenPresent:r.anonymousPacketTokenPresent,hmacEnabled:r.hmacEnabled,error:r.error instanceof Error?{name:r.error.name,message:r.error.message,stack:r.error.stack}:r.error})}function ut(r){return r!=="GET"&&r!=="HEAD"&&r!=="OPTIONS"}function H(r){if(typeof document>"u")return"";for(let n of document.cookie.split(";")){let e=n.indexOf("=");if(!(e<0)&&n.substring(0,e).trim()===r)return decodeURIComponent(n.substring(e+1).trim())}return""}function ct(r,n){return r===403&&/csrf/i.test(n)?!0:/csrf/i.test(n)&&/expired|token validation failed/i.test(n)}function lt(r,n){return r===401&&/nonce already used/i.test(n)}async function _e(r){if((r.headers.get("Content-Type")??"").includes("application/json")){let t=await r.json().catch(()=>null);if(t?.error)return{message:t.error,code:t.code,body:t};if(t?.message)return{message:t.message,code:t.code,body:t}}return{message:await r.text().catch(()=>"")||`HTTP ${r.status}`}}function X(r,n){let e=new Error(n.message);return e.status=r,n.code&&(e.code=n.code),n.body&&(e.details=n.body),e}async function w(r,n,e,t,s=!0,i={},o=!0){let a=typeof o=="boolean"?{requireOkShape:o}:o,u=a.requireOkShape??!0,m=new Set(a.allowStatuses??[]),g=nt(r,n,e,a),h=g.signal,{baseUrl:k,token:R,apiKey:T,hmacSecret:S,encryptRequests:F,csrfEnabled:D,csrfHeaderName:j,csrfCookieName:p,refreshCsrfCookie:d,onAccessToken:y,debugPlainSecret:K}=r,A=r.anonymousPacketToken||H("anon_token"),B=s&&!!(T&&S),Fe=st(r),we=it(r,s,A),L=D&&ut(n)&&!B,C=L?H(p):"",ve="application/json",De=!B&&!!A,P=null;if(t!=null)if(!K&&F&&!!Fe&&s&&n!=="GET"&&n!=="HEAD"){let f=M(S,R||A);P=Ue(new TextEncoder().encode(JSON.stringify(t)),f),ve="application/octet-stream"}else P=JSON.stringify(t);let je=c=>{let f={...i},q=Object.keys(f).some(b=>b.toLowerCase()==="content-type");if(P!=null&&!q&&(f["Content-Type"]=ve),!B&&s&&R&&(f.Authorization=`Bearer ${R}`),De&&(f["X-Packet-Token"]=A),K&&(f["X-Debug-Plain"]=K),L&&c&&(f[j]=c),B){let b=P instanceof Uint8Array?P:typeof P=="string"?new TextEncoder().encode(P):new Uint8Array(0);Object.assign(f,Le(n,e,b,T,S))}return f};L&&!C&&d&&(await d(),C=H(p));let N=c=>fetch(k+e,{method:n,headers:je(c),...P!=null?{body:P}:{},credentials:"include",signal:h});try{let c=await N(C);if(!c.ok){let $=await _e(c.clone());if(B&&lt(c.status,$.message))c=await N(C);else if(L&&d&&ct(c.status,$.message))await d(),C=H(p),c=await N(C);else if(!m.has(c.status))throw X(c.status,$)}if(!c.ok&&!m.has(c.status))throw X(c.status,await _e(c));let f=c.headers.get("X-Access-Token")?.trim()??"",q=c.headers.get("Content-Type")??"";if(q.includes("application/octet-stream")){let $=M(S,we),Ke=await c.arrayBuffer(),Re;try{Re=I(Ke,$)}catch(Se){throw at({method:n,path:e,withAuth:s,status:c.status,contentType:q,responsePacketSource:we,tokenPresent:!!R,anonymousPacketTokenPresent:!!A,hmacEnabled:!!S,error:Se}),Se}return f&&y?.(f),Re}if(f&&y?.(f),!q.includes("application/json"))return await c.text();let b=await c.json();if(u&&!b.ok&&!m.has(c.status))throw X(c.status,{message:b.message??`EntityServer error (HTTP ${c.status})`,code:b.code,body:b});return b}finally{rt(r,g.abortKey,g.controller)}}var J="/v1/realtime",G=class{baseUrl;token;anonymousPacketToken;apiKey;hmacSecret;encryptRequests;debugPlainSecret;csrfEnabled;csrfHeaderName;csrfCookieName;csrfRefresher=null;requestAbortControllers=new Map;activeTxId=null;initialHealthFired=!1;keepSession;refreshBuffer;onTokenRefreshed;onSessionExpired;onHealthChange;sessionRefreshToken=null;refreshTimer=null;healthTickTimer=null;healthTickPromise=null;realtimeEnabled;realtimePath;realtimeAutoReconnect;realtimeReconnectDelayMs;realtimeStatus;realtimeSocket=null;realtimeConnectPromise=null;realtimeReconnectTimer=null;realtimeShouldReconnect=!1;realtimeMessageListeners=new Set;realtimeStatusListeners=new Set;realtimeEventListeners=new Map;constructor(n={}){let e=V("VITE_ENTITY_SERVER_URL");this.baseUrl=(n.baseUrl??e??"").replace(/\/$/,""),this.token=n.token??"",this.anonymousPacketToken=n.anonymousPacketToken??"",this.apiKey=n.apiKey??"",this.hmacSecret=n.hmacSecret??"",this.encryptRequests=n.encryptRequests??!1,this.debugPlainSecret=n.debugPlainSecret??"",this.csrfEnabled=n.csrfEnabled??!1,this.csrfHeaderName=n.csrfHeaderName??"x-csrf-token",this.csrfCookieName=n.csrfCookieName??"_csrf",this.keepSession=n.keepSession??!1,this.refreshBuffer=n.refreshBuffer??60,this.onTokenRefreshed=n.onTokenRefreshed,this.onSessionExpired=n.onSessionExpired,this.onHealthChange=n.onHealthChange,this.realtimeEnabled=!1,this.realtimePath=J,this.realtimeAutoReconnect=!0,this.realtimeReconnectDelayMs=3e3,this.realtimeStatus="idle",this.applyRealtimeOptions(n.realtime),typeof n.healthTickInterval=="number"&&n.healthTickInterval>0&&Promise.resolve().then(()=>this.startHealthTick(n.healthTickInterval,!1)),this.fireInitialHealth()}configure(n){typeof n.baseUrl=="string"&&(this.baseUrl=n.baseUrl.replace(/\/$/,"")),typeof n.token=="string"&&(this.token=n.token),typeof n.anonymousPacketToken=="string"&&(this.anonymousPacketToken=n.anonymousPacketToken),typeof n.encryptRequests=="boolean"&&(this.encryptRequests=n.encryptRequests),typeof n.debugPlainSecret=="string"&&(this.debugPlainSecret=n.debugPlainSecret),typeof n.csrfEnabled=="boolean"&&(this.csrfEnabled=n.csrfEnabled),typeof n.csrfHeaderName=="string"&&(this.csrfHeaderName=n.csrfHeaderName),typeof n.csrfCookieName=="string"&&(this.csrfCookieName=n.csrfCookieName),typeof n.apiKey=="string"&&(this.apiKey=n.apiKey),typeof n.hmacSecret=="string"&&(this.hmacSecret=n.hmacSecret),typeof n.keepSession=="boolean"&&(this.keepSession=n.keepSession),typeof n.refreshBuffer=="number"&&(this.refreshBuffer=n.refreshBuffer),n.onTokenRefreshed&&(this.onTokenRefreshed=n.onTokenRefreshed),n.onSessionExpired&&(this.onSessionExpired=n.onSessionExpired),n.onHealthChange&&(this.onHealthChange=n.onHealthChange),typeof n.realtime<"u"&&this.applyRealtimeOptions(n.realtime),typeof n.healthTickInterval=="number"&&n.healthTickInterval>0&&Promise.resolve().then(()=>this.startHealthTick(n.healthTickInterval,!1)),this.fireInitialHealth()}fireInitialHealth(){if(this.initialHealthFired||typeof document>"u"||!this.baseUrl)return;this.initialHealthFired=!0;let n=this;typeof n.checkHealth=="function"&&Promise.resolve().then(()=>n.checkHealth(!1).catch(()=>{}))}setToken(n){this.token=n,this.syncRealtimeWithToken()}setAccessTokenFromResponse(n){this.token=n,this.syncRealtimeWithToken()}syncRealtimeWithToken(){if(!this.token){this.disconnectRealtime("token_cleared");return}!this.realtimeEnabled||typeof WebSocket>"u"||this.connectRealtime().catch(()=>{})}setAnonymousPacketToken(n){this.anonymousPacketToken=n}setApiKey(n){this.apiKey=n}setHmacSecret(n){this.hmacSecret=n}setEncryptRequests(n){this.encryptRequests=n}setCsrfEnabled(n){this.csrfEnabled=n}addRealtimeListener(n){this.realtimeMessageListeners.add(n)}removeRealtimeListener(n){this.realtimeMessageListeners.delete(n)}addRealtimeStatusListener(n){this.realtimeStatusListeners.add(n)}removeRealtimeStatusListener(n){this.realtimeStatusListeners.delete(n)}addRealtimeEventListener(n,e){let t=String(n).trim();t&&(this.realtimeEventListeners.has(t)||this.realtimeEventListeners.set(t,new Set),this.realtimeEventListeners.get(t).add(e))}removeRealtimeEventListener(n,e){let t=String(n).trim();if(!t)return;let s=this.realtimeEventListeners.get(t);s&&(s.delete(e),s.size===0&&this.realtimeEventListeners.delete(t))}async connectRealtime(){if(!this.realtimeEnabled){this.setRealtimeStatus("disabled","realtime_disabled");return}if(!this.token)throw new Error("Cannot open realtime connection without access token.");if(typeof WebSocket>"u")throw new Error("WebSocket is not available in this environment.");if(this.realtimeSocket&&this.realtimeSocket.readyState===WebSocket.OPEN)return;if(this.realtimeSocket&&this.realtimeSocket.readyState===WebSocket.CONNECTING&&this.realtimeConnectPromise)return this.realtimeConnectPromise;this.clearRealtimeReconnectTimer(),this.realtimeShouldReconnect=this.realtimeAutoReconnect,this.setRealtimeStatus("connecting","connect_requested");let n=new WebSocket(this.buildRealtimeUrl());return this.realtimeSocket=n,this.realtimeConnectPromise=new Promise((e,t)=>{let s=!1,i=()=>{s||(s=!0,this.realtimeConnectPromise=null,e())},o=a=>{s||(s=!0,this.realtimeConnectPromise=null,t(a))};n.addEventListener("open",()=>{this.setRealtimeStatus("open","socket_open"),i()}),n.addEventListener("message",a=>{this.handleRealtimeMessage(a.data)}),n.addEventListener("error",()=>{this.setRealtimeStatus("closed","socket_error",new Error("Realtime socket error."))}),n.addEventListener("close",a=>{this.realtimeSocket===n&&(this.realtimeSocket=null);let u=a.reason||"socket_closed",m=new Error(`Realtime socket closed (${a.code}${a.reason?`: ${a.reason}`:""}).`);this.setRealtimeStatus("closed",u,m),s||o(m),this.realtimeShouldReconnect&&this.realtimeEnabled&&this.realtimeAutoReconnect&&this.token&&this.scheduleRealtimeReconnect(u)})}),this.realtimeConnectPromise}disconnectRealtime(n="client_disconnect"){if(this.realtimeShouldReconnect=!1,this.clearRealtimeReconnectTimer(),this.realtimeSocket){let e=this.realtimeSocket;this.realtimeSocket=null;try{(e.readyState===WebSocket.OPEN||e.readyState===WebSocket.CONNECTING)&&e.close(1e3,n)}catch{}}this.realtimeConnectPromise=null,this.setRealtimeStatus(this.realtimeEnabled?"idle":"disabled",n)}sendRealtime(n){return!this.realtimeSocket||this.realtimeSocket.readyState!==WebSocket.OPEN?!1:(this.realtimeSocket.send(JSON.stringify(n)),!0)}subscribeRealtime(n){return this.sendRealtime({type:"subscribe",channel:"session",event:"session.subscribe",data:{subscriptions:n}})}unsubscribeRealtime(n){return this.sendRealtime({type:"unsubscribe",channel:"session",event:"session.unsubscribe",data:{subscriptions:n}})}startHealthTick(n=300*1e3,e=!0){this.stopHealthTick();let t=()=>{this.healthTickPromise||(this.healthTickPromise=(this.csrfRefresher?this.csrfRefresher():Promise.resolve()).then(()=>{this.onHealthChange?.(!0)}).catch(()=>{this.onHealthChange?.(!1)}).finally(()=>{this.healthTickPromise=null}))};e&&t(),this.healthTickTimer=setInterval(t,n)}stopHealthTick(){this.healthTickTimer!==null&&(clearInterval(this.healthTickTimer),this.healthTickTimer=null),this.healthTickPromise=null}scheduleKeepSession(n,e,t){this.clearRefreshTimer(),this.sessionRefreshToken=n;let s=Math.max((e-this.refreshBuffer)*1e3,0);this.refreshTimer=setTimeout(async()=>{if(this.sessionRefreshToken)try{let i=await t(this.sessionRefreshToken);this.onTokenRefreshed?.(i.access_token,i.expires_in),this.scheduleKeepSession(this.sessionRefreshToken,i.expires_in,t)}catch(i){this.clearRefreshTimer(),this.onSessionExpired?.(i instanceof Error?i:new Error(String(i)))}},s)}clearRefreshTimer(){this.refreshTimer!==null&&(clearTimeout(this.refreshTimer),this.refreshTimer=null)}stopKeepSession(){this.clearRefreshTimer(),this.sessionRefreshToken=null}applyRealtimeOptions(n){let e=typeof n=="boolean"?{enabled:n}:n??{};if(this.realtimeEnabled=e.enabled??!1,this.realtimePath=String(e.path??J).trim()||J,this.realtimeAutoReconnect=e.autoReconnect??!0,this.realtimeReconnectDelayMs=Math.max(250,e.reconnectDelayMs??3e3),!this.realtimeEnabled){this.disconnectRealtime("realtime_disabled");return}this.setRealtimeStatus("idle","realtime_enabled")}buildRealtimeUrl(){let n=this.baseUrl||V("VITE_ENTITY_SERVER_URL")||"",e=typeof window<"u"?window.location.origin:"",t=n||e;if(!t)throw new Error("Realtime connection requires baseUrl.");let s=new URL(t,e||void 0),i=s.pathname==="/"?"":s.pathname.replace(/\/+$/,""),o=`/${this.realtimePath.replace(/^\/+/,"")}`;return s.pathname=`${i}${o}`||o,s.search="",s.hash="",s.protocol=s.protocol==="https:"?"wss:":"ws:",s.searchParams.set("access_token",this.token),s.toString()}handleRealtimeMessage(n){if(typeof n!="string")return;let e;try{e=JSON.parse(n)}catch{return}for(let s of this.realtimeMessageListeners)s(e);let t=this.realtimeEventListeners.get(e.event);if(t)for(let s of t)s(e)}scheduleRealtimeReconnect(n){this.clearRealtimeReconnectTimer(),this.realtimeReconnectTimer=setTimeout(()=>{this.realtimeReconnectTimer=null,!(!this.realtimeEnabled||!this.token)&&(this.setRealtimeStatus("connecting",`${n}:reconnect`),this.connectRealtime().catch(()=>{}))},this.realtimeReconnectDelayMs)}clearRealtimeReconnectTimer(){this.realtimeReconnectTimer!==null&&(clearTimeout(this.realtimeReconnectTimer),this.realtimeReconnectTimer=null)}setRealtimeStatus(n,e,t){let s=this.realtimeStatus;if(!(s===n&&typeof e>"u"&&typeof t>"u")){this.realtimeStatus=n;for(let i of this.realtimeStatusListeners)i({status:n,previousStatus:s,...e?{reason:e}:{},...t?{error:t}:{}})}}applyCsrfHealth(){if(!(typeof document>"u")){for(let n of document.cookie.split(";")){let e=n.indexOf("=");if(!(e<0)&&n.substring(0,e).trim()===this.csrfCookieName){this.csrfEnabled=!!n.substring(e+1).trim();return}}this.csrfEnabled=!1}}readRequestBody(n,e="application/json",t=!1){let s=M(this.hmacSecret,this.token||this.anonymousPacketToken);return Me(n,e,t,s)}get reqOpts(){return{baseUrl:this.baseUrl,token:this.token,anonymousPacketToken:this.anonymousPacketToken,apiKey:this.apiKey,hmacSecret:this.hmacSecret,encryptRequests:this.encryptRequests,csrfEnabled:this.csrfEnabled,csrfHeaderName:this.csrfHeaderName,csrfCookieName:this.csrfCookieName,refreshCsrfCookie:this.csrfEnabled?this.csrfRefresher:null,requestAbortControllers:this.requestAbortControllers,debugPlainSecret:this.debugPlainSecret,onAccessToken:n=>{this.setAccessTokenFromResponse(n)}}}prepareRequest(n){return Promise.resolve()}get http(){let n=this;return{get(e,t=!0,s,i){return n.prepareRequest(t).then(()=>w(n.reqOpts,"GET",e,void 0,t,s,i??!0))},post(e,t,s=!0,i,o){return n.prepareRequest(s).then(()=>w(n.reqOpts,"POST",e,t,s,i,o??!0))},put(e,t,s=!0,i,o){return n.prepareRequest(s).then(()=>w(n.reqOpts,"PUT",e,t,s,i,o??!0))},patch(e,t,s=!0,i,o){return n.prepareRequest(s).then(()=>w(n.reqOpts,"PATCH",e,t,s,i,o??!0))},delete(e,t,s=!0,i,o){return n.prepareRequest(s).then(()=>w(n.reqOpts,"DELETE",e,t,s,i,o??!0))}}}request(n,e,t,s=!0,i,o){return this.prepareRequest(s).then(()=>w(this.reqOpts,n,e,t,s,i,o??!0))}async requestBinary(n,e,t,s=!0){await this.prepareRequest(s);let i={"Content-Type":"application/json"};s&&this.token&&(i.Authorization=`Bearer ${this.token}`),this.apiKey&&(i["X-API-Key"]=this.apiKey);let o=await fetch(this.baseUrl+e,{method:n,headers:i,...t!=null?{body:JSON.stringify(t)}:{},credentials:"include"});if(!o.ok){let a=await o.text(),u=new Error(`HTTP ${o.status}: ${a}`);throw u.status=o.status,u}return o.arrayBuffer()}async requestForm(n,e,t,s=!0){let i={};s&&this.token&&(i.Authorization=`Bearer ${this.token}`),this.apiKey&&(i["X-API-Key"]=this.apiKey);let o=await fetch(this.baseUrl+e,{method:n,headers:i,body:t,credentials:"include"}),a=await o.json();if(!a.ok){let u=new Error(a.message??`EntityServer error (HTTP ${o.status})`);throw u.status=o.status,u}return a}async requestFormBinary(n,e,t,s=!0){let i={};s&&this.token&&(i.Authorization=`Bearer ${this.token}`),this.apiKey&&(i["X-API-Key"]=this.apiKey);let o=await fetch(this.baseUrl+e,{method:n,headers:i,body:t,credentials:"include"});if(!o.ok){let a=await o.text(),u=new Error(`HTTP ${o.status}: ${a}`);throw u.status=o.status,u}return o.arrayBuffer()}};function Ie(r){return r.ok===!0&&r.requires_2fa!==!0&&typeof r.data=="object"&&r.data!==null&&"access_token"in r.data}function Y(r){return class extends r{authBootstrapPromise=null;authBootstrapToken="";authBootstrapAnonymousCompleted=!1;setAccessTokenFromResponse(e){super.setAccessTokenFromResponse(e),this.authBootstrapToken=e,this.authBootstrapAnonymousCompleted=!1}csrfRefresher=()=>this.checkHealth(this.keepSession).then(()=>{});async checkHealth(e=!1){try{let t=this.token,s={};e&&(s["X-Session-Bootstrap"]="1");let i=await fetch(`${this.baseUrl}/v1/health`,{signal:AbortSignal.timeout(3e3),credentials:"include",headers:s}),o=await i.json(),a=i.headers.get("X-Access-Token");a&&(this.token=a,e&&a!==t&&this.onTokenRefreshed?.(a,0));let u=i.headers.get("X-Packet-Encryption")==="1"||o.packet_encryption===!0,m=this.readCookie("anon_token");return u&&m&&(this.anonymousPacketToken=m,this.encryptRequests=!0),this.applyCsrfHealth(),this.onHealthChange?.(!0),e&&o.authenticated===!1&&t&&(this.disconnectRealtime("session_expired"),this.onSessionExpired?.(new Error("Session expired"))),o}catch(t){throw this.onHealthChange?.(!1),t}}readCookie(e){if(typeof document>"u")return null;let t=document.cookie.split(";").map(s=>s.trim()).find(s=>s.startsWith(`${e}=`));if(!t)return null;try{return decodeURIComponent(t.slice(e.length+1))}catch{return t.slice(e.length+1)}}async ensurePublicAuthBootstrap(){if(typeof document>"u"||this.apiKey&&this.hmacSecret)return;let e=!!this.anonymousPacketToken||!!this.readCookie("anon_token"),t=!!this.readCookie(this.csrfCookieName);e&&t&&this.csrfEnabled||await this.checkHealth(!1)}async ensureAuthenticatedRequestBootstrap(){if(!(typeof document>"u")&&!(this.apiKey&&this.hmacSecret)){if(this.token){if(this.authBootstrapToken===this.token)return}else if(this.authBootstrapAnonymousCompleted)return;return this.authBootstrapPromise?this.authBootstrapPromise:(this.authBootstrapPromise=this.checkHealth(!0).then(()=>{this.token?this.authBootstrapToken=this.token:this.authBootstrapAnonymousCompleted=!0}).finally(()=>{this.authBootstrapPromise=null}),this.authBootstrapPromise)}}async prepareRequest(e){await super.prepareRequest(e),e&&await this.ensureAuthenticatedRequestBootstrap()}async login(e,t){await this.ensurePublicAuthBootstrap();let s=await w(this.reqOpts,"POST","/v1/auth/login",{email:e,passwd:t},!1,{},{requireOkShape:!1,allowStatuses:[403]});return Ie(s)&&(this.token=s.data.access_token,this.applyCsrfHealth(),this.keepSession&&this.healthTickTimer===null&&this.startHealthTick()),s}async tokenRefresh(){let e=await this.request("POST","/v1/auth/token_refresh",void 0,!1);return this.token=e.data.access_token,this.applyCsrfHealth(),e.data}async refreshToken(e){if(!e)return this.tokenRefresh();let t=await this.request("POST","/v1/auth/refresh",{refresh_token:e},!1);return this.token=t.data.access_token,this.applyCsrfHealth(),t.data}async logout(e){this.stopKeepSession(),this.stopHealthTick(),this.disconnectRealtime("logout");let t=await this.request("POST","/v1/auth/logout",e?{refresh_token:e}:void 0,!1);return this.token="",this.applyCsrfHealth(),t}me(){return this.request("GET","/v1/auth/me")}withdraw(e){return this.request("POST","/v1/auth/withdraw",e?{passwd:e}:{})}}}function Z(r){return class extends r{async transStart(){let e=await this.request("POST","/v1/transaction/start",void 0,!1);return this.activeTxId=e.transaction_id,this.activeTxId}transRollback(e){let t=e??this.activeTxId;return t?(this.activeTxId=null,this.request("POST",`/v1/transaction/rollback/${t}`)):Promise.reject(new Error("No active transaction. Call transStart() first."))}transCommit(e){let t=e??this.activeTxId;return t?(this.activeTxId=null,this.request("POST",`/v1/transaction/commit/${t}`)):Promise.reject(new Error("No active transaction. Call transStart() first."))}meta(e){return this.request("POST",`/v1/entity/${e}/meta`,{})}validate(e,t){return this.http.post(`/v1/entity/${e}/validate`,t)}get(e,t,s={}){let i=s.skipHooks?"?skipHooks=true":"";return this.request("GET",`/v1/entity/${e}/${t}${i}`)}find(e,t,s={}){let i=s.skipHooks?"?skipHooks=true":"";return this.request("POST",`/v1/entity/${e}/find${i}`,t??{})}list(e,t={}){let{conditions:s,fields:i,orderDir:o,orderBy:a,...u}=t,m={page:1,limit:20,...u};return a&&(m.orderBy=o==="DESC"?`-${a}`:a),i?.length&&(m.fields=i.join(",")),this.request("POST",`/v1/entity/${e}/list?${l(m)}`,s??{})}count(e,t){return this.request("POST",`/v1/entity/${e}/count`,t??{})}query(e,t){return this.request("POST",`/v1/entity/${e}/query`,t)}submit(e,t,s={}){let i=s.transactionId??this.activeTxId,o=i?{"X-Transaction-ID":i}:void 0,a=s.skipHooks?"?skipHooks=true":"";return this.request("POST",`/v1/entity/${e}/submit${a}`,t,!0,o)}delete(e,t,s={}){let i=new URLSearchParams;s.hard&&i.set("hard","true"),s.skipHooks&&i.set("skipHooks","true");let o=i.size?`?${i}`:"",a=s.transactionId??this.activeTxId,u=a?{"X-Transaction-ID":a}:void 0;return this.request("POST",`/v1/entity/${e}/delete/${t}${o}`,void 0,!0,u)}history(e,t,s={}){return this.request("GET",`/v1/entity/${e}/history/${t}?${l({page:1,limit:50,...s})}`)}rollback(e,t){return this.request("POST",`/v1/entity/${e}/rollback/${t}`)}}}function ee(r){return class extends r{async fileUpload(e,t,s={}){let i=new FormData;return i.append("file",t,t instanceof File?t.name:"upload"),s.refSeq!=null&&i.append("ref_seq",String(s.refSeq)),s.isPublic!=null&&i.append("is_public",s.isPublic?"true":"false"),this.requestForm("POST",`/v1/files/${e}/upload`,i)}fileDownload(e,t){return this.requestBinary("POST",`/v1/files/${e}/download/${t}`,{})}fileDelete(e,t){return this.request("POST",`/v1/files/${e}/delete/${t}`,{})}fileList(e,t={}){return this.request("POST",`/v1/files/${e}/list`,t.refSeq?{ref_seq:t.refSeq}:{})}fileMeta(e,t){return this.request("POST",`/v1/files/${e}/meta/${t}`,{})}fileToken(e){return this.request("POST",`/v1/files/token/${e}`,{})}fileViewUrl(e,t={}){let s=t.download?"?download=true":"";return`${this.baseUrl}/v1/files/${e}${s}`}fileUrl(e){return`${this.baseUrl}/v1/files/${e}`}storageUpload(e,t,s={}){return this.fileUpload(e,t,s)}storageDownload(e,t){return this.fileDownload(e,t)}storageDelete(e,t){return this.fileDelete(e,t)}storageList(e,t={}){return this.fileList(e,t)}storageMeta(e,t){return this.fileMeta(e,t)}storageToken(e){return this.fileToken(e)}storageViewUrl(e,t={}){return this.fileViewUrl(e,t)}storageDownloadUrl(e){return this.fileViewUrl(e,{download:!0})}storageUrl(e){return this.fileUrl(e)}}}function te(r){return class extends r{push(e,t,s={}){return this.submit(e,t,s)}pushLogList(e={}){return this.list("push_log",e)}registerPushDevice(e,t,s,i={}){let{platform:o,deviceType:a,browser:u,browserVersion:m,pushEnabled:g=!0,transactionId:h}=i;return this.submit("account_device",{id:t,account_seq:e,push_token:s,push_enabled:g,...o?{platform:o}:{},...a?{device_type:a}:{},...u?{browser:u}:{},...m?{browser_version:m}:{}},{transactionId:h})}updatePushDeviceToken(e,t,s={}){let{pushEnabled:i=!0,transactionId:o}=s;return this.submit("account_device",{seq:e,push_token:t,push_enabled:i},{transactionId:o})}disablePushDevice(e,t={}){return this.submit("account_device",{seq:e,push_enabled:!1},{transactionId:t.transactionId})}}}function ne(r){return class extends r{smtpSend(e){return this.request("POST","/v1/smtp/send",e)}smtpStatus(e){return this.request("POST",`/v1/smtp/status/${e}`,{})}smtpTemplatePreview(e){let t=e.split("/").map(encodeURIComponent).join("/");return fetch(`${this.baseUrl}/v1/smtp/template/${t}`,{credentials:"include"}).then(s=>s.text())}}}function re(r){return class extends r{transactionStart(e){return this.request("POST","/v1/transaction/start",e??{})}transactionCommit(e){return this.request("POST",`/v1/transaction/commit/${encodeURIComponent(e)}`,{})}transactionRollback(e){return this.request("POST",`/v1/transaction/rollback/${encodeURIComponent(e)}`,{})}}}function se(r){return class extends r{addressSido(){return this.http.get("/v1/utils/address/sido",!1)}addressSigungu(e){let t=new URLSearchParams({sido:e.sido}).toString();return this.http.get(`/v1/utils/address/sigungu?${t}`,!1)}addressDong(e){let t=new URLSearchParams({sido:e.sido,sigungu:e.sigungu}).toString();return this.http.get(`/v1/utils/address/dong?${t}`,!1)}addressClean(e){let t=new URLSearchParams({q:e.q}).toString();return this.http.get(`/v1/utils/address/clean?${t}`,!1)}qrcode(e,t={}){return this.requestBinary("POST","/v1/utils/qrcode",{content:e,...t})}qrcodeBase64(e,t={}){return this.request("POST","/v1/utils/qrcode/base64",{content:e,...t})}qrcodeText(e,t={}){return this.request("POST","/v1/utils/qrcode/text",{content:e,...t})}barcode(e,t={}){return this.requestBinary("POST","/v1/utils/barcode",{content:e,...t})}pdf2png(e,t={}){let s=new FormData;s.append("file",new Blob([e],{type:"application/pdf"}),"document.pdf");let i=new URLSearchParams;t.dpi!=null&&i.set("dpi",String(t.dpi)),t.firstPage!=null&&i.set("first_page",String(t.firstPage)),t.lastPage!=null&&i.set("last_page",String(t.lastPage));let o=i.toString(),a="/v1/utils/pdf2png"+(o?`?${o}`:"");return this.requestFormBinary("POST",a,s)}pdf2pngByFileSeq(e,t={}){return this.requestBinary("POST",`/v1/utils/pdf2png/${e}`,t)}pdf2jpg(e,t={}){let s=new FormData;s.append("file",new Blob([e],{type:"application/pdf"}),"document.pdf");let i=new URLSearchParams;t.dpi!=null&&i.set("dpi",String(t.dpi)),t.firstPage!=null&&i.set("first_page",String(t.firstPage)),t.lastPage!=null&&i.set("last_page",String(t.lastPage));let o=i.toString(),a="/v1/utils/pdf2jpg"+(o?`?${o}`:"");return this.requestFormBinary("POST",a,s)}pdf2jpgByFileSeq(e,t={}){return this.requestBinary("POST",`/v1/utils/pdf2jpg/${e}`,t)}}}function ie(r){return class extends r{adminPath(e){return`/v1/admin${e}`}adminGet(e){return this.http.get(this.adminPath(e))}adminPost(e,t){return this.http.post(this.adminPath(e),t)}adminPut(e,t){return this.http.put(this.adminPath(e),t)}adminPatch(e,t){return this.http.patch(this.adminPath(e),t)}adminDelete(e,t){return this.http.delete(this.adminPath(e),t)}listAdminEntities(){return this.adminGet("/entities")}getAdminErdSchema(){return this.adminGet("/erd/schema")}batchEnsureAdminEntities(e){return this.adminPost("/entities/batch-ensure",e)}createAdminEntityConfig(e,t){return this.adminPost(`/${e}/create`,t)}getAdminEntityConfig(e){return this.adminGet(`/${e}/config`)}updateAdminEntityConfig(e,t){return this.adminPut(`/${e}/config`,t)}validateAdminEntityConfig(e,t){return this.adminPost(t?`/${t}/validate`:"/entity/validate",e)}normalizeAdminEntityConfig(e,t){return this.adminPost(t?`/${t}/normalize`:"/entity/normalize",e)}getAdminEntityStats(e,t){return this.adminPost(`/${e}/stats`,t)}reindexAdminEntity(e){return this.adminPost(`/${e}/reindex`)}syncAdminEntitySchema(e){return this.adminPost(`/${e}/sync-schema`)}resetAdminEntity(e){return this.adminPost(`/${e}/reset`)}truncateAdminEntity(e){return this.adminPost(`/${e}/truncate`)}dropAdminEntity(e){return this.adminPost(`/${e}/drop`)}resetAllAdmin(e){return this.adminPost("/reset-all",e)}listAdminConfigs(){return this.adminGet("/configs")}getAdminConfig(e){return this.adminGet(`/configs/${e}`)}updateAdminConfig(e,t){return this.adminPatch(`/configs/${e}`,t)}listAdminRoles(){return this.adminGet("/roles")}createAdminRole(e){return this.adminPost("/roles",e)}getAdminRole(e){return this.adminGet(`/roles/${e}`)}updateAdminRole(e,t){return this.adminPatch(`/roles/${e}`,t)}deleteAdminRole(e){return this.adminDelete(`/roles/${e}`)}listAdminApiKeys(){return this.adminGet("/api-keys")}createAdminApiKey(e){return this.adminPost("/api-keys",e)}getAdminApiKey(e){return this.adminGet(`/api-keys/${e}`)}updateAdminApiKey(e,t){return this.adminPatch(`/api-keys/${e}`,t)}deleteAdminApiKey(e){return this.adminDelete(`/api-keys/${e}`)}regenerateAdminApiKeySecret(e){return this.adminPost(`/api-keys/${e}/regenerate-secret`)}listAdminAccounts(){return this.adminGet("/accounts")}createAdminAccount(e){return this.adminPost("/accounts",e)}getAdminAccount(e){return this.adminGet(`/accounts/${e}`)}updateAdminAccount(e,t){return this.adminPatch(`/accounts/${e}`,t)}deleteAdminAccount(e){return this.adminDelete(`/accounts/${e}`)}listAdminLicenses(){return this.adminGet("/licenses")}createAdminLicense(e){return this.adminPost("/licenses",e)}getAdminLicense(e){return this.adminGet(`/licenses/${e}`)}updateAdminLicense(e,t){return this.adminPatch(`/licenses/${e}`,t)}deleteAdminLicense(e){return this.adminDelete(`/licenses/${e}`)}runAdminBackup(e){return this.adminPost("/backup/run",e)}getAdminBackupStatus(e){return this.adminPost("/backup/status",e)}listAdminBackups(e){return this.adminPost("/backup/list",e)}restoreAdminBackup(e){return this.adminPost("/backup/restore",e)}deleteAdminBackup(e){return this.adminPost("/backup/delete",e)}disableAdminAccountTwoFactor(e){return this.adminDelete(`/accounts/${e}/2fa`)}}}var v=class extends se(re(ee(ne(te(ie(Z(Y(G)))))))){};function oe(r){return class extends r{accountRegister(e){return this.http.post("/v1/account/register",e,!1)}accountWithdraw(e){return this.http.post("/v1/account/withdraw",e)}accountChangePassword(e){return this.http.post("/v1/account/change-password",e)}accountReactivate(e){return this.http.post("/v1/account/reactivate",e,!1)}listAccountBiometrics(){return this.http.get("/v1/account/biometric")}registerAccountBiometric(e){return this.http.post("/v1/account/biometric",e)}deleteAccountBiometric(e){return this.http.delete(`/v1/account/biometric/${e}`)}}}function ae(r){return class extends r{listBoardCategories(e={}){let t=l(e);return this.http.get(`/v1/board/categories${t?`?${t}`:""}`,!1)}getBoardCategory(e){return this.http.get(`/v1/board/categories/${e}`,!1)}createBoardCategory(e){return this.http.post("/v1/board/categories",e)}updateBoardCategory(e,t){return this.http.put(`/v1/board/categories/${e}`,t)}deleteBoardCategory(e){return this.http.delete(`/v1/board/categories/${e}`)}listBoardPosts(e,t={}){let s=l(t);return this.http.get(`/v1/board/${e}/list${s?`?${s}`:""}`)}getBoardPost(e){return this.http.get(`/v1/board/posts/${e}`)}createBoardPost(e,t){return this.http.post(`/v1/board/${e}/submit`,t)}updateBoardPost(e,t){return this.http.patch(`/v1/board/posts/${e}`,t)}expireBoardPost(e){return this.http.post(`/v1/board/posts/${e}/expire`,{})}deleteBoardPost(e){return this.http.delete(`/v1/board/posts/${e}`)}listBoardComments(e,t={}){let s=l(t);return this.http.get(`/v1/board/posts/${e}/comments${s?`?${s}`:""}`,!1)}createBoardComment(e,t){return this.http.post(`/v1/board/posts/${e}/comments/submit`,t)}updateBoardComment(e,t){return this.http.put(`/v1/board/comments/${e}`,t)}deleteBoardComment(e){return this.http.delete(`/v1/board/comments/${e}`)}listBoardFiles(e){return this.http.get(`/v1/board/posts/${e}/files`,!1)}async uploadBoardFile(e,t){let s=new FormData;return s.append("file",t,t instanceof File?t.name:"upload"),this.requestForm("POST",`/v1/board/posts/${e}/files`,s)}boardFileUrl(e){return`${this.baseUrl}/v1/board/files/${e}`}deleteBoardFile(e){return this.http.delete(`/v1/board/files/${e}`)}createBoardGuestPost(e,t){return this.http.post(`/v1/board/${e}/guest-submit`,t,!1)}authenticateBoardGuestPost(e,t){return this.http.post(`/v1/board/posts/${e}/guest-auth`,t,!1)}toggleBoardPostLike(e){return this.http.post(`/v1/board/posts/${e}/like`,{})}acceptBoardPost(e){return this.http.post(`/v1/board/posts/${e}/accept`,{})}rateBoardPost(e,t){return this.http.post(`/v1/board/posts/${e}/rating`,t)}rateBoardComment(e,t){return this.http.post(`/v1/board/comments/${e}/rating`,t)}listBoardTags(e={}){let t=l(e);return this.http.get(`/v1/board/tags${t?`?${t}`:""}`,!1)}setBoardPostTags(e,t){return this.http.put(`/v1/board/posts/${e}/tags`,t)}reportBoardPost(e,t){return this.http.post(`/v1/board/posts/${e}/report`,t)}reportBoardComment(e,t){return this.http.post(`/v1/board/comments/${e}/report`,t)}listBoardReports(e={}){let t=l(e);return this.http.get(`/v1/board/admin/reports${t?`?${t}`:""}`)}updateBoardReport(e,t){return this.http.patch(`/v1/board/admin/reports/${e}`,t)}markBoardPostRead(e){return this.http.post(`/v1/board/posts/${e}/read`,{})}listBoardMentions(e={}){let t=l(e);return this.http.get(`/v1/board/mentions${t?`?${t}`:""}`)}markBoardMentionRead(e){return this.http.patch(`/v1/board/mentions/${e}/read`,{})}}}function ue(r){return class extends r{sendEmailVerification(e){return this.http.post("/v1/email-verify/send",e,!1)}confirmEmailVerification(e){return this.http.post("/v1/email-verify/confirm",e,!1)}activateEmailVerification(e){let t=l(e);return this.http.get(`/v1/email-verify/activate${t?`?${t}`:""}`,!1)}getEmailVerificationStatus(){return this.http.get("/v1/email-verify/status")}changeVerifiedEmail(e){return this.http.post("/v1/email-verify/change",e)}}}function ce(r){return class extends r{oauthAuthorizeUrl(e,t={}){let s=l(t);return`${this.baseUrl}/v1/oauth/${e}${s?`?${s}`:""}`}oauthCallback(e,t,s="POST"){if(s==="GET"){let i=l(t??{});return this.http.get(`/v1/oauth/${e}/callback${i?`?${i}`:""}`,!1)}return this.http.post(`/v1/oauth/${e}/callback`,t,!1)}linkOAuthAccount(e){return this.http.post("/v1/account/oauth/link",e)}unlinkOAuthAccount(e){return this.http.delete(`/v1/account/oauth/link/${e}`)}listOAuthProviders(){return this.http.get("/v1/account/oauth/providers")}refreshOAuthProviderToken(e,t){return this.http.post(`/v1/account/oauth/refresh/${e}`,t)}}}function le(r){return class extends r{requestPasswordReset(e){return this.http.post("/v1/password-reset/request",e,!1)}validatePasswordResetToken(e){return this.http.get(`/v1/password-reset/validate/${encodeURIComponent(e)}`,!1)}verifyPasswordReset(e){return this.http.post("/v1/password-reset/verify",e,!1)}}}function me(r){return class extends r{setupTwoFactor(e){return this.http.post("/v1/account/2fa/setup",e)}verifyTwoFactorSetup(e){return this.http.post("/v1/account/2fa/setup/verify",e,!1)}disableTwoFactor(){return this.http.delete("/v1/account/2fa")}getTwoFactorStatus(){return this.http.get("/v1/account/2fa/status")}regenerateTwoFactorRecoveryCodes(){return this.http.post("/v1/account/2fa/recovery/regenerate")}verifyTwoFactor(e){return this.http.post("/v1/account/2fa/verify",e,!1)}recoverTwoFactorAccess(e){return this.http.post("/v1/account/2fa/recovery",e,!1)}}}function de(r){return class extends r{alimtalkSend(e){return this.http.post("/v1/alimtalk/send",e)}alimtalkStatus(e){return this.http.get(`/v1/alimtalk/status/${e}`,!1)}listAlimtalkTemplates(){return this.http.get("/v1/alimtalk/templates",!1)}alimtalkWebhook(e,t){return this.http.post(`/v1/alimtalk/webhook/${encodeURIComponent(e)}`,t,!1)}}}function he(r){return class extends r{friendtalkSend(e){return this.http.post("/v1/friendtalk/send",e)}}}function pe(r){return class extends r{listHolidays(e={}){let t=l(e);return this.http.get(`/v1/holidays${t?`?${t}`:""}`,!1)}getHolidayByDate(e){return this.http.get(`/v1/holidays/${encodeURIComponent(e)}`,!1)}syncHolidays(e){return this.http.post("/v1/holidays/sync",e)}}}function fe(r){return class extends r{identityRequest(e){return this.http.post("/v1/identity/request",e,!1)}identityCallback(e){return this.http.post("/v1/identity/callback",e,!1)}identityResult(e){return this.http.get(`/v1/identity/result/${encodeURIComponent(e)}`,!1)}identityVerifyCI(e){return this.http.post("/v1/identity/verify-ci",e)}}}function ge(r){return class extends r{llmChat(e){return this.http.post("/v1/llm/chat",e)}llmChatStream(e){return this.http.post("/v1/llm/chat/stream",e)}createLlmConversation(e){return this.http.post("/v1/llm/conversations",e)}sendLlmMessage(e,t){return this.http.post(`/v1/llm/conversations/${e}/messages`,t)}listLlmConversations(e={}){let t=l(e);return this.http.get(`/v1/llm/conversations${t?`?${t}`:""}`)}getLlmConversation(e){return this.http.get(`/v1/llm/conversations/${e}`)}updateLlmConversation(e,t){return this.http.patch(`/v1/llm/conversations/${e}`,t)}deleteLlmConversation(e){return this.http.delete(`/v1/llm/conversations/${e}`)}ragUploadDocument(e){return this.requestForm("POST","/v1/llm/rag/documents",e)}ragListDocuments(e={}){let t=l(e);return this.http.get(`/v1/llm/rag/documents${t?`?${t}`:""}`)}ragDeleteDocument(e){return this.http.delete(`/v1/llm/rag/documents/${encodeURIComponent(e)}`)}ragSearch(e){return this.http.post("/v1/llm/rag/search",e)}ragChat(e){return this.http.post("/v1/llm/rag/chat",e)}ragChatStream(e){return this.http.post("/v1/llm/rag/chat/stream",e)}ragRebuildIndex(e){return this.http.post("/v1/llm/rag/rebuild-index",e)}listLlmProviders(){return this.http.get("/v1/llm/providers")}getLlmUsage(e={}){let t=l(e);return this.http.get(`/v1/llm/usage${t?`?${t}`:""}`)}getLlmUsageSummary(e={}){let t=l(e);return this.http.get(`/v1/llm/usage/summary${t?`?${t}`:""}`)}getLlmCacheStats(){return this.http.get("/v1/llm/cache/stats")}clearLlmCache(){return this.http.delete("/v1/llm/cache")}listLlmTemplates(){return this.http.get("/v1/llm/templates")}llmTemplateChat(e,t){return this.http.post(`/v1/llm/${encodeURIComponent(e)}/chat`,t)}llmTemplateChatStream(e,t){return this.http.post(`/v1/llm/${encodeURIComponent(e)}/chat/stream`,t)}listLlmChatbots(e={}){let t=l(e);return this.http.get(`/v1/llm/chatbots${t?`?${t}`:""}`)}createLlmChatbot(e){return this.http.post("/v1/llm/chatbots",e)}getLlmChatbot(e){return this.http.get(`/v1/llm/chatbots/${e}`)}updateLlmChatbot(e,t){return this.http.patch(`/v1/llm/chatbots/${e}`,t)}deleteLlmChatbot(e){return this.http.delete(`/v1/llm/chatbots/${e}`)}llmChatbotChat(e,t){return this.http.post(`/v1/llm/chatbots/${e}/chat`,t)}llmChatbotChatStream(e,t){return this.http.post(`/v1/llm/chatbots/${e}/chat/stream`,t)}listLlmChatbotSessions(e,t={}){let s=l(t);return this.http.get(`/v1/llm/chatbots/${e}/sessions${s?`?${s}`:""}`)}deleteLlmChatbotSession(e,t){return this.http.delete(`/v1/llm/chatbots/${e}/sessions/${t}`)}listLlmProfiles(e={}){let t=l(e);return this.http.get(`/v1/llm/profiles${t?`?${t}`:""}`)}upsertLlmProfile(e){return this.http.post("/v1/llm/profiles",e)}deleteLlmProfile(e){return this.http.delete(`/v1/llm/profiles/${e}`)}}}function ke(r){return class extends r{ocrRecognize(e){return this.requestForm("POST","/v1/ocr/recognize",e)}ocrRecognizeAsync(e){return this.requestForm("POST","/v1/ocr/recognize/async",e)}ocrRecognizeByDocType(e,t){return this.requestForm("POST",`/v1/ocr/${encodeURIComponent(e)}`,t)}listOcrResults(e={}){let t=l(e);return this.http.get(`/v1/ocr/results${t?`?${t}`:""}`)}getOcrResult(e){return this.http.get(`/v1/ocr/results/${encodeURIComponent(e)}`)}getOcrResultText(e){return this.http.get(`/v1/ocr/results/${encodeURIComponent(e)}/text`)}deleteOcrResult(e){return this.http.delete(`/v1/ocr/results/${encodeURIComponent(e)}`)}getOcrQuota(){return this.http.get("/v1/ocr/quota")}}}function Te(r){return class extends r{pgCreateOrder(e){return this.http.post("/v1/pg/orders",e)}pgGetOrder(e){return this.http.get(`/v1/pg/orders/${encodeURIComponent(e)}`)}pgConfirmPayment(e){return this.http.post("/v1/pg/confirm",e)}pgCancelPayment(e,t){return this.http.post(`/v1/pg/orders/${encodeURIComponent(e)}/cancel`,t)}pgSyncPaymentStatus(e,t){return this.http.post(`/v1/pg/orders/${encodeURIComponent(e)}/sync`,t)}pgWebhook(e){return this.http.post("/v1/pg/webhook",e,!1)}pgGetClientConfig(){return this.http.get("/v1/pg/config",!1)}}}function ye(r){return class extends r{appPushSend(e){return this.http.post("/v1/push/send",e)}appPushBroadcast(e){return this.http.post("/v1/push/broadcast",e)}appPushStatus(e){return this.http.get(`/v1/push/status/${e}`)}appPushRegisterDevice(e){return this.http.post("/v1/push/device",e)}appPushUnregisterDevice(e){return this.http.delete(`/v1/push/device/${e}`)}}}function Pe(r){return class extends r{smsSend(e){return this.http.post("/v1/sms/send",e)}smsStatus(e){return this.http.get(`/v1/sms/status/${e}`,!1)}smsVerificationSend(e){return this.http.post("/v1/sms/verification/send",e,!1)}smsVerificationVerify(e){return this.http.post("/v1/sms/verification/verify",e,!1)}}}function be(r){return class extends r{taxinvoiceRegistIssue(e){return this.http.post("/v1/taxinvoice",e)}taxinvoiceRegister(e){return this.http.post("/v1/taxinvoice/register",e)}taxinvoiceIssue(e){return this.http.post(`/v1/taxinvoice/${e}/issue`,{})}taxinvoiceCancelIssue(e,t){return this.http.post(`/v1/taxinvoice/${e}/cancel`,t)}taxinvoiceGetState(e){return this.http.get(`/v1/taxinvoice/${e}/state`)}taxinvoiceGetDetail(e){return this.http.get(`/v1/taxinvoice/${e}`)}}}var E=class extends de(he(Pe(ye(Te(be(ke(ge(fe(pe(ce(me(le(ue(ae(oe(v)))))))))))))))){};var He=new v,Ge=new E;function Rr(r={}){return _(r,{singletonInstance:He,ClientClass:v})}function Er(r={}){return _(r,{singletonInstance:Ge,ClientClass:E})}export{Er as useEntityAppServer,_ as useEntityClient,Rr as useEntityServer};
1
+ import{useCallback as D,useEffect as Ae,useMemo as Xe,useRef as Be,useState as qe}from"react";function W(r,n){let{singleton:e=!0,tokenResolver:t,baseUrl:s,token:i,resumeSession:o}=r,[a,u]=qe(!1),[d,k]=qe(null),h=Be(!0);Ae(()=>(h.current=!0,()=>{h.current=!1}),[]);let f=Xe(()=>{let g=e?n.singletonInstance:new n.ClientClass({baseUrl:s,token:i});e&&g.configure({baseUrl:s,token:i});let m=t?.();return typeof m=="string"&&g.setToken(m),g},[e,t,s,i,n.ClientClass,n.singletonInstance]),R=Be(o);Ae(()=>{if(R.current){if(f.checkHealth){f.checkHealth(!0).catch(()=>{});return}f.refreshToken(R.current).catch(()=>{})}},[f]);let b=D(async g=>{h.current&&(u(!0),k(null));try{return await g()}catch(m){let v=m instanceof Error?m:new Error(String(m));throw h.current&&k(v),v}finally{h.current&&u(!1)}},[]),w=D((g,m,v)=>b(()=>f.submit(g,m,v)),[f,b]),A=D((g,m,v)=>b(()=>f.delete(g,m,v)),[f,b]),O=D((g,m)=>b(()=>f.query(g,m)),[f,b]),B=D(()=>{u(!1),k(null)},[]);return{client:f,isPending:a,error:d,reset:B,submit:w,del:A,query:O}}function Y(r){let n=import.meta;if(n?.env?.[r]!=null)return n.env[r];let e=globalThis.process;if(e?.env?.[r]!=null)return e.env[r]}function l(r){return Object.entries(r).filter(([,n])=>n!=null).map(([n,e])=>`${encodeURIComponent(n==="orderBy"?"order_by":n)}=${encodeURIComponent(String(e))}`).join("&")}import{xchacha20poly1305 as $e}from"@noble/ciphers/chacha";import{sha256 as Je}from"@noble/hashes/sha2";import{hkdf as Ye}from"@noble/hashes/hkdf";var Z=32,ee=2,te=14,L=24,Ze=16,et="entity-server:hkdf:v1",tt="entity-server:packet-encryption";function j(r){return r instanceof Uint8Array?r:new Uint8Array(r)}function Oe(r,n=tt){return Ye(Je,new TextEncoder().encode(r),new TextEncoder().encode(et),new TextEncoder().encode(n),Z)}function Ue(r,n=ee,e=te){let t=j(r);return t.length<Z?n:n+t[Z-1]%e}function Me(r,n,e=ee,t=te){let s=j(r),i=j(n),o=Ue(i,e,t),a=crypto.getRandomValues(new Uint8Array(o)),u=crypto.getRandomValues(new Uint8Array(L)),k=$e(i,u).encrypt(s),h=new Uint8Array(o+L+k.length);return h.set(a,0),h.set(u,o),h.set(k,o+L),h}function Le(r,n,e=ee,t=te){let s=j(r),i=j(n),o=Ue(i,e,t);if(s.length<o+L+Ze)throw new Error("Encrypted packet too short");let a=s.slice(o,o+L),u=s.slice(o+L);return $e(i,a).decrypt(u)}function _(r,n){return Oe(r||n)}function _e(r,n){return Me(r,n)}function K(r,n){let e=Le(r,n);return JSON.parse(new TextDecoder().decode(e))}function He(r,n,e,t){let s=n.toLowerCase().includes("application/octet-stream");if(e&&!s)throw new Error("Encrypted request required: Content-Type must be application/octet-stream");if(s){if(r==null)throw new Error("Encrypted request body is empty");if(r instanceof ArrayBuffer)return K(r,t);if(r instanceof Uint8Array){let i=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength);return K(i,t)}throw new Error("Encrypted request body must be ArrayBuffer or Uint8Array")}return r==null||r===""?{}:typeof r=="string"?JSON.parse(r):r}import{sha256 as nt}from"@noble/hashes/sha2";import{hmac as rt}from"@noble/hashes/hmac";function Ie(r,n,e,t,s){let i=String(Math.floor(Date.now()/1e3)),o=crypto.randomUUID(),a=new TextEncoder().encode(`${r}|${n}|${i}|${o}|`),u=new Uint8Array(a.length+e.length);u.set(a,0),u.set(e,a.length);let k=[...rt(nt,new TextEncoder().encode(s),u)].map(h=>h.toString(16).padStart(2,"0")).join("");return{"X-API-Key":t,"X-Timestamp":i,"X-Nonce":o,"X-Signature":k}}function st(r){switch(r.toUpperCase()){case"POST":case"PUT":case"PATCH":case"DELETE":return!0;default:return!1}}function it(r,n,e){if(e.autoAbortKey===!1)return null;if(typeof e.autoAbortKey=="string"){let t=e.autoAbortKey.trim();return t||null}return typeof window>"u"?null:st(r)?`${r.toUpperCase()} ${n}`:null}function ot(r){let n=r.filter(s=>!!s);if(n.length===0)return;if(n.length===1)return n[0];if(typeof AbortSignal.any=="function")return AbortSignal.any(n);let e=new AbortController,t=()=>e.abort();for(let s of n){if(s.aborted){e.abort();break}s.addEventListener("abort",t,{once:!0})}return e.signal}function at(r,n,e,t){let s=it(n,e,t);if(!s)return{signal:t.signal,abortKey:null,controller:null};r.requestAbortControllers.get(s)?.abort();let i=new AbortController;return r.requestAbortControllers.set(s,i),{signal:ot([t.signal,i.signal]),abortKey:s,controller:i}}function ut(r,n,e){!n||!e||r.requestAbortControllers.get(n)===e&&r.requestAbortControllers.delete(n)}function ct(r){return r.hmacSecret||r.token||r.anonymousPacketToken}function Ge(r,n,e){return r.hmacSecret?r.hmacSecret:n&&r.token||e}function lt(r){return r?r.length<=8?`${r.slice(0,2)}...${r.slice(-2)}`:`${r.slice(0,4)}...${r.slice(-4)}`:""}function Fe(r){typeof console>"u"||typeof console.error!="function"||console.error("[entity-client] packet decrypt failed",{method:r.method,path:r.path,withAuth:r.withAuth,status:r.status,contentType:r.contentType,responsePacketSource:lt(r.responsePacketSource),tokenPresent:r.tokenPresent,anonymousPacketTokenPresent:r.anonymousPacketTokenPresent,hmacEnabled:r.hmacEnabled,error:r.error instanceof Error?{name:r.error.name,message:r.error.message,stack:r.error.stack}:r.error})}function De(r){return r!=="GET"&&r!=="HEAD"&&r!=="OPTIONS"}function q(r){if(typeof document>"u")return"";for(let n of document.cookie.split(";")){let e=n.indexOf("=");if(!(e<0)&&n.substring(0,e).trim()===r)return decodeURIComponent(n.substring(e+1).trim())}return""}function je(r,n){return r===403&&/csrf/i.test(n)?!0:/csrf/i.test(n)&&/expired|token validation failed/i.test(n)}function mt(r,n){return r===401&&/nonce already used/i.test(n)}async function Q(r){if((r.headers.get("Content-Type")??"").includes("application/json")){let t=await r.json().catch(()=>null);if(t?.error)return{message:t.error,code:t.code,body:t};if(t?.message)return{message:t.message,code:t.code,body:t}}return{message:await r.text().catch(()=>"")||`HTTP ${r.status}`}}function z(r,n){let e=new Error(n.message);return e.status=r,n.code&&(e.code=n.code),n.body&&(e.details=n.body),e}async function E(r,n,e,t,s=!0,i={},o=!0){let a=typeof o=="boolean"?{requireOkShape:o}:o,u=a.requireOkShape??!0,d=new Set(a.allowStatuses??[]),k=at(r,n,e,a),h=k.signal,{baseUrl:f,token:R,apiKey:b,hmacSecret:w,encryptRequests:A,csrfEnabled:O,csrfHeaderName:B,csrfCookieName:g,refreshCsrfCookie:m,onAccessToken:v,debugPlainSecret:U}=r,p=r.anonymousPacketToken||q("anon_token"),S=s&&!!(b&&w),N=ct(r),M=Ge(r,s,p),P=O&&De(n)&&!S,T=P?q(g):"",I="application/json",V=!S&&!!p,C=null;if(t!=null)if(!U&&A&&!!N&&s&&n!=="GET"&&n!=="HEAD"){let y=_(w,R||p);C=_e(new TextEncoder().encode(JSON.stringify(t)),y),I="application/octet-stream"}else C=JSON.stringify(t);let ze=c=>{let y={...i},G=Object.keys(y).some(x=>x.toLowerCase()==="content-type");if(C!=null&&!G&&(y["Content-Type"]=I),!S&&s&&R&&(y.Authorization=`Bearer ${R}`),V&&(y["X-Packet-Token"]=p),U&&(y["X-Debug-Plain"]=U),P&&c&&(y[B]=c),S){let x=C instanceof Uint8Array?C:typeof C=="string"?new TextEncoder().encode(C):new Uint8Array(0);Object.assign(y,Ie(n,e,x,b,w))}return y};P&&!T&&m&&(await m(),T=q(g));let J=c=>fetch(f+e,{method:n,headers:ze(c),...C!=null?{body:C}:{},credentials:"include",signal:h});try{let c=await J(T);if(!c.ok){let F=await Q(c.clone());if(S&&mt(c.status,F.message))c=await J(T);else if(P&&m&&je(c.status,F.message))await m(),T=q(g),c=await J(T);else if(!d.has(c.status))throw z(c.status,F)}if(!c.ok&&!d.has(c.status))throw z(c.status,await Q(c));let y=c.headers.get("X-Access-Token")?.trim()??"",G=c.headers.get("Content-Type")??"";if(G.includes("application/octet-stream")){let F=_(w,M),Qe=await c.arrayBuffer(),xe;try{xe=K(Qe,F)}catch(Ee){throw Fe({method:n,path:e,withAuth:s,status:c.status,contentType:G,responsePacketSource:M,tokenPresent:!!R,anonymousPacketTokenPresent:!!p,hmacEnabled:!!w,error:Ee}),Ee}return y&&v?.(y),xe}if(y&&v?.(y),!G.includes("application/json"))return await c.text();let x=await c.json();if(u&&!x.ok&&!d.has(c.status))throw z(c.status,{message:x.message??`EntityServer error (HTTP ${c.status})`,code:x.code,body:x});return x}finally{ut(r,k.abortKey,k.controller)}}async function Ke(r,n,e,t,s=!0){let{baseUrl:i,token:o,apiKey:a,hmacSecret:u,csrfEnabled:d,csrfHeaderName:k,csrfCookieName:h,refreshCsrfCookie:f,onAccessToken:R,debugPlainSecret:b}=r,w=r.anonymousPacketToken||q("anon_token"),A=s&&!!(a&&u),O=Ge(r,s,w),B=d&&De(n)&&!A,g=!A&&!!w,m=B?q(h):"";B&&!m&&f&&(await f(),m=q(h));let v=P=>{let T={};return!A&&s&&o&&(T.Authorization=`Bearer ${o}`),A&&a&&(T["X-API-Key"]=a),g&&(T["X-Packet-Token"]=w),b&&(T["X-Debug-Plain"]=b),B&&P&&(T[k]=P),T},U=P=>fetch(i+e,{method:n,headers:v(P),body:t,credentials:"include"}),p=await U(m);if(!p.ok&&B&&f&&je(p.status,(await Q(p.clone())).message)&&(await f(),m=q(h),p=await U(m)),!p.ok)throw z(p.status,await Q(p));let S=p.headers.get("X-Access-Token")?.trim()??"",N=p.headers.get("Content-Type")??"";if(N.includes("application/octet-stream")){let P=_(u,O),T=await p.arrayBuffer(),I;try{I=K(T,P)}catch(V){throw Fe({method:n,path:e,withAuth:s,status:p.status,contentType:N,responsePacketSource:O,tokenPresent:!!o,anonymousPacketTokenPresent:!!w,hmacEnabled:!!u,error:V}),V}return S&&R?.(S),I}S&&R?.(S);let M=await p.json();if(!M.ok){let P=new Error(M.message??`EntityServer error (HTTP ${p.status})`);throw P.status=p.status,P}return M}var ne="/v1/realtime",X=class{baseUrl;token;anonymousPacketToken;apiKey;hmacSecret;encryptRequests;debugPlainSecret;csrfEnabled;csrfHeaderName;csrfCookieName;csrfRefresher=null;requestAbortControllers=new Map;activeTxId=null;initialHealthFired=!1;keepSession;refreshBuffer;onTokenRefreshed;onSessionExpired;onHealthChange;sessionRefreshToken=null;refreshTimer=null;healthTickTimer=null;healthTickPromise=null;realtimeEnabled;realtimePath;realtimeAutoReconnect;realtimeReconnectDelayMs;realtimeStatus;realtimeSocket=null;realtimeConnectPromise=null;realtimeReconnectTimer=null;realtimeShouldReconnect=!1;realtimeMessageListeners=new Set;realtimeStatusListeners=new Set;realtimeEventListeners=new Map;constructor(n={}){let e=Y("VITE_ENTITY_SERVER_URL");this.baseUrl=(n.baseUrl??e??"").replace(/\/$/,""),this.token=n.token??"",this.anonymousPacketToken=n.anonymousPacketToken??"",this.apiKey=n.apiKey??"",this.hmacSecret=n.hmacSecret??"",this.encryptRequests=n.encryptRequests??!1,this.debugPlainSecret=n.debugPlainSecret??"",this.csrfEnabled=n.csrfEnabled??!1,this.csrfHeaderName=n.csrfHeaderName??"x-csrf-token",this.csrfCookieName=n.csrfCookieName??"_csrf",this.keepSession=n.keepSession??!1,this.refreshBuffer=n.refreshBuffer??60,this.onTokenRefreshed=n.onTokenRefreshed,this.onSessionExpired=n.onSessionExpired,this.onHealthChange=n.onHealthChange,this.realtimeEnabled=!1,this.realtimePath=ne,this.realtimeAutoReconnect=!0,this.realtimeReconnectDelayMs=3e3,this.realtimeStatus="idle",this.applyRealtimeOptions(n.realtime),typeof n.healthTickInterval=="number"&&n.healthTickInterval>0&&Promise.resolve().then(()=>this.startHealthTick(n.healthTickInterval,!1)),this.fireInitialHealth()}configure(n){typeof n.baseUrl=="string"&&(this.baseUrl=n.baseUrl.replace(/\/$/,"")),typeof n.token=="string"&&(this.token=n.token),typeof n.anonymousPacketToken=="string"&&(this.anonymousPacketToken=n.anonymousPacketToken),typeof n.encryptRequests=="boolean"&&(this.encryptRequests=n.encryptRequests),typeof n.debugPlainSecret=="string"&&(this.debugPlainSecret=n.debugPlainSecret),typeof n.csrfEnabled=="boolean"&&(this.csrfEnabled=n.csrfEnabled),typeof n.csrfHeaderName=="string"&&(this.csrfHeaderName=n.csrfHeaderName),typeof n.csrfCookieName=="string"&&(this.csrfCookieName=n.csrfCookieName),typeof n.apiKey=="string"&&(this.apiKey=n.apiKey),typeof n.hmacSecret=="string"&&(this.hmacSecret=n.hmacSecret),typeof n.keepSession=="boolean"&&(this.keepSession=n.keepSession),typeof n.refreshBuffer=="number"&&(this.refreshBuffer=n.refreshBuffer),n.onTokenRefreshed&&(this.onTokenRefreshed=n.onTokenRefreshed),n.onSessionExpired&&(this.onSessionExpired=n.onSessionExpired),n.onHealthChange&&(this.onHealthChange=n.onHealthChange),typeof n.realtime<"u"&&this.applyRealtimeOptions(n.realtime),typeof n.healthTickInterval=="number"&&n.healthTickInterval>0&&Promise.resolve().then(()=>this.startHealthTick(n.healthTickInterval,!1)),this.fireInitialHealth()}fireInitialHealth(){if(this.initialHealthFired||typeof document>"u"||!this.baseUrl)return;this.initialHealthFired=!0;let n=this;typeof n.checkHealth=="function"&&Promise.resolve().then(()=>n.checkHealth(!1).catch(()=>{}))}setToken(n){this.token=n,this.syncRealtimeWithToken()}setAccessTokenFromResponse(n){this.token=n,this.syncRealtimeWithToken()}syncRealtimeWithToken(){if(!this.token){this.disconnectRealtime("token_cleared");return}!this.realtimeEnabled||typeof WebSocket>"u"||this.connectRealtime().catch(()=>{})}setAnonymousPacketToken(n){this.anonymousPacketToken=n}setApiKey(n){this.apiKey=n}setHmacSecret(n){this.hmacSecret=n}setEncryptRequests(n){this.encryptRequests=n}setCsrfEnabled(n){this.csrfEnabled=n}addRealtimeListener(n){this.realtimeMessageListeners.add(n)}removeRealtimeListener(n){this.realtimeMessageListeners.delete(n)}addRealtimeStatusListener(n){this.realtimeStatusListeners.add(n)}removeRealtimeStatusListener(n){this.realtimeStatusListeners.delete(n)}addRealtimeEventListener(n,e){let t=String(n).trim();t&&(this.realtimeEventListeners.has(t)||this.realtimeEventListeners.set(t,new Set),this.realtimeEventListeners.get(t).add(e))}removeRealtimeEventListener(n,e){let t=String(n).trim();if(!t)return;let s=this.realtimeEventListeners.get(t);s&&(s.delete(e),s.size===0&&this.realtimeEventListeners.delete(t))}async connectRealtime(){if(!this.realtimeEnabled){this.setRealtimeStatus("disabled","realtime_disabled");return}if(!this.token)throw new Error("Cannot open realtime connection without access token.");if(typeof WebSocket>"u")throw new Error("WebSocket is not available in this environment.");if(this.realtimeSocket&&this.realtimeSocket.readyState===WebSocket.OPEN)return;if(this.realtimeSocket&&this.realtimeSocket.readyState===WebSocket.CONNECTING&&this.realtimeConnectPromise)return this.realtimeConnectPromise;this.clearRealtimeReconnectTimer(),this.realtimeShouldReconnect=this.realtimeAutoReconnect,this.setRealtimeStatus("connecting","connect_requested");let n=new WebSocket(this.buildRealtimeUrl());return this.realtimeSocket=n,this.realtimeConnectPromise=new Promise((e,t)=>{let s=!1,i=()=>{s||(s=!0,this.realtimeConnectPromise=null,e())},o=a=>{s||(s=!0,this.realtimeConnectPromise=null,t(a))};n.addEventListener("open",()=>{this.setRealtimeStatus("open","socket_open"),i()}),n.addEventListener("message",a=>{this.handleRealtimeMessage(a.data)}),n.addEventListener("error",()=>{this.setRealtimeStatus("closed","socket_error",new Error("Realtime socket error."))}),n.addEventListener("close",a=>{this.realtimeSocket===n&&(this.realtimeSocket=null);let u=a.reason||"socket_closed",d=new Error(`Realtime socket closed (${a.code}${a.reason?`: ${a.reason}`:""}).`);this.setRealtimeStatus("closed",u,d),s||o(d),this.realtimeShouldReconnect&&this.realtimeEnabled&&this.realtimeAutoReconnect&&this.token&&this.scheduleRealtimeReconnect(u)})}),this.realtimeConnectPromise}disconnectRealtime(n="client_disconnect"){if(this.realtimeShouldReconnect=!1,this.clearRealtimeReconnectTimer(),this.realtimeSocket){let e=this.realtimeSocket;this.realtimeSocket=null;try{(e.readyState===WebSocket.OPEN||e.readyState===WebSocket.CONNECTING)&&e.close(1e3,n)}catch{}}this.realtimeConnectPromise=null,this.setRealtimeStatus(this.realtimeEnabled?"idle":"disabled",n)}sendRealtime(n){return!this.realtimeSocket||this.realtimeSocket.readyState!==WebSocket.OPEN?!1:(this.realtimeSocket.send(JSON.stringify(n)),!0)}subscribeRealtime(n){return this.sendRealtime({type:"subscribe",channel:"session",event:"session.subscribe",data:{subscriptions:n}})}unsubscribeRealtime(n){return this.sendRealtime({type:"unsubscribe",channel:"session",event:"session.unsubscribe",data:{subscriptions:n}})}startHealthTick(n=300*1e3,e=!0){this.stopHealthTick();let t=()=>{this.healthTickPromise||(this.healthTickPromise=(this.csrfRefresher?this.csrfRefresher():Promise.resolve()).then(()=>{this.onHealthChange?.(!0)}).catch(()=>{this.onHealthChange?.(!1)}).finally(()=>{this.healthTickPromise=null}))};e&&t(),this.healthTickTimer=setInterval(t,n)}stopHealthTick(){this.healthTickTimer!==null&&(clearInterval(this.healthTickTimer),this.healthTickTimer=null),this.healthTickPromise=null}scheduleKeepSession(n,e,t){this.clearRefreshTimer(),this.sessionRefreshToken=n;let s=Math.max((e-this.refreshBuffer)*1e3,0);this.refreshTimer=setTimeout(async()=>{if(this.sessionRefreshToken)try{let i=await t(this.sessionRefreshToken);this.onTokenRefreshed?.(i.access_token,i.expires_in),this.scheduleKeepSession(this.sessionRefreshToken,i.expires_in,t)}catch(i){this.clearRefreshTimer(),this.onSessionExpired?.(i instanceof Error?i:new Error(String(i)))}},s)}clearRefreshTimer(){this.refreshTimer!==null&&(clearTimeout(this.refreshTimer),this.refreshTimer=null)}stopKeepSession(){this.clearRefreshTimer(),this.sessionRefreshToken=null}applyRealtimeOptions(n){let e=typeof n=="boolean"?{enabled:n}:n??{};if(this.realtimeEnabled=e.enabled??!1,this.realtimePath=String(e.path??ne).trim()||ne,this.realtimeAutoReconnect=e.autoReconnect??!0,this.realtimeReconnectDelayMs=Math.max(250,e.reconnectDelayMs??3e3),!this.realtimeEnabled){this.disconnectRealtime("realtime_disabled");return}this.setRealtimeStatus("idle","realtime_enabled")}buildRealtimeUrl(){let n=this.baseUrl||Y("VITE_ENTITY_SERVER_URL")||"",e=typeof window<"u"?window.location.origin:"",t=n||e;if(!t)throw new Error("Realtime connection requires baseUrl.");let s=new URL(t,e||void 0),i=s.pathname==="/"?"":s.pathname.replace(/\/+$/,""),o=`/${this.realtimePath.replace(/^\/+/,"")}`;return s.pathname=`${i}${o}`||o,s.search="",s.hash="",s.protocol=s.protocol==="https:"?"wss:":"ws:",s.searchParams.set("access_token",this.token),s.toString()}handleRealtimeMessage(n){if(typeof n!="string")return;let e;try{e=JSON.parse(n)}catch{return}for(let s of this.realtimeMessageListeners)s(e);let t=this.realtimeEventListeners.get(e.event);if(t)for(let s of t)s(e)}scheduleRealtimeReconnect(n){this.clearRealtimeReconnectTimer(),this.realtimeReconnectTimer=setTimeout(()=>{this.realtimeReconnectTimer=null,!(!this.realtimeEnabled||!this.token)&&(this.setRealtimeStatus("connecting",`${n}:reconnect`),this.connectRealtime().catch(()=>{}))},this.realtimeReconnectDelayMs)}clearRealtimeReconnectTimer(){this.realtimeReconnectTimer!==null&&(clearTimeout(this.realtimeReconnectTimer),this.realtimeReconnectTimer=null)}setRealtimeStatus(n,e,t){let s=this.realtimeStatus;if(!(s===n&&typeof e>"u"&&typeof t>"u")){this.realtimeStatus=n;for(let i of this.realtimeStatusListeners)i({status:n,previousStatus:s,...e?{reason:e}:{},...t?{error:t}:{}})}}applyCsrfHealth(){if(!(typeof document>"u")){for(let n of document.cookie.split(";")){let e=n.indexOf("=");if(!(e<0)&&n.substring(0,e).trim()===this.csrfCookieName){this.csrfEnabled=!!n.substring(e+1).trim();return}}this.csrfEnabled=!1}}readRequestBody(n,e="application/json",t=!1){let s=_(this.hmacSecret,this.token||this.anonymousPacketToken);return He(n,e,t,s)}get reqOpts(){return{baseUrl:this.baseUrl,token:this.token,anonymousPacketToken:this.anonymousPacketToken,apiKey:this.apiKey,hmacSecret:this.hmacSecret,encryptRequests:this.encryptRequests,csrfEnabled:this.csrfEnabled,csrfHeaderName:this.csrfHeaderName,csrfCookieName:this.csrfCookieName,refreshCsrfCookie:this.csrfEnabled?this.csrfRefresher:null,requestAbortControllers:this.requestAbortControllers,debugPlainSecret:this.debugPlainSecret,onAccessToken:n=>{this.setAccessTokenFromResponse(n)}}}prepareRequest(n){return Promise.resolve()}get http(){let n=this;return{get(e,t=!0,s,i){return n.prepareRequest(t).then(()=>E(n.reqOpts,"GET",e,void 0,t,s,i??!0))},post(e,t,s=!0,i,o){return n.prepareRequest(s).then(()=>E(n.reqOpts,"POST",e,t,s,i,o??!0))},put(e,t,s=!0,i,o){return n.prepareRequest(s).then(()=>E(n.reqOpts,"PUT",e,t,s,i,o??!0))},patch(e,t,s=!0,i,o){return n.prepareRequest(s).then(()=>E(n.reqOpts,"PATCH",e,t,s,i,o??!0))},delete(e,t,s=!0,i,o){return n.prepareRequest(s).then(()=>E(n.reqOpts,"DELETE",e,t,s,i,o??!0))}}}request(n,e,t,s=!0,i,o){return this.prepareRequest(s).then(()=>E(this.reqOpts,n,e,t,s,i,o??!0))}async requestBinary(n,e,t,s=!0){await this.prepareRequest(s);let i={"Content-Type":"application/json"};s&&this.token&&(i.Authorization=`Bearer ${this.token}`),this.apiKey&&(i["X-API-Key"]=this.apiKey);let o=await fetch(this.baseUrl+e,{method:n,headers:i,...t!=null?{body:JSON.stringify(t)}:{},credentials:"include"});if(!o.ok){let a=await o.text(),u=new Error(`HTTP ${o.status}: ${a}`);throw u.status=o.status,u}return o.arrayBuffer()}async requestForm(n,e,t,s=!0){return await this.prepareRequest(s),Ke(this.reqOpts,n,e,t,s)}async requestFormBinary(n,e,t,s=!0){let i={};s&&this.token&&(i.Authorization=`Bearer ${this.token}`),this.apiKey&&(i["X-API-Key"]=this.apiKey);let o=await fetch(this.baseUrl+e,{method:n,headers:i,body:t,credentials:"include"});if(!o.ok){let a=await o.text(),u=new Error(`HTTP ${o.status}: ${a}`);throw u.status=o.status,u}return o.arrayBuffer()}};function Ne(r){return r.ok===!0&&r.requires_2fa!==!0&&typeof r.data=="object"&&r.data!==null&&"access_token"in r.data}function re(r){return class extends r{authBootstrapPromise=null;authBootstrapToken="";authBootstrapAnonymousCompleted=!1;setAccessTokenFromResponse(e){super.setAccessTokenFromResponse(e),this.authBootstrapToken=e,this.authBootstrapAnonymousCompleted=!1}csrfRefresher=()=>this.checkHealth(this.keepSession).then(()=>{});async checkHealth(e=!1){try{let t=this.token,s={};e&&(s["X-Session-Bootstrap"]="1");let i=await fetch(`${this.baseUrl}/v1/health`,{signal:AbortSignal.timeout(3e3),credentials:"include",headers:s}),o=await i.json(),a=i.headers.get("X-Access-Token");a&&(this.token=a,e&&a!==t&&this.onTokenRefreshed?.(a,0));let u=i.headers.get("X-Packet-Encryption")==="1"||o.packet_encryption===!0,d=this.readCookie("anon_token");return u&&d&&(this.anonymousPacketToken=d,this.encryptRequests=!0),this.applyCsrfHealth(),this.onHealthChange?.(!0),e&&o.authenticated===!1&&t&&(this.disconnectRealtime("session_expired"),this.onSessionExpired?.(new Error("Session expired"))),o}catch(t){throw this.onHealthChange?.(!1),t}}readCookie(e){if(typeof document>"u")return null;let t=document.cookie.split(";").map(s=>s.trim()).find(s=>s.startsWith(`${e}=`));if(!t)return null;try{return decodeURIComponent(t.slice(e.length+1))}catch{return t.slice(e.length+1)}}async ensurePublicAuthBootstrap(){if(typeof document>"u"||this.apiKey&&this.hmacSecret)return;let e=!!this.anonymousPacketToken||!!this.readCookie("anon_token"),t=!!this.readCookie(this.csrfCookieName);e&&t&&this.csrfEnabled||await this.checkHealth(!1)}async ensureAuthenticatedRequestBootstrap(){if(!(typeof document>"u")&&!(this.apiKey&&this.hmacSecret)){if(this.token){if(this.authBootstrapToken===this.token)return}else if(this.authBootstrapAnonymousCompleted)return;return this.authBootstrapPromise?this.authBootstrapPromise:(this.authBootstrapPromise=this.checkHealth(!0).then(()=>{this.token?this.authBootstrapToken=this.token:this.authBootstrapAnonymousCompleted=!0}).finally(()=>{this.authBootstrapPromise=null}),this.authBootstrapPromise)}}async prepareRequest(e){await super.prepareRequest(e),e&&await this.ensureAuthenticatedRequestBootstrap()}async login(e,t){await this.ensurePublicAuthBootstrap();let s=await E(this.reqOpts,"POST","/v1/auth/login",{email:e,passwd:t},!1,{},{requireOkShape:!1,allowStatuses:[403]});return Ne(s)&&(this.token=s.data.access_token,this.applyCsrfHealth(),this.keepSession&&this.healthTickTimer===null&&this.startHealthTick()),s}async tokenRefresh(){let e=await this.request("POST","/v1/auth/token_refresh",void 0,!1);return this.token=e.data.access_token,this.applyCsrfHealth(),e.data}async refreshToken(e){if(!e)return this.tokenRefresh();let t=await this.request("POST","/v1/auth/refresh",{refresh_token:e},!1);return this.token=t.data.access_token,this.applyCsrfHealth(),t.data}async logout(e){this.stopKeepSession(),this.stopHealthTick(),this.disconnectRealtime("logout");let t=await this.request("POST","/v1/auth/logout",e?{refresh_token:e}:void 0,!1);return this.token="",this.applyCsrfHealth(),t}me(){return this.request("GET","/v1/auth/me")}withdraw(e){return this.request("POST","/v1/auth/withdraw",e?{passwd:e}:{})}}}function se(r){return class extends r{async transStart(){let e=await this.request("POST","/v1/transaction/start",void 0,!1);return this.activeTxId=e.transaction_id,this.activeTxId}transRollback(e){let t=e??this.activeTxId;return t?(this.activeTxId=null,this.request("POST",`/v1/transaction/rollback/${t}`)):Promise.reject(new Error("No active transaction. Call transStart() first."))}transCommit(e){let t=e??this.activeTxId;return t?(this.activeTxId=null,this.request("POST",`/v1/transaction/commit/${t}`)):Promise.reject(new Error("No active transaction. Call transStart() first."))}meta(e){return this.request("POST",`/v1/entity/${e}/meta`,{})}validate(e,t){return this.http.post(`/v1/entity/${e}/validate`,t)}get(e,t,s={}){let i=s.skipHooks?"?skipHooks=true":"";return this.request("GET",`/v1/entity/${e}/${t}${i}`)}find(e,t,s={}){let i=s.skipHooks?"?skipHooks=true":"";return this.request("POST",`/v1/entity/${e}/find${i}`,t??{})}list(e,t={}){let{conditions:s,fields:i,orderDir:o,orderBy:a,...u}=t,d={page:1,limit:20,...u};return a&&(d.orderBy=o==="DESC"?`-${a}`:a),i?.length&&(d.fields=i.join(",")),this.request("POST",`/v1/entity/${e}/list?${l(d)}`,s??{})}count(e,t){return this.request("POST",`/v1/entity/${e}/count`,t??{})}query(e,t){return this.request("POST",`/v1/entity/${e}/query`,t)}submit(e,t,s={}){let i=s.transactionId??this.activeTxId,o=i?{"X-Transaction-ID":i}:void 0,a=s.skipHooks?"?skipHooks=true":"";return this.request("POST",`/v1/entity/${e}/submit${a}`,t,!0,o)}delete(e,t,s={}){let i=new URLSearchParams;s.hard&&i.set("hard","true"),s.skipHooks&&i.set("skipHooks","true");let o=i.size?`?${i}`:"",a=s.transactionId??this.activeTxId,u=a?{"X-Transaction-ID":a}:void 0;return this.request("POST",`/v1/entity/${e}/delete/${t}${o}`,void 0,!0,u)}history(e,t,s={}){return this.request("GET",`/v1/entity/${e}/history/${t}?${l({page:1,limit:50,...s})}`)}rollback(e,t){return this.request("POST",`/v1/entity/${e}/rollback/${t}`)}}}function ie(r){return class extends r{async fileUpload(e,t,s={}){let i=new FormData;return i.append("file",t,t instanceof File?t.name:"upload"),s.refSeq!=null&&i.append("ref_seq",String(s.refSeq)),s.isPublic!=null&&i.append("is_public",s.isPublic?"true":"false"),this.requestForm("POST",`/v1/files/${e}/upload`,i)}fileDownload(e,t){return this.requestBinary("POST",`/v1/files/${e}/download/${t}`,{})}fileDelete(e,t){return this.request("POST",`/v1/files/${e}/delete/${t}`,{})}fileList(e,t={}){return this.request("POST",`/v1/files/${e}/list`,t.refSeq?{ref_seq:t.refSeq}:{})}fileMeta(e,t){return this.request("POST",`/v1/files/${e}/meta/${t}`,{})}fileToken(e){return this.request("POST",`/v1/files/token/${e}`,{})}fileViewUrl(e,t={}){let s=t.download?"?download=true":"";return`${this.baseUrl}/v1/files/${e}${s}`}fileUrl(e){return`${this.baseUrl}/v1/files/${e}`}storageUpload(e,t,s={}){return this.fileUpload(e,t,s)}storageDownload(e,t){return this.fileDownload(e,t)}storageDelete(e,t){return this.fileDelete(e,t)}storageList(e,t={}){return this.fileList(e,t)}storageMeta(e,t){return this.fileMeta(e,t)}storageToken(e){return this.fileToken(e)}storageViewUrl(e,t={}){return this.fileViewUrl(e,t)}storageDownloadUrl(e){return this.fileViewUrl(e,{download:!0})}storageUrl(e){return this.fileUrl(e)}}}function oe(r){return class extends r{push(e,t,s={}){return this.submit(e,t,s)}pushLogList(e={}){return this.list("push_log",e)}registerPushDevice(e,t,s,i={}){let{platform:o,deviceType:a,browser:u,browserVersion:d,pushEnabled:k=!0,transactionId:h}=i;return this.submit("account_device",{id:t,account_seq:e,push_token:s,push_enabled:k,...o?{platform:o}:{},...a?{device_type:a}:{},...u?{browser:u}:{},...d?{browser_version:d}:{}},{transactionId:h})}updatePushDeviceToken(e,t,s={}){let{pushEnabled:i=!0,transactionId:o}=s;return this.submit("account_device",{seq:e,push_token:t,push_enabled:i},{transactionId:o})}disablePushDevice(e,t={}){return this.submit("account_device",{seq:e,push_enabled:!1},{transactionId:t.transactionId})}}}function ae(r){return class extends r{smtpSend(e){return this.request("POST","/v1/smtp/send",e)}smtpStatus(e){return this.request("POST",`/v1/smtp/status/${e}`,{})}smtpTemplatePreview(e){let t=e.split("/").map(encodeURIComponent).join("/");return fetch(`${this.baseUrl}/v1/smtp/template/${t}`,{credentials:"include"}).then(s=>s.text())}}}function ue(r){return class extends r{transactionStart(e){return this.request("POST","/v1/transaction/start",e??{})}transactionCommit(e){return this.request("POST",`/v1/transaction/commit/${encodeURIComponent(e)}`,{})}transactionRollback(e){return this.request("POST",`/v1/transaction/rollback/${encodeURIComponent(e)}`,{})}}}function ce(r){return class extends r{addressSido(){return this.http.get("/v1/utils/address/sido",!1)}addressSigungu(e){let t=new URLSearchParams({sido:e.sido}).toString();return this.http.get(`/v1/utils/address/sigungu?${t}`,!1)}addressDong(e){let t=new URLSearchParams({sido:e.sido,sigungu:e.sigungu}).toString();return this.http.get(`/v1/utils/address/dong?${t}`,!1)}addressClean(e){let t=new URLSearchParams({q:e.q}).toString();return this.http.get(`/v1/utils/address/clean?${t}`,!1)}qrcode(e,t={}){return this.requestBinary("POST","/v1/utils/qrcode",{content:e,...t})}qrcodeBase64(e,t={}){return this.request("POST","/v1/utils/qrcode/base64",{content:e,...t})}qrcodeText(e,t={}){return this.request("POST","/v1/utils/qrcode/text",{content:e,...t})}barcode(e,t={}){return this.requestBinary("POST","/v1/utils/barcode",{content:e,...t})}pdf2png(e,t={}){let s=new FormData;s.append("file",new Blob([e],{type:"application/pdf"}),"document.pdf");let i=new URLSearchParams;t.dpi!=null&&i.set("dpi",String(t.dpi)),t.firstPage!=null&&i.set("first_page",String(t.firstPage)),t.lastPage!=null&&i.set("last_page",String(t.lastPage));let o=i.toString(),a="/v1/utils/pdf2png"+(o?`?${o}`:"");return this.requestFormBinary("POST",a,s)}pdf2pngByFileSeq(e,t={}){return this.requestBinary("POST",`/v1/utils/pdf2png/${e}`,t)}pdf2jpg(e,t={}){let s=new FormData;s.append("file",new Blob([e],{type:"application/pdf"}),"document.pdf");let i=new URLSearchParams;t.dpi!=null&&i.set("dpi",String(t.dpi)),t.firstPage!=null&&i.set("first_page",String(t.firstPage)),t.lastPage!=null&&i.set("last_page",String(t.lastPage));let o=i.toString(),a="/v1/utils/pdf2jpg"+(o?`?${o}`:"");return this.requestFormBinary("POST",a,s)}pdf2jpgByFileSeq(e,t={}){return this.requestBinary("POST",`/v1/utils/pdf2jpg/${e}`,t)}}}function le(r){return class extends r{adminPath(e){return`/v1/admin${e}`}adminGet(e){return this.http.get(this.adminPath(e))}adminPost(e,t){return this.http.post(this.adminPath(e),t)}adminPut(e,t){return this.http.put(this.adminPath(e),t)}adminPatch(e,t){return this.http.patch(this.adminPath(e),t)}adminDelete(e,t){return this.http.delete(this.adminPath(e),t)}listAdminEntities(){return this.adminGet("/entities")}getAdminErdSchema(){return this.adminGet("/erd/schema")}batchEnsureAdminEntities(e){return this.adminPost("/entities/batch-ensure",e)}createAdminEntityConfig(e,t){return this.adminPost(`/${e}/create`,t)}getAdminEntityConfig(e){return this.adminGet(`/${e}/config`)}updateAdminEntityConfig(e,t){return this.adminPut(`/${e}/config`,t)}validateAdminEntityConfig(e,t){return this.adminPost(t?`/${t}/validate`:"/entity/validate",e)}normalizeAdminEntityConfig(e,t){return this.adminPost(t?`/${t}/normalize`:"/entity/normalize",e)}getAdminEntityStats(e,t){return this.adminPost(`/${e}/stats`,t)}reindexAdminEntity(e){return this.adminPost(`/${e}/reindex`)}syncAdminEntitySchema(e){return this.adminPost(`/${e}/sync-schema`)}resetAdminEntity(e){return this.adminPost(`/${e}/reset`)}truncateAdminEntity(e){return this.adminPost(`/${e}/truncate`)}dropAdminEntity(e){return this.adminPost(`/${e}/drop`)}resetAllAdmin(e){return this.adminPost("/reset-all",e)}listAdminConfigs(){return this.adminGet("/configs")}getAdminConfig(e){return this.adminGet(`/configs/${e}`)}updateAdminConfig(e,t){return this.adminPatch(`/configs/${e}`,t)}listAdminRoles(){return this.adminGet("/roles")}createAdminRole(e){return this.adminPost("/roles",e)}getAdminRole(e){return this.adminGet(`/roles/${e}`)}updateAdminRole(e,t){return this.adminPatch(`/roles/${e}`,t)}deleteAdminRole(e){return this.adminDelete(`/roles/${e}`)}listAdminApiKeys(){return this.adminGet("/api-keys")}createAdminApiKey(e){return this.adminPost("/api-keys",e)}getAdminApiKey(e){return this.adminGet(`/api-keys/${e}`)}updateAdminApiKey(e,t){return this.adminPatch(`/api-keys/${e}`,t)}deleteAdminApiKey(e){return this.adminDelete(`/api-keys/${e}`)}regenerateAdminApiKeySecret(e){return this.adminPost(`/api-keys/${e}/regenerate-secret`)}listAdminAccounts(){return this.adminGet("/accounts")}createAdminAccount(e){return this.adminPost("/accounts",e)}getAdminAccount(e){return this.adminGet(`/accounts/${e}`)}updateAdminAccount(e,t){return this.adminPatch(`/accounts/${e}`,t)}deleteAdminAccount(e){return this.adminDelete(`/accounts/${e}`)}listAdminLicenses(){return this.adminGet("/licenses")}createAdminLicense(e){return this.adminPost("/licenses",e)}getAdminLicense(e){return this.adminGet(`/licenses/${e}`)}updateAdminLicense(e,t){return this.adminPatch(`/licenses/${e}`,t)}deleteAdminLicense(e){return this.adminDelete(`/licenses/${e}`)}runAdminBackup(e){return this.adminPost("/backup/run",e)}getAdminBackupStatus(e){return this.adminPost("/backup/status",e)}listAdminBackups(e){return this.adminPost("/backup/list",e)}restoreAdminBackup(e){return this.adminPost("/backup/restore",e)}deleteAdminBackup(e){return this.adminPost("/backup/delete",e)}disableAdminAccountTwoFactor(e){return this.adminDelete(`/accounts/${e}/2fa`)}}}var $=class extends ce(ue(ie(ae(oe(le(se(re(X)))))))){};function me(r){return class extends r{accountRegister(e){return this.http.post("/v1/account/register",e,!1)}accountWithdraw(e){return this.http.post("/v1/account/withdraw",e)}accountChangePassword(e){return this.http.post("/v1/account/change-password",e)}accountReactivate(e){return this.http.post("/v1/account/reactivate",e,!1)}listAccountBiometrics(){return this.http.get("/v1/account/biometric")}registerAccountBiometric(e){return this.http.post("/v1/account/biometric",e)}deleteAccountBiometric(e){return this.http.delete(`/v1/account/biometric/${e}`)}}}function de(r){return class extends r{listBoardCategories(e={}){let t=l(e);return this.http.get(`/v1/board/categories${t?`?${t}`:""}`,!1)}getBoardCategory(e){return this.http.get(`/v1/board/categories/${e}`,!1)}createBoardCategory(e){return this.http.post("/v1/board/categories",e)}updateBoardCategory(e,t){return this.http.put(`/v1/board/categories/${e}`,t)}deleteBoardCategory(e){return this.http.delete(`/v1/board/categories/${e}`)}listBoardPosts(e,t={}){let s=l(t);return this.http.get(`/v1/board/${e}/list${s?`?${s}`:""}`)}getBoardPost(e){return this.http.get(`/v1/board/posts/${e}`)}createBoardPost(e,t){return this.http.post(`/v1/board/${e}/submit`,t)}updateBoardPost(e,t){return this.http.patch(`/v1/board/posts/${e}`,t)}expireBoardPost(e){return this.http.post(`/v1/board/posts/${e}/expire`,{})}deleteBoardPost(e){return this.http.delete(`/v1/board/posts/${e}`)}listBoardComments(e,t={}){let s=l(t);return this.http.get(`/v1/board/posts/${e}/comments${s?`?${s}`:""}`,!1)}createBoardComment(e,t){return this.http.post(`/v1/board/posts/${e}/comments/submit`,t)}updateBoardComment(e,t){return this.http.put(`/v1/board/comments/${e}`,t)}deleteBoardComment(e){return this.http.delete(`/v1/board/comments/${e}`)}listBoardFiles(e){return this.http.get(`/v1/board/posts/${e}/files`,!1)}async uploadBoardFile(e,t){let s=new FormData;return s.append("file",t,t instanceof File?t.name:"upload"),this.requestForm("POST",`/v1/board/posts/${e}/files`,s)}boardFileUrl(e){return`${this.baseUrl}/v1/board/files/${e}`}deleteBoardFile(e){return this.http.delete(`/v1/board/files/${e}`)}createBoardGuestPost(e,t){return this.http.post(`/v1/board/${e}/guest-submit`,t,!1)}authenticateBoardGuestPost(e,t){return this.http.post(`/v1/board/posts/${e}/guest-auth`,t,!1)}toggleBoardPostLike(e){return this.http.post(`/v1/board/posts/${e}/like`,{})}acceptBoardPost(e){return this.http.post(`/v1/board/posts/${e}/accept`,{})}rateBoardPost(e,t){return this.http.post(`/v1/board/posts/${e}/rating`,t)}rateBoardComment(e,t){return this.http.post(`/v1/board/comments/${e}/rating`,t)}listBoardTags(e={}){let t=l(e);return this.http.get(`/v1/board/tags${t?`?${t}`:""}`,!1)}setBoardPostTags(e,t){return this.http.put(`/v1/board/posts/${e}/tags`,t)}reportBoardPost(e,t){return this.http.post(`/v1/board/posts/${e}/report`,t)}reportBoardComment(e,t){return this.http.post(`/v1/board/comments/${e}/report`,t)}listBoardReports(e={}){let t=l(e);return this.http.get(`/v1/board/admin/reports${t?`?${t}`:""}`)}updateBoardReport(e,t){return this.http.patch(`/v1/board/admin/reports/${e}`,t)}markBoardPostRead(e){return this.http.post(`/v1/board/posts/${e}/read`,{})}listBoardMentions(e={}){let t=l(e);return this.http.get(`/v1/board/mentions${t?`?${t}`:""}`)}markBoardMentionRead(e){return this.http.patch(`/v1/board/mentions/${e}/read`,{})}}}function he(r){return class extends r{sendEmailVerification(e){return this.http.post("/v1/email-verify/send",e,!1)}confirmEmailVerification(e){return this.http.post("/v1/email-verify/confirm",e,!1)}activateEmailVerification(e){let t=l(e);return this.http.get(`/v1/email-verify/activate${t?`?${t}`:""}`,!1)}getEmailVerificationStatus(){return this.http.get("/v1/email-verify/status")}changeVerifiedEmail(e){return this.http.post("/v1/email-verify/change",e)}}}function pe(r){return class extends r{oauthAuthorizeUrl(e,t={}){let s=l(t);return`${this.baseUrl}/v1/oauth/${e}${s?`?${s}`:""}`}oauthCallback(e,t,s="POST"){if(s==="GET"){let i=l(t??{});return this.http.get(`/v1/oauth/${e}/callback${i?`?${i}`:""}`,!1)}return this.http.post(`/v1/oauth/${e}/callback`,t,!1)}linkOAuthAccount(e){return this.http.post("/v1/account/oauth/link",e)}unlinkOAuthAccount(e){return this.http.delete(`/v1/account/oauth/link/${e}`)}listOAuthProviders(){return this.http.get("/v1/account/oauth/providers")}refreshOAuthProviderToken(e,t){return this.http.post(`/v1/account/oauth/refresh/${e}`,t)}}}function fe(r){return class extends r{requestPasswordReset(e){return this.http.post("/v1/password-reset/request",e,!1)}validatePasswordResetToken(e){return this.http.get(`/v1/password-reset/validate/${encodeURIComponent(e)}`,!1)}verifyPasswordReset(e){return this.http.post("/v1/password-reset/verify",e,!1)}}}function ge(r){return class extends r{setupTwoFactor(e){return this.http.post("/v1/account/2fa/setup",e)}verifyTwoFactorSetup(e){return this.http.post("/v1/account/2fa/setup/verify",e,!1)}disableTwoFactor(){return this.http.delete("/v1/account/2fa")}getTwoFactorStatus(){return this.http.get("/v1/account/2fa/status")}regenerateTwoFactorRecoveryCodes(){return this.http.post("/v1/account/2fa/recovery/regenerate")}verifyTwoFactor(e){return this.http.post("/v1/account/2fa/verify",e,!1)}recoverTwoFactorAccess(e){return this.http.post("/v1/account/2fa/recovery",e,!1)}}}function ke(r){return class extends r{alimtalkSend(e){return this.http.post("/v1/alimtalk/send",e)}alimtalkStatus(e){return this.http.get(`/v1/alimtalk/status/${e}`,!1)}listAlimtalkTemplates(){return this.http.get("/v1/alimtalk/templates",!1)}alimtalkWebhook(e,t){return this.http.post(`/v1/alimtalk/webhook/${encodeURIComponent(e)}`,t,!1)}}}function Te(r){return class extends r{friendtalkSend(e){return this.http.post("/v1/friendtalk/send",e)}}}function ye(r){return class extends r{listHolidays(e={}){let t=l(e);return this.http.get(`/v1/holidays${t?`?${t}`:""}`,!1)}getHolidayByDate(e){return this.http.get(`/v1/holidays/${encodeURIComponent(e)}`,!1)}syncHolidays(e){return this.http.post("/v1/holidays/sync",e)}}}function Pe(r){return class extends r{identityRequest(e){return this.http.post("/v1/identity/request",e,!1)}identityCallback(e){return this.http.post("/v1/identity/callback",e,!1)}identityResult(e){return this.http.get(`/v1/identity/result/${encodeURIComponent(e)}`,!1)}identityVerifyCI(e){return this.http.post("/v1/identity/verify-ci",e)}}}function be(r){return class extends r{llmChat(e){return this.http.post("/v1/llm/chat",e)}llmChatStream(e){return this.http.post("/v1/llm/chat/stream",e)}createLlmConversation(e){return this.http.post("/v1/llm/conversations",e)}sendLlmMessage(e,t){return this.http.post(`/v1/llm/conversations/${e}/messages`,t)}listLlmConversations(e={}){let t=l(e);return this.http.get(`/v1/llm/conversations${t?`?${t}`:""}`)}getLlmConversation(e){return this.http.get(`/v1/llm/conversations/${e}`)}updateLlmConversation(e,t){return this.http.patch(`/v1/llm/conversations/${e}`,t)}deleteLlmConversation(e){return this.http.delete(`/v1/llm/conversations/${e}`)}ragUploadDocument(e){return this.requestForm("POST","/v1/llm/rag/documents",e)}ragListDocuments(e={}){let t=l(e);return this.http.get(`/v1/llm/rag/documents${t?`?${t}`:""}`)}ragDeleteDocument(e){return this.http.delete(`/v1/llm/rag/documents/${encodeURIComponent(e)}`)}ragSearch(e){return this.http.post("/v1/llm/rag/search",e)}ragChat(e){return this.http.post("/v1/llm/rag/chat",e)}ragChatStream(e){return this.http.post("/v1/llm/rag/chat/stream",e)}ragRebuildIndex(e){return this.http.post("/v1/llm/rag/rebuild-index",e)}listLlmProviders(){return this.http.get("/v1/llm/providers")}getLlmUsage(e={}){let t=l(e);return this.http.get(`/v1/llm/usage${t?`?${t}`:""}`)}getLlmUsageSummary(e={}){let t=l(e);return this.http.get(`/v1/llm/usage/summary${t?`?${t}`:""}`)}getLlmCacheStats(){return this.http.get("/v1/llm/cache/stats")}clearLlmCache(){return this.http.delete("/v1/llm/cache")}listLlmTemplates(){return this.http.get("/v1/llm/templates")}llmTemplateChat(e,t){return this.http.post(`/v1/llm/${encodeURIComponent(e)}/chat`,t)}llmTemplateChatStream(e,t){return this.http.post(`/v1/llm/${encodeURIComponent(e)}/chat/stream`,t)}listLlmChatbots(e={}){let t=l(e);return this.http.get(`/v1/llm/chatbots${t?`?${t}`:""}`)}createLlmChatbot(e){return this.http.post("/v1/llm/chatbots",e)}getLlmChatbot(e){return this.http.get(`/v1/llm/chatbots/${e}`)}updateLlmChatbot(e,t){return this.http.patch(`/v1/llm/chatbots/${e}`,t)}deleteLlmChatbot(e){return this.http.delete(`/v1/llm/chatbots/${e}`)}llmChatbotChat(e,t){return this.http.post(`/v1/llm/chatbots/${e}/chat`,t)}llmChatbotChatStream(e,t){return this.http.post(`/v1/llm/chatbots/${e}/chat/stream`,t)}listLlmChatbotSessions(e,t={}){let s=l(t);return this.http.get(`/v1/llm/chatbots/${e}/sessions${s?`?${s}`:""}`)}deleteLlmChatbotSession(e,t){return this.http.delete(`/v1/llm/chatbots/${e}/sessions/${t}`)}listLlmProfiles(e={}){let t=l(e);return this.http.get(`/v1/llm/profiles${t?`?${t}`:""}`)}upsertLlmProfile(e){return this.http.post("/v1/llm/profiles",e)}deleteLlmProfile(e){return this.http.delete(`/v1/llm/profiles/${e}`)}}}function we(r){return class extends r{ocrRecognize(e){return this.requestForm("POST","/v1/ocr/recognize",e)}ocrRecognizeAsync(e){return this.requestForm("POST","/v1/ocr/recognize/async",e)}ocrRecognizeByDocType(e,t){return this.requestForm("POST",`/v1/ocr/${encodeURIComponent(e)}`,t)}listOcrResults(e={}){let t=l(e);return this.http.get(`/v1/ocr/results${t?`?${t}`:""}`)}getOcrResult(e){return this.http.get(`/v1/ocr/results/${encodeURIComponent(e)}`)}getOcrResultText(e){return this.http.get(`/v1/ocr/results/${encodeURIComponent(e)}/text`)}deleteOcrResult(e){return this.http.delete(`/v1/ocr/results/${encodeURIComponent(e)}`)}getOcrQuota(){return this.http.get("/v1/ocr/quota")}}}function ve(r){return class extends r{pgCreateOrder(e){return this.http.post("/v1/pg/orders",e)}pgGetOrder(e){return this.http.get(`/v1/pg/orders/${encodeURIComponent(e)}`)}pgConfirmPayment(e){return this.http.post("/v1/pg/confirm",e)}pgCancelPayment(e,t){return this.http.post(`/v1/pg/orders/${encodeURIComponent(e)}/cancel`,t)}pgSyncPaymentStatus(e,t){return this.http.post(`/v1/pg/orders/${encodeURIComponent(e)}/sync`,t)}pgWebhook(e){return this.http.post("/v1/pg/webhook",e,!1)}pgGetClientConfig(){return this.http.get("/v1/pg/config",!1)}}}function Re(r){return class extends r{appPushSend(e){return this.http.post("/v1/push/send",e)}appPushBroadcast(e){return this.http.post("/v1/push/broadcast",e)}appPushStatus(e){return this.http.get(`/v1/push/status/${e}`)}appPushRegisterDevice(e){return this.http.post("/v1/push/device",e)}appPushUnregisterDevice(e){return this.http.delete(`/v1/push/device/${e}`)}}}function Se(r){return class extends r{smsSend(e){return this.http.post("/v1/sms/send",e)}smsStatus(e){return this.http.get(`/v1/sms/status/${e}`,!1)}smsVerificationSend(e){return this.http.post("/v1/sms/verification/send",e,!1)}smsVerificationVerify(e){return this.http.post("/v1/sms/verification/verify",e,!1)}}}function Ce(r){return class extends r{taxinvoiceRegistIssue(e){return this.http.post("/v1/taxinvoice",e)}taxinvoiceRegister(e){return this.http.post("/v1/taxinvoice/register",e)}taxinvoiceIssue(e){return this.http.post(`/v1/taxinvoice/${e}/issue`,{})}taxinvoiceCancelIssue(e,t){return this.http.post(`/v1/taxinvoice/${e}/cancel`,t)}taxinvoiceGetState(e){return this.http.get(`/v1/taxinvoice/${e}/state`)}taxinvoiceGetDetail(e){return this.http.get(`/v1/taxinvoice/${e}`)}}}var H=class extends ke(Te(Se(Re(ve(Ce(we(be(Pe(ye(pe(ge(fe(he(de(me($)))))))))))))))){};var Ve=new $,We=new H;function Sr(r={}){return W(r,{singletonInstance:Ve,ClientClass:$})}function Ar(r={}){return W(r,{singletonInstance:We,ClientClass:H})}export{Ar as useEntityAppServer,W as useEntityClient,Sr as useEntityServer};
2
2
  //# sourceMappingURL=react.js.map