import { isPlatformServer } from '@angular/common' ; import { Injectable , Inject , PLATFORM_ID , } from '@angular/core' ; import { CanActivate , ActivatedRouteSnapshot , Router , RouterStateSnapshot , UrlTree , } from '@angular/router' ; import { Observable , of , } from 'rxjs' ; import { catchError , map , switchMap , } from 'rxjs/operators' ; import { DaffRoutingUriNormalizer } from '@daffodil/core/routing' ; import { DaffExternalRouter , DaffExternalRouterConfiguration , DAFF_EXTERNAL_ROUTER_CONFIG , DaffExternallyResolvableUrl , } from '@daffodil/external-router' ; import { DaffExternalRouterDriverInterface , DaffExternalRouterDriver , } from '@daffodil/external-router/driver' ; import { DaffExternalRouterNotFoundError } from '../errors/not-found-error' ; import { DaffExternalRouterPermanentRedirectError } from '../errors/permanent-redirect' ; import { DaffExternalRouterTemporaryRedirectError } from '../errors/temporary-redirect' ; import { processErrors } from '../processors/process-errors' ; import { processRedirects } from '../processors/process-redirect' ; /**
 * The DaffExternalRouterExistenceGuard is responsible for guarding the wildcard route
 * of an Angular App and either navigating to a resolved route upon successful resolution
 * or navigating to the configured route upon a failed resolution.
 */ @ Injectable ( { providedIn : 'root' , } ) export class DaffExternalRouterExistenceGuard implements CanActivate { constructor ( @ Inject ( DaffExternalRouterDriver ) private driver , private externalRouter , private router , @ Inject ( DAFF_EXTERNAL_ROUTER_CONFIG ) private config , private urlNormalizer ) { } canActivate ( next , state ) { return this . driver . resolve ( this . urlNormalizer . normalize ( state . url ) ) . pipe ( map ( ( resolvedRoute ) => processErrors ( resolvedRoute ) ) , switchMap ( resolvedRoute => { this . externalRouter . add ( resolvedRoute ) ; return of ( resolvedRoute ) ; } ) , map ( ( resolvedRoute ) => processRedirects ( resolvedRoute ) ) , map ( ( ) => this . router . parseUrl ( state . url ) ) , catchError ( error => { if ( ! ( error instanceof DaffExternalRouterPermanentRedirectError ) && ! ( error instanceof DaffExternalRouterTemporaryRedirectError ) ) { throw error ; } return of ( this . router . parseUrl ( error . redirectUrl ) ) ; } ) , catchError ( ( error ) => { if ( ! ( error instanceof DaffExternalRouterNotFoundError ) ) { throw error ; } return of ( this . router . parseUrl ( this . config . notFoundResolutionPath ) ) ; } ) , catchError ( ( error ) => { console . log ( error ) ; return of ( this . router . parseUrl ( this . config . failedResolutionPath ) ) ; } ) ) ; } }