All files / lib/core/runtime AvenxRouter.js

95.64% Statements 703/735
83.48% Branches 182/218
96% Functions 24/25
95.64% Lines 703/735

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 73547x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 8x 8x 8x 8x 1x 1x 1x 1x 8x 8x 87x 87x 87x 87x 87x 87x 87x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 87x 87x 87x 87x 87x 82x 82x 87x 87x 87x 87x 87x 87x 87x 72x 72x 72x 72x 1x 1x 1x 1x     1x 72x 72x 87x 87x 87x 87x 87x 4x 4x 87x 87x 87x 87x 87x 3x 3x 87x 87x 87x 87x 87x 87x 5x 5x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 72x 65x 65x 65x 65x 65x 65x 65x 65x 72x 87x 87x 87x 87x 87x 87x 8x 18x 18x 8x 8x 87x 87x 87x 87x 87x 87x 87x 4x 4x 4x     4x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 49x 49x 49x 49x 49x 49x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 186x 186x 216x 167x 199x 49x 49x 49x 49x 49x 49x 49x 48x 29x 29x 48x 19x 19x 49x 1x 1x     49x 1x 1x 49x 49x 49x 49x 49x 49x 3x 49x 49x 49x 49x 49x 44x 44x 3x 3x 3x 3x 41x 42x 44x 44x 44x 44x 14x 42x 27x 27x 49x 49x 5x 5x 3x 5x 2x 2x 2x 49x 49x 186x 186x 186x 186x 87x 87x 87x 87x 87x 87x 87x 87x 151x 1x 1x 1x         1x     1x 151x 87x 87x 87x 87x 87x 87x 87x 244x 244x 244x 244x 244x 244x 244x 2x 2x 244x 244x 7x 7x 7x 237x 237x 237x 237x 237x 237x 237x 237x 237x 237x 244x 21x 20x 20x 21x 21x 216x 216x 244x 244x 244x 30x 30x 9x 9x 9x 9x 9x 30x 30x 30x 30x 30x 2x 2x 28x 28x 30x 30x 30x         30x 30x 30x 1x 1x 1x 1x 29x 29x 30x 30x 30x                 29x 29x 30x 1x 1x 1x 1x 1x 28x 28x 28x 28x 28x 30x 30x     30x 30x 30x 30x 30x 186x 186x 244x 244x 244x 244x 244x 244x 244x 244x 244x 244x 244x 244x 244x 244x 244x 79x 79x 79x 79x 79x 79x 79x 244x 244x 244x 244x 183x 183x 183x 17x 17x 166x 183x 4x 4x 3x 3x 3x 183x 7x 162x 155x 155x 4x 155x 4x 2x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 3x 3x 3x 3x 2x 2x 2x 2x 155x 151x 151x 2x 2x 2x 2x 2x 2x 2x 2x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 244x 244x 3x     3x 3x 3x 1x 3x 2x 2x 2x 2x 2x 244x 244x 87x 87x 87x 87x 87x 87x 151x 149x 149x 149x 12x 12x 149x 149x 151x 66x 66x 66x 66x 66x 66x 63x 62x 63x 61x 61x 63x 63x 63x 61x 61x 66x 66x 149x 149x 151x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 151x 93x 93x 58x 151x 151x 2x 2x 56x 151x 2x 2x 2x 2x 2x 56x 56x 39x 36x 36x 36x 3x 3x 3x 3x 1x 3x 2x 2x 3x 56x 56x 56x 56x 56x 56x 151x 151x 151x 151x 87x 87x 87x 87x 87x 87x 87x 87x 151x 151x 11x 11x 12x 4x 4x 4x 1x 1x 1x 12x 7x 7x 10x 12x 10x 151x 151x 151x 151x 87x 87x 87x 87x 87x 87x 87x 87x 87x 1015x 1015x 87x 87x 87x 87x 87x 87x 243x 92x 92x 2x 2x 2x 2x 2x     2x     2x 243x 151x 151x 84x 84x 84x 84x 84x 84x 151x 151x 151x 151x 151x 21x 21x 151x 32x 32x 151x 16x 16x 151x 151x 22x 22x 151x 243x 87x
import { AvenxErrorCodes, formatMessage, AvenxError } from './AvenxError.js';
import { GuardContext } from './AvenxGuard.js';
import { logger } from './AvenxLogger.js';
import { ProxyHandlerFactory } from '../reactive/proxyHandler.js';
import { RouteMatcher } from './RouteMatcher.js';
import { createNavigationDelegate } from './navigation/index.js';
import { tracer } from '../trace/tracer.js';
import { TraceNodeType } from '../trace/schema.js';
import { announce, manageFocus } from './navigation/A11yManager.js';
 
