@nocios/crudify-ui 4.4.86 → 4.4.88

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.
@@ -0,0 +1 @@
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 b=[/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];function w(n){if(typeof document>"u")return null;let e=document.cookie.match(new RegExp("(^|;)\\s*"+n+"=([^;]+)"));return e?e[2]:null}function S(){if(typeof window<"u"&&window.__CRUDIFY_ENV__)return window.__CRUDIFY_ENV__;let n=w("environment");return n&&["dev","stg","api","prod"].includes(n)?n:"prod"}var N=null,_="CrudifyUI",v=class{constructor(){this.explicitEnv=null;this.explicitEnv=N,this.prefix=_}getEffectiveEnv(){return this.explicitEnv!==null?this.explicitEnv:S()}sanitize(e){let t=e;for(let o of b)t=t.replace(o,"[REDACTED]");return t}sanitizeContext(e){let t={};for(let[o,r]of Object.entries(e))if(r!=null)if(o==="userId"&&typeof r=="string")t[o]=r.length>8?`${r.substring(0,8)}***`:r;else if(o==="email"&&typeof r=="string"){let[a,u]=r.split("@");t[o]=a&&u?`${a.substring(0,3)}***@${u}`:"[REDACTED]"}else typeof r=="string"?t[o]=this.sanitize(r):typeof r=="object"&&r!==null?t[o]=this.sanitizeContext(r):t[o]=r;return t}shouldLog(e){if(typeof window<"u"&&window.__CRUDIFY_DEBUG_MODE__)return!0;let t=this.getEffectiveEnv();return!((t==="prod"||t==="production"||t==="api")&&e!=="error")}log(e,t,o){if(!this.shouldLog(e))return;let r=this.sanitize(t),a=o?this.sanitizeContext(o):void 0,u={timestamp:new Date().toISOString(),level:e,environment:this.getEffectiveEnv(),service:this.prefix,message:r,...a&&Object.keys(a).length>0&&{context:a}},l=JSON.stringify(u);switch(e){case"error":console.error(l);break;case"warn":console.warn(l);break;case"info":console.info(l);break;case"debug":console.log(l);break}}error(e,t){let o;t instanceof Error?o={errorName:t.name,errorMessage:t.message,stack:t.stack}:o=t,this.log("error",e,o)}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.getEffectiveEnv()}setEnvironment(e){this.explicitEnv=e,N=e,typeof window<"u"&&(window.__CRUDIFY_ENV__=e)}isExplicitlyConfigured(){return this.explicitEnv!==null}},i= exports.a =new v;var f=n=>{let e=document.cookie.match(new RegExp("(^|;)\\s*"+n+"=([^;]+)"));return e?e[2]:null};function O(n={}){let{publicApiKey:e,env:t,appName:o,logo:r,loginActions:a,featureKeys:u,enableDebug:l=!1}=n,s={configSource:"none"};l&&i.info("[ConfigResolver] Resolving configuration...",{propsApiKey:e?`${e.substring(0,10)}...`:void 0,propsEnv:t,hasPropsAppName:!!o,hasPropsLogo:!!r,propsLoginActions:a,propsFeatureKeys:u});let d=f("publicApiKey");if(l&&i.info("[ConfigResolver] Cookie check:",{hasCookieApiKey:!!d,cookieApiKey:d?`${d.substring(0,10)}...`:null,allCookies:typeof document<"u"?document.cookie:"N/A"}),d){let c=f("environment"),p=f("appName"),y=f("logo"),R=f("loginActions"),C=f("featureKeys"),A=f("theme");return s={publicApiKey:decodeURIComponent(d),env:c&&["dev","stg","api","prod"].includes(c)?c:"prod",appName:p?decodeURIComponent(p):void 0,logo:y?decodeURIComponent(y):void 0,loginActions:R?decodeURIComponent(R).split(",").map(E=>E.trim()).filter(Boolean):void 0,featureKeys:C?decodeURIComponent(C).split(",").map(E=>E.trim()).filter(Boolean):void 0,theme:A?(()=>{try{return JSON.parse(decodeURIComponent(A))}catch(E){l&&i.warn("[ConfigResolver] Failed to parse theme cookie",E instanceof Error?{errorMessage:E.message}:{message:String(E)});return}})():void 0,configSource:"cookies"},l&&(i.info("[ConfigResolver] \u2705 Using COOKIES configuration",{env:s.env,hasAppName:!!s.appName,hasLogo:!!s.logo,loginActionsCount:_optionalChain([s, 'access', _2 => _2.loginActions, 'optionalAccess', _3 => _3.length]),featureKeysCount:_optionalChain([s, 'access', _4 => _4.featureKeys, 'optionalAccess', _5 => _5.length])}),typeof window<"u"&&(window.__CRUDIFY_RESOLVED_CONFIG=s)),s}return e?(s={publicApiKey:e,env:t||"prod",appName:o,logo:r,loginActions:a,featureKeys:u,configSource:"props"},l&&(i.info("[ConfigResolver] \u2705 Using PROPS configuration (fallback - no cookies found)",{env:s.env,hasAppName:!!s.appName,hasLogo:!!s.logo,loginActionsCount:_optionalChain([s, 'access', _6 => _6.loginActions, 'optionalAccess', _7 => _7.length]),featureKeysCount:_optionalChain([s, 'access', _8 => _8.featureKeys, 'optionalAccess', _9 => _9.length])}),typeof window<"u"&&(window.__CRUDIFY_RESOLVED_CONFIG=s)),s):(l&&i.error("[ConfigResolver] \u274C No configuration found! Neither cookies nor props have publicApiKey",{hasCookies:!!d,hasProps:!!e}),s)}function M(n={}){return O(n)}var k=["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 h(n,e){let{translateFn:t,currentLanguage:o,enableDebug:r}=e;r&&i.debug(`[ErrorTranslation] Translating error code: ${n} (lang: ${o||"unknown"})`);let a=n.toUpperCase(),u=D[a],l=k.map(c=>c.replace("{category}",u||"general").replace("{code}",a));r&&i.debug("[ErrorTranslation] Searching keys:",{translationKeys:l});for(let c of l){let p=t(c);if(r&&i.debug(`[ErrorTranslation] Checking key: "${c}" -> result: "${p}" (same as key: ${p===c})`),p&&p!==c)return r&&i.debug(`[ErrorTranslation] Found translation at key: ${c} = "${p}"`),p}let s=L[a];if(s)return r&&i.debug(`[ErrorTranslation] Using default message: "${s}"`),s;let d=a.replace(/_/g," ").toLowerCase().replace(/\b\w/g,c=>c.toUpperCase());return r&&i.debug(`[ErrorTranslation] No translation found, using friendly code: "${d}"`),d}function U(n,e){return n.map(t=>h(t,e))}function x(n,e){let{enableDebug:t}=e;t&&i.debug("[ErrorTranslation] Translating error:",{error:n});let o=h(n.code,e);return o!==n.code.toUpperCase()&&o!==n.code?(t&&i.debug(`[ErrorTranslation] Using hierarchical translation: "${o}"`),n.field?`${n.field}: ${o}`:o):n.message&&!n.message.includes("Error:")&&n.message.length>0&&n.message!==n.code?(t&&i.debug(`[ErrorTranslation] No hierarchical translation found, using API message: "${n.message}"`),n.message):(t&&i.debug(`[ErrorTranslation] Using final fallback: "${o}"`),n.field?`${n.field}: ${o}`:o)}function z(n,e={}){let t={translateFn:n,currentLanguage:e.currentLanguage,enableDebug:e.enableDebug||!1};return{translateErrorCode:o=>h(o,t),translateErrorCodes:o=>U(o,t),translateError:o=>x(o,t),translateApiError:o=>_optionalChain([o, 'optionalAccess', _10 => _10.data, 'optionalAccess', _11 => _11.response, 'optionalAccess', _12 => _12.status])?h(o.data.response.status,t):_optionalChain([o, 'optionalAccess', _13 => _13.status])?h(o.status,t):_optionalChain([o, 'optionalAccess', _14 => _14.code])?h(o.code,t):"Unknown error"}}var m=class n{constructor(){this.listeners=new Set;this.isHandlingAuthError=!1;this.lastErrorTime=0;this.lastEventType=null;this.DEBOUNCE_TIME=1e3}static getInstance(){return n.instance||(n.instance=new n),n.instance}emit(e,t){let o=Date.now();if(this.isHandlingAuthError&&this.lastEventType===e&&o-this.lastErrorTime<this.DEBOUNCE_TIME){i.debug(`AuthEventBus: Ignoring duplicate ${e} event (debounced)`);return}this.isHandlingAuthError=!0,this.lastErrorTime=o,this.lastEventType=e,i.debug(`AuthEventBus: Emitting ${e} event`,t?{details:t}:void 0);let r={type:e,details:t,timestamp:o};this.listeners.forEach(a=>{try{a(r)}catch(u){i.error("AuthEventBus: Error in listener",u instanceof Error?u:{message:String(u)})}}),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}},J= 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 o=e.originalPushState.apply(this,t);return e.notifyListeners(),o},window.history.replaceState=function(...t){let o=e.originalReplaceState.apply(this,t);return e.notifyListeners(),o},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', _15 => _15.instance, 'optionalAccess', _16 => _16.isPatched])&&g.instance.removePatches(),g.instance=null}getSubscriberCount(){return this.refCount}isActive(){return this.isPatched}};g.instance=null;var I=g;var T=n=>{try{let e=n.split(".");if(e.length!==3)return i.warn("Invalid JWT format: token must have 3 parts"),null;let t=e[1],o=t+"=".repeat((4-t.length%4)%4);return JSON.parse(atob(o))}catch(e){return i.warn("Failed to decode JWT token",e instanceof Error?{errorMessage:e.message}:{message:String(e)}),null}},j= exports.l =()=>{try{let n=null;if(n=sessionStorage.getItem("authToken"),n||(n=sessionStorage.getItem("token")),n||(n=localStorage.getItem("authToken")||localStorage.getItem("token")),!n)return null;let e=T(n);return e&&(e.email||e["cognito:username"])||null}catch(n){return i.warn("Failed to get current user email",n instanceof Error?{errorMessage:n.message}:{message:String(n)}),null}},q= exports.m =n=>{try{let e=T(n);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 = f; exports.c = O; exports.d = M; exports.e = h; exports.f = U; exports.g = x; exports.h = z; exports.i = J; exports.j = I; exports.k = T; exports.l = j; exports.m = q;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }var _chunkDJ3T7VVSjs = require('./chunk-DJ3T7VVS.js');var _cryptojs = require('crypto-js'); var _cryptojs2 = _interopRequireDefault(_cryptojs);var c=class{constructor(t="sessionStorage"){this.encryptionKey=this.generateEncryptionKey(),this.storage=t==="localStorage"?window.localStorage:window.sessionStorage}generateEncryptionKey(){let t=[navigator.userAgent,navigator.language,new Date().getTimezoneOffset(),screen.colorDepth,screen.width,screen.height,"crudify-login"].join("|");return _cryptojs2.default.SHA256(t).toString()}setItem(t,e,n){try{let r=_cryptojs2.default.AES.encrypt(e,this.encryptionKey).toString();if(this.storage.setItem(t,r),n){let s=new Date().getTime()+n*60*1e3;this.storage.setItem(`${t}_expiry`,s.toString())}}catch(r){_chunkDJ3T7VVSjs.a.error("Failed to encrypt and store data",r instanceof Error?r:{message:String(r)})}}getItem(t){try{let e=`${t}_expiry`,n=this.storage.getItem(e);if(n){let g=parseInt(n,10);if(new Date().getTime()>g)return this.removeItem(t),null}let r=this.storage.getItem(t);if(!r)return null;let i=_cryptojs2.default.AES.decrypt(r,this.encryptionKey).toString(_cryptojs2.default.enc.Utf8);return i||(_chunkDJ3T7VVSjs.a.warn("Failed to decrypt stored data - may be corrupted"),this.removeItem(t),null)}catch(e){return _chunkDJ3T7VVSjs.a.error("Failed to decrypt data",e instanceof Error?e:{message:String(e)}),this.removeItem(t),null}}removeItem(t){this.storage.removeItem(t),this.storage.removeItem(`${t}_expiry`)}setToken(t){try{let e=t.split(".");if(e.length===3){let n=JSON.parse(atob(e[1]));if(n.exp){let r=n.exp*1e3,s=new Date().getTime(),i=Math.floor((r-s)/(60*1e3));if(i>0){this.setItem("authToken",t,i);return}}}}catch (e2){_chunkDJ3T7VVSjs.a.warn("Failed to parse token expiry, using default expiry")}this.setItem("authToken",t,1440)}getToken(){let t=this.getItem("authToken");if(t)try{let e=t.split(".");if(e.length===3){let n=JSON.parse(atob(e[1]));if(n.exp){let r=Math.floor(Date.now()/1e3);if(n.exp<r)return this.removeItem("authToken"),null}}}catch (e3){return _chunkDJ3T7VVSjs.a.warn("Failed to validate token expiry"),this.removeItem("authToken"),null}return t}},y= exports.a =new c("sessionStorage"),h= exports.b =new c("localStorage");exports.a = y; exports.b = h;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }var _chunk34FAL7YWjs = require('./chunk-34FAL7YW.js');var _cryptojs = require('crypto-js'); var _cryptojs2 = _interopRequireDefault(_cryptojs);var c=class{constructor(t="sessionStorage"){this.encryptionKey=this.generateEncryptionKey(),this.storage=t==="localStorage"?window.localStorage:window.sessionStorage}generateEncryptionKey(){let t=[navigator.userAgent,navigator.language,new Date().getTimezoneOffset(),screen.colorDepth,screen.width,screen.height,"crudify-login"].join("|");return _cryptojs2.default.SHA256(t).toString()}setItem(t,e,n){try{let r=_cryptojs2.default.AES.encrypt(e,this.encryptionKey).toString();if(this.storage.setItem(t,r),n){let s=new Date().getTime()+n*60*1e3;this.storage.setItem(`${t}_expiry`,s.toString())}}catch(r){_chunk34FAL7YWjs.a.error("Failed to encrypt and store data",r instanceof Error?r:{message:String(r)})}}getItem(t){try{let e=`${t}_expiry`,n=this.storage.getItem(e);if(n){let g=parseInt(n,10);if(new Date().getTime()>g)return this.removeItem(t),null}let r=this.storage.getItem(t);if(!r)return null;let i=_cryptojs2.default.AES.decrypt(r,this.encryptionKey).toString(_cryptojs2.default.enc.Utf8);return i||(_chunk34FAL7YWjs.a.warn("Failed to decrypt stored data - may be corrupted"),this.removeItem(t),null)}catch(e){return _chunk34FAL7YWjs.a.error("Failed to decrypt data",e instanceof Error?e:{message:String(e)}),this.removeItem(t),null}}removeItem(t){this.storage.removeItem(t),this.storage.removeItem(`${t}_expiry`)}setToken(t){try{let e=t.split(".");if(e.length===3){let n=JSON.parse(atob(e[1]));if(n.exp){let r=n.exp*1e3,s=new Date().getTime(),i=Math.floor((r-s)/(60*1e3));if(i>0){this.setItem("authToken",t,i);return}}}}catch (e2){_chunk34FAL7YWjs.a.warn("Failed to parse token expiry, using default expiry")}this.setItem("authToken",t,1440)}getToken(){let t=this.getItem("authToken");if(t)try{let e=t.split(".");if(e.length===3){let n=JSON.parse(atob(e[1]));if(n.exp){let r=Math.floor(Date.now()/1e3);if(n.exp<r)return this.removeItem("authToken"),null}}}catch (e3){return _chunk34FAL7YWjs.a.warn("Failed to validate token expiry"),this.removeItem("authToken"),null}return t}},y= exports.a =new c("sessionStorage"),h= exports.b =new c("localStorage");exports.a = y; exports.b = h;
@@ -1 +1 @@
1
- import{a as o}from"./chunk-HQKET2ZX.mjs";import a from"crypto-js";var c=class{constructor(t="sessionStorage"){this.encryptionKey=this.generateEncryptionKey(),this.storage=t==="localStorage"?window.localStorage:window.sessionStorage}generateEncryptionKey(){let t=[navigator.userAgent,navigator.language,new Date().getTimezoneOffset(),screen.colorDepth,screen.width,screen.height,"crudify-login"].join("|");return a.SHA256(t).toString()}setItem(t,e,n){try{let r=a.AES.encrypt(e,this.encryptionKey).toString();if(this.storage.setItem(t,r),n){let s=new Date().getTime()+n*60*1e3;this.storage.setItem(`${t}_expiry`,s.toString())}}catch(r){o.error("Failed to encrypt and store data",r instanceof Error?r:{message:String(r)})}}getItem(t){try{let e=`${t}_expiry`,n=this.storage.getItem(e);if(n){let g=parseInt(n,10);if(new Date().getTime()>g)return this.removeItem(t),null}let r=this.storage.getItem(t);if(!r)return null;let i=a.AES.decrypt(r,this.encryptionKey).toString(a.enc.Utf8);return i||(o.warn("Failed to decrypt stored data - may be corrupted"),this.removeItem(t),null)}catch(e){return o.error("Failed to decrypt data",e instanceof Error?e:{message:String(e)}),this.removeItem(t),null}}removeItem(t){this.storage.removeItem(t),this.storage.removeItem(`${t}_expiry`)}setToken(t){try{let e=t.split(".");if(e.length===3){let n=JSON.parse(atob(e[1]));if(n.exp){let r=n.exp*1e3,s=new Date().getTime(),i=Math.floor((r-s)/(60*1e3));if(i>0){this.setItem("authToken",t,i);return}}}}catch{o.warn("Failed to parse token expiry, using default expiry")}this.setItem("authToken",t,1440)}getToken(){let t=this.getItem("authToken");if(t)try{let e=t.split(".");if(e.length===3){let n=JSON.parse(atob(e[1]));if(n.exp){let r=Math.floor(Date.now()/1e3);if(n.exp<r)return this.removeItem("authToken"),null}}}catch{return o.warn("Failed to validate token expiry"),this.removeItem("authToken"),null}return t}},y=new c("sessionStorage"),h=new c("localStorage");export{y as a,h as b};
1
+ import{a as o}from"./chunk-SUWV767V.mjs";import a from"crypto-js";var c=class{constructor(t="sessionStorage"){this.encryptionKey=this.generateEncryptionKey(),this.storage=t==="localStorage"?window.localStorage:window.sessionStorage}generateEncryptionKey(){let t=[navigator.userAgent,navigator.language,new Date().getTimezoneOffset(),screen.colorDepth,screen.width,screen.height,"crudify-login"].join("|");return a.SHA256(t).toString()}setItem(t,e,n){try{let r=a.AES.encrypt(e,this.encryptionKey).toString();if(this.storage.setItem(t,r),n){let s=new Date().getTime()+n*60*1e3;this.storage.setItem(`${t}_expiry`,s.toString())}}catch(r){o.error("Failed to encrypt and store data",r instanceof Error?r:{message:String(r)})}}getItem(t){try{let e=`${t}_expiry`,n=this.storage.getItem(e);if(n){let g=parseInt(n,10);if(new Date().getTime()>g)return this.removeItem(t),null}let r=this.storage.getItem(t);if(!r)return null;let i=a.AES.decrypt(r,this.encryptionKey).toString(a.enc.Utf8);return i||(o.warn("Failed to decrypt stored data - may be corrupted"),this.removeItem(t),null)}catch(e){return o.error("Failed to decrypt data",e instanceof Error?e:{message:String(e)}),this.removeItem(t),null}}removeItem(t){this.storage.removeItem(t),this.storage.removeItem(`${t}_expiry`)}setToken(t){try{let e=t.split(".");if(e.length===3){let n=JSON.parse(atob(e[1]));if(n.exp){let r=n.exp*1e3,s=new Date().getTime(),i=Math.floor((r-s)/(60*1e3));if(i>0){this.setItem("authToken",t,i);return}}}}catch{o.warn("Failed to parse token expiry, using default expiry")}this.setItem("authToken",t,1440)}getToken(){let t=this.getItem("authToken");if(t)try{let e=t.split(".");if(e.length===3){let n=JSON.parse(atob(e[1]));if(n.exp){let r=Math.floor(Date.now()/1e3);if(n.exp<r)return this.removeItem("authToken"),null}}}catch{return o.warn("Failed to validate token expiry"),this.removeItem("authToken"),null}return t}},y=new c("sessionStorage"),h=new c("localStorage");export{y as a,h as b};
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 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 _chunkL7LTBWM5js = require('./chunk-L7LTBWM5.js');var _chunkDJ3T7VVSjs = require('./chunk-DJ3T7VVS.js');var _react = require('react');var _crudifybrowser = require('@nocios/crudify-browser'); var _crudifybrowser2 = _interopRequireDefault(_crudifybrowser);var J=(S={})=>{let{autoFetch:c=!0,retryOnError:N=!1,maxRetries:m=3}=S,{isAuthenticated:T,isInitialized:I,sessionData:u,tokens:p}=_chunkL7LTBWM5js.j.call(void 0, ),[R,d]=_react.useState.call(void 0, null),[y,A]=_react.useState.call(void 0, c&&T),[C,E]=_react.useState.call(void 0, null),l=_react.useRef.call(void 0, null),o=_react.useRef.call(void 0, !0),g=_react.useRef.call(void 0, 0),f=_react.useRef.call(void 0, 0),F=_react.useCallback.call(void 0, ()=>{if(!u)return null;let h=u["cognito:username"];return u.email||(typeof h=="string"?h:null)},[u]),P=_react.useCallback.call(void 0, ()=>{d(null),E(null),A(!1),f.current=0},[]),D=_react.useCallback.call(void 0, async()=>{let h=F();if(!h){o.current&&(E("No user email available from session data"),A(!1));return}if(!I){o.current&&(E("Session not initialized"),A(!1));return}l.current&&l.current.abort();let e=new AbortController;l.current=e;let i=++g.current;try{o.current&&(A(!0),E(null));let s=await _crudifybrowser2.default.readItems("users",{filter:{email:h},pagination:{limit:1}});if(i===g.current&&o.current&&!e.signal.aborted){let r=null;if(s.success){let t=s.data;if(Array.isArray(t)&&t.length>0)r=t[0];else if(t&&typeof t=="object"&&!Array.isArray(t)&&_optionalChain([t, 'access', _2 => _2.response, 'optionalAccess', _3 => _3.data]))try{let n=t.response.data,a=typeof n=="string"?JSON.parse(n):n;a&&a.items&&Array.isArray(a.items)&&a.items.length>0&&(r=a.items[0])}catch (e2){}else t&&typeof t=="object"&&!Array.isArray(t)&&t.items&&Array.isArray(t.items)&&t.items.length>0&&(r=t.items[0]);if(!r&&t&&typeof t=="object"&&!Array.isArray(t)&&_optionalChain([t, 'access', _4 => _4.data, 'optionalAccess', _5 => _5.response, 'optionalAccess', _6 => _6.data]))try{let n=t.data.response.data,a=typeof n=="string"?JSON.parse(n):n;a&&a.items&&Array.isArray(a.items)&&a.items.length>0&&(r=a.items[0])}catch (e3){}}r?(d(r),E(null),f.current=0):(E("User profile not found in database"),d(null))}}catch(s){if(i===g.current&&o.current){let r=s;if(r.name==="AbortError")return;N&&f.current<m&&(_optionalChain([r, 'access', _7 => _7.message, 'optionalAccess', _8 => _8.includes, 'call', _9 => _9("Network Error")])||_optionalChain([r, 'access', _10 => _10.message, 'optionalAccess', _11 => _11.includes, 'call', _12 => _12("Failed to fetch")]))?(f.current++,setTimeout(()=>{o.current&&D()},1e3*f.current)):(E("Failed to load user profile from database"),d(null))}}finally{i===g.current&&o.current&&A(!1),l.current===e&&(l.current=null)}},[I,F,N,m]);return _react.useEffect.call(void 0, ()=>{c&&T&&I?D():T||P()},[c,T,I,D,P]),_react.useEffect.call(void 0, ()=>(o.current=!0,()=>{o.current=!1,l.current&&(l.current.abort(),l.current=null)}),[]),{user:{session:u,data:R},loading:y,error:C,refreshProfile:D,clearProfile:P}};var te=()=>{let{isAuthenticated:S,isLoading:c,isInitialized:N,tokens:m,error:T,sessionData:I,login:u,logout:p,refreshTokens:R,clearError:d,getTokenInfo:y,isExpiringSoon:A,expiresIn:C,refreshExpiresIn:E}=_chunkL7LTBWM5js.j.call(void 0, ),l=_react.useCallback.call(void 0, g=>{g?_chunkDJ3T7VVSjs.a.warn("useAuth.setToken() is deprecated. Use login() method instead for better security."):p()},[p]),o=_optionalChain([m, 'optionalAccess', _13 => _13.expiresAt])?new Date(m.expiresAt):null;return{isAuthenticated:S,loading:c,error:T,token:_optionalChain([m, 'optionalAccess', _14 => _14.accessToken])||null,user:I,tokenExpiration:o,setToken:l,logout:p,refreshToken:R,login:u,isExpiringSoon:A,expiresIn:C,refreshExpiresIn:E,getTokenInfo:y,clearError:d}};var ae=()=>{let{isInitialized:S,isLoading:c,error:N,isAuthenticated:m,login:T}=_chunkL7LTBWM5js.j.call(void 0, ),I=_react.useCallback.call(void 0, ()=>S&&!c&&!N,[S,c,N]),u=_react.useCallback.call(void 0, async()=>new Promise((o,g)=>{let f=()=>{I()?o():N?g(new Error(N)):setTimeout(f,100)};f()}),[I,N]),p=_react.useCallback.call(void 0, async()=>{if(!I())throw new Error("System not ready. Check isInitialized, isLoading, and error states.")},[I]),R=_react.useCallback.call(void 0, async(o,g,f)=>(await p(),await _crudifybrowser2.default.readItems(o,g||{},f)),[p]),d=_react.useCallback.call(void 0, async(o,g,f)=>(await p(),await _crudifybrowser2.default.readItem(o,g,f)),[p]),y=_react.useCallback.call(void 0, async(o,g,f)=>(await p(),await _crudifybrowser2.default.createItem(o,g,f)),[p]),A=_react.useCallback.call(void 0, async(o,g,f)=>(await p(),await _crudifybrowser2.default.updateItem(o,g,f)),[p]),C=_react.useCallback.call(void 0, async(o,g,f)=>(await p(),await _crudifybrowser2.default.deleteItem(o,g,f)),[p]),E=_react.useCallback.call(void 0, async(o,g)=>(await p(),await _crudifybrowser2.default.transaction(o,g)),[p]),l=_react.useCallback.call(void 0, async(o,g)=>{try{let f=await T(o,g);return f.success?{success:!0,data:f.tokens}:{success:!1,errors:f.error||"Login failed"}}catch(f){return{success:!1,errors:f instanceof Error?f.message:"Login failed"}}},[T]);return{readItems:R,readItem:d,createItem:y,updateItem:A,deleteItem:C,transaction:E,login:l,isInitialized:S,isInitializing:c,initializationError:N,isReady:I,waitForReady:u}};var Y={INVALID_CREDENTIALS:"warning",UNAUTHORIZED:"warning",INVALID_API_KEY:"error",USER_NOT_FOUND:"warning",USER_NOT_ACTIVE:"warning",NO_PERMISSION:"warning",ITEM_NOT_FOUND:"info",NOT_FOUND:"info",IN_USE:"warning",FIELD_ERROR:"warning",BAD_REQUEST:"warning",INTERNAL_SERVER_ERROR:"error",DATABASE_CONNECTION_ERROR:"error",INVALID_CONFIGURATION:"error",UNKNOWN_OPERATION:"error",TOO_MANY_REQUESTS:"warning"},M={INVALID_CREDENTIALS:"errors.auth.INVALID_CREDENTIALS",UNAUTHORIZED:"errors.auth.UNAUTHORIZED",INVALID_API_KEY:"errors.auth.INVALID_API_KEY",USER_NOT_FOUND:"errors.auth.USER_NOT_FOUND",USER_NOT_ACTIVE:"errors.auth.USER_NOT_ACTIVE",NO_PERMISSION:"errors.auth.NO_PERMISSION",ITEM_NOT_FOUND:"errors.data.ITEM_NOT_FOUND",NOT_FOUND:"errors.data.NOT_FOUND",IN_USE:"errors.data.IN_USE",FIELD_ERROR:"errors.data.FIELD_ERROR",BAD_REQUEST:"errors.data.BAD_REQUEST",INTERNAL_SERVER_ERROR:"errors.system.INTERNAL_SERVER_ERROR",DATABASE_CONNECTION_ERROR:"errors.system.DATABASE_CONNECTION_ERROR",INVALID_CONFIGURATION:"errors.system.INVALID_CONFIGURATION",UNKNOWN_OPERATION:"errors.system.UNKNOWN_OPERATION",TOO_MANY_REQUESTS:"errors.system.TOO_MANY_REQUESTS"},de= exports.d =(S={})=>{let{showNotification:c}=_chunkL7LTBWM5js.h.call(void 0, ),{showSuccessNotifications:N=!1,showErrorNotifications:m=!0,customErrorMessages:T={},defaultErrorMessage:I="Ha ocurrido un error inesperado",autoHideDuration:u=6e3,appStructure:p=[],translateFn:R=e=>e}=S,d=_react.useCallback.call(void 0, e=>{if(!e.success&&e.errors&&(Object.keys(e.errors).some(r=>r!=="_error"&&r!=="_graphql"&&r!=="_transaction")||_optionalChain([e, 'access', _15 => _15.errors, 'access', _16 => _16._transaction, 'optionalAccess', _17 => _17.includes, 'call', _18 => _18("ONE_OR_MORE_OPERATIONS_FAILED")])||_optionalChain([e, 'access', _19 => _19.errors, 'access', _20 => _20._error, 'optionalAccess', _21 => _21.includes, 'call', _22 => _22("TOO_MANY_REQUESTS")])))return!1;let i=e.data;return!(!e.success&&_optionalChain([i, 'optionalAccess', _23 => _23.response, 'optionalAccess', _24 => _24.status])==="TOO_MANY_REQUESTS")},[]),y=_react.useCallback.call(void 0, (e,i)=>{let s=R(e);return s===e?i||R("error.unknown"):s},[R]),A=_react.useCallback.call(void 0, e=>["create","update","delete"].includes(e),[]),C=_react.useCallback.call(void 0, (e,i)=>N?A(e)&&i?!0:p.some(s=>s.key===e):!1,[N,p,A]),E=_react.useCallback.call(void 0, (e,i,s)=>{let r=_optionalChain([s, 'optionalAccess', _25 => _25.key])&&typeof s.key=="string"?s.key:e,t=`action.onSuccess.${r}`,n=y(t);if(n!==R("error.unknown")){if(A(r)&&i){let a=`action.${i}Singular`,O=y(a);if(O!==R("error.unknown"))return R(t,{item:O});{let L=`action.onSuccess.${r}WithoutItem`,x=y(L);return x!==R("error.unknown")?x:n}}return n}return R("success.transaction")},[y,R,A]),l=_react.useCallback.call(void 0, e=>{if(e.errorCode&&T[e.errorCode])return T[e.errorCode];if(e.errorCode&&M[e.errorCode])return y(M[e.errorCode]);if(e.errorCode){let i=[`errors.auth.${e.errorCode}`,`errors.data.${e.errorCode}`,`errors.system.${e.errorCode}`,`errors.${e.errorCode}`];for(let s of i){let r=y(s);if(r!==R("error.unknown"))return r}}if(typeof e.data=="string"&&e.data.startsWith("errors.")){let i=y(e.data);if(i!==R("error.unknown"))return i}if(e.errors&&Object.keys(e.errors).length>0){let i=Object.keys(e.errors);if(i.length===1&&i[0]==="_transaction"){let s=e.errors._transaction;if(_optionalChain([s, 'optionalAccess', _26 => _26.includes, 'call', _27 => _27("ONE_OR_MORE_OPERATIONS_FAILED")]))return"";if(Array.isArray(s)&&s.length>0){let r=s[0];if(typeof r=="string"&&r!=="ONE_OR_MORE_OPERATIONS_FAILED")try{let t=JSON.parse(r);if(Array.isArray(t)&&t.length>0){let n=t[0];if(_optionalChain([n, 'optionalAccess', _28 => _28.response, 'optionalAccess', _29 => _29.errorCode])){let a=n.response.errorCode;if(M[a])return y(M[a]);let O=[`errors.auth.${a}`,`errors.data.${a}`,`errors.system.${a}`,`errors.${a}`];for(let L of O){let x=y(L);if(x!==y("error.unknown"))return x}}if(_optionalChain([n, 'optionalAccess', _30 => _30.response, 'optionalAccess', _31 => _31.data]))return n.response.data}if(_optionalChain([t, 'optionalAccess', _32 => _32.response, 'optionalAccess', _33 => _33.message])){let n=t.response.message.toLowerCase();return n.includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):n.includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):t.response.message}}catch (e4){return r.toLowerCase().includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):r.toLowerCase().includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):r}}return y("error.transaction","Error en la operaci\xF3n")}if(i.length===1&&i[0]==="_error"){let s=e.errors._error;return Array.isArray(s)?s[0]:String(s)}return i.length===1&&i[0]==="_graphql"?y("errors.system.DATABASE_CONNECTION_ERROR"):`${y("errors.data.FIELD_ERROR")}: ${i.join(", ")}`}return I||R("error.unknown")},[T,I,R,y]),o=_react.useCallback.call(void 0, e=>e.errorCode&&Y[e.errorCode]?Y[e.errorCode]:"error",[]),g=_react.useCallback.call(void 0, async(e,i,s)=>{let r=await _crudifybrowser2.default.createItem(e,i,s);if(!r.success&&m&&d(r)){let t=l(r),n=o(r);c(t,n,{autoHideDuration:u})}else if(r.success){let t=_optionalChain([s, 'optionalAccess', _34 => _34.actionConfig]),n=_optionalChain([t, 'optionalAccess', _35 => _35.key])||"create",a=_optionalChain([t, 'optionalAccess', _36 => _36.moduleKey])||e;if(C(n,a)){let O=E(n,a,t);c(O,"success",{autoHideDuration:u})}}return r},[m,C,c,l,o,E,u,d]),f=_react.useCallback.call(void 0, async(e,i,s)=>{let r=await _crudifybrowser2.default.updateItem(e,i,s),t=_optionalChain([s, 'optionalAccess', _37 => _37.skipNotifications])===!0;if(!t&&!r.success&&m&&d(r)){let n=l(r),a=o(r);c(n,a,{autoHideDuration:u})}else if(!t&&r.success){let n=_optionalChain([s, 'optionalAccess', _38 => _38.actionConfig]),a=_optionalChain([n, 'optionalAccess', _39 => _39.key])||"update",O=_optionalChain([n, 'optionalAccess', _40 => _40.moduleKey])||e;if(C(a,O)){let L=E(a,O,n);c(L,"success",{autoHideDuration:u})}}return r},[m,C,c,l,o,E,u,d]),F=_react.useCallback.call(void 0, async(e,i,s)=>{let r=await _crudifybrowser2.default.deleteItem(e,i,s);if(!r.success&&m&&d(r)){let t=l(r),n=o(r);c(t,n,{autoHideDuration:u})}else if(r.success){let t=_optionalChain([s, 'optionalAccess', _41 => _41.actionConfig]),n=_optionalChain([t, 'optionalAccess', _42 => _42.key])||"delete",a=_optionalChain([t, 'optionalAccess', _43 => _43.moduleKey])||e;if(C(n,a)){let O=E(n,a,t);c(O,"success",{autoHideDuration:u})}}return r},[m,C,c,l,o,E,u,d]),P=_react.useCallback.call(void 0, async(e,i,s)=>{let r=await _crudifybrowser2.default.readItem(e,i,s);if(!r.success&&m&&d(r)){let t=l(r),n=o(r);c(t,n,{autoHideDuration:u})}return r},[m,c,l,o,u,d]),D=_react.useCallback.call(void 0, async(e,i,s)=>{let r=await _crudifybrowser2.default.readItems(e,i,s);if(!r.success&&m&&d(r)){let t=l(r),n=o(r);c(t,n,{autoHideDuration:u})}return r},[m,c,l,o,u,d]),q=_react.useCallback.call(void 0, async(e,i)=>{let s=await _crudifybrowser2.default.transaction(e,i),r=_optionalChain([i, 'optionalAccess', _44 => _44.skipNotifications])===!0;if(!r&&!s.success&&m&&d(s)){let t=l(s),n=o(s);c(t,n,{autoHideDuration:u})}else if(!r&&s.success){let t="transaction",n,a=null;if(_optionalChain([i, 'optionalAccess', _45 => _45.actionConfig])?(a=i.actionConfig,t=a.key,n=a.moduleKey):Array.isArray(e)&&e.length>0&&e[0].operation&&(t=e[0].operation,a=p.find(O=>O.key===t),a&&(n=a.moduleKey)),C(t,n)){let O=E(t,n,a);c(O,"success",{autoHideDuration:u})}}return s},[m,C,c,l,o,E,u,d,p]),h=_react.useCallback.call(void 0, (e,i)=>{if(!e.success&&m&&d(e)){let s=l(e),r=o(e);c(s,r,{autoHideDuration:u})}else e.success&&N&&i&&c(i,"success",{autoHideDuration:u});return e},[m,N,c,l,o,u,d,R]);return{createItem:g,updateItem:f,deleteItem:F,readItem:P,readItems:D,transaction:q,handleResponse:h,getErrorMessage:l,getErrorSeverity:o,shouldShowNotification:d}};exports.a = J; exports.b = te; exports.c = ae; exports.d = de;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 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 _chunkXBRMX26Njs = require('./chunk-XBRMX26N.js');var _chunk34FAL7YWjs = require('./chunk-34FAL7YW.js');var _react = require('react');var _crudifybrowser = require('@nocios/crudify-browser'); var _crudifybrowser2 = _interopRequireDefault(_crudifybrowser);var J=(S={})=>{let{autoFetch:c=!0,retryOnError:N=!1,maxRetries:m=3}=S,{isAuthenticated:T,isInitialized:I,sessionData:u,tokens:p}=_chunkXBRMX26Njs.j.call(void 0, ),[R,d]=_react.useState.call(void 0, null),[y,A]=_react.useState.call(void 0, c&&T),[C,E]=_react.useState.call(void 0, null),l=_react.useRef.call(void 0, null),o=_react.useRef.call(void 0, !0),g=_react.useRef.call(void 0, 0),f=_react.useRef.call(void 0, 0),F=_react.useCallback.call(void 0, ()=>{if(!u)return null;let h=u["cognito:username"];return u.email||(typeof h=="string"?h:null)},[u]),P=_react.useCallback.call(void 0, ()=>{d(null),E(null),A(!1),f.current=0},[]),D=_react.useCallback.call(void 0, async()=>{let h=F();if(!h){o.current&&(E("No user email available from session data"),A(!1));return}if(!I){o.current&&(E("Session not initialized"),A(!1));return}l.current&&l.current.abort();let e=new AbortController;l.current=e;let i=++g.current;try{o.current&&(A(!0),E(null));let s=await _crudifybrowser2.default.readItems("users",{filter:{email:h},pagination:{limit:1}});if(i===g.current&&o.current&&!e.signal.aborted){let r=null;if(s.success){let t=s.data;if(Array.isArray(t)&&t.length>0)r=t[0];else if(t&&typeof t=="object"&&!Array.isArray(t)&&_optionalChain([t, 'access', _2 => _2.response, 'optionalAccess', _3 => _3.data]))try{let n=t.response.data,a=typeof n=="string"?JSON.parse(n):n;a&&a.items&&Array.isArray(a.items)&&a.items.length>0&&(r=a.items[0])}catch (e2){}else t&&typeof t=="object"&&!Array.isArray(t)&&t.items&&Array.isArray(t.items)&&t.items.length>0&&(r=t.items[0]);if(!r&&t&&typeof t=="object"&&!Array.isArray(t)&&_optionalChain([t, 'access', _4 => _4.data, 'optionalAccess', _5 => _5.response, 'optionalAccess', _6 => _6.data]))try{let n=t.data.response.data,a=typeof n=="string"?JSON.parse(n):n;a&&a.items&&Array.isArray(a.items)&&a.items.length>0&&(r=a.items[0])}catch (e3){}}r?(d(r),E(null),f.current=0):(E("User profile not found in database"),d(null))}}catch(s){if(i===g.current&&o.current){let r=s;if(r.name==="AbortError")return;N&&f.current<m&&(_optionalChain([r, 'access', _7 => _7.message, 'optionalAccess', _8 => _8.includes, 'call', _9 => _9("Network Error")])||_optionalChain([r, 'access', _10 => _10.message, 'optionalAccess', _11 => _11.includes, 'call', _12 => _12("Failed to fetch")]))?(f.current++,setTimeout(()=>{o.current&&D()},1e3*f.current)):(E("Failed to load user profile from database"),d(null))}}finally{i===g.current&&o.current&&A(!1),l.current===e&&(l.current=null)}},[I,F,N,m]);return _react.useEffect.call(void 0, ()=>{c&&T&&I?D():T||P()},[c,T,I,D,P]),_react.useEffect.call(void 0, ()=>(o.current=!0,()=>{o.current=!1,l.current&&(l.current.abort(),l.current=null)}),[]),{user:{session:u,data:R},loading:y,error:C,refreshProfile:D,clearProfile:P}};var te=()=>{let{isAuthenticated:S,isLoading:c,isInitialized:N,tokens:m,error:T,sessionData:I,login:u,logout:p,refreshTokens:R,clearError:d,getTokenInfo:y,isExpiringSoon:A,expiresIn:C,refreshExpiresIn:E}=_chunkXBRMX26Njs.j.call(void 0, ),l=_react.useCallback.call(void 0, g=>{g?_chunk34FAL7YWjs.a.warn("useAuth.setToken() is deprecated. Use login() method instead for better security."):p()},[p]),o=_optionalChain([m, 'optionalAccess', _13 => _13.expiresAt])?new Date(m.expiresAt):null;return{isAuthenticated:S,loading:c,error:T,token:_optionalChain([m, 'optionalAccess', _14 => _14.accessToken])||null,user:I,tokenExpiration:o,setToken:l,logout:p,refreshToken:R,login:u,isExpiringSoon:A,expiresIn:C,refreshExpiresIn:E,getTokenInfo:y,clearError:d}};var ae=()=>{let{isInitialized:S,isLoading:c,error:N,isAuthenticated:m,login:T}=_chunkXBRMX26Njs.j.call(void 0, ),I=_react.useCallback.call(void 0, ()=>S&&!c&&!N,[S,c,N]),u=_react.useCallback.call(void 0, async()=>new Promise((o,g)=>{let f=()=>{I()?o():N?g(new Error(N)):setTimeout(f,100)};f()}),[I,N]),p=_react.useCallback.call(void 0, async()=>{if(!I())throw new Error("System not ready. Check isInitialized, isLoading, and error states.")},[I]),R=_react.useCallback.call(void 0, async(o,g,f)=>(await p(),await _crudifybrowser2.default.readItems(o,g||{},f)),[p]),d=_react.useCallback.call(void 0, async(o,g,f)=>(await p(),await _crudifybrowser2.default.readItem(o,g,f)),[p]),y=_react.useCallback.call(void 0, async(o,g,f)=>(await p(),await _crudifybrowser2.default.createItem(o,g,f)),[p]),A=_react.useCallback.call(void 0, async(o,g,f)=>(await p(),await _crudifybrowser2.default.updateItem(o,g,f)),[p]),C=_react.useCallback.call(void 0, async(o,g,f)=>(await p(),await _crudifybrowser2.default.deleteItem(o,g,f)),[p]),E=_react.useCallback.call(void 0, async(o,g)=>(await p(),await _crudifybrowser2.default.transaction(o,g)),[p]),l=_react.useCallback.call(void 0, async(o,g)=>{try{let f=await T(o,g);return f.success?{success:!0,data:f.tokens}:{success:!1,errors:f.error||"Login failed"}}catch(f){return{success:!1,errors:f instanceof Error?f.message:"Login failed"}}},[T]);return{readItems:R,readItem:d,createItem:y,updateItem:A,deleteItem:C,transaction:E,login:l,isInitialized:S,isInitializing:c,initializationError:N,isReady:I,waitForReady:u}};var Y={INVALID_CREDENTIALS:"warning",UNAUTHORIZED:"warning",INVALID_API_KEY:"error",USER_NOT_FOUND:"warning",USER_NOT_ACTIVE:"warning",NO_PERMISSION:"warning",ITEM_NOT_FOUND:"info",NOT_FOUND:"info",IN_USE:"warning",FIELD_ERROR:"warning",BAD_REQUEST:"warning",INTERNAL_SERVER_ERROR:"error",DATABASE_CONNECTION_ERROR:"error",INVALID_CONFIGURATION:"error",UNKNOWN_OPERATION:"error",TOO_MANY_REQUESTS:"warning"},M={INVALID_CREDENTIALS:"errors.auth.INVALID_CREDENTIALS",UNAUTHORIZED:"errors.auth.UNAUTHORIZED",INVALID_API_KEY:"errors.auth.INVALID_API_KEY",USER_NOT_FOUND:"errors.auth.USER_NOT_FOUND",USER_NOT_ACTIVE:"errors.auth.USER_NOT_ACTIVE",NO_PERMISSION:"errors.auth.NO_PERMISSION",ITEM_NOT_FOUND:"errors.data.ITEM_NOT_FOUND",NOT_FOUND:"errors.data.NOT_FOUND",IN_USE:"errors.data.IN_USE",FIELD_ERROR:"errors.data.FIELD_ERROR",BAD_REQUEST:"errors.data.BAD_REQUEST",INTERNAL_SERVER_ERROR:"errors.system.INTERNAL_SERVER_ERROR",DATABASE_CONNECTION_ERROR:"errors.system.DATABASE_CONNECTION_ERROR",INVALID_CONFIGURATION:"errors.system.INVALID_CONFIGURATION",UNKNOWN_OPERATION:"errors.system.UNKNOWN_OPERATION",TOO_MANY_REQUESTS:"errors.system.TOO_MANY_REQUESTS"},de= exports.d =(S={})=>{let{showNotification:c}=_chunkXBRMX26Njs.h.call(void 0, ),{showSuccessNotifications:N=!1,showErrorNotifications:m=!0,customErrorMessages:T={},defaultErrorMessage:I="Ha ocurrido un error inesperado",autoHideDuration:u=6e3,appStructure:p=[],translateFn:R=e=>e}=S,d=_react.useCallback.call(void 0, e=>{if(!e.success&&e.errors&&(Object.keys(e.errors).some(r=>r!=="_error"&&r!=="_graphql"&&r!=="_transaction")||_optionalChain([e, 'access', _15 => _15.errors, 'access', _16 => _16._transaction, 'optionalAccess', _17 => _17.includes, 'call', _18 => _18("ONE_OR_MORE_OPERATIONS_FAILED")])||_optionalChain([e, 'access', _19 => _19.errors, 'access', _20 => _20._error, 'optionalAccess', _21 => _21.includes, 'call', _22 => _22("TOO_MANY_REQUESTS")])))return!1;let i=e.data;return!(!e.success&&_optionalChain([i, 'optionalAccess', _23 => _23.response, 'optionalAccess', _24 => _24.status])==="TOO_MANY_REQUESTS")},[]),y=_react.useCallback.call(void 0, (e,i)=>{let s=R(e);return s===e?i||R("error.unknown"):s},[R]),A=_react.useCallback.call(void 0, e=>["create","update","delete"].includes(e),[]),C=_react.useCallback.call(void 0, (e,i)=>N?A(e)&&i?!0:p.some(s=>s.key===e):!1,[N,p,A]),E=_react.useCallback.call(void 0, (e,i,s)=>{let r=_optionalChain([s, 'optionalAccess', _25 => _25.key])&&typeof s.key=="string"?s.key:e,t=`action.onSuccess.${r}`,n=y(t);if(n!==R("error.unknown")){if(A(r)&&i){let a=`action.${i}Singular`,O=y(a);if(O!==R("error.unknown"))return R(t,{item:O});{let L=`action.onSuccess.${r}WithoutItem`,x=y(L);return x!==R("error.unknown")?x:n}}return n}return R("success.transaction")},[y,R,A]),l=_react.useCallback.call(void 0, e=>{if(e.errorCode&&T[e.errorCode])return T[e.errorCode];if(e.errorCode&&M[e.errorCode])return y(M[e.errorCode]);if(e.errorCode){let i=[`errors.auth.${e.errorCode}`,`errors.data.${e.errorCode}`,`errors.system.${e.errorCode}`,`errors.${e.errorCode}`];for(let s of i){let r=y(s);if(r!==R("error.unknown"))return r}}if(typeof e.data=="string"&&e.data.startsWith("errors.")){let i=y(e.data);if(i!==R("error.unknown"))return i}if(e.errors&&Object.keys(e.errors).length>0){let i=Object.keys(e.errors);if(i.length===1&&i[0]==="_transaction"){let s=e.errors._transaction;if(_optionalChain([s, 'optionalAccess', _26 => _26.includes, 'call', _27 => _27("ONE_OR_MORE_OPERATIONS_FAILED")]))return"";if(Array.isArray(s)&&s.length>0){let r=s[0];if(typeof r=="string"&&r!=="ONE_OR_MORE_OPERATIONS_FAILED")try{let t=JSON.parse(r);if(Array.isArray(t)&&t.length>0){let n=t[0];if(_optionalChain([n, 'optionalAccess', _28 => _28.response, 'optionalAccess', _29 => _29.errorCode])){let a=n.response.errorCode;if(M[a])return y(M[a]);let O=[`errors.auth.${a}`,`errors.data.${a}`,`errors.system.${a}`,`errors.${a}`];for(let L of O){let x=y(L);if(x!==y("error.unknown"))return x}}if(_optionalChain([n, 'optionalAccess', _30 => _30.response, 'optionalAccess', _31 => _31.data]))return n.response.data}if(_optionalChain([t, 'optionalAccess', _32 => _32.response, 'optionalAccess', _33 => _33.message])){let n=t.response.message.toLowerCase();return n.includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):n.includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):t.response.message}}catch (e4){return r.toLowerCase().includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):r.toLowerCase().includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):r}}return y("error.transaction","Error en la operaci\xF3n")}if(i.length===1&&i[0]==="_error"){let s=e.errors._error;return Array.isArray(s)?s[0]:String(s)}return i.length===1&&i[0]==="_graphql"?y("errors.system.DATABASE_CONNECTION_ERROR"):`${y("errors.data.FIELD_ERROR")}: ${i.join(", ")}`}return I||R("error.unknown")},[T,I,R,y]),o=_react.useCallback.call(void 0, e=>e.errorCode&&Y[e.errorCode]?Y[e.errorCode]:"error",[]),g=_react.useCallback.call(void 0, async(e,i,s)=>{let r=await _crudifybrowser2.default.createItem(e,i,s);if(!r.success&&m&&d(r)){let t=l(r),n=o(r);c(t,n,{autoHideDuration:u})}else if(r.success){let t=_optionalChain([s, 'optionalAccess', _34 => _34.actionConfig]),n=_optionalChain([t, 'optionalAccess', _35 => _35.key])||"create",a=_optionalChain([t, 'optionalAccess', _36 => _36.moduleKey])||e;if(C(n,a)){let O=E(n,a,t);c(O,"success",{autoHideDuration:u})}}return r},[m,C,c,l,o,E,u,d]),f=_react.useCallback.call(void 0, async(e,i,s)=>{let r=await _crudifybrowser2.default.updateItem(e,i,s),t=_optionalChain([s, 'optionalAccess', _37 => _37.skipNotifications])===!0;if(!t&&!r.success&&m&&d(r)){let n=l(r),a=o(r);c(n,a,{autoHideDuration:u})}else if(!t&&r.success){let n=_optionalChain([s, 'optionalAccess', _38 => _38.actionConfig]),a=_optionalChain([n, 'optionalAccess', _39 => _39.key])||"update",O=_optionalChain([n, 'optionalAccess', _40 => _40.moduleKey])||e;if(C(a,O)){let L=E(a,O,n);c(L,"success",{autoHideDuration:u})}}return r},[m,C,c,l,o,E,u,d]),F=_react.useCallback.call(void 0, async(e,i,s)=>{let r=await _crudifybrowser2.default.deleteItem(e,i,s);if(!r.success&&m&&d(r)){let t=l(r),n=o(r);c(t,n,{autoHideDuration:u})}else if(r.success){let t=_optionalChain([s, 'optionalAccess', _41 => _41.actionConfig]),n=_optionalChain([t, 'optionalAccess', _42 => _42.key])||"delete",a=_optionalChain([t, 'optionalAccess', _43 => _43.moduleKey])||e;if(C(n,a)){let O=E(n,a,t);c(O,"success",{autoHideDuration:u})}}return r},[m,C,c,l,o,E,u,d]),P=_react.useCallback.call(void 0, async(e,i,s)=>{let r=await _crudifybrowser2.default.readItem(e,i,s);if(!r.success&&m&&d(r)){let t=l(r),n=o(r);c(t,n,{autoHideDuration:u})}return r},[m,c,l,o,u,d]),D=_react.useCallback.call(void 0, async(e,i,s)=>{let r=await _crudifybrowser2.default.readItems(e,i,s);if(!r.success&&m&&d(r)){let t=l(r),n=o(r);c(t,n,{autoHideDuration:u})}return r},[m,c,l,o,u,d]),q=_react.useCallback.call(void 0, async(e,i)=>{let s=await _crudifybrowser2.default.transaction(e,i),r=_optionalChain([i, 'optionalAccess', _44 => _44.skipNotifications])===!0;if(!r&&!s.success&&m&&d(s)){let t=l(s),n=o(s);c(t,n,{autoHideDuration:u})}else if(!r&&s.success){let t="transaction",n,a=null;if(_optionalChain([i, 'optionalAccess', _45 => _45.actionConfig])?(a=i.actionConfig,t=a.key,n=a.moduleKey):Array.isArray(e)&&e.length>0&&e[0].operation&&(t=e[0].operation,a=p.find(O=>O.key===t),a&&(n=a.moduleKey)),C(t,n)){let O=E(t,n,a);c(O,"success",{autoHideDuration:u})}}return s},[m,C,c,l,o,E,u,d,p]),h=_react.useCallback.call(void 0, (e,i)=>{if(!e.success&&m&&d(e)){let s=l(e),r=o(e);c(s,r,{autoHideDuration:u})}else e.success&&N&&i&&c(i,"success",{autoHideDuration:u});return e},[m,N,c,l,o,u,d,R]);return{createItem:g,updateItem:f,deleteItem:F,readItem:P,readItems:D,transaction:q,handleResponse:h,getErrorMessage:l,getErrorSeverity:o,shouldShowNotification:d}};exports.a = J; exports.b = te; exports.c = ae; exports.d = de;
@@ -0,0 +1 @@
1
+ import{a as d,c as ce,e as me,i as G,j as Ee,k as Te,l as ve}from"./chunk-SUWV767V.mjs";import{createContext as Ge,useContext as Ve,useEffect as $e,useState as Z}from"react";import q from"@nocios/crudify-browser";var ue=class r{constructor(){this.listeners=[];this.credentials=null;this.isReady=!1}static getInstance(){return r.instance||(r.instance=new r),r.instance}notifyCredentialsReady(i){this.credentials=i,this.isReady=!0,this.listeners.forEach(e=>{try{e(i)}catch(t){d.error("[CredentialsEventBus] Error in listener",t instanceof Error?t:{message:String(t)})}}),this.listeners=[]}waitForCredentials(){return this.isReady&&this.credentials?Promise.resolve(this.credentials):new Promise(i=>{this.listeners.push(i)})}reset(){this.credentials=null,this.isReady=!1,this.listeners=[]}areCredentialsReady(){return this.isReady&&this.credentials!==null}},j=ue.getInstance();import{jsx as Ye}from"react/jsx-runtime";var Ae=Ge(void 0),ke=({config:r,children:i})=>{let[e,t]=Z(!0),[o,s]=Z(null),[u,m]=Z(!1),[w,k]=Z(""),[v,c]=Z();$e(()=>{if(!r.publicApiKey){s("No publicApiKey provided"),t(!1),m(!1);return}let l=`${r.publicApiKey}-${r.env}`;if(l===w&&u){t(!1);return}(async()=>{t(!0),s(null),m(!1);try{q.config(r.env||"prod");let g=await q.init(r.publicApiKey,"none");if(c(g),typeof q.transaction=="function"&&typeof q.login=="function")m(!0),k(l),g.apiEndpointAdmin&&g.apiKeyEndpointAdmin&&j.notifyCredentialsReady({apiUrl:g.apiEndpointAdmin,apiKey:g.apiKeyEndpointAdmin});else throw new Error("Crudify methods not properly initialized")}catch(g){let E=g instanceof Error?g.message:"Failed to initialize Crudify";d.error("[CrudifyProvider] Initialization error",g instanceof Error?g:{message:String(g)}),s(E),m(!1)}finally{t(!1)}})()},[r.publicApiKey,r.env,w,u]);let a={crudify:u?q:null,isLoading:e,error:o,isInitialized:u,adminCredentials:v};return Ye(Ae.Provider,{value:a,children:i})},be=()=>{let r=Ve(Ae);if(r===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return r};import J from"crypto-js";var p=class p{static setStorageType(i){p.storageType=i}static generateEncryptionKey(){let i=[navigator.userAgent,navigator.language,navigator.platform,screen.width,screen.height,Date.now().toString(),Math.random().toString(36)].join("|");return J.SHA256(i).toString()}static getEncryptionKey(){if(p.encryptionKey)return p.encryptionKey;let i=window.localStorage;if(!i)return p.encryptionKey=p.generateEncryptionKey(),p.encryptionKey;try{let e=i.getItem(p.ENCRYPTION_KEY_STORAGE);return(!e||e.length<32)&&(e=p.generateEncryptionKey(),i.setItem(p.ENCRYPTION_KEY_STORAGE,e)),p.encryptionKey=e,e}catch{return d.warn("Crudify: Cannot persist encryption key, using temporary key"),p.encryptionKey=p.generateEncryptionKey(),p.encryptionKey}}static isStorageAvailable(i){try{let e=window[i],t="__storage_test__";return e.setItem(t,"test"),e.removeItem(t),!0}catch{return!1}}static getStorage(){return p.storageType==="none"?null:p.isStorageAvailable(p.storageType)?window[p.storageType]:(d.warn(`Crudify: ${p.storageType} not available, tokens won't persist`),null)}static encrypt(i){try{let e=p.getEncryptionKey();return J.AES.encrypt(i,e).toString()}catch(e){return d.error("Crudify: Encryption failed",e instanceof Error?e:{message:String(e)}),i}}static decrypt(i){try{let e=p.getEncryptionKey();return J.AES.decrypt(i,e).toString(J.enc.Utf8)||i}catch(e){return d.error("Crudify: Decryption failed",e instanceof Error?e:{message:String(e)}),i}}static saveTokens(i){let e=p.getStorage();if(e)try{let t={accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt,savedAt:Date.now()},o=p.encrypt(JSON.stringify(t));e.setItem(p.TOKEN_KEY,o),d.debug("Crudify: Tokens saved successfully")}catch(t){d.error("Crudify: Failed to save tokens",t instanceof Error?t:{message:String(t)})}}static getTokens(){let i=p.getStorage();if(!i)return null;try{let e=i.getItem(p.TOKEN_KEY);if(!e)return null;let t=p.decrypt(e),o=JSON.parse(t);return!o.accessToken||!o.refreshToken||!o.expiresAt||!o.refreshExpiresAt?(d.warn("Crudify: Incomplete token data found, clearing storage"),p.clearTokens(),null):Date.now()>=o.refreshExpiresAt?(d.info("Crudify: Refresh token expired, clearing storage"),p.clearTokens(),null):{accessToken:o.accessToken,refreshToken:o.refreshToken,expiresAt:o.expiresAt,refreshExpiresAt:o.refreshExpiresAt}}catch(e){return d.error("Crudify: Failed to retrieve tokens",e instanceof Error?e:{message:String(e)}),p.clearTokens(),null}}static clearTokens(){let i=p.getStorage();if(i)try{i.removeItem(p.TOKEN_KEY),d.debug("Crudify: Tokens cleared from storage")}catch(e){d.error("Crudify: Failed to clear tokens",e instanceof Error?e:{message:String(e)})}}static rotateEncryptionKey(){try{p.clearTokens(),p.encryptionKey=null;let i=window.localStorage;i&&i.removeItem(p.ENCRYPTION_KEY_STORAGE),d.info("Crudify: Encryption key rotated successfully")}catch(i){d.error("Crudify: Failed to rotate encryption key",i instanceof Error?i:{message:String(i)})}}static hasValidTokens(){return p.getTokens()!==null}static getExpirationInfo(){let i=p.getTokens();if(!i)return null;let e=Date.now();return{accessExpired:e>=i.expiresAt,refreshExpired:e>=i.refreshExpiresAt,accessExpiresIn:Math.max(0,i.expiresAt-e),refreshExpiresIn:Math.max(0,i.refreshExpiresAt-e)}}static updateAccessToken(i,e){let t=p.getTokens();if(!t){d.warn("Crudify: Cannot update access token, no existing tokens found");return}p.saveTokens({...t,accessToken:i,expiresAt:e})}static createSyncEvent(i,e,t){return{type:i,tokens:e,hadPreviousTokens:t}}static subscribeToChanges(i){let e=t=>{if(t.key!==p.TOKEN_KEY)return;let o=t.oldValue!==null&&t.oldValue!=="";if(t.newValue===null){d.debug("Crudify: Tokens removed in another tab"),i(null,p.SYNC_EVENTS.TOKENS_CLEARED,o);return}if(t.newValue){d.debug("Crudify: Tokens updated in another tab");let s=p.getTokens();i(s,p.SYNC_EVENTS.TOKENS_UPDATED,o)}};return window.addEventListener("storage",e),()=>{window.removeEventListener("storage",e)}}};p.TOKEN_KEY="crudify_tokens",p.ENCRYPTION_KEY_STORAGE="crudify_enc_key",p.encryptionKey=null,p.storageType="localStorage",p.SYNC_EVENTS={TOKENS_CLEARED:"TOKENS_CLEARED",TOKENS_UPDATED:"TOKENS_UPDATED"};var T=p;import R from"@nocios/crudify-browser";var Q=class r{constructor(){this.config={};this.initialized=!1;this.crudifyInitialized=!1;this.lastActivityTime=0;this.isRefreshingLocally=!1;this.refreshPromise=null}static getInstance(){return r.instance||(r.instance=new r),r.instance}async initialize(i={}){if(!this.initialized){if(this.config={storageType:"localStorage",autoRestore:!0,enableLogging:!1,env:"stg",...i},T.setStorageType(this.config.storageType||"localStorage"),this.config.publicApiKey&&!this.crudifyInitialized&&await this.ensureCrudifyInitialized(),R.setTokenInvalidationCallback(()=>{this.log("Tokens invalidated by crudify-core"),G.emit("SESSION_EXPIRED",{message:"Your session has expired. Please log in again.",source:"crudify-core.clearTokensAndRefreshState"})}),this.config.apiEndpointAdmin&&this.config.apiKeyEndpointAdmin){let e=T.getTokens();e?T.saveTokens({...e,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin}):T.saveTokens({accessToken:"",refreshToken:"",expiresAt:0,refreshExpiresAt:0,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin})}this.config.autoRestore&&await this.restoreSession(),this.initialized=!0}}async login(i,e){try{let t=await R.login(i,e);if(!t.success)return{success:!1,error:this.formatError(t.errors),rawResponse:t};let o=T.getTokens(),s=t.data,u={accessToken:s.token,refreshToken:s.refreshToken,expiresAt:s.expiresAt,refreshExpiresAt:s.refreshExpiresAt,apiEndpointAdmin:o?.apiEndpointAdmin||this.config.apiEndpointAdmin,apiKeyEndpointAdmin:o?.apiKeyEndpointAdmin||this.config.apiKeyEndpointAdmin};return T.saveTokens(u),this.lastActivityTime=Date.now(),this.config.onLoginSuccess?.(u),{success:!0,tokens:u,data:s}}catch(t){return d.error("[SessionManager] Login error",t instanceof Error?t:{message:String(t)}),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}async logout(){try{this.log("Logging out..."),await R.logout(),T.clearTokens(),this.log("Logout successful"),this.config.onLogout?.()}catch(i){this.log("Logout error:",i),T.clearTokens()}}async restoreSession(){try{this.log("Attempting to restore session...");let i=T.getTokens();if(!i)return this.log("No valid tokens found in storage"),!1;if(Date.now()>=i.refreshExpiresAt)return this.log("Refresh token expired, clearing storage"),T.clearTokens(),!1;if(R.setTokens({accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt}),R.getTokenData().isValid===!1){if(this.log("Restored access token is invalid or expired"),Date.now()<i.refreshExpiresAt&&(this.log("Access token expired but refresh is valid, attempting refresh..."),await this.refreshTokens())){this.log("Session restored successfully via token refresh");let o=T.getTokens();return o&&this.config.onSessionRestored?.(o),!0}return T.clearTokens(),await R.logout(),!1}return this.log("Session restored successfully"),this.lastActivityTime=Date.now(),this.config.onSessionRestored?.(i),!0}catch(i){return this.log("Session restore error:",i),T.clearTokens(),await R.logout(),!1}}isAuthenticated(){return R.isLogin()||T.hasValidTokens()}getTokenInfo(){let i=R.getTokenData(),e=T.getExpirationInfo(),t=T.getTokens();return{isLoggedIn:this.isAuthenticated(),crudifyTokens:i,storageInfo:e,hasValidTokens:T.hasValidTokens(),apiEndpointAdmin:t?.apiEndpointAdmin,apiKeyEndpointAdmin:t?.apiKeyEndpointAdmin}}async refreshTokens(){if(this.isRefreshingLocally&&this.refreshPromise)return this.log("Refresh already in progress, waiting for existing promise..."),this.refreshPromise;this.isRefreshingLocally=!0,this.refreshPromise=this._performRefresh();try{return await this.refreshPromise}finally{this.isRefreshingLocally=!1,this.refreshPromise=null}}async _performRefresh(){try{this.log("Starting token refresh...");let i=await R.refreshAccessToken();if(!i.success)return this.log("Token refresh failed:",i.errors),T.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1;let e=i.data,t={accessToken:e.token,refreshToken:e.refreshToken,expiresAt:e.expiresAt,refreshExpiresAt:e.refreshExpiresAt};return T.saveTokens(t),this.log("Tokens refreshed and saved successfully"),this.lastActivityTime=Date.now(),!0}catch(i){return this.log("Token refresh error:",i),T.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1}}isRefreshing(){return this.isRefreshingLocally}setupResponseInterceptor(){R.setResponseInterceptor(async i=>{this.updateLastActivity();let e=this.detectAuthorizationError(i);if(e.isAuthError){if(this.log("\u{1F6A8} Authorization error detected:",{errorType:e.errorType,shouldLogout:e.shouldTriggerLogout}),e.isRefreshTokenInvalid||e.isTokenRefreshFailed)return this.log("Refresh token invalid, emitting TOKEN_REFRESH_FAILED event"),G.emit("TOKEN_REFRESH_FAILED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"}),i;e.shouldTriggerLogout&&(T.hasValidTokens()&&!e.isIrrecoverable?(this.log("Access token expired, emitting TOKEN_EXPIRED event"),G.emit("TOKEN_EXPIRED",{message:"Access token expired, refresh needed",error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"})):(this.log("No valid tokens or irrecoverable error, emitting SESSION_EXPIRED event"),G.emit("SESSION_EXPIRED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"})))}return i}),this.log("Response interceptor configured (non-blocking mode)")}async ensureCrudifyInitialized(){if(!this.crudifyInitialized)try{this.log("Initializing crudify SDK...");let i=R.getTokenData();if(i&&i.endpoint){this.log("Crudify already initialized by another service"),this.crudifyInitialized=!0;return}let e=this.config.env||"stg";R.config(e);let t=this.config.publicApiKey,o=this.config.enableLogging?"debug":"none",s=await R.init(t,o);if(s&&s.success===!1&&s.errors)throw new Error(`Failed to initialize crudify: ${JSON.stringify(s.errors)}`);this.crudifyInitialized=!0,this.log("Crudify SDK initialized successfully")}catch(i){throw d.error("[SessionManager] Failed to initialize crudify",i instanceof Error?i:{message:String(i)}),i}}detectAuthorizationError(i){let e={isAuthError:!1,isRefreshTokenInvalid:!1,isTokenRefreshFailed:!1,isTokenExpired:!1,isUnauthorized:!1,isIrrecoverable:!1,shouldTriggerLogout:!1,errorType:"",errorDetails:null,userFriendlyMessage:""};if(i.errors&&Array.isArray(i.errors)){let t=i.errors.find(o=>o.errorType==="Unauthorized"||o.message?.includes("Unauthorized")||o.message?.includes("Not Authorized")||o.message?.includes("NOT_AUTHORIZED")||o.message?.includes("Token")||o.message?.includes("TOKEN")||o.message?.includes("Authentication")||o.message?.includes("UNAUTHENTICATED")||o.extensions?.code==="UNAUTHENTICATED"||o.extensions?.code==="FORBIDDEN");t&&(e.isAuthError=!0,e.errorType="GraphQL Array",e.errorDetails=t,e.shouldTriggerLogout=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.",(t.message?.includes("TOKEN")||t.message?.includes("Token"))&&(e.isTokenExpired=!0),t.extensions?.code==="UNAUTHENTICATED"&&(e.isUnauthorized=!0))}if(!e.isAuthError&&i.errors&&typeof i.errors=="object"&&!Array.isArray(i.errors)){let o=Object.values(i.errors).flat().find(s=>typeof s=="string"&&(s.includes("NOT_AUTHORIZED")||s.includes("TOKEN_REFRESH_FAILED")||s.includes("TOKEN_HAS_EXPIRED")||s.includes("PLEASE_LOGIN")||s.includes("Unauthorized")||s.includes("UNAUTHENTICATED")||s.includes("SESSION_EXPIRED")||s.includes("INVALID_TOKEN")));o&&typeof o=="string"&&(e.isAuthError=!0,e.errorType="GraphQL Object",e.errorDetails=i.errors,e.shouldTriggerLogout=!0,o.includes("TOKEN_REFRESH_FAILED")?(e.isTokenRefreshFailed=!0,e.isRefreshTokenInvalid=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Tu sesi\xF3n ha caducado. Por favor, inicia sesi\xF3n nuevamente."):o.includes("TOKEN_HAS_EXPIRED")||o.includes("SESSION_EXPIRED")?(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."):o.includes("INVALID_TOKEN")?(e.isTokenExpired=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Token inv\xE1lido. Por favor, inicia sesi\xF3n nuevamente."):e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!e.isAuthError&&i.data?.response?.status){let t=i.data.response.status.toUpperCase();(t==="UNAUTHORIZED"||t==="UNAUTHENTICATED")&&(e.isAuthError=!0,e.errorType="Status",e.errorDetails=i.data.response,e.isUnauthorized=!0,e.shouldTriggerLogout=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!e.isAuthError&&i.data?.response?.data)try{let t=typeof i.data.response.data=="string"?JSON.parse(i.data.response.data):i.data.response.data;(t.error==="REFRESH_TOKEN_INVALID"||t.error==="TOKEN_EXPIRED"||t.error==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Parsed Data",e.errorDetails=t,e.shouldTriggerLogout=!0,e.isIrrecoverable=!0,t.error==="REFRESH_TOKEN_INVALID"?(e.isRefreshTokenInvalid=!0,e.isTokenRefreshFailed=!0,e.userFriendlyMessage="Tu sesi\xF3n ha caducado. Por favor, inicia sesi\xF3n nuevamente."):(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."))}catch{}if(!e.isAuthError&&i.errorCode){let t=String(i.errorCode).toUpperCase();(t==="UNAUTHORIZED"||t==="UNAUTHENTICATED"||t==="TOKEN_EXPIRED"||t==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Error Code",e.errorDetails={errorCode:t},e.shouldTriggerLogout=!0,t==="TOKEN_EXPIRED"?e.isTokenExpired=!0:e.isUnauthorized=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}return e}updateLastActivity(){this.lastActivityTime=Date.now(),this.log("Last activity updated")}getTimeSinceLastActivity(){return this.lastActivityTime===0?0:Date.now()-this.lastActivityTime}checkInactivity(){let i=this.getTimeSinceLastActivity();if(this.lastActivityTime===0)return"none";let e=1800*1e3;return i>e?(this.log(`Inactivity timeout: ${Math.floor(i/6e4)} minutes since last activity`),"logout"):"none"}clearSession(){T.clearTokens(),R.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?me("SESSION_EXPIRED",{translateFn:this.config.translateFn,enableDebug:this.config.enableLogging}):"Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."}log(i,...e){this.config.enableLogging&&console.log(`[SessionManager] ${i}`,...e)}formatError(i){return i?typeof i=="string"?i:typeof i=="object"?Object.values(i).flat().map(String).join(", "):"Authentication failed":"Unknown error"}};import{useState as Be,useEffect as ee,useCallback as $}from"react";function Ie(r={}){let[i,e]=Be({isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),t=Q.getInstance(),o=$(async()=>{try{e(n=>({...n,isLoading:!0,error:null}));let c={autoRestore:r.autoRestore??!0,enableLogging:r.enableLogging??!1,showNotification:r.showNotification,translateFn:r.translateFn,apiEndpointAdmin:r.apiEndpointAdmin,apiKeyEndpointAdmin:r.apiKeyEndpointAdmin,publicApiKey:r.publicApiKey,env:r.env||"stg",onSessionExpired:()=>{e(n=>({...n,isAuthenticated:!1,tokens:null,error:"Session expired"})),r.onSessionExpired?.()},onSessionRestored:n=>{e(g=>({...g,isAuthenticated:!0,tokens:n,error:null})),r.onSessionRestored?.(n)},onLoginSuccess:n=>{e(g=>({...g,isAuthenticated:!0,tokens:n,error:null}))},onLogout:()=>{e(n=>({...n,isAuthenticated:!1,tokens:null,error:null}))}};await t.initialize(c),t.setupResponseInterceptor();let a=t.isAuthenticated(),l=t.getTokenInfo();e(n=>({...n,isAuthenticated:a,isInitialized:!0,isLoading:!1,tokens:l.crudifyTokens.accessToken?{accessToken:l.crudifyTokens.accessToken,refreshToken:l.crudifyTokens.refreshToken,expiresAt:l.crudifyTokens.expiresAt,refreshExpiresAt:l.crudifyTokens.refreshExpiresAt}:null}))}catch(c){let a=c instanceof Error?c.message:"Initialization failed";d.error("[useSession] Initialize failed",c instanceof Error?c:{message:a}),e(l=>({...l,isLoading:!1,isInitialized:!0,error:a}))}},[r.autoRestore,r.enableLogging,r.onSessionExpired,r.onSessionRestored]),s=$(async(c,a)=>{e(l=>({...l,isLoading:!0,error:null}));try{let l=await t.login(c,a);return l.success&&l.tokens?e(n=>({...n,isAuthenticated:!0,tokens:l.tokens,isLoading:!1,error:null})):e(n=>({...n,isAuthenticated:!1,tokens:null,isLoading:!1,error:null})),l}catch(l){let n=l instanceof Error?l.message:"Login failed";d.error("[useSession] Login error",l instanceof Error?l:{message:n});let g=n.includes("INVALID_CREDENTIALS")||n.includes("Invalid email")||n.includes("Invalid password")||n.includes("credentials");return e(E=>({...E,isAuthenticated:!1,tokens:null,isLoading:!1,error:g?null:n})),{success:!1,error:n}}},[t]),u=$(async()=>{e(c=>({...c,isLoading:!0}));try{await t.logout(),e(c=>({...c,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))}catch(c){e(a=>({...a,isAuthenticated:!1,tokens:null,isLoading:!1,error:c instanceof Error?c.message:"Logout error"}))}},[t]),m=$(async()=>{try{let c=await t.refreshTokens();if(c){let a=t.getTokenInfo();e(l=>({...l,tokens:a.crudifyTokens.accessToken?{accessToken:a.crudifyTokens.accessToken,refreshToken:a.crudifyTokens.refreshToken,expiresAt:a.crudifyTokens.expiresAt,refreshExpiresAt:a.crudifyTokens.refreshExpiresAt}:null,error:null}))}else e(a=>({...a,isAuthenticated:!1,tokens:null,error:"Token refresh failed"}));return c}catch(c){return e(a=>({...a,isAuthenticated:!1,tokens:null,error:c instanceof Error?c.message:"Token refresh failed"})),!1}},[t]),w=$(()=>{e(c=>({...c,error:null}))},[]),k=$(()=>t.getTokenInfo(),[t]);ee(()=>{o()},[o]),ee(()=>{if(!i.isAuthenticated||!i.tokens)return;let c=Ee.getInstance(),a=()=>{t.updateLastActivity()},l=c.subscribe(a);window.addEventListener("popstate",a);let n=()=>{let C=t.getTokenInfo().crudifyTokens.expiresIn||0;return C<300*1e3?30*1e3:C<1800*1e3?60*1e3:120*1e3},g,E=()=>{let I=n();g=setTimeout(async()=>{if(t.isRefreshing()){E();return}let C=t.getTokenInfo(),x=C.crudifyTokens.expiresIn||0,O=((C.crudifyTokens.expiresAt||0)-(Date.now()-x))*.5;if(x>0&&x<=O)if(e(L=>({...L,isLoading:!0})),await t.refreshTokens()){let L=t.getTokenInfo();e(ae=>({...ae,isLoading:!1,tokens:L.crudifyTokens.accessToken?{accessToken:L.crudifyTokens.accessToken,refreshToken:L.crudifyTokens.refreshToken,expiresAt:L.crudifyTokens.expiresAt,refreshExpiresAt:L.crudifyTokens.refreshExpiresAt}:null}))}else e(L=>({...L,isLoading:!1,isAuthenticated:!1,tokens:null}));let b=t.getTimeSinceLastActivity(),W=1800*1e3;b>W?await u():E()},I)};return E(),()=>{clearTimeout(g),window.removeEventListener("popstate",a),l()}},[i.isAuthenticated,i.tokens,t,r.enableLogging,u]),ee(()=>{let c=G.subscribe(async a=>{if(a.type==="TOKEN_EXPIRED"){if(t.isRefreshing())return;e(l=>({...l,isLoading:!0}));try{if(await t.refreshTokens()){let n=t.getTokenInfo();e(g=>({...g,isLoading:!1,tokens:n.crudifyTokens.accessToken?{accessToken:n.crudifyTokens.accessToken,refreshToken:n.crudifyTokens.refreshToken,expiresAt:n.crudifyTokens.expiresAt,refreshExpiresAt:n.crudifyTokens.refreshExpiresAt}:null}))}else G.emit("SESSION_EXPIRED",{message:"Failed to refresh token after detecting expiration",source:"useSession.TOKEN_EXPIRED handler"})}catch(l){G.emit("SESSION_EXPIRED",{message:l instanceof Error?l.message:"Unknown error during refresh",source:"useSession.TOKEN_EXPIRED handler (error)"})}}(a.type==="SESSION_EXPIRED"||a.type==="TOKEN_REFRESH_FAILED")&&(e(l=>({...l,isAuthenticated:!1,tokens:null,isLoading:!1,error:a.details?.message||"Session expired"})),r.onSessionExpired?.())});return()=>c()},[r.onSessionExpired,t]),ee(()=>{let c=T.subscribeToChanges((a,l,n)=>{l===T.SYNC_EVENTS.TOKENS_CLEARED?n&&i.isAuthenticated?(d.debug("[useSession] Cross-tab logout detected"),e(g=>({...g,isAuthenticated:!1,tokens:null})),r.onSessionExpired?.()):n&&e(g=>({...g,isAuthenticated:!1,tokens:null})):l===T.SYNC_EVENTS.TOKENS_UPDATED&&a&&(d.debug("[useSession] Cross-tab login/refresh detected"),e(g=>({...g,tokens:a,isAuthenticated:!0,error:null})))});return()=>c()},[i.isAuthenticated,r.onSessionExpired]);let v=$(()=>{t.updateLastActivity()},[t]);return{...i,login:s,logout:u,refreshTokens:m,clearError:w,getTokenInfo:k,updateActivity:v,isExpiringSoon:i.tokens?i.tokens.expiresAt-Date.now()<300*1e3:!1,expiresIn:i.tokens?Math.max(0,i.tokens.expiresAt-Date.now()):0,refreshExpiresIn:i.tokens?Math.max(0,i.tokens.refreshExpiresAt-Date.now()):0}}import{useState as Se,createContext as Xe,useContext as We,useCallback as ie,useEffect as Ze}from"react";import{Snackbar as qe,Alert as je,Box as Je,Portal as Qe}from"@mui/material";import{v4 as ei}from"uuid";import ii from"dompurify";import{jsx as Y,jsxs as ni}from"react/jsx-runtime";var xe=Xe(null),ti=r=>ii.sanitize(r,{ALLOWED_TAGS:["b","i","em","strong","br","span"],ALLOWED_ATTR:["class"],FORBID_TAGS:["script","iframe","object","embed"],FORBID_ATTR:["onload","onerror","onclick","onmouseover","onfocus","onblur"],WHOLE_DOCUMENT:!1,RETURN_DOM:!1,RETURN_DOM_FRAGMENT:!1,RETURN_TRUSTED_TYPE:!1}),de=({children:r,maxNotifications:i=5,defaultAutoHideDuration:e=6e3,position:t={vertical:"top",horizontal:"right"},enabled:o=!1,allowHtml:s=!1})=>{let[u,m]=Se([]),w=ie((a,l="info",n)=>{if(!o)return"";if(!a||typeof a!="string")return d.warn("GlobalNotificationProvider: Invalid message provided"),"";a.length>1e3&&(d.warn("GlobalNotificationProvider: Message too long, truncating"),a=a.substring(0,1e3)+"...");let g=ei(),E={id:g,message:a,severity:l,autoHideDuration:n?.autoHideDuration??e,persistent:n?.persistent??!1,allowHtml:n?.allowHtml??s};return m(I=>[...I.length>=i?I.slice(-(i-1)):I,E]),g},[i,e,o,s]),k=ie(a=>{m(l=>l.filter(n=>n.id!==a))},[]),v=ie(()=>{m([])},[]),c={showNotification:w,hideNotification:k,clearAllNotifications:v};return ni(xe.Provider,{value:c,children:[r,o&&Y(Qe,{children:Y(Je,{sx:{position:"fixed",zIndex:9999,[t.vertical]:(t.vertical==="top",24),[t.horizontal]:t.horizontal==="right"||t.horizontal==="left"?24:"50%",...t.horizontal==="center"&&{transform:"translateX(-50%)"},display:"flex",flexDirection:t.vertical==="top"?"column":"column-reverse",gap:1,maxWidth:"400px",width:"auto"},children:u.map(a=>Y(ri,{notification:a,onClose:()=>k(a.id)},a.id))})})]})},ri=({notification:r,onClose:i})=>{let[e,t]=Se(!0),o=ie((s,u)=>{u!=="clickaway"&&(t(!1),setTimeout(i,300))},[i]);return Ze(()=>{if(!r.persistent&&r.autoHideDuration){let s=setTimeout(()=>{o()},r.autoHideDuration);return()=>clearTimeout(s)}},[r.autoHideDuration,r.persistent,o]),Y(qe,{open:e,onClose:o,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:Y(je,{variant:"filled",severity:r.severity,onClose:o,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:r.allowHtml?Y("span",{dangerouslySetInnerHTML:{__html:ti(r.message)}}):Y("span",{children:r.message})})})},we=()=>{let r=We(xe);if(!r)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return r};import oi,{createContext as si,useContext as ai,useMemo as fe}from"react";import{Fragment as ci,jsx as P,jsxs as M}from"react/jsx-runtime";var Pe=si(void 0);function Ne({children:r,options:i={},config:e,showNotifications:t=!1,notificationOptions:o={}}){let s;try{let{showNotification:n}=we();s=n}catch{}let u={};try{let n=be();n.isInitialized&&n.adminCredentials&&(u=n.adminCredentials)}catch{}let m=fe(()=>{let n=ce({publicApiKey:e?.publicApiKey,env:e?.env,enableDebug:i?.enableLogging});return{publicApiKey:n.publicApiKey,env:n.env||"prod"}},[e,i?.enableLogging]),w=oi.useMemo(()=>({...i,showNotification:s,apiEndpointAdmin:u.apiEndpointAdmin,apiKeyEndpointAdmin:u.apiKeyEndpointAdmin,publicApiKey:m.publicApiKey,env:m.env,onSessionExpired:()=>{i.onSessionExpired?.()}}),[i,s,u.apiEndpointAdmin,u.apiKeyEndpointAdmin,m]),k=Ie(w),v=fe(()=>{let n=ce({publicApiKey:e?.publicApiKey,env:e?.env,appName:e?.appName,logo:e?.logo,loginActions:e?.loginActions,enableDebug:i?.enableLogging});return{publicApiKey:n.publicApiKey,env:n.env,appName:n.appName,loginActions:n.loginActions,logo:n.logo}},[e,i?.enableLogging]),c=fe(()=>{if(!k.tokens?.accessToken||!k.isAuthenticated)return null;try{let n=Te(k.tokens.accessToken);if(n&&n.sub&&n.email&&n.subscriber){let g={_id:n.sub,email:n.email,subscriberKey:n.subscriber};return Object.keys(n).forEach(E=>{["sub","email","subscriber"].includes(E)||(g[E]=n[E])}),g}}catch(n){d.error("Error decoding JWT token for sessionData",n instanceof Error?n:{message:String(n)})}return null},[k.tokens?.accessToken,k.isAuthenticated]),a={...k,sessionData:c,config:v},l={enabled:t,maxNotifications:o.maxNotifications||5,defaultAutoHideDuration:o.defaultAutoHideDuration||6e3,position:o.position||{vertical:"top",horizontal:"right"}};return P(Pe.Provider,{value:a,children:r})}function ut(r){let i={enabled:r.showNotifications,maxNotifications:r.notificationOptions?.maxNotifications||5,defaultAutoHideDuration:r.notificationOptions?.defaultAutoHideDuration||6e3,position:r.notificationOptions?.position||{vertical:"top",horizontal:"right"},allowHtml:r.notificationOptions?.allowHtml||!1};return r.config?.publicApiKey?P(ke,{config:{publicApiKey:r.config.publicApiKey,env:r.config.env||"prod",appName:r.config.appName,loginActions:r.config.loginActions,logo:r.config.logo},children:P(de,{...i,children:P(Ne,{...r})})}):P(de,{...i,children:P(Ne,{...r})})}function li(){let r=ai(Pe);if(r===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return r}function dt(){let r=li();return r.isInitialized?M("div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[P("h4",{children:"Session Debug Info"}),M("div",{children:[P("strong",{children:"Authenticated:"})," ",r.isAuthenticated?"Yes":"No"]}),M("div",{children:[P("strong",{children:"Loading:"})," ",r.isLoading?"Yes":"No"]}),M("div",{children:[P("strong",{children:"Error:"})," ",r.error||"None"]}),r.tokens&&M(ci,{children:[M("div",{children:[P("strong",{children:"Access Token:"})," ",r.tokens.accessToken.substring(0,20),"..."]}),M("div",{children:[P("strong",{children:"Refresh Token:"})," ",r.tokens.refreshToken.substring(0,20),"..."]}),M("div",{children:[P("strong",{children:"Access Expires In:"})," ",Math.round(r.expiresIn/1e3/60)," minutes"]}),M("div",{children:[P("strong",{children:"Refresh Expires In:"})," ",Math.round(r.refreshExpiresIn/1e3/60/60)," hours"]}),M("div",{children:[P("strong",{children:"Expiring Soon:"})," ",r.isExpiringSoon?"Yes":"No"]})]})]}):P("div",{children:"Session not initialized"})}import{useState as te,useEffect as Re,useCallback as Ce,useRef as re}from"react";import ui from"@nocios/crudify-browser";var mt=(r={})=>{let{autoFetch:i=!0,retryOnError:e=!1,maxRetries:t=3}=r,[o,s]=te(null),[u,m]=te(!1),[w,k]=te(null),[v,c]=te({}),a=re(null),l=re(!0),n=re(0),g=re(0),E=Ce(()=>{s(null),k(null),m(!1),c({})},[]),I=Ce(async()=>{let C=ve();if(!C){l.current&&(k("No user email available"),m(!1));return}a.current&&a.current.abort();let x=new AbortController;a.current=x;let D=++n.current;try{l.current&&(m(!0),k(null));let F=await ui.readItems("users",{filter:{email:C},pagination:{limit:1}});if(D===n.current&&l.current&&!x.signal.aborted){let O=F.data;if(F.success&&O&&O.length>0){let b=O[0];s(b);let W={fullProfile:b,totalFields:Object.keys(b).length,displayData:{id:b.id,email:b.email,username:b.username,firstName:b.firstName,lastName:b.lastName,fullName:b.fullName||`${b.firstName||""} ${b.lastName||""}`.trim(),role:b.role,permissions:b.permissions||[],isActive:b.isActive,lastLogin:b.lastLogin,createdAt:b.createdAt,updatedAt:b.updatedAt,...Object.keys(b).filter(B=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(B)).reduce((B,L)=>({...B,[L]:b[L]}),{})}};c(W),k(null),g.current=0}else k("User profile not found"),s(null),c({})}}catch(F){if(D===n.current&&l.current){let O=F;if(O.name==="AbortError")return;e&&g.current<t&&(O.message?.includes("Network Error")||O.message?.includes("Failed to fetch"))?(g.current++,setTimeout(()=>{l.current&&I()},1e3*g.current)):(k("Failed to load user profile"),s(null),c({}))}}finally{D===n.current&&l.current&&m(!1),a.current===x&&(a.current=null)}},[e,t]);return Re(()=>{i&&I()},[i,I]),Re(()=>(l.current=!0,()=>{l.current=!1,a.current&&(a.current.abort(),a.current=null)}),[]),{userProfile:o,loading:u,error:w,extendedData:v,refreshProfile:I,clearProfile:E}};import{useState as pe,useEffect as di,useCallback as ne,useRef as fi}from"react";import pi from"@nocios/crudify-browser";var At=(r,i={})=>{let{autoFetch:e=!0,onSuccess:t,onError:o}=i,{prefix:s,padding:u=0,separator:m=""}=r,[w,k]=pe(""),[v,c]=pe(!1),[a,l]=pe(null),n=fi(!1),g=ne(x=>{let D=String(x).padStart(u,"0");return`${s}${m}${D}`},[s,u,m]),E=ne(async()=>{c(!0),l(null);try{let x=await pi.getNextSequence(s),D=x.data;if(x.success&&D?.value){let F=g(D.value);k(F),t?.(F)}else{let F=x.errors?._error?.[0]||"Failed to generate code";l(F),o?.(F)}}catch(x){let D=x instanceof Error?x.message:"Unknown error";l(D),o?.(D)}finally{c(!1)}},[s,g,t,o]),I=ne(async()=>{await E()},[E]),C=ne(()=>{l(null)},[]);return di(()=>{e&&!w&&!n.current&&(n.current=!0,E())},[e,w,E]),{value:w,loading:v,error:a,regenerate:I,clearError:C}};import ge from"@nocios/crudify-browser";var ye=class r{constructor(){this.state={status:"UNINITIALIZED",priority:null,publicApiKey:null,env:null,error:null,initializedBy:null};this.initializationPromise=null;this.highPriorityInitializerPresent=!1;this.waitingForHighPriority=new Set;this.HIGH_PRIORITY_WAIT_TIMEOUT=100}static getInstance(){return r.instance||(r.instance=new r),r.instance}registerHighPriorityInitializer(){this.highPriorityInitializerPresent=!0}isHighPriorityInitializerPresent(){return this.highPriorityInitializerPresent}getState(){return{...this.state}}async initialize(i){let{priority:e,publicApiKey:t,env:o,enableLogging:s,requestedBy:u}=i;if(this.state.status==="INITIALIZED"){this.state.publicApiKey!==t&&d.warn(`[CrudifyInitialization] ${u} attempted to initialize with different key. Already initialized with key: ${this.state.publicApiKey?.slice(0,10)}... by ${this.state.initializedBy}`);return}if(this.initializationPromise)return s&&d.debug(`[CrudifyInitialization] ${u} waiting for ongoing initialization...`),this.initializationPromise;if(e==="LOW"&&this.highPriorityInitializerPresent&&this.state.status==="UNINITIALIZED"){if(s&&d.debug(`[CrudifyInitialization] ${u} (LOW priority) waiting for HIGH priority initializer...`),this.waitingForHighPriority.add(u),await this.waitForHighPriorityOrTimeout(s),this.waitingForHighPriority.delete(u),this.getState().status==="INITIALIZED"){s&&d.debug(`[CrudifyInitialization] ${u} found initialization completed by HIGH priority`);return}s&&d.warn(`[CrudifyInitialization] ${u} timeout waiting for HIGH priority, initializing with LOW priority`)}e==="HIGH"&&this.state.status==="INITIALIZING"&&this.state.priority==="LOW"&&(d.warn(`[CrudifyInitialization] HIGH priority request from ${u} interrupting LOW priority initialization by ${this.state.initializedBy}`),this.state.status="UNINITIALIZED",this.initializationPromise=null),s&&d.debug(`[CrudifyInitialization] ${u} starting initialization (${e} priority)...`),this.state.status="INITIALIZING",this.state.priority=e,this.state.initializedBy=u,this.initializationPromise=this.performInitialization(t,o,s);try{await this.initializationPromise,this.state.status="INITIALIZED",this.state.publicApiKey=t,this.state.env=o,this.state.error=null,s&&d.info(`[CrudifyInitialization] Successfully initialized by ${u} (${e} priority)`)}catch(m){throw this.state.status="ERROR",this.state.error=m instanceof Error?m:new Error(String(m)),this.initializationPromise=null,d.error(`[CrudifyInitialization] Initialization failed for ${u}`,m instanceof Error?m:{message:String(m)}),m}}async waitForHighPriorityOrTimeout(i){return new Promise(e=>{let o=0,s=setInterval(()=>{if(o+=10,this.state.status==="INITIALIZED"&&this.state.priority==="HIGH"){clearInterval(s),e();return}if(this.state.status==="INITIALIZING"&&this.state.priority==="HIGH"){o=0;return}o>=this.HIGH_PRIORITY_WAIT_TIMEOUT&&(clearInterval(s),i&&d.debug(`[CrudifyInitialization] Timeout waiting for HIGH priority (${this.HIGH_PRIORITY_WAIT_TIMEOUT}ms)`),e())},10)})}async performInitialization(i,e,t){let o=ge.getTokenData();if(o&&o.endpoint){t&&d.debug("[CrudifyInitialization] SDK already initialized externally");return}ge.config(e);let s=t?"debug":"none",u=await ge.init(i,s);if(u.success===!1)throw new Error(`Crudify initialization failed: ${JSON.stringify(u.errors||"Unknown error")}`);u.apiEndpointAdmin&&u.apiKeyEndpointAdmin&&j.notifyCredentialsReady({apiUrl:u.apiEndpointAdmin,apiKey:u.apiKeyEndpointAdmin})}reset(){this.state={status:"UNINITIALIZED",priority:null,publicApiKey:null,env:null,error:null,initializedBy:null},this.initializationPromise=null,this.highPriorityInitializerPresent=!1,this.waitingForHighPriority.clear()}isInitialized(){return this.state.status==="INITIALIZED"}getDiagnostics(){return{...this.state,waitingCount:this.waitingForHighPriority.size,waitingComponents:Array.from(this.waitingForHighPriority),hasActivePromise:this.initializationPromise!==null}}},oe=ye.getInstance();import{useState as De,useCallback as U,useRef as gi,useMemo as se}from"react";import he from"@nocios/crudify-browser";var Le=()=>`file_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,yi=r=>{let i=r.lastIndexOf("."),e=i>0?r.substring(i):"",t=Date.now(),o=Math.random().toString(36).substring(2,8);return`${t}_${o}${e}`},Ct=(r={})=>{let{acceptedTypes:i,maxFileSize:e=10*1024*1024,maxFiles:t,minFiles:o=0,visibility:s="private",onUploadComplete:u,onUploadError:m,onFileRemoved:w,onFilesChange:k}=r,[v,c]=De([]),[a,l]=De(!1),n=gi(new Map),g=U(()=>{l(!0)},[]),E=U((f,h)=>{c(y=>y.map(A=>A.id===f?{...A,...h}:A))},[]),I=U(f=>{k?.(f)},[k]),C=U(f=>i&&i.length>0&&!i.includes(f.type)?{valid:!1,error:`File type not allowed: ${f.type}`}:f.size>e?{valid:!1,error:`File exceeds maximum size of ${(e/1048576).toFixed(1)}MB`}:{valid:!0},[i,e]),x=U(async(f,h)=>{try{if(!oe.isInitialized())throw new Error("Crudify is not initialized. Please wait for the application to finish loading.");let y=yi(h.name),S=await he.generateSignedUrl({fileName:y,contentType:h.type,visibility:s});if(!S.success||!S.data)throw new Error("Failed to get upload URL");let A=S.data,{uploadUrl:z,s3Key:N,publicUrl:H}=A;if(!z||!N)throw new Error("Incomplete signed URL response");let X=N.indexOf("/"),He=X>0?N.substring(X+1):N;E(f.id,{status:"uploading",progress:0}),await new Promise((le,V)=>{let K=new XMLHttpRequest;K.upload.addEventListener("progress",_=>{if(_.lengthComputable){let _e=Math.round(_.loaded/_.total*100);E(f.id,{progress:_e})}}),K.addEventListener("load",()=>{K.status>=200&&K.status<300?le():V(new Error(`Upload failed with status ${K.status}`))}),K.addEventListener("error",()=>{V(new Error("Network error during upload"))}),K.addEventListener("abort",()=>{V(new Error("Upload cancelled"))}),K.open("PUT",z),K.setRequestHeader("Content-Type",h.type),K.send(h)});let Me={status:"completed",progress:100,filePath:He,visibility:s,publicUrl:s==="public"?H:void 0,file:void 0};c(le=>{let V=le.map(_=>_.id===f.id?{..._,...Me}:_);I(V);let K=V.find(_=>_.id===f.id);return K&&u?.(K),V})}catch(y){let S=y instanceof Error?y.message:"Unknown error";E(f.id,{status:"error",progress:0,errorMessage:S}),c(A=>{let z=A.find(N=>N.id===f.id);return z&&m?.(z,S),A})}},[E,u,m,s]),D=U(async f=>{let h=Array.from(f),y=[];c(S=>{if(t!==void 0){let N=S.filter(X=>X.status!=="error").length,H=t-N;if(H<=0)return d.warn(`File limit of ${t} already reached`),S;h.length>H&&(h=h.slice(0,H),d.warn(`Only ${H} files will be added to not exceed limit`))}let A=[];for(let N of h){let H=C(N),X={id:Le(),name:N.name,size:N.size,contentType:N.type,status:H.valid?"pending":"error",progress:0,createdAt:Date.now(),file:H.valid?N:void 0,errorMessage:H.error};A.push(X)}y=A;let z=[...S,...A];return I(z),z}),setTimeout(()=>{let S=y.filter(A=>A.status==="pending"&&A.file);for(let A of S)if(A.file){let z=x(A,A.file);n.current.set(A.id,z),z.finally(()=>{n.current.delete(A.id)})}},0)},[t,C,x,I]),F=U(async f=>{let h=v.find(y=>y.id===f);if(!h)return!1;E(f,{status:"removing"});try{if(h.filePath){if(!oe.isInitialized())throw new Error("Crudify is not initialized. Please wait for the application to finish loading.");if(!(await he.disableFile({filePath:h.filePath})).success)throw new Error("Failed to remove file from server")}return c(y=>{let S=y.filter(A=>A.id!==f);return I(S),S}),w?.(h),!0}catch(y){return E(f,{status:h.filePath?"completed":"error",errorMessage:y instanceof Error?y.message:"Error removing file"}),!1}},[v,E,I,w]),O=U(()=>{c([]),I([])},[I]),b=U(async f=>{let h=v.find(S=>S.id===f);if(!h||h.status!=="error"||!h.file){d.warn("Cannot retry: file not found or no original file");return}E(f,{status:"pending",progress:0,errorMessage:void 0});let y=x(h,h.file);n.current.set(f,y),y.finally(()=>{n.current.delete(f)})},[v,E,x]),W=U(async()=>{let f=Array.from(n.current.values());f.length>0&&await Promise.allSettled(f)},[]),B=f=>{let h=f.split(".").pop()?.toLowerCase()||"";return{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",ico:"image/x-icon",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",txt:"text/plain",csv:"text/csv",mp3:"audio/mpeg",wav:"audio/wav",mp4:"video/mp4",webm:"video/webm",zip:"application/zip",rar:"application/x-rar-compressed",json:"application/json",xml:"application/xml"}[h]||"application/octet-stream"},L=U(f=>{let h=f.map(y=>{let A=y.filePath.startsWith("http://")||y.filePath.startsWith("https://")?new URL(y.filePath).pathname:y.filePath,z=A.includes("/public/")||A.startsWith("public/")?"public":"private",N=y.contentType||B(y.name);return{id:Le(),name:y.name,size:y.size||0,contentType:N,status:"completed",progress:100,filePath:y.filePath,visibility:z,createdAt:Date.now()}});c(h),I(h)},[I]),ae=U(async f=>{let h=v.find(y=>y.id===f);if(!h||!h.filePath)return null;if(h.visibility==="public"&&h.publicUrl)return h.publicUrl;try{if(!oe.isInitialized())return null;let y=await he.getFileUrl({filePath:h.filePath,expiresIn:3600}),S=y.data;return y.success&&S?.url?S.url:null}catch{return null}},[v]),Fe=se(()=>v.some(f=>f.status==="uploading"||f.status==="pending"),[v]),ze=se(()=>v.filter(f=>f.status==="uploading"||f.status==="pending").length,[v]),Ke=se(()=>v.filter(f=>f.status==="completed"&&f.filePath).map(f=>f.filePath),[v]),{isValid:Ue,validationError:Oe}=se(()=>{let f=v.filter(y=>y.status==="completed").length;return f<o?{isValid:!1,validationError:o===1?"At least one file is required":`At least ${o} files are required`}:t!==void 0&&f>t?{isValid:!1,validationError:`Maximum ${t} files allowed`}:v.some(y=>y.status==="error")?{isValid:!1,validationError:"Some files have errors"}:{isValid:!0,validationError:null}},[v,o,t]);return{files:v,isUploading:Fe,pendingCount:ze,addFiles:D,removeFile:F,clearFiles:O,retryUpload:b,isValid:Ue,validationError:Oe,waitForUploads:W,completedFilePaths:Ke,initializeFiles:L,isTouched:a,markAsTouched:g,getPreviewUrl:ae}};export{j as a,ke as b,be as c,T as d,Q as e,Ie as f,de as g,we as h,ut as i,li as j,dt as k,mt as l,At as m,ye as n,oe as o,Ct as p};