All files / api/trimet-client/src tripplanner.ts

95.08% Statements 58/61
85.22% Branches 75/88
100% Functions 17/17
98.11% Lines 52/53

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                      57x 51x 6x   23x 23x                                                                                                                         455x       143x 143x       76x 42x   34x 34x       76x       20x 4x   16x 16x                   6x 6x 6x 6x 6x                   6x   6x                                       4x 4x 4x 10x     4x                                   6x         5x 5x       1x     4x 4x 4x   4x     5x 5x   5x           4x                     1x 1x 1x 1x 1x 1x 1x 1x   1x 1x           1x    
import type { TrimetClientOptions } from "./options";
 
export type TripPlannerOptions = (
  { fromPlace: string; fromCoord?: string } | { fromPlace?: string; fromCoord: string }
) & (
  { toPlace: string; toCoord?: string } | { toPlace?: string; toCoord: string }
) & {
  signal?: AbortSignal;
};
 
export function parsePlannerCoordinates(value: string): [number, number] | undefined {
  const parts = value.split(",").map(part => part.trim());
  if (parts.length !== 2 || parts.some(part => !/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/.test(part))) {
    return undefined;
  }
  const [lon, lat] = parts.map(Number);
  if (Math.abs(lon) <= 180 && Math.abs(lat) <= 90) return [lon, lat];
}
 
export interface TripPlannerLocation {
  description?: string;
  stopId?: number;
  stopSequence?: number;
  lat?: number;
  lon?: number;
}
 
export interface TripPlannerRoute {
  number?: string;
  internalNumber?: number;
  name?: string;
  key?: string;
  direction?: string;
  block?: number;
}
 
export interface TripPlannerLeg {
  id?: string;
  mode?: string;
  order?: string;
  from?: TripPlannerLocation;
  to?: TripPlannerLocation;
  route?: TripPlannerRoute;
  direction?: string;
  startTime?: string;
  endTime?: string;
  duration?: number;
  distance?: number;
  partial: boolean;
}
 
export interface TripPlannerItinerary {
  id?: string;
  viaRoute?: string;
  startTime?: string;
  endTime?: string;
  duration?: number;
  distance?: number;
  numberOfTransfers?: number;
  walkingTime?: number;
  transitTime?: number;
  waitingTime?: number;
  fare?: number;
  legs: TripPlannerLeg[];
  partial: boolean;
}
 
export interface TripPlannerResponse {
  success: boolean;
  from?: TripPlannerLocation;
  to?: TripPlannerLocation;
  itineraries: TripPlannerItinerary[];
  errorMessage?: string;
  partial: boolean;
}
 
function child(parent: Element, name: string): Element | undefined {
  return Array.from(parent.children).find((element) => element.localName === name);
}
 
function text(parent: Element, name: string): string | undefined {
  const value = child(parent, name)?.textContent?.trim();
  return value || undefined;
}
 
function numberValue(value?: string): number | undefined {
  if (value === undefined || value.trim() === "") {
    return undefined;
  }
  const parsed = Number(value);
  return Number.isFinite(parsed) ? parsed : undefined;
}
 
function numberText(parent: Element, name: string): number | undefined {
  return numberValue(text(parent, name));
}
 
function parseLocation(element?: Element): TripPlannerLocation | undefined {
  if (!element) {
    return undefined;
  }
  const position = child(element, "pos");
  return {
    description: text(element, "description"),
    stopId: numberText(element, "stopId"),
    stopSequence: numberText(element, "stopSequence"),
    lat: position && numberText(position, "lat"),
    lon: position && numberText(position, "lon"),
  };
}
 
