@nocios/crudify-ui 4.4.26 → 4.4.30

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.
@@ -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 _chunkFC7HOMNQjs = require('./chunk-FC7HOMNQ.js');var _react = require('react'); var _react2 = _interopRequireDefault(_react);var _crudifybrowser = require('@nocios/crudify-browser'); var _crudifybrowser2 = _interopRequireDefault(_crudifybrowser);var Y=class r{constructor(){this.listeners=[];this.credentials=null;this.isReady=!1}static getInstance(){return r.instance||(r.instance=new r),r.instance}notifyCredentialsReady(i){this.credentials=i,this.isReady=!0,this.listeners.forEach(e=>{try{e(i)}catch(t){console.error("[CredentialsEventBus] Error in listener:",t)}}),this.listeners=[]}waitForCredentials(){return this.isReady&&this.credentials?Promise.resolve(this.credentials):new Promise(i=>{this.listeners.push(i)})}reset(){this.credentials=null,this.isReady=!1,this.listeners=[]}areCredentialsReady(){return this.isReady&&this.credentials!==null}},Q= exports.a =Y.getInstance();var _jsxruntime = require('react/jsx-runtime');var ee=_react.createContext.call(void 0, void 0),ie= exports.b =({config:r,children:i})=>{let[e,t]=_react.useState.call(void 0, !0),[o,c]=_react.useState.call(void 0, null),[p,y]=_react.useState.call(void 0, !1),[k,h]=_react.useState.call(void 0, ""),[x,u]=_react.useState.call(void 0, );_react.useEffect.call(void 0, ()=>{if(!r.publicApiKey){c("No publicApiKey provided"),t(!1),y(!1);return}let a=`${r.publicApiKey}-${r.env}`;if(a===k&&p){t(!1);return}(async()=>{t(!0),c(null),y(!1);try{_crudifybrowser2.default.config(r.env||"prod");let d=await _crudifybrowser2.default.init(r.publicApiKey,"none");if(u(d),typeof _crudifybrowser2.default.transaction=="function"&&typeof _crudifybrowser2.default.login=="function")y(!0),h(a),d.apiEndpointAdmin&&d.apiKeyEndpointAdmin&&Q.notifyCredentialsReady({apiUrl:d.apiEndpointAdmin,apiKey:d.apiKeyEndpointAdmin});else throw new Error("Crudify methods not properly initialized")}catch(d){let m=d instanceof Error?d.message:"Failed to initialize Crudify";console.error("[CrudifyProvider] Initialization error:",d),c(m),y(!1)}finally{t(!1)}})()},[r.publicApiKey,r.env,k,p]);let s={crudify:p?_crudifybrowser2.default:null,isLoading:e,error:o,isInitialized:p,adminCredentials:x};return _jsxruntime.jsx.call(void 0, ee.Provider,{value:s,children:i})},te= exports.c =()=>{let r=_react.useContext.call(void 0, ee);if(r===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return r};var _cryptojs = require('crypto-js'); var _cryptojs2 = _interopRequireDefault(_cryptojs);var l=class l{static setStorageType(i){l.storageType=i}static generateEncryptionKey(){let i=[navigator.userAgent,navigator.language,navigator.platform,screen.width,screen.height,Date.now().toString(),Math.random().toString(36)].join("|");return _cryptojs2.default.SHA256(i).toString()}static getEncryptionKey(){if(l.encryptionKey)return l.encryptionKey;let i=window.localStorage;if(!i)return l.encryptionKey=l.generateEncryptionKey(),l.encryptionKey;try{let e=i.getItem(l.ENCRYPTION_KEY_STORAGE);return(!e||e.length<32)&&(e=l.generateEncryptionKey(),i.setItem(l.ENCRYPTION_KEY_STORAGE,e)),l.encryptionKey=e,e}catch (e2){return console.warn("Crudify: Cannot persist encryption key, using temporary key"),l.encryptionKey=l.generateEncryptionKey(),l.encryptionKey}}static isStorageAvailable(i){try{let e=window[i],t="__storage_test__";return e.setItem(t,"test"),e.removeItem(t),!0}catch (e3){return!1}}static getStorage(){return l.storageType==="none"?null:l.isStorageAvailable(l.storageType)?window[l.storageType]:(console.warn(`Crudify: ${l.storageType} not available, tokens won't persist`),null)}static encrypt(i){try{let e=l.getEncryptionKey();return _cryptojs2.default.AES.encrypt(i,e).toString()}catch(e){return console.error("Crudify: Encryption failed",e),i}}static decrypt(i){try{let e=l.getEncryptionKey();return _cryptojs2.default.AES.decrypt(i,e).toString(_cryptojs2.default.enc.Utf8)||i}catch(e){return console.error("Crudify: Decryption failed",e),i}}static saveTokens(i){let e=l.getStorage();if(e)try{let t={accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt,savedAt:Date.now()},o=l.encrypt(JSON.stringify(t));e.setItem(l.TOKEN_KEY,o),console.debug("Crudify: Tokens saved successfully")}catch(t){console.error("Crudify: Failed to save tokens",t)}}static getTokens(){let i=l.getStorage();if(!i)return null;try{let e=i.getItem(l.TOKEN_KEY);if(!e)return null;let t=l.decrypt(e),o=JSON.parse(t);return!o.accessToken||!o.refreshToken||!o.expiresAt||!o.refreshExpiresAt?(console.warn("Crudify: Incomplete token data found, clearing storage"),l.clearTokens(),null):Date.now()>=o.refreshExpiresAt?(console.info("Crudify: Refresh token expired, clearing storage"),l.clearTokens(),null):{accessToken:o.accessToken,refreshToken:o.refreshToken,expiresAt:o.expiresAt,refreshExpiresAt:o.refreshExpiresAt}}catch(e){return console.error("Crudify: Failed to retrieve tokens",e),l.clearTokens(),null}}static clearTokens(){let i=l.getStorage();if(i)try{i.removeItem(l.TOKEN_KEY),console.debug("Crudify: Tokens cleared from storage")}catch(e){console.error("Crudify: Failed to clear tokens",e)}}static rotateEncryptionKey(){try{l.clearTokens(),l.encryptionKey=null;let i=window.localStorage;i&&i.removeItem(l.ENCRYPTION_KEY_STORAGE),console.info("Crudify: Encryption key rotated successfully")}catch(i){console.error("Crudify: Failed to rotate encryption key",i)}}static hasValidTokens(){return l.getTokens()!==null}static getExpirationInfo(){let i=l.getTokens();if(!i)return null;let e=Date.now();return{accessExpired:e>=i.expiresAt,refreshExpired:e>=i.refreshExpiresAt,accessExpiresIn:Math.max(0,i.expiresAt-e),refreshExpiresIn:Math.max(0,i.refreshExpiresAt-e)}}static updateAccessToken(i,e){let t=l.getTokens();if(!t){console.warn("Crudify: Cannot update access token, no existing tokens found");return}l.saveTokens({...t,accessToken:i,expiresAt:e})}static subscribeToChanges(i){let e=t=>{if(t.key===l.TOKEN_KEY){if(t.newValue===null){console.debug("Crudify: Tokens removed in another tab"),i(null);return}if(t.newValue){console.debug("Crudify: Tokens updated in another tab");let o=l.getTokens();i(o)}}};return window.addEventListener("storage",e),()=>{window.removeEventListener("storage",e)}}};l.TOKEN_KEY="crudify_tokens",l.ENCRYPTION_KEY_STORAGE="crudify_enc_key",l.encryptionKey=null,l.storageType="localStorage";var f=l;var F=class r{constructor(){this.config={};this.initialized=!1;this.crudifyInitialized=!1;this.lastActivityTime=0;this.isRefreshingLocally=!1;this.refreshPromise=null}static getInstance(){return r.instance||(r.instance=new r),r.instance}async initialize(i={}){if(!this.initialized){if(this.config={storageType:"localStorage",autoRestore:!0,enableLogging:!1,env:"stg",...i},f.setStorageType(this.config.storageType||"localStorage"),this.config.publicApiKey&&!this.crudifyInitialized&&await this.ensureCrudifyInitialized(),_crudifybrowser2.default.setTokenInvalidationCallback(()=>{this.log("Tokens invalidated by crudify-core"),_chunkFC7HOMNQjs.h.emit("SESSION_EXPIRED",{message:"Your session has expired. Please log in again.",source:"crudify-core.clearTokensAndRefreshState"})}),this.config.apiEndpointAdmin&&this.config.apiKeyEndpointAdmin){let e=f.getTokens();e?f.saveTokens({...e,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin}):f.saveTokens({accessToken:"",refreshToken:"",expiresAt:0,refreshExpiresAt:0,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin})}this.config.autoRestore&&await this.restoreSession(),this.initialized=!0}}async login(i,e){try{let t=await _crudifybrowser2.default.login(i,e);if(!t.success)return{success:!1,error:this.formatError(t.errors),rawResponse:t};let o=f.getTokens(),c={accessToken:t.data.token,refreshToken:t.data.refreshToken,expiresAt:t.data.expiresAt,refreshExpiresAt:t.data.refreshExpiresAt,apiEndpointAdmin:_optionalChain([o, 'optionalAccess', _2 => _2.apiEndpointAdmin])||this.config.apiEndpointAdmin,apiKeyEndpointAdmin:_optionalChain([o, 'optionalAccess', _3 => _3.apiKeyEndpointAdmin])||this.config.apiKeyEndpointAdmin};return f.saveTokens(c),this.lastActivityTime=Date.now(),_optionalChain([this, 'access', _4 => _4.config, 'access', _5 => _5.onLoginSuccess, 'optionalCall', _6 => _6(c)]),{success:!0,tokens:c,data:t.data}}catch(t){return console.error("[SessionManager] Login error:",t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}async logout(){try{this.log("Logging out..."),await _crudifybrowser2.default.logout(),f.clearTokens(),this.log("Logout successful"),_optionalChain([this, 'access', _7 => _7.config, 'access', _8 => _8.onLogout, 'optionalCall', _9 => _9()])}catch(i){this.log("Logout error:",i),f.clearTokens()}}async restoreSession(){try{this.log("Attempting to restore session...");let i=f.getTokens();if(!i)return this.log("No valid tokens found in storage"),!1;if(Date.now()>=i.refreshExpiresAt)return this.log("Refresh token expired, clearing storage"),f.clearTokens(),!1;if(_crudifybrowser2.default.setTokens({accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt}),_crudifybrowser2.default.getTokenData().isValid===!1){if(this.log("Restored access token is invalid or expired"),Date.now()<i.refreshExpiresAt&&(this.log("Access token expired but refresh is valid, attempting refresh..."),await this.refreshTokens())){this.log("Session restored successfully via token refresh");let o=f.getTokens();return o&&_optionalChain([this, 'access', _10 => _10.config, 'access', _11 => _11.onSessionRestored, 'optionalCall', _12 => _12(o)]),!0}return f.clearTokens(),await _crudifybrowser2.default.logout(),!1}return this.log("Session restored successfully"),this.lastActivityTime=Date.now(),_optionalChain([this, 'access', _13 => _13.config, 'access', _14 => _14.onSessionRestored, 'optionalCall', _15 => _15(i)]),!0}catch(i){return this.log("Session restore error:",i),f.clearTokens(),await _crudifybrowser2.default.logout(),!1}}isAuthenticated(){return _crudifybrowser2.default.isLogin()||f.hasValidTokens()}getTokenInfo(){let i=_crudifybrowser2.default.getTokenData(),e=f.getExpirationInfo(),t=f.getTokens();return{isLoggedIn:this.isAuthenticated(),crudifyTokens:i,storageInfo:e,hasValidTokens:f.hasValidTokens(),apiEndpointAdmin:_optionalChain([t, 'optionalAccess', _16 => _16.apiEndpointAdmin]),apiKeyEndpointAdmin:_optionalChain([t, 'optionalAccess', _17 => _17.apiKeyEndpointAdmin])}}async refreshTokens(){if(this.isRefreshingLocally&&this.refreshPromise)return this.log("Refresh already in progress, waiting for existing promise..."),this.refreshPromise;this.isRefreshingLocally=!0,this.refreshPromise=this._performRefresh();try{return await this.refreshPromise}finally{this.isRefreshingLocally=!1,this.refreshPromise=null}}async _performRefresh(){try{this.log("Starting token refresh...");let i=await _crudifybrowser2.default.refreshAccessToken();if(!i.success)return this.log("Token refresh failed:",i.errors),f.clearTokens(),_optionalChain([this, 'access', _18 => _18.config, 'access', _19 => _19.showNotification, 'optionalCall', _20 => _20(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _21 => _21.config, 'access', _22 => _22.onSessionExpired, 'optionalCall', _23 => _23()]),!1;let e={accessToken:i.data.token,refreshToken:i.data.refreshToken,expiresAt:i.data.expiresAt,refreshExpiresAt:i.data.refreshExpiresAt};return f.saveTokens(e),this.log("Tokens refreshed and saved successfully"),this.lastActivityTime=Date.now(),!0}catch(i){return this.log("Token refresh error:",i),f.clearTokens(),_optionalChain([this, 'access', _24 => _24.config, 'access', _25 => _25.showNotification, 'optionalCall', _26 => _26(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _27 => _27.config, 'access', _28 => _28.onSessionExpired, 'optionalCall', _29 => _29()]),!1}}isRefreshing(){return this.isRefreshingLocally}setupResponseInterceptor(){_crudifybrowser2.default.setResponseInterceptor(async i=>{this.updateLastActivity();let e=this.detectAuthorizationError(i);if(e.isAuthError){if(this.log("\u{1F6A8} Authorization error detected:",{errorType:e.errorType,shouldLogout:e.shouldTriggerLogout}),e.isRefreshTokenInvalid||e.isTokenRefreshFailed)return this.log("Refresh token invalid, emitting TOKEN_REFRESH_FAILED event"),_chunkFC7HOMNQjs.h.emit("TOKEN_REFRESH_FAILED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"}),i;e.shouldTriggerLogout&&(f.hasValidTokens()&&!e.isIrrecoverable?(this.log("Access token expired, emitting TOKEN_EXPIRED event"),_chunkFC7HOMNQjs.h.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"),_chunkFC7HOMNQjs.h.emit("SESSION_EXPIRED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"})))}return i}),this.log("Response interceptor configured (non-blocking mode)")}async ensureCrudifyInitialized(){if(!this.crudifyInitialized)try{this.log("Initializing crudify SDK...");let i=_crudifybrowser2.default.getTokenData();if(i&&i.endpoint){this.log("Crudify already initialized by another service"),this.crudifyInitialized=!0;return}let e=this.config.env||"stg";_crudifybrowser2.default.config(e);let t=this.config.publicApiKey,o=this.config.enableLogging?"debug":"none",c=await _crudifybrowser2.default.init(t,o);if(c&&c.success===!1&&c.errors)throw new Error(`Failed to initialize crudify: ${JSON.stringify(c.errors)}`);this.crudifyInitialized=!0,this.log("Crudify SDK initialized successfully")}catch(i){throw console.error("[SessionManager] Failed to initialize crudify:",i),i}}detectAuthorizationError(i){let e={isAuthError:!1,isRefreshTokenInvalid:!1,isTokenRefreshFailed:!1,isTokenExpired:!1,isUnauthorized:!1,isIrrecoverable:!1,shouldTriggerLogout:!1,errorType:"",errorDetails:null,userFriendlyMessage:""};if(i.errors&&Array.isArray(i.errors)){let t=i.errors.find(o=>o.errorType==="Unauthorized"||_optionalChain([o, 'access', _30 => _30.message, 'optionalAccess', _31 => _31.includes, 'call', _32 => _32("Unauthorized")])||_optionalChain([o, 'access', _33 => _33.message, 'optionalAccess', _34 => _34.includes, 'call', _35 => _35("Not Authorized")])||_optionalChain([o, 'access', _36 => _36.message, 'optionalAccess', _37 => _37.includes, 'call', _38 => _38("NOT_AUTHORIZED")])||_optionalChain([o, 'access', _39 => _39.message, 'optionalAccess', _40 => _40.includes, 'call', _41 => _41("Token")])||_optionalChain([o, 'access', _42 => _42.message, 'optionalAccess', _43 => _43.includes, 'call', _44 => _44("TOKEN")])||_optionalChain([o, 'access', _45 => _45.message, 'optionalAccess', _46 => _46.includes, 'call', _47 => _47("Authentication")])||_optionalChain([o, 'access', _48 => _48.message, 'optionalAccess', _49 => _49.includes, 'call', _50 => _50("UNAUTHENTICATED")])||_optionalChain([o, 'access', _51 => _51.extensions, 'optionalAccess', _52 => _52.code])==="UNAUTHENTICATED"||_optionalChain([o, 'access', _53 => _53.extensions, 'optionalAccess', _54 => _54.code])==="FORBIDDEN");t&&(e.isAuthError=!0,e.errorType="GraphQL Array",e.errorDetails=t,e.shouldTriggerLogout=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.",(_optionalChain([t, 'access', _55 => _55.message, 'optionalAccess', _56 => _56.includes, 'call', _57 => _57("TOKEN")])||_optionalChain([t, 'access', _58 => _58.message, 'optionalAccess', _59 => _59.includes, 'call', _60 => _60("Token")]))&&(e.isTokenExpired=!0),_optionalChain([t, 'access', _61 => _61.extensions, 'optionalAccess', _62 => _62.code])==="UNAUTHENTICATED"&&(e.isUnauthorized=!0))}if(!e.isAuthError&&i.errors&&typeof i.errors=="object"&&!Array.isArray(i.errors)){let o=Object.values(i.errors).flat().find(c=>typeof c=="string"&&(c.includes("NOT_AUTHORIZED")||c.includes("TOKEN_REFRESH_FAILED")||c.includes("TOKEN_HAS_EXPIRED")||c.includes("PLEASE_LOGIN")||c.includes("Unauthorized")||c.includes("UNAUTHENTICATED")||c.includes("SESSION_EXPIRED")||c.includes("INVALID_TOKEN")));o&&typeof o=="string"&&(e.isAuthError=!0,e.errorType="GraphQL Object",e.errorDetails=i.errors,e.shouldTriggerLogout=!0,o.includes("TOKEN_REFRESH_FAILED")?(e.isTokenRefreshFailed=!0,e.isRefreshTokenInvalid=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Tu sesi\xF3n ha caducado. Por favor, inicia sesi\xF3n nuevamente."):o.includes("TOKEN_HAS_EXPIRED")||o.includes("SESSION_EXPIRED")?(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."):o.includes("INVALID_TOKEN")?(e.isTokenExpired=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Token inv\xE1lido. Por favor, inicia sesi\xF3n nuevamente."):e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!e.isAuthError&&_optionalChain([i, 'access', _63 => _63.data, 'optionalAccess', _64 => _64.response, 'optionalAccess', _65 => _65.status])){let t=i.data.response.status.toUpperCase();(t==="UNAUTHORIZED"||t==="UNAUTHENTICATED")&&(e.isAuthError=!0,e.errorType="Status",e.errorDetails=i.data.response,e.isUnauthorized=!0,e.shouldTriggerLogout=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!e.isAuthError&&_optionalChain([i, 'access', _66 => _66.data, 'optionalAccess', _67 => _67.response, 'optionalAccess', _68 => _68.data]))try{let t=typeof i.data.response.data=="string"?JSON.parse(i.data.response.data):i.data.response.data;(t.error==="REFRESH_TOKEN_INVALID"||t.error==="TOKEN_EXPIRED"||t.error==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Parsed Data",e.errorDetails=t,e.shouldTriggerLogout=!0,e.isIrrecoverable=!0,t.error==="REFRESH_TOKEN_INVALID"?(e.isRefreshTokenInvalid=!0,e.isTokenRefreshFailed=!0,e.userFriendlyMessage="Tu sesi\xF3n ha caducado. Por favor, inicia sesi\xF3n nuevamente."):(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."))}catch (e4){}if(!e.isAuthError&&i.errorCode){let t=i.errorCode.toUpperCase();(t==="UNAUTHORIZED"||t==="UNAUTHENTICATED"||t==="TOKEN_EXPIRED"||t==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Error Code",e.errorDetails={errorCode:t},e.shouldTriggerLogout=!0,t==="TOKEN_EXPIRED"?e.isTokenExpired=!0:e.isUnauthorized=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}return e}updateLastActivity(){this.lastActivityTime=Date.now(),this.log("Last activity updated")}getTimeSinceLastActivity(){return this.lastActivityTime===0?0:Date.now()-this.lastActivityTime}checkInactivity(){let i=this.getTimeSinceLastActivity();if(this.lastActivityTime===0)return"none";let e=1800*1e3;return i>e?(this.log(`Inactivity timeout: ${Math.floor(i/6e4)} minutes since last activity`),"logout"):"none"}clearSession(){f.clearTokens(),_crudifybrowser2.default.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?_chunkFC7HOMNQjs.d.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(i,...e){this.config.enableLogging&&console.log(`[SessionManager] ${i}`,...e)}formatError(i){return i?typeof i=="string"?i:typeof i=="object"?Object.values(i).flat().join(", "):"Authentication failed":"Unknown error"}};function re(r={}){let[i,e]=_react.useState.call(void 0, {isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),t=F.getInstance(),o=_react.useCallback.call(void 0, async()=>{console.log("\u{1F535} [useSession] initialize() CALLED"),console.log("\u{1F50D} [useSession] options received:",{autoRestore:r.autoRestore,enableLogging:r.enableLogging,apiEndpointAdmin:r.apiEndpointAdmin,apiKeyEndpointAdmin:r.apiKeyEndpointAdmin});try{e(n=>({...n,isLoading:!0,error:null}));let u={autoRestore:_nullishCoalesce(r.autoRestore, () => (!0)),enableLogging:_nullishCoalesce(r.enableLogging, () => (!1)),showNotification:r.showNotification,translateFn:r.translateFn,apiEndpointAdmin:r.apiEndpointAdmin,apiKeyEndpointAdmin:r.apiKeyEndpointAdmin,publicApiKey:r.publicApiKey,env:r.env||"stg",onSessionExpired:()=>{e(n=>({...n,isAuthenticated:!1,tokens:null,error:"Session expired"})),_optionalChain([r, 'access', _69 => _69.onSessionExpired, 'optionalCall', _70 => _70()])},onSessionRestored:n=>{e(d=>({...d,isAuthenticated:!0,tokens:n,error:null})),_optionalChain([r, 'access', _71 => _71.onSessionRestored, 'optionalCall', _72 => _72(n)])},onLoginSuccess:n=>{e(d=>({...d,isAuthenticated:!0,tokens:n,error:null}))},onLogout:()=>{e(n=>({...n,isAuthenticated:!1,tokens:null,error:null}))}};console.log("\u{1F50D} [useSession] Calling sessionManager.initialize() with config:",u),await t.initialize(u),console.log("\u2705 [useSession] sessionManager.initialize() completed"),t.setupResponseInterceptor();let s=t.isAuthenticated(),a=t.getTokenInfo();console.log("\u{1F50D} [useSession] After initialize, isAuth:",s),console.log("\u{1F50D} [useSession] After initialize, tokenInfo:",a),e(n=>({...n,isAuthenticated:s,isInitialized:!0,isLoading:!1,tokens:a.crudifyTokens.accessToken?{accessToken:a.crudifyTokens.accessToken,refreshToken:a.crudifyTokens.refreshToken,expiresAt:a.crudifyTokens.expiresAt,refreshExpiresAt:a.crudifyTokens.refreshExpiresAt}:null}))}catch(u){let s=u instanceof Error?u.message:"Initialization failed";e(a=>({...a,isLoading:!1,isInitialized:!0,error:s}))}},[r.autoRestore,r.enableLogging,r.onSessionExpired,r.onSessionRestored]),c=_react.useCallback.call(void 0, async(u,s)=>{e(a=>({...a,isLoading:!0,error:null}));try{let a=await t.login(u,s);return a.success&&a.tokens?e(n=>({...n,isAuthenticated:!0,tokens:a.tokens,isLoading:!1,error:null})):e(n=>({...n,isAuthenticated:!1,tokens:null,isLoading:!1,error:null})),a}catch(a){let n=a instanceof Error?a.message:"Login failed",d=n.includes("INVALID_CREDENTIALS")||n.includes("Invalid email")||n.includes("Invalid password")||n.includes("credentials");return e(m=>({...m,isAuthenticated:!1,tokens:null,isLoading:!1,error:d?null:n})),{success:!1,error:n}}},[t]),p=_react.useCallback.call(void 0, async()=>{e(u=>({...u,isLoading:!0}));try{await t.logout(),e(u=>({...u,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))}catch(u){e(s=>({...s,isAuthenticated:!1,tokens:null,isLoading:!1,error:u instanceof Error?u.message:"Logout error"}))}},[t]),y=_react.useCallback.call(void 0, async()=>{try{let u=await t.refreshTokens();if(u){let s=t.getTokenInfo();e(a=>({...a,tokens:s.crudifyTokens.accessToken?{accessToken:s.crudifyTokens.accessToken,refreshToken:s.crudifyTokens.refreshToken,expiresAt:s.crudifyTokens.expiresAt,refreshExpiresAt:s.crudifyTokens.refreshExpiresAt}:null,error:null}))}else e(s=>({...s,isAuthenticated:!1,tokens:null,error:"Token refresh failed"}));return u}catch(u){return e(s=>({...s,isAuthenticated:!1,tokens:null,error:u instanceof Error?u.message:"Token refresh failed"})),!1}},[t]),k=_react.useCallback.call(void 0, ()=>{e(u=>({...u,error:null}))},[]),h=_react.useCallback.call(void 0, ()=>t.getTokenInfo(),[t]);_react.useEffect.call(void 0, ()=>{o()},[o]),_react.useEffect.call(void 0, ()=>{if(!i.isAuthenticated||!i.tokens)return;let u=_chunkFC7HOMNQjs.i.getInstance(),s=()=>{t.updateLastActivity(),r.enableLogging&&console.log("\u{1F4CD} User navigating - activity updated")},a=u.subscribe(s);window.addEventListener("popstate",s);let n=()=>{let S=t.getTokenInfo().crudifyTokens.expiresIn||0;return S<300*1e3?30*1e3:S<1800*1e3?60*1e3:120*1e3},d,m=()=>{let b=n();d=setTimeout(async()=>{if(t.isRefreshing()){r.enableLogging&&console.log("\u23F8\uFE0F Refresh in progress, rescheduling check"),m();return}let S=t.getTokenInfo(),T=S.crudifyTokens.expiresIn||0,R=(S.crudifyTokens.expiresAt||0)-(Date.now()-T),g=R*.5;if(T>0&&T<=g){let U=Math.round(T/R*100);if(r.enableLogging&&console.log(`\u{1F504} Token at ${U}% of TTL (${Math.round(T/6e4)}min remaining), refreshing...`),e(C=>({...C,isLoading:!0})),await t.refreshTokens()){let C=t.getTokenInfo();e(de=>({...de,isLoading:!1,tokens:C.crudifyTokens.accessToken?{accessToken:C.crudifyTokens.accessToken,refreshToken:C.crudifyTokens.refreshToken,expiresAt:C.crudifyTokens.expiresAt,refreshExpiresAt:C.crudifyTokens.refreshExpiresAt}:null}))}else e(C=>({...C,isLoading:!1,isAuthenticated:!1,tokens:null}))}let O=t.getTimeSinceLastActivity(),w=1800*1e3;O>w?(r.enableLogging&&console.log("\u23F1\uFE0F Inactivity timeout (30min) - logging out"),await p()):m()},b)};return m(),()=>{clearTimeout(d),window.removeEventListener("popstate",s),a()}},[i.isAuthenticated,i.tokens,t,r.enableLogging,p]),_react.useEffect.call(void 0, ()=>{let u=_chunkFC7HOMNQjs.h.subscribe(async s=>{if(r.enableLogging&&console.log(`\u{1F4E2} useSession: Received auth event: ${s.type}`),s.type==="TOKEN_EXPIRED"){if(t.isRefreshing()){r.enableLogging&&console.log("\u23F8\uFE0F Refresh already in progress, skipping TOKEN_EXPIRED handler");return}r.enableLogging&&console.log("\u{1F504} Token expired, attempting refresh..."),e(a=>({...a,isLoading:!0}));try{if(await t.refreshTokens()){r.enableLogging&&console.log("\u2705 Token refreshed successfully");let n=t.getTokenInfo();e(d=>({...d,isLoading:!1,tokens:n.crudifyTokens.accessToken?{accessToken:n.crudifyTokens.accessToken,refreshToken:n.crudifyTokens.refreshToken,expiresAt:n.crudifyTokens.expiresAt,refreshExpiresAt:n.crudifyTokens.refreshExpiresAt}:null}))}else r.enableLogging&&console.log("\u274C Token refresh failed, session expired"),_chunkFC7HOMNQjs.h.emit("SESSION_EXPIRED",{message:"Failed to refresh token after detecting expiration",source:"useSession.TOKEN_EXPIRED handler"})}catch(a){r.enableLogging&&console.error("\u274C Error during token refresh:",a),_chunkFC7HOMNQjs.h.emit("SESSION_EXPIRED",{message:a instanceof Error?a.message:"Unknown error during refresh",source:"useSession.TOKEN_EXPIRED handler (error)"})}}(s.type==="SESSION_EXPIRED"||s.type==="TOKEN_REFRESH_FAILED")&&(r.enableLogging&&console.log(`\u{1F534} Session expired (${s.type}), logging out...`),e(a=>({...a,isAuthenticated:!1,tokens:null,isLoading:!1,error:_optionalChain([s, 'access', _73 => _73.details, 'optionalAccess', _74 => _74.message])||"Session expired"})),_optionalChain([r, 'access', _75 => _75.onSessionExpired, 'optionalCall', _76 => _76()]))});return()=>u()},[r.enableLogging,r.onSessionExpired,t]),_react.useEffect.call(void 0, ()=>{let u=f.subscribeToChanges(s=>{s?(r.enableLogging&&console.log("\u{1F504} Tokens updated in another tab"),e(a=>({...a,tokens:s,isAuthenticated:!0}))):(r.enableLogging&&console.log("\u{1F504} Logout detected in another tab"),e(a=>({...a,isAuthenticated:!1,tokens:null})),_chunkFC7HOMNQjs.h.emit("SESSION_EXPIRED",{message:"Sesi\xF3n cerrada en otra pesta\xF1a",source:"CrossTabSync"}))});return()=>u()},[r.enableLogging]);let x=_react.useCallback.call(void 0, ()=>{t.updateLastActivity()},[t]);return{...i,login:c,logout:p,refreshTokens:y,clearError:k,getTokenInfo:h,updateActivity:x,isExpiringSoon:i.tokens?i.tokens.expiresAt-Date.now()<300*1e3:!1,expiresIn:i.tokens?Math.max(0,i.tokens.expiresAt-Date.now()):0,refreshExpiresIn:i.tokens?Math.max(0,i.tokens.refreshExpiresAt-Date.now()):0}}var _material = require('@mui/material');var _uuid = require('uuid');var _dompurify = require('dompurify'); var _dompurify2 = _interopRequireDefault(_dompurify);var oe=_react.createContext.call(void 0, null),Ie=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}),$= exports.g =({children:r,maxNotifications:i=5,defaultAutoHideDuration:e=6e3,position:t={vertical:"top",horizontal:"right"},enabled:o=!1,allowHtml:c=!1})=>{let[p,y]=_react.useState.call(void 0, []),k=_react.useCallback.call(void 0, (s,a="info",n)=>{if(!o)return"";if(!s||typeof s!="string")return console.warn("\u26A0\uFE0F GlobalNotificationProvider: Invalid message provided"),"";s.length>1e3&&(console.warn("\u26A0\uFE0F GlobalNotificationProvider: Message too long, truncating"),s=s.substring(0,1e3)+"...");let d=_uuid.v4.call(void 0, ),m={id:d,message:s,severity:a,autoHideDuration:_nullishCoalesce(_optionalChain([n, 'optionalAccess', _77 => _77.autoHideDuration]), () => (e)),persistent:_nullishCoalesce(_optionalChain([n, 'optionalAccess', _78 => _78.persistent]), () => (!1)),allowHtml:_nullishCoalesce(_optionalChain([n, 'optionalAccess', _79 => _79.allowHtml]), () => (c))};return y(b=>[...b.length>=i?b.slice(-(i-1)):b,m]),d},[i,e,o,c]),h=_react.useCallback.call(void 0, s=>{y(a=>a.filter(n=>n.id!==s))},[]),x=_react.useCallback.call(void 0, ()=>{y([])},[]),u={showNotification:k,hideNotification:h,clearAllNotifications:x};return _jsxruntime.jsxs.call(void 0, oe.Provider,{value:u,children:[r,o&&_jsxruntime.jsx.call(void 0, _material.Portal,{children:_jsxruntime.jsx.call(void 0, _material.Box,{sx:{position:"fixed",zIndex:9999,[t.vertical]:(t.vertical==="top",24),[t.horizontal]:t.horizontal==="right"||t.horizontal==="left"?24:"50%",...t.horizontal==="center"&&{transform:"translateX(-50%)"},display:"flex",flexDirection:t.vertical==="top"?"column":"column-reverse",gap:1,maxWidth:"400px",width:"auto"},children:p.map(s=>_jsxruntime.jsx.call(void 0, Ne,{notification:s,onClose:()=>h(s.id)},s.id))})})]})},Ne=({notification:r,onClose:i})=>{let[e,t]=_react.useState.call(void 0, !0),o=_react.useCallback.call(void 0, (c,p)=>{p!=="clickaway"&&(t(!1),setTimeout(i,300))},[i]);return _react.useEffect.call(void 0, ()=>{if(!r.persistent&&r.autoHideDuration){let c=setTimeout(()=>{o()},r.autoHideDuration);return()=>clearTimeout(c)}},[r.autoHideDuration,r.persistent,o]),_jsxruntime.jsx.call(void 0, _material.Snackbar,{open:e,onClose:o,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:o,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:r.allowHtml?_jsxruntime.jsx.call(void 0, "span",{dangerouslySetInnerHTML:{__html:Ie(r.message)}}):_jsxruntime.jsx.call(void 0, "span",{children:r.message})})})},se= exports.h =()=>{let r=_react.useContext.call(void 0, oe);if(!r)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return r};var le=_react.createContext.call(void 0, void 0);function ae({children:r,options:i={},config:e,showNotifications:t=!1,notificationOptions:o={}}){let c;try{let{showNotification:n}=se();c=n}catch (e5){}let p={};try{let n=te();n.isInitialized&&n.adminCredentials&&(p=n.adminCredentials)}catch (e6){}let y=_react.useMemo.call(void 0, ()=>{let n=_chunkFC7HOMNQjs.b.call(void 0, {publicApiKey:_optionalChain([e, 'optionalAccess', _80 => _80.publicApiKey]),env:_optionalChain([e, 'optionalAccess', _81 => _81.env]),enableDebug:_optionalChain([i, 'optionalAccess', _82 => _82.enableLogging])});return{publicApiKey:n.publicApiKey,env:n.env||"prod"}},[e,_optionalChain([i, 'optionalAccess', _83 => _83.enableLogging])]),k=_react2.default.useMemo(()=>({...i,showNotification:c,apiEndpointAdmin:p.apiEndpointAdmin,apiKeyEndpointAdmin:p.apiKeyEndpointAdmin,publicApiKey:y.publicApiKey,env:y.env,onSessionExpired:()=>{_optionalChain([i, 'access', _84 => _84.onSessionExpired, 'optionalCall', _85 => _85()])}}),[i,c,p.apiEndpointAdmin,p.apiKeyEndpointAdmin,y]),h=re(k),x=_react.useMemo.call(void 0, ()=>{let n=_chunkFC7HOMNQjs.b.call(void 0, {publicApiKey:_optionalChain([e, 'optionalAccess', _86 => _86.publicApiKey]),env:_optionalChain([e, 'optionalAccess', _87 => _87.env]),appName:_optionalChain([e, 'optionalAccess', _88 => _88.appName]),logo:_optionalChain([e, 'optionalAccess', _89 => _89.logo]),loginActions:_optionalChain([e, 'optionalAccess', _90 => _90.loginActions]),enableDebug:_optionalChain([i, 'optionalAccess', _91 => _91.enableLogging])});return{publicApiKey:n.publicApiKey,env:n.env,appName:n.appName,loginActions:n.loginActions,logo:n.logo}},[e,_optionalChain([i, 'optionalAccess', _92 => _92.enableLogging])]),u=_react.useMemo.call(void 0, ()=>{if(!_optionalChain([h, 'access', _93 => _93.tokens, 'optionalAccess', _94 => _94.accessToken])||!h.isAuthenticated)return null;try{let n=_chunkFC7HOMNQjs.j.call(void 0, h.tokens.accessToken);if(n&&n.sub&&n.email&&n.subscriber){let d={_id:n.sub,email:n.email,subscriberKey:n.subscriber};return Object.keys(n).forEach(m=>{["sub","email","subscriber"].includes(m)||(d[m]=n[m])}),d}}catch(n){console.error("Error decoding JWT token for sessionData:",n)}return null},[_optionalChain([h, 'access', _95 => _95.tokens, 'optionalAccess', _96 => _96.accessToken]),h.isAuthenticated]),s={...h,sessionData:u,config:x},a={enabled:t,maxNotifications:o.maxNotifications||5,defaultAutoHideDuration:o.defaultAutoHideDuration||6e3,position:o.position||{vertical:"top",horizontal:"right"}};return _jsxruntime.jsx.call(void 0, le.Provider,{value:s,children:r})}function Ii(r){let i={enabled:r.showNotifications,maxNotifications:_optionalChain([r, 'access', _97 => _97.notificationOptions, 'optionalAccess', _98 => _98.maxNotifications])||5,defaultAutoHideDuration:_optionalChain([r, 'access', _99 => _99.notificationOptions, 'optionalAccess', _100 => _100.defaultAutoHideDuration])||6e3,position:_optionalChain([r, 'access', _101 => _101.notificationOptions, 'optionalAccess', _102 => _102.position])||{vertical:"top",horizontal:"right"},allowHtml:_optionalChain([r, 'access', _103 => _103.notificationOptions, 'optionalAccess', _104 => _104.allowHtml])||!1};return _optionalChain([r, 'access', _105 => _105.config, 'optionalAccess', _106 => _106.publicApiKey])?_jsxruntime.jsx.call(void 0, ie,{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, $,{...i,children:_jsxruntime.jsx.call(void 0, ae,{...r})})}):_jsxruntime.jsx.call(void 0, $,{...i,children:_jsxruntime.jsx.call(void 0, ae,{...r})})}function we(){let r=_react.useContext.call(void 0, le);if(r===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return r}function Ni(){let r=we();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 Pi=(r={})=>{let{autoFetch:i=!0,retryOnError:e=!1,maxRetries:t=3}=r,[o,c]=_react.useState.call(void 0, null),[p,y]=_react.useState.call(void 0, !1),[k,h]=_react.useState.call(void 0, null),[x,u]=_react.useState.call(void 0, {}),s=_react.useRef.call(void 0, null),a=_react.useRef.call(void 0, !0),n=_react.useRef.call(void 0, 0),d=_react.useRef.call(void 0, 0),m=_react.useCallback.call(void 0, ()=>{c(null),h(null),y(!1),u({})},[]),b=_react.useCallback.call(void 0, async()=>{let S=_chunkFC7HOMNQjs.k.call(void 0, );if(!S){a.current&&(h("No user email available"),y(!1));return}s.current&&s.current.abort();let T=new AbortController;s.current=T;let v=++n.current;try{a.current&&(y(!0),h(null));let R=await _crudifybrowser2.default.readItems("users",{filter:{email:S},pagination:{limit:1}});if(v===n.current&&a.current&&!T.signal.aborted)if(R.success&&R.data&&R.data.length>0){let g=R.data[0];c(g);let O={fullProfile:g,totalFields:Object.keys(g).length,displayData:{id:g.id,email:g.email,username:g.username,firstName:g.firstName,lastName:g.lastName,fullName:g.fullName||`${g.firstName||""} ${g.lastName||""}`.trim(),role:g.role,permissions:g.permissions||[],isActive:g.isActive,lastLogin:g.lastLogin,createdAt:g.createdAt,updatedAt:g.updatedAt,...Object.keys(g).filter(w=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(w)).reduce((w,U)=>({...w,[U]:g[U]}),{})}};u(O),h(null),d.current=0}else h("User profile not found"),c(null),u({})}catch(R){if(v===n.current&&a.current){let g=R;if(g.name==="AbortError")return;e&&d.current<t&&(_optionalChain([g, 'access', _107 => _107.message, 'optionalAccess', _108 => _108.includes, 'call', _109 => _109("Network Error")])||_optionalChain([g, 'access', _110 => _110.message, 'optionalAccess', _111 => _111.includes, 'call', _112 => _112("Failed to fetch")]))?(d.current++,setTimeout(()=>{a.current&&b()},1e3*d.current)):(h("Failed to load user profile"),c(null),u({}))}}finally{v===n.current&&a.current&&y(!1),s.current===T&&(s.current=null)}},[e,t]);return _react.useEffect.call(void 0, ()=>{i&&b()},[i,b]),_react.useEffect.call(void 0, ()=>(a.current=!0,()=>{a.current=!1,s.current&&(s.current.abort(),s.current=null)}),[]),{userProfile:o,loading:p,error:k,extendedData:x,refreshProfile:b,clearProfile:m}};var zi=(r,i={})=>{let{autoFetch:e=!0,onSuccess:t,onError:o}=i,{prefix:c,padding:p=0,separator:y=""}=r,[k,h]=_react.useState.call(void 0, ""),[x,u]=_react.useState.call(void 0, !1),[s,a]=_react.useState.call(void 0, null),n=_react.useRef.call(void 0, !1),d=_react.useCallback.call(void 0, T=>{let v=String(T).padStart(p,"0");return`${c}${y}${v}`},[c,p,y]),m=_react.useCallback.call(void 0, async()=>{u(!0),a(null);try{let T=await _crudifybrowser2.default.getNextSequence(c);if(T.success&&_optionalChain([T, 'access', _113 => _113.data, 'optionalAccess', _114 => _114.value])){let v=d(T.data.value);h(v),_optionalChain([t, 'optionalCall', _115 => _115(v)])}else{let v=_optionalChain([T, 'access', _116 => _116.errors, 'optionalAccess', _117 => _117._error, 'optionalAccess', _118 => _118[0]])||"Failed to generate code";a(v),_optionalChain([o, 'optionalCall', _119 => _119(v)])}}catch(T){let v=T instanceof Error?T.message:"Unknown error";a(v),_optionalChain([o, 'optionalCall', _120 => _120(v)])}finally{u(!1)}},[c,d,t,o]),b=_react.useCallback.call(void 0, async()=>{await m()},[m]),S=_react.useCallback.call(void 0, ()=>{a(null)},[]);return _react.useEffect.call(void 0, ()=>{e&&!k&&!n.current&&(n.current=!0,m())},[e,k,m]),{value:k,loading:x,error:s,regenerate:b,clearError:S}};exports.a = Q; exports.b = ie; exports.c = te; exports.d = f; exports.e = F; exports.f = re; exports.g = $; exports.h = se; exports.i = Ii; exports.j = we; exports.k = Ni; exports.l = Pi; exports.m = zi;