entity-server-client 1.0.2 → 1.0.3
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/EntityServerClient.d.ts +40 -40
- package/dist/client/base.d.ts +2 -2
- package/dist/hooks/useEntityServer.d.ts +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +1 -1
- package/dist/index.js.map +2 -2
- package/dist/mixins/auth.d.ts +4 -4
- package/dist/mixins/entity.d.ts +5 -5
- package/dist/mixins/file.d.ts +5 -5
- package/dist/mixins/push.d.ts +5 -5
- package/dist/mixins/smtp.d.ts +5 -5
- package/dist/mixins/utils.d.ts +5 -5
- package/dist/react.d.ts +1 -1
- package/dist/react.js +1 -1
- package/dist/react.js.map +2 -2
- package/package.json +2 -2
package/dist/mixins/utils.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { QRCodeOptions, BarcodeOptions, Pdf2PngOptions } from "../types";
|
|
2
|
-
import type { GConstructor, EntityServerClientBase } from "../client/base";
|
|
1
|
+
import type { QRCodeOptions, BarcodeOptions, Pdf2PngOptions } from "../types.js";
|
|
2
|
+
import type { GConstructor, EntityServerClientBase } from "../client/base.js";
|
|
3
3
|
export declare function UtilsMixin<TBase extends GConstructor<EntityServerClientBase>>(Base: TBase): {
|
|
4
4
|
new (...args: any[]): {
|
|
5
5
|
/**
|
|
@@ -69,7 +69,7 @@ export declare function UtilsMixin<TBase extends GConstructor<EntityServerClient
|
|
|
69
69
|
_refreshTimer: ReturnType<typeof setTimeout> | null;
|
|
70
70
|
_csrfRefreshTimer: ReturnType<typeof setTimeout> | null;
|
|
71
71
|
_csrfRefreshPromise: Promise<string> | null;
|
|
72
|
-
configure(options: Partial<import("
|
|
72
|
+
configure(options: Partial<import("../types.js").EntityServerClientOptions>): void;
|
|
73
73
|
setToken(token: string): void;
|
|
74
74
|
setAnonymousPacketToken(token: string): void;
|
|
75
75
|
setApiKey(apiKey: string): void;
|
|
@@ -87,9 +87,9 @@ export declare function UtilsMixin<TBase extends GConstructor<EntityServerClient
|
|
|
87
87
|
stopCsrfRefresh(): void;
|
|
88
88
|
_scheduleCsrfRefresh(expiresIn: number): void;
|
|
89
89
|
refreshCsrfToken(): Promise<string>;
|
|
90
|
-
_applyCsrfHealth(csrf?: import("
|
|
90
|
+
_applyCsrfHealth(csrf?: import("../types.js").EntityServerClientHealthCsrf | null): void;
|
|
91
91
|
readRequestBody<T = Record<string, unknown>>(body: ArrayBuffer | Uint8Array | string | T | null | undefined, contentType?: string, requireEncrypted?: boolean): T;
|
|
92
|
-
get _reqOpts(): import("../client/request").RequestOptions;
|
|
92
|
+
get _reqOpts(): import("../client/request.js").RequestOptions;
|
|
93
93
|
requestJson<T>(method: string, path: string, body?: unknown, withAuth?: boolean, extraHeaders?: Record<string, string>): Promise<T>;
|
|
94
94
|
requestBinary(method: string, path: string, body?: unknown, withAuth?: boolean): Promise<ArrayBuffer>;
|
|
95
95
|
requestForm<T>(method: string, path: string, form: FormData, withAuth?: boolean): Promise<T>;
|
package/dist/react.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export * from "./hooks/useEntityServer";
|
|
1
|
+
export * from "./hooks/useEntityServer.js";
|
package/dist/react.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{useCallback as v,useEffect as se,useMemo as Te,useRef as ne,useState as ie}from"react";function F(s){let e=import.meta;if(e?.env?.[s]!=null)return e.env[s];let t=globalThis.process;if(t?.env?.[s]!=null)return t.env[s]}function U(s){return Object.entries(s).filter(([,e])=>e!=null).map(([e,t])=>`${encodeURIComponent(e==="orderBy"?"order_by":e)}=${encodeURIComponent(String(t))}`).join("&")}import{xchacha20poly1305 as N}from"@noble/ciphers/chacha";import{sha256 as ue}from"@noble/hashes/sha2";import{hkdf as fe}from"@noble/hashes/hkdf";var O=32,$=2,H=14,E=24,le=16,he="entity-server:hkdf:v1",de="entity-server:packet-encryption";function R(s){return s instanceof Uint8Array?s:new Uint8Array(s)}function L(s,e=de){return fe(ue,new TextEncoder().encode(s),new TextEncoder().encode(he),new TextEncoder().encode(e),O)}function D(s,e=$,t=H){let r=R(s);return r.length<O?e:e+r[O-1]%t}function G(s,e,t=$,r=H){let n=R(s),i=R(e),o=D(i,t,r),a=crypto.getRandomValues(new Uint8Array(o)),c=crypto.getRandomValues(new Uint8Array(E)),l=N(i,c).encrypt(n),p=new Uint8Array(o+E+l.length);return p.set(a,0),p.set(c,o),p.set(l,o+E),p}function j(s,e,t=$,r=H){let n=R(s),i=R(e),o=D(i,t,r);if(n.length<o+E+le)throw new Error("Encrypted packet too short");let a=n.slice(o,o+E),c=n.slice(o+E);return N(i,a).decrypt(c)}function x(s,e){return L(s||e)}function Q(s,e){return G(s,e)}function q(s,e){let t=j(s,e);return JSON.parse(new TextDecoder().decode(t))}function X(s,e,t,r){let n=e.toLowerCase().includes("application/octet-stream");if(t&&!n)throw new Error("Encrypted request required: Content-Type must be application/octet-stream");if(n){if(s==null)throw new Error("Encrypted request body is empty");if(s instanceof ArrayBuffer)return q(s,r);if(s instanceof Uint8Array){let i=s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength);return q(i,r)}throw new Error("Encrypted request body must be ArrayBuffer or Uint8Array")}return s==null||s===""?{}:typeof s=="string"?JSON.parse(s):s}import{sha256 as me}from"@noble/hashes/sha2";import{hmac as ye}from"@noble/hashes/hmac";function J(s,e,t,r,n){let i=String(Math.floor(Date.now()/1e3)),o=crypto.randomUUID(),a=new TextEncoder().encode(`${s}|${e}|${i}|${o}|`),c=new Uint8Array(a.length+t.length);c.set(a,0),c.set(t,a.length);let l=[...ye(me,new TextEncoder().encode(n),c)].map(p=>p.toString(16).padStart(2,"0")).join("");return{"X-API-Key":r,"X-Timestamp":i,"X-Nonce":o,"X-Signature":l}}function pe(s){return s.hmacSecret||s.token||s.anonymousPacketToken}function ke(s){return s!=="GET"&&s!=="HEAD"&&s!=="OPTIONS"}function ge(s,e){return s===403&&/csrf/i.test(e)?!0:/csrf/i.test(e)&&/expired|token validation failed/i.test(e)}async function z(s){if((s.headers.get("Content-Type")??"").includes("application/json")){let r=await s.json().catch(()=>null);if(r?.error)return r.error;if(r?.message)return r.message}return await s.text().catch(()=>"")||`HTTP ${s.status}`}async function I(s,e,t,r,n=!0,i={},o=!0){let{baseUrl:a,token:c,apiKey:h,hmacSecret:l,encryptRequests:p,anonymousPacketToken:y,csrfEnabled:T,csrfHeaderName:C,refreshCsrfToken:P}=s,_=n&&!!(h&&l),B=pe(s),f=T&&ke(e)&&!_,u=s.csrfToken,g="application/json",oe=!c&&!_&&!!y,b=null;if(r!=null)if(p&&!!B&&e!=="GET"&&e!=="HEAD"){let k=x(l,c||y);b=Q(new TextEncoder().encode(JSON.stringify(r)),k),g="application/octet-stream"}else b=JSON.stringify(r);let ae=d=>{let k={"Content-Type":g,...i};if(!_&&n&&c&&(k.Authorization=`Bearer ${c}`),oe&&(k["X-Packet-Token"]=y),f&&d&&(k[C]=d),_){let ce=b instanceof Uint8Array?b:typeof b=="string"?new TextEncoder().encode(b):new Uint8Array(0);Object.assign(k,J(e,t,ce,h,l))}return k};f&&!u&&P&&(u=await P());let K=d=>fetch(a+t,{method:e,headers:ae(d),...b!=null?{body:b}:{},credentials:"include"}),m=await K(u);if(!m.ok){let d=await z(m.clone());if(f&&P&&ge(m.status,d))u=await P(),m=await K(u);else{let k=new Error(d);throw k.status=m.status,k}}if(!m.ok){let d=new Error(await z(m));throw d.status=m.status,d}let M=m.headers.get("Content-Type")??"";if(M.includes("application/octet-stream")){let d=x(l,c||y);return q(await m.arrayBuffer(),d)}if(!M.includes("application/json"))return await m.text();let A=await m.json();if(o&&!A.ok){let d=new Error(A.message??`EntityServer error (HTTP ${m.status})`);throw d.status=m.status,d}return A}var w=class{baseUrl;token;anonymousPacketToken;apiKey;hmacSecret;encryptRequests;csrfEnabled;csrfToken;csrfHeaderName;csrfRefreshPath;csrfRefreshBuffer;activeTxId=null;keepSession;refreshBuffer;onTokenRefreshed;onSessionExpired;_sessionRefreshToken=null;_refreshTimer=null;_csrfRefreshTimer=null;_csrfRefreshPromise=null;constructor(e={}){let t=F("VITE_ENTITY_SERVER_URL");this.baseUrl=(e.baseUrl??t??"").replace(/\/$/,""),this.token=e.token??"",this.anonymousPacketToken=e.anonymousPacketToken??"",this.apiKey=e.apiKey??"",this.hmacSecret=e.hmacSecret??"",this.encryptRequests=e.encryptRequests??!1,this.csrfEnabled=e.csrfEnabled??!1,this.csrfToken=e.csrfToken??"",this.csrfHeaderName=e.csrfHeaderName??"x-csrf-token",this.csrfRefreshPath=e.csrfRefreshPath??"/v1/csrf-token",this.csrfRefreshBuffer=e.csrfRefreshBuffer??60,this.keepSession=e.keepSession??!1,this.refreshBuffer=e.refreshBuffer??60,this.onTokenRefreshed=e.onTokenRefreshed,this.onSessionExpired=e.onSessionExpired}configure(e){typeof e.baseUrl=="string"&&(this.baseUrl=e.baseUrl.replace(/\/$/,"")),typeof e.token=="string"&&(this.token=e.token),typeof e.anonymousPacketToken=="string"&&(this.anonymousPacketToken=e.anonymousPacketToken),typeof e.encryptRequests=="boolean"&&(this.encryptRequests=e.encryptRequests),typeof e.csrfEnabled=="boolean"&&(this.csrfEnabled=e.csrfEnabled,e.csrfEnabled||(this.csrfToken="",this.stopCsrfRefresh())),typeof e.csrfToken=="string"&&(this.csrfToken=e.csrfToken),typeof e.csrfHeaderName=="string"&&(this.csrfHeaderName=e.csrfHeaderName),typeof e.csrfRefreshPath=="string"&&(this.csrfRefreshPath=e.csrfRefreshPath),typeof e.csrfRefreshBuffer=="number"&&(this.csrfRefreshBuffer=e.csrfRefreshBuffer),typeof e.apiKey=="string"&&(this.apiKey=e.apiKey),typeof e.hmacSecret=="string"&&(this.hmacSecret=e.hmacSecret),typeof e.keepSession=="boolean"&&(this.keepSession=e.keepSession),typeof e.refreshBuffer=="number"&&(this.refreshBuffer=e.refreshBuffer),e.onTokenRefreshed&&(this.onTokenRefreshed=e.onTokenRefreshed),e.onSessionExpired&&(this.onSessionExpired=e.onSessionExpired)}setToken(e){this.token=e}setAnonymousPacketToken(e){this.anonymousPacketToken=e}setApiKey(e){this.apiKey=e}setHmacSecret(e){this.hmacSecret=e}setEncryptRequests(e){this.encryptRequests=e}setCsrfToken(e){this.csrfToken=e}setCsrfEnabled(e){this.csrfEnabled=e,e||(this.csrfToken="",this.stopCsrfRefresh())}_scheduleKeepSession(e,t,r){this._clearRefreshTimer(),this._sessionRefreshToken=e;let n=Math.max((t-this.refreshBuffer)*1e3,0);this._refreshTimer=setTimeout(async()=>{if(this._sessionRefreshToken)try{let i=await r(this._sessionRefreshToken);this.onTokenRefreshed?.(i.access_token,i.expires_in),this._scheduleKeepSession(this._sessionRefreshToken,i.expires_in,r)}catch(i){this._clearRefreshTimer(),this.onSessionExpired?.(i instanceof Error?i:new Error(String(i)))}},n)}_clearRefreshTimer(){this._refreshTimer!==null&&(clearTimeout(this._refreshTimer),this._refreshTimer=null)}stopKeepSession(){this._clearRefreshTimer(),this._sessionRefreshToken=null}_clearCsrfRefreshTimer(){this._csrfRefreshTimer!==null&&(clearTimeout(this._csrfRefreshTimer),this._csrfRefreshTimer=null)}stopCsrfRefresh(){this._clearCsrfRefreshTimer(),this._csrfRefreshPromise=null}_scheduleCsrfRefresh(e){if(this._clearCsrfRefreshTimer(),!this.csrfEnabled||!this.csrfRefreshPath)return;let t=Math.max((e-this.csrfRefreshBuffer)*1e3,0);this._csrfRefreshTimer=setTimeout(()=>{this.refreshCsrfToken().catch(()=>{this._clearCsrfRefreshTimer()})},t)}async refreshCsrfToken(){return!this.csrfEnabled||!this.csrfRefreshPath?"":(this._csrfRefreshPromise||(this._csrfRefreshPromise=(async()=>{let e=await fetch(`${this.baseUrl}${this.csrfRefreshPath}`,{method:"GET",credentials:"include"});if(!e.ok){let n=await e.text().catch(()=>""),i=new Error(n||`HTTP ${e.status}`);throw i.status=e.status,i}let t=await e.json().catch(()=>null),r=t&&typeof t=="object"&&"data"in t?t.data??null:t;if(!r?.enabled||typeof r.token!="string")throw new Error("CSRF token refresh failed");return this._applyCsrfHealth(r),this.csrfToken})().finally(()=>{this._csrfRefreshPromise=null})),this._csrfRefreshPromise)}_applyCsrfHealth(e){if(!e?.enabled){this.setCsrfEnabled(!1);return}this.csrfEnabled=!0,typeof e.token=="string"&&(this.csrfToken=e.token),typeof e.headerName=="string"&&(this.csrfHeaderName=e.headerName),typeof e.refreshPath=="string"&&(this.csrfRefreshPath=e.refreshPath),typeof e.expiresIn=="number"&&e.expiresIn>0&&this._scheduleCsrfRefresh(e.expiresIn)}readRequestBody(e,t="application/json",r=!1){let n=x(this.hmacSecret,this.token||this.anonymousPacketToken);return X(e,t,r,n)}get _reqOpts(){return{baseUrl:this.baseUrl,token:this.token,anonymousPacketToken:this.anonymousPacketToken,apiKey:this.apiKey,hmacSecret:this.hmacSecret,encryptRequests:this.encryptRequests,csrfEnabled:this.csrfEnabled,csrfToken:this.csrfToken,csrfHeaderName:this.csrfHeaderName,refreshCsrfToken:this.csrfEnabled?()=>this.refreshCsrfToken():null}}requestJson(e,t,r,n=!0,i){return I(this._reqOpts,e,t,r,n,i,!1)}requestBinary(e,t,r,n=!0){return this._requestBinary(e,t,r,n)}requestForm(e,t,r,n=!0){return this._requestForm(e,t,r,n)}requestFormBinary(e,t,r,n=!0){return this._requestFormBinary(e,t,r,n)}_request(e,t,r,n=!0,i){return I(this._reqOpts,e,t,r,n,i,!0)}async _requestBinary(e,t,r,n=!0){let i={"Content-Type":"application/json"};n&&this.token&&(i.Authorization=`Bearer ${this.token}`),this.apiKey&&(i["X-API-Key"]=this.apiKey);let o=await fetch(this.baseUrl+t,{method:e,headers:i,...r!=null?{body:JSON.stringify(r)}:{},credentials:"include"});if(!o.ok){let a=await o.text(),c=new Error(`HTTP ${o.status}: ${a}`);throw c.status=o.status,c}return o.arrayBuffer()}async _requestForm(e,t,r,n=!0){let i={};n&&this.token&&(i.Authorization=`Bearer ${this.token}`),this.apiKey&&(i["X-API-Key"]=this.apiKey);let o=await fetch(this.baseUrl+t,{method:e,headers:i,body:r,credentials:"include"}),a=await o.json();if(!a.ok){let c=new Error(a.message??`EntityServer error (HTTP ${o.status})`);throw c.status=o.status,c}return a}async _requestFormBinary(e,t,r,n=!0){let i={};n&&this.token&&(i.Authorization=`Bearer ${this.token}`),this.apiKey&&(i["X-API-Key"]=this.apiKey);let o=await fetch(this.baseUrl+t,{method:e,headers:i,body:r,credentials:"include"});if(!o.ok){let a=await o.text(),c=new Error(`HTTP ${o.status}: ${a}`);throw c.status=o.status,c}return o.arrayBuffer()}};function V(s){return class extends s{async checkHealth(){let r=await(await fetch(`${this.baseUrl}/v1/health`,{signal:AbortSignal.timeout(3e3),credentials:"include"})).json();return r.packet_encryption&&(this.encryptRequests=!0),typeof r.packet_token=="string"&&(this.anonymousPacketToken=r.packet_token),this._applyCsrfHealth(r.csrf),r}async login(t,r){let n=await this._request("POST","/v1/auth/login",{email:t,passwd:r},!1);return this.token=n.data.access_token,this.keepSession&&this._scheduleKeepSession(n.data.refresh_token,n.data.expires_in,i=>this.refreshToken(i)),n.data}async refreshToken(t){let r=await this._request("POST","/v1/auth/refresh",{refresh_token:t},!1);return this.token=r.data.access_token,this.keepSession&&this._scheduleKeepSession(t,r.data.expires_in,n=>this.refreshToken(n)),r.data}async logout(t){this.stopKeepSession();let r=await this._request("POST","/v1/auth/logout",{refresh_token:t},!1);return this.token="",r}me(){return this._request("GET","/v1/auth/me")}withdraw(t){return this._request("POST","/v1/auth/withdraw",t?{passwd:t}:{})}reactivate(t){return this._request("POST","/v1/auth/reactivate",t,!1)}}}function Z(s){return class extends s{async transStart(){let t=await this._request("POST","/v1/transaction/start",void 0,!1);return this.activeTxId=t.transaction_id,this.activeTxId}transRollback(t){let r=t??this.activeTxId;return r?(this.activeTxId=null,this._request("POST",`/v1/transaction/rollback/${r}`)):Promise.reject(new Error("No active transaction. Call transStart() first."))}transCommit(t){let r=t??this.activeTxId;return r?(this.activeTxId=null,this._request("POST",`/v1/transaction/commit/${r}`)):Promise.reject(new Error("No active transaction. Call transStart() first."))}get(t,r,n={}){let i=n.skipHooks?"?skipHooks=true":"";return this._request("GET",`/v1/entity/${t}/${r}${i}`)}find(t,r,n={}){let i=n.skipHooks?"?skipHooks=true":"";return this._request("POST",`/v1/entity/${t}/find${i}`,r??{})}list(t,r={}){let{conditions:n,fields:i,orderDir:o,orderBy:a,...c}=r,h={page:1,limit:20,...c};return a&&(h.orderBy=o==="DESC"?`-${a}`:a),i?.length&&(h.fields=i.join(",")),this._request("POST",`/v1/entity/${t}/list?${U(h)}`,n??{})}count(t,r){return this._request("POST",`/v1/entity/${t}/count`,r??{})}query(t,r){return this._request("POST",`/v1/entity/${t}/query`,r)}submit(t,r,n={}){let i=n.transactionId??this.activeTxId,o=i?{"X-Transaction-ID":i}:void 0,a=n.skipHooks?"?skipHooks=true":"";return this._request("POST",`/v1/entity/${t}/submit${a}`,r,!0,o)}delete(t,r,n={}){let i=new URLSearchParams;n.hard&&i.set("hard","true"),n.skipHooks&&i.set("skipHooks","true");let o=i.size?`?${i}`:"",a=n.transactionId??this.activeTxId,c=a?{"X-Transaction-ID":a}:void 0;return this._request("POST",`/v1/entity/${t}/delete/${r}${o}`,void 0,!0,c)}history(t,r,n={}){return this._request("GET",`/v1/entity/${t}/history/${r}?${U({page:1,limit:50,...n})}`)}rollback(t,r){return this._request("POST",`/v1/entity/${t}/rollback/${r}`)}}}function W(s){return class extends s{push(t,r,n={}){return this.submit(t,r,n)}pushLogList(t={}){return this.list("push_log",t)}registerPushDevice(t,r,n,i={}){let{platform:o,deviceType:a,browser:c,browserVersion:h,pushEnabled:l=!0,transactionId:p}=i;return this.submit("account_device",{id:r,account_seq:t,push_token:n,push_enabled:l,...o?{platform:o}:{},...a?{device_type:a}:{},...c?{browser:c}:{},...h?{browser_version:h}:{}},{transactionId:p})}updatePushDeviceToken(t,r,n={}){let{pushEnabled:i=!0,transactionId:o}=n;return this.submit("account_device",{seq:t,push_token:r,push_enabled:i},{transactionId:o})}disablePushDevice(t,r={}){return this.submit("account_device",{seq:t,push_enabled:!1},{transactionId:r.transactionId})}}}function Y(s){return class extends s{smtpSend(t){return this._request("POST","/v1/smtp/send",t)}smtpStatus(t){return this._request("POST",`/v1/smtp/status/${t}`,{})}}}function ee(s){return class extends s{async fileUpload(t,r,n={}){let i=new FormData;return i.append("file",r,r instanceof File?r.name:"upload"),n.refSeq!=null&&i.append("ref_seq",String(n.refSeq)),n.isPublic!=null&&i.append("is_public",n.isPublic?"true":"false"),this._requestForm("POST",`/v1/files/${t}/upload`,i)}fileDownload(t,r){return this._requestBinary("POST",`/v1/files/${t}/download/${r}`,{})}fileDelete(t,r){return this._request("POST",`/v1/files/${t}/delete/${r}`,{})}fileList(t,r={}){return this._request("POST",`/v1/files/${t}/list`,r.refSeq?{ref_seq:r.refSeq}:{})}fileMeta(t,r){return this._request("POST",`/v1/files/${t}/meta/${r}`,{})}fileToken(t){return this._request("POST",`/v1/files/token/${t}`,{})}fileUrl(t){return`${this.baseUrl}/v1/files/${t}`}}}function te(s){return class extends s{qrcode(t,r={}){return this._requestBinary("POST","/v1/utils/qrcode",{content:t,...r})}qrcodeBase64(t,r={}){return this._request("POST","/v1/utils/qrcode/base64",{content:t,...r})}qrcodeText(t,r={}){return this._request("POST","/v1/utils/qrcode/text",{content:t,...r})}barcode(t,r={}){return this._requestBinary("POST","/v1/utils/barcode",{content:t,...r})}pdf2png(t,r={}){let n=new FormData;n.append("file",new Blob([t],{type:"application/pdf"}),"document.pdf");let i=new URLSearchParams;r.dpi!=null&&i.set("dpi",String(r.dpi)),r.firstPage!=null&&i.set("first_page",String(r.firstPage)),r.lastPage!=null&&i.set("last_page",String(r.lastPage));let o=i.toString(),a="/v1/utils/pdf2png"+(o?`?${o}`:"");return this._requestFormBinary("POST",a,n)}}}var S=class extends te(ee(Y(W(Z(V(w)))))){};var re=new S;function ft(s={}){let{singleton:e=!0,tokenResolver:t,baseUrl:r,token:n,resumeSession:i}=s,[o,a]=ie(!1),[c,h]=ie(null),l=ne(!0);se(()=>(l.current=!0,()=>{l.current=!1}),[]);let p=ne(i);se(()=>{let f=p.current;f&&y.refreshToken(f).catch(()=>{})},[]);let y=Te(()=>{let f=e?re:new S({baseUrl:r,token:n});e&&f.configure({baseUrl:r,token:n});let u=t?.();return typeof u=="string"&&f.setToken(u),f},[e,t,r,n]),T=v(async f=>{l.current&&(a(!0),h(null));try{return await f()}catch(u){let g=u instanceof Error?u:new Error(String(u));throw l.current&&h(g),g}finally{l.current&&a(!1)}},[]),C=v((f,u,g)=>T(()=>y.submit(f,u,g)),[y,T]),P=v((f,u,g)=>T(()=>y.delete(f,u,g)),[y,T]),_=v((f,u)=>T(()=>y.query(f,u)),[y,T]),B=v(()=>{a(!1),h(null)},[]);return{client:y,isPending:o,error:c,reset:B,submit:C,del:P,query:_}}export{ft as useEntityServer};
|
|
1
|
+
import{useCallback as v,useEffect as se,useMemo as Te,useRef as ne,useState as ie}from"react";function j(s){let e=import.meta;if(e?.env?.[s]!=null)return e.env[s];let t=globalThis.process;if(t?.env?.[s]!=null)return t.env[s]}function U(s){return Object.entries(s).filter(([,e])=>e!=null).map(([e,t])=>`${encodeURIComponent(e==="orderBy"?"order_by":e)}=${encodeURIComponent(String(t))}`).join("&")}import{xchacha20poly1305 as F}from"@noble/ciphers/chacha";import{sha256 as ue}from"@noble/hashes/sha2";import{hkdf as fe}from"@noble/hashes/hkdf";var O=32,$=2,H=14,E=24,le=16,he="entity-server:hkdf:v1",de="entity-server:packet-encryption";function R(s){return s instanceof Uint8Array?s:new Uint8Array(s)}function N(s,e=de){return fe(ue,new TextEncoder().encode(s),new TextEncoder().encode(he),new TextEncoder().encode(e),O)}function L(s,e=$,t=H){let r=R(s);return r.length<O?e:e+r[O-1]%t}function D(s,e,t=$,r=H){let n=R(s),i=R(e),o=L(i,t,r),a=crypto.getRandomValues(new Uint8Array(o)),c=crypto.getRandomValues(new Uint8Array(E)),l=F(i,c).encrypt(n),p=new Uint8Array(o+E+l.length);return p.set(a,0),p.set(c,o),p.set(l,o+E),p}function G(s,e,t=$,r=H){let n=R(s),i=R(e),o=L(i,t,r);if(n.length<o+E+le)throw new Error("Encrypted packet too short");let a=n.slice(o,o+E),c=n.slice(o+E);return F(i,a).decrypt(c)}function x(s,e){return N(s||e)}function Q(s,e){return D(s,e)}function q(s,e){let t=G(s,e);return JSON.parse(new TextDecoder().decode(t))}function X(s,e,t,r){let n=e.toLowerCase().includes("application/octet-stream");if(t&&!n)throw new Error("Encrypted request required: Content-Type must be application/octet-stream");if(n){if(s==null)throw new Error("Encrypted request body is empty");if(s instanceof ArrayBuffer)return q(s,r);if(s instanceof Uint8Array){let i=s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength);return q(i,r)}throw new Error("Encrypted request body must be ArrayBuffer or Uint8Array")}return s==null||s===""?{}:typeof s=="string"?JSON.parse(s):s}import{sha256 as me}from"@noble/hashes/sha2";import{hmac as ye}from"@noble/hashes/hmac";function J(s,e,t,r,n){let i=String(Math.floor(Date.now()/1e3)),o=crypto.randomUUID(),a=new TextEncoder().encode(`${s}|${e}|${i}|${o}|`),c=new Uint8Array(a.length+t.length);c.set(a,0),c.set(t,a.length);let l=[...ye(me,new TextEncoder().encode(n),c)].map(p=>p.toString(16).padStart(2,"0")).join("");return{"X-API-Key":r,"X-Timestamp":i,"X-Nonce":o,"X-Signature":l}}function pe(s){return s.hmacSecret||s.token||s.anonymousPacketToken}function ke(s){return s!=="GET"&&s!=="HEAD"&&s!=="OPTIONS"}function ge(s,e){return s===403&&/csrf/i.test(e)?!0:/csrf/i.test(e)&&/expired|token validation failed/i.test(e)}async function z(s){if((s.headers.get("Content-Type")??"").includes("application/json")){let r=await s.json().catch(()=>null);if(r?.error)return r.error;if(r?.message)return r.message}return await s.text().catch(()=>"")||`HTTP ${s.status}`}async function I(s,e,t,r,n=!0,i={},o=!0){let{baseUrl:a,token:c,apiKey:h,hmacSecret:l,encryptRequests:p,anonymousPacketToken:y,csrfEnabled:T,csrfHeaderName:C,refreshCsrfToken:P}=s,_=n&&!!(h&&l),B=pe(s),f=T&&ke(e)&&!_,u=s.csrfToken,g="application/json",oe=!c&&!_&&!!y,b=null;if(r!=null)if(p&&!!B&&e!=="GET"&&e!=="HEAD"){let k=x(l,c||y);b=Q(new TextEncoder().encode(JSON.stringify(r)),k),g="application/octet-stream"}else b=JSON.stringify(r);let ae=d=>{let k={"Content-Type":g,...i};if(!_&&n&&c&&(k.Authorization=`Bearer ${c}`),oe&&(k["X-Packet-Token"]=y),f&&d&&(k[C]=d),_){let ce=b instanceof Uint8Array?b:typeof b=="string"?new TextEncoder().encode(b):new Uint8Array(0);Object.assign(k,J(e,t,ce,h,l))}return k};f&&!u&&P&&(u=await P());let K=d=>fetch(a+t,{method:e,headers:ae(d),...b!=null?{body:b}:{},credentials:"include"}),m=await K(u);if(!m.ok){let d=await z(m.clone());if(f&&P&&ge(m.status,d))u=await P(),m=await K(u);else{let k=new Error(d);throw k.status=m.status,k}}if(!m.ok){let d=new Error(await z(m));throw d.status=m.status,d}let M=m.headers.get("Content-Type")??"";if(M.includes("application/octet-stream")){let d=x(l,c||y);return q(await m.arrayBuffer(),d)}if(!M.includes("application/json"))return await m.text();let A=await m.json();if(o&&!A.ok){let d=new Error(A.message??`EntityServer error (HTTP ${m.status})`);throw d.status=m.status,d}return A}var w=class{baseUrl;token;anonymousPacketToken;apiKey;hmacSecret;encryptRequests;csrfEnabled;csrfToken;csrfHeaderName;csrfRefreshPath;csrfRefreshBuffer;activeTxId=null;keepSession;refreshBuffer;onTokenRefreshed;onSessionExpired;_sessionRefreshToken=null;_refreshTimer=null;_csrfRefreshTimer=null;_csrfRefreshPromise=null;constructor(e={}){let t=j("VITE_ENTITY_SERVER_URL");this.baseUrl=(e.baseUrl??t??"").replace(/\/$/,""),this.token=e.token??"",this.anonymousPacketToken=e.anonymousPacketToken??"",this.apiKey=e.apiKey??"",this.hmacSecret=e.hmacSecret??"",this.encryptRequests=e.encryptRequests??!1,this.csrfEnabled=e.csrfEnabled??!1,this.csrfToken=e.csrfToken??"",this.csrfHeaderName=e.csrfHeaderName??"x-csrf-token",this.csrfRefreshPath=e.csrfRefreshPath??"/v1/csrf-token",this.csrfRefreshBuffer=e.csrfRefreshBuffer??60,this.keepSession=e.keepSession??!1,this.refreshBuffer=e.refreshBuffer??60,this.onTokenRefreshed=e.onTokenRefreshed,this.onSessionExpired=e.onSessionExpired}configure(e){typeof e.baseUrl=="string"&&(this.baseUrl=e.baseUrl.replace(/\/$/,"")),typeof e.token=="string"&&(this.token=e.token),typeof e.anonymousPacketToken=="string"&&(this.anonymousPacketToken=e.anonymousPacketToken),typeof e.encryptRequests=="boolean"&&(this.encryptRequests=e.encryptRequests),typeof e.csrfEnabled=="boolean"&&(this.csrfEnabled=e.csrfEnabled,e.csrfEnabled||(this.csrfToken="",this.stopCsrfRefresh())),typeof e.csrfToken=="string"&&(this.csrfToken=e.csrfToken),typeof e.csrfHeaderName=="string"&&(this.csrfHeaderName=e.csrfHeaderName),typeof e.csrfRefreshPath=="string"&&(this.csrfRefreshPath=e.csrfRefreshPath),typeof e.csrfRefreshBuffer=="number"&&(this.csrfRefreshBuffer=e.csrfRefreshBuffer),typeof e.apiKey=="string"&&(this.apiKey=e.apiKey),typeof e.hmacSecret=="string"&&(this.hmacSecret=e.hmacSecret),typeof e.keepSession=="boolean"&&(this.keepSession=e.keepSession),typeof e.refreshBuffer=="number"&&(this.refreshBuffer=e.refreshBuffer),e.onTokenRefreshed&&(this.onTokenRefreshed=e.onTokenRefreshed),e.onSessionExpired&&(this.onSessionExpired=e.onSessionExpired)}setToken(e){this.token=e}setAnonymousPacketToken(e){this.anonymousPacketToken=e}setApiKey(e){this.apiKey=e}setHmacSecret(e){this.hmacSecret=e}setEncryptRequests(e){this.encryptRequests=e}setCsrfToken(e){this.csrfToken=e}setCsrfEnabled(e){this.csrfEnabled=e,e||(this.csrfToken="",this.stopCsrfRefresh())}_scheduleKeepSession(e,t,r){this._clearRefreshTimer(),this._sessionRefreshToken=e;let n=Math.max((t-this.refreshBuffer)*1e3,0);this._refreshTimer=setTimeout(async()=>{if(this._sessionRefreshToken)try{let i=await r(this._sessionRefreshToken);this.onTokenRefreshed?.(i.access_token,i.expires_in),this._scheduleKeepSession(this._sessionRefreshToken,i.expires_in,r)}catch(i){this._clearRefreshTimer(),this.onSessionExpired?.(i instanceof Error?i:new Error(String(i)))}},n)}_clearRefreshTimer(){this._refreshTimer!==null&&(clearTimeout(this._refreshTimer),this._refreshTimer=null)}stopKeepSession(){this._clearRefreshTimer(),this._sessionRefreshToken=null}_clearCsrfRefreshTimer(){this._csrfRefreshTimer!==null&&(clearTimeout(this._csrfRefreshTimer),this._csrfRefreshTimer=null)}stopCsrfRefresh(){this._clearCsrfRefreshTimer(),this._csrfRefreshPromise=null}_scheduleCsrfRefresh(e){if(this._clearCsrfRefreshTimer(),!this.csrfEnabled||!this.csrfRefreshPath)return;let t=Math.max((e-this.csrfRefreshBuffer)*1e3,0);this._csrfRefreshTimer=setTimeout(()=>{this.refreshCsrfToken().catch(()=>{this._clearCsrfRefreshTimer()})},t)}async refreshCsrfToken(){return!this.csrfEnabled||!this.csrfRefreshPath?"":(this._csrfRefreshPromise||(this._csrfRefreshPromise=(async()=>{let e=await fetch(`${this.baseUrl}${this.csrfRefreshPath}`,{method:"GET",credentials:"include"});if(!e.ok){let n=await e.text().catch(()=>""),i=new Error(n||`HTTP ${e.status}`);throw i.status=e.status,i}let t=await e.json().catch(()=>null),r=t&&typeof t=="object"&&"data"in t?t.data??null:t;if(!r?.enabled||typeof r.token!="string")throw new Error("CSRF token refresh failed");return this._applyCsrfHealth(r),this.csrfToken})().finally(()=>{this._csrfRefreshPromise=null})),this._csrfRefreshPromise)}_applyCsrfHealth(e){if(!e?.enabled){this.setCsrfEnabled(!1);return}this.csrfEnabled=!0,typeof e.token=="string"&&(this.csrfToken=e.token),typeof e.headerName=="string"&&(this.csrfHeaderName=e.headerName),typeof e.refreshPath=="string"&&(this.csrfRefreshPath=e.refreshPath),typeof e.expiresIn=="number"&&e.expiresIn>0&&this._scheduleCsrfRefresh(e.expiresIn)}readRequestBody(e,t="application/json",r=!1){let n=x(this.hmacSecret,this.token||this.anonymousPacketToken);return X(e,t,r,n)}get _reqOpts(){return{baseUrl:this.baseUrl,token:this.token,anonymousPacketToken:this.anonymousPacketToken,apiKey:this.apiKey,hmacSecret:this.hmacSecret,encryptRequests:this.encryptRequests,csrfEnabled:this.csrfEnabled,csrfToken:this.csrfToken,csrfHeaderName:this.csrfHeaderName,refreshCsrfToken:this.csrfEnabled?()=>this.refreshCsrfToken():null}}requestJson(e,t,r,n=!0,i){return I(this._reqOpts,e,t,r,n,i,!1)}requestBinary(e,t,r,n=!0){return this._requestBinary(e,t,r,n)}requestForm(e,t,r,n=!0){return this._requestForm(e,t,r,n)}requestFormBinary(e,t,r,n=!0){return this._requestFormBinary(e,t,r,n)}_request(e,t,r,n=!0,i){return I(this._reqOpts,e,t,r,n,i,!0)}async _requestBinary(e,t,r,n=!0){let i={"Content-Type":"application/json"};n&&this.token&&(i.Authorization=`Bearer ${this.token}`),this.apiKey&&(i["X-API-Key"]=this.apiKey);let o=await fetch(this.baseUrl+t,{method:e,headers:i,...r!=null?{body:JSON.stringify(r)}:{},credentials:"include"});if(!o.ok){let a=await o.text(),c=new Error(`HTTP ${o.status}: ${a}`);throw c.status=o.status,c}return o.arrayBuffer()}async _requestForm(e,t,r,n=!0){let i={};n&&this.token&&(i.Authorization=`Bearer ${this.token}`),this.apiKey&&(i["X-API-Key"]=this.apiKey);let o=await fetch(this.baseUrl+t,{method:e,headers:i,body:r,credentials:"include"}),a=await o.json();if(!a.ok){let c=new Error(a.message??`EntityServer error (HTTP ${o.status})`);throw c.status=o.status,c}return a}async _requestFormBinary(e,t,r,n=!0){let i={};n&&this.token&&(i.Authorization=`Bearer ${this.token}`),this.apiKey&&(i["X-API-Key"]=this.apiKey);let o=await fetch(this.baseUrl+t,{method:e,headers:i,body:r,credentials:"include"});if(!o.ok){let a=await o.text(),c=new Error(`HTTP ${o.status}: ${a}`);throw c.status=o.status,c}return o.arrayBuffer()}};function V(s){return class extends s{async checkHealth(){let r=await(await fetch(`${this.baseUrl}/v1/health`,{signal:AbortSignal.timeout(3e3),credentials:"include"})).json();return r.packet_encryption&&(this.encryptRequests=!0),typeof r.packet_token=="string"&&(this.anonymousPacketToken=r.packet_token),this._applyCsrfHealth(r.csrf),r}async login(t,r){let n=await this._request("POST","/v1/auth/login",{email:t,passwd:r},!1);return this.token=n.data.access_token,this.keepSession&&this._scheduleKeepSession(n.data.refresh_token,n.data.expires_in,i=>this.refreshToken(i)),n.data}async refreshToken(t){let r=await this._request("POST","/v1/auth/refresh",{refresh_token:t},!1);return this.token=r.data.access_token,this.keepSession&&this._scheduleKeepSession(t,r.data.expires_in,n=>this.refreshToken(n)),r.data}async logout(t){this.stopKeepSession();let r=await this._request("POST","/v1/auth/logout",{refresh_token:t},!1);return this.token="",r}me(){return this._request("GET","/v1/auth/me")}withdraw(t){return this._request("POST","/v1/auth/withdraw",t?{passwd:t}:{})}reactivate(t){return this._request("POST","/v1/auth/reactivate",t,!1)}}}function Z(s){return class extends s{async transStart(){let t=await this._request("POST","/v1/transaction/start",void 0,!1);return this.activeTxId=t.transaction_id,this.activeTxId}transRollback(t){let r=t??this.activeTxId;return r?(this.activeTxId=null,this._request("POST",`/v1/transaction/rollback/${r}`)):Promise.reject(new Error("No active transaction. Call transStart() first."))}transCommit(t){let r=t??this.activeTxId;return r?(this.activeTxId=null,this._request("POST",`/v1/transaction/commit/${r}`)):Promise.reject(new Error("No active transaction. Call transStart() first."))}get(t,r,n={}){let i=n.skipHooks?"?skipHooks=true":"";return this._request("GET",`/v1/entity/${t}/${r}${i}`)}find(t,r,n={}){let i=n.skipHooks?"?skipHooks=true":"";return this._request("POST",`/v1/entity/${t}/find${i}`,r??{})}list(t,r={}){let{conditions:n,fields:i,orderDir:o,orderBy:a,...c}=r,h={page:1,limit:20,...c};return a&&(h.orderBy=o==="DESC"?`-${a}`:a),i?.length&&(h.fields=i.join(",")),this._request("POST",`/v1/entity/${t}/list?${U(h)}`,n??{})}count(t,r){return this._request("POST",`/v1/entity/${t}/count`,r??{})}query(t,r){return this._request("POST",`/v1/entity/${t}/query`,r)}submit(t,r,n={}){let i=n.transactionId??this.activeTxId,o=i?{"X-Transaction-ID":i}:void 0,a=n.skipHooks?"?skipHooks=true":"";return this._request("POST",`/v1/entity/${t}/submit${a}`,r,!0,o)}delete(t,r,n={}){let i=new URLSearchParams;n.hard&&i.set("hard","true"),n.skipHooks&&i.set("skipHooks","true");let o=i.size?`?${i}`:"",a=n.transactionId??this.activeTxId,c=a?{"X-Transaction-ID":a}:void 0;return this._request("POST",`/v1/entity/${t}/delete/${r}${o}`,void 0,!0,c)}history(t,r,n={}){return this._request("GET",`/v1/entity/${t}/history/${r}?${U({page:1,limit:50,...n})}`)}rollback(t,r){return this._request("POST",`/v1/entity/${t}/rollback/${r}`)}}}function W(s){return class extends s{push(t,r,n={}){return this.submit(t,r,n)}pushLogList(t={}){return this.list("push_log",t)}registerPushDevice(t,r,n,i={}){let{platform:o,deviceType:a,browser:c,browserVersion:h,pushEnabled:l=!0,transactionId:p}=i;return this.submit("account_device",{id:r,account_seq:t,push_token:n,push_enabled:l,...o?{platform:o}:{},...a?{device_type:a}:{},...c?{browser:c}:{},...h?{browser_version:h}:{}},{transactionId:p})}updatePushDeviceToken(t,r,n={}){let{pushEnabled:i=!0,transactionId:o}=n;return this.submit("account_device",{seq:t,push_token:r,push_enabled:i},{transactionId:o})}disablePushDevice(t,r={}){return this.submit("account_device",{seq:t,push_enabled:!1},{transactionId:r.transactionId})}}}function Y(s){return class extends s{smtpSend(t){return this._request("POST","/v1/smtp/send",t)}smtpStatus(t){return this._request("POST",`/v1/smtp/status/${t}`,{})}}}function ee(s){return class extends s{async fileUpload(t,r,n={}){let i=new FormData;return i.append("file",r,r instanceof File?r.name:"upload"),n.refSeq!=null&&i.append("ref_seq",String(n.refSeq)),n.isPublic!=null&&i.append("is_public",n.isPublic?"true":"false"),this._requestForm("POST",`/v1/files/${t}/upload`,i)}fileDownload(t,r){return this._requestBinary("POST",`/v1/files/${t}/download/${r}`,{})}fileDelete(t,r){return this._request("POST",`/v1/files/${t}/delete/${r}`,{})}fileList(t,r={}){return this._request("POST",`/v1/files/${t}/list`,r.refSeq?{ref_seq:r.refSeq}:{})}fileMeta(t,r){return this._request("POST",`/v1/files/${t}/meta/${r}`,{})}fileToken(t){return this._request("POST",`/v1/files/token/${t}`,{})}fileUrl(t){return`${this.baseUrl}/v1/files/${t}`}}}function te(s){return class extends s{qrcode(t,r={}){return this._requestBinary("POST","/v1/utils/qrcode",{content:t,...r})}qrcodeBase64(t,r={}){return this._request("POST","/v1/utils/qrcode/base64",{content:t,...r})}qrcodeText(t,r={}){return this._request("POST","/v1/utils/qrcode/text",{content:t,...r})}barcode(t,r={}){return this._requestBinary("POST","/v1/utils/barcode",{content:t,...r})}pdf2png(t,r={}){let n=new FormData;n.append("file",new Blob([t],{type:"application/pdf"}),"document.pdf");let i=new URLSearchParams;r.dpi!=null&&i.set("dpi",String(r.dpi)),r.firstPage!=null&&i.set("first_page",String(r.firstPage)),r.lastPage!=null&&i.set("last_page",String(r.lastPage));let o=i.toString(),a="/v1/utils/pdf2png"+(o?`?${o}`:"");return this._requestFormBinary("POST",a,n)}}}var S=class extends te(ee(Y(W(Z(V(w)))))){};var re=new S;function ft(s={}){let{singleton:e=!0,tokenResolver:t,baseUrl:r,token:n,resumeSession:i}=s,[o,a]=ie(!1),[c,h]=ie(null),l=ne(!0);se(()=>(l.current=!0,()=>{l.current=!1}),[]);let p=ne(i);se(()=>{let f=p.current;f&&y.refreshToken(f).catch(()=>{})},[]);let y=Te(()=>{let f=e?re:new S({baseUrl:r,token:n});e&&f.configure({baseUrl:r,token:n});let u=t?.();return typeof u=="string"&&f.setToken(u),f},[e,t,r,n]),T=v(async f=>{l.current&&(a(!0),h(null));try{return await f()}catch(u){let g=u instanceof Error?u:new Error(String(u));throw l.current&&h(g),g}finally{l.current&&a(!1)}},[]),C=v((f,u,g)=>T(()=>y.submit(f,u,g)),[y,T]),P=v((f,u,g)=>T(()=>y.delete(f,u,g)),[y,T]),_=v((f,u)=>T(()=>y.query(f,u)),[y,T]),B=v(()=>{a(!1),h(null)},[]);return{client:y,isPending:o,error:c,reset:B,submit:C,del:P,query:_}}export{ft as useEntityServer};
|
|
2
2
|
//# sourceMappingURL=react.js.map
|