feat(All): 第一版项目

This commit is contained in:
2025-12-19 09:33:04 +08:00
parent 154132f17e
commit 2f6831336e
35 changed files with 5120 additions and 0 deletions

8
.idea/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,8 @@
# 默认忽略的文件
/shelf/
/workspace.xml
# 基于编辑器的 HTTP 客户端请求
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

9
.idea/LatencyTest.iml generated Normal file
View File

@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@@ -0,0 +1,5 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
</profile>
</component>

6
.idea/misc.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_25" default="true" project-jdk-name="25" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

8
.idea/modules.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/LatencyTest.iml" filepath="$PROJECT_DIR$/.idea/LatencyTest.iml" />
</modules>
</component>
</project>

6
.idea/vcs.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>

13
index.html Normal file
View File

@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/globe.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Latency Test</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/client/main.tsx"></script>
</body>
</html>

3828
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

37
package.json Normal file
View File

@@ -0,0 +1,37 @@
{
"name": "latency-test",
"private": true,
"version": "1.0.0",
"type": "module",
"scripts": {
"dev": "concurrently \"npm run dev:server\" \"npm run dev:client\"",
"dev:client": "vite",
"dev:server": "tsx watch src/server/index.ts",
"build": "npm run build:client && npm run build:server",
"build:client": "tsc -b tsconfig.client.json && vite build",
"build:server": "tsc -b tsconfig.server.json",
"preview": "vite preview",
"start": "node dist/server/index.js"
},
"dependencies": {
"cors": "^2.8.5",
"express": "^4.19.2",
"express-rate-limit": "^7.1.3",
"ipaddr.js": "^2.1.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-simple-maps": "^3.0.0"
},
"devDependencies": {
"@types/cors": "^2.8.17",
"@types/express": "^4.17.21",
"@types/node": "^20.11.30",
"@types/react": "^18.3.18",
"@types/react-dom": "^18.3.5",
"@vitejs/plugin-react": "^4.3.4",
"concurrently": "^9.1.2",
"tsx": "^4.7.0",
"typescript": "~5.6.2",
"vite": "^6.0.5"
}
}

1
public/globe.svg Normal file
View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>

After

Width:  |  Height:  |  Size: 360 B

58
src/client/App.tsx Normal file
View File

@@ -0,0 +1,58 @@
import { useState, useCallback } from 'react'
import { ThemeProvider } from './contexts/ThemeContext'
import ThemeSwitcher from './components/ThemeSwitcher'
import IpInput from './components/IpInput'
import LatencyMap from './components/LatencyMap'
import ResultsPanel from './components/ResultsPanel'
import { testAllNodes } from './api/latency'
import { LatencyResult } from '@shared/types'
import './styles/index.css'
function AppContent() {
const [results, setResults] = useState<Map<string, LatencyResult>>(new Map())
const [testing, setTesting] = useState(false)
const handleTest = useCallback(async (ip: string) => {
setTesting(true)
setResults(new Map())
await testAllNodes(ip, (result) => {
setResults((prev) => new Map(prev).set(result.nodeId, result))
})
setTesting(false)
}, [])
return (
<div className="app">
<header className="app-header">
<h1 className="app-title">
<span className="title-icon">🌐</span>
Latency Test
</h1>
<ThemeSwitcher />
</header>
<main className="app-main">
<p className="app-description">
Test network latency from global locations to any IP address
</p>
<IpInput onTest={handleTest} testing={testing} />
<LatencyMap results={results} />
<ResultsPanel results={results} />
</main>
<footer className="app-footer">
<p>Latency thresholds: <span className="excellent"></span> &lt;50ms <span className="good"></span> 50-150ms <span className="poor"></span> &gt;150ms</p>
</footer>
</div>
)
}
export default function App() {
return (
<ThemeProvider>
<AppContent />
</ThemeProvider>
)
}

52
src/client/api/latency.ts Normal file
View File

