@k-msg/core 0.29.7 → 0.29.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -13,10 +13,6 @@ export declare class FieldCryptoError extends KMsgError {
13
13
  readonly openFallback?: FieldCryptoOpenFallback;
14
14
  constructor(kind: FieldCryptoErrorKind, message: string, details?: Record<string, unknown>, metadata?: FieldCryptoErrorMetadata);
15
15
  toJSON(): {
16
- kind: FieldCryptoErrorKind;
17
- fieldPath: string | undefined;
18
- failMode: FieldCryptoFailMode | undefined;
19
- openFallback: FieldCryptoOpenFallback | undefined;
20
16
  name: string;
21
17
  code: KMsgErrorCode;
22
18
  message: string;
@@ -28,5 +24,9 @@ export declare class FieldCryptoError extends KMsgError {
28
24
  retryAfterMs: number | undefined;
29
25
  attempt: number | undefined;
30
26
  causeChain: unknown[] | undefined;
27
+ kind: FieldCryptoErrorKind;
28
+ fieldPath: string | undefined;
29
+ failMode: FieldCryptoFailMode | undefined;
30
+ openFallback: FieldCryptoOpenFallback | undefined;
31
31
  };
32
32
  }
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- var{defineProperty:V,getOwnPropertyNames:Et,getOwnPropertyDescriptor:xt}=Object,Mt=Object.prototype.hasOwnProperty;function vt(t){return this[t]}var _t=(t)=>{var n=(pt??=new WeakMap).get(t),e;if(n)return n;if(n=V({},"__esModule",{value:!0}),t&&typeof t==="object"||typeof t==="function"){for(var i of Et(t))if(!Mt.call(n,i))V(n,i,{get:vt.bind(t,i),enumerable:!(e=xt(t,i))||e.enumerable})}return pt.set(t,n),n},pt;var Nt=(t)=>t;function It(t,n){this[t]=Nt.bind(null,n)}var Ut=(t,n)=>{for(var e in n)V(t,e,{get:n[e],enumerable:!0,configurable:!0,set:It.bind(n,e)})};var vn={};Ut(vn,{validateFieldCryptoConfig:()=>Pt,validateErrorRetryPolicy:()=>gt,toCiphertextEnvelopeString:()=>ln,setGlobalLogger:()=>Fn,selectActiveKidByRollout:()=>N,resolveFieldMode:()=>L,readRuntimeEnv:()=>Sn,parseErrorRetryPolicyFromJson:()=>Gt,ok:()=>it,normalizeRetryAfterMs:()=>x,normalizeProviderError:()=>Yt,normalizePhoneForHash:()=>bt,normalizeMessageStatus:()=>Mn,normalizeErrorRetryPolicy:()=>Kt,loggerMiddleware:()=>Pn,logger:()=>An,isTerminalDeliveryStatus:()=>mn,isPollableDeliveryStatus:()=>Tn,isKMsgTerminalStatus:()=>kn,isKMsgMessageType:()=>En,isKMsgDeliveryStatus:()=>Dn,isCryptoEnvelope:()=>cn,getRuntimeEnvSource:()=>Dt,getRolloutKnownKids:()=>W,getPollableStatuses:()=>On,getLogger:()=>k,fail:()=>st,createVaultTransitKeyResolver:()=>pn,createStaticKeyResolver:()=>Q,createRollingKeyResolver:()=>nn,createRefreshableKeyResolver:()=>v,createNoopFieldCryptoProvider:()=>dn,createLogger:()=>tt,createEnvKeyResolver:()=>rn,createDefaultMasker:()=>X,createAwsKmsKeyResolver:()=>en,createAesGcmFieldCryptoProvider:()=>an,assertFieldCryptoConfig:()=>yn,RetryHandler:()=>T,Result:()=>wn,RateLimiter:()=>et,QUEUED_MESSAGE_STATUS:()=>Rt,Logger:()=>$,LogLevel:()=>ut,KNOWN_MESSAGE_STATUSES:()=>xn,KMsgErrorCode:()=>R,KMsgError:()=>K,KMSG_TERMINAL_STATUSES:()=>mt,KMSG_POLLABLE_STATUSES:()=>rt,KMSG_MESSAGE_TYPES:()=>Ot,KMSG_DELIVERY_STATUSES:()=>kt,FieldCryptoError:()=>M,ErrorUtils:()=>O,CircuitBreaker:()=>nt,BulkOperationHandler:()=>H});module.exports=_t(vn);var R;((l)=>{l.INVALID_REQUEST="INVALID_REQUEST";l.AUTHENTICATION_FAILED="AUTHENTICATION_FAILED";l.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE";l.TEMPLATE_NOT_FOUND="TEMPLATE_NOT_FOUND";l.RATE_LIMIT_EXCEEDED="RATE_LIMIT_EXCEEDED";l.NETWORK_ERROR="NETWORK_ERROR";l.NETWORK_TIMEOUT="NETWORK_TIMEOUT";l.NETWORK_SERVICE_UNAVAILABLE="NETWORK_SERVICE_UNAVAILABLE";l.PROVIDER_ERROR="PROVIDER_ERROR";l.MESSAGE_SEND_FAILED="MESSAGE_SEND_FAILED";l.CRYPTO_CONFIG_ERROR="CRYPTO_CONFIG_ERROR";l.CRYPTO_ENCRYPT_FAILED="CRYPTO_ENCRYPT_FAILED";l.CRYPTO_DECRYPT_FAILED="CRYPTO_DECRYPT_FAILED";l.CRYPTO_HASH_FAILED="CRYPTO_HASH_FAILED";l.CRYPTO_POLICY_VIOLATION="CRYPTO_POLICY_VIOLATION";l.UNKNOWN_ERROR="UNKNOWN_ERROR"})(R||={});var Bt={["INVALID_REQUEST"]:{ko:"잘못된 요청입니다",en:"Invalid request"},["AUTHENTICATION_FAILED"]:{ko:"인증에 실패했습니다",en:"Authentication failed"},["INSUFFICIENT_BALANCE"]:{ko:"잔액이 부족합니다",en:"Insufficient balance"},["TEMPLATE_NOT_FOUND"]:{ko:"템플릿을 찾을 수 없습니다",en:"Template not found"},["RATE_LIMIT_EXCEEDED"]:{ko:"요청 한도를 초과했습니다",en:"Rate limit exceeded"},["NETWORK_ERROR"]:{ko:"네트워크 오류가 발생했습니다",en:"Network error"},["NETWORK_TIMEOUT"]:{ko:"네트워크 요청 시간이 초과되었습니다",en:"Network timeout"},["NETWORK_SERVICE_UNAVAILABLE"]:{ko:"서비스를 일시적으로 사용할 수 없습니다",en:"Service temporarily unavailable"},["PROVIDER_ERROR"]:{ko:"제공자 오류가 발생했습니다",en:"Provider error"},["MESSAGE_SEND_FAILED"]:{ko:"메시지 전송에 실패했습니다",en:"Message send failed"},["CRYPTO_CONFIG_ERROR"]:{ko:"암호화 설정 오류가 발생했습니다",en:"Crypto configuration error"},["CRYPTO_ENCRYPT_FAILED"]:{ko:"암호화에 실패했습니다",en:"Encryption failed"},["CRYPTO_DECRYPT_FAILED"]:{ko:"복호화에 실패했습니다",en:"Decryption failed"},["CRYPTO_HASH_FAILED"]:{ko:"해시 생성에 실패했습니다",en:"Hash generation failed"},["CRYPTO_POLICY_VIOLATION"]:{ko:"암호화 정책 위반이 발생했습니다",en:"Crypto policy violation"},["UNKNOWN_ERROR"]:{ko:"알 수 없는 오류가 발생했습니다",en:"Unknown error"}},qt=new Set(Object.values(R)),yt=new Set(["NETWORK_ERROR","RATE_LIMIT_EXCEEDED","NETWORK_TIMEOUT","NETWORK_SERVICE_UNAVAILABLE","PROVIDER_ERROR","UNKNOWN_ERROR"]),ft=new Set(["INVALID_REQUEST","AUTHENTICATION_FAILED","INSUFFICIENT_BALANCE","TEMPLATE_NOT_FOUND","MESSAGE_SEND_FAILED","CRYPTO_CONFIG_ERROR","CRYPTO_ENCRYPT_FAILED","CRYPTO_DECRYPT_FAILED","CRYPTO_HASH_FAILED","CRYPTO_POLICY_VIOLATION"]),P=(t)=>{if(typeof t!=="number"||Number.isNaN(t)||!Number.isFinite(t))return;return Math.trunc(t)},x=(t)=>{let n=P(t);if(n===void 0||n<0)return;return n},G=(t)=>{if(typeof t!=="string")return;return t.toLowerCase().trim()},$t=(t)=>{if(typeof t!=="string")return;let n=t.trim();return n.length>0?n:void 0},w=(t)=>{return typeof t==="object"&&t!==null&&!Array.isArray(t)},u=(t,n)=>{for(let e of n)if(e in t)return t[e];return},Ht=(t)=>{return t.length>0?t:"$"},lt=(t)=>{return t==="compat"?"compat":"safe"},ot=(t)=>{if(t>=500)return"retryable";if(t===408||t===425||t===429)return"retryable";return"non_retryable"},ct=(t)=>{let n=t.toLowerCase();if(n.includes("timeout")||n.includes("temporar")||n.includes("network")||n.includes("retry"))return"retryable";return};class K extends Error{code;details;providerErrorCode;providerErrorText;httpStatus;requestId;retryAfterMs;attempt;causeChain;constructor(t,n,e,i={}){super(n);if(this.name="KMsgError",this.code=t,this.details=e,this.providerErrorCode=i.providerErrorCode,this.providerErrorText=i.providerErrorText,this.httpStatus=P(i.httpStatus),this.requestId=typeof i.requestId==="string"?i.requestId:void 0,this.retryAfterMs=P(i.retryAfterMs),this.attempt=P(i.attempt),Array.isArray(i.causeChain))this.causeChain=i.causeChain;else if(i.causeChain!==void 0)this.causeChain=[i.causeChain];let r=Error.captureStackTrace;if(r)r(this,K)}getLocalizedMessage(t="ko"){let n=Bt[this.code];if(n?.[t])return n[t];return this.message}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details,providerErrorCode:this.providerErrorCode,providerErrorText:this.providerErrorText,httpStatus:this.httpStatus,requestId:this.requestId,retryAfterMs:this.retryAfterMs,attempt:this.attempt,causeChain:this.causeChain}}}var D=(t,n)=>{let e=P(t);if(e!==void 0)return e;if(n==="compat"&&typeof t==="string"){let i=Number(t.trim());if(Number.isFinite(i))return Math.trunc(i)}return},J=(t,n)=>{let e=$t(t);if(e)return e;if(n==="compat"&&(typeof t==="number"||typeof t==="boolean"))return String(t);return},ht=(t)=>{if(typeof t!=="string")return;let n=t.trim().toUpperCase();if(!qt.has(n))return;return n},m=(t,n)=>{t.push({...n,path:Ht(n.path)})},at=(t,n,e,i)=>{if(t===void 0)return[];let r=(()=>{if(Array.isArray(t))return t;if(e==="compat"&&typeof t==="string")return t.split(",").map((f)=>f.trim()).filter((f)=>f.length>0);return m(i,{code:"invalid_type",message:"expected array of KMsgErrorCode values",path:n}),[]})(),s=[],p=new Set;for(let f=0;f<r.length;f+=1){let y=r[f],o=ht(typeof y==="string"?y:e==="compat"?String(y):y);if(!o){m(i,{code:"unknown_code",message:`unknown retry policy code: ${String(y)}`,path:`${n}[${f}]`});continue}if(p.has(o)){m(i,{code:"duplicate_code",message:`duplicate retry policy code: ${o}`,path:`${n}[${f}]`});continue}p.add(o),s.push(o)}return s},Vt=(t,n,e)=>{if(t===void 0)return;if(typeof t==="string"){let i=t.trim().toLowerCase();if(i==="retryable")return"retryable";if(i==="non_retryable"||i==="non-retryable")return"non_retryable"}if(n==="compat"&&typeof t==="boolean")return t?"retryable":"non_retryable";m(e,{code:"invalid_fallback",message:`invalid fallback value: ${String(t)}`,path:"fallback"});return};function gt(t,n={}){let e=lt(n.mode),i=[];if(!w(t))return m(i,{code:"invalid_root",message:"retry policy must be an object",path:"$"}),{policy:null,issues:i};let r=new Set(["retryableCodes","nonRetryableCodes","fallback"]);for(let d of Object.keys(t)){if(r.has(d))continue;m(i,{code:"unknown_field",message:`unknown retry policy field: ${d}`,path:d})}let s=at(t.retryableCodes,"retryableCodes",e,i),p=at(t.nonRetryableCodes,"nonRetryableCodes",e,i),f=Vt(t.fallback,e,i),y=new Set(s),o=new Set(p);for(let d of y){if(!o.has(d))continue;y.delete(d),m(i,{code:"conflicting_code",message:`code '${d}' is both retryable and nonRetryable; nonRetryable wins`,path:"retryableCodes"})}let a={...y.size>0?{retryableCodes:Array.from(y)}:{},...o.size>0?{nonRetryableCodes:Array.from(o)}:{},...f?{fallback:f}:{}};return{policy:a.retryableCodes!==void 0||a.nonRetryableCodes!==void 0||a.fallback!==void 0?a:null,issues:i}}function Kt(t,n={}){return gt(t,n).policy}function Gt(t,n={}){if(typeof t!=="string"||t.trim().length===0)return null;try{let e=JSON.parse(t);return Kt(e,n)}catch{return null}}var dt=(t,n)=>{let e=t.response;if(!w(e))return;return D(u(e,["status","statusCode","httpStatus"]),n)},Jt=(t,n)=>{if(t instanceof K&&Array.isArray(t.causeChain))return t.causeChain.slice();if(w(t)){let s=t.causeChain;if(Array.isArray(s))return s.slice();let p=t.details;if(n==="compat"&&w(p)){let f=p.causeChain;if(Array.isArray(f))return f.slice();if(f!==void 0)return[f]}}let e=[],i=new Set,r=t;for(let s=0;s<8;s+=1){if(!w(r))break;let p=r.cause;if(p===void 0||i.has(p))break;i.add(p),e.push(p),r=p}return e.length>0?e:void 0},Wt=(t)=>{if(t instanceof Error&&typeof t.message==="string")return t.message;if(w(t)&&typeof t.message==="string")return t.message;return typeof t==="string"?t:"Unknown error"};function Yt(t,n={}){let e=lt(n.mode),r=n.defaultCode??"UNKNOWN_ERROR",s={code:"fallback",classification:n.policy?"policy":"fallback"},p,f,y,o,a,h,d,A=(c)=>{if(c.providerErrorCode!==void 0)p=c.providerErrorCode,s.providerErrorCode="metadata";if(c.providerErrorText!==void 0)f=c.providerErrorText,s.providerErrorText="metadata";if(c.httpStatus!==void 0)y=c.httpStatus,s.httpStatus="metadata";if(c.requestId!==void 0)o=c.requestId,s.requestId="metadata";if(c.retryAfterMs!==void 0)a=x(c.retryAfterMs),s.retryAfterMs="metadata";if(c.attempt!==void 0)h=D(c.attempt,e),s.attempt="metadata";if(Array.isArray(c.causeChain))d=c.causeChain.slice(),s.causeChain="metadata"},C=(c,F)=>{if(p===void 0){let g=J(u(c,["providerErrorCode","errorCode","resultCode"]),e);if(g!==void 0)p=g,s.providerErrorCode=F}if(f===void 0){let g=J(u(c,["providerErrorText","errorMessage","msg","message"]),e);if(g!==void 0)f=g,s.providerErrorText=F}if(y===void 0){let g=D(u(c,["httpStatus","statusCode","status"]),e)??dt(c,e);if(g!==void 0)y=g,s.httpStatus=F==="details"?"details":"http"}if(o===void 0){let g=J(u(c,["requestId","request_id","reqId","traceId"]),e);if(g!==void 0)o=g,s.requestId=F}if(a===void 0){let g=x(D(u(c,["retryAfterMs","retry_after_ms","retryAfter"]),e));if(g!==void 0)a=g,s.retryAfterMs=F}if(h===void 0){let g=D(c.attempt,e);if(g!==void 0&&g>0)h=g,s.attempt=F}};if(t instanceof K){if(r=t.code,s.code="input",A(t),e==="compat"&&w(t.details))C(t.details,"details")}else if(w(t)){let c=ht(u(t,["code","errorCode","resultCode"]));if(c!==void 0)r=c,s.code="input";else if(y===void 0){let F=D(u(t,["httpStatus","statusCode","status"]),e)??dt(t,e);if(F!==void 0&&F>=500)r="PROVIDER_ERROR",s.code="http"}if(C(t,"input"),e==="compat"&&w(t.details))C(t.details,"details")}if(d===void 0){let c=Jt(t,e);if(c!==void 0)d=c,s.causeChain="input"}if(n.attempt!==void 0&&D(n.attempt,e)!==void 0){let c=D(n.attempt,e);if(c!==void 0&&c>0)h=c,s.attempt="input"}let b=new K(r,Wt(t),void 0,{providerErrorCode:p,providerErrorText:f,httpStatus:y,requestId:o,retryAfterMs:a,attempt:h,causeChain:d}),l=O.classifyForRetry(b,n.policy);return{code:r,classification:l,...p!==void 0?{providerErrorCode:p}:{},...f!==void 0?{providerErrorText:f}:{},...y!==void 0?{httpStatus:y}:{},...o!==void 0?{requestId:o}:{},...a!==void 0?{retryAfterMs:a}:{},...h!==void 0?{attempt:h}:{},...d!==void 0?{causeChain:d}:{},sources:s}}var O={isRetryable(t,n={}){return O.classifyForRetry(t,n)==="retryable"},classifyForRetry(t,n={}){if(t instanceof K){if(new Set(n.retryableCodes??Array.from(yt)).has(t.code))return"retryable";if(new Set(n.nonRetryableCodes??Array.from(ft)).has(t.code))return"non_retryable";if(t.httpStatus!==void 0)return ot(t.httpStatus);let y=ct(t.message);if(y)return y;if(n.classifyByMessage&&t.message){let o=n.classifyByMessage(t.message);if(o)return o}if(n.fallback)return n.fallback;return"non_retryable"}let e=t&&typeof t==="object"?t:void 0,i=G(e?.status)??G(e?.statusCode)??G(e?.code),r=P(e?.status)??P(e?.statusCode)??P(e?.httpStatus);if(typeof i==="string"&&i.startsWith("5"))return"retryable";if(r!==void 0){if(n.classifyByStatusCode)return n.classifyByStatusCode(r);return ot(r)}let s=typeof e?.message==="string"?ct(e.message):void 0;if(s)return s;if(n.classifyByMessage&&typeof e?.message==="string"){let p=n.classifyByMessage(e.message);if(p)return p}return n.fallback??"non_retryable"},resolveRetryAfterMs(t,n){if(n?.retryAfterMs){let e=n.retryAfterMs(t),i=x(e);if(i!==void 0)return i}if(t.retryAfterMs!==void 0)return x(t.retryAfterMs);if(t.code==="RATE_LIMIT_EXCEEDED"&&t.retryAfterMs===void 0)return;return},isUnknownStatus:(t)=>{if(t===void 0||Number.isNaN(t)||!Number.isFinite(t))return!1;return t<500},toRetryMetadata(t){return{providerErrorCode:t.providerErrorCode,providerErrorText:t.providerErrorText,httpStatus:t.httpStatus,requestId:t.requestId,retryAfterMs:t.retryAfterMs,attempt:t.attempt,causeChain:t.causeChain}},withAttempt(t,n){return new K(t.code,t.message,t.details,{...O.toRetryMetadata(t),attempt:P(n)})},DEFAULT_RETRYABLE_ERROR_CODES:yt,DEFAULT_NON_RETRYABLE_ERROR_CODES:ft};function jt(t){switch(t){case"config":return"CRYPTO_CONFIG_ERROR";case"encrypt":return"CRYPTO_ENCRYPT_FAILED";case"decrypt":return"CRYPTO_DECRYPT_FAILED";case"hash":return"CRYPTO_HASH_FAILED";case"policy":return"CRYPTO_POLICY_VIOLATION"}}class M extends K{kind;fieldPath;failMode;openFallback;constructor(t,n,e,i={}){super(jt(t),n,e,i);this.name="FieldCryptoError",this.kind=t,this.fieldPath=typeof i.fieldPath==="string"?i.fieldPath:void 0,this.failMode=i.failMode,this.openFallback=i.openFallback}toJSON(){return{...super.toJSON(),kind:this.kind,fieldPath:this.fieldPath,failMode:this.failMode,openFallback:this.openFallback}}}var Qt=["tenantId","providerId","messageId"];function _(t){if(typeof t!=="string")return;let n=t.trim();return n.length>0?n:void 0}function Zt(t){if(typeof t!=="number"||!Number.isFinite(t))return;if(t<=0||t>100)return;return t}function Ct(t){let n=[];for(let e of t){let i=_(e.kid),r=Zt(e.percentage);if(!i||r===void 0)continue;n.push({kid:i,percentage:r})}return n}function Lt(t,n,e){let i=n.map((r)=>{let s=t[r];return typeof s==="string"?s:""}).join("|");return`${e}::${i}`}function Xt(t){let n=2166136261;for(let e=0;e<t.length;e+=1)n^=t.charCodeAt(e),n=n*16777619>>>0;return n>>>0}function zt(t,n){let e=0;for(let i of t)if(e+=i.percentage,n<e)return i.kid;return}function N(t,n,e){let i=Ct(n.buckets),r=_(n.defaultKid)??_(e);if(i.length===0)return r;let s=_(n.seed)??"kmsg-rollout-v1",p=n.stickyFields??Qt,f=Lt(t,p,s),y=Xt(f)%100;return zt(i,y)??r}function W(t){return Ct(t.buckets).map((n)=>n.kid)}function E(t){if(typeof t!=="string")return;let n=t.trim();return n.length>0?n:void 0}function Y(t){if(!Array.isArray(t))return[];return t.map((n)=>E(n)).filter((n)=>Boolean(n))}function j(t){let n=[],e=new Set;for(let i of t){let r=E(i);if(!r||e.has(r))continue;e.add(r),n.push(r)}return n}function tn(t){return E(t.providerId)??"default"}function Q(t){let n=E(t.activeKid)??"default",e=j([n,...Y(t.decryptKids)]);return{async resolveEncryptKey(){return{kid:n}},async resolveDecryptKeys(){return e}}}function v(t){let n=typeof t.cacheTtlMs==="number"&&t.cacheTtlMs>=0?Math.trunc(t.cacheTtlMs):30000,e=E(t.fallback?.activeKid),i=Y(t.fallback?.decryptKids),r;async function s(p){let f=Date.now();if(r&&f<r.expiresAt)return r.value;let y=await t.provider.loadKeySet(p),o=E(y.activeKid)??e??tn(p),a=j([o,...Y(y.decryptKids),...i]),h={activeKid:o,decryptKids:a,refreshedAt:Date.now()};return r={value:h,expiresAt:Date.now()+n},h}return{async resolveEncryptKey(p){return{kid:(await s(p)).activeKid}},async resolveDecryptKeys(p){let f=await s(p);return f.decryptKids??[f.activeKid]}}}function nn(t,n){return{async resolveEncryptKey(e){let i=await t.resolveEncryptKey(e);return{kid:N(e,n,i.kid)??i.kid}},async resolveDecryptKeys(e){let i=await t.resolveEncryptKey(e),r=t.resolveDecryptKeys?await t.resolveDecryptKeys(e):[i.kid],s=N(e,n,i.kid),p=W(n);return j([...s?[s]:[],i.kid,...r??[],...p])}}}function en(t){return v({provider:{async loadKeySet(e){return t.client.getKeyState({...e,...t.keyAlias?{keyAlias:t.keyAlias}:{},...t.region?{region:t.region}:{}})}},cacheTtlMs:t.cacheTtlMs,fallback:{activeKid:t.fallbackActiveKid,decryptKids:t.fallbackDecryptKids}})}function I(t){if(typeof t!=="string")return;let n=t.trim();return n.length>0?n:void 0}function Ft(t,n){return I(t[n])}function sn(t,n){if(!t)return[];return t.split(n).map((e)=>I(e)).filter((e)=>Boolean(e))}function rn(t={}){let n=globalThis.process?.env,e=t.env??n??{},i=I(t.delimiter)??",",r=t.activeKidEnv??"KMSG_ACTIVE_KID",s=t.decryptKidsEnv??"KMSG_DECRYPT_KIDS",p=Ft(e,r)??I(t.fallbackActiveKid)??"default",f=[p,...sn(Ft(e,s),i),...t.fallbackDecryptKids??[]];return Q({activeKid:p,decryptKids:f})}function pn(t){return v({provider:{async loadKeySet(e){return t.client.getKeyState({...e,...t.mountPath?{mountPath:t.mountPath}:{},...t.keyName?{keyName:t.keyName}:{},...t.namespace?{namespace:t.namespace}:{}})}},cacheTtlMs:t.cacheTtlMs,fallback:{activeKid:t.fallbackActiveKid,decryptKids:t.fallbackDecryptKids}})}function Z(t){return typeof t==="function"}function At(t){if(typeof t!=="string")return;let n=t.trim();return n.length>0?n:void 0}function L(t,n,e){let i=t.fields[n];if(i)return i;if(n.startsWith("metadata.")){let r=t.fields["metadata.*"];if(r)return r}return e}function Pt(t,n={}){let e=[];if(!t||typeof t!=="object")return{valid:!1,issues:[{message:"fieldCrypto config must be an object",rule:"fieldCrypto.config.object",hint:"Provide a valid FieldCryptoConfig object"}]};if(!t.provider||typeof t.provider!=="object")e.push({message:"fieldCrypto provider is required",rule:"fieldCrypto.provider.required",path:"provider",hint:"Set provider with encrypt/decrypt/hash methods"});else{if(!Z(t.provider.encrypt))e.push({message:"provider.encrypt must be a function",rule:"fieldCrypto.provider.encrypt.required",path:"provider.encrypt"});if(!Z(t.provider.decrypt))e.push({message:"provider.decrypt must be a function",rule:"fieldCrypto.provider.decrypt.required",path:"provider.decrypt"});if(!Z(t.provider.hash))e.push({message:"provider.hash must be a function",rule:"fieldCrypto.provider.hash.required",path:"provider.hash"})}if(!t.fields||typeof t.fields!=="object")e.push({message:"fieldCrypto.fields must be an object",rule:"fieldCrypto.fields.object",path:"fields",hint:"Define policies such as to, from, metadata.phoneNumber"});else{let s=Object.entries(t.fields);if(s.length===0)e.push({message:"fieldCrypto.fields must not be empty",rule:"fieldCrypto.fields.non_empty",path:"fields",hint:"Add at least one field mode mapping"});for(let[p,f]of s){if(!At(p))e.push({message:"field path must be a non-empty string",rule:"fieldCrypto.fields.path.non_empty",path:"fields"});if(f!=="plain"&&f!=="encrypt"&&f!=="encrypt+hash"&&f!=="mask")e.push({message:`unsupported field mode: ${String(f)}`,rule:"fieldCrypto.fields.mode.supported",path:`fields.${p}`})}}let i=t.failMode??"closed",r=t.openFallback??"masked";if(i==="open"&&r==="plaintext"&&t.unsafeAllowPlaintextStorage!==!0)e.push({message:"openFallback=plaintext requires unsafeAllowPlaintextStorage=true",rule:"fieldCrypto.fail_open.plaintext_guard",path:"openFallback",hint:"Use masked/null fallback, or explicitly enable unsafe plaintext"});if(Array.isArray(t.aadFields)){if(t.aadFields.length===0)e.push({message:"aadFields must not be empty when provided",rule:"fieldCrypto.aad_fields.non_empty",path:"aadFields"});for(let s=0;s<t.aadFields.length;s+=1){let p=t.aadFields[s];if(!At(p))e.push({message:"aadFields cannot include empty key",rule:"fieldCrypto.aad_fields.no_empty_key",path:`aadFields[${s}]`})}}if(n.secureMode&&!n.compatPlainColumns){let s=L(t,"to","encrypt+hash"),p=L(t,"from","encrypt+hash");if(s==="plain")e.push({message:"secure mode requires non-plain policy for `to` when compatPlainColumns=false",rule:"fieldCrypto.secure_mode.to_non_plain",path:"fields.to",hint:"Use encrypt+hash for lookup fields"});if(p==="plain")e.push({message:"secure mode requires non-plain policy for `from` when compatPlainColumns=false",rule:"fieldCrypto.secure_mode.from_non_plain",path:"fields.from",hint:"Use encrypt+hash for lookup fields"})}return{valid:e.length===0,issues:e}}function yn(t,n={}){let e=Pt(t,n);if(e.valid)return;let i=e.issues[0];if(!i)throw new M("config","fieldCrypto config validation failed",{rule:"fieldCrypto.config.invalid",issues:e.issues});throw new M("config",i.message,{rule:i.rule,path:i.path,hint:i.hint,issues:e.issues},{fieldPath:i.path})}function U(t){let n=t instanceof Uint8Array?t:new Uint8Array(t),e=typeof globalThis<"u"?globalThis.Buffer:void 0;return(e?e.from(n).toString("base64"):btoa(String.fromCharCode(...n))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function B(t){let n=t.replace(/-/g,"+").replace(/_/g,"/"),e=n.length%4===0?n:`${n}${"=".repeat(4-n.length%4)}`,i=typeof globalThis<"u"?globalThis.Buffer:void 0;if(i)return new Uint8Array(i.from(e,"base64"));let r=atob(e),s=new Uint8Array(r.length);for(let p=0;p<r.length;p+=1)s[p]=r.charCodeAt(p);return s}function wt(t,n){if(t instanceof Uint8Array)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(n==="base64url")return B(t);return new TextEncoder().encode(t)}function fn(t){let n=t instanceof Uint8Array?t:new Uint8Array(t);return Array.from(n).map((e)=>e.toString(16).padStart(2,"0")).join("")}function S(t){let n=new Uint8Array(t.byteLength);return n.set(t),n.buffer}function St(t){let n=JSON.parse(t);if(!n||typeof n!=="object"||typeof n.v!=="number"||typeof n.alg!=="string"||typeof n.kid!=="string"||typeof n.iv!=="string"||typeof n.tag!=="string"||typeof n.ct!=="string")throw Error("Invalid ciphertext envelope");return n}function on(t){if(typeof t==="string")return t;return JSON.stringify(t)}function cn(t){if(!t||typeof t!=="object")return!1;let n=t;return typeof n.v==="number"&&typeof n.alg==="string"&&typeof n.kid==="string"&&typeof n.iv==="string"&&typeof n.tag==="string"&&typeof n.ct==="string"}function bt(t){let n=String(t??"").trim();if(n.length===0)return"";let e=n.startsWith("+"),i=n.replace(/\D/g,"");return e?`+${i}`:i}function X(t=3,n=2){return(e)=>{let i=String(e??"");if(i.length<=t+n)return"*".repeat(Math.max(0,i.length));let r=i.slice(0,t),s=i.slice(-n);return`${r}${"*".repeat(i.length-t-n)}${s}`}}function an(t){let n=t.algorithm??"A256GCM",e=t.keyEncoding??"base64url",i=t.hashKeyEncoding??e,r=new Map,s=new Map,p=(y)=>{let o=r.get(y);if(o)return o;let a=t.keys[y];if(!a)throw Error(`Unknown encryption key id: ${y}`);let h=wt(a,e),d=crypto.subtle.importKey("raw",S(h),"AES-GCM",!1,["encrypt","decrypt"]);return r.set(y,d),d},f=(y)=>{let o=s.get(y);if(o)return o;let a=t.hashKeys?.[y]??t.keys[y];if(!a)throw Error(`Unknown hash key id: ${y}`);let h=wt(a,i),d=crypto.subtle.importKey("raw",S(h),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return s.set(y,d),d};return{async encrypt(y){let o=y.kid??t.activeKid,a=await p(o),h=crypto.getRandomValues(new Uint8Array(12)),d=new TextEncoder().encode(JSON.stringify(y.aad??{})),A=new TextEncoder().encode(y.value),C=await crypto.subtle.encrypt({name:"AES-GCM",iv:S(h),additionalData:S(d),tagLength:128},a,S(A)),b=new Uint8Array(C),l=b.slice(b.length-16),c=b.slice(0,b.length-16);return{ciphertext:{v:1,alg:n,kid:o,iv:U(h),tag:U(l),ct:U(c)},kid:o}},async decrypt(y){let o=St(y.ciphertext),a=y.candidateKids&&y.candidateKids.length>0?y.candidateKids:[o.kid],h=B(o.iv),d=B(o.tag),A=B(o.ct),C=new Uint8Array(A.length+d.length);C.set(A,0),C.set(d,A.length);let b=new TextEncoder().encode(JSON.stringify(y.aad??{})),l;for(let c of a)try{let F=await p(c),g=await crypto.subtle.decrypt({name:"AES-GCM",iv:S(h),additionalData:S(b),tagLength:128},F,S(C));return new TextDecoder().decode(new Uint8Array(g))}catch(F){l=F}throw Error(`Failed to decrypt ciphertext: ${l instanceof Error?l.message:String(l??"unknown")}`)},async hash(y){let o=y.kid??t.activeKid,a=await f(o),h=await crypto.subtle.sign("HMAC",a,S(new TextEncoder().encode(y.value)));return fn(h)},mask(y){return X()(y.value)}}}function dn(){return{encrypt(t){return{ciphertext:JSON.stringify({v:1,alg:"NOOP",kid:"noop",iv:"",tag:"",ct:t.value})}},decrypt(t){try{return St(t.ciphertext).ct}catch{return t.ciphertext}},hash(t){let n=bt(t.value);return U(new TextEncoder().encode(n))},mask(t){return X()(t.value)}}}function ln(t){return on(t)}var ut;((r)=>{r.DEBUG="DEBUG";r.INFO="INFO";r.WARN="WARN";r.ERROR="ERROR"})(ut||={});var hn=["to","from","phone","phoneNumber","recipient","sender","secret","apiKey","apiSecret","authorization","auth","token","password","payload","message","content","text"];function gn(t){let n=t.toLowerCase();return hn.some((e)=>n.includes(e.toLowerCase()))}function Kn(t){let n=t.trim();if(n.length<=4)return"***";if(n.includes("@")){let[r,s]=n.split("@");return`${r.slice(0,2)}${"*".repeat(Math.max(1,r.length-2))}@${s}`}let e=n.slice(0,3),i=n.slice(-2);return`${e}${"*".repeat(Math.max(1,n.length-5))}${i}`}function z(t,n){if(n===void 0||n===null)return n;if(gn(t)){if(typeof n==="string")return Kn(n);if(typeof n==="number"||typeof n==="boolean")return"***";if(Array.isArray(n))return"[REDACTED]";if(typeof n==="object")return"[REDACTED]"}if(Array.isArray(n))return n.map((e)=>z(t,e));if(typeof n==="object"){let e={};for(let[i,r]of Object.entries(n))e[i]=z(i,r);return e}return n}function Cn(t){let n={};for(let[e,i]of Object.entries(t))n[e]=z(e,i);return n}class ${config;context;constructor(t={},n={}){this.context=t,this.config={level:"INFO",enableConsole:!0,enableJson:!1,enableColors:!0,...n}}shouldLog(t){let n=["DEBUG","INFO","WARN","ERROR"];return n.indexOf(t)>=n.indexOf(this.config.level)}formatMessage(t){let n=Cn(t.context);if(this.config.enableJson)return JSON.stringify({level:t.level,message:t.message,timestamp:t.timestamp.toISOString(),context:n,...t.error&&{error:{name:t.error.name,message:t.error.message,stack:t.error.stack}},...t.duration&&{duration:t.duration}});let e=t.timestamp.toISOString(),i=this.config.enableColors?this.colorizeLevel(t.level):t.level,r=Object.keys(n).length>0?` [${Object.entries(n).map(([p,f])=>`${p}=${f}`).join(", ")}]`:"",s=`${e} ${i}${r}: ${t.message}`;if(t.duration!==void 0)s+=` (${t.duration}ms)`;if(t.error)s+=`
2
- ${t.error.stack}`;return s}colorizeLevel(t){if(!this.config.enableColors)return t;return`${{["DEBUG"]:"\x1B[36m",["INFO"]:"\x1B[32m",["WARN"]:"\x1B[33m",["ERROR"]:"\x1B[31m"}[t]}${t}\x1B[0m`}writeLog(t){if(!this.shouldLog(t.level))return;let n=this.formatMessage(t);if(this.config.enableConsole)(t.level==="ERROR"?console.error:t.level==="WARN"?console.warn:console.log)(n);if(this.config.enableFile&&this.config.filePath);}debug(t,n={}){this.writeLog({level:"DEBUG",message:t,timestamp:new Date,context:{...this.context,...n}})}info(t,n={}){this.writeLog({level:"INFO",message:t,timestamp:new Date,context:{...this.context,...n}})}warn(t,n={},e){this.writeLog({level:"WARN",message:t,timestamp:new Date,context:{...this.context,...n},error:e})}error(t,n={},e){this.writeLog({level:"ERROR",message:t,timestamp:new Date,context:{...this.context,...n},error:e})}child(t){return new $({...this.context,...t},this.config)}time(t){let n=Date.now();return()=>{let e=Date.now()-n;this.info(`${t} completed`,{duration:e})}}async measure(t,n,e={}){let i=Date.now(),r={...e,operation:t};this.debug(`Starting ${t}`,r);try{let s=await n(),p=Date.now()-i;return this.info(`Completed ${t}`,{...r,duration:p}),s}catch(s){let p=Date.now()-i;throw this.error(`Failed ${t}`,{...r,duration:p},s instanceof Error?s:Error(String(s))),s}}}var q;function tt(t,n){return new $(t,n)}function k(){if(!q)q=tt();return q}function Fn(t){q=t}var An={debug:(t,n)=>k().debug(t,n),info:(t,n)=>k().info(t,n),warn:(t,n,e)=>k().warn(t,n,e),error:(t,n,e)=>k().error(t,n,e),child:(t)=>k().child(t),time:(t)=>k().time(t),measure:(t,n,e)=>k().measure(t,n,e)};function Pn(t){let n=tt({},t);return async(e,i)=>{let r=Date.now(),p={requestId:Math.random().toString(36).substring(7),method:e.req.method,path:e.req.path,userAgent:e.req.header("user-agent")||"unknown"};n.info("Request started",p);try{await i();let f=Date.now()-r;n.info("Request completed",{...p,status:e.res.status,duration:f})}catch(f){let y=Date.now()-r;throw n.error("Request failed",{...p,duration:y},f instanceof Error?f:Error(String(f))),f}}}class T{static defaultOptions={maxAttempts:3,initialDelay:1000,maxDelay:30000,backoffMultiplier:2,jitter:!0,retryCondition:(t)=>O.isRetryable(t)};static async execute(t,n={}){let e={...T.defaultOptions,...n},i,r=e.initialDelay;for(let s=1;s<=e.maxAttempts;s++)try{return await t()}catch(p){if(i=p,s===e.maxAttempts||!e.retryCondition(i,s))throw i;let f=e.jitter?r+Math.random()*r*0.1:r;e.onRetry?.(i,s),await new Promise((y)=>setTimeout(y,f)),r=Math.min(r*e.backoffMultiplier,e.maxDelay)}throw i}static createRetryableFunction(t,n={}){return async(...e)=>{return T.execute(()=>t(...e),n)}}}class H{static async execute(t,n,e={}){let i={concurrency:5,retryOptions:{maxAttempts:3,initialDelay:1000,maxDelay:1e4,backoffMultiplier:2,jitter:!0},failFast:!1,...e},r=Date.now(),s=[],p=[],f=0,y=T.createRetryableFunction(n,i.retryOptions),o=H.createBatches(t,i.concurrency);for(let h of o){let d=h.map(async(A)=>{try{let C=await y(A);s.push({item:A,result:C})}catch(C){if(p.push({item:A,error:C}),i.failFast)throw new K("MESSAGE_SEND_FAILED",`Bulk operation failed fast after ${p.length} failures`,{totalItems:t.length,failedCount:p.length})}finally{f++,i.onProgress?.(f,t.length,p.length)}});if(await Promise.allSettled(d),i.failFast&&p.length>0)break}let a=Date.now()-r;return{successful:s,failed:p,summary:{total:t.length,successful:s.length,failed:p.length,duration:a}}}static createBatches(t,n){let e=[];for(let i=0;i<t.length;i+=n)e.push(t.slice(i,i+n));return e}}class nt{options;state="CLOSED";failureCount=0;lastFailureTime=0;nextAttemptTime=0;constructor(t){this.options=t}async execute(t){let n=Date.now();switch(this.state){case"OPEN":if(n<this.nextAttemptTime)throw new K("NETWORK_SERVICE_UNAVAILABLE","Circuit breaker is OPEN",{state:this.state,nextAttemptTime:this.nextAttemptTime});this.state="HALF_OPEN",this.options.onHalfOpen?.();break;case"HALF_OPEN":break;case"CLOSED":break}try{let e=await Promise.race([t(),new Promise((i,r)=>setTimeout(()=>r(new K("NETWORK_TIMEOUT","Circuit breaker timeout",{timeout:this.options.timeout})),this.options.timeout))]);if(this.state==="HALF_OPEN")this.state="CLOSED",this.failureCount=0,this.options.onClose?.();return e}catch(e){throw this.recordFailure(),e}}recordFailure(){if(this.failureCount++,this.lastFailureTime=Date.now(),this.failureCount>=this.options.failureThreshold)this.state="OPEN",this.nextAttemptTime=this.lastFailureTime+this.options.resetTimeout,this.options.onOpen?.()}getState(){return this.state}getFailureCount(){return this.failureCount}reset(){this.state="CLOSED",this.failureCount=0,this.lastFailureTime=0,this.nextAttemptTime=0}}class et{maxRequests;windowMs;requests=[];constructor(t,n){this.maxRequests=t;this.windowMs=n}async acquire(){let t=Date.now();if(this.requests=this.requests.filter((n)=>t-n<this.windowMs),this.requests.length>=this.maxRequests){let n=Math.min(...this.requests),e=this.windowMs-(t-n);if(e>0)return await new Promise((i)=>setTimeout(i,e)),this.acquire()}this.requests.push(t)}canMakeRequest(){let t=Date.now();return this.requests=this.requests.filter((n)=>t-n<this.windowMs),this.requests.length<this.maxRequests}getRemainingRequests(){let t=Date.now();return this.requests=this.requests.filter((n)=>t-n<this.windowMs),Math.max(0,this.maxRequests-this.requests.length)}}var it=(t)=>({isSuccess:!0,isFailure:!1,value:t}),st=(t)=>({isSuccess:!1,isFailure:!0,error:t}),wn={map(t,n){if(t.isSuccess)return it(n(t.value));return t},flatMap(t,n){if(t.isSuccess)return n(t.value);return t},mapError(t,n){if(t.isFailure)return st(n(t.error));return t},unwrap(t){if(t.isSuccess)return t.value;throw t.error},unwrapOr(t,n){if(t.isSuccess)return t.value;return n},unwrapOrElse(t,n){if(t.isSuccess)return t.value;return n(t.error)},match(t,n){if(t.isSuccess)return n.ok(t.value);return n.fail(t.error)},async fromPromise(t){try{let n=await t;return it(n)}catch(n){return st(n)}},isOk(t){return t.isSuccess},isFail(t){return t.isFailure},tap(t,n){return n(t),t},tapOk(t,n){if(t.isSuccess)n(t.value);return t},tapErr(t,n){if(t.isFailure)n(t.error);return t},expect(t,n){if(t.isSuccess)return t.value;throw Error(n,{cause:t.error})}};function Dt(){let t=globalThis;return t.__K_MSG_ENV__??t.__ENV__??t.process?.env??{}}function Sn(t){let n=Dt()[t];if(typeof n==="string")return n;if(n===void 0)return;return String(n)}var kt=["PENDING","SENT","DELIVERED","FAILED","CANCELLED","UNKNOWN"],mt=["DELIVERED","FAILED","CANCELLED","UNKNOWN"],rt=["PENDING","SENT"],bn=new Set(kt),Tt=new Set(mt),un=new Set(rt);function Dn(t){return bn.has(t)}function kn(t){return Tt.has(t)}function mn(t){return Tt.has(t)}function Tn(t){return un.has(t)}function On(){return rt}var Ot=["ALIMTALK","FRIENDTALK","SMS","LMS","MMS","NSA","VOICE","FAX","RCS_SMS","RCS_LMS","RCS_MMS","RCS_TPL","RCS_ITPL","RCS_LTPL"],Rn=new Set(Ot);function En(t){return Rn.has(t)}var xn=["PENDING","SENT","FAILED"],Rt="PENDING",Mn=(t)=>{let n=typeof t==="string"?t.trim().toUpperCase():"";if(n==="PENDING"||n==="SENT"||n==="FAILED")return n;return Rt};
1
+ var{defineProperty:V,getOwnPropertyNames:Et,getOwnPropertyDescriptor:xt}=Object,Mt=Object.prototype.hasOwnProperty;var pt=new WeakMap,vt=(t)=>{var n=pt.get(t),e;if(n)return n;if(n=V({},"__esModule",{value:!0}),t&&typeof t==="object"||typeof t==="function")Et(t).map((i)=>!Mt.call(n,i)&&V(n,i,{get:()=>t[i],enumerable:!(e=xt(t,i))||e.enumerable}));return pt.set(t,n),n};var _t=(t,n)=>{for(var e in n)V(t,e,{get:n[e],enumerable:!0,configurable:!0,set:(i)=>n[e]=()=>i})};var En={};_t(En,{validateFieldCryptoConfig:()=>Pt,validateErrorRetryPolicy:()=>gt,toCiphertextEnvelopeString:()=>cn,setGlobalLogger:()=>gn,selectActiveKidByRollout:()=>N,resolveFieldMode:()=>L,readRuntimeEnv:()=>An,parseErrorRetryPolicyFromJson:()=>$t,ok:()=>it,normalizeRetryAfterMs:()=>x,normalizeProviderError:()=>Gt,normalizePhoneForHash:()=>bt,normalizeMessageStatus:()=>Rn,normalizeErrorRetryPolicy:()=>Kt,loggerMiddleware:()=>Cn,logger:()=>Kn,isTerminalDeliveryStatus:()=>un,isPollableDeliveryStatus:()=>Dn,isKMsgTerminalStatus:()=>bn,isKMsgMessageType:()=>Tn,isKMsgDeliveryStatus:()=>Sn,isCryptoEnvelope:()=>yn,getRuntimeEnvSource:()=>Dt,getRolloutKnownKids:()=>W,getPollableStatuses:()=>kn,getLogger:()=>k,fail:()=>st,createVaultTransitKeyResolver:()=>en,createStaticKeyResolver:()=>Q,createRollingKeyResolver:()=>Xt,createRefreshableKeyResolver:()=>v,createNoopFieldCryptoProvider:()=>on,createLogger:()=>tt,createEnvKeyResolver:()=>nn,createDefaultMasker:()=>X,createAwsKmsKeyResolver:()=>zt,createAesGcmFieldCryptoProvider:()=>fn,assertFieldCryptoConfig:()=>sn,RetryHandler:()=>T,Result:()=>Fn,RateLimiter:()=>et,QUEUED_MESSAGE_STATUS:()=>Rt,Logger:()=>$,LogLevel:()=>ut,KNOWN_MESSAGE_STATUSES:()=>On,KMsgErrorCode:()=>R,KMsgError:()=>K,KMSG_TERMINAL_STATUSES:()=>mt,KMSG_POLLABLE_STATUSES:()=>rt,KMSG_MESSAGE_TYPES:()=>Ot,KMSG_DELIVERY_STATUSES:()=>kt,FieldCryptoError:()=>M,ErrorUtils:()=>O,CircuitBreaker:()=>nt,BulkOperationHandler:()=>H});module.exports=vt(En);var R;((l)=>{l.INVALID_REQUEST="INVALID_REQUEST";l.AUTHENTICATION_FAILED="AUTHENTICATION_FAILED";l.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE";l.TEMPLATE_NOT_FOUND="TEMPLATE_NOT_FOUND";l.RATE_LIMIT_EXCEEDED="RATE_LIMIT_EXCEEDED";l.NETWORK_ERROR="NETWORK_ERROR";l.NETWORK_TIMEOUT="NETWORK_TIMEOUT";l.NETWORK_SERVICE_UNAVAILABLE="NETWORK_SERVICE_UNAVAILABLE";l.PROVIDER_ERROR="PROVIDER_ERROR";l.MESSAGE_SEND_FAILED="MESSAGE_SEND_FAILED";l.CRYPTO_CONFIG_ERROR="CRYPTO_CONFIG_ERROR";l.CRYPTO_ENCRYPT_FAILED="CRYPTO_ENCRYPT_FAILED";l.CRYPTO_DECRYPT_FAILED="CRYPTO_DECRYPT_FAILED";l.CRYPTO_HASH_FAILED="CRYPTO_HASH_FAILED";l.CRYPTO_POLICY_VIOLATION="CRYPTO_POLICY_VIOLATION";l.UNKNOWN_ERROR="UNKNOWN_ERROR"})(R||={});var Nt={["INVALID_REQUEST"]:{ko:"잘못된 요청입니다",en:"Invalid request"},["AUTHENTICATION_FAILED"]:{ko:"인증에 실패했습니다",en:"Authentication failed"},["INSUFFICIENT_BALANCE"]:{ko:"잔액이 부족합니다",en:"Insufficient balance"},["TEMPLATE_NOT_FOUND"]:{ko:"템플릿을 찾을 수 없습니다",en:"Template not found"},["RATE_LIMIT_EXCEEDED"]:{ko:"요청 한도를 초과했습니다",en:"Rate limit exceeded"},["NETWORK_ERROR"]:{ko:"네트워크 오류가 발생했습니다",en:"Network error"},["NETWORK_TIMEOUT"]:{ko:"네트워크 요청 시간이 초과되었습니다",en:"Network timeout"},["NETWORK_SERVICE_UNAVAILABLE"]:{ko:"서비스를 일시적으로 사용할 수 없습니다",en:"Service temporarily unavailable"},["PROVIDER_ERROR"]:{ko:"제공자 오류가 발생했습니다",en:"Provider error"},["MESSAGE_SEND_FAILED"]:{ko:"메시지 전송에 실패했습니다",en:"Message send failed"},["CRYPTO_CONFIG_ERROR"]:{ko:"암호화 설정 오류가 발생했습니다",en:"Crypto configuration error"},["CRYPTO_ENCRYPT_FAILED"]:{ko:"암호화에 실패했습니다",en:"Encryption failed"},["CRYPTO_DECRYPT_FAILED"]:{ko:"복호화에 실패했습니다",en:"Decryption failed"},["CRYPTO_HASH_FAILED"]:{ko:"해시 생성에 실패했습니다",en:"Hash generation failed"},["CRYPTO_POLICY_VIOLATION"]:{ko:"암호화 정책 위반이 발생했습니다",en:"Crypto policy violation"},["UNKNOWN_ERROR"]:{ko:"알 수 없는 오류가 발생했습니다",en:"Unknown error"}},It=new Set(Object.values(R)),yt=new Set(["NETWORK_ERROR","RATE_LIMIT_EXCEEDED","NETWORK_TIMEOUT","NETWORK_SERVICE_UNAVAILABLE","PROVIDER_ERROR","UNKNOWN_ERROR"]),ft=new Set(["INVALID_REQUEST","AUTHENTICATION_FAILED","INSUFFICIENT_BALANCE","TEMPLATE_NOT_FOUND","MESSAGE_SEND_FAILED","CRYPTO_CONFIG_ERROR","CRYPTO_ENCRYPT_FAILED","CRYPTO_DECRYPT_FAILED","CRYPTO_HASH_FAILED","CRYPTO_POLICY_VIOLATION"]),P=(t)=>{if(typeof t!=="number"||Number.isNaN(t)||!Number.isFinite(t))return;return Math.trunc(t)},x=(t)=>{let n=P(t);if(n===void 0||n<0)return;return n},G=(t)=>{if(typeof t!=="string")return;return t.toLowerCase().trim()},Ut=(t)=>{if(typeof t!=="string")return;let n=t.trim();return n.length>0?n:void 0},w=(t)=>{return typeof t==="object"&&t!==null&&!Array.isArray(t)},u=(t,n)=>{for(let e of n)if(e in t)return t[e];return},Bt=(t)=>{return t.length>0?t:"$"},lt=(t)=>{return t==="compat"?"compat":"safe"},ot=(t)=>{if(t>=500)return"retryable";if(t===408||t===425||t===429)return"retryable";return"non_retryable"},ct=(t)=>{let n=t.toLowerCase();if(n.includes("timeout")||n.includes("temporar")||n.includes("network")||n.includes("retry"))return"retryable";return};class K extends Error{code;details;providerErrorCode;providerErrorText;httpStatus;requestId;retryAfterMs;attempt;causeChain;constructor(t,n,e,i={}){super(n);if(this.name="KMsgError",this.code=t,this.details=e,this.providerErrorCode=i.providerErrorCode,this.providerErrorText=i.providerErrorText,this.httpStatus=P(i.httpStatus),this.requestId=typeof i.requestId==="string"?i.requestId:void 0,this.retryAfterMs=P(i.retryAfterMs),this.attempt=P(i.attempt),Array.isArray(i.causeChain))this.causeChain=i.causeChain;else if(i.causeChain!==void 0)this.causeChain=[i.causeChain];let r=Error.captureStackTrace;if(r)r(this,K)}getLocalizedMessage(t="ko"){let n=Nt[this.code];if(n?.[t])return n[t];return this.message}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details,providerErrorCode:this.providerErrorCode,providerErrorText:this.providerErrorText,httpStatus:this.httpStatus,requestId:this.requestId,retryAfterMs:this.retryAfterMs,attempt:this.attempt,causeChain:this.causeChain}}}var D=(t,n)=>{let e=P(t);if(e!==void 0)return e;if(n==="compat"&&typeof t==="string"){let i=Number(t.trim());if(Number.isFinite(i))return Math.trunc(i)}return},J=(t,n)=>{let e=Ut(t);if(e)return e;if(n==="compat"&&(typeof t==="number"||typeof t==="boolean"))return String(t);return},ht=(t)=>{if(typeof t!=="string")return;let n=t.trim().toUpperCase();if(!It.has(n))return;return n},m=(t,n)=>{t.push({...n,path:Bt(n.path)})},at=(t,n,e,i)=>{if(t===void 0)return[];let r=(()=>{if(Array.isArray(t))return t;if(e==="compat"&&typeof t==="string")return t.split(",").map((f)=>f.trim()).filter((f)=>f.length>0);return m(i,{code:"invalid_type",message:"expected array of KMsgErrorCode values",path:n}),[]})(),s=[],p=new Set;for(let f=0;f<r.length;f+=1){let y=r[f],o=ht(typeof y==="string"?y:e==="compat"?String(y):y);if(!o){m(i,{code:"unknown_code",message:`unknown retry policy code: ${String(y)}`,path:`${n}[${f}]`});continue}if(p.has(o)){m(i,{code:"duplicate_code",message:`duplicate retry policy code: ${o}`,path:`${n}[${f}]`});continue}p.add(o),s.push(o)}return s},qt=(t,n,e)=>{if(t===void 0)return;if(typeof t==="string"){let i=t.trim().toLowerCase();if(i==="retryable")return"retryable";if(i==="non_retryable"||i==="non-retryable")return"non_retryable"}if(n==="compat"&&typeof t==="boolean")return t?"retryable":"non_retryable";m(e,{code:"invalid_fallback",message:`invalid fallback value: ${String(t)}`,path:"fallback"});return};function gt(t,n={}){let e=lt(n.mode),i=[];if(!w(t))return m(i,{code:"invalid_root",message:"retry policy must be an object",path:"$"}),{policy:null,issues:i};let r=new Set(["retryableCodes","nonRetryableCodes","fallback"]);for(let d of Object.keys(t)){if(r.has(d))continue;m(i,{code:"unknown_field",message:`unknown retry policy field: ${d}`,path:d})}let s=at(t.retryableCodes,"retryableCodes",e,i),p=at(t.nonRetryableCodes,"nonRetryableCodes",e,i),f=qt(t.fallback,e,i),y=new Set(s),o=new Set(p);for(let d of y){if(!o.has(d))continue;y.delete(d),m(i,{code:"conflicting_code",message:`code '${d}' is both retryable and nonRetryable; nonRetryable wins`,path:"retryableCodes"})}let a={...y.size>0?{retryableCodes:Array.from(y)}:{},...o.size>0?{nonRetryableCodes:Array.from(o)}:{},...f?{fallback:f}:{}};return{policy:a.retryableCodes!==void 0||a.nonRetryableCodes!==void 0||a.fallback!==void 0?a:null,issues:i}}function Kt(t,n={}){return gt(t,n).policy}function $t(t,n={}){if(typeof t!=="string"||t.trim().length===0)return null;try{let e=JSON.parse(t);return Kt(e,n)}catch{return null}}var dt=(t,n)=>{let e=t.response;if(!w(e))return;return D(u(e,["status","statusCode","httpStatus"]),n)},Ht=(t,n)=>{if(t instanceof K&&Array.isArray(t.causeChain))return t.causeChain.slice();if(w(t)){let s=t.causeChain;if(Array.isArray(s))return s.slice();let p=t.details;if(n==="compat"&&w(p)){let f=p.causeChain;if(Array.isArray(f))return f.slice();if(f!==void 0)return[f]}}let e=[],i=new Set,r=t;for(let s=0;s<8;s+=1){if(!w(r))break;let p=r.cause;if(p===void 0||i.has(p))break;i.add(p),e.push(p),r=p}return e.length>0?e:void 0},Vt=(t)=>{if(t instanceof Error&&typeof t.message==="string")return t.message;if(w(t)&&typeof t.message==="string")return t.message;return typeof t==="string"?t:"Unknown error"};function Gt(t,n={}){let e=lt(n.mode),r=n.defaultCode??"UNKNOWN_ERROR",s={code:"fallback",classification:n.policy?"policy":"fallback"},p,f,y,o,a,h,d,A=(c)=>{if(c.providerErrorCode!==void 0)p=c.providerErrorCode,s.providerErrorCode="metadata";if(c.providerErrorText!==void 0)f=c.providerErrorText,s.providerErrorText="metadata";if(c.httpStatus!==void 0)y=c.httpStatus,s.httpStatus="metadata";if(c.requestId!==void 0)o=c.requestId,s.requestId="metadata";if(c.retryAfterMs!==void 0)a=x(c.retryAfterMs),s.retryAfterMs="metadata";if(c.attempt!==void 0)h=D(c.attempt,e),s.attempt="metadata";if(Array.isArray(c.causeChain))d=c.causeChain.slice(),s.causeChain="metadata"},C=(c,F)=>{if(p===void 0){let g=J(u(c,["providerErrorCode","errorCode","resultCode"]),e);if(g!==void 0)p=g,s.providerErrorCode=F}if(f===void 0){let g=J(u(c,["providerErrorText","errorMessage","msg","message"]),e);if(g!==void 0)f=g,s.providerErrorText=F}if(y===void 0){let g=D(u(c,["httpStatus","statusCode","status"]),e)??dt(c,e);if(g!==void 0)y=g,s.httpStatus=F==="details"?"details":"http"}if(o===void 0){let g=J(u(c,["requestId","request_id","reqId","traceId"]),e);if(g!==void 0)o=g,s.requestId=F}if(a===void 0){let g=x(D(u(c,["retryAfterMs","retry_after_ms","retryAfter"]),e));if(g!==void 0)a=g,s.retryAfterMs=F}if(h===void 0){let g=D(c.attempt,e);if(g!==void 0&&g>0)h=g,s.attempt=F}};if(t instanceof K){if(r=t.code,s.code="input",A(t),e==="compat"&&w(t.details))C(t.details,"details")}else if(w(t)){let c=ht(u(t,["code","errorCode","resultCode"]));if(c!==void 0)r=c,s.code="input";else if(y===void 0){let F=D(u(t,["httpStatus","statusCode","status"]),e)??dt(t,e);if(F!==void 0&&F>=500)r="PROVIDER_ERROR",s.code="http"}if(C(t,"input"),e==="compat"&&w(t.details))C(t.details,"details")}if(d===void 0){let c=Ht(t,e);if(c!==void 0)d=c,s.causeChain="input"}if(n.attempt!==void 0&&D(n.attempt,e)!==void 0){let c=D(n.attempt,e);if(c!==void 0&&c>0)h=c,s.attempt="input"}let b=new K(r,Vt(t),void 0,{providerErrorCode:p,providerErrorText:f,httpStatus:y,requestId:o,retryAfterMs:a,attempt:h,causeChain:d}),l=O.classifyForRetry(b,n.policy);return{code:r,classification:l,...p!==void 0?{providerErrorCode:p}:{},...f!==void 0?{providerErrorText:f}:{},...y!==void 0?{httpStatus:y}:{},...o!==void 0?{requestId:o}:{},...a!==void 0?{retryAfterMs:a}:{},...h!==void 0?{attempt:h}:{},...d!==void 0?{causeChain:d}:{},sources:s}}var O={isRetryable(t,n={}){return O.classifyForRetry(t,n)==="retryable"},classifyForRetry(t,n={}){if(t instanceof K){if(new Set(n.retryableCodes??Array.from(yt)).has(t.code))return"retryable";if(new Set(n.nonRetryableCodes??Array.from(ft)).has(t.code))return"non_retryable";if(t.httpStatus!==void 0)return ot(t.httpStatus);let y=ct(t.message);if(y)return y;if(n.classifyByMessage&&t.message){let o=n.classifyByMessage(t.message);if(o)return o}if(n.fallback)return n.fallback;return"non_retryable"}let e=t&&typeof t==="object"?t:void 0,i=G(e?.status)??G(e?.statusCode)??G(e?.code),r=P(e?.status)??P(e?.statusCode)??P(e?.httpStatus);if(typeof i==="string"&&i.startsWith("5"))return"retryable";if(r!==void 0){if(n.classifyByStatusCode)return n.classifyByStatusCode(r);return ot(r)}let s=typeof e?.message==="string"?ct(e.message):void 0;if(s)return s;if(n.classifyByMessage&&typeof e?.message==="string"){let p=n.classifyByMessage(e.message);if(p)return p}return n.fallback??"non_retryable"},resolveRetryAfterMs(t,n){if(n?.retryAfterMs){let e=n.retryAfterMs(t),i=x(e);if(i!==void 0)return i}if(t.retryAfterMs!==void 0)return x(t.retryAfterMs);if(t.code==="RATE_LIMIT_EXCEEDED"&&t.retryAfterMs===void 0)return;return},isUnknownStatus:(t)=>{if(t===void 0||Number.isNaN(t)||!Number.isFinite(t))return!1;return t<500},toRetryMetadata(t){return{providerErrorCode:t.providerErrorCode,providerErrorText:t.providerErrorText,httpStatus:t.httpStatus,requestId:t.requestId,retryAfterMs:t.retryAfterMs,attempt:t.attempt,causeChain:t.causeChain}},withAttempt(t,n){return new K(t.code,t.message,t.details,{...O.toRetryMetadata(t),attempt:P(n)})},DEFAULT_RETRYABLE_ERROR_CODES:yt,DEFAULT_NON_RETRYABLE_ERROR_CODES:ft};function Jt(t){switch(t){case"config":return"CRYPTO_CONFIG_ERROR";case"encrypt":return"CRYPTO_ENCRYPT_FAILED";case"decrypt":return"CRYPTO_DECRYPT_FAILED";case"hash":return"CRYPTO_HASH_FAILED";case"policy":return"CRYPTO_POLICY_VIOLATION"}}class M extends K{kind;fieldPath;failMode;openFallback;constructor(t,n,e,i={}){super(Jt(t),n,e,i);this.name="FieldCryptoError",this.kind=t,this.fieldPath=typeof i.fieldPath==="string"?i.fieldPath:void 0,this.failMode=i.failMode,this.openFallback=i.openFallback}toJSON(){return{...super.toJSON(),kind:this.kind,fieldPath:this.fieldPath,failMode:this.failMode,openFallback:this.openFallback}}}var Wt=["tenantId","providerId","messageId"];function _(t){if(typeof t!=="string")return;let n=t.trim();return n.length>0?n:void 0}function Yt(t){if(typeof t!=="number"||!Number.isFinite(t))return;if(t<=0||t>100)return;return t}function Ct(t){let n=[];for(let e of t){let i=_(e.kid),r=Yt(e.percentage);if(!i||r===void 0)continue;n.push({kid:i,percentage:r})}return n}function jt(t,n,e){let i=n.map((r)=>{let s=t[r];return typeof s==="string"?s:""}).join("|");return`${e}::${i}`}function Qt(t){let n=2166136261;for(let e=0;e<t.length;e+=1)n^=t.charCodeAt(e),n=n*16777619>>>0;return n>>>0}function Zt(t,n){let e=0;for(let i of t)if(e+=i.percentage,n<e)return i.kid;return}function N(t,n,e){let i=Ct(n.buckets),r=_(n.defaultKid)??_(e);if(i.length===0)return r;let s=_(n.seed)??"kmsg-rollout-v1",p=n.stickyFields??Wt,f=jt(t,p,s),y=Qt(f)%100;return Zt(i,y)??r}function W(t){return Ct(t.buckets).map((n)=>n.kid)}function E(t){if(typeof t!=="string")return;let n=t.trim();return n.length>0?n:void 0}function Y(t){if(!Array.isArray(t))return[];return t.map((n)=>E(n)).filter((n)=>Boolean(n))}function j(t){let n=[],e=new Set;for(let i of t){let r=E(i);if(!r||e.has(r))continue;e.add(r),n.push(r)}return n}function Lt(t){return E(t.providerId)??"default"}function Q(t){let n=E(t.activeKid)??"default",e=j([n,...Y(t.decryptKids)]);return{async resolveEncryptKey(){return{kid:n}},async resolveDecryptKeys(){return e}}}function v(t){let n=typeof t.cacheTtlMs==="number"&&t.cacheTtlMs>=0?Math.trunc(t.cacheTtlMs):30000,e=E(t.fallback?.activeKid),i=Y(t.fallback?.decryptKids),r;async function s(p){let f=Date.now();if(r&&f<r.expiresAt)return r.value;let y=await t.provider.loadKeySet(p),o=E(y.activeKid)??e??Lt(p),a=j([o,...Y(y.decryptKids),...i]),h={activeKid:o,decryptKids:a,refreshedAt:Date.now()};return r={value:h,expiresAt:Date.now()+n},h}return{async resolveEncryptKey(p){return{kid:(await s(p)).activeKid}},async resolveDecryptKeys(p){let f=await s(p);return f.decryptKids??[f.activeKid]}}}function Xt(t,n){return{async resolveEncryptKey(e){let i=await t.resolveEncryptKey(e);return{kid:N(e,n,i.kid)??i.kid}},async resolveDecryptKeys(e){let i=await t.resolveEncryptKey(e),r=t.resolveDecryptKeys?await t.resolveDecryptKeys(e):[i.kid],s=N(e,n,i.kid),p=W(n);return j([...s?[s]:[],i.kid,...r??[],...p])}}}function zt(t){return v({provider:{async loadKeySet(e){return t.client.getKeyState({...e,...t.keyAlias?{keyAlias:t.keyAlias}:{},...t.region?{region:t.region}:{}})}},cacheTtlMs:t.cacheTtlMs,fallback:{activeKid:t.fallbackActiveKid,decryptKids:t.fallbackDecryptKids}})}function I(t){if(typeof t!=="string")return;let n=t.trim();return n.length>0?n:void 0}function Ft(t,n){return I(t[n])}function tn(t,n){if(!t)return[];return t.split(n).map((e)=>I(e)).filter((e)=>Boolean(e))}function nn(t={}){let n=globalThis.process?.env,e=t.env??n??{},i=I(t.delimiter)??",",r=t.activeKidEnv??"KMSG_ACTIVE_KID",s=t.decryptKidsEnv??"KMSG_DECRYPT_KIDS",p=Ft(e,r)??I(t.fallbackActiveKid)??"default",f=[p,...tn(Ft(e,s),i),...t.fallbackDecryptKids??[]];return Q({activeKid:p,decryptKids:f})}function en(t){return v({provider:{async loadKeySet(e){return t.client.getKeyState({...e,...t.mountPath?{mountPath:t.mountPath}:{},...t.keyName?{keyName:t.keyName}:{},...t.namespace?{namespace:t.namespace}:{}})}},cacheTtlMs:t.cacheTtlMs,fallback:{activeKid:t.fallbackActiveKid,decryptKids:t.fallbackDecryptKids}})}function Z(t){return typeof t==="function"}function At(t){if(typeof t!=="string")return;let n=t.trim();return n.length>0?n:void 0}function L(t,n,e){let i=t.fields[n];if(i)return i;if(n.startsWith("metadata.")){let r=t.fields["metadata.*"];if(r)return r}return e}function Pt(t,n={}){let e=[];if(!t||typeof t!=="object")return{valid:!1,issues:[{message:"fieldCrypto config must be an object",rule:"fieldCrypto.config.object",hint:"Provide a valid FieldCryptoConfig object"}]};if(!t.provider||typeof t.provider!=="object")e.push({message:"fieldCrypto provider is required",rule:"fieldCrypto.provider.required",path:"provider",hint:"Set provider with encrypt/decrypt/hash methods"});else{if(!Z(t.provider.encrypt))e.push({message:"provider.encrypt must be a function",rule:"fieldCrypto.provider.encrypt.required",path:"provider.encrypt"});if(!Z(t.provider.decrypt))e.push({message:"provider.decrypt must be a function",rule:"fieldCrypto.provider.decrypt.required",path:"provider.decrypt"});if(!Z(t.provider.hash))e.push({message:"provider.hash must be a function",rule:"fieldCrypto.provider.hash.required",path:"provider.hash"})}if(!t.fields||typeof t.fields!=="object")e.push({message:"fieldCrypto.fields must be an object",rule:"fieldCrypto.fields.object",path:"fields",hint:"Define policies such as to, from, metadata.phoneNumber"});else{let s=Object.entries(t.fields);if(s.length===0)e.push({message:"fieldCrypto.fields must not be empty",rule:"fieldCrypto.fields.non_empty",path:"fields",hint:"Add at least one field mode mapping"});for(let[p,f]of s){if(!At(p))e.push({message:"field path must be a non-empty string",rule:"fieldCrypto.fields.path.non_empty",path:"fields"});if(f!=="plain"&&f!=="encrypt"&&f!=="encrypt+hash"&&f!=="mask")e.push({message:`unsupported field mode: ${String(f)}`,rule:"fieldCrypto.fields.mode.supported",path:`fields.${p}`})}}let i=t.failMode??"closed",r=t.openFallback??"masked";if(i==="open"&&r==="plaintext"&&t.unsafeAllowPlaintextStorage!==!0)e.push({message:"openFallback=plaintext requires unsafeAllowPlaintextStorage=true",rule:"fieldCrypto.fail_open.plaintext_guard",path:"openFallback",hint:"Use masked/null fallback, or explicitly enable unsafe plaintext"});if(Array.isArray(t.aadFields)){if(t.aadFields.length===0)e.push({message:"aadFields must not be empty when provided",rule:"fieldCrypto.aad_fields.non_empty",path:"aadFields"});for(let s=0;s<t.aadFields.length;s+=1){let p=t.aadFields[s];if(!At(p))e.push({message:"aadFields cannot include empty key",rule:"fieldCrypto.aad_fields.no_empty_key",path:`aadFields[${s}]`})}}if(n.secureMode&&!n.compatPlainColumns){let s=L(t,"to","encrypt+hash"),p=L(t,"from","encrypt+hash");if(s==="plain")e.push({message:"secure mode requires non-plain policy for `to` when compatPlainColumns=false",rule:"fieldCrypto.secure_mode.to_non_plain",path:"fields.to",hint:"Use encrypt+hash for lookup fields"});if(p==="plain")e.push({message:"secure mode requires non-plain policy for `from` when compatPlainColumns=false",rule:"fieldCrypto.secure_mode.from_non_plain",path:"fields.from",hint:"Use encrypt+hash for lookup fields"})}return{valid:e.length===0,issues:e}}function sn(t,n={}){let e=Pt(t,n);if(e.valid)return;let i=e.issues[0];if(!i)throw new M("config","fieldCrypto config validation failed",{rule:"fieldCrypto.config.invalid",issues:e.issues});throw new M("config",i.message,{rule:i.rule,path:i.path,hint:i.hint,issues:e.issues},{fieldPath:i.path})}function U(t){let n=t instanceof Uint8Array?t:new Uint8Array(t),e=typeof globalThis<"u"?globalThis.Buffer:void 0;return(e?e.from(n).toString("base64"):btoa(String.fromCharCode(...n))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function B(t){let n=t.replace(/-/g,"+").replace(/_/g,"/"),e=n.length%4===0?n:`${n}${"=".repeat(4-n.length%4)}`,i=typeof globalThis<"u"?globalThis.Buffer:void 0;if(i)return new Uint8Array(i.from(e,"base64"));let r=atob(e),s=new Uint8Array(r.length);for(let p=0;p<r.length;p+=1)s[p]=r.charCodeAt(p);return s}function wt(t,n){if(t instanceof Uint8Array)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(n==="base64url")return B(t);return new TextEncoder().encode(t)}function rn(t){let n=t instanceof Uint8Array?t:new Uint8Array(t);return Array.from(n).map((e)=>e.toString(16).padStart(2,"0")).join("")}function S(t){let n=new Uint8Array(t.byteLength);return n.set(t),n.buffer}function St(t){let n=JSON.parse(t);if(!n||typeof n!=="object"||typeof n.v!=="number"||typeof n.alg!=="string"||typeof n.kid!=="string"||typeof n.iv!=="string"||typeof n.tag!=="string"||typeof n.ct!=="string")throw Error("Invalid ciphertext envelope");return n}function pn(t){if(typeof t==="string")return t;return JSON.stringify(t)}function yn(t){if(!t||typeof t!=="object")return!1;let n=t;return typeof n.v==="number"&&typeof n.alg==="string"&&typeof n.kid==="string"&&typeof n.iv==="string"&&typeof n.tag==="string"&&typeof n.ct==="string"}function bt(t){let n=String(t??"").trim();if(n.length===0)return"";let e=n.startsWith("+"),i=n.replace(/\D/g,"");return e?`+${i}`:i}function X(t=3,n=2){return(e)=>{let i=String(e??"");if(i.length<=t+n)return"*".repeat(Math.max(0,i.length));let r=i.slice(0,t),s=i.slice(-n);return`${r}${"*".repeat(i.length-t-n)}${s}`}}function fn(t){let n=t.algorithm??"A256GCM",e=t.keyEncoding??"base64url",i=t.hashKeyEncoding??e,r=new Map,s=new Map,p=(y)=>{let o=r.get(y);if(o)return o;let a=t.keys[y];if(!a)throw Error(`Unknown encryption key id: ${y}`);let h=wt(a,e),d=crypto.subtle.importKey("raw",S(h),"AES-GCM",!1,["encrypt","decrypt"]);return r.set(y,d),d},f=(y)=>{let o=s.get(y);if(o)return o;let a=t.hashKeys?.[y]??t.keys[y];if(!a)throw Error(`Unknown hash key id: ${y}`);let h=wt(a,i),d=crypto.subtle.importKey("raw",S(h),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return s.set(y,d),d};return{async encrypt(y){let o=y.kid??t.activeKid,a=await p(o),h=crypto.getRandomValues(new Uint8Array(12)),d=new TextEncoder().encode(JSON.stringify(y.aad??{})),A=new TextEncoder().encode(y.value),C=await crypto.subtle.encrypt({name:"AES-GCM",iv:S(h),additionalData:S(d),tagLength:128},a,S(A)),b=new Uint8Array(C),l=b.slice(b.length-16),c=b.slice(0,b.length-16);return{ciphertext:{v:1,alg:n,kid:o,iv:U(h),tag:U(l),ct:U(c)},kid:o}},async decrypt(y){let o=St(y.ciphertext),a=y.candidateKids&&y.candidateKids.length>0?y.candidateKids:[o.kid],h=B(o.iv),d=B(o.tag),A=B(o.ct),C=new Uint8Array(A.length+d.length);C.set(A,0),C.set(d,A.length);let b=new TextEncoder().encode(JSON.stringify(y.aad??{})),l;for(let c of a)try{let F=await p(c),g=await crypto.subtle.decrypt({name:"AES-GCM",iv:S(h),additionalData:S(b),tagLength:128},F,S(C));return new TextDecoder().decode(new Uint8Array(g))}catch(F){l=F}throw Error(`Failed to decrypt ciphertext: ${l instanceof Error?l.message:String(l??"unknown")}`)},async hash(y){let o=y.kid??t.activeKid,a=await f(o),h=await crypto.subtle.sign("HMAC",a,S(new TextEncoder().encode(y.value)));return rn(h)},mask(y){return X()(y.value)}}}function on(){return{encrypt(t){return{ciphertext:JSON.stringify({v:1,alg:"NOOP",kid:"noop",iv:"",tag:"",ct:t.value})}},decrypt(t){try{return St(t.ciphertext).ct}catch{return t.ciphertext}},hash(t){let n=bt(t.value);return U(new TextEncoder().encode(n))},mask(t){return X()(t.value)}}}function cn(t){return pn(t)}var ut;((r)=>{r.DEBUG="DEBUG";r.INFO="INFO";r.WARN="WARN";r.ERROR="ERROR"})(ut||={});var an=["to","from","phone","phoneNumber","recipient","sender","secret","apiKey","apiSecret","authorization","auth","token","password","payload","message","content","text"];function dn(t){let n=t.toLowerCase();return an.some((e)=>n.includes(e.toLowerCase()))}function ln(t){let n=t.trim();if(n.length<=4)return"***";if(n.includes("@")){let[r,s]=n.split("@");return`${r.slice(0,2)}${"*".repeat(Math.max(1,r.length-2))}@${s}`}let e=n.slice(0,3),i=n.slice(-2);return`${e}${"*".repeat(Math.max(1,n.length-5))}${i}`}function z(t,n){if(n===void 0||n===null)return n;if(dn(t)){if(typeof n==="string")return ln(n);if(typeof n==="number"||typeof n==="boolean")return"***";if(Array.isArray(n))return"[REDACTED]";if(typeof n==="object")return"[REDACTED]"}if(Array.isArray(n))return n.map((e)=>z(t,e));if(typeof n==="object"){let e={};for(let[i,r]of Object.entries(n))e[i]=z(i,r);return e}return n}function hn(t){let n={};for(let[e,i]of Object.entries(t))n[e]=z(e,i);return n}class ${config;context;constructor(t={},n={}){this.context=t,this.config={level:"INFO",enableConsole:!0,enableJson:!1,enableColors:!0,...n}}shouldLog(t){let n=["DEBUG","INFO","WARN","ERROR"];return n.indexOf(t)>=n.indexOf(this.config.level)}formatMessage(t){let n=hn(t.context);if(this.config.enableJson)return JSON.stringify({level:t.level,message:t.message,timestamp:t.timestamp.toISOString(),context:n,...t.error&&{error:{name:t.error.name,message:t.error.message,stack:t.error.stack}},...t.duration&&{duration:t.duration}});let e=t.timestamp.toISOString(),i=this.config.enableColors?this.colorizeLevel(t.level):t.level,r=Object.keys(n).length>0?` [${Object.entries(n).map(([p,f])=>`${p}=${f}`).join(", ")}]`:"",s=`${e} ${i}${r}: ${t.message}`;if(t.duration!==void 0)s+=` (${t.duration}ms)`;if(t.error)s+=`
2
+ ${t.error.stack}`;return s}colorizeLevel(t){if(!this.config.enableColors)return t;return`${{["DEBUG"]:"\x1B[36m",["INFO"]:"\x1B[32m",["WARN"]:"\x1B[33m",["ERROR"]:"\x1B[31m"}[t]}${t}\x1B[0m`}writeLog(t){if(!this.shouldLog(t.level))return;let n=this.formatMessage(t);if(this.config.enableConsole)(t.level==="ERROR"?console.error:t.level==="WARN"?console.warn:console.log)(n);if(this.config.enableFile&&this.config.filePath);}debug(t,n={}){this.writeLog({level:"DEBUG",message:t,timestamp:new Date,context:{...this.context,...n}})}info(t,n={}){this.writeLog({level:"INFO",message:t,timestamp:new Date,context:{...this.context,...n}})}warn(t,n={},e){this.writeLog({level:"WARN",message:t,timestamp:new Date,context:{...this.context,...n},error:e})}error(t,n={},e){this.writeLog({level:"ERROR",message:t,timestamp:new Date,context:{...this.context,...n},error:e})}child(t){return new $({...this.context,...t},this.config)}time(t){let n=Date.now();return()=>{let e=Date.now()-n;this.info(`${t} completed`,{duration:e})}}async measure(t,n,e={}){let i=Date.now(),r={...e,operation:t};this.debug(`Starting ${t}`,r);try{let s=await n(),p=Date.now()-i;return this.info(`Completed ${t}`,{...r,duration:p}),s}catch(s){let p=Date.now()-i;throw this.error(`Failed ${t}`,{...r,duration:p},s instanceof Error?s:Error(String(s))),s}}}var q;function tt(t,n){return new $(t,n)}function k(){if(!q)q=tt();return q}function gn(t){q=t}var Kn={debug:(t,n)=>k().debug(t,n),info:(t,n)=>k().info(t,n),warn:(t,n,e)=>k().warn(t,n,e),error:(t,n,e)=>k().error(t,n,e),child:(t)=>k().child(t),time:(t)=>k().time(t),measure:(t,n,e)=>k().measure(t,n,e)};function Cn(t){let n=tt({},t);return async(e,i)=>{let r=Date.now(),p={requestId:Math.random().toString(36).substring(7),method:e.req.method,path:e.req.path,userAgent:e.req.header("user-agent")||"unknown"};n.info("Request started",p);try{await i();let f=Date.now()-r;n.info("Request completed",{...p,status:e.res.status,duration:f})}catch(f){let y=Date.now()-r;throw n.error("Request failed",{...p,duration:y},f instanceof Error?f:Error(String(f))),f}}}class T{static defaultOptions={maxAttempts:3,initialDelay:1000,maxDelay:30000,backoffMultiplier:2,jitter:!0,retryCondition:(t)=>O.isRetryable(t)};static async execute(t,n={}){let e={...T.defaultOptions,...n},i,r=e.initialDelay;for(let s=1;s<=e.maxAttempts;s++)try{return await t()}catch(p){if(i=p,s===e.maxAttempts||!e.retryCondition(i,s))throw i;let f=e.jitter?r+Math.random()*r*0.1:r;e.onRetry?.(i,s),await new Promise((y)=>setTimeout(y,f)),r=Math.min(r*e.backoffMultiplier,e.maxDelay)}throw i}static createRetryableFunction(t,n={}){return async(...e)=>{return T.execute(()=>t(...e),n)}}}class H{static async execute(t,n,e={}){let i={concurrency:5,retryOptions:{maxAttempts:3,initialDelay:1000,maxDelay:1e4,backoffMultiplier:2,jitter:!0},failFast:!1,...e},r=Date.now(),s=[],p=[],f=0,y=T.createRetryableFunction(n,i.retryOptions),o=H.createBatches(t,i.concurrency);for(let h of o){let d=h.map(async(A)=>{try{let C=await y(A);s.push({item:A,result:C})}catch(C){if(p.push({item:A,error:C}),i.failFast)throw new K("MESSAGE_SEND_FAILED",`Bulk operation failed fast after ${p.length} failures`,{totalItems:t.length,failedCount:p.length})}finally{f++,i.onProgress?.(f,t.length,p.length)}});if(await Promise.allSettled(d),i.failFast&&p.length>0)break}let a=Date.now()-r;return{successful:s,failed:p,summary:{total:t.length,successful:s.length,failed:p.length,duration:a}}}static createBatches(t,n){let e=[];for(let i=0;i<t.length;i+=n)e.push(t.slice(i,i+n));return e}}class nt{options;state="CLOSED";failureCount=0;lastFailureTime=0;nextAttemptTime=0;constructor(t){this.options=t}async execute(t){let n=Date.now();switch(this.state){case"OPEN":if(n<this.nextAttemptTime)throw new K("NETWORK_SERVICE_UNAVAILABLE","Circuit breaker is OPEN",{state:this.state,nextAttemptTime:this.nextAttemptTime});this.state="HALF_OPEN",this.options.onHalfOpen?.();break;case"HALF_OPEN":break;case"CLOSED":break}try{let e=await Promise.race([t(),new Promise((i,r)=>setTimeout(()=>r(new K("NETWORK_TIMEOUT","Circuit breaker timeout",{timeout:this.options.timeout})),this.options.timeout))]);if(this.state==="HALF_OPEN")this.state="CLOSED",this.failureCount=0,this.options.onClose?.();return e}catch(e){throw this.recordFailure(),e}}recordFailure(){if(this.failureCount++,this.lastFailureTime=Date.now(),this.failureCount>=this.options.failureThreshold)this.state="OPEN",this.nextAttemptTime=this.lastFailureTime+this.options.resetTimeout,this.options.onOpen?.()}getState(){return this.state}getFailureCount(){return this.failureCount}reset(){this.state="CLOSED",this.failureCount=0,this.lastFailureTime=0,this.nextAttemptTime=0}}class et{maxRequests;windowMs;requests=[];constructor(t,n){this.maxRequests=t;this.windowMs=n}async acquire(){let t=Date.now();if(this.requests=this.requests.filter((n)=>t-n<this.windowMs),this.requests.length>=this.maxRequests){let n=Math.min(...this.requests),e=this.windowMs-(t-n);if(e>0)return await new Promise((i)=>setTimeout(i,e)),this.acquire()}this.requests.push(t)}canMakeRequest(){let t=Date.now();return this.requests=this.requests.filter((n)=>t-n<this.windowMs),this.requests.length<this.maxRequests}getRemainingRequests(){let t=Date.now();return this.requests=this.requests.filter((n)=>t-n<this.windowMs),Math.max(0,this.maxRequests-this.requests.length)}}var it=(t)=>({isSuccess:!0,isFailure:!1,value:t}),st=(t)=>({isSuccess:!1,isFailure:!0,error:t}),Fn={map(t,n){if(t.isSuccess)return it(n(t.value));return t},flatMap(t,n){if(t.isSuccess)return n(t.value);return t},mapError(t,n){if(t.isFailure)return st(n(t.error));return t},unwrap(t){if(t.isSuccess)return t.value;throw t.error},unwrapOr(t,n){if(t.isSuccess)return t.value;return n},unwrapOrElse(t,n){if(t.isSuccess)return t.value;return n(t.error)},match(t,n){if(t.isSuccess)return n.ok(t.value);return n.fail(t.error)},async fromPromise(t){try{let n=await t;return it(n)}catch(n){return st(n)}},isOk(t){return t.isSuccess},isFail(t){return t.isFailure},tap(t,n){return n(t),t},tapOk(t,n){if(t.isSuccess)n(t.value);return t},tapErr(t,n){if(t.isFailure)n(t.error);return t},expect(t,n){if(t.isSuccess)return t.value;throw Error(n,{cause:t.error})}};function Dt(){let t=globalThis;return t.__K_MSG_ENV__??t.__ENV__??t.process?.env??{}}function An(t){let n=Dt()[t];if(typeof n==="string")return n;if(n===void 0)return;return String(n)}var kt=["PENDING","SENT","DELIVERED","FAILED","CANCELLED","UNKNOWN"],mt=["DELIVERED","FAILED","CANCELLED","UNKNOWN"],rt=["PENDING","SENT"],Pn=new Set(kt),Tt=new Set(mt),wn=new Set(rt);function Sn(t){return Pn.has(t)}function bn(t){return Tt.has(t)}function un(t){return Tt.has(t)}function Dn(t){return wn.has(t)}function kn(){return rt}var Ot=["ALIMTALK","FRIENDTALK","SMS","LMS","MMS","NSA","VOICE","FAX","RCS_SMS","RCS_LMS","RCS_MMS","RCS_TPL","RCS_ITPL","RCS_LTPL"],mn=new Set(Ot);function Tn(t){return mn.has(t)}var On=["PENDING","SENT","FAILED"],Rt="PENDING",Rn=(t)=>{let n=typeof t==="string"?t.trim().toUpperCase():"";if(n==="PENDING"||n==="SENT"||n==="FAILED")return n;return Rt};
3
3
 
4
- //# debugId=E16D0DFAC995D1EC64756E2164756E21
4
+ //# debugId=A5BAB2911583302264756E2164756E21
5
5
  //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@k-msg/core",
3
- "version": "0.29.7",
4
- "packageManager": "bun@1.3.11",
3
+ "version": "0.29.9",
4
+ "packageManager": "bun@1.3.9",
5
5
  "description": "Core types and interfaces for K-Message platform",
6
6
  "type": "module",
7
7
  "main": "./dist/index.js",
@@ -30,17 +30,18 @@
30
30
  "test:e2e": "bun test --testPathPattern='.*\\.e2e\\.(ts|js)$' --testTimeout=30000",
31
31
  "test:coverage": "bun test --coverage",
32
32
  "test:watch": "bun test --watch",
33
- "typecheck": "tsc --noEmit",
33
+ "typecheck": "ttsc --noEmit",
34
34
  "clean": "rm -rf dist tsconfig.tsbuildinfo",
35
35
  "pack": "bun pm pack",
36
36
  "publish": "bun publish --access public"
37
37
  },
38
38
  "dependencies": {
39
- "zod": "^4.0.14"
39
+ "zod": "^4.4.3"
40
40
  },
41
41
  "devDependencies": {
42
42
  "@types/bun": "^1.3.14",
43
- "typescript": "^6.0.3"
43
+ "ttsc": "^0.18.4",
44
+ "typescript": "^7.0.2"
44
45
  },
45
46
  "peerDependencies": {},
46
47
  "files": [