PageSourceSearch

https://rooftopapp.com/chunk-3BCKCKAC.js

js rooftopapp.com collected 2026-10-04 20:03:58 UTC 49,378 bytes, 1 lines download raw bytes

1import{e as ie}from"./chunk-SUY6KX6X.js";import{a as se}from"./chunk-GTEYSQ4V.js";import{a as re}from"./chunk-BW542A5L.js";import{b as ee}from"./chunk-Y2DG2TYW.js";import{a as Z}from"./chunk-LI7KSK6P.js";import{a as $}from"./chunk-VJGBFOXR.js";import{a as te}from"./chunk-372KZGH4.js";import{a as J}from"./chunk-NFLKEUJS.js";import{a as Y,b as X,e as Q,g as D}from"./chunk-ZIRBTTM7.js";import{a as b}from"./chunk-DEALW54I.js";import{a as S}from"./chunk-JWYWOZIG.js";import{a as T,b as p}from"./chunk-JNII2LYP.js";import{J as W}from"./chunk-F7WQZFUR.js";import{b as H,f as z,h as P}from"./chunk-CAOFRRG2.js";import{f as j}from"./chunk-WNNT6KH3.js";import{Ea as E,I as V,Pa as B,Vd as L,bd as G,ga as m,la as u,qa as K,va as q}from"./chunk-7GTDZMJG.js";import{a as _,b as R}from"./chunk-ZGVHDELW.js";var d={OTP_LENGTH:6,OTP_TIMER_SECONDS:60,OTP_RESEND_COOLDOWN_SECONDS:60,MAX_OTP_REQUESTS_PER_WINDOW:3,OTP_RATE_LIMIT_WINDOW_MS:9e5,RECAPTCHA_CONTAINER_ID:"recaptcha-container",RECAPTCHA_SIZE:"invisible",MIN_PHONE_LENGTH:10,MAX_PHONE_LENGTH:15,MIN_USERNAME_LENGTH:3,MAX_USERNAME_LENGTH:20,MIN_NAME_LENGTH:3,MAX_NAME_LENGTH:50,USERNAME_PATTERN:/^[a-zA-Z0-9_]+$/,TOKEN_REFRESH_BEFORE_EXPIRY_MS:3e5,PHONE_FOCUS_DELAY_MS:500,RECAPTCHA_INIT_DELAY_MS:100,RECAPTCHA_INIT_TIMEOUT:2e4,FIREBASE_SMS_REQUEST_TIMEOUT:3e4,TOKEN_FETCH_TIMEOUT:1e4,API_REQUEST_TIMEOUT:15e3,ERRORS:{OTP_INVALID_CODE:"The OTP you entered is incorrect. Please check the code and try again.",OTP_CODE_EXPIRED:"The OTP has expired. Please request a new one.",OTP_SESSION_EXPIRED:"Your session has expired. Please request a new OTP.",OTP_TOO_MANY_REQUESTS:"Too many requests. Please try again later.",RECAPTCHA_FAILED:"Security check failed. Please try again.",PHONE_INVALID:"Please enter a valid phone number.",NETWORK_ERROR:"Network error. Please check your connection and try again.",GENERIC_ERROR:"An error occurred. Please try again."}};var x=p("AuthErrorHandler"),de=new Set(["auth/invalid-phone-number","auth/missing-phone-number","auth/invalid-verification-code","auth/code-expired","auth/session-expired","auth/invalid-verification-id","auth/too-many-requests","auth/quota-exceeded","auth/captcha-check-failed","auth/missing-app-credential","auth/invalid-app-credential","auth/app-not-authorized","auth/app-check-token-expired","auth/rejected-by-app-check","auth/unauthorized-domain","auth/network-request-failed","auth/timeout","auth/internal-error","auth/operation-not-allowed"]);function ne(o){if(typeof o=="string")return o;if(o&&typeof o=="object"&&"code"in o&&typeof o.code=="string")return o.code;if(o instanceof Error)switch(o.message){case"OTP_INVALID_CODE":return"auth/invalid-verification-code";case"OTP_CODE_EXPIRED":return"auth/code-expired";case"OTP_SESSION_EXPIRED":return"auth/session-expired";case"TOO_MANY_REQUESTS":return"auth/too-many-requests";case"NETWORK_ERROR":return"auth/network-request-failed"}return"unknown"}function fe(o){return o.includes("captcha")||o.includes("app-credential")||o.includes("app-check")?"recaptcha":o.includes("verification-code")||o.includes("code-expired")||o.includes("session-expired")||o.includes("verification-id")?"verify":"send"}function w(o,s=fe(ne(o))){let e=ne(o),t=e==="auth/error-code:-39",r=t?"auth/internal-error":e,i={code:r,message:r,userMessage:d.ERRORS.GENERIC_ERROR,shouldRetry:!0,stage:s,recoveryAction:s==="verify"?"retry-verify":"retry-send",retryable:!0,requiresNewCode:!1,requiresFreshVerifier:!1};if(e==="auth/invalid-phone-number"||e==="auth/missing-phone-number")return R(_({},i),{userMessage:d.ERRORS.PHONE_INVALID,recoveryAction:"correct-phone",retryable:!1,shouldRetry:!1});if(e==="auth/invalid-verification-code")return R(_({},i),{userMessage:d.ERRORS.OTP_INVALID_CODE,recoveryAction:"retry-verify"});if(e==="auth/code-expired"||e==="auth/session-expired"||e==="auth/invalid-verification-id")return R(_({},i),{userMessage:d.ERRORS.OTP_SESSION_EXPIRED,recoveryAction:"request-new-code",requiresNewCode:!0});if(e==="auth/too-many-requests"||e==="auth/quota-exceeded"){let n=e==="auth/quota-exceeded"?"SMS service is temporarily unavailable. Please try again later.":d.ERRORS.OTP_TOO_MANY_REQUESTS;return R(_({},i),{userMessage:n,recoveryAction:"wait",retryAfterSeconds:60,cooldownSeconds:60})}return de.has(e)&&(s==="recaptcha"||e==="auth/captcha-check-failed"||e.includes("app-check")||e.includes("credential")||e==="auth/app-not-authorized"||e==="auth/rejected-by-app-check")?R(_({},i),{userMessage:d.ERRORS.RECAPTCHA_FAILED,recoveryAction:"refresh-page",requiresFreshVerifier:!0}):e==="auth/unauthorized-domain"||e==="auth/operation-not-allowed"?R(_({},i),{userMessage:e==="auth/unauthorized-domain"?"Login is not allowed from this website.":"This login method is currently unavailable.",recoveryAction:"contact-support",retryable:!1,shouldRetry:!1}):e==="auth/network-request-failed"||e==="auth/timeout"||e==="NETWORK_E
1RROR"?R(_({},i),{userMessage:d.ERRORS.NETWORK_ERROR,recoveryAction:s==="verify"?"retry-verify":"retry-send"}):e==="auth/internal-error"||t?R(_({},i),{userMessage:"Security verification could not be completed. Please try again.",recoveryAction:s==="verify"?"request-new-code":"retry-send",requiresNewCode:s==="verify",requiresFreshVerifier:!0}):i}function k(o){let s={code:"unknown",message:"",userMessage:d.ERRORS.GENERIC_ERROR,shouldRetry:!0};try{if(o instanceof Error)switch(o.message){case"OTP_INVALID_CODE":case"OTP_CODE_EXPIRED":case"OTP_SESSION_EXPIRED":case"TOO_MANY_REQUESTS":case"NETWORK_ERROR":return k(o.message)}if(typeof o=="string"){switch(o){case"TOO_MANY_REQUESTS":s.code="rate_limit",s.userMessage=d.ERRORS.OTP_TOO_MANY_REQUESTS,s.shouldRetry=!0,s.stage="send",s.recoveryAction="wait",s.retryable=!0,s.retryAfterSeconds=60,s.cooldownSeconds=60,s.requiresNewCode=!1,s.requiresFreshVerifier=!1;break;case"OTP_INVALID_CODE":s.code="auth/invalid-verification-code",s.userMessage=d.ERRORS.OTP_INVALID_CODE,s.stage="verify",s.recoveryAction="retry-verify",s.retryable=!0,s.requiresNewCode=!1,s.requiresFreshVerifier=!1;break;case"OTP_CODE_EXPIRED":s.code="auth/code-expired",s.userMessage=d.ERRORS.OTP_CODE_EXPIRED,s.stage="verify",s.recoveryAction="request-new-code",s.retryable=!0,s.requiresNewCode=!0,s.requiresFreshVerifier=!1;break;case"OTP_SESSION_EXPIRED":s.code="auth/session-expired",s.userMessage=d.ERRORS.OTP_SESSION_EXPIRED,s.stage="verify",s.recoveryAction="request-new-code",s.retryable=!0,s.requiresNewCode=!0,s.requiresFreshVerifier=!1;break;case"OTP_CONFIRMATION_FAILED_FIREBASE":s.code="auth/internal-error",s.userMessage="Security verification could not be completed. Please try again.",s.stage="verify",s.recoveryAction="retry-send",s.retryable=!0,s.requiresNewCode=!1,s.requiresFreshVerifier=!0;break;case"OTP_CONFIRMATION_FAILED_UNKNOWN":s.code="unknown",s.stage="verify",s.recoveryAction="retry-verify",s.retryable=!0,s.requiresNewCode=!1,s.requiresFreshVerifier=!1;break;case"OTP_CONFIRMATION_MISSING":s.code="confirmation_missing",s.userMessage="Please request a new OTP code.",s.shouldRetry=!0;break;case"OTP_USER_CREDENTIAL_ISSUE":s.code="credential_issue",s.userMessage=d.ERRORS.GENERIC_ERROR,s.shouldRetry=!0;break;case"Token fetch timeout":case"OTP verification timeout":case"OAuth token fetch timeout":case"Login success callback t
1imeout":case"FIREBASE_TOKEN_FETCH_FAILED":case"TOKEN_FETCH_TIMEOUT":s.code="timeout",s.userMessage="The request took too long. Please check your connection and try again.",s.shouldRetry=!0;break;case"TOKEN_EXCHANGE_FAILED":s.code="token_exchange",s.userMessage="Unable to complete login. Please try again.",s.shouldRetry=!0;break;case"INVALID_OTP_FORMAT":s.code="invalid_format",s.userMessage="Please enter a valid 6-digit OTP code.",s.shouldRetry=!0;break;case"INVALID_FIREBASE_TOKEN":s.code="invalid_token",s.userMessage=d.ERRORS.GENERIC_ERROR,s.shouldRetry=!1;break;case"NETWORK_ERROR":s.code="network",s.userMessage=d.ERRORS.NETWORK_ERROR,s.shouldRetry=!0;break;default:x.warn("Unknown error string:",o),s.userMessage=d.ERRORS.GENERIC_ERROR}return s.message=o,s}if(o?.code){let e=w(o);s.code=e.code,s.message=e.message,s.userMessage=e.userMessage,s.shouldRetry=e.shouldRetry,s.retryAfterSeconds=e.retryAfterSeconds,s.stage=e.stage,s.recoveryAction=e.recoveryAction,s.retryable=e.retryable,s.cooldownSeconds=e.cooldownSeconds,s.requiresNewCode=e.requiresNewCode,s.requiresFreshVerifier=e.requiresFreshVerifier}if(o?.status)switch(s.code=`http_${o.status}`,s.message=o.statusText||"",o.status){case 400:s.userMessage="Invalid request. Please check your input.",s.shouldRetry=!1;break;case 401:s.userMessage="Authentication failed. Please try again.",s.shouldRetry=!0;break;case 403:s.userMessage="Access denied. Please contact support.",s.shouldRetry=!1;break;case 429:s.userMessage=d.ERRORS.OTP_TOO_MANY_REQUESTS,s.shouldRetry=!0,s.retryAfterSeconds=900;break;case 500:case 502:case 503:s.userMessage="Server error. Please try again later.",s.shouldRetry=!0;break;default:s.userMessage=d.ERRORS.NETWORK_ERROR,s.shouldRetry=!0}x.error("Authentication error:",{code:s.code,message:s.message,originalError:o})}catch(e){x.error("Error while handling auth error:",e),s.userMessage=d.ERRORS.GENERIC_ERROR}return s}function ye(o){return k(o).userMessage}var me=p("AppCheckService"),oe=(()=>{class o{constructor(){this.platformId=u(B),this.app=u(W,{optional:!0}),this.appCheckInstance=E(null),this.initPromise=null,this.appCheckSdk=null,this.interactionWarmupRegistered=!1}ensureInitialized(){if(!L(this.platformId))return Promise.resolve(null);let e=window.location.hostname.endsWith("rooftopapp.com"),t=T.appCheckDebugToken;return!e&&!t?Promise.resolve(null):(t&&(window.FIREBASE_APPCHECK_DEBUG_TOKEN=typeof t=="string"?t:!0),this.appCheckInstance()?Promise.resolve(this.appCheckInstance()):this.initPromise?this.initPromise:this.app?(this.initPromise=(async()=>{try{let r=await import("./chunk-EU5RPOHA.js");this.appCheckSdk=r;let i=r.initializeAppCheck(this.app,{provider:new r.ReCaptchaV3Provider(T.appCheckSiteKey),isTokenAutoRefreshEnabled:!0});return this.appCheckInstance.set(i),i}catch(r){return me.error("App Check initialization failed:",r),null}})(),this.initPromise):Promise.resolve(null))}scheduleInteractionWarmup(){if(!L(this.platformId)||this.interactionWarmupRegistered)return;this.interactionWarmupRegistered=!0;let e=["pointerdown","touchstart","keydown"],t={capture:!0,passive:!0},r=()=>{e.forEach(i=>window.removeEventListener(i,r,t)),this.ensureInitialized()};e.forEach(i=>window.addEventListener(i,r,t))}async getToken(){let e=await this.ensureInitialized();if(!e)return null;let t=await(this.appCheckSdk?this.appCheckSdk.getToken(e).catch(()=>null):null);return t?typeof t=="string"?t:t.token??null:null}static{this.\u0275fac=function(t){return new(t||o)}}static{this.\u0275prov=m({token:o,factory:o.\u0275fac,providedIn:"root"})}}return o})();var pe="rooftop_cookie_consent_v1",M="utm_params",F="original_utm_params",ge=720*60*60*1e3,N={utm_source:"direct",utm_medium:"direct",utm_campaign:"direct",utm_term:"direct",utm_content:"direct"},ae=(()=>{class o{constructor(){this.router=u(P),this.activatedRoute=u(z),this.runtimeService=u(S)}initialize(){this.runtimeService.isBrowser&&(this.router.events.pipe(V(e=>e instanceof H)).subscribe(()=>{this.captureUtmParams(this.activatedRoute.snapshot.queryParams)}),window.addEventListener("rooftop-consent-updated",e=>{if(e.detail?.analytics!==!0){this.clearAllUtms();return}this.captureUtmParams(this.activatedRoute.snapshot.queryParams)}))}captureUtmParams(e){if(!this.hasAnalyticsConsent())return;let t=this.sanitizeUtmParams(e);if(Object.keys(t).length===0)return;let r={params:t,expiresAt:Date.now()+ge};try{sessionStorage.setItem(M,JSON.stringify(r)),this.readStoredParams(localStorage,F)||localStorage.setItem(F,JSON.stringify(r))}catch{}}getLifetimeUtmParams(){return this.runtimeService.isBrowser?this.get
1StoredParams(localStorage,F)??this.getStoredParams(sessionStorage,M)??N:N}getSessionUtmParams(){return this.runtimeService.isBrowser?this.getStoredParams(sessionStorage,M)??N:N}clearAllUtms(){this.runtimeService.isBrowser&&(sessionStorage.removeItem(M),localStorage.removeItem(F))}hasAnalyticsConsent(){if(!this.runtimeService.isBrowser)return!1;try{let e=JSON.parse(localStorage.getItem(pe)??"null");return e?.version===1&&e.analytics===!0}catch{return!1}}sanitizeUtmParams(e){let t={};return Object.keys(N).forEach(r=>{let i=e[r],n=typeof i=="string"?i.trim().replace(/[\u0000-\u001F\u007F]/g,"").slice(0,100):"";n&&(t[r]=n)}),t}getStoredParams(e,t){return!this.runtimeService.isBrowser||!this.hasAnalyticsConsent()?null:this.readStoredParams(e,t)?.params??null}readStoredParams(e,t){try{let r=e.getItem(t);if(!r)return null;let i=JSON.parse(r);return!i?.params||typeof i.expiresAt!="number"||i.expiresAt<=Date.now()?(e.removeItem(t),null):i}catch{return null}}static{this.\u0275fac=function(t){return new(t||o)}}static{this.\u0275prov=m({token:o,factory:o.\u0275fac,providedIn:"root"})}}return o})();var A=p("RateLimiterService"),ce=(()=>{class o{constructor(){this.runtimeService=u(S),this.STORAGE_KEY_PREFIX="rt_ratelimit_"}checkLimit(e,t,r){if(this.runtimeService.isServer)return!0;let i=Date.now(),n=this.getEntry(e);if(!n||i-n.windowStart>r)return this.setEntry(e,{count:1,windowStart:i,lastAttempt:i}),!0;if(n.count>=t){let c=r-(i-n.windowStart);return A.warn(`Rate limit exceeded for ${e}. Try again in ${Math.ceil(c/1e3)}s`),!1}return this.setEntry(e,R(_({},n),{count:n.count+1,lastAttempt:i})),!0}getTimeRemaining(e,t){if(this.runtimeService.isServer)return 0;let r=this.getEntry(e);if(!r)return 0;let n=Date.now()-r.windowStart;return n>t?0:Math.ceil((t-n)/1e3)}reset(e){if(!this.runtimeService.isServer)try{sessionStorage.removeItem(this.STORAGE_KEY_PREFIX+e),A.info(`Rate limit reset for: ${e}`)}catch(t){A.error(`Failed to reset rate limit for ${e}:`,t)}}clearAll(){if(!this.runtimeService.isServer)try{Object.keys(sessionStorage).forEach(t=>{t.startsWith(this.STORAGE_KEY_PREFIX)&&sessionStorage.removeItem(t)}),A.info("All rate limits cleared")}catch(e){A.error("Failed to clear rate limits:",e)}}getEntry(e){try{let t=sessionStorage.getItem(this.STORAGE_KEY_PREFIX+e);return t?JSON.parse(t):null}catch(t){return A.error(`Failed to get rate limit entry for ${e}:`,t),null}}setEntry(e,t){try{sessionStorage.setItem(this.STORAGE_KEY_PREFIX+e,JSON.stringify(t))}catch(r){A.error(`Failed to set rate limit entry for ${e}:`,r)}}static{this.\u0275fac=function(t){return new(t||o)}}static{this.\u0275prov=m({token:o,factory:o.\u0275fac,providedIn:"root"})}}return o})();var g=p("SecureStorageService"),U=(()=>{class o{constructor(){this.runtimeService=u(S),this.DB_NAME="rooftop_secure_storage",this.DB_VERSION=1,this.STORE_NAME="auth",this.SENSITIVE_KEYS=["access_token","refresh_token","firebase_token","encryption_key","oauth_token"]}async setSecure(e,t,r){if(this.runtimeService.isServer){g.warn("Secure storage not available on server");return}try{let{encryptedValue:i,iv:n,encryptionKey:c}=await this.encrypt(t),l=await this.openDatabase(),h=l.transaction(this.STORE_NAME,"readwrite"),f=h.objectStore(this.STORE_NAME),C={id:e,value:i,iv:Array.from(n),encrypted:!0,timestamp:Date.now()};r&&(C.expires=Date.now()+r*1e3),f.put(C),await this.storeEncryptionKey(e,c),await this.promisifyTransaction(h),l.close(),g.info(`Securely stored: ${e}`)}catch(i){throw g.error(`Failed to securely store ${e}:`,i),i}}async setItem(e,t,r){let i=typeof t=="string"?t:JSON.stringify(t);return this.setSecure(e,i,r)}
1async getItem(e){let t=await this.getSecure(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}}async removeItem(e){return this.remove(e)}async set(e,t){return this.setItem(e,t)}async get(e){return this.getItem(e)}async getSecure(e){if(this.runtimeService.isServer)return null;try{let t=await this.openDatabase(),i=t.transaction(this.STORE_NAME,"readonly").objectStore(this.STORE_NAME),n=await this.promisifyRequest(i.get(e));if(t.close(),!n)return null;if(n.expires&&n.expires<Date.now())return g.info(`${e} has expired, removing it`),await this.remove(e),null;if(n.encrypted&&n.iv&&n.value){let c=await this.getEncryptionKey(e);if(!c)return g.error(`Encryption key not found for ${e}`),null;let l=new Uint8Array(n.iv);return await this.decrypt(n.value,c,l)}return n.value||null}catch(t){return g.error(`Failed to retrieve ${e}:`,t),null}}async remove(e){if(!this.runtimeService.isServer)try{let t=await this.openDatabase(),r=t.transaction(this.STORE_NAME,"readwrite"),i=r.objectStore(this.STORE_NAME);i.delete(e),i.delete(`${e}_encryption_key`),await this.promisifyTransaction(r),t.close(),g.info(`Removed: ${e}`)}catch(t){g.error(`Failed to remove ${e}:`,t)}}async clearAuthData(){if(!this.runtimeService.isServer)try{let e=["access_token","refresh_token","firebase_token","oauth_token","phone_number","user_data"];for(let t of e)await this.remove(t);g.info("All auth data cleared")}catch(e){g.error("Failed to clear auth data:",e)}}setNonSensitive(e,t){if(!this.runtimeService.isServer)try{sessionStorage.setItem(e,t)}catch(r){g.error(`Failed to store in sessionStorage: ${e}`,r)}}getNonSensitive(e){if(this.runtimeService.isServer)return null;try{return sessionStorage.getItem(e)}catch(t){return g.error(`Failed to retrieve from sessionStorage: ${e}`,t),null}}openDatabase(){return this.runtimeService.isServer?Promise.reject(new Error("IndexedDB is not available on the server")):new Promise((e,t)=>{let r=indexedDB.open(this.DB_NAME,this.DB_VERSION);r.onerror=()=>{g.error("Failed to open IndexedDB"),t(r.error)},r.onsuccess=()=>{e(r.result)},r.onupgradeneeded=i=>{let n=i.target.result;n.objectStoreNames.contains(this.STORE_NAME)||n.createObjectStore(this.STORE_NAME,{keyPath:"id"})}})}async encrypt(e){if(this.runtimeService.isServer)throw new Error("Encryption is not available on the server");let r=new TextEncoder().encode(e),i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),n=crypto.getRandomValues(new Uint8Array(12)),c=await crypto.subtle.encrypt({name:"AES-GCM",iv:n},i,r),l=Array.from(new Uint8Array(c));return{encryptedValue:btoa(String.fromCharCode(...l)),iv:n,encryptionKey:i}}async decrypt(e,t,r){if(this.runtimeService.isServer)return"";try{if(!e||!t||!r)throw new Error("Invalid decryption parameters");if(r.length!==12)throw new Error("Invalid IV length");let i=Uint8Array.from(atob(e),h=>h.charCodeAt(0)),n=await crypto.subtle.decrypt({name:"AES-GCM",iv:r},t,i),l=new TextDecoder().decode(n);if(!l)throw new Error("Decryption resulted in empty data");return l}catch(i){throw i instanceof Error?g.error("Decryption failed:",i.message):g.error("Decryption failed with unknown error"),new Error("Failed to decrypt data")}}async storeEncryptionKey(e,t){if(this.runtimeService.isServer)return;let r=await crypto.subtle.exportKey("raw",t),i=await this.openDatabase(),n=i.transaction(this.STORE_NAME,"readwrite");n.objectStore(this.STORE_NAME).put({id:`${e}_encryption_key`,key:Array.from(new Uint8Array(r)),encrypted:!1}),await this.promisifyTransaction(n),i.close()}async getEncryptionKey(e){if(this.runtimeService.isServer)return null;try{let t=await this.openDatabase(),i=t.transaction(this.STORE_NAME,"readonly").objectStore(this.STORE_NAME),n=await this.promisifyRequest(i.get(`${e}_encryption_key`));if(t.close(),!n||!n.key)return null;let c=new Uint8Array(n.key);return await crypto.subtle.importKey("raw",c,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"])}catch(t){return g.error("Failed to retrieve encryption key:",t),null}}promisifyRequest(e){return new Promise((t,r)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>r(e.error)})}promisifyTransaction(e){return new Promise((t,r)=>{e.oncomplete=()=>t(),e.onerror=()=>r(e.error),e.onabort=()=>r(new Error("Transaction aborted"))})}static{this.\u0275fac=function(t){return new(t||o)}}static{this.\u0275prov=m({token:o,factory:o.\u0275fac,providedIn:"root"})}}return o}
1)();var I=p("SessionMonitorService"),ue=(()=>{class o{constructor(){this.sessionActive=E(!0),this.timeUntilTimeout=E(null),this.runtimeService=u(S),this.secureStorage=u(U),this.SESSION_KEY="session_activity",this.INACTIVITY_TIMEOUT=1800*1e3,this.WARNING_BEFORE_TIMEOUT=300*1e3,this.runtimeService.isBrowser&&this.initializeMonitoring()}startNewSession(){let e={lastActivity:Date.now(),sessionStart:Date.now(),activityCount:0};this.saveSession(e),this.resetInactivityTimer(),this.sessionActive.set(!0)}updateActivity(){let e=this.loadSession();if(!e){this.startNewSession();return}e.lastActivity=Date.now(),e.activityCount++,this.saveSession(e),this.resetInactivityTimer(),this.sessionActive.set(!0)}onWarning(e){this.onWarningCallback=e}onTimeout(e){this.onTimeoutCallback=e}extendSession(){this.updateActivity(),this.timeUntilTimeout.set(null),I.info("Session manually extended")}endSession(){this.clearSession(),this.sessionActive.set(!1),this.activityTimer&&window.clearTimeout(this.activityTimer),this.warningTimer&&window.clearTimeout(this.warningTimer),I.info("Session ended")}getSessionDuration(){let e=this.loadSession();return e?Date.now()-e.sessionStart:0}getTimeSinceActivity(){let e=this.loadSession();return e?Date.now()-e.lastActivity:0}initializeMonitoring(){let e=this.loadSession();!e||this.isSessionExpired(e)?this.startNewSession():this.resumeSession(e),this.setupActivityListeners(),this.setupCrossTabSync()}resumeSession(e){this.updateActivity()}isSessionExpired(e){return Date.now()-e.lastActivity>this.INACTIVITY_TIMEOUT}setupActivityListeners(){let e=["mousedown","keydown","scroll","touchstart","click"],t=0,r=5e3,i=()=>{let n=Date.now();n-t>r&&(t=n,this.updateActivity())};e.forEach(n=>{window.addEventListener(n,i,{passive:!0})}),document.addEventListener("visibilitychange",()=>{document.hidden||this.updateActivity()})}resetInactivityTimer(){this.activityTimer&&window.clearTimeout(this.activityTimer),this.warningTimer&&window.clearTimeout(this.warningTimer),this.warningTimer=window.setTimeout(()=>{I.warn("Session inactivity warning"),this.timeUntilTimeout.set(this.WARNING_BEFORE_TIMEOUT),this.onWarningCallback?.()},this.INACTIVITY_TIMEOUT-this.WARNING_BEFORE_TIMEOUT),this.activityTimer=window.setTimeout(()=>{I.warn("Session timeout due to inactivity"),this.handleSessionTimeout()},this.INACTIVITY_TIMEOUT)}handleSessionTimeout(){this.sessionActive.set(!1),this.clearSession(),this.onTimeoutCallback?.()}setupCrossTabSync(){window.addEventListener("storage",e=>{if(e.key===this.SESSION_KEY&&e.newValue)try{let t=JSON.parse(e.newValue);this.isSessionExpired(t)?this.handleSessionTimeout():this.resetInactivityTimer()}catch(t){I.error("Error parsing session from storage event:",t)}})}loadSession(){try{let e=localStorage.getItem(this.SESSION_KEY);return e?JSON.parse(e):null}catch(e){return I.error("Error loading session:",e),null}}saveSession(e){try{localStorage.setItem(this.SESSION_KEY,JSON.stringify(e))}catch(t){I.error("Error saving session:",t)}}clearSession(){try{localStorage.removeItem(this.SESSION_KEY)}catch(e){I.error("Error clearing session:",e)}}static{this.\u0275fac=function(t){return new(t||o)}}static{this.\u0275prov=m({token:o,factory:o.\u0275fac,providedIn:"root"})}}return o})();var v=p("DeviceBindingService"),he=(()=>{class o{constructor(){this.secureStorage=u(U),this.runtime=u(S),this.DEVICE_KEY="device_fingerprint",this.DEVICE_ID_KEY="device_id"}async generateFingerprint(){if(this.runtime.isServer)throw new Error("Device fingerprinting not available on server");try{let e={deviceId:await this.generateDeviceId(),userAgent:navigator.userAgent,screenResolution:`${screen.width}x${screen.height}`,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,language:navigator.language,platform:navigator.platform,hardwareConcurrency:navigator.hardwareConcurrency||0,deviceMemory:navigator.deviceMemory,colorDepth:screen.colorDepth,pixelRatio:window.devicePixelRatio,touchSupport:"ontouchstart"in window||navigator.maxTouchPoints>0,vendor:navigator.vendor,canvas:await this.getCanvasFingerprint(),webgl:await this.getWebGLFingerprint(),createdAt:Date.now()};return await this.secureStorage.setItem(this.DEVICE_KEY,e),v.info("Device fingerprint generated",{deviceId:e.deviceId,platform:e.platform}),e}catch(e){throw v.error("Failed to generate device fingerprint",e),e}}async getFingerprint(){try{return await this.secureStorage.getItem(this.DEVICE_KEY)}catch(e){return v.error("Failed to get device fingerprint",e),null}}async getDeviceId(){try{let e=await this.secureStorage.getItem(this.DEVICE_ID_KEY);return e||await this.generateDeviceId()}catch(e){throw v.error("Failed to get device ID",e),e}}async verifyDevice(){if(this.runtime.isServer)return!0;try{let e=await this.getFingerprint();if(!e)return v.warn("No stored fingerprint found, device verification skipped"),!0;let t=await this.generateFingerprint(),n=[t.deviceId===e.deviceId,t.userAgent===e.userAgent,t.platform===e.platform,t.timezone===e.timezone].filter(
1Boolean).length>=3;return n||v.warn("Device verification failed",{stored:{deviceId:e.deviceId,platform:e.platform},current:{deviceId:t.deviceId,platform:t.platform}}),n}catch(e){return v.error("Device verification error",e),!1}}async clearFingerprint(){try{await this.secureStorage.removeItem(this.DEVICE_KEY),v.info("Device fingerprint cleared")}catch(e){v.error("Failed to clear device fingerprint",e)}}async getDeviceInfo(){let e=await this.getFingerprint();return e?{deviceId:e.deviceId,platform:e.platform,timezone:e.timezone,language:e.language}:{}}async hasDeviceChanged(){return!await this.verifyDevice()}async generateDeviceId(){try{let e=await this.secureStorage.getItem(this.DEVICE_ID_KEY);if(e)return e;let t;if(crypto.randomUUID)t=crypto.randomUUID();else{let r=new Uint8Array(16);crypto.getRandomValues(r),t=Array.from(r,i=>i.toString(16).padStart(2,"0")).join("")}return await this.secureStorage.setItem(this.DEVICE_ID_KEY,t),v.info("New device ID generated",{deviceId:t}),t}catch(e){throw v.error("Failed to generate device ID",e),e}}async getCanvasFingerprint(){try{let e=document.createElement("canvas"),t=e.getContext("2d");if(!t)return"unsupported";let r="DeviceFingerprint@123";t.textBaseline="top",t.font="14px Arial",t.textBaseline="alphabetic",t.fillStyle="#f60",t.fillRect(125,1,62,20),t.fillStyle="#069",t.fillText(r,2,15),t.fillStyle="rgba(102, 204, 0, 0.7)",t.fillText(r,4,17);let i=e.toDataURL();return await this.hashString(i)}catch(e){return v.error("Failed to generate canvas fingerprint",e),"error"}}async getWebGLFingerprint(){try{let e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");if(!t)return"unsupported";let r=t.getExtension("WEBGL_debug_renderer_info"),i=r?t.getParameter(r.UNMASKED_VENDOR_WEBGL):"unknown",n=r?t.getParameter(r.UNMASKED_RENDERER_WEBGL):"unknown",c=`${i}|${n}`;return await this.hashString(c)}catch(e){return v.error("Failed to generate WebGL fingerprint",e),"error"}}async hashString(e){try{let r=new TextEncoder().encode(e),i=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(i)).map(c=>c.toString(16).padStart(2,"0")).join("").substring(0,16)}catch(t){return v.error("Failed to hash string",t),e.substring(0,16)}}static{this.\u0275fac=function(t){return new(t||o)}}static{this.\u0275prov=m({token:o,factory:o.\u0275fac,providedIn:"root"})}}return o})();var y=p("TokenRefreshService"),le=(()=>{class o{constructor(){this.refreshTimer=null,this.isRefreshing=!1,this.apiService=u(b),this.userService=u(D),this.runtimeService=u(S),this.runtimeService.isBrowser&&this.initializeTokenMonitoring()}async startTokenRefreshMonitoring(e){if(!this.runtimeService.isBrowser)return;let t=Date.now()+e*1e3;this.scheduleTokenRefresh(t)}stopTokenRefreshMonitoring(){y.info("Stopping token refresh monitoring"),this.clearRefreshTimer()}ngOnDestroy(){this.clearRefreshTimer()}async initializeTokenMonitoring(){try{let e=await this.getTokenExpiryTime();e&&this.scheduleTokenRefresh(e)}catch(e){y.error("Failed to initialize token monitoring:",e)}}scheduleTokenRefresh(e){this.clearRefreshTimer();let r=e-d.TOKEN_REFRESH_BEFORE_EXPIRY_MS-Date.now();r<=0?(y.info("Token expired or expiring soon, refreshing immediately"),this.refreshTokenNow()):(y.info(`Token refresh scheduled in ${Math.round(r/1e3/60)} minutes`),this.refreshTimer=setTimeout(()=>{this.refreshTokenNow()},r))}async refreshTokenNow(){if(this.isRefreshing){y.info("Token refresh already in progress, skipping");return}this.isRefreshing=!0,y.info("Starting token refresh");try{if(await this.apiService.refreshToken()){y.info("Token refreshed successfully");let t=await this.getTokenExpiryTime();t&&this.scheduleTokenRefresh(t)}else y.warn("Token refresh failed, triggering logout"),await this.handleRefreshFailure()}catch(e){y.error("Error during token refresh:",e),await this.handleRefreshFailure()}finally{this.isRefreshing=!1}}async handleRefreshFailure(){try{y.warn("Token refresh failed, clearing auth data and redirecting to login"),await this.apiService.clearAllAuthData(),this.userService.clearCurrentUser(),this.runtimeService.isBrowser&&(window.location.href="/"),y.info("User session cleared due to token refresh failure")}catch(e){y.error("Error during refresh failure handling:",e)}}async getTokenExpiryTime(){return await this.apiService.getTokenExpiry()}clearRefreshTimer(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null)}static{this.\u0275fac=function(t){return new(t||o)}}static{this.\u0275prov=m({token:o,factory:o.\u0275fac,providedIn:"root"})}}return o}
1)();var a=p("AuthService"),Vt=(()=>{class o{constructor(){this.auth=u(X),this.http=u(j),this.apiService=u(b),this.userService=u(D),this.analyticsGaService=u(ee),this.appCheckService=u(oe),this._authStatus=E("idle"),this.authStatus=this._authStatus.asReadonly(),this._otpSendDelayed=E(!1),this.otpSendDelayed=this._otpSendDelayed.asReadonly(),this._authError=E(null),this.authError=this._authError.asReadonly(),this._phoneAuthFailure=E(null),this.phoneAuthFailure=this._phoneAuthFailure.asReadonly(),this._rateLimitCooldown=E(0),this.rateLimitCooldown=this._rateLimitCooldown.asReadonly(),this._appCheckStatus=E("unchecked"),this.appCheckStatus=this._appCheckStatus.asReadonly(),this.isBypassEnabled=E(T.firebaseBypass),this.isAuthenticated=G(()=>this.userService.isLoggedIn()),this.guestCartService=u(J),this.cartService=u(Z),this.liftService=u(se),this.wishlistService=u(te),this.utmService=u(ae),this.router=u(P),this.rateLimiter=u(ce),this.errorTracking=u(ie),this.sessionMonitor=u(ue),this.deviceBinding=u(he),this.sanitization=u($),this.injector=u(q),this.cacheService=u(re),this.confirmationRecaptchaContainerId=null,this.#e=u(S),this._lastMergeResult=E(null),this.lastMergeResult=this._lastMergeResult.asReadonly(),this._isMergeInProgress=E(!1),this.isMergeInProgress=this._isMergeInProgress.asReadonly(),this._mergeCompletionResolver=null,this._mergeCompletionPromise=null,this._recaptchaLifecycles=new Map}async checkAppCheckStatus(){if(!this.#e.isBrowser)return!0;try{return await this.appCheckService.getToken()?(this._appCheckStatus.set("valid"),!0):(this._appCheckStatus.set("invalid"),!1)}catch(e){return a.error("App Check validation failed:",e),this._appCheckStatus.set("invalid"),!1}}#e;async waitForMergeCompletion(e=8e3){return!this._isMergeInProgress()&&this._lastMergeResult()!==null?this._lastMergeResult():!this._isMergeInProgress()&&this._mergeCompletionPromise===null?this._lastMergeResult():this._mergeCompletionPromise?Promise.race([this._mergeCompletionPromise,new Promise(t=>setTimeout(()=>{a.warn("Cart merge wait timed out after",e,"ms"),t(this._lastMergeResult())},e))]):this._lastMergeResult()}consumeLastMergeResult(){let e=this._lastMergeResult();return this._lastMergeResult.set(null),e}clearLastMergeResult(){this._lastMergeResult.set(null)}getRecaptchaLifecycle(e){let t=this._recaptchaLifecycles.get(e);return t||(t={verifier:null,initPromise:null,activeRequest:null,delayedTimer:null,delayedRequest:null,disposalRequested:!1},this._recaptchaLifecycles.set(e,t)),t}resolveRecaptchaTarget(e){if(typeof e=="string"){let t=this.getRecaptchaLifecycle(e);return t.verifier?{containerId:e,lifecycle:t,verifier:t.verifier}:null}for(let[t,r]of this._recaptchaLifecycles)if(r.verifier===e)return{containerId:t,lifecycle:r,verifier:e};return{containerId:null,lifecycle:null,verifier:e}}getRecaptchaVerifier(e){return this.getRecaptchaLifecycle(e).verifier}get recaptchaVerifier(){return this.getRecaptchaVerifier("recaptcha-container-login")}async initRecaptchaVerifier(e){if(!this.#e.isBrowser)return a.warn("RecaptchaVerifier cannot be initialized on the server."),!1;if(T.firebaseBypass)return!0;try{let t=this.getRecaptchaLifecycle(e);
1if(t.disposalRequested){if(t.initPromise)return t.initPromise.then(()=>this.initRecaptchaVerifier(e));this.disposeRecaptchaIfIdle(e,t)}if(t.verifier)return a.info("reCAPTCHA already initialized for container:",e),!0;if(t.initPromise)return t.initPromise;if(!document.getElementById(e))return a.warn(`Recaptcha container with ID '${e}' not found in the DOM.`),!1;let i=new Y(this.auth,e,{size:d.RECAPTCHA_SIZE});return t.initPromise=Promise.resolve().then(()=>i.render()).then(()=>(t.verifier=i,t.disposalRequested?(this.disposeRecaptchaIfIdle(e,t),!1):!0)).catch(n=>{a.error("Error initializing or rendering RecaptchaVerifier:",n);try{i.clear()}catch(c){a.warn(`Error clearing RecaptchaVerifier for ${e}:`,c)}return!1}).finally(()=>{t.initPromise=null,this.disposeRecaptchaIfIdle(e,t)}),t.initPromise}catch(t){return a.error("Error initializing or rendering RecaptchaVerifier:",t),!1}}ensureRecaptchaReady(e){return this.initRecaptchaVerifier(e)}disposeRecaptchaIfIdle(e,t=this.getRecaptchaLifecycle(e)){if(!t.disposalRequested||t.initPromise||t.activeRequest)return;if(!t.verifier){t.disposalRequested=!1;return}let r=t.verifier;t.verifier=null,t.disposalRequested=!1;try{r.clear()}catch(i){a.warn(`Error clearing RecaptchaVerifier for ${e}:`,i)}}startOtpDelayedTimer(e,t){e.delayedRequest=t,e.delayedTimer=setTimeout(()=>{e.activeRequest===t&&e.delayedRequest===t&&this._otpSendDelayed.set(!0)},3e4)}clearOtpDelayedTimer(e,t){e.delayedRequest===t&&(e.delayedTimer&&clearTimeout(e.delayedTimer),e.delayedTimer=null,e.delayedRequest=null,this._otpSendDelayed.set(!1))}clearRecaptchaVerifier(e="recaptcha-container-login"){let t=this.getRecaptchaLifecycle(e);t.disposalRequested=!0,this.disposeRecaptchaIfIdle(e,t)}requestRecaptchaDisposal(e="recaptcha-container-login"){this.clearRecaptchaVerifier(e)}startRateLimitTimer(e){this._rateLimitCooldown.set(e);let t=setInterval(()=>{let r=this._rateLimitCooldown();r<=1?(this._rateLimitCooldown.set(0),clearInterval(t)):this._rateLimitCooldown.set(r-1)},1e3)}async sendOtp(e,t="recaptcha-container-login"){if(this._authError.set(null),this._phoneAuthFailure.set(null),this._authStatus.set("sending_otp"),!this.#e.isBrowser){a.error("OTP sending is not supported on the server.");let h=new Error("OTP sending is not supported on the server.");throw this._phoneAuthFailure.set(w(h,"send")),this._authError.set(this._phoneAuthFailure().userMessage),this.errorTracking.trackAuthError(h,{action:"sendOtp",metadata:{reason:"server-side-call"}}),h}let r=this.sanitization.sanitizePhoneNumber(e);if(!r||r.length<10){a.error("Invalid phone number format after sanitization");let h=new Error("INVALID_PHONE_NUMBER"),f=w({code:"auth/invalid-phone-number"},"send");throw this._phoneAuthFailure.set(f),this._authError.set(f.userMessage),this.errorTracking.trackAuthError(h,{action:"sendOtp",metadata:{reason:"invalid-format"}}),h}if(T.firebaseBypass){a.info("\u{1F513} Firebase OTP Bypass Mode: Enabled - Skipping Firebase OTP"),a.info(`\u{1F4F1} Phone: ${r} - Use any 6-digit code to login`),this.confirmationResult={_bypassMode:!0,_phone:r},this.confirmationRecaptchaContainerId=null,await this.apiService.storePhoneNumber(r.replace(/\s+/g,"")),this._authStatus.set("otp_
1sent"),this._authError.set(null);return}a.info(`\u{1F525} Normal Firebase Mode: Sending OTP to ${r.slice(0,4)}...${r.slice(-4)}`);let i=this.resolveRecaptchaTarget(t),n=i?.lifecycle,c=i?.containerId,l=i?.verifier;if(!l){a.error("RecaptchaVerifier is not initialized. Cannot send OTP.");let h=new Error("RecaptchaVerifier is not initialized. Please ensure it is initialized before sending OTP."),f=w({code:"auth/captcha-check-failed"},"recaptcha");throw this._phoneAuthFailure.set(f),this._authError.set(f.userMessage),this.errorTracking.trackAuthError(h,{action:"sendOtp",metadata:{reason:"recaptcha-not-initialized"}}),h}try{await this.appCheckService.ensureInitialized(),a.info("[AuthService.sendOtp] Calling Firebase signInWithPhoneNumber...");let h=n?.activeRequest??K(this.injector,async()=>{try{let f=await Q(this.auth,r,l);return a.info("[AuthService.sendOtp] Firebase signInWithPhoneNumber SUCCESS"),f}catch(f){throw a.error("[AuthService.sendOtp] Firebase signInWithPhoneNumber FAILED:",{code:f?.code,message:f?.message}),f}});if(n&&!n.activeRequest&&(n.activeRequest=h,this.startOtpDelayedTimer(n,h),h.finally(()=>{n.activeRequest===h&&(n.activeRequest=null),this.clearOtpDelayedTimer(n,h),c&&n&&this.disposeRecaptchaIfIdle(c,n)}).catch(()=>{})),this.confirmationResult=await h,this.confirmationRecaptchaContainerId=c??null,!this.confirmationResult)throw new Error("Firebase returned null confirmation result");await this.apiService.storePhoneNumber(r.replace(/\s+/g,"")),this._authStatus.set("otp_
1sent")}catch(h){this._authStatus.set("error");let f=w(h,"send"),C=k(h);throw this._phoneAuthFailure.set(f),this._authError.set(f.userMessage||C.userMessage),f.cooldownSeconds&&this.startRateLimitTimer(f.cooldownSeconds),f.requiresFreshVerifier&&c&&this.requestRecaptchaDisposal(c),a.error("Phone authentication error:",h),this.errorTracking.trackAuthError(h,{action:"sendOtp",metadata:{errorCode:h?.code||"UNKNOWN",errorMessage:h?.message||"Unknown error",phoneNumber:r.slice(-4)}}),h}}async confirmOtp(e){if(this._authStatus.set("verifying_otp"),this._authError.set(null),this._phoneAuthFailure.set(null),!this.confirmationResult){a.error("No confirmation result available. OTP not sent or already used?");let r=new Error("OTP_CONFIRMATION_MISSING"),i=w(r,"verify");throw this._phoneAuthFailure.set(i),this._authError.set(i.userMessage),this.errorTracking.trackAuthError(r,{action:"confirmOtp",metadata:{reason:"no-confirmation-result"}}),r}let t=this.sanitization.sanitizeOTP(e,6);if(!t){a.error("Invalid OTP format after sanitization");let r=new Error("INVALID_OTP_FORMAT"),i=w(r,"verify");throw this._phoneAuthFailure.set(i),this._authError.set(i.userMessage),this.errorTracking.trackAuthError(r,{action:"confirmOtp",metadata:{otpLength:e?.length||0}}),r}try{let r;if(T.firebaseBypass&&this.confirmationResult._bypassMode)a.info("\u{1F513} Firebase OTP Bypass Mode: Accepting OTP without Firebase verification"),a.info(`\u{1F4F1} Phone: ${this.confirmationResult._phone} - OTP: ${t}`),r=`bypass_${this.confirmationResult._phone}`,a.info(`\u{1F3AB} Generated bypass token: ${r.substring(0,20)}...`),this.deviceBinding.generateFingerprint().then(()=>a.info("Device fingerprint generated")).catch(i=>a.debug("Device fingerprint skipped (non-critical)",i?.message)),await this.apiService.storeFirebaseToken(r);else try{if(a.info(`[AuthService.confirmOtp] Attempting Firebase confirmation. OTP Length: ${t.length}`),!this.confirmationResult||typeof this.confirmationResult.confirm!="function")throw a.error("[AuthService.confirmOtp] confirmationResult is invalid or missing confirm method",{hasResult:!!this.confirmationResult,type:typeof this.confirmationResult,keys:this.confirmationResult?Object.keys(this.confirmationResult):[]}),new Error("OTP_CONFIRMATION_MISSING");let i=await this.confirmationResult.confirm(t);if(!i.user){a.error("User credential is null or undefined after OTP confirmation.");let n=new Error("OTP_USER_CREDENTIAL_ISSUE");throw this.errorTracking.trackAuthError(n,{action:"confirmOtp",metadata:{reason:"null-user-credential"}}),n}this.deviceBinding.generateFingerprint().then(()=>a.info("Device fingerprint generated")).catch(n=>a.debug("Device fingerprint skipped (non-critical)",n?.message));try{r=await Promise.race([i.user.getIdToken(),new Promise((n,c)=>setTimeout(()=>c(new Error("Token fetch timeout")),d.TOKEN_FETCH_TIMEOUT))])}catch(n){a.error("Failed to get ID token from Firebase:",n);let c=new Error("FIREBASE_TOKEN_FETCH_FAILED");throw this.errorTracking.trackAuthError(c,{action:"confirmOtp",metadata:{reason:n.message||"timeout"}}),c}if(!r||typeof r!="string"||r.length<50){a.error("Invalid Firebase ID token received");let n=new Error("INVALID_FIREBASE_TOKEN");throw this.errorTracking.trackAuthError(n,{action:"confirmOtp",metadata:{tokenLength:r?.length||0}}),n}await this.apiService.storeFirebaseToken(r)}catch(i){throw a.error("[AuthService.confirmOtp] Firebase OTP confirmation error:",i),i}try{let i=await Promise.race([this.getOAuthToken(r),new Promise((c,l)=>setTimeout(()=>l(new Error("OAuth token fetch timeout")),15e3))]);if(i==="userNotFound")return a.info("User not found in backend, returning newUser status for registration"),this._authStatus.set("idle"),{status:"newUser",fid:r};if(typeof i!="string"||!i){a.error("OAuth token is unexpectedly not a valid string after successful-looking fetch in confirmOtp:",i);let c=new Error("TOKEN_UNEXPECTED_STATE");throw this.errorTracking.trackAuthError(c,{action:"confirmOtp",metadata:{tokenType:typeof i}}),c}this.sessionMonitor.startNewSession();try{let c=await this.userService.fetchCurrentUser(["profile"]);c?.is_provider&&(c.provider_status!==void 0&&c.provider_status!==0&&
1c.provider_status!==4?(a.info(`Provider status ${c.provider_status} - redirecting to dashboard`),setTimeout(()=>{this.router.navigate(["/provider/dashboard"],{replaceUrl:!0})},100)):(a.info(`Provider status ${c.provider_status} - redirecting to signup to complete onboarding`),setTimeout(()=>{this.router.navigate(["/provider/signup"],{replaceUrl:!0})},100)))}catch(c){a.warn("Initial user profile fetch failed, but continuing login session:",c?.message)}this.userService.triggerUserRefresh();let n=this.guestCartService.getGuestToken();if(n)this._isMergeInProgress.set(!0),this._mergeCompletionPromise=new Promise(c=>{this._mergeCompletionResolver=c}),(async()=>{try{a.info("Starting cart merge for guest token...");let l=(await this.cartService.mergeGuestCart(n)).mergeResult;this._lastMergeResult.set(l),a.info("Cart merge completed with result:",{items_added:l.items_added.length,items_combined:l.items_combined.length,items_adjusted:l.items_adjusted.length,items_skipped:l.items_skipped.length,cart_changed:l.cart_changed,user_had_items:l.user_cart_had_items}),this.guestCartService.clearGuestToken(),this.cartService.triggerCartRefresh(),this._mergeCompletionResolver&&this._mergeCompletionResolver(l)}catch(c){let l=null;if(c?.error?.message==="Guest cart not found")a.info("Guest cart not found - this is OK, no merge needed"),this.guestCartService.clearGuestToken(),l={items_added:[],items_combined:[],items_adjusted:[],items_skipped:[],user_cart_had_items:!1,guest_items_count:0,final_items_count:0,cart_changed:!1},this._lastMergeResult.set(l),await this.cartService.getCart({expand:"cartItems,cartItems.entity,cartItems.variant"}),this.cartService.triggerCartRefresh();else{a.error("Cart merge error:",c),this._lastMergeResult.set(null);try{await this.cartService.getCart({expand:"cartItems,cartItems.entity,cartItems.variant"}),this.cartService.triggerCartRefresh()}catch(h){a.error("Failed to fetch user cart after merge error:",h)}}this._mergeCompletionResolver&&this._mergeCompletionResolver(l)}finally{this._isMergeInProgress.set(!1),this._mergeCompletionPromise=null,this._mergeCompletionResolver=null}})();else{let c={items_added:[],items_combined:[],items_adjusted:[],items_skipped:[],user_cart_had_items:!1,guest_items_count:0,final_items_count:0,cart_changed:!1};this._lastMergeResult.set(c),(async()=>{try{await this.cartService.getCart({expand:"cartItems,cartItems.entity,cartItems.variant"}),this.cartService.triggerCartRefresh()}catch(l){a.error("Cart fetch error:",l)}})()}return n&&this.syncGuestData(n),this._authStatus.set("authenticated"),{status:"success",token:i}}catch(i){if(a.warn("[AuthService.confirmOtp] getOAuthToken failed:",i.message),i.message==="OAUTH_USER_NOT_FOUND")return this._authStatus.set("idle"),{status:"newUser",fid:r};throw i.message==="OAuth token fetch timeout"?(a.error("OAuth token fetch timed out"),new Error("TOKEN_FETCH_TIMEOUT")):new Error("TOKEN_EXCHANGE_FAILED")}}catch(r){this._authStatus.set("error");let i=w(r,"verify"),n=k(r);if(this._phoneAuthFailure.set(i),this._authError.set(i.userMessage||n.userMessage),(i.requiresNewCode||i.requiresFreshVerifier)&&(this.confirmationResult=null),i.requiresFreshVerifier){let c=this.confirmationRecaptchaContainerId;this.confirmationRecaptchaContainerId=null,c&&this.requestRecaptchaDisposal(c)}if(i.cooldownSeconds&&this.startRateLimitTimer(i.cooldownSeconds),a.error("[AuthService.confirmOtp] OTP confirmation processing error:",r,`Firebase error code (if any): ${r.code}`),r.message==="TOKEN_EXCHANGE_FAILED"||r.message==="TOKEN_FETCH_TIMEOUT"||r.message==="FIREBASE_TOKEN_FETCH_FAILED"||r.message==="TOKEN_UNEXPECTED_STATE"||r.message==="OTP_CONFIRMATION_MISSING"||r.message==="OTP_USER_CREDENTIAL_ISSUE"||r.message==="INVALID_OTP_FORMAT"||r.message==="INVALID_FIREBASE_TOKEN")throw r;if(r.code)switch(r.code){case"auth/invalid-verification-code":throw new Error("OTP_INVALID_CODE");case"auth/code-expired":throw new Error("OTP_CODE_EXPIRED");case"auth/session-expired":throw new Error("OTP_SESSION_EXPIRED");case"auth/too-many-requests":throw new Error("TOO_MANY_REQUESTS");
1case"auth/network-request-failed":throw new Error("NETWORK_ERROR");default:throw a.error("Unexpected Firebase error:",r.code),new Error("OTP_CONFIRMATION_FAILED_FIREBASE")}throw new Error("OTP_CONFIRMATION_FAILED_UNKNOWN")}}async signOut(){if((!T.firebaseBypass||this.auth.currentUser)&&await this.auth.signOut(),await this.clearTokens(),this.utmService.clearAllUtms(),this.getTokenRefreshService().stopTokenRefreshMonitoring(),this.sessionMonitor.endSession(),this.#e.isBrowser)try{sessionStorage.removeItem("csrf_token"),sessionStorage.removeItem("csrf_token_expiry")}catch(r){a.warn("Failed to clear CSRF token:",r)}if(this.analyticsGaService.clearUserId(),this.userService.clearCurrentUser(),this.cartService.clearCartState(),this.wishlistService.clearWishlistState(),this.cartService.triggerCartRefresh(),this.cacheService.clear(),a.info("Cache cleared on logout to prevent cross-user data leakage"),a.info("User and cart state cleared on signOut"),["oauth_token","refresh_token","firebase_token","phone_number","user_data"].forEach(r=>localStorage.removeItem(r)),this.#e.isBrowser)try{["user_preferences","checkout_data","cart_timestamp"].forEach(i=>{try{sessionStorage.removeItem(i)}catch{}})}catch(r){a.warn("Failed to clear session storage:",r)}this._authStatus.set("idle"),this.confirmationResult=null,this.confirmationRecaptchaContainerId=null}async getTokenFromFid(e){if(e===null)return a.warn("getTokenFromFid called with null FID."),null;try{return await this.getOAuthToken(e)}catch(t){return t.message==="OAUTH_USER_NOT_FOUND"?(a.warn("[AuthService.getTokenFromFid] User not found by OAuth provider for FID:",e),"userNotFound"):(a.error("[AuthService.getTokenFromFid] Error during token fetch:",t.message),null)}}async getOAuthToken(e){if(!e)throw a.error("[AuthService.getOAuthToken] Called with null or empty firebaseIdToken"),new Error("INVALID_FID_PROVIDED_TO_GETOAUTHTOKEN");T.firebaseBypass&&e.startsWith("bypass_")&&(a.info("\u{1F513} Firebase Bypass Mode: Using bypass token for OAuth exchange"),a.info(`\u{1F3AB} Bypass Token: ${e.substring(0,20)}...`));try{let t=await this.apiService.exchangeFirebaseToken(e);if(t){if(!await this.apiService.getToken())throw a.error("Token storage verification failed - token not found after storage"),new Error("TOKEN_STORAGE_VERIFICATION_FAILED");try{await this.getTokenRefreshService().startTokenRefreshMonitoring(3600)}catch(i){a.warn("Token refresh monitoring failed to start (non-critical):",i)}return t}else throw new Error("OAUTH_TOKEN_REQUEST_FAILED")}catch(t){throw t.message==="TOKEN_STORAGE_VERIFICATION_FAILED"||a.error(`[AuthService.getOAuthToken] Failed: ${t.message||"Unknown error during token fetch"}.`),t}}syncGuestData(e){this.liftService.syncGuestReactions().then(t=>{t.synced>0&&a.info(`Synced ${t.synced} guest lift reaction(s) to user account`)}).catch(t=>{a.warn("Failed to sync guest lift reactions:",t)}),this.liftService.syncGuestViews().then(t=>{t.synced>0&&a.info(`Synced ${t.synced} guest lift view(s) to user account`)}).catch(t=>{a.warn("Failed to sync guest lift views:",t)}),this.wishlistService.syncGuestWishlist(e).then(t=>{t.items_synced>0&&a.info(`Synced ${t.items_synced} guest wishlist item(s) to user account`)}).catch(t=>{a.warn("Failed to sync guest wishlist:",t)})}getTokenRefreshService(){return this._tokenRefresh||(this._tokenRefresh=this.injector.get(le)),this._tokenRefresh}async clearTokens(){if(this.#e.isServer)return;let e=await this.apiService.openIndexedDB(),t=e.transaction("auth","readwrite");t.objectStore("auth").clear(),t.oncomplete=()=>{},t.onerror=i=>{a.error("Error clearing tokens from IndexedDB",i)},e.close()}static{this.\u0275fac=function(t){return new(t||o)}}static{this.\u0275prov=m({token:o,factory:o.\u0275fac,providedIn:"root"})}}return o})();export{oe as a,ae as b,d as c,U as d,ue as e,he as f,ye as g,Vt as h};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.