@@ -0,0 +1,52 @@
import { LatencyResult, TEST_NODES } from '@shared/types'
const API_BASE = '/api'
export interface IpInfoResponse {
ip: string
}
export interface LatencyTestResponse {
nodeId: string
latency: number | null
success: boolean
}
export async function fetchUserIp(): Promise<string> {
const res = await fetch(`${API_BASE}/ip`)
if (!res.ok) throw new Error('Failed to fetch IP')
const data: IpInfoResponse = await res.json()
return data.ip
}
export async function testLatency(
targetIp: string,
nodeId: string
): Promise<LatencyResult> {
const res = await fetch(`${API_BASE}/latency`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ targetIp, nodeId }),
})
if (!res.ok) {
return { nodeId, latency: null, status: 'failed' }
}
const data: LatencyTestResponse = await res.json()
return {
nodeId: data.nodeId,
latency: data.latency,
status: data.success ? 'success' : 'failed',
}
}
export async function testAllNodes(
targetIp: string,
onProgress: (result: LatencyResult) => void
): Promise<void> {
const promises = TEST_NODES.map(async (node) => {
onProgress({ nodeId: node.id, latency: null, status: 'testing' })
const result = await testLatency(targetIp, node.id)
onProgress(result)
})
await Promise.all(promises)
}

View File

@@ -0,0 +1,112 @@
.ip-input-form {
display: flex;
justify-content: center;
gap: 0;
margin-bottom: 2rem;
flex-wrap: wrap;
}
.input-wrapper {
position: relative;
flex: 1;
max-width: 300px;
min-width: 200px;
}
.ip-input {
width: 100%;
box-sizing: border-box;
font-size: 1rem;
padding: 12px 16px;
border-radius: 8px 0 0 8px;
border: 2px solid var(--border-color);
background-color: var(--input-bg);
color: var(--text-color);
outline: none;
transition: border-color 0.2s;
}
.ip-input:focus {
border-color: var(--primary-color);
}
.ip-input-error {
border-color: var(--error-color);
}
.ip-input:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.error-hint {
position: absolute;
left: 0;
bottom: -20px;
font-size: 0.75rem;
color: var(--error-color);
}
.test-button {
display: flex;
align-items: center;
gap: 8px;
font-size: 1rem;
padding: 12px 24px;
border-radius: 0 8px 8px 0;
border: 2px solid var(--primary-color);
background-color: var(--primary-color);
color: white;
cursor: pointer;
transition: background-color 0.2s, transform 0.1s;
font-weight: 600;
}
.test-button:hover:not(:disabled) {
background-color: var(--primary-hover);
border-color: var(--primary-hover);
}
.test-button:active:not(:disabled) {
transform: scale(0.98);
}
.test-button:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.spinner {
width: 16px;
height: 16px;
border: 2px solid white;
border-top-color: transparent;
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
@media (max-width: 480px) {
.ip-input-form {
flex-direction: column;
align-items: stretch;
gap: 8px;
padding: 0 16px;
}
.input-wrapper {
max-width: none;
}
.ip-input {
border-radius: 8px;
}
.test-button {
border-radius: 8px;
justify-content: center;
}
}

View File

@@ -0,0 +1,62 @@
import { useState, useEffect } from 'react'
import { fetchUserIp } from '../api/latency'
import './IpInput.css'
interface IpInputProps {
onTest: (ip: string) => void
testing: boolean
}
const IP_REGEX = /^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)$/
export default function IpInput({ onTest, testing }: IpInputProps) {
const [ip, setIp] = useState('')
const [loading, setLoading] = useState(true)
const [error, setError] = useState('')
useEffect(() => {
fetchUserIp()
.then(setIp)
.catch(() => setError('Failed to detect IP'))
.finally(() => setLoading(false))
}, [])
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault()
if (!IP_REGEX.test(ip)) {
setError('Invalid IP address')
return
}
setError('')
onTest(ip)
}
return (
<form onSubmit={handleSubmit} className="ip-input-form">
<div className="input-wrapper">
<input
type="text"
value={ip}
onChange={(e) => {
setIp(e.target.value)
setError('')
}}
placeholder={loading ? 'Detecting IP...' : 'Enter IP address'}
className={`ip-input ${error ? 'ip-input-error' : ''}`}
disabled={testing || loading}
/>
{error && <span className="error-hint">{error}</span>}
</div>
<button type="submit" className="test-button" disabled={testing || loading || !ip}>
{testing ? (
<>
<span className="spinner" />
Testing...
</>
) : (
'Test Latency'
)}
</button>
</form>
)
}