// This is declared for controlling the depth of a redirected loop
const MAX_REDIRECT = 10;
 
/**
 * AvenxRouter handles routing for the application.
 * Matches URL route definitions to specific Page components using pluggable navigation delegates.
 */
export class AvenxRouter {
  /** @type {Map<string, { x: number, y: number }>} */
  #scrollPositions = new Map();
 
  /**
   * Monotonic id identifying the most recently started navigation.
   *
   * Route guards may be asynchronous, so two navigations can be in flight at
   * once and resolve out of order. Each attempt captures the id it started
   * with and only commits if it is still the current one, so a guard belonging
   * to an abandoned route cannot mount its page over the route the user
   * actually asked for.
   * @type {number}
   */
  #navigationId = 0;
 
  /**
   * @param {AvenxApp} app - The main application instance.
   * @param {Object<string, string | object>} routes - A map of hash routes to page names or route definitions.
   * @param {object} [options] - Optional router configurations (e.g. prefix, delegate, mode).
   */
  constructor(app, routes = {}, options = {}) {
    /** @type {AvenxApp} */
    this.app = app;
    /** @type {Object<string, string | object>} */
    this.routes = routes;
    /** @type {object} */
    this.options = options;
    this.currentRoute = null;
    /** @type {{ chain: string[], count: number } | null} */
    this.redirectContext = null; // The context that is used to prevent the redirect loop using redirect chain and a maxRedirect limit
    /** @type {string|null} */
    this.hashToIgnore = null;
    /** @type {boolean} Whether destroy() has already run. */
    this.__destroyed = false;
 
    /** @type {Array<Function|object>} */
    this.beforeHooks = [];
    /** @type {Array<Function>} */
    this.afterHooks = [];
 
    /** @type {object} */
    this.a11y = {
      focusOnNavigate: true,
      announceRouteChanges: true,
      focusTarget: '[data-ax-page-heading]',
      ...(options.a11y || {}),
    };
    this._isInitialLoad = true;
 
    /** @type {object} */
    this.delegate = createNavigationDelegate(options);
 
    // AVX_W08 used to be raised here for any pattern that did not begin with a
    // slash once its '#' was stripped. That was a true warning about a real
    // failure -- such a pattern could never match -- but it named the symptom
    // rather than the cause, and it fired on `''`, which is what this project's
    // own scaffold writes. RouteMatcher.normalizePattern now brings every
    // spelling into the form the matcher compares against, so there is no
    // longer a pattern shape that silently fails to resolve. The code stays
    // reserved rather than reused.
 
    this.delegate.registerRouter(this);
 
    this.unsubscribeHashChange = this.delegate.onHashChange(() => this.#handleRoute());
    this.unsubscribeLinkClick = this.delegate.onLinkClick((route) => this.navigate(route));
  }
 
  /**
   * Registers a global guard callback that executes before route guards on navigation transitions.
   * @param {Function|object} callback - The guard callback or guard instance/class.
   * @returns {Function} Unregister function.
   */
  beforeEach(callback) {
    if (typeof callback === 'function' || (callback && typeof callback.canActivate === 'function')) {
      this.beforeHooks.push(callback);
    }
    return () => {
      const idx = this.beforeHooks.indexOf(callback);
      if (idx !== -1) {
        this.beforeHooks.splice(idx, 1);
      }
    };
  }
 
  /**
   * Registers a global after hook callback that executes after successful route navigation.
   * @param {Function} callback - The callback to execute after navigation.
   * @returns {Function} Unregister function.
   */
  afterEach(callback) {
    if (typeof callback === 'function') {
      this.afterHooks.push(callback);
    }
    return () => {
      const idx = this.afterHooks.indexOf(callback);
      if (idx !== -1) {
        this.afterHooks.splice(idx, 1);
      }
    };
  }
 
  /**
   * Starts the router and handles the initial route.
   */
  start() {
    this.#handleRoute();
  }
 
  /**
   * Navigates to a specific hash route.
   * @param {string} hash - The target hash (e.g., '#/about').
   * @param {Object} [options] - Navigation options.
   */
  navigate(hash, options = {}) {
    // Force clean paths like '/profile' into hash paths like '#/profile'
    let targetHash = hash.startsWith('#') ? decodeURIComponent(hash) : '#' + decodeURIComponent(hash);
 
    if (this.options && this.options.prefix) {
      const prefix = this.options.prefix;
      if (targetHash.startsWith('#/')) {
        targetHash = '#' + prefix + targetHash.substring(1);
      } else if (targetHash.startsWith('#')) {
        targetHash = '#' + prefix + '/' + targetHash.substring(1);
      }
    }
    this.delegate.setHash(targetHash, options);
  }
 
  /**
   * Steps backward in navigation history.
   */
  back() {
    this.delegate.back();
  }
 
  /**
   * Steps forward in navigation history.
   */
  forward() {
    this.delegate.forward();
  }
 
  /**
   * Moves to a specific history position relative to current position.
   * @param {number} delta - Relative step count in history (e.g. -1 for back, 1 for forward).
   */
  go(delta) {
    this.delegate.go(delta);
  }
 
  /**
   * Destroys the router and cleans up event listeners.
   *
   * Idempotent. Removing an event listener that is no longer attached is a
   * no-op in a real DOM, so a second call was harmless in a browser -- but it
   * also re-ran `delegate.destroy()` and `unregisterRouter`, which is not
   * something a teardown path should depend on being harmless. The router is
   * destroyed once and then knows it.
   * @returns {void}
   */
  destroy() {
    if (this.__destroyed) return;
    this.__destroyed = true;
 
    if (this.unsubscribeHashChange) this.unsubscribeHashChange();
    if (this.unsubscribeLinkClick) this.unsubscribeLinkClick();
    this.unsubscribeHashChange = null;
    this.unsubscribeLinkClick = null;
    this.delegate.unregisterRouter(this);
    this.delegate.destroy();
  }
 
  /**
   * Returns a snapshot of all registered routes.
   * @returns {Array<{pattern: string, definition: string | object}>}
   */
  getRoutes() {
    return Object.entries(this.routes).map(([pattern, definition]) => ({
      pattern,
      definition: typeof definition === 'object' && definition !== null ? { ...definition } : definition,
    }));
  }
 
  /**
   * Checks if this router has a matching route (excluding fallback) for the given hash.
   * @param {string} hash - The URL hash.
   * @returns {boolean} True if a non-fallback route matches.
   */
  matches(hash) {
    try {
      return RouteMatcher.matches(this.routes, decodeURIComponent(hash).replace(/%20/g, ' '), this.options);
    } catch {
      return RouteMatcher.matches(this.routes, hash, this.options);
    }
  }
 
  /**
   * Sequentially executes an array of guards for a route transition.
   * @param {Array<Function|object>} guards - Route guards.
   * @param {object} to - Target route details.
   * @param {object | null} from - Current route details.
   * @returns {Promise<boolean|string|object>} Result of the guard checks.
   * @private
   */
  /**
   * Builds the capabilities handed to a guard for one navigation.
   *
   * A guard used to receive nothing but the route, which made "is this visitor
   * signed in?" unanswerable: it had no supported route to shared state. The
   * context carries the application's bridges and the router asking, and
   * deliberately carries no browser globals -- a guard that needs one reads it
   * through a bridge, like everything else.
   * @returns {GuardContext} The context for this navigation.
   * @private
   */
  #guardContext() {
    return new GuardContext({
      bridges: this.app ? this.app.bridges : {},
      app: this.app || null,
      router: this,
    });
  }
 
