All files / tao-router/src Router.js

100% Statements 151/151
100% Branches 149/149
100% Functions 27/27
100% Lines 150/150

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                                                                                                                                            1x                     9x 6x   3x                     33x                             6x 4x   2x 3x   2x 5x 4x 2x                             10x 10x 10x 3x 7x 3x                                       9x   9x 28x 17x   11x 11x 11x 11x 10x   11x   9x 3x 3x 3x     9x   9x   9x 14x     14x 14x 7x   14x 14x             14x   14x 14x                                                                                                     7x 7x 2x 2x   7x 7x 7x 7x 7x 7x 7x 7x   7x 7x 7x                                             7x 7x 7x     5x   7x 1x   7x     2x     2x 2x 1x   2x 1x   2x 1x   2x 1x     2x     7x         6x 6x 6x 6x 6x 1x   6x 6x 6x   6x 6x 3x       7x         4x 4x 4x 4x 2x   2x 2x 2x 1x       7x         12x 12x 12x 12x 12x 12x 12x 12x 12x   12x 12x 12x 12x 6x       7x         4x 4x 4x 4x 4x 4x   3x 3x 7x     3x 2x                                 7x   5x 5x 5x   8x     8x 8x 2x   2x               8x 7x                                                 7x 3x 1x   2x                     7x 1x                       7x     5x 5x 5x 2x        
/**
 * The legacy TAO-native URL routing bridge: a two-way binding between a
 * `history` instance and a TAO signal network, configured entirely through
 * TAO signals (`{Routes,Configure}`, `{Route,Add|Remove|Attach|Detach}`)
 * rather than a route table. See {@link Router} for the full protocol.
 *
 * @module @tao.js/router/Router
 */
// import createHistory from 'history/createBrowserHistory';
/* v8 ignore next -- module imports are recorded as an unreachable branch by V8. */
import { createBrowserHistory as createHistory } from 'history';
import routington from 'routington';
import get from 'get-value';
import set from 'set-value';
import { AppCtx } from '@tao.js/core';
 
import makeRouteHandler, { deconstructPath, convertPath } from './routeHandler';
 
/**
 * @typedef {import('@tao.js/core').Kernel} Kernel
 * @typedef {import('@tao.js/core').Trigram} Trigram
 * @typedef {import('@tao.js/core').Handler} Handler
 * @typedef {import('./routeHandler').HistoryLike} HistoryLike
 * @typedef {import('./routeHandler').RouteConfig} RouteConfig
 * @typedef {import('./routeHandler').PathPart} PathPart
 */
 
/**
 * A node in the route match tree: a `routington` node extended with the
 * Router's own bookkeeping (written by the `{Route,Attach}` handler).
 *
 * @typedef {Object} RouteNode
 * @property {RouteConfig} route - the route as originally attached
 * @property {(boolean|undefined)} lowerCase - when set, path-extracted
 *           trigram parts are re-capitalized (pushed URLs are lowercased)
 * @property {PathPart[]} deconstruction - the route's deconstructed path
 *           template
 * @property {AppCtx[]} attached - trigrams attached to this route (fired on
 *           a URL match; wildcard parts are filled from the URL)
 * @property {Map<string, Object>} defaultData - default AppCon data per
 *           attached trigram (keyed by the trigram's AppCtx key)
 */
 
/**
 * A match of the current pathname against the route tree.
 *
 * @typedef {Object} RouteMatch
 * @property {RouteNode} node - the matched route's node
 * @property {Object.<string, string>} param - values captured from the URL
 *           per path parameter
 */
 
/**
 * Options for the {@link Router} (and the package's default `init` export).
 *
 * @typedef {Object} RouterOptions
 * @property {(Trigram|AppCtx)} [initAc] - trigram whose inline handler
 *           chains `{Router,Init,<orient of the signal>}` on startup
 * @property {(Trigram|AppCtx|Array<Trigram|AppCtx>)} [incomingAc] -
 *           trigram(s) that trigger matching the current location against
 *           the route tree (firing the matched route's attached AppCons);
 *           the first one is also chained after `{Routes,Configure}`
 * @property {string} [defaultRoute] - path matched instead when the current
 *           location has no route match on an incoming AC
 * @property {string} [orient] - orient the Router's configuration trigrams
 *           (`{Routes,Configure}`, `{Route,Add|Remove|Attach|Detach}`)
 *           listen on; empty/omitted = wildcard
 * @property {boolean} [debug=false] - console.log internal activity
 */
 