View File

@@ -0,0 +1,70 @@
.map-container {
width: 100%;
max-width: 900px;
margin: 0 auto 2rem;
border: 1px solid var(--border-color);
border-radius: 12px;
overflow: hidden;
background-color: var(--card-bg);
}
.geography {
fill: var(--map-land);
stroke: var(--map-border);
stroke-width: 0.5;
outline: none;
transition: fill 0.2s;
}
.marker-group {
cursor: pointer;
}
.marker-dot {
transition: r 0.3s, fill 0.3s;
}
.marker-dot.testing {
animation: pulse 1s ease-in-out infinite;
}
.marker-label {
font-size: 10px;
font-weight: 600;
fill: var(--text-color);
pointer-events: none;
}
.marker-latency {
font-size: 11px;
font-weight: 700;
pointer-events: none;
}
.marker-inactive {
fill: var(--marker-inactive);
}
.pulse-ring {
fill: none;
stroke: var(--primary-color);
stroke-width: 2;
opacity: 0;
animation: pulse-ring 1.5s ease-out infinite;
}
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.5; }
}
@keyframes pulse-ring {
0% {
r: 8;
opacity: 0.8;
}
100% {
r: 24;
opacity: 0;
}
}

View File

@@ -0,0 +1,70 @@
import { ComposableMap, Geographies, Geography, Marker } from 'react-simple-maps'
import { TEST_NODES, LatencyResult, getLatencyColor } from '@shared/types'
import './LatencyMap.css'
const GEO_URL = 'https://cdn.jsdelivr.net/npm/world-atlas@2/countries-110m.json'
interface LatencyMapProps {
results: Map<string, LatencyResult>
}
export default function LatencyMap({ results }: LatencyMapProps) {
return (
<div className="map-container">
<ComposableMap
projectionConfig={{ scale: 140, center: [0, 20] }}
style={{ width: '100%', height: 'auto' }}
>
<Geographies geography={GEO_URL}>
{({ geographies }) =>
geographies.map((geo) => (
<Geography
key={geo.rsmKey}
geography={geo}
className="geography"
/>
))
}
</Geographies>
{TEST_NODES.map((node) => {
const result = results.get(node.id)
const isTesting = result?.status === 'testing'
const hasResult = result?.status === 'success' || result?.status === 'failed'
return (
<Marker key={node.id} coordinates={node.coords}>
<g className="marker-group">
{isTesting && (
<circle r={16} className="pulse-ring" />
)}
<circle
r={8}
fill={hasResult ? getLatencyColor(result?.latency ?? null) : 'var(--marker-inactive)'}
className={`marker-dot ${isTesting ? 'testing' : ''}`}
/>
<text
textAnchor="middle"
y={-16}
className="marker-label"
>
{node.name}
</text>
{hasResult && (
<text
textAnchor="middle"
y={24}
className="marker-latency"
fill={getLatencyColor(result?.latency ?? null)}
>
{result?.latency !== null ? `${result.latency}ms` : 'Timeout'}
</text>
)}
</g>
</Marker>
)
})}
</ComposableMap>
</div>
)
}

View File

