Skip to content

lis186/tdx-rail-metro-cli

Repository files navigation

TDX Rail Metro CLI

License: MIT TypeScript Node.js Tests

Command-line tool for accessing Taiwan Metro (MRT) data via the TDX API

Query real-time and static data for 9 Taiwan metro systems including Taipei Metro, Kaohsiung Metro, Taoyuan Airport MRT, and more - all from your terminal.

Features

  • 14 API Endpoints: Complete coverage of TDX Metro API
    • 11 static data endpoints (stations, lines, routes, fares, timetables, etc.)
    • 3 real-time endpoints (live board, alerts, news)
  • 🚇 9 Metro Systems: TRTC, KRTC, TYMC, TMRT, KLRT, NTDLRT, NTMC, NTALRT, TRTCMG
  • 📊 Dual Output Formats: Beautiful tables or JSON for scripting
  • Smart Caching: Tiered TTL strategy (24h/7d/4h/5min based on data type)
  • 🔐 OAuth2 Authentication: Automatic token management
  • 100% Test Coverage: 33 passing tests with TDD methodology
  • 📝 TypeScript: Full type safety with strict mode

Installation

From npm (coming soon)

npm install -g tdx-rail-metro-cli

From source

git clone https://github.com/lis186/tdx-rail-metro-cli.git
cd tdx-rail-metro-cli
npm install
npm run build
npm link

Quick Start

1. Get TDX API Credentials

Sign up at TDX Transport Data Platform to get your API credentials.

2. Configure Environment

Copy the example environment file and add your credentials:

cp .env.example .env
# Edit .env with your TDX credentials

3. Run Commands

# List supported metro operators
metro operators

# List all stations for Taipei Metro
metro stations list TRTC

# Search stations by name
metro stations search 台北 TRTC

# Get fare between two stations
metro fare query BL01 BL23 TRTC

# Check real-time arrivals
metro live board TRTC --station BL12

# View current alerts
metro alerts list TRTC

Usage

Supported Operators

Code Name Description
TRTC 台北捷運 Taipei Metro
KRTC 高雄捷運 Kaohsiung Metro
TYMC 桃園機場捷運 Taoyuan Airport MRT
TMRT 台中捷運 Taichung Metro
KLRT 高雄輕軌 Kaohsiung Light Rail
NTDLRT 淡海輕軌 New Taipei Danhai Light Rail
NTMC 新北環狀線 New Taipei Circular Line
NTALRT 安坑輕軌 New Taipei Ankeng Light Rail
TRTCMG 貓空纜車 Maokong Gondola

Commands

Stations

# List all stations
metro stations list <operator>

# Search stations by name (Chinese or English)
metro stations search <query> <operator>

# Get detailed station information
metro stations info <stationId> <operator>

# Output as JSON
metro stations list TRTC --format json

Lines

# List all lines
metro lines list <operator>

# Get line details
metro lines info <lineId> <operator>

# Get stations on a specific line
metro lines stations <lineId> <operator>

Fares

# List all origin-destination fares
metro fare list <operator>

# Query fare between two stations
metro fare query <fromStationId> <toStationId> <operator>

# Filter by origin/destination
metro fare list TRTC --from BL01 --to BL23

Timetables

# Get first and last train times
metro timetable first-last <operator>
metro timetable first-last TRTC --station BL12

# Get train frequency (headway)
metro timetable frequency <operator>
metro timetable frequency TRTC --line BL

# Get station-to-station travel times
metro timetable travel-time <operator>

Live Information

# Get live departure board
metro live board <operator>

# Filter by station
metro live board TRTC --station BL12

# Filter by line
metro live board TRTC --line BL

Alerts & News

# List current service alerts
metro alerts list <operator>

# Get latest news and announcements
metro alerts news <operator>

Global Options

All commands support:

--format json       # Output as JSON instead of table
--no-cache         # Skip cache and fetch fresh data

Examples

Example 1: Plan a trip on Taipei Metro

# Find your origin station
$ metro stations search 台北車站 TRTC
┌──────┬──────────────┬─────────────────────────────┬────────┐
│ ID   │ Name         │ English                     │ City   │
├──────┼──────────────┼─────────────────────────────┼────────┤
│ BL12 │ 台北車站     │ Taipei Main Station         │ 臺北市 │
│ R10  │ 台北車站     │ Taipei Main Station         │ 臺北市 │
└──────┴──────────────┴─────────────────────────────┴────────┘

# Check the fare
$ metro fare query BL01 BL23 TRTC
┌──────┬────────────┬───────┬──────────┐
│ From │ To         │ Price │ Distance │
├──────┼────────────┼───────┼──────────┤
│ 頂埔 │ 南港展覽館 │ $55   │ 26.64 km │
└──────┴────────────┴───────┴──────────┘

# Check real-time arrivals
$ metro live board TRTC --station BL12
[Shows upcoming trains with estimated arrival times]

Example 2: Get JSON for scripting

# Export all stations to process with jq
metro stations list TRTC --format json | jq '.[] | select(.LocationCity == "臺北市")'

# Monitor alerts and send to notification service
metro alerts list TRTC --format json | \
  jq -r '.Alerts[] | select(.Status != 1) | .Description'

Development

Prerequisites

  • Node.js 20+
  • npm or yarn

Setup

# Clone repository
git clone https://github.com/lis186/tdx-rail-metro-cli.git
cd tdx-rail-metro-cli

# Install dependencies
npm install

# Copy environment template
cp .env.example .env
# Edit .env with your TDX credentials

# Run in development mode
npm run dev -- stations list TRTC

# Run tests
npm test

# Run tests with coverage
npm run test:coverage

# Build
npm run build

# Type check
npm run typecheck

Project Structure

tdx-rail-metro-cli/
├── src/
│   ├── index.ts              # CLI entry point
│   ├── cli.ts                # Command definitions
│   ├── types/
│   │   ├── api.ts            # TDX API response types
│   │   ├── config.ts         # Configuration types
│   │   └── auth.ts           # Authentication types
│   ├── services/
│   │   ├── api.ts            # Metro API client
│   │   ├── auth.ts           # OAuth2 authentication
│   │   └── cache.ts          # Caching service
│   ├── lib/
│   │   ├── output.ts         # Output formatting
│   │   └── config.ts         # Configuration management
│   └── commands/
│       ├── stations.ts       # Station commands
│       ├── lines.ts          # Line commands
│       ├── fare.ts           # Fare commands
│       ├── timetable.ts      # Timetable commands
│       ├── live.ts           # Live board commands
│       └── alerts.ts         # Alert/news commands
├── tests/
│   └── services/             # Service layer tests
├── PRD.md                    # Product requirements
└── README.md                 # This file

Testing

This project follows Test-Driven Development (TDD) methodology:

# Run all tests
npm test

# Watch mode (auto-rerun on changes)
npm run test:watch

# Coverage report
npm run test:coverage

Current test stats: 33 tests passing with 80% coverage thresholds.

Architecture

Service-Oriented Design

  • Services Layer: Business logic (API client, auth, cache)
  • Commands Layer: CLI command handlers
  • Lib Layer: Utilities (output formatting, config)
  • Types Layer: TypeScript type definitions

Caching Strategy

Tiered TTL based on data volatility:

Data Type TTL Rationale
Static data (stations, lines) 24 hours Rarely changes
Fares 7 days Almost never changes
Timetables 4 hours May change for maintenance
Alerts 5 minutes Real-time data

Authentication

  • OAuth2 Client Credentials flow
  • Automatic token refresh before expiration
  • Secure token storage

API Reference

This CLI wraps the TDX Transport Data Platform API v2.

Endpoints covered:

  • ✅ Station
  • ✅ Line
  • ✅ Route
  • ✅ StationOfLine
  • ✅ S2STravelTime
  • ✅ Frequency
  • ✅ FirstLastTimetable
  • ✅ ODFare
  • ✅ StationExit
  • ✅ StationFacility
  • ✅ Shape
  • ✅ LiveBoard
  • ✅ Alert
  • ✅ News

Troubleshooting

Authentication Errors

Error: Invalid credentials

Solution: Check your .env file has correct TDX API credentials.

Rate Limiting

Error: Too many requests

Solution: TDX API has rate limits. Use --no-cache sparingly and rely on cached data when possible.

No Data Returned

No data found

Possible causes:

  • Invalid operator code (use metro operators to see valid codes)
  • Invalid station/line ID
  • Service temporarily unavailable

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Write tests for your changes
  4. Ensure all tests pass (npm test)
  5. Commit your changes (git commit -m 'Add some AmazingFeature')
  6. Push to the branch (git push origin feature/AmazingFeature)
  7. Open a Pull Request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Acknowledgments

Changelog

See PRD.md for detailed changelog and development progress.


Questions or Issues?

Made with ❤️ for Taiwan's public transportation community

About

Taiwan Metro (MRT) CLI tool powered by TDX API

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors