gtfs-to-html 2.12.11 → 2.12.13

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.
package/dist/app/index.js CHANGED
@@ -1,2543 +1,121 @@
1
- var __defProp = Object.defineProperty;
2
- var __export = (target, all) => {
3
- for (var name in all)
4
- __defProp(target, name, { get: all[name], enumerable: true });
5
- };
6
-
7
- // src/app/index.ts
8
- import { dirname as dirname2, join as join2 } from "path";
9
- import { fileURLToPath as fileURLToPath2 } from "url";
10
- import { readFileSync } from "fs";
1
+ import { E as GtfsToHtmlErrorCode, T as GtfsToHtmlErrorCategory, _ as setDefaultConfig, a as getPathToViewsFolder, c as untildify, d as generateOverviewHTML, g as getTimetablePagesForAgency, h as getFormattedTimetablePage, k as isGtfsToHtmlError, m as generateTimetableHTML, u as formatTimetableLabel, w as GtfsToHtmlError } from "../file-utils-B3ZcDOSK.js";
2
+ import { dirname, join } from "node:path";
3
+ import { openDb } from "gtfs";
4
+ import { readFileSync } from "node:fs";
5
+ import { fileURLToPath } from "node:url";
11
6
  import yargs from "yargs";
12
7
  import { hideBin } from "yargs/helpers";
13
- import { openDb as openDb2 } from "gtfs";
14
8
  import express from "express";
15
9
 