@@ -0,0 +1,89 @@
.results-panel {
max-width: 900px;
margin: 0 auto;
}
.results-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 1rem;
padding: 0 4px;
}
.results-header h2 {
margin: 0;
font-size: 1.25rem;
color: var(--text-color);
}
.avg-latency {
font-size: 1rem;
color: var(--text-secondary);
}
.results-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
gap: 12px;
}
.result-card {
background-color: var(--card-bg);
border: 1px solid var(--border-color);
border-radius: 8px;
padding: 12px;
text-align: center;
transition: transform 0.2s, box-shadow 0.2s;
}
.result-card:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px var(--shadow-color);
}
.result-card.excellent {
border-color: #22c55e;
}
.result-card.good {
border-color: #eab308;
}
.result-card.poor {
border-color: #ef4444;
}
.result-region {
font-size: 0.7rem;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 0.5px;
margin-bottom: 4px;
}
.result-name {
font-size: 0.9rem;
font-weight: 600;
color: var(--text-color);
margin-bottom: 8px;
}
.result-latency {
font-size: 1.1rem;
font-weight: 700;
}
.testing-indicator {
color: var(--primary-color);
animation: pulse 1s ease-in-out infinite;
}
.pending {
color: var(--text-secondary);
}
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.5; }
}

View File

@@ -0,0 +1,71 @@
import { TEST_NODES, LatencyResult, getLatencyColor, getLatencyLevel } from '@shared/types'
import './ResultsPanel.css'
interface ResultsPanelProps {
results: Map<string, LatencyResult>
}
export default function ResultsPanel({ results }: ResultsPanelProps) {
if (results.size === 0) return null
const sortedNodes = [...TEST_NODES].sort((a, b) => {
const aResult = results.get(a.id)
const bResult = results.get(b.id)
const aLatency = aResult?.latency ?? Infinity
const bLatency = bResult?.latency ?? Infinity
return aLatency - bLatency
})
const completedResults = sortedNodes
.map((node) => ({ node, result: results.get(node.id) }))
.filter(({ result }) => result?.status === 'success' || result?.status === 'failed')
const avgLatency =
completedResults.length > 0
? Math.round(
completedResults
.filter(({ result }) => result?.latency !== null)
.reduce((sum, { result }) => sum + (result?.latency ?? 0), 0) /
completedResults.filter(({ result }) => result?.latency !== null).length
)
: null
return (
<div className="results-panel">
<div className="results-header">
<h2>Test Results</h2>
{avgLatency !== null && (
<div className="avg-latency">
Avg: <span style={{ color: getLatencyColor(avgLatency) }}>{avgLatency}ms</span>
</div>
)}
</div>
<div className="results-grid">
{sortedNodes.map((node) => {
const result = results.get(node.id)
const isTesting = result?.status === 'testing'
const hasResult = result?.status === 'success' || result?.status === 'failed'
return (
<div key={node.id} className={`result-card ${hasResult ? getLatencyLevel(result?.latency ?? null) : ''}`}>
<div className="result-region">{node.region}</div>
<div className="result-name">{node.name}</div>
<div className="result-latency">
{isTesting ? (
<span className="testing-indicator">Testing...</span>
) : hasResult ? (
<span style={{ color: getLatencyColor(result?.latency ?? null) }}>
{result?.latency !== null ? `${result.latency}ms` : 'Timeout'}
</span>
) : (
<span className="pending"></span>
)}
</div>
</div>
)
})}
</div>
</div>
)
}

View File

@@ -0,0 +1,17 @@
.theme-switcher {
background: transparent;
border: 1px solid var(--border-color);
border-radius: 8px;
padding: 8px 12px;
font-size: 1.25rem;
cursor: pointer;
transition: background-color 0.2s, transform 0.1s;
}
.theme-switcher:hover {
background-color: var(--hover-bg);
}
.theme-switcher:active {
transform: scale(0.95);
}

View File