function parseLeg(element: Element): TripPlannerLeg {
  const timeDistance = child(element, "time-distance");
  const from = parseLocation(child(element, "from"));
  const to = parseLocation(child(element, "to"));
  const routeElement = child(element, "route");
  const route = routeElement
    ? {
        number: text(routeElement, "number"),
        internalNumber: numberText(routeElement, "internalNumber"),
        name: text(routeElement, "name"),
        key: text(routeElement, "key"),
        direction: text(routeElement, "direction"),
        block: numberText(routeElement, "block"),
      }
    : undefined;
  const mode = element.getAttribute("mode") || undefined;
 
  return {
    id: element.getAttribute("id") || undefined,
    mode,
    order: element.getAttribute("order") || undefined,
    from,
    to,
    route,
    direction: text(element, "direction"),
    startTime: timeDistance && text(timeDistance, "startTime"),
    endTime: timeDistance && text(timeDistance, "endTime"),
    duration: timeDistance && numberText(timeDistance, "duration"),
    distance: timeDistance && numberText(timeDistance, "distance"),
    partial:
      !from?.description ||
      !to?.description ||
      (!!mode && mode !== "Walk" && !route),
  };
}
 
function parseItinerary(element: Element): TripPlannerItinerary {
  const timeDistance = child(element, "time-distance");
  const fare = child(element, "fare");
  const legs = Array.from(element.children)
    .filter((childElement) => childElement.localName === "leg")
    .map(parseLeg);
 
  return {
    id: element.getAttribute("id") || undefined,
    viaRoute: element.getAttribute("viaRoute") || undefined,
    startTime: timeDistance && text(timeDistance, "startTime"),
    endTime: timeDistance && text(timeDistance, "endTime"),
    duration: timeDistance && numberText(timeDistance, "duration"),
    distance: timeDistance && numberText(timeDistance, "distance"),
    numberOfTransfers: timeDistance && numberText(timeDistance, "numberOfTransfers"),
    walkingTime: timeDistance && numberText(timeDistance, "walkingTime"),
    transitTime: timeDistance && numberText(timeDistance, "transitTime"),
    waitingTime: timeDistance && numberText(timeDistance, "waitingTime"),
    fare: fare && numberText(fare, "regular"),
    legs,
    partial:
      !timeDistance ||
      !text(timeDistance, "startTime") ||
      !text(timeDistance, "endTime") ||
      legs.length === 0 ||
      legs.some((leg) => leg.partial),
  };
}
 
export function parseTripPlannerResponse(xml: string): TripPlannerResponse {
  const document = new DOMParser().parseFromString(xml, "application/xml");
  if (
    document.getElementsByTagName("parsererror").length > 0 ||
    document.documentElement.localName !== "response"
  ) {
    throw new Error("TriMet returned an unreadable trip-planner response.");
  }
 
  const root = document.documentElement;
  const itinerariesElement = child(root, "itineraries");
  const itineraries = itinerariesElement
    ? Array.from(itinerariesElement.children)
        .filter((element) => element.localName === "itinerary")
        .map(parseItinerary)
    : [];
  const error = child(root, "error");
  const errorMessage = error && text(error, "message");
 
  return {
    success: root.getAttribute("success") === "true",
    from: parseLocation(child(root, "from")),
    to: parseLocation(child(root, "to")),
    itineraries,
    errorMessage,
    partial: itineraries.some((itinerary) => itinerary.partial),
  };
}
 
export async function planTrip({
  fromPlace,
  toPlace,
  fromCoord,
  toCoord,
  signal,
}: TripPlannerOptions, { baseUrl, appId }: Pick<TrimetClientOptions, "baseUrl" | "appId">): Promise<TripPlannerResponse> {
  const url = new URL("V1/trips/tripplanner", baseUrl);
  Iif (fromPlace) url.searchParams.set("fromPlace", fromPlace);
  Eif (toPlace) url.searchParams.set("toPlace", toPlace);
  Eif (fromCoord) url.searchParams.set("fromCoord", fromCoord);
  Iif (toCoord) url.searchParams.set("toCoord", toCoord);
  url.searchParams.set("format", "xml");
  url.searchParams.set("appID", appId);
  url.searchParams.set("maxIntineraries", "6");
 
  const response = await fetch(url.toString(), { signal });
  Iif (!response.ok) {
    throw new Error(
      `TriMet trip planning failed (${response.status} ${response.statusText}).`,
    );
  }
 
  return parseTripPlannerResponse(await response.text());
}