Compare commits

...

40 Commits
doc ... main

Author SHA1 Message Date
wang ze yao df0a52ceb5 v1.0
6 months ago
pfio43gvp 4def465034 Delete 'doc/软件需求规格说明书.docx'
6 months ago
pfio43gvp fa7e9a184a Delete 'doc/无人机敌我识别系统设计文档.docx'
6 months ago
pfio43gvp 26e42218a6 Delete '333'
6 months ago
pfio43gvp ae4c4a4a66 Delete '软件需求规格说明书.docx'
6 months ago
pfio43gvp 04c22dd742 Merge pull request '333' (#5) from wzy into main
6 months ago
pfio43gvp 31748e7bf1 Add 333
6 months ago
pfio43gvp c70ef322fb Delete '123'
6 months ago
pfio43gvp b51a830223 Merge pull request '123' (#4) from wzy into main
6 months ago
pfio43gvp 7a03de5158 Add 123
6 months ago
pfio43gvp 297bf34da8 Delete '123'
6 months ago
pfio43gvp 04577d493b Add 123
6 months ago
“jiuan” 9763990965 v2.2
6 months ago
xuyuanpeng22 cd180106ab Merge branch 'main' of https://bdgit.educoder.net/pfio42gvp/wangzeyao
6 months ago
xuyuanpeng22 116a824093 delete
6 months ago
pka3vx8jw a61886e630 Delete 'src/yolo测试代码/requirements.txt'
6 months ago
xuyuanpeng22 9e40b3b443 delete
6 months ago
wang ze yao 0ebae78438 源代码
6 months ago
pka3vx8jw 4ec412e421 Merge pull request 'yolo模型1.0' (#2) from 王琰 into main
6 months ago
“jiuan” b52d780bcf delete
6 months ago
“jiuan” 863aafaace V2.1
6 months ago
“jiuan” 9c1d15ea24 完全合并王琰分支(强制使用其版本)
6 months ago
pr3xei76a 919972e4dd Merge pull request 'pr' (#3) from xyp.branch into main
6 months ago
xuyuanpeng22 3090f7e1a2 3.0
6 months ago
xuyuanpeng22 075c317354 delete
6 months ago
xuyuanpeng22 95bbc27902 delete
6 months ago
xuyuanpeng22 d255a833a7 delete
6 months ago
“jiuan” 75d2daa3e0 V2.0
6 months ago
xuyuanpeng22 f5c7f7156f 2.0
6 months ago
xuyuanpeng22 4cbada2119 delete
6 months ago
xuyuanpeng22 339f989f57 前端
6 months ago
xuyuanpeng22 4195d39530 前端
6 months ago
xuyuanpeng22 5f8b8fc956 前端
6 months ago
xuyuanpeng22 d19811752f 前端
6 months ago
“jiuan” e320c1145c v1.0
6 months ago
“jiuan” 7e2c0a808c 文档
9 months ago
pfio43gvp 9a69f18e12 ADD file via upload
10 months ago
pfio43gvp 0048152c03 Delete '软件需求规格说明书.docx'
10 months ago
pfio43gvp 5d7a55dad5 Delete '“军事训练动作识别系统”的需求构思及描述.docx'
10 months ago
pfio43gvp 0dd117618f ADD file via upload
10 months ago

@ -0,0 +1 @@
Subproject commit 20196b57d0285856d2b9e9ef095beb39d0643c8e

@ -0,0 +1,63 @@
# MQTT与ATOMS3通信说明
## 功能概述
本系统通过MQTT实现前端界面与ATOMS3设备之间的通信功能。当用户在前端信号识别界面点击"发送身份请求消息"按钮时系统会通过MQTT向ATOMS3设备发送消息ATOMS3设备接收到消息后会自动回复并显示在前端界面上。
## 使用方法
1. **启动前端服务器**
```bash
cd 无人机
python serve_frontend.py
```
2. **访问信号识别界面**
在浏览器中访问 http://localhost:8000/encryption.html
3. **发送消息给ATOMS3**
- 可以在"文本内容"框中输入任意消息,使用加密功能加密后发送
- 也可以直接点击"发送身份请求消息"按钮,发送默认的身份请求
- 系统会自动通过MQTT将消息发送到topic: `atoms3-1`
4. **查看ATOMS3回复**
- ATOMS3设备收到消息后会自动处理并回复
- 回复的消息会发送到topic: `atoms3-1/response`
- 点击右侧的"接收身份确认消息"按钮可以查看最新回复
## MQTT配置说明
系统使用以下MQTT配置
- MQTT服务器broker.emqx.io
- 端口1883
- 客户端ID随机生成
- 发布主题atoms3-1
- 订阅主题atoms3-1/response
## ATOMS3设备说明
ATOMS3设备已通过UIFlow2编程实现以下功能
- 连接WIFI并自动连接MQTT服务器
- 监听主题`atoms3-1`接收消息
- 根据消息内容作出不同响应:
- 如果收到包含"id"的消息会亮红灯并回复设备ID
- 其他消息会亮蓝灯并发送确认信息
- 所有回复都会发送到主题`atoms3-1/response`
## 注意事项
1. 确保ATOMS3设备已正确烧录了代码并连接到网络
2. ATOMS3设备和前端需要使用相同的MQTT服务器和主题
3. 若连接失败可能需要检查网络连接或重启ATOMS3设备
## 故障排除
1. 如果消息发送失败,请检查:
- 前端是否成功连接到MQTT服务器
- ATOMS3设备是否在线
- 网络连接是否正常
2. 如果没有收到ATOMS3回复请检查
- ATOMS3设备是否成功连接到WIFI和MQTT
- 前端是否正确订阅了响应主题
- 尝试重启ATOMS3设备

@ -0,0 +1,53 @@
# jiamisuanfa.py 中各加密算法行数统计
## 经典加密算法
ClassicalCipher: 531 行 (凯撒密码、维吉尼亚密码、Playfair密码等)
## 现代对称加密算法
ModernSymmetricCipher: 31 行 (XOR加密)
StreamCipher: 42 行 (RC4流密码)
BlockCipher: 64 行 (分组密码基础)
DES: 278 行 (数据加密标准)
AES: 304 行 (高级加密标准)
Blowfish: 217 行
Serpent: 143 行
ChaCha20: 137 行
SEAL: 134 行
SNOW: 163 行
## AEAD加密模式
ChaCha20Poly1305: 75 行
AES_GCM: 159 行
AES_CCM: 168 行
AES_EAX: 137 行
AES_OCB: 210 行
AES_SIV: 165 行
## MAC/认证算法
Poly1305: 43 行
## 非对称加密算法
RSA: 210 行
ECC: 286 行
## 哈希算法
HashFunctions: 48 行 (MD5, SHA1, SHA256等基础哈希)
SHA3: 189 行
Blake2: 177 行
Whirlpool: 198 行 (根据前后类推算)
RIPEMD160: 142 行 (根据前后类推算)
Tiger: 74 行
## 数学工具类
BigNumber: 198 行
FiniteField: 344 行
EllipticCurve: 396 行
StandardCurves: 123 行
Ed25519: 140 行
## 辅助类/基类
CryptoError: 3 行
InvalidKeyError: 3 行
InvalidInputError: 4 行
CryptoResult: 5 行
CryptoBase: 22 行

@ -0,0 +1,318 @@
import http.server
import socketserver
import json
import sys
import os
from urllib.parse import parse_qs, urlparse
# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
# 导入加密算法
from jiamisuanfa import (
ClassicalCipher, ModernSymmetricCipher,
StreamCipher, HashFunctions, BlockCipher,
AES, DES, Blowfish
)
# 设置服务器端口
PORT = 5001
# 自定义处理器支持POST请求和CORS
class APIHandler(http.server.SimpleHTTPRequestHandler):
def end_headers(self):
# 添加CORS头
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
self.send_header('Access-Control-Allow-Headers', 'Content-Type, Authorization')
super().end_headers()
def do_OPTIONS(self):
# 处理OPTIONS请求
self.send_response(200)
self.end_headers()
def do_GET(self):
# 处理GET请求主要用于/api/algorithms
if self.path == '/api/algorithms':
response = self.handle_get_algorithms()
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps(response).encode('utf-8'))
else:
# 对于非API请求,使用默认处理
super().do_GET()
def do_POST(self):
# 处理POST请求
if self.path.startswith('/api/'):
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length).decode('utf-8')
try:
data = json.loads(post_data)
response = self.handle_api(self.path, data)
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps(response).encode('utf-8'))
except Exception as e:
self.send_response(500)
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({"success": False, "error": str(e)}).encode('utf-8'))
else:
# 对于非API请求,使用默认处理
super().do_POST()
def handle_api(self, path, data):
# API路由处理
if path == '/api/encrypt':
return self.handle_encrypt(data)
elif path == '/api/decrypt':
return self.handle_decrypt(data)
else:
return {"success": False, "error": "Unknown API endpoint"}
def handle_get_algorithms(self):
# 返回可用的算法列表
algorithms = {
"classical": ["caesar", "vigenere", "playfair", "hill", "affine", "permutation", "autokey", "beaufort"],
"modern": ["xor"],
"stream": ["rc4"],
"hash": ["md5", "sha1", "sha256", "sha512", "hmac_sha256"],
"block": ["aes", "des", "blowfish"]
}
return {"success": True, "algorithms": algorithms}
def handle_encrypt(self, data):
# 处理加密请求
method = data.get('method')
text = data.get('text', '')
key = data.get('key', '')
category = data.get('category', 'classical')
result = {"success": True}
try:
# 经典加密
if category == "classical":
if method == 'caesar':
shift = int(key) if key else 3
result['data'] = ClassicalCipher.caesar_encrypt(text, shift)
elif method == 'vigenere':
result['data'] = ClassicalCipher.vigenere_encrypt(text, key)
elif method == 'playfair':
result['data'] = ClassicalCipher.playfair_encrypt(text, key)
elif method == 'hill':
block_size = int(data.get('blockSize', 2))
result['data'] = ClassicalCipher.hill_encrypt(text, key, block_size)
elif method == 'affine':
params = key.split(',')
if len(params) != 2:
raise ValueError("仿射密码需要两个参数格式a,b")
a, b = int(params[0]), int(params[1])
result['data'] = ClassicalCipher.affine_encrypt(text, a, b)
elif method == 'permutation':
try:
key_list = [int(k) for k in key.split(',')]
result['data'] = ClassicalCipher.permutation_encrypt(text, key_list)
except:
raise ValueError("置换密码需要数字列表例如1,3,0,2")
elif method == 'autokey':
result['data'] = ClassicalCipher.autokey_encrypt(text, key)
elif method == 'beaufort':
result['data'] = ClassicalCipher.beaufort_encrypt(text, key)
else:
result['success'] = False
result['error'] = f"不支持的算法: {method}"
# 现代对称加密
elif category == "modern":
if method == 'xor':
key_bytes = key.encode('utf-8')
data_bytes = text.encode('utf-8')
encrypted = ModernSymmetricCipher.xor_encrypt(data_bytes, key_bytes)
result['data'] = encrypted.hex()
else:
result['success'] = False
result['error'] = f"不支持的算法: {method}"
# 流密码
elif category == "stream":
if method == 'rc4':
stream_cipher = StreamCipher()
key_bytes = key.encode('utf-8')
data_bytes = text.encode('utf-8')
encrypted = stream_cipher.rc4_encrypt(data_bytes, key_bytes)
result['data'] = encrypted.hex()
else:
result['success'] = False
result['error'] = f"不支持的算法: {method}"
# 哈希函数
elif category == "hash":
if method == 'md5':
result['data'] = HashFunctions.md5(text)
elif method == 'sha1':
result['data'] = HashFunctions.sha1(text)
elif method == 'sha256':
result['data'] = HashFunctions.sha256(text)
elif method == 'sha512':
result['data'] = HashFunctions.sha512(text)
elif method == 'hmac_sha256':
result['data'] = HashFunctions.hmac_sha256(key, text)
else:
result['success'] = False
result['error'] = f"不支持的算法: {method}"
# 块密码
elif category == "block":
data_bytes = text.encode('utf-8')
key_bytes = key.encode('utf-8')
if method == 'aes':
aes = AES()
encrypted = aes.encrypt(data_bytes, key_bytes)
result['data'] = encrypted.hex()
elif method == 'des':
des = DES()
encrypted = des.encrypt(data_bytes, key_bytes)
result['data'] = encrypted.hex()
elif method == 'blowfish':
blowfish = Blowfish()
encrypted = blowfish.encrypt(data_bytes, key_bytes)
result['data'] = encrypted.hex()
else:
result['success'] = False
result['error'] = f"不支持的算法: {method}"
else:
result['success'] = False
result['error'] = f"不支持的算法类别: {category}"
except Exception as e:
result['success'] = False
result['error'] = str(e)
return result
def handle_decrypt(self, data):
# 处理解密请求
method = data.get('method')
text = data.get('text', '')
key = data.get('key', '')
category = data.get('category', 'classical')
result = {"success": True}
try:
# 经典解密
if category == "classical":
if method == 'caesar':
shift = int(key) if key else 3
result['data'] = ClassicalCipher.caesar_decrypt(text, shift)
elif method == 'vigenere':
result['data'] = ClassicalCipher.vigenere_decrypt(text, key)
elif method == 'playfair':
result['data'] = ClassicalCipher.playfair_decrypt(text, key)
elif method == 'hill':
block_size = int(data.get('blockSize', 2))
result['data'] = ClassicalCipher.hill_decrypt(text, key, block_size)
elif method == 'affine':
params = key.split(',')
if len(params) != 2:
raise ValueError("仿射密码需要两个参数格式a,b")
a, b = int(params[0]), int(params[1])
result['data'] = ClassicalCipher.affine_decrypt(text, a, b)
elif method == 'permutation':
try:
key_list = [int(k) for k in key.split(',')]
result['data'] = ClassicalCipher.permutation_decrypt(text, key_list)
except:
raise ValueError("置换密码需要数字列表例如1,3,0,2")
elif method == 'autokey':
result['data'] = ClassicalCipher.autokey_decrypt(text, key)
elif method == 'beaufort':
result['data'] = ClassicalCipher.beaufort_decrypt(text, key)
else:
result['success'] = False
result['error'] = f"不支持的算法: {method}"
# 现代对称解密
elif category == "modern":
if method == 'xor':
key_bytes = key.encode('utf-8')
data_bytes = bytes.fromhex(text)
decrypted = ModernSymmetricCipher.xor_decrypt(data_bytes, key_bytes)
result['data'] = decrypted.decode('utf-8', errors='replace')
else:
result['success'] = False
result['error'] = f"不支持的算法: {method}"
# 流密码解密
elif category == "stream":
if method == 'rc4':
stream_cipher = StreamCipher()
key_bytes = key.encode('utf-8')
data_bytes = bytes.fromhex(text)
decrypted = stream_cipher.rc4_decrypt(data_bytes, key_bytes)
result['data'] = decrypted.decode('utf-8', errors='replace')
else:
result['success'] = False
result['error'] = f"不支持的算法: {method}"
# 哈希函数不可解密
elif category == "hash":
result['success'] = False
result['error'] = "哈希函数是单向的,无法解密"
# 块密码解密
elif category == "block":
try:
data_bytes = bytes.fromhex(text)
key_bytes = key.encode('utf-8')
if method == 'aes':
aes = AES()
decrypted = aes.decrypt(data_bytes, key_bytes)
result['data'] = decrypted.decode('utf-8', errors='replace')
elif method == 'des':
des = DES()
decrypted = des.decrypt(data_bytes, key_bytes)
result['data'] = decrypted.decode('utf-8', errors='replace')
elif method == 'blowfish':
blowfish = Blowfish()
decrypted = blowfish.decrypt(data_bytes, key_bytes)
result['data'] = decrypted.decode('utf-8', errors='replace')
else:
result['success'] = False
result['error'] = f"不支持的算法: {method}"
except Exception as e:
result['success'] = False
result['error'] = f"解密失败: {str(e)}"
else:
result['success'] = False
result['error'] = f"不支持的算法类别: {category}"
except Exception as e:
result['success'] = False
result['error'] = str(e)
return result
print(f"API服务器启动在 http://localhost:{PORT}")
print("请在浏览器中访问上述地址")
print("按 Ctrl+C 可以停止服务器")
# 创建HTTP服务器
try:
httpd = socketserver.TCPServer(("", PORT), APIHandler)
# 启动服务器
httpd.serve_forever()
except OSError as e:
if e.errno == 10048: # 端口被占用
print(f"错误: 端口 {PORT} 已被占用,请关闭占用该端口的程序后再试")
else:
print(f"服务器启动错误: {e}")
except KeyboardInterrupt:
print("\n服务器已停止")

@ -0,0 +1,52 @@
@echo off
echo 开始清理不需要的文件...
REM 删除视频流相关文件
del /q capture_ffplay.ps1 capture_rtmp_stream.bat capture_window.cmd capture_full_window.ps1 2>nul
del /q run_rtmp_stream.bat start_rtmp_stream.bat start_rtmp_test.bat start_rtmp_to_http.bat rtmp_to_http.py 2>nul
del /q stream_to_file.bat direct_vlc_view.html screenshot.ps1 ffplay_screenshot.png ffplay_fullscreen.png 2>nul
del /q simple_rtmp_test.bat start_ffmpeg_rtmp.bat node-media-server.js 2>nul
del /q run_capture.ps1 capture_api.py start_capture_api.bat start_capture_api.ps1 2>nul
REM 删除VLC相关文件
del /q vlc_capture_yolo.py vlc_to_hls.py enable_vlc_http.bat check_vlc_yolo_connection.py 2>nul
del /q start_vlc_ffmpeg.bat start_vlc_rtsp.bat start_vlc_yolo_api.bat start_vlc_yolo_detection.bat 2>nul
del /q install_vlc_yolo_dependencies.bat "VLC接口使用指南.md" "VLC视频截图识别使用说明.md" 2>nul
del /q "VLC视频流集成说明.md" "VLC配置指南.md" "启用VLC_HTTP接口.bat" 2>nul
REM 删除大疆直播相关文件
del /q start_dji_air3_all.bat start_dji_air3_rtmp.bat start_dji_air3_stream.bat dji_stream_api.py 2>nul
del /q "大疆Air3无人机视频流识别系统使用说明.md" 2>nul
REM 删除打包封装相关文件
del /q build_app.py package_app.py prepare_release.bat "准备发布包.bat" "打包应用.bat" 2>nul
REM 删除其他相关文件
del /q "无人机视频流连接问题解决方案.md" "检查RTMP服务器.bat" start_video_viewer.bat 2>nul
REM 删除YOLO相关文件
del /q yolo_api.py start_yolo_api.bat start_yolo_api.ps1 yolo_requirements.txt 2>nul
REM 删除多余的启动文件
del /q start_all_services.bat start_all_with_video.bat start_app.bat 2>nul
del /q start_camera.bat start_console_app.bat start_pure_console.bat start_qt_app.bat 2>nul
del /q start_standalone_app.bat "启动系统.bat" "启动无人机识别系统.bat" "一键启动.bat" test_login.bat 2>nul
del /q stop_all_services.bat 2>nul
REM 删除前端视频流相关文件
cd frontend
del /q rtmp_test.html video_stream.html video_player.html hls_player.html direct_video.html 2>nul
del /q "VLC接口使用指南.md" "VLC控制器.html" "启用VLC_HTTP接口.bat" 2>nul
cd common\js
del /q rtmp_player.js 2>nul
cd ..\..\..
echo.
echo 注意:请手动删除以下目录(如果需要):
echo 1. 项目根目录上级目录中的"无人机yolov8"文件夹
echo 2. 当前目录中的"detection_results"文件夹
echo 3. "无人机"目录下的所有冗余子目录
echo.
echo 清理完成!
pause

@ -0,0 +1,9 @@
2025-07-09 19:37:40,422 - DroneApp - INFO - 启动服务: backend_server
2025-07-09 19:37:40,425 - DroneApp - INFO - 服务 backend_server 已启动PID: 2776
2025-07-09 19:37:40,426 - DroneApp - INFO - 启动服务: frontend_server
2025-07-09 19:37:40,429 - DroneApp - INFO - 服务 frontend_server 已启动PID: 13144
2025-07-09 19:37:40,429 - DroneApp - INFO - 启动服务: video_server
2025-07-09 19:37:40,432 - DroneApp - INFO - 服务 video_server 已启动PID: 3740
2025-07-09 19:37:41,433 - DroneApp - INFO - 服务 backend_server 正常退出
2025-07-09 19:37:41,434 - DroneApp - INFO - 服务 frontend_server 正常退出
2025-07-09 19:37:47,437 - DroneApp - INFO - 服务 video_server 正常退出

@ -0,0 +1,179 @@
from ultralytics import YOLO
import cv2
import os
import argparse
import time
def parse_args():
parser = argparse.ArgumentParser(description='无人机检测应用')
parser.add_argument('--model', type=str, default='drone2/weights/best.pt', help='模型路径')
parser.add_argument('--source', type=str, default='0', help='输入源 (0=摄像头, 路径=图像/视频文件, 或文件夹路径)')
parser.add_argument('--conf', type=float, default=0.25, help='置信度阈值')
parser.add_argument('--save', action='store_true', help='保存结果')
parser.add_argument('--view', action='store_true', help='实时查看结果')
return parser.parse_args()
def process_camera(model, conf, save, view):
"""处理摄像头输入"""
cap = cv2.VideoCapture(0)
if not cap.isOpened():
print("错误: 无法打开摄像头")
return
while True:
ret, frame = cap.read()
if not ret:
print("无法获取帧")
break
# 使用模型进行预测
results = model.predict(source=frame, conf=conf, verbose=False)
# 处理结果
annotated_frame = results[0].plot()
# 显示结果
if view:
cv2.imshow("无人机检测", annotated_frame)
# 如果按下 'q' 键则退出
if cv2.waitKey(1) == ord('q'):
break
# 释放资源
cap.release()
cv2.destroyAllWindows()
def process_video(model, source, conf, save, view):
"""处理视频文件"""
cap = cv2.VideoCapture(source)
if not cap.isOpened():
print(f"错误: 无法打开视频文件 {source}")
return
# 获取视频属性
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = cap.get(cv2.CAP_PROP_FPS)
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
# 设置输出视频
output = None
if save:
output_path = f"output_{os.path.basename(source)}"
output = cv2.VideoWriter(output_path,
cv2.VideoWriter_fourcc(*'mp4v'),
fps, (width, height))
frame_count = 0
start_time = time.time()
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
frame_count += 1
# 使用模型进行预测
results = model.predict(source=frame, conf=conf, verbose=False)
# 处理结果
annotated_frame = results[0].plot()
# 保存结果
if save and output is not None:
output.write(annotated_frame)
# 显示结果
if view:
cv2.imshow("无人机检测", annotated_frame)
# 计算和显示进度
elapsed_time = time.time() - start_time
fps_current = frame_count / elapsed_time if elapsed_time > 0 else 0
progress = frame_count / total_frames * 100 if total_frames > 0 else 0
print(f"\r处理中: {frame_count}/{total_frames} 帧 ({progress:.1f}%) - {fps_current:.1f} FPS", end="")
# 如果按下 'q' 键则退出
if cv2.waitKey(1) == ord('q'):
break
# 释放资源
cap.release()
if output is not None:
output.release()
cv2.destroyAllWindows()
print(f"\n处理完成! 处理了 {frame_count} 帧,平均 {frame_count / elapsed_time:.1f} FPS")
if save:
print(f"输出已保存到: {output_path}")
def process_image(model, source, conf, save, view):
"""处理单个图像或图像文件夹"""
# 检查source是文件夹还是单个文件
if os.path.isdir(source):
# 处理文件夹中的所有图像
image_files = [os.path.join(source, f) for f in os.listdir(source)
if f.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp'))]
for img_path in image_files:
process_single_image(model, img_path, conf, save, view)
else:
# 处理单个图像
process_single_image(model, source, conf, save, view)
def process_single_image(model, img_path, conf, save, view):
"""处理单个图像文件"""
# 使用模型进行预测
results = model.predict(source=img_path, conf=conf)
# 获取结果
result = results[0]
# 输出检测结果
num_drones = len(result.boxes)
print(f"图像 {os.path.basename(img_path)}: 检测到 {num_drones} 个无人机")
# 获取标注后的图像
img = cv2.imread(img_path)
annotated_img = result.plot()
# 保存结果
if save:
output_dir = "results"
os.makedirs(output_dir, exist_ok=True)
output_path = os.path.join(output_dir, f"detected_{os.path.basename(img_path)}")
cv2.imwrite(output_path, annotated_img)
print(f"结果已保存到: {output_path}")
# 显示结果
if view:
cv2.imshow(f"检测结果 - {os.path.basename(img_path)}", annotated_img)
print("按任意键继续...")
cv2.waitKey(0)
cv2.destroyAllWindows()
def main():
# 解析命令行参数
args = parse_args()
# 加载模型
print(f"正在加载模型: {args.model}")
model = YOLO(args.model)
# 处理不同类型的输入
source = args.source
if source.isdigit(): # 摄像头输入
process_camera(model, args.conf, args.save, True)
elif os.path.isfile(source) and source.lower().endswith(('.mp4', '.avi', '.mov')): # 视频文件
process_video(model, source, args.conf, args.save, args.view)
else: # 图像或图像文件夹
process_image(model, source, args.conf, args.save, args.view)
if __name__ == "__main__":
main()

@ -0,0 +1,56 @@
<!-- 状态卡片 -->
<div class="row g-3 mb-4">
<!-- 识别目标数 -->
<div class="col-md-4">
<div class="status-card executing">
<div class="card-header">
<div class="card-title">识别目标数</div>
<div class="card-tools">
<button class="btn btn-sm btn-refresh-stats" title="刷新统计数据">
<i class="fas fa-sync-alt"></i>
</button>
</div>
</div>
<div class="card-body">
<div class="status-value">0</div>
<div class="mini-chart"></div>
</div>
</div>
</div>
<!-- 友方目标数 -->
<div class="col-md-4">
<div class="status-card friendly">
<div class="card-header">
<div class="card-title">友方目标数</div>
<div class="card-tools">
<button class="btn btn-sm btn-refresh-stats" title="刷新统计数据">
<i class="fas fa-sync-alt"></i>
</button>
</div>
</div>
<div class="card-body">
<div class="status-value">0</div>
<div class="mini-chart"></div>
</div>
</div>
</div>
<!-- 敌方目标数 -->
<div class="col-md-4">
<div class="status-card hostile">
<div class="card-header">
<div class="card-title">敌方目标数</div>
<div class="card-tools">
<button class="btn btn-sm btn-refresh-stats" title="刷新统计数据">
<i class="fas fa-sync-alt"></i>
</button>
</div>
</div>
<div class="card-body">
<div class="status-value">0</div>
<div class="mini-chart"></div>
</div>
</div>
</div>
</div>

@ -0,0 +1,902 @@
/* 全局样式 */
:root {
--primary-color: #1a2634;
--secondary-color: #2c3e50;
--accent-color: #00b4d8;
--text-color: #e9ecef;
--border-color: #2d4356;
--card-bg: rgba(26, 38, 52, 0.8);
--success-color: #2ecc71;
--warning-color: #f1c40f;
--danger-color: #e74c3c;
--info-color: #3498db;
--executing-color: #3498db;
--identification-color: #2ecc71;
--friendly-color: #27ae60;
--hostile-color: #e74c3c;
}
body {
font-family: 'Noto Sans SC', sans-serif;
background-color: var(--primary-color);
color: var(--text-color);
min-height: 100vh;
}
/* 登录页面样式 */
.login-page {
background:
linear-gradient(135deg, rgba(26, 38, 52, 0.92) 0%, rgba(44, 62, 80, 0.95) 100%),
url("data:image/svg+xml,%3Csvg width='100' height='100' viewBox='0 0 100 100' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg stroke='%230a4b78' stroke-width='1' stroke-opacity='0.1'%3E%3Cpath d='M50 0v100M0 50h100'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E"),
url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg stroke='%230a4b78' stroke-width='1' stroke-opacity='0.05'%3E%3Cpath d='M30 0v60M0 30h60'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E");
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
overflow: hidden;
position: relative;
}
/* 雷达动画效果 */
.radar-animation {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 100vw;
height: 100vw;
pointer-events: none;
z-index: 0;
}
.radar-spinner {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 80vw;
height: 80vw;
border: 1px solid rgba(0, 180, 216, 0.1);
border-radius: 50%;
}
.radar-spinner::before {
content: "";
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
border: 1px solid rgba(0, 180, 216, 0.05);
border-radius: 50%;
animation: pulse 4s infinite linear;
}
.radar-spinner::after {
content: "";
position: absolute;
top: -20px;
left: -20px;
right: -20px;
bottom: -20px;
border: 1px solid rgba(0, 180, 216, 0.03);
border-radius: 50%;
animation: pulse 8s infinite linear;
}
.radar-line {
position: absolute;
top: 0;
left: 50%;
height: 50%;
width: 2px;
background: linear-gradient(to top, rgba(0, 180, 216, 0.8), transparent);
transform-origin: bottom center;
animation: radar-sweep 8s infinite linear;
}
@keyframes radar-sweep {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
/* 登录容器 */
.login-container {
position: relative;
z-index: 10;
width: 100%;
max-width: 480px;
padding: 0 20px;
animation: fadeIn 0.8s ease-out;
}
.login-box {
background: rgba(26, 38, 52, 0.85);
border-radius: 10px;
border: 1px solid rgba(0, 180, 216, 0.2);
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2),
0 0 20px rgba(0, 180, 216, 0.1);
overflow: hidden;
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
animation: glow 3s infinite alternate;
}
.login-header {
padding: 2.5rem 2rem 1.5rem;
text-align: center;
position: relative;
overflow: hidden;
}
.login-header::before {
content: "";
position: absolute;
top: -10px;
left: -10px;
right: -10px;
height: 10px;
background: var(--accent-color);
box-shadow: 0 0 20px rgba(0, 180, 216, 0.5);
}
.login-header h2 {
font-size: 2.2rem;
font-weight: 600;
margin-top: 0.5rem;
margin-bottom: 0.5rem;
color: #ffffff;
text-shadow: 0 2px 10px rgba(0, 180, 216, 0.3);
letter-spacing: 1px;
}
.login-header p {
color: rgba(255, 255, 255, 0.7);
font-size: 0.9rem;
margin-bottom: 0;
}
.military-star {
font-size: 2rem;
color: var(--accent-color);
text-shadow: 0 0 15px rgba(0, 180, 216, 0.8);
animation: pulse 2s infinite;
display: inline-block;
}
.logo-icon {
background: rgba(0, 180, 216, 0.1);
width: 60px;
height: 60px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
margin: 0 auto 1rem;
border: 2px solid rgba(0, 180, 216, 0.3);
position: relative;
overflow: hidden;
}
.logo-icon::after {
content: "";
position: absolute;
top: 0;
left: -100%;
width: 50%;
height: 100%;
background: linear-gradient(
to right,
rgba(255, 255, 255, 0),
rgba(255, 255, 255, 0.3),
rgba(255, 255, 255, 0)
);
transform: skewX(-25deg);
animation: shine 3s infinite;
}
@keyframes shine {
0% {
left: -100%;
}
20% {
left: 100%;
}
100% {
left: 100%;
}
}
.login-form {
padding: 1.5rem 2rem 2rem;
}
.login-form .form-group {
margin-bottom: 1.5rem;
}
.login-form .form-control {
background-color: rgba(255, 255, 255, 0.08);
border: 1px solid rgba(0, 180, 216, 0.2);
color: white;
border-radius: 4px;
height: 50px;
font-size: 1rem;
transition: all 0.3s;
}
.login-form .form-control:focus {
background-color: rgba(255, 255, 255, 0.12);
border-color: var(--accent-color);
box-shadow: 0 0 0 0.2rem rgba(0, 180, 216, 0.25);
}
.login-form .input-group-text {
background-color: rgba(0, 180, 216, 0.1);
border: 1px solid rgba(0, 180, 216, 0.2);
color: var(--accent-color);
border-right: none;
}
.login-form .btn-primary {
background-color: var(--accent-color);
border-color: var(--accent-color);
font-weight: 600;
height: 50px;
font-size: 1.1rem;
transition: all 0.3s;
position: relative;
overflow: hidden;
}
.login-form .btn-primary:hover {
background-color: #0099b8;
border-color: #0099b8;
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(0, 180, 216, 0.4);
}
.login-form .btn-primary:active {
transform: translateY(0);
box-shadow: 0 2px 6px rgba(0, 180, 216, 0.3);
}
.login-form .form-check-label {
color: rgba(255, 255, 255, 0.7);
font-size: 0.9rem;
}
.login-form .form-check-input {
border-color: rgba(0, 180, 216, 0.3);
}
.login-form .form-check-input:checked {
background-color: var(--accent-color);
border-color: var(--accent-color);
}
.forgot-password {
color: var(--accent-color);
font-size: 0.9rem;
text-decoration: none;
}
.forgot-password:hover {
color: #0099b8;
text-decoration: underline;
}
.login-footer {
padding: 1rem 2rem;
background: rgba(0, 0, 0, 0.1);
border-top: 1px solid rgba(0, 180, 216, 0.1);
}
.login-footer small {
color: rgba(255, 255, 255, 0.6);
font-size: 0.85rem;
}
/* 战场主题 */
.battlefield-theme {
background:
linear-gradient(135deg, rgba(26, 38, 52, 0.95) 0%, rgba(44, 62, 80, 0.95) 100%),
url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%230a4b78' fill-opacity='0.1'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E"),
url("data:image/svg+xml,%3Csvg width='100' height='100' viewBox='0 0 100 100' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%230a4b78' fill-opacity='0.05'%3E%3Cpath d='M50 50l30-30M50 50l-30 30M50 50l30 30M50 50l-30-30'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E");
background-attachment: fixed;
}
/* 动画效果 */
@keyframes pulse {
0% {
transform: scale(1);
opacity: 1;
}
50% {
transform: scale(1.1);
opacity: 0.8;
}
100% {
transform: scale(1);
opacity: 1;
}
}
@keyframes fadeIn {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes glow {
0% {
box-shadow: 0 0 5px rgba(0, 180, 216, 0.2);
}
50% {
box-shadow: 0 0 20px rgba(0, 180, 216, 0.4);
}
100% {
box-shadow: 0 0 5px rgba(0, 180, 216, 0.2);
}
}
/* 主内容区域 */
.main-content {
margin-left: 250px;
padding: 1rem;
min-height: 100vh;
}
/* 侧边栏样式 */
.sidebar {
position: fixed;
left: 0;
top: 0;
bottom: 0;
width: 250px;
background-color: var(--secondary-color);
border-right: 1px solid var(--border-color);
padding: 1rem;
z-index: 1000;
}
.sidebar-header {
padding: 1rem 0;
border-bottom: 1px solid var(--border-color);
}
.sidebar-header h4 {
color: var(--text-color);
margin: 0;
display: flex;
align-items: center;
}
.logo-icon {
margin-right: 0.5rem;
color: var(--accent-color);
}
.nav-link {
color: var(--text-color);
padding: 0.8rem 1rem;
margin: 0.2rem 0;
border-radius: 5px;
transition: all 0.3s ease;
}
.nav-link:hover,
.nav-link.active {
background-color: var(--accent-color);
color: white;
}
.nav-link i {
margin-right: 0.5rem;
width: 20px;
text-align: center;
}
/* 战场头部 */
.battlefield-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 1rem;
padding: 0.5rem 1rem;
background: var(--card-bg);
border-radius: 10px;
border: 1px solid var(--border-color);
}
.header-left {
display: flex;
align-items: center;
gap: 1.5rem;
}
.battlefield-time {
display: flex;
align-items: center;
gap: 0.5rem;
color: var(--accent-color);
font-size: 0.9rem;
}
.operator-info {
display: flex;
align-items: center;
gap: 0.5rem;
color: var(--text-color);
}
.status-badge {
padding: 0.25rem 0.5rem;
border-radius: 20px;
font-size: 0.8rem;
font-weight: 500;
}
.status-badge.online {
background: rgba(46, 204, 113, 0.2);
color: var(--success-color);
}
.page-title {
color: var(--text-color);
margin: 0;
font-weight: 500;
}
/* 状态卡片 */
.status-cards {
margin-bottom: 1rem;
}
.status-cards .col-md-3,
.status-cards .col-md-4 {
padding: 0.4rem;
animation: fadeIn 0.5s ease-out forwards;
}
.status-cards .col-md-3:nth-child(1),
.status-cards .col-md-4:nth-child(1) { animation-delay: 0s; }
.status-cards .col-md-3:nth-child(2),
.status-cards .col-md-4:nth-child(2) { animation-delay: 0.2s; }
.status-cards .col-md-3:nth-child(3),
.status-cards .col-md-4:nth-child(3) { animation-delay: 0.4s; }
.status-cards .col-md-3:nth-child(4),
.status-cards .col-md-4:nth-child(4) { animation-delay: 0.6s; }
.status-card {
background: var(--card-bg);
border-radius: 8px;
padding: 12px;
margin-bottom: 0.8rem;
position: relative;
overflow: hidden;
min-height: 90px;
border: 1px solid rgba(255, 255, 255, 0.1);
transition: all 0.3s ease;
}
.status-card.executing {
background: linear-gradient(135deg, var(--executing-color) 0%, rgba(52, 152, 219, 0.2) 100%);
}
.status-card.identification {
background: linear-gradient(135deg, var(--identification-color) 0%, rgba(46, 204, 113, 0.2) 100%);
}
.status-card.friendly {
background: linear-gradient(135deg, var(--friendly-color) 0%, rgba(39, 174, 96, 0.2) 100%);
}
.status-card.hostile {
background: linear-gradient(135deg, var(--hostile-color) 0%, rgba(231, 76, 60, 0.2) 100%);
}
.status-info {
position: relative;
z-index: 1;
}
.status-info h3 {
font-size: 0.9rem;
margin: 0 0 8px 0;
color: rgba(255, 255, 255, 0.9);
font-weight: 500;
}
.status-value {
font-size: 1.5rem;
font-weight: 600;
color: white;
text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
/* 卡片样式 */
.battlefield-card {
background: var(--card-bg);
border: 1px solid var(--border-color);
border-radius: 10px;
margin-bottom: 1rem;
}
.battlefield-card .card-header {
background-color: rgba(20, 20, 40, 0.7);
border-bottom: 1px solid var(--border-color);
padding: 15px 20px;
display: flex;
justify-content: space-between;
align-items: center;
}
.battlefield-card .card-title {
color: #fff;
font-size: 1.1rem;
margin: 0;
display: flex;
align-items: center;
}
.battlefield-card .card-title i {
margin-right: 10px;
color: var(--accent-color);
}
.battlefield-card .card-body {
padding: 20px;
}
/* 视频流样式 */
.video-container {
position: relative;
width: 100%;
border-radius: 8px;
overflow: hidden;
background-color: #000;
}
.video-stream {
width: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.video-overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
}
.overlay-info {
position: absolute;
bottom: 10px;
left: 10px;
display: flex;
flex-direction: column;
gap: 5px;
}
.info-item {
background-color: rgba(0, 0, 0, 0.6);
color: #fff;
padding: 5px 10px;
border-radius: 4px;
font-size: 0.8rem;
display: flex;
align-items: center;
}
.info-item i {
margin-right: 5px;
color: var(--accent-color);
}
.target-box {
position: absolute;
width: 80px;
height: 80px;
border: 2px dashed rgba(255, 0, 0, 0.8);
display: flex;
flex-direction: column;
align-items: center;
}
.target-marker {
width: 20px;
height: 20px;
border: 2px solid red;
border-radius: 50%;
position: relative;
}
.target-marker:before, .target-marker:after {
content: '';
position: absolute;
background-color: red;
}
.target-marker:before {
width: 2px;
height: 10px;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
.target-marker:after {
width: 10px;
height: 2px;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
.target-info {
background-color: rgba(0, 0, 0, 0.7);
color: #fff;
padding: 3px 8px;
border-radius: 4px;
font-size: 0.7rem;
margin-top: 5px;
display: flex;
flex-direction: column;
align-items: center;
}
.stream-status {
display: flex;
align-items: center;
font-size: 0.9rem;
color: rgba(255, 255, 255, 0.7);
}
.status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background-color: #6c757d;
margin-right: 8px;
}
.status-dot.active {
background-color: #2ecc71;
box-shadow: 0 0 10px rgba(46, 204, 113, 0.5);
animation: pulse 1.5s infinite;
}
@keyframes pulse {
0% {
box-shadow: 0 0 0 0 rgba(46, 204, 113, 0.7);
}
70% {
box-shadow: 0 0 0 5px rgba(46, 204, 113, 0);
}
100% {
box-shadow: 0 0 0 0 rgba(46, 204, 113, 0);
}
}
/* 控制按钮样式 */
.control-buttons {
display: flex;
justify-content: center;
margin-top: 15px;
gap: 15px;
}
.control-buttons .btn {
min-width: 120px;
font-weight: 500;
}
/* 识别结果容器 */
.result-container {
width: 100%;
height: 300px;
background-color: #1a1a2e;
border-radius: 8px;
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
position: relative;
}
.result-container img {
max-width: 100%;
max-height: 100%;
object-fit: contain;
}
.result-placeholder {
color: rgba(255, 255, 255, 0.3);
font-size: 1.2rem;
text-align: center;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
/* 截图动画效果 */
.capture-flash {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(255, 255, 255, 0.8);
opacity: 0;
animation: flash 0.2s ease-out;
pointer-events: none;
z-index: 10;
}
@keyframes flash {
0% { opacity: 0.8; }
100% { opacity: 0; }
}
/* Toast通知样式 */
.toast-container {
position: fixed;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
z-index: 9999;
display: flex;
flex-direction: column;
align-items: center;
gap: 10px;
}
.toast-message {
background-color: rgba(0, 0, 0, 0.8);
color: #fff;
padding: 10px 20px;
border-radius: 4px;
font-size: 0.9rem;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
opacity: 0;
transform: translateY(20px);
transition: all 0.3s ease;
}
.toast-message.show {
opacity: 1;
transform: translateY(0);
}
/* 视频模式样式 */
.video-container.night-vision {
filter: hue-rotate(120deg) grayscale(0.5) brightness(1.5);
}
.video-container.thermal {
filter: hue-rotate(180deg) saturate(200%) contrast(150%);
}
.video-overlay.ar-mode .overlay-info {
background-color: rgba(0, 180, 216, 0.2);
border: 1px solid rgba(0, 180, 216, 0.5);
padding: 5px;
border-radius: 5px;
}
/* 响应式调整 */
@media (max-width: 768px) {
.sidebar {
width: 60px;
overflow: hidden;
}
.sidebar-header h4 {
display: none;
}
.logo-icon {
margin-right: 0;
}
.nav-link span {
display: none;
}
.main-content {
margin-left: 60px;
}
}
/* 按钮动画效果 */
.btn {
transition: all 0.2s ease;
}
.btn:active {
transform: scale(0.95);
}
/* 威胁等级指示器 */
.threat-level {
padding: 1rem;
background: rgba(0, 180, 216, 0.1);
border-radius: 5px;
margin-bottom: 1rem;
}
.level-label {
color: var(--text-color);
margin-bottom: 0.5rem;
}
.level-value {
font-size: 2rem;
font-weight: bold;
margin-bottom: 0.5rem;
}
.level-value.low {
color: var(--success-color);
}
.level-value.medium {
color: var(--warning-color);
}
.level-value.high {
color: var(--danger-color);
}
.level-indicator {
height: 6px;
background: rgba(255, 255, 255, 0.1);
border-radius: 3px;
overflow: hidden;
}
.level-indicator .indicator-bar {
height: 100%;
background: var(--success-color);
border-radius: 3px;
transition: width 0.3s ease;
}
/* 身份标识样式 */
.badge {
padding: 5px 10px;
border-radius: 4px;
font-weight: 500;
font-size: 0.8rem;
display: inline-block;
}
.badge-friendly {
background-color: #28a745;
color: white;
}
.badge-hostile {
background-color: #dc3545;
color: white;
}
.badge-unknown {
background-color: #ffc107;
color: #212529;
}

@ -0,0 +1,284 @@
//封装了与后端的通信功能
// API 基础 URL
const API_BASE_URL = 'http://localhost:5001/api';
// API 调用函数
const api = {
// 通用POST方法
post: async (endpoint, data) => {
try {
const response = await fetch(`${API_BASE_URL}${endpoint}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.message || '请求失败');
}
return await response.json();
} catch (error) {
throw error;
}
},
// 登录
login: async (username, password) => {
try {
const response = await fetch(`${API_BASE_URL}/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ username, password })
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.message || '登录失败');
}
return await response.json();
} catch (error) {
throw error;
}
},
// 获取无人机列表
getDrones: async () => {
try {
const response = await fetch(`${API_BASE_URL}/drones`, {
headers: {
'Authorization': `Bearer ${currentUser?.token}`
}
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.message || '获取无人机列表失败');
}
return await response.json();
} catch (error) {
throw error;
}
},
// 添加无人机
addDrone: async (droneData) => {
try {
const response = await fetch(`${API_BASE_URL}/drones`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${currentUser?.token}`
},
body: JSON.stringify(droneData)
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.message || '添加无人机失败');
}
return await response.json();
} catch (error) {
throw error;
}
},
// 更新无人机
updateDrone: async (droneId, droneData) => {
try {
const response = await fetch(`${API_BASE_URL}/drones/${droneId}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${currentUser?.token}`
},
body: JSON.stringify(droneData)
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.message || '更新无人机失败');
}
return await response.json();
} catch (error) {
throw error;
}
},
// 删除无人机
deleteDrone: async (droneId) => {
try {
const response = await fetch(`${API_BASE_URL}/drones/${droneId}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${currentUser?.token}`
}
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.message || '删除无人机失败');
}
return await response.json();
} catch (error) {
throw error;
}
},
// 获取识别记录
getRecords: async (filters = {}) => {
try {
const queryParams = new URLSearchParams(filters).toString();
const response = await fetch(`${API_BASE_URL}/records?${queryParams}`, {
headers: {
'Authorization': `Bearer ${currentUser?.token}`
}
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.message || '获取识别记录失败');
}
return await response.json();
} catch (error) {
throw error;
}
},
// 获取记录详情
getRecordDetail: async (recordId) => {
try {
const response = await fetch(`${API_BASE_URL}/records/${recordId}`, {
headers: {
'Authorization': `Bearer ${currentUser?.token}`
}
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.message || '获取记录详情失败');
}
return await response.json();
} catch (error) {
throw error;
}
},
// 目标识别
identify: async (formData) => {
try {
const response = await fetch(`${API_BASE_URL}/identify`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${currentUser?.token}`
},
body: formData
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.message || '目标识别失败');
}
return await response.json();
} catch (error) {
throw error;
}
},
// 信号识别
identifySignal: async (signal) => {
try {
const response = await fetch(`${API_BASE_URL}/signal_identify`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${currentUser?.token}`
},
body: JSON.stringify({ signal })
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.message || '信号识别失败');
}
return await response.json();
} catch (error) {
throw error;
}
},
// 加密
encrypt: async (text, method, key) => {
try {
const response = await fetch(`${API_BASE_URL}/encrypt`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ text, method, key })
});
return await response.json();
} catch (error) {
throw error;
}
},
// 解密
decrypt: async (text, method, key) => {
try {
const response = await fetch(`${API_BASE_URL}/decrypt`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ text, method, key })
});
return await response.json();
} catch (error) {
throw error;
}
},
// 哈希
hash: async (text, method) => {
try {
const response = await fetch(`${API_BASE_URL}/hash`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${currentUser?.token}`
},
body: JSON.stringify({ text, method })
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.message || '哈希计算失败');
}
return await response.json();
} catch (error) {
throw error;
}
}
};