const CHANGE_ACTION_SIGNAL = 'POP';
 
/**
 * Uppercase a captured path segment's first character (used to restore
 * trigram casing for `lowerCase` routes); non-strings pass through.
 *
 * @param {string} str
 * @returns {string}
 */
function capitalize(str) {
  // Stryker disable next-line LogicalOperator,ConditionalExpression: equivalent - str is always undefined or a string captured from a URL path segment here, never a truthy non-string, so `!str` alone (or forcing this guard true/false) can't diverge from the full guard for any reachable input
  if (!str || typeof str !== 'string') {
    return str;
  }
  return `${str.substring(0, 1).toUpperCase()}${str.substring(1)}`;
}
 
/**
 * Coerce a trigram (short or long keys) into a data-less AppCtx; AppCtx
 * instances pass through.
 *
 * @param {(Trigram|AppCtx)} ac
 * @returns {AppCtx}
 */
function wrapAc(ac) {
  return ac instanceof AppCtx
    ? ac
    : new AppCtx(ac.t || ac.term, ac.a || ac.action, ac.o || ac.orient);
}
 
/**
 * Wrap a route handler so it skips AppCons matching any of the `ignore`
 * trigrams (`Add.ignore` on `{Route,Add}`).
 *
 * @param {Handler} handler - the compiled route handler
 * @param {(Trigram|AppCtx|Array<Trigram|AppCtx>)} [ignore] - trigram(s) the
 *        handler must not react to
 * @returns {Handler}
 */
function wrapIgnore(handler, ignore) {
  if (!ignore) {
    return handler;
  }
  const ignoreACs = (Array.isArray(ignore) ? ignore : [ignore]).map((iac) =>
    wrapAc(iac),
  );
  return (tao, data) => {
    const matchedIgnore = ignoreACs.some((ignoreAc) => ignoreAc.isMatch(tao));
    if (!matchedIgnore) {
      return handler(tao, data);
    }
  };
}
 
/**
 * Deep-merge a route's default data into the path-extracted data without
 * overwriting values the URL provided.
 *
 * @param {Object} pathData - the path-extracted data (mutated)
 * @param {Object} defaultData - the attached trigram's default data
 * @param {string} [parentPath] - current key path while recursing
 * @returns {void}
 */
function mergeData(pathData, defaultData, parentPath) {
  Object.entries(defaultData).forEach(([key, val]) => {
    const dataPath = parentPath ? `${parentPath}.${key}` : key;
    if (typeof get(pathData, dataPath) === 'undefined') {
      set(pathData, dataPath, val);
    } else if (typeof val === 'object' && !Array.isArray(val)) {
      mergeData(pathData, val, dataPath);
    }
  });
}
 
/**
 * Fire the AppCons for a URL match: for every trigram attached to the
 * matched route, build an AppCtx from the URL-captured data (+ the
 * trigram's default data; wildcard parts filled from the URL, re-cased for
 * `lowerCase` routes), signal `{Route,Match,<orient>}` with
 * `[route, appCtx]`, then set the AppCtx itself.
 *
 * @param {Kernel} TAO - the kernel to signal on
 * @param {RouteMatch} match - the matched route
 * @param {boolean} [debug=false] - console.log internal activity
 * @returns {void}
 */
// Stryker disable next-line BooleanLiteral: unreachable - every internal caller of reactToRoute always passes an explicit boolean `this._debug`, so the `= false` default is never actually evaluated
function reactToRoute(TAO, match, /* istanbul ignore next */ debug = false) {
  // Stryker disable all: optional debug logging
  debug && console.log('Router::reacting to route');
  // Stryker restore all
  const pathMatched = match.node.deconstruction.reduce((pathData, pathItem) => {
    if (!pathItem.match) {
      return pathData;
    }
    const dataPath = pathItem.match[2];
    const pathParam = pathItem.use.substring(1);
    let paramData = match.param[pathParam];
    if (paramData) {
      set(pathData, dataPath, paramData);
    }
    return pathData;
  }, /** @type {Object.<string, *>} */ ({}));
  if (match.node.lowerCase) {
    pathMatched.t = capitalize(pathMatched.t);
    pathMatched.a = capitalize(pathMatched.a);
    pathMatched.o = capitalize(pathMatched.o);
  }
  // Stryker disable all: optional debug logging
  debug &&
    console.log('reactToRoute::node.defaultData:', match.node.defaultData);
  debug && console.log('reactToRoute::node.attached:', match.node.attached);
  // Stryker restore all
  match.node.attached.forEach((trigram) => {
    const defaultData = match.node.defaultData
      ? match.node.defaultData.get(trigram.key)
      : null;
    let acParts = pathMatched;
    if (defaultData) {
      mergeData(acParts, defaultData);
    }
    const { t, a, o, ...data } = acParts;
    const ac = new AppCtx(
      trigram.isTermWild ? t : trigram.t,
      trigram.isActionWild ? a : trigram.a,
      trigram.isOrientWild ? o : trigram.o,
      data,
    );
 
    TAO.setCtx({ t: 'Route', a: 'Match', o: ac.o }, [match.node.route, ac]);
    // Stryker disable next-line all: optional debug logging
    debug && console.log('reactToRoute::TAO.setAppCtx::ac', ac);
    TAO.setAppCtx(ac);
  });
}
 
