minotor 12.0.0 → 13.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/CHANGELOG.md +4 -4
  2. package/README.md +7 -4
  3. package/dist/cli/perf.d.ts +19 -9
  4. package/dist/cli.mjs +289 -206
  5. package/dist/cli.mjs.map +1 -1
  6. package/dist/parser.cjs.js +37 -19
  7. package/dist/parser.cjs.js.map +1 -1
  8. package/dist/parser.esm.js +37 -19
  9. package/dist/parser.esm.js.map +1 -1
  10. package/dist/router.cjs.js +1 -1
  11. package/dist/router.cjs.js.map +1 -1
  12. package/dist/router.d.ts +2 -1
  13. package/dist/router.esm.js +1 -1
  14. package/dist/router.esm.js.map +1 -1
  15. package/dist/router.umd.js +1 -1
  16. package/dist/router.umd.js.map +1 -1
  17. package/dist/routing/rangeResult.d.ts +34 -25
  18. package/dist/routing/result.d.ts +28 -9
  19. package/dist/routing/resultInternals.d.ts +4 -0
  20. package/dist/routing/routingResult.d.ts +29 -0
  21. package/dist/routing/state.d.ts +2 -2
  22. package/dist/stops/stopsIndex.d.ts +1 -1
  23. package/dist/timetable/route.d.ts +2 -0
  24. package/package.json +2 -2
  25. package/src/cli/minotor.ts +20 -3
  26. package/src/cli/perf.ts +98 -111
  27. package/src/cli/repl.ts +1 -1
  28. package/src/router.ts +3 -0
  29. package/src/routing/__tests__/plotter.test.ts +0 -11
  30. package/src/routing/__tests__/rangeResult.test.ts +1470 -46
  31. package/src/routing/__tests__/rangeRouter.test.ts +14 -8
  32. package/src/routing/__tests__/result.test.ts +375 -76
  33. package/src/routing/__tests__/state.test.ts +29 -0
  34. package/src/routing/plainRouter.ts +1 -6
  35. package/src/routing/plotter.ts +6 -5
  36. package/src/routing/rangeResult.ts +67 -52
  37. package/src/routing/rangeRouter.ts +3 -8
  38. package/src/routing/result.ts +95 -36
  39. package/src/routing/resultInternals.ts +5 -0
  40. package/src/routing/routingResult.ts +34 -0
  41. package/src/routing/state.ts +11 -3
  42. package/src/stops/__tests__/stopFinder.test.ts +13 -0
  43. package/src/stops/stopsIndex.ts +13 -19
  44. package/src/timetable/__tests__/io.test.ts +27 -0
  45. package/src/timetable/__tests__/route.test.ts +30 -0
  46. package/src/timetable/io.ts +15 -1
  47. package/src/timetable/route.ts +19 -5
  48. package/src/timetable/timetable.ts +1 -1
@@ -2,6 +2,7 @@ import { StopId } from '../stops/stops.js';
2
2
  import { Duration, Time } from '../timetable/time.js';
3
3
  import { Result } from './result.js';
4
4
  import { Route } from './route.js';
5
+ import type { RoutingResult, StopArrival } from './routingResult.js';
5
6
  import { Arrival } from './state.js';
6
7
  /**
7
8
  * A single departure-time iteration that produced at least one Pareto-optimal
@@ -39,37 +40,34 @@ export type ArrivalWithDuration = Arrival & {
39
40
  * strictly earlier *and* arrives strictly earlier than the previous one,
40
41
  * forming the classic staircase Pareto frontier.
41
42
  *
42
- * **Full-network mode** (empty `destinations`): when no destinations are
43
+ * **Full-network mode** (no query destinations): when no destinations are
43
44
  * supplied to the range query every departure slot in the window becomes its
44
45
  * own run, because destination-based Pareto pruning cannot be applied.
45
- * In this mode the destination-specific helpers ({@link getRoutes},
46
+ * In this mode the destination-specific helpers ({@link routes},
46
47
  * {@link bestRoute}, {@link latestDepartureRoute}, {@link fastestRoute})
47
- * return empty results; use {@link allEarliestArrivals},
48
- * {@link allShortestDurations}, {@link earliestArrivalAt}, or
48
+ * return empty results; use {@link arrivals},
49
+ * {@link shortestDurations}, {@link arrivalAt}, or
49
50
  * {@link shortestDurationTo} instead.
50
51
  *
51
52
  * Destination handling is delegated to {@link Result}, which expands
52
53
  * equivalent stops when reconstructing routes or looking up arrivals.
53
54
  */