File diff suppressed because it is too large Load Diff

@ -0,0 +1,206 @@
//通用功能,包括用户认证、页面初始化、侧边栏管理等
// 全局变量
let currentUser = null;
let threatChart = null;
let radarTargets = []; // 存储雷达上的目标
let radarInterval = null; // 存储雷达更新间隔
// 显示提示消息
function showToast(message, type = 'info') {
// 创建toast容器如果不存在
let toastContainer = document.getElementById('toast-container');
if (!toastContainer) {
toastContainer = document.createElement('div');
toastContainer.id = 'toast-container';
toastContainer.className = 'position-fixed top-0 end-0 p-3';
toastContainer.style.zIndex = '1050';
document.body.appendChild(toastContainer);
}
// 创建toast元素
const toastId = 'toast-' + Date.now();
const toast = document.createElement('div');
toast.className = `toast align-items-center text-white bg-${type} border-0`;
toast.id = toastId;
toast.setAttribute('role', 'alert');
toast.setAttribute('aria-live', 'assertive');
toast.setAttribute('aria-atomic', 'true');
toast.innerHTML = `
<div class="d-flex">
<div class="toast-body">
${message}
</div>
<button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
</div>
`;
toastContainer.appendChild(toast);
// 显示toast
const bsToast = new bootstrap.Toast(toast, {
animation: true,
autohide: true,
delay: 3000
});
bsToast.show();
// 自动删除toast元素
toast.addEventListener('hidden.bs.toast', function() {
toast.remove();
});
}
// 处理登录
function handleLogin(event) {
event.preventDefault();
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
// 硬编码的用户验证
if (username === 'admin' && password === '123') {
// 保存登录状态
currentUser = {
username: 'admin',
token: 'dummy-token'
};
// 保存到 localStorage
localStorage.setItem('currentUser', JSON.stringify(currentUser));
// 显示成功消息
showToast('登录成功', 'success');
// 跳转到仪表盘页面
setTimeout(() => {
window.location.href = 'dashboard.html';
}, 1000);
return false;
} else {
showToast('用户名或密码错误', 'danger');
return false;
}
}
// 退出登录
function logout() {
currentUser = null;
localStorage.removeItem('currentUser');
// 清除雷达间隔
if (radarInterval) {
clearInterval(radarInterval);
radarInterval = null;
}
// 重定向到登录页面
window.location.href = 'login.html';
}
// 初始化侧边栏
function initializeSidebar() {
// 处理侧边栏链接点击
document.querySelectorAll('.nav-link').forEach(link => {
link.addEventListener('click', function(e) {
e.preventDefault();
// 处理退出登录
if (this.id === 'logout-tab') {
logout();
return;
}
// 更新活动标签
document.querySelectorAll('.nav-link').forEach(nav => nav.classList.remove('active'));
this.classList.add('active');
// 获取目标部分的ID和页面
const tabId = this.id;
const sectionId = tabId.replace('-tab', '-section');
const targetPage = this.getAttribute('href') || `${tabId.replace('-tab', '')}.html`;
// 尝试在当前页面中切换内容
const targetSection = document.getElementById(sectionId);
if (targetSection) {
// 如果目标部分存在于当前页面,则在当前页面内切换
document.querySelectorAll('.main-content > div[id$="-section"]').forEach(section => {
section.style.display = 'none';
});
targetSection.style.display = 'block';
} else {
// 如果目标部分不存在于当前页面,跳转到对应页面
window.location.href = targetPage;
}
});
});
}
// 检查登录状态
function checkAuth() {
// 从 localStorage 获取用户信息
const savedUser = localStorage.getItem('currentUser');
if (savedUser) {
currentUser = JSON.parse(savedUser);
return true;
}
// 如果不在登录页面,则重定向到登录页面
if (!window.location.pathname.includes('login.html')) {
window.location.href = 'login.html';
}
return false;
}
// 更新用户信息显示
function updateUserInfo() {
if (currentUser) {
const userNameElement = document.getElementById('user-name');
if (userNameElement) {
userNameElement.textContent = currentUser.username;
}
}
}
// 更新当前时间
function updateCurrentTime() {
const timeElement = document.getElementById('current-time');
if (timeElement) {
const now = new Date();
const options = {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false
};
timeElement.textContent = now.toLocaleString('zh-CN', options).replace(/\//g, '-');
}
}
// 初始化页面
function initializePage() {
// 如果是登录页面,不需要检查认证
if (window.location.pathname.includes('login.html')) {
return;
}
if (!checkAuth()) return;
initializeSidebar();
updateUserInfo();
// 更新当前时间并设置定时器每秒更新
updateCurrentTime();
setInterval(updateCurrentTime, 1000);
}
// 在页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
initializePage();
});

File diff suppressed because it is too large Load Diff

@ -0,0 +1,618 @@
// 更新时间显示
function updateTime() {
const now = new Date();
document.getElementById('current-time').textContent = now.toLocaleString();
}
setInterval(updateTime, 1000);
// 页面加载时初始化
document.addEventListener('DOMContentLoaded', function() {
// 更新时间
updateTime();
// 默认VLC HTTP流地址
const vlcUrl = 'http://localhost:8888/video.mjpeg';
// 将地址填入输入框
const vlcUrlInput = document.getElementById('vlcUrlInput');
if (vlcUrlInput) {
vlcUrlInput.value = vlcUrl;
// 自动连接到VLC流
setTimeout(() => {
const connectBtn = document.getElementById('connectVlcBtn');
if (connectBtn) {
connectBtn.click();
console.log('自动连接到VLC流');
}
}, 1000);
}
// 尝试连接到VLC HTTP接口
initVLCConnection();
// 绑定控制按钮事件
bindControlEvents();
});
// 初始化VLC连接
function initVLCConnection() {
const vlcHost = document.getElementById('vlcHost');
const vlcPort = document.getElementById('vlcPort');
const vlcPassword = document.getElementById('vlcPassword');
if (vlcHost && vlcPort) {
// 尝试连接到VLC
setTimeout(() => {
VLC.connect(vlcHost.value, vlcPort.value, vlcPassword ? vlcPassword.value : '', function(success, message, data) {
const statusElement = document.getElementById('vlcStatus');
if (statusElement) {
if (success) {
statusElement.textContent = `已连接 - ${data.version}`;
statusElement.className = 'status';
// 更新音量滑块
if (data.volume !== undefined) {
const volume = Math.round(data.volume / 2.56); // VLC音量范围是0-256
const volumeSlider = document.getElementById('volumeSlider');
const volumeValue = document.getElementById('volumeValue');
if (volumeSlider && volumeValue) {
volumeSlider.value = volume;
volumeValue.textContent = volume + '%';
}
}
} else {
statusElement.textContent = message;
statusElement.className = 'status status-error';
}
}
});
}, 1000);
}
}
// 绑定控制按钮事件
function bindControlEvents() {
// 连接VLC流按钮
const connectVlcBtn = document.getElementById('connectVlcBtn');
if (connectVlcBtn) {
connectVlcBtn.addEventListener('click', function() {
const streamUrl = document.getElementById('vlcUrlInput').value.trim();
if (!streamUrl) {
alert('请输入有效的VLC HTTP流地址');
return;
}
// 更新状态为连接中
const streamStatus = document.getElementById('streamStatus');
const statusText = document.getElementById('statusText');
if (streamStatus && statusText) {
streamStatus.className = 'status-indicator';
streamStatus.style.backgroundColor = '#ffc107'; // 黄色表示连接中
statusText.textContent = '连接中...';
}
// 获取视频流元素
const mjpegStream = document.getElementById('mjpegStream');
if (!mjpegStream) {
console.error('找不到视频流元素');
return;
}
// 先清除旧的流
mjpegStream.src = '';
// 设置新的流地址
setTimeout(() => {
mjpegStream.src = streamUrl;
console.log('正在连接到VLC HTTP流:', streamUrl);
// 监控流健康状态
monitorStreamHealth(mjpegStream, streamStatus, statusText);
}, 100);
});
}
// 刷新VLC流按钮
const refreshVlcBtn = document.getElementById('refreshVlcBtn');
if (refreshVlcBtn) {
refreshVlcBtn.addEventListener('click', function() {
const mjpegStream = document.getElementById('mjpegStream');
if (!mjpegStream) return;
const currentSrc = mjpegStream.src;
// 更新状态为刷新中
const streamStatus = document.getElementById('streamStatus');
const statusText = document.getElementById('statusText');
if (streamStatus && statusText) {
streamStatus.className = 'status-indicator';
streamStatus.style.backgroundColor = '#ffc107'; // 黄色表示刷新中
statusText.textContent = '刷新中...';
}
// 刷新流
mjpegStream.src = '';
setTimeout(() => {
mjpegStream.src = currentSrc;
console.log('刷新VLC HTTP流:', currentSrc);
// 监控流健康状态
monitorStreamHealth(mjpegStream, streamStatus, statusText);
}, 100);
});
}
// 截图按钮
const captureBtn = document.getElementById('captureBtn');
if (captureBtn) {
captureBtn.addEventListener('click', function() {
captureVideoFrame();
});
}
// 全屏按钮
const fullscreenBtn = document.getElementById('fullscreenBtn');
if (fullscreenBtn) {
fullscreenBtn.addEventListener('click', function() {
const videoContainer = document.querySelector('.video-container');
if (!videoContainer) return;
if (document.fullscreenElement) {
document.exitFullscreen();
} else {
videoContainer.requestFullscreen();
}
});
}
// 连接到VLC按钮
const connectToVLCBtn = document.getElementById('connectToVLC');
if (connectToVLCBtn) {
connectToVLCBtn.addEventListener('click', function() {
const vlcHost = document.getElementById('vlcHost').value;
const vlcPort = document.getElementById('vlcPort').value;
const vlcPassword = document.getElementById('vlcPassword').value;
const statusElement = document.getElementById('vlcStatus');
if (statusElement) {
statusElement.textContent = '正在连接...';
statusElement.className = 'status';
}
// 使用VLC API连接
VLC.connect(vlcHost, vlcPort, vlcPassword, function(success, message, data) {
if (statusElement) {
if (success) {
statusElement.textContent = `已连接 - ${data.version}`;
statusElement.className = 'status';
// 更新音量滑块
if (data.volume !== undefined) {
const volume = Math.round(data.volume / 2.56); // VLC音量范围是0-256
const volumeSlider = document.getElementById('volumeSlider');
const volumeValue = document.getElementById('volumeValue');
if (volumeSlider && volumeValue) {
volumeSlider.value = volume;
volumeValue.textContent = volume + '%';
}
}
} else {
statusElement.textContent = message;
statusElement.className = 'status status-error';
}
}
});
});
}
// 检查VLC状态按钮
const checkVLCStatusBtn = document.getElementById('checkVLCStatus');
if (checkVLCStatusBtn) {
checkVLCStatusBtn.addEventListener('click', function() {
const statusElement = document.getElementById('vlcStatus');
if (statusElement) {
statusElement.textContent = '正在检查...';
statusElement.className = 'status';
}
// 使用VLC API获取状态
VLC.getStatus(function(success, message, data) {
if (statusElement) {
if (success) {
statusElement.textContent = `已连接 - ${data.version}`;
statusElement.className = 'status';
// 更新音量滑块
if (data.volume !== undefined) {
const volume = Math.round(data.volume / 2.56); // VLC音量范围是0-256
const volumeSlider = document.getElementById('volumeSlider');
const volumeValue = document.getElementById('volumeValue');
if (volumeSlider && volumeValue) {
volumeSlider.value = volume;
volumeValue.textContent = volume + '%';
}
}
} else {
statusElement.textContent = message;
statusElement.className = 'status status-error';
}
}
});
});
}
// 播放按钮
const playBtn = document.querySelector('button[onclick="sendVLCCommand(\'pl_play\')"]');
if (playBtn) {
playBtn.onclick = function() {
VLC.pause(function(success, message) {
updateVLCStatus(success, message);
});
return false;
};
}
// 暂停按钮
const pauseBtn = document.querySelector('button[onclick="sendVLCCommand(\'pl_pause\')"]');
if (pauseBtn) {
pauseBtn.onclick = function() {
VLC.pause(function(success, message) {
updateVLCStatus(success, message);
});
return false;
};
}
// 停止按钮
const stopBtn = document.querySelector('button[onclick="sendVLCCommand(\'pl_stop\')"]');
if (stopBtn) {
stopBtn.onclick = function() {
VLC.stop(function(success, message) {
updateVLCStatus(success, message);
});
return false;
};
}
// 上一个按钮
const prevBtn = document.querySelector('button[onclick="sendVLCCommand(\'pl_previous\')"]');
if (prevBtn) {
prevBtn.onclick = function() {
VLC.previous(function(success, message) {
updateVLCStatus(success, message);
});
return false;
};
}
// 下一个按钮
const nextBtn = document.querySelector('button[onclick="sendVLCCommand(\'pl_next\')"]');
if (nextBtn) {
nextBtn.onclick = function() {
VLC.next(function(success, message) {
updateVLCStatus(success, message);
});
return false;
};
}
// 音量滑块
const volumeSlider = document.getElementById('volumeSlider');
if (volumeSlider) {
volumeSlider.onchange = function() {
const volume = this.value;
const volumeValue = document.getElementById('volumeValue');
if (volumeValue) {
volumeValue.textContent = volume + '%';
}
VLC.setVolume(volume, function(success, message) {
updateVLCStatus(success, message);
});
};
}
// 播放媒体按钮
const playMediaBtn = document.querySelector('button[onclick="playSelectedMedia()"]');
if (playMediaBtn) {
playMediaBtn.onclick = function() {
const sourceType = document.getElementById('mediaSource').value;
let mrl = '';
switch (sourceType) {
case 'file':
mrl = 'file:///' + document.getElementById('filePath').value.replace(/\\/g, '/');
break;
case 'network':
mrl = document.getElementById('networkUrl').value;
break;
case 'screen':
mrl = 'screen://';
break;
case 'camera':
mrl = 'dshow://';
break;
}
if (!mrl) {
const statusElement = document.getElementById('vlcStatus');
if (statusElement) {
statusElement.textContent = '请输入有效的媒体源';
statusElement.className = 'status status-error';
}
return;
}
VLC.playMedia(mrl, function(success, message) {
updateVLCStatus(success, message);
});
return false;
};
}
// 配置HTTP流按钮
const setupHttpStreamBtn = document.querySelector('button[onclick="setupHttpStream()"]');
if (setupHttpStreamBtn) {
setupHttpStreamBtn.onclick = function() {
const sourceType = document.getElementById('mediaSource').value;
let mrl = '';
switch (sourceType) {
case 'file':
mrl = 'file:///' + document.getElementById('filePath').value.replace(/\\/g, '/');
break;
case 'network':
mrl = document.getElementById('networkUrl').value;
break;
case 'screen':
mrl = 'screen://';
break;
case 'camera':
mrl = 'dshow://';
break;
}
if (!mrl) {
const statusElement = document.getElementById('vlcStatus');
if (statusElement) {
statusElement.textContent = '请输入有效的媒体源';
statusElement.className = 'status status-error';
}
return;
}
const statusElement = document.getElementById('vlcStatus');
if (statusElement) {
statusElement.textContent = '正在配置HTTP流...';
statusElement.className = 'status';
}
VLC.setupHttpStream(mrl, {}, function(success, message) {
if (statusElement) {
if (success) {
statusElement.textContent = 'HTTP流配置成功';
statusElement.className = 'status';
// 自动连接到HTTP流
setTimeout(() => {
document.getElementById('streamUrl').value = 'http://localhost:8888/video.mjpeg';
connectToStream();
}, 2000);
} else {
statusElement.textContent = message;
statusElement.className = 'status status-error';
}
}
});
return false;
};
}
}
// 更新VLC状态
function updateVLCStatus(success, message) {
const statusElement = document.getElementById('vlcStatus');
if (statusElement) {
if (success) {
statusElement.textContent = message;
statusElement.className = 'status';
} else {
statusElement.textContent = message;
statusElement.className = 'status status-error';
}
}
}
// 连接到HTTP流
function connectToStream() {
const streamUrl = document.getElementById('streamUrl').value;
const videoStream = document.getElementById('videoStream');
const streamStatus = document.getElementById('streamStatus');
if (!streamUrl) {
streamStatus.textContent = '请输入有效的HTTP流地址';
streamStatus.className = 'status status-error';
return;
}
streamStatus.textContent = '正在连接...';
// 先清除旧的流
videoStream.src = '';
// 设置新的流地址
setTimeout(() => {
videoStream.src = streamUrl;
// 监控流健康状态
videoStream.onload = function() {
streamStatus.textContent = '连接成功';
streamStatus.className = 'status';
};
videoStream.onerror = function() {
streamStatus.textContent = '连接失败无法连接到视频流请确保VLC HTTP流服务器已正确启动';
streamStatus.className = 'status status-error';
};
}, 100);
}
// 监控流健康状态
function monitorStreamHealth(streamElement, statusIndicator, statusText) {
if (!streamElement || !statusIndicator || !statusText) return;
// 设置加载事件
streamElement.onload = function() {
statusIndicator.className = 'status-indicator status-online';
statusIndicator.style.backgroundColor = '#28a745'; // 绿色表示在线
statusText.textContent = '已连接';
};
// 设置错误事件
streamElement.onerror = function() {
statusIndicator.className = 'status-indicator status-offline';
statusIndicator.style.backgroundColor = '#dc3545'; // 红色表示离线
statusText.textContent = '连接失败';
};
}
// 截图功能
function captureVideoFrame() {
const mjpegStream = document.getElementById('mjpegStream');
if (!mjpegStream) {
alert('未找到视频流');
return;
}
try {
// 创建canvas
const canvas = document.createElement('canvas');
canvas.width = mjpegStream.naturalWidth || mjpegStream.width;
canvas.height = mjpegStream.naturalHeight || mjpegStream.height;
// 绘制当前帧到canvas
const ctx = canvas.getContext('2d');
ctx.drawImage(mjpegStream, 0, 0, canvas.width, canvas.height);
// 转换为图片
const imageData = canvas.toDataURL('image/png');
// 创建下载链接
const link = document.createElement('a');
link.href = imageData;
link.download = `capture_${new Date().toISOString().replace(/[:.]/g, '-')}.png`;
link.click();
console.log('已截取当前帧');
} catch (error) {
console.error('截图失败:', error);
alert('截图失败: ' + error.message);
}
}
// 开始目标识别
function startDetection() {
const detectionResults = document.getElementById('detectionResults');
detectionResults.innerHTML = '<p>正在进行目标识别...</p>';
// 这里可以添加实际的目标识别逻辑
// 例如调用后端API进行识别
// 模拟识别结果
setTimeout(() => {
detectionResults.innerHTML = `
<div>
<h3>识别结果</h3>
<ul>
<li>检测到无人机 (置信度: 95%)</li>
<li>类型: 大疆 Air3</li>
<li>位置: 左上角</li>
</ul>
</div>
`;
}, 2000);
}
// 停止目标识别
function stopDetection() {
const detectionResults = document.getElementById('detectionResults');
detectionResults.innerHTML = '<p>已停止识别</p>';
// 这里可以添加停止识别的逻辑
}
// 创建测试记录用于验证功能
function createTestRecords() {
console.log('创建测试记录...');
// 生成一些测试记录
const testRecords = [
{
id: 'test-' + Date.now() + '-1',
droneId: 'TEST-001',
model: 'DJI Mavic 3',
identity: '友方',
timestamp: new Date().toISOString(),
position: { lat: 39.9042, lng: 116.4074 },
altitude: 100,
distance: 1.5,
relativePosition: { x: 1.2, y: 0.1, z: 0.8 }
},
{
id: 'test-' + Date.now() + '-2',
droneId: 'TEST-002',
model: 'DJI Phantom 4',
identity: '敌方',
timestamp: new Date().toISOString(),
position: { lat: 39.9142, lng: 116.4174 },
altitude: 120,
distance: 2.1,
relativePosition: { x: -1.5, y: 0.2, z: 1.2 }
},
{
id: 'test-' + Date.now() + '-3',
droneId: 'TEST-003',
model: 'Autel EVO II',
identity: '敌方',
timestamp: new Date().toISOString(),
position: { lat: 39.9242, lng: 116.4274 },
altitude: 150,
distance: 3.2,
relativePosition: { x: 2.1, y: 0.5, z: -1.8 }
}
];
// 获取现有记录
let existingRecords = [];
try {
const storedRecords = localStorage.getItem('recordsList');
if (storedRecords) {
existingRecords = JSON.parse(storedRecords);
}
} catch (error) {
console.error('读取现有记录失败:', error);
}
// 合并记录
const allRecords = [...existingRecords, ...testRecords];
// 保存到localStorage
try {
localStorage.setItem('recordsList', JSON.stringify(allRecords));
console.log(`成功创建${testRecords.length}条测试记录,总记录数: ${allRecords.length}`);
// 更新统计数据
updateRecordsStatistics();
// 显示提示
alert(`已创建${testRecords.length}条测试记录其中2条敌方记录1条友方记录`);
} catch (error) {
console.error('保存测试记录失败:', error);
}
}
// 添加到全局作用域,以便可以从控制台调用
window.createTestRecords = createTestRecords;