/**
 * The legacy TAO-native URL bridge. Constructing a Router registers inline
 * handlers on the kernel that turn TAO signals into route configuration,
 * and wires history so URL changes fire AppCons (and matching AppCons push
 * URLs):
 *
 * - `opts.initAc` → chains `{Router,Init,<orient of the signal>}`.
 * - `{Routes,Configure,<orient>}` → fans each entry of `data.Routes` out as
 *   `{Route,Add|Remove|Attach|Detach}` signals (keyed by the entry's
 *   `Add`/`Remove`/`Attach`/`Detach` properties), then chains the first
 *   `opts.incomingAc`.
 * - `{Route,Add,<orient>}` → compiles the route
 *   (`makeRouteHandler`) and registers it as an **async** handler for
 *   `Add`'s trigram (`Add.tao` or `Add` itself): matching AppCons push the
 *   route's URL onto history when it differs, chaining `{Route,Set}`.
 *   Re-adding a trigram replaces its previous handler; `Add.ignore` lists
 *   trigrams the handler must skip; `Add.attach: true` chains
 *   `{Route,Attach,<orient>}` with the same `[Route, Add]` data.
 * - `{Route,Remove,<orient>}` → unregisters the trigram's route handler;
 *   `Remove.detach: true` chains `{Route,Detach,<orient>}`.
 * - `{Route,Attach,<orient>}` → binds `Attach`'s trigram (`Attach.tao` or
 *   `Attach` itself, with `Attach.data` as default AppCon data) to the
 *   route's path pattern in the match tree, so URL changes fire it.
 * - `{Route,Detach,<orient>}` → unbinds the trigram from the route.
 *
 * Inbound direction: history `POP` events (back/forward) and any
 * `opts.incomingAc` signal match the current pathname against the attached
 * routes (falling back to `opts.defaultRoute` for incoming ACs) and fire
 * `{Route,Match}` + the attached AppCons — see `reactToRoute`.
 *
 * The instance keeps no public state; it lives through the handlers it
 * registers (the package's default `init` export does not even return it).
 *
 * @export
 * @class Router
 */
export default class Router {
  /**
   * Creates a Router and registers all of its TAO handlers.
   *
   * @param {Kernel} TAO - the kernel to bridge
   * @param {(HistoryLike|RouterOptions|null)} [history] - the history to
   *        drive; omit (or pass the options object here) to create a
   *        browser history
   * @param {RouterOptions} [opts]
   */
  constructor(TAO, history, opts) {
    this._tao = TAO;
    if (!opts) {
      opts = /** @type {RouterOptions} */ (history);
      history = null;
    }
    opts = opts || {};
    const { debug = false } = opts;
    this._debug = debug;
    this._history = /** @type {HistoryLike} */ (history || createHistory());
    this.setupEvents = this.setupEvents.bind(this);
    this.historyChange = this.historyChange.bind(this);
    this.getPathFrom = this.getPathFrom.bind(this);
    this.getAcsFrom = this.getAcsFrom.bind(this);
    /** @type {Map<string, Handler>} */
    this._routes = new Map();
    this._router = routington();
    this.setupEvents(
      TAO,
      this._history,
      opts.initAc,
      opts.incomingAc,
      opts.defaultRoute,
      opts.orient,
    );
  }
 
  /**
   * Register the Router's handlers (see the class doc for the protocol).
   * Called once from the constructor.
   *
   * @param {Kernel} TAO - the kernel to bridge
   * @param {HistoryLike} history - the history to drive
   * @param {(Trigram|AppCtx)} [initAc] - see `RouterOptions.initAc`
   * @param {(Trigram|AppCtx|Array<Trigram|AppCtx>)} [incomingAc] - see
   *        `RouterOptions.incomingAc`
   * @param {string} [defaultRoute] - see `RouterOptions.defaultRoute`
   * @param {string} [orient] - see `RouterOptions.orient`
   * @returns {void}
   */
  setupEvents = (TAO, history, initAc, incomingAc, defaultRoute, orient) => {
    this._unlistenHistory = history.listen(this.historyChange);
    const incoming = !incomingAc
      ? []
      : (Array.isArray(incomingAc) ? incomingAc : [incomingAc]).map((ac) =>
          wrapAc(ac),
        );
    TAO.addInlineHandler(initAc, (tao, data) => {
      return new AppCtx('Router', 'Init', tao.o);
    });
    TAO.addInlineHandler(
      { t: 'Routes', a: 'Configure', o: orient || '' },
      (tao, { Routes, Configure }) => {
        const routes = Array.isArray(Routes) ? Routes : [Routes];
        // routes.forEach((r, i) => {
        //   const config = Configure[i];
        routes.forEach(({ Route, Add, Remove, Attach, Detach }) => {
          if (Add) {
            TAO.setCtx({ t: 'Route', a: 'Add', o: tao.o }, [Route, Add]);
          }
          if (Remove) {
            TAO.setCtx({ t: 'Route', a: 'Remove', o: tao.o }, [Route, Remove]);
          }
          if (Attach) {
            TAO.setCtx({ t: 'Route', a: 'Attach', o: tao.o }, [Route, Attach]);
          }
          if (Detach) {
            TAO.setCtx({ t: 'Route', a: 'Detach', o: tao.o }, [Route, Detach]);
          }
        });
        return incoming[0];
      },
    );
    TAO.addInlineHandler(
      { t: 'Route', a: 'Add', o: orient || '' },
      (tao, { Route, Add }) => {
        // add Route to the Router's configuration
        // Stryker disable next-line all: optional debug logging
        this._debug && console.log(`adding to Route:`, Route, Add);
        const routeHandler = makeRouteHandler(history, Route, this._debug);
        const trigram = wrapAc(Add.tao || Add);
        const oldHandler = this._routes.get(trigram.key);
        if (oldHandler) {
          TAO.removeAsyncHandler(trigram.unwrapCtx(), oldHandler);
        }
        const handler = wrapIgnore(routeHandler, Add.ignore);
        this._routes.set(trigram.key, handler);
        this._debug &&
          console.log('route.add::trigram.unwrapCtx():', trigram.unwrapCtx());
        TAO.addAsyncHandler(trigram.unwrapCtx(), handler);
        if (Add.attach) {
          return new AppCtx('Route', 'Attach', tao.o, Route, Add);
        }
      },
    );
    TAO.addInlineHandler(
      { t: 'Route', a: 'Remove', o: orient || '' },
      (tao, { Route, Remove }) => {
        // remove Route from the Router's configuration
        // Stryker disable next-line all: optional debug logging
        this._debug && console.log(`removing from Route ${Route}:`, Remove);
        const trigram = wrapAc(Remove);
        const routeHandler = this._routes.get(trigram.key);
        if (!routeHandler) {
          return;
        }
        TAO.removeAsyncHandler(trigram.unwrapCtx(), routeHandler);
        this._routes.delete(trigram.key);
        if (Remove.detach) {
          return new AppCtx('Route', 'Detach', tao.o, Route, Remove);
        }
      },
    );
    TAO.addInlineHandler(
      { t: 'Route', a: 'Attach', o: orient || '' },
      (tao, { Route, Attach }) => {
        // attach Trigram to an incoming route
        // Stryker disable next-line all: optional debug logging
        this._debug && console.log('Going to Attach Route:', { Route, Attach });
        const routeToUse = Route.path || Route;
        const deconstruction = deconstructPath(routeToUse);
        const convertedPath = convertPath(deconstruction);
        const node = this._router.define(convertedPath)[0];
        node.route = routeToUse;
        node.lowerCase = Route.lowerCase;
        node.deconstruction = deconstruction;
        node.attached = node.attached || [];
        // const attachTo = wrapAc({ o: tao.o, ...(Attach.tao || Attach) });
        const attachTo = wrapAc(Attach.tao || Attach);
        node.attached.push(attachTo);
        node.defaultData = node.defaultData || new Map();
        if (Attach.tao) {
          node.defaultData.set(attachTo.key, Attach.data || {});
        }
      },
    );
    TAO.addInlineHandler(
      { t: 'Route', a: 'Detach', o: orient || '' },
      (tao, { Route, Detach }) => {
        // detach Trigram from an incoming route
        // Stryker disable next-line all: optional debug logging
        this._debug && console.log('Going to Detach Route:', { Route, Detach });
        const routeToUse = Route.path || Route;
        const deconstruction = deconstructPath(routeToUse);
        const convertedPath = convertPath(deconstruction);
        const node = this._router.define(convertedPath)[0];
        if (node.attached && node.attached.length) {
          // const attachTo = wrapAc({ o: tao.o, ...(Attach.tao || Attach) });
          const attachTo = wrapAc(Detach.tao || Detach);
          node.attached = node.attached.filter(
            (trigram) => !trigram.isMatch(attachTo, true),
          );
          // Stryker disable next-line ConditionalExpression,LogicalOperator: equivalent - the Attach handler above always initializes node.defaultData together with node.attached, so by the time Detach's outer `node.attached.length` guard is true, node.defaultData is always truthy too
          if (node.defaultData && node.defaultData.has(attachTo.key)) {
            node.defaultData.delete(attachTo.key);
          }
        }
      },
    );
    // TAO.addAsyncHandler({}, (tao, data) => {
    //   const current = new AppCtx(tao.t, tao.a, tao.o, data);
    //   // ignore the initial AC b/c we use that to trigger {Router,Init,}
    //   if (current.key === initAc.key) {
    //     return;
    //   }
    //   const updatePath = this.getPathFrom(tao, data);
    //   if (updatePath != null) {
    //     this._history.push(updatePath);
    //   }
    // });
    // Stryker disable next-line ConditionalExpression: equivalent - forEach over an empty `incoming` array is already a no-op, so forcing entry into this block changes nothing observable when incoming.length is 0
    if (incoming.length) {
      // Stryker disable next-line all: optional debug logging
      this._debug && console.log('adding handlers for incoming:', incoming);
      incoming.forEach((inAc) => {
        TAO.addInlineHandler(inAc, (tao, data) => {
          // Stryker disable all: optional debug logging
          this._debug &&
            console.log('Router::incoming AC handler:', { tao, data });
          // Stryker restore all
          let match = this._router.match(this._history.location.pathname);
          if (!match && defaultRoute) {
            match = this._router.match(defaultRoute);
            // Stryker disable all: optional debug logging
            this._debug &&
              console.log(
                'Router::no match::match from default route "%s"',
                defaultRoute,
                match,
              );
            // Stryker restore all
          }
          if (match) {
            reactToRoute(this._tao, match, this._debug);
          }
          // const loc = this._history.location;
          // const acs = this.getAcsFrom(loc, tao, data);
          // acs.forEach(appCtx => {
          //   if (appCtx != null) {
          //     TAO.setAppCtx(appCtx);
          //   }
          // });
        });
      });
    }
  }; //;
 