  /**
   * Sequentially executes an array of guards for a route transition.
   * @param {Array<Function|object>} guards - Route guards.
   * @param {object} to - The target route.
   * @param {object} from - The route being left.
   * @returns {Promise<boolean|string|object>} Result of the guard checks.
   * @private
   */
  #runGuards(guards, to, from) {
    return new Promise((resolve, reject) => {
      const nextGuard = (index) => {
        if (index >= guards.length) {
          resolve(true);
        } else {
          const Guard = guards[index];
          let canActivateResult;
          // Built per guard rather than per navigation so a guard that runs
          // after an earlier one mutated a bridge sees the current registry.
          const context = this.#guardContext();
          try {
            if (typeof Guard === 'function') {
              if (Guard.prototype && typeof Guard.prototype.canActivate === 'function') {
                const instance = new Guard(context);
                canActivateResult = instance.canActivate(to, from, context);
              } else {
                canActivateResult = Guard(to, from, context);
              }
            } else if (Guard && typeof Guard.canActivate === 'function') {
              canActivateResult = Guard.canActivate(to, from, context);
            } else {
              canActivateResult = true;
            }
          } catch (err) {
            canActivateResult = Promise.reject(err);
          }
 
          const guardTimeout = this.options && this.options.guardTimeout !== undefined ? this.options.guardTimeout : 5000;
 
          let timeoutId;
          const timeoutPromise = new Promise((_, reqReject) => {
            timeoutId = setTimeout(() => {
              reqReject(new AvenxError(AvenxErrorCodes.ROUTER_GUARD_TIMEOUT, guardTimeout, to.hash));
            }, guardTimeout);
          });
 
          Promise.race([Promise.resolve(canActivateResult), timeoutPromise])
            .then((result) => {
              clearTimeout(timeoutId);
              if (result === undefined) {
                logger.warn(formatMessage(AvenxErrorCodes.ROUTER_GUARD_UNDEFINED_RETURN, to.hash));
                nextGuard(index + 1);
                return;
              }
              const isControlObject =
                typeof result === 'object' &&
                result !== null &&
                (result.cancel === true || typeof result.redirect === 'string');
 
              if (result === false || typeof result === 'string' || isControlObject) {
                resolve(result);
              } else {
                nextGuard(index + 1);
              }
            })
            .catch((err) => {
              clearTimeout(timeoutId);
              if (err.code === AvenxErrorCodes.ROUTER_GUARD_TIMEOUT) {
                reject(err);
              } else {
                logger.error(formatMessage(AvenxErrorCodes.ROUTER_GUARD_ERROR, to.hash, err));
                resolve(false);
              }
            });
        }
      };
      nextGuard(0);
    });
  }
 
  /**
   * Sequentially executes all registered global after hooks.
   * @param {object} to - Target route details.
   * @param {object|null} from - Previous route details.
   * @private
   */
  #runAfterHooks(to, from) {
    for (const hook of this.afterHooks) {
      try {
        const res = hook(to, from);
        if (res && typeof res.catch === 'function') {
          res.catch((err) => {
            logger.error(formatMessage(AvenxErrorCodes.ROUTER_GUARD_ERROR, to.hash, err));
          });
        }
      } catch (err) {
        logger.error(formatMessage(AvenxErrorCodes.ROUTER_GUARD_ERROR, to.hash, err));
      }
    }
  }
 
  /**
   * Handles the current route by matching it against patterns, executing guards,
   * and mounting the corresponding page.
   * @private
   */
  #handleRoute() {
    // Starting a new navigation supersedes any still-pending one.
    const navigationId = ++this.#navigationId;
 
    let hash = this.delegate.getHash();
    try {
      hash = decodeURIComponent(hash);
    } catch {
      // Fallback
    }
 
    if (this.hashToIgnore === hash) {
      this.hashToIgnore = null;
      return;
    }
 
    const activeRouters = this.delegate.getActiveRouters();
    const { matchedRoute, params, query, path, otherRouterMatches, normalizedHash } = RouteMatcher.matchRoute(
      this.routes,
      hash,
      this.options,
      activeRouters,
      this,
    );
 
    if (!matchedRoute) {
      if (!otherRouterMatches) {
        logger.warn(formatMessage(AvenxErrorCodes.ROUTE_NOT_FOUND, hash));
      }
      return;
    }
 
    const def = matchedRoute.definition;
    const meta = typeof def === 'object' && def.meta && typeof def.meta === 'object' ? def.meta : {};
 
    if (def && typeof def === 'object' && def.redirect) {
      // Create a new redirect context when the redirect starts
      if (!this.redirectContext) {
        this.redirectContext = {
          chain: [normalizedHash],
          count: 0,
        };
      }
 
      Promise.resolve()
        .then(() => {
          // If redirect is function then execute it with params
          if (typeof def.redirect === 'function') {
            return def.redirect(params);
          }
 
          return def.redirect;
        })
        .then((target) => {
          if (typeof target !== 'string' || target.length === 0) {
            logger.error('Invalid redirect target');
            this.redirectContext = null;
            return;
          }
 
          // Check the maximum redirect limit
          if (this.redirectContext.count >= MAX_REDIRECT) {
            logger.error('Maximum redirect limit exceeded');
            this.redirectContext = null;
            return;
          }
 
          // Normalize the target hash same like navigate does
          let targetHash = target.startsWith('#') ? decodeURIComponent(target) : '#' + decodeURIComponent(target);
 
          if (this.options && this.options.prefix) {
            const prefix = this.options.prefix;

            if (targetHash.startsWith('#/')) {
              targetHash = '#' + prefix + targetHash.substring(1);
            } else if (targetHash.startsWith('#')) {
              targetHash = '#' + prefix + '/' + targetHash.substring(1);
            }
          }
 
          // Check whether the target is already in the redirect chain
          if (this.redirectContext.chain.includes(targetHash)) {
            logger.error(`Redirect loop detected: ${[...this.redirectContext.chain, targetHash].join(' → ')}`);
 
            this.redirectContext = null;
            return;
          }
 
          this.redirectContext.chain.push(targetHash);
          this.redirectContext.count++;
 
          this.navigate(targetHash, { replace: true });
        })
        .catch((err) => {
          logger.error(err);
          this.redirectContext = null;
        });
 
      // Do not continue to page, guards or mountPage for redirect route
      return;
    }
 
    const parentDef = matchedRoute.parent;
    const pageName = typeof def === 'string' ? def : def.page;
    const childGuards = typeof def === 'object' ? def.guards || [] : [];
    const parentGuards = parentDef && typeof parentDef === 'object' ? parentDef.guards || [] : [];
    const guards = [...this.beforeHooks, ...parentGuards, ...childGuards];
 
    const to = {
      hash: normalizedHash,
      path: path || '',
      page: pageName,
      params,
      query: query || {},
      meta,
    };
    const from = this.currentRoute
      ? {
        hash: this.currentRoute.hash,
        path: this.currentRoute.path,
        page: this.currentRoute.page,
        params: { ...this.currentRoute.params },
        query: { ...this.currentRoute.query },
        meta: { ...(this.currentRoute.meta || {}) },
      }
      : null;
 
    this.#runGuards(guards, to, from)
      .then((result) => {
        // A newer navigation started while these guards were pending; its
        // outcome is the one that must be applied, not this one's.
        if (navigationId !== this.#navigationId) {
          return;
        }
 
        if (result === false) {
          logger.warn(formatMessage(AvenxErrorCodes.ROUTER_GUARD_DENIED, to.hash));
          if (from && from.hash !== this.delegate.getHash()) {
            this.hashToIgnore = from.hash;
            this.delegate.setHash(from.hash);
          }
        } else if (typeof result === 'string') {
          this.navigate(result);
        } else if (
          typeof result === 'object' &&
          result !== null &&
          (result.cancel === true || typeof result.redirect === 'string')
        ) {
          if (result.cancel) {
            if (!result.silent) {
              logger.warn(formatMessage(AvenxErrorCodes.ROUTER_GUARD_DENIED, to.hash));
            }
            if (from && from.hash !== this.delegate.getHash()) {
              this.hashToIgnore = from.hash;
              this.delegate.setHash(from.hash);
            }
          } else if (result.redirect) {
            let redirectPath = result.redirect;
            const paramsToAppend = { ...result.state, ...result.query };
            if (Object.keys(paramsToAppend).length > 0) {
              const [pathPart, queryPart] = redirectPath.split('?');
              const searchParams = new URLSearchParams(queryPart || '');
              for (const [key, value] of Object.entries(paramsToAppend)) {
                if (value !== undefined && value !== null) {
                  searchParams.set(key, String(value));
                }
              }
              redirectPath = pathPart + '?' + searchParams.toString();
            }
            this.navigate(redirectPath);
          }
        } else {
          this.redirectContext = null;
          if (tracer.on) {
            tracer.record(TraceNodeType.NAVIGATION, {
              from: from ? from.hash : null,
              to: to.hash,
              page: to.page,
              params: to.params,
              query: to.query,
            });
          }
          this.currentRoute = to;
          this.#applyTitle(def, params);
          const transitionName = (typeof def === 'object' && def.transition) || this.options.transition;
          const keepAlive =
            typeof def === 'object' && def.keepAlive !== undefined ? !!def.keepAlive : !!this.options.keepAlive;
          if (this.app && typeof this.app.mountPage === 'function') {
            const layoutName = parentDef && typeof parentDef === 'object' ? parentDef.page : null;
            this.app.mountPage(pageName, params, { transition: transitionName, keepAlive, layout: layoutName });
          }
          this.#runAfterHooks(to, from);
          this.#applyScrollRestoration(to, from);
 
          // Accessibility management (announcements & focus shift)
          this.#applyA11y();
        }
      })
      .catch((err) => {
        if (navigationId !== this.#navigationId) {
          return;
        }
 
        logger.error(err);
        if (this.options && this.options.guardTimeoutRedirect) {
          this.navigate(this.options.guardTimeoutRedirect);
        } else {
          if (from && from.hash !== this.delegate.getHash()) {
            this.hashToIgnore = from.hash;
            this.delegate.setHash(from.hash);
          }
        }
      });
  }
 
  /**
   * Applies focus management and live-region announcements after successful navigation.
   * @private
   */
  #applyA11y() {
    if (typeof document === 'undefined') return;
 
    if (this.a11y.announceRouteChanges) {
      if (document.title) {
        announce(document.title);
      }
    }
 
    if (this.a11y.focusOnNavigate && !this._isInitialLoad) {
      const schedule =
        typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function'
          ? (cb) => window.requestAnimationFrame(cb)
          : (cb) => setTimeout(cb, 0);
 
      schedule(() => {
        if (typeof document === 'undefined') return;
        const pageRoot =
          (this.app && this.app.currentPageInstance && this.app.currentPageInstance.$el) ||
          (typeof document.querySelector === 'function'
            ? document.querySelector('[data-ax-page]') || document.querySelector('main') || document.body
            : document.body || null);
 
        if (pageRoot) {
          manageFocus(pageRoot, this.a11y.focusTarget);
        }
      });
    }
 
    this._isInitialLoad = false;
  }
 
  /**
   * Applies scroll restoration after a successful navigation.
   * Modes: 'top' (default) scrolls to 0,0; 'auto' restores saved position for the target
   * hash or scrolls to top; 'manual' is a no-op.
   * @param {{ hash: string }} to - Target route.
   * @param {{ hash: string } | null} from - Previous route.
   * @private
   */
  #applyScrollRestoration(to, from) {
    if (typeof window === 'undefined' || typeof window.scrollTo !== 'function') {
      return;
    }
 
    const mode = this.options?.scrollRestoration ?? 'top';
    if (mode === 'manual') {
      return;
    }
 
    if (mode === 'auto' && from?.hash) {
      this.#scrollPositions.set(from.hash, {
        x: window.scrollX || 0,
        y: window.scrollY || 0,
      });
    }
 
    const apply = () => {
      if (mode === 'top') {
        window.scrollTo(0, 0);
        return;
      }
 
      if (mode === 'auto') {
        const saved = this.#scrollPositions.get(to.hash);
        if (saved) {
          window.scrollTo(saved.x, saved.y);
        } else {
          window.scrollTo(0, 0);
        }
      }
    };
 
    // Double rAF so layout has settled after mountPage
    const schedule =
      typeof window.requestAnimationFrame === 'function'
        ? (cb) => window.requestAnimationFrame(cb)
        : (cb) => setTimeout(cb, 0);
 
    schedule(() => schedule(apply));
  }
 
  /**
   * Resolves the title from a route definition and updates current title.
   * @param {string | object} def - The route definition.
   * @param {object} params - Parsed route parameters.
   * @private
   */
  #applyTitle(def, params) {
    const rawTitle = typeof def === 'object' ? def.title : undefined;
    if (rawTitle === undefined) return;
 
    let resolved;
    if (typeof rawTitle === 'function') {
      try {
        resolved = rawTitle(params);
      } catch (err) {
        logger.warn(formatMessage(AvenxErrorCodes.ROUTE_TITLE_EVALUATION_FAILED, err));
        return;
      }
    } else {
      resolved = rawTitle;
    }
 
    if (typeof resolved !== 'string') return;
 
    const prefix = this.options.titlePrefix || '';
    const suffix = this.options.titleSuffix || '';
    this.delegate.setTitle(prefix + resolved + suffix);
  }
 
  #currentRouteProxy = null;
  #currentRouteIsNull = true;
 
  /**
   * Getter for currentRoute. Returns null if null was assigned, or the stable reactive proxy.
   * @returns {object|null}
   */
  get currentRoute() {
    return this.#currentRouteIsNull ? null : this.#currentRouteProxy;
  }
 
  /**
   * Setter for currentRoute. Reactively updates the stable proxy properties.
   * @param {object|null} val
   */
  set currentRoute(val) {
    if (val === null) {
      this.#currentRouteIsNull = true;
      if (this.#currentRouteProxy) {
        this.#currentRouteProxy.hash = '';
        this.#currentRouteProxy.path = '';
        this.#currentRouteProxy.page = '';
        this.#currentRouteProxy.meta = {};
        for (const key of Object.keys(this.#currentRouteProxy.params)) {
          delete this.#currentRouteProxy.params[key];
        }
        for (const key of Object.keys(this.#currentRouteProxy.query)) {
          delete this.#currentRouteProxy.query[key];
        }
      }
    } else {
      this.#currentRouteIsNull = false;
      if (!this.#currentRouteProxy) {
        const handlerFactory = new ProxyHandlerFactory();
        this.#currentRouteProxy = new Proxy(
          { hash: '', path: '', page: '', params: {}, query: {}, meta: {} },
          handlerFactory.create(),
        );
      }
      this.#currentRouteProxy.hash = val.hash || '';
      this.#currentRouteProxy.path = val.path !== undefined ? val.path : val.hash ? val.hash.split('?')[0] : '';
      this.#currentRouteProxy.page = val.page || '';
      this.#currentRouteProxy.meta = { ...(val.meta || {}) };
      for (const key of Object.keys(this.#currentRouteProxy.params)) {
        delete this.#currentRouteProxy.params[key];
      }
      for (const [key, v] of Object.entries(val.params || {})) {
        this.#currentRouteProxy.params[key] = v;
      }
      for (const key of Object.keys(this.#currentRouteProxy.query)) {
        delete this.#currentRouteProxy.query[key];
      }
      const incomingQuery = val.query || (val.params && val.params.query) || {};
      for (const [key, v] of Object.entries(incomingQuery)) {
        this.#currentRouteProxy.query[key] = v;
      }
    }
  }
}