@ -0,0 +1,213 @@
/**
* MQTT连接处理模块
* 用于连接MQTT服务器并发送/接收消息
*/
// MQTT客户端对象
let mqttClient = null;
let isConnected = false;
let connectionStatus = 'disconnected'; // 'disconnected', 'connecting', 'connected', 'failed'
/**
* 初始化MQTT连接
* @param {string} brokerUrl - MQTT服务器地址
* @param {string} clientId - 客户端ID
* @param {Object} options - 连接选项
* @returns {Promise} 连接结果Promise
*/
function initMqttConnection(brokerUrl = 'broker.emqx.io', clientId = 'web_client_' + Math.random().toString(16).substr(2, 8), options = {}) {
return new Promise((resolve, reject) => {
try {
// 检查MQTT库是否加载
if (typeof mqtt === 'undefined') {
console.error('MQTT客户端库未加载');
connectionStatus = 'failed';
reject(new Error('MQTT客户端库未加载'));
return;
}
connectionStatus = 'connecting';
// 默认连接选项
const defaultOptions = {
port: 1883,
useSSL: false,
username: '',
password: '',
keepalive: 60,
clean: true
};
// 合并选项
const connectionOptions = { ...defaultOptions, ...options };
// 创建完整的URL (使用SSL或非SSL)
const protocolPrefix = connectionOptions.useSSL ? 'wss://' : 'ws://';
const fullBrokerUrl = `${protocolPrefix}${brokerUrl}:${connectionOptions.port}/mqtt`;
console.log('正在连接MQTT服务器:', fullBrokerUrl);
// 创建MQTT客户端
mqttClient = mqtt.connect(fullBrokerUrl, {
clientId: clientId,
username: connectionOptions.username,
password: connectionOptions.password,
keepalive: connectionOptions.keepalive,
clean: connectionOptions.clean
});
// 连接成功事件
mqttClient.on('connect', () => {
console.log('MQTT连接成功');
connectionStatus = 'connected';
isConnected = true;
resolve(mqttClient);
});
// 连接失败事件
mqttClient.on('error', (err) => {
console.error('MQTT连接失败:', err);
connectionStatus = 'failed';
isConnected = false;
reject(err);
});
// 连接断开事件
mqttClient.on('close', () => {
console.log('MQTT连接已断开');
connectionStatus = 'disconnected';
isConnected = false;
});
// 消息接收事件
mqttClient.on('message', (topic, message) => {
const messageStr = message.toString();
console.log('收到MQTT消息:', topic, messageStr);
// 触发自定义事件,方便其他模块接收消息
const mqttEvent = new CustomEvent('mqtt-message', {
detail: { topic, message: messageStr }
});
document.dispatchEvent(mqttEvent);
});
} catch (error) {
console.error('初始化MQTT连接时发生错误:', error);
connectionStatus = 'failed';
reject(error);
}
});
}
/**
* 发布消息到指定主题
* @param {string} topic - 发布主题
* @param {string} message - 要发送的消息
* @param {Object} options - 发布选项QoS, retain等
* @returns {Promise} 发布结果Promise
*/
function publishMessage(topic, message, options = { qos: 0, retain: false }) {
return new Promise((resolve, reject) => {
if (!mqttClient || !isConnected) {
console.error('MQTT客户端未连接无法发送消息');
reject(new Error('MQTT客户端未连接'));
return;
}
console.log(`发送消息到主题 ${topic}:`, message);
mqttClient.publish(topic, message, options, (err) => {
if (err) {
console.error('MQTT消息发送失败:', err);
reject(err);
} else {
console.log('MQTT消息发送成功');
resolve(true);
}
});
});
}
/**
* 订阅指定主题
* @param {string} topic - 要订阅的主题
* @param {Object} options - 订阅选项如QoS等
* @returns {Promise} 订阅结果Promise
*/
function subscribeToTopic(topic, options = { qos: 0 }) {
return new Promise((resolve, reject) => {
if (!mqttClient || !isConnected) {
console.error('MQTT客户端未连接无法订阅主题');
reject(new Error('MQTT客户端未连接'));
return;
}
console.log('正在订阅主题:', topic);
mqttClient.subscribe(topic, options, (err) => {
if (err) {
console.error('主题订阅失败:', err);
reject(err);
} else {
console.log('主题订阅成功:', topic);
resolve(true);
}
});
});
}
/**
* 取消订阅指定主题
* @param {string} topic - 要取消订阅的主题
* @returns {Promise} 取消订阅结果Promise
*/
function unsubscribeFromTopic(topic) {
return new Promise((resolve, reject) => {
if (!mqttClient || !isConnected) {
console.error('MQTT客户端未连接无法取消订阅');
reject(new Error('MQTT客户端未连接'));
return;
}
console.log('正在取消订阅主题:', topic);
mqttClient.unsubscribe(topic, (err) => {
if (err) {
console.error('取消订阅失败:', err);
reject(err);
} else {
console.log('取消订阅成功:', topic);
resolve(true);
}
});
});
}
/**
* 断开MQTT连接
* @returns {Promise} 断开连接结果Promise
*/
function disconnectMqtt() {
return new Promise((resolve) => {
if (mqttClient && isConnected) {
mqttClient.end(false, () => {
console.log('MQTT连接已断开');
isConnected = false;
connectionStatus = 'disconnected';
resolve(true);
});
} else {
console.log('MQTT客户端未连接');
isConnected = false;
connectionStatus = 'disconnected';
resolve(false);
}
});
}
/**
* 获取连接状态
* @returns {Object} 连接状态对象
*/
function getConnectionStatus() {
return {
isConnected,
status: connectionStatus
};
}

@ -0,0 +1,448 @@
// 更新时间显示仅在common.js中的updateCurrentTime函数不存在时使用
function updateRecordsTime() {
const now = new Date();
console.log('records.js: 更新时间,当前时间:', now);
const timeElement = document.getElementById('current-time');
if (timeElement) {
console.log('records.js: 找到时间元素,更新内容');
timeElement.textContent = now.toLocaleString();
} else {
console.error('records.js: 未找到时间元素 #current-time');
}
}
// 检查是否需要设置时间更新间隔
let timeInterval = null;
function setupTimeUpdate() {
// 如果common.js已经处理了时间更新则不需要在这里再次处理
if (typeof updateCurrentTime === 'function') {
console.log('records.js: 检测到common.js中的updateCurrentTime函数不再设置时间更新');
return;
}
// 否则,设置自己的时间更新间隔
console.log('records.js: 设置时间更新间隔');
updateRecordsTime();
timeInterval = setInterval(updateRecordsTime, 1000);
}
// 页面加载时初始化
document.addEventListener('DOMContentLoaded', function() {
console.log('识别记录页面加载完成');
// 设置时间更新
setupTimeUpdate();
// 清除测试数据
removeTestRecords();
// 更新统计数据
updateRecordsStatistics();
// 加载识别记录
loadRecords();
// 绑定事件处理器
bindEventHandlers();
});
// 移除测试记录数据
function removeTestRecords() {
try {
const storedRecords = localStorage.getItem('recordsList');
if (storedRecords) {
let records = JSON.parse(storedRecords);
// 过滤掉TEST-001, TEST-002, TEST-003这些测试数据
const originalLength = records.length;
records = records.filter(record =>
!record.id.startsWith('TEST-') &&
!record.droneId.startsWith('TEST-')
);
// 如果有测试数据被移除更新localStorage
if (records.length !== originalLength) {
console.log(`已移除${originalLength - records.length}条测试记录`);
localStorage.setItem('recordsList', JSON.stringify(records));
} else {
console.log('未发现测试记录数据');
}
}
} catch (error) {
console.error('移除测试记录时出错:', error);
}
}
// 绑定事件处理器
function bindEventHandlers() {
// 筛选表单提交
const filterForm = document.getElementById('filterForm');
if (filterForm) {
filterForm.addEventListener('submit', function(e) {
e.preventDefault();
loadRecords(getFilters());
});
}
// 重置筛选
const resetButton = filterForm ? filterForm.querySelector('button[type="reset"]') : null;
if (resetButton) {
resetButton.addEventListener('click', function() {
setTimeout(() => {
loadRecords();
}, 100);
});
}
}
// 获取筛选条件
function getFilters() {
const timeRange = document.getElementById('timeRange').value;
const droneId = document.getElementById('droneId').value;
const droneModel = document.getElementById('droneModel').value;
const droneIdentity = document.getElementById('droneIdentity').value;
return {
timeRange,
droneId,
droneModel,
droneIdentity
};
}
// 加载识别记录
function loadRecords(filters = {}) {
// 从localStorage获取记录
let records = [];
try {
const storedRecords = localStorage.getItem('recordsList');
if (storedRecords) {
records = JSON.parse(storedRecords);
}
} catch (error) {
console.error('Error loading records:', error);
}
// 应用筛选
if (filters) {
if (filters.timeRange) {
const now = new Date();
let startDate;
switch (filters.timeRange) {
case 'today':
startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate());
break;
case 'week':
startDate = new Date(now);
startDate.setDate(now.getDate() - 7);
break;
case 'month':
startDate = new Date(now);
startDate.setMonth(now.getMonth() - 1);
break;
case 'custom':
// 自定义时间范围功能可以在这里扩展
break;
}
if (startDate) {
records = records.filter(record => {
const recordDate = new Date(record.timestamp);
return recordDate >= startDate;
});
}
}
if (filters.droneId) {
const idQuery = filters.droneId.toLowerCase();
records = records.filter(record =>
record.droneId && record.droneId.toLowerCase().includes(idQuery)
);
}
if (filters.droneModel) {
const modelQuery = filters.droneModel.toLowerCase();
records = records.filter(record =>
record.model && record.model.toLowerCase().includes(modelQuery)
);
}
if (filters.droneIdentity) {
records = records.filter(record =>
record.identity === filters.droneIdentity
);
}
}
// 更新UI
updateRecordsList(records);
}
// 更新记录列表
function updateRecordsList(records) {
console.log('开始更新记录列表,记录数量:', records ? records.length : 0);
const tbody = document.getElementById('recordsList');
if (!tbody) {
console.error('找不到记录列表元素 #recordsList');
return;
}
console.log('找到记录列表元素:', tbody);
// 清空现有内容
tbody.innerHTML = '';
// 如果没有记录
if (!records || records.length === 0) {
console.log('没有记录,显示空记录提示');
tbody.innerHTML = '<tr><td colspan="7" class="text-center">暂无记录</td></tr>';
return;
}
// 按时间降序排序
records.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
console.log('记录已按时间排序');
// 添加记录行
records.forEach((record, index) => {
console.log(`处理记录 ${index+1}/${records.length}:`, record);
const tr = document.createElement('tr');
// 格式化时间
const date = new Date(record.timestamp);
const formattedTime = date.toLocaleString('zh-CN');
// 格式化经纬度
const formattedPosition = record.position ?
`${record.position.lat.toFixed(6)}, ${record.position.lng.toFixed(6)}` :
'未知';
// 设置身份标识样式
let identityClass = '';
switch(record.identity) {
case '友方':
identityClass = 'badge badge-friendly';
break;
case '敌方':
identityClass = 'badge badge-hostile';
break;
default:
identityClass = 'badge badge-unknown';
}
// 格式化相对位置信息
let relativePositionInfo = '未知';
if (record.relativePosition) {
const { x, y, z } = record.relativePosition;
relativePositionInfo = `X: ${x.toFixed(2)}km, Y: ${y.toFixed(2)}km, Z: ${z.toFixed(2)}km`;
}
tr.innerHTML = `
<td>${formattedTime}</td>
<td>${record.droneId || ''}</td>
<td>${record.model || ''}</td>
<td><span class="${identityClass}">${record.identity || '未知'}</span></td>
<td>${formattedPosition}</td>
<td>${record.altitude ? record.altitude + 'm' : '未知'}</td>
<td>${record.distance ? record.distance + 'km' : '未知'}</td>
<td>${relativePositionInfo}</td>
<td>
<button class="btn btn-sm btn-outline-danger delete-record" data-id="${record.id}" title="删除此记录">
<i class="fas fa-trash-alt"></i>
</button>
</td>
`;
// 添加点击事件显示详情
tr.style.cursor = 'pointer';
tr.addEventListener('click', function(e) {
// 如果点击的是删除按钮或其子元素,不显示详情
if (e.target.closest('.delete-record')) {
return;
}
showRecordDetails(record);
});
// 添加删除按钮的点击事件处理
const deleteButton = tr.querySelector('.delete-record');
if (deleteButton) {
deleteButton.addEventListener('click', function(e) {
e.stopPropagation(); // 阻止事件冒泡
deleteRecord(record.id);
});
}
tbody.appendChild(tr);
});
console.log('记录列表更新完成');
}
// 更新记录统计
function updateRecordsStatistics() {
console.log('更新记录统计数据');
try {
// 从localStorage获取记录
const storedRecords = localStorage.getItem('recordsList');
if (storedRecords) {
const records = JSON.parse(storedRecords);
// 计算统计数据
const totalCount = records.length;
const friendlyCount = records.filter(record => record.identity === '友方').length;
const hostileCount = records.filter(record => record.identity === '敌方').length;
const unknownCount = records.filter(record => record.identity === '未知' || !record.identity).length;
console.log(`统计结果: 总数=${totalCount}, 友方=${friendlyCount}, 敌方=${hostileCount}, 未知=${unknownCount}`);
// 保存统计数据到localStorage
const stats = {
total: totalCount,
friendly: friendlyCount,
hostile: hostileCount,
unknown: unknownCount,
lastUpdate: new Date().toISOString()
};
localStorage.setItem('droneStats', JSON.stringify(stats));
console.log('记录统计数据已更新到localStorage');
// 触发自定义事件,通知其他页面数据已更新
try {
const event = new CustomEvent('droneStatsUpdated', { detail: stats });
window.dispatchEvent(event);
console.log('已触发droneStatsUpdated事件');
// 为了确保其他页面能收到通知还要模拟storage事件
localStorage.setItem('droneStats_trigger', new Date().getTime().toString());
console.log('已触发storage事件确保跨页面通信');
} catch (e) {
console.error('触发事件失败:', e);
}
// 直接更新当前页面的统计卡片(如果存在)
try {
const totalElement = document.querySelector('.status-card.executing .status-value');
const friendlyElement = document.querySelector('.status-card.friendly .status-value');
const hostileElement = document.querySelector('.status-card.hostile .status-value');
if (totalElement) totalElement.textContent = totalCount;
if (friendlyElement) friendlyElement.textContent = friendlyCount;
if (hostileElement) hostileElement.textContent = hostileCount;
console.log('已直接更新当前页面的统计卡片');
} catch (e) {
console.error('更新当前页面统计卡片失败:', e);
}
return stats;
}
} catch (error) {
console.error('更新记录统计数据失败:', error);
}
return null;
}
// 删除记录
function deleteRecord(recordId) {
console.log(`准备删除记录ID: ${recordId}`);
if (!recordId) {
console.error('删除记录失败: 记录ID为空');
return;
}
// 从localStorage获取记录
let recordsList = [];
try {
const storedRecords = localStorage.getItem('recordsList');
if (storedRecords) {
recordsList = JSON.parse(storedRecords);
}
} catch (error) {
console.error('获取记录失败:', error);
return;
}
// 查找记录索引
const recordIndex = recordsList.findIndex(record => record.id === recordId);
if (recordIndex === -1) {
console.error(`删除记录失败: 未找到ID为${recordId}的记录`);
return;
}
// 确认删除
if (confirm(`确定要删除这条记录吗?`)) {
// 删除记录
recordsList.splice(recordIndex, 1);
// 保存回localStorage
try {
localStorage.setItem('recordsList', JSON.stringify(recordsList));
console.log(`成功删除ID为${recordId}的记录`);
// 更新统计数据
updateRecordsStatistics();
// 重新加载记录列表
loadRecords(getFilters());
} catch (error) {
console.error('保存记录时出错:', error);
}
}
}
// 显示记录详情
function showRecordDetails(record) {
// 设置模态框内容
document.getElementById('detailTime').textContent = new Date(record.timestamp).toLocaleString('zh-CN');
document.getElementById('detailId').textContent = record.droneId || '';
document.getElementById('detailModel').textContent = record.model || '';
// 设置身份标识样式
const identityElement = document.getElementById('detailIdentity');
if (identityElement) {
let identityHtml = '';
switch(record.identity) {
case '友方':
identityHtml = '<span class="badge badge-friendly">友方</span>';
break;
case '敌方':
identityHtml = '<span class="badge badge-hostile">敌方</span>';
break;
default:
identityHtml = '<span class="badge badge-unknown">未知</span>';
}
identityElement.innerHTML = identityHtml;
}
// 设置位置信息
document.getElementById('detailLocation').textContent = record.position ?
`${record.position.lat.toFixed(6)}, ${record.position.lng.toFixed(6)}` : '未知';
document.getElementById('detailAltitude').textContent = record.altitude ?
record.altitude + 'm' : '未知';
document.getElementById('detailDistance').textContent = record.distance ?
record.distance + 'km' : '未知';
// 设置相对位置信息
const relativePositionElement = document.getElementById('detailRelativePosition');
if (relativePositionElement) {
if (record.relativePosition) {
const { x, y, z } = record.relativePosition;
relativePositionElement.textContent = `X: ${x.toFixed(2)}km, Y: ${y.toFixed(2)}km, Z: ${z.toFixed(2)}km`;
} else {
relativePositionElement.textContent = '未知';
}
}
// 显示模态框
const modal = new bootstrap.Modal(document.getElementById('recordDetailModal'));
modal.show();
}

@ -0,0 +1,261 @@
// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
initializeSignalCanvas();
initializeControls();
setupEventListeners();
});
let isScanning = false;
let animationFrameId = null;
let scanningData = [];
let currentFrequency = 2400; // MHz
// 初始化信号画布
function initializeSignalCanvas() {
const canvas = document.getElementById('signalCanvas');
const ctx = canvas.getContext('2d');
// 设置画布大小
function resizeCanvas() {
const container = canvas.parentElement;
canvas.width = container.clientWidth;
canvas.height = container.clientHeight;
}
resizeCanvas();
window.addEventListener('resize', resizeCanvas);
// 初始化扫描数据
for (let i = 0; i < 100; i++) {
scanningData.push(Math.random() * 0.5);
}
// 开始动画循环
function animate() {
if (!isScanning) return;
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawSignalWaveform(ctx);
animationFrameId = requestAnimationFrame(animate);
}
// 绘制信号波形
function drawSignalWaveform(ctx) {
const width = canvas.width;
const height = canvas.height;
const points = 100;
// 更新扫描数据
scanningData.shift();
scanningData.push(Math.random() * 0.5 + (isScanning ? Math.random() * 0.5 : 0));
// 绘制网格
drawGrid(ctx, width, height);
// 绘制波形
ctx.beginPath();
ctx.strokeStyle = '#00b4d8';
ctx.lineWidth = 2;
for (let i = 0; i < points; i++) {
const x = (i / points) * width;
const y = height - (scanningData[i] * height);
if (i === 0) {
ctx.moveTo(x, y);
} else {
ctx.lineTo(x, y);
}
}
ctx.stroke();
// 绘制填充
ctx.lineTo(width, height);
ctx.lineTo(0, height);
ctx.closePath();
const gradient = ctx.createLinearGradient(0, 0, 0, height);
gradient.addColorStop(0, 'rgba(0, 180, 216, 0.2)');
gradient.addColorStop(1, 'rgba(0, 180, 216, 0)');
ctx.fillStyle = gradient;
ctx.fill();
}
// 绘制网格
function drawGrid(ctx, width, height) {
const gridSize = 40;
ctx.strokeStyle = 'rgba(255, 255, 255, 0.1)';
ctx.lineWidth = 1;
// 绘制垂直线
for (let x = 0; x <= width; x += gridSize) {
ctx.beginPath();
ctx.moveTo(x, 0);
ctx.lineTo(x, height);
ctx.stroke();
}
// 绘制水平线
for (let y = 0; y <= height; y += gridSize) {
ctx.beginPath();
ctx.moveTo(0, y);
ctx.lineTo(width, y);
ctx.stroke();
}
}
// 导出动画控制函数
window.startAnimation = function() {
if (!isScanning) {
isScanning = true;
animate();
}
};
window.stopAnimation = function() {
isScanning = false;
if (animationFrameId) {
cancelAnimationFrame(animationFrameId);
}
};
}
// 初始化控制器
function initializeControls() {
const startButton = document.getElementById('startSignalScan');
const stopButton = document.getElementById('stopSignalScan');
const captureButton = document.getElementById('captureSignal');
const frequencyRange = document.getElementById('frequencyRange');
const scanSpeed = document.getElementById('scanSpeed');
// 开始扫描
startButton.addEventListener('click', function() {
startButton.disabled = true;
stopButton.disabled = false;
window.startAnimation();
updateSignalInfo();
});
// 停止扫描
stopButton.addEventListener('click', function() {
startButton.disabled = false;
stopButton.disabled = true;
window.stopAnimation();
});
// 捕获信号
captureButton.addEventListener('click', function() {
captureCurrentSignal();
});
// 频率范围选择
frequencyRange.addEventListener('change', function() {
updateFrequencyRange(this.value);
});
// 扫描速度调节
scanSpeed.addEventListener('input', function() {
updateScanSpeed(this.value);
});
}
// 更新信号信息
function updateSignalInfo() {
if (!isScanning) return;
// 模拟信号数据更新
const frequencyStep = Math.random() * 10 - 5;
currentFrequency = Math.max(300, Math.min(5000, currentFrequency + frequencyStep));
document.getElementById('currentFrequency').textContent = `${(currentFrequency / 1000).toFixed(2)} GHz`;
document.getElementById('signalStrength').textContent = `${-Math.floor(Math.random() * 20 + 60)} dBm`;
document.getElementById('bandwidth').textContent = `${Math.floor(Math.random() * 10 + 15)} MHz`;
document.getElementById('snr').textContent = `${Math.floor(Math.random() * 10 + 25)} dB`;
setTimeout(() => {
if (isScanning) {
updateSignalInfo();
}
}, 1000);
}
// 捕获当前信号
function captureCurrentSignal() {
const signalTypes = ['遥控信号', '数据链路', '图传信号', '干扰信号'];
const modulationTypes = ['QPSK', 'OFDM', '16QAM', 'FHSS'];
const encryptionTypes = ['AES-256', 'RSA-2048', 'ECC', '未加密'];
// 更新信号特征
document.getElementById('signalType').textContent = signalTypes[Math.floor(Math.random() * signalTypes.length)];
document.getElementById('modulationType').textContent = modulationTypes[Math.floor(Math.random() * modulationTypes.length)];
document.getElementById('encryptionType').textContent = encryptionTypes[Math.floor(Math.random() * encryptionTypes.length)];
// 显示捕获成功提示
showToast('信号捕获成功');
}
// 更新频率范围
function updateFrequencyRange(range) {
const ranges = {
'low': { min: 300, max: 1000 },
'mid': { min: 1000, max: 2400 },
'high': { min: 2400, max: 5000 }
};
if (range !== 'all' && ranges[range]) {
currentFrequency = (ranges[range].min + ranges[range].max) / 2;
}
}
// 更新扫描速度
function updateScanSpeed(speed) {
// 实现扫描速度调节逻辑
}
// 设置事件监听器
function setupEventListeners() {
// 全屏切换
document.getElementById('toggleFullscreen').addEventListener('click', function() {
const signalContainer = document.querySelector('.signal-container');
if (!document.fullscreenElement) {
signalContainer.requestFullscreen();
this.innerHTML = '<i class="fas fa-compress"></i>';
} else {
document.exitFullscreen();
this.innerHTML = '<i class="fas fa-expand"></i>';
}
});
// 导出记录
document.querySelector('.btn-outline-primary').addEventListener('click', function() {
// 实现导出功能
showToast('记录导出成功');
});
// 清除记录
document.querySelector('.btn-outline-danger').addEventListener('click', function() {
if (confirm('确定要清除所有记录吗?')) {
// 实现清除功能
showToast('记录已清除');
}
});
}
// 显示提示信息
function showToast(message) {
// 创建提示元素
const toast = document.createElement('div');
toast.className = 'toast-message';
toast.textContent = message;
document.body.appendChild(toast);
// 添加动画类
setTimeout(() => toast.classList.add('show'), 100);
// 自动移除
setTimeout(() => {
toast.classList.remove('show');
setTimeout(() => toast.remove(), 300);
}, 3000);
}

@ -0,0 +1,545 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>战场态势 - 无人机敌我识别系统</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.0.0/css/all.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@300;400;500;700&display=swap" rel="stylesheet">
<link href="common/css/style.css" rel="stylesheet">
<style>
/* 闪烁按钮动画 */
@keyframes buttonPulse {
0% { transform: scale(1); box-shadow: 0 0 0 0 rgba(255, 255, 255, 0.7); }
70% { transform: scale(1.05); box-shadow: 0 0 0 15px rgba(255, 255, 255, 0); }
100% { transform: scale(1); box-shadow: 0 0 0 0 rgba(255, 255, 255, 0); }
}
.pulse-button {
animation: buttonPulse 2s infinite;
background-color: #dc3545; /* 红色 */
border: 3px solid white;
}
/* 确保全屏按钮始终显示 */
#bigFullscreenBtn {
display: block !important;
opacity: 1 !important;
visibility: visible !important;
transform: none !important;
pointer-events: all !important;
}
</style>
</head>
<body class="battlefield-theme">
<div class="sidebar">
<div class="sidebar-header">
<h4>
<div class="logo-icon">
<i class="fas fa-drone"></i>
</div>
无人机敌我识别系统
</h4>
</div>
<nav class="nav flex-column">
<a class="nav-link active" href="dashboard.html">
<i class="fas fa-chart-line"></i>战场态势
</a>
<a class="nav-link" href="identification.html">
<i class="fas fa-crosshairs"></i>目标识别
</a>
<a class="nav-link" href="drones.html">
<i class="fas fa-drone"></i>无人机管理
</a>
<a class="nav-link" href="records.html">
<i class="fas fa-history"></i>识别记录
</a>
<a class="nav-link" href="encryption.html">
<i class="fas fa-broadcast-tower"></i>信号收发
</a>
</nav>
</div>
<div class="main-content">
<div class="container-fluid">
<div class="battlefield-header">
<div class="header-left">
<h2 class="page-title">战场态势</h2>
<div class="battlefield-time">
<i class="fas fa-clock"></i>
<span id="current-time">2024-01-01 12:00:00</span>
</div>
</div>
<div class="operator-info">
<i class="fas fa-user-shield"></i>
操作员:战术指挥官
<span class="status-badge online">在线</span>
</div>
</div>
<div class="row status-cards">
<div class="col-md-4">
<div class="status-card executing">
<div class="status-info">
<h3>今日识别总数</h3>
<div class="status-value">0</div>
</div>
<div class="card-tools position-absolute" style="top: 10px; right: 10px;">
<button class="btn btn-sm btn-refresh-stats" title="刷新统计数据">
<i class="fas fa-sync-alt"></i>
</button>
</div>
</div>
</div>
<div class="col-md-4">
<div class="status-card friendly">
<div class="status-info">
<h3>友方目标数</h3>
<div class="status-value">0</div>
</div>
<div class="card-tools position-absolute" style="top: 10px; right: 10px;">
<button class="btn btn-sm btn-refresh-stats" title="刷新统计数据">
<i class="fas fa-sync-alt"></i>
</button>
</div>
</div>
</div>
<div class="col-md-4">
<div class="status-card hostile">
<div class="status-info">
<h3>敌方目标数</h3>
<div class="status-value">0</div>
</div>
<div class="card-tools position-absolute" style="top: 10px; right: 10px;">
<button class="btn btn-sm btn-refresh-stats" title="刷新统计数据">
<i class="fas fa-sync-alt"></i>
</button>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-12">
<div class="card battlefield-card main-radar-card">
<div class="card-header">
<h5 class="card-title" style="color: white;">
<i class="fas fa-radar"></i>相对位置显示
</h5>
<div class="radar-controls">
<button class="btn btn-sm btn-outline-info" id="toggleFullscreen">
<i class="fas fa-expand"></i>
</button>
<button class="btn btn-sm btn-outline-info" id="resetCamera">
<i class="fas fa-sync"></i>
</button>
<button class="btn btn-sm btn-outline-info" id="toggleGrid">
<i class="fas fa-th"></i>
</button>
</div>
</div>
<div class="card-body p-0">
<div id="tacticalRadar" class="tactical-radar" style="height: 55vh; min-height: 400px; position: relative;">
<button id="bigFullscreenBtn" class="btn btn-danger position-absolute pulse-button" style="bottom: 30px; right: 30px; z-index: 2000; padding: 15px 30px; font-size: 18px; font-weight: bold; border-radius: 8px; box-shadow: 0 6px 12px rgba(0,0,0,0.5); border: 3px solid white;">
<i class="fas fa-expand fa-lg"></i> 点击全屏
</button>
</div>
</div>
</div>
</div>
</div>
<div class="row mt-2">
<div class="col-md-6">
<!-- 独立的坐标输入卡片 -->
<div class="card battlefield-card main-radar-card">
<div class="card-header py-2">
<h5 class="card-title" style="color: white; margin-bottom: 0;">
<i class="fas fa-map-marker-alt"></i>坐标输入
</h5>
</div>
<div class="card-body py-2">
<div class="row">
<div class="col-md-6">
<h6 class="form-label" style="color: white;">我方无人机坐标</h6>
<div class="input-group input-group-sm mb-2">
<span class="input-group-text">经度</span>
<input type="number" step="0.000001" id="myLongitude" class="form-control" placeholder="例116.397128">
</div>
<div class="input-group input-group-sm mb-2">
<span class="input-group-text">纬度</span>
<input type="number" step="0.000001" id="myLatitude" class="form-control" placeholder="例39.916527">
</div>
<div class="input-group input-group-sm mb-2">
<span class="input-group-text">海拔(m)</span>
<input type="number" id="myAltitude" class="form-control" placeholder="例100">
</div>
</div>
<div class="col-md-6">
<h6 class="form-label" style="color: white;">目标机坐标</h6>
<div class="input-group input-group-sm mb-2">
<span class="input-group-text">经度</span>
<input type="number" step="0.000001" id="targetLongitude" class="form-control" placeholder="例116.399128">
</div>
<div class="input-group input-group-sm mb-2">
<span class="input-group-text">纬度</span>
<input type="number" step="0.000001" id="targetLatitude" class="form-control" placeholder="例39.917527">
</div>
<div class="input-group input-group-sm mb-2">
<span class="input-group-text">海拔(m)</span>
<input type="number" id="targetAltitude" class="form-control" placeholder="例120">
</div>
</div>
</div>
<div class="d-grid gap-2">
<button id="calculatePositionBtn" class="btn btn-sm btn-outline-info">计算相对位置并显示</button>
</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="card battlefield-card main-radar-card">
<div class="card-header py-2">
<h5 class="card-title" style="color: white; margin-bottom: 0;">
<i class="fas fa-shield-alt"></i>威胁态势分析
</h5>
<div class="card-tools">
<button class="btn btn-sm btn-outline-info btn-refresh-threat" title="刷新威胁等级">
<i class="fas fa-sync"></i>
</button>
</div>
</div>
<div class="card-body py-3">
<div id="threatAnalysis">
<div class="threat-level" style="background: rgba(0, 0, 0, 0.2);">
<div class="level-label">当前威胁等级</div>
<div class="level-value low"></div>
<div class="level-indicator">
<div class="indicator-bar" style="width: 20%"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/0.158.0/three.min.js"></script>
<script src="https://unpkg.com/three@0.158.0/examples/jsm/controls/OrbitControls.js"></script>
<script>
// 确保OrbitControls正确加载
window.addEventListener('DOMContentLoaded', function() {
console.log('检查OrbitControls是否加载:', typeof THREE.OrbitControls);
if (typeof THREE.OrbitControls === 'undefined') {
// 如果THREE.OrbitControls未定义尝试从模块导出中获取
import('https://unpkg.com/three@0.158.0/examples/jsm/controls/OrbitControls.js')
.then(module => {
console.log('从模块导入OrbitControls:', module);
window.OrbitControls = module.OrbitControls;
console.log('OrbitControls已设置到window对象:', typeof window.OrbitControls);
})
.catch(error => {
console.error('加载OrbitControls失败:', error);
});
} else {
window.OrbitControls = THREE.OrbitControls;
console.log('使用THREE.OrbitControls');
}
});
</script>
<script src="common/js/api.js"></script>
<script src="common/js/common.js"></script>
<script src="common/js/battlefield.js"></script>
<!-- 确保全屏按钮始终显示的脚本 -->
<script>
// 在页面加载完成后立即执行
window.addEventListener('load', function() {
console.log('页面完全加载,执行额外初始化');
// 确保全屏按钮存在
setTimeout(function() {
var tacticalRadar = document.getElementById('tacticalRadar');
var existingBtn = document.getElementById('bigFullscreenBtn');
// 如果按钮不存在,创建一个新按钮
if (!existingBtn && tacticalRadar) {
console.log('创建新全屏按钮');
var newBtn = document.createElement('button');
newBtn.id = 'bigFullscreenBtn';
newBtn.className = 'btn btn-danger position-absolute pulse-button';
newBtn.style.cssText = 'bottom: 30px; right: 30px; z-index: 2000; padding: 15px 30px; font-size: 18px; font-weight: bold; border-radius: 8px; box-shadow: 0 6px 12px rgba(0,0,0,0.5); border: 3px solid white;';
newBtn.innerHTML = '<i class="fas fa-expand fa-lg"></i> 点击全屏';
// 添加点击事件
newBtn.addEventListener('click', function() {
if (typeof toggleFullscreen === 'function') {
toggleFullscreen();
}
});
// 添加到雷达容器
tacticalRadar.appendChild(newBtn);
console.log('新全屏按钮已创建并添加');
} else if (existingBtn) {
console.log('全屏按钮已存在,确保其可见');
existingBtn.style.display = 'block';
existingBtn.style.opacity = '1';
existingBtn.style.visibility = 'visible';
}
}, 1000); // 延迟1秒执行确保其他脚本已加载
});
</script>
<!-- 立即更新统计数据的脚本 -->
<script>
window.addEventListener('load', function() {
console.log('强制更新战场态势页面的统计数据');
// 延迟执行确保battlefield.js已加载
setTimeout(function() {
// 检查函数是否存在
if (typeof updateRecordsStatisticsOnLoad === 'function' &&
typeof updateStatusCardValues === 'function') {
// 强制更新统计数据
updateRecordsStatisticsOnLoad();
updateStatusCardValues();
// 每隔2秒检查一次确保数据更新
const checkInterval = setInterval(function() {
// 获取卡片元素
const hostileElement = document.querySelector('.status-card.hostile .status-value');
const friendlyElement = document.querySelector('.status-card.friendly .status-value');
const totalElement = document.querySelector('.status-card.executing .status-value');
// 获取localStorage中的统计数据
try {
const storedStats = localStorage.getItem('droneStats');
if (storedStats) {
const stats = JSON.parse(storedStats);
console.log('当前统计数据:', stats);
// 直接更新DOM元素
if (totalElement) totalElement.textContent = stats.total || 0;
if (friendlyElement) friendlyElement.textContent = stats.friendly || 0;
if (hostileElement) hostileElement.textContent = stats.hostile || 0;
console.log('已直接更新DOM元素');
// 更新威胁等级
if (window.globalThreatAnalysis) {
console.log('更新威胁等级');
window.globalThreatAnalysis.updateThreatLevel();
} else if (typeof ThreatAnalysis === 'function') {
console.log('创建新的威胁分析实例');
window.globalThreatAnalysis = new ThreatAnalysis('threatAnalysis');
}
}
} catch (e) {
console.error('读取统计数据失败:', e);
}
// 再次调用更新函数
updateRecordsStatisticsOnLoad();
updateStatusCardValues();
// 确保威胁等级更新
setTimeout(function() {
if (window.globalThreatAnalysis) {
window.globalThreatAnalysis.updateThreatLevel();
}
}, 500);
}, 2000);
// 最多检查5次
setTimeout(function() {
clearInterval(checkInterval);
}, 10000);
} else {
console.error('找不到更新函数battlefield.js可能未正确加载');
}
}, 2000);
});
</script>
<!-- 直接触发威胁等级更新的脚本 -->
<script>
// 确保页面加载完成后执行
window.addEventListener('load', function() {
console.log('准备直接更新威胁等级');
// 定期尝试更新威胁等级
const threatUpdateInterval = setInterval(function() {
console.log('定期尝试更新威胁等级');
// 尝试直接更新DOM
try {
// 获取统计数据
const identificationTotal = parseInt(document.querySelector('.status-card.executing .status-value').textContent) || 0;
const friendlyCount = parseInt(document.querySelector('.status-card.friendly .status-value').textContent) || 0;
const hostileCount = parseInt(document.querySelector('.status-card.hostile .status-value').textContent) || 0;
console.log(`直接计算威胁等级: 总数=${identificationTotal}, 友方=${friendlyCount}, 敌方=${hostileCount}`);
// 计算威胁等级
let threatLevel = 'low';
let threatColor = '#28a745'; // 绿色
let threatText = '低';
let threatWidth = '20%';
// 当识别总数和敌方目标数都为0时默认威胁等级为低
if (identificationTotal === 0 && hostileCount === 0) {
// 默认低级别
}
// 当识别总数为0但敌方目标数不为0时异常情况
else if (identificationTotal === 0 && hostileCount > 0) {
threatLevel = 'high';
threatColor = '#dc3545'; // 红色
threatText = '高';
threatWidth = '100%';
}
// 正常情况:根据敌方目标数与总数的比值确定威胁等级
else {
const ratio = hostileCount / identificationTotal;
if (ratio < 1/3) {
// 默认低级别
} else if (ratio >= 1/3 && ratio < 2/3) {
threatLevel = 'medium';
threatColor = '#ffc107'; // 黄色/橙色
threatText = '中';
threatWidth = '60%';
} else {
threatLevel = 'high';
threatColor = '#dc3545'; // 红色
threatText = '高';
threatWidth = '100%';
}
}
// 直接更新DOM
const levelValueElement = document.querySelector('.level-value');
const indicatorBarElement = document.querySelector('.level-indicator .indicator-bar');
if (levelValueElement && indicatorBarElement) {
// 移除所有可能的等级类
levelValueElement.classList.remove('low', 'medium', 'high');
// 添加当前等级类
levelValueElement.classList.add(threatLevel);
// 更新文本
levelValueElement.textContent = threatText;
// 更新颜色
levelValueElement.style.color = threatColor;
// 更新指示条
indicatorBarElement.style.width = threatWidth;
indicatorBarElement.style.background = threatColor;
console.log(`已直接更新威胁等级为: ${threatText}`);
}
} catch (error) {
console.error('直接更新威胁等级失败:', error);
}
}, 3000);
// 10秒后停止尝试
setTimeout(function() {
clearInterval(threatUpdateInterval);
}, 15000);
// 添加刷新威胁等级按钮点击事件
setTimeout(function() {
const refreshThreatBtn = document.querySelector('.btn-refresh-threat');
if (refreshThreatBtn) {
console.log('找到刷新威胁等级按钮,添加点击事件');
refreshThreatBtn.addEventListener('click', function() {
console.log('手动点击刷新威胁等级按钮');
// 显示加载状态
const icon = this.querySelector('i');
if (icon) {
icon.className = 'fas fa-spinner fa-spin';
}
// 尝试直接更新DOM
try {
// 获取统计数据
const identificationTotal = parseInt(document.querySelector('.status-card.executing .status-value').textContent) || 0;
const friendlyCount = parseInt(document.querySelector('.status-card.friendly .status-value').textContent) || 0;
const hostileCount = parseInt(document.querySelector('.status-card.hostile .status-value').textContent) || 0;
console.log(`手动刷新威胁等级: 总数=${identificationTotal}, 友方=${friendlyCount}, 敌方=${hostileCount}`);
// 计算威胁等级
let threatLevel = 'low';
let threatColor = '#28a745'; // 绿色
let threatText = '低';
let threatWidth = '20%';
// 根据敌方目标数与总数的比值确定威胁等级
if (identificationTotal === 0 && hostileCount === 0) {
// 默认低级别
} else if (identificationTotal === 0 && hostileCount > 0) {
threatLevel = 'high';
threatColor = '#dc3545'; // 红色
threatText = '高';
threatWidth = '100%';
} else {
const ratio = hostileCount / identificationTotal;
if (ratio < 1/3) {
// 默认低级别
} else if (ratio >= 1/3 && ratio < 2/3) {
threatLevel = 'medium';
threatColor = '#ffc107'; // 黄色/橙色
threatText = '中';
threatWidth = '60%';
} else {
threatLevel = 'high';
threatColor = '#dc3545'; // 红色
threatText = '高';
threatWidth = '100%';
}
}
// 直接更新DOM
const levelValueElement = document.querySelector('.level-value');
const indicatorBarElement = document.querySelector('.level-indicator .indicator-bar');
if (levelValueElement && indicatorBarElement) {
// 移除所有可能的等级类
levelValueElement.classList.remove('low', 'medium', 'high');
// 添加当前等级类
levelValueElement.classList.add(threatLevel);
// 更新文本
levelValueElement.textContent = threatText;
// 更新颜色
levelValueElement.style.color = threatColor;
// 更新指示条
indicatorBarElement.style.width = threatWidth;
indicatorBarElement.style.background = threatColor;
console.log(`已手动更新威胁等级为: ${threatText}`);
}
} catch (error) {
console.error('手动更新威胁等级失败:', error);
}
// 恢复按钮状态
setTimeout(() => {
if (icon) {
icon.className = 'fas fa-sync';
}
}, 500);
});
}
}, 1000);
});
</script>
</body>
</html>

@ -0,0 +1,404 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>无人机管理 - 无人机敌我识别系统</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.0.0/css/all.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@300;400;500;700&display=swap" rel="stylesheet">
<link href="common/css/style.css" rel="stylesheet">
<style>
#map {
height: 300px;
border-radius: 8px;
background: #f5f5f5;
position: relative;
}
.drone-status-card {
background: rgba(33, 37, 41, 0.8);
border-radius: 10px;
padding: 15px;
margin-bottom: 20px;
border: 1px solid rgba(255, 255, 255, 0.1);
}
.status-indicator {
width: 12px;
height: 12px;
border-radius: 50%;
display: inline-block;
margin-right: 8px;
}
.status-online { background-color: #28a745; }
.status-mission { background-color: #007bff; }
.status-maintenance { background-color: #ffc107; }
.status-offline { background-color: #dc3545; }
.drone-detail-panel {
background: rgba(33, 37, 41, 0.9);
border-radius: 10px;
padding: 20px;
margin-top: 20px;
}
.mission-timeline {
position: relative;
padding-left: 20px;
}
.mission-timeline::before {
content: '';
position: absolute;
left: 0;
top: 0;
height: 100%;
width: 2px;
background: rgba(255, 255, 255, 0.1);
}
.mission-point {
position: relative;
padding-bottom: 15px;
}
.mission-point::before {
content: '';
position: absolute;
left: -24px;
top: 5px;
width: 10px;
height: 10px;
border-radius: 50%;
background: #007bff;
}
.battery-indicator {
width: 100%;
height: 20px;
background: rgba(255, 255, 255, 0.1);
border-radius: 10px;
overflow: hidden;
}
.battery-level {
height: 100%;
background: linear-gradient(90deg, #28a745 0%, #ffc107 50%, #dc3545 100%);
transition: width 0.3s ease;
}
.card.bg-dark {
background: rgba(33, 37, 41, 0.7) !important;
border: 1px solid rgba(255, 255, 255, 0.1);
}
.card-header {
background: rgba(0, 0, 0, 0.2);
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}
.info-item {
padding: 8px;
border-radius: 6px;
background: rgba(0, 0, 0, 0.1);
}
.info-item h6 {
margin-bottom: 0;
font-weight: 500;
color: #ffffff; /* 将文字颜色改为白色 */
}
/* 确保所有详情面板中的文字都是浅色的 */
.drone-detail-panel .text-muted {
color: rgba(255, 255, 255, 0.7) !important;
}
.drone-detail-panel h6, .drone-detail-panel p, .drone-detail-panel div {
color: #ffffff;
}
/* 无人机列表行样式 */
.drone-list-row:hover {
background-color: rgba(0, 180, 216, 0.1) !important;
}
.drone-list-row.table-active {
background-color: rgba(0, 180, 216, 0.3) !important;
box-shadow: 0 0 5px rgba(0, 180, 216, 0.5);
}
/* 高亮标记样式 */
.highlight-marker {
pointer-events: none;
z-index: 1000;
}
</style>
<script type="text/javascript" src="https://api.map.baidu.com/api?v=3.0&ak=nSxiPohfziUaCuONe4ViUP2N"></script>
</head>
<body class="battlefield-theme">
<div class="sidebar">
<div class="sidebar-header">
<h4>
<div class="logo-icon">
<i class="fas fa-drone"></i>
</div>
无人机敌我识别系统
</h4>
</div>
<nav class="nav flex-column">
<a class="nav-link" href="dashboard.html">
<i class="fas fa-chart-line"></i>战场态势
</a>
<a class="nav-link" href="identification.html">
<i class="fas fa-crosshairs"></i>目标识别
</a>
<a class="nav-link active" href="drones.html">
<i class="fas fa-drone"></i>无人机管理
</a>
<a class="nav-link" href="records.html">
<i class="fas fa-history"></i>识别记录
</a>
<a class="nav-link" href="encryption.html">
<i class="fas fa-broadcast-tower"></i>信号收发
</a>
</nav>
</div>
<div class="main-content">
<div class="container-fluid">
<div class="battlefield-header">
<div class="header-left">
<h2 class="page-title">无人机管理</h2>
<div class="battlefield-time">
<i class="fas fa-clock"></i>
<span id="current-time">2024-01-01 12:00:00</span>
</div>
</div>
<div class="operator-info">
<i class="fas fa-user-shield"></i>
操作员:战术指挥官
<span class="status-badge online">在线</span>
</div>
</div>
<div class="row mb-4">
<div class="col-12">
<div class="d-flex justify-content-end">
<button class="btn btn-outline-primary me-2" id="refreshStatus">
<i class="fas fa-sync-alt"></i> 刷新状态
</button>
<button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addDroneModal">
<i class="fas fa-plus"></i> 添加无人机
</button>
</div>
</div>
</div>
<!-- 状态概览卡片 -->
<div class="row">
<div class="col-lg-8">
<!-- 无人机位置地图 -->
<div class="card mb-4">
<div class="card-header">
<h5 class="card-title">
<i class="fas fa-map-marked-alt"></i> 无人机位置
</h5>
</div>
<div class="card-body">
<div id="map"></div>
</div>
</div>
<!-- 无人机列表 -->
<div class="card">
<div class="card-header">
<div class="d-flex justify-content-between align-items-center">
<h5 class="card-title mb-0">
<i class="fas fa-list"></i> 无人机列表
</h5>
<div class="btn-group">
<button class="btn btn-sm btn-outline-secondary">
<i class="fas fa-filter"></i> 筛选
</button>
<button class="btn btn-sm btn-outline-secondary">
<i class="fas fa-sort"></i> 排序
</button>
</div>
</div>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-hover">
<thead>
<tr>
<th>编号</th>
<th>型号</th>
<th>身份</th>
<th>位置</th>
<th>操作</th>
</tr>
</thead>
<tbody id="dronesList">
</tbody>
</table>
</div>
</div>
</div>
</div>
<div class="col-lg-4">
<!-- 无人机详情面板 -->
<div class="drone-detail-panel h-100" id="droneDetailPanel">
<h5 class="mb-3">目标详情</h5>
<div class="card bg-dark mb-3">
<div class="card-header">
<h6 class="mb-0">基本信息</h6>
</div>
<div class="card-body">
<div class="row g-3">
<div class="col-6">
<div class="info-item">
<label class="text-muted mb-1">型号</label>
<h6>--</h6>
</div>
</div>
<div class="col-6">
<div class="info-item">
<label class="text-muted mb-1">身份</label>
<h6>--</h6>
</div>
</div>
<div class="col-6">
<div class="info-item">
<label class="text-muted mb-1">检测时间</label>
<h6>--</h6>
</div>
</div>
<div class="col-6">
<div class="info-item">
<label class="text-muted mb-1">相对距离</label>
<h6>--</h6>
</div>
</div>
</div>
</div>
</div>
<div class="card bg-dark mb-3">
<div class="card-header">
<h6 class="mb-0">实时状态</h6>
</div>
<div class="card-body">
<div class="row g-3">
<div class="col-6">
<div class="info-item">
<label class="text-muted mb-1">目标经度</label>
<h6>--</h6>
</div>
</div>
<div class="col-6">
<div class="info-item">
<label class="text-muted mb-1">目标纬度</label>
<h6>--</h6>
</div>
</div>
<div class="col-6">
<div class="info-item">
<label class="text-muted mb-1">目标海拔</label>
<h6>--</h6>
</div>
</div>
<div class="col-6">
<div class="info-item">
<label class="text-muted mb-1">移动速度</label>
<h6>--</h6>
</div>
</div>
</div>
</div>
</div>
<div class="card bg-dark">
<div class="card-header">
<h6 class="mb-0">相对位置信息</h6>
</div>
<div class="card-body">
<div class="row g-3">
<div class="col-4">
<div class="info-item">
<label class="text-muted mb-1">X轴距离</label>
<h6>--</h6>
</div>
</div>
<div class="col-4">
<div class="info-item">
<label class="text-muted mb-1">Y轴距离</label>
<h6>--</h6>
</div>
</div>
<div class="col-4">
<div class="info-item">
<label class="text-muted mb-1">Z轴距离</label>
<h6>--</h6>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- 添加无人机模态框 -->
<div class="modal fade" id="addDroneModal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">添加新无人机</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<form id="addDroneForm">
<div class="mb-3">
<label class="form-label">无人机型号</label>
<input type="text" class="form-control" id="droneModel" required>
</div>
<div class="mb-3">
<label class="form-label">序列号</label>
<input type="text" class="form-control" id="serialNumber" required>
</div>
<div class="mb-3">
<label class="form-label">最大续航时间(小时)</label>
<input type="number" class="form-control" id="maxFlightTime" required>
</div>
<div class="mb-3">
<label class="form-label">最大载重kg</label>
<input type="number" class="form-control" id="maxPayload" required>
</div>
<div class="mb-3">
<label class="form-label">通信频段</label>
<input type="text" class="form-control" id="communicationBand" required>
</div>
<div class="mb-3">
<label class="form-label">设备配置</label>
<div class="form-check">
<input class="form-check-input" type="checkbox" id="hasCamera">
<label class="form-check-label">高清摄像头</label>
</div>
<div class="form-check">
<input class="form-check-input" type="checkbox" id="hasInfrared">
<label class="form-check-label">红外传感器</label>
</div>
<div class="form-check">
<input class="form-check-input" type="checkbox" id="hasGPS">
<label class="form-check-label">GPS定位系统</label>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
<button type="button" class="btn btn-primary" id="saveDrone">保存</button>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="common/js/api.js"></script>
<script src="common/js/common.js"></script>
<script src="common/js/drones.js"></script>
</body>
</html>

File diff suppressed because it is too large Load Diff

@ -0,0 +1,829 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>目标识别 - 无人机敌我识别系统</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.0.0/css/all.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@300;400;500;700&display=swap" rel="stylesheet">
<link href="common/css/style.css" rel="stylesheet">
<!-- VideoJS 样式 -->
<link href="https://vjs.zencdn.net/7.20.3/video-js.css" rel="stylesheet" />
<style>
/* 额外的内联样式确保界面美观 */
.battlefield-card {
background-color: rgba(30, 30, 60, 0.7);
border: 1px solid rgba(52, 152, 219, 0.3);
box-shadow: 0 0 15px rgba(52, 152, 219, 0.1);
}
.battlefield-card .card-header {
background-color: rgba(20, 20, 40, 0.7);
border-bottom: 1px solid rgba(52, 152, 219, 0.2);
}
.battlefield-card .card-title i {
color: #3498db;
}
.btn-primary {
background-color: #3498db;
border-color: #3498db;
}
.btn-primary:hover {
background-color: #2980b9;
border-color: #2980b9;
}
.btn-secondary {
background-color: #7f8c8d;
border-color: #7f8c8d;
}
.btn-secondary:hover {
background-color: #6c7a7d;
border-color: #6c7a7d;
}
.form-select, .form-control {
background-color: rgba(30, 30, 60, 0.5);
border: 1px solid rgba(52, 152, 219, 0.3);
color: #e9ecef;
}
.form-select:focus, .form-control:focus {
background-color: rgba(30, 30, 60, 0.7);
border-color: rgba(52, 152, 219, 0.5);
box-shadow: 0 0 0 0.25rem rgba(52, 152, 219, 0.25);
color: #e9ecef;
}
.video-container {
position: relative;
width: 100%;
height: 0;
padding-bottom: 56.25%; /* 16:9 比例 */
background-color: #000;
overflow: hidden;
border-radius: 8px;
border: 1px solid rgba(52, 152, 219, 0.3);
margin-bottom: 1rem;
}
.video-stream {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
}
.result-container {
width: 100%;
height: 65vh;
background-color: rgba(15, 20, 40, 0.4);
border-radius: 8px;
overflow: hidden;
position: relative;
border: 1px solid rgba(52, 152, 219, 0.2);
display: flex;
flex-direction: column;
}
.detection-result {
position: absolute;
bottom: 0;
left: 0;
right: 0;
padding: 10px;
background-color: rgba(15, 20, 40, 0.7);
color: white;
z-index: 10;
}
.detection-overlay {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
z-index: 5;
pointer-events: none;
}
.command-list {
max-height: 300px;
overflow-y: auto;
border-top: 1px solid rgba(52, 152, 219, 0.3);
margin-top: 1rem;
padding-top: 1rem;
}
.command-item {
background-color: rgba(30, 30, 60, 0.5);
border-radius: 8px;
padding: 0.75rem 1rem;
margin-bottom: 0.75rem;
border-left: 3px solid #3498db;
}
.command-question {
font-weight: 500;
color: #e9ecef;
margin-bottom: 0.25rem;
}
.command-answer {
color: rgba(255, 255, 255, 0.7);
}
/* 视频控制条 */
.video-controls {
background-color: rgba(15, 20, 40, 0.7);
border-top: 1px solid rgba(52, 152, 219, 0.2);
padding: 10px;
display: flex;
align-items: center;
}
/* 自定义滚动条 */
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: rgba(30, 30, 60, 0.2);
}
::-webkit-scrollbar-thumb {
background: rgba(52, 152, 219, 0.5);
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: rgba(52, 152, 219, 0.7);
}
/* 视频播放器样式覆盖 */
.video-js {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
background-color: #000;
}
.video-js .vjs-tech {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
</style>
</head>
<body class="battlefield-theme">
<div class="sidebar">
<div class="sidebar-header">
<h4>
<div class="logo-icon">
<i class="fas fa-drone"></i>
</div>
无人机敌我识别系统
</h4>
</div>
<nav class="nav flex-column">
<a class="nav-link" href="dashboard.html">
<i class="fas fa-chart-line"></i>战场态势
</a>
<a class="nav-link active" href="identification.html">
<i class="fas fa-crosshairs"></i>目标识别
</a>
<a class="nav-link" href="drones.html">
<i class="fas fa-drone"></i>无人机管理
</a>
<a class="nav-link" href="records.html">
<i class="fas fa-history"></i>识别记录
</a>
<a class="nav-link" href="encryption.html">
<i class="fas fa-broadcast-tower"></i>信号收发
</a>
</nav>
</div>
<div class="main-content">
<div class="container-fluid">
<div class="battlefield-header">
<div class="header-left">
<h2 class="page-title">目标识别</h2>
<div class="battlefield-time">
<i class="fas fa-clock"></i>
<span id="current-time">2024-01-01 12:00:00</span>
</div>
</div>
<div class="operator-info">
<i class="fas fa-user-shield"></i>
操作员:战术指挥官
<span class="status-badge online">在线</span>
</div>
</div>
<div class="row">
<!-- VLC播放器启动按钮卡片 -->
<div class="col-md-12 mb-4">
<div class="card battlefield-card">
<div class="card-header">
<h5 class="card-title">
<i class="fas fa-play-circle"></i> 视频监控
</h5>
</div>
<div class="card-body">
<div class="d-grid">
<button class="btn btn-info btn-lg" id="openVlcBtn">
<i class="fas fa-play-circle"></i> 实时视频流
</button>
</div>
</div>
</div>
</div>
<!-- 身份核对卡片 -->
<div class="col-md-12 mb-4">
<div class="card battlefield-card">
<div class="card-header">
<h5 class="card-title">
<i class="fas fa-id-card"></i> 身份核对
</h5>
</div>
<div class="card-body">
<div class="row align-items-end">
<div class="col-md-3 mb-3 mb-md-0">
<label for="checkId" class="form-label" style="color: #ffffff;">编号</label>
<input type="text" class="form-control" id="checkId" placeholder="输入编号">
</div>
<div class="col-md-3 mb-3 mb-md-0">
<label for="checkQuestion" class="form-label" style="color: #ffffff;">问令</label>
<input type="text" class="form-control" id="checkQuestion" placeholder="输入问令">
</div>
<div class="col-md-3 mb-3 mb-md-0">
<label for="checkAnswer" class="form-label" style="color: #ffffff;">答令</label>
<input type="text" class="form-control" id="checkAnswer" placeholder="输入答令">
</div>
<div class="col-md-3">
<button class="btn btn-primary w-100" id="checkIdentityBtn">
<i class="fas fa-search"></i> 核验身份
</button>
</div>
</div>
<div class="mt-3" id="identityResult" style="display: none;">
<div class="alert alert-info" role="alert" id="identityResultText">
请输入信息进行身份核对
</div>
</div>
</div>
</div>
</div>
<!-- 右侧区域:口令管理 -->
<div class="col-md-12">
<div class="card battlefield-card" style="height: calc(100% - 30px);">
<div class="card-header">
<h5 class="card-title">
<i class="fas fa-key"></i>口令管理
</h5>
</div>
<div class="card-body d-flex flex-column" style="height: calc(100% - 56px);">
<div class="mb-3">
<label for="commandQuestion" class="form-label" style="color: #ffffff;">问令</label>
<input type="text" class="form-control" id="commandQuestion" placeholder="输入问令...">
</div>
<div class="mb-3">
<label for="commandAnswer" class="form-label" style="color: #ffffff;">答令</label>
<input type="text" class="form-control" id="commandAnswer" placeholder="输入答令...">
</div>
<div class="d-grid mb-3">
<button class="btn btn-primary" id="saveCommandBtn">
<i class="fas fa-save"></i> 存入
</button>
</div>
<div class="command-list flex-grow-1 overflow-auto" id="commandList" style="min-height: 200px;">
<!-- 示例口令 -->
<div class="command-item">
<div class="command-question">今日口令是什么?</div>
<div class="command-answer">蓝天白云</div>
</div>
<div class="command-item">
<div class="command-question">请问任务代号?</div>
<div class="command-answer">雄鹰展翅</div>
</div>
<div class="command-item">
<div class="command-question">确认身份?</div>
<div class="command-answer">猎鹰小队</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="common/js/api.js"></script>
<script src="common/js/common.js"></script>
<script>
// 更新当前时间
function updateTime() {
const now = new Date();
const options = {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false
};
document.getElementById('current-time').textContent = now.toLocaleString('zh-CN', options);
}
// 每秒更新一次时间
setInterval(updateTime, 1000);
updateTime();
// 打开VLC播放器按钮点击事件
document.getElementById('openVlcBtn').addEventListener('click', function() {
// 显示正在处理的信息
showToast('正在播放实时视频流...');
console.log('点击了实时视频流按钮');
// 调用后端API打开VLC播放器
fetch('/api/open-vlc', {
method: 'POST'
})
.then(response => {
console.log('收到响应:', response.status, response.statusText);
return response.json().catch(e => {
console.error('解析JSON失败:', e);
return {success: false, error: '无法解析服务器响应'};
});
})
.then(data => {
console.log('响应数据:', data);
if (data.success) {
showToast('实时视频流已播放');
} else {
showToast('无法播放: ' + (data.error || '未知错误'));
}
})
.catch(error => {
console.error('调用API出错:', error);
showToast('无法播放,请检查控制台错误信息');
});
});
// 添加口令保存功能
document.getElementById('saveCommandBtn').addEventListener('click', function() {
const question = document.getElementById('commandQuestion').value.trim();
const answer = document.getElementById('commandAnswer').value.trim();
if (question && answer) {
// 创建唯一ID
const id = 'cmd_' + Date.now();
// 保存到localStorage
saveCommand(id, question, answer);
// 添加到UI
addCommandToUI(id, question, answer);
// 清空输入
document.getElementById('commandQuestion').value = '';
document.getElementById('commandAnswer').value = '';
showToast('口令已保存');
} else {
showToast('请输入完整的问答口令');
}
});
// 保存命令到localStorage
function saveCommand(id, question, answer) {
// 获取现有命令
let commands = getCommands();
// 添加新命令
commands.push({
id: id,
question: question,
answer: answer
});
// 保存回localStorage
localStorage.setItem('droneCommands', JSON.stringify(commands));
}
// 从localStorage获取命令
function getCommands() {
const commandsStr = localStorage.getItem('droneCommands');
return commandsStr ? JSON.parse(commandsStr) : [];
}
// 将命令添加到UI
function addCommandToUI(id, question, answer) {
const commandItem = document.createElement('div');
commandItem.className = 'command-item';
commandItem.dataset.id = id;
commandItem.dataset.question = question;
commandItem.dataset.answer = answer;
// 创建问答内容
const contentDiv = document.createElement('div');
contentDiv.style.flex = '1';
const questionDiv = document.createElement('div');
questionDiv.className = 'command-question';
questionDiv.textContent = question;
const answerDiv = document.createElement('div');
answerDiv.className = 'command-answer';
answerDiv.textContent = answer;
contentDiv.appendChild(questionDiv);
contentDiv.appendChild(answerDiv);
// 创建删除按钮
const deleteBtn = document.createElement('button');
deleteBtn.className = 'btn btn-sm btn-danger ms-2';
deleteBtn.innerHTML = '<i class="fas fa-trash"></i>';
deleteBtn.title = '删除口令';
deleteBtn.style.alignSelf = 'center';
// 添加删除事件
deleteBtn.addEventListener('click', function() {
deleteCommand(id);
});
// 设置flex容器
commandItem.style.display = 'flex';
commandItem.style.justifyContent = 'space-between';
commandItem.style.alignItems = 'flex-start';
// 添加内容和按钮
commandItem.appendChild(contentDiv);
commandItem.appendChild(deleteBtn);
// 添加到列表
document.getElementById('commandList').prepend(commandItem);
}
// 从UI和localStorage删除命令
function deleteCommand(id) {
// 从UI中移除
const commandItem = document.querySelector(`.command-item[data-id="${id}"]`);
if (commandItem) {
commandItem.remove();
}
// 从localStorage中移除
let commands = getCommands();
commands = commands.filter(cmd => cmd.id !== id);
localStorage.setItem('droneCommands', JSON.stringify(commands));
showToast('口令已删除');
}
// 页面加载时从localStorage加载命令
window.addEventListener('DOMContentLoaded', function() {
loadCommands();
});
// 从localStorage加载命令到UI
function loadCommands() {
const commands = getCommands();
commands.forEach(cmd => {
addCommandToUI(cmd.id, cmd.question, cmd.answer);
});
}
// 身份核对功能
document.getElementById('checkIdentityBtn').addEventListener('click', function() {
const id = document.getElementById('checkId').value.trim();
const question = document.getElementById('checkQuestion').value.trim();
const answer = document.getElementById('checkAnswer').value.trim();
if (!question || !answer) {
showIdentityResult('请输入完整的问令和答令信息', 'info');
return;
}
if (!id) {
showIdentityResult('请输入无人机编号', 'info');
return;
}
// 获取所有已保存的口令
const commands = getCommands();
let isMatched = false;
// 检查是否有匹配的问答口令
commands.forEach(cmd => {
if (cmd.question === question && cmd.answer === answer) {
isMatched = true;
}
});
// 确定身份
const identity = isMatched ? '友方' : '敌方';
// 显示核验结果
showIdentityResult(`编号 ${id} 核验成功:${identity}目标`, isMatched ? 'success' : 'danger');
// 更新无人机管理和识别记录中的身份信息
updateDroneIdentity(id, identity);
});
// 更新无人机身份信息
function updateDroneIdentity(droneId, identity) {
if (!droneId) return;
console.log(`开始更新无人机 ${droneId} 的身份为 ${identity}`);
// 1. 更新无人机管理中的身份
let updated = false;
try {
const storedDrones = localStorage.getItem('targetDrones');
if (storedDrones) {
console.log('获取到targetDrones数据', storedDrones);
const targetDrones = JSON.parse(storedDrones);
// 查找并更新匹配的无人机
for (let i = 0; i < targetDrones.length; i++) {
if (targetDrones[i].id === droneId) {
console.log(`找到匹配的无人机,当前身份: ${targetDrones[i].identity}`);
targetDrones[i].identity = identity;
updated = true;
console.log(`已更新身份为: ${identity}`);
}
}
// 保存更新后的数据
if (updated) {
localStorage.setItem('targetDrones', JSON.stringify(targetDrones));
console.log(`已保存更新后的targetDrones数据`);
} else {
console.log(`未找到匹配的无人机 ${droneId}`);
// 如果没有找到匹配的无人机,可能是因为数据刚刚被添加但还未完成数据同步
// 尝试创建新的无人机记录
const newDrone = {
id: droneId,
timestamp: new Date().toISOString(),
model: '',
identity: identity,
targetPosition: {
lng: 116.4074,
lat: 39.9042,
alt: 100
},
distance: 0,
relativePosition: {
x: 0,
y: 0,
z: 0
}
};
targetDrones.push(newDrone);
localStorage.setItem('targetDrones', JSON.stringify(targetDrones));
console.log(`已创建并添加新的无人机记录: ${droneId}`);
updated = true;
}
} else {
console.log('未找到targetDrones数据创建新的数据');
// 如果没有targetDrones数据创建新的
const newDrones = [{
id: droneId,
timestamp: new Date().toISOString(),
model: '',
identity: identity,
targetPosition: {
lng: 116.4074,
lat: 39.9042,
alt: 100
},
distance: 0,
relativePosition: {
x: 0,
y: 0,
z: 0
}
}];
localStorage.setItem('targetDrones', JSON.stringify(newDrones));
console.log(`已创建targetDrones数据并添加无人机 ${droneId}`);
updated = true;
}
} catch (error) {
console.error('更新无人机身份失败:', error);
}
// 2. 更新识别记录中的身份
try {
const storedRecords = localStorage.getItem('recordsList');
if (storedRecords) {
const records = JSON.parse(storedRecords);
let recordsUpdated = false;
// 查找并更新匹配的记录
for (let i = 0; i < records.length; i++) {
if (records[i].droneId === droneId) {
records[i].identity = identity;
recordsUpdated = true;
}
}
// 保存更新后的记录
if (recordsUpdated) {
localStorage.setItem('recordsList', JSON.stringify(records));
console.log(`已更新记录中无人机 ${droneId} 的身份为 ${identity}`);
}
}
} catch (error) {
console.error('更新识别记录失败:', error);
}
// 3. 强制更新统计数据
updateRecordsStatistics();
// 4. 立即触发更新事件,确保所有页面都能收到更新
try {
// 获取最新统计数据
const storedStats = localStorage.getItem('droneStats');
if (storedStats) {
const stats = JSON.parse(storedStats);
// 触发自定义事件
const event = new CustomEvent('droneStatsUpdated', { detail: stats });
window.dispatchEvent(event);
console.log('已触发droneStatsUpdated事件通知其他页面更新');
// 为了确保其他页面能收到通知还要模拟storage事件
localStorage.setItem('droneStats_trigger', new Date().getTime().toString());
console.log('已触发storage事件确保跨页面通信');
}
} catch (e) {
console.error('触发统计更新事件失败:', e);
}
// 显示更新结果
if (updated) {
showToast(`已将无人机 ${droneId} 身份更新为 ${identity},并同步更新了识别记录`);
// 触发统计数据更新
updateRecordsStatistics();
// 主动触发droneStatsUpdated事件确保战场态势页面能够收到更新
try {
const storedStats = localStorage.getItem('droneStats');
if (storedStats) {
const stats = JSON.parse(storedStats);
const event = new CustomEvent('droneStatsUpdated', { detail: stats });
window.dispatchEvent(event);
console.log('已在无人机身份更新后触发droneStatsUpdated事件');
// 为了确保其他页面能收到通知还要模拟storage事件
localStorage.setItem('droneStats_trigger', new Date().getTime().toString());
}
} catch (e) {
console.error('触发事件失败:', e);
}
} else {
showToast(`未找到无人机 ${droneId},已创建新的无人机记录`);
}
}
// 更新记录统计
function updateRecordsStatistics() {
console.log('更新记录统计数据');
try {
// 从localStorage获取记录
const storedRecords = localStorage.getItem('recordsList');
if (storedRecords) {
const records = JSON.parse(storedRecords);
// 计算统计数据
const totalCount = records.length;
const friendlyCount = records.filter(record => record.identity === '友方').length;
const hostileCount = records.filter(record => record.identity === '敌方').length;
const unknownCount = records.filter(record => record.identity === '未知' || !record.identity).length;
console.log(`统计结果: 总数=${totalCount}, 友方=${friendlyCount}, 敌方=${hostileCount}, 未知=${unknownCount}`);
// 保存统计数据到localStorage
const stats = {
total: totalCount,
friendly: friendlyCount,
hostile: hostileCount,
unknown: unknownCount,
lastUpdate: new Date().toISOString()
};
localStorage.setItem('droneStats', JSON.stringify(stats));
console.log('记录统计数据已更新到localStorage');
// 触发自定义事件,通知其他页面数据已更新
try {
const event = new CustomEvent('droneStatsUpdated', { detail: stats });
window.dispatchEvent(event);
console.log('已触发droneStatsUpdated事件');
} catch (e) {
console.error('触发事件失败:', e);
}
}
} catch (error) {
console.error('更新记录统计数据失败:', error);
}
}
// 显示身份核对结果
function showIdentityResult(message, type) {
const resultDiv = document.getElementById('identityResult');
const resultText = document.getElementById('identityResultText');
resultDiv.style.display = 'block';
resultText.className = `alert alert-${type}`;
resultText.innerHTML = message;
}
// 显示提示消息
function showToast(message) {
// 检查是否已存在toast容器
let toastContainer = document.getElementById('toast-container');
if (!toastContainer) {
toastContainer = document.createElement('div');
toastContainer.id = 'toast-container';
toastContainer.style.position = 'fixed';
toastContainer.style.bottom = '20px';
toastContainer.style.right = '20px';
toastContainer.style.zIndex = '9999';
document.body.appendChild(toastContainer);
}
// 创建新的toast
const toast = document.createElement('div');
toast.className = 'toast show';
toast.style.backgroundColor = 'rgba(30, 30, 60, 0.9)';
toast.style.color = 'white';
toast.style.padding = '10px 15px';
toast.style.marginBottom = '10px';
toast.style.borderRadius = '4px';
toast.style.boxShadow = '0 0 10px rgba(0,0,0,0.2)';
toast.style.borderLeft = '4px solid #3498db';
toast.textContent = message;
// 添加到容器
toastContainer.appendChild(toast);
// 3秒后自动移除
setTimeout(() => {
toast.style.opacity = '0';
toast.style.transition = 'opacity 0.5s';
setTimeout(() => {
toastContainer.removeChild(toast);
}, 500);
}, 3000);
}
</script>
<!-- 添加测试按钮 -->
<div class="position-fixed" style="bottom: 20px; left: 20px; z-index: 1000;">
<button id="createTestRecordsBtn" class="btn btn-warning">
<i class="fas fa-vial"></i> 创建测试记录
</button>
</div>
<script>
// 绑定测试按钮事件
document.addEventListener('DOMContentLoaded', function() {
const testButton = document.getElementById('createTestRecordsBtn');
if (testButton) {
testButton.addEventListener('click', function() {
if (typeof createTestRecords === 'function') {
createTestRecords();
} else {
alert('createTestRecords函数未定义请确保已加载identification.js');
}
});
}
});
</script>
</body>
</html>

File diff suppressed because it is too large Load Diff

@ -0,0 +1,14 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>无人机敌我识别系统</title>
<script>
window.location.href = 'login.html';
</script>
</head>
<body>
正在跳转到登录页面...
</body>
</html>

@ -0,0 +1,75 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>登录 - 无人机敌我识别系统</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.0.0/css/all.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@300;400;500;700&display=swap" rel="stylesheet">
<link href="common/css/style.css" rel="stylesheet">
</head>
<body class="login-page">
<!-- 雷达动画背景 -->
<div class="radar-animation">
<div class="radar-spinner"></div>
<div class="radar-line"></div>
</div>
<div class="login-container">
<div class="login-box">
<div class="login-header">
<div class="logo-icon">
<div class="military-star"></div>
</div>
<h2>无人机敌我识别系统</h2>
<p class="text-muted">军用级安全认证</p>
</div>
<div class="login-form">
<form id="loginForm" onsubmit="return handleLogin(event)">
<div class="form-group">
<div class="input-group">
<span class="input-group-text">
<i class="fas fa-user-shield"></i>
</span>
<input type="text" class="form-control" id="username" placeholder="用户名" required>
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-text">
<i class="fas fa-key"></i>
</span>
<input type="password" class="form-control" id="password" placeholder="密码" required>
</div>
</div>
<div class="form-group">
<div class="d-flex justify-content-between align-items-center">
<div class="form-check">
<input type="checkbox" class="form-check-input" id="rememberMe">
<label class="form-check-label" for="rememberMe">记住登录</label>
</div>
<a href="#" class="forgot-password">重置密码</a>
</div>
</div>
<button type="submit" class="btn btn-primary w-100">
<i class="fas fa-sign-in-alt me-2"></i>安全登录
</button>
</form>
</div>
<div class="login-footer">
<p class="text-center mb-0">
<small>
<i class="fas fa-shield-alt me-1"></i>
军用级安全加密传输
</small>
</p>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="common/js/api.js"></script>
<script src="common/js/common.js"></script>
</body>
</html>

@ -0,0 +1,257 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>识别记录 - 无人机敌我识别系统</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.0.0/css/all.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@300;400;500;700&display=swap" rel="stylesheet">
<link href="common/css/style.css" rel="stylesheet">
</head>
<body class="battlefield-theme">
<div class="sidebar">
<div class="sidebar-header">
<h4>
<div class="logo-icon">
<i class="fas fa-drone"></i>
</div>
无人机敌我识别系统
</h4>
</div>
<nav class="nav flex-column">
<a class="nav-link" href="dashboard.html">
<i class="fas fa-chart-line"></i>战场态势
</a>
<a class="nav-link" href="identification.html">
<i class="fas fa-crosshairs"></i>目标识别
</a>
<a class="nav-link" href="drones.html">
<i class="fas fa-drone"></i>无人机管理
</a>
<a class="nav-link active" href="records.html">
<i class="fas fa-history"></i>识别记录
</a>
<a class="nav-link" href="encryption.html">
<i class="fas fa-broadcast-tower"></i>信号收发
</a>
</nav>
</div>
<div class="main-content">
<div class="container-fluid records-page">
<!-- 页面头部 -->
<div class="battlefield-header mb-4">
<div class="header-left">
<h2 class="page-title">识别记录</h2>
<div class="battlefield-time">
<i class="fas fa-clock"></i>
<span id="current-time">2024-01-01 12:00:00</span>
</div>
</div>
<div class="operator-info">
<i class="fas fa-user-shield"></i>
操作员:战术指挥官
<span class="status-badge online">在线</span>
</div>
</div>
<!-- 筛选条件卡片 -->
<div class="row mb-4">
<div class="col-12">
<div class="card slide-in">
<div class="card-header">
<h5 class="card-title">
<i class="fas fa-filter"></i> 筛选条件
</h5>
</div>
<div class="card-body">
<form id="filterForm" class="row g-3">
<div class="col-md-3">
<label class="form-label">时间范围</label>
<select class="form-select" id="timeRange">
<option value="today">今天</option>
<option value="week">本周</option>
<option value="month">本月</option>
<option value="custom">自定义</option>
</select>
</div>
<div class="col-md-3">
<label class="form-label">编号</label>
<input type="text" class="form-control" id="droneId" placeholder="输入编号">
</div>
<div class="col-md-3">
<label class="form-label">型号</label>
<input type="text" class="form-control" id="droneModel" placeholder="输入型号">
</div>
<div class="col-md-3">
<label class="form-label">身份</label>
<select class="form-select" id="droneIdentity">
<option value="">全部</option>
<option value="友方">友方</option>
<option value="敌方">敌方</option>
<option value="未知">未知</option>
</select>
</div>
<div class="col-12 mt-4">
<button type="submit" class="btn btn-primary">
<i class="fas fa-search"></i> 搜索
</button>
<button type="reset" class="btn btn-secondary ms-2">
<i class="fas fa-redo"></i> 重置
</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- 记录列表卡片 -->
<div class="row">
<div class="col-12">
<div class="card slide-in">
<div class="card-header">
<div class="d-flex justify-content-between align-items-center">
<h5 class="card-title">
<i class="fas fa-list"></i> 识别记录列表
</h5>
<div class="btn-group">
<button class="btn btn-outline-primary">
<i class="fas fa-download"></i> 导出
</button>
<button class="btn btn-outline-primary ms-2">
<i class="fas fa-print"></i> 打印
</button>
</div>
</div>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>时间</th>
<th>编号</th>
<th>型号</th>
<th>身份</th>
<th>经纬度</th>
<th>海拔</th>
<th>相对距离</th>
<th>相对位置</th>
<th>操作</th>
</tr>
</thead>
<tbody id="recordsList">
<!-- 示例数据 -->
</tbody>
</table>
</div>
<nav aria-label="Page navigation" class="mt-4">
<ul class="pagination justify-content-center">
<li class="page-item disabled">
<a class="page-link" href="#" tabindex="-1">上一页</a>
</li>
<li class="page-item active"><a class="page-link" href="#">1</a></li>
<li class="page-item"><a class="page-link" href="#">2</a></li>
<li class="page-item"><a class="page-link" href="#">3</a></li>
<li class="page-item">
<a class="page-link" href="#">下一页</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- 记录详情模态框 -->
<div class="modal fade" id="recordDetailModal" tabindex="-1">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">识别记录详情</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-6">
<img src="" class="img-fluid mb-3" id="targetImage" alt="目标图像">
</div>
<div class="col-md-6">
<h6 class="text-accent mb-3">基本信息</h6>
<table class="table table-sm">
<tbody>
<tr>
<td width="35%">识别时间:</td>
<td id="detailTime">2024-01-15 14:30:25</td>
</tr>
<tr>
<td>编号:</td>
<td id="detailId"></td>
</tr>
<tr>
<td>型号:</td>
<td id="detailModel"></td>
</tr>
<tr>
<td>身份:</td>
<td id="detailIdentity"></td>
</tr>
<tr>
<td>经纬度:</td>
<td id="detailLocation"></td>
</tr>
<tr>
<td>海拔:</td>
<td id="detailAltitude"></td>
</tr>
<tr>
<td>相对距离:</td>
<td id="detailDistance"></td>
</tr>
<tr>
<td>相对位置:</td>
<td id="detailRelativePosition"></td>
</tr>
</tbody>
</table>
<h6 class="text-accent mb-3">技术参数</h6>
<table class="table table-sm">
<tbody>
<tr>
<td width="35%">飞行高度:</td>
<td>1,200米</td>
</tr>
<tr>
<td>飞行速度:</td>
<td>180km/h</td>
</tr>
<tr>
<td>航向角度:</td>
<td>45°</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
<button type="button" class="btn btn-primary">
<i class="fas fa-download"></i> 导出详情
</button>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="common/js/api.js"></script>
<script src="common/js/common.js"></script>
<script src="common/js/records.js"></script>
</body>
</html>

@ -0,0 +1,135 @@
import http.server
import socketserver
import os
import sys
import argparse
import json
import subprocess
import socket
import time
# 解析命令行参数
parser = argparse.ArgumentParser(description='启动前端服务器')
parser.add_argument('--port', type=int, default=8081, help='指定服务器端口号')
args = parser.parse_args()
# 设置端口
PORT = args.port
# 自定义处理器添加CORS头
class CORSHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
def end_headers(self):
# 添加CORS头
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
self.send_header('Access-Control-Allow-Headers', 'Content-Type, Authorization')
super().end_headers()
def do_OPTIONS(self):
# 处理OPTIONS请求
self.send_response(200)
self.end_headers()
def do_POST(self):
# 处理POST请求
if self.path == '/api/open-vlc':
try:
# 直接执行VLC命令忽略所有输出防止编码错误
subprocess.Popen(
r"python drone_detector.py --source shibie.mp4 --conf 0.59 --save --view",
shell=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
creationflags=subprocess.CREATE_NO_WINDOW # 防止显示命令窗口
)
# 返回响应
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({'success': True}).encode())
except Exception as e:
# 捕获所有异常,确保服务器不会崩溃
print(f"执行VLC命令时出错: {str(e)}")
self.send_response(500)
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({'success': False, 'error': str(e)}).encode())
else:
# 对于不支持的请求
self.send_response(405)
self.end_headers()
self.wfile.write(b'Method Not Allowed')
# 自定义TCP服务器确保端口可以立即重用
class MyTCPServer(socketserver.TCPServer):
def server_bind(self):
# 设置 SO_REUSEADDR 选项
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# 在支持的平台上设置 SO_REUSEPORT 选项
if hasattr(socket, 'SO_REUSEPORT'):
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
self.socket.bind(self.server_address)
self.server_address = self.socket.getsockname()
# 检查端口是否被占用,如果占用则尝试关闭
def check_and_free_port(port):
try:
# 尝试连接到端口,检查是否被占用
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1)
result = sock.connect_ex(('localhost', port))
sock.close()
if result == 0: # 端口被占用
print(f"端口 {port} 已被占用,尝试强制释放...")
# 在Windows上可以使用netstat和taskkill来查找并终止占用端口的进程
try:
# 查找占用端口的进程ID
cmd = f'for /f "tokens=5" %a in (\'netstat -aon ^| findstr :{port}\') do @echo %a'
result = subprocess.check_output(cmd, shell=True).decode().strip()
if result:
pids = set(result.split('\n'))
for pid in pids:
if pid.isdigit():
print(f"正在终止进程ID: {pid}")
subprocess.call(f'taskkill /F /PID {pid}', shell=True)
# 等待端口释放
time.sleep(1)
return True
except Exception as e:
print(f"尝试释放端口时出错: {e}")
return False
return True
except Exception as e:
print(f"检查端口时出错: {e}")
return False
# 打印启动信息
print(f"启动前端服务器,端口: {PORT}")
print(f"请在浏览器中访问: http://localhost:{PORT}")
print("按Ctrl+C终止服务器")
# 启动服务器
if not check_and_free_port(PORT):
print(f"无法释放端口 {PORT},请手动关闭占用该端口的程序后再试")
sys.exit(1)
try:
with MyTCPServer(("", PORT), CORSHTTPRequestHandler) as httpd:
print("前端服务器正在运行...")
try:
httpd.serve_forever()
except KeyboardInterrupt:
print("\n正在关闭服务器...")
httpd.server_close() # 显式关闭服务器
print("服务器已停止")
except OSError as e:
if e.errno == 10048: # Windows错误码端口已被占用
print(f"错误: 端口 {PORT} 已被占用,请关闭占用该端口的程序后再试")
sys.exit(1)
else:
print(f"服务器启动错误: {e}")
sys.exit(2)

@ -0,0 +1,15 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>信号收发 - 无人机敌我识别系统</title>
<meta http-equiv="refresh" content="0; url=encryption.html">
</head>
<body>
<p>如果您没有被自动重定向,请<a href="encryption.html">点击这里</a></p>
<script>
window.location.href = "encryption.html";
</script>
</body>
</html>

File diff suppressed because it is too large Load Diff

@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../mime/cli.js" "$@"
else
exec node "$basedir/../mime/cli.js" "$@"
fi

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\mime\cli.js" %*

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../mime/cli.js" $args
} else {
& "$basedir/node$exe" "$basedir/../mime/cli.js" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../mime/cli.js" $args
} else {
& "node$exe" "$basedir/../mime/cli.js" $args
}
$ret=$LASTEXITCODE
}
exit $ret

