@nocios/crudify-components 2.0.0 → 2.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-47SM45CV.js +1 -0
- package/dist/{chunk-4VN5YRYZ.js → chunk-5HFI5CZ5.js} +1 -1
- package/dist/chunk-72CJ7DHU.mjs +1 -0
- package/dist/{chunk-XZ6OGRJR.mjs → chunk-C35OZ7PU.mjs} +1 -1
- package/dist/chunk-ISEMM6ZR.mjs +1 -0
- package/dist/chunk-JNEWPO2J.mjs +1 -0
- package/dist/chunk-MFYHD6S5.js +1 -0
- package/dist/chunk-MGJZTOEM.mjs +1 -0
- package/dist/chunk-QXKVRWT3.js +1 -0
- package/dist/{chunk-RORGWKHP.js → chunk-U5NSADER.js} +1 -1
- package/dist/components.js +1 -1
- package/dist/components.mjs +1 -1
- package/dist/errorTranslation-DGdrMidg.d.ts +143 -0
- package/dist/errorTranslation-qwwQTvCO.d.mts +143 -0
- package/dist/hooks.js +1 -1
- package/dist/hooks.mjs +1 -1
- package/dist/index.d.mts +45 -8
- package/dist/index.d.ts +45 -8
- package/dist/index.js +2 -2
- package/dist/index.mjs +2 -2
- package/dist/utils.d.mts +48 -2
- package/dist/utils.d.ts +48 -2
- package/dist/utils.js +1 -1
- package/dist/utils.mjs +1 -1
- package/package.json +1 -1
- package/dist/chunk-4ILUXVPW.mjs +0 -1
- package/dist/chunk-7ORHVSWL.mjs +0 -1
- package/dist/chunk-AOPB3KXB.js +0 -1
- package/dist/chunk-CR5KJUST.js +0 -1
- package/dist/chunk-GT7B57S5.mjs +0 -1
- package/dist/chunk-LK6QVSG4.js +0 -1
- package/dist/chunk-RJBX4MWF.mjs +0 -1
- package/dist/errorTranslation-By5Av0tL.d.ts +0 -335
- package/dist/errorTranslation-DeeDj7Vt.d.mts +0 -335
package/dist/chunk-LK6QVSG4.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 _chunkCR5KJUSTjs = require('./chunk-CR5KJUST.js');var ze="crudify_storage_version",Ue=2,a=class a{static setStorageType(t){a.storageType=t}static async initialize(){if(!(a.encryptionKey&&a.salt))return a.initPromise||(a.initPromise=(async()=>{let e=null;for(let i=1;i<=3;i++)try{a.checkStorageVersion(),a.salt=a.getOrCreateSalt(),a.fingerprint=await a.generateFingerprint(),a.encryptionKey=await _chunkCR5KJUSTjs.h.call(void 0, a.fingerprint,a.salt);return}catch(n){e=n instanceof Error?n:new Error(String(n)),i<3&&await new Promise(s=>setTimeout(s,100*i))}throw _chunkCR5KJUSTjs.a.error("Crudify: Failed to initialize encryption after retries",_nullishCoalesce(e, () => ({message:"Unknown error"}))),e})()),a.initPromise}static checkStorageVersion(){try{if(parseInt(localStorage.getItem(ze)||"1",10)<Ue){let e=a.getStorage();e&&e.removeItem(a.TOKEN_KEY),localStorage.removeItem(a.ENCRYPTION_KEY_STORAGE),localStorage.removeItem(a.SALT_KEY),localStorage.setItem(ze,Ue.toString()),_chunkCR5KJUSTjs.a.info("Crudify: Storage upgraded to v2, tokens cleared for security")}}catch (e2){}}static getOrCreateSalt(){try{let e=localStorage.getItem(a.SALT_KEY);if(e){let i=atob(e),n=new Uint8Array(i.length);for(let s=0;s<i.length;s++)n[s]=i.charCodeAt(s);return n}}catch (e3){}let t=_chunkCR5KJUSTjs.k.call(void 0, );try{let e="";for(let i=0;i<t.length;i++)e+=String.fromCharCode(t[i]);localStorage.setItem(a.SALT_KEY,btoa(e))}catch (e4){_chunkCR5KJUSTjs.a.warn("Crudify: Cannot persist salt, encryption may not persist across sessions")}return t}static async generateFingerprint(){try{let n=localStorage.getItem(a.ENCRYPTION_KEY_STORAGE);if(n&&n.length>=32)return n}catch (e5){}let e=[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 _chunkCR5KJUSTjs.g.call(void 0, e);try{localStorage.setItem(a.ENCRYPTION_KEY_STORAGE,i)}catch (e6){_chunkCR5KJUSTjs.a.warn("Crudify: Cannot persist encryption key hash, session may not survive page reload")}return i}static isStorageAvailable(t){try{let e=window[t],i="__storage_test__";return e.setItem(i,"test"),e.removeItem(i),!0}catch (e7){return!1}}static getStorage(){return a.storageType==="none"?null:a.isStorageAvailable(a.storageType)?window[a.storageType]:(_chunkCR5KJUSTjs.a.warn(`Crudify: ${a.storageType} not available, tokens won't persist`),null)}static async encryptData(t){if(await a.initialize(),!a.encryptionKey||!a.salt)throw new Error("Encryption not initialized");return _chunkCR5KJUSTjs.i.call(void 0, t,a.encryptionKey,a.salt)}static async decryptData(t){if(await a.initialize(),!a.fingerprint)throw new Error("Encryption not initialized");return _chunkCR5KJUSTjs.l.call(void 0, t)?_chunkCR5KJUSTjs.j.call(void 0, t,a.fingerprint):(_chunkCR5KJUSTjs.a.warn("Crudify: Legacy encrypted data detected, cannot decrypt"),null)}static async saveTokens(t){let e=a.getStorage();if(e)try{let i={accessToken:t.accessToken,refreshToken:t.refreshToken,expiresAt:t.expiresAt,refreshExpiresAt:t.refreshExpiresAt,savedAt:Date.now()},n=await a.encryptData(JSON.stringify(i));e.setItem(a.TOKEN_KEY,n),_chunkCR5KJUSTjs.a.debug("Crudify: Tokens saved successfully")}catch(i){_chunkCR5KJUSTjs.a.error("Crudify: Failed to save tokens",i instanceof Error?i:{message:String(i)})}}static async getTokens(){let t=a.getStorage();if(!t)return null;try{let e=t.getItem(a.TOKEN_KEY);if(!e)return null;let i=await a.decryptData(e);if(!i)return _chunkCR5KJUSTjs.a.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?(_chunkCR5KJUSTjs.a.warn("Crudify: Incomplete token data found, clearing storage"),await a.clearTokens(),null):Date.now()>=n.refreshExpiresAt?(_chunkCR5KJUSTjs.a.info("Crudify: Refresh token expired, clearing storage"),await a.clearTokens(),null):{accessToken:n.accessToken,refreshToken:n.refreshToken,expiresAt:n.expiresAt,refreshExpiresAt:n.refreshExpiresAt}}catch(e){return _chunkCR5KJUSTjs.a.error("Crudify: Failed to retrieve tokens",e instanceof Error?e:{message:String(e)}),await a.clearTokens(),null}}static async clearTokens(){let t=a.getStorage();if(t)try{t.removeItem(a.TOKEN_KEY),_chunkCR5KJUSTjs.a.debug("Crudify: Tokens cleared from storage")}catch(e){_chunkCR5KJUSTjs.a.error("Crudify: Failed to clear tokens",e instanceof Error?e:{message:String(e)})}}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 (e8){}_chunkCR5KJUSTjs.a.info("Crudify: Encryption key rotated successfully")}catch(t){_chunkCR5KJUSTjs.a.error("Crudify: Failed to rotate encryption key",t instanceof Error?t:{message:String(t)})}}static async hasValidTokens(){return await a.getTokens()!==null}static async ensureInitialized(){await a.initialize()}static async getExpirationInfo(){let t=await a.getTokens();if(!t)return null;let e=Date.now();return{accessExpired:e>=t.expiresAt,refreshExpired:e>=t.refreshExpiresAt,accessExpiresIn:Math.max(0,t.expiresAt-e),refreshExpiresIn:Math.max(0,t.refreshExpiresAt-e)}}static async updateAccessToken(t,e){let i=await a.getTokens();if(!i){_chunkCR5KJUSTjs.a.warn("Crudify: Cannot update access token, no existing tokens found");return}await a.saveTokens({...i,accessToken:t,expiresAt:e})}static createSyncEvent(t,e,i){return{type:t,tokens:e,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(t){let e=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=_optionalChain([a, 'access', _2 => _2.getStorage, 'call', _3 => _3(), 'optionalAccess', _4 => _4.getItem, 'call', _5 => _5(a.TOKEN_KEY)]);if(l!==null&&l!=="")return}let n=i.oldValue!==null&&i.oldValue!=="";if(i.newValue===null){_chunkCR5KJUSTjs.a.debug("Crudify: Tokens removed in another tab"),t(null,a.SYNC_EVENTS.TOKENS_CLEARED,n);return}if(i.newValue){_chunkCR5KJUSTjs.a.debug("Crudify: Tokens updated in another tab");let s=await a.getTokens();t(s,a.SYNC_EVENTS.TOKENS_UPDATED,n)}};return window.addEventListener("storage",e),()=>{window.removeEventListener("storage",e)}}};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 t=Date.now().toString(36),e=Math.random().toString(36).substring(2,9);return`tab_${t}_${e}`}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=t=>{this.handleMessage(t.data)},this.broadcastChannel.onmessageerror=()=>{_chunkCR5KJUSTjs.a.warn("Crudify: CrossTabSync message error")},_chunkCR5KJUSTjs.a.debug("Crudify: CrossTabSync initialized with BroadcastChannel")):_chunkCR5KJUSTjs.a.debug("Crudify: BroadcastChannel not available, using localStorage fallback"),this.isInitialized=!0}catch(t){_chunkCR5KJUSTjs.a.warn("Crudify: Failed to initialize CrossTabSync",{message:t instanceof Error?t.message:String(t)})}}destroy(){this.broadcastChannel&&(this.broadcastChannel.close(),this.broadcastChannel=null),this.listeners.clear(),this.isInitialized=!1}getTabId(){return this.tabId}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}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(t){this.isInitialized||this.initialize();try{this.broadcastChannel&&(this.broadcastChannel.postMessage(t),_chunkCR5KJUSTjs.a.debug(`Crudify: CrossTab broadcast ${t.type}`))}catch(e){_chunkCR5KJUSTjs.a.warn("Crudify: Failed to broadcast cross-tab message",{message:e instanceof Error?e.message:String(e)})}}handleMessage(t){t.tabId!==this.tabId&&(_chunkCR5KJUSTjs.a.debug(`Crudify: CrossTab received ${t.type} from ${t.tabId}`),t.type==="SESSION_PING"&&this.broadcast({type:"SESSION_PONG",tabId:this.tabId,timestamp:Date.now(),payload:{respondingTo:t.tabId}}),this.listeners.forEach(e=>{try{e(t)}catch(i){_chunkCR5KJUSTjs.a.error("Crudify: CrossTab listener error",{message:i instanceof Error?i.message:String(i)})}}))}};K.instance=null;var ye=K,W= exports.c =ye.getInstance();var _crudifysdk = require('@nocios/crudify-sdk'); var _crudifysdk2 = _interopRequireDefault(_crudifysdk);var ne=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(t={}){if(!this.initialized){if(this.config={storageType:"localStorage",autoRestore:!0,enableLogging:!1,env:"stg",...t},v.setStorageType(this.config.storageType||"localStorage"),this.config.publicApiKey&&!this.crudifyInitialized&&await this.ensureCrudifyInitialized(),_crudifysdk2.default.setTokenInvalidationCallback(()=>{this.log("Tokens invalidated by crudify-core"),_chunkCR5KJUSTjs.f.emit("SESSION_EXPIRED",{message:"Your session has expired. Please log in again.",source:"crudify-core.clearTokensAndRefreshState"})}),this.config.apiEndpointAdmin&&this.config.apiKeyEndpointAdmin){let e=await v.getTokens();e?await v.saveTokens({...e,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(t,e){try{let i=await _crudifysdk2.default.login(t,e);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:_optionalChain([n, 'optionalAccess', _6 => _6.apiEndpointAdmin])||this.config.apiEndpointAdmin,apiKeyEndpointAdmin:_optionalChain([n, 'optionalAccess', _7 => _7.apiKeyEndpointAdmin])||this.config.apiKeyEndpointAdmin};return await v.saveTokens(l),v.markSuccessfulLogin(),this.lastActivityTime=Date.now(),W.notifyLogin(),_optionalChain([this, 'access', _8 => _8.config, 'access', _9 => _9.onLoginSuccess, 'optionalCall', _10 => _10(l)]),{success:!0,tokens:l,data:s}}catch(i){return _chunkCR5KJUSTjs.a.error("[SessionManager] Login error",i instanceof Error?i:{message:String(i)}),{success:!1,error:i instanceof Error?i.message:"Unknown error"}}}async logout(){try{this.log("Logging out..."),_chunkCR5KJUSTjs.f.emit("LOGOUT",{message:"User logged out",source:"SessionManager.logout"}),await _crudifysdk2.default.logout(),await v.clearTokens(),W.notifyLogout(),this.log("Logout successful"),_optionalChain([this, 'access', _11 => _11.config, 'access', _12 => _12.onLogout, 'optionalCall', _13 => _13()])}catch(t){this.log("Logout error",{error:t instanceof Error?t.message:String(t)}),await v.clearTokens(),W.notifyLogout()}}async restoreSession(){try{this.log("Attempting to restore session...");let t=await v.getTokens();if(!t)return this.log("No valid tokens found in storage"),!1;if(Date.now()>=t.refreshExpiresAt)return this.log("Refresh token expired, clearing storage"),await v.clearTokens(),!1;if(_crudifysdk2.default.setTokens({accessToken:t.accessToken,refreshToken:t.refreshToken,expiresAt:t.expiresAt,refreshExpiresAt:t.refreshExpiresAt}),_crudifysdk2.default.getTokenData().isValid===!1){if(this.log("Restored access token is invalid or expired"),Date.now()<t.refreshExpiresAt&&(this.log("Access token expired but refresh is valid, attempting refresh..."),await this.refreshTokens())){this.log("Session restored successfully via token refresh");let n=await v.getTokens();return n&&_optionalChain([this, 'access', _14 => _14.config, 'access', _15 => _15.onSessionRestored, 'optionalCall', _16 => _16(n)]),!0}return await v.clearTokens(),await _crudifysdk2.default.logout(),!1}return this.log("Session restored successfully"),this.lastActivityTime=Date.now(),_optionalChain([this, 'access', _17 => _17.config, 'access', _18 => _18.onSessionRestored, 'optionalCall', _19 => _19(t)]),!0}catch(t){return this.log("Session restore error",{error:t instanceof Error?t.message:String(t)}),await v.clearTokens(),await _crudifysdk2.default.logout(),!1}}async isAuthenticated(){return _crudifysdk2.default.isLogin()||await v.hasValidTokens()}async getTokenInfo(){let t=_crudifysdk2.default.getTokenData(),e=await v.getExpirationInfo(),i=await v.getTokens();return{isLoggedIn:await this.isAuthenticated(),crudifyTokens:t,storageInfo:e,hasValidTokens:await v.hasValidTokens(),apiEndpointAdmin:_optionalChain([i, 'optionalAccess', _20 => _20.apiEndpointAdmin]),apiKeyEndpointAdmin:_optionalChain([i, 'optionalAccess', _21 => _21.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 t=await _crudifysdk2.default.refreshAccessToken();if(!t.success)return this.log("Token refresh failed",{errors:t.errors}),await v.clearTokens(),_optionalChain([this, 'access', _22 => _22.config, 'access', _23 => _23.showNotification, 'optionalCall', _24 => _24(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _25 => _25.config, 'access', _26 => _26.onSessionExpired, 'optionalCall', _27 => _27()]),!1;let e=t.data,i={accessToken:e.token,refreshToken:e.refreshToken,expiresAt:e.expiresAt,refreshExpiresAt:e.refreshExpiresAt};return await v.saveTokens(i),this.log("Tokens refreshed and saved successfully"),this.lastActivityTime=Date.now(),W.notifyTokenRefreshed(),!0}catch(t){return this.log("Token refresh error",{error:t instanceof Error?t.message:String(t)}),await v.clearTokens(),_optionalChain([this, 'access', _28 => _28.config, 'access', _29 => _29.showNotification, 'optionalCall', _30 => _30(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _31 => _31.config, 'access', _32 => _32.onSessionExpired, 'optionalCall', _33 => _33()]),!1}}isRefreshing(){return this.isRefreshingLocally}setupResponseInterceptor(){_crudifysdk2.default.setResponseInterceptor(async t=>{this.updateLastActivity();let e=this.detectAuthorizationError(t);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"),_chunkCR5KJUSTjs.f.emit("TOKEN_REFRESH_FAILED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"}),t;e.shouldTriggerLogout&&(await v.hasValidTokens()&&!e.isIrrecoverable?(this.log("Access token expired, emitting TOKEN_EXPIRED event"),_chunkCR5KJUSTjs.f.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"),_chunkCR5KJUSTjs.f.emit("SESSION_EXPIRED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"})))}return t}),this.log("Response interceptor configured (non-blocking mode)")}async ensureCrudifyInitialized(){if(!this.crudifyInitialized)try{this.log("Initializing crudify SDK...");let t=_crudifysdk2.default.getTokenData();if(t&&t.endpoint){this.log("Crudify already initialized by another service"),this.crudifyInitialized=!0;return}let e=this.config.env||"stg";_crudifysdk2.default.config(e);let i=this.config.publicApiKey,n=this.config.enableLogging?"debug":"none",s=await _crudifysdk2.default.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(t){throw _chunkCR5KJUSTjs.a.error("[SessionManager] Failed to initialize crudify",t instanceof Error?t:{message:String(t)}),t}}detectAuthorizationError(t){let e={isAuthError:!1,isRefreshTokenInvalid:!1,isTokenRefreshFailed:!1,isTokenExpired:!1,isUnauthorized:!1,isIrrecoverable:!1,shouldTriggerLogout:!1,errorType:"",errorDetails:null,userFriendlyMessage:""};if(t.errors&&Array.isArray(t.errors)){let i=t.errors.find(n=>n.errorType==="Unauthorized"||_optionalChain([n, 'access', _34 => _34.message, 'optionalAccess', _35 => _35.includes, 'call', _36 => _36("Unauthorized")])||_optionalChain([n, 'access', _37 => _37.message, 'optionalAccess', _38 => _38.includes, 'call', _39 => _39("Not Authorized")])||_optionalChain([n, 'access', _40 => _40.message, 'optionalAccess', _41 => _41.includes, 'call', _42 => _42("NOT_AUTHORIZED")])||_optionalChain([n, 'access', _43 => _43.message, 'optionalAccess', _44 => _44.includes, 'call', _45 => _45("Token")])||_optionalChain([n, 'access', _46 => _46.message, 'optionalAccess', _47 => _47.includes, 'call', _48 => _48("TOKEN")])||_optionalChain([n, 'access', _49 => _49.message, 'optionalAccess', _50 => _50.includes, 'call', _51 => _51("Authentication")])||_optionalChain([n, 'access', _52 => _52.message, 'optionalAccess', _53 => _53.includes, 'call', _54 => _54("UNAUTHENTICATED")])||_optionalChain([n, 'access', _55 => _55.extensions, 'optionalAccess', _56 => _56.code])==="UNAUTHENTICATED"||_optionalChain([n, 'access', _57 => _57.extensions, 'optionalAccess', _58 => _58.code])==="FORBIDDEN");i&&(e.isAuthError=!0,e.errorType="GraphQL Array",e.errorDetails=i,e.shouldTriggerLogout=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.",(_optionalChain([i, 'access', _59 => _59.message, 'optionalAccess', _60 => _60.includes, 'call', _61 => _61("TOKEN")])||_optionalChain([i, 'access', _62 => _62.message, 'optionalAccess', _63 => _63.includes, 'call', _64 => _64("Token")]))&&(e.isTokenExpired=!0),_optionalChain([i, 'access', _65 => _65.extensions, 'optionalAccess', _66 => _66.code])==="UNAUTHENTICATED"&&(e.isUnauthorized=!0))}if(!e.isAuthError&&t.errors&&typeof t.errors=="object"&&!Array.isArray(t.errors)){let n=Object.values(t.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"&&(e.isAuthError=!0,e.errorType="GraphQL Object",e.errorDetails=t.errors,e.shouldTriggerLogout=!0,n.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."):n.includes("TOKEN_HAS_EXPIRED")||n.includes("SESSION_EXPIRED")?(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."):n.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&&_optionalChain([t, 'access', _67 => _67.data, 'optionalAccess', _68 => _68.response, 'optionalAccess', _69 => _69.status])){let i=t.data.response.status.toUpperCase();(i==="UNAUTHORIZED"||i==="UNAUTHENTICATED")&&(e.isAuthError=!0,e.errorType="Status",e.errorDetails=t.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&&_optionalChain([t, 'access', _70 => _70.data, 'optionalAccess', _71 => _71.response, 'optionalAccess', _72 => _72.data]))try{let i=typeof t.data.response.data=="string"?JSON.parse(t.data.response.data):t.data.response.data;(i.error==="REFRESH_TOKEN_INVALID"||i.error==="TOKEN_EXPIRED"||i.error==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Parsed Data",e.errorDetails=i,e.shouldTriggerLogout=!0,e.isIrrecoverable=!0,i.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 (e9){}if(!e.isAuthError&&t.errorCode){let i=String(t.errorCode).toUpperCase();(i==="UNAUTHORIZED"||i==="UNAUTHENTICATED"||i==="TOKEN_EXPIRED"||i==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Error Code",e.errorDetails={errorCode:i},e.shouldTriggerLogout=!0,i==="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 t=this.getTimeSinceLastActivity();if(this.lastActivityTime===0)return"none";let e=1800*1e3;return t>e?(this.log(`Inactivity timeout: ${Math.floor(t/6e4)} minutes since last activity`),"logout"):"none"}async clearSession(){await v.clearTokens(),await _crudifysdk2.default.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?_chunkCR5KJUSTjs.m.call(void 0, "SESSION_EXPIRED",{translateFn:this.config.translateFn,enableDebug:this.config.enableLogging}):"Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."}log(t,e){this.config.enableLogging&&_chunkCR5KJUSTjs.a.debug(`[SessionManager] ${t}`,e)}formatError(t){return t?typeof t=="string"?t:typeof t=="object"?Object.values(t).flat().map(String).join(", "):"Authentication failed":"Unknown error"}};var _react = require('react'); var _react2 = _interopRequireDefault(_react);var Ke={isAuthenticated:!1,isLoading:!0,isLoggingOut:!1,isInitialized:!1,tokens:null,error:null};function Me(){let[r,t]=_react.useState.call(void 0, Ke),e=_react.useCallback.call(void 0, o=>{t(f=>({...f,isLoading:o}))},[]),i=_react.useCallback.call(void 0, (o,f)=>{t(E=>({...E,isAuthenticated:o,tokens:f,error:o?null:E.error}))},[]),n=_react.useCallback.call(void 0, o=>{t(f=>({...f,isLoggingOut:o}))},[]),s=_react.useCallback.call(void 0, o=>{t(f=>({...f,error:o}))},[]),l=_react.useCallback.call(void 0, o=>{t(f=>({...f,isInitialized:o}))},[]);return{state:r,setState:t,setLoading:e,setAuthenticated:i,setLoggingOut:n,setError:s,setInitialized:l}}var se={AGGRESSIVE:3e4,MODERATE:6e4,RELAXED:12e4},he={AGGRESSIVE:300*1e3,MODERATE:1800*1e3},He=.5;function Ge(r){return r?r.expiresAt-Date.now()<3e5:!1}function _e(r){return r?Math.max(0,r.expiresAt-Date.now()):0}function Ve(r){return r?Math.max(0,r.refreshExpiresAt-Date.now()):0}function $(r){return r.crudifyTokens.accessToken?{accessToken:r.crudifyTokens.accessToken,refreshToken:r.crudifyTokens.refreshToken||"",expiresAt:r.crudifyTokens.expiresAt,refreshExpiresAt:r.crudifyTokens.refreshExpiresAt}:null}function $e(r){let{sessionManager:t,stateManager:e}=r,i=_react.useCallback.call(void 0, async(o,f)=>{e.setState(E=>({...E,isLoading:!0,isLoggingOut:!1,error:null}));try{let E=await t.login(o,f);return E.success&&E.tokens?e.setState(b=>({...b,isAuthenticated:!0,tokens:E.tokens,isLoading:!1,isLoggingOut:!1,error:null})):e.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";_chunkCR5KJUSTjs.a.error("[useSession] Login error",E instanceof Error?E:{message:b});let T=b.includes("INVALID_CREDENTIALS")||b.includes("Invalid email")||b.includes("Invalid password")||b.includes("credentials");return e.setState(m=>({...m,isAuthenticated:!1,tokens:null,isLoading:!1,isLoggingOut:!1,error:T?null:b})),{success:!1,error:b}}},[t,e]),n=_react.useCallback.call(void 0, async()=>{e.setState(o=>({...o,isLoading:!0,isLoggingOut:!0}));try{await t.logout(),e.setState(o=>({...o,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))}catch(o){e.setState(f=>({...f,isAuthenticated:!1,tokens:null,isLoading:!1,error:o instanceof Error?o.message:"Logout error"}))}},[t,e]),s=_react.useCallback.call(void 0, async()=>{try{let o=await t.refreshTokens();if(o){let f=await t.getTokenInfo();e.setState(E=>({...E,tokens:$(f),error:null}))}else e.setState(f=>({...f,isAuthenticated:!1,tokens:null,error:"Token refresh failed"}));return o}catch(o){return e.setState(f=>({...f,isAuthenticated:!1,tokens:null,error:o instanceof Error?o.message:"Token refresh failed"})),!1}},[t,e]),l=_react.useCallback.call(void 0, ()=>{e.setError(null)},[e]);return{login:i,logout:n,refreshTokens:s,clearError:l}}function zt(r){return r<he.AGGRESSIVE?se.AGGRESSIVE:r<he.MODERATE?se.MODERATE:se.RELAXED}function Ye(r){let{isAuthenticated:t,tokens:e,sessionManager:i,onTokensRefreshed:n,onSessionExpired:s,onSetLoading:l,logout:o}=r,f=_react.useCallback.call(void 0, ()=>{i.updateLastActivity()},[i]);_react.useEffect.call(void 0, ()=>{if(!t||!e)return;let b=_chunkCR5KJUSTjs.q.getInstance().subscribe(f);window.addEventListener("popstate",f);let T,m=!0,I=async()=>{if(!m)return;let A=(await i.getTokenInfo()).crudifyTokens.expiresIn||0,N=zt(A);T=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))*He;if(O>0&&O<=z)if(l(!0),await i.refreshTokens()){let Z=await i.getTokenInfo();n($(Z)),l(!1)}else n(null),s(),l(!1);i.getTimeSinceLastActivity()>18e5?await o():m&&I()},N)};return I(),()=>{m=!1,clearTimeout(T),window.removeEventListener("popstate",f),b()}},[t,e,i,f,n,s,l,o])}function Be(r){let{sessionManager:t,onTokensUpdated:e,onSessionExpired:i,onSetLoading:n,onSetError:s}=r;_react.useEffect.call(void 0, ()=>{let l=_chunkCR5KJUSTjs.f.subscribe(async o=>{if(o.type==="TOKEN_EXPIRED"){if(t.isRefreshing())return;n(!0);try{if(await t.refreshTokens()){let E=await t.getTokenInfo();e($(E)),n(!1)}else _chunkCR5KJUSTjs.f.emit("SESSION_EXPIRED",{message:"Failed to refresh token after detecting expiration",source:"useSession.TOKEN_EXPIRED handler"})}catch(f){_chunkCR5KJUSTjs.f.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")&&(e(null),n(!1),s(_optionalChain([o, 'access', _73 => _73.details, 'optionalAccess', _74 => _74.message, 'optionalAccess', _75 => _75.toString, 'call', _76 => _76()])||"Session expired"),i())});return()=>l()},[t,e,i,n,s])}function Xe(r){let{isAuthenticated:t,onTokensUpdated:e,onSessionExpired:i}=r;_react.useEffect.call(void 0, ()=>{let n=async l=>{switch(l.type){case"SESSION_STARTED":case"TOKEN_REFRESHED":try{await v.ensureInitialized();let o=await v.getTokens();o&&(_chunkCR5KJUSTjs.a.debug(`[useCrossTabSync] Syncing ${l.type} from tab ${l.tabId}`),e(o))}catch(o){_chunkCR5KJUSTjs.a.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()||(_chunkCR5KJUSTjs.a.debug(`[useCrossTabSync] Syncing SESSION_ENDED from tab ${l.tabId}`),e(null),t&&i())}catch(o){_chunkCR5KJUSTjs.a.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=W.subscribe(n);return()=>s()},[t,e,i]),_react.useEffect.call(void 0, ()=>{let n=v.subscribeToChanges(async(s,l,o)=>{if(l===v.SYNC_EVENTS.TOKENS_CLEARED){if(await v.hasValidTokens())return;o&&t?(e(null),i()):o&&e(null)}else l===v.SYNC_EVENTS.TOKENS_UPDATED&&s&&e(s)});return()=>n()},[t,e,i])}async function Ze(r){let{sessionManager:t,options:e,stateActions:i}=r;try{i.setState(o=>({...o,isLoading:!0,error:null}));let n={autoRestore:_nullishCoalesce(e.autoRestore, () => (!0)),enableLogging:_nullishCoalesce(e.enableLogging, () => (!1)),showNotification:e.showNotification,translateFn:e.translateFn,apiEndpointAdmin:e.apiEndpointAdmin,apiKeyEndpointAdmin:e.apiKeyEndpointAdmin,publicApiKey:e.publicApiKey,env:e.env||"stg",onSessionExpired:()=>{i.setState(o=>({...o,isAuthenticated:!1,tokens:null,error:"Session expired"})),_optionalChain([e, 'access', _77 => _77.onSessionExpired, 'optionalCall', _78 => _78()])},onSessionRestored:o=>{i.setState(f=>({...f,isAuthenticated:!0,tokens:o,error:null})),_optionalChain([e, 'access', _79 => _79.onSessionRestored, 'optionalCall', _80 => _80(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 t.initialize(n),t.setupResponseInterceptor();let s=await t.isAuthenticated(),l=await t.getTokenInfo();i.setState(o=>({...o,isAuthenticated:s,isInitialized:!0,isLoading:!1,isLoggingOut:!1,tokens:$(l)}))}catch(n){let s=n instanceof Error?n.message:"Initialization failed";_chunkCR5KJUSTjs.a.error("[useSession] Initialize failed",n instanceof Error?n:{message:s}),i.setState(l=>({...l,isLoading:!1,isInitialized:!0,isLoggingOut:!1,error:s}))}}function Ee(r={}){let t=ne.getInstance(),e=Me(),{state:i}=e,{login:n,logout:s,refreshTokens:l,clearError:o}=$e({sessionManager:t,stateManager:e}),f=_react.useCallback.call(void 0, g=>{e.setAuthenticated(!!g,g)},[e]),E=_react.useCallback.call(void 0, ()=>{e.setAuthenticated(!1,null),_optionalChain([r, 'access', _81 => _81.onSessionExpired, 'optionalCall', _82 => _82()])},[e,r.onSessionExpired]),b=_react.useCallback.call(void 0, g=>{e.setLoading(g)},[e]),T=_react.useCallback.call(void 0, g=>{e.setError(g)},[e]);_react.useEffect.call(void 0, ()=>{Ze({sessionManager:t,options:r,stateActions:e})},[]),Ye({isAuthenticated:i.isAuthenticated,tokens:i.tokens,sessionManager:t,onTokensRefreshed:f,onSessionExpired:E,onSetLoading:b,logout:s}),Be({sessionManager:t,onTokensUpdated:f,onSessionExpired:E,onSetLoading:b,onSetError:T}),Xe({isAuthenticated:i.isAuthenticated,onTokensUpdated:f,onSessionExpired:E});let m=_react.useCallback.call(void 0, ()=>{t.updateLastActivity()},[t]),I=_react.useCallback.call(void 0, async()=>t.getTokenInfo(),[t]);return{...i,login:n,logout:s,refreshTokens:l,clearError:o,getTokenInfo:I,updateActivity:m,isExpiringSoon:Ge(i.tokens),expiresIn:_e(i.tokens),refreshExpiresIn:Ve(i.tokens)}}var _material = require('@mui/material');var _uuid = require('uuid');var _dompurify = require('dompurify'); var _dompurify2 = _interopRequireDefault(_dompurify);var _jsxruntime = require('react/jsx-runtime');var je=_react.createContext.call(void 0, null),Xt=r=>_dompurify2.default.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}),Te= exports.f =({children:r,maxNotifications:t=5,defaultAutoHideDuration:e=6e3,position:i={vertical:"top",horizontal:"right"},enabled:n=!1,allowHtml:s=!1})=>{let[l,o]=_react.useState.call(void 0, []),f=_react.useCallback.call(void 0, (m,I="info",g)=>{if(!n)return"";if(!m||typeof m!="string")return _chunkCR5KJUSTjs.a.warn("GlobalNotificationProvider: Invalid message provided"),"";m.length>1e3&&(_chunkCR5KJUSTjs.a.warn("GlobalNotificationProvider: Message too long, truncating"),m=m.substring(0,1e3)+"...");let A=_uuid.v4.call(void 0, ),N={id:A,message:m,severity:I,autoHideDuration:_nullishCoalesce(_optionalChain([g, 'optionalAccess', _83 => _83.autoHideDuration]), () => (e)),persistent:_nullishCoalesce(_optionalChain([g, 'optionalAccess', _84 => _84.persistent]), () => (!1)),allowHtml:_nullishCoalesce(_optionalChain([g, 'optionalAccess', _85 => _85.allowHtml]), () => (s))};return o(x=>[...x.length>=t?x.slice(-(t-1)):x,N]),A},[t,e,n,s]),E=_react.useCallback.call(void 0, m=>{o(I=>I.filter(g=>g.id!==m))},[]),b=_react.useCallback.call(void 0, ()=>{o([])},[]),T={showNotification:f,hideNotification:E,clearAllNotifications:b};return _jsxruntime.jsxs.call(void 0, je.Provider,{value:T,children:[r,n&&_jsxruntime.jsx.call(void 0, _material.Portal,{children:_jsxruntime.jsx.call(void 0, _material.Box,{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=>_jsxruntime.jsx.call(void 0, Zt,{notification:m,onClose:()=>E(m.id)},m.id))})})]})},Zt=({notification:r,onClose:t})=>{let[e,i]=_react.useState.call(void 0, !0),n=_react.useCallback.call(void 0, (s,l)=>{l!=="clickaway"&&(i(!1),setTimeout(t,300))},[t]);return _react.useEffect.call(void 0, ()=>{if(!r.persistent&&r.autoHideDuration){let s=setTimeout(()=>{n()},r.autoHideDuration);return()=>clearTimeout(s)}},[r.autoHideDuration,r.persistent,n]),_jsxruntime.jsx.call(void 0, _material.Snackbar,{open:e,onClose:n,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:_jsxruntime.jsx.call(void 0, _material.Alert,{variant:"filled",severity:r.severity,onClose:n,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:r.allowHtml?_jsxruntime.jsx.call(void 0, "span",{dangerouslySetInnerHTML:{__html:Xt(r.message)}}):_jsxruntime.jsx.call(void 0, "span",{children:r.message})})})},Je= exports.g =()=>{let r=_react.useContext.call(void 0, je);if(!r)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return r};var Se=class r{constructor(){this.listeners=[];this.credentials=null;this.isReady=!1}static getInstance(){return r.instance||(r.instance=new r),r.instance}notifyCredentialsReady(t){this.credentials=t,this.isReady=!0,this.listeners.forEach(e=>{try{e(t)}catch(i){_chunkCR5KJUSTjs.a.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(t=>{this.listeners.push(t)})}reset(){this.credentials=null,this.isReady=!1,this.listeners=[]}areCredentialsReady(){return this.isReady&&this.credentials!==null}},le= exports.h =Se.getInstance();var Qe=_react.createContext.call(void 0, void 0),et= exports.i =({config:r,children:t})=>{let[e,i]=_react.useState.call(void 0, !0),[n,s]=_react.useState.call(void 0, null),[l,o]=_react.useState.call(void 0, !1),[f,E]=_react.useState.call(void 0, ""),[b,T]=_react.useState.call(void 0, );_react.useEffect.call(void 0, ()=>{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{_crudifysdk2.default.config(r.env||"prod");let A=await _crudifysdk2.default.init(r.publicApiKey,"none");if(T(A),typeof _crudifysdk2.default.transaction=="function"&&typeof _crudifysdk2.default.login=="function")o(!0),E(I),A.apiEndpointAdmin&&A.apiKeyEndpointAdmin&&le.notifyCredentialsReady({apiUrl:A.apiEndpointAdmin,apiKey:A.apiKeyEndpointAdmin});else throw new Error("Crudify methods not properly initialized")}catch(A){let N=A instanceof Error?A.message:"Failed to initialize Crudify";_chunkCR5KJUSTjs.a.error("[CrudifyProvider] Initialization error",A instanceof Error?A:{message:String(A)}),s(N),o(!1)}finally{i(!1)}})()},[r.publicApiKey,r.env,f,l]);let m={crudify:l?_crudifysdk2.default:null,isLoading:e,error:n,isInitialized:l,adminCredentials:b};return _jsxruntime.jsx.call(void 0, Qe.Provider,{value:m,children:t})},tt= exports.j =()=>{let r=_react.useContext.call(void 0, Qe);if(r===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return r};var rt=_react.createContext.call(void 0, void 0);function it({children:r,options:t={},config:e,showNotifications:i=!1,notificationOptions:n={}}){let s;try{let{showNotification:g}=Je();s=g}catch (e10){}let l={};try{let g=tt();g.isInitialized&&g.adminCredentials&&(l=g.adminCredentials)}catch (e11){}let o=_react.useMemo.call(void 0, ()=>{let g=_chunkCR5KJUSTjs.d.call(void 0, {publicApiKey:_optionalChain([e, 'optionalAccess', _86 => _86.publicApiKey]),env:_optionalChain([e, 'optionalAccess', _87 => _87.env]),enableDebug:_optionalChain([t, 'optionalAccess', _88 => _88.enableLogging])});return{publicApiKey:g.publicApiKey,env:g.env||"prod"}},[e,_optionalChain([t, 'optionalAccess', _89 => _89.enableLogging])]),f=_react2.default.useMemo(()=>({...t,showNotification:s,apiEndpointAdmin:l.apiEndpointAdmin,apiKeyEndpointAdmin:l.apiKeyEndpointAdmin,publicApiKey:o.publicApiKey,env:o.env,onSessionExpired:()=>{_optionalChain([t, 'access', _90 => _90.onSessionExpired, 'optionalCall', _91 => _91()])}}),[t,s,l.apiEndpointAdmin,l.apiKeyEndpointAdmin,o]),E=Ee(f),b=_react.useMemo.call(void 0, ()=>{let g=_chunkCR5KJUSTjs.d.call(void 0, {publicApiKey:_optionalChain([e, 'optionalAccess', _92 => _92.publicApiKey]),env:_optionalChain([e, 'optionalAccess', _93 => _93.env]),appName:_optionalChain([e, 'optionalAccess', _94 => _94.appName]),logo:_optionalChain([e, 'optionalAccess', _95 => _95.logo]),loginActions:_optionalChain([e, 'optionalAccess', _96 => _96.loginActions]),enableDebug:_optionalChain([t, 'optionalAccess', _97 => _97.enableLogging])});return{publicApiKey:g.publicApiKey,env:g.env,appName:g.appName,loginActions:g.loginActions,logo:g.logo}},[e,_optionalChain([t, 'optionalAccess', _98 => _98.enableLogging])]),T=_react.useMemo.call(void 0, ()=>{if(!_optionalChain([E, 'access', _99 => _99.tokens, 'optionalAccess', _100 => _100.accessToken])||!E.isAuthenticated)return null;try{let g=_chunkCR5KJUSTjs.r.call(void 0, E.tokens.accessToken);if(g&&g.sub&&g.email&&g.subscriber){let A={_id:g.sub,email:g.email,subscriberKey:g.subscriber};return Object.keys(g).forEach(N=>{["sub","email","subscriber"].includes(N)||(A[N]=g[N])}),A}}catch(g){_chunkCR5KJUSTjs.a.error("Error decoding JWT token for sessionData",g instanceof Error?g:{message:String(g)})}return null},[_optionalChain([E, 'access', _101 => _101.tokens, 'optionalAccess', _102 => _102.accessToken]),E.isAuthenticated]),m={...E,sessionData:T,config:b},I={enabled:i,maxNotifications:n.maxNotifications||5,defaultAutoHideDuration:n.defaultAutoHideDuration||6e3,position:n.position||{vertical:"top",horizontal:"right"}};return _jsxruntime.jsx.call(void 0, rt.Provider,{value:m,children:r})}function Vr(r){let t={enabled:r.showNotifications,maxNotifications:_optionalChain([r, 'access', _103 => _103.notificationOptions, 'optionalAccess', _104 => _104.maxNotifications])||5,defaultAutoHideDuration:_optionalChain([r, 'access', _105 => _105.notificationOptions, 'optionalAccess', _106 => _106.defaultAutoHideDuration])||6e3,position:_optionalChain([r, 'access', _107 => _107.notificationOptions, 'optionalAccess', _108 => _108.position])||{vertical:"top",horizontal:"right"},allowHtml:_optionalChain([r, 'access', _109 => _109.notificationOptions, 'optionalAccess', _110 => _110.allowHtml])||!1};return _optionalChain([r, 'access', _111 => _111.config, 'optionalAccess', _112 => _112.publicApiKey])?_jsxruntime.jsx.call(void 0, et,{config:{publicApiKey:r.config.publicApiKey,env:r.config.env||"prod",appName:r.config.appName,loginActions:r.config.loginActions,logo:r.config.logo},children:_jsxruntime.jsx.call(void 0, Te,{...t,children:_jsxruntime.jsx.call(void 0, it,{...r})})}):_jsxruntime.jsx.call(void 0, Te,{...t,children:_jsxruntime.jsx.call(void 0, it,{...r})})}function ni(){let r=_react.useContext.call(void 0, rt);if(r===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return r}function $r(){let r=ni();return r.isInitialized?_jsxruntime.jsxs.call(void 0, "div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[_jsxruntime.jsx.call(void 0, "h4",{children:"Session Debug Info"}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Authenticated:"})," ",r.isAuthenticated?"Yes":"No"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Loading:"})," ",r.isLoading?"Yes":"No"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Error:"})," ",r.error||"None"]}),r.tokens&&_jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Access Token:"})," ",r.tokens.accessToken.substring(0,20),"..."]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Refresh Token:"})," ",r.tokens.refreshToken.substring(0,20),"..."]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Access Expires In:"})," ",Math.round(r.expiresIn/1e3/60)," minutes"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Refresh Expires In:"})," ",Math.round(r.refreshExpiresIn/1e3/60/60)," hours"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Expiring Soon:"})," ",r.isExpiringSoon?"Yes":"No"]})]})]}):_jsxruntime.jsx.call(void 0, "div",{children:"Session not initialized"})}var qr=(r={})=>{let{autoFetch:t=!0,retryOnError:e=!1,maxRetries:i=3}=r,[n,s]=_react.useState.call(void 0, null),[l,o]=_react.useState.call(void 0, !1),[f,E]=_react.useState.call(void 0, null),[b,T]=_react.useState.call(void 0, {}),m=_react.useRef.call(void 0, null),I=_react.useRef.call(void 0, !0),g=_react.useRef.call(void 0, 0),A=_react.useRef.call(void 0, 0),N=_react.useCallback.call(void 0, ()=>{s(null),E(null),o(!1),T({})},[]),x=_react.useCallback.call(void 0, async()=>{let O=_chunkCR5KJUSTjs.s.call(void 0, );if(!O){I.current&&(E("No user email available"),o(!1));return}m.current&&m.current.abort();let w=new AbortController;m.current=w;let F=++g.current;try{I.current&&(o(!0),E(null));let z=await _crudifysdk2.default.readItems("users",{filter:{email:O},pagination:{limit:1}});if(F===g.current&&I.current&&!w.signal.aborted){let D=z.data;if(z.success&&D&&D.length>0){let S=D[0];s(S);let Z={fullProfile:S,totalFields:Object.keys(S).length,displayData:{id:S.id,email:S.email,username:S.username,firstName:S.firstName,lastName:S.lastName,fullName:S.fullName||`${S.firstName||""} ${S.lastName||""}`.trim(),role:S.role,permissions:S.permissions||[],isActive:S.isActive,lastLogin:S.lastLogin,createdAt:S.createdAt,updatedAt:S.updatedAt,...Object.keys(S).filter(V=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(V)).reduce((V,re)=>({...V,[re]:S[re]}),{})}};T(Z),E(null),A.current=0}else E("User profile not found"),s(null),T({})}}catch(z){if(F===g.current&&I.current){let D=z;if(D.name==="AbortError")return;e&&A.current<i&&(_optionalChain([D, 'access', _113 => _113.message, 'optionalAccess', _114 => _114.includes, 'call', _115 => _115("Network Error")])||_optionalChain([D, 'access', _116 => _116.message, 'optionalAccess', _117 => _117.includes, 'call', _118 => _118("Failed to fetch")]))?(A.current++,setTimeout(()=>{I.current&&x()},1e3*A.current)):(E("Failed to load user profile"),s(null),T({}))}}finally{F===g.current&&I.current&&o(!1),m.current===w&&(m.current=null)}},[e,i]);return _react.useEffect.call(void 0, ()=>{t&&x()},[t,x]),_react.useEffect.call(void 0, ()=>(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:N}};var en=(r,t={})=>{let{autoFetch:e=!0,onSuccess:i,onError:n}=t,{prefix:s,padding:l=0,separator:o=""}=r,[f,E]=_react.useState.call(void 0, ""),[b,T]=_react.useState.call(void 0, !1),[m,I]=_react.useState.call(void 0, null),g=_react.useRef.call(void 0, !1),A=_react.useCallback.call(void 0, w=>{let F=String(w).padStart(l,"0");return`${s}${o}${F}`},[s,l,o]),N=_react.useCallback.call(void 0, async()=>{T(!0),I(null);try{let w=await _crudifysdk2.default.getNextSequence(s),F=w.data;if(w.success&&_optionalChain([F, 'optionalAccess', _119 => _119.value])){let z=A(F.value);E(z),_optionalChain([i, 'optionalCall', _120 => _120(z)])}else{let z=_optionalChain([w, 'access', _121 => _121.errors, 'optionalAccess', _122 => _122._error, 'optionalAccess', _123 => _123[0]])||"Failed to generate code";I(z),_optionalChain([n, 'optionalCall', _124 => _124(z)])}}catch(w){let F=w instanceof Error?w.message:"Unknown error";I(F),_optionalChain([n, 'optionalCall', _125 => _125(F)])}finally{T(!1)}},[s,A,i,n]),x=_react.useCallback.call(void 0, async()=>{await N()},[N]),O=_react.useCallback.call(void 0, ()=>{I(null)},[]);return _react.useEffect.call(void 0, ()=>{e&&!f&&!g.current&&(g.current=!0,N())},[e,f,N]),{value:f,loading:b,error:m,regenerate:x,clearError:O}};var Ae=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(t){let{priority:e,publicApiKey:i,env:n,enableLogging:s,requestedBy:l}=t;if(this.state.status==="INITIALIZED"){this.state.publicApiKey!==i&&_chunkCR5KJUSTjs.a.warn(`[CrudifyInitialization] ${l} attempted to initialize with different key. Already initialized with key: ${_optionalChain([this, 'access', _126 => _126.state, 'access', _127 => _127.publicApiKey, 'optionalAccess', _128 => _128.slice, 'call', _129 => _129(0,10)])}... by ${this.state.initializedBy}`);return}if(this.initializationPromise)return s&&_chunkCR5KJUSTjs.a.debug(`[CrudifyInitialization] ${l} waiting for ongoing initialization...`),this.initializationPromise;if(e==="LOW"&&this.highPriorityInitializerPresent&&this.state.status==="UNINITIALIZED"){if(s&&_chunkCR5KJUSTjs.a.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&&_chunkCR5KJUSTjs.a.debug(`[CrudifyInitialization] ${l} found initialization completed by HIGH priority`);return}s&&_chunkCR5KJUSTjs.a.warn(`[CrudifyInitialization] ${l} timeout waiting for HIGH priority, initializing with LOW priority`)}e==="HIGH"&&this.state.status==="INITIALIZING"&&this.state.priority==="LOW"&&(_chunkCR5KJUSTjs.a.warn(`[CrudifyInitialization] HIGH priority request from ${l} interrupting LOW priority initialization by ${this.state.initializedBy}`),this.state.status="UNINITIALIZED",this.initializationPromise=null),s&&_chunkCR5KJUSTjs.a.debug(`[CrudifyInitialization] ${l} starting initialization (${e} priority)...`),this.state.status="INITIALIZING",this.state.priority=e,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&&_chunkCR5KJUSTjs.a.info(`[CrudifyInitialization] Successfully initialized by ${l} (${e} priority)`)}catch(o){throw this.state.status="ERROR",this.state.error=o instanceof Error?o:new Error(String(o)),this.initializationPromise=null,_chunkCR5KJUSTjs.a.error(`[CrudifyInitialization] Initialization failed for ${l}`,o instanceof Error?o:{message:String(o)}),o}}async waitForHighPriorityOrTimeout(t){return new Promise(e=>{let n=0,s=setInterval(()=>{if(n+=10,this.state.status==="INITIALIZED"&&this.state.priority==="HIGH"){clearInterval(s),e();return}if(this.state.status==="INITIALIZING"&&this.state.priority==="HIGH"){n=0;return}n>=this.HIGH_PRIORITY_WAIT_TIMEOUT&&(clearInterval(s),t&&_chunkCR5KJUSTjs.a.debug(`[CrudifyInitialization] Timeout waiting for HIGH priority (${this.HIGH_PRIORITY_WAIT_TIMEOUT}ms)`),e())},10)})}async performInitialization(t,e,i){let n=_crudifysdk2.default.getTokenData();if(n&&n.endpoint){i&&_chunkCR5KJUSTjs.a.debug("[CrudifyInitialization] SDK already initialized externally");return}_crudifysdk2.default.config(e);let s=i?"debug":"none",l=await _crudifysdk2.default.init(t,s);if(l.success===!1)throw new Error(`Crudify initialization failed: ${JSON.stringify(l.errors||"Unknown error")}`);l.apiEndpointAdmin&&l.apiKeyEndpointAdmin&&le.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}}},ie= exports.q =Ae.getInstance();var at=r=>{let t=new Uint8Array(r);return crypto.getRandomValues(t),Array.from(t,e=>e.toString(36).padStart(2,"0")).join("").substring(0,r)},ot=()=>`file_${Date.now()}_${at(7)}`,di=r=>{let t=r.lastIndexOf("."),e=t>0?r.substring(t):"",i=Date.now(),n=at(6);return`${i}_${n}${e}`},ke=(r,t)=>{if(r.startsWith("http://")||r.startsWith("https://"))try{let e=new URL(r);return e.pathname.startsWith("/")?e.pathname.substring(1):e.pathname}catch (e12){if(t&&r.startsWith(t))return r.substring(t.length)}return t&&r.startsWith(t)?r.substring(t.length):r},dn= exports.r =(r={})=>{let{acceptedTypes:t,maxFileSize:e=10*1024*1024,maxFiles:i,minFiles:n=0,visibility:s="private",onUploadComplete:l,onUploadError:o,onFileRemoved:f,onFilesChange:E,mode:b="edit"}=r,[T,m]=_react.useState.call(void 0, []),[I,g]=_react.useState.call(void 0, !1),[A,N]=_react.useState.call(void 0, !1),[x,O]=_react.useState.call(void 0, []),w=_react.useRef.call(void 0, new Map),F=_react.useCallback.call(void 0, ()=>{g(!0)},[]),z=_react.useCallback.call(void 0, ()=>{N(!0),g(!0)},[]),D=_react.useCallback.call(void 0, (c,p)=>{m(d=>d.map(h=>h.id===c?{...h,...p}:h))},[]),S=_react.useCallback.call(void 0, c=>{_optionalChain([E, 'optionalCall', _130 => _130(c)])},[E]),Z=_react.useCallback.call(void 0, c=>t&&t.length>0&&!t.includes(c.type)?{valid:!1,error:`File type not allowed: ${c.type}`}:c.size>e?{valid:!1,error:`File exceeds maximum size of ${(e/1048576).toFixed(1)}MB`}:{valid:!0},[t,e]),V=_react.useCallback.call(void 0, async(c,p)=>{try{if(!ie.isInitialized())throw new Error("Crudify is not initialized. Please wait for the application to finish loading.");let d=di(p.name),y=await _crudifysdk2.default.generateSignedUrl({fileName:d,contentType:p.type,visibility:s});if(!y.success||!y.data)throw new Error("Failed to get upload URL");let h=y.data,{uploadUrl:R,s3Key:k,publicUrl:M}=h;if(!R||!k)throw new Error("Incomplete signed URL response");let Y=k.indexOf("/"),Rt=Y>0?k.substring(Y+1):k;D(c.id,{status:"uploading",progress:0}),await new Promise((pe,B)=>{let U=new XMLHttpRequest;U.upload.addEventListener("progress",_=>{if(_.lengthComputable){let Ct=Math.round(_.loaded/_.total*100);D(c.id,{progress:Ct})}}),U.addEventListener("load",()=>{U.status>=200&&U.status<300?pe():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",R),U.setRequestHeader("Content-Type",p.type),U.send(p)});let Nt={status:"completed",progress:100,filePath:Rt,visibility:s,publicUrl:s==="public"?M:void 0,file:void 0};m(pe=>{let B=pe.map(_=>_.id===c.id?{..._,...Nt}:_);S(B);let U=B.find(_=>_.id===c.id);return U&&_optionalChain([l, 'optionalCall', _131 => _131(U)]),B})}catch(d){let y=d instanceof Error?d.message:"Unknown error";D(c.id,{status:"error",progress:0,errorMessage:y}),m(h=>{let R=h.find(k=>k.id===c.id);return R&&_optionalChain([o, 'optionalCall', _132 => _132(R,y)]),h})}},[D,l,o,s]),re=_react.useCallback.call(void 0, async c=>{let p=Array.from(c),d=[];m(y=>{if(i!==void 0){let k=y.filter(Y=>Y.status!=="pendingDeletion"&&Y.status!=="error").length,M=i-k;if(M<=0)return _chunkCR5KJUSTjs.a.warn(`File limit of ${i} already reached`),y;p.length>M&&(p=p.slice(0,M),_chunkCR5KJUSTjs.a.warn(`Only ${M} files will be added to not exceed limit`))}let h=[];for(let k of p){let M=Z(k),Y={id:ot(),name:k.name,size:k.size,contentType:k.type,status:M.valid?"pending":"error",progress:0,createdAt:Date.now(),file:M.valid?k:void 0,errorMessage:M.error,isExisting:!1};h.push(Y)}d=h;let R=[...y,...h];return S(R),R}),setTimeout(()=>{let y=d.filter(h=>h.status==="pending"&&h.file);for(let h of y)if(h.file){let R=V(h,h.file);w.current.set(h.id,R),R.finally(()=>{w.current.delete(h.id)})}},0)},[i,Z,V,S]),lt=_react.useCallback.call(void 0, async c=>{let p=T.find(y=>y.id===c);if(!p)return{needsConfirmation:!1,isExisting:!1};let d=p.isExisting===!0;return b==="create"||!d?{needsConfirmation:!0,isExisting:d}:(O(y=>[...y,c]),m(y=>{let h=y.map(k=>k.id===c?{...k,status:"pendingDeletion"}:k),R=h.filter(k=>k.status!=="pendingDeletion");return S(R),h}),{needsConfirmation:!1,isExisting:d})},[T,b,S]),ct=_react.useCallback.call(void 0, async c=>{let p=T.find(d=>d.id===c);if(!p)return{success:!1,error:"File not found"};if(!p.filePath)return m(d=>{let y=d.filter(h=>h.id!==c);return S(y),y}),{success:!0};try{if(!ie.isInitialized())return{success:!1,error:"Crudify not initialized"};let d=ke(p.filePath);return(await _crudifysdk2.default.disableFile({filePath:d})).success?(m(h=>{let R=h.filter(k=>k.id!==c);return S(R),R}),_optionalChain([f, 'optionalCall', _133 => _133(p)]),{success:!0}):{success:!1,error:"Failed to delete file"}}catch(d){return{success:!1,error:d instanceof Error?d.message:"Unknown error"}}},[T,S,f]),ut=_react.useCallback.call(void 0, c=>{let p=T.find(d=>d.id===c);return!p||!p.isExisting?!1:(O(d=>d.filter(y=>y!==c)),m(d=>{let y=d.map(h=>h.id===c?{...h,status:"completed"}:h);return S(y),y}),!0)},[T,S]),dt=_react.useCallback.call(void 0, ()=>{x.length!==0&&(m(c=>{let p=c.map(d=>x.includes(d.id)?{...d,status:"completed"}:d);return S(p),p}),O([]))},[x,S]),ft=_react.useCallback.call(void 0, async()=>{if(x.length===0)return{success:!0,errors:[]};let c=[],p=[];if(!ie.isInitialized())return{success:!1,errors:["Crudify is not initialized. Please wait for the application to finish loading."]};for(let d of x){let y=T.find(h=>h.id===d);if(!_optionalChain([y, 'optionalAccess', _134 => _134.filePath])){p.push(d);continue}try{let h=ke(y.filePath);(await _crudifysdk2.default.disableFile({filePath:h})).success?(p.push(d),_optionalChain([f, 'optionalCall', _135 => _135(y)])):c.push(`Failed to delete ${y.name}`)}catch(h){c.push(`Error deleting ${y.name}: ${h instanceof Error?h.message:"Unknown error"}`)}}return p.length>0&&(m(d=>d.filter(h=>!p.includes(h.id))),O(d=>d.filter(y=>!p.includes(y)))),{success:c.length===0,errors:c}},[T,x,f]),gt=_react.useCallback.call(void 0, ()=>{m([]),S([])},[S]),pt=_react.useCallback.call(void 0, async c=>{let p=T.find(y=>y.id===c);if(!p||p.status!=="error"||!p.file){_chunkCR5KJUSTjs.a.warn("Cannot retry: file not found or no original file");return}D(c,{status:"pending",progress:0,errorMessage:void 0});let d=V(p,p.file);w.current.set(c,d),d.finally(()=>{w.current.delete(c)})},[T,D,V]),mt=_react.useCallback.call(void 0, async()=>{let c=Array.from(w.current.values());return c.length>0&&await Promise.allSettled(c),new Promise(p=>{setTimeout(()=>{m(d=>{let y=d.filter(h=>h.status==="completed"&&h.filePath).map(h=>h.filePath);return p(y),d})},0)})},[]),yt=c=>{let p=_optionalChain([c, 'access', _136 => _136.split, 'call', _137 => _137("."), 'access', _138 => _138.pop, 'call', _139 => _139(), 'optionalAccess', _140 => _140.toLowerCase, 'call', _141 => _141()])||"";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"},ht=_react.useCallback.call(void 0, (c,p)=>{let d=c.map(y=>{let h=ke(y.filePath,p),R=h.includes("/public/")||h.startsWith("public/")?"public":"private",k=y.contentType||yt(y.name);return{id:ot(),name:y.name,size:y.size||0,contentType:k,status:"completed",progress:100,filePath:h,visibility:R,createdAt:Date.now(),isExisting:!0}});m(d),S(d)},[S]),Et=_react.useCallback.call(void 0, async c=>{let p=T.find(d=>d.id===c);if(!p||!p.filePath)return null;if(p.visibility==="public"&&p.publicUrl)return p.publicUrl;try{if(!ie.isInitialized())return null;let d=await _crudifysdk2.default.getFileUrl({filePath:p.filePath,expiresIn:3600}),y=d.data;return d.success&&_optionalChain([y, 'optionalAccess', _142 => _142.url])?y.url:null}catch (e13){return null}},[T]),Tt=_react.useMemo.call(void 0, ()=>T.some(c=>c.status==="uploading"||c.status==="pending"),[T]),St=_react.useMemo.call(void 0, ()=>T.filter(c=>c.status==="uploading"||c.status==="pending").length,[T]),vt=_react.useMemo.call(void 0, ()=>T.filter(c=>c.status==="completed"&&c.filePath).map(c=>c.filePath),[T]),q=_react.useMemo.call(void 0, ()=>T.filter(c=>c.status!=="pendingDeletion"),[T]),bt=_react.useMemo.call(void 0, ()=>q.filter(c=>c.status==="completed"||c.status==="pending"||c.status==="uploading").length,[q]),{isValid:It,validationError:At,validationErrorKey:kt,validationErrorParams:xt}=_react.useMemo.call(void 0, ()=>{let c=q.filter(d=>d.status==="completed").length;if(c<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&&c>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]),wt=x.length>0;return{files:T,activeFiles:q,activeFileCount:bt,isUploading:Tt,pendingCount:St,addFiles:re,removeFile:lt,deleteFileImmediately:ct,restoreFile:ut,clearFiles:gt,retryUpload:pt,isValid:It,validationError:At,validationErrorKey:kt,validationErrorParams:xt,waitForUploads:mt,completedFilePaths:vt,initializeFiles:ht,isTouched:I,markAsTouched:F,isSubmitted:A,markAsSubmitted:z,getPreviewUrl:Et,pendingDeletions:x,hasPendingDeletions:wt,commitDeletions:ft,restorePendingDeletions:dt}};exports.a = v; exports.b = ye; exports.c = W; exports.d = ne; exports.e = Ee; exports.f = Te; exports.g = Je; exports.h = le; exports.i = et; exports.j = tt; exports.k = Vr; exports.l = ni; exports.m = $r; exports.n = qr; exports.o = en; exports.p = Ae; exports.q = ie; exports.r = dn;
|
package/dist/chunk-RJBX4MWF.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as n,g as h,h as m,i as p,j as u,k as y,l}from"./chunk-4ILUXVPW.mjs";var c="crudify_login_storage_version",d=2,g="crudify_login_encryption_salt",a=class{constructor(t="sessionStorage"){this.encryptionKey=null;this.salt=null;this.initPromise=null;this.initialized=!1;this.storage=t==="localStorage"?window.localStorage:window.sessionStorage}async ensureInitialized(){if(!(this.initialized&&this.encryptionKey)){if(this.initPromise){await this.initPromise;return}this.initPromise=this.initialize(),await this.initPromise}}async initialize(){try{parseInt(this.storage.getItem(c)||"1")<d&&(this.clearLegacyData(),this.storage.setItem(c,d.toString()));let e=this.storage.getItem(g);e&&l(`v2:x:${e}:x`)?this.salt=this.base64ToUint8Array(e):(this.salt=y(),this.storage.setItem(g,this.uint8ArrayToBase64(this.salt)));let i=await this.generateFingerprint();this.encryptionKey=await m(i,this.salt),this.initialized=!0}catch(t){n.error("SecureStorage initialization failed",t instanceof Error?t:{message:String(t)}),this.initialized=!1}}async generateFingerprint(){let t=[navigator.userAgent,navigator.language,new Date().getTimezoneOffset().toString(),screen.colorDepth.toString(),screen.width.toString(),screen.height.toString(),"crudify-login"].join("|");return h(t)}clearLegacyData(){let t=[];for(let e=0;e<this.storage.length;e++){let i=this.storage.key(e);i&&!i.startsWith(c)&&!i.startsWith(g)&&t.push(i)}t.forEach(e=>this.storage.removeItem(e))}async setItem(t,e,i){try{if(await this.ensureInitialized(),!this.encryptionKey||!this.salt){n.error("SecureStorage not properly initialized");return}let r=await p(e,this.encryptionKey,this.salt);if(this.storage.setItem(t,r),i){let o=Date.now()+i*60*1e3;this.storage.setItem(`${t}_expiry`,o.toString())}}catch(r){n.error("Failed to encrypt and store data",r instanceof Error?r:{message:String(r)})}}async getItem(t){try{await this.ensureInitialized();let e=`${t}_expiry`,i=this.storage.getItem(e);if(i){let f=parseInt(i,10);if(Date.now()>f)return this.removeItem(t),null}let r=this.storage.getItem(t);if(!r)return null;if(!l(r))return this.removeItem(t),null;let o=await this.generateFingerprint(),s=await u(r,o);return s||(n.warn("Failed to decrypt stored data - may be corrupted"),this.removeItem(t),null)}catch(e){return n.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`)}clear(){this.storage.clear()}async setToken(t){try{let e=t.split(".");if(e.length===3){let i=JSON.parse(atob(e[1]));if(i.exp){let r=i.exp*1e3,o=Date.now(),s=Math.floor((r-o)/(60*1e3));if(s>0){await this.setItem("authToken",t,s);return}}}}catch{n.warn("Failed to parse token expiry, using default expiry")}await this.setItem("authToken",t,1440)}async getToken(){let t=await this.getItem("authToken");if(t)try{let e=t.split(".");if(e.length===3){let i=JSON.parse(atob(e[1]));if(i.exp){let r=Math.floor(Date.now()/1e3);if(i.exp<r)return this.removeItem("authToken"),null}}}catch{return n.warn("Failed to validate token expiry"),this.removeItem("authToken"),null}return t}async hasValidToken(){return await this.getToken()!==null}async migrateFromLocalStorage(t){let e=window.localStorage.getItem(t);e&&(window.localStorage.removeItem(t),t==="authToken"?await this.setToken(e):await this.setItem(t,e))}uint8ArrayToBase64(t){let e="";for(let i=0;i<t.length;i++)e+=String.fromCharCode(t[i]);return btoa(e)}base64ToUint8Array(t){let e=atob(t),i=new Uint8Array(e.length);for(let r=0;r<e.length;r++)i[r]=e.charCodeAt(r);return i}},I=new a("sessionStorage"),T=new a("localStorage");export{I as a,T as b};
|
|
@@ -1,335 +0,0 @@
|
|
|
1
|
-
import { J as JwtPayload } from './api-B4uXiHF0.js';
|
|
2
|
-
|
|
3
|
-
interface JWTPayload extends JwtPayload {
|
|
4
|
-
"cognito:username"?: string;
|
|
5
|
-
}
|
|
6
|
-
declare const decodeJwtSafely: (token: string) => JWTPayload | null;
|
|
7
|
-
declare const getCurrentUserEmail: () => string | null;
|
|
8
|
-
declare const isTokenExpired: (token: string) => boolean;
|
|
9
|
-
|
|
10
|
-
/**
|
|
11
|
-
* Configuration resolver for crudify-components
|
|
12
|
-
*
|
|
13
|
-
* PRIORITY (v2.0.0 - No longer uses cookies):
|
|
14
|
-
* 1. window.__TENANT_CONFIG__ (production - injected by Lambda@Edge)
|
|
15
|
-
* 2. Props (development - from .env variables)
|
|
16
|
-
* 3. Error (no configuration available)
|
|
17
|
-
*
|
|
18
|
-
* This module now delegates to tenantConfig.ts for the actual resolution.
|
|
19
|
-
* It maintains backward compatibility with the old API.
|
|
20
|
-
*/
|
|
21
|
-
|
|
22
|
-
interface ResolvedConfig {
|
|
23
|
-
publicApiKey?: string;
|
|
24
|
-
env?: CrudifyEnvironment;
|
|
25
|
-
appName?: string;
|
|
26
|
-
logo?: string;
|
|
27
|
-
loginActions?: string[];
|
|
28
|
-
featureKeys?: string[];
|
|
29
|
-
theme?: Record<string, unknown>;
|
|
30
|
-
configSource: "props" | "cookies" | "none";
|
|
31
|
-
}
|
|
32
|
-
interface ConfigResolverOptions {
|
|
33
|
-
publicApiKey?: string;
|
|
34
|
-
env?: CrudifyEnvironment;
|
|
35
|
-
appName?: string;
|
|
36
|
-
logo?: string;
|
|
37
|
-
loginActions?: string[];
|
|
38
|
-
featureKeys?: string[];
|
|
39
|
-
enableDebug?: boolean;
|
|
40
|
-
}
|
|
41
|
-
/**
|
|
42
|
-
* Resolves Crudify configuration with the following priority:
|
|
43
|
-
* 1. window.__TENANT_CONFIG__ (production - injected by Lambda@Edge) - HIGHEST PRIORITY
|
|
44
|
-
* 2. Props (development - from .env variables) - FALLBACK
|
|
45
|
-
* 3. None (error - no configuration available)
|
|
46
|
-
*
|
|
47
|
-
* @param options - Configuration options including props for development
|
|
48
|
-
* @returns Resolved configuration with source indicator
|
|
49
|
-
*
|
|
50
|
-
* @example
|
|
51
|
-
* ```typescript
|
|
52
|
-
* // In production (Lambda@Edge injects window.__TENANT_CONFIG__)
|
|
53
|
-
* const config = resolveConfig();
|
|
54
|
-
* console.log(config.publicApiKey); // From injected config
|
|
55
|
-
* console.log(config.configSource); // "cookies" (for backward compatibility)
|
|
56
|
-
*
|
|
57
|
-
* // In development (with .env variables)
|
|
58
|
-
* const config = resolveConfig({
|
|
59
|
-
* publicApiKey: import.meta.env.VITE_PUBLIC_API_KEY,
|
|
60
|
-
* env: import.meta.env.VITE_ENV,
|
|
61
|
-
* });
|
|
62
|
-
* console.log(config.configSource); // "props"
|
|
63
|
-
* ```
|
|
64
|
-
*/
|
|
65
|
-
declare function resolveConfig(options?: ConfigResolverOptions): ResolvedConfig;
|
|
66
|
-
/**
|
|
67
|
-
* React hook to use config resolver
|
|
68
|
-
* Useful when you need config in a component
|
|
69
|
-
*
|
|
70
|
-
* @param options - Configuration options
|
|
71
|
-
* @returns Resolved configuration
|
|
72
|
-
*/
|
|
73
|
-
declare function useResolvedConfig(options?: ConfigResolverOptions): ResolvedConfig;
|
|
74
|
-
|
|
75
|
-
/**
|
|
76
|
-
* Global type declarations for window extensions used by Crudify
|
|
77
|
-
*
|
|
78
|
-
* These types enable type-safe access to window properties that are
|
|
79
|
-
* set dynamically at runtime by Crudify components.
|
|
80
|
-
*/
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
/**
|
|
85
|
-
* Tenant configuration injected by Lambda@Edge into the HTML
|
|
86
|
-
* This is the primary source of configuration in production
|
|
87
|
-
*/
|
|
88
|
-
interface TenantConfig {
|
|
89
|
-
publicApiKey: string;
|
|
90
|
-
environment: "dev" | "stg" | "api" | "prod";
|
|
91
|
-
appName?: string;
|
|
92
|
-
logo?: string;
|
|
93
|
-
loginActions?: string[];
|
|
94
|
-
featureKeys?: string[];
|
|
95
|
-
theme?: Record<string, unknown>;
|
|
96
|
-
enabledServices?: string[];
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
declare global {
|
|
100
|
-
interface Window {
|
|
101
|
-
// NEW: Tenant configuration injected by Lambda@Edge (primary source in production)
|
|
102
|
-
__TENANT_CONFIG__?: TenantConfig;
|
|
103
|
-
|
|
104
|
-
// Crudify environment configuration (legacy, kept for compatibility)
|
|
105
|
-
__CRUDIFY_ENV__?: CrudifyEnvironment;
|
|
106
|
-
__CRUDIFY_DEBUG_MODE__?: boolean;
|
|
107
|
-
__CRUDIFY_RESOLVED_CONFIG?: ResolvedConfig;
|
|
108
|
-
|
|
109
|
-
// i18next integration (optional, used when auto-syncing translations)
|
|
110
|
-
i18next?: {
|
|
111
|
-
addResourceBundle: (lang: string, ns: string, resources: Record<string, string>, deep?: boolean, overwrite?: boolean) => void;
|
|
112
|
-
language?: string;
|
|
113
|
-
changeLanguage: (lang: string) => void;
|
|
114
|
-
};
|
|
115
|
-
i18n?: Window["i18next"];
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
/**
|
|
120
|
-
* Centralized tenant configuration system for crudify-components
|
|
121
|
-
*
|
|
122
|
-
* This module provides a unified way to access tenant configuration
|
|
123
|
-
* that is injected by Lambda@Edge in production or provided via props
|
|
124
|
-
* in development.
|
|
125
|
-
*
|
|
126
|
-
* PRIORITY:
|
|
127
|
-
* 1. window.__TENANT_CONFIG__ (production - injected by Lambda@Edge)
|
|
128
|
-
* 2. Props (development - from .env variables)
|
|
129
|
-
* 3. Error (no configuration available)
|
|
130
|
-
*
|
|
131
|
-
* This replaces the cookie-based system to avoid race conditions
|
|
132
|
-
* where cookies from Set-Cookie headers are not immediately available
|
|
133
|
-
* to JavaScript on the first page load.
|
|
134
|
-
*/
|
|
135
|
-
type CrudifyEnvironment = "dev" | "stg" | "api" | "prod";
|
|
136
|
-
interface ResolvedTenantConfig {
|
|
137
|
-
publicApiKey?: string;
|
|
138
|
-
environment?: CrudifyEnvironment;
|
|
139
|
-
appName?: string;
|
|
140
|
-
logo?: string;
|
|
141
|
-
loginActions?: string[];
|
|
142
|
-
featureKeys?: string[];
|
|
143
|
-
theme?: Record<string, unknown>;
|
|
144
|
-
enabledServices?: string[];
|
|
145
|
-
configSource: "injected" | "props" | "none";
|
|
146
|
-
}
|
|
147
|
-
interface TenantConfigOptions {
|
|
148
|
-
publicApiKey?: string;
|
|
149
|
-
env?: CrudifyEnvironment;
|
|
150
|
-
appName?: string;
|
|
151
|
-
logo?: string;
|
|
152
|
-
loginActions?: string[];
|
|
153
|
-
featureKeys?: string[];
|
|
154
|
-
theme?: Record<string, unknown>;
|
|
155
|
-
enabledServices?: string[];
|
|
156
|
-
enableDebug?: boolean;
|
|
157
|
-
}
|
|
158
|
-
/**
|
|
159
|
-
* Resolves tenant configuration with the following priority:
|
|
160
|
-
* 1. window.__TENANT_CONFIG__ (production - injected by Lambda@Edge) - HIGHEST PRIORITY
|
|
161
|
-
* 2. Props (development - from .env variables) - FALLBACK
|
|
162
|
-
* 3. None (error - no configuration available)
|
|
163
|
-
*
|
|
164
|
-
* @param options - Configuration options including props for development
|
|
165
|
-
* @returns Resolved configuration with source indicator
|
|
166
|
-
*
|
|
167
|
-
* @example
|
|
168
|
-
* ```typescript
|
|
169
|
-
* // In production (Lambda@Edge injects window.__TENANT_CONFIG__)
|
|
170
|
-
* const config = resolveTenantConfig();
|
|
171
|
-
* console.log(config.publicApiKey); // From injected config
|
|
172
|
-
* console.log(config.configSource); // "injected"
|
|
173
|
-
*
|
|
174
|
-
* // In development (with .env variables)
|
|
175
|
-
* const config = resolveTenantConfig({
|
|
176
|
-
* publicApiKey: import.meta.env.VITE_PUBLIC_API_KEY,
|
|
177
|
-
* env: import.meta.env.VITE_ENV,
|
|
178
|
-
* });
|
|
179
|
-
* console.log(config.configSource); // "props"
|
|
180
|
-
* ```
|
|
181
|
-
*/
|
|
182
|
-
declare function resolveTenantConfig(options?: TenantConfigOptions): ResolvedTenantConfig;
|
|
183
|
-
/**
|
|
184
|
-
* React hook to access tenant configuration
|
|
185
|
-
*
|
|
186
|
-
* @param options - Configuration options
|
|
187
|
-
* @returns Resolved tenant configuration
|
|
188
|
-
*
|
|
189
|
-
* @example
|
|
190
|
-
* ```tsx
|
|
191
|
-
* function MyComponent() {
|
|
192
|
-
* const config = useTenantConfig();
|
|
193
|
-
*
|
|
194
|
-
* if (config.configSource === "none") {
|
|
195
|
-
* return <Error>No configuration available</Error>;
|
|
196
|
-
* }
|
|
197
|
-
*
|
|
198
|
-
* return <div>API Key: {config.publicApiKey}</div>;
|
|
199
|
-
* }
|
|
200
|
-
* ```
|
|
201
|
-
*/
|
|
202
|
-
declare function useTenantConfig(options?: TenantConfigOptions): ResolvedTenantConfig;
|
|
203
|
-
|
|
204
|
-
declare class SecureStorage {
|
|
205
|
-
private readonly storage;
|
|
206
|
-
private encryptionKey;
|
|
207
|
-
private salt;
|
|
208
|
-
private initPromise;
|
|
209
|
-
private initialized;
|
|
210
|
-
constructor(storageType?: "localStorage" | "sessionStorage");
|
|
211
|
-
/**
|
|
212
|
-
* Initialize encryption key asynchronously
|
|
213
|
-
* Must be called before using encryption methods
|
|
214
|
-
*/
|
|
215
|
-
private ensureInitialized;
|
|
216
|
-
private initialize;
|
|
217
|
-
private generateFingerprint;
|
|
218
|
-
private clearLegacyData;
|
|
219
|
-
setItem(key: string, value: string, expiryMinutes?: number): Promise<void>;
|
|
220
|
-
getItem(key: string): Promise<string | null>;
|
|
221
|
-
removeItem(key: string): void;
|
|
222
|
-
clear(): void;
|
|
223
|
-
setToken(token: string): Promise<void>;
|
|
224
|
-
getToken(): Promise<string | null>;
|
|
225
|
-
hasValidToken(): Promise<boolean>;
|
|
226
|
-
migrateFromLocalStorage(key: string): Promise<void>;
|
|
227
|
-
private uint8ArrayToBase64;
|
|
228
|
-
private base64ToUint8Array;
|
|
229
|
-
}
|
|
230
|
-
declare const secureSessionStorage: SecureStorage;
|
|
231
|
-
declare const secureLocalStorage: SecureStorage;
|
|
232
|
-
|
|
233
|
-
declare const ERROR_CODES: {
|
|
234
|
-
readonly INVALID_CREDENTIALS: "INVALID_CREDENTIALS";
|
|
235
|
-
readonly UNAUTHORIZED: "UNAUTHORIZED";
|
|
236
|
-
readonly INVALID_API_KEY: "INVALID_API_KEY";
|
|
237
|
-
readonly USER_NOT_FOUND: "USER_NOT_FOUND";
|
|
238
|
-
readonly USER_NOT_ACTIVE: "USER_NOT_ACTIVE";
|
|
239
|
-
readonly NO_PERMISSION: "NO_PERMISSION";
|
|
240
|
-
readonly ITEM_NOT_FOUND: "ITEM_NOT_FOUND";
|
|
241
|
-
readonly NOT_FOUND: "NOT_FOUND";
|
|
242
|
-
readonly IN_USE: "IN_USE";
|
|
243
|
-
readonly FIELD_ERROR: "FIELD_ERROR";
|
|
244
|
-
readonly BAD_REQUEST: "BAD_REQUEST";
|
|
245
|
-
readonly INVALID_EMAIL: "INVALID_EMAIL";
|
|
246
|
-
readonly INVALID_CODE: "INVALID_CODE";
|
|
247
|
-
readonly INTERNAL_SERVER_ERROR: "INTERNAL_SERVER_ERROR";
|
|
248
|
-
readonly DATABASE_CONNECTION_ERROR: "DATABASE_CONNECTION_ERROR";
|
|
249
|
-
readonly INVALID_CONFIGURATION: "INVALID_CONFIGURATION";
|
|
250
|
-
readonly UNKNOWN_OPERATION: "UNKNOWN_OPERATION";
|
|
251
|
-
readonly TOO_MANY_REQUESTS: "TOO_MANY_REQUESTS";
|
|
252
|
-
readonly NETWORK_ERROR: "NETWORK_ERROR";
|
|
253
|
-
readonly TIMEOUT_ERROR: "TIMEOUT_ERROR";
|
|
254
|
-
};
|
|
255
|
-
type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES];
|
|
256
|
-
type ErrorSeverity = "info" | "warning" | "error" | "critical";
|
|
257
|
-
declare const ERROR_SEVERITY_MAP: Record<ErrorCode, ErrorSeverity>;
|
|
258
|
-
interface ParsedError {
|
|
259
|
-
code: ErrorCode;
|
|
260
|
-
message: string;
|
|
261
|
-
severity: ErrorSeverity;
|
|
262
|
-
field?: string;
|
|
263
|
-
details?: Record<string, unknown>;
|
|
264
|
-
}
|
|
265
|
-
/**
|
|
266
|
-
* Parse a Crudify API response and extract standardized error information
|
|
267
|
-
*/
|
|
268
|
-
declare function parseApiError(response: unknown): ParsedError[];
|
|
269
|
-
/**
|
|
270
|
-
* Parse transaction response errors
|
|
271
|
-
*/
|
|
272
|
-
declare function parseTransactionError(response: unknown): ParsedError[];
|
|
273
|
-
/**
|
|
274
|
-
* Get a human-readable error message for an error code
|
|
275
|
-
*/
|
|
276
|
-
declare function getErrorMessage(code: ErrorCode): string;
|
|
277
|
-
/**
|
|
278
|
-
* Handle JavaScript/Network errors and convert to ParsedError
|
|
279
|
-
*/
|
|
280
|
-
declare function parseJavaScriptError(error: unknown): ParsedError;
|
|
281
|
-
/**
|
|
282
|
-
* Universal error handler that can process any type of error from Crudify APIs
|
|
283
|
-
*/
|
|
284
|
-
declare function handleCrudifyError(error: unknown): ParsedError[];
|
|
285
|
-
|
|
286
|
-
interface ErrorTranslationConfig {
|
|
287
|
-
/** Función de traducción de i18next */
|
|
288
|
-
translateFn: (key: string) => string;
|
|
289
|
-
/** Idioma actual (opcional, para logging) */
|
|
290
|
-
currentLanguage?: string;
|
|
291
|
-
/** Habilitar logs de debug */
|
|
292
|
-
enableDebug?: boolean;
|
|
293
|
-
}
|
|
294
|
-
/**
|
|
295
|
-
* Traduce un código de error usando jerarquía de fallbacks
|
|
296
|
-
*/
|
|
297
|
-
declare function translateErrorCode(errorCode: string, config: ErrorTranslationConfig): string;
|
|
298
|
-
/**
|
|
299
|
-
* Traduce múltiples códigos de error
|
|
300
|
-
*/
|
|
301
|
-
declare function translateErrorCodes(errorCodes: string[], config: ErrorTranslationConfig): string[];
|
|
302
|
-
/**
|
|
303
|
-
* Traduce un error completo (código + mensaje personalizado)
|
|
304
|
-
*/
|
|
305
|
-
declare function translateError(error: {
|
|
306
|
-
code: string;
|
|
307
|
-
message?: string;
|
|
308
|
-
field?: string;
|
|
309
|
-
}, config: ErrorTranslationConfig): string;
|
|
310
|
-
/**
|
|
311
|
-
* Hook para usar en componentes React con i18next
|
|
312
|
-
*/
|
|
313
|
-
declare function createErrorTranslator(translateFn: (key: string) => string, options?: {
|
|
314
|
-
currentLanguage?: string;
|
|
315
|
-
enableDebug?: boolean;
|
|
316
|
-
}): {
|
|
317
|
-
translateErrorCode: (code: string) => string;
|
|
318
|
-
translateErrorCodes: (codes: string[]) => string[];
|
|
319
|
-
translateError: (error: {
|
|
320
|
-
code: string;
|
|
321
|
-
message?: string;
|
|
322
|
-
field?: string;
|
|
323
|
-
}) => string;
|
|
324
|
-
translateApiError: (apiResponse: {
|
|
325
|
-
data?: {
|
|
326
|
-
response?: {
|
|
327
|
-
status?: string;
|
|
328
|
-
};
|
|
329
|
-
};
|
|
330
|
-
status?: string;
|
|
331
|
-
code?: string;
|
|
332
|
-
} | null | undefined) => string;
|
|
333
|
-
};
|
|
334
|
-
|
|
335
|
-
export { type ConfigResolverOptions as C, ERROR_CODES as E, type ParsedError as P, type ResolvedTenantConfig as R, type TenantConfig as T, secureLocalStorage as a, type TenantConfigOptions as b, resolveConfig as c, decodeJwtSafely as d, useResolvedConfig as e, type ResolvedConfig as f, getCurrentUserEmail as g, type CrudifyEnvironment as h, isTokenExpired as i, handleCrudifyError as j, parseTransactionError as k, parseJavaScriptError as l, getErrorMessage as m, ERROR_SEVERITY_MAP as n, translateErrorCodes as o, parseApiError as p, translateError as q, resolveTenantConfig as r, secureSessionStorage as s, translateErrorCode as t, useTenantConfig as u, createErrorTranslator as v, type ErrorCode as w, type ErrorSeverity as x, type ErrorTranslationConfig as y };
|