  // this should move to just being an added Async Handler on the individual routes
  // OR would that make the TAO sets too big?
  // they would certainly be completely directed with no middle man interpreter
  /**
   * Vestigial: hardcoded tao→path mapping from the original prototype
   * (`{Space,View}` → `/space`); not called by anything today.
   *
   * @param {Object} tao - a `{ t, a, o }` trigram
   * @param {*} data
   * @returns {(string|undefined)}
   */
  getPathFrom = (tao, data) => {
    if (tao.a !== 'View') {
      return;
    }
    return tao.t === 'Space' ? '/space' : '';
  };
 
  /**
   * Vestigial: always returns an empty list; not called by anything today.
   *
   * @param {Object} location - a history location
   * @param {Object} tao - a `{ t, a, o }` trigram
   * @param {*} data
   * @returns {AppCtx[]}
   */
  getAcsFrom = (location, tao, data) => {
    return [];
  };
 
  /**
   * History listener: on `POP` (back/forward navigation), match the new
   * pathname against the route tree and fire the matched route's attached
   * AppCons (`reactToRoute`). Pushes from route handlers do not re-fire.
   *
   * @param {{ pathname: string }} location - the new location
   * @param {string} action - the history action (`'PUSH'`/`'REPLACE'`/`'POP'`)
   * @returns {void}
   */
  historyChange = (location, action) => {
    // match the new location to our route tree to find Trigrams and fire ACs from path data
    // Stryker disable next-line all: optional debug logging
    this._debug && console.log('history change:', { location, action });
    const match = this._router.match(location.pathname);
    if (CHANGE_ACTION_SIGNAL === action && match) {
      reactToRoute(this._tao, match, this._debug);
    }
  };
}