@@ -0,0 +1,16 @@
import { useTheme } from '../contexts/ThemeContext'
import './ThemeSwitcher.css'
export default function ThemeSwitcher() {
const { theme, toggleTheme } = useTheme()
return (
<button
onClick={toggleTheme}
className="theme-switcher"
aria-label={`Switch to ${theme === 'light' ? 'dark' : 'light'} mode`}
>
{theme === 'light' ? '🌙' : '☀️'}
</button>
)
}

View File

@@ -0,0 +1,37 @@
import { createContext, useContext, useEffect, useState, ReactNode } from 'react'
type Theme = 'light' | 'dark'
interface ThemeContextValue {
theme: Theme
toggleTheme: () => void
}
const ThemeContext = createContext<ThemeContextValue | null>(null)
export function ThemeProvider({ children }: { children: ReactNode }) {
const [theme, setTheme] = useState<Theme>(() => {
const saved = localStorage.getItem('theme') as Theme
if (saved) return saved
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
})
useEffect(() => {
document.documentElement.setAttribute('data-theme', theme)
localStorage.setItem('theme', theme)
}, [theme])
const toggleTheme = () => setTheme(t => (t === 'light' ? 'dark' : 'light'))
return (
<ThemeContext.Provider value={{ theme, toggleTheme }}>
{children}
</ThemeContext.Provider>
)
}
export function useTheme() {
const ctx = useContext(ThemeContext)
if (!ctx) throw new Error('useTheme must be used within ThemeProvider')
return ctx
}

9
src/client/main.tsx Normal file
View File

@@ -0,0 +1,9 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<App />
</React.StrictMode>
)

59
src/client/react-simple-maps.d.ts vendored Normal file
View File

@@ -0,0 +1,59 @@
declare module 'react-simple-maps' {
import { ComponentType, ReactNode } from 'react'
interface ComposableMapProps {
projection?: string
projectionConfig?: {
scale?: number
center?: [number, number]
rotate?: [number, number, number]
}
width?: number
height?: number
style?: React.CSSProperties
children?: ReactNode
}
interface GeographiesProps {
geography: string | object
children: (data: { geographies: Geography[] }) => ReactNode
}
interface Geography {
rsmKey: string
properties: Record<string, unknown>
}
interface GeographyProps {
geography: Geography
style?: {
default?: React.CSSProperties
hover?: React.CSSProperties
pressed?: React.CSSProperties
}
className?: string
onClick?: (event: React.MouseEvent) => void
onMouseEnter?: (event: React.MouseEvent) => void
onMouseLeave?: (event: React.MouseEvent) => void
}
interface MarkerProps {
coordinates: [number, number]
children?: ReactNode
}
interface LineProps {
from: [number, number]
to: [number, number]
stroke?: string
strokeWidth?: number
strokeLinecap?: string
strokeDasharray?: string
}
export const ComposableMap: ComponentType<ComposableMapProps>
export const Geographies: ComponentType<GeographiesProps>
export const Geography: ComponentType<GeographyProps>
export const Marker: ComponentType<MarkerProps>
export const Line: ComponentType<LineProps>
}

113
src/client/styles/index.css Normal file
View File

