@nocios/crudify-components 2.0.32 → 2.0.36
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/coverage/base.css +224 -0
- package/coverage/block-navigation.js +87 -0
- package/coverage/coverage-final.json +120 -0
- package/coverage/favicon.png +0 -0
- package/coverage/index.html +686 -0
- package/coverage/prettify.css +1 -0
- package/coverage/prettify.js +2 -0
- package/coverage/sort-arrow-sprite.png +0 -0
- package/coverage/sorter.js +210 -0
- package/dist/{CrudiaMarkdownField-C54-A_J3.d.mts → CrudiaMarkdownField-Bxl08sRG.d.mts} +12 -7
- package/dist/{CrudiaMarkdownField-C8HQh7s5.d.ts → CrudiaMarkdownField-DUJNOOzP.d.ts} +12 -7
- package/dist/chunk-44VU4TSP.mjs +1 -0
- package/dist/chunk-4LMFQECS.js +1 -0
- package/dist/chunk-77UKXG5L.mjs +1 -0
- package/dist/{chunk-4VN5YRYZ.js → chunk-BXFEQ6KP.js} +1 -1
- package/dist/{chunk-6ONAT4QU.js → chunk-H6XXWDUT.js} +1 -1
- package/dist/chunk-NIRLP2TC.js +1 -0
- package/dist/chunk-O4FUHIQG.mjs +1 -0
- package/dist/chunk-QFACMV2I.mjs +1 -0
- package/dist/chunk-QZH3KSJZ.js +1 -0
- package/dist/{chunk-RJBX4MWF.mjs → chunk-WMLIOPUC.mjs} +1 -1
- package/dist/components.d.mts +1 -1
- package/dist/components.d.ts +1 -1
- package/dist/components.js +1 -1
- package/dist/components.mjs +1 -1
- package/dist/errorTranslation-D-Y7uNN_.d.mts +141 -0
- package/dist/errorTranslation-DDlAXpMl.d.ts +141 -0
- package/dist/hooks.d.mts +2 -2
- package/dist/hooks.d.ts +2 -2
- package/dist/hooks.js +1 -1
- package/dist/hooks.mjs +1 -1
- package/dist/{index-DY90WVQQ.d.mts → index-U--xRr8A.d.mts} +225 -191
- package/dist/{index-d1vE803G.d.ts → index-dXVRVcEB.d.ts} +225 -191
- package/dist/index.d.mts +175 -6
- package/dist/index.d.ts +175 -6
- package/dist/index.js +2 -2
- package/dist/index.mjs +1 -1
- package/dist/{errorTranslation-By5Av0tL.d.ts → tenantConfig-DqJqQkoR.d.mts} +116 -139
- package/dist/{errorTranslation-DeeDj7Vt.d.mts → tenantConfig-DqJqQkoR.d.ts} +116 -139
- package/dist/utils.d.mts +2 -2
- package/dist/utils.d.ts +2 -2
- package/dist/utils.js +1 -1
- package/dist/utils.mjs +1 -1
- package/package.json +1 -1
- package/coverage/.tmp/coverage-102.json +0 -1
- package/coverage/.tmp/coverage-103.json +0 -1
- package/coverage/.tmp/coverage-104.json +0 -1
- package/coverage/.tmp/coverage-105.json +0 -1
- package/coverage/.tmp/coverage-106.json +0 -1
- package/coverage/.tmp/coverage-107.json +0 -1
- package/dist/api-B4uXiHF0.d.mts +0 -118
- package/dist/api-B4uXiHF0.d.ts +0 -118
- package/dist/chunk-4ILUXVPW.mjs +0 -1
- package/dist/chunk-5XBTRBE5.js +0 -1
- package/dist/chunk-CR5KJUST.js +0 -1
- package/dist/chunk-H5M2Q6PB.mjs +0 -1
- package/dist/chunk-JAPL7EZJ.mjs +0 -1
- package/dist/chunk-L7GKP6XY.mjs +0 -1
- package/dist/chunk-NSV6ECYO.js +0 -1
- package/dist/chunk-PTUSZGL4.mjs +0 -1
- package/dist/chunk-T6R65ROU.js +0 -1
package/dist/chunk-NSV6ECYO.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 r={INVALID_CREDENTIALS:"INVALID_CREDENTIALS",UNAUTHORIZED:"UNAUTHORIZED",INVALID_API_KEY:"INVALID_API_KEY",USER_NOT_FOUND:"USER_NOT_FOUND",USER_NOT_ACTIVE:"USER_NOT_ACTIVE",NO_PERMISSION:"NO_PERMISSION",ITEM_NOT_FOUND:"ITEM_NOT_FOUND",NOT_FOUND:"NOT_FOUND",IN_USE:"IN_USE",FIELD_ERROR:"FIELD_ERROR",BAD_REQUEST:"BAD_REQUEST",INVALID_EMAIL:"INVALID_EMAIL",INVALID_CODE:"INVALID_CODE",INTERNAL_SERVER_ERROR:"INTERNAL_SERVER_ERROR",DATABASE_CONNECTION_ERROR:"DATABASE_CONNECTION_ERROR",INVALID_CONFIGURATION:"INVALID_CONFIGURATION",UNKNOWN_OPERATION:"UNKNOWN_OPERATION",TOO_MANY_REQUESTS:"TOO_MANY_REQUESTS",NETWORK_ERROR:"NETWORK_ERROR",TIMEOUT_ERROR:"TIMEOUT_ERROR"},O= exports.b ={[r.INVALID_CREDENTIALS]:"warning",[r.UNAUTHORIZED]:"warning",[r.INVALID_API_KEY]:"error",[r.USER_NOT_FOUND]:"warning",[r.USER_NOT_ACTIVE]:"warning",[r.NO_PERMISSION]:"warning",[r.ITEM_NOT_FOUND]:"info",[r.NOT_FOUND]:"info",[r.IN_USE]:"warning",[r.FIELD_ERROR]:"warning",[r.BAD_REQUEST]:"warning",[r.INVALID_EMAIL]:"warning",[r.INVALID_CODE]:"warning",[r.INTERNAL_SERVER_ERROR]:"error",[r.DATABASE_CONNECTION_ERROR]:"error",[r.INVALID_CONFIGURATION]:"error",[r.UNKNOWN_OPERATION]:"error",[r.TOO_MANY_REQUESTS]:"warning",[r.NETWORK_ERROR]:"error",[r.TIMEOUT_ERROR]:"error"};function _(e){let o=[];try{let s=e;if(s.data&&typeof s.data=="object"){let a=s.data;if(a.response){let{status:t,fieldsWarning:R}=a.response;if(R&&typeof R=="object"&&Object.entries(R).forEach(([n,E])=>{Array.isArray(E)&&E.length>0&&o.push({code:r.FIELD_ERROR,message:E[0],severity:"warning",field:n})}),t&&typeof t=="string"){let n=t;O[n]&&o.push({code:n,message:i(n),severity:O[n]})}}}if(s.errors){if(typeof s.errors=="string")o.push({code:r.BAD_REQUEST,message:s.errors,severity:"warning"});else if(typeof s.errors=="object"){let a=s.errors;Object.entries(a).forEach(([t,R])=>{Array.isArray(R)&&R.length>0&&(t==="_error"?R.forEach(n=>{let E=typeof n=="string"&&N(n)?n:r.BAD_REQUEST;o.push({code:E,message:typeof n=="string"?n:i(E),severity:O[E]||"warning"})}):t==="_graphql"?R.forEach(n=>{if(typeof n=="string"){let E=N(n)?n:r.BAD_REQUEST;o.push({code:E,message:i(E),severity:O[E]||"warning"})}}):o.push({code:r.FIELD_ERROR,message:typeof R[0]=="string"?R[0]:"Validation error",severity:"warning",field:t}))})}}o.length===0&&s.success===!1&&o.push({code:r.BAD_REQUEST,message:"Request failed",severity:"warning"})}catch(s){o.push({code:r.INTERNAL_SERVER_ERROR,message:"Failed to parse error response",severity:"error",details:{originalError:s}})}return o.length>0?o:[{code:r.INTERNAL_SERVER_ERROR,message:"Unknown error occurred",severity:"error"}]}function I(e){try{let o=e;if(o.data&&Array.isArray(o.data)){let s=[];return o.data.forEach((a,t)=>{_optionalChain([a, 'access', _2 => _2.response, 'optionalAccess', _3 => _3.status])==="TOO_MANY_REQUESTS"?s.push({code:r.TOO_MANY_REQUESTS,message:i(r.TOO_MANY_REQUESTS),severity:"warning",details:{transactionIndex:t}}):(!a.response||a.response.status!=="OK")&&s.push({code:r.BAD_REQUEST,message:"Transaction failed",severity:"warning",details:{transactionIndex:t,response:a.response}})}),s}return _(e)}catch(o){return[{code:r.INTERNAL_SERVER_ERROR,message:"Failed to parse transaction error",severity:"error",details:{originalError:o}}]}}function N(e){return Object.values(r).includes(e)}function i(e){return{[r.INVALID_CREDENTIALS]:"Invalid email or password",[r.UNAUTHORIZED]:"You are not authorized to perform this action",[r.INVALID_API_KEY]:"Invalid API key",[r.USER_NOT_FOUND]:"User not found",[r.USER_NOT_ACTIVE]:"User account is not active",[r.NO_PERMISSION]:"You do not have permission to perform this action",[r.ITEM_NOT_FOUND]:"Item not found",[r.NOT_FOUND]:"Resource not found",[r.IN_USE]:"Resource is currently in use",[r.FIELD_ERROR]:"Validation error",[r.BAD_REQUEST]:"Invalid request",[r.INVALID_EMAIL]:"Please enter a valid email address",[r.INVALID_CODE]:"Invalid or expired code",[r.INTERNAL_SERVER_ERROR]:"Internal server error",[r.DATABASE_CONNECTION_ERROR]:"Database connection error",[r.INVALID_CONFIGURATION]:"Invalid configuration",[r.UNKNOWN_OPERATION]:"Unknown operation",[r.TOO_MANY_REQUESTS]:"Too many requests. Please try again later.",[r.NETWORK_ERROR]:"Network error. Please check your connection.",[r.TIMEOUT_ERROR]:"Request timed out. Please try again."}[e]||"An unknown error occurred"}function c(e){return e instanceof Error?e.name==="AbortError"?{code:r.TIMEOUT_ERROR,message:"Request was cancelled",severity:"info"}:e.message.includes("NetworkError")||e.message.includes("Failed to fetch")?{code:r.NETWORK_ERROR,message:i(r.NETWORK_ERROR),severity:"error"}:{code:r.INTERNAL_SERVER_ERROR,message:e.message||"An unexpected error occurred",severity:"error",details:{originalError:e}}:{code:r.INTERNAL_SERVER_ERROR,message:"An unknown error occurred",severity:"error",details:{originalError:e}}}function d(e){if(e instanceof Error)return[c(e)];if(typeof e=="object"&&e!==null){let o=e;return o.data&&Array.isArray(o.data)?I(e):_(e)}return[{code:r.INTERNAL_SERVER_ERROR,message:"An unknown error occurred",severity:"error",details:{originalError:e}}]}exports.a = r; exports.b = O; exports.c = _; exports.d = I; exports.e = i; exports.f = c; exports.g = d;
|
package/dist/chunk-PTUSZGL4.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as c,d as ye,f as H,g as Re,h as Pe,i as Ne,j as De,k as Le,l as Oe,m as Fe,q as ze,r as Ue,s as Ke}from"./chunk-4ILUXVPW.mjs";var Me="crudify_storage_version",He=2,a=class a{static setStorageType(e){a.storageType=e}static async initialize(){if(!(a.encryptionKey&&a.salt))return a.initPromise||(a.initPromise=(async()=>{let t=null;for(let i=1;i<=3;i++)try{a.checkStorageVersion(),a.salt=a.getOrCreateSalt(),a.fingerprint=await a.generateFingerprint(),a.encryptionKey=await Pe(a.fingerprint,a.salt);return}catch(n){t=n instanceof Error?n:new Error(String(n)),i<3&&await new Promise(s=>setTimeout(s,100*i))}throw c.error("Crudify: Failed to initialize encryption after retries",t??{message:"Unknown error"}),t})()),a.initPromise}static checkStorageVersion(){try{if(parseInt(localStorage.getItem(Me)||"1",10)<He){let t=a.getStorage();t&&t.removeItem(a.TOKEN_KEY),localStorage.removeItem(a.ENCRYPTION_KEY_STORAGE),localStorage.removeItem(a.SALT_KEY),localStorage.setItem(Me,He.toString()),c.info("Crudify: Storage upgraded to v2, tokens cleared for security")}}catch{}}static getOrCreateSalt(){try{let t=localStorage.getItem(a.SALT_KEY);if(t){let i=atob(t),n=new Uint8Array(i.length);for(let s=0;s<i.length;s++)n[s]=i.charCodeAt(s);return n}}catch{}let e=Le();try{let t="";for(let i=0;i<e.length;i++)t+=String.fromCharCode(e[i]);localStorage.setItem(a.SALT_KEY,btoa(t))}catch{c.warn("Crudify: Cannot persist salt, encryption may not persist across sessions")}return e}static async generateFingerprint(){try{let n=localStorage.getItem(a.ENCRYPTION_KEY_STORAGE);if(n&&n.length>=32)return n}catch{}let t=[navigator.userAgent,navigator.language,navigator.platform||"unknown",String(screen.width),String(screen.height),String(screen.colorDepth||24),String(new Date().getTimezoneOffset()),"crudify-session-v3"].join("|"),i=await Re(t);try{localStorage.setItem(a.ENCRYPTION_KEY_STORAGE,i)}catch{c.warn("Crudify: Cannot persist encryption key hash, session may not survive page reload")}return i}static isStorageAvailable(e){try{let t=window[e],i="__storage_test__";return t.setItem(i,"test"),t.removeItem(i),!0}catch{return!1}}static getStorage(){return a.storageType==="none"?null:a.isStorageAvailable(a.storageType)?window[a.storageType]:(c.warn(`Crudify: ${a.storageType} not available, tokens won't persist`),null)}static async encryptData(e){if(await a.initialize(),!a.encryptionKey||!a.salt)throw new Error("Encryption not initialized");return Ne(e,a.encryptionKey,a.salt)}static async decryptData(e){if(await a.initialize(),!a.fingerprint)throw new Error("Encryption not initialized");return Oe(e)?De(e,a.fingerprint):(c.warn("Crudify: Legacy encrypted data detected, cannot decrypt"),null)}static async saveTokens(e){let t=a.getStorage();if(t)try{let i={accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt,refreshExpiresAt:e.refreshExpiresAt,savedAt:Date.now()},n=await a.encryptData(JSON.stringify(i));t.setItem(a.TOKEN_KEY,n),c.debug("Crudify: Tokens saved successfully")}catch(i){c.error("Crudify: Failed to save tokens",i instanceof Error?i:{message:String(i)})}}static async getTokens(){let e=a.getStorage();if(!e)return null;try{let t=e.getItem(a.TOKEN_KEY);if(!t)return null;let i=await a.decryptData(t);if(!i)return c.warn("Crudify: Failed to decrypt tokens, clearing storage"),await a.clearTokens(),null;let n=JSON.parse(i);return!n.accessToken||!n.refreshToken||!n.expiresAt||!n.refreshExpiresAt?(c.warn("Crudify: Incomplete token data found, clearing storage"),await a.clearTokens(),null):Date.now()>=n.refreshExpiresAt?(c.info("Crudify: Refresh token expired, clearing storage"),await a.clearTokens(),null):{accessToken:n.accessToken,refreshToken:n.refreshToken,expiresAt:n.expiresAt,refreshExpiresAt:n.refreshExpiresAt}}catch(t){return c.error("Crudify: Failed to retrieve tokens",t instanceof Error?t:{message:String(t)}),await a.clearTokens(),null}}static async clearTokens(){let e=a.getStorage();if(e)try{e.removeItem(a.TOKEN_KEY),c.debug("Crudify: Tokens cleared from storage")}catch(t){c.error("Crudify: Failed to clear tokens",t instanceof Error?t:{message:String(t)})}}static async rotateEncryptionKey(){try{await a.clearTokens(),a.encryptionKey=null,a.salt=null,a.fingerprint=null,a.initPromise=null;try{localStorage.removeItem(a.ENCRYPTION_KEY_STORAGE),localStorage.removeItem(a.SALT_KEY)}catch{}c.info("Crudify: Encryption key rotated successfully")}catch(e){c.error("Crudify: Failed to rotate encryption key",e instanceof Error?e:{message:String(e)})}}static async hasValidTokens(){return await a.getTokens()!==null}static async ensureInitialized(){await a.initialize()}static async getExpirationInfo(){let e=await a.getTokens();if(!e)return null;let t=Date.now();return{accessExpired:t>=e.expiresAt,refreshExpired:t>=e.refreshExpiresAt,accessExpiresIn:Math.max(0,e.expiresAt-t),refreshExpiresIn:Math.max(0,e.refreshExpiresAt-t)}}static async updateAccessToken(e,t){let i=await a.getTokens();if(!i){c.warn("Crudify: Cannot update access token, no existing tokens found");return}await a.saveTokens({...i,accessToken:e,expiresAt:t})}static createSyncEvent(e,t,i){return{type:e,tokens:t,hadPreviousTokens:i}}static markLocalChange(){a.ignoreNextStorageEvent=!0,a.ignoreStorageEventTimeout&&clearTimeout(a.ignoreStorageEventTimeout),a.ignoreStorageEventTimeout=setTimeout(()=>{a.ignoreNextStorageEvent=!1},100)}static markSuccessfulLogin(){a.lastSuccessfulLoginTime=Date.now()}static isWithinLoginGracePeriod(){return a.lastSuccessfulLoginTime===0?!1:Date.now()-a.lastSuccessfulLoginTime<a.LOGIN_GRACE_PERIOD_MS}static subscribeToChanges(e){let t=async i=>{if(i.key!==a.TOKEN_KEY)return;if(a.ignoreNextStorageEvent){a.ignoreNextStorageEvent=!1;return}if(i.newValue===null&&a.isWithinLoginGracePeriod())return;if(i.newValue===null){let l=a.getStorage()?.getItem(a.TOKEN_KEY);if(l!==null&&l!=="")return}let n=i.oldValue!==null&&i.oldValue!=="";if(i.newValue===null){c.debug("Crudify: Tokens removed in another tab"),e(null,a.SYNC_EVENTS.TOKENS_CLEARED,n);return}if(i.newValue){c.debug("Crudify: Tokens updated in another tab");let s=await a.getTokens();e(s,a.SYNC_EVENTS.TOKENS_UPDATED,n)}};return window.addEventListener("storage",t),()=>{window.removeEventListener("storage",t)}}};a.TOKEN_KEY="crudify_tokens",a.ENCRYPTION_KEY_STORAGE="crudify_enc_key",a.SALT_KEY="crudify_enc_salt",a.encryptionKey=null,a.salt=null,a.fingerprint=null,a.storageType="localStorage",a.initPromise=null,a.lastSuccessfulLoginTime=0,a.LOGIN_GRACE_PERIOD_MS=5e3,a.SYNC_EVENTS={TOKENS_CLEARED:"TOKENS_CLEARED",TOKENS_UPDATED:"TOKENS_UPDATED"},a.ignoreNextStorageEvent=!1,a.ignoreStorageEventTimeout=null;var v=a;var K=class K{constructor(){this.broadcastChannel=null;this.CHANNEL_NAME="crudify-session-sync";this.listeners=new Set;this.isInitialized=!1;this.tabId=K.generateTabId(),this.initialize()}static generateTabId(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,9);return`tab_${e}_${t}`}static getInstance(){return K.instance||(K.instance=new K),K.instance}static resetInstance(){K.instance&&(K.instance.destroy(),K.instance=null)}initialize(){if(!this.isInitialized)try{typeof BroadcastChannel<"u"?(this.broadcastChannel=new BroadcastChannel(this.CHANNEL_NAME),this.broadcastChannel.onmessage=e=>{this.handleMessage(e.data)},this.broadcastChannel.onmessageerror=()=>{c.warn("Crudify: CrossTabSync message error")},c.debug("Crudify: CrossTabSync initialized with BroadcastChannel")):c.debug("Crudify: BroadcastChannel not available, using localStorage fallback"),this.isInitialized=!0}catch(e){c.warn("Crudify: Failed to initialize CrossTabSync",{message:e instanceof Error?e.message:String(e)})}}destroy(){this.broadcastChannel&&(this.broadcastChannel.close(),this.broadcastChannel=null),this.listeners.clear(),this.isInitialized=!1}getTabId(){return this.tabId}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notifyLogin(){this.broadcast({type:"SESSION_STARTED",tabId:this.tabId,timestamp:Date.now()})}notifyLogout(){this.broadcast({type:"SESSION_ENDED",tabId:this.tabId,timestamp:Date.now()})}notifyTokenRefreshed(){this.broadcast({type:"TOKEN_REFRESHED",tabId:this.tabId,timestamp:Date.now()})}ping(){this.broadcast({type:"SESSION_PING",tabId:this.tabId,timestamp:Date.now()})}broadcast(e){this.isInitialized||this.initialize();try{this.broadcastChannel&&(this.broadcastChannel.postMessage(e),c.debug(`Crudify: CrossTab broadcast ${e.type}`))}catch(t){c.warn("Crudify: Failed to broadcast cross-tab message",{message:t instanceof Error?t.message:String(t)})}}handleMessage(e){e.tabId!==this.tabId&&(c.debug(`Crudify: CrossTab received ${e.type} from ${e.tabId}`),e.type==="SESSION_PING"&&this.broadcast({type:"SESSION_PONG",tabId:this.tabId,timestamp:Date.now(),payload:{respondingTo:e.tabId}}),this.listeners.forEach(t=>{try{t(e)}catch(i){c.error("Crudify: CrossTab listener error",{message:i instanceof Error?i.message:String(i)})}}))}};K.instance=null;var Ee=K,$=Ee.getInstance();import N from"@nocios/crudify-sdk";var se="crudify_auth",Se=r=>{if(r==="dev"||typeof window>"u"||!window.location)return"";if(!r){let e=window.location.hostname;return e?e.endsWith(".nocios.link")||e==="nocios.link"?".nocios.link":e.endsWith(".crudia.com")||e==="crudia.com"?".crudia.com":"":""}return r==="prod"||r==="api"?".crudia.com":".nocios.link"},Ot=(r,e,t)=>{if(typeof document>"u"){c.debug("[CookieSync] No document available (SSR), skipping cookie set");return}if(!r){c.warn("[CookieSync] Attempted to set cookie with empty token");return}try{let i=Se(t),n=Date.now(),s=Math.max(0,Math.floor((e-n)/1e3)),l=[`${se}=${encodeURIComponent(r)}`,"path=/","SameSite=Lax",`max-age=${s}`];typeof window<"u"&&window.location.protocol==="https:"&&l.push("Secure"),i&&l.push(`domain=${i}`),document.cookie=l.join("; "),c.debug("[CookieSync] Cookie set successfully",{domain:i||"(current host)",maxAgeSeconds:s,tokenLength:r.length})}catch(i){c.error("[CookieSync] Failed to set cookie",i instanceof Error?i:{message:String(i)})}},Ft=r=>{if(typeof document>"u"){c.debug("[CookieSync] No document available (SSR), skipping cookie clear");return}try{let e=Se(r),t=[`${se}=`,"path=/","max-age=0","expires=Thu, 01 Jan 1970 00:00:00 GMT"];e&&t.push(`domain=${e}`),document.cookie=t.join("; "),document.cookie=`${se}=; path=/; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 GMT`,c.debug("[CookieSync] Cookie cleared successfully",{domain:e||"(current host)"})}catch(e){c.error("[CookieSync] Failed to clear cookie",e instanceof Error?e:{message:String(e)})}},zt=()=>{if(typeof document>"u")return null;try{let e=document.cookie.split(";").map(i=>i.trim()).find(i=>i.startsWith(`${se}=`));if(!e)return null;let t=e.split("=")[1];return t?decodeURIComponent(t):null}catch(r){return c.error("[CookieSync] Failed to read cookie",r instanceof Error?r:{message:String(r)}),null}},j={setCrossSubdomainCookie:Ot,clearCrossSubdomainCookie:Ft,getCrossSubdomainCookie:zt,getCookieDomain:Se};var oe=class r{constructor(){this.config={};this.initialized=!1;this.crudifyInitialized=!1;this.lastActivityTime=0;this.isRefreshingLocally=!1;this.refreshPromise=null;this.isSessionActive=!1;this.isColdStartRestore=!1}static getInstance(){return r.instance||(r.instance=new r),r.instance}async initialize(e={}){if(!this.initialized){if(this.config={storageType:"localStorage",autoRestore:!0,enableLogging:!1,env:"stg",...e},v.setStorageType(this.config.storageType||"localStorage"),this.config.publicApiKey&&!this.crudifyInitialized&&await this.ensureCrudifyInitialized(),N.setTokenInvalidationCallback(()=>{this.log("Tokens invalidated by crudify-core"),H.emit("SESSION_EXPIRED",{message:"Your session has expired. Please log in again.",source:"crudify-core.clearTokensAndRefreshState"})}),this.config.apiEndpointAdmin&&this.config.apiKeyEndpointAdmin){let t=await v.getTokens();t?await v.saveTokens({...t,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin}):await v.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(e,t){try{let i=await N.login(e,t);if(!i.success)return{success:!1,error:this.formatError(i.errors),rawResponse:i};let n=await v.getTokens(),s=i.data,l={accessToken:s.token,refreshToken:s.refreshToken,expiresAt:s.expiresAt,refreshExpiresAt:s.refreshExpiresAt,apiEndpointAdmin:n?.apiEndpointAdmin||this.config.apiEndpointAdmin,apiKeyEndpointAdmin:n?.apiKeyEndpointAdmin||this.config.apiKeyEndpointAdmin};return await v.saveTokens(l),v.markSuccessfulLogin(),this.lastActivityTime=Date.now(),this.isSessionActive=!0,this.isColdStartRestore=!1,j.setCrossSubdomainCookie(l.accessToken,l.expiresAt,this.config.env),$.notifyLogin(),this.config.onLoginSuccess?.(l),{success:!0,tokens:l,data:s}}catch(i){return c.error("[SessionManager] Login error",i instanceof Error?i:{message:String(i)}),{success:!1,error:i instanceof Error?i.message:"Unknown error"}}}async logout(){this.isSessionActive=!1;try{this.log("Logging out..."),H.emit("LOGOUT",{message:"User logged out",source:"SessionManager.logout"}),j.clearCrossSubdomainCookie(this.config.env),await N.logout(),await v.clearTokens(),$.notifyLogout(),this.log("Logout successful"),this.config.onLogout?.()}catch(e){this.log("Logout error",{error:e instanceof Error?e.message:String(e)}),await v.clearTokens(),$.notifyLogout()}}async restoreSession(){try{this.isColdStartRestore=!0,this.log("Attempting to restore session (cold start)...");let e=await v.getTokens();if(!e)return this.log("No valid tokens found in storage"),this.isColdStartRestore=!1,!1;if(Date.now()>=e.refreshExpiresAt)return this.log("Refresh token expired, clearing storage (cold start - no notification)"),await v.clearTokens(),this.isColdStartRestore=!1,!1;if(N.setTokens({accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt,refreshExpiresAt:e.refreshExpiresAt}),N.getTokenData().isValid===!1){if(this.log("Restored access token is invalid or expired"),Date.now()<e.refreshExpiresAt&&(this.log("Access token expired but refresh is valid, attempting silent refresh..."),await this.refreshTokensSilent())){this.log("Session restored successfully via silent token refresh"),this.isSessionActive=!0,this.isColdStartRestore=!1;let n=await v.getTokens();return n&&this.config.onSessionRestored?.(n),!0}return this.log("Could not restore session, clearing tokens (cold start - no notification)"),await v.clearTokens(),await N.logout(),this.isColdStartRestore=!1,!1}return this.log("Session restored successfully"),this.isSessionActive=!0,this.isColdStartRestore=!1,this.lastActivityTime=Date.now(),this.config.onSessionRestored?.(e),!0}catch(e){return this.log("Session restore error",{error:e instanceof Error?e.message:String(e)}),await v.clearTokens(),await N.logout(),this.isColdStartRestore=!1,!1}}async isAuthenticated(){return N.isLogin()||await v.hasValidTokens()}async getTokenInfo(){let e=N.getTokenData(),t=await v.getExpirationInfo(),i=await v.getTokens();return{isLoggedIn:await this.isAuthenticated(),crudifyTokens:e,storageInfo:t,hasValidTokens:await v.hasValidTokens(),apiEndpointAdmin:i?.apiEndpointAdmin,apiKeyEndpointAdmin:i?.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 e=await N.refreshAccessToken();if(!e.success)return this.log("Token refresh failed",{errors:e.errors}),await v.clearTokens(),this.isSessionActive&&!this.isColdStartRestore&&this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),this.isSessionActive=!1,!1;let t=e.data,i={accessToken:t.token,refreshToken:t.refreshToken,expiresAt:t.expiresAt,refreshExpiresAt:t.refreshExpiresAt};return await v.saveTokens(i),this.log("Tokens refreshed and saved successfully"),j.setCrossSubdomainCookie(i.accessToken,i.expiresAt,this.config.env),this.lastActivityTime=Date.now(),$.notifyTokenRefreshed(),!0}catch(e){return this.log("Token refresh error",{error:e instanceof Error?e.message:String(e)}),await v.clearTokens(),this.isSessionActive&&!this.isColdStartRestore&&this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),this.isSessionActive=!1,!1}}isRefreshing(){return this.isRefreshingLocally}async refreshTokensSilent(){if(this.isRefreshingLocally&&this.refreshPromise)return this.log("Silent refresh: waiting for existing refresh promise..."),this.refreshPromise;this.isRefreshingLocally=!0,this.refreshPromise=this._performRefreshSilent();try{return await this.refreshPromise}finally{this.isRefreshingLocally=!1,this.refreshPromise=null}}async _performRefreshSilent(){try{this.log("Starting silent token refresh (cold start)...");let e=await N.refreshAccessToken();if(!e.success)return this.log("Silent token refresh failed",{errors:e.errors}),await v.clearTokens(),!1;let t=e.data,i={accessToken:t.token,refreshToken:t.refreshToken,expiresAt:t.expiresAt,refreshExpiresAt:t.refreshExpiresAt};return await v.saveTokens(i),this.log("Tokens refreshed silently and saved successfully"),j.setCrossSubdomainCookie(i.accessToken,i.expiresAt,this.config.env),this.lastActivityTime=Date.now(),$.notifyTokenRefreshed(),!0}catch(e){return this.log("Silent token refresh error",{error:e instanceof Error?e.message:String(e)}),await v.clearTokens(),!1}}getIsSessionActive(){return this.isSessionActive}setupResponseInterceptor(){N.setResponseInterceptor(async e=>{this.updateLastActivity();let t=this.detectAuthorizationError(e);if(t.isAuthError){if(this.log("\u{1F6A8} Authorization error detected:",{errorType:t.errorType,shouldLogout:t.shouldTriggerLogout}),t.isRefreshTokenInvalid||t.isTokenRefreshFailed)return this.log("Refresh token invalid, emitting TOKEN_REFRESH_FAILED event"),H.emit("TOKEN_REFRESH_FAILED",{message:t.userFriendlyMessage,error:t.errorDetails,source:"SessionManager.setupResponseInterceptor"}),e;t.shouldTriggerLogout&&(await v.hasValidTokens()&&!t.isIrrecoverable?(this.log("Access token expired, emitting TOKEN_EXPIRED event"),H.emit("TOKEN_EXPIRED",{message:"Access token expired, refresh needed",error:t.errorDetails,source:"SessionManager.setupResponseInterceptor"})):(this.log("No valid tokens or irrecoverable error, emitting SESSION_EXPIRED event"),H.emit("SESSION_EXPIRED",{message:t.userFriendlyMessage,error:t.errorDetails,source:"SessionManager.setupResponseInterceptor"})))}return e}),this.log("Response interceptor configured (non-blocking mode)")}async ensureCrudifyInitialized(){if(!this.crudifyInitialized)try{this.log("Initializing crudify SDK...");let e=N.getTokenData();if(e&&e.endpoint){this.log("Crudify already initialized by another service"),this.crudifyInitialized=!0;return}let t=this.config.env||"stg";N.config(t);let i=this.config.publicApiKey,n=this.config.enableLogging?"debug":"none",s=await N.init(i,n);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(e){throw c.error("[SessionManager] Failed to initialize crudify",e instanceof Error?e:{message:String(e)}),e}}detectAuthorizationError(e){let t={isAuthError:!1,isRefreshTokenInvalid:!1,isTokenRefreshFailed:!1,isTokenExpired:!1,isUnauthorized:!1,isIrrecoverable:!1,shouldTriggerLogout:!1,errorType:"",errorDetails:null,userFriendlyMessage:""};if(e.errors&&Array.isArray(e.errors)){let i=e.errors.find(n=>n.errorType==="Unauthorized"||n.message?.includes("Unauthorized")||n.message?.includes("Not Authorized")||n.message?.includes("NOT_AUTHORIZED")||n.message?.includes("Token")||n.message?.includes("TOKEN")||n.message?.includes("Authentication")||n.message?.includes("UNAUTHENTICATED")||n.extensions?.code==="UNAUTHENTICATED"||n.extensions?.code==="FORBIDDEN");i&&(t.isAuthError=!0,t.errorType="GraphQL Array",t.errorDetails=i,t.shouldTriggerLogout=!0,t.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.",(i.message?.includes("TOKEN")||i.message?.includes("Token"))&&(t.isTokenExpired=!0),i.extensions?.code==="UNAUTHENTICATED"&&(t.isUnauthorized=!0))}if(!t.isAuthError&&e.errors&&typeof e.errors=="object"&&!Array.isArray(e.errors)){let n=Object.values(e.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")));n&&typeof n=="string"&&(t.isAuthError=!0,t.errorType="GraphQL Object",t.errorDetails=e.errors,t.shouldTriggerLogout=!0,n.includes("TOKEN_REFRESH_FAILED")?(t.isTokenRefreshFailed=!0,t.isRefreshTokenInvalid=!0,t.isIrrecoverable=!0,t.userFriendlyMessage="Tu sesi\xF3n ha caducado. Por favor, inicia sesi\xF3n nuevamente."):n.includes("TOKEN_HAS_EXPIRED")||n.includes("SESSION_EXPIRED")?(t.isTokenExpired=!0,t.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."):n.includes("INVALID_TOKEN")?(t.isTokenExpired=!0,t.isIrrecoverable=!0,t.userFriendlyMessage="Token inv\xE1lido. Por favor, inicia sesi\xF3n nuevamente."):t.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!t.isAuthError&&e.data?.response?.status){let i=e.data.response.status.toUpperCase();(i==="UNAUTHORIZED"||i==="UNAUTHENTICATED")&&(t.isAuthError=!0,t.errorType="Status",t.errorDetails=e.data.response,t.isUnauthorized=!0,t.shouldTriggerLogout=!0,t.isIrrecoverable=!0,t.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!t.isAuthError&&e.data?.response?.data)try{let i=typeof e.data.response.data=="string"?JSON.parse(e.data.response.data):e.data.response.data;(i.error==="REFRESH_TOKEN_INVALID"||i.error==="TOKEN_EXPIRED"||i.error==="INVALID_TOKEN")&&(t.isAuthError=!0,t.errorType="Parsed Data",t.errorDetails=i,t.shouldTriggerLogout=!0,t.isIrrecoverable=!0,i.error==="REFRESH_TOKEN_INVALID"?(t.isRefreshTokenInvalid=!0,t.isTokenRefreshFailed=!0,t.userFriendlyMessage="Tu sesi\xF3n ha caducado. Por favor, inicia sesi\xF3n nuevamente."):(t.isTokenExpired=!0,t.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."))}catch{}if(!t.isAuthError&&e.errorCode){let i=String(e.errorCode).toUpperCase();(i==="UNAUTHORIZED"||i==="UNAUTHENTICATED"||i==="TOKEN_EXPIRED"||i==="INVALID_TOKEN")&&(t.isAuthError=!0,t.errorType="Error Code",t.errorDetails={errorCode:i},t.shouldTriggerLogout=!0,i==="TOKEN_EXPIRED"?t.isTokenExpired=!0:t.isUnauthorized=!0,t.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}return t}updateLastActivity(){this.lastActivityTime=Date.now(),this.log("Last activity updated")}getTimeSinceLastActivity(){return this.lastActivityTime===0?0:Date.now()-this.lastActivityTime}checkInactivity(){let e=this.getTimeSinceLastActivity();if(this.lastActivityTime===0)return"none";let t=1800*1e3;return e>t?(this.log(`Inactivity timeout: ${Math.floor(e/6e4)} minutes since last activity`),"logout"):"none"}async clearSession(){j.clearCrossSubdomainCookie(this.config.env),await v.clearTokens(),await N.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?Fe("SESSION_EXPIRED",{translateFn:this.config.translateFn,enableDebug:this.config.enableLogging}):"Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."}log(e,t){this.config.enableLogging&&c.debug(`[SessionManager] ${e}`,t)}formatError(e){return e?typeof e=="string"?e:typeof e=="object"?Object.values(e).flat().map(String).join(", "):"Authentication failed":"Unknown error"}};import{useEffect as $t,useCallback as J}from"react";import{useState as Ut,useCallback as ee}from"react";var Ge={isAuthenticated:!1,isLoading:!0,isLoggingOut:!1,isInitialized:!1,tokens:null,error:null};function _e(){let[r,e]=Ut(Ge),t=ee(o=>{e(f=>({...f,isLoading:o}))},[]),i=ee((o,f)=>{e(E=>({...E,isAuthenticated:o,tokens:f,error:o?null:E.error}))},[]),n=ee(o=>{e(f=>({...f,isLoggingOut:o}))},[]),s=ee(o=>{e(f=>({...f,error:o}))},[]),l=ee(o=>{e(f=>({...f,isInitialized:o}))},[]);return{state:r,setState:e,setLoading:t,setAuthenticated:i,setLoggingOut:n,setError:s,setInitialized:l}}import{useCallback as le}from"react";var ae={AGGRESSIVE:3e4,MODERATE:6e4,RELAXED:12e4},Te={AGGRESSIVE:300*1e3,MODERATE:1800*1e3},Ve=.5;function $e(r){return r?r.expiresAt-Date.now()<3e5:!1}function Ye(r){return r?Math.max(0,r.expiresAt-Date.now()):0}function We(r){return r?Math.max(0,r.refreshExpiresAt-Date.now()):0}function Y(r){return r.crudifyTokens.accessToken?{accessToken:r.crudifyTokens.accessToken,refreshToken:r.crudifyTokens.refreshToken||"",expiresAt:r.crudifyTokens.expiresAt,refreshExpiresAt:r.crudifyTokens.refreshExpiresAt}:null}function Be(r){let{sessionManager:e,stateManager:t}=r,i=le(async(o,f)=>{t.setState(E=>({...E,isLoading:!0,isLoggingOut:!1,error:null}));try{let E=await e.login(o,f);return E.success&&E.tokens?t.setState(b=>({...b,isAuthenticated:!0,tokens:E.tokens,isLoading:!1,isLoggingOut:!1,error:null})):t.setState(b=>({...b,isAuthenticated:!1,tokens:null,isLoading:!1,isLoggingOut:!1,error:null})),E}catch(E){let b=E instanceof Error?E.message:"Login failed";c.error("[useSession] Login error",E instanceof Error?E:{message:b});let S=b.includes("INVALID_CREDENTIALS")||b.includes("Invalid email")||b.includes("Invalid password")||b.includes("credentials");return t.setState(m=>({...m,isAuthenticated:!1,tokens:null,isLoading:!1,isLoggingOut:!1,error:S?null:b})),{success:!1,error:b}}},[e,t]),n=le(async()=>{t.setState(o=>({...o,isLoading:!0,isLoggingOut:!0}));try{await e.logout(),t.setState(o=>({...o,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))}catch(o){t.setState(f=>({...f,isAuthenticated:!1,tokens:null,isLoading:!1,error:o instanceof Error?o.message:"Logout error"}))}},[e,t]),s=le(async()=>{try{let o=await e.refreshTokens();if(o){let f=await e.getTokenInfo();t.setState(E=>({...E,tokens:Y(f),error:null}))}else t.setState(f=>({...f,isAuthenticated:!1,tokens:null,error:"Token refresh failed"}));return o}catch(o){return t.setState(f=>({...f,isAuthenticated:!1,tokens:null,error:o instanceof Error?o.message:"Token refresh failed"})),!1}},[e,t]),l=le(()=>{t.setError(null)},[t]);return{login:i,logout:n,refreshTokens:s,clearError:l}}import{useEffect as Ht,useCallback as Gt}from"react";function _t(r){return r<Te.AGGRESSIVE?ae.AGGRESSIVE:r<Te.MODERATE?ae.MODERATE:ae.RELAXED}function Xe(r){let{isAuthenticated:e,tokens:t,sessionManager:i,onTokensRefreshed:n,onSessionExpired:s,onSetLoading:l,logout:o}=r,f=Gt(()=>{i.updateLastActivity()},[i]);Ht(()=>{if(!e||!t)return;let b=ze.getInstance().subscribe(f);window.addEventListener("popstate",f);let S,m=!0,I=async()=>{if(!m)return;let k=(await i.getTokenInfo()).crudifyTokens.expiresIn||0,R=_t(k);S=setTimeout(async()=>{if(!m)return;if(i.isRefreshing()){I();return}let x=await i.getTokenInfo(),O=x.crudifyTokens.expiresIn||0,z=((x.crudifyTokens.expiresAt||0)-(Date.now()-O))*Ve;if(O>0&&O<=z)if(l(!0),await i.refreshTokens()){let Z=await i.getTokenInfo();n(Y(Z)),l(!1)}else n(null),s(),l(!1);i.getTimeSinceLastActivity()>18e5?await o():m&&I()},R)};return I(),()=>{m=!1,clearTimeout(S),window.removeEventListener("popstate",f),b()}},[e,t,i,f,n,s,l,o])}import{useEffect as Vt}from"react";function Ze(r){let{sessionManager:e,onTokensUpdated:t,onSessionExpired:i,onSetLoading:n,onSetError:s}=r;Vt(()=>{let l=H.subscribe(async o=>{if(o.type==="TOKEN_EXPIRED"){if(e.isRefreshing())return;n(!0);try{if(await e.refreshTokens()){let E=await e.getTokenInfo();t(Y(E)),n(!1)}else H.emit("SESSION_EXPIRED",{message:"Failed to refresh token after detecting expiration",source:"useSession.TOKEN_EXPIRED handler"})}catch(f){H.emit("SESSION_EXPIRED",{message:f instanceof Error?f.message:"Unknown error during refresh",source:"useSession.TOKEN_EXPIRED handler (error)"})}}(o.type==="SESSION_EXPIRED"||o.type==="TOKEN_REFRESH_FAILED")&&(t(null),n(!1),o.details?.isColdStart!==!0&&o.details?.shouldShowNotification!==!1&&s(o.details?.message?.toString()||"Session expired"),i())});return()=>l()},[e,t,i,n,s])}import{useEffect as qe}from"react";function je(r){let{isAuthenticated:e,onTokensUpdated:t,onSessionExpired:i}=r;qe(()=>{let n=async l=>{switch(l.type){case"SESSION_STARTED":case"TOKEN_REFRESHED":try{await v.ensureInitialized();let o=await v.getTokens();o&&(c.debug(`[useCrossTabSync] Syncing ${l.type} from tab ${l.tabId}`),t(o))}catch(o){c.warn("[useCrossTabSync] Failed to read tokens after cross-tab event",{error:o instanceof Error?o.message:String(o)})}break;case"SESSION_ENDED":try{await v.hasValidTokens()||(c.debug(`[useCrossTabSync] Syncing SESSION_ENDED from tab ${l.tabId}`),t(null),e&&i())}catch(o){c.warn("[useCrossTabSync] Failed to verify tokens after logout event",{error:o instanceof Error?o.message:String(o)})}break;case"SESSION_PING":case"SESSION_PONG":break}},s=$.subscribe(n);return()=>s()},[e,t,i]),qe(()=>{let n=v.subscribeToChanges(async(s,l,o)=>{if(l===v.SYNC_EVENTS.TOKENS_CLEARED){if(await v.hasValidTokens())return;o&&e?(t(null),i()):o&&t(null)}else l===v.SYNC_EVENTS.TOKENS_UPDATED&&s&&t(s)});return()=>n()},[e,t,i])}async function Je(r){let{sessionManager:e,options:t,stateActions:i}=r;try{i.setState(o=>({...o,isLoading:!0,error:null}));let n={autoRestore:t.autoRestore??!0,enableLogging:t.enableLogging??!1,showNotification:t.showNotification,translateFn:t.translateFn,apiEndpointAdmin:t.apiEndpointAdmin,apiKeyEndpointAdmin:t.apiKeyEndpointAdmin,publicApiKey:t.publicApiKey,env:t.env||"stg",onSessionExpired:()=>{let o=e.getIsSessionActive();i.setState(f=>({...f,isAuthenticated:!1,tokens:null,error:o?"Session expired":null})),t.onSessionExpired?.()},onSessionRestored:o=>{i.setState(f=>({...f,isAuthenticated:!0,tokens:o,error:null})),t.onSessionRestored?.(o)},onLoginSuccess:o=>{i.setState(f=>({...f,isAuthenticated:!0,tokens:o,error:null}))},onLogout:()=>{i.setState(o=>({...o,isAuthenticated:!1,tokens:null,error:null}))}};await e.initialize(n),e.setupResponseInterceptor();let s=await e.isAuthenticated(),l=await e.getTokenInfo();i.setState(o=>({...o,isAuthenticated:s,isInitialized:!0,isLoading:!1,isLoggingOut:!1,tokens:Y(l)}))}catch(n){let s=n instanceof Error?n.message:"Initialization failed";c.error("[useSession] Initialize failed",n instanceof Error?n:{message:s}),i.setState(l=>({...l,isLoading:!1,isInitialized:!0,isLoggingOut:!1,error:s}))}}function ve(r={}){let e=oe.getInstance(),t=_e(),{state:i}=t,{login:n,logout:s,refreshTokens:l,clearError:o}=Be({sessionManager:e,stateManager:t}),f=J(g=>{t.setAuthenticated(!!g,g)},[t]),E=J(()=>{t.setAuthenticated(!1,null),r.onSessionExpired?.()},[t,r.onSessionExpired]),b=J(g=>{t.setLoading(g)},[t]),S=J(g=>{t.setError(g)},[t]);$t(()=>{Je({sessionManager:e,options:r,stateActions:t})},[]),Xe({isAuthenticated:i.isAuthenticated,tokens:i.tokens,sessionManager:e,onTokensRefreshed:f,onSessionExpired:E,onSetLoading:b,logout:s}),Ze({sessionManager:e,onTokensUpdated:f,onSessionExpired:E,onSetLoading:b,onSetError:S}),je({isAuthenticated:i.isAuthenticated,onTokensUpdated:f,onSessionExpired:E});let m=J(()=>{e.updateLastActivity()},[e]),I=J(async()=>e.getTokenInfo(),[e]);return{...i,login:n,logout:s,refreshTokens:l,clearError:o,getTokenInfo:I,updateActivity:m,isExpiringSoon:$e(i.tokens),expiresIn:Ye(i.tokens),refreshExpiresIn:We(i.tokens)}}import{useState as Qe,createContext as Yt,useContext as Wt,useCallback as ce,useEffect as Bt}from"react";import{Snackbar as Xt,Alert as Zt,Box as qt,Portal as jt}from"@mui/material";import{v4 as Jt}from"uuid";import Qt from"dompurify";import{jsx as X,jsxs as ii}from"react/jsx-runtime";var et=Yt(null),ei=r=>Qt.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}),be=({children:r,maxNotifications:e=5,defaultAutoHideDuration:t=6e3,position:i={vertical:"top",horizontal:"right"},enabled:n=!1,allowHtml:s=!1})=>{let[l,o]=Qe([]),f=ce((m,I="info",g)=>{if(!n)return"";if(!m||typeof m!="string")return c.warn("GlobalNotificationProvider: Invalid message provided"),"";m.length>1e3&&(c.warn("GlobalNotificationProvider: Message too long, truncating"),m=m.substring(0,1e3)+"...");let k=Jt(),R={id:k,message:m,severity:I,autoHideDuration:g?.autoHideDuration??t,persistent:g?.persistent??!1,allowHtml:g?.allowHtml??s};return o(x=>[...x.length>=e?x.slice(-(e-1)):x,R]),k},[e,t,n,s]),E=ce(m=>{o(I=>I.filter(g=>g.id!==m))},[]),b=ce(()=>{o([])},[]),S={showNotification:f,hideNotification:E,clearAllNotifications:b};return ii(et.Provider,{value:S,children:[r,n&&X(jt,{children:X(qt,{sx:{position:"fixed",zIndex:9999,[i.vertical]:(i.vertical==="top",24),[i.horizontal]:i.horizontal==="right"||i.horizontal==="left"?24:"50%",...i.horizontal==="center"&&{transform:"translateX(-50%)"},display:"flex",flexDirection:i.vertical==="top"?"column":"column-reverse",gap:1,maxWidth:"400px",width:"auto"},children:l.map(m=>X(ti,{notification:m,onClose:()=>E(m.id)},m.id))})})]})},ti=({notification:r,onClose:e})=>{let[t,i]=Qe(!0),n=ce((s,l)=>{l!=="clickaway"&&(i(!1),setTimeout(e,300))},[e]);return Bt(()=>{if(!r.persistent&&r.autoHideDuration){let s=setTimeout(()=>{n()},r.autoHideDuration);return()=>clearTimeout(s)}},[r.autoHideDuration,r.persistent,n]),X(Xt,{open:t,onClose:n,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:X(Zt,{variant:"filled",severity:r.severity,onClose:n,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:r.allowHtml?X("span",{dangerouslySetInnerHTML:{__html:ei(r.message)}}):X("span",{children:r.message})})})},tt=()=>{let r=Wt(et);if(!r)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return r};import{createContext as ri,useContext as ni,useEffect as si,useState as te}from"react";import ie from"@nocios/crudify-sdk";var Ie=class r{constructor(){this.listeners=[];this.credentials=null;this.isReady=!1}static getInstance(){return r.instance||(r.instance=new r),r.instance}notifyCredentialsReady(e){this.credentials=e,this.isReady=!0,this.listeners.forEach(t=>{try{t(e)}catch(i){c.error("[CredentialsEventBus] Error in listener",i instanceof Error?i:{message:String(i)})}}),this.listeners=[]}waitForCredentials(){return this.isReady&&this.credentials?Promise.resolve(this.credentials):new Promise(e=>{this.listeners.push(e)})}reset(){this.credentials=null,this.isReady=!1,this.listeners=[]}areCredentialsReady(){return this.isReady&&this.credentials!==null}},ue=Ie.getInstance();import{jsx as oi}from"react/jsx-runtime";var it=ri(void 0),rt=({config:r,children:e})=>{let[t,i]=te(!0),[n,s]=te(null),[l,o]=te(!1),[f,E]=te(""),[b,S]=te();si(()=>{if(!r.publicApiKey){s("No publicApiKey provided"),i(!1),o(!1);return}let I=`${r.publicApiKey}-${r.env}`;if(I===f&&l){i(!1);return}(async()=>{i(!0),s(null),o(!1);try{ie.config(r.env||"prod");let k=await ie.init(r.publicApiKey,"none");if(S(k),typeof ie.transaction=="function"&&typeof ie.login=="function")o(!0),E(I),k.apiEndpointAdmin&&k.apiKeyEndpointAdmin&&ue.notifyCredentialsReady({apiUrl:k.apiEndpointAdmin,apiKey:k.apiKeyEndpointAdmin});else throw new Error("Crudify methods not properly initialized")}catch(k){let R=k instanceof Error?k.message:"Failed to initialize Crudify";c.error("[CrudifyProvider] Initialization error",k instanceof Error?k:{message:String(k)}),s(R),o(!1)}finally{i(!1)}})()},[r.publicApiKey,r.env,f,l]);let m={crudify:l?ie:null,isLoading:t,error:n,isInitialized:l,adminCredentials:b};return oi(it.Provider,{value:m,children:e})},nt=()=>{let r=ni(it);if(r===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return r};import ai,{createContext as li,useContext as ci,useMemo as ke}from"react";import{Fragment as di,jsx as D,jsxs as G}from"react/jsx-runtime";var ot=li(void 0);function st({children:r,options:e={},config:t,showNotifications:i=!1,notificationOptions:n={}}){let s;try{let{showNotification:g}=tt();s=g}catch{}let l={};try{let g=nt();g.isInitialized&&g.adminCredentials&&(l=g.adminCredentials)}catch{}let o=ke(()=>{let g=ye({publicApiKey:t?.publicApiKey,env:t?.env,enableDebug:e?.enableLogging});return{publicApiKey:g.publicApiKey,env:g.env||"prod"}},[t,e?.enableLogging]),f=ai.useMemo(()=>({...e,showNotification:s,apiEndpointAdmin:l.apiEndpointAdmin,apiKeyEndpointAdmin:l.apiKeyEndpointAdmin,publicApiKey:o.publicApiKey,env:o.env,onSessionExpired:()=>{e.onSessionExpired?.()}}),[e,s,l.apiEndpointAdmin,l.apiKeyEndpointAdmin,o]),E=ve(f),b=ke(()=>{let g=ye({publicApiKey:t?.publicApiKey,env:t?.env,appName:t?.appName,logo:t?.logo,loginActions:t?.loginActions,enableDebug:e?.enableLogging});return{publicApiKey:g.publicApiKey,env:g.env,appName:g.appName,loginActions:g.loginActions,logo:g.logo}},[t,e?.enableLogging]),S=ke(()=>{if(!E.tokens?.accessToken||!E.isAuthenticated)return null;try{let g=Ue(E.tokens.accessToken);if(g&&g.sub&&g.email&&g.subscriber){let k={_id:g.sub,email:g.email,subscriberKey:g.subscriber};return Object.keys(g).forEach(R=>{["sub","email","subscriber"].includes(R)||(k[R]=g[R])}),k}}catch(g){c.error("Error decoding JWT token for sessionData",g instanceof Error?g:{message:String(g)})}return null},[E.tokens?.accessToken,E.isAuthenticated]),m={...E,sessionData:S,config:b},I={enabled:i,maxNotifications:n.maxNotifications||5,defaultAutoHideDuration:n.defaultAutoHideDuration||6e3,position:n.position||{vertical:"top",horizontal:"right"}};return D(ot.Provider,{value:m,children:r})}function Jr(r){let e={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?D(rt,{config:{publicApiKey:r.config.publicApiKey,env:r.config.env||"prod",appName:r.config.appName,loginActions:r.config.loginActions,logo:r.config.logo},children:D(be,{...e,children:D(st,{...r})})}):D(be,{...e,children:D(st,{...r})})}function ui(){let r=ci(ot);if(r===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return r}function Qr(){let r=ui();return r.isInitialized?G("div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[D("h4",{children:"Session Debug Info"}),G("div",{children:[D("strong",{children:"Authenticated:"})," ",r.isAuthenticated?"Yes":"No"]}),G("div",{children:[D("strong",{children:"Loading:"})," ",r.isLoading?"Yes":"No"]}),G("div",{children:[D("strong",{children:"Error:"})," ",r.error||"None"]}),r.tokens&&G(di,{children:[G("div",{children:[D("strong",{children:"Access Token:"})," ",r.tokens.accessToken.substring(0,20),"..."]}),G("div",{children:[D("strong",{children:"Refresh Token:"})," ",r.tokens.refreshToken.substring(0,20),"..."]}),G("div",{children:[D("strong",{children:"Access Expires In:"})," ",Math.round(r.expiresIn/1e3/60)," minutes"]}),G("div",{children:[D("strong",{children:"Refresh Expires In:"})," ",Math.round(r.refreshExpiresIn/1e3/60/60)," hours"]}),G("div",{children:[D("strong",{children:"Expiring Soon:"})," ",r.isExpiringSoon?"Yes":"No"]})]})]}):D("div",{children:"Session not initialized"})}import{useState as de,useEffect as at,useCallback as lt,useRef as fe}from"react";import fi from"@nocios/crudify-sdk";var on=(r={})=>{let{autoFetch:e=!0,retryOnError:t=!1,maxRetries:i=3}=r,[n,s]=de(null),[l,o]=de(!1),[f,E]=de(null),[b,S]=de({}),m=fe(null),I=fe(!0),g=fe(0),k=fe(0),R=lt(()=>{s(null),E(null),o(!1),S({})},[]),x=lt(async()=>{let O=Ke();if(!O){I.current&&(E("No user email available"),o(!1));return}m.current&&m.current.abort();let C=new AbortController;m.current=C;let F=++g.current;try{I.current&&(o(!0),E(null));let z=await fi.readItems("users",{filter:{email:O},pagination:{limit:1}});if(F===g.current&&I.current&&!C.signal.aborted){let L=z.data;if(z.success&&L&&L.length>0){let T=L[0];s(T);let Z={fullProfile:T,totalFields:Object.keys(T).length,displayData:{id:T.id,email:T.email,username:T.username,firstName:T.firstName,lastName:T.lastName,fullName:T.fullName||`${T.firstName||""} ${T.lastName||""}`.trim(),role:T.role,permissions:T.permissions||[],isActive:T.isActive,lastLogin:T.lastLogin,createdAt:T.createdAt,updatedAt:T.updatedAt,...Object.keys(T).filter(V=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(V)).reduce((V,ne)=>({...V,[ne]:T[ne]}),{})}};S(Z),E(null),k.current=0}else E("User profile not found"),s(null),S({})}}catch(z){if(F===g.current&&I.current){let L=z;if(L.name==="AbortError")return;t&&k.current<i&&(L.message?.includes("Network Error")||L.message?.includes("Failed to fetch"))?(k.current++,setTimeout(()=>{I.current&&x()},1e3*k.current)):(E("Failed to load user profile"),s(null),S({}))}}finally{F===g.current&&I.current&&o(!1),m.current===C&&(m.current=null)}},[t,i]);return at(()=>{e&&x()},[e,x]),at(()=>(I.current=!0,()=>{I.current=!1,m.current&&(m.current.abort(),m.current=null)}),[]),{userProfile:n,loading:l,error:f,extendedData:b,refreshProfile:x,clearProfile:R}};import{useState as Ae,useEffect as gi,useCallback as ge,useRef as pi}from"react";import mi from"@nocios/crudify-sdk";var un=(r,e={})=>{let{autoFetch:t=!0,onSuccess:i,onError:n}=e,{prefix:s,padding:l=0,separator:o=""}=r,[f,E]=Ae(""),[b,S]=Ae(!1),[m,I]=Ae(null),g=pi(!1),k=ge(C=>{let F=String(C).padStart(l,"0");return`${s}${o}${F}`},[s,l,o]),R=ge(async()=>{S(!0),I(null);try{let C=await mi.getNextSequence(s),F=C.data;if(C.success&&F?.value){let z=k(F.value);E(z),i?.(z)}else{let z=C.errors?._error?.[0]||"Failed to generate code";I(z),n?.(z)}}catch(C){let F=C instanceof Error?C.message:"Unknown error";I(F),n?.(F)}finally{S(!1)}},[s,k,i,n]),x=ge(async()=>{await R()},[R]),O=ge(()=>{I(null)},[]);return gi(()=>{t&&!f&&!g.current&&(g.current=!0,R())},[t,f,R]),{value:f,loading:b,error:m,regenerate:x,clearError:O}};import xe from"@nocios/crudify-sdk";var Ce=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(e){let{priority:t,publicApiKey:i,env:n,enableLogging:s,requestedBy:l}=e;if(this.state.status==="INITIALIZED"){this.state.publicApiKey!==i&&c.warn(`[CrudifyInitialization] ${l} 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&&c.debug(`[CrudifyInitialization] ${l} waiting for ongoing initialization...`),this.initializationPromise;if(t==="LOW"&&this.highPriorityInitializerPresent&&this.state.status==="UNINITIALIZED"){if(s&&c.debug(`[CrudifyInitialization] ${l} (LOW priority) waiting for HIGH priority initializer...`),this.waitingForHighPriority.add(l),await this.waitForHighPriorityOrTimeout(s),this.waitingForHighPriority.delete(l),this.getState().status==="INITIALIZED"){s&&c.debug(`[CrudifyInitialization] ${l} found initialization completed by HIGH priority`);return}s&&c.warn(`[CrudifyInitialization] ${l} timeout waiting for HIGH priority, initializing with LOW priority`)}t==="HIGH"&&this.state.status==="INITIALIZING"&&this.state.priority==="LOW"&&(c.warn(`[CrudifyInitialization] HIGH priority request from ${l} interrupting LOW priority initialization by ${this.state.initializedBy}`),this.state.status="UNINITIALIZED",this.initializationPromise=null),s&&c.debug(`[CrudifyInitialization] ${l} starting initialization (${t} priority)...`),this.state.status="INITIALIZING",this.state.priority=t,this.state.initializedBy=l,this.initializationPromise=this.performInitialization(i,n,s);try{await this.initializationPromise,this.state.status="INITIALIZED",this.state.publicApiKey=i,this.state.env=n,this.state.error=null,s&&c.info(`[CrudifyInitialization] Successfully initialized by ${l} (${t} priority)`)}catch(o){throw this.state.status="ERROR",this.state.error=o instanceof Error?o:new Error(String(o)),this.initializationPromise=null,c.error(`[CrudifyInitialization] Initialization failed for ${l}`,o instanceof Error?o:{message:String(o)}),o}}async waitForHighPriorityOrTimeout(e){return new Promise(t=>{let n=0,s=setInterval(()=>{if(n+=10,this.state.status==="INITIALIZED"&&this.state.priority==="HIGH"){clearInterval(s),t();return}if(this.state.status==="INITIALIZING"&&this.state.priority==="HIGH"){n=0;return}n>=this.HIGH_PRIORITY_WAIT_TIMEOUT&&(clearInterval(s),e&&c.debug(`[CrudifyInitialization] Timeout waiting for HIGH priority (${this.HIGH_PRIORITY_WAIT_TIMEOUT}ms)`),t())},10)})}async performInitialization(e,t,i){let n=xe.getTokenData();if(n&&n.endpoint){i&&c.debug("[CrudifyInitialization] SDK already initialized externally");return}xe.config(t);let s=i?"debug":"none",l=await xe.init(e,s);if(l.success===!1)throw new Error(`Crudify initialization failed: ${JSON.stringify(l.errors||"Unknown error")}`);l.apiEndpointAdmin&&l.apiKeyEndpointAdmin&&ue.notifyCredentialsReady({apiUrl:l.apiEndpointAdmin,apiKey:l.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}}},re=Ce.getInstance();import{useState as pe,useCallback as P,useRef as hi,useMemo as Q}from"react";import me from"@nocios/crudify-sdk";var ut=r=>{let e=new Uint8Array(r);return crypto.getRandomValues(e),Array.from(e,t=>t.toString(36).padStart(2,"0")).join("").substring(0,r)},ct=()=>`file_${Date.now()}_${ut(7)}`,yi=r=>{let e=r.lastIndexOf("."),t=e>0?r.substring(e):"",i=Date.now(),n=ut(6);return`${i}_${n}${t}`},we=(r,e)=>{if(r.startsWith("http://")||r.startsWith("https://"))try{let t=new URL(r);return t.pathname.startsWith("/")?t.pathname.substring(1):t.pathname}catch{if(e&&r.startsWith(e))return r.substring(e.length)}return e&&r.startsWith(e)?r.substring(e.length):r},Tn=(r={})=>{let{acceptedTypes:e,maxFileSize:t=10*1024*1024,maxFiles:i,minFiles:n=0,visibility:s="private",onUploadComplete:l,onUploadError:o,onFileRemoved:f,onFilesChange:E,mode:b="edit"}=r,[S,m]=pe([]),[I,g]=pe(!1),[k,R]=pe(!1),[x,O]=pe([]),C=hi(new Map),F=P(()=>{g(!0)},[]),z=P(()=>{R(!0),g(!0)},[]),L=P((u,p)=>{m(d=>d.map(y=>y.id===u?{...y,...p}:y))},[]),T=P(u=>{E?.(u)},[E]),Z=P(u=>e&&e.length>0&&!e.includes(u.type)?{valid:!1,error:`File type not allowed: ${u.type}`}:u.size>t?{valid:!1,error:`File exceeds maximum size of ${(t/1048576).toFixed(1)}MB`}:{valid:!0},[e,t]),V=P(async(u,p)=>{try{if(!re.isInitialized())throw new Error("Crudify is not initialized. Please wait for the application to finish loading.");let d=yi(p.name),h=await me.generateSignedUrl({fileName:d,contentType:p.type,visibility:s});if(!h.success||!h.data)throw new Error("Failed to get upload URL");let y=h.data,{uploadUrl:w,s3Key:A,publicUrl:M}=y;if(!w||!A)throw new Error("Incomplete signed URL response");let W=A.indexOf("/"),Nt=W>0?A.substring(W+1):A;L(u.id,{status:"uploading",progress:0}),await new Promise((he,B)=>{let U=new XMLHttpRequest;U.upload.addEventListener("progress",_=>{if(_.lengthComputable){let Lt=Math.round(_.loaded/_.total*100);L(u.id,{progress:Lt})}}),U.addEventListener("load",()=>{U.status>=200&&U.status<300?he():B(new Error(`Upload failed with status ${U.status}`))}),U.addEventListener("error",()=>{B(new Error("Network error during upload"))}),U.addEventListener("abort",()=>{B(new Error("Upload cancelled"))}),U.open("PUT",w),U.setRequestHeader("Content-Type",p.type),U.send(p)});let Dt={status:"completed",progress:100,filePath:Nt,visibility:s,publicUrl:s==="public"?M:void 0,file:void 0};m(he=>{let B=he.map(_=>_.id===u.id?{..._,...Dt}:_);T(B);let U=B.find(_=>_.id===u.id);return U&&l?.(U),B})}catch(d){let h=d instanceof Error?d.message:"Unknown error";L(u.id,{status:"error",progress:0,errorMessage:h}),m(y=>{let w=y.find(A=>A.id===u.id);return w&&o?.(w,h),y})}},[L,l,o,s]),ne=P(async u=>{let p=Array.from(u),d=[];m(h=>{if(i!==void 0){let A=h.filter(W=>W.status!=="pendingDeletion"&&W.status!=="error").length,M=i-A;if(M<=0)return c.warn(`File limit of ${i} already reached`),h;p.length>M&&(p=p.slice(0,M),c.warn(`Only ${M} files will be added to not exceed limit`))}let y=[];for(let A of p){let M=Z(A),W={id:ct(),name:A.name,size:A.size,contentType:A.type,status:M.valid?"pending":"error",progress:0,createdAt:Date.now(),file:M.valid?A:void 0,errorMessage:M.error,isExisting:!1};y.push(W)}d=y;let w=[...h,...y];return T(w),w}),setTimeout(()=>{let h=d.filter(y=>y.status==="pending"&&y.file);for(let y of h)if(y.file){let w=V(y,y.file);C.current.set(y.id,w),w.finally(()=>{C.current.delete(y.id)})}},0)},[i,Z,V,T]),dt=P(async u=>{let p=S.find(h=>h.id===u);if(!p)return{needsConfirmation:!1,isExisting:!1};let d=p.isExisting===!0;return b==="create"||!d?{needsConfirmation:!0,isExisting:d}:(O(h=>[...h,u]),m(h=>{let y=h.map(A=>A.id===u?{...A,status:"pendingDeletion"}:A),w=y.filter(A=>A.status!=="pendingDeletion");return T(w),y}),{needsConfirmation:!1,isExisting:d})},[S,b,T]),ft=P(async u=>{let p=S.find(d=>d.id===u);if(!p)return{success:!1,error:"File not found"};if(!p.filePath)return m(d=>{let h=d.filter(y=>y.id!==u);return T(h),h}),{success:!0};try{if(!re.isInitialized())return{success:!1,error:"Crudify not initialized"};let d=we(p.filePath);return(await me.disableFile({filePath:d})).success?(m(y=>{let w=y.filter(A=>A.id!==u);return T(w),w}),f?.(p),{success:!0}):{success:!1,error:"Failed to delete file"}}catch(d){return{success:!1,error:d instanceof Error?d.message:"Unknown error"}}},[S,T,f]),gt=P(u=>{let p=S.find(d=>d.id===u);return!p||!p.isExisting?!1:(O(d=>d.filter(h=>h!==u)),m(d=>{let h=d.map(y=>y.id===u?{...y,status:"completed"}:y);return T(h),h}),!0)},[S,T]),pt=P(()=>{x.length!==0&&(m(u=>{let p=u.map(d=>x.includes(d.id)?{...d,status:"completed"}:d);return T(p),p}),O([]))},[x,T]),mt=P(async()=>{if(x.length===0)return{success:!0,errors:[]};let u=[],p=[];if(!re.isInitialized())return{success:!1,errors:["Crudify is not initialized. Please wait for the application to finish loading."]};for(let d of x){let h=S.find(y=>y.id===d);if(!h?.filePath){p.push(d);continue}try{let y=we(h.filePath);(await me.disableFile({filePath:y})).success?(p.push(d),f?.(h)):u.push(`Failed to delete ${h.name}`)}catch(y){u.push(`Error deleting ${h.name}: ${y instanceof Error?y.message:"Unknown error"}`)}}return p.length>0&&(m(d=>d.filter(y=>!p.includes(y.id))),O(d=>d.filter(h=>!p.includes(h)))),{success:u.length===0,errors:u}},[S,x,f]),ht=P(()=>{m([]),T([])},[T]),yt=P(async u=>{let p=S.find(h=>h.id===u);if(!p||p.status!=="error"||!p.file){c.warn("Cannot retry: file not found or no original file");return}L(u,{status:"pending",progress:0,errorMessage:void 0});let d=V(p,p.file);C.current.set(u,d),d.finally(()=>{C.current.delete(u)})},[S,L,V]),Et=P(async()=>{let u=Array.from(C.current.values());return u.length>0&&await Promise.allSettled(u),new Promise(p=>{setTimeout(()=>{m(d=>{let h=d.filter(y=>y.status==="completed"&&y.filePath).map(y=>y.filePath);return p(h),d})},0)})},[]),St=u=>{let p=u.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"}[p]||"application/octet-stream"},Tt=P((u,p)=>{let d=u.map(h=>{let y=we(h.filePath,p),w=y.includes("/public/")||y.startsWith("public/")?"public":"private",A=h.contentType||St(h.name);return{id:ct(),name:h.name,size:h.size||0,contentType:A,status:"completed",progress:100,filePath:y,visibility:w,createdAt:Date.now(),isExisting:!0}});m(d),T(d)},[T]),vt=P(async u=>{let p=S.find(d=>d.id===u);if(!p||!p.filePath)return null;if(p.visibility==="public"&&p.publicUrl)return p.publicUrl;try{if(!re.isInitialized())return null;let d=await me.getFileUrl({filePath:p.filePath,expiresIn:3600}),h=d.data;return d.success&&h?.url?h.url:null}catch{return null}},[S]),bt=Q(()=>S.some(u=>u.status==="uploading"||u.status==="pending"),[S]),It=Q(()=>S.filter(u=>u.status==="uploading"||u.status==="pending").length,[S]),kt=Q(()=>S.filter(u=>u.status==="completed"&&u.filePath).map(u=>u.filePath),[S]),q=Q(()=>S.filter(u=>u.status!=="pendingDeletion"),[S]),At=Q(()=>q.filter(u=>u.status==="completed"||u.status==="pending"||u.status==="uploading").length,[q]),{isValid:xt,validationError:Ct,validationErrorKey:wt,validationErrorParams:Rt}=Q(()=>{let u=q.filter(d=>d.status==="completed").length;if(u<n){let d=n===1?"file.validation.minFilesRequired":"file.validation.minFilesRequiredPlural";return{isValid:!1,validationError:d,validationErrorKey:d,validationErrorParams:{count:n}}}return i!==void 0&&u>i?{isValid:!1,validationError:"file.validation.maxFilesExceeded",validationErrorKey:"file.validation.maxFilesExceeded",validationErrorParams:{count:i}}:q.some(d=>d.status==="error")?{isValid:!1,validationError:"file.validation.filesWithErrors",validationErrorKey:"file.validation.filesWithErrors",validationErrorParams:{}}:{isValid:!0,validationError:null,validationErrorKey:null,validationErrorParams:{}}},[q,n,i]),Pt=x.length>0;return{files:S,activeFiles:q,activeFileCount:At,isUploading:bt,pendingCount:It,addFiles:ne,removeFile:dt,deleteFileImmediately:ft,restoreFile:gt,clearFiles:ht,retryUpload:yt,isValid:xt,validationError:Ct,validationErrorKey:wt,validationErrorParams:Rt,waitForUploads:Et,completedFilePaths:kt,initializeFiles:Tt,isTouched:I,markAsTouched:F,isSubmitted:k,markAsSubmitted:z,getPreviewUrl:vt,pendingDeletions:x,hasPendingDeletions:Pt,commitDeletions:mt,restorePendingDeletions:pt}};export{v as a,Ee as b,$ as c,oe as d,ve as e,be as f,tt as g,ue as h,rt as i,nt as j,Jr as k,ui as l,Qr as m,on as n,un as o,Ce as p,re as q,Tn as r};
|
package/dist/chunk-T6R65ROU.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } 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 _chunk6ONAT4QUjs = require('./chunk-6ONAT4QU.js');var _chunkCR5KJUSTjs = require('./chunk-CR5KJUST.js');var _react = require('react');var _crudifysdk = require('@nocios/crudify-sdk'); var _crudifysdk2 = _interopRequireDefault(_crudifysdk);var J=(w={})=>{let{autoFetch:c=!0,retryOnError:N=!1,maxRetries:g=3}=w,{isAuthenticated:T,isInitialized:I,sessionData:u,tokens:m}=_chunk6ONAT4QUjs.l.call(void 0, ),[R,d]=_react.useState.call(void 0, null),[p,A]=_react.useState.call(void 0, c&&T),[C,E]=_react.useState.call(void 0, null),f=_react.useRef.call(void 0, null),o=_react.useRef.call(void 0, !0),y=_react.useRef.call(void 0, 0),l=_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]),L=_react.useCallback.call(void 0, ()=>{d(null),E(null),A(!1),l.current=0},[]),U=_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}f.current&&f.current.abort();let e=new AbortController;f.current=e;let i=++y.current;try{o.current&&(A(!0),E(null));let s=await _crudifysdk2.default.readItems("users",{filter:{email:h},pagination:{limit:1}});if(i===y.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),l.current=0):(E("User profile not found in database"),d(null))}}catch(s){if(i===y.current&&o.current){let r=s;if(r.name==="AbortError")return;N&&l.current<g&&(_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")]))?(l.current++,setTimeout(()=>{o.current&&U()},1e3*l.current)):(E("Failed to load user profile from database"),d(null))}}finally{i===y.current&&o.current&&A(!1),f.current===e&&(f.current=null)}},[I,F,N,g]);return _react.useEffect.call(void 0, ()=>{c&&T&&I?U():T||L()},[c,T,I,U,L]),_react.useEffect.call(void 0, ()=>(o.current=!0,()=>{o.current=!1,f.current&&(f.current.abort(),f.current=null)}),[]),{user:{session:u,data:R},loading:p,error:C,refreshProfile:U,clearProfile:L}};var te=()=>{let{isAuthenticated:w,isLoading:c,isInitialized:N,tokens:g,error:T,sessionData:I,login:u,logout:m,refreshTokens:R,clearError:d,getTokenInfo:p,isExpiringSoon:A,expiresIn:C,refreshExpiresIn:E}=_chunk6ONAT4QUjs.l.call(void 0, ),f=_react.useCallback.call(void 0, y=>{y?_chunkCR5KJUSTjs.a.warn("useAuth.setToken() is deprecated. Use login() method instead for better security."):m()},[m]),o=_optionalChain([g, 'optionalAccess', _13 => _13.expiresAt])?new Date(g.expiresAt):null;return{isAuthenticated:w,loading:c,error:T,token:_optionalChain([g, 'optionalAccess', _14 => _14.accessToken])||null,user:I,tokenExpiration:o,setToken:f,logout:m,refreshToken:R,login:u,isExpiringSoon:A,expiresIn:C,refreshExpiresIn:E,getTokenInfo:p,clearError:d}};var ae=()=>{let{isInitialized:w,isLoading:c,error:N,isAuthenticated:g,login:T}=_chunk6ONAT4QUjs.l.call(void 0, ),I=_react.useCallback.call(void 0, ()=>w&&!c&&!N,[w,c,N]),u=_react.useCallback.call(void 0, async()=>new Promise((o,y)=>{let l=()=>{I()?o():N?y(new Error(N)):setTimeout(l,100)};l()}),[I,N]),m=_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,y,l)=>(await m(),await _crudifysdk2.default.readItems(o,y||{},l)),[m]),d=_react.useCallback.call(void 0, async(o,y,l)=>(await m(),await _crudifysdk2.default.readItem(o,y,l)),[m]),p=_react.useCallback.call(void 0, async(o,y,l)=>(await m(),await _crudifysdk2.default.createItem(o,y,l)),[m]),A=_react.useCallback.call(void 0, async(o,y,l)=>(await m(),await _crudifysdk2.default.updateItem(o,y,l)),[m]),C=_react.useCallback.call(void 0, async(o,y,l)=>(await m(),await _crudifysdk2.default.deleteItem(o,y,l)),[m]),E=_react.useCallback.call(void 0, async(o,y)=>(await m(),await _crudifysdk2.default.transaction(o,y)),[m]),f=_react.useCallback.call(void 0, async(o,y)=>{try{let l=await T(o,y);return l.success?{success:!0,data:l.tokens}:{success:!1,errors:l.error||"Login failed"}}catch(l){return{success:!1,errors:l instanceof Error?l.message:"Login failed"}}},[T]);return{readItems:R,readItem:d,createItem:p,updateItem:A,deleteItem:C,transaction:E,login:f,isInitialized:w,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 =(w={})=>{let{showNotification:c}=_chunk6ONAT4QUjs.g.call(void 0, ),{showSuccessNotifications:N=!1,showErrorNotifications:g=!0,customErrorMessages:T={},defaultErrorMessage:I="Ha ocurrido un error inesperado",autoHideDuration:u=6e3,appStructure:m=[],translateFn:R=e=>e}=w,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")},[]),p=_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:m.some(s=>s.key===e):!1,[N,m,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=p(t);if(n!==R("error.unknown")){if(A(r)&&i){let a=`action.${i}Singular`,O=p(a);if(O!==R("error.unknown"))return R(t,{item:O});{let D=`action.onSuccess.${r}WithoutItem`,x=p(D);return x!==R("error.unknown")?x:n}}return n}return R("base.success.transaction")},[p,R,A]),f=_react.useCallback.call(void 0, e=>{if(e.errorCode&&T[e.errorCode])return T[e.errorCode];if(e.errorCode&&M[e.errorCode])return p(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=p(s);if(r!==R("error.unknown"))return r}}if(typeof e.data=="string"&&e.data.startsWith("errors.")){let i=p(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 p(M[a]);let O=[`errors.auth.${a}`,`errors.data.${a}`,`errors.system.${a}`,`errors.${a}`];for(let D of O){let x=p(D);if(x!==p("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")?p("resetPassword.linkExpired","El enlace ha expirado"):n.includes("invalid")?p("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):t.response.message}}catch (e4){return r.toLowerCase().includes("expired")?p("resetPassword.linkExpired","El enlace ha expirado"):r.toLowerCase().includes("invalid")?p("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):r}}return p("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"?p("errors.system.DATABASE_CONNECTION_ERROR"):`${p("errors.data.FIELD_ERROR")}: ${i.join(", ")}`}return I||R("error.unknown")},[T,I,R,p]),o=_react.useCallback.call(void 0, e=>e.errorCode&&Y[e.errorCode]?Y[e.errorCode]:"error",[]),y=_react.useCallback.call(void 0, async(e,i,s)=>{let r=await _crudifysdk2.default.createItem(e,i,s);if(!r.success&&g&&d(r)){let t=f(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},[g,C,c,f,o,E,u,d]),l=_react.useCallback.call(void 0, async(e,i,s)=>{let r=await _crudifysdk2.default.updateItem(e,i,s),t=_optionalChain([s, 'optionalAccess', _37 => _37.skipNotifications])===!0;if(!t&&!r.success&&g&&d(r)){let n=f(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 D=E(a,O,n);c(D,"success",{autoHideDuration:u})}}return r},[g,C,c,f,o,E,u,d]),F=_react.useCallback.call(void 0, async(e,i,s)=>{let r=await _crudifysdk2.default.deleteItem(e,i,s);if(!r.success&&g&&d(r)){let t=f(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},[g,C,c,f,o,E,u,d]),L=_react.useCallback.call(void 0, async(e,i,s)=>{let r=await _crudifysdk2.default.readItem(e,i,s);if(!r.success&&g&&d(r)){let t=f(r),n=o(r);c(t,n,{autoHideDuration:u})}return r},[g,c,f,o,u,d]),U=_react.useCallback.call(void 0, async(e,i,s)=>{let r=await _crudifysdk2.default.readItems(e,i,s);if(!r.success&&g&&d(r)){let t=f(r),n=o(r);c(t,n,{autoHideDuration:u})}return r},[g,c,f,o,u,d]),q=_react.useCallback.call(void 0, async(e,i)=>{let s=await _crudifysdk2.default.transaction(e,i),r=_optionalChain([i, 'optionalAccess', _44 => _44.skipNotifications])===!0;if(!r&&!s.success&&g&&d(s)){let t=f(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;else if(Array.isArray(e)&&e.length>0&&"operation"in e[0]&&e[0].operation){t=e[0].operation;let O=m.find(D=>D.key===t);O&&(a=O,n=O.moduleKey)}if(C(t,n)){let O=E(t,n,_nullishCoalesce(a, () => (void 0)));c(O,"success",{autoHideDuration:u})}}return s},[g,C,c,f,o,E,u,d,m]),h=_react.useCallback.call(void 0, (e,i)=>{if(!e.success&&g&&d(e)){let s=f(e),r=o(e);c(s,r,{autoHideDuration:u})}else e.success&&N&&i&&c(i,"success",{autoHideDuration:u});return e},[g,N,c,f,o,u,d,R]);return{createItem:y,updateItem:l,deleteItem:F,readItem:L,readItems:U,transaction:q,handleResponse:h,getErrorMessage:f,getErrorSeverity:o,shouldShowNotification:d}};exports.a = J; exports.b = te; exports.c = ae; exports.d = de;
|