@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../node-media-server/bin/app.js" "$@"
else
exec node "$basedir/../node-media-server/bin/app.js" "$@"
fi

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\node-media-server\bin\app.js" %*

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../node-media-server/bin/app.js" $args
} else {
& "$basedir/node$exe" "$basedir/../node-media-server/bin/app.js" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../node-media-server/bin/app.js" $args
} else {
& "node$exe" "$basedir/../node-media-server/bin/app.js" $args
}
$ret=$LASTEXITCODE
}
exit $ret

@ -0,0 +1,872 @@
{
"name": "无人机",
"lockfileVersion": 3,
"requires": true,
"packages": {
"node_modules/accepts": {
"version": "1.3.8",
"resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz",
"integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==",
"license": "MIT",
"dependencies": {
"mime-types": "~2.1.34",
"negotiator": "0.6.3"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/array-flatten": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
"integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==",
"license": "MIT"
},
"node_modules/body-parser": {
"version": "1.20.3",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.3.tgz",
"integrity": "sha512-7rAxByjUMqQ3/bHJy7D6OGXvx/MMc4IqBn/X0fcM1QUcAItpZrBEYhWGem+tzXH90c+G01ypMcYJBO9Y30203g==",
"license": "MIT",
"dependencies": {
"bytes": "3.1.2",
"content-type": "~1.0.5",
"debug": "2.6.9",
"depd": "2.0.0",
"destroy": "1.2.0",
"http-errors": "2.0.0",
"iconv-lite": "0.4.24",
"on-finished": "2.4.1",
"qs": "6.13.0",
"raw-body": "2.5.2",
"type-is": "~1.6.18",
"unpipe": "1.0.0"
},
"engines": {
"node": ">= 0.8",
"npm": "1.2.8000 || >= 1.4.16"
}
},
"node_modules/bytes": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
"integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/call-bind-apply-helpers": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
"integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"function-bind": "^1.1.2"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/call-bound": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz",
"integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",
"license": "MIT",
"dependencies": {
"call-bind-apply-helpers": "^1.0.2",
"get-intrinsic": "^1.3.0"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/content-disposition": {
"version": "0.5.4",
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz",
"integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==",
"license": "MIT",
"dependencies": {
"safe-buffer": "5.2.1"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/content-type": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz",
"integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/cookie": {
"version": "0.7.1",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.1.tgz",
"integrity": "sha512-6DnInpx7SJ2AK3+CTUE/ZM0vWTUboZCegxhC2xiIydHR9jNuTAASBrfEpHhiGOZw/nX51bHt6YQl8jsGo4y/0w==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/cookie-signature": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz",
"integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==",
"license": "MIT"
},
"node_modules/cors": {
"version": "2.8.5",
"resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz",
"integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==",
"license": "MIT",
"dependencies": {
"object-assign": "^4",
"vary": "^1"
},
"engines": {
"node": ">= 0.10"
}
},
"node_modules/debug": {
"version": "2.6.9",
"resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
"integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
"license": "MIT",
"dependencies": {
"ms": "2.0.0"
}
},
"node_modules/depd": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
"integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/destroy": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz",
"integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==",
"license": "MIT",
"engines": {
"node": ">= 0.8",
"npm": "1.2.8000 || >= 1.4.16"
}
},
"node_modules/dunder-proto": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
"integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
"license": "MIT",
"dependencies": {
"call-bind-apply-helpers": "^1.0.1",
"es-errors": "^1.3.0",
"gopd": "^1.2.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/ee-first": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
"integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",
"license": "MIT"
},
"node_modules/encodeurl": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",
"integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/es-define-property": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
"integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/es-errors": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
"integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/es-object-atoms": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz",
"integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/escape-html": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
"integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",
"license": "MIT"
},
"node_modules/etag": {
"version": "1.8.1",
"resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",
"integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/express": {
"version": "4.21.2",
"resolved": "https://registry.npmjs.org/express/-/express-4.21.2.tgz",
"integrity": "sha512-28HqgMZAmih1Czt9ny7qr6ek2qddF4FclbMzwhCREB6OFfH+rXAnuNCwo1/wFvrtbgsQDb4kSbX9de9lFbrXnA==",
"license": "MIT",
"dependencies": {
"accepts": "~1.3.8",
"array-flatten": "1.1.1",
"body-parser": "1.20.3",
"content-disposition": "0.5.4",
"content-type": "~1.0.4",
"cookie": "0.7.1",
"cookie-signature": "1.0.6",
"debug": "2.6.9",
"depd": "2.0.0",
"encodeurl": "~2.0.0",
"escape-html": "~1.0.3",
"etag": "~1.8.1",
"finalhandler": "1.3.1",
"fresh": "0.5.2",
"http-errors": "2.0.0",
"merge-descriptors": "1.0.3",
"methods": "~1.1.2",
"on-finished": "2.4.1",
"parseurl": "~1.3.3",
"path-to-regexp": "0.1.12",
"proxy-addr": "~2.0.7",
"qs": "6.13.0",
"range-parser": "~1.2.1",
"safe-buffer": "5.2.1",
"send": "0.19.0",
"serve-static": "1.16.2",
"setprototypeof": "1.2.0",
"statuses": "2.0.1",
"type-is": "~1.6.18",
"utils-merge": "1.0.1",
"vary": "~1.1.2"
},
"engines": {
"node": ">= 0.10.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/finalhandler": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.1.tgz",
"integrity": "sha512-6BN9trH7bp3qvnrRyzsBz+g3lZxTNZTbVO2EV1CS0WIcDbawYVdYvGflME/9QP0h0pYlCDBCTjYa9nZzMDpyxQ==",
"license": "MIT",
"dependencies": {
"debug": "2.6.9",
"encodeurl": "~2.0.0",
"escape-html": "~1.0.3",
"on-finished": "2.4.1",
"parseurl": "~1.3.3",
"statuses": "2.0.1",
"unpipe": "~1.0.0"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/forwarded": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
"integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/fresh": {
"version": "0.5.2",
"resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz",
"integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/function-bind": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
"integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/get-intrinsic": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
"integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
"license": "MIT",
"dependencies": {
"call-bind-apply-helpers": "^1.0.2",
"es-define-property": "^1.0.1",
"es-errors": "^1.3.0",
"es-object-atoms": "^1.1.1",
"function-bind": "^1.1.2",
"get-proto": "^1.0.1",
"gopd": "^1.2.0",
"has-symbols": "^1.1.0",
"hasown": "^2.0.2",
"math-intrinsics": "^1.1.0"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/get-proto": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
"integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
"license": "MIT",
"dependencies": {
"dunder-proto": "^1.0.1",
"es-object-atoms": "^1.0.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/gopd": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
"integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/has-symbols": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
"integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/hasown": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",
"integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",
"license": "MIT",
"dependencies": {
"function-bind": "^1.1.2"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/http-errors": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz",
"integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==",
"license": "MIT",
"dependencies": {
"depd": "2.0.0",
"inherits": "2.0.4",
"setprototypeof": "1.2.0",
"statuses": "2.0.1",
"toidentifier": "1.0.1"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/http2-express": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/http2-express/-/http2-express-1.0.1.tgz",
"integrity": "sha512-3NP5595eHFkZOBD4RXCNDrTQvuxKfcr3Q62RrHlywNc0vw/PR2HKxtF4JqFhXWVJsxb9pTf/1hZ8iLaJrWdUmQ==",
"license": "MIT",
"engines": {
"node": ">= 20.0.0"
}
},
"node_modules/iconv-lite": {
"version": "0.4.24",
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz",
"integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==",
"license": "MIT",
"dependencies": {
"safer-buffer": ">= 2.1.2 < 3"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/inherits": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
"license": "ISC"
},
"node_modules/ipaddr.js": {
"version": "1.9.1",
"resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
"integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",
"license": "MIT",
"engines": {
"node": ">= 0.10"
}
},
"node_modules/math-intrinsics": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
"integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/media-typer": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
"integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/merge-descriptors": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz",
"integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/methods": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz",
"integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/mime": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz",
"integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==",
"license": "MIT",
"bin": {
"mime": "cli.js"
},
"engines": {
"node": ">=4"
}
},
"node_modules/mime-db": {
"version": "1.52.0",
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
"integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/mime-types": {
"version": "2.1.35",
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
"integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
"license": "MIT",
"dependencies": {
"mime-db": "1.52.0"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/ms": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
"license": "MIT"
},
"node_modules/negotiator": {
"version": "0.6.3",
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz",
"integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/node-media-server": {
"version": "4.0.18",
"resolved": "https://registry.npmjs.org/node-media-server/-/node-media-server-4.0.18.tgz",
"integrity": "sha512-4MTsrSDP1LSr9OFo+x7v40qMdKbuU78cQm/ykslZwMjjcOlGSbUjOsdC06bEwVNNd1zcNT/M+saqtouGK0lhCw==",
"license": "Apache-2.0",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.21.2",
"http2-express": "^1.0.0"
},
"bin": {
"node-media-server": "bin/app.js"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/object-assign": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
"integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/object-inspect": {
"version": "1.13.4",
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
"integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/on-finished": {
"version": "2.4.1",
"resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz",
"integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==",
"license": "MIT",
"dependencies": {
"ee-first": "1.1.1"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/parseurl": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
"integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/path-to-regexp": {
"version": "0.1.12",
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.12.tgz",
"integrity": "sha512-RA1GjUVMnvYFxuqovrEqZoxxW5NUZqbwKtYz/Tt7nXerk0LbLblQmrsgdeOxV5SFHf0UDggjS/bSeOZwt1pmEQ==",
"license": "MIT"
},
"node_modules/proxy-addr": {
"version": "2.0.7",
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
"integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==",
"license": "MIT",
"dependencies": {
"forwarded": "0.2.0",
"ipaddr.js": "1.9.1"
},
"engines": {
"node": ">= 0.10"
}
},
"node_modules/qs": {
"version": "6.13.0",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.13.0.tgz",
"integrity": "sha512-+38qI9SOr8tfZ4QmJNplMUxqjbe7LKvvZgWdExBOmd+egZTtjLB67Gu0HRX3u/XOq7UU2Nx6nsjvS16Z9uwfpg==",
"license": "BSD-3-Clause",
"dependencies": {
"side-channel": "^1.0.6"
},
"engines": {
"node": ">=0.6"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/range-parser": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",
"integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/raw-body": {
"version": "2.5.2",
"resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.2.tgz",
"integrity": "sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==",
"license": "MIT",
"dependencies": {
"bytes": "3.1.2",
"http-errors": "2.0.0",
"iconv-lite": "0.4.24",
"unpipe": "1.0.0"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/safe-buffer": {
"version": "5.2.1",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
"integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "MIT"
},
"node_modules/safer-buffer": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
"license": "MIT"
},
"node_modules/send": {
"version": "0.19.0",
"resolved": "https://registry.npmjs.org/send/-/send-0.19.0.tgz",
"integrity": "sha512-dW41u5VfLXu8SJh5bwRmyYUbAoSB3c9uQh6L8h/KtsFREPWpbX1lrljJo186Jc4nmci/sGUZ9a0a0J2zgfq2hw==",
"license": "MIT",
"dependencies": {
"debug": "2.6.9",
"depd": "2.0.0",
"destroy": "1.2.0",
"encodeurl": "~1.0.2",
"escape-html": "~1.0.3",
"etag": "~1.8.1",
"fresh": "0.5.2",
"http-errors": "2.0.0",
"mime": "1.6.0",
"ms": "2.1.3",
"on-finished": "2.4.1",
"range-parser": "~1.2.1",
"statuses": "2.0.1"
},
"engines": {
"node": ">= 0.8.0"
}
},
"node_modules/send/node_modules/encodeurl": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz",
"integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/send/node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"license": "MIT"
},
"node_modules/serve-static": {
"version": "1.16.2",
"resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.2.tgz",
"integrity": "sha512-VqpjJZKadQB/PEbEwvFdO43Ax5dFBZ2UECszz8bQ7pi7wt//PWe1P6MN7eCnjsatYtBT6EuiClbjSWP2WrIoTw==",
"license": "MIT",
"dependencies": {
"encodeurl": "~2.0.0",
"escape-html": "~1.0.3",
"parseurl": "~1.3.3",
"send": "0.19.0"
},
"engines": {
"node": ">= 0.8.0"
}
},
"node_modules/setprototypeof": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
"integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",
"license": "ISC"
},
"node_modules/side-channel": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz",
"integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"object-inspect": "^1.13.3",
"side-channel-list": "^1.0.0",
"side-channel-map": "^1.0.1",
"side-channel-weakmap": "^1.0.2"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/side-channel-list": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz",
"integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"object-inspect": "^1.13.3"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/side-channel-map": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz",
"integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",
"license": "MIT",
"dependencies": {
"call-bound": "^1.0.2",
"es-errors": "^1.3.0",
"get-intrinsic": "^1.2.5",
"object-inspect": "^1.13.3"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/side-channel-weakmap": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",
"integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",
"license": "MIT",
"dependencies": {
"call-bound": "^1.0.2",
"es-errors": "^1.3.0",
"get-intrinsic": "^1.2.5",
"object-inspect": "^1.13.3",
"side-channel-map": "^1.0.1"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/statuses": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz",
"integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/toidentifier": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
"integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",
"license": "MIT",
"engines": {
"node": ">=0.6"
}
},
"node_modules/type-is": {
"version": "1.6.18",
"resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz",
"integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==",
"license": "MIT",
"dependencies": {
"media-typer": "0.3.0",
"mime-types": "~2.1.24"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/unpipe": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
"integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/utils-merge": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
"integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==",
"license": "MIT",
"engines": {
"node": ">= 0.4.0"
}
},
"node_modules/vary": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
"integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
}
}
}

@ -0,0 +1,243 @@
1.3.8 / 2022-02-02
==================
* deps: mime-types@~2.1.34
- deps: mime-db@~1.51.0
* deps: negotiator@0.6.3
1.3.7 / 2019-04-29
==================
* deps: negotiator@0.6.2
- Fix sorting charset, encoding, and language with extra parameters
1.3.6 / 2019-04-28
==================
* deps: mime-types@~2.1.24
- deps: mime-db@~1.40.0
1.3.5 / 2018-02-28
==================
* deps: mime-types@~2.1.18
- deps: mime-db@~1.33.0
1.3.4 / 2017-08-22
==================
* deps: mime-types@~2.1.16
- deps: mime-db@~1.29.0
1.3.3 / 2016-05-02
==================
* deps: mime-types@~2.1.11
- deps: mime-db@~1.23.0
* deps: negotiator@0.6.1
- perf: improve `Accept` parsing speed
- perf: improve `Accept-Charset` parsing speed
- perf: improve `Accept-Encoding` parsing speed
- perf: improve `Accept-Language` parsing speed
1.3.2 / 2016-03-08
==================
* deps: mime-types@~2.1.10
- Fix extension of `application/dash+xml`
- Update primary extension for `audio/mp4`
- deps: mime-db@~1.22.0
1.3.1 / 2016-01-19
==================
* deps: mime-types@~2.1.9
- deps: mime-db@~1.21.0
1.3.0 / 2015-09-29
==================
* deps: mime-types@~2.1.7
- deps: mime-db@~1.19.0
* deps: negotiator@0.6.0
- Fix including type extensions in parameters in `Accept` parsing
- Fix parsing `Accept` parameters with quoted equals
- Fix parsing `Accept` parameters with quoted semicolons
- Lazy-load modules from main entry point
- perf: delay type concatenation until needed
- perf: enable strict mode
- perf: hoist regular expressions
- perf: remove closures getting spec properties
- perf: remove a closure from media type parsing
- perf: remove property delete from media type parsing
1.2.13 / 2015-09-06
===================
* deps: mime-types@~2.1.6
- deps: mime-db@~1.18.0
1.2.12 / 2015-07-30
===================
* deps: mime-types@~2.1.4
- deps: mime-db@~1.16.0
1.2.11 / 2015-07-16
===================
* deps: mime-types@~2.1.3
- deps: mime-db@~1.15.0
1.2.10 / 2015-07-01
===================
* deps: mime-types@~2.1.2
- deps: mime-db@~1.14.0
1.2.9 / 2015-06-08
==================
* deps: mime-types@~2.1.1
- perf: fix deopt during mapping
1.2.8 / 2015-06-07
==================
* deps: mime-types@~2.1.0
- deps: mime-db@~1.13.0
* perf: avoid argument reassignment & argument slice
* perf: avoid negotiator recursive construction
* perf: enable strict mode
* perf: remove unnecessary bitwise operator
1.2.7 / 2015-05-10
==================
* deps: negotiator@0.5.3
- Fix media type parameter matching to be case-insensitive
1.2.6 / 2015-05-07
==================
* deps: mime-types@~2.0.11
- deps: mime-db@~1.9.1
* deps: negotiator@0.5.2
- Fix comparing media types with quoted values
- Fix splitting media types with quoted commas
1.2.5 / 2015-03-13
==================
* deps: mime-types@~2.0.10
- deps: mime-db@~1.8.0
1.2.4 / 2015-02-14
==================
* Support Node.js 0.6
* deps: mime-types@~2.0.9
- deps: mime-db@~1.7.0
* deps: negotiator@0.5.1
- Fix preference sorting to be stable for long acceptable lists
1.2.3 / 2015-01-31
==================
* deps: mime-types@~2.0.8
- deps: mime-db@~1.6.0
1.2.2 / 2014-12-30
==================
* deps: mime-types@~2.0.7
- deps: mime-db@~1.5.0
1.2.1 / 2014-12-30
==================
* deps: mime-types@~2.0.5
- deps: mime-db@~1.3.1
1.2.0 / 2014-12-19
==================
* deps: negotiator@0.5.0
- Fix list return order when large accepted list
- Fix missing identity encoding when q=0 exists
- Remove dynamic building of Negotiator class
1.1.4 / 2014-12-10
==================
* deps: mime-types@~2.0.4
- deps: mime-db@~1.3.0
1.1.3 / 2014-11-09
==================
* deps: mime-types@~2.0.3
- deps: mime-db@~1.2.0
1.1.2 / 2014-10-14
==================
* deps: negotiator@0.4.9
- Fix error when media type has invalid parameter
1.1.1 / 2014-09-28
==================
* deps: mime-types@~2.0.2
- deps: mime-db@~1.1.0
* deps: negotiator@0.4.8
- Fix all negotiations to be case-insensitive
- Stable sort preferences of same quality according to client order
1.1.0 / 2014-09-02
==================
* update `mime-types`
1.0.7 / 2014-07-04
==================
* Fix wrong type returned from `type` when match after unknown extension
1.0.6 / 2014-06-24
==================
* deps: negotiator@0.4.7
1.0.5 / 2014-06-20
==================
* fix crash when unknown extension given
1.0.4 / 2014-06-19
==================
* use `mime-types`
1.0.3 / 2014-06-11
==================
* deps: negotiator@0.4.6
- Order by specificity when quality is the same
1.0.2 / 2014-05-29
==================
* Fix interpretation when header not in request
* deps: pin negotiator@0.4.5
1.0.1 / 2014-01-18
==================
* Identity encoding isn't always acceptable
* deps: negotiator@~0.4.0
1.0.0 / 2013-12-27
==================
* Genesis

@ -0,0 +1,23 @@
(The MIT License)
Copyright (c) 2014 Jonathan Ong <me@jongleberry.com>
Copyright (c) 2015 Douglas Christopher Wilson <doug@somethingdoug.com>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

@ -0,0 +1,140 @@
# accepts
[![NPM Version][npm-version-image]][npm-url]
[![NPM Downloads][npm-downloads-image]][npm-url]
[![Node.js Version][node-version-image]][node-version-url]
[![Build Status][github-actions-ci-image]][github-actions-ci-url]
[![Test Coverage][coveralls-image]][coveralls-url]
Higher level content negotiation based on [negotiator](https://www.npmjs.com/package/negotiator).
Extracted from [koa](https://www.npmjs.com/package/koa) for general use.
In addition to negotiator, it allows:
- Allows types as an array or arguments list, ie `(['text/html', 'application/json'])`
as well as `('text/html', 'application/json')`.
- Allows type shorthands such as `json`.
- Returns `false` when no types match
- Treats non-existent headers as `*`
## Installation
This is a [Node.js](https://nodejs.org/en/) module available through the
[npm registry](https://www.npmjs.com/). Installation is done using the
[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
```sh
$ npm install accepts
```
## API
```js
var accepts = require('accepts')
```
### accepts(req)
Create a new `Accepts` object for the given `req`.
#### .charset(charsets)
Return the first accepted charset. If nothing in `charsets` is accepted,
then `false` is returned.
#### .charsets()
Return the charsets that the request accepts, in the order of the client's
preference (most preferred first).
#### .encoding(encodings)
Return the first accepted encoding. If nothing in `encodings` is accepted,
then `false` is returned.
#### .encodings()
Return the encodings that the request accepts, in the order of the client's
preference (most preferred first).
#### .language(languages)
Return the first accepted language. If nothing in `languages` is accepted,
then `false` is returned.
#### .languages()
Return the languages that the request accepts, in the order of the client's
preference (most preferred first).
#### .type(types)
Return the first accepted type (and it is returned as the same text as what
appears in the `types` array). If nothing in `types` is accepted, then `false`
is returned.
The `types` array can contain full MIME types or file extensions. Any value
that is not a full MIME types is passed to `require('mime-types').lookup`.
#### .types()
Return the types that the request accepts, in the order of the client's
preference (most preferred first).
## Examples
### Simple type negotiation
This simple example shows how to use `accepts` to return a different typed
respond body based on what the client wants to accept. The server lists it's
preferences in order and will get back the best match between the client and
server.
```js
var accepts = require('accepts')
var http = require('http')
function app (req, res) {
var accept = accepts(req)
// the order of this list is significant; should be server preferred order
switch (accept.type(['json', 'html'])) {
case 'json':
res.setHeader('Content-Type', 'application/json')
res.write('{"hello":"world!"}')
break
case 'html':
res.setHeader('Content-Type', 'text/html')
res.write('<b>hello, world!</b>')
break
default:
// the fallback is text/plain, so no need to specify it above
res.setHeader('Content-Type', 'text/plain')
res.write('hello, world!')
break
}
res.end()
}
http.createServer(app).listen(3000)
```
You can test this out with the cURL program:
```sh
curl -I -H'Accept: text/html' http://localhost:3000/
```
## License
[MIT](LICENSE)
[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/accepts/master
[coveralls-url]: https://coveralls.io/r/jshttp/accepts?branch=master
[github-actions-ci-image]: https://badgen.net/github/checks/jshttp/accepts/master?label=ci
[github-actions-ci-url]: https://github.com/jshttp/accepts/actions/workflows/ci.yml
[node-version-image]: https://badgen.net/npm/node/accepts
[node-version-url]: https://nodejs.org/en/download
[npm-downloads-image]: https://badgen.net/npm/dm/accepts
[npm-url]: https://npmjs.org/package/accepts
[npm-version-image]: https://badgen.net/npm/v/accepts

@ -0,0 +1,238 @@
/*!
* accepts
* Copyright(c) 2014 Jonathan Ong
* Copyright(c) 2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Module dependencies.
* @private
*/
var Negotiator = require('negotiator')
var mime = require('mime-types')
/**
* Module exports.
* @public
*/
module.exports = Accepts
/**
* Create a new Accepts object for the given req.
*
* @param {object} req
* @public
*/
function Accepts (req) {
if (!(this instanceof Accepts)) {
return new Accepts(req)
}
this.headers = req.headers
this.negotiator = new Negotiator(req)
}
/**
* Check if the given `type(s)` is acceptable, returning
* the best match when true, otherwise `undefined`, in which
* case you should respond with 406 "Not Acceptable".
*
* The `type` value may be a single mime type string
* such as "application/json", the extension name
* such as "json" or an array `["json", "html", "text/plain"]`. When a list
* or array is given the _best_ match, if any is returned.
*
* Examples:
*
* // Accept: text/html
* this.types('html');
* // => "html"
*
* // Accept: text/*, application/json
* this.types('html');
* // => "html"
* this.types('text/html');
* // => "text/html"
* this.types('json', 'text');
* // => "json"
* this.types('application/json');
* // => "application/json"
*
* // Accept: text/*, application/json
* this.types('image/png');
* this.types('png');
* // => undefined
*
* // Accept: text/*;q=.5, application/json
* this.types(['html', 'json']);
* this.types('html', 'json');
* // => "json"
*
* @param {String|Array} types...
* @return {String|Array|Boolean}
* @public
*/
Accepts.prototype.type =
Accepts.prototype.types = function (types_) {
var types = types_
// support flattened arguments
if (types && !Array.isArray(types)) {
types = new Array(arguments.length)
for (var i = 0; i < types.length; i++) {
types[i] = arguments[i]
}
}
// no types, return all requested types
if (!types || types.length === 0) {
return this.negotiator.mediaTypes()
}
// no accept header, return first given type
if (!this.headers.accept) {
return types[0]
}
var mimes = types.map(extToMime)
var accepts = this.negotiator.mediaTypes(mimes.filter(validMime))
var first = accepts[0]
return first
? types[mimes.indexOf(first)]
: false
}
/**
* Return accepted encodings or best fit based on `encodings`.
*
* Given `Accept-Encoding: gzip, deflate`
* an array sorted by quality is returned:
*
* ['gzip', 'deflate']
*
* @param {String|Array} encodings...
* @return {String|Array}
* @public
*/
Accepts.prototype.encoding =
Accepts.prototype.encodings = function (encodings_) {
var encodings = encodings_
// support flattened arguments
if (encodings && !Array.isArray(encodings)) {
encodings = new Array(arguments.length)
for (var i = 0; i < encodings.length; i++) {
encodings[i] = arguments[i]
}
}
// no encodings, return all requested encodings
if (!encodings || encodings.length === 0) {
return this.negotiator.encodings()
}
return this.negotiator.encodings(encodings)[0] || false
}
/**
* Return accepted charsets or best fit based on `charsets`.
*
* Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5`
* an array sorted by quality is returned:
*
* ['utf-8', 'utf-7', 'iso-8859-1']
*
* @param {String|Array} charsets...
* @return {String|Array}
* @public
*/
Accepts.prototype.charset =
Accepts.prototype.charsets = function (charsets_) {
var charsets = charsets_
// support flattened arguments
if (charsets && !Array.isArray(charsets)) {
charsets = new Array(arguments.length)
for (var i = 0; i < charsets.length; i++) {
charsets[i] = arguments[i]
}
}
// no charsets, return all requested charsets
if (!charsets || charsets.length === 0) {
return this.negotiator.charsets()
}
return this.negotiator.charsets(charsets)[0] || false
}
/**
* Return accepted languages or best fit based on `langs`.
*
* Given `Accept-Language: en;q=0.8, es, pt`
* an array sorted by quality is returned:
*
* ['es', 'pt', 'en']
*
* @param {String|Array} langs...
* @return {Array|String}
* @public
*/
Accepts.prototype.lang =
Accepts.prototype.langs =
Accepts.prototype.language =
Accepts.prototype.languages = function (languages_) {
var languages = languages_
// support flattened arguments
if (languages && !Array.isArray(languages)) {
languages = new Array(arguments.length)
for (var i = 0; i < languages.length; i++) {
languages[i] = arguments[i]
}
}
// no languages, return all requested languages
if (!languages || languages.length === 0) {
return this.negotiator.languages()
}
return this.negotiator.languages(languages)[0] || false
}
/**
* Convert extnames to mime.
*
* @param {String} type
* @return {String}
* @private
*/
function extToMime (type) {
return type.indexOf('/') === -1
? mime.lookup(type)
: type
}
/**
* Check if mime is valid.
*
* @param {String} type
* @return {String}
* @private
*/
function validMime (type) {
return typeof type === 'string'
}

@ -0,0 +1,47 @@
{
"name": "accepts",
"description": "Higher-level content negotiation",
"version": "1.3.8",
"contributors": [
"Douglas Christopher Wilson <doug@somethingdoug.com>",
"Jonathan Ong <me@jongleberry.com> (http://jongleberry.com)"
],
"license": "MIT",
"repository": "jshttp/accepts",
"dependencies": {
"mime-types": "~2.1.34",
"negotiator": "0.6.3"
},
"devDependencies": {
"deep-equal": "1.0.1",
"eslint": "7.32.0",
"eslint-config-standard": "14.1.1",
"eslint-plugin-import": "2.25.4",
"eslint-plugin-markdown": "2.2.1",
"eslint-plugin-node": "11.1.0",
"eslint-plugin-promise": "4.3.1",
"eslint-plugin-standard": "4.1.0",
"mocha": "9.2.0",
"nyc": "15.1.0"
},
"files": [
"LICENSE",
"HISTORY.md",
"index.js"
],
"engines": {
"node": ">= 0.6"
},
"scripts": {
"lint": "eslint .",
"test": "mocha --reporter spec --check-leaks --bail test/",
"test-ci": "nyc --reporter=lcov --reporter=text npm test",
"test-cov": "nyc --reporter=html --reporter=text npm test"
},
"keywords": [
"content",
"negotiation",
"accept",
"accepts"
]
}

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014 Blake Embrey (hello@blakeembrey.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

@ -0,0 +1,43 @@
# Array Flatten
[![NPM version][npm-image]][npm-url]
[![NPM downloads][downloads-image]][downloads-url]
[![Build status][travis-image]][travis-url]
[![Test coverage][coveralls-image]][coveralls-url]
> Flatten an array of nested arrays into a single flat array. Accepts an optional depth.
## Installation
```
npm install array-flatten --save
```
## Usage
```javascript
var flatten = require('array-flatten')
flatten([1, [2, [3, [4, [5], 6], 7], 8], 9])
//=> [1, 2, 3, 4, 5, 6, 7, 8, 9]
flatten([1, [2, [3, [4, [5], 6], 7], 8], 9], 2)
//=> [1, 2, 3, [4, [5], 6], 7, 8, 9]
(function () {
flatten(arguments) //=> [1, 2, 3]
})(1, [2, 3])
```
## License
MIT
[npm-image]: https://img.shields.io/npm/v/array-flatten.svg?style=flat
[npm-url]: https://npmjs.org/package/array-flatten
[downloads-image]: https://img.shields.io/npm/dm/array-flatten.svg?style=flat
[downloads-url]: https://npmjs.org/package/array-flatten
[travis-image]: https://img.shields.io/travis/blakeembrey/array-flatten.svg?style=flat
[travis-url]: https://travis-ci.org/blakeembrey/array-flatten
[coveralls-image]: https://img.shields.io/coveralls/blakeembrey/array-flatten.svg?style=flat
[coveralls-url]: https://coveralls.io/r/blakeembrey/array-flatten?branch=master

@ -0,0 +1,64 @@
'use strict'
/**
* Expose `arrayFlatten`.
*/
module.exports = arrayFlatten
/**
* Recursive flatten function with depth.
*
* @param {Array} array
* @param {Array} result
* @param {Number} depth
* @return {Array}
*/
function flattenWithDepth (array, result, depth) {
for (var i = 0; i < array.length; i++) {
var value = array[i]
if (depth > 0 && Array.isArray(value)) {
flattenWithDepth(value, result, depth - 1)
} else {
result.push(value)
}
}
return result
}
/**
* Recursive flatten function. Omitting depth is slightly faster.
*
* @param {Array} array
* @param {Array} result
* @return {Array}
*/
function flattenForever (array, result) {
for (var i = 0; i < array.length; i++) {
var value = array[i]
if (Array.isArray(value)) {
flattenForever(value, result)
} else {
result.push(value)
}
}
return result
}
/**
* Flatten an array, with the ability to define a depth.
*
* @param {Array} array
* @param {Number} depth
* @return {Array}
*/
function arrayFlatten (array, depth) {
if (depth == null) {
return flattenForever(array, [])
}
return flattenWithDepth(array, [], depth)
}

@ -0,0 +1,39 @@
{
"name": "array-flatten",
"version": "1.1.1",
"description": "Flatten an array of nested arrays into a single flat array",
"main": "array-flatten.js",
"files": [
"array-flatten.js",
"LICENSE"
],
"scripts": {
"test": "istanbul cover _mocha -- -R spec"
},
"repository": {
"type": "git",
"url": "git://github.com/blakeembrey/array-flatten.git"
},
"keywords": [
"array",
"flatten",
"arguments",
"depth"
],
"author": {
"name": "Blake Embrey",
"email": "hello@blakeembrey.com",
"url": "http://blakeembrey.me"
},
"license": "MIT",
"bugs": {
"url": "https://github.com/blakeembrey/array-flatten/issues"
},
"homepage": "https://github.com/blakeembrey/array-flatten",
"devDependencies": {
"istanbul": "^0.3.13",
"mocha": "^2.2.4",
"pre-commit": "^1.0.7",
"standard": "^3.7.3"
}
}

@ -0,0 +1,672 @@
1.20.3 / 2024-09-10
===================
* deps: qs@6.13.0
* add `depth` option to customize the depth level in the parser
* IMPORTANT: The default `depth` level for parsing URL-encoded data is now `32` (previously was `Infinity`)
1.20.2 / 2023-02-21
===================
* Fix strict json error message on Node.js 19+
* deps: content-type@~1.0.5
- perf: skip value escaping when unnecessary
* deps: raw-body@2.5.2
1.20.1 / 2022-10-06
===================
* deps: qs@6.11.0
* perf: remove unnecessary object clone
1.20.0 / 2022-04-02
===================
* Fix error message for json parse whitespace in `strict`
* Fix internal error when inflated body exceeds limit
* Prevent loss of async hooks context
* Prevent hanging when request already read
* deps: depd@2.0.0
- Replace internal `eval` usage with `Function` constructor
- Use instance methods on `process` to check for listeners
* deps: http-errors@2.0.0
- deps: depd@2.0.0
- deps: statuses@2.0.1
* deps: on-finished@2.4.1
* deps: qs@6.10.3
* deps: raw-body@2.5.1
- deps: http-errors@2.0.0
1.19.2 / 2022-02-15
===================
* deps: bytes@3.1.2
* deps: qs@6.9.7
* Fix handling of `__proto__` keys
* deps: raw-body@2.4.3
- deps: bytes@3.1.2
1.19.1 / 2021-12-10
===================
* deps: bytes@3.1.1
* deps: http-errors@1.8.1
- deps: inherits@2.0.4
- deps: toidentifier@1.0.1
- deps: setprototypeof@1.2.0
* deps: qs@6.9.6
* deps: raw-body@2.4.2
- deps: bytes@3.1.1
- deps: http-errors@1.8.1
* deps: safe-buffer@5.2.1
* deps: type-is@~1.6.18
1.19.0 / 2019-04-25
===================
* deps: bytes@3.1.0
- Add petabyte (`pb`) support
* deps: http-errors@1.7.2
- Set constructor name when possible
- deps: setprototypeof@1.1.1
- deps: statuses@'>= 1.5.0 < 2'
* deps: iconv-lite@0.4.24
- Added encoding MIK
* deps: qs@6.7.0
- Fix parsing array brackets after index
* deps: raw-body@2.4.0
- deps: bytes@3.1.0
- deps: http-errors@1.7.2
- deps: iconv-lite@0.4.24
* deps: type-is@~1.6.17
- deps: mime-types@~2.1.24
- perf: prevent internal `throw` on invalid type
1.18.3 / 2018-05-14
===================
* Fix stack trace for strict json parse error
* deps: depd@~1.1.2
- perf: remove argument reassignment
* deps: http-errors@~1.6.3
- deps: depd@~1.1.2
- deps: setprototypeof@1.1.0
- deps: statuses@'>= 1.3.1 < 2'
* deps: iconv-lite@0.4.23
- Fix loading encoding with year appended
- Fix deprecation warnings on Node.js 10+
* deps: qs@6.5.2
* deps: raw-body@2.3.3
- deps: http-errors@1.6.3
- deps: iconv-lite@0.4.23
* deps: type-is@~1.6.16
- deps: mime-types@~2.1.18
1.18.2 / 2017-09-22
===================
* deps: debug@2.6.9
* perf: remove argument reassignment
1.18.1 / 2017-09-12
===================
* deps: content-type@~1.0.4
- perf: remove argument reassignment
- perf: skip parameter parsing when no parameters
* deps: iconv-lite@0.4.19
- Fix ISO-8859-1 regression
- Update Windows-1255
* deps: qs@6.5.1
- Fix parsing & compacting very deep objects
* deps: raw-body@2.3.2
- deps: iconv-lite@0.4.19
1.18.0 / 2017-09-08
===================
* Fix JSON strict violation error to match native parse error
* Include the `body` property on verify errors
* Include the `type` property on all generated errors
* Use `http-errors` to set status code on errors
* deps: bytes@3.0.0
* deps: debug@2.6.8
* deps: depd@~1.1.1
- Remove unnecessary `Buffer` loading
* deps: http-errors@~1.6.2
- deps: depd@1.1.1
* deps: iconv-lite@0.4.18
- Add support for React Native
- Add a warning if not loaded as utf-8
- Fix CESU-8 decoding in Node.js 8
- Improve speed of ISO-8859-1 encoding
* deps: qs@6.5.0
* deps: raw-body@2.3.1
- Use `http-errors` for standard emitted errors
- deps: bytes@3.0.0
- deps: iconv-lite@0.4.18
- perf: skip buffer decoding on overage chunk
* perf: prevent internal `throw` when missing charset
1.17.2 / 2017-05-17
===================
* deps: debug@2.6.7
- Fix `DEBUG_MAX_ARRAY_LENGTH`
- deps: ms@2.0.0
* deps: type-is@~1.6.15
- deps: mime-types@~2.1.15
1.17.1 / 2017-03-06
===================
* deps: qs@6.4.0
- Fix regression parsing keys starting with `[`
1.17.0 / 2017-03-01
===================
* deps: http-errors@~1.6.1
- Make `message` property enumerable for `HttpError`s
- deps: setprototypeof@1.0.3
* deps: qs@6.3.1
- Fix compacting nested arrays
1.16.1 / 2017-02-10
===================
* deps: debug@2.6.1
- Fix deprecation messages in WebStorm and other editors
- Undeprecate `DEBUG_FD` set to `1` or `2`
1.16.0 / 2017-01-17
===================
* deps: debug@2.6.0
- Allow colors in workers
- Deprecated `DEBUG_FD` environment variable
- Fix error when running under React Native
- Use same color for same namespace
- deps: ms@0.7.2
* deps: http-errors@~1.5.1
- deps: inherits@2.0.3
- deps: setprototypeof@1.0.2
- deps: statuses@'>= 1.3.1 < 2'
* deps: iconv-lite@0.4.15
- Added encoding MS-31J
- Added encoding MS-932
- Added encoding MS-936
- Added encoding MS-949
- Added encoding MS-950
- Fix GBK/GB18030 handling of Euro character
* deps: qs@6.2.1
- Fix array parsing from skipping empty values
* deps: raw-body@~2.2.0
- deps: iconv-lite@0.4.15
* deps: type-is@~1.6.14
- deps: mime-types@~2.1.13
1.15.2 / 2016-06-19
===================
* deps: bytes@2.4.0
* deps: content-type@~1.0.2
- perf: enable strict mode
* deps: http-errors@~1.5.0
- Use `setprototypeof` module to replace `__proto__` setting
- deps: statuses@'>= 1.3.0 < 2'
- perf: enable strict mode
* deps: qs@6.2.0
* deps: raw-body@~2.1.7
- deps: bytes@2.4.0
- perf: remove double-cleanup on happy path
* deps: type-is@~1.6.13
- deps: mime-types@~2.1.11
1.15.1 / 2016-05-05
===================
* deps: bytes@2.3.0
- Drop partial bytes on all parsed units
- Fix parsing byte string that looks like hex
* deps: raw-body@~2.1.6
- deps: bytes@2.3.0
* deps: type-is@~1.6.12
- deps: mime-types@~2.1.10
1.15.0 / 2016-02-10
===================
* deps: http-errors@~1.4.0
- Add `HttpError` export, for `err instanceof createError.HttpError`
- deps: inherits@2.0.1
- deps: statuses@'>= 1.2.1 < 2'
* deps: qs@6.1.0
* deps: type-is@~1.6.11
- deps: mime-types@~2.1.9
1.14.2 / 2015-12-16
===================
* deps: bytes@2.2.0
* deps: iconv-lite@0.4.13
* deps: qs@5.2.0
* deps: raw-body@~2.1.5
- deps: bytes@2.2.0
- deps: iconv-lite@0.4.13
* deps: type-is@~1.6.10
- deps: mime-types@~2.1.8
1.14.1 / 2015-09-27
===================
* Fix issue where invalid charset results in 400 when `verify` used
* deps: iconv-lite@0.4.12
- Fix CESU-8 decoding in Node.js 4.x
* deps: raw-body@~2.1.4
- Fix masking critical errors from `iconv-lite`
- deps: iconv-lite@0.4.12
* deps: type-is@~1.6.9
- deps: mime-types@~2.1.7
1.14.0 / 2015-09-16
===================
* Fix JSON strict parse error to match syntax errors
* Provide static `require` analysis in `urlencoded` parser
* deps: depd@~1.1.0
- Support web browser loading
* deps: qs@5.1.0
* deps: raw-body@~2.1.3
- Fix sync callback when attaching data listener causes sync read
* deps: type-is@~1.6.8
- Fix type error when given invalid type to match against
- deps: mime-types@~2.1.6
1.13.3 / 2015-07-31
===================
* deps: type-is@~1.6.6
- deps: mime-types@~2.1.4
1.13.2 / 2015-07-05
===================
* deps: iconv-lite@0.4.11
* deps: qs@4.0.0
- Fix dropping parameters like `hasOwnProperty`
- Fix user-visible incompatibilities from 3.1.0
- Fix various parsing edge cases
* deps: raw-body@~2.1.2
- Fix error stack traces to skip `makeError`
- deps: iconv-lite@0.4.11
* deps: type-is@~1.6.4
- deps: mime-types@~2.1.2
- perf: enable strict mode
- perf: remove argument reassignment
1.13.1 / 2015-06-16
===================
* deps: qs@2.4.2
- Downgraded from 3.1.0 because of user-visible incompatibilities
1.13.0 / 2015-06-14
===================
* Add `statusCode` property on `Error`s, in addition to `status`
* Change `type` default to `application/json` for JSON parser
* Change `type` default to `application/x-www-form-urlencoded` for urlencoded parser
* Provide static `require` analysis
* Use the `http-errors` module to generate errors
* deps: bytes@2.1.0
- Slight optimizations
* deps: iconv-lite@0.4.10
- The encoding UTF-16 without BOM now defaults to UTF-16LE when detection fails
- Leading BOM is now removed when decoding
* deps: on-finished@~2.3.0
- Add defined behavior for HTTP `CONNECT` requests
- Add defined behavior for HTTP `Upgrade` requests
- deps: ee-first@1.1.1
* deps: qs@3.1.0
- Fix dropping parameters like `hasOwnProperty`
- Fix various parsing edge cases
- Parsed object now has `null` prototype
* deps: raw-body@~2.1.1
- Use `unpipe` module for unpiping requests
- deps: iconv-lite@0.4.10
* deps: type-is@~1.6.3
- deps: mime-types@~2.1.1
- perf: reduce try block size
- perf: remove bitwise operations
* perf: enable strict mode
* perf: remove argument reassignment
* perf: remove delete call
1.12.4 / 2015-05-10
===================
* deps: debug@~2.2.0
* deps: qs@2.4.2
- Fix allowing parameters like `constructor`
* deps: on-finished@~2.2.1
* deps: raw-body@~2.0.1
- Fix a false-positive when unpiping in Node.js 0.8
- deps: bytes@2.0.1
* deps: type-is@~1.6.2
- deps: mime-types@~2.0.11
1.12.3 / 2015-04-15
===================
* Slight efficiency improvement when not debugging
* deps: depd@~1.0.1
* deps: iconv-lite@0.4.8
- Add encoding alias UNICODE-1-1-UTF-7
* deps: raw-body@1.3.4
- Fix hanging callback if request aborts during read
- deps: iconv-lite@0.4.8
1.12.2 / 2015-03-16
===================
* deps: qs@2.4.1
- Fix error when parameter `hasOwnProperty` is present
1.12.1 / 2015-03-15
===================
* deps: debug@~2.1.3
- Fix high intensity foreground color for bold
- deps: ms@0.7.0
* deps: type-is@~1.6.1
- deps: mime-types@~2.0.10
1.12.0 / 2015-02-13
===================
* add `debug` messages
* accept a function for the `type` option
* use `content-type` to parse `Content-Type` headers
* deps: iconv-lite@0.4.7
- Gracefully support enumerables on `Object.prototype`
* deps: raw-body@1.3.3
- deps: iconv-lite@0.4.7
* deps: type-is@~1.6.0
- fix argument reassignment
- fix false-positives in `hasBody` `Transfer-Encoding` check
- support wildcard for both type and subtype (`*/*`)
- deps: mime-types@~2.0.9
1.11.0 / 2015-01-30
===================
* make internal `extended: true` depth limit infinity
* deps: type-is@~1.5.6
- deps: mime-types@~2.0.8
1.10.2 / 2015-01-20
===================
* deps: iconv-lite@0.4.6
- Fix rare aliases of single-byte encodings
* deps: raw-body@1.3.2
- deps: iconv-lite@0.4.6
1.10.1 / 2015-01-01
===================
* deps: on-finished@~2.2.0
* deps: type-is@~1.5.5
- deps: mime-types@~2.0.7
1.10.0 / 2014-12-02
===================
* make internal `extended: true` array limit dynamic
1.9.3 / 2014-11-21
==================
* deps: iconv-lite@0.4.5
- Fix Windows-31J and X-SJIS encoding support
* deps: qs@2.3.3
- Fix `arrayLimit` behavior
* deps: raw-body@1.3.1
- deps: iconv-lite@0.4.5
* deps: type-is@~1.5.3
- deps: mime-types@~2.0.3
1.9.2 / 2014-10-27
==================
* deps: qs@2.3.2
- Fix parsing of mixed objects and values
1.9.1 / 2014-10-22
==================
* deps: on-finished@~2.1.1
- Fix handling of pipelined requests
* deps: qs@2.3.0
- Fix parsing of mixed implicit and explicit arrays
* deps: type-is@~1.5.2
- deps: mime-types@~2.0.2
1.9.0 / 2014-09-24
==================
* include the charset in "unsupported charset" error message
* include the encoding in "unsupported content encoding" error message
* deps: depd@~1.0.0
1.8.4 / 2014-09-23
==================
* fix content encoding to be case-insensitive
1.8.3 / 2014-09-19
==================
* deps: qs@2.2.4
- Fix issue with object keys starting with numbers truncated
1.8.2 / 2014-09-15
==================
* deps: depd@0.4.5
1.8.1 / 2014-09-07
==================
* deps: media-typer@0.3.0
* deps: type-is@~1.5.1
1.8.0 / 2014-09-05
==================
* make empty-body-handling consistent between chunked requests
- empty `json` produces `{}`
- empty `raw` produces `new Buffer(0)`
- empty `text` produces `''`
- empty `urlencoded` produces `{}`
* deps: qs@2.2.3
- Fix issue where first empty value in array is discarded
* deps: type-is@~1.5.0
- fix `hasbody` to be true for `content-length: 0`
1.7.0 / 2014-09-01
==================
* add `parameterLimit` option to `urlencoded` parser
* change `urlencoded` extended array limit to 100
* respond with 413 when over `parameterLimit` in `urlencoded`
1.6.7 / 2014-08-29
==================
* deps: qs@2.2.2
- Remove unnecessary cloning
1.6.6 / 2014-08-27
==================
* deps: qs@2.2.0
- Array parsing fix
- Performance improvements
1.6.5 / 2014-08-16
==================
* deps: on-finished@2.1.0
1.6.4 / 2014-08-14
==================
* deps: qs@1.2.2
1.6.3 / 2014-08-10
==================
* deps: qs@1.2.1
1.6.2 / 2014-08-07
==================
* deps: qs@1.2.0
- Fix parsing array of objects
1.6.1 / 2014-08-06
==================
* deps: qs@1.1.0
- Accept urlencoded square brackets
- Accept empty values in implicit array notation
1.6.0 / 2014-08-05
==================
* deps: qs@1.0.2
- Complete rewrite
- Limits array length to 20
- Limits object depth to 5
- Limits parameters to 1,000
1.5.2 / 2014-07-27
==================
* deps: depd@0.4.4
- Work-around v8 generating empty stack traces
1.5.1 / 2014-07-26
==================
* deps: depd@0.4.3
- Fix exception when global `Error.stackTraceLimit` is too low
1.5.0 / 2014-07-20
==================
* deps: depd@0.4.2
- Add `TRACE_DEPRECATION` environment variable
- Remove non-standard grey color from color output
- Support `--no-deprecation` argument
- Support `--trace-deprecation` argument
* deps: iconv-lite@0.4.4
- Added encoding UTF-7
* deps: raw-body@1.3.0
- deps: iconv-lite@0.4.4
- Added encoding UTF-7
- Fix `Cannot switch to old mode now` error on Node.js 0.10+
* deps: type-is@~1.3.2
1.4.3 / 2014-06-19
==================
* deps: type-is@1.3.1
- fix global variable leak
1.4.2 / 2014-06-19
==================
* deps: type-is@1.3.0
- improve type parsing
1.4.1 / 2014-06-19
==================
* fix urlencoded extended deprecation message
1.4.0 / 2014-06-19
==================
* add `text` parser
* add `raw` parser
* check accepted charset in content-type (accepts utf-8)
* check accepted encoding in content-encoding (accepts identity)
* deprecate `bodyParser()` middleware; use `.json()` and `.urlencoded()` as needed
* deprecate `urlencoded()` without provided `extended` option
* lazy-load urlencoded parsers
* parsers split into files for reduced mem usage
* support gzip and deflate bodies
- set `inflate: false` to turn off
* deps: raw-body@1.2.2
- Support all encodings from `iconv-lite`
1.3.1 / 2014-06-11
==================
* deps: type-is@1.2.1
- Switch dependency from mime to mime-types@1.0.0
1.3.0 / 2014-05-31
==================
* add `extended` option to urlencoded parser
1.2.2 / 2014-05-27
==================
* deps: raw-body@1.1.6
- assert stream encoding on node.js 0.8
- assert stream encoding on node.js < 0.10.6
- deps: bytes@1
1.2.1 / 2014-05-26
==================
* invoke `next(err)` after request fully read
- prevents hung responses and socket hang ups
1.2.0 / 2014-05-11
==================
* add `verify` option
* deps: type-is@1.2.0
- support suffix matching
1.1.2 / 2014-05-11
==================
* improve json parser speed
1.1.1 / 2014-05-11
==================
* fix repeated limit parsing with every request
1.1.0 / 2014-05-10
==================
* add `type` option
* deps: pin for safety and consistency
1.0.2 / 2014-04-14
==================
* use `type-is` module
1.0.1 / 2014-03-20
==================
* lower default limits to 100kb

@ -0,0 +1,23 @@
(The MIT License)
Copyright (c) 2014 Jonathan Ong <me@jongleberry.com>
Copyright (c) 2014-2015 Douglas Christopher Wilson <doug@somethingdoug.com>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

@ -0,0 +1,476 @@
# body-parser
[![NPM Version][npm-version-image]][npm-url]
[![NPM Downloads][npm-downloads-image]][npm-url]
[![Build Status][ci-image]][ci-url]
[![Test Coverage][coveralls-image]][coveralls-url]
[![OpenSSF Scorecard Badge][ossf-scorecard-badge]][ossf-scorecard-visualizer]
Node.js body parsing middleware.
Parse incoming request bodies in a middleware before your handlers, available
under the `req.body` property.
**Note** As `req.body`'s shape is based on user-controlled input, all
properties and values in this object are untrusted and should be validated
before trusting. For example, `req.body.foo.toString()` may fail in multiple
ways, for example the `foo` property may not be there or may not be a string,
and `toString` may not be a function and instead a string or other user input.
[Learn about the anatomy of an HTTP transaction in Node.js](https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/).
_This does not handle multipart bodies_, due to their complex and typically
large nature. For multipart bodies, you may be interested in the following
modules:
* [busboy](https://www.npmjs.org/package/busboy#readme) and
[connect-busboy](https://www.npmjs.org/package/connect-busboy#readme)
* [multiparty](https://www.npmjs.org/package/multiparty#readme) and
[connect-multiparty](https://www.npmjs.org/package/connect-multiparty#readme)
* [formidable](https://www.npmjs.org/package/formidable#readme)
* [multer](https://www.npmjs.org/package/multer#readme)
This module provides the following parsers:
* [JSON body parser](#bodyparserjsonoptions)
* [Raw body parser](#bodyparserrawoptions)
* [Text body parser](#bodyparsertextoptions)
* [URL-encoded form body parser](#bodyparserurlencodedoptions)
Other body parsers you might be interested in:
- [body](https://www.npmjs.org/package/body#readme)
- [co-body](https://www.npmjs.org/package/co-body#readme)
## Installation
```sh
$ npm install body-parser
```
## API
```js
var bodyParser = require('body-parser')
```
The `bodyParser` object exposes various factories to create middlewares. All
middlewares will populate the `req.body` property with the parsed body when
the `Content-Type` request header matches the `type` option, or an empty
object (`{}`) if there was no body to parse, the `Content-Type` was not matched,
or an error occurred.
The various errors returned by this module are described in the
[errors section](#errors).
### bodyParser.json([options])
Returns middleware that only parses `json` and only looks at requests where
the `Content-Type` header matches the `type` option. This parser accepts any
Unicode encoding of the body and supports automatic inflation of `gzip` and
`deflate` encodings.
A new `body` object containing the parsed data is populated on the `request`
object after the middleware (i.e. `req.body`).
#### Options
The `json` function takes an optional `options` object that may contain any of
the following keys:
##### inflate
When set to `true`, then deflated (compressed) bodies will be inflated; when
`false`, deflated bodies are rejected. Defaults to `true`.
##### limit
Controls the maximum request body size. If this is a number, then the value
specifies the number of bytes; if it is a string, the value is passed to the
[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults
to `'100kb'`.
##### reviver
The `reviver` option is passed directly to `JSON.parse` as the second
argument. You can find more information on this argument
[in the MDN documentation about JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Example.3A_Using_the_reviver_parameter).
##### strict
When set to `true`, will only accept arrays and objects; when `false` will
accept anything `JSON.parse` accepts. Defaults to `true`.
##### type
The `type` option is used to determine what media type the middleware will
parse. This option can be a string, array of strings, or a function. If not a
function, `type` option is passed directly to the
[type-is](https://www.npmjs.org/package/type-is#readme) library and this can
be an extension name (like `json`), a mime type (like `application/json`), or
a mime type with a wildcard (like `*/*` or `*/json`). If a function, the `type`
option is called as `fn(req)` and the request is parsed if it returns a truthy
value. Defaults to `application/json`.
##### verify
The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`,
where `buf` is a `Buffer` of the raw request body and `encoding` is the
encoding of the request. The parsing can be aborted by throwing an error.
### bodyParser.raw([options])
Returns middleware that parses all bodies as a `Buffer` and only looks at
requests where the `Content-Type` header matches the `type` option. This
parser supports automatic inflation of `gzip` and `deflate` encodings.
A new `body` object containing the parsed data is populated on the `request`
object after the middleware (i.e. `req.body`). This will be a `Buffer` object
of the body.
#### Options
The `raw` function takes an optional `options` object that may contain any of
the following keys:
##### inflate
When set to `true`, then deflated (compressed) bodies will be inflated; when
`false`, deflated bodies are rejected. Defaults to `true`.
##### limit
Controls the maximum request body size. If this is a number, then the value
specifies the number of bytes; if it is a string, the value is passed to the
[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults
to `'100kb'`.
##### type
The `type` option is used to determine what media type the middleware will
parse. This option can be a string, array of strings, or a function.
If not a function, `type` option is passed directly to the
[type-is](https://www.npmjs.org/package/type-is#readme) library and this
can be an extension name (like `bin`), a mime type (like
`application/octet-stream`), or a mime type with a wildcard (like `*/*` or
`application/*`). If a function, the `type` option is called as `fn(req)`
and the request is parsed if it returns a truthy value. Defaults to
`application/octet-stream`.
##### verify
The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`,
where `buf` is a `Buffer` of the raw request body and `encoding` is the
encoding of the request. The parsing can be aborted by throwing an error.
### bodyParser.text([options])
Returns middleware that parses all bodies as a string and only looks at
requests where the `Content-Type` header matches the `type` option. This
parser supports automatic inflation of `gzip` and `deflate` encodings.
A new `body` string containing the parsed data is populated on the `request`
object after the middleware (i.e. `req.body`). This will be a string of the
body.
#### Options
The `text` function takes an optional `options` object that may contain any of
the following keys:
##### defaultCharset
Specify the default character set for the text content if the charset is not
specified in the `Content-Type` header of the request. Defaults to `utf-8`.
##### inflate
When set to `true`, then deflated (compressed) bodies will be inflated; when
`false`, deflated bodies are rejected. Defaults to `true`.
##### limit
Controls the maximum request body size. If this is a number, then the value
specifies the number of bytes; if it is a string, the value is passed to the
[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults
to `'100kb'`.
##### type
The `type` option is used to determine what media type the middleware will
parse. This option can be a string, array of strings, or a function. If not
a function, `type` option is passed directly to the
[type-is](https://www.npmjs.org/package/type-is#readme) library and this can
be an extension name (like `txt`), a mime type (like `text/plain`), or a mime
type with a wildcard (like `*/*` or `text/*`). If a function, the `type`
option is called as `fn(req)` and the request is parsed if it returns a
truthy value. Defaults to `text/plain`.
##### verify
The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`,
where `buf` is a `Buffer` of the raw request body and `encoding` is the
encoding of the request. The parsing can be aborted by throwing an error.
### bodyParser.urlencoded([options])
Returns middleware that only parses `urlencoded` bodies and only looks at
requests where the `Content-Type` header matches the `type` option. This
parser accepts only UTF-8 encoding of the body and supports automatic
inflation of `gzip` and `deflate` encodings.
A new `body` object containing the parsed data is populated on the `request`
object after the middleware (i.e. `req.body`). This object will contain
key-value pairs, where the value can be a string or array (when `extended` is
`false`), or any type (when `extended` is `true`).
#### Options
The `urlencoded` function takes an optional `options` object that may contain
any of the following keys:
##### extended
The `extended` option allows to choose between parsing the URL-encoded data
with the `querystring` library (when `false`) or the `qs` library (when
`true`). The "extended" syntax allows for rich objects and arrays to be
encoded into the URL-encoded format, allowing for a JSON-like experience
with URL-encoded. For more information, please
[see the qs library](https://www.npmjs.org/package/qs#readme).
Defaults to `true`, but using the default has been deprecated. Please
research into the difference between `qs` and `querystring` and choose the
appropriate setting.
##### inflate
When set to `true`, then deflated (compressed) bodies will be inflated; when
`false`, deflated bodies are rejected. Defaults to `true`.
##### limit
Controls the maximum request body size. If this is a number, then the value
specifies the number of bytes; if it is a string, the value is passed to the
[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults
to `'100kb'`.
##### parameterLimit
The `parameterLimit` option controls the maximum number of parameters that
are allowed in the URL-encoded data. If a request contains more parameters
than this value, a 413 will be returned to the client. Defaults to `1000`.
##### type
The `type` option is used to determine what media type the middleware will
parse. This option can be a string, array of strings, or a function. If not
a function, `type` option is passed directly to the
[type-is](https://www.npmjs.org/package/type-is#readme) library and this can
be an extension name (like `urlencoded`), a mime type (like
`application/x-www-form-urlencoded`), or a mime type with a wildcard (like
`*/x-www-form-urlencoded`). If a function, the `type` option is called as
`fn(req)` and the request is parsed if it returns a truthy value. Defaults
to `application/x-www-form-urlencoded`.
##### verify
The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`,
where `buf` is a `Buffer` of the raw request body and `encoding` is the
encoding of the request. The parsing can be aborted by throwing an error.
#### depth
The `depth` option is used to configure the maximum depth of the `qs` library when `extended` is `true`. This allows you to limit the amount of keys that are parsed and can be useful to prevent certain types of abuse. Defaults to `32`. It is recommended to keep this value as low as possible.
## Errors
The middlewares provided by this module create errors using the
[`http-errors` module](https://www.npmjs.com/package/http-errors). The errors
will typically have a `status`/`statusCode` property that contains the suggested
HTTP response code, an `expose` property to determine if the `message` property
should be displayed to the client, a `type` property to determine the type of
error without matching against the `message`, and a `body` property containing
the read body, if available.
The following are the common errors created, though any error can come through
for various reasons.
### content encoding unsupported
This error will occur when the request had a `Content-Encoding` header that
contained an encoding but the "inflation" option was set to `false`. The
`status` property is set to `415`, the `type` property is set to
`'encoding.unsupported'`, and the `charset` property will be set to the
encoding that is unsupported.
### entity parse failed
This error will occur when the request contained an entity that could not be
parsed by the middleware. The `status` property is set to `400`, the `type`
property is set to `'entity.parse.failed'`, and the `body` property is set to
the entity value that failed parsing.
### entity verify failed
This error will occur when the request contained an entity that could not be
failed verification by the defined `verify` option. The `status` property is
set to `403`, the `type` property is set to `'entity.verify.failed'`, and the
`body` property is set to the entity value that failed verification.
### request aborted
This error will occur when the request is aborted by the client before reading
the body has finished. The `received` property will be set to the number of
bytes received before the request was aborted and the `expected` property is
set to the number of expected bytes. The `status` property is set to `400`
and `type` property is set to `'request.aborted'`.
### request entity too large
This error will occur when the request body's size is larger than the "limit"
option. The `limit` property will be set to the byte limit and the `length`
property will be set to the request body's length. The `status` property is
set to `413` and the `type` property is set to `'entity.too.large'`.
### request size did not match content length
This error will occur when the request's length did not match the length from
the `Content-Length` header. This typically occurs when the request is malformed,
typically when the `Content-Length` header was calculated based on characters
instead of bytes. The `status` property is set to `400` and the `type` property
is set to `'request.size.invalid'`.
### stream encoding should not be set
This error will occur when something called the `req.setEncoding` method prior
to this middleware. This module operates directly on bytes only and you cannot
call `req.setEncoding` when using this module. The `status` property is set to
`500` and the `type` property is set to `'stream.encoding.set'`.
### stream is not readable
This error will occur when the request is no longer readable when this middleware
attempts to read it. This typically means something other than a middleware from
this module read the request body already and the middleware was also configured to
read the same request. The `status` property is set to `500` and the `type`
property is set to `'stream.not.readable'`.
### too many parameters
This error will occur when the content of the request exceeds the configured
`parameterLimit` for the `urlencoded` parser. The `status` property is set to
`413` and the `type` property is set to `'parameters.too.many'`.
### unsupported charset "BOGUS"
This error will occur when the request had a charset parameter in the
`Content-Type` header, but the `iconv-lite` module does not support it OR the
parser does not support it. The charset is contained in the message as well
as in the `charset` property. The `status` property is set to `415`, the
`type` property is set to `'charset.unsupported'`, and the `charset` property
is set to the charset that is unsupported.
### unsupported content encoding "bogus"
This error will occur when the request had a `Content-Encoding` header that
contained an unsupported encoding. The encoding is contained in the message
as well as in the `encoding` property. The `status` property is set to `415`,
the `type` property is set to `'encoding.unsupported'`, and the `encoding`
property is set to the encoding that is unsupported.
### The input exceeded the depth
This error occurs when using `bodyParser.urlencoded` with the `extended` property set to `true` and the input exceeds the configured `depth` option. The `status` property is set to `400`. It is recommended to review the `depth` option and evaluate if it requires a higher value. When the `depth` option is set to `32` (default value), the error will not be thrown.
## Examples
### Express/Connect top-level generic
This example demonstrates adding a generic JSON and URL-encoded parser as a
top-level middleware, which will parse the bodies of all incoming requests.
This is the simplest setup.
```js
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.use(function (req, res) {
res.setHeader('Content-Type', 'text/plain')
res.write('you posted:\n')
res.end(JSON.stringify(req.body, null, 2))
})
```
### Express route-specific
This example demonstrates adding body parsers specifically to the routes that
need them. In general, this is the most recommended way to use body-parser with
Express.
```js
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// create application/json parser
var jsonParser = bodyParser.json()
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
// POST /login gets urlencoded bodies
app.post('/login', urlencodedParser, function (req, res) {
res.send('welcome, ' + req.body.username)
})
// POST /api/users gets JSON bodies
app.post('/api/users', jsonParser, function (req, res) {
// create user in req.body
})
```
### Change accepted type for parsers
All the parsers accept a `type` option which allows you to change the
`Content-Type` that the middleware will parse.
```js
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse various different custom JSON types as JSON
app.use(bodyParser.json({ type: 'application/*+json' }))
// parse some custom thing into a Buffer
app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }))
// parse an HTML body into a string
app.use(bodyParser.text({ type: 'text/html' }))
```
## License
[MIT](LICENSE)
[ci-image]: https://badgen.net/github/checks/expressjs/body-parser/master?label=ci
[ci-url]: https://github.com/expressjs/body-parser/actions/workflows/ci.yml
[coveralls-image]: https://badgen.net/coveralls/c/github/expressjs/body-parser/master
[coveralls-url]: https://coveralls.io/r/expressjs/body-parser?branch=master
[node-version-image]: https://badgen.net/npm/node/body-parser
[node-version-url]: https://nodejs.org/en/download
[npm-downloads-image]: https://badgen.net/npm/dm/body-parser
[npm-url]: https://npmjs.org/package/body-parser
[npm-version-image]: https://badgen.net/npm/v/body-parser
[ossf-scorecard-badge]: https://api.scorecard.dev/projects/github.com/expressjs/body-parser/badge
[ossf-scorecard-visualizer]: https://ossf.github.io/scorecard-visualizer/#/projects/github.com/expressjs/body-parser

@ -0,0 +1,25 @@
# Security Policies and Procedures
## Reporting a Bug
The Express team and community take all security bugs seriously. Thank you
for improving the security of Express. We appreciate your efforts and
responsible disclosure and will make every effort to acknowledge your
contributions.
Report security bugs by emailing the current owner(s) of `body-parser`. This
information can be found in the npm registry using the command
`npm owner ls body-parser`.
If unsure or unable to get the information from the above, open an issue
in the [project issue tracker](https://github.com/expressjs/body-parser/issues)
asking for the current contact information.
To ensure the timely response to your report, please ensure that the entirety
of the report is contained within the email body and not solely behind a web
link or an attachment.
At least one owner will acknowledge your email within 48 hours, and will send a
more detailed response within 48 hours indicating the next steps in handling
your report. After the initial reply to your report, the owners will
endeavor to keep you informed of the progress towards a fix and full
announcement, and may ask for additional information or guidance.

@ -0,0 +1,156 @@
/*!
* body-parser
* Copyright(c) 2014-2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Module dependencies.
* @private
*/
var deprecate = require('depd')('body-parser')
/**
* Cache of loaded parsers.
* @private
*/
var parsers = Object.create(null)
/**
* @typedef Parsers
* @type {function}
* @property {function} json
* @property {function} raw
* @property {function} text
* @property {function} urlencoded
*/
/**
* Module exports.
* @type {Parsers}
*/
exports = module.exports = deprecate.function(bodyParser,
'bodyParser: use individual json/urlencoded middlewares')
/**
* JSON parser.
* @public
*/
Object.defineProperty(exports, 'json', {
configurable: true,
enumerable: true,
get: createParserGetter('json')
})
/**
* Raw parser.
* @public
*/
Object.defineProperty(exports, 'raw', {
configurable: true,
enumerable: true,
get: createParserGetter('raw')
})
/**
* Text parser.
* @public
*/
Object.defineProperty(exports, 'text', {
configurable: true,
enumerable: true,
get: createParserGetter('text')
})
/**
* URL-encoded parser.
* @public
*/
Object.defineProperty(exports, 'urlencoded', {
configurable: true,
enumerable: true,
get: createParserGetter('urlencoded')
})
/**
* Create a middleware to parse json and urlencoded bodies.
*
* @param {object} [options]
* @return {function}
* @deprecated
* @public
*/
function bodyParser (options) {
// use default type for parsers
var opts = Object.create(options || null, {
type: {
configurable: true,
enumerable: true,
value: undefined,
writable: true
}
})
var _urlencoded = exports.urlencoded(opts)
var _json = exports.json(opts)
return function bodyParser (req, res, next) {
_json(req, res, function (err) {
if (err) return next(err)
_urlencoded(req, res, next)
})
}
}
/**
* Create a getter for loading a parser.
* @private
*/
function createParserGetter (name) {
return function get () {
return loadParser(name)
}
}
/**
* Load a parser module.
* @private
*/
function loadParser (parserName) {
var parser = parsers[parserName]
if (parser !== undefined) {
return parser
}
// this uses a switch for static require analysis
switch (parserName) {
case 'json':
parser = require('./lib/types/json')
break
case 'raw':
parser = require('./lib/types/raw')
break
case 'text':
parser = require('./lib/types/text')
break
case 'urlencoded':
parser = require('./lib/types/urlencoded')
break
}
// store to prevent invoking require()
return (parsers[parserName] = parser)
}

@ -0,0 +1,205 @@
/*!
* body-parser
* Copyright(c) 2014-2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Module dependencies.
* @private
*/
var createError = require('http-errors')
var destroy = require('destroy')
var getBody = require('raw-body')
var iconv = require('iconv-lite')
var onFinished = require('on-finished')
var unpipe = require('unpipe')
var zlib = require('zlib')
/**
* Module exports.
*/
module.exports = read
/**
* Read a request into a buffer and parse.
*
* @param {object} req
* @param {object} res
* @param {function} next
* @param {function} parse
* @param {function} debug
* @param {object} options
* @private
*/
function read (req, res, next, parse, debug, options) {
var length
var opts = options
var stream
// flag as parsed
req._body = true
// read options
var encoding = opts.encoding !== null
? opts.encoding
: null
var verify = opts.verify
try {
// get the content stream
stream = contentstream(req, debug, opts.inflate)
length = stream.length
stream.length = undefined
} catch (err) {
return next(err)
}
// set raw-body options
opts.length = length
opts.encoding = verify
? null
: encoding
// assert charset is supported
if (opts.encoding === null && encoding !== null && !iconv.encodingExists(encoding)) {
return next(createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', {
charset: encoding.toLowerCase(),
type: 'charset.unsupported'
}))
}
// read body
debug('read body')
getBody(stream, opts, function (error, body) {
if (error) {
var _error
if (error.type === 'encoding.unsupported') {
// echo back charset
_error = createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', {
charset: encoding.toLowerCase(),
type: 'charset.unsupported'
})
} else {
// set status code on error
_error = createError(400, error)
}
// unpipe from stream and destroy
if (stream !== req) {
unpipe(req)
destroy(stream, true)
}
// read off entire request
dump(req, function onfinished () {
next(createError(400, _error))
})
return
}
// verify
if (verify) {
try {
debug('verify body')
verify(req, res, body, encoding)
} catch (err) {
next(createError(403, err, {
body: body,
type: err.type || 'entity.verify.failed'
}))
return
}
}
// parse
var str = body
try {
debug('parse body')
str = typeof body !== 'string' && encoding !== null
? iconv.decode(body, encoding)
: body
req.body = parse(str)
} catch (err) {
next(createError(400, err, {
body: str,
type: err.type || 'entity.parse.failed'
}))
return
}
next()
})
}
/**
* Get the content stream of the request.
*
* @param {object} req
* @param {function} debug
* @param {boolean} [inflate=true]
* @return {object}
* @api private
*/
function contentstream (req, debug, inflate) {
var encoding = (req.headers['content-encoding'] || 'identity').toLowerCase()
var length = req.headers['content-length']
var stream
debug('content-encoding "%s"', encoding)
if (inflate === false && encoding !== 'identity') {
throw createError(415, 'content encoding unsupported', {
encoding: encoding,
type: 'encoding.unsupported'
})
}
switch (encoding) {
case 'deflate':
stream = zlib.createInflate()
debug('inflate body')
req.pipe(stream)
break
case 'gzip':
stream = zlib.createGunzip()
debug('gunzip body')
req.pipe(stream)
break
case 'identity':
stream = req
stream.length = length
break
default:
throw createError(415, 'unsupported content encoding "' + encoding + '"', {
encoding: encoding,
type: 'encoding.unsupported'
})
}
return stream
}
/**
* Dump the contents of a request.
*
* @param {object} req
* @param {function} callback
* @api private
*/
function dump (req, callback) {
if (onFinished.isFinished(req)) {
callback(null)
} else {
onFinished(req, callback)
req.resume()
}
}

@ -0,0 +1,247 @@
/*!
* body-parser
* Copyright(c) 2014 Jonathan Ong
* Copyright(c) 2014-2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Module dependencies.
* @private
*/
var bytes = require('bytes')
var contentType = require('content-type')
var createError = require('http-errors')
var debug = require('debug')('body-parser:json')
var read = require('../read')
var typeis = require('type-is')
/**
* Module exports.
*/
module.exports = json
/**
* RegExp to match the first non-space in a string.
*
* Allowed whitespace is defined in RFC 7159:
*
* ws = *(
* %x20 / ; Space
* %x09 / ; Horizontal tab
* %x0A / ; Line feed or New line
* %x0D ) ; Carriage return
*/
var FIRST_CHAR_REGEXP = /^[\x20\x09\x0a\x0d]*([^\x20\x09\x0a\x0d])/ // eslint-disable-line no-control-regex
var JSON_SYNTAX_CHAR = '#'
var JSON_SYNTAX_REGEXP = /#+/g
/**
* Create a middleware to parse JSON bodies.
*
* @param {object} [options]
* @return {function}
* @public
*/
function json (options) {
var opts = options || {}
var limit = typeof opts.limit !== 'number'
? bytes.parse(opts.limit || '100kb')
: opts.limit
var inflate = opts.inflate !== false
var reviver = opts.reviver
var strict = opts.strict !== false
var type = opts.type || 'application/json'
var verify = opts.verify || false
if (verify !== false && typeof verify !== 'function') {
throw new TypeError('option verify must be function')
}
// create the appropriate type checking function
var shouldParse = typeof type !== 'function'
? typeChecker(type)
: type
function parse (body) {
if (body.length === 0) {
// special-case empty json body, as it's a common client-side mistake
// TODO: maybe make this configurable or part of "strict" option
return {}
}
if (strict) {
var first = firstchar(body)
if (first !== '{' && first !== '[') {
debug('strict violation')
throw createStrictSyntaxError(body, first)
}
}
try {
debug('parse json')
return JSON.parse(body, reviver)
} catch (e) {
throw normalizeJsonSyntaxError(e, {
message: e.message,
stack: e.stack
})
}
}
return function jsonParser (req, res, next) {
if (req._body) {
debug('body already parsed')
next()
return
}
req.body = req.body || {}
// skip requests without bodies
if (!typeis.hasBody(req)) {
debug('skip empty body')
next()
return
}
debug('content-type %j', req.headers['content-type'])
// determine if request should be parsed
if (!shouldParse(req)) {
debug('skip parsing')
next()
return
}
// assert charset per RFC 7159 sec 8.1
var charset = getCharset(req) || 'utf-8'
if (charset.slice(0, 4) !== 'utf-') {
debug('invalid charset')
next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', {
charset: charset,
type: 'charset.unsupported'
}))
return
}
// read
read(req, res, next, parse, debug, {
encoding: charset,
inflate: inflate,
limit: limit,
verify: verify
})
}
}
/**
* Create strict violation syntax error matching native error.
*
* @param {string} str
* @param {string} char
* @return {Error}
* @private
*/
function createStrictSyntaxError (str, char) {
var index = str.indexOf(char)
var partial = ''
if (index !== -1) {
partial = str.substring(0, index) + JSON_SYNTAX_CHAR
for (var i = index + 1; i < str.length; i++) {
partial += JSON_SYNTAX_CHAR
}
}
try {
JSON.parse(partial); /* istanbul ignore next */ throw new SyntaxError('strict violation')
} catch (e) {
return normalizeJsonSyntaxError(e, {
message: e.message.replace(JSON_SYNTAX_REGEXP, function (placeholder) {
return str.substring(index, index + placeholder.length)
}),
stack: e.stack
})
}
}
/**
* Get the first non-whitespace character in a string.
*
* @param {string} str
* @return {function}
* @private
*/
function firstchar (str) {
var match = FIRST_CHAR_REGEXP.exec(str)
return match
? match[1]
: undefined
}
/**
* Get the charset of a request.
*
* @param {object} req
* @api private
*/
function getCharset (req) {
try {
return (contentType.parse(req).parameters.charset || '').toLowerCase()
} catch (e) {
return undefined
}
}
/**
* Normalize a SyntaxError for JSON.parse.
*
* @param {SyntaxError} error
* @param {object} obj
* @return {SyntaxError}
*/
function normalizeJsonSyntaxError (error, obj) {
var keys = Object.getOwnPropertyNames(error)
for (var i = 0; i < keys.length; i++) {
var key = keys[i]
if (key !== 'stack' && key !== 'message') {
delete error[key]
}
}
// replace stack before message for Node.js 0.10 and below
error.stack = obj.stack.replace(error.message, obj.message)
error.message = obj.message
return error
}
/**
* Get the simple type checker.
*
* @param {string} type
* @return {function}
*/
function typeChecker (type) {
return function checkType (req) {
return Boolean(typeis(req, type))
}
}

@ -0,0 +1,101 @@
/*!
* body-parser
* Copyright(c) 2014-2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Module dependencies.
*/
var bytes = require('bytes')
var debug = require('debug')('body-parser:raw')
var read = require('../read')
var typeis = require('type-is')
/**
* Module exports.
*/
module.exports = raw
/**
* Create a middleware to parse raw bodies.
*
* @param {object} [options]
* @return {function}
* @api public
*/
function raw (options) {
var opts = options || {}
var inflate = opts.inflate !== false
var limit = typeof opts.limit !== 'number'
? bytes.parse(opts.limit || '100kb')
: opts.limit
var type = opts.type || 'application/octet-stream'
var verify = opts.verify || false
if (verify !== false && typeof verify !== 'function') {
throw new TypeError('option verify must be function')
}
// create the appropriate type checking function
var shouldParse = typeof type !== 'function'
? typeChecker(type)
: type
function parse (buf) {
return buf
}
return function rawParser (req, res, next) {
if (req._body) {
debug('body already parsed')
next()
return
}
req.body = req.body || {}
// skip requests without bodies
if (!typeis.hasBody(req)) {
debug('skip empty body')
next()
return
}
debug('content-type %j', req.headers['content-type'])
// determine if request should be parsed
if (!shouldParse(req)) {
debug('skip parsing')
next()
return
}
// read
read(req, res, next, parse, debug, {
encoding: null,
inflate: inflate,
limit: limit,
verify: verify
})
}
}
/**
* Get the simple type checker.
*
* @param {string} type
* @return {function}
*/
function typeChecker (type) {
return function checkType (req) {
return Boolean(typeis(req, type))
}
}

@ -0,0 +1,121 @@
/*!
* body-parser
* Copyright(c) 2014-2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Module dependencies.
*/
var bytes = require('bytes')
var contentType = require('content-type')
var debug = require('debug')('body-parser:text')
var read = require('../read')
var typeis = require('type-is')
/**
* Module exports.
*/
module.exports = text
/**
* Create a middleware to parse text bodies.
*
* @param {object} [options]
* @return {function}
* @api public
*/
function text (options) {
var opts = options || {}
var defaultCharset = opts.defaultCharset || 'utf-8'
var inflate = opts.inflate !== false
var limit = typeof opts.limit !== 'number'
? bytes.parse(opts.limit || '100kb')
: opts.limit
var type = opts.type || 'text/plain'
var verify = opts.verify || false
if (verify !== false && typeof verify !== 'function') {
throw new TypeError('option verify must be function')
}
// create the appropriate type checking function
var shouldParse = typeof type !== 'function'
? typeChecker(type)
: type
function parse (buf) {
return buf
}
return function textParser (req, res, next) {
if (req._body) {
debug('body already parsed')
next()
return
}
req.body = req.body || {}
// skip requests without bodies
if (!typeis.hasBody(req)) {
debug('skip empty body')
next()
return
}
debug('content-type %j', req.headers['content-type'])
// determine if request should be parsed
if (!shouldParse(req)) {
debug('skip parsing')
next()
return
}
// get charset
var charset = getCharset(req) || defaultCharset
// read
read(req, res, next, parse, debug, {
encoding: charset,
inflate: inflate,
limit: limit,
verify: verify
})
}
}
/**
* Get the charset of a request.
*
* @param {object} req
* @api private
*/
function getCharset (req) {
try {
return (contentType.parse(req).parameters.charset || '').toLowerCase()
} catch (e) {
return undefined
}
}
/**
* Get the simple type checker.
*
* @param {string} type
* @return {function}
*/
function typeChecker (type) {
return function checkType (req) {
return Boolean(typeis(req, type))
}
}

@ -0,0 +1,307 @@
/*!
* body-parser
* Copyright(c) 2014 Jonathan Ong
* Copyright(c) 2014-2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Module dependencies.
* @private
*/
var bytes = require('bytes')
var contentType = require('content-type')
var createError = require('http-errors')
var debug = require('debug')('body-parser:urlencoded')
var deprecate = require('depd')('body-parser')
var read = require('../read')
var typeis = require('type-is')
/**
* Module exports.
*/
module.exports = urlencoded
/**
* Cache of parser modules.
*/
var parsers = Object.create(null)
/**
* Create a middleware to parse urlencoded bodies.
*
* @param {object} [options]
* @return {function}
* @public
*/
function urlencoded (options) {
var opts = options || {}
// notice because option default will flip in next major
if (opts.extended === undefined) {
deprecate('undefined extended: provide extended option')
}
var extended = opts.extended !== false
var inflate = opts.inflate !== false
var limit = typeof opts.limit !== 'number'
? bytes.parse(opts.limit || '100kb')
: opts.limit
var type = opts.type || 'application/x-www-form-urlencoded'
var verify = opts.verify || false
var depth = typeof opts.depth !== 'number'
? Number(opts.depth || 32)
: opts.depth
if (verify !== false && typeof verify !== 'function') {
throw new TypeError('option verify must be function')
}
// create the appropriate query parser
var queryparse = extended
? extendedparser(opts)
: simpleparser(opts)
// create the appropriate type checking function
var shouldParse = typeof type !== 'function'
? typeChecker(type)
: type
function parse (body) {
return body.length
? queryparse(body)
: {}
}
return function urlencodedParser (req, res, next) {
if (req._body) {
debug('body already parsed')
next()
return
}
req.body = req.body || {}
// skip requests without bodies
if (!typeis.hasBody(req)) {
debug('skip empty body')
next()
return
}
debug('content-type %j', req.headers['content-type'])
// determine if request should be parsed
if (!shouldParse(req)) {
debug('skip parsing')
next()
return
}
// assert charset
var charset = getCharset(req) || 'utf-8'
if (charset !== 'utf-8') {
debug('invalid charset')
next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', {
charset: charset,
type: 'charset.unsupported'
}))
return
}
// read
read(req, res, next, parse, debug, {
debug: debug,
encoding: charset,
inflate: inflate,
limit: limit,
verify: verify,
depth: depth
})
}
}
/**
* Get the extended query parser.
*
* @param {object} options
*/
function extendedparser (options) {
var parameterLimit = options.parameterLimit !== undefined
? options.parameterLimit
: 1000
var depth = typeof options.depth !== 'number'
? Number(options.depth || 32)
: options.depth
var parse = parser('qs')
if (isNaN(parameterLimit) || parameterLimit < 1) {
throw new TypeError('option parameterLimit must be a positive number')
}
if (isNaN(depth) || depth < 0) {
throw new TypeError('option depth must be a zero or a positive number')
}
if (isFinite(parameterLimit)) {
parameterLimit = parameterLimit | 0
}
return function queryparse (body) {
var paramCount = parameterCount(body, parameterLimit)
if (paramCount === undefined) {
debug('too many parameters')
throw createError(413, 'too many parameters', {
type: 'parameters.too.many'
})
}
var arrayLimit = Math.max(100, paramCount)
debug('parse extended urlencoding')
try {
return parse(body, {
allowPrototypes: true,
arrayLimit: arrayLimit,
depth: depth,
strictDepth: true,
parameterLimit: parameterLimit
})
} catch (err) {
if (err instanceof RangeError) {
throw createError(400, 'The input exceeded the depth', {
type: 'querystring.parse.rangeError'
})
} else {
throw err
}
}
}
}
/**
* Get the charset of a request.
*
* @param {object} req
* @api private
*/
function getCharset (req) {
try {
return (contentType.parse(req).parameters.charset || '').toLowerCase()
} catch (e) {
return undefined
}
}
/**
* Count the number of parameters, stopping once limit reached
*
* @param {string} body
* @param {number} limit
* @api private
*/
function parameterCount (body, limit) {
var count = 0
var index = 0
while ((index = body.indexOf('&', index)) !== -1) {
count++
index++
if (count === limit) {
return undefined
}
}
return count
}
/**
* Get parser for module name dynamically.
*
* @param {string} name
* @return {function}
* @api private
*/
function parser (name) {
var mod = parsers[name]
if (mod !== undefined) {
return mod.parse
}
// this uses a switch for static require analysis
switch (name) {
case 'qs':
mod = require('qs')
break
case 'querystring':
mod = require('querystring')
break
}
// store to prevent invoking require()
parsers[name] = mod
return mod.parse
}
/**
* Get the simple query parser.
*
* @param {object} options
*/
function simpleparser (options) {
var parameterLimit = options.parameterLimit !== undefined
? options.parameterLimit
: 1000
var parse = parser('querystring')
if (isNaN(parameterLimit) || parameterLimit < 1) {
throw new TypeError('option parameterLimit must be a positive number')
}
if (isFinite(parameterLimit)) {
parameterLimit = parameterLimit | 0
}
return function queryparse (body) {
var paramCount = parameterCount(body, parameterLimit)
if (paramCount === undefined) {
debug('too many parameters')
throw createError(413, 'too many parameters', {
type: 'parameters.too.many'
})
}
debug('parse urlencoding')
return parse(body, undefined, undefined, { maxKeys: parameterLimit })
}
}
/**
* Get the simple type checker.
*
* @param {string} type
* @return {function}
*/
function typeChecker (type) {
return function checkType (req) {
return Boolean(typeis(req, type))
}
}

@ -0,0 +1,56 @@
{
"name": "body-parser",
"description": "Node.js body parsing middleware",
"version": "1.20.3",
"contributors": [
"Douglas Christopher Wilson <doug@somethingdoug.com>",
"Jonathan Ong <me@jongleberry.com> (http://jongleberry.com)"
],
"license": "MIT",
"repository": "expressjs/body-parser",
"dependencies": {
"bytes": "3.1.2",
"content-type": "~1.0.5",
"debug": "2.6.9",
"depd": "2.0.0",
"destroy": "1.2.0",
"http-errors": "2.0.0",
"iconv-lite": "0.4.24",
"on-finished": "2.4.1",
"qs": "6.13.0",
"raw-body": "2.5.2",
"type-is": "~1.6.18",
"unpipe": "1.0.0"
},
"devDependencies": {
"eslint": "8.34.0",
"eslint-config-standard": "14.1.1",
"eslint-plugin-import": "2.27.5",
"eslint-plugin-markdown": "3.0.0",
"eslint-plugin-node": "11.1.0",
"eslint-plugin-promise": "6.1.1",
"eslint-plugin-standard": "4.1.0",
"methods": "1.1.2",
"mocha": "10.2.0",
"nyc": "15.1.0",
"safe-buffer": "5.2.1",
"supertest": "6.3.3"
},
"files": [
"lib/",
"LICENSE",
"HISTORY.md",
"SECURITY.md",
"index.js"
],
"engines": {
"node": ">= 0.8",
"npm": "1.2.8000 || >= 1.4.16"
},
"scripts": {
"lint": "eslint .",
"test": "mocha --require test/support/env --reporter spec --check-leaks --bail test/",
"test-ci": "nyc --reporter=lcov --reporter=text npm test",
"test-cov": "nyc --reporter=html --reporter=text npm test"
}
}

@ -0,0 +1,97 @@
3.1.2 / 2022-01-27
==================
* Fix return value for un-parsable strings
3.1.1 / 2021-11-15
==================
* Fix "thousandsSeparator" incorrecting formatting fractional part
3.1.0 / 2019-01-22
==================
* Add petabyte (`pb`) support
3.0.0 / 2017-08-31
==================
* Change "kB" to "KB" in format output
* Remove support for Node.js 0.6
* Remove support for ComponentJS
2.5.0 / 2017-03-24
==================
* Add option "unit"
2.4.0 / 2016-06-01
==================
* Add option "unitSeparator"
2.3.0 / 2016-02-15
==================
* Drop partial bytes on all parsed units
* Fix non-finite numbers to `.format` to return `null`
* Fix parsing byte string that looks like hex
* perf: hoist regular expressions
2.2.0 / 2015-11-13
==================
* add option "decimalPlaces"
* add option "fixedDecimals"
2.1.0 / 2015-05-21
==================
* add `.format` export
* add `.parse` export
2.0.2 / 2015-05-20
==================
* remove map recreation
* remove unnecessary object construction
2.0.1 / 2015-05-07
==================
* fix browserify require
* remove node.extend dependency
2.0.0 / 2015-04-12
==================
* add option "case"
* add option "thousandsSeparator"
* return "null" on invalid parse input
* support proper round-trip: bytes(bytes(num)) === num
* units no longer case sensitive when parsing
1.0.0 / 2014-05-05
==================
* add negative support. fixes #6
0.3.0 / 2014-03-19
==================
* added terabyte support
0.2.1 / 2013-04-01
==================
* add .component
0.2.0 / 2012-10-28
==================
* bytes(200).should.eql('200b')
0.1.0 / 2012-07-04
==================
* add bytes to string conversion [yields]

@ -0,0 +1,23 @@
(The MIT License)
Copyright (c) 2012-2014 TJ Holowaychuk <tj@vision-media.ca>
Copyright (c) 2015 Jed Watson <jed.watson@me.com>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

@ -0,0 +1,152 @@
# Bytes utility
[![NPM Version][npm-image]][npm-url]
[![NPM Downloads][downloads-image]][downloads-url]
[![Build Status][ci-image]][ci-url]
[![Test Coverage][coveralls-image]][coveralls-url]
Utility to parse a string bytes (ex: `1TB`) to bytes (`1099511627776`) and vice-versa.
## Installation
This is a [Node.js](https://nodejs.org/en/) module available through the
[npm registry](https://www.npmjs.com/). Installation is done using the
[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
```bash
$ npm install bytes
```
## Usage
```js
var bytes = require('bytes');
```
#### bytes(numberstring value, [options]): numberstringnull
Default export function. Delegates to either `bytes.format` or `bytes.parse` based on the type of `value`.
**Arguments**
| Name | Type | Description |
|---------|----------|--------------------|
| value | `number``string` | Number value to format or string value to parse |
| options | `Object` | Conversion options for `format` |
**Returns**
| Name | Type | Description |
|---------|------------------|-------------------------------------------------|
| results | `string``number``null` | Return null upon error. Numeric value in bytes, or string value otherwise. |
**Example**
```js
bytes(1024);
// output: '1KB'
bytes('1KB');
// output: 1024
```
#### bytes.format(number value, [options]): stringnull
Format the given value in bytes into a string. If the value is negative, it is kept as such. If it is a float, it is
rounded.
**Arguments**
| Name | Type | Description |
|---------|----------|--------------------|
| value | `number` | Value in bytes |
| options | `Object` | Conversion options |
**Options**
| Property | Type | Description |
|-------------------|--------|-----------------------------------------------------------------------------------------|
| decimalPlaces | `number``null` | Maximum number of decimal places to include in output. Default value to `2`. |
| fixedDecimals | `boolean``null` | Whether to always display the maximum number of decimal places. Default value to `false` |
| thousandsSeparator | `string``null` | Example of values: `' '`, `','` and `'.'`... Default value to `''`. |
| unit | `string``null` | The unit in which the result will be returned (B/KB/MB/GB/TB). Default value to `''` (which means auto detect). |
| unitSeparator | `string``null` | Separator to use between number and unit. Default value to `''`. |
**Returns**
| Name | Type | Description |
|---------|------------------|-------------------------------------------------|
| results | `string``null` | Return null upon error. String value otherwise. |
**Example**
```js
bytes.format(1024);
// output: '1KB'
bytes.format(1000);
// output: '1000B'
bytes.format(1000, {thousandsSeparator: ' '});
// output: '1 000B'
bytes.format(1024 * 1.7, {decimalPlaces: 0});
// output: '2KB'
bytes.format(1024, {unitSeparator: ' '});
// output: '1 KB'
```
#### bytes.parse(stringnumber value): numbernull
Parse the string value into an integer in bytes. If no unit is given, or `value`
is a number, it is assumed the value is in bytes.
Supported units and abbreviations are as follows and are case-insensitive:
* `b` for bytes
* `kb` for kilobytes
* `mb` for megabytes
* `gb` for gigabytes
* `tb` for terabytes
* `pb` for petabytes
The units are in powers of two, not ten. This means 1kb = 1024b according to this parser.
**Arguments**
| Name | Type | Description |
|---------------|--------|--------------------|
| value | `string``number` | String to parse, or number in bytes. |
**Returns**
| Name | Type | Description |
|---------|-------------|-------------------------|
| results | `number``null` | Return null upon error. Value in bytes otherwise. |
**Example**
```js
bytes.parse('1KB');
// output: 1024
bytes.parse('1024');
// output: 1024
bytes.parse(1024);
// output: 1024
```
## License
[MIT](LICENSE)
[ci-image]: https://badgen.net/github/checks/visionmedia/bytes.js/master?label=ci
[ci-url]: https://github.com/visionmedia/bytes.js/actions?query=workflow%3Aci
[coveralls-image]: https://badgen.net/coveralls/c/github/visionmedia/bytes.js/master
[coveralls-url]: https://coveralls.io/r/visionmedia/bytes.js?branch=master
[downloads-image]: https://badgen.net/npm/dm/bytes
[downloads-url]: https://npmjs.org/package/bytes
[npm-image]: https://badgen.net/npm/v/bytes
[npm-url]: https://npmjs.org/package/bytes

@ -0,0 +1,170 @@
/*!
* bytes
* Copyright(c) 2012-2014 TJ Holowaychuk
* Copyright(c) 2015 Jed Watson
* MIT Licensed
*/
'use strict';
/**
* Module exports.
* @public
*/
module.exports = bytes;
module.exports.format = format;
module.exports.parse = parse;
/**
* Module variables.
* @private
*/
var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g;
var formatDecimalsRegExp = /(?:\.0*|(\.[^0]+)0+)$/;
var map = {
b: 1,
kb: 1 << 10,
mb: 1 << 20,
gb: 1 << 30,
tb: Math.pow(1024, 4),
pb: Math.pow(1024, 5),
};
var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i;
/**
* Convert the given value in bytes into a string or parse to string to an integer in bytes.
*
* @param {string|number} value
* @param {{
* case: [string],
* decimalPlaces: [number]
* fixedDecimals: [boolean]
* thousandsSeparator: [string]
* unitSeparator: [string]
* }} [options] bytes options.
*
* @returns {string|number|null}
*/
function bytes(value, options) {
if (typeof value === 'string') {
return parse(value);
}
if (typeof value === 'number') {
return format(value, options);
}
return null;
}
/**
* Format the given value in bytes into a string.
*
* If the value is negative, it is kept as such. If it is a float,
* it is rounded.
*
* @param {number} value
* @param {object} [options]
* @param {number} [options.decimalPlaces=2]
* @param {number} [options.fixedDecimals=false]
* @param {string} [options.thousandsSeparator=]
* @param {string} [options.unit=]
* @param {string} [options.unitSeparator=]
*
* @returns {string|null}
* @public
*/
function format(value, options) {
if (!Number.isFinite(value)) {
return null;
}
var mag = Math.abs(value);
var thousandsSeparator = (options && options.thousandsSeparator) || '';
var unitSeparator = (options && options.unitSeparator) || '';
var decimalPlaces = (options && options.decimalPlaces !== undefined) ? options.decimalPlaces : 2;
var fixedDecimals = Boolean(options && options.fixedDecimals);
var unit = (options && options.unit) || '';
if (!unit || !map[unit.toLowerCase()]) {
if (mag >= map.pb) {
unit = 'PB';
} else if (mag >= map.tb) {
unit = 'TB';
} else if (mag >= map.gb) {
unit = 'GB';
} else if (mag >= map.mb) {
unit = 'MB';
} else if (mag >= map.kb) {
unit = 'KB';
} else {
unit = 'B';
}
}
var val = value / map[unit.toLowerCase()];
var str = val.toFixed(decimalPlaces);
if (!fixedDecimals) {
str = str.replace(formatDecimalsRegExp, '$1');
}
if (thousandsSeparator) {
str = str.split('.').map(function (s, i) {
return i === 0
? s.replace(formatThousandsRegExp, thousandsSeparator)
: s
}).join('.');
}
return str + unitSeparator + unit;
}
/**
* Parse the string value into an integer in bytes.
*
* If no unit is given, it is assumed the value is in bytes.
*
* @param {number|string} val
*
* @returns {number|null}
* @public
*/
function parse(val) {
if (typeof val === 'number' && !isNaN(val)) {
return val;
}
if (typeof val !== 'string') {
return null;
}
// Test if the string passed is valid
var results = parseRegExp.exec(val);
var floatValue;
var unit = 'b';
if (!results) {
// Nothing could be extracted from the given string
floatValue = parseInt(val, 10);
unit = 'b'
} else {
// Retrieve the value and the unit
floatValue = parseFloat(results[1]);
unit = results[4].toLowerCase();
}
if (isNaN(floatValue)) {
return null;
}
return Math.floor(map[unit] * floatValue);
}

@ -0,0 +1,42 @@
{
"name": "bytes",
"description": "Utility to parse a string bytes to bytes and vice-versa",
"version": "3.1.2",
"author": "TJ Holowaychuk <tj@vision-media.ca> (http://tjholowaychuk.com)",
"contributors": [
"Jed Watson <jed.watson@me.com>",
"Théo FIDRY <theo.fidry@gmail.com>"
],
"license": "MIT",
"keywords": [
"byte",
"bytes",
"utility",
"parse",
"parser",
"convert",
"converter"
],
"repository": "visionmedia/bytes.js",
"devDependencies": {
"eslint": "7.32.0",
"eslint-plugin-markdown": "2.2.1",
"mocha": "9.2.0",
"nyc": "15.1.0"
},
"files": [
"History.md",
"LICENSE",
"Readme.md",
"index.js"
],
"engines": {
"node": ">= 0.8"
},
"scripts": {
"lint": "eslint .",
"test": "mocha --check-leaks --reporter spec",
"test-ci": "nyc --reporter=lcov --reporter=text npm test",
"test-cov": "nyc --reporter=html --reporter=text npm test"
}
}

@ -0,0 +1,17 @@
{
"root": true,
"extends": "@ljharb",
"rules": {
"func-name-matching": 0,
"id-length": 0,
"new-cap": [2, {
"capIsNewExceptions": [
"GetIntrinsic",
],
}],
"no-extra-parens": 0,
"no-magic-numbers": 0,
},
}

@ -0,0 +1,12 @@
# These are supported funding model platforms
github: [ljharb]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: npm/call-bind-apply-helpers
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']

@ -0,0 +1,9 @@
{
"all": true,
"check-coverage": false,
"reporter": ["text-summary", "text", "html", "json"],
"exclude": [
"coverage",
"test"
]
}

@ -0,0 +1,30 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [v1.0.2](https://github.com/ljharb/call-bind-apply-helpers/compare/v1.0.1...v1.0.2) - 2025-02-12
### Commits
- [types] improve inferred types [`e6f9586`](https://github.com/ljharb/call-bind-apply-helpers/commit/e6f95860a3c72879cb861a858cdfb8138fbedec1)
- [Dev Deps] update `@arethetypeswrong/cli`, `@ljharb/tsconfig`, `@types/tape`, `es-value-fixtures`, `for-each`, `has-strict-mode`, `object-inspect` [`e43d540`](https://github.com/ljharb/call-bind-apply-helpers/commit/e43d5409f97543bfbb11f345d47d8ce4e066d8c1)
## [v1.0.1](https://github.com/ljharb/call-bind-apply-helpers/compare/v1.0.0...v1.0.1) - 2024-12-08
### Commits
- [types] `reflectApply`: fix types [`4efc396`](https://github.com/ljharb/call-bind-apply-helpers/commit/4efc3965351a4f02cc55e836fa391d3d11ef2ef8)
- [Fix] `reflectApply`: oops, Reflect is not a function [`83cc739`](https://github.com/ljharb/call-bind-apply-helpers/commit/83cc7395de6b79b7730bdf092f1436f0b1263c75)
- [Dev Deps] update `@arethetypeswrong/cli` [`80bd5d3`](https://github.com/ljharb/call-bind-apply-helpers/commit/80bd5d3ae58b4f6b6995ce439dd5a1bcb178a940)
## v1.0.0 - 2024-12-05
### Commits
- Initial implementation, tests, readme [`7879629`](https://github.com/ljharb/call-bind-apply-helpers/commit/78796290f9b7430c9934d6f33d94ae9bc89fce04)
- Initial commit [`3f1dc16`](https://github.com/ljharb/call-bind-apply-helpers/commit/3f1dc164afc43285631b114a5f9dd9137b2b952f)
- npm init [`081df04`](https://github.com/ljharb/call-bind-apply-helpers/commit/081df048c312fcee400922026f6e97281200a603)
- Only apps should have lockfiles [`5b9ca0f`](https://github.com/ljharb/call-bind-apply-helpers/commit/5b9ca0fe8101ebfaf309c549caac4e0a017ed930)

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2024 Jordan Harband
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

@ -0,0 +1,62 @@
# call-bind-apply-helpers <sup>[![Version Badge][npm-version-svg]][package-url]</sup>
[![github actions][actions-image]][actions-url]
[![coverage][codecov-image]][codecov-url]
[![dependency status][deps-svg]][deps-url]
[![dev dependency status][dev-deps-svg]][dev-deps-url]
[![License][license-image]][license-url]
[![Downloads][downloads-image]][downloads-url]
[![npm badge][npm-badge-png]][package-url]
Helper functions around Function call/apply/bind, for use in `call-bind`.
The only packages that should likely ever use this package directly are `call-bind` and `get-intrinsic`.
Please use `call-bind` unless you have a very good reason not to.
## Getting started
```sh
npm install --save call-bind-apply-helpers
```
## Usage/Examples
```js
const assert = require('assert');
const callBindBasic = require('call-bind-apply-helpers');
function f(a, b) {
assert.equal(this, 1);
assert.equal(a, 2);
assert.equal(b, 3);
assert.equal(arguments.length, 2);
}
const fBound = callBindBasic([f, 1]);
delete Function.prototype.call;
delete Function.prototype.bind;
fBound(2, 3);
```
## Tests
Clone the repo, `npm install`, and run `npm test`
[package-url]: https://npmjs.org/package/call-bind-apply-helpers
[npm-version-svg]: https://versionbadg.es/ljharb/call-bind-apply-helpers.svg
[deps-svg]: https://david-dm.org/ljharb/call-bind-apply-helpers.svg
[deps-url]: https://david-dm.org/ljharb/call-bind-apply-helpers
[dev-deps-svg]: https://david-dm.org/ljharb/call-bind-apply-helpers/dev-status.svg
[dev-deps-url]: https://david-dm.org/ljharb/call-bind-apply-helpers#info=devDependencies
[npm-badge-png]: https://nodei.co/npm/call-bind-apply-helpers.png?downloads=true&stars=true
[license-image]: https://img.shields.io/npm/l/call-bind-apply-helpers.svg
[license-url]: LICENSE
[downloads-image]: https://img.shields.io/npm/dm/call-bind-apply-helpers.svg
[downloads-url]: https://npm-stat.com/charts.html?package=call-bind-apply-helpers
[codecov-image]: https://codecov.io/gh/ljharb/call-bind-apply-helpers/branch/main/graphs/badge.svg
[codecov-url]: https://app.codecov.io/gh/ljharb/call-bind-apply-helpers/
[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/call-bind-apply-helpers
[actions-url]: https://github.com/ljharb/call-bind-apply-helpers/actions

@ -0,0 +1 @@
export = Reflect.apply;

@ -0,0 +1,10 @@
'use strict';
var bind = require('function-bind');
var $apply = require('./functionApply');
var $call = require('./functionCall');
var $reflectApply = require('./reflectApply');
/** @type {import('./actualApply')} */
module.exports = $reflectApply || bind.call($call, $apply);

@ -0,0 +1,19 @@
import actualApply from './actualApply';
type TupleSplitHead<T extends any[], N extends number> = T['length'] extends N
? T
: T extends [...infer R, any]
? TupleSplitHead<R, N>
: never
type TupleSplitTail<T, N extends number, O extends any[] = []> = O['length'] extends N
? T
: T extends [infer F, ...infer R]
? TupleSplitTail<[...R], N, [...O, F]>
: never
type TupleSplit<T extends any[], N extends number> = [TupleSplitHead<T, N>, TupleSplitTail<T, N>]
declare function applyBind(...args: TupleSplit<Parameters<typeof actualApply>, 2>[1]): ReturnType<typeof actualApply>;
export = applyBind;

@ -0,0 +1,10 @@
'use strict';
var bind = require('function-bind');
var $apply = require('./functionApply');
var actualApply = require('./actualApply');
/** @type {import('./applyBind')} */
module.exports = function applyBind() {
return actualApply(bind, $apply, arguments);
};

@ -0,0 +1 @@
export = Function.prototype.apply;

@ -0,0 +1,4 @@
'use strict';
/** @type {import('./functionApply')} */
module.exports = Function.prototype.apply;

@ -0,0 +1 @@
export = Function.prototype.call;

@ -0,0 +1,4 @@
'use strict';
/** @type {import('./functionCall')} */
module.exports = Function.prototype.call;

@ -0,0 +1,64 @@
type RemoveFromTuple<
Tuple extends readonly unknown[],
RemoveCount extends number,
Index extends 1[] = []
> = Index["length"] extends RemoveCount
? Tuple
: Tuple extends [infer First, ...infer Rest]
? RemoveFromTuple<Rest, RemoveCount, [...Index, 1]>
: Tuple;
type ConcatTuples<
Prefix extends readonly unknown[],
Suffix extends readonly unknown[]
> = [...Prefix, ...Suffix];
type ExtractFunctionParams<T> = T extends (this: infer TThis, ...args: infer P extends readonly unknown[]) => infer R
? { thisArg: TThis; params: P; returnType: R }
: never;
type BindFunction<
T extends (this: any, ...args: any[]) => any,
TThis,
TBoundArgs extends readonly unknown[],
ReceiverBound extends boolean
> = ExtractFunctionParams<T> extends {
thisArg: infer OrigThis;
params: infer P extends readonly unknown[];
returnType: infer R;
}
? ReceiverBound extends true
? (...args: RemoveFromTuple<P, Extract<TBoundArgs["length"], number>>) => R extends [OrigThis, ...infer Rest]
? [TThis, ...Rest] // Replace `this` with `thisArg`
: R
: <U, RemainingArgs extends RemoveFromTuple<P, Extract<TBoundArgs["length"], number>>>(
thisArg: U,
...args: RemainingArgs
) => R extends [OrigThis, ...infer Rest]
? [U, ...ConcatTuples<TBoundArgs, Rest>] // Preserve bound args in return type
: R
: never;
declare function callBind<
const T extends (this: any, ...args: any[]) => any,
Extracted extends ExtractFunctionParams<T>,
const TBoundArgs extends Partial<Extracted["params"]> & readonly unknown[],
const TThis extends Extracted["thisArg"]
>(
args: [fn: T, thisArg: TThis, ...boundArgs: TBoundArgs]
): BindFunction<T, TThis, TBoundArgs, true>;
declare function callBind<
const T extends (this: any, ...args: any[]) => any,
Extracted extends ExtractFunctionParams<T>,
const TBoundArgs extends Partial<Extracted["params"]> & readonly unknown[]
>(
args: [fn: T, ...boundArgs: TBoundArgs]
): BindFunction<T, Extracted["thisArg"], TBoundArgs, false>;
declare function callBind<const TArgs extends readonly unknown[]>(
args: [fn: Exclude<TArgs[0], Function>, ...rest: TArgs]
): never;
// export as namespace callBind;
export = callBind;

@ -0,0 +1,15 @@
'use strict';
var bind = require('function-bind');
var $TypeError = require('es-errors/type');
var $call = require('./functionCall');
var $actualApply = require('./actualApply');
/** @type {(args: [Function, thisArg?: unknown, ...args: unknown[]]) => Function} TODO FIXME, find a way to use import('.') */
module.exports = function callBindBasic(args) {
if (args.length < 1 || typeof args[0] !== 'function') {
throw new $TypeError('a function is required');
}
return $actualApply(bind, $call, args);
};

@ -0,0 +1,85 @@
{
"name": "call-bind-apply-helpers",
"version": "1.0.2",
"description": "Helper functions around Function call/apply/bind, for use in `call-bind`",
"main": "index.js",
"exports": {
".": "./index.js",
"./actualApply": "./actualApply.js",
"./applyBind": "./applyBind.js",
"./functionApply": "./functionApply.js",
"./functionCall": "./functionCall.js",
"./reflectApply": "./reflectApply.js",
"./package.json": "./package.json"
},
"scripts": {
"prepack": "npmignore --auto --commentLines=auto",
"prepublish": "not-in-publish || npm run prepublishOnly",
"prepublishOnly": "safe-publish-latest",
"prelint": "evalmd README.md",
"lint": "eslint --ext=.js,.mjs .",
"postlint": "tsc -p . && attw -P",
"pretest": "npm run lint",
"tests-only": "nyc tape 'test/**/*.js'",
"test": "npm run tests-only",
"posttest": "npx npm@'>=10.2' audit --production",
"version": "auto-changelog && git add CHANGELOG.md",
"postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\""
},
"repository": {
"type": "git",
"url": "git+https://github.com/ljharb/call-bind-apply-helpers.git"
},
"author": "Jordan Harband <ljharb@gmail.com>",
"license": "MIT",
"bugs": {
"url": "https://github.com/ljharb/call-bind-apply-helpers/issues"
},
"homepage": "https://github.com/ljharb/call-bind-apply-helpers#readme",
"dependencies": {
"es-errors": "^1.3.0",
"function-bind": "^1.1.2"
},
"devDependencies": {
"@arethetypeswrong/cli": "^0.17.3",
"@ljharb/eslint-config": "^21.1.1",
"@ljharb/tsconfig": "^0.2.3",
"@types/for-each": "^0.3.3",
"@types/function-bind": "^1.1.10",
"@types/object-inspect": "^1.13.0",
"@types/tape": "^5.8.1",
"auto-changelog": "^2.5.0",
"encoding": "^0.1.13",
"es-value-fixtures": "^1.7.1",
"eslint": "=8.8.0",
"evalmd": "^0.0.19",
"for-each": "^0.3.5",
"has-strict-mode": "^1.1.0",
"in-publish": "^2.0.1",
"npmignore": "^0.3.1",
"nyc": "^10.3.2",
"object-inspect": "^1.13.4",
"safe-publish-latest": "^2.0.0",
"tape": "^5.9.0",
"typescript": "next"
},
"testling": {
"files": "test/index.js"
},
"auto-changelog": {
"output": "CHANGELOG.md",
"template": "keepachangelog",
"unreleased": false,
"commitLimit": false,
"backfillLimit": false,
"hideCredit": true
},
"publishConfig": {
"ignore": [
".github/workflows"
]
},
"engines": {
"node": ">= 0.4"
}
}

@ -0,0 +1,3 @@
declare const reflectApply: false | typeof Reflect.apply;
export = reflectApply;

@ -0,0 +1,4 @@
'use strict';
/** @type {import('./reflectApply')} */
module.exports = typeof Reflect !== 'undefined' && Reflect && Reflect.apply;

@ -0,0 +1,63 @@
'use strict';
var callBind = require('../');
var hasStrictMode = require('has-strict-mode')();
var forEach = require('for-each');
var inspect = require('object-inspect');
var v = require('es-value-fixtures');
var test = require('tape');
test('callBindBasic', function (t) {
forEach(v.nonFunctions, function (nonFunction) {
t['throws'](
// @ts-expect-error
function () { callBind([nonFunction]); },
TypeError,
inspect(nonFunction) + ' is not a function'
);
});
var sentinel = { sentinel: true };
/** @type {<T, A extends number, B extends number>(this: T, a: A, b: B) => [T | undefined, A, B]} */
var func = function (a, b) {
// eslint-disable-next-line no-invalid-this
return [!hasStrictMode && this === global ? undefined : this, a, b];
};
t.equal(func.length, 2, 'original function length is 2');
/** type {(thisArg: unknown, a: number, b: number) => [unknown, number, number]} */
var bound = callBind([func]);
/** type {((a: number, b: number) => [typeof sentinel, typeof a, typeof b])} */
var boundR = callBind([func, sentinel]);
/** type {((b: number) => [typeof sentinel, number, typeof b])} */
var boundArg = callBind([func, sentinel, /** @type {const} */ (1)]);
// @ts-expect-error
t.deepEqual(bound(), [undefined, undefined, undefined], 'bound func with no args');
// @ts-expect-error
t.deepEqual(func(), [undefined, undefined, undefined], 'unbound func with too few args');
// @ts-expect-error
t.deepEqual(bound(1, 2), [hasStrictMode ? 1 : Object(1), 2, undefined], 'bound func too few args');
// @ts-expect-error
t.deepEqual(boundR(), [sentinel, undefined, undefined], 'bound func with receiver, with too few args');
// @ts-expect-error
t.deepEqual(boundArg(), [sentinel, 1, undefined], 'bound func with receiver and arg, with too few args');
t.deepEqual(func(1, 2), [undefined, 1, 2], 'unbound func with right args');
t.deepEqual(bound(1, 2, 3), [hasStrictMode ? 1 : Object(1), 2, 3], 'bound func with right args');
t.deepEqual(boundR(1, 2), [sentinel, 1, 2], 'bound func with receiver, with right args');
t.deepEqual(boundArg(2), [sentinel, 1, 2], 'bound func with receiver and arg, with right arg');
// @ts-expect-error
t.deepEqual(func(1, 2, 3), [undefined, 1, 2], 'unbound func with too many args');
// @ts-expect-error
t.deepEqual(bound(1, 2, 3, 4), [hasStrictMode ? 1 : Object(1), 2, 3], 'bound func with too many args');
// @ts-expect-error
t.deepEqual(boundR(1, 2, 3), [sentinel, 1, 2], 'bound func with receiver, with too many args');
// @ts-expect-error
t.deepEqual(boundArg(2, 3), [sentinel, 1, 2], 'bound func with receiver and arg, with too many args');
t.end();
});

@ -0,0 +1,9 @@
{
"extends": "@ljharb/tsconfig",
"compilerOptions": {
"target": "es2021",
},
"exclude": [
"coverage",
],
}

@ -0,0 +1,13 @@
{
"root": true,
"extends": "@ljharb",
"rules": {
"new-cap": [2, {
"capIsNewExceptions": [
"GetIntrinsic",
],
}],
},
}

@ -0,0 +1,12 @@
# These are supported funding model platforms
github: [ljharb]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: npm/call-bound
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']

@ -0,0 +1,9 @@
{
"all": true,
"check-coverage": false,
"reporter": ["text-summary", "text", "html", "json"],
"exclude": [
"coverage",
"test"
]
}

@ -0,0 +1,42 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [v1.0.4](https://github.com/ljharb/call-bound/compare/v1.0.3...v1.0.4) - 2025-03-03
### Commits
- [types] improve types [`e648922`](https://github.com/ljharb/call-bound/commit/e6489222a9e54f350fbf952ceabe51fd8b6027ff)
- [Dev Deps] update `@arethetypeswrong/cli`, `@ljharb/tsconfig`, `@types/tape`, `es-value-fixtures`, `for-each`, `has-strict-mode`, `object-inspect` [`a42a5eb`](https://github.com/ljharb/call-bound/commit/a42a5ebe6c1b54fcdc7997c7dc64fdca9e936719)
- [Deps] update `call-bind-apply-helpers`, `get-intrinsic` [`f529eac`](https://github.com/ljharb/call-bound/commit/f529eac132404c17156bbc23ab2297a25d0f20b8)
## [v1.0.3](https://github.com/ljharb/call-bound/compare/v1.0.2...v1.0.3) - 2024-12-15
### Commits
- [Refactor] use `call-bind-apply-helpers` instead of `call-bind` [`5e0b134`](https://github.com/ljharb/call-bound/commit/5e0b13496df14fb7d05dae9412f088da8d3f75be)
- [Deps] update `get-intrinsic` [`41fc967`](https://github.com/ljharb/call-bound/commit/41fc96732a22c7b7e8f381f93ccc54bb6293be2e)
- [readme] fix example [`79a0137`](https://github.com/ljharb/call-bound/commit/79a0137723f7c6d09c9c05452bbf8d5efb5d6e49)
- [meta] add `sideEffects` flag [`08b07be`](https://github.com/ljharb/call-bound/commit/08b07be7f1c03f67dc6f3cdaf0906259771859f7)
## [v1.0.2](https://github.com/ljharb/call-bound/compare/v1.0.1...v1.0.2) - 2024-12-10
### Commits
- [Dev Deps] update `@arethetypeswrong/cli`, `@ljharb/tsconfig`, `gopd` [`e6a5ffe`](https://github.com/ljharb/call-bound/commit/e6a5ffe849368fe4f74dfd6cdeca1b9baa39e8d5)
- [Deps] update `call-bind`, `get-intrinsic` [`2aeb5b5`](https://github.com/ljharb/call-bound/commit/2aeb5b521dc2b2683d1345c753ea1161de2d1c14)
- [types] improve return type [`1a0c9fe`](https://github.com/ljharb/call-bound/commit/1a0c9fe3114471e7ca1f57d104e2efe713bb4871)
## v1.0.1 - 2024-12-05
### Commits
- Initial implementation, tests, readme, types [`6d94121`](https://github.com/ljharb/call-bound/commit/6d94121a9243602e506334069f7a03189fe3363d)
- Initial commit [`0eae867`](https://github.com/ljharb/call-bound/commit/0eae867334ea025c33e6e91cdecfc9df96680cf9)
- npm init [`71b2479`](https://github.com/ljharb/call-bound/commit/71b2479c6723e0b7d91a6b663613067e98b7b275)
- Only apps should have lockfiles [`c3754a9`](https://github.com/ljharb/call-bound/commit/c3754a949b7f9132b47e2d18c1729889736741eb)
- [actions] skip `npm ls` in node &lt; 10 [`74275a5`](https://github.com/ljharb/call-bound/commit/74275a5186b8caf6309b6b97472bdcb0df4683a8)
- [Dev Deps] add missing peer dep [`1354de8`](https://github.com/ljharb/call-bound/commit/1354de8679413e4ae9c523d85f76fa7a5e032d97)

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2024 Jordan Harband
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

@ -0,0 +1,53 @@
# call-bound <sup>[![Version Badge][npm-version-svg]][package-url]</sup>
[![github actions][actions-image]][actions-url]
[![coverage][codecov-image]][codecov-url]
[![dependency status][deps-svg]][deps-url]
[![dev dependency status][dev-deps-svg]][dev-deps-url]
[![License][license-image]][license-url]
[![Downloads][downloads-image]][downloads-url]
[![npm badge][npm-badge-png]][package-url]
Robust call-bound JavaScript intrinsics, using `call-bind` and `get-intrinsic`.
## Getting started
```sh
npm install --save call-bound
```
## Usage/Examples
```js
const assert = require('assert');
const callBound = require('call-bound');
const slice = callBound('Array.prototype.slice');
delete Function.prototype.call;
delete Function.prototype.bind;
delete Array.prototype.slice;
assert.deepEqual(slice([1, 2, 3, 4], 1, -1), [2, 3]);
```
## Tests
Clone the repo, `npm install`, and run `npm test`
[package-url]: https://npmjs.org/package/call-bound
[npm-version-svg]: https://versionbadg.es/ljharb/call-bound.svg
[deps-svg]: https://david-dm.org/ljharb/call-bound.svg
[deps-url]: https://david-dm.org/ljharb/call-bound
[dev-deps-svg]: https://david-dm.org/ljharb/call-bound/dev-status.svg
[dev-deps-url]: https://david-dm.org/ljharb/call-bound#info=devDependencies
[npm-badge-png]: https://nodei.co/npm/call-bound.png?downloads=true&stars=true
[license-image]: https://img.shields.io/npm/l/call-bound.svg
[license-url]: LICENSE
[downloads-image]: https://img.shields.io/npm/dm/call-bound.svg
[downloads-url]: https://npm-stat.com/charts.html?package=call-bound
[codecov-image]: https://codecov.io/gh/ljharb/call-bound/branch/main/graphs/badge.svg
[codecov-url]: https://app.codecov.io/gh/ljharb/call-bound/
[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/call-bound
[actions-url]: https://github.com/ljharb/call-bound/actions

@ -0,0 +1,94 @@
type Intrinsic = typeof globalThis;
type IntrinsicName = keyof Intrinsic | `%${keyof Intrinsic}%`;
type IntrinsicPath = IntrinsicName | `${StripPercents<IntrinsicName>}.${string}` | `%${StripPercents<IntrinsicName>}.${string}%`;
type AllowMissing = boolean;
type StripPercents<T extends string> = T extends `%${infer U}%` ? U : T;
type BindMethodPrecise<F> =
F extends (this: infer This, ...args: infer Args) => infer R
? (obj: This, ...args: Args) => R
: F extends {
(this: infer This1, ...args: infer Args1): infer R1;
(this: infer This2, ...args: infer Args2): infer R2
}
? {
(obj: This1, ...args: Args1): R1;
(obj: This2, ...args: Args2): R2
}
: never
// Extract method type from a prototype
type GetPrototypeMethod<T extends keyof typeof globalThis, M extends string> =
(typeof globalThis)[T] extends { prototype: any }
? M extends keyof (typeof globalThis)[T]['prototype']
? (typeof globalThis)[T]['prototype'][M]
: never
: never
// Get static property/method
type GetStaticMember<T extends keyof typeof globalThis, P extends string> =
P extends keyof (typeof globalThis)[T] ? (typeof globalThis)[T][P] : never
// Type that maps string path to actual bound function or value with better precision
type BoundIntrinsic<S extends string> =
S extends `${infer Obj}.prototype.${infer Method}`
? Obj extends keyof typeof globalThis
? BindMethodPrecise<GetPrototypeMethod<Obj, Method & string>>
: unknown
: S extends `${infer Obj}.${infer Prop}`
? Obj extends keyof typeof globalThis
? GetStaticMember<Obj, Prop & string>
: unknown
: unknown
declare function arraySlice<T>(array: readonly T[], start?: number, end?: number): T[];
declare function arraySlice<T>(array: ArrayLike<T>, start?: number, end?: number): T[];
declare function arraySlice<T>(array: IArguments, start?: number, end?: number): T[];
// Special cases for methods that need explicit typing
interface SpecialCases {
'%Object.prototype.isPrototypeOf%': (thisArg: {}, obj: unknown) => boolean;
'%String.prototype.replace%': {
(str: string, searchValue: string | RegExp, replaceValue: string): string;
(str: string, searchValue: string | RegExp, replacer: (substring: string, ...args: any[]) => string): string
};
'%Object.prototype.toString%': (obj: {}) => string;
'%Object.prototype.hasOwnProperty%': (obj: {}, v: PropertyKey) => boolean;
'%Array.prototype.slice%': typeof arraySlice;
'%Array.prototype.map%': <T, U>(array: readonly T[], callbackfn: (value: T, index: number, array: readonly T[]) => U, thisArg?: any) => U[];
'%Array.prototype.filter%': <T>(array: readonly T[], predicate: (value: T, index: number, array: readonly T[]) => unknown, thisArg?: any) => T[];
'%Array.prototype.indexOf%': <T>(array: readonly T[], searchElement: T, fromIndex?: number) => number;
'%Function.prototype.apply%': <T, A extends any[], R>(fn: (...args: A) => R, thisArg: any, args: A) => R;
'%Function.prototype.call%': <T, A extends any[], R>(fn: (...args: A) => R, thisArg: any, ...args: A) => R;
'%Function.prototype.bind%': <T, A extends any[], R>(fn: (...args: A) => R, thisArg: any, ...args: A) => (...remainingArgs: A) => R;
'%Promise.prototype.then%': {
<T, R>(promise: Promise<T>, onfulfilled: (value: T) => R | PromiseLike<R>): Promise<R>;
<T, R>(promise: Promise<T>, onfulfilled: ((value: T) => R | PromiseLike<R>) | undefined | null, onrejected: (reason: any) => R | PromiseLike<R>): Promise<R>;
};
'%RegExp.prototype.test%': (regexp: RegExp, str: string) => boolean;
'%RegExp.prototype.exec%': (regexp: RegExp, str: string) => RegExpExecArray | null;
'%Error.prototype.toString%': (error: Error) => string;
'%TypeError.prototype.toString%': (error: TypeError) => string;
'%String.prototype.split%': (
obj: unknown,
splitter: string | RegExp | {
[Symbol.split](string: string, limit?: number): string[];
},
limit?: number | undefined
) => string[];
}
/**
* Returns a bound function for a prototype method, or a value for a static property.
*
* @param name - The name of the intrinsic (e.g. 'Array.prototype.slice')
* @param {AllowMissing} [allowMissing] - Whether to allow missing intrinsics (default: false)
*/
declare function callBound<K extends keyof SpecialCases | StripPercents<keyof SpecialCases>, S extends IntrinsicPath>(name: K, allowMissing?: AllowMissing): SpecialCases[`%${StripPercents<K>}%`];
declare function callBound<K extends keyof SpecialCases | StripPercents<keyof SpecialCases>, S extends IntrinsicPath>(name: S, allowMissing?: AllowMissing): BoundIntrinsic<S>;
export = callBound;

@ -0,0 +1,19 @@
'use strict';
var GetIntrinsic = require('get-intrinsic');
var callBindBasic = require('call-bind-apply-helpers');
/** @type {(thisArg: string, searchString: string, position?: number) => number} */
var $indexOf = callBindBasic([GetIntrinsic('%String.prototype.indexOf%')]);
/** @type {import('.')} */
module.exports = function callBoundIntrinsic(name, allowMissing) {
/* eslint no-extra-parens: 0 */
var intrinsic = /** @type {(this: unknown, ...args: unknown[]) => unknown} */ (GetIntrinsic(name, !!allowMissing));
if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) {
return callBindBasic(/** @type {const} */ ([intrinsic]));
}
return intrinsic;
};

@ -0,0 +1,99 @@
{
"name": "call-bound",
"version": "1.0.4",
"description": "Robust call-bound JavaScript intrinsics, using `call-bind` and `get-intrinsic`.",
"main": "index.js",
"exports": {
".": "./index.js",
"./package.json": "./package.json"
},
"sideEffects": false,
"scripts": {
"prepack": "npmignore --auto --commentLines=auto",
"prepublish": "not-in-publish || npm run prepublishOnly",
"prepublishOnly": "safe-publish-latest",
"prelint": "evalmd README.md",
"lint": "eslint --ext=.js,.mjs .",
"postlint": "tsc -p . && attw -P",
"pretest": "npm run lint",
"tests-only": "nyc tape 'test/**/*.js'",
"test": "npm run tests-only",
"posttest": "npx npm@'>=10.2' audit --production",
"version": "auto-changelog && git add CHANGELOG.md",
"postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\""
},
"repository": {
"type": "git",
"url": "git+https://github.com/ljharb/call-bound.git"
},
"keywords": [
"javascript",
"ecmascript",
"es",
"js",
"callbind",
"callbound",
"call",
"bind",
"bound",
"call-bind",
"call-bound",
"function",
"es-abstract"
],
"author": "Jordan Harband <ljharb@gmail.com>",
"funding": {
"url": "https://github.com/sponsors/ljharb"
},
"license": "MIT",
"bugs": {
"url": "https://github.com/ljharb/call-bound/issues"
},
"homepage": "https://github.com/ljharb/call-bound#readme",
"dependencies": {
"call-bind-apply-helpers": "^1.0.2",
"get-intrinsic": "^1.3.0"
},
"devDependencies": {
"@arethetypeswrong/cli": "^0.17.4",
"@ljharb/eslint-config": "^21.1.1",
"@ljharb/tsconfig": "^0.3.0",
"@types/call-bind": "^1.0.5",
"@types/get-intrinsic": "^1.2.3",
"@types/tape": "^5.8.1",
"auto-changelog": "^2.5.0",
"encoding": "^0.1.13",
"es-value-fixtures": "^1.7.1",
"eslint": "=8.8.0",
"evalmd": "^0.0.19",
"for-each": "^0.3.5",
"gopd": "^1.2.0",
"has-strict-mode": "^1.1.0",
"in-publish": "^2.0.1",
"npmignore": "^0.3.1",
"nyc": "^10.3.2",
"object-inspect": "^1.13.4",
"safe-publish-latest": "^2.0.0",
"tape": "^5.9.0",
"typescript": "next"
},
"testling": {
"files": "test/index.js"
},
"auto-changelog": {
"output": "CHANGELOG.md",
"template": "keepachangelog",
"unreleased": false,
"commitLimit": false,
"backfillLimit": false,
"hideCredit": true
},
"publishConfig": {
"ignore": [
".github/workflows"
]
},
"engines": {
"node": ">= 0.4"
}
}

@ -0,0 +1,61 @@
'use strict';
var test = require('tape');
var callBound = require('../');
/** @template {true} T @template U @typedef {T extends U ? T : never} AssertType */
test('callBound', function (t) {
// static primitive
t.equal(callBound('Array.length'), Array.length, 'Array.length yields itself');
t.equal(callBound('%Array.length%'), Array.length, '%Array.length% yields itself');
// static non-function object
t.equal(callBound('Array.prototype'), Array.prototype, 'Array.prototype yields itself');
t.equal(callBound('%Array.prototype%'), Array.prototype, '%Array.prototype% yields itself');
t.equal(callBound('Array.constructor'), Array.constructor, 'Array.constructor yields itself');
t.equal(callBound('%Array.constructor%'), Array.constructor, '%Array.constructor% yields itself');
// static function
t.equal(callBound('Date.parse'), Date.parse, 'Date.parse yields itself');
t.equal(callBound('%Date.parse%'), Date.parse, '%Date.parse% yields itself');
// prototype primitive
t.equal(callBound('Error.prototype.message'), Error.prototype.message, 'Error.prototype.message yields itself');
t.equal(callBound('%Error.prototype.message%'), Error.prototype.message, '%Error.prototype.message% yields itself');
var x = callBound('Object.prototype.toString');
var y = callBound('%Object.prototype.toString%');
// prototype function
t.notEqual(x, Object.prototype.toString, 'Object.prototype.toString does not yield itself');
t.notEqual(y, Object.prototype.toString, '%Object.prototype.toString% does not yield itself');
t.equal(x(true), Object.prototype.toString.call(true), 'call-bound Object.prototype.toString calls into the original');
t.equal(y(true), Object.prototype.toString.call(true), 'call-bound %Object.prototype.toString% calls into the original');
t['throws'](
// @ts-expect-error
function () { callBound('does not exist'); },
SyntaxError,
'nonexistent intrinsic throws'
);
t['throws'](
// @ts-expect-error
function () { callBound('does not exist', true); },
SyntaxError,
'allowMissing arg still throws for unknown intrinsic'
);
t.test('real but absent intrinsic', { skip: typeof WeakRef !== 'undefined' }, function (st) {
st['throws'](
function () { callBound('WeakRef'); },
TypeError,
'real but absent intrinsic throws'
);
st.equal(callBound('WeakRef', true), undefined, 'allowMissing arg avoids exception');
st.end();
});
t.end();
});

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save