@nocios/crudify-ui 4.4.72 → 4.4.74
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-ZANWILS7.mjs → chunk-2RQAIPFB.mjs} +1 -1
- package/dist/{chunk-SEDLJT7G.js → chunk-4Z2XAMJA.js} +1 -1
- package/dist/{chunk-Q5EJLSB4.mjs → chunk-7X3OJMPH.mjs} +1 -1
- package/dist/{chunk-YLKGZV2N.js → chunk-EXXKBYWY.js} +1 -1
- package/dist/{chunk-LPC6P3Z7.mjs → chunk-ML7JNB3X.mjs} +1 -1
- package/dist/{chunk-L454VIXN.js → chunk-N6OQJOCM.js} +1 -1
- package/dist/chunk-NXXCVAVE.js +1 -0
- package/dist/chunk-PK2UX3UH.mjs +1 -0
- package/dist/{chunk-JCMHUFYK.mjs → chunk-RPYFDF5Q.mjs} +1 -1
- package/dist/{chunk-4LSVF26Q.js → chunk-YLCEL2HE.js} +1 -1
- package/dist/components.js +1 -1
- package/dist/components.mjs +1 -1
- package/dist/hooks.js +1 -1
- package/dist/hooks.mjs +1 -1
- package/dist/index.d.mts +92 -1
- package/dist/index.d.ts +92 -1
- package/dist/index.js +2 -2
- package/dist/index.mjs +2 -2
- package/dist/utils.d.mts +8 -1
- package/dist/utils.d.ts +8 -1
- package/dist/utils.js +1 -1
- package/dist/utils.mjs +1 -1
- package/package.json +1 -1
- package/dist/chunk-UJD6SL66.mjs +0 -1
- package/dist/chunk-X3JFRSEA.js +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{a as V,b as _,c as B,d as H,e as q,f as W,g as J,h as ye,i as xe,j as Ce,k as Pe,l as Re,m as Ie,n as he,o as ve,p as Me,q as ze}from"./chunk-
|
|
1
|
+
import{a as V,b as _,c as B,d as H,e as q,f as W,g as J,h as ye,i as xe,j as Ce,k as Pe,l as Re,m as Ie,n as he,o as ve,p as Me,q as ze}from"./chunk-7X3OJMPH.mjs";import{a as ke,b as Le,c as be,d as Fe}from"./chunk-ML7JNB3X.mjs";import{a as k,b as $,c as Y,d as Z,e as f,f as re,g as ne,h as se,i as ae,j as m,k as pe,l as Ae,m as Se,n as Te,o as R,p as Ee}from"./chunk-RPYFDF5Q.mjs";import{a as we,b as Ue}from"./chunk-2RQAIPFB.mjs";import{a as ce,b as de,c as ue,d as le,e as fe,f as me,g as ge}from"./chunk-BJ6PIVZR.mjs";import{a as s,b as v,c as z,e as Q,f as X,g as j,h as ee,k as oe,l as te,m as ie}from"./chunk-PK2UX3UH.mjs";import{default as Zr}from"@nocios/crudify-browser";export*from"@nocios/crudify-browser";import{useMemo as Oe}from"react";import{ThemeProvider as Ne,createTheme as De,CssBaseline as Ge}from"@mui/material";import{jsx as _e,jsxs as Be}from"react/jsx-runtime";var Ke=(e={})=>{try{let r=v("theme");if(r){let o=JSON.parse(decodeURIComponent(r));return{...e,...o}}}catch(r){s.warn("Error parsing theme from cookie",r instanceof Error?{errorMessage:r.message}:{message:String(r)})}return e};function Ve({children:e,defaultTheme:r={},disableCssBaseline:o=!1}){let t=Oe(()=>{let a=Ke(r);return De(a)},[r]);return Be(Ne,{theme:t,children:[!o&&_e(Ge,{}),e]})}import{Navigate as Ye,useLocation as Ze}from"react-router-dom";import{Fragment as We,jsx as I,jsxs as L}from"react/jsx-runtime";var He={border:"5px solid rgba(0, 0, 0, 0.1)",borderTopColor:"#3B82F6",borderRadius:"50%",width:"50px",height:"50px",animation:"spin 1s linear infinite"},qe=()=>I("style",{children:`
|
|
2
2
|
@keyframes spin {
|
|
3
3
|
0% { transform: rotate(0deg); }
|
|
4
4
|
100% { transform: rotate(360deg); }
|
|
5
5
|
}
|
|
6
|
-
`});function T({stage:e="loading",message:r}){let t=r||{initializing:"Initializing application...","validating-session":"Validating session...",loading:"Loading..."}[e];return
|
|
6
|
+
`});function T({stage:e="loading",message:r}){let t=r||{initializing:"Initializing application...","validating-session":"Validating session...",loading:"Loading..."}[e];return L(We,{children:[I(qe,{}),L("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100vh",width:"100vw",backgroundColor:"#f0f2f5",fontFamily:'"Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',color:"#333",textAlign:"center",boxSizing:"border-box",padding:"20px",background:"#fff"},children:[I("div",{style:He}),I("p",{style:{fontSize:"1.25em",fontWeight:"500",marginTop:"24px",color:"#1f2937"},children:t})]})]})}var Je=/^[a-zA-Z0-9\-_./\?=&%#]+$/,$e=[/^https?:\/\//i,/^ftp:\/\//i,/^\/\//,/javascript:/i,/data:/i,/vbscript:/i,/about:/i,/\.\.\//,/\.\.\\/,/%2e%2e%2f/i,/%2e%2e%5c/i,/%2f%2f/i,/%5c%5c/i,/[\x00-\x1f\x7f-\x9f]/,/\\/],h=(e,r="/")=>{if(!e||typeof e!="string")return r;let o=e.trim();if(!o)return r;if(!o.startsWith("/"))return s.warn("Open redirect blocked (relative path)",{path:e}),r;if(!Je.test(o))return s.warn("Open redirect blocked (invalid characters)",{path:e}),r;let t=o.toLowerCase();for(let p of $e)if(p.test(t))return s.warn("Open redirect blocked (dangerous pattern)",{path:e}),r;let a=o.split("?")[0].split("/").filter(Boolean);if(a.length===0)return o;for(let p of a)if(p===".."||p.includes(":")||p.length>100)return s.warn("Open redirect blocked (suspicious path part)",{part:p}),r;return o},E=(e,r="/")=>{try{let t=(typeof e=="string"?new URLSearchParams(e):e).get("redirect");if(!t)return r;let a=decodeURIComponent(t);return h(a,r)}catch(o){return s.warn("Error parsing redirect parameter",o instanceof Error?{errorMessage:o.message}:{message:String(o)}),r}};import{Fragment as b,jsx as S}from"react/jsx-runtime";function w({children:e,loadingComponent:r,loginPath:o="/login"}){let{isAuthenticated:t,isLoading:a,isInitialized:p,tokens:d,error:y}=m(),u=Ze();if(!p||a)return S(b,{children:r||S(T,{stage:"validating-session"})});let l=t&&d?.accessToken&&d.accessToken.length>0;if(y||!t||!l){d&&(!d.accessToken||d.accessToken.length===0)&&localStorage.removeItem("crudify_tokens");let A=u.pathname+u.search,x=h(A),C=encodeURIComponent(x);return S(Ye,{to:`${o}?redirect=${C}`,replace:!0})}return S(b,{children:e})}import{Navigate as Qe,useLocation as Xe}from"react-router-dom";import{Fragment as je,jsx as U}from"react/jsx-runtime";function F({children:e,redirectTo:r="/"}){let{isAuthenticated:o}=m(),t=Xe();if(o){let a=new URLSearchParams(t.search),p=E(a,r);return U(Qe,{to:p,replace:!0})}return U(je,{children:e})}import{createContext as er,useContext as rr,useEffect as or,useRef as O,useState as M}from"react";import{Fragment as nr,jsx as N}from"react/jsx-runtime";var D=er(void 0),tr=({config:e,children:r,fallback:o=null,onInitialized:t,onError:a})=>{let[p,d]=M(!1),[y,u]=M(!1),[l,A]=M(null),x=O(!1),C=O(!1);or(()=>{x.current||(R.registerHighPriorityInitializer(),x.current=!0),C.current||(C.current=!0,(async()=>{u(!0),A(null);try{let c=z({publicApiKey:e?.publicApiKey,env:e?.env,enableDebug:e?.enableLogging});if(!c.publicApiKey)throw new Error("Crudify configuration missing. Please provide publicApiKey via props or ensure cookies are set by Lambda.");let P=c.env||"prod";s.setEnvironment(P),await R.initialize({priority:"HIGH",publicApiKey:c.publicApiKey,env:c.env||"prod",enableLogging:e?.enableLogging,requestedBy:"CrudifyInitializer"}),d(!0),u(!1),t&&t()}catch(c){let P=c instanceof Error?c:new Error(String(c));A(P),u(!1),a&&a(P)}})())},[e?.publicApiKey,e?.env,e?.enableLogging,t,a]);let K={isInitialized:p,isInitializing:y,error:l};return y&&o?N(nr,{children:o}):(l&&s.error("[CrudifyInitializer] Initialization failed",l),N(D.Provider,{value:K,children:r}))},ir=()=>{let e=rr(D);if(!e)throw new Error("useCrudifyInitializer must be used within CrudifyInitializer");return e};import i from"@nocios/crudify-admin";var G=!1,g=null;async function sr(){let r=f.getInstance().getTokenInfo(),o=r?.apiEndpointAdmin,t=r?.apiKeyEndpointAdmin;return o&&t?{apiUrl:o,apiKey:t}:k.waitForCredentials()}async function ar(){if(!G)return g||(g=(async()=>{try{let e=f.getInstance(),{apiUrl:r,apiKey:o}=await sr();i.init({url:r,apiKey:o,getAdditionalHeaders:()=>{let t=e.getTokenInfo();return t?.crudifyTokens?.accessToken?{Authorization:`Bearer ${t.crudifyTokens.accessToken}`}:{}}}),G=!0}catch(e){throw g=null,s.error("[crudifyAdminWrapper] Initialization failed",e instanceof Error?e:{message:String(e)}),e}})(),g)}async function n(e){try{await ar();let r=await e();return!r.success&&r.errors?.includes("401")?await f.getInstance().refreshTokens()?await e():(s.error("[crudifyAdmin] Token refresh failed"),typeof window<"u"&&(window.location.href="/login"),r):r}catch(r){return s.error("[crudifyAdmin] Operation error",r instanceof Error?r:{message:String(r)}),{success:!1,errors:r instanceof Error?r.message:"Unknown error"}}}var pr={listModules:()=>n(()=>i.listModules()),getModule:e=>n(()=>i.getModule(e)),createModule:e=>n(()=>i.createModule(e)),editModule:(e,r)=>n(()=>i.editModule(e,r)),deleteModule:e=>n(()=>i.deleteModule(e)),activateModule:e=>n(()=>i.activateModule(e)),deactivateModule:e=>n(()=>i.deactivateModule(e)),getModuleVersions:e=>n(()=>i.getModuleVersions(e)),listActions:e=>n(()=>i.listActions(e)),getAction:e=>n(()=>i.getAction(e)),createAction:e=>n(()=>i.createAction(e)),editAction:(e,r)=>n(()=>i.editAction(e,r)),deleteAction:e=>n(()=>i.deleteAction(e)),activateAction:e=>n(()=>i.activateAction(e)),deactivateAction:e=>n(()=>i.deactivateAction(e)),getActionVersions:e=>n(()=>i.getActionVersions(e)),getActionsByProfile:e=>n(()=>i.getActionsByProfile(e)),updateActionsProfiles:e=>n(()=>i.updateActionsProfiles(e))};export{F as AuthRoute,V as CRITICAL_TRANSLATIONS,ve as CrudiaAutoGenerate,Me as CrudiaFileField,ze as CrudiaMarkdownField,Te as CrudifyInitializationManager,tr as CrudifyInitializer,ye as CrudifyLogin,$ as CrudifyProvider,Ve as CrudifyThemeProvider,ce as ERROR_CODES,de as ERROR_SEVERITY_MAP,ne as GlobalNotificationProvider,Ie as LoginComponent,Ce as POLICY_ACTIONS,Pe as PREFERRED_POLICY_ORDER,Re as Policies,w as ProtectedRoute,pe as SessionDebugInfo,T as SessionLoadingScreen,f as SessionManager,ae as SessionProvider,he as SessionStatus,Z as TokenStorage,H as TranslationService,W as TranslationsProvider,xe as UserProfileDisplay,ee as createErrorTranslator,Zr as crudify,pr as crudifyAdmin,R as crudifyInitManager,oe as decodeJwtSafely,E as extractSafeRedirectFromUrl,v as getCookie,_ as getCriticalLanguages,B as getCriticalTranslations,te as getCurrentUserEmail,fe as getErrorMessage,ge as handleCrudifyError,ie as isTokenExpired,s as logger,ue as parseApiError,me as parseJavaScriptError,le as parseTransactionError,Ue as secureLocalStorage,we as secureSessionStorage,j as translateError,Q as translateErrorCode,X as translateErrorCodes,q as translationService,Le as useAuth,Se as useAutoGenerate,Y as useCrudify,ir as useCrudifyInitializer,Fe as useCrudifyWithNotifications,be as useData,Ee as useFileUpload,se as useGlobalNotification,re as useSession,m as useSessionContext,J as useTranslations,ke as useUserData,Ae as useUserProfile,h as validateInternalRedirect};
|
package/dist/utils.d.mts
CHANGED
|
@@ -3,7 +3,14 @@ import './api-Djqihi4n.mjs';
|
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Sistema centralizado de resolución de configuración para npm-crudify-ui
|
|
6
|
-
*
|
|
6
|
+
*
|
|
7
|
+
* Prioridad:
|
|
8
|
+
* 1. Cookies (producción con Lambda@Edge multitenancy) - MAYOR PRIORIDAD
|
|
9
|
+
* 2. Props explícitas (desarrollo local con .env) - FALLBACK
|
|
10
|
+
* 3. Error (ninguna configuración disponible)
|
|
11
|
+
*
|
|
12
|
+
* En producción, Lambda@Edge inyecta cookies con la configuración del tenant.
|
|
13
|
+
* En desarrollo local, no hay cookies y se usan las variables de .env como fallback.
|
|
7
14
|
*/
|
|
8
15
|
type CrudifyEnvironment = "dev" | "stg" | "api" | "prod";
|
|
9
16
|
interface ResolvedConfig {
|
package/dist/utils.d.ts
CHANGED
|
@@ -3,7 +3,14 @@ import './api-Djqihi4n.js';
|
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Sistema centralizado de resolución de configuración para npm-crudify-ui
|
|
6
|
-
*
|
|
6
|
+
*
|
|
7
|
+
* Prioridad:
|
|
8
|
+
* 1. Cookies (producción con Lambda@Edge multitenancy) - MAYOR PRIORIDAD
|
|
9
|
+
* 2. Props explícitas (desarrollo local con .env) - FALLBACK
|
|
10
|
+
* 3. Error (ninguna configuración disponible)
|
|
11
|
+
*
|
|
12
|
+
* En producción, Lambda@Edge inyecta cookies con la configuración del tenant.
|
|
13
|
+
* En desarrollo local, no hay cookies y se usan las variables de .env como fallback.
|
|
7
14
|
*/
|
|
8
15
|
type CrudifyEnvironment = "dev" | "stg" | "api" | "prod";
|
|
9
16
|
interface ResolvedConfig {
|
package/dist/utils.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkYLCEL2HEjs = require('./chunk-YLCEL2HE.js');var _chunkYIIUEOXCjs = require('./chunk-YIIUEOXC.js');var _chunkNXXCVAVEjs = require('./chunk-NXXCVAVE.js');exports.ERROR_CODES = _chunkYIIUEOXCjs.a; exports.ERROR_SEVERITY_MAP = _chunkYIIUEOXCjs.b; exports.NavigationTracker = _chunkNXXCVAVEjs.j; exports.authEventBus = _chunkNXXCVAVEjs.i; exports.createErrorTranslator = _chunkNXXCVAVEjs.h; exports.decodeJwtSafely = _chunkNXXCVAVEjs.k; exports.getCookie = _chunkNXXCVAVEjs.b; exports.getCurrentUserEmail = _chunkNXXCVAVEjs.l; exports.getErrorMessage = _chunkYIIUEOXCjs.e; exports.handleCrudifyError = _chunkYIIUEOXCjs.g; exports.isTokenExpired = _chunkNXXCVAVEjs.m; exports.parseApiError = _chunkYIIUEOXCjs.c; exports.parseJavaScriptError = _chunkYIIUEOXCjs.f; exports.parseTransactionError = _chunkYIIUEOXCjs.d; exports.resolveConfig = _chunkNXXCVAVEjs.c; exports.secureLocalStorage = _chunkYLCEL2HEjs.b; exports.secureSessionStorage = _chunkYLCEL2HEjs.a; exports.translateError = _chunkNXXCVAVEjs.g; exports.translateErrorCode = _chunkNXXCVAVEjs.e; exports.translateErrorCodes = _chunkNXXCVAVEjs.f; exports.useResolvedConfig = _chunkNXXCVAVEjs.d;
|
package/dist/utils.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as R,b as c}from"./chunk-
|
|
1
|
+
import{a as R,b as c}from"./chunk-2RQAIPFB.mjs";import{a as m,b as v,c as d,d as g,e as u,f as x,g as C}from"./chunk-BJ6PIVZR.mjs";import{b as r,c as e,d as o,e as t,f as a,g as n,h as s,i as E,j as i,k as p,l as f,m as l}from"./chunk-PK2UX3UH.mjs";export{m as ERROR_CODES,v as ERROR_SEVERITY_MAP,i as NavigationTracker,E as authEventBus,s as createErrorTranslator,p as decodeJwtSafely,r as getCookie,f as getCurrentUserEmail,u as getErrorMessage,C as handleCrudifyError,l as isTokenExpired,d as parseApiError,x as parseJavaScriptError,g as parseTransactionError,e as resolveConfig,c as secureLocalStorage,R as secureSessionStorage,n as translateError,t as translateErrorCode,a as translateErrorCodes,o as useResolvedConfig};
|
package/package.json
CHANGED
package/dist/chunk-UJD6SL66.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var p=r=>{let e=document.cookie.match(new RegExp("(^|;)\\s*"+r+"=([^;]+)"));return e?e[2]:null};var C=[/password[^:]*[:=]\s*[^\s,}]+/gi,/token[^:]*[:=]\s*[^\s,}]+/gi,/key[^:]*[:=]\s*["']?[^\s,}"']+/gi,/secret[^:]*[:=]\s*[^\s,}]+/gi,/authorization[^:]*[:=]\s*[^\s,}]+/gi,/mongodb(\+srv)?:\/\/[^\s]+/gi,/postgres:\/\/[^\s]+/gi,/mysql:\/\/[^\s]+/gi],A="prod",S="CrudifyUI",v=class{constructor(){this.env=A,this.prefix=S}sanitize(e){let t=e;for(let n of C)t=t.replace(n,"[REDACTED]");return t}sanitizeContext(e){let t={};for(let[n,o]of Object.entries(e))if(o!=null)if(n==="userId"&&typeof o=="string")t[n]=o.length>8?`${o.substring(0,8)}***`:o;else if(n==="email"&&typeof o=="string"){let[s,l]=o.split("@");t[n]=s&&l?`${s.substring(0,3)}***@${l}`:"[REDACTED]"}else typeof o=="string"?t[n]=this.sanitize(o):typeof o=="object"&&o!==null?t[n]=this.sanitizeContext(o):t[n]=o;return t}shouldLog(e){return!((this.env==="prod"||this.env==="production"||this.env==="api")&&e!=="error")}log(e,t,n){if(!this.shouldLog(e))return;let o=this.sanitize(t),s=n?this.sanitizeContext(n):void 0,l={timestamp:new Date().toISOString(),level:e,environment:this.env,service:this.prefix,message:o,...s&&Object.keys(s).length>0&&{context:s}},u=JSON.stringify(l);switch(e){case"error":console.error(u);break;case"warn":console.warn(u);break;case"info":console.info(u);break;case"debug":console.log(u);break}}error(e,t){let n;t instanceof Error?n={errorName:t.name,errorMessage:t.message,stack:t.stack}:n=t,this.log("error",e,n)}warn(e,t){this.log("warn",e,t)}info(e,t){this.log("info",e,t)}debug(e,t){this.log("debug",e,t)}getEnvironment(){return this.env}setEnvironment(e){this.env=e,A=e}},i=new v;function O(r={}){let{publicApiKey:e,env:t,appName:n,logo:o,loginActions:s,featureKeys:l,enableDebug:u=!1}=r,c={configSource:"none"},h=p("publicApiKey");if(h){let a=p("environment"),d=p("appName"),y=p("logo"),R=p("loginActions"),T=p("featureKeys"),I=p("theme");return c={publicApiKey:decodeURIComponent(h),env:a&&["dev","stg","api","prod"].includes(a)?a:"prod",appName:d?decodeURIComponent(d):void 0,logo:y?decodeURIComponent(y):void 0,loginActions:R?decodeURIComponent(R).split(",").map(f=>f.trim()).filter(Boolean):void 0,featureKeys:T?decodeURIComponent(T).split(",").map(f=>f.trim()).filter(Boolean):void 0,theme:I?(()=>{try{return JSON.parse(decodeURIComponent(I))}catch(f){u&&i.warn("[ConfigResolver] Failed to parse theme cookie",f instanceof Error?{errorMessage:f.message}:{message:String(f)});return}})():void 0,configSource:"cookies"},u&&typeof window<"u"&&(window.__CRUDIFY_RESOLVED_CONFIG=c),c}return e&&(c={publicApiKey:e,env:t||"prod",appName:n,logo:o,loginActions:s,featureKeys:l,configSource:"props"},u&&typeof window<"u"&&(window.__CRUDIFY_RESOLVED_CONFIG=c)),c}function K(r={}){return O(r)}var w=["errors.{category}.{code}","errors.{code}","login.{code}","error.{code}","messages.{code}","{code}"],D={INVALID_CREDENTIALS:"auth",UNAUTHORIZED:"auth",INVALID_API_KEY:"auth",USER_NOT_FOUND:"auth",USER_NOT_ACTIVE:"auth",NO_PERMISSION:"auth",SESSION_EXPIRED:"auth",ITEM_NOT_FOUND:"data",NOT_FOUND:"data",IN_USE:"data",DUPLICATE_ENTRY:"data",FIELD_ERROR:"validation",BAD_REQUEST:"validation",INVALID_EMAIL:"validation",INVALID_CODE:"validation",REQUIRED_FIELD:"validation",INTERNAL_SERVER_ERROR:"system",DATABASE_CONNECTION_ERROR:"system",INVALID_CONFIGURATION:"system",UNKNOWN_OPERATION:"system",TIMEOUT_ERROR:"system",NETWORK_ERROR:"system",TOO_MANY_REQUESTS:"rate_limit"},L={INVALID_CREDENTIALS:"Invalid username or password",UNAUTHORIZED:"You are not authorized to perform this action",SESSION_EXPIRED:"Your session has expired. Please log in again.",USER_NOT_FOUND:"User not found",ITEM_NOT_FOUND:"Item not found",FIELD_ERROR:"Invalid field value",INTERNAL_SERVER_ERROR:"An internal error occurred",NETWORK_ERROR:"Network connection error",TIMEOUT_ERROR:"Request timeout",UNKNOWN_OPERATION:"Unknown operation",INVALID_EMAIL:"Invalid email format",INVALID_CODE:"Invalid code",TOO_MANY_REQUESTS:"Too many requests, please try again later"};function E(r,e){let{translateFn:t,currentLanguage:n,enableDebug:o}=e;o&&i.debug(`[ErrorTranslation] Translating error code: ${r} (lang: ${n||"unknown"})`);let s=r.toUpperCase(),l=D[s],u=w.map(a=>a.replace("{category}",l||"general").replace("{code}",s));o&&i.debug("[ErrorTranslation] Searching keys:",{translationKeys:u});for(let a of u){let d=t(a);if(o&&i.debug(`[ErrorTranslation] Checking key: "${a}" -> result: "${d}" (same as key: ${d===a})`),d&&d!==a)return o&&i.debug(`[ErrorTranslation] Found translation at key: ${a} = "${d}"`),d}let c=L[s];if(c)return o&&i.debug(`[ErrorTranslation] Using default message: "${c}"`),c;let h=s.replace(/_/g," ").toLowerCase().replace(/\b\w/g,a=>a.toUpperCase());return o&&i.debug(`[ErrorTranslation] No translation found, using friendly code: "${h}"`),h}function _(r,e){return r.map(t=>E(t,e))}function k(r,e){let{enableDebug:t}=e;t&&i.debug("[ErrorTranslation] Translating error:",{error:r});let n=E(r.code,e);return n!==r.code.toUpperCase()&&n!==r.code?(t&&i.debug(`[ErrorTranslation] Using hierarchical translation: "${n}"`),r.field?`${r.field}: ${n}`:n):r.message&&!r.message.includes("Error:")&&r.message.length>0&&r.message!==r.code?(t&&i.debug(`[ErrorTranslation] No hierarchical translation found, using API message: "${r.message}"`),r.message):(t&&i.debug(`[ErrorTranslation] Using final fallback: "${n}"`),r.field?`${r.field}: ${n}`:n)}function V(r,e={}){let t={translateFn:r,currentLanguage:e.currentLanguage,enableDebug:e.enableDebug||!1};return{translateErrorCode:n=>E(n,t),translateErrorCodes:n=>_(n,t),translateError:n=>k(n,t),translateApiError:n=>n?.data?.response?.status?E(n.data.response.status,t):n?.status?E(n.status,t):n?.code?E(n.code,t):"Unknown error"}}var m=class r{constructor(){this.listeners=new Set;this.isHandlingAuthError=!1;this.lastErrorTime=0;this.lastEventType=null;this.DEBOUNCE_TIME=1e3}static getInstance(){return r.instance||(r.instance=new r),r.instance}emit(e,t){let n=Date.now();if(this.isHandlingAuthError&&this.lastEventType===e&&n-this.lastErrorTime<this.DEBOUNCE_TIME){i.debug(`AuthEventBus: Ignoring duplicate ${e} event (debounced)`);return}this.isHandlingAuthError=!0,this.lastErrorTime=n,this.lastEventType=e,i.debug(`AuthEventBus: Emitting ${e} event`,t?{details:t}:void 0);let o={type:e,details:t,timestamp:n};this.listeners.forEach(s=>{try{s(o)}catch(l){i.error("AuthEventBus: Error in listener",l instanceof Error?l:{message:String(l)})}}),setTimeout(()=>{this.isHandlingAuthError=!1,this.lastEventType=null},2e3)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}clear(){this.listeners.clear(),this.isHandlingAuthError=!1,this.lastEventType=null}isHandling(){return this.isHandlingAuthError}},B=m.getInstance();var g=class g{constructor(){this.isPatched=!1;this.refCount=0;this.listeners=new Set;this.originalPushState=window.history.pushState,this.originalReplaceState=window.history.replaceState}static getInstance(){return g.instance||(g.instance=new g),g.instance}subscribe(e){return this.listeners.add(e),this.refCount++,this.isPatched||this.applyPatches(),()=>{this.unsubscribe(e)}}unsubscribe(e){this.listeners.delete(e),this.refCount--,this.refCount===0&&this.isPatched&&this.removePatches()}applyPatches(){let e=this;window.history.pushState=function(...t){let n=e.originalPushState.apply(this,t);return e.notifyListeners(),n},window.history.replaceState=function(...t){let n=e.originalReplaceState.apply(this,t);return e.notifyListeners(),n},this.isPatched=!0}removePatches(){window.history.pushState=this.originalPushState,window.history.replaceState=this.originalReplaceState,this.isPatched=!1}notifyListeners(){this.listeners.forEach(e=>{try{e()}catch(t){i.error("NavigationTracker: Error in navigation listener",t instanceof Error?t:{message:String(t)})}})}static reset(){g.instance?.isPatched&&g.instance.removePatches(),g.instance=null}getSubscriberCount(){return this.refCount}isActive(){return this.isPatched}};g.instance=null;var N=g;var b=r=>{try{let e=r.split(".");if(e.length!==3)return i.warn("Invalid JWT format: token must have 3 parts"),null;let t=e[1],n=t+"=".repeat((4-t.length%4)%4);return JSON.parse(atob(n))}catch(e){return i.warn("Failed to decode JWT token",e instanceof Error?{errorMessage:e.message}:{message:String(e)}),null}},X=()=>{try{let r=null;if(r=sessionStorage.getItem("authToken"),r||(r=sessionStorage.getItem("token")),r||(r=localStorage.getItem("authToken")||localStorage.getItem("token")),!r)return null;let e=b(r);return e&&(e.email||e["cognito:username"])||null}catch(r){return i.warn("Failed to get current user email",r instanceof Error?{errorMessage:r.message}:{message:String(r)}),null}},Q=r=>{try{let e=b(r);if(!e||!e.exp)return!0;let t=Math.floor(Date.now()/1e3);return e.exp<t}catch{return!0}};export{i as a,p as b,O as c,K as d,E as e,_ as f,k as g,V as h,B as i,N as j,b as k,X as l,Q as m};
|
package/dist/chunk-X3JFRSEA.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var p=r=>{let e=document.cookie.match(new RegExp("(^|;)\\s*"+r+"=([^;]+)"));return e?e[2]:null};var C=[/password[^:]*[:=]\s*[^\s,}]+/gi,/token[^:]*[:=]\s*[^\s,}]+/gi,/key[^:]*[:=]\s*["']?[^\s,}"']+/gi,/secret[^:]*[:=]\s*[^\s,}]+/gi,/authorization[^:]*[:=]\s*[^\s,}]+/gi,/mongodb(\+srv)?:\/\/[^\s]+/gi,/postgres:\/\/[^\s]+/gi,/mysql:\/\/[^\s]+/gi],A="prod",S="CrudifyUI",v=class{constructor(){this.env=A,this.prefix=S}sanitize(e){let t=e;for(let n of C)t=t.replace(n,"[REDACTED]");return t}sanitizeContext(e){let t={};for(let[n,o]of Object.entries(e))if(o!=null)if(n==="userId"&&typeof o=="string")t[n]=o.length>8?`${o.substring(0,8)}***`:o;else if(n==="email"&&typeof o=="string"){let[s,l]=o.split("@");t[n]=s&&l?`${s.substring(0,3)}***@${l}`:"[REDACTED]"}else typeof o=="string"?t[n]=this.sanitize(o):typeof o=="object"&&o!==null?t[n]=this.sanitizeContext(o):t[n]=o;return t}shouldLog(e){return!((this.env==="prod"||this.env==="production"||this.env==="api")&&e!=="error")}log(e,t,n){if(!this.shouldLog(e))return;let o=this.sanitize(t),s=n?this.sanitizeContext(n):void 0,l={timestamp:new Date().toISOString(),level:e,environment:this.env,service:this.prefix,message:o,...s&&Object.keys(s).length>0&&{context:s}},u=JSON.stringify(l);switch(e){case"error":console.error(u);break;case"warn":console.warn(u);break;case"info":console.info(u);break;case"debug":console.log(u);break}}error(e,t){let n;t instanceof Error?n={errorName:t.name,errorMessage:t.message,stack:t.stack}:n=t,this.log("error",e,n)}warn(e,t){this.log("warn",e,t)}info(e,t){this.log("info",e,t)}debug(e,t){this.log("debug",e,t)}getEnvironment(){return this.env}setEnvironment(e){this.env=e,A=e}},i= exports.a =new v;function O(r={}){let{publicApiKey:e,env:t,appName:n,logo:o,loginActions:s,featureKeys:l,enableDebug:u=!1}=r,c={configSource:"none"},h=p("publicApiKey");if(h){let a=p("environment"),d=p("appName"),y=p("logo"),R=p("loginActions"),T=p("featureKeys"),I=p("theme");return c={publicApiKey:decodeURIComponent(h),env:a&&["dev","stg","api","prod"].includes(a)?a:"prod",appName:d?decodeURIComponent(d):void 0,logo:y?decodeURIComponent(y):void 0,loginActions:R?decodeURIComponent(R).split(",").map(f=>f.trim()).filter(Boolean):void 0,featureKeys:T?decodeURIComponent(T).split(",").map(f=>f.trim()).filter(Boolean):void 0,theme:I?(()=>{try{return JSON.parse(decodeURIComponent(I))}catch(f){u&&i.warn("[ConfigResolver] Failed to parse theme cookie",f instanceof Error?{errorMessage:f.message}:{message:String(f)});return}})():void 0,configSource:"cookies"},u&&typeof window<"u"&&(window.__CRUDIFY_RESOLVED_CONFIG=c),c}return e&&(c={publicApiKey:e,env:t||"prod",appName:n,logo:o,loginActions:s,featureKeys:l,configSource:"props"},u&&typeof window<"u"&&(window.__CRUDIFY_RESOLVED_CONFIG=c)),c}function K(r={}){return O(r)}var w=["errors.{category}.{code}","errors.{code}","login.{code}","error.{code}","messages.{code}","{code}"],D={INVALID_CREDENTIALS:"auth",UNAUTHORIZED:"auth",INVALID_API_KEY:"auth",USER_NOT_FOUND:"auth",USER_NOT_ACTIVE:"auth",NO_PERMISSION:"auth",SESSION_EXPIRED:"auth",ITEM_NOT_FOUND:"data",NOT_FOUND:"data",IN_USE:"data",DUPLICATE_ENTRY:"data",FIELD_ERROR:"validation",BAD_REQUEST:"validation",INVALID_EMAIL:"validation",INVALID_CODE:"validation",REQUIRED_FIELD:"validation",INTERNAL_SERVER_ERROR:"system",DATABASE_CONNECTION_ERROR:"system",INVALID_CONFIGURATION:"system",UNKNOWN_OPERATION:"system",TIMEOUT_ERROR:"system",NETWORK_ERROR:"system",TOO_MANY_REQUESTS:"rate_limit"},L={INVALID_CREDENTIALS:"Invalid username or password",UNAUTHORIZED:"You are not authorized to perform this action",SESSION_EXPIRED:"Your session has expired. Please log in again.",USER_NOT_FOUND:"User not found",ITEM_NOT_FOUND:"Item not found",FIELD_ERROR:"Invalid field value",INTERNAL_SERVER_ERROR:"An internal error occurred",NETWORK_ERROR:"Network connection error",TIMEOUT_ERROR:"Request timeout",UNKNOWN_OPERATION:"Unknown operation",INVALID_EMAIL:"Invalid email format",INVALID_CODE:"Invalid code",TOO_MANY_REQUESTS:"Too many requests, please try again later"};function E(r,e){let{translateFn:t,currentLanguage:n,enableDebug:o}=e;o&&i.debug(`[ErrorTranslation] Translating error code: ${r} (lang: ${n||"unknown"})`);let s=r.toUpperCase(),l=D[s],u=w.map(a=>a.replace("{category}",l||"general").replace("{code}",s));o&&i.debug("[ErrorTranslation] Searching keys:",{translationKeys:u});for(let a of u){let d=t(a);if(o&&i.debug(`[ErrorTranslation] Checking key: "${a}" -> result: "${d}" (same as key: ${d===a})`),d&&d!==a)return o&&i.debug(`[ErrorTranslation] Found translation at key: ${a} = "${d}"`),d}let c=L[s];if(c)return o&&i.debug(`[ErrorTranslation] Using default message: "${c}"`),c;let h=s.replace(/_/g," ").toLowerCase().replace(/\b\w/g,a=>a.toUpperCase());return o&&i.debug(`[ErrorTranslation] No translation found, using friendly code: "${h}"`),h}function _(r,e){return r.map(t=>E(t,e))}function k(r,e){let{enableDebug:t}=e;t&&i.debug("[ErrorTranslation] Translating error:",{error:r});let n=E(r.code,e);return n!==r.code.toUpperCase()&&n!==r.code?(t&&i.debug(`[ErrorTranslation] Using hierarchical translation: "${n}"`),r.field?`${r.field}: ${n}`:n):r.message&&!r.message.includes("Error:")&&r.message.length>0&&r.message!==r.code?(t&&i.debug(`[ErrorTranslation] No hierarchical translation found, using API message: "${r.message}"`),r.message):(t&&i.debug(`[ErrorTranslation] Using final fallback: "${n}"`),r.field?`${r.field}: ${n}`:n)}function V(r,e={}){let t={translateFn:r,currentLanguage:e.currentLanguage,enableDebug:e.enableDebug||!1};return{translateErrorCode:n=>E(n,t),translateErrorCodes:n=>_(n,t),translateError:n=>k(n,t),translateApiError:n=>_optionalChain([n, 'optionalAccess', _2 => _2.data, 'optionalAccess', _3 => _3.response, 'optionalAccess', _4 => _4.status])?E(n.data.response.status,t):_optionalChain([n, 'optionalAccess', _5 => _5.status])?E(n.status,t):_optionalChain([n, 'optionalAccess', _6 => _6.code])?E(n.code,t):"Unknown error"}}var m=class r{constructor(){this.listeners=new Set;this.isHandlingAuthError=!1;this.lastErrorTime=0;this.lastEventType=null;this.DEBOUNCE_TIME=1e3}static getInstance(){return r.instance||(r.instance=new r),r.instance}emit(e,t){let n=Date.now();if(this.isHandlingAuthError&&this.lastEventType===e&&n-this.lastErrorTime<this.DEBOUNCE_TIME){i.debug(`AuthEventBus: Ignoring duplicate ${e} event (debounced)`);return}this.isHandlingAuthError=!0,this.lastErrorTime=n,this.lastEventType=e,i.debug(`AuthEventBus: Emitting ${e} event`,t?{details:t}:void 0);let o={type:e,details:t,timestamp:n};this.listeners.forEach(s=>{try{s(o)}catch(l){i.error("AuthEventBus: Error in listener",l instanceof Error?l:{message:String(l)})}}),setTimeout(()=>{this.isHandlingAuthError=!1,this.lastEventType=null},2e3)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}clear(){this.listeners.clear(),this.isHandlingAuthError=!1,this.lastEventType=null}isHandling(){return this.isHandlingAuthError}},B= exports.i =m.getInstance();var g=class g{constructor(){this.isPatched=!1;this.refCount=0;this.listeners=new Set;this.originalPushState=window.history.pushState,this.originalReplaceState=window.history.replaceState}static getInstance(){return g.instance||(g.instance=new g),g.instance}subscribe(e){return this.listeners.add(e),this.refCount++,this.isPatched||this.applyPatches(),()=>{this.unsubscribe(e)}}unsubscribe(e){this.listeners.delete(e),this.refCount--,this.refCount===0&&this.isPatched&&this.removePatches()}applyPatches(){let e=this;window.history.pushState=function(...t){let n=e.originalPushState.apply(this,t);return e.notifyListeners(),n},window.history.replaceState=function(...t){let n=e.originalReplaceState.apply(this,t);return e.notifyListeners(),n},this.isPatched=!0}removePatches(){window.history.pushState=this.originalPushState,window.history.replaceState=this.originalReplaceState,this.isPatched=!1}notifyListeners(){this.listeners.forEach(e=>{try{e()}catch(t){i.error("NavigationTracker: Error in navigation listener",t instanceof Error?t:{message:String(t)})}})}static reset(){_optionalChain([g, 'access', _7 => _7.instance, 'optionalAccess', _8 => _8.isPatched])&&g.instance.removePatches(),g.instance=null}getSubscriberCount(){return this.refCount}isActive(){return this.isPatched}};g.instance=null;var N=g;var b=r=>{try{let e=r.split(".");if(e.length!==3)return i.warn("Invalid JWT format: token must have 3 parts"),null;let t=e[1],n=t+"=".repeat((4-t.length%4)%4);return JSON.parse(atob(n))}catch(e){return i.warn("Failed to decode JWT token",e instanceof Error?{errorMessage:e.message}:{message:String(e)}),null}},X= exports.l =()=>{try{let r=null;if(r=sessionStorage.getItem("authToken"),r||(r=sessionStorage.getItem("token")),r||(r=localStorage.getItem("authToken")||localStorage.getItem("token")),!r)return null;let e=b(r);return e&&(e.email||e["cognito:username"])||null}catch(r){return i.warn("Failed to get current user email",r instanceof Error?{errorMessage:r.message}:{message:String(r)}),null}},Q= exports.m =r=>{try{let e=b(r);if(!e||!e.exp)return!0;let t=Math.floor(Date.now()/1e3);return e.exp<t}catch (e2){return!0}};exports.a = i; exports.b = p; exports.c = O; exports.d = K; exports.e = E; exports.f = _; exports.g = k; exports.h = V; exports.i = B; exports.j = N; exports.k = b; exports.l = X; exports.m = Q;
|