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