16
- // src/lib/formatters.ts
17
- import {
18
- clone,
19
- find as find2,
20
- first as first2,
21
- groupBy as groupBy2,
22
- last as last2,
23
- omit,
24
- sortBy as sortBy2,
25
- zipObject
26
- } from "lodash-es";
27
- import moment3 from "moment";
28
-
29
- // src/lib/time-utils.ts
30
- import moment from "moment";
31
- function fromGTFSTime(timeString) {
32
- const duration = moment.duration(timeString);
33
- return moment({
34
- hour: duration.hours(),
35
- minute: duration.minutes(),
36
- second: duration.seconds()
37
- });
38
- }
39
- function toGTFSTime(time) {
40
- return time.format("HH:mm:ss");
41
- }
42
- function calendarToCalendarCode(calendar) {
43
- if (Object.values(calendar).every((value) => value === null)) {
44
- return "";
45
- }
46
- return `${calendar.monday ?? "0"}${calendar.tuesday ?? "0"}${calendar.wednesday ?? "0"}${calendar.thursday ?? "0"}${calendar.friday ?? "0"}${calendar.saturday ?? "0"}${calendar.sunday ?? "0"}`;
47
- }
48
- function calendarCodeToCalendar(code) {
49
- const days2 = [
50
- "monday",
51
- "tuesday",
52
- "wednesday",
53
- "thursday",
54
- "friday",
55
- "saturday",
56
- "sunday"
57
- ];
58
- const calendar = {};
59
- for (const [index, day] of days2.entries()) {
60
- calendar[day] = code[index];
61
- }
62
- return calendar;
63
- }
64
- function calendarToDateList(calendar, startDate, endDate) {
65
- if (!startDate || !endDate) {
66
- return [];
67
- }
68
- const activeWeekdays = [
69
- calendar.monday === 1 ? 1 : null,
70
- calendar.tuesday === 1 ? 2 : null,
71
- calendar.wednesday === 1 ? 3 : null,
72
- calendar.thursday === 1 ? 4 : null,
73
- calendar.friday === 1 ? 5 : null,
74
- calendar.saturday === 1 ? 6 : null,
75
- calendar.sunday === 1 ? 7 : null
76
- ].filter((weekday) => weekday !== null);
77
- if (activeWeekdays.length === 0) {
78
- return [];
79
- }
80
- const activeWeekdaySet = new Set(activeWeekdays);
81
- const dates = /* @__PURE__ */ new Set();
82
- const date = moment(startDate.toString(), "YYYYMMDD");
83
- const endDateMoment = moment(endDate.toString(), "YYYYMMDD");
84
- while (date.isSameOrBefore(endDateMoment)) {
85
- const isoWeekday = date.isoWeekday();
86
- if (activeWeekdaySet.has(isoWeekday)) {
87
- dates.add(parseInt(date.format("YYYYMMDD"), 10));
88
- }
89
- date.add(1, "day");
90
- }
91
- return Array.from(dates);
92
- }
93
- function combineCalendars(calendars) {
94
- const combinedCalendar = {
95
- monday: 0,
96
- tuesday: 0,
97
- wednesday: 0,
98
- thursday: 0,
99
- friday: 0,
100
- saturday: 0,
101
- sunday: 0
102
- };
103
- for (const calendar of calendars) {
104
- for (const day of Object.keys(
105
- combinedCalendar
106
- )) {
107
- if (calendar[day] === 1) {
108
- combinedCalendar[day] = 1;
109
- }
110
- }
111
- }
112
- return combinedCalendar;
113
- }
114
- function secondsAfterMidnight(timeString) {
115
- return moment.duration(timeString).asSeconds();
116
- }
117
- function minutesAfterMidnight(timeString) {
118
- return moment.duration(timeString).asMinutes();
119
- }
120
- function updateTimeByOffset(timeString, offsetSeconds) {
121
- const newTime = fromGTFSTime(timeString);
122
- return toGTFSTime(newTime.add(offsetSeconds, "seconds"));
123
- }
124
-
125
- // src/lib/utils.ts
126
- import {
127
- cloneDeep,
128
- compact,
129
- countBy,
130
- difference,
131
- entries,
132
- every as every2,
133
- find,
134
- findLast,
135
- first,
136
- flatMap,
137
- flow,
138
- groupBy,
139
- head,
140
- last,
141
- maxBy,
142
- orderBy,
143
- partialRight,
144
- reduce,
145
- size,
146
- some,
147
- sortBy,
148
- uniq,
149
- uniqBy as uniqBy2,
150
- zip
151
- } from "lodash-es";
152
- import {
153
- getCalendarDates,
154
- getTrips,
155
- getTimetableNotesReferences,
156
- getTimetableNotes,
157
- getRoutes,
158
- getCalendars,
159
- getTimetableStopOrders,
160
- getStops,
161
- getStopAttributes,
162
- getStoptimes,
163
- getFrequencies,
164
- getTimetables,
165
- getTimetablePages,
166
- getAgencies as getAgencies2,
167
- openDb
168
- } from "gtfs";
169
- import { stringify } from "csv-stringify";
170
- import moment2 from "moment";
171
- import sqlString from "sqlstring";
172
- import toposort from "toposort";
173
-
174
- // src/lib/file-utils.ts
175
- import { dirname, join, resolve } from "path";
176
- import cssEscape from "css.escape";
177
- import { createWriteStream } from "fs";
178
- import { fileURLToPath } from "url";
179
- import {
180
- access,
181
- cp,
182
- copyFile,
183
- mkdir,
184
- readdir,
185
- readFile,
186
- rm
187
- } from "fs/promises";
188
- import { homedir } from "os";
189
- import * as _ from "lodash-es";
190
- import { uniqBy } from "lodash-es";
191
- import { ZipArchive } from "archiver";
192
- import beautify from "js-beautify";
193
- import sanitizeHtml from "sanitize-html";
194
- import { renderFile } from "pug";
195
- import puppeteer from "puppeteer";
196
- import sanitize from "sanitize-filename";
197
- import { marked } from "marked";
198
-
199
- // src/lib/template-functions.ts
200
- var template_functions_exports = {};
201
- __export(template_functions_exports, {
202
- formatTripName: () => formatTripName,
203
- formatTripNameForCSV: () => formatTripNameForCSV,
204
- getNotesForStop: () => getNotesForStop,
205
- getNotesForStoptime: () => getNotesForStoptime,
206
- getNotesForTimetableLabel: () => getNotesForTimetableLabel,
207
- getNotesForTrip: () => getNotesForTrip,
208
- hasNotesOrNotices: () => hasNotesOrNotices,
209
- timetableHasDifferentDays: () => timetableHasDifferentDays,
210
- timetablePageHasDifferentDays: () => timetablePageHasDifferentDays,
211
- timetablePageHasDifferentLabels: () => timetablePageHasDifferentLabels
212
- });
213
- import { every } from "lodash-es";
214
- function timetableHasDifferentDays(timetable) {
215
- return !every(timetable.orderedTrips, (trip, idx) => {
216
- if (idx === 0) {
217
- return true;
218
- }
219
- return trip.dayList === timetable.orderedTrips[idx - 1].dayList;
220
- });
221
- }
222
- function timetablePageHasDifferentDays(timetablePage) {
223
- return !every(timetablePage.consolidatedTimetables, (timetable, idx) => {
224
- if (idx === 0) {
225
- return true;
226
- }
227
- return timetable.dayListLong === timetablePage.consolidatedTimetables[idx - 1].dayListLong;
228
- });
229
- }
230
- function timetablePageHasDifferentLabels(timetablePage) {
231
- return !every(timetablePage.consolidatedTimetables, (timetable, idx) => {
232
- if (idx === 0) {
233
- return true;
234
- }
235
- return timetable.timetable_label === timetablePage.consolidatedTimetables[idx - 1].timetable_label;
236
- });
237
- }
238
- function hasNotesOrNotices(timetable) {
239
- return timetable.requestPickupSymbolUsed || timetable.noPickupSymbolUsed || timetable.requestDropoffSymbolUsed || timetable.noDropoffSymbolUsed || timetable.noServiceSymbolUsed || timetable.interpolatedStopSymbolUsed || timetable.notes.length > 0;
240
- }
241
- function getNotesForTimetableLabel(notes) {
242
- return notes.filter((note) => !note.stop_id && !note.trip_id);
243
- }
244
- function getNotesForStop(notes, stop) {
245
- return notes.filter((note) => {
246
- if (note.trip_id) {
247
- return false;
248
- }
249
- if (note.stop_sequence && !stop.trips.some((trip) => trip.stop_sequence === note.stop_sequence)) {
250
- return false;
251
- }
252
- return note.stop_id === stop.stop_id;
253
- });
254
- }
255
- function getNotesForTrip(notes, trip) {
256
- return notes.filter((note) => {
257
- if (note.stop_id) {
258
- return false;
259
- }
260
- return note.trip_id === trip.trip_id;
261
- });
262
- }
263
- function getNotesForStoptime(notes, stoptime) {
264
- return notes.filter((note) => {
265
- if (!note.trip_id && note.stop_id === stoptime.stop_id && note.show_on_stoptime === 1) {
266
- return true;
267
- }
268
- if (!note.stop_id && note.trip_id === stoptime.trip_id && note.show_on_stoptime === 1) {
269
- return true;
270
- }
271
- return note.trip_id === stoptime.trip_id && note.stop_id === stoptime.stop_id;
272
- });
273
- }
274
- function formatTripName(trip, index, timetable) {
275
- let tripName;
276
- if (timetable.routes.length > 1) {
277
- tripName = trip.route_short_name;
278
- } else if (timetable.orientation === "horizontal") {
279
- if (trip.trip_short_name) {
280
- tripName = trip.trip_short_name;
281
- } else {
282
- tripName = `Run #${index + 1}`;
283
- }
284
- }
285
- if (timetableHasDifferentDays(timetable)) {
286
- tripName += ` ${trip.dayList}`;
287
- }
288
- return tripName;
289
- }
290
- function formatTripNameForCSV(trip, timetable) {
291
- let tripName = "";
292
- if (timetable.routes.length > 1) {
293
- tripName += `${trip.route_short_name} - `;
294
- }
295
- if (trip.trip_short_name) {
296
- tripName += trip.trip_short_name;
297
- } else {
298
- tripName += trip.trip_id;
299
- }
300
- if (trip.trip_headsign) {
301
- tripName += ` - ${trip.trip_headsign}`;
302
- }
303
- if (timetableHasDifferentDays(timetable)) {
304
- tripName += ` - ${trip.dayList}`;
305
- }
306
- return tripName;
307
- }
308
-
309
- // src/lib/errors.ts
310
- import { GtfsErrorCategory, isGtfsError } from "gtfs";
311
- var GtfsToHtmlError = class extends Error {
312
- code;
313
- category;
314
- isOperational;
315
- details;
316
- constructor(message, options) {
317
- super(message, { cause: options.cause });
318
- this.name = "GtfsToHtmlError";
319
- this.code = options.code;
320
- this.category = options.category;
321
- this.isOperational = options.isOperational ?? true;
322
- this.details = options.details;
323
- }
324
- };
325
- function isGtfsToHtmlError(error) {
326
- if (!error || typeof error !== "object") {
327
- return false;
328
- }
329
- const candidate = error;
330
- return candidate.name === "GtfsToHtmlError" && typeof candidate.message === "string" && typeof candidate.code === "string" && typeof candidate.category === "string" && typeof candidate.isOperational === "boolean";
331
- }
332
-
333
- // src/lib/file-utils.ts
334
- var homeDirectory = homedir();
335
- function getPathToThisModuleFolder() {
336
- const __dirname = dirname(fileURLToPath(import.meta.url));
337
- let distFolderPath;
338
- if (__dirname.endsWith("/dist/bin") || __dirname.endsWith("/dist/app")) {
339
- distFolderPath = resolve(__dirname, "../../");
340
- } else if (__dirname.endsWith("/dist")) {
341
- distFolderPath = resolve(__dirname, "../");
342
- } else {
343
- distFolderPath = resolve(__dirname, "../../");
344
- }
345
- return distFolderPath;
346
- }
347
- function getPathToViewsFolder(config2) {
348
- if (config2.templatePath) {
349
- return untildify(config2.templatePath);
350
- }
351
- return join(getPathToThisModuleFolder(), "views/default");
352
- }
353
- function getPathToTemplateFile(templateFileName, config2) {
354
- const fullTemplateFileName = config2.noHead !== true ? `${templateFileName}_full.pug` : `${templateFileName}.pug`;
355
- return join(getPathToViewsFolder(config2), fullTemplateFileName);
356
- }
357
- function generateTimetablePageFileName(timetablePage, config2) {
358
- if (timetablePage.filename) {
359
- return sanitize(timetablePage.filename);
360
- }
361
- if (config2.groupTimetablesIntoPages === true && uniqBy(timetablePage.timetables, "route_id").length === 1) {
362
- const route = timetablePage.timetables[0].routes[0];
363
- return sanitize(`${formatRouteNameForFilename(route).toLowerCase()}.html`);
364
- }
365
- const timetable = timetablePage.timetables[0];
366
- if (timetable.timetable_id) {
367
- return sanitize(
368
- `${timetable.timetable_id.replace(/\|/g, "_").toLowerCase()}.html`
369
- );
370
- }
371
- let filename = "";
372
- for (const route of timetable.routes) {
373
- filename += `_${formatRouteNameForFilename(route)}`;
374
- }
375
- if (!isNullOrEmpty(timetable.direction_id)) {
376
- filename += `_${timetable.direction_id}`;
377
- }
378
- filename += `_${formatDays(timetable, config2).replace(/\s/g, "")}.html`;
379
- return sanitize(filename.toLowerCase());
380
- }
381
- async function renderTemplate(templateFileName, templateVars, config2) {
382
- const templatePath = getPathToTemplateFile(templateFileName, config2);
383
- const html = await renderFile(templatePath, {
384
- _,
385
- cssEscape,
386
- md: (text) => sanitizeHtml(marked.parseInline(text)),
387
- ...template_functions_exports,
388
- formatRouteColor,
389
- formatRouteTextColor,
390
- ...templateVars
391
- });
392
- if (config2.beautify === true) {
393
- return beautify.html_beautify(html, {
394
- indent_size: 2
395
- });
396
- }
397
- return html;
398
- }
399
- function untildify(pathWithTilde) {
400
- return homeDirectory ? pathWithTilde.replace(/^~(?=$|\/|\\)/, homeDirectory) : pathWithTilde;
401
- }
402
-
403
- // src/lib/geojson-utils.ts
404
- import { getShapesAsGeoJSON, getStopsAsGeoJSON } from "gtfs";
405
- import simplify from "@turf/simplify";
406
- import { featureCollection, round } from "@turf/helpers";
407
-
408
- // src/lib/log-utils.ts
409
- import { clearLine, cursorTo } from "readline";
410
- import { noop } from "lodash-es";
411
- import * as colors from "yoctocolors";
412
- import { getAgencies, getFeedInfo, isGtfsError as isGtfsError2, formatGtfsError } from "gtfs";
413
- import Table from "cli-table";
414
- function logWarning(config2) {
415
- if (config2.logFunction) {
416
- return config2.logFunction;
417
- }
418
- return (text) => {
419
- process.stdout.write(`
420
- ${formatWarning(text)}
421
- `);
422
- };
423
- }
424
- function formatWarning(text) {
425
- const warningMessage = `${colors.underline("Warning")}: ${text}`;
426
- return colors.yellow(warningMessage);
427
- }
428
-
429
- // src/lib/trip-id-utils.ts
430
- var getBaseTripId = (tripId) => tripId.replace(/_freq_\d+$/, "");
431
- var getBaseTripIds = (trips) => Array.from(new Set(trips.map((trip) => getBaseTripId(trip.trip_id))));
432
-
433
- // src/lib/geojson-utils.ts
434
- var mergeGeojson = (...geojsons) => featureCollection(geojsons.flatMap((geojson) => geojson.features));
435
- var truncateGeoJSONDecimals = (geojson, config2) => {
436
- for (const feature of geojson.features) {
437
- if (feature.geometry.coordinates) {
438
- if (feature.geometry.type.toLowerCase() === "point") {
439
- feature.geometry.coordinates = feature.geometry.coordinates.map(
440
- (number) => round(number, config2.coordinatePrecision)
441
- );
442
- } else if (feature.geometry.type.toLowerCase() === "linestring") {
443
- feature.geometry.coordinates = feature.geometry.coordinates.map(
444
- (coordinate) => coordinate.map(
445
- (number) => round(number, config2.coordinatePrecision)
446
- )
447
- );
448
- } else if (feature.geometry.type.toLowerCase() === "multilinestring") {
449
- feature.geometry.coordinates = feature.geometry.coordinates.map(
450
- (linestring) => linestring.map(
451
- (coordinate) => coordinate.map(
452
- (number) => round(number, config2.coordinatePrecision)
453
- )
454
- )
455
- );
456
- }
457
- }
458
- }
459
- return geojson;
460
- };
461
- function getTimetableGeoJSON(timetable, config2) {
462
- const tripIds = getBaseTripIds(timetable.orderedTrips);
463
- const shapesGeojsons = timetable.route_ids.map(
464
- (routeId) => getShapesAsGeoJSON({
465
- route_id: routeId,
466
- direction_id: timetable.direction_id,
467
- trip_id: tripIds
468
- })
469
- );
470
- const stopsGeojsons = timetable.route_ids.map(
471
- (routeId) => getStopsAsGeoJSON({
472
- route_id: routeId,
473
- direction_id: timetable.direction_id,
474
- trip_id: tripIds
475
- })
476
- );
477
- const geojson = mergeGeojson(...shapesGeojsons, ...stopsGeojsons);
478
- let simplifiedGeojson;
479
- try {
480
- simplifiedGeojson = simplify(geojson, {
481
- tolerance: 1 / 10 ** config2.coordinatePrecision,
482
- highQuality: true
483
- });
484
- } catch {
485
- timetable.warnings.push(
486
- `Timetable ${timetable.timetable_id} - Unable to simplify geojson`
487
- );
488
- simplifiedGeojson = geojson;
489
- }
490
- return truncateGeoJSONDecimals(simplifiedGeojson, config2);
491
- }
492
- function getAgencyGeoJSON(config2) {
493
- const shapesGeojsons = getShapesAsGeoJSON();
494
- const stopsGeojsons = getStopsAsGeoJSON();
495
- const geojson = mergeGeojson(shapesGeojsons, stopsGeojsons);
496
- let simplifiedGeojson;
497
- try {
498
- simplifiedGeojson = simplify(geojson, {
499
- tolerance: 1 / 10 ** config2.coordinatePrecision,
500
- highQuality: true
501
- });
502
- } catch {
503
- logWarning(config2)("Unable to simplify geojson");
504
- simplifiedGeojson = geojson;
505
- }
506
- return truncateGeoJSONDecimals(simplifiedGeojson, config2);
507
- }
508
-
509
- // package.json
510
- var package_default = {
511
- name: "gtfs-to-html",
512
- version: "2.12.11",
513
- private: false,
514
- description: "Build human readable transit timetables as HTML, PDF or CSV from GTFS",
515
- keywords: [
516
- "transit",
517
- "gtfs",
518
- "gtfs-realtime",
519
- "transportation",
520
- "timetables"
521
- ],
522
- homepage: "https://gtfstohtml.com",
523
- bugs: {
524
- url: "https://github.com/blinktaginc/gtfs-to-html/issues"
525
- },
526
- repository: "git://github.com/blinktaginc/gtfs-to-html",
527
- license: "MIT",
528
- author: "Brendan Nee <brendan@blinktag.com>",
529
- contributors: [
530
- "Evan Siroky <evan.siroky@yahoo.com>",
531
- "Nathan Selikoff",
532
- "Aaron Antrim <aaron@trilliumtransit.com>",
533
- "Thomas Craig <thomas@trilliumtransit.com>",
534
- "Holly Kvalheim",
535
- "Pawajoro",
536
- "Andrea Mignone",
537
- "Evo Stamatov",
538
- "Sebastian Knopf"
539
- ],
540
- type: "module",
541
- main: "./dist/index.js",
542
- types: "./dist/index.d.ts",
543
- files: [
544
- "dist",
545
- "docker",
546
- "examples",
547
- "scripts",
548
- "views/default",
549
- "config-sample.json"
550
- ],
551
- bin: {
552
- "gtfs-to-html": "dist/bin/gtfs-to-html.js"
553
- },
554
- scripts: {
555
- build: "tsup && node scripts/copy-browser-assets.js",
556
- start: "node ./dist/app",
557
- prepare: "husky && pnpm run build",
558
- prepack: "husky && pnpm run build"
559
- },
560
- dependencies: {
561
- "@turf/helpers": "^7.3.5",
562
- "@turf/simplify": "^7.3.5",
563
- archiver: "^8.0.0",
564
- "cli-table": "^0.3.11",
565
- "css.escape": "^1.5.1",
566
- "csv-stringify": "^6.7.0",
567
- express: "^5.2.1",
568
- gtfs: "^4.18.6",
569
- "js-beautify": "^1.15.4",
570
- "lodash-es": "^4.18.1",
571
- marked: "^18.0.4",
572
- moment: "^2.30.1",
573
- "pretty-error": "^4.0.0",
574
- pug: "^3.0.4",
575
- puppeteer: "^25.0.4",
576
- "sanitize-filename": "^1.6.4",
577
- "sanitize-html": "^2.17.4",
578
- sqlstring: "^2.3.3",
579
- toposort: "^2.0.2",
580
- yargs: "^18.0.0",
581
- yoctocolors: "^2.1.2"
582
- },
583
- devDependencies: {
584
- "@maplibre/maplibre-gl-geocoder": "^1.9.4",
585
- "@types/archiver": "^7.0.0",
586
- "@types/cli-table": "^0.3.4",
587
- "@types/express": "^5.0.6",
588
- "@types/js-beautify": "^1.14.3",
589
- "@types/lodash-es": "^4.17.12",
590
- "@types/node": "^25",
591
- "@types/pug": "^2.0.10",
592
- "@types/sanitize-html": "^2.16.1",
593
- "@types/sqlstring": "^2.3.2",
594
- "@types/toposort": "^2.0.7",
595
- "@types/yargs": "^17.0.35",
596
- anchorme: "^3.0.8",
597
- "gtfs-realtime-pbf-js-module": "^1.0.0",
598
- husky: "^9.1.7",
599
- "lint-staged": "^17.0.5",
600
- "maplibre-gl": "^5.24.0",
601
- pbf: "^4.0.2",
602
- prettier: "^3.8.3",
603
- tsup: "^8.5.1",
604
- typescript: "^6.0.3"
605
- },
606
- engines: {
607
- node: ">= 22"
608
- },
609
- packageManager: "pnpm@11.3.0",
610
- "release-it": {
611
- github: {
612
- release: true
613
- },
614
- plugins: {
615
- "@release-it/keep-a-changelog": {
616
- filename: "CHANGELOG.md"
617
- }
618
- },
619
- hooks: {
620
- "after:bump": "pnpm run build"
621
- }
622
- },
623
- prettier: {
624
- singleQuote: true
625
- },
626
- "lint-staged": {
627
- "*.{js,ts,json}": "prettier --write"
628
- }
629
- };
630
-
631
- // src/lib/utils.ts
632
- var { version } = package_default;
633
- var isTimepoint = (stoptime) => {
634
- if (isNullOrEmpty(stoptime.timepoint)) {
635
- return !isNullOrEmpty(stoptime.arrival_time) && !isNullOrEmpty(stoptime.departure_time);
636
- }
637
- return stoptime.timepoint === 1;
638
- };
639
- var getLongestTripStoptimes = (trips, config2) => {
640
- const filteredTripStoptimes = trips.map(
641
- (trip) => trip.stoptimes.filter((stoptime) => {
642
- if (config2.showOnlyTimepoint === true) {
643
- return isTimepoint(stoptime);
644
- }
645
- return true;
646
- })
647
- );
648
- return maxBy(filteredTripStoptimes, (stoptimes) => size(stoptimes));
649
- };
650
- var findCommonStopId = (trips, config2) => {
651
- const longestTripStoptimes = getLongestTripStoptimes(trips, config2);
652
- if (!longestTripStoptimes) {
653
- return null;
654
- }
655
- const commonStoptime = longestTripStoptimes.find((stoptime, idx) => {
656
- if (idx === 0 && stoptime.stop_id === last(longestTripStoptimes)?.stop_id) {
657
- return false;
658
- }
659
- if (isNullOrEmpty(stoptime.arrival_time)) {
660
- return false;
661
- }
662
- return every2(
663
- trips,
664
- (trip) => trip.stoptimes.find(
665
- (tripStoptime) => tripStoptime.stop_id === stoptime.stop_id && tripStoptime.arrival_time !== null
666
- )
667
- );
668
- });
669
- return commonStoptime ? commonStoptime.stop_id : null;
670
- };
671
- var deduplicateTrips = (trips) => {
672
- if (trips.length <= 1) {
673
- return trips;
674
- }
675
- const uniqueTrips = /* @__PURE__ */ new Map();
676
- for (const trip of trips) {
677
- const tripSignature = trip.stoptimes.map(
678
- (stoptime) => `${stoptime.stop_id}|${stoptime.departure_time}|${stoptime.arrival_time}`
679
- ).join("|");
680
- if (!uniqueTrips.has(tripSignature)) {
681
- uniqueTrips.set(tripSignature, trip);
682
- } else {
683
- const existingTrip = uniqueTrips.get(tripSignature);
684
- if (!existingTrip) {
685
- continue;
686
- }
687
- if (!existingTrip.additional_service_ids) {
688
- existingTrip.additional_service_ids = [];
689
- }
690
- existingTrip.additional_service_ids.push(trip.service_id);
691
- uniqueTrips.set(tripSignature, existingTrip);
692
- }
693
- }
694
- return Array.from(uniqueTrips.values());
695
- };
696
- var sortTrips = (trips, config2) => {
697
- let sortedTrips;
698
- let commonStopId;
699
- if (config2.sortingAlgorithm === "common") {
700
- commonStopId = findCommonStopId(trips, config2);
701
- if (commonStopId) {
702
- sortedTrips = sortTripsByStoptimeAtStop(trips, commonStopId);
703
- } else {
704
- sortedTrips = sortTrips(trips, {
705
- ...config2,
706
- sortingAlgorithm: "beginning"
707
- });
708
- }
709
- } else if (config2.sortingAlgorithm === "beginning") {
710
- for (const trip of trips) {
711
- if (trip.stoptimes.length === 0) {
712
- continue;
713
- }
714
- trip.firstStoptime = timeToSeconds(trip.stoptimes[0].departure_time);
715
- trip.lastStoptime = timeToSeconds(
716
- trip.stoptimes[trip.stoptimes.length - 1].departure_time
717
- );
718
- }
719
- sortedTrips = sortBy(trips, ["firstStoptime", "lastStoptime"]);
720
- } else if (config2.sortingAlgorithm === "end") {
721
- for (const trip of trips) {
722
- if (trip.stoptimes.length === 0) {
723
- continue;
724
- }
725
- trip.firstStoptime = timeToSeconds(trip.stoptimes[0].departure_time);
726
- trip.lastStoptime = timeToSeconds(
727
- trip.stoptimes[trip.stoptimes.length - 1].departure_time
728
- );
729
- }
730
- sortedTrips = sortBy(trips, ["lastStoptime", "firstStoptime"]);
731
- } else if (config2.sortingAlgorithm === "first") {
732
- const longestTripStoptimes = getLongestTripStoptimes(trips, config2);
733
- const firstStopId = first(longestTripStoptimes).stop_id;
734
- sortedTrips = sortTripsByStoptimeAtStop(trips, firstStopId);
735
- } else if (config2.sortingAlgorithm === "last") {
736
- const longestTripStoptimes = getLongestTripStoptimes(trips, config2);
737
- const lastStopId = last(longestTripStoptimes).stop_id;
738
- sortedTrips = sortTripsByStoptimeAtStop(trips, lastStopId);
739
- }
740
- return sortedTrips ?? [];
741
- };
742
- var sortTripsByStoptimeAtStop = (trips, stopId) => sortBy(trips, (trip) => {
743
- const stoptime = find(trip.stoptimes, { stop_id: stopId });
744
- return stoptime ? timeToSeconds(stoptime.departure_time) : void 0;
745
- });
746
- var getCalendarDatesForTimetable = (timetable, config2) => {
747
- const calendarDates = getCalendarDates(
748
- {
749
- service_id: timetable.service_ids
750
- },
751
- [],
752
- [["date", "ASC"]]
753
- );
754
- const start = moment2(timetable.start_date, "YYYYMMDD");
755
- const end = moment2(timetable.end_date, "YYYYMMDD");
756
- const excludedDates = /* @__PURE__ */ new Set();
757
- const includedDates = /* @__PURE__ */ new Set();
758
- for (const calendarDate of calendarDates) {
759
- if (moment2(calendarDate.date, "YYYYMMDD").isBetween(
760
- start,
761
- end,
762
- void 0,
763
- "[]"
764
- )) {
765
- if (calendarDate.exception_type === 1) {
766
- includedDates.add(formatDate(calendarDate, config2.dateFormat));
767
- } else if (calendarDate.exception_type === 2) {
768
- excludedDates.add(formatDate(calendarDate, config2.dateFormat));
769
- }
770
- }
771
- }
772
- const includedAndExcludedDates = new Set(
773
- [...excludedDates].filter((date) => includedDates.has(date))
774
- );
775
- return {
776
- excludedDates: [...excludedDates].filter(
777
- (date) => !includedAndExcludedDates.has(date)
778
- ),
779
- includedDates: [...includedDates].filter(
780
- (date) => !includedAndExcludedDates.has(date)
781
- )
782
- };
783
- };
784
- var getDaysFromCalendars = (calendars) => {
785
- const days2 = {
786
- monday: 0,
787
- tuesday: 0,
788
- wednesday: 0,
789
- thursday: 0,
790
- friday: 0,
791
- saturday: 0,
792
- sunday: 0
793
- };
794
- for (const calendar of calendars) {
795
- for (const day of Object.keys(days2)) {
796
- days2[day] = days2[day] | calendar[day];
797
- }
798
- }
799
- return days2;
800
- };
801
- var getDirectionHeadsignFromTimetable = (timetable) => {
802
- const trips = getTrips(
803
- {
804
- direction_id: timetable.direction_id,
805
- route_id: timetable.route_ids
806
- },
807
- ["trip_headsign"]
808
- );
809
- if (trips.length === 0) {
810
- return "";
811
- }
812
- const mostCommonHeadsign = flow(
813
- countBy,
814
- entries,
815
- partialRight(maxBy, last),
816
- head
817
- )(compact(trips.map((trip) => trip.trip_headsign)));
818
- return mostCommonHeadsign;
819
- };
820
- var getTimetableNotesForTimetable = (timetable, config2) => {
821
- const noteReferences = [
822
- // Get all notes for this timetable.
823
- ...getTimetableNotesReferences({
824
- timetable_id: timetable.timetable_id
825
- }),
826
- // Get all notes for this route.
827
- ...getTimetableNotesReferences({
828
- route_id: timetable.routes.map((route) => route.route_id),
829
- timetable_id: null
830
- }),
831
- // Get all notes for all trips in this timetable.
832
- ...getTimetableNotesReferences({
833
- trip_id: getBaseTripIds(timetable.orderedTrips)
834
- }),
835
- // Get all notes for all stops in this timetable.
836
- ...getTimetableNotesReferences({
837
- stop_id: timetable.stops.map((stop) => stop.stop_id),
838
- trip_id: null,
839
- route_id: null,
840
- timetable_id: null
841
- })
842
- ];
843
- const usedNoteReferences = [];
844
- for (const noteReference of noteReferences) {
845
- if (noteReference.stop_sequence === "" || noteReference.stop_sequence === null) {
846
- usedNoteReferences.push(noteReference);
847
- continue;
848
- }
849
- if (noteReference.stop_id === "" || noteReference.stop_id === null) {
850
- timetable.warnings.push(
851
- `Timetable Note Reference for note_id=${noteReference.note_id} has a \`stop_sequence\` but no \`stop_id\` - ignoring`
852
- );
853
- continue;
854
- }
855
- const stop = timetable.stops.find(
856
- (stop2) => stop2.stop_id === noteReference.stop_id
857
- );
858
- if (!stop) {
859
- continue;
860
- }
861
- const tripWithMatchingStopSequence = stop.trips.find(
862
- (trip) => trip.stop_sequence === noteReference.stop_sequence
863
- );
864
- if (tripWithMatchingStopSequence) {
865
- usedNoteReferences.push(noteReference);
866
- }
867
- }
868
- const notes = getTimetableNotes({
869
- note_id: usedNoteReferences.map((noteReference) => noteReference.note_id)
870
- });
871
- const symbols = "abcdefghijklmnopqrstuvwxyz".split("");
872
- let symbolIndex = 0;
873
- for (const note of notes) {
874
- if (note.symbol === "" || note.symbol === null) {
875
- note.symbol = symbolIndex < symbols.length - 1 ? symbols[symbolIndex] : symbolIndex - symbols.length;
876
- symbolIndex += 1;
877
- }
878
- }
879
- const formattedNotes = usedNoteReferences.map((noteReference) => ({
880
- ...noteReference,
881
- ...notes.find((note) => note.note_id === noteReference.note_id)
882
- }));
883
- return sortBy(formattedNotes, "symbol");
884
- };
885
- var createTimetablePage = ({
886
- timetablePageId,
887
- timetables,
888
- config: config2
889
- }) => {
890
- const updatedTimetables = timetables.map((timetable) => {
891
- if (!timetable.routes) {
892
- timetable.routes = getRoutes({
893
- route_id: timetable.route_ids
894
- });
895
- }
896
- return timetable;
897
- });
898
- const timetablePage = {
899
- timetable_page_id: timetablePageId,
900
- timetables: updatedTimetables,
901
- routes: updatedTimetables.flatMap((timetable) => timetable.routes)
902
- };
903
- const filename = generateTimetablePageFileName(timetablePage, config2);
904
- return {
905
- ...timetablePage,
906
- filename
907
- };
908
- };
909
- var createTimetable = ({
910
- route,
911
- directionId,
912
- tripHeadsign,
913
- calendars,
914
- calendarDates
915
- }) => {
916
- const serviceIds = uniq([
917
- ...calendars?.map((calendar) => calendar.service_id) ?? [],
918
- ...calendarDates?.map((calendarDate) => calendarDate.service_id) ?? []
919
- ]);
920
- const days2 = {
921
- monday: null,
922
- tuesday: null,
923
- wednesday: null,
924
- thursday: null,
925
- friday: null,
926
- saturday: null,
927
- sunday: null
928
- };
929
- let startDate = null;
930
- let endDate = null;
931
- if (calendars && calendars.length > 0) {
932
- Object.assign(days2, getDaysFromCalendars(calendars));
933
- startDate = parseInt(
934
- moment2.min(
935
- calendars.map((calendar) => moment2(calendar.start_date, "YYYYMMDD"))
936
- ).format("YYYYMMDD"),
937
- 10
938
- );
939
- endDate = parseInt(
940
- moment2.max(calendars.map((calendar) => moment2(calendar.end_date, "YYYYMMDD"))).format("YYYYMMDD"),
941
- 10
942
- );
943
- }
944
- const timetableId = formatTimetableId({
945
- routeIds: [route.route_id],
946
- directionId,
947
- days: days2,
948
- dates: calendarDates?.map((calendarDate) => calendarDate.date)
949
- });
950
- return {
951
- timetable_id: timetableId,
952
- route_ids: [route.route_id],
953
- direction_id: directionId === null ? null : directionId,
954
- direction_name: tripHeadsign === null ? null : tripHeadsign,
955
- routes: [route],
956
- include_exceptions: calendarDates && calendarDates.length > 0 ? 1 : 0,
957
- service_ids: serviceIds,
958
- service_notes: null,
959
- timetable_label: null,
960
- start_time: null,
961
- end_time: null,
962
- orientation: null,
963
- timetable_sequence: null,
964
- show_trip_continuation: null,
965
- start_date: startDate,
966
- end_date: endDate,
967
- ...days2
968
- };
969
- };
970
- var convertRoutesToTimetablePages = (config2) => {
971
- const routes = getRoutes();
972
- const timetablePages = [];
973
- const { calendars, calendarDates } = getCalendarsFromConfig(config2);
974
- for (const route of routes) {
975
- const trips = getTrips(
976
- {
977
- route_id: route.route_id
978
- },
979
- ["trip_headsign", "direction_id", "trip_id", "service_id"]
980
- );
981
- const uniqueTripDirections = orderBy(
982
- uniqBy2(trips, (trip) => trip.direction_id),
983
- "direction_id"
984
- );
985
- const sortedCalendars = orderBy(calendars, calendarToCalendarCode, "desc");
986
- const calendarGroups = groupBy(sortedCalendars, calendarToCalendarCode);
987
- const calendarDateGroups = groupBy(calendarDates, "service_id");
988
- const timetables = [];
989
- for (const uniqueTripDirection of uniqueTripDirections) {
990
- for (const calendars2 of Object.values(calendarGroups)) {
991
- const tripsForCalendars = trips.filter(
992
- (trip) => some(calendars2, { service_id: trip.service_id })
993
- );
994
- if (tripsForCalendars.length > 0) {
995
- timetables.push(
996
- createTimetable({
997
- route,
998
- directionId: uniqueTripDirection.direction_id,
999
- tripHeadsign: uniqueTripDirection.trip_headsign,
1000
- calendars: calendars2
1001
- })
1002
- );
1003
- }
1004
- }
1005
- for (const calendarDates2 of Object.values(calendarDateGroups)) {
1006
- const tripsForCalendarDates = trips.filter(
1007
- (trip) => some(calendarDates2, { service_id: trip.service_id })
1008
- );
1009
- if (tripsForCalendarDates.length > 0) {
1010
- timetables.push(
1011
- createTimetable({
1012
- route,
1013
- directionId: uniqueTripDirection.direction_id,
1014
- tripHeadsign: uniqueTripDirection.trip_headsign,
1015
- calendarDates: calendarDates2
1016
- })
1017
- );
1018
- }
1019
- }
1020
- }
1021
- if (timetables.length === 0) {
1022
- continue;
1023
- }
1024
- if (config2.groupTimetablesIntoPages === true) {
1025
- timetablePages.push(
1026
- createTimetablePage({
1027
- timetablePageId: `route_${route.route_id}`,
1028
- timetables,
1029
- config: config2
1030
- })
1031
- );
1032
- } else {
1033
- for (const timetable of timetables) {
1034
- timetablePages.push(
1035
- createTimetablePage({
1036
- timetablePageId: timetable.timetable_id,
1037
- timetables: [timetable],
1038
- config: config2
1039
- })
1040
- );
1041
- }
1042
- }
1043
- }
1044
- return timetablePages;
1045
- };
1046
- var generateTripsByFrequencies = (trip, frequencies, config2) => {
1047
- const formattedFrequencies = frequencies.map(
1048
- (frequency) => formatFrequency(frequency, config2)
1049
- );
1050
- const resetTrip = resetStoptimesToMidnight(trip);
1051
- const trips = [];
1052
- for (const frequency of formattedFrequencies) {
1053
- const startSeconds = secondsAfterMidnight(frequency.start_time);
1054
- const endSeconds = secondsAfterMidnight(frequency.end_time);
1055
- for (let offset = startSeconds; offset < endSeconds; offset += frequency.headway_secs) {
1056
- const newTrip = cloneDeep(resetTrip);
1057
- trips.push({
1058
- ...newTrip,
1059
- trip_id: `${resetTrip.trip_id}_freq_${trips.length}`,
1060
- stoptimes: updateStoptimesByOffset(newTrip, offset)
1061
- });
1062
- }
1063
- }
1064
- return trips;
1065
- };
1066
- var duplicateStopsForDifferentArrivalDeparture = (stopIds, timetable, config2) => {
1067
- if (config2.showArrivalOnDifference === null || config2.showArrivalOnDifference === void 0) {
1068
- return stopIds;
1069
- }
1070
- for (const trip of timetable.orderedTrips) {
1071
- for (const stoptime of trip.stoptimes) {
1072
- const timepointDifference = fromGTFSTime(stoptime.departure_time).diff(
1073
- fromGTFSTime(stoptime.arrival_time),
1074
- "minutes"
1075
- );
1076
- if (timepointDifference < config2.showArrivalOnDifference) {
1077
- continue;
1078
- }
1079
- const index = stopIds.indexOf(stoptime.stop_id);
1080
- if (index === 0 || index === stopIds.length - 1) {
1081
- continue;
1082
- }
1083
- if (stoptime.stop_id === stopIds[index + 1] || stoptime.stop_id === stopIds[index - 1]) {
1084
- continue;
1085
- }
1086
- stopIds.splice(index, 0, stoptime.stop_id);
1087
- }
1088
- }
1089
- return stopIds;
1090
- };
1091
- var getStopOrder = (timetable, config2) => {
1092
- const timetableStopOrders = getTimetableStopOrders(
1093
- {
1094
- timetable_id: timetable.timetable_id
1095
- },
1096
- ["stop_id"],
1097
- [["stop_sequence", "ASC"]]
1098
- );
1099
- if (timetableStopOrders.length > 0) {
1100
- return timetableStopOrders.map(
1101
- (timetableStopOrder) => timetableStopOrder.stop_id
1102
- );
1103
- }
1104
- try {
1105
- const stopGraph = [];
1106
- const timepointStopIds = new Set(
1107
- timetable.orderedTrips.flatMap(
1108
- (trip) => trip.stoptimes.filter((stoptime) => isTimepoint(stoptime)).map((stoptime) => stoptime.stop_id)
1109
- )
1110
- );
1111
- for (const trip of timetable.orderedTrips) {
1112
- const sortedStopIds = trip.stoptimes.filter((stoptime) => {
1113
- if (config2.showOnlyTimepoint === true) {
1114
- return timepointStopIds.has(stoptime.stop_id);
1115
- }
1116
- return true;
1117
- }).map((stoptime) => stoptime.stop_id);
1118
- for (const [index, stopId] of sortedStopIds.entries()) {
1119
- if (index === sortedStopIds.length - 1) {
1120
- continue;
1121
- }
1122
- stopGraph.push([stopId, sortedStopIds[index + 1]]);
1123
- }
1124
- }
1125
- if (stopGraph.length === 0 && config2.showOnlyTimepoint === true) {
1126
- timetable.warnings.push(
1127
- `Timetable ${timetable.timetable_id}'s trips have stoptimes with timepoints but \`showOnlyTimepoint\` is true. Try setting \`showOnlyTimepoint\` to false.`
1128
- );
1129
- }
1130
- const stopIds = toposort(stopGraph);
1131
- return duplicateStopsForDifferentArrivalDeparture(
1132
- stopIds,
1133
- timetable,
1134
- config2
1135
- );
1136
- } catch {
1137
- const longestTripStoptimes = getLongestTripStoptimes(
1138
- timetable.orderedTrips,
1139
- config2
1140
- );
1141
- const stopIds = longestTripStoptimes.map(
1142
- (stoptime) => stoptime.stop_id
1143
- );
1144
- const missingStopIds = difference(
1145
- new Set(
1146
- timetable.orderedTrips.flatMap(
1147
- (trip) => trip.stoptimes.map((stoptime) => stoptime.stop_id)
1148
- )
1149
- ),
1150
- new Set(stopIds)
1151
- );
1152
- if (missingStopIds.length > 0) {
1153
- timetable.warnings.push(
1154
- `Timetable ${timetable.timetable_id} stops are unable to be topologically sorted and has no \`timetable_stop_order.txt\`. Falling back to using the using the stop order from trip with most stoptimes, but this does not include stop_ids ${formatListForDisplay(missingStopIds)}. Try manually specifying stops with \`timetable_stop_order.txt\`. Read more at https://gtfstohtml.com/docs/timetable-stop-order`
1155
- );
1156
- }
1157
- return duplicateStopsForDifferentArrivalDeparture(
1158
- stopIds,
1159
- timetable,
1160
- config2
1161
- );
1162
- }
1163
- };
1164
- var getStopsForTimetable = (timetable, config2) => {
1165
- if (timetable.orderedTrips.length === 0) {
1166
- return [];
1167
- }
1168
- const orderedStopIds = getStopOrder(timetable, config2);
1169
- const orderedStops = orderedStopIds.map((stopId, index) => {
1170
- const stops = getStops({
1171
- stop_id: stopId
1172
- });
1173
- if (stops.length === 0) {
1174
- throw new GtfsToHtmlError(
1175
- `No stop found found for stop_id=${stopId} in timetable_id=${timetable.timetable_id}`,
1176
- {
1177
- code: "GTFS_TO_HTML_QUERY_RESULT_NOT_FOUND" /* QUERY_RESULT_NOT_FOUND */,
1178
- category: "query" /* QUERY */,
1179
- details: {
1180
- entity: "stop",
1181
- stopId,
1182
- timetableId: timetable.timetable_id
1183
- }
1184
- }
1185
- );
1186
- }
1187
- const stop = {
1188
- ...stops[0],
1189
- trips: []
1190
- };
1191
- if (index < orderedStopIds.length - 1 && stopId === orderedStopIds[index + 1]) {
1192
- stop.type = "arrival";
1193
- } else if (index > 0 && stopId === orderedStopIds[index - 1]) {
1194
- stop.type = "departure";
1195
- }
1196
- return stop;
1197
- });
1198
- if (config2.showStopCity) {
1199
- const stopAttributes = getStopAttributes({
1200
- stop_id: orderedStopIds
1201
- });
1202
- for (const stopAttribute of stopAttributes) {
1203
- const stop = orderedStops.find(
1204
- (stop2) => stop2.stop_id === stopAttribute.stop_id
1205
- );
1206
- if (stop) {
1207
- stop.stop_city = stopAttribute.stop_city;
1208
- }
1209
- }
1210
- }
1211
- return orderedStops;
1212
- };
1213
- var getCalendarsFromConfig = (config2) => {
1214
- const db = openDb();
1215
- let whereClause = "";
1216
- const whereClauses = [];
1217
- if (config2.endDate) {
1218
- if (!moment2(config2.endDate).isValid()) {
1219
- throw new GtfsToHtmlError(
1220
- `Invalid endDate=${config2.endDate} in config.json`,
1221
- {
1222
- code: "GTFS_TO_HTML_CONFIG_DATE_INVALID" /* CONFIG_DATE_INVALID */,
1223
- category: "config" /* CONFIG */,
1224
- details: { field: "endDate", value: config2.endDate }
1225
- }
1226
- );
1227
- }
1228
- whereClauses.push(
1229
- `start_date <= ${sqlString.escape(moment2(config2.endDate).format("YYYYMMDD"))}`
1230
- );
1231
- }
1232
- if (config2.startDate) {
1233
- if (!moment2(config2.startDate).isValid()) {
1234
- throw new GtfsToHtmlError(
1235
- `Invalid startDate=${config2.startDate} in config.json`,
1236
- {
1237
- code: "GTFS_TO_HTML_CONFIG_DATE_INVALID" /* CONFIG_DATE_INVALID */,
1238
- category: "config" /* CONFIG */,
1239
- details: { field: "startDate", value: config2.startDate }
1240
- }
1241
- );
1242
- }
1243
- whereClauses.push(
1244
- `end_date >= ${sqlString.escape(moment2(config2.startDate).format("YYYYMMDD"))}`
1245
- );
1246
- }
1247
- if (whereClauses.length > 0) {
1248
- whereClause = `WHERE ${whereClauses.join(" AND ")}`;
1249
- }
1250
- const calendars = db.prepare(`SELECT * FROM calendar ${whereClause}`).all();
1251
- const serviceIds = calendars.map((calendar) => calendar.service_id);
1252
- const calendarDatesQuery = serviceIds.length > 0 ? `SELECT * FROM calendar_dates WHERE exception_type = 1 AND service_id NOT IN (${serviceIds.map((serviceId) => sqlString.escape(serviceId)).join(", ")})` : "SELECT * FROM calendar_dates WHERE exception_type = 1";
1253
- const calendarDates = db.prepare(calendarDatesQuery).all();
1254
- return {
1255
- calendars,
1256
- calendarDates
1257
- };
1258
- };
1259
- var getCalendarsFromTimetable = (timetable) => {
1260
- const db = openDb();
1261
- let whereClause = "";
1262
- const whereClauses = [];
1263
- if (timetable.end_date) {
1264
- if (!moment2(timetable.end_date, "YYYYMMDD", true).isValid()) {
1265
- throw new GtfsToHtmlError(
1266
- `Invalid end_date=${timetable.end_date} for timetable_id=${timetable.timetable_id}`,
1267
- {
1268
- code: "GTFS_TO_HTML_QUERY_INVALID" /* QUERY_INVALID */,
1269
- category: "validation" /* VALIDATION */,
1270
- details: {
1271
- field: "end_date",
1272
- value: timetable.end_date,
1273
- timetableId: timetable.timetable_id
1274
- }
1275
- }
1276
- );
1277
- }
1278
- whereClauses.push(`start_date <= ${sqlString.escape(timetable.end_date)}`);
1279
- }
1280
- if (timetable.start_date) {
1281
- if (!moment2(timetable.start_date, "YYYYMMDD", true).isValid()) {
1282
- throw new GtfsToHtmlError(
1283
- `Invalid start_date=${timetable.start_date} for timetable_id=${timetable.timetable_id}`,
1284
- {
1285
- code: "GTFS_TO_HTML_QUERY_INVALID" /* QUERY_INVALID */,
1286
- category: "validation" /* VALIDATION */,
1287
- details: {
1288
- field: "start_date",
1289
- value: timetable.start_date,
1290
- timetableId: timetable.timetable_id
1291
- }
1292
- }
1293
- );
1294
- }
1295
- whereClauses.push(`end_date >= ${sqlString.escape(timetable.start_date)}`);
1296
- }
1297
- const days2 = getDaysFromCalendars([timetable]);
1298
- const dayQueries = reduce(
1299
- days2,
1300
- (memo, value, key) => {
1301
- if (value === 1) {
1302
- memo.push(`${key} = 1`);
1303
- }
1304
- return memo;
1305
- },
1306
- []
1307
- );
1308
- if (dayQueries.length > 0) {
1309
- whereClauses.push(`(${dayQueries.join(" OR ")})`);
1310
- }
1311
- if (whereClauses.length > 0) {
1312
- whereClause = `WHERE ${whereClauses.join(" AND ")}`;
1313
- }
1314
- return db.prepare(`SELECT * FROM calendar ${whereClause}`).all();
1315
- };
1316
- var getCalendarDatesForDateRange = (startDate, endDate) => {
1317
- const db = openDb();
1318
- const whereClauses = [];
1319
- if (endDate) {
1320
- whereClauses.push(`date <= ${sqlString.escape(endDate)}`);
1321
- }
1322
- if (startDate) {
1323
- whereClauses.push(`date >= ${sqlString.escape(startDate)}`);
1324
- }
1325
- const whereClause = whereClauses.length > 0 ? ` WHERE ${whereClauses.join(" AND ")}` : "";
1326
- const calendarDates = db.prepare(
1327
- `SELECT service_id, date, exception_type FROM calendar_dates${whereClause}`
1328
- ).all();
1329
- return calendarDates;
1330
- };
1331
- var getAllStationStopIds = (stopId) => {
1332
- const stops = getStops({
1333
- stop_id: stopId
1334
- });
1335
- if (stops.length === 0) {
1336
- throw new GtfsToHtmlError(`No stop found for stop_id=${stopId}`, {
1337
- code: "GTFS_TO_HTML_QUERY_RESULT_NOT_FOUND" /* QUERY_RESULT_NOT_FOUND */,
1338
- category: "query" /* QUERY */,
1339
- details: { entity: "stop", stopId }
1340
- });
1341
- }
1342
- const stop = stops[0];
1343
- if (isNullOrEmpty(stop.parent_station)) {
1344
- return [stopId];
1345
- }
1346
- const stopsInParentStation = getStops(
1347
- {
1348
- parent_station: stop.parent_station
1349
- },
1350
- ["stop_id"]
1351
- );
1352
- return [
1353
- stop.parent_station,
1354
- ...stopsInParentStation.map((stop2) => stop2.stop_id)
1355
- ];
1356
- };
1357
- var getTripsWithSameBlock = (trip, timetable) => {
1358
- const trips = getTrips(
1359
- {
1360
- block_id: trip.block_id,
1361
- service_id: timetable.service_ids
1362
- },
1363
- ["trip_id", "route_id"]
1364
- );
1365
- for (const blockTrip of trips) {
1366
- const stopTimes = getStoptimes(
1367
- {
1368
- trip_id: blockTrip.trip_id
1369
- },
1370
- [],
1371
- [["stop_sequence", "ASC"]]
1372
- );
1373
- if (stopTimes.length === 0) {
1374
- throw new GtfsToHtmlError(
1375
- `No stoptimes found found for trip_id=${blockTrip.trip_id}`,
1376
- {
1377
- code: "GTFS_TO_HTML_QUERY_RESULT_NOT_FOUND" /* QUERY_RESULT_NOT_FOUND */,
1378
- category: "query" /* QUERY */,
1379
- details: { entity: "stoptime", tripId: blockTrip.trip_id }
1380
- }
1381
- );
1382
- }
1383
- blockTrip.firstStoptime = first(stopTimes);
1384
- blockTrip.lastStoptime = last(stopTimes);
1385
- }
1386
- return sortBy(trips, (trip2) => trip2.firstStoptime.departure_timestamp);
1387
- };
1388
- var addTripContinuation = (trip, timetable) => {
1389
- if (!trip.block_id || trip.stoptimes.length === 0) {
1390
- return;
1391
- }
1392
- const maxContinuesAsWaitingTimeSeconds = 60 * 60;
1393
- const firstStoptime = first(trip.stoptimes);
1394
- const firstStopIds = getAllStationStopIds(firstStoptime.stop_id);
1395
- const lastStoptime = last(trip.stoptimes);
1396
- const lastStopIds = getAllStationStopIds(lastStoptime.stop_id);
1397
- const blockTrips = getTripsWithSameBlock(trip, timetable);
1398
- const previousTrip = findLast(
1399
- blockTrips,
1400
- (blockTrip) => blockTrip.lastStoptime.arrival_timestamp <= firstStoptime.departure_timestamp
1401
- );
1402
- if (previousTrip && previousTrip.route_id !== trip.route_id && previousTrip.lastStoptime.arrival_timestamp >= firstStoptime.departure_timestamp - maxContinuesAsWaitingTimeSeconds && firstStopIds.includes(previousTrip.lastStoptime.stop_id)) {
1403
- const routes = getRoutes({
1404
- route_id: previousTrip.route_id
1405
- });
1406
- previousTrip.route = routes[0];
1407
- trip.continues_from_route = previousTrip;
1408
- }
1409
- const nextTrip = find(
1410
- blockTrips,
1411
- (blockTrip) => blockTrip.firstStoptime.departure_timestamp >= lastStoptime.arrival_timestamp
1412
- );
1413
- if (nextTrip && nextTrip.route_id !== trip.route_id && nextTrip.firstStoptime.departure_timestamp <= lastStoptime.arrival_timestamp + maxContinuesAsWaitingTimeSeconds && lastStopIds.includes(nextTrip.firstStoptime.stop_id)) {
1414
- const routes = getRoutes({
1415
- route_id: nextTrip.route_id
1416
- });
1417
- nextTrip.route = routes[0];
1418
- trip.continues_as_route = nextTrip;
1419
- }
1420
- };
1421
- var filterTrips = (timetable, calendars, config2) => {
1422
- let filteredTrips = timetable.orderedTrips;
1423
- for (const trip of filteredTrips) {
1424
- const combinedStoptimes = [];
1425
- for (const [index, stoptime] of trip.stoptimes.entries()) {
1426
- if (index === 0 || stoptime.stop_id !== trip.stoptimes[index - 1].stop_id) {
1427
- combinedStoptimes.push(stoptime);
1428
- } else {
1429
- combinedStoptimes[combinedStoptimes.length - 1].departure_time = stoptime.departure_time;
1430
- }
1431
- }
1432
- trip.stoptimes = combinedStoptimes;
1433
- }
1434
- const timetableStopIds = new Set(
1435
- timetable.stops.map((stop) => stop.stop_id)
1436
- );
1437
- for (const trip of filteredTrips) {
1438
- trip.stoptimes = trip.stoptimes.filter(
1439
- (stoptime) => timetableStopIds.has(stoptime.stop_id)
1440
- );
1441
- }
1442
- filteredTrips = filteredTrips.filter(
1443
- (trip) => trip.stoptimes.length > 1
1444
- );
1445
- if (config2.showDuplicateTrips === false) {
1446
- filteredTrips = deduplicateTrips(filteredTrips);
1447
- }
1448
- const dayNames = [
1449
- "monday",
1450
- "tuesday",
1451
- "wednesday",
1452
- "thursday",
1453
- "friday",
1454
- "saturday",
1455
- "sunday"
1456
- ];
1457
- const timetableDays = dayNames.filter((day) => timetable[day] === 1);
1458
- if (timetableDays.length > 1) {
1459
- const warnedServiceIds = /* @__PURE__ */ new Set();
1460
- for (const trip of filteredTrips) {
1461
- const tripServiceIds = [
1462
- trip.service_id,
1463
- ...trip.additional_service_ids ?? []
1464
- ];
1465
- const tripCalendars = calendars.filter(
1466
- (c) => tripServiceIds.includes(c.service_id)
1467
- );
1468
- if (tripCalendars.length === 0) {
1469
- continue;
1470
- }
1471
- const tripDays = getDaysFromCalendars(tripCalendars);
1472
- const missingDays = timetableDays.filter(
1473
- (day) => (tripDays[day] ?? 0) !== 1
1474
- );
1475
- if (missingDays.length > 0) {
1476
- const serviceIdKey = tripServiceIds.sort().join("|");
1477
- if (!warnedServiceIds.has(serviceIdKey)) {
1478
- warnedServiceIds.add(serviceIdKey);
1479
- const tripDayList = formatDays(tripDays, config2);
1480
- const timetableDayList = formatDays(timetable, config2);
1481
- timetable.warnings.push(
1482
- `Timetable ${timetable.timetable_id} (Routes: ${timetable.routes.map((route) => route.route_short_name).join(", ")}) covers ${timetableDayList} but some trips (service_id=${tripServiceIds.join(", ")}) only run on ${tripDayList}. This may indicate a data issue in the GTFS or that you should generate separate timetables for different days of the week.`
1483
- );
1484
- }
1485
- }
1486
- }
1487
- }
1488
- const formattedTrips = filteredTrips.map((trip) => {
1489
- const tripCalendars = calendars.filter((calendar) => {
1490
- return [
1491
- trip.service_id,
1492
- ...trip.additional_service_ids || []
1493
- ].includes(calendar.service_id);
1494
- }) ?? [];
1495
- trip.dayList = formatDays(combineCalendars(tripCalendars), config2);
1496
- trip.dayListLong = formatDaysLong(trip.dayList, config2);
1497
- if (timetable.routes.length === 1) {
1498
- trip.route_short_name = timetable.routes[0].route_short_name;
1499
- } else {
1500
- const route = timetable.routes.find(
1501
- (route2) => route2.route_id === trip.route_id
1502
- );
1503
- trip.route_short_name = route?.route_short_name;
1504
- }
1505
- return trip;
1506
- });
1507
- return formattedTrips;
1508
- };
1509
- var getTripsForTimetable = (timetable, calendars, config2) => {
1510
- const tripQuery = {
1511
- route_id: timetable.route_ids,
1512
- service_id: timetable.service_ids
1513
- };
1514
- if (!isNullOrEmpty(timetable.direction_id)) {
1515
- tripQuery.direction_id = timetable.direction_id;
1516
- }
1517
- const trips = getTrips(tripQuery);
1518
- if (trips.length === 0) {
1519
- timetable.warnings.push(
1520
- `No trips found for route_id=${timetable.route_ids.join(
1521
- "_"
1522
- )}, direction_id=${timetable.direction_id}, service_ids=${JSON.stringify(
1523
- timetable.service_ids
1524
- )}, timetable_id=${timetable.timetable_id}`
1525
- );
1526
- }
1527
- const frequencies = getFrequencies({
1528
- trip_id: trips.map((trip) => trip.trip_id)
1529
- });
1530
- timetable.service_ids = uniq(trips.map((trip) => trip.service_id));
1531
- const formattedTrips = [];
1532
- for (const trip of trips) {
1533
- const formattedTrip = trip;
1534
- formattedTrip.stoptimes = getStoptimes(
1535
- {
1536
- trip_id: formattedTrip.trip_id
1537
- },
1538
- [],
1539
- [["stop_sequence", "ASC"]]
1540
- );
1541
- if (formattedTrip.stoptimes.length === 0) {
1542
- timetable.warnings.push(
1543
- `No stoptimes found for trip_id=${formattedTrip.trip_id}, route_id=${timetable.route_ids.join("_")}, timetable_id=${timetable.timetable_id}`
1544
- );
1545
- }
1546
- if (timetable.start_timestamp !== "" && timetable.start_timestamp !== null && timetable.start_timestamp !== void 0 && trip.stoptimes[0].arrival_timestamp < timetable.start_timestamp) {
1547
- return;
1548
- }
1549
- if (timetable.end_timestamp !== "" && timetable.end_timestamp !== null && timetable.end_timestamp !== void 0 && trip.stoptimes[0].arrival_timestamp >= timetable.end_timestamp) {
1550
- return;
1551
- }
1552
- if (timetable.show_trip_continuation) {
1553
- addTripContinuation(formattedTrip, timetable);
1554
- if (formattedTrip.continues_as_route) {
1555
- timetable.has_continues_as_route = true;
1556
- }
1557
- if (formattedTrip.continues_from_route) {
1558
- timetable.has_continues_from_route = true;
1559
- }
1560
- }
1561
- const tripFrequencies = frequencies.filter(
1562
- (frequency) => frequency.trip_id === trip.trip_id
1563
- );
1564
- if (tripFrequencies.length === 0) {
1565
- formattedTrips.push(formattedTrip);
1566
- } else {
1567
- const frequencyTrips = generateTripsByFrequencies(
1568
- formattedTrip,
1569
- frequencies,
1570
- config2
1571
- );
1572
- formattedTrips.push(...frequencyTrips);
1573
- timetable.frequencies = frequencies;
1574
- timetable.frequencyExactTimes = some(frequencies, {
1575
- exact_times: 1
1576
- });
1577
- }
1578
- }
1579
- if (config2.useParentStation) {
1580
- const stopIds = [];
1581
- for (const trip of formattedTrips) {
1582
- for (const stoptime of trip.stoptimes) {
1583
- stopIds.push(stoptime.stop_id);
1584
- }
1585
- }
1586
- const stops = getStops(
1587
- {
1588
- stop_id: uniq(stopIds)
1589
- },
1590
- ["parent_station", "stop_id"]
1591
- );
1592
- for (const trip of formattedTrips) {
1593
- for (const stoptime of trip.stoptimes) {
1594
- const stop = stops.find((stop2) => stop2.stop_id === stoptime.stop_id);
1595
- if (stop?.parent_station) {
1596
- stoptime.stop_id = stop.parent_station;
1597
- }
1598
- }
1599
- }
1600
- }
1601
- return sortTrips(formattedTrips, config2);
1602
- };
1603
- var formatTimetables = (timetables, config2) => {
1604
- const formattedTimetables = timetables.map((timetable) => {
1605
- timetable.warnings = [];
1606
- const dayList = formatDays(timetable, config2);
1607
- const calendars = getCalendarsFromTimetable(timetable);
1608
- const serviceIds = /* @__PURE__ */ new Set();
1609
- for (const calendar of calendars) {
1610
- serviceIds.add(calendar.service_id);
1611
- }
1612
- if (timetable.include_exceptions === 1) {
1613
- const calendarDates = getCalendarDatesForDateRange(
1614
- timetable.start_date,
1615
- timetable.end_date
1616
- );
1617
- const calendarDateGroups = groupBy(calendarDates, "service_id");
1618
- for (const [serviceId, calendarDateGroup] of Object.entries(
1619
- calendarDateGroups
1620
- )) {
1621
- const calendar = calendars.find(
1622
- (c) => c.service_id === serviceId
1623
- );
1624
- if (calendarDateGroup.some(
1625
- (calendarDate) => calendarDate.exception_type === 1
1626
- )) {
1627
- serviceIds.add(serviceId);
1628
- }
1629
- const calendarDateGroupExceptionType2 = calendarDateGroup.filter(
1630
- (calendarDate) => calendarDate.exception_type === 2
1631
- );
1632
- if (timetable.start_date && timetable.end_date && calendar && calendarDateGroupExceptionType2.length > 0) {
1633
- const datesDuringDateRange = calendarToDateList(
1634
- calendar,
1635
- timetable.start_date,
1636
- timetable.end_date
1637
- );
1638
- if (datesDuringDateRange.length === 0) {
1639
- serviceIds.delete(serviceId);
1640
- }
1641
- const everyDateIsExcluded = datesDuringDateRange.every(
1642
- (dateDuringDateRange) => calendarDateGroupExceptionType2.some(
1643
- (calendarDate) => calendarDate.date === dateDuringDateRange
1644
- )
1645
- );
1646
- if (everyDateIsExcluded) {
1647
- serviceIds.delete(serviceId);
1648
- }
1649
- }
1650
- }
1651
- }
1652
- Object.assign(timetable, {
1653
- noServiceSymbolUsed: false,
1654
- requestDropoffSymbolUsed: false,
1655
- noDropoffSymbolUsed: false,
1656
- requestPickupSymbolUsed: false,
1657
- noPickupSymbolUsed: false,
1658
- interpolatedStopSymbolUsed: false,
1659
- showStopCity: config2.showStopCity,
1660
- showStopDescription: config2.showStopDescription,
1661
- noServiceSymbol: config2.noServiceSymbol,
1662
- requestDropoffSymbol: config2.requestDropoffSymbol,
1663
- noDropoffSymbol: config2.noDropoffSymbol,
1664
- requestPickupSymbol: config2.requestPickupSymbol,
1665
- noPickupSymbol: config2.noPickupSymbol,
1666
- interpolatedStopSymbol: config2.interpolatedStopSymbol,
1667
- orientation: timetable.orientation || config2.defaultOrientation,
1668
- service_ids: Array.from(serviceIds),
1669
- dayList,
1670
- dayListLong: formatDaysLong(dayList, config2)
1671
- });
1672
- timetable.orderedTrips = getTripsForTimetable(timetable, calendars, config2);
1673
- timetable.stops = getStopsForTimetable(timetable, config2);
1674
- timetable.calendarDates = getCalendarDatesForTimetable(timetable, config2);
1675
- timetable.timetable_label = formatTimetableLabel(timetable);
1676
- timetable.notes = getTimetableNotesForTimetable(timetable, config2);
1677
- if (config2.showMap) {
1678
- timetable.geojson = getTimetableGeoJSON(timetable, config2);
1679
- }
1680
- timetable.trip_ids = uniq(getBaseTripIds(timetable.orderedTrips));
1681
- timetable.orderedTrips = filterTrips(timetable, calendars, config2);
1682
- timetable.stops = formatStops(timetable, config2);
1683
- return timetable;
1684
- });
1685
- if (config2.allowEmptyTimetables) {
1686
- return formattedTimetables;
1687
- }
1688
- return formattedTimetables.filter(
1689
- (timetable) => timetable.orderedTrips.length > 0
1690
- );
1691
- };
1692
- function getTimetablePagesForAgency(config2) {
1693
- const timetables = mergeTimetablesWithSameId(getTimetables());
1694
- const routes = getRoutes();
1695
- const formattedTimetables = timetables.map((timetable) => {
1696
- return {
1697
- ...timetable,
1698
- routes: routes.filter(
1699
- (route) => timetable.route_ids.includes(route.route_id)
1700
- )
1701
- };
1702
- });
1703
- if (timetables.length === 0) {
1704
- return convertRoutesToTimetablePages(config2);
1705
- }
1706
- const timetablePages = getTimetablePages(
1707
- {},
1708
- [],
1709
- [["timetable_page_id", "ASC"]]
1710
- );
1711
- if (timetablePages.length === 0) {
1712
- return formattedTimetables.map(
1713
- (timetable) => createTimetablePage({
1714
- timetablePageId: timetable.timetable_id,
1715
- timetables: [timetable],
1716
- config: config2
1717
- })
1718
- );
1719
- }
1720
- return timetablePages.map((timetablePage) => {
1721
- return {
1722
- ...timetablePage,
1723
- timetables: sortBy(
1724
- formattedTimetables.filter(
1725
- (timetable) => timetable.timetable_page_id === timetablePage.timetable_page_id
1726
- ),
1727
- "timetable_sequence"
1728
- )
1729
- };
1730
- });
1731
- }
1732
- var getDataForTimetablePageById = (timetablePageId) => {
1733
- let calendarCode;
1734
- let calendars;
1735
- let calendarDates;
1736
- let serviceId;
1737
- let directionId = "";
1738
- const parts = timetablePageId?.split("|") ?? [];
1739
- if (parts.length > 2) {
1740
- directionId = Number.parseInt(parts.pop(), 10);
1741
- calendarCode = parts.pop();
1742
- } else if (parts.length > 1) {
1743
- directionId = null;
1744
- calendarCode = parts.pop();
1745
- }
1746
- const routeId = parts.join("|");
1747
- const routes = getRoutes({
1748
- route_id: routeId
1749
- });
1750
- const trips = getTrips(
1751
- {
1752
- route_id: routeId,
1753
- direction_id: directionId
1754
- },
1755
- ["trip_headsign", "direction_id"]
1756
- );
1757
- const uniqueTripDirections = uniqBy2(trips, (trip) => trip.direction_id);
1758
- if (uniqueTripDirections.length === 0) {
1759
- throw new GtfsToHtmlError(
1760
- `No trips found for timetable_page_id=${timetablePageId} route_id=${routeId} direction_id=${directionId}`,
1761
- {
1762
- code: "GTFS_TO_HTML_QUERY_RESULT_NOT_FOUND" /* QUERY_RESULT_NOT_FOUND */,
1763
- category: "query" /* QUERY */,
1764
- details: {
1765
- entity: "trip",
1766
- timetablePageId,
1767
- routeId,
1768
- directionId
1769
- }
1770
- }
1771
- );
1772
- }
1773
- if (/^[01]*$/.test(calendarCode ?? "")) {
1774
- calendars = getCalendars({
1775
- ...calendarCodeToCalendar(calendarCode)
1776
- });
1777
- } else {
1778
- serviceId = calendarCode;
1779
- calendarDates = getCalendarDates({
1780
- exception_type: 1,
1781
- service_id: serviceId
1782
- });
1783
- }
1784
- return {
1785
- calendars,
1786
- calendarDates,
1787
- route: routes[0],
1788
- directionId: uniqueTripDirections[0].direction_id,
1789
- tripHeadsign: uniqueTripDirections[0].trip_headsign
1790
- };
1791
- };
1792
- var getTimetablePageById = (timetablePageId, config2) => {
1793
- const timetablePages = getTimetablePages({
1794
- timetable_page_id: timetablePageId
1795
- });
1796
- const timetables = mergeTimetablesWithSameId(
1797
- getTimetables()
1798
- );
1799
- if (timetablePages.length > 1) {
1800
- throw new GtfsToHtmlError(
1801
- `Multiple timetable_pages found for timetable_page_id=${timetablePageId}`,
1802
- {
1803
- code: "GTFS_TO_HTML_QUERY_RESULT_AMBIGUOUS" /* QUERY_RESULT_AMBIGUOUS */,
1804
- category: "query" /* QUERY */,
1805
- details: { entity: "timetable_page", timetablePageId }
1806
- }
1807
- );
1808
- }
1809
- if (timetablePages.length === 1) {
1810
- const timetablePage = timetablePages[0];
1811
- timetablePage.timetables = sortBy(
1812
- timetables.filter(
1813
- (timetable2) => timetable2.timetable_page_id === timetablePageId
1814
- ),
1815
- "timetable_sequence"
1816
- );
1817
- for (const timetable2 of timetablePage.timetables) {
1818
- timetable2.routes = getRoutes({
1819
- route_id: timetable2.route_ids
1820
- });
1821
- }
1822
- return timetablePage;
1823
- }
1824
- if (timetables.length > 0) {
1825
- const timetablePageTimetables = timetables.filter(
1826
- (timetable2) => timetable2.timetable_id === timetablePageId
1827
- );
1828
- if (timetablePageTimetables.length === 0) {
1829
- throw new GtfsToHtmlError(
1830
- `No timetable found for timetable_page_id=${timetablePageId}`,
1831
- {
1832
- code: "GTFS_TO_HTML_QUERY_RESULT_NOT_FOUND" /* QUERY_RESULT_NOT_FOUND */,
1833
- category: "query" /* QUERY */,
1834
- details: { entity: "timetable", timetablePageId }
1835
- }
1836
- );
1837
- }
1838
- return createTimetablePage({
1839
- timetablePageId,
1840
- timetables: [timetablePageTimetables[0]],
1841
- config: config2
1842
- });
1843
- }
1844
- if (timetablePageId.startsWith("route_")) {
1845
- const routes = getRoutes({
1846
- route_id: timetablePageId.slice("route_".length)
1847
- });
1848
- if (routes.length === 0) {
1849
- throw new GtfsToHtmlError(
1850
- `No route found for timetable_page_id=${timetablePageId}`,
1851
- {
1852
- code: "GTFS_TO_HTML_QUERY_RESULT_NOT_FOUND" /* QUERY_RESULT_NOT_FOUND */,
1853
- category: "query" /* QUERY */,
1854
- details: { entity: "route", timetablePageId }
1855
- }
1856
- );
1857
- }
1858
- const { calendars: calendars2, calendarDates: calendarDates2 } = getCalendarsFromConfig(config2);
1859
- const trips = getTrips(
1860
- {
1861
- route_id: routes[0].route_id
1862
- },
1863
- ["trip_headsign", "direction_id", "trip_id", "service_id"]
1864
- );
1865
- const uniqueTripDirections = orderBy(
1866
- uniqBy2(trips, (trip) => trip.direction_id),
1867
- "direction_id"
1868
- );
1869
- const sortedCalendars = orderBy(calendars2, calendarToCalendarCode, "desc");
1870
- const calendarGroups = groupBy(sortedCalendars, calendarToCalendarCode);
1871
- const calendarDateGroups = groupBy(calendarDates2, "service_id");
1872
- const timetables2 = [];
1873
- for (const uniqueTripDirection of uniqueTripDirections) {
1874
- for (const calendars3 of Object.values(calendarGroups)) {
1875
- const tripsForCalendars = trips.filter(
1876
- (trip) => some(calendars3, { service_id: trip.service_id })
1877
- );
1878
- if (tripsForCalendars.length > 0) {
1879
- timetables2.push(
1880
- createTimetable({
1881
- route: routes[0],
1882
- directionId: uniqueTripDirection.direction_id,
1883
- tripHeadsign: uniqueTripDirection.trip_headsign,
1884
- calendars: calendars3
1885
- })
1886
- );
1887
- }
1888
- }
1889
- for (const calendarDates3 of Object.values(calendarDateGroups)) {
1890
- const tripsForCalendarDates = trips.filter(
1891
- (trip) => some(calendarDates3, { service_id: trip.service_id })
1892
- );
1893
- if (tripsForCalendarDates.length > 0) {
1894
- timetables2.push(
1895
- createTimetable({
1896
- route: routes[0],
1897
- directionId: uniqueTripDirection.direction_id,
1898
- tripHeadsign: uniqueTripDirection.trip_headsign,
1899
- calendarDates: calendarDates3
1900
- })
1901
- );
1902
- }
1903
- }
1904
- }
1905
- return createTimetablePage({
1906
- timetablePageId,
1907
- timetables: timetables2,
1908
- config: config2
1909
- });
1910
- }
1911
- const { calendars, calendarDates, route, directionId, tripHeadsign } = getDataForTimetablePageById(timetablePageId);
1912
- const timetable = createTimetable({
1913
- route,
1914
- directionId,
1915
- tripHeadsign,
1916
- calendars,
1917
- calendarDates
1918
- });
1919
- return createTimetablePage({
1920
- timetablePageId,
1921
- timetables: [timetable],
1922
- config: config2
1923
- });
1924
- };
1925
- function setDefaultConfig(initialConfig) {
1926
- const defaults = {
1927
- allowEmptyTimetables: false,
1928
- beautify: false,
1929
- coordinatePrecision: 5,
1930
- dateFormat: "MMM D, YYYY",
1931
- daysShortStrings: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
1932
- daysStrings: [
1933
- "Monday",
1934
- "Tuesday",
1935
- "Wednesday",
1936
- "Thursday",
1937
- "Friday",
1938
- "Saturday",
1939
- "Sunday"
1940
- ],
1941
- defaultOrientation: "vertical",
1942
- interpolatedStopSymbol: "\u2022",
1943
- interpolatedStopText: "Estimated time of arrival",
1944
- groupTimetablesIntoPages: true,
1945
- gtfsToHtmlVersion: version,
1946
- linkStopUrls: false,
1947
- mapStyleUrl: "https://tiles.openfreemap.org/styles/positron",
1948
- menuType: "jump",
1949
- noDropoffSymbol: "\u2021",
1950
- noDropoffText: "No drop off available",
1951
- noHead: false,
1952
- noPickupSymbol: "**",
1953
- noPickupText: "No pickup available",
1954
- noRegularServiceDaysText: "No regular service days",
1955
- noServiceSymbol: "-",
1956
- noServiceText: "No service at this stop",
1957
- outputFormat: "html",
1958
- overwriteExistingFiles: true,
1959
- requestDropoffSymbol: "\u2020",
1960
- requestDropoffText: "Must request drop off",
1961
- requestPickupSymbol: "***",
1962
- requestPickupText: "Request stop - call for pickup",
1963
- serviceNotProvidedOnText: "Service not provided on",
1964
- serviceProvidedOnText: "Service provided on",
1965
- showArrivalOnDifference: 0.2,
1966
- showCalendarExceptions: true,
1967
- showDuplicateTrips: false,
1968
- showMap: false,
1969
- showOnlyTimepoint: false,
1970
- showRouteTitle: true,
1971
- showStopCity: false,
1972
- showStopDescription: false,
1973
- showStoptimesForRequestStops: true,
1974
- skipImport: false,
1975
- sortingAlgorithm: "common",
1976
- timeFormat: "h:mma",
1977
- useParentStation: true,
1978
- verbose: true,
1979
- zipOutput: false
1980
- };
1981
- const config2 = Object.assign(defaults, initialConfig);
1982
- if (config2.outputFormat === "pdf") {
1983
- config2.noHead = false;
1984
- config2.menuType = "none";
1985
- }
1986
- config2.hasGtfsRealtimeVehiclePositions = config2.agencies.some(
1987
- (agency) => agency.realtimeVehiclePositions?.url
1988
- );
1989
- config2.hasGtfsRealtimeTripUpdates = config2.agencies.some(
1990
- (agency) => agency.realtimeTripUpdates?.url
1991
- );
1992
- config2.hasGtfsRealtimeAlerts = config2.agencies.some(
1993
- (agency) => agency.realtimeAlerts?.url
1994
- );
1995
- return config2;
1996
- }
1997
- function getFormattedTimetablePage(timetablePageId, config2) {
1998
- const timetablePage = getTimetablePageById(
1999
- timetablePageId,
2000
- config2
2001
- );
2002
- const consolidatedTimetables = formatTimetables(
2003
- timetablePage.timetables,
2004
- config2
2005
- );
2006
- for (const timetable of consolidatedTimetables) {
2007
- if (isNullOrEmpty(timetable.direction_name)) {
2008
- timetable.direction_name = getDirectionHeadsignFromTimetable(timetable);
2009
- }
2010
- if (!timetable.routes) {
2011
- timetable.routes = getRoutes({
2012
- route_id: timetable.route_ids
2013
- });
2014
- }
2015
- }
2016
- const uniqueRoutes = uniqBy2(
2017
- flatMap(consolidatedTimetables, (timetable) => timetable.routes),
2018
- "route_id"
2019
- );
2020
- const formattedTimetablePage = {
2021
- ...timetablePage,
2022
- consolidatedTimetables,
2023
- dayList: formatDays(getDaysFromCalendars(consolidatedTimetables), config2),
2024
- dayLists: uniq(
2025
- consolidatedTimetables.map((timetable) => timetable.dayList)
2026
- ),
2027
- route_ids: uniqueRoutes.map((route) => route.route_id),
2028
- agency_ids: uniq(compact(uniqueRoutes.map((route) => route.agency_id))),
2029
- filename: timetablePage.filename ?? `${timetablePage.timetable_page_id}.html`,
2030
- timetable_page_label: timetablePage.timetable_page_label ?? formatListForDisplay(uniqueRoutes.map((route) => formatRouteName(route)))
2031
- };
2032
- return formattedTimetablePage;
2033
- }
2034
- function generateTimetableHTML(timetablePage, config2) {
2035
- const agencies = getAgencies2();
2036
- const templateVars = {
2037
- timetablePage,
2038
- config: config2,
2039
- title: `${timetablePage.timetable_page_label} | ${formatListForDisplay(agencies.map((agency) => agency.agency_name))}`
2040
- };
2041
- return renderTemplate("timetablepage", templateVars, config2);
2042
- }
2043
- function generateOverviewHTML(timetablePages, config2) {
2044
- const agencies = getAgencies2();
2045
- if (agencies.length === 0) {
2046
- throw new GtfsToHtmlError("No agencies found", {
2047
- code: "GTFS_TO_HTML_QUERY_RESULT_NOT_FOUND" /* QUERY_RESULT_NOT_FOUND */,
2048
- category: "query" /* QUERY */,
2049
- details: { entity: "agency" }
2050
- });
2051
- }
2052
- const geojson = config2.showMap ? getAgencyGeoJSON(config2) : void 0;
2053
- const templateVars = {
2054
- agency: {
2055
- ...first(agencies),
2056
- geojson
2057
- },
2058
- // Legacy agency object
2059
- agencies,
2060
- geojson,
2061
- config: config2,
2062
- timetablePages,
2063
- title: `${formatListForDisplay(agencies.map((agency) => agency.agency_name))} Timetables`
2064
- };
2065
- return renderTemplate("overview", templateVars, config2);
2066
- }
2067
-
2068
- // src/lib/formatters.ts
2069
- function replaceAll(string, mapObject) {
2070
- const re = new RegExp(Object.keys(mapObject).join("|"), "gi");
2071
- return string.replace(re, (matched) => mapObject[matched]);
2072
- }
2073
- function isNullOrEmpty(value) {
2074
- return value === null || value === "";
2075
- }
2076
- function formatDate(date, dateFormat) {
2077
- if (date.holiday_name) {
2078
- return date.holiday_name;
2079
- }
2080
- return moment3(date.date, "YYYYMMDD").format(dateFormat);
2081
- }
2082
- function timeToSeconds(time) {
2083
- return moment3.duration(time).asSeconds();
2084
- }
2085
- function formatStopTime(stoptime, timetable, config2) {
2086
- stoptime.classes = [];
2087
- if (stoptime.type === "arrival" && stoptime.arrival_time) {
2088
- const arrivalTime = fromGTFSTime(stoptime.arrival_time);
2089
- stoptime.formatted_time = arrivalTime.format(config2.timeFormat);
2090
- stoptime.classes.push(arrivalTime.format("a"));
2091
- } else if (stoptime.type === "departure" && stoptime.departure_time) {
2092
- const departureTime = fromGTFSTime(stoptime.departure_time);
2093
- stoptime.formatted_time = departureTime.format(config2.timeFormat);
2094
- stoptime.classes.push(departureTime.format("a"));
2095
- }
2096
- if (stoptime.pickup_type === 1) {
2097
- stoptime.noPickup = true;
2098
- stoptime.classes.push("no-pickup");
2099
- if (timetable.noPickupSymbol !== null) {
2100
- timetable.noPickupSymbolUsed = true;
2101
- }
2102
- } else if (stoptime.pickup_type === 2 || stoptime.pickup_type === 3) {
2103
- stoptime.requestPickup = true;
2104
- stoptime.classes.push("request-pickup");
2105
- if (timetable.requestPickupSymbol !== null) {
2106
- timetable.requestPickupSymbolUsed = true;
2107
- }
2108
- }
2109
- if (stoptime.drop_off_type === 1) {
2110
- stoptime.noDropoff = true;
2111
- stoptime.classes.push("no-drop-off");
2112
- if (timetable.noDropoffSymbol !== null) {
2113
- timetable.noDropoffSymbolUsed = true;
2114
- }
2115
- } else if (stoptime.drop_off_type === 2 || stoptime.drop_off_type === 3) {
2116
- stoptime.requestDropoff = true;
2117
- stoptime.classes.push("request-drop-off");
2118
- if (timetable.requestDropoffSymbol !== null) {
2119
- timetable.requestDropoffSymbolUsed = true;
2120
- }
2121
- }
2122
- if (stoptime.timepoint === 0 || stoptime.departure_time === "") {
2123
- stoptime.interpolated = true;
2124
- stoptime.classes.push("interpolated");
2125
- if (timetable.interpolatedStopSymbol !== null) {
2126
- timetable.interpolatedStopSymbolUsed = true;
2127
- }
2128
- }
2129
- if (stoptime.timepoint === null && stoptime.departure_time === null && stoptime.stop_sequence === null) {
2130
- stoptime.skipped = true;
2131
- stoptime.classes.push("skipped");
2132
- if (timetable.noServiceSymbol !== null) {
2133
- timetable.noServiceSymbolUsed = true;
2134
- }
2135
- }
2136
- if (stoptime.timepoint === 1) {
2137
- stoptime.classes.push("timepoint");
2138
- }
2139
- return stoptime;
2140
- }
2141
- function filterHourlyTimes(stops) {
2142
- const firstStopTimes = [];
2143
- const firstTripMinutes = minutesAfterMidnight(stops[0].trips[0].arrival_time);
2144
- for (const trip of stops[0].trips) {
2145
- const minutes = minutesAfterMidnight(trip.arrival_time);
2146
- if (minutes >= firstTripMinutes + 60) {
2147
- break;
2148
- }
2149
- firstStopTimes.push(fromGTFSTime(trip.arrival_time));
2150
- }
2151
- const firstStopTimesAndIndex = firstStopTimes.map((time, idx) => ({
2152
- idx,
2153
- time
2154
- }));
2155
- const sortedFirstStopTimesAndIndex = sortBy2(
2156
- firstStopTimesAndIndex,
2157
- (item) => Number.parseInt(item.time.format("m"), 10)
2158
- );
2159
- return stops.map((stop) => {
2160
- stop.hourlyTimes = sortedFirstStopTimesAndIndex.map(
2161
- (item) => fromGTFSTime(stop.trips[item.idx].arrival_time).format(":mm")
2162
- );
2163
- return stop;
2164
- });
2165
- }
2166
- var days = [
2167
- "monday",
2168
- "tuesday",
2169
- "wednesday",
2170
- "thursday",
2171
- "friday",
2172
- "saturday",
2173
- "sunday"
2174
- ];
2175
- function formatDays(calendar, config2) {
2176
- const daysShort = config2.daysShortStrings;
2177
- let daysInARow = 0;
2178
- let dayString = "";
2179
- if (!calendar) {
2180
- return "";
2181
- }
2182
- for (let i = 0; i <= 6; i += 1) {
2183
- const currentDayOperating = calendar[days[i]] === 1;
2184
- const previousDayOperating = i > 0 ? calendar[days[i - 1]] === 1 : false;
2185
- const nextDayOperating = i < 6 ? calendar[days[i + 1]] === 1 : false;
2186
- if (currentDayOperating) {
2187
- if (dayString.length > 0) {
2188
- if (!previousDayOperating) {
2189
- dayString += ", ";
2190
- } else if (daysInARow === 1) {
2191
- dayString += "-";
2192
- }
2193
- }
2194
- daysInARow += 1;
2195
- if (dayString.length === 0 || !nextDayOperating || i === 6 || !previousDayOperating) {
2196
- dayString += daysShort[i];
2197
- }
2198
- } else {
2199
- daysInARow = 0;
2200
- }
2201
- }
2202
- if (dayString.length === 0) {
2203
- dayString = config2.noRegularServiceDaysText;
2204
- }
2205
- return dayString;
2206
- }
2207
- function formatDaysLong(dayList, config2) {
2208
- const mapObject = zipObject(config2.daysShortStrings, config2.daysStrings);
2209
- return replaceAll(dayList, mapObject);
2210
- }
2211
- function formatFrequency(frequency, config2) {
2212
- const startTime = fromGTFSTime(frequency.start_time);
2213
- const endTime = fromGTFSTime(frequency.end_time);
2214
- const headway = moment3.duration(frequency.headway_secs, "seconds");
2215
- frequency.start_formatted_time = startTime.format(config2.timeFormat);
2216
- frequency.end_formatted_time = endTime.format(config2.timeFormat);
2217
- frequency.headway_min = Math.round(headway.asMinutes());
2218
- return frequency;
2219
- }
2220
- function formatTimetableId({
2221
- routeIds,
2222
- directionId,
2223
- days: days2,
2224
- dates
2225
- }) {
2226
- let timetableId = routeIds.join("_");
2227
- if (calendarToCalendarCode(days2)) {
2228
- timetableId += `|${calendarToCalendarCode(days2)}`;
2229
- } else if (dates && dates.length > 0) {
2230
- timetableId += `|${dates.join("_")}`;
2231
- }
2232
- if (!isNullOrEmpty(directionId)) {
2233
- timetableId += `|${directionId}`;
2234
- }
2235
- return timetableId;
2236
- }
2237
- function createEmptyStoptime(stopId, tripId) {
2238
- return {
2239
- id: null,
2240
- trip_id: tripId,
2241
- arrival_time: null,
2242
- departure_time: null,
2243
- stop_id: stopId,
2244
- stop_sequence: null,
2245
- stop_headsign: null,
2246
- pickup_type: null,
2247
- drop_off_type: null,
2248
- continuous_pickup: null,
2249
- continuous_drop_off: null,
2250
- shape_dist_traveled: null,
2251
- timepoint: null
2252
- };
2253
- }
2254
- function formatStops(timetable, config2) {
2255
- for (const trip of timetable.orderedTrips) {
2256
- let stopIndex = -1;
2257
- for (const [idx, stoptime] of trip.stoptimes.entries()) {
2258
- const stop = find2(timetable.stops, (st, idx2) => {
2259
- if (st.stop_id === stoptime.stop_id && idx2 > stopIndex) {
2260
- stopIndex = idx2;
2261
- return true;
2262
- }
2263
- return false;
2264
- });
2265
- if (!stop) {
2266
- continue;
2267
- }
2268
- if (idx === 0) {
2269
- stoptime.drop_off_type = 0;
2270
- }
2271
- if (idx === trip.stoptimes.length - 1) {
2272
- stoptime.pickup_type = 0;
2273
- }
2274
- if (stop.type === "arrival" && idx < trip.stoptimes.length - 1) {
2275
- const departureStoptime = clone(stoptime);
2276
- departureStoptime.type = "departure";
2277
- timetable.stops[stopIndex + 1].trips.push(
2278
- formatStopTime(departureStoptime, timetable, config2)
2279
- );
2280
- }
2281
- if (!(stop.type === "arrival" && idx === 0)) {
2282
- stoptime.type = "arrival";
2283
- stop.trips.push(formatStopTime(stoptime, timetable, config2));
2284
- }
2285
- }
2286
- for (const stop of timetable.stops) {
2287
- const lastStopTime = last2(stop.trips);
2288
- if (!lastStopTime || lastStopTime.trip_id !== trip.trip_id) {
2289
- stop.trips.push(
2290
- formatStopTime(
2291
- createEmptyStoptime(stop.stop_id, trip.trip_id),
2292
- timetable,
2293
- config2
2294
- )
2295
- );
2296
- }
2297
- }
2298
- }
2299
- if (timetable.orientation === "hourly") {
2300
- timetable.stops = filterHourlyTimes(timetable.stops);
2301
- }
2302
- for (const stop of timetable.stops) {
2303
- stop.is_timepoint = stop.trips.some((stoptime) => isTimepoint(stoptime));
2304
- }
2305
- return timetable.stops;
2306
- }
2307
- function resetStoptimesToMidnight(trip) {
2308
- const offsetSeconds = secondsAfterMidnight(
2309
- first2(trip.stoptimes).departure_time
2310
- );
2311
- if (offsetSeconds > 0) {
2312
- for (const stoptime of trip.stoptimes) {
2313
- stoptime.departure_time = toGTFSTime(
2314
- fromGTFSTime(stoptime.departure_time).subtract(
2315
- offsetSeconds,
2316
- "seconds"
2317
- )
2318
- );
2319
- stoptime.arrival_time = toGTFSTime(
2320
- fromGTFSTime(stoptime.arrival_time).subtract(offsetSeconds, "seconds")
2321
- );
2322
- }
2323
- }
2324
- return trip;
2325
- }
2326
- function updateStoptimesByOffset(trip, offsetSeconds) {
2327
- return trip.stoptimes.map((stoptime) => {
2328
- delete stoptime._id;
2329
- stoptime.departure_time = updateTimeByOffset(
2330
- stoptime.departure_time,
2331
- offsetSeconds
2332
- );
2333
- stoptime.arrival_time = updateTimeByOffset(
2334
- stoptime.arrival_time,
2335
- offsetSeconds
2336
- );
2337
- stoptime.trip_id = trip.trip_id;
2338
- return stoptime;
2339
- });
2340
- }
2341
- function formatRouteColor(route) {
2342
- return route.route_color ? `#${route.route_color}` : "#000000";
2343
- }
2344
- function formatRouteTextColor(route) {
2345
- return route.route_text_color ? `#${route.route_text_color}` : "#FFFFFF";
2346
- }
2347
- function formatTimetableLabel(timetable) {
2348
- if (!isNullOrEmpty(timetable.timetable_label)) {
2349
- return timetable.timetable_label;
2350
- }
2351
- let timetableLabel = "";
2352
- if (timetable.routes && timetable.routes.length > 0) {
2353
- timetableLabel += "Route ";
2354
- if (!isNullOrEmpty(timetable.routes[0].route_short_name)) {
2355
- timetableLabel += timetable.routes[0].route_short_name;
2356
- } else if (!isNullOrEmpty(timetable.routes[0].route_long_name)) {
2357
- timetableLabel += timetable.routes[0].route_long_name;
2358
- }
2359
- }
2360
- if (timetable.stops && timetable.stops.length > 0) {
2361
- const firstStop = timetable.stops[0].stop_name;
2362
- const lastStop = timetable.stops[timetable.stops.length - 1].stop_name;
2363
- if (firstStop === lastStop) {
2364
- if (!isNullOrEmpty(timetable.routes[0].route_long_name)) {
2365
- timetableLabel += ` - ${timetable.routes[0].route_long_name}`;
2366
- }
2367
- timetableLabel += " - Loop";
2368
- } else {
2369
- timetableLabel += ` - ${firstStop} to ${lastStop}`;
2370
- }
2371
- } else if (timetable.direction_name !== null) {
2372
- timetableLabel += ` to ${timetable.direction_name}`;
2373
- }
2374
- return timetableLabel;
2375
- }
2376
- var formatRouteName = (route) => {
2377
- if (route.route_long_name === null || route.route_long_name === "") {
2378
- return `Route ${route.route_short_name}`;
2379
- }
2380
- return route.route_long_name ?? "Unknown";
2381
- };
2382
- var formatRouteNameForFilename = (route) => {
2383
- if (route.route_short_name) {
2384
- return route.route_short_name.replace(/\s/g, "-");
2385
- } else if (route.route_long_name) {
2386
- return route.route_long_name.replace(/\s/g, "-");
2387
- }
2388
- return "Unknown";
2389
- };
2390
- var formatListForDisplay = (list) => {
2391
- return new Intl.ListFormat("en-US", {
2392
- style: "long",
2393
- type: "conjunction"
2394
- }).format(list);
2395
- };
2396
- function mergeTimetablesWithSameId(timetables) {
2397
- if (timetables.length === 0) {
2398
- return [];
2399
- }
2400
- const mergedTimetables = groupBy2(timetables, "timetable_id");
2401
- return Object.values(mergedTimetables).map((timetableGroup) => {
2402
- const mergedTimetable = omit(timetableGroup[0], "route_id");
2403
- mergedTimetable.route_ids = timetableGroup.map(
2404
- (timetable) => timetable.route_id
2405
- );
2406
- return mergedTimetable;
2407
- });
2408
- }
2409
-
2410
- // src/app/index.ts
2411
- var argv = yargs(hideBin(process.argv)).option("c", {
2412
- alias: "configPath",
2413
- describe: "Path to config file",
2414
- default: "./config.json",
2415
- type: "string"
10
+ //#region src/app/index.ts
11
+ const argv = yargs(hideBin(process.argv)).option("c", {
12
+ alias: "configPath",
13
+ describe: "Path to config file",
14
+ default: "./config.json",
15
+ type: "string"
2416
16
  }).parseSync();
2417
- var app = express();
2418
- var configPath = argv.configPath || join2(process.cwd(), "config.json");
2419
- var selectedConfig = JSON.parse(readFileSync(configPath, "utf8"));
2420
- var config = setDefaultConfig(selectedConfig);
17
+ const app = express();
18
+ const configPath = argv.configPath || join(process.cwd(), "config.json");
19
+ const config = setDefaultConfig(JSON.parse(readFileSync(configPath, "utf8")));
2421
20
  config.noHead = false;
2422
21
  config.assetPath = "/";
2423
22
  config.logFunction = console.log;
2424
23
  try {
2425
- openDb2(config);
24
+ openDb(config);
2426
25
  } catch (error) {
2427
- console.error(
2428
- `Unable to open sqlite database "${config.sqlitePath}" defined as \`sqlitePath\` config.json. Ensure the parent directory exists and run gtfs-to-html to import GTFS before running this app.`
2429
- );
2430
- throw new GtfsToHtmlError(
2431
- `Unable to open sqlite database "${config.sqlitePath}"`,
2432
- {
2433
- code: "GTFS_TO_HTML_DATABASE_OPEN_FAILED" /* DATABASE_OPEN_FAILED */,
2434
- category: "database" /* DATABASE */,
2435
- details: { sqlitePath: config.sqlitePath, dbCode: error?.code },
2436
- cause: error
2437
- }
2438
- );
26
+ console.error(`Unable to open sqlite database "${config.sqlitePath}" defined as \`sqlitePath\` config.json. Ensure the parent directory exists and run gtfs-to-html to import GTFS before running this app.`);
27
+ throw new GtfsToHtmlError(`Unable to open sqlite database "${config.sqlitePath}"`, {
28
+ code: "GTFS_TO_HTML_DATABASE_OPEN_FAILED",
29
+ category: "database",
30
+ details: {
31
+ sqlitePath: config.sqlitePath,
32
+ dbCode: error?.code
33
+ },
34
+ cause: error
35
+ });
2439
36
  }
2440
37
  app.set("views", getPathToViewsFolder(config));
2441
38
  app.set("view engine", "pug");
2442
39
  app.use((req, res, next) => {
2443
- console.log(`${req.method} ${req.url}`);
2444
- next();
40
+ console.log(`${req.method} ${req.url}`);
41
+ next();
2445
42
  });
2446
- var staticAssetPath = config.templatePath === void 0 ? getPathToViewsFolder(config) : untildify(config.templatePath);
43
+ const staticAssetPath = config.templatePath === void 0 ? getPathToViewsFolder(config) : untildify(config.templatePath);
2447
44
  app.use(express.static(staticAssetPath));
2448
- var browserAssetsPath = join2(
2449
- dirname2(fileURLToPath2(import.meta.url)),
2450
- "../browser"
2451
- );
45
+ const browserAssetsPath = join(dirname(fileURLToPath(import.meta.url)), "../browser");
2452
46
  app.use("/js", express.static(browserAssetsPath));
2453
47
  app.use("/css", express.static(browserAssetsPath));
2454
48
  app.get("/", async (req, res, next) => {
2455
- try {
2456
- const timetablePages = [];
2457
- const timetablePageIds = getTimetablePagesForAgency(config).map(
2458
- (timetablePage) => timetablePage.timetable_page_id
2459
- );
2460
- for (const timetablePageId of timetablePageIds) {
2461
- if (!timetablePageId) {
2462
- continue;
2463
- }
2464
- const timetablePage = await getFormattedTimetablePage(
2465
- timetablePageId,
2466
- config
2467
- );
2468
- if (!timetablePage.consolidatedTimetables || timetablePage.consolidatedTimetables.length === 0) {
2469
- console.error(
2470
- `No timetables found for timetable_page_id=${timetablePage.timetable_page_id}`
2471
- );
2472
- continue;
2473
- }
2474
- timetablePage.relativePath = `/timetables/${timetablePage.timetable_page_id}`;
2475
- for (const timetable of timetablePage.consolidatedTimetables) {
2476
- timetable.timetable_label = formatTimetableLabel(timetable);
2477
- }
2478
- timetablePages.push(timetablePage);
2479
- }
2480
- const html = await generateOverviewHTML(timetablePages, config);
2481
- res.send(html);
2482
- } catch (error) {
2483
- next(error);
2484
- }
49
+ try {
50
+ const timetablePages = [];
51
+ const timetablePageIds = getTimetablePagesForAgency(config).map((timetablePage) => timetablePage.timetable_page_id);
52
+ for (const timetablePageId of timetablePageIds) {
53
+ if (!timetablePageId) continue;
54
+ const timetablePage = await getFormattedTimetablePage(timetablePageId, config);
55
+ if (!timetablePage.consolidatedTimetables || timetablePage.consolidatedTimetables.length === 0) {
56
+ console.error(`No timetables found for timetable_page_id=${timetablePage.timetable_page_id}`);
57
+ continue;
58
+ }
59
+ timetablePage.relativePath = `/timetables/${timetablePage.timetable_page_id}`;
60
+ for (const timetable of timetablePage.consolidatedTimetables) timetable.timetable_label = formatTimetableLabel(timetable);
61
+ timetablePages.push(timetablePage);
62
+ }
63
+ const html = await generateOverviewHTML(timetablePages, config);
64
+ res.send(html);
65
+ } catch (error) {
66
+ next(error);
67
+ }
2485
68
  });
2486
69
  app.get("/timetables/:timetablePageId", async (req, res, next) => {
2487
- const { timetablePageId } = req.params;
2488
- if (!timetablePageId) {
2489
- res.status(400).send("No timetablePageId provided");
2490
- return;
2491
- }
2492
- try {
2493
- const timetablePage = await getFormattedTimetablePage(
2494
- timetablePageId,
2495
- config
2496
- );
2497
- if (!timetablePage || !timetablePage.consolidatedTimetables || timetablePage.consolidatedTimetables.length === 0) {
2498
- res.status(404).send("Timetable page not found");
2499
- return;
2500
- }
2501
- const html = await generateTimetableHTML(timetablePage, config);
2502
- res.send(html);
2503
- } catch (error) {
2504
- if (isGtfsToHtmlError(error) && error.code === "GTFS_TO_HTML_QUERY_RESULT_NOT_FOUND" /* QUERY_RESULT_NOT_FOUND */) {
2505
- res.status(404).send("Timetable page not found");
2506
- return;
2507
- }
2508
- next(error);
2509
- }
70
+ const { timetablePageId } = req.params;
71
+ if (!timetablePageId) {
72
+ res.status(400).send("No timetablePageId provided");
73
+ return;
74
+ }
75
+ try {
76
+ const timetablePage = await getFormattedTimetablePage(timetablePageId, config);
77
+ if (!timetablePage || !timetablePage.consolidatedTimetables || timetablePage.consolidatedTimetables.length === 0) {
78
+ res.status(404).send("Timetable page not found");
79
+ return;
80
+ }
81
+ const html = await generateTimetableHTML(timetablePage, config);
82
+ res.send(html);
83
+ } catch (error) {
84
+ if (isGtfsToHtmlError(error) && error.code === "GTFS_TO_HTML_QUERY_RESULT_NOT_FOUND") {
85
+ res.status(404).send("Timetable page not found");
86
+ return;
87
+ }
88
+ next(error);
89
+ }
2510
90
  });
2511
91
  app.use((req, res) => {
2512
- res.status(404).send("Not Found");
92
+ res.status(404).send("Not Found");
2513
93
  });
2514
- app.use(
2515
- (err, req, res, next) => {
2516
- console.error(err.stack);
2517
- res.status(500).send("Something broke!");
2518
- }
2519
- );
2520
- var startServer = async (port2) => {
2521
- try {
2522
- await new Promise((resolve2, reject) => {
2523
- const server = app.listen(port2).once("listening", () => {
2524
- console.log(`Express server listening on port ${port2}`);
2525
- resolve2();
2526
- }).once("error", (err) => {
2527
- if (err.code === "EADDRINUSE") {
2528
- console.log(`Port ${port2} is in use, trying ${port2 + 1}`);
2529
- server.close();
2530
- resolve2(startServer(port2 + 1));
2531
- } else {
2532
- reject(err);
2533
- }
2534
- });
2535
- });
2536
- } catch (err) {
2537
- console.error("Failed to start server:", err);
2538
- process.exit(1);
2539
- }
2540
- };
2541
- var port = process.env.PORT ? parseInt(process.env.PORT, 10) : 3e3;
2542
- startServer(port);
94
+ app.use((err, req, res, next) => {
95
+ console.error(err.stack);
96
+ res.status(500).send("Something broke!");
97
+ });
98
+ const startServer = async (port) => {
99
+ try {
100
+ await new Promise((resolve, reject) => {
101
+ const server = app.listen(port).once("listening", () => {
102
+ console.log(`Express server listening on port ${port}`);
103
+ resolve();
104
+ }).once("error", (err) => {
105
+ if (err.code === "EADDRINUSE") {
106
+ console.log(`Port ${port} is in use, trying ${port + 1}`);
107
+ server.close();
108
+ resolve(startServer(port + 1));
109
+ } else reject(err);
110
+ });
111
+ });
112
+ } catch (err) {
113
+ console.error("Failed to start server:", err);
114
+ process.exit(1);
115
+ }
116
+ };
117
+ startServer(process.env.PORT ? parseInt(process.env.PORT, 10) : 3e3);
118
+
119
+ //#endregion
120
+ export { };
2543
121
  //# sourceMappingURL=index.js.map