54
- export declare class RangeResult {
55
+ export declare class RangeResult implements RoutingResult {
55
56
  private readonly _runs;
56
- private readonly _destinations;
57
- constructor(runs: ParetoRun[], destinations: ReadonlySet<StopId>);
58
- /** The resolved destination stop IDs for this result. */
59
- get destinations(): ReadonlySet<StopId>;
57
+ constructor(runs: ParetoRun[]);
60
58
  private normalizeTargets;
61
59
  /**
62
- * Returns all non-dominated routes to this result's default destination set,
60
+ * Lazily yields all non-dominated routes to this result's default destination set,
63
61
  * ordered from the earliest departure to the latest departure.
64
62
  *
65
- * Each route in the list departs strictly earlier *and* arrives strictly
66
- * earlier than its predecessor.
63
+ * Each route in the list departs strictly later *and* arrives strictly
64
+ * later than its predecessor.
67
65
  *
68
- * Returns an empty array when no destinations were provided (full-network
69
- * mode). Use {@link allEarliestArrivals} or {@link allShortestDurations}
66
+ * Yields nothing when no destinations were provided (full-network
67
+ * mode). Use {@link arrivals} or {@link shortestDurations}
70
68
  * to query individual stops in that case.
71
69
  */
72
- getRoutes(): Route[];
70
+ routes(): Generator<Route>;
73
71
  /**
74
72
  * The route that arrives **earliest** at the given stop(s) across all
75
73
  * Pareto-optimal runs.
@@ -83,10 +81,11 @@ export declare class RangeResult {
83
81
  * (no destinations), otherwise `undefined` is returned.
84
82
  *
85
83
  * @param to Optional destination stop ID or set of stop IDs.
84
+ * @param maxTransfers Optional transfer limit within retained data.
86
85
  * @returns The reconstructed {@link Route} with the earliest arrival,
87
86
  * or `undefined` if the target is unreachable in every run.
88
87
  */
89
- bestRoute(to?: StopId | Set<StopId>): Route | undefined;
88
+ bestRoute(to?: StopId | Set<StopId>, maxTransfers?: number): Route | undefined;
90
89
  /**
91
90
  * The route with the **latest possible departure** from the origin among all
92
91
  * Pareto-optimal journeys in the window.
@@ -101,10 +100,11 @@ export declare class RangeResult {
101
100
  * (no destinations), otherwise `undefined` is returned.
102
101
  *
103
102
  * @param to Optional destination stop ID or set of stop IDs.
103
+ * @param maxTransfers Optional transfer limit within retained data.
104
104
  * @returns The reconstructed {@link Route} with the latest departure,
105
105
  * or `undefined` if the target is unreachable in every run.
106
106
  */
107
- latestDepartureRoute(to?: StopId | Set<StopId>): Route | undefined;
107
+ latestDepartureRoute(to?: StopId | Set<StopId>, maxTransfers?: number): Route | undefined;
108
108
  /**
109
109
  * Reconstructs the **fastest** route to the given stop(s) — the journey with
110
110
  * the shortest travel duration (arrival time − origin departure time) across
@@ -119,10 +119,11 @@ export declare class RangeResult {
119
119
  * (no destinations), otherwise `undefined` is returned.
120
120
  *
121
121
  * @param to Optional destination stop ID or set of stop IDs.
122
+ * @param maxTransfers Optional transfer limit within retained data.
122
123
  * @returns The reconstructed fastest {@link Route}, or `undefined` if the
123
124
  * target is unreachable in every run.
124
125
  */
125
- fastestRoute(to?: StopId | Set<StopId>): Route | undefined;
126
+ fastestRoute(to?: StopId | Set<StopId>, maxTransfers?: number): Route | undefined;
126
127
  /** Number of Pareto-optimal journeys found. */
127
128
  get size(): number;
128
129
  /**
@@ -135,9 +136,9 @@ export declare class RangeResult {
135
136
  * Equivalent stops are handled by {@link Result.arrivalAt}.
136
137
  *
137
138
  * @param stop The target stop ID.
138
- * @param maxTransfers Optional upper bound on the number of transfers.
139
+ * @param maxTransfers Optional transfer limit within retained data.
139
140
  */
140
- earliestArrivalAt(stop: StopId, maxTransfers?: number): Arrival | undefined;
141
+ arrivalAt(stop: StopId, maxTransfers?: number): Arrival | undefined;
141
142
  /**
142
143
  * Shortest travel duration to reach a stop across all Pareto-optimal runs.
143
144
  *
@@ -154,19 +155,27 @@ export declare class RangeResult {
154
155
  * Returns `undefined` if `stop` is unreachable in every run.
155
156
  *
156
157
  * @param stop The target stop ID.
157
- * @param maxTransfers Optional upper bound on the number of transfers.
158
+ * @param maxTransfers Optional transfer limit within retained data.
158
159
  */
159
160
  shortestDurationTo(stop: StopId, maxTransfers?: number): ArrivalWithDuration | undefined;
160
161
  /**
161
162
  * Shortest travel duration to **every reachable stop** across all
162
- * Pareto-optimal runs, as a single `Map<StopId, DurationArrival>`.
163
+ * Pareto-optimal runs, yielding the stop ID and arrival with duration.
164
+ * All runs are aggregated before the first value is yielded. Ties retain
165
+ * the first run's arrival and leg count.
166
+ * @param maxTransfers Optional transfer limit within retained data.
163
167
  */
164
- allShortestDurations(): Map<StopId, ArrivalWithDuration>;
168
+ shortestDurations(maxTransfers?: number): Generator<StopArrival & {
169
+ duration: Duration;
170
+ }>;
165
171
  /**
166
172
  * Earliest achievable arrival at **every reachable stop** across all
167
- * Pareto-optimal runs, as a single `Map<StopId, Arrival>`.
173
+ * Pareto-optimal runs, yielding the stop ID and arrival.
174
+ * All runs are aggregated before the first value is yielded. Ties retain
175
+ * the first run's arrival and leg count.
176
+ * @param maxTransfers Optional transfer limit within retained data.
168
177
  */
169
- allEarliestArrivals(): Map<StopId, Arrival>;
178
+ arrivals(maxTransfers?: number): Generator<StopArrival>;
170
179
  /**
171
180
  * Iterates over all Pareto-optimal `(departureTime, result)` pairs,
172
181
  * ordered from the latest departure to the earliest departure.
@@ -1,19 +1,36 @@
1
1
  import { Timetable } from '../router.js';
2
2
  import { SourceStopId, StopId } from '../stops/stops.js';
3
3
  import { StopsIndex } from '../stops/stopsIndex.js';
4
+ import { resultDestinations, resultGraph } from './resultInternals.js';
4
5
  import { Route } from './route.js';
5
6
  import { Arrival, RoutingState } from './router.js';
6
- export declare class Result {
7
- private readonly destinations;
8
- readonly routingState: RoutingState;
7
+ import type { RoutingResult, StopArrival } from './routingResult.js';
8
+ /**
9
+ * A single-departure routing result.
10
+ */
11
+ export declare class Result implements RoutingResult {
12
+ #private;
9
13
  readonly stopsIndex: StopsIndex;
10
14
  readonly timetable: Timetable;
11
- constructor(destinations: ReadonlySet<StopId>, routingState: RoutingState, stopsIndex: StopsIndex, timetable: Timetable);
15
+ constructor(routingState: RoutingState, stopsIndex: StopsIndex, timetable: Timetable);
16
+ /** @internal Default query destinations for range result selection. */
17
+ [resultDestinations](): readonly StopId[];
18
+ /** @internal Routing graph and destination metadata for the graph plotter. */
19
+ [resultGraph](): Pick<RoutingState, 'graph' | 'destinations'>;
20
+ /**
21
+ * Iterates over reached stops, yielding each concrete stop ID, its earliest
22
+ * arrival time, and the number of legs taken to reach it. Unreached stops
23
+ * are omitted. Destination pruning may limit which stops were reached.
24
+ * @param maxTransfers Optional transfer limit within retained data.
25
+ */
26
+ arrivals(maxTransfers?: number): Generator<StopArrival>;
27
+ /** Looks up one concrete stop without expanding equivalent stops. */
28
+ private concreteArrivalAt;
12
29
  /**
13
30
  * Expands a target stop or stop set to all equivalent concrete stop IDs.
14
31
  *
15
- * When `to` is omitted, defaults to the resolved destinations stored on this
16
- * result.
32
+ * When `to` is omitted, defaults to the resolved destinations in the
33
+ * query.
17
34
  *
18
35
  * Equivalent stops are expanded here so destination handling has a single
19
36
  * source of truth shared by route reconstruction and arrival lookups.
@@ -25,9 +42,10 @@ export declare class Result {
25
42
  * destination set)
26
43
  *
27
44
  * @param to The destination stop by SourceStopId.
45
+ * @param maxTransfers Optional transfer limit within retained data.
28
46
  * @returns a route to the destination stop if it exists.
29
47
  */
30
- bestRouteToSourceStopId(to: SourceStopId | Set<SourceStopId>): Route | undefined;
48
+ bestRouteToSourceStopId(to: SourceStopId | Set<SourceStopId>, maxTransfers?: number): Route | undefined;
31
49
  /**
32
50
  * Reconstructs the best route to a stop.
33
51
  * (to any stop reachable in less time / transfers than this result's
@@ -35,9 +53,10 @@ export declare class Result {
35
53
  *
36
54
  * @param to The destination stop. Defaults to this result's resolved
37
55
  * destinations.
56
+ * @param maxTransfers Optional transfer limit within retained data.
38
57
  * @returns a route to the destination stop if it exists.
39
58
  */
40
- bestRoute(to?: StopId | Set<StopId>): Route | undefined;
59
+ bestRoute(to?: StopId | Set<StopId>, maxTransfers?: number): Route | undefined;
41
60
  private buildServiceRouteInfo;
42
61
  /**
43
62
  * Builds a vehicle leg from a chain of vehicle edges.
@@ -76,7 +95,7 @@ export declare class Result {
76
95
  * than this result's destination set.
77
96
  *
78
97
  * @param stop The target stop for which to return the arrival time.
79
- * @param maxTransfers The optional maximum number of transfers allowed.
98
+ * @param maxTransfers Optional transfer limit within retained data.
80
99
  * @returns The arrival time if the target stop is reachable, otherwise undefined.
81
100
  */
82
101
  arrivalAt(stop: StopId, maxTransfers?: number): Arrival | undefined;
@@ -0,0 +1,4 @@
1
+ /** Internal plotter access; deliberately not exported from the package entry point. */
2
+ export declare const resultGraph: unique symbol;
3
+ /** Internal access to query destinations for range result selection. */
4
+ export declare const resultDestinations: unique symbol;
@@ -0,0 +1,29 @@
1
+ import type { StopId } from '../stops/stops.js';
2
+ import type { Route } from './route.js';
3
+ import type { Arrival } from './state.js';
4
+ export type StopArrival = Arrival & {
5
+ stop: StopId;
6
+ };
7
+ /**
8
+ * Common earliest-arrival operations for single-departure and range results.
9
+ */
10
+ export interface RoutingResult {
11
+ /**
12
+ * Earliest arrival at a stop or an equivalent stop, optionally limited by
13
+ * transfer count. Returns undefined when no matching stop was reached.
14
+ */
15
+ arrivalAt(stop: StopId, maxTransfers?: number): Arrival | undefined;
16
+ /**
17
+ * Iterates once over each reached concrete stop and its earliest arrival.
18
+ * Destination pruning may limit coverage. Each call returns a fresh iterator.
19
+ * @param maxTransfers Optional transfer limit within retained data.
20
+ */
21
+ arrivals(maxTransfers?: number): IterableIterator<StopArrival>;
22
+ /**
23
+ * Reconstructs the earliest-arriving route to the given or default
24
+ * destinations. Returns undefined when none
25
+ * were reached or when no destinations were provided.
26
+ * @param maxTransfers Optional transfer limit within retained data.
27
+ */
28
+ bestRoute(to?: StopId | Set<StopId>, maxTransfers?: number): Route | undefined;
29
+ }
@@ -87,8 +87,8 @@ export declare class RoutingState implements IRaptorState {
87
87
  */
88
88
  private readonly maxDuration?;
89
89
  /**
90
- * Every stop that has received an arrival improvement during the current run,
91
- * in the order the improvements occurred. Used by {@link resetFor} to clear
90
+ * Every stop reached during the current run, recorded once in first-reached
91
+ * order. Used by {@link resetFor} to clear
92
92
  * only the touched entries instead of scanning the entire array.
93
93
  */
94
94
  private readonly reachedStops;
@@ -9,7 +9,7 @@ export declare class StopsIndex {
9
9
  private readonly sourceStopsMap;
10
10
  private readonly textIndex;
11
11
  private readonly geoIndex;
12
- private readonly stopPoints;
12
+ private readonly geoStopIds;
13
13
  constructor(stops: Stop[]);
14
14
  /**
15
15
  * Deserializes a binary representation of the stops.
@@ -201,6 +201,8 @@ export declare class Route {
201
201
  * @returns An array of indices where the stop appears in the route, or an empty array if the stop is not found.
202
202
  */
203
203
  stopRouteIndices(stopId: StopId): StopRouteIndex[];
204
+ /** Returns the first occurrence without allocating an array. */
205
+ firstStopRouteIndex(stopId: StopId): StopRouteIndex | undefined;
204
206
  /**
205
207
  * Retrieves the id of a stop at a given index in a route.
206
208
  * @param stopRouteIndex The route index of the stop.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "minotor",
3
- "version": "12.0.0",
3
+ "version": "13.0.0",
4
4
  "description": "A lightweight client-side transit routing library.",
5
5
  "keywords": [
6
6
  "minotor",
@@ -65,7 +65,7 @@
65
65
  "format": "prettier --write .",
66
66
  "test": "tsx --test src/**/__tests__/*.test.ts",
67
67
  "e2e": "tsx --test src/__e2e__/*.test.ts",
68
- "perf": "tsx src/cli/minotor perf -s src/__e2e__/timetable/stops.bin -t src/__e2e__/timetable/timetable.bin src/__e2e__/benchmark.json",
68
+ "perf": "node --expose-gc --import tsx src/cli/minotor perf -s src/__e2e__/timetable/stops.bin -t src/__e2e__/timetable/timetable.bin src/__e2e__/benchmark.json",
69
69
  "repl": "tsx src/cli/minotor repl -s src/__e2e__/timetable/stops.bin -t src/__e2e__/timetable/timetable.bin",
70
70
  "test:watch": "tsx --watch --test src/**/*.test.ts",
71
71
  "test:coverage": "c8 -x 'src/**/proto/**/*.ts' -x 'src/**/__tests__/*.ts' --check-coverage --lines=85 tsx --test src/**/__tests__/*.test.ts",
@@ -14,6 +14,7 @@ import { Router, StopsIndex, Timetable } from '../router.js';
14
14
  import {
15
15
  loadQueriesFromJson,
16
16
  loadRangeQueriesFromJson,
17
+ measureRetainedMemory,
17
18
  prettyPrintPerformanceResults,
18
19
  testBestRoutePerformance,
19
20
  testRangeResultPerformance,
@@ -175,9 +176,25 @@ program
175
176
  const stopsIndex = StopsIndex.fromData(
176
177
  fs.readFileSync(options.stopsPath),
177
178
  );
178
- const timetable = Timetable.fromData(
179
- fs.readFileSync(options.timetablePath),
179
+ const loading = measureRetainedMemory(() =>
180
+ Timetable.fromData(fs.readFileSync(options.timetablePath)),
180
181
  );
182
+ const timetable = loading.value;
183
+ console.log(
184
+ `Timetable load (read + decode): ${loading.loadTimeMs.toFixed(2)} ms`,
185
+ );
186
+ if (
187
+ loading.retainedHeapMiB !== undefined &&
188
+ loading.retainedArrayBuffersMiB !== undefined
189
+ ) {
190
+ console.log(
191
+ `Timetable retained after GC: heap ${loading.retainedHeapMiB.toFixed(2)} MiB; ArrayBuffers ${loading.retainedArrayBuffersMiB.toFixed(2)} MiB`,
192
+ );
193
+ } else {
194
+ console.log(
195
+ 'Retained memory skipped: explicit GC unavailable; use node --expose-gc.',
196
+ );
197
+ }
181
198
  const router = new Router(timetable, stopsIndex);
182
199
 
183
200
  const queries = loadQueriesFromJson(routesPath, stopsIndex);
@@ -226,7 +243,7 @@ program
226
243
  );
227
244
  prettyPrintPerformanceResults(
228
245
  rangeResultResults,
229
- 'Range queries — rangeResult.getRoutes() (reconstruction only)',
246
+ 'Range queries — rangeResult.routes() (reconstruction only)',
230
247
  );
231
248
  },
232
249
  );
package/src/cli/perf.ts CHANGED
@@ -13,7 +13,68 @@ import { timeFromString, timeToString } from '../timetable/time.js';
13
13
  type PerformanceResult = {
14
14
  label: string;
15
15
  meanTimeUs: number;
16
- meanMemoryMb: number;
16
+ meanHeapMiB: number;
17
+ meanArrayBuffersMiB: number;
18
+ };
19
+
20
+ // Keep operation results reachable until the ending memory sample has been taken.
21
+ const retainedResults: unknown[] = [];
22
+
23
+ /** Observed deltas, not peak memory or total allocations; GC can make them negative. */
24
+ export const measurePerformance = (
25
+ operation: () => unknown,
26
+ iterations: number,
27
+ ): Omit<PerformanceResult, 'label'> => {
28
+ let totalTime = 0;
29
+ let totalHeap = 0;
30
+ let totalArrayBuffers = 0;
31
+ for (let i = 0; i < iterations; i++) {
32
+ global.gc?.();
33
+ const before = process.memoryUsage();
34
+ const start = performance.now();
35
+ const result = operation();
36
+ const end = performance.now();
37
+ retainedResults.push(result);
38
+ const after = process.memoryUsage();
39
+ retainedResults.pop();
40
+ totalTime += (end - start) * 1_000;
41
+ totalHeap += after.heapUsed - before.heapUsed;
42
+ totalArrayBuffers += after.arrayBuffers - before.arrayBuffers;
43
+ }
44
+ return {
45
+ meanTimeUs: totalTime / iterations,
46
+ meanHeapMiB: totalHeap / iterations / (1024 * 1024),
47
+ meanArrayBuffersMiB: totalArrayBuffers / iterations / (1024 * 1024),
48
+ };
49
+ };
50
+
51
+ /** Measure retained storage after collection, keeping only the returned value alive. */
52
+ export const measureRetainedMemory = <T>(
53
+ operation: () => T,
54
+ ): {
55
+ value: T;
56
+ loadTimeMs: number;
57
+ retainedHeapMiB?: number;
58
+ retainedArrayBuffersMiB?: number;
59
+ } => {
60
+ const gc = global.gc;
61
+ gc?.();
62
+ const before = gc ? process.memoryUsage() : undefined;
63
+ const start = performance.now();
64
+ const value = operation();
65
+ const loadTimeMs = performance.now() - start;
66
+ if (!gc || !before) return { value, loadTimeMs };
67
+ // A second collection lets backing storage released by finalization settle.
68
+ gc();
69
+ gc();
70
+ const after = process.memoryUsage();
71
+ return {
72
+ value,
73
+ loadTimeMs,
74
+ retainedHeapMiB: (after.heapUsed - before.heapUsed) / (1024 * 1024),
75
+ retainedArrayBuffersMiB:
76
+ (after.arrayBuffers - before.arrayBuffers) / (1024 * 1024),
77
+ };
17
78
  };
18
79
 
19
80
  type SerializedQuery = {
@@ -204,7 +265,7 @@ export const loadRangeQueriesFromJson = (
204
265
  * yield a more stable mean at the cost of longer wall-clock time.
205
266
  * @param stopsIndex - Used to resolve stop names for result labels.
206
267
  * @returns An array of {@link PerformanceResult} objects, one per query, each
207
- * containing the mean wall-clock time (µs) and mean heap delta (MB).
268
+ * containing the mean wall-clock time (µs) and mean heap and ArrayBuffer deltas (MiB).
208
269
  */
209
270
  export const testRouterPerformance = (
210
271
  router: Router,
@@ -215,32 +276,9 @@ export const testRouterPerformance = (
215
276
  const results: PerformanceResult[] = [];
216
277
 
217
278
  for (const task of tasks) {
218
- let totalTime = 0;
219
- let totalMemory = 0;
220
-
221
- for (let i = 0; i < iterations; i++) {
222
- if (global.gc) {
223
- global.gc();
224
- }
225
-
226
- const startMemory = process.memoryUsage().heapUsed;
227
- const startTime = performance.now();
228
-
229
- router.route(task);
230
-
231
- const endTime = performance.now();
232
- const endMemory = process.memoryUsage().heapUsed;
233
-
234
- totalTime += (endTime - startTime) * 1_000;
235
- if (endMemory >= startMemory) {
236
- totalMemory += endMemory - startMemory;
237
- }
238
- }
239
-
240
279
  results.push({
241
280
  label: buildQueryLabel(task, stopsIndex),
242
- meanTimeUs: totalTime / iterations,
243
- meanMemoryMb: totalMemory / iterations / (1024 * 1024),
281
+ ...measurePerformance(() => router.route(task), iterations),
244
282
  });
245
283
  }
246
284
 
@@ -258,7 +296,7 @@ export const testRouterPerformance = (
258
296
  * @param iterations - Number of times `bestRoute` is called per query.
259
297
  * @param stopsIndex - Used to resolve stop names for result labels.
260
298
  * @returns An array of {@link PerformanceResult} objects, one per query, each
261
- * containing the mean wall-clock time (µs) and mean heap delta (MB) for the
299
+ * containing the mean wall-clock time (µs) and mean heap and ArrayBuffer deltas (MiB) for the
262
300
  * `bestRoute` call alone.
263
301
  */
264
302
  export const testBestRoutePerformance = (
@@ -272,32 +310,9 @@ export const testBestRoutePerformance = (
272
310
  for (const task of tasks) {
273
311
  const result = router.route(task);
274
312
 
275
- let totalTime = 0;
276
- let totalMemory = 0;
277
-
278
- for (let i = 0; i < iterations; i++) {
279
- if (global.gc) {
280
- global.gc();
281
- }
282
-
283
- const startMemory = process.memoryUsage().heapUsed;
284
- const startTime = performance.now();
285
-
286
- result.bestRoute();
287
-
288
- const endTime = performance.now();
289
- const endMemory = process.memoryUsage().heapUsed;
290
-
291
- totalTime += (endTime - startTime) * 1_000;
292
- if (endMemory >= startMemory) {
293
- totalMemory += endMemory - startMemory;
294
- }
295
- }
296
-
297
313
  results.push({
298
314
  label: buildQueryLabel(task, stopsIndex),
299
- meanTimeUs: totalTime / iterations,
300
- meanMemoryMb: totalMemory / iterations / (1024 * 1024),
315
+ ...measurePerformance(() => result.bestRoute(), iterations),
301
316
  });
302
317
  }
303
318
 
@@ -313,7 +328,7 @@ export const testBestRoutePerformance = (
313
328
  * @param iterations - Number of times each query is repeated.
314
329
  * @param stopsIndex - Used to resolve stop names for result labels.
315
330
  * @returns An array of {@link PerformanceResult} objects, one per query, each
316
- * containing the mean wall-clock time (µs) and mean heap delta (MB).
331
+ * containing the mean wall-clock time (µs) and mean heap and ArrayBuffer deltas (MiB).
317
332
  */
318
333
  export const testRangeRouterPerformance = (
319
334
  router: Router,
@@ -324,32 +339,9 @@ export const testRangeRouterPerformance = (
324
339
  const results: PerformanceResult[] = [];
325
340
 
326
341
  for (const task of tasks) {
327
- let totalTime = 0;
328
- let totalMemory = 0;
329
-
330
- for (let i = 0; i < iterations; i++) {
331
- if (global.gc) {
332
- global.gc();
333
- }
334
-
335
- const startMemory = process.memoryUsage().heapUsed;
336
- const startTime = performance.now();
337
-
338
- router.rangeRoute(task);
339
-
340
- const endTime = performance.now();
341
- const endMemory = process.memoryUsage().heapUsed;
342
-
343
- totalTime += (endTime - startTime) * 1_000;
344
- if (endMemory >= startMemory) {
345
- totalMemory += endMemory - startMemory;
346
- }
347
- }
348
-
349
342
  results.push({
350
343
  label: buildQueryLabel(task, stopsIndex),
351
- meanTimeUs: totalTime / iterations,
352
- meanMemoryMb: totalMemory / iterations / (1024 * 1024),
344
+ ...measurePerformance(() => router.rangeRoute(task), iterations),
353
345
  });
354
346
  }
355
347
 
@@ -357,18 +349,18 @@ export const testRangeRouterPerformance = (
357
349
  };
358
350
 
359
351
  /**
360
- * Benchmarks {@link RangeResult.getRoutes} — the full Pareto-frontier
352
+ * Benchmarks {@link RangeResult.routes} — the full Pareto-frontier
361
353
  * reconstruction phase — independently of the range routing phase.
362
354
  *
363
355
  * @param router - The router instance used to produce the range results that
364
- * are then fed into `getRoutes`.
356
+ * are then fed into `routes`.
365
357
  * @param tasks - The list of range queries to benchmark. One
366
358
  * {@link PerformanceResult} is produced per query.
367
- * @param iterations - Number of times `getRoutes` is called per query.
359
+ * @param iterations - Number of times `routes` is fully consumed per query.
368
360
  * @param stopsIndex - Used to resolve stop names for result labels.
369
361
  * @returns An array of {@link PerformanceResult} objects, one per query, each
370
- * containing the mean wall-clock time (µs) and mean heap delta (MB) for the
371
- * `getRoutes` call alone.
362
+ * containing the mean wall-clock time (µs) and mean heap and ArrayBuffer deltas (MiB) for the
363
+ * full `routes` iteration alone.
372
364
  */
373
365
  export const testRangeResultPerformance = (
374
366
  router: Router,
@@ -381,40 +373,15 @@ export const testRangeResultPerformance = (
381
373
  for (const task of tasks) {
382
374
  const rangeResult: RangeResult = router.rangeRoute(task);
383
375
 
384
- let totalTime = 0;
385
- let totalMemory = 0;
386
-
387
- for (let i = 0; i < iterations; i++) {
388
- if (global.gc) {
389
- global.gc();
390
- }
391
-
392
- const startMemory = process.memoryUsage().heapUsed;
393
- const startTime = performance.now();
394
-
395
- rangeResult.getRoutes();
396
-
397
- const endTime = performance.now();
398
- const endMemory = process.memoryUsage().heapUsed;
399
-
400
- totalTime += (endTime - startTime) * 1_000;
401
- if (endMemory >= startMemory) {
402
- totalMemory += endMemory - startMemory;
403
- }
404
- }
405
-
406
376
  results.push({
407
377
  label: buildQueryLabel(task, stopsIndex),
408
- meanTimeUs: totalTime / iterations,
409
- meanMemoryMb: totalMemory / iterations / (1024 * 1024),
378
+ ...measurePerformance(() => [...rangeResult.routes()], iterations),
410
379
  });
411
380
  }
412
381
 
413
382
  return results;
414
383
  };
415
384
 
416
- // ─── Output ───────────────────────────────────────────────────────────────────
417
-
418
385
  /**
419
386
  * Prints a table summary of performance results to stdout.
420
387
  *
@@ -442,14 +409,19 @@ export const prettyPrintPerformanceResults = (
442
409
  const meanTime =
443
410
  results.reduce((s, r) => s + r.meanTimeUs, 0) / results.length;
444
411
  const meanMem =
445
- results.reduce((s, r) => s + r.meanMemoryMb, 0) / results.length;
412
+ results.reduce((s, r) => s + r.meanHeapMiB, 0) / results.length;
413
+ const meanBuffers =
414
+ results.reduce((s, r) => s + r.meanArrayBuffersMiB, 0) / results.length;
446
415
 
447
416
  const queryHeader = 'Query';
448
417
  const timeHeader = 'Time (µs)';
449
- const memHeader = 'Mem (MB)';
418
+ const memHeader = 'Heap Δ (MiB)';
419
+ const buffersHeader = 'ArrayBuffers Δ (MiB)';
450
420
 
451
421
  const timeVals = results.map((r) => fmtTime(r.meanTimeUs));
452
- const memVals = results.map((r) => fmtMem(r.meanMemoryMb));
422
+ const memVals = results.map((r) => fmtMem(r.meanHeapMiB));
423
+ const bufferVals = results.map((r) => fmtMem(r.meanArrayBuffersMiB));
424
+ const meanBuffersStr = fmtMem(meanBuffers);
453
425
  const meanTimeStr = fmtTime(meanTime);
454
426
  const meanMemStr = fmtMem(meanMem);
455
427
 
@@ -473,14 +445,29 @@ export const prettyPrintPerformanceResults = (
473
445
  { header: queryHeader, width: queryWidth, align: 'left' },
474
446
  { header: timeHeader, width: timeWidth, align: 'right' },
475
447
  { header: memHeader, width: memWidth, align: 'right' },
448
+ {
449
+ header: buffersHeader,
450
+ width: Math.max(
451
+ buffersHeader.length,
452
+ meanBuffersStr.length,
453
+ ...bufferVals.map((v) => v.length),
454
+ ),
455
+ align: 'right',
456
+ },
476
457
  ];
477
458
 
478
459
  const rows = results.map((r, i) => [
479
460
  r.label,
480
461
  timeVals[i] ?? '',
481
462
  memVals[i] ?? '',
463
+ bufferVals[i] ?? '',
482
464
  ]);
483
- const footer = ['mean', meanTimeStr, meanMemStr];
465
+ const footer = ['mean', meanTimeStr, meanMemStr, meanBuffersStr];
484
466
 
485
467
  console.log(renderTable(columns, rows, footer));
468
+ if (!global.gc) {
469
+ console.log(
470
+ 'Explicit GC unavailable; use node --expose-gc for more consistent samples.',
471
+ );
472
+ }
486
473
  };
package/src/cli/repl.ts CHANGED
@@ -173,7 +173,7 @@ export const startRepl = (stopsPath: string, timetablePath: string) => {
173
173
  `from ${fromStop.name} to ${toStop.name} ` +
174
174
  `(window ${atTime}–${beforeTime}):`,
175
175
  );
176
- const routes = result.getRoutes();
176
+ const routes = [...result.routes()];
177
177
  routes.forEach((route, index) => {
178
178
  const journeyNumber = index + 1;
179
179
  console.log(`\nJourney ${journeyNumber}:`);