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.
@@ -11,21 +11,21 @@
11
11
  * src/mixins/file.ts — 파일 스토리지
12
12
  * src/mixins/utils.ts — QR코드/바코드/PDF변환
13
13
  */
14
- import { EntityServerClientBase } from "./client/base";
14
+ import { EntityServerClientBase } from "./client/base.js";
15
15
  declare const EntityServerClient_base: {
16
16
  new (...args: any[]): {
17
- qrcode(content: string, opts?: import("./types").QRCodeOptions): Promise<ArrayBuffer>;
18
- qrcodeBase64(content: string, opts?: import("./types").QRCodeOptions): Promise<{
17
+ qrcode(content: string, opts?: import("./types.js").QRCodeOptions): Promise<ArrayBuffer>;
18
+ qrcodeBase64(content: string, opts?: import("./types.js").QRCodeOptions): Promise<{
19
19
  ok: boolean;
20
20
  data: string;
21
21
  data_uri: string;
22
22
  }>;
23
- qrcodeText(content: string, opts?: import("./types").QRCodeOptions): Promise<{
23
+ qrcodeText(content: string, opts?: import("./types.js").QRCodeOptions): Promise<{
24
24
  ok: boolean;
25
25
  text: string;
26
26
  }>;
27
- barcode(content: string, opts?: import("./types").BarcodeOptions): Promise<ArrayBuffer>;
28
- pdf2png(pdfData: ArrayBuffer | Uint8Array<ArrayBuffer>, opts?: import("./types").Pdf2PngOptions): Promise<ArrayBuffer>;
27
+ barcode(content: string, opts?: import("./types.js").BarcodeOptions): Promise<ArrayBuffer>;
28
+ pdf2png(pdfData: ArrayBuffer | Uint8Array<ArrayBuffer>, opts?: import("./types.js").Pdf2PngOptions): Promise<ArrayBuffer>;
29
29
  baseUrl: string;
30
30
  token: string;
31
31
  anonymousPacketToken: string;
@@ -46,7 +46,7 @@ declare const EntityServerClient_base: {
46
46
  _refreshTimer: ReturnType<typeof setTimeout> | null;
47
47
  _csrfRefreshTimer: ReturnType<typeof setTimeout> | null;
48
48
  _csrfRefreshPromise: Promise<string> | null;
49
- configure(options: Partial<import("./types").EntityServerClientOptions>): void;
49
+ configure(options: Partial<import("./types.js").EntityServerClientOptions>): void;
50
50
  setToken(token: string): void;
51
51
  setAnonymousPacketToken(token: string): void;
52
52
  setApiKey(apiKey: string): void;
@@ -64,9 +64,9 @@ declare const EntityServerClient_base: {
64
64
  stopCsrfRefresh(): void;
65
65
  _scheduleCsrfRefresh(expiresIn: number): void;
66
66
  refreshCsrfToken(): Promise<string>;
67
- _applyCsrfHealth(csrf?: import("./types").EntityServerClientHealthCsrf | null): void;
67
+ _applyCsrfHealth(csrf?: import("./types.js").EntityServerClientHealthCsrf | null): void;
68
68
  readRequestBody<T = Record<string, unknown>>(body: ArrayBuffer | Uint8Array | string | T | null | undefined, contentType?: string, requireEncrypted?: boolean): T;
69
- get _reqOpts(): import("./client/request").RequestOptions;
69
+ get _reqOpts(): import("./client/request.js").RequestOptions;
70
70
  requestJson<T>(method: string, path: string, body?: unknown, withAuth?: boolean, extraHeaders?: Record<string, string>): Promise<T>;
71
71
  requestBinary(method: string, path: string, body?: unknown, withAuth?: boolean): Promise<ArrayBuffer>;
72
72
  requestForm<T>(method: string, path: string, form: FormData, withAuth?: boolean): Promise<T>;
@@ -78,10 +78,10 @@ declare const EntityServerClient_base: {
78
78
  };
79
79
  } & {
80
80
  new (...args: any[]): {
81
- fileUpload(entity: string, file: File | Blob, opts?: import("./types").FileUploadOptions): Promise<{
81
+ fileUpload(entity: string, file: File | Blob, opts?: import("./types.js").FileUploadOptions): Promise<{
82
82
  ok: boolean;
83
83
  uuid: string;
84
- data: import("./types").FileMeta;
84
+ data: import("./types.js").FileMeta;
85
85
  }>;
86
86
  fileDownload(entity: string, uuid: string): Promise<ArrayBuffer>;
87
87
  fileDelete(entity: string, uuid: string): Promise<{
@@ -94,13 +94,13 @@ declare const EntityServerClient_base: {
94
94
  }): Promise<{
95
95
  ok: boolean;
96
96
  data: {
97
- items: import("./types").FileMeta[];
97
+ items: import("./types.js").FileMeta[];
98
98
  total: number;
99
99
  };
100
100
  }>;
101
101
  fileMeta(entity: string, uuid: string): Promise<{
102
102
  ok: boolean;
103
- data: import("./types").FileMeta;
103
+ data: import("./types.js").FileMeta;
104
104
  }>;
105
105
  fileToken(uuid: string): Promise<{
106
106
  ok: boolean;
@@ -127,7 +127,7 @@ declare const EntityServerClient_base: {
127
127
  _refreshTimer: ReturnType<typeof setTimeout> | null;
128
128
  _csrfRefreshTimer: ReturnType<typeof setTimeout> | null;
129
129
  _csrfRefreshPromise: Promise<string> | null;
130
- configure(options: Partial<import("./types").EntityServerClientOptions>): void;
130
+ configure(options: Partial<import("./types.js").EntityServerClientOptions>): void;
131
131
  setToken(token: string): void;
132
132
  setAnonymousPacketToken(token: string): void;
133
133
  setApiKey(apiKey: string): void;
@@ -145,9 +145,9 @@ declare const EntityServerClient_base: {
145
145
  stopCsrfRefresh(): void;
146
146
  _scheduleCsrfRefresh(expiresIn: number): void;
147
147
  refreshCsrfToken(): Promise<string>;
148
- _applyCsrfHealth(csrf?: import("./types").EntityServerClientHealthCsrf | null): void;
148
+ _applyCsrfHealth(csrf?: import("./types.js").EntityServerClientHealthCsrf | null): void;
149
149
  readRequestBody<T = Record<string, unknown>>(body: ArrayBuffer | Uint8Array | string | T | null | undefined, contentType?: string, requireEncrypted?: boolean): T;
150
- get _reqOpts(): import("./client/request").RequestOptions;
150
+ get _reqOpts(): import("./client/request.js").RequestOptions;
151
151
  requestJson<T>(method: string, path: string, body?: unknown, withAuth?: boolean, extraHeaders?: Record<string, string>): Promise<T>;
152
152
  requestBinary(method: string, path: string, body?: unknown, withAuth?: boolean): Promise<ArrayBuffer>;
153
153
  requestForm<T>(method: string, path: string, form: FormData, withAuth?: boolean): Promise<T>;
@@ -159,7 +159,7 @@ declare const EntityServerClient_base: {
159
159
  };
160
160
  } & {
161
161
  new (...args: any[]): {
162
- smtpSend(req: import("./types").SmtpSendRequest): Promise<{
162
+ smtpSend(req: import("./types.js").SmtpSendRequest): Promise<{
163
163
  ok: boolean;
164
164
  seq: number;
165
165
  }>;
@@ -187,7 +187,7 @@ declare const EntityServerClient_base: {
187
187
  _refreshTimer: ReturnType<typeof setTimeout> | null;
188
188
  _csrfRefreshTimer: ReturnType<typeof setTimeout> | null;
189
189
  _csrfRefreshPromise: Promise<string> | null;
190
- configure(options: Partial<import("./types").EntityServerClientOptions>): void;
190
+ configure(options: Partial<import("./types.js").EntityServerClientOptions>): void;
191
191
  setToken(token: string): void;
192
192
  setAnonymousPacketToken(token: string): void;
193
193
  setApiKey(apiKey: string): void;
@@ -205,9 +205,9 @@ declare const EntityServerClient_base: {
205
205
  stopCsrfRefresh(): void;
206
206
  _scheduleCsrfRefresh(expiresIn: number): void;
207
207
  refreshCsrfToken(): Promise<string>;
208
- _applyCsrfHealth(csrf?: import("./types").EntityServerClientHealthCsrf | null): void;
208
+ _applyCsrfHealth(csrf?: import("./types.js").EntityServerClientHealthCsrf | null): void;
209
209
  readRequestBody<T = Record<string, unknown>>(body: ArrayBuffer | Uint8Array | string | T | null | undefined, contentType?: string, requireEncrypted?: boolean): T;
210
- get _reqOpts(): import("./client/request").RequestOptions;
210
+ get _reqOpts(): import("./client/request.js").RequestOptions;
211
211
  requestJson<T>(method: string, path: string, body?: unknown, withAuth?: boolean, extraHeaders?: Record<string, string>): Promise<T>;
212
212
  requestBinary(method: string, path: string, body?: unknown, withAuth?: boolean): Promise<ArrayBuffer>;
213
213
  requestForm<T>(method: string, path: string, form: FormData, withAuth?: boolean): Promise<T>;
@@ -225,11 +225,11 @@ declare const EntityServerClient_base: {
225
225
  ok: boolean;
226
226
  seq: number;
227
227
  }>;
228
- pushLogList<T = unknown>(params?: import("./types").EntityListParams): Promise<{
228
+ pushLogList<T = unknown>(params?: import("./types.js").EntityListParams): Promise<{
229
229
  ok: boolean;
230
- data: import("./types").EntityListResult<T>;
230
+ data: import("./types.js").EntityListResult<T>;
231
231
  }>;
232
- registerPushDevice(accountSeq: number, deviceId: string, pushToken: string, opts?: import("./types").RegisterPushDeviceOptions): Promise<{
232
+ registerPushDevice(accountSeq: number, deviceId: string, pushToken: string, opts?: import("./types.js").RegisterPushDeviceOptions): Promise<{
233
233
  ok: boolean;
234
234
  seq: number;
235
235
  }>;
@@ -266,7 +266,7 @@ declare const EntityServerClient_base: {
266
266
  _refreshTimer: ReturnType<typeof setTimeout> | null;
267
267
  _csrfRefreshTimer: ReturnType<typeof setTimeout> | null;
268
268
  _csrfRefreshPromise: Promise<string> | null;
269
- configure(options: Partial<import("./types").EntityServerClientOptions>): void;
269
+ configure(options: Partial<import("./types.js").EntityServerClientOptions>): void;
270
270
  setToken(token: string): void;
271
271
  setAnonymousPacketToken(token: string): void;
272
272
  setApiKey(apiKey: string): void;
@@ -284,9 +284,9 @@ declare const EntityServerClient_base: {
284
284
  stopCsrfRefresh(): void;
285
285
  _scheduleCsrfRefresh(expiresIn: number): void;
286
286
  refreshCsrfToken(): Promise<string>;
287
- _applyCsrfHealth(csrf?: import("./types").EntityServerClientHealthCsrf | null): void;
287
+ _applyCsrfHealth(csrf?: import("./types.js").EntityServerClientHealthCsrf | null): void;
288
288
  readRequestBody<T = Record<string, unknown>>(body: ArrayBuffer | Uint8Array | string | T | null | undefined, contentType?: string, requireEncrypted?: boolean): T;
289
- get _reqOpts(): import("./client/request").RequestOptions;
289
+ get _reqOpts(): import("./client/request.js").RequestOptions;
290
290
  requestJson<T>(method: string, path: string, body?: unknown, withAuth?: boolean, extraHeaders?: Record<string, string>): Promise<T>;
291
291
  requestBinary(method: string, path: string, body?: unknown, withAuth?: boolean): Promise<ArrayBuffer>;
292
292
  requestForm<T>(method: string, path: string, form: FormData, withAuth?: boolean): Promise<T>;
@@ -302,9 +302,9 @@ declare const EntityServerClient_base: {
302
302
  ok: boolean;
303
303
  seq: number;
304
304
  }>;
305
- list<T = unknown>(entity: string, params?: import("./types").EntityListParams): Promise<{
305
+ list<T = unknown>(entity: string, params?: import("./types.js").EntityListParams): Promise<{
306
306
  ok: boolean;
307
- data: import("./types").EntityListResult<T>;
307
+ data: import("./types.js").EntityListResult<T>;
308
308
  }>;
309
309
  };
310
310
  } & {
@@ -333,15 +333,15 @@ declare const EntityServerClient_base: {
333
333
  ok: boolean;
334
334
  data: T;
335
335
  }>;
336
- list<T = unknown>(entity: string, params?: import("./types").EntityListParams): Promise<{
336
+ list<T = unknown>(entity: string, params?: import("./types.js").EntityListParams): Promise<{
337
337
  ok: boolean;
338
- data: import("./types").EntityListResult<T>;
338
+ data: import("./types.js").EntityListResult<T>;
339
339
  }>;
340
340
  count(entity: string, conditions?: Record<string, unknown>): Promise<{
341
341
  ok: boolean;
342
342
  count: number;
343
343
  }>;
344
- query<T = unknown>(entity: string, req: import("./types").EntityQueryRequest): Promise<{
344
+ query<T = unknown>(entity: string, req: import("./types.js").EntityQueryRequest): Promise<{
345
345
  ok: boolean;
346
346
  data: {
347
347
  items: T[];
@@ -363,9 +363,9 @@ declare const EntityServerClient_base: {
363
363
  ok: boolean;
364
364
  deleted: number;
365
365
  }>;
366
- history<T = unknown>(entity: string, seq: number, params?: Pick<import("./types").EntityListParams, "page" | "limit">): Promise<{
366
+ history<T = unknown>(entity: string, seq: number, params?: Pick<import("./types.js").EntityListParams, "page" | "limit">): Promise<{
367
367
  ok: boolean;
368
- data: import("./types").EntityListResult<import("./types").EntityHistoryRecord<T>>;
368
+ data: import("./types.js").EntityListResult<import("./types.js").EntityHistoryRecord<T>>;
369
369
  }>;
370
370
  rollback(entity: string, historySeq: number): Promise<{
371
371
  ok: boolean;
@@ -390,7 +390,7 @@ declare const EntityServerClient_base: {
390
390
  _refreshTimer: ReturnType<typeof setTimeout> | null;
391
391
  _csrfRefreshTimer: ReturnType<typeof setTimeout> | null;
392
392
  _csrfRefreshPromise: Promise<string> | null;
393
- configure(options: Partial<import("./types").EntityServerClientOptions>): void;
393
+ configure(options: Partial<import("./types.js").EntityServerClientOptions>): void;
394
394
  setToken(token: string): void;
395
395
  setAnonymousPacketToken(token: string): void;
396
396
  setApiKey(apiKey: string): void;
@@ -408,9 +408,9 @@ declare const EntityServerClient_base: {
408
408
  stopCsrfRefresh(): void;
409
409
  _scheduleCsrfRefresh(expiresIn: number): void;
410
410
  refreshCsrfToken(): Promise<string>;
411
- _applyCsrfHealth(csrf?: import("./types").EntityServerClientHealthCsrf | null): void;
411
+ _applyCsrfHealth(csrf?: import("./types.js").EntityServerClientHealthCsrf | null): void;
412
412
  readRequestBody<T = Record<string, unknown>>(body: ArrayBuffer | Uint8Array | string | T | null | undefined, contentType?: string, requireEncrypted?: boolean): T;
413
- get _reqOpts(): import("./client/request").RequestOptions;
413
+ get _reqOpts(): import("./client/request.js").RequestOptions;
414
414
  requestJson<T>(method: string, path: string, body?: unknown, withAuth?: boolean, extraHeaders?: Record<string, string>): Promise<T>;
415
415
  requestBinary(method: string, path: string, body?: unknown, withAuth?: boolean): Promise<ArrayBuffer>;
416
416
  requestForm<T>(method: string, path: string, form: FormData, withAuth?: boolean): Promise<T>;
@@ -427,7 +427,7 @@ declare const EntityServerClient_base: {
427
427
  packet_encryption?: boolean;
428
428
  packet_mode?: string;
429
429
  packet_token?: string;
430
- csrf?: import("./types").EntityServerClientHealthCsrf;
430
+ csrf?: import("./types.js").EntityServerClientHealthCsrf;
431
431
  }>;
432
432
  login(email: string, password: string): Promise<{
433
433
  access_token: string;
@@ -481,7 +481,7 @@ declare const EntityServerClient_base: {
481
481
  _refreshTimer: ReturnType<typeof setTimeout> | null;
482
482
  _csrfRefreshTimer: ReturnType<typeof setTimeout> | null;
483
483
  _csrfRefreshPromise: Promise<string> | null;
484
- configure(options: Partial<import("./types").EntityServerClientOptions>): void;
484
+ configure(options: Partial<import("./types.js").EntityServerClientOptions>): void;
485
485
  setToken(token: string): void;
486
486
  setAnonymousPacketToken(token: string): void;
487
487
  setApiKey(apiKey: string): void;
@@ -499,9 +499,9 @@ declare const EntityServerClient_base: {
499
499
  stopCsrfRefresh(): void;
500
500
  _scheduleCsrfRefresh(expiresIn: number): void;
501
501
  refreshCsrfToken(): Promise<string>;
502
- _applyCsrfHealth(csrf?: import("./types").EntityServerClientHealthCsrf | null): void;
502
+ _applyCsrfHealth(csrf?: import("./types.js").EntityServerClientHealthCsrf | null): void;
503
503
  readRequestBody<T = Record<string, unknown>>(body: ArrayBuffer | Uint8Array | string | T | null | undefined, contentType?: string, requireEncrypted?: boolean): T;
504
- get _reqOpts(): import("./client/request").RequestOptions;
504
+ get _reqOpts(): import("./client/request.js").RequestOptions;
505
505
  requestJson<T>(method: string, path: string, body?: unknown, withAuth?: boolean, extraHeaders?: Record<string, string>): Promise<T>;
506
506
  requestBinary(method: string, path: string, body?: unknown, withAuth?: boolean): Promise<ArrayBuffer>;
507
507
  requestForm<T>(method: string, path: string, form: FormData, withAuth?: boolean): Promise<T>;
@@ -1,5 +1,5 @@
1
- import type { EntityServerClientHealthCsrf, EntityServerClientOptions } from "../types";
2
- import { type RequestOptions } from "./request";
1
+ import type { EntityServerClientHealthCsrf, EntityServerClientOptions } from "../types.js";
2
+ import { type RequestOptions } from "./request.js";
3
3
  export type GConstructor<T = object> = new (...args: any[]) => T;
4
4
  export declare class EntityServerClientBase {
5
5
  baseUrl: string;
@@ -1,4 +1,4 @@
1
- import { EntityServerClient, type EntityQueryRequest, type EntityServerClientOptions } from "../index";
1
+ import { EntityServerClient, type EntityQueryRequest, type EntityServerClientOptions } from "../index.js";
2
2
  export interface UseEntityServerOptions extends EntityServerClientOptions {
3
3
  singleton?: boolean;
4
4
  tokenResolver?: () => string | undefined | null;
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export * from "./types";
2
- export * from "./EntityServerClient";
3
- import { EntityServerClient } from "./EntityServerClient";
1
+ export * from "./types.js";
2
+ export * from "./EntityServerClient.js";
3
+ import { EntityServerClient } from "./EntityServerClient.js";
4
4
  export declare const entityServer: EntityServerClient;
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- function H(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 w(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 I}from"@noble/ciphers/chacha";import{sha256 as ne}from"@noble/hashes/sha2";import{hkdf as ie}from"@noble/hashes/hkdf";var q=32,C=2,B=14,y=24,oe=16,ae="entity-server:hkdf:v1",ce="entity-server:packet-encryption";function g(s){return s instanceof Uint8Array?s:new Uint8Array(s)}function K(s,e=ce){return ie(ne,new TextEncoder().encode(s),new TextEncoder().encode(ae),new TextEncoder().encode(e),q)}function M(s,e=C,t=B){let r=g(s);return r.length<q?e:e+r[q-1]%t}function F(s,e,t=C,r=B){let n=g(s),i=g(e),o=M(i,t,r),a=crypto.getRandomValues(new Uint8Array(o)),c=crypto.getRandomValues(new Uint8Array(y)),h=I(i,c).encrypt(n),d=new Uint8Array(o+y+h.length);return d.set(a,0),d.set(c,o),d.set(h,o+y),d}function N(s,e,t=C,r=B){let n=g(s),i=g(e),o=M(i,t,r);if(n.length<o+y+oe)throw new Error("Encrypted packet too short");let a=n.slice(o,o+y),c=n.slice(o+y);return I(i,a).decrypt(c)}function T(s,e){return K(s||e)}function L(s,e){return F(s,e)}function S(s,e){let t=N(s,e);return JSON.parse(new TextDecoder().decode(t))}function D(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 S(s,r);if(s instanceof Uint8Array){let i=s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength);return S(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 ue}from"@noble/hashes/sha2";import{hmac as fe}from"@noble/hashes/hmac";function G(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 h=[...fe(ue,new TextEncoder().encode(n),c)].map(d=>d.toString(16).padStart(2,"0")).join("");return{"X-API-Key":r,"X-Timestamp":i,"X-Nonce":o,"X-Signature":h}}function le(s){return s.hmacSecret||s.token||s.anonymousPacketToken}function he(s){return s!=="GET"&&s!=="HEAD"&&s!=="OPTIONS"}function de(s,e){return s===403&&/csrf/i.test(e)?!0:/csrf/i.test(e)&&/expired|token validation failed/i.test(e)}async function j(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 A(s,e,t,r,n=!0,i={},o=!0){let{baseUrl:a,token:c,apiKey:l,hmacSecret:h,encryptRequests:d,anonymousPacketToken:b,csrfEnabled:W,csrfHeaderName:Y,refreshCsrfToken:P}=s,_=n&&!!(l&&h),ee=le(s),R=W&&he(e)&&!_,k=s.csrfToken,O="application/json",te=!c&&!_&&!!b,m=null;if(r!=null)if(d&&!!ee&&e!=="GET"&&e!=="HEAD"){let p=T(h,c||b);m=L(new TextEncoder().encode(JSON.stringify(r)),p),O="application/octet-stream"}else m=JSON.stringify(r);let re=u=>{let p={"Content-Type":O,...i};if(!_&&n&&c&&(p.Authorization=`Bearer ${c}`),te&&(p["X-Packet-Token"]=b),R&&u&&(p[Y]=u),_){let se=m instanceof Uint8Array?m:typeof m=="string"?new TextEncoder().encode(m):new Uint8Array(0);Object.assign(p,G(e,t,se,l,h))}return p};R&&!k&&P&&(k=await P());let U=u=>fetch(a+t,{method:e,headers:re(u),...m!=null?{body:m}:{},credentials:"include"}),f=await U(k);if(!f.ok){let u=await j(f.clone());if(R&&P&&de(f.status,u))k=await P(),f=await U(k);else{let p=new Error(u);throw p.status=f.status,p}}if(!f.ok){let u=new Error(await j(f));throw u.status=f.status,u}let $=f.headers.get("Content-Type")??"";if($.includes("application/octet-stream")){let u=T(h,c||b);return S(await f.arrayBuffer(),u)}if(!$.includes("application/json"))return await f.text();let v=await f.json();if(o&&!v.ok){let u=new Error(v.message??`EntityServer error (HTTP ${f.status})`);throw u.status=f.status,u}return v}var x=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=H("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=T(this.hmacSecret,this.token||this.anonymousPacketToken);return D(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 A(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 A(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 X(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 Q(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,l={page:1,limit:20,...c};return a&&(l.orderBy=o==="DESC"?`-${a}`:a),i?.length&&(l.fields=i.join(",")),this._request("POST",`/v1/entity/${t}/list?${w(l)}`,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}?${w({page:1,limit:50,...n})}`)}rollback(t,r){return this._request("POST",`/v1/entity/${t}/rollback/${r}`)}}}function J(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:l,pushEnabled:h=!0,transactionId:d}=i;return this.submit("account_device",{id:r,account_seq:t,push_token:n,push_enabled:h,...o?{platform:o}:{},...a?{device_type:a}:{},...c?{browser:c}:{},...l?{browser_version:l}:{}},{transactionId:d})}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 z(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 V(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 Z(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 E=class extends Z(V(z(J(Q(X(x)))))){};var Ye=new E;export{E as EntityServerClient,Ye as entityServer};
1
+ function H(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 w(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 I}from"@noble/ciphers/chacha";import{sha256 as ne}from"@noble/hashes/sha2";import{hkdf as ie}from"@noble/hashes/hkdf";var q=32,C=2,B=14,y=24,oe=16,ae="entity-server:hkdf:v1",ce="entity-server:packet-encryption";function g(s){return s instanceof Uint8Array?s:new Uint8Array(s)}function K(s,e=ce){return ie(ne,new TextEncoder().encode(s),new TextEncoder().encode(ae),new TextEncoder().encode(e),q)}function M(s,e=C,t=B){let r=g(s);return r.length<q?e:e+r[q-1]%t}function j(s,e,t=C,r=B){let n=g(s),i=g(e),o=M(i,t,r),a=crypto.getRandomValues(new Uint8Array(o)),c=crypto.getRandomValues(new Uint8Array(y)),h=I(i,c).encrypt(n),d=new Uint8Array(o+y+h.length);return d.set(a,0),d.set(c,o),d.set(h,o+y),d}function F(s,e,t=C,r=B){let n=g(s),i=g(e),o=M(i,t,r);if(n.length<o+y+oe)throw new Error("Encrypted packet too short");let a=n.slice(o,o+y),c=n.slice(o+y);return I(i,a).decrypt(c)}function T(s,e){return K(s||e)}function N(s,e){return j(s,e)}function S(s,e){let t=F(s,e);return JSON.parse(new TextDecoder().decode(t))}function L(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 S(s,r);if(s instanceof Uint8Array){let i=s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength);return S(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 ue}from"@noble/hashes/sha2";import{hmac as fe}from"@noble/hashes/hmac";function D(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 h=[...fe(ue,new TextEncoder().encode(n),c)].map(d=>d.toString(16).padStart(2,"0")).join("");return{"X-API-Key":r,"X-Timestamp":i,"X-Nonce":o,"X-Signature":h}}function le(s){return s.hmacSecret||s.token||s.anonymousPacketToken}function he(s){return s!=="GET"&&s!=="HEAD"&&s!=="OPTIONS"}function de(s,e){return s===403&&/csrf/i.test(e)?!0:/csrf/i.test(e)&&/expired|token validation failed/i.test(e)}async function G(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 A(s,e,t,r,n=!0,i={},o=!0){let{baseUrl:a,token:c,apiKey:l,hmacSecret:h,encryptRequests:d,anonymousPacketToken:b,csrfEnabled:W,csrfHeaderName:Y,refreshCsrfToken:P}=s,_=n&&!!(l&&h),ee=le(s),R=W&&he(e)&&!_,k=s.csrfToken,O="application/json",te=!c&&!_&&!!b,m=null;if(r!=null)if(d&&!!ee&&e!=="GET"&&e!=="HEAD"){let p=T(h,c||b);m=N(new TextEncoder().encode(JSON.stringify(r)),p),O="application/octet-stream"}else m=JSON.stringify(r);let re=u=>{let p={"Content-Type":O,...i};if(!_&&n&&c&&(p.Authorization=`Bearer ${c}`),te&&(p["X-Packet-Token"]=b),R&&u&&(p[Y]=u),_){let se=m instanceof Uint8Array?m:typeof m=="string"?new TextEncoder().encode(m):new Uint8Array(0);Object.assign(p,D(e,t,se,l,h))}return p};R&&!k&&P&&(k=await P());let U=u=>fetch(a+t,{method:e,headers:re(u),...m!=null?{body:m}:{},credentials:"include"}),f=await U(k);if(!f.ok){let u=await G(f.clone());if(R&&P&&de(f.status,u))k=await P(),f=await U(k);else{let p=new Error(u);throw p.status=f.status,p}}if(!f.ok){let u=new Error(await G(f));throw u.status=f.status,u}let $=f.headers.get("Content-Type")??"";if($.includes("application/octet-stream")){let u=T(h,c||b);return S(await f.arrayBuffer(),u)}if(!$.includes("application/json"))return await f.text();let v=await f.json();if(o&&!v.ok){let u=new Error(v.message??`EntityServer error (HTTP ${f.status})`);throw u.status=f.status,u}return v}var x=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=H("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=T(this.hmacSecret,this.token||this.anonymousPacketToken);return L(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 A(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 A(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 X(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 Q(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,l={page:1,limit:20,...c};return a&&(l.orderBy=o==="DESC"?`-${a}`:a),i?.length&&(l.fields=i.join(",")),this._request("POST",`/v1/entity/${t}/list?${w(l)}`,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}?${w({page:1,limit:50,...n})}`)}rollback(t,r){return this._request("POST",`/v1/entity/${t}/rollback/${r}`)}}}function J(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:l,pushEnabled:h=!0,transactionId:d}=i;return this.submit("account_device",{id:r,account_seq:t,push_token:n,push_enabled:h,...o?{platform:o}:{},...a?{device_type:a}:{},...c?{browser:c}:{},...l?{browser_version:l}:{}},{transactionId:d})}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 z(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 V(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 Z(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 E=class extends Z(V(z(J(Q(X(x)))))){};var Ye=new E;export{E as EntityServerClient,Ye as entityServer};
2
2
  //# sourceMappingURL=index.js.map