@@ -0,0 +1,113 @@
:root {
--primary-color: #3b82f6;
--primary-hover: #2563eb;
--error-color: #ef4444;
--text-color: #1f2937;
--text-secondary: #6b7280;
--background-color: #f9fafb;
--card-bg: #ffffff;
--input-bg: #ffffff;
--border-color: #e5e7eb;
--hover-bg: rgba(0, 0, 0, 0.05);
--shadow-color: rgba(0, 0, 0, 0.1);
--map-land: #e5e7eb;
--map-border: #d1d5db;
--marker-inactive: #9ca3af;
}
[data-theme='dark'] {
--text-color: #f9fafb;
--text-secondary: #9ca3af;
--background-color: #111827;
--card-bg: #1f2937;
--input-bg: #374151;
--border-color: #374151;
--hover-bg: rgba(255, 255, 255, 0.1);
--shadow-color: rgba(0, 0, 0, 0.3);
--map-land: #374151;
--map-border: #4b5563;
--marker-inactive: #6b7280;
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
background-color: var(--background-color);
color: var(--text-color);
line-height: 1.5;
transition: background-color 0.3s, color 0.3s;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.app {
min-height: 100vh;
display: flex;
flex-direction: column;
}
.app-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem 2rem;
border-bottom: 1px solid var(--border-color);
background-color: var(--card-bg);
}
.app-title {
display: flex;
align-items: center;
gap: 8px;
font-size: 1.5rem;
font-weight: 700;
}
.title-icon {
font-size: 1.75rem;
}
.app-main {
flex: 1;
padding: 2rem;
max-width: 1200px;
margin: 0 auto;
width: 100%;
}
.app-description {
text-align: center;
color: var(--text-secondary);
margin-bottom: 1.5rem;
}
.app-footer {
text-align: center;
padding: 1rem;
border-top: 1px solid var(--border-color);
font-size: 0.85rem;
color: var(--text-secondary);
}
.app-footer .excellent { color: #22c55e; }
.app-footer .good { color: #eab308; }
.app-footer .poor { color: #ef4444; }
@media (max-width: 768px) {
.app-header {
padding: 1rem;
}
.app-title {
font-size: 1.25rem;
}
.app-main {
padding: 1rem;
}
}

1
src/client/vite-env.d.ts vendored Normal file
View File

@@ -0,0 +1 @@
/// <reference types="vite/client" />

172
src/server/index.ts Normal file
View File

@@ -0,0 +1,172 @@
import express, { Request, Response } from 'express'
import cors from 'cors'
import rateLimit from 'express-rate-limit'
import ipaddr from 'ipaddr.js'
const app = express()
const PORT = process.env.PORT || 3000
const GLOBALPING_API = 'https://api.globalping.io/v1'
app.use(express.json())
app.use(cors({ origin: 'http://localhost:5173' }))
app.use(rateLimit({
windowMs: 60 * 1000,
limit: 10,
message: { error: 'Rate limit exceeded' }
}))
interface GlobalPingLocation {
country: string
city?: string
}
const NODE_LOCATIONS: Record<string, GlobalPingLocation> = {
'us-west': { country: 'US', city: 'San Francisco' },
'us-east': { country: 'US', city: 'New York' },
'europe': { country: 'DE', city: 'Frankfurt' },
'asia': { country: 'JP', city: 'Tokyo' },
'south-america': { country: 'BR', city: 'Sao Paulo' },
'africa': { country: 'ZA', city: 'Cape Town' },
'oceania': { country: 'AU', city: 'Sydney' }
}
function extractClientIp(req: Request): string | null {
const forwarded = req.headers['x-forwarded-for']
const raw = typeof forwarded === 'string' ? forwarded.split(',')[0].trim() : req.socket.remoteAddress
if (!raw) return null
const normalized = raw.replace(/^::ffff:/, '')
if (ipaddr.isValid(normalized)) return normalized
return null
}
function isPublicIp(ip: string): boolean {
if (!ipaddr.isValid(ip)) return false
const parsed = ipaddr.parse(ip)
return parsed.range() === 'unicast'
}
interface MeasurementResponse {
id: string
probesCount: number
}
interface MeasurementResult {
id: string
type: string
status: 'in-progress' | 'finished'
results?: Array<{
probe: {
continent: string
country: string
city: string
asn: number
network: string
}
result: {
status: string
rawOutput: string
stats?: {
min: number
max: number
avg: number
total: number
loss: number
}
}
}>
}
async function createMeasurement(target: string, location: GlobalPingLocation): Promise<string> {
const res = await fetch(`${GLOBALPING_API}/measurements`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept-Encoding': 'gzip',
'User-Agent': 'LatencyTest/1.0.0'
},
body: JSON.stringify({
type: 'ping',
target,
locations: [location],
measurementOptions: {
packets: 3
}
})
})
if (!res.ok) {
const error = await res.json().catch(() => ({})) as { error?: { message?: string } }
throw new Error(error.error?.message || `GlobalPing API error: ${res.status}`)
}
const data = await res.json() as MeasurementResponse
return data.id
}
async function getMeasurementResult(id: string, timeout = 30000): Promise<{ latency: number | null; success: boolean }> {
const startTime = Date.now()
while (Date.now() - startTime < timeout) {
await new Promise(r => setTimeout(r, 500))
const res = await fetch(`${GLOBALPING_API}/measurements/${id}`, {
headers: {
'Accept-Encoding': 'gzip',
'User-Agent': 'LatencyTest/1.0.0'
}
})
if (!res.ok) {
throw new Error(`Failed to get measurement: ${res.status}`)
}
const data = await res.json() as MeasurementResult
if (data.status !== 'in-progress') {
const result = data.results?.[0]?.result
if (result?.status === 'finished' && result.stats?.avg != null) {
return { latency: Math.round(result.stats.avg), success: true }
}
return { latency: null, success: false }
}
}
return { latency: null, success: false }
}
app.get('/api/ip', (req: Request, res: Response) => {
const ip = extractClientIp(req)
if (!ip) {
return res.status(500).json({ error: 'Unable to determine IP' })
}
res.json({ ip })
})
app.post('/api/latency', async (req: Request, res: Response) => {
const { targetIp, nodeId } = req.body
if (!targetIp || typeof targetIp !== 'string') {
return res.status(400).json({ error: 'targetIp is required' })
}
if (!nodeId || !NODE_LOCATIONS[nodeId]) {
return res.status(400).json({ error: `Invalid nodeId. Available: ${Object.keys(NODE_LOCATIONS).join(', ')}` })
}
if (!isPublicIp(targetIp)) {
return res.status(400).json({ error: 'Invalid or private IP address' })
}
try {
const measurementId = await createMeasurement(targetIp, NODE_LOCATIONS[nodeId])
const { latency, success } = await getMeasurementResult(measurementId)
res.json({ nodeId, latency, success })
} catch (error) {
console.error('Latency test error:', error)
res.status(500).json({ nodeId, latency: null, success: false })
}
})
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`)
})

32
src/shared/types.js Normal file
View File

@@ -0,0 +1,32 @@
export const LATENCY_THRESHOLDS = {
excellent: 50,
good: 150,
poor: Infinity,
};
export const TEST_NODES = [
{ id: 'us-west', name: 'US West', region: 'North America', coords: [-122.4194, 37.7749] },
{ id: 'us-east', name: 'US East', region: 'North America', coords: [-74.006, 40.7128] },
{ id: 'europe', name: 'Frankfurt', region: 'Europe', coords: [8.6821, 50.1109] },
{ id: 'asia', name: 'Tokyo', region: 'Asia', coords: [139.6917, 35.6895] },
{ id: 'south-america', name: 'São Paulo', region: 'South America', coords: [-46.6333, -23.5505] },
{ id: 'africa', name: 'Cape Town', region: 'Africa', coords: [18.4241, -33.9249] },
{ id: 'oceania', name: 'Sydney', region: 'Oceania', coords: [151.2093, -33.8688] },
];
export function getLatencyLevel(latency) {
if (latency === null)
return 'poor';
if (latency < LATENCY_THRESHOLDS.excellent)
return 'excellent';
if (latency < LATENCY_THRESHOLDS.good)
return 'good';
return 'poor';
}
export function getLatencyColor(latency) {
const level = getLatencyLevel(latency);
const colors = {
excellent: '#22c55e',
good: '#eab308',
poor: '#ef4444',
};
return colors[level];
}

47
src/shared/types.ts Normal file
View File

@@ -0,0 +1,47 @@
export interface TestNode {
id: string
name: string
region: string
coords: [number, number] // [longitude, latitude]
}
export interface LatencyResult {
nodeId: string
latency: number | null
status: 'pending' | 'testing' | 'success' | 'failed'
}
export type LatencyLevel = 'excellent' | 'good' | 'poor'
export const LATENCY_THRESHOLDS = {
excellent: 50,
good: 150,
poor: Infinity,
} as const
export const TEST_NODES: TestNode[] = [
{ id: 'us-west', name: 'US West', region: 'North America', coords: [-122.4194, 37.7749] },
{ id: 'us-east', name: 'US East', region: 'North America', coords: [-74.006, 40.7128] },
{ id: 'europe', name: 'Frankfurt', region: 'Europe', coords: [8.6821, 50.1109] },
{ id: 'asia', name: 'Tokyo', region: 'Asia', coords: [139.6917, 35.6895] },
{ id: 'south-america', name: 'São Paulo', region: 'South America', coords: [-46.6333, -23.5505] },
{ id: 'africa', name: 'Cape Town', region: 'Africa', coords: [18.4241, -33.9249] },
{ id: 'oceania', name: 'Sydney', region: 'Oceania', coords: [151.2093, -33.8688] },
]
export function getLatencyLevel(latency: number | null): LatencyLevel {
if (latency === null) return 'poor'
if (latency < LATENCY_THRESHOLDS.excellent) return 'excellent'
if (latency < LATENCY_THRESHOLDS.good) return 'good'
return 'poor'
}
export function getLatencyColor(latency: number | null): string {
const level = getLatencyLevel(latency)
const colors: Record<LatencyLevel, string> = {
excellent: '#22c55e',
good: '#eab308',
poor: '#ef4444',
}
return colors[level]
}

25
tsconfig.client.json Normal file
View File

@@ -0,0 +1,25 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"paths": {
"@/*": ["./src/client/*"],
"@shared/*": ["./src/shared/*"]
}
},
"include": ["src/client", "src/shared"],
"references": [{ "path": "./tsconfig.node.json" }]
}

7
tsconfig.json Normal file
View File

@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.client.json" },
{ "path": "./tsconfig.server.json" }
]
}

10
tsconfig.node.json Normal file
View File

@@ -0,0 +1,10 @@
{
"compilerOptions": {
"composite": true,
"skipLibCheck": true,
"module": "ESNext",
"moduleResolution": "bundler",
"allowSyntheticDefaultImports": true
},
"include": ["vite.config.ts"]
}

17
tsconfig.server.json Normal file
View File

@@ -0,0 +1,17 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ES2022",
"moduleResolution": "node",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"outDir": "dist/server",
"rootDir": "src",
"baseUrl": ".",
"paths": {
"@shared/*": ["./src/shared/*"]
}
},
"include": ["src/server/**/*", "src/shared/**/*"]
}

2
vite.config.d.ts vendored Normal file
View File

@@ -0,0 +1,2 @@
declare const _default: import("vite").UserConfig;
export default _default;

25
vite.config.js Normal file
View File

@@ -0,0 +1,25 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import path from 'path';
export default defineConfig({
plugins: [react()],
root: '.',
publicDir: 'public',
build: {
outDir: 'dist/client',
},
server: {
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
},
},
},
resolve: {
alias: {
'@': path.resolve(__dirname, 'src/client'),
'@shared': path.resolve(__dirname, 'src/shared'),
},
},
});

26
vite.config.ts Normal file
View File

@@ -0,0 +1,26 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import path from 'path'
export default defineConfig({
plugins: [react()],
root: '.',
publicDir: 'public',
build: {
outDir: 'dist/client',
},
server: {
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
},
},
},
resolve: {
alias: {
'@': path.resolve(__dirname, 'src/client'),
'@shared': path.resolve(__dirname, 'src/shared'),
},
},
})