diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..d0ce6bf --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "libcore"] + path = libcore + url = https://github.com/hiddify/hiddify-next-core diff --git a/ANDROID_LOGIN_PANEL_FIX_SUMMARY.md b/ANDROID_LOGIN_PANEL_FIX_SUMMARY.md deleted file mode 100755 index cbbe089..0000000 --- a/ANDROID_LOGIN_PANEL_FIX_SUMMARY.md +++ /dev/null @@ -1,157 +0,0 @@ -# Android 登录框不显示问题修复总结 - -## 🔧 修复内容 - -### **1. KRHomeController 登录状态初始化逻辑修复** - -#### **修复前的问题** -- 登录状态初始化没有延迟,可能在异步操作完成前就执行 -- 缺少状态验证,直接使用 `kr_isLogin.value` 可能导致状态不一致 -- 订阅服务初始化失败时没有错误处理 -- 缺少状态同步检查机制 - -#### **修复后的改进** -```dart -// 1. 添加延迟初始化 -Future.delayed(const Duration(milliseconds: 100), () { - _kr_validateAndSetLoginStatus(); -}); - -// 2. 添加状态验证 -final isValidLogin = KRAppRunData().kr_token != null && - KRAppRunData().kr_isLogin.value; - -// 3. 添加错误处理 -kr_subscribeService.kr_refreshAll().catchError((error) { - KRLogUtil.kr_e('订阅服务初始化失败: $error', tag: 'HomeController'); -}); - -// 4. 添加状态同步检查 -WidgetsBinding.instance.addPostFrameCallback((_) { - _kr_syncLoginStatus(); -}); -``` - -### **2. KRAppRunData 初始化逻辑优化** - -#### **修复前的问题** -- 登录状态设置和异步操作之间存在竞态条件 -- 缺少详细的日志记录,难以调试问题 -- 错误处理不够完善 - -#### **修复后的改进** -```dart -// 1. 添加详细日志 -KRLogUtil.kr_i('开始初始化用户信息', tag: 'AppRunData'); - -// 2. 验证token有效性 -if (kr_token != null && kr_token!.isNotEmpty) { - kr_isLogin.value = true; - // 异步获取用户信息,不等待结果 - _iniUserInfo().catchError((error) { - KRLogUtil.kr_e('获取用户信息失败: $error', tag: 'AppRunData'); - }); -} - -// 3. 改进保存逻辑 -// 只有在保存成功后才设置登录状态 -kr_isLogin.value = true; -``` - -### **3. 启动页面保护机制** - -#### **修复前的问题** -- 启动完成后立即跳转,没有验证初始化结果 -- 缺少启动状态的日志记录 - -#### **修复后的改进** -```dart -// 1. 添加初始化完成等待 -await Future.delayed(const Duration(milliseconds: 200)); - -// 2. 验证登录状态 -final loginStatus = KRAppRunData.getInstance().kr_isLogin.value; -KRLogUtil.kr_i('启动完成,最终登录状态: $loginStatus', tag: 'SplashController'); -``` - -## 🎯 修复效果 - -### **解决的问题** -1. **竞态条件** - 通过延迟初始化和状态验证解决 -2. **状态不一致** - 通过状态同步检查机制解决 -3. **异步操作失败** - 通过错误处理和重试机制解决 -4. **调试困难** - 通过详细日志记录解决 - -### **预期改进** -1. **登录框显示稳定性** - 减少启动时登录框不显示的情况 -2. **状态一致性** - 确保UI状态与实际登录状态一致 -3. **错误恢复能力** - 提高应用在异常情况下的恢复能力 -4. **调试便利性** - 通过详细日志便于问题定位 - -## 📊 修复策略 - -### **1. 延迟初始化策略** -- 在首页控制器初始化时延迟100ms执行状态验证 -- 确保所有异步操作有足够时间完成 - -### **2. 状态验证策略** -- 双重验证:检查 `kr_token` 和 `kr_isLogin.value` -- 防止状态不一致导致的UI问题 - -### **3. 错误处理策略** -- 订阅服务初始化失败时不重置登录状态 -- 记录错误但不影响用户使用 - -### **4. 状态同步策略** -- 在UI渲染后检查状态一致性 -- 自动修正不一致的状态 - -## 🧪 测试建议 - -### **1. 基础功能测试** -- 正常启动测试:连续启动应用10次,观察登录框显示情况 -- 登录状态测试:验证已登录和未登录状态的正确显示 - -### **2. 异常情况测试** -- 网络异常测试:在网络不稳定环境下测试 -- 存储异常测试:模拟存储读取失败的情况 -- 内存压力测试:在低内存环境下测试 - -### **3. 边界情况测试** -- 快速重启测试:连续快速重启应用 -- 后台恢复测试:应用从后台恢复时的状态检查 - -## 📝 监控要点 - -### **1. 关键日志** -- `HomeController` 的登录状态初始化日志 -- `AppRunData` 的用户信息初始化日志 -- `SplashController` 的启动完成日志 - -### **2. 状态检查** -- 登录状态与UI状态的一致性 -- 订阅服务初始化的成功率 -- 应用启动的成功率 - -## 🔄 后续优化建议 - -### **1. 短期优化** -- 监控修复效果,收集用户反馈 -- 根据实际使用情况调整延迟时间 -- 优化错误处理逻辑 - -### **2. 长期优化** -- 考虑使用状态管理框架(如Riverpod)统一管理状态 -- 实现更完善的状态持久化机制 -- 添加应用健康检查机制 - -## ✅ 修复完成 - -所有修复已完成,包括: -- ✅ KRHomeController 登录状态初始化逻辑修复 -- ✅ 状态验证和错误处理添加 -- ✅ 状态同步检查机制添加 -- ✅ KRAppRunData 初始化逻辑优化 -- ✅ 启动页面保护机制添加 - -修复后的代码应该能显著减少 Android 应用启动时登录框不显示的问题。 diff --git a/ANDROID_LOGIN_PANEL_ISSUE_ANALYSIS.md b/ANDROID_LOGIN_PANEL_ISSUE_ANALYSIS.md deleted file mode 100755 index 4d9f968..0000000 --- a/ANDROID_LOGIN_PANEL_ISSUE_ANALYSIS.md +++ /dev/null @@ -1,241 +0,0 @@ -# Android 应用启动时登录框不显示问题分析 - -## 🔍 问题描述 - -**现象**:Android 应用退出重新打开后,有时会出现无法加载所有功能的情况,具体表现为进入首页后没有显示下面的登录框,需要退出重进多次才能恢复正常。 - -## 📋 代码逻辑分析 - -### **1. 应用启动流程** - -```dart -// main.dart -> splash -> main -main() -> KRAppRunData().kr_initializeUserInfo() -> Get.offAllNamed(Routes.KR_MAIN) -``` - -### **2. 登录状态初始化流程** - -#### **A. 启动时初始化 (KRAppRunData.kr_initializeUserInfo)** -```dart -Future kr_initializeUserInfo() async { - final String? userInfoString = await KRSecureStorage().kr_readData(key: _keyUserInfo); - - if (userInfoString != null) { - // 解析用户信息 - kr_token = userInfo['token']; - kr_account = userInfo['account']; - // ... - - kr_isLogin.value = kr_token != null; // ⚠️ 关键:设置登录状态 - if (kr_isLogin.value) { - await _iniUserInfo(); // 异步获取用户信息 - } - } -} -``` - -#### **B. 首页控制器初始化 (KRHomeController._kr_initLoginStatus)** -```dart -void _kr_initLoginStatus() { - if (KRAppRunData().kr_isLogin.value) { - kr_currentViewStatus.value = KRHomeViewsStatus.kr_loggedIn; - kr_subscribeService.kr_refreshAll(); // ⚠️ 异步刷新订阅数据 - } else { - kr_currentViewStatus.value = KRHomeViewsStatus.kr_notLoggedIn; - } - - ever(KRAppRunData().kr_isLogin, (isLoggedIn) { - // 监听登录状态变化 - }); -} -``` - -### **3. 登录框显示逻辑** - -#### **A. 首页视图判断 (KRHomeView.build)** -```dart -Widget build(BuildContext context) { - return Obx(() { - if (controller.kr_currentViewStatus.value == KRHomeViewsStatus.kr_notLoggedIn) { - return Scaffold( - body: Stack( - children: [ - const KRHomeMapView(), - Positioned( - bottom: 0, - child: Container( - child: const KRLoginView(), // ⚠️ 登录框在这里显示 - ), - ), - ], - ), - ); - } - // 已登录状态的其他UI... - }); -} -``` - -#### **B. 底部面板判断 (KRHomeBottomPanel._kr_buildDefaultView)** -```dart -Widget _kr_buildDefaultView(BuildContext context) { - final isNotLoggedIn = controller.kr_currentViewStatus.value == KRHomeViewsStatus.kr_notLoggedIn; - - if (isNotLoggedIn) { - return SingleChildScrollView( - child: Column( - children: [ - const KRHomeConnectionOptionsView(), // ⚠️ 登录选项在这里显示 - ], - ), - ); - } - // 已登录状态的其他内容... -} -``` - -## 🚨 问题根因分析 - -### **1. 竞态条件 (Race Condition)** - -**问题**:`kr_initializeUserInfo()` 中的异步操作可能导致状态不一致 - -```dart -// 问题代码 -kr_isLogin.value = kr_token != null; // 立即设置状态 -if (kr_isLogin.value) { - await _iniUserInfo(); // 异步操作,可能失败 -} -``` - -**风险**: -- 如果 `_iniUserInfo()` 失败,登录状态可能不正确 -- 网络请求超时或失败时,状态可能不一致 - -### **2. 异步初始化时序问题** - -**问题**:多个异步操作没有正确的依赖关系 - -```dart -// 启动流程 -await KRAppRunData.getInstance().kr_initializeUserInfo(); // 异步1 -Get.offAllNamed(Routes.KR_MAIN); // 立即跳转 - -// 首页初始化 -_kr_initLoginStatus(); // 可能此时 kr_isLogin 还未正确设置 -``` - -### **3. 状态监听器初始化时机** - -**问题**:`ever()` 监听器可能在状态变化后才注册 - -```dart -// 可能的问题 -kr_isLogin.value = true; // 状态已变化 -ever(KRAppRunData().kr_isLogin, (isLoggedIn) { // 监听器注册太晚 - // 这个回调可能不会立即触发 -}); -``` - -### **4. 订阅服务初始化失败** - -**问题**:`kr_subscribeService.kr_refreshAll()` 可能失败 - -```dart -if (KRAppRunData().kr_isLogin.value) { - kr_currentViewStatus.value = KRHomeViewsStatus.kr_loggedIn; - kr_subscribeService.kr_refreshAll(); // 如果这个失败,UI状态可能不正确 -} -``` - -## 🔧 潜在修复方案 - -### **1. 添加状态初始化延迟** - -```dart -void _kr_initLoginStatus() { - // 延迟初始化,确保所有异步操作完成 - Future.delayed(const Duration(milliseconds: 100), () { - if (KRAppRunData().kr_isLogin.value) { - kr_currentViewStatus.value = KRHomeViewsStatus.kr_loggedIn; - } else { - kr_currentViewStatus.value = KRHomeViewsStatus.kr_notLoggedIn; - } - }); -} -``` - -### **2. 添加状态验证** - -```dart -void _kr_initLoginStatus() { - // 验证登录状态的有效性 - final isValidLogin = KRAppRunData().kr_token != null && - KRAppRunData().kr_isLogin.value; - - if (isValidLogin) { - kr_currentViewStatus.value = KRHomeViewsStatus.kr_loggedIn; - } else { - kr_currentViewStatus.value = KRHomeViewsStatus.kr_notLoggedIn; - } -} -``` - -### **3. 添加错误处理和重试机制** - -```dart -void _kr_initLoginStatus() { - try { - if (KRAppRunData().kr_isLogin.value) { - kr_currentViewStatus.value = KRHomeViewsStatus.kr_loggedIn; - // 添加错误处理 - kr_subscribeService.kr_refreshAll().catchError((error) { - KRLogUtil.kr_e('订阅服务初始化失败: $error', tag: 'HomeController'); - // 重试或降级处理 - }); - } else { - kr_currentViewStatus.value = KRHomeViewsStatus.kr_notLoggedIn; - } - } catch (e) { - KRLogUtil.kr_e('登录状态初始化失败: $e', tag: 'HomeController'); - kr_currentViewStatus.value = KRHomeViewsStatus.kr_notLoggedIn; - } -} -``` - -### **4. 添加状态同步检查** - -```dart -void _kr_initLoginStatus() { - // 强制同步状态 - WidgetsBinding.instance.addPostFrameCallback((_) { - final currentLoginStatus = KRAppRunData().kr_isLogin.value; - if (kr_currentViewStatus.value == KRHomeViewsStatus.kr_loggedIn && !currentLoginStatus) { - kr_currentViewStatus.value = KRHomeViewsStatus.kr_notLoggedIn; - } else if (kr_currentViewStatus.value == KRHomeViewsStatus.kr_notLoggedIn && currentLoginStatus) { - kr_currentViewStatus.value = KRHomeViewsStatus.kr_loggedIn; - } - }); -} -``` - -## 📊 问题影响 - -1. **用户体验差**:需要多次重启应用才能正常使用 -2. **功能不可用**:登录框不显示导致无法登录 -3. **状态不一致**:UI状态与实际登录状态不匹配 - -## 🎯 建议修复优先级 - -1. **高优先级**:添加状态初始化延迟和验证 -2. **中优先级**:添加错误处理和重试机制 -3. **低优先级**:优化异步操作时序 - -## 📝 测试建议 - -1. **多次重启测试**:连续重启应用 10-20 次,观察登录框显示情况 -2. **网络异常测试**:在网络不稳定环境下测试 -3. **存储异常测试**:模拟存储读取失败的情况 -4. **内存压力测试**:在低内存环境下测试 - -这个分析为后续的修复提供了明确的方向和具体的实现建议。 diff --git a/CONNECTION_DEBUG_SUMMARY.md b/CONNECTION_DEBUG_SUMMARY.md deleted file mode 100755 index 394880f..0000000 --- a/CONNECTION_DEBUG_SUMMARY.md +++ /dev/null @@ -1,87 +0,0 @@ -# BearVPN 连接调试总结 - -## 🔍 问题分析 - -通过日志分析,发现了节点连接超时的根本原因: - -### 核心问题 -1. **SingBox URL 测试配置问题**: - - 测试间隔过长:`url-test-interval: 300` (5分钟) - - 测试 URL 可能不稳定:`http://cp.cloudflare.com` - -2. **节点延迟值异常**: - - 初始状态:`delay=0` (未测试) - - 测试后:`delay=65535` (超时/失败) - - 反复在 0 和 65535 之间切换 - -## 🛠️ 解决方案 - -### 1. 修复 SingBox 配置 -```dart -// 修改前 -"connection-test-url": "http://cp.cloudflare.com", -"url-test-interval": 300, - -// 修改后 -"connection-test-url": "http://www.gstatic.com/generate_204", -"url-test-interval": 30, -``` - -### 2. 添加详细调试信息 -- ✅ SingBox 启动过程调试 -- ✅ 配置文件保存调试 -- ✅ 节点选择过程调试 -- ✅ URL 测试过程调试 -- ✅ 活动组状态监控 - -### 3. 优化节点延迟测试 -- ✅ 增加详细的连接测试日志 -- ✅ 改进错误处理和重试机制 -- ✅ 添加测试前后状态对比 - -## 📊 测试结果 - -### URL 连通性测试 -- ✅ `http://www.gstatic.com/generate_204` - 连接正常 -- ✅ `http://cp.cloudflare.com` - 连接正常 -- ❌ `http://www.cloudflare.com` - 连接失败 - -### 预期效果 -1. **更快的节点测试**:从 5 分钟间隔改为 30 秒 -2. **更稳定的测试 URL**:使用 Google 的连通性测试服务 -3. **更详细的调试信息**:便于问题定位和解决 - -## 🚀 下一步 - -1. **重新运行应用**:测试修复后的效果 -2. **观察日志**:查看新的调试信息 -3. **验证节点延迟**:确认延迟值是否正常更新 -4. **测试连接稳定性**:验证连接是否稳定 - -## 📝 调试命令 - -```bash -# 运行应用并查看日志 -flutter run -d macos --debug - -# 测试 URL 连通性 -./test_url_connectivity.sh - -# 基础连接测试 -./test_connection.sh -``` - -## 🔧 关键文件修改 - -1. `lib/app/services/singbox_imp/kr_sing_box_imp.dart` - - 修复 URL 测试配置 - - 添加详细调试信息 - - 优化错误处理 - -2. `lib/app/modules/kr_home/controllers/kr_home_controller.dart` - - 增强节点延迟测试日志 - - 改进错误处理机制 - -3. 新增调试脚本 - - `test_connection.sh` - 基础连接测试 - - `test_url_connectivity.sh` - URL 连通性测试 diff --git a/CONNECTION_INFO_DISAPPEAR_ANALYSIS.md b/CONNECTION_INFO_DISAPPEAR_ANALYSIS.md deleted file mode 100755 index 8f6a474..0000000 --- a/CONNECTION_INFO_DISAPPEAR_ANALYSIS.md +++ /dev/null @@ -1,202 +0,0 @@ -# 连接信息消失问题分析 - -## 🔍 问题描述 - -用户反馈:在什么情况下,把app关掉后重新打开,下面的"当前连接"和"连接方式"都不显示了。 - -## 📋 显示逻辑分析 - -### **1. 当前连接显示条件** - -#### **显示位置**: `kr_home_bottom_panel.dart` 第94-97行 -```dart -// 1. 如果已订阅,展示当前连接卡片 -if (hasValidSubscription) - Container( - margin: EdgeInsets.only(top: 12.h), - child: const KRHomeConnectionInfoView()) -``` - -#### **显示条件**: `hasValidSubscription` -```dart -final hasValidSubscription = - controller.kr_subscribeService.kr_currentSubscribe.value != null; -``` - -### **2. 连接方式显示条件** - -#### **显示位置**: `kr_home_bottom_panel.dart` 第118-123行 -```dart -// 4. 连接选项(分组和国家入口) -Padding( - padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.w), - child: const KRHomeConnectionOptionsView(), -), -``` - -#### **显示条件**: 始终显示(在已登录状态下) - -### **3. 登录状态判断** - -#### **显示逻辑**: `kr_home_bottom_panel.dart` 第72-85行 -```dart -if (isNotLoggedIn) - // 未登录状态下,只显示连接选项 - SingleChildScrollView( - child: Column( - children: [ - Padding( - padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.w), - child: const KRHomeConnectionOptionsView(), - ), - ], - ), - ) -else - // 已登录状态下,显示完整内容 - Expanded( - child: SingleChildScrollView( - child: Column( - children: [ - // 当前连接卡片(需要hasValidSubscription) - // 连接选项 - ], - ), - ), - ) -``` - -## 🎯 问题根源分析 - -### **核心问题**: `kr_currentSubscribe.value` 为 `null` - -当 `kr_currentSubscribe.value` 为 `null` 时: -1. **当前连接卡片不显示**: `hasValidSubscription = false` -2. **连接方式可能不显示**: 取决于登录状态 - -### **可能导致 `kr_currentSubscribe.value` 为 `null` 的情况**: - -#### **1. 订阅服务初始化失败** -- **网络问题**: API请求失败 -- **服务器问题**: 后端服务异常 -- **超时问题**: 请求超时 - -#### **2. 订阅数据获取失败** -- **API返回空列表**: `subscribes.isEmpty` -- **订阅过期**: 所有订阅都已过期 -- **权限问题**: 用户没有可用订阅 - -#### **3. 应用启动时序问题** -- **竞态条件**: 订阅服务初始化晚于UI渲染 -- **状态同步问题**: 登录状态和订阅状态不同步 -- **缓存问题**: 本地缓存数据损坏 - -#### **4. 登录状态问题** -- **Token失效**: 用户token过期或无效 -- **登录状态丢失**: `kr_isLogin.value = false` -- **用户信息加载失败**: 用户信息初始化失败 - -## 🔧 具体场景分析 - -### **场景1: 网络问题** -``` -启动应用 → 登录成功 → 订阅服务初始化 → 网络请求失败 → kr_currentSubscribe.value = null → 当前连接不显示 -``` - -### **场景2: 订阅过期** -``` -启动应用 → 登录成功 → 订阅服务初始化 → 获取订阅列表 → 所有订阅已过期 → kr_currentSubscribe.value = null → 当前连接不显示 -``` - -### **场景3: 竞态条件** -``` -启动应用 → UI渲染 → 订阅服务还在初始化中 → kr_currentSubscribe.value = null → 当前连接不显示 -``` - -### **场景4: 登录状态问题** -``` -启动应用 → 登录状态判断错误 → 显示未登录界面 → 连接方式显示但当前连接不显示 -``` - -## 📊 调试方法 - -### **1. 检查关键状态** -```dart -// 在 kr_home_bottom_panel.dart 中添加日志 -KRLogUtil.kr_i('当前登录状态: ${controller.kr_currentViewStatus.value}', tag: 'HomeBottomPanel'); -KRLogUtil.kr_i('当前订阅: ${controller.kr_subscribeService.kr_currentSubscribe.value}', tag: 'HomeBottomPanel'); -KRLogUtil.kr_i('订阅服务状态: ${controller.kr_subscribeService.kr_currentStatus.value}', tag: 'HomeBottomPanel'); -``` - -### **2. 检查订阅服务初始化** -```dart -// 在 kr_subscribe_service.dart 中添加日志 -KRLogUtil.kr_i('订阅服务初始化开始', tag: 'SubscribeService'); -KRLogUtil.kr_i('获取订阅列表结果: ${subscribes.length} 个订阅', tag: 'SubscribeService'); -KRLogUtil.kr_i('当前订阅设置: ${kr_currentSubscribe.value?.name}', tag: 'SubscribeService'); -``` - -### **3. 检查网络请求** -```dart -// 检查API请求是否成功 -KRLogUtil.kr_i('API请求状态: ${result.isLeft() ? "失败" : "成功"}', tag: 'SubscribeService'); -``` - -## 🛠️ 修复建议 - -### **1. 增强错误处理** -```dart -// 在订阅服务初始化失败时,显示错误信息而不是空白 -if (kr_currentStatus.value == KRSubscribeServiceStatus.kr_error) { - return _kr_buildErrorView(context); -} -``` - -### **2. 添加重试机制** -```dart -// 订阅服务初始化失败时自动重试 -if (kr_currentSubscribe.value == null && kr_currentStatus.value == KRSubscribeServiceStatus.kr_error) { - // 延迟重试 - Future.delayed(Duration(seconds: 3), () { - kr_refreshAll(); - }); -} -``` - -### **3. 改善用户体验** -```dart -// 显示加载状态而不是空白 -if (kr_currentSubscribe.value == null && kr_currentStatus.value == KRSubscribeServiceStatus.kr_loading) { - return _kr_buildLoadingView(); -} -``` - -### **4. 添加状态检查** -```dart -// 定期检查订阅状态 -Timer.periodic(Duration(seconds: 30), (timer) { - if (kr_currentSubscribe.value == null && kr_isLogin.value) { - kr_refreshAll(); - } -}); -``` - -## 📝 总结 - -**问题根源**: `kr_currentSubscribe.value` 为 `null`,导致 `hasValidSubscription = false` - -**主要原因**: -1. 订阅服务初始化失败 -2. 网络请求失败 -3. 订阅数据获取失败 -4. 应用启动时序问题 -5. 登录状态问题 - -**解决方案**: -1. 增强错误处理和重试机制 -2. 改善用户体验(显示加载状态) -3. 添加状态检查和自动恢复 -4. 完善日志记录便于调试 - -**建议**: 先添加详细的日志记录,确定具体是哪种情况导致的问题,然后针对性地修复。 - diff --git a/CONNECTION_REFUSED_ISSUE_ANALYSIS.md b/CONNECTION_REFUSED_ISSUE_ANALYSIS.md deleted file mode 100755 index 0d9b4e6..0000000 --- a/CONNECTION_REFUSED_ISSUE_ANALYSIS.md +++ /dev/null @@ -1,122 +0,0 @@ -# Connection Refused 问题分析和修复 - -## 🔍 问题现象 - -从日志中可以看到所有节点都出现 "Connection refused" 错误: - -``` -❌ 本机网络测试节点 德国 失败: SocketException: Connection refused (OS Error: Connection refused, errno = 111), address = 156.226.175.116, port = 51036 -❌ 本机网络测试节点 美国 失败: SocketException: Connection refused (OS Error: Connection refused, errno = 111), address = 154.29.154.241, port = 59118 -❌ 本机网络测试节点 英国 失败: SocketException: Connection refused (OS Error: Connection refused, errno = 111), address = 89.213.40.159, port = 45268 -❌ 本机网络测试节点 台湾 失败: SocketException: Connection refused (OS Error: Connection refused, errno = 111), address = 83.147.12.27, port = 49826 -❌ 本机网络测试节点 香港 失败: SocketException: Connection refused (OS Error: Connection refused, errno = 111), address = 156.224.78.176, port = 44782 -``` - -## 🎯 问题分析 - -### **1. 地址解析问题** - -#### **问题现象**: -- 所有节点的端口都是随机的大数字(如 51036, 59118, 45268 等) -- 这些端口看起来不像是正常的代理服务端口 - -#### **根本原因**: -- 原来的代码使用 `Uri.parse(item.serverAddr)` 来解析地址和端口 -- 但是 `serverAddr` 可能不包含端口信息,或者解析逻辑有问题 -- 端口应该从节点的配置中获取,而不是从 `serverAddr` 中解析 - -### **2. 配置获取问题** - -#### **问题现象**: -- 没有从节点的配置中获取正确的端口号 -- 使用了错误的默认端口或解析出的错误端口 - -#### **根本原因**: -- 节点的端口信息存储在 `item.config['server_port']` 中 -- 原来的代码没有正确获取这个配置 - -## 🔧 修复方案 - -### **修复内容**: - -1. **改进地址解析逻辑**: - ```dart - // 从配置中获取正确的地址和端口 - String address = item.serverAddr; - int port = 443; // 默认端口 - - // 如果serverAddr包含端口,先解析 - if (item.serverAddr.contains(':')) { - final parts = item.serverAddr.split(':'); - if (parts.length == 2) { - address = parts[0]; - port = int.tryParse(parts[1]) ?? 443; - } - } - - // 从配置中获取端口(优先级更高) - if (item.config != null && item.config['server_port'] != null) { - port = item.config['server_port']; - KRLogUtil.kr_i('📌 从配置获取端口: $port', tag: 'NodeTest'); - } - ``` - -2. **增加详细日志**: - ```dart - KRLogUtil.kr_i('📋 节点配置: ${item.config}', tag: 'NodeTest'); - KRLogUtil.kr_i('📍 最终地址: $address, 端口: $port', tag: 'NodeTest'); - ``` - -### **修复逻辑**: - -1. **地址处理**: - - 首先使用 `item.serverAddr` 作为地址 - - 如果包含端口,则分离地址和端口 - - 否则使用默认端口 443 - -2. **端口获取**: - - 优先从 `item.config['server_port']` 获取端口 - - 如果配置中没有端口,使用解析出的端口或默认端口 - -3. **日志记录**: - - 记录节点配置信息 - - 记录最终使用的地址和端口 - - 便于调试和问题排查 - -## 📊 预期效果 - -### **修复前**: -- 使用错误的端口(如 51036, 59118 等) -- 所有节点连接被拒绝 -- 无法获取真实的延迟信息 - -### **修复后**: -- 使用正确的端口(从配置中获取) -- 能够成功连接到节点 -- 获取真实的网络延迟 - -## 🔍 验证方法 - -### **1. 检查日志**: -- 查看 `📋 节点配置:` 日志,确认配置信息 -- 查看 `📌 从配置获取端口:` 日志,确认端口获取 -- 查看 `📍 最终地址:` 日志,确认最终使用的地址和端口 - -### **2. 测试连接**: -- 确认不再出现 "Connection refused" 错误 -- 能够获取到合理的延迟值(通常 < 5000ms) -- 部分节点可能仍然超时,但应该有一些节点能够连接成功 - -### **3. 端口验证**: -- 确认使用的端口是合理的(如 443, 80, 8080 等) -- 不再使用随机的大数字端口 - -## 📝 总结 - -**问题根源**: 地址和端口解析逻辑错误,没有从节点配置中获取正确的端口信息。 - -**修复方案**: 改进地址解析逻辑,优先从节点配置中获取端口,并增加详细的日志记录。 - -**预期结果**: 能够使用正确的地址和端口连接节点,获取真实的网络延迟信息。 - -现在可以重新测试,应该能够看到正确的端口和成功的连接! diff --git a/CRISP_CHAT_FIX_SUMMARY.md b/CRISP_CHAT_FIX_SUMMARY.md deleted file mode 100644 index 589d26d..0000000 --- a/CRISP_CHAT_FIX_SUMMARY.md +++ /dev/null @@ -1,184 +0,0 @@ -# Crisp Chat 功能修复总结(支持多平台) - -## 问题描述 -Crisp 客服聊天功能无法使用,原因是: -1. `crisp_sdk` 包被注释掉(依赖 `flutter_inappwebview` 有问题) -2. 所有 Crisp 相关代码被注释 -3. 用户界面显示"客服功能暂时不可用" -4. `crisp_chat` 包只支持 iOS/Android,不支持桌面平台 - -## 解决方案 - -### 1. 依赖更新 -**文件**: `pubspec.yaml` - -- 移除了有问题的 `crisp_sdk` 包 -- 添加了 `crisp_chat: ^2.4.1`(使用原生实现,不依赖 `flutter_inappwebview`) - -```yaml -crisp_chat: ^2.4.1 # 使用原生实现的 crisp_chat,不依赖 flutter_inappwebview -``` - -### 2. 控制器重写(支持多平台) -**文件**: `lib/app/modules/kr_crisp_chat/controllers/kr_crisp_controller.dart` - -- 完全重写了控制器以支持多平台 -- **移动平台(iOS/Android)**: - - 使用 `crisp_chat` 包的原生 API - - 使用 `CrispConfig` 配置 Crisp - - 使用 `FlutterCrispChat.openCrispChat()` 打开聊天窗口 - - 使用 `FlutterCrispChat.setSessionString()` 设置会话数据 -- **桌面平台(macOS/Windows/Linux)**: - - 使用 WebView 加载 Crisp 官方嵌入脚本 - - 动态生成包含 Crisp SDK 的 HTML 页面 - - 通过 JavaScript 设置用户信息和会话数据 - - 自动打开聊天窗口 - -**主要改进**: -- ✅ 支持所有平台(iOS、Android、macOS、Windows、Linux) -- ✅ 自动检测平台并选择合适的实现方式 -- ✅ 支持用户邮箱和昵称设置 -- ✅ 自动收集平台信息 -- ✅ 设置语言、应用版本、设备 ID 等会话数据 - -### 3. 视图重写(多平台支持) -**文件**: `lib/app/modules/kr_crisp_chat/views/kr_crisp_view.dart` - -- 移除了占位视图 -- **移动平台**: 初始化成功后自动打开 Crisp 原生聊天窗口,窗口关闭后返回 -- **桌面平台**: 使用 `webview_flutter` 在应用内显示 Crisp 聊天界面 -- 添加了错误处理和重试功能 -- 使用 `PopScope` 替代已弃用的 `WillPopScope` -- 移除了 `setBackgroundColor` 调用(macOS 不支持) - -### 4. iOS 配置更新 -**文件**: `ios/Runner/Info.plist` - -添加了 Crisp 所需的权限: -```xml -NSCameraUsageDescription -需要相机权限以支持拍照功能 -NSMicrophoneUsageDescription -需要麦克风权限以支持语音消息功能 -NSPhotoLibraryUsageDescription -需要相册权限以支持图片上传功能 -NSPhotoLibraryAddUsageDescription -需要相册添加权限以保存图片 -``` - -### 5. Android 配置 -**文件**: `android/app/build.gradle` - -- ✅ `compileSdk 36` - 已满足要求(需要 35 或更高) -- ✅ 网络权限已在 `AndroidManifest.xml` 中配置 - -## 技术细节 - -### crisp_chat vs crisp_sdk -| 特性 | crisp_chat | crisp_sdk | -|------|-----------|-----------| -| 实现方式 | 原生 SDK | WebView | -| 依赖 | 无额外依赖 | 需要 flutter_inappwebview | -| 性能 | 更好 | 较慢 | -| 兼容性 | 更好 | 依赖问题 | -| 最新版本 | 2.4.1 (2025) | 1.1.0 (2024) | - -### API 使用示例 - -```dart -// 创建配置 -final config = CrispConfig( - websiteID: 'your-website-id', - enableNotifications: true, - user: User( - email: 'user@example.com', - nickName: 'User Name', - ), -); - -// 打开聊天窗口 -await FlutterCrispChat.openCrispChat(config: config); - -// 设置会话数据 -FlutterCrispChat.setSessionString(key: 'platform', value: 'android'); - -// 重置会话 -await FlutterCrispChat.resetCrispChatSession(); -``` - -## 工作流程 - -1. 用户点击客服按钮 -2. 进入 `KRCrispView` 页面 -3. `KRCrispController` 初始化: - - 获取用户信息(邮箱/设备ID) - - 创建 `CrispConfig` - - 设置会话数据 -4. 初始化完成后自动调用 `openCrispChat()` -5. 显示原生 Crisp 聊天界面 -6. 用户关闭聊天后,自动返回上一页 - -## 测试建议 - -### 前置条件 -1. 确保 `AppConfig.kr_website_id` 配置了有效的 Crisp Website ID -2. 在 Crisp 控制台配置网站设置 - -### 测试步骤 -1. **基础功能测试** - - 打开应用 - - 进入"我的"页面 - - 点击"客服"按钮 - - 验证 Crisp 聊天窗口是否正确打开 - -2. **用户信息测试** - - 登录用户状态下,验证用户邮箱是否正确传递 - - 未登录状态下,验证设备 ID 是否正确使用 - -3. **会话数据测试** - - 在 Crisp 控制台查看会话数据 - - 验证平台、语言、设备 ID 等信息是否正确 - -4. **权限测试 (iOS)** - - 测试相机权限提示 - - 测试麦克风权限提示 - - 测试相册权限提示 - -5. **跨平台测试** - - Android 设备测试 - - iOS 设备测试 - - Windows/macOS 桌面测试(如果支持) - -## 注意事项 - -1. **Website ID 配置** - - 确保在 `AppConfig` 中配置了正确的 Crisp Website ID - - 可以从 Crisp 控制台获取:Settings → Website Settings → Website ID - -2. **推送通知** - - 如需启用推送通知,需要额外配置 Firebase - - 参考 `crisp_chat` 包文档进行配置 - -3. **语言支持** - - Crisp 支持多语言 - - 当前实现会根据应用语言自动设置(zh、zh-tw、en 等) - -4. **隐私合规** - - 确保在隐私政策中说明使用 Crisp 客服系统 - - 告知用户会话数据的收集和使用 - -## 相关文件 - -- `pubspec.yaml` - 依赖配置 -- `lib/app/modules/kr_crisp_chat/controllers/kr_crisp_controller.dart` - 控制器 -- `lib/app/modules/kr_crisp_chat/views/kr_crisp_view.dart` - 视图 -- `lib/app/modules/kr_crisp_chat/bindings/kr_crisp_binding.dart` - 绑定 -- `ios/Runner/Info.plist` - iOS 权限配置 -- `android/app/build.gradle` - Android 编译配置 - -## 参考链接 - -- [crisp_chat 包文档](https://pub.dev/packages/crisp_chat) -- [Crisp 官方文档](https://docs.crisp.chat/) -- [Crisp iOS SDK](https://github.com/crisp-im/crisp-sdk-ios) -- [Crisp Android SDK](https://github.com/crisp-im/crisp-sdk-android) diff --git a/CRISP_MULTI_LANGUAGE_SUPPORT.md b/CRISP_MULTI_LANGUAGE_SUPPORT.md deleted file mode 100644 index 4ba5af6..0000000 --- a/CRISP_MULTI_LANGUAGE_SUPPORT.md +++ /dev/null @@ -1,190 +0,0 @@ -# Crisp 多语言支持说明 - -## 🌍 自动语言适配 - -Crisp 客服聊天**会自动跟随应用的当前语言设置**显示对应的界面! - -## 支持的语言 - -应用支持 7 种语言,Crisp 会自动切换到对应的界面语言: - -| 应用语言 | Crisp 显示语言 | 语言代码 | -|---------|--------------|---------| -| 🇬🇧 English | English | `en` | -| 🇨🇳 中文 | 简体中文 | `zh` | -| 🇹🇼 繁體中文 | 繁体中文 | `zh-tw` | -| 🇪🇸 Español | Español | `es` | -| 🇯🇵 日本語 | 日本語 | `ja` | -| 🇷🇺 Русский | Русский | `ru` | -| 🇪🇪 Eesti | Eesti keel | `et` | - -## 工作原理 - -### 1. 获取当前语言 -```dart -final currentLanguage = KRLanguageUtils.getCurrentLanguageCode(); -``` - -### 2. 映射到 Crisp Locale -```dart -String _getLocaleForCrisp(String languageCode) { - switch (languageCode) { - case 'zh_CN': - case 'zh': - return 'zh'; // 简体中文 - case 'zh_TW': - case 'zhHant': - return 'zh-tw'; // 繁体中文 - case 'es': - return 'es'; // 西班牙语 - case 'ja': - return 'ja'; // 日语 - case 'ru': - return 'ru'; // 俄语 - case 'et': - return 'et'; // 爱沙尼亚语 - case 'en': - default: - return 'en'; // 英语(默认) - } -} -``` - -### 3. 初始化 Crisp -```dart -crispController = CrispController( - websiteId: AppConfig.getInstance().kr_website_id, - locale: locale, // 自动设置的语言 -); -``` - -## 用户体验 - -1. **打开应用** → 应用读取系统语言或用户设置的语言 -2. **进入"我的"页面** -3. **点击"客服"按钮** -4. **Crisp 自动以当前应用语言显示界面** ✨ - -### 示例流程 - -``` -用户系统语言: 简体中文 - ↓ -应用启动,检测语言: zh_CN - ↓ -用户点击"客服" - ↓ -Crisp 初始化,locale: 'zh' - ↓ -显示简体中文界面 🇨🇳 -``` - -如果用户在应用内切换语言: -``` -应用设置页面 → 切换语言到 "日本語" - ↓ -应用重新加载,语言: ja - ↓ -再次点击"客服" - ↓ -Crisp 显示日语界面 🇯🇵 -``` - -## 语言切换 - -用户可以在应用的"设置"页面切换语言: -1. 进入"我的" → "语言切换" -2. 选择想要的语言 -3. 应用界面立即切换 -4. **下次打开客服,Crisp 也会自动切换到新语言** - -## 技术细节 - -### 代码位置 -- **控制器**: `lib/app/modules/kr_crisp_chat/controllers/kr_crisp_controller.dart` -- **语言工具**: `lib/app/localization/kr_language_utils.dart` - -### 关键方法 -```dart -// 在控制器初始化时调用 -Future kr_initializeCrisp() async { - final currentLanguage = KRLanguageUtils.getCurrentLanguageCode(); - String locale = _getLocaleForCrisp(currentLanguage); - - crispController = CrispController( - websiteId: AppConfig.getInstance().kr_website_id, - locale: locale, - ); -} -``` - -## 扩展支持 - -如果需要添加新语言支持: - -1. **在应用中添加新语言**(`kr_language_utils.dart`) -2. **在 Crisp 控制器中添加映射**(`_getLocaleForCrisp` 方法) -3. **确保 Crisp 支持该语言**(查看 [Crisp 支持的语言列表](https://docs.crisp.chat/guides/chatbox/languages/)) - -### 添加新语言示例 - -假设要添加法语支持: - -```dart -// 1. 在 KRLanguage enum 中添加 -fr('🇫🇷', 'Français', 'fr') - -// 2. 在 _getLocaleForCrisp 中添加映射 -case 'fr': - return 'fr'; // 法语 -``` - -## 注意事项 - -1. **系统语言优先**: 应用会优先使用用户在应用内设置的语言,如果没有设置,则使用系统语言 -2. **默认语言**: 如果检测到不支持的语言,默认使用英语(`en`) -3. **实时生效**: 语言切换后,下次打开 Crisp 客服即可看到新语言界面 -4. **无需重启**: 切换语言不需要重启应用 - -## 验证方法 - -### 测试步骤 -1. 打开应用 -2. 进入"我的" → "语言切换" -3. 依次选择不同语言 -4. 每次选择后,点击"客服"按钮 -5. 验证 Crisp 界面语言是否正确切换 - -### 预期结果 -- ✅ 界面文字使用选定的语言 -- ✅ 输入框提示文字使用对应语言 -- ✅ 系统消息使用对应语言 -- ✅ 按钮文字使用对应语言 - -## 常见问题 - -### Q: 为什么我切换了语言,Crisp 还是英文? -A: 请确保: -1. 已关闭之前的 Crisp 窗口 -2. 重新点击"客服"按钮 -3. Crisp 会使用新的语言初始化 - -### Q: Crisp 支持哪些语言? -A: Crisp 官方支持 30+ 种语言,包括所有主流语言。查看完整列表:https://docs.crisp.chat/guides/chatbox/languages/ - -### Q: 可以强制使用某个语言吗? -A: 当前实现会自动跟随应用语言。如需强制使用某个语言,可以在初始化时硬编码 locale: -```dart -crispController = CrispController( - websiteId: AppConfig.getInstance().kr_website_id, - locale: 'zh', // 强制使用简体中文 -); -``` - -## 总结 - -✅ **自动化**: Crisp 完全自动跟随应用语言 -✅ **全面支持**: 支持应用所有 7 种语言 -✅ **用户友好**: 无需用户手动设置 -✅ **实时切换**: 切换语言后立即生效 -✅ **可扩展**: 易于添加新语言支持 diff --git a/INSTALLATION_GUIDE.md b/INSTALLATION_GUIDE.md deleted file mode 100644 index f518f30..0000000 --- a/INSTALLATION_GUIDE.md +++ /dev/null @@ -1,62 +0,0 @@ -# BearVPN macOS 安装指南 - -## 🚨 如果遇到"应用程序无法打开"的问题 - -### 问题原因 -macOS 的安全机制(Gatekeeper)可能会阻止未签名的应用运行。 - -### 解决方案 - -#### 方法 1:右键打开(推荐) -1. 右键点击 `BearVPN.app` -2. 选择"打开" -3. 在弹出的对话框中点击"打开" - -#### 方法 2:系统偏好设置 -1. 打开"系统偏好设置" > "安全性与隐私" -2. 在"通用"标签页中,找到被阻止的应用 -3. 点击"仍要打开" - -#### 方法 3:终端命令(高级用户) -```bash -# 移除隔离属性 -sudo xattr -rd com.apple.quarantine /Applications/BearVPN.app - -# 或者完全禁用 Gatekeeper(不推荐) -sudo spctl --master-disable -``` - -### 验证应用完整性 -```bash -# 检查签名状态 -codesign -dv --verbose=4 /Applications/BearVPN.app - -# 验证签名 -codesign --verify --verbose /Applications/BearVPN.app -``` - -## 📋 系统要求 -- macOS 10.15 或更高版本 -- 支持 Intel 和 Apple Silicon (M1/M2) 芯片 -- 至少 200MB 可用磁盘空间 - -## 🔧 故障排除 - -### 如果应用仍然无法打开 -1. 确保 macOS 版本符合要求 -2. 检查系统时间是否正确 -3. 尝试重新下载应用 -4. 联系技术支持 - -### 性能优化 -1. 将应用添加到"登录项"以自动启动 -2. 在"系统偏好设置"中允许应用访问网络 -3. 确保防火墙没有阻止应用 - -## 📞 技术支持 -如果遇到问题,请联系: -- 邮箱:support@bearvpn.com -- 网站:https://bearvpn.com - ---- -**注意**:本应用已通过 Apple 开发者证书签名,确保安全性和完整性。 diff --git a/IOS_BUILD_README.md b/IOS_BUILD_README.md deleted file mode 100644 index 5d70ad1..0000000 --- a/IOS_BUILD_README.md +++ /dev/null @@ -1,183 +0,0 @@ -# iOS 自动化构建指南 - -本指南将帮助您使用自动化脚本构建和签名 iOS 应用,并创建 DMG 安装包。 - -## 🎯 目标 - -创建经过签名的 iOS 应用 DMG 文件,用于分发和安装。 - -## 📋 前提条件 - -### 1. Apple Developer 账户 -- 需要有效的 Apple Developer 账户 -- 需要 **iOS Development** 证书 -- 需要 **Provisioning Profile** - -### 2. 获取证书和配置文件 -1. 登录 [Apple Developer Portal](https://developer.apple.com) -2. 进入 "Certificates, Identifiers & Profiles" -3. 创建以下证书: - - **iOS Development** (用于应用签名) -4. 创建 App ID 和 Provisioning Profile -5. 下载并安装证书和配置文件 - -## 🚀 快速开始 - -### 步骤 1: 配置签名信息 - -```bash -# 运行配置脚本 -./update_team_id.sh -``` - -按照提示输入您的 Team ID,脚本会自动更新配置文件。 - -### 步骤 2: 加载配置 - -```bash -# 加载签名配置 -source ios_signing_config.sh -``` - -### 步骤 3: 构建 DMG - -```bash -# 构建发布版本 -./build_ios_dmg.sh - -# 或构建调试版本 -./build_ios_dmg.sh debug -``` - -## 📁 输出文件 - -构建完成后,文件将位于: -``` -build/ios/ -├── BearVPN-1.0.0.ipa # 签名的 IPA 文件 -└── BearVPN-1.0.0-iOS.dmg # DMG 安装包 -``` - -## 🛠️ 可用的构建脚本 - -### 1. `build_ios_dmg.sh` - 主要构建脚本 -- 构建签名的 iOS 应用 -- 创建 DMG 安装包 -- 支持调试和发布版本 - -```bash -./build_ios_dmg.sh [debug|release] -``` - -### 2. `build_ios_simple.sh` - 简化构建脚本 -- 构建未签名的版本 -- 仅用于测试和开发 - -```bash -./build_ios_simple.sh [debug|release] -``` - -### 3. `build_ios_appstore.sh` - App Store 构建脚本 -- 构建用于 App Store 分发的版本 -- 支持自动上传到 App Store Connect - -```bash -./build_ios_appstore.sh [upload|build] -``` - -## 🔧 配置文件 - -### `ios_signing_config.sh` -包含所有签名配置信息: - -```bash -# Apple Developer 账户信息 -export APPLE_ID="your-apple-id@example.com" -export APPLE_PASSWORD="your-app-password" -export TEAM_ID="YOUR_TEAM_ID" - -# 应用信息 -export APP_NAME="BearVPN" -export BUNDLE_ID="com.bearvpn.app" -export VERSION="1.0.0" -export BUILD_NUMBER="1" - -# 签名身份 -export SIGNING_IDENTITY="iPhone Developer: Your Name (YOUR_TEAM_ID)" -export DISTRIBUTION_IDENTITY="iPhone Distribution: Your Name (YOUR_TEAM_ID)" -``` - -## 🔍 验证构建结果 - -构建完成后,您可以验证结果: - -```bash -# 验证 IPA 文件 -unzip -l build/ios/BearVPN-1.0.0.ipa - -# 验证 DMG 文件 -hdiutil verify build/ios/BearVPN-1.0.0-iOS.dmg - -# 查看 DMG 内容 -hdiutil mount build/ios/BearVPN-1.0.0-iOS.dmg -``` - -## 🛠️ 故障排除 - -### 1. 证书问题 -```bash -# 查看可用证书 -security find-identity -v -p codesigning - -# 如果看到 "0 valid identities found",说明没有安装证书 -``` - -### 2. 配置文件问题 -- 确保 Provisioning Profile 已正确安装 -- 检查 Bundle ID 是否匹配 -- 确保证书和配置文件匹配 - -### 3. 构建失败 -- 检查 Xcode 是否正确安装 -- 确保 Flutter 环境正确配置 -- 查看构建日志中的具体错误信息 - -### 4. 签名失败 -- 确保证书已正确安装 -- 检查签名身份名称是否正确 -- 确保证书未过期 - -## 📚 相关文档 - -- [Apple 代码签名指南](https://developer.apple.com/documentation/security/notarizing_macos_software_before_distribution) -- [Flutter iOS 部署指南](https://docs.flutter.dev/deployment/ios) -- [Xcode 构建指南](https://developer.apple.com/documentation/xcode) - -## ⚠️ 重要提醒 - -1. **安全性**:请妥善保管您的开发者证书和密码 -2. **测试**:在分发前,请在真实的 iOS 设备上测试 -3. **更新**:定期更新证书,避免过期 -4. **备份**:建议备份您的签名配置 - -## 🎉 成功标志 - -如果构建成功,您应该看到: -- ✅ 应用构建成功 -- ✅ 应用签名成功 -- ✅ IPA 文件创建成功 -- ✅ DMG 文件创建成功 -- ✅ 最终验证通过 - -## 📞 支持 - -如果遇到问题,请检查: -1. 构建日志中的错误信息 -2. 证书和配置文件是否正确安装 -3. 网络连接是否正常 -4. Xcode 和 Flutter 版本是否兼容 - - - - - diff --git a/LATENCY_TEST_LOGIC_CONFIRMATION.md b/LATENCY_TEST_LOGIC_CONFIRMATION.md deleted file mode 100755 index d541c9d..0000000 --- a/LATENCY_TEST_LOGIC_CONFIRMATION.md +++ /dev/null @@ -1,176 +0,0 @@ -# 延迟测试逻辑确认 - -## 🎯 需求确认 - -**用户需求**: -- **连接代理时**: 保持默认测试规则(使用 SingBox 通过代理测试) -- **没连接时**: 使用本地网络的ping(直接连接节点IP) - -## 📋 当前实现逻辑 - -### **1. 连接状态判断** - -#### **连接状态变量**: `kr_isConnected` -```dart -// 是否已连接 -final kr_isConnected = false.obs; -``` - -#### **连接状态更新逻辑**: `_bindConnectionStatus()` -```dart -void _bindConnectionStatus() { - ever(KRSingBoxImp.instance.kr_status, (status) { - switch (status) { - case SingboxStopped(): - kr_isConnected.value = false; // 未连接 - break; - case SingboxStarting(): - kr_isConnected.value = true; // 连接中 - break; - case SingboxStarted(): - kr_isConnected.value = true; // 已连接 - break; - case SingboxStopping(): - kr_isConnected.value = false; // 断开中 - break; - } - }); -} -``` - -### **2. 延迟测试逻辑** - -#### **主测试方法**: `kr_urlTest()` -```dart -Future kr_urlTest() async { - KRLogUtil.kr_i('📊 当前连接状态: ${kr_isConnected.value}', tag: 'HomeController'); - - if (kr_isConnected.value) { - // ✅ 已连接状态:使用 SingBox 通过代理测试(默认测试规则) - KRLogUtil.kr_i('🔗 已连接状态 - 使用 SingBox 通过代理测试延迟', tag: 'HomeController'); - await KRSingBoxImp.instance.kr_urlTest("select"); - - // 等待 SingBox 完成测试 - await Future.delayed(const Duration(seconds: 3)); - - // 检查活动组状态 - final activeGroups = KRSingBoxImp.instance.kr_activeGroups; - // ... 处理测试结果 - } else { - // ✅ 未连接状态:使用本机网络直接ping节点IP - KRLogUtil.kr_i('🔌 未连接状态 - 使用本机网络直接ping节点IP测试延迟', tag: 'HomeController'); - KRLogUtil.kr_i('🌐 这将绕过代理,直接使用本机网络连接节点', tag: 'HomeController'); - await _kr_testLatencyWithoutVpn(); - } -} -``` - -### **3. 本机网络测试逻辑** - -#### **本机网络测试方法**: `_kr_testLatencyWithoutVpn()` -```dart -/// 未连接状态下的延迟测试(使用本机网络直接ping节点IP) -Future _kr_testLatencyWithoutVpn() async { - KRLogUtil.kr_i('🔌 开始未连接状态延迟测试(使用本机网络)', tag: 'HomeController'); - KRLogUtil.kr_i('🌐 将使用本机网络直接连接节点IP进行延迟测试', tag: 'HomeController'); - - // 获取所有非auto节点 - final testableNodes = kr_subscribeService.allList - .where((item) => item.tag != 'auto') - .toList(); - - // 并行执行所有测试任务 - final testTasks = testableNodes - .map((item) => _kr_testSingleNode(item)) - .toList(); - - await Future.wait(testTasks); - - // 统计和显示测试结果 - // ... -} -``` - -#### **单个节点测试方法**: `_kr_testSingleNode()` -```dart -/// 测试单个节点的延迟(使用本机网络直接ping节点IP) -Future _kr_testSingleNode(dynamic item) async { - KRLogUtil.kr_i('🔌 使用本机网络直接连接测试(绕过代理)', tag: 'NodeTest'); - - // 使用本机网络直接连接测试节点延迟 - final socket = await Socket.connect( - address, - port, - timeout: const Duration(seconds: 8), // 8秒超时 - ); - - // 获取延迟时间 - final delay = stopwatch.elapsedMilliseconds; - - // 设置延迟阈值:超过5秒认为节点不可用 - if (delay > 5000) { - item.urlTestDelay.value = 65535; // 标记为不可用 - } else { - item.urlTestDelay.value = delay; // 使用本机网络测试的延迟结果 - } -} -``` - -## ✅ 逻辑确认 - -### **连接代理时(kr_isConnected.value = true)**: -1. **使用默认测试规则**: 调用 `KRSingBoxImp.instance.kr_urlTest("select")` -2. **通过代理测试**: 使用 SingBox 的 URL 测试功能 -3. **等待测试完成**: 等待3秒让 SingBox 完成测试 -4. **获取测试结果**: 从 `KRSingBoxImp.instance.kr_activeGroups` 获取延迟信息 - -### **没连接时(kr_isConnected.value = false)**: -1. **使用本机网络**: 调用 `_kr_testLatencyWithoutVpn()` -2. **直接连接节点**: 使用 `Socket.connect()` 直接连接节点IP -3. **绕过代理**: 不经过任何代理,使用本机网络 -4. **并行测试**: 同时测试所有节点,提高效率 -5. **真实延迟**: 获得本机到节点的真实网络延迟 - -## 🔍 关键判断点 - -### **连接状态判断**: -```dart -if (kr_isConnected.value) { - // 连接代理时:使用 SingBox 默认测试规则 -} else { - // 没连接时:使用本机网络直接ping节点IP -} -``` - -### **连接状态来源**: -- `kr_isConnected` 的值来自 `KRSingBoxImp.instance.kr_status` -- 当 SingBox 状态为 `SingboxStarted()` 或 `SingboxStarting()` 时,`kr_isConnected = true` -- 当 SingBox 状态为 `SingboxStopped()` 或 `SingboxStopping()` 时,`kr_isConnected = false` - -## 📊 测试验证 - -### **测试场景1: 连接代理时** -- **预期行为**: 使用 SingBox 通过代理测试 -- **验证日志**: `🔗 已连接状态 - 使用 SingBox 通过代理测试延迟` -- **测试方式**: `KRSingBoxImp.instance.kr_urlTest("select")` - -### **测试场景2: 没连接时** -- **预期行为**: 使用本机网络直接ping节点IP -- **验证日志**: `🔌 未连接状态 - 使用本机网络直接ping节点IP测试延迟` -- **测试方式**: `Socket.connect()` 直接连接节点 - -## 📝 总结 - -**✅ 当前实现完全符合用户需求**: - -1. **连接代理时**: 保持默认测试规则,使用 SingBox 通过代理测试延迟 -2. **没连接时**: 使用本机网络直接ping节点IP,绕过代理获取真实延迟 - -**🔧 实现特点**: -- 自动根据连接状态选择测试方式 -- 连接时使用代理测试,未连接时使用直连测试 -- 详细的日志记录,便于调试和验证 -- 并行测试提高效率 -- 完善的错误处理和超时机制 - -**🎯 用户需求已完全实现!** diff --git a/LATENCY_TEST_OPTIMIZATION_SUMMARY.md b/LATENCY_TEST_OPTIMIZATION_SUMMARY.md deleted file mode 100755 index 6d25317..0000000 --- a/LATENCY_TEST_OPTIMIZATION_SUMMARY.md +++ /dev/null @@ -1,171 +0,0 @@ -# 延迟测试优化总结 - -## 🎯 优化目标 - -解决延迟测试的问题: -- **开启代理后**: 可以正常获取节点的延迟信息 -- **不开启代理时**: 无法获取节点延迟,因为网络请求被代理拦截 - -**解决方案**: 在不开启代理时,使用本机网络直接ping节点IP来获取延迟信息。 - -## 🔧 优化内容 - -### **1. 优化延迟测试主逻辑** - -#### **修改位置**: `kr_urlTest()` 方法 - -#### **优化内容**: -- **明确区分测试方式**: 根据连接状态选择不同的测试方法 -- **已连接状态**: 使用 SingBox 通过代理测试延迟 -- **未连接状态**: 使用本机网络直接ping节点IP测试延迟 - -```dart -if (kr_isConnected.value) { - // 已连接状态:使用 SingBox 通过代理测试 - KRLogUtil.kr_i('🔗 已连接状态 - 使用 SingBox 通过代理测试延迟', tag: 'HomeController'); - await KRSingBoxImp.instance.kr_urlTest("select"); -} else { - // 未连接状态:使用本机网络直接ping节点IP - KRLogUtil.kr_i('🔌 未连接状态 - 使用本机网络直接ping节点IP测试延迟', tag: 'HomeController'); - KRLogUtil.kr_i('🌐 这将绕过代理,直接使用本机网络连接节点', tag: 'HomeController'); - await _kr_testLatencyWithoutVpn(); -} -``` - -### **2. 优化未连接状态延迟测试** - -#### **修改位置**: `_kr_testLatencyWithoutVpn()` 方法 - -#### **优化内容**: -- **明确测试方式**: 强调使用本机网络直接连接 -- **详细日志记录**: 记录测试过程和结果统计 -- **结果展示**: 显示延迟最低的前3个节点 -- **错误处理**: 完善的错误处理和统计 - -```dart -/// 未连接状态下的延迟测试(使用本机网络直接ping节点IP) -Future _kr_testLatencyWithoutVpn() async { - KRLogUtil.kr_i('🔌 开始未连接状态延迟测试(使用本机网络)', tag: 'HomeController'); - KRLogUtil.kr_i('🌐 将使用本机网络直接连接节点IP进行延迟测试', tag: 'HomeController'); - - // 获取所有非auto节点 - final testableNodes = kr_subscribeService.allList - .where((item) => item.tag != 'auto') - .toList(); - - // 并行执行所有测试任务 - await Future.wait(testTasks); - - // 统计测试结果 - final successCount = testableNodes.where((item) => item.urlTestDelay.value < 65535).length; - final failCount = testableNodes.length - successCount; - - KRLogUtil.kr_i('📊 测试结果: 成功 $successCount 个,失败 $failCount 个', tag: 'HomeController'); -} -``` - -### **3. 优化单个节点测试方法** - -#### **修改位置**: `_kr_testSingleNode()` 方法 - -#### **优化内容**: -- **明确测试方式**: 强调使用本机网络直接连接(绕过代理) -- **增加超时时间**: 从5秒增加到8秒 -- **调整延迟阈值**: 从3秒调整到5秒 -- **详细错误分类**: 区分不同类型的连接错误 -- **更清晰的日志**: 明确标识使用本机网络测试 - -```dart -/// 测试单个节点的延迟(使用本机网络直接ping节点IP) -Future _kr_testSingleNode(dynamic item) async { - KRLogUtil.kr_i('🔌 使用本机网络直接连接测试(绕过代理)', tag: 'NodeTest'); - - // 创建Socket连接,使用本机网络(不经过代理) - final socket = await Socket.connect( - address, - port, - timeout: const Duration(seconds: 8), // 增加超时时间到8秒 - ); - - // 设置延迟阈值:超过5秒认为节点不可用 - if (delay > 5000) { - item.urlTestDelay.value = 65535; - KRLogUtil.kr_w('⚠️ 节点 ${item.tag} 延迟过高: ${delay}ms,标记为不可用', tag: 'NodeTest'); - } else { - // 使用本机网络测试的延迟结果 - item.urlTestDelay.value = delay; - KRLogUtil.kr_i('✅ 节点 ${item.tag} 本机网络延迟测试成功: ${delay}ms', tag: 'NodeTest'); - } -} -``` - -## 🎯 优化效果 - -### **解决的问题**: - -1. **代理拦截问题**: 未连接时使用本机网络直接连接,绕过代理拦截 -2. **延迟测试不准确**: 使用本机网络直接ping节点IP,获得真实的网络延迟 -3. **测试方式不明确**: 明确区分代理测试和直连测试 -4. **错误处理不完善**: 增加详细的错误分类和处理 - -### **预期改善**: - -1. **未连接状态**: 可以正常获取节点延迟信息 -2. **测试准确性**: 使用本机网络测试,获得更准确的延迟数据 -3. **用户体验**: 无论是否连接代理,都能看到节点延迟 -4. **调试能力**: 详细的日志记录,便于问题排查 - -## 📊 测试场景 - -### **测试场景1: 未连接状态延迟测试** -- **预期行为**: 使用本机网络直接连接节点IP -- **验证要点**: - - 日志显示"使用本机网络直接连接测试(绕过代理)" - - 能够获取到节点的真实延迟 - - 延迟值合理(通常 < 5000ms) - -### **测试场景2: 已连接状态延迟测试** -- **预期行为**: 使用 SingBox 通过代理测试 -- **验证要点**: - - 日志显示"使用 SingBox 通过代理测试延迟" - - 通过代理获取延迟信息 - - 测试结果正确显示 - -### **测试场景3: 网络异常处理** -- **预期行为**: 正确处理连接超时、拒绝、不可达等情况 -- **验证要点**: - - 超时节点标记为不可用(65535) - - 错误日志详细记录错误类型 - - 测试继续进行,不影响其他节点 - -## 🔍 关键日志点 - -### **测试开始**: -- `🔌 开始未连接状态延迟测试(使用本机网络)` -- `🌐 将使用本机网络直接连接节点IP进行延迟测试` - -### **单个节点测试**: -- `🔌 使用本机网络直接连接测试(绕过代理)` -- `⏱️ 本机网络连接延迟: XXXms` -- `✅ 节点 XXX 本机网络延迟测试成功: XXXms` - -### **测试结果**: -- `📊 测试结果: 成功 X 个,失败 X 个` -- `🏆 延迟最低的前3个节点:` - -### **错误处理**: -- `⏰ 节点 XXX 连接超时` -- `🚫 节点 XXX 连接被拒绝` -- `🌐 节点 XXX 网络不可达` - -## 📝 总结 - -通过这次优化,我们解决了延迟测试的核心问题: - -1. **明确区分测试方式**: 根据连接状态选择代理测试或直连测试 -2. **使用本机网络**: 未连接时直接ping节点IP,绕过代理拦截 -3. **提高测试准确性**: 获得真实的网络延迟数据 -4. **完善错误处理**: 详细的错误分类和日志记录 -5. **改善用户体验**: 无论是否连接代理,都能看到节点延迟 - -现在用户可以在未连接代理的情况下,通过本机网络直接测试节点延迟,获得准确的延迟信息! diff --git a/LOGIN_MAP_ONLY_ISSUE_ANALYSIS.md b/LOGIN_MAP_ONLY_ISSUE_ANALYSIS.md deleted file mode 100755 index 67dcc86..0000000 --- a/LOGIN_MAP_ONLY_ISSUE_ANALYSIS.md +++ /dev/null @@ -1,285 +0,0 @@ -# 登录后只显示地图问题分析 - -## 🔍 问题描述 - -用户反馈:登录后,有时候重新打开app会直接只加载地图,其他的页面(底部面板、登录框等)就没有正常显示。 - -## 📋 问题分析 - -### **1. 页面显示逻辑分析** - -#### **首页视图显示逻辑** (`kr_home_view.dart`) -```dart -// 根据登录状态决定显示内容 -if (controller.kr_currentViewStatus.value == KRHomeViewsStatus.kr_notLoggedIn) { - // 未登录:显示地图 + 登录框 - return Scaffold( - body: Stack( - children: [ - const KRHomeMapView(), // 地图视图 - Positioned(bottom: 0, child: KRLoginView()), // 登录框 - ], - ), - ); -} - -// 已登录:显示地图 + 底部面板 -return Scaffold( - body: Stack( - children: [ - const KRHomeMapView(), // 地图视图 - Positioned(bottom: 0, child: KRHomeBottomPanel()), // 底部面板 - ], - ), -); -``` - -#### **底部面板显示逻辑** (`kr_home_bottom_panel.dart`) -```dart -// 根据订阅服务状态决定显示内容 -if (controller.kr_currentListStatus.value == KRHomeViewsListStatus.kr_loading) { - return _kr_buildLoadingView(); // 显示加载动画 -} - -if (controller.kr_currentListStatus.value == KRHomeViewsListStatus.kr_error) { - return _kr_buildErrorView(context); // 显示错误信息 -} - -// 正常状态:显示订阅信息、连接选项等 -return _kr_buildDefaultView(context); -``` - -### **2. 状态初始化流程** - -#### **启动流程** -1. **启动页面** (`kr_splash_controller.dart`) - - 初始化 SingBox - - 初始化用户信息 (`KRAppRunData.getInstance().kr_initializeUserInfo()`) - - 跳转到主页面 - -2. **主页面初始化** (`kr_main_controller.dart`) - - 创建首页控制器 (`KRHomeController`) - - 显示首页视图 (`KRHomeView`) - -3. **首页控制器初始化** (`kr_home_controller.dart`) - - `_kr_initLoginStatus()` - 初始化登录状态 - - `_bindSubscribeStatus()` - 绑定订阅状态 - - `_bindConnectionStatus()` - 绑定连接状态 - -#### **登录状态初始化** (`_kr_initLoginStatus`) -```dart -void _kr_initLoginStatus() { - // 延迟100ms初始化,确保异步操作完成 - Future.delayed(const Duration(milliseconds: 100), () { - _kr_validateAndSetLoginStatus(); - }); - - // 注册登录状态监听器 - ever(KRAppRunData().kr_isLogin, (isLoggedIn) { - _kr_handleLoginStatusChange(isLoggedIn); - }); -} -``` - -#### **订阅状态绑定** (`_bindSubscribeStatus`) -```dart -void _bindSubscribeStatus() { - ever(kr_subscribeService.kr_currentStatus, (data) { - if (KRAppRunData.getInstance().kr_isLogin.value) { - if (data == KRSubscribeServiceStatus.kr_loading) { - kr_currentListStatus.value = KRHomeViewsListStatus.kr_loading; - } else if (data == KRSubscribeServiceStatus.kr_error) { - kr_currentListStatus.value = KRHomeViewsListStatus.kr_error; - } else { - kr_currentListStatus.value = KRHomeViewsListStatus.kr_none; - } - } - }); -} -``` - -### **3. 潜在问题点** - -#### **问题1: 竞态条件 (Race Condition)** -- **现象**: 登录状态和订阅服务状态初始化时序不确定 -- **原因**: - - `_kr_initLoginStatus()` 延迟100ms执行 - - `kr_subscribeService.kr_refreshAll()` 异步执行 - - 两个异步操作可能产生竞态条件 - -#### **问题2: 订阅服务初始化失败** -- **现象**: 订阅服务状态卡在 `kr_loading` 或 `kr_error` -- **原因**: - - 网络请求失败 - - API 响应异常 - - 数据解析错误 - - 超时问题 - -#### **问题3: 状态监听器注册时机** -- **现象**: 状态变化时监听器未正确响应 -- **原因**: - - 监听器注册在异步操作之后 - - 状态变化发生在监听器注册之前 - -#### **问题4: 登录状态验证逻辑** -- **现象**: 登录状态判断不准确 -- **原因**: - - Token 验证逻辑复杂 - - 状态同步检查可能失败 - -### **4. 具体场景分析** - -#### **场景1: 只显示地图,无底部面板** -``` -可能原因: -1. kr_currentViewStatus = kr_loggedIn (已登录) -2. kr_currentListStatus = kr_loading (订阅服务加载中) -3. 订阅服务初始化失败或超时 -4. 底部面板显示加载动画,但加载动画可能有问题 -``` - -#### **场景2: 显示地图 + 登录框(应该是已登录状态)** -``` -可能原因: -1. kr_currentViewStatus = kr_notLoggedIn (未登录) -2. 登录状态验证失败 -3. Token 无效或过期 -4. 状态同步检查失败 -``` - -#### **场景3: 显示地图 + 错误信息** -``` -可能原因: -1. kr_currentViewStatus = kr_loggedIn (已登录) -2. kr_currentListStatus = kr_error (订阅服务错误) -3. 网络请求失败 -4. API 返回错误 -``` - -## 🛠️ 修复建议 - -### **1. 增强状态验证** -```dart -void _kr_validateAndSetLoginStatus() { - try { - // 多重验证登录状态 - final hasToken = KRAppRunData().kr_token != null && KRAppRunData().kr_token!.isNotEmpty; - final isLoginFlag = KRAppRunData().kr_isLogin.value; - final isValidLogin = hasToken && isLoginFlag; - - KRLogUtil.kr_i('登录状态验证: hasToken=$hasToken, isLogin=$isLoginFlag, isValid=$isValidLogin', tag: 'HomeController'); - - if (isValidLogin) { - kr_currentViewStatus.value = KRHomeViewsStatus.kr_loggedIn; - // 确保订阅服务初始化 - _kr_ensureSubscribeServiceInitialized(); - } else { - kr_currentViewStatus.value = KRHomeViewsStatus.kr_notLoggedIn; - } - } catch (e) { - KRLogUtil.kr_e('登录状态验证失败: $e', tag: 'HomeController'); - kr_currentViewStatus.value = KRHomeViewsStatus.kr_notLoggedIn; - } -} -``` - -### **2. 确保订阅服务初始化** -```dart -void _kr_ensureSubscribeServiceInitialized() { - // 检查订阅服务状态 - if (kr_subscribeService.kr_currentStatus.value == KRSubscribeServiceStatus.kr_none) { - KRLogUtil.kr_i('订阅服务未初始化,开始初始化', tag: 'HomeController'); - kr_subscribeService.kr_refreshAll().catchError((error) { - KRLogUtil.kr_e('订阅服务初始化失败: $error', tag: 'HomeController'); - // 设置错误状态 - kr_currentListStatus.value = KRHomeViewsListStatus.kr_error; - }); - } -} -``` - -### **3. 添加超时处理** -```dart -void _kr_initLoginStatus() { - // 设置超时处理 - Timer(const Duration(seconds: 10), () { - if (kr_currentListStatus.value == KRHomeViewsListStatus.kr_loading) { - KRLogUtil.kr_w('订阅服务初始化超时', tag: 'HomeController'); - kr_currentListStatus.value = KRHomeViewsListStatus.kr_error; - } - }); - - // 延迟初始化 - Future.delayed(const Duration(milliseconds: 100), () { - _kr_validateAndSetLoginStatus(); - }); -} -``` - -### **4. 增强错误处理** -```dart -void _bindSubscribeStatus() { - ever(kr_subscribeService.kr_currentStatus, (data) { - if (KRAppRunData.getInstance().kr_isLogin.value) { - switch (data) { - case KRSubscribeServiceStatus.kr_loading: - kr_currentListStatus.value = KRHomeViewsListStatus.kr_loading; - break; - case KRSubscribeServiceStatus.kr_error: - kr_currentListStatus.value = KRHomeViewsListStatus.kr_error; - // 添加重试机制 - _kr_retrySubscribeService(); - break; - case KRSubscribeServiceStatus.kr_success: - kr_currentListStatus.value = KRHomeViewsListStatus.kr_none; - break; - default: - kr_currentListStatus.value = KRHomeViewsListStatus.kr_none; - } - } - }); -} -``` - -### **5. 添加重试机制** -```dart -void _kr_retrySubscribeService() { - Timer(const Duration(seconds: 3), () { - if (kr_currentListStatus.value == KRHomeViewsListStatus.kr_error) { - KRLogUtil.kr_i('重试订阅服务初始化', tag: 'HomeController'); - kr_subscribeService.kr_refreshAll().catchError((error) { - KRLogUtil.kr_e('重试失败: $error', tag: 'HomeController'); - }); - } - }); -} -``` - -## 📊 监控和调试 - -### **1. 关键日志点** -- 登录状态验证日志 -- 订阅服务初始化日志 -- 状态变化日志 -- 错误处理日志 - -### **2. 状态检查** -- `kr_currentViewStatus` 的值 -- `kr_currentListStatus` 的值 -- `kr_subscribeService.kr_currentStatus` 的值 -- `KRAppRunData().kr_isLogin` 的值 - -### **3. 网络状态** -- API 请求是否成功 -- 响应数据是否正常 -- 超时情况 - -## 🎯 总结 - -这个问题主要是由于**异步初始化时序问题**和**状态管理复杂性**导致的。核心问题是: - -1. **登录状态验证** 和 **订阅服务初始化** 之间存在竞态条件 -2. **订阅服务初始化失败** 时没有合适的错误处理和重试机制 -3. **状态监听器注册时机** 可能晚于状态变化 - -通过增强状态验证、添加超时处理、完善错误处理和重试机制,可以显著改善这个问题的发生频率。 diff --git a/LOGIN_MAP_ONLY_ISSUE_FIX_SUMMARY.md b/LOGIN_MAP_ONLY_ISSUE_FIX_SUMMARY.md deleted file mode 100755 index 8ac7b26..0000000 --- a/LOGIN_MAP_ONLY_ISSUE_FIX_SUMMARY.md +++ /dev/null @@ -1,218 +0,0 @@ -# 登录后只显示地图问题修复总结 - -## 🎯 修复目标 - -解决登录后重新打开app时只显示地图而其他页面(底部面板、登录框等)不显示的问题。 - -## 🔧 修复内容 - -### **1. 增强登录状态验证逻辑** - -#### **修改位置**: `_kr_validateAndSetLoginStatus()` 方法 - -#### **修复内容**: -- **多重验证**: 同时检查 `hasToken` 和 `isLoginFlag` -- **详细日志**: 添加更详细的状态验证日志 -- **Token验证**: 确保Token不为空且不为空字符串 -- **状态设置**: 明确设置登录状态并记录日志 - -```dart -// 多重验证登录状态 -final hasToken = KRAppRunData().kr_token != null && KRAppRunData().kr_token!.isNotEmpty; -final isLoginFlag = KRAppRunData().kr_isLogin.value; -final isValidLogin = hasToken && isLoginFlag; - -KRLogUtil.kr_i('登录状态验证: hasToken=$hasToken, isLogin=$isLoginFlag, isValid=$isValidLogin', tag: 'HomeController'); -KRLogUtil.kr_i('Token内容: ${KRAppRunData().kr_token?.substring(0, 10)}...', tag: 'HomeController'); -``` - -### **2. 确保订阅服务初始化** - -#### **新增方法**: `_kr_ensureSubscribeServiceInitialized()` - -#### **修复内容**: -- **状态检查**: 检查订阅服务当前状态 -- **智能初始化**: 根据状态决定是否需要初始化 -- **错误处理**: 初始化失败时设置错误状态 -- **自动重试**: 失败时自动启动重试机制 - -```dart -void _kr_ensureSubscribeServiceInitialized() { - try { - // 检查订阅服务状态 - final currentStatus = kr_subscribeService.kr_currentStatus.value; - - if (currentStatus == KRSubscribeServiceStatus.kr_none || - currentStatus == KRSubscribeServiceStatus.kr_error) { - // 设置加载状态并初始化 - kr_currentListStatus.value = KRHomeViewsListStatus.kr_loading; - kr_subscribeService.kr_refreshAll().then((_) { - KRLogUtil.kr_i('订阅服务初始化完成', tag: 'HomeController'); - }).catchError((error) { - KRLogUtil.kr_e('订阅服务初始化失败: $error', tag: 'HomeController'); - kr_currentListStatus.value = KRHomeViewsListStatus.kr_error; - _kr_retrySubscribeService(); - }); - } - } catch (e) { - KRLogUtil.kr_e('确保订阅服务初始化失败: $e', tag: 'HomeController'); - kr_currentListStatus.value = KRHomeViewsListStatus.kr_error; - } -} -``` - -### **3. 添加超时处理机制** - -#### **修改位置**: `_kr_initLoginStatus()` 方法 - -#### **修复内容**: -- **超时检测**: 10秒后检查订阅服务是否还在加载 -- **自动处理**: 超时时自动设置为错误状态 -- **重试机制**: 超时后自动启动重试 - -```dart -// 设置超时处理 -Timer(const Duration(seconds: 10), () { - if (kr_currentListStatus.value == KRHomeViewsListStatus.kr_loading) { - KRLogUtil.kr_w('订阅服务初始化超时,设置为错误状态', tag: 'HomeController'); - kr_currentListStatus.value = KRHomeViewsListStatus.kr_error; - _kr_retrySubscribeService(); - } -}); -``` - -### **4. 增强错误处理和重试机制** - -#### **新增方法**: `_kr_retrySubscribeService()` - -#### **修复内容**: -- **智能重试**: 3秒后自动重试 -- **多次重试**: 最多重试3次 -- **渐进延迟**: 重试间隔逐渐增加 -- **状态检查**: 只在错误状态时重试 - -```dart -void _kr_retrySubscribeService() { - KRLogUtil.kr_i('启动订阅服务重试机制', tag: 'HomeController'); - - Timer(const Duration(seconds: 3), () { - if (kr_currentListStatus.value == KRHomeViewsListStatus.kr_error) { - KRLogUtil.kr_i('重试订阅服务初始化', tag: 'HomeController'); - - kr_subscribeService.kr_refreshAll().then((_) { - KRLogUtil.kr_i('订阅服务重试成功', tag: 'HomeController'); - }).catchError((error) { - KRLogUtil.kr_e('订阅服务重试失败: $error', tag: 'HomeController'); - - // 第二次重试 - Timer(const Duration(seconds: 5), () { - if (kr_currentListStatus.value == KRHomeViewsListStatus.kr_error) { - KRLogUtil.kr_i('第二次重试订阅服务初始化', tag: 'HomeController'); - kr_subscribeService.kr_refreshAll().catchError((error) { - KRLogUtil.kr_e('第二次重试失败: $error', tag: 'HomeController'); - }); - } - }); - }); - } - }); -} -``` - -### **5. 优化异步初始化时序** - -#### **修改位置**: `_bindSubscribeStatus()` 方法 - -#### **修复内容**: -- **状态监听**: 增强订阅服务状态监听 -- **智能处理**: 根据状态自动处理不同情况 -- **自动初始化**: 状态为none时自动尝试初始化 -- **详细日志**: 添加详细的状态变化日志 - -```dart -void _bindSubscribeStatus() { - ever(kr_subscribeService.kr_currentStatus, (data) { - KRLogUtil.kr_i('订阅服务状态变化: $data', tag: 'HomeController'); - - if (KRAppRunData.getInstance().kr_isLogin.value) { - switch (data) { - case KRSubscribeServiceStatus.kr_loading: - kr_currentListStatus.value = KRHomeViewsListStatus.kr_loading; - break; - case KRSubscribeServiceStatus.kr_error: - kr_currentListStatus.value = KRHomeViewsListStatus.kr_error; - _kr_retrySubscribeService(); - break; - case KRSubscribeServiceStatus.kr_success: - kr_currentListStatus.value = KRHomeViewsListStatus.kr_none; - break; - case KRSubscribeServiceStatus.kr_none: - // 如果状态为none且已登录,尝试初始化 - if (kr_currentViewStatus.value == KRHomeViewsStatus.kr_loggedIn) { - _kr_ensureSubscribeServiceInitialized(); - } - break; - } - } - }); -} -``` - -## 🎯 修复效果 - -### **解决的问题**: - -1. **竞态条件**: 通过增强状态验证和确保订阅服务初始化解决 -2. **订阅服务初始化失败**: 通过添加重试机制和超时处理解决 -3. **状态监听器注册时机**: 通过优化异步初始化时序解决 -4. **登录状态验证不准确**: 通过多重验证和详细日志解决 - -### **预期改善**: - -1. **减少只显示地图的情况**: 通过确保订阅服务正确初始化 -2. **提高状态一致性**: 通过增强状态验证和同步检查 -3. **增强错误恢复能力**: 通过自动重试机制 -4. **改善用户体验**: 通过超时处理和智能重试 - -## 📊 监控和调试 - -### **关键日志点**: -- `登录状态验证: hasToken=xxx, isLogin=xxx, isValid=xxx` -- `订阅服务当前状态: xxx` -- `订阅服务状态变化: xxx` -- `启动订阅服务重试机制` -- `订阅服务初始化超时` - -### **状态检查**: -- `kr_currentViewStatus` 的值 -- `kr_currentListStatus` 的值 -- `kr_subscribeService.kr_currentStatus` 的值 -- `KRAppRunData().kr_isLogin` 的值 - -## 🚀 测试建议 - -### **测试场景**: -1. **正常登录**: 验证登录后所有功能正常显示 -2. **网络异常**: 验证网络异常时的重试机制 -3. **超时情况**: 验证超时处理和自动重试 -4. **状态切换**: 验证登录/登出状态切换 -5. **多次重试**: 验证多次重试后的最终状态 - -### **验证要点**: -- 登录后底部面板是否正常显示 -- 订阅服务是否成功初始化 -- 错误状态是否自动恢复 -- 重试机制是否正常工作 -- 日志信息是否详细准确 - -## 📝 总结 - -通过系统性的修复,我们解决了登录后只显示地图问题的根本原因: - -1. **增强了状态验证的可靠性** -2. **确保了订阅服务的正确初始化** -3. **添加了超时处理和重试机制** -4. **优化了异步初始化的时序** -5. **完善了错误处理和恢复逻辑** - -这些修复将显著减少问题的发生频率,提高应用的稳定性和用户体验。 diff --git a/MACOS_BUILD_README.md b/MACOS_BUILD_README.md deleted file mode 100644 index bb5bf93..0000000 --- a/MACOS_BUILD_README.md +++ /dev/null @@ -1,126 +0,0 @@ -# macOS DMG 构建指南 - -本指南将帮助您构建 macOS DMG 安装包,并避免用户在安装时需要在安全隐私设置中手动允许。 - -## 🎯 目标 - -构建一个经过代码签名和公证的 DMG 安装包,用户安装时无需手动允许。 - -## 📋 前提条件 - -### 1. Apple Developer 账户 -- 需要有效的 Apple Developer 账户($99/年) -- 需要 **Developer ID Application** 证书 -- 需要 **Developer ID Installer** 证书 - -### 2. 获取证书 -1. 登录 [Apple Developer Portal](https://developer.apple.com) -2. 进入 "Certificates, Identifiers & Profiles" -3. 创建以下证书: - - **Developer ID Application** (用于应用签名) - - **Developer ID Installer** (用于安装包签名) - -### 3. 创建 App 专用密码 -1. 登录 [Apple ID 管理页面](https://appleid.apple.com) -2. 在 "App 专用密码" 部分创建新密码 -3. 记录此密码,稍后需要用到 - -## 🚀 构建步骤 - -### 方法一:完整签名版本(推荐) - -1. **配置签名信息** - ```bash - # 编辑配置文件 - nano macos_signing_config.sh - - # 修改以下信息: - export APPLE_ID="your-apple-id@example.com" - export APPLE_PASSWORD="your-app-specific-password" - export TEAM_ID="YOUR_TEAM_ID" - export SIGNING_IDENTITY="Developer ID Application: Your Name (YOUR_TEAM_ID)" - ``` - -2. **加载配置并构建** - ```bash - # 加载配置 - source macos_signing_config.sh - - # 构建 DMG - ./build_macos_dmg.sh - ``` - -### 方法二:简化版本(需要手动允许) - -如果您没有开发者证书,可以使用简化版本: - -```bash -./build_macos_simple.sh -``` - -**注意**:此版本需要用户在安装时手动在安全隐私设置中允许。 - -## 📁 输出文件 - -构建完成后,DMG 文件将位于: -``` -build/macos/Build/Products/Release/kaer_with_panels.dmg -``` - -## 🔍 验证签名 - -构建完成后,您可以验证签名: - -```bash -# 验证应用签名 -codesign --verify --verbose build/macos/Build/Products/Release/kaer_with_panels.app - -# 验证 DMG 签名 -codesign --verify --verbose build/macos/Build/Products/Release/kaer_with_panels.dmg - -# 检查公证状态 -spctl --assess --verbose build/macos/Build/Products/Release/kaer_with_panels.dmg -``` - -## 🛠️ 故障排除 - -### 1. 证书问题 -```bash -# 查看可用证书 -security find-identity -v -p codesigning - -# 如果看到 "0 valid identities found",说明没有安装证书 -``` - -### 2. 公证失败 -- 确保 Apple ID 和密码正确 -- 确保 Team ID 正确 -- 检查网络连接 - -### 3. 签名失败 -- 确保证书已正确安装 -- 检查签名身份名称是否正确 -- 确保证书未过期 - -## 📚 相关文档 - -- [Apple 代码签名指南](https://developer.apple.com/documentation/security/notarizing_macos_software_before_distribution) -- [Flutter macOS 部署指南](https://docs.flutter.dev/deployment/macos) -- [DMG 创建指南](https://developer.apple.com/design/human-interface-guidelines/macos/windows-and-views/dialogs/) - -## ⚠️ 重要提醒 - -1. **安全性**:请妥善保管您的开发者证书和密码 -2. **测试**:在分发前,请在干净的 macOS 系统上测试安装 -3. **更新**:定期更新证书,避免过期 -4. **备份**:建议备份您的签名配置 - -## 🎉 成功标志 - -如果构建成功,您应该看到: -- ✅ 应用签名成功 -- ✅ DMG 签名成功 -- ✅ DMG 公证成功 -- ✅ 最终验证通过 - -用户安装时应该能够直接运行,无需手动允许。 diff --git a/MySQL-Backup-Guide.md b/MySQL-Backup-Guide.md deleted file mode 100755 index a70258d..0000000 --- a/MySQL-Backup-Guide.md +++ /dev/null @@ -1,234 +0,0 @@ -# MySQL 5.7 自动备份指南 - -## 📋 配置说明 - -### 🔧 需要修改的配置项 - -在 `docker-compose-mysql-backup.yml` 文件中,请修改以下配置: - -```yaml -environment: - # 🔗 远程 MySQL 5.7 服务器配置 - MYSQL_HOST: "your-mysql-server.com" # ← 修改为你的MySQL服务器地址 - MYSQL_PORT: "3306" # ← 修改为你的MySQL端口 - MYSQL_USER: "backup_user" # ← 修改为你的备份用户 - MYSQL_PASSWORD: "backup_password" # ← 修改为你的备份密码 - MYSQL_VERSION: "5.7" # ← MySQL版本 (已设置为5.7) - - # 📁 备份配置 - BACKUP_RETENTION_DAYS: "7" # ← 备份保留天数 - BACKUP_SCHEDULE: "0 2 * * *" # ← 备份时间 (每天凌晨2点) - - # 🔧 备份选项 - BACKUP_TYPE: "full" # ← 备份类型: full(全量) / incremental(增量) - COMPRESS_BACKUP: "true" # ← 是否压缩备份 - PARALLEL_THREADS: "2" # ← 并行线程数 (MySQL 5.7 建议使用较少线程) -``` - -## 🚀 执行步骤 - -### 步骤1: 准备环境 - -```bash -# 1. 创建必要的目录 -mkdir -p backup logs scripts monitor - -# 2. 设置目录权限 -chmod 755 backup logs scripts monitor -``` - -### 步骤2: 修改配置 - -```bash -# 编辑配置文件 -nano docker-compose-mysql-backup.yml - -# 或者使用 vim -vim docker-compose-mysql-backup.yml -``` - -**重要**: 请将以下配置修改为你的实际信息: -- `MYSQL_HOST`: 你的MySQL服务器地址 -- `MYSQL_PORT`: MySQL端口 (通常是3306) -- `MYSQL_USER`: 备份用户账号 -- `MYSQL_PASSWORD`: 备份用户密码 - -### 步骤3: 启动备份服务 - -```bash -# 启动备份服务 -docker-compose -f docker-compose-mysql-backup.yml up -d - -# 查看服务状态 -docker-compose -f docker-compose-mysql-backup.yml ps -``` - -### 步骤4: 验证备份 - -```bash -# 查看备份日志 -docker-compose -f docker-compose-mysql-backup.yml logs -f mysql-backup - -# 查看备份文件 -ls -la backup/ - -# 手动触发备份 (可选) -docker-compose -f docker-compose-mysql-backup.yml exec mysql-backup /scripts/backup.sh -``` - -### 步骤5: 访问监控界面 - -```bash -# 访问监控界面 -open http://localhost:8080 -# 或者 -curl http://localhost:8080 -``` - -## 📊 备份时间配置 - -### 常用时间配置 - -```bash -# 每天凌晨2点备份 -BACKUP_SCHEDULE: "0 2 * * *" - -# 每6小时备份一次 -BACKUP_SCHEDULE: "0 */6 * * *" - -# 每周日凌晨2点备份 -BACKUP_SCHEDULE: "0 2 * * 0" - -# 每月1日凌晨2点备份 -BACKUP_SCHEDULE: "0 2 1 * *" - -# 每天上午8点和晚上8点备份 -BACKUP_SCHEDULE: "0 8,20 * * *" -``` - -### 时间格式说明 - -``` -# crontab 格式: 分 时 日 月 周 -# 分: 0-59 -# 时: 0-23 -# 日: 1-31 -# 月: 1-12 -# 周: 0-7 (0和7都表示周日) -``` - -## 🔍 故障排除 - -### 常见问题 - -#### 1. 连接失败 -```bash -# 检查网络连接 -ping your-mysql-server.com - -# 检查端口是否开放 -telnet your-mysql-server.com 3306 - -# 查看详细错误日志 -docker-compose -f docker-compose-mysql-backup.yml logs mysql-backup -``` - -#### 2. 权限问题 -```bash -# 检查目录权限 -ls -la backup/ logs/ scripts/ - -# 修复权限 -chmod 755 backup/ logs/ scripts/ -chown -R $USER:$USER backup/ logs/ scripts/ -``` - -#### 3. 备份失败 -```bash -# 查看详细日志 -docker-compose -f docker-compose-mysql-backup.yml logs mysql-backup - -# 手动测试连接 -docker-compose -f docker-compose-mysql-backup.yml exec mysql-backup \ - mysql -h your-mysql-server.com -P 3306 -u backup_user -p -``` - -### 日志分析 - -```bash -# 实时查看日志 -docker-compose -f docker-compose-mysql-backup.yml logs -f mysql-backup - -# 查看最近的日志 -docker-compose -f docker-compose-mysql-backup.yml logs --tail=100 mysql-backup - -# 查看特定时间的日志 -docker-compose -f docker-compose-mysql-backup.yml logs --since="2024-01-15T00:00:00" mysql-backup -``` - -## 📁 备份文件结构 - -``` -backup/ -├── full/ # 全量备份目录 -│ ├── 20240115_020000/ # 按时间戳命名的备份目录 -│ │ └── backup.tar.gz # 压缩的备份文件 -│ └── 20240116_020000/ -│ └── backup.tar.gz -└── incremental/ # 增量备份目录 - ├── 20240115_140000/ - │ └── backup.tar.gz - └── 20240115_200000/ - └── backup.tar.gz -``` - -## 🔧 高级配置 - -### 自定义备份脚本 - -```bash -# 创建自定义备份脚本 -cat > scripts/custom-backup.sh << 'EOF' -#!/bin/bash -# 自定义备份逻辑 -echo "执行自定义备份..." -# 在这里添加你的自定义逻辑 -EOF - -chmod +x scripts/custom-backup.sh -``` - -### 备份到云存储 - -```bash -# 安装云存储工具 -docker-compose -f docker-compose-mysql-backup.yml exec mysql-backup \ - apt-get update && apt-get install -y awscli - -# 配置云存储 -docker-compose -f docker-compose-mysql-backup.yml exec mysql-backup \ - aws configure -``` - -## 📞 支持 - -如果遇到问题,请检查: - -1. **网络连接**: 确保可以访问MySQL服务器 -2. **用户权限**: 确保备份用户有足够权限 -3. **磁盘空间**: 确保有足够的存储空间 -4. **日志文件**: 查看详细的错误日志 - -## 🎯 总结 - -这个配置提供了: - -- ✅ **自动备份**: 定时自动执行备份 -- ✅ **MySQL 5.7 支持**: 使用兼容的Percona XtraBackup 2.4 -- ✅ **压缩备份**: 节省存储空间 -- ✅ **自动清理**: 自动删除旧备份 -- ✅ **监控界面**: Web界面查看备份状态 -- ✅ **详细日志**: 完整的备份日志记录 -- ✅ **错误处理**: 完善的错误检测和处理 - -按照上述步骤配置后,你的MySQL 5.7数据库将自动进行定时备份! diff --git a/PING_LATENCY_TEST_CONFIRMATION.md b/PING_LATENCY_TEST_CONFIRMATION.md deleted file mode 100755 index 7c43e1b..0000000 --- a/PING_LATENCY_TEST_CONFIRMATION.md +++ /dev/null @@ -1,164 +0,0 @@ -# Ping延迟测试逻辑确认 - -## 🎯 用户需求确认 - -**用户明确需求**: -1. **连接后的测速逻辑**: 保持不变,使用 SingBox 通过代理测试 -2. **没连接前的测速逻辑**: - - 从接口获取节点信息 - - 如果信息包含 `ip:端口` 格式,则只取 IP 部分 - - 使用本机网络直接 ping 这个 IP 获取延迟 - - 将 ping 的延迟作为节点延迟显示 - -## 📋 当前实现逻辑 - -### **1. 连接状态判断** - -#### **主测试方法**: `kr_urlTest()` -```dart -if (kr_isConnected.value) { - // ✅ 连接后:保持默认测试规则,使用 SingBox 通过代理测试 - KRLogUtil.kr_i('🔗 已连接状态 - 使用 SingBox 通过代理测试延迟', tag: 'HomeController'); - await KRSingBoxImp.instance.kr_urlTest("select"); - // 等待 SingBox 完成测试并获取结果 -} else { - // ✅ 没连接前:使用本机网络直接ping节点IP - KRLogUtil.kr_i('🔌 未连接状态 - 使用本机网络直接ping节点IP测试延迟', tag: 'HomeController'); - await _kr_testLatencyWithoutVpn(); -} -``` - -### **2. 没连接前的Ping测试逻辑** - -#### **Ping测试方法**: `_kr_testSingleNode()` -```dart -/// 测试单个节点的延迟(使用本机网络直接ping节点IP) -Future _kr_testSingleNode(dynamic item) async { - // 从接口获取的节点信息中提取IP地址 - String targetIp = item.serverAddr; - - // 如果信息包含 ip:端口 格式,则只取IP部分 - if (targetIp.contains(':')) { - final parts = targetIp.split(':'); - if (parts.length == 2) { - targetIp = parts[0]; - KRLogUtil.kr_i('📌 从 ip:端口 格式中提取IP: $targetIp', tag: 'NodeTest'); - } - } - - KRLogUtil.kr_i('🎯 目标IP地址: $targetIp', tag: 'NodeTest'); - KRLogUtil.kr_i('🔌 使用本机网络直接ping IP地址(绕过代理)', tag: 'NodeTest'); - - // 使用本机网络直接ping IP地址测试延迟 - final socket = await Socket.connect( - targetIp, - 80, // 使用80端口进行ping测试 - timeout: const Duration(seconds: 5), // 5秒超时 - ); - - // 获取延迟时间 - final delay = stopwatch.elapsedMilliseconds; - - // 使用ping的延迟结果作为节点延迟 - item.urlTestDelay.value = delay; - KRLogUtil.kr_i('✅ 节点 ${item.tag} ping测试成功: ${delay}ms', tag: 'NodeTest'); -} -``` - -## ✅ 逻辑确认 - -### **连接后(kr_isConnected.value = true)**: -1. **保持默认测试规则**: 使用 `KRSingBoxImp.instance.kr_urlTest("select")` -2. **通过代理测试**: 使用 SingBox 的 URL 测试功能 -3. **等待测试完成**: 等待3秒让 SingBox 完成测试 -4. **获取测试结果**: 从 `KRSingBoxImp.instance.kr_activeGroups` 获取延迟信息 - -### **没连接前(kr_isConnected.value = false)**: -1. **从接口获取节点信息**: 使用 `item.serverAddr` -2. **提取IP地址**: 如果包含 `ip:端口` 格式,只取IP部分 -3. **使用本机网络ping**: 使用 `Socket.connect()` 直接连接IP的80端口 -4. **获取ping延迟**: 测量连接建立的时间作为延迟 -5. **显示延迟结果**: 将ping延迟作为节点延迟显示 - -## 🔍 关键实现点 - -### **IP地址提取逻辑**: -```dart -// 从接口获取的节点信息中提取IP地址 -String targetIp = item.serverAddr; - -// 如果信息包含 ip:端口 格式,则只取IP部分 -if (targetIp.contains(':')) { - final parts = targetIp.split(':'); - if (parts.length == 2) { - targetIp = parts[0]; // 只取IP部分 - } -} -``` - -### **Ping测试实现**: -```dart -// 使用Socket连接测试ping延迟(模拟ping) -final socket = await Socket.connect( - targetIp, - 80, // 使用80端口进行ping测试 - timeout: const Duration(seconds: 5), // 5秒超时 -); - -// 获取延迟时间 -final delay = stopwatch.elapsedMilliseconds; - -// 使用ping的延迟结果作为节点延迟 -item.urlTestDelay.value = delay; -``` - -## 📊 测试场景 - -### **测试场景1: 连接代理时** -- **预期行为**: 使用 SingBox 通过代理测试(保持默认规则) -- **验证日志**: `🔗 已连接状态 - 使用 SingBox 通过代理测试延迟` -- **测试方式**: `KRSingBoxImp.instance.kr_urlTest("select")` - -### **测试场景2: 没连接时** -- **预期行为**: 使用本机网络直接ping节点IP -- **验证日志**: `🔌 未连接状态 - 使用本机网络直接ping节点IP测试延迟` -- **IP提取**: `📌 从 ip:端口 格式中提取IP: XXX.XXX.XXX.XXX` -- **Ping测试**: `🎯 目标IP地址: XXX.XXX.XXX.XXX` -- **测试方式**: `Socket.connect(targetIp, 80)` 模拟ping - -## 🔍 关键日志点 - -### **IP提取**: -- `📌 从 ip:端口 格式中提取IP: XXX.XXX.XXX.XXX` -- `🎯 目标IP地址: XXX.XXX.XXX.XXX` - -### **Ping测试**: -- `🔌 使用本机网络直接ping IP地址(绕过代理)` -- `⏱️ 开始ping测试...` -- `⏱️ ping延迟: XXXms` -- `✅ 节点 XXX ping测试成功: XXXms` - -### **错误处理**: -- `⏰ 节点 XXX ping超时` -- `🚫 节点 XXX ping被拒绝` -- `🌐 节点 XXX 网络不可达` - -## 📝 总结 - -**✅ 当前实现完全符合用户需求**: - -1. **连接后**: 保持默认测试规则,使用 SingBox 通过代理测试延迟 -2. **没连接前**: - - 从接口获取节点信息 - - 如果包含 `ip:端口` 格式,只取IP部分 - - 使用本机网络直接ping IP地址 - - 将ping延迟作为节点延迟显示 - -**🔧 实现特点**: -- 自动根据连接状态选择测试方式 -- 智能提取IP地址(处理ip:端口格式) -- 使用80端口进行ping测试(更稳定) -- 详细的日志记录,便于调试 -- 完善的错误处理和超时机制 - -**🎯 用户需求已完全实现!** diff --git a/README.md b/README.md deleted file mode 100755 index 5904c8c..0000000 --- a/README.md +++ /dev/null @@ -1,141 +0,0 @@ -# OmnTech - Instant Cloud Services - -## Hi there 👋 - -Welcome to **OmnTech**, where innovation meets freedom in the cloud computing space! - -### 🌟 About Us - -We are a passionate team of technology enthusiasts at **OmnTech**, a cutting-edge technology company specializing in **instant cloud services**. Our mission is to deliver lightning-fast, reliable, and scalable cloud solutions that empower businesses and individuals worldwide. - -### 🌍 Our Locations - -- **Headquarters**: Tallinn, Estonia 🇪🇪 -- **US Office**: San Jose, California 🇺🇸 - -### 💻 Our Culture - -We are a team of **technology lovers** and **freedom seekers** who believe in the power of remote work. Our distributed workforce spans across different time zones, bringing together diverse perspectives and innovative ideas. We embrace the flexibility of remote collaboration while maintaining the highest standards of technical excellence. - -### 🚀 What We Do - -**OmnTech** specializes in: - -- **Instant Cloud Services** - Rapid deployment and scaling solutions -- **Real-time Infrastructure** - Low-latency cloud computing platforms -- **Global Network Solutions** - Worldwide connectivity and optimization -- **Developer Tools** - APIs and SDKs for seamless integration -- **Enterprise Solutions** - Custom cloud architectures for businesses - -### 🌈 How to Get Involved - -We welcome contributions from the global developer community! Here's how you can get involved: - -- **Open Source Projects** - Contribute to our public repositories -- **Documentation** - Help improve our technical documentation -- **Bug Reports** - Report issues and help us improve -- **Feature Requests** - Suggest new features and improvements -- **Community Discussions** - Join our technical discussions - -### 👩‍💻 Useful Resources - -- **Documentation**: [docs.omntech.com](https://docs.omntech.com) -- **API Reference**: [api.omntech.com](https://api.omntech.com) -- **Community Forum**: [community.omntech.com](https://community.omntech.com) -- **Support**: [support@omntech.com](mailto:support@omntech.com) - -### 🍿 Fun Facts About Our Team - -- **Breakfast of Champions**: Our remote team enjoys everything from traditional Estonian black bread to California avocado toast -- **Coffee Culture**: We have a virtual coffee break every day at 3 PM EST -- **Global Perspectives**: Our team speaks 12+ languages fluently -- **Innovation Time**: Every Friday is dedicated to personal projects and innovation -- **Remote First**: We've been remote-first since day one, long before it became mainstream - -### 🧙 Our Philosophy - -We believe that **technology should serve humanity**, not the other way around. Our commitment to freedom, innovation, and excellence drives everything we do. We're not just building cloud services – we're building the future of how people work, collaborate, and create. - -### 📞 Contact Us - -- **Website**: [omntech.com](https://omntech.com) -- **Email**: [hello@omntech.com](mailto:hello@omntech.com) -- **LinkedIn**: [OmnTech](https://linkedin.com/company/omntech) -- **Twitter**: [@OmnTech](https://twitter.com/omntech) - ---- - -*Remember, you can do mighty things with the power of [Markdown](https://docs.github.com/github/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax) and the right team!* - ---- - -## 中文翻译 - -# OmnTech - 即时云服务 - -## 你好 👋 - -欢迎来到 **OmnTech**,在这里创新与自由在云计算领域相遇! - -### 🌟 关于我们 - -我们是 **OmnTech** 充满激情的科技爱好者团队,这是一家专注于**即时云服务**的前沿科技公司。我们的使命是为全球企业和个人提供闪电般快速、可靠且可扩展的云解决方案。 - -### 🌍 我们的办公地点 - -- **总部**: 爱沙尼亚塔林 🇪🇪 -- **美国办公室**: 加利福尼亚圣何塞 🇺🇸 - -### 💻 我们的文化 - -我们是一群**技术爱好者**和**自由追求者**,相信远程工作的力量。我们的分布式团队跨越不同时区,汇聚了多样化的观点和创新理念。我们拥抱远程协作的灵活性,同时保持最高的技术卓越标准。 - -### 🚀 我们的业务 - -**OmnTech** 专注于: - -- **即时云服务** - 快速部署和扩展解决方案 -- **实时基础设施** - 低延迟云计算平台 -- **全球网络解决方案** - 全球连接和优化 -- **开发者工具** - 无缝集成的API和SDK -- **企业解决方案** - 定制化云架构 - -### 🌈 如何参与 - -我们欢迎全球开发者社区的贡献!以下是您可以参与的方式: - -- **开源项目** - 为我们的公共仓库做出贡献 -- **文档** - 帮助改进我们的技术文档 -- **错误报告** - 报告问题并帮助我们改进 -- **功能请求** - 建议新功能和改进 -- **社区讨论** - 加入我们的技术讨论 - -### 👩‍💻 有用资源 - -- **文档**: [docs.omntech.com](https://docs.omntech.com) -- **API参考**: [api.omntech.com](https://api.omntech.com) -- **社区论坛**: [community.omntech.com](https://community.omntech.com) -- **支持**: [support@omntech.com](mailto:support@omntech.com) - -### 🍿 关于我们团队的有趣事实 - -- **冠军早餐**: 我们的远程团队享受从传统爱沙尼亚黑面包到加州鳄梨吐司的一切 -- **咖啡文化**: 我们每天下午3点EST都有虚拟咖啡时间 -- **全球视野**: 我们的团队流利掌握12+种语言 -- **创新时间**: 每个周五都致力于个人项目和创新 -- **远程优先**: 我们从第一天起就是远程优先,远在它成为主流之前 - -### 🧙 我们的理念 - -我们相信**技术应该为人类服务**,而不是相反。我们对自由、创新和卓越的承诺驱动着我们所做的一切。我们不仅仅是在构建云服务——我们正在构建人们工作、协作和创造未来的方式。 - -### 📞 联系我们 - -- **网站**: [omntech.com](https://omntech.com) -- **邮箱**: [hello@omntech.com](mailto:hello@omntech.com) -- **LinkedIn**: [OmnTech](https://linkedin.com/company/omntech) -- **Twitter**: [@OmnTech](https://twitter.com/omntech) - ---- - -*记住,有了[Markdown](https://docs.github.com/github/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax)的力量和正确的团队,你可以做强大的事情!* \ No newline at end of file diff --git a/SINGBOX_TIMEOUT_ANALYSIS.md b/SINGBOX_TIMEOUT_ANALYSIS.md deleted file mode 100755 index 7ec1f7b..0000000 --- a/SINGBOX_TIMEOUT_ANALYSIS.md +++ /dev/null @@ -1,97 +0,0 @@ -# SingBox 节点超时问题分析 - -## 🔍 问题分析 - -### **核心问题** -从日志分析发现,SingBox 的 URL 测试功能正在工作,但是**测试失败**,导致所有节点显示超时(`delay=65535`)。 - -### **关键日志证据** -``` -flutter: 👻 16:40:26.497617 INFO SingBox - 📡 收到活动组更新,数量: 2 -flutter: 👻 16:40:26.497808 INFO KRLogUtil - 处理活动组: [SingboxOutboundGroup(tag: select, type: ProxyType.selector, selected: auto, items: [SingboxOutboundGroupItem(tag: auto, type: ProxyType.urltest, urlTestDelay: 65535)]), SingboxOutboundGroup(tag: auto, type: ProxyType.urltest, selected: 香港, items: [SingboxOutboundGroupItem(tag: 香港, type: ProxyType.trojan, urlTestDelay: 65535)])] -``` - -**延迟值从 `0` 变成了 `65535`**,说明: -1. ✅ SingBox 的 URL 测试功能正在工作 -2. ❌ 但是测试失败了,返回超时值 `65535` - -### **问题原因** -**SingBox 无法通过代理访问测试 URL** `http://connectivitycheck.gstatic.com/generate_204` - -这是一个经典的"鸡生蛋,蛋生鸡"问题: -- SingBox 需要通过代理测试节点延迟 -- 但是代理本身可能无法访问外部测试 URL -- 导致所有节点测试失败,显示超时 - -## 🛠️ 解决方案 - -### 1. **修改测试 URL** -已将测试 URL 从 `http://connectivitycheck.gstatic.com/generate_204` 改为 `http://www.gstatic.com/generate_204` - -### 2. **添加备用测试方法** -- `kr_manualUrlTest()` - 手动触发 SingBox URL 测试 -- `kr_forceDirectTest()` - 强制使用直接连接测试(绕过 SingBox URL 测试) - -### 3. **可能的其他解决方案** - -#### A. **使用本地测试 URL** -```dart -"connection-test-url": "http://127.0.0.1:8080/test" -``` - -#### B. **禁用 URL 测试** -```dart -"url-test-interval": 0 // 禁用自动测试 -``` - -#### C. **使用直接连接测试** -在应用层面实现延迟测试,不依赖 SingBox 的 URL 测试功能。 - -## 🧪 测试步骤 - -### 1. **测试新的 URL** -```bash -curl -I "http://www.gstatic.com/generate_204" -``` - -### 2. **手动触发测试** -在应用中调用: -```dart -await homeController.kr_manualUrlTest(); -``` - -### 3. **使用直接连接测试** -```dart -await homeController.kr_forceDirectTest(); -``` - -## 📊 预期结果 - -如果问题解决,应该看到: -``` -└─ 节点[0]: tag=auto, type=ProxyType.urltest, delay=150 -└─ 节点[0]: tag=香港, type=ProxyType.trojan, delay=200 -``` - -延迟值应该是实际的毫秒数,而不是 0 或 65535。 - -## 🔧 下一步调试 - -1. **重新运行应用**,观察新的测试 URL 是否有效 -2. **如果仍然超时**,尝试使用直接连接测试 -3. **考虑禁用 SingBox 的 URL 测试**,完全依赖应用层面的延迟测试 - -## 📝 关键文件 - -- `lib/app/services/singbox_imp/kr_sing_box_imp.dart` - SingBox 配置 -- `lib/app/modules/kr_home/controllers/kr_home_controller.dart` - 延迟测试逻辑 -- `lib/app/modules/kr_home/controllers/kr_home_controller.dart` - 直接连接测试 - -## 💡 根本解决方案 - -**最佳解决方案**是使用应用层面的直接连接测试,而不是依赖 SingBox 的 URL 测试功能。这样可以: - -1. 避免代理环境下的测试问题 -2. 提供更准确的延迟测量 -3. 更好的用户体验 -4. 更稳定的测试结果 diff --git a/SINGBOX_URL_TEST_DEBUG.md b/SINGBOX_URL_TEST_DEBUG.md deleted file mode 100755 index 0e06e62..0000000 --- a/SINGBOX_URL_TEST_DEBUG.md +++ /dev/null @@ -1,98 +0,0 @@ -# SingBox URL 测试调试分析 - -## 🔍 问题分析 - -从日志分析发现: - -### 1. **配置已正确更新** ✅ -``` -URLTestOptions:{ConnectionTestUrl:http://connectivitycheck.gstatic.com/generate_204 URLTestInterval:30} -``` -- ✅ 测试 URL: `http://connectivitycheck.gstatic.com/generate_204` -- ✅ 测试间隔: 30 秒 - -### 2. **核心问题:节点延迟始终为 0** ❌ -``` -└─ 节点[0]: tag=auto, type=ProxyType.urltest, delay=0 -└─ 节点[0]: tag=香港, type=ProxyType.trojan, delay=0 -``` - -**问题原因**:SingBox 的 URL 测试功能没有正常工作,导致所有节点的延迟值始终为 0。 - -### 3. **活动组更新过于频繁** ⚠️ -日志显示活动组几乎每秒都在更新,这可能导致性能问题。 - -## 🛠️ 解决方案 - -### 1. **添加手动 URL 测试功能** -- 新增 `kr_manualUrlTest()` 方法用于调试 -- 直接调用 SingBox 的 URL 测试 API -- 等待测试完成并检查结果 - -### 2. **增强调试信息** -- 在 `kr_urlTest()` 中添加详细的测试过程日志 -- 测试前后对比活动组状态 -- 显示连接状态和测试方法 - -### 3. **可能的问题原因** - -#### A. **SingBox 配置问题** -- URL 测试功能可能没有正确启用 -- 测试 URL 可能无法访问 -- 测试间隔设置可能有问题 - -#### B. **API 调用问题** -- `urlTest()` 方法可能没有正确调用 -- 原生库的 URL 测试功能可能有问题 -- 测试结果可能没有正确返回 - -#### C. **网络问题** -- 测试 URL 可能被防火墙阻止 -- 网络连接可能有问题 -- DNS 解析可能有问题 - -## 🧪 调试步骤 - -### 1. **手动触发 URL 测试** -```dart -// 在应用中调用 -await homeController.kr_manualUrlTest(); -``` - -### 2. **检查 SingBox 日志** -查看 SingBox 的日志文件,确认是否有 URL 测试相关的日志。 - -### 3. **验证测试 URL** -```bash -curl -I "http://connectivitycheck.gstatic.com/generate_204" -``` - -### 4. **检查网络连接** -```bash -ping connectivitycheck.gstatic.com -nslookup connectivitycheck.gstatic.com -``` - -## 📊 预期结果 - -如果 URL 测试正常工作,应该看到: -``` -└─ 节点[0]: tag=auto, type=ProxyType.urltest, delay=150 -└─ 节点[0]: tag=香港, type=ProxyType.trojan, delay=200 -``` - -延迟值应该是实际的毫秒数,而不是 0 或 65535。 - -## 🔧 下一步调试 - -1. **运行应用并手动触发 URL 测试** -2. **观察新的调试日志** -3. **检查 SingBox 原生日志** -4. **验证网络连接** -5. **如果问题持续,考虑使用直接连接测试作为备选方案** - -## 📝 关键文件 - -- `lib/app/modules/kr_home/controllers/kr_home_controller.dart` - 添加了手动测试方法 -- `lib/app/services/singbox_imp/kr_sing_box_imp.dart` - SingBox 配置和 URL 测试 -- `lib/singbox/service/ffi_singbox_service.dart` - 原生库 URL 测试实现 diff --git a/SPEED_TEST_FIX_ANALYSIS.md b/SPEED_TEST_FIX_ANALYSIS.md deleted file mode 100755 index 5f5a96d..0000000 --- a/SPEED_TEST_FIX_ANALYSIS.md +++ /dev/null @@ -1,142 +0,0 @@ -# 测速功能问题分析与修复 - -## 🔍 问题分析 - -### **用户配置策略** ✅ **完全正确** - -你的 Trojan 配置策略是合理的: - -```json -{ - "server": "156.224.78.176", - "server_name": "baidu.com", // ✅ 防 SNI 检测 - "tls": { - "enabled": true, - "insecure": true, // ✅ 允许自签证书 - "utls": {"enabled": true, "fingerprint": "chrome"} - } -} -``` - -**这个配置不会影响测速功能**,问题在于测速逻辑本身。 - -### **根本原因:测速逻辑设计缺陷** ❌ - -#### **未连接状态下的测速逻辑** ❌ -```dart -// 原始代码:直接连接 Cloudflare -final testSocket = await Socket.connect( - 'speed.cloudflare.com', // ❌ 问题:直接连接,没有通过代理 - 443, - timeout: const Duration(seconds: 3), -); -``` - -#### **已连接状态下的测速逻辑** ✅ -```dart -// 通过 SingBox 代理测试 -await KRSingBoxImp.instance.kr_urlTest("select"); -``` - -### **问题详解** - -1. **未连接时**: - - 直接连接 `speed.cloudflare.com` - - **没有通过代理节点** - - 如果网络环境限制,会超时 - -2. **已连接时**: - - 通过 SingBox 代理测试 - - **流量经过代理节点** - - 可以正常访问测速服务器 - -## 🛠️ 修复方案 - -### **修复后的测速逻辑** ✅ - -```dart -/// 测试单个节点的延迟 -Future _kr_testSingleNode(dynamic item) async { - try { - // 解析地址和端口 - final uri = Uri.parse(item.serverAddr); - final address = uri.host.isEmpty ? item.serverAddr : uri.host; - final port = uri.port > 0 ? uri.port : 443; - - // 使用 Socket 测试到实际节点的 TCP 连接延迟 - final stopwatch = Stopwatch()..start(); - - final socket = await Socket.connect( - address, - port, - timeout: const Duration(seconds: 5), // 增加超时时间 - ); - stopwatch.stop(); - - // 获取延迟时间 - final delay = stopwatch.elapsedMilliseconds; - - // 关闭连接 - await socket.close(); - - // 如果延迟超过3秒,认为节点不可用 - if (delay > 3000) { - item.urlTestDelay.value = 65535; - } else { - // 直接使用连接延迟,不再进行二次测试 - item.urlTestDelay.value = delay; - } - } catch (e) { - item.urlTestDelay.value = 65535; - } -} -``` - -### **修复要点** - -1. **移除二次测试** - 不再连接 `speed.cloudflare.com` -2. **增加超时时间** - 从 3 秒增加到 5 秒 -3. **简化逻辑** - 直接使用节点连接延迟 -4. **提高阈值** - 从 2 秒提高到 3 秒 - -## 📊 修复效果 - -### **修复前** ❌ -- 未连接时:测速超时(直接连接 Cloudflare 失败) -- 已连接时:测速正常(通过代理连接) - -### **修复后** ✅ -- 未连接时:测速正常(直接测试节点连接延迟) -- 已连接时:测速正常(通过代理测试) - -## 🧪 测试步骤 - -1. **重新运行应用** -2. **在未连接状态下测试延迟** - 应该能正常显示延迟值 -3. **连接节点后测试延迟** - 应该能正常显示延迟值 -4. **对比两种状态下的延迟** - 应该都能正常工作 - -## 💡 关键要点 - -1. **你的 Trojan 配置是正确的** - 防 SNI 检测策略有效 -2. **问题在于测速逻辑** - 不是配置问题 -3. **修复后两种状态都能测速** - 解决了根本问题 -4. **延迟测试更准确** - 直接测试节点连接延迟 - -## 🔧 配置建议 - -你的当前配置策略很好,建议保持: - -```json -{ - "server_name": "baidu.com", // 防 SNI 检测 - "tls": { - "insecure": true, // 允许自签证书 - "utls": {"enabled": true, "fingerprint": "chrome"} - } -} -``` - -这个配置能有效防止 GFW 的 SNI 检测和流量分析。 - -修复后,你的测速功能应该能在任何状态下正常工作了! diff --git a/TROJAN_SERVER_NAME_FIX.md b/TROJAN_SERVER_NAME_FIX.md deleted file mode 100755 index 1024c19..0000000 --- a/TROJAN_SERVER_NAME_FIX.md +++ /dev/null @@ -1,134 +0,0 @@ -# Trojan 配置中 server_name 参数修复 - -## 🔍 问题分析 - -### **原始问题** -你的 Trojan 配置中存在 `server_name` 设置错误: - -```json -{ - "server": "156.224.78.176", - "server_name": "baidu.com" // ❌ 错误:服务器 IP 与 SNI 不匹配 -} -``` - -### **问题原因** -1. **TLS 握手失败** - 服务器没有为 `baidu.com` 配置证书 -2. **SNI 不匹配** - 客户端请求 `baidu.com`,但服务器只支持 IP 地址 -3. **代理无法工作** - TLS 验证失败导致连接中断 - -## 🛠️ 修复方案 - -### **智能 server_name 设置** -已修改配置生成逻辑,现在会: - -1. **优先使用配置的 SNI** - 如果服务器配置了 `sni` 参数 -2. **回退到服务器地址** - 如果没有配置 SNI,使用服务器 IP/域名 -3. **避免不匹配** - 确保 `server_name` 与服务器实际配置一致 - -### **修复后的逻辑** -```dart -// 智能设置 server_name -String serverName = securityConfig["sni"] ?? ""; -if (serverName.isEmpty) { - // 如果没有配置 SNI,使用服务器地址 - serverName = nodeListItem.serverAddr; -} -``` - -### **修复后的配置** -```json -{ - "server": "156.224.78.176", - "server_name": "156.224.78.176" // ✅ 正确:使用服务器 IP -} -``` - -## 📋 server_name 参数说明 - -### **应该填什么值** - -#### **1. 服务器实际域名** ✅ **最佳选择** -```json -{ - "server_name": "your-server-domain.com" -} -``` - -#### **2. 服务器 IP 地址** ✅ **推荐** -```json -{ - "server_name": "156.224.78.176" -} -``` - -#### **3. 空字符串** ✅ **某些情况下** -```json -{ - "server_name": "" -} -``` - -### **不应该填什么值** - -#### **❌ 随机域名** -```json -{ - "server_name": "baidu.com" // 错误:服务器没有这个域名的证书 -} -``` - -#### **❌ 不相关的域名** -```json -{ - "server_name": "google.com" // 错误:与服务器不匹配 -} -``` - -## 🔧 其他协议修复 - -已同时修复了以下协议的 `server_name` 设置: - -- **VLESS** - 智能 SNI 设置 -- **VMess** - 智能 SNI 设置 -- **Trojan** - 智能 SNI 设置 - -## 🧪 测试步骤 - -1. **重新运行应用** -2. **检查新的配置** - 应该看到 `server_name` 使用服务器 IP -3. **测试连接** - 应该能正常通过代理访问网络 -4. **验证延迟** - 延迟测试应该能正常工作 - -## 📊 预期结果 - -修复后应该看到: - -```json -{ - "type": "trojan", - "tag": "香港", - "server": "156.224.78.176", - "server_port": 27639, - "password": "cf6dc0d8-4997-4fc3-b790-1a54e38c6e8c", - "tls": { - "enabled": true, - "server_name": "156.224.78.176", // ✅ 修复后 - "insecure": false, - "utls": { - "enabled": true, - "fingerprint": "chrome" - } - } -} -``` - -## 💡 关键要点 - -1. **`server_name` 必须与服务器配置匹配** -2. **优先使用服务器实际域名** -3. **IP 地址也是有效的选择** -4. **避免使用不相关的域名** -5. **TLS 验证失败会导致代理无法工作** - -这个修复应该能解决你的 Trojan 连接问题! diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index d33bce2..2bba432 100755 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -32,12 +32,15 @@ android:name="android.permission.QUERY_ALL_PACKAGES" tools:ignore="QueryAllPackagesPermission" /> - + + { + stopService() + } + + Action.SERVICE_RELOAD -> { + serviceReload() + } + + PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED -> { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + serviceUpdateIdleMode() + } + } + } + } + } + + private fun startCommandServer() { + val commandServer = + CommandServer(this, 300) + commandServer.start() + this.commandServer = commandServer + } + + private var activeProfileName = "" + private suspend fun startService(delayStart: Boolean = false) { + try { + Log.d(TAG, "starting service") + // 暂时禁用通知显示 + // withContext(Dispatchers.Main) { + // notification.show(activeProfileName, R.string.status_starting) + // } + + val selectedConfigPath = Settings.activeConfigPath + if (selectedConfigPath.isBlank()) { + stopAndAlert(Alert.EmptyConfiguration) + return + } + + activeProfileName = Settings.activeProfileName + + val configOptions = Settings.configOptions + if (configOptions.isBlank()) { + stopAndAlert(Alert.EmptyConfiguration) + return + } + + val content = try { + Mobile.buildConfig(selectedConfigPath, configOptions) + } catch (e: Exception) { + Log.w(TAG, e) + stopAndAlert(Alert.EmptyConfiguration) + return + } + + // ✅ 始终保存完整配置以便调试 + try { + File(workingDir, "current-config.json").writeText(content) + Log.d(TAG, "✅ 完整配置已保存到: ${workingDir}/current-config.json") + Log.d(TAG, "📄 配置长度: ${content.length} 字符") + Log.d(TAG, "📄 配置前1000字符:\n${content.substring(0, minOf(1000, content.length))}") + } catch (e: Exception) { + Log.w(TAG, "保存配置文件失败: $e") + } + + withContext(Dispatchers.Main) { + notification.show(activeProfileName, R.string.status_starting) + binder.broadcast { + it.onServiceResetLogs(listOf()) + } + } + + DefaultNetworkMonitor.start() + Libbox.registerLocalDNSTransport(LocalResolver) + Libbox.setMemoryLimit(!Settings.disableMemoryLimit) + + val newService = try { + Libbox.newService(content, platformInterface) + } catch (e: Exception) { + stopAndAlert(Alert.CreateService, e.message) + return + } + + if (delayStart) { + delay(1000L) + } + + newService.start() + boxService = newService + commandServer?.setService(boxService) + status.postValue(Status.Started) + + withContext(Dispatchers.Main) { + notification.show(activeProfileName, R.string.status_started) + } + notification.start() + } catch (e: Exception) { + stopAndAlert(Alert.StartService, e.message) + return + } + } + + override fun serviceReload() { + notification.close() + status.postValue(Status.Starting) + val pfd = fileDescriptor + if (pfd != null) { + pfd.close() + fileDescriptor = null + } + commandServer?.setService(null) + boxService?.apply { + runCatching { + close() + }.onFailure { + writeLog("service: error when closing: $it") + } + Seq.destroyRef(refnum) + } + boxService = null + runBlocking { + startService(true) + } + } + + override fun getSystemProxyStatus(): SystemProxyStatus { + val status = SystemProxyStatus() + if (service is VPNService) { + status.available = service.systemProxyAvailable + status.enabled = service.systemProxyEnabled + } + return status + } + + override fun setSystemProxyEnabled(isEnabled: Boolean) { + serviceReload() + } + + @RequiresApi(Build.VERSION_CODES.M) + private fun serviceUpdateIdleMode() { + if (Application.powerManager.isDeviceIdleMode) { + boxService?.pause() + } else { + boxService?.wake() + } + } + + private fun stopService() { + if (status.value != Status.Started) return + status.value = Status.Stopping + if (receiverRegistered) { + service.unregisterReceiver(receiver) + receiverRegistered = false + } + notification.close() + GlobalScope.launch(Dispatchers.IO) { + val pfd = fileDescriptor + if (pfd != null) { + pfd.close() + fileDescriptor = null + } + commandServer?.setService(null) + boxService?.apply { + runCatching { + close() + }.onFailure { + writeLog("service: error when closing: $it") + } + Seq.destroyRef(refnum) + } + boxService = null + Libbox.registerLocalDNSTransport(null) + DefaultNetworkMonitor.stop() + + commandServer?.apply { + close() + Seq.destroyRef(refnum) + } + commandServer = null + Settings.startedByUser = false + withContext(Dispatchers.Main) { + status.value = Status.Stopped + service.stopSelf() + } + } + } + override fun postServiceClose() { + // Not used on Android + } + + private suspend fun stopAndAlert(type: Alert, message: String? = null) { + Settings.startedByUser = false + withContext(Dispatchers.Main) { + if (receiverRegistered) { + service.unregisterReceiver(receiver) + receiverRegistered = false + } + notification.close() + binder.broadcast { callback -> + callback.onServiceAlert(type.ordinal, message) + } + status.value = Status.Stopped + } + } + + fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + if (status.value != Status.Stopped) return Service.START_NOT_STICKY + status.value = Status.Starting + + if (!receiverRegistered) { + ContextCompat.registerReceiver(service, receiver, IntentFilter().apply { + addAction(Action.SERVICE_CLOSE) + addAction(Action.SERVICE_RELOAD) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED) + } + }, ContextCompat.RECEIVER_NOT_EXPORTED) + receiverRegistered = true + } + + GlobalScope.launch(Dispatchers.IO) { + Settings.startedByUser = true + initialize() + try { + startCommandServer() + } catch (e: Exception) { + stopAndAlert(Alert.StartCommandServer, e.message) + return@launch + } + startService() + } + return Service.START_NOT_STICKY + } + + fun onBind(intent: Intent): IBinder { + return binder + } + + fun onDestroy() { + binder.close() + } + + fun onRevoke() { + stopService() + } + + fun writeLog(message: String) { + binder.broadcast { + it.onServiceWriteLog(message) + } + } + +} \ No newline at end of file diff --git a/android/app/src/main/kotlin/com/hiddify/hiddify/bg/VPNService.kt b/android/app/src/main/kotlin/com/hiddify/hiddify/bg/VPNService.kt index 1d48e2f..fd3df14 100755 --- a/android/app/src/main/kotlin/com/hiddify/hiddify/bg/VPNService.kt +++ b/android/app/src/main/kotlin/com/hiddify/hiddify/bg/VPNService.kt @@ -47,17 +47,19 @@ class VPNService : VpnService(), PlatformInterfaceWrapper { } override fun autoDetectInterfaceControl(fd: Int) { - protect(fd) + Log.d(TAG, "🛡️ autoDetectInterfaceControl 被调用, fd=$fd") + val result = protect(fd) + Log.d(TAG, "🛡️ protect(fd=$fd) 返回: $result") } var systemProxyAvailable = false var systemProxyEnabled = false fun addIncludePackage(builder: Builder, packageName: String) { - if (packageName == this.packageName) { + if (packageName == this.packageName) { Log.d("VpnService","Cannot include myself: $packageName") return } - try { + try { Log.d("VpnService","Including $packageName") builder.addAllowedApplication(packageName) } catch (e: NameNotFoundException) { @@ -75,6 +77,10 @@ class VPNService : VpnService(), PlatformInterfaceWrapper { override fun openTun(options: TunOptions): Int { if (prepare(this) != null) error("android: missing vpn permission") + Log.d(TAG, "🔧 openTun 被调用") + Log.d(TAG, " MTU: ${options.mtu}") + Log.d(TAG, " AutoRoute: ${options.autoRoute}") + val builder = Builder() .setSession("sing-box") .setMtu(options.mtu) @@ -128,50 +134,87 @@ class VPNService : VpnService(), PlatformInterfaceWrapper { } } else { val inet4RouteAddress = options.inet4RouteRange + Log.d(TAG, "📍 Android <13: 配置IPv4路由") if (inet4RouteAddress.hasNext()) { + Log.d(TAG, "✅ 找到IPv4路由配置,开始添加...") while (inet4RouteAddress.hasNext()) { val address = inet4RouteAddress.next() + Log.d(TAG, " 添加路由: ${address.address()}/${address.prefix()}") builder.addRoute(address.address(), address.prefix()) } + } else { + // ⚠️ 如果没有指定路由,添加默认路由 + Log.w(TAG, "⚠️ 没有IPv4路由配置,添加默认路由 0.0.0.0/0") + builder.addRoute("0.0.0.0", 0) } val inet6RouteAddress = options.inet6RouteRange if (inet6RouteAddress.hasNext()) { + Log.d(TAG, "✅ 找到IPv6路由配置,开始添加...") while (inet6RouteAddress.hasNext()) { val address = inet6RouteAddress.next() + Log.d(TAG, " 添加IPv6路由: ${address.address()}/${address.prefix()}") builder.addRoute(address.address(), address.prefix()) } } } + Log.d(TAG, "📱 包过滤配置:") + Log.d(TAG, " perAppProxyEnabled: ${Settings.perAppProxyEnabled}") + Log.d(TAG, " 当前应用包名: $packageName") + if (Settings.perAppProxyEnabled) { val appList = Settings.perAppProxyList + Log.d(TAG, " ✅ 使用应用级代理,模式: ${Settings.perAppProxyMode}") + Log.d(TAG, " 📋 应用列表数量: ${appList.size}") if (Settings.perAppProxyMode == PerAppProxyMode.INCLUDE) { + Log.d(TAG, " 🔵 INCLUDE模式 - 只有以下应用使用VPN:") appList.forEach { + Log.d(TAG, " - $it") addIncludePackage(builder,it) } + Log.d(TAG, " - $packageName (本应用)") addIncludePackage(builder,packageName) } else { + Log.d(TAG, " 🔴 EXCLUDE模式 - 以下应用不使用VPN:") appList.forEach { + Log.d(TAG, " - $it") addExcludePackage(builder,it) } - //addExcludePackage(builder,packageName) + // 不排除本应用,让libcore能正常工作 + // Log.d(TAG, " ⚠️ 本应用也排除VPN") + // addExcludePackage(builder,packageName) + Log.d(TAG, " ℹ️ 本应用不在排除列表") } } else { + Log.d(TAG, " ⚙️ 使用配置文件的包过滤规则") val includePackage = options.includePackage if (includePackage.hasNext()) { + Log.d(TAG, " 🔵 INCLUDE列表:") while (includePackage.hasNext()) { - addIncludePackage(builder,includePackage.next()) + val pkg = includePackage.next() + Log.d(TAG, " - $pkg") + addIncludePackage(builder,pkg) } + } else { + Log.d(TAG, " ℹ️ 无INCLUDE规则") } + val excludePackage = options.excludePackage if (excludePackage.hasNext()) { + Log.d(TAG, " 🔴 EXCLUDE列表:") while (excludePackage.hasNext()) { - addExcludePackage(builder,excludePackage.next()) + val pkg = excludePackage.next() + Log.d(TAG, " - $pkg") + addExcludePackage(builder,pkg) } + } else { + Log.d(TAG, " ℹ️ 无EXCLUDE规则") } - //addExcludePackage(builder,packageName) - + // 不排除本应用,让libcore能正常工作 + // Log.d(TAG, " ⚠️ 始终排除本应用: $packageName") + // addExcludePackage(builder,packageName) + } } diff --git a/lib/app/common/app_config.dart b/lib/app/common/app_config.dart index 01b00d0..40a6615 100755 --- a/lib/app/common/app_config.dart +++ b/lib/app/common/app_config.dart @@ -3,10 +3,13 @@ import '../services/api_service/kr_api.user.dart'; import '../utils/kr_update_util.dart'; import '../utils/kr_secure_storage.dart'; import '../utils/kr_log_util.dart'; +import '../services/singbox_imp/kr_sing_box_imp.dart'; import 'dart:async'; import 'dart:convert'; +import 'dart:io'; import 'dart:math'; import 'package:dio/dio.dart'; +import 'package:dio/io.dart'; import 'package:flutter/foundation.dart'; /// 协议配置 @@ -54,7 +57,27 @@ class KRDomain { static Map _domainResponseTimes = {}; // 域名响应时间记录 static Map _domainLastCheck = {}; // 域名最后检测时间 static const int _domainCacheDuration = 300; // 域名缓存时间(秒) - static final Dio _dio = Dio(); // Dio 实例 + + // Dio 实例及初始化 + static final Dio _dio = (() { + final dio = Dio(); + // 🔧 配置HttpClientAdapter使用sing-box的mixed代理 + dio.httpClientAdapter = IOHttpClientAdapter( + createHttpClient: () { + final client = HttpClient(); + client.findProxy = (url) { + final proxyConfig = KRSingBoxImp.instance.kr_buildProxyRule(); + KRLogUtil.kr_i( + '🔍 KRDomain 请求使用代理: $proxyConfig, url: $url', + tag: 'KRDomain', + ); + return proxyConfig; + }; + return client; + }, + ); + return dio; + })(); /// API 域名 static String get kr_api => kr_currentDomain; @@ -1032,12 +1055,13 @@ class AppConfig { /// 请求域名地址 /// 基础url + /// // static String baseUrl = "http://103.112.98.72:8088"; /// 请求域名地址调试模式 String get baseUrl { if (kDebugMode) { - return "https://api.maodag.top"; + return "http://154.12.35.103:8080"; } return "${KRProtocol.kr_https}://${KRDomain.kr_api}"; } diff --git a/lib/app/network/http_util.dart b/lib/app/network/http_util.dart index 921b87c..d96ca9a 100755 --- a/lib/app/network/http_util.dart +++ b/lib/app/network/http_util.dart @@ -1,7 +1,8 @@ import 'dart:convert'; -import 'dart:io' show Platform; +import 'dart:io'; import 'package:dio/dio.dart'; +import 'package:dio/io.dart'; // import 'package:flutter_easyloading/flutter_easyloading.dart'; // 已替换为自定义组件 import 'package:flutter_loggy_dio/flutter_loggy_dio.dart'; @@ -11,6 +12,7 @@ import 'package:kaer_with_panels/app/common/app_run_data.dart'; import 'package:kaer_with_panels/app/network/base_response.dart'; import 'package:kaer_with_panels/app/localization/kr_language_utils.dart'; import 'package:kaer_with_panels/app/utils/kr_common_util.dart'; +import 'package:kaer_with_panels/app/services/singbox_imp/kr_sing_box_imp.dart'; import 'package:kaer_with_panels/app/services/kr_site_config_service.dart'; // import 'package:crypto/crypto.dart'; @@ -44,6 +46,7 @@ class HttpUtil { /// 对dio进行配置 void initDio() { + KRLogUtil.kr_i('🚀 HttpUtil.initDio() 开始初始化', tag: 'HttpUtil'); // 不使用 Loggy,改用自定义简洁拦截器 _dio.interceptors.add(_KRSimpleHttpInterceptor()); _dio.options.baseUrl = AppConfig.getInstance().baseUrl; @@ -67,6 +70,26 @@ class HttpUtil { _dio.options.validateStatus = (status) { return status != null && status >= 200 && status < 500; }; + + // 🔧 配置HttpClientAdapter 优先走本地 sing-box mixed 端口, + // 若代理不可用则回退到直连 + KRLogUtil.kr_i('🔧 配置 HttpClientAdapter...', tag: 'HttpUtil'); + _dio.httpClientAdapter = IOHttpClientAdapter( + createHttpClient: () { + KRLogUtil.kr_i('📱 createHttpClient 回调被调用', tag: 'HttpUtil'); + final client = HttpClient(); + client.findProxy = (url) { + final proxyConfig = KRSingBoxImp.instance.kr_buildProxyRule(); + KRLogUtil.kr_i( + '🔍 findProxy 被调用, url: $url, proxy: $proxyConfig', + tag: 'HttpUtil', + ); + return proxyConfig; + }; + return client; + }, + ); + KRLogUtil.kr_i('✅ HttpUtil.initDio() 初始化完成', tag: 'HttpUtil'); } /// 更新baseUrl diff --git a/lib/app/services/api_service/kr_auth_api.dart b/lib/app/services/api_service/kr_auth_api.dart index eead726..71c4955 100755 --- a/lib/app/services/api_service/kr_auth_api.dart +++ b/lib/app/services/api_service/kr_auth_api.dart @@ -1,6 +1,7 @@ -import 'dart:io'; +import 'dart:io' as io; import 'dart:math'; import 'dart:convert'; +import 'package:dio/io.dart' as dio_io; import 'package:fpdart/fpdart.dart'; import 'package:get/get.dart'; @@ -20,6 +21,7 @@ import '../kr_device_info_service.dart'; import '../kr_site_config_service.dart'; import '../../common/app_config.dart'; import 'package:dio/dio.dart' as dio; +import 'package:kaer_with_panels/app/services/singbox_imp/kr_sing_box_imp.dart'; class KRAuthApi { /// 检查账号是否已注册(仅支持邮箱) @@ -227,6 +229,24 @@ class KRAuthApi { // 使用 Dio 直接发送请求(因为需要特殊的加密处理) final dioInstance = dio.Dio(); + + // 🔧 配置HttpClientAdapter优先使用本地 sing-box mixed 端口, + // 失败时退回直连 + dioInstance.httpClientAdapter = dio_io.IOHttpClientAdapter( + createHttpClient: () { + final client = io.HttpClient(); + client.findProxy = (url) { + final proxyConfig = KRSingBoxImp.instance.kr_buildProxyRule(); + KRLogUtil.kr_i( + '🔍 KRAuthApi 请求使用代理: $proxyConfig, url: $url', + tag: 'KRAuthApi', + ); + return proxyConfig; + }; + return client; + }, + ); + final baseUrl = AppConfig.getInstance().baseUrl; final url = '$baseUrl${Api.kr_deviceLogin}'; @@ -313,17 +333,17 @@ class KRAuthApi { } String _kr_getUserAgent() { - if (Platform.isAndroid) { + if (io.Platform.isAndroid) { return 'android'; - } else if (Platform.isIOS) { + } else if (io.Platform.isIOS) { return 'ios'; - } else if (Platform.isMacOS) { + } else if (io.Platform.isMacOS) { return 'mac'; - } else if (Platform.isWindows) { + } else if (io.Platform.isWindows) { return 'windows'; - } else if (Platform.isLinux) { + } else if (io.Platform.isLinux) { return 'linux'; - } else if (Platform.isFuchsia) { + } else if (io.Platform.isFuchsia) { return 'harmony'; } else { return 'unknown'; diff --git a/lib/app/services/kr_site_config_service.dart b/lib/app/services/kr_site_config_service.dart index ae7e3fa..bf8d726 100644 --- a/lib/app/services/kr_site_config_service.dart +++ b/lib/app/services/kr_site_config_service.dart @@ -1,8 +1,11 @@ +import 'dart:io'; import 'package:dio/dio.dart'; +import 'package:dio/io.dart'; import 'package:flutter/foundation.dart'; import '../model/response/kr_site_config.dart'; import '../common/app_config.dart'; import '../utils/kr_log_util.dart'; +import 'singbox_imp/kr_sing_box_imp.dart'; /// 网站配置服务 class KRSiteConfigService extends ChangeNotifier { @@ -13,6 +16,22 @@ class KRSiteConfigService extends ChangeNotifier { _dio.options.connectTimeout = const Duration(seconds: 10); _dio.options.sendTimeout = const Duration(seconds: 10); _dio.options.receiveTimeout = const Duration(seconds: 10); + + // 🔧 配置HttpClientAdapter使用sing-box的mixed代理 + _dio.httpClientAdapter = IOHttpClientAdapter( + createHttpClient: () { + final client = HttpClient(); + client.findProxy = (url) { + final proxyConfig = KRSingBoxImp.instance.kr_buildProxyRule(); + KRLogUtil.kr_i( + '🔍 KRSiteConfigService 请求使用代理: $proxyConfig, url: $url', + tag: 'KRSiteConfigService', + ); + return proxyConfig; + }; + return client; + }, + ); } KRSiteConfig? _siteConfig; diff --git a/lib/app/services/singbox_imp/kr_sing_box_imp.dart b/lib/app/services/singbox_imp/kr_sing_box_imp.dart index 759c025..8725b89 100755 --- a/lib/app/services/singbox_imp/kr_sing_box_imp.dart +++ b/lib/app/services/singbox_imp/kr_sing_box_imp.dart @@ -97,6 +97,36 @@ class KRSingBoxImp { /// Stream 订阅管理器 final List> _kr_subscriptions = []; + /// 当前混合代理端口是否就绪 + bool get kr_isProxyReady => kr_status.value is SingboxStarted; + + String? _lastProxyRule; + + /// 构建 Dart HttpClient 可识别的代理规则字符串 + /// + /// 当 sing-box 尚未启动时返回 `DIRECT`,启动后返回 + /// `PROXY 127.0.0.1:; DIRECT`,以便在代理不可用时自动回落。 + String kr_buildProxyRule({bool includeDirectFallback = true}) { + if (!kr_isProxyReady) { + const directRule = 'DIRECT'; + if (_lastProxyRule != directRule) { + KRLogUtil.kr_i('⏳ sing-box 未就绪,使用 DIRECT 直连', tag: 'SingBox'); + _lastProxyRule = directRule; + } + return directRule; + } + final proxyRule = StringBuffer('PROXY 127.0.0.1:$kr_port'); + if (includeDirectFallback) { + proxyRule.write('; DIRECT'); + } + final ruleString = proxyRule.toString(); + if (_lastProxyRule != ruleString) { + KRLogUtil.kr_i('🛠️ 使用代理规则: $ruleString', tag: 'SingBox'); + _lastProxyRule = ruleString; + } + return ruleString; + } + /// 初始化 Future init() async { try { @@ -426,8 +456,10 @@ class KRSingBoxImp { kr_outbounds = outbounds; - final map = {}; - map["outbounds"] = kr_outbounds; + // 只保存 outbounds,Mobile.buildConfig() 会添加其他配置 + final map = { + "outbounds": kr_outbounds + }; final file = _file(kr_configName); final temp = _tempFile(kr_configName); diff --git a/lib/main.dart b/lib/main.dart index c558f1a..e7b964d 100755 --- a/lib/main.dart +++ b/lib/main.dart @@ -14,10 +14,9 @@ import 'package:kaer_with_panels/app/localization/kr_language_utils.dart'; import 'package:kaer_with_panels/app/routes/app_pages.dart'; import 'package:kaer_with_panels/app/utils/kr_window_manager.dart'; - -import 'app/utils/kr_secure_storage.dart'; +import 'app/services/singbox_imp/kr_sing_box_imp.dart'; import 'app/common/app_config.dart'; -import 'app/services/kr_site_config_service.dart'; +import 'app/utils/kr_secure_storage.dart'; // 全局导航键 final GlobalKey navigatorKey = GlobalKey(); @@ -25,6 +24,9 @@ final GlobalKey navigatorKey = GlobalKey(); void main() async { WidgetsFlutterBinding.ensureInitialized(); + // 为所有 HttpClient 请求统一注入代理策略 + HttpOverrides.global = KRProxyHttpOverrides(); + // 初始化 Hive await KRSecureStorage().kr_initHive(); @@ -131,3 +133,13 @@ Widget _myApp(GetxTranslations translations, Locale initialLocale) { // defaultTransition: Transition.fade, ); } + +/// 全局 HttpOverrides,确保所有 dart:io 网络请求遵循 sing-box 代理策略 +class KRProxyHttpOverrides extends HttpOverrides { + @override + HttpClient createHttpClient(SecurityContext? context) { + final client = super.createHttpClient(context); + client.findProxy = (uri) => KRSingBoxImp.instance.kr_buildProxyRule(); + return client; + } +} diff --git a/libcore/.gitattributes b/libcore/.gitattributes new file mode 100644 index 0000000..ad4e1a9 --- /dev/null +++ b/libcore/.gitattributes @@ -0,0 +1,2 @@ +*.h linguist-detectable=false +*.c linguist-detectable=false \ No newline at end of file diff --git a/libcore/.github/change_version.sh b/libcore/.github/change_version.sh new file mode 100755 index 0000000..3d037ac --- /dev/null +++ b/libcore/.github/change_version.sh @@ -0,0 +1,23 @@ +#! /bin/bash + +SED() { [[ "$OSTYPE" == "darwin"* ]] && sed -i '' "$@" || sed -i "$@"; } + +echo "previous version was $(git describe --tags $(git rev-list --tags --max-count=1))" +echo "WARNING: This operation will creates version tag and push to github" +read -p "Version? (provide the next x.y.z semver) : " TAG +echo $TAG +[[ "$TAG" =~ ^[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,2}(\.dev)?$ ]] || { echo "Incorrect tag. e.g., 1.2.3 or 1.2.3.dev"; exit 1; } +IFS="." read -r -a VERSION_ARRAY <<< "$TAG" +VERSION_STR="${VERSION_ARRAY[0]}.${VERSION_ARRAY[1]}.${VERSION_ARRAY[2]}" +BUILD_NUMBER=$(( ${VERSION_ARRAY[0]} * 10000 + ${VERSION_ARRAY[1]} * 100 + ${VERSION_ARRAY[2]} )) +echo "version: ${VERSION_STR}+${BUILD_NUMBER}" +SED -e "s|CFBundleVersion\s*[^<]*|CFBundleVersion${VERSION_STR}|" Info.plist +SED -e "s|CFBundleShortVersionString\s*[^<]*|CFBundleShortVersionString${VERSION_STR}|" Info.plist +SED "s|ENV VERSION=.*|ENV VERSION=v${TAG}|g" docker/Dockerfile +git add Info.plist docker/Dockerfile +git commit -m "release: version ${TAG}" +echo "creating git tag : v${TAG}" +git push +git tag v${TAG} +git push -u origin HEAD --tags +echo "Github Actions will detect the new tag and release the new version." \ No newline at end of file diff --git a/libcore/.github/workflows/build.yml b/libcore/.github/workflows/build.yml new file mode 100644 index 0000000..4afb0db --- /dev/null +++ b/libcore/.github/workflows/build.yml @@ -0,0 +1,303 @@ +name: Build +on: + workflow_call: + inputs: + upload-artifact: + type: boolean + default: true + tag-name: + type: string + default: "draft" + channel: + type: string + default: "dev" +env: + REGISTRY_IMAGE: ghcr.io/hiddify/hiddify-core + + +jobs: + update_wrt_hash: + permissions: write-all + runs-on: ubuntu-latest + if: ${{ inputs.channel=='prod' }} + steps: + - uses: actions/checkout@v4 + - run: | + git checkout -b main + curl -L -o hiddify-core.tar.gz https://codeload.github.com/hiddify/hiddify-core/tar.gz/${{ inputs.tag-name }} + HIDDIFY_CORE_WRT_HASH=$(sha256sum hiddify-core.tar.gz | cut -d' ' -f1) + github_ref_name="${{ inputs.tag-name }}" + IFS="." read -r -a VERSION_ARRAY <<< "${github_ref_name#v}" + VERSION_STR="${VERSION_ARRAY[0]}.${VERSION_ARRAY[1]}.${VERSION_ARRAY[2]}" + sed -i "s|PKG_VERSION:=.*|PKG_VERSION:=${VERSION_STR}|g" wrt/Makefile + sed -i "s|PKG_HASH:=.*|PKG_HASH:=${HIDDIFY_CORE_WRT_HASH}|g" wrt/Makefile + - uses: stefanzweifel/git-auto-commit-action@v5 + with: + commit_message: "Update WRT package HASH." + branch: main + # push_options: --force + build: + permissions: write-all + strategy: + fail-fast: false + matrix: + job: + - { name: 'hiddify-core-android', os: 'ubuntu-latest', target: 'android' } + - { name: 'hiddify-core-linux-amd64', os: 'ubuntu-20.04', target: 'linux-amd64' } + - { name: "hiddify-core-windows-amd64", os: 'ubuntu-latest', target: 'windows-amd64', aarch: 'x64' } + - { name: "hiddify-core-macos-universal", os: 'macos-12', target: 'macos-universal' } + - { name: "hiddify-core-ios", os: "macos-12", target: "ios" } + # linux custom + - {name: hiddify-cli-linux-amd64, goos: linux, goarch: amd64, goamd64: v1, target: 'linux-custom', os: 'ubuntu-20.04'} + - {name: hiddify-cli-linux-amd64-v3, goos: linux, goarch: amd64, goamd64: v3, target: 'linux-custom', os: 'ubuntu-20.04'} + - {name: hiddify-cli-linux-386, goos: linux, goarch: 386, target: 'linux-custom', os: 'ubuntu-20.04'} + - {name: hiddify-cli-linux-arm64, goos: linux, goarch: arm64, target: 'linux-custom', os: 'ubuntu-20.04'} + - {name: hiddify-cli-linux-armv5, goos: linux, goarch: arm, goarm: 5, target: 'linux-custom', os: 'ubuntu-20.04'} + - {name: hiddify-cli-linux-armv6, goos: linux, goarch: arm, goarm: 6, target: 'linux-custom', os: 'ubuntu-20.04'} + - {name: hiddify-cli-linux-armv7, goos: linux, goarch: arm, goarm: 7, target: 'linux-custom', os: 'ubuntu-20.04'} + - {name: hiddify-cli-linux-mips-softfloat, goos: linux, goarch: mips, gomips: softfloat, target: 'linux-custom', os: 'ubuntu-20.04'} + - {name: hiddify-cli-linux-mips-hardfloat, goos: linux, goarch: mips, gomips: hardfloat, target: 'linux-custom', os: 'ubuntu-20.04'} + - {name: hiddify-cli-linux-mipsel-softfloat, goos: linux, goarch: mipsle, gomips: softfloat, target: 'linux-custom', os: 'ubuntu-20.04'} + - {name: hiddify-cli-linux-mipsel-hardfloat, goos: linux, goarch: mipsle, gomips: hardfloat, target: 'linux-custom', os: 'ubuntu-20.04'} + - {name: hiddify-cli-linux-mips64, goos: linux, goarch: mips64, target: 'linux-custom', os: 'ubuntu-20.04'} + - {name: hiddify-cli-linux-mips64el, goos: linux, goarch: mips64le, target: 'linux-custom', os: 'ubuntu-20.04'} + - {name: hiddify-cli-linux-s390x, goos: linux, goarch: s390x, target: 'linux-custom', os: 'ubuntu-20.04'} + + runs-on: ${{ matrix.job.os }} + env: + GOOS: ${{ matrix.job.goos }} + GOARCH: ${{ matrix.job.goarch }} + GOAMD64: ${{ matrix.job.goamd64 }} + GOARM: ${{ matrix.job.goarm }} + GOMIPS: ${{ matrix.job.gomips }} + steps: + - name: Checkout + uses: actions/checkout@v3 + with: + fetch-depth: 0 + + - name: Setup Go + uses: actions/setup-go@v5 + with: + go-version-file: 'go.mod' + check-latest: false + + - name: Setup Java + if: startsWith(matrix.job.target,'android') + uses: actions/setup-java@v3 + with: + distribution: 'zulu' + java-version: '17' + + - name: Setup NDK + if: startsWith(matrix.job.target,'android') + uses: nttld/setup-ndk@v1.4.0 + id: setup-ndk + with: + ndk-version: r26b + add-to-path: true + local-cache: false + link-to-sdk: true + + - name: Setup MinGW + if: startsWith(matrix.job.target,'windows') + uses: egor-tensin/setup-mingw@v2 + with: + platform: ${{ matrix.job.aarch }} + - name: Setup macos + if: startsWith(matrix.job.target,'macos') || startsWith(matrix.job.target,'ios') + run: | + brew install create-dmg tree coreutils + + - name: Build + run: | + make -j$(($(nproc) + 1)) ${{ matrix.job.target }} + + - name: zip + run: | + tree + rm -f /*.h */*.h + rm ./hiddify-libcore*sources* ||echo "no source" + rm ./hiddify-libcore-macos-a*.dylib || echo "no macos arm and amd" + files=$(ls | grep -E '^(libcore\.(dll|so|dylib|aar)|webui|Libcore.xcframework|lib|HiddifyCli(\.exe)?)$') + echo tar -czvf ${{ matrix.job.name }}.tar.gz $files + tar -czvf ${{ matrix.job.name }}.tar.gz $files + + working-directory: bin + - uses: actions/upload-artifact@v4 + if: ${{ success() }} + with: + name: ${{ matrix.job.name }} + path: bin/*.tar.gz + retention-days: 1 + + + upload-prerelease: + permissions: write-all + if: ${{ inputs.upload-artifact }} + needs: [build] + runs-on: ubuntu-latest + steps: + - uses: actions/download-artifact@v4 + with: + merge-multiple: true + pattern: hiddify-* + path: bin/ + + - name: Display Files Structure + run: tree + working-directory: bin + + - name: Delete Current Release Assets + uses: 8Mi-Tech/delete-release-assets-action@main + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + tag: 'draft' + deleteOnlyFromDrafts: false + + - name: Create or Update Draft Release + uses: softprops/action-gh-release@v1 + if: ${{ success() }} + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + files: ./bin/*.tar.gz + name: 'draft' + tag_name: 'draft' + prerelease: true + + upload-release: + permissions: write-all + if: ${{ inputs.channel=='prod' }} + needs: [build] + runs-on: ubuntu-latest + steps: + - uses: actions/download-artifact@v4 + with: + merge-multiple: true + pattern: hiddify-* + path: bin/ + + - name: Display Files Structure + run: ls -R + working-directory: bin + + - name: Upload Release + uses: softprops/action-gh-release@v1 + if: ${{ success() }} + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + tag_name: ${{ inputs.tag-name }} + + files: bin/*.tar.gz + + + + + + + + + + + + make-upload-docker: + permissions: write-all + if: ${{ inputs.channel=='prod' }} + needs: [upload-release] + + runs-on: ubuntu-latest + strategy: + fail-fast: true + matrix: + platform: + - linux/amd64 + # - linux/arm/v5 + - linux/arm/v6 + - linux/arm/v7 + - linux/arm64 + - linux/386 + # - linux/ppc64le + # - linux/riscv64 + - linux/s390x + steps: + - name: Checkout + uses: actions/checkout@v3 + with: + fetch-depth: 0 + - name: Prepare + run: | + platform=${{ matrix.platform }} + echo "PLATFORM_PAIR=${platform//\//-}" >> $GITHUB_ENV + - name: Setup QEMU + uses: docker/setup-qemu-action@v3 + - name: Setup Docker Buildx + uses: docker/setup-buildx-action@v3 + - name: Login to GitHub Container Registry + uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.repository_owner }} + password: ${{ secrets.GITHUB_TOKEN }} + - name: Docker meta + id: meta + uses: docker/metadata-action@v5 + with: + images: ${{ env.REGISTRY_IMAGE }} + - name: Build and push by digest + id: build + uses: docker/build-push-action@v6 + with: + platforms: ${{ matrix.platform }} + context: ./docker/ + build-args: | + BUILDKIT_CONTEXT_KEEP_GIT_DIR=1 + labels: ${{ steps.meta.outputs.labels }} + outputs: type=image,name=${{ env.REGISTRY_IMAGE }},push-by-digest=true,name-canonical=true,push=true + - name: Export digest + run: | + mkdir -p /tmp/digests + digest="${{ steps.build.outputs.digest }}" + touch "/tmp/digests/${digest#sha256:}" + - name: Upload digest + uses: actions/upload-artifact@v4 + with: + name: digests-${{ env.PLATFORM_PAIR }} + path: /tmp/digests/* + if-no-files-found: error + retention-days: 1 + merge: + permissions: write-all + runs-on: ubuntu-latest + needs: + - make-upload-docker + env: + LATEST: ${{ endsWith(inputs.tag-name , 'dev') && 'beta' ||'latest'}} + steps: + - name: Download digests + uses: actions/download-artifact@v4 + with: + path: /tmp/digests + pattern: digests-* + merge-multiple: true + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + - name: Login to GitHub Container Registry + uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.repository_owner }} + password: ${{ secrets.GITHUB_TOKEN }} + - name: Create manifest list and push + working-directory: /tmp/digests + run: | + docker buildx imagetools create \ + -t "${{ env.REGISTRY_IMAGE }}:${{ env.LATEST }}" \ + -t "${{ env.REGISTRY_IMAGE }}:${{ inputs.tag-name }}" \ + $(printf '${{ env.REGISTRY_IMAGE }}@sha256:%s ' *) + - name: Inspect image + + run: | + docker buildx imagetools inspect ${{ env.REGISTRY_IMAGE }}:${{ env.LATEST }} + docker buildx imagetools inspect ${{ env.REGISTRY_IMAGE }}:${{ inputs.tag-name }} diff --git a/libcore/.github/workflows/ci.yml b/libcore/.github/workflows/ci.yml new file mode 100644 index 0000000..1711997 --- /dev/null +++ b/libcore/.github/workflows/ci.yml @@ -0,0 +1,32 @@ +name: CI +on: + pull_request: + paths-ignore: + - '**.md' + - 'docs/**' + - '.vscode/' + - 'appcast.xml' + push: + branches: + - main + - dev + - android-fix-action-bug + paths-ignore: + - '**.md' + - 'docs/**' + - '.vscode/' + - 'appcast.xml' + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + run: + uses: ./.github/workflows/build.yml + secrets: inherit + permissions: write-all + if: "${{!contains(github.event.head_commit.message, 'release: version')}}" + with: + upload-artifact: ${{ github.event_name == 'push' }} + diff --git a/libcore/.github/workflows/release.yml b/libcore/.github/workflows/release.yml new file mode 100644 index 0000000..8ad5700 --- /dev/null +++ b/libcore/.github/workflows/release.yml @@ -0,0 +1,20 @@ +name: Release +on: + push: + tags: + - 'v[0-9]+.[0-9]+.[0-9]+' + - 'v[0-9]+.[0-9]+.[0-9]+.*' + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + build-release: + uses: ./.github/workflows/build.yml + secrets: inherit + permissions: write-all + with: + upload-artifact: true + tag-name: "${{ github.ref_name }}" + channel: "${{ github.ref_type == 'tag' && endsWith(github.ref_name, 'dev') && 'dev' || github.ref_type != 'tag' && 'dev' || 'prod' }}" diff --git a/libcore/.gitignore b/libcore/.gitignore new file mode 100644 index 0000000..545c18c --- /dev/null +++ b/libcore/.gitignore @@ -0,0 +1,12 @@ +/bin/* +!/bin/.gitkeep +.build +.idea +cert +**/*.log +.DS_Store + +**/*.syso +node_modules +*.db +*.json \ No newline at end of file diff --git a/libcore/.prettierrc b/libcore/.prettierrc new file mode 100644 index 0000000..7f51a41 --- /dev/null +++ b/libcore/.prettierrc @@ -0,0 +1,10 @@ +{ + "overrides": [ + { + "files": ".github/**", + "options": { + "singleQuote": true + } + } + ] +} \ No newline at end of file diff --git a/libcore/.stignore b/libcore/.stignore new file mode 100644 index 0000000..9bd8bad --- /dev/null +++ b/libcore/.stignore @@ -0,0 +1,9 @@ +.git + +.build +.idea + +**/*.log +.DS_Store + +**/*.syso \ No newline at end of file diff --git a/libcore/CONTRIBUTING.md b/libcore/CONTRIBUTING.md new file mode 100644 index 0000000..65b5865 --- /dev/null +++ b/libcore/CONTRIBUTING.md @@ -0,0 +1,26 @@ +Hiddify uses [Go](https://go.dev), make sure that you have the correct version installed before starting development. You can use the following commands to check your installed version: + + +```shell +$ go version + +# example response +go version go1.21.1 darwin/arm64 +``` + +### Working with the Go Code + +> if you're not interested in building/contributing to the Go code, you can skip this section + +The Go code for Hiddify can be found in the `libcore` folder, as a [git submodule](https://git-scm.com/book/en/v2/Git-Tools-Submodules) and in [core repository](https://github.com/hiddify/hiddify-next-core). The entrypoints for the desktop version are available in the [`libcore/custom`](https://github.com/hiddify/hiddify-next-core/tree/main/custom) folder and for the mobile version they can be found in the [`libcore/mobile`](https://github.com/hiddify/hiddify-next-core/tree/main/mobile) folder. + +For the desktop version, we have to compile the Go code into a C shared library. We are providing a Makefile to generate the C shared libraries for all operating systems. The following Make commands will build libcore and copy the resulting output in [`libcore/bin`](https://github.com/hiddify/hiddify-next-core/tree/main/bin): + +- `make windows-amd64` +- `make linux-amd64` +- `make macos-universal` + +For the mobile version, we are using the [`gomobile`](https://github.com/golang/go/wiki/Mobile) tools. The following Make commands will build libcore for Android and iOS and copy the resulting output in [`libcore/bin`](https://github.com/hiddify/hiddify-next-core/tree/main/bin): + +- `make android` +- `make ios` diff --git a/libcore/Info.plist b/libcore/Info.plist new file mode 100644 index 0000000..8da5f7e --- /dev/null +++ b/libcore/Info.plist @@ -0,0 +1,50 @@ + + + + + AvailableLibraries + + + BinaryPath + Libcore.framework/Libcore + LibraryIdentifier + ios-arm64_x86_64-simulator + LibraryPath + Libcore.framework + SupportedArchitectures + + arm64 + x86_64 + + SupportedPlatform + ios + SupportedPlatformVariant + simulator + + + BinaryPath + Libcore.framework/Libcore + LibraryIdentifier + ios-arm64 + LibraryPath + Libcore.framework + SupportedArchitectures + + arm64 + + SupportedPlatform + ios + + + CFBundlePackageType + XFWK + XCFrameworkFormatVersion + 1.0 + CFBundleIdentifier + ios.libcore.hiddify + CFBundleShortVersionString3.1.7 + CFBundleVersion3.1.7 + MinimumOSVersion + 15.0 + + \ No newline at end of file diff --git a/libcore/LICENSE.md b/libcore/LICENSE.md new file mode 100644 index 0000000..3110493 --- /dev/null +++ b/libcore/LICENSE.md @@ -0,0 +1,699 @@ + +# GNU GENERAL PUBLIC LICENSE v3 + +## Summary: +Additional Permissions and Restrictions Under GNU GPL Version 3 Section 7 +- If you use extends this code, you should directly fork it from github. + +- The forks of the app are not allowed to be listed on F-Droid or other app stores under the original name or original design. + +- Any forks should be published open-source under the same license. + +- Prior consent is required to publish a fork or utilize any part of this repository (github.com/hiddify/hiddify-next and github.com/hiddify/hiddify-next-core) in an application intended for publication on the App Store or for iOS/macOS platforms. (We reserve the right to modify this requirement in the future after completing development for iOS and macOS). +- You need prior consent to publish a fork or use any part of this code in an application published in AppStore or publish for iOS or macOS. (We reserve the right to modify this requirement in the future after completing development for iOS and macOS). +- You are free to: + - Share — copy and redistribute the material in any medium or format with + - Adapt — remix, transform, and build upon the material +- Under the following terms: + - Attribution — You must give appropriate credit, provide a link to the license, and indicate if changes were made. You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use. + + - NonCommercial — You may not use the material for commercial purposes. You can not even include ads in it. + + - ShareAlike — If you remix, transform, or build upon the material, you must distribute your contributions under the same license as the original. + + - Prior consent is required before utilizing any portion of this code for integration into an application intended for the App Store. + + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/libcore/Makefile b/libcore/Makefile new file mode 100644 index 0000000..45213b0 --- /dev/null +++ b/libcore/Makefile @@ -0,0 +1,107 @@ +.ONESHELL: +PRODUCT_NAME=libcore +BASENAME=$(PRODUCT_NAME) +BINDIR=bin +LIBNAME=$(PRODUCT_NAME) +CLINAME=HiddifyCli + +BRANCH=$(shell git branch --show-current) +VERSION=$(shell git describe --tags || echo "unknown version") +ifeq ($(OS),Windows_NT) +Not available for Windows! use bash in WSL +endif + +TAGS=with_gvisor,with_quic,with_wireguard,with_ech,with_utls,with_clash_api,with_grpc +IOS_ADD_TAGS=with_dhcp,with_low_memory,with_conntrack +GOBUILDLIB=CGO_ENABLED=1 go build -trimpath -tags $(TAGS) -ldflags="-w -s" -buildmode=c-shared +GOBUILDSRV=CGO_ENABLED=1 go build -ldflags "-s -w" -trimpath -tags $(TAGS) + +.PHONY: protos +protos: + protoc --go_out=./ --go-grpc_out=./ --proto_path=hiddifyrpc hiddifyrpc/*.proto + protoc --js_out=import_style=commonjs,binary:./extension/html/rpc/ --grpc-web_out=import_style=commonjs,mode=grpcwebtext:./extension/html/rpc/ --proto_path=hiddifyrpc hiddifyrpc/*.proto + npx browserify extension/html/rpc/extension.js >extension/html/rpc.js + + +lib_install: + go install -v github.com/sagernet/gomobile/cmd/gomobile@v0.1.1 + go install -v github.com/sagernet/gomobile/cmd/gobind@v0.1.1 + npm install + +headers: + go build -buildmode=c-archive -o $(BINDIR)/$(LIBNAME).h ./custom + +android: lib_install + gomobile bind -v -androidapi=21 -javapkg=io.nekohasekai -libname=box -tags=$(TAGS) -trimpath -target=android -o $(BINDIR)/$(LIBNAME).aar github.com/sagernet/sing-box/experimental/libbox ./mobile + +ios-full: lib_install + gomobile bind -v -target ios,iossimulator,tvos,tvossimulator,macos -libname=box -tags=$(TAGS),$(IOS_ADD_TAGS) -trimpath -ldflags="-w -s" -o $(BINDIR)/$(PRODUCT_NAME).xcframework github.com/sagernet/sing-box/experimental/libbox ./mobile + mv $(BINDIR)/$(PRODUCT_NAME).xcframework $(BINDIR)/$(LIBNAME).xcframework + cp Libcore.podspec $(BINDIR)/$(LIBNAME).xcframework/ + +ios: lib_install + gomobile bind -v -target ios -libname=box -tags=$(TAGS),$(IOS_ADD_TAGS) -trimpath -ldflags="-w -s" -o $(BINDIR)/Libcore.xcframework github.com/sagernet/sing-box/experimental/libbox ./mobile + cp Info.plist $(BINDIR)/Libcore.xcframework/ + + +webui: + curl -L -o webui.zip https://github.com/hiddify/Yacd-meta/archive/gh-pages.zip + unzip -d ./ -q webui.zip + rm webui.zip + rm -rf bin/webui + mv Yacd-meta-gh-pages bin/webui + +.PHONY: build +windows-amd64: + curl http://localhost:18020/exit || echo "exited" + env GOOS=windows GOARCH=amd64 CC=x86_64-w64-mingw32-gcc $(GOBUILDLIB) -o $(BINDIR)/$(LIBNAME).dll ./custom + go install -mod=readonly github.com/akavel/rsrc@latest ||echo "rsrc error in installation" + go run ./cli tunnel exit + cp $(BINDIR)/$(LIBNAME).dll ./$(LIBNAME).dll + $$(go env GOPATH)/bin/rsrc -ico ./assets/hiddify-cli.ico -o ./cli/bydll/cli.syso ||echo "rsrc error in syso" + env GOOS=windows GOARCH=amd64 CC=x86_64-w64-mingw32-gcc CGO_LDFLAGS="$(LIBNAME).dll" $(GOBUILDSRV) -o $(BINDIR)/$(CLINAME).exe ./cli/bydll + rm ./$(LIBNAME).dll + make webui + + +linux-amd64: + mkdir -p $(BINDIR)/lib + env GOOS=linux GOARCH=amd64 $(GOBUILDLIB) -o $(BINDIR)/lib/$(LIBNAME).so ./custom + mkdir lib + cp $(BINDIR)/lib/$(LIBNAME).so ./lib/$(LIBNAME).so + env GOOS=linux GOARCH=amd64 CGO_LDFLAGS="./lib/$(LIBNAME).so" $(GOBUILDSRV) -o $(BINDIR)/$(CLINAME) ./cli/bydll + rm -rf ./lib + chmod +x $(BINDIR)/$(CLINAME) + make webui + + +linux-custom: + mkdir -p $(BINDIR)/ + #env GOARCH=mips $(GOBUILDSRV) -o $(BINDIR)/$(CLINAME) ./cli/ + go build -ldflags "-s -w" -trimpath -tags $(TAGS) -o $(BINDIR)/$(CLINAME) ./cli/ + chmod +x $(BINDIR)/$(CLINAME) + make webui + +macos-amd64: + env GOOS=darwin GOARCH=amd64 CGO_CFLAGS="-mmacosx-version-min=10.11" CGO_LDFLAGS="-mmacosx-version-min=10.11" CGO_ENABLED=1 go build -trimpath -tags $(TAGS),$(IOS_ADD_TAGS) -buildmode=c-shared -o $(BINDIR)/$(LIBNAME)-amd64.dylib ./custom +macos-arm64: + env GOOS=darwin GOARCH=arm64 CGO_CFLAGS="-mmacosx-version-min=10.11" CGO_LDFLAGS="-mmacosx-version-min=10.11" CGO_ENABLED=1 go build -trimpath -tags $(TAGS),$(IOS_ADD_TAGS) -buildmode=c-shared -o $(BINDIR)/$(LIBNAME)-arm64.dylib ./custom + +macos-universal: macos-amd64 macos-arm64 + lipo -create $(BINDIR)/$(LIBNAME)-amd64.dylib $(BINDIR)/$(LIBNAME)-arm64.dylib -output $(BINDIR)/$(LIBNAME).dylib + cp $(BINDIR)/$(LIBNAME).dylib ./$(LIBNAME).dylib + env GOOS=darwin GOARCH=amd64 CGO_CFLAGS="-mmacosx-version-min=10.11" CGO_LDFLAGS="-mmacosx-version-min=10.11" CGO_LDFLAGS="bin/$(LIBNAME).dylib" CGO_ENABLED=1 $(GOBUILDSRV) -o $(BINDIR)/$(CLINAME) ./cli/bydll + rm ./$(LIBNAME).dylib + chmod +x $(BINDIR)/$(CLINAME) + +clean: + rm $(BINDIR)/* + + + + +release: # Create a new tag for release. + @bash -c '.github/change_version.sh' + + + diff --git a/libcore/README.md b/libcore/README.md new file mode 100644 index 0000000..f5392d1 --- /dev/null +++ b/libcore/README.md @@ -0,0 +1,53 @@ +# hiddify-core + + +## Docker +To Run our docker image see https://github.com/hiddify/hiddify-core/pkgs/container/hiddify-core + +Docker +``` +docker pull ghcr.io/hiddify/hiddify-core:latest +``` + +Docker Compose +``` +git clone https://github.com/hiddify/hiddify-core +cd hiddify-core/docker +docker-compose up +``` + +## WRT +... + +## Extension + +An extension is something that can be added to hiddify application by a third party. It will add capability to modify configs, do some extra action, show and receive data from users. + +This extension will be shown in all Hiddify Platforms such as Android/macOS/Linux/Windows/iOS + +[Create an extension](https://github.com/hiddify/hiddify-app-example-extension) + +Features and Road map: + +- [x] Add Third Party Extension capability +- [x] Test Extension from Browser without any dependency to android/mac/.... `./cmd.sh extension` the open browser `https://127.0.0.1:12346` +- [x] Show Custom UI from Extension `github.com/hiddify/hiddify-core/extension.UpdateUI()` +- [x] Show Custom Dialog from Extension `github.com/hiddify/hiddify-core/extension.ShowDialog()` +- [x] Show Alert Dialog from Extension `github.com/hiddify/hiddify-core/extension.ShowMessage()` +- [x] Get Data from UI `github.com/hiddify/hiddify-core/extension.SubmitData()` +- [x] Save Extension Data from `e.Base.Data` +- [x] Load Extension Data to `e.Base.Data` +- [x] Disable / Enable Extension +- [x] Update user proxies before connecting `github.com/hiddify/hiddify-core/extension.BeforeAppConnect()` +- [x] Run Tiny Independent Instance `github.com/hiddify/hiddify-core/extension/sdk.RunInstance()` +- [x] Parse Any type of configs/url `github.com/hiddify/hiddify-core/extension/sdk.ParseConfig()` +- [ ] ToDo: Add Support for MultiLanguage Interface +- [ ] ToDo: Custom Extension Outbound +- [ ] ToDo: Custom Extension Inbound +- [ ] ToDo: Custom Extension ProxyConfig + + Demo Screenshots from HTML: + + image + image + diff --git a/libcore/assets/hiddify-cli.ico b/libcore/assets/hiddify-cli.ico new file mode 100644 index 0000000..65d4406 Binary files /dev/null and b/libcore/assets/hiddify-cli.ico differ diff --git a/libcore/bin/.gitkeep b/libcore/bin/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/libcore/bin/HiddifyCli b/libcore/bin/HiddifyCli deleted file mode 100755 index fcdd3e0..0000000 Binary files a/libcore/bin/HiddifyCli and /dev/null differ diff --git a/libcore/bin/libcore-sources.jar b/libcore/bin/libcore-sources.jar new file mode 100644 index 0000000..14ac7c5 Binary files /dev/null and b/libcore/bin/libcore-sources.jar differ diff --git a/libcore/bridge/bridge.go b/libcore/bridge/bridge.go new file mode 100644 index 0000000..cdd9659 --- /dev/null +++ b/libcore/bridge/bridge.go @@ -0,0 +1,36 @@ +// +build cgo +package bridge + +// #include "stdint.h" +// #include "include/dart_api_dl.c" +// +// // Go does not allow calling C function pointers directly. So we are +// // forced to provide a trampoline. +// bool GoDart_PostCObject(Dart_Port_DL port, Dart_CObject* obj) { +// return Dart_PostCObject_DL(port, obj); +// } +import "C" +import ( + "fmt" + "unsafe" +) + +func InitializeDartApi(api unsafe.Pointer) { + if C.Dart_InitializeApiDL(api) != 0 { + panic("failed to initialize Dart DL C API: version mismatch. " + + "must update include/ to match Dart SDK version") + } +} + +func SendStringToPort(port int64, msg string) { + var obj C.Dart_CObject + obj._type = C.Dart_CObject_kString + msg_obj := C.CString(msg) // go string -> char*s + // union type, we do a force conversion + ptr := unsafe.Pointer(&obj.value[0]) + *(**C.char)(ptr) = msg_obj + ret := C.GoDart_PostCObject(C.Dart_Port_DL(port), &obj) + if !ret { + fmt.Println("ERROR: post to port ", port, " failed", msg) + } +} diff --git a/libcore/bridge/bridge_stub.go b/libcore/bridge/bridge_stub.go new file mode 100644 index 0000000..be021a9 --- /dev/null +++ b/libcore/bridge/bridge_stub.go @@ -0,0 +1,11 @@ +//go:build !cgo +// +build !cgo + +package bridge + +import "unsafe" + +func InitializeDartApi(api unsafe.Pointer) { +} +func SendStringToPort(port int64, msg string) { +} diff --git a/libcore/bridge/include/BUILD.gn b/libcore/bridge/include/BUILD.gn new file mode 100644 index 0000000..2b10262 --- /dev/null +++ b/libcore/bridge/include/BUILD.gn @@ -0,0 +1,23 @@ +# Copyright (c) 2021, the Dart project authors. Please see the AUTHORS file +# for details. All rights reserved. Use of this source code is governed by a +# BSD-style license that can be found in the LICENSE file. + +import("../../sdk_args.gni") + +# This rule copies header files to include/ +copy("copy_headers") { + visibility = [ "../../sdk:copy_headers" ] + + sources = [ + "dart_api.h", + "dart_api_dl.c", + "dart_api_dl.h", + "dart_native_api.h", + "dart_tools_api.h", + "dart_version.h", + "internal/dart_api_dl_impl.h", + ] + + outputs = + [ "$root_out_dir/$dart_sdk_output/include/{{source_target_relative}}" ] +} diff --git a/libcore/bridge/include/analyze_snapshot_api.h b/libcore/bridge/include/analyze_snapshot_api.h new file mode 100644 index 0000000..38b58e0 --- /dev/null +++ b/libcore/bridge/include/analyze_snapshot_api.h @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2021, the Dart project authors. Please see the AUTHORS file + * for details. All rights reserved. Use of this source code is governed by a + * BSD-style license that can be found in the LICENSE file. + */ + +#ifndef RUNTIME_INCLUDE_ANALYZE_SNAPSHOT_API_H_ +#define RUNTIME_INCLUDE_ANALYZE_SNAPSHOT_API_H_ + +#include +#include + +namespace dart { +namespace snapshot_analyzer { +typedef struct { + const uint8_t* vm_snapshot_data; + const uint8_t* vm_snapshot_instructions; + const uint8_t* vm_isolate_data; + const uint8_t* vm_isolate_instructions; +} Dart_SnapshotAnalyzerInformation; + +void Dart_DumpSnapshotInformationAsJson( + const Dart_SnapshotAnalyzerInformation& info, + char** buffer, + intptr_t* buffer_length); + +} // namespace snapshot_analyzer +} // namespace dart + +#endif // RUNTIME_INCLUDE_ANALYZE_SNAPSHOT_API_H_ diff --git a/libcore/bridge/include/bin/dart_io_api.h b/libcore/bridge/include/bin/dart_io_api.h new file mode 100644 index 0000000..cc64797 --- /dev/null +++ b/libcore/bridge/include/bin/dart_io_api.h @@ -0,0 +1,69 @@ +// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +#ifndef RUNTIME_INCLUDE_BIN_DART_IO_API_H_ +#define RUNTIME_INCLUDE_BIN_DART_IO_API_H_ + +#include "dart_tools_api.h" + +namespace dart { +namespace bin { + +// Bootstraps 'dart:io'. +void BootstrapDartIo(); + +// Cleans up 'dart:io'. +void CleanupDartIo(); + +// Lets dart:io know where the system temporary directory is located. +// Currently only wired up on Android. +void SetSystemTempDirectory(const char* system_temp); + +// Tells the system whether to capture Stdout events. +void SetCaptureStdout(bool value); + +// Tells the system whether to capture Stderr events. +void SetCaptureStderr(bool value); + +// Should Stdout events be captured? +bool ShouldCaptureStdout(); + +// Should Stderr events be captured? +bool ShouldCaptureStderr(); + +// Set the executable name used by Platform.executable. +void SetExecutableName(const char* executable_name); + +// Set the arguments used by Platform.executableArguments. +void SetExecutableArguments(int script_index, char** argv); + +// Set dart:io implementation specific fields of Dart_EmbedderInformation. +void GetIOEmbedderInformation(Dart_EmbedderInformation* info); + +// Appropriate to assign to Dart_InitializeParams.file_open/read/write/close. +void* OpenFile(const char* name, bool write); +void ReadFile(uint8_t** data, intptr_t* file_len, void* stream); +void WriteFile(const void* buffer, intptr_t num_bytes, void* stream); +void CloseFile(void* stream); + +// Generates 'length' random bytes into 'buffer'. Returns true on success +// and false on failure. This is appropriate to assign to +// Dart_InitializeParams.entropy_source. +bool GetEntropy(uint8_t* buffer, intptr_t length); + +// Performs a lookup of the I/O Dart_NativeFunction with a specified 'name' and +// 'argument_count'. Returns NULL if no I/O native function with a matching +// name and parameter count is found. +Dart_NativeFunction LookupIONative(Dart_Handle name, + int argument_count, + bool* auto_setup_scope); + +// Returns the symbol for I/O native function 'nf'. Returns NULL if 'nf' is not +// a valid I/O native function. +const uint8_t* LookupIONativeSymbol(Dart_NativeFunction nf); + +} // namespace bin +} // namespace dart + +#endif // RUNTIME_INCLUDE_BIN_DART_IO_API_H_ diff --git a/libcore/bridge/include/dart_api.h b/libcore/bridge/include/dart_api.h new file mode 100644 index 0000000..1b39620 --- /dev/null +++ b/libcore/bridge/include/dart_api.h @@ -0,0 +1,4172 @@ +/* + * Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file + * for details. All rights reserved. Use of this source code is governed by a + * BSD-style license that can be found in the LICENSE file. + */ + +#ifndef RUNTIME_INCLUDE_DART_API_H_ +#define RUNTIME_INCLUDE_DART_API_H_ + +/** \mainpage Dart Embedding API Reference + * + * This reference describes the Dart Embedding API, which is used to embed the + * Dart Virtual Machine within C/C++ applications. + * + * This reference is generated from the header include/dart_api.h. + */ + +/* __STDC_FORMAT_MACROS has to be defined before including to + * enable platform independent printf format specifiers. */ +#ifndef __STDC_FORMAT_MACROS +#define __STDC_FORMAT_MACROS +#endif + +#include +#include +#include + +#if defined(__Fuchsia__) +#include +#endif + +#ifdef __cplusplus +#define DART_EXTERN_C extern "C" +#else +#define DART_EXTERN_C extern +#endif + +#if defined(__CYGWIN__) +#error Tool chain and platform not supported. +#elif defined(_WIN32) +#if defined(DART_SHARED_LIB) +#define DART_EXPORT DART_EXTERN_C __declspec(dllexport) +#else +#define DART_EXPORT DART_EXTERN_C +#endif +#else +#if __GNUC__ >= 4 +#if defined(DART_SHARED_LIB) +#define DART_EXPORT \ + DART_EXTERN_C __attribute__((visibility("default"))) __attribute((used)) +#else +#define DART_EXPORT DART_EXTERN_C +#endif +#else +#error Tool chain not supported. +#endif +#endif + +#if __GNUC__ +#define DART_WARN_UNUSED_RESULT __attribute__((warn_unused_result)) +#define DART_DEPRECATED(msg) __attribute__((deprecated(msg))) +#elif _MSC_VER +#define DART_WARN_UNUSED_RESULT _Check_return_ +#define DART_DEPRECATED(msg) __declspec(deprecated(msg)) +#else +#define DART_WARN_UNUSED_RESULT +#define DART_DEPRECATED(msg) +#endif + +/* + * ======= + * Handles + * ======= + */ + +/** + * An isolate is the unit of concurrency in Dart. Each isolate has + * its own memory and thread of control. No state is shared between + * isolates. Instead, isolates communicate by message passing. + * + * Each thread keeps track of its current isolate, which is the + * isolate which is ready to execute on the current thread. The + * current isolate may be NULL, in which case no isolate is ready to + * execute. Most of the Dart apis require there to be a current + * isolate in order to function without error. The current isolate is + * set by any call to Dart_CreateIsolateGroup or Dart_EnterIsolate. + */ +typedef struct _Dart_Isolate* Dart_Isolate; +typedef struct _Dart_IsolateGroup* Dart_IsolateGroup; + +/** + * An object reference managed by the Dart VM garbage collector. + * + * Because the garbage collector may move objects, it is unsafe to + * refer to objects directly. Instead, we refer to objects through + * handles, which are known to the garbage collector and updated + * automatically when the object is moved. Handles should be passed + * by value (except in cases like out-parameters) and should never be + * allocated on the heap. + * + * Most functions in the Dart Embedding API return a handle. When a + * function completes normally, this will be a valid handle to an + * object in the Dart VM heap. This handle may represent the result of + * the operation or it may be a special valid handle used merely to + * indicate successful completion. Note that a valid handle may in + * some cases refer to the null object. + * + * --- Error handles --- + * + * When a function encounters a problem that prevents it from + * completing normally, it returns an error handle (See Dart_IsError). + * An error handle has an associated error message that gives more + * details about the problem (See Dart_GetError). + * + * There are four kinds of error handles that can be produced, + * depending on what goes wrong: + * + * - Api error handles are produced when an api function is misused. + * This happens when a Dart embedding api function is called with + * invalid arguments or in an invalid context. + * + * - Unhandled exception error handles are produced when, during the + * execution of Dart code, an exception is thrown but not caught. + * Prototypically this would occur during a call to Dart_Invoke, but + * it can occur in any function which triggers the execution of Dart + * code (for example, Dart_ToString). + * + * An unhandled exception error provides access to an exception and + * stacktrace via the functions Dart_ErrorGetException and + * Dart_ErrorGetStackTrace. + * + * - Compilation error handles are produced when, during the execution + * of Dart code, a compile-time error occurs. As above, this can + * occur in any function which triggers the execution of Dart code. + * + * - Fatal error handles are produced when the system wants to shut + * down the current isolate. + * + * --- Propagating errors --- + * + * When an error handle is returned from the top level invocation of + * Dart code in a program, the embedder must handle the error as they + * see fit. Often, the embedder will print the error message produced + * by Dart_Error and exit the program. + * + * When an error is returned while in the body of a native function, + * it can be propagated up the call stack by calling + * Dart_PropagateError, Dart_SetReturnValue, or Dart_ThrowException. + * Errors should be propagated unless there is a specific reason not + * to. If an error is not propagated then it is ignored. For + * example, if an unhandled exception error is ignored, that + * effectively "catches" the unhandled exception. Fatal errors must + * always be propagated. + * + * When an error is propagated, any current scopes created by + * Dart_EnterScope will be exited. + * + * Using Dart_SetReturnValue to propagate an exception is somewhat + * more convenient than using Dart_PropagateError, and should be + * preferred for reasons discussed below. + * + * Dart_PropagateError and Dart_ThrowException do not return. Instead + * they transfer control non-locally using a setjmp-like mechanism. + * This can be inconvenient if you have resources that you need to + * clean up before propagating the error. + * + * When relying on Dart_PropagateError, we often return error handles + * rather than propagating them from helper functions. Consider the + * following contrived example: + * + * 1 Dart_Handle isLongStringHelper(Dart_Handle arg) { + * 2 intptr_t* length = 0; + * 3 result = Dart_StringLength(arg, &length); + * 4 if (Dart_IsError(result)) { + * 5 return result; + * 6 } + * 7 return Dart_NewBoolean(length > 100); + * 8 } + * 9 + * 10 void NativeFunction_isLongString(Dart_NativeArguments args) { + * 11 Dart_EnterScope(); + * 12 AllocateMyResource(); + * 13 Dart_Handle arg = Dart_GetNativeArgument(args, 0); + * 14 Dart_Handle result = isLongStringHelper(arg); + * 15 if (Dart_IsError(result)) { + * 16 FreeMyResource(); + * 17 Dart_PropagateError(result); + * 18 abort(); // will not reach here + * 19 } + * 20 Dart_SetReturnValue(result); + * 21 FreeMyResource(); + * 22 Dart_ExitScope(); + * 23 } + * + * In this example, we have a native function which calls a helper + * function to do its work. On line 5, the helper function could call + * Dart_PropagateError, but that would not give the native function a + * chance to call FreeMyResource(), causing a leak. Instead, the + * helper function returns the error handle to the caller, giving the + * caller a chance to clean up before propagating the error handle. + * + * When an error is propagated by calling Dart_SetReturnValue, the + * native function will be allowed to complete normally and then the + * exception will be propagated only once the native call + * returns. This can be convenient, as it allows the C code to clean + * up normally. + * + * The example can be written more simply using Dart_SetReturnValue to + * propagate the error. + * + * 1 Dart_Handle isLongStringHelper(Dart_Handle arg) { + * 2 intptr_t* length = 0; + * 3 result = Dart_StringLength(arg, &length); + * 4 if (Dart_IsError(result)) { + * 5 return result + * 6 } + * 7 return Dart_NewBoolean(length > 100); + * 8 } + * 9 + * 10 void NativeFunction_isLongString(Dart_NativeArguments args) { + * 11 Dart_EnterScope(); + * 12 AllocateMyResource(); + * 13 Dart_Handle arg = Dart_GetNativeArgument(args, 0); + * 14 Dart_SetReturnValue(isLongStringHelper(arg)); + * 15 FreeMyResource(); + * 16 Dart_ExitScope(); + * 17 } + * + * In this example, the call to Dart_SetReturnValue on line 14 will + * either return the normal return value or the error (potentially + * generated on line 3). The call to FreeMyResource on line 15 will + * execute in either case. + * + * --- Local and persistent handles --- + * + * Local handles are allocated within the current scope (see + * Dart_EnterScope) and go away when the current scope exits. Unless + * otherwise indicated, callers should assume that all functions in + * the Dart embedding api return local handles. + * + * Persistent handles are allocated within the current isolate. They + * can be used to store objects across scopes. Persistent handles have + * the lifetime of the current isolate unless they are explicitly + * deallocated (see Dart_DeletePersistentHandle). + * The type Dart_Handle represents a handle (both local and persistent). + * The type Dart_PersistentHandle is a Dart_Handle and it is used to + * document that a persistent handle is expected as a parameter to a call + * or the return value from a call is a persistent handle. + * + * FinalizableHandles are persistent handles which are auto deleted when + * the object is garbage collected. It is never safe to use these handles + * unless you know the object is still reachable. + * + * WeakPersistentHandles are persistent handles which are automatically set + * to point Dart_Null when the object is garbage collected. They are not auto + * deleted, so it is safe to use them after the object has become unreachable. + */ +typedef struct _Dart_Handle* Dart_Handle; +typedef Dart_Handle Dart_PersistentHandle; +typedef struct _Dart_WeakPersistentHandle* Dart_WeakPersistentHandle; +typedef struct _Dart_FinalizableHandle* Dart_FinalizableHandle; +// These structs are versioned by DART_API_DL_MAJOR_VERSION, bump the +// version when changing this struct. + +typedef void (*Dart_HandleFinalizer)(void* isolate_callback_data, void* peer); + +/** + * Is this an error handle? + * + * Requires there to be a current isolate. + */ +DART_EXPORT bool Dart_IsError(Dart_Handle handle); + +/** + * Is this an api error handle? + * + * Api error handles are produced when an api function is misused. + * This happens when a Dart embedding api function is called with + * invalid arguments or in an invalid context. + * + * Requires there to be a current isolate. + */ +DART_EXPORT bool Dart_IsApiError(Dart_Handle handle); + +/** + * Is this an unhandled exception error handle? + * + * Unhandled exception error handles are produced when, during the + * execution of Dart code, an exception is thrown but not caught. + * This can occur in any function which triggers the execution of Dart + * code. + * + * See Dart_ErrorGetException and Dart_ErrorGetStackTrace. + * + * Requires there to be a current isolate. + */ +DART_EXPORT bool Dart_IsUnhandledExceptionError(Dart_Handle handle); + +/** + * Is this a compilation error handle? + * + * Compilation error handles are produced when, during the execution + * of Dart code, a compile-time error occurs. This can occur in any + * function which triggers the execution of Dart code. + * + * Requires there to be a current isolate. + */ +DART_EXPORT bool Dart_IsCompilationError(Dart_Handle handle); + +/** + * Is this a fatal error handle? + * + * Fatal error handles are produced when the system wants to shut down + * the current isolate. + * + * Requires there to be a current isolate. + */ +DART_EXPORT bool Dart_IsFatalError(Dart_Handle handle); + +/** + * Gets the error message from an error handle. + * + * Requires there to be a current isolate. + * + * \return A C string containing an error message if the handle is + * error. An empty C string ("") if the handle is valid. This C + * String is scope allocated and is only valid until the next call + * to Dart_ExitScope. +*/ +DART_EXPORT const char* Dart_GetError(Dart_Handle handle); + +/** + * Is this an error handle for an unhandled exception? + */ +DART_EXPORT bool Dart_ErrorHasException(Dart_Handle handle); + +/** + * Gets the exception Object from an unhandled exception error handle. + */ +DART_EXPORT Dart_Handle Dart_ErrorGetException(Dart_Handle handle); + +/** + * Gets the stack trace Object from an unhandled exception error handle. + */ +DART_EXPORT Dart_Handle Dart_ErrorGetStackTrace(Dart_Handle handle); + +/** + * Produces an api error handle with the provided error message. + * + * Requires there to be a current isolate. + * + * \param error the error message. + */ +DART_EXPORT Dart_Handle Dart_NewApiError(const char* error); +DART_EXPORT Dart_Handle Dart_NewCompilationError(const char* error); + +/** + * Produces a new unhandled exception error handle. + * + * Requires there to be a current isolate. + * + * \param exception An instance of a Dart object to be thrown or + * an ApiError or CompilationError handle. + * When an ApiError or CompilationError handle is passed in + * a string object of the error message is created and it becomes + * the Dart object to be thrown. + */ +DART_EXPORT Dart_Handle Dart_NewUnhandledExceptionError(Dart_Handle exception); + +/** + * Propagates an error. + * + * If the provided handle is an unhandled exception error, this + * function will cause the unhandled exception to be rethrown. This + * will proceed in the standard way, walking up Dart frames until an + * appropriate 'catch' block is found, executing 'finally' blocks, + * etc. + * + * If the error is not an unhandled exception error, we will unwind + * the stack to the next C frame. Intervening Dart frames will be + * discarded; specifically, 'finally' blocks will not execute. This + * is the standard way that compilation errors (and the like) are + * handled by the Dart runtime. + * + * In either case, when an error is propagated any current scopes + * created by Dart_EnterScope will be exited. + * + * See the additional discussion under "Propagating Errors" at the + * beginning of this file. + * + * \param handle An error handle (See Dart_IsError) + * + * On success, this function does not return. On failure, the + * process is terminated. + */ +DART_EXPORT void Dart_PropagateError(Dart_Handle handle); + +/** + * Converts an object to a string. + * + * May generate an unhandled exception error. + * + * \return The converted string if no error occurs during + * the conversion. If an error does occur, an error handle is + * returned. + */ +DART_EXPORT Dart_Handle Dart_ToString(Dart_Handle object); + +/** + * Checks to see if two handles refer to identically equal objects. + * + * If both handles refer to instances, this is equivalent to using the top-level + * function identical() from dart:core. Otherwise, returns whether the two + * argument handles refer to the same object. + * + * \param obj1 An object to be compared. + * \param obj2 An object to be compared. + * + * \return True if the objects are identically equal. False otherwise. + */ +DART_EXPORT bool Dart_IdentityEquals(Dart_Handle obj1, Dart_Handle obj2); + +/** + * Allocates a handle in the current scope from a persistent handle. + */ +DART_EXPORT Dart_Handle Dart_HandleFromPersistent(Dart_PersistentHandle object); + +/** + * Allocates a handle in the current scope from a weak persistent handle. + * + * This will be a handle to Dart_Null if the object has been garbage collected. + */ +DART_EXPORT Dart_Handle +Dart_HandleFromWeakPersistent(Dart_WeakPersistentHandle object); + +/** + * Allocates a persistent handle for an object. + * + * This handle has the lifetime of the current isolate unless it is + * explicitly deallocated by calling Dart_DeletePersistentHandle. + * + * Requires there to be a current isolate. + */ +DART_EXPORT Dart_PersistentHandle Dart_NewPersistentHandle(Dart_Handle object); + +/** + * Assign value of local handle to a persistent handle. + * + * Requires there to be a current isolate. + * + * \param obj1 A persistent handle whose value needs to be set. + * \param obj2 An object whose value needs to be set to the persistent handle. + */ +DART_EXPORT void Dart_SetPersistentHandle(Dart_PersistentHandle obj1, + Dart_Handle obj2); + +/** + * Deallocates a persistent handle. + * + * Requires there to be a current isolate group. + */ +DART_EXPORT void Dart_DeletePersistentHandle(Dart_PersistentHandle object); + +/** + * Allocates a weak persistent handle for an object. + * + * This handle has the lifetime of the current isolate. The handle can also be + * explicitly deallocated by calling Dart_DeleteWeakPersistentHandle. + * + * If the object becomes unreachable the callback is invoked with the peer as + * argument. The callback can be executed on any thread, will have a current + * isolate group, but will not have a current isolate. The callback can only + * call Dart_DeletePersistentHandle or Dart_DeleteWeakPersistentHandle. This + * gives the embedder the ability to cleanup data associated with the object. + * The handle will point to the Dart_Null object after the finalizer has been + * run. It is illegal to call into the VM with any other Dart_* functions from + * the callback. If the handle is deleted before the object becomes + * unreachable, the callback is never invoked. + * + * Requires there to be a current isolate. + * + * \param object An object with identity. + * \param peer A pointer to a native object or NULL. This value is + * provided to callback when it is invoked. + * \param external_allocation_size The number of externally allocated + * bytes for peer. Used to inform the garbage collector. + * \param callback A function pointer that will be invoked sometime + * after the object is garbage collected, unless the handle has been deleted. + * A valid callback needs to be specified it cannot be NULL. + * + * \return The weak persistent handle or NULL. NULL is returned in case of bad + * parameters. + */ +DART_EXPORT Dart_WeakPersistentHandle +Dart_NewWeakPersistentHandle(Dart_Handle object, + void* peer, + intptr_t external_allocation_size, + Dart_HandleFinalizer callback); + +/** + * Deletes the given weak persistent [object] handle. + * + * Requires there to be a current isolate group. + */ +DART_EXPORT void Dart_DeleteWeakPersistentHandle( + Dart_WeakPersistentHandle object); + +/** + * Allocates a finalizable handle for an object. + * + * This handle has the lifetime of the current isolate group unless the object + * pointed to by the handle is garbage collected, in this case the VM + * automatically deletes the handle after invoking the callback associated + * with the handle. The handle can also be explicitly deallocated by + * calling Dart_DeleteFinalizableHandle. + * + * If the object becomes unreachable the callback is invoked with the + * the peer as argument. The callback can be executed on any thread, will have + * an isolate group, but will not have a current isolate. The callback can only + * call Dart_DeletePersistentHandle or Dart_DeleteWeakPersistentHandle. + * This gives the embedder the ability to cleanup data associated with the + * object and clear out any cached references to the handle. All references to + * this handle after the callback will be invalid. It is illegal to call into + * the VM with any other Dart_* functions from the callback. If the handle is + * deleted before the object becomes unreachable, the callback is never + * invoked. + * + * Requires there to be a current isolate. + * + * \param object An object with identity. + * \param peer A pointer to a native object or NULL. This value is + * provided to callback when it is invoked. + * \param external_allocation_size The number of externally allocated + * bytes for peer. Used to inform the garbage collector. + * \param callback A function pointer that will be invoked sometime + * after the object is garbage collected, unless the handle has been deleted. + * A valid callback needs to be specified it cannot be NULL. + * + * \return The finalizable handle or NULL. NULL is returned in case of bad + * parameters. + */ +DART_EXPORT Dart_FinalizableHandle +Dart_NewFinalizableHandle(Dart_Handle object, + void* peer, + intptr_t external_allocation_size, + Dart_HandleFinalizer callback); + +/** + * Deletes the given finalizable [object] handle. + * + * The caller has to provide the actual Dart object the handle was created from + * to prove the object (and therefore the finalizable handle) is still alive. + * + * Requires there to be a current isolate. + */ +DART_EXPORT void Dart_DeleteFinalizableHandle(Dart_FinalizableHandle object, + Dart_Handle strong_ref_to_object); + + +/* + * ========================== + * Initialization and Globals + * ========================== + */ + +/** + * Gets the version string for the Dart VM. + * + * The version of the Dart VM can be accessed without initializing the VM. + * + * \return The version string for the embedded Dart VM. + */ +DART_EXPORT const char* Dart_VersionString(void); + +/** + * Isolate specific flags are set when creating a new isolate using the + * Dart_IsolateFlags structure. + * + * Current version of flags is encoded in a 32-bit integer with 16 bits used + * for each part. + */ + +#define DART_FLAGS_CURRENT_VERSION (0x0000000c) + +typedef struct { + int32_t version; + bool enable_asserts; + bool use_field_guards; + bool use_osr; + bool obfuscate; + bool load_vmservice_library; + bool copy_parent_code; + bool null_safety; + bool is_system_isolate; + bool snapshot_is_dontneed_safe; + bool branch_coverage; +} Dart_IsolateFlags; + +/** + * Initialize Dart_IsolateFlags with correct version and default values. + */ +DART_EXPORT void Dart_IsolateFlagsInitialize(Dart_IsolateFlags* flags); + +/** + * An isolate creation and initialization callback function. + * + * This callback, provided by the embedder, is called when the VM + * needs to create an isolate. The callback should create an isolate + * by calling Dart_CreateIsolateGroup and load any scripts required for + * execution. + * + * This callback may be called on a different thread than the one + * running the parent isolate. + * + * When the function returns NULL, it is the responsibility of this + * function to ensure that Dart_ShutdownIsolate has been called if + * required (for example, if the isolate was created successfully by + * Dart_CreateIsolateGroup() but the root library fails to load + * successfully, then the function should call Dart_ShutdownIsolate + * before returning). + * + * When the function returns NULL, the function should set *error to + * a malloc-allocated buffer containing a useful error message. The + * caller of this function (the VM) will make sure that the buffer is + * freed. + * + * \param script_uri The uri of the main source file or snapshot to load. + * Either the URI of the parent isolate set in Dart_CreateIsolateGroup for + * Isolate.spawn, or the argument to Isolate.spawnUri canonicalized by the + * library tag handler of the parent isolate. + * The callback is responsible for loading the program by a call to + * Dart_LoadScriptFromKernel. + * \param main The name of the main entry point this isolate will + * eventually run. This is provided for advisory purposes only to + * improve debugging messages. The main function is not invoked by + * this function. + * \param package_root Ignored. + * \param package_config Uri of the package configuration file (either in format + * of .packages or .dart_tool/package_config.json) for this isolate + * to resolve package imports against. If this parameter is not passed the + * package resolution of the parent isolate should be used. + * \param flags Default flags for this isolate being spawned. Either inherited + * from the spawning isolate or passed as parameters when spawning the + * isolate from Dart code. + * \param isolate_data The isolate data which was passed to the + * parent isolate when it was created by calling Dart_CreateIsolateGroup(). + * \param error A structure into which the embedder can place a + * C string containing an error message in the case of failures. + * + * \return The embedder returns NULL if the creation and + * initialization was not successful and the isolate if successful. + */ +typedef Dart_Isolate (*Dart_IsolateGroupCreateCallback)( + const char* script_uri, + const char* main, + const char* package_root, + const char* package_config, + Dart_IsolateFlags* flags, + void* isolate_data, + char** error); + +/** + * An isolate initialization callback function. + * + * This callback, provided by the embedder, is called when the VM has created an + * isolate within an existing isolate group (i.e. from the same source as an + * existing isolate). + * + * The callback should setup native resolvers and might want to set a custom + * message handler via [Dart_SetMessageNotifyCallback] and mark the isolate as + * runnable. + * + * This callback may be called on a different thread than the one + * running the parent isolate. + * + * When the function returns `false`, it is the responsibility of this + * function to ensure that `Dart_ShutdownIsolate` has been called. + * + * When the function returns `false`, the function should set *error to + * a malloc-allocated buffer containing a useful error message. The + * caller of this function (the VM) will make sure that the buffer is + * freed. + * + * \param child_isolate_data The callback data to associate with the new + * child isolate. + * \param error A structure into which the embedder can place a + * C string containing an error message in the case the initialization fails. + * + * \return The embedder returns true if the initialization was successful and + * false otherwise (in which case the VM will terminate the isolate). + */ +typedef bool (*Dart_InitializeIsolateCallback)(void** child_isolate_data, + char** error); + +/** + * An isolate shutdown callback function. + * + * This callback, provided by the embedder, is called before the vm + * shuts down an isolate. The isolate being shutdown will be the current + * isolate. It is safe to run Dart code. + * + * This function should be used to dispose of native resources that + * are allocated to an isolate in order to avoid leaks. + * + * \param isolate_group_data The same callback data which was passed to the + * isolate group when it was created. + * \param isolate_data The same callback data which was passed to the isolate + * when it was created. + */ +typedef void (*Dart_IsolateShutdownCallback)(void* isolate_group_data, + void* isolate_data); + +/** + * An isolate cleanup callback function. + * + * This callback, provided by the embedder, is called after the vm + * shuts down an isolate. There will be no current isolate and it is *not* + * safe to run Dart code. + * + * This function should be used to dispose of native resources that + * are allocated to an isolate in order to avoid leaks. + * + * \param isolate_group_data The same callback data which was passed to the + * isolate group when it was created. + * \param isolate_data The same callback data which was passed to the isolate + * when it was created. + */ +typedef void (*Dart_IsolateCleanupCallback)(void* isolate_group_data, + void* isolate_data); + +/** + * An isolate group cleanup callback function. + * + * This callback, provided by the embedder, is called after the vm + * shuts down an isolate group. + * + * This function should be used to dispose of native resources that + * are allocated to an isolate in order to avoid leaks. + * + * \param isolate_group_data The same callback data which was passed to the + * isolate group when it was created. + * + */ +typedef void (*Dart_IsolateGroupCleanupCallback)(void* isolate_group_data); + +/** + * A thread start callback function. + * This callback, provided by the embedder, is called after a thread in the + * vm thread pool starts. + * This function could be used to adjust thread priority or attach native + * resources to the thread. + */ +typedef void (*Dart_ThreadStartCallback)(void); + +/** + * A thread death callback function. + * This callback, provided by the embedder, is called before a thread in the + * vm thread pool exits. + * This function could be used to dispose of native resources that + * are associated and attached to the thread, in order to avoid leaks. + */ +typedef void (*Dart_ThreadExitCallback)(void); + +/** + * Opens a file for reading or writing. + * + * Callback provided by the embedder for file operations. If the + * embedder does not allow file operations this callback can be + * NULL. + * + * \param name The name of the file to open. + * \param write A boolean variable which indicates if the file is to + * opened for writing. If there is an existing file it needs to truncated. + */ +typedef void* (*Dart_FileOpenCallback)(const char* name, bool write); + +/** + * Read contents of file. + * + * Callback provided by the embedder for file operations. If the + * embedder does not allow file operations this callback can be + * NULL. + * + * \param data Buffer allocated in the callback into which the contents + * of the file are read into. It is the responsibility of the caller to + * free this buffer. + * \param file_length A variable into which the length of the file is returned. + * In the case of an error this value would be -1. + * \param stream Handle to the opened file. + */ +typedef void (*Dart_FileReadCallback)(uint8_t** data, + intptr_t* file_length, + void* stream); + +/** + * Write data into file. + * + * Callback provided by the embedder for file operations. If the + * embedder does not allow file operations this callback can be + * NULL. + * + * \param data Buffer which needs to be written into the file. + * \param length Length of the buffer. + * \param stream Handle to the opened file. + */ +typedef void (*Dart_FileWriteCallback)(const void* data, + intptr_t length, + void* stream); + +/** + * Closes the opened file. + * + * Callback provided by the embedder for file operations. If the + * embedder does not allow file operations this callback can be + * NULL. + * + * \param stream Handle to the opened file. + */ +typedef void (*Dart_FileCloseCallback)(void* stream); + +typedef bool (*Dart_EntropySource)(uint8_t* buffer, intptr_t length); + +/** + * Callback provided by the embedder that is used by the vmservice isolate + * to request the asset archive. The asset archive must be an uncompressed tar + * archive that is stored in a Uint8List. + * + * If the embedder has no vmservice isolate assets, the callback can be NULL. + * + * \return The embedder must return a handle to a Uint8List containing an + * uncompressed tar archive or null. + */ +typedef Dart_Handle (*Dart_GetVMServiceAssetsArchive)(void); + +/** + * The current version of the Dart_InitializeFlags. Should be incremented every + * time Dart_InitializeFlags changes in a binary incompatible way. + */ +#define DART_INITIALIZE_PARAMS_CURRENT_VERSION (0x00000008) + +/** Forward declaration */ +struct Dart_CodeObserver; + +/** + * Callback provided by the embedder that is used by the VM to notify on code + * object creation, *before* it is invoked the first time. + * This is useful for embedders wanting to e.g. keep track of PCs beyond + * the lifetime of the garbage collected code objects. + * Note that an address range may be used by more than one code object over the + * lifecycle of a process. Clients of this function should record timestamps for + * these compilation events and when collecting PCs to disambiguate reused + * address ranges. + */ +typedef void (*Dart_OnNewCodeCallback)(struct Dart_CodeObserver* observer, + const char* name, + uintptr_t base, + uintptr_t size); + +typedef struct Dart_CodeObserver { + void* data; + + Dart_OnNewCodeCallback on_new_code; +} Dart_CodeObserver; + +/** + * Optional callback provided by the embedder that is used by the VM to + * implement registration of kernel blobs for the subsequent Isolate.spawnUri + * If no callback is provided, the registration of kernel blobs will throw + * an error. + * + * \param kernel_buffer A buffer which contains a kernel program. Callback + * should copy the contents of `kernel_buffer` as + * it may be freed immediately after registration. + * \param kernel_buffer_size The size of `kernel_buffer`. + * + * \return A C string representing URI which can be later used + * to spawn a new isolate. This C String should be scope allocated + * or owned by the embedder. + * Returns NULL if embedder runs out of memory. + */ +typedef const char* (*Dart_RegisterKernelBlobCallback)( + const uint8_t* kernel_buffer, + intptr_t kernel_buffer_size); + +/** + * Optional callback provided by the embedder that is used by the VM to + * unregister kernel blobs. + * If no callback is provided, the unregistration of kernel blobs will throw + * an error. + * + * \param kernel_blob_uri URI of the kernel blob to unregister. + */ +typedef void (*Dart_UnregisterKernelBlobCallback)(const char* kernel_blob_uri); + +/** + * Describes how to initialize the VM. Used with Dart_Initialize. + */ +typedef struct { + /** + * Identifies the version of the struct used by the client. + * should be initialized to DART_INITIALIZE_PARAMS_CURRENT_VERSION. + */ + int32_t version; + + /** + * A buffer containing snapshot data, or NULL if no snapshot is provided. + * + * If provided, the buffer must remain valid until Dart_Cleanup returns. + */ + const uint8_t* vm_snapshot_data; + + /** + * A buffer containing a snapshot of precompiled instructions, or NULL if + * no snapshot is provided. + * + * If provided, the buffer must remain valid until Dart_Cleanup returns. + */ + const uint8_t* vm_snapshot_instructions; + + /** + * A function to be called during isolate group creation. + * See Dart_IsolateGroupCreateCallback. + */ + Dart_IsolateGroupCreateCallback create_group; + + /** + * A function to be called during isolate + * initialization inside an existing isolate group. + * See Dart_InitializeIsolateCallback. + */ + Dart_InitializeIsolateCallback initialize_isolate; + + /** + * A function to be called right before an isolate is shutdown. + * See Dart_IsolateShutdownCallback. + */ + Dart_IsolateShutdownCallback shutdown_isolate; + + /** + * A function to be called after an isolate was shutdown. + * See Dart_IsolateCleanupCallback. + */ + Dart_IsolateCleanupCallback cleanup_isolate; + + /** + * A function to be called after an isolate group is + * shutdown. See Dart_IsolateGroupCleanupCallback. + */ + Dart_IsolateGroupCleanupCallback cleanup_group; + + Dart_ThreadStartCallback thread_start; + Dart_ThreadExitCallback thread_exit; + Dart_FileOpenCallback file_open; + Dart_FileReadCallback file_read; + Dart_FileWriteCallback file_write; + Dart_FileCloseCallback file_close; + Dart_EntropySource entropy_source; + + /** + * A function to be called by the service isolate when it requires the + * vmservice assets archive. See Dart_GetVMServiceAssetsArchive. + */ + Dart_GetVMServiceAssetsArchive get_service_assets; + + bool start_kernel_isolate; + + /** + * An external code observer callback function. The observer can be invoked + * as early as during the Dart_Initialize() call. + */ + Dart_CodeObserver* code_observer; + + /** + * Kernel blob registration callback function. See Dart_RegisterKernelBlobCallback. + */ + Dart_RegisterKernelBlobCallback register_kernel_blob; + + /** + * Kernel blob unregistration callback function. See Dart_UnregisterKernelBlobCallback. + */ + Dart_UnregisterKernelBlobCallback unregister_kernel_blob; + +#if defined(__Fuchsia__) + /** + * The resource needed to use zx_vmo_replace_as_executable. Can be + * ZX_HANDLE_INVALID if the process has ambient-replace-as-executable or if + * executable memory is not needed (e.g., this is an AOT runtime). + */ + zx_handle_t vmex_resource; +#endif +} Dart_InitializeParams; + +/** + * Initializes the VM. + * + * \param params A struct containing initialization information. The version + * field of the struct must be DART_INITIALIZE_PARAMS_CURRENT_VERSION. + * + * \return NULL if initialization is successful. Returns an error message + * otherwise. The caller is responsible for freeing the error message. + */ +DART_EXPORT DART_WARN_UNUSED_RESULT char* Dart_Initialize( + Dart_InitializeParams* params); + +/** + * Cleanup state in the VM before process termination. + * + * \return NULL if cleanup is successful. Returns an error message otherwise. + * The caller is responsible for freeing the error message. + * + * NOTE: This function must not be called on a thread that was created by the VM + * itself. + */ +DART_EXPORT DART_WARN_UNUSED_RESULT char* Dart_Cleanup(void); + +/** + * Sets command line flags. Should be called before Dart_Initialize. + * + * \param argc The length of the arguments array. + * \param argv An array of arguments. + * + * \return NULL if successful. Returns an error message otherwise. + * The caller is responsible for freeing the error message. + * + * NOTE: This call does not store references to the passed in c-strings. + */ +DART_EXPORT DART_WARN_UNUSED_RESULT char* Dart_SetVMFlags(int argc, + const char** argv); + +/** + * Returns true if the named VM flag is of boolean type, specified, and set to + * true. + * + * \param flag_name The name of the flag without leading punctuation + * (example: "enable_asserts"). + */ +DART_EXPORT bool Dart_IsVMFlagSet(const char* flag_name); + +/* + * ======== + * Isolates + * ======== + */ + +/** + * Creates a new isolate. The new isolate becomes the current isolate. + * + * A snapshot can be used to restore the VM quickly to a saved state + * and is useful for fast startup. If snapshot data is provided, the + * isolate will be started using that snapshot data. Requires a core snapshot or + * an app snapshot created by Dart_CreateSnapshot or + * Dart_CreatePrecompiledSnapshot* from a VM with the same version. + * + * Requires there to be no current isolate. + * + * \param script_uri The main source file or snapshot this isolate will load. + * The VM will provide this URI to the Dart_IsolateGroupCreateCallback when a + * child isolate is created by Isolate.spawn. The embedder should use a URI + * that allows it to load the same program into such a child isolate. + * \param name A short name for the isolate to improve debugging messages. + * Typically of the format 'foo.dart:main()'. + * \param isolate_snapshot_data Buffer containing the snapshot data of the + * isolate or NULL if no snapshot is provided. If provided, the buffer must + * remain valid until the isolate shuts down. + * \param isolate_snapshot_instructions Buffer containing the snapshot + * instructions of the isolate or NULL if no snapshot is provided. If + * provided, the buffer must remain valid until the isolate shuts down. + * \param flags Pointer to VM specific flags or NULL for default flags. + * \param isolate_group_data Embedder group data. This data can be obtained + * by calling Dart_IsolateGroupData and will be passed to the + * Dart_IsolateShutdownCallback, Dart_IsolateCleanupCallback, and + * Dart_IsolateGroupCleanupCallback. + * \param isolate_data Embedder data. This data will be passed to + * the Dart_IsolateGroupCreateCallback when new isolates are spawned from + * this parent isolate. + * \param error Returns NULL if creation is successful, an error message + * otherwise. The caller is responsible for calling free() on the error + * message. + * + * \return The new isolate on success, or NULL if isolate creation failed. + */ +DART_EXPORT Dart_Isolate +Dart_CreateIsolateGroup(const char* script_uri, + const char* name, + const uint8_t* isolate_snapshot_data, + const uint8_t* isolate_snapshot_instructions, + Dart_IsolateFlags* flags, + void* isolate_group_data, + void* isolate_data, + char** error); +/** + * Creates a new isolate inside the isolate group of [group_member]. + * + * Requires there to be no current isolate. + * + * \param group_member An isolate from the same group into which the newly created + * isolate should be born into. Other threads may not have entered / enter this + * member isolate. + * \param name A short name for the isolate for debugging purposes. + * \param shutdown_callback A callback to be called when the isolate is being + * shutdown (may be NULL). + * \param cleanup_callback A callback to be called when the isolate is being + * cleaned up (may be NULL). + * \param child_isolate_data The embedder-specific data associated with this isolate. + * \param error Set to NULL if creation is successful, set to an error + * message otherwise. The caller is responsible for calling free() on the + * error message. + * + * \return The newly created isolate on success, or NULL if isolate creation + * failed. + * + * If successful, the newly created isolate will become the current isolate. + */ +DART_EXPORT Dart_Isolate +Dart_CreateIsolateInGroup(Dart_Isolate group_member, + const char* name, + Dart_IsolateShutdownCallback shutdown_callback, + Dart_IsolateCleanupCallback cleanup_callback, + void* child_isolate_data, + char** error); + +/* TODO(turnidge): Document behavior when there is already a current + * isolate. */ + +/** + * Creates a new isolate from a Dart Kernel file. The new isolate + * becomes the current isolate. + * + * Requires there to be no current isolate. + * + * \param script_uri The main source file or snapshot this isolate will load. + * The VM will provide this URI to the Dart_IsolateGroupCreateCallback when a + * child isolate is created by Isolate.spawn. The embedder should use a URI that + * allows it to load the same program into such a child isolate. + * \param name A short name for the isolate to improve debugging messages. + * Typically of the format 'foo.dart:main()'. + * \param kernel_buffer A buffer which contains a kernel/DIL program. Must + * remain valid until isolate shutdown. + * \param kernel_buffer_size The size of `kernel_buffer`. + * \param flags Pointer to VM specific flags or NULL for default flags. + * \param isolate_group_data Embedder group data. This data can be obtained + * by calling Dart_IsolateGroupData and will be passed to the + * Dart_IsolateShutdownCallback, Dart_IsolateCleanupCallback, and + * Dart_IsolateGroupCleanupCallback. + * \param isolate_data Embedder data. This data will be passed to + * the Dart_IsolateGroupCreateCallback when new isolates are spawned from + * this parent isolate. + * \param error Returns NULL if creation is successful, an error message + * otherwise. The caller is responsible for calling free() on the error + * message. + * + * \return The new isolate on success, or NULL if isolate creation failed. + */ +DART_EXPORT Dart_Isolate +Dart_CreateIsolateGroupFromKernel(const char* script_uri, + const char* name, + const uint8_t* kernel_buffer, + intptr_t kernel_buffer_size, + Dart_IsolateFlags* flags, + void* isolate_group_data, + void* isolate_data, + char** error); +/** + * Shuts down the current isolate. After this call, the current isolate is NULL. + * Any current scopes created by Dart_EnterScope will be exited. Invokes the + * shutdown callback and any callbacks of remaining weak persistent handles. + * + * Requires there to be a current isolate. + */ +DART_EXPORT void Dart_ShutdownIsolate(void); +/* TODO(turnidge): Document behavior when there is no current isolate. */ + +/** + * Returns the current isolate. Will return NULL if there is no + * current isolate. + */ +DART_EXPORT Dart_Isolate Dart_CurrentIsolate(void); + +/** + * Returns the callback data associated with the current isolate. This + * data was set when the isolate got created or initialized. + */ +DART_EXPORT void* Dart_CurrentIsolateData(void); + +/** + * Returns the callback data associated with the given isolate. This + * data was set when the isolate got created or initialized. + */ +DART_EXPORT void* Dart_IsolateData(Dart_Isolate isolate); + +/** + * Returns the current isolate group. Will return NULL if there is no + * current isolate group. + */ +DART_EXPORT Dart_IsolateGroup Dart_CurrentIsolateGroup(void); + +/** + * Returns the callback data associated with the current isolate group. This + * data was passed to the isolate group when it was created. + */ +DART_EXPORT void* Dart_CurrentIsolateGroupData(void); + +/** + * Gets an id that uniquely identifies current isolate group. + * + * It is the responsibility of the caller to free the returned ID. + */ +typedef int64_t Dart_IsolateGroupId; +DART_EXPORT Dart_IsolateGroupId Dart_CurrentIsolateGroupId(void); + +/** + * Returns the callback data associated with the specified isolate group. This + * data was passed to the isolate when it was created. + * The embedder is responsible for ensuring the consistency of this data + * with respect to the lifecycle of an isolate group. + */ +DART_EXPORT void* Dart_IsolateGroupData(Dart_Isolate isolate); + +/** + * Returns the debugging name for the current isolate. + * + * This name is unique to each isolate and should only be used to make + * debugging messages more comprehensible. + */ +DART_EXPORT Dart_Handle Dart_DebugName(void); + +/** + * Returns the debugging name for the current isolate. + * + * This name is unique to each isolate and should only be used to make + * debugging messages more comprehensible. + * + * The returned string is scope allocated and is only valid until the next call + * to Dart_ExitScope. + */ +DART_EXPORT const char* Dart_DebugNameToCString(void); + +/** + * Returns the ID for an isolate which is used to query the service protocol. + * + * It is the responsibility of the caller to free the returned ID. + */ +DART_EXPORT const char* Dart_IsolateServiceId(Dart_Isolate isolate); + +/** + * Enters an isolate. After calling this function, + * the current isolate will be set to the provided isolate. + * + * Requires there to be no current isolate. Multiple threads may not be in + * the same isolate at once. + */ +DART_EXPORT void Dart_EnterIsolate(Dart_Isolate isolate); + +/** + * Kills the given isolate. + * + * This function has the same effect as dart:isolate's + * Isolate.kill(priority:immediate). + * It can interrupt ordinary Dart code but not native code. If the isolate is + * in the middle of a long running native function, the isolate will not be + * killed until control returns to Dart. + * + * Does not require a current isolate. It is safe to kill the current isolate if + * there is one. + */ +DART_EXPORT void Dart_KillIsolate(Dart_Isolate isolate); + +/** + * Notifies the VM that the embedder expects to be idle until |deadline|. The VM + * may use this time to perform garbage collection or other tasks to avoid + * delays during execution of Dart code in the future. + * + * |deadline| is measured in microseconds against the system's monotonic time. + * This clock can be accessed via Dart_TimelineGetMicros(). + * + * Requires there to be a current isolate. + */ +DART_EXPORT void Dart_NotifyIdle(int64_t deadline); + +typedef void (*Dart_HeapSamplingReportCallback)(void* context, + void* data); + +typedef void* (*Dart_HeapSamplingCreateCallback)( + Dart_Isolate isolate, + Dart_IsolateGroup isolate_group, + const char* cls_name, + intptr_t allocation_size); +typedef void (*Dart_HeapSamplingDeleteCallback)(void* data); + +/** + * Starts the heap sampling profiler for each thread in the VM. + */ +DART_EXPORT void Dart_EnableHeapSampling(void); + +/* + * Stops the heap sampling profiler for each thread in the VM. + */ +DART_EXPORT void Dart_DisableHeapSampling(void); + +/* Registers callbacks are invoked once per sampled allocation upon object + * allocation and garbage collection. + * + * |create_callback| can be used to associate additional data with the sampled + * allocation, such as a stack trace. This data pointer will be passed to + * |delete_callback| to allow for proper disposal when the object associated + * with the allocation sample is collected. + * + * The provided callbacks must not call into the VM and should do as little + * work as possible to avoid performance penalities during object allocation and + * garbage collection. + * + * NOTE: It is a fatal error to set either callback to null once they have been + * initialized. + */ +DART_EXPORT void Dart_RegisterHeapSamplingCallback( + Dart_HeapSamplingCreateCallback create_callback, + Dart_HeapSamplingDeleteCallback delete_callback); + +/* + * Reports the surviving allocation samples for all live isolate groups in the + * VM. + * + * When the callback is invoked: + * - |context| will be the context object provided when invoking + * |Dart_ReportSurvivingAllocations|. This can be safely set to null if not + * required. + * - |heap_size| will be equal to the size of the allocated object associated + * with the sample. + * - |cls_name| will be a C String representing + * the class name of the allocated object. This string is valid for the + * duration of the call to Dart_ReportSurvivingAllocations and can be + * freed by the VM at any point after the method returns. + * - |data| will be set to the data associated with the sample by + * |Dart_HeapSamplingCreateCallback|. + * + * If |force_gc| is true, a full GC will be performed before reporting the + * allocations. + */ +DART_EXPORT void Dart_ReportSurvivingAllocations( + Dart_HeapSamplingReportCallback callback, + void* context, + bool force_gc); + +/* + * Sets the average heap sampling rate based on a number of |bytes| for each + * thread. + * + * In other words, approximately every |bytes| allocated will create a sample. + * Defaults to 512 KiB. + */ +DART_EXPORT void Dart_SetHeapSamplingPeriod(intptr_t bytes); + +/** + * Notifies the VM that the embedder expects the application's working set has + * recently shrunk significantly and is not expected to rise in the near future. + * The VM may spend O(heap-size) time performing clean up work. + * + * Requires there to be a current isolate. + */ +DART_EXPORT void Dart_NotifyDestroyed(void); + +/** + * Notifies the VM that the system is running low on memory. + * + * Does not require a current isolate. Only valid after calling Dart_Initialize. + */ +DART_EXPORT void Dart_NotifyLowMemory(void); + +typedef enum { + /** + * Balanced + */ + Dart_PerformanceMode_Default, + /** + * Optimize for low latency, at the expense of throughput and memory overhead + * by performing work in smaller batches (requiring more overhead) or by + * delaying work (requiring more memory). An embedder should not remain in + * this mode indefinitely. + */ + Dart_PerformanceMode_Latency, + /** + * Optimize for high throughput, at the expense of latency and memory overhead + * by performing work in larger batches with more intervening growth. + */ + Dart_PerformanceMode_Throughput, + /** + * Optimize for low memory, at the expensive of throughput and latency by more + * frequently performing work. + */ + Dart_PerformanceMode_Memory, +} Dart_PerformanceMode; + +/** + * Set the desired performance trade-off. + * + * Requires a current isolate. + * + * Returns the previous performance mode. + */ +DART_EXPORT Dart_PerformanceMode +Dart_SetPerformanceMode(Dart_PerformanceMode mode); + +/** + * Starts the CPU sampling profiler. + */ +DART_EXPORT void Dart_StartProfiling(void); + +/** + * Stops the CPU sampling profiler. + * + * Note that some profile samples might still be taken after this function + * returns due to the asynchronous nature of the implementation on some + * platforms. + */ +DART_EXPORT void Dart_StopProfiling(void); + +/** + * Notifies the VM that the current thread should not be profiled until a + * matching call to Dart_ThreadEnableProfiling is made. + * + * NOTE: By default, if a thread has entered an isolate it will be profiled. + * This function should be used when an embedder knows a thread is about + * to make a blocking call and wants to avoid unnecessary interrupts by + * the profiler. + */ +DART_EXPORT void Dart_ThreadDisableProfiling(void); + +/** + * Notifies the VM that the current thread should be profiled. + * + * NOTE: It is only legal to call this function *after* calling + * Dart_ThreadDisableProfiling. + * + * NOTE: By default, if a thread has entered an isolate it will be profiled. + */ +DART_EXPORT void Dart_ThreadEnableProfiling(void); + +/** + * Register symbol information for the Dart VM's profiler and crash dumps. + * + * This consumes the output of //topaz/runtime/dart/profiler_symbols, which + * should be treated as opaque. + */ +DART_EXPORT void Dart_AddSymbols(const char* dso_name, + void* buffer, + intptr_t buffer_size); + +/** + * Exits an isolate. After this call, Dart_CurrentIsolate will + * return NULL. + * + * Requires there to be a current isolate. + */ +DART_EXPORT void Dart_ExitIsolate(void); +/* TODO(turnidge): We don't want users of the api to be able to exit a + * "pure" dart isolate. Implement and document. */ + +/** + * Creates a full snapshot of the current isolate heap. + * + * A full snapshot is a compact representation of the dart vm isolate heap + * and dart isolate heap states. These snapshots are used to initialize + * the vm isolate on startup and fast initialization of an isolate. + * A Snapshot of the heap is created before any dart code has executed. + * + * Requires there to be a current isolate. Not available in the precompiled + * runtime (check Dart_IsPrecompiledRuntime). + * + * \param vm_snapshot_data_buffer Returns a pointer to a buffer containing the + * vm snapshot. This buffer is scope allocated and is only valid + * until the next call to Dart_ExitScope. + * \param vm_snapshot_data_size Returns the size of vm_snapshot_data_buffer. + * \param isolate_snapshot_data_buffer Returns a pointer to a buffer containing + * the isolate snapshot. This buffer is scope allocated and is only valid + * until the next call to Dart_ExitScope. + * \param isolate_snapshot_data_size Returns the size of + * isolate_snapshot_data_buffer. + * \param is_core Create a snapshot containing core libraries. + * Such snapshot should be agnostic to null safety mode. + * + * \return A valid handle if no error occurs during the operation. + */ +DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle +Dart_CreateSnapshot(uint8_t** vm_snapshot_data_buffer, + intptr_t* vm_snapshot_data_size, + uint8_t** isolate_snapshot_data_buffer, + intptr_t* isolate_snapshot_data_size, + bool is_core); + +/** + * Returns whether the buffer contains a kernel file. + * + * \param buffer Pointer to a buffer that might contain a kernel binary. + * \param buffer_size Size of the buffer. + * + * \return Whether the buffer contains a kernel binary (full or partial). + */ +DART_EXPORT bool Dart_IsKernel(const uint8_t* buffer, intptr_t buffer_size); + +/** + * Make isolate runnable. + * + * When isolates are spawned, this function is used to indicate that + * the creation and initialization (including script loading) of the + * isolate is complete and the isolate can start. + * This function expects there to be no current isolate. + * + * \param isolate The isolate to be made runnable. + * + * \return NULL if successful. Returns an error message otherwise. The caller + * is responsible for freeing the error message. + */ +DART_EXPORT DART_WARN_UNUSED_RESULT char* Dart_IsolateMakeRunnable( + Dart_Isolate isolate); + +/* + * ================== + * Messages and Ports + * ================== + */ + +/** + * A port is used to send or receive inter-isolate messages + */ +typedef int64_t Dart_Port; + +/** + * ILLEGAL_PORT is a port number guaranteed never to be associated with a valid + * port. + */ +#define ILLEGAL_PORT ((Dart_Port)0) + +/** + * A message notification callback. + * + * This callback allows the embedder to provide a custom wakeup mechanism for + * the delivery of inter-isolate messages. This function is called once per + * message on an arbitrary thread. It is the responsibility of the embedder to + * eventually call Dart_HandleMessage once per callback received with the + * destination isolate set as the current isolate to process the message. + */ +typedef void (*Dart_MessageNotifyCallback)(Dart_Isolate destination_isolate); + +/** + * Allows embedders to provide a custom wakeup mechanism for the delivery of + * inter-isolate messages. This setting only applies to the current isolate. + * + * This mechanism is optional: if not provided, the isolate will be scheduled on + * a VM-managed thread pool. An embedder should provide this callback if it + * wants to run an isolate on a specific thread or to interleave handling of + * inter-isolate messages with other event sources. + * + * Most embedders will only call this function once, before isolate + * execution begins. If this function is called after isolate + * execution begins, the embedder is responsible for threading issues. + */ +DART_EXPORT void Dart_SetMessageNotifyCallback( + Dart_MessageNotifyCallback message_notify_callback); +/* TODO(turnidge): Consider moving this to isolate creation so that it + * is impossible to mess up. */ + +/** + * Query the current message notify callback for the isolate. + * + * \return The current message notify callback for the isolate. + */ +DART_EXPORT Dart_MessageNotifyCallback Dart_GetMessageNotifyCallback(void); + +/** + * The VM's default message handler supports pausing an isolate before it + * processes the first message and right after the it processes the isolate's + * final message. This can be controlled for all isolates by two VM flags: + * + * `--pause-isolates-on-start` + * `--pause-isolates-on-exit` + * + * Additionally, Dart_SetShouldPauseOnStart and Dart_SetShouldPauseOnExit can be + * used to control this behaviour on a per-isolate basis. + * + * When an embedder is using a Dart_MessageNotifyCallback the embedder + * needs to cooperate with the VM so that the service protocol can report + * accurate information about isolates and so that tools such as debuggers + * work reliably. + * + * The following functions can be used to implement pausing on start and exit. + */ + +/** + * If the VM flag `--pause-isolates-on-start` was passed this will be true. + * + * \return A boolean value indicating if pause on start was requested. + */ +DART_EXPORT bool Dart_ShouldPauseOnStart(void); + +/** + * Override the VM flag `--pause-isolates-on-start` for the current isolate. + * + * \param should_pause Should the isolate be paused on start? + * + * NOTE: This must be called before Dart_IsolateMakeRunnable. + */ +DART_EXPORT void Dart_SetShouldPauseOnStart(bool should_pause); + +/** + * Is the current isolate paused on start? + * + * \return A boolean value indicating if the isolate is paused on start. + */ +DART_EXPORT bool Dart_IsPausedOnStart(void); + +/** + * Called when the embedder has paused the current isolate on start and when + * the embedder has resumed the isolate. + * + * \param paused Is the isolate paused on start? + */ +DART_EXPORT void Dart_SetPausedOnStart(bool paused); + +/** + * If the VM flag `--pause-isolates-on-exit` was passed this will be true. + * + * \return A boolean value indicating if pause on exit was requested. + */ +DART_EXPORT bool Dart_ShouldPauseOnExit(void); + +/** + * Override the VM flag `--pause-isolates-on-exit` for the current isolate. + * + * \param should_pause Should the isolate be paused on exit? + * + */ +DART_EXPORT void Dart_SetShouldPauseOnExit(bool should_pause); + +/** + * Is the current isolate paused on exit? + * + * \return A boolean value indicating if the isolate is paused on exit. + */ +DART_EXPORT bool Dart_IsPausedOnExit(void); + +/** + * Called when the embedder has paused the current isolate on exit and when + * the embedder has resumed the isolate. + * + * \param paused Is the isolate paused on exit? + */ +DART_EXPORT void Dart_SetPausedOnExit(bool paused); + +/** + * Called when the embedder has caught a top level unhandled exception error + * in the current isolate. + * + * NOTE: It is illegal to call this twice on the same isolate without first + * clearing the sticky error to null. + * + * \param error The unhandled exception error. + */ +DART_EXPORT void Dart_SetStickyError(Dart_Handle error); + +/** + * Does the current isolate have a sticky error? + */ +DART_EXPORT bool Dart_HasStickyError(void); + +/** + * Gets the sticky error for the current isolate. + * + * \return A handle to the sticky error object or null. + */ +DART_EXPORT Dart_Handle Dart_GetStickyError(void); + +/** + * Handles the next pending message for the current isolate. + * + * May generate an unhandled exception error. + * + * \return A valid handle if no error occurs during the operation. + */ +DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle Dart_HandleMessage(void); + +/** + * Drains the microtask queue, then blocks the calling thread until the current + * isolate receives a message, then handles all messages. + * + * \param timeout_millis When non-zero, the call returns after the indicated + number of milliseconds even if no message was received. + * \return A valid handle if no error occurs, otherwise an error handle. + */ +DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle +Dart_WaitForEvent(int64_t timeout_millis); + +/** + * Handles any pending messages for the vm service for the current + * isolate. + * + * This function may be used by an embedder at a breakpoint to avoid + * pausing the vm service. + * + * This function can indirectly cause the message notify callback to + * be called. + * + * \return true if the vm service requests the program resume + * execution, false otherwise + */ +DART_EXPORT bool Dart_HandleServiceMessages(void); + +/** + * Does the current isolate have pending service messages? + * + * \return true if the isolate has pending service messages, false otherwise. + */ +DART_EXPORT bool Dart_HasServiceMessages(void); + +/** + * Processes any incoming messages for the current isolate. + * + * This function may only be used when the embedder has not provided + * an alternate message delivery mechanism with + * Dart_SetMessageCallbacks. It is provided for convenience. + * + * This function waits for incoming messages for the current + * isolate. As new messages arrive, they are handled using + * Dart_HandleMessage. The routine exits when all ports to the + * current isolate are closed. + * + * \return A valid handle if the run loop exited successfully. If an + * exception or other error occurs while processing messages, an + * error handle is returned. + */ +DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle Dart_RunLoop(void); + +/** + * Lets the VM run message processing for the isolate. + * + * This function expects there to a current isolate and the current isolate + * must not have an active api scope. The VM will take care of making the + * isolate runnable (if not already), handles its message loop and will take + * care of shutting the isolate down once it's done. + * + * \param errors_are_fatal Whether uncaught errors should be fatal. + * \param on_error_port A port to notify on uncaught errors (or ILLEGAL_PORT). + * \param on_exit_port A port to notify on exit (or ILLEGAL_PORT). + * \param error A non-NULL pointer which will hold an error message if the call + * fails. The error has to be free()ed by the caller. + * + * \return If successful the VM takes ownership of the isolate and takes care + * of its message loop. If not successful the caller retains ownership of the + * isolate. + */ +DART_EXPORT DART_WARN_UNUSED_RESULT bool Dart_RunLoopAsync( + bool errors_are_fatal, + Dart_Port on_error_port, + Dart_Port on_exit_port, + char** error); + +/* TODO(turnidge): Should this be removed from the public api? */ + +/** + * Gets the main port id for the current isolate. + */ +DART_EXPORT Dart_Port Dart_GetMainPortId(void); + +/** + * Does the current isolate have live ReceivePorts? + * + * A ReceivePort is live when it has not been closed. + */ +DART_EXPORT bool Dart_HasLivePorts(void); + +/** + * Posts a message for some isolate. The message is a serialized + * object. + * + * Requires there to be a current isolate. + * + * For posting messages outside of an isolate see \ref Dart_PostCObject. + * + * \param port_id The destination port. + * \param object An object from the current isolate. + * + * \return True if the message was posted. + */ +DART_EXPORT bool Dart_Post(Dart_Port port_id, Dart_Handle object); + +/** + * Returns a new SendPort with the provided port id. + * + * \param port_id The destination port. + * + * \return A new SendPort if no errors occurs. Otherwise returns + * an error handle. + */ +DART_EXPORT Dart_Handle Dart_NewSendPort(Dart_Port port_id); + +/** + * Gets the SendPort id for the provided SendPort. + * \param port A SendPort object whose id is desired. + * \param port_id Returns the id of the SendPort. + * \return Success if no error occurs. Otherwise returns + * an error handle. + */ +DART_EXPORT Dart_Handle Dart_SendPortGetId(Dart_Handle port, + Dart_Port* port_id); + +/* + * ====== + * Scopes + * ====== + */ + +/** + * Enters a new scope. + * + * All new local handles will be created in this scope. Additionally, + * some functions may return "scope allocated" memory which is only + * valid within this scope. + * + * Requires there to be a current isolate. + */ +DART_EXPORT void Dart_EnterScope(void); + +/** + * Exits a scope. + * + * The previous scope (if any) becomes the current scope. + * + * Requires there to be a current isolate. + */ +DART_EXPORT void Dart_ExitScope(void); + +/** + * The Dart VM uses "zone allocation" for temporary structures. Zones + * support very fast allocation of small chunks of memory. The chunks + * cannot be deallocated individually, but instead zones support + * deallocating all chunks in one fast operation. + * + * This function makes it possible for the embedder to allocate + * temporary data in the VMs zone allocator. + * + * Zone allocation is possible: + * 1. when inside a scope where local handles can be allocated + * 2. when processing a message from a native port in a native port + * handler + * + * All the memory allocated this way will be reclaimed either on the + * next call to Dart_ExitScope or when the native port handler exits. + * + * \param size Size of the memory to allocate. + * + * \return A pointer to the allocated memory. NULL if allocation + * failed. Failure might due to is no current VM zone. + */ +DART_EXPORT uint8_t* Dart_ScopeAllocate(intptr_t size); + +/* + * ======= + * Objects + * ======= + */ + +/** + * Returns the null object. + * + * \return A handle to the null object. + */ +DART_EXPORT Dart_Handle Dart_Null(void); + +/** + * Is this object null? + */ +DART_EXPORT bool Dart_IsNull(Dart_Handle object); + +/** + * Returns the empty string object. + * + * \return A handle to the empty string object. + */ +DART_EXPORT Dart_Handle Dart_EmptyString(void); + +/** + * Returns types that are not classes, and which therefore cannot be looked up + * as library members by Dart_GetType. + * + * \return A handle to the dynamic, void or Never type. + */ +DART_EXPORT Dart_Handle Dart_TypeDynamic(void); +DART_EXPORT Dart_Handle Dart_TypeVoid(void); +DART_EXPORT Dart_Handle Dart_TypeNever(void); + +/** + * Checks if the two objects are equal. + * + * The result of the comparison is returned through the 'equal' + * parameter. The return value itself is used to indicate success or + * failure, not equality. + * + * May generate an unhandled exception error. + * + * \param obj1 An object to be compared. + * \param obj2 An object to be compared. + * \param equal Returns the result of the equality comparison. + * + * \return A valid handle if no error occurs during the comparison. + */ +DART_EXPORT Dart_Handle Dart_ObjectEquals(Dart_Handle obj1, + Dart_Handle obj2, + bool* equal); + +/** + * Is this object an instance of some type? + * + * The result of the test is returned through the 'instanceof' parameter. + * The return value itself is used to indicate success or failure. + * + * \param object An object. + * \param type A type. + * \param instanceof Return true if 'object' is an instance of type 'type'. + * + * \return A valid handle if no error occurs during the operation. + */ +DART_EXPORT Dart_Handle Dart_ObjectIsType(Dart_Handle object, + Dart_Handle type, + bool* instanceof); + +/** + * Query object type. + * + * \param object Some Object. + * + * \return true if Object is of the specified type. + */ +DART_EXPORT bool Dart_IsInstance(Dart_Handle object); +DART_EXPORT bool Dart_IsNumber(Dart_Handle object); +DART_EXPORT bool Dart_IsInteger(Dart_Handle object); +DART_EXPORT bool Dart_IsDouble(Dart_Handle object); +DART_EXPORT bool Dart_IsBoolean(Dart_Handle object); +DART_EXPORT bool Dart_IsString(Dart_Handle object); +DART_EXPORT bool Dart_IsStringLatin1(Dart_Handle object); /* (ISO-8859-1) */ +DART_EXPORT bool Dart_IsExternalString(Dart_Handle object); +DART_EXPORT bool Dart_IsList(Dart_Handle object); +DART_EXPORT bool Dart_IsMap(Dart_Handle object); +DART_EXPORT bool Dart_IsLibrary(Dart_Handle object); +DART_EXPORT bool Dart_IsType(Dart_Handle handle); +DART_EXPORT bool Dart_IsFunction(Dart_Handle handle); +DART_EXPORT bool Dart_IsVariable(Dart_Handle handle); +DART_EXPORT bool Dart_IsTypeVariable(Dart_Handle handle); +DART_EXPORT bool Dart_IsClosure(Dart_Handle object); +DART_EXPORT bool Dart_IsTypedData(Dart_Handle object); +DART_EXPORT bool Dart_IsByteBuffer(Dart_Handle object); +DART_EXPORT bool Dart_IsFuture(Dart_Handle object); + +/* + * ========= + * Instances + * ========= + */ + +/* + * For the purposes of the embedding api, not all objects returned are + * Dart language objects. Within the api, we use the term 'Instance' + * to indicate handles which refer to true Dart language objects. + * + * TODO(turnidge): Reorganize the "Object" section above, pulling down + * any functions that more properly belong here. */ + +/** + * Gets the type of a Dart language object. + * + * \param instance Some Dart object. + * + * \return If no error occurs, the type is returned. Otherwise an + * error handle is returned. + */ +DART_EXPORT Dart_Handle Dart_InstanceGetType(Dart_Handle instance); + +/** + * Returns the name for the provided class type. + * + * \return A valid string handle if no error occurs during the + * operation. + */ +DART_EXPORT Dart_Handle Dart_ClassName(Dart_Handle cls_type); + +/** + * Returns the name for the provided function or method. + * + * \return A valid string handle if no error occurs during the + * operation. + */ +DART_EXPORT Dart_Handle Dart_FunctionName(Dart_Handle function); + +/** + * Returns a handle to the owner of a function. + * + * The owner of an instance method or a static method is its defining + * class. The owner of a top-level function is its defining + * library. The owner of the function of a non-implicit closure is the + * function of the method or closure that defines the non-implicit + * closure. + * + * \return A valid handle to the owner of the function, or an error + * handle if the argument is not a valid handle to a function. + */ +DART_EXPORT Dart_Handle Dart_FunctionOwner(Dart_Handle function); + +/** + * Determines whether a function handle refers to a static function + * of method. + * + * For the purposes of the embedding API, a top-level function is + * implicitly declared static. + * + * \param function A handle to a function or method declaration. + * \param is_static Returns whether the function or method is declared static. + * + * \return A valid handle if no error occurs during the operation. + */ +DART_EXPORT Dart_Handle Dart_FunctionIsStatic(Dart_Handle function, + bool* is_static); + +/** + * Is this object a closure resulting from a tear-off (closurized method)? + * + * Returns true for closures produced when an ordinary method is accessed + * through a getter call. Returns false otherwise, in particular for closures + * produced from local function declarations. + * + * \param object Some Object. + * + * \return true if Object is a tear-off. + */ +DART_EXPORT bool Dart_IsTearOff(Dart_Handle object); + +/** + * Retrieves the function of a closure. + * + * \return A handle to the function of the closure, or an error handle if the + * argument is not a closure. + */ +DART_EXPORT Dart_Handle Dart_ClosureFunction(Dart_Handle closure); + +/** + * Returns a handle to the library which contains class. + * + * \return A valid handle to the library with owns class, null if the class + * has no library or an error handle if the argument is not a valid handle + * to a class type. + */ +DART_EXPORT Dart_Handle Dart_ClassLibrary(Dart_Handle cls_type); + +/* + * ============================= + * Numbers, Integers and Doubles + * ============================= + */ + +/** + * Does this Integer fit into a 64-bit signed integer? + * + * \param integer An integer. + * \param fits Returns true if the integer fits into a 64-bit signed integer. + * + * \return A valid handle if no error occurs during the operation. + */ +DART_EXPORT Dart_Handle Dart_IntegerFitsIntoInt64(Dart_Handle integer, + bool* fits); + +/** + * Does this Integer fit into a 64-bit unsigned integer? + * + * \param integer An integer. + * \param fits Returns true if the integer fits into a 64-bit unsigned integer. + * + * \return A valid handle if no error occurs during the operation. + */ +DART_EXPORT Dart_Handle Dart_IntegerFitsIntoUint64(Dart_Handle integer, + bool* fits); + +/** + * Returns an Integer with the provided value. + * + * \param value The value of the integer. + * + * \return The Integer object if no error occurs. Otherwise returns + * an error handle. + */ +DART_EXPORT Dart_Handle Dart_NewInteger(int64_t value); + +/** + * Returns an Integer with the provided value. + * + * \param value The unsigned value of the integer. + * + * \return The Integer object if no error occurs. Otherwise returns + * an error handle. + */ +DART_EXPORT Dart_Handle Dart_NewIntegerFromUint64(uint64_t value); + +/** + * Returns an Integer with the provided value. + * + * \param value The value of the integer represented as a C string + * containing a hexadecimal number. + * + * \return The Integer object if no error occurs. Otherwise returns + * an error handle. + */ +DART_EXPORT Dart_Handle Dart_NewIntegerFromHexCString(const char* value); + +/** + * Gets the value of an Integer. + * + * The integer must fit into a 64-bit signed integer, otherwise an error occurs. + * + * \param integer An Integer. + * \param value Returns the value of the Integer. + * + * \return A valid handle if no error occurs during the operation. + */ +DART_EXPORT Dart_Handle Dart_IntegerToInt64(Dart_Handle integer, + int64_t* value); + +/** + * Gets the value of an Integer. + * + * The integer must fit into a 64-bit unsigned integer, otherwise an + * error occurs. + * + * \param integer An Integer. + * \param value Returns the value of the Integer. + * + * \return A valid handle if no error occurs during the operation. + */ +DART_EXPORT Dart_Handle Dart_IntegerToUint64(Dart_Handle integer, + uint64_t* value); + +/** + * Gets the value of an integer as a hexadecimal C string. + * + * \param integer An Integer. + * \param value Returns the value of the Integer as a hexadecimal C + * string. This C string is scope allocated and is only valid until + * the next call to Dart_ExitScope. + * + * \return A valid handle if no error occurs during the operation. + */ +DART_EXPORT Dart_Handle Dart_IntegerToHexCString(Dart_Handle integer, + const char** value); + +/** + * Returns a Double with the provided value. + * + * \param value A double. + * + * \return The Double object if no error occurs. Otherwise returns + * an error handle. + */ +DART_EXPORT Dart_Handle Dart_NewDouble(double value); + +/** + * Gets the value of a Double + * + * \param double_obj A Double + * \param value Returns the value of the Double. + * + * \return A valid handle if no error occurs during the operation. + */ +DART_EXPORT Dart_Handle Dart_DoubleValue(Dart_Handle double_obj, double* value); + +/** + * Returns a closure of static function 'function_name' in the class 'class_name' + * in the exported namespace of specified 'library'. + * + * \param library Library object + * \param cls_type Type object representing a Class + * \param function_name Name of the static function in the class + * + * \return A valid Dart instance if no error occurs during the operation. + */ +DART_EXPORT Dart_Handle Dart_GetStaticMethodClosure(Dart_Handle library, + Dart_Handle cls_type, + Dart_Handle function_name); + +/* + * ======== + * Booleans + * ======== + */ + +/** + * Returns the True object. + * + * Requires there to be a current isolate. + * + * \return A handle to the True object. + */ +DART_EXPORT Dart_Handle Dart_True(void); + +/** + * Returns the False object. + * + * Requires there to be a current isolate. + * + * \return A handle to the False object. + */ +DART_EXPORT Dart_Handle Dart_False(void); + +/** + * Returns a Boolean with the provided value. + * + * \param value true or false. + * + * \return The Boolean object if no error occurs. Otherwise returns + * an error handle. + */ +DART_EXPORT Dart_Handle Dart_NewBoolean(bool value); + +/** + * Gets the value of a Boolean + * + * \param boolean_obj A Boolean + * \param value Returns the value of the Boolean. + * + * \return A valid handle if no error occurs during the operation. + */ +DART_EXPORT Dart_Handle Dart_BooleanValue(Dart_Handle boolean_obj, bool* value); + +/* + * ======= + * Strings + * ======= + */ + +/** + * Gets the length of a String. + * + * \param str A String. + * \param length Returns the length of the String. + * + * \return A valid handle if no error occurs during the operation. + */ +DART_EXPORT Dart_Handle Dart_StringLength(Dart_Handle str, intptr_t* length); + +/** + * Returns a String built from the provided C string + * (There is an implicit assumption that the C string passed in contains + * UTF-8 encoded characters and '\0' is considered as a termination + * character). + * + * \param str A C String + * + * \return The String object if no error occurs. Otherwise returns + * an error handle. + */ +DART_EXPORT Dart_Handle Dart_NewStringFromCString(const char* str); +/* TODO(turnidge): Document what happens when we run out of memory + * during this call. */ + +/** + * Returns a String built from an array of UTF-8 encoded characters. + * + * \param utf8_array An array of UTF-8 encoded characters. + * \param length The length of the codepoints array. + * + * \return The String object if no error occurs. Otherwise returns + * an error handle. + */ +DART_EXPORT Dart_Handle Dart_NewStringFromUTF8(const uint8_t* utf8_array, + intptr_t length); + +/** + * Returns a String built from an array of UTF-16 encoded characters. + * + * \param utf16_array An array of UTF-16 encoded characters. + * \param length The length of the codepoints array. + * + * \return The String object if no error occurs. Otherwise returns + * an error handle. + */ +DART_EXPORT Dart_Handle Dart_NewStringFromUTF16(const uint16_t* utf16_array, + intptr_t length); + +/** + * Returns a String built from an array of UTF-32 encoded characters. + * + * \param utf32_array An array of UTF-32 encoded characters. + * \param length The length of the codepoints array. + * + * \return The String object if no error occurs. Otherwise returns + * an error handle. + */ +DART_EXPORT Dart_Handle Dart_NewStringFromUTF32(const int32_t* utf32_array, + intptr_t length); + +/** + * Returns a String which references an external array of + * Latin-1 (ISO-8859-1) encoded characters. + * + * \param latin1_array Array of Latin-1 encoded characters. This must not move. + * \param length The length of the characters array. + * \param peer An external pointer to associate with this string. + * \param external_allocation_size The number of externally allocated + * bytes for peer. Used to inform the garbage collector. + * \param callback A callback to be called when this string is finalized. + * + * \return The String object if no error occurs. Otherwise returns + * an error handle. + */ +DART_EXPORT Dart_Handle +Dart_NewExternalLatin1String(const uint8_t* latin1_array, + intptr_t length, + void* peer, + intptr_t external_allocation_size, + Dart_HandleFinalizer callback); + +/** + * Returns a String which references an external array of UTF-16 encoded + * characters. + * + * \param utf16_array An array of UTF-16 encoded characters. This must not move. + * \param length The length of the characters array. + * \param peer An external pointer to associate with this string. + * \param external_allocation_size The number of externally allocated + * bytes for peer. Used to inform the garbage collector. + * \param callback A callback to be called when this string is finalized. + * + * \return The String object if no error occurs. Otherwise returns + * an error handle. + */ +DART_EXPORT Dart_Handle +Dart_NewExternalUTF16String(const uint16_t* utf16_array, + intptr_t length, + void* peer, + intptr_t external_allocation_size, + Dart_HandleFinalizer callback); + +/** + * Gets the C string representation of a String. + * (It is a sequence of UTF-8 encoded values with a '\0' termination.) + * + * \param str A string. + * \param cstr Returns the String represented as a C string. + * This C string is scope allocated and is only valid until + * the next call to Dart_ExitScope. + * + * \return A valid handle if no error occurs during the operation. + */ +DART_EXPORT Dart_Handle Dart_StringToCString(Dart_Handle str, + const char** cstr); + +/** + * Gets a UTF-8 encoded representation of a String. + * + * Any unpaired surrogate code points in the string will be converted as + * replacement characters (U+FFFD, 0xEF 0xBF 0xBD in UTF-8). If you need + * to preserve unpaired surrogates, use the Dart_StringToUTF16 function. + * + * \param str A string. + * \param utf8_array Returns the String represented as UTF-8 code + * units. This UTF-8 array is scope allocated and is only valid + * until the next call to Dart_ExitScope. + * \param length Used to return the length of the array which was + * actually used. + * + * \return A valid handle if no error occurs during the operation. + */ +DART_EXPORT Dart_Handle Dart_StringToUTF8(Dart_Handle str, + uint8_t** utf8_array, + intptr_t* length); + +/** + * Gets the data corresponding to the string object. This function returns + * the data only for Latin-1 (ISO-8859-1) string objects. For all other + * string objects it returns an error. + * + * \param str A string. + * \param latin1_array An array allocated by the caller, used to return + * the string data. + * \param length Used to pass in the length of the provided array. + * Used to return the length of the array which was actually used. + * + * \return A valid handle if no error occurs during the operation. + */ +DART_EXPORT Dart_Handle Dart_StringToLatin1(Dart_Handle str, + uint8_t* latin1_array, + intptr_t* length); + +/** + * Gets the UTF-16 encoded representation of a string. + * + * \param str A string. + * \param utf16_array An array allocated by the caller, used to return + * the array of UTF-16 encoded characters. + * \param length Used to pass in the length of the provided array. + * Used to return the length of the array which was actually used. + * + * \return A valid handle if no error occurs during the operation. + */ +DART_EXPORT Dart_Handle Dart_StringToUTF16(Dart_Handle str, + uint16_t* utf16_array, + intptr_t* length); + +/** + * Gets the storage size in bytes of a String. + * + * \param str A String. + * \param size Returns the storage size in bytes of the String. + * This is the size in bytes needed to store the String. + * + * \return A valid handle if no error occurs during the operation. + */ +DART_EXPORT Dart_Handle Dart_StringStorageSize(Dart_Handle str, intptr_t* size); + +/** + * Retrieves some properties associated with a String. + * Properties retrieved are: + * - character size of the string (one or two byte) + * - length of the string + * - peer pointer of string if it is an external string. + * \param str A String. + * \param char_size Returns the character size of the String. + * \param str_len Returns the length of the String. + * \param peer Returns the peer pointer associated with the String or 0 if + * there is no peer pointer for it. + * \return Success if no error occurs. Otherwise returns + * an error handle. + */ +DART_EXPORT Dart_Handle Dart_StringGetProperties(Dart_Handle str, + intptr_t* char_size, + intptr_t* str_len, + void** peer); + +/* + * ===== + * Lists + * ===== + */ + +/** + * Returns a List of the desired length. + * + * \param length The length of the list. + * + * \return The List object if no error occurs. Otherwise returns + * an error handle. + */ +DART_EXPORT Dart_Handle Dart_NewList(intptr_t length); + +typedef enum { + Dart_CoreType_Dynamic, + Dart_CoreType_Int, + Dart_CoreType_String, +} Dart_CoreType_Id; + +// TODO(bkonyi): convert this to use nullable types once NNBD is enabled. +/** + * Returns a List of the desired length with the desired legacy element type. + * + * \param element_type_id The type of elements of the list. + * \param length The length of the list. + * + * \return The List object if no error occurs. Otherwise returns an error + * handle. + */ +DART_EXPORT Dart_Handle Dart_NewListOf(Dart_CoreType_Id element_type_id, + intptr_t length); + +/** + * Returns a List of the desired length with the desired element type. + * + * \param element_type Handle to a nullable type object. E.g., from + * Dart_GetType or Dart_GetNullableType. + * + * \param length The length of the list. + * + * \return The List object if no error occurs. Otherwise returns + * an error handle. + */ +DART_EXPORT Dart_Handle Dart_NewListOfType(Dart_Handle element_type, + intptr_t length); + +/** + * Returns a List of the desired length with the desired element type, filled + * with the provided object. + * + * \param element_type Handle to a type object. E.g., from Dart_GetType. + * + * \param fill_object Handle to an object of type 'element_type' that will be + * used to populate the list. This parameter can only be Dart_Null() if the + * length of the list is 0 or 'element_type' is a nullable type. + * + * \param length The length of the list. + * + * \return The List object if no error occurs. Otherwise returns + * an error handle. + */ +DART_EXPORT Dart_Handle Dart_NewListOfTypeFilled(Dart_Handle element_type, + Dart_Handle fill_object, + intptr_t length); + +/** + * Gets the length of a List. + * + * May generate an unhandled exception error. + * + * \param list A List. + * \param length Returns the length of the List. + * + * \return A valid handle if no error occurs during the operation. + */ +DART_EXPORT Dart_Handle Dart_ListLength(Dart_Handle list, intptr_t* length); + +/** + * Gets the Object at some index of a List. + * + * If the index is out of bounds, an error occurs. + * + * May generate an unhandled exception error. + * + * \param list A List. + * \param index A valid index into the List. + * + * \return The Object in the List at the specified index if no error + * occurs. Otherwise returns an error handle. + */ +DART_EXPORT Dart_Handle Dart_ListGetAt(Dart_Handle list, intptr_t index); + +/** +* Gets a range of Objects from a List. +* +* If any of the requested index values are out of bounds, an error occurs. +* +* May generate an unhandled exception error. +* +* \param list A List. +* \param offset The offset of the first item to get. +* \param length The number of items to get. +* \param result A pointer to fill with the objects. +* +* \return Success if no error occurs during the operation. +*/ +DART_EXPORT Dart_Handle Dart_ListGetRange(Dart_Handle list, + intptr_t offset, + intptr_t length, + Dart_Handle* result); + +/** + * Sets the Object at some index of a List. + * + * If the index is out of bounds, an error occurs. + * + * May generate an unhandled exception error. + * + * \param list A List. + * \param index A valid index into the List. + * \param value The Object to put in the List. + * + * \return A valid handle if no error occurs during the operation. + */ +DART_EXPORT Dart_Handle Dart_ListSetAt(Dart_Handle list, + intptr_t index, + Dart_Handle value); + +/** + * May generate an unhandled exception error. + */ +DART_EXPORT Dart_Handle Dart_ListGetAsBytes(Dart_Handle list, + intptr_t offset, + uint8_t* native_array, + intptr_t length); + +/** + * May generate an unhandled exception error. + */ +DART_EXPORT Dart_Handle Dart_ListSetAsBytes(Dart_Handle list, + intptr_t offset, + const uint8_t* native_array, + intptr_t length); + +/* + * ==== + * Maps + * ==== + */ + +/** + * Gets the Object at some key of a Map. + * + * May generate an unhandled exception error. + * + * \param map A Map. + * \param key An Object. + * + * \return The value in the map at the specified key, null if the map does not + * contain the key, or an error handle. + */ +DART_EXPORT Dart_Handle Dart_MapGetAt(Dart_Handle map, Dart_Handle key); + +/** + * Returns whether the Map contains a given key. + * + * May generate an unhandled exception error. + * + * \param map A Map. + * + * \return A handle on a boolean indicating whether map contains the key. + * Otherwise returns an error handle. + */ +DART_EXPORT Dart_Handle Dart_MapContainsKey(Dart_Handle map, Dart_Handle key); + +/** + * Gets the list of keys of a Map. + * + * May generate an unhandled exception error. + * + * \param map A Map. + * + * \return The list of key Objects if no error occurs. Otherwise returns an + * error handle. + */ +DART_EXPORT Dart_Handle Dart_MapKeys(Dart_Handle map); + +/* + * ========== + * Typed Data + * ========== + */ + +typedef enum { + Dart_TypedData_kByteData = 0, + Dart_TypedData_kInt8, + Dart_TypedData_kUint8, + Dart_TypedData_kUint8Clamped, + Dart_TypedData_kInt16, + Dart_TypedData_kUint16, + Dart_TypedData_kInt32, + Dart_TypedData_kUint32, + Dart_TypedData_kInt64, + Dart_TypedData_kUint64, + Dart_TypedData_kFloat32, + Dart_TypedData_kFloat64, + Dart_TypedData_kInt32x4, + Dart_TypedData_kFloat32x4, + Dart_TypedData_kFloat64x2, + Dart_TypedData_kInvalid +} Dart_TypedData_Type; + +/** + * Return type if this object is a TypedData object. + * + * \return kInvalid if the object is not a TypedData object or the appropriate + * Dart_TypedData_Type. + */ +DART_EXPORT Dart_TypedData_Type Dart_GetTypeOfTypedData(Dart_Handle object); + +/** + * Return type if this object is an external TypedData object. + * + * \return kInvalid if the object is not an external TypedData object or + * the appropriate Dart_TypedData_Type. + */ +DART_EXPORT Dart_TypedData_Type +Dart_GetTypeOfExternalTypedData(Dart_Handle object); + +/** + * Returns a TypedData object of the desired length and type. + * + * \param type The type of the TypedData object. + * \param length The length of the TypedData object (length in type units). + * + * \return The TypedData object if no error occurs. Otherwise returns + * an error handle. + */ +DART_EXPORT Dart_Handle Dart_NewTypedData(Dart_TypedData_Type type, + intptr_t length); + +/** + * Returns a TypedData object which references an external data array. + * + * \param type The type of the data array. + * \param data A data array. This array must not move. + * \param length The length of the data array (length in type units). + * + * \return The TypedData object if no error occurs. Otherwise returns + * an error handle. + */ +DART_EXPORT Dart_Handle Dart_NewExternalTypedData(Dart_TypedData_Type type, + void* data, + intptr_t length); + +/** + * Returns a TypedData object which references an external data array. + * + * \param type The type of the data array. + * \param data A data array. This array must not move. + * \param length The length of the data array (length in type units). + * \param peer A pointer to a native object or NULL. This value is + * provided to callback when it is invoked. + * \param external_allocation_size The number of externally allocated + * bytes for peer. Used to inform the garbage collector. + * \param callback A function pointer that will be invoked sometime + * after the object is garbage collected, unless the handle has been deleted. + * A valid callback needs to be specified it cannot be NULL. + * + * \return The TypedData object if no error occurs. Otherwise returns + * an error handle. + */ +DART_EXPORT Dart_Handle +Dart_NewExternalTypedDataWithFinalizer(Dart_TypedData_Type type, + void* data, + intptr_t length, + void* peer, + intptr_t external_allocation_size, + Dart_HandleFinalizer callback); +DART_EXPORT Dart_Handle Dart_NewUnmodifiableExternalTypedDataWithFinalizer( + Dart_TypedData_Type type, + const void* data, + intptr_t length, + void* peer, + intptr_t external_allocation_size, + Dart_HandleFinalizer callback); + +/** + * Returns a ByteBuffer object for the typed data. + * + * \param typed_data The TypedData object. + * + * \return The ByteBuffer object if no error occurs. Otherwise returns + * an error handle. + */ +DART_EXPORT Dart_Handle Dart_NewByteBuffer(Dart_Handle typed_data); + +/** + * Acquires access to the internal data address of a TypedData object. + * + * \param object The typed data object whose internal data address is to + * be accessed. + * \param type The type of the object is returned here. + * \param data The internal data address is returned here. + * \param len Size of the typed array is returned here. + * + * Notes: + * When the internal address of the object is acquired any calls to a + * Dart API function that could potentially allocate an object or run + * any Dart code will return an error. + * + * Any Dart API functions for accessing the data should not be called + * before the corresponding release. In particular, the object should + * not be acquired again before its release. This leads to undefined + * behavior. + * + * \return Success if the internal data address is acquired successfully. + * Otherwise, returns an error handle. + */ +DART_EXPORT Dart_Handle Dart_TypedDataAcquireData(Dart_Handle object, + Dart_TypedData_Type* type, + void** data, + intptr_t* len); + +/** + * Releases access to the internal data address that was acquired earlier using + * Dart_TypedDataAcquireData. + * + * \param object The typed data object whose internal data address is to be + * released. + * + * \return Success if the internal data address is released successfully. + * Otherwise, returns an error handle. + */ +DART_EXPORT Dart_Handle Dart_TypedDataReleaseData(Dart_Handle object); + +/** + * Returns the TypedData object associated with the ByteBuffer object. + * + * \param byte_buffer The ByteBuffer object. + * + * \return The TypedData object if no error occurs. Otherwise returns + * an error handle. + */ +DART_EXPORT Dart_Handle Dart_GetDataFromByteBuffer(Dart_Handle byte_buffer); + +/* + * ============================================================ + * Invoking Constructors, Methods, Closures and Field accessors + * ============================================================ + */ + +/** + * Invokes a constructor, creating a new object. + * + * This function allows hidden constructors (constructors with leading + * underscores) to be called. + * + * \param type Type of object to be constructed. + * \param constructor_name The name of the constructor to invoke. Use + * Dart_Null() or Dart_EmptyString() to invoke the unnamed constructor. + * This name should not include the name of the class. + * \param number_of_arguments Size of the arguments array. + * \param arguments An array of arguments to the constructor. + * + * \return If the constructor is called and completes successfully, + * then the new object. If an error occurs during execution, then an + * error handle is returned. + */ +DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle +Dart_New(Dart_Handle type, + Dart_Handle constructor_name, + int number_of_arguments, + Dart_Handle* arguments); + +/** + * Allocate a new object without invoking a constructor. + * + * \param type The type of an object to be allocated. + * + * \return The new object. If an error occurs during execution, then an + * error handle is returned. + */ +DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle Dart_Allocate(Dart_Handle type); + +/** + * Allocate a new object without invoking a constructor, and sets specified + * native fields. + * + * \param type The type of an object to be allocated. + * \param num_native_fields The number of native fields to set. + * \param native_fields An array containing the value of native fields. + * + * \return The new object. If an error occurs during execution, then an + * error handle is returned. + */ +DART_EXPORT Dart_Handle +Dart_AllocateWithNativeFields(Dart_Handle type, + intptr_t num_native_fields, + const intptr_t* native_fields); + +/** + * Invokes a method or function. + * + * The 'target' parameter may be an object, type, or library. If + * 'target' is an object, then this function will invoke an instance + * method. If 'target' is a type, then this function will invoke a + * static method. If 'target' is a library, then this function will + * invoke a top-level function from that library. + * NOTE: This API call cannot be used to invoke methods of a type object. + * + * This function ignores visibility (leading underscores in names). + * + * May generate an unhandled exception error. + * + * \param target An object, type, or library. + * \param name The name of the function or method to invoke. + * \param number_of_arguments Size of the arguments array. + * \param arguments An array of arguments to the function. + * + * \return If the function or method is called and completes + * successfully, then the return value is returned. If an error + * occurs during execution, then an error handle is returned. + */ +DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle +Dart_Invoke(Dart_Handle target, + Dart_Handle name, + int number_of_arguments, + Dart_Handle* arguments); +/* TODO(turnidge): Document how to invoke operators. */ + +/** + * Invokes a Closure with the given arguments. + * + * May generate an unhandled exception error. + * + * \return If no error occurs during execution, then the result of + * invoking the closure is returned. If an error occurs during + * execution, then an error handle is returned. + */ +DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle +Dart_InvokeClosure(Dart_Handle closure, + int number_of_arguments, + Dart_Handle* arguments); + +/** + * Invokes a Generative Constructor on an object that was previously + * allocated using Dart_Allocate/Dart_AllocateWithNativeFields. + * + * The 'object' parameter must be an object. + * + * This function ignores visibility (leading underscores in names). + * + * May generate an unhandled exception error. + * + * \param object An object. + * \param name The name of the constructor to invoke. + * Use Dart_Null() or Dart_EmptyString() to invoke the unnamed constructor. + * \param number_of_arguments Size of the arguments array. + * \param arguments An array of arguments to the function. + * + * \return If the constructor is called and completes + * successfully, then the object is returned. If an error + * occurs during execution, then an error handle is returned. + */ +DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle +Dart_InvokeConstructor(Dart_Handle object, + Dart_Handle name, + int number_of_arguments, + Dart_Handle* arguments); + +/** + * Gets the value of a field. + * + * The 'container' parameter may be an object, type, or library. If + * 'container' is an object, then this function will access an + * instance field. If 'container' is a type, then this function will + * access a static field. If 'container' is a library, then this + * function will access a top-level variable. + * NOTE: This API call cannot be used to access fields of a type object. + * + * This function ignores field visibility (leading underscores in names). + * + * May generate an unhandled exception error. + * + * \param container An object, type, or library. + * \param name A field name. + * + * \return If no error occurs, then the value of the field is + * returned. Otherwise an error handle is returned. + */ +DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle +Dart_GetField(Dart_Handle container, Dart_Handle name); + +/** + * Sets the value of a field. + * + * The 'container' parameter may actually be an object, type, or + * library. If 'container' is an object, then this function will + * access an instance field. If 'container' is a type, then this + * function will access a static field. If 'container' is a library, + * then this function will access a top-level variable. + * NOTE: This API call cannot be used to access fields of a type object. + * + * This function ignores field visibility (leading underscores in names). + * + * May generate an unhandled exception error. + * + * \param container An object, type, or library. + * \param name A field name. + * \param value The new field value. + * + * \return A valid handle if no error occurs. + */ +DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle +Dart_SetField(Dart_Handle container, Dart_Handle name, Dart_Handle value); + +/* + * ========== + * Exceptions + * ========== + */ + +/* + * TODO(turnidge): Remove these functions from the api and replace all + * uses with Dart_NewUnhandledExceptionError. */ + +/** + * Throws an exception. + * + * This function causes a Dart language exception to be thrown. This + * will proceed in the standard way, walking up Dart frames until an + * appropriate 'catch' block is found, executing 'finally' blocks, + * etc. + * + * If an error handle is passed into this function, the error is + * propagated immediately. See Dart_PropagateError for a discussion + * of error propagation. + * + * If successful, this function does not return. Note that this means + * that the destructors of any stack-allocated C++ objects will not be + * called. If there are no Dart frames on the stack, an error occurs. + * + * \return An error handle if the exception was not thrown. + * Otherwise the function does not return. + */ +DART_EXPORT Dart_Handle Dart_ThrowException(Dart_Handle exception); + +/** + * Rethrows an exception. + * + * Rethrows an exception, unwinding all dart frames on the stack. If + * successful, this function does not return. Note that this means + * that the destructors of any stack-allocated C++ objects will not be + * called. If there are no Dart frames on the stack, an error occurs. + * + * \return An error handle if the exception was not thrown. + * Otherwise the function does not return. + */ +DART_EXPORT Dart_Handle Dart_ReThrowException(Dart_Handle exception, + Dart_Handle stacktrace); + +/* + * =========================== + * Native fields and functions + * =========================== + */ + +/** + * Gets the number of native instance fields in an object. + */ +DART_EXPORT Dart_Handle Dart_GetNativeInstanceFieldCount(Dart_Handle obj, + int* count); + +/** + * Gets the value of a native field. + * + * TODO(turnidge): Document. + */ +DART_EXPORT Dart_Handle Dart_GetNativeInstanceField(Dart_Handle obj, + int index, + intptr_t* value); + +/** + * Sets the value of a native field. + * + * TODO(turnidge): Document. + */ +DART_EXPORT Dart_Handle Dart_SetNativeInstanceField(Dart_Handle obj, + int index, + intptr_t value); + +/** + * The arguments to a native function. + * + * This object is passed to a native function to represent its + * arguments and return value. It allows access to the arguments to a + * native function by index. It also allows the return value of a + * native function to be set. + */ +typedef struct _Dart_NativeArguments* Dart_NativeArguments; + +/** + * Extracts current isolate group data from the native arguments structure. + */ +DART_EXPORT void* Dart_GetNativeIsolateGroupData(Dart_NativeArguments args); + +typedef enum { + Dart_NativeArgument_kBool = 0, + Dart_NativeArgument_kInt32, + Dart_NativeArgument_kUint32, + Dart_NativeArgument_kInt64, + Dart_NativeArgument_kUint64, + Dart_NativeArgument_kDouble, + Dart_NativeArgument_kString, + Dart_NativeArgument_kInstance, + Dart_NativeArgument_kNativeFields, +} Dart_NativeArgument_Type; + +typedef struct _Dart_NativeArgument_Descriptor { + uint8_t type; + uint8_t index; +} Dart_NativeArgument_Descriptor; + +typedef union _Dart_NativeArgument_Value { + bool as_bool; + int32_t as_int32; + uint32_t as_uint32; + int64_t as_int64; + uint64_t as_uint64; + double as_double; + struct { + Dart_Handle dart_str; + void* peer; + } as_string; + struct { + intptr_t num_fields; + intptr_t* values; + } as_native_fields; + Dart_Handle as_instance; +} Dart_NativeArgument_Value; + +enum { + kNativeArgNumberPos = 0, + kNativeArgNumberSize = 8, + kNativeArgTypePos = kNativeArgNumberPos + kNativeArgNumberSize, + kNativeArgTypeSize = 8, +}; + +#define BITMASK(size) ((1 << size) - 1) +#define DART_NATIVE_ARG_DESCRIPTOR(type, position) \ + (((type & BITMASK(kNativeArgTypeSize)) << kNativeArgTypePos) | \ + (position & BITMASK(kNativeArgNumberSize))) + +/** + * Gets the native arguments based on the types passed in and populates + * the passed arguments buffer with appropriate native values. + * + * \param args the Native arguments block passed into the native call. + * \param num_arguments length of argument descriptor array and argument + * values array passed in. + * \param arg_descriptors an array that describes the arguments that + * need to be retrieved. For each argument to be retrieved the descriptor + * contains the argument number (0, 1 etc.) and the argument type + * described using Dart_NativeArgument_Type, e.g: + * DART_NATIVE_ARG_DESCRIPTOR(Dart_NativeArgument_kBool, 1) indicates + * that the first argument is to be retrieved and it should be a boolean. + * \param arg_values array into which the native arguments need to be + * extracted into, the array is allocated by the caller (it could be + * stack allocated to avoid the malloc/free performance overhead). + * + * \return Success if all the arguments could be extracted correctly, + * returns an error handle if there were any errors while extracting the + * arguments (mismatched number of arguments, incorrect types, etc.). + */ +DART_EXPORT Dart_Handle +Dart_GetNativeArguments(Dart_NativeArguments args, + int num_arguments, + const Dart_NativeArgument_Descriptor* arg_descriptors, + Dart_NativeArgument_Value* arg_values); + +/** + * Gets the native argument at some index. + */ +DART_EXPORT Dart_Handle Dart_GetNativeArgument(Dart_NativeArguments args, + int index); +/* TODO(turnidge): Specify the behavior of an out-of-bounds access. */ + +/** + * Gets the number of native arguments. + */ +DART_EXPORT int Dart_GetNativeArgumentCount(Dart_NativeArguments args); + +/** + * Gets all the native fields of the native argument at some index. + * \param args Native arguments structure. + * \param arg_index Index of the desired argument in the structure above. + * \param num_fields size of the intptr_t array 'field_values' passed in. + * \param field_values intptr_t array in which native field values are returned. + * \return Success if the native fields where copied in successfully. Otherwise + * returns an error handle. On success the native field values are copied + * into the 'field_values' array, if the argument at 'arg_index' is a + * null object then 0 is copied as the native field values into the + * 'field_values' array. + */ +DART_EXPORT Dart_Handle +Dart_GetNativeFieldsOfArgument(Dart_NativeArguments args, + int arg_index, + int num_fields, + intptr_t* field_values); + +/** + * Gets the native field of the receiver. + */ +DART_EXPORT Dart_Handle Dart_GetNativeReceiver(Dart_NativeArguments args, + intptr_t* value); + +/** + * Gets a string native argument at some index. + * \param args Native arguments structure. + * \param arg_index Index of the desired argument in the structure above. + * \param peer Returns the peer pointer if the string argument has one. + * \return Success if the string argument has a peer, if it does not + * have a peer then the String object is returned. Otherwise returns + * an error handle (argument is not a String object). + */ +DART_EXPORT Dart_Handle Dart_GetNativeStringArgument(Dart_NativeArguments args, + int arg_index, + void** peer); + +/** + * Gets an integer native argument at some index. + * \param args Native arguments structure. + * \param index Index of the desired argument in the structure above. + * \param value Returns the integer value if the argument is an Integer. + * \return Success if no error occurs. Otherwise returns an error handle. + */ +DART_EXPORT Dart_Handle Dart_GetNativeIntegerArgument(Dart_NativeArguments args, + int index, + int64_t* value); + +/** + * Gets a boolean native argument at some index. + * \param args Native arguments structure. + * \param index Index of the desired argument in the structure above. + * \param value Returns the boolean value if the argument is a Boolean. + * \return Success if no error occurs. Otherwise returns an error handle. + */ +DART_EXPORT Dart_Handle Dart_GetNativeBooleanArgument(Dart_NativeArguments args, + int index, + bool* value); + +/** + * Gets a double native argument at some index. + * \param args Native arguments structure. + * \param index Index of the desired argument in the structure above. + * \param value Returns the double value if the argument is a double. + * \return Success if no error occurs. Otherwise returns an error handle. + */ +DART_EXPORT Dart_Handle Dart_GetNativeDoubleArgument(Dart_NativeArguments args, + int index, + double* value); + +/** + * Sets the return value for a native function. + * + * If retval is an Error handle, then error will be propagated once + * the native functions exits. See Dart_PropagateError for a + * discussion of how different types of errors are propagated. + */ +DART_EXPORT void Dart_SetReturnValue(Dart_NativeArguments args, + Dart_Handle retval); + +DART_EXPORT void Dart_SetWeakHandleReturnValue(Dart_NativeArguments args, + Dart_WeakPersistentHandle rval); + +DART_EXPORT void Dart_SetBooleanReturnValue(Dart_NativeArguments args, + bool retval); + +DART_EXPORT void Dart_SetIntegerReturnValue(Dart_NativeArguments args, + int64_t retval); + +DART_EXPORT void Dart_SetDoubleReturnValue(Dart_NativeArguments args, + double retval); + +/** + * A native function. + */ +typedef void (*Dart_NativeFunction)(Dart_NativeArguments arguments); + +/** + * Native entry resolution callback. + * + * For libraries and scripts which have native functions, the embedder + * can provide a native entry resolver. This callback is used to map a + * name/arity to a Dart_NativeFunction. If no function is found, the + * callback should return NULL. + * + * The parameters to the native resolver function are: + * \param name a Dart string which is the name of the native function. + * \param num_of_arguments is the number of arguments expected by the + * native function. + * \param auto_setup_scope is a boolean flag that can be set by the resolver + * to indicate if this function needs a Dart API scope (see Dart_EnterScope/ + * Dart_ExitScope) to be setup automatically by the VM before calling into + * the native function. By default most native functions would require this + * to be true but some light weight native functions which do not call back + * into the VM through the Dart API may not require a Dart scope to be + * setup automatically. + * + * \return A valid Dart_NativeFunction which resolves to a native entry point + * for the native function. + * + * See Dart_SetNativeResolver. + */ +typedef Dart_NativeFunction (*Dart_NativeEntryResolver)(Dart_Handle name, + int num_of_arguments, + bool* auto_setup_scope); +/* TODO(turnidge): Consider renaming to NativeFunctionResolver or + * NativeResolver. */ + +/** + * Native entry symbol lookup callback. + * + * For libraries and scripts which have native functions, the embedder + * can provide a callback for mapping a native entry to a symbol. This callback + * maps a native function entry PC to the native function name. If no native + * entry symbol can be found, the callback should return NULL. + * + * The parameters to the native reverse resolver function are: + * \param nf A Dart_NativeFunction. + * + * \return A const UTF-8 string containing the symbol name or NULL. + * + * See Dart_SetNativeResolver. + */ +typedef const uint8_t* (*Dart_NativeEntrySymbol)(Dart_NativeFunction nf); + +/** + * FFI Native C function pointer resolver callback. + * + * See Dart_SetFfiNativeResolver. + */ +typedef void* (*Dart_FfiNativeResolver)(const char* name, uintptr_t args_n); + +/* + * =========== + * Environment + * =========== + */ + +/** + * An environment lookup callback function. + * + * \param name The name of the value to lookup in the environment. + * + * \return A valid handle to a string if the name exists in the + * current environment or Dart_Null() if not. + */ +typedef Dart_Handle (*Dart_EnvironmentCallback)(Dart_Handle name); + +/** + * Sets the environment callback for the current isolate. This + * callback is used to lookup environment values by name in the + * current environment. This enables the embedder to supply values for + * the const constructors bool.fromEnvironment, int.fromEnvironment + * and String.fromEnvironment. + */ +DART_EXPORT Dart_Handle +Dart_SetEnvironmentCallback(Dart_EnvironmentCallback callback); + +/** + * Sets the callback used to resolve native functions for a library. + * + * \param library A library. + * \param resolver A native entry resolver. + * + * \return A valid handle if the native resolver was set successfully. + */ +DART_EXPORT Dart_Handle +Dart_SetNativeResolver(Dart_Handle library, + Dart_NativeEntryResolver resolver, + Dart_NativeEntrySymbol symbol); +/* TODO(turnidge): Rename to Dart_LibrarySetNativeResolver? */ + +/** + * Returns the callback used to resolve native functions for a library. + * + * \param library A library. + * \param resolver a pointer to a Dart_NativeEntryResolver + * + * \return A valid handle if the library was found. + */ +DART_EXPORT Dart_Handle +Dart_GetNativeResolver(Dart_Handle library, Dart_NativeEntryResolver* resolver); + +/** + * Returns the callback used to resolve native function symbols for a library. + * + * \param library A library. + * \param resolver a pointer to a Dart_NativeEntrySymbol. + * + * \return A valid handle if the library was found. + */ +DART_EXPORT Dart_Handle Dart_GetNativeSymbol(Dart_Handle library, + Dart_NativeEntrySymbol* resolver); + +/** + * Sets the callback used to resolve FFI native functions for a library. + * The resolved functions are expected to be a C function pointer of the + * correct signature (as specified in the `@FfiNative()` function + * annotation in Dart code). + * + * NOTE: This is an experimental feature and might change in the future. + * + * \param library A library. + * \param resolver A native function resolver. + * + * \return A valid handle if the native resolver was set successfully. + */ +DART_EXPORT Dart_Handle +Dart_SetFfiNativeResolver(Dart_Handle library, Dart_FfiNativeResolver resolver); + +/* + * ===================== + * Scripts and Libraries + * ===================== + */ + +typedef enum { + Dart_kCanonicalizeUrl = 0, + Dart_kImportTag, + Dart_kKernelTag, +} Dart_LibraryTag; + +/** + * The library tag handler is a multi-purpose callback provided by the + * embedder to the Dart VM. The embedder implements the tag handler to + * provide the ability to load Dart scripts and imports. + * + * -- TAGS -- + * + * Dart_kCanonicalizeUrl + * + * This tag indicates that the embedder should canonicalize 'url' with + * respect to 'library'. For most embedders, the + * Dart_DefaultCanonicalizeUrl function is a sufficient implementation + * of this tag. The return value should be a string holding the + * canonicalized url. + * + * Dart_kImportTag + * + * This tag is used to load a library from IsolateMirror.loadUri. The embedder + * should call Dart_LoadLibraryFromKernel to provide the library to the VM. The + * return value should be an error or library (the result from + * Dart_LoadLibraryFromKernel). + * + * Dart_kKernelTag + * + * This tag is used to load the intermediate file (kernel) generated by + * the Dart front end. This tag is typically used when a 'hot-reload' + * of an application is needed and the VM is 'use dart front end' mode. + * The dart front end typically compiles all the scripts, imports and part + * files into one intermediate file hence we don't use the source/import or + * script tags. The return value should be an error or a TypedData containing + * the kernel bytes. + * + */ +typedef Dart_Handle (*Dart_LibraryTagHandler)( + Dart_LibraryTag tag, + Dart_Handle library_or_package_map_url, + Dart_Handle url); + +/** + * Sets library tag handler for the current isolate. This handler is + * used to handle the various tags encountered while loading libraries + * or scripts in the isolate. + * + * \param handler Handler code to be used for handling the various tags + * encountered while loading libraries or scripts in the isolate. + * + * \return If no error occurs, the handler is set for the isolate. + * Otherwise an error handle is returned. + * + * TODO(turnidge): Document. + */ +DART_EXPORT Dart_Handle +Dart_SetLibraryTagHandler(Dart_LibraryTagHandler handler); + +/** + * Handles deferred loading requests. When this handler is invoked, it should + * eventually load the deferred loading unit with the given id and call + * Dart_DeferredLoadComplete or Dart_DeferredLoadCompleteError. It is + * recommended that the loading occur asynchronously, but it is permitted to + * call Dart_DeferredLoadComplete or Dart_DeferredLoadCompleteError before the + * handler returns. + * + * If an error is returned, it will be propagated through + * `prefix.loadLibrary()`. This is useful for synchronous + * implementations, which must propagate any unwind errors from + * Dart_DeferredLoadComplete or Dart_DeferredLoadComplete. Otherwise the handler + * should return a non-error such as `Dart_Null()`. + */ +typedef Dart_Handle (*Dart_DeferredLoadHandler)(intptr_t loading_unit_id); + +/** + * Sets the deferred load handler for the current isolate. This handler is + * used to handle loading deferred imports in an AppJIT or AppAOT program. + */ +DART_EXPORT Dart_Handle +Dart_SetDeferredLoadHandler(Dart_DeferredLoadHandler handler); + +/** + * Notifies the VM that a deferred load completed successfully. This function + * will eventually cause the corresponding `prefix.loadLibrary()` futures to + * complete. + * + * Requires the current isolate to be the same current isolate during the + * invocation of the Dart_DeferredLoadHandler. + */ +DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle +Dart_DeferredLoadComplete(intptr_t loading_unit_id, + const uint8_t* snapshot_data, + const uint8_t* snapshot_instructions); + +/** + * Notifies the VM that a deferred load failed. This function + * will eventually cause the corresponding `prefix.loadLibrary()` futures to + * complete with an error. + * + * If `transient` is true, future invocations of `prefix.loadLibrary()` will + * trigger new load requests. If false, futures invocation will complete with + * the same error. + * + * Requires the current isolate to be the same current isolate during the + * invocation of the Dart_DeferredLoadHandler. + */ +DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle +Dart_DeferredLoadCompleteError(intptr_t loading_unit_id, + const char* error_message, + bool transient); + +/** + * Canonicalizes a url with respect to some library. + * + * The url is resolved with respect to the library's url and some url + * normalizations are performed. + * + * This canonicalization function should be sufficient for most + * embedders to implement the Dart_kCanonicalizeUrl tag. + * + * \param base_url The base url relative to which the url is + * being resolved. + * \param url The url being resolved and canonicalized. This + * parameter is a string handle. + * + * \return If no error occurs, a String object is returned. Otherwise + * an error handle is returned. + */ +DART_EXPORT Dart_Handle Dart_DefaultCanonicalizeUrl(Dart_Handle base_url, + Dart_Handle url); + +/** + * Loads the root library for the current isolate. + * + * Requires there to be no current root library. + * + * \param kernel_buffer A buffer which contains a kernel binary (see + * pkg/kernel/binary.md). Must remain valid until isolate group shutdown. + * \param kernel_size Length of the passed in buffer. + * + * \return A handle to the root library, or an error. + */ +DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle +Dart_LoadScriptFromKernel(const uint8_t* kernel_buffer, intptr_t kernel_size); + +/** + * Gets the library for the root script for the current isolate. + * + * If the root script has not yet been set for the current isolate, + * this function returns Dart_Null(). This function never returns an + * error handle. + * + * \return Returns the root Library for the current isolate or Dart_Null(). + */ +DART_EXPORT Dart_Handle Dart_RootLibrary(void); + +/** + * Sets the root library for the current isolate. + * + * \return Returns an error handle if `library` is not a library handle. + */ +DART_EXPORT Dart_Handle Dart_SetRootLibrary(Dart_Handle library); + +/** + * Lookup or instantiate a legacy type by name and type arguments from a + * Library. + * + * \param library The library containing the class or interface. + * \param class_name The class name for the type. + * \param number_of_type_arguments Number of type arguments. + * For non parametric types the number of type arguments would be 0. + * \param type_arguments Pointer to an array of type arguments. + * For non parametric types a NULL would be passed in for this argument. + * + * \return If no error occurs, the type is returned. + * Otherwise an error handle is returned. + */ +DART_EXPORT Dart_Handle Dart_GetType(Dart_Handle library, + Dart_Handle class_name, + intptr_t number_of_type_arguments, + Dart_Handle* type_arguments); + +/** + * Lookup or instantiate a nullable type by name and type arguments from + * Library. + * + * \param library The library containing the class or interface. + * \param class_name The class name for the type. + * \param number_of_type_arguments Number of type arguments. + * For non parametric types the number of type arguments would be 0. + * \param type_arguments Pointer to an array of type arguments. + * For non parametric types a NULL would be passed in for this argument. + * + * \return If no error occurs, the type is returned. + * Otherwise an error handle is returned. + */ +DART_EXPORT Dart_Handle Dart_GetNullableType(Dart_Handle library, + Dart_Handle class_name, + intptr_t number_of_type_arguments, + Dart_Handle* type_arguments); + +/** + * Lookup or instantiate a non-nullable type by name and type arguments from + * Library. + * + * \param library The library containing the class or interface. + * \param class_name The class name for the type. + * \param number_of_type_arguments Number of type arguments. + * For non parametric types the number of type arguments would be 0. + * \param type_arguments Pointer to an array of type arguments. + * For non parametric types a NULL would be passed in for this argument. + * + * \return If no error occurs, the type is returned. + * Otherwise an error handle is returned. + */ +DART_EXPORT Dart_Handle +Dart_GetNonNullableType(Dart_Handle library, + Dart_Handle class_name, + intptr_t number_of_type_arguments, + Dart_Handle* type_arguments); + +/** + * Creates a nullable version of the provided type. + * + * \param type The type to be converted to a nullable type. + * + * \return If no error occurs, a nullable type is returned. + * Otherwise an error handle is returned. + */ +DART_EXPORT Dart_Handle Dart_TypeToNullableType(Dart_Handle type); + +/** + * Creates a non-nullable version of the provided type. + * + * \param type The type to be converted to a non-nullable type. + * + * \return If no error occurs, a non-nullable type is returned. + * Otherwise an error handle is returned. + */ +DART_EXPORT Dart_Handle Dart_TypeToNonNullableType(Dart_Handle type); + +/** + * A type's nullability. + * + * \param type A Dart type. + * \param result An out parameter containing the result of the check. True if + * the type is of the specified nullability, false otherwise. + * + * \return Returns an error handle if type is not of type Type. + */ +DART_EXPORT Dart_Handle Dart_IsNullableType(Dart_Handle type, bool* result); +DART_EXPORT Dart_Handle Dart_IsNonNullableType(Dart_Handle type, bool* result); +DART_EXPORT Dart_Handle Dart_IsLegacyType(Dart_Handle type, bool* result); + +/** + * Lookup a class or interface by name from a Library. + * + * \param library The library containing the class or interface. + * \param class_name The name of the class or interface. + * + * \return If no error occurs, the class or interface is + * returned. Otherwise an error handle is returned. + */ +DART_EXPORT Dart_Handle Dart_GetClass(Dart_Handle library, + Dart_Handle class_name); +/* TODO(asiva): The above method needs to be removed once all uses + * of it are removed from the embedder code. */ + +/** + * Returns an import path to a Library, such as "file:///test.dart" or + * "dart:core". + */ +DART_EXPORT Dart_Handle Dart_LibraryUrl(Dart_Handle library); + +/** + * Returns a URL from which a Library was loaded. + */ +DART_EXPORT Dart_Handle Dart_LibraryResolvedUrl(Dart_Handle library); + +/** + * \return An array of libraries. + */ +DART_EXPORT Dart_Handle Dart_GetLoadedLibraries(void); + +DART_EXPORT Dart_Handle Dart_LookupLibrary(Dart_Handle url); +/* TODO(turnidge): Consider returning Dart_Null() when the library is + * not found to distinguish that from a true error case. */ + +/** + * Report an loading error for the library. + * + * \param library The library that failed to load. + * \param error The Dart error instance containing the load error. + * + * \return If the VM handles the error, the return value is + * a null handle. If it doesn't handle the error, the error + * object is returned. + */ +DART_EXPORT Dart_Handle Dart_LibraryHandleError(Dart_Handle library, + Dart_Handle error); + +/** + * Called by the embedder to load a partial program. Does not set the root + * library. + * + * \param kernel_buffer A buffer which contains a kernel binary (see + * pkg/kernel/binary.md). Must remain valid until isolate shutdown. + * \param kernel_buffer_size Length of the passed in buffer. + * + * \return A handle to the main library of the compilation unit, or an error. + */ +DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle +Dart_LoadLibraryFromKernel(const uint8_t* kernel_buffer, + intptr_t kernel_buffer_size); +DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle +Dart_LoadLibrary(Dart_Handle kernel_buffer); + +/** + * Indicates that all outstanding load requests have been satisfied. + * This finalizes all the new classes loaded and optionally completes + * deferred library futures. + * + * Requires there to be a current isolate. + * + * \param complete_futures Specify true if all deferred library + * futures should be completed, false otherwise. + * + * \return Success if all classes have been finalized and deferred library + * futures are completed. Otherwise, returns an error. + */ +DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle +Dart_FinalizeLoading(bool complete_futures); + +/* + * ===== + * Peers + * ===== + */ + +/** + * The peer field is a lazily allocated field intended for storage of + * an uncommonly used values. Most instances types can have a peer + * field allocated. The exceptions are subtypes of Null, num, and + * bool. + */ + +/** + * Returns the value of peer field of 'object' in 'peer'. + * + * \param object An object. + * \param peer An out parameter that returns the value of the peer + * field. + * + * \return Returns an error if 'object' is a subtype of Null, num, or + * bool. + */ +DART_EXPORT Dart_Handle Dart_GetPeer(Dart_Handle object, void** peer); + +/** + * Sets the value of the peer field of 'object' to the value of + * 'peer'. + * + * \param object An object. + * \param peer A value to store in the peer field. + * + * \return Returns an error if 'object' is a subtype of Null, num, or + * bool. + */ +DART_EXPORT Dart_Handle Dart_SetPeer(Dart_Handle object, void* peer); + +/* + * ====== + * Kernel + * ====== + */ + +/** + * Experimental support for Dart to Kernel parser isolate. + * + * TODO(hausner): Document finalized interface. + * + */ + +// TODO(33433): Remove kernel service from the embedding API. + +typedef enum { + Dart_KernelCompilationStatus_Unknown = -1, + Dart_KernelCompilationStatus_Ok = 0, + Dart_KernelCompilationStatus_Error = 1, + Dart_KernelCompilationStatus_Crash = 2, + Dart_KernelCompilationStatus_MsgFailed = 3, +} Dart_KernelCompilationStatus; + +typedef struct { + Dart_KernelCompilationStatus status; + bool null_safety; + char* error; + uint8_t* kernel; + intptr_t kernel_size; +} Dart_KernelCompilationResult; + +typedef enum { + Dart_KernelCompilationVerbosityLevel_Error = 0, + Dart_KernelCompilationVerbosityLevel_Warning, + Dart_KernelCompilationVerbosityLevel_Info, + Dart_KernelCompilationVerbosityLevel_All, +} Dart_KernelCompilationVerbosityLevel; + +DART_EXPORT bool Dart_IsKernelIsolate(Dart_Isolate isolate); +DART_EXPORT bool Dart_KernelIsolateIsRunning(void); +DART_EXPORT Dart_Port Dart_KernelPort(void); + +/** + * Compiles the given `script_uri` to a kernel file. + * + * \param platform_kernel A buffer containing the kernel of the platform (e.g. + * `vm_platform_strong.dill`). The VM does not take ownership of this memory. + * + * \param platform_kernel_size The length of the platform_kernel buffer. + * + * \param snapshot_compile Set to `true` when the compilation is for a snapshot. + * This is used by the frontend to determine if compilation related information + * should be printed to console (e.g., null safety mode). + * + * \param embed_sources Set to `true` when sources should be embedded in the + * kernel file. + * + * \param verbosity Specifies the logging behavior of the kernel compilation + * service. + * + * \return Returns the result of the compilation. + * + * On a successful compilation the returned [Dart_KernelCompilationResult] has + * a status of [Dart_KernelCompilationStatus_Ok] and the `kernel`/`kernel_size` + * fields are set. The caller takes ownership of the malloc()ed buffer. + * + * On a failed compilation the `error` might be set describing the reason for + * the failed compilation. The caller takes ownership of the malloc()ed + * error. + * + * Requires there to be a current isolate. + */ +DART_EXPORT Dart_KernelCompilationResult +Dart_CompileToKernel(const char* script_uri, + const uint8_t* platform_kernel, + const intptr_t platform_kernel_size, + bool incremental_compile, + bool snapshot_compile, + bool embed_sources, + const char* package_config, + Dart_KernelCompilationVerbosityLevel verbosity); + +typedef struct { + const char* uri; + const char* source; +} Dart_SourceFile; + +DART_EXPORT Dart_KernelCompilationResult Dart_KernelListDependencies(void); + +/** + * Sets the kernel buffer which will be used to load Dart SDK sources + * dynamically at runtime. + * + * \param platform_kernel A buffer containing kernel which has sources for the + * Dart SDK populated. Note: The VM does not take ownership of this memory. + * + * \param platform_kernel_size The length of the platform_kernel buffer. + */ +DART_EXPORT void Dart_SetDartLibrarySourcesKernel( + const uint8_t* platform_kernel, + const intptr_t platform_kernel_size); + +/** + * Detect the null safety opt-in status. + * + * When running from source, it is based on the opt-in status of `script_uri`. + * When running from a kernel buffer, it is based on the mode used when + * generating `kernel_buffer`. + * When running from an appJIT or AOT snapshot, it is based on the mode used + * when generating `snapshot_data`. + * + * \param script_uri Uri of the script that contains the source code + * + * \param package_config Uri of the package configuration file (either in format + * of .packages or .dart_tool/package_config.json) for the null safety + * detection to resolve package imports against. If this parameter is not + * passed the package resolution of the parent isolate should be used. + * + * \param original_working_directory current working directory when the VM + * process was launched, this is used to correctly resolve the path specified + * for package_config. + * + * \param snapshot_data Buffer containing the snapshot data of the + * isolate or NULL if no snapshot is provided. If provided, the buffers must + * remain valid until the isolate shuts down. + * + * \param snapshot_instructions Buffer containing the snapshot instructions of + * the isolate or NULL if no snapshot is provided. If provided, the buffers + * must remain valid until the isolate shuts down. + * + * \param kernel_buffer A buffer which contains a kernel/DIL program. Must + * remain valid until isolate shutdown. + * + * \param kernel_buffer_size The size of `kernel_buffer`. + * + * \return Returns true if the null safety is opted in by the input being + * run `script_uri`, `snapshot_data` or `kernel_buffer`. + * + */ +DART_EXPORT bool Dart_DetectNullSafety(const char* script_uri, + const char* package_config, + const char* original_working_directory, + const uint8_t* snapshot_data, + const uint8_t* snapshot_instructions, + const uint8_t* kernel_buffer, + intptr_t kernel_buffer_size); + +#define DART_KERNEL_ISOLATE_NAME "kernel-service" + +/* + * ======= + * Service + * ======= + */ + +#define DART_VM_SERVICE_ISOLATE_NAME "vm-service" + +/** + * Returns true if isolate is the service isolate. + * + * \param isolate An isolate + * + * \return Returns true if 'isolate' is the service isolate. + */ +DART_EXPORT bool Dart_IsServiceIsolate(Dart_Isolate isolate); + +/** + * Writes the CPU profile to the timeline as a series of 'instant' events. + * + * Note that this is an expensive operation. + * + * \param main_port The main port of the Isolate whose profile samples to write. + * \param error An optional error, must be free()ed by caller. + * + * \return Returns true if the profile is successfully written and false + * otherwise. + */ +DART_EXPORT bool Dart_WriteProfileToTimeline(Dart_Port main_port, char** error); + +/* + * ============== + * Precompilation + * ============== + */ + +/** + * Compiles all functions reachable from entry points and marks + * the isolate to disallow future compilation. + * + * Entry points should be specified using `@pragma("vm:entry-point")` + * annotation. + * + * \return An error handle if a compilation error or runtime error running const + * constructors was encountered. + */ +DART_EXPORT Dart_Handle Dart_Precompile(void); + +typedef void (*Dart_CreateLoadingUnitCallback)( + void* callback_data, + intptr_t loading_unit_id, + void** write_callback_data, + void** write_debug_callback_data); +typedef void (*Dart_StreamingWriteCallback)(void* callback_data, + const uint8_t* buffer, + intptr_t size); +typedef void (*Dart_StreamingCloseCallback)(void* callback_data); + +DART_EXPORT Dart_Handle Dart_LoadingUnitLibraryUris(intptr_t loading_unit_id); + +// On Darwin systems, 'dlsym' adds an '_' to the beginning of the symbol name. +// Use the '...CSymbol' definitions for resolving through 'dlsym'. The actual +// symbol names in the objects are given by the '...AsmSymbol' definitions. +#if defined(__APPLE__) +#define kSnapshotBuildIdCSymbol "kDartSnapshotBuildId" +#define kVmSnapshotDataCSymbol "kDartVmSnapshotData" +#define kVmSnapshotInstructionsCSymbol "kDartVmSnapshotInstructions" +#define kVmSnapshotBssCSymbol "kDartVmSnapshotBss" +#define kIsolateSnapshotDataCSymbol "kDartIsolateSnapshotData" +#define kIsolateSnapshotInstructionsCSymbol "kDartIsolateSnapshotInstructions" +#define kIsolateSnapshotBssCSymbol "kDartIsolateSnapshotBss" +#else +#define kSnapshotBuildIdCSymbol "_kDartSnapshotBuildId" +#define kVmSnapshotDataCSymbol "_kDartVmSnapshotData" +#define kVmSnapshotInstructionsCSymbol "_kDartVmSnapshotInstructions" +#define kVmSnapshotBssCSymbol "_kDartVmSnapshotBss" +#define kIsolateSnapshotDataCSymbol "_kDartIsolateSnapshotData" +#define kIsolateSnapshotInstructionsCSymbol "_kDartIsolateSnapshotInstructions" +#define kIsolateSnapshotBssCSymbol "_kDartIsolateSnapshotBss" +#endif + +#define kSnapshotBuildIdAsmSymbol "_kDartSnapshotBuildId" +#define kVmSnapshotDataAsmSymbol "_kDartVmSnapshotData" +#define kVmSnapshotInstructionsAsmSymbol "_kDartVmSnapshotInstructions" +#define kVmSnapshotBssAsmSymbol "_kDartVmSnapshotBss" +#define kIsolateSnapshotDataAsmSymbol "_kDartIsolateSnapshotData" +#define kIsolateSnapshotInstructionsAsmSymbol \ + "_kDartIsolateSnapshotInstructions" +#define kIsolateSnapshotBssAsmSymbol "_kDartIsolateSnapshotBss" + +/** + * Creates a precompiled snapshot. + * - A root library must have been loaded. + * - Dart_Precompile must have been called. + * + * Outputs an assembly file defining the symbols listed in the definitions + * above. + * + * The assembly should be compiled as a static or shared library and linked or + * loaded by the embedder. Running this snapshot requires a VM compiled with + * DART_PRECOMPILED_SNAPSHOT. The kDartVmSnapshotData and + * kDartVmSnapshotInstructions should be passed to Dart_Initialize. The + * kDartIsolateSnapshotData and kDartIsolateSnapshotInstructions should be + * passed to Dart_CreateIsolateGroup. + * + * The callback will be invoked one or more times to provide the assembly code. + * + * If stripped is true, then the assembly code will not include DWARF + * debugging sections. + * + * If debug_callback_data is provided, debug_callback_data will be used with + * the callback to provide separate debugging information. + * + * \return A valid handle if no error occurs during the operation. + */ +DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle +Dart_CreateAppAOTSnapshotAsAssembly(Dart_StreamingWriteCallback callback, + void* callback_data, + bool stripped, + void* debug_callback_data); +DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle +Dart_CreateAppAOTSnapshotAsAssemblies( + Dart_CreateLoadingUnitCallback next_callback, + void* next_callback_data, + bool stripped, + Dart_StreamingWriteCallback write_callback, + Dart_StreamingCloseCallback close_callback); + +/** + * Creates a precompiled snapshot. + * - A root library must have been loaded. + * - Dart_Precompile must have been called. + * + * Outputs an ELF shared library defining the symbols + * - _kDartVmSnapshotData + * - _kDartVmSnapshotInstructions + * - _kDartIsolateSnapshotData + * - _kDartIsolateSnapshotInstructions + * + * The shared library should be dynamically loaded by the embedder. + * Running this snapshot requires a VM compiled with DART_PRECOMPILED_SNAPSHOT. + * The kDartVmSnapshotData and kDartVmSnapshotInstructions should be passed to + * Dart_Initialize. The kDartIsolateSnapshotData and + * kDartIsolateSnapshotInstructions should be passed to Dart_CreateIsolate. + * + * The callback will be invoked one or more times to provide the binary output. + * + * If stripped is true, then the binary output will not include DWARF + * debugging sections. + * + * If debug_callback_data is provided, debug_callback_data will be used with + * the callback to provide separate debugging information. + * + * \return A valid handle if no error occurs during the operation. + */ +DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle +Dart_CreateAppAOTSnapshotAsElf(Dart_StreamingWriteCallback callback, + void* callback_data, + bool stripped, + void* debug_callback_data); +DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle +Dart_CreateAppAOTSnapshotAsElfs(Dart_CreateLoadingUnitCallback next_callback, + void* next_callback_data, + bool stripped, + Dart_StreamingWriteCallback write_callback, + Dart_StreamingCloseCallback close_callback); + +/** + * Like Dart_CreateAppAOTSnapshotAsAssembly, but only includes + * kDartVmSnapshotData and kDartVmSnapshotInstructions. It also does + * not strip DWARF information from the generated assembly or allow for + * separate debug information. + */ +DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle +Dart_CreateVMAOTSnapshotAsAssembly(Dart_StreamingWriteCallback callback, + void* callback_data); + +/** + * Sorts the class-ids in depth first traversal order of the inheritance + * tree. This is a costly operation, but it can make method dispatch + * more efficient and is done before writing snapshots. + * + * \return A valid handle if no error occurs during the operation. + */ +DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle Dart_SortClasses(void); + +/** + * Creates a snapshot that caches compiled code and type feedback for faster + * startup and quicker warmup in a subsequent process. + * + * Outputs a snapshot in two pieces. The pieces should be passed to + * Dart_CreateIsolateGroup in a VM using the same VM snapshot pieces used in the + * current VM. The instructions piece must be loaded with read and execute + * permissions; the data piece may be loaded as read-only. + * + * - Requires the VM to have not been started with --precompilation. + * - Not supported when targeting IA32. + * - The VM writing the snapshot and the VM reading the snapshot must be the + * same version, must be built in the same DEBUG/RELEASE/PRODUCT mode, must + * be targeting the same architecture, and must both be in checked mode or + * both in unchecked mode. + * + * The buffers are scope allocated and are only valid until the next call to + * Dart_ExitScope. + * + * \return A valid handle if no error occurs during the operation. + */ +DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle +Dart_CreateAppJITSnapshotAsBlobs(uint8_t** isolate_snapshot_data_buffer, + intptr_t* isolate_snapshot_data_size, + uint8_t** isolate_snapshot_instructions_buffer, + intptr_t* isolate_snapshot_instructions_size); + +/** + * Like Dart_CreateAppJITSnapshotAsBlobs, but also creates a new VM snapshot. + */ +DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle +Dart_CreateCoreJITSnapshotAsBlobs( + uint8_t** vm_snapshot_data_buffer, + intptr_t* vm_snapshot_data_size, + uint8_t** vm_snapshot_instructions_buffer, + intptr_t* vm_snapshot_instructions_size, + uint8_t** isolate_snapshot_data_buffer, + intptr_t* isolate_snapshot_data_size, + uint8_t** isolate_snapshot_instructions_buffer, + intptr_t* isolate_snapshot_instructions_size); + +/** + * Get obfuscation map for precompiled code. + * + * Obfuscation map is encoded as a JSON array of pairs (original name, + * obfuscated name). + * + * \return Returns an error handler if the VM was built in a mode that does not + * support obfuscation. + */ +DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle +Dart_GetObfuscationMap(uint8_t** buffer, intptr_t* buffer_length); + +/** + * Returns whether the VM only supports running from precompiled snapshots and + * not from any other kind of snapshot or from source (that is, the VM was + * compiled with DART_PRECOMPILED_RUNTIME). + */ +DART_EXPORT bool Dart_IsPrecompiledRuntime(void); + +/** + * Print a native stack trace. Used for crash handling. + * + * If context is NULL, prints the current stack trace. Otherwise, context + * should be a CONTEXT* (Windows) or ucontext_t* (POSIX) from a signal handler + * running on the current thread. + */ +DART_EXPORT void Dart_DumpNativeStackTrace(void* context); + +/** + * Indicate that the process is about to abort, and the Dart VM should not + * attempt to cleanup resources. + */ +DART_EXPORT void Dart_PrepareToAbort(void); + +/** + * Callback provided by the embedder that is used by the VM to + * produce footnotes appended to DWARF stack traces. + * + * Whenever VM formats a stack trace as a string it would call this callback + * passing raw program counters for each frame in the stack trace. + * + * Embedder can then return a string which if not-null will be appended to the + * formatted stack trace. + * + * Returned string is expected to be `malloc()` allocated. VM takes ownership + * of the returned string and will `free()` it. + * + * \param addresses raw program counter addresses for each frame + * \param count number of elements in the addresses array + */ +typedef char* (*Dart_DwarfStackTraceFootnoteCallback)(void* addresses[], + intptr_t count); + +/** + * Configure DWARF stack trace footnote callback. + */ +DART_EXPORT void Dart_SetDwarfStackTraceFootnoteCallback( + Dart_DwarfStackTraceFootnoteCallback callback); + +#endif /* INCLUDE_DART_API_H_ */ /* NOLINT */ diff --git a/libcore/bridge/include/dart_api_dl.c b/libcore/bridge/include/dart_api_dl.c new file mode 100644 index 0000000..48fb54e --- /dev/null +++ b/libcore/bridge/include/dart_api_dl.c @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file + * for details. All rights reserved. Use of this source code is governed by a + * BSD-style license that can be found in the LICENSE file. + */ + +#include "dart_api_dl.h" /* NOLINT */ +#include "dart_version.h" /* NOLINT */ +#include "internal/dart_api_dl_impl.h" /* NOLINT */ + +#include +#include + +#define DART_API_DL_DEFINITIONS(name, R, A) name##_Type name##_DL = NULL; + +DART_API_ALL_DL_SYMBOLS(DART_API_DL_DEFINITIONS) +DART_API_DEPRECATED_DL_SYMBOLS(DART_API_DL_DEFINITIONS) + +#undef DART_API_DL_DEFINITIONS + +typedef void* DartApiEntry_function; + +DartApiEntry_function FindFunctionPointer(const DartApiEntry* entries, + const char* name) { + while (entries->name != NULL) { + if (strcmp(entries->name, name) == 0) return entries->function; + entries++; + } + return NULL; +} + +DART_EXPORT void Dart_UpdateExternalSize_Deprecated( + Dart_WeakPersistentHandle object, intptr_t external_size) { + printf("Dart_UpdateExternalSize is a nop, it has been deprecated\n"); +} + +DART_EXPORT void Dart_UpdateFinalizableExternalSize_Deprecated( + Dart_FinalizableHandle object, + Dart_Handle strong_ref_to_object, + intptr_t external_allocation_size) { + printf("Dart_UpdateFinalizableExternalSize is a nop, " + "it has been deprecated\n"); +} + +intptr_t Dart_InitializeApiDL(void* data) { + DartApi* dart_api_data = (DartApi*)data; + + if (dart_api_data->major != DART_API_DL_MAJOR_VERSION) { + // If the DartVM we're running on does not have the same version as this + // file was compiled against, refuse to initialize. The symbols are not + // compatible. + return -1; + } + // Minor versions are allowed to be different. + // If the DartVM has a higher minor version, it will provide more symbols + // than we initialize here. + // If the DartVM has a lower minor version, it will not provide all symbols. + // In that case, we leave the missing symbols un-initialized. Those symbols + // should not be used by the Dart and native code. The client is responsible + // for checking the minor version number himself based on which symbols it + // is using. + // (If we would error out on this case, recompiling native code against a + // newer SDK would break all uses on older SDKs, which is too strict.) + + const DartApiEntry* dart_api_function_pointers = dart_api_data->functions; + +#define DART_API_DL_INIT(name, R, A) \ + name##_DL = \ + (name##_Type)(FindFunctionPointer(dart_api_function_pointers, #name)); + DART_API_ALL_DL_SYMBOLS(DART_API_DL_INIT) +#undef DART_API_DL_INIT + +#define DART_API_DEPRECATED_DL_INIT(name, R, A) \ + name##_DL = name##_Deprecated; + DART_API_DEPRECATED_DL_SYMBOLS(DART_API_DEPRECATED_DL_INIT) +#undef DART_API_DEPRECATED_DL_INIT + + return 0; +} diff --git a/libcore/bridge/include/dart_api_dl.h b/libcore/bridge/include/dart_api_dl.h new file mode 100644 index 0000000..99aa269 --- /dev/null +++ b/libcore/bridge/include/dart_api_dl.h @@ -0,0 +1,162 @@ +/* + * Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file + * for details. All rights reserved. Use of this source code is governed by a + * BSD-style license that can be found in the LICENSE file. + */ + +#ifndef RUNTIME_INCLUDE_DART_API_DL_H_ +#define RUNTIME_INCLUDE_DART_API_DL_H_ + +#include "dart_api.h" /* NOLINT */ +#include "dart_native_api.h" /* NOLINT */ + +/** \mainpage Dynamically Linked Dart API + * + * This exposes a subset of symbols from dart_api.h and dart_native_api.h + * available in every Dart embedder through dynamic linking. + * + * All symbols are postfixed with _DL to indicate that they are dynamically + * linked and to prevent conflicts with the original symbol. + * + * Link `dart_api_dl.c` file into your library and invoke + * `Dart_InitializeApiDL` with `NativeApi.initializeApiDLData`. + */ + +DART_EXPORT intptr_t Dart_InitializeApiDL(void* data); + +// ============================================================================ +// IMPORTANT! Never update these signatures without properly updating +// DART_API_DL_MAJOR_VERSION and DART_API_DL_MINOR_VERSION. +// +// Verbatim copy of `dart_native_api.h` and `dart_api.h` symbol names and types +// to trigger compile-time errors if the symbols in those files are updated +// without updating these. +// +// Function return and argument types, and typedefs are carbon copied. Structs +// are typechecked nominally in C/C++, so they are not copied, instead a +// comment is added to their definition. +typedef int64_t Dart_Port_DL; + +typedef void (*Dart_NativeMessageHandler_DL)(Dart_Port_DL dest_port_id, + Dart_CObject* message); + +// dart_native_api.h symbols can be called on any thread. +#define DART_NATIVE_API_DL_SYMBOLS(F) \ + /***** dart_native_api.h *****/ \ + /* Dart_Port */ \ + F(Dart_PostCObject, bool, (Dart_Port_DL port_id, Dart_CObject * message)) \ + F(Dart_PostInteger, bool, (Dart_Port_DL port_id, int64_t message)) \ + F(Dart_NewNativePort, Dart_Port_DL, \ + (const char* name, Dart_NativeMessageHandler_DL handler, \ + bool handle_concurrently)) \ + F(Dart_CloseNativePort, bool, (Dart_Port_DL native_port_id)) + +// dart_api.h symbols can only be called on Dart threads. +#define DART_API_DL_SYMBOLS(F) \ + /***** dart_api.h *****/ \ + /* Errors */ \ + F(Dart_IsError, bool, (Dart_Handle handle)) \ + F(Dart_IsApiError, bool, (Dart_Handle handle)) \ + F(Dart_IsUnhandledExceptionError, bool, (Dart_Handle handle)) \ + F(Dart_IsCompilationError, bool, (Dart_Handle handle)) \ + F(Dart_IsFatalError, bool, (Dart_Handle handle)) \ + F(Dart_GetError, const char*, (Dart_Handle handle)) \ + F(Dart_ErrorHasException, bool, (Dart_Handle handle)) \ + F(Dart_ErrorGetException, Dart_Handle, (Dart_Handle handle)) \ + F(Dart_ErrorGetStackTrace, Dart_Handle, (Dart_Handle handle)) \ + F(Dart_NewApiError, Dart_Handle, (const char* error)) \ + F(Dart_NewCompilationError, Dart_Handle, (const char* error)) \ + F(Dart_NewUnhandledExceptionError, Dart_Handle, (Dart_Handle exception)) \ + F(Dart_PropagateError, void, (Dart_Handle handle)) \ + /* Dart_Handle, Dart_PersistentHandle, Dart_WeakPersistentHandle */ \ + F(Dart_HandleFromPersistent, Dart_Handle, (Dart_PersistentHandle object)) \ + F(Dart_HandleFromWeakPersistent, Dart_Handle, \ + (Dart_WeakPersistentHandle object)) \ + F(Dart_NewPersistentHandle, Dart_PersistentHandle, (Dart_Handle object)) \ + F(Dart_SetPersistentHandle, void, \ + (Dart_PersistentHandle obj1, Dart_Handle obj2)) \ + F(Dart_DeletePersistentHandle, void, (Dart_PersistentHandle object)) \ + F(Dart_NewWeakPersistentHandle, Dart_WeakPersistentHandle, \ + (Dart_Handle object, void* peer, intptr_t external_allocation_size, \ + Dart_HandleFinalizer callback)) \ + F(Dart_DeleteWeakPersistentHandle, void, (Dart_WeakPersistentHandle object)) \ + F(Dart_NewFinalizableHandle, Dart_FinalizableHandle, \ + (Dart_Handle object, void* peer, intptr_t external_allocation_size, \ + Dart_HandleFinalizer callback)) \ + F(Dart_DeleteFinalizableHandle, void, \ + (Dart_FinalizableHandle object, Dart_Handle strong_ref_to_object)) \ + /* Isolates */ \ + F(Dart_CurrentIsolate, Dart_Isolate, (void)) \ + F(Dart_ExitIsolate, void, (void)) \ + F(Dart_EnterIsolate, void, (Dart_Isolate)) \ + /* Dart_Port */ \ + F(Dart_Post, bool, (Dart_Port_DL port_id, Dart_Handle object)) \ + F(Dart_NewSendPort, Dart_Handle, (Dart_Port_DL port_id)) \ + F(Dart_SendPortGetId, Dart_Handle, \ + (Dart_Handle port, Dart_Port_DL * port_id)) \ + /* Scopes */ \ + F(Dart_EnterScope, void, (void)) \ + F(Dart_ExitScope, void, (void)) \ + /* Objects */ \ + F(Dart_IsNull, bool, (Dart_Handle)) + +// dart_api.h symbols that have been deprecated but are retained here +// until we can make a breaking change bumping the major version number +// (DART_API_DL_MAJOR_VERSION) +#define DART_API_DEPRECATED_DL_SYMBOLS(F) \ + F(Dart_UpdateExternalSize, void, \ + (Dart_WeakPersistentHandle object, intptr_t external_allocation_size)) \ + F(Dart_UpdateFinalizableExternalSize, void, \ + (Dart_FinalizableHandle object, Dart_Handle strong_ref_to_object, \ + intptr_t external_allocation_size)) + +#define DART_API_ALL_DL_SYMBOLS(F) \ + DART_NATIVE_API_DL_SYMBOLS(F) \ + DART_API_DL_SYMBOLS(F) +// IMPORTANT! Never update these signatures without properly updating +// DART_API_DL_MAJOR_VERSION and DART_API_DL_MINOR_VERSION. +// +// End of verbatim copy. +// ============================================================================ + +// Copy of definition of DART_EXPORT without 'used' attribute. +// +// The 'used' attribute cannot be used with DART_API_ALL_DL_SYMBOLS because +// they are not function declarations, but variable declarations with a +// function pointer type. +// +// The function pointer variables are initialized with the addresses of the +// functions in the VM. If we were to use function declarations instead, we +// would need to forward the call to the VM adding indirection. +#if defined(__CYGWIN__) +#error Tool chain and platform not supported. +#elif defined(_WIN32) +#if defined(DART_SHARED_LIB) +#define DART_EXPORT_DL DART_EXTERN_C __declspec(dllexport) +#else +#define DART_EXPORT_DL DART_EXTERN_C +#endif +#else +#if __GNUC__ >= 4 +#if defined(DART_SHARED_LIB) +#define DART_EXPORT_DL DART_EXTERN_C __attribute__((visibility("default"))) +#else +#define DART_EXPORT_DL DART_EXTERN_C +#endif +#else +#error Tool chain not supported. +#endif +#endif + +#define DART_API_DL_DECLARATIONS(name, R, A) \ + typedef R(*name##_Type) A; \ + DART_EXPORT_DL name##_Type name##_DL; + +DART_API_ALL_DL_SYMBOLS(DART_API_DL_DECLARATIONS) +DART_API_DEPRECATED_DL_SYMBOLS(DART_API_DL_DECLARATIONS) + +#undef DART_API_DL_DECLARATIONS + +#undef DART_EXPORT_DL + +#endif /* RUNTIME_INCLUDE_DART_API_DL_H_ */ /* NOLINT */ diff --git a/libcore/bridge/include/dart_embedder_api.h b/libcore/bridge/include/dart_embedder_api.h new file mode 100644 index 0000000..e565ebf --- /dev/null +++ b/libcore/bridge/include/dart_embedder_api.h @@ -0,0 +1,108 @@ +// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +#ifndef RUNTIME_INCLUDE_DART_EMBEDDER_API_H_ +#define RUNTIME_INCLUDE_DART_EMBEDDER_API_H_ + +#include "include/dart_api.h" +#include "include/dart_tools_api.h" + +namespace dart { +namespace embedder { + +// Initialize all subsystems of the embedder. +// +// Must be called before the `Dart_Initialize()` call to initialize the +// Dart VM. +// +// Returns true on success and false otherwise, in which case error would +// contain error message. +DART_WARN_UNUSED_RESULT bool InitOnce(char** error); + +// Cleans up all subsystems of the embedder. +// +// Must be called after the `Dart_Cleanup()` call to initialize the +// Dart VM. +void Cleanup(); + +// Common arguments that are passed to isolate creation callback and to +// API methods that create isolates. +struct IsolateCreationData { + // URI for the main script that will be running in the isolate. + const char* script_uri; + + // Advisory name of the main method that will be run by isolate. + // Only used for error messages. + const char* main; + + // Isolate creation flags. Might be absent. + Dart_IsolateFlags* flags; + + // Isolate group callback data. + void* isolate_group_data; + + // Isolate callback data. + void* isolate_data; +}; + +// Create and initialize kernel-service isolate. This method should be used +// when VM invokes isolate creation callback with DART_KERNEL_ISOLATE_NAME as +// script_uri. +// The isolate is created from the given snapshot (might be kernel data or +// app-jit snapshot). +DART_WARN_UNUSED_RESULT Dart_Isolate +CreateKernelServiceIsolate(const IsolateCreationData& data, + const uint8_t* buffer, + intptr_t buffer_size, + char** error); + +// Service isolate configuration. +struct VmServiceConfiguration { + enum { + kBindHttpServerToAFreePort = 0, + kDoNotAutoStartHttpServer = -1 + }; + + // Address to which HTTP server will be bound. + const char* ip; + + // Default port. See enum above for special values. + int port; + + // If non-null, connection information for the VM service will be output to a + // file in JSON format at the location specified. + const char* write_service_info_filename; + + // TODO(vegorov) document these ones. + bool dev_mode; + bool deterministic; + bool disable_auth_codes; +}; + +// Create and initialize vm-service isolate from the given AOT snapshot, which +// is expected to contain all necessary 'vm-service' libraries. +// This method should be used when VM invokes isolate creation callback with +// DART_VM_SERVICE_ISOLATE_NAME as script_uri. +DART_WARN_UNUSED_RESULT Dart_Isolate +CreateVmServiceIsolate(const IsolateCreationData& data, + const VmServiceConfiguration& config, + const uint8_t* isolate_data, + const uint8_t* isolate_instr, + char** error); + +// Create and initialize vm-service isolate from the given kernel binary, which +// is expected to contain all necessary 'vm-service' libraries. +// This method should be used when VM invokes isolate creation callback with +// DART_VM_SERVICE_ISOLATE_NAME as script_uri. +DART_WARN_UNUSED_RESULT Dart_Isolate +CreateVmServiceIsolateFromKernel(const IsolateCreationData& data, + const VmServiceConfiguration& config, + const uint8_t* kernel_buffer, + intptr_t kernel_buffer_size, + char** error); + +} // namespace embedder +} // namespace dart + +#endif // RUNTIME_INCLUDE_DART_EMBEDDER_API_H_ diff --git a/libcore/bridge/include/dart_native_api.h b/libcore/bridge/include/dart_native_api.h new file mode 100644 index 0000000..79194e0 --- /dev/null +++ b/libcore/bridge/include/dart_native_api.h @@ -0,0 +1,207 @@ +/* + * Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file + * for details. All rights reserved. Use of this source code is governed by a + * BSD-style license that can be found in the LICENSE file. + */ + +#ifndef RUNTIME_INCLUDE_DART_NATIVE_API_H_ +#define RUNTIME_INCLUDE_DART_NATIVE_API_H_ + +#include "dart_api.h" /* NOLINT */ + +/* + * ========================================== + * Message sending/receiving from native code + * ========================================== + */ + +/** + * A Dart_CObject is used for representing Dart objects as native C + * data outside the Dart heap. These objects are totally detached from + * the Dart heap. Only a subset of the Dart objects have a + * representation as a Dart_CObject. + * + * The string encoding in the 'value.as_string' is UTF-8. + * + * All the different types from dart:typed_data are exposed as type + * kTypedData. The specific type from dart:typed_data is in the type + * field of the as_typed_data structure. The length in the + * as_typed_data structure is always in bytes. + * + * The data for kTypedData is copied on message send and ownership remains with + * the caller. The ownership of data for kExternalTyped is passed to the VM on + * message send and returned when the VM invokes the + * Dart_HandleFinalizer callback; a non-NULL callback must be provided. + * + * Note that Dart_CObject_kNativePointer is intended for internal use by + * dart:io implementation and has no connection to dart:ffi Pointer class. + * It represents a pointer to a native resource of a known type. + * The receiving side will only see this pointer as an integer and will not + * see the specified finalizer. + * The specified finalizer will only be invoked if the message is not delivered. + */ +typedef enum { + Dart_CObject_kNull = 0, + Dart_CObject_kBool, + Dart_CObject_kInt32, + Dart_CObject_kInt64, + Dart_CObject_kDouble, + Dart_CObject_kString, + Dart_CObject_kArray, + Dart_CObject_kTypedData, + Dart_CObject_kExternalTypedData, + Dart_CObject_kSendPort, + Dart_CObject_kCapability, + Dart_CObject_kNativePointer, + Dart_CObject_kUnsupported, + Dart_CObject_kUnmodifiableExternalTypedData, + Dart_CObject_kNumberOfTypes +} Dart_CObject_Type; +// This enum is versioned by DART_API_DL_MAJOR_VERSION, only add at the end +// and bump the DART_API_DL_MINOR_VERSION. + +typedef struct _Dart_CObject { + Dart_CObject_Type type; + union { + bool as_bool; + int32_t as_int32; + int64_t as_int64; + double as_double; + const char* as_string; + struct { + Dart_Port id; + Dart_Port origin_id; + } as_send_port; + struct { + int64_t id; + } as_capability; + struct { + intptr_t length; + struct _Dart_CObject** values; + } as_array; + struct { + Dart_TypedData_Type type; + intptr_t length; /* in elements, not bytes */ + const uint8_t* values; + } as_typed_data; + struct { + Dart_TypedData_Type type; + intptr_t length; /* in elements, not bytes */ + uint8_t* data; + void* peer; + Dart_HandleFinalizer callback; + } as_external_typed_data; + struct { + intptr_t ptr; + intptr_t size; + Dart_HandleFinalizer callback; + } as_native_pointer; + } value; +} Dart_CObject; +// This struct is versioned by DART_API_DL_MAJOR_VERSION, bump the version when +// changing this struct. + +/** + * Posts a message on some port. The message will contain the Dart_CObject + * object graph rooted in 'message'. + * + * While the message is being sent the state of the graph of Dart_CObject + * structures rooted in 'message' should not be accessed, as the message + * generation will make temporary modifications to the data. When the message + * has been sent the graph will be fully restored. + * + * If true is returned, the message was enqueued, and finalizers for external + * typed data will eventually run, even if the receiving isolate shuts down + * before processing the message. If false is returned, the message was not + * enqueued and ownership of external typed data in the message remains with the + * caller. + * + * This function may be called on any thread when the VM is running (that is, + * after Dart_Initialize has returned and before Dart_Cleanup has been called). + * + * \param port_id The destination port. + * \param message The message to send. + * + * \return True if the message was posted. + */ +DART_EXPORT bool Dart_PostCObject(Dart_Port port_id, Dart_CObject* message); + +/** + * Posts a message on some port. The message will contain the integer 'message'. + * + * \param port_id The destination port. + * \param message The message to send. + * + * \return True if the message was posted. + */ +DART_EXPORT bool Dart_PostInteger(Dart_Port port_id, int64_t message); + +/** + * A native message handler. + * + * This handler is associated with a native port by calling + * Dart_NewNativePort. + * + * The message received is decoded into the message structure. The + * lifetime of the message data is controlled by the caller. All the + * data references from the message are allocated by the caller and + * will be reclaimed when returning to it. + */ +typedef void (*Dart_NativeMessageHandler)(Dart_Port dest_port_id, + Dart_CObject* message); + +/** + * Creates a new native port. When messages are received on this + * native port, then they will be dispatched to the provided native + * message handler. + * + * \param name The name of this port in debugging messages. + * \param handler The C handler to run when messages arrive on the port. + * \param handle_concurrently Is it okay to process requests on this + * native port concurrently? + * + * \return If successful, returns the port id for the native port. In + * case of error, returns ILLEGAL_PORT. + */ +DART_EXPORT Dart_Port Dart_NewNativePort(const char* name, + Dart_NativeMessageHandler handler, + bool handle_concurrently); +/* TODO(turnidge): Currently handle_concurrently is ignored. */ + +/** + * Closes the native port with the given id. + * + * The port must have been allocated by a call to Dart_NewNativePort. + * + * \param native_port_id The id of the native port to close. + * + * \return Returns true if the port was closed successfully. + */ +DART_EXPORT bool Dart_CloseNativePort(Dart_Port native_port_id); + +/* + * ================== + * Verification Tools + * ================== + */ + +/** + * Forces all loaded classes and functions to be compiled eagerly in + * the current isolate.. + * + * TODO(turnidge): Document. + */ +DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle Dart_CompileAll(void); + +/** + * Finalizes all classes. + */ +DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle Dart_FinalizeAllClasses(void); + +/* This function is intentionally undocumented. + * + * It should not be used outside internal tests. + */ +DART_EXPORT void* Dart_ExecuteInternalCommand(const char* command, void* arg); + +#endif /* INCLUDE_DART_NATIVE_API_H_ */ /* NOLINT */ diff --git a/libcore/bridge/include/dart_tools_api.h b/libcore/bridge/include/dart_tools_api.h new file mode 100644 index 0000000..7b706bc --- /dev/null +++ b/libcore/bridge/include/dart_tools_api.h @@ -0,0 +1,658 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +#ifndef RUNTIME_INCLUDE_DART_TOOLS_API_H_ +#define RUNTIME_INCLUDE_DART_TOOLS_API_H_ + +#include "dart_api.h" /* NOLINT */ + +/** \mainpage Dart Tools Embedding API Reference + * + * This reference describes the Dart embedding API for tools. Tools include + * a debugger, service protocol, and timeline. + * + * NOTE: The APIs described in this file are unstable and subject to change. + * + * This reference is generated from the header include/dart_tools_api.h. + */ + +/* + * ======== + * Debugger + * ======== + */ + +/** + * ILLEGAL_ISOLATE_ID is a number guaranteed never to be associated with a + * valid isolate. + */ +#define ILLEGAL_ISOLATE_ID ILLEGAL_PORT + +/** + * ILLEGAL_ISOLATE_GROUP_ID is a number guaranteed never to be associated with a + * valid isolate group. + */ +#define ILLEGAL_ISOLATE_GROUP_ID 0 + +/* + * ======= + * Service + * ======= + */ + +/** + * A service request callback function. + * + * These callbacks, registered by the embedder, are called when the VM receives + * a service request it can't handle and the service request command name + * matches one of the embedder registered handlers. + * + * The return value of the callback indicates whether the response + * should be used as a regular result or an error result. + * Specifically, if the callback returns true, a regular JSON-RPC + * response is built in the following way: + * + * { + * "jsonrpc": "2.0", + * "result": , + * "id": , + * } + * + * If the callback returns false, a JSON-RPC error is built like this: + * + * { + * "jsonrpc": "2.0", + * "error": , + * "id": , + * } + * + * \param method The rpc method name. + * \param param_keys Service requests can have key-value pair parameters. The + * keys and values are flattened and stored in arrays. + * \param param_values The values associated with the keys. + * \param num_params The length of the param_keys and param_values arrays. + * \param user_data The user_data pointer registered with this handler. + * \param result A C string containing a valid JSON object. The returned + * pointer will be freed by the VM by calling free. + * + * \return True if the result is a regular JSON-RPC response, false if the + * result is a JSON-RPC error. + */ +typedef bool (*Dart_ServiceRequestCallback)(const char* method, + const char** param_keys, + const char** param_values, + intptr_t num_params, + void* user_data, + const char** json_object); + +/** + * Register a Dart_ServiceRequestCallback to be called to handle + * requests for the named rpc on a specific isolate. The callback will + * be invoked with the current isolate set to the request target. + * + * \param method The name of the method that this callback is responsible for. + * \param callback The callback to invoke. + * \param user_data The user data passed to the callback. + * + * NOTE: If multiple callbacks with the same name are registered, only + * the last callback registered will be remembered. + */ +DART_EXPORT void Dart_RegisterIsolateServiceRequestCallback( + const char* method, + Dart_ServiceRequestCallback callback, + void* user_data); + +/** + * Register a Dart_ServiceRequestCallback to be called to handle + * requests for the named rpc. The callback will be invoked without a + * current isolate. + * + * \param method The name of the command that this callback is responsible for. + * \param callback The callback to invoke. + * \param user_data The user data passed to the callback. + * + * NOTE: If multiple callbacks with the same name are registered, only + * the last callback registered will be remembered. + */ +DART_EXPORT void Dart_RegisterRootServiceRequestCallback( + const char* method, + Dart_ServiceRequestCallback callback, + void* user_data); + +/** + * Embedder information which can be requested by the VM for internal or + * reporting purposes. + * + * The pointers in this structure are not going to be cached or freed by the VM. + */ + + #define DART_EMBEDDER_INFORMATION_CURRENT_VERSION (0x00000001) + +typedef struct { + int32_t version; + const char* name; // [optional] The name of the embedder + int64_t current_rss; // [optional] the current RSS of the embedder + int64_t max_rss; // [optional] the maximum RSS of the embedder +} Dart_EmbedderInformation; + +/** + * Callback provided by the embedder that is used by the VM to request + * information. + * + * \return Returns a pointer to a Dart_EmbedderInformation structure. + * The embedder keeps the ownership of the structure and any field in it. + * The embedder must ensure that the structure will remain valid until the + * next invocation of the callback. + */ +typedef void (*Dart_EmbedderInformationCallback)( + Dart_EmbedderInformation* info); + +/** + * Register a Dart_ServiceRequestCallback to be called to handle + * requests for the named rpc. The callback will be invoked without a + * current isolate. + * + * \param method The name of the command that this callback is responsible for. + * \param callback The callback to invoke. + * \param user_data The user data passed to the callback. + * + * NOTE: If multiple callbacks are registered, only the last callback registered + * will be remembered. + */ +DART_EXPORT void Dart_SetEmbedderInformationCallback( + Dart_EmbedderInformationCallback callback); + +/** + * Invoke a vm-service method and wait for its result. + * + * \param request_json The utf8-encoded json-rpc request. + * \param request_json_length The length of the json-rpc request. + * + * \param response_json The returned utf8-encoded json response, must be + * free()ed by caller. + * \param response_json_length The length of the returned json response. + * \param error An optional error, must be free()ed by caller. + * + * \return Whether the call was successfully performed. + * + * NOTE: This method does not need a current isolate and must not have the + * vm-isolate being the current isolate. It must be called after + * Dart_Initialize() and before Dart_Cleanup(). + */ +DART_EXPORT bool Dart_InvokeVMServiceMethod(uint8_t* request_json, + intptr_t request_json_length, + uint8_t** response_json, + intptr_t* response_json_length, + char** error); + +/* + * ======== + * Event Streams + * ======== + */ + +/** + * A callback invoked when the VM service gets a request to listen to + * some stream. + * + * \return Returns true iff the embedder supports the named stream id. + */ +typedef bool (*Dart_ServiceStreamListenCallback)(const char* stream_id); + +/** + * A callback invoked when the VM service gets a request to cancel + * some stream. + */ +typedef void (*Dart_ServiceStreamCancelCallback)(const char* stream_id); + +/** + * Adds VM service stream callbacks. + * + * \param listen_callback A function pointer to a listen callback function. + * A listen callback function should not be already set when this function + * is called. A NULL value removes the existing listen callback function + * if any. + * + * \param cancel_callback A function pointer to a cancel callback function. + * A cancel callback function should not be already set when this function + * is called. A NULL value removes the existing cancel callback function + * if any. + * + * \return Success if the callbacks were added. Otherwise, returns an + * error handle. + */ +DART_EXPORT char* Dart_SetServiceStreamCallbacks( + Dart_ServiceStreamListenCallback listen_callback, + Dart_ServiceStreamCancelCallback cancel_callback); + +/** + * Sends a data event to clients of the VM Service. + * + * A data event is used to pass an array of bytes to subscribed VM + * Service clients. For example, in the standalone embedder, this is + * function used to provide WriteEvents on the Stdout and Stderr + * streams. + * + * If the embedder passes in a stream id for which no client is + * subscribed, then the event is ignored. + * + * \param stream_id The id of the stream on which to post the event. + * + * \param event_kind A string identifying what kind of event this is. + * For example, 'WriteEvent'. + * + * \param bytes A pointer to an array of bytes. + * + * \param bytes_length The length of the byte array. + * + * \return NULL if the arguments are well formed. Otherwise, returns an + * error string. The caller is responsible for freeing the error message. + */ +DART_EXPORT char* Dart_ServiceSendDataEvent(const char* stream_id, + const char* event_kind, + const uint8_t* bytes, + intptr_t bytes_length); + +/* + * ======== + * Reload support + * ======== + * + * These functions are used to implement reloading in the Dart VM. + * This is an experimental feature, so embedders should be prepared + * for these functions to change. + */ + +/** + * A callback which determines whether the file at some url has been + * modified since some time. If the file cannot be found, true should + * be returned. + */ +typedef bool (*Dart_FileModifiedCallback)(const char* url, int64_t since); + +DART_EXPORT char* Dart_SetFileModifiedCallback( + Dart_FileModifiedCallback file_modified_callback); + +/** + * Returns true if isolate is currently reloading. + */ +DART_EXPORT bool Dart_IsReloading(); + +/* + * ======== + * Timeline + * ======== + */ + +/** + * Enable tracking of specified timeline category. This is operational + * only when systrace timeline functionality is turned on. + * + * \param categories A comma separated list of categories that need to + * be enabled, the categories are + * "all" : All categories + * "API" - Execution of Dart C API functions + * "Compiler" - Execution of Dart JIT compiler + * "CompilerVerbose" - More detailed Execution of Dart JIT compiler + * "Dart" - Execution of Dart code + * "Debugger" - Execution of Dart debugger + * "Embedder" - Execution of Dart embedder code + * "GC" - Execution of Dart Garbage Collector + * "Isolate" - Dart Isolate lifecycle execution + * "VM" - Execution in Dart VM runtime code + * "" - None + * + * When "all" is specified all the categories are enabled. + * When a comma separated list of categories is specified, the categories + * that are specified will be enabled and the rest will be disabled. + * When "" is specified all the categories are disabled. + * The category names are case sensitive. + * eg: Dart_EnableTimelineCategory("all"); + * Dart_EnableTimelineCategory("GC,API,Isolate"); + * Dart_EnableTimelineCategory("GC,Debugger,Dart"); + * + * \return True if the categories were successfully enabled, False otherwise. + */ +DART_EXPORT bool Dart_SetEnabledTimelineCategory(const char* categories); + +/** + * Returns a timestamp in microseconds. This timestamp is suitable for + * passing into the timeline system, and uses the same monotonic clock + * as dart:developer's Timeline.now. + * + * \return A timestamp that can be passed to the timeline system. + */ +DART_EXPORT int64_t Dart_TimelineGetMicros(); + +/** + * Returns a raw timestamp in from the monotonic clock. + * + * \return A raw timestamp from the monotonic clock. + */ +DART_EXPORT int64_t Dart_TimelineGetTicks(); + +/** + * Returns the frequency of the monotonic clock. + * + * \return The frequency of the monotonic clock. + */ +DART_EXPORT int64_t Dart_TimelineGetTicksFrequency(); + +typedef enum { + Dart_Timeline_Event_Begin, // Phase = 'B'. + Dart_Timeline_Event_End, // Phase = 'E'. + Dart_Timeline_Event_Instant, // Phase = 'i'. + Dart_Timeline_Event_Duration, // Phase = 'X'. + Dart_Timeline_Event_Async_Begin, // Phase = 'b'. + Dart_Timeline_Event_Async_End, // Phase = 'e'. + Dart_Timeline_Event_Async_Instant, // Phase = 'n'. + Dart_Timeline_Event_Counter, // Phase = 'C'. + Dart_Timeline_Event_Flow_Begin, // Phase = 's'. + Dart_Timeline_Event_Flow_Step, // Phase = 't'. + Dart_Timeline_Event_Flow_End, // Phase = 'f'. +} Dart_Timeline_Event_Type; + +/** + * Add a timeline event to the embedder stream. + * + * DEPRECATED: this function will be removed in Dart SDK v3.2. + * + * \param label The name of the event. Its lifetime must extend at least until + * Dart_Cleanup. + * \param timestamp0 The first timestamp of the event. + * \param timestamp1_or_id When reporting an event of type + * |Dart_Timeline_Event_Duration|, the second (end) timestamp of the event + * should be passed through |timestamp1_or_id|. When reporting an event of + * type |Dart_Timeline_Event_Async_Begin|, |Dart_Timeline_Event_Async_End|, + * or |Dart_Timeline_Event_Async_Instant|, the async ID associated with the + * event should be passed through |timestamp1_or_id|. When reporting an + * event of type |Dart_Timeline_Event_Flow_Begin|, + * |Dart_Timeline_Event_Flow_Step|, or |Dart_Timeline_Event_Flow_End|, the + * flow ID associated with the event should be passed through + * |timestamp1_or_id|. When reporting an event of type + * |Dart_Timeline_Event_Begin| or |Dart_Timeline_Event_End|, the event ID + * associated with the event should be passed through |timestamp1_or_id|. + * Note that this event ID will only be used by the MacOS recorder. The + * argument to |timestamp1_or_id| will not be used when reporting events of + * other types. + * \param argument_count The number of argument names and values. + * \param argument_names An array of names of the arguments. The lifetime of the + * names must extend at least until Dart_Cleanup. The array may be reclaimed + * when this call returns. + * \param argument_values An array of values of the arguments. The values and + * the array may be reclaimed when this call returns. + */ +DART_EXPORT void Dart_TimelineEvent(const char* label, + int64_t timestamp0, + int64_t timestamp1_or_id, + Dart_Timeline_Event_Type type, + intptr_t argument_count, + const char** argument_names, + const char** argument_values); + +/** + * Add a timeline event to the embedder stream. + * + * Note regarding flow events: events must be associated with flow IDs in two + * different ways to allow flow events to be serialized correctly in both + * Chrome's JSON trace event format and Perfetto's proto trace format. Events + * of type |Dart_Timeline_Event_Flow_Begin|, |Dart_Timeline_Event_Flow_Step|, + * and |Dart_Timeline_Event_Flow_End| must be reported to support serialization + * in Chrome's trace format. The |flow_ids| argument must be supplied when + * reporting events of type |Dart_Timeline_Event_Begin|, + * |Dart_Timeline_Event_Duration|, |Dart_Timeline_Event_Instant|, + * |Dart_Timeline_Event_Async_Begin|, and |Dart_Timeline_Event_Async_Instant| to + * support serialization in Perfetto's proto format. + * + * \param label The name of the event. Its lifetime must extend at least until + * Dart_Cleanup. + * \param timestamp0 The first timestamp of the event. + * \param timestamp1_or_id When reporting an event of type + * |Dart_Timeline_Event_Duration|, the second (end) timestamp of the event + * should be passed through |timestamp1_or_id|. When reporting an event of + * type |Dart_Timeline_Event_Async_Begin|, |Dart_Timeline_Event_Async_End|, + * or |Dart_Timeline_Event_Async_Instant|, the async ID associated with the + * event should be passed through |timestamp1_or_id|. When reporting an + * event of type |Dart_Timeline_Event_Flow_Begin|, + * |Dart_Timeline_Event_Flow_Step|, or |Dart_Timeline_Event_Flow_End|, the + * flow ID associated with the event should be passed through + * |timestamp1_or_id|. When reporting an event of type + * |Dart_Timeline_Event_Begin| or |Dart_Timeline_Event_End|, the event ID + * associated with the event should be passed through |timestamp1_or_id|. + * Note that this event ID will only be used by the MacOS recorder. The + * argument to |timestamp1_or_id| will not be used when reporting events of + * other types. + * \param flow_id_count The number of flow IDs associated with this event. + * \param flow_ids An array of flow IDs associated with this event. The array + * may be reclaimed when this call returns. + * \param argument_count The number of argument names and values. + * \param argument_names An array of names of the arguments. The lifetime of the + * names must extend at least until Dart_Cleanup. The array may be reclaimed + * when this call returns. + * \param argument_values An array of values of the arguments. The values and + * the array may be reclaimed when this call returns. + */ +DART_EXPORT void Dart_RecordTimelineEvent(const char* label, + int64_t timestamp0, + int64_t timestamp1_or_id, + intptr_t flow_id_count, + const int64_t* flow_ids, + Dart_Timeline_Event_Type type, + intptr_t argument_count, + const char** argument_names, + const char** argument_values); + +/** + * Associates a name with the current thread. This name will be used to name + * threads in the timeline. Can only be called after a call to Dart_Initialize. + * + * \param name The name of the thread. + */ +DART_EXPORT void Dart_SetThreadName(const char* name); + +typedef struct { + const char* name; + const char* value; +} Dart_TimelineRecorderEvent_Argument; + +#define DART_TIMELINE_RECORDER_CURRENT_VERSION (0x00000002) + +typedef struct { + /* Set to DART_TIMELINE_RECORDER_CURRENT_VERSION */ + int32_t version; + + /* The event's type / phase. */ + Dart_Timeline_Event_Type type; + + /* The event's timestamp according to the same clock as + * Dart_TimelineGetMicros. For a duration event, this is the beginning time. + */ + int64_t timestamp0; + + /** + * For a duration event, this is the end time. For an async event, this is the + * async ID. For a flow event, this is the flow ID. For a begin or end event, + * this is the event ID (which is only referenced by the MacOS recorder). + */ + int64_t timestamp1_or_id; + + /* The current isolate of the event, as if by Dart_GetMainPortId, or + * ILLEGAL_PORT if the event had no current isolate. */ + Dart_Port isolate; + + /* The current isolate group of the event, as if by + * Dart_CurrentIsolateGroupId, or ILLEGAL_PORT if the event had no current + * isolate group. */ + Dart_IsolateGroupId isolate_group; + + /* The callback data associated with the isolate if any. */ + void* isolate_data; + + /* The callback data associated with the isolate group if any. */ + void* isolate_group_data; + + /* The name / label of the event. */ + const char* label; + + /* The stream / category of the event. */ + const char* stream; + + intptr_t argument_count; + Dart_TimelineRecorderEvent_Argument* arguments; +} Dart_TimelineRecorderEvent; + +/** + * Callback provided by the embedder to handle the completion of timeline + * events. + * + * \param event A timeline event that has just been completed. The VM keeps + * ownership of the event and any field in it (i.e., the embedder should copy + * any values it needs after the callback returns). + */ +typedef void (*Dart_TimelineRecorderCallback)( + Dart_TimelineRecorderEvent* event); + +/** + * Register a `Dart_TimelineRecorderCallback` to be called as timeline events + * are completed. + * + * The callback will be invoked without a current isolate. + * + * The callback will be invoked on the thread completing the event. Because + * `Dart_TimelineEvent` may be called by any thread, the callback may be called + * on any thread. + * + * The callback may be invoked at any time after `Dart_Initialize` is called and + * before `Dart_Cleanup` returns. + * + * If multiple callbacks are registered, only the last callback registered + * will be remembered. Providing a NULL callback will clear the registration + * (i.e., a NULL callback produced a no-op instead of a crash). + * + * Setting a callback is insufficient to receive events through the callback. The + * VM flag `timeline_recorder` must also be set to `callback`. + */ +DART_EXPORT void Dart_SetTimelineRecorderCallback( + Dart_TimelineRecorderCallback callback); + +/* + * ======= + * Metrics + * ======= + */ + +/** + * Return metrics gathered for the VM and individual isolates. + */ +DART_EXPORT int64_t +Dart_IsolateGroupHeapOldUsedMetric(Dart_IsolateGroup group); // Byte +DART_EXPORT int64_t +Dart_IsolateGroupHeapOldCapacityMetric(Dart_IsolateGroup group); // Byte +DART_EXPORT int64_t +Dart_IsolateGroupHeapOldExternalMetric(Dart_IsolateGroup group); // Byte +DART_EXPORT int64_t +Dart_IsolateGroupHeapNewUsedMetric(Dart_IsolateGroup group); // Byte +DART_EXPORT int64_t +Dart_IsolateGroupHeapNewCapacityMetric(Dart_IsolateGroup group); // Byte +DART_EXPORT int64_t +Dart_IsolateGroupHeapNewExternalMetric(Dart_IsolateGroup group); // Byte + +/* + * ======== + * UserTags + * ======== + */ + +/* + * Gets the current isolate's currently set UserTag instance. + * + * \return The currently set UserTag instance. + */ +DART_EXPORT Dart_Handle Dart_GetCurrentUserTag(); + +/* + * Gets the current isolate's default UserTag instance. + * + * \return The default UserTag with label 'Default' + */ +DART_EXPORT Dart_Handle Dart_GetDefaultUserTag(); + +/* + * Creates a new UserTag instance. + * + * \param label The name of the new UserTag. + * + * \return The newly created UserTag instance or an error handle. + */ +DART_EXPORT Dart_Handle Dart_NewUserTag(const char* label); + +/* + * Updates the current isolate's UserTag to a new value. + * + * \param user_tag The UserTag to be set as the current UserTag. + * + * \return The previously set UserTag instance or an error handle. + */ +DART_EXPORT Dart_Handle Dart_SetCurrentUserTag(Dart_Handle user_tag); + +/* + * Returns the label of a given UserTag instance. + * + * \param user_tag The UserTag from which the label will be retrieved. + * + * \return The UserTag's label. NULL if the user_tag is invalid. The caller is + * responsible for freeing the returned label. + */ +DART_EXPORT DART_WARN_UNUSED_RESULT char* Dart_GetUserTagLabel( + Dart_Handle user_tag); + +/* + * ======= + * Heap Snapshot + * ======= + */ + +/** + * Callback provided by the caller of `Dart_WriteHeapSnapshot` which is + * used to write out chunks of the requested heap snapshot. + * + * \param context An opaque context which was passed to `Dart_WriteHeapSnapshot` + * together with this callback. + * + * \param buffer Pointer to the buffer containing a chunk of the snapshot. + * The callback owns the buffer and needs to `free` it. + * + * \param size Number of bytes in the `buffer` to be written. + * + * \param is_last Set to `true` for the last chunk. The callback will not + * be invoked again after it was invoked once with `is_last` set to `true`. + */ +typedef void (*Dart_HeapSnapshotWriteChunkCallback)(void* context, + uint8_t* buffer, + intptr_t size, + bool is_last); + +/** + * Generate heap snapshot of the current isolate group and stream it into the + * given `callback`. VM would produce snapshot in chunks and send these chunks + * one by one back to the embedder by invoking the provided `callback`. + * + * This API enables embedder to stream snapshot into a file or socket without + * allocating a buffer to hold the whole snapshot in memory. + * + * The isolate group will be paused for the duration of this operation. + * + * \param write Callback used to write chunks of the heap snapshot. + * + * \param context Opaque context which would be passed on each invocation of + * `write` callback. + * + * \returns `nullptr` if the operation is successful otherwise error message. + * Caller owns error message string and needs to `free` it. + */ +DART_EXPORT char* Dart_WriteHeapSnapshot( + Dart_HeapSnapshotWriteChunkCallback write, + void* context); + +#endif // RUNTIME_INCLUDE_DART_TOOLS_API_H_ diff --git a/libcore/bridge/include/dart_version.h b/libcore/bridge/include/dart_version.h new file mode 100644 index 0000000..e2d3651 --- /dev/null +++ b/libcore/bridge/include/dart_version.h @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file + * for details. All rights reserved. Use of this source code is governed by a + * BSD-style license that can be found in the LICENSE file. + */ + +#ifndef RUNTIME_INCLUDE_DART_VERSION_H_ +#define RUNTIME_INCLUDE_DART_VERSION_H_ + +// On breaking changes the major version is increased. +// On backwards compatible changes the minor version is increased. +// The versioning covers the symbols exposed in dart_api_dl.h +#define DART_API_DL_MAJOR_VERSION 2 +#define DART_API_DL_MINOR_VERSION 3 + +#endif /* RUNTIME_INCLUDE_DART_VERSION_H_ */ /* NOLINT */ diff --git a/libcore/bridge/include/internal/dart_api_dl_impl.h b/libcore/bridge/include/internal/dart_api_dl_impl.h new file mode 100644 index 0000000..e4a5689 --- /dev/null +++ b/libcore/bridge/include/internal/dart_api_dl_impl.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file + * for details. All rights reserved. Use of this source code is governed by a + * BSD-style license that can be found in the LICENSE file. + */ + +#ifndef RUNTIME_INCLUDE_INTERNAL_DART_API_DL_IMPL_H_ +#define RUNTIME_INCLUDE_INTERNAL_DART_API_DL_IMPL_H_ + +typedef struct { + const char* name; + void (*function)(void); +} DartApiEntry; + +typedef struct { + const int major; + const int minor; + const DartApiEntry* const functions; +} DartApi; + +#endif /* RUNTIME_INCLUDE_INTERNAL_DART_API_DL_IMPL_H_ */ /* NOLINT */ diff --git a/libcore/build_windows.bat b/libcore/build_windows.bat new file mode 100644 index 0000000..153248a --- /dev/null +++ b/libcore/build_windows.bat @@ -0,0 +1,18 @@ +@echo off +set GOOS=windows +set GOARCH=amd64 +set CC=x86_64-w64-mingw32-gcc +set CGO_ENABLED=1 +go run ./cli tunnel exit +del bin\libcore.dll bin\HiddifyCli.exe +set CGO_LDFLAGS= +go build -trimpath -tags with_gvisor,with_quic,with_wireguard,with_ech,with_utls,with_clash_api,with_grpc -ldflags="-w -s" -buildmode=c-shared -o bin/libcore.dll ./custom +go get github.com/akavel/rsrc +go install github.com/akavel/rsrc + +rsrc -ico .\assets\hiddify-cli.ico -o cli\bydll\cli.syso + +copy bin\libcore.dll . +set CGO_LDFLAGS="libcore.dll" +go build -o bin/HiddifyCli.exe ./cli/bydll/ +del libcore.dll diff --git a/libcore/cli/bydll/clibydll.go b/libcore/cli/bydll/clibydll.go new file mode 100644 index 0000000..02c7184 --- /dev/null +++ b/libcore/cli/bydll/clibydll.go @@ -0,0 +1,35 @@ +package main + +/* +#include +#include + +// Import the function from the DLL +char* parseCli(int argc, char** argv); +*/ +import "C" + +import ( + "fmt" + "os" + "unsafe" +) + +func main() { + args := os.Args + + // Convert []string to []*C.char + var cArgs []*C.char + for _, arg := range args { + cArgs = append(cArgs, C.CString(arg)) + } + defer func() { + for _, arg := range cArgs { + C.free(unsafe.Pointer(arg)) + } + }() + + // Call the C function + result := C.parseCli(C.int(len(cArgs)), (**C.char)(unsafe.Pointer(&cArgs[0]))) + fmt.Println(C.GoString(result)) +} diff --git a/libcore/cli/main.go b/libcore/cli/main.go new file mode 100644 index 0000000..13953ff --- /dev/null +++ b/libcore/cli/main.go @@ -0,0 +1,29 @@ +package main + +import ( + "os" + + "github.com/hiddify/hiddify-core/cmd" +) + +type UpdateRequest struct { + Description string `json:"description,omitempty"` + PrivatePods bool `json:"private_pods"` + OperatingMode string `json:"operating_mode,omitempty"` + ActivationState string `json:"activation_state,omitempty"` +} + +func main() { + cmd.ParseCli(os.Args[1:]) + + // var request UpdateRequest + // // jsonTag, err2 := validation.ErrorFieldName(&request, &request.OperatingMode) + // jsonTag, err2 := request.ValName(&request.OperatingMode) + + // fmt.Println(jsonTag, err2) + // RegisterExtension("com.example.extension", NewExampleExtension()) + // ex := extensionsMap["com.example.extension"].(*Extension[struct]) + // fmt.Println(NewExampleExtension().Get()) + + // fmt.Println(ex.Get()) +} diff --git a/libcore/cmd.bat b/libcore/cmd.bat new file mode 100644 index 0000000..0f7f0c1 --- /dev/null +++ b/libcore/cmd.bat @@ -0,0 +1,4 @@ +@echo off +set TAGS=with_gvisor,with_quic,with_wireguard,with_ech,with_utls,with_clash_api,with_grpc +@REM set TAGS=with_dhcp,with_low_memory,with_conntrack +go run --tags %TAGS% ./cli %* \ No newline at end of file diff --git a/libcore/cmd.sh b/libcore/cmd.sh new file mode 100755 index 0000000..c547a19 --- /dev/null +++ b/libcore/cmd.sh @@ -0,0 +1,4 @@ +go mod tidy +TAGS=with_gvisor,with_quic,with_wireguard,with_ech,with_utls,with_clash_api,with_grpc +# TAGS=with_dhcp,with_low_memory,with_conntrack +go run --tags $TAGS ./cli $@ \ No newline at end of file diff --git a/libcore/cmd/cmd_config.go b/libcore/cmd/cmd_config.go new file mode 100644 index 0000000..f34ebb3 --- /dev/null +++ b/libcore/cmd/cmd_config.go @@ -0,0 +1,188 @@ +package cmd + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + + "github.com/hiddify/hiddify-core/config" + pb "github.com/hiddify/hiddify-core/hiddifyrpc" + v2 "github.com/hiddify/hiddify-core/v2" + "github.com/sagernet/sing-box/experimental/libbox" + "github.com/sagernet/sing-box/log" + "github.com/sagernet/sing-box/option" + + "github.com/spf13/cobra" +) + +var ( + hiddifySettingPath string + configPath string + defaultConfigs config.HiddifyOptions = *config.DefaultHiddifyOptions() + commandBuildOutputPath string +) + +var commandBuild = &cobra.Command{ + Use: "build", + Short: "Build configuration", + Run: func(cmd *cobra.Command, args []string) { + err := build(configPath, hiddifySettingPath) + if err != nil { + log.Fatal(err) + } + }, +} + +var generateConfig = &cobra.Command{ + Use: "gen", + Short: "gen configuration", + Run: func(cmd *cobra.Command, args []string) { + conf, err := v2.GenerateConfig(&pb.GenerateConfigRequest{ + Path: args[0], + }) + if err != nil { + log.Fatal(err) + } + log.Debug(string(conf.ConfigContent)) + }, +} + +var commandCheck = &cobra.Command{ + Use: "check", + Short: "Check configuration", + Run: func(cmd *cobra.Command, args []string) { + err := check(configPath) + if err != nil { + log.Fatal(err) + } + }, +} + +func init() { + commandBuild.Flags().StringVarP(&commandBuildOutputPath, "output", "o", "", "write result to file path instead of stdout") + addHConfigFlags(commandBuild) + + mainCommand.AddCommand(commandBuild) + mainCommand.AddCommand(generateConfig) +} + +func build(path string, optionsPath string) error { + if workingDir != "" { + path = filepath.Join(workingDir, path) + if optionsPath != "" { + optionsPath = filepath.Join(workingDir, optionsPath) + } + os.Chdir(workingDir) + } + options, err := readConfigAt(path) + if err != nil { + return err + } + + HiddifyOptions := &defaultConfigs // config.DefaultHiddifyOptions() + if optionsPath != "" { + HiddifyOptions, err = readHiddifyOptionsAt(optionsPath) + if err != nil { + return err + } + } + config, err := config.BuildConfigJson(*HiddifyOptions, *options) + if err != nil { + return err + } + if commandBuildOutputPath != "" { + outputPath, _ := filepath.Abs(filepath.Join(workingDir, commandBuildOutputPath)) + err = os.WriteFile(outputPath, []byte(config), 0o644) + if err != nil { + return err + } + fmt.Println("result successfully written to ", outputPath) + // libbox.Setup(outputPath, workingDir, workingDir, true) + // instance, err := NewService(*patchedOptions) + } else { + os.Stdout.WriteString(config) + } + return nil +} + +func check(path string) error { + content, err := os.ReadFile(path) + if err != nil { + return err + } + return libbox.CheckConfig(string(content)) +} + +func readConfigAt(path string) (*option.Options, error) { + content, err := os.ReadFile(path) + if err != nil { + return nil, err + } + var options option.Options + err = options.UnmarshalJSON(content) + if err != nil { + return nil, err + } + return &options, nil +} + +func readConfigBytes(content []byte) (*option.Options, error) { + var options option.Options + err := options.UnmarshalJSON(content) + if err != nil { + return nil, err + } + return &options, nil +} + +func readHiddifyOptionsAt(path string) (*config.HiddifyOptions, error) { + content, err := os.ReadFile(path) + if err != nil { + return nil, err + } + var options config.HiddifyOptions + err = json.Unmarshal(content, &options) + if err != nil { + return nil, err + } + if options.Warp.WireguardConfigStr != "" { + err := json.Unmarshal([]byte(options.Warp.WireguardConfigStr), &options.Warp.WireguardConfig) + if err != nil { + return nil, err + } + } + if options.Warp2.WireguardConfigStr != "" { + err := json.Unmarshal([]byte(options.Warp2.WireguardConfigStr), &options.Warp2.WireguardConfig) + if err != nil { + return nil, err + } + } + + return &options, nil +} + +func addHConfigFlags(commandRun *cobra.Command) { + commandRun.Flags().StringVarP(&configPath, "config", "c", "", "proxy config path or url") + commandRun.MarkFlagRequired("config") + commandRun.Flags().StringVarP(&hiddifySettingPath, "hiddify", "d", "", "Hiddify Setting JSON Path") + commandRun.Flags().BoolVar(&defaultConfigs.EnableFullConfig, "full-config", false, "allows including tags other than output") + commandRun.Flags().StringVar(&defaultConfigs.LogLevel, "log", "warn", "log level") + commandRun.Flags().BoolVar(&defaultConfigs.InboundOptions.EnableTun, "tun", false, "Enable Tun") + commandRun.Flags().BoolVar(&defaultConfigs.InboundOptions.EnableTunService, "tun-service", false, "Enable Tun Service") + commandRun.Flags().BoolVar(&defaultConfigs.InboundOptions.SetSystemProxy, "system-proxy", false, "Enable System Proxy") + commandRun.Flags().Uint16Var(&defaultConfigs.InboundOptions.MixedPort, "in-proxy-port", 2334, "Input Mixed Port") + commandRun.Flags().BoolVar(&defaultConfigs.TLSTricks.EnableFragment, "fragment", false, "Enable Fragment") + commandRun.Flags().StringVar(&defaultConfigs.TLSTricks.FragmentSize, "fragment-size", "2-4", "FragmentSize") + commandRun.Flags().StringVar(&defaultConfigs.TLSTricks.FragmentSleep, "fragment-sleep", "2-4", "FragmentSleep") + + commandRun.Flags().BoolVar(&defaultConfigs.TLSTricks.EnablePadding, "padding", false, "Enable Padding") + commandRun.Flags().StringVar(&defaultConfigs.TLSTricks.PaddingSize, "padding-size", "1300-1400", "PaddingSize") + + commandRun.Flags().BoolVar(&defaultConfigs.TLSTricks.MixedSNICase, "mixed-sni-case", false, "MixedSNICase") + + commandRun.Flags().StringVar(&defaultConfigs.RemoteDnsAddress, "dns-remote", "1.1.1.1", "RemoteDNS (1.1.1.1, https://1.1.1.1/dns-query)") + commandRun.Flags().StringVar(&defaultConfigs.DirectDnsAddress, "dns-direct", "1.1.1.1", "DirectDNS (1.1.1.1, https://1.1.1.1/dns-query)") + commandRun.Flags().StringVar(&defaultConfigs.ClashApiSecret, "web-secret", "", "Web Server Secret") + commandRun.Flags().Uint16Var(&defaultConfigs.ClashApiPort, "web-port", 6756, "Web Server Port") +} diff --git a/libcore/cmd/cmd_extension.go b/libcore/cmd/cmd_extension.go new file mode 100644 index 0000000..fffa5d5 --- /dev/null +++ b/libcore/cmd/cmd_extension.go @@ -0,0 +1,21 @@ +package cmd + +import ( + _ "github.com/hiddify/hiddify-core/extension/repository" + "github.com/hiddify/hiddify-core/extension/server" + "github.com/spf13/cobra" +) + +var commandExtension = &cobra.Command{ + Use: "extension", + Short: "extension configuration", + Args: cobra.MaximumNArgs(0), + Run: func(cmd *cobra.Command, args []string) { + server.StartTestExtensionServer() + }, +} + +func init() { + // commandWarp.Flags().StringVarP(&warpKey, "key", "k", "", "warp key") + mainCommand.AddCommand(commandExtension) +} diff --git a/libcore/cmd/cmd_gen_cert.go b/libcore/cmd/cmd_gen_cert.go new file mode 100644 index 0000000..cd78289 --- /dev/null +++ b/libcore/cmd/cmd_gen_cert.go @@ -0,0 +1,21 @@ +package cmd + +import ( + "os" + + "github.com/hiddify/hiddify-core/utils" + "github.com/spf13/cobra" +) + +var commandGenerateCertification = &cobra.Command{ + Use: "gen-cert", + Short: "Generate certification for web server", + Run: func(cmd *cobra.Command, args []string) { + err := os.MkdirAll("cert", 0o644) + if err != nil { + panic("Error: " + err.Error()) + } + utils.GenerateCertificate("cert/server-cert.pem", "cert/server-key.pem", true, true) + utils.GenerateCertificate("cert/client-cert.pem", "cert/client-key.pem", false, true) + }, +} diff --git a/libcore/cmd/cmd_instance.go b/libcore/cmd/cmd_instance.go new file mode 100644 index 0000000..936ed25 --- /dev/null +++ b/libcore/cmd/cmd_instance.go @@ -0,0 +1,59 @@ +package cmd + +import ( + "os" + "os/signal" + "syscall" + + v2 "github.com/hiddify/hiddify-core/v2" + "github.com/sagernet/sing-box/log" + "github.com/spf13/cobra" +) + +var commandInstance = &cobra.Command{ + Use: "instance", + Short: "instance", + Args: cobra.OnlyValidArgs, + Run: func(cmd *cobra.Command, args []string) { + hiddifySetting := defaultConfigs + if hiddifySettingPath != "" { + hiddifySetting2, err := v2.ReadHiddifyOptionsAt(hiddifySettingPath) + if err != nil { + log.Fatal(err) + } + hiddifySetting = *hiddifySetting2 + } + + instance, err := v2.RunInstanceString(&hiddifySetting, configPath) + if err != nil { + log.Fatal(err) + } + defer instance.Close() + ping, err := instance.PingAverage("http://cp.cloudflare.com", 4) + if err != nil { + // log.Fatal(err) + } + log.Info("Average Ping to Cloudflare : ", ping, "\n") + + for i := 1; i <= 4; i++ { + ping, err := instance.PingCloudflare() + if err != nil { + log.Warn(i, " Error ", err, "\n") + } else { + log.Info(i, " Ping time: ", ping, " ms\n") + } + } + log.Info("Instance is running on port socks5://127.0.0.1:", instance.ListenPort, "\n") + log.Info("Press Ctrl+C to exit\n") + sigChan := make(chan os.Signal, 1) + signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM) + <-sigChan + log.Info("CTRL+C recived-->stopping\n") + instance.Close() + }, +} + +func init() { + mainCommand.AddCommand(commandInstance) + addHConfigFlags(commandInstance) +} diff --git a/libcore/cmd/cmd_parse.go b/libcore/cmd/cmd_parse.go new file mode 100644 index 0000000..9862bfd --- /dev/null +++ b/libcore/cmd/cmd_parse.go @@ -0,0 +1,52 @@ +package cmd + +import ( + "fmt" + "os" + "path/filepath" + + "github.com/hiddify/hiddify-core/config" + "github.com/sagernet/sing-box/log" + "github.com/spf13/cobra" +) + +var commandParseOutputPath string + +var commandParse = &cobra.Command{ + Use: "parse", + Short: "Parse configuration", + Args: cobra.ExactArgs(1), + Run: func(cmd *cobra.Command, args []string) { + err := parse(args[0]) + if err != nil { + log.Fatal(err) + } + }, +} + +func init() { + commandParse.Flags().StringVarP(&commandParseOutputPath, "output", "o", "", "write result to file path instead of stdout") + + mainCommand.AddCommand(commandParse) +} + +func parse(path string) error { + if workingDir != "" { + path = filepath.Join(workingDir, path) + } + config, err := config.ParseConfig(path, true) + if err != nil { + return err + } + if commandParseOutputPath != "" { + outputPath, _ := filepath.Abs(filepath.Join(workingDir, commandParseOutputPath)) + err = os.WriteFile(outputPath, config, 0644) + if err != nil { + return err + } + fmt.Println("result successfully written to ", outputPath) + } else { + os.Stdout.Write(config) + } + return nil +} diff --git a/libcore/cmd/cmd_run.go b/libcore/cmd/cmd_run.go new file mode 100644 index 0000000..a0f5d3e --- /dev/null +++ b/libcore/cmd/cmd_run.go @@ -0,0 +1,28 @@ +package cmd + +import ( + v2 "github.com/hiddify/hiddify-core/v2" + + "github.com/spf13/cobra" +) + +var commandRun = &cobra.Command{ + Use: "run", + Short: "run", + Args: cobra.OnlyValidArgs, + Run: runCommand, +} + +func init() { + // commandRun.PersistentFlags().BoolP("help", "", false, "help for this command") + // commandRun.Flags().StringVarP(&hiddifySettingPath, "hiddify", "d", "", "Hiddify Setting JSON Path") + + addHConfigFlags(commandRun) + + mainCommand.AddCommand(commandRun) +} + +func runCommand(cmd *cobra.Command, args []string) { + v2.Setup("./tmp", "./", "./tmp", 0, false) + v2.RunStandalone(hiddifySettingPath, configPath, defaultConfigs) +} diff --git a/libcore/cmd/cmd_temp.go b/libcore/cmd/cmd_temp.go new file mode 100644 index 0000000..55832b7 --- /dev/null +++ b/libcore/cmd/cmd_temp.go @@ -0,0 +1,141 @@ +package cmd + +// import ( +// "context" +// "fmt" +// "io" +// "math/rand" +// "net/http" +// "net/netip" +// "time" + +// "github.com/hiddify/hiddify-core/common" +// // "github.com/hiddify/hiddify-core/extension_repository/cleanip_scanner" +// "github.com/spf13/cobra" +// "golang.org/x/net/proxy" +// ) + +// var commandTemp = &cobra.Command{ +// Use: "temp", +// Short: "temp", +// Args: cobra.MaximumNArgs(2), +// Run: func(cmd *cobra.Command, args []string) { +// // fmt.Printf("Ping time: %d ms\n", Ping()) +// scanner := cleanip_scanner.NewScannerEngine(&cleanip_scanner.ScannerOptions{ +// UseIPv4: true, +// UseIPv6: common.CanConnectIPv6(), +// MaxDesirableRTT: 500 * time.Millisecond, +// IPQueueSize: 4, +// IPQueueTTL: 10 * time.Second, +// ConcurrentPings: 10, +// // MaxDesirableIPs: e.count, +// CidrList: cleanip_scanner.DefaultCFRanges(), +// PingFunc: func(ip netip.Addr) (cleanip_scanner.IPInfo, error) { +// fmt.Printf("Ping: %s\n", ip.String()) +// return cleanip_scanner.IPInfo{ +// AddrPort: netip.AddrPortFrom(ip, 80), +// RTT: time.Duration(rand.Intn(1000)), +// CreatedAt: time.Now(), +// }, nil +// }, +// }, +// ) + +// ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) +// defer cancel() + +// scanner.Run(ctx) + +// t := time.NewTicker(1 * time.Second) +// defer t.Stop() + +// for { +// ipList := scanner.GetAvailableIPs(false) +// if len(ipList) > 1 { +// // e.result = "" +// for i := 0; i < 2; i++ { +// // result = append(result, ipList[i]) +// // e.result = e.result + ipList[i].AddrPort.String() + "\n" +// fmt.Printf("%d %s\n", ipList[i].RTT, ipList[i].AddrPort.String()) +// } +// return +// } + +// select { +// case <-ctx.Done(): +// // Context is done +// return +// case <-t.C: +// // Prevent the loop from spinning too fast +// continue +// } +// } +// }, +// } + +// func init() { +// mainCommand.AddCommand(commandTemp) +// } + +// func GetContent(url string) (string, error) { +// return ContentFromURL("GET", url, 10*time.Second) +// } + +// func ContentFromURL(method string, url string, timeout time.Duration) (string, error) { +// if method == "" { +// return "", fmt.Errorf("empty method") +// } +// if url == "" { +// return "", fmt.Errorf("empty url") +// } + +// req, err := http.NewRequest(method, url, nil) +// if err != nil { +// return "", err +// } + +// dialer, err := proxy.SOCKS5("tcp", "127.0.0.1:12334", nil, proxy.Direct) +// if err != nil { +// return "", err +// } + +// transport := &http.Transport{ +// Dial: dialer.Dial, +// } + +// client := &http.Client{ +// Transport: transport, +// Timeout: timeout, +// } + +// resp, err := client.Do(req) +// if err != nil { +// return "", err +// } +// defer resp.Body.Close() + +// if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent { +// return "", fmt.Errorf("request failed with status code: %d", resp.StatusCode) +// } + +// body, err := io.ReadAll(resp.Body) +// if err != nil { +// return "", err +// } + +// if body == nil { +// return "", fmt.Errorf("empty body") +// } + +// return string(body), nil +// } + +// func Ping() int { +// startTime := time.Now() +// _, err := ContentFromURL("HEAD", "https://cp.cloudflare.com", 4*time.Second) +// if err != nil { +// return -1 +// } +// duration := time.Since(startTime) +// return int(duration.Milliseconds()) +// } diff --git a/libcore/cmd/cmd_tunnel_service.go b/libcore/cmd/cmd_tunnel_service.go new file mode 100644 index 0000000..899cce5 --- /dev/null +++ b/libcore/cmd/cmd_tunnel_service.go @@ -0,0 +1,40 @@ +package cmd + +import ( + "fmt" + "time" + + "github.com/hiddify/hiddify-core/config" + v2 "github.com/hiddify/hiddify-core/v2" + + "github.com/spf13/cobra" +) + +var commandService = &cobra.Command{ + Use: "tunnel run/start/stop/install/uninstall/activate/deactivate/exit", + Short: "Tunnel Service run/start/stop/install/uninstall/activate/deactivate/exit", + ValidArgs: []string{"run", "start", "stop", "install", "uninstall", "activate", "deactivate", "exit"}, + Args: cobra.MatchAll(cobra.ExactArgs(1), cobra.OnlyValidArgs), + Run: func(cmd *cobra.Command, args []string) { + arg := args[0] + switch arg { + case "activate": + config.ActivateTunnelService(config.HiddifyOptions{ + InboundOptions: config.InboundOptions{ + EnableTunService: true, + MixedPort: 12334, + TUNStack: "gvisor", + }, + }) + <-time.After(1 * time.Second) + + case "deactivate": + config.DeactivateTunnelServiceForce() + case "exit": + config.ExitTunnelService() + default: + code, out := v2.StartTunnelService(arg) + fmt.Printf("exitCode:%d msg=%s", code, out) + } + }, +} diff --git a/libcore/cmd/cmd_warp.go b/libcore/cmd/cmd_warp.go new file mode 100644 index 0000000..df10be3 --- /dev/null +++ b/libcore/cmd/cmd_warp.go @@ -0,0 +1,126 @@ +package cmd + +import ( + "bufio" + "encoding/json" + "fmt" + + "os" + "strings" + + "github.com/hiddify/hiddify-core/config" + T "github.com/sagernet/sing-box/option" + "github.com/spf13/cobra" +) + +var warpKey string + +var commandWarp = &cobra.Command{ + Use: "warp", + Short: "warp configuration", + Args: cobra.ExactArgs(0), + Run: func(cmd *cobra.Command, args []string) { + out, err := generateWarp() + fmt.Printf("out=%v Error! %v", out, err) + if err != nil { + fmt.Printf("Error! %v", err) + } + }, +} + +func init() { + // commandWarp.Flags().StringVarP(&warpKey, "key", "k", "", "warp key") + mainCommand.AddCommand(commandWarp) +} + +type WireGuardConfig struct { + Interface InterfaceConfig `json:"Interface"` + Peer PeerConfig `json:"Peer"` +} + +type InterfaceConfig struct { + PrivateKey string `json:"PrivateKey"` + DNS string `json:"DNS"` + Address []string `json:"Address"` +} + +type PeerConfig struct { + PublicKey string `json:"PublicKey"` + AllowedIPs []string `json:"AllowedIPs"` + Endpoint string `json:"Endpoint"` +} + +type SingboxConfig struct { + Type string `json:"type"` + Tag string `json:"tag"` + Server string `json:"server"` + ServerPort int `json:"server_port"` + LocalAddress []string `json:"local_address"` + PrivateKey string `json:"private_key"` + PeerPublicKey string `json:"peer_public_key"` + Reserved []int `json:"reserved"` + MTU int `json:"mtu"` +} + +func readWireGuardConfig(filePath string) (WireGuardConfig, error) { + file, err := os.Open(filePath) + if err != nil { + return WireGuardConfig{}, err + } + defer file.Close() + + scanner := bufio.NewScanner(file) + + var wgConfig WireGuardConfig + var currentSection string + + for scanner.Scan() { + line := scanner.Text() + + if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") { + currentSection = strings.TrimSpace(line[1 : len(line)-1]) + continue + } + + if currentSection == "Interface" { + parseInterfaceConfig(&wgConfig.Interface, line) + } else if currentSection == "Peer" { + parsePeerConfig(&wgConfig.Peer, line) + } + } + + return wgConfig, nil +} + +func parseInterfaceConfig(interfaceConfig *InterfaceConfig, line string) { + if strings.HasPrefix(line, "PrivateKey") { + interfaceConfig.PrivateKey = strings.TrimSpace(strings.SplitN(line, "=", 2)[1]) + } else if strings.HasPrefix(line, "DNS") { + interfaceConfig.DNS = strings.TrimSpace(strings.SplitN(line, "=", 2)[1]) + } else if strings.HasPrefix(line, "Address") { + interfaceConfig.Address = append(interfaceConfig.Address, strings.TrimSpace(strings.SplitN(line, "=", 2)[1])) + } +} + +func parsePeerConfig(peerConfig *PeerConfig, line string) { + if strings.HasPrefix(line, "PublicKey") { + peerConfig.PublicKey = strings.TrimSpace(strings.SplitN(line, "=", 2)[1]) + } else if strings.HasPrefix(line, "AllowedIPs") { + peerConfig.AllowedIPs = append(peerConfig.AllowedIPs, strings.TrimSpace(strings.SplitN(line, "=", 2)[1])) + } else if strings.HasPrefix(line, "Endpoint") { + peerConfig.Endpoint = strings.TrimSpace(strings.SplitN(line, "=", 2)[1]) + } +} +func generateWarp() (*T.Outbound, error) { + _, _, wg, err := config.GenerateWarpInfo("", "", "") + + // fmt.Printf("%v", wgConfig) + singboxConfig, err := config.GenerateWarpSingbox(*wg, "", 0, "", "", "", "") + singboxJSON, err := json.MarshalIndent(singboxConfig, "", " ") + if err != nil { + fmt.Println("Error marshaling Singbox configuration:", err) + return nil, err + } + fmt.Println(string(singboxJSON)) + return nil, nil +} diff --git a/libcore/cmd/interface.go b/libcore/cmd/interface.go new file mode 100644 index 0000000..8d05e91 --- /dev/null +++ b/libcore/cmd/interface.go @@ -0,0 +1,55 @@ +package cmd + +import ( + "os" + "time" + + "context" + + "github.com/sagernet/sing-box/log" + + "github.com/spf13/cobra" +) + +var ( + workingDir string + disableColor bool +) + +var mainCommand = &cobra.Command{ + Use: "HiddifyCli", + PersistentPreRun: preRun, +} + +func init() { + mainCommand.AddCommand(commandService) + mainCommand.AddCommand(commandGenerateCertification) + + mainCommand.PersistentFlags().StringVarP(&workingDir, "directory", "D", "", "set working directory") + mainCommand.PersistentFlags().BoolVarP(&disableColor, "disable-color", "", false, "disable color output") + +} + +func ParseCli(args []string) error { + mainCommand.SetArgs(args) + err := mainCommand.Execute() + if err != nil { + log.Fatal(err) + } + return err +} + +func preRun(cmd *cobra.Command, args []string) { + if disableColor { + log.SetStdLogger(log.NewDefaultFactory(context.Background(), log.Formatter{BaseTime: time.Now(), DisableColors: true}, os.Stderr, "", nil, false).Logger()) + } + if workingDir != "" { + _, err := os.Stat(workingDir) + if err != nil { + os.MkdirAll(workingDir, 0o0644) + } + if err := os.Chdir(workingDir); err != nil { + log.Fatal(err) + } + } +} diff --git a/libcore/cmd/internal/build_libcore/main.go b/libcore/cmd/internal/build_libcore/main.go new file mode 100644 index 0000000..f47357b --- /dev/null +++ b/libcore/cmd/internal/build_libcore/main.go @@ -0,0 +1,217 @@ +package main + +import ( + "flag" + "os" + "os/exec" + "path/filepath" + "strings" + + "github.com/hiddify/hiddify-core/cmd/internal/build_shared" + _ "github.com/sagernet/gomobile" + "github.com/sagernet/sing-box/log" + "github.com/sagernet/sing/common/rw" +) + +var target string + +func init() { + flag.StringVar(&target, "target", "android", "target platform") +} + +func main() { + flag.Parse() + + switch target { + case "windows": + buildWindows() + case "linux": + buildLinux() + case "macos": + buildMacOS() + case "android": + buildAndroid() + case "ios": + buildIOS() + } +} + +var ( + sharedFlags []string + sharedTags []string + iosTags []string +) + +const libName = "libcore" + +func init() { + sharedFlags = append(sharedFlags, "-trimpath") + sharedFlags = append(sharedFlags, "-ldflags", "-s -w") + sharedTags = append(sharedTags, "with_gvisor", "with_quic", "with_wireguard", "with_ech", "with_utls", "with_clash_api", "with_grpc") + iosTags = append(iosTags, "with_dhcp", "with_low_memory", "with_conntrack") +} + +func setDesktopEnv() { + os.Setenv("CGO_ENABLED", "1") + os.Setenv("buildmode", "c-shared") +} + +func buildWindows() { + setDesktopEnv() + os.Setenv("GOOS", "windows") + os.Setenv("GOARCH", "amd64") + os.Setenv("CC", "x86_64-w64-mingw32-gcc") + + args := []string{"build"} + args = append(args, sharedFlags...) + args = append(args, "-tags") + args = append(args, strings.Join(sharedTags, ",")) + + output := filepath.Join("bin", libName+".dll") + args = append(args, "-o", output, "./custom") + + command := exec.Command("go", args...) + command.Stdout = os.Stdout + command.Stderr = os.Stderr + log.Debug("command: ", command.String()) + err := command.Run() + if err != nil { + log.Fatal(err) + } +} + +func buildLinux() { + setDesktopEnv() + os.Setenv("GOOS", "linux") + os.Setenv("GOARCH", "amd64") + + args := []string{"build"} + args = append(args, sharedFlags...) + args = append(args, "-tags") + args = append(args, strings.Join(sharedTags, ",")) + + output := filepath.Join("bin", libName+".so") + args = append(args, "-o", output, "./custom") + + command := exec.Command("go", args...) + command.Stdout = os.Stdout + command.Stderr = os.Stderr + log.Debug("command: ", command.String()) + err := command.Run() + if err != nil { + log.Fatal(err) + } +} + +func buildMacOS() { + libPaths := []string{} + for _, arch := range []string{"amd64", "arm64"} { + out, err := buildMacOSArch(arch) + if err != nil { + log.Fatal(err) + return + } + libPaths = append(libPaths, out) + } + + args := []string{"-create"} + args = append(args, libPaths...) + args = append(args, "-output", filepath.Join("bin", libName+".dylib")) + + command := exec.Command("lipo", args...) + command.Stdout = os.Stdout + command.Stderr = os.Stderr + log.Debug("command: ", command.String()) + err := command.Run() + if err != nil { + log.Fatal(err) + } +} + +func buildMacOSArch(arch string) (string, error) { + setDesktopEnv() + os.Setenv("GOOS", "darwin") + os.Setenv("GOARCH", arch) + os.Setenv("CGO_CFLAGS", "-mmacosx-version-min=10.11") + os.Setenv("CGO_LDFLAGS", "-mmacosx-version-min=10.11") + + args := []string{"build"} + args = append(args, sharedFlags...) + tags := append(sharedTags, iosTags...) + args = append(args, "-tags") + args = append(args, strings.Join(tags, ",")) + + filename := libName + "-" + arch + ".dylib" + output := filepath.Join("bin", filename) + args = append(args, "-o", output, "./custom") + + command := exec.Command("go", args...) + command.Stdout = os.Stdout + command.Stderr = os.Stderr + log.Debug("command: ", command.String()) + err := command.Run() + if err != nil { + return "", err + } + return output, nil +} + +func buildAndroid() { + build_shared.FindMobile() + build_shared.FindSDK() + + args := []string{ + "bind", + "-v", + "-androidapi", "21", + "-javapkg=io.nekohasekai", + "-libname=box", + "-target=android", + } + + args = append(args, sharedFlags...) + args = append(args, "-tags") + args = append(args, strings.Join(sharedTags, ",")) + + output := filepath.Join("bin", libName+".aar") + args = append(args, "-o", output, "github.com/sagernet/sing-box/experimental/libbox", "./mobile") + + command := exec.Command(build_shared.GoBinPath+"/gomobile", args...) + command.Stdout = os.Stdout + command.Stderr = os.Stderr + log.Debug("command: ", command.String()) + err := command.Run() + if err != nil { + log.Fatal(err) + } +} + +func buildIOS() { + build_shared.FindMobile() + + args := []string{ + "bind", + "-v", + "-libname=box", + "-target", "ios,iossimulator,tvos,tvossimulator,macos", + } + + args = append(args, sharedFlags...) + tags := append(sharedTags, iosTags...) + args = append(args, "-tags") + args = append(args, strings.Join(tags, ",")) + + output := filepath.Join("bin", "Libcore.xcframework") + args = append(args, "-o", output, "github.com/sagernet/sing-box/experimental/libbox", "./mobile") + + command := exec.Command(build_shared.GoBinPath+"/gomobile", args...) + command.Stdout = os.Stdout + command.Stderr = os.Stderr + log.Debug("command: ", command.String()) + err := command.Run() + if err != nil { + log.Fatal(err) + } + + rw.CopyFile("Info.plist", filepath.Join(output, "Info.plist")) +} diff --git a/libcore/cmd/internal/build_shared/sdk.go b/libcore/cmd/internal/build_shared/sdk.go new file mode 100644 index 0000000..5d651e5 --- /dev/null +++ b/libcore/cmd/internal/build_shared/sdk.go @@ -0,0 +1,99 @@ +package build_shared + +import ( + "go/build" + "os" + "path/filepath" + "runtime" + "sort" + "strconv" + "strings" + + "github.com/sagernet/sing-box/log" + "github.com/sagernet/sing/common" + "github.com/sagernet/sing/common/rw" +) + +var ( + androidSDKPath string + androidNDKPath string +) + +func FindSDK() { + searchPath := []string{ + "$ANDROID_HOME", + "$HOME/Android/Sdk", + "$HOME/.local/lib/android/sdk", + "$HOME/Library/Android/sdk", + } + for _, path := range searchPath { + path = os.ExpandEnv(path) + if rw.FileExists(path + "/licenses/android-sdk-license") { + androidSDKPath = path + break + } + } + if androidSDKPath == "" { + log.Fatal("android SDK not found") + } + if !findNDK() { + log.Fatal("android NDK not found") + } + + os.Setenv("ANDROID_HOME", androidSDKPath) + os.Setenv("ANDROID_SDK_HOME", androidSDKPath) + os.Setenv("ANDROID_NDK_HOME", androidNDKPath) + os.Setenv("NDK", androidNDKPath) + os.Setenv("PATH", os.Getenv("PATH")+":"+filepath.Join(androidNDKPath, "toolchains", "llvm", "prebuilt", runtime.GOOS+"-x86_64", "bin")) +} + +func findNDK() bool { + if rw.FileExists(androidSDKPath + "/ndk/26.1.10909125") { + androidNDKPath = androidSDKPath + "/ndk/26.1.10909125" + return true + } + ndkVersions, err := os.ReadDir(androidSDKPath + "/ndk") + if err != nil { + return false + } + versionNames := common.Map(ndkVersions, os.DirEntry.Name) + if len(versionNames) == 0 { + return false + } + sort.Slice(versionNames, func(i, j int) bool { + iVersions := strings.Split(versionNames[i], ".") + jVersions := strings.Split(versionNames[j], ".") + for k := 0; k < len(iVersions) && k < len(jVersions); k++ { + iVersion, _ := strconv.Atoi(iVersions[k]) + jVersion, _ := strconv.Atoi(jVersions[k]) + if iVersion != jVersion { + return iVersion > jVersion + } + } + return true + }) + for _, versionName := range versionNames { + if rw.FileExists(androidSDKPath + "/ndk/" + versionName) { + androidNDKPath = androidSDKPath + "/ndk/" + versionName + return true + } + } + return false +} + +var GoBinPath string + +func FindMobile() { + goBin := filepath.Join(build.Default.GOPATH, "bin") + + if runtime.GOOS == "windows" { + if !rw.FileExists(goBin + "/" + "gobind.exe") { + log.Fatal("missing gomobile.exe installation") + } + } else { + if !rw.FileExists(goBin + "/" + "gobind") { + log.Fatal("missing gomobile installation") + } + } + GoBinPath = goBin +} diff --git a/libcore/config/admin_service_cmd_runner.go b/libcore/config/admin_service_cmd_runner.go new file mode 100644 index 0000000..761b94a --- /dev/null +++ b/libcore/config/admin_service_cmd_runner.go @@ -0,0 +1,49 @@ +//go:build !windows + +package config + +import ( + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" +) + +func ExecuteCmd(executablePath string, background bool, args ...string) (string, error) { + cwd := filepath.Dir(executablePath) + if appimage := os.Getenv("APPIMAGE"); appimage != "" { + executablePath = appimage + if !background { + return "Fail", fmt.Errorf("Appimage cannot have service") + } + } + + commands := [][]string{ + {"cocoasudo", "--prompt=Hiddify needs root for tunneling.", executablePath}, + {"gksu", executablePath}, + {"pkexec", executablePath}, + {"xterm", "-e", "sudo", executablePath, strings.Join(args, " ")}, + {"sudo", executablePath}, + } + + var err error + var cmd *exec.Cmd + for _, command := range commands { + cmd = exec.Command(command[0], command[1:]...) + cmd.Dir = cwd + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + fmt.Printf("Running command: %v\n", command) + if background { + err = cmd.Start() + } else { + err = cmd.Run() + } + if err == nil { + return "Ok", nil + } + } + + return "", fmt.Errorf("Error executing run as root shell command") +} diff --git a/libcore/config/admin_service_cmd_runner_windows.go b/libcore/config/admin_service_cmd_runner_windows.go new file mode 100644 index 0000000..d7047e0 --- /dev/null +++ b/libcore/config/admin_service_cmd_runner_windows.go @@ -0,0 +1,32 @@ +//go:build windows + +package config + +import ( + "os" + "strings" + "syscall" + + "golang.org/x/sys/windows" +) + +func ExecuteCmd(exe string, background bool, args ...string) (string, error) { + verb := "runas" + cwd, err := os.Getwd() // Error handling added + if err != nil { + return "", err + } + + verbPtr, _ := syscall.UTF16PtrFromString(verb) + exePtr, _ := syscall.UTF16PtrFromString(exe) + cwdPtr, _ := syscall.UTF16PtrFromString(cwd) + argPtr, _ := syscall.UTF16PtrFromString(strings.Join(args, " ")) + + var showCmd int32 = 0 // SW_NORMAL + + err = windows.ShellExecute(0, verbPtr, exePtr, argPtr, cwdPtr, showCmd) + if err != nil { + return "", err + } + return "", nil +} diff --git a/libcore/config/admin_service_commander.go b/libcore/config/admin_service_commander.go new file mode 100644 index 0000000..ef422a9 --- /dev/null +++ b/libcore/config/admin_service_commander.go @@ -0,0 +1,188 @@ +package config + +import ( + context "context" + "fmt" + "log" + "net" + "os" + "path/filepath" + "runtime" + "time" + + pb "github.com/hiddify/hiddify-core/hiddifyrpc" + "github.com/sagernet/sing-box/option" + dns "github.com/sagernet/sing-dns" + grpc "google.golang.org/grpc" +) + +const ( + serviceURL = "http://localhost:18020" + startEndpoint = "/start" + stopEndpoint = "/stop" +) + +var tunnelServiceRunning = false + +func isSupportedOS() bool { + return runtime.GOOS == "windows" || runtime.GOOS == "linux" +} + +func ActivateTunnelService(opt HiddifyOptions) (bool, error) { + tunnelServiceRunning = true + // if !isSupportedOS() { + // return false, E.New("Unsupported OS: " + runtime.GOOS) + // } + + go startTunnelRequestWithFailover(opt, true) + return true, nil +} + +func DeactivateTunnelServiceForce() (bool, error) { + return stopTunnelRequest() +} + +func DeactivateTunnelService() (bool, error) { + // if !isSupportedOS() { + // return true, nil + // } + + if tunnelServiceRunning { + res, err := stopTunnelRequest() + if err != nil { + tunnelServiceRunning = false + } + return res, err + } else { + go stopTunnelRequest() + } + + return true, nil +} + +func startTunnelRequestWithFailover(opt HiddifyOptions, installService bool) { + res, err := startTunnelRequest(opt, installService) + fmt.Printf("Start Tunnel Result: %v\n", res) + if err != nil { + fmt.Printf("Start Tunnel Failed! Stopping core... err=%v\n", err) + // StopAndAlert(pb.MessageType.MessageType_UNEXPECTED_ERROR, "Start Tunnel Failed! Stopping...") + } +} + +func isPortInUse(port string) bool { + listener, err := net.Listen("tcp", "127.0.0.1:"+port) + if err != nil { + return true // Port is in use + } + defer listener.Close() + return false // Port is available +} + +func startTunnelRequest(opt HiddifyOptions, installService bool) (bool, error) { + if !isPortInUse("18020") { + if installService { + return runTunnelService(opt) + } + return false, fmt.Errorf("service is not running") + } + conn, err := grpc.Dial("127.0.0.1:18020", grpc.WithInsecure()) + if err != nil { + log.Printf("did not connect: %v", err) + } + defer conn.Close() + c := pb.NewTunnelServiceClient(conn) + ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) + defer cancel() + _, _ = c.Stop(ctx, &pb.Empty{}) + res, err := c.Start(ctx, &pb.TunnelStartRequest{ + Ipv6: opt.IPv6Mode == option.DomainStrategy(dns.DomainStrategyUseIPv4), + ServerPort: int32(opt.InboundOptions.MixedPort), + StrictRoute: opt.InboundOptions.StrictRoute, + EndpointIndependentNat: true, + Stack: opt.InboundOptions.TUNStack, + }) + if err != nil { + log.Printf("could not greet: %+v %+v", res, err) + + if installService { + ExitTunnelService() + return runTunnelService(opt) + } + return false, err + } + + return true, nil +} + +func stopTunnelRequest() (bool, error) { + conn, err := grpc.Dial("127.0.0.1:18020", grpc.WithInsecure()) + if err != nil { + log.Printf("did not connect: %v", err) + return false, err + } + defer conn.Close() + c := pb.NewTunnelServiceClient(conn) + ctx, cancel := context.WithTimeout(context.Background(), time.Second*20) + defer cancel() + + res, err := c.Stop(ctx, &pb.Empty{}) + if err != nil { + log.Printf("did not Stopped: %v %v", res, err) + _, _ = c.Stop(ctx, &pb.Empty{}) + return false, err + } + + return true, nil +} + +func ExitTunnelService() (bool, error) { + conn, err := grpc.Dial("127.0.0.1:18020", grpc.WithInsecure()) + if err != nil { + log.Printf("did not connect: %v", err) + return false, err + } + defer conn.Close() + c := pb.NewTunnelServiceClient(conn) + ctx, cancel := context.WithTimeout(context.Background(), time.Second*1) + defer cancel() + + res, err := c.Exit(ctx, &pb.Empty{}) + if res != nil { + log.Printf("did not exit: %v %v", res, err) + return false, err + } + + return true, nil +} + +func runTunnelService(opt HiddifyOptions) (bool, error) { + executablePath := getTunnelServicePath() + fmt.Printf("Executable path is %s", executablePath) + out, err := ExecuteCmd(executablePath, false, "tunnel", "install") + fmt.Println("Shell command executed:", out, err) + if err != nil { + out, err = ExecuteCmd(executablePath, true, "tunnel", "run") + fmt.Println("Shell command executed without flag:", out, err) + } + if err == nil { + <-time.After(1 * time.Second) // wait until service loaded completely + } + return startTunnelRequest(opt, false) +} + +func getTunnelServicePath() string { + var fullPath string + exePath, _ := os.Executable() + binFolder := filepath.Dir(exePath) + switch runtime.GOOS { + case "windows": + fullPath = "HiddifyCli.exe" + case "darwin": + fallthrough + default: + fullPath = "HiddifyCli" + } + + abspath, _ := filepath.Abs(filepath.Join(binFolder, fullPath)) + return abspath +} diff --git a/libcore/config/config.go b/libcore/config/config.go new file mode 100644 index 0000000..89b513e --- /dev/null +++ b/libcore/config/config.go @@ -0,0 +1,869 @@ +package config + +import ( + "bytes" + "encoding/base64" + "encoding/json" + "fmt" + "math/rand" + "net" + "net/netip" + "net/url" + "runtime" + "strings" + "time" + + C "github.com/sagernet/sing-box/constant" + "github.com/sagernet/sing-box/option" + dns "github.com/sagernet/sing-dns" +) + +const ( + DNSRemoteTag = "dns-remote" + DNSLocalTag = "dns-local" + DNSDirectTag = "dns-direct" + DNSBlockTag = "dns-block" + DNSFakeTag = "dns-fake" + DNSTricksDirectTag = "dns-trick-direct" + + OutboundDirectTag = "direct" + OutboundBypassTag = "bypass" + OutboundBlockTag = "block" + OutboundSelectTag = "select" + OutboundURLTestTag = "auto" + OutboundDNSTag = "dns-out" + OutboundDirectFragmentTag = "direct-fragment" + + InboundTUNTag = "tun-in" + InboundMixedTag = "mixed-in" + InboundDNSTag = "dns-in" +) + +var OutboundMainProxyTag = OutboundSelectTag + +func BuildConfigJson(configOpt HiddifyOptions, input option.Options) (string, error) { + options, err := BuildConfig(configOpt, input) + if err != nil { + return "", err + } + var buffer bytes.Buffer + json.NewEncoder(&buffer) + encoder := json.NewEncoder(&buffer) + encoder.SetIndent("", " ") + err = encoder.Encode(options) + if err != nil { + return "", err + } + return buffer.String(), nil +} + +// TODO include selectors +func BuildConfig(opt HiddifyOptions, input option.Options) (*option.Options, error) { + fmt.Printf("config options: %++v\n", opt) + + var options option.Options + if opt.EnableFullConfig { + options.Inbounds = input.Inbounds + options.DNS = input.DNS + options.Route = input.Route + } + + setClashAPI(&options, &opt) + setLog(&options, &opt) + setInbound(&options, &opt) + setDns(&options, &opt) + setRoutingOptions(&options, &opt) + setFakeDns(&options, &opt) + err := setOutbounds(&options, &input, &opt) + if err != nil { + return nil, err + } + + return &options, nil +} + +func addForceDirect(options *option.Options, opt *HiddifyOptions, directDNSDomains map[string]bool) { + remoteDNSAddress := opt.RemoteDnsAddress + if strings.Contains(remoteDNSAddress, "://") { + remoteDNSAddress = strings.SplitAfter(remoteDNSAddress, "://")[1] + } + parsedUrl, err := url.Parse(fmt.Sprintf("https://%s", remoteDNSAddress)) + if err == nil && net.ParseIP(parsedUrl.Host) == nil { + directDNSDomains[parsedUrl.Host] = true + } + if len(directDNSDomains) > 0 { + // trickDnsDomains := []string{} + // directDNSDomains = removeDuplicateStr(directDNSDomains) + // b, _ := batch.New(context.Background(), batch.WithConcurrencyNum[bool](10)) + // for _, d := range directDNSDomains { + // b.Go(d, func() (bool, error) { + // return isBlockedDomain(d), nil + // }) + // } + // b.Wait() + // for domain, isBlock := range b.Result() { + // if isBlock.Value { + // trickDnsDomains = append(trickDnsDomains, domain) + // } + // } + + // trickDomains := strings.Join(trickDnsDomains, ",") + // trickRule := Rule{Domains: trickDomains, Outbound: OutboundBypassTag} + // trickDnsRule := trickRule.MakeDNSRule() + // trickDnsRule.Server = DNSTricksDirectTag + // options.DNS.Rules = append([]option.DNSRule{{Type: C.RuleTypeDefault, DefaultOptions: trickDnsRule}}, options.DNS.Rules...) + + directDNSDomainskeys := make([]string, 0, len(directDNSDomains)) + for key := range directDNSDomains { + directDNSDomainskeys = append(directDNSDomainskeys, key) + } + + domains := strings.Join(directDNSDomainskeys, ",") + directRule := Rule{Domains: domains, Outbound: OutboundBypassTag} + dnsRule := directRule.MakeDNSRule() + dnsRule.Server = DNSDirectTag + options.DNS.Rules = append([]option.DNSRule{{Type: C.RuleTypeDefault, DefaultOptions: dnsRule}}, options.DNS.Rules...) + } +} + +func setOutbounds(options *option.Options, input *option.Options, opt *HiddifyOptions) error { + directDNSDomains := make(map[string]bool) + var outbounds []option.Outbound + var tags []string + OutboundMainProxyTag = OutboundSelectTag + // inbound==warp over proxies + // outbound==proxies over warp + if opt.Warp.EnableWarp { + for _, out := range input.Outbounds { + if out.Type == C.TypeCustom { + if warp, ok := out.CustomOptions["warp"].(map[string]interface{}); ok { + key, _ := warp["key"].(string) + if key == "p1" { + opt.Warp.EnableWarp = false + break + } + } + } + if out.Type == C.TypeWireGuard && (out.WireGuardOptions.PrivateKey == opt.Warp.WireguardConfig.PrivateKey || out.WireGuardOptions.PrivateKey == "p1") { + opt.Warp.EnableWarp = false + break + } + } + } + if opt.Warp.EnableWarp && (opt.Warp.Mode == "warp_over_proxy" || opt.Warp.Mode == "proxy_over_warp") { + out, err := GenerateWarpSingbox(opt.Warp.WireguardConfig, opt.Warp.CleanIP, opt.Warp.CleanPort, opt.Warp.FakePackets, opt.Warp.FakePacketSize, opt.Warp.FakePacketDelay, opt.Warp.FakePacketMode) + if err != nil { + return fmt.Errorf("failed to generate warp config: %v", err) + } + out.Tag = "Hiddify Warp ✅" + if opt.Warp.Mode == "warp_over_proxy" { + out.WireGuardOptions.Detour = OutboundSelectTag + OutboundMainProxyTag = out.Tag + } else { + out.WireGuardOptions.Detour = OutboundDirectTag + } + patchWarp(out, opt, true, nil) + outbounds = append(outbounds, *out) + // tags = append(tags, out.Tag) + } + for _, out := range input.Outbounds { + outbound, serverDomain, err := patchOutbound(out, *opt, options.DNS.StaticIPs) + if err != nil { + return err + } + + if serverDomain != "" { + directDNSDomains[serverDomain] = true + } + out = *outbound + + switch out.Type { + case C.TypeDirect, C.TypeBlock, C.TypeDNS: + continue + case C.TypeSelector, C.TypeURLTest: + continue + case C.TypeCustom: + continue + default: + if !strings.Contains(out.Tag, "§hide§") { + tags = append(tags, out.Tag) + } + out = patchHiddifyWarpFromConfig(out, *opt) + outbounds = append(outbounds, out) + } + } + + urlTest := option.Outbound{ + Type: C.TypeURLTest, + Tag: OutboundURLTestTag, + URLTestOptions: option.URLTestOutboundOptions{ + Outbounds: tags, + URL: opt.ConnectionTestUrl, + Interval: option.Duration(opt.URLTestInterval.Duration()), + // IdleTimeout: option.Duration(opt.URLTestIdleTimeout.Duration()), + Tolerance: 1, + IdleTimeout: option.Duration(opt.URLTestInterval.Duration().Nanoseconds() * 3), + InterruptExistConnections: true, + }, + } + defaultSelect := urlTest.Tag + + for _, tag := range tags { + if strings.Contains(tag, "§default§") { + defaultSelect = "§default§" + } + } + selector := option.Outbound{ + Type: C.TypeSelector, + Tag: OutboundSelectTag, + SelectorOptions: option.SelectorOutboundOptions{ + Outbounds: append([]string{urlTest.Tag}, tags...), + Default: defaultSelect, + InterruptExistConnections: true, + }, + } + + outbounds = append([]option.Outbound{selector, urlTest}, outbounds...) + + options.Outbounds = append( + outbounds, + []option.Outbound{ + { + Tag: OutboundDNSTag, + Type: C.TypeDNS, + }, + { + Tag: OutboundDirectTag, + Type: C.TypeDirect, + }, + { + Tag: OutboundDirectFragmentTag, + Type: C.TypeDirect, + DirectOptions: option.DirectOutboundOptions{ + DialerOptions: option.DialerOptions{ + TCPFastOpen: false, + TLSFragment: option.TLSFragmentOptions{ + Enabled: true, + Size: opt.TLSTricks.FragmentSize, + Sleep: opt.TLSTricks.FragmentSleep, + }, + }, + }, + }, + { + Tag: OutboundBypassTag, + Type: C.TypeDirect, + }, + { + Tag: OutboundBlockTag, + Type: C.TypeBlock, + }, + }..., + ) + + addForceDirect(options, opt, directDNSDomains) + return nil +} + +func setClashAPI(options *option.Options, opt *HiddifyOptions) { + if opt.EnableClashApi { + if opt.ClashApiSecret == "" { + opt.ClashApiSecret = generateRandomString(16) + } + options.Experimental = &option.ExperimentalOptions{ + ClashAPI: &option.ClashAPIOptions{ + ExternalController: fmt.Sprintf("%s:%d", "127.0.0.1", opt.ClashApiPort), + Secret: opt.ClashApiSecret, + }, + + CacheFile: &option.CacheFileOptions{ + Enabled: true, + Path: "clash.db", + }, + } + } +} + +func setLog(options *option.Options, opt *HiddifyOptions) { + options.Log = &option.LogOptions{ + Level: opt.LogLevel, + Output: opt.LogFile, + Disabled: false, + Timestamp: true, + DisableColor: true, + } +} + +func setInbound(options *option.Options, opt *HiddifyOptions) { + var inboundDomainStrategy option.DomainStrategy + if !opt.ResolveDestination { + inboundDomainStrategy = option.DomainStrategy(dns.DomainStrategyAsIS) + } else { + inboundDomainStrategy = opt.IPv6Mode + } + if opt.EnableTunService { + ActivateTunnelService(*opt) + } else if opt.EnableTun { + tunInbound := option.Inbound{ + Type: C.TypeTun, + Tag: InboundTUNTag, + + TunOptions: option.TunInboundOptions{ + Stack: opt.TUNStack, + MTU: opt.MTU, + AutoRoute: true, + StrictRoute: opt.StrictRoute, + EndpointIndependentNat: true, + // GSO: runtime.GOOS != "windows", + InboundOptions: option.InboundOptions{ + SniffEnabled: true, + SniffOverrideDestination: false, + DomainStrategy: inboundDomainStrategy, + }, + }, + } + switch opt.IPv6Mode { + case option.DomainStrategy(dns.DomainStrategyUseIPv4): + tunInbound.TunOptions.Inet4Address = []netip.Prefix{ + netip.MustParsePrefix("172.19.0.1/28"), + } + case option.DomainStrategy(dns.DomainStrategyUseIPv6): + tunInbound.TunOptions.Inet6Address = []netip.Prefix{ + netip.MustParsePrefix("fdfe:dcba:9876::1/126"), + } + default: + tunInbound.TunOptions.Inet4Address = []netip.Prefix{ + netip.MustParsePrefix("172.19.0.1/28"), + } + tunInbound.TunOptions.Inet6Address = []netip.Prefix{ + netip.MustParsePrefix("fdfe:dcba:9876::1/126"), + } + } + options.Inbounds = append(options.Inbounds, tunInbound) + + } + + var bind string + if opt.AllowConnectionFromLAN { + bind = "0.0.0.0" + } else { + bind = "127.0.0.1" + } + + options.Inbounds = append( + options.Inbounds, + option.Inbound{ + Type: C.TypeMixed, + Tag: InboundMixedTag, + MixedOptions: option.HTTPMixedInboundOptions{ + ListenOptions: option.ListenOptions{ + Listen: option.NewListenAddress(netip.MustParseAddr(bind)), + ListenPort: opt.MixedPort, + InboundOptions: option.InboundOptions{ + SniffEnabled: true, + SniffOverrideDestination: true, + DomainStrategy: inboundDomainStrategy, + }, + }, + SetSystemProxy: opt.SetSystemProxy, + }, + }, + ) + + options.Inbounds = append( + options.Inbounds, + option.Inbound{ + Type: C.TypeDirect, + Tag: InboundDNSTag, + DirectOptions: option.DirectInboundOptions{ + ListenOptions: option.ListenOptions{ + Listen: option.NewListenAddress(netip.MustParseAddr(bind)), + ListenPort: opt.LocalDnsPort, + }, + // OverrideAddress: "1.1.1.1", + // OverridePort: 53, + }, + }, + ) +} + +func setDns(options *option.Options, opt *HiddifyOptions) { + options.DNS = &option.DNSOptions{ + StaticIPs: map[string][]string{}, + DNSClientOptions: option.DNSClientOptions{ + IndependentCache: opt.IndependentDNSCache, + }, + Final: DNSRemoteTag, + Servers: []option.DNSServerOptions{ + { + Tag: DNSRemoteTag, + Address: opt.RemoteDnsAddress, + AddressResolver: DNSDirectTag, + Strategy: opt.RemoteDnsDomainStrategy, + }, + { + Tag: DNSTricksDirectTag, + Address: "https://sky.rethinkdns.com/", + // AddressResolver: "dns-local", + Strategy: opt.DirectDnsDomainStrategy, + Detour: OutboundDirectFragmentTag, + }, + { + Tag: DNSDirectTag, + Address: opt.DirectDnsAddress, + AddressResolver: DNSLocalTag, + Strategy: opt.DirectDnsDomainStrategy, + Detour: OutboundDirectTag, + }, + { + Tag: DNSLocalTag, + Address: "local", + Detour: OutboundDirectTag, + }, + { + Tag: DNSBlockTag, + Address: "rcode://success", + }, + }, + } + sky_rethinkdns := getIPs([]string{"www.speedtest.net", "sky.rethinkdns.com"}) + if len(sky_rethinkdns) > 0 { + options.DNS.StaticIPs["sky.rethinkdns.com"] = sky_rethinkdns + } +} + +func setFakeDns(options *option.Options, opt *HiddifyOptions) { + if opt.EnableFakeDNS { + inet4Range := netip.MustParsePrefix("198.18.0.0/15") + inet6Range := netip.MustParsePrefix("fc00::/18") + options.DNS.FakeIP = &option.DNSFakeIPOptions{ + Enabled: true, + Inet4Range: &inet4Range, + Inet6Range: &inet6Range, + } + options.DNS.Servers = append( + options.DNS.Servers, + option.DNSServerOptions{ + Tag: DNSFakeTag, + Address: "fakeip", + Strategy: option.DomainStrategy(dns.DomainStrategyUseIPv4), + }, + ) + options.DNS.Rules = append( + options.DNS.Rules, + option.DNSRule{ + Type: C.RuleTypeDefault, + DefaultOptions: option.DefaultDNSRule{ + Inbound: []string{InboundTUNTag}, + Server: DNSFakeTag, + DisableCache: true, + }, + }, + ) + + } +} + +func setRoutingOptions(options *option.Options, opt *HiddifyOptions) { + dnsRules := []option.DefaultDNSRule{} + routeRules := []option.Rule{} + rulesets := []option.RuleSet{} + + if opt.EnableTun && runtime.GOOS == "android" { + routeRules = append( + routeRules, + option.Rule{ + Type: C.RuleTypeDefault, + + DefaultOptions: option.DefaultRule{ + Inbound: []string{InboundTUNTag}, + PackageName: []string{"app.brAccelerator.com"}, + Outbound: OutboundBypassTag, + }, + }, + ) + // routeRules = append( + // routeRules, + // option.Rule{ + // Type: C.RuleTypeDefault, + // DefaultOptions: option.DefaultRule{ + // ProcessName: []string{"Hiddify", "Hiddify.exe", "HiddifyCli", "HiddifyCli.exe"}, + // Outbound: OutboundBypassTag, + // }, + // }, + // ) + } + routeRules = append(routeRules, option.Rule{ + Type: C.RuleTypeDefault, + DefaultOptions: option.DefaultRule{ + Inbound: []string{InboundDNSTag}, + Outbound: OutboundDNSTag, + }, + }) + routeRules = append(routeRules, option.Rule{ + Type: C.RuleTypeDefault, + DefaultOptions: option.DefaultRule{ + Port: []uint16{53}, + Outbound: OutboundDNSTag, + }, + }) + + // { + // Type: C.RuleTypeDefault, + // DefaultOptions: option.DefaultRule{ + // ClashMode: "Direct", + // Outbound: OutboundDirectTag, + // }, + // }, + // { + // Type: C.RuleTypeDefault, + // DefaultOptions: option.DefaultRule{ + // ClashMode: "Global", + // Outbound: OutboundMainProxyTag, + // }, + // }, } + + if opt.BypassLAN { + routeRules = append( + routeRules, + option.Rule{ + Type: C.RuleTypeDefault, + DefaultOptions: option.DefaultRule{ + // GeoIP: []string{"private"}, + IPIsPrivate: true, + Outbound: OutboundBypassTag, + }, + }, + ) + } + + for _, rule := range opt.Rules { + routeRule := rule.MakeRule() + switch rule.Outbound { + case "bypass": + routeRule.Outbound = OutboundBypassTag + case "block": + routeRule.Outbound = OutboundBlockTag + case "proxy": + routeRule.Outbound = OutboundMainProxyTag + } + + if routeRule.IsValid() { + routeRules = append( + routeRules, + option.Rule{ + Type: C.RuleTypeDefault, + DefaultOptions: routeRule, + }, + ) + } + + dnsRule := rule.MakeDNSRule() + switch rule.Outbound { + case "bypass": + dnsRule.Server = DNSDirectTag + case "block": + dnsRule.Server = DNSBlockTag + dnsRule.DisableCache = true + case "proxy": + if opt.EnableFakeDNS { + fakeDnsRule := dnsRule + fakeDnsRule.Server = DNSFakeTag + fakeDnsRule.Inbound = []string{InboundTUNTag, InboundMixedTag} + dnsRules = append(dnsRules, fakeDnsRule) + } + dnsRule.Server = DNSRemoteTag + } + dnsRules = append(dnsRules, dnsRule) + } + + parsedURL, err := url.Parse(opt.ConnectionTestUrl) + if err == nil { + var dnsCPttl uint32 = 3000 + dnsRules = append(dnsRules, option.DefaultDNSRule{ + Domain: []string{parsedURL.Host}, + Server: DNSRemoteTag, + RewriteTTL: &dnsCPttl, + DisableCache: false, + }) + } + + if opt.BlockAds { + rulesets = append(rulesets, option.RuleSet{ + Type: C.RuleSetTypeRemote, + Tag: "geosite-ads", + Format: C.RuleSetFormatBinary, + RemoteOptions: option.RemoteRuleSet{ + URL: "https://raw.githubusercontent.com/hiddify/hiddify-geo/rule-set/block/geosite-category-ads-all.srs", + UpdateInterval: option.Duration(5 * time.Hour * 24), + }, + }) + rulesets = append(rulesets, option.RuleSet{ + Type: C.RuleSetTypeRemote, + Tag: "geosite-malware", + Format: C.RuleSetFormatBinary, + RemoteOptions: option.RemoteRuleSet{ + URL: "https://raw.githubusercontent.com/hiddify/hiddify-geo/rule-set/block/geosite-malware.srs", + UpdateInterval: option.Duration(5 * time.Hour * 24), + }, + }) + rulesets = append(rulesets, option.RuleSet{ + Type: C.RuleSetTypeRemote, + Tag: "geosite-phishing", + Format: C.RuleSetFormatBinary, + RemoteOptions: option.RemoteRuleSet{ + URL: "https://raw.githubusercontent.com/hiddify/hiddify-geo/rule-set/block/geosite-phishing.srs", + UpdateInterval: option.Duration(5 * time.Hour * 24), + }, + }) + rulesets = append(rulesets, option.RuleSet{ + Type: C.RuleSetTypeRemote, + Tag: "geosite-cryptominers", + Format: C.RuleSetFormatBinary, + RemoteOptions: option.RemoteRuleSet{ + URL: "https://raw.githubusercontent.com/hiddify/hiddify-geo/rule-set/block/geosite-cryptominers.srs", + UpdateInterval: option.Duration(5 * time.Hour * 24), + }, + }) + rulesets = append(rulesets, option.RuleSet{ + Type: C.RuleSetTypeRemote, + Tag: "geoip-phishing", + Format: C.RuleSetFormatBinary, + RemoteOptions: option.RemoteRuleSet{ + URL: "https://raw.githubusercontent.com/hiddify/hiddify-geo/rule-set/block/geoip-phishing.srs", + UpdateInterval: option.Duration(5 * time.Hour * 24), + }, + }) + rulesets = append(rulesets, option.RuleSet{ + Type: C.RuleSetTypeRemote, + Tag: "geoip-malware", + Format: C.RuleSetFormatBinary, + RemoteOptions: option.RemoteRuleSet{ + URL: "https://raw.githubusercontent.com/hiddify/hiddify-geo/rule-set/block/geoip-malware.srs", + UpdateInterval: option.Duration(5 * time.Hour * 24), + }, + }) + + routeRules = append(routeRules, option.Rule{ + Type: C.RuleTypeDefault, + DefaultOptions: option.DefaultRule{ + RuleSet: []string{ + "geosite-ads", + "geosite-malware", + "geosite-phishing", + "geosite-cryptominers", + "geoip-malware", + "geoip-phishing", + }, + Outbound: OutboundBlockTag, + }, + }) + dnsRules = append(dnsRules, option.DefaultDNSRule{ + RuleSet: []string{ + "geosite-ads", + "geosite-malware", + "geosite-phishing", + "geosite-cryptominers", + "geoip-malware", + "geoip-phishing", + }, + Server: DNSBlockTag, + // DisableCache: true, + }) + + } + if opt.Region != "other" { + dnsRules = append(dnsRules, option.DefaultDNSRule{ + DomainSuffix: []string{"." + opt.Region}, + Server: DNSDirectTag, + }) + routeRules = append(routeRules, option.Rule{ + Type: C.RuleTypeDefault, + DefaultOptions: option.DefaultRule{ + DomainSuffix: []string{"." + opt.Region}, + Outbound: OutboundDirectTag, + }, + }) + dnsRules = append(dnsRules, option.DefaultDNSRule{ + RuleSet: []string{ + "geoip-" + opt.Region, + "geosite-" + opt.Region, + }, + Server: DNSDirectTag, + }) + + rulesets = append(rulesets, option.RuleSet{ + Type: C.RuleSetTypeRemote, + Tag: "geoip-" + opt.Region, + Format: C.RuleSetFormatBinary, + RemoteOptions: option.RemoteRuleSet{ + URL: "https://raw.githubusercontent.com/hiddify/hiddify-geo/rule-set/country/geoip-" + opt.Region + ".srs", + UpdateInterval: option.Duration(5 * time.Hour * 24), + }, + }) + rulesets = append(rulesets, option.RuleSet{ + Type: C.RuleSetTypeRemote, + Tag: "geosite-" + opt.Region, + Format: C.RuleSetFormatBinary, + RemoteOptions: option.RemoteRuleSet{ + URL: "https://raw.githubusercontent.com/hiddify/hiddify-geo/rule-set/country/geosite-" + opt.Region + ".srs", + UpdateInterval: option.Duration(5 * time.Hour * 24), + }, + }) + + routeRules = append(routeRules, option.Rule{ + Type: C.RuleTypeDefault, + DefaultOptions: option.DefaultRule{ + RuleSet: []string{ + "geoip-" + opt.Region, + "geosite-" + opt.Region, + }, + Outbound: OutboundDirectTag, + }, + }) + + } + options.Route = &option.RouteOptions{ + Rules: routeRules, + Final: OutboundMainProxyTag, + AutoDetectInterface: true, + OverrideAndroidVPN: true, + RuleSet: rulesets, + // GeoIP: &option.GeoIPOptions{ + // Path: opt.GeoIPPath, + // }, + // Geosite: &option.GeositeOptions{ + // Path: opt.GeoSitePath, + // }, + } + if opt.EnableDNSRouting { + for _, dnsRule := range dnsRules { + if dnsRule.IsValid() { + options.DNS.Rules = append( + options.DNS.Rules, + option.DNSRule{ + Type: C.RuleTypeDefault, + DefaultOptions: dnsRule, + }, + ) + } + } + } +} + +func patchHiddifyWarpFromConfig(out option.Outbound, opt HiddifyOptions) option.Outbound { + if opt.Warp.EnableWarp && opt.Warp.Mode == "proxy_over_warp" { + if out.DirectOptions.Detour == "" { + out.DirectOptions.Detour = "Hiddify Warp ✅" + } + if out.HTTPOptions.Detour == "" { + out.HTTPOptions.Detour = "Hiddify Warp ✅" + } + if out.Hysteria2Options.Detour == "" { + out.Hysteria2Options.Detour = "Hiddify Warp ✅" + } + if out.HysteriaOptions.Detour == "" { + out.HysteriaOptions.Detour = "Hiddify Warp ✅" + } + if out.SSHOptions.Detour == "" { + out.SSHOptions.Detour = "Hiddify Warp ✅" + } + if out.ShadowTLSOptions.Detour == "" { + out.ShadowTLSOptions.Detour = "Hiddify Warp ✅" + } + if out.ShadowsocksOptions.Detour == "" { + out.ShadowsocksOptions.Detour = "Hiddify Warp ✅" + } + if out.ShadowsocksROptions.Detour == "" { + out.ShadowsocksROptions.Detour = "Hiddify Warp ✅" + } + if out.SocksOptions.Detour == "" { + out.SocksOptions.Detour = "Hiddify Warp ✅" + } + if out.TUICOptions.Detour == "" { + out.TUICOptions.Detour = "Hiddify Warp ✅" + } + if out.TorOptions.Detour == "" { + out.TorOptions.Detour = "Hiddify Warp ✅" + } + if out.TrojanOptions.Detour == "" { + out.TrojanOptions.Detour = "Hiddify Warp ✅" + } + if out.VLESSOptions.Detour == "" { + out.VLESSOptions.Detour = "Hiddify Warp ✅" + } + if out.VMessOptions.Detour == "" { + out.VMessOptions.Detour = "Hiddify Warp ✅" + } + if out.WireGuardOptions.Detour == "" { + out.WireGuardOptions.Detour = "Hiddify Warp ✅" + } + } + return out +} + +func getIPs(domains []string) []string { + res := []string{} + for _, d := range domains { + ips, err := net.LookupHost(d) + if err != nil { + continue + } + for _, ip := range ips { + if !strings.HasPrefix(ip, "10.") { + res = append(res, ip) + } + } + } + return res +} + +func isBlockedDomain(domain string) bool { + if strings.HasPrefix("full:", domain) { + return false + } + ips, err := net.LookupHost(domain) + if err != nil { + // fmt.Println(err) + return true + } + + // Print the IP addresses associated with the domain + fmt.Printf("IP addresses for %s:\n", domain) + for _, ip := range ips { + if strings.HasPrefix(ip, "10.") { + return true + } + } + return false +} + +func removeDuplicateStr(strSlice []string) []string { + allKeys := make(map[string]bool) + list := []string{} + for _, item := range strSlice { + if _, value := allKeys[item]; !value { + allKeys[item] = true + list = append(list, item) + } + } + return list +} + +func generateRandomString(length int) string { + // Determine the number of bytes needed + bytesNeeded := (length*6 + 7) / 8 + + // Generate random bytes + randomBytes := make([]byte, bytesNeeded) + _, err := rand.Read(randomBytes) + if err != nil { + return "hiddify" + } + + // Encode random bytes to base64 + randomString := base64.URLEncoding.EncodeToString(randomBytes) + + // Trim padding characters and return the string + return randomString[:length] +} diff --git a/libcore/config/config.json.template b/libcore/config/config.json.template new file mode 100644 index 0000000..06c91ad --- /dev/null +++ b/libcore/config/config.json.template @@ -0,0 +1,8 @@ +{ + "log": {}, + "dns": {}, + "inbounds": [], + "outbounds": [], + "route": {}, + "experimental": {} +} \ No newline at end of file diff --git a/libcore/config/constant.go b/libcore/config/constant.go new file mode 100644 index 0000000..b781d61 --- /dev/null +++ b/libcore/config/constant.go @@ -0,0 +1,6 @@ +package config + +const ( + WarpOverProxy = "warp_over_proxy" + ProxyOverWarp = "proxy_over_warp" +) diff --git a/libcore/config/core.pb.go b/libcore/config/core.pb.go new file mode 100644 index 0000000..ea37d77 --- /dev/null +++ b/libcore/config/core.pb.go @@ -0,0 +1,389 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.33.0 +// protoc v4.25.3 +// source: core.proto + +package config + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +type ParseConfigRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + TempPath string `protobuf:"bytes,1,opt,name=tempPath,proto3" json:"tempPath,omitempty"` + Path string `protobuf:"bytes,2,opt,name=path,proto3" json:"path,omitempty"` + Debug bool `protobuf:"varint,3,opt,name=debug,proto3" json:"debug,omitempty"` +} + +func (x *ParseConfigRequest) Reset() { + *x = ParseConfigRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_core_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ParseConfigRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ParseConfigRequest) ProtoMessage() {} + +func (x *ParseConfigRequest) ProtoReflect() protoreflect.Message { + mi := &file_core_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ParseConfigRequest.ProtoReflect.Descriptor instead. +func (*ParseConfigRequest) Descriptor() ([]byte, []int) { + return file_core_proto_rawDescGZIP(), []int{0} +} + +func (x *ParseConfigRequest) GetTempPath() string { + if x != nil { + return x.TempPath + } + return "" +} + +func (x *ParseConfigRequest) GetPath() string { + if x != nil { + return x.Path + } + return "" +} + +func (x *ParseConfigRequest) GetDebug() bool { + if x != nil { + return x.Debug + } + return false +} + +type ParseConfigResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Error *string `protobuf:"bytes,1,opt,name=error,proto3,oneof" json:"error,omitempty"` +} + +func (x *ParseConfigResponse) Reset() { + *x = ParseConfigResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_core_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ParseConfigResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ParseConfigResponse) ProtoMessage() {} + +func (x *ParseConfigResponse) ProtoReflect() protoreflect.Message { + mi := &file_core_proto_msgTypes[1] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ParseConfigResponse.ProtoReflect.Descriptor instead. +func (*ParseConfigResponse) Descriptor() ([]byte, []int) { + return file_core_proto_rawDescGZIP(), []int{1} +} + +func (x *ParseConfigResponse) GetError() string { + if x != nil && x.Error != nil { + return *x.Error + } + return "" +} + +type GenerateConfigRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Path string `protobuf:"bytes,1,opt,name=path,proto3" json:"path,omitempty"` + Debug bool `protobuf:"varint,2,opt,name=debug,proto3" json:"debug,omitempty"` +} + +func (x *GenerateConfigRequest) Reset() { + *x = GenerateConfigRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_core_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *GenerateConfigRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GenerateConfigRequest) ProtoMessage() {} + +func (x *GenerateConfigRequest) ProtoReflect() protoreflect.Message { + mi := &file_core_proto_msgTypes[2] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GenerateConfigRequest.ProtoReflect.Descriptor instead. +func (*GenerateConfigRequest) Descriptor() ([]byte, []int) { + return file_core_proto_rawDescGZIP(), []int{2} +} + +func (x *GenerateConfigRequest) GetPath() string { + if x != nil { + return x.Path + } + return "" +} + +func (x *GenerateConfigRequest) GetDebug() bool { + if x != nil { + return x.Debug + } + return false +} + +type GenerateConfigResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Config string `protobuf:"bytes,1,opt,name=config,proto3" json:"config,omitempty"` + Error *string `protobuf:"bytes,2,opt,name=error,proto3,oneof" json:"error,omitempty"` +} + +func (x *GenerateConfigResponse) Reset() { + *x = GenerateConfigResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_core_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *GenerateConfigResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GenerateConfigResponse) ProtoMessage() {} + +func (x *GenerateConfigResponse) ProtoReflect() protoreflect.Message { + mi := &file_core_proto_msgTypes[3] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GenerateConfigResponse.ProtoReflect.Descriptor instead. +func (*GenerateConfigResponse) Descriptor() ([]byte, []int) { + return file_core_proto_rawDescGZIP(), []int{3} +} + +func (x *GenerateConfigResponse) GetConfig() string { + if x != nil { + return x.Config + } + return "" +} + +func (x *GenerateConfigResponse) GetError() string { + if x != nil && x.Error != nil { + return *x.Error + } + return "" +} + +var File_core_proto protoreflect.FileDescriptor + +var file_core_proto_rawDesc = []byte{ + 0x0a, 0x0a, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0d, 0x43, 0x6f, + 0x6e, 0x66, 0x69, 0x67, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x22, 0x5a, 0x0a, 0x12, 0x50, + 0x61, 0x72, 0x73, 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, + 0x74, 0x12, 0x1a, 0x0a, 0x08, 0x74, 0x65, 0x6d, 0x70, 0x50, 0x61, 0x74, 0x68, 0x18, 0x01, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x08, 0x74, 0x65, 0x6d, 0x70, 0x50, 0x61, 0x74, 0x68, 0x12, 0x12, 0x0a, + 0x04, 0x70, 0x61, 0x74, 0x68, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x70, 0x61, 0x74, + 0x68, 0x12, 0x14, 0x0a, 0x05, 0x64, 0x65, 0x62, 0x75, 0x67, 0x18, 0x03, 0x20, 0x01, 0x28, 0x08, + 0x52, 0x05, 0x64, 0x65, 0x62, 0x75, 0x67, 0x22, 0x3a, 0x0a, 0x13, 0x50, 0x61, 0x72, 0x73, 0x65, + 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x19, + 0x0a, 0x05, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x48, 0x00, 0x52, + 0x05, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x88, 0x01, 0x01, 0x42, 0x08, 0x0a, 0x06, 0x5f, 0x65, 0x72, + 0x72, 0x6f, 0x72, 0x22, 0x41, 0x0a, 0x15, 0x47, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74, 0x65, 0x43, + 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x12, 0x0a, 0x04, + 0x70, 0x61, 0x74, 0x68, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x70, 0x61, 0x74, 0x68, + 0x12, 0x14, 0x0a, 0x05, 0x64, 0x65, 0x62, 0x75, 0x67, 0x18, 0x02, 0x20, 0x01, 0x28, 0x08, 0x52, + 0x05, 0x64, 0x65, 0x62, 0x75, 0x67, 0x22, 0x55, 0x0a, 0x16, 0x47, 0x65, 0x6e, 0x65, 0x72, 0x61, + 0x74, 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, + 0x12, 0x16, 0x0a, 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, + 0x52, 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x19, 0x0a, 0x05, 0x65, 0x72, 0x72, 0x6f, + 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x48, 0x00, 0x52, 0x05, 0x65, 0x72, 0x72, 0x6f, 0x72, + 0x88, 0x01, 0x01, 0x42, 0x08, 0x0a, 0x06, 0x5f, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x32, 0xc6, 0x01, + 0x0a, 0x0b, 0x43, 0x6f, 0x72, 0x65, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x54, 0x0a, + 0x0b, 0x50, 0x61, 0x72, 0x73, 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x21, 0x2e, 0x43, + 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x50, 0x61, 0x72, + 0x73, 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, + 0x22, 0x2e, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, + 0x50, 0x61, 0x72, 0x73, 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x65, 0x73, 0x70, 0x6f, + 0x6e, 0x73, 0x65, 0x12, 0x61, 0x0a, 0x12, 0x47, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74, 0x65, 0x46, + 0x75, 0x6c, 0x6c, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x24, 0x2e, 0x43, 0x6f, 0x6e, 0x66, + 0x69, 0x67, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x47, 0x65, 0x6e, 0x65, 0x72, 0x61, + 0x74, 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, + 0x25, 0x2e, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, + 0x47, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74, 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x65, + 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x42, 0x0b, 0x5a, 0x09, 0x2e, 0x2e, 0x2f, 0x63, 0x6f, 0x6e, + 0x66, 0x69, 0x67, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_core_proto_rawDescOnce sync.Once + file_core_proto_rawDescData = file_core_proto_rawDesc +) + +func file_core_proto_rawDescGZIP() []byte { + file_core_proto_rawDescOnce.Do(func() { + file_core_proto_rawDescData = protoimpl.X.CompressGZIP(file_core_proto_rawDescData) + }) + return file_core_proto_rawDescData +} + +var file_core_proto_msgTypes = make([]protoimpl.MessageInfo, 4) +var file_core_proto_goTypes = []interface{}{ + (*ParseConfigRequest)(nil), // 0: HiddifyOptions.ParseConfigRequest + (*ParseConfigResponse)(nil), // 1: HiddifyOptions.ParseConfigResponse + (*GenerateConfigRequest)(nil), // 2: HiddifyOptions.GenerateConfigRequest + (*GenerateConfigResponse)(nil), // 3: HiddifyOptions.GenerateConfigResponse +} +var file_core_proto_depIdxs = []int32{ + 0, // 0: HiddifyOptions.CoreService.ParseConfig:input_type -> HiddifyOptions.ParseConfigRequest + 2, // 1: HiddifyOptions.CoreService.GenerateFullConfig:input_type -> HiddifyOptions.GenerateConfigRequest + 1, // 2: HiddifyOptions.CoreService.ParseConfig:output_type -> HiddifyOptions.ParseConfigResponse + 3, // 3: HiddifyOptions.CoreService.GenerateFullConfig:output_type -> HiddifyOptions.GenerateConfigResponse + 2, // [2:4] is the sub-list for method output_type + 0, // [0:2] is the sub-list for method input_type + 0, // [0:0] is the sub-list for extension type_name + 0, // [0:0] is the sub-list for extension extendee + 0, // [0:0] is the sub-list for field type_name +} + +func init() { file_core_proto_init() } +func file_core_proto_init() { + if File_core_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_core_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ParseConfigRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_core_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ParseConfigResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_core_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*GenerateConfigRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_core_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*GenerateConfigResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + file_core_proto_msgTypes[1].OneofWrappers = []interface{}{} + file_core_proto_msgTypes[3].OneofWrappers = []interface{}{} + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_core_proto_rawDesc, + NumEnums: 0, + NumMessages: 4, + NumExtensions: 0, + NumServices: 1, + }, + GoTypes: file_core_proto_goTypes, + DependencyIndexes: file_core_proto_depIdxs, + MessageInfos: file_core_proto_msgTypes, + }.Build() + File_core_proto = out.File + file_core_proto_rawDesc = nil + file_core_proto_goTypes = nil + file_core_proto_depIdxs = nil +} diff --git a/libcore/config/core_grpc.pb.go b/libcore/config/core_grpc.pb.go new file mode 100644 index 0000000..17efffd --- /dev/null +++ b/libcore/config/core_grpc.pb.go @@ -0,0 +1,146 @@ +// Code generated by protoc-gen-go-grpc. DO NOT EDIT. +// versions: +// - protoc-gen-go-grpc v1.3.0 +// - protoc v4.25.3 +// source: core.proto + +package config + +import ( + context "context" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" +) + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +// Requires gRPC-Go v1.32.0 or later. +const _ = grpc.SupportPackageIsVersion7 + +const ( + CoreService_ParseConfig_FullMethodName = "/HiddifyOptions.CoreService/ParseConfig" + CoreService_GenerateFullConfig_FullMethodName = "/HiddifyOptions.CoreService/GenerateFullConfig" +) + +// CoreServiceClient is the client API for CoreService service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +type CoreServiceClient interface { + ParseConfig(ctx context.Context, in *ParseConfigRequest, opts ...grpc.CallOption) (*ParseConfigResponse, error) + GenerateFullConfig(ctx context.Context, in *GenerateConfigRequest, opts ...grpc.CallOption) (*GenerateConfigResponse, error) +} + +type coreServiceClient struct { + cc grpc.ClientConnInterface +} + +func NewCoreServiceClient(cc grpc.ClientConnInterface) CoreServiceClient { + return &coreServiceClient{cc} +} + +func (c *coreServiceClient) ParseConfig(ctx context.Context, in *ParseConfigRequest, opts ...grpc.CallOption) (*ParseConfigResponse, error) { + out := new(ParseConfigResponse) + err := c.cc.Invoke(ctx, CoreService_ParseConfig_FullMethodName, in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *coreServiceClient) GenerateFullConfig(ctx context.Context, in *GenerateConfigRequest, opts ...grpc.CallOption) (*GenerateConfigResponse, error) { + out := new(GenerateConfigResponse) + err := c.cc.Invoke(ctx, CoreService_GenerateFullConfig_FullMethodName, in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// CoreServiceServer is the server API for CoreService service. +// All implementations must embed UnimplementedCoreServiceServer +// for forward compatibility +type CoreServiceServer interface { + ParseConfig(context.Context, *ParseConfigRequest) (*ParseConfigResponse, error) + GenerateFullConfig(context.Context, *GenerateConfigRequest) (*GenerateConfigResponse, error) + mustEmbedUnimplementedCoreServiceServer() +} + +// UnimplementedCoreServiceServer must be embedded to have forward compatible implementations. +type UnimplementedCoreServiceServer struct { +} + +func (UnimplementedCoreServiceServer) ParseConfig(context.Context, *ParseConfigRequest) (*ParseConfigResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method ParseConfig not implemented") +} +func (UnimplementedCoreServiceServer) GenerateFullConfig(context.Context, *GenerateConfigRequest) (*GenerateConfigResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method GenerateFullConfig not implemented") +} +func (UnimplementedCoreServiceServer) mustEmbedUnimplementedCoreServiceServer() {} + +// UnsafeCoreServiceServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to CoreServiceServer will +// result in compilation errors. +type UnsafeCoreServiceServer interface { + mustEmbedUnimplementedCoreServiceServer() +} + +func RegisterCoreServiceServer(s grpc.ServiceRegistrar, srv CoreServiceServer) { + s.RegisterService(&CoreService_ServiceDesc, srv) +} + +func _CoreService_ParseConfig_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(ParseConfigRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(CoreServiceServer).ParseConfig(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: CoreService_ParseConfig_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(CoreServiceServer).ParseConfig(ctx, req.(*ParseConfigRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _CoreService_GenerateFullConfig_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GenerateConfigRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(CoreServiceServer).GenerateFullConfig(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: CoreService_GenerateFullConfig_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(CoreServiceServer).GenerateFullConfig(ctx, req.(*GenerateConfigRequest)) + } + return interceptor(ctx, in, info, handler) +} + +// CoreService_ServiceDesc is the grpc.ServiceDesc for CoreService service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var CoreService_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "HiddifyOptions.CoreService", + HandlerType: (*CoreServiceServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "ParseConfig", + Handler: _CoreService_ParseConfig_Handler, + }, + { + MethodName: "GenerateFullConfig", + Handler: _CoreService_GenerateFullConfig_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "core.proto", +} diff --git a/libcore/config/debug.go b/libcore/config/debug.go new file mode 100644 index 0000000..fab5a9e --- /dev/null +++ b/libcore/config/debug.go @@ -0,0 +1,45 @@ +package config + +import ( + "bytes" + "encoding/json" + "fmt" + "os" + "path/filepath" + "runtime/debug" + + "github.com/sagernet/sing-box/option" +) + +func SaveCurrentConfig(path string, options option.Options) error { + json, err := ToJson(options) + if err != nil { + return err + } + p, err := filepath.Abs(path) + fmt.Printf("Saving config to %v %+v\n", p, err) + if err != nil { + return err + } + return os.WriteFile(p, []byte(json), 0644) +} + +func ToJson(options option.Options) (string, error) { + var buffer bytes.Buffer + encoder := json.NewEncoder(&buffer) + encoder.SetIndent("", " ") + // fmt.Printf("%+v\n", options) + err := encoder.Encode(options) + if err != nil { + fmt.Printf("ERROR in coding:%+v\n", err) + return "", err + } + return buffer.String(), nil +} + +func DeferPanicToError(name string, err func(error)) { + if r := recover(); r != nil { + s := fmt.Errorf("%s panic: %s\n%s", name, r, string(debug.Stack())) + err(s) + } +} diff --git a/libcore/config/hiddify_option.go b/libcore/config/hiddify_option.go new file mode 100644 index 0000000..5b13242 --- /dev/null +++ b/libcore/config/hiddify_option.go @@ -0,0 +1,155 @@ +package config + +import ( + "github.com/sagernet/sing-box/option" + dns "github.com/sagernet/sing-dns" +) + +type HiddifyOptions struct { + EnableFullConfig bool `json:"enable-full-config"` + LogLevel string `json:"log-level"` + LogFile string `json:"log-file"` + EnableClashApi bool `json:"enable-clash-api"` + ClashApiPort uint16 `json:"clash-api-port"` + ClashApiSecret string `json:"web-secret"` + Region string `json:"region"` + BlockAds bool `json:"block-ads"` + UseXrayCoreWhenPossible bool `json:"use-xray-core-when-possible"` + // GeoIPPath string `json:"geoip-path"` + // GeoSitePath string `json:"geosite-path"` + Rules []Rule `json:"rules"` + Warp WarpOptions `json:"warp"` + Warp2 WarpOptions `json:"warp2"` + Mux MuxOptions `json:"mux"` + TLSTricks TLSTricks `json:"tls-tricks"` + DNSOptions + InboundOptions + URLTestOptions + RouteOptions +} + +type DNSOptions struct { + RemoteDnsAddress string `json:"remote-dns-address"` + RemoteDnsDomainStrategy option.DomainStrategy `json:"remote-dns-domain-strategy"` + DirectDnsAddress string `json:"direct-dns-address"` + DirectDnsDomainStrategy option.DomainStrategy `json:"direct-dns-domain-strategy"` + IndependentDNSCache bool `json:"independent-dns-cache"` + EnableFakeDNS bool `json:"enable-fake-dns"` + EnableDNSRouting bool `json:"enable-dns-routing"` +} + +type InboundOptions struct { + EnableTun bool `json:"enable-tun"` + EnableTunService bool `json:"enable-tun-service"` + SetSystemProxy bool `json:"set-system-proxy"` + MixedPort uint16 `json:"mixed-port"` + TProxyPort uint16 `json:"tproxy-port"` + LocalDnsPort uint16 `json:"local-dns-port"` + MTU uint32 `json:"mtu"` + StrictRoute bool `json:"strict-route"` + TUNStack string `json:"tun-implementation"` +} + +type URLTestOptions struct { + ConnectionTestUrl string `json:"connection-test-url"` + URLTestInterval DurationInSeconds `json:"url-test-interval"` + // URLTestIdleTimeout DurationInSeconds `json:"url-test-idle-timeout"` +} + +type RouteOptions struct { + ResolveDestination bool `json:"resolve-destination"` + IPv6Mode option.DomainStrategy `json:"ipv6-mode"` + BypassLAN bool `json:"bypass-lan"` + AllowConnectionFromLAN bool `json:"allow-connection-from-lan"` +} + +type TLSTricks struct { + EnableFragment bool `json:"enable-fragment"` + FragmentSize string `json:"fragment-size"` + FragmentSleep string `json:"fragment-sleep"` + MixedSNICase bool `json:"mixed-sni-case"` + EnablePadding bool `json:"enable-padding"` + PaddingSize string `json:"padding-size"` +} + +type MuxOptions struct { + Enable bool `json:"enable"` + Padding bool `json:"padding"` + MaxStreams int `json:"max-streams"` + Protocol string `json:"protocol"` +} + +type WarpOptions struct { + Id string `json:"id"` + EnableWarp bool `json:"enable"` + Mode string `json:"mode"` + WireguardConfigStr string `json:"wireguard-config"` + WireguardConfig WarpWireguardConfig `json:"wireguardConfig"` // TODO check + FakePackets string `json:"noise"` + FakePacketSize string `json:"noise-size"` + FakePacketDelay string `json:"noise-delay"` + FakePacketMode string `json:"noise-mode"` + CleanIP string `json:"clean-ip"` + CleanPort uint16 `json:"clean-port"` + Account WarpAccount +} + +func DefaultHiddifyOptions() *HiddifyOptions { + return &HiddifyOptions{ + DNSOptions: DNSOptions{ + RemoteDnsAddress: "1.1.1.1", + RemoteDnsDomainStrategy: option.DomainStrategy(dns.DomainStrategyAsIS), + DirectDnsAddress: "1.1.1.1", + DirectDnsDomainStrategy: option.DomainStrategy(dns.DomainStrategyAsIS), + IndependentDNSCache: false, + EnableFakeDNS: false, + EnableDNSRouting: false, + }, + InboundOptions: InboundOptions{ + EnableTun: false, + SetSystemProxy: false, + MixedPort: 12334, + TProxyPort: 12335, + LocalDnsPort: 16450, + MTU: 9000, + StrictRoute: true, + TUNStack: "mixed", + }, + URLTestOptions: URLTestOptions{ + ConnectionTestUrl: "http://cp.cloudflare.com/", + URLTestInterval: DurationInSeconds(600), + // URLTestIdleTimeout: DurationInSeconds(6000), + }, + RouteOptions: RouteOptions{ + ResolveDestination: false, + IPv6Mode: option.DomainStrategy(dns.DomainStrategyAsIS), + BypassLAN: false, + AllowConnectionFromLAN: false, + }, + LogLevel: "warn", + // LogFile: "/dev/null", + LogFile: "box.log", + Region: "other", + EnableClashApi: true, + ClashApiPort: 16756, + ClashApiSecret: "", + // GeoIPPath: "geoip.db", + // GeoSitePath: "geosite.db", + Rules: []Rule{}, + Mux: MuxOptions{ + Enable: false, + Padding: true, + MaxStreams: 8, + Protocol: "h2mux", + }, + TLSTricks: TLSTricks{ + EnableFragment: false, + FragmentSize: "10-100", + FragmentSleep: "50-200", + MixedSNICase: false, + EnablePadding: false, + PaddingSize: "1200-1500", + }, + UseXrayCoreWhenPossible: false, + } +} diff --git a/libcore/config/outbound.go b/libcore/config/outbound.go new file mode 100644 index 0000000..73e0886 --- /dev/null +++ b/libcore/config/outbound.go @@ -0,0 +1,185 @@ +package config + +import ( + "encoding/json" + "fmt" + "net" + + C "github.com/sagernet/sing-box/constant" + "github.com/sagernet/sing-box/option" +) + +type outboundMap map[string]interface{} + +func patchOutboundMux(base option.Outbound, configOpt HiddifyOptions, obj outboundMap) outboundMap { + if configOpt.Mux.Enable { + multiplex := option.OutboundMultiplexOptions{ + Enabled: true, + Padding: configOpt.Mux.Padding, + MaxStreams: configOpt.Mux.MaxStreams, + Protocol: configOpt.Mux.Protocol, + } + obj["multiplex"] = multiplex + // } else { + // delete(obj, "multiplex") + } + return obj +} + +func patchOutboundTLSTricks(base option.Outbound, configOpt HiddifyOptions, obj outboundMap) outboundMap { + if base.Type == C.TypeSelector || base.Type == C.TypeURLTest || base.Type == C.TypeBlock || base.Type == C.TypeDNS { + return obj + } + if isOutboundReality(base) { + return obj + } + + var tls *option.OutboundTLSOptions + var transport *option.V2RayTransportOptions + if base.VLESSOptions.OutboundTLSOptionsContainer.TLS != nil { + tls = base.VLESSOptions.OutboundTLSOptionsContainer.TLS + transport = base.VLESSOptions.Transport + } else if base.TrojanOptions.OutboundTLSOptionsContainer.TLS != nil { + tls = base.TrojanOptions.OutboundTLSOptionsContainer.TLS + transport = base.TrojanOptions.Transport + } else if base.VMessOptions.OutboundTLSOptionsContainer.TLS != nil { + tls = base.VMessOptions.OutboundTLSOptionsContainer.TLS + transport = base.VMessOptions.Transport + } + if base.Type == C.TypeXray { + if configOpt.TLSTricks.EnableFragment { + if obj["xray_fragment"] == nil || obj["xray_fragment"].(map[string]any)["packets"] == "" { + obj["xray_fragment"] = map[string]any{ + "packets": "tlshello", + "length": configOpt.TLSTricks.FragmentSize, + "interval": configOpt.TLSTricks.FragmentSleep, + } + } + } + } + if base.Type == C.TypeDirect { + return patchOutboundFragment(base, configOpt, obj) + } + + if tls == nil || !tls.Enabled || transport == nil { + return obj + } + + if transport.Type != C.V2RayTransportTypeWebsocket && transport.Type != C.V2RayTransportTypeGRPC && transport.Type != C.V2RayTransportTypeHTTPUpgrade { + return obj + } + + if outtls, ok := obj["tls"].(map[string]interface{}); ok { + obj = patchOutboundFragment(base, configOpt, obj) + tlsTricks := tls.TLSTricks + if tlsTricks == nil { + tlsTricks = &option.TLSTricksOptions{} + } + tlsTricks.MixedCaseSNI = tlsTricks.MixedCaseSNI || configOpt.TLSTricks.MixedSNICase + + if configOpt.TLSTricks.EnablePadding { + tlsTricks.PaddingMode = "random" + tlsTricks.PaddingSize = configOpt.TLSTricks.PaddingSize + // fmt.Printf("--------------------%+v----%+v", tlsTricks.PaddingSize, configOpt) + outtls["utls"] = map[string]interface{}{ + "enabled": true, + "fingerprint": "custom", + } + } + + outtls["tls_tricks"] = tlsTricks + // if tlsTricks.MixedCaseSNI || tlsTricks.PaddingMode != "" { + // // } else { + // // tls["tls_tricks"] = nil + // } + // fmt.Printf("-------%+v------------- ", tlsTricks) + } + return obj +} + +func patchOutboundFragment(base option.Outbound, configOpt HiddifyOptions, obj outboundMap) outboundMap { + if configOpt.TLSTricks.EnableFragment { + obj["tcp_fast_open"] = false + obj["tls_fragment"] = option.TLSFragmentOptions{ + Enabled: configOpt.TLSTricks.EnableFragment, + Size: configOpt.TLSTricks.FragmentSize, + Sleep: configOpt.TLSTricks.FragmentSleep, + } + + } + + return obj +} + +func isOutboundReality(base option.Outbound) bool { + // this function checks reality status ONLY FOR VLESS. + // Some other protocols can also use reality, but it's discouraged as stated in the reality document + if base.Type != C.TypeVLESS { + return false + } + if base.VLESSOptions.OutboundTLSOptionsContainer.TLS == nil { + return false + } + if base.VLESSOptions.OutboundTLSOptionsContainer.TLS.Reality == nil { + return false + } + return base.VLESSOptions.OutboundTLSOptionsContainer.TLS.Reality.Enabled +} + +func patchOutbound(base option.Outbound, configOpt HiddifyOptions, staticIpsDns map[string][]string) (*option.Outbound, string, error) { + formatErr := func(err error) error { + return fmt.Errorf("error patching outbound[%s][%s]: %w", base.Tag, base.Type, err) + } + err := patchWarp(&base, &configOpt, true, staticIpsDns) + if err != nil { + return nil, "", formatErr(err) + } + var outbound option.Outbound + + jsonData, err := base.MarshalJSON() + if err != nil { + return nil, "", formatErr(err) + } + + var obj outboundMap + err = json.Unmarshal(jsonData, &obj) + if err != nil { + return nil, "", formatErr(err) + } + var serverDomain string + if detour, ok := obj["detour"].(string); !ok || detour == "" { + if server, ok := obj["server"].(string); ok { + if server != "" && net.ParseIP(server) == nil { + serverDomain = fmt.Sprintf("full:%s", server) + } + } + } + + obj = patchOutboundTLSTricks(base, configOpt, obj) + + switch base.Type { + case C.TypeVMess, C.TypeVLESS, C.TypeTrojan, C.TypeShadowsocks: + obj = patchOutboundMux(base, configOpt, obj) + } + + modifiedJson, err := json.Marshal(obj) + if err != nil { + return nil, "", formatErr(err) + } + + err = outbound.UnmarshalJSON(modifiedJson) + if err != nil { + return nil, "", formatErr(err) + } + + return &outbound, serverDomain, nil +} + +// func (o outboundMap) transportType() string { +// if transport, ok := o["transport"].(map[string]interface{}); ok { +// if transportType, ok := transport["type"].(string); ok { +// return transportType +// } +// } +// return "" +// } diff --git a/libcore/config/parser.go b/libcore/config/parser.go new file mode 100644 index 0000000..b6e23de --- /dev/null +++ b/libcore/config/parser.go @@ -0,0 +1,142 @@ +package config + +import ( + "bytes" + "context" + _ "embed" + "encoding/json" + "fmt" + "os" + "path/filepath" + + "github.com/hiddify/ray2sing/ray2sing" + "github.com/sagernet/sing-box/experimental/libbox" + "github.com/sagernet/sing-box/option" + "github.com/sagernet/sing/common/batch" + SJ "github.com/sagernet/sing/common/json" + "github.com/xmdhs/clash2singbox/convert" + "github.com/xmdhs/clash2singbox/model/clash" + "gopkg.in/yaml.v3" +) + +//go:embed config.json.template +var configByte []byte + +func ParseConfig(path string, debug bool) ([]byte, error) { + content, err := os.ReadFile(path) + os.Chdir(filepath.Dir(path)) + if err != nil { + return nil, err + } + return ParseConfigContent(string(content), debug, nil, false) +} + +func ParseConfigContentToOptions(contentstr string, debug bool, configOpt *HiddifyOptions, fullConfig bool) (*option.Options, error) { + content, err := ParseConfigContent(contentstr, debug, configOpt, fullConfig) + if err != nil { + return nil, err + } + var options option.Options + err = json.Unmarshal(content, &options) + if err != nil { + return nil, err + } + return &options, nil +} + +func ParseConfigContent(contentstr string, debug bool, configOpt *HiddifyOptions, fullConfig bool) ([]byte, error) { + if configOpt == nil { + configOpt = DefaultHiddifyOptions() + } + content := []byte(contentstr) + var jsonObj map[string]interface{} = make(map[string]interface{}) + + fmt.Printf("Convert using json\n") + var tmpJsonResult any + jsonDecoder := json.NewDecoder(SJ.NewCommentFilter(bytes.NewReader(content))) + if err := jsonDecoder.Decode(&tmpJsonResult); err == nil { + if tmpJsonObj, ok := tmpJsonResult.(map[string]interface{}); ok { + if tmpJsonObj["outbounds"] == nil { + jsonObj["outbounds"] = []interface{}{jsonObj} + } else { + if fullConfig || (configOpt != nil && configOpt.EnableFullConfig) { + jsonObj = tmpJsonObj + } else { + jsonObj["outbounds"] = tmpJsonObj["outbounds"] + } + } + } else if jsonArray, ok := tmpJsonResult.([]map[string]interface{}); ok { + jsonObj["outbounds"] = jsonArray + } else { + return nil, fmt.Errorf("[SingboxParser] Incorrect Json Format") + } + + newContent, _ := json.MarshalIndent(jsonObj, "", " ") + + return patchConfig(newContent, "SingboxParser", configOpt) + } + + v2rayStr, err := ray2sing.Ray2Singbox(string(content), configOpt.UseXrayCoreWhenPossible) + if err == nil { + return patchConfig([]byte(v2rayStr), "V2rayParser", configOpt) + } + fmt.Printf("Convert using clash\n") + clashObj := clash.Clash{} + if err := yaml.Unmarshal(content, &clashObj); err == nil && clashObj.Proxies != nil { + if len(clashObj.Proxies) == 0 { + return nil, fmt.Errorf("[ClashParser] no outbounds found") + } + converted, err := convert.Clash2sing(clashObj) + if err != nil { + return nil, fmt.Errorf("[ClashParser] converting clash to sing-box error: %w", err) + } + output := configByte + output, err = convert.Patch(output, converted, "", "", nil) + if err != nil { + return nil, fmt.Errorf("[ClashParser] patching clash config error: %w", err) + } + return patchConfig(output, "ClashParser", configOpt) + } + + return nil, fmt.Errorf("unable to determine config format") +} + +func patchConfig(content []byte, name string, configOpt *HiddifyOptions) ([]byte, error) { + options := option.Options{} + err := json.Unmarshal(content, &options) + if err != nil { + return nil, fmt.Errorf("[SingboxParser] unmarshal error: %w", err) + } + b, _ := batch.New(context.Background(), batch.WithConcurrencyNum[*option.Outbound](2)) + for _, base := range options.Outbounds { + out := base + b.Go(base.Tag, func() (*option.Outbound, error) { + err := patchWarp(&out, configOpt, false, nil) + if err != nil { + return nil, fmt.Errorf("[Warp] patch warp error: %w", err) + } + // options.Outbounds[i] = base + return &out, nil + }) + } + if res, err := b.WaitAndGetResult(); err != nil { + return nil, err + } else { + for i, base := range options.Outbounds { + options.Outbounds[i] = *res[base.Tag].Value + } + } + + content, _ = json.MarshalIndent(options, "", " ") + + fmt.Printf("%s\n", content) + return validateResult(content, name) +} + +func validateResult(content []byte, name string) ([]byte, error) { + err := libbox.CheckConfig(string(content)) + if err != nil { + return nil, fmt.Errorf("[%s] invalid sing-box config: %w", name, err) + } + return content, nil +} diff --git a/libcore/config/rules.go b/libcore/config/rules.go new file mode 100644 index 0000000..d9be177 --- /dev/null +++ b/libcore/config/rules.go @@ -0,0 +1,96 @@ +package config + +import ( + "strconv" + "strings" + + "github.com/sagernet/sing-box/option" +) + +type Rule struct { + RuleSetUrl string `json:"rule-set-url"` + Domains string `json:"domains"` + IP string `json:"ip"` + Port string `json:"port"` + Network string `json:"network"` + Protocol string `json:"protocol"` + Outbound string `json:"outbound"` +} + +func (r *Rule) MakeRule() option.DefaultRule { + rule := option.DefaultRule{} + if len(r.Domains) > 0 { + rule = makeDomainRule(rule, strings.Split(r.Domains, ",")) + } + if len(r.IP) > 0 { + rule = makeIpRule(rule, strings.Split(r.IP, ",")) + } + if len(r.Port) > 0 { + rule = makePortRule(rule, strings.Split(r.Port, ",")) + } + if len(r.Network) > 0 { + rule.Network = append(rule.Network, r.Network) + } + if len(r.Protocol) > 0 { + rule.Protocol = append(rule.Protocol, strings.Split(r.Protocol, ",")...) + } + return rule +} + +func (r *Rule) MakeDNSRule() option.DefaultDNSRule { + rule := option.DefaultDNSRule{} + domains := strings.Split(r.Domains, ",") + for _, item := range domains { + if strings.HasPrefix(item, "geosite:") { + rule.Geosite = append(rule.Geosite, strings.TrimPrefix(item, "geosite:")) + } else if strings.HasPrefix(item, "full:") { + rule.Domain = append(rule.Domain, strings.ToLower(strings.TrimPrefix(item, "full:"))) + } else if strings.HasPrefix(item, "domain:") { + rule.DomainSuffix = append(rule.DomainSuffix, strings.ToLower(strings.TrimPrefix(item, "domain:"))) + } else if strings.HasPrefix(item, "regexp:") { + rule.DomainRegex = append(rule.DomainRegex, strings.ToLower(strings.TrimPrefix(item, "regexp:"))) + } else if strings.HasPrefix(item, "keyword:") { + rule.DomainKeyword = append(rule.DomainKeyword, strings.ToLower(strings.TrimPrefix(item, "keyword:"))) + } + } + return rule +} + +func makeDomainRule(options option.DefaultRule, list []string) option.DefaultRule { + for _, item := range list { + if strings.HasPrefix(item, "geosite:") { + options.Geosite = append(options.Geosite, strings.TrimPrefix(item, "geosite:")) + } else if strings.HasPrefix(item, "full:") { + options.Domain = append(options.Domain, strings.ToLower(strings.TrimPrefix(item, "full:"))) + } else if strings.HasPrefix(item, "domain:") { + options.DomainSuffix = append(options.DomainSuffix, strings.ToLower(strings.TrimPrefix(item, "domain:"))) + } else if strings.HasPrefix(item, "regexp:") { + options.DomainRegex = append(options.DomainRegex, strings.ToLower(strings.TrimPrefix(item, "regexp:"))) + } else if strings.HasPrefix(item, "keyword:") { + options.DomainKeyword = append(options.DomainKeyword, strings.ToLower(strings.TrimPrefix(item, "keyword:"))) + } + } + return options +} + +func makeIpRule(options option.DefaultRule, list []string) option.DefaultRule { + for _, item := range list { + if strings.HasPrefix(item, "geoip:") { + options.GeoIP = append(options.GeoIP, strings.TrimPrefix(item, "geoip:")) + } else { + options.IPCIDR = append(options.IPCIDR, item) + } + } + return options +} + +func makePortRule(options option.DefaultRule, list []string) option.DefaultRule { + for _, item := range list { + if strings.Contains(item, ":") { + options.PortRange = append(options.PortRange, item) + } else if i, err := strconv.Atoi(item); err == nil { + options.Port = append(options.Port, uint16(i)) + } + } + return options +} diff --git a/libcore/config/server.go b/libcore/config/server.go new file mode 100644 index 0000000..6824220 --- /dev/null +++ b/libcore/config/server.go @@ -0,0 +1,75 @@ +package config + +import ( + context "context" + "fmt" + "log" + "net" + "os" + "path/filepath" + + "github.com/sagernet/sing-box/option" + "google.golang.org/grpc" +) + +type server struct { + UnimplementedCoreServiceServer +} + +func String(s string) *string { + return &s +} + +func (s *server) ParseConfig(ctx context.Context, in *ParseConfigRequest) (*ParseConfigResponse, error) { + config, err := ParseConfig(in.TempPath, in.Debug) + if err != nil { + return &ParseConfigResponse{Error: String(err.Error())}, nil + } + err = os.WriteFile(in.Path, config, 0o644) + if err != nil { + return nil, err + } + return &ParseConfigResponse{Error: String("")}, nil +} + +func (s *server) GenerateFullConfig(ctx context.Context, in *GenerateConfigRequest) (*GenerateConfigResponse, error) { + os.Chdir(filepath.Dir(in.Path)) + content, err := os.ReadFile(in.Path) + if err != nil { + return nil, err + } + var options option.Options + err = options.UnmarshalJSON(content) + if err != nil { + return nil, err + } + if err != nil { + return nil, err + } + config, err := BuildConfigJson(*DefaultHiddifyOptions(), options) + if err != nil { + return nil, err + } + return &GenerateConfigResponse{ + Config: config, + }, nil +} + +func StartGRPCServer(port uint16) error { + lis, err := net.Listen("tcp", fmt.Sprintf(":%d", port)) + if err != nil { + log.Fatalf("Failed to listen: %v", err) + } + + s := grpc.NewServer() + RegisterCoreServiceServer(s, &server{}) + + log.Println("Server started on :", port) + go func() { + if err := s.Serve(lis); err != nil { + log.Fatalf("Failed to serve: %v", err) + } + }() + + return nil +} diff --git a/libcore/config/types.go b/libcore/config/types.go new file mode 100644 index 0000000..9fe6cc5 --- /dev/null +++ b/libcore/config/types.go @@ -0,0 +1,25 @@ +package config + +import ( + "encoding/json" + "time" +) + +type DurationInSeconds int + +func (d DurationInSeconds) MarshalJSON() ([]byte, error) { + return json.Marshal(int64(d)) +} + +func (d *DurationInSeconds) UnmarshalJSON(bytes []byte) error { + var v int64 + if err := json.Unmarshal(bytes, &v); err != nil { + return err + } + *d = DurationInSeconds(v) + return nil +} + +func (d DurationInSeconds) Duration() time.Duration { + return time.Duration(d) * time.Second +} diff --git a/libcore/config/warp.go b/libcore/config/warp.go new file mode 100644 index 0000000..36a3416 --- /dev/null +++ b/libcore/config/warp.go @@ -0,0 +1,270 @@ +package config + +import ( + "encoding/base64" + "fmt" + "log/slog" + "net/netip" + "os" + "strings" + + "github.com/bepass-org/warp-plus/warp" + "github.com/hiddify/hiddify-core/v2/common" + C "github.com/sagernet/sing-box/constant" + + // "github.com/bepass-org/wireguard-go/warp" + "github.com/hiddify/hiddify-core/v2/db" + + "github.com/sagernet/sing-box/option" + T "github.com/sagernet/sing-box/option" +) + +type SingboxConfig struct { + Type string `json:"type"` + Tag string `json:"tag"` + Server string `json:"server"` + ServerPort int `json:"server_port"` + LocalAddress []string `json:"local_address"` + PrivateKey string `json:"private_key"` + PeerPublicKey string `json:"peer_public_key"` + Reserved []int `json:"reserved"` + MTU int `json:"mtu"` +} + +func wireGuardToSingbox(wgConfig WarpWireguardConfig, server string, port uint16) (*T.Outbound, error) { + clientID, _ := base64.StdEncoding.DecodeString(wgConfig.ClientID) + if len(clientID) < 2 { + clientID = []byte{0, 0, 0} + } + out := T.Outbound{ + Type: "wireguard", + Tag: "WARP", + WireGuardOptions: T.WireGuardOutboundOptions{ + ServerOptions: T.ServerOptions{ + Server: server, + ServerPort: port, + }, + + PrivateKey: wgConfig.PrivateKey, + PeerPublicKey: wgConfig.PeerPublicKey, + Reserved: []uint8{clientID[0], clientID[1], clientID[2]}, + // Reserved: []uint8{0, 0, 0}, + MTU: 1330, + }, + } + ips := []string{wgConfig.LocalAddressIPv4 + "/24", wgConfig.LocalAddressIPv6 + "/128"} + + for _, addr := range ips { + if addr == "" { + continue + } + prefix, err := netip.ParsePrefix(addr) + if err != nil { + return nil, err // Handle the error appropriately + } + out.WireGuardOptions.LocalAddress = append(out.WireGuardOptions.LocalAddress, prefix) + } + return &out, nil +} + +func getRandomIP() string { + ipPort, err := warp.RandomWarpEndpoint(true, true) + if err == nil { + return ipPort.Addr().String() + } + return "engage.cloudflareclient.com" +} + +func generateWarp(license string, host string, port uint16, fakePackets string, fakePacketsSize string, fakePacketsDelay string, fakePacketsMode string) (*T.Outbound, error) { + _, _, wgConfig, err := GenerateWarpInfo(license, "", "") + if err != nil { + return nil, err + } + if wgConfig == nil { + return nil, fmt.Errorf("invalid warp config") + } + + return GenerateWarpSingbox(*wgConfig, host, port, fakePackets, fakePacketsSize, fakePacketsDelay, fakePacketsMode) +} + +func GenerateWarpSingbox(wgConfig WarpWireguardConfig, host string, port uint16, fakePackets string, fakePacketsSize string, fakePacketsDelay string, fakePacketMode string) (*T.Outbound, error) { + if host == "" { + host = "auto4" + } + + if (host == "auto" || host == "auto4" || host == "auto6") && fakePackets == "" { + fakePackets = "1-3" + } + if fakePackets != "" && fakePacketsSize == "" { + fakePacketsSize = "10-30" + } + if fakePackets != "" && fakePacketsDelay == "" { + fakePacketsDelay = "10-30" + } + singboxConfig, err := wireGuardToSingbox(wgConfig, host, port) + if err != nil { + fmt.Printf("%v %v", singboxConfig, err) + return nil, err + } + + singboxConfig.WireGuardOptions.FakePackets = fakePackets + singboxConfig.WireGuardOptions.FakePacketsSize = fakePacketsSize + singboxConfig.WireGuardOptions.FakePacketsDelay = fakePacketsDelay + singboxConfig.WireGuardOptions.FakePacketsMode = fakePacketMode + + return singboxConfig, nil +} + +func GenerateWarpInfo(license string, oldAccountId string, oldAccessToken string) (*warp.Identity, string, *WarpWireguardConfig, error) { + if oldAccountId != "" && oldAccessToken != "" { + err := warp.DeleteDevice(oldAccessToken, oldAccountId) + if err != nil { + fmt.Printf("Error in removing old device: %v\n", err) + } else { + fmt.Printf("Old Device Removed") + } + } + l := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo})) + identity, err := warp.CreateIdentityOnly(l, license) + res := "Error!" + var warpcfg WarpWireguardConfig + if err == nil { + res = "Success" + res = fmt.Sprintf("Warp+ enabled: %t\n", identity.Account.WarpPlus) + res += fmt.Sprintf("\nAccount type: %s\n", identity.Account.AccountType) + warpcfg = WarpWireguardConfig{ + PrivateKey: identity.PrivateKey, + PeerPublicKey: identity.Config.Peers[0].PublicKey, + LocalAddressIPv4: identity.Config.Interface.Addresses.V4, + LocalAddressIPv6: identity.Config.Interface.Addresses.V6, + ClientID: identity.Config.ClientID, + } + } + + return &identity, res, &warpcfg, err +} + +func getOrGenerateWarpLocallyIfNeeded(warpOptions *WarpOptions) WarpWireguardConfig { + if warpOptions.WireguardConfig.PrivateKey != "" { + return warpOptions.WireguardConfig + } + table := db.GetTable[WarpOptions]() + dbWarpOptions, err := table.Get(warpOptions.Id) + if err == nil && dbWarpOptions.WireguardConfig.PrivateKey != "" { + return warpOptions.WireguardConfig + } + license := "" + if len(warpOptions.Id) == 26 { // warp key is 26 characters long + license = warpOptions.Id + } else if len(warpOptions.Id) > 28 && warpOptions.Id[2] == '_' { // warp key is 26 characters long + license = warpOptions.Id[3:] + } + + accountidentity, _, wireguardConfig, err := GenerateWarpInfo(license, warpOptions.Account.AccountID, warpOptions.Account.AccessToken) + if err != nil { + return WarpWireguardConfig{} + } + warpOptions.Account = WarpAccount{ + AccountID: accountidentity.ID, + AccessToken: accountidentity.Token, + } + warpOptions.WireguardConfig = *wireguardConfig + table.UpdateInsert(warpOptions) + + return *wireguardConfig +} + +func patchWarp(base *option.Outbound, configOpt *HiddifyOptions, final bool, staticIpsDns map[string][]string) error { + if base.Type == C.TypeCustom { + if warp, ok := base.CustomOptions["warp"].(map[string]interface{}); ok { + key, _ := warp["key"].(string) + host, _ := warp["host"].(string) + port, _ := warp["port"].(uint16) + detour, _ := warp["detour"].(string) + fakePackets, _ := warp["fake_packets"].(string) + fakePacketsSize, _ := warp["fake_packets_size"].(string) + fakePacketsDelay, _ := warp["fake_packets_delay"].(string) + fakePacketsMode, _ := warp["fake_packets_mode"].(string) + var warpOutbound *T.Outbound + var err error + + is_saved_key := len(key) > 1 && key[0] == 'p' + + if (configOpt == nil || !final) && is_saved_key { + return nil + } + var wireguardConfig WarpWireguardConfig + if is_saved_key { + var warpOpt *WarpOptions + if key == "p1" { + warpOpt = &configOpt.Warp + } else if key == "p2" { + warpOpt = &configOpt.Warp2 + } else { + warpOpt = &WarpOptions{ + Id: key, + } + } + warpOpt.Id = key + + wireguardConfig = getOrGenerateWarpLocallyIfNeeded(warpOpt) + } else { + _, _, wgConfig, err := GenerateWarpInfo(key, "", "") + if err != nil { + return err + } + wireguardConfig = *wgConfig + } + warpOutbound, err = GenerateWarpSingbox(wireguardConfig, host, port, fakePackets, fakePacketsSize, fakePacketsDelay, fakePacketsMode) + if err != nil { + fmt.Printf("Error generating warp config: %v", err) + return err + } + warpOutbound.WireGuardOptions.Detour = detour + base.Type = C.TypeWireGuard + base.WireGuardOptions = warpOutbound.WireGuardOptions + } + } + + if final && base.Type == C.TypeWireGuard { + host := base.WireGuardOptions.Server + + if host == "default" || host == "random" || host == "auto" || host == "auto4" || host == "auto6" || isBlockedDomain(host) { + // if base.WireGuardOptions.Detour != "" { + // base.WireGuardOptions.Server = "162.159.192.1" + // } else { + rndDomain := strings.ToLower(generateRandomString(20)) + staticIpsDns[rndDomain] = []string{} + if host != "auto4" { + if host == "auto6" || common.CanConnectIPv6() { + randomIpPort, _ := warp.RandomWarpEndpoint(false, true) + staticIpsDns[rndDomain] = append(staticIpsDns[rndDomain], randomIpPort.Addr().String()) + } + } + if host != "auto6" { + randomIpPort, _ := warp.RandomWarpEndpoint(true, false) + staticIpsDns[rndDomain] = append(staticIpsDns[rndDomain], randomIpPort.Addr().String()) + } + base.WireGuardOptions.Server = rndDomain + // } + } + if base.WireGuardOptions.ServerPort == 0 { + port := warp.RandomWarpPort() + base.WireGuardOptions.ServerPort = port + } + + if base.WireGuardOptions.Detour != "" { + if base.WireGuardOptions.MTU < 100 { + base.WireGuardOptions.MTU = 1280 + } + base.WireGuardOptions.FakePackets = "" + base.WireGuardOptions.FakePacketsDelay = "" + base.WireGuardOptions.FakePacketsSize = "" + } + // if base.WireGuardOptions.Detour == "" { + // base.WireGuardOptions.GSO = runtime.GOOS != "windows" + // } + } + + return nil +} diff --git a/libcore/config/warp_account.go b/libcore/config/warp_account.go new file mode 100644 index 0000000..2578e35 --- /dev/null +++ b/libcore/config/warp_account.go @@ -0,0 +1,50 @@ +package config + +import ( + "encoding/json" +) + +type WarpAccount struct { + AccountID string `json:"account-id"` + AccessToken string `json:"access-token"` +} + +type WarpWireguardConfig struct { + PrivateKey string `json:"private-key"` + LocalAddressIPv4 string `json:"local-address-ipv4"` + LocalAddressIPv6 string `json:"local-address-ipv6"` + PeerPublicKey string `json:"peer-public-key"` + ClientID string `json:"client-id"` +} + +type WarpGenerationResponse struct { + WarpAccount + Log string `json:"log"` + Config WarpWireguardConfig `json:"config"` +} + +func GenerateWarpAccount(licenseKey string, accountId string, accessToken string) (string, error) { + identity, log, wg, err := GenerateWarpInfo(licenseKey, accountId, accessToken) + if err != nil { + return "", err + } + + warpAccount := WarpAccount{ + AccountID: identity.ID, + AccessToken: identity.Token, + } + warpConfig := WarpWireguardConfig{ + PrivateKey: wg.PrivateKey, + LocalAddressIPv4: wg.LocalAddressIPv4, + LocalAddressIPv6: wg.LocalAddressIPv6, + PeerPublicKey: wg.PeerPublicKey, + ClientID: wg.ClientID, + } + response := WarpGenerationResponse{warpAccount, log, warpConfig} + + responseJson, err := json.Marshal(response) + if err != nil { + return "", err + } + return string(responseJson), nil +} diff --git a/libcore/custom/cmd_interface.go b/libcore/custom/cmd_interface.go new file mode 100644 index 0000000..28c34b8 --- /dev/null +++ b/libcore/custom/cmd_interface.go @@ -0,0 +1,26 @@ +package main + +/* +#include +*/ +import "C" +import ( + "unsafe" + + "github.com/hiddify/hiddify-core/cmd" +) + +//export parseCli +func parseCli(argc C.int, argv **C.char) *C.char { + args := make([]string, argc) + for i := 0; i < int(argc); i++ { + // fmt.Println("parseCli", C.GoString(*argv)) + args[i] = C.GoString(*argv) + argv = (**C.char)(unsafe.Pointer(uintptr(unsafe.Pointer(argv)) + uintptr(unsafe.Sizeof(*argv)))) + } + err := cmd.ParseCli(args[1:]) + if err != nil { + return C.CString(err.Error()) + } + return C.CString("") +} diff --git a/libcore/custom/custom.go b/libcore/custom/custom.go new file mode 100644 index 0000000..ff99021 --- /dev/null +++ b/libcore/custom/custom.go @@ -0,0 +1,169 @@ +package main + +/* +#include "stdint.h" +*/ +import "C" + +import ( + "encoding/json" + "fmt" + "os" + "unsafe" + + "github.com/hiddify/hiddify-core/bridge" + "github.com/hiddify/hiddify-core/config" + pb "github.com/hiddify/hiddify-core/hiddifyrpc" + v2 "github.com/hiddify/hiddify-core/v2" + + "github.com/sagernet/sing-box/log" +) + +//export setupOnce +func setupOnce(api unsafe.Pointer) { + bridge.InitializeDartApi(api) +} + +//export setup +func setup(baseDir *C.char, workingDir *C.char, tempDir *C.char, statusPort C.longlong, debug bool) (CErr *C.char) { + err := v2.Setup(C.GoString(baseDir), C.GoString(workingDir), C.GoString(tempDir), int64(statusPort), debug) + return emptyOrErrorC(err) +} + +//export parse +func parse(path *C.char, tempPath *C.char, debug bool) (CErr *C.char) { + res, err := v2.Parse(&pb.ParseRequest{ + ConfigPath: C.GoString(path), + TempPath: C.GoString(tempPath), + }) + if err != nil { + log.Error(err.Error()) + return C.CString(err.Error()) + } + + err = os.WriteFile(C.GoString(path), []byte(res.Content), 0o644) + return emptyOrErrorC(err) +} + +//export changeHiddifyOptions +func changeHiddifyOptions(HiddifyOptionsJson *C.char) (CErr *C.char) { + _, err := v2.ChangeHiddifySettings(&pb.ChangeHiddifySettingsRequest{ + HiddifySettingsJson: C.GoString(HiddifyOptionsJson), + }) + return emptyOrErrorC(err) +} + +//export generateConfig +func generateConfig(path *C.char) (res *C.char) { + conf, err := v2.GenerateConfig(&pb.GenerateConfigRequest{ + Path: C.GoString(path), + }) + if err != nil { + return emptyOrErrorC(err) + } + fmt.Printf("Config: %+v\n", conf) + fmt.Printf("ConfigContent: %+v\n", conf.ConfigContent) + return C.CString(conf.ConfigContent) +} + +//export start +func start(configPath *C.char, disableMemoryLimit bool) (CErr *C.char) { + _, err := v2.Start(&pb.StartRequest{ + ConfigPath: C.GoString(configPath), + EnableOldCommandServer: true, + DisableMemoryLimit: disableMemoryLimit, + }) + return emptyOrErrorC(err) +} + +//export stop +func stop() (CErr *C.char) { + _, err := v2.Stop() + return emptyOrErrorC(err) +} + +//export restart +func restart(configPath *C.char, disableMemoryLimit bool) (CErr *C.char) { + _, err := v2.Restart(&pb.StartRequest{ + ConfigPath: C.GoString(configPath), + EnableOldCommandServer: true, + DisableMemoryLimit: disableMemoryLimit, + }) + return emptyOrErrorC(err) +} + +//export startCommandClient +func startCommandClient(command C.int, port C.longlong) *C.char { + err := v2.StartCommand(int32(command), int64(port)) + return emptyOrErrorC(err) +} + +//export stopCommandClient +func stopCommandClient(command C.int) *C.char { + err := v2.StopCommand(int32(command)) + return emptyOrErrorC(err) +} + +//export selectOutbound +func selectOutbound(groupTag *C.char, outboundTag *C.char) (CErr *C.char) { + _, err := v2.SelectOutbound(&pb.SelectOutboundRequest{ + GroupTag: C.GoString(groupTag), + OutboundTag: C.GoString(outboundTag), + }) + + return emptyOrErrorC(err) +} + +//export urlTest +func urlTest(groupTag *C.char) (CErr *C.char) { + _, err := v2.UrlTest(&pb.UrlTestRequest{ + GroupTag: C.GoString(groupTag), + }) + + return emptyOrErrorC(err) +} + +func emptyOrErrorC(err error) *C.char { + if err == nil { + return C.CString("") + } + log.Error(err.Error()) + return C.CString(err.Error()) +} + +//export generateWarpConfig +func generateWarpConfig(licenseKey *C.char, accountId *C.char, accessToken *C.char) (CResp *C.char) { + res, err := v2.GenerateWarpConfig(&pb.GenerateWarpConfigRequest{ + LicenseKey: C.GoString(licenseKey), + AccountId: C.GoString(accountId), + AccessToken: C.GoString(accessToken), + }) + if err != nil { + return C.CString(fmt.Sprint("error: ", err.Error())) + } + warpAccount := config.WarpAccount{ + AccountID: res.Account.AccountId, + AccessToken: res.Account.AccessToken, + } + warpConfig := config.WarpWireguardConfig{ + PrivateKey: res.Config.PrivateKey, + LocalAddressIPv4: res.Config.LocalAddressIpv4, + LocalAddressIPv6: res.Config.LocalAddressIpv6, + PeerPublicKey: res.Config.PeerPublicKey, + ClientID: res.Config.ClientId, + } + log := res.Log + response := &config.WarpGenerationResponse{ + WarpAccount: warpAccount, + Log: log, + Config: warpConfig, + } + + responseJson, err := json.Marshal(response) + if err != nil { + return C.CString("") + } + return C.CString(string(responseJson)) +} + +func main() {} diff --git a/libcore/custom/grpc_interface.go b/libcore/custom/grpc_interface.go new file mode 100644 index 0000000..b9cab67 --- /dev/null +++ b/libcore/custom/grpc_interface.go @@ -0,0 +1,10 @@ +package main + +import "C" +import v2 "github.com/hiddify/hiddify-core/v2" + +//export StartCoreGrpcServer +func StartCoreGrpcServer(listenAddress *C.char) (CErr *C.char) { + _, err := v2.StartCoreGrpcServer(C.GoString(listenAddress)) + return emptyOrErrorC(err) +} diff --git a/libcore/docker-compile.sh b/libcore/docker-compile.sh new file mode 100755 index 0000000..0963791 --- /dev/null +++ b/libcore/docker-compile.sh @@ -0,0 +1,72 @@ +#!/bin/bash +set -e + +echo "安装构建依赖..." +apt-get update -qq +apt-get install -y -qq wget unzip openjdk-17-jdk build-essential npm + +echo "创建Android SDK目录结构..." +mkdir -p /opt/android-sdk/cmdline-tools + +echo "下载Android SDK命令行工具..." +cd /tmp +wget -q https://dl.google.com/android/repository/commandlinetools-linux-11076708_latest.zip +unzip -q commandlinetools-linux-11076708_latest.zip +mv cmdline-tools /opt/android-sdk/cmdline-tools/latest + +export ANDROID_HOME=/opt/android-sdk +export PATH=$PATH:$ANDROID_HOME/cmdline-tools/latest/bin:$ANDROID_HOME/platform-tools + +echo "接受Android SDK许可..." +yes | sdkmanager --licenses > /dev/null 2>&1 || true + +echo "安装Android SDK Platform 21和Build Tools..." +sdkmanager "platforms;android-21" "build-tools;30.0.3" "platform-tools" + +echo "安装Android NDK..." +cd /tmp +wget -q https://dl.google.com/android/repository/android-ndk-r26c-linux.zip +unzip -q android-ndk-r26c-linux.zip +export ANDROID_NDK_HOME=/tmp/android-ndk-r26c + +echo "安装gomobile..." +go install -v github.com/sagernet/gomobile/cmd/gomobile@v0.1.1 +go install -v github.com/sagernet/gomobile/cmd/gobind@v0.1.1 + +export PATH=$PATH:/root/go/bin + +echo "安装npm依赖..." +npm install --silent + +echo "初始化gomobile..." +gomobile init -ndk $ANDROID_NDK_HOME + +cd /workspace + +echo "开始使用gomobile编译..." +gomobile bind -v \ + -androidapi=21 \ + -javapkg=io.nekohasekai \ + -libname=box \ + -tags="with_gvisor,with_quic,with_wireguard,with_ech,with_utls,with_clash_api,with_grpc" \ + -trimpath \ + -target=android/arm64 \ + -o libcore.aar \ + github.com/sagernet/sing-box/experimental/libbox ./mobile + +if [ ! -f libcore.aar ]; then + echo "❌ 编译失败: libcore.aar未生成" + exit 1 +fi + +echo "提取libbox.so..." +unzip -j libcore.aar jni/arm64-v8a/libbox.so -d /tmp/ +if [ -f /tmp/libbox.so ]; then + cp /tmp/libbox.so /workspace/libbox-new.so + echo "✅ 编译成功!" + ls -lh /workspace/libbox-new.so + md5sum /workspace/libbox-new.so +else + echo "❌ 提取失败: libbox.so未找到" + exit 1 +fi diff --git a/libcore/docker/Dockerfile b/libcore/docker/Dockerfile new file mode 100644 index 0000000..be0c723 --- /dev/null +++ b/libcore/docker/Dockerfile @@ -0,0 +1,30 @@ +FROM alpine:latest +ENV CONFIG='https://raw.githubusercontent.com/ircfspace/warpsub/main/export/warp#WARP%20(IRCF)' +ENV VERSION=v3.1.7 +WORKDIR /hiddify +RUN apk add curl tar gzip libc6-compat # iptables ip6tables + +RUN echo "architecture: $(apk --print-arch)" && \ + case "$(apk --print-arch)" in \ + x86_64) ARCH=amd64 ;; \ + i386|x86) ARCH=386 ;; \ + aarch64) ARCH=arm64 ;; \ + armv7) ARCH=armv7 ;; \ + armv6|armhf) ARCH=armv6 ;; \ + armv5) ARCH=armv5 ;; \ + s390x) ARCH=s390x ;; \ + *) echo "Unsupported architecture: $(apk --print-arch) $(uname -m)" && exit 1 ;; \ + esac && \ + echo "Downloading https://github.com/hiddify/hiddify-core/releases/download/${VERSION}/hiddify-cli-linux-$ARCH.tar.gz" && \ + curl -L -o hiddify-cli.tar.gz https://github.com/hiddify/hiddify-core/releases/download/${VERSION}/hiddify-cli-linux-$ARCH.tar.gz && \ + tar -xzf hiddify-cli.tar.gz && rm hiddify-cli.tar.gz +COPY hiddify.sh . +RUN chmod +x hiddify.sh + +EXPOSE 12334 +EXPOSE 12335 +EXPOSE 16756 +EXPOSE 16450 + + +ENTRYPOINT [ "/hiddify/hiddify.sh" ] diff --git a/libcore/docker/docker-compose.yml b/libcore/docker/docker-compose.yml new file mode 100644 index 0000000..c1275eb --- /dev/null +++ b/libcore/docker/docker-compose.yml @@ -0,0 +1,11 @@ +version: '3.8' + +services: + hiddify: + image: ghcr.io/hiddify/hiddify-core:latest + network_mode: host + environment: + CONFIG: "https://github.com/hiddify/hiddify-next/raw/refs/heads/main/test.configs/warp" + volumes: + - ./hiddify.json:/hiddify/hiddify.json + command: ["/opt/hiddify.sh"] diff --git a/libcore/docker/hiddify.json b/libcore/docker/hiddify.json new file mode 100644 index 0000000..29e01c2 --- /dev/null +++ b/libcore/docker/hiddify.json @@ -0,0 +1,42 @@ +{ + "region":"other", + "service-mode": "proxy", + "log-level": "info", + "resolve-destination": true, + "ipv6-mode": "prefer_ipv4", + "remote-dns-address": "tcp://1.1.1.1", + "remote-dns-domain-strategy": "", + "direct-dns-address": "1.1.1.1", + "direct-dns-domain-strategy": "", + "mixed-port": 12334, + "local-dns-port": 16450, + "tun-implementation": "mixed", + "mtu": 9000, + "strict-route": false, + "connection-test-url": "https://www.gstatic.com/generate_204", + "url-test-interval": 600, + "enable-clash-api": true, + "clash-api-port": 16756, + "bypass-lan": false, + "allow-connection-from-lan": true, + "enable-fake-dns": false, + "enable-dns-routing": true, + "independent-dns-cache": true, + "enable-tls-fragment": false, + "tls-fragment-size": "20-70", + "tls-fragment-sleep": "10-30", + "enable-tls-mixed-sni-case": false, + "enable-tls-padding": false, + "tls-padding-size": "15-30", + "enable-mux": false, + "mux-padding": false, + "mux-max-streams": 4, + "mux-protocol": "h2mux", + "enable-warp": false, + "warp-detour-mode": "outbound", + "warp-license-key": "", + "warp-clean-ip": "auto", + "warp-port": 0, + "warp-noise": "5-10", + "warp-noise-delay": "20-200" +} \ No newline at end of file diff --git a/libcore/docker/hiddify.sh b/libcore/docker/hiddify.sh new file mode 100644 index 0000000..5b1f805 --- /dev/null +++ b/libcore/docker/hiddify.sh @@ -0,0 +1,40 @@ +#!/bin/sh +# sysctl -w net.ipv4.ip_forward=1 +# sysctl -w net.ipv6.ip_forward=1 + +# ip rule add fwmark 1 table 100 ; +# ip route add local 0.0.0.0/0 dev lo table 100 + +# # CREATE TABLE +# iptables -t mangle -N hiddify + +# # RETURN LOCAL AND LANS +# iptables -t mangle -A OUTPUT -j RETURN +# iptables -t nat -A hiddify --dport 2334 -j RETURN + +# iptables -t mangle -A hiddify -d 10.0.0.0/8 -j RETURN +# iptables -t mangle -A hiddify -d 127.0.0.0/8 -j RETURN +# iptables -t mangle -A hiddify -d 169.254.0.0/16 -j RETURN +# iptables -t mangle -A hiddify -d 172.16.0.0/12 -j RETURN +# iptables -t mangle -A hiddify -d 192.168.50.0/16 -j RETURN +# iptables -t mangle -A hiddify -d 192.168.9.0/16 -j RETURN +# iptables -t mangle -A hiddify -d 224.0.0.0/4 -j RETURN +# iptables -t mangle -A hiddify -d 240.0.0.0/4 -j RETURN + +# iptables -t mangle -A hiddify -p udp -j TPROXY --on-port 2334 --tproxy-mark 1 +# iptables -t mangle -A hiddify -p tcp -j TPROXY --on-port 2334 --tproxy-mark 1 + +# # HIJACK ICMP (untested) +# # iptables -t mangle -A hiddify -p icmp -j DNAT --to-destination 127.0.0.1 + +# # REDIRECT +# iptables -t mangle -A PREROUTING -j hiddify + + +if [ -f "/hiddify/hiddify.json" ]; then + /hiddify/HiddifyCli run --config "$CONFIG" -d /hiddify/hiddify.json +else + /hiddify/HiddifyCli run --config "$CONFIG" +fi + + diff --git a/libcore/extension/extension.go b/libcore/extension/extension.go new file mode 100644 index 0000000..09dc4e7 --- /dev/null +++ b/libcore/extension/extension.go @@ -0,0 +1,143 @@ +package extension + +import ( + "encoding/json" + + "github.com/hiddify/hiddify-core/config" + "github.com/hiddify/hiddify-core/extension/ui" + pb "github.com/hiddify/hiddify-core/hiddifyrpc" + "github.com/hiddify/hiddify-core/v2/db" + "github.com/jellydator/validation" + "github.com/sagernet/sing-box/log" + "github.com/sagernet/sing-box/option" +) + +type Extension interface { + GetUI() ui.Form + SubmitData(button string, data map[string]string) error + Close() error + UpdateUI(form ui.Form) error + + BeforeAppConnect(hiddifySettings *config.HiddifyOptions, singconfig *option.Options) error + + StoreData() + + init(id string) + getQueue() chan *pb.ExtensionResponse + getId() string +} + +type Base[T any] struct { + id string + // responseStream grpc.ServerStreamingServer[pb.ExtensionResponse] + queue chan *pb.ExtensionResponse + Data T +} + +// func (b *Base) mustEmbdedBaseExtension() { +// } + +func (b *Base[T]) BeforeAppConnect(hiddifySettings *config.HiddifyOptions, singconfig *option.Options) error { + return nil +} + +func (b *Base[T]) StoreData() { + table := db.GetTable[extensionData]() + ed, err := table.Get(b.id) + if err != nil { + log.Warn("error: ", err) + return + } + res, err := json.Marshal(b.Data) + if err != nil { + log.Warn("error: ", err) + return + } + ed.JsonData = (res) + table.UpdateInsert(ed) +} + +func (b *Base[T]) init(id string) { + b.id = id + b.queue = make(chan *pb.ExtensionResponse, 1) + table := db.GetTable[extensionData]() + extdata, err := table.Get(b.id) + if err != nil { + log.Warn("error: ", err) + return + } + if extdata == nil { + log.Warn("extension data not found ", id) + return + } + if extdata.JsonData != nil { + var t T + if err := json.Unmarshal(extdata.JsonData, &t); err != nil { + log.Warn("error loading data of ", id, " : ", err) + } else { + b.Data = t + } + } +} + +func (b *Base[T]) getQueue() chan *pb.ExtensionResponse { + return b.queue +} + +func (b *Base[T]) getId() string { + return b.id +} + +func (e *Base[T]) ShowMessage(title string, msg string) error { + return e.ShowDialog(ui.Form{ + Title: title, + Description: msg, + Fields: [][]ui.FormField{ + {{ + Type: ui.FieldButton, + Key: ui.ButtonDialogOk, + Label: "Ok", + }}, + }, + // Buttons: []string{ui.Button_Ok}, + }) +} + +func (p *Base[T]) UpdateUI(form ui.Form) error { + p.queue <- &pb.ExtensionResponse{ + ExtensionId: p.id, + Type: pb.ExtensionResponseType_UPDATE_UI, + JsonUi: form.ToJSON(), + } + return nil +} + +func (p *Base[T]) ShowDialog(form ui.Form) error { + p.queue <- &pb.ExtensionResponse{ + ExtensionId: p.id, + Type: pb.ExtensionResponseType_SHOW_DIALOG, + JsonUi: form.ToJSON(), + } + // log.Printf("Updated UI for extension %s: %s", err, p.id) + return nil +} + +func (base *Base[T]) ValName(fieldPtr interface{}) string { + val, err := validation.ErrorFieldName(&base.Data, fieldPtr) + if err != nil { + log.Warn(err) + return "" + } + if val == "" { + log.Warn("Field not found") + return "" + } + return val +} + +type ExtensionFactory struct { + Id string + Title string + Description string + Builder func() Extension +} diff --git a/libcore/extension/extension_host.go b/libcore/extension/extension_host.go new file mode 100644 index 0000000..c66e07f --- /dev/null +++ b/libcore/extension/extension_host.go @@ -0,0 +1,146 @@ +package extension + +import ( + "context" + "fmt" + "log" + + pb "github.com/hiddify/hiddify-core/hiddifyrpc" + "github.com/hiddify/hiddify-core/v2/db" + "google.golang.org/grpc" +) + +type ExtensionHostService struct { + pb.UnimplementedExtensionHostServiceServer +} + +func (ExtensionHostService) ListExtensions(ctx context.Context, empty *pb.Empty) (*pb.ExtensionList, error) { + extensionList := &pb.ExtensionList{ + Extensions: make([]*pb.Extension, 0), + } + allext, err := db.GetTable[extensionData]().All() + if err != nil { + return nil, err + } + for _, dbext := range allext { + if ext, ok := allExtensionsMap[dbext.Id]; ok { + extensionList.Extensions = append(extensionList.Extensions, &pb.Extension{ + Id: ext.Id, + Title: ext.Title, + Description: ext.Description, + Enable: dbext.Enable, + }) + } + } + + return extensionList, nil +} + +func getExtension(id string) (*Extension, error) { + if !isEnable(id) { + return nil, fmt.Errorf("Extension with ID %s is not enabled", id) + } + if extension, ok := enabledExtensionsMap[id]; ok { + return extension, nil + } + return nil, fmt.Errorf("Extension with ID %s not found", id) +} + +func (e ExtensionHostService) Connect(req *pb.ExtensionRequest, stream grpc.ServerStreamingServer[pb.ExtensionResponse]) error { + extension, err := getExtension(req.GetExtensionId()) + if err != nil { + log.Printf("Error connecting stream for extension %s: %v", req.GetExtensionId(), err) + return err + } + + log.Printf("Connecting stream for extension %s", req.GetExtensionId()) + log.Printf("Extension data: %+v", extension) + + if err := (*extension).UpdateUI((*extension).GetUI()); err != nil { + log.Printf("Error updating UI for extension %s: %v", req.GetExtensionId(), err) + } + + for { + select { + case <-stream.Context().Done(): + return nil + case info := <-(*extension).getQueue(): + stream.Send(info) + if info.GetType() == pb.ExtensionResponseType_END { + return nil + } + } + } +} + +func (e ExtensionHostService) SubmitForm(ctx context.Context, req *pb.SendExtensionDataRequest) (*pb.ExtensionActionResult, error) { + extension, err := getExtension(req.GetExtensionId()) + if err != nil { + log.Println(err) + return &pb.ExtensionActionResult{ + ExtensionId: req.ExtensionId, + Code: pb.ResponseCode_FAILED, + Message: err.Error(), + }, err + } + (*extension).SubmitData(req.Button, req.GetData()) + + return &pb.ExtensionActionResult{ + ExtensionId: req.ExtensionId, + Code: pb.ResponseCode_OK, + Message: "Success", + }, nil +} + +func (e ExtensionHostService) Close(ctx context.Context, req *pb.ExtensionRequest) (*pb.ExtensionActionResult, error) { + extension, err := getExtension(req.GetExtensionId()) + if err != nil { + log.Println(err) + return &pb.ExtensionActionResult{ + ExtensionId: req.ExtensionId, + Code: pb.ResponseCode_FAILED, + Message: err.Error(), + }, err + } + (*extension).Close() + (*extension).StoreData() + return &pb.ExtensionActionResult{ + ExtensionId: req.ExtensionId, + Code: pb.ResponseCode_OK, + Message: "Success", + }, nil +} + +func (e ExtensionHostService) EditExtension(ctx context.Context, req *pb.EditExtensionRequest) (*pb.ExtensionActionResult, error) { + if !req.Enable { + extension, _ := getExtension(req.GetExtensionId()) + if extension != nil { + (*extension).Close() + (*extension).StoreData() + } + delete(enabledExtensionsMap, req.GetExtensionId()) + } + table := db.GetTable[extensionData]() + data, err := table.Get(req.GetExtensionId()) + if err != nil { + return nil, err + } + data.Enable = req.Enable + table.UpdateInsert(data) + + if req.Enable { + loadExtension(allExtensionsMap[req.GetExtensionId()]) + } + + return &pb.ExtensionActionResult{ + ExtensionId: req.ExtensionId, + Code: pb.ResponseCode_OK, + Message: "Success", + }, nil +} + +type extensionData struct { + Id string `json:"id"` + Enable bool `json:"enable"` + JsonData []byte +} diff --git a/libcore/extension/html/a.js b/libcore/extension/html/a.js new file mode 100644 index 0000000..c161e8c --- /dev/null +++ b/libcore/extension/html/a.js @@ -0,0 +1,12 @@ + +import * as a from "./rpc/extension_grpc_web_pb.js"; +const client = new ExtensionHostServiceClient('http://localhost:8080'); +const request = new GetHelloRequest(); +export const getHello = (name) => { + request.setName(name) +client.getHello(request, {}, (err, response) => { + console.log(request.getName()); + console.log(response.toObject()); + }); +} +getHello("D") \ No newline at end of file diff --git a/libcore/extension/html/index.html b/libcore/extension/html/index.html new file mode 100644 index 0000000..d201fb9 --- /dev/null +++ b/libcore/extension/html/index.html @@ -0,0 +1,82 @@ + + + + + + Hiddify Extensions + + + + + + + + +
+
+
+

Connection Settings

+ +
+ + +
+
+ + +
+ +
+ + +
+ +
+
+

Connecting...

+ +
+
+
+

+ Extension List +

+
+
+ +
+ +
+ +
+
+ +
+ + + + + + + + + \ No newline at end of file diff --git a/libcore/extension/html/rpc.js b/libcore/extension/html/rpc.js new file mode 100644 index 0000000..6d13d8b --- /dev/null +++ b/libcore/extension/html/rpc.js @@ -0,0 +1,10048 @@ +(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.HelloRequest.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.HelloRequest.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.HelloRequest} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.HelloRequest.toObject = function(includeInstance, msg) { + var f, obj = { +name: jspb.Message.getFieldWithDefault(msg, 1, "") + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.HelloRequest} + */ +proto.hiddifyrpc.HelloRequest.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.HelloRequest; + return proto.hiddifyrpc.HelloRequest.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.HelloRequest} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.HelloRequest} + */ +proto.hiddifyrpc.HelloRequest.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {string} */ (reader.readString()); + msg.setName(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.HelloRequest.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.HelloRequest.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.HelloRequest} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.HelloRequest.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getName(); + if (f.length > 0) { + writer.writeString( + 1, + f + ); + } +}; + + +/** + * optional string name = 1; + * @return {string} + */ +proto.hiddifyrpc.HelloRequest.prototype.getName = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.HelloRequest} returns this + */ +proto.hiddifyrpc.HelloRequest.prototype.setName = function(value) { + return jspb.Message.setProto3StringField(this, 1, value); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.HelloResponse.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.HelloResponse.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.HelloResponse} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.HelloResponse.toObject = function(includeInstance, msg) { + var f, obj = { +message: jspb.Message.getFieldWithDefault(msg, 1, "") + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.HelloResponse} + */ +proto.hiddifyrpc.HelloResponse.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.HelloResponse; + return proto.hiddifyrpc.HelloResponse.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.HelloResponse} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.HelloResponse} + */ +proto.hiddifyrpc.HelloResponse.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {string} */ (reader.readString()); + msg.setMessage(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.HelloResponse.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.HelloResponse.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.HelloResponse} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.HelloResponse.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getMessage(); + if (f.length > 0) { + writer.writeString( + 1, + f + ); + } +}; + + +/** + * optional string message = 1; + * @return {string} + */ +proto.hiddifyrpc.HelloResponse.prototype.getMessage = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.HelloResponse} returns this + */ +proto.hiddifyrpc.HelloResponse.prototype.setMessage = function(value) { + return jspb.Message.setProto3StringField(this, 1, value); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.Empty.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.Empty.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.Empty} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.Empty.toObject = function(includeInstance, msg) { + var f, obj = { + + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.Empty} + */ +proto.hiddifyrpc.Empty.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.Empty; + return proto.hiddifyrpc.Empty.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.Empty} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.Empty} + */ +proto.hiddifyrpc.Empty.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.Empty.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.Empty.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.Empty} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.Empty.serializeBinaryToWriter = function(message, writer) { + var f = undefined; +}; + + +/** + * @enum {number} + */ +proto.hiddifyrpc.ResponseCode = { + OK: 0, + FAILED: 1 +}; + +goog.object.extend(exports, proto.hiddifyrpc); + +},{"google-protobuf":12}],2:[function(require,module,exports){ +const hiddify = require("./hiddify_grpc_web_pb.js"); +const extension = require("./extension_grpc_web_pb.js"); + +const grpcServerAddress = '/'; +const extensionClient = new extension.ExtensionHostServicePromiseClient(grpcServerAddress, null, null); +const hiddifyClient = new hiddify.CorePromiseClient(grpcServerAddress, null, null); + +module.exports = { extensionClient ,hiddifyClient}; +},{"./extension_grpc_web_pb.js":7,"./hiddify_grpc_web_pb.js":10}],3:[function(require,module,exports){ +const { hiddifyClient } = require('./client.js'); +const hiddify = require("./hiddify_grpc_web_pb.js"); + +function openConnectionPage() { + + $("#extension-list-container").show(); + $("#extension-page-container").hide(); + $("#connection-page").show(); + connect(); + $("#connect-button").click(async () => { + const hsetting_request = new hiddify.ChangeHiddifySettingsRequest(); + hsetting_request.setHiddifySettingsJson($("#hiddify-settings").val()); + try{ + const hres=await hiddifyClient.changeHiddifySettings(hsetting_request, {}); + }catch(err){ + $("#hiddify-settings").val("") + console.log(err) + } + + const parse_request = new hiddify.ParseRequest(); + parse_request.setContent($("#config-content").val()); + try{ + const pres=await hiddifyClient.parse(parse_request, {}); + if (pres.getResponseCode() !== hiddify.ResponseCode.OK){ + alert(pres.getMessage()); + return + } + $("#config-content").val(pres.getContent()); + }catch(err){ + console.log(err) + alert(JSON.stringify(err)) + return + } + + const request = new hiddify.StartRequest(); + + request.setConfigContent($("#config-content").val()); + request.setEnableRawConfig(false); + try{ + const res=await hiddifyClient.start(request, {}); + console.log(res.getCoreState(),res.getMessage()) + handleCoreStatus(res.getCoreState()); + }catch(err){ + console.log(err) + alert(JSON.stringify(err)) + return + } + + + }) + + $("#disconnect-button").click(async () => { + const request = new hiddify.Empty(); + try{ + const res=await hiddifyClient.stop(request, {}); + console.log(res.getCoreState(),res.getMessage()) + handleCoreStatus(res.getCoreState()); + }catch(err){ + console.log(err) + alert(JSON.stringify(err)) + return + } + }) +} + + +function connect(){ + const request = new hiddify.Empty(); + const stream = hiddifyClient.coreInfoListener(request, {}); + stream.on('data', (response) => { + console.log('Receving ',response); + handleCoreStatus(response); + }); + + stream.on('error', (err) => { + console.error('Error opening extension page:', err); + // openExtensionPage(extensionId); + }); + + stream.on('end', () => { + console.log('Stream ended'); + setTimeout(connect, 1000); + + }); +} + + +function handleCoreStatus(status){ + if (status == hiddify.CoreState.STOPPED){ + $("#connection-before-connect").show(); + $("#connection-connecting").hide(); + }else{ + $("#connection-before-connect").hide(); + $("#connection-connecting").show(); + if (status == hiddify.CoreState.STARTING){ + $("#connection-status").text("Starting"); + $("#connection-status").css("color", "yellow"); + }else if (status == hiddify.CoreState.STOPPING){ + $("#connection-status").text("Stopping"); + $("#connection-status").css("color", "red"); + }else if (status == hiddify.CoreState.STARTED){ + $("#connection-status").text("Connected"); + $("#connection-status").css("color", "green"); + } + } +} + + +module.exports = { openConnectionPage }; +},{"./client.js":2,"./hiddify_grpc_web_pb.js":10}],4:[function(require,module,exports){ +const { listExtensions } = require('./extensionList.js'); +const { openConnectionPage } = require('./connectionPage.js'); +window.onload = () => { + listExtensions(); + openConnectionPage(); +}; + + + +},{"./connectionPage.js":3,"./extensionList.js":5}],5:[function(require,module,exports){ + +const { extensionClient } = require('./client.js'); +const extension = require("./extension_grpc_web_pb.js"); +async function listExtensions() { + $("#extension-list-container").show(); + $("#extension-page-container").hide(); + $("#connection-page").show(); + + try { + const extensionListContainer = document.getElementById('extension-list'); + extensionListContainer.innerHTML = ''; // Clear previous entries + const response = await extensionClient.listExtensions(new extension.Empty(), {}); + + const extensionList = response.getExtensionsList(); + extensionList.forEach(ext => { + const listItem = createExtensionListItem(ext); + extensionListContainer.appendChild(listItem); + }); + } catch (err) { + console.error('Error listing extensions:', err); + } +} + +function createExtensionListItem(ext) { + const listItem = document.createElement('li'); + listItem.className = 'list-group-item d-flex justify-content-between align-items-center'; + listItem.setAttribute('data-extension-id', ext.getId()); + + const contentDiv = document.createElement('div'); + + const titleElement = document.createElement('span'); + titleElement.innerHTML = `${ext.getTitle()}`; + contentDiv.appendChild(titleElement); + + const descriptionElement = document.createElement('p'); + descriptionElement.className = 'mb-0'; + descriptionElement.textContent = ext.getDescription(); + contentDiv.appendChild(descriptionElement); + contentDiv.style.width="100%"; + listItem.appendChild(contentDiv); + + const switchDiv = createSwitchElement(ext); + listItem.appendChild(switchDiv); + const {openExtensionPage} = require('./extensionPage.js'); + + contentDiv.addEventListener('click', () =>{ + if (!ext.getEnable() ){ + alert("Extension is not enabled") + return + } + openExtensionPage(ext.getId()) + }); + + return listItem; +} + +function createSwitchElement(ext) { + const switchDiv = document.createElement('div'); + switchDiv.className = 'form-check form-switch'; + + const switchButton = document.createElement('input'); + switchButton.type = 'checkbox'; + switchButton.className = 'form-check-input'; + switchButton.checked = ext.getEnable(); + switchButton.addEventListener('change', (e) => { + + toggleExtension(ext.getId(), switchButton.checked) + }); + + switchDiv.appendChild(switchButton); + return switchDiv; +} + +async function toggleExtension(extensionId, enable) { + const request = new extension.EditExtensionRequest(); + request.setExtensionId(extensionId); + request.setEnable(enable); + + try { + await extensionClient.editExtension(request, {}); + console.log(`Extension ${extensionId} updated to ${enable ? 'enabled' : 'disabled'}`); + } catch (err) { + console.error('Error updating extension status:', err); + } + listExtensions(); +} + + + +module.exports = { listExtensions }; +},{"./client.js":2,"./extensionPage.js":6,"./extension_grpc_web_pb.js":7}],6:[function(require,module,exports){ +const { extensionClient } = require('./client.js'); +const extension = require("./extension_grpc_web_pb.js"); + +const { renderForm } = require('./formRenderer.js'); +const { listExtensions } = require('./extensionList.js'); +var currentExtensionId = undefined; +function openExtensionPage(extensionId) { + currentExtensionId = extensionId; + $("#extension-list-container").hide(); + $("#extension-page-container").show(); + $("#connection-page").hide(); + connect() +} + +function connect() { + const request = new extension.ExtensionRequest(); + request.setExtensionId(currentExtensionId); + + const stream = extensionClient.connect(request, {}); + + stream.on('data', (response) => { + console.log('Receiving ', response); + if (response.getExtensionId() === currentExtensionId) { + ui = JSON.parse(response.getJsonUi()) + if (response.getType() == proto.hiddifyrpc.ExtensionResponseType.SHOW_DIALOG) { + renderForm(ui, "dialog", handleSubmitButtonClick, undefined); + } else { + renderForm(ui, "", handleSubmitButtonClick, handleStopButtonClick); + } + + + } + }); + + stream.on('error', (err) => { + console.error('Error opening extension page:', err); + // openExtensionPage(extensionId); + }); + + stream.on('end', () => { + console.log('Stream ended'); + setTimeout(connect, 1000); + + }); +} + +async function handleSubmitButtonClick(event, button) { + event.preventDefault(); + bootstrap.Modal.getOrCreateInstance("#extension-dialog").hide(); + const request = new extension.SendExtensionDataRequest(); + request.setButton(button); + if (event.type != 'hidden.bs.modal') { + const formData = new FormData(event.target.closest('form')); + const datamap = request.getDataMap() + formData.forEach((value, key) => { + datamap.set(key, value); + }); + } + request.setExtensionId(currentExtensionId); + + try { + await extensionClient.submitForm(request, {}); + console.log('Form submitted successfully.'); + } catch (err) { + console.error('Error submitting form:', err); + } +} + + +async function handleStopButtonClick(event) { + event.preventDefault(); + const request = new extension.ExtensionRequest(); + request.setExtensionId(currentExtensionId); + bootstrap.Modal.getOrCreateInstance("#extension-dialog").hide(); + try { + await extensionClient.close(request, {}); + console.log('Extension stopped successfully.'); + currentExtensionId = undefined; + listExtensions(); // Return to the extension list + } catch (err) { + console.error('Error stopping extension:', err); + } +} + + + +module.exports = { openExtensionPage }; +},{"./client.js":2,"./extensionList.js":5,"./extension_grpc_web_pb.js":7,"./formRenderer.js":9}],7:[function(require,module,exports){ +/** + * @fileoverview gRPC-Web generated client stub for hiddifyrpc + * @enhanceable + * @public + */ + +// Code generated by protoc-gen-grpc-web. DO NOT EDIT. +// versions: +// protoc-gen-grpc-web v1.5.0 +// protoc v5.28.0 +// source: extension.proto + + +/* eslint-disable */ +// @ts-nocheck + + + +const grpc = {}; +grpc.web = require('grpc-web'); + + +var base_pb = require('./base_pb.js') +const proto = {}; +proto.hiddifyrpc = require('./extension_pb.js'); + +/** + * @param {string} hostname + * @param {?Object} credentials + * @param {?grpc.web.ClientOptions} options + * @constructor + * @struct + * @final + */ +proto.hiddifyrpc.ExtensionHostServiceClient = + function(hostname, credentials, options) { + if (!options) options = {}; + options.format = 'text'; + + /** + * @private @const {!grpc.web.GrpcWebClientBase} The client + */ + this.client_ = new grpc.web.GrpcWebClientBase(options); + + /** + * @private @const {string} The hostname + */ + this.hostname_ = hostname.replace(/\/+$/, ''); + +}; + + +/** + * @param {string} hostname + * @param {?Object} credentials + * @param {?grpc.web.ClientOptions} options + * @constructor + * @struct + * @final + */ +proto.hiddifyrpc.ExtensionHostServicePromiseClient = + function(hostname, credentials, options) { + if (!options) options = {}; + options.format = 'text'; + + /** + * @private @const {!grpc.web.GrpcWebClientBase} The client + */ + this.client_ = new grpc.web.GrpcWebClientBase(options); + + /** + * @private @const {string} The hostname + */ + this.hostname_ = hostname.replace(/\/+$/, ''); + +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.Empty, + * !proto.hiddifyrpc.ExtensionList>} + */ +const methodDescriptor_ExtensionHostService_ListExtensions = new grpc.web.MethodDescriptor( + '/hiddifyrpc.ExtensionHostService/ListExtensions', + grpc.web.MethodType.UNARY, + base_pb.Empty, + proto.hiddifyrpc.ExtensionList, + /** + * @param {!proto.hiddifyrpc.Empty} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.ExtensionList.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.Empty} request The + * request proto + * @param {?Object} metadata User defined + * call metadata + * @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.ExtensionList)} + * callback The callback function(error, response) + * @return {!grpc.web.ClientReadableStream|undefined} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.ExtensionHostServiceClient.prototype.listExtensions = + function(request, metadata, callback) { + return this.client_.rpcCall(this.hostname_ + + '/hiddifyrpc.ExtensionHostService/ListExtensions', + request, + metadata || {}, + methodDescriptor_ExtensionHostService_ListExtensions, + callback); +}; + + +/** + * @param {!proto.hiddifyrpc.Empty} request The + * request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!Promise} + * Promise that resolves to the response + */ +proto.hiddifyrpc.ExtensionHostServicePromiseClient.prototype.listExtensions = + function(request, metadata) { + return this.client_.unaryCall(this.hostname_ + + '/hiddifyrpc.ExtensionHostService/ListExtensions', + request, + metadata || {}, + methodDescriptor_ExtensionHostService_ListExtensions); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.ExtensionRequest, + * !proto.hiddifyrpc.ExtensionResponse>} + */ +const methodDescriptor_ExtensionHostService_Connect = new grpc.web.MethodDescriptor( + '/hiddifyrpc.ExtensionHostService/Connect', + grpc.web.MethodType.SERVER_STREAMING, + proto.hiddifyrpc.ExtensionRequest, + proto.hiddifyrpc.ExtensionResponse, + /** + * @param {!proto.hiddifyrpc.ExtensionRequest} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.ExtensionResponse.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.ExtensionRequest} request The request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!grpc.web.ClientReadableStream} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.ExtensionHostServiceClient.prototype.connect = + function(request, metadata) { + return this.client_.serverStreaming(this.hostname_ + + '/hiddifyrpc.ExtensionHostService/Connect', + request, + metadata || {}, + methodDescriptor_ExtensionHostService_Connect); +}; + + +/** + * @param {!proto.hiddifyrpc.ExtensionRequest} request The request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!grpc.web.ClientReadableStream} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.ExtensionHostServicePromiseClient.prototype.connect = + function(request, metadata) { + return this.client_.serverStreaming(this.hostname_ + + '/hiddifyrpc.ExtensionHostService/Connect', + request, + metadata || {}, + methodDescriptor_ExtensionHostService_Connect); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.EditExtensionRequest, + * !proto.hiddifyrpc.ExtensionActionResult>} + */ +const methodDescriptor_ExtensionHostService_EditExtension = new grpc.web.MethodDescriptor( + '/hiddifyrpc.ExtensionHostService/EditExtension', + grpc.web.MethodType.UNARY, + proto.hiddifyrpc.EditExtensionRequest, + proto.hiddifyrpc.ExtensionActionResult, + /** + * @param {!proto.hiddifyrpc.EditExtensionRequest} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.ExtensionActionResult.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.EditExtensionRequest} request The + * request proto + * @param {?Object} metadata User defined + * call metadata + * @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.ExtensionActionResult)} + * callback The callback function(error, response) + * @return {!grpc.web.ClientReadableStream|undefined} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.ExtensionHostServiceClient.prototype.editExtension = + function(request, metadata, callback) { + return this.client_.rpcCall(this.hostname_ + + '/hiddifyrpc.ExtensionHostService/EditExtension', + request, + metadata || {}, + methodDescriptor_ExtensionHostService_EditExtension, + callback); +}; + + +/** + * @param {!proto.hiddifyrpc.EditExtensionRequest} request The + * request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!Promise} + * Promise that resolves to the response + */ +proto.hiddifyrpc.ExtensionHostServicePromiseClient.prototype.editExtension = + function(request, metadata) { + return this.client_.unaryCall(this.hostname_ + + '/hiddifyrpc.ExtensionHostService/EditExtension', + request, + metadata || {}, + methodDescriptor_ExtensionHostService_EditExtension); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.SendExtensionDataRequest, + * !proto.hiddifyrpc.ExtensionActionResult>} + */ +const methodDescriptor_ExtensionHostService_SubmitForm = new grpc.web.MethodDescriptor( + '/hiddifyrpc.ExtensionHostService/SubmitForm', + grpc.web.MethodType.UNARY, + proto.hiddifyrpc.SendExtensionDataRequest, + proto.hiddifyrpc.ExtensionActionResult, + /** + * @param {!proto.hiddifyrpc.SendExtensionDataRequest} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.ExtensionActionResult.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.SendExtensionDataRequest} request The + * request proto + * @param {?Object} metadata User defined + * call metadata + * @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.ExtensionActionResult)} + * callback The callback function(error, response) + * @return {!grpc.web.ClientReadableStream|undefined} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.ExtensionHostServiceClient.prototype.submitForm = + function(request, metadata, callback) { + return this.client_.rpcCall(this.hostname_ + + '/hiddifyrpc.ExtensionHostService/SubmitForm', + request, + metadata || {}, + methodDescriptor_ExtensionHostService_SubmitForm, + callback); +}; + + +/** + * @param {!proto.hiddifyrpc.SendExtensionDataRequest} request The + * request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!Promise} + * Promise that resolves to the response + */ +proto.hiddifyrpc.ExtensionHostServicePromiseClient.prototype.submitForm = + function(request, metadata) { + return this.client_.unaryCall(this.hostname_ + + '/hiddifyrpc.ExtensionHostService/SubmitForm', + request, + metadata || {}, + methodDescriptor_ExtensionHostService_SubmitForm); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.ExtensionRequest, + * !proto.hiddifyrpc.ExtensionActionResult>} + */ +const methodDescriptor_ExtensionHostService_Close = new grpc.web.MethodDescriptor( + '/hiddifyrpc.ExtensionHostService/Close', + grpc.web.MethodType.UNARY, + proto.hiddifyrpc.ExtensionRequest, + proto.hiddifyrpc.ExtensionActionResult, + /** + * @param {!proto.hiddifyrpc.ExtensionRequest} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.ExtensionActionResult.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.ExtensionRequest} request The + * request proto + * @param {?Object} metadata User defined + * call metadata + * @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.ExtensionActionResult)} + * callback The callback function(error, response) + * @return {!grpc.web.ClientReadableStream|undefined} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.ExtensionHostServiceClient.prototype.close = + function(request, metadata, callback) { + return this.client_.rpcCall(this.hostname_ + + '/hiddifyrpc.ExtensionHostService/Close', + request, + metadata || {}, + methodDescriptor_ExtensionHostService_Close, + callback); +}; + + +/** + * @param {!proto.hiddifyrpc.ExtensionRequest} request The + * request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!Promise} + * Promise that resolves to the response + */ +proto.hiddifyrpc.ExtensionHostServicePromiseClient.prototype.close = + function(request, metadata) { + return this.client_.unaryCall(this.hostname_ + + '/hiddifyrpc.ExtensionHostService/Close', + request, + metadata || {}, + methodDescriptor_ExtensionHostService_Close); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.ExtensionRequest, + * !proto.hiddifyrpc.ExtensionActionResult>} + */ +const methodDescriptor_ExtensionHostService_GetUI = new grpc.web.MethodDescriptor( + '/hiddifyrpc.ExtensionHostService/GetUI', + grpc.web.MethodType.UNARY, + proto.hiddifyrpc.ExtensionRequest, + proto.hiddifyrpc.ExtensionActionResult, + /** + * @param {!proto.hiddifyrpc.ExtensionRequest} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.ExtensionActionResult.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.ExtensionRequest} request The + * request proto + * @param {?Object} metadata User defined + * call metadata + * @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.ExtensionActionResult)} + * callback The callback function(error, response) + * @return {!grpc.web.ClientReadableStream|undefined} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.ExtensionHostServiceClient.prototype.getUI = + function(request, metadata, callback) { + return this.client_.rpcCall(this.hostname_ + + '/hiddifyrpc.ExtensionHostService/GetUI', + request, + metadata || {}, + methodDescriptor_ExtensionHostService_GetUI, + callback); +}; + + +/** + * @param {!proto.hiddifyrpc.ExtensionRequest} request The + * request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!Promise} + * Promise that resolves to the response + */ +proto.hiddifyrpc.ExtensionHostServicePromiseClient.prototype.getUI = + function(request, metadata) { + return this.client_.unaryCall(this.hostname_ + + '/hiddifyrpc.ExtensionHostService/GetUI', + request, + metadata || {}, + methodDescriptor_ExtensionHostService_GetUI); +}; + + +module.exports = proto.hiddifyrpc; + + +},{"./base_pb.js":1,"./extension_pb.js":8,"grpc-web":13}],8:[function(require,module,exports){ +// source: extension.proto +/** + * @fileoverview + * @enhanceable + * @suppress {missingRequire} reports error on implicit type usages. + * @suppress {messageConventions} JS Compiler reports an error if a variable or + * field starts with 'MSG_' and isn't a translatable message. + * @public + */ +// GENERATED CODE -- DO NOT EDIT! +/* eslint-disable */ +// @ts-nocheck + +var jspb = require('google-protobuf'); +var goog = jspb; +var global = + (typeof globalThis !== 'undefined' && globalThis) || + (typeof window !== 'undefined' && window) || + (typeof global !== 'undefined' && global) || + (typeof self !== 'undefined' && self) || + (function () { return this; }).call(null) || + Function('return this')(); + +var base_pb = require('./base_pb.js'); +goog.object.extend(proto, base_pb); +goog.exportSymbol('proto.hiddifyrpc.EditExtensionRequest', null, global); +goog.exportSymbol('proto.hiddifyrpc.Extension', null, global); +goog.exportSymbol('proto.hiddifyrpc.ExtensionActionResult', null, global); +goog.exportSymbol('proto.hiddifyrpc.ExtensionList', null, global); +goog.exportSymbol('proto.hiddifyrpc.ExtensionRequest', null, global); +goog.exportSymbol('proto.hiddifyrpc.ExtensionResponse', null, global); +goog.exportSymbol('proto.hiddifyrpc.ExtensionResponseType', null, global); +goog.exportSymbol('proto.hiddifyrpc.SendExtensionDataRequest', null, global); +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.ExtensionActionResult = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.ExtensionActionResult, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.ExtensionActionResult.displayName = 'proto.hiddifyrpc.ExtensionActionResult'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.ExtensionList = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, proto.hiddifyrpc.ExtensionList.repeatedFields_, null); +}; +goog.inherits(proto.hiddifyrpc.ExtensionList, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.ExtensionList.displayName = 'proto.hiddifyrpc.ExtensionList'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.EditExtensionRequest = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.EditExtensionRequest, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.EditExtensionRequest.displayName = 'proto.hiddifyrpc.EditExtensionRequest'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.Extension = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.Extension, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.Extension.displayName = 'proto.hiddifyrpc.Extension'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.ExtensionRequest = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.ExtensionRequest, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.ExtensionRequest.displayName = 'proto.hiddifyrpc.ExtensionRequest'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.SendExtensionDataRequest = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.SendExtensionDataRequest, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.SendExtensionDataRequest.displayName = 'proto.hiddifyrpc.SendExtensionDataRequest'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.ExtensionResponse = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.ExtensionResponse, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.ExtensionResponse.displayName = 'proto.hiddifyrpc.ExtensionResponse'; +} + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.ExtensionActionResult.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.ExtensionActionResult.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.ExtensionActionResult} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.ExtensionActionResult.toObject = function(includeInstance, msg) { + var f, obj = { +extensionId: jspb.Message.getFieldWithDefault(msg, 1, ""), +code: jspb.Message.getFieldWithDefault(msg, 2, 0), +message: jspb.Message.getFieldWithDefault(msg, 3, "") + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.ExtensionActionResult} + */ +proto.hiddifyrpc.ExtensionActionResult.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.ExtensionActionResult; + return proto.hiddifyrpc.ExtensionActionResult.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.ExtensionActionResult} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.ExtensionActionResult} + */ +proto.hiddifyrpc.ExtensionActionResult.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {string} */ (reader.readString()); + msg.setExtensionId(value); + break; + case 2: + var value = /** @type {!proto.hiddifyrpc.ResponseCode} */ (reader.readEnum()); + msg.setCode(value); + break; + case 3: + var value = /** @type {string} */ (reader.readString()); + msg.setMessage(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.ExtensionActionResult.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.ExtensionActionResult.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.ExtensionActionResult} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.ExtensionActionResult.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getExtensionId(); + if (f.length > 0) { + writer.writeString( + 1, + f + ); + } + f = message.getCode(); + if (f !== 0.0) { + writer.writeEnum( + 2, + f + ); + } + f = message.getMessage(); + if (f.length > 0) { + writer.writeString( + 3, + f + ); + } +}; + + +/** + * optional string extension_id = 1; + * @return {string} + */ +proto.hiddifyrpc.ExtensionActionResult.prototype.getExtensionId = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.ExtensionActionResult} returns this + */ +proto.hiddifyrpc.ExtensionActionResult.prototype.setExtensionId = function(value) { + return jspb.Message.setProto3StringField(this, 1, value); +}; + + +/** + * optional ResponseCode code = 2; + * @return {!proto.hiddifyrpc.ResponseCode} + */ +proto.hiddifyrpc.ExtensionActionResult.prototype.getCode = function() { + return /** @type {!proto.hiddifyrpc.ResponseCode} */ (jspb.Message.getFieldWithDefault(this, 2, 0)); +}; + + +/** + * @param {!proto.hiddifyrpc.ResponseCode} value + * @return {!proto.hiddifyrpc.ExtensionActionResult} returns this + */ +proto.hiddifyrpc.ExtensionActionResult.prototype.setCode = function(value) { + return jspb.Message.setProto3EnumField(this, 2, value); +}; + + +/** + * optional string message = 3; + * @return {string} + */ +proto.hiddifyrpc.ExtensionActionResult.prototype.getMessage = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.ExtensionActionResult} returns this + */ +proto.hiddifyrpc.ExtensionActionResult.prototype.setMessage = function(value) { + return jspb.Message.setProto3StringField(this, 3, value); +}; + + + +/** + * List of repeated fields within this message type. + * @private {!Array} + * @const + */ +proto.hiddifyrpc.ExtensionList.repeatedFields_ = [1]; + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.ExtensionList.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.ExtensionList.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.ExtensionList} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.ExtensionList.toObject = function(includeInstance, msg) { + var f, obj = { +extensionsList: jspb.Message.toObjectList(msg.getExtensionsList(), + proto.hiddifyrpc.Extension.toObject, includeInstance) + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.ExtensionList} + */ +proto.hiddifyrpc.ExtensionList.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.ExtensionList; + return proto.hiddifyrpc.ExtensionList.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.ExtensionList} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.ExtensionList} + */ +proto.hiddifyrpc.ExtensionList.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = new proto.hiddifyrpc.Extension; + reader.readMessage(value,proto.hiddifyrpc.Extension.deserializeBinaryFromReader); + msg.addExtensions(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.ExtensionList.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.ExtensionList.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.ExtensionList} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.ExtensionList.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getExtensionsList(); + if (f.length > 0) { + writer.writeRepeatedMessage( + 1, + f, + proto.hiddifyrpc.Extension.serializeBinaryToWriter + ); + } +}; + + +/** + * repeated Extension extensions = 1; + * @return {!Array} + */ +proto.hiddifyrpc.ExtensionList.prototype.getExtensionsList = function() { + return /** @type{!Array} */ ( + jspb.Message.getRepeatedWrapperField(this, proto.hiddifyrpc.Extension, 1)); +}; + + +/** + * @param {!Array} value + * @return {!proto.hiddifyrpc.ExtensionList} returns this +*/ +proto.hiddifyrpc.ExtensionList.prototype.setExtensionsList = function(value) { + return jspb.Message.setRepeatedWrapperField(this, 1, value); +}; + + +/** + * @param {!proto.hiddifyrpc.Extension=} opt_value + * @param {number=} opt_index + * @return {!proto.hiddifyrpc.Extension} + */ +proto.hiddifyrpc.ExtensionList.prototype.addExtensions = function(opt_value, opt_index) { + return jspb.Message.addToRepeatedWrapperField(this, 1, opt_value, proto.hiddifyrpc.Extension, opt_index); +}; + + +/** + * Clears the list making it empty but non-null. + * @return {!proto.hiddifyrpc.ExtensionList} returns this + */ +proto.hiddifyrpc.ExtensionList.prototype.clearExtensionsList = function() { + return this.setExtensionsList([]); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.EditExtensionRequest.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.EditExtensionRequest.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.EditExtensionRequest} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.EditExtensionRequest.toObject = function(includeInstance, msg) { + var f, obj = { +extensionId: jspb.Message.getFieldWithDefault(msg, 1, ""), +enable: jspb.Message.getBooleanFieldWithDefault(msg, 2, false) + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.EditExtensionRequest} + */ +proto.hiddifyrpc.EditExtensionRequest.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.EditExtensionRequest; + return proto.hiddifyrpc.EditExtensionRequest.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.EditExtensionRequest} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.EditExtensionRequest} + */ +proto.hiddifyrpc.EditExtensionRequest.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {string} */ (reader.readString()); + msg.setExtensionId(value); + break; + case 2: + var value = /** @type {boolean} */ (reader.readBool()); + msg.setEnable(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.EditExtensionRequest.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.EditExtensionRequest.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.EditExtensionRequest} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.EditExtensionRequest.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getExtensionId(); + if (f.length > 0) { + writer.writeString( + 1, + f + ); + } + f = message.getEnable(); + if (f) { + writer.writeBool( + 2, + f + ); + } +}; + + +/** + * optional string extension_id = 1; + * @return {string} + */ +proto.hiddifyrpc.EditExtensionRequest.prototype.getExtensionId = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.EditExtensionRequest} returns this + */ +proto.hiddifyrpc.EditExtensionRequest.prototype.setExtensionId = function(value) { + return jspb.Message.setProto3StringField(this, 1, value); +}; + + +/** + * optional bool enable = 2; + * @return {boolean} + */ +proto.hiddifyrpc.EditExtensionRequest.prototype.getEnable = function() { + return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 2, false)); +}; + + +/** + * @param {boolean} value + * @return {!proto.hiddifyrpc.EditExtensionRequest} returns this + */ +proto.hiddifyrpc.EditExtensionRequest.prototype.setEnable = function(value) { + return jspb.Message.setProto3BooleanField(this, 2, value); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.Extension.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.Extension.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.Extension} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.Extension.toObject = function(includeInstance, msg) { + var f, obj = { +id: jspb.Message.getFieldWithDefault(msg, 1, ""), +title: jspb.Message.getFieldWithDefault(msg, 2, ""), +description: jspb.Message.getFieldWithDefault(msg, 3, ""), +enable: jspb.Message.getBooleanFieldWithDefault(msg, 4, false) + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.Extension} + */ +proto.hiddifyrpc.Extension.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.Extension; + return proto.hiddifyrpc.Extension.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.Extension} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.Extension} + */ +proto.hiddifyrpc.Extension.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {string} */ (reader.readString()); + msg.setId(value); + break; + case 2: + var value = /** @type {string} */ (reader.readString()); + msg.setTitle(value); + break; + case 3: + var value = /** @type {string} */ (reader.readString()); + msg.setDescription(value); + break; + case 4: + var value = /** @type {boolean} */ (reader.readBool()); + msg.setEnable(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.Extension.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.Extension.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.Extension} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.Extension.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getId(); + if (f.length > 0) { + writer.writeString( + 1, + f + ); + } + f = message.getTitle(); + if (f.length > 0) { + writer.writeString( + 2, + f + ); + } + f = message.getDescription(); + if (f.length > 0) { + writer.writeString( + 3, + f + ); + } + f = message.getEnable(); + if (f) { + writer.writeBool( + 4, + f + ); + } +}; + + +/** + * optional string id = 1; + * @return {string} + */ +proto.hiddifyrpc.Extension.prototype.getId = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.Extension} returns this + */ +proto.hiddifyrpc.Extension.prototype.setId = function(value) { + return jspb.Message.setProto3StringField(this, 1, value); +}; + + +/** + * optional string title = 2; + * @return {string} + */ +proto.hiddifyrpc.Extension.prototype.getTitle = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.Extension} returns this + */ +proto.hiddifyrpc.Extension.prototype.setTitle = function(value) { + return jspb.Message.setProto3StringField(this, 2, value); +}; + + +/** + * optional string description = 3; + * @return {string} + */ +proto.hiddifyrpc.Extension.prototype.getDescription = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.Extension} returns this + */ +proto.hiddifyrpc.Extension.prototype.setDescription = function(value) { + return jspb.Message.setProto3StringField(this, 3, value); +}; + + +/** + * optional bool enable = 4; + * @return {boolean} + */ +proto.hiddifyrpc.Extension.prototype.getEnable = function() { + return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 4, false)); +}; + + +/** + * @param {boolean} value + * @return {!proto.hiddifyrpc.Extension} returns this + */ +proto.hiddifyrpc.Extension.prototype.setEnable = function(value) { + return jspb.Message.setProto3BooleanField(this, 4, value); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.ExtensionRequest.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.ExtensionRequest.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.ExtensionRequest} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.ExtensionRequest.toObject = function(includeInstance, msg) { + var f, obj = { +extensionId: jspb.Message.getFieldWithDefault(msg, 1, ""), +dataMap: (f = msg.getDataMap()) ? f.toObject(includeInstance, undefined) : [] + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.ExtensionRequest} + */ +proto.hiddifyrpc.ExtensionRequest.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.ExtensionRequest; + return proto.hiddifyrpc.ExtensionRequest.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.ExtensionRequest} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.ExtensionRequest} + */ +proto.hiddifyrpc.ExtensionRequest.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {string} */ (reader.readString()); + msg.setExtensionId(value); + break; + case 2: + var value = msg.getDataMap(); + reader.readMessage(value, function(message, reader) { + jspb.Map.deserializeBinary(message, reader, jspb.BinaryReader.prototype.readString, jspb.BinaryReader.prototype.readString, null, "", ""); + }); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.ExtensionRequest.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.ExtensionRequest.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.ExtensionRequest} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.ExtensionRequest.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getExtensionId(); + if (f.length > 0) { + writer.writeString( + 1, + f + ); + } + f = message.getDataMap(true); + if (f && f.getLength() > 0) { + f.serializeBinary(2, writer, jspb.BinaryWriter.prototype.writeString, jspb.BinaryWriter.prototype.writeString); + } +}; + + +/** + * optional string extension_id = 1; + * @return {string} + */ +proto.hiddifyrpc.ExtensionRequest.prototype.getExtensionId = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.ExtensionRequest} returns this + */ +proto.hiddifyrpc.ExtensionRequest.prototype.setExtensionId = function(value) { + return jspb.Message.setProto3StringField(this, 1, value); +}; + + +/** + * map data = 2; + * @param {boolean=} opt_noLazyCreate Do not create the map if + * empty, instead returning `undefined` + * @return {!jspb.Map} + */ +proto.hiddifyrpc.ExtensionRequest.prototype.getDataMap = function(opt_noLazyCreate) { + return /** @type {!jspb.Map} */ ( + jspb.Message.getMapField(this, 2, opt_noLazyCreate, + null)); +}; + + +/** + * Clears values from the map. The map will be non-null. + * @return {!proto.hiddifyrpc.ExtensionRequest} returns this + */ +proto.hiddifyrpc.ExtensionRequest.prototype.clearDataMap = function() { + this.getDataMap().clear(); + return this; +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.SendExtensionDataRequest.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.SendExtensionDataRequest.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.SendExtensionDataRequest} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.SendExtensionDataRequest.toObject = function(includeInstance, msg) { + var f, obj = { +extensionId: jspb.Message.getFieldWithDefault(msg, 1, ""), +button: jspb.Message.getFieldWithDefault(msg, 2, ""), +dataMap: (f = msg.getDataMap()) ? f.toObject(includeInstance, undefined) : [] + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.SendExtensionDataRequest} + */ +proto.hiddifyrpc.SendExtensionDataRequest.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.SendExtensionDataRequest; + return proto.hiddifyrpc.SendExtensionDataRequest.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.SendExtensionDataRequest} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.SendExtensionDataRequest} + */ +proto.hiddifyrpc.SendExtensionDataRequest.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {string} */ (reader.readString()); + msg.setExtensionId(value); + break; + case 2: + var value = /** @type {string} */ (reader.readString()); + msg.setButton(value); + break; + case 3: + var value = msg.getDataMap(); + reader.readMessage(value, function(message, reader) { + jspb.Map.deserializeBinary(message, reader, jspb.BinaryReader.prototype.readString, jspb.BinaryReader.prototype.readString, null, "", ""); + }); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.SendExtensionDataRequest.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.SendExtensionDataRequest.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.SendExtensionDataRequest} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.SendExtensionDataRequest.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getExtensionId(); + if (f.length > 0) { + writer.writeString( + 1, + f + ); + } + f = message.getButton(); + if (f.length > 0) { + writer.writeString( + 2, + f + ); + } + f = message.getDataMap(true); + if (f && f.getLength() > 0) { + f.serializeBinary(3, writer, jspb.BinaryWriter.prototype.writeString, jspb.BinaryWriter.prototype.writeString); + } +}; + + +/** + * optional string extension_id = 1; + * @return {string} + */ +proto.hiddifyrpc.SendExtensionDataRequest.prototype.getExtensionId = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.SendExtensionDataRequest} returns this + */ +proto.hiddifyrpc.SendExtensionDataRequest.prototype.setExtensionId = function(value) { + return jspb.Message.setProto3StringField(this, 1, value); +}; + + +/** + * optional string button = 2; + * @return {string} + */ +proto.hiddifyrpc.SendExtensionDataRequest.prototype.getButton = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.SendExtensionDataRequest} returns this + */ +proto.hiddifyrpc.SendExtensionDataRequest.prototype.setButton = function(value) { + return jspb.Message.setProto3StringField(this, 2, value); +}; + + +/** + * map data = 3; + * @param {boolean=} opt_noLazyCreate Do not create the map if + * empty, instead returning `undefined` + * @return {!jspb.Map} + */ +proto.hiddifyrpc.SendExtensionDataRequest.prototype.getDataMap = function(opt_noLazyCreate) { + return /** @type {!jspb.Map} */ ( + jspb.Message.getMapField(this, 3, opt_noLazyCreate, + null)); +}; + + +/** + * Clears values from the map. The map will be non-null. + * @return {!proto.hiddifyrpc.SendExtensionDataRequest} returns this + */ +proto.hiddifyrpc.SendExtensionDataRequest.prototype.clearDataMap = function() { + this.getDataMap().clear(); + return this; +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.ExtensionResponse.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.ExtensionResponse.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.ExtensionResponse} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.ExtensionResponse.toObject = function(includeInstance, msg) { + var f, obj = { +type: jspb.Message.getFieldWithDefault(msg, 1, 0), +extensionId: jspb.Message.getFieldWithDefault(msg, 2, ""), +jsonUi: jspb.Message.getFieldWithDefault(msg, 3, "") + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.ExtensionResponse} + */ +proto.hiddifyrpc.ExtensionResponse.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.ExtensionResponse; + return proto.hiddifyrpc.ExtensionResponse.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.ExtensionResponse} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.ExtensionResponse} + */ +proto.hiddifyrpc.ExtensionResponse.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {!proto.hiddifyrpc.ExtensionResponseType} */ (reader.readEnum()); + msg.setType(value); + break; + case 2: + var value = /** @type {string} */ (reader.readString()); + msg.setExtensionId(value); + break; + case 3: + var value = /** @type {string} */ (reader.readString()); + msg.setJsonUi(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.ExtensionResponse.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.ExtensionResponse.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.ExtensionResponse} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.ExtensionResponse.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getType(); + if (f !== 0.0) { + writer.writeEnum( + 1, + f + ); + } + f = message.getExtensionId(); + if (f.length > 0) { + writer.writeString( + 2, + f + ); + } + f = message.getJsonUi(); + if (f.length > 0) { + writer.writeString( + 3, + f + ); + } +}; + + +/** + * optional ExtensionResponseType type = 1; + * @return {!proto.hiddifyrpc.ExtensionResponseType} + */ +proto.hiddifyrpc.ExtensionResponse.prototype.getType = function() { + return /** @type {!proto.hiddifyrpc.ExtensionResponseType} */ (jspb.Message.getFieldWithDefault(this, 1, 0)); +}; + + +/** + * @param {!proto.hiddifyrpc.ExtensionResponseType} value + * @return {!proto.hiddifyrpc.ExtensionResponse} returns this + */ +proto.hiddifyrpc.ExtensionResponse.prototype.setType = function(value) { + return jspb.Message.setProto3EnumField(this, 1, value); +}; + + +/** + * optional string extension_id = 2; + * @return {string} + */ +proto.hiddifyrpc.ExtensionResponse.prototype.getExtensionId = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.ExtensionResponse} returns this + */ +proto.hiddifyrpc.ExtensionResponse.prototype.setExtensionId = function(value) { + return jspb.Message.setProto3StringField(this, 2, value); +}; + + +/** + * optional string json_ui = 3; + * @return {string} + */ +proto.hiddifyrpc.ExtensionResponse.prototype.getJsonUi = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.ExtensionResponse} returns this + */ +proto.hiddifyrpc.ExtensionResponse.prototype.setJsonUi = function(value) { + return jspb.Message.setProto3StringField(this, 3, value); +}; + + +/** + * @enum {number} + */ +proto.hiddifyrpc.ExtensionResponseType = { + NOTHING: 0, + UPDATE_UI: 1, + SHOW_DIALOG: 2, + END: 3 +}; + +goog.object.extend(exports, proto.hiddifyrpc); + +},{"./base_pb.js":1,"google-protobuf":12}],9:[function(require,module,exports){ + +const ansi_up = new AnsiUp({ + escape_html: false, + +}); + + +function renderForm(json, dialog, submitAction, stopAction) { + const container = document.getElementById(`extension-page-container${dialog}`); + const formId = `dynamicForm${json.id}${dialog}`; + + const existingForm = document.getElementById(formId); + if (existingForm) { + existingForm.remove(); + } + const form = document.createElement('form'); + container.appendChild(form); + form.id = formId; + + if (dialog === "dialog") { + document.getElementById("modalLabel").textContent = json.title; + } else { + const titleElement = createTitleElement(json); + const stopBtn = document.createElement('button'); + stopBtn.type = 'button'; + stopBtn.className = 'btn btn-danger'; + stopBtn.textContent = 'Close'; + stopBtn.addEventListener('click', stopAction); + form.appendChild(stopBtn); + form.appendChild(titleElement); + } + addElementsToForm(form, json,submitAction); + + if (dialog === "dialog") { + document.getElementById("modal-footer").innerHTML = ''; + // if ($(form.lastChild).find("button").length > 0) { + + // document.getElementById("modal-footer").appendChild(form.lastChild); + + // } + const extensionDialog = document.getElementById("extension-dialog"); + const dialog = bootstrap.Modal.getOrCreateInstance(extensionDialog); + dialog.show(); + extensionDialog.addEventListener("hidden.bs.modal", (e)=>submitAction(e,"CloseDialog")); + } + +} + +function addElementsToForm(form, json,submitAction) { + + + + const description = document.createElement('p'); + description.textContent = json.description; + form.appendChild(description); + if (json.fields) { + json.fields.forEach(field => { + div=document.createElement("div") + div.classList.add("row") + form.appendChild(div) + for (let i = 0; i < field.length; i++) { + const formGroup = createFormGroup(field[i], submitAction); + formGroup.classList.add("col") + div.appendChild(formGroup); + } + }); + } + + return form; +} + +function createTitleElement(json) { + const title = document.createElement('h1'); + title.textContent = json.title; + return title; +} + +function createFormGroup(field, submitAction) { + const formGroup = document.createElement('div'); + formGroup.classList.add('mb-3'); + if (field.type == "Button") { + const button = document.createElement('button'); + button.textContent = field.label; + button.name=field.key + button.classList.add('btn'); + if (field.key == "Submit") { + button.classList.add('btn-primary'); + } else if (field.key == "Cancel") { + button.classList.add('btn-secondary'); + }else{ + button.classList.add('btn', 'btn-outline-secondary'); + } + + button.addEventListener('click', (e) => submitAction(e,field.key)); + formGroup.appendChild(button); + } else { + if (field.label && !field.labelHidden) { + const label = document.createElement('label'); + label.textContent = field.label; + label.setAttribute('for', field.key); + formGroup.appendChild(label); + } + + const input = createInputElement(field); + formGroup.appendChild(input); + } + return formGroup; +} + +function createInputElement(field) { + let input; + + switch (field.type) { + case "Console": + input = document.createElement('pre'); + input.innerHTML = ansi_up.ansi_to_html(field.value || field.placeholder || ''); + input.style.maxHeight = field.lines * 20 + 'px'; + break; + case "TextArea": + input = document.createElement('textarea'); + input.rows = field.lines || 3; + input.textContent = field.value || ''; + break; + + case "Checkbox": + case "RadioButton": + input = createCheckboxOrRadioGroup(field); + break; + + case "Switch": + input = createSwitchElement(field); + break; + + case "Select": + input = document.createElement('select'); + field.items.forEach(item => { + const option = document.createElement('option'); + option.value = item.value; + option.text = item.label; + input.appendChild(option); + }); + break; + + default: + input = document.createElement('input'); + input.type = field.type.toLowerCase(); + input.value = field.value; + break; + } + + input.id = field.key; + input.name = field.key; + if (field.readOnly) input.readOnly = true; + if (field.type == "Checkbox" || field.type == "RadioButton" || field.type == "Switch") { + + } else { + if (field.required) input.required = true; + input.classList.add('form-control'); + if (field.placeholder) input.placeholder = field.placeholder; + } + return input; +} + +function createCheckboxOrRadioGroup(field) { + const wrapper = document.createDocumentFragment(); + + field.items.forEach(item => { + const inputWrapper = document.createElement('div'); + inputWrapper.classList.add('form-check'); + + const input = document.createElement('input'); + input.type = field.type === "Checkbox" ? 'checkbox' : 'radio'; + input.classList.add('form-check-input'); + input.id = `${field.key}_${item.value}`; + input.name = field.key; // Grouping by name for radio buttons + input.value = item.value; + input.checked = field.value === item.value; + + const itemLabel = document.createElement('label'); + itemLabel.classList.add('form-check-label'); + itemLabel.setAttribute('for', input.id); + itemLabel.textContent = item.label; + + inputWrapper.appendChild(input); + inputWrapper.appendChild(itemLabel); + wrapper.appendChild(inputWrapper); + }); + + return wrapper; +} + +function createSwitchElement(field) { + const switchWrapper = document.createElement('div'); + switchWrapper.classList.add('form-check', 'form-switch'); + + const input = document.createElement('input'); + input.type = 'checkbox'; + input.classList.add('form-check-input'); + input.setAttribute('role', 'switch'); + input.id = field.key; + input.checked = field.value === "true"; + + const label = document.createElement('label'); + label.classList.add('form-check-label'); + label.setAttribute('for', field.key); + label.textContent = field.label; + + switchWrapper.appendChild(input); + switchWrapper.appendChild(label); + + return switchWrapper; +} + +function createButtonGroup(json, submitAction, cancelAction) { + const buttonGroup = document.createElement('div'); + buttonGroup.classList.add('btn-group'); + json.buttons.forEach(buttonText => { + const btn = document.createElement('button'); + btn.classList.add('btn', "btn-default"); + buttonGroup.appendChild(btn); + btn.textContent = buttonText + if (buttonText == "Cancel") { + btn.classList.add('btn-secondary'); + btn.addEventListener('click', cancelAction); + } else { + if (buttonText == "Submit" || buttonText == "Ok") + btn.classList.add('btn-primary'); + btn.addEventListener('click', submitAction); + } + + }) + + + + return buttonGroup; +} + + +module.exports = { renderForm }; +},{}],10:[function(require,module,exports){ +/** + * @fileoverview gRPC-Web generated client stub for hiddifyrpc + * @enhanceable + * @public + */ + +// Code generated by protoc-gen-grpc-web. DO NOT EDIT. +// versions: +// protoc-gen-grpc-web v1.5.0 +// protoc v5.28.0 +// source: hiddify.proto + + +/* eslint-disable */ +// @ts-nocheck + + + +const grpc = {}; +grpc.web = require('grpc-web'); + + +var base_pb = require('./base_pb.js') +const proto = {}; +proto.hiddifyrpc = require('./hiddify_pb.js'); + +/** + * @param {string} hostname + * @param {?Object} credentials + * @param {?grpc.web.ClientOptions} options + * @constructor + * @struct + * @final + */ +proto.hiddifyrpc.HelloClient = + function(hostname, credentials, options) { + if (!options) options = {}; + options.format = 'text'; + + /** + * @private @const {!grpc.web.GrpcWebClientBase} The client + */ + this.client_ = new grpc.web.GrpcWebClientBase(options); + + /** + * @private @const {string} The hostname + */ + this.hostname_ = hostname.replace(/\/+$/, ''); + +}; + + +/** + * @param {string} hostname + * @param {?Object} credentials + * @param {?grpc.web.ClientOptions} options + * @constructor + * @struct + * @final + */ +proto.hiddifyrpc.HelloPromiseClient = + function(hostname, credentials, options) { + if (!options) options = {}; + options.format = 'text'; + + /** + * @private @const {!grpc.web.GrpcWebClientBase} The client + */ + this.client_ = new grpc.web.GrpcWebClientBase(options); + + /** + * @private @const {string} The hostname + */ + this.hostname_ = hostname.replace(/\/+$/, ''); + +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.HelloRequest, + * !proto.hiddifyrpc.HelloResponse>} + */ +const methodDescriptor_Hello_SayHello = new grpc.web.MethodDescriptor( + '/hiddifyrpc.Hello/SayHello', + grpc.web.MethodType.UNARY, + base_pb.HelloRequest, + base_pb.HelloResponse, + /** + * @param {!proto.hiddifyrpc.HelloRequest} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + base_pb.HelloResponse.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.HelloRequest} request The + * request proto + * @param {?Object} metadata User defined + * call metadata + * @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.HelloResponse)} + * callback The callback function(error, response) + * @return {!grpc.web.ClientReadableStream|undefined} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.HelloClient.prototype.sayHello = + function(request, metadata, callback) { + return this.client_.rpcCall(this.hostname_ + + '/hiddifyrpc.Hello/SayHello', + request, + metadata || {}, + methodDescriptor_Hello_SayHello, + callback); +}; + + +/** + * @param {!proto.hiddifyrpc.HelloRequest} request The + * request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!Promise} + * Promise that resolves to the response + */ +proto.hiddifyrpc.HelloPromiseClient.prototype.sayHello = + function(request, metadata) { + return this.client_.unaryCall(this.hostname_ + + '/hiddifyrpc.Hello/SayHello', + request, + metadata || {}, + methodDescriptor_Hello_SayHello); +}; + + +/** + * @param {string} hostname + * @param {?Object} credentials + * @param {?grpc.web.ClientOptions} options + * @constructor + * @struct + * @final + */ +proto.hiddifyrpc.CoreClient = + function(hostname, credentials, options) { + if (!options) options = {}; + options.format = 'text'; + + /** + * @private @const {!grpc.web.GrpcWebClientBase} The client + */ + this.client_ = new grpc.web.GrpcWebClientBase(options); + + /** + * @private @const {string} The hostname + */ + this.hostname_ = hostname.replace(/\/+$/, ''); + +}; + + +/** + * @param {string} hostname + * @param {?Object} credentials + * @param {?grpc.web.ClientOptions} options + * @constructor + * @struct + * @final + */ +proto.hiddifyrpc.CorePromiseClient = + function(hostname, credentials, options) { + if (!options) options = {}; + options.format = 'text'; + + /** + * @private @const {!grpc.web.GrpcWebClientBase} The client + */ + this.client_ = new grpc.web.GrpcWebClientBase(options); + + /** + * @private @const {string} The hostname + */ + this.hostname_ = hostname.replace(/\/+$/, ''); + +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.StartRequest, + * !proto.hiddifyrpc.CoreInfoResponse>} + */ +const methodDescriptor_Core_Start = new grpc.web.MethodDescriptor( + '/hiddifyrpc.Core/Start', + grpc.web.MethodType.UNARY, + proto.hiddifyrpc.StartRequest, + proto.hiddifyrpc.CoreInfoResponse, + /** + * @param {!proto.hiddifyrpc.StartRequest} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.CoreInfoResponse.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.StartRequest} request The + * request proto + * @param {?Object} metadata User defined + * call metadata + * @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.CoreInfoResponse)} + * callback The callback function(error, response) + * @return {!grpc.web.ClientReadableStream|undefined} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.CoreClient.prototype.start = + function(request, metadata, callback) { + return this.client_.rpcCall(this.hostname_ + + '/hiddifyrpc.Core/Start', + request, + metadata || {}, + methodDescriptor_Core_Start, + callback); +}; + + +/** + * @param {!proto.hiddifyrpc.StartRequest} request The + * request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!Promise} + * Promise that resolves to the response + */ +proto.hiddifyrpc.CorePromiseClient.prototype.start = + function(request, metadata) { + return this.client_.unaryCall(this.hostname_ + + '/hiddifyrpc.Core/Start', + request, + metadata || {}, + methodDescriptor_Core_Start); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.Empty, + * !proto.hiddifyrpc.CoreInfoResponse>} + */ +const methodDescriptor_Core_CoreInfoListener = new grpc.web.MethodDescriptor( + '/hiddifyrpc.Core/CoreInfoListener', + grpc.web.MethodType.SERVER_STREAMING, + base_pb.Empty, + proto.hiddifyrpc.CoreInfoResponse, + /** + * @param {!proto.hiddifyrpc.Empty} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.CoreInfoResponse.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.Empty} request The request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!grpc.web.ClientReadableStream} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.CoreClient.prototype.coreInfoListener = + function(request, metadata) { + return this.client_.serverStreaming(this.hostname_ + + '/hiddifyrpc.Core/CoreInfoListener', + request, + metadata || {}, + methodDescriptor_Core_CoreInfoListener); +}; + + +/** + * @param {!proto.hiddifyrpc.Empty} request The request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!grpc.web.ClientReadableStream} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.CorePromiseClient.prototype.coreInfoListener = + function(request, metadata) { + return this.client_.serverStreaming(this.hostname_ + + '/hiddifyrpc.Core/CoreInfoListener', + request, + metadata || {}, + methodDescriptor_Core_CoreInfoListener); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.Empty, + * !proto.hiddifyrpc.OutboundGroupList>} + */ +const methodDescriptor_Core_OutboundsInfo = new grpc.web.MethodDescriptor( + '/hiddifyrpc.Core/OutboundsInfo', + grpc.web.MethodType.SERVER_STREAMING, + base_pb.Empty, + proto.hiddifyrpc.OutboundGroupList, + /** + * @param {!proto.hiddifyrpc.Empty} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.OutboundGroupList.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.Empty} request The request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!grpc.web.ClientReadableStream} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.CoreClient.prototype.outboundsInfo = + function(request, metadata) { + return this.client_.serverStreaming(this.hostname_ + + '/hiddifyrpc.Core/OutboundsInfo', + request, + metadata || {}, + methodDescriptor_Core_OutboundsInfo); +}; + + +/** + * @param {!proto.hiddifyrpc.Empty} request The request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!grpc.web.ClientReadableStream} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.CorePromiseClient.prototype.outboundsInfo = + function(request, metadata) { + return this.client_.serverStreaming(this.hostname_ + + '/hiddifyrpc.Core/OutboundsInfo', + request, + metadata || {}, + methodDescriptor_Core_OutboundsInfo); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.Empty, + * !proto.hiddifyrpc.OutboundGroupList>} + */ +const methodDescriptor_Core_MainOutboundsInfo = new grpc.web.MethodDescriptor( + '/hiddifyrpc.Core/MainOutboundsInfo', + grpc.web.MethodType.SERVER_STREAMING, + base_pb.Empty, + proto.hiddifyrpc.OutboundGroupList, + /** + * @param {!proto.hiddifyrpc.Empty} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.OutboundGroupList.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.Empty} request The request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!grpc.web.ClientReadableStream} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.CoreClient.prototype.mainOutboundsInfo = + function(request, metadata) { + return this.client_.serverStreaming(this.hostname_ + + '/hiddifyrpc.Core/MainOutboundsInfo', + request, + metadata || {}, + methodDescriptor_Core_MainOutboundsInfo); +}; + + +/** + * @param {!proto.hiddifyrpc.Empty} request The request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!grpc.web.ClientReadableStream} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.CorePromiseClient.prototype.mainOutboundsInfo = + function(request, metadata) { + return this.client_.serverStreaming(this.hostname_ + + '/hiddifyrpc.Core/MainOutboundsInfo', + request, + metadata || {}, + methodDescriptor_Core_MainOutboundsInfo); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.Empty, + * !proto.hiddifyrpc.SystemInfo>} + */ +const methodDescriptor_Core_GetSystemInfo = new grpc.web.MethodDescriptor( + '/hiddifyrpc.Core/GetSystemInfo', + grpc.web.MethodType.SERVER_STREAMING, + base_pb.Empty, + proto.hiddifyrpc.SystemInfo, + /** + * @param {!proto.hiddifyrpc.Empty} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.SystemInfo.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.Empty} request The request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!grpc.web.ClientReadableStream} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.CoreClient.prototype.getSystemInfo = + function(request, metadata) { + return this.client_.serverStreaming(this.hostname_ + + '/hiddifyrpc.Core/GetSystemInfo', + request, + metadata || {}, + methodDescriptor_Core_GetSystemInfo); +}; + + +/** + * @param {!proto.hiddifyrpc.Empty} request The request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!grpc.web.ClientReadableStream} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.CorePromiseClient.prototype.getSystemInfo = + function(request, metadata) { + return this.client_.serverStreaming(this.hostname_ + + '/hiddifyrpc.Core/GetSystemInfo', + request, + metadata || {}, + methodDescriptor_Core_GetSystemInfo); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.SetupRequest, + * !proto.hiddifyrpc.Response>} + */ +const methodDescriptor_Core_Setup = new grpc.web.MethodDescriptor( + '/hiddifyrpc.Core/Setup', + grpc.web.MethodType.UNARY, + proto.hiddifyrpc.SetupRequest, + proto.hiddifyrpc.Response, + /** + * @param {!proto.hiddifyrpc.SetupRequest} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.Response.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.SetupRequest} request The + * request proto + * @param {?Object} metadata User defined + * call metadata + * @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.Response)} + * callback The callback function(error, response) + * @return {!grpc.web.ClientReadableStream|undefined} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.CoreClient.prototype.setup = + function(request, metadata, callback) { + return this.client_.rpcCall(this.hostname_ + + '/hiddifyrpc.Core/Setup', + request, + metadata || {}, + methodDescriptor_Core_Setup, + callback); +}; + + +/** + * @param {!proto.hiddifyrpc.SetupRequest} request The + * request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!Promise} + * Promise that resolves to the response + */ +proto.hiddifyrpc.CorePromiseClient.prototype.setup = + function(request, metadata) { + return this.client_.unaryCall(this.hostname_ + + '/hiddifyrpc.Core/Setup', + request, + metadata || {}, + methodDescriptor_Core_Setup); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.ParseRequest, + * !proto.hiddifyrpc.ParseResponse>} + */ +const methodDescriptor_Core_Parse = new grpc.web.MethodDescriptor( + '/hiddifyrpc.Core/Parse', + grpc.web.MethodType.UNARY, + proto.hiddifyrpc.ParseRequest, + proto.hiddifyrpc.ParseResponse, + /** + * @param {!proto.hiddifyrpc.ParseRequest} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.ParseResponse.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.ParseRequest} request The + * request proto + * @param {?Object} metadata User defined + * call metadata + * @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.ParseResponse)} + * callback The callback function(error, response) + * @return {!grpc.web.ClientReadableStream|undefined} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.CoreClient.prototype.parse = + function(request, metadata, callback) { + return this.client_.rpcCall(this.hostname_ + + '/hiddifyrpc.Core/Parse', + request, + metadata || {}, + methodDescriptor_Core_Parse, + callback); +}; + + +/** + * @param {!proto.hiddifyrpc.ParseRequest} request The + * request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!Promise} + * Promise that resolves to the response + */ +proto.hiddifyrpc.CorePromiseClient.prototype.parse = + function(request, metadata) { + return this.client_.unaryCall(this.hostname_ + + '/hiddifyrpc.Core/Parse', + request, + metadata || {}, + methodDescriptor_Core_Parse); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.ChangeHiddifySettingsRequest, + * !proto.hiddifyrpc.CoreInfoResponse>} + */ +const methodDescriptor_Core_ChangeHiddifySettings = new grpc.web.MethodDescriptor( + '/hiddifyrpc.Core/ChangeHiddifySettings', + grpc.web.MethodType.UNARY, + proto.hiddifyrpc.ChangeHiddifySettingsRequest, + proto.hiddifyrpc.CoreInfoResponse, + /** + * @param {!proto.hiddifyrpc.ChangeHiddifySettingsRequest} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.CoreInfoResponse.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.ChangeHiddifySettingsRequest} request The + * request proto + * @param {?Object} metadata User defined + * call metadata + * @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.CoreInfoResponse)} + * callback The callback function(error, response) + * @return {!grpc.web.ClientReadableStream|undefined} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.CoreClient.prototype.changeHiddifySettings = + function(request, metadata, callback) { + return this.client_.rpcCall(this.hostname_ + + '/hiddifyrpc.Core/ChangeHiddifySettings', + request, + metadata || {}, + methodDescriptor_Core_ChangeHiddifySettings, + callback); +}; + + +/** + * @param {!proto.hiddifyrpc.ChangeHiddifySettingsRequest} request The + * request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!Promise} + * Promise that resolves to the response + */ +proto.hiddifyrpc.CorePromiseClient.prototype.changeHiddifySettings = + function(request, metadata) { + return this.client_.unaryCall(this.hostname_ + + '/hiddifyrpc.Core/ChangeHiddifySettings', + request, + metadata || {}, + methodDescriptor_Core_ChangeHiddifySettings); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.StartRequest, + * !proto.hiddifyrpc.CoreInfoResponse>} + */ +const methodDescriptor_Core_StartService = new grpc.web.MethodDescriptor( + '/hiddifyrpc.Core/StartService', + grpc.web.MethodType.UNARY, + proto.hiddifyrpc.StartRequest, + proto.hiddifyrpc.CoreInfoResponse, + /** + * @param {!proto.hiddifyrpc.StartRequest} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.CoreInfoResponse.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.StartRequest} request The + * request proto + * @param {?Object} metadata User defined + * call metadata + * @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.CoreInfoResponse)} + * callback The callback function(error, response) + * @return {!grpc.web.ClientReadableStream|undefined} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.CoreClient.prototype.startService = + function(request, metadata, callback) { + return this.client_.rpcCall(this.hostname_ + + '/hiddifyrpc.Core/StartService', + request, + metadata || {}, + methodDescriptor_Core_StartService, + callback); +}; + + +/** + * @param {!proto.hiddifyrpc.StartRequest} request The + * request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!Promise} + * Promise that resolves to the response + */ +proto.hiddifyrpc.CorePromiseClient.prototype.startService = + function(request, metadata) { + return this.client_.unaryCall(this.hostname_ + + '/hiddifyrpc.Core/StartService', + request, + metadata || {}, + methodDescriptor_Core_StartService); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.Empty, + * !proto.hiddifyrpc.CoreInfoResponse>} + */ +const methodDescriptor_Core_Stop = new grpc.web.MethodDescriptor( + '/hiddifyrpc.Core/Stop', + grpc.web.MethodType.UNARY, + base_pb.Empty, + proto.hiddifyrpc.CoreInfoResponse, + /** + * @param {!proto.hiddifyrpc.Empty} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.CoreInfoResponse.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.Empty} request The + * request proto + * @param {?Object} metadata User defined + * call metadata + * @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.CoreInfoResponse)} + * callback The callback function(error, response) + * @return {!grpc.web.ClientReadableStream|undefined} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.CoreClient.prototype.stop = + function(request, metadata, callback) { + return this.client_.rpcCall(this.hostname_ + + '/hiddifyrpc.Core/Stop', + request, + metadata || {}, + methodDescriptor_Core_Stop, + callback); +}; + + +/** + * @param {!proto.hiddifyrpc.Empty} request The + * request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!Promise} + * Promise that resolves to the response + */ +proto.hiddifyrpc.CorePromiseClient.prototype.stop = + function(request, metadata) { + return this.client_.unaryCall(this.hostname_ + + '/hiddifyrpc.Core/Stop', + request, + metadata || {}, + methodDescriptor_Core_Stop); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.StartRequest, + * !proto.hiddifyrpc.CoreInfoResponse>} + */ +const methodDescriptor_Core_Restart = new grpc.web.MethodDescriptor( + '/hiddifyrpc.Core/Restart', + grpc.web.MethodType.UNARY, + proto.hiddifyrpc.StartRequest, + proto.hiddifyrpc.CoreInfoResponse, + /** + * @param {!proto.hiddifyrpc.StartRequest} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.CoreInfoResponse.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.StartRequest} request The + * request proto + * @param {?Object} metadata User defined + * call metadata + * @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.CoreInfoResponse)} + * callback The callback function(error, response) + * @return {!grpc.web.ClientReadableStream|undefined} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.CoreClient.prototype.restart = + function(request, metadata, callback) { + return this.client_.rpcCall(this.hostname_ + + '/hiddifyrpc.Core/Restart', + request, + metadata || {}, + methodDescriptor_Core_Restart, + callback); +}; + + +/** + * @param {!proto.hiddifyrpc.StartRequest} request The + * request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!Promise} + * Promise that resolves to the response + */ +proto.hiddifyrpc.CorePromiseClient.prototype.restart = + function(request, metadata) { + return this.client_.unaryCall(this.hostname_ + + '/hiddifyrpc.Core/Restart', + request, + metadata || {}, + methodDescriptor_Core_Restart); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.SelectOutboundRequest, + * !proto.hiddifyrpc.Response>} + */ +const methodDescriptor_Core_SelectOutbound = new grpc.web.MethodDescriptor( + '/hiddifyrpc.Core/SelectOutbound', + grpc.web.MethodType.UNARY, + proto.hiddifyrpc.SelectOutboundRequest, + proto.hiddifyrpc.Response, + /** + * @param {!proto.hiddifyrpc.SelectOutboundRequest} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.Response.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.SelectOutboundRequest} request The + * request proto + * @param {?Object} metadata User defined + * call metadata + * @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.Response)} + * callback The callback function(error, response) + * @return {!grpc.web.ClientReadableStream|undefined} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.CoreClient.prototype.selectOutbound = + function(request, metadata, callback) { + return this.client_.rpcCall(this.hostname_ + + '/hiddifyrpc.Core/SelectOutbound', + request, + metadata || {}, + methodDescriptor_Core_SelectOutbound, + callback); +}; + + +/** + * @param {!proto.hiddifyrpc.SelectOutboundRequest} request The + * request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!Promise} + * Promise that resolves to the response + */ +proto.hiddifyrpc.CorePromiseClient.prototype.selectOutbound = + function(request, metadata) { + return this.client_.unaryCall(this.hostname_ + + '/hiddifyrpc.Core/SelectOutbound', + request, + metadata || {}, + methodDescriptor_Core_SelectOutbound); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.UrlTestRequest, + * !proto.hiddifyrpc.Response>} + */ +const methodDescriptor_Core_UrlTest = new grpc.web.MethodDescriptor( + '/hiddifyrpc.Core/UrlTest', + grpc.web.MethodType.UNARY, + proto.hiddifyrpc.UrlTestRequest, + proto.hiddifyrpc.Response, + /** + * @param {!proto.hiddifyrpc.UrlTestRequest} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.Response.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.UrlTestRequest} request The + * request proto + * @param {?Object} metadata User defined + * call metadata + * @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.Response)} + * callback The callback function(error, response) + * @return {!grpc.web.ClientReadableStream|undefined} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.CoreClient.prototype.urlTest = + function(request, metadata, callback) { + return this.client_.rpcCall(this.hostname_ + + '/hiddifyrpc.Core/UrlTest', + request, + metadata || {}, + methodDescriptor_Core_UrlTest, + callback); +}; + + +/** + * @param {!proto.hiddifyrpc.UrlTestRequest} request The + * request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!Promise} + * Promise that resolves to the response + */ +proto.hiddifyrpc.CorePromiseClient.prototype.urlTest = + function(request, metadata) { + return this.client_.unaryCall(this.hostname_ + + '/hiddifyrpc.Core/UrlTest', + request, + metadata || {}, + methodDescriptor_Core_UrlTest); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.GenerateWarpConfigRequest, + * !proto.hiddifyrpc.WarpGenerationResponse>} + */ +const methodDescriptor_Core_GenerateWarpConfig = new grpc.web.MethodDescriptor( + '/hiddifyrpc.Core/GenerateWarpConfig', + grpc.web.MethodType.UNARY, + proto.hiddifyrpc.GenerateWarpConfigRequest, + proto.hiddifyrpc.WarpGenerationResponse, + /** + * @param {!proto.hiddifyrpc.GenerateWarpConfigRequest} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.WarpGenerationResponse.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.GenerateWarpConfigRequest} request The + * request proto + * @param {?Object} metadata User defined + * call metadata + * @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.WarpGenerationResponse)} + * callback The callback function(error, response) + * @return {!grpc.web.ClientReadableStream|undefined} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.CoreClient.prototype.generateWarpConfig = + function(request, metadata, callback) { + return this.client_.rpcCall(this.hostname_ + + '/hiddifyrpc.Core/GenerateWarpConfig', + request, + metadata || {}, + methodDescriptor_Core_GenerateWarpConfig, + callback); +}; + + +/** + * @param {!proto.hiddifyrpc.GenerateWarpConfigRequest} request The + * request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!Promise} + * Promise that resolves to the response + */ +proto.hiddifyrpc.CorePromiseClient.prototype.generateWarpConfig = + function(request, metadata) { + return this.client_.unaryCall(this.hostname_ + + '/hiddifyrpc.Core/GenerateWarpConfig', + request, + metadata || {}, + methodDescriptor_Core_GenerateWarpConfig); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.Empty, + * !proto.hiddifyrpc.SystemProxyStatus>} + */ +const methodDescriptor_Core_GetSystemProxyStatus = new grpc.web.MethodDescriptor( + '/hiddifyrpc.Core/GetSystemProxyStatus', + grpc.web.MethodType.UNARY, + base_pb.Empty, + proto.hiddifyrpc.SystemProxyStatus, + /** + * @param {!proto.hiddifyrpc.Empty} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.SystemProxyStatus.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.Empty} request The + * request proto + * @param {?Object} metadata User defined + * call metadata + * @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.SystemProxyStatus)} + * callback The callback function(error, response) + * @return {!grpc.web.ClientReadableStream|undefined} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.CoreClient.prototype.getSystemProxyStatus = + function(request, metadata, callback) { + return this.client_.rpcCall(this.hostname_ + + '/hiddifyrpc.Core/GetSystemProxyStatus', + request, + metadata || {}, + methodDescriptor_Core_GetSystemProxyStatus, + callback); +}; + + +/** + * @param {!proto.hiddifyrpc.Empty} request The + * request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!Promise} + * Promise that resolves to the response + */ +proto.hiddifyrpc.CorePromiseClient.prototype.getSystemProxyStatus = + function(request, metadata) { + return this.client_.unaryCall(this.hostname_ + + '/hiddifyrpc.Core/GetSystemProxyStatus', + request, + metadata || {}, + methodDescriptor_Core_GetSystemProxyStatus); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.SetSystemProxyEnabledRequest, + * !proto.hiddifyrpc.Response>} + */ +const methodDescriptor_Core_SetSystemProxyEnabled = new grpc.web.MethodDescriptor( + '/hiddifyrpc.Core/SetSystemProxyEnabled', + grpc.web.MethodType.UNARY, + proto.hiddifyrpc.SetSystemProxyEnabledRequest, + proto.hiddifyrpc.Response, + /** + * @param {!proto.hiddifyrpc.SetSystemProxyEnabledRequest} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.Response.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.SetSystemProxyEnabledRequest} request The + * request proto + * @param {?Object} metadata User defined + * call metadata + * @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.Response)} + * callback The callback function(error, response) + * @return {!grpc.web.ClientReadableStream|undefined} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.CoreClient.prototype.setSystemProxyEnabled = + function(request, metadata, callback) { + return this.client_.rpcCall(this.hostname_ + + '/hiddifyrpc.Core/SetSystemProxyEnabled', + request, + metadata || {}, + methodDescriptor_Core_SetSystemProxyEnabled, + callback); +}; + + +/** + * @param {!proto.hiddifyrpc.SetSystemProxyEnabledRequest} request The + * request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!Promise} + * Promise that resolves to the response + */ +proto.hiddifyrpc.CorePromiseClient.prototype.setSystemProxyEnabled = + function(request, metadata) { + return this.client_.unaryCall(this.hostname_ + + '/hiddifyrpc.Core/SetSystemProxyEnabled', + request, + metadata || {}, + methodDescriptor_Core_SetSystemProxyEnabled); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.Empty, + * !proto.hiddifyrpc.LogMessage>} + */ +const methodDescriptor_Core_LogListener = new grpc.web.MethodDescriptor( + '/hiddifyrpc.Core/LogListener', + grpc.web.MethodType.SERVER_STREAMING, + base_pb.Empty, + proto.hiddifyrpc.LogMessage, + /** + * @param {!proto.hiddifyrpc.Empty} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.LogMessage.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.Empty} request The request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!grpc.web.ClientReadableStream} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.CoreClient.prototype.logListener = + function(request, metadata) { + return this.client_.serverStreaming(this.hostname_ + + '/hiddifyrpc.Core/LogListener', + request, + metadata || {}, + methodDescriptor_Core_LogListener); +}; + + +/** + * @param {!proto.hiddifyrpc.Empty} request The request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!grpc.web.ClientReadableStream} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.CorePromiseClient.prototype.logListener = + function(request, metadata) { + return this.client_.serverStreaming(this.hostname_ + + '/hiddifyrpc.Core/LogListener', + request, + metadata || {}, + methodDescriptor_Core_LogListener); +}; + + +/** + * @param {string} hostname + * @param {?Object} credentials + * @param {?grpc.web.ClientOptions} options + * @constructor + * @struct + * @final + */ +proto.hiddifyrpc.TunnelServiceClient = + function(hostname, credentials, options) { + if (!options) options = {}; + options.format = 'text'; + + /** + * @private @const {!grpc.web.GrpcWebClientBase} The client + */ + this.client_ = new grpc.web.GrpcWebClientBase(options); + + /** + * @private @const {string} The hostname + */ + this.hostname_ = hostname.replace(/\/+$/, ''); + +}; + + +/** + * @param {string} hostname + * @param {?Object} credentials + * @param {?grpc.web.ClientOptions} options + * @constructor + * @struct + * @final + */ +proto.hiddifyrpc.TunnelServicePromiseClient = + function(hostname, credentials, options) { + if (!options) options = {}; + options.format = 'text'; + + /** + * @private @const {!grpc.web.GrpcWebClientBase} The client + */ + this.client_ = new grpc.web.GrpcWebClientBase(options); + + /** + * @private @const {string} The hostname + */ + this.hostname_ = hostname.replace(/\/+$/, ''); + +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.TunnelStartRequest, + * !proto.hiddifyrpc.TunnelResponse>} + */ +const methodDescriptor_TunnelService_Start = new grpc.web.MethodDescriptor( + '/hiddifyrpc.TunnelService/Start', + grpc.web.MethodType.UNARY, + proto.hiddifyrpc.TunnelStartRequest, + proto.hiddifyrpc.TunnelResponse, + /** + * @param {!proto.hiddifyrpc.TunnelStartRequest} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.TunnelResponse.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.TunnelStartRequest} request The + * request proto + * @param {?Object} metadata User defined + * call metadata + * @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.TunnelResponse)} + * callback The callback function(error, response) + * @return {!grpc.web.ClientReadableStream|undefined} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.TunnelServiceClient.prototype.start = + function(request, metadata, callback) { + return this.client_.rpcCall(this.hostname_ + + '/hiddifyrpc.TunnelService/Start', + request, + metadata || {}, + methodDescriptor_TunnelService_Start, + callback); +}; + + +/** + * @param {!proto.hiddifyrpc.TunnelStartRequest} request The + * request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!Promise} + * Promise that resolves to the response + */ +proto.hiddifyrpc.TunnelServicePromiseClient.prototype.start = + function(request, metadata) { + return this.client_.unaryCall(this.hostname_ + + '/hiddifyrpc.TunnelService/Start', + request, + metadata || {}, + methodDescriptor_TunnelService_Start); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.Empty, + * !proto.hiddifyrpc.TunnelResponse>} + */ +const methodDescriptor_TunnelService_Stop = new grpc.web.MethodDescriptor( + '/hiddifyrpc.TunnelService/Stop', + grpc.web.MethodType.UNARY, + base_pb.Empty, + proto.hiddifyrpc.TunnelResponse, + /** + * @param {!proto.hiddifyrpc.Empty} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.TunnelResponse.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.Empty} request The + * request proto + * @param {?Object} metadata User defined + * call metadata + * @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.TunnelResponse)} + * callback The callback function(error, response) + * @return {!grpc.web.ClientReadableStream|undefined} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.TunnelServiceClient.prototype.stop = + function(request, metadata, callback) { + return this.client_.rpcCall(this.hostname_ + + '/hiddifyrpc.TunnelService/Stop', + request, + metadata || {}, + methodDescriptor_TunnelService_Stop, + callback); +}; + + +/** + * @param {!proto.hiddifyrpc.Empty} request The + * request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!Promise} + * Promise that resolves to the response + */ +proto.hiddifyrpc.TunnelServicePromiseClient.prototype.stop = + function(request, metadata) { + return this.client_.unaryCall(this.hostname_ + + '/hiddifyrpc.TunnelService/Stop', + request, + metadata || {}, + methodDescriptor_TunnelService_Stop); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.Empty, + * !proto.hiddifyrpc.TunnelResponse>} + */ +const methodDescriptor_TunnelService_Status = new grpc.web.MethodDescriptor( + '/hiddifyrpc.TunnelService/Status', + grpc.web.MethodType.UNARY, + base_pb.Empty, + proto.hiddifyrpc.TunnelResponse, + /** + * @param {!proto.hiddifyrpc.Empty} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.TunnelResponse.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.Empty} request The + * request proto + * @param {?Object} metadata User defined + * call metadata + * @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.TunnelResponse)} + * callback The callback function(error, response) + * @return {!grpc.web.ClientReadableStream|undefined} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.TunnelServiceClient.prototype.status = + function(request, metadata, callback) { + return this.client_.rpcCall(this.hostname_ + + '/hiddifyrpc.TunnelService/Status', + request, + metadata || {}, + methodDescriptor_TunnelService_Status, + callback); +}; + + +/** + * @param {!proto.hiddifyrpc.Empty} request The + * request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!Promise} + * Promise that resolves to the response + */ +proto.hiddifyrpc.TunnelServicePromiseClient.prototype.status = + function(request, metadata) { + return this.client_.unaryCall(this.hostname_ + + '/hiddifyrpc.TunnelService/Status', + request, + metadata || {}, + methodDescriptor_TunnelService_Status); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.Empty, + * !proto.hiddifyrpc.TunnelResponse>} + */ +const methodDescriptor_TunnelService_Exit = new grpc.web.MethodDescriptor( + '/hiddifyrpc.TunnelService/Exit', + grpc.web.MethodType.UNARY, + base_pb.Empty, + proto.hiddifyrpc.TunnelResponse, + /** + * @param {!proto.hiddifyrpc.Empty} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.TunnelResponse.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.Empty} request The + * request proto + * @param {?Object} metadata User defined + * call metadata + * @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.TunnelResponse)} + * callback The callback function(error, response) + * @return {!grpc.web.ClientReadableStream|undefined} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.TunnelServiceClient.prototype.exit = + function(request, metadata, callback) { + return this.client_.rpcCall(this.hostname_ + + '/hiddifyrpc.TunnelService/Exit', + request, + metadata || {}, + methodDescriptor_TunnelService_Exit, + callback); +}; + + +/** + * @param {!proto.hiddifyrpc.Empty} request The + * request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!Promise} + * Promise that resolves to the response + */ +proto.hiddifyrpc.TunnelServicePromiseClient.prototype.exit = + function(request, metadata) { + return this.client_.unaryCall(this.hostname_ + + '/hiddifyrpc.TunnelService/Exit', + request, + metadata || {}, + methodDescriptor_TunnelService_Exit); +}; + + +module.exports = proto.hiddifyrpc; + + +},{"./base_pb.js":1,"./hiddify_pb.js":11,"grpc-web":13}],11:[function(require,module,exports){ +// source: hiddify.proto +/** + * @fileoverview + * @enhanceable + * @suppress {missingRequire} reports error on implicit type usages. + * @suppress {messageConventions} JS Compiler reports an error if a variable or + * field starts with 'MSG_' and isn't a translatable message. + * @public + */ +// GENERATED CODE -- DO NOT EDIT! +/* eslint-disable */ +// @ts-nocheck + +var jspb = require('google-protobuf'); +var goog = jspb; +var global = + (typeof globalThis !== 'undefined' && globalThis) || + (typeof window !== 'undefined' && window) || + (typeof global !== 'undefined' && global) || + (typeof self !== 'undefined' && self) || + (function () { return this; }).call(null) || + Function('return this')(); + +var base_pb = require('./base_pb.js'); +goog.object.extend(proto, base_pb); +goog.exportSymbol('proto.hiddifyrpc.ChangeHiddifySettingsRequest', null, global); +goog.exportSymbol('proto.hiddifyrpc.CoreInfoResponse', null, global); +goog.exportSymbol('proto.hiddifyrpc.CoreState', null, global); +goog.exportSymbol('proto.hiddifyrpc.GenerateConfigRequest', null, global); +goog.exportSymbol('proto.hiddifyrpc.GenerateConfigResponse', null, global); +goog.exportSymbol('proto.hiddifyrpc.GenerateWarpConfigRequest', null, global); +goog.exportSymbol('proto.hiddifyrpc.LogLevel', null, global); +goog.exportSymbol('proto.hiddifyrpc.LogMessage', null, global); +goog.exportSymbol('proto.hiddifyrpc.LogType', null, global); +goog.exportSymbol('proto.hiddifyrpc.MessageType', null, global); +goog.exportSymbol('proto.hiddifyrpc.OutboundGroup', null, global); +goog.exportSymbol('proto.hiddifyrpc.OutboundGroupItem', null, global); +goog.exportSymbol('proto.hiddifyrpc.OutboundGroupList', null, global); +goog.exportSymbol('proto.hiddifyrpc.ParseRequest', null, global); +goog.exportSymbol('proto.hiddifyrpc.ParseResponse', null, global); +goog.exportSymbol('proto.hiddifyrpc.Response', null, global); +goog.exportSymbol('proto.hiddifyrpc.SelectOutboundRequest', null, global); +goog.exportSymbol('proto.hiddifyrpc.SetSystemProxyEnabledRequest', null, global); +goog.exportSymbol('proto.hiddifyrpc.SetupRequest', null, global); +goog.exportSymbol('proto.hiddifyrpc.StartRequest', null, global); +goog.exportSymbol('proto.hiddifyrpc.StopRequest', null, global); +goog.exportSymbol('proto.hiddifyrpc.SystemInfo', null, global); +goog.exportSymbol('proto.hiddifyrpc.SystemProxyStatus', null, global); +goog.exportSymbol('proto.hiddifyrpc.TunnelResponse', null, global); +goog.exportSymbol('proto.hiddifyrpc.TunnelStartRequest', null, global); +goog.exportSymbol('proto.hiddifyrpc.UrlTestRequest', null, global); +goog.exportSymbol('proto.hiddifyrpc.WarpAccount', null, global); +goog.exportSymbol('proto.hiddifyrpc.WarpGenerationResponse', null, global); +goog.exportSymbol('proto.hiddifyrpc.WarpWireguardConfig', null, global); +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.CoreInfoResponse = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.CoreInfoResponse, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.CoreInfoResponse.displayName = 'proto.hiddifyrpc.CoreInfoResponse'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.StartRequest = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.StartRequest, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.StartRequest.displayName = 'proto.hiddifyrpc.StartRequest'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.SetupRequest = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.SetupRequest, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.SetupRequest.displayName = 'proto.hiddifyrpc.SetupRequest'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.Response = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.Response, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.Response.displayName = 'proto.hiddifyrpc.Response'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.SystemInfo = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.SystemInfo, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.SystemInfo.displayName = 'proto.hiddifyrpc.SystemInfo'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.OutboundGroupItem = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.OutboundGroupItem, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.OutboundGroupItem.displayName = 'proto.hiddifyrpc.OutboundGroupItem'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.OutboundGroup = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, proto.hiddifyrpc.OutboundGroup.repeatedFields_, null); +}; +goog.inherits(proto.hiddifyrpc.OutboundGroup, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.OutboundGroup.displayName = 'proto.hiddifyrpc.OutboundGroup'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.OutboundGroupList = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, proto.hiddifyrpc.OutboundGroupList.repeatedFields_, null); +}; +goog.inherits(proto.hiddifyrpc.OutboundGroupList, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.OutboundGroupList.displayName = 'proto.hiddifyrpc.OutboundGroupList'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.WarpAccount = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.WarpAccount, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.WarpAccount.displayName = 'proto.hiddifyrpc.WarpAccount'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.WarpWireguardConfig = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.WarpWireguardConfig, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.WarpWireguardConfig.displayName = 'proto.hiddifyrpc.WarpWireguardConfig'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.WarpGenerationResponse = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.WarpGenerationResponse, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.WarpGenerationResponse.displayName = 'proto.hiddifyrpc.WarpGenerationResponse'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.SystemProxyStatus = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.SystemProxyStatus, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.SystemProxyStatus.displayName = 'proto.hiddifyrpc.SystemProxyStatus'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.ParseRequest = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.ParseRequest, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.ParseRequest.displayName = 'proto.hiddifyrpc.ParseRequest'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.ParseResponse = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.ParseResponse, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.ParseResponse.displayName = 'proto.hiddifyrpc.ParseResponse'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.ChangeHiddifySettingsRequest = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.ChangeHiddifySettingsRequest, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.ChangeHiddifySettingsRequest.displayName = 'proto.hiddifyrpc.ChangeHiddifySettingsRequest'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.GenerateConfigRequest = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.GenerateConfigRequest, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.GenerateConfigRequest.displayName = 'proto.hiddifyrpc.GenerateConfigRequest'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.GenerateConfigResponse = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.GenerateConfigResponse, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.GenerateConfigResponse.displayName = 'proto.hiddifyrpc.GenerateConfigResponse'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.SelectOutboundRequest = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.SelectOutboundRequest, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.SelectOutboundRequest.displayName = 'proto.hiddifyrpc.SelectOutboundRequest'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.UrlTestRequest = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.UrlTestRequest, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.UrlTestRequest.displayName = 'proto.hiddifyrpc.UrlTestRequest'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.GenerateWarpConfigRequest = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.GenerateWarpConfigRequest, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.GenerateWarpConfigRequest.displayName = 'proto.hiddifyrpc.GenerateWarpConfigRequest'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.SetSystemProxyEnabledRequest = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.SetSystemProxyEnabledRequest, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.SetSystemProxyEnabledRequest.displayName = 'proto.hiddifyrpc.SetSystemProxyEnabledRequest'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.LogMessage = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.LogMessage, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.LogMessage.displayName = 'proto.hiddifyrpc.LogMessage'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.StopRequest = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.StopRequest, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.StopRequest.displayName = 'proto.hiddifyrpc.StopRequest'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.TunnelStartRequest = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.TunnelStartRequest, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.TunnelStartRequest.displayName = 'proto.hiddifyrpc.TunnelStartRequest'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.TunnelResponse = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.TunnelResponse, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.TunnelResponse.displayName = 'proto.hiddifyrpc.TunnelResponse'; +} + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.CoreInfoResponse.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.CoreInfoResponse.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.CoreInfoResponse} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.CoreInfoResponse.toObject = function(includeInstance, msg) { + var f, obj = { +coreState: jspb.Message.getFieldWithDefault(msg, 1, 0), +messageType: jspb.Message.getFieldWithDefault(msg, 2, 0), +message: jspb.Message.getFieldWithDefault(msg, 3, "") + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.CoreInfoResponse} + */ +proto.hiddifyrpc.CoreInfoResponse.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.CoreInfoResponse; + return proto.hiddifyrpc.CoreInfoResponse.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.CoreInfoResponse} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.CoreInfoResponse} + */ +proto.hiddifyrpc.CoreInfoResponse.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {!proto.hiddifyrpc.CoreState} */ (reader.readEnum()); + msg.setCoreState(value); + break; + case 2: + var value = /** @type {!proto.hiddifyrpc.MessageType} */ (reader.readEnum()); + msg.setMessageType(value); + break; + case 3: + var value = /** @type {string} */ (reader.readString()); + msg.setMessage(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.CoreInfoResponse.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.CoreInfoResponse.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.CoreInfoResponse} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.CoreInfoResponse.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getCoreState(); + if (f !== 0.0) { + writer.writeEnum( + 1, + f + ); + } + f = message.getMessageType(); + if (f !== 0.0) { + writer.writeEnum( + 2, + f + ); + } + f = message.getMessage(); + if (f.length > 0) { + writer.writeString( + 3, + f + ); + } +}; + + +/** + * optional CoreState core_state = 1; + * @return {!proto.hiddifyrpc.CoreState} + */ +proto.hiddifyrpc.CoreInfoResponse.prototype.getCoreState = function() { + return /** @type {!proto.hiddifyrpc.CoreState} */ (jspb.Message.getFieldWithDefault(this, 1, 0)); +}; + + +/** + * @param {!proto.hiddifyrpc.CoreState} value + * @return {!proto.hiddifyrpc.CoreInfoResponse} returns this + */ +proto.hiddifyrpc.CoreInfoResponse.prototype.setCoreState = function(value) { + return jspb.Message.setProto3EnumField(this, 1, value); +}; + + +/** + * optional MessageType message_type = 2; + * @return {!proto.hiddifyrpc.MessageType} + */ +proto.hiddifyrpc.CoreInfoResponse.prototype.getMessageType = function() { + return /** @type {!proto.hiddifyrpc.MessageType} */ (jspb.Message.getFieldWithDefault(this, 2, 0)); +}; + + +/** + * @param {!proto.hiddifyrpc.MessageType} value + * @return {!proto.hiddifyrpc.CoreInfoResponse} returns this + */ +proto.hiddifyrpc.CoreInfoResponse.prototype.setMessageType = function(value) { + return jspb.Message.setProto3EnumField(this, 2, value); +}; + + +/** + * optional string message = 3; + * @return {string} + */ +proto.hiddifyrpc.CoreInfoResponse.prototype.getMessage = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.CoreInfoResponse} returns this + */ +proto.hiddifyrpc.CoreInfoResponse.prototype.setMessage = function(value) { + return jspb.Message.setProto3StringField(this, 3, value); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.StartRequest.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.StartRequest.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.StartRequest} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.StartRequest.toObject = function(includeInstance, msg) { + var f, obj = { +configPath: jspb.Message.getFieldWithDefault(msg, 1, ""), +configContent: jspb.Message.getFieldWithDefault(msg, 2, ""), +disableMemoryLimit: jspb.Message.getBooleanFieldWithDefault(msg, 3, false), +delayStart: jspb.Message.getBooleanFieldWithDefault(msg, 4, false), +enableOldCommandServer: jspb.Message.getBooleanFieldWithDefault(msg, 5, false), +enableRawConfig: jspb.Message.getBooleanFieldWithDefault(msg, 6, false) + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.StartRequest} + */ +proto.hiddifyrpc.StartRequest.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.StartRequest; + return proto.hiddifyrpc.StartRequest.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.StartRequest} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.StartRequest} + */ +proto.hiddifyrpc.StartRequest.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {string} */ (reader.readString()); + msg.setConfigPath(value); + break; + case 2: + var value = /** @type {string} */ (reader.readString()); + msg.setConfigContent(value); + break; + case 3: + var value = /** @type {boolean} */ (reader.readBool()); + msg.setDisableMemoryLimit(value); + break; + case 4: + var value = /** @type {boolean} */ (reader.readBool()); + msg.setDelayStart(value); + break; + case 5: + var value = /** @type {boolean} */ (reader.readBool()); + msg.setEnableOldCommandServer(value); + break; + case 6: + var value = /** @type {boolean} */ (reader.readBool()); + msg.setEnableRawConfig(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.StartRequest.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.StartRequest.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.StartRequest} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.StartRequest.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getConfigPath(); + if (f.length > 0) { + writer.writeString( + 1, + f + ); + } + f = message.getConfigContent(); + if (f.length > 0) { + writer.writeString( + 2, + f + ); + } + f = message.getDisableMemoryLimit(); + if (f) { + writer.writeBool( + 3, + f + ); + } + f = message.getDelayStart(); + if (f) { + writer.writeBool( + 4, + f + ); + } + f = message.getEnableOldCommandServer(); + if (f) { + writer.writeBool( + 5, + f + ); + } + f = message.getEnableRawConfig(); + if (f) { + writer.writeBool( + 6, + f + ); + } +}; + + +/** + * optional string config_path = 1; + * @return {string} + */ +proto.hiddifyrpc.StartRequest.prototype.getConfigPath = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.StartRequest} returns this + */ +proto.hiddifyrpc.StartRequest.prototype.setConfigPath = function(value) { + return jspb.Message.setProto3StringField(this, 1, value); +}; + + +/** + * optional string config_content = 2; + * @return {string} + */ +proto.hiddifyrpc.StartRequest.prototype.getConfigContent = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.StartRequest} returns this + */ +proto.hiddifyrpc.StartRequest.prototype.setConfigContent = function(value) { + return jspb.Message.setProto3StringField(this, 2, value); +}; + + +/** + * optional bool disable_memory_limit = 3; + * @return {boolean} + */ +proto.hiddifyrpc.StartRequest.prototype.getDisableMemoryLimit = function() { + return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 3, false)); +}; + + +/** + * @param {boolean} value + * @return {!proto.hiddifyrpc.StartRequest} returns this + */ +proto.hiddifyrpc.StartRequest.prototype.setDisableMemoryLimit = function(value) { + return jspb.Message.setProto3BooleanField(this, 3, value); +}; + + +/** + * optional bool delay_start = 4; + * @return {boolean} + */ +proto.hiddifyrpc.StartRequest.prototype.getDelayStart = function() { + return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 4, false)); +}; + + +/** + * @param {boolean} value + * @return {!proto.hiddifyrpc.StartRequest} returns this + */ +proto.hiddifyrpc.StartRequest.prototype.setDelayStart = function(value) { + return jspb.Message.setProto3BooleanField(this, 4, value); +}; + + +/** + * optional bool enable_old_command_server = 5; + * @return {boolean} + */ +proto.hiddifyrpc.StartRequest.prototype.getEnableOldCommandServer = function() { + return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 5, false)); +}; + + +/** + * @param {boolean} value + * @return {!proto.hiddifyrpc.StartRequest} returns this + */ +proto.hiddifyrpc.StartRequest.prototype.setEnableOldCommandServer = function(value) { + return jspb.Message.setProto3BooleanField(this, 5, value); +}; + + +/** + * optional bool enable_raw_config = 6; + * @return {boolean} + */ +proto.hiddifyrpc.StartRequest.prototype.getEnableRawConfig = function() { + return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 6, false)); +}; + + +/** + * @param {boolean} value + * @return {!proto.hiddifyrpc.StartRequest} returns this + */ +proto.hiddifyrpc.StartRequest.prototype.setEnableRawConfig = function(value) { + return jspb.Message.setProto3BooleanField(this, 6, value); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.SetupRequest.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.SetupRequest.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.SetupRequest} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.SetupRequest.toObject = function(includeInstance, msg) { + var f, obj = { +basePath: jspb.Message.getFieldWithDefault(msg, 1, ""), +workingPath: jspb.Message.getFieldWithDefault(msg, 2, ""), +tempPath: jspb.Message.getFieldWithDefault(msg, 3, "") + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.SetupRequest} + */ +proto.hiddifyrpc.SetupRequest.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.SetupRequest; + return proto.hiddifyrpc.SetupRequest.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.SetupRequest} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.SetupRequest} + */ +proto.hiddifyrpc.SetupRequest.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {string} */ (reader.readString()); + msg.setBasePath(value); + break; + case 2: + var value = /** @type {string} */ (reader.readString()); + msg.setWorkingPath(value); + break; + case 3: + var value = /** @type {string} */ (reader.readString()); + msg.setTempPath(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.SetupRequest.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.SetupRequest.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.SetupRequest} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.SetupRequest.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getBasePath(); + if (f.length > 0) { + writer.writeString( + 1, + f + ); + } + f = message.getWorkingPath(); + if (f.length > 0) { + writer.writeString( + 2, + f + ); + } + f = message.getTempPath(); + if (f.length > 0) { + writer.writeString( + 3, + f + ); + } +}; + + +/** + * optional string base_path = 1; + * @return {string} + */ +proto.hiddifyrpc.SetupRequest.prototype.getBasePath = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.SetupRequest} returns this + */ +proto.hiddifyrpc.SetupRequest.prototype.setBasePath = function(value) { + return jspb.Message.setProto3StringField(this, 1, value); +}; + + +/** + * optional string working_path = 2; + * @return {string} + */ +proto.hiddifyrpc.SetupRequest.prototype.getWorkingPath = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.SetupRequest} returns this + */ +proto.hiddifyrpc.SetupRequest.prototype.setWorkingPath = function(value) { + return jspb.Message.setProto3StringField(this, 2, value); +}; + + +/** + * optional string temp_path = 3; + * @return {string} + */ +proto.hiddifyrpc.SetupRequest.prototype.getTempPath = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.SetupRequest} returns this + */ +proto.hiddifyrpc.SetupRequest.prototype.setTempPath = function(value) { + return jspb.Message.setProto3StringField(this, 3, value); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.Response.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.Response.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.Response} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.Response.toObject = function(includeInstance, msg) { + var f, obj = { +responseCode: jspb.Message.getFieldWithDefault(msg, 1, 0), +message: jspb.Message.getFieldWithDefault(msg, 2, "") + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.Response} + */ +proto.hiddifyrpc.Response.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.Response; + return proto.hiddifyrpc.Response.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.Response} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.Response} + */ +proto.hiddifyrpc.Response.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {!proto.hiddifyrpc.ResponseCode} */ (reader.readEnum()); + msg.setResponseCode(value); + break; + case 2: + var value = /** @type {string} */ (reader.readString()); + msg.setMessage(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.Response.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.Response.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.Response} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.Response.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getResponseCode(); + if (f !== 0.0) { + writer.writeEnum( + 1, + f + ); + } + f = message.getMessage(); + if (f.length > 0) { + writer.writeString( + 2, + f + ); + } +}; + + +/** + * optional ResponseCode response_code = 1; + * @return {!proto.hiddifyrpc.ResponseCode} + */ +proto.hiddifyrpc.Response.prototype.getResponseCode = function() { + return /** @type {!proto.hiddifyrpc.ResponseCode} */ (jspb.Message.getFieldWithDefault(this, 1, 0)); +}; + + +/** + * @param {!proto.hiddifyrpc.ResponseCode} value + * @return {!proto.hiddifyrpc.Response} returns this + */ +proto.hiddifyrpc.Response.prototype.setResponseCode = function(value) { + return jspb.Message.setProto3EnumField(this, 1, value); +}; + + +/** + * optional string message = 2; + * @return {string} + */ +proto.hiddifyrpc.Response.prototype.getMessage = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.Response} returns this + */ +proto.hiddifyrpc.Response.prototype.setMessage = function(value) { + return jspb.Message.setProto3StringField(this, 2, value); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.SystemInfo.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.SystemInfo.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.SystemInfo} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.SystemInfo.toObject = function(includeInstance, msg) { + var f, obj = { +memory: jspb.Message.getFieldWithDefault(msg, 1, 0), +goroutines: jspb.Message.getFieldWithDefault(msg, 2, 0), +connectionsIn: jspb.Message.getFieldWithDefault(msg, 3, 0), +connectionsOut: jspb.Message.getFieldWithDefault(msg, 4, 0), +trafficAvailable: jspb.Message.getBooleanFieldWithDefault(msg, 5, false), +uplink: jspb.Message.getFieldWithDefault(msg, 6, 0), +downlink: jspb.Message.getFieldWithDefault(msg, 7, 0), +uplinkTotal: jspb.Message.getFieldWithDefault(msg, 8, 0), +downlinkTotal: jspb.Message.getFieldWithDefault(msg, 9, 0) + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.SystemInfo} + */ +proto.hiddifyrpc.SystemInfo.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.SystemInfo; + return proto.hiddifyrpc.SystemInfo.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.SystemInfo} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.SystemInfo} + */ +proto.hiddifyrpc.SystemInfo.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {number} */ (reader.readInt64()); + msg.setMemory(value); + break; + case 2: + var value = /** @type {number} */ (reader.readInt32()); + msg.setGoroutines(value); + break; + case 3: + var value = /** @type {number} */ (reader.readInt32()); + msg.setConnectionsIn(value); + break; + case 4: + var value = /** @type {number} */ (reader.readInt32()); + msg.setConnectionsOut(value); + break; + case 5: + var value = /** @type {boolean} */ (reader.readBool()); + msg.setTrafficAvailable(value); + break; + case 6: + var value = /** @type {number} */ (reader.readInt64()); + msg.setUplink(value); + break; + case 7: + var value = /** @type {number} */ (reader.readInt64()); + msg.setDownlink(value); + break; + case 8: + var value = /** @type {number} */ (reader.readInt64()); + msg.setUplinkTotal(value); + break; + case 9: + var value = /** @type {number} */ (reader.readInt64()); + msg.setDownlinkTotal(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.SystemInfo.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.SystemInfo.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.SystemInfo} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.SystemInfo.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getMemory(); + if (f !== 0) { + writer.writeInt64( + 1, + f + ); + } + f = message.getGoroutines(); + if (f !== 0) { + writer.writeInt32( + 2, + f + ); + } + f = message.getConnectionsIn(); + if (f !== 0) { + writer.writeInt32( + 3, + f + ); + } + f = message.getConnectionsOut(); + if (f !== 0) { + writer.writeInt32( + 4, + f + ); + } + f = message.getTrafficAvailable(); + if (f) { + writer.writeBool( + 5, + f + ); + } + f = message.getUplink(); + if (f !== 0) { + writer.writeInt64( + 6, + f + ); + } + f = message.getDownlink(); + if (f !== 0) { + writer.writeInt64( + 7, + f + ); + } + f = message.getUplinkTotal(); + if (f !== 0) { + writer.writeInt64( + 8, + f + ); + } + f = message.getDownlinkTotal(); + if (f !== 0) { + writer.writeInt64( + 9, + f + ); + } +}; + + +/** + * optional int64 memory = 1; + * @return {number} + */ +proto.hiddifyrpc.SystemInfo.prototype.getMemory = function() { + return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 1, 0)); +}; + + +/** + * @param {number} value + * @return {!proto.hiddifyrpc.SystemInfo} returns this + */ +proto.hiddifyrpc.SystemInfo.prototype.setMemory = function(value) { + return jspb.Message.setProto3IntField(this, 1, value); +}; + + +/** + * optional int32 goroutines = 2; + * @return {number} + */ +proto.hiddifyrpc.SystemInfo.prototype.getGoroutines = function() { + return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 2, 0)); +}; + + +/** + * @param {number} value + * @return {!proto.hiddifyrpc.SystemInfo} returns this + */ +proto.hiddifyrpc.SystemInfo.prototype.setGoroutines = function(value) { + return jspb.Message.setProto3IntField(this, 2, value); +}; + + +/** + * optional int32 connections_in = 3; + * @return {number} + */ +proto.hiddifyrpc.SystemInfo.prototype.getConnectionsIn = function() { + return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 3, 0)); +}; + + +/** + * @param {number} value + * @return {!proto.hiddifyrpc.SystemInfo} returns this + */ +proto.hiddifyrpc.SystemInfo.prototype.setConnectionsIn = function(value) { + return jspb.Message.setProto3IntField(this, 3, value); +}; + + +/** + * optional int32 connections_out = 4; + * @return {number} + */ +proto.hiddifyrpc.SystemInfo.prototype.getConnectionsOut = function() { + return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 4, 0)); +}; + + +/** + * @param {number} value + * @return {!proto.hiddifyrpc.SystemInfo} returns this + */ +proto.hiddifyrpc.SystemInfo.prototype.setConnectionsOut = function(value) { + return jspb.Message.setProto3IntField(this, 4, value); +}; + + +/** + * optional bool traffic_available = 5; + * @return {boolean} + */ +proto.hiddifyrpc.SystemInfo.prototype.getTrafficAvailable = function() { + return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 5, false)); +}; + + +/** + * @param {boolean} value + * @return {!proto.hiddifyrpc.SystemInfo} returns this + */ +proto.hiddifyrpc.SystemInfo.prototype.setTrafficAvailable = function(value) { + return jspb.Message.setProto3BooleanField(this, 5, value); +}; + + +/** + * optional int64 uplink = 6; + * @return {number} + */ +proto.hiddifyrpc.SystemInfo.prototype.getUplink = function() { + return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 6, 0)); +}; + + +/** + * @param {number} value + * @return {!proto.hiddifyrpc.SystemInfo} returns this + */ +proto.hiddifyrpc.SystemInfo.prototype.setUplink = function(value) { + return jspb.Message.setProto3IntField(this, 6, value); +}; + + +/** + * optional int64 downlink = 7; + * @return {number} + */ +proto.hiddifyrpc.SystemInfo.prototype.getDownlink = function() { + return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 7, 0)); +}; + + +/** + * @param {number} value + * @return {!proto.hiddifyrpc.SystemInfo} returns this + */ +proto.hiddifyrpc.SystemInfo.prototype.setDownlink = function(value) { + return jspb.Message.setProto3IntField(this, 7, value); +}; + + +/** + * optional int64 uplink_total = 8; + * @return {number} + */ +proto.hiddifyrpc.SystemInfo.prototype.getUplinkTotal = function() { + return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 8, 0)); +}; + + +/** + * @param {number} value + * @return {!proto.hiddifyrpc.SystemInfo} returns this + */ +proto.hiddifyrpc.SystemInfo.prototype.setUplinkTotal = function(value) { + return jspb.Message.setProto3IntField(this, 8, value); +}; + + +/** + * optional int64 downlink_total = 9; + * @return {number} + */ +proto.hiddifyrpc.SystemInfo.prototype.getDownlinkTotal = function() { + return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 9, 0)); +}; + + +/** + * @param {number} value + * @return {!proto.hiddifyrpc.SystemInfo} returns this + */ +proto.hiddifyrpc.SystemInfo.prototype.setDownlinkTotal = function(value) { + return jspb.Message.setProto3IntField(this, 9, value); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.OutboundGroupItem.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.OutboundGroupItem.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.OutboundGroupItem} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.OutboundGroupItem.toObject = function(includeInstance, msg) { + var f, obj = { +tag: jspb.Message.getFieldWithDefault(msg, 1, ""), +type: jspb.Message.getFieldWithDefault(msg, 2, ""), +urlTestTime: jspb.Message.getFieldWithDefault(msg, 3, 0), +urlTestDelay: jspb.Message.getFieldWithDefault(msg, 4, 0) + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.OutboundGroupItem} + */ +proto.hiddifyrpc.OutboundGroupItem.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.OutboundGroupItem; + return proto.hiddifyrpc.OutboundGroupItem.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.OutboundGroupItem} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.OutboundGroupItem} + */ +proto.hiddifyrpc.OutboundGroupItem.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {string} */ (reader.readString()); + msg.setTag(value); + break; + case 2: + var value = /** @type {string} */ (reader.readString()); + msg.setType(value); + break; + case 3: + var value = /** @type {number} */ (reader.readInt64()); + msg.setUrlTestTime(value); + break; + case 4: + var value = /** @type {number} */ (reader.readInt32()); + msg.setUrlTestDelay(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.OutboundGroupItem.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.OutboundGroupItem.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.OutboundGroupItem} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.OutboundGroupItem.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getTag(); + if (f.length > 0) { + writer.writeString( + 1, + f + ); + } + f = message.getType(); + if (f.length > 0) { + writer.writeString( + 2, + f + ); + } + f = message.getUrlTestTime(); + if (f !== 0) { + writer.writeInt64( + 3, + f + ); + } + f = message.getUrlTestDelay(); + if (f !== 0) { + writer.writeInt32( + 4, + f + ); + } +}; + + +/** + * optional string tag = 1; + * @return {string} + */ +proto.hiddifyrpc.OutboundGroupItem.prototype.getTag = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.OutboundGroupItem} returns this + */ +proto.hiddifyrpc.OutboundGroupItem.prototype.setTag = function(value) { + return jspb.Message.setProto3StringField(this, 1, value); +}; + + +/** + * optional string type = 2; + * @return {string} + */ +proto.hiddifyrpc.OutboundGroupItem.prototype.getType = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.OutboundGroupItem} returns this + */ +proto.hiddifyrpc.OutboundGroupItem.prototype.setType = function(value) { + return jspb.Message.setProto3StringField(this, 2, value); +}; + + +/** + * optional int64 url_test_time = 3; + * @return {number} + */ +proto.hiddifyrpc.OutboundGroupItem.prototype.getUrlTestTime = function() { + return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 3, 0)); +}; + + +/** + * @param {number} value + * @return {!proto.hiddifyrpc.OutboundGroupItem} returns this + */ +proto.hiddifyrpc.OutboundGroupItem.prototype.setUrlTestTime = function(value) { + return jspb.Message.setProto3IntField(this, 3, value); +}; + + +/** + * optional int32 url_test_delay = 4; + * @return {number} + */ +proto.hiddifyrpc.OutboundGroupItem.prototype.getUrlTestDelay = function() { + return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 4, 0)); +}; + + +/** + * @param {number} value + * @return {!proto.hiddifyrpc.OutboundGroupItem} returns this + */ +proto.hiddifyrpc.OutboundGroupItem.prototype.setUrlTestDelay = function(value) { + return jspb.Message.setProto3IntField(this, 4, value); +}; + + + +/** + * List of repeated fields within this message type. + * @private {!Array} + * @const + */ +proto.hiddifyrpc.OutboundGroup.repeatedFields_ = [4]; + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.OutboundGroup.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.OutboundGroup.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.OutboundGroup} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.OutboundGroup.toObject = function(includeInstance, msg) { + var f, obj = { +tag: jspb.Message.getFieldWithDefault(msg, 1, ""), +type: jspb.Message.getFieldWithDefault(msg, 2, ""), +selected: jspb.Message.getFieldWithDefault(msg, 3, ""), +itemsList: jspb.Message.toObjectList(msg.getItemsList(), + proto.hiddifyrpc.OutboundGroupItem.toObject, includeInstance) + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.OutboundGroup} + */ +proto.hiddifyrpc.OutboundGroup.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.OutboundGroup; + return proto.hiddifyrpc.OutboundGroup.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.OutboundGroup} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.OutboundGroup} + */ +proto.hiddifyrpc.OutboundGroup.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {string} */ (reader.readString()); + msg.setTag(value); + break; + case 2: + var value = /** @type {string} */ (reader.readString()); + msg.setType(value); + break; + case 3: + var value = /** @type {string} */ (reader.readString()); + msg.setSelected(value); + break; + case 4: + var value = new proto.hiddifyrpc.OutboundGroupItem; + reader.readMessage(value,proto.hiddifyrpc.OutboundGroupItem.deserializeBinaryFromReader); + msg.addItems(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.OutboundGroup.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.OutboundGroup.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.OutboundGroup} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.OutboundGroup.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getTag(); + if (f.length > 0) { + writer.writeString( + 1, + f + ); + } + f = message.getType(); + if (f.length > 0) { + writer.writeString( + 2, + f + ); + } + f = message.getSelected(); + if (f.length > 0) { + writer.writeString( + 3, + f + ); + } + f = message.getItemsList(); + if (f.length > 0) { + writer.writeRepeatedMessage( + 4, + f, + proto.hiddifyrpc.OutboundGroupItem.serializeBinaryToWriter + ); + } +}; + + +/** + * optional string tag = 1; + * @return {string} + */ +proto.hiddifyrpc.OutboundGroup.prototype.getTag = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.OutboundGroup} returns this + */ +proto.hiddifyrpc.OutboundGroup.prototype.setTag = function(value) { + return jspb.Message.setProto3StringField(this, 1, value); +}; + + +/** + * optional string type = 2; + * @return {string} + */ +proto.hiddifyrpc.OutboundGroup.prototype.getType = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.OutboundGroup} returns this + */ +proto.hiddifyrpc.OutboundGroup.prototype.setType = function(value) { + return jspb.Message.setProto3StringField(this, 2, value); +}; + + +/** + * optional string selected = 3; + * @return {string} + */ +proto.hiddifyrpc.OutboundGroup.prototype.getSelected = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.OutboundGroup} returns this + */ +proto.hiddifyrpc.OutboundGroup.prototype.setSelected = function(value) { + return jspb.Message.setProto3StringField(this, 3, value); +}; + + +/** + * repeated OutboundGroupItem items = 4; + * @return {!Array} + */ +proto.hiddifyrpc.OutboundGroup.prototype.getItemsList = function() { + return /** @type{!Array} */ ( + jspb.Message.getRepeatedWrapperField(this, proto.hiddifyrpc.OutboundGroupItem, 4)); +}; + + +/** + * @param {!Array} value + * @return {!proto.hiddifyrpc.OutboundGroup} returns this +*/ +proto.hiddifyrpc.OutboundGroup.prototype.setItemsList = function(value) { + return jspb.Message.setRepeatedWrapperField(this, 4, value); +}; + + +/** + * @param {!proto.hiddifyrpc.OutboundGroupItem=} opt_value + * @param {number=} opt_index + * @return {!proto.hiddifyrpc.OutboundGroupItem} + */ +proto.hiddifyrpc.OutboundGroup.prototype.addItems = function(opt_value, opt_index) { + return jspb.Message.addToRepeatedWrapperField(this, 4, opt_value, proto.hiddifyrpc.OutboundGroupItem, opt_index); +}; + + +/** + * Clears the list making it empty but non-null. + * @return {!proto.hiddifyrpc.OutboundGroup} returns this + */ +proto.hiddifyrpc.OutboundGroup.prototype.clearItemsList = function() { + return this.setItemsList([]); +}; + + + +/** + * List of repeated fields within this message type. + * @private {!Array} + * @const + */ +proto.hiddifyrpc.OutboundGroupList.repeatedFields_ = [1]; + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.OutboundGroupList.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.OutboundGroupList.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.OutboundGroupList} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.OutboundGroupList.toObject = function(includeInstance, msg) { + var f, obj = { +itemsList: jspb.Message.toObjectList(msg.getItemsList(), + proto.hiddifyrpc.OutboundGroup.toObject, includeInstance) + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.OutboundGroupList} + */ +proto.hiddifyrpc.OutboundGroupList.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.OutboundGroupList; + return proto.hiddifyrpc.OutboundGroupList.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.OutboundGroupList} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.OutboundGroupList} + */ +proto.hiddifyrpc.OutboundGroupList.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = new proto.hiddifyrpc.OutboundGroup; + reader.readMessage(value,proto.hiddifyrpc.OutboundGroup.deserializeBinaryFromReader); + msg.addItems(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.OutboundGroupList.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.OutboundGroupList.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.OutboundGroupList} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.OutboundGroupList.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getItemsList(); + if (f.length > 0) { + writer.writeRepeatedMessage( + 1, + f, + proto.hiddifyrpc.OutboundGroup.serializeBinaryToWriter + ); + } +}; + + +/** + * repeated OutboundGroup items = 1; + * @return {!Array} + */ +proto.hiddifyrpc.OutboundGroupList.prototype.getItemsList = function() { + return /** @type{!Array} */ ( + jspb.Message.getRepeatedWrapperField(this, proto.hiddifyrpc.OutboundGroup, 1)); +}; + + +/** + * @param {!Array} value + * @return {!proto.hiddifyrpc.OutboundGroupList} returns this +*/ +proto.hiddifyrpc.OutboundGroupList.prototype.setItemsList = function(value) { + return jspb.Message.setRepeatedWrapperField(this, 1, value); +}; + + +/** + * @param {!proto.hiddifyrpc.OutboundGroup=} opt_value + * @param {number=} opt_index + * @return {!proto.hiddifyrpc.OutboundGroup} + */ +proto.hiddifyrpc.OutboundGroupList.prototype.addItems = function(opt_value, opt_index) { + return jspb.Message.addToRepeatedWrapperField(this, 1, opt_value, proto.hiddifyrpc.OutboundGroup, opt_index); +}; + + +/** + * Clears the list making it empty but non-null. + * @return {!proto.hiddifyrpc.OutboundGroupList} returns this + */ +proto.hiddifyrpc.OutboundGroupList.prototype.clearItemsList = function() { + return this.setItemsList([]); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.WarpAccount.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.WarpAccount.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.WarpAccount} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.WarpAccount.toObject = function(includeInstance, msg) { + var f, obj = { +accountId: jspb.Message.getFieldWithDefault(msg, 1, ""), +accessToken: jspb.Message.getFieldWithDefault(msg, 2, "") + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.WarpAccount} + */ +proto.hiddifyrpc.WarpAccount.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.WarpAccount; + return proto.hiddifyrpc.WarpAccount.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.WarpAccount} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.WarpAccount} + */ +proto.hiddifyrpc.WarpAccount.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {string} */ (reader.readString()); + msg.setAccountId(value); + break; + case 2: + var value = /** @type {string} */ (reader.readString()); + msg.setAccessToken(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.WarpAccount.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.WarpAccount.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.WarpAccount} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.WarpAccount.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getAccountId(); + if (f.length > 0) { + writer.writeString( + 1, + f + ); + } + f = message.getAccessToken(); + if (f.length > 0) { + writer.writeString( + 2, + f + ); + } +}; + + +/** + * optional string account_id = 1; + * @return {string} + */ +proto.hiddifyrpc.WarpAccount.prototype.getAccountId = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.WarpAccount} returns this + */ +proto.hiddifyrpc.WarpAccount.prototype.setAccountId = function(value) { + return jspb.Message.setProto3StringField(this, 1, value); +}; + + +/** + * optional string access_token = 2; + * @return {string} + */ +proto.hiddifyrpc.WarpAccount.prototype.getAccessToken = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.WarpAccount} returns this + */ +proto.hiddifyrpc.WarpAccount.prototype.setAccessToken = function(value) { + return jspb.Message.setProto3StringField(this, 2, value); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.WarpWireguardConfig.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.WarpWireguardConfig.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.WarpWireguardConfig} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.WarpWireguardConfig.toObject = function(includeInstance, msg) { + var f, obj = { +privateKey: jspb.Message.getFieldWithDefault(msg, 1, ""), +localAddressIpv4: jspb.Message.getFieldWithDefault(msg, 2, ""), +localAddressIpv6: jspb.Message.getFieldWithDefault(msg, 3, ""), +peerPublicKey: jspb.Message.getFieldWithDefault(msg, 4, ""), +clientId: jspb.Message.getFieldWithDefault(msg, 5, "") + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.WarpWireguardConfig} + */ +proto.hiddifyrpc.WarpWireguardConfig.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.WarpWireguardConfig; + return proto.hiddifyrpc.WarpWireguardConfig.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.WarpWireguardConfig} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.WarpWireguardConfig} + */ +proto.hiddifyrpc.WarpWireguardConfig.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {string} */ (reader.readString()); + msg.setPrivateKey(value); + break; + case 2: + var value = /** @type {string} */ (reader.readString()); + msg.setLocalAddressIpv4(value); + break; + case 3: + var value = /** @type {string} */ (reader.readString()); + msg.setLocalAddressIpv6(value); + break; + case 4: + var value = /** @type {string} */ (reader.readString()); + msg.setPeerPublicKey(value); + break; + case 5: + var value = /** @type {string} */ (reader.readString()); + msg.setClientId(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.WarpWireguardConfig.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.WarpWireguardConfig.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.WarpWireguardConfig} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.WarpWireguardConfig.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getPrivateKey(); + if (f.length > 0) { + writer.writeString( + 1, + f + ); + } + f = message.getLocalAddressIpv4(); + if (f.length > 0) { + writer.writeString( + 2, + f + ); + } + f = message.getLocalAddressIpv6(); + if (f.length > 0) { + writer.writeString( + 3, + f + ); + } + f = message.getPeerPublicKey(); + if (f.length > 0) { + writer.writeString( + 4, + f + ); + } + f = message.getClientId(); + if (f.length > 0) { + writer.writeString( + 5, + f + ); + } +}; + + +/** + * optional string private_key = 1; + * @return {string} + */ +proto.hiddifyrpc.WarpWireguardConfig.prototype.getPrivateKey = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.WarpWireguardConfig} returns this + */ +proto.hiddifyrpc.WarpWireguardConfig.prototype.setPrivateKey = function(value) { + return jspb.Message.setProto3StringField(this, 1, value); +}; + + +/** + * optional string local_address_ipv4 = 2; + * @return {string} + */ +proto.hiddifyrpc.WarpWireguardConfig.prototype.getLocalAddressIpv4 = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.WarpWireguardConfig} returns this + */ +proto.hiddifyrpc.WarpWireguardConfig.prototype.setLocalAddressIpv4 = function(value) { + return jspb.Message.setProto3StringField(this, 2, value); +}; + + +/** + * optional string local_address_ipv6 = 3; + * @return {string} + */ +proto.hiddifyrpc.WarpWireguardConfig.prototype.getLocalAddressIpv6 = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.WarpWireguardConfig} returns this + */ +proto.hiddifyrpc.WarpWireguardConfig.prototype.setLocalAddressIpv6 = function(value) { + return jspb.Message.setProto3StringField(this, 3, value); +}; + + +/** + * optional string peer_public_key = 4; + * @return {string} + */ +proto.hiddifyrpc.WarpWireguardConfig.prototype.getPeerPublicKey = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 4, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.WarpWireguardConfig} returns this + */ +proto.hiddifyrpc.WarpWireguardConfig.prototype.setPeerPublicKey = function(value) { + return jspb.Message.setProto3StringField(this, 4, value); +}; + + +/** + * optional string client_id = 5; + * @return {string} + */ +proto.hiddifyrpc.WarpWireguardConfig.prototype.getClientId = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 5, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.WarpWireguardConfig} returns this + */ +proto.hiddifyrpc.WarpWireguardConfig.prototype.setClientId = function(value) { + return jspb.Message.setProto3StringField(this, 5, value); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.WarpGenerationResponse.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.WarpGenerationResponse.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.WarpGenerationResponse} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.WarpGenerationResponse.toObject = function(includeInstance, msg) { + var f, obj = { +account: (f = msg.getAccount()) && proto.hiddifyrpc.WarpAccount.toObject(includeInstance, f), +log: jspb.Message.getFieldWithDefault(msg, 2, ""), +config: (f = msg.getConfig()) && proto.hiddifyrpc.WarpWireguardConfig.toObject(includeInstance, f) + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.WarpGenerationResponse} + */ +proto.hiddifyrpc.WarpGenerationResponse.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.WarpGenerationResponse; + return proto.hiddifyrpc.WarpGenerationResponse.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.WarpGenerationResponse} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.WarpGenerationResponse} + */ +proto.hiddifyrpc.WarpGenerationResponse.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = new proto.hiddifyrpc.WarpAccount; + reader.readMessage(value,proto.hiddifyrpc.WarpAccount.deserializeBinaryFromReader); + msg.setAccount(value); + break; + case 2: + var value = /** @type {string} */ (reader.readString()); + msg.setLog(value); + break; + case 3: + var value = new proto.hiddifyrpc.WarpWireguardConfig; + reader.readMessage(value,proto.hiddifyrpc.WarpWireguardConfig.deserializeBinaryFromReader); + msg.setConfig(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.WarpGenerationResponse.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.WarpGenerationResponse.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.WarpGenerationResponse} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.WarpGenerationResponse.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getAccount(); + if (f != null) { + writer.writeMessage( + 1, + f, + proto.hiddifyrpc.WarpAccount.serializeBinaryToWriter + ); + } + f = message.getLog(); + if (f.length > 0) { + writer.writeString( + 2, + f + ); + } + f = message.getConfig(); + if (f != null) { + writer.writeMessage( + 3, + f, + proto.hiddifyrpc.WarpWireguardConfig.serializeBinaryToWriter + ); + } +}; + + +/** + * optional WarpAccount account = 1; + * @return {?proto.hiddifyrpc.WarpAccount} + */ +proto.hiddifyrpc.WarpGenerationResponse.prototype.getAccount = function() { + return /** @type{?proto.hiddifyrpc.WarpAccount} */ ( + jspb.Message.getWrapperField(this, proto.hiddifyrpc.WarpAccount, 1)); +}; + + +/** + * @param {?proto.hiddifyrpc.WarpAccount|undefined} value + * @return {!proto.hiddifyrpc.WarpGenerationResponse} returns this +*/ +proto.hiddifyrpc.WarpGenerationResponse.prototype.setAccount = function(value) { + return jspb.Message.setWrapperField(this, 1, value); +}; + + +/** + * Clears the message field making it undefined. + * @return {!proto.hiddifyrpc.WarpGenerationResponse} returns this + */ +proto.hiddifyrpc.WarpGenerationResponse.prototype.clearAccount = function() { + return this.setAccount(undefined); +}; + + +/** + * Returns whether this field is set. + * @return {boolean} + */ +proto.hiddifyrpc.WarpGenerationResponse.prototype.hasAccount = function() { + return jspb.Message.getField(this, 1) != null; +}; + + +/** + * optional string log = 2; + * @return {string} + */ +proto.hiddifyrpc.WarpGenerationResponse.prototype.getLog = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.WarpGenerationResponse} returns this + */ +proto.hiddifyrpc.WarpGenerationResponse.prototype.setLog = function(value) { + return jspb.Message.setProto3StringField(this, 2, value); +}; + + +/** + * optional WarpWireguardConfig config = 3; + * @return {?proto.hiddifyrpc.WarpWireguardConfig} + */ +proto.hiddifyrpc.WarpGenerationResponse.prototype.getConfig = function() { + return /** @type{?proto.hiddifyrpc.WarpWireguardConfig} */ ( + jspb.Message.getWrapperField(this, proto.hiddifyrpc.WarpWireguardConfig, 3)); +}; + + +/** + * @param {?proto.hiddifyrpc.WarpWireguardConfig|undefined} value + * @return {!proto.hiddifyrpc.WarpGenerationResponse} returns this +*/ +proto.hiddifyrpc.WarpGenerationResponse.prototype.setConfig = function(value) { + return jspb.Message.setWrapperField(this, 3, value); +}; + + +/** + * Clears the message field making it undefined. + * @return {!proto.hiddifyrpc.WarpGenerationResponse} returns this + */ +proto.hiddifyrpc.WarpGenerationResponse.prototype.clearConfig = function() { + return this.setConfig(undefined); +}; + + +/** + * Returns whether this field is set. + * @return {boolean} + */ +proto.hiddifyrpc.WarpGenerationResponse.prototype.hasConfig = function() { + return jspb.Message.getField(this, 3) != null; +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.SystemProxyStatus.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.SystemProxyStatus.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.SystemProxyStatus} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.SystemProxyStatus.toObject = function(includeInstance, msg) { + var f, obj = { +available: jspb.Message.getBooleanFieldWithDefault(msg, 1, false), +enabled: jspb.Message.getBooleanFieldWithDefault(msg, 2, false) + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.SystemProxyStatus} + */ +proto.hiddifyrpc.SystemProxyStatus.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.SystemProxyStatus; + return proto.hiddifyrpc.SystemProxyStatus.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.SystemProxyStatus} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.SystemProxyStatus} + */ +proto.hiddifyrpc.SystemProxyStatus.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {boolean} */ (reader.readBool()); + msg.setAvailable(value); + break; + case 2: + var value = /** @type {boolean} */ (reader.readBool()); + msg.setEnabled(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.SystemProxyStatus.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.SystemProxyStatus.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.SystemProxyStatus} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.SystemProxyStatus.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getAvailable(); + if (f) { + writer.writeBool( + 1, + f + ); + } + f = message.getEnabled(); + if (f) { + writer.writeBool( + 2, + f + ); + } +}; + + +/** + * optional bool available = 1; + * @return {boolean} + */ +proto.hiddifyrpc.SystemProxyStatus.prototype.getAvailable = function() { + return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 1, false)); +}; + + +/** + * @param {boolean} value + * @return {!proto.hiddifyrpc.SystemProxyStatus} returns this + */ +proto.hiddifyrpc.SystemProxyStatus.prototype.setAvailable = function(value) { + return jspb.Message.setProto3BooleanField(this, 1, value); +}; + + +/** + * optional bool enabled = 2; + * @return {boolean} + */ +proto.hiddifyrpc.SystemProxyStatus.prototype.getEnabled = function() { + return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 2, false)); +}; + + +/** + * @param {boolean} value + * @return {!proto.hiddifyrpc.SystemProxyStatus} returns this + */ +proto.hiddifyrpc.SystemProxyStatus.prototype.setEnabled = function(value) { + return jspb.Message.setProto3BooleanField(this, 2, value); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.ParseRequest.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.ParseRequest.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.ParseRequest} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.ParseRequest.toObject = function(includeInstance, msg) { + var f, obj = { +content: jspb.Message.getFieldWithDefault(msg, 1, ""), +configPath: jspb.Message.getFieldWithDefault(msg, 2, ""), +tempPath: jspb.Message.getFieldWithDefault(msg, 3, ""), +debug: jspb.Message.getBooleanFieldWithDefault(msg, 4, false) + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.ParseRequest} + */ +proto.hiddifyrpc.ParseRequest.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.ParseRequest; + return proto.hiddifyrpc.ParseRequest.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.ParseRequest} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.ParseRequest} + */ +proto.hiddifyrpc.ParseRequest.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {string} */ (reader.readString()); + msg.setContent(value); + break; + case 2: + var value = /** @type {string} */ (reader.readString()); + msg.setConfigPath(value); + break; + case 3: + var value = /** @type {string} */ (reader.readString()); + msg.setTempPath(value); + break; + case 4: + var value = /** @type {boolean} */ (reader.readBool()); + msg.setDebug(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.ParseRequest.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.ParseRequest.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.ParseRequest} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.ParseRequest.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getContent(); + if (f.length > 0) { + writer.writeString( + 1, + f + ); + } + f = message.getConfigPath(); + if (f.length > 0) { + writer.writeString( + 2, + f + ); + } + f = message.getTempPath(); + if (f.length > 0) { + writer.writeString( + 3, + f + ); + } + f = message.getDebug(); + if (f) { + writer.writeBool( + 4, + f + ); + } +}; + + +/** + * optional string content = 1; + * @return {string} + */ +proto.hiddifyrpc.ParseRequest.prototype.getContent = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.ParseRequest} returns this + */ +proto.hiddifyrpc.ParseRequest.prototype.setContent = function(value) { + return jspb.Message.setProto3StringField(this, 1, value); +}; + + +/** + * optional string config_path = 2; + * @return {string} + */ +proto.hiddifyrpc.ParseRequest.prototype.getConfigPath = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.ParseRequest} returns this + */ +proto.hiddifyrpc.ParseRequest.prototype.setConfigPath = function(value) { + return jspb.Message.setProto3StringField(this, 2, value); +}; + + +/** + * optional string temp_path = 3; + * @return {string} + */ +proto.hiddifyrpc.ParseRequest.prototype.getTempPath = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.ParseRequest} returns this + */ +proto.hiddifyrpc.ParseRequest.prototype.setTempPath = function(value) { + return jspb.Message.setProto3StringField(this, 3, value); +}; + + +/** + * optional bool debug = 4; + * @return {boolean} + */ +proto.hiddifyrpc.ParseRequest.prototype.getDebug = function() { + return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 4, false)); +}; + + +/** + * @param {boolean} value + * @return {!proto.hiddifyrpc.ParseRequest} returns this + */ +proto.hiddifyrpc.ParseRequest.prototype.setDebug = function(value) { + return jspb.Message.setProto3BooleanField(this, 4, value); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.ParseResponse.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.ParseResponse.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.ParseResponse} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.ParseResponse.toObject = function(includeInstance, msg) { + var f, obj = { +responseCode: jspb.Message.getFieldWithDefault(msg, 1, 0), +content: jspb.Message.getFieldWithDefault(msg, 2, ""), +message: jspb.Message.getFieldWithDefault(msg, 3, "") + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.ParseResponse} + */ +proto.hiddifyrpc.ParseResponse.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.ParseResponse; + return proto.hiddifyrpc.ParseResponse.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.ParseResponse} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.ParseResponse} + */ +proto.hiddifyrpc.ParseResponse.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {!proto.hiddifyrpc.ResponseCode} */ (reader.readEnum()); + msg.setResponseCode(value); + break; + case 2: + var value = /** @type {string} */ (reader.readString()); + msg.setContent(value); + break; + case 3: + var value = /** @type {string} */ (reader.readString()); + msg.setMessage(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.ParseResponse.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.ParseResponse.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.ParseResponse} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.ParseResponse.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getResponseCode(); + if (f !== 0.0) { + writer.writeEnum( + 1, + f + ); + } + f = message.getContent(); + if (f.length > 0) { + writer.writeString( + 2, + f + ); + } + f = message.getMessage(); + if (f.length > 0) { + writer.writeString( + 3, + f + ); + } +}; + + +/** + * optional ResponseCode response_code = 1; + * @return {!proto.hiddifyrpc.ResponseCode} + */ +proto.hiddifyrpc.ParseResponse.prototype.getResponseCode = function() { + return /** @type {!proto.hiddifyrpc.ResponseCode} */ (jspb.Message.getFieldWithDefault(this, 1, 0)); +}; + + +/** + * @param {!proto.hiddifyrpc.ResponseCode} value + * @return {!proto.hiddifyrpc.ParseResponse} returns this + */ +proto.hiddifyrpc.ParseResponse.prototype.setResponseCode = function(value) { + return jspb.Message.setProto3EnumField(this, 1, value); +}; + + +/** + * optional string content = 2; + * @return {string} + */ +proto.hiddifyrpc.ParseResponse.prototype.getContent = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.ParseResponse} returns this + */ +proto.hiddifyrpc.ParseResponse.prototype.setContent = function(value) { + return jspb.Message.setProto3StringField(this, 2, value); +}; + + +/** + * optional string message = 3; + * @return {string} + */ +proto.hiddifyrpc.ParseResponse.prototype.getMessage = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.ParseResponse} returns this + */ +proto.hiddifyrpc.ParseResponse.prototype.setMessage = function(value) { + return jspb.Message.setProto3StringField(this, 3, value); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.ChangeHiddifySettingsRequest.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.ChangeHiddifySettingsRequest.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.ChangeHiddifySettingsRequest} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.ChangeHiddifySettingsRequest.toObject = function(includeInstance, msg) { + var f, obj = { +hiddifySettingsJson: jspb.Message.getFieldWithDefault(msg, 1, "") + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.ChangeHiddifySettingsRequest} + */ +proto.hiddifyrpc.ChangeHiddifySettingsRequest.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.ChangeHiddifySettingsRequest; + return proto.hiddifyrpc.ChangeHiddifySettingsRequest.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.ChangeHiddifySettingsRequest} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.ChangeHiddifySettingsRequest} + */ +proto.hiddifyrpc.ChangeHiddifySettingsRequest.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {string} */ (reader.readString()); + msg.setHiddifySettingsJson(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.ChangeHiddifySettingsRequest.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.ChangeHiddifySettingsRequest.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.ChangeHiddifySettingsRequest} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.ChangeHiddifySettingsRequest.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getHiddifySettingsJson(); + if (f.length > 0) { + writer.writeString( + 1, + f + ); + } +}; + + +/** + * optional string hiddify_settings_json = 1; + * @return {string} + */ +proto.hiddifyrpc.ChangeHiddifySettingsRequest.prototype.getHiddifySettingsJson = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.ChangeHiddifySettingsRequest} returns this + */ +proto.hiddifyrpc.ChangeHiddifySettingsRequest.prototype.setHiddifySettingsJson = function(value) { + return jspb.Message.setProto3StringField(this, 1, value); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.GenerateConfigRequest.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.GenerateConfigRequest.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.GenerateConfigRequest} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.GenerateConfigRequest.toObject = function(includeInstance, msg) { + var f, obj = { +path: jspb.Message.getFieldWithDefault(msg, 1, ""), +tempPath: jspb.Message.getFieldWithDefault(msg, 2, ""), +debug: jspb.Message.getBooleanFieldWithDefault(msg, 3, false) + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.GenerateConfigRequest} + */ +proto.hiddifyrpc.GenerateConfigRequest.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.GenerateConfigRequest; + return proto.hiddifyrpc.GenerateConfigRequest.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.GenerateConfigRequest} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.GenerateConfigRequest} + */ +proto.hiddifyrpc.GenerateConfigRequest.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {string} */ (reader.readString()); + msg.setPath(value); + break; + case 2: + var value = /** @type {string} */ (reader.readString()); + msg.setTempPath(value); + break; + case 3: + var value = /** @type {boolean} */ (reader.readBool()); + msg.setDebug(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.GenerateConfigRequest.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.GenerateConfigRequest.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.GenerateConfigRequest} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.GenerateConfigRequest.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getPath(); + if (f.length > 0) { + writer.writeString( + 1, + f + ); + } + f = message.getTempPath(); + if (f.length > 0) { + writer.writeString( + 2, + f + ); + } + f = message.getDebug(); + if (f) { + writer.writeBool( + 3, + f + ); + } +}; + + +/** + * optional string path = 1; + * @return {string} + */ +proto.hiddifyrpc.GenerateConfigRequest.prototype.getPath = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.GenerateConfigRequest} returns this + */ +proto.hiddifyrpc.GenerateConfigRequest.prototype.setPath = function(value) { + return jspb.Message.setProto3StringField(this, 1, value); +}; + + +/** + * optional string temp_path = 2; + * @return {string} + */ +proto.hiddifyrpc.GenerateConfigRequest.prototype.getTempPath = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.GenerateConfigRequest} returns this + */ +proto.hiddifyrpc.GenerateConfigRequest.prototype.setTempPath = function(value) { + return jspb.Message.setProto3StringField(this, 2, value); +}; + + +/** + * optional bool debug = 3; + * @return {boolean} + */ +proto.hiddifyrpc.GenerateConfigRequest.prototype.getDebug = function() { + return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 3, false)); +}; + + +/** + * @param {boolean} value + * @return {!proto.hiddifyrpc.GenerateConfigRequest} returns this + */ +proto.hiddifyrpc.GenerateConfigRequest.prototype.setDebug = function(value) { + return jspb.Message.setProto3BooleanField(this, 3, value); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.GenerateConfigResponse.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.GenerateConfigResponse.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.GenerateConfigResponse} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.GenerateConfigResponse.toObject = function(includeInstance, msg) { + var f, obj = { +configContent: jspb.Message.getFieldWithDefault(msg, 1, "") + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.GenerateConfigResponse} + */ +proto.hiddifyrpc.GenerateConfigResponse.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.GenerateConfigResponse; + return proto.hiddifyrpc.GenerateConfigResponse.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.GenerateConfigResponse} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.GenerateConfigResponse} + */ +proto.hiddifyrpc.GenerateConfigResponse.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {string} */ (reader.readString()); + msg.setConfigContent(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.GenerateConfigResponse.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.GenerateConfigResponse.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.GenerateConfigResponse} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.GenerateConfigResponse.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getConfigContent(); + if (f.length > 0) { + writer.writeString( + 1, + f + ); + } +}; + + +/** + * optional string config_content = 1; + * @return {string} + */ +proto.hiddifyrpc.GenerateConfigResponse.prototype.getConfigContent = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.GenerateConfigResponse} returns this + */ +proto.hiddifyrpc.GenerateConfigResponse.prototype.setConfigContent = function(value) { + return jspb.Message.setProto3StringField(this, 1, value); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.SelectOutboundRequest.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.SelectOutboundRequest.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.SelectOutboundRequest} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.SelectOutboundRequest.toObject = function(includeInstance, msg) { + var f, obj = { +groupTag: jspb.Message.getFieldWithDefault(msg, 1, ""), +outboundTag: jspb.Message.getFieldWithDefault(msg, 2, "") + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.SelectOutboundRequest} + */ +proto.hiddifyrpc.SelectOutboundRequest.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.SelectOutboundRequest; + return proto.hiddifyrpc.SelectOutboundRequest.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.SelectOutboundRequest} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.SelectOutboundRequest} + */ +proto.hiddifyrpc.SelectOutboundRequest.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {string} */ (reader.readString()); + msg.setGroupTag(value); + break; + case 2: + var value = /** @type {string} */ (reader.readString()); + msg.setOutboundTag(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.SelectOutboundRequest.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.SelectOutboundRequest.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.SelectOutboundRequest} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.SelectOutboundRequest.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getGroupTag(); + if (f.length > 0) { + writer.writeString( + 1, + f + ); + } + f = message.getOutboundTag(); + if (f.length > 0) { + writer.writeString( + 2, + f + ); + } +}; + + +/** + * optional string group_tag = 1; + * @return {string} + */ +proto.hiddifyrpc.SelectOutboundRequest.prototype.getGroupTag = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.SelectOutboundRequest} returns this + */ +proto.hiddifyrpc.SelectOutboundRequest.prototype.setGroupTag = function(value) { + return jspb.Message.setProto3StringField(this, 1, value); +}; + + +/** + * optional string outbound_tag = 2; + * @return {string} + */ +proto.hiddifyrpc.SelectOutboundRequest.prototype.getOutboundTag = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.SelectOutboundRequest} returns this + */ +proto.hiddifyrpc.SelectOutboundRequest.prototype.setOutboundTag = function(value) { + return jspb.Message.setProto3StringField(this, 2, value); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.UrlTestRequest.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.UrlTestRequest.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.UrlTestRequest} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.UrlTestRequest.toObject = function(includeInstance, msg) { + var f, obj = { +groupTag: jspb.Message.getFieldWithDefault(msg, 1, "") + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.UrlTestRequest} + */ +proto.hiddifyrpc.UrlTestRequest.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.UrlTestRequest; + return proto.hiddifyrpc.UrlTestRequest.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.UrlTestRequest} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.UrlTestRequest} + */ +proto.hiddifyrpc.UrlTestRequest.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {string} */ (reader.readString()); + msg.setGroupTag(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.UrlTestRequest.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.UrlTestRequest.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.UrlTestRequest} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.UrlTestRequest.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getGroupTag(); + if (f.length > 0) { + writer.writeString( + 1, + f + ); + } +}; + + +/** + * optional string group_tag = 1; + * @return {string} + */ +proto.hiddifyrpc.UrlTestRequest.prototype.getGroupTag = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.UrlTestRequest} returns this + */ +proto.hiddifyrpc.UrlTestRequest.prototype.setGroupTag = function(value) { + return jspb.Message.setProto3StringField(this, 1, value); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.GenerateWarpConfigRequest.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.GenerateWarpConfigRequest.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.GenerateWarpConfigRequest} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.GenerateWarpConfigRequest.toObject = function(includeInstance, msg) { + var f, obj = { +licenseKey: jspb.Message.getFieldWithDefault(msg, 1, ""), +accountId: jspb.Message.getFieldWithDefault(msg, 2, ""), +accessToken: jspb.Message.getFieldWithDefault(msg, 3, "") + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.GenerateWarpConfigRequest} + */ +proto.hiddifyrpc.GenerateWarpConfigRequest.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.GenerateWarpConfigRequest; + return proto.hiddifyrpc.GenerateWarpConfigRequest.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.GenerateWarpConfigRequest} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.GenerateWarpConfigRequest} + */ +proto.hiddifyrpc.GenerateWarpConfigRequest.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {string} */ (reader.readString()); + msg.setLicenseKey(value); + break; + case 2: + var value = /** @type {string} */ (reader.readString()); + msg.setAccountId(value); + break; + case 3: + var value = /** @type {string} */ (reader.readString()); + msg.setAccessToken(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.GenerateWarpConfigRequest.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.GenerateWarpConfigRequest.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.GenerateWarpConfigRequest} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.GenerateWarpConfigRequest.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getLicenseKey(); + if (f.length > 0) { + writer.writeString( + 1, + f + ); + } + f = message.getAccountId(); + if (f.length > 0) { + writer.writeString( + 2, + f + ); + } + f = message.getAccessToken(); + if (f.length > 0) { + writer.writeString( + 3, + f + ); + } +}; + + +/** + * optional string license_key = 1; + * @return {string} + */ +proto.hiddifyrpc.GenerateWarpConfigRequest.prototype.getLicenseKey = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.GenerateWarpConfigRequest} returns this + */ +proto.hiddifyrpc.GenerateWarpConfigRequest.prototype.setLicenseKey = function(value) { + return jspb.Message.setProto3StringField(this, 1, value); +}; + + +/** + * optional string account_id = 2; + * @return {string} + */ +proto.hiddifyrpc.GenerateWarpConfigRequest.prototype.getAccountId = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.GenerateWarpConfigRequest} returns this + */ +proto.hiddifyrpc.GenerateWarpConfigRequest.prototype.setAccountId = function(value) { + return jspb.Message.setProto3StringField(this, 2, value); +}; + + +/** + * optional string access_token = 3; + * @return {string} + */ +proto.hiddifyrpc.GenerateWarpConfigRequest.prototype.getAccessToken = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.GenerateWarpConfigRequest} returns this + */ +proto.hiddifyrpc.GenerateWarpConfigRequest.prototype.setAccessToken = function(value) { + return jspb.Message.setProto3StringField(this, 3, value); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.SetSystemProxyEnabledRequest.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.SetSystemProxyEnabledRequest.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.SetSystemProxyEnabledRequest} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.SetSystemProxyEnabledRequest.toObject = function(includeInstance, msg) { + var f, obj = { +isEnabled: jspb.Message.getBooleanFieldWithDefault(msg, 1, false) + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.SetSystemProxyEnabledRequest} + */ +proto.hiddifyrpc.SetSystemProxyEnabledRequest.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.SetSystemProxyEnabledRequest; + return proto.hiddifyrpc.SetSystemProxyEnabledRequest.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.SetSystemProxyEnabledRequest} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.SetSystemProxyEnabledRequest} + */ +proto.hiddifyrpc.SetSystemProxyEnabledRequest.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {boolean} */ (reader.readBool()); + msg.setIsEnabled(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.SetSystemProxyEnabledRequest.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.SetSystemProxyEnabledRequest.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.SetSystemProxyEnabledRequest} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.SetSystemProxyEnabledRequest.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getIsEnabled(); + if (f) { + writer.writeBool( + 1, + f + ); + } +}; + + +/** + * optional bool is_enabled = 1; + * @return {boolean} + */ +proto.hiddifyrpc.SetSystemProxyEnabledRequest.prototype.getIsEnabled = function() { + return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 1, false)); +}; + + +/** + * @param {boolean} value + * @return {!proto.hiddifyrpc.SetSystemProxyEnabledRequest} returns this + */ +proto.hiddifyrpc.SetSystemProxyEnabledRequest.prototype.setIsEnabled = function(value) { + return jspb.Message.setProto3BooleanField(this, 1, value); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.LogMessage.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.LogMessage.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.LogMessage} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.LogMessage.toObject = function(includeInstance, msg) { + var f, obj = { +level: jspb.Message.getFieldWithDefault(msg, 1, 0), +type: jspb.Message.getFieldWithDefault(msg, 2, 0), +message: jspb.Message.getFieldWithDefault(msg, 3, "") + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.LogMessage} + */ +proto.hiddifyrpc.LogMessage.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.LogMessage; + return proto.hiddifyrpc.LogMessage.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.LogMessage} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.LogMessage} + */ +proto.hiddifyrpc.LogMessage.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {!proto.hiddifyrpc.LogLevel} */ (reader.readEnum()); + msg.setLevel(value); + break; + case 2: + var value = /** @type {!proto.hiddifyrpc.LogType} */ (reader.readEnum()); + msg.setType(value); + break; + case 3: + var value = /** @type {string} */ (reader.readString()); + msg.setMessage(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.LogMessage.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.LogMessage.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.LogMessage} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.LogMessage.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getLevel(); + if (f !== 0.0) { + writer.writeEnum( + 1, + f + ); + } + f = message.getType(); + if (f !== 0.0) { + writer.writeEnum( + 2, + f + ); + } + f = message.getMessage(); + if (f.length > 0) { + writer.writeString( + 3, + f + ); + } +}; + + +/** + * optional LogLevel level = 1; + * @return {!proto.hiddifyrpc.LogLevel} + */ +proto.hiddifyrpc.LogMessage.prototype.getLevel = function() { + return /** @type {!proto.hiddifyrpc.LogLevel} */ (jspb.Message.getFieldWithDefault(this, 1, 0)); +}; + + +/** + * @param {!proto.hiddifyrpc.LogLevel} value + * @return {!proto.hiddifyrpc.LogMessage} returns this + */ +proto.hiddifyrpc.LogMessage.prototype.setLevel = function(value) { + return jspb.Message.setProto3EnumField(this, 1, value); +}; + + +/** + * optional LogType type = 2; + * @return {!proto.hiddifyrpc.LogType} + */ +proto.hiddifyrpc.LogMessage.prototype.getType = function() { + return /** @type {!proto.hiddifyrpc.LogType} */ (jspb.Message.getFieldWithDefault(this, 2, 0)); +}; + + +/** + * @param {!proto.hiddifyrpc.LogType} value + * @return {!proto.hiddifyrpc.LogMessage} returns this + */ +proto.hiddifyrpc.LogMessage.prototype.setType = function(value) { + return jspb.Message.setProto3EnumField(this, 2, value); +}; + + +/** + * optional string message = 3; + * @return {string} + */ +proto.hiddifyrpc.LogMessage.prototype.getMessage = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.LogMessage} returns this + */ +proto.hiddifyrpc.LogMessage.prototype.setMessage = function(value) { + return jspb.Message.setProto3StringField(this, 3, value); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.StopRequest.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.StopRequest.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.StopRequest} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.StopRequest.toObject = function(includeInstance, msg) { + var f, obj = { + + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.StopRequest} + */ +proto.hiddifyrpc.StopRequest.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.StopRequest; + return proto.hiddifyrpc.StopRequest.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.StopRequest} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.StopRequest} + */ +proto.hiddifyrpc.StopRequest.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.StopRequest.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.StopRequest.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.StopRequest} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.StopRequest.serializeBinaryToWriter = function(message, writer) { + var f = undefined; +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.TunnelStartRequest.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.TunnelStartRequest.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.TunnelStartRequest} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.TunnelStartRequest.toObject = function(includeInstance, msg) { + var f, obj = { +ipv6: jspb.Message.getBooleanFieldWithDefault(msg, 1, false), +serverPort: jspb.Message.getFieldWithDefault(msg, 2, 0), +strictRoute: jspb.Message.getBooleanFieldWithDefault(msg, 3, false), +endpointIndependentNat: jspb.Message.getBooleanFieldWithDefault(msg, 4, false), +stack: jspb.Message.getFieldWithDefault(msg, 5, "") + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.TunnelStartRequest} + */ +proto.hiddifyrpc.TunnelStartRequest.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.TunnelStartRequest; + return proto.hiddifyrpc.TunnelStartRequest.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.TunnelStartRequest} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.TunnelStartRequest} + */ +proto.hiddifyrpc.TunnelStartRequest.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {boolean} */ (reader.readBool()); + msg.setIpv6(value); + break; + case 2: + var value = /** @type {number} */ (reader.readInt32()); + msg.setServerPort(value); + break; + case 3: + var value = /** @type {boolean} */ (reader.readBool()); + msg.setStrictRoute(value); + break; + case 4: + var value = /** @type {boolean} */ (reader.readBool()); + msg.setEndpointIndependentNat(value); + break; + case 5: + var value = /** @type {string} */ (reader.readString()); + msg.setStack(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.TunnelStartRequest.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.TunnelStartRequest.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.TunnelStartRequest} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.TunnelStartRequest.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getIpv6(); + if (f) { + writer.writeBool( + 1, + f + ); + } + f = message.getServerPort(); + if (f !== 0) { + writer.writeInt32( + 2, + f + ); + } + f = message.getStrictRoute(); + if (f) { + writer.writeBool( + 3, + f + ); + } + f = message.getEndpointIndependentNat(); + if (f) { + writer.writeBool( + 4, + f + ); + } + f = message.getStack(); + if (f.length > 0) { + writer.writeString( + 5, + f + ); + } +}; + + +/** + * optional bool ipv6 = 1; + * @return {boolean} + */ +proto.hiddifyrpc.TunnelStartRequest.prototype.getIpv6 = function() { + return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 1, false)); +}; + + +/** + * @param {boolean} value + * @return {!proto.hiddifyrpc.TunnelStartRequest} returns this + */ +proto.hiddifyrpc.TunnelStartRequest.prototype.setIpv6 = function(value) { + return jspb.Message.setProto3BooleanField(this, 1, value); +}; + + +/** + * optional int32 server_port = 2; + * @return {number} + */ +proto.hiddifyrpc.TunnelStartRequest.prototype.getServerPort = function() { + return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 2, 0)); +}; + + +/** + * @param {number} value + * @return {!proto.hiddifyrpc.TunnelStartRequest} returns this + */ +proto.hiddifyrpc.TunnelStartRequest.prototype.setServerPort = function(value) { + return jspb.Message.setProto3IntField(this, 2, value); +}; + + +/** + * optional bool strict_route = 3; + * @return {boolean} + */ +proto.hiddifyrpc.TunnelStartRequest.prototype.getStrictRoute = function() { + return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 3, false)); +}; + + +/** + * @param {boolean} value + * @return {!proto.hiddifyrpc.TunnelStartRequest} returns this + */ +proto.hiddifyrpc.TunnelStartRequest.prototype.setStrictRoute = function(value) { + return jspb.Message.setProto3BooleanField(this, 3, value); +}; + + +/** + * optional bool endpoint_independent_nat = 4; + * @return {boolean} + */ +proto.hiddifyrpc.TunnelStartRequest.prototype.getEndpointIndependentNat = function() { + return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 4, false)); +}; + + +/** + * @param {boolean} value + * @return {!proto.hiddifyrpc.TunnelStartRequest} returns this + */ +proto.hiddifyrpc.TunnelStartRequest.prototype.setEndpointIndependentNat = function(value) { + return jspb.Message.setProto3BooleanField(this, 4, value); +}; + + +/** + * optional string stack = 5; + * @return {string} + */ +proto.hiddifyrpc.TunnelStartRequest.prototype.getStack = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 5, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.TunnelStartRequest} returns this + */ +proto.hiddifyrpc.TunnelStartRequest.prototype.setStack = function(value) { + return jspb.Message.setProto3StringField(this, 5, value); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.TunnelResponse.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.TunnelResponse.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.TunnelResponse} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.TunnelResponse.toObject = function(includeInstance, msg) { + var f, obj = { +message: jspb.Message.getFieldWithDefault(msg, 1, "") + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.TunnelResponse} + */ +proto.hiddifyrpc.TunnelResponse.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.TunnelResponse; + return proto.hiddifyrpc.TunnelResponse.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.TunnelResponse} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.TunnelResponse} + */ +proto.hiddifyrpc.TunnelResponse.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {string} */ (reader.readString()); + msg.setMessage(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.TunnelResponse.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.TunnelResponse.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.TunnelResponse} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.TunnelResponse.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getMessage(); + if (f.length > 0) { + writer.writeString( + 1, + f + ); + } +}; + + +/** + * optional string message = 1; + * @return {string} + */ +proto.hiddifyrpc.TunnelResponse.prototype.getMessage = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.TunnelResponse} returns this + */ +proto.hiddifyrpc.TunnelResponse.prototype.setMessage = function(value) { + return jspb.Message.setProto3StringField(this, 1, value); +}; + + +/** + * @enum {number} + */ +proto.hiddifyrpc.CoreState = { + STOPPED: 0, + STARTING: 1, + STARTED: 2, + STOPPING: 3 +}; + +/** + * @enum {number} + */ +proto.hiddifyrpc.MessageType = { + EMPTY: 0, + EMPTY_CONFIGURATION: 1, + START_COMMAND_SERVER: 2, + CREATE_SERVICE: 3, + START_SERVICE: 4, + UNEXPECTED_ERROR: 5, + ALREADY_STARTED: 6, + ALREADY_STOPPED: 7, + INSTANCE_NOT_FOUND: 8, + INSTANCE_NOT_STOPPED: 9, + INSTANCE_NOT_STARTED: 10, + ERROR_BUILDING_CONFIG: 11, + ERROR_PARSING_CONFIG: 12, + ERROR_READING_CONFIG: 13 +}; + +/** + * @enum {number} + */ +proto.hiddifyrpc.LogLevel = { + DEBUG: 0, + INFO: 1, + WARNING: 2, + ERROR: 3, + FATAL: 4 +}; + +/** + * @enum {number} + */ +proto.hiddifyrpc.LogType = { + CORE: 0, + SERVICE: 1, + CONFIG: 2 +}; + +goog.object.extend(exports, proto.hiddifyrpc); + +},{"./base_pb.js":1,"google-protobuf":12}],12:[function(require,module,exports){ +(function (global){(function (){ +/* + + Copyright The Closure Library Authors. + SPDX-License-Identifier: Apache-2.0 +*/ +var aa="function"==typeof Object.defineProperties?Object.defineProperty:function(a,b,c){a!=Array.prototype&&a!=Object.prototype&&(a[b]=c.value)},e="undefined"!=typeof window&&window===this?this:"undefined"!=typeof global&&null!=global?global:this;function ba(a,b){if(b){var c=e;a=a.split(".");for(var d=0;d=arguments.length?Array.prototype.slice.call(a,b):Array.prototype.slice.call(a,b,c)};function sa(a,b,c,d){var f="Assertion failed";if(c){f+=": "+c;var h=d}else a&&(f+=": "+a,h=b);throw Error(f,h||[]);}function n(a,b,c){for(var d=[],f=2;f=a.length)return String.fromCharCode.apply(null,a);for(var b="",c=0;c>2;f=(f&3)<<4|m>>4;m=(m&15)<<2|B>>6;B&=63;t||(B=64,h||(m=64));c.push(b[M],b[f],b[m]||"",b[B]||"")}return c.join("")}function Da(a){var b=a.length,c=3*b/4;c%3?c=Math.floor(c):-1!="=.".indexOf(a[b-1])&&(c=-1!="=.".indexOf(a[b-2])?c-2:c-1);var d=new Uint8Array(c),f=0;Ea(a,function(h){d[f++]=h});return d.subarray(0,f)} +function Ea(a,b){function c(B){for(;d>4);64!=m&&(b(h<<4&240|m>>2),64!=t&&b(m<<6&192|t))}} +function Ca(){if(!x){x={};for(var a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""),b=["+/=","+/","-_=","-_.","-_"],c=0;5>c;c++){var d=a.concat(b[c].split(""));Aa[c]=d;for(var f=0;f>>0;a=Math.floor((a-b)/4294967296)>>>0;y=b;z=a}g("jspb.utils.splitUint64",Fa,void 0);function A(a){var b=0>a;a=Math.abs(a);var c=a>>>0;a=Math.floor((a-c)/4294967296);a>>>=0;b&&(a=~a>>>0,c=(~c>>>0)+1,4294967295a;a=2*Math.abs(a);Fa(a);a=y;var c=z;b&&(0==a?0==c?c=a=4294967295:(c--,a=4294967295):a--);y=a;z=c}g("jspb.utils.splitZigzag64",Ga,void 0); +function Ha(a){var b=0>a?1:0;a=b?-a:a;if(0===a)0<1/a?y=z=0:(z=0,y=2147483648);else if(isNaN(a))z=0,y=2147483647;else if(3.4028234663852886E38>>0;else if(1.1754943508222875E-38>a)a=Math.round(a/Math.pow(2,-149)),z=0,y=(b<<31|a)>>>0;else{var c=Math.floor(Math.log(a)/Math.LN2);a*=Math.pow(2,-c);a=Math.round(8388608*a);16777216<=a&&++c;z=0;y=(b<<31|c+127<<23|a&8388607)>>>0}}g("jspb.utils.splitFloat32",Ha,void 0); +function Ia(a){var b=0>a?1:0;a=b?-a:a;if(0===a)z=0<1/a?0:2147483648,y=0;else if(isNaN(a))z=2147483647,y=4294967295;else if(1.7976931348623157E308>>0,y=0;else if(2.2250738585072014E-308>a)a/=Math.pow(2,-1074),z=(b<<31|a/4294967296)>>>0,y=a>>>0;else{var c=a,d=0;if(2<=c)for(;2<=c&&1023>d;)d++,c/=2;else for(;1>c&&-1022>>0;y=4503599627370496*a>>>0}}g("jspb.utils.splitFloat64",Ia,void 0); +function C(a){var b=a.charCodeAt(4),c=a.charCodeAt(5),d=a.charCodeAt(6),f=a.charCodeAt(7);y=a.charCodeAt(0)+(a.charCodeAt(1)<<8)+(a.charCodeAt(2)<<16)+(a.charCodeAt(3)<<24)>>>0;z=b+(c<<8)+(d<<16)+(f<<24)>>>0}g("jspb.utils.splitHash64",C,void 0);function D(a,b){return 4294967296*b+(a>>>0)}g("jspb.utils.joinUint64",D,void 0);function E(a,b){var c=b&2147483648;c&&(a=~a+1>>>0,b=~b>>>0,0==a&&(b=b+1>>>0));a=D(a,b);return c?-a:a}g("jspb.utils.joinInt64",E,void 0); +function Ja(a,b,c){var d=b>>31;return c(a<<1^d,(b<<1|a>>>31)^d)}g("jspb.utils.toZigzag64",Ja,void 0);function Ka(a,b){return Ma(a,b,E)}g("jspb.utils.joinZigzag64",Ka,void 0);function Ma(a,b,c){var d=-(a&1);return c((a>>>1|b<<31)^d,b>>>1^d)}g("jspb.utils.fromZigzag64",Ma,void 0);function Na(a){var b=2*(a>>31)+1,c=a>>>23&255;a&=8388607;return 255==c?a?NaN:Infinity*b:0==c?b*Math.pow(2,-149)*a:b*Math.pow(2,c-150)*(a+Math.pow(2,23))}g("jspb.utils.joinFloat32",Na,void 0); +function Oa(a,b){var c=2*(b>>31)+1,d=b>>>20&2047;a=4294967296*(b&1048575)+a;return 2047==d?a?NaN:Infinity*c:0==d?c*Math.pow(2,-1074)*a:c*Math.pow(2,d-1075)*(a+4503599627370496)}g("jspb.utils.joinFloat64",Oa,void 0);function Pa(a,b){return String.fromCharCode(a>>>0&255,a>>>8&255,a>>>16&255,a>>>24&255,b>>>0&255,b>>>8&255,b>>>16&255,b>>>24&255)}g("jspb.utils.joinHash64",Pa,void 0);g("jspb.utils.DIGITS","0123456789abcdef".split(""),void 0); +function F(a,b){function c(f,h){f=f?String(f):"";return h?"0000000".slice(f.length)+f:f}if(2097151>=b)return""+D(a,b);var d=(a>>>24|b<<8)>>>0&16777215;b=b>>16&65535;a=(a&16777215)+6777216*d+6710656*b;d+=8147497*b;b*=2;1E7<=a&&(d+=Math.floor(a/1E7),a%=1E7);1E7<=d&&(b+=Math.floor(d/1E7),d%=1E7);return c(b,0)+c(d,b)+c(a,1)}g("jspb.utils.joinUnsignedDecimalString",F,void 0);function G(a,b){var c=b&2147483648;c&&(a=~a+1>>>0,b=~b+(0==a?1:0)>>>0);a=F(a,b);return c?"-"+a:a} +g("jspb.utils.joinSignedDecimalString",G,void 0);function Qa(a,b){C(a);a=y;var c=z;return b?G(a,c):F(a,c)}g("jspb.utils.hash64ToDecimalString",Qa,void 0);g("jspb.utils.hash64ArrayToDecimalStrings",function(a,b){for(var c=Array(a.length),d=0;dB&&(1!==m||0>>=8}function c(){for(var m=0;8>m;m++)f[m]=~f[m]&255}n(0a?48+a:87+a)} +function Sa(a){return 97<=a?a-97+10:a-48}g("jspb.utils.hash64ToHexString",function(a){var b=Array(18);b[0]="0";b[1]="x";for(var c=0;8>c;c++){var d=a.charCodeAt(7-c);b[2*c+2]=Ra(d>>4);b[2*c+3]=Ra(d&15)}return b.join("")},void 0);g("jspb.utils.hexStringToHash64",function(a){a=a.toLowerCase();n(18==a.length);n("0"==a[0]);n("x"==a[1]);for(var b="",c=0;8>c;c++)b=String.fromCharCode(16*Sa(a.charCodeAt(2*c+2))+Sa(a.charCodeAt(2*c+3)))+b;return b},void 0); +g("jspb.utils.hash64ToNumber",function(a,b){C(a);a=y;var c=z;return b?E(a,c):D(a,c)},void 0);g("jspb.utils.numberToHash64",function(a){A(a);return Pa(y,z)},void 0);g("jspb.utils.countVarints",function(a,b,c){for(var d=0,f=b;f>7;return c-b-d},void 0); +g("jspb.utils.countVarintFields",function(a,b,c,d){var f=0;d*=8;if(128>d)for(;b>=7}if(a[b++]!=h)break;for(f++;h=a[b++],0!=(h&128););}return f},void 0);function Ta(a,b,c,d,f){var h=0;if(128>d)for(;b>=7}if(a[b++]!=m)break;h++;b+=f}return h} +g("jspb.utils.countFixed32Fields",function(a,b,c,d){return Ta(a,b,c,8*d+5,4)},void 0);g("jspb.utils.countFixed64Fields",function(a,b,c,d){return Ta(a,b,c,8*d+1,8)},void 0);g("jspb.utils.countDelimitedFields",function(a,b,c,d){var f=0;for(d=8*d+2;b>=7}if(a[b++]!=h)break;f++;for(var m=0,t=1;h=a[b++],m+=(h&127)*t,t*=128,0!=(h&128););b+=m}return f},void 0); +g("jspb.utils.debugBytesToTextFormat",function(a){var b='"';if(a){a=Ua(a);for(var c=0;ca[c]&&(b+="0"),b+=a[c].toString(16)}return b+'"'},void 0); +g("jspb.utils.debugScalarToTextFormat",function(a){if("string"===typeof a){a=String(a);for(var b=['"'],c=0;cf))if(f=d,f in za)d=za[f];else if(f in ya)d=za[f]=ya[f];else{m=f.charCodeAt(0);if(31m)d=f;else{if(256>m){if(d="\\x",16>m||256m&&(d+="0");d+=m.toString(16).toUpperCase()}d=za[f]=d}m=d}b[h]=m}b.push('"');a=b.join("")}else a=a.toString();return a},void 0); +g("jspb.utils.stringToByteArray",function(a){for(var b=new Uint8Array(a.length),c=0;cVa.length&&Va.push(this)};I.prototype.free=I.prototype.Ca;I.prototype.clone=function(){return Wa(this.b,this.h,this.c-this.h)};I.prototype.clone=I.prototype.clone; +I.prototype.clear=function(){this.b=null;this.a=this.c=this.h=0;this.v=!1};I.prototype.clear=I.prototype.clear;I.prototype.Y=function(){return this.b};I.prototype.getBuffer=I.prototype.Y;I.prototype.H=function(a,b,c){this.b=Ua(a);this.h=void 0!==b?b:0;this.c=void 0!==c?this.h+c:this.b.length;this.a=this.h};I.prototype.setBlock=I.prototype.H;I.prototype.Db=function(){return this.c};I.prototype.getEnd=I.prototype.Db;I.prototype.setEnd=function(a){this.c=a};I.prototype.setEnd=I.prototype.setEnd; +I.prototype.reset=function(){this.a=this.h};I.prototype.reset=I.prototype.reset;I.prototype.B=function(){return this.a};I.prototype.getCursor=I.prototype.B;I.prototype.Ma=function(a){this.a=a};I.prototype.setCursor=I.prototype.Ma;I.prototype.advance=function(a){this.a+=a;n(this.a<=this.c)};I.prototype.advance=I.prototype.advance;I.prototype.ya=function(){return this.a==this.c};I.prototype.atEnd=I.prototype.ya;I.prototype.Qb=function(){return this.a>this.c};I.prototype.pastEnd=I.prototype.Qb; +I.prototype.getError=function(){return this.v||0>this.a||this.a>this.c};I.prototype.getError=I.prototype.getError;I.prototype.w=function(a){for(var b=128,c=0,d=0,f=0;4>f&&128<=b;f++)b=this.b[this.a++],c|=(b&127)<<7*f;128<=b&&(b=this.b[this.a++],c|=(b&127)<<28,d|=(b&127)>>4);if(128<=b)for(f=0;5>f&&128<=b;f++)b=this.b[this.a++],d|=(b&127)<<7*f+3;if(128>b)return a(c>>>0,d>>>0);p("Failed to read varint, encoding is invalid.");this.v=!0};I.prototype.readSplitVarint64=I.prototype.w; +I.prototype.ea=function(a){return this.w(function(b,c){return Ma(b,c,a)})};I.prototype.readSplitZigzagVarint64=I.prototype.ea;I.prototype.ta=function(a){var b=this.b,c=this.a;this.a+=8;for(var d=0,f=0,h=c+7;h>=c;h--)d=d<<8|b[h],f=f<<8|b[h+4];return a(d,f)};I.prototype.readSplitFixed64=I.prototype.ta;I.prototype.kb=function(){for(;this.b[this.a]&128;)this.a++;this.a++};I.prototype.skipVarint=I.prototype.kb;I.prototype.mb=function(a){for(;128>>=7;this.a--};I.prototype.unskipVarint=I.prototype.mb; +I.prototype.o=function(){var a=this.b;var b=a[this.a];var c=b&127;if(128>b)return this.a+=1,n(this.a<=this.c),c;b=a[this.a+1];c|=(b&127)<<7;if(128>b)return this.a+=2,n(this.a<=this.c),c;b=a[this.a+2];c|=(b&127)<<14;if(128>b)return this.a+=3,n(this.a<=this.c),c;b=a[this.a+3];c|=(b&127)<<21;if(128>b)return this.a+=4,n(this.a<=this.c),c;b=a[this.a+4];c|=(b&15)<<28;if(128>b)return this.a+=5,n(this.a<=this.c),c>>>0;this.a+=5;128<=a[this.a++]&&128<=a[this.a++]&&128<=a[this.a++]&&128<=a[this.a++]&&128<= +a[this.a++]&&n(!1);n(this.a<=this.c);return c};I.prototype.readUnsignedVarint32=I.prototype.o;I.prototype.da=function(){return~~this.o()};I.prototype.readSignedVarint32=I.prototype.da;I.prototype.O=function(){return this.o().toString()};I.prototype.Ea=function(){return this.da().toString()};I.prototype.readSignedVarint32String=I.prototype.Ea;I.prototype.Ia=function(){var a=this.o();return a>>>1^-(a&1)};I.prototype.readZigzagVarint32=I.prototype.Ia;I.prototype.Ga=function(){return this.w(D)}; +I.prototype.readUnsignedVarint64=I.prototype.Ga;I.prototype.Ha=function(){return this.w(F)};I.prototype.readUnsignedVarint64String=I.prototype.Ha;I.prototype.sa=function(){return this.w(E)};I.prototype.readSignedVarint64=I.prototype.sa;I.prototype.Fa=function(){return this.w(G)};I.prototype.readSignedVarint64String=I.prototype.Fa;I.prototype.Ja=function(){return this.w(Ka)};I.prototype.readZigzagVarint64=I.prototype.Ja;I.prototype.fb=function(){return this.ea(Pa)}; +I.prototype.readZigzagVarintHash64=I.prototype.fb;I.prototype.Ka=function(){return this.ea(G)};I.prototype.readZigzagVarint64String=I.prototype.Ka;I.prototype.Gc=function(){var a=this.b[this.a];this.a+=1;n(this.a<=this.c);return a};I.prototype.readUint8=I.prototype.Gc;I.prototype.Ec=function(){var a=this.b[this.a],b=this.b[this.a+1];this.a+=2;n(this.a<=this.c);return a<<0|b<<8};I.prototype.readUint16=I.prototype.Ec; +I.prototype.m=function(){var a=this.b[this.a],b=this.b[this.a+1],c=this.b[this.a+2],d=this.b[this.a+3];this.a+=4;n(this.a<=this.c);return(a<<0|b<<8|c<<16|d<<24)>>>0};I.prototype.readUint32=I.prototype.m;I.prototype.ga=function(){var a=this.m(),b=this.m();return D(a,b)};I.prototype.readUint64=I.prototype.ga;I.prototype.ha=function(){var a=this.m(),b=this.m();return F(a,b)};I.prototype.readUint64String=I.prototype.ha; +I.prototype.Xb=function(){var a=this.b[this.a];this.a+=1;n(this.a<=this.c);return a<<24>>24};I.prototype.readInt8=I.prototype.Xb;I.prototype.Vb=function(){var a=this.b[this.a],b=this.b[this.a+1];this.a+=2;n(this.a<=this.c);return(a<<0|b<<8)<<16>>16};I.prototype.readInt16=I.prototype.Vb;I.prototype.P=function(){var a=this.b[this.a],b=this.b[this.a+1],c=this.b[this.a+2],d=this.b[this.a+3];this.a+=4;n(this.a<=this.c);return a<<0|b<<8|c<<16|d<<24};I.prototype.readInt32=I.prototype.P; +I.prototype.ba=function(){var a=this.m(),b=this.m();return E(a,b)};I.prototype.readInt64=I.prototype.ba;I.prototype.ca=function(){var a=this.m(),b=this.m();return G(a,b)};I.prototype.readInt64String=I.prototype.ca;I.prototype.aa=function(){var a=this.m();return Na(a,0)};I.prototype.readFloat=I.prototype.aa;I.prototype.Z=function(){var a=this.m(),b=this.m();return Oa(a,b)};I.prototype.readDouble=I.prototype.Z;I.prototype.pa=function(){return!!this.b[this.a++]};I.prototype.readBool=I.prototype.pa; +I.prototype.ra=function(){return this.da()};I.prototype.readEnum=I.prototype.ra; +I.prototype.fa=function(a){var b=this.b,c=this.a;a=c+a;for(var d=[],f="";ch)d.push(h);else if(192>h)continue;else if(224>h){var m=b[c++];d.push((h&31)<<6|m&63)}else if(240>h){m=b[c++];var t=b[c++];d.push((h&15)<<12|(m&63)<<6|t&63)}else if(248>h){m=b[c++];t=b[c++];var B=b[c++];h=(h&7)<<18|(m&63)<<12|(t&63)<<6|B&63;h-=65536;d.push((h>>10&1023)+55296,(h&1023)+56320)}8192<=d.length&&(f+=String.fromCharCode.apply(null,d),d.length=0)}f+=xa(d);this.a=c;return f}; +I.prototype.readString=I.prototype.fa;I.prototype.Dc=function(){var a=this.o();return this.fa(a)};I.prototype.readStringWithLength=I.prototype.Dc;I.prototype.qa=function(a){if(0>a||this.a+a>this.b.length)return this.v=!0,p("Invalid byte length!"),new Uint8Array(0);var b=this.b.subarray(this.a,this.a+a);this.a+=a;n(this.a<=this.c);return b};I.prototype.readBytes=I.prototype.qa;I.prototype.ia=function(){return this.w(Pa)};I.prototype.readVarintHash64=I.prototype.ia; +I.prototype.$=function(){var a=this.b,b=this.a,c=a[b],d=a[b+1],f=a[b+2],h=a[b+3],m=a[b+4],t=a[b+5],B=a[b+6];a=a[b+7];this.a+=8;return String.fromCharCode(c,d,f,h,m,t,B,a)};I.prototype.readFixedHash64=I.prototype.$;function J(a,b,c){this.a=Wa(a,b,c);this.O=this.a.B();this.b=this.c=-1;this.h=!1;this.v=null}g("jspb.BinaryReader",J,void 0);var K=[];J.clearInstanceCache=function(){K=[]};J.getInstanceCacheLength=function(){return K.length};function Xa(a,b,c){if(K.length){var d=K.pop();a&&d.a.H(a,b,c);return d}return new J(a,b,c)}J.alloc=Xa;J.prototype.zb=Xa;J.prototype.alloc=J.prototype.zb;J.prototype.Ca=function(){this.a.clear();this.b=this.c=-1;this.h=!1;this.v=null;100>K.length&&K.push(this)}; +J.prototype.free=J.prototype.Ca;J.prototype.Fb=function(){return this.O};J.prototype.getFieldCursor=J.prototype.Fb;J.prototype.B=function(){return this.a.B()};J.prototype.getCursor=J.prototype.B;J.prototype.Y=function(){return this.a.Y()};J.prototype.getBuffer=J.prototype.Y;J.prototype.Hb=function(){return this.c};J.prototype.getFieldNumber=J.prototype.Hb;J.prototype.Lb=function(){return this.b};J.prototype.getWireType=J.prototype.Lb;J.prototype.Mb=function(){return 2==this.b}; +J.prototype.isDelimited=J.prototype.Mb;J.prototype.bb=function(){return 4==this.b};J.prototype.isEndGroup=J.prototype.bb;J.prototype.getError=function(){return this.h||this.a.getError()};J.prototype.getError=J.prototype.getError;J.prototype.H=function(a,b,c){this.a.H(a,b,c);this.b=this.c=-1};J.prototype.setBlock=J.prototype.H;J.prototype.reset=function(){this.a.reset();this.b=this.c=-1};J.prototype.reset=J.prototype.reset;J.prototype.advance=function(a){this.a.advance(a)};J.prototype.advance=J.prototype.advance; +J.prototype.oa=function(){if(this.a.ya())return!1;if(this.getError())return p("Decoder hit an error"),!1;this.O=this.a.B();var a=this.a.o(),b=a>>>3;a&=7;if(0!=a&&5!=a&&1!=a&&2!=a&&3!=a&&4!=a)return p("Invalid wire type: %s (at position %s)",a,this.O),this.h=!0,!1;this.c=b;this.b=a;return!0};J.prototype.nextField=J.prototype.oa;J.prototype.Oa=function(){this.a.mb(this.c<<3|this.b)};J.prototype.unskipHeader=J.prototype.Oa; +J.prototype.Lc=function(){var a=this.c;for(this.Oa();this.oa()&&this.c==a;)this.C();this.a.ya()||this.Oa()};J.prototype.skipMatchingFields=J.prototype.Lc;J.prototype.lb=function(){0!=this.b?(p("Invalid wire type for skipVarintField"),this.C()):this.a.kb()};J.prototype.skipVarintField=J.prototype.lb;J.prototype.gb=function(){if(2!=this.b)p("Invalid wire type for skipDelimitedField"),this.C();else{var a=this.a.o();this.a.advance(a)}};J.prototype.skipDelimitedField=J.prototype.gb; +J.prototype.hb=function(){5!=this.b?(p("Invalid wire type for skipFixed32Field"),this.C()):this.a.advance(4)};J.prototype.skipFixed32Field=J.prototype.hb;J.prototype.ib=function(){1!=this.b?(p("Invalid wire type for skipFixed64Field"),this.C()):this.a.advance(8)};J.prototype.skipFixed64Field=J.prototype.ib;J.prototype.jb=function(){var a=this.c;do{if(!this.oa()){p("Unmatched start-group tag: stream EOF");this.h=!0;break}if(4==this.b){this.c!=a&&(p("Unmatched end-group tag"),this.h=!0);break}this.C()}while(1)}; +J.prototype.skipGroup=J.prototype.jb;J.prototype.C=function(){switch(this.b){case 0:this.lb();break;case 1:this.ib();break;case 2:this.gb();break;case 5:this.hb();break;case 3:this.jb();break;default:p("Invalid wire encoding for field.")}};J.prototype.skipField=J.prototype.C;J.prototype.Hc=function(a,b){null===this.v&&(this.v={});n(!this.v[a]);this.v[a]=b};J.prototype.registerReadCallback=J.prototype.Hc;J.prototype.Ic=function(a){n(null!==this.v);a=this.v[a];n(a);return a(this)}; +J.prototype.runReadCallback=J.prototype.Ic;J.prototype.Yb=function(a,b){n(2==this.b);var c=this.a.c,d=this.a.o();d=this.a.B()+d;this.a.setEnd(d);b(a,this);this.a.Ma(d);this.a.setEnd(c)};J.prototype.readMessage=J.prototype.Yb;J.prototype.Ub=function(a,b,c){n(3==this.b);n(this.c==a);c(b,this);this.h||4==this.b||(p("Group submessage did not end with an END_GROUP tag"),this.h=!0)};J.prototype.readGroup=J.prototype.Ub; +J.prototype.Gb=function(){n(2==this.b);var a=this.a.o(),b=this.a.B(),c=b+a;a=Wa(this.a.Y(),b,a);this.a.Ma(c);return a};J.prototype.getFieldDecoder=J.prototype.Gb;J.prototype.P=function(){n(0==this.b);return this.a.da()};J.prototype.readInt32=J.prototype.P;J.prototype.Wb=function(){n(0==this.b);return this.a.Ea()};J.prototype.readInt32String=J.prototype.Wb;J.prototype.ba=function(){n(0==this.b);return this.a.sa()};J.prototype.readInt64=J.prototype.ba;J.prototype.ca=function(){n(0==this.b);return this.a.Fa()}; +J.prototype.readInt64String=J.prototype.ca;J.prototype.m=function(){n(0==this.b);return this.a.o()};J.prototype.readUint32=J.prototype.m;J.prototype.Fc=function(){n(0==this.b);return this.a.O()};J.prototype.readUint32String=J.prototype.Fc;J.prototype.ga=function(){n(0==this.b);return this.a.Ga()};J.prototype.readUint64=J.prototype.ga;J.prototype.ha=function(){n(0==this.b);return this.a.Ha()};J.prototype.readUint64String=J.prototype.ha;J.prototype.zc=function(){n(0==this.b);return this.a.Ia()}; +J.prototype.readSint32=J.prototype.zc;J.prototype.Ac=function(){n(0==this.b);return this.a.Ja()};J.prototype.readSint64=J.prototype.Ac;J.prototype.Bc=function(){n(0==this.b);return this.a.Ka()};J.prototype.readSint64String=J.prototype.Bc;J.prototype.Rb=function(){n(5==this.b);return this.a.m()};J.prototype.readFixed32=J.prototype.Rb;J.prototype.Sb=function(){n(1==this.b);return this.a.ga()};J.prototype.readFixed64=J.prototype.Sb;J.prototype.Tb=function(){n(1==this.b);return this.a.ha()}; +J.prototype.readFixed64String=J.prototype.Tb;J.prototype.vc=function(){n(5==this.b);return this.a.P()};J.prototype.readSfixed32=J.prototype.vc;J.prototype.wc=function(){n(5==this.b);return this.a.P().toString()};J.prototype.readSfixed32String=J.prototype.wc;J.prototype.xc=function(){n(1==this.b);return this.a.ba()};J.prototype.readSfixed64=J.prototype.xc;J.prototype.yc=function(){n(1==this.b);return this.a.ca()};J.prototype.readSfixed64String=J.prototype.yc; +J.prototype.aa=function(){n(5==this.b);return this.a.aa()};J.prototype.readFloat=J.prototype.aa;J.prototype.Z=function(){n(1==this.b);return this.a.Z()};J.prototype.readDouble=J.prototype.Z;J.prototype.pa=function(){n(0==this.b);return!!this.a.o()};J.prototype.readBool=J.prototype.pa;J.prototype.ra=function(){n(0==this.b);return this.a.sa()};J.prototype.readEnum=J.prototype.ra;J.prototype.fa=function(){n(2==this.b);var a=this.a.o();return this.a.fa(a)};J.prototype.readString=J.prototype.fa; +J.prototype.qa=function(){n(2==this.b);var a=this.a.o();return this.a.qa(a)};J.prototype.readBytes=J.prototype.qa;J.prototype.ia=function(){n(0==this.b);return this.a.ia()};J.prototype.readVarintHash64=J.prototype.ia;J.prototype.Cc=function(){n(0==this.b);return this.a.fb()};J.prototype.readSintHash64=J.prototype.Cc;J.prototype.w=function(a){n(0==this.b);return this.a.w(a)};J.prototype.readSplitVarint64=J.prototype.w; +J.prototype.ea=function(a){n(0==this.b);return this.a.w(function(b,c){return Ma(b,c,a)})};J.prototype.readSplitZigzagVarint64=J.prototype.ea;J.prototype.$=function(){n(1==this.b);return this.a.$()};J.prototype.readFixedHash64=J.prototype.$;J.prototype.ta=function(a){n(1==this.b);return this.a.ta(a)};J.prototype.readSplitFixed64=J.prototype.ta;function L(a,b){n(2==a.b);var c=a.a.o();c=a.a.B()+c;for(var d=[];a.a.B()b.length?c.length:b.length;a.b&&(d[0]=a.b,f=1);for(;fa);for(n(0<=b&&4294967296>b);0>>7|b<<25)>>>0,b>>>=7;this.a.push(a)};S.prototype.writeSplitVarint64=S.prototype.l; +S.prototype.A=function(a,b){n(a==Math.floor(a));n(b==Math.floor(b));n(0<=a&&4294967296>a);n(0<=b&&4294967296>b);this.s(a);this.s(b)};S.prototype.writeSplitFixed64=S.prototype.A;S.prototype.j=function(a){n(a==Math.floor(a));for(n(0<=a&&4294967296>a);127>>=7;this.a.push(a)};S.prototype.writeUnsignedVarint32=S.prototype.j;S.prototype.M=function(a){n(a==Math.floor(a));n(-2147483648<=a&&2147483648>a);if(0<=a)this.j(a);else{for(var b=0;9>b;b++)this.a.push(a&127|128),a>>=7;this.a.push(1)}}; +S.prototype.writeSignedVarint32=S.prototype.M;S.prototype.va=function(a){n(a==Math.floor(a));n(0<=a&&1.8446744073709552E19>a);A(a);this.l(y,z)};S.prototype.writeUnsignedVarint64=S.prototype.va;S.prototype.ua=function(a){n(a==Math.floor(a));n(-9223372036854775808<=a&&0x7fffffffffffffff>a);A(a);this.l(y,z)};S.prototype.writeSignedVarint64=S.prototype.ua;S.prototype.wa=function(a){n(a==Math.floor(a));n(-2147483648<=a&&2147483648>a);this.j((a<<1^a>>31)>>>0)};S.prototype.writeZigzagVarint32=S.prototype.wa; +S.prototype.xa=function(a){n(a==Math.floor(a));n(-9223372036854775808<=a&&0x7fffffffffffffff>a);Ga(a);this.l(y,z)};S.prototype.writeZigzagVarint64=S.prototype.xa;S.prototype.Ta=function(a){this.W(H(a))};S.prototype.writeZigzagVarint64String=S.prototype.Ta;S.prototype.W=function(a){var b=this;C(a);Ja(y,z,function(c,d){b.l(c>>>0,d>>>0)})};S.prototype.writeZigzagVarintHash64=S.prototype.W;S.prototype.be=function(a){n(a==Math.floor(a));n(0<=a&&256>a);this.a.push(a>>>0&255)};S.prototype.writeUint8=S.prototype.be; +S.prototype.ae=function(a){n(a==Math.floor(a));n(0<=a&&65536>a);this.a.push(a>>>0&255);this.a.push(a>>>8&255)};S.prototype.writeUint16=S.prototype.ae;S.prototype.s=function(a){n(a==Math.floor(a));n(0<=a&&4294967296>a);this.a.push(a>>>0&255);this.a.push(a>>>8&255);this.a.push(a>>>16&255);this.a.push(a>>>24&255)};S.prototype.writeUint32=S.prototype.s;S.prototype.V=function(a){n(a==Math.floor(a));n(0<=a&&1.8446744073709552E19>a);Fa(a);this.s(y);this.s(z)};S.prototype.writeUint64=S.prototype.V; +S.prototype.Qc=function(a){n(a==Math.floor(a));n(-128<=a&&128>a);this.a.push(a>>>0&255)};S.prototype.writeInt8=S.prototype.Qc;S.prototype.Pc=function(a){n(a==Math.floor(a));n(-32768<=a&&32768>a);this.a.push(a>>>0&255);this.a.push(a>>>8&255)};S.prototype.writeInt16=S.prototype.Pc;S.prototype.S=function(a){n(a==Math.floor(a));n(-2147483648<=a&&2147483648>a);this.a.push(a>>>0&255);this.a.push(a>>>8&255);this.a.push(a>>>16&255);this.a.push(a>>>24&255)};S.prototype.writeInt32=S.prototype.S; +S.prototype.T=function(a){n(a==Math.floor(a));n(-9223372036854775808<=a&&0x7fffffffffffffff>a);A(a);this.A(y,z)};S.prototype.writeInt64=S.prototype.T;S.prototype.ka=function(a){n(a==Math.floor(a));n(-9223372036854775808<=+a&&0x7fffffffffffffff>+a);C(H(a));this.A(y,z)};S.prototype.writeInt64String=S.prototype.ka;S.prototype.L=function(a){n(Infinity===a||-Infinity===a||isNaN(a)||-3.4028234663852886E38<=a&&3.4028234663852886E38>=a);Ha(a);this.s(y)};S.prototype.writeFloat=S.prototype.L; +S.prototype.J=function(a){n(Infinity===a||-Infinity===a||isNaN(a)||-1.7976931348623157E308<=a&&1.7976931348623157E308>=a);Ia(a);this.s(y);this.s(z)};S.prototype.writeDouble=S.prototype.J;S.prototype.I=function(a){n("boolean"===typeof a||"number"===typeof a);this.a.push(a?1:0)};S.prototype.writeBool=S.prototype.I;S.prototype.R=function(a){n(a==Math.floor(a));n(-2147483648<=a&&2147483648>a);this.M(a)};S.prototype.writeEnum=S.prototype.R;S.prototype.ja=function(a){this.a.push.apply(this.a,a)}; +S.prototype.writeBytes=S.prototype.ja;S.prototype.N=function(a){C(a);this.l(y,z)};S.prototype.writeVarintHash64=S.prototype.N;S.prototype.K=function(a){C(a);this.s(y);this.s(z)};S.prototype.writeFixedHash64=S.prototype.K; +S.prototype.U=function(a){var b=this.a.length;ta(a);for(var c=0;cd)this.a.push(d);else if(2048>d)this.a.push(d>>6|192),this.a.push(d&63|128);else if(65536>d)if(55296<=d&&56319>=d&&c+1=f&&(d=1024*(d-55296)+f-56320+65536,this.a.push(d>>18|240),this.a.push(d>>12&63|128),this.a.push(d>>6&63|128),this.a.push(d&63|128),c++)}else this.a.push(d>>12|224),this.a.push(d>>6&63|128),this.a.push(d&63|128)}return this.a.length- +b};S.prototype.writeString=S.prototype.U;function T(a,b){this.lo=a;this.hi=b}g("jspb.arith.UInt64",T,void 0);T.prototype.cmp=function(a){return this.hi>>1|(this.hi&1)<<31)>>>0,this.hi>>>1>>>0)};T.prototype.rightShift=T.prototype.La;T.prototype.Da=function(){return new T(this.lo<<1>>>0,(this.hi<<1|this.lo>>>31)>>>0)};T.prototype.leftShift=T.prototype.Da; +T.prototype.cb=function(){return!!(this.hi&2147483648)};T.prototype.msb=T.prototype.cb;T.prototype.Ob=function(){return!!(this.lo&1)};T.prototype.lsb=T.prototype.Ob;T.prototype.Ua=function(){return 0==this.lo&&0==this.hi};T.prototype.zero=T.prototype.Ua;T.prototype.add=function(a){return new T((this.lo+a.lo&4294967295)>>>0>>>0,((this.hi+a.hi&4294967295)>>>0)+(4294967296<=this.lo+a.lo?1:0)>>>0)};T.prototype.add=T.prototype.add; +T.prototype.sub=function(a){return new T((this.lo-a.lo&4294967295)>>>0>>>0,((this.hi-a.hi&4294967295)>>>0)-(0>this.lo-a.lo?1:0)>>>0)};T.prototype.sub=T.prototype.sub;function rb(a,b){var c=a&65535;a>>>=16;var d=b&65535,f=b>>>16;b=c*d+65536*(c*f&65535)+65536*(a*d&65535);for(c=a*f+(c*f>>>16)+(a*d>>>16);4294967296<=b;)b-=4294967296,c+=1;return new T(b>>>0,c>>>0)}T.mul32x32=rb;T.prototype.eb=function(a){var b=rb(this.lo,a);a=rb(this.hi,a);a.hi=a.lo;a.lo=0;return b.add(a)};T.prototype.mul=T.prototype.eb; +T.prototype.Xa=function(a){if(0==a)return[];var b=new T(0,0),c=new T(this.lo,this.hi);a=new T(a,0);for(var d=new T(1,0);!a.cb();)a=a.Da(),d=d.Da();for(;!d.Ua();)0>=a.cmp(c)&&(b=b.add(d),c=c.sub(a)),a=a.La(),d=d.La();return[b,c]};T.prototype.div=T.prototype.Xa;T.prototype.toString=function(){for(var a="",b=this;!b.Ua();){b=b.Xa(10);var c=b[0];a=b[1].lo+a;b=c}""==a&&(a="0");return a};T.prototype.toString=T.prototype.toString; +function U(a){for(var b=new T(0,0),c=new T(0,0),d=0;da[d]||"9">>0>>>0,((this.hi+a.hi&4294967295)>>>0)+(4294967296<=this.lo+a.lo?1:0)>>>0)};V.prototype.add=V.prototype.add; +V.prototype.sub=function(a){return new V((this.lo-a.lo&4294967295)>>>0>>>0,((this.hi-a.hi&4294967295)>>>0)-(0>this.lo-a.lo?1:0)>>>0)};V.prototype.sub=V.prototype.sub;V.prototype.clone=function(){return new V(this.lo,this.hi)};V.prototype.clone=V.prototype.clone;V.prototype.toString=function(){var a=0!=(this.hi&2147483648),b=new T(this.lo,this.hi);a&&(b=(new T(0,0)).sub(b));return(a?"-":"")+b.toString()};V.prototype.toString=V.prototype.toString; +function sb(a){var b=0>>=7,a.b++;b.push(c);a.b++}W.prototype.pb=function(a,b,c){tb(this,a.subarray(b,c))};W.prototype.writeSerializedMessage=W.prototype.pb; +W.prototype.Pb=function(a,b,c){null!=a&&null!=b&&null!=c&&this.pb(a,b,c)};W.prototype.maybeWriteSerializedMessage=W.prototype.Pb;W.prototype.reset=function(){this.c=[];this.a.end();this.b=0;this.h=[]};W.prototype.reset=W.prototype.reset;W.prototype.ab=function(){n(0==this.h.length);for(var a=new Uint8Array(this.b+this.a.length()),b=this.c,c=b.length,d=0,f=0;fb),vb(this,a,b))};W.prototype.writeInt32=W.prototype.S; +W.prototype.ob=function(a,b){null!=b&&(b=parseInt(b,10),n(-2147483648<=b&&2147483648>b),vb(this,a,b))};W.prototype.writeInt32String=W.prototype.ob;W.prototype.T=function(a,b){null!=b&&(n(-9223372036854775808<=b&&0x7fffffffffffffff>b),null!=b&&(Y(this,a,0),this.a.ua(b)))};W.prototype.writeInt64=W.prototype.T;W.prototype.ka=function(a,b){null!=b&&(b=sb(b),Y(this,a,0),this.a.l(b.lo,b.hi))};W.prototype.writeInt64String=W.prototype.ka; +W.prototype.s=function(a,b){null!=b&&(n(0<=b&&4294967296>b),ub(this,a,b))};W.prototype.writeUint32=W.prototype.s;W.prototype.ub=function(a,b){null!=b&&(b=parseInt(b,10),n(0<=b&&4294967296>b),ub(this,a,b))};W.prototype.writeUint32String=W.prototype.ub;W.prototype.V=function(a,b){null!=b&&(n(0<=b&&1.8446744073709552E19>b),null!=b&&(Y(this,a,0),this.a.va(b)))};W.prototype.writeUint64=W.prototype.V;W.prototype.vb=function(a,b){null!=b&&(b=U(b),Y(this,a,0),this.a.l(b.lo,b.hi))}; +W.prototype.writeUint64String=W.prototype.vb;W.prototype.rb=function(a,b){null!=b&&(n(-2147483648<=b&&2147483648>b),null!=b&&(Y(this,a,0),this.a.wa(b)))};W.prototype.writeSint32=W.prototype.rb;W.prototype.sb=function(a,b){null!=b&&(n(-9223372036854775808<=b&&0x7fffffffffffffff>b),null!=b&&(Y(this,a,0),this.a.xa(b)))};W.prototype.writeSint64=W.prototype.sb;W.prototype.$d=function(a,b){null!=b&&null!=b&&(Y(this,a,0),this.a.W(b))};W.prototype.writeSintHash64=W.prototype.$d; +W.prototype.Zd=function(a,b){null!=b&&null!=b&&(Y(this,a,0),this.a.Ta(b))};W.prototype.writeSint64String=W.prototype.Zd;W.prototype.Pa=function(a,b){null!=b&&(n(0<=b&&4294967296>b),Y(this,a,5),this.a.s(b))};W.prototype.writeFixed32=W.prototype.Pa;W.prototype.Qa=function(a,b){null!=b&&(n(0<=b&&1.8446744073709552E19>b),Y(this,a,1),this.a.V(b))};W.prototype.writeFixed64=W.prototype.Qa;W.prototype.nb=function(a,b){null!=b&&(b=U(b),Y(this,a,1),this.a.A(b.lo,b.hi))};W.prototype.writeFixed64String=W.prototype.nb; +W.prototype.Ra=function(a,b){null!=b&&(n(-2147483648<=b&&2147483648>b),Y(this,a,5),this.a.S(b))};W.prototype.writeSfixed32=W.prototype.Ra;W.prototype.Sa=function(a,b){null!=b&&(n(-9223372036854775808<=b&&0x7fffffffffffffff>b),Y(this,a,1),this.a.T(b))};W.prototype.writeSfixed64=W.prototype.Sa;W.prototype.qb=function(a,b){null!=b&&(b=sb(b),Y(this,a,1),this.a.A(b.lo,b.hi))};W.prototype.writeSfixed64String=W.prototype.qb;W.prototype.L=function(a,b){null!=b&&(Y(this,a,5),this.a.L(b))}; +W.prototype.writeFloat=W.prototype.L;W.prototype.J=function(a,b){null!=b&&(Y(this,a,1),this.a.J(b))};W.prototype.writeDouble=W.prototype.J;W.prototype.I=function(a,b){null!=b&&(n("boolean"===typeof b||"number"===typeof b),Y(this,a,0),this.a.I(b))};W.prototype.writeBool=W.prototype.I;W.prototype.R=function(a,b){null!=b&&(n(-2147483648<=b&&2147483648>b),Y(this,a,0),this.a.M(b))};W.prototype.writeEnum=W.prototype.R;W.prototype.U=function(a,b){null!=b&&(a=X(this,a),this.a.U(b),Z(this,a))}; +W.prototype.writeString=W.prototype.U;W.prototype.ja=function(a,b){null!=b&&(b=Ua(b),Y(this,a,2),this.a.j(b.length),tb(this,b))};W.prototype.writeBytes=W.prototype.ja;W.prototype.Rc=function(a,b,c){null!=b&&(a=X(this,a),c(b,this),Z(this,a))};W.prototype.writeMessage=W.prototype.Rc;W.prototype.Sc=function(a,b,c){null!=b&&(Y(this,1,3),Y(this,2,0),this.a.M(a),a=X(this,3),c(b,this),Z(this,a),Y(this,1,4))};W.prototype.writeMessageSet=W.prototype.Sc; +W.prototype.Oc=function(a,b,c){null!=b&&(Y(this,a,3),c(b,this),Y(this,a,4))};W.prototype.writeGroup=W.prototype.Oc;W.prototype.K=function(a,b){null!=b&&(n(8==b.length),Y(this,a,1),this.a.K(b))};W.prototype.writeFixedHash64=W.prototype.K;W.prototype.N=function(a,b){null!=b&&(n(8==b.length),Y(this,a,0),this.a.N(b))};W.prototype.writeVarintHash64=W.prototype.N;W.prototype.A=function(a,b,c){Y(this,a,1);this.a.A(b,c)};W.prototype.writeSplitFixed64=W.prototype.A; +W.prototype.l=function(a,b,c){Y(this,a,0);this.a.l(b,c)};W.prototype.writeSplitVarint64=W.prototype.l;W.prototype.tb=function(a,b,c){Y(this,a,0);var d=this.a;Ja(b,c,function(f,h){d.l(f>>>0,h>>>0)})};W.prototype.writeSplitZigzagVarint64=W.prototype.tb;W.prototype.Ed=function(a,b){if(null!=b)for(var c=0;c>>0,t>>>0)});Z(this,a)}}; +W.prototype.writePackedSplitZigzagVarint64=W.prototype.od;W.prototype.dd=function(a,b){if(null!=b&&b.length){a=X(this,a);for(var c=0;cc&&(c=Math.max(c+f,0));c>>0),ua=0;function va(a,b,c){return a.call.apply(a.bind,arguments)} +function wa(a,b,c){if(!a)throw Error();if(2b?1:0};var I;a:{var Ra=x.navigator;if(Ra){var Sa=Ra.userAgent;if(Sa){I=Sa;break a}}I=""};function Ta(a,b){for(var c in a)b.call(void 0,a[c],c,a)}function Ua(a,b){var c={},d;for(d in a)c[d]=b.call(void 0,a[d],d,a);return c}var Va="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function Wa(a,b){for(var c,d,f=1;fparseFloat(gb)){fb=String(ib);break a}}fb=gb}var $a={}; +function kb(){return Za(function(){for(var a=0,b=Pa(String(fb)).split("."),c=Pa("9").split("."),d=Math.max(b.length,c.length),f=0;0==a&&f>>0);function Bb(a){if("function"===typeof a)return a;a[Jb]||(a[Jb]=function(b){return a.handleEvent(b)});return a[Jb]};function N(){lb.call(this);this.f=new tb(this);this.U=this}B(N,lb);N.prototype[M]=!0;N.prototype.addEventListener=function(a,b,c,d){zb(this,a,b,c,d)};N.prototype.removeEventListener=function(a,b,c,d){Hb(this,a,b,c,d)};function O(a,b){a=a.U;var c=b.type||b;if("string"===typeof b)b=new J(b,a);else if(b instanceof J)b.target=b.target||a;else{var d=b;b=new J(c,a);Wa(b,d)}a=b.a=a;Kb(a,c,!0,b);Kb(a,c,!1,b)} +function Kb(a,b,c,d){if(b=a.f.a[String(b)]){b=b.concat();for(var f=!0,g=0;g=f.value}d&&(b=b||Ob,d=ac(bc(),a.getName()),"function"===typeof c&&(c=c()),Ub||(Ub=new Tb),a=a.getName(),a=new Vb(b,c,a),Yb(d,a))}function P(a,b){a&&cc(a,Rb,b)};function dc(){}dc.prototype.a=null;function ec(a){var b;(b=a.a)||(b={},fc(a)&&(b[0]=!0,b[1]=!0),b=a.a=b);return b};var gc;function hc(){}B(hc,dc);function ic(a){return(a=fc(a))?new ActiveXObject(a):new XMLHttpRequest}function fc(a){if(!a.b&&"undefined"==typeof XMLHttpRequest&&"undefined"!=typeof ActiveXObject){for(var b=["MSXML2.XMLHTTP.6.0","MSXML2.XMLHTTP.3.0","MSXML2.XMLHTTP","Microsoft.XMLHTTP"],c=0;c2*this.size&&pc(this),!0):!1};function pc(a){if(a.size!=a.j.length){for(var b=0,c=0;b=d.j.length)throw lc;var g=d.j[b++];return a?g:d.o[g]};f.next=f.a.bind(f);return f};function U(a,b){return Object.prototype.hasOwnProperty.call(a,b)};var qc=/^(?:([^:/?#.]+):)?(?:\/\/(?:([^\\/?#]*)@)?([^\\/?#]*?)(?::([0-9]+))?(?=[\\/?#]|$))?([^?#]+)?(?:\?([^#]*))?(?:#([\s\S]*))?$/;function rc(a){N.call(this);this.headers=new oc;this.C=a||null;this.c=!1;this.J=this.a=null;this.P=this.v="";this.g=0;this.l="";this.i=this.N=this.s=this.L=!1;this.h=0;this.w=null;this.m=sc;this.I=this.M=!1}B(rc,N);var sc="";rc.prototype.b=ac(bc(),"goog.net.XhrIo",void 0).g;var tc=/^https?$/i,uc=["POST","PUT"]; +function vc(a,b,c){if(a.a)throw Error("[goog.net.XhrIo] Object is active with another request="+a.v+"; newUri="+b);a.v=b;a.l="";a.g=0;a.P="POST";a.L=!1;a.c=!0;a.a=a.C?ic(a.C):ic(gc);a.J=a.C?ec(a.C):ec(gc);a.a.onreadystatechange=z(a.R,a);try{P(a.b,V(a,"Opening Xhr")),a.N=!0,a.a.open("POST",String(b),!0),a.N=!1}catch(g){P(a.b,V(a,"Error opening Xhr: "+g.message));wc(a,g);return}b=c||"";c=a.headers.clone();var d=c.G().find(function(g){return"content-type"==g.toLowerCase()}),f=x.FormData&&b instanceof +x.FormData;!(0<=Oa(uc,"POST"))||d||f||c.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8");c.forEach(function(g,e){this.a.setRequestHeader(e,g)},a);a.m&&(a.a.responseType=a.m);"withCredentials"in a.a&&a.a.withCredentials!==a.M&&(a.a.withCredentials=a.M);try{xc(a),0>4);64!=e&&(b(g<<4&240|e>>2),64!=h&&b(e<<6&192|h))}} +function Ic(){if(!Fc){Fc={};for(var a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""),b=["+/=","+/","-_=","-_.","-_"],c=0;5>c;c++){var d=a.concat(b[c].split(""));Ec[c]=d;for(var f=0;fh&&(h=f.length),e=f.indexOf("?"), +0>e||e>h?(e=h,k=""):k=f.substring(e+1,h),f=[f.substr(0,e),k,f.substr(h)],h=f[1],f[1]=m?h?h+"&"+m:m:h,f=f[0]+(f[1]?"?"+f[1]:"")+f[2]}else f.a("$httpHeaders",h)}b=(0,d.a)(b.getRequestMessage());d=b.length;m=[0,0,0,0];h=new Uint8Array(5+d);for(e=3;0<=e;e--)m[e]=d%256,d>>>=8;h.set(new Uint8Array(m),1);h.set(b,5);b=h;if("text"==a.a){a=b;var p;void 0===p&&(p=0);Ic();p=Ec[p];b=Array(Math.floor(a.length/3));d=p[64]||"";for(m=h=0;h>2];l=p[(l&3)<<4|q>>4]; +q=p[(q&15)<<2|k>>6];k=p[k&63];b[m++]=e+l+q+k}e=0;k=d;switch(a.length-h){case 2:e=a[h+1],k=p[(e&15)<<2]||d;case 1:a=a[h],b[m]=p[a>>2]+p[(a&3)<<4|e>>4]+k+d}b=b.join("")}else"binary"==a.a&&(c.m="arraybuffer");vc(c,f,b);return g} +function Qc(a,b,c){var d=!1,f=null,g=!1;a.on("data",function(e){d=!0;f=e});a.on("error",function(e){0==e.code||g||(g=!0,b(e,null))});a.on("status",function(e){0==e.code||g?c&&b(null,null,e):(g=!0,b({code:e.code,message:e.details,metadata:e.metadata},null))});if(c)a.on("metadata",function(e){b(null,null,null,e)});a.on("end",function(){g||(d?c?b(null,f,null,null,!0):b(null,f):b({code:2,message:"Incomplete response"}));c&&b(null,null)})} +function Oc(a,b){var c=a;b.forEach(function(d){var f=c;c=function(g){return d.intercept(g,f)}});return c}Z.prototype.serverStreaming=Z.prototype.Y;Z.prototype.unaryCall=Z.prototype.unaryCall;Z.prototype.thenableCall=Z.prototype.S;Z.prototype.rpcCall=Z.prototype.X;module.exports.CallOptions=xa;module.exports.MethodDescriptor=ya;module.exports.GrpcWebClientBase=Z;module.exports.RpcError=E;module.exports.StatusCode={OK:0,CANCELLED:1,UNKNOWN:2,INVALID_ARGUMENT:3,DEADLINE_EXCEEDED:4,NOT_FOUND:5,ALREADY_EXISTS:6,PERMISSION_DENIED:7,UNAUTHENTICATED:16,RESOURCE_EXHAUSTED:8,FAILED_PRECONDITION:9,ABORTED:10,OUT_OF_RANGE:11,UNIMPLEMENTED:12,INTERNAL:13,UNAVAILABLE:14,DATA_LOSS:15};module.exports.MethodType={UNARY:"unary",SERVER_STREAMING:"server_streaming",BIDI_STREAMING:"bidi_streaming"}; +Lb="undefined"!==typeof globalThis&&globalThis||self; + +}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}]},{},[4]); diff --git a/libcore/extension/html/rpc/base_pb.js b/libcore/extension/html/rpc/base_pb.js new file mode 100644 index 0000000..a4a8f12 --- /dev/null +++ b/libcore/extension/html/rpc/base_pb.js @@ -0,0 +1,460 @@ +// source: base.proto +/** + * @fileoverview + * @enhanceable + * @suppress {missingRequire} reports error on implicit type usages. + * @suppress {messageConventions} JS Compiler reports an error if a variable or + * field starts with 'MSG_' and isn't a translatable message. + * @public + */ +// GENERATED CODE -- DO NOT EDIT! +/* eslint-disable */ +// @ts-nocheck + +var jspb = require('google-protobuf'); +var goog = jspb; +var global = + (typeof globalThis !== 'undefined' && globalThis) || + (typeof window !== 'undefined' && window) || + (typeof global !== 'undefined' && global) || + (typeof self !== 'undefined' && self) || + (function () { return this; }).call(null) || + Function('return this')(); + +goog.exportSymbol('proto.hiddifyrpc.Empty', null, global); +goog.exportSymbol('proto.hiddifyrpc.HelloRequest', null, global); +goog.exportSymbol('proto.hiddifyrpc.HelloResponse', null, global); +goog.exportSymbol('proto.hiddifyrpc.ResponseCode', null, global); +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.HelloRequest = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.HelloRequest, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.HelloRequest.displayName = 'proto.hiddifyrpc.HelloRequest'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.HelloResponse = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.HelloResponse, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.HelloResponse.displayName = 'proto.hiddifyrpc.HelloResponse'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.Empty = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.Empty, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.Empty.displayName = 'proto.hiddifyrpc.Empty'; +} + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.HelloRequest.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.HelloRequest.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.HelloRequest} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.HelloRequest.toObject = function(includeInstance, msg) { + var f, obj = { +name: jspb.Message.getFieldWithDefault(msg, 1, "") + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.HelloRequest} + */ +proto.hiddifyrpc.HelloRequest.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.HelloRequest; + return proto.hiddifyrpc.HelloRequest.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.HelloRequest} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.HelloRequest} + */ +proto.hiddifyrpc.HelloRequest.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {string} */ (reader.readString()); + msg.setName(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.HelloRequest.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.HelloRequest.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.HelloRequest} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.HelloRequest.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getName(); + if (f.length > 0) { + writer.writeString( + 1, + f + ); + } +}; + + +/** + * optional string name = 1; + * @return {string} + */ +proto.hiddifyrpc.HelloRequest.prototype.getName = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.HelloRequest} returns this + */ +proto.hiddifyrpc.HelloRequest.prototype.setName = function(value) { + return jspb.Message.setProto3StringField(this, 1, value); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.HelloResponse.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.HelloResponse.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.HelloResponse} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.HelloResponse.toObject = function(includeInstance, msg) { + var f, obj = { +message: jspb.Message.getFieldWithDefault(msg, 1, "") + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.HelloResponse} + */ +proto.hiddifyrpc.HelloResponse.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.HelloResponse; + return proto.hiddifyrpc.HelloResponse.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.HelloResponse} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.HelloResponse} + */ +proto.hiddifyrpc.HelloResponse.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {string} */ (reader.readString()); + msg.setMessage(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.HelloResponse.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.HelloResponse.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.HelloResponse} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.HelloResponse.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getMessage(); + if (f.length > 0) { + writer.writeString( + 1, + f + ); + } +}; + + +/** + * optional string message = 1; + * @return {string} + */ +proto.hiddifyrpc.HelloResponse.prototype.getMessage = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.HelloResponse} returns this + */ +proto.hiddifyrpc.HelloResponse.prototype.setMessage = function(value) { + return jspb.Message.setProto3StringField(this, 1, value); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.Empty.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.Empty.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.Empty} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.Empty.toObject = function(includeInstance, msg) { + var f, obj = { + + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.Empty} + */ +proto.hiddifyrpc.Empty.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.Empty; + return proto.hiddifyrpc.Empty.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.Empty} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.Empty} + */ +proto.hiddifyrpc.Empty.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.Empty.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.Empty.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.Empty} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.Empty.serializeBinaryToWriter = function(message, writer) { + var f = undefined; +}; + + +/** + * @enum {number} + */ +proto.hiddifyrpc.ResponseCode = { + OK: 0, + FAILED: 1 +}; + +goog.object.extend(exports, proto.hiddifyrpc); diff --git a/libcore/extension/html/rpc/client.js b/libcore/extension/html/rpc/client.js new file mode 100644 index 0000000..f81c0ba --- /dev/null +++ b/libcore/extension/html/rpc/client.js @@ -0,0 +1,8 @@ +const hiddify = require("./hiddify_grpc_web_pb.js"); +const extension = require("./extension_grpc_web_pb.js"); + +const grpcServerAddress = '/'; +const extensionClient = new extension.ExtensionHostServicePromiseClient(grpcServerAddress, null, null); +const hiddifyClient = new hiddify.CorePromiseClient(grpcServerAddress, null, null); + +module.exports = { extensionClient ,hiddifyClient}; \ No newline at end of file diff --git a/libcore/extension/html/rpc/connectionPage.js b/libcore/extension/html/rpc/connectionPage.js new file mode 100644 index 0000000..0452a88 --- /dev/null +++ b/libcore/extension/html/rpc/connectionPage.js @@ -0,0 +1,109 @@ +const { hiddifyClient } = require('./client.js'); +const hiddify = require("./hiddify_grpc_web_pb.js"); + +function openConnectionPage() { + + $("#extension-list-container").show(); + $("#extension-page-container").hide(); + $("#connection-page").show(); + connect(); + $("#connect-button").click(async () => { + const hsetting_request = new hiddify.ChangeHiddifySettingsRequest(); + hsetting_request.setHiddifySettingsJson($("#hiddify-settings").val()); + try{ + const hres=await hiddifyClient.changeHiddifySettings(hsetting_request, {}); + }catch(err){ + $("#hiddify-settings").val("") + console.log(err) + } + + const parse_request = new hiddify.ParseRequest(); + parse_request.setContent($("#config-content").val()); + try{ + const pres=await hiddifyClient.parse(parse_request, {}); + if (pres.getResponseCode() !== hiddify.ResponseCode.OK){ + alert(pres.getMessage()); + return + } + $("#config-content").val(pres.getContent()); + }catch(err){ + console.log(err) + alert(JSON.stringify(err)) + return + } + + const request = new hiddify.StartRequest(); + + request.setConfigContent($("#config-content").val()); + request.setEnableRawConfig(false); + try{ + const res=await hiddifyClient.start(request, {}); + console.log(res.getCoreState(),res.getMessage()) + handleCoreStatus(res.getCoreState()); + }catch(err){ + console.log(err) + alert(JSON.stringify(err)) + return + } + + + }) + + $("#disconnect-button").click(async () => { + const request = new hiddify.Empty(); + try{ + const res=await hiddifyClient.stop(request, {}); + console.log(res.getCoreState(),res.getMessage()) + handleCoreStatus(res.getCoreState()); + }catch(err){ + console.log(err) + alert(JSON.stringify(err)) + return + } + }) +} + + +function connect(){ + const request = new hiddify.Empty(); + const stream = hiddifyClient.coreInfoListener(request, {}); + stream.on('data', (response) => { + console.log('Receving ',response); + handleCoreStatus(response); + }); + + stream.on('error', (err) => { + console.error('Error opening extension page:', err); + // openExtensionPage(extensionId); + }); + + stream.on('end', () => { + console.log('Stream ended'); + setTimeout(connect, 1000); + + }); +} + + +function handleCoreStatus(status){ + if (status == hiddify.CoreState.STOPPED){ + $("#connection-before-connect").show(); + $("#connection-connecting").hide(); + }else{ + $("#connection-before-connect").hide(); + $("#connection-connecting").show(); + if (status == hiddify.CoreState.STARTING){ + $("#connection-status").text("Starting"); + $("#connection-status").css("color", "yellow"); + }else if (status == hiddify.CoreState.STOPPING){ + $("#connection-status").text("Stopping"); + $("#connection-status").css("color", "red"); + }else if (status == hiddify.CoreState.STARTED){ + $("#connection-status").text("Connected"); + $("#connection-status").css("color", "green"); + } + } +} + + +module.exports = { openConnectionPage }; \ No newline at end of file diff --git a/libcore/extension/html/rpc/extension.js b/libcore/extension/html/rpc/extension.js new file mode 100644 index 0000000..fe8ca02 --- /dev/null +++ b/libcore/extension/html/rpc/extension.js @@ -0,0 +1,8 @@ +const { listExtensions } = require('./extensionList.js'); +const { openConnectionPage } = require('./connectionPage.js'); +window.onload = () => { + listExtensions(); + openConnectionPage(); +}; + + diff --git a/libcore/extension/html/rpc/extensionList.js b/libcore/extension/html/rpc/extensionList.js new file mode 100644 index 0000000..f5978ba --- /dev/null +++ b/libcore/extension/html/rpc/extensionList.js @@ -0,0 +1,90 @@ + +const { extensionClient } = require('./client.js'); +const extension = require("./extension_grpc_web_pb.js"); +async function listExtensions() { + $("#extension-list-container").show(); + $("#extension-page-container").hide(); + $("#connection-page").show(); + + try { + const extensionListContainer = document.getElementById('extension-list'); + extensionListContainer.innerHTML = ''; // Clear previous entries + const response = await extensionClient.listExtensions(new extension.Empty(), {}); + + const extensionList = response.getExtensionsList(); + extensionList.forEach(ext => { + const listItem = createExtensionListItem(ext); + extensionListContainer.appendChild(listItem); + }); + } catch (err) { + console.error('Error listing extensions:', err); + } +} + +function createExtensionListItem(ext) { + const listItem = document.createElement('li'); + listItem.className = 'list-group-item d-flex justify-content-between align-items-center'; + listItem.setAttribute('data-extension-id', ext.getId()); + + const contentDiv = document.createElement('div'); + + const titleElement = document.createElement('span'); + titleElement.innerHTML = `${ext.getTitle()}`; + contentDiv.appendChild(titleElement); + + const descriptionElement = document.createElement('p'); + descriptionElement.className = 'mb-0'; + descriptionElement.textContent = ext.getDescription(); + contentDiv.appendChild(descriptionElement); + contentDiv.style.width="100%"; + listItem.appendChild(contentDiv); + + const switchDiv = createSwitchElement(ext); + listItem.appendChild(switchDiv); + const {openExtensionPage} = require('./extensionPage.js'); + + contentDiv.addEventListener('click', () =>{ + if (!ext.getEnable() ){ + alert("Extension is not enabled") + return + } + openExtensionPage(ext.getId()) + }); + + return listItem; +} + +function createSwitchElement(ext) { + const switchDiv = document.createElement('div'); + switchDiv.className = 'form-check form-switch'; + + const switchButton = document.createElement('input'); + switchButton.type = 'checkbox'; + switchButton.className = 'form-check-input'; + switchButton.checked = ext.getEnable(); + switchButton.addEventListener('change', (e) => { + + toggleExtension(ext.getId(), switchButton.checked) + }); + + switchDiv.appendChild(switchButton); + return switchDiv; +} + +async function toggleExtension(extensionId, enable) { + const request = new extension.EditExtensionRequest(); + request.setExtensionId(extensionId); + request.setEnable(enable); + + try { + await extensionClient.editExtension(request, {}); + console.log(`Extension ${extensionId} updated to ${enable ? 'enabled' : 'disabled'}`); + } catch (err) { + console.error('Error updating extension status:', err); + } + listExtensions(); +} + + + +module.exports = { listExtensions }; \ No newline at end of file diff --git a/libcore/extension/html/rpc/extensionPage.js b/libcore/extension/html/rpc/extensionPage.js new file mode 100644 index 0000000..7140b76 --- /dev/null +++ b/libcore/extension/html/rpc/extensionPage.js @@ -0,0 +1,87 @@ +const { extensionClient } = require('./client.js'); +const extension = require("./extension_grpc_web_pb.js"); + +const { renderForm } = require('./formRenderer.js'); +const { listExtensions } = require('./extensionList.js'); +var currentExtensionId = undefined; +function openExtensionPage(extensionId) { + currentExtensionId = extensionId; + $("#extension-list-container").hide(); + $("#extension-page-container").show(); + $("#connection-page").hide(); + connect() +} + +function connect() { + const request = new extension.ExtensionRequest(); + request.setExtensionId(currentExtensionId); + + const stream = extensionClient.connect(request, {}); + + stream.on('data', (response) => { + console.log('Receiving ', response); + if (response.getExtensionId() === currentExtensionId) { + ui = JSON.parse(response.getJsonUi()) + if (response.getType() == proto.hiddifyrpc.ExtensionResponseType.SHOW_DIALOG) { + renderForm(ui, "dialog", handleSubmitButtonClick, undefined); + } else { + renderForm(ui, "", handleSubmitButtonClick, handleStopButtonClick); + } + + + } + }); + + stream.on('error', (err) => { + console.error('Error opening extension page:', err); + // openExtensionPage(extensionId); + }); + + stream.on('end', () => { + console.log('Stream ended'); + setTimeout(connect, 1000); + + }); +} + +async function handleSubmitButtonClick(event, button) { + event.preventDefault(); + bootstrap.Modal.getOrCreateInstance("#extension-dialog").hide(); + const request = new extension.SendExtensionDataRequest(); + request.setButton(button); + if (event.type != 'hidden.bs.modal') { + const formData = new FormData(event.target.closest('form')); + const datamap = request.getDataMap() + formData.forEach((value, key) => { + datamap.set(key, value); + }); + } + request.setExtensionId(currentExtensionId); + + try { + await extensionClient.submitForm(request, {}); + console.log('Form submitted successfully.'); + } catch (err) { + console.error('Error submitting form:', err); + } +} + + +async function handleStopButtonClick(event) { + event.preventDefault(); + const request = new extension.ExtensionRequest(); + request.setExtensionId(currentExtensionId); + bootstrap.Modal.getOrCreateInstance("#extension-dialog").hide(); + try { + await extensionClient.close(request, {}); + console.log('Extension stopped successfully.'); + currentExtensionId = undefined; + listExtensions(); // Return to the extension list + } catch (err) { + console.error('Error stopping extension:', err); + } +} + + + +module.exports = { openExtensionPage }; \ No newline at end of file diff --git a/libcore/extension/html/rpc/extension_grpc_web_pb.js b/libcore/extension/html/rpc/extension_grpc_web_pb.js new file mode 100644 index 0000000..16d808c --- /dev/null +++ b/libcore/extension/html/rpc/extension_grpc_web_pb.js @@ -0,0 +1,441 @@ +/** + * @fileoverview gRPC-Web generated client stub for hiddifyrpc + * @enhanceable + * @public + */ + +// Code generated by protoc-gen-grpc-web. DO NOT EDIT. +// versions: +// protoc-gen-grpc-web v1.5.0 +// protoc v5.28.0 +// source: extension.proto + + +/* eslint-disable */ +// @ts-nocheck + + + +const grpc = {}; +grpc.web = require('grpc-web'); + + +var base_pb = require('./base_pb.js') +const proto = {}; +proto.hiddifyrpc = require('./extension_pb.js'); + +/** + * @param {string} hostname + * @param {?Object} credentials + * @param {?grpc.web.ClientOptions} options + * @constructor + * @struct + * @final + */ +proto.hiddifyrpc.ExtensionHostServiceClient = + function(hostname, credentials, options) { + if (!options) options = {}; + options.format = 'text'; + + /** + * @private @const {!grpc.web.GrpcWebClientBase} The client + */ + this.client_ = new grpc.web.GrpcWebClientBase(options); + + /** + * @private @const {string} The hostname + */ + this.hostname_ = hostname.replace(/\/+$/, ''); + +}; + + +/** + * @param {string} hostname + * @param {?Object} credentials + * @param {?grpc.web.ClientOptions} options + * @constructor + * @struct + * @final + */ +proto.hiddifyrpc.ExtensionHostServicePromiseClient = + function(hostname, credentials, options) { + if (!options) options = {}; + options.format = 'text'; + + /** + * @private @const {!grpc.web.GrpcWebClientBase} The client + */ + this.client_ = new grpc.web.GrpcWebClientBase(options); + + /** + * @private @const {string} The hostname + */ + this.hostname_ = hostname.replace(/\/+$/, ''); + +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.Empty, + * !proto.hiddifyrpc.ExtensionList>} + */ +const methodDescriptor_ExtensionHostService_ListExtensions = new grpc.web.MethodDescriptor( + '/hiddifyrpc.ExtensionHostService/ListExtensions', + grpc.web.MethodType.UNARY, + base_pb.Empty, + proto.hiddifyrpc.ExtensionList, + /** + * @param {!proto.hiddifyrpc.Empty} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.ExtensionList.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.Empty} request The + * request proto + * @param {?Object} metadata User defined + * call metadata + * @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.ExtensionList)} + * callback The callback function(error, response) + * @return {!grpc.web.ClientReadableStream|undefined} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.ExtensionHostServiceClient.prototype.listExtensions = + function(request, metadata, callback) { + return this.client_.rpcCall(this.hostname_ + + '/hiddifyrpc.ExtensionHostService/ListExtensions', + request, + metadata || {}, + methodDescriptor_ExtensionHostService_ListExtensions, + callback); +}; + + +/** + * @param {!proto.hiddifyrpc.Empty} request The + * request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!Promise} + * Promise that resolves to the response + */ +proto.hiddifyrpc.ExtensionHostServicePromiseClient.prototype.listExtensions = + function(request, metadata) { + return this.client_.unaryCall(this.hostname_ + + '/hiddifyrpc.ExtensionHostService/ListExtensions', + request, + metadata || {}, + methodDescriptor_ExtensionHostService_ListExtensions); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.ExtensionRequest, + * !proto.hiddifyrpc.ExtensionResponse>} + */ +const methodDescriptor_ExtensionHostService_Connect = new grpc.web.MethodDescriptor( + '/hiddifyrpc.ExtensionHostService/Connect', + grpc.web.MethodType.SERVER_STREAMING, + proto.hiddifyrpc.ExtensionRequest, + proto.hiddifyrpc.ExtensionResponse, + /** + * @param {!proto.hiddifyrpc.ExtensionRequest} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.ExtensionResponse.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.ExtensionRequest} request The request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!grpc.web.ClientReadableStream} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.ExtensionHostServiceClient.prototype.connect = + function(request, metadata) { + return this.client_.serverStreaming(this.hostname_ + + '/hiddifyrpc.ExtensionHostService/Connect', + request, + metadata || {}, + methodDescriptor_ExtensionHostService_Connect); +}; + + +/** + * @param {!proto.hiddifyrpc.ExtensionRequest} request The request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!grpc.web.ClientReadableStream} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.ExtensionHostServicePromiseClient.prototype.connect = + function(request, metadata) { + return this.client_.serverStreaming(this.hostname_ + + '/hiddifyrpc.ExtensionHostService/Connect', + request, + metadata || {}, + methodDescriptor_ExtensionHostService_Connect); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.EditExtensionRequest, + * !proto.hiddifyrpc.ExtensionActionResult>} + */ +const methodDescriptor_ExtensionHostService_EditExtension = new grpc.web.MethodDescriptor( + '/hiddifyrpc.ExtensionHostService/EditExtension', + grpc.web.MethodType.UNARY, + proto.hiddifyrpc.EditExtensionRequest, + proto.hiddifyrpc.ExtensionActionResult, + /** + * @param {!proto.hiddifyrpc.EditExtensionRequest} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.ExtensionActionResult.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.EditExtensionRequest} request The + * request proto + * @param {?Object} metadata User defined + * call metadata + * @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.ExtensionActionResult)} + * callback The callback function(error, response) + * @return {!grpc.web.ClientReadableStream|undefined} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.ExtensionHostServiceClient.prototype.editExtension = + function(request, metadata, callback) { + return this.client_.rpcCall(this.hostname_ + + '/hiddifyrpc.ExtensionHostService/EditExtension', + request, + metadata || {}, + methodDescriptor_ExtensionHostService_EditExtension, + callback); +}; + + +/** + * @param {!proto.hiddifyrpc.EditExtensionRequest} request The + * request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!Promise} + * Promise that resolves to the response + */ +proto.hiddifyrpc.ExtensionHostServicePromiseClient.prototype.editExtension = + function(request, metadata) { + return this.client_.unaryCall(this.hostname_ + + '/hiddifyrpc.ExtensionHostService/EditExtension', + request, + metadata || {}, + methodDescriptor_ExtensionHostService_EditExtension); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.SendExtensionDataRequest, + * !proto.hiddifyrpc.ExtensionActionResult>} + */ +const methodDescriptor_ExtensionHostService_SubmitForm = new grpc.web.MethodDescriptor( + '/hiddifyrpc.ExtensionHostService/SubmitForm', + grpc.web.MethodType.UNARY, + proto.hiddifyrpc.SendExtensionDataRequest, + proto.hiddifyrpc.ExtensionActionResult, + /** + * @param {!proto.hiddifyrpc.SendExtensionDataRequest} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.ExtensionActionResult.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.SendExtensionDataRequest} request The + * request proto + * @param {?Object} metadata User defined + * call metadata + * @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.ExtensionActionResult)} + * callback The callback function(error, response) + * @return {!grpc.web.ClientReadableStream|undefined} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.ExtensionHostServiceClient.prototype.submitForm = + function(request, metadata, callback) { + return this.client_.rpcCall(this.hostname_ + + '/hiddifyrpc.ExtensionHostService/SubmitForm', + request, + metadata || {}, + methodDescriptor_ExtensionHostService_SubmitForm, + callback); +}; + + +/** + * @param {!proto.hiddifyrpc.SendExtensionDataRequest} request The + * request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!Promise} + * Promise that resolves to the response + */ +proto.hiddifyrpc.ExtensionHostServicePromiseClient.prototype.submitForm = + function(request, metadata) { + return this.client_.unaryCall(this.hostname_ + + '/hiddifyrpc.ExtensionHostService/SubmitForm', + request, + metadata || {}, + methodDescriptor_ExtensionHostService_SubmitForm); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.ExtensionRequest, + * !proto.hiddifyrpc.ExtensionActionResult>} + */ +const methodDescriptor_ExtensionHostService_Close = new grpc.web.MethodDescriptor( + '/hiddifyrpc.ExtensionHostService/Close', + grpc.web.MethodType.UNARY, + proto.hiddifyrpc.ExtensionRequest, + proto.hiddifyrpc.ExtensionActionResult, + /** + * @param {!proto.hiddifyrpc.ExtensionRequest} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.ExtensionActionResult.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.ExtensionRequest} request The + * request proto + * @param {?Object} metadata User defined + * call metadata + * @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.ExtensionActionResult)} + * callback The callback function(error, response) + * @return {!grpc.web.ClientReadableStream|undefined} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.ExtensionHostServiceClient.prototype.close = + function(request, metadata, callback) { + return this.client_.rpcCall(this.hostname_ + + '/hiddifyrpc.ExtensionHostService/Close', + request, + metadata || {}, + methodDescriptor_ExtensionHostService_Close, + callback); +}; + + +/** + * @param {!proto.hiddifyrpc.ExtensionRequest} request The + * request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!Promise} + * Promise that resolves to the response + */ +proto.hiddifyrpc.ExtensionHostServicePromiseClient.prototype.close = + function(request, metadata) { + return this.client_.unaryCall(this.hostname_ + + '/hiddifyrpc.ExtensionHostService/Close', + request, + metadata || {}, + methodDescriptor_ExtensionHostService_Close); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.ExtensionRequest, + * !proto.hiddifyrpc.ExtensionActionResult>} + */ +const methodDescriptor_ExtensionHostService_GetUI = new grpc.web.MethodDescriptor( + '/hiddifyrpc.ExtensionHostService/GetUI', + grpc.web.MethodType.UNARY, + proto.hiddifyrpc.ExtensionRequest, + proto.hiddifyrpc.ExtensionActionResult, + /** + * @param {!proto.hiddifyrpc.ExtensionRequest} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.ExtensionActionResult.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.ExtensionRequest} request The + * request proto + * @param {?Object} metadata User defined + * call metadata + * @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.ExtensionActionResult)} + * callback The callback function(error, response) + * @return {!grpc.web.ClientReadableStream|undefined} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.ExtensionHostServiceClient.prototype.getUI = + function(request, metadata, callback) { + return this.client_.rpcCall(this.hostname_ + + '/hiddifyrpc.ExtensionHostService/GetUI', + request, + metadata || {}, + methodDescriptor_ExtensionHostService_GetUI, + callback); +}; + + +/** + * @param {!proto.hiddifyrpc.ExtensionRequest} request The + * request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!Promise} + * Promise that resolves to the response + */ +proto.hiddifyrpc.ExtensionHostServicePromiseClient.prototype.getUI = + function(request, metadata) { + return this.client_.unaryCall(this.hostname_ + + '/hiddifyrpc.ExtensionHostService/GetUI', + request, + metadata || {}, + methodDescriptor_ExtensionHostService_GetUI); +}; + + +module.exports = proto.hiddifyrpc; + diff --git a/libcore/extension/html/rpc/extension_pb.js b/libcore/extension/html/rpc/extension_pb.js new file mode 100644 index 0000000..a0ea9f7 --- /dev/null +++ b/libcore/extension/html/rpc/extension_pb.js @@ -0,0 +1,1469 @@ +// source: extension.proto +/** + * @fileoverview + * @enhanceable + * @suppress {missingRequire} reports error on implicit type usages. + * @suppress {messageConventions} JS Compiler reports an error if a variable or + * field starts with 'MSG_' and isn't a translatable message. + * @public + */ +// GENERATED CODE -- DO NOT EDIT! +/* eslint-disable */ +// @ts-nocheck + +var jspb = require('google-protobuf'); +var goog = jspb; +var global = + (typeof globalThis !== 'undefined' && globalThis) || + (typeof window !== 'undefined' && window) || + (typeof global !== 'undefined' && global) || + (typeof self !== 'undefined' && self) || + (function () { return this; }).call(null) || + Function('return this')(); + +var base_pb = require('./base_pb.js'); +goog.object.extend(proto, base_pb); +goog.exportSymbol('proto.hiddifyrpc.EditExtensionRequest', null, global); +goog.exportSymbol('proto.hiddifyrpc.Extension', null, global); +goog.exportSymbol('proto.hiddifyrpc.ExtensionActionResult', null, global); +goog.exportSymbol('proto.hiddifyrpc.ExtensionList', null, global); +goog.exportSymbol('proto.hiddifyrpc.ExtensionRequest', null, global); +goog.exportSymbol('proto.hiddifyrpc.ExtensionResponse', null, global); +goog.exportSymbol('proto.hiddifyrpc.ExtensionResponseType', null, global); +goog.exportSymbol('proto.hiddifyrpc.SendExtensionDataRequest', null, global); +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.ExtensionActionResult = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.ExtensionActionResult, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.ExtensionActionResult.displayName = 'proto.hiddifyrpc.ExtensionActionResult'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.ExtensionList = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, proto.hiddifyrpc.ExtensionList.repeatedFields_, null); +}; +goog.inherits(proto.hiddifyrpc.ExtensionList, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.ExtensionList.displayName = 'proto.hiddifyrpc.ExtensionList'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.EditExtensionRequest = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.EditExtensionRequest, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.EditExtensionRequest.displayName = 'proto.hiddifyrpc.EditExtensionRequest'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.Extension = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.Extension, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.Extension.displayName = 'proto.hiddifyrpc.Extension'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.ExtensionRequest = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.ExtensionRequest, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.ExtensionRequest.displayName = 'proto.hiddifyrpc.ExtensionRequest'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.SendExtensionDataRequest = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.SendExtensionDataRequest, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.SendExtensionDataRequest.displayName = 'proto.hiddifyrpc.SendExtensionDataRequest'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.ExtensionResponse = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.ExtensionResponse, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.ExtensionResponse.displayName = 'proto.hiddifyrpc.ExtensionResponse'; +} + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.ExtensionActionResult.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.ExtensionActionResult.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.ExtensionActionResult} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.ExtensionActionResult.toObject = function(includeInstance, msg) { + var f, obj = { +extensionId: jspb.Message.getFieldWithDefault(msg, 1, ""), +code: jspb.Message.getFieldWithDefault(msg, 2, 0), +message: jspb.Message.getFieldWithDefault(msg, 3, "") + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.ExtensionActionResult} + */ +proto.hiddifyrpc.ExtensionActionResult.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.ExtensionActionResult; + return proto.hiddifyrpc.ExtensionActionResult.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.ExtensionActionResult} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.ExtensionActionResult} + */ +proto.hiddifyrpc.ExtensionActionResult.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {string} */ (reader.readString()); + msg.setExtensionId(value); + break; + case 2: + var value = /** @type {!proto.hiddifyrpc.ResponseCode} */ (reader.readEnum()); + msg.setCode(value); + break; + case 3: + var value = /** @type {string} */ (reader.readString()); + msg.setMessage(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.ExtensionActionResult.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.ExtensionActionResult.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.ExtensionActionResult} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.ExtensionActionResult.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getExtensionId(); + if (f.length > 0) { + writer.writeString( + 1, + f + ); + } + f = message.getCode(); + if (f !== 0.0) { + writer.writeEnum( + 2, + f + ); + } + f = message.getMessage(); + if (f.length > 0) { + writer.writeString( + 3, + f + ); + } +}; + + +/** + * optional string extension_id = 1; + * @return {string} + */ +proto.hiddifyrpc.ExtensionActionResult.prototype.getExtensionId = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.ExtensionActionResult} returns this + */ +proto.hiddifyrpc.ExtensionActionResult.prototype.setExtensionId = function(value) { + return jspb.Message.setProto3StringField(this, 1, value); +}; + + +/** + * optional ResponseCode code = 2; + * @return {!proto.hiddifyrpc.ResponseCode} + */ +proto.hiddifyrpc.ExtensionActionResult.prototype.getCode = function() { + return /** @type {!proto.hiddifyrpc.ResponseCode} */ (jspb.Message.getFieldWithDefault(this, 2, 0)); +}; + + +/** + * @param {!proto.hiddifyrpc.ResponseCode} value + * @return {!proto.hiddifyrpc.ExtensionActionResult} returns this + */ +proto.hiddifyrpc.ExtensionActionResult.prototype.setCode = function(value) { + return jspb.Message.setProto3EnumField(this, 2, value); +}; + + +/** + * optional string message = 3; + * @return {string} + */ +proto.hiddifyrpc.ExtensionActionResult.prototype.getMessage = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.ExtensionActionResult} returns this + */ +proto.hiddifyrpc.ExtensionActionResult.prototype.setMessage = function(value) { + return jspb.Message.setProto3StringField(this, 3, value); +}; + + + +/** + * List of repeated fields within this message type. + * @private {!Array} + * @const + */ +proto.hiddifyrpc.ExtensionList.repeatedFields_ = [1]; + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.ExtensionList.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.ExtensionList.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.ExtensionList} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.ExtensionList.toObject = function(includeInstance, msg) { + var f, obj = { +extensionsList: jspb.Message.toObjectList(msg.getExtensionsList(), + proto.hiddifyrpc.Extension.toObject, includeInstance) + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.ExtensionList} + */ +proto.hiddifyrpc.ExtensionList.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.ExtensionList; + return proto.hiddifyrpc.ExtensionList.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.ExtensionList} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.ExtensionList} + */ +proto.hiddifyrpc.ExtensionList.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = new proto.hiddifyrpc.Extension; + reader.readMessage(value,proto.hiddifyrpc.Extension.deserializeBinaryFromReader); + msg.addExtensions(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.ExtensionList.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.ExtensionList.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.ExtensionList} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.ExtensionList.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getExtensionsList(); + if (f.length > 0) { + writer.writeRepeatedMessage( + 1, + f, + proto.hiddifyrpc.Extension.serializeBinaryToWriter + ); + } +}; + + +/** + * repeated Extension extensions = 1; + * @return {!Array} + */ +proto.hiddifyrpc.ExtensionList.prototype.getExtensionsList = function() { + return /** @type{!Array} */ ( + jspb.Message.getRepeatedWrapperField(this, proto.hiddifyrpc.Extension, 1)); +}; + + +/** + * @param {!Array} value + * @return {!proto.hiddifyrpc.ExtensionList} returns this +*/ +proto.hiddifyrpc.ExtensionList.prototype.setExtensionsList = function(value) { + return jspb.Message.setRepeatedWrapperField(this, 1, value); +}; + + +/** + * @param {!proto.hiddifyrpc.Extension=} opt_value + * @param {number=} opt_index + * @return {!proto.hiddifyrpc.Extension} + */ +proto.hiddifyrpc.ExtensionList.prototype.addExtensions = function(opt_value, opt_index) { + return jspb.Message.addToRepeatedWrapperField(this, 1, opt_value, proto.hiddifyrpc.Extension, opt_index); +}; + + +/** + * Clears the list making it empty but non-null. + * @return {!proto.hiddifyrpc.ExtensionList} returns this + */ +proto.hiddifyrpc.ExtensionList.prototype.clearExtensionsList = function() { + return this.setExtensionsList([]); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.EditExtensionRequest.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.EditExtensionRequest.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.EditExtensionRequest} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.EditExtensionRequest.toObject = function(includeInstance, msg) { + var f, obj = { +extensionId: jspb.Message.getFieldWithDefault(msg, 1, ""), +enable: jspb.Message.getBooleanFieldWithDefault(msg, 2, false) + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.EditExtensionRequest} + */ +proto.hiddifyrpc.EditExtensionRequest.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.EditExtensionRequest; + return proto.hiddifyrpc.EditExtensionRequest.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.EditExtensionRequest} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.EditExtensionRequest} + */ +proto.hiddifyrpc.EditExtensionRequest.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {string} */ (reader.readString()); + msg.setExtensionId(value); + break; + case 2: + var value = /** @type {boolean} */ (reader.readBool()); + msg.setEnable(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.EditExtensionRequest.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.EditExtensionRequest.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.EditExtensionRequest} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.EditExtensionRequest.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getExtensionId(); + if (f.length > 0) { + writer.writeString( + 1, + f + ); + } + f = message.getEnable(); + if (f) { + writer.writeBool( + 2, + f + ); + } +}; + + +/** + * optional string extension_id = 1; + * @return {string} + */ +proto.hiddifyrpc.EditExtensionRequest.prototype.getExtensionId = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.EditExtensionRequest} returns this + */ +proto.hiddifyrpc.EditExtensionRequest.prototype.setExtensionId = function(value) { + return jspb.Message.setProto3StringField(this, 1, value); +}; + + +/** + * optional bool enable = 2; + * @return {boolean} + */ +proto.hiddifyrpc.EditExtensionRequest.prototype.getEnable = function() { + return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 2, false)); +}; + + +/** + * @param {boolean} value + * @return {!proto.hiddifyrpc.EditExtensionRequest} returns this + */ +proto.hiddifyrpc.EditExtensionRequest.prototype.setEnable = function(value) { + return jspb.Message.setProto3BooleanField(this, 2, value); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.Extension.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.Extension.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.Extension} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.Extension.toObject = function(includeInstance, msg) { + var f, obj = { +id: jspb.Message.getFieldWithDefault(msg, 1, ""), +title: jspb.Message.getFieldWithDefault(msg, 2, ""), +description: jspb.Message.getFieldWithDefault(msg, 3, ""), +enable: jspb.Message.getBooleanFieldWithDefault(msg, 4, false) + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.Extension} + */ +proto.hiddifyrpc.Extension.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.Extension; + return proto.hiddifyrpc.Extension.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.Extension} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.Extension} + */ +proto.hiddifyrpc.Extension.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {string} */ (reader.readString()); + msg.setId(value); + break; + case 2: + var value = /** @type {string} */ (reader.readString()); + msg.setTitle(value); + break; + case 3: + var value = /** @type {string} */ (reader.readString()); + msg.setDescription(value); + break; + case 4: + var value = /** @type {boolean} */ (reader.readBool()); + msg.setEnable(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.Extension.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.Extension.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.Extension} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.Extension.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getId(); + if (f.length > 0) { + writer.writeString( + 1, + f + ); + } + f = message.getTitle(); + if (f.length > 0) { + writer.writeString( + 2, + f + ); + } + f = message.getDescription(); + if (f.length > 0) { + writer.writeString( + 3, + f + ); + } + f = message.getEnable(); + if (f) { + writer.writeBool( + 4, + f + ); + } +}; + + +/** + * optional string id = 1; + * @return {string} + */ +proto.hiddifyrpc.Extension.prototype.getId = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.Extension} returns this + */ +proto.hiddifyrpc.Extension.prototype.setId = function(value) { + return jspb.Message.setProto3StringField(this, 1, value); +}; + + +/** + * optional string title = 2; + * @return {string} + */ +proto.hiddifyrpc.Extension.prototype.getTitle = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.Extension} returns this + */ +proto.hiddifyrpc.Extension.prototype.setTitle = function(value) { + return jspb.Message.setProto3StringField(this, 2, value); +}; + + +/** + * optional string description = 3; + * @return {string} + */ +proto.hiddifyrpc.Extension.prototype.getDescription = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.Extension} returns this + */ +proto.hiddifyrpc.Extension.prototype.setDescription = function(value) { + return jspb.Message.setProto3StringField(this, 3, value); +}; + + +/** + * optional bool enable = 4; + * @return {boolean} + */ +proto.hiddifyrpc.Extension.prototype.getEnable = function() { + return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 4, false)); +}; + + +/** + * @param {boolean} value + * @return {!proto.hiddifyrpc.Extension} returns this + */ +proto.hiddifyrpc.Extension.prototype.setEnable = function(value) { + return jspb.Message.setProto3BooleanField(this, 4, value); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.ExtensionRequest.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.ExtensionRequest.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.ExtensionRequest} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.ExtensionRequest.toObject = function(includeInstance, msg) { + var f, obj = { +extensionId: jspb.Message.getFieldWithDefault(msg, 1, ""), +dataMap: (f = msg.getDataMap()) ? f.toObject(includeInstance, undefined) : [] + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.ExtensionRequest} + */ +proto.hiddifyrpc.ExtensionRequest.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.ExtensionRequest; + return proto.hiddifyrpc.ExtensionRequest.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.ExtensionRequest} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.ExtensionRequest} + */ +proto.hiddifyrpc.ExtensionRequest.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {string} */ (reader.readString()); + msg.setExtensionId(value); + break; + case 2: + var value = msg.getDataMap(); + reader.readMessage(value, function(message, reader) { + jspb.Map.deserializeBinary(message, reader, jspb.BinaryReader.prototype.readString, jspb.BinaryReader.prototype.readString, null, "", ""); + }); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.ExtensionRequest.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.ExtensionRequest.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.ExtensionRequest} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.ExtensionRequest.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getExtensionId(); + if (f.length > 0) { + writer.writeString( + 1, + f + ); + } + f = message.getDataMap(true); + if (f && f.getLength() > 0) { + f.serializeBinary(2, writer, jspb.BinaryWriter.prototype.writeString, jspb.BinaryWriter.prototype.writeString); + } +}; + + +/** + * optional string extension_id = 1; + * @return {string} + */ +proto.hiddifyrpc.ExtensionRequest.prototype.getExtensionId = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.ExtensionRequest} returns this + */ +proto.hiddifyrpc.ExtensionRequest.prototype.setExtensionId = function(value) { + return jspb.Message.setProto3StringField(this, 1, value); +}; + + +/** + * map data = 2; + * @param {boolean=} opt_noLazyCreate Do not create the map if + * empty, instead returning `undefined` + * @return {!jspb.Map} + */ +proto.hiddifyrpc.ExtensionRequest.prototype.getDataMap = function(opt_noLazyCreate) { + return /** @type {!jspb.Map} */ ( + jspb.Message.getMapField(this, 2, opt_noLazyCreate, + null)); +}; + + +/** + * Clears values from the map. The map will be non-null. + * @return {!proto.hiddifyrpc.ExtensionRequest} returns this + */ +proto.hiddifyrpc.ExtensionRequest.prototype.clearDataMap = function() { + this.getDataMap().clear(); + return this; +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.SendExtensionDataRequest.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.SendExtensionDataRequest.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.SendExtensionDataRequest} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.SendExtensionDataRequest.toObject = function(includeInstance, msg) { + var f, obj = { +extensionId: jspb.Message.getFieldWithDefault(msg, 1, ""), +button: jspb.Message.getFieldWithDefault(msg, 2, ""), +dataMap: (f = msg.getDataMap()) ? f.toObject(includeInstance, undefined) : [] + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.SendExtensionDataRequest} + */ +proto.hiddifyrpc.SendExtensionDataRequest.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.SendExtensionDataRequest; + return proto.hiddifyrpc.SendExtensionDataRequest.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.SendExtensionDataRequest} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.SendExtensionDataRequest} + */ +proto.hiddifyrpc.SendExtensionDataRequest.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {string} */ (reader.readString()); + msg.setExtensionId(value); + break; + case 2: + var value = /** @type {string} */ (reader.readString()); + msg.setButton(value); + break; + case 3: + var value = msg.getDataMap(); + reader.readMessage(value, function(message, reader) { + jspb.Map.deserializeBinary(message, reader, jspb.BinaryReader.prototype.readString, jspb.BinaryReader.prototype.readString, null, "", ""); + }); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.SendExtensionDataRequest.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.SendExtensionDataRequest.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.SendExtensionDataRequest} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.SendExtensionDataRequest.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getExtensionId(); + if (f.length > 0) { + writer.writeString( + 1, + f + ); + } + f = message.getButton(); + if (f.length > 0) { + writer.writeString( + 2, + f + ); + } + f = message.getDataMap(true); + if (f && f.getLength() > 0) { + f.serializeBinary(3, writer, jspb.BinaryWriter.prototype.writeString, jspb.BinaryWriter.prototype.writeString); + } +}; + + +/** + * optional string extension_id = 1; + * @return {string} + */ +proto.hiddifyrpc.SendExtensionDataRequest.prototype.getExtensionId = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.SendExtensionDataRequest} returns this + */ +proto.hiddifyrpc.SendExtensionDataRequest.prototype.setExtensionId = function(value) { + return jspb.Message.setProto3StringField(this, 1, value); +}; + + +/** + * optional string button = 2; + * @return {string} + */ +proto.hiddifyrpc.SendExtensionDataRequest.prototype.getButton = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.SendExtensionDataRequest} returns this + */ +proto.hiddifyrpc.SendExtensionDataRequest.prototype.setButton = function(value) { + return jspb.Message.setProto3StringField(this, 2, value); +}; + + +/** + * map data = 3; + * @param {boolean=} opt_noLazyCreate Do not create the map if + * empty, instead returning `undefined` + * @return {!jspb.Map} + */ +proto.hiddifyrpc.SendExtensionDataRequest.prototype.getDataMap = function(opt_noLazyCreate) { + return /** @type {!jspb.Map} */ ( + jspb.Message.getMapField(this, 3, opt_noLazyCreate, + null)); +}; + + +/** + * Clears values from the map. The map will be non-null. + * @return {!proto.hiddifyrpc.SendExtensionDataRequest} returns this + */ +proto.hiddifyrpc.SendExtensionDataRequest.prototype.clearDataMap = function() { + this.getDataMap().clear(); + return this; +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.ExtensionResponse.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.ExtensionResponse.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.ExtensionResponse} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.ExtensionResponse.toObject = function(includeInstance, msg) { + var f, obj = { +type: jspb.Message.getFieldWithDefault(msg, 1, 0), +extensionId: jspb.Message.getFieldWithDefault(msg, 2, ""), +jsonUi: jspb.Message.getFieldWithDefault(msg, 3, "") + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.ExtensionResponse} + */ +proto.hiddifyrpc.ExtensionResponse.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.ExtensionResponse; + return proto.hiddifyrpc.ExtensionResponse.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.ExtensionResponse} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.ExtensionResponse} + */ +proto.hiddifyrpc.ExtensionResponse.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {!proto.hiddifyrpc.ExtensionResponseType} */ (reader.readEnum()); + msg.setType(value); + break; + case 2: + var value = /** @type {string} */ (reader.readString()); + msg.setExtensionId(value); + break; + case 3: + var value = /** @type {string} */ (reader.readString()); + msg.setJsonUi(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.ExtensionResponse.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.ExtensionResponse.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.ExtensionResponse} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.ExtensionResponse.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getType(); + if (f !== 0.0) { + writer.writeEnum( + 1, + f + ); + } + f = message.getExtensionId(); + if (f.length > 0) { + writer.writeString( + 2, + f + ); + } + f = message.getJsonUi(); + if (f.length > 0) { + writer.writeString( + 3, + f + ); + } +}; + + +/** + * optional ExtensionResponseType type = 1; + * @return {!proto.hiddifyrpc.ExtensionResponseType} + */ +proto.hiddifyrpc.ExtensionResponse.prototype.getType = function() { + return /** @type {!proto.hiddifyrpc.ExtensionResponseType} */ (jspb.Message.getFieldWithDefault(this, 1, 0)); +}; + + +/** + * @param {!proto.hiddifyrpc.ExtensionResponseType} value + * @return {!proto.hiddifyrpc.ExtensionResponse} returns this + */ +proto.hiddifyrpc.ExtensionResponse.prototype.setType = function(value) { + return jspb.Message.setProto3EnumField(this, 1, value); +}; + + +/** + * optional string extension_id = 2; + * @return {string} + */ +proto.hiddifyrpc.ExtensionResponse.prototype.getExtensionId = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.ExtensionResponse} returns this + */ +proto.hiddifyrpc.ExtensionResponse.prototype.setExtensionId = function(value) { + return jspb.Message.setProto3StringField(this, 2, value); +}; + + +/** + * optional string json_ui = 3; + * @return {string} + */ +proto.hiddifyrpc.ExtensionResponse.prototype.getJsonUi = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.ExtensionResponse} returns this + */ +proto.hiddifyrpc.ExtensionResponse.prototype.setJsonUi = function(value) { + return jspb.Message.setProto3StringField(this, 3, value); +}; + + +/** + * @enum {number} + */ +proto.hiddifyrpc.ExtensionResponseType = { + NOTHING: 0, + UPDATE_UI: 1, + SHOW_DIALOG: 2, + END: 3 +}; + +goog.object.extend(exports, proto.hiddifyrpc); diff --git a/libcore/extension/html/rpc/formRenderer.js b/libcore/extension/html/rpc/formRenderer.js new file mode 100644 index 0000000..3f7128d --- /dev/null +++ b/libcore/extension/html/rpc/formRenderer.js @@ -0,0 +1,239 @@ + +const ansi_up = new AnsiUp({ + escape_html: false, + +}); + + +function renderForm(json, dialog, submitAction, stopAction) { + const container = document.getElementById(`extension-page-container${dialog}`); + const formId = `dynamicForm${json.id}${dialog}`; + + const existingForm = document.getElementById(formId); + if (existingForm) { + existingForm.remove(); + } + const form = document.createElement('form'); + container.appendChild(form); + form.id = formId; + + if (dialog === "dialog") { + document.getElementById("modalLabel").textContent = json.title; + } else { + const titleElement = createTitleElement(json); + const stopBtn = document.createElement('button'); + stopBtn.type = 'button'; + stopBtn.className = 'btn btn-danger'; + stopBtn.textContent = 'Close'; + stopBtn.addEventListener('click', stopAction); + form.appendChild(stopBtn); + form.appendChild(titleElement); + } + addElementsToForm(form, json,submitAction); + + if (dialog === "dialog") { + document.getElementById("modal-footer").innerHTML = ''; + // if ($(form.lastChild).find("button").length > 0) { + + // document.getElementById("modal-footer").appendChild(form.lastChild); + + // } + const extensionDialog = document.getElementById("extension-dialog"); + const dialog = bootstrap.Modal.getOrCreateInstance(extensionDialog); + dialog.show(); + extensionDialog.addEventListener("hidden.bs.modal", (e)=>submitAction(e,"CloseDialog")); + } + +} + +function addElementsToForm(form, json,submitAction) { + + + + const description = document.createElement('p'); + description.textContent = json.description; + form.appendChild(description); + if (json.fields) { + json.fields.forEach(field => { + div=document.createElement("div") + div.classList.add("row") + form.appendChild(div) + for (let i = 0; i < field.length; i++) { + const formGroup = createFormGroup(field[i], submitAction); + formGroup.classList.add("col") + div.appendChild(formGroup); + } + }); + } + + return form; +} + +function createTitleElement(json) { + const title = document.createElement('h1'); + title.textContent = json.title; + return title; +} + +function createFormGroup(field, submitAction) { + const formGroup = document.createElement('div'); + formGroup.classList.add('mb-3'); + if (field.type == "Button") { + const button = document.createElement('button'); + button.textContent = field.label; + button.name=field.key + button.classList.add('btn'); + if (field.key == "Submit") { + button.classList.add('btn-primary'); + } else if (field.key == "Cancel") { + button.classList.add('btn-secondary'); + }else{ + button.classList.add('btn', 'btn-outline-secondary'); + } + + button.addEventListener('click', (e) => submitAction(e,field.key)); + formGroup.appendChild(button); + } else { + if (field.label && !field.labelHidden) { + const label = document.createElement('label'); + label.textContent = field.label; + label.setAttribute('for', field.key); + formGroup.appendChild(label); + } + + const input = createInputElement(field); + formGroup.appendChild(input); + } + return formGroup; +} + +function createInputElement(field) { + let input; + + switch (field.type) { + case "Console": + input = document.createElement('pre'); + input.innerHTML = ansi_up.ansi_to_html(field.value || field.placeholder || ''); + input.style.maxHeight = field.lines * 20 + 'px'; + break; + case "TextArea": + input = document.createElement('textarea'); + input.rows = field.lines || 3; + input.textContent = field.value || ''; + break; + + case "Checkbox": + case "RadioButton": + input = createCheckboxOrRadioGroup(field); + break; + + case "Switch": + input = createSwitchElement(field); + break; + + case "Select": + input = document.createElement('select'); + field.items.forEach(item => { + const option = document.createElement('option'); + option.value = item.value; + option.text = item.label; + input.appendChild(option); + }); + break; + + default: + input = document.createElement('input'); + input.type = field.type.toLowerCase(); + input.value = field.value; + break; + } + + input.id = field.key; + input.name = field.key; + if (field.readOnly) input.readOnly = true; + if (field.type == "Checkbox" || field.type == "RadioButton" || field.type == "Switch") { + + } else { + if (field.required) input.required = true; + input.classList.add('form-control'); + if (field.placeholder) input.placeholder = field.placeholder; + } + return input; +} + +function createCheckboxOrRadioGroup(field) { + const wrapper = document.createDocumentFragment(); + + field.items.forEach(item => { + const inputWrapper = document.createElement('div'); + inputWrapper.classList.add('form-check'); + + const input = document.createElement('input'); + input.type = field.type === "Checkbox" ? 'checkbox' : 'radio'; + input.classList.add('form-check-input'); + input.id = `${field.key}_${item.value}`; + input.name = field.key; // Grouping by name for radio buttons + input.value = item.value; + input.checked = field.value === item.value; + + const itemLabel = document.createElement('label'); + itemLabel.classList.add('form-check-label'); + itemLabel.setAttribute('for', input.id); + itemLabel.textContent = item.label; + + inputWrapper.appendChild(input); + inputWrapper.appendChild(itemLabel); + wrapper.appendChild(inputWrapper); + }); + + return wrapper; +} + +function createSwitchElement(field) { + const switchWrapper = document.createElement('div'); + switchWrapper.classList.add('form-check', 'form-switch'); + + const input = document.createElement('input'); + input.type = 'checkbox'; + input.classList.add('form-check-input'); + input.setAttribute('role', 'switch'); + input.id = field.key; + input.checked = field.value === "true"; + + const label = document.createElement('label'); + label.classList.add('form-check-label'); + label.setAttribute('for', field.key); + label.textContent = field.label; + + switchWrapper.appendChild(input); + switchWrapper.appendChild(label); + + return switchWrapper; +} + +function createButtonGroup(json, submitAction, cancelAction) { + const buttonGroup = document.createElement('div'); + buttonGroup.classList.add('btn-group'); + json.buttons.forEach(buttonText => { + const btn = document.createElement('button'); + btn.classList.add('btn', "btn-default"); + buttonGroup.appendChild(btn); + btn.textContent = buttonText + if (buttonText == "Cancel") { + btn.classList.add('btn-secondary'); + btn.addEventListener('click', cancelAction); + } else { + if (buttonText == "Submit" || buttonText == "Ok") + btn.classList.add('btn-primary'); + btn.addEventListener('click', submitAction); + } + + }) + + + + return buttonGroup; +} + + +module.exports = { renderForm }; \ No newline at end of file diff --git a/libcore/extension/html/rpc/hiddify_grpc_web_pb.js b/libcore/extension/html/rpc/hiddify_grpc_web_pb.js new file mode 100644 index 0000000..0b44622 --- /dev/null +++ b/libcore/extension/html/rpc/hiddify_grpc_web_pb.js @@ -0,0 +1,1501 @@ +/** + * @fileoverview gRPC-Web generated client stub for hiddifyrpc + * @enhanceable + * @public + */ + +// Code generated by protoc-gen-grpc-web. DO NOT EDIT. +// versions: +// protoc-gen-grpc-web v1.5.0 +// protoc v5.28.0 +// source: hiddify.proto + + +/* eslint-disable */ +// @ts-nocheck + + + +const grpc = {}; +grpc.web = require('grpc-web'); + + +var base_pb = require('./base_pb.js') +const proto = {}; +proto.hiddifyrpc = require('./hiddify_pb.js'); + +/** + * @param {string} hostname + * @param {?Object} credentials + * @param {?grpc.web.ClientOptions} options + * @constructor + * @struct + * @final + */ +proto.hiddifyrpc.HelloClient = + function(hostname, credentials, options) { + if (!options) options = {}; + options.format = 'text'; + + /** + * @private @const {!grpc.web.GrpcWebClientBase} The client + */ + this.client_ = new grpc.web.GrpcWebClientBase(options); + + /** + * @private @const {string} The hostname + */ + this.hostname_ = hostname.replace(/\/+$/, ''); + +}; + + +/** + * @param {string} hostname + * @param {?Object} credentials + * @param {?grpc.web.ClientOptions} options + * @constructor + * @struct + * @final + */ +proto.hiddifyrpc.HelloPromiseClient = + function(hostname, credentials, options) { + if (!options) options = {}; + options.format = 'text'; + + /** + * @private @const {!grpc.web.GrpcWebClientBase} The client + */ + this.client_ = new grpc.web.GrpcWebClientBase(options); + + /** + * @private @const {string} The hostname + */ + this.hostname_ = hostname.replace(/\/+$/, ''); + +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.HelloRequest, + * !proto.hiddifyrpc.HelloResponse>} + */ +const methodDescriptor_Hello_SayHello = new grpc.web.MethodDescriptor( + '/hiddifyrpc.Hello/SayHello', + grpc.web.MethodType.UNARY, + base_pb.HelloRequest, + base_pb.HelloResponse, + /** + * @param {!proto.hiddifyrpc.HelloRequest} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + base_pb.HelloResponse.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.HelloRequest} request The + * request proto + * @param {?Object} metadata User defined + * call metadata + * @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.HelloResponse)} + * callback The callback function(error, response) + * @return {!grpc.web.ClientReadableStream|undefined} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.HelloClient.prototype.sayHello = + function(request, metadata, callback) { + return this.client_.rpcCall(this.hostname_ + + '/hiddifyrpc.Hello/SayHello', + request, + metadata || {}, + methodDescriptor_Hello_SayHello, + callback); +}; + + +/** + * @param {!proto.hiddifyrpc.HelloRequest} request The + * request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!Promise} + * Promise that resolves to the response + */ +proto.hiddifyrpc.HelloPromiseClient.prototype.sayHello = + function(request, metadata) { + return this.client_.unaryCall(this.hostname_ + + '/hiddifyrpc.Hello/SayHello', + request, + metadata || {}, + methodDescriptor_Hello_SayHello); +}; + + +/** + * @param {string} hostname + * @param {?Object} credentials + * @param {?grpc.web.ClientOptions} options + * @constructor + * @struct + * @final + */ +proto.hiddifyrpc.CoreClient = + function(hostname, credentials, options) { + if (!options) options = {}; + options.format = 'text'; + + /** + * @private @const {!grpc.web.GrpcWebClientBase} The client + */ + this.client_ = new grpc.web.GrpcWebClientBase(options); + + /** + * @private @const {string} The hostname + */ + this.hostname_ = hostname.replace(/\/+$/, ''); + +}; + + +/** + * @param {string} hostname + * @param {?Object} credentials + * @param {?grpc.web.ClientOptions} options + * @constructor + * @struct + * @final + */ +proto.hiddifyrpc.CorePromiseClient = + function(hostname, credentials, options) { + if (!options) options = {}; + options.format = 'text'; + + /** + * @private @const {!grpc.web.GrpcWebClientBase} The client + */ + this.client_ = new grpc.web.GrpcWebClientBase(options); + + /** + * @private @const {string} The hostname + */ + this.hostname_ = hostname.replace(/\/+$/, ''); + +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.StartRequest, + * !proto.hiddifyrpc.CoreInfoResponse>} + */ +const methodDescriptor_Core_Start = new grpc.web.MethodDescriptor( + '/hiddifyrpc.Core/Start', + grpc.web.MethodType.UNARY, + proto.hiddifyrpc.StartRequest, + proto.hiddifyrpc.CoreInfoResponse, + /** + * @param {!proto.hiddifyrpc.StartRequest} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.CoreInfoResponse.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.StartRequest} request The + * request proto + * @param {?Object} metadata User defined + * call metadata + * @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.CoreInfoResponse)} + * callback The callback function(error, response) + * @return {!grpc.web.ClientReadableStream|undefined} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.CoreClient.prototype.start = + function(request, metadata, callback) { + return this.client_.rpcCall(this.hostname_ + + '/hiddifyrpc.Core/Start', + request, + metadata || {}, + methodDescriptor_Core_Start, + callback); +}; + + +/** + * @param {!proto.hiddifyrpc.StartRequest} request The + * request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!Promise} + * Promise that resolves to the response + */ +proto.hiddifyrpc.CorePromiseClient.prototype.start = + function(request, metadata) { + return this.client_.unaryCall(this.hostname_ + + '/hiddifyrpc.Core/Start', + request, + metadata || {}, + methodDescriptor_Core_Start); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.Empty, + * !proto.hiddifyrpc.CoreInfoResponse>} + */ +const methodDescriptor_Core_CoreInfoListener = new grpc.web.MethodDescriptor( + '/hiddifyrpc.Core/CoreInfoListener', + grpc.web.MethodType.SERVER_STREAMING, + base_pb.Empty, + proto.hiddifyrpc.CoreInfoResponse, + /** + * @param {!proto.hiddifyrpc.Empty} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.CoreInfoResponse.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.Empty} request The request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!grpc.web.ClientReadableStream} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.CoreClient.prototype.coreInfoListener = + function(request, metadata) { + return this.client_.serverStreaming(this.hostname_ + + '/hiddifyrpc.Core/CoreInfoListener', + request, + metadata || {}, + methodDescriptor_Core_CoreInfoListener); +}; + + +/** + * @param {!proto.hiddifyrpc.Empty} request The request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!grpc.web.ClientReadableStream} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.CorePromiseClient.prototype.coreInfoListener = + function(request, metadata) { + return this.client_.serverStreaming(this.hostname_ + + '/hiddifyrpc.Core/CoreInfoListener', + request, + metadata || {}, + methodDescriptor_Core_CoreInfoListener); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.Empty, + * !proto.hiddifyrpc.OutboundGroupList>} + */ +const methodDescriptor_Core_OutboundsInfo = new grpc.web.MethodDescriptor( + '/hiddifyrpc.Core/OutboundsInfo', + grpc.web.MethodType.SERVER_STREAMING, + base_pb.Empty, + proto.hiddifyrpc.OutboundGroupList, + /** + * @param {!proto.hiddifyrpc.Empty} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.OutboundGroupList.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.Empty} request The request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!grpc.web.ClientReadableStream} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.CoreClient.prototype.outboundsInfo = + function(request, metadata) { + return this.client_.serverStreaming(this.hostname_ + + '/hiddifyrpc.Core/OutboundsInfo', + request, + metadata || {}, + methodDescriptor_Core_OutboundsInfo); +}; + + +/** + * @param {!proto.hiddifyrpc.Empty} request The request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!grpc.web.ClientReadableStream} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.CorePromiseClient.prototype.outboundsInfo = + function(request, metadata) { + return this.client_.serverStreaming(this.hostname_ + + '/hiddifyrpc.Core/OutboundsInfo', + request, + metadata || {}, + methodDescriptor_Core_OutboundsInfo); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.Empty, + * !proto.hiddifyrpc.OutboundGroupList>} + */ +const methodDescriptor_Core_MainOutboundsInfo = new grpc.web.MethodDescriptor( + '/hiddifyrpc.Core/MainOutboundsInfo', + grpc.web.MethodType.SERVER_STREAMING, + base_pb.Empty, + proto.hiddifyrpc.OutboundGroupList, + /** + * @param {!proto.hiddifyrpc.Empty} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.OutboundGroupList.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.Empty} request The request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!grpc.web.ClientReadableStream} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.CoreClient.prototype.mainOutboundsInfo = + function(request, metadata) { + return this.client_.serverStreaming(this.hostname_ + + '/hiddifyrpc.Core/MainOutboundsInfo', + request, + metadata || {}, + methodDescriptor_Core_MainOutboundsInfo); +}; + + +/** + * @param {!proto.hiddifyrpc.Empty} request The request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!grpc.web.ClientReadableStream} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.CorePromiseClient.prototype.mainOutboundsInfo = + function(request, metadata) { + return this.client_.serverStreaming(this.hostname_ + + '/hiddifyrpc.Core/MainOutboundsInfo', + request, + metadata || {}, + methodDescriptor_Core_MainOutboundsInfo); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.Empty, + * !proto.hiddifyrpc.SystemInfo>} + */ +const methodDescriptor_Core_GetSystemInfo = new grpc.web.MethodDescriptor( + '/hiddifyrpc.Core/GetSystemInfo', + grpc.web.MethodType.SERVER_STREAMING, + base_pb.Empty, + proto.hiddifyrpc.SystemInfo, + /** + * @param {!proto.hiddifyrpc.Empty} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.SystemInfo.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.Empty} request The request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!grpc.web.ClientReadableStream} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.CoreClient.prototype.getSystemInfo = + function(request, metadata) { + return this.client_.serverStreaming(this.hostname_ + + '/hiddifyrpc.Core/GetSystemInfo', + request, + metadata || {}, + methodDescriptor_Core_GetSystemInfo); +}; + + +/** + * @param {!proto.hiddifyrpc.Empty} request The request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!grpc.web.ClientReadableStream} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.CorePromiseClient.prototype.getSystemInfo = + function(request, metadata) { + return this.client_.serverStreaming(this.hostname_ + + '/hiddifyrpc.Core/GetSystemInfo', + request, + metadata || {}, + methodDescriptor_Core_GetSystemInfo); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.SetupRequest, + * !proto.hiddifyrpc.Response>} + */ +const methodDescriptor_Core_Setup = new grpc.web.MethodDescriptor( + '/hiddifyrpc.Core/Setup', + grpc.web.MethodType.UNARY, + proto.hiddifyrpc.SetupRequest, + proto.hiddifyrpc.Response, + /** + * @param {!proto.hiddifyrpc.SetupRequest} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.Response.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.SetupRequest} request The + * request proto + * @param {?Object} metadata User defined + * call metadata + * @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.Response)} + * callback The callback function(error, response) + * @return {!grpc.web.ClientReadableStream|undefined} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.CoreClient.prototype.setup = + function(request, metadata, callback) { + return this.client_.rpcCall(this.hostname_ + + '/hiddifyrpc.Core/Setup', + request, + metadata || {}, + methodDescriptor_Core_Setup, + callback); +}; + + +/** + * @param {!proto.hiddifyrpc.SetupRequest} request The + * request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!Promise} + * Promise that resolves to the response + */ +proto.hiddifyrpc.CorePromiseClient.prototype.setup = + function(request, metadata) { + return this.client_.unaryCall(this.hostname_ + + '/hiddifyrpc.Core/Setup', + request, + metadata || {}, + methodDescriptor_Core_Setup); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.ParseRequest, + * !proto.hiddifyrpc.ParseResponse>} + */ +const methodDescriptor_Core_Parse = new grpc.web.MethodDescriptor( + '/hiddifyrpc.Core/Parse', + grpc.web.MethodType.UNARY, + proto.hiddifyrpc.ParseRequest, + proto.hiddifyrpc.ParseResponse, + /** + * @param {!proto.hiddifyrpc.ParseRequest} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.ParseResponse.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.ParseRequest} request The + * request proto + * @param {?Object} metadata User defined + * call metadata + * @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.ParseResponse)} + * callback The callback function(error, response) + * @return {!grpc.web.ClientReadableStream|undefined} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.CoreClient.prototype.parse = + function(request, metadata, callback) { + return this.client_.rpcCall(this.hostname_ + + '/hiddifyrpc.Core/Parse', + request, + metadata || {}, + methodDescriptor_Core_Parse, + callback); +}; + + +/** + * @param {!proto.hiddifyrpc.ParseRequest} request The + * request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!Promise} + * Promise that resolves to the response + */ +proto.hiddifyrpc.CorePromiseClient.prototype.parse = + function(request, metadata) { + return this.client_.unaryCall(this.hostname_ + + '/hiddifyrpc.Core/Parse', + request, + metadata || {}, + methodDescriptor_Core_Parse); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.ChangeHiddifySettingsRequest, + * !proto.hiddifyrpc.CoreInfoResponse>} + */ +const methodDescriptor_Core_ChangeHiddifySettings = new grpc.web.MethodDescriptor( + '/hiddifyrpc.Core/ChangeHiddifySettings', + grpc.web.MethodType.UNARY, + proto.hiddifyrpc.ChangeHiddifySettingsRequest, + proto.hiddifyrpc.CoreInfoResponse, + /** + * @param {!proto.hiddifyrpc.ChangeHiddifySettingsRequest} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.CoreInfoResponse.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.ChangeHiddifySettingsRequest} request The + * request proto + * @param {?Object} metadata User defined + * call metadata + * @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.CoreInfoResponse)} + * callback The callback function(error, response) + * @return {!grpc.web.ClientReadableStream|undefined} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.CoreClient.prototype.changeHiddifySettings = + function(request, metadata, callback) { + return this.client_.rpcCall(this.hostname_ + + '/hiddifyrpc.Core/ChangeHiddifySettings', + request, + metadata || {}, + methodDescriptor_Core_ChangeHiddifySettings, + callback); +}; + + +/** + * @param {!proto.hiddifyrpc.ChangeHiddifySettingsRequest} request The + * request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!Promise} + * Promise that resolves to the response + */ +proto.hiddifyrpc.CorePromiseClient.prototype.changeHiddifySettings = + function(request, metadata) { + return this.client_.unaryCall(this.hostname_ + + '/hiddifyrpc.Core/ChangeHiddifySettings', + request, + metadata || {}, + methodDescriptor_Core_ChangeHiddifySettings); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.StartRequest, + * !proto.hiddifyrpc.CoreInfoResponse>} + */ +const methodDescriptor_Core_StartService = new grpc.web.MethodDescriptor( + '/hiddifyrpc.Core/StartService', + grpc.web.MethodType.UNARY, + proto.hiddifyrpc.StartRequest, + proto.hiddifyrpc.CoreInfoResponse, + /** + * @param {!proto.hiddifyrpc.StartRequest} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.CoreInfoResponse.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.StartRequest} request The + * request proto + * @param {?Object} metadata User defined + * call metadata + * @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.CoreInfoResponse)} + * callback The callback function(error, response) + * @return {!grpc.web.ClientReadableStream|undefined} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.CoreClient.prototype.startService = + function(request, metadata, callback) { + return this.client_.rpcCall(this.hostname_ + + '/hiddifyrpc.Core/StartService', + request, + metadata || {}, + methodDescriptor_Core_StartService, + callback); +}; + + +/** + * @param {!proto.hiddifyrpc.StartRequest} request The + * request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!Promise} + * Promise that resolves to the response + */ +proto.hiddifyrpc.CorePromiseClient.prototype.startService = + function(request, metadata) { + return this.client_.unaryCall(this.hostname_ + + '/hiddifyrpc.Core/StartService', + request, + metadata || {}, + methodDescriptor_Core_StartService); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.Empty, + * !proto.hiddifyrpc.CoreInfoResponse>} + */ +const methodDescriptor_Core_Stop = new grpc.web.MethodDescriptor( + '/hiddifyrpc.Core/Stop', + grpc.web.MethodType.UNARY, + base_pb.Empty, + proto.hiddifyrpc.CoreInfoResponse, + /** + * @param {!proto.hiddifyrpc.Empty} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.CoreInfoResponse.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.Empty} request The + * request proto + * @param {?Object} metadata User defined + * call metadata + * @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.CoreInfoResponse)} + * callback The callback function(error, response) + * @return {!grpc.web.ClientReadableStream|undefined} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.CoreClient.prototype.stop = + function(request, metadata, callback) { + return this.client_.rpcCall(this.hostname_ + + '/hiddifyrpc.Core/Stop', + request, + metadata || {}, + methodDescriptor_Core_Stop, + callback); +}; + + +/** + * @param {!proto.hiddifyrpc.Empty} request The + * request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!Promise} + * Promise that resolves to the response + */ +proto.hiddifyrpc.CorePromiseClient.prototype.stop = + function(request, metadata) { + return this.client_.unaryCall(this.hostname_ + + '/hiddifyrpc.Core/Stop', + request, + metadata || {}, + methodDescriptor_Core_Stop); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.StartRequest, + * !proto.hiddifyrpc.CoreInfoResponse>} + */ +const methodDescriptor_Core_Restart = new grpc.web.MethodDescriptor( + '/hiddifyrpc.Core/Restart', + grpc.web.MethodType.UNARY, + proto.hiddifyrpc.StartRequest, + proto.hiddifyrpc.CoreInfoResponse, + /** + * @param {!proto.hiddifyrpc.StartRequest} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.CoreInfoResponse.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.StartRequest} request The + * request proto + * @param {?Object} metadata User defined + * call metadata + * @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.CoreInfoResponse)} + * callback The callback function(error, response) + * @return {!grpc.web.ClientReadableStream|undefined} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.CoreClient.prototype.restart = + function(request, metadata, callback) { + return this.client_.rpcCall(this.hostname_ + + '/hiddifyrpc.Core/Restart', + request, + metadata || {}, + methodDescriptor_Core_Restart, + callback); +}; + + +/** + * @param {!proto.hiddifyrpc.StartRequest} request The + * request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!Promise} + * Promise that resolves to the response + */ +proto.hiddifyrpc.CorePromiseClient.prototype.restart = + function(request, metadata) { + return this.client_.unaryCall(this.hostname_ + + '/hiddifyrpc.Core/Restart', + request, + metadata || {}, + methodDescriptor_Core_Restart); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.SelectOutboundRequest, + * !proto.hiddifyrpc.Response>} + */ +const methodDescriptor_Core_SelectOutbound = new grpc.web.MethodDescriptor( + '/hiddifyrpc.Core/SelectOutbound', + grpc.web.MethodType.UNARY, + proto.hiddifyrpc.SelectOutboundRequest, + proto.hiddifyrpc.Response, + /** + * @param {!proto.hiddifyrpc.SelectOutboundRequest} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.Response.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.SelectOutboundRequest} request The + * request proto + * @param {?Object} metadata User defined + * call metadata + * @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.Response)} + * callback The callback function(error, response) + * @return {!grpc.web.ClientReadableStream|undefined} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.CoreClient.prototype.selectOutbound = + function(request, metadata, callback) { + return this.client_.rpcCall(this.hostname_ + + '/hiddifyrpc.Core/SelectOutbound', + request, + metadata || {}, + methodDescriptor_Core_SelectOutbound, + callback); +}; + + +/** + * @param {!proto.hiddifyrpc.SelectOutboundRequest} request The + * request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!Promise} + * Promise that resolves to the response + */ +proto.hiddifyrpc.CorePromiseClient.prototype.selectOutbound = + function(request, metadata) { + return this.client_.unaryCall(this.hostname_ + + '/hiddifyrpc.Core/SelectOutbound', + request, + metadata || {}, + methodDescriptor_Core_SelectOutbound); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.UrlTestRequest, + * !proto.hiddifyrpc.Response>} + */ +const methodDescriptor_Core_UrlTest = new grpc.web.MethodDescriptor( + '/hiddifyrpc.Core/UrlTest', + grpc.web.MethodType.UNARY, + proto.hiddifyrpc.UrlTestRequest, + proto.hiddifyrpc.Response, + /** + * @param {!proto.hiddifyrpc.UrlTestRequest} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.Response.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.UrlTestRequest} request The + * request proto + * @param {?Object} metadata User defined + * call metadata + * @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.Response)} + * callback The callback function(error, response) + * @return {!grpc.web.ClientReadableStream|undefined} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.CoreClient.prototype.urlTest = + function(request, metadata, callback) { + return this.client_.rpcCall(this.hostname_ + + '/hiddifyrpc.Core/UrlTest', + request, + metadata || {}, + methodDescriptor_Core_UrlTest, + callback); +}; + + +/** + * @param {!proto.hiddifyrpc.UrlTestRequest} request The + * request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!Promise} + * Promise that resolves to the response + */ +proto.hiddifyrpc.CorePromiseClient.prototype.urlTest = + function(request, metadata) { + return this.client_.unaryCall(this.hostname_ + + '/hiddifyrpc.Core/UrlTest', + request, + metadata || {}, + methodDescriptor_Core_UrlTest); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.GenerateWarpConfigRequest, + * !proto.hiddifyrpc.WarpGenerationResponse>} + */ +const methodDescriptor_Core_GenerateWarpConfig = new grpc.web.MethodDescriptor( + '/hiddifyrpc.Core/GenerateWarpConfig', + grpc.web.MethodType.UNARY, + proto.hiddifyrpc.GenerateWarpConfigRequest, + proto.hiddifyrpc.WarpGenerationResponse, + /** + * @param {!proto.hiddifyrpc.GenerateWarpConfigRequest} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.WarpGenerationResponse.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.GenerateWarpConfigRequest} request The + * request proto + * @param {?Object} metadata User defined + * call metadata + * @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.WarpGenerationResponse)} + * callback The callback function(error, response) + * @return {!grpc.web.ClientReadableStream|undefined} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.CoreClient.prototype.generateWarpConfig = + function(request, metadata, callback) { + return this.client_.rpcCall(this.hostname_ + + '/hiddifyrpc.Core/GenerateWarpConfig', + request, + metadata || {}, + methodDescriptor_Core_GenerateWarpConfig, + callback); +}; + + +/** + * @param {!proto.hiddifyrpc.GenerateWarpConfigRequest} request The + * request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!Promise} + * Promise that resolves to the response + */ +proto.hiddifyrpc.CorePromiseClient.prototype.generateWarpConfig = + function(request, metadata) { + return this.client_.unaryCall(this.hostname_ + + '/hiddifyrpc.Core/GenerateWarpConfig', + request, + metadata || {}, + methodDescriptor_Core_GenerateWarpConfig); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.Empty, + * !proto.hiddifyrpc.SystemProxyStatus>} + */ +const methodDescriptor_Core_GetSystemProxyStatus = new grpc.web.MethodDescriptor( + '/hiddifyrpc.Core/GetSystemProxyStatus', + grpc.web.MethodType.UNARY, + base_pb.Empty, + proto.hiddifyrpc.SystemProxyStatus, + /** + * @param {!proto.hiddifyrpc.Empty} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.SystemProxyStatus.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.Empty} request The + * request proto + * @param {?Object} metadata User defined + * call metadata + * @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.SystemProxyStatus)} + * callback The callback function(error, response) + * @return {!grpc.web.ClientReadableStream|undefined} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.CoreClient.prototype.getSystemProxyStatus = + function(request, metadata, callback) { + return this.client_.rpcCall(this.hostname_ + + '/hiddifyrpc.Core/GetSystemProxyStatus', + request, + metadata || {}, + methodDescriptor_Core_GetSystemProxyStatus, + callback); +}; + + +/** + * @param {!proto.hiddifyrpc.Empty} request The + * request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!Promise} + * Promise that resolves to the response + */ +proto.hiddifyrpc.CorePromiseClient.prototype.getSystemProxyStatus = + function(request, metadata) { + return this.client_.unaryCall(this.hostname_ + + '/hiddifyrpc.Core/GetSystemProxyStatus', + request, + metadata || {}, + methodDescriptor_Core_GetSystemProxyStatus); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.SetSystemProxyEnabledRequest, + * !proto.hiddifyrpc.Response>} + */ +const methodDescriptor_Core_SetSystemProxyEnabled = new grpc.web.MethodDescriptor( + '/hiddifyrpc.Core/SetSystemProxyEnabled', + grpc.web.MethodType.UNARY, + proto.hiddifyrpc.SetSystemProxyEnabledRequest, + proto.hiddifyrpc.Response, + /** + * @param {!proto.hiddifyrpc.SetSystemProxyEnabledRequest} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.Response.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.SetSystemProxyEnabledRequest} request The + * request proto + * @param {?Object} metadata User defined + * call metadata + * @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.Response)} + * callback The callback function(error, response) + * @return {!grpc.web.ClientReadableStream|undefined} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.CoreClient.prototype.setSystemProxyEnabled = + function(request, metadata, callback) { + return this.client_.rpcCall(this.hostname_ + + '/hiddifyrpc.Core/SetSystemProxyEnabled', + request, + metadata || {}, + methodDescriptor_Core_SetSystemProxyEnabled, + callback); +}; + + +/** + * @param {!proto.hiddifyrpc.SetSystemProxyEnabledRequest} request The + * request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!Promise} + * Promise that resolves to the response + */ +proto.hiddifyrpc.CorePromiseClient.prototype.setSystemProxyEnabled = + function(request, metadata) { + return this.client_.unaryCall(this.hostname_ + + '/hiddifyrpc.Core/SetSystemProxyEnabled', + request, + metadata || {}, + methodDescriptor_Core_SetSystemProxyEnabled); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.Empty, + * !proto.hiddifyrpc.LogMessage>} + */ +const methodDescriptor_Core_LogListener = new grpc.web.MethodDescriptor( + '/hiddifyrpc.Core/LogListener', + grpc.web.MethodType.SERVER_STREAMING, + base_pb.Empty, + proto.hiddifyrpc.LogMessage, + /** + * @param {!proto.hiddifyrpc.Empty} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.LogMessage.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.Empty} request The request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!grpc.web.ClientReadableStream} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.CoreClient.prototype.logListener = + function(request, metadata) { + return this.client_.serverStreaming(this.hostname_ + + '/hiddifyrpc.Core/LogListener', + request, + metadata || {}, + methodDescriptor_Core_LogListener); +}; + + +/** + * @param {!proto.hiddifyrpc.Empty} request The request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!grpc.web.ClientReadableStream} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.CorePromiseClient.prototype.logListener = + function(request, metadata) { + return this.client_.serverStreaming(this.hostname_ + + '/hiddifyrpc.Core/LogListener', + request, + metadata || {}, + methodDescriptor_Core_LogListener); +}; + + +/** + * @param {string} hostname + * @param {?Object} credentials + * @param {?grpc.web.ClientOptions} options + * @constructor + * @struct + * @final + */ +proto.hiddifyrpc.TunnelServiceClient = + function(hostname, credentials, options) { + if (!options) options = {}; + options.format = 'text'; + + /** + * @private @const {!grpc.web.GrpcWebClientBase} The client + */ + this.client_ = new grpc.web.GrpcWebClientBase(options); + + /** + * @private @const {string} The hostname + */ + this.hostname_ = hostname.replace(/\/+$/, ''); + +}; + + +/** + * @param {string} hostname + * @param {?Object} credentials + * @param {?grpc.web.ClientOptions} options + * @constructor + * @struct + * @final + */ +proto.hiddifyrpc.TunnelServicePromiseClient = + function(hostname, credentials, options) { + if (!options) options = {}; + options.format = 'text'; + + /** + * @private @const {!grpc.web.GrpcWebClientBase} The client + */ + this.client_ = new grpc.web.GrpcWebClientBase(options); + + /** + * @private @const {string} The hostname + */ + this.hostname_ = hostname.replace(/\/+$/, ''); + +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.TunnelStartRequest, + * !proto.hiddifyrpc.TunnelResponse>} + */ +const methodDescriptor_TunnelService_Start = new grpc.web.MethodDescriptor( + '/hiddifyrpc.TunnelService/Start', + grpc.web.MethodType.UNARY, + proto.hiddifyrpc.TunnelStartRequest, + proto.hiddifyrpc.TunnelResponse, + /** + * @param {!proto.hiddifyrpc.TunnelStartRequest} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.TunnelResponse.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.TunnelStartRequest} request The + * request proto + * @param {?Object} metadata User defined + * call metadata + * @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.TunnelResponse)} + * callback The callback function(error, response) + * @return {!grpc.web.ClientReadableStream|undefined} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.TunnelServiceClient.prototype.start = + function(request, metadata, callback) { + return this.client_.rpcCall(this.hostname_ + + '/hiddifyrpc.TunnelService/Start', + request, + metadata || {}, + methodDescriptor_TunnelService_Start, + callback); +}; + + +/** + * @param {!proto.hiddifyrpc.TunnelStartRequest} request The + * request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!Promise} + * Promise that resolves to the response + */ +proto.hiddifyrpc.TunnelServicePromiseClient.prototype.start = + function(request, metadata) { + return this.client_.unaryCall(this.hostname_ + + '/hiddifyrpc.TunnelService/Start', + request, + metadata || {}, + methodDescriptor_TunnelService_Start); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.Empty, + * !proto.hiddifyrpc.TunnelResponse>} + */ +const methodDescriptor_TunnelService_Stop = new grpc.web.MethodDescriptor( + '/hiddifyrpc.TunnelService/Stop', + grpc.web.MethodType.UNARY, + base_pb.Empty, + proto.hiddifyrpc.TunnelResponse, + /** + * @param {!proto.hiddifyrpc.Empty} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.TunnelResponse.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.Empty} request The + * request proto + * @param {?Object} metadata User defined + * call metadata + * @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.TunnelResponse)} + * callback The callback function(error, response) + * @return {!grpc.web.ClientReadableStream|undefined} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.TunnelServiceClient.prototype.stop = + function(request, metadata, callback) { + return this.client_.rpcCall(this.hostname_ + + '/hiddifyrpc.TunnelService/Stop', + request, + metadata || {}, + methodDescriptor_TunnelService_Stop, + callback); +}; + + +/** + * @param {!proto.hiddifyrpc.Empty} request The + * request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!Promise} + * Promise that resolves to the response + */ +proto.hiddifyrpc.TunnelServicePromiseClient.prototype.stop = + function(request, metadata) { + return this.client_.unaryCall(this.hostname_ + + '/hiddifyrpc.TunnelService/Stop', + request, + metadata || {}, + methodDescriptor_TunnelService_Stop); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.Empty, + * !proto.hiddifyrpc.TunnelResponse>} + */ +const methodDescriptor_TunnelService_Status = new grpc.web.MethodDescriptor( + '/hiddifyrpc.TunnelService/Status', + grpc.web.MethodType.UNARY, + base_pb.Empty, + proto.hiddifyrpc.TunnelResponse, + /** + * @param {!proto.hiddifyrpc.Empty} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.TunnelResponse.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.Empty} request The + * request proto + * @param {?Object} metadata User defined + * call metadata + * @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.TunnelResponse)} + * callback The callback function(error, response) + * @return {!grpc.web.ClientReadableStream|undefined} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.TunnelServiceClient.prototype.status = + function(request, metadata, callback) { + return this.client_.rpcCall(this.hostname_ + + '/hiddifyrpc.TunnelService/Status', + request, + metadata || {}, + methodDescriptor_TunnelService_Status, + callback); +}; + + +/** + * @param {!proto.hiddifyrpc.Empty} request The + * request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!Promise} + * Promise that resolves to the response + */ +proto.hiddifyrpc.TunnelServicePromiseClient.prototype.status = + function(request, metadata) { + return this.client_.unaryCall(this.hostname_ + + '/hiddifyrpc.TunnelService/Status', + request, + metadata || {}, + methodDescriptor_TunnelService_Status); +}; + + +/** + * @const + * @type {!grpc.web.MethodDescriptor< + * !proto.hiddifyrpc.Empty, + * !proto.hiddifyrpc.TunnelResponse>} + */ +const methodDescriptor_TunnelService_Exit = new grpc.web.MethodDescriptor( + '/hiddifyrpc.TunnelService/Exit', + grpc.web.MethodType.UNARY, + base_pb.Empty, + proto.hiddifyrpc.TunnelResponse, + /** + * @param {!proto.hiddifyrpc.Empty} request + * @return {!Uint8Array} + */ + function(request) { + return request.serializeBinary(); + }, + proto.hiddifyrpc.TunnelResponse.deserializeBinary +); + + +/** + * @param {!proto.hiddifyrpc.Empty} request The + * request proto + * @param {?Object} metadata User defined + * call metadata + * @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.TunnelResponse)} + * callback The callback function(error, response) + * @return {!grpc.web.ClientReadableStream|undefined} + * The XHR Node Readable Stream + */ +proto.hiddifyrpc.TunnelServiceClient.prototype.exit = + function(request, metadata, callback) { + return this.client_.rpcCall(this.hostname_ + + '/hiddifyrpc.TunnelService/Exit', + request, + metadata || {}, + methodDescriptor_TunnelService_Exit, + callback); +}; + + +/** + * @param {!proto.hiddifyrpc.Empty} request The + * request proto + * @param {?Object=} metadata User defined + * call metadata + * @return {!Promise} + * Promise that resolves to the response + */ +proto.hiddifyrpc.TunnelServicePromiseClient.prototype.exit = + function(request, metadata) { + return this.client_.unaryCall(this.hostname_ + + '/hiddifyrpc.TunnelService/Exit', + request, + metadata || {}, + methodDescriptor_TunnelService_Exit); +}; + + +module.exports = proto.hiddifyrpc; + diff --git a/libcore/extension/html/rpc/hiddify_pb.js b/libcore/extension/html/rpc/hiddify_pb.js new file mode 100644 index 0000000..5532c9b --- /dev/null +++ b/libcore/extension/html/rpc/hiddify_pb.js @@ -0,0 +1,5393 @@ +// source: hiddify.proto +/** + * @fileoverview + * @enhanceable + * @suppress {missingRequire} reports error on implicit type usages. + * @suppress {messageConventions} JS Compiler reports an error if a variable or + * field starts with 'MSG_' and isn't a translatable message. + * @public + */ +// GENERATED CODE -- DO NOT EDIT! +/* eslint-disable */ +// @ts-nocheck + +var jspb = require('google-protobuf'); +var goog = jspb; +var global = + (typeof globalThis !== 'undefined' && globalThis) || + (typeof window !== 'undefined' && window) || + (typeof global !== 'undefined' && global) || + (typeof self !== 'undefined' && self) || + (function () { return this; }).call(null) || + Function('return this')(); + +var base_pb = require('./base_pb.js'); +goog.object.extend(proto, base_pb); +goog.exportSymbol('proto.hiddifyrpc.ChangeHiddifySettingsRequest', null, global); +goog.exportSymbol('proto.hiddifyrpc.CoreInfoResponse', null, global); +goog.exportSymbol('proto.hiddifyrpc.CoreState', null, global); +goog.exportSymbol('proto.hiddifyrpc.GenerateConfigRequest', null, global); +goog.exportSymbol('proto.hiddifyrpc.GenerateConfigResponse', null, global); +goog.exportSymbol('proto.hiddifyrpc.GenerateWarpConfigRequest', null, global); +goog.exportSymbol('proto.hiddifyrpc.LogLevel', null, global); +goog.exportSymbol('proto.hiddifyrpc.LogMessage', null, global); +goog.exportSymbol('proto.hiddifyrpc.LogType', null, global); +goog.exportSymbol('proto.hiddifyrpc.MessageType', null, global); +goog.exportSymbol('proto.hiddifyrpc.OutboundGroup', null, global); +goog.exportSymbol('proto.hiddifyrpc.OutboundGroupItem', null, global); +goog.exportSymbol('proto.hiddifyrpc.OutboundGroupList', null, global); +goog.exportSymbol('proto.hiddifyrpc.ParseRequest', null, global); +goog.exportSymbol('proto.hiddifyrpc.ParseResponse', null, global); +goog.exportSymbol('proto.hiddifyrpc.Response', null, global); +goog.exportSymbol('proto.hiddifyrpc.SelectOutboundRequest', null, global); +goog.exportSymbol('proto.hiddifyrpc.SetSystemProxyEnabledRequest', null, global); +goog.exportSymbol('proto.hiddifyrpc.SetupRequest', null, global); +goog.exportSymbol('proto.hiddifyrpc.StartRequest', null, global); +goog.exportSymbol('proto.hiddifyrpc.StopRequest', null, global); +goog.exportSymbol('proto.hiddifyrpc.SystemInfo', null, global); +goog.exportSymbol('proto.hiddifyrpc.SystemProxyStatus', null, global); +goog.exportSymbol('proto.hiddifyrpc.TunnelResponse', null, global); +goog.exportSymbol('proto.hiddifyrpc.TunnelStartRequest', null, global); +goog.exportSymbol('proto.hiddifyrpc.UrlTestRequest', null, global); +goog.exportSymbol('proto.hiddifyrpc.WarpAccount', null, global); +goog.exportSymbol('proto.hiddifyrpc.WarpGenerationResponse', null, global); +goog.exportSymbol('proto.hiddifyrpc.WarpWireguardConfig', null, global); +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.CoreInfoResponse = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.CoreInfoResponse, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.CoreInfoResponse.displayName = 'proto.hiddifyrpc.CoreInfoResponse'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.StartRequest = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.StartRequest, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.StartRequest.displayName = 'proto.hiddifyrpc.StartRequest'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.SetupRequest = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.SetupRequest, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.SetupRequest.displayName = 'proto.hiddifyrpc.SetupRequest'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.Response = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.Response, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.Response.displayName = 'proto.hiddifyrpc.Response'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.SystemInfo = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.SystemInfo, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.SystemInfo.displayName = 'proto.hiddifyrpc.SystemInfo'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.OutboundGroupItem = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.OutboundGroupItem, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.OutboundGroupItem.displayName = 'proto.hiddifyrpc.OutboundGroupItem'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.OutboundGroup = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, proto.hiddifyrpc.OutboundGroup.repeatedFields_, null); +}; +goog.inherits(proto.hiddifyrpc.OutboundGroup, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.OutboundGroup.displayName = 'proto.hiddifyrpc.OutboundGroup'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.OutboundGroupList = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, proto.hiddifyrpc.OutboundGroupList.repeatedFields_, null); +}; +goog.inherits(proto.hiddifyrpc.OutboundGroupList, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.OutboundGroupList.displayName = 'proto.hiddifyrpc.OutboundGroupList'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.WarpAccount = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.WarpAccount, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.WarpAccount.displayName = 'proto.hiddifyrpc.WarpAccount'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.WarpWireguardConfig = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.WarpWireguardConfig, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.WarpWireguardConfig.displayName = 'proto.hiddifyrpc.WarpWireguardConfig'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.WarpGenerationResponse = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.WarpGenerationResponse, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.WarpGenerationResponse.displayName = 'proto.hiddifyrpc.WarpGenerationResponse'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.SystemProxyStatus = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.SystemProxyStatus, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.SystemProxyStatus.displayName = 'proto.hiddifyrpc.SystemProxyStatus'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.ParseRequest = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.ParseRequest, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.ParseRequest.displayName = 'proto.hiddifyrpc.ParseRequest'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.ParseResponse = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.ParseResponse, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.ParseResponse.displayName = 'proto.hiddifyrpc.ParseResponse'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.ChangeHiddifySettingsRequest = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.ChangeHiddifySettingsRequest, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.ChangeHiddifySettingsRequest.displayName = 'proto.hiddifyrpc.ChangeHiddifySettingsRequest'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.GenerateConfigRequest = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.GenerateConfigRequest, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.GenerateConfigRequest.displayName = 'proto.hiddifyrpc.GenerateConfigRequest'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.GenerateConfigResponse = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.GenerateConfigResponse, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.GenerateConfigResponse.displayName = 'proto.hiddifyrpc.GenerateConfigResponse'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.SelectOutboundRequest = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.SelectOutboundRequest, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.SelectOutboundRequest.displayName = 'proto.hiddifyrpc.SelectOutboundRequest'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.UrlTestRequest = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.UrlTestRequest, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.UrlTestRequest.displayName = 'proto.hiddifyrpc.UrlTestRequest'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.GenerateWarpConfigRequest = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.GenerateWarpConfigRequest, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.GenerateWarpConfigRequest.displayName = 'proto.hiddifyrpc.GenerateWarpConfigRequest'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.SetSystemProxyEnabledRequest = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.SetSystemProxyEnabledRequest, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.SetSystemProxyEnabledRequest.displayName = 'proto.hiddifyrpc.SetSystemProxyEnabledRequest'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.LogMessage = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.LogMessage, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.LogMessage.displayName = 'proto.hiddifyrpc.LogMessage'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.StopRequest = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.StopRequest, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.StopRequest.displayName = 'proto.hiddifyrpc.StopRequest'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.TunnelStartRequest = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.TunnelStartRequest, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.TunnelStartRequest.displayName = 'proto.hiddifyrpc.TunnelStartRequest'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.hiddifyrpc.TunnelResponse = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.hiddifyrpc.TunnelResponse, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.hiddifyrpc.TunnelResponse.displayName = 'proto.hiddifyrpc.TunnelResponse'; +} + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.CoreInfoResponse.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.CoreInfoResponse.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.CoreInfoResponse} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.CoreInfoResponse.toObject = function(includeInstance, msg) { + var f, obj = { +coreState: jspb.Message.getFieldWithDefault(msg, 1, 0), +messageType: jspb.Message.getFieldWithDefault(msg, 2, 0), +message: jspb.Message.getFieldWithDefault(msg, 3, "") + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.CoreInfoResponse} + */ +proto.hiddifyrpc.CoreInfoResponse.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.CoreInfoResponse; + return proto.hiddifyrpc.CoreInfoResponse.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.CoreInfoResponse} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.CoreInfoResponse} + */ +proto.hiddifyrpc.CoreInfoResponse.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {!proto.hiddifyrpc.CoreState} */ (reader.readEnum()); + msg.setCoreState(value); + break; + case 2: + var value = /** @type {!proto.hiddifyrpc.MessageType} */ (reader.readEnum()); + msg.setMessageType(value); + break; + case 3: + var value = /** @type {string} */ (reader.readString()); + msg.setMessage(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.CoreInfoResponse.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.CoreInfoResponse.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.CoreInfoResponse} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.CoreInfoResponse.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getCoreState(); + if (f !== 0.0) { + writer.writeEnum( + 1, + f + ); + } + f = message.getMessageType(); + if (f !== 0.0) { + writer.writeEnum( + 2, + f + ); + } + f = message.getMessage(); + if (f.length > 0) { + writer.writeString( + 3, + f + ); + } +}; + + +/** + * optional CoreState core_state = 1; + * @return {!proto.hiddifyrpc.CoreState} + */ +proto.hiddifyrpc.CoreInfoResponse.prototype.getCoreState = function() { + return /** @type {!proto.hiddifyrpc.CoreState} */ (jspb.Message.getFieldWithDefault(this, 1, 0)); +}; + + +/** + * @param {!proto.hiddifyrpc.CoreState} value + * @return {!proto.hiddifyrpc.CoreInfoResponse} returns this + */ +proto.hiddifyrpc.CoreInfoResponse.prototype.setCoreState = function(value) { + return jspb.Message.setProto3EnumField(this, 1, value); +}; + + +/** + * optional MessageType message_type = 2; + * @return {!proto.hiddifyrpc.MessageType} + */ +proto.hiddifyrpc.CoreInfoResponse.prototype.getMessageType = function() { + return /** @type {!proto.hiddifyrpc.MessageType} */ (jspb.Message.getFieldWithDefault(this, 2, 0)); +}; + + +/** + * @param {!proto.hiddifyrpc.MessageType} value + * @return {!proto.hiddifyrpc.CoreInfoResponse} returns this + */ +proto.hiddifyrpc.CoreInfoResponse.prototype.setMessageType = function(value) { + return jspb.Message.setProto3EnumField(this, 2, value); +}; + + +/** + * optional string message = 3; + * @return {string} + */ +proto.hiddifyrpc.CoreInfoResponse.prototype.getMessage = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.CoreInfoResponse} returns this + */ +proto.hiddifyrpc.CoreInfoResponse.prototype.setMessage = function(value) { + return jspb.Message.setProto3StringField(this, 3, value); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.StartRequest.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.StartRequest.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.StartRequest} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.StartRequest.toObject = function(includeInstance, msg) { + var f, obj = { +configPath: jspb.Message.getFieldWithDefault(msg, 1, ""), +configContent: jspb.Message.getFieldWithDefault(msg, 2, ""), +disableMemoryLimit: jspb.Message.getBooleanFieldWithDefault(msg, 3, false), +delayStart: jspb.Message.getBooleanFieldWithDefault(msg, 4, false), +enableOldCommandServer: jspb.Message.getBooleanFieldWithDefault(msg, 5, false), +enableRawConfig: jspb.Message.getBooleanFieldWithDefault(msg, 6, false) + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.StartRequest} + */ +proto.hiddifyrpc.StartRequest.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.StartRequest; + return proto.hiddifyrpc.StartRequest.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.StartRequest} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.StartRequest} + */ +proto.hiddifyrpc.StartRequest.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {string} */ (reader.readString()); + msg.setConfigPath(value); + break; + case 2: + var value = /** @type {string} */ (reader.readString()); + msg.setConfigContent(value); + break; + case 3: + var value = /** @type {boolean} */ (reader.readBool()); + msg.setDisableMemoryLimit(value); + break; + case 4: + var value = /** @type {boolean} */ (reader.readBool()); + msg.setDelayStart(value); + break; + case 5: + var value = /** @type {boolean} */ (reader.readBool()); + msg.setEnableOldCommandServer(value); + break; + case 6: + var value = /** @type {boolean} */ (reader.readBool()); + msg.setEnableRawConfig(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.StartRequest.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.StartRequest.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.StartRequest} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.StartRequest.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getConfigPath(); + if (f.length > 0) { + writer.writeString( + 1, + f + ); + } + f = message.getConfigContent(); + if (f.length > 0) { + writer.writeString( + 2, + f + ); + } + f = message.getDisableMemoryLimit(); + if (f) { + writer.writeBool( + 3, + f + ); + } + f = message.getDelayStart(); + if (f) { + writer.writeBool( + 4, + f + ); + } + f = message.getEnableOldCommandServer(); + if (f) { + writer.writeBool( + 5, + f + ); + } + f = message.getEnableRawConfig(); + if (f) { + writer.writeBool( + 6, + f + ); + } +}; + + +/** + * optional string config_path = 1; + * @return {string} + */ +proto.hiddifyrpc.StartRequest.prototype.getConfigPath = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.StartRequest} returns this + */ +proto.hiddifyrpc.StartRequest.prototype.setConfigPath = function(value) { + return jspb.Message.setProto3StringField(this, 1, value); +}; + + +/** + * optional string config_content = 2; + * @return {string} + */ +proto.hiddifyrpc.StartRequest.prototype.getConfigContent = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.StartRequest} returns this + */ +proto.hiddifyrpc.StartRequest.prototype.setConfigContent = function(value) { + return jspb.Message.setProto3StringField(this, 2, value); +}; + + +/** + * optional bool disable_memory_limit = 3; + * @return {boolean} + */ +proto.hiddifyrpc.StartRequest.prototype.getDisableMemoryLimit = function() { + return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 3, false)); +}; + + +/** + * @param {boolean} value + * @return {!proto.hiddifyrpc.StartRequest} returns this + */ +proto.hiddifyrpc.StartRequest.prototype.setDisableMemoryLimit = function(value) { + return jspb.Message.setProto3BooleanField(this, 3, value); +}; + + +/** + * optional bool delay_start = 4; + * @return {boolean} + */ +proto.hiddifyrpc.StartRequest.prototype.getDelayStart = function() { + return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 4, false)); +}; + + +/** + * @param {boolean} value + * @return {!proto.hiddifyrpc.StartRequest} returns this + */ +proto.hiddifyrpc.StartRequest.prototype.setDelayStart = function(value) { + return jspb.Message.setProto3BooleanField(this, 4, value); +}; + + +/** + * optional bool enable_old_command_server = 5; + * @return {boolean} + */ +proto.hiddifyrpc.StartRequest.prototype.getEnableOldCommandServer = function() { + return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 5, false)); +}; + + +/** + * @param {boolean} value + * @return {!proto.hiddifyrpc.StartRequest} returns this + */ +proto.hiddifyrpc.StartRequest.prototype.setEnableOldCommandServer = function(value) { + return jspb.Message.setProto3BooleanField(this, 5, value); +}; + + +/** + * optional bool enable_raw_config = 6; + * @return {boolean} + */ +proto.hiddifyrpc.StartRequest.prototype.getEnableRawConfig = function() { + return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 6, false)); +}; + + +/** + * @param {boolean} value + * @return {!proto.hiddifyrpc.StartRequest} returns this + */ +proto.hiddifyrpc.StartRequest.prototype.setEnableRawConfig = function(value) { + return jspb.Message.setProto3BooleanField(this, 6, value); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.SetupRequest.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.SetupRequest.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.SetupRequest} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.SetupRequest.toObject = function(includeInstance, msg) { + var f, obj = { +basePath: jspb.Message.getFieldWithDefault(msg, 1, ""), +workingPath: jspb.Message.getFieldWithDefault(msg, 2, ""), +tempPath: jspb.Message.getFieldWithDefault(msg, 3, "") + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.SetupRequest} + */ +proto.hiddifyrpc.SetupRequest.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.SetupRequest; + return proto.hiddifyrpc.SetupRequest.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.SetupRequest} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.SetupRequest} + */ +proto.hiddifyrpc.SetupRequest.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {string} */ (reader.readString()); + msg.setBasePath(value); + break; + case 2: + var value = /** @type {string} */ (reader.readString()); + msg.setWorkingPath(value); + break; + case 3: + var value = /** @type {string} */ (reader.readString()); + msg.setTempPath(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.SetupRequest.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.SetupRequest.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.SetupRequest} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.SetupRequest.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getBasePath(); + if (f.length > 0) { + writer.writeString( + 1, + f + ); + } + f = message.getWorkingPath(); + if (f.length > 0) { + writer.writeString( + 2, + f + ); + } + f = message.getTempPath(); + if (f.length > 0) { + writer.writeString( + 3, + f + ); + } +}; + + +/** + * optional string base_path = 1; + * @return {string} + */ +proto.hiddifyrpc.SetupRequest.prototype.getBasePath = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.SetupRequest} returns this + */ +proto.hiddifyrpc.SetupRequest.prototype.setBasePath = function(value) { + return jspb.Message.setProto3StringField(this, 1, value); +}; + + +/** + * optional string working_path = 2; + * @return {string} + */ +proto.hiddifyrpc.SetupRequest.prototype.getWorkingPath = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.SetupRequest} returns this + */ +proto.hiddifyrpc.SetupRequest.prototype.setWorkingPath = function(value) { + return jspb.Message.setProto3StringField(this, 2, value); +}; + + +/** + * optional string temp_path = 3; + * @return {string} + */ +proto.hiddifyrpc.SetupRequest.prototype.getTempPath = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.SetupRequest} returns this + */ +proto.hiddifyrpc.SetupRequest.prototype.setTempPath = function(value) { + return jspb.Message.setProto3StringField(this, 3, value); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.Response.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.Response.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.Response} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.Response.toObject = function(includeInstance, msg) { + var f, obj = { +responseCode: jspb.Message.getFieldWithDefault(msg, 1, 0), +message: jspb.Message.getFieldWithDefault(msg, 2, "") + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.Response} + */ +proto.hiddifyrpc.Response.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.Response; + return proto.hiddifyrpc.Response.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.Response} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.Response} + */ +proto.hiddifyrpc.Response.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {!proto.hiddifyrpc.ResponseCode} */ (reader.readEnum()); + msg.setResponseCode(value); + break; + case 2: + var value = /** @type {string} */ (reader.readString()); + msg.setMessage(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.Response.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.Response.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.Response} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.Response.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getResponseCode(); + if (f !== 0.0) { + writer.writeEnum( + 1, + f + ); + } + f = message.getMessage(); + if (f.length > 0) { + writer.writeString( + 2, + f + ); + } +}; + + +/** + * optional ResponseCode response_code = 1; + * @return {!proto.hiddifyrpc.ResponseCode} + */ +proto.hiddifyrpc.Response.prototype.getResponseCode = function() { + return /** @type {!proto.hiddifyrpc.ResponseCode} */ (jspb.Message.getFieldWithDefault(this, 1, 0)); +}; + + +/** + * @param {!proto.hiddifyrpc.ResponseCode} value + * @return {!proto.hiddifyrpc.Response} returns this + */ +proto.hiddifyrpc.Response.prototype.setResponseCode = function(value) { + return jspb.Message.setProto3EnumField(this, 1, value); +}; + + +/** + * optional string message = 2; + * @return {string} + */ +proto.hiddifyrpc.Response.prototype.getMessage = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.Response} returns this + */ +proto.hiddifyrpc.Response.prototype.setMessage = function(value) { + return jspb.Message.setProto3StringField(this, 2, value); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.SystemInfo.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.SystemInfo.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.SystemInfo} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.SystemInfo.toObject = function(includeInstance, msg) { + var f, obj = { +memory: jspb.Message.getFieldWithDefault(msg, 1, 0), +goroutines: jspb.Message.getFieldWithDefault(msg, 2, 0), +connectionsIn: jspb.Message.getFieldWithDefault(msg, 3, 0), +connectionsOut: jspb.Message.getFieldWithDefault(msg, 4, 0), +trafficAvailable: jspb.Message.getBooleanFieldWithDefault(msg, 5, false), +uplink: jspb.Message.getFieldWithDefault(msg, 6, 0), +downlink: jspb.Message.getFieldWithDefault(msg, 7, 0), +uplinkTotal: jspb.Message.getFieldWithDefault(msg, 8, 0), +downlinkTotal: jspb.Message.getFieldWithDefault(msg, 9, 0) + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.SystemInfo} + */ +proto.hiddifyrpc.SystemInfo.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.SystemInfo; + return proto.hiddifyrpc.SystemInfo.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.SystemInfo} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.SystemInfo} + */ +proto.hiddifyrpc.SystemInfo.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {number} */ (reader.readInt64()); + msg.setMemory(value); + break; + case 2: + var value = /** @type {number} */ (reader.readInt32()); + msg.setGoroutines(value); + break; + case 3: + var value = /** @type {number} */ (reader.readInt32()); + msg.setConnectionsIn(value); + break; + case 4: + var value = /** @type {number} */ (reader.readInt32()); + msg.setConnectionsOut(value); + break; + case 5: + var value = /** @type {boolean} */ (reader.readBool()); + msg.setTrafficAvailable(value); + break; + case 6: + var value = /** @type {number} */ (reader.readInt64()); + msg.setUplink(value); + break; + case 7: + var value = /** @type {number} */ (reader.readInt64()); + msg.setDownlink(value); + break; + case 8: + var value = /** @type {number} */ (reader.readInt64()); + msg.setUplinkTotal(value); + break; + case 9: + var value = /** @type {number} */ (reader.readInt64()); + msg.setDownlinkTotal(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.SystemInfo.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.SystemInfo.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.SystemInfo} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.SystemInfo.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getMemory(); + if (f !== 0) { + writer.writeInt64( + 1, + f + ); + } + f = message.getGoroutines(); + if (f !== 0) { + writer.writeInt32( + 2, + f + ); + } + f = message.getConnectionsIn(); + if (f !== 0) { + writer.writeInt32( + 3, + f + ); + } + f = message.getConnectionsOut(); + if (f !== 0) { + writer.writeInt32( + 4, + f + ); + } + f = message.getTrafficAvailable(); + if (f) { + writer.writeBool( + 5, + f + ); + } + f = message.getUplink(); + if (f !== 0) { + writer.writeInt64( + 6, + f + ); + } + f = message.getDownlink(); + if (f !== 0) { + writer.writeInt64( + 7, + f + ); + } + f = message.getUplinkTotal(); + if (f !== 0) { + writer.writeInt64( + 8, + f + ); + } + f = message.getDownlinkTotal(); + if (f !== 0) { + writer.writeInt64( + 9, + f + ); + } +}; + + +/** + * optional int64 memory = 1; + * @return {number} + */ +proto.hiddifyrpc.SystemInfo.prototype.getMemory = function() { + return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 1, 0)); +}; + + +/** + * @param {number} value + * @return {!proto.hiddifyrpc.SystemInfo} returns this + */ +proto.hiddifyrpc.SystemInfo.prototype.setMemory = function(value) { + return jspb.Message.setProto3IntField(this, 1, value); +}; + + +/** + * optional int32 goroutines = 2; + * @return {number} + */ +proto.hiddifyrpc.SystemInfo.prototype.getGoroutines = function() { + return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 2, 0)); +}; + + +/** + * @param {number} value + * @return {!proto.hiddifyrpc.SystemInfo} returns this + */ +proto.hiddifyrpc.SystemInfo.prototype.setGoroutines = function(value) { + return jspb.Message.setProto3IntField(this, 2, value); +}; + + +/** + * optional int32 connections_in = 3; + * @return {number} + */ +proto.hiddifyrpc.SystemInfo.prototype.getConnectionsIn = function() { + return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 3, 0)); +}; + + +/** + * @param {number} value + * @return {!proto.hiddifyrpc.SystemInfo} returns this + */ +proto.hiddifyrpc.SystemInfo.prototype.setConnectionsIn = function(value) { + return jspb.Message.setProto3IntField(this, 3, value); +}; + + +/** + * optional int32 connections_out = 4; + * @return {number} + */ +proto.hiddifyrpc.SystemInfo.prototype.getConnectionsOut = function() { + return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 4, 0)); +}; + + +/** + * @param {number} value + * @return {!proto.hiddifyrpc.SystemInfo} returns this + */ +proto.hiddifyrpc.SystemInfo.prototype.setConnectionsOut = function(value) { + return jspb.Message.setProto3IntField(this, 4, value); +}; + + +/** + * optional bool traffic_available = 5; + * @return {boolean} + */ +proto.hiddifyrpc.SystemInfo.prototype.getTrafficAvailable = function() { + return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 5, false)); +}; + + +/** + * @param {boolean} value + * @return {!proto.hiddifyrpc.SystemInfo} returns this + */ +proto.hiddifyrpc.SystemInfo.prototype.setTrafficAvailable = function(value) { + return jspb.Message.setProto3BooleanField(this, 5, value); +}; + + +/** + * optional int64 uplink = 6; + * @return {number} + */ +proto.hiddifyrpc.SystemInfo.prototype.getUplink = function() { + return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 6, 0)); +}; + + +/** + * @param {number} value + * @return {!proto.hiddifyrpc.SystemInfo} returns this + */ +proto.hiddifyrpc.SystemInfo.prototype.setUplink = function(value) { + return jspb.Message.setProto3IntField(this, 6, value); +}; + + +/** + * optional int64 downlink = 7; + * @return {number} + */ +proto.hiddifyrpc.SystemInfo.prototype.getDownlink = function() { + return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 7, 0)); +}; + + +/** + * @param {number} value + * @return {!proto.hiddifyrpc.SystemInfo} returns this + */ +proto.hiddifyrpc.SystemInfo.prototype.setDownlink = function(value) { + return jspb.Message.setProto3IntField(this, 7, value); +}; + + +/** + * optional int64 uplink_total = 8; + * @return {number} + */ +proto.hiddifyrpc.SystemInfo.prototype.getUplinkTotal = function() { + return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 8, 0)); +}; + + +/** + * @param {number} value + * @return {!proto.hiddifyrpc.SystemInfo} returns this + */ +proto.hiddifyrpc.SystemInfo.prototype.setUplinkTotal = function(value) { + return jspb.Message.setProto3IntField(this, 8, value); +}; + + +/** + * optional int64 downlink_total = 9; + * @return {number} + */ +proto.hiddifyrpc.SystemInfo.prototype.getDownlinkTotal = function() { + return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 9, 0)); +}; + + +/** + * @param {number} value + * @return {!proto.hiddifyrpc.SystemInfo} returns this + */ +proto.hiddifyrpc.SystemInfo.prototype.setDownlinkTotal = function(value) { + return jspb.Message.setProto3IntField(this, 9, value); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.OutboundGroupItem.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.OutboundGroupItem.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.OutboundGroupItem} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.OutboundGroupItem.toObject = function(includeInstance, msg) { + var f, obj = { +tag: jspb.Message.getFieldWithDefault(msg, 1, ""), +type: jspb.Message.getFieldWithDefault(msg, 2, ""), +urlTestTime: jspb.Message.getFieldWithDefault(msg, 3, 0), +urlTestDelay: jspb.Message.getFieldWithDefault(msg, 4, 0) + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.OutboundGroupItem} + */ +proto.hiddifyrpc.OutboundGroupItem.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.OutboundGroupItem; + return proto.hiddifyrpc.OutboundGroupItem.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.OutboundGroupItem} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.OutboundGroupItem} + */ +proto.hiddifyrpc.OutboundGroupItem.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {string} */ (reader.readString()); + msg.setTag(value); + break; + case 2: + var value = /** @type {string} */ (reader.readString()); + msg.setType(value); + break; + case 3: + var value = /** @type {number} */ (reader.readInt64()); + msg.setUrlTestTime(value); + break; + case 4: + var value = /** @type {number} */ (reader.readInt32()); + msg.setUrlTestDelay(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.OutboundGroupItem.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.OutboundGroupItem.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.OutboundGroupItem} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.OutboundGroupItem.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getTag(); + if (f.length > 0) { + writer.writeString( + 1, + f + ); + } + f = message.getType(); + if (f.length > 0) { + writer.writeString( + 2, + f + ); + } + f = message.getUrlTestTime(); + if (f !== 0) { + writer.writeInt64( + 3, + f + ); + } + f = message.getUrlTestDelay(); + if (f !== 0) { + writer.writeInt32( + 4, + f + ); + } +}; + + +/** + * optional string tag = 1; + * @return {string} + */ +proto.hiddifyrpc.OutboundGroupItem.prototype.getTag = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.OutboundGroupItem} returns this + */ +proto.hiddifyrpc.OutboundGroupItem.prototype.setTag = function(value) { + return jspb.Message.setProto3StringField(this, 1, value); +}; + + +/** + * optional string type = 2; + * @return {string} + */ +proto.hiddifyrpc.OutboundGroupItem.prototype.getType = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.OutboundGroupItem} returns this + */ +proto.hiddifyrpc.OutboundGroupItem.prototype.setType = function(value) { + return jspb.Message.setProto3StringField(this, 2, value); +}; + + +/** + * optional int64 url_test_time = 3; + * @return {number} + */ +proto.hiddifyrpc.OutboundGroupItem.prototype.getUrlTestTime = function() { + return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 3, 0)); +}; + + +/** + * @param {number} value + * @return {!proto.hiddifyrpc.OutboundGroupItem} returns this + */ +proto.hiddifyrpc.OutboundGroupItem.prototype.setUrlTestTime = function(value) { + return jspb.Message.setProto3IntField(this, 3, value); +}; + + +/** + * optional int32 url_test_delay = 4; + * @return {number} + */ +proto.hiddifyrpc.OutboundGroupItem.prototype.getUrlTestDelay = function() { + return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 4, 0)); +}; + + +/** + * @param {number} value + * @return {!proto.hiddifyrpc.OutboundGroupItem} returns this + */ +proto.hiddifyrpc.OutboundGroupItem.prototype.setUrlTestDelay = function(value) { + return jspb.Message.setProto3IntField(this, 4, value); +}; + + + +/** + * List of repeated fields within this message type. + * @private {!Array} + * @const + */ +proto.hiddifyrpc.OutboundGroup.repeatedFields_ = [4]; + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.OutboundGroup.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.OutboundGroup.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.OutboundGroup} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.OutboundGroup.toObject = function(includeInstance, msg) { + var f, obj = { +tag: jspb.Message.getFieldWithDefault(msg, 1, ""), +type: jspb.Message.getFieldWithDefault(msg, 2, ""), +selected: jspb.Message.getFieldWithDefault(msg, 3, ""), +itemsList: jspb.Message.toObjectList(msg.getItemsList(), + proto.hiddifyrpc.OutboundGroupItem.toObject, includeInstance) + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.OutboundGroup} + */ +proto.hiddifyrpc.OutboundGroup.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.OutboundGroup; + return proto.hiddifyrpc.OutboundGroup.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.OutboundGroup} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.OutboundGroup} + */ +proto.hiddifyrpc.OutboundGroup.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {string} */ (reader.readString()); + msg.setTag(value); + break; + case 2: + var value = /** @type {string} */ (reader.readString()); + msg.setType(value); + break; + case 3: + var value = /** @type {string} */ (reader.readString()); + msg.setSelected(value); + break; + case 4: + var value = new proto.hiddifyrpc.OutboundGroupItem; + reader.readMessage(value,proto.hiddifyrpc.OutboundGroupItem.deserializeBinaryFromReader); + msg.addItems(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.OutboundGroup.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.OutboundGroup.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.OutboundGroup} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.OutboundGroup.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getTag(); + if (f.length > 0) { + writer.writeString( + 1, + f + ); + } + f = message.getType(); + if (f.length > 0) { + writer.writeString( + 2, + f + ); + } + f = message.getSelected(); + if (f.length > 0) { + writer.writeString( + 3, + f + ); + } + f = message.getItemsList(); + if (f.length > 0) { + writer.writeRepeatedMessage( + 4, + f, + proto.hiddifyrpc.OutboundGroupItem.serializeBinaryToWriter + ); + } +}; + + +/** + * optional string tag = 1; + * @return {string} + */ +proto.hiddifyrpc.OutboundGroup.prototype.getTag = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.OutboundGroup} returns this + */ +proto.hiddifyrpc.OutboundGroup.prototype.setTag = function(value) { + return jspb.Message.setProto3StringField(this, 1, value); +}; + + +/** + * optional string type = 2; + * @return {string} + */ +proto.hiddifyrpc.OutboundGroup.prototype.getType = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.OutboundGroup} returns this + */ +proto.hiddifyrpc.OutboundGroup.prototype.setType = function(value) { + return jspb.Message.setProto3StringField(this, 2, value); +}; + + +/** + * optional string selected = 3; + * @return {string} + */ +proto.hiddifyrpc.OutboundGroup.prototype.getSelected = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.OutboundGroup} returns this + */ +proto.hiddifyrpc.OutboundGroup.prototype.setSelected = function(value) { + return jspb.Message.setProto3StringField(this, 3, value); +}; + + +/** + * repeated OutboundGroupItem items = 4; + * @return {!Array} + */ +proto.hiddifyrpc.OutboundGroup.prototype.getItemsList = function() { + return /** @type{!Array} */ ( + jspb.Message.getRepeatedWrapperField(this, proto.hiddifyrpc.OutboundGroupItem, 4)); +}; + + +/** + * @param {!Array} value + * @return {!proto.hiddifyrpc.OutboundGroup} returns this +*/ +proto.hiddifyrpc.OutboundGroup.prototype.setItemsList = function(value) { + return jspb.Message.setRepeatedWrapperField(this, 4, value); +}; + + +/** + * @param {!proto.hiddifyrpc.OutboundGroupItem=} opt_value + * @param {number=} opt_index + * @return {!proto.hiddifyrpc.OutboundGroupItem} + */ +proto.hiddifyrpc.OutboundGroup.prototype.addItems = function(opt_value, opt_index) { + return jspb.Message.addToRepeatedWrapperField(this, 4, opt_value, proto.hiddifyrpc.OutboundGroupItem, opt_index); +}; + + +/** + * Clears the list making it empty but non-null. + * @return {!proto.hiddifyrpc.OutboundGroup} returns this + */ +proto.hiddifyrpc.OutboundGroup.prototype.clearItemsList = function() { + return this.setItemsList([]); +}; + + + +/** + * List of repeated fields within this message type. + * @private {!Array} + * @const + */ +proto.hiddifyrpc.OutboundGroupList.repeatedFields_ = [1]; + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.OutboundGroupList.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.OutboundGroupList.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.OutboundGroupList} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.OutboundGroupList.toObject = function(includeInstance, msg) { + var f, obj = { +itemsList: jspb.Message.toObjectList(msg.getItemsList(), + proto.hiddifyrpc.OutboundGroup.toObject, includeInstance) + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.OutboundGroupList} + */ +proto.hiddifyrpc.OutboundGroupList.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.OutboundGroupList; + return proto.hiddifyrpc.OutboundGroupList.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.OutboundGroupList} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.OutboundGroupList} + */ +proto.hiddifyrpc.OutboundGroupList.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = new proto.hiddifyrpc.OutboundGroup; + reader.readMessage(value,proto.hiddifyrpc.OutboundGroup.deserializeBinaryFromReader); + msg.addItems(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.OutboundGroupList.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.OutboundGroupList.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.OutboundGroupList} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.OutboundGroupList.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getItemsList(); + if (f.length > 0) { + writer.writeRepeatedMessage( + 1, + f, + proto.hiddifyrpc.OutboundGroup.serializeBinaryToWriter + ); + } +}; + + +/** + * repeated OutboundGroup items = 1; + * @return {!Array} + */ +proto.hiddifyrpc.OutboundGroupList.prototype.getItemsList = function() { + return /** @type{!Array} */ ( + jspb.Message.getRepeatedWrapperField(this, proto.hiddifyrpc.OutboundGroup, 1)); +}; + + +/** + * @param {!Array} value + * @return {!proto.hiddifyrpc.OutboundGroupList} returns this +*/ +proto.hiddifyrpc.OutboundGroupList.prototype.setItemsList = function(value) { + return jspb.Message.setRepeatedWrapperField(this, 1, value); +}; + + +/** + * @param {!proto.hiddifyrpc.OutboundGroup=} opt_value + * @param {number=} opt_index + * @return {!proto.hiddifyrpc.OutboundGroup} + */ +proto.hiddifyrpc.OutboundGroupList.prototype.addItems = function(opt_value, opt_index) { + return jspb.Message.addToRepeatedWrapperField(this, 1, opt_value, proto.hiddifyrpc.OutboundGroup, opt_index); +}; + + +/** + * Clears the list making it empty but non-null. + * @return {!proto.hiddifyrpc.OutboundGroupList} returns this + */ +proto.hiddifyrpc.OutboundGroupList.prototype.clearItemsList = function() { + return this.setItemsList([]); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.WarpAccount.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.WarpAccount.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.WarpAccount} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.WarpAccount.toObject = function(includeInstance, msg) { + var f, obj = { +accountId: jspb.Message.getFieldWithDefault(msg, 1, ""), +accessToken: jspb.Message.getFieldWithDefault(msg, 2, "") + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.WarpAccount} + */ +proto.hiddifyrpc.WarpAccount.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.WarpAccount; + return proto.hiddifyrpc.WarpAccount.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.WarpAccount} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.WarpAccount} + */ +proto.hiddifyrpc.WarpAccount.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {string} */ (reader.readString()); + msg.setAccountId(value); + break; + case 2: + var value = /** @type {string} */ (reader.readString()); + msg.setAccessToken(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.WarpAccount.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.WarpAccount.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.WarpAccount} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.WarpAccount.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getAccountId(); + if (f.length > 0) { + writer.writeString( + 1, + f + ); + } + f = message.getAccessToken(); + if (f.length > 0) { + writer.writeString( + 2, + f + ); + } +}; + + +/** + * optional string account_id = 1; + * @return {string} + */ +proto.hiddifyrpc.WarpAccount.prototype.getAccountId = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.WarpAccount} returns this + */ +proto.hiddifyrpc.WarpAccount.prototype.setAccountId = function(value) { + return jspb.Message.setProto3StringField(this, 1, value); +}; + + +/** + * optional string access_token = 2; + * @return {string} + */ +proto.hiddifyrpc.WarpAccount.prototype.getAccessToken = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.WarpAccount} returns this + */ +proto.hiddifyrpc.WarpAccount.prototype.setAccessToken = function(value) { + return jspb.Message.setProto3StringField(this, 2, value); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.WarpWireguardConfig.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.WarpWireguardConfig.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.WarpWireguardConfig} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.WarpWireguardConfig.toObject = function(includeInstance, msg) { + var f, obj = { +privateKey: jspb.Message.getFieldWithDefault(msg, 1, ""), +localAddressIpv4: jspb.Message.getFieldWithDefault(msg, 2, ""), +localAddressIpv6: jspb.Message.getFieldWithDefault(msg, 3, ""), +peerPublicKey: jspb.Message.getFieldWithDefault(msg, 4, ""), +clientId: jspb.Message.getFieldWithDefault(msg, 5, "") + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.WarpWireguardConfig} + */ +proto.hiddifyrpc.WarpWireguardConfig.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.WarpWireguardConfig; + return proto.hiddifyrpc.WarpWireguardConfig.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.WarpWireguardConfig} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.WarpWireguardConfig} + */ +proto.hiddifyrpc.WarpWireguardConfig.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {string} */ (reader.readString()); + msg.setPrivateKey(value); + break; + case 2: + var value = /** @type {string} */ (reader.readString()); + msg.setLocalAddressIpv4(value); + break; + case 3: + var value = /** @type {string} */ (reader.readString()); + msg.setLocalAddressIpv6(value); + break; + case 4: + var value = /** @type {string} */ (reader.readString()); + msg.setPeerPublicKey(value); + break; + case 5: + var value = /** @type {string} */ (reader.readString()); + msg.setClientId(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.WarpWireguardConfig.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.WarpWireguardConfig.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.WarpWireguardConfig} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.WarpWireguardConfig.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getPrivateKey(); + if (f.length > 0) { + writer.writeString( + 1, + f + ); + } + f = message.getLocalAddressIpv4(); + if (f.length > 0) { + writer.writeString( + 2, + f + ); + } + f = message.getLocalAddressIpv6(); + if (f.length > 0) { + writer.writeString( + 3, + f + ); + } + f = message.getPeerPublicKey(); + if (f.length > 0) { + writer.writeString( + 4, + f + ); + } + f = message.getClientId(); + if (f.length > 0) { + writer.writeString( + 5, + f + ); + } +}; + + +/** + * optional string private_key = 1; + * @return {string} + */ +proto.hiddifyrpc.WarpWireguardConfig.prototype.getPrivateKey = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.WarpWireguardConfig} returns this + */ +proto.hiddifyrpc.WarpWireguardConfig.prototype.setPrivateKey = function(value) { + return jspb.Message.setProto3StringField(this, 1, value); +}; + + +/** + * optional string local_address_ipv4 = 2; + * @return {string} + */ +proto.hiddifyrpc.WarpWireguardConfig.prototype.getLocalAddressIpv4 = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.WarpWireguardConfig} returns this + */ +proto.hiddifyrpc.WarpWireguardConfig.prototype.setLocalAddressIpv4 = function(value) { + return jspb.Message.setProto3StringField(this, 2, value); +}; + + +/** + * optional string local_address_ipv6 = 3; + * @return {string} + */ +proto.hiddifyrpc.WarpWireguardConfig.prototype.getLocalAddressIpv6 = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.WarpWireguardConfig} returns this + */ +proto.hiddifyrpc.WarpWireguardConfig.prototype.setLocalAddressIpv6 = function(value) { + return jspb.Message.setProto3StringField(this, 3, value); +}; + + +/** + * optional string peer_public_key = 4; + * @return {string} + */ +proto.hiddifyrpc.WarpWireguardConfig.prototype.getPeerPublicKey = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 4, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.WarpWireguardConfig} returns this + */ +proto.hiddifyrpc.WarpWireguardConfig.prototype.setPeerPublicKey = function(value) { + return jspb.Message.setProto3StringField(this, 4, value); +}; + + +/** + * optional string client_id = 5; + * @return {string} + */ +proto.hiddifyrpc.WarpWireguardConfig.prototype.getClientId = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 5, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.WarpWireguardConfig} returns this + */ +proto.hiddifyrpc.WarpWireguardConfig.prototype.setClientId = function(value) { + return jspb.Message.setProto3StringField(this, 5, value); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.WarpGenerationResponse.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.WarpGenerationResponse.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.WarpGenerationResponse} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.WarpGenerationResponse.toObject = function(includeInstance, msg) { + var f, obj = { +account: (f = msg.getAccount()) && proto.hiddifyrpc.WarpAccount.toObject(includeInstance, f), +log: jspb.Message.getFieldWithDefault(msg, 2, ""), +config: (f = msg.getConfig()) && proto.hiddifyrpc.WarpWireguardConfig.toObject(includeInstance, f) + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.WarpGenerationResponse} + */ +proto.hiddifyrpc.WarpGenerationResponse.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.WarpGenerationResponse; + return proto.hiddifyrpc.WarpGenerationResponse.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.WarpGenerationResponse} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.WarpGenerationResponse} + */ +proto.hiddifyrpc.WarpGenerationResponse.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = new proto.hiddifyrpc.WarpAccount; + reader.readMessage(value,proto.hiddifyrpc.WarpAccount.deserializeBinaryFromReader); + msg.setAccount(value); + break; + case 2: + var value = /** @type {string} */ (reader.readString()); + msg.setLog(value); + break; + case 3: + var value = new proto.hiddifyrpc.WarpWireguardConfig; + reader.readMessage(value,proto.hiddifyrpc.WarpWireguardConfig.deserializeBinaryFromReader); + msg.setConfig(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.WarpGenerationResponse.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.WarpGenerationResponse.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.WarpGenerationResponse} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.WarpGenerationResponse.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getAccount(); + if (f != null) { + writer.writeMessage( + 1, + f, + proto.hiddifyrpc.WarpAccount.serializeBinaryToWriter + ); + } + f = message.getLog(); + if (f.length > 0) { + writer.writeString( + 2, + f + ); + } + f = message.getConfig(); + if (f != null) { + writer.writeMessage( + 3, + f, + proto.hiddifyrpc.WarpWireguardConfig.serializeBinaryToWriter + ); + } +}; + + +/** + * optional WarpAccount account = 1; + * @return {?proto.hiddifyrpc.WarpAccount} + */ +proto.hiddifyrpc.WarpGenerationResponse.prototype.getAccount = function() { + return /** @type{?proto.hiddifyrpc.WarpAccount} */ ( + jspb.Message.getWrapperField(this, proto.hiddifyrpc.WarpAccount, 1)); +}; + + +/** + * @param {?proto.hiddifyrpc.WarpAccount|undefined} value + * @return {!proto.hiddifyrpc.WarpGenerationResponse} returns this +*/ +proto.hiddifyrpc.WarpGenerationResponse.prototype.setAccount = function(value) { + return jspb.Message.setWrapperField(this, 1, value); +}; + + +/** + * Clears the message field making it undefined. + * @return {!proto.hiddifyrpc.WarpGenerationResponse} returns this + */ +proto.hiddifyrpc.WarpGenerationResponse.prototype.clearAccount = function() { + return this.setAccount(undefined); +}; + + +/** + * Returns whether this field is set. + * @return {boolean} + */ +proto.hiddifyrpc.WarpGenerationResponse.prototype.hasAccount = function() { + return jspb.Message.getField(this, 1) != null; +}; + + +/** + * optional string log = 2; + * @return {string} + */ +proto.hiddifyrpc.WarpGenerationResponse.prototype.getLog = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.WarpGenerationResponse} returns this + */ +proto.hiddifyrpc.WarpGenerationResponse.prototype.setLog = function(value) { + return jspb.Message.setProto3StringField(this, 2, value); +}; + + +/** + * optional WarpWireguardConfig config = 3; + * @return {?proto.hiddifyrpc.WarpWireguardConfig} + */ +proto.hiddifyrpc.WarpGenerationResponse.prototype.getConfig = function() { + return /** @type{?proto.hiddifyrpc.WarpWireguardConfig} */ ( + jspb.Message.getWrapperField(this, proto.hiddifyrpc.WarpWireguardConfig, 3)); +}; + + +/** + * @param {?proto.hiddifyrpc.WarpWireguardConfig|undefined} value + * @return {!proto.hiddifyrpc.WarpGenerationResponse} returns this +*/ +proto.hiddifyrpc.WarpGenerationResponse.prototype.setConfig = function(value) { + return jspb.Message.setWrapperField(this, 3, value); +}; + + +/** + * Clears the message field making it undefined. + * @return {!proto.hiddifyrpc.WarpGenerationResponse} returns this + */ +proto.hiddifyrpc.WarpGenerationResponse.prototype.clearConfig = function() { + return this.setConfig(undefined); +}; + + +/** + * Returns whether this field is set. + * @return {boolean} + */ +proto.hiddifyrpc.WarpGenerationResponse.prototype.hasConfig = function() { + return jspb.Message.getField(this, 3) != null; +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.SystemProxyStatus.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.SystemProxyStatus.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.SystemProxyStatus} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.SystemProxyStatus.toObject = function(includeInstance, msg) { + var f, obj = { +available: jspb.Message.getBooleanFieldWithDefault(msg, 1, false), +enabled: jspb.Message.getBooleanFieldWithDefault(msg, 2, false) + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.SystemProxyStatus} + */ +proto.hiddifyrpc.SystemProxyStatus.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.SystemProxyStatus; + return proto.hiddifyrpc.SystemProxyStatus.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.SystemProxyStatus} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.SystemProxyStatus} + */ +proto.hiddifyrpc.SystemProxyStatus.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {boolean} */ (reader.readBool()); + msg.setAvailable(value); + break; + case 2: + var value = /** @type {boolean} */ (reader.readBool()); + msg.setEnabled(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.SystemProxyStatus.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.SystemProxyStatus.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.SystemProxyStatus} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.SystemProxyStatus.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getAvailable(); + if (f) { + writer.writeBool( + 1, + f + ); + } + f = message.getEnabled(); + if (f) { + writer.writeBool( + 2, + f + ); + } +}; + + +/** + * optional bool available = 1; + * @return {boolean} + */ +proto.hiddifyrpc.SystemProxyStatus.prototype.getAvailable = function() { + return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 1, false)); +}; + + +/** + * @param {boolean} value + * @return {!proto.hiddifyrpc.SystemProxyStatus} returns this + */ +proto.hiddifyrpc.SystemProxyStatus.prototype.setAvailable = function(value) { + return jspb.Message.setProto3BooleanField(this, 1, value); +}; + + +/** + * optional bool enabled = 2; + * @return {boolean} + */ +proto.hiddifyrpc.SystemProxyStatus.prototype.getEnabled = function() { + return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 2, false)); +}; + + +/** + * @param {boolean} value + * @return {!proto.hiddifyrpc.SystemProxyStatus} returns this + */ +proto.hiddifyrpc.SystemProxyStatus.prototype.setEnabled = function(value) { + return jspb.Message.setProto3BooleanField(this, 2, value); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.ParseRequest.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.ParseRequest.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.ParseRequest} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.ParseRequest.toObject = function(includeInstance, msg) { + var f, obj = { +content: jspb.Message.getFieldWithDefault(msg, 1, ""), +configPath: jspb.Message.getFieldWithDefault(msg, 2, ""), +tempPath: jspb.Message.getFieldWithDefault(msg, 3, ""), +debug: jspb.Message.getBooleanFieldWithDefault(msg, 4, false) + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.ParseRequest} + */ +proto.hiddifyrpc.ParseRequest.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.ParseRequest; + return proto.hiddifyrpc.ParseRequest.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.ParseRequest} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.ParseRequest} + */ +proto.hiddifyrpc.ParseRequest.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {string} */ (reader.readString()); + msg.setContent(value); + break; + case 2: + var value = /** @type {string} */ (reader.readString()); + msg.setConfigPath(value); + break; + case 3: + var value = /** @type {string} */ (reader.readString()); + msg.setTempPath(value); + break; + case 4: + var value = /** @type {boolean} */ (reader.readBool()); + msg.setDebug(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.ParseRequest.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.ParseRequest.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.ParseRequest} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.ParseRequest.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getContent(); + if (f.length > 0) { + writer.writeString( + 1, + f + ); + } + f = message.getConfigPath(); + if (f.length > 0) { + writer.writeString( + 2, + f + ); + } + f = message.getTempPath(); + if (f.length > 0) { + writer.writeString( + 3, + f + ); + } + f = message.getDebug(); + if (f) { + writer.writeBool( + 4, + f + ); + } +}; + + +/** + * optional string content = 1; + * @return {string} + */ +proto.hiddifyrpc.ParseRequest.prototype.getContent = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.ParseRequest} returns this + */ +proto.hiddifyrpc.ParseRequest.prototype.setContent = function(value) { + return jspb.Message.setProto3StringField(this, 1, value); +}; + + +/** + * optional string config_path = 2; + * @return {string} + */ +proto.hiddifyrpc.ParseRequest.prototype.getConfigPath = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.ParseRequest} returns this + */ +proto.hiddifyrpc.ParseRequest.prototype.setConfigPath = function(value) { + return jspb.Message.setProto3StringField(this, 2, value); +}; + + +/** + * optional string temp_path = 3; + * @return {string} + */ +proto.hiddifyrpc.ParseRequest.prototype.getTempPath = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.ParseRequest} returns this + */ +proto.hiddifyrpc.ParseRequest.prototype.setTempPath = function(value) { + return jspb.Message.setProto3StringField(this, 3, value); +}; + + +/** + * optional bool debug = 4; + * @return {boolean} + */ +proto.hiddifyrpc.ParseRequest.prototype.getDebug = function() { + return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 4, false)); +}; + + +/** + * @param {boolean} value + * @return {!proto.hiddifyrpc.ParseRequest} returns this + */ +proto.hiddifyrpc.ParseRequest.prototype.setDebug = function(value) { + return jspb.Message.setProto3BooleanField(this, 4, value); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.ParseResponse.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.ParseResponse.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.ParseResponse} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.ParseResponse.toObject = function(includeInstance, msg) { + var f, obj = { +responseCode: jspb.Message.getFieldWithDefault(msg, 1, 0), +content: jspb.Message.getFieldWithDefault(msg, 2, ""), +message: jspb.Message.getFieldWithDefault(msg, 3, "") + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.ParseResponse} + */ +proto.hiddifyrpc.ParseResponse.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.ParseResponse; + return proto.hiddifyrpc.ParseResponse.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.ParseResponse} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.ParseResponse} + */ +proto.hiddifyrpc.ParseResponse.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {!proto.hiddifyrpc.ResponseCode} */ (reader.readEnum()); + msg.setResponseCode(value); + break; + case 2: + var value = /** @type {string} */ (reader.readString()); + msg.setContent(value); + break; + case 3: + var value = /** @type {string} */ (reader.readString()); + msg.setMessage(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.ParseResponse.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.ParseResponse.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.ParseResponse} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.ParseResponse.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getResponseCode(); + if (f !== 0.0) { + writer.writeEnum( + 1, + f + ); + } + f = message.getContent(); + if (f.length > 0) { + writer.writeString( + 2, + f + ); + } + f = message.getMessage(); + if (f.length > 0) { + writer.writeString( + 3, + f + ); + } +}; + + +/** + * optional ResponseCode response_code = 1; + * @return {!proto.hiddifyrpc.ResponseCode} + */ +proto.hiddifyrpc.ParseResponse.prototype.getResponseCode = function() { + return /** @type {!proto.hiddifyrpc.ResponseCode} */ (jspb.Message.getFieldWithDefault(this, 1, 0)); +}; + + +/** + * @param {!proto.hiddifyrpc.ResponseCode} value + * @return {!proto.hiddifyrpc.ParseResponse} returns this + */ +proto.hiddifyrpc.ParseResponse.prototype.setResponseCode = function(value) { + return jspb.Message.setProto3EnumField(this, 1, value); +}; + + +/** + * optional string content = 2; + * @return {string} + */ +proto.hiddifyrpc.ParseResponse.prototype.getContent = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.ParseResponse} returns this + */ +proto.hiddifyrpc.ParseResponse.prototype.setContent = function(value) { + return jspb.Message.setProto3StringField(this, 2, value); +}; + + +/** + * optional string message = 3; + * @return {string} + */ +proto.hiddifyrpc.ParseResponse.prototype.getMessage = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.ParseResponse} returns this + */ +proto.hiddifyrpc.ParseResponse.prototype.setMessage = function(value) { + return jspb.Message.setProto3StringField(this, 3, value); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.ChangeHiddifySettingsRequest.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.ChangeHiddifySettingsRequest.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.ChangeHiddifySettingsRequest} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.ChangeHiddifySettingsRequest.toObject = function(includeInstance, msg) { + var f, obj = { +hiddifySettingsJson: jspb.Message.getFieldWithDefault(msg, 1, "") + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.ChangeHiddifySettingsRequest} + */ +proto.hiddifyrpc.ChangeHiddifySettingsRequest.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.ChangeHiddifySettingsRequest; + return proto.hiddifyrpc.ChangeHiddifySettingsRequest.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.ChangeHiddifySettingsRequest} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.ChangeHiddifySettingsRequest} + */ +proto.hiddifyrpc.ChangeHiddifySettingsRequest.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {string} */ (reader.readString()); + msg.setHiddifySettingsJson(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.ChangeHiddifySettingsRequest.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.ChangeHiddifySettingsRequest.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.ChangeHiddifySettingsRequest} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.ChangeHiddifySettingsRequest.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getHiddifySettingsJson(); + if (f.length > 0) { + writer.writeString( + 1, + f + ); + } +}; + + +/** + * optional string hiddify_settings_json = 1; + * @return {string} + */ +proto.hiddifyrpc.ChangeHiddifySettingsRequest.prototype.getHiddifySettingsJson = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.ChangeHiddifySettingsRequest} returns this + */ +proto.hiddifyrpc.ChangeHiddifySettingsRequest.prototype.setHiddifySettingsJson = function(value) { + return jspb.Message.setProto3StringField(this, 1, value); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.GenerateConfigRequest.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.GenerateConfigRequest.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.GenerateConfigRequest} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.GenerateConfigRequest.toObject = function(includeInstance, msg) { + var f, obj = { +path: jspb.Message.getFieldWithDefault(msg, 1, ""), +tempPath: jspb.Message.getFieldWithDefault(msg, 2, ""), +debug: jspb.Message.getBooleanFieldWithDefault(msg, 3, false) + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.GenerateConfigRequest} + */ +proto.hiddifyrpc.GenerateConfigRequest.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.GenerateConfigRequest; + return proto.hiddifyrpc.GenerateConfigRequest.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.GenerateConfigRequest} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.GenerateConfigRequest} + */ +proto.hiddifyrpc.GenerateConfigRequest.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {string} */ (reader.readString()); + msg.setPath(value); + break; + case 2: + var value = /** @type {string} */ (reader.readString()); + msg.setTempPath(value); + break; + case 3: + var value = /** @type {boolean} */ (reader.readBool()); + msg.setDebug(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.GenerateConfigRequest.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.GenerateConfigRequest.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.GenerateConfigRequest} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.GenerateConfigRequest.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getPath(); + if (f.length > 0) { + writer.writeString( + 1, + f + ); + } + f = message.getTempPath(); + if (f.length > 0) { + writer.writeString( + 2, + f + ); + } + f = message.getDebug(); + if (f) { + writer.writeBool( + 3, + f + ); + } +}; + + +/** + * optional string path = 1; + * @return {string} + */ +proto.hiddifyrpc.GenerateConfigRequest.prototype.getPath = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.GenerateConfigRequest} returns this + */ +proto.hiddifyrpc.GenerateConfigRequest.prototype.setPath = function(value) { + return jspb.Message.setProto3StringField(this, 1, value); +}; + + +/** + * optional string temp_path = 2; + * @return {string} + */ +proto.hiddifyrpc.GenerateConfigRequest.prototype.getTempPath = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.GenerateConfigRequest} returns this + */ +proto.hiddifyrpc.GenerateConfigRequest.prototype.setTempPath = function(value) { + return jspb.Message.setProto3StringField(this, 2, value); +}; + + +/** + * optional bool debug = 3; + * @return {boolean} + */ +proto.hiddifyrpc.GenerateConfigRequest.prototype.getDebug = function() { + return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 3, false)); +}; + + +/** + * @param {boolean} value + * @return {!proto.hiddifyrpc.GenerateConfigRequest} returns this + */ +proto.hiddifyrpc.GenerateConfigRequest.prototype.setDebug = function(value) { + return jspb.Message.setProto3BooleanField(this, 3, value); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.GenerateConfigResponse.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.GenerateConfigResponse.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.GenerateConfigResponse} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.GenerateConfigResponse.toObject = function(includeInstance, msg) { + var f, obj = { +configContent: jspb.Message.getFieldWithDefault(msg, 1, "") + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.GenerateConfigResponse} + */ +proto.hiddifyrpc.GenerateConfigResponse.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.GenerateConfigResponse; + return proto.hiddifyrpc.GenerateConfigResponse.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.GenerateConfigResponse} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.GenerateConfigResponse} + */ +proto.hiddifyrpc.GenerateConfigResponse.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {string} */ (reader.readString()); + msg.setConfigContent(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.GenerateConfigResponse.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.GenerateConfigResponse.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.GenerateConfigResponse} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.GenerateConfigResponse.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getConfigContent(); + if (f.length > 0) { + writer.writeString( + 1, + f + ); + } +}; + + +/** + * optional string config_content = 1; + * @return {string} + */ +proto.hiddifyrpc.GenerateConfigResponse.prototype.getConfigContent = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.GenerateConfigResponse} returns this + */ +proto.hiddifyrpc.GenerateConfigResponse.prototype.setConfigContent = function(value) { + return jspb.Message.setProto3StringField(this, 1, value); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.SelectOutboundRequest.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.SelectOutboundRequest.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.SelectOutboundRequest} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.SelectOutboundRequest.toObject = function(includeInstance, msg) { + var f, obj = { +groupTag: jspb.Message.getFieldWithDefault(msg, 1, ""), +outboundTag: jspb.Message.getFieldWithDefault(msg, 2, "") + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.SelectOutboundRequest} + */ +proto.hiddifyrpc.SelectOutboundRequest.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.SelectOutboundRequest; + return proto.hiddifyrpc.SelectOutboundRequest.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.SelectOutboundRequest} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.SelectOutboundRequest} + */ +proto.hiddifyrpc.SelectOutboundRequest.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {string} */ (reader.readString()); + msg.setGroupTag(value); + break; + case 2: + var value = /** @type {string} */ (reader.readString()); + msg.setOutboundTag(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.SelectOutboundRequest.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.SelectOutboundRequest.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.SelectOutboundRequest} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.SelectOutboundRequest.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getGroupTag(); + if (f.length > 0) { + writer.writeString( + 1, + f + ); + } + f = message.getOutboundTag(); + if (f.length > 0) { + writer.writeString( + 2, + f + ); + } +}; + + +/** + * optional string group_tag = 1; + * @return {string} + */ +proto.hiddifyrpc.SelectOutboundRequest.prototype.getGroupTag = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.SelectOutboundRequest} returns this + */ +proto.hiddifyrpc.SelectOutboundRequest.prototype.setGroupTag = function(value) { + return jspb.Message.setProto3StringField(this, 1, value); +}; + + +/** + * optional string outbound_tag = 2; + * @return {string} + */ +proto.hiddifyrpc.SelectOutboundRequest.prototype.getOutboundTag = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.SelectOutboundRequest} returns this + */ +proto.hiddifyrpc.SelectOutboundRequest.prototype.setOutboundTag = function(value) { + return jspb.Message.setProto3StringField(this, 2, value); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.UrlTestRequest.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.UrlTestRequest.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.UrlTestRequest} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.UrlTestRequest.toObject = function(includeInstance, msg) { + var f, obj = { +groupTag: jspb.Message.getFieldWithDefault(msg, 1, "") + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.UrlTestRequest} + */ +proto.hiddifyrpc.UrlTestRequest.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.UrlTestRequest; + return proto.hiddifyrpc.UrlTestRequest.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.UrlTestRequest} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.UrlTestRequest} + */ +proto.hiddifyrpc.UrlTestRequest.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {string} */ (reader.readString()); + msg.setGroupTag(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.UrlTestRequest.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.UrlTestRequest.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.UrlTestRequest} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.UrlTestRequest.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getGroupTag(); + if (f.length > 0) { + writer.writeString( + 1, + f + ); + } +}; + + +/** + * optional string group_tag = 1; + * @return {string} + */ +proto.hiddifyrpc.UrlTestRequest.prototype.getGroupTag = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.UrlTestRequest} returns this + */ +proto.hiddifyrpc.UrlTestRequest.prototype.setGroupTag = function(value) { + return jspb.Message.setProto3StringField(this, 1, value); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.GenerateWarpConfigRequest.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.GenerateWarpConfigRequest.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.GenerateWarpConfigRequest} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.GenerateWarpConfigRequest.toObject = function(includeInstance, msg) { + var f, obj = { +licenseKey: jspb.Message.getFieldWithDefault(msg, 1, ""), +accountId: jspb.Message.getFieldWithDefault(msg, 2, ""), +accessToken: jspb.Message.getFieldWithDefault(msg, 3, "") + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.GenerateWarpConfigRequest} + */ +proto.hiddifyrpc.GenerateWarpConfigRequest.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.GenerateWarpConfigRequest; + return proto.hiddifyrpc.GenerateWarpConfigRequest.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.GenerateWarpConfigRequest} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.GenerateWarpConfigRequest} + */ +proto.hiddifyrpc.GenerateWarpConfigRequest.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {string} */ (reader.readString()); + msg.setLicenseKey(value); + break; + case 2: + var value = /** @type {string} */ (reader.readString()); + msg.setAccountId(value); + break; + case 3: + var value = /** @type {string} */ (reader.readString()); + msg.setAccessToken(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.GenerateWarpConfigRequest.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.GenerateWarpConfigRequest.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.GenerateWarpConfigRequest} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.GenerateWarpConfigRequest.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getLicenseKey(); + if (f.length > 0) { + writer.writeString( + 1, + f + ); + } + f = message.getAccountId(); + if (f.length > 0) { + writer.writeString( + 2, + f + ); + } + f = message.getAccessToken(); + if (f.length > 0) { + writer.writeString( + 3, + f + ); + } +}; + + +/** + * optional string license_key = 1; + * @return {string} + */ +proto.hiddifyrpc.GenerateWarpConfigRequest.prototype.getLicenseKey = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.GenerateWarpConfigRequest} returns this + */ +proto.hiddifyrpc.GenerateWarpConfigRequest.prototype.setLicenseKey = function(value) { + return jspb.Message.setProto3StringField(this, 1, value); +}; + + +/** + * optional string account_id = 2; + * @return {string} + */ +proto.hiddifyrpc.GenerateWarpConfigRequest.prototype.getAccountId = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.GenerateWarpConfigRequest} returns this + */ +proto.hiddifyrpc.GenerateWarpConfigRequest.prototype.setAccountId = function(value) { + return jspb.Message.setProto3StringField(this, 2, value); +}; + + +/** + * optional string access_token = 3; + * @return {string} + */ +proto.hiddifyrpc.GenerateWarpConfigRequest.prototype.getAccessToken = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.GenerateWarpConfigRequest} returns this + */ +proto.hiddifyrpc.GenerateWarpConfigRequest.prototype.setAccessToken = function(value) { + return jspb.Message.setProto3StringField(this, 3, value); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.SetSystemProxyEnabledRequest.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.SetSystemProxyEnabledRequest.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.SetSystemProxyEnabledRequest} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.SetSystemProxyEnabledRequest.toObject = function(includeInstance, msg) { + var f, obj = { +isEnabled: jspb.Message.getBooleanFieldWithDefault(msg, 1, false) + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.SetSystemProxyEnabledRequest} + */ +proto.hiddifyrpc.SetSystemProxyEnabledRequest.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.SetSystemProxyEnabledRequest; + return proto.hiddifyrpc.SetSystemProxyEnabledRequest.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.SetSystemProxyEnabledRequest} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.SetSystemProxyEnabledRequest} + */ +proto.hiddifyrpc.SetSystemProxyEnabledRequest.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {boolean} */ (reader.readBool()); + msg.setIsEnabled(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.SetSystemProxyEnabledRequest.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.SetSystemProxyEnabledRequest.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.SetSystemProxyEnabledRequest} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.SetSystemProxyEnabledRequest.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getIsEnabled(); + if (f) { + writer.writeBool( + 1, + f + ); + } +}; + + +/** + * optional bool is_enabled = 1; + * @return {boolean} + */ +proto.hiddifyrpc.SetSystemProxyEnabledRequest.prototype.getIsEnabled = function() { + return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 1, false)); +}; + + +/** + * @param {boolean} value + * @return {!proto.hiddifyrpc.SetSystemProxyEnabledRequest} returns this + */ +proto.hiddifyrpc.SetSystemProxyEnabledRequest.prototype.setIsEnabled = function(value) { + return jspb.Message.setProto3BooleanField(this, 1, value); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.LogMessage.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.LogMessage.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.LogMessage} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.LogMessage.toObject = function(includeInstance, msg) { + var f, obj = { +level: jspb.Message.getFieldWithDefault(msg, 1, 0), +type: jspb.Message.getFieldWithDefault(msg, 2, 0), +message: jspb.Message.getFieldWithDefault(msg, 3, "") + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.LogMessage} + */ +proto.hiddifyrpc.LogMessage.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.LogMessage; + return proto.hiddifyrpc.LogMessage.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.LogMessage} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.LogMessage} + */ +proto.hiddifyrpc.LogMessage.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {!proto.hiddifyrpc.LogLevel} */ (reader.readEnum()); + msg.setLevel(value); + break; + case 2: + var value = /** @type {!proto.hiddifyrpc.LogType} */ (reader.readEnum()); + msg.setType(value); + break; + case 3: + var value = /** @type {string} */ (reader.readString()); + msg.setMessage(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.LogMessage.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.LogMessage.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.LogMessage} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.LogMessage.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getLevel(); + if (f !== 0.0) { + writer.writeEnum( + 1, + f + ); + } + f = message.getType(); + if (f !== 0.0) { + writer.writeEnum( + 2, + f + ); + } + f = message.getMessage(); + if (f.length > 0) { + writer.writeString( + 3, + f + ); + } +}; + + +/** + * optional LogLevel level = 1; + * @return {!proto.hiddifyrpc.LogLevel} + */ +proto.hiddifyrpc.LogMessage.prototype.getLevel = function() { + return /** @type {!proto.hiddifyrpc.LogLevel} */ (jspb.Message.getFieldWithDefault(this, 1, 0)); +}; + + +/** + * @param {!proto.hiddifyrpc.LogLevel} value + * @return {!proto.hiddifyrpc.LogMessage} returns this + */ +proto.hiddifyrpc.LogMessage.prototype.setLevel = function(value) { + return jspb.Message.setProto3EnumField(this, 1, value); +}; + + +/** + * optional LogType type = 2; + * @return {!proto.hiddifyrpc.LogType} + */ +proto.hiddifyrpc.LogMessage.prototype.getType = function() { + return /** @type {!proto.hiddifyrpc.LogType} */ (jspb.Message.getFieldWithDefault(this, 2, 0)); +}; + + +/** + * @param {!proto.hiddifyrpc.LogType} value + * @return {!proto.hiddifyrpc.LogMessage} returns this + */ +proto.hiddifyrpc.LogMessage.prototype.setType = function(value) { + return jspb.Message.setProto3EnumField(this, 2, value); +}; + + +/** + * optional string message = 3; + * @return {string} + */ +proto.hiddifyrpc.LogMessage.prototype.getMessage = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.LogMessage} returns this + */ +proto.hiddifyrpc.LogMessage.prototype.setMessage = function(value) { + return jspb.Message.setProto3StringField(this, 3, value); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.StopRequest.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.StopRequest.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.StopRequest} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.StopRequest.toObject = function(includeInstance, msg) { + var f, obj = { + + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.StopRequest} + */ +proto.hiddifyrpc.StopRequest.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.StopRequest; + return proto.hiddifyrpc.StopRequest.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.StopRequest} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.StopRequest} + */ +proto.hiddifyrpc.StopRequest.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.StopRequest.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.StopRequest.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.StopRequest} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.StopRequest.serializeBinaryToWriter = function(message, writer) { + var f = undefined; +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.TunnelStartRequest.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.TunnelStartRequest.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.TunnelStartRequest} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.TunnelStartRequest.toObject = function(includeInstance, msg) { + var f, obj = { +ipv6: jspb.Message.getBooleanFieldWithDefault(msg, 1, false), +serverPort: jspb.Message.getFieldWithDefault(msg, 2, 0), +strictRoute: jspb.Message.getBooleanFieldWithDefault(msg, 3, false), +endpointIndependentNat: jspb.Message.getBooleanFieldWithDefault(msg, 4, false), +stack: jspb.Message.getFieldWithDefault(msg, 5, "") + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.TunnelStartRequest} + */ +proto.hiddifyrpc.TunnelStartRequest.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.TunnelStartRequest; + return proto.hiddifyrpc.TunnelStartRequest.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.TunnelStartRequest} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.TunnelStartRequest} + */ +proto.hiddifyrpc.TunnelStartRequest.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {boolean} */ (reader.readBool()); + msg.setIpv6(value); + break; + case 2: + var value = /** @type {number} */ (reader.readInt32()); + msg.setServerPort(value); + break; + case 3: + var value = /** @type {boolean} */ (reader.readBool()); + msg.setStrictRoute(value); + break; + case 4: + var value = /** @type {boolean} */ (reader.readBool()); + msg.setEndpointIndependentNat(value); + break; + case 5: + var value = /** @type {string} */ (reader.readString()); + msg.setStack(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.TunnelStartRequest.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.TunnelStartRequest.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.TunnelStartRequest} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.TunnelStartRequest.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getIpv6(); + if (f) { + writer.writeBool( + 1, + f + ); + } + f = message.getServerPort(); + if (f !== 0) { + writer.writeInt32( + 2, + f + ); + } + f = message.getStrictRoute(); + if (f) { + writer.writeBool( + 3, + f + ); + } + f = message.getEndpointIndependentNat(); + if (f) { + writer.writeBool( + 4, + f + ); + } + f = message.getStack(); + if (f.length > 0) { + writer.writeString( + 5, + f + ); + } +}; + + +/** + * optional bool ipv6 = 1; + * @return {boolean} + */ +proto.hiddifyrpc.TunnelStartRequest.prototype.getIpv6 = function() { + return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 1, false)); +}; + + +/** + * @param {boolean} value + * @return {!proto.hiddifyrpc.TunnelStartRequest} returns this + */ +proto.hiddifyrpc.TunnelStartRequest.prototype.setIpv6 = function(value) { + return jspb.Message.setProto3BooleanField(this, 1, value); +}; + + +/** + * optional int32 server_port = 2; + * @return {number} + */ +proto.hiddifyrpc.TunnelStartRequest.prototype.getServerPort = function() { + return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 2, 0)); +}; + + +/** + * @param {number} value + * @return {!proto.hiddifyrpc.TunnelStartRequest} returns this + */ +proto.hiddifyrpc.TunnelStartRequest.prototype.setServerPort = function(value) { + return jspb.Message.setProto3IntField(this, 2, value); +}; + + +/** + * optional bool strict_route = 3; + * @return {boolean} + */ +proto.hiddifyrpc.TunnelStartRequest.prototype.getStrictRoute = function() { + return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 3, false)); +}; + + +/** + * @param {boolean} value + * @return {!proto.hiddifyrpc.TunnelStartRequest} returns this + */ +proto.hiddifyrpc.TunnelStartRequest.prototype.setStrictRoute = function(value) { + return jspb.Message.setProto3BooleanField(this, 3, value); +}; + + +/** + * optional bool endpoint_independent_nat = 4; + * @return {boolean} + */ +proto.hiddifyrpc.TunnelStartRequest.prototype.getEndpointIndependentNat = function() { + return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 4, false)); +}; + + +/** + * @param {boolean} value + * @return {!proto.hiddifyrpc.TunnelStartRequest} returns this + */ +proto.hiddifyrpc.TunnelStartRequest.prototype.setEndpointIndependentNat = function(value) { + return jspb.Message.setProto3BooleanField(this, 4, value); +}; + + +/** + * optional string stack = 5; + * @return {string} + */ +proto.hiddifyrpc.TunnelStartRequest.prototype.getStack = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 5, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.TunnelStartRequest} returns this + */ +proto.hiddifyrpc.TunnelStartRequest.prototype.setStack = function(value) { + return jspb.Message.setProto3StringField(this, 5, value); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.hiddifyrpc.TunnelResponse.prototype.toObject = function(opt_includeInstance) { + return proto.hiddifyrpc.TunnelResponse.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.hiddifyrpc.TunnelResponse} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.TunnelResponse.toObject = function(includeInstance, msg) { + var f, obj = { +message: jspb.Message.getFieldWithDefault(msg, 1, "") + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.hiddifyrpc.TunnelResponse} + */ +proto.hiddifyrpc.TunnelResponse.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.hiddifyrpc.TunnelResponse; + return proto.hiddifyrpc.TunnelResponse.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.hiddifyrpc.TunnelResponse} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.hiddifyrpc.TunnelResponse} + */ +proto.hiddifyrpc.TunnelResponse.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {string} */ (reader.readString()); + msg.setMessage(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.hiddifyrpc.TunnelResponse.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.hiddifyrpc.TunnelResponse.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.hiddifyrpc.TunnelResponse} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.hiddifyrpc.TunnelResponse.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getMessage(); + if (f.length > 0) { + writer.writeString( + 1, + f + ); + } +}; + + +/** + * optional string message = 1; + * @return {string} + */ +proto.hiddifyrpc.TunnelResponse.prototype.getMessage = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); +}; + + +/** + * @param {string} value + * @return {!proto.hiddifyrpc.TunnelResponse} returns this + */ +proto.hiddifyrpc.TunnelResponse.prototype.setMessage = function(value) { + return jspb.Message.setProto3StringField(this, 1, value); +}; + + +/** + * @enum {number} + */ +proto.hiddifyrpc.CoreState = { + STOPPED: 0, + STARTING: 1, + STARTED: 2, + STOPPING: 3 +}; + +/** + * @enum {number} + */ +proto.hiddifyrpc.MessageType = { + EMPTY: 0, + EMPTY_CONFIGURATION: 1, + START_COMMAND_SERVER: 2, + CREATE_SERVICE: 3, + START_SERVICE: 4, + UNEXPECTED_ERROR: 5, + ALREADY_STARTED: 6, + ALREADY_STOPPED: 7, + INSTANCE_NOT_FOUND: 8, + INSTANCE_NOT_STOPPED: 9, + INSTANCE_NOT_STARTED: 10, + ERROR_BUILDING_CONFIG: 11, + ERROR_PARSING_CONFIG: 12, + ERROR_READING_CONFIG: 13 +}; + +/** + * @enum {number} + */ +proto.hiddifyrpc.LogLevel = { + DEBUG: 0, + INFO: 1, + WARNING: 2, + ERROR: 3, + FATAL: 4 +}; + +/** + * @enum {number} + */ +proto.hiddifyrpc.LogType = { + CORE: 0, + SERVICE: 1, + CONFIG: 2 +}; + +goog.object.extend(exports, proto.hiddifyrpc); diff --git a/libcore/extension/interface.go b/libcore/extension/interface.go new file mode 100644 index 0000000..60cbb56 --- /dev/null +++ b/libcore/extension/interface.go @@ -0,0 +1,91 @@ +package extension + +import ( + "fmt" + + "github.com/hiddify/hiddify-core/v2/db" + "github.com/sagernet/sing-box/log" + + "github.com/hiddify/hiddify-core/v2/service_manager" +) + +var ( + allExtensionsMap = make(map[string]ExtensionFactory) + enabledExtensionsMap = make(map[string]*Extension) +) + +func RegisterExtension(factory ExtensionFactory) error { + if _, ok := allExtensionsMap[factory.Id]; ok { + err := fmt.Errorf("Extension with ID %s already exists", factory.Id) + log.Warn(err) + return err + } + + allExtensionsMap[factory.Id] = factory + + return nil +} + +func isEnable(id string) bool { + table := db.GetTable[extensionData]() + extdata, err := table.Get(id) + if err != nil { + return false + } + return extdata.Enable +} + +func loadExtension(factory ExtensionFactory) error { + if !isEnable(factory.Id) { + return fmt.Errorf("Extension with ID %s is not enabled", factory.Id) + } + extension := factory.Builder() + extension.init(factory.Id) + + // fmt.Printf("Registered extension: %+v\n", extension) + enabledExtensionsMap[factory.Id] = &extension + + return nil +} + +type extensionService struct { + // Storage *CacheFile +} + +func (s *extensionService) Start() error { + table := db.GetTable[extensionData]() + + for _, factory := range allExtensionsMap { + data, err := table.Get(factory.Id) + + if data == nil || err != nil { + log.Warn("Data of Extension ", factory.Id, " not found, creating new one") + data = &extensionData{Id: factory.Id, Enable: false} + if err := table.UpdateInsert(data); err != nil { + log.Warn("Failed to create new extension data: ", err, " ", factory.Id) + return err + } + } + + if data.Enable { + if err := loadExtension(factory); err != nil { + return fmt.Errorf("failed to load extension %s: %w", data.Id, err) + } + } + } + + return nil +} + +func (s *extensionService) Close() error { + for _, extension := range enabledExtensionsMap { + if err := (*extension).Close(); err != nil { + return err + } + } + return nil +} + +func init() { + service_manager.Register(&extensionService{}) +} diff --git a/libcore/extension/repository/extension_list.go b/libcore/extension/repository/extension_list.go new file mode 100644 index 0000000..cfb9bf2 --- /dev/null +++ b/libcore/extension/repository/extension_list.go @@ -0,0 +1,6 @@ +package repository + +import ( + _ "github.com/hiddify/hiddify-app-demo-extension/hiddify_extension" + _ "github.com/hiddify/hiddify-ip-scanner-extension/hiddify_extension" +) diff --git a/libcore/extension/sdk/interface.go b/libcore/extension/sdk/interface.go new file mode 100644 index 0000000..e84cb2b --- /dev/null +++ b/libcore/extension/sdk/interface.go @@ -0,0 +1,47 @@ +package sdk + +import ( + "fmt" + "io/ioutil" + "net/http" + "runtime" + "strings" + + "github.com/hiddify/hiddify-core/config" + v2 "github.com/hiddify/hiddify-core/v2" + "github.com/sagernet/sing-box/option" +) + +func RunInstance(hiddifySettings *config.HiddifyOptions, singconfig *option.Options) (*v2.HiddifyService, error) { + return v2.RunInstance(hiddifySettings, singconfig) +} + +func ParseConfig(hiddifySettings *config.HiddifyOptions, configStr string) (*option.Options, error) { + if hiddifySettings == nil { + hiddifySettings = config.DefaultHiddifyOptions() + } + if strings.HasPrefix(configStr, "http://") || strings.HasPrefix(configStr, "https://") { + client := &http.Client{} + configPath := strings.Split(configStr, "\n")[0] + // Create a new request + req, err := http.NewRequest("GET", configPath, nil) + if err != nil { + fmt.Println("Error creating request:", err) + return nil, err + } + req.Header.Set("User-Agent", "HiddifyNext/2.3.1 ("+runtime.GOOS+") like ClashMeta v2ray sing-box") + resp, err := client.Do(req) + if err != nil { + fmt.Println("Error making GET request:", err) + return nil, err + } + defer resp.Body.Close() + + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, fmt.Errorf("failed to read config body: %w", err) + } + configStr = string(body) + } + return config.ParseConfigContentToOptions(configStr, true, hiddifySettings, false) +} diff --git a/libcore/extension/server/run_server.go b/libcore/extension/server/run_server.go new file mode 100644 index 0000000..d1a8217 --- /dev/null +++ b/libcore/extension/server/run_server.go @@ -0,0 +1,117 @@ +package server + +import ( + "context" + "fmt" + "log" + "net/http" + "os" + "os/signal" + "sync" + "syscall" + + v2 "github.com/hiddify/hiddify-core/v2" + + "github.com/hiddify/hiddify-core/utils" + "github.com/improbable-eng/grpc-web/go/grpcweb" + "google.golang.org/grpc" +) + +func StartTestExtensionServer() { + v2.Setup("./tmp", "./", "./tmp", 0, false) + StartExtensionServer() +} + +func StartExtensionServer() { + grpc_server, _ := v2.StartCoreGrpcServer("127.0.0.1:12345") + fmt.Printf("Waiting for CTRL+C to stop\n") + runWebserver(grpc_server) +} + +func allowCors(resp http.ResponseWriter, req *http.Request) { + resp.Header().Set("Access-Control-Allow-Origin", "*") + resp.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS") + resp.Header().Set("Access-Control-Allow-Headers", "Content-Type") + if req.Method == "OPTIONS" { + resp.WriteHeader(http.StatusOK) + return + } +} + +func runWebserver(grpcServer *grpc.Server) { + // Context for cancellation + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + // Channels to signal termination + grpcTerminated := make(chan struct{}) + grpcWebTerminated := make(chan struct{}) + + // Specify the directory to serve static files + dir := "./extension/html/" + + // Wrapping gRPC server with grpc-web + grpcWeb := grpcweb.WrapServer(grpcServer) + + // HTTP multiplexer + mux := http.NewServeMux() + mux.HandleFunc("/", func(resp http.ResponseWriter, req *http.Request) { + allowCors(resp, req) + if grpcWeb.IsGrpcWebRequest(req) || grpcWeb.IsAcceptableGrpcCorsRequest(req) { + grpcWeb.ServeHTTP(resp, req) + } else { + http.DefaultServeMux.ServeHTTP(resp, req) + } + }) + + // File server for static files + fs := http.FileServer(http.Dir(dir)) + http.Handle("/", http.StripPrefix("/", fs)) + + // HTTP server for grpc-web + rpcWebServer := &http.Server{ + Handler: mux, + Addr: ":12346", + } + log.Println("Serving grpc-web from https://localhost:12346/") + + // Add a goroutine for the grpc-web server + wg := sync.WaitGroup{} + wg.Add(1) + + go func() { + defer wg.Done() + utils.GenerateCertificate("cert/server-cert.pem", "cert/server-key.pem", true, true) + if err := rpcWebServer.ListenAndServeTLS("cert/server-cert.pem", "cert/server-key.pem"); err != nil && err != http.ErrServerClosed { + // if err := rpcWebServer.ListenAndServe(); err != nil && err != http.ErrServerClosed { + fmt.Printf("Web server (gRPC-web) shutdown with error: %s", err) + } + grpcServer.Stop() + close(grpcWebTerminated) // Server terminated + }() + + // Signal handling to gracefully shutdown + sigChan := make(chan os.Signal, 1) + signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM) + + select { + case <-ctx.Done(): // Context canceled + log.Println("Context canceled, shutting down servers...") + case sig := <-sigChan: // OS signal received + log.Printf("Received signal: %s, shutting down servers...", sig) + case <-grpcTerminated: // Unexpected gRPC termination + log.Println("gRPC server terminated unexpectedly") + case <-grpcWebTerminated: // Unexpected gRPC-web termination + log.Println("gRPC-web server terminated unexpectedly") + } + + // Graceful shutdown of the servers + if err := rpcWebServer.Shutdown(ctx); err != nil { + log.Printf("gRPC-web server shutdown with error: %s", err) + } + <-grpcWebTerminated + + // Ensure all routines finish + wg.Wait() + log.Println("Server shutdown complete") +} diff --git a/libcore/extension/ui/abstract.go b/libcore/extension/ui/abstract.go new file mode 100644 index 0000000..b3c703d --- /dev/null +++ b/libcore/extension/ui/abstract.go @@ -0,0 +1,42 @@ +package ui + +// // Field is an interface that all specific field types implement. +// type Field interface { +// GetType() string +// } + +// // GenericField holds common field properties. +// const ( +// Select string = "Select" +// Email string = "Email" +// Input string = "Input" +// Password string = "Password" +// TextArea string = "TextArea" +// Switch string = "Switch" +// Checkbox string = "Checkbox" +// RadioButton string = "RadioButton" +// DigitsOnly string = "digitsOnly" +// ) + +// // FormField extends GenericField with additional common properties. +// type FormField struct { +// Key string `json:"key"` +// Type string `json:"type"` +// Label string `json:"label,omitempty"` +// LabelHidden bool `json:"labelHidden"` +// Required bool `json:"required,omitempty"` +// Placeholder string `json:"placeholder,omitempty"` +// Readonly bool `json:"readonly,omitempty"` +// Value string `json:"value"` +// Validator string `json:"validator,omitempty"` +// Items []SelectItem `json:"items,omitempty"` +// Lines int `json:"lines,omitempty"` +// VerticalScroll bool `json:"verticalScroll,omitempty"` +// HorizontalScroll bool `json:"horizontalScroll,omitempty"` +// Monospace bool `json:"monospace,omitempty"` +// } + +// // GetType returns the type of the field. +// func (gf FormField) GetType() string { +// return gf.Type +// } diff --git a/libcore/extension/ui/all_test.go b/libcore/extension/ui/all_test.go new file mode 100644 index 0000000..eedd36f --- /dev/null +++ b/libcore/extension/ui/all_test.go @@ -0,0 +1,75 @@ +package ui + +// import ( +// "encoding/json" +// "testing" +// ) + +// // Test UnmarshalJSON for different field types +// func TestFormUnmarshalJSON(t *testing.T) { +// formJSON := `{ +// "title": "Form Example", +// "description": "This is a sample form.", +// "fields": [ +// { +// "key": "inputKey", +// "type": "Input", +// "label": "Hi Group", +// "placeholder": "Hi Group flutter", +// "required": true, +// "value": "D" +// }, +// { +// "key": "passwordKey", +// "type": "Password", +// "label": "Password", +// "required": true, +// "value": "secret" +// }, +// { +// "key": "emailKey", +// "type": "Email", +// "label": "Email Label", +// "placeholder": "Enter your email", +// "required": true, +// "value": "example@example.com" +// } +// ] +// }` + +// var form Form +// err := json.Unmarshal([]byte(formJSON), &form) +// if err != nil { +// t.Fatalf("Error unmarshaling form JSON: %v", err) +// } + +// if form.Title != "Form Example" { +// t.Errorf("Expected Title to be 'Form Example', got '%s'", form.Title) +// } +// if form.Description != "This is a sample form." { +// t.Errorf("Expected Description to be 'This is a sample form.', got '%s'", form.Description) +// } + +// if len(form.Fields) != 3 { +// t.Fatalf("Expected 3 fields, got %d", len(form.Fields)) +// } + +// for i, field := range form.Fields { +// switch f := field.(type) { +// case InputField: +// if f.Type != "Input" { +// t.Errorf("Field %d: Expected Type to be 'Input', got '%s'", i+1, f.Type) +// } +// case PasswordField: +// if f.Type != "Password" { +// t.Errorf("Field %d: Expected Type to be 'Password', got '%s'", i+1, f.Type) +// } +// case EmailField: +// if f.Type != "Email" { +// t.Errorf("Field %d: Expected Type to be 'Email', got '%s'", i+1, f.Type) +// } +// default: +// t.Errorf("Field %d: Unexpected field type %T", i+1, f) +// } +// } +// } diff --git a/libcore/extension/ui/base.go b/libcore/extension/ui/base.go new file mode 100644 index 0000000..b9adc99 --- /dev/null +++ b/libcore/extension/ui/base.go @@ -0,0 +1,88 @@ +package ui + +import ( + "encoding/json" + "fmt" +) + +// Field is an interface that all specific field types implement. +type Field interface { + GetType() string +} + +// GenericField holds common field properties. +const ( + FieldSelect string = "Select" + FieldEmail string = "Email" + FieldInput string = "Input" + FieldPassword string = "Password" + FieldTextArea string = "TextArea" + FieldSwitch string = "Switch" + FieldCheckbox string = "Checkbox" + FieldRadioButton string = "RadioButton" + FieldConsole string = "Console" + FieldButton string = "Button" + ValidatorDigitsOnly string = "digitsOnly" + + ButtonSubmit string = "Submit" + ButtonCancel string = "Cancel" + + ButtonDialogClose string = "CloseDialog" + ButtonDialogOk string = "OkDialog" +) + +// FormField extends GenericField with additional common properties. +type FormField struct { + Key string `json:"key"` + Type string `json:"type"` + Label string `json:"label,omitempty"` + LabelHidden bool `json:"labelHidden"` + Required bool `json:"required,omitempty"` + Placeholder string `json:"placeholder,omitempty"` + Readonly bool `json:"readonly,omitempty"` + Value string `json:"value"` + Validator string `json:"validator,omitempty"` + Items []SelectItem `json:"items,omitempty"` + Lines int `json:"lines,omitempty"` +} + +// GetType returns the type of the field. +func (gf FormField) GetType() string { + return gf.Type +} + +type InputField struct { + FormField + Validator string `json:"validator,omitempty"` +} + +type SelectItem struct { + Label string `json:"label"` + Value string `json:"value"` +} + +type Form struct { + Title string `json:"title"` + Description string `json:"description"` + Fields [][]FormField `json:"fields"` + // Buttons []string `json:"buttons"` +} + +func (f *Form) ToJSON() string { + formJson, err := json.MarshalIndent(f, "", " ") + if err != nil { + fmt.Println("Error encoding to JSON:", err) + return "" + } + + return (string(formJson)) +} + +// UnmarshalJSON custom unmarshals JSON data into a Form. +func (f *Form) UnmarshalJSON(data []byte) error { + if err := json.Unmarshal(data, &f); err != nil { + return err + } + + return nil +} diff --git a/libcore/extension/ui/content.go b/libcore/extension/ui/content.go new file mode 100644 index 0000000..d78d045 --- /dev/null +++ b/libcore/extension/ui/content.go @@ -0,0 +1,25 @@ +package ui + +// // ContentField represents a label with additional properties. +// type ContentField struct { +// GenericField +// Lines int `json:"lines,omitempty"` +// VerticalScroll bool `json:"verticalScroll,omitempty"` +// HorizontalScroll bool `json:"horizontalScroll,omitempty"` +// Monospace bool `json:"monospace,omitempty"` +// } + +// // NewContentField creates a new ContentField. +// func NewContentField(key, label string, lines int, monospace, horizontalScroll, verticalScroll bool) ContentField { +// return ContentField{ +// GenericField: GenericField{ +// Key: key, +// Type: "Content", +// Label: label, +// }, +// Lines: lines, +// VerticalScroll: verticalScroll, +// HorizontalScroll: horizontalScroll, +// Monospace: monospace, +// } +// } diff --git a/libcore/extension/ui/data.go b/libcore/extension/ui/data.go new file mode 100644 index 0000000..5b1faa2 --- /dev/null +++ b/libcore/extension/ui/data.go @@ -0,0 +1 @@ +package ui diff --git a/libcore/extension/ui/form.go b/libcore/extension/ui/form.go new file mode 100644 index 0000000..f07dfc8 --- /dev/null +++ b/libcore/extension/ui/form.go @@ -0,0 +1,244 @@ +package ui + +// import ( +// "encoding/json" +// "fmt" +// ) + +// // InputField represents a text input field. +// type InputField struct { +// FormField +// Validator string `json:"validator,omitempty"` + +// } + +// // // NewInputField creates a new InputField. +// // func NewInputField(key, label, placeholder string, required bool, value string) InputField { +// // return InputField{ +// // FormField: FormField{ +// // GenericField: GenericField{ +// // Key: key, +// // Type: "Input", +// // Label: label, +// // }, +// // Placeholder: placeholder, +// // Required: required, +// // Value: value, +// // }, +// // } +// // } + +// // // PasswordField represents a password field. +// // type PasswordField struct { +// // FormField +// // } + +// // // NewPasswordField creates a new PasswordField. +// // func NewPasswordField(key, label string, required bool, value string) PasswordField { +// // return PasswordField{ +// // FormField: FormField{ +// // GenericField: GenericField{ +// // Key: key, +// // Type: "Password", +// // Label: label, +// // }, +// // Required: required, +// // Value: value, +// // }, +// // } +// // } + +// // // EmailField represents an email field. +// // type EmailField struct { +// // FormField +// // } + +// // // NewEmailField creates a new EmailField. +// // func NewEmailField(key, label, placeholder string, required bool, value string) EmailField { +// // return EmailField{ +// // FormField: FormField{ +// // GenericField: GenericField{ +// // Key: key, +// // Type: "Email", +// // Label: label, +// // }, +// // Placeholder: placeholder, +// // Required: required, +// // Value: value, +// // }, +// // } +// // } + +// // // TextAreaField represents a multi-line text area field. +// // type TextAreaField struct { +// // FormField +// // } + +// // // NewTextAreaField creates a new TextAreaField. +// // func NewTextAreaField(key, label, placeholder string, required bool, value string) TextAreaField { +// // return TextAreaField{ +// // FormField: FormField{ +// // GenericField: GenericField{ +// // Key: key, +// // Type: "TextArea", +// // Label: label, +// // }, +// // Placeholder: placeholder, +// // Required: required, +// // Value: value, +// // }, +// // } +// // } + +// // // SelectField represents a dropdown selection field. +// // type SelectField struct { +// // FormField +// // Items []SelectItem `json:"items"` +// // } + +// // // SelectItem represents an item in a dropdown. +// type SelectItem struct { +// Label string `json:"label"` +// Value string `json:"value"` +// } + +// // // NewSelectField creates a new SelectField. +// // func NewSelectField(key, label, value string, items []SelectItem) SelectField { +// // return SelectField{ +// // FormField: FormField{ +// // GenericField: GenericField{ +// // Key: key, +// // Type: "Select", +// // Label: label, +// // }, +// // Value: value, +// // }, +// // Items: items, +// // } +// // } + +// // Form represents a collection of fields with metadata. +// type Form struct { +// Title string `json:"title"` +// Description string `json:"description"` +// Fields []FormField `json:"fields"` +// } + +// func (f *Form) ToJSON() string { +// formJson, err := json.MarshalIndent(f, "", " ") +// if err != nil { +// fmt.Println("Error encoding to JSON:", err) +// return "" +// } +// return (string(formJson)) +// } + +// // UnmarshalJSON custom unmarshals JSON data into a Form. +// func (f *Form) UnmarshalJSON(data []byte) error { +// if err := json.Unmarshal(data, &f); err != nil { +// return err +// } + +// // f.Title = raw.Title +// // f.Description = raw.Description + +// // for _, fieldData := range raw.Fields { +// // var base FormField +// // if err := json.Unmarshal(fieldData, &base); err != nil { +// // return err +// // } + +// // var field Field +// // switch base.Type { +// // case "Input": +// // var inputField InputField +// // if err := json.Unmarshal(fieldData, &inputField); err != nil { +// // return err +// // } +// // field = inputField +// // case "Password": +// // var passwordField PasswordField +// // if err := json.Unmarshal(fieldData, &passwordField); err != nil { +// // return err +// // } +// // field = passwordField +// // case "Email": +// // var emailField EmailField +// // if err := json.Unmarshal(fieldData, &emailField); err != nil { +// // return err +// // } +// // field = emailField +// // case "TextArea": +// // var textAreaField TextAreaField +// // if err := json.Unmarshal(fieldData, &textAreaField); err != nil { +// // return err +// // } +// // field = textAreaField +// // case "Select": +// // var selectField SelectField +// // if err := json.Unmarshal(fieldData, &selectField); err != nil { +// // return err +// // } +// // field = selectField +// // case "Content": +// // var contentField ContentField +// // if err := json.Unmarshal(fieldData, &contentField); err != nil { +// // return err +// // } +// // field = contentField +// // default: +// // return fmt.Errorf("unsupported field type: %s", base.Type) +// // } + +// // f.Fields = append(f.Fields, field) +// // } + +// return nil +// } + +// // func main() { +// // // Example form JSON +// // formJSON := `{ +// // "title": "Form Example", +// // "description": "", +// // "fields": [ +// // { +// // "key": "inputKey", +// // "type": "Input", +// // "label": "Hi Group", +// // "placeholder": "Hi Group flutter", +// // "required": true, +// // "value": "D" +// // }, +// // { +// // "key": "passwordKey", +// // "type": "Password", +// // "label": "Password", +// // "required": true, +// // "value": "secret" +// // }, +// // { +// // "key": "emailKey", +// // "type": "Email", +// // "label": "Email Label", +// // "placeholder": "Enter your email", +// // "required": true, +// // "value": "example@example.com" +// // } +// // ] +// // }` + +// // var form Form + +// // // Decode the form JSON +// // if err := json.Unmarshal([]byte(formJSON), &form); err != nil { +// // fmt.Println("Error decoding form:", err) +// // return +// // } + +// // // Print decoded form fields +// // fmt.Println("Form Title:", form.Title) +// // for i, field := range form.Fields { +// // fmt.Printf("Field %d: %T\n", i+1, field) +// // } +// // } diff --git a/libcore/go.mod b/libcore/go.mod new file mode 100644 index 0000000..0e69779 --- /dev/null +++ b/libcore/go.mod @@ -0,0 +1,162 @@ +module github.com/hiddify/hiddify-core + +go 1.22.0 + +toolchain go1.22.3 + +require ( + github.com/bepass-org/warp-plus v1.2.4 + github.com/fatih/color v1.16.0 // indirect + github.com/hiddify/hiddify-app-demo-extension v0.0.0-20241001070003-26039f960ad6 + github.com/hiddify/hiddify-ip-scanner-extension v0.0.0-20241001070353-7ffd688b96b2 + github.com/improbable-eng/grpc-web v0.15.0 + github.com/jellydator/validation v1.1.0 + github.com/kardianos/service v1.2.2 + github.com/sagernet/gomobile v0.1.4 + github.com/sagernet/sing v0.4.3 + github.com/sagernet/sing-box v1.8.9 + github.com/sagernet/sing-dns v0.2.3 + github.com/spf13/cobra v1.8.0 + github.com/xmdhs/clash2singbox v0.0.2 + golang.org/x/sys v0.25.0 + google.golang.org/grpc v1.66.0 + google.golang.org/protobuf v1.34.2 + gopkg.in/yaml.v3 v3.0.1 +) + +require ( + github.com/Yiwen-Chan/tinydb v0.0.0-20230129042445-3321642f0674 + github.com/syndtr/goleveldb v1.0.1-0.20200815110645-5c35d600f0ca + github.com/tendermint/tm-db v0.6.7 +) + +require ( + github.com/DataDog/zstd v1.4.1 // indirect + github.com/cenkalti/backoff/v4 v4.1.1 // indirect + github.com/cespare/xxhash v1.1.0 // indirect + github.com/cosmos/gorocksdb v1.2.0 // indirect + github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f // indirect + github.com/dgraph-io/badger/v2 v2.2007.2 // indirect + github.com/dgraph-io/ristretto v0.0.3-0.20200630154024-f66de99634de // indirect + github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2 // indirect + github.com/dustin/go-humanize v1.0.0 // indirect + github.com/golang/protobuf v1.5.4 // indirect + github.com/golang/snappy v0.0.1 // indirect + github.com/jmhodges/levigo v1.0.0 // indirect + github.com/mattn/go-colorable v0.1.13 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/metacubex/tfo-go v0.0.0-20240821025650-e9be0afd5e7d // indirect + github.com/pkg/errors v0.9.1 // indirect + github.com/rodaine/table v1.1.1 // indirect + github.com/rs/cors v1.7.0 // indirect + go.etcd.io/bbolt v1.3.6 // indirect + gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect + nhooyr.io/websocket v1.8.6 // indirect +) + +require ( + berty.tech/go-libtor v1.0.385 // indirect + github.com/ajg/form v1.5.1 // indirect + github.com/andybalholm/brotli v1.1.0 // indirect + github.com/caddyserver/certmagic v0.20.0 // indirect + github.com/cloudflare/circl v1.4.0 // indirect + github.com/cretz/bine v0.2.0 // indirect + github.com/dgryski/go-metro v0.0.0-20211217172704-adc40b04c140 // indirect + github.com/francoispqt/gojay v1.2.13 // indirect + github.com/fsnotify/fsnotify v1.7.0 // indirect + github.com/gaukas/godicttls v0.0.4 // indirect + github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344 // indirect + github.com/go-chi/chi/v5 v5.0.12 // indirect + github.com/go-chi/cors v1.2.1 // indirect + github.com/go-chi/render v1.0.3 // indirect + github.com/go-ole/go-ole v1.3.0 // indirect + github.com/go-task/slim-sprig/v3 v3.0.0 // indirect + github.com/gobwas/httphead v0.1.0 // indirect + github.com/gobwas/pool v0.2.1 // indirect + github.com/gofrs/uuid/v5 v5.2.0 // indirect + github.com/google/btree v1.1.2 // indirect + github.com/google/pprof v0.0.0-20240528025155-186aa0362fba // indirect + github.com/gorilla/websocket v1.5.3 // indirect + github.com/hashicorp/yamux v0.1.1 // indirect + github.com/hiddify/ray2sing v0.0.0-20240804185422-f340989b59a0 + github.com/imkira/go-observer/v2 v2.0.0-20230629064422-8e0b61f11f1b // indirect + github.com/inconshreveable/mousetrap v1.1.0 // indirect + github.com/insomniacslk/dhcp v0.0.0-20231206064809-8c70d406f6d2 // indirect + github.com/josharian/native v1.1.0 // indirect + github.com/klauspost/compress v1.17.8 // indirect + github.com/klauspost/cpuid/v2 v2.2.7 // indirect + github.com/libdns/alidns v1.0.3 // indirect + github.com/libdns/cloudflare v0.1.1 // indirect + github.com/libdns/libdns v0.2.2 // indirect + github.com/logrusorgru/aurora v2.0.3+incompatible // indirect + github.com/mholt/acmez v1.2.0 // indirect + github.com/miekg/dns v1.1.62 // indirect + github.com/onsi/ginkgo/v2 v2.19.0 // indirect + github.com/ooni/go-libtor v1.1.8 // indirect + github.com/oschwald/maxminddb-golang v1.12.0 // indirect + github.com/pelletier/go-toml v1.9.5 // indirect + github.com/pierrec/lz4/v4 v4.1.14 // indirect + github.com/pion/dtls/v2 v2.2.7 // indirect + github.com/pion/logging v0.2.2 // indirect + github.com/pion/randutil v0.1.0 // indirect + github.com/pion/stun/v2 v2.0.0 // indirect + github.com/pion/transport/v2 v2.2.3 // indirect + github.com/pion/transport/v3 v3.0.1 // indirect + github.com/pion/turn/v3 v3.0.1 // indirect + github.com/pires/go-proxyproto v0.7.0 // indirect + github.com/quic-go/qpack v0.4.0 // indirect + github.com/quic-go/qtls-go1-20 v0.4.1 // indirect + github.com/quic-go/quic-go v0.46.0 // indirect + github.com/refraction-networking/utls v1.6.7 // indirect + github.com/riobard/go-bloom v0.0.0-20200614022211-cdc8013cb5b3 // indirect + github.com/sagernet/bbolt v0.0.0-20231014093535-ea5cb2fe9f0a // indirect + github.com/sagernet/cloudflare-tls v0.0.0-20231208171750-a4483c1b7cd1 // indirect + github.com/sagernet/gvisor v0.0.0-20240428053021-e691de28565f // indirect + github.com/sagernet/netlink v0.0.0-20240523065131-45e60152f9ba // indirect + github.com/sagernet/quic-go v0.47.0-beta.2 // indirect + github.com/sagernet/reality v0.0.0-20230406110435-ee17307e7691 // indirect + github.com/sagernet/sing-mux v0.2.0 // indirect + github.com/sagernet/sing-quic v0.2.2 // indirect + github.com/sagernet/sing-shadowsocks v0.2.7 // indirect + github.com/sagernet/sing-shadowsocks2 v0.2.0 // indirect + github.com/sagernet/sing-shadowtls v0.1.4 // indirect + github.com/sagernet/sing-tun v0.3.3 // indirect + github.com/sagernet/sing-vmess v0.1.12 // indirect + github.com/sagernet/smux v0.0.0-20231208180855-7041f6ea79e7 // indirect + github.com/sagernet/utls v1.5.4 // indirect + github.com/sagernet/wireguard-go v0.0.0-20231215174105-89dec3b2f3e8 // indirect + github.com/sagernet/ws v0.0.0-20231204124109-acfe8907c854 // indirect + github.com/seiflotfy/cuckoofilter v0.0.0-20240715131351-a2f2c23f1771 // indirect + github.com/spf13/pflag v1.0.5 // indirect + github.com/u-root/uio v0.0.0-20230220225925-ffce2a382923 // indirect + github.com/v2fly/ss-bloomring v0.0.0-20210312155135-28617310f63e // indirect + github.com/vishvananda/netns v0.0.4 // indirect + github.com/xtls/reality v0.0.0-20240712055506-48f0b2d5ed6d // indirect + github.com/xtls/xray-core v1.8.21 // indirect + github.com/zeebo/blake3 v0.2.3 // indirect + go.uber.org/mock v0.4.0 // indirect + go.uber.org/multierr v1.11.0 // indirect + go.uber.org/zap v1.27.0 // indirect + go4.org/netipx v0.0.0-20231129151722-fdeea329fbba // indirect + golang.org/x/crypto v0.26.0 // indirect + golang.org/x/exp v0.0.0-20240531132922-fd00a4e0eefc // indirect + golang.org/x/mod v0.18.0 // indirect + golang.org/x/net v0.28.0 + golang.org/x/sync v0.8.0 // indirect + golang.org/x/text v0.18.0 // indirect + golang.org/x/time v0.5.0 // indirect + golang.org/x/tools v0.22.0 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20240604185151-ef581f913117 // indirect + gopkg.in/yaml.v2 v2.4.0 // indirect + lukechampine.com/blake3 v1.3.0 // indirect +) + +replace github.com/sagernet/sing-box => github.com/hiddify/hiddify-sing-box v1.8.9-0.20240928213625-7b79bf0c814d + +replace github.com/xtls/xray-core => github.com/hiddify/xray-core v0.0.0-20240902024714-0fcb0895bb4b + +replace github.com/sagernet/wireguard-go => github.com/hiddify/wireguard-go v0.0.0-20240727191222-383c1da14ff1 + +replace github.com/bepass-org/warp-plus => github.com/hiddify/warp-plus v0.0.0-20240717223357-4f3122e0d11d + +replace github.com/hiddify/ray2sing => github.com/hiddify/ray2sing v0.0.0-20240928221833-190b549d5222 diff --git a/libcore/go.sum b/libcore/go.sum new file mode 100644 index 0000000..3f2f260 --- /dev/null +++ b/libcore/go.sum @@ -0,0 +1,976 @@ +berty.tech/go-libtor v1.0.385 h1:RWK94C3hZj6Z2GdvePpHJLnWYobFr3bY/OdUJ5aoEXw= +berty.tech/go-libtor v1.0.385/go.mod h1:9swOOQVb+kmvuAlsgWUK/4c52pm69AdbJsxLzk+fJEw= +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.31.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.37.0/go.mod h1:TS1dMSSfndXH133OKGwekG838Om/cQT0BUHV3HcBgoo= +dmitri.shuralyov.com/app/changes v0.0.0-20180602232624-0a106ad413e3/go.mod h1:Yl+fi1br7+Rr3LqpNJf1/uxUdtRUV+Tnj0o93V2B9MU= +dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= +dmitri.shuralyov.com/html/belt v0.0.0-20180602232347-f7d459c86be0/go.mod h1:JLBrvjyP0v+ecvNYvCpyZgu5/xkfAUhi6wJj28eUfSU= +dmitri.shuralyov.com/service/change v0.0.0-20181023043359-a85b471d5412/go.mod h1:a1inKt/atXimZ4Mv927x+r7UpyzRUf4emIoiiSC2TN4= +dmitri.shuralyov.com/state v0.0.0-20180228185332-28bcc343414c/go.mod h1:0PRwlb0D6DFvNNtx+9ybjezNCa8XF0xaYcETyp6rHWU= +git.apache.org/thrift.git v0.0.0-20180902110319-2566ecd5d999/go.mod h1:fPE2ZNJGynbRyZ4dJvy6G277gSllfV2HJqblrnkyeyg= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= +github.com/DataDog/zstd v1.4.1 h1:3oxKN3wbHibqx897utPC2LTQU4J+IHWWJO+glkAkpFM= +github.com/DataDog/zstd v1.4.1/go.mod h1:1jcaCB/ufaK+sKp1NBhlGmpz41jOoPQ35bpF36t7BBo= +github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0= +github.com/OmarTariq612/goech v0.0.0-20240405204721-8e2e1dafd3a0 h1:Wo41lDOevRJSGpevP+8Pk5bANX7fJacO2w04aqLiC5I= +github.com/OmarTariq612/goech v0.0.0-20240405204721-8e2e1dafd3a0/go.mod h1:FVGavL/QEBQDcBpr3fAojoK17xX5k9bicBphrOpP7uM= +github.com/OneOfOne/xxhash v1.2.2 h1:KMrpdQIwFcEqXDklaen+P1axHaj9BSKzvpUUfnHldSE= +github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= +github.com/Shopify/sarama v1.19.0/go.mod h1:FVkBWblsNy7DGZRfXLU0O9RCGt5g3g3yEuWXgklEdEo= +github.com/Shopify/toxiproxy v2.1.4+incompatible/go.mod h1:OXgGpZ6Cli1/URJOF1DMxUHB2q5Ap20/P/eIdh4G0pI= +github.com/VividCortex/gohistogram v1.0.0/go.mod h1:Pf5mBqqDxYaXu3hDrrU+w6nw50o/4+TcAqDqk/vUH7g= +github.com/Yiwen-Chan/tinydb v0.0.0-20230129042445-3321642f0674 h1:Sf029Pn6NCxD0TP/AeEO87epoaNeCtUFrCHKndEc3G0= +github.com/Yiwen-Chan/tinydb v0.0.0-20230129042445-3321642f0674/go.mod h1:FKpvt4bXlMiJn5DipBosCuM1tH27p0z9RI3sHRMH+40= +github.com/afex/hystrix-go v0.0.0-20180502004556-fa1af6a1f4f5/go.mod h1:SkGFH1ia65gfNATL8TAiHDNxPzPdmEL5uirI2Uyuz6c= +github.com/ajg/form v1.5.1 h1:t9c7v8JUKu/XxOGBU0yjNpaMloxGEJhUkqFRq0ibGeU= +github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY= +github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho= +github.com/andybalholm/brotli v1.1.0 h1:eLKJA0d02Lf0mVpIDgYnqXcUn0GqVmEFny3VuID1U3M= +github.com/andybalholm/brotli v1.1.0/go.mod h1:sms7XGricyQI9K10gOSf56VKKWS4oLer58Q+mhRPtnY= +github.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239/go.mod h1:2FmKhYUyUczH0OGQWaF5ceTx0UBShxjsH6f8oGKYe2c= +github.com/apache/thrift v0.12.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ= +github.com/apache/thrift v0.13.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ= +github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= +github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= +github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= +github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= +github.com/aryann/difflib v0.0.0-20170710044230-e206f873d14a/go.mod h1:DAHtR1m6lCRdSC2Tm3DSWRPvIPr6xNKyeHdqDQSQT+A= +github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d h1:Byv0BzEl3/e6D5CLfI0j/7hiIEtvGVFPCZ7Ei2oq8iQ= +github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw= +github.com/aws/aws-lambda-go v1.13.3/go.mod h1:4UKl9IzQMoD+QF79YdCuzCwp8VbmG4VAQwij/eHl5CU= +github.com/aws/aws-sdk-go v1.27.0/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= +github.com/aws/aws-sdk-go-v2 v0.18.0/go.mod h1:JWVYvqSMppoMJC0x5wdwiImzgXTI9FuZwxzkQq9wy+g= +github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= +github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= +github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= +github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= +github.com/bradfitz/go-smtpd v0.0.0-20170404230938-deb6d6237625/go.mod h1:HYsPBTaaSFSlLx/70C2HPIMNZpVV8+vt/A+FMnYP11g= +github.com/buger/jsonparser v0.0.0-20181115193947-bf1c66bbce23/go.mod h1:bbYlZJ7hK1yFx9hf58LP0zeX7UjIGs20ufpu3evjr+s= +github.com/caddyserver/certmagic v0.20.0 h1:bTw7LcEZAh9ucYCRXyCpIrSAGplplI0vGYJ4BpCQ/Fc= +github.com/caddyserver/certmagic v0.20.0/go.mod h1:N4sXgpICQUskEWpj7zVzvWD41p3NYacrNoZYiRM2jTg= +github.com/casbin/casbin/v2 v2.1.2/go.mod h1:YcPU1XXisHhLzuxH9coDNf2FbKpjGlbCg3n9yuLkIJQ= +github.com/cenkalti/backoff v2.2.1+incompatible/go.mod h1:90ReRw6GdpyfrHakVjL/QHaoyV4aDUVVkXQJJJ3NXXM= +github.com/cenkalti/backoff/v4 v4.1.1 h1:G2HAfAmvm/GcKan2oOQpBXOd2tT2G57ZnZGWa1PxPBQ= +github.com/cenkalti/backoff/v4 v4.1.1/go.mod h1:scbssz8iZGpm3xbr14ovlUdkxfGXNInqkPWOWmG2CLw= +github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/cespare/xxhash v1.1.0 h1:a6HrQnmkObjyL+Gs60czilIUGqrzKutQD6XZog3p+ko= +github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= +github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/clbanning/x2j v0.0.0-20191024224557-825249438eec/go.mod h1:jMjuTZXRI4dUb/I5gc9Hdhagfvm9+RyrPryS/auMzxE= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cloudflare/circl v1.4.0 h1:BV7h5MgrktNzytKmWjpOtdYrf0lkkbF8YMlBGPhJQrY= +github.com/cloudflare/circl v1.4.0/go.mod h1:PDRU+oXvdD7KCtgKxW95M5Z8BpSCJXQORiZFnBQS5QU= +github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= +github.com/cockroachdb/datadriven v0.0.0-20190809214429-80d97fb3cbaa/go.mod h1:zn76sxSg3SzpJ0PPJaLDCu+Bu0Lg3sKTORVIj19EIF8= +github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd/go.mod h1:sE/e/2PUdi/liOCUjSTXgM1o87ZssimdTWN964YiIeI= +github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= +github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= +github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= +github.com/coreos/go-systemd v0.0.0-20180511133405-39ca1b05acc7/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= +github.com/coreos/go-systemd v0.0.0-20181012123002-c6f51f82210d/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= +github.com/coreos/pkg v0.0.0-20160727233714-3ac0863d7acf/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= +github.com/cosmos/gorocksdb v1.2.0 h1:d0l3jJG8M4hBouIZq0mDUHZ+zjOx044J3nGRskwTb4Y= +github.com/cosmos/gorocksdb v1.2.0/go.mod h1:aaKvKItm514hKfNJpUJXnnOWeBnk2GL4+Qw9NHizILw= +github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE= +github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= +github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= +github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY= +github.com/cretz/bine v0.1.0/go.mod h1:6PF6fWAvYtwjRGkAuDEJeWNOv3a2hUouSP/yRYXmvHw= +github.com/cretz/bine v0.2.0 h1:8GiDRGlTgz+o8H9DSnsl+5MeBK4HsExxgl6WgzOCuZo= +github.com/cretz/bine v0.2.0/go.mod h1:WU4o9QR9wWp8AVKtTM1XD5vUHkEqnf2vVSo6dBqbetI= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f h1:U5y3Y5UE0w7amNe7Z5G/twsBW0KEalRQXZzf8ufSh9I= +github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f/go.mod h1:xH/i4TFMt8koVQZ6WFms69WAsDWr2XsYL3Hkl7jkoLE= +github.com/dgraph-io/badger/v2 v2.2007.2 h1:EjjK0KqwaFMlPin1ajhP943VPENHJdEz1KLIegjaI3k= +github.com/dgraph-io/badger/v2 v2.2007.2/go.mod h1:26P/7fbL4kUZVEVKLAKXkBXKOydDmM2p1e+NhhnBCAE= +github.com/dgraph-io/ristretto v0.0.3-0.20200630154024-f66de99634de h1:t0UHb5vdojIDUqktM6+xJAfScFBsVpXZmqC9dsgJmeA= +github.com/dgraph-io/ristretto v0.0.3-0.20200630154024-f66de99634de/go.mod h1:KPxhHT9ZxKefz+PCeOGsrHpl1qZ7i70dGTu2u+Ahh6E= +github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= +github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2 h1:tdlZCpZ/P9DhczCTSixgIKmwPv6+wP5DGjqLYw5SUiA= +github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= +github.com/dgryski/go-metro v0.0.0-20200812162917-85c65e2d0165/go.mod h1:c9O8+fpSOX1DM8cPNSkX/qsBWdkD4yd2dpciOWQjpBw= +github.com/dgryski/go-metro v0.0.0-20211217172704-adc40b04c140 h1:y7y0Oa6UawqTFPCDw9JG6pdKt4F9pAhHv0B7FMGaGD0= +github.com/dgryski/go-metro v0.0.0-20211217172704-adc40b04c140/go.mod h1:c9O8+fpSOX1DM8cPNSkX/qsBWdkD4yd2dpciOWQjpBw= +github.com/dustin/go-humanize v0.0.0-20171111073723-bb3d318650d4/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= +github.com/dustin/go-humanize v1.0.0 h1:VSnTsYCnlFHaM2/igO1h6X3HA71jcobQuxemgkq4zYo= +github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= +github.com/eapache/go-resiliency v1.1.0/go.mod h1:kFI+JgMyC7bLPUVY133qvEBtVayf5mFgVsvEsIPBvNs= +github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21/go.mod h1:+020luEh2TKB4/GOp8oxxtq0Daoen/Cii55CzbTV6DU= +github.com/eapache/queue v1.1.0/go.mod h1:6eCeP0CKFpHLu8blIFXhExK/dRa7WDZfr6jVFPTqq+I= +github.com/edsrzf/mmap-go v1.0.0/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M= +github.com/envoyproxy/go-control-plane v0.6.9/go.mod h1:SBwIajubJHhxtWwsL9s8ss4safvEdbitLhGGK48rN6g= +github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= +github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/facebookgo/ensure v0.0.0-20200202191622-63f1cf65ac4c h1:8ISkoahWXwZR41ois5lSJBSVw4D0OV19Ht/JSTzvSv0= +github.com/facebookgo/ensure v0.0.0-20200202191622-63f1cf65ac4c/go.mod h1:Yg+htXGokKKdzcwhuNDwVvN+uBxDGXJ7G/VN1d8fa64= +github.com/facebookgo/stack v0.0.0-20160209184415-751773369052 h1:JWuenKqqX8nojtoVVWjGfOF9635RETekkoH6Cc9SX0A= +github.com/facebookgo/stack v0.0.0-20160209184415-751773369052/go.mod h1:UbMTZqLaRiH3MsBH8va0n7s1pQYcu3uTb8G4tygF4Zg= +github.com/facebookgo/subset v0.0.0-20200203212716-c811ad88dec4 h1:7HZCaLC5+BZpmbhCOZJ293Lz68O7PYrF2EzeiFMwCLk= +github.com/facebookgo/subset v0.0.0-20200203212716-c811ad88dec4/go.mod h1:5tD+neXqOorC30/tWg0LCSkrqj/AR6gu8yY8/fpw1q0= +github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= +github.com/fatih/color v1.16.0 h1:zmkK9Ngbjj+K0yRhTVONQh1p/HknKYSlNT+vZCzyokM= +github.com/fatih/color v1.16.0/go.mod h1:fL2Sau1YI5c0pdGEVCbKQbLXB6edEj1ZgiY4NijnWvE= +github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:xEzjJPgXI435gkrCt3MPfRiAkVrwSbHsst4LCFVfpJc= +github.com/francoispqt/gojay v1.2.13 h1:d2m3sFjloqoIUQU3TsHBgj6qg/BVGlTBeHDUmyJnXKk= +github.com/francoispqt/gojay v1.2.13/go.mod h1:ehT5mTG4ua4581f1++1WLG0vPdaA9HaiDsoyrBGkyDY= +github.com/franela/goblin v0.0.0-20200105215937-c9ffbefa60db/go.mod h1:7dvUGVsVBjqR7JHJk0brhHOZYGmfBYOrK0ZhYMEtBr4= +github.com/franela/goreq v0.0.0-20171204163338-bcd34c9993f8/go.mod h1:ZhphrRTfi2rbfLwlschooIH4+wKKDR4Pdxhh+TRoA20= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= +github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= +github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= +github.com/gaukas/godicttls v0.0.4 h1:NlRaXb3J6hAnTmWdsEKb9bcSBD6BvcIjdGdeb0zfXbk= +github.com/gaukas/godicttls v0.0.4/go.mod h1:l6EenT4TLWgTdwslVb4sEMOCf7Bv0JAK67deKr9/NCI= +github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= +github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344 h1:Arcl6UOIS/kgO2nW3A65HN+7CMjSDP/gofXL4CZt1V4= +github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= +github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= +github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= +github.com/gin-gonic/gin v1.6.3 h1:ahKqKTFpO5KTPHxWZjEdPScmYaGtLo8Y4DMHoEsnp14= +github.com/gin-gonic/gin v1.6.3/go.mod h1:75u5sXoLsGZoRN5Sgbi1eraJ4GU3++wFwWzhwvtwp4M= +github.com/gliderlabs/ssh v0.1.1/go.mod h1:U7qILu1NlMHj9FlMhZLlkCdDnU1DBEAqr0aevW3Awn0= +github.com/go-chi/chi/v5 v5.0.12 h1:9euLV5sTrTNTRUU9POmDUvfxyj6LAABLUcEWO+JJb4s= +github.com/go-chi/chi/v5 v5.0.12/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8= +github.com/go-chi/cors v1.2.1 h1:xEC8UT3Rlp2QuWNEr4Fs/c2EAGVKBwy/1vHx3bppil4= +github.com/go-chi/cors v1.2.1/go.mod h1:sSbTewc+6wYHBBCW7ytsFSn836hqM7JxpglAy2Vzc58= +github.com/go-chi/render v1.0.3 h1:AsXqd2a1/INaIfUSKq3G5uA8weYx20FOsM7uSoCyyt4= +github.com/go-chi/render v1.0.3/go.mod h1:/gr3hVkmYR0YlEy3LxCuVRFzEu9Ruok+gFqbIofjao0= +github.com/go-errors/errors v1.0.1/go.mod h1:f4zRHt4oKfwPJE5k8C9vpYG+aDHdBFUsgrm6/TyX73Q= +github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= +github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-kit/kit v0.10.0/go.mod h1:xUsJbQ/Fp4kEt7AFgCuvyX4a71u8h9jB8tj/ORgOZ7o= +github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= +github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= +github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A= +github.com/go-logr/logr v1.4.1 h1:pKouT5E8xu9zeFC39JXRDukb6JFQPXM5p5I91188VAQ= +github.com/go-logr/logr v1.4.1/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE= +github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78= +github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= +github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q= +github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8= +github.com/go-playground/universal-translator v0.17.0 h1:icxd5fm+REJzpZx7ZfpaD876Lmtgy7VtROAbHHXk8no= +github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA= +github.com/go-playground/validator/v10 v10.2.0 h1:KgJ0snyC2R9VXYN2rneOtQcw5aHQB1Vv0sFl1UcHBOY= +github.com/go-playground/validator/v10 v10.2.0/go.mod h1:uOYAAleCW8F/7oMFd6aG0GOhaH6EGOAJShg8Id5JGkI= +github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= +github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= +github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI= +github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= +github.com/gobwas/httphead v0.0.0-20180130184737-2c6c146eadee/go.mod h1:L0fX3K22YWvt/FAX9NnzrNzcI4wNYi9Yku4O0LKYflo= +github.com/gobwas/httphead v0.1.0 h1:exrUm0f4YX0L7EBwZHuCF4GDp8aJfVeBrlLQrs6NqWU= +github.com/gobwas/httphead v0.1.0/go.mod h1:O/RXo79gxV8G+RqlR/otEwx4Q36zl9rqC5u12GKvMCM= +github.com/gobwas/pool v0.2.0/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw= +github.com/gobwas/pool v0.2.1 h1:xfeeEhW7pwmX8nuLVlqbzVc7udMDrwetjEv+TZIz1og= +github.com/gobwas/pool v0.2.1/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw= +github.com/gobwas/ws v1.0.2 h1:CoAavW/wd/kulfZmSIBt6p24n4j7tHgNVCjsfHVNUbo= +github.com/gobwas/ws v1.0.2/go.mod h1:szmBTxLgaFppYjEmNtny/v3w89xOydFnnZMcgRRu/EM= +github.com/gofrs/uuid/v5 v5.2.0 h1:qw1GMx6/y8vhVsx626ImfKMuS5CvJmhIKKtuyvfajMM= +github.com/gofrs/uuid/v5 v5.2.0/go.mod h1:CDOjlDMVAtN56jqyRUZh58JT31Tiw7/oQyEXZV+9bD8= +github.com/gogo/googleapis v1.1.0/go.mod h1:gf4bu3Q80BeJ6H1S1vYPm8/ELATdvryBaNFGgqEef3s= +github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= +github.com/gogo/protobuf v1.2.0/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= +github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/groupcache v0.0.0-20160516000752-02826c3e7903/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/lint v0.0.0-20180702182130-06c8688daad7/go.mod h1:tluoj9z5200jBnyusfRPU2LqT6J+DAorxEvtC7LHB+E= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/mock v1.7.0-rc.1 h1:YojYx61/OLFsiv6Rw1Z96LpldJIy31o+UHmwAUMJ6/U= +github.com/golang/mock v1.7.0-rc.1/go.mod h1:s42URUywIqd+OcERslBJvOjepvNymP31m3q8d/GkuRs= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/golang/protobuf v1.3.5/go.mod h1:6O5/vntMXwX2lRkT1hjjk0nAC1IDOTvTlVgjlRvqsdk= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= +github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= +github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/golang/snappy v0.0.1 h1:Qgr9rKW7uDUkrbSmQeiDsGa8SjGyCOGtuasMWwvp2P4= +github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= +github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= +github.com/google/btree v1.1.2 h1:xf4v41cLI2Z6FxbKm+8Bu+m8ifhj15JuZ9sa0jZCMUU= +github.com/google/btree v1.1.2/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/go-github v17.0.0+incompatible/go.mod h1:zLgOLi98H3fifZn+44m+umXrS52loVEgC2AApnigrVQ= +github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= +github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= +github.com/google/pprof v0.0.0-20240528025155-186aa0362fba h1:ql1qNgCyOB7iAEk8JTNM+zJrgIbnyCKX/wdlyPufP5g= +github.com/google/pprof v0.0.0-20240528025155-186aa0362fba/go.mod h1:K1liHPHnj73Fdn/EKuT8nrFqBihUSKXoLYU0BuatOYo= +github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= +github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/googleapis/gax-go v2.0.0+incompatible/go.mod h1:SFVmujtThgffbyetf+mdk2eWhX2bMyUtNHzFKcPA9HY= +github.com/googleapis/gax-go/v2 v2.0.3/go.mod h1:LLvjysVCY1JZeum8Z6l8qUty8fiNwE08qbEPm1M08qg= +github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= +github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg= +github.com/gorilla/mux v1.6.2/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= +github.com/gorilla/mux v1.7.3/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= +github.com/gorilla/websocket v0.0.0-20170926233335-4201258b820c/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= +github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= +github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA= +github.com/grpc-ecosystem/go-grpc-middleware v1.0.1-0.20190118093823-f849b5445de4/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= +github.com/grpc-ecosystem/go-grpc-middleware v1.2.2/go.mod h1:EaizFBKfUKtMIF5iaDEhniwNedqGo9FuLFzppDr3uwI= +github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= +github.com/grpc-ecosystem/grpc-gateway v1.5.0/go.mod h1:RSKVYQBd5MCa4OVpNdGskqpgL2+G+NZTnrVHpWWfpdw= +github.com/grpc-ecosystem/grpc-gateway v1.9.5/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= +github.com/hashicorp/consul/api v1.3.0/go.mod h1:MmDNSzIMUjNpY/mQ398R4bk2FnqQLoPndWW5VkKPlCE= +github.com/hashicorp/consul/sdk v0.3.0/go.mod h1:VKf9jXwCTEY1QZP2MOLRhb5i/I/ssyNV1vwHyQBF0x8= +github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= +github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= +github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM= +github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= +github.com/hashicorp/go-rootcerts v1.0.0/go.mod h1:K6zTfqpRlCUIjkwsN4Z+hiSfzSTQa6eBIzfwKfwNnHU= +github.com/hashicorp/go-sockaddr v1.0.0/go.mod h1:7Xibr9yA9JjQq1JpNB2Vw7kxv8xerXegt+ozgdvDeDU= +github.com/hashicorp/go-syslog v1.0.0/go.mod h1:qPfqrKkXGihmCqbJM2mZgkZGvKG1dFdvsLplgctolz4= +github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= +github.com/hashicorp/go-uuid v1.0.1/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= +github.com/hashicorp/go-version v1.2.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= +github.com/hashicorp/go.net v0.0.1/go.mod h1:hjKkEWcCURg++eb33jQU7oqQcI9XDCnUzHA0oac0k90= +github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= +github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64= +github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ= +github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2pPBoIllUwCN7I= +github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc= +github.com/hashicorp/yamux v0.1.1 h1:yrQxtgseBDrq9Y652vSRDvsKCJKOUD+GzTS4Y0Y8pvE= +github.com/hashicorp/yamux v0.1.1/go.mod h1:CtWFDAQgb7dxtzFs4tWbplKIe2jSi3+5vKbgIO0SLnQ= +github.com/hiddify/hiddify-app-demo-extension v0.0.0-20241001070003-26039f960ad6 h1:ZErxaLRV5iWCBAR8qsyoNemEKntE4WSvK00Ts4zbS84= +github.com/hiddify/hiddify-app-demo-extension v0.0.0-20241001070003-26039f960ad6/go.mod h1:1F56GeIkSjUJF0VP/zPS9rJhVc97TjEQsDTFhmr9Ddc= +github.com/hiddify/hiddify-ip-scanner-extension v0.0.0-20241001070353-7ffd688b96b2 h1:cEzfvap7MfInrl15PWkt7761D/hc7JYVwFLIek3CGm8= +github.com/hiddify/hiddify-ip-scanner-extension v0.0.0-20241001070353-7ffd688b96b2/go.mod h1:/jZoGToOSqviabjNGrwRA5UsiO6EggHsRDaMK3sCHw8= +github.com/hiddify/hiddify-sing-box v1.8.9-0.20240928213625-7b79bf0c814d h1:+jTGlmOl+Kt3JEU1pt5yIItpi6nKKqUIUf76jkONHgQ= +github.com/hiddify/hiddify-sing-box v1.8.9-0.20240928213625-7b79bf0c814d/go.mod h1:2Cozqb5uVY/y0c/HWZ57CfE6fZwjmik/J3tWynsjjDA= +github.com/hiddify/ray2sing v0.0.0-20240928221833-190b549d5222 h1:+MFxFxoWCA44WhqIixqL/Zkt4DwnqhQvafS0Dm4+dKM= +github.com/hiddify/ray2sing v0.0.0-20240928221833-190b549d5222/go.mod h1:cFEg1b0eBgL9kBgIPAD71lHO1Q5g20PZL4dUGhQpAO8= +github.com/hiddify/warp-plus v0.0.0-20240717223357-4f3122e0d11d h1:vRGKh9ou+/vQGfVYa8MczhbIVjHxlP52OWwrDWO77RA= +github.com/hiddify/warp-plus v0.0.0-20240717223357-4f3122e0d11d/go.mod h1:uSRUbr1CcvFrEV69FTvuJFwpzEmwO8N4knb6+Zq3Ys4= +github.com/hiddify/wireguard-go v0.0.0-20240727191222-383c1da14ff1 h1:xdbHlZtzs+jijAxy85qal835GglwmjohA/srHT8gm9s= +github.com/hiddify/wireguard-go v0.0.0-20240727191222-383c1da14ff1/go.mod h1:K4J7/npM+VAMUeUmTa2JaA02JmyheP0GpRBOUvn3ecc= +github.com/hiddify/xray-core v0.0.0-20240902024714-0fcb0895bb4b h1:fF9wb8XnL4dk/suRK1cOKPN1x1BG3F5iHN3Aq2mrKaE= +github.com/hiddify/xray-core v0.0.0-20240902024714-0fcb0895bb4b/go.mod h1:kYMVgEAXeeoD9I08aS15jLRv4RF88vc1uf8xIjlnskU= +github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/hudl/fargo v1.3.0/go.mod h1:y3CKSmjA+wD2gak7sUSXTAoopbhU08POFhmITJgmKTg= +github.com/imkira/go-observer/v2 v2.0.0-20230629064422-8e0b61f11f1b h1:1+115FqGoS8p6Iry9AYmrcWDvSveH0F7P2nX1LU00qg= +github.com/imkira/go-observer/v2 v2.0.0-20230629064422-8e0b61f11f1b/go.mod h1:XCscqBi1KKh7GcVDDAdkT/Cf6WDjnDAA1XM3nwmA0Ag= +github.com/improbable-eng/grpc-web v0.15.0 h1:BN+7z6uNXZ1tQGcNAuaU1YjsLTApzkjt2tzCixLaUPQ= +github.com/improbable-eng/grpc-web v0.15.0/go.mod h1:1sy9HKV4Jt9aEs9JSnkWlRJPuPtwNr0l57L4f878wP8= +github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= +github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= +github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= +github.com/influxdata/influxdb1-client v0.0.0-20191209144304-8bf82d3c094d/go.mod h1:qj24IKcXYK6Iy9ceXlo3Tc+vtHo9lIhSX5JddghvEPo= +github.com/insomniacslk/dhcp v0.0.0-20231206064809-8c70d406f6d2 h1:9K06NfxkBh25x56yVhWWlKFE8YpicaSfHwoV8SFbueA= +github.com/insomniacslk/dhcp v0.0.0-20231206064809-8c70d406f6d2/go.mod h1:3A9PQ1cunSDF/1rbTq99Ts4pVnycWg+vlPkfeD2NLFI= +github.com/jellevandenhooff/dkim v0.0.0-20150330215556-f50fe3d243e1/go.mod h1:E0B/fFc00Y+Rasa88328GlI/XbtyysCtTHZS8h7IrBU= +github.com/jellydator/validation v1.1.0 h1:TBkx56y6dd0By2AhtStRdTIhDjtcuoSE9w6G6z7wQ4o= +github.com/jellydator/validation v1.1.0/go.mod h1:AaCjfkQ4Ykdcb+YCwqCtaI3wDsf2UAGhJ06lJs0VgOw= +github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= +github.com/jmhodges/levigo v1.0.0 h1:q5EC36kV79HWeTBWsod3mG11EgStG3qArTKcvlksN1U= +github.com/jmhodges/levigo v1.0.0/go.mod h1:Q6Qx+uH3RAqyK4rFQroq9RL7mdkABMcfhEI+nNuzMJQ= +github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo= +github.com/josharian/native v1.0.1-0.20221213033349-c1e37c09b531/go.mod h1:7X/raswPFr05uY3HiLlYeyQntB6OO7E/d2Cu7qoaN2w= +github.com/josharian/native v1.1.0 h1:uuaP0hAbW7Y4l0ZRQ6C9zfb7Mg1mbFKry/xzDAfmtLA= +github.com/josharian/native v1.1.0/go.mod h1:7X/raswPFr05uY3HiLlYeyQntB6OO7E/d2Cu7qoaN2w= +github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4= +github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= +github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/json-iterator/go v1.1.8/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= +github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= +github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= +github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM= +github.com/kardianos/service v1.2.2 h1:ZvePhAHfvo0A7Mftk/tEzqEZ7Q4lgnR8sGz4xu1YX60= +github.com/kardianos/service v1.2.2/go.mod h1:CIMRFEJVL+0DS1a3Nx06NaMn4Dz63Ng6O7dl0qH0zVM= +github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/klauspost/compress v1.10.3/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= +github.com/klauspost/compress v1.11.7/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= +github.com/klauspost/compress v1.17.8 h1:YcnTYrq7MikUT7k0Yb5eceMmALQPYBW/Xltxn0NAMnU= +github.com/klauspost/compress v1.17.8/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw= +github.com/klauspost/cpuid/v2 v2.0.12/go.mod h1:g2LTdtYhdyuGPqyWyv7qRAmj1WBqxuObKfj5c0PQa7c= +github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM= +github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws= +github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/pty v1.1.3/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y= +github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII= +github.com/libdns/alidns v1.0.3 h1:LFHuGnbseq5+HCeGa1aW8awyX/4M2psB9962fdD2+yQ= +github.com/libdns/alidns v1.0.3/go.mod h1:e18uAG6GanfRhcJj6/tps2rCMzQJaYVcGKT+ELjdjGE= +github.com/libdns/cloudflare v0.1.1 h1:FVPfWwP8zZCqj268LZjmkDleXlHPlFU9KC4OJ3yn054= +github.com/libdns/cloudflare v0.1.1/go.mod h1:9VK91idpOjg6v7/WbjkEW49bSCxj00ALesIFDhJ8PBU= +github.com/libdns/libdns v0.2.0/go.mod h1:yQCXzk1lEZmmCPa857bnk4TsOiqYasqpyOEeSObbb40= +github.com/libdns/libdns v0.2.2 h1:O6ws7bAfRPaBsgAYt8MDe2HcNBGC29hkZ9MX2eUSX3s= +github.com/libdns/libdns v0.2.2/go.mod h1:4Bj9+5CQiNMVGf87wjX4CY3HQJypUHRuLvlsfsZqLWQ= +github.com/lightstep/lightstep-tracer-common/golang/gogo v0.0.0-20190605223551-bc2310a04743/go.mod h1:qklhhLq1aX+mtWk9cPHPzaBjWImj5ULL6C7HFJtXQMM= +github.com/lightstep/lightstep-tracer-go v0.18.1/go.mod h1:jlF1pusYV4pidLvZ+XD0UBX0ZE6WURAspgAczcDHrL4= +github.com/logrusorgru/aurora v2.0.3+incompatible h1:tOpm7WcpBTn4fjmVfgpQq0EfczGlG91VSDkswnjF5A8= +github.com/logrusorgru/aurora v2.0.3+incompatible/go.mod h1:7rIyQOR62GCctdiQpZ/zOJlFyk6y+94wXzv6RNZgaR4= +github.com/lunixbochs/vtclean v1.0.0/go.mod h1:pHhQNgMf3btfWnGBVipUOjRYhoOsdGqdm/+2c2E2WMI= +github.com/lyft/protoc-gen-validate v0.0.13/go.mod h1:XbGvPuh87YZc5TdIa2/I4pLk0QoUACkjt2znoq26NVQ= +github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= +github.com/mailru/easyjson v0.0.0-20190312143242-1de009706dbe/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= +github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= +github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= +github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= +github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= +github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= +github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= +github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= +github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U= +github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= +github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= +github.com/metacubex/tfo-go v0.0.0-20240821025650-e9be0afd5e7d h1:j9LtzkYstLFoNvXW824QQeN7Y26uPL5249kzWKbzO9U= +github.com/metacubex/tfo-go v0.0.0-20240821025650-e9be0afd5e7d/go.mod h1:c7bVFM9f5+VzeZ/6Kg77T/jrg1Xp8QpqlSHvG/aXVts= +github.com/mholt/acmez v1.2.0 h1:1hhLxSgY5FvH5HCnGUuwbKY2VQVo8IU7rxXKSnZ7F30= +github.com/mholt/acmez v1.2.0/go.mod h1:VT9YwH1xgNX1kmYY89gY8xPJC84BFAisjo8Egigt4kE= +github.com/microcosm-cc/bluemonday v1.0.1/go.mod h1:hsXNsILzKxV+sX77C5b8FSuKF00vh2OMYv+xgHpAMF4= +github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg= +github.com/miekg/dns v1.1.62 h1:cN8OuEF1/x5Rq6Np+h1epln8OiyPWV+lROx9LxcGgIQ= +github.com/miekg/dns v1.1.62/go.mod h1:mvDlcItzm+br7MToIKqkglaGhlFMHJ9DTNNWONWXbNQ= +github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc= +github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= +github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= +github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= +github.com/mitchellh/gox v0.4.0/go.mod h1:Sd9lOJ0+aimLBi73mGofS1ycjY8lL3uZM3JPS42BGNg= +github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0QubkSMEySY= +github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= +github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/modern-go/reflect2 v1.0.1 h1:9f412s+6RmYXLWZSEzVVgPGK7C2PphHj5RJrvfx9AWI= +github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= +github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f h1:KUppIJq7/+SVif2QVs3tOP0zanoHgBEVAwHxUSIzRqU= +github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= +github.com/mwitkow/grpc-proxy v0.0.0-20181017164139-0f1106ef9c76/go.mod h1:x5OoJHDHqxHS801UIuhqGl6QdSAEJvtausosHSdazIo= +github.com/nats-io/jwt v0.3.0/go.mod h1:fRYCDE99xlTsqUzISS1Bi75UBJ6ljOJQOAAu5VglpSg= +github.com/nats-io/jwt v0.3.2/go.mod h1:/euKqTS1ZD+zzjYrY7pseZrTtWQSjujC7xjPc8wL6eU= +github.com/nats-io/nats-server/v2 v2.1.2/go.mod h1:Afk+wRZqkMQs/p45uXdrVLuab3gwv3Z8C4HTBu8GD/k= +github.com/nats-io/nats.go v1.9.1/go.mod h1:ZjDU1L/7fJ09jvUSRVBR2e7+RnLiiIQyqyzEE/Zbp4w= +github.com/nats-io/nkeys v0.1.0/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxziKVo7w= +github.com/nats-io/nkeys v0.1.3/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxziKVo7w= +github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c= +github.com/neelance/astrewrite v0.0.0-20160511093645-99348263ae86/go.mod h1:kHJEU3ofeGjhHklVoIGuVj85JJwZ6kWPaJwCIxgnFmo= +github.com/neelance/sourcemap v0.0.0-20151028013722-8c68805598ab/go.mod h1:Qr6/a/Q4r9LP1IltGz7tA7iOK1WonHEYhu1HRBA7ZiM= +github.com/nxadm/tail v1.4.4 h1:DQuhQpB1tVlglWS2hLQ5OV6B5r8aGxSrPc5Qo6uTN78= +github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= +github.com/oklog/oklog v0.3.2/go.mod h1:FCV+B7mhrz4o+ueLpx+KqkyXRGMWOYEvfiXtdGtbWGs= +github.com/oklog/run v1.0.0/go.mod h1:dlhp/R75TPv97u0XWUtDeV/lRKWPKSdTuV0TZvrmrQA= +github.com/olekukonko/tablewriter v0.0.0-20170122224234-a0225b3f23b5/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo= +github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= +github.com/onsi/ginkgo v1.14.0 h1:2mOpI4JVVPBN+WQRa0WKH2eXR+Ey+uK4n7Zj0aYpIQA= +github.com/onsi/ginkgo v1.14.0/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9klQyY= +github.com/onsi/ginkgo/v2 v2.19.0 h1:9Cnnf7UHo57Hy3k6/m5k3dRfGTMXGvxhHFvkDTCTpvA= +github.com/onsi/ginkgo/v2 v2.19.0/go.mod h1:rlwLi9PilAFJ8jCg9UE1QP6VBpd6/xj3SRC0d6TU0To= +github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= +github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= +github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= +github.com/onsi/gomega v1.33.1 h1:dsYjIxxSR755MDmKVsaFQTE22ChNBcuuTWgkUDSubOk= +github.com/onsi/gomega v1.33.1/go.mod h1:U4R44UsT+9eLIaYRB2a5qajjtQYn0hauxvRm16AVYg0= +github.com/ooni/go-libtor v1.1.8 h1:Wo3V3DVTxl5vZdxtQakqYP+DAHx7pPtAFSl1bnAa08w= +github.com/ooni/go-libtor v1.1.8/go.mod h1:q1YyLwRD9GeMyeerVvwc0vJ2YgwDLTp2bdVcrh/JXyI= +github.com/op/go-logging v0.0.0-20160315200505-970db520ece7/go.mod h1:HzydrMdWErDVzsI23lYNej1Htcns9BCg93Dk0bBINWk= +github.com/opentracing-contrib/go-observer v0.0.0-20170622124052-a52f23424492/go.mod h1:Ngi6UdF0k5OKD5t5wlmGhe/EDKPoUM3BXZSSfIuJbis= +github.com/opentracing/basictracer-go v1.0.0/go.mod h1:QfBfYuafItcjQuMwinw9GhYKwFXS9KnPs5lxoYwgW74= +github.com/opentracing/opentracing-go v1.0.2/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o= +github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o= +github.com/openzipkin-contrib/zipkin-go-opentracing v0.4.5/go.mod h1:/wsWhb9smxSfWAKL3wpBW7V8scJMt8N8gnaMCS9E/cA= +github.com/openzipkin/zipkin-go v0.1.1/go.mod h1:NtoC/o8u3JlF1lSlyPNswIbeQH9bJTmOf0Erfk+hxe8= +github.com/openzipkin/zipkin-go v0.1.6/go.mod h1:QgAqvLzwWbR/WpD4A3cGpPtJrZXNIiJc5AZX7/PBEpw= +github.com/openzipkin/zipkin-go v0.2.1/go.mod h1:NaW6tEwdmWMaCDZzg8sh+IBNOxHMPnhQw8ySjnjRyN4= +github.com/openzipkin/zipkin-go v0.2.2/go.mod h1:NaW6tEwdmWMaCDZzg8sh+IBNOxHMPnhQw8ySjnjRyN4= +github.com/oschwald/maxminddb-golang v1.12.0 h1:9FnTOD0YOhP7DGxGsq4glzpGy5+w7pq50AS6wALUMYs= +github.com/oschwald/maxminddb-golang v1.12.0/go.mod h1:q0Nob5lTCqyQ8WT6FYgS1L7PXKVVbgiymefNwIjPzgY= +github.com/pact-foundation/pact-go v1.0.4/go.mod h1:uExwJY4kCzNPcHRj+hCR/HBbOOIwwtUjcrb0b5/5kLM= +github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= +github.com/pborman/uuid v1.2.0/go.mod h1:X/NO0urCmaxf9VXbdlT7C2Yzkj2IKimNn4k+gtPdI/k= +github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= +github.com/pelletier/go-toml v1.9.5 h1:4yBQzkHv+7BHq2PQUZF3Mx0IYxG7LsP222s7Agd3ve8= +github.com/pelletier/go-toml v1.9.5/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= +github.com/performancecopilot/speed v3.0.0+incompatible/go.mod h1:/CLtqpZ5gBg1M9iaPbIdPPGyKcA8hKdoy6hAWba7Yac= +github.com/pierrec/lz4 v1.0.2-0.20190131084431-473cd7ce01a1/go.mod h1:3/3N9NVKO0jef7pBehbT1qWhCMrIgbYNnFAZCqQ5LRc= +github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY= +github.com/pierrec/lz4/v4 v4.1.14 h1:+fL8AQEZtz/ijeNnpduH0bROTu0O3NZAlPjQxGn8LwE= +github.com/pierrec/lz4/v4 v4.1.14/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4= +github.com/pion/dtls/v2 v2.2.7 h1:cSUBsETxepsCSFSxC3mc/aDo14qQLMSL+O6IjG28yV8= +github.com/pion/dtls/v2 v2.2.7/go.mod h1:8WiMkebSHFD0T+dIU+UeBaoV7kDhOW5oDCzZ7WZ/F9s= +github.com/pion/logging v0.2.2 h1:M9+AIj/+pxNsDfAT64+MAVgJO0rsyLnoJKCqf//DoeY= +github.com/pion/logging v0.2.2/go.mod h1:k0/tDVsRCX2Mb2ZEmTqNa7CWsQPc+YYCB7Q+5pahoms= +github.com/pion/randutil v0.1.0 h1:CFG1UdESneORglEsnimhUjf33Rwjubwj6xfiOXBa3mA= +github.com/pion/randutil v0.1.0/go.mod h1:XcJrSMMbbMRhASFVOlj/5hQial/Y8oH/HVo7TBZq+j8= +github.com/pion/stun/v2 v2.0.0 h1:A5+wXKLAypxQri59+tmQKVs7+l6mMM+3d+eER9ifRU0= +github.com/pion/stun/v2 v2.0.0/go.mod h1:22qRSh08fSEttYUmJZGlriq9+03jtVmXNODgLccj8GQ= +github.com/pion/transport/v2 v2.2.1/go.mod h1:cXXWavvCnFF6McHTft3DWS9iic2Mftcz1Aq29pGcU5g= +github.com/pion/transport/v2 v2.2.3 h1:XcOE3/x41HOSKbl1BfyY1TF1dERx7lVvlMCbXU7kfvA= +github.com/pion/transport/v2 v2.2.3/go.mod h1:q2U/tf9FEfnSBGSW6w5Qp5PFWRLRj3NjLhCCgpRK4p0= +github.com/pion/transport/v3 v3.0.1 h1:gDTlPJwROfSfz6QfSi0ZmeCSkFcnWWiiR9ES0ouANiM= +github.com/pion/transport/v3 v3.0.1/go.mod h1:UY7kiITrlMv7/IKgd5eTUcaahZx5oUN3l9SzK5f5xE0= +github.com/pion/turn/v3 v3.0.1 h1:wLi7BTQr6/Q20R0vt/lHbjv6y4GChFtC33nkYbasoT8= +github.com/pion/turn/v3 v3.0.1/go.mod h1:MrJDKgqryDyWy1/4NT9TWfXWGMC7UHT6pJIv1+gMeNE= +github.com/pires/go-proxyproto v0.7.0 h1:IukmRewDQFWC7kfnb66CSomk2q/seBuilHBYFwyq0Hs= +github.com/pires/go-proxyproto v0.7.0/go.mod h1:Vz/1JPY/OACxWGQNIRY2BeyDmpoaWmEP40O9LbuiFR4= +github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/profile v1.2.1/go.mod h1:hJw3o1OdXxsrSjjVksARp5W95eeEaEfptyVZyv6JUPA= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= +github.com/prometheus/client_golang v0.8.0/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= +github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= +github.com/prometheus/client_golang v0.9.3-0.20190127221311-3c4408c8b829/go.mod h1:p2iRAGwDERtqlqzRXnrOVns+ignqQo//hLXqYxZYVNs= +github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= +github.com/prometheus/client_golang v1.3.0/go.mod h1:hJaj2vgQTGQmVCsAACORcieXFeDPbaTKGT+JTgUa3og= +github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= +github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= +github.com/prometheus/client_model v0.0.0-20190115171406-56726106282f/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= +github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.1.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/common v0.0.0-20180801064454-c7de2306084e/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= +github.com/prometheus/common v0.2.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= +github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= +github.com/prometheus/common v0.7.0/go.mod h1:DjGbpBbp5NYNiECxcL/VnbXCCaQpKd3tt26CguLLsqA= +github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo= +github.com/prometheus/common v0.15.0/go.mod h1:U+gB1OBLb1lF3O42bTCL+FK18tX9Oar16Clt/msog/s= +github.com/prometheus/procfs v0.0.0-20180725123919-05ee40e3a273/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/prometheus/procfs v0.0.0-20190117184657-bf6a532e95b1/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= +github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A= +github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= +github.com/prometheus/procfs v0.3.0/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= +github.com/quic-go/qpack v0.4.0 h1:Cr9BXA1sQS2SmDUWjSofMPNKmvF6IiIfDRmgU0w1ZCo= +github.com/quic-go/qpack v0.4.0/go.mod h1:UZVnYIfi5GRk+zI9UMaCPsmZ2xKJP7XBUvVyT1Knj9A= +github.com/quic-go/qtls-go1-20 v0.4.1 h1:D33340mCNDAIKBqXuAvexTNMUByrYmFYVfKfDN5nfFs= +github.com/quic-go/qtls-go1-20 v0.4.1/go.mod h1:X9Nh97ZL80Z+bX/gUXMbipO6OxdiDi58b/fMC9mAL+k= +github.com/quic-go/quic-go v0.46.0 h1:uuwLClEEyk1DNvchH8uCByQVjo3yKL9opKulExNDs7Y= +github.com/quic-go/quic-go v0.46.0/go.mod h1:1dLehS7TIR64+vxGR70GDcatWTOtMX2PUtnKsjbTurI= +github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= +github.com/refraction-networking/utls v1.6.7 h1:zVJ7sP1dJx/WtVuITug3qYUq034cDq9B2MR1K67ULZM= +github.com/refraction-networking/utls v1.6.7/go.mod h1:BC3O4vQzye5hqpmDTWUqi4P5DDhzJfkV1tdqtawQIH0= +github.com/riobard/go-bloom v0.0.0-20200614022211-cdc8013cb5b3 h1:f/FNXud6gA3MNr8meMVVGxhp+QBTqY91tM8HjEuMjGg= +github.com/riobard/go-bloom v0.0.0-20200614022211-cdc8013cb5b3/go.mod h1:HgjTstvQsPGkxUsCd2KWxErBblirPizecHcpD3ffK+s= +github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY= +github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= +github.com/rodaine/table v1.1.1 h1:zBliy3b4Oj6JRmncse2Z85WmoQvDrXOYuy0JXCt8Qz8= +github.com/rodaine/table v1.1.1/go.mod h1:iqTRptjn+EVcrVBYtNMlJ2wrJZa3MpULUmcXFpfcziA= +github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= +github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= +github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= +github.com/rs/cors v1.7.0 h1:+88SsELBHx5r+hZ8TCkggzSstaWNbDvThkVK8H6f9ik= +github.com/rs/cors v1.7.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= +github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= +github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= +github.com/sagernet/bbolt v0.0.0-20231014093535-ea5cb2fe9f0a h1:+NkI2670SQpQWvkkD2QgdTuzQG263YZ+2emfpeyGqW0= +github.com/sagernet/bbolt v0.0.0-20231014093535-ea5cb2fe9f0a/go.mod h1:63s7jpZqcDAIpj8oI/1v4Izok+npJOHACFCU6+huCkM= +github.com/sagernet/cloudflare-tls v0.0.0-20231208171750-a4483c1b7cd1 h1:YbmpqPQEMdlk9oFSKYWRqVuu9qzNiOayIonKmv1gCXY= +github.com/sagernet/cloudflare-tls v0.0.0-20231208171750-a4483c1b7cd1/go.mod h1:J2yAxTFPDjrDPhuAi9aWFz2L3ox9it4qAluBBbN0H5k= +github.com/sagernet/gomobile v0.1.4 h1:WzX9ka+iHdupMgy2Vdich+OAt7TM8C2cZbIbzNjBrJY= +github.com/sagernet/gomobile v0.1.4/go.mod h1:Pqq2+ZVvs10U7xK+UwJgwYWUykewi8H6vlslAO73n9E= +github.com/sagernet/gvisor v0.0.0-20240428053021-e691de28565f h1:NkhuupzH5ch7b/Y/6ZHJWrnNLoiNnSJaow6DPb8VW2I= +github.com/sagernet/gvisor v0.0.0-20240428053021-e691de28565f/go.mod h1:KXmw+ouSJNOsuRpg4wgwwCQuunrGz4yoAqQjsLjc6N0= +github.com/sagernet/netlink v0.0.0-20240523065131-45e60152f9ba h1:EY5AS7CCtfmARNv2zXUOrsEMPFDGYxaw65JzA2p51Vk= +github.com/sagernet/netlink v0.0.0-20240523065131-45e60152f9ba/go.mod h1:xLnfdiJbSp8rNqYEdIW/6eDO4mVoogml14Bh2hSiFpM= +github.com/sagernet/quic-go v0.47.0-beta.2 h1:1tCGWFOSaXIeuQaHrwOMJIYvlupjTcaVInGQw5ArULU= +github.com/sagernet/quic-go v0.47.0-beta.2/go.mod h1:bLVKvElSEMNv7pu7SZHscW02TYigzQ5lQu3Nh4wNh8Q= +github.com/sagernet/reality v0.0.0-20230406110435-ee17307e7691 h1:5Th31OC6yj8byLGkEnIYp6grlXfo1QYUfiYFGjewIdc= +github.com/sagernet/reality v0.0.0-20230406110435-ee17307e7691/go.mod h1:B8lp4WkQ1PwNnrVMM6KyuFR20pU8jYBD+A4EhJovEXU= +github.com/sagernet/sing v0.2.18/go.mod h1:OL6k2F0vHmEzXz2KW19qQzu172FDgSbUSODylighuVo= +github.com/sagernet/sing v0.4.3 h1:Ty/NAiNnVd6844k7ujlL5lkzydhcTH5Psc432jXA4Y8= +github.com/sagernet/sing v0.4.3/go.mod h1:ieZHA/+Y9YZfXs2I3WtuwgyCZ6GPsIR7HdKb1SdEnls= +github.com/sagernet/sing-dns v0.2.3 h1:YzeBUn2tR38F7HtvGEQ0kLRLmZWMEgi/+7wqa4Twb1k= +github.com/sagernet/sing-dns v0.2.3/go.mod h1:BJpJv6XLnrUbSyIntOT6DG9FW0f4fETmPAHvNjOprLg= +github.com/sagernet/sing-mux v0.2.0 h1:4C+vd8HztJCWNYfufvgL49xaOoOHXty2+EAjnzN3IYo= +github.com/sagernet/sing-mux v0.2.0/go.mod h1:khzr9AOPocLa+g53dBplwNDz4gdsyx/YM3swtAhlkHQ= +github.com/sagernet/sing-quic v0.2.2 h1:Ryp02zMhHh/ZDrG7MdLsmhuBU8+BEpOdJonFQiqIopo= +github.com/sagernet/sing-quic v0.2.2/go.mod h1:YLV1dUDv8Eyp/8e55O/EvfsrwxOgEDVgDCIoPqmDREE= +github.com/sagernet/sing-shadowsocks v0.2.7 h1:zaopR1tbHEw5Nk6FAkM05wCslV6ahVegEZaKMv9ipx8= +github.com/sagernet/sing-shadowsocks v0.2.7/go.mod h1:0rIKJZBR65Qi0zwdKezt4s57y/Tl1ofkaq6NlkzVuyE= +github.com/sagernet/sing-shadowsocks2 v0.2.0 h1:wpZNs6wKnR7mh1wV9OHwOyUr21VkS3wKFHi+8XwgADg= +github.com/sagernet/sing-shadowsocks2 v0.2.0/go.mod h1:RnXS0lExcDAovvDeniJ4IKa2IuChrdipolPYWBv9hWQ= +github.com/sagernet/sing-shadowtls v0.1.4 h1:aTgBSJEgnumzFenPvc+kbD9/W0PywzWevnVpEx6Tw3k= +github.com/sagernet/sing-shadowtls v0.1.4/go.mod h1:F8NBgsY5YN2beQavdgdm1DPlhaKQlaL6lpDdcBglGK4= +github.com/sagernet/sing-tun v0.3.3 h1:LZnQNmfGcNG2KPTPkLgc+Lo7k606QJVkPp2DnjriwUk= +github.com/sagernet/sing-tun v0.3.3/go.mod h1:DxLIyhjWU/HwGYoX0vNGg2c5QgTQIakphU1MuERR5tQ= +github.com/sagernet/sing-vmess v0.1.12 h1:2gFD8JJb+eTFMoa8FIVMnknEi+vCSfaiTXTfEYAYAPg= +github.com/sagernet/sing-vmess v0.1.12/go.mod h1:luTSsfyBGAc9VhtCqwjR+dt1QgqBhuYBCONB/POhF8I= +github.com/sagernet/smux v0.0.0-20231208180855-7041f6ea79e7 h1:DImB4lELfQhplLTxeq2z31Fpv8CQqqrUwTbrIRumZqQ= +github.com/sagernet/smux v0.0.0-20231208180855-7041f6ea79e7/go.mod h1:FP9X2xjT/Az1EsG/orYYoC+5MojWnuI7hrffz8fGwwo= +github.com/sagernet/utls v1.5.4 h1:KmsEGbB2dKUtCNC+44NwAdNAqnqQ6GA4pTO0Yik56co= +github.com/sagernet/utls v1.5.4/go.mod h1:CTGxPWExIloRipK3XFpYv0OVyhO8kk3XCGW/ieyTh1s= +github.com/sagernet/ws v0.0.0-20231204124109-acfe8907c854 h1:6uUiZcDRnZSAegryaUGwPC/Fj13JSHwiTftrXhMmYOc= +github.com/sagernet/ws v0.0.0-20231204124109-acfe8907c854/go.mod h1:LtfoSK3+NG57tvnVEHgcuBW9ujgE8enPSgzgwStwCAA= +github.com/samuel/go-zookeeper v0.0.0-20190923202752-2cc03de413da/go.mod h1:gi+0XIa01GRL2eRQVjQkKGqKF3SF9vZR/HnPullcV2E= +github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= +github.com/seiflotfy/cuckoofilter v0.0.0-20240715131351-a2f2c23f1771 h1:emzAzMZ1L9iaKCTxdy3Em8Wv4ChIAGnfiz18Cda70g4= +github.com/seiflotfy/cuckoofilter v0.0.0-20240715131351-a2f2c23f1771/go.mod h1:bR6DqgcAl1zTcOX8/pE2Qkj9XO00eCNqmKb7lXP8EAg= +github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= +github.com/shurcooL/component v0.0.0-20170202220835-f88ec8f54cc4/go.mod h1:XhFIlyj5a1fBNx5aJTbKoIq0mNaPvOagO+HjB3EtxrY= +github.com/shurcooL/events v0.0.0-20181021180414-410e4ca65f48/go.mod h1:5u70Mqkb5O5cxEA8nxTsgrgLehJeAw6Oc4Ab1c/P1HM= +github.com/shurcooL/github_flavored_markdown v0.0.0-20181002035957-2122de532470/go.mod h1:2dOwnU2uBioM+SGy2aZoq1f/Sd1l9OkAeAUvjSyvgU0= +github.com/shurcooL/go v0.0.0-20180423040247-9e1955d9fb6e/go.mod h1:TDJrrUr11Vxrven61rcy3hJMUqaf/CLWYhHNPmT14Lk= +github.com/shurcooL/go-goon v0.0.0-20170922171312-37c2f522c041/go.mod h1:N5mDOmsrJOB+vfqUK+7DmDyjhSLIIBnXo9lvZJj3MWQ= +github.com/shurcooL/gofontwoff v0.0.0-20180329035133-29b52fc0a18d/go.mod h1:05UtEgK5zq39gLST6uB0cf3NEHjETfB4Fgr3Gx5R9Vw= +github.com/shurcooL/gopherjslib v0.0.0-20160914041154-feb6d3990c2c/go.mod h1:8d3azKNyqcHP1GaQE/c6dDgjkgSx2BZ4IoEi4F1reUI= +github.com/shurcooL/highlight_diff v0.0.0-20170515013008-09bb4053de1b/go.mod h1:ZpfEhSmds4ytuByIcDnOLkTHGUI6KNqRNPDLHDk+mUU= +github.com/shurcooL/highlight_go v0.0.0-20181028180052-98c3abbbae20/go.mod h1:UDKB5a1T23gOMUJrI+uSuH0VRDStOiUVSjBTRDVBVag= +github.com/shurcooL/home v0.0.0-20181020052607-80b7ffcb30f9/go.mod h1:+rgNQw2P9ARFAs37qieuu7ohDNQ3gds9msbT2yn85sg= +github.com/shurcooL/htmlg v0.0.0-20170918183704-d01228ac9e50/go.mod h1:zPn1wHpTIePGnXSHpsVPWEktKXHr6+SS6x/IKRb7cpw= +github.com/shurcooL/httperror v0.0.0-20170206035902-86b7830d14cc/go.mod h1:aYMfkZ6DWSJPJ6c4Wwz3QtW22G7mf/PEgaB9k/ik5+Y= +github.com/shurcooL/httpfs v0.0.0-20171119174359-809beceb2371/go.mod h1:ZY1cvUeJuFPAdZ/B6v7RHavJWZn2YPVFQ1OSXhCGOkg= +github.com/shurcooL/httpgzip v0.0.0-20180522190206-b1c53ac65af9/go.mod h1:919LwcH0M7/W4fcZ0/jy0qGght1GIhqyS/EgWGH2j5Q= +github.com/shurcooL/issues v0.0.0-20181008053335-6292fdc1e191/go.mod h1:e2qWDig5bLteJ4fwvDAc2NHzqFEthkqn7aOZAOpj+PQ= +github.com/shurcooL/issuesapp v0.0.0-20180602232740-048589ce2241/go.mod h1:NPpHK2TI7iSaM0buivtFUc9offApnI0Alt/K8hcHy0I= +github.com/shurcooL/notifications v0.0.0-20181007000457-627ab5aea122/go.mod h1:b5uSkrEVM1jQUspwbixRBhaIjIzL2xazXp6kntxYle0= +github.com/shurcooL/octicon v0.0.0-20181028054416-fa4f57f9efb2/go.mod h1:eWdoE5JD4R5UVWDucdOPg1g2fqQRq78IQa9zlOV1vpQ= +github.com/shurcooL/reactions v0.0.0-20181006231557-f2e0b4ca5b82/go.mod h1:TCR1lToEk4d2s07G3XGfz2QrgHXg4RJBvjrOozvoWfk= +github.com/shurcooL/sanitized_anchor_name v0.0.0-20170918181015-86672fcb3f95/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= +github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= +github.com/shurcooL/users v0.0.0-20180125191416-49c67e49c537/go.mod h1:QJTqeLYEDaXHZDBsXlPCDqdhQuJkuw4NOtaxYe3xii4= +github.com/shurcooL/webdavfs v0.0.0-20170829043945-18c3829fa133/go.mod h1:hKmq5kWdCj2z2KEozexVbfEZIWiTjhE0+UjmZgPqehw= +github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= +github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= +github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88= +github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= +github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= +github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= +github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM= +github.com/sony/gobreaker v0.4.1/go.mod h1:ZKptC7FHNvhBz7dN2LGjPVBz2sZJmc0/PkyDJOjmxWY= +github.com/sourcegraph/annotate v0.0.0-20160123013949-f4cad6c6324d/go.mod h1:UdhH50NIW0fCiwBSr0co2m7BnFLdv4fQTgdqdJTHFeE= +github.com/sourcegraph/syntaxhighlight v0.0.0-20170531221838-bd320f5d308e/go.mod h1:HuIsMU8RRBOtsCgI77wP899iHVBQpCmg4ErYMZB+2IA= +github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= +github.com/spaolacci/murmur3 v1.1.0 h1:7c1g84S4BPRrfL5Xrdp6fOJ206sU9y293DDHaoy0bLI= +github.com/spaolacci/murmur3 v1.1.0/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= +github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= +github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= +github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= +github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU= +github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0= +github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho= +github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= +github.com/spf13/pflag v1.0.1/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= +github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= +github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= +github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DMA2s= +github.com/streadway/amqp v0.0.0-20190404075320-75d898a42a94/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw= +github.com/streadway/amqp v0.0.0-20190827072141-edfb9018d271/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw= +github.com/streadway/handy v0.0.0-20190108123426-d5acb3125c2a/go.mod h1:qNTQ5P5JnDBl6z3cMAg/SywNDC5ABu5ApDIw6lUbRmI= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/syndtr/goleveldb v1.0.1-0.20200815110645-5c35d600f0ca h1:Ld/zXl5t4+D69SiV4JoN7kkfvJdOWlPpfxrzxpLMoUk= +github.com/syndtr/goleveldb v1.0.1-0.20200815110645-5c35d600f0ca/go.mod h1:u2MKkTVTVJWe5D1rCvame8WqhBd88EuIwODJZ1VHCPM= +github.com/tarm/serial v0.0.0-20180830185346-98f6abe2eb07/go.mod h1:kDXzergiv9cbyO7IOYJZWg1U88JhDg3PB6klq9Hg2pA= +github.com/tendermint/tm-db v0.6.7 h1:fE00Cbl0jayAoqlExN6oyQJ7fR/ZtoVOmvPJ//+shu8= +github.com/tendermint/tm-db v0.6.7/go.mod h1:byQDzFkZV1syXr/ReXS808NxA2xvyuuVgXOJ/088L6I= +github.com/tmc/grpc-websocket-proxy v0.0.0-20170815181823-89b8d40f7ca8/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= +github.com/u-root/uio v0.0.0-20230220225925-ffce2a382923 h1:tHNk7XK9GkmKUR6Gh8gVBKXc2MVSZ4G/NnWLtzw4gNA= +github.com/u-root/uio v0.0.0-20230220225925-ffce2a382923/go.mod h1:eLL9Nub3yfAho7qB0MzZizFhTU2QkLeoVsWdHtDW264= +github.com/ugorji/go v1.1.7 h1:/68gy2h+1mWMrwZFeD1kQialdSzAb432dtpeJ42ovdo= +github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw= +github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= +github.com/ugorji/go/codec v1.1.7 h1:2SvQaVZ1ouYrrKKwoSk2pzd4A9evlKJb9oTL+OaLUSs= +github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY= +github.com/urfave/cli v1.20.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA= +github.com/urfave/cli v1.22.1/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= +github.com/v2fly/ss-bloomring v0.0.0-20210312155135-28617310f63e h1:5QefA066A1tF8gHIiADmOVOV5LS43gt3ONnlEl3xkwI= +github.com/v2fly/ss-bloomring v0.0.0-20210312155135-28617310f63e/go.mod h1:5t19P9LBIrNamL6AcMQOncg/r10y3Pc01AbHeMhwlpU= +github.com/viant/assertly v0.4.8/go.mod h1:aGifi++jvCrUaklKEKT0BU95igDNaqkvz+49uaYMPRU= +github.com/viant/toolbox v0.24.0/go.mod h1:OxMCG57V0PXuIP2HNQrtJf2CjqdmbrOx5EkMILuUhzM= +github.com/vishvananda/netns v0.0.4 h1:Oeaw1EM2JMxD51g9uhtC0D7erkIjgmj8+JZc26m1YX8= +github.com/vishvananda/netns v0.0.4/go.mod h1:SpkAiCQRtJ6TvvxPnOSyH3BMl6unz3xZlaprSwhNNJM= +github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= +github.com/xmdhs/clash2singbox v0.0.2 h1:/gxaFm8fmv+UcUZzK508Z0yR01wg1LHrrq872Qibk1I= +github.com/xmdhs/clash2singbox v0.0.2/go.mod h1:B5pbJCwIHhJg6YRPCT04EXw6XXNIIOllMfL3XyJ7ob8= +github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= +github.com/xtls/reality v0.0.0-20240712055506-48f0b2d5ed6d h1:+B97uD9uHLgAAulhigmys4BVwZZypzK7gPN3WtpgRJg= +github.com/xtls/reality v0.0.0-20240712055506-48f0b2d5ed6d/go.mod h1:dm4y/1QwzjGaK17ofi0Vs6NpKAHegZky8qk6J2JJZAE= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +github.com/zeebo/assert v1.1.0 h1:hU1L1vLTHsnO8x8c9KAR5GmM5QscxHg5RNU5z5qbUWY= +github.com/zeebo/assert v1.1.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0= +github.com/zeebo/blake3 v0.2.3 h1:TFoLXsjeXqRNFxSbk35Dk4YtszE/MQQGK10BH4ptoTg= +github.com/zeebo/blake3 v0.2.3/go.mod h1:mjJjZpnsyIVtVgTOSpJ9vmRE4wgDeyt2HU3qXvvKCaQ= +github.com/zeebo/pcg v1.0.1 h1:lyqfGeWiv4ahac6ttHs+I5hwtH/+1mrhlCtVNQM2kHo= +github.com/zeebo/pcg v1.0.1/go.mod h1:09F0S9iiKrwn9rlI5yjLkmrug154/YRW6KnnXVDM/l4= +go.etcd.io/bbolt v1.3.3/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= +go.etcd.io/bbolt v1.3.6 h1:/ecaJf0sk1l4l6V4awd65v2C3ILy7MSj+s/x1ADCIMU= +go.etcd.io/bbolt v1.3.6/go.mod h1:qXsaaIqmgQH0T+OPdb99Bf+PKfBBQVAdyD6TY9G8XM4= +go.etcd.io/etcd v0.0.0-20191023171146-3cf2f69b5738/go.mod h1:dnLIgRNXwCJa5e+c6mIZCrds/GIG4ncV9HhK5PX7jPg= +go.opencensus.io v0.18.0/go.mod h1:vKdFvxhtzZ9onBp9VKHK8z/sRpBMnKAsufL7wlDrCOA= +go.opencensus.io v0.20.1/go.mod h1:6WKK9ahsWS3RSO+PY9ZHZUfv2irvY6gN279GOPZjmmk= +go.opencensus.io v0.20.2/go.mod h1:6WKK9ahsWS3RSO+PY9ZHZUfv2irvY6gN279GOPZjmmk= +go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= +go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= +go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= +go.uber.org/atomic v1.5.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= +go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= +go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= +go.uber.org/mock v0.4.0 h1:VcM4ZOtdbR4f6VXfiOpwpVJDL6lCReaZ6mw31wqh7KU= +go.uber.org/mock v0.4.0/go.mod h1:a6FSlNadKUHUa9IP5Vyt1zh4fC7uAwxMutEAscFbkZc= +go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= +go.uber.org/multierr v1.3.0/go.mod h1:VgVr7evmIr6uPjLBxg28wmKNXyqE9akIJ5XnfpiKl+4= +go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= +go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= +go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA= +go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= +go.uber.org/zap v1.13.0/go.mod h1:zwrFLgMcdUuIBviXEYEH1YKNaOBnKXsx2IPda5bBwHM= +go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8= +go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= +go4.org v0.0.0-20180809161055-417644f6feb5/go.mod h1:MkTOUMDaeVYJUOUsaDXIhWPZYa1yOyC1qaOBpL57BhE= +go4.org/netipx v0.0.0-20231129151722-fdeea329fbba h1:0b9z3AuHCjxk0x/opv64kcgZLBseWJUpBw5I82+2U4M= +go4.org/netipx v0.0.0-20231129151722-fdeea329fbba/go.mod h1:PLyyIXexvUFg3Owu6p/WfdlivPbZJsZdgWZlrGope/Y= +golang.org/x/build v0.0.0-20190111050920-041ab4dc3f9d/go.mod h1:OWs+y06UdEOHN4y+MfF/py+xQ/tYqIWW03b70/CG9Rw= +golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20181030102418-4d3f4d9ffa16/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190313024323-a1f597ede03a/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190404164418-38d8ce5564a5/go.mod h1:WFFai1msRO1wXaEeE5yQxYXgSfI8pQAWXbQop6sCtWE= +golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.8.0/go.mod h1:mRqEX+O9/h5TFCrQhkgjo2yKi0yYA+9ecGkdQoHrywE= +golang.org/x/crypto v0.12.0/go.mod h1:NF0Gs7EO5K4qLn+Ylc+fih8BSTeIjAP05siRnAh98yw= +golang.org/x/crypto v0.26.0 h1:RrRspgV4mU+YwB4FYnuBoKsUapNIL5cohGAmSH3azsw= +golang.org/x/crypto v0.26.0/go.mod h1:GY7jblb9wI+FOo5y8/S2oY4zWP07AkOJ4+jxCqdqn54= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20200331195152-e8c3332aa8e5/go.mod h1:4M0jN8W1tt0AVLNr8HDosyJCDCDuyL9N9+3m7wDWgKw= +golang.org/x/exp v0.0.0-20240531132922-fd00a4e0eefc h1:O9NuF4s+E/PvMIy+9IUZB9znFwUIXEWSstNjek6VpVg= +golang.org/x/exp v0.0.0-20240531132922-fd00a4e0eefc/go.mod h1:XtvwrStGgqGPLc4cjQfWqZHG1YFdYs6swckp8vpsjnc= +golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= +golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/lint v0.0.0-20180702182130-06c8688daad7/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= +golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= +golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/mod v0.18.0 h1:5+9lSbEzPSdWkH32vYPBwEpX8KwDbM52Ud9xBUvNlb0= +golang.org/x/mod v0.18.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181023162649-9b4f9f5ad519/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181029044818-c44066c5c816/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181106065722-10aee1819953/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181201002055-351d144fa1fc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190125091013-d26f9f9a57f3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190313220215-9f648a60d977/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= +golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190813141303-74dc4d7220e7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200421231249-e086a090c8fd/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20200813134508-3edf25e44fcc/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns= +golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= +golang.org/x/net v0.14.0/go.mod h1:PpSgVXXLK0OxS0F31C1/tv6XNguvCrnXIDrFMspZIUI= +golang.org/x/net v0.28.0 h1:a9JDOJc5GMUJ0+UDqmLT86WiEy7iWyIhz8gz8E4e5hE= +golang.org/x/net v0.28.0/go.mod h1:yqtgsTWOOnlGLG9GFRrK3++bGOUEkNBoHZc8MEDWPNg= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/oauth2 v0.0.0-20181017192945-9dcd33a902f4/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/oauth2 v0.0.0-20181203162652-d668ce993890/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/perf v0.0.0-20180704124530-6e6d33e29852/go.mod h1:JLpeXjPJfIyPr5TlbXLkXWLhP8nz10XfvxElABhCtcw= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ= +golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181026203630-95b1ffbd15a5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181029174526-d69651ed3497/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181122145206-62eef0e2fa9b/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190316082340-a2f829d7f35f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190403152447-81d4e9dc473e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190626221950-04f50cda93cb/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190826190057-c7b8b68b1456/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191220142924-d4481acd189f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200420163511-1957bb5e6d1f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200519105757-fe76b779f299/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200814200057-3d37ad5750ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200923182605-d9f96fdee20d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201015000850-e3ed0017c211/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220622161953-175b2fd9d664/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.14.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34= +golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= +golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY= +golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= +golang.org/x/term v0.11.0/go.mod h1:zC9APTIj3jG3FdV/Ons+XE1riIZXG4aZ4GTHiPZJPIU= +golang.org/x/term v0.23.0 h1:F6D4vR+EHoL9/sWAWgAR1H2DcHr4PareCbAaCo1RpuU= +golang.org/x/term v0.23.0/go.mod h1:DgV24QBUrK6jhZXl+20l6UWznPlwAHm1Q1mGHtydmSk= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/text v0.12.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= +golang.org/x/text v0.18.0 h1:XvMDiNzPAl0jr17s6W9lcaIhGUfUORdGCNsuLmPG224= +golang.org/x/text v0.18.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= +golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk= +golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= +golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20181030000716-a0a13e073c7b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20200103221440-774c71fcf114/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200207183749-b753a1ba74fa/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= +golang.org/x/tools v0.22.0 h1:gqSGLZqv+AI9lIQzniJ0nZDRG5GBPsSi+DRNHWNz6yA= +golang.org/x/tools v0.22.0/go.mod h1:aCwcsjqvq7Yqt6TNyX7QMU2enbQ/Gt0bo6krSeEri+c= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/api v0.0.0-20180910000450-7ca32eb868bf/go.mod h1:4mhQ8q/RsB7i+udVvVy5NUi08OU8ZlA0gRVgrF7VFY0= +google.golang.org/api v0.0.0-20181030000543-1d582fd0359e/go.mod h1:4mhQ8q/RsB7i+udVvVy5NUi08OU8ZlA0gRVgrF7VFY0= +google.golang.org/api v0.1.0/go.mod h1:UGEZY7KEX120AnNLIHFMKIo4obdJhkp2tPbaPlQx13Y= +google.golang.org/api v0.3.1/go.mod h1:6wY9I6uQWHQ8EM57III9mq/AjF+i8G65rmVagqKMtkk= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.2.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.3.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20180831171423-11092d34479b/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20181029155118-b69ba1387ce2/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20181202183823-bd91e49a0898/go.mod h1:7Ep/1NZk928CDR8SjdVbjWNpdIf6nzjE3BTgJDr2Atg= +google.golang.org/genproto v0.0.0-20190306203927-b5d61aea6440/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190530194941-fb225487d101/go.mod h1:z3L6/3dTEVtUr6QSP8miRzeRqwQOioJ9I66odjN4I7s= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20200423170343-7949de9c1215/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= +google.golang.org/genproto v0.0.0-20210126160654-44e461bb6506/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto/googleapis/rpc v0.0.0-20240604185151-ef581f913117 h1:1GBuWVLM/KMVUv1t1En5Gs+gFZCNd360GGb4sSxtrhU= +google.golang.org/genproto/googleapis/rpc v0.0.0-20240604185151-ef581f913117/go.mod h1:EfXuqaE1J41VCDicxHzUDm+8rk+7ZdXzHV0IhO/I6s0= +google.golang.org/grpc v1.14.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= +google.golang.org/grpc v1.16.0/go.mod h1:0JHn/cJsOMiMfNA9+DeHDlAU7KAAB5GDlYFpa9MZMio= +google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.20.0/go.mod h1:chYK+tFQF0nDUGJgXMSgLCQk3phJEuONr2DCgLDdAQM= +google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= +google.golang.org/grpc v1.21.0/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= +google.golang.org/grpc v1.22.1/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.23.1/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= +google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= +google.golang.org/grpc v1.32.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +google.golang.org/grpc v1.66.0 h1:DibZuoBznOxbDQxRINckZcUvnCEvrW9pcWIE2yF9r1c= +google.golang.org/grpc v1.66.0/go.mod h1:s3/l6xSSCURdVfAnL+TqCNMyTDAGN6+lZeVxnZR128Y= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGjtUeSXeh4= +google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= +google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg= +google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw= +gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/cheggaaa/pb.v1 v1.0.25/go.mod h1:V/YB90LKu/1FcN3WVnfiiE5oMCibMjukxqG/qStrOgw= +gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= +gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/gcfg.v1 v1.2.3/go.mod h1:yesOnuUOFQAhST5vPY4nbZsb/huCgGGXlipJsBn0b3o= +gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= +gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= +gopkg.in/warnings.v0 v0.1.2/go.mod h1:jksf8JmL6Qr/oQM2OXTHunEvvTAsrWBLb6OOjuVWRNI= +gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74= +gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20200605160147-a5ece683394c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +grpc.go4.org v0.0.0-20170609214715-11d0a25b4919/go.mod h1:77eQGdRu53HpSqPFJFmuJdjuHRquDANNeA4x7B8WQ9o= +honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= +lukechampine.com/blake3 v1.3.0 h1:sJ3XhFINmHSrYCgl958hscfIa3bw8x4DqMP3u1YvoYE= +lukechampine.com/blake3 v1.3.0/go.mod h1:0OFRp7fBtAylGVCO40o87sbupkyIGgbpv1+M1k1LM6k= +nhooyr.io/websocket v1.8.6 h1:s+C3xAMLwGmlI31Nyn/eAehUlZPwfYZu2JXM621Q5/k= +nhooyr.io/websocket v1.8.6/go.mod h1:B70DZP8IakI65RVQ51MsWP/8jndNma26DVA/nFSCgW0= +sigs.k8s.io/yaml v1.1.0/go.mod h1:UJmg0vDUVViEyp3mgSv9WPwZCDxu4rQW1olrI1uml+o= +sourcegraph.com/sourcegraph/appdash v0.0.0-20190731080439-ebfcffb1b5c0/go.mod h1:hI742Nqp5OhwiqlzhgfbWU4mW4yO10fP+LoT9WOswdU= +sourcegraph.com/sourcegraph/go-diff v0.5.0/go.mod h1:kuch7UrkMzY0X+p9CRK03kfuPQ2zzQcaEFbx8wA8rck= +sourcegraph.com/sqs/pbtypes v0.0.0-20180604144634-d3ebe8f20ae4/go.mod h1:ketZ/q3QxT9HOBeFhu6RdvsftgpsbFHBF5Cas6cDKZ0= diff --git a/libcore/hiddify-core.tar.gz b/libcore/hiddify-core.tar.gz new file mode 100644 index 0000000..3e267ce Binary files /dev/null and b/libcore/hiddify-core.tar.gz differ diff --git a/libcore/hiddifyrpc/base.pb.go b/libcore/hiddifyrpc/base.pb.go new file mode 100644 index 0000000..e9d9595 --- /dev/null +++ b/libcore/hiddifyrpc/base.pb.go @@ -0,0 +1,307 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.34.2 +// protoc v5.28.0 +// source: base.proto + +package hiddifyrpc + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +type ResponseCode int32 + +const ( + ResponseCode_OK ResponseCode = 0 + ResponseCode_FAILED ResponseCode = 1 +) + +// Enum value maps for ResponseCode. +var ( + ResponseCode_name = map[int32]string{ + 0: "OK", + 1: "FAILED", + } + ResponseCode_value = map[string]int32{ + "OK": 0, + "FAILED": 1, + } +) + +func (x ResponseCode) Enum() *ResponseCode { + p := new(ResponseCode) + *p = x + return p +} + +func (x ResponseCode) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (ResponseCode) Descriptor() protoreflect.EnumDescriptor { + return file_base_proto_enumTypes[0].Descriptor() +} + +func (ResponseCode) Type() protoreflect.EnumType { + return &file_base_proto_enumTypes[0] +} + +func (x ResponseCode) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use ResponseCode.Descriptor instead. +func (ResponseCode) EnumDescriptor() ([]byte, []int) { + return file_base_proto_rawDescGZIP(), []int{0} +} + +type HelloRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` +} + +func (x *HelloRequest) Reset() { + *x = HelloRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_base_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *HelloRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*HelloRequest) ProtoMessage() {} + +func (x *HelloRequest) ProtoReflect() protoreflect.Message { + mi := &file_base_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use HelloRequest.ProtoReflect.Descriptor instead. +func (*HelloRequest) Descriptor() ([]byte, []int) { + return file_base_proto_rawDescGZIP(), []int{0} +} + +func (x *HelloRequest) GetName() string { + if x != nil { + return x.Name + } + return "" +} + +type HelloResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Message string `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"` +} + +func (x *HelloResponse) Reset() { + *x = HelloResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_base_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *HelloResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*HelloResponse) ProtoMessage() {} + +func (x *HelloResponse) ProtoReflect() protoreflect.Message { + mi := &file_base_proto_msgTypes[1] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use HelloResponse.ProtoReflect.Descriptor instead. +func (*HelloResponse) Descriptor() ([]byte, []int) { + return file_base_proto_rawDescGZIP(), []int{1} +} + +func (x *HelloResponse) GetMessage() string { + if x != nil { + return x.Message + } + return "" +} + +type Empty struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields +} + +func (x *Empty) Reset() { + *x = Empty{} + if protoimpl.UnsafeEnabled { + mi := &file_base_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Empty) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Empty) ProtoMessage() {} + +func (x *Empty) ProtoReflect() protoreflect.Message { + mi := &file_base_proto_msgTypes[2] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Empty.ProtoReflect.Descriptor instead. +func (*Empty) Descriptor() ([]byte, []int) { + return file_base_proto_rawDescGZIP(), []int{2} +} + +var File_base_proto protoreflect.FileDescriptor + +var file_base_proto_rawDesc = []byte{ + 0x0a, 0x0a, 0x62, 0x61, 0x73, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0a, 0x68, 0x69, + 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x22, 0x22, 0x0a, 0x0c, 0x48, 0x65, 0x6c, 0x6c, + 0x6f, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, + 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x22, 0x29, 0x0a, 0x0d, + 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x18, 0x0a, + 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, + 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x22, 0x07, 0x0a, 0x05, 0x45, 0x6d, 0x70, 0x74, 0x79, + 0x2a, 0x22, 0x0a, 0x0c, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x43, 0x6f, 0x64, 0x65, + 0x12, 0x06, 0x0a, 0x02, 0x4f, 0x4b, 0x10, 0x00, 0x12, 0x0a, 0x0a, 0x06, 0x46, 0x41, 0x49, 0x4c, + 0x45, 0x44, 0x10, 0x01, 0x42, 0x0e, 0x5a, 0x0c, 0x2e, 0x2f, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, + 0x79, 0x72, 0x70, 0x63, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_base_proto_rawDescOnce sync.Once + file_base_proto_rawDescData = file_base_proto_rawDesc +) + +func file_base_proto_rawDescGZIP() []byte { + file_base_proto_rawDescOnce.Do(func() { + file_base_proto_rawDescData = protoimpl.X.CompressGZIP(file_base_proto_rawDescData) + }) + return file_base_proto_rawDescData +} + +var file_base_proto_enumTypes = make([]protoimpl.EnumInfo, 1) +var file_base_proto_msgTypes = make([]protoimpl.MessageInfo, 3) +var file_base_proto_goTypes = []any{ + (ResponseCode)(0), // 0: hiddifyrpc.ResponseCode + (*HelloRequest)(nil), // 1: hiddifyrpc.HelloRequest + (*HelloResponse)(nil), // 2: hiddifyrpc.HelloResponse + (*Empty)(nil), // 3: hiddifyrpc.Empty +} +var file_base_proto_depIdxs = []int32{ + 0, // [0:0] is the sub-list for method output_type + 0, // [0:0] is the sub-list for method input_type + 0, // [0:0] is the sub-list for extension type_name + 0, // [0:0] is the sub-list for extension extendee + 0, // [0:0] is the sub-list for field type_name +} + +func init() { file_base_proto_init() } +func file_base_proto_init() { + if File_base_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_base_proto_msgTypes[0].Exporter = func(v any, i int) any { + switch v := v.(*HelloRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_base_proto_msgTypes[1].Exporter = func(v any, i int) any { + switch v := v.(*HelloResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_base_proto_msgTypes[2].Exporter = func(v any, i int) any { + switch v := v.(*Empty); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_base_proto_rawDesc, + NumEnums: 1, + NumMessages: 3, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_base_proto_goTypes, + DependencyIndexes: file_base_proto_depIdxs, + EnumInfos: file_base_proto_enumTypes, + MessageInfos: file_base_proto_msgTypes, + }.Build() + File_base_proto = out.File + file_base_proto_rawDesc = nil + file_base_proto_goTypes = nil + file_base_proto_depIdxs = nil +} diff --git a/libcore/hiddifyrpc/base.proto b/libcore/hiddifyrpc/base.proto new file mode 100644 index 0000000..f532a0b --- /dev/null +++ b/libcore/hiddifyrpc/base.proto @@ -0,0 +1,21 @@ +syntax = "proto3"; + +package hiddifyrpc; + +option go_package = "./hiddifyrpc"; + +message HelloRequest { + string name = 1; +} + +message HelloResponse { + string message = 1; +} + +message Empty { +} + +enum ResponseCode { + OK = 0; + FAILED = 1; +} \ No newline at end of file diff --git a/libcore/hiddifyrpc/extension.pb.go b/libcore/hiddifyrpc/extension.pb.go new file mode 100644 index 0000000..9af07cd --- /dev/null +++ b/libcore/hiddifyrpc/extension.pb.go @@ -0,0 +1,759 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.34.2 +// protoc v5.28.0 +// source: extension.proto + +package hiddifyrpc + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +type ExtensionResponseType int32 + +const ( + ExtensionResponseType_NOTHING ExtensionResponseType = 0 + ExtensionResponseType_UPDATE_UI ExtensionResponseType = 1 + ExtensionResponseType_SHOW_DIALOG ExtensionResponseType = 2 + ExtensionResponseType_END ExtensionResponseType = 3 +) + +// Enum value maps for ExtensionResponseType. +var ( + ExtensionResponseType_name = map[int32]string{ + 0: "NOTHING", + 1: "UPDATE_UI", + 2: "SHOW_DIALOG", + 3: "END", + } + ExtensionResponseType_value = map[string]int32{ + "NOTHING": 0, + "UPDATE_UI": 1, + "SHOW_DIALOG": 2, + "END": 3, + } +) + +func (x ExtensionResponseType) Enum() *ExtensionResponseType { + p := new(ExtensionResponseType) + *p = x + return p +} + +func (x ExtensionResponseType) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (ExtensionResponseType) Descriptor() protoreflect.EnumDescriptor { + return file_extension_proto_enumTypes[0].Descriptor() +} + +func (ExtensionResponseType) Type() protoreflect.EnumType { + return &file_extension_proto_enumTypes[0] +} + +func (x ExtensionResponseType) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use ExtensionResponseType.Descriptor instead. +func (ExtensionResponseType) EnumDescriptor() ([]byte, []int) { + return file_extension_proto_rawDescGZIP(), []int{0} +} + +type ExtensionActionResult struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + ExtensionId string `protobuf:"bytes,1,opt,name=extension_id,json=extensionId,proto3" json:"extension_id,omitempty"` + Code ResponseCode `protobuf:"varint,2,opt,name=code,proto3,enum=hiddifyrpc.ResponseCode" json:"code,omitempty"` + Message string `protobuf:"bytes,3,opt,name=message,proto3" json:"message,omitempty"` +} + +func (x *ExtensionActionResult) Reset() { + *x = ExtensionActionResult{} + if protoimpl.UnsafeEnabled { + mi := &file_extension_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ExtensionActionResult) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ExtensionActionResult) ProtoMessage() {} + +func (x *ExtensionActionResult) ProtoReflect() protoreflect.Message { + mi := &file_extension_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ExtensionActionResult.ProtoReflect.Descriptor instead. +func (*ExtensionActionResult) Descriptor() ([]byte, []int) { + return file_extension_proto_rawDescGZIP(), []int{0} +} + +func (x *ExtensionActionResult) GetExtensionId() string { + if x != nil { + return x.ExtensionId + } + return "" +} + +func (x *ExtensionActionResult) GetCode() ResponseCode { + if x != nil { + return x.Code + } + return ResponseCode_OK +} + +func (x *ExtensionActionResult) GetMessage() string { + if x != nil { + return x.Message + } + return "" +} + +type ExtensionList struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Extensions []*Extension `protobuf:"bytes,1,rep,name=extensions,proto3" json:"extensions,omitempty"` +} + +func (x *ExtensionList) Reset() { + *x = ExtensionList{} + if protoimpl.UnsafeEnabled { + mi := &file_extension_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ExtensionList) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ExtensionList) ProtoMessage() {} + +func (x *ExtensionList) ProtoReflect() protoreflect.Message { + mi := &file_extension_proto_msgTypes[1] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ExtensionList.ProtoReflect.Descriptor instead. +func (*ExtensionList) Descriptor() ([]byte, []int) { + return file_extension_proto_rawDescGZIP(), []int{1} +} + +func (x *ExtensionList) GetExtensions() []*Extension { + if x != nil { + return x.Extensions + } + return nil +} + +type EditExtensionRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + ExtensionId string `protobuf:"bytes,1,opt,name=extension_id,json=extensionId,proto3" json:"extension_id,omitempty"` + Enable bool `protobuf:"varint,2,opt,name=enable,proto3" json:"enable,omitempty"` +} + +func (x *EditExtensionRequest) Reset() { + *x = EditExtensionRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_extension_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *EditExtensionRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*EditExtensionRequest) ProtoMessage() {} + +func (x *EditExtensionRequest) ProtoReflect() protoreflect.Message { + mi := &file_extension_proto_msgTypes[2] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use EditExtensionRequest.ProtoReflect.Descriptor instead. +func (*EditExtensionRequest) Descriptor() ([]byte, []int) { + return file_extension_proto_rawDescGZIP(), []int{2} +} + +func (x *EditExtensionRequest) GetExtensionId() string { + if x != nil { + return x.ExtensionId + } + return "" +} + +func (x *EditExtensionRequest) GetEnable() bool { + if x != nil { + return x.Enable + } + return false +} + +type Extension struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` + Title string `protobuf:"bytes,2,opt,name=title,proto3" json:"title,omitempty"` + Description string `protobuf:"bytes,3,opt,name=description,proto3" json:"description,omitempty"` + Enable bool `protobuf:"varint,4,opt,name=enable,proto3" json:"enable,omitempty"` +} + +func (x *Extension) Reset() { + *x = Extension{} + if protoimpl.UnsafeEnabled { + mi := &file_extension_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Extension) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Extension) ProtoMessage() {} + +func (x *Extension) ProtoReflect() protoreflect.Message { + mi := &file_extension_proto_msgTypes[3] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Extension.ProtoReflect.Descriptor instead. +func (*Extension) Descriptor() ([]byte, []int) { + return file_extension_proto_rawDescGZIP(), []int{3} +} + +func (x *Extension) GetId() string { + if x != nil { + return x.Id + } + return "" +} + +func (x *Extension) GetTitle() string { + if x != nil { + return x.Title + } + return "" +} + +func (x *Extension) GetDescription() string { + if x != nil { + return x.Description + } + return "" +} + +func (x *Extension) GetEnable() bool { + if x != nil { + return x.Enable + } + return false +} + +type ExtensionRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + ExtensionId string `protobuf:"bytes,1,opt,name=extension_id,json=extensionId,proto3" json:"extension_id,omitempty"` + Data map[string]string `protobuf:"bytes,2,rep,name=data,proto3" json:"data,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` +} + +func (x *ExtensionRequest) Reset() { + *x = ExtensionRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_extension_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ExtensionRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ExtensionRequest) ProtoMessage() {} + +func (x *ExtensionRequest) ProtoReflect() protoreflect.Message { + mi := &file_extension_proto_msgTypes[4] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ExtensionRequest.ProtoReflect.Descriptor instead. +func (*ExtensionRequest) Descriptor() ([]byte, []int) { + return file_extension_proto_rawDescGZIP(), []int{4} +} + +func (x *ExtensionRequest) GetExtensionId() string { + if x != nil { + return x.ExtensionId + } + return "" +} + +func (x *ExtensionRequest) GetData() map[string]string { + if x != nil { + return x.Data + } + return nil +} + +type SendExtensionDataRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + ExtensionId string `protobuf:"bytes,1,opt,name=extension_id,json=extensionId,proto3" json:"extension_id,omitempty"` + Button string `protobuf:"bytes,2,opt,name=button,proto3" json:"button,omitempty"` + Data map[string]string `protobuf:"bytes,3,rep,name=data,proto3" json:"data,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` +} + +func (x *SendExtensionDataRequest) Reset() { + *x = SendExtensionDataRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_extension_proto_msgTypes[5] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *SendExtensionDataRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SendExtensionDataRequest) ProtoMessage() {} + +func (x *SendExtensionDataRequest) ProtoReflect() protoreflect.Message { + mi := &file_extension_proto_msgTypes[5] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SendExtensionDataRequest.ProtoReflect.Descriptor instead. +func (*SendExtensionDataRequest) Descriptor() ([]byte, []int) { + return file_extension_proto_rawDescGZIP(), []int{5} +} + +func (x *SendExtensionDataRequest) GetExtensionId() string { + if x != nil { + return x.ExtensionId + } + return "" +} + +func (x *SendExtensionDataRequest) GetButton() string { + if x != nil { + return x.Button + } + return "" +} + +func (x *SendExtensionDataRequest) GetData() map[string]string { + if x != nil { + return x.Data + } + return nil +} + +type ExtensionResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Type ExtensionResponseType `protobuf:"varint,1,opt,name=type,proto3,enum=hiddifyrpc.ExtensionResponseType" json:"type,omitempty"` + ExtensionId string `protobuf:"bytes,2,opt,name=extension_id,json=extensionId,proto3" json:"extension_id,omitempty"` + JsonUi string `protobuf:"bytes,3,opt,name=json_ui,json=jsonUi,proto3" json:"json_ui,omitempty"` +} + +func (x *ExtensionResponse) Reset() { + *x = ExtensionResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_extension_proto_msgTypes[6] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ExtensionResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ExtensionResponse) ProtoMessage() {} + +func (x *ExtensionResponse) ProtoReflect() protoreflect.Message { + mi := &file_extension_proto_msgTypes[6] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ExtensionResponse.ProtoReflect.Descriptor instead. +func (*ExtensionResponse) Descriptor() ([]byte, []int) { + return file_extension_proto_rawDescGZIP(), []int{6} +} + +func (x *ExtensionResponse) GetType() ExtensionResponseType { + if x != nil { + return x.Type + } + return ExtensionResponseType_NOTHING +} + +func (x *ExtensionResponse) GetExtensionId() string { + if x != nil { + return x.ExtensionId + } + return "" +} + +func (x *ExtensionResponse) GetJsonUi() string { + if x != nil { + return x.JsonUi + } + return "" +} + +var File_extension_proto protoreflect.FileDescriptor + +var file_extension_proto_rawDesc = []byte{ + 0x0a, 0x0f, 0x65, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, + 0x6f, 0x12, 0x0a, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x1a, 0x0a, 0x62, + 0x61, 0x73, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x82, 0x01, 0x0a, 0x15, 0x45, 0x78, + 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x41, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, + 0x75, 0x6c, 0x74, 0x12, 0x21, 0x0a, 0x0c, 0x65, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, + 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x65, 0x78, 0x74, 0x65, 0x6e, + 0x73, 0x69, 0x6f, 0x6e, 0x49, 0x64, 0x12, 0x2c, 0x0a, 0x04, 0x63, 0x6f, 0x64, 0x65, 0x18, 0x02, + 0x20, 0x01, 0x28, 0x0e, 0x32, 0x18, 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, + 0x63, 0x2e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x43, 0x6f, 0x64, 0x65, 0x52, 0x04, + 0x63, 0x6f, 0x64, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, + 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x22, 0x46, + 0x0a, 0x0d, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x4c, 0x69, 0x73, 0x74, 0x12, + 0x35, 0x0a, 0x0a, 0x65, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x01, 0x20, + 0x03, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, + 0x2e, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x0a, 0x65, 0x78, 0x74, 0x65, + 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x22, 0x51, 0x0a, 0x14, 0x45, 0x64, 0x69, 0x74, 0x45, 0x78, + 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x21, + 0x0a, 0x0c, 0x65, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x01, + 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x65, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x49, + 0x64, 0x12, 0x16, 0x0a, 0x06, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, + 0x08, 0x52, 0x06, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x22, 0x6b, 0x0a, 0x09, 0x45, 0x78, 0x74, + 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, + 0x28, 0x09, 0x52, 0x02, 0x69, 0x64, 0x12, 0x14, 0x0a, 0x05, 0x74, 0x69, 0x74, 0x6c, 0x65, 0x18, + 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x74, 0x69, 0x74, 0x6c, 0x65, 0x12, 0x20, 0x0a, 0x0b, + 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, + 0x09, 0x52, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x16, + 0x0a, 0x06, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x08, 0x52, 0x06, + 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x22, 0xaa, 0x01, 0x0a, 0x10, 0x45, 0x78, 0x74, 0x65, 0x6e, + 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x21, 0x0a, 0x0c, 0x65, + 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, + 0x09, 0x52, 0x0b, 0x65, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x49, 0x64, 0x12, 0x3a, + 0x0a, 0x04, 0x64, 0x61, 0x74, 0x61, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x26, 0x2e, 0x68, + 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73, + 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, 0x44, 0x61, 0x74, 0x61, 0x45, + 0x6e, 0x74, 0x72, 0x79, 0x52, 0x04, 0x64, 0x61, 0x74, 0x61, 0x1a, 0x37, 0x0a, 0x09, 0x44, 0x61, + 0x74, 0x61, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, + 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, + 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, + 0x02, 0x38, 0x01, 0x22, 0xd2, 0x01, 0x0a, 0x18, 0x53, 0x65, 0x6e, 0x64, 0x45, 0x78, 0x74, 0x65, + 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x44, 0x61, 0x74, 0x61, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, + 0x12, 0x21, 0x0a, 0x0c, 0x65, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x5f, 0x69, 0x64, + 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x65, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, + 0x6e, 0x49, 0x64, 0x12, 0x16, 0x0a, 0x06, 0x62, 0x75, 0x74, 0x74, 0x6f, 0x6e, 0x18, 0x02, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x06, 0x62, 0x75, 0x74, 0x74, 0x6f, 0x6e, 0x12, 0x42, 0x0a, 0x04, 0x64, + 0x61, 0x74, 0x61, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2e, 0x2e, 0x68, 0x69, 0x64, 0x64, + 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, 0x53, 0x65, 0x6e, 0x64, 0x45, 0x78, 0x74, 0x65, 0x6e, + 0x73, 0x69, 0x6f, 0x6e, 0x44, 0x61, 0x74, 0x61, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, + 0x44, 0x61, 0x74, 0x61, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x04, 0x64, 0x61, 0x74, 0x61, 0x1a, + 0x37, 0x0a, 0x09, 0x44, 0x61, 0x74, 0x61, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, + 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x14, + 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, + 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x22, 0x86, 0x01, 0x0a, 0x11, 0x45, 0x78, 0x74, + 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x35, + 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x21, 0x2e, 0x68, + 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73, + 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x54, 0x79, 0x70, 0x65, 0x52, + 0x04, 0x74, 0x79, 0x70, 0x65, 0x12, 0x21, 0x0a, 0x0c, 0x65, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, + 0x6f, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x65, 0x78, 0x74, + 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x49, 0x64, 0x12, 0x17, 0x0a, 0x07, 0x6a, 0x73, 0x6f, 0x6e, + 0x5f, 0x75, 0x69, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x6a, 0x73, 0x6f, 0x6e, 0x55, + 0x69, 0x2a, 0x4d, 0x0a, 0x15, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x65, + 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x54, 0x79, 0x70, 0x65, 0x12, 0x0b, 0x0a, 0x07, 0x4e, 0x4f, + 0x54, 0x48, 0x49, 0x4e, 0x47, 0x10, 0x00, 0x12, 0x0d, 0x0a, 0x09, 0x55, 0x50, 0x44, 0x41, 0x54, + 0x45, 0x5f, 0x55, 0x49, 0x10, 0x01, 0x12, 0x0f, 0x0a, 0x0b, 0x53, 0x48, 0x4f, 0x57, 0x5f, 0x44, + 0x49, 0x41, 0x4c, 0x4f, 0x47, 0x10, 0x02, 0x12, 0x07, 0x0a, 0x03, 0x45, 0x4e, 0x44, 0x10, 0x03, + 0x32, 0xed, 0x03, 0x0a, 0x14, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x48, 0x6f, + 0x73, 0x74, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x40, 0x0a, 0x0e, 0x4c, 0x69, 0x73, + 0x74, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x11, 0x2e, 0x68, 0x69, + 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a, 0x19, + 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, 0x45, 0x78, 0x74, 0x65, + 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x4c, 0x69, 0x73, 0x74, 0x22, 0x00, 0x12, 0x4a, 0x0a, 0x07, 0x43, + 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x12, 0x1c, 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, + 0x72, 0x70, 0x63, 0x2e, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x71, + 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1d, 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, + 0x63, 0x2e, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x6f, + 0x6e, 0x73, 0x65, 0x22, 0x00, 0x30, 0x01, 0x12, 0x56, 0x0a, 0x0d, 0x45, 0x64, 0x69, 0x74, 0x45, + 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x20, 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, + 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, 0x45, 0x64, 0x69, 0x74, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73, + 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x21, 0x2e, 0x68, 0x69, 0x64, + 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, + 0x6e, 0x41, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x22, 0x00, 0x12, + 0x57, 0x0a, 0x0a, 0x53, 0x75, 0x62, 0x6d, 0x69, 0x74, 0x46, 0x6f, 0x72, 0x6d, 0x12, 0x24, 0x2e, + 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, 0x53, 0x65, 0x6e, 0x64, 0x45, + 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x44, 0x61, 0x74, 0x61, 0x52, 0x65, 0x71, 0x75, + 0x65, 0x73, 0x74, 0x1a, 0x21, 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, + 0x2e, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x41, 0x63, 0x74, 0x69, 0x6f, 0x6e, + 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x22, 0x00, 0x12, 0x4a, 0x0a, 0x05, 0x43, 0x6c, 0x6f, 0x73, + 0x65, 0x12, 0x1c, 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, 0x45, + 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, + 0x21, 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, 0x45, 0x78, 0x74, + 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x41, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x75, + 0x6c, 0x74, 0x22, 0x00, 0x12, 0x4a, 0x0a, 0x05, 0x47, 0x65, 0x74, 0x55, 0x49, 0x12, 0x1c, 0x2e, + 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, 0x45, 0x78, 0x74, 0x65, 0x6e, + 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x21, 0x2e, 0x68, 0x69, + 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, + 0x6f, 0x6e, 0x41, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x22, 0x00, + 0x42, 0x0e, 0x5a, 0x0c, 0x2e, 0x2f, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, + 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_extension_proto_rawDescOnce sync.Once + file_extension_proto_rawDescData = file_extension_proto_rawDesc +) + +func file_extension_proto_rawDescGZIP() []byte { + file_extension_proto_rawDescOnce.Do(func() { + file_extension_proto_rawDescData = protoimpl.X.CompressGZIP(file_extension_proto_rawDescData) + }) + return file_extension_proto_rawDescData +} + +var file_extension_proto_enumTypes = make([]protoimpl.EnumInfo, 1) +var file_extension_proto_msgTypes = make([]protoimpl.MessageInfo, 9) +var file_extension_proto_goTypes = []any{ + (ExtensionResponseType)(0), // 0: hiddifyrpc.ExtensionResponseType + (*ExtensionActionResult)(nil), // 1: hiddifyrpc.ExtensionActionResult + (*ExtensionList)(nil), // 2: hiddifyrpc.ExtensionList + (*EditExtensionRequest)(nil), // 3: hiddifyrpc.EditExtensionRequest + (*Extension)(nil), // 4: hiddifyrpc.Extension + (*ExtensionRequest)(nil), // 5: hiddifyrpc.ExtensionRequest + (*SendExtensionDataRequest)(nil), // 6: hiddifyrpc.SendExtensionDataRequest + (*ExtensionResponse)(nil), // 7: hiddifyrpc.ExtensionResponse + nil, // 8: hiddifyrpc.ExtensionRequest.DataEntry + nil, // 9: hiddifyrpc.SendExtensionDataRequest.DataEntry + (ResponseCode)(0), // 10: hiddifyrpc.ResponseCode + (*Empty)(nil), // 11: hiddifyrpc.Empty +} +var file_extension_proto_depIdxs = []int32{ + 10, // 0: hiddifyrpc.ExtensionActionResult.code:type_name -> hiddifyrpc.ResponseCode + 4, // 1: hiddifyrpc.ExtensionList.extensions:type_name -> hiddifyrpc.Extension + 8, // 2: hiddifyrpc.ExtensionRequest.data:type_name -> hiddifyrpc.ExtensionRequest.DataEntry + 9, // 3: hiddifyrpc.SendExtensionDataRequest.data:type_name -> hiddifyrpc.SendExtensionDataRequest.DataEntry + 0, // 4: hiddifyrpc.ExtensionResponse.type:type_name -> hiddifyrpc.ExtensionResponseType + 11, // 5: hiddifyrpc.ExtensionHostService.ListExtensions:input_type -> hiddifyrpc.Empty + 5, // 6: hiddifyrpc.ExtensionHostService.Connect:input_type -> hiddifyrpc.ExtensionRequest + 3, // 7: hiddifyrpc.ExtensionHostService.EditExtension:input_type -> hiddifyrpc.EditExtensionRequest + 6, // 8: hiddifyrpc.ExtensionHostService.SubmitForm:input_type -> hiddifyrpc.SendExtensionDataRequest + 5, // 9: hiddifyrpc.ExtensionHostService.Close:input_type -> hiddifyrpc.ExtensionRequest + 5, // 10: hiddifyrpc.ExtensionHostService.GetUI:input_type -> hiddifyrpc.ExtensionRequest + 2, // 11: hiddifyrpc.ExtensionHostService.ListExtensions:output_type -> hiddifyrpc.ExtensionList + 7, // 12: hiddifyrpc.ExtensionHostService.Connect:output_type -> hiddifyrpc.ExtensionResponse + 1, // 13: hiddifyrpc.ExtensionHostService.EditExtension:output_type -> hiddifyrpc.ExtensionActionResult + 1, // 14: hiddifyrpc.ExtensionHostService.SubmitForm:output_type -> hiddifyrpc.ExtensionActionResult + 1, // 15: hiddifyrpc.ExtensionHostService.Close:output_type -> hiddifyrpc.ExtensionActionResult + 1, // 16: hiddifyrpc.ExtensionHostService.GetUI:output_type -> hiddifyrpc.ExtensionActionResult + 11, // [11:17] is the sub-list for method output_type + 5, // [5:11] is the sub-list for method input_type + 5, // [5:5] is the sub-list for extension type_name + 5, // [5:5] is the sub-list for extension extendee + 0, // [0:5] is the sub-list for field type_name +} + +func init() { file_extension_proto_init() } +func file_extension_proto_init() { + if File_extension_proto != nil { + return + } + file_base_proto_init() + if !protoimpl.UnsafeEnabled { + file_extension_proto_msgTypes[0].Exporter = func(v any, i int) any { + switch v := v.(*ExtensionActionResult); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_extension_proto_msgTypes[1].Exporter = func(v any, i int) any { + switch v := v.(*ExtensionList); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_extension_proto_msgTypes[2].Exporter = func(v any, i int) any { + switch v := v.(*EditExtensionRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_extension_proto_msgTypes[3].Exporter = func(v any, i int) any { + switch v := v.(*Extension); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_extension_proto_msgTypes[4].Exporter = func(v any, i int) any { + switch v := v.(*ExtensionRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_extension_proto_msgTypes[5].Exporter = func(v any, i int) any { + switch v := v.(*SendExtensionDataRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_extension_proto_msgTypes[6].Exporter = func(v any, i int) any { + switch v := v.(*ExtensionResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_extension_proto_rawDesc, + NumEnums: 1, + NumMessages: 9, + NumExtensions: 0, + NumServices: 1, + }, + GoTypes: file_extension_proto_goTypes, + DependencyIndexes: file_extension_proto_depIdxs, + EnumInfos: file_extension_proto_enumTypes, + MessageInfos: file_extension_proto_msgTypes, + }.Build() + File_extension_proto = out.File + file_extension_proto_rawDesc = nil + file_extension_proto_goTypes = nil + file_extension_proto_depIdxs = nil +} diff --git a/libcore/hiddifyrpc/extension.proto b/libcore/hiddifyrpc/extension.proto new file mode 100644 index 0000000..2bbb175 --- /dev/null +++ b/libcore/hiddifyrpc/extension.proto @@ -0,0 +1,66 @@ +syntax = "proto3"; + +import "base.proto"; + +package hiddifyrpc; + +option go_package = "./hiddifyrpc"; + +service ExtensionHostService { + rpc ListExtensions (Empty) returns (ExtensionList) {} + rpc Connect (ExtensionRequest) returns (stream ExtensionResponse) {} + rpc EditExtension (EditExtensionRequest) returns (ExtensionActionResult) {} + rpc SubmitForm (SendExtensionDataRequest) returns (ExtensionActionResult) {} + rpc Close (ExtensionRequest) returns (ExtensionActionResult) {} + + rpc GetUI (ExtensionRequest) returns (ExtensionActionResult) {} +} + +message ExtensionActionResult { + string extension_id = 1; + ResponseCode code = 2; + string message = 3; +} + +message ExtensionList { + repeated Extension extensions = 1; +} + +message EditExtensionRequest { + string extension_id = 1; + bool enable = 2; +} + +message Extension { + string id = 1; + string title = 2; + string description = 3; + bool enable = 4; +} + +message ExtensionRequest { + string extension_id = 1; + map data = 2; +} + +message SendExtensionDataRequest { + string extension_id = 1; + string button=2; + map data = 3; +} + +message ExtensionResponse { + ExtensionResponseType type = 1; + string extension_id = 2; + string json_ui = 3; +} + + +enum ExtensionResponseType { + NOTHING = 0; + UPDATE_UI = 1; + SHOW_DIALOG = 2; + END=3; +} + + diff --git a/libcore/hiddifyrpc/extension_grpc.pb.go b/libcore/hiddifyrpc/extension_grpc.pb.go new file mode 100644 index 0000000..847d992 --- /dev/null +++ b/libcore/hiddifyrpc/extension_grpc.pb.go @@ -0,0 +1,315 @@ +// Code generated by protoc-gen-go-grpc. DO NOT EDIT. +// versions: +// - protoc-gen-go-grpc v1.5.1 +// - protoc v5.28.0 +// source: extension.proto + +package hiddifyrpc + +import ( + context "context" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" +) + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +// Requires gRPC-Go v1.64.0 or later. +const _ = grpc.SupportPackageIsVersion9 + +const ( + ExtensionHostService_ListExtensions_FullMethodName = "/hiddifyrpc.ExtensionHostService/ListExtensions" + ExtensionHostService_Connect_FullMethodName = "/hiddifyrpc.ExtensionHostService/Connect" + ExtensionHostService_EditExtension_FullMethodName = "/hiddifyrpc.ExtensionHostService/EditExtension" + ExtensionHostService_SubmitForm_FullMethodName = "/hiddifyrpc.ExtensionHostService/SubmitForm" + ExtensionHostService_Close_FullMethodName = "/hiddifyrpc.ExtensionHostService/Close" + ExtensionHostService_GetUI_FullMethodName = "/hiddifyrpc.ExtensionHostService/GetUI" +) + +// ExtensionHostServiceClient is the client API for ExtensionHostService service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +type ExtensionHostServiceClient interface { + ListExtensions(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*ExtensionList, error) + Connect(ctx context.Context, in *ExtensionRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[ExtensionResponse], error) + EditExtension(ctx context.Context, in *EditExtensionRequest, opts ...grpc.CallOption) (*ExtensionActionResult, error) + SubmitForm(ctx context.Context, in *SendExtensionDataRequest, opts ...grpc.CallOption) (*ExtensionActionResult, error) + Close(ctx context.Context, in *ExtensionRequest, opts ...grpc.CallOption) (*ExtensionActionResult, error) + GetUI(ctx context.Context, in *ExtensionRequest, opts ...grpc.CallOption) (*ExtensionActionResult, error) +} + +type extensionHostServiceClient struct { + cc grpc.ClientConnInterface +} + +func NewExtensionHostServiceClient(cc grpc.ClientConnInterface) ExtensionHostServiceClient { + return &extensionHostServiceClient{cc} +} + +func (c *extensionHostServiceClient) ListExtensions(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*ExtensionList, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(ExtensionList) + err := c.cc.Invoke(ctx, ExtensionHostService_ListExtensions_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *extensionHostServiceClient) Connect(ctx context.Context, in *ExtensionRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[ExtensionResponse], error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + stream, err := c.cc.NewStream(ctx, &ExtensionHostService_ServiceDesc.Streams[0], ExtensionHostService_Connect_FullMethodName, cOpts...) + if err != nil { + return nil, err + } + x := &grpc.GenericClientStream[ExtensionRequest, ExtensionResponse]{ClientStream: stream} + if err := x.ClientStream.SendMsg(in); err != nil { + return nil, err + } + if err := x.ClientStream.CloseSend(); err != nil { + return nil, err + } + return x, nil +} + +// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name. +type ExtensionHostService_ConnectClient = grpc.ServerStreamingClient[ExtensionResponse] + +func (c *extensionHostServiceClient) EditExtension(ctx context.Context, in *EditExtensionRequest, opts ...grpc.CallOption) (*ExtensionActionResult, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(ExtensionActionResult) + err := c.cc.Invoke(ctx, ExtensionHostService_EditExtension_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *extensionHostServiceClient) SubmitForm(ctx context.Context, in *SendExtensionDataRequest, opts ...grpc.CallOption) (*ExtensionActionResult, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(ExtensionActionResult) + err := c.cc.Invoke(ctx, ExtensionHostService_SubmitForm_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *extensionHostServiceClient) Close(ctx context.Context, in *ExtensionRequest, opts ...grpc.CallOption) (*ExtensionActionResult, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(ExtensionActionResult) + err := c.cc.Invoke(ctx, ExtensionHostService_Close_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *extensionHostServiceClient) GetUI(ctx context.Context, in *ExtensionRequest, opts ...grpc.CallOption) (*ExtensionActionResult, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(ExtensionActionResult) + err := c.cc.Invoke(ctx, ExtensionHostService_GetUI_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +// ExtensionHostServiceServer is the server API for ExtensionHostService service. +// All implementations must embed UnimplementedExtensionHostServiceServer +// for forward compatibility. +type ExtensionHostServiceServer interface { + ListExtensions(context.Context, *Empty) (*ExtensionList, error) + Connect(*ExtensionRequest, grpc.ServerStreamingServer[ExtensionResponse]) error + EditExtension(context.Context, *EditExtensionRequest) (*ExtensionActionResult, error) + SubmitForm(context.Context, *SendExtensionDataRequest) (*ExtensionActionResult, error) + Close(context.Context, *ExtensionRequest) (*ExtensionActionResult, error) + GetUI(context.Context, *ExtensionRequest) (*ExtensionActionResult, error) + mustEmbedUnimplementedExtensionHostServiceServer() +} + +// UnimplementedExtensionHostServiceServer must be embedded to have +// forward compatible implementations. +// +// NOTE: this should be embedded by value instead of pointer to avoid a nil +// pointer dereference when methods are called. +type UnimplementedExtensionHostServiceServer struct{} + +func (UnimplementedExtensionHostServiceServer) ListExtensions(context.Context, *Empty) (*ExtensionList, error) { + return nil, status.Errorf(codes.Unimplemented, "method ListExtensions not implemented") +} +func (UnimplementedExtensionHostServiceServer) Connect(*ExtensionRequest, grpc.ServerStreamingServer[ExtensionResponse]) error { + return status.Errorf(codes.Unimplemented, "method Connect not implemented") +} +func (UnimplementedExtensionHostServiceServer) EditExtension(context.Context, *EditExtensionRequest) (*ExtensionActionResult, error) { + return nil, status.Errorf(codes.Unimplemented, "method EditExtension not implemented") +} +func (UnimplementedExtensionHostServiceServer) SubmitForm(context.Context, *SendExtensionDataRequest) (*ExtensionActionResult, error) { + return nil, status.Errorf(codes.Unimplemented, "method SubmitForm not implemented") +} +func (UnimplementedExtensionHostServiceServer) Close(context.Context, *ExtensionRequest) (*ExtensionActionResult, error) { + return nil, status.Errorf(codes.Unimplemented, "method Close not implemented") +} +func (UnimplementedExtensionHostServiceServer) GetUI(context.Context, *ExtensionRequest) (*ExtensionActionResult, error) { + return nil, status.Errorf(codes.Unimplemented, "method GetUI not implemented") +} +func (UnimplementedExtensionHostServiceServer) mustEmbedUnimplementedExtensionHostServiceServer() {} +func (UnimplementedExtensionHostServiceServer) testEmbeddedByValue() {} + +// UnsafeExtensionHostServiceServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to ExtensionHostServiceServer will +// result in compilation errors. +type UnsafeExtensionHostServiceServer interface { + mustEmbedUnimplementedExtensionHostServiceServer() +} + +func RegisterExtensionHostServiceServer(s grpc.ServiceRegistrar, srv ExtensionHostServiceServer) { + // If the following call pancis, it indicates UnimplementedExtensionHostServiceServer was + // embedded by pointer and is nil. This will cause panics if an + // unimplemented method is ever invoked, so we test this at initialization + // time to prevent it from happening at runtime later due to I/O. + if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { + t.testEmbeddedByValue() + } + s.RegisterService(&ExtensionHostService_ServiceDesc, srv) +} + +func _ExtensionHostService_ListExtensions_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(Empty) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ExtensionHostServiceServer).ListExtensions(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: ExtensionHostService_ListExtensions_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ExtensionHostServiceServer).ListExtensions(ctx, req.(*Empty)) + } + return interceptor(ctx, in, info, handler) +} + +func _ExtensionHostService_Connect_Handler(srv interface{}, stream grpc.ServerStream) error { + m := new(ExtensionRequest) + if err := stream.RecvMsg(m); err != nil { + return err + } + return srv.(ExtensionHostServiceServer).Connect(m, &grpc.GenericServerStream[ExtensionRequest, ExtensionResponse]{ServerStream: stream}) +} + +// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name. +type ExtensionHostService_ConnectServer = grpc.ServerStreamingServer[ExtensionResponse] + +func _ExtensionHostService_EditExtension_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(EditExtensionRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ExtensionHostServiceServer).EditExtension(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: ExtensionHostService_EditExtension_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ExtensionHostServiceServer).EditExtension(ctx, req.(*EditExtensionRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _ExtensionHostService_SubmitForm_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(SendExtensionDataRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ExtensionHostServiceServer).SubmitForm(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: ExtensionHostService_SubmitForm_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ExtensionHostServiceServer).SubmitForm(ctx, req.(*SendExtensionDataRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _ExtensionHostService_Close_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(ExtensionRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ExtensionHostServiceServer).Close(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: ExtensionHostService_Close_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ExtensionHostServiceServer).Close(ctx, req.(*ExtensionRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _ExtensionHostService_GetUI_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(ExtensionRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ExtensionHostServiceServer).GetUI(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: ExtensionHostService_GetUI_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ExtensionHostServiceServer).GetUI(ctx, req.(*ExtensionRequest)) + } + return interceptor(ctx, in, info, handler) +} + +// ExtensionHostService_ServiceDesc is the grpc.ServiceDesc for ExtensionHostService service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var ExtensionHostService_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "hiddifyrpc.ExtensionHostService", + HandlerType: (*ExtensionHostServiceServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "ListExtensions", + Handler: _ExtensionHostService_ListExtensions_Handler, + }, + { + MethodName: "EditExtension", + Handler: _ExtensionHostService_EditExtension_Handler, + }, + { + MethodName: "SubmitForm", + Handler: _ExtensionHostService_SubmitForm_Handler, + }, + { + MethodName: "Close", + Handler: _ExtensionHostService_Close_Handler, + }, + { + MethodName: "GetUI", + Handler: _ExtensionHostService_GetUI_Handler, + }, + }, + Streams: []grpc.StreamDesc{ + { + StreamName: "Connect", + Handler: _ExtensionHostService_Connect_Handler, + ServerStreams: true, + }, + }, + Metadata: "extension.proto", +} diff --git a/libcore/hiddifyrpc/hiddify.pb.go b/libcore/hiddifyrpc/hiddify.pb.go new file mode 100644 index 0000000..40fec00 --- /dev/null +++ b/libcore/hiddifyrpc/hiddify.pb.go @@ -0,0 +1,2584 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.34.2 +// protoc v5.28.0 +// source: hiddify.proto + +package hiddifyrpc + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +type CoreState int32 + +const ( + CoreState_STOPPED CoreState = 0 + CoreState_STARTING CoreState = 1 + CoreState_STARTED CoreState = 2 + CoreState_STOPPING CoreState = 3 +) + +// Enum value maps for CoreState. +var ( + CoreState_name = map[int32]string{ + 0: "STOPPED", + 1: "STARTING", + 2: "STARTED", + 3: "STOPPING", + } + CoreState_value = map[string]int32{ + "STOPPED": 0, + "STARTING": 1, + "STARTED": 2, + "STOPPING": 3, + } +) + +func (x CoreState) Enum() *CoreState { + p := new(CoreState) + *p = x + return p +} + +func (x CoreState) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (CoreState) Descriptor() protoreflect.EnumDescriptor { + return file_hiddify_proto_enumTypes[0].Descriptor() +} + +func (CoreState) Type() protoreflect.EnumType { + return &file_hiddify_proto_enumTypes[0] +} + +func (x CoreState) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use CoreState.Descriptor instead. +func (CoreState) EnumDescriptor() ([]byte, []int) { + return file_hiddify_proto_rawDescGZIP(), []int{0} +} + +type MessageType int32 + +const ( + MessageType_EMPTY MessageType = 0 + MessageType_EMPTY_CONFIGURATION MessageType = 1 + MessageType_START_COMMAND_SERVER MessageType = 2 + MessageType_CREATE_SERVICE MessageType = 3 + MessageType_START_SERVICE MessageType = 4 + MessageType_UNEXPECTED_ERROR MessageType = 5 + MessageType_ALREADY_STARTED MessageType = 6 + MessageType_ALREADY_STOPPED MessageType = 7 + MessageType_INSTANCE_NOT_FOUND MessageType = 8 + MessageType_INSTANCE_NOT_STOPPED MessageType = 9 + MessageType_INSTANCE_NOT_STARTED MessageType = 10 + MessageType_ERROR_BUILDING_CONFIG MessageType = 11 + MessageType_ERROR_PARSING_CONFIG MessageType = 12 + MessageType_ERROR_READING_CONFIG MessageType = 13 +) + +// Enum value maps for MessageType. +var ( + MessageType_name = map[int32]string{ + 0: "EMPTY", + 1: "EMPTY_CONFIGURATION", + 2: "START_COMMAND_SERVER", + 3: "CREATE_SERVICE", + 4: "START_SERVICE", + 5: "UNEXPECTED_ERROR", + 6: "ALREADY_STARTED", + 7: "ALREADY_STOPPED", + 8: "INSTANCE_NOT_FOUND", + 9: "INSTANCE_NOT_STOPPED", + 10: "INSTANCE_NOT_STARTED", + 11: "ERROR_BUILDING_CONFIG", + 12: "ERROR_PARSING_CONFIG", + 13: "ERROR_READING_CONFIG", + } + MessageType_value = map[string]int32{ + "EMPTY": 0, + "EMPTY_CONFIGURATION": 1, + "START_COMMAND_SERVER": 2, + "CREATE_SERVICE": 3, + "START_SERVICE": 4, + "UNEXPECTED_ERROR": 5, + "ALREADY_STARTED": 6, + "ALREADY_STOPPED": 7, + "INSTANCE_NOT_FOUND": 8, + "INSTANCE_NOT_STOPPED": 9, + "INSTANCE_NOT_STARTED": 10, + "ERROR_BUILDING_CONFIG": 11, + "ERROR_PARSING_CONFIG": 12, + "ERROR_READING_CONFIG": 13, + } +) + +func (x MessageType) Enum() *MessageType { + p := new(MessageType) + *p = x + return p +} + +func (x MessageType) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (MessageType) Descriptor() protoreflect.EnumDescriptor { + return file_hiddify_proto_enumTypes[1].Descriptor() +} + +func (MessageType) Type() protoreflect.EnumType { + return &file_hiddify_proto_enumTypes[1] +} + +func (x MessageType) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use MessageType.Descriptor instead. +func (MessageType) EnumDescriptor() ([]byte, []int) { + return file_hiddify_proto_rawDescGZIP(), []int{1} +} + +type LogLevel int32 + +const ( + LogLevel_DEBUG LogLevel = 0 + LogLevel_INFO LogLevel = 1 + LogLevel_WARNING LogLevel = 2 + LogLevel_ERROR LogLevel = 3 + LogLevel_FATAL LogLevel = 4 +) + +// Enum value maps for LogLevel. +var ( + LogLevel_name = map[int32]string{ + 0: "DEBUG", + 1: "INFO", + 2: "WARNING", + 3: "ERROR", + 4: "FATAL", + } + LogLevel_value = map[string]int32{ + "DEBUG": 0, + "INFO": 1, + "WARNING": 2, + "ERROR": 3, + "FATAL": 4, + } +) + +func (x LogLevel) Enum() *LogLevel { + p := new(LogLevel) + *p = x + return p +} + +func (x LogLevel) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (LogLevel) Descriptor() protoreflect.EnumDescriptor { + return file_hiddify_proto_enumTypes[2].Descriptor() +} + +func (LogLevel) Type() protoreflect.EnumType { + return &file_hiddify_proto_enumTypes[2] +} + +func (x LogLevel) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use LogLevel.Descriptor instead. +func (LogLevel) EnumDescriptor() ([]byte, []int) { + return file_hiddify_proto_rawDescGZIP(), []int{2} +} + +type LogType int32 + +const ( + LogType_CORE LogType = 0 + LogType_SERVICE LogType = 1 + LogType_CONFIG LogType = 2 +) + +// Enum value maps for LogType. +var ( + LogType_name = map[int32]string{ + 0: "CORE", + 1: "SERVICE", + 2: "CONFIG", + } + LogType_value = map[string]int32{ + "CORE": 0, + "SERVICE": 1, + "CONFIG": 2, + } +) + +func (x LogType) Enum() *LogType { + p := new(LogType) + *p = x + return p +} + +func (x LogType) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (LogType) Descriptor() protoreflect.EnumDescriptor { + return file_hiddify_proto_enumTypes[3].Descriptor() +} + +func (LogType) Type() protoreflect.EnumType { + return &file_hiddify_proto_enumTypes[3] +} + +func (x LogType) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use LogType.Descriptor instead. +func (LogType) EnumDescriptor() ([]byte, []int) { + return file_hiddify_proto_rawDescGZIP(), []int{3} +} + +type CoreInfoResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + CoreState CoreState `protobuf:"varint,1,opt,name=core_state,json=coreState,proto3,enum=hiddifyrpc.CoreState" json:"core_state,omitempty"` + MessageType MessageType `protobuf:"varint,2,opt,name=message_type,json=messageType,proto3,enum=hiddifyrpc.MessageType" json:"message_type,omitempty"` + Message string `protobuf:"bytes,3,opt,name=message,proto3" json:"message,omitempty"` +} + +func (x *CoreInfoResponse) Reset() { + *x = CoreInfoResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_hiddify_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *CoreInfoResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CoreInfoResponse) ProtoMessage() {} + +func (x *CoreInfoResponse) ProtoReflect() protoreflect.Message { + mi := &file_hiddify_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use CoreInfoResponse.ProtoReflect.Descriptor instead. +func (*CoreInfoResponse) Descriptor() ([]byte, []int) { + return file_hiddify_proto_rawDescGZIP(), []int{0} +} + +func (x *CoreInfoResponse) GetCoreState() CoreState { + if x != nil { + return x.CoreState + } + return CoreState_STOPPED +} + +func (x *CoreInfoResponse) GetMessageType() MessageType { + if x != nil { + return x.MessageType + } + return MessageType_EMPTY +} + +func (x *CoreInfoResponse) GetMessage() string { + if x != nil { + return x.Message + } + return "" +} + +type StartRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + ConfigPath string `protobuf:"bytes,1,opt,name=config_path,json=configPath,proto3" json:"config_path,omitempty"` + ConfigContent string `protobuf:"bytes,2,opt,name=config_content,json=configContent,proto3" json:"config_content,omitempty"` // Optional if configPath is not provided. + DisableMemoryLimit bool `protobuf:"varint,3,opt,name=disable_memory_limit,json=disableMemoryLimit,proto3" json:"disable_memory_limit,omitempty"` + DelayStart bool `protobuf:"varint,4,opt,name=delay_start,json=delayStart,proto3" json:"delay_start,omitempty"` + EnableOldCommandServer bool `protobuf:"varint,5,opt,name=enable_old_command_server,json=enableOldCommandServer,proto3" json:"enable_old_command_server,omitempty"` + EnableRawConfig bool `protobuf:"varint,6,opt,name=enable_raw_config,json=enableRawConfig,proto3" json:"enable_raw_config,omitempty"` +} + +func (x *StartRequest) Reset() { + *x = StartRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_hiddify_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *StartRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*StartRequest) ProtoMessage() {} + +func (x *StartRequest) ProtoReflect() protoreflect.Message { + mi := &file_hiddify_proto_msgTypes[1] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use StartRequest.ProtoReflect.Descriptor instead. +func (*StartRequest) Descriptor() ([]byte, []int) { + return file_hiddify_proto_rawDescGZIP(), []int{1} +} + +func (x *StartRequest) GetConfigPath() string { + if x != nil { + return x.ConfigPath + } + return "" +} + +func (x *StartRequest) GetConfigContent() string { + if x != nil { + return x.ConfigContent + } + return "" +} + +func (x *StartRequest) GetDisableMemoryLimit() bool { + if x != nil { + return x.DisableMemoryLimit + } + return false +} + +func (x *StartRequest) GetDelayStart() bool { + if x != nil { + return x.DelayStart + } + return false +} + +func (x *StartRequest) GetEnableOldCommandServer() bool { + if x != nil { + return x.EnableOldCommandServer + } + return false +} + +func (x *StartRequest) GetEnableRawConfig() bool { + if x != nil { + return x.EnableRawConfig + } + return false +} + +type SetupRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + BasePath string `protobuf:"bytes,1,opt,name=base_path,json=basePath,proto3" json:"base_path,omitempty"` + WorkingPath string `protobuf:"bytes,2,opt,name=working_path,json=workingPath,proto3" json:"working_path,omitempty"` + TempPath string `protobuf:"bytes,3,opt,name=temp_path,json=tempPath,proto3" json:"temp_path,omitempty"` +} + +func (x *SetupRequest) Reset() { + *x = SetupRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_hiddify_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *SetupRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SetupRequest) ProtoMessage() {} + +func (x *SetupRequest) ProtoReflect() protoreflect.Message { + mi := &file_hiddify_proto_msgTypes[2] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SetupRequest.ProtoReflect.Descriptor instead. +func (*SetupRequest) Descriptor() ([]byte, []int) { + return file_hiddify_proto_rawDescGZIP(), []int{2} +} + +func (x *SetupRequest) GetBasePath() string { + if x != nil { + return x.BasePath + } + return "" +} + +func (x *SetupRequest) GetWorkingPath() string { + if x != nil { + return x.WorkingPath + } + return "" +} + +func (x *SetupRequest) GetTempPath() string { + if x != nil { + return x.TempPath + } + return "" +} + +type Response struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + ResponseCode ResponseCode `protobuf:"varint,1,opt,name=response_code,json=responseCode,proto3,enum=hiddifyrpc.ResponseCode" json:"response_code,omitempty"` + Message string `protobuf:"bytes,2,opt,name=message,proto3" json:"message,omitempty"` +} + +func (x *Response) Reset() { + *x = Response{} + if protoimpl.UnsafeEnabled { + mi := &file_hiddify_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Response) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Response) ProtoMessage() {} + +func (x *Response) ProtoReflect() protoreflect.Message { + mi := &file_hiddify_proto_msgTypes[3] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Response.ProtoReflect.Descriptor instead. +func (*Response) Descriptor() ([]byte, []int) { + return file_hiddify_proto_rawDescGZIP(), []int{3} +} + +func (x *Response) GetResponseCode() ResponseCode { + if x != nil { + return x.ResponseCode + } + return ResponseCode_OK +} + +func (x *Response) GetMessage() string { + if x != nil { + return x.Message + } + return "" +} + +type SystemInfo struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Memory int64 `protobuf:"varint,1,opt,name=memory,proto3" json:"memory,omitempty"` + Goroutines int32 `protobuf:"varint,2,opt,name=goroutines,proto3" json:"goroutines,omitempty"` + ConnectionsIn int32 `protobuf:"varint,3,opt,name=connections_in,json=connectionsIn,proto3" json:"connections_in,omitempty"` + ConnectionsOut int32 `protobuf:"varint,4,opt,name=connections_out,json=connectionsOut,proto3" json:"connections_out,omitempty"` + TrafficAvailable bool `protobuf:"varint,5,opt,name=traffic_available,json=trafficAvailable,proto3" json:"traffic_available,omitempty"` + Uplink int64 `protobuf:"varint,6,opt,name=uplink,proto3" json:"uplink,omitempty"` + Downlink int64 `protobuf:"varint,7,opt,name=downlink,proto3" json:"downlink,omitempty"` + UplinkTotal int64 `protobuf:"varint,8,opt,name=uplink_total,json=uplinkTotal,proto3" json:"uplink_total,omitempty"` + DownlinkTotal int64 `protobuf:"varint,9,opt,name=downlink_total,json=downlinkTotal,proto3" json:"downlink_total,omitempty"` +} + +func (x *SystemInfo) Reset() { + *x = SystemInfo{} + if protoimpl.UnsafeEnabled { + mi := &file_hiddify_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *SystemInfo) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SystemInfo) ProtoMessage() {} + +func (x *SystemInfo) ProtoReflect() protoreflect.Message { + mi := &file_hiddify_proto_msgTypes[4] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SystemInfo.ProtoReflect.Descriptor instead. +func (*SystemInfo) Descriptor() ([]byte, []int) { + return file_hiddify_proto_rawDescGZIP(), []int{4} +} + +func (x *SystemInfo) GetMemory() int64 { + if x != nil { + return x.Memory + } + return 0 +} + +func (x *SystemInfo) GetGoroutines() int32 { + if x != nil { + return x.Goroutines + } + return 0 +} + +func (x *SystemInfo) GetConnectionsIn() int32 { + if x != nil { + return x.ConnectionsIn + } + return 0 +} + +func (x *SystemInfo) GetConnectionsOut() int32 { + if x != nil { + return x.ConnectionsOut + } + return 0 +} + +func (x *SystemInfo) GetTrafficAvailable() bool { + if x != nil { + return x.TrafficAvailable + } + return false +} + +func (x *SystemInfo) GetUplink() int64 { + if x != nil { + return x.Uplink + } + return 0 +} + +func (x *SystemInfo) GetDownlink() int64 { + if x != nil { + return x.Downlink + } + return 0 +} + +func (x *SystemInfo) GetUplinkTotal() int64 { + if x != nil { + return x.UplinkTotal + } + return 0 +} + +func (x *SystemInfo) GetDownlinkTotal() int64 { + if x != nil { + return x.DownlinkTotal + } + return 0 +} + +type OutboundGroupItem struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Tag string `protobuf:"bytes,1,opt,name=tag,proto3" json:"tag,omitempty"` + Type string `protobuf:"bytes,2,opt,name=type,proto3" json:"type,omitempty"` + UrlTestTime int64 `protobuf:"varint,3,opt,name=url_test_time,json=urlTestTime,proto3" json:"url_test_time,omitempty"` + UrlTestDelay int32 `protobuf:"varint,4,opt,name=url_test_delay,json=urlTestDelay,proto3" json:"url_test_delay,omitempty"` +} + +func (x *OutboundGroupItem) Reset() { + *x = OutboundGroupItem{} + if protoimpl.UnsafeEnabled { + mi := &file_hiddify_proto_msgTypes[5] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *OutboundGroupItem) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*OutboundGroupItem) ProtoMessage() {} + +func (x *OutboundGroupItem) ProtoReflect() protoreflect.Message { + mi := &file_hiddify_proto_msgTypes[5] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use OutboundGroupItem.ProtoReflect.Descriptor instead. +func (*OutboundGroupItem) Descriptor() ([]byte, []int) { + return file_hiddify_proto_rawDescGZIP(), []int{5} +} + +func (x *OutboundGroupItem) GetTag() string { + if x != nil { + return x.Tag + } + return "" +} + +func (x *OutboundGroupItem) GetType() string { + if x != nil { + return x.Type + } + return "" +} + +func (x *OutboundGroupItem) GetUrlTestTime() int64 { + if x != nil { + return x.UrlTestTime + } + return 0 +} + +func (x *OutboundGroupItem) GetUrlTestDelay() int32 { + if x != nil { + return x.UrlTestDelay + } + return 0 +} + +type OutboundGroup struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Tag string `protobuf:"bytes,1,opt,name=tag,proto3" json:"tag,omitempty"` + Type string `protobuf:"bytes,2,opt,name=type,proto3" json:"type,omitempty"` + Selected string `protobuf:"bytes,3,opt,name=selected,proto3" json:"selected,omitempty"` + Items []*OutboundGroupItem `protobuf:"bytes,4,rep,name=items,proto3" json:"items,omitempty"` +} + +func (x *OutboundGroup) Reset() { + *x = OutboundGroup{} + if protoimpl.UnsafeEnabled { + mi := &file_hiddify_proto_msgTypes[6] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *OutboundGroup) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*OutboundGroup) ProtoMessage() {} + +func (x *OutboundGroup) ProtoReflect() protoreflect.Message { + mi := &file_hiddify_proto_msgTypes[6] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use OutboundGroup.ProtoReflect.Descriptor instead. +func (*OutboundGroup) Descriptor() ([]byte, []int) { + return file_hiddify_proto_rawDescGZIP(), []int{6} +} + +func (x *OutboundGroup) GetTag() string { + if x != nil { + return x.Tag + } + return "" +} + +func (x *OutboundGroup) GetType() string { + if x != nil { + return x.Type + } + return "" +} + +func (x *OutboundGroup) GetSelected() string { + if x != nil { + return x.Selected + } + return "" +} + +func (x *OutboundGroup) GetItems() []*OutboundGroupItem { + if x != nil { + return x.Items + } + return nil +} + +type OutboundGroupList struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Items []*OutboundGroup `protobuf:"bytes,1,rep,name=items,proto3" json:"items,omitempty"` +} + +func (x *OutboundGroupList) Reset() { + *x = OutboundGroupList{} + if protoimpl.UnsafeEnabled { + mi := &file_hiddify_proto_msgTypes[7] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *OutboundGroupList) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*OutboundGroupList) ProtoMessage() {} + +func (x *OutboundGroupList) ProtoReflect() protoreflect.Message { + mi := &file_hiddify_proto_msgTypes[7] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use OutboundGroupList.ProtoReflect.Descriptor instead. +func (*OutboundGroupList) Descriptor() ([]byte, []int) { + return file_hiddify_proto_rawDescGZIP(), []int{7} +} + +func (x *OutboundGroupList) GetItems() []*OutboundGroup { + if x != nil { + return x.Items + } + return nil +} + +type WarpAccount struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + AccountId string `protobuf:"bytes,1,opt,name=account_id,json=accountId,proto3" json:"account_id,omitempty"` + AccessToken string `protobuf:"bytes,2,opt,name=access_token,json=accessToken,proto3" json:"access_token,omitempty"` +} + +func (x *WarpAccount) Reset() { + *x = WarpAccount{} + if protoimpl.UnsafeEnabled { + mi := &file_hiddify_proto_msgTypes[8] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *WarpAccount) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*WarpAccount) ProtoMessage() {} + +func (x *WarpAccount) ProtoReflect() protoreflect.Message { + mi := &file_hiddify_proto_msgTypes[8] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use WarpAccount.ProtoReflect.Descriptor instead. +func (*WarpAccount) Descriptor() ([]byte, []int) { + return file_hiddify_proto_rawDescGZIP(), []int{8} +} + +func (x *WarpAccount) GetAccountId() string { + if x != nil { + return x.AccountId + } + return "" +} + +func (x *WarpAccount) GetAccessToken() string { + if x != nil { + return x.AccessToken + } + return "" +} + +type WarpWireguardConfig struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + PrivateKey string `protobuf:"bytes,1,opt,name=private_key,json=privateKey,proto3" json:"private_key,omitempty"` + LocalAddressIpv4 string `protobuf:"bytes,2,opt,name=local_address_ipv4,json=localAddressIpv4,proto3" json:"local_address_ipv4,omitempty"` + LocalAddressIpv6 string `protobuf:"bytes,3,opt,name=local_address_ipv6,json=localAddressIpv6,proto3" json:"local_address_ipv6,omitempty"` + PeerPublicKey string `protobuf:"bytes,4,opt,name=peer_public_key,json=peerPublicKey,proto3" json:"peer_public_key,omitempty"` + ClientId string `protobuf:"bytes,5,opt,name=client_id,json=clientId,proto3" json:"client_id,omitempty"` +} + +func (x *WarpWireguardConfig) Reset() { + *x = WarpWireguardConfig{} + if protoimpl.UnsafeEnabled { + mi := &file_hiddify_proto_msgTypes[9] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *WarpWireguardConfig) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*WarpWireguardConfig) ProtoMessage() {} + +func (x *WarpWireguardConfig) ProtoReflect() protoreflect.Message { + mi := &file_hiddify_proto_msgTypes[9] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use WarpWireguardConfig.ProtoReflect.Descriptor instead. +func (*WarpWireguardConfig) Descriptor() ([]byte, []int) { + return file_hiddify_proto_rawDescGZIP(), []int{9} +} + +func (x *WarpWireguardConfig) GetPrivateKey() string { + if x != nil { + return x.PrivateKey + } + return "" +} + +func (x *WarpWireguardConfig) GetLocalAddressIpv4() string { + if x != nil { + return x.LocalAddressIpv4 + } + return "" +} + +func (x *WarpWireguardConfig) GetLocalAddressIpv6() string { + if x != nil { + return x.LocalAddressIpv6 + } + return "" +} + +func (x *WarpWireguardConfig) GetPeerPublicKey() string { + if x != nil { + return x.PeerPublicKey + } + return "" +} + +func (x *WarpWireguardConfig) GetClientId() string { + if x != nil { + return x.ClientId + } + return "" +} + +type WarpGenerationResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Account *WarpAccount `protobuf:"bytes,1,opt,name=account,proto3" json:"account,omitempty"` + Log string `protobuf:"bytes,2,opt,name=log,proto3" json:"log,omitempty"` + Config *WarpWireguardConfig `protobuf:"bytes,3,opt,name=config,proto3" json:"config,omitempty"` +} + +func (x *WarpGenerationResponse) Reset() { + *x = WarpGenerationResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_hiddify_proto_msgTypes[10] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *WarpGenerationResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*WarpGenerationResponse) ProtoMessage() {} + +func (x *WarpGenerationResponse) ProtoReflect() protoreflect.Message { + mi := &file_hiddify_proto_msgTypes[10] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use WarpGenerationResponse.ProtoReflect.Descriptor instead. +func (*WarpGenerationResponse) Descriptor() ([]byte, []int) { + return file_hiddify_proto_rawDescGZIP(), []int{10} +} + +func (x *WarpGenerationResponse) GetAccount() *WarpAccount { + if x != nil { + return x.Account + } + return nil +} + +func (x *WarpGenerationResponse) GetLog() string { + if x != nil { + return x.Log + } + return "" +} + +func (x *WarpGenerationResponse) GetConfig() *WarpWireguardConfig { + if x != nil { + return x.Config + } + return nil +} + +type SystemProxyStatus struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Available bool `protobuf:"varint,1,opt,name=available,proto3" json:"available,omitempty"` + Enabled bool `protobuf:"varint,2,opt,name=enabled,proto3" json:"enabled,omitempty"` +} + +func (x *SystemProxyStatus) Reset() { + *x = SystemProxyStatus{} + if protoimpl.UnsafeEnabled { + mi := &file_hiddify_proto_msgTypes[11] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *SystemProxyStatus) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SystemProxyStatus) ProtoMessage() {} + +func (x *SystemProxyStatus) ProtoReflect() protoreflect.Message { + mi := &file_hiddify_proto_msgTypes[11] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SystemProxyStatus.ProtoReflect.Descriptor instead. +func (*SystemProxyStatus) Descriptor() ([]byte, []int) { + return file_hiddify_proto_rawDescGZIP(), []int{11} +} + +func (x *SystemProxyStatus) GetAvailable() bool { + if x != nil { + return x.Available + } + return false +} + +func (x *SystemProxyStatus) GetEnabled() bool { + if x != nil { + return x.Enabled + } + return false +} + +type ParseRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Content string `protobuf:"bytes,1,opt,name=content,proto3" json:"content,omitempty"` + ConfigPath string `protobuf:"bytes,2,opt,name=config_path,json=configPath,proto3" json:"config_path,omitempty"` + TempPath string `protobuf:"bytes,3,opt,name=temp_path,json=tempPath,proto3" json:"temp_path,omitempty"` + Debug bool `protobuf:"varint,4,opt,name=debug,proto3" json:"debug,omitempty"` +} + +func (x *ParseRequest) Reset() { + *x = ParseRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_hiddify_proto_msgTypes[12] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ParseRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ParseRequest) ProtoMessage() {} + +func (x *ParseRequest) ProtoReflect() protoreflect.Message { + mi := &file_hiddify_proto_msgTypes[12] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ParseRequest.ProtoReflect.Descriptor instead. +func (*ParseRequest) Descriptor() ([]byte, []int) { + return file_hiddify_proto_rawDescGZIP(), []int{12} +} + +func (x *ParseRequest) GetContent() string { + if x != nil { + return x.Content + } + return "" +} + +func (x *ParseRequest) GetConfigPath() string { + if x != nil { + return x.ConfigPath + } + return "" +} + +func (x *ParseRequest) GetTempPath() string { + if x != nil { + return x.TempPath + } + return "" +} + +func (x *ParseRequest) GetDebug() bool { + if x != nil { + return x.Debug + } + return false +} + +type ParseResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + ResponseCode ResponseCode `protobuf:"varint,1,opt,name=response_code,json=responseCode,proto3,enum=hiddifyrpc.ResponseCode" json:"response_code,omitempty"` + Content string `protobuf:"bytes,2,opt,name=content,proto3" json:"content,omitempty"` + Message string `protobuf:"bytes,3,opt,name=message,proto3" json:"message,omitempty"` +} + +func (x *ParseResponse) Reset() { + *x = ParseResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_hiddify_proto_msgTypes[13] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ParseResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ParseResponse) ProtoMessage() {} + +func (x *ParseResponse) ProtoReflect() protoreflect.Message { + mi := &file_hiddify_proto_msgTypes[13] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ParseResponse.ProtoReflect.Descriptor instead. +func (*ParseResponse) Descriptor() ([]byte, []int) { + return file_hiddify_proto_rawDescGZIP(), []int{13} +} + +func (x *ParseResponse) GetResponseCode() ResponseCode { + if x != nil { + return x.ResponseCode + } + return ResponseCode_OK +} + +func (x *ParseResponse) GetContent() string { + if x != nil { + return x.Content + } + return "" +} + +func (x *ParseResponse) GetMessage() string { + if x != nil { + return x.Message + } + return "" +} + +type ChangeHiddifySettingsRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + HiddifySettingsJson string `protobuf:"bytes,1,opt,name=hiddify_settings_json,json=hiddifySettingsJson,proto3" json:"hiddify_settings_json,omitempty"` +} + +func (x *ChangeHiddifySettingsRequest) Reset() { + *x = ChangeHiddifySettingsRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_hiddify_proto_msgTypes[14] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ChangeHiddifySettingsRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ChangeHiddifySettingsRequest) ProtoMessage() {} + +func (x *ChangeHiddifySettingsRequest) ProtoReflect() protoreflect.Message { + mi := &file_hiddify_proto_msgTypes[14] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ChangeHiddifySettingsRequest.ProtoReflect.Descriptor instead. +func (*ChangeHiddifySettingsRequest) Descriptor() ([]byte, []int) { + return file_hiddify_proto_rawDescGZIP(), []int{14} +} + +func (x *ChangeHiddifySettingsRequest) GetHiddifySettingsJson() string { + if x != nil { + return x.HiddifySettingsJson + } + return "" +} + +type GenerateConfigRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Path string `protobuf:"bytes,1,opt,name=path,proto3" json:"path,omitempty"` + TempPath string `protobuf:"bytes,2,opt,name=temp_path,json=tempPath,proto3" json:"temp_path,omitempty"` + Debug bool `protobuf:"varint,3,opt,name=debug,proto3" json:"debug,omitempty"` +} + +func (x *GenerateConfigRequest) Reset() { + *x = GenerateConfigRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_hiddify_proto_msgTypes[15] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *GenerateConfigRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GenerateConfigRequest) ProtoMessage() {} + +func (x *GenerateConfigRequest) ProtoReflect() protoreflect.Message { + mi := &file_hiddify_proto_msgTypes[15] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GenerateConfigRequest.ProtoReflect.Descriptor instead. +func (*GenerateConfigRequest) Descriptor() ([]byte, []int) { + return file_hiddify_proto_rawDescGZIP(), []int{15} +} + +func (x *GenerateConfigRequest) GetPath() string { + if x != nil { + return x.Path + } + return "" +} + +func (x *GenerateConfigRequest) GetTempPath() string { + if x != nil { + return x.TempPath + } + return "" +} + +func (x *GenerateConfigRequest) GetDebug() bool { + if x != nil { + return x.Debug + } + return false +} + +type GenerateConfigResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + ConfigContent string `protobuf:"bytes,1,opt,name=config_content,json=configContent,proto3" json:"config_content,omitempty"` +} + +func (x *GenerateConfigResponse) Reset() { + *x = GenerateConfigResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_hiddify_proto_msgTypes[16] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *GenerateConfigResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GenerateConfigResponse) ProtoMessage() {} + +func (x *GenerateConfigResponse) ProtoReflect() protoreflect.Message { + mi := &file_hiddify_proto_msgTypes[16] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GenerateConfigResponse.ProtoReflect.Descriptor instead. +func (*GenerateConfigResponse) Descriptor() ([]byte, []int) { + return file_hiddify_proto_rawDescGZIP(), []int{16} +} + +func (x *GenerateConfigResponse) GetConfigContent() string { + if x != nil { + return x.ConfigContent + } + return "" +} + +type SelectOutboundRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + GroupTag string `protobuf:"bytes,1,opt,name=group_tag,json=groupTag,proto3" json:"group_tag,omitempty"` + OutboundTag string `protobuf:"bytes,2,opt,name=outbound_tag,json=outboundTag,proto3" json:"outbound_tag,omitempty"` +} + +func (x *SelectOutboundRequest) Reset() { + *x = SelectOutboundRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_hiddify_proto_msgTypes[17] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *SelectOutboundRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SelectOutboundRequest) ProtoMessage() {} + +func (x *SelectOutboundRequest) ProtoReflect() protoreflect.Message { + mi := &file_hiddify_proto_msgTypes[17] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SelectOutboundRequest.ProtoReflect.Descriptor instead. +func (*SelectOutboundRequest) Descriptor() ([]byte, []int) { + return file_hiddify_proto_rawDescGZIP(), []int{17} +} + +func (x *SelectOutboundRequest) GetGroupTag() string { + if x != nil { + return x.GroupTag + } + return "" +} + +func (x *SelectOutboundRequest) GetOutboundTag() string { + if x != nil { + return x.OutboundTag + } + return "" +} + +type UrlTestRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + GroupTag string `protobuf:"bytes,1,opt,name=group_tag,json=groupTag,proto3" json:"group_tag,omitempty"` +} + +func (x *UrlTestRequest) Reset() { + *x = UrlTestRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_hiddify_proto_msgTypes[18] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *UrlTestRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*UrlTestRequest) ProtoMessage() {} + +func (x *UrlTestRequest) ProtoReflect() protoreflect.Message { + mi := &file_hiddify_proto_msgTypes[18] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use UrlTestRequest.ProtoReflect.Descriptor instead. +func (*UrlTestRequest) Descriptor() ([]byte, []int) { + return file_hiddify_proto_rawDescGZIP(), []int{18} +} + +func (x *UrlTestRequest) GetGroupTag() string { + if x != nil { + return x.GroupTag + } + return "" +} + +type GenerateWarpConfigRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + LicenseKey string `protobuf:"bytes,1,opt,name=license_key,json=licenseKey,proto3" json:"license_key,omitempty"` + AccountId string `protobuf:"bytes,2,opt,name=account_id,json=accountId,proto3" json:"account_id,omitempty"` + AccessToken string `protobuf:"bytes,3,opt,name=access_token,json=accessToken,proto3" json:"access_token,omitempty"` +} + +func (x *GenerateWarpConfigRequest) Reset() { + *x = GenerateWarpConfigRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_hiddify_proto_msgTypes[19] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *GenerateWarpConfigRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GenerateWarpConfigRequest) ProtoMessage() {} + +func (x *GenerateWarpConfigRequest) ProtoReflect() protoreflect.Message { + mi := &file_hiddify_proto_msgTypes[19] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GenerateWarpConfigRequest.ProtoReflect.Descriptor instead. +func (*GenerateWarpConfigRequest) Descriptor() ([]byte, []int) { + return file_hiddify_proto_rawDescGZIP(), []int{19} +} + +func (x *GenerateWarpConfigRequest) GetLicenseKey() string { + if x != nil { + return x.LicenseKey + } + return "" +} + +func (x *GenerateWarpConfigRequest) GetAccountId() string { + if x != nil { + return x.AccountId + } + return "" +} + +func (x *GenerateWarpConfigRequest) GetAccessToken() string { + if x != nil { + return x.AccessToken + } + return "" +} + +type SetSystemProxyEnabledRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + IsEnabled bool `protobuf:"varint,1,opt,name=is_enabled,json=isEnabled,proto3" json:"is_enabled,omitempty"` +} + +func (x *SetSystemProxyEnabledRequest) Reset() { + *x = SetSystemProxyEnabledRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_hiddify_proto_msgTypes[20] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *SetSystemProxyEnabledRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SetSystemProxyEnabledRequest) ProtoMessage() {} + +func (x *SetSystemProxyEnabledRequest) ProtoReflect() protoreflect.Message { + mi := &file_hiddify_proto_msgTypes[20] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SetSystemProxyEnabledRequest.ProtoReflect.Descriptor instead. +func (*SetSystemProxyEnabledRequest) Descriptor() ([]byte, []int) { + return file_hiddify_proto_rawDescGZIP(), []int{20} +} + +func (x *SetSystemProxyEnabledRequest) GetIsEnabled() bool { + if x != nil { + return x.IsEnabled + } + return false +} + +type LogMessage struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Level LogLevel `protobuf:"varint,1,opt,name=level,proto3,enum=hiddifyrpc.LogLevel" json:"level,omitempty"` + Type LogType `protobuf:"varint,2,opt,name=type,proto3,enum=hiddifyrpc.LogType" json:"type,omitempty"` + Message string `protobuf:"bytes,3,opt,name=message,proto3" json:"message,omitempty"` +} + +func (x *LogMessage) Reset() { + *x = LogMessage{} + if protoimpl.UnsafeEnabled { + mi := &file_hiddify_proto_msgTypes[21] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *LogMessage) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*LogMessage) ProtoMessage() {} + +func (x *LogMessage) ProtoReflect() protoreflect.Message { + mi := &file_hiddify_proto_msgTypes[21] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use LogMessage.ProtoReflect.Descriptor instead. +func (*LogMessage) Descriptor() ([]byte, []int) { + return file_hiddify_proto_rawDescGZIP(), []int{21} +} + +func (x *LogMessage) GetLevel() LogLevel { + if x != nil { + return x.Level + } + return LogLevel_DEBUG +} + +func (x *LogMessage) GetType() LogType { + if x != nil { + return x.Type + } + return LogType_CORE +} + +func (x *LogMessage) GetMessage() string { + if x != nil { + return x.Message + } + return "" +} + +type StopRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields +} + +func (x *StopRequest) Reset() { + *x = StopRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_hiddify_proto_msgTypes[22] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *StopRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*StopRequest) ProtoMessage() {} + +func (x *StopRequest) ProtoReflect() protoreflect.Message { + mi := &file_hiddify_proto_msgTypes[22] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use StopRequest.ProtoReflect.Descriptor instead. +func (*StopRequest) Descriptor() ([]byte, []int) { + return file_hiddify_proto_rawDescGZIP(), []int{22} +} + +type TunnelStartRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Ipv6 bool `protobuf:"varint,1,opt,name=ipv6,proto3" json:"ipv6,omitempty"` + ServerPort int32 `protobuf:"varint,2,opt,name=server_port,json=serverPort,proto3" json:"server_port,omitempty"` + StrictRoute bool `protobuf:"varint,3,opt,name=strict_route,json=strictRoute,proto3" json:"strict_route,omitempty"` + EndpointIndependentNat bool `protobuf:"varint,4,opt,name=endpoint_independent_nat,json=endpointIndependentNat,proto3" json:"endpoint_independent_nat,omitempty"` + Stack string `protobuf:"bytes,5,opt,name=stack,proto3" json:"stack,omitempty"` +} + +func (x *TunnelStartRequest) Reset() { + *x = TunnelStartRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_hiddify_proto_msgTypes[23] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *TunnelStartRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*TunnelStartRequest) ProtoMessage() {} + +func (x *TunnelStartRequest) ProtoReflect() protoreflect.Message { + mi := &file_hiddify_proto_msgTypes[23] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use TunnelStartRequest.ProtoReflect.Descriptor instead. +func (*TunnelStartRequest) Descriptor() ([]byte, []int) { + return file_hiddify_proto_rawDescGZIP(), []int{23} +} + +func (x *TunnelStartRequest) GetIpv6() bool { + if x != nil { + return x.Ipv6 + } + return false +} + +func (x *TunnelStartRequest) GetServerPort() int32 { + if x != nil { + return x.ServerPort + } + return 0 +} + +func (x *TunnelStartRequest) GetStrictRoute() bool { + if x != nil { + return x.StrictRoute + } + return false +} + +func (x *TunnelStartRequest) GetEndpointIndependentNat() bool { + if x != nil { + return x.EndpointIndependentNat + } + return false +} + +func (x *TunnelStartRequest) GetStack() string { + if x != nil { + return x.Stack + } + return "" +} + +type TunnelResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Message string `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"` +} + +func (x *TunnelResponse) Reset() { + *x = TunnelResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_hiddify_proto_msgTypes[24] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *TunnelResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*TunnelResponse) ProtoMessage() {} + +func (x *TunnelResponse) ProtoReflect() protoreflect.Message { + mi := &file_hiddify_proto_msgTypes[24] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use TunnelResponse.ProtoReflect.Descriptor instead. +func (*TunnelResponse) Descriptor() ([]byte, []int) { + return file_hiddify_proto_rawDescGZIP(), []int{24} +} + +func (x *TunnelResponse) GetMessage() string { + if x != nil { + return x.Message + } + return "" +} + +var File_hiddify_proto protoreflect.FileDescriptor + +var file_hiddify_proto_rawDesc = []byte{ + 0x0a, 0x0d, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, + 0x0a, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x1a, 0x0a, 0x62, 0x61, 0x73, + 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x9e, 0x01, 0x0a, 0x10, 0x43, 0x6f, 0x72, 0x65, + 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x34, 0x0a, 0x0a, + 0x63, 0x6f, 0x72, 0x65, 0x5f, 0x73, 0x74, 0x61, 0x74, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, + 0x32, 0x15, 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, 0x43, 0x6f, + 0x72, 0x65, 0x53, 0x74, 0x61, 0x74, 0x65, 0x52, 0x09, 0x63, 0x6f, 0x72, 0x65, 0x53, 0x74, 0x61, + 0x74, 0x65, 0x12, 0x3a, 0x0a, 0x0c, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x5f, 0x74, 0x79, + 0x70, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x17, 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, + 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x54, 0x79, 0x70, + 0x65, 0x52, 0x0b, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x54, 0x79, 0x70, 0x65, 0x12, 0x18, + 0x0a, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x22, 0x90, 0x02, 0x0a, 0x0c, 0x53, 0x74, 0x61, + 0x72, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1f, 0x0a, 0x0b, 0x63, 0x6f, 0x6e, + 0x66, 0x69, 0x67, 0x5f, 0x70, 0x61, 0x74, 0x68, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, + 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x50, 0x61, 0x74, 0x68, 0x12, 0x25, 0x0a, 0x0e, 0x63, 0x6f, + 0x6e, 0x66, 0x69, 0x67, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x18, 0x02, 0x20, 0x01, + 0x28, 0x09, 0x52, 0x0d, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, + 0x74, 0x12, 0x30, 0x0a, 0x14, 0x64, 0x69, 0x73, 0x61, 0x62, 0x6c, 0x65, 0x5f, 0x6d, 0x65, 0x6d, + 0x6f, 0x72, 0x79, 0x5f, 0x6c, 0x69, 0x6d, 0x69, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x08, 0x52, + 0x12, 0x64, 0x69, 0x73, 0x61, 0x62, 0x6c, 0x65, 0x4d, 0x65, 0x6d, 0x6f, 0x72, 0x79, 0x4c, 0x69, + 0x6d, 0x69, 0x74, 0x12, 0x1f, 0x0a, 0x0b, 0x64, 0x65, 0x6c, 0x61, 0x79, 0x5f, 0x73, 0x74, 0x61, + 0x72, 0x74, 0x18, 0x04, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0a, 0x64, 0x65, 0x6c, 0x61, 0x79, 0x53, + 0x74, 0x61, 0x72, 0x74, 0x12, 0x39, 0x0a, 0x19, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x5f, 0x6f, + 0x6c, 0x64, 0x5f, 0x63, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x5f, 0x73, 0x65, 0x72, 0x76, 0x65, + 0x72, 0x18, 0x05, 0x20, 0x01, 0x28, 0x08, 0x52, 0x16, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x4f, + 0x6c, 0x64, 0x43, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x12, + 0x2a, 0x0a, 0x11, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x5f, 0x72, 0x61, 0x77, 0x5f, 0x63, 0x6f, + 0x6e, 0x66, 0x69, 0x67, 0x18, 0x06, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0f, 0x65, 0x6e, 0x61, 0x62, + 0x6c, 0x65, 0x52, 0x61, 0x77, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x22, 0x6b, 0x0a, 0x0c, 0x53, + 0x65, 0x74, 0x75, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x62, + 0x61, 0x73, 0x65, 0x5f, 0x70, 0x61, 0x74, 0x68, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, + 0x62, 0x61, 0x73, 0x65, 0x50, 0x61, 0x74, 0x68, 0x12, 0x21, 0x0a, 0x0c, 0x77, 0x6f, 0x72, 0x6b, + 0x69, 0x6e, 0x67, 0x5f, 0x70, 0x61, 0x74, 0x68, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, + 0x77, 0x6f, 0x72, 0x6b, 0x69, 0x6e, 0x67, 0x50, 0x61, 0x74, 0x68, 0x12, 0x1b, 0x0a, 0x09, 0x74, + 0x65, 0x6d, 0x70, 0x5f, 0x70, 0x61, 0x74, 0x68, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, + 0x74, 0x65, 0x6d, 0x70, 0x50, 0x61, 0x74, 0x68, 0x22, 0x63, 0x0a, 0x08, 0x52, 0x65, 0x73, 0x70, + 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x3d, 0x0a, 0x0d, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, + 0x5f, 0x63, 0x6f, 0x64, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x18, 0x2e, 0x68, 0x69, + 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, + 0x65, 0x43, 0x6f, 0x64, 0x65, 0x52, 0x0c, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x43, + 0x6f, 0x64, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x02, + 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x22, 0xbf, 0x02, + 0x0a, 0x0a, 0x53, 0x79, 0x73, 0x74, 0x65, 0x6d, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x16, 0x0a, 0x06, + 0x6d, 0x65, 0x6d, 0x6f, 0x72, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x06, 0x6d, 0x65, + 0x6d, 0x6f, 0x72, 0x79, 0x12, 0x1e, 0x0a, 0x0a, 0x67, 0x6f, 0x72, 0x6f, 0x75, 0x74, 0x69, 0x6e, + 0x65, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0a, 0x67, 0x6f, 0x72, 0x6f, 0x75, 0x74, + 0x69, 0x6e, 0x65, 0x73, 0x12, 0x25, 0x0a, 0x0e, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, + 0x6f, 0x6e, 0x73, 0x5f, 0x69, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0d, 0x63, 0x6f, + 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x49, 0x6e, 0x12, 0x27, 0x0a, 0x0f, 0x63, + 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x5f, 0x6f, 0x75, 0x74, 0x18, 0x04, + 0x20, 0x01, 0x28, 0x05, 0x52, 0x0e, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, + 0x73, 0x4f, 0x75, 0x74, 0x12, 0x2b, 0x0a, 0x11, 0x74, 0x72, 0x61, 0x66, 0x66, 0x69, 0x63, 0x5f, + 0x61, 0x76, 0x61, 0x69, 0x6c, 0x61, 0x62, 0x6c, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x08, 0x52, + 0x10, 0x74, 0x72, 0x61, 0x66, 0x66, 0x69, 0x63, 0x41, 0x76, 0x61, 0x69, 0x6c, 0x61, 0x62, 0x6c, + 0x65, 0x12, 0x16, 0x0a, 0x06, 0x75, 0x70, 0x6c, 0x69, 0x6e, 0x6b, 0x18, 0x06, 0x20, 0x01, 0x28, + 0x03, 0x52, 0x06, 0x75, 0x70, 0x6c, 0x69, 0x6e, 0x6b, 0x12, 0x1a, 0x0a, 0x08, 0x64, 0x6f, 0x77, + 0x6e, 0x6c, 0x69, 0x6e, 0x6b, 0x18, 0x07, 0x20, 0x01, 0x28, 0x03, 0x52, 0x08, 0x64, 0x6f, 0x77, + 0x6e, 0x6c, 0x69, 0x6e, 0x6b, 0x12, 0x21, 0x0a, 0x0c, 0x75, 0x70, 0x6c, 0x69, 0x6e, 0x6b, 0x5f, + 0x74, 0x6f, 0x74, 0x61, 0x6c, 0x18, 0x08, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0b, 0x75, 0x70, 0x6c, + 0x69, 0x6e, 0x6b, 0x54, 0x6f, 0x74, 0x61, 0x6c, 0x12, 0x25, 0x0a, 0x0e, 0x64, 0x6f, 0x77, 0x6e, + 0x6c, 0x69, 0x6e, 0x6b, 0x5f, 0x74, 0x6f, 0x74, 0x61, 0x6c, 0x18, 0x09, 0x20, 0x01, 0x28, 0x03, + 0x52, 0x0d, 0x64, 0x6f, 0x77, 0x6e, 0x6c, 0x69, 0x6e, 0x6b, 0x54, 0x6f, 0x74, 0x61, 0x6c, 0x22, + 0x83, 0x01, 0x0a, 0x11, 0x4f, 0x75, 0x74, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x47, 0x72, 0x6f, 0x75, + 0x70, 0x49, 0x74, 0x65, 0x6d, 0x12, 0x10, 0x0a, 0x03, 0x74, 0x61, 0x67, 0x18, 0x01, 0x20, 0x01, + 0x28, 0x09, 0x52, 0x03, 0x74, 0x61, 0x67, 0x12, 0x12, 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x18, + 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x74, 0x79, 0x70, 0x65, 0x12, 0x22, 0x0a, 0x0d, 0x75, + 0x72, 0x6c, 0x5f, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, + 0x28, 0x03, 0x52, 0x0b, 0x75, 0x72, 0x6c, 0x54, 0x65, 0x73, 0x74, 0x54, 0x69, 0x6d, 0x65, 0x12, + 0x24, 0x0a, 0x0e, 0x75, 0x72, 0x6c, 0x5f, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x64, 0x65, 0x6c, 0x61, + 0x79, 0x18, 0x04, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0c, 0x75, 0x72, 0x6c, 0x54, 0x65, 0x73, 0x74, + 0x44, 0x65, 0x6c, 0x61, 0x79, 0x22, 0x86, 0x01, 0x0a, 0x0d, 0x4f, 0x75, 0x74, 0x62, 0x6f, 0x75, + 0x6e, 0x64, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x12, 0x10, 0x0a, 0x03, 0x74, 0x61, 0x67, 0x18, 0x01, + 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x74, 0x61, 0x67, 0x12, 0x12, 0x0a, 0x04, 0x74, 0x79, 0x70, + 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x74, 0x79, 0x70, 0x65, 0x12, 0x1a, 0x0a, + 0x08, 0x73, 0x65, 0x6c, 0x65, 0x63, 0x74, 0x65, 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x08, 0x73, 0x65, 0x6c, 0x65, 0x63, 0x74, 0x65, 0x64, 0x12, 0x33, 0x0a, 0x05, 0x69, 0x74, 0x65, + 0x6d, 0x73, 0x18, 0x04, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1d, 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, + 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, 0x4f, 0x75, 0x74, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x47, 0x72, + 0x6f, 0x75, 0x70, 0x49, 0x74, 0x65, 0x6d, 0x52, 0x05, 0x69, 0x74, 0x65, 0x6d, 0x73, 0x22, 0x44, + 0x0a, 0x11, 0x4f, 0x75, 0x74, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x4c, + 0x69, 0x73, 0x74, 0x12, 0x2f, 0x0a, 0x05, 0x69, 0x74, 0x65, 0x6d, 0x73, 0x18, 0x01, 0x20, 0x03, + 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, + 0x4f, 0x75, 0x74, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x52, 0x05, 0x69, + 0x74, 0x65, 0x6d, 0x73, 0x22, 0x4f, 0x0a, 0x0b, 0x57, 0x61, 0x72, 0x70, 0x41, 0x63, 0x63, 0x6f, + 0x75, 0x6e, 0x74, 0x12, 0x1d, 0x0a, 0x0a, 0x61, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x5f, 0x69, + 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x61, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, + 0x49, 0x64, 0x12, 0x21, 0x0a, 0x0c, 0x61, 0x63, 0x63, 0x65, 0x73, 0x73, 0x5f, 0x74, 0x6f, 0x6b, + 0x65, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x61, 0x63, 0x63, 0x65, 0x73, 0x73, + 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x22, 0xd7, 0x01, 0x0a, 0x13, 0x57, 0x61, 0x72, 0x70, 0x57, 0x69, + 0x72, 0x65, 0x67, 0x75, 0x61, 0x72, 0x64, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x1f, 0x0a, + 0x0b, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x5f, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, + 0x28, 0x09, 0x52, 0x0a, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x4b, 0x65, 0x79, 0x12, 0x2c, + 0x0a, 0x12, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x5f, + 0x69, 0x70, 0x76, 0x34, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x10, 0x6c, 0x6f, 0x63, 0x61, + 0x6c, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x49, 0x70, 0x76, 0x34, 0x12, 0x2c, 0x0a, 0x12, + 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x5f, 0x69, 0x70, + 0x76, 0x36, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x10, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x41, + 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x49, 0x70, 0x76, 0x36, 0x12, 0x26, 0x0a, 0x0f, 0x70, 0x65, + 0x65, 0x72, 0x5f, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x5f, 0x6b, 0x65, 0x79, 0x18, 0x04, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x0d, 0x70, 0x65, 0x65, 0x72, 0x50, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x4b, + 0x65, 0x79, 0x12, 0x1b, 0x0a, 0x09, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x69, 0x64, 0x18, + 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x49, 0x64, 0x22, + 0x96, 0x01, 0x0a, 0x16, 0x57, 0x61, 0x72, 0x70, 0x47, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74, 0x69, + 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x31, 0x0a, 0x07, 0x61, 0x63, + 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x68, 0x69, + 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, 0x57, 0x61, 0x72, 0x70, 0x41, 0x63, 0x63, + 0x6f, 0x75, 0x6e, 0x74, 0x52, 0x07, 0x61, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x10, 0x0a, + 0x03, 0x6c, 0x6f, 0x67, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6c, 0x6f, 0x67, 0x12, + 0x37, 0x0a, 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, + 0x1f, 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, 0x57, 0x61, 0x72, + 0x70, 0x57, 0x69, 0x72, 0x65, 0x67, 0x75, 0x61, 0x72, 0x64, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, + 0x52, 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x22, 0x4b, 0x0a, 0x11, 0x53, 0x79, 0x73, 0x74, + 0x65, 0x6d, 0x50, 0x72, 0x6f, 0x78, 0x79, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x1c, 0x0a, + 0x09, 0x61, 0x76, 0x61, 0x69, 0x6c, 0x61, 0x62, 0x6c, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, + 0x52, 0x09, 0x61, 0x76, 0x61, 0x69, 0x6c, 0x61, 0x62, 0x6c, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x65, + 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x08, 0x52, 0x07, 0x65, 0x6e, + 0x61, 0x62, 0x6c, 0x65, 0x64, 0x22, 0x7c, 0x0a, 0x0c, 0x50, 0x61, 0x72, 0x73, 0x65, 0x52, 0x65, + 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x18, 0x0a, 0x07, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, + 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x12, + 0x1f, 0x0a, 0x0b, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x5f, 0x70, 0x61, 0x74, 0x68, 0x18, 0x02, + 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x50, 0x61, 0x74, 0x68, + 0x12, 0x1b, 0x0a, 0x09, 0x74, 0x65, 0x6d, 0x70, 0x5f, 0x70, 0x61, 0x74, 0x68, 0x18, 0x03, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x08, 0x74, 0x65, 0x6d, 0x70, 0x50, 0x61, 0x74, 0x68, 0x12, 0x14, 0x0a, + 0x05, 0x64, 0x65, 0x62, 0x75, 0x67, 0x18, 0x04, 0x20, 0x01, 0x28, 0x08, 0x52, 0x05, 0x64, 0x65, + 0x62, 0x75, 0x67, 0x22, 0x82, 0x01, 0x0a, 0x0d, 0x50, 0x61, 0x72, 0x73, 0x65, 0x52, 0x65, 0x73, + 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x3d, 0x0a, 0x0d, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, + 0x65, 0x5f, 0x63, 0x6f, 0x64, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x18, 0x2e, 0x68, + 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, + 0x73, 0x65, 0x43, 0x6f, 0x64, 0x65, 0x52, 0x0c, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, + 0x43, 0x6f, 0x64, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x18, + 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x12, 0x18, + 0x0a, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x22, 0x52, 0x0a, 0x1c, 0x43, 0x68, 0x61, 0x6e, + 0x67, 0x65, 0x48, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, + 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x32, 0x0a, 0x15, 0x68, 0x69, 0x64, 0x64, + 0x69, 0x66, 0x79, 0x5f, 0x73, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x5f, 0x6a, 0x73, 0x6f, + 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x13, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, + 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x4a, 0x73, 0x6f, 0x6e, 0x22, 0x5e, 0x0a, 0x15, + 0x47, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74, 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x65, + 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x12, 0x0a, 0x04, 0x70, 0x61, 0x74, 0x68, 0x18, 0x01, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x04, 0x70, 0x61, 0x74, 0x68, 0x12, 0x1b, 0x0a, 0x09, 0x74, 0x65, 0x6d, + 0x70, 0x5f, 0x70, 0x61, 0x74, 0x68, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x74, 0x65, + 0x6d, 0x70, 0x50, 0x61, 0x74, 0x68, 0x12, 0x14, 0x0a, 0x05, 0x64, 0x65, 0x62, 0x75, 0x67, 0x18, + 0x03, 0x20, 0x01, 0x28, 0x08, 0x52, 0x05, 0x64, 0x65, 0x62, 0x75, 0x67, 0x22, 0x3f, 0x0a, 0x16, + 0x47, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74, 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x65, + 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x25, 0x0a, 0x0e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, + 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, + 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x22, 0x57, 0x0a, + 0x15, 0x53, 0x65, 0x6c, 0x65, 0x63, 0x74, 0x4f, 0x75, 0x74, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x52, + 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x5f, + 0x74, 0x61, 0x67, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x67, 0x72, 0x6f, 0x75, 0x70, + 0x54, 0x61, 0x67, 0x12, 0x21, 0x0a, 0x0c, 0x6f, 0x75, 0x74, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x5f, + 0x74, 0x61, 0x67, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x6f, 0x75, 0x74, 0x62, 0x6f, + 0x75, 0x6e, 0x64, 0x54, 0x61, 0x67, 0x22, 0x2d, 0x0a, 0x0e, 0x55, 0x72, 0x6c, 0x54, 0x65, 0x73, + 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x67, 0x72, 0x6f, 0x75, + 0x70, 0x5f, 0x74, 0x61, 0x67, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x67, 0x72, 0x6f, + 0x75, 0x70, 0x54, 0x61, 0x67, 0x22, 0x7e, 0x0a, 0x19, 0x47, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74, + 0x65, 0x57, 0x61, 0x72, 0x70, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x65, 0x71, 0x75, 0x65, + 0x73, 0x74, 0x12, 0x1f, 0x0a, 0x0b, 0x6c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65, 0x5f, 0x6b, 0x65, + 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x6c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65, + 0x4b, 0x65, 0x79, 0x12, 0x1d, 0x0a, 0x0a, 0x61, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x5f, 0x69, + 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x61, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, + 0x49, 0x64, 0x12, 0x21, 0x0a, 0x0c, 0x61, 0x63, 0x63, 0x65, 0x73, 0x73, 0x5f, 0x74, 0x6f, 0x6b, + 0x65, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x61, 0x63, 0x63, 0x65, 0x73, 0x73, + 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x22, 0x3d, 0x0a, 0x1c, 0x53, 0x65, 0x74, 0x53, 0x79, 0x73, 0x74, + 0x65, 0x6d, 0x50, 0x72, 0x6f, 0x78, 0x79, 0x45, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x52, 0x65, + 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1d, 0x0a, 0x0a, 0x69, 0x73, 0x5f, 0x65, 0x6e, 0x61, 0x62, + 0x6c, 0x65, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x09, 0x69, 0x73, 0x45, 0x6e, 0x61, + 0x62, 0x6c, 0x65, 0x64, 0x22, 0x7b, 0x0a, 0x0a, 0x4c, 0x6f, 0x67, 0x4d, 0x65, 0x73, 0x73, 0x61, + 0x67, 0x65, 0x12, 0x2a, 0x0a, 0x05, 0x6c, 0x65, 0x76, 0x65, 0x6c, 0x18, 0x01, 0x20, 0x01, 0x28, + 0x0e, 0x32, 0x14, 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, 0x4c, + 0x6f, 0x67, 0x4c, 0x65, 0x76, 0x65, 0x6c, 0x52, 0x05, 0x6c, 0x65, 0x76, 0x65, 0x6c, 0x12, 0x27, + 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x13, 0x2e, 0x68, + 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, 0x4c, 0x6f, 0x67, 0x54, 0x79, 0x70, + 0x65, 0x52, 0x04, 0x74, 0x79, 0x70, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, + 0x67, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, + 0x65, 0x22, 0x0d, 0x0a, 0x0b, 0x53, 0x74, 0x6f, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, + 0x22, 0xbc, 0x01, 0x0a, 0x12, 0x54, 0x75, 0x6e, 0x6e, 0x65, 0x6c, 0x53, 0x74, 0x61, 0x72, 0x74, + 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x12, 0x0a, 0x04, 0x69, 0x70, 0x76, 0x36, 0x18, + 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x04, 0x69, 0x70, 0x76, 0x36, 0x12, 0x1f, 0x0a, 0x0b, 0x73, + 0x65, 0x72, 0x76, 0x65, 0x72, 0x5f, 0x70, 0x6f, 0x72, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x05, + 0x52, 0x0a, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x50, 0x6f, 0x72, 0x74, 0x12, 0x21, 0x0a, 0x0c, + 0x73, 0x74, 0x72, 0x69, 0x63, 0x74, 0x5f, 0x72, 0x6f, 0x75, 0x74, 0x65, 0x18, 0x03, 0x20, 0x01, + 0x28, 0x08, 0x52, 0x0b, 0x73, 0x74, 0x72, 0x69, 0x63, 0x74, 0x52, 0x6f, 0x75, 0x74, 0x65, 0x12, + 0x38, 0x0a, 0x18, 0x65, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x5f, 0x69, 0x6e, 0x64, 0x65, + 0x70, 0x65, 0x6e, 0x64, 0x65, 0x6e, 0x74, 0x5f, 0x6e, 0x61, 0x74, 0x18, 0x04, 0x20, 0x01, 0x28, + 0x08, 0x52, 0x16, 0x65, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x49, 0x6e, 0x64, 0x65, 0x70, + 0x65, 0x6e, 0x64, 0x65, 0x6e, 0x74, 0x4e, 0x61, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x73, 0x74, 0x61, + 0x63, 0x6b, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x73, 0x74, 0x61, 0x63, 0x6b, 0x22, + 0x2a, 0x0a, 0x0e, 0x54, 0x75, 0x6e, 0x6e, 0x65, 0x6c, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, + 0x65, 0x12, 0x18, 0x0a, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x01, 0x20, 0x01, + 0x28, 0x09, 0x52, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x2a, 0x41, 0x0a, 0x09, 0x43, + 0x6f, 0x72, 0x65, 0x53, 0x74, 0x61, 0x74, 0x65, 0x12, 0x0b, 0x0a, 0x07, 0x53, 0x54, 0x4f, 0x50, + 0x50, 0x45, 0x44, 0x10, 0x00, 0x12, 0x0c, 0x0a, 0x08, 0x53, 0x54, 0x41, 0x52, 0x54, 0x49, 0x4e, + 0x47, 0x10, 0x01, 0x12, 0x0b, 0x0a, 0x07, 0x53, 0x54, 0x41, 0x52, 0x54, 0x45, 0x44, 0x10, 0x02, + 0x12, 0x0c, 0x0a, 0x08, 0x53, 0x54, 0x4f, 0x50, 0x50, 0x49, 0x4e, 0x47, 0x10, 0x03, 0x2a, 0xcd, + 0x02, 0x0a, 0x0b, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x54, 0x79, 0x70, 0x65, 0x12, 0x09, + 0x0a, 0x05, 0x45, 0x4d, 0x50, 0x54, 0x59, 0x10, 0x00, 0x12, 0x17, 0x0a, 0x13, 0x45, 0x4d, 0x50, + 0x54, 0x59, 0x5f, 0x43, 0x4f, 0x4e, 0x46, 0x49, 0x47, 0x55, 0x52, 0x41, 0x54, 0x49, 0x4f, 0x4e, + 0x10, 0x01, 0x12, 0x18, 0x0a, 0x14, 0x53, 0x54, 0x41, 0x52, 0x54, 0x5f, 0x43, 0x4f, 0x4d, 0x4d, + 0x41, 0x4e, 0x44, 0x5f, 0x53, 0x45, 0x52, 0x56, 0x45, 0x52, 0x10, 0x02, 0x12, 0x12, 0x0a, 0x0e, + 0x43, 0x52, 0x45, 0x41, 0x54, 0x45, 0x5f, 0x53, 0x45, 0x52, 0x56, 0x49, 0x43, 0x45, 0x10, 0x03, + 0x12, 0x11, 0x0a, 0x0d, 0x53, 0x54, 0x41, 0x52, 0x54, 0x5f, 0x53, 0x45, 0x52, 0x56, 0x49, 0x43, + 0x45, 0x10, 0x04, 0x12, 0x14, 0x0a, 0x10, 0x55, 0x4e, 0x45, 0x58, 0x50, 0x45, 0x43, 0x54, 0x45, + 0x44, 0x5f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x05, 0x12, 0x13, 0x0a, 0x0f, 0x41, 0x4c, 0x52, + 0x45, 0x41, 0x44, 0x59, 0x5f, 0x53, 0x54, 0x41, 0x52, 0x54, 0x45, 0x44, 0x10, 0x06, 0x12, 0x13, + 0x0a, 0x0f, 0x41, 0x4c, 0x52, 0x45, 0x41, 0x44, 0x59, 0x5f, 0x53, 0x54, 0x4f, 0x50, 0x50, 0x45, + 0x44, 0x10, 0x07, 0x12, 0x16, 0x0a, 0x12, 0x49, 0x4e, 0x53, 0x54, 0x41, 0x4e, 0x43, 0x45, 0x5f, + 0x4e, 0x4f, 0x54, 0x5f, 0x46, 0x4f, 0x55, 0x4e, 0x44, 0x10, 0x08, 0x12, 0x18, 0x0a, 0x14, 0x49, + 0x4e, 0x53, 0x54, 0x41, 0x4e, 0x43, 0x45, 0x5f, 0x4e, 0x4f, 0x54, 0x5f, 0x53, 0x54, 0x4f, 0x50, + 0x50, 0x45, 0x44, 0x10, 0x09, 0x12, 0x18, 0x0a, 0x14, 0x49, 0x4e, 0x53, 0x54, 0x41, 0x4e, 0x43, + 0x45, 0x5f, 0x4e, 0x4f, 0x54, 0x5f, 0x53, 0x54, 0x41, 0x52, 0x54, 0x45, 0x44, 0x10, 0x0a, 0x12, + 0x19, 0x0a, 0x15, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x5f, 0x42, 0x55, 0x49, 0x4c, 0x44, 0x49, 0x4e, + 0x47, 0x5f, 0x43, 0x4f, 0x4e, 0x46, 0x49, 0x47, 0x10, 0x0b, 0x12, 0x18, 0x0a, 0x14, 0x45, 0x52, + 0x52, 0x4f, 0x52, 0x5f, 0x50, 0x41, 0x52, 0x53, 0x49, 0x4e, 0x47, 0x5f, 0x43, 0x4f, 0x4e, 0x46, + 0x49, 0x47, 0x10, 0x0c, 0x12, 0x18, 0x0a, 0x14, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x5f, 0x52, 0x45, + 0x41, 0x44, 0x49, 0x4e, 0x47, 0x5f, 0x43, 0x4f, 0x4e, 0x46, 0x49, 0x47, 0x10, 0x0d, 0x2a, 0x42, + 0x0a, 0x08, 0x4c, 0x6f, 0x67, 0x4c, 0x65, 0x76, 0x65, 0x6c, 0x12, 0x09, 0x0a, 0x05, 0x44, 0x45, + 0x42, 0x55, 0x47, 0x10, 0x00, 0x12, 0x08, 0x0a, 0x04, 0x49, 0x4e, 0x46, 0x4f, 0x10, 0x01, 0x12, + 0x0b, 0x0a, 0x07, 0x57, 0x41, 0x52, 0x4e, 0x49, 0x4e, 0x47, 0x10, 0x02, 0x12, 0x09, 0x0a, 0x05, + 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x03, 0x12, 0x09, 0x0a, 0x05, 0x46, 0x41, 0x54, 0x41, 0x4c, + 0x10, 0x04, 0x2a, 0x2c, 0x0a, 0x07, 0x4c, 0x6f, 0x67, 0x54, 0x79, 0x70, 0x65, 0x12, 0x08, 0x0a, + 0x04, 0x43, 0x4f, 0x52, 0x45, 0x10, 0x00, 0x12, 0x0b, 0x0a, 0x07, 0x53, 0x45, 0x52, 0x56, 0x49, + 0x43, 0x45, 0x10, 0x01, 0x12, 0x0a, 0x0a, 0x06, 0x43, 0x4f, 0x4e, 0x46, 0x49, 0x47, 0x10, 0x02, + 0x32, 0x93, 0x01, 0x0a, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x12, 0x3f, 0x0a, 0x08, 0x53, 0x61, + 0x79, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x12, 0x18, 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, + 0x72, 0x70, 0x63, 0x2e, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, + 0x1a, 0x19, 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, 0x48, 0x65, + 0x6c, 0x6c, 0x6f, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x49, 0x0a, 0x0e, 0x53, + 0x61, 0x79, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x12, 0x18, 0x2e, + 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, 0x48, 0x65, 0x6c, 0x6c, 0x6f, + 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x19, 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, + 0x79, 0x72, 0x70, 0x63, 0x2e, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, + 0x73, 0x65, 0x28, 0x01, 0x30, 0x01, 0x32, 0xbe, 0x09, 0x0a, 0x04, 0x43, 0x6f, 0x72, 0x65, 0x12, + 0x3f, 0x0a, 0x05, 0x53, 0x74, 0x61, 0x72, 0x74, 0x12, 0x18, 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, + 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, 0x53, 0x74, 0x61, 0x72, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, + 0x73, 0x74, 0x1a, 0x1c, 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, + 0x43, 0x6f, 0x72, 0x65, 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, + 0x12, 0x45, 0x0a, 0x10, 0x43, 0x6f, 0x72, 0x65, 0x49, 0x6e, 0x66, 0x6f, 0x4c, 0x69, 0x73, 0x74, + 0x65, 0x6e, 0x65, 0x72, 0x12, 0x11, 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, + 0x63, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a, 0x1c, 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, + 0x79, 0x72, 0x70, 0x63, 0x2e, 0x43, 0x6f, 0x72, 0x65, 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x65, 0x73, + 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x30, 0x01, 0x12, 0x43, 0x0a, 0x0d, 0x4f, 0x75, 0x74, 0x62, 0x6f, + 0x75, 0x6e, 0x64, 0x73, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x11, 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, + 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a, 0x1d, 0x2e, 0x68, 0x69, + 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, 0x4f, 0x75, 0x74, 0x62, 0x6f, 0x75, 0x6e, + 0x64, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x4c, 0x69, 0x73, 0x74, 0x30, 0x01, 0x12, 0x47, 0x0a, 0x11, + 0x4d, 0x61, 0x69, 0x6e, 0x4f, 0x75, 0x74, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x73, 0x49, 0x6e, 0x66, + 0x6f, 0x12, 0x11, 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, 0x45, + 0x6d, 0x70, 0x74, 0x79, 0x1a, 0x1d, 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, + 0x63, 0x2e, 0x4f, 0x75, 0x74, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x4c, + 0x69, 0x73, 0x74, 0x30, 0x01, 0x12, 0x3c, 0x0a, 0x0d, 0x47, 0x65, 0x74, 0x53, 0x79, 0x73, 0x74, + 0x65, 0x6d, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x11, 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, + 0x72, 0x70, 0x63, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a, 0x16, 0x2e, 0x68, 0x69, 0x64, 0x64, + 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, 0x53, 0x79, 0x73, 0x74, 0x65, 0x6d, 0x49, 0x6e, 0x66, + 0x6f, 0x30, 0x01, 0x12, 0x37, 0x0a, 0x05, 0x53, 0x65, 0x74, 0x75, 0x70, 0x12, 0x18, 0x2e, 0x68, + 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, 0x53, 0x65, 0x74, 0x75, 0x70, 0x52, + 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x14, 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, + 0x72, 0x70, 0x63, 0x2e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x3c, 0x0a, 0x05, + 0x50, 0x61, 0x72, 0x73, 0x65, 0x12, 0x18, 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, + 0x70, 0x63, 0x2e, 0x50, 0x61, 0x72, 0x73, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, + 0x19, 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, 0x50, 0x61, 0x72, + 0x73, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x5f, 0x0a, 0x15, 0x43, 0x68, + 0x61, 0x6e, 0x67, 0x65, 0x48, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x53, 0x65, 0x74, 0x74, 0x69, + 0x6e, 0x67, 0x73, 0x12, 0x28, 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, + 0x2e, 0x43, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x48, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x53, 0x65, + 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1c, 0x2e, + 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, 0x43, 0x6f, 0x72, 0x65, 0x49, + 0x6e, 0x66, 0x6f, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x46, 0x0a, 0x0c, 0x53, + 0x74, 0x61, 0x72, 0x74, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x18, 0x2e, 0x68, 0x69, + 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, 0x53, 0x74, 0x61, 0x72, 0x74, 0x52, 0x65, + 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1c, 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, + 0x70, 0x63, 0x2e, 0x43, 0x6f, 0x72, 0x65, 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x65, 0x73, 0x70, 0x6f, + 0x6e, 0x73, 0x65, 0x12, 0x37, 0x0a, 0x04, 0x53, 0x74, 0x6f, 0x70, 0x12, 0x11, 0x2e, 0x68, 0x69, + 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a, 0x1c, + 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, 0x43, 0x6f, 0x72, 0x65, + 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x41, 0x0a, 0x07, + 0x52, 0x65, 0x73, 0x74, 0x61, 0x72, 0x74, 0x12, 0x18, 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, + 0x79, 0x72, 0x70, 0x63, 0x2e, 0x53, 0x74, 0x61, 0x72, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, + 0x74, 0x1a, 0x1c, 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, 0x43, + 0x6f, 0x72, 0x65, 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, + 0x49, 0x0a, 0x0e, 0x53, 0x65, 0x6c, 0x65, 0x63, 0x74, 0x4f, 0x75, 0x74, 0x62, 0x6f, 0x75, 0x6e, + 0x64, 0x12, 0x21, 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, 0x53, + 0x65, 0x6c, 0x65, 0x63, 0x74, 0x4f, 0x75, 0x74, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x52, 0x65, 0x71, + 0x75, 0x65, 0x73, 0x74, 0x1a, 0x14, 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, + 0x63, 0x2e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x3b, 0x0a, 0x07, 0x55, 0x72, + 0x6c, 0x54, 0x65, 0x73, 0x74, 0x12, 0x1a, 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, + 0x70, 0x63, 0x2e, 0x55, 0x72, 0x6c, 0x54, 0x65, 0x73, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, + 0x74, 0x1a, 0x14, 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, 0x52, + 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x5f, 0x0a, 0x12, 0x47, 0x65, 0x6e, 0x65, 0x72, + 0x61, 0x74, 0x65, 0x57, 0x61, 0x72, 0x70, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x25, 0x2e, + 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, 0x47, 0x65, 0x6e, 0x65, 0x72, + 0x61, 0x74, 0x65, 0x57, 0x61, 0x72, 0x70, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x65, 0x71, + 0x75, 0x65, 0x73, 0x74, 0x1a, 0x22, 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, + 0x63, 0x2e, 0x57, 0x61, 0x72, 0x70, 0x47, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, + 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x48, 0x0a, 0x14, 0x47, 0x65, 0x74, 0x53, + 0x79, 0x73, 0x74, 0x65, 0x6d, 0x50, 0x72, 0x6f, 0x78, 0x79, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, + 0x12, 0x11, 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, 0x45, 0x6d, + 0x70, 0x74, 0x79, 0x1a, 0x1d, 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, + 0x2e, 0x53, 0x79, 0x73, 0x74, 0x65, 0x6d, 0x50, 0x72, 0x6f, 0x78, 0x79, 0x53, 0x74, 0x61, 0x74, + 0x75, 0x73, 0x12, 0x57, 0x0a, 0x15, 0x53, 0x65, 0x74, 0x53, 0x79, 0x73, 0x74, 0x65, 0x6d, 0x50, + 0x72, 0x6f, 0x78, 0x79, 0x45, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x12, 0x28, 0x2e, 0x68, 0x69, + 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, 0x53, 0x65, 0x74, 0x53, 0x79, 0x73, 0x74, + 0x65, 0x6d, 0x50, 0x72, 0x6f, 0x78, 0x79, 0x45, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x52, 0x65, + 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x14, 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, + 0x70, 0x63, 0x2e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x3a, 0x0a, 0x0b, 0x4c, + 0x6f, 0x67, 0x4c, 0x69, 0x73, 0x74, 0x65, 0x6e, 0x65, 0x72, 0x12, 0x11, 0x2e, 0x68, 0x69, 0x64, + 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a, 0x16, 0x2e, + 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, 0x4c, 0x6f, 0x67, 0x4d, 0x65, + 0x73, 0x73, 0x61, 0x67, 0x65, 0x30, 0x01, 0x32, 0xfb, 0x01, 0x0a, 0x0d, 0x54, 0x75, 0x6e, 0x6e, + 0x65, 0x6c, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x43, 0x0a, 0x05, 0x53, 0x74, 0x61, + 0x72, 0x74, 0x12, 0x1e, 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, + 0x54, 0x75, 0x6e, 0x6e, 0x65, 0x6c, 0x53, 0x74, 0x61, 0x72, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, + 0x73, 0x74, 0x1a, 0x1a, 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, + 0x54, 0x75, 0x6e, 0x6e, 0x65, 0x6c, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x35, + 0x0a, 0x04, 0x53, 0x74, 0x6f, 0x70, 0x12, 0x11, 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, + 0x72, 0x70, 0x63, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a, 0x1a, 0x2e, 0x68, 0x69, 0x64, 0x64, + 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, 0x54, 0x75, 0x6e, 0x6e, 0x65, 0x6c, 0x52, 0x65, 0x73, + 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x37, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, + 0x11, 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, 0x45, 0x6d, 0x70, + 0x74, 0x79, 0x1a, 0x1a, 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, + 0x54, 0x75, 0x6e, 0x6e, 0x65, 0x6c, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x35, + 0x0a, 0x04, 0x45, 0x78, 0x69, 0x74, 0x12, 0x11, 0x2e, 0x68, 0x69, 0x64, 0x64, 0x69, 0x66, 0x79, + 0x72, 0x70, 0x63, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a, 0x1a, 0x2e, 0x68, 0x69, 0x64, 0x64, + 0x69, 0x66, 0x79, 0x72, 0x70, 0x63, 0x2e, 0x54, 0x75, 0x6e, 0x6e, 0x65, 0x6c, 0x52, 0x65, 0x73, + 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x42, 0x0e, 0x5a, 0x0c, 0x2e, 0x2f, 0x68, 0x69, 0x64, 0x64, 0x69, + 0x66, 0x79, 0x72, 0x70, 0x63, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_hiddify_proto_rawDescOnce sync.Once + file_hiddify_proto_rawDescData = file_hiddify_proto_rawDesc +) + +func file_hiddify_proto_rawDescGZIP() []byte { + file_hiddify_proto_rawDescOnce.Do(func() { + file_hiddify_proto_rawDescData = protoimpl.X.CompressGZIP(file_hiddify_proto_rawDescData) + }) + return file_hiddify_proto_rawDescData +} + +var file_hiddify_proto_enumTypes = make([]protoimpl.EnumInfo, 4) +var file_hiddify_proto_msgTypes = make([]protoimpl.MessageInfo, 25) +var file_hiddify_proto_goTypes = []any{ + (CoreState)(0), // 0: hiddifyrpc.CoreState + (MessageType)(0), // 1: hiddifyrpc.MessageType + (LogLevel)(0), // 2: hiddifyrpc.LogLevel + (LogType)(0), // 3: hiddifyrpc.LogType + (*CoreInfoResponse)(nil), // 4: hiddifyrpc.CoreInfoResponse + (*StartRequest)(nil), // 5: hiddifyrpc.StartRequest + (*SetupRequest)(nil), // 6: hiddifyrpc.SetupRequest + (*Response)(nil), // 7: hiddifyrpc.Response + (*SystemInfo)(nil), // 8: hiddifyrpc.SystemInfo + (*OutboundGroupItem)(nil), // 9: hiddifyrpc.OutboundGroupItem + (*OutboundGroup)(nil), // 10: hiddifyrpc.OutboundGroup + (*OutboundGroupList)(nil), // 11: hiddifyrpc.OutboundGroupList + (*WarpAccount)(nil), // 12: hiddifyrpc.WarpAccount + (*WarpWireguardConfig)(nil), // 13: hiddifyrpc.WarpWireguardConfig + (*WarpGenerationResponse)(nil), // 14: hiddifyrpc.WarpGenerationResponse + (*SystemProxyStatus)(nil), // 15: hiddifyrpc.SystemProxyStatus + (*ParseRequest)(nil), // 16: hiddifyrpc.ParseRequest + (*ParseResponse)(nil), // 17: hiddifyrpc.ParseResponse + (*ChangeHiddifySettingsRequest)(nil), // 18: hiddifyrpc.ChangeHiddifySettingsRequest + (*GenerateConfigRequest)(nil), // 19: hiddifyrpc.GenerateConfigRequest + (*GenerateConfigResponse)(nil), // 20: hiddifyrpc.GenerateConfigResponse + (*SelectOutboundRequest)(nil), // 21: hiddifyrpc.SelectOutboundRequest + (*UrlTestRequest)(nil), // 22: hiddifyrpc.UrlTestRequest + (*GenerateWarpConfigRequest)(nil), // 23: hiddifyrpc.GenerateWarpConfigRequest + (*SetSystemProxyEnabledRequest)(nil), // 24: hiddifyrpc.SetSystemProxyEnabledRequest + (*LogMessage)(nil), // 25: hiddifyrpc.LogMessage + (*StopRequest)(nil), // 26: hiddifyrpc.StopRequest + (*TunnelStartRequest)(nil), // 27: hiddifyrpc.TunnelStartRequest + (*TunnelResponse)(nil), // 28: hiddifyrpc.TunnelResponse + (ResponseCode)(0), // 29: hiddifyrpc.ResponseCode + (*HelloRequest)(nil), // 30: hiddifyrpc.HelloRequest + (*Empty)(nil), // 31: hiddifyrpc.Empty + (*HelloResponse)(nil), // 32: hiddifyrpc.HelloResponse +} +var file_hiddify_proto_depIdxs = []int32{ + 0, // 0: hiddifyrpc.CoreInfoResponse.core_state:type_name -> hiddifyrpc.CoreState + 1, // 1: hiddifyrpc.CoreInfoResponse.message_type:type_name -> hiddifyrpc.MessageType + 29, // 2: hiddifyrpc.Response.response_code:type_name -> hiddifyrpc.ResponseCode + 9, // 3: hiddifyrpc.OutboundGroup.items:type_name -> hiddifyrpc.OutboundGroupItem + 10, // 4: hiddifyrpc.OutboundGroupList.items:type_name -> hiddifyrpc.OutboundGroup + 12, // 5: hiddifyrpc.WarpGenerationResponse.account:type_name -> hiddifyrpc.WarpAccount + 13, // 6: hiddifyrpc.WarpGenerationResponse.config:type_name -> hiddifyrpc.WarpWireguardConfig + 29, // 7: hiddifyrpc.ParseResponse.response_code:type_name -> hiddifyrpc.ResponseCode + 2, // 8: hiddifyrpc.LogMessage.level:type_name -> hiddifyrpc.LogLevel + 3, // 9: hiddifyrpc.LogMessage.type:type_name -> hiddifyrpc.LogType + 30, // 10: hiddifyrpc.Hello.SayHello:input_type -> hiddifyrpc.HelloRequest + 30, // 11: hiddifyrpc.Hello.SayHelloStream:input_type -> hiddifyrpc.HelloRequest + 5, // 12: hiddifyrpc.Core.Start:input_type -> hiddifyrpc.StartRequest + 31, // 13: hiddifyrpc.Core.CoreInfoListener:input_type -> hiddifyrpc.Empty + 31, // 14: hiddifyrpc.Core.OutboundsInfo:input_type -> hiddifyrpc.Empty + 31, // 15: hiddifyrpc.Core.MainOutboundsInfo:input_type -> hiddifyrpc.Empty + 31, // 16: hiddifyrpc.Core.GetSystemInfo:input_type -> hiddifyrpc.Empty + 6, // 17: hiddifyrpc.Core.Setup:input_type -> hiddifyrpc.SetupRequest + 16, // 18: hiddifyrpc.Core.Parse:input_type -> hiddifyrpc.ParseRequest + 18, // 19: hiddifyrpc.Core.ChangeHiddifySettings:input_type -> hiddifyrpc.ChangeHiddifySettingsRequest + 5, // 20: hiddifyrpc.Core.StartService:input_type -> hiddifyrpc.StartRequest + 31, // 21: hiddifyrpc.Core.Stop:input_type -> hiddifyrpc.Empty + 5, // 22: hiddifyrpc.Core.Restart:input_type -> hiddifyrpc.StartRequest + 21, // 23: hiddifyrpc.Core.SelectOutbound:input_type -> hiddifyrpc.SelectOutboundRequest + 22, // 24: hiddifyrpc.Core.UrlTest:input_type -> hiddifyrpc.UrlTestRequest + 23, // 25: hiddifyrpc.Core.GenerateWarpConfig:input_type -> hiddifyrpc.GenerateWarpConfigRequest + 31, // 26: hiddifyrpc.Core.GetSystemProxyStatus:input_type -> hiddifyrpc.Empty + 24, // 27: hiddifyrpc.Core.SetSystemProxyEnabled:input_type -> hiddifyrpc.SetSystemProxyEnabledRequest + 31, // 28: hiddifyrpc.Core.LogListener:input_type -> hiddifyrpc.Empty + 27, // 29: hiddifyrpc.TunnelService.Start:input_type -> hiddifyrpc.TunnelStartRequest + 31, // 30: hiddifyrpc.TunnelService.Stop:input_type -> hiddifyrpc.Empty + 31, // 31: hiddifyrpc.TunnelService.Status:input_type -> hiddifyrpc.Empty + 31, // 32: hiddifyrpc.TunnelService.Exit:input_type -> hiddifyrpc.Empty + 32, // 33: hiddifyrpc.Hello.SayHello:output_type -> hiddifyrpc.HelloResponse + 32, // 34: hiddifyrpc.Hello.SayHelloStream:output_type -> hiddifyrpc.HelloResponse + 4, // 35: hiddifyrpc.Core.Start:output_type -> hiddifyrpc.CoreInfoResponse + 4, // 36: hiddifyrpc.Core.CoreInfoListener:output_type -> hiddifyrpc.CoreInfoResponse + 11, // 37: hiddifyrpc.Core.OutboundsInfo:output_type -> hiddifyrpc.OutboundGroupList + 11, // 38: hiddifyrpc.Core.MainOutboundsInfo:output_type -> hiddifyrpc.OutboundGroupList + 8, // 39: hiddifyrpc.Core.GetSystemInfo:output_type -> hiddifyrpc.SystemInfo + 7, // 40: hiddifyrpc.Core.Setup:output_type -> hiddifyrpc.Response + 17, // 41: hiddifyrpc.Core.Parse:output_type -> hiddifyrpc.ParseResponse + 4, // 42: hiddifyrpc.Core.ChangeHiddifySettings:output_type -> hiddifyrpc.CoreInfoResponse + 4, // 43: hiddifyrpc.Core.StartService:output_type -> hiddifyrpc.CoreInfoResponse + 4, // 44: hiddifyrpc.Core.Stop:output_type -> hiddifyrpc.CoreInfoResponse + 4, // 45: hiddifyrpc.Core.Restart:output_type -> hiddifyrpc.CoreInfoResponse + 7, // 46: hiddifyrpc.Core.SelectOutbound:output_type -> hiddifyrpc.Response + 7, // 47: hiddifyrpc.Core.UrlTest:output_type -> hiddifyrpc.Response + 14, // 48: hiddifyrpc.Core.GenerateWarpConfig:output_type -> hiddifyrpc.WarpGenerationResponse + 15, // 49: hiddifyrpc.Core.GetSystemProxyStatus:output_type -> hiddifyrpc.SystemProxyStatus + 7, // 50: hiddifyrpc.Core.SetSystemProxyEnabled:output_type -> hiddifyrpc.Response + 25, // 51: hiddifyrpc.Core.LogListener:output_type -> hiddifyrpc.LogMessage + 28, // 52: hiddifyrpc.TunnelService.Start:output_type -> hiddifyrpc.TunnelResponse + 28, // 53: hiddifyrpc.TunnelService.Stop:output_type -> hiddifyrpc.TunnelResponse + 28, // 54: hiddifyrpc.TunnelService.Status:output_type -> hiddifyrpc.TunnelResponse + 28, // 55: hiddifyrpc.TunnelService.Exit:output_type -> hiddifyrpc.TunnelResponse + 33, // [33:56] is the sub-list for method output_type + 10, // [10:33] is the sub-list for method input_type + 10, // [10:10] is the sub-list for extension type_name + 10, // [10:10] is the sub-list for extension extendee + 0, // [0:10] is the sub-list for field type_name +} + +func init() { file_hiddify_proto_init() } +func file_hiddify_proto_init() { + if File_hiddify_proto != nil { + return + } + file_base_proto_init() + if !protoimpl.UnsafeEnabled { + file_hiddify_proto_msgTypes[0].Exporter = func(v any, i int) any { + switch v := v.(*CoreInfoResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_hiddify_proto_msgTypes[1].Exporter = func(v any, i int) any { + switch v := v.(*StartRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_hiddify_proto_msgTypes[2].Exporter = func(v any, i int) any { + switch v := v.(*SetupRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_hiddify_proto_msgTypes[3].Exporter = func(v any, i int) any { + switch v := v.(*Response); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_hiddify_proto_msgTypes[4].Exporter = func(v any, i int) any { + switch v := v.(*SystemInfo); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_hiddify_proto_msgTypes[5].Exporter = func(v any, i int) any { + switch v := v.(*OutboundGroupItem); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_hiddify_proto_msgTypes[6].Exporter = func(v any, i int) any { + switch v := v.(*OutboundGroup); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_hiddify_proto_msgTypes[7].Exporter = func(v any, i int) any { + switch v := v.(*OutboundGroupList); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_hiddify_proto_msgTypes[8].Exporter = func(v any, i int) any { + switch v := v.(*WarpAccount); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_hiddify_proto_msgTypes[9].Exporter = func(v any, i int) any { + switch v := v.(*WarpWireguardConfig); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_hiddify_proto_msgTypes[10].Exporter = func(v any, i int) any { + switch v := v.(*WarpGenerationResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_hiddify_proto_msgTypes[11].Exporter = func(v any, i int) any { + switch v := v.(*SystemProxyStatus); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_hiddify_proto_msgTypes[12].Exporter = func(v any, i int) any { + switch v := v.(*ParseRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_hiddify_proto_msgTypes[13].Exporter = func(v any, i int) any { + switch v := v.(*ParseResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_hiddify_proto_msgTypes[14].Exporter = func(v any, i int) any { + switch v := v.(*ChangeHiddifySettingsRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_hiddify_proto_msgTypes[15].Exporter = func(v any, i int) any { + switch v := v.(*GenerateConfigRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_hiddify_proto_msgTypes[16].Exporter = func(v any, i int) any { + switch v := v.(*GenerateConfigResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_hiddify_proto_msgTypes[17].Exporter = func(v any, i int) any { + switch v := v.(*SelectOutboundRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_hiddify_proto_msgTypes[18].Exporter = func(v any, i int) any { + switch v := v.(*UrlTestRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_hiddify_proto_msgTypes[19].Exporter = func(v any, i int) any { + switch v := v.(*GenerateWarpConfigRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_hiddify_proto_msgTypes[20].Exporter = func(v any, i int) any { + switch v := v.(*SetSystemProxyEnabledRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_hiddify_proto_msgTypes[21].Exporter = func(v any, i int) any { + switch v := v.(*LogMessage); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_hiddify_proto_msgTypes[22].Exporter = func(v any, i int) any { + switch v := v.(*StopRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_hiddify_proto_msgTypes[23].Exporter = func(v any, i int) any { + switch v := v.(*TunnelStartRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_hiddify_proto_msgTypes[24].Exporter = func(v any, i int) any { + switch v := v.(*TunnelResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_hiddify_proto_rawDesc, + NumEnums: 4, + NumMessages: 25, + NumExtensions: 0, + NumServices: 3, + }, + GoTypes: file_hiddify_proto_goTypes, + DependencyIndexes: file_hiddify_proto_depIdxs, + EnumInfos: file_hiddify_proto_enumTypes, + MessageInfos: file_hiddify_proto_msgTypes, + }.Build() + File_hiddify_proto = out.File + file_hiddify_proto_rawDesc = nil + file_hiddify_proto_goTypes = nil + file_hiddify_proto_depIdxs = nil +} diff --git a/libcore/hiddifyrpc/hiddify.proto b/libcore/hiddifyrpc/hiddify.proto new file mode 100644 index 0000000..fc515e9 --- /dev/null +++ b/libcore/hiddifyrpc/hiddify.proto @@ -0,0 +1,229 @@ +syntax = "proto3"; +import "base.proto"; +package hiddifyrpc; + +option go_package = "./hiddifyrpc"; + + +enum CoreState { + STOPPED = 0; + STARTING = 1; + STARTED = 2; + STOPPING = 3; +} + +enum MessageType { + EMPTY=0; + EMPTY_CONFIGURATION = 1; + START_COMMAND_SERVER = 2; + CREATE_SERVICE = 3; + START_SERVICE = 4; + UNEXPECTED_ERROR = 5; + ALREADY_STARTED = 6; + ALREADY_STOPPED = 7; + INSTANCE_NOT_FOUND = 8; + INSTANCE_NOT_STOPPED = 9; + INSTANCE_NOT_STARTED = 10; + ERROR_BUILDING_CONFIG = 11; + ERROR_PARSING_CONFIG = 12; + ERROR_READING_CONFIG = 13; +} + +message CoreInfoResponse { + CoreState core_state = 1; + MessageType message_type = 2; + string message = 3; +} + +message StartRequest { + string config_path = 1; + string config_content = 2; // Optional if configPath is not provided. + bool disable_memory_limit = 3; + bool delay_start = 4; + bool enable_old_command_server = 5; + bool enable_raw_config = 6; +} + +message SetupRequest { + string base_path = 1; + string working_path = 2; + string temp_path = 3; +} + +message Response { + ResponseCode response_code = 1; + string message = 2; +} + + +message SystemInfo { + int64 memory = 1; + int32 goroutines = 2; + int32 connections_in = 3; + int32 connections_out = 4; + bool traffic_available = 5; + int64 uplink = 6; + int64 downlink = 7; + int64 uplink_total = 8; + int64 downlink_total = 9; +} + +message OutboundGroupItem { + string tag = 1; + string type = 2; + int64 url_test_time = 3; + int32 url_test_delay = 4; +} + +message OutboundGroup { + string tag = 1; + string type = 2; + string selected=3; + repeated OutboundGroupItem items = 4; + +} +message OutboundGroupList{ + repeated OutboundGroup items = 1; +} + +message WarpAccount { + string account_id = 1; + string access_token = 2; +} + +message WarpWireguardConfig { + string private_key = 1; + string local_address_ipv4 = 2; + string local_address_ipv6 = 3; + string peer_public_key = 4; + string client_id=5; +} + +message WarpGenerationResponse { + WarpAccount account = 1; + string log = 2; + WarpWireguardConfig config = 3; +} + +message SystemProxyStatus { + bool available = 1; + bool enabled = 2; +} + +message ParseRequest { + string content = 1; + string config_path = 2; + string temp_path = 3; + bool debug = 4; +} + +message ParseResponse { + ResponseCode response_code = 1; + string content = 2; + string message = 3; +} + +message ChangeHiddifySettingsRequest { + string hiddify_settings_json = 1; +} + +message GenerateConfigRequest { + string path = 1; + string temp_path = 2; + bool debug = 3; +} + +message GenerateConfigResponse { + string config_content = 1; +} + + + +message SelectOutboundRequest { + string group_tag = 1; + string outbound_tag = 2; +} + +message UrlTestRequest { + string group_tag = 1; +} + +message GenerateWarpConfigRequest { + string license_key = 1; + string account_id = 2; + string access_token = 3; +} + +message SetSystemProxyEnabledRequest { + bool is_enabled = 1; +} + +enum LogLevel { + DEBUG = 0; + INFO = 1; + WARNING = 2; + ERROR = 3; + FATAL = 4; +} +enum LogType { + CORE = 0; + SERVICE = 1; + CONFIG = 2; +} +message LogMessage { + LogLevel level = 1; + LogType type = 2; + string message = 3; +} + +message StopRequest{ +} + + + +message TunnelStartRequest { + bool ipv6 = 1; + int32 server_port = 2; + bool strict_route = 3; + bool endpoint_independent_nat = 4; + string stack = 5; + +} + +message TunnelResponse { + string message = 1; +} + +service Hello { + rpc SayHello (HelloRequest) returns (HelloResponse); + rpc SayHelloStream (stream HelloRequest) returns (stream HelloResponse); +} +service Core { + rpc Start (StartRequest) returns (CoreInfoResponse); + rpc CoreInfoListener (Empty) returns (stream CoreInfoResponse); + rpc OutboundsInfo (Empty) returns (stream OutboundGroupList); + rpc MainOutboundsInfo (Empty) returns (stream OutboundGroupList); + rpc GetSystemInfo (Empty) returns (stream SystemInfo); + rpc Setup (SetupRequest) returns (Response); + rpc Parse (ParseRequest) returns (ParseResponse); + rpc ChangeHiddifySettings (ChangeHiddifySettingsRequest) returns (CoreInfoResponse); + //rpc GenerateConfig (GenerateConfigRequest) returns (GenerateConfigResponse); + rpc StartService (StartRequest) returns (CoreInfoResponse); + rpc Stop (Empty) returns (CoreInfoResponse); + rpc Restart (StartRequest) returns (CoreInfoResponse); + rpc SelectOutbound (SelectOutboundRequest) returns (Response); + rpc UrlTest (UrlTestRequest) returns (Response); + rpc GenerateWarpConfig (GenerateWarpConfigRequest) returns (WarpGenerationResponse); + rpc GetSystemProxyStatus (Empty) returns (SystemProxyStatus); + rpc SetSystemProxyEnabled (SetSystemProxyEnabledRequest) returns (Response); + rpc LogListener (Empty) returns (stream LogMessage); +} + + + +service TunnelService { + rpc Start(TunnelStartRequest ) returns (TunnelResponse); + rpc Stop(Empty) returns (TunnelResponse); + rpc Status(Empty) returns (TunnelResponse); + rpc Exit(Empty) returns (TunnelResponse); +} \ No newline at end of file diff --git a/libcore/hiddifyrpc/hiddify_grpc.pb.go b/libcore/hiddifyrpc/hiddify_grpc.pb.go new file mode 100644 index 0000000..21e6fd2 --- /dev/null +++ b/libcore/hiddifyrpc/hiddify_grpc.pb.go @@ -0,0 +1,1098 @@ +// Code generated by protoc-gen-go-grpc. DO NOT EDIT. +// versions: +// - protoc-gen-go-grpc v1.5.1 +// - protoc v5.28.0 +// source: hiddify.proto + +package hiddifyrpc + +import ( + context "context" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" +) + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +// Requires gRPC-Go v1.64.0 or later. +const _ = grpc.SupportPackageIsVersion9 + +const ( + Hello_SayHello_FullMethodName = "/hiddifyrpc.Hello/SayHello" + Hello_SayHelloStream_FullMethodName = "/hiddifyrpc.Hello/SayHelloStream" +) + +// HelloClient is the client API for Hello service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +type HelloClient interface { + SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloResponse, error) + SayHelloStream(ctx context.Context, opts ...grpc.CallOption) (grpc.BidiStreamingClient[HelloRequest, HelloResponse], error) +} + +type helloClient struct { + cc grpc.ClientConnInterface +} + +func NewHelloClient(cc grpc.ClientConnInterface) HelloClient { + return &helloClient{cc} +} + +func (c *helloClient) SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(HelloResponse) + err := c.cc.Invoke(ctx, Hello_SayHello_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *helloClient) SayHelloStream(ctx context.Context, opts ...grpc.CallOption) (grpc.BidiStreamingClient[HelloRequest, HelloResponse], error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + stream, err := c.cc.NewStream(ctx, &Hello_ServiceDesc.Streams[0], Hello_SayHelloStream_FullMethodName, cOpts...) + if err != nil { + return nil, err + } + x := &grpc.GenericClientStream[HelloRequest, HelloResponse]{ClientStream: stream} + return x, nil +} + +// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name. +type Hello_SayHelloStreamClient = grpc.BidiStreamingClient[HelloRequest, HelloResponse] + +// HelloServer is the server API for Hello service. +// All implementations must embed UnimplementedHelloServer +// for forward compatibility. +type HelloServer interface { + SayHello(context.Context, *HelloRequest) (*HelloResponse, error) + SayHelloStream(grpc.BidiStreamingServer[HelloRequest, HelloResponse]) error + mustEmbedUnimplementedHelloServer() +} + +// UnimplementedHelloServer must be embedded to have +// forward compatible implementations. +// +// NOTE: this should be embedded by value instead of pointer to avoid a nil +// pointer dereference when methods are called. +type UnimplementedHelloServer struct{} + +func (UnimplementedHelloServer) SayHello(context.Context, *HelloRequest) (*HelloResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method SayHello not implemented") +} +func (UnimplementedHelloServer) SayHelloStream(grpc.BidiStreamingServer[HelloRequest, HelloResponse]) error { + return status.Errorf(codes.Unimplemented, "method SayHelloStream not implemented") +} +func (UnimplementedHelloServer) mustEmbedUnimplementedHelloServer() {} +func (UnimplementedHelloServer) testEmbeddedByValue() {} + +// UnsafeHelloServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to HelloServer will +// result in compilation errors. +type UnsafeHelloServer interface { + mustEmbedUnimplementedHelloServer() +} + +func RegisterHelloServer(s grpc.ServiceRegistrar, srv HelloServer) { + // If the following call pancis, it indicates UnimplementedHelloServer was + // embedded by pointer and is nil. This will cause panics if an + // unimplemented method is ever invoked, so we test this at initialization + // time to prevent it from happening at runtime later due to I/O. + if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { + t.testEmbeddedByValue() + } + s.RegisterService(&Hello_ServiceDesc, srv) +} + +func _Hello_SayHello_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(HelloRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(HelloServer).SayHello(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: Hello_SayHello_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(HelloServer).SayHello(ctx, req.(*HelloRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Hello_SayHelloStream_Handler(srv interface{}, stream grpc.ServerStream) error { + return srv.(HelloServer).SayHelloStream(&grpc.GenericServerStream[HelloRequest, HelloResponse]{ServerStream: stream}) +} + +// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name. +type Hello_SayHelloStreamServer = grpc.BidiStreamingServer[HelloRequest, HelloResponse] + +// Hello_ServiceDesc is the grpc.ServiceDesc for Hello service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var Hello_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "hiddifyrpc.Hello", + HandlerType: (*HelloServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "SayHello", + Handler: _Hello_SayHello_Handler, + }, + }, + Streams: []grpc.StreamDesc{ + { + StreamName: "SayHelloStream", + Handler: _Hello_SayHelloStream_Handler, + ServerStreams: true, + ClientStreams: true, + }, + }, + Metadata: "hiddify.proto", +} + +const ( + Core_Start_FullMethodName = "/hiddifyrpc.Core/Start" + Core_CoreInfoListener_FullMethodName = "/hiddifyrpc.Core/CoreInfoListener" + Core_OutboundsInfo_FullMethodName = "/hiddifyrpc.Core/OutboundsInfo" + Core_MainOutboundsInfo_FullMethodName = "/hiddifyrpc.Core/MainOutboundsInfo" + Core_GetSystemInfo_FullMethodName = "/hiddifyrpc.Core/GetSystemInfo" + Core_Setup_FullMethodName = "/hiddifyrpc.Core/Setup" + Core_Parse_FullMethodName = "/hiddifyrpc.Core/Parse" + Core_ChangeHiddifySettings_FullMethodName = "/hiddifyrpc.Core/ChangeHiddifySettings" + Core_StartService_FullMethodName = "/hiddifyrpc.Core/StartService" + Core_Stop_FullMethodName = "/hiddifyrpc.Core/Stop" + Core_Restart_FullMethodName = "/hiddifyrpc.Core/Restart" + Core_SelectOutbound_FullMethodName = "/hiddifyrpc.Core/SelectOutbound" + Core_UrlTest_FullMethodName = "/hiddifyrpc.Core/UrlTest" + Core_GenerateWarpConfig_FullMethodName = "/hiddifyrpc.Core/GenerateWarpConfig" + Core_GetSystemProxyStatus_FullMethodName = "/hiddifyrpc.Core/GetSystemProxyStatus" + Core_SetSystemProxyEnabled_FullMethodName = "/hiddifyrpc.Core/SetSystemProxyEnabled" + Core_LogListener_FullMethodName = "/hiddifyrpc.Core/LogListener" +) + +// CoreClient is the client API for Core service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +type CoreClient interface { + Start(ctx context.Context, in *StartRequest, opts ...grpc.CallOption) (*CoreInfoResponse, error) + CoreInfoListener(ctx context.Context, in *Empty, opts ...grpc.CallOption) (grpc.ServerStreamingClient[CoreInfoResponse], error) + OutboundsInfo(ctx context.Context, in *Empty, opts ...grpc.CallOption) (grpc.ServerStreamingClient[OutboundGroupList], error) + MainOutboundsInfo(ctx context.Context, in *Empty, opts ...grpc.CallOption) (grpc.ServerStreamingClient[OutboundGroupList], error) + GetSystemInfo(ctx context.Context, in *Empty, opts ...grpc.CallOption) (grpc.ServerStreamingClient[SystemInfo], error) + Setup(ctx context.Context, in *SetupRequest, opts ...grpc.CallOption) (*Response, error) + Parse(ctx context.Context, in *ParseRequest, opts ...grpc.CallOption) (*ParseResponse, error) + ChangeHiddifySettings(ctx context.Context, in *ChangeHiddifySettingsRequest, opts ...grpc.CallOption) (*CoreInfoResponse, error) + //rpc GenerateConfig (GenerateConfigRequest) returns (GenerateConfigResponse); + StartService(ctx context.Context, in *StartRequest, opts ...grpc.CallOption) (*CoreInfoResponse, error) + Stop(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*CoreInfoResponse, error) + Restart(ctx context.Context, in *StartRequest, opts ...grpc.CallOption) (*CoreInfoResponse, error) + SelectOutbound(ctx context.Context, in *SelectOutboundRequest, opts ...grpc.CallOption) (*Response, error) + UrlTest(ctx context.Context, in *UrlTestRequest, opts ...grpc.CallOption) (*Response, error) + GenerateWarpConfig(ctx context.Context, in *GenerateWarpConfigRequest, opts ...grpc.CallOption) (*WarpGenerationResponse, error) + GetSystemProxyStatus(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*SystemProxyStatus, error) + SetSystemProxyEnabled(ctx context.Context, in *SetSystemProxyEnabledRequest, opts ...grpc.CallOption) (*Response, error) + LogListener(ctx context.Context, in *Empty, opts ...grpc.CallOption) (grpc.ServerStreamingClient[LogMessage], error) +} + +type coreClient struct { + cc grpc.ClientConnInterface +} + +func NewCoreClient(cc grpc.ClientConnInterface) CoreClient { + return &coreClient{cc} +} + +func (c *coreClient) Start(ctx context.Context, in *StartRequest, opts ...grpc.CallOption) (*CoreInfoResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(CoreInfoResponse) + err := c.cc.Invoke(ctx, Core_Start_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *coreClient) CoreInfoListener(ctx context.Context, in *Empty, opts ...grpc.CallOption) (grpc.ServerStreamingClient[CoreInfoResponse], error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + stream, err := c.cc.NewStream(ctx, &Core_ServiceDesc.Streams[0], Core_CoreInfoListener_FullMethodName, cOpts...) + if err != nil { + return nil, err + } + x := &grpc.GenericClientStream[Empty, CoreInfoResponse]{ClientStream: stream} + if err := x.ClientStream.SendMsg(in); err != nil { + return nil, err + } + if err := x.ClientStream.CloseSend(); err != nil { + return nil, err + } + return x, nil +} + +// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name. +type Core_CoreInfoListenerClient = grpc.ServerStreamingClient[CoreInfoResponse] + +func (c *coreClient) OutboundsInfo(ctx context.Context, in *Empty, opts ...grpc.CallOption) (grpc.ServerStreamingClient[OutboundGroupList], error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + stream, err := c.cc.NewStream(ctx, &Core_ServiceDesc.Streams[1], Core_OutboundsInfo_FullMethodName, cOpts...) + if err != nil { + return nil, err + } + x := &grpc.GenericClientStream[Empty, OutboundGroupList]{ClientStream: stream} + if err := x.ClientStream.SendMsg(in); err != nil { + return nil, err + } + if err := x.ClientStream.CloseSend(); err != nil { + return nil, err + } + return x, nil +} + +// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name. +type Core_OutboundsInfoClient = grpc.ServerStreamingClient[OutboundGroupList] + +func (c *coreClient) MainOutboundsInfo(ctx context.Context, in *Empty, opts ...grpc.CallOption) (grpc.ServerStreamingClient[OutboundGroupList], error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + stream, err := c.cc.NewStream(ctx, &Core_ServiceDesc.Streams[2], Core_MainOutboundsInfo_FullMethodName, cOpts...) + if err != nil { + return nil, err + } + x := &grpc.GenericClientStream[Empty, OutboundGroupList]{ClientStream: stream} + if err := x.ClientStream.SendMsg(in); err != nil { + return nil, err + } + if err := x.ClientStream.CloseSend(); err != nil { + return nil, err + } + return x, nil +} + +// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name. +type Core_MainOutboundsInfoClient = grpc.ServerStreamingClient[OutboundGroupList] + +func (c *coreClient) GetSystemInfo(ctx context.Context, in *Empty, opts ...grpc.CallOption) (grpc.ServerStreamingClient[SystemInfo], error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + stream, err := c.cc.NewStream(ctx, &Core_ServiceDesc.Streams[3], Core_GetSystemInfo_FullMethodName, cOpts...) + if err != nil { + return nil, err + } + x := &grpc.GenericClientStream[Empty, SystemInfo]{ClientStream: stream} + if err := x.ClientStream.SendMsg(in); err != nil { + return nil, err + } + if err := x.ClientStream.CloseSend(); err != nil { + return nil, err + } + return x, nil +} + +// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name. +type Core_GetSystemInfoClient = grpc.ServerStreamingClient[SystemInfo] + +func (c *coreClient) Setup(ctx context.Context, in *SetupRequest, opts ...grpc.CallOption) (*Response, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(Response) + err := c.cc.Invoke(ctx, Core_Setup_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *coreClient) Parse(ctx context.Context, in *ParseRequest, opts ...grpc.CallOption) (*ParseResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(ParseResponse) + err := c.cc.Invoke(ctx, Core_Parse_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *coreClient) ChangeHiddifySettings(ctx context.Context, in *ChangeHiddifySettingsRequest, opts ...grpc.CallOption) (*CoreInfoResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(CoreInfoResponse) + err := c.cc.Invoke(ctx, Core_ChangeHiddifySettings_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *coreClient) StartService(ctx context.Context, in *StartRequest, opts ...grpc.CallOption) (*CoreInfoResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(CoreInfoResponse) + err := c.cc.Invoke(ctx, Core_StartService_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *coreClient) Stop(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*CoreInfoResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(CoreInfoResponse) + err := c.cc.Invoke(ctx, Core_Stop_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *coreClient) Restart(ctx context.Context, in *StartRequest, opts ...grpc.CallOption) (*CoreInfoResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(CoreInfoResponse) + err := c.cc.Invoke(ctx, Core_Restart_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *coreClient) SelectOutbound(ctx context.Context, in *SelectOutboundRequest, opts ...grpc.CallOption) (*Response, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(Response) + err := c.cc.Invoke(ctx, Core_SelectOutbound_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *coreClient) UrlTest(ctx context.Context, in *UrlTestRequest, opts ...grpc.CallOption) (*Response, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(Response) + err := c.cc.Invoke(ctx, Core_UrlTest_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *coreClient) GenerateWarpConfig(ctx context.Context, in *GenerateWarpConfigRequest, opts ...grpc.CallOption) (*WarpGenerationResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(WarpGenerationResponse) + err := c.cc.Invoke(ctx, Core_GenerateWarpConfig_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *coreClient) GetSystemProxyStatus(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*SystemProxyStatus, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(SystemProxyStatus) + err := c.cc.Invoke(ctx, Core_GetSystemProxyStatus_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *coreClient) SetSystemProxyEnabled(ctx context.Context, in *SetSystemProxyEnabledRequest, opts ...grpc.CallOption) (*Response, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(Response) + err := c.cc.Invoke(ctx, Core_SetSystemProxyEnabled_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *coreClient) LogListener(ctx context.Context, in *Empty, opts ...grpc.CallOption) (grpc.ServerStreamingClient[LogMessage], error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + stream, err := c.cc.NewStream(ctx, &Core_ServiceDesc.Streams[4], Core_LogListener_FullMethodName, cOpts...) + if err != nil { + return nil, err + } + x := &grpc.GenericClientStream[Empty, LogMessage]{ClientStream: stream} + if err := x.ClientStream.SendMsg(in); err != nil { + return nil, err + } + if err := x.ClientStream.CloseSend(); err != nil { + return nil, err + } + return x, nil +} + +// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name. +type Core_LogListenerClient = grpc.ServerStreamingClient[LogMessage] + +// CoreServer is the server API for Core service. +// All implementations must embed UnimplementedCoreServer +// for forward compatibility. +type CoreServer interface { + Start(context.Context, *StartRequest) (*CoreInfoResponse, error) + CoreInfoListener(*Empty, grpc.ServerStreamingServer[CoreInfoResponse]) error + OutboundsInfo(*Empty, grpc.ServerStreamingServer[OutboundGroupList]) error + MainOutboundsInfo(*Empty, grpc.ServerStreamingServer[OutboundGroupList]) error + GetSystemInfo(*Empty, grpc.ServerStreamingServer[SystemInfo]) error + Setup(context.Context, *SetupRequest) (*Response, error) + Parse(context.Context, *ParseRequest) (*ParseResponse, error) + ChangeHiddifySettings(context.Context, *ChangeHiddifySettingsRequest) (*CoreInfoResponse, error) + //rpc GenerateConfig (GenerateConfigRequest) returns (GenerateConfigResponse); + StartService(context.Context, *StartRequest) (*CoreInfoResponse, error) + Stop(context.Context, *Empty) (*CoreInfoResponse, error) + Restart(context.Context, *StartRequest) (*CoreInfoResponse, error) + SelectOutbound(context.Context, *SelectOutboundRequest) (*Response, error) + UrlTest(context.Context, *UrlTestRequest) (*Response, error) + GenerateWarpConfig(context.Context, *GenerateWarpConfigRequest) (*WarpGenerationResponse, error) + GetSystemProxyStatus(context.Context, *Empty) (*SystemProxyStatus, error) + SetSystemProxyEnabled(context.Context, *SetSystemProxyEnabledRequest) (*Response, error) + LogListener(*Empty, grpc.ServerStreamingServer[LogMessage]) error + mustEmbedUnimplementedCoreServer() +} + +// UnimplementedCoreServer must be embedded to have +// forward compatible implementations. +// +// NOTE: this should be embedded by value instead of pointer to avoid a nil +// pointer dereference when methods are called. +type UnimplementedCoreServer struct{} + +func (UnimplementedCoreServer) Start(context.Context, *StartRequest) (*CoreInfoResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method Start not implemented") +} +func (UnimplementedCoreServer) CoreInfoListener(*Empty, grpc.ServerStreamingServer[CoreInfoResponse]) error { + return status.Errorf(codes.Unimplemented, "method CoreInfoListener not implemented") +} +func (UnimplementedCoreServer) OutboundsInfo(*Empty, grpc.ServerStreamingServer[OutboundGroupList]) error { + return status.Errorf(codes.Unimplemented, "method OutboundsInfo not implemented") +} +func (UnimplementedCoreServer) MainOutboundsInfo(*Empty, grpc.ServerStreamingServer[OutboundGroupList]) error { + return status.Errorf(codes.Unimplemented, "method MainOutboundsInfo not implemented") +} +func (UnimplementedCoreServer) GetSystemInfo(*Empty, grpc.ServerStreamingServer[SystemInfo]) error { + return status.Errorf(codes.Unimplemented, "method GetSystemInfo not implemented") +} +func (UnimplementedCoreServer) Setup(context.Context, *SetupRequest) (*Response, error) { + return nil, status.Errorf(codes.Unimplemented, "method Setup not implemented") +} +func (UnimplementedCoreServer) Parse(context.Context, *ParseRequest) (*ParseResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method Parse not implemented") +} +func (UnimplementedCoreServer) ChangeHiddifySettings(context.Context, *ChangeHiddifySettingsRequest) (*CoreInfoResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method ChangeHiddifySettings not implemented") +} +func (UnimplementedCoreServer) StartService(context.Context, *StartRequest) (*CoreInfoResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method StartService not implemented") +} +func (UnimplementedCoreServer) Stop(context.Context, *Empty) (*CoreInfoResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method Stop not implemented") +} +func (UnimplementedCoreServer) Restart(context.Context, *StartRequest) (*CoreInfoResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method Restart not implemented") +} +func (UnimplementedCoreServer) SelectOutbound(context.Context, *SelectOutboundRequest) (*Response, error) { + return nil, status.Errorf(codes.Unimplemented, "method SelectOutbound not implemented") +} +func (UnimplementedCoreServer) UrlTest(context.Context, *UrlTestRequest) (*Response, error) { + return nil, status.Errorf(codes.Unimplemented, "method UrlTest not implemented") +} +func (UnimplementedCoreServer) GenerateWarpConfig(context.Context, *GenerateWarpConfigRequest) (*WarpGenerationResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method GenerateWarpConfig not implemented") +} +func (UnimplementedCoreServer) GetSystemProxyStatus(context.Context, *Empty) (*SystemProxyStatus, error) { + return nil, status.Errorf(codes.Unimplemented, "method GetSystemProxyStatus not implemented") +} +func (UnimplementedCoreServer) SetSystemProxyEnabled(context.Context, *SetSystemProxyEnabledRequest) (*Response, error) { + return nil, status.Errorf(codes.Unimplemented, "method SetSystemProxyEnabled not implemented") +} +func (UnimplementedCoreServer) LogListener(*Empty, grpc.ServerStreamingServer[LogMessage]) error { + return status.Errorf(codes.Unimplemented, "method LogListener not implemented") +} +func (UnimplementedCoreServer) mustEmbedUnimplementedCoreServer() {} +func (UnimplementedCoreServer) testEmbeddedByValue() {} + +// UnsafeCoreServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to CoreServer will +// result in compilation errors. +type UnsafeCoreServer interface { + mustEmbedUnimplementedCoreServer() +} + +func RegisterCoreServer(s grpc.ServiceRegistrar, srv CoreServer) { + // If the following call pancis, it indicates UnimplementedCoreServer was + // embedded by pointer and is nil. This will cause panics if an + // unimplemented method is ever invoked, so we test this at initialization + // time to prevent it from happening at runtime later due to I/O. + if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { + t.testEmbeddedByValue() + } + s.RegisterService(&Core_ServiceDesc, srv) +} + +func _Core_Start_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(StartRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(CoreServer).Start(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: Core_Start_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(CoreServer).Start(ctx, req.(*StartRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Core_CoreInfoListener_Handler(srv interface{}, stream grpc.ServerStream) error { + m := new(Empty) + if err := stream.RecvMsg(m); err != nil { + return err + } + return srv.(CoreServer).CoreInfoListener(m, &grpc.GenericServerStream[Empty, CoreInfoResponse]{ServerStream: stream}) +} + +// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name. +type Core_CoreInfoListenerServer = grpc.ServerStreamingServer[CoreInfoResponse] + +func _Core_OutboundsInfo_Handler(srv interface{}, stream grpc.ServerStream) error { + m := new(Empty) + if err := stream.RecvMsg(m); err != nil { + return err + } + return srv.(CoreServer).OutboundsInfo(m, &grpc.GenericServerStream[Empty, OutboundGroupList]{ServerStream: stream}) +} + +// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name. +type Core_OutboundsInfoServer = grpc.ServerStreamingServer[OutboundGroupList] + +func _Core_MainOutboundsInfo_Handler(srv interface{}, stream grpc.ServerStream) error { + m := new(Empty) + if err := stream.RecvMsg(m); err != nil { + return err + } + return srv.(CoreServer).MainOutboundsInfo(m, &grpc.GenericServerStream[Empty, OutboundGroupList]{ServerStream: stream}) +} + +// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name. +type Core_MainOutboundsInfoServer = grpc.ServerStreamingServer[OutboundGroupList] + +func _Core_GetSystemInfo_Handler(srv interface{}, stream grpc.ServerStream) error { + m := new(Empty) + if err := stream.RecvMsg(m); err != nil { + return err + } + return srv.(CoreServer).GetSystemInfo(m, &grpc.GenericServerStream[Empty, SystemInfo]{ServerStream: stream}) +} + +// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name. +type Core_GetSystemInfoServer = grpc.ServerStreamingServer[SystemInfo] + +func _Core_Setup_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(SetupRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(CoreServer).Setup(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: Core_Setup_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(CoreServer).Setup(ctx, req.(*SetupRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Core_Parse_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(ParseRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(CoreServer).Parse(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: Core_Parse_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(CoreServer).Parse(ctx, req.(*ParseRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Core_ChangeHiddifySettings_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(ChangeHiddifySettingsRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(CoreServer).ChangeHiddifySettings(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: Core_ChangeHiddifySettings_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(CoreServer).ChangeHiddifySettings(ctx, req.(*ChangeHiddifySettingsRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Core_StartService_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(StartRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(CoreServer).StartService(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: Core_StartService_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(CoreServer).StartService(ctx, req.(*StartRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Core_Stop_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(Empty) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(CoreServer).Stop(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: Core_Stop_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(CoreServer).Stop(ctx, req.(*Empty)) + } + return interceptor(ctx, in, info, handler) +} + +func _Core_Restart_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(StartRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(CoreServer).Restart(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: Core_Restart_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(CoreServer).Restart(ctx, req.(*StartRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Core_SelectOutbound_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(SelectOutboundRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(CoreServer).SelectOutbound(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: Core_SelectOutbound_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(CoreServer).SelectOutbound(ctx, req.(*SelectOutboundRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Core_UrlTest_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(UrlTestRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(CoreServer).UrlTest(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: Core_UrlTest_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(CoreServer).UrlTest(ctx, req.(*UrlTestRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Core_GenerateWarpConfig_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GenerateWarpConfigRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(CoreServer).GenerateWarpConfig(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: Core_GenerateWarpConfig_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(CoreServer).GenerateWarpConfig(ctx, req.(*GenerateWarpConfigRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Core_GetSystemProxyStatus_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(Empty) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(CoreServer).GetSystemProxyStatus(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: Core_GetSystemProxyStatus_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(CoreServer).GetSystemProxyStatus(ctx, req.(*Empty)) + } + return interceptor(ctx, in, info, handler) +} + +func _Core_SetSystemProxyEnabled_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(SetSystemProxyEnabledRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(CoreServer).SetSystemProxyEnabled(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: Core_SetSystemProxyEnabled_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(CoreServer).SetSystemProxyEnabled(ctx, req.(*SetSystemProxyEnabledRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Core_LogListener_Handler(srv interface{}, stream grpc.ServerStream) error { + m := new(Empty) + if err := stream.RecvMsg(m); err != nil { + return err + } + return srv.(CoreServer).LogListener(m, &grpc.GenericServerStream[Empty, LogMessage]{ServerStream: stream}) +} + +// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name. +type Core_LogListenerServer = grpc.ServerStreamingServer[LogMessage] + +// Core_ServiceDesc is the grpc.ServiceDesc for Core service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var Core_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "hiddifyrpc.Core", + HandlerType: (*CoreServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "Start", + Handler: _Core_Start_Handler, + }, + { + MethodName: "Setup", + Handler: _Core_Setup_Handler, + }, + { + MethodName: "Parse", + Handler: _Core_Parse_Handler, + }, + { + MethodName: "ChangeHiddifySettings", + Handler: _Core_ChangeHiddifySettings_Handler, + }, + { + MethodName: "StartService", + Handler: _Core_StartService_Handler, + }, + { + MethodName: "Stop", + Handler: _Core_Stop_Handler, + }, + { + MethodName: "Restart", + Handler: _Core_Restart_Handler, + }, + { + MethodName: "SelectOutbound", + Handler: _Core_SelectOutbound_Handler, + }, + { + MethodName: "UrlTest", + Handler: _Core_UrlTest_Handler, + }, + { + MethodName: "GenerateWarpConfig", + Handler: _Core_GenerateWarpConfig_Handler, + }, + { + MethodName: "GetSystemProxyStatus", + Handler: _Core_GetSystemProxyStatus_Handler, + }, + { + MethodName: "SetSystemProxyEnabled", + Handler: _Core_SetSystemProxyEnabled_Handler, + }, + }, + Streams: []grpc.StreamDesc{ + { + StreamName: "CoreInfoListener", + Handler: _Core_CoreInfoListener_Handler, + ServerStreams: true, + }, + { + StreamName: "OutboundsInfo", + Handler: _Core_OutboundsInfo_Handler, + ServerStreams: true, + }, + { + StreamName: "MainOutboundsInfo", + Handler: _Core_MainOutboundsInfo_Handler, + ServerStreams: true, + }, + { + StreamName: "GetSystemInfo", + Handler: _Core_GetSystemInfo_Handler, + ServerStreams: true, + }, + { + StreamName: "LogListener", + Handler: _Core_LogListener_Handler, + ServerStreams: true, + }, + }, + Metadata: "hiddify.proto", +} + +const ( + TunnelService_Start_FullMethodName = "/hiddifyrpc.TunnelService/Start" + TunnelService_Stop_FullMethodName = "/hiddifyrpc.TunnelService/Stop" + TunnelService_Status_FullMethodName = "/hiddifyrpc.TunnelService/Status" + TunnelService_Exit_FullMethodName = "/hiddifyrpc.TunnelService/Exit" +) + +// TunnelServiceClient is the client API for TunnelService service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +type TunnelServiceClient interface { + Start(ctx context.Context, in *TunnelStartRequest, opts ...grpc.CallOption) (*TunnelResponse, error) + Stop(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*TunnelResponse, error) + Status(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*TunnelResponse, error) + Exit(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*TunnelResponse, error) +} + +type tunnelServiceClient struct { + cc grpc.ClientConnInterface +} + +func NewTunnelServiceClient(cc grpc.ClientConnInterface) TunnelServiceClient { + return &tunnelServiceClient{cc} +} + +func (c *tunnelServiceClient) Start(ctx context.Context, in *TunnelStartRequest, opts ...grpc.CallOption) (*TunnelResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(TunnelResponse) + err := c.cc.Invoke(ctx, TunnelService_Start_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *tunnelServiceClient) Stop(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*TunnelResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(TunnelResponse) + err := c.cc.Invoke(ctx, TunnelService_Stop_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *tunnelServiceClient) Status(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*TunnelResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(TunnelResponse) + err := c.cc.Invoke(ctx, TunnelService_Status_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *tunnelServiceClient) Exit(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*TunnelResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(TunnelResponse) + err := c.cc.Invoke(ctx, TunnelService_Exit_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +// TunnelServiceServer is the server API for TunnelService service. +// All implementations must embed UnimplementedTunnelServiceServer +// for forward compatibility. +type TunnelServiceServer interface { + Start(context.Context, *TunnelStartRequest) (*TunnelResponse, error) + Stop(context.Context, *Empty) (*TunnelResponse, error) + Status(context.Context, *Empty) (*TunnelResponse, error) + Exit(context.Context, *Empty) (*TunnelResponse, error) + mustEmbedUnimplementedTunnelServiceServer() +} + +// UnimplementedTunnelServiceServer must be embedded to have +// forward compatible implementations. +// +// NOTE: this should be embedded by value instead of pointer to avoid a nil +// pointer dereference when methods are called. +type UnimplementedTunnelServiceServer struct{} + +func (UnimplementedTunnelServiceServer) Start(context.Context, *TunnelStartRequest) (*TunnelResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method Start not implemented") +} +func (UnimplementedTunnelServiceServer) Stop(context.Context, *Empty) (*TunnelResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method Stop not implemented") +} +func (UnimplementedTunnelServiceServer) Status(context.Context, *Empty) (*TunnelResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method Status not implemented") +} +func (UnimplementedTunnelServiceServer) Exit(context.Context, *Empty) (*TunnelResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method Exit not implemented") +} +func (UnimplementedTunnelServiceServer) mustEmbedUnimplementedTunnelServiceServer() {} +func (UnimplementedTunnelServiceServer) testEmbeddedByValue() {} + +// UnsafeTunnelServiceServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to TunnelServiceServer will +// result in compilation errors. +type UnsafeTunnelServiceServer interface { + mustEmbedUnimplementedTunnelServiceServer() +} + +func RegisterTunnelServiceServer(s grpc.ServiceRegistrar, srv TunnelServiceServer) { + // If the following call pancis, it indicates UnimplementedTunnelServiceServer was + // embedded by pointer and is nil. This will cause panics if an + // unimplemented method is ever invoked, so we test this at initialization + // time to prevent it from happening at runtime later due to I/O. + if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { + t.testEmbeddedByValue() + } + s.RegisterService(&TunnelService_ServiceDesc, srv) +} + +func _TunnelService_Start_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(TunnelStartRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(TunnelServiceServer).Start(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: TunnelService_Start_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(TunnelServiceServer).Start(ctx, req.(*TunnelStartRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _TunnelService_Stop_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(Empty) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(TunnelServiceServer).Stop(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: TunnelService_Stop_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(TunnelServiceServer).Stop(ctx, req.(*Empty)) + } + return interceptor(ctx, in, info, handler) +} + +func _TunnelService_Status_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(Empty) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(TunnelServiceServer).Status(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: TunnelService_Status_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(TunnelServiceServer).Status(ctx, req.(*Empty)) + } + return interceptor(ctx, in, info, handler) +} + +func _TunnelService_Exit_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(Empty) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(TunnelServiceServer).Exit(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: TunnelService_Exit_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(TunnelServiceServer).Exit(ctx, req.(*Empty)) + } + return interceptor(ctx, in, info, handler) +} + +// TunnelService_ServiceDesc is the grpc.ServiceDesc for TunnelService service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var TunnelService_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "hiddifyrpc.TunnelService", + HandlerType: (*TunnelServiceServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "Start", + Handler: _TunnelService_Start_Handler, + }, + { + MethodName: "Stop", + Handler: _TunnelService_Stop_Handler, + }, + { + MethodName: "Status", + Handler: _TunnelService_Status_Handler, + }, + { + MethodName: "Exit", + Handler: _TunnelService_Exit_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "hiddify.proto", +} diff --git a/libcore/mobile/mobile.go b/libcore/mobile/mobile.go new file mode 100644 index 0000000..3eefeb1 --- /dev/null +++ b/libcore/mobile/mobile.go @@ -0,0 +1,64 @@ +package mobile + +import ( + "encoding/json" + "os" + "path/filepath" + + "github.com/hiddify/hiddify-core/config" + + "github.com/hiddify/hiddify-core/v2" + + _ "github.com/sagernet/gomobile" + "github.com/sagernet/sing-box/option" +) + +func Setup(baseDir string, workingDir string, tempDir string, debug bool) error { + return v2.Setup(baseDir, workingDir, tempDir, 0, debug) + // return v2.Start(17078) +} + +func Parse(path string, tempPath string, debug bool) error { + config, err := config.ParseConfig(tempPath, debug) + if err != nil { + return err + } + return os.WriteFile(path, config, 0o644) +} + +func BuildConfig(path string, HiddifyOptionsJson string) (string, error) { + os.Chdir(filepath.Dir(path)) + fileContent, err := os.ReadFile(path) + if err != nil { + return "", err + } + var options option.Options + err = options.UnmarshalJSON(fileContent) + if err != nil { + return "", err + } + HiddifyOptions := &config.HiddifyOptions{} + err = json.Unmarshal([]byte(HiddifyOptionsJson), HiddifyOptions) + if err != nil { + return "", nil + } + if HiddifyOptions.Warp.WireguardConfigStr != "" { + err := json.Unmarshal([]byte(HiddifyOptions.Warp.WireguardConfigStr), &HiddifyOptions.Warp.WireguardConfig) + if err != nil { + return "", err + } + } + + if HiddifyOptions.Warp2.WireguardConfigStr != "" { + err := json.Unmarshal([]byte(HiddifyOptions.Warp2.WireguardConfigStr), &HiddifyOptions.Warp2.WireguardConfig) + if err != nil { + return "", err + } + } + + return config.BuildConfigJson(*HiddifyOptions, options) +} + +func GenerateWarpConfig(licenseKey string, accountId string, accessToken string) (string, error) { + return config.GenerateWarpAccount(licenseKey, accountId, accessToken) +} diff --git a/libcore/node_modules/.bin/JSONStream b/libcore/node_modules/.bin/JSONStream new file mode 120000 index 0000000..3983a36 --- /dev/null +++ b/libcore/node_modules/.bin/JSONStream @@ -0,0 +1 @@ +../JSONStream/bin.js \ No newline at end of file diff --git a/libcore/node_modules/.bin/acorn b/libcore/node_modules/.bin/acorn new file mode 120000 index 0000000..cf76760 --- /dev/null +++ b/libcore/node_modules/.bin/acorn @@ -0,0 +1 @@ +../acorn/bin/acorn \ No newline at end of file diff --git a/libcore/node_modules/.bin/browser-pack b/libcore/node_modules/.bin/browser-pack new file mode 120000 index 0000000..1d047b9 --- /dev/null +++ b/libcore/node_modules/.bin/browser-pack @@ -0,0 +1 @@ +../browser-pack/bin/cmd.js \ No newline at end of file diff --git a/libcore/node_modules/.bin/browserify b/libcore/node_modules/.bin/browserify new file mode 120000 index 0000000..ab156b3 --- /dev/null +++ b/libcore/node_modules/.bin/browserify @@ -0,0 +1 @@ +../browserify/bin/cmd.js \ No newline at end of file diff --git a/libcore/node_modules/.bin/deps-sort b/libcore/node_modules/.bin/deps-sort new file mode 120000 index 0000000..b2dda9e --- /dev/null +++ b/libcore/node_modules/.bin/deps-sort @@ -0,0 +1 @@ +../deps-sort/bin/cmd.js \ No newline at end of file diff --git a/libcore/node_modules/.bin/detective b/libcore/node_modules/.bin/detective new file mode 120000 index 0000000..8c3093a --- /dev/null +++ b/libcore/node_modules/.bin/detective @@ -0,0 +1 @@ +../detective/bin/detective.js \ No newline at end of file diff --git a/libcore/node_modules/.bin/escodegen b/libcore/node_modules/.bin/escodegen new file mode 120000 index 0000000..01a7c32 --- /dev/null +++ b/libcore/node_modules/.bin/escodegen @@ -0,0 +1 @@ +../escodegen/bin/escodegen.js \ No newline at end of file diff --git a/libcore/node_modules/.bin/esgenerate b/libcore/node_modules/.bin/esgenerate new file mode 120000 index 0000000..7d0293e --- /dev/null +++ b/libcore/node_modules/.bin/esgenerate @@ -0,0 +1 @@ +../escodegen/bin/esgenerate.js \ No newline at end of file diff --git a/libcore/node_modules/.bin/esparse b/libcore/node_modules/.bin/esparse new file mode 120000 index 0000000..7423b18 --- /dev/null +++ b/libcore/node_modules/.bin/esparse @@ -0,0 +1 @@ +../esprima/bin/esparse.js \ No newline at end of file diff --git a/libcore/node_modules/.bin/esvalidate b/libcore/node_modules/.bin/esvalidate new file mode 120000 index 0000000..16069ef --- /dev/null +++ b/libcore/node_modules/.bin/esvalidate @@ -0,0 +1 @@ +../esprima/bin/esvalidate.js \ No newline at end of file diff --git a/libcore/node_modules/.bin/insert-module-globals b/libcore/node_modules/.bin/insert-module-globals new file mode 120000 index 0000000..68af3a9 --- /dev/null +++ b/libcore/node_modules/.bin/insert-module-globals @@ -0,0 +1 @@ +../insert-module-globals/bin/cmd.js \ No newline at end of file diff --git a/libcore/node_modules/.bin/jsdoc b/libcore/node_modules/.bin/jsdoc new file mode 120000 index 0000000..5c04777 --- /dev/null +++ b/libcore/node_modules/.bin/jsdoc @@ -0,0 +1 @@ +../jsdoc/jsdoc.js \ No newline at end of file diff --git a/libcore/node_modules/.bin/markdown-it b/libcore/node_modules/.bin/markdown-it new file mode 120000 index 0000000..8a64108 --- /dev/null +++ b/libcore/node_modules/.bin/markdown-it @@ -0,0 +1 @@ +../markdown-it/bin/markdown-it.mjs \ No newline at end of file diff --git a/libcore/node_modules/.bin/marked b/libcore/node_modules/.bin/marked new file mode 120000 index 0000000..6827ff3 --- /dev/null +++ b/libcore/node_modules/.bin/marked @@ -0,0 +1 @@ +../marked/bin/marked.js \ No newline at end of file diff --git a/libcore/node_modules/.bin/miller-rabin b/libcore/node_modules/.bin/miller-rabin new file mode 120000 index 0000000..c175fe9 --- /dev/null +++ b/libcore/node_modules/.bin/miller-rabin @@ -0,0 +1 @@ +../miller-rabin/bin/miller-rabin \ No newline at end of file diff --git a/libcore/node_modules/.bin/mkdirp b/libcore/node_modules/.bin/mkdirp new file mode 120000 index 0000000..017896c --- /dev/null +++ b/libcore/node_modules/.bin/mkdirp @@ -0,0 +1 @@ +../mkdirp/bin/cmd.js \ No newline at end of file diff --git a/libcore/node_modules/.bin/module-deps b/libcore/node_modules/.bin/module-deps new file mode 120000 index 0000000..66a1f24 --- /dev/null +++ b/libcore/node_modules/.bin/module-deps @@ -0,0 +1 @@ +../module-deps/bin/cmd.js \ No newline at end of file diff --git a/libcore/node_modules/.bin/parser b/libcore/node_modules/.bin/parser new file mode 120000 index 0000000..ce7bf97 --- /dev/null +++ b/libcore/node_modules/.bin/parser @@ -0,0 +1 @@ +../@babel/parser/bin/babel-parser.js \ No newline at end of file diff --git a/libcore/node_modules/.bin/pbjs b/libcore/node_modules/.bin/pbjs new file mode 120000 index 0000000..d7cc903 --- /dev/null +++ b/libcore/node_modules/.bin/pbjs @@ -0,0 +1 @@ +../protobufjs-cli/bin/pbjs \ No newline at end of file diff --git a/libcore/node_modules/.bin/pbts b/libcore/node_modules/.bin/pbts new file mode 120000 index 0000000..98ad9e3 --- /dev/null +++ b/libcore/node_modules/.bin/pbts @@ -0,0 +1 @@ +../protobufjs-cli/bin/pbts \ No newline at end of file diff --git a/libcore/node_modules/.bin/resolve b/libcore/node_modules/.bin/resolve new file mode 120000 index 0000000..b6afda6 --- /dev/null +++ b/libcore/node_modules/.bin/resolve @@ -0,0 +1 @@ +../resolve/bin/resolve \ No newline at end of file diff --git a/libcore/node_modules/.bin/semver b/libcore/node_modules/.bin/semver new file mode 120000 index 0000000..5aaadf4 --- /dev/null +++ b/libcore/node_modules/.bin/semver @@ -0,0 +1 @@ +../semver/bin/semver.js \ No newline at end of file diff --git a/libcore/node_modules/.bin/sha.js b/libcore/node_modules/.bin/sha.js new file mode 120000 index 0000000..3c76105 --- /dev/null +++ b/libcore/node_modules/.bin/sha.js @@ -0,0 +1 @@ +../sha.js/bin.js \ No newline at end of file diff --git a/libcore/node_modules/.bin/uglifyjs b/libcore/node_modules/.bin/uglifyjs new file mode 120000 index 0000000..fef3468 --- /dev/null +++ b/libcore/node_modules/.bin/uglifyjs @@ -0,0 +1 @@ +../uglify-js/bin/uglifyjs \ No newline at end of file diff --git a/libcore/node_modules/.bin/umd b/libcore/node_modules/.bin/umd new file mode 120000 index 0000000..69767ed --- /dev/null +++ b/libcore/node_modules/.bin/umd @@ -0,0 +1 @@ +../umd/bin/cli.js \ No newline at end of file diff --git a/libcore/node_modules/.bin/undeclared-identifiers b/libcore/node_modules/.bin/undeclared-identifiers new file mode 120000 index 0000000..c95efdb --- /dev/null +++ b/libcore/node_modules/.bin/undeclared-identifiers @@ -0,0 +1 @@ +../undeclared-identifiers/bin.js \ No newline at end of file diff --git a/libcore/node_modules/.package-lock.json b/libcore/node_modules/.package-lock.json new file mode 100644 index 0000000..2bebc96 --- /dev/null +++ b/libcore/node_modules/.package-lock.json @@ -0,0 +1,2648 @@ +{ + "name": "libcore", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/@babel/helper-string-parser": { + "version": "7.24.8", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.24.8.tgz", + "integrity": "sha512-pO9KhhRcuUyGnJWwyEgnRJTSIZHiT+vMD0kPeD+so0l7mxkMT19g3pjY9GTnHySck/hDzq+dtW/4VgnMkippsQ==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.24.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.24.7.tgz", + "integrity": "sha512-rR+PBcQ1SMQDDyF6X0wxtG8QyLCgUB0eRAGguqRLfkCA87l7yAP7ehq8SNj96OOGTO8OBV70KhuFYcIkHXOg0w==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.25.6", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.25.6.tgz", + "integrity": "sha512-trGdfBdbD0l1ZPmcJ83eNxB9rbEax4ALFTF7fN386TMYbeCQbyme5cOEXQhbGXKebwGaB/J52w1mrklMcbgy6Q==", + "license": "MIT", + "dependencies": { + "@babel/types": "^7.25.6" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/types": { + "version": "7.25.6", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.25.6.tgz", + "integrity": "sha512-/l42B1qxpG6RdfYf343Uw1vmDjeNhneUXtzhojE7pDgfpEypmRhI6j1kr17XCVv4Cgl9HdAiQY2x0GwKm7rWCw==", + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.24.8", + "@babel/helper-validator-identifier": "^7.24.7", + "to-fast-properties": "^2.0.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@jsdoc/salty": { + "version": "0.2.8", + "resolved": "https://registry.npmjs.org/@jsdoc/salty/-/salty-0.2.8.tgz", + "integrity": "sha512-5e+SFVavj1ORKlKaKr2BmTOekmXbelU7dC0cDkQLqag7xfuTPuGMUFx7KWJuv4bYZrTsoL2Z18VVCOKYxzoHcg==", + "license": "Apache-2.0", + "dependencies": { + "lodash": "^4.17.21" + }, + "engines": { + "node": ">=v12.0.0" + } + }, + "node_modules/@protobufjs/aspromise": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz", + "integrity": "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==", + "license": "BSD-3-Clause", + "peer": true + }, + "node_modules/@protobufjs/base64": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz", + "integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==", + "license": "BSD-3-Clause", + "peer": true + }, + "node_modules/@protobufjs/codegen": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.4.tgz", + "integrity": "sha512-YyFaikqM5sH0ziFZCN3xDC7zeGaB/d0IUb9CATugHWbd1FRFwWwt4ld4OYMPWu5a3Xe01mGAULCdqhMlPl29Jg==", + "license": "BSD-3-Clause", + "peer": true + }, + "node_modules/@protobufjs/eventemitter": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.0.tgz", + "integrity": "sha512-j9ednRT81vYJ9OfVuXG6ERSTdEL1xVsNgqpkxMsbIabzSo3goCjDIveeGv5d03om39ML71RdmrGNjG5SReBP/Q==", + "license": "BSD-3-Clause", + "peer": true + }, + "node_modules/@protobufjs/fetch": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.0.tgz", + "integrity": "sha512-lljVXpqXebpsijW71PZaCYeIcE5on1w5DlQy5WH6GLbFryLUrBD4932W/E2BSpfRJWseIL4v/KPgBFxDOIdKpQ==", + "license": "BSD-3-Clause", + "peer": true, + "dependencies": { + "@protobufjs/aspromise": "^1.1.1", + "@protobufjs/inquire": "^1.1.0" + } + }, + "node_modules/@protobufjs/float": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz", + "integrity": "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==", + "license": "BSD-3-Clause", + "peer": true + }, + "node_modules/@protobufjs/inquire": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/inquire/-/inquire-1.1.0.tgz", + "integrity": "sha512-kdSefcPdruJiFMVSbn801t4vFK7KB/5gd2fYvrxhuJYg8ILrmn9SKSX2tZdV6V+ksulWqS7aXjBcRXl3wHoD9Q==", + "license": "BSD-3-Clause", + "peer": true + }, + "node_modules/@protobufjs/path": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz", + "integrity": "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==", + "license": "BSD-3-Clause", + "peer": true + }, + "node_modules/@protobufjs/pool": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz", + "integrity": "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==", + "license": "BSD-3-Clause", + "peer": true + }, + "node_modules/@protobufjs/utf8": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.0.tgz", + "integrity": "sha512-Vvn3zZrhQZkkBE8LSuW3em98c0FwgO4nxzv6OdSxPKJIEKY2bGbHn+mhGIPerzI4twdxaP8/0+06HBpwf345Lw==", + "license": "BSD-3-Clause", + "peer": true + }, + "node_modules/@types/linkify-it": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@types/linkify-it/-/linkify-it-5.0.0.tgz", + "integrity": "sha512-sVDA58zAw4eWAffKOaQH5/5j3XeayukzDk+ewSsnv3p4yJEZHCCzMDiZM8e0OUrRvmpGZ85jf4yDHkHsgBNr9Q==", + "license": "MIT" + }, + "node_modules/@types/markdown-it": { + "version": "14.1.2", + "resolved": "https://registry.npmjs.org/@types/markdown-it/-/markdown-it-14.1.2.tgz", + "integrity": "sha512-promo4eFwuiW+TfGxhi+0x3czqTYJkG8qB17ZUJiVF10Xm7NLVRSLUsfRTU/6h1e24VvRnXCx+hG7li58lkzog==", + "license": "MIT", + "dependencies": { + "@types/linkify-it": "^5", + "@types/mdurl": "^2" + } + }, + "node_modules/@types/mdurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@types/mdurl/-/mdurl-2.0.0.tgz", + "integrity": "sha512-RGdgjQUZba5p6QEFAVx2OGb8rQDL/cPRG7GiedRzMcJ1tYnUANBncjbSB1NRGwbvjcPeikRABz2nshyPk1bhWg==", + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "22.5.4", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.5.4.tgz", + "integrity": "sha512-FDuKUJQm/ju9fT/SeX/6+gBzoPzlVCzfzmGkwKvRHQVxi4BntVbyIwf6a4Xn62mrvndLiml6z/UBXIdEVjQLXg==", + "license": "MIT", + "peer": true, + "dependencies": { + "undici-types": "~6.19.2" + } + }, + "node_modules/acorn": { + "version": "8.12.1", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.12.1.tgz", + "integrity": "sha512-tcpGyI9zbizT9JbV6oYE477V6mTlXvvi0T0G3SNIYE2apm/G5huBa1+K89VGeovbg+jycCrfhl3ADxErOuO6Jg==", + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-jsx": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", + "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", + "license": "MIT", + "peerDependencies": { + "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" + } + }, + "node_modules/acorn-node": { + "version": "1.8.2", + "resolved": "https://registry.npmjs.org/acorn-node/-/acorn-node-1.8.2.tgz", + "integrity": "sha512-8mt+fslDufLYntIoPAaIMUe/lrbrehIiwmR3t2k9LljIzoigEPF27eLk2hy8zSGzmR/ogr7zbRKINMo1u0yh5A==", + "license": "Apache-2.0", + "dependencies": { + "acorn": "^7.0.0", + "acorn-walk": "^7.0.0", + "xtend": "^4.0.2" + } + }, + "node_modules/acorn-node/node_modules/acorn": { + "version": "7.4.1", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-7.4.1.tgz", + "integrity": "sha512-nQyp0o1/mNdbTO1PO6kHkwSrmgZ0MT/jCCpNiwbUjGoRN4dlBhqJtoQuCnEOKzgTVwg0ZWiCoQy6SxMebQVh8A==", + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-walk": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-7.2.0.tgz", + "integrity": "sha512-OPdCF6GsMIP+Az+aWfAAOEt2/+iVDKE7oy6lJ098aoe59oAmK76qV6Gw60SbZ8jHuG2wH058GF4pLFbYamYrVA==", + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "license": "Python-2.0" + }, + "node_modules/asn1.js": { + "version": "4.10.1", + "resolved": "https://registry.npmjs.org/asn1.js/-/asn1.js-4.10.1.tgz", + "integrity": "sha512-p32cOF5q0Zqs9uBiONKYLm6BClCoBCM5O9JfeUSlnQLBTxYdTK+pW+nXflm8UkKd2UYlEbYz5qEi0JuZR9ckSw==", + "license": "MIT", + "dependencies": { + "bn.js": "^4.0.0", + "inherits": "^2.0.1", + "minimalistic-assert": "^1.0.0" + } + }, + "node_modules/asn1.js/node_modules/bn.js": { + "version": "4.12.0", + "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.0.tgz", + "integrity": "sha512-c98Bf3tPniI+scsdk237ku1Dc3ujXQTSgyiPUDEOe7tRkhrqridvh8klBv0HCEso1OLOYcHuCv/cS6DNxKH+ZA==", + "license": "MIT" + }, + "node_modules/assert": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/assert/-/assert-1.5.1.tgz", + "integrity": "sha512-zzw1uCAgLbsKwBfFc8CX78DDg+xZeBksSO3vwVIDDN5i94eOrPsSSyiVhmsSABFDM/OcpE2aagCat9dnWQLG1A==", + "license": "MIT", + "dependencies": { + "object.assign": "^4.1.4", + "util": "^0.10.4" + } + }, + "node_modules/assert/node_modules/inherits": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", + "integrity": "sha512-x00IRNXNy63jwGkJmzPigoySHbaqpNuzKbBOmzK+g2OdZpQ9w+sxCN+VSB3ja7IAge2OP2qpfxTjeNcyjmW1uw==", + "license": "ISC" + }, + "node_modules/assert/node_modules/util": { + "version": "0.10.4", + "resolved": "https://registry.npmjs.org/util/-/util-0.10.4.tgz", + "integrity": "sha512-0Pm9hTQ3se5ll1XihRic3FDIku70C+iHUdT/W926rSgHV5QgXsYbKZN8MSC3tJtSkhuROzvsQjAaFENRXr+19A==", + "license": "MIT", + "dependencies": { + "inherits": "2.0.3" + } + }, + "node_modules/available-typed-arrays": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.7.tgz", + "integrity": "sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==", + "license": "MIT", + "dependencies": { + "possible-typed-array-names": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "license": "MIT" + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "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/bluebird": { + "version": "3.7.2", + "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.7.2.tgz", + "integrity": "sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==", + "license": "MIT" + }, + "node_modules/bn.js": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-5.2.1.tgz", + "integrity": "sha512-eXRvHzWyYPBuB4NBy0cmYQjGitUrtqwbvlzP3G6VFnNRbsZQIxQ10PbKKHt8gZ/HW/D/747aDl+QkDqg3KQLMQ==", + "license": "MIT" + }, + "node_modules/brace-expansion": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", + "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/brorand": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/brorand/-/brorand-1.1.0.tgz", + "integrity": "sha512-cKV8tMCEpQs4hK/ik71d6LrPOnpkpGBR0wzxqr68g2m/LB2GxVYQroAjMJZRVM1Y4BCjCKc3vAamxSzOY2RP+w==", + "license": "MIT" + }, + "node_modules/browser-pack": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/browser-pack/-/browser-pack-6.1.0.tgz", + "integrity": "sha512-erYug8XoqzU3IfcU8fUgyHqyOXqIE4tUTTQ+7mqUjQlvnXkOO6OlT9c/ZoJVHYoAaqGxr09CN53G7XIsO4KtWA==", + "license": "MIT", + "dependencies": { + "combine-source-map": "~0.8.0", + "defined": "^1.0.0", + "JSONStream": "^1.0.3", + "safe-buffer": "^5.1.1", + "through2": "^2.0.0", + "umd": "^3.0.0" + }, + "bin": { + "browser-pack": "bin/cmd.js" + } + }, + "node_modules/browser-resolve": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/browser-resolve/-/browser-resolve-2.0.0.tgz", + "integrity": "sha512-7sWsQlYL2rGLy2IWm8WL8DCTJvYLc/qlOnsakDac87SOoCd16WLsaAMdCiAqsTNHIe+SXfaqyxyo6THoWqs8WQ==", + "license": "MIT", + "dependencies": { + "resolve": "^1.17.0" + } + }, + "node_modules/browserify": { + "version": "17.0.0", + "resolved": "https://registry.npmjs.org/browserify/-/browserify-17.0.0.tgz", + "integrity": "sha512-SaHqzhku9v/j6XsQMRxPyBrSP3gnwmE27gLJYZgMT2GeK3J0+0toN+MnuNYDfHwVGQfLiMZ7KSNSIXHemy905w==", + "license": "MIT", + "dependencies": { + "assert": "^1.4.0", + "browser-pack": "^6.0.1", + "browser-resolve": "^2.0.0", + "browserify-zlib": "~0.2.0", + "buffer": "~5.2.1", + "cached-path-relative": "^1.0.0", + "concat-stream": "^1.6.0", + "console-browserify": "^1.1.0", + "constants-browserify": "~1.0.0", + "crypto-browserify": "^3.0.0", + "defined": "^1.0.0", + "deps-sort": "^2.0.1", + "domain-browser": "^1.2.0", + "duplexer2": "~0.1.2", + "events": "^3.0.0", + "glob": "^7.1.0", + "has": "^1.0.0", + "htmlescape": "^1.1.0", + "https-browserify": "^1.0.0", + "inherits": "~2.0.1", + "insert-module-globals": "^7.2.1", + "JSONStream": "^1.0.3", + "labeled-stream-splicer": "^2.0.0", + "mkdirp-classic": "^0.5.2", + "module-deps": "^6.2.3", + "os-browserify": "~0.3.0", + "parents": "^1.0.1", + "path-browserify": "^1.0.0", + "process": "~0.11.0", + "punycode": "^1.3.2", + "querystring-es3": "~0.2.0", + "read-only-stream": "^2.0.0", + "readable-stream": "^2.0.2", + "resolve": "^1.1.4", + "shasum-object": "^1.0.0", + "shell-quote": "^1.6.1", + "stream-browserify": "^3.0.0", + "stream-http": "^3.0.0", + "string_decoder": "^1.1.1", + "subarg": "^1.0.0", + "syntax-error": "^1.1.1", + "through2": "^2.0.0", + "timers-browserify": "^1.0.1", + "tty-browserify": "0.0.1", + "url": "~0.11.0", + "util": "~0.12.0", + "vm-browserify": "^1.0.0", + "xtend": "^4.0.0" + }, + "bin": { + "browserify": "bin/cmd.js" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/browserify-aes": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/browserify-aes/-/browserify-aes-1.2.0.tgz", + "integrity": "sha512-+7CHXqGuspUn/Sl5aO7Ea0xWGAtETPXNSAjHo48JfLdPWcMng33Xe4znFvQweqc/uzk5zSOI3H52CYnjCfb5hA==", + "license": "MIT", + "dependencies": { + "buffer-xor": "^1.0.3", + "cipher-base": "^1.0.0", + "create-hash": "^1.1.0", + "evp_bytestokey": "^1.0.3", + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/browserify-cipher": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/browserify-cipher/-/browserify-cipher-1.0.1.tgz", + "integrity": "sha512-sPhkz0ARKbf4rRQt2hTpAHqn47X3llLkUGn+xEJzLjwY8LRs2p0v7ljvI5EyoRO/mexrNunNECisZs+gw2zz1w==", + "license": "MIT", + "dependencies": { + "browserify-aes": "^1.0.4", + "browserify-des": "^1.0.0", + "evp_bytestokey": "^1.0.0" + } + }, + "node_modules/browserify-des": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/browserify-des/-/browserify-des-1.0.2.tgz", + "integrity": "sha512-BioO1xf3hFwz4kc6iBhI3ieDFompMhrMlnDFC4/0/vd5MokpuAc3R+LYbwTA9A5Yc9pq9UYPqffKpW2ObuwX5A==", + "license": "MIT", + "dependencies": { + "cipher-base": "^1.0.1", + "des.js": "^1.0.0", + "inherits": "^2.0.1", + "safe-buffer": "^5.1.2" + } + }, + "node_modules/browserify-rsa": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/browserify-rsa/-/browserify-rsa-4.1.0.tgz", + "integrity": "sha512-AdEER0Hkspgno2aR97SAf6vi0y0k8NuOpGnVH3O99rcA5Q6sh8QxcngtHuJ6uXwnfAXNM4Gn1Gb7/MV1+Ymbog==", + "license": "MIT", + "dependencies": { + "bn.js": "^5.0.0", + "randombytes": "^2.0.1" + } + }, + "node_modules/browserify-sign": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/browserify-sign/-/browserify-sign-4.2.3.tgz", + "integrity": "sha512-JWCZW6SKhfhjJxO8Tyiiy+XYB7cqd2S5/+WeYHsKdNKFlCBhKbblba1A/HN/90YwtxKc8tCErjffZl++UNmGiw==", + "license": "ISC", + "dependencies": { + "bn.js": "^5.2.1", + "browserify-rsa": "^4.1.0", + "create-hash": "^1.2.0", + "create-hmac": "^1.1.7", + "elliptic": "^6.5.5", + "hash-base": "~3.0", + "inherits": "^2.0.4", + "parse-asn1": "^5.1.7", + "readable-stream": "^2.3.8", + "safe-buffer": "^5.2.1" + }, + "engines": { + "node": ">= 0.12" + } + }, + "node_modules/browserify-zlib": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/browserify-zlib/-/browserify-zlib-0.2.0.tgz", + "integrity": "sha512-Z942RysHXmJrhqk88FmKBVq/v5tqmSkDz7p54G/MGyjMnCFFnC79XWNbg+Vta8W6Wb2qtSZTSxIGkJrRpCFEiA==", + "license": "MIT", + "dependencies": { + "pako": "~1.0.5" + } + }, + "node_modules/browserify/node_modules/brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/browserify/node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "deprecated": "Glob versions prior to v9 are no longer supported", + "license": "ISC", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/browserify/node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.2.1.tgz", + "integrity": "sha512-c+Ko0loDaFfuPWiL02ls9Xd3GO3cPVmUobQ6t3rXNUk304u6hGq+8N/kFi+QEIKhzK3uwolVhLzszmfLmMLnqg==", + "license": "MIT", + "dependencies": { + "base64-js": "^1.0.2", + "ieee754": "^1.1.4" + } + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "license": "MIT" + }, + "node_modules/buffer-xor": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/buffer-xor/-/buffer-xor-1.0.3.tgz", + "integrity": "sha512-571s0T7nZWK6vB67HI5dyUF7wXiNcfaPPPTl6zYCNApANjIvYJTg7hlud/+cJpdAhS7dVzqMLmfhfHR3rAcOjQ==", + "license": "MIT" + }, + "node_modules/builtin-status-codes": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/builtin-status-codes/-/builtin-status-codes-3.0.0.tgz", + "integrity": "sha512-HpGFw18DgFWlncDfjTa2rcQ4W88O1mC8e8yZ2AvQY5KDaktSTwo+KRf6nHK6FRI5FyRyb/5T6+TSxfP7QyGsmQ==", + "license": "MIT" + }, + "node_modules/cached-path-relative": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/cached-path-relative/-/cached-path-relative-1.1.0.tgz", + "integrity": "sha512-WF0LihfemtesFcJgO7xfOoOcnWzY/QHR4qeDqV44jPU3HTI54+LnfXK3SA27AVVGCdZFgjjFFaqUA9Jx7dMJZA==", + "license": "MIT" + }, + "node_modules/call-bind": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.7.tgz", + "integrity": "sha512-GHTSNSYICQ7scH7sZ+M2rFopRoLh8t2bLSW6BbgrtLsahOIB5iyAVJf9GjWK3cYTDaMj4XdBpM1cA6pIS0Kv2w==", + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "set-function-length": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/catharsis": { + "version": "0.9.0", + "resolved": "https://registry.npmjs.org/catharsis/-/catharsis-0.9.0.tgz", + "integrity": "sha512-prMTQVpcns/tzFgFVkVp6ak6RykZyWb3gu8ckUpd6YkTlacOd3DXGJjIpD4Q6zJirizvaiAjSSHlOsA+6sNh2A==", + "license": "MIT", + "dependencies": { + "lodash": "^4.17.15" + }, + "engines": { + "node": ">= 10" + } + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/cipher-base": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/cipher-base/-/cipher-base-1.0.4.tgz", + "integrity": "sha512-Kkht5ye6ZGmwv40uUDZztayT2ThLQGfnj/T71N/XzeZeo3nf8foyW7zGTsPYkEya3m5f3cAypH+qe7YOrM1U2Q==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "license": "MIT" + }, + "node_modules/combine-source-map": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/combine-source-map/-/combine-source-map-0.8.0.tgz", + "integrity": "sha512-UlxQ9Vw0b/Bt/KYwCFqdEwsQ1eL8d1gibiFb7lxQJFdvTgc2hIZi6ugsg+kyhzhPV+QEpUiEIwInIAIrgoEkrg==", + "license": "MIT", + "dependencies": { + "convert-source-map": "~1.1.0", + "inline-source-map": "~0.6.0", + "lodash.memoize": "~3.0.3", + "source-map": "~0.5.3" + } + }, + "node_modules/combine-source-map/node_modules/source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha512-LbrmJOMUSdEVxIKvdcJzQC+nQhe8FUZQTXQy6+I75skNgn3OoQ0DZA8YnFa7gp8tqtL3KPf1kmo0R5DoApeSGQ==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "license": "MIT" + }, + "node_modules/concat-stream": { + "version": "1.6.2", + "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.2.tgz", + "integrity": "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==", + "engines": [ + "node >= 0.8" + ], + "license": "MIT", + "dependencies": { + "buffer-from": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^2.2.2", + "typedarray": "^0.0.6" + } + }, + "node_modules/console-browserify": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/console-browserify/-/console-browserify-1.2.0.tgz", + "integrity": "sha512-ZMkYO/LkF17QvCPqM0gxw8yUzigAOZOSWSHg91FH6orS7vcEj5dVZTidN2fQ14yBSdg97RqhSNwLUXInd52OTA==" + }, + "node_modules/constants-browserify": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/constants-browserify/-/constants-browserify-1.0.0.tgz", + "integrity": "sha512-xFxOwqIzR/e1k1gLiWEophSCMqXcwVHIH7akf7b/vxcUeGunlj3hvZaaqxwHsTgn+IndtkQJgSztIDWeumWJDQ==", + "license": "MIT" + }, + "node_modules/convert-source-map": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.1.3.tgz", + "integrity": "sha512-Y8L5rp6jo+g9VEPgvqNfEopjTR4OTYct8lXlS8iVQdmnjDvbdbzYe9rjtFCB9egC86JoNCU61WRY+ScjkZpnIg==", + "license": "MIT" + }, + "node_modules/core-util-is": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", + "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==", + "license": "MIT" + }, + "node_modules/create-ecdh": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/create-ecdh/-/create-ecdh-4.0.4.tgz", + "integrity": "sha512-mf+TCx8wWc9VpuxfP2ht0iSISLZnt0JgWlrOKZiNqyUZWnjIaCIVNQArMHnCZKfEYRg6IM7A+NeJoN8gf/Ws0A==", + "license": "MIT", + "dependencies": { + "bn.js": "^4.1.0", + "elliptic": "^6.5.3" + } + }, + "node_modules/create-ecdh/node_modules/bn.js": { + "version": "4.12.0", + "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.0.tgz", + "integrity": "sha512-c98Bf3tPniI+scsdk237ku1Dc3ujXQTSgyiPUDEOe7tRkhrqridvh8klBv0HCEso1OLOYcHuCv/cS6DNxKH+ZA==", + "license": "MIT" + }, + "node_modules/create-hash": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/create-hash/-/create-hash-1.2.0.tgz", + "integrity": "sha512-z00bCGNHDG8mHAkP7CtT1qVu+bFQUPjYq/4Iv3C3kWjTFV10zIjfSoeqXo9Asws8gwSHDGj/hl2u4OGIjapeCg==", + "license": "MIT", + "dependencies": { + "cipher-base": "^1.0.1", + "inherits": "^2.0.1", + "md5.js": "^1.3.4", + "ripemd160": "^2.0.1", + "sha.js": "^2.4.0" + } + }, + "node_modules/create-hmac": { + "version": "1.1.7", + "resolved": "https://registry.npmjs.org/create-hmac/-/create-hmac-1.1.7.tgz", + "integrity": "sha512-MJG9liiZ+ogc4TzUwuvbER1JRdgvUFSB5+VR/g5h82fGaIRWMWddtKBHi7/sVhfjQZ6SehlyhvQYrcYkaUIpLg==", + "license": "MIT", + "dependencies": { + "cipher-base": "^1.0.3", + "create-hash": "^1.1.0", + "inherits": "^2.0.1", + "ripemd160": "^2.0.0", + "safe-buffer": "^5.0.1", + "sha.js": "^2.4.8" + } + }, + "node_modules/crypto-browserify": { + "version": "3.12.0", + "resolved": "https://registry.npmjs.org/crypto-browserify/-/crypto-browserify-3.12.0.tgz", + "integrity": "sha512-fz4spIh+znjO2VjL+IdhEpRJ3YN6sMzITSBijk6FK2UvTqruSQW+/cCZTSNsMiZNvUeq0CqurF+dAbyiGOY6Wg==", + "license": "MIT", + "dependencies": { + "browserify-cipher": "^1.0.0", + "browserify-sign": "^4.0.0", + "create-ecdh": "^4.0.0", + "create-hash": "^1.1.0", + "create-hmac": "^1.1.0", + "diffie-hellman": "^5.0.0", + "inherits": "^2.0.1", + "pbkdf2": "^3.0.3", + "public-encrypt": "^4.0.0", + "randombytes": "^2.0.0", + "randomfill": "^1.0.3" + }, + "engines": { + "node": "*" + } + }, + "node_modules/dash-ast": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/dash-ast/-/dash-ast-1.0.0.tgz", + "integrity": "sha512-Vy4dx7gquTeMcQR/hDkYLGUnwVil6vk4FOOct+djUnHOUWt+zJPJAaRIXaAFkPXtJjvlY7o3rfRu0/3hpnwoUA==", + "license": "Apache-2.0" + }, + "node_modules/deep-is": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", + "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", + "license": "MIT" + }, + "node_modules/define-data-property": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", + "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/define-properties": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz", + "integrity": "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==", + "license": "MIT", + "dependencies": { + "define-data-property": "^1.0.1", + "has-property-descriptors": "^1.0.0", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/defined": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/defined/-/defined-1.0.1.tgz", + "integrity": "sha512-hsBd2qSVCRE+5PmNdHt1uzyrFu5d3RwmFDKzyNZMFq/EwDNJF7Ee5+D5oEKF0hU6LhtoUF1macFvOe4AskQC1Q==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/deps-sort": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/deps-sort/-/deps-sort-2.0.1.tgz", + "integrity": "sha512-1orqXQr5po+3KI6kQb9A4jnXT1PBwggGl2d7Sq2xsnOeI9GPcE/tGcF9UiSZtZBM7MukY4cAh7MemS6tZYipfw==", + "license": "MIT", + "dependencies": { + "JSONStream": "^1.0.3", + "shasum-object": "^1.0.0", + "subarg": "^1.0.0", + "through2": "^2.0.0" + }, + "bin": { + "deps-sort": "bin/cmd.js" + } + }, + "node_modules/des.js": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/des.js/-/des.js-1.1.0.tgz", + "integrity": "sha512-r17GxjhUCjSRy8aiJpr8/UadFIzMzJGexI3Nmz4ADi9LYSFx4gTBp80+NaX/YsXWWLhpZ7v/v/ubEc/bCNfKwg==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.1", + "minimalistic-assert": "^1.0.0" + } + }, + "node_modules/detective": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/detective/-/detective-5.2.1.tgz", + "integrity": "sha512-v9XE1zRnz1wRtgurGu0Bs8uHKFSTdteYZNbIPFVhUZ39L/S79ppMpdmVOZAnoz1jfEFodc48n6MX483Xo3t1yw==", + "license": "MIT", + "dependencies": { + "acorn-node": "^1.8.2", + "defined": "^1.0.0", + "minimist": "^1.2.6" + }, + "bin": { + "detective": "bin/detective.js" + }, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/diffie-hellman": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/diffie-hellman/-/diffie-hellman-5.0.3.tgz", + "integrity": "sha512-kqag/Nl+f3GwyK25fhUMYj81BUOrZ9IuJsjIcDE5icNM9FJHAVm3VcUDxdLPoQtTuUylWm6ZIknYJwwaPxsUzg==", + "license": "MIT", + "dependencies": { + "bn.js": "^4.1.0", + "miller-rabin": "^4.0.0", + "randombytes": "^2.0.0" + } + }, + "node_modules/diffie-hellman/node_modules/bn.js": { + "version": "4.12.0", + "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.0.tgz", + "integrity": "sha512-c98Bf3tPniI+scsdk237ku1Dc3ujXQTSgyiPUDEOe7tRkhrqridvh8klBv0HCEso1OLOYcHuCv/cS6DNxKH+ZA==", + "license": "MIT" + }, + "node_modules/domain-browser": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/domain-browser/-/domain-browser-1.2.0.tgz", + "integrity": "sha512-jnjyiM6eRyZl2H+W8Q/zLMA481hzi0eszAaBUzIVnmYVDBbnLxVNnfu1HgEBvCbL+71FrxMl3E6lpKH7Ge3OXA==", + "license": "MIT", + "engines": { + "node": ">=0.4", + "npm": ">=1.2" + } + }, + "node_modules/duplexer2": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/duplexer2/-/duplexer2-0.1.4.tgz", + "integrity": "sha512-asLFVfWWtJ90ZyOUHMqk7/S2w2guQKxUI2itj3d92ADHhxUSbCMGi1f1cBcJ7xM1To+pE/Khbwo1yuNbMEPKeA==", + "license": "BSD-3-Clause", + "dependencies": { + "readable-stream": "^2.0.2" + } + }, + "node_modules/elliptic": { + "version": "6.5.7", + "resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.5.7.tgz", + "integrity": "sha512-ESVCtTwiA+XhY3wyh24QqRGBoP3rEdDUl3EDUUo9tft074fi19IrdpH7hLCMMP3CIj7jb3W96rn8lt/BqIlt5Q==", + "license": "MIT", + "dependencies": { + "bn.js": "^4.11.9", + "brorand": "^1.1.0", + "hash.js": "^1.0.0", + "hmac-drbg": "^1.0.1", + "inherits": "^2.0.4", + "minimalistic-assert": "^1.0.1", + "minimalistic-crypto-utils": "^1.0.1" + } + }, + "node_modules/elliptic/node_modules/bn.js": { + "version": "4.12.0", + "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.0.tgz", + "integrity": "sha512-c98Bf3tPniI+scsdk237ku1Dc3ujXQTSgyiPUDEOe7tRkhrqridvh8klBv0HCEso1OLOYcHuCv/cS6DNxKH+ZA==", + "license": "MIT" + }, + "node_modules/entities": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", + "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/es-define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.0.tgz", + "integrity": "sha512-jxayLKShrEqqzJ0eumQbVhTYQM27CfT1T35+gCgDFoL82JLsXqTJ76zv6A0YLOgEnLUMvLzsDsGIrl8NFpT2gQ==", + "license": "MIT", + "dependencies": { + "get-intrinsic": "^1.2.4" + }, + "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/escape-string-regexp": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", + "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/escodegen": { + "version": "1.14.3", + "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-1.14.3.tgz", + "integrity": "sha512-qFcX0XJkdg+PB3xjZZG/wKSuT1PnQWx57+TVSjIMmILd2yC/6ByYElPwJnslDsuWuSAp4AwJGumarAAmJch5Kw==", + "license": "BSD-2-Clause", + "dependencies": { + "esprima": "^4.0.1", + "estraverse": "^4.2.0", + "esutils": "^2.0.2", + "optionator": "^0.8.1" + }, + "bin": { + "escodegen": "bin/escodegen.js", + "esgenerate": "bin/esgenerate.js" + }, + "engines": { + "node": ">=4.0" + }, + "optionalDependencies": { + "source-map": "~0.6.1" + } + }, + "node_modules/escodegen/node_modules/estraverse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz", + "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/eslint-visitor-keys": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", + "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", + "license": "Apache-2.0", + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/espree": { + "version": "9.6.1", + "resolved": "https://registry.npmjs.org/espree/-/espree-9.6.1.tgz", + "integrity": "sha512-oruZaFkjorTpF32kDSI5/75ViwGeZginGGy2NoOSg3Q9bnwlnmDm4HLnkl0RE3n+njDXR037aY1+x58Z/zFdwQ==", + "license": "BSD-2-Clause", + "dependencies": { + "acorn": "^8.9.0", + "acorn-jsx": "^5.3.2", + "eslint-visitor-keys": "^3.4.1" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/esprima": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", + "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", + "license": "BSD-2-Clause", + "bin": { + "esparse": "bin/esparse.js", + "esvalidate": "bin/esvalidate.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/esutils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/events": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz", + "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==", + "license": "MIT", + "engines": { + "node": ">=0.8.x" + } + }, + "node_modules/evp_bytestokey": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/evp_bytestokey/-/evp_bytestokey-1.0.3.tgz", + "integrity": "sha512-/f2Go4TognH/KvCISP7OUsHn85hT9nUkxxA9BEWxFn+Oj9o8ZNLm/40hdlgSLyuOimsrTKLUMEorQexp/aPQeA==", + "license": "MIT", + "dependencies": { + "md5.js": "^1.3.4", + "safe-buffer": "^5.1.1" + } + }, + "node_modules/fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", + "license": "MIT" + }, + "node_modules/fast-safe-stringify": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.1.1.tgz", + "integrity": "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==", + "license": "MIT" + }, + "node_modules/for-each": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.3.tgz", + "integrity": "sha512-jqYfLp7mo9vIyQf8ykW2v7A+2N4QjeCeI5+Dz9XraiO1ign81wjiH7Fb9vSOWvQfNtmSa4H2RoQTrrXivdUZmw==", + "license": "MIT", + "dependencies": { + "is-callable": "^1.1.3" + } + }, + "node_modules/fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", + "license": "ISC" + }, + "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-assigned-identifiers": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/get-assigned-identifiers/-/get-assigned-identifiers-1.2.0.tgz", + "integrity": "sha512-mBBwmeGTrxEMO4pMaaf/uUEFHnYtwr8FTe8Y/mer4rcV/bye0qGm6pw1bGZFGStxC5O76c5ZAVBGnqHmOaJpdQ==", + "license": "Apache-2.0" + }, + "node_modules/get-intrinsic": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.4.tgz", + "integrity": "sha512-5uYhsJH8VJBTv7oslg4BznJYhDoRI6waYCxMmCdnTrcCrHA/fCFKoTFz2JKKE0HdDFUF7/oQuhzumXJK7paBRQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3", + "hasown": "^2.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/glob": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/glob/-/glob-8.1.0.tgz", + "integrity": "sha512-r8hpEjiQEYlF2QU0df3dS+nxxSIreXQS1qRhMJM0Q5NDdR386C7jb7Hwwod8Fgiuex+k0GFjgft18yvxm5XoCQ==", + "deprecated": "Glob versions prior to v9 are no longer supported", + "license": "ISC", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^5.0.1", + "once": "^1.3.0" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/google-protobuf": { + "version": "3.21.4", + "resolved": "https://registry.npmjs.org/google-protobuf/-/google-protobuf-3.21.4.tgz", + "integrity": "sha512-MnG7N936zcKTco4Jd2PX2U96Kf9PxygAPKBug+74LHzmHXmceN16MmRcdgZv+DGef/S9YvQAfRsNCn4cjf9yyQ==", + "license": "(BSD-3-Clause AND Apache-2.0)" + }, + "node_modules/gopd": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.0.1.tgz", + "integrity": "sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==", + "license": "MIT", + "dependencies": { + "get-intrinsic": "^1.1.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", + "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", + "license": "ISC" + }, + "node_modules/grpc-web": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/grpc-web/-/grpc-web-1.5.0.tgz", + "integrity": "sha512-y1tS3BBIoiVSzKTDF3Hm7E8hV2n7YY7pO0Uo7depfWJqKzWE+SKr0jvHNIJsJJYILQlpYShpi/DRJJMbosgDMQ==", + "license": "Apache-2.0" + }, + "node_modules/has": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/has/-/has-1.0.4.tgz", + "integrity": "sha512-qdSAmqLF6209RFj4VVItywPMbm3vWylknmB3nvNiUIs72xAimcM8nVYxYr7ncvZq5qzk9MKIZR8ijqD/1QuYjQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/has-property-descriptors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", + "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-proto": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.0.3.tgz", + "integrity": "sha512-SJ1amZAJUiZS+PhsVLf5tGydlaVB8EdFpaSO4gmiUKUOxk8qzn5AIy4ZeJUmh22znIdk/uMAUT2pl3FxzVUH+Q==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hash-base": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/hash-base/-/hash-base-3.0.4.tgz", + "integrity": "sha512-EeeoJKjTyt868liAlVmcv2ZsUfGHlE3Q+BICOXcZiwN3osr5Q/zFGYmTJpoIzuaSTAwndFy+GqhEwlU4L3j4Ow==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/hash.js": { + "version": "1.1.7", + "resolved": "https://registry.npmjs.org/hash.js/-/hash.js-1.1.7.tgz", + "integrity": "sha512-taOaskGt4z4SOANNseOviYDvjEJinIkRgmp7LbKP2YTTmVxWBl87s/uzK9r+44BclBSp2X7K1hqeNfz9JbBeXA==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "minimalistic-assert": "^1.0.1" + } + }, + "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/hmac-drbg": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/hmac-drbg/-/hmac-drbg-1.0.1.tgz", + "integrity": "sha512-Tti3gMqLdZfhOQY1Mzf/AanLiqh1WTiJgEj26ZuYQ9fbkLomzGchCws4FyrSd4VkpBfiNhaE1On+lOz894jvXg==", + "license": "MIT", + "dependencies": { + "hash.js": "^1.0.3", + "minimalistic-assert": "^1.0.0", + "minimalistic-crypto-utils": "^1.0.1" + } + }, + "node_modules/htmlescape": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/htmlescape/-/htmlescape-1.1.1.tgz", + "integrity": "sha512-eVcrzgbR4tim7c7soKQKtxa/kQM4TzjnlU83rcZ9bHU6t31ehfV7SktN6McWgwPWg+JYMA/O3qpGxBvFq1z2Jg==", + "license": "MIT", + "engines": { + "node": ">=0.10" + } + }, + "node_modules/https-browserify": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/https-browserify/-/https-browserify-1.0.0.tgz", + "integrity": "sha512-J+FkSdyD+0mA0N+81tMotaRMfSL9SGi+xpD3T6YApKsc3bGSXJlfXri3VyFOeYkfLRQisDk1W+jIFFKBeUBbBg==", + "license": "MIT" + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "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": "BSD-3-Clause" + }, + "node_modules/inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", + "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.", + "license": "ISC", + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "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/inline-source-map": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/inline-source-map/-/inline-source-map-0.6.3.tgz", + "integrity": "sha512-1aVsPEsJWMJq/pdMU61CDlm1URcW702MTB4w9/zUjMus6H/Py8o7g68Pr9D4I6QluWGt/KdmswuRhaA05xVR1w==", + "license": "MIT", + "dependencies": { + "source-map": "~0.5.3" + } + }, + "node_modules/inline-source-map/node_modules/source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha512-LbrmJOMUSdEVxIKvdcJzQC+nQhe8FUZQTXQy6+I75skNgn3OoQ0DZA8YnFa7gp8tqtL3KPf1kmo0R5DoApeSGQ==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/insert-module-globals": { + "version": "7.2.1", + "resolved": "https://registry.npmjs.org/insert-module-globals/-/insert-module-globals-7.2.1.tgz", + "integrity": "sha512-ufS5Qq9RZN+Bu899eA9QCAYThY+gGW7oRkmb0vC93Vlyu/CFGcH0OYPEjVkDXA5FEbTt1+VWzdoOD3Ny9N+8tg==", + "license": "MIT", + "dependencies": { + "acorn-node": "^1.5.2", + "combine-source-map": "^0.8.0", + "concat-stream": "^1.6.1", + "is-buffer": "^1.1.0", + "JSONStream": "^1.0.3", + "path-is-absolute": "^1.0.1", + "process": "~0.11.0", + "through2": "^2.0.0", + "undeclared-identifiers": "^1.1.2", + "xtend": "^4.0.0" + }, + "bin": { + "insert-module-globals": "bin/cmd.js" + } + }, + "node_modules/is-arguments": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-arguments/-/is-arguments-1.1.1.tgz", + "integrity": "sha512-8Q7EARjzEnKpt/PCD7e1cgUS0a6X8u5tdSiMqXhojOdoV9TsMsiO+9VLC5vAmO8N7/GmXn7yjR8qnA6bVAEzfA==", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.2", + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-buffer": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", + "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==", + "license": "MIT" + }, + "node_modules/is-callable": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.7.tgz", + "integrity": "sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-core-module": { + "version": "2.15.1", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.15.1.tgz", + "integrity": "sha512-z0vtXSwucUJtANQWldhbtbt7BnL0vxiFjIdDLAatwhDYty2bad6s+rijD6Ri4YuYJubLzIJLUidCh09e1djEVQ==", + "license": "MIT", + "dependencies": { + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-generator-function": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/is-generator-function/-/is-generator-function-1.0.10.tgz", + "integrity": "sha512-jsEjy9l3yiXEQ+PsXdmBwEPcOxaXWLspKdplFUVI9vq1iZgIekeC0L167qeu86czQaxed3q/Uzuw0swL0irL8A==", + "license": "MIT", + "dependencies": { + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-typed-array": { + "version": "1.1.13", + "resolved": "https://registry.npmjs.org/is-typed-array/-/is-typed-array-1.1.13.tgz", + "integrity": "sha512-uZ25/bUAlUY5fR4OKT4rZQEBrzQWYV9ZJYGGsUmEJ6thodVJ1HX64ePQ6Z0qPWP+m+Uq6e9UugrE38jeYsDSMw==", + "license": "MIT", + "dependencies": { + "which-typed-array": "^1.1.14" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", + "license": "MIT" + }, + "node_modules/js2xmlparser": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/js2xmlparser/-/js2xmlparser-4.0.2.tgz", + "integrity": "sha512-6n4D8gLlLf1n5mNLQPRfViYzu9RATblzPEtm1SthMX1Pjao0r9YI9nw7ZIfRxQMERS87mcswrg+r/OYrPRX6jA==", + "license": "Apache-2.0", + "dependencies": { + "xmlcreate": "^2.0.4" + } + }, + "node_modules/jsdoc": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/jsdoc/-/jsdoc-4.0.3.tgz", + "integrity": "sha512-Nu7Sf35kXJ1MWDZIMAuATRQTg1iIPdzh7tqJ6jjvaU/GfDf+qi5UV8zJR3Mo+/pYFvm8mzay4+6O5EWigaQBQw==", + "license": "Apache-2.0", + "dependencies": { + "@babel/parser": "^7.20.15", + "@jsdoc/salty": "^0.2.1", + "@types/markdown-it": "^14.1.1", + "bluebird": "^3.7.2", + "catharsis": "^0.9.0", + "escape-string-regexp": "^2.0.0", + "js2xmlparser": "^4.0.2", + "klaw": "^3.0.0", + "markdown-it": "^14.1.0", + "markdown-it-anchor": "^8.6.7", + "marked": "^4.0.10", + "mkdirp": "^1.0.4", + "requizzle": "^0.2.3", + "strip-json-comments": "^3.1.0", + "underscore": "~1.13.2" + }, + "bin": { + "jsdoc": "jsdoc.js" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/jsonparse": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/jsonparse/-/jsonparse-1.3.1.tgz", + "integrity": "sha512-POQXvpdL69+CluYsillJ7SUhKvytYjW9vG/GKpnf+xP8UWgYEM/RaMzHHofbALDiKbbP1W8UEYmgGl39WkPZsg==", + "engines": [ + "node >= 0.2.0" + ], + "license": "MIT" + }, + "node_modules/JSONStream": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/JSONStream/-/JSONStream-1.3.5.tgz", + "integrity": "sha512-E+iruNOY8VV9s4JEbe1aNEm6MiszPRr/UfcHMz0TQh1BXSxHK+ASV1R6W4HpjBhSeS+54PIsAMCBmwD06LLsqQ==", + "license": "(MIT OR Apache-2.0)", + "dependencies": { + "jsonparse": "^1.2.0", + "through": ">=2.2.7 <3" + }, + "bin": { + "JSONStream": "bin.js" + }, + "engines": { + "node": "*" + } + }, + "node_modules/klaw": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/klaw/-/klaw-3.0.0.tgz", + "integrity": "sha512-0Fo5oir+O9jnXu5EefYbVK+mHMBeEVEy2cmctR1O1NECcCkPRreJKrS6Qt/j3KC2C148Dfo9i3pCmCMsdqGr0g==", + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.1.9" + } + }, + "node_modules/labeled-stream-splicer": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/labeled-stream-splicer/-/labeled-stream-splicer-2.0.2.tgz", + "integrity": "sha512-Ca4LSXFFZUjPScRaqOcFxneA0VpKZr4MMYCljyQr4LIewTLb3Y0IUTIsnBBsVubIeEfxeSZpSjSsRM8APEQaAw==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.1", + "stream-splicer": "^2.0.0" + } + }, + "node_modules/levn": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz", + "integrity": "sha512-0OO4y2iOHix2W6ujICbKIaEQXvFQHue65vUG3pb5EUomzPI90z9hsA1VsO/dbIIpC53J8gxM9Q4Oho0jrCM/yA==", + "license": "MIT", + "dependencies": { + "prelude-ls": "~1.1.2", + "type-check": "~0.3.2" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/linkify-it": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/linkify-it/-/linkify-it-5.0.0.tgz", + "integrity": "sha512-5aHCbzQRADcdP+ATqnDuhhJ/MRIqDkZX5pyjFHRRysS8vZ5AbqGEoFIb6pYHPZ+L/OC2Lc+xT8uHVVR5CAK/wQ==", + "license": "MIT", + "dependencies": { + "uc.micro": "^2.0.0" + } + }, + "node_modules/lodash": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", + "license": "MIT" + }, + "node_modules/lodash.memoize": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/lodash.memoize/-/lodash.memoize-3.0.4.tgz", + "integrity": "sha512-eDn9kqrAmVUC1wmZvlQ6Uhde44n+tXpqPrN8olQJbttgh0oKclk+SF54P47VEGE9CEiMeRwAP8BaM7UHvBkz2A==", + "license": "MIT" + }, + "node_modules/long": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/long/-/long-5.2.3.tgz", + "integrity": "sha512-lcHwpNoggQTObv5apGNCTdJrO69eHOZMi4BNC+rTLER8iHAqGrUVeLh/irVIM7zTw2bOXA8T6uNPeujwOLg/2Q==", + "license": "Apache-2.0", + "peer": true + }, + "node_modules/markdown-it": { + "version": "14.1.0", + "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-14.1.0.tgz", + "integrity": "sha512-a54IwgWPaeBCAAsv13YgmALOF1elABB08FxO9i+r4VFk5Vl4pKokRPeX8u5TCgSsPi6ec1otfLjdOpVcgbpshg==", + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1", + "entities": "^4.4.0", + "linkify-it": "^5.0.0", + "mdurl": "^2.0.0", + "punycode.js": "^2.3.1", + "uc.micro": "^2.1.0" + }, + "bin": { + "markdown-it": "bin/markdown-it.mjs" + } + }, + "node_modules/markdown-it-anchor": { + "version": "8.6.7", + "resolved": "https://registry.npmjs.org/markdown-it-anchor/-/markdown-it-anchor-8.6.7.tgz", + "integrity": "sha512-FlCHFwNnutLgVTflOYHPW2pPcl2AACqVzExlkGQNsi4CJgqOHN7YTgDd4LuhgN1BFO3TS0vLAruV1Td6dwWPJA==", + "license": "Unlicense", + "peerDependencies": { + "@types/markdown-it": "*", + "markdown-it": "*" + } + }, + "node_modules/marked": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/marked/-/marked-4.3.0.tgz", + "integrity": "sha512-PRsaiG84bK+AMvxziE/lCFss8juXjNaWzVbN5tXAm4XjeaS9NAHhop+PjQxz2A9h8Q4M/xGmzP8vqNwy6JeK0A==", + "license": "MIT", + "bin": { + "marked": "bin/marked.js" + }, + "engines": { + "node": ">= 12" + } + }, + "node_modules/md5.js": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/md5.js/-/md5.js-1.3.5.tgz", + "integrity": "sha512-xitP+WxNPcTTOgnTJcrhM0xvdPepipPSf3I8EIpGKeFLjt3PlJLIDG3u8EX53ZIubkb+5U2+3rELYpEhHhzdkg==", + "license": "MIT", + "dependencies": { + "hash-base": "^3.0.0", + "inherits": "^2.0.1", + "safe-buffer": "^5.1.2" + } + }, + "node_modules/mdurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/mdurl/-/mdurl-2.0.0.tgz", + "integrity": "sha512-Lf+9+2r+Tdp5wXDXC4PcIBjTDtq4UKjCPMQhKIuzpJNW0b96kVqSwW0bT7FhRSfmAiFYgP+SCRvdrDozfh0U5w==", + "license": "MIT" + }, + "node_modules/miller-rabin": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/miller-rabin/-/miller-rabin-4.0.1.tgz", + "integrity": "sha512-115fLhvZVqWwHPbClyntxEVfVDfl9DLLTuJvq3g2O/Oxi8AiNouAHvDSzHS0viUJc+V5vm3eq91Xwqn9dp4jRA==", + "license": "MIT", + "dependencies": { + "bn.js": "^4.0.0", + "brorand": "^1.0.1" + }, + "bin": { + "miller-rabin": "bin/miller-rabin" + } + }, + "node_modules/miller-rabin/node_modules/bn.js": { + "version": "4.12.0", + "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.0.tgz", + "integrity": "sha512-c98Bf3tPniI+scsdk237ku1Dc3ujXQTSgyiPUDEOe7tRkhrqridvh8klBv0HCEso1OLOYcHuCv/cS6DNxKH+ZA==", + "license": "MIT" + }, + "node_modules/minimalistic-assert": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz", + "integrity": "sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A==", + "license": "ISC" + }, + "node_modules/minimalistic-crypto-utils": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/minimalistic-crypto-utils/-/minimalistic-crypto-utils-1.0.1.tgz", + "integrity": "sha512-JIYlbt6g8i5jKfJ3xz7rF0LXmv2TkDxBLUkiBeZ7bAx4GnnNMr8xFpGnOxn6GhTEHx3SjRrZEoU+j04prX1ktg==", + "license": "MIT" + }, + "node_modules/minimatch": { + "version": "5.1.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.6.tgz", + "integrity": "sha512-lKwV/1brpG6mBUFHtb7NUmtABCb2WZZmm2wNiOA5hAb8VdCS4B3dtMWyvcoViccwAW/COERjXLt0zP1zXUN26g==", + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/mkdirp": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", + "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==", + "license": "MIT", + "bin": { + "mkdirp": "bin/cmd.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/mkdirp-classic": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz", + "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==", + "license": "MIT" + }, + "node_modules/module-deps": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/module-deps/-/module-deps-6.2.3.tgz", + "integrity": "sha512-fg7OZaQBcL4/L+AK5f4iVqf9OMbCclXfy/znXRxTVhJSeW5AIlS9AwheYwDaXM3lVW7OBeaeUEY3gbaC6cLlSA==", + "license": "MIT", + "dependencies": { + "browser-resolve": "^2.0.0", + "cached-path-relative": "^1.0.2", + "concat-stream": "~1.6.0", + "defined": "^1.0.0", + "detective": "^5.2.0", + "duplexer2": "^0.1.2", + "inherits": "^2.0.1", + "JSONStream": "^1.0.3", + "parents": "^1.0.0", + "readable-stream": "^2.0.2", + "resolve": "^1.4.0", + "stream-combiner2": "^1.1.1", + "subarg": "^1.0.0", + "through2": "^2.0.0", + "xtend": "^4.0.0" + }, + "bin": { + "module-deps": "bin/cmd.js" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.2.tgz", + "integrity": "sha512-IRZSRuzJiynemAXPYtPe5BoI/RESNYR7TYm50MC5Mqbd3Jmw5y790sErYw3V6SryFJD64b74qQQs9wn5Bg/k3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object-keys": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", + "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/object.assign": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.5.tgz", + "integrity": "sha512-byy+U7gp+FVwmyzKPYhW2h5l3crpmGsxl7X2s8y43IgxvG4g3QZ6CffDtsNQy1WsmZpQbO+ybo0AlW7TY6DcBQ==", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.5", + "define-properties": "^1.2.1", + "has-symbols": "^1.0.3", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/optionator": { + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.8.3.tgz", + "integrity": "sha512-+IW9pACdk3XWmmTXG8m3upGUJst5XRGzxMRjXzAuJ1XnIFNvfhjjIuYkDvysnPQ7qzqVzLt78BCruntqRhWQbA==", + "license": "MIT", + "dependencies": { + "deep-is": "~0.1.3", + "fast-levenshtein": "~2.0.6", + "levn": "~0.3.0", + "prelude-ls": "~1.1.2", + "type-check": "~0.3.2", + "word-wrap": "~1.2.3" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/os-browserify": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/os-browserify/-/os-browserify-0.3.0.tgz", + "integrity": "sha512-gjcpUc3clBf9+210TRaDWbf+rZZZEshZ+DlXMRCeAjp0xhTrnQsKHypIy1J3d5hKdUzj69t708EHtU8P6bUn0A==", + "license": "MIT" + }, + "node_modules/pako": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz", + "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==", + "license": "(MIT AND Zlib)" + }, + "node_modules/parents": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parents/-/parents-1.0.1.tgz", + "integrity": "sha512-mXKF3xkoUt5td2DoxpLmtOmZvko9VfFpwRwkKDHSNvgmpLAeBo18YDhcPbBzJq+QLCHMbGOfzia2cX4U+0v9Mg==", + "license": "MIT", + "dependencies": { + "path-platform": "~0.11.15" + } + }, + "node_modules/parse-asn1": { + "version": "5.1.7", + "resolved": "https://registry.npmjs.org/parse-asn1/-/parse-asn1-5.1.7.tgz", + "integrity": "sha512-CTM5kuWR3sx9IFamcl5ErfPl6ea/N8IYwiJ+vpeB2g+1iknv7zBl5uPwbMbRVznRVbrNY6lGuDoE5b30grmbqg==", + "license": "ISC", + "dependencies": { + "asn1.js": "^4.10.1", + "browserify-aes": "^1.2.0", + "evp_bytestokey": "^1.0.3", + "hash-base": "~3.0", + "pbkdf2": "^3.1.2", + "safe-buffer": "^5.2.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/path-browserify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-1.0.1.tgz", + "integrity": "sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==", + "license": "MIT" + }, + "node_modules/path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "license": "MIT" + }, + "node_modules/path-platform": { + "version": "0.11.15", + "resolved": "https://registry.npmjs.org/path-platform/-/path-platform-0.11.15.tgz", + "integrity": "sha512-Y30dB6rab1A/nfEKsZxmr01nUotHX0c/ZiIAsCTatEe1CmS5Pm5He7fZ195bPT7RdquoaL8lLxFCMQi/bS7IJg==", + "license": "MIT", + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/pbkdf2": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/pbkdf2/-/pbkdf2-3.1.2.tgz", + "integrity": "sha512-iuh7L6jA7JEGu2WxDwtQP1ddOpaJNC4KlDEFfdQajSGgGPNi4OyDc2R7QnbY2bR9QjBVGwgvTdNJZoE7RaxUMA==", + "license": "MIT", + "dependencies": { + "create-hash": "^1.1.2", + "create-hmac": "^1.1.4", + "ripemd160": "^2.0.1", + "safe-buffer": "^5.0.1", + "sha.js": "^2.4.8" + }, + "engines": { + "node": ">=0.12" + } + }, + "node_modules/possible-typed-array-names": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.0.0.tgz", + "integrity": "sha512-d7Uw+eZoloe0EHDIYoe+bQ5WXnGMOpmiZFTuMWCwpjzzkL2nTjcKiAk4hh8TjnGye2TwWOk3UXucZ+3rbmBa8Q==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/prelude-ls": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz", + "integrity": "sha512-ESF23V4SKG6lVSGZgYNpbsiaAkdab6ZgOxe52p7+Kid3W3u3bxR4Vfd/o21dmN7jSt0IwgZ4v5MUd26FEtXE9w==", + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/process": { + "version": "0.11.10", + "resolved": "https://registry.npmjs.org/process/-/process-0.11.10.tgz", + "integrity": "sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A==", + "license": "MIT", + "engines": { + "node": ">= 0.6.0" + } + }, + "node_modules/process-nextick-args": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", + "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==", + "license": "MIT" + }, + "node_modules/protobufjs": { + "version": "7.4.0", + "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.4.0.tgz", + "integrity": "sha512-mRUWCc3KUU4w1jU8sGxICXH/gNS94DvI1gxqDvBzhj1JpcsimQkYiOJfwsPUykUI5ZaspFbSgmBLER8IrQ3tqw==", + "hasInstallScript": true, + "license": "BSD-3-Clause", + "peer": true, + "dependencies": { + "@protobufjs/aspromise": "^1.1.2", + "@protobufjs/base64": "^1.1.2", + "@protobufjs/codegen": "^2.0.4", + "@protobufjs/eventemitter": "^1.1.0", + "@protobufjs/fetch": "^1.1.0", + "@protobufjs/float": "^1.0.2", + "@protobufjs/inquire": "^1.1.0", + "@protobufjs/path": "^1.1.2", + "@protobufjs/pool": "^1.1.0", + "@protobufjs/utf8": "^1.1.0", + "@types/node": ">=13.7.0", + "long": "^5.0.0" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/protobufjs-cli": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/protobufjs-cli/-/protobufjs-cli-1.1.3.tgz", + "integrity": "sha512-MqD10lqF+FMsOayFiNOdOGNlXc4iKDCf0ZQPkPR+gizYh9gqUeGTWulABUCdI+N67w5RfJ6xhgX4J8pa8qmMXQ==", + "license": "BSD-3-Clause", + "dependencies": { + "chalk": "^4.0.0", + "escodegen": "^1.13.0", + "espree": "^9.0.0", + "estraverse": "^5.1.0", + "glob": "^8.0.0", + "jsdoc": "^4.0.0", + "minimist": "^1.2.0", + "semver": "^7.1.2", + "tmp": "^0.2.1", + "uglify-js": "^3.7.7" + }, + "bin": { + "pbjs": "bin/pbjs", + "pbts": "bin/pbts" + }, + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "protobufjs": "^7.0.0" + } + }, + "node_modules/public-encrypt": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/public-encrypt/-/public-encrypt-4.0.3.tgz", + "integrity": "sha512-zVpa8oKZSz5bTMTFClc1fQOnyyEzpl5ozpi1B5YcvBrdohMjH2rfsBtyXcuNuwjsDIXmBYlF2N5FlJYhR29t8Q==", + "license": "MIT", + "dependencies": { + "bn.js": "^4.1.0", + "browserify-rsa": "^4.0.0", + "create-hash": "^1.1.0", + "parse-asn1": "^5.0.0", + "randombytes": "^2.0.1", + "safe-buffer": "^5.1.2" + } + }, + "node_modules/public-encrypt/node_modules/bn.js": { + "version": "4.12.0", + "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.0.tgz", + "integrity": "sha512-c98Bf3tPniI+scsdk237ku1Dc3ujXQTSgyiPUDEOe7tRkhrqridvh8klBv0HCEso1OLOYcHuCv/cS6DNxKH+ZA==", + "license": "MIT" + }, + "node_modules/punycode": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.4.1.tgz", + "integrity": "sha512-jmYNElW7yvO7TV33CjSmvSiE2yco3bV2czu/OzDKdMNVZQWfxCblURLhf+47syQRBntjfLdd/H0egrzIG+oaFQ==", + "license": "MIT" + }, + "node_modules/punycode.js": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode.js/-/punycode.js-2.3.1.tgz", + "integrity": "sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "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/querystring-es3": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/querystring-es3/-/querystring-es3-0.2.1.tgz", + "integrity": "sha512-773xhDQnZBMFobEiztv8LIl70ch5MSF/jUQVlhwFyBILqq96anmoctVIYz+ZRp0qbCKATTn6ev02M3r7Ga5vqA==", + "engines": { + "node": ">=0.4.x" + } + }, + "node_modules/randombytes": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", + "integrity": "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==", + "license": "MIT", + "dependencies": { + "safe-buffer": "^5.1.0" + } + }, + "node_modules/randomfill": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/randomfill/-/randomfill-1.0.4.tgz", + "integrity": "sha512-87lcbR8+MhcWcUiQ+9e+Rwx8MyR2P7qnt15ynUlbm3TU/fjbgz4GsvfSUDTemtCCtVCqb4ZcEFlyPNTh9bBTLw==", + "license": "MIT", + "dependencies": { + "randombytes": "^2.0.5", + "safe-buffer": "^5.1.0" + } + }, + "node_modules/read-only-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/read-only-stream/-/read-only-stream-2.0.0.tgz", + "integrity": "sha512-3ALe0bjBVZtkdWKIcThYpQCLbBMd/+Tbh2CDSrAIDO3UsZ4Xs+tnyjv2MjCOMMgBG+AsUOeuP1cgtY1INISc8w==", + "license": "MIT", + "dependencies": { + "readable-stream": "^2.0.2" + } + }, + "node_modules/readable-stream": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", + "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", + "license": "MIT", + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/readable-stream/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "license": "MIT" + }, + "node_modules/readable-stream/node_modules/string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/requizzle": { + "version": "0.2.4", + "resolved": "https://registry.npmjs.org/requizzle/-/requizzle-0.2.4.tgz", + "integrity": "sha512-JRrFk1D4OQ4SqovXOgdav+K8EAhSB/LJZqCz8tbX0KObcdeM15Ss59ozWMBWmmINMagCwmqn4ZNryUGpBsl6Jw==", + "license": "MIT", + "dependencies": { + "lodash": "^4.17.21" + } + }, + "node_modules/resolve": { + "version": "1.22.8", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.8.tgz", + "integrity": "sha512-oKWePCxqpd6FlLvGV1VU0x7bkPmmCNolxzjMf4NczoDnQcIWrAF+cPtZn5i6n+RfD2d9i0tzpKnG6Yk168yIyw==", + "license": "MIT", + "dependencies": { + "is-core-module": "^2.13.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/ripemd160": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/ripemd160/-/ripemd160-2.0.2.tgz", + "integrity": "sha512-ii4iagi25WusVoiC4B4lq7pbXfAp3D9v5CwfkY33vffw2+pkDjY1D8GaN7spsxvCSx8dkPqOZCEZyfxcmJG2IA==", + "license": "MIT", + "dependencies": { + "hash-base": "^3.0.0", + "inherits": "^2.0.1" + } + }, + "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/semver": { + "version": "7.6.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.3.tgz", + "integrity": "sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/set-function-length": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", + "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==", + "license": "MIT", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/sha.js": { + "version": "2.4.11", + "resolved": "https://registry.npmjs.org/sha.js/-/sha.js-2.4.11.tgz", + "integrity": "sha512-QMEp5B7cftE7APOjk5Y6xgrbWu+WkLVQwk8JNjZ8nKRciZaByEW6MubieAiToS7+dwvrjGhH8jRXz3MVd0AYqQ==", + "license": "(MIT AND BSD-3-Clause)", + "dependencies": { + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" + }, + "bin": { + "sha.js": "bin.js" + } + }, + "node_modules/shasum-object": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/shasum-object/-/shasum-object-1.0.0.tgz", + "integrity": "sha512-Iqo5rp/3xVi6M4YheapzZhhGPVs0yZwHj7wvwQ1B9z8H6zk+FEnI7y3Teq7qwnekfEhu8WmG2z0z4iWZaxLWVg==", + "license": "Apache-2.0", + "dependencies": { + "fast-safe-stringify": "^2.0.7" + } + }, + "node_modules/shell-quote": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.1.tgz", + "integrity": "sha512-6j1W9l1iAs/4xYBI1SYOVZyFcCis9b4KCLQ8fgAGG07QvzaRLVVRQvAy85yNmmZSjYjg4MWh4gNvlPujU/5LpA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.6.tgz", + "integrity": "sha512-fDW/EZ6Q9RiO8eFG8Hj+7u/oW+XrPTIChwCOM2+th2A6OblDtYYIpve9m+KvI9Z4C9qSEXlaGR6bTEYHReuglA==", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.4", + "object-inspect": "^1.13.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/simple-concat": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz", + "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==", + "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/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "license": "BSD-3-Clause", + "optional": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/stream-browserify": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/stream-browserify/-/stream-browserify-3.0.0.tgz", + "integrity": "sha512-H73RAHsVBapbim0tU2JwwOiXUj+fikfiaoYAKHF3VJfA0pe2BCzkhAHBlLG6REzE+2WNZcxOXjK7lkso+9euLA==", + "license": "MIT", + "dependencies": { + "inherits": "~2.0.4", + "readable-stream": "^3.5.0" + } + }, + "node_modules/stream-browserify/node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/stream-combiner2": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/stream-combiner2/-/stream-combiner2-1.1.1.tgz", + "integrity": "sha512-3PnJbYgS56AeWgtKF5jtJRT6uFJe56Z0Hc5Ngg/6sI6rIt8iiMBTa9cvdyFfpMQjaVHr8dusbNeFGIIonxOvKw==", + "license": "MIT", + "dependencies": { + "duplexer2": "~0.1.0", + "readable-stream": "^2.0.2" + } + }, + "node_modules/stream-http": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/stream-http/-/stream-http-3.2.0.tgz", + "integrity": "sha512-Oq1bLqisTyK3TSCXpPbT4sdeYNdmyZJv1LxpEm2vu1ZhK89kSE5YXwZc3cWk0MagGaKriBh9mCFbVGtO+vY29A==", + "license": "MIT", + "dependencies": { + "builtin-status-codes": "^3.0.0", + "inherits": "^2.0.4", + "readable-stream": "^3.6.0", + "xtend": "^4.0.2" + } + }, + "node_modules/stream-http/node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/stream-splicer": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/stream-splicer/-/stream-splicer-2.0.1.tgz", + "integrity": "sha512-Xizh4/NPuYSyAXyT7g8IvdJ9HJpxIGL9PjyhtywCZvvP0OPIdqyrr4dMikeuvY8xahpdKEBlBTySe583totajg==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.1", + "readable-stream": "^2.0.2" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/strip-json-comments": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", + "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/subarg": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/subarg/-/subarg-1.0.0.tgz", + "integrity": "sha512-RIrIdRY0X1xojthNcVtgT9sjpOGagEUKpZdgBUi054OEPFo282yg+zE+t1Rj3+RqKq2xStL7uUHhY+AjbC4BXg==", + "license": "MIT", + "dependencies": { + "minimist": "^1.1.0" + } + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/syntax-error": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/syntax-error/-/syntax-error-1.4.0.tgz", + "integrity": "sha512-YPPlu67mdnHGTup2A8ff7BC2Pjq0e0Yp/IyTFN03zWO0RcK07uLcbi7C2KpGR2FvWbaB0+bfE27a+sBKebSo7w==", + "license": "MIT", + "dependencies": { + "acorn-node": "^1.2.0" + } + }, + "node_modules/through": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", + "integrity": "sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg==", + "license": "MIT" + }, + "node_modules/through2": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/through2/-/through2-2.0.5.tgz", + "integrity": "sha512-/mrRod8xqpA+IHSLyGCQ2s8SPHiCDEeQJSep1jqLYeEUClOFG2Qsh+4FU6G9VeqpZnGW/Su8LQGc4YKni5rYSQ==", + "license": "MIT", + "dependencies": { + "readable-stream": "~2.3.6", + "xtend": "~4.0.1" + } + }, + "node_modules/timers-browserify": { + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/timers-browserify/-/timers-browserify-1.4.2.tgz", + "integrity": "sha512-PIxwAupJZiYU4JmVZYwXp9FKsHMXb5h0ZEFyuXTAn8WLHOlcij+FEcbrvDsom1o5dr1YggEtFbECvGCW2sT53Q==", + "dependencies": { + "process": "~0.11.0" + }, + "engines": { + "node": ">=0.6.0" + } + }, + "node_modules/tmp": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.3.tgz", + "integrity": "sha512-nZD7m9iCPC5g0pYmcaxogYKggSfLsdxl8of3Q/oIbqCqLLIO9IAF0GWjX1z9NZRHPiXv8Wex4yDCaZsgEw0Y8w==", + "license": "MIT", + "engines": { + "node": ">=14.14" + } + }, + "node_modules/to-fast-properties": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz", + "integrity": "sha512-/OaKK0xYrs3DmxRYqL/yDc+FxFUVYhDlXMhRmv3z915w2HF1tnN1omB354j8VUGO/hbRzyD6Y3sA7v7GS/ceog==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/tty-browserify": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/tty-browserify/-/tty-browserify-0.0.1.tgz", + "integrity": "sha512-C3TaO7K81YvjCgQH9Q1S3R3P3BtN3RIM8n+OvX4il1K1zgE8ZhI0op7kClgkxtutIE8hQrcrHBXvIheqKUUCxw==", + "license": "MIT" + }, + "node_modules/type-check": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.3.2.tgz", + "integrity": "sha512-ZCmOJdvOWDBYJlzAoFkC+Q0+bUyEOS1ltgp1MGU03fqHG+dbi9tBFU2Rd9QKiDZFAYrhPh2JUf7rZRIuHRKtOg==", + "license": "MIT", + "dependencies": { + "prelude-ls": "~1.1.2" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/typedarray": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz", + "integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==", + "license": "MIT" + }, + "node_modules/uc.micro": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/uc.micro/-/uc.micro-2.1.0.tgz", + "integrity": "sha512-ARDJmphmdvUk6Glw7y9DQ2bFkKBHwQHLi2lsaH6PPmz/Ka9sFOBsBluozhDltWmnv9u/cF6Rt87znRTPV+yp/A==", + "license": "MIT" + }, + "node_modules/uglify-js": { + "version": "3.19.3", + "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.19.3.tgz", + "integrity": "sha512-v3Xu+yuwBXisp6QYTcH4UbH+xYJXqnq2m/LtQVWKWzYc1iehYnLixoQDN9FH6/j9/oybfd6W9Ghwkl8+UMKTKQ==", + "license": "BSD-2-Clause", + "bin": { + "uglifyjs": "bin/uglifyjs" + }, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/umd": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/umd/-/umd-3.0.3.tgz", + "integrity": "sha512-4IcGSufhFshvLNcMCV80UnQVlZ5pMOC8mvNPForqwA4+lzYQuetTESLDQkeLmihq8bRcnpbQa48Wb8Lh16/xow==", + "license": "MIT", + "bin": { + "umd": "bin/cli.js" + } + }, + "node_modules/undeclared-identifiers": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/undeclared-identifiers/-/undeclared-identifiers-1.1.3.tgz", + "integrity": "sha512-pJOW4nxjlmfwKApE4zvxLScM/njmwj/DiUBv7EabwE4O8kRUy+HIwxQtZLBPll/jx1LJyBcqNfB3/cpv9EZwOw==", + "license": "Apache-2.0", + "dependencies": { + "acorn-node": "^1.3.0", + "dash-ast": "^1.0.0", + "get-assigned-identifiers": "^1.2.0", + "simple-concat": "^1.0.0", + "xtend": "^4.0.1" + }, + "bin": { + "undeclared-identifiers": "bin.js" + } + }, + "node_modules/underscore": { + "version": "1.13.7", + "resolved": "https://registry.npmjs.org/underscore/-/underscore-1.13.7.tgz", + "integrity": "sha512-GMXzWtsc57XAtguZgaQViUOzs0KTkk8ojr3/xAxXLITqf/3EMwxC0inyETfDFjH/Krbhuep0HNbbjI9i/q3F3g==", + "license": "MIT" + }, + "node_modules/undici-types": { + "version": "6.19.8", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.19.8.tgz", + "integrity": "sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw==", + "license": "MIT", + "peer": true + }, + "node_modules/url": { + "version": "0.11.4", + "resolved": "https://registry.npmjs.org/url/-/url-0.11.4.tgz", + "integrity": "sha512-oCwdVC7mTuWiPyjLUz/COz5TLk6wgp0RCsN+wHZ2Ekneac9w8uuV0njcbbie2ME+Vs+d6duwmYuR3HgQXs1fOg==", + "license": "MIT", + "dependencies": { + "punycode": "^1.4.1", + "qs": "^6.12.3" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/util": { + "version": "0.12.5", + "resolved": "https://registry.npmjs.org/util/-/util-0.12.5.tgz", + "integrity": "sha512-kZf/K6hEIrWHI6XqOFUiiMa+79wE/D8Q+NCNAWclkyg3b4d2k7s0QGepNjiABc+aR3N1PAyHL7p6UcLY6LmrnA==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "is-arguments": "^1.0.4", + "is-generator-function": "^1.0.7", + "is-typed-array": "^1.1.3", + "which-typed-array": "^1.1.2" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "license": "MIT" + }, + "node_modules/vm-browserify": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vm-browserify/-/vm-browserify-1.1.2.tgz", + "integrity": "sha512-2ham8XPWTONajOR0ohOKOHXkm3+gaBmGut3SRuu75xLd/RRaY6vqgh8NBYYk7+RW3u5AtzPQZG8F10LHkl0lAQ==", + "license": "MIT" + }, + "node_modules/which-typed-array": { + "version": "1.1.15", + "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.15.tgz", + "integrity": "sha512-oV0jmFtUky6CXfkqehVvBP/LSWJ2sy4vWMioiENyJLePrBO/yKyV9OyJySfAKosh+RYkIl5zJCNZ8/4JncrpdA==", + "license": "MIT", + "dependencies": { + "available-typed-arrays": "^1.0.7", + "call-bind": "^1.0.7", + "for-each": "^0.3.3", + "gopd": "^1.0.1", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/word-wrap": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", + "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + }, + "node_modules/xmlcreate": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/xmlcreate/-/xmlcreate-2.0.4.tgz", + "integrity": "sha512-nquOebG4sngPmGPICTS5EnxqhKbCmz5Ox5hsszI2T6U5qdrJizBc+0ilYSEjTSzU0yZcmvppztXe/5Al5fUwdg==", + "license": "Apache-2.0" + }, + "node_modules/xtend": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", + "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", + "license": "MIT", + "engines": { + "node": ">=0.4" + } + } + } +} diff --git a/libcore/node_modules/@babel/helper-string-parser/LICENSE b/libcore/node_modules/@babel/helper-string-parser/LICENSE new file mode 100644 index 0000000..f31575e --- /dev/null +++ b/libcore/node_modules/@babel/helper-string-parser/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +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. diff --git a/libcore/node_modules/@babel/helper-string-parser/README.md b/libcore/node_modules/@babel/helper-string-parser/README.md new file mode 100644 index 0000000..771b470 --- /dev/null +++ b/libcore/node_modules/@babel/helper-string-parser/README.md @@ -0,0 +1,19 @@ +# @babel/helper-string-parser + +> A utility package to parse strings + +See our website [@babel/helper-string-parser](https://babeljs.io/docs/babel-helper-string-parser) for more information. + +## Install + +Using npm: + +```sh +npm install --save @babel/helper-string-parser +``` + +or using yarn: + +```sh +yarn add @babel/helper-string-parser +``` diff --git a/libcore/node_modules/@babel/helper-string-parser/lib/index.js b/libcore/node_modules/@babel/helper-string-parser/lib/index.js new file mode 100644 index 0000000..2d94115 --- /dev/null +++ b/libcore/node_modules/@babel/helper-string-parser/lib/index.js @@ -0,0 +1,295 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.readCodePoint = readCodePoint; +exports.readInt = readInt; +exports.readStringContents = readStringContents; +var _isDigit = function isDigit(code) { + return code >= 48 && code <= 57; +}; +const forbiddenNumericSeparatorSiblings = { + decBinOct: new Set([46, 66, 69, 79, 95, 98, 101, 111]), + hex: new Set([46, 88, 95, 120]) +}; +const isAllowedNumericSeparatorSibling = { + bin: ch => ch === 48 || ch === 49, + oct: ch => ch >= 48 && ch <= 55, + dec: ch => ch >= 48 && ch <= 57, + hex: ch => ch >= 48 && ch <= 57 || ch >= 65 && ch <= 70 || ch >= 97 && ch <= 102 +}; +function readStringContents(type, input, pos, lineStart, curLine, errors) { + const initialPos = pos; + const initialLineStart = lineStart; + const initialCurLine = curLine; + let out = ""; + let firstInvalidLoc = null; + let chunkStart = pos; + const { + length + } = input; + for (;;) { + if (pos >= length) { + errors.unterminated(initialPos, initialLineStart, initialCurLine); + out += input.slice(chunkStart, pos); + break; + } + const ch = input.charCodeAt(pos); + if (isStringEnd(type, ch, input, pos)) { + out += input.slice(chunkStart, pos); + break; + } + if (ch === 92) { + out += input.slice(chunkStart, pos); + const res = readEscapedChar(input, pos, lineStart, curLine, type === "template", errors); + if (res.ch === null && !firstInvalidLoc) { + firstInvalidLoc = { + pos, + lineStart, + curLine + }; + } else { + out += res.ch; + } + ({ + pos, + lineStart, + curLine + } = res); + chunkStart = pos; + } else if (ch === 8232 || ch === 8233) { + ++pos; + ++curLine; + lineStart = pos; + } else if (ch === 10 || ch === 13) { + if (type === "template") { + out += input.slice(chunkStart, pos) + "\n"; + ++pos; + if (ch === 13 && input.charCodeAt(pos) === 10) { + ++pos; + } + ++curLine; + chunkStart = lineStart = pos; + } else { + errors.unterminated(initialPos, initialLineStart, initialCurLine); + } + } else { + ++pos; + } + } + return { + pos, + str: out, + firstInvalidLoc, + lineStart, + curLine, + containsInvalid: !!firstInvalidLoc + }; +} +function isStringEnd(type, ch, input, pos) { + if (type === "template") { + return ch === 96 || ch === 36 && input.charCodeAt(pos + 1) === 123; + } + return ch === (type === "double" ? 34 : 39); +} +function readEscapedChar(input, pos, lineStart, curLine, inTemplate, errors) { + const throwOnInvalid = !inTemplate; + pos++; + const res = ch => ({ + pos, + ch, + lineStart, + curLine + }); + const ch = input.charCodeAt(pos++); + switch (ch) { + case 110: + return res("\n"); + case 114: + return res("\r"); + case 120: + { + let code; + ({ + code, + pos + } = readHexChar(input, pos, lineStart, curLine, 2, false, throwOnInvalid, errors)); + return res(code === null ? null : String.fromCharCode(code)); + } + case 117: + { + let code; + ({ + code, + pos + } = readCodePoint(input, pos, lineStart, curLine, throwOnInvalid, errors)); + return res(code === null ? null : String.fromCodePoint(code)); + } + case 116: + return res("\t"); + case 98: + return res("\b"); + case 118: + return res("\u000b"); + case 102: + return res("\f"); + case 13: + if (input.charCodeAt(pos) === 10) { + ++pos; + } + case 10: + lineStart = pos; + ++curLine; + case 8232: + case 8233: + return res(""); + case 56: + case 57: + if (inTemplate) { + return res(null); + } else { + errors.strictNumericEscape(pos - 1, lineStart, curLine); + } + default: + if (ch >= 48 && ch <= 55) { + const startPos = pos - 1; + const match = /^[0-7]+/.exec(input.slice(startPos, pos + 2)); + let octalStr = match[0]; + let octal = parseInt(octalStr, 8); + if (octal > 255) { + octalStr = octalStr.slice(0, -1); + octal = parseInt(octalStr, 8); + } + pos += octalStr.length - 1; + const next = input.charCodeAt(pos); + if (octalStr !== "0" || next === 56 || next === 57) { + if (inTemplate) { + return res(null); + } else { + errors.strictNumericEscape(startPos, lineStart, curLine); + } + } + return res(String.fromCharCode(octal)); + } + return res(String.fromCharCode(ch)); + } +} +function readHexChar(input, pos, lineStart, curLine, len, forceLen, throwOnInvalid, errors) { + const initialPos = pos; + let n; + ({ + n, + pos + } = readInt(input, pos, lineStart, curLine, 16, len, forceLen, false, errors, !throwOnInvalid)); + if (n === null) { + if (throwOnInvalid) { + errors.invalidEscapeSequence(initialPos, lineStart, curLine); + } else { + pos = initialPos - 1; + } + } + return { + code: n, + pos + }; +} +function readInt(input, pos, lineStart, curLine, radix, len, forceLen, allowNumSeparator, errors, bailOnError) { + const start = pos; + const forbiddenSiblings = radix === 16 ? forbiddenNumericSeparatorSiblings.hex : forbiddenNumericSeparatorSiblings.decBinOct; + const isAllowedSibling = radix === 16 ? isAllowedNumericSeparatorSibling.hex : radix === 10 ? isAllowedNumericSeparatorSibling.dec : radix === 8 ? isAllowedNumericSeparatorSibling.oct : isAllowedNumericSeparatorSibling.bin; + let invalid = false; + let total = 0; + for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) { + const code = input.charCodeAt(pos); + let val; + if (code === 95 && allowNumSeparator !== "bail") { + const prev = input.charCodeAt(pos - 1); + const next = input.charCodeAt(pos + 1); + if (!allowNumSeparator) { + if (bailOnError) return { + n: null, + pos + }; + errors.numericSeparatorInEscapeSequence(pos, lineStart, curLine); + } else if (Number.isNaN(next) || !isAllowedSibling(next) || forbiddenSiblings.has(prev) || forbiddenSiblings.has(next)) { + if (bailOnError) return { + n: null, + pos + }; + errors.unexpectedNumericSeparator(pos, lineStart, curLine); + } + ++pos; + continue; + } + if (code >= 97) { + val = code - 97 + 10; + } else if (code >= 65) { + val = code - 65 + 10; + } else if (_isDigit(code)) { + val = code - 48; + } else { + val = Infinity; + } + if (val >= radix) { + if (val <= 9 && bailOnError) { + return { + n: null, + pos + }; + } else if (val <= 9 && errors.invalidDigit(pos, lineStart, curLine, radix)) { + val = 0; + } else if (forceLen) { + val = 0; + invalid = true; + } else { + break; + } + } + ++pos; + total = total * radix + val; + } + if (pos === start || len != null && pos - start !== len || invalid) { + return { + n: null, + pos + }; + } + return { + n: total, + pos + }; +} +function readCodePoint(input, pos, lineStart, curLine, throwOnInvalid, errors) { + const ch = input.charCodeAt(pos); + let code; + if (ch === 123) { + ++pos; + ({ + code, + pos + } = readHexChar(input, pos, lineStart, curLine, input.indexOf("}", pos) - pos, true, throwOnInvalid, errors)); + ++pos; + if (code !== null && code > 0x10ffff) { + if (throwOnInvalid) { + errors.invalidCodePoint(pos, lineStart, curLine); + } else { + return { + code: null, + pos + }; + } + } + } else { + ({ + code, + pos + } = readHexChar(input, pos, lineStart, curLine, 4, false, throwOnInvalid, errors)); + } + return { + code, + pos + }; +} + +//# sourceMappingURL=index.js.map diff --git a/libcore/node_modules/@babel/helper-string-parser/lib/index.js.map b/libcore/node_modules/@babel/helper-string-parser/lib/index.js.map new file mode 100644 index 0000000..cd50797 --- /dev/null +++ b/libcore/node_modules/@babel/helper-string-parser/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"names":["isDigit","code","forbiddenNumericSeparatorSiblings","decBinOct","Set","hex","isAllowedNumericSeparatorSibling","bin","ch","oct","dec","readStringContents","type","input","pos","lineStart","curLine","errors","initialPos","initialLineStart","initialCurLine","out","firstInvalidLoc","chunkStart","length","unterminated","slice","charCodeAt","isStringEnd","res","readEscapedChar","str","containsInvalid","inTemplate","throwOnInvalid","readHexChar","String","fromCharCode","readCodePoint","fromCodePoint","strictNumericEscape","startPos","match","exec","octalStr","octal","parseInt","next","len","forceLen","n","readInt","invalidEscapeSequence","radix","allowNumSeparator","bailOnError","start","forbiddenSiblings","isAllowedSibling","invalid","total","i","e","Infinity","val","prev","numericSeparatorInEscapeSequence","Number","isNaN","has","unexpectedNumericSeparator","_isDigit","invalidDigit","indexOf","invalidCodePoint"],"sources":["../src/index.ts"],"sourcesContent":["// We inline this package\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport * as charCodes from \"charcodes\";\n\n// The following character codes are forbidden from being\n// an immediate sibling of NumericLiteralSeparator _\nconst forbiddenNumericSeparatorSiblings = {\n decBinOct: new Set([\n charCodes.dot,\n charCodes.uppercaseB,\n charCodes.uppercaseE,\n charCodes.uppercaseO,\n charCodes.underscore, // multiple separators are not allowed\n charCodes.lowercaseB,\n charCodes.lowercaseE,\n charCodes.lowercaseO,\n ]),\n hex: new Set([\n charCodes.dot,\n charCodes.uppercaseX,\n charCodes.underscore, // multiple separators are not allowed\n charCodes.lowercaseX,\n ]),\n};\n\nconst isAllowedNumericSeparatorSibling = {\n // 0 - 1\n bin: (ch: number) => ch === charCodes.digit0 || ch === charCodes.digit1,\n\n // 0 - 7\n oct: (ch: number) => ch >= charCodes.digit0 && ch <= charCodes.digit7,\n\n // 0 - 9\n dec: (ch: number) => ch >= charCodes.digit0 && ch <= charCodes.digit9,\n\n // 0 - 9, A - F, a - f,\n hex: (ch: number) =>\n (ch >= charCodes.digit0 && ch <= charCodes.digit9) ||\n (ch >= charCodes.uppercaseA && ch <= charCodes.uppercaseF) ||\n (ch >= charCodes.lowercaseA && ch <= charCodes.lowercaseF),\n};\n\nexport type StringContentsErrorHandlers = EscapedCharErrorHandlers & {\n unterminated(\n initialPos: number,\n initialLineStart: number,\n initialCurLine: number,\n ): void;\n};\n\nexport function readStringContents(\n type: \"single\" | \"double\" | \"template\",\n input: string,\n pos: number,\n lineStart: number,\n curLine: number,\n errors: StringContentsErrorHandlers,\n) {\n const initialPos = pos;\n const initialLineStart = lineStart;\n const initialCurLine = curLine;\n\n let out = \"\";\n let firstInvalidLoc = null;\n let chunkStart = pos;\n const { length } = input;\n for (;;) {\n if (pos >= length) {\n errors.unterminated(initialPos, initialLineStart, initialCurLine);\n out += input.slice(chunkStart, pos);\n break;\n }\n const ch = input.charCodeAt(pos);\n if (isStringEnd(type, ch, input, pos)) {\n out += input.slice(chunkStart, pos);\n break;\n }\n if (ch === charCodes.backslash) {\n out += input.slice(chunkStart, pos);\n const res = readEscapedChar(\n input,\n pos,\n lineStart,\n curLine,\n type === \"template\",\n errors,\n );\n if (res.ch === null && !firstInvalidLoc) {\n firstInvalidLoc = { pos, lineStart, curLine };\n } else {\n out += res.ch;\n }\n ({ pos, lineStart, curLine } = res);\n chunkStart = pos;\n } else if (\n ch === charCodes.lineSeparator ||\n ch === charCodes.paragraphSeparator\n ) {\n ++pos;\n ++curLine;\n lineStart = pos;\n } else if (ch === charCodes.lineFeed || ch === charCodes.carriageReturn) {\n if (type === \"template\") {\n out += input.slice(chunkStart, pos) + \"\\n\";\n ++pos;\n if (\n ch === charCodes.carriageReturn &&\n input.charCodeAt(pos) === charCodes.lineFeed\n ) {\n ++pos;\n }\n ++curLine;\n chunkStart = lineStart = pos;\n } else {\n errors.unterminated(initialPos, initialLineStart, initialCurLine);\n }\n } else {\n ++pos;\n }\n }\n return process.env.BABEL_8_BREAKING\n ? { pos, str: out, firstInvalidLoc, lineStart, curLine }\n : {\n pos,\n str: out,\n firstInvalidLoc,\n lineStart,\n curLine,\n containsInvalid: !!firstInvalidLoc,\n };\n}\n\nfunction isStringEnd(\n type: \"single\" | \"double\" | \"template\",\n ch: number,\n input: string,\n pos: number,\n) {\n if (type === \"template\") {\n return (\n ch === charCodes.graveAccent ||\n (ch === charCodes.dollarSign &&\n input.charCodeAt(pos + 1) === charCodes.leftCurlyBrace)\n );\n }\n return (\n ch === (type === \"double\" ? charCodes.quotationMark : charCodes.apostrophe)\n );\n}\n\ntype EscapedCharErrorHandlers = HexCharErrorHandlers &\n CodePointErrorHandlers & {\n strictNumericEscape(pos: number, lineStart: number, curLine: number): void;\n };\n\nfunction readEscapedChar(\n input: string,\n pos: number,\n lineStart: number,\n curLine: number,\n inTemplate: boolean,\n errors: EscapedCharErrorHandlers,\n) {\n const throwOnInvalid = !inTemplate;\n pos++; // skip '\\'\n\n const res = (ch: string | null) => ({ pos, ch, lineStart, curLine });\n\n const ch = input.charCodeAt(pos++);\n switch (ch) {\n case charCodes.lowercaseN:\n return res(\"\\n\");\n case charCodes.lowercaseR:\n return res(\"\\r\");\n case charCodes.lowercaseX: {\n let code;\n ({ code, pos } = readHexChar(\n input,\n pos,\n lineStart,\n curLine,\n 2,\n false,\n throwOnInvalid,\n errors,\n ));\n return res(code === null ? null : String.fromCharCode(code));\n }\n case charCodes.lowercaseU: {\n let code;\n ({ code, pos } = readCodePoint(\n input,\n pos,\n lineStart,\n curLine,\n throwOnInvalid,\n errors,\n ));\n return res(code === null ? null : String.fromCodePoint(code));\n }\n case charCodes.lowercaseT:\n return res(\"\\t\");\n case charCodes.lowercaseB:\n return res(\"\\b\");\n case charCodes.lowercaseV:\n return res(\"\\u000b\");\n case charCodes.lowercaseF:\n return res(\"\\f\");\n case charCodes.carriageReturn:\n if (input.charCodeAt(pos) === charCodes.lineFeed) {\n ++pos;\n }\n // fall through\n case charCodes.lineFeed:\n lineStart = pos;\n ++curLine;\n // fall through\n case charCodes.lineSeparator:\n case charCodes.paragraphSeparator:\n return res(\"\");\n case charCodes.digit8:\n case charCodes.digit9:\n if (inTemplate) {\n return res(null);\n } else {\n errors.strictNumericEscape(pos - 1, lineStart, curLine);\n }\n // fall through\n default:\n if (ch >= charCodes.digit0 && ch <= charCodes.digit7) {\n const startPos = pos - 1;\n const match = /^[0-7]+/.exec(input.slice(startPos, pos + 2));\n\n let octalStr = match[0];\n\n let octal = parseInt(octalStr, 8);\n if (octal > 255) {\n octalStr = octalStr.slice(0, -1);\n octal = parseInt(octalStr, 8);\n }\n pos += octalStr.length - 1;\n const next = input.charCodeAt(pos);\n if (\n octalStr !== \"0\" ||\n next === charCodes.digit8 ||\n next === charCodes.digit9\n ) {\n if (inTemplate) {\n return res(null);\n } else {\n errors.strictNumericEscape(startPos, lineStart, curLine);\n }\n }\n\n return res(String.fromCharCode(octal));\n }\n\n return res(String.fromCharCode(ch));\n }\n}\n\ntype HexCharErrorHandlers = IntErrorHandlers & {\n invalidEscapeSequence(pos: number, lineStart: number, curLine: number): void;\n};\n\n// Used to read character escape sequences ('\\x', '\\u').\nfunction readHexChar(\n input: string,\n pos: number,\n lineStart: number,\n curLine: number,\n len: number,\n forceLen: boolean,\n throwOnInvalid: boolean,\n errors: HexCharErrorHandlers,\n) {\n const initialPos = pos;\n let n;\n ({ n, pos } = readInt(\n input,\n pos,\n lineStart,\n curLine,\n 16,\n len,\n forceLen,\n false,\n errors,\n /* bailOnError */ !throwOnInvalid,\n ));\n if (n === null) {\n if (throwOnInvalid) {\n errors.invalidEscapeSequence(initialPos, lineStart, curLine);\n } else {\n pos = initialPos - 1;\n }\n }\n return { code: n, pos };\n}\n\nexport type IntErrorHandlers = {\n numericSeparatorInEscapeSequence(\n pos: number,\n lineStart: number,\n curLine: number,\n ): void;\n unexpectedNumericSeparator(\n pos: number,\n lineStart: number,\n curLine: number,\n ): void;\n // It can return \"true\" to indicate that the error was handled\n // and the int parsing should continue.\n invalidDigit(\n pos: number,\n lineStart: number,\n curLine: number,\n radix: number,\n ): boolean;\n};\n\nexport function readInt(\n input: string,\n pos: number,\n lineStart: number,\n curLine: number,\n radix: number,\n len: number | undefined,\n forceLen: boolean,\n allowNumSeparator: boolean | \"bail\",\n errors: IntErrorHandlers,\n bailOnError: boolean,\n) {\n const start = pos;\n const forbiddenSiblings =\n radix === 16\n ? forbiddenNumericSeparatorSiblings.hex\n : forbiddenNumericSeparatorSiblings.decBinOct;\n const isAllowedSibling =\n radix === 16\n ? isAllowedNumericSeparatorSibling.hex\n : radix === 10\n ? isAllowedNumericSeparatorSibling.dec\n : radix === 8\n ? isAllowedNumericSeparatorSibling.oct\n : isAllowedNumericSeparatorSibling.bin;\n\n let invalid = false;\n let total = 0;\n\n for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) {\n const code = input.charCodeAt(pos);\n let val;\n\n if (code === charCodes.underscore && allowNumSeparator !== \"bail\") {\n const prev = input.charCodeAt(pos - 1);\n const next = input.charCodeAt(pos + 1);\n\n if (!allowNumSeparator) {\n if (bailOnError) return { n: null, pos };\n errors.numericSeparatorInEscapeSequence(pos, lineStart, curLine);\n } else if (\n Number.isNaN(next) ||\n !isAllowedSibling(next) ||\n forbiddenSiblings.has(prev) ||\n forbiddenSiblings.has(next)\n ) {\n if (bailOnError) return { n: null, pos };\n errors.unexpectedNumericSeparator(pos, lineStart, curLine);\n }\n\n // Ignore this _ character\n ++pos;\n continue;\n }\n\n if (code >= charCodes.lowercaseA) {\n val = code - charCodes.lowercaseA + charCodes.lineFeed;\n } else if (code >= charCodes.uppercaseA) {\n val = code - charCodes.uppercaseA + charCodes.lineFeed;\n } else if (charCodes.isDigit(code)) {\n val = code - charCodes.digit0; // 0-9\n } else {\n val = Infinity;\n }\n if (val >= radix) {\n // If we found a digit which is too big, errors.invalidDigit can return true to avoid\n // breaking the loop (this is used for error recovery).\n if (val <= 9 && bailOnError) {\n return { n: null, pos };\n } else if (\n val <= 9 &&\n errors.invalidDigit(pos, lineStart, curLine, radix)\n ) {\n val = 0;\n } else if (forceLen) {\n val = 0;\n invalid = true;\n } else {\n break;\n }\n }\n ++pos;\n total = total * radix + val;\n }\n if (pos === start || (len != null && pos - start !== len) || invalid) {\n return { n: null, pos };\n }\n\n return { n: total, pos };\n}\n\nexport type CodePointErrorHandlers = HexCharErrorHandlers & {\n invalidCodePoint(pos: number, lineStart: number, curLine: number): void;\n};\n\nexport function readCodePoint(\n input: string,\n pos: number,\n lineStart: number,\n curLine: number,\n throwOnInvalid: boolean,\n errors: CodePointErrorHandlers,\n) {\n const ch = input.charCodeAt(pos);\n let code;\n\n if (ch === charCodes.leftCurlyBrace) {\n ++pos;\n ({ code, pos } = readHexChar(\n input,\n pos,\n lineStart,\n curLine,\n input.indexOf(\"}\", pos) - pos,\n true,\n throwOnInvalid,\n errors,\n ));\n ++pos;\n if (code !== null && code > 0x10ffff) {\n if (throwOnInvalid) {\n errors.invalidCodePoint(pos, lineStart, curLine);\n } else {\n return { code: null, pos };\n }\n }\n } else {\n ({ code, pos } = readHexChar(\n input,\n pos,\n lineStart,\n curLine,\n 4,\n false,\n throwOnInvalid,\n errors,\n ));\n }\n return { code, pos };\n}\n"],"mappings":";;;;;;;;eAAA,SAASA,OAAOA,CAACC,IAAI,EAAE;EACrB,OAAOA,IAAI,MAAU,IAAIA,IAAI,MAAU;AACzC,CAAC;AAID,MAAMC,iCAAiC,GAAG;EACxCC,SAAS,EAAE,IAAIC,GAAG,CAAS,kCAS1B,CAAC;EACFC,GAAG,EAAE,IAAID,GAAG,CAAS,iBAKpB;AACH,CAAC;AAED,MAAME,gCAAgC,GAAG;EAEvCC,GAAG,EAAGC,EAAU,IAAKA,EAAE,OAAqB,IAAIA,EAAE,OAAqB;EAGvEC,GAAG,EAAGD,EAAU,IAAKA,EAAE,MAAoB,IAAIA,EAAE,MAAoB;EAGrEE,GAAG,EAAGF,EAAU,IAAKA,EAAE,MAAoB,IAAIA,EAAE,MAAoB;EAGrEH,GAAG,EAAGG,EAAU,IACbA,EAAE,MAAoB,IAAIA,EAAE,MAAoB,IAChDA,EAAE,MAAwB,IAAIA,EAAE,MAAyB,IACzDA,EAAE,MAAwB,IAAIA,EAAE;AACrC,CAAC;AAUM,SAASG,kBAAkBA,CAChCC,IAAsC,EACtCC,KAAa,EACbC,GAAW,EACXC,SAAiB,EACjBC,OAAe,EACfC,MAAmC,EACnC;EACA,MAAMC,UAAU,GAAGJ,GAAG;EACtB,MAAMK,gBAAgB,GAAGJ,SAAS;EAClC,MAAMK,cAAc,GAAGJ,OAAO;EAE9B,IAAIK,GAAG,GAAG,EAAE;EACZ,IAAIC,eAAe,GAAG,IAAI;EAC1B,IAAIC,UAAU,GAAGT,GAAG;EACpB,MAAM;IAAEU;EAAO,CAAC,GAAGX,KAAK;EACxB,SAAS;IACP,IAAIC,GAAG,IAAIU,MAAM,EAAE;MACjBP,MAAM,CAACQ,YAAY,CAACP,UAAU,EAAEC,gBAAgB,EAAEC,cAAc,CAAC;MACjEC,GAAG,IAAIR,KAAK,CAACa,KAAK,CAACH,UAAU,EAAET,GAAG,CAAC;MACnC;IACF;IACA,MAAMN,EAAE,GAAGK,KAAK,CAACc,UAAU,CAACb,GAAG,CAAC;IAChC,IAAIc,WAAW,CAAChB,IAAI,EAAEJ,EAAE,EAAEK,KAAK,EAAEC,GAAG,CAAC,EAAE;MACrCO,GAAG,IAAIR,KAAK,CAACa,KAAK,CAACH,UAAU,EAAET,GAAG,CAAC;MACnC;IACF;IACA,IAAIN,EAAE,OAAwB,EAAE;MAC9Ba,GAAG,IAAIR,KAAK,CAACa,KAAK,CAACH,UAAU,EAAET,GAAG,CAAC;MACnC,MAAMe,GAAG,GAAGC,eAAe,CACzBjB,KAAK,EACLC,GAAG,EACHC,SAAS,EACTC,OAAO,EACPJ,IAAI,KAAK,UAAU,EACnBK,MACF,CAAC;MACD,IAAIY,GAAG,CAACrB,EAAE,KAAK,IAAI,IAAI,CAACc,eAAe,EAAE;QACvCA,eAAe,GAAG;UAAER,GAAG;UAAEC,SAAS;UAAEC;QAAQ,CAAC;MAC/C,CAAC,MAAM;QACLK,GAAG,IAAIQ,GAAG,CAACrB,EAAE;MACf;MACA,CAAC;QAAEM,GAAG;QAAEC,SAAS;QAAEC;MAAQ,CAAC,GAAGa,GAAG;MAClCN,UAAU,GAAGT,GAAG;IAClB,CAAC,MAAM,IACLN,EAAE,SAA4B,IAC9BA,EAAE,SAAiC,EACnC;MACA,EAAEM,GAAG;MACL,EAAEE,OAAO;MACTD,SAAS,GAAGD,GAAG;IACjB,CAAC,MAAM,IAAIN,EAAE,OAAuB,IAAIA,EAAE,OAA6B,EAAE;MACvE,IAAII,IAAI,KAAK,UAAU,EAAE;QACvBS,GAAG,IAAIR,KAAK,CAACa,KAAK,CAACH,UAAU,EAAET,GAAG,CAAC,GAAG,IAAI;QAC1C,EAAEA,GAAG;QACL,IACEN,EAAE,OAA6B,IAC/BK,KAAK,CAACc,UAAU,CAACb,GAAG,CAAC,OAAuB,EAC5C;UACA,EAAEA,GAAG;QACP;QACA,EAAEE,OAAO;QACTO,UAAU,GAAGR,SAAS,GAAGD,GAAG;MAC9B,CAAC,MAAM;QACLG,MAAM,CAACQ,YAAY,CAACP,UAAU,EAAEC,gBAAgB,EAAEC,cAAc,CAAC;MACnE;IACF,CAAC,MAAM;MACL,EAAEN,GAAG;IACP;EACF;EACA,OAEI;IACEA,GAAG;IACHiB,GAAG,EAAEV,GAAG;IACRC,eAAe;IACfP,SAAS;IACTC,OAAO;IACPgB,eAAe,EAAE,CAAC,CAACV;EACrB,CAAC;AACP;AAEA,SAASM,WAAWA,CAClBhB,IAAsC,EACtCJ,EAAU,EACVK,KAAa,EACbC,GAAW,EACX;EACA,IAAIF,IAAI,KAAK,UAAU,EAAE;IACvB,OACEJ,EAAE,OAA0B,IAC3BA,EAAE,OAAyB,IAC1BK,KAAK,CAACc,UAAU,CAACb,GAAG,GAAG,CAAC,CAAC,QAA8B;EAE7D;EACA,OACEN,EAAE,MAAMI,IAAI,KAAK,QAAQ,UAAiD,CAAC;AAE/E;AAOA,SAASkB,eAAeA,CACtBjB,KAAa,EACbC,GAAW,EACXC,SAAiB,EACjBC,OAAe,EACfiB,UAAmB,EACnBhB,MAAgC,EAChC;EACA,MAAMiB,cAAc,GAAG,CAACD,UAAU;EAClCnB,GAAG,EAAE;EAEL,MAAMe,GAAG,GAAIrB,EAAiB,KAAM;IAAEM,GAAG;IAAEN,EAAE;IAAEO,SAAS;IAAEC;EAAQ,CAAC,CAAC;EAEpE,MAAMR,EAAE,GAAGK,KAAK,CAACc,UAAU,CAACb,GAAG,EAAE,CAAC;EAClC,QAAQN,EAAE;IACR;MACE,OAAOqB,GAAG,CAAC,IAAI,CAAC;IAClB;MACE,OAAOA,GAAG,CAAC,IAAI,CAAC;IAClB;MAA2B;QACzB,IAAI5B,IAAI;QACR,CAAC;UAAEA,IAAI;UAAEa;QAAI,CAAC,GAAGqB,WAAW,CAC1BtB,KAAK,EACLC,GAAG,EACHC,SAAS,EACTC,OAAO,EACP,CAAC,EACD,KAAK,EACLkB,cAAc,EACdjB,MACF,CAAC;QACD,OAAOY,GAAG,CAAC5B,IAAI,KAAK,IAAI,GAAG,IAAI,GAAGmC,MAAM,CAACC,YAAY,CAACpC,IAAI,CAAC,CAAC;MAC9D;IACA;MAA2B;QACzB,IAAIA,IAAI;QACR,CAAC;UAAEA,IAAI;UAAEa;QAAI,CAAC,GAAGwB,aAAa,CAC5BzB,KAAK,EACLC,GAAG,EACHC,SAAS,EACTC,OAAO,EACPkB,cAAc,EACdjB,MACF,CAAC;QACD,OAAOY,GAAG,CAAC5B,IAAI,KAAK,IAAI,GAAG,IAAI,GAAGmC,MAAM,CAACG,aAAa,CAACtC,IAAI,CAAC,CAAC;MAC/D;IACA;MACE,OAAO4B,GAAG,CAAC,IAAI,CAAC;IAClB;MACE,OAAOA,GAAG,CAAC,IAAI,CAAC;IAClB;MACE,OAAOA,GAAG,CAAC,QAAQ,CAAC;IACtB;MACE,OAAOA,GAAG,CAAC,IAAI,CAAC;IAClB;MACE,IAAIhB,KAAK,CAACc,UAAU,CAACb,GAAG,CAAC,OAAuB,EAAE;QAChD,EAAEA,GAAG;MACP;IAEF;MACEC,SAAS,GAAGD,GAAG;MACf,EAAEE,OAAO;IAEX;IACA;MACE,OAAOa,GAAG,CAAC,EAAE,CAAC;IAChB;IACA;MACE,IAAII,UAAU,EAAE;QACd,OAAOJ,GAAG,CAAC,IAAI,CAAC;MAClB,CAAC,MAAM;QACLZ,MAAM,CAACuB,mBAAmB,CAAC1B,GAAG,GAAG,CAAC,EAAEC,SAAS,EAAEC,OAAO,CAAC;MACzD;IAEF;MACE,IAAIR,EAAE,MAAoB,IAAIA,EAAE,MAAoB,EAAE;QACpD,MAAMiC,QAAQ,GAAG3B,GAAG,GAAG,CAAC;QACxB,MAAM4B,KAAK,GAAG,SAAS,CAACC,IAAI,CAAC9B,KAAK,CAACa,KAAK,CAACe,QAAQ,EAAE3B,GAAG,GAAG,CAAC,CAAC,CAAC;QAE5D,IAAI8B,QAAQ,GAAGF,KAAK,CAAC,CAAC,CAAC;QAEvB,IAAIG,KAAK,GAAGC,QAAQ,CAACF,QAAQ,EAAE,CAAC,CAAC;QACjC,IAAIC,KAAK,GAAG,GAAG,EAAE;UACfD,QAAQ,GAAGA,QAAQ,CAAClB,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;UAChCmB,KAAK,GAAGC,QAAQ,CAACF,QAAQ,EAAE,CAAC,CAAC;QAC/B;QACA9B,GAAG,IAAI8B,QAAQ,CAACpB,MAAM,GAAG,CAAC;QAC1B,MAAMuB,IAAI,GAAGlC,KAAK,CAACc,UAAU,CAACb,GAAG,CAAC;QAClC,IACE8B,QAAQ,KAAK,GAAG,IAChBG,IAAI,OAAqB,IACzBA,IAAI,OAAqB,EACzB;UACA,IAAId,UAAU,EAAE;YACd,OAAOJ,GAAG,CAAC,IAAI,CAAC;UAClB,CAAC,MAAM;YACLZ,MAAM,CAACuB,mBAAmB,CAACC,QAAQ,EAAE1B,SAAS,EAAEC,OAAO,CAAC;UAC1D;QACF;QAEA,OAAOa,GAAG,CAACO,MAAM,CAACC,YAAY,CAACQ,KAAK,CAAC,CAAC;MACxC;MAEA,OAAOhB,GAAG,CAACO,MAAM,CAACC,YAAY,CAAC7B,EAAE,CAAC,CAAC;EACvC;AACF;AAOA,SAAS2B,WAAWA,CAClBtB,KAAa,EACbC,GAAW,EACXC,SAAiB,EACjBC,OAAe,EACfgC,GAAW,EACXC,QAAiB,EACjBf,cAAuB,EACvBjB,MAA4B,EAC5B;EACA,MAAMC,UAAU,GAAGJ,GAAG;EACtB,IAAIoC,CAAC;EACL,CAAC;IAAEA,CAAC;IAAEpC;EAAI,CAAC,GAAGqC,OAAO,CACnBtC,KAAK,EACLC,GAAG,EACHC,SAAS,EACTC,OAAO,EACP,EAAE,EACFgC,GAAG,EACHC,QAAQ,EACR,KAAK,EACLhC,MAAM,EACY,CAACiB,cACrB,CAAC;EACD,IAAIgB,CAAC,KAAK,IAAI,EAAE;IACd,IAAIhB,cAAc,EAAE;MAClBjB,MAAM,CAACmC,qBAAqB,CAAClC,UAAU,EAAEH,SAAS,EAAEC,OAAO,CAAC;IAC9D,CAAC,MAAM;MACLF,GAAG,GAAGI,UAAU,GAAG,CAAC;IACtB;EACF;EACA,OAAO;IAAEjB,IAAI,EAAEiD,CAAC;IAAEpC;EAAI,CAAC;AACzB;AAuBO,SAASqC,OAAOA,CACrBtC,KAAa,EACbC,GAAW,EACXC,SAAiB,EACjBC,OAAe,EACfqC,KAAa,EACbL,GAAuB,EACvBC,QAAiB,EACjBK,iBAAmC,EACnCrC,MAAwB,EACxBsC,WAAoB,EACpB;EACA,MAAMC,KAAK,GAAG1C,GAAG;EACjB,MAAM2C,iBAAiB,GACrBJ,KAAK,KAAK,EAAE,GACRnD,iCAAiC,CAACG,GAAG,GACrCH,iCAAiC,CAACC,SAAS;EACjD,MAAMuD,gBAAgB,GACpBL,KAAK,KAAK,EAAE,GACR/C,gCAAgC,CAACD,GAAG,GACpCgD,KAAK,KAAK,EAAE,GACV/C,gCAAgC,CAACI,GAAG,GACpC2C,KAAK,KAAK,CAAC,GACT/C,gCAAgC,CAACG,GAAG,GACpCH,gCAAgC,CAACC,GAAG;EAE9C,IAAIoD,OAAO,GAAG,KAAK;EACnB,IAAIC,KAAK,GAAG,CAAC;EAEb,KAAK,IAAIC,CAAC,GAAG,CAAC,EAAEC,CAAC,GAAGd,GAAG,IAAI,IAAI,GAAGe,QAAQ,GAAGf,GAAG,EAAEa,CAAC,GAAGC,CAAC,EAAE,EAAED,CAAC,EAAE;IAC5D,MAAM5D,IAAI,GAAGY,KAAK,CAACc,UAAU,CAACb,GAAG,CAAC;IAClC,IAAIkD,GAAG;IAEP,IAAI/D,IAAI,OAAyB,IAAIqD,iBAAiB,KAAK,MAAM,EAAE;MACjE,MAAMW,IAAI,GAAGpD,KAAK,CAACc,UAAU,CAACb,GAAG,GAAG,CAAC,CAAC;MACtC,MAAMiC,IAAI,GAAGlC,KAAK,CAACc,UAAU,CAACb,GAAG,GAAG,CAAC,CAAC;MAEtC,IAAI,CAACwC,iBAAiB,EAAE;QACtB,IAAIC,WAAW,EAAE,OAAO;UAAEL,CAAC,EAAE,IAAI;UAAEpC;QAAI,CAAC;QACxCG,MAAM,CAACiD,gCAAgC,CAACpD,GAAG,EAAEC,SAAS,EAAEC,OAAO,CAAC;MAClE,CAAC,MAAM,IACLmD,MAAM,CAACC,KAAK,CAACrB,IAAI,CAAC,IAClB,CAACW,gBAAgB,CAACX,IAAI,CAAC,IACvBU,iBAAiB,CAACY,GAAG,CAACJ,IAAI,CAAC,IAC3BR,iBAAiB,CAACY,GAAG,CAACtB,IAAI,CAAC,EAC3B;QACA,IAAIQ,WAAW,EAAE,OAAO;UAAEL,CAAC,EAAE,IAAI;UAAEpC;QAAI,CAAC;QACxCG,MAAM,CAACqD,0BAA0B,CAACxD,GAAG,EAAEC,SAAS,EAAEC,OAAO,CAAC;MAC5D;MAGA,EAAEF,GAAG;MACL;IACF;IAEA,IAAIb,IAAI,MAAwB,EAAE;MAChC+D,GAAG,GAAG/D,IAAI,KAAuB,KAAqB;IACxD,CAAC,MAAM,IAAIA,IAAI,MAAwB,EAAE;MACvC+D,GAAG,GAAG/D,IAAI,KAAuB,KAAqB;IACxD,CAAC,MAAM,IAAIsE,QAAA,CAAkBtE,IAAI,CAAC,EAAE;MAClC+D,GAAG,GAAG/D,IAAI,KAAmB;IAC/B,CAAC,MAAM;MACL+D,GAAG,GAAGD,QAAQ;IAChB;IACA,IAAIC,GAAG,IAAIX,KAAK,EAAE;MAGhB,IAAIW,GAAG,IAAI,CAAC,IAAIT,WAAW,EAAE;QAC3B,OAAO;UAAEL,CAAC,EAAE,IAAI;UAAEpC;QAAI,CAAC;MACzB,CAAC,MAAM,IACLkD,GAAG,IAAI,CAAC,IACR/C,MAAM,CAACuD,YAAY,CAAC1D,GAAG,EAAEC,SAAS,EAAEC,OAAO,EAAEqC,KAAK,CAAC,EACnD;QACAW,GAAG,GAAG,CAAC;MACT,CAAC,MAAM,IAAIf,QAAQ,EAAE;QACnBe,GAAG,GAAG,CAAC;QACPL,OAAO,GAAG,IAAI;MAChB,CAAC,MAAM;QACL;MACF;IACF;IACA,EAAE7C,GAAG;IACL8C,KAAK,GAAGA,KAAK,GAAGP,KAAK,GAAGW,GAAG;EAC7B;EACA,IAAIlD,GAAG,KAAK0C,KAAK,IAAKR,GAAG,IAAI,IAAI,IAAIlC,GAAG,GAAG0C,KAAK,KAAKR,GAAI,IAAIW,OAAO,EAAE;IACpE,OAAO;MAAET,CAAC,EAAE,IAAI;MAAEpC;IAAI,CAAC;EACzB;EAEA,OAAO;IAAEoC,CAAC,EAAEU,KAAK;IAAE9C;EAAI,CAAC;AAC1B;AAMO,SAASwB,aAAaA,CAC3BzB,KAAa,EACbC,GAAW,EACXC,SAAiB,EACjBC,OAAe,EACfkB,cAAuB,EACvBjB,MAA8B,EAC9B;EACA,MAAMT,EAAE,GAAGK,KAAK,CAACc,UAAU,CAACb,GAAG,CAAC;EAChC,IAAIb,IAAI;EAER,IAAIO,EAAE,QAA6B,EAAE;IACnC,EAAEM,GAAG;IACL,CAAC;MAAEb,IAAI;MAAEa;IAAI,CAAC,GAAGqB,WAAW,CAC1BtB,KAAK,EACLC,GAAG,EACHC,SAAS,EACTC,OAAO,EACPH,KAAK,CAAC4D,OAAO,CAAC,GAAG,EAAE3D,GAAG,CAAC,GAAGA,GAAG,EAC7B,IAAI,EACJoB,cAAc,EACdjB,MACF,CAAC;IACD,EAAEH,GAAG;IACL,IAAIb,IAAI,KAAK,IAAI,IAAIA,IAAI,GAAG,QAAQ,EAAE;MACpC,IAAIiC,cAAc,EAAE;QAClBjB,MAAM,CAACyD,gBAAgB,CAAC5D,GAAG,EAAEC,SAAS,EAAEC,OAAO,CAAC;MAClD,CAAC,MAAM;QACL,OAAO;UAAEf,IAAI,EAAE,IAAI;UAAEa;QAAI,CAAC;MAC5B;IACF;EACF,CAAC,MAAM;IACL,CAAC;MAAEb,IAAI;MAAEa;IAAI,CAAC,GAAGqB,WAAW,CAC1BtB,KAAK,EACLC,GAAG,EACHC,SAAS,EACTC,OAAO,EACP,CAAC,EACD,KAAK,EACLkB,cAAc,EACdjB,MACF,CAAC;EACH;EACA,OAAO;IAAEhB,IAAI;IAAEa;EAAI,CAAC;AACtB","ignoreList":[]} \ No newline at end of file diff --git a/libcore/node_modules/@babel/helper-string-parser/package.json b/libcore/node_modules/@babel/helper-string-parser/package.json new file mode 100644 index 0000000..8c7e067 --- /dev/null +++ b/libcore/node_modules/@babel/helper-string-parser/package.json @@ -0,0 +1,31 @@ +{ + "name": "@babel/helper-string-parser", + "version": "7.24.8", + "description": "A utility package to parse strings", + "repository": { + "type": "git", + "url": "https://github.com/babel/babel.git", + "directory": "packages/babel-helper-string-parser" + }, + "homepage": "https://babel.dev/docs/en/next/babel-helper-string-parser", + "license": "MIT", + "publishConfig": { + "access": "public" + }, + "main": "./lib/index.js", + "devDependencies": { + "charcodes": "^0.2.0" + }, + "engines": { + "node": ">=6.9.0" + }, + "author": "The Babel Team (https://babel.dev/team)", + "exports": { + ".": { + "types": "./lib/index.d.ts", + "default": "./lib/index.js" + }, + "./package.json": "./package.json" + }, + "type": "commonjs" +} \ No newline at end of file diff --git a/libcore/node_modules/@babel/helper-validator-identifier/LICENSE b/libcore/node_modules/@babel/helper-validator-identifier/LICENSE new file mode 100644 index 0000000..f31575e --- /dev/null +++ b/libcore/node_modules/@babel/helper-validator-identifier/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +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. diff --git a/libcore/node_modules/@babel/helper-validator-identifier/README.md b/libcore/node_modules/@babel/helper-validator-identifier/README.md new file mode 100644 index 0000000..05c19e6 --- /dev/null +++ b/libcore/node_modules/@babel/helper-validator-identifier/README.md @@ -0,0 +1,19 @@ +# @babel/helper-validator-identifier + +> Validate identifier/keywords name + +See our website [@babel/helper-validator-identifier](https://babeljs.io/docs/babel-helper-validator-identifier) for more information. + +## Install + +Using npm: + +```sh +npm install --save @babel/helper-validator-identifier +``` + +or using yarn: + +```sh +yarn add @babel/helper-validator-identifier +``` diff --git a/libcore/node_modules/@babel/helper-validator-identifier/lib/identifier.js b/libcore/node_modules/@babel/helper-validator-identifier/lib/identifier.js new file mode 100644 index 0000000..8ef8303 --- /dev/null +++ b/libcore/node_modules/@babel/helper-validator-identifier/lib/identifier.js @@ -0,0 +1,70 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isIdentifierChar = isIdentifierChar; +exports.isIdentifierName = isIdentifierName; +exports.isIdentifierStart = isIdentifierStart; +let nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7ca\ua7d0\ua7d1\ua7d3\ua7d5-\ua7d9\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"; +let nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0898-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\u30fb\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f\uff65"; +const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); +const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); +nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; +const astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 68, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 4026, 582, 8634, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8936, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 757, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4153, 7, 221, 3, 5761, 15, 7472, 16, 621, 2467, 541, 1507, 4938, 6, 4191]; +const astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 81, 2, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 9, 5351, 0, 7, 14, 13835, 9, 87, 9, 39, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4706, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 983, 6, 110, 6, 6, 9, 4759, 9, 787719, 239]; +function isInAstralSet(code, set) { + let pos = 0x10000; + for (let i = 0, length = set.length; i < length; i += 2) { + pos += set[i]; + if (pos > code) return false; + pos += set[i + 1]; + if (pos >= code) return true; + } + return false; +} +function isIdentifierStart(code) { + if (code < 65) return code === 36; + if (code <= 90) return true; + if (code < 97) return code === 95; + if (code <= 122) return true; + if (code <= 0xffff) { + return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)); + } + return isInAstralSet(code, astralIdentifierStartCodes); +} +function isIdentifierChar(code) { + if (code < 48) return code === 36; + if (code < 58) return true; + if (code < 65) return false; + if (code <= 90) return true; + if (code < 97) return code === 95; + if (code <= 122) return true; + if (code <= 0xffff) { + return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)); + } + return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes); +} +function isIdentifierName(name) { + let isFirst = true; + for (let i = 0; i < name.length; i++) { + let cp = name.charCodeAt(i); + if ((cp & 0xfc00) === 0xd800 && i + 1 < name.length) { + const trail = name.charCodeAt(++i); + if ((trail & 0xfc00) === 0xdc00) { + cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff); + } + } + if (isFirst) { + isFirst = false; + if (!isIdentifierStart(cp)) { + return false; + } + } else if (!isIdentifierChar(cp)) { + return false; + } + } + return !isFirst; +} + +//# sourceMappingURL=identifier.js.map diff --git a/libcore/node_modules/@babel/helper-validator-identifier/lib/identifier.js.map b/libcore/node_modules/@babel/helper-validator-identifier/lib/identifier.js.map new file mode 100644 index 0000000..e2a9c30 --- /dev/null +++ b/libcore/node_modules/@babel/helper-validator-identifier/lib/identifier.js.map @@ -0,0 +1 @@ +{"version":3,"names":["nonASCIIidentifierStartChars","nonASCIIidentifierChars","nonASCIIidentifierStart","RegExp","nonASCIIidentifier","astralIdentifierStartCodes","astralIdentifierCodes","isInAstralSet","code","set","pos","i","length","isIdentifierStart","test","String","fromCharCode","isIdentifierChar","isIdentifierName","name","isFirst","cp","charCodeAt","trail"],"sources":["../src/identifier.ts"],"sourcesContent":["// We inline this package\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport * as charCodes from \"charcodes\";\n\n// ## Character categories\n\n// Big ugly regular expressions that match characters in the\n// whitespace, identifier, and identifier-start categories. These\n// are only applied when a character is found to actually have a\n// code point between 0x80 and 0xffff.\n// Generated by `scripts/generate-identifier-regex.js`.\n\n/* prettier-ignore */\nlet nonASCIIidentifierStartChars = \"\\xaa\\xb5\\xba\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\u02c1\\u02c6-\\u02d1\\u02e0-\\u02e4\\u02ec\\u02ee\\u0370-\\u0374\\u0376\\u0377\\u037a-\\u037d\\u037f\\u0386\\u0388-\\u038a\\u038c\\u038e-\\u03a1\\u03a3-\\u03f5\\u03f7-\\u0481\\u048a-\\u052f\\u0531-\\u0556\\u0559\\u0560-\\u0588\\u05d0-\\u05ea\\u05ef-\\u05f2\\u0620-\\u064a\\u066e\\u066f\\u0671-\\u06d3\\u06d5\\u06e5\\u06e6\\u06ee\\u06ef\\u06fa-\\u06fc\\u06ff\\u0710\\u0712-\\u072f\\u074d-\\u07a5\\u07b1\\u07ca-\\u07ea\\u07f4\\u07f5\\u07fa\\u0800-\\u0815\\u081a\\u0824\\u0828\\u0840-\\u0858\\u0860-\\u086a\\u0870-\\u0887\\u0889-\\u088e\\u08a0-\\u08c9\\u0904-\\u0939\\u093d\\u0950\\u0958-\\u0961\\u0971-\\u0980\\u0985-\\u098c\\u098f\\u0990\\u0993-\\u09a8\\u09aa-\\u09b0\\u09b2\\u09b6-\\u09b9\\u09bd\\u09ce\\u09dc\\u09dd\\u09df-\\u09e1\\u09f0\\u09f1\\u09fc\\u0a05-\\u0a0a\\u0a0f\\u0a10\\u0a13-\\u0a28\\u0a2a-\\u0a30\\u0a32\\u0a33\\u0a35\\u0a36\\u0a38\\u0a39\\u0a59-\\u0a5c\\u0a5e\\u0a72-\\u0a74\\u0a85-\\u0a8d\\u0a8f-\\u0a91\\u0a93-\\u0aa8\\u0aaa-\\u0ab0\\u0ab2\\u0ab3\\u0ab5-\\u0ab9\\u0abd\\u0ad0\\u0ae0\\u0ae1\\u0af9\\u0b05-\\u0b0c\\u0b0f\\u0b10\\u0b13-\\u0b28\\u0b2a-\\u0b30\\u0b32\\u0b33\\u0b35-\\u0b39\\u0b3d\\u0b5c\\u0b5d\\u0b5f-\\u0b61\\u0b71\\u0b83\\u0b85-\\u0b8a\\u0b8e-\\u0b90\\u0b92-\\u0b95\\u0b99\\u0b9a\\u0b9c\\u0b9e\\u0b9f\\u0ba3\\u0ba4\\u0ba8-\\u0baa\\u0bae-\\u0bb9\\u0bd0\\u0c05-\\u0c0c\\u0c0e-\\u0c10\\u0c12-\\u0c28\\u0c2a-\\u0c39\\u0c3d\\u0c58-\\u0c5a\\u0c5d\\u0c60\\u0c61\\u0c80\\u0c85-\\u0c8c\\u0c8e-\\u0c90\\u0c92-\\u0ca8\\u0caa-\\u0cb3\\u0cb5-\\u0cb9\\u0cbd\\u0cdd\\u0cde\\u0ce0\\u0ce1\\u0cf1\\u0cf2\\u0d04-\\u0d0c\\u0d0e-\\u0d10\\u0d12-\\u0d3a\\u0d3d\\u0d4e\\u0d54-\\u0d56\\u0d5f-\\u0d61\\u0d7a-\\u0d7f\\u0d85-\\u0d96\\u0d9a-\\u0db1\\u0db3-\\u0dbb\\u0dbd\\u0dc0-\\u0dc6\\u0e01-\\u0e30\\u0e32\\u0e33\\u0e40-\\u0e46\\u0e81\\u0e82\\u0e84\\u0e86-\\u0e8a\\u0e8c-\\u0ea3\\u0ea5\\u0ea7-\\u0eb0\\u0eb2\\u0eb3\\u0ebd\\u0ec0-\\u0ec4\\u0ec6\\u0edc-\\u0edf\\u0f00\\u0f40-\\u0f47\\u0f49-\\u0f6c\\u0f88-\\u0f8c\\u1000-\\u102a\\u103f\\u1050-\\u1055\\u105a-\\u105d\\u1061\\u1065\\u1066\\u106e-\\u1070\\u1075-\\u1081\\u108e\\u10a0-\\u10c5\\u10c7\\u10cd\\u10d0-\\u10fa\\u10fc-\\u1248\\u124a-\\u124d\\u1250-\\u1256\\u1258\\u125a-\\u125d\\u1260-\\u1288\\u128a-\\u128d\\u1290-\\u12b0\\u12b2-\\u12b5\\u12b8-\\u12be\\u12c0\\u12c2-\\u12c5\\u12c8-\\u12d6\\u12d8-\\u1310\\u1312-\\u1315\\u1318-\\u135a\\u1380-\\u138f\\u13a0-\\u13f5\\u13f8-\\u13fd\\u1401-\\u166c\\u166f-\\u167f\\u1681-\\u169a\\u16a0-\\u16ea\\u16ee-\\u16f8\\u1700-\\u1711\\u171f-\\u1731\\u1740-\\u1751\\u1760-\\u176c\\u176e-\\u1770\\u1780-\\u17b3\\u17d7\\u17dc\\u1820-\\u1878\\u1880-\\u18a8\\u18aa\\u18b0-\\u18f5\\u1900-\\u191e\\u1950-\\u196d\\u1970-\\u1974\\u1980-\\u19ab\\u19b0-\\u19c9\\u1a00-\\u1a16\\u1a20-\\u1a54\\u1aa7\\u1b05-\\u1b33\\u1b45-\\u1b4c\\u1b83-\\u1ba0\\u1bae\\u1baf\\u1bba-\\u1be5\\u1c00-\\u1c23\\u1c4d-\\u1c4f\\u1c5a-\\u1c7d\\u1c80-\\u1c88\\u1c90-\\u1cba\\u1cbd-\\u1cbf\\u1ce9-\\u1cec\\u1cee-\\u1cf3\\u1cf5\\u1cf6\\u1cfa\\u1d00-\\u1dbf\\u1e00-\\u1f15\\u1f18-\\u1f1d\\u1f20-\\u1f45\\u1f48-\\u1f4d\\u1f50-\\u1f57\\u1f59\\u1f5b\\u1f5d\\u1f5f-\\u1f7d\\u1f80-\\u1fb4\\u1fb6-\\u1fbc\\u1fbe\\u1fc2-\\u1fc4\\u1fc6-\\u1fcc\\u1fd0-\\u1fd3\\u1fd6-\\u1fdb\\u1fe0-\\u1fec\\u1ff2-\\u1ff4\\u1ff6-\\u1ffc\\u2071\\u207f\\u2090-\\u209c\\u2102\\u2107\\u210a-\\u2113\\u2115\\u2118-\\u211d\\u2124\\u2126\\u2128\\u212a-\\u2139\\u213c-\\u213f\\u2145-\\u2149\\u214e\\u2160-\\u2188\\u2c00-\\u2ce4\\u2ceb-\\u2cee\\u2cf2\\u2cf3\\u2d00-\\u2d25\\u2d27\\u2d2d\\u2d30-\\u2d67\\u2d6f\\u2d80-\\u2d96\\u2da0-\\u2da6\\u2da8-\\u2dae\\u2db0-\\u2db6\\u2db8-\\u2dbe\\u2dc0-\\u2dc6\\u2dc8-\\u2dce\\u2dd0-\\u2dd6\\u2dd8-\\u2dde\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303c\\u3041-\\u3096\\u309b-\\u309f\\u30a1-\\u30fa\\u30fc-\\u30ff\\u3105-\\u312f\\u3131-\\u318e\\u31a0-\\u31bf\\u31f0-\\u31ff\\u3400-\\u4dbf\\u4e00-\\ua48c\\ua4d0-\\ua4fd\\ua500-\\ua60c\\ua610-\\ua61f\\ua62a\\ua62b\\ua640-\\ua66e\\ua67f-\\ua69d\\ua6a0-\\ua6ef\\ua717-\\ua71f\\ua722-\\ua788\\ua78b-\\ua7ca\\ua7d0\\ua7d1\\ua7d3\\ua7d5-\\ua7d9\\ua7f2-\\ua801\\ua803-\\ua805\\ua807-\\ua80a\\ua80c-\\ua822\\ua840-\\ua873\\ua882-\\ua8b3\\ua8f2-\\ua8f7\\ua8fb\\ua8fd\\ua8fe\\ua90a-\\ua925\\ua930-\\ua946\\ua960-\\ua97c\\ua984-\\ua9b2\\ua9cf\\ua9e0-\\ua9e4\\ua9e6-\\ua9ef\\ua9fa-\\ua9fe\\uaa00-\\uaa28\\uaa40-\\uaa42\\uaa44-\\uaa4b\\uaa60-\\uaa76\\uaa7a\\uaa7e-\\uaaaf\\uaab1\\uaab5\\uaab6\\uaab9-\\uaabd\\uaac0\\uaac2\\uaadb-\\uaadd\\uaae0-\\uaaea\\uaaf2-\\uaaf4\\uab01-\\uab06\\uab09-\\uab0e\\uab11-\\uab16\\uab20-\\uab26\\uab28-\\uab2e\\uab30-\\uab5a\\uab5c-\\uab69\\uab70-\\uabe2\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\uf900-\\ufa6d\\ufa70-\\ufad9\\ufb00-\\ufb06\\ufb13-\\ufb17\\ufb1d\\ufb1f-\\ufb28\\ufb2a-\\ufb36\\ufb38-\\ufb3c\\ufb3e\\ufb40\\ufb41\\ufb43\\ufb44\\ufb46-\\ufbb1\\ufbd3-\\ufd3d\\ufd50-\\ufd8f\\ufd92-\\ufdc7\\ufdf0-\\ufdfb\\ufe70-\\ufe74\\ufe76-\\ufefc\\uff21-\\uff3a\\uff41-\\uff5a\\uff66-\\uffbe\\uffc2-\\uffc7\\uffca-\\uffcf\\uffd2-\\uffd7\\uffda-\\uffdc\";\n/* prettier-ignore */\nlet nonASCIIidentifierChars = \"\\u200c\\u200d\\xb7\\u0300-\\u036f\\u0387\\u0483-\\u0487\\u0591-\\u05bd\\u05bf\\u05c1\\u05c2\\u05c4\\u05c5\\u05c7\\u0610-\\u061a\\u064b-\\u0669\\u0670\\u06d6-\\u06dc\\u06df-\\u06e4\\u06e7\\u06e8\\u06ea-\\u06ed\\u06f0-\\u06f9\\u0711\\u0730-\\u074a\\u07a6-\\u07b0\\u07c0-\\u07c9\\u07eb-\\u07f3\\u07fd\\u0816-\\u0819\\u081b-\\u0823\\u0825-\\u0827\\u0829-\\u082d\\u0859-\\u085b\\u0898-\\u089f\\u08ca-\\u08e1\\u08e3-\\u0903\\u093a-\\u093c\\u093e-\\u094f\\u0951-\\u0957\\u0962\\u0963\\u0966-\\u096f\\u0981-\\u0983\\u09bc\\u09be-\\u09c4\\u09c7\\u09c8\\u09cb-\\u09cd\\u09d7\\u09e2\\u09e3\\u09e6-\\u09ef\\u09fe\\u0a01-\\u0a03\\u0a3c\\u0a3e-\\u0a42\\u0a47\\u0a48\\u0a4b-\\u0a4d\\u0a51\\u0a66-\\u0a71\\u0a75\\u0a81-\\u0a83\\u0abc\\u0abe-\\u0ac5\\u0ac7-\\u0ac9\\u0acb-\\u0acd\\u0ae2\\u0ae3\\u0ae6-\\u0aef\\u0afa-\\u0aff\\u0b01-\\u0b03\\u0b3c\\u0b3e-\\u0b44\\u0b47\\u0b48\\u0b4b-\\u0b4d\\u0b55-\\u0b57\\u0b62\\u0b63\\u0b66-\\u0b6f\\u0b82\\u0bbe-\\u0bc2\\u0bc6-\\u0bc8\\u0bca-\\u0bcd\\u0bd7\\u0be6-\\u0bef\\u0c00-\\u0c04\\u0c3c\\u0c3e-\\u0c44\\u0c46-\\u0c48\\u0c4a-\\u0c4d\\u0c55\\u0c56\\u0c62\\u0c63\\u0c66-\\u0c6f\\u0c81-\\u0c83\\u0cbc\\u0cbe-\\u0cc4\\u0cc6-\\u0cc8\\u0cca-\\u0ccd\\u0cd5\\u0cd6\\u0ce2\\u0ce3\\u0ce6-\\u0cef\\u0cf3\\u0d00-\\u0d03\\u0d3b\\u0d3c\\u0d3e-\\u0d44\\u0d46-\\u0d48\\u0d4a-\\u0d4d\\u0d57\\u0d62\\u0d63\\u0d66-\\u0d6f\\u0d81-\\u0d83\\u0dca\\u0dcf-\\u0dd4\\u0dd6\\u0dd8-\\u0ddf\\u0de6-\\u0def\\u0df2\\u0df3\\u0e31\\u0e34-\\u0e3a\\u0e47-\\u0e4e\\u0e50-\\u0e59\\u0eb1\\u0eb4-\\u0ebc\\u0ec8-\\u0ece\\u0ed0-\\u0ed9\\u0f18\\u0f19\\u0f20-\\u0f29\\u0f35\\u0f37\\u0f39\\u0f3e\\u0f3f\\u0f71-\\u0f84\\u0f86\\u0f87\\u0f8d-\\u0f97\\u0f99-\\u0fbc\\u0fc6\\u102b-\\u103e\\u1040-\\u1049\\u1056-\\u1059\\u105e-\\u1060\\u1062-\\u1064\\u1067-\\u106d\\u1071-\\u1074\\u1082-\\u108d\\u108f-\\u109d\\u135d-\\u135f\\u1369-\\u1371\\u1712-\\u1715\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17b4-\\u17d3\\u17dd\\u17e0-\\u17e9\\u180b-\\u180d\\u180f-\\u1819\\u18a9\\u1920-\\u192b\\u1930-\\u193b\\u1946-\\u194f\\u19d0-\\u19da\\u1a17-\\u1a1b\\u1a55-\\u1a5e\\u1a60-\\u1a7c\\u1a7f-\\u1a89\\u1a90-\\u1a99\\u1ab0-\\u1abd\\u1abf-\\u1ace\\u1b00-\\u1b04\\u1b34-\\u1b44\\u1b50-\\u1b59\\u1b6b-\\u1b73\\u1b80-\\u1b82\\u1ba1-\\u1bad\\u1bb0-\\u1bb9\\u1be6-\\u1bf3\\u1c24-\\u1c37\\u1c40-\\u1c49\\u1c50-\\u1c59\\u1cd0-\\u1cd2\\u1cd4-\\u1ce8\\u1ced\\u1cf4\\u1cf7-\\u1cf9\\u1dc0-\\u1dff\\u200c\\u200d\\u203f\\u2040\\u2054\\u20d0-\\u20dc\\u20e1\\u20e5-\\u20f0\\u2cef-\\u2cf1\\u2d7f\\u2de0-\\u2dff\\u302a-\\u302f\\u3099\\u309a\\u30fb\\ua620-\\ua629\\ua66f\\ua674-\\ua67d\\ua69e\\ua69f\\ua6f0\\ua6f1\\ua802\\ua806\\ua80b\\ua823-\\ua827\\ua82c\\ua880\\ua881\\ua8b4-\\ua8c5\\ua8d0-\\ua8d9\\ua8e0-\\ua8f1\\ua8ff-\\ua909\\ua926-\\ua92d\\ua947-\\ua953\\ua980-\\ua983\\ua9b3-\\ua9c0\\ua9d0-\\ua9d9\\ua9e5\\ua9f0-\\ua9f9\\uaa29-\\uaa36\\uaa43\\uaa4c\\uaa4d\\uaa50-\\uaa59\\uaa7b-\\uaa7d\\uaab0\\uaab2-\\uaab4\\uaab7\\uaab8\\uaabe\\uaabf\\uaac1\\uaaeb-\\uaaef\\uaaf5\\uaaf6\\uabe3-\\uabea\\uabec\\uabed\\uabf0-\\uabf9\\ufb1e\\ufe00-\\ufe0f\\ufe20-\\ufe2f\\ufe33\\ufe34\\ufe4d-\\ufe4f\\uff10-\\uff19\\uff3f\\uff65\";\n\nconst nonASCIIidentifierStart = new RegExp(\n \"[\" + nonASCIIidentifierStartChars + \"]\",\n);\nconst nonASCIIidentifier = new RegExp(\n \"[\" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + \"]\",\n);\n\nnonASCIIidentifierStartChars = nonASCIIidentifierChars = null;\n\n// These are a run-length and offset-encoded representation of the\n// >0xffff code points that are a valid part of identifiers. The\n// offset starts at 0x10000, and each pair of numbers represents an\n// offset to the next range, and then a size of the range. They were\n// generated by `scripts/generate-identifier-regex.js`.\n/* prettier-ignore */\nconst astralIdentifierStartCodes = [0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,68,310,10,21,11,7,25,5,2,41,2,8,70,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,349,41,7,1,79,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,20,1,64,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,264,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,4026,582,8634,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,689,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,43,8,8936,3,2,6,2,1,2,290,16,0,30,2,3,0,15,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,30,7,5,262,61,147,44,11,6,17,0,322,29,19,43,485,27,757,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4153,7,221,3,5761,15,7472,16,621,2467,541,1507,4938,6,4191];\n/* prettier-ignore */\nconst astralIdentifierCodes = [509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,370,1,81,2,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,406,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,10,1,2,0,49,6,4,4,14,9,5351,0,7,14,13835,9,87,9,39,4,60,6,26,9,1014,0,2,54,8,3,82,0,12,1,19628,1,4706,45,3,22,543,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,101,0,161,6,10,9,357,0,62,13,499,13,983,6,110,6,6,9,4759,9,787719,239];\n\n// This has a complexity linear to the value of the code. The\n// assumption is that looking up astral identifier characters is\n// rare.\nfunction isInAstralSet(code: number, set: readonly number[]): boolean {\n let pos = 0x10000;\n for (let i = 0, length = set.length; i < length; i += 2) {\n pos += set[i];\n if (pos > code) return false;\n\n pos += set[i + 1];\n if (pos >= code) return true;\n }\n return false;\n}\n\n// Test whether a given character code starts an identifier.\n\nexport function isIdentifierStart(code: number): boolean {\n if (code < charCodes.uppercaseA) return code === charCodes.dollarSign;\n if (code <= charCodes.uppercaseZ) return true;\n if (code < charCodes.lowercaseA) return code === charCodes.underscore;\n if (code <= charCodes.lowercaseZ) return true;\n if (code <= 0xffff) {\n return (\n code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code))\n );\n }\n return isInAstralSet(code, astralIdentifierStartCodes);\n}\n\n// Test whether a given character is part of an identifier.\n\nexport function isIdentifierChar(code: number): boolean {\n if (code < charCodes.digit0) return code === charCodes.dollarSign;\n if (code < charCodes.colon) return true;\n if (code < charCodes.uppercaseA) return false;\n if (code <= charCodes.uppercaseZ) return true;\n if (code < charCodes.lowercaseA) return code === charCodes.underscore;\n if (code <= charCodes.lowercaseZ) return true;\n if (code <= 0xffff) {\n return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));\n }\n return (\n isInAstralSet(code, astralIdentifierStartCodes) ||\n isInAstralSet(code, astralIdentifierCodes)\n );\n}\n\n// Test whether a given string is a valid identifier name\n\nexport function isIdentifierName(name: string): boolean {\n let isFirst = true;\n for (let i = 0; i < name.length; i++) {\n // The implementation is based on\n // https://source.chromium.org/chromium/chromium/src/+/master:v8/src/builtins/builtins-string-gen.cc;l=1455;drc=221e331b49dfefadbc6fa40b0c68e6f97606d0b3;bpv=0;bpt=1\n // We reimplement `codePointAt` because `codePointAt` is a V8 builtin which is not inlined by TurboFan (as of M91)\n // since `name` is mostly ASCII, an inlined `charCodeAt` wins here\n let cp = name.charCodeAt(i);\n if ((cp & 0xfc00) === 0xd800 && i + 1 < name.length) {\n const trail = name.charCodeAt(++i);\n if ((trail & 0xfc00) === 0xdc00) {\n cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff);\n }\n }\n if (isFirst) {\n isFirst = false;\n if (!isIdentifierStart(cp)) {\n return false;\n }\n } else if (!isIdentifierChar(cp)) {\n return false;\n }\n }\n return !isFirst;\n}\n"],"mappings":";;;;;;;;AAaA,IAAIA,4BAA4B,GAAG,8qIAA8qI;AAEjtI,IAAIC,uBAAuB,GAAG,2lFAA2lF;AAEznF,MAAMC,uBAAuB,GAAG,IAAIC,MAAM,CACxC,GAAG,GAAGH,4BAA4B,GAAG,GACvC,CAAC;AACD,MAAMI,kBAAkB,GAAG,IAAID,MAAM,CACnC,GAAG,GAAGH,4BAA4B,GAAGC,uBAAuB,GAAG,GACjE,CAAC;AAEDD,4BAA4B,GAAGC,uBAAuB,GAAG,IAAI;AAQ7D,MAAMI,0BAA0B,GAAG,CAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,GAAG,EAAC,EAAE,EAAC,EAAE,EAAC,GAAG,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,GAAG,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,GAAG,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,GAAG,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,GAAG,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,GAAG,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,GAAG,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,GAAG,EAAC,EAAE,EAAC,GAAG,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,GAAG,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,GAAG,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,GAAG,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,GAAG,EAAC,CAAC,EAAC,EAAE,EAAC,GAAG,EAAC,GAAG,EAAC,GAAG,EAAC,EAAE,EAAC,GAAG,EAAC,IAAI,EAAC,EAAE,EAAC,EAAE,EAAC,IAAI,EAAC,EAAE,EAAC,CAAC,EAAC,IAAI,EAAC,GAAG,EAAC,IAAI,EAAC,GAAG,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,GAAG,EAAC,EAAE,EAAC,GAAG,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,IAAI,EAAC,CAAC,EAAC,IAAI,EAAC,EAAE,EAAC,CAAC,EAAC,IAAI,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,GAAG,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,GAAG,EAAC,IAAI,EAAC,GAAG,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,IAAI,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,GAAG,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,IAAI,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,GAAG,EAAC,EAAE,EAAC,GAAG,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,GAAG,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,GAAG,EAAC,EAAE,EAAC,GAAG,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,GAAG,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,IAAI,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,IAAI,EAAC,KAAK,EAAC,EAAE,EAAC,IAAI,EAAC,CAAC,EAAC,GAAG,EAAC,CAAC,EAAC,IAAI,EAAC,EAAE,EAAC,IAAI,EAAC,EAAE,EAAC,GAAG,EAAC,IAAI,EAAC,GAAG,EAAC,IAAI,EAAC,IAAI,EAAC,CAAC,EAAC,IAAI,CAAC;AAEx+C,MAAMC,qBAAqB,GAAG,CAAC,GAAG,EAAC,CAAC,EAAC,GAAG,EAAC,CAAC,EAAC,GAAG,EAAC,CAAC,EAAC,GAAG,EAAC,CAAC,EAAC,IAAI,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,GAAG,EAAC,CAAC,EAAC,GAAG,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,GAAG,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,GAAG,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,GAAG,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,GAAG,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,GAAG,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,GAAG,EAAC,EAAE,EAAC,GAAG,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,GAAG,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,GAAG,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,GAAG,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,GAAG,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,IAAI,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,KAAK,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,IAAI,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,KAAK,EAAC,CAAC,EAAC,IAAI,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,GAAG,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,GAAG,EAAC,CAAC,EAAC,IAAI,EAAC,EAAE,EAAC,GAAG,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,IAAI,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,GAAG,EAAC,CAAC,EAAC,GAAG,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,GAAG,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,GAAG,EAAC,EAAE,EAAC,GAAG,EAAC,CAAC,EAAC,GAAG,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,IAAI,EAAC,CAAC,EAAC,MAAM,EAAC,GAAG,CAAC;AAKjwB,SAASC,aAAaA,CAACC,IAAY,EAAEC,GAAsB,EAAW;EACpE,IAAIC,GAAG,GAAG,OAAO;EACjB,KAAK,IAAIC,CAAC,GAAG,CAAC,EAAEC,MAAM,GAAGH,GAAG,CAACG,MAAM,EAAED,CAAC,GAAGC,MAAM,EAAED,CAAC,IAAI,CAAC,EAAE;IACvDD,GAAG,IAAID,GAAG,CAACE,CAAC,CAAC;IACb,IAAID,GAAG,GAAGF,IAAI,EAAE,OAAO,KAAK;IAE5BE,GAAG,IAAID,GAAG,CAACE,CAAC,GAAG,CAAC,CAAC;IACjB,IAAID,GAAG,IAAIF,IAAI,EAAE,OAAO,IAAI;EAC9B;EACA,OAAO,KAAK;AACd;AAIO,SAASK,iBAAiBA,CAACL,IAAY,EAAW;EACvD,IAAIA,IAAI,KAAuB,EAAE,OAAOA,IAAI,OAAyB;EACrE,IAAIA,IAAI,MAAwB,EAAE,OAAO,IAAI;EAC7C,IAAIA,IAAI,KAAuB,EAAE,OAAOA,IAAI,OAAyB;EACrE,IAAIA,IAAI,OAAwB,EAAE,OAAO,IAAI;EAC7C,IAAIA,IAAI,IAAI,MAAM,EAAE;IAClB,OACEA,IAAI,IAAI,IAAI,IAAIN,uBAAuB,CAACY,IAAI,CAACC,MAAM,CAACC,YAAY,CAACR,IAAI,CAAC,CAAC;EAE3E;EACA,OAAOD,aAAa,CAACC,IAAI,EAAEH,0BAA0B,CAAC;AACxD;AAIO,SAASY,gBAAgBA,CAACT,IAAY,EAAW;EACtD,IAAIA,IAAI,KAAmB,EAAE,OAAOA,IAAI,OAAyB;EACjE,IAAIA,IAAI,KAAkB,EAAE,OAAO,IAAI;EACvC,IAAIA,IAAI,KAAuB,EAAE,OAAO,KAAK;EAC7C,IAAIA,IAAI,MAAwB,EAAE,OAAO,IAAI;EAC7C,IAAIA,IAAI,KAAuB,EAAE,OAAOA,IAAI,OAAyB;EACrE,IAAIA,IAAI,OAAwB,EAAE,OAAO,IAAI;EAC7C,IAAIA,IAAI,IAAI,MAAM,EAAE;IAClB,OAAOA,IAAI,IAAI,IAAI,IAAIJ,kBAAkB,CAACU,IAAI,CAACC,MAAM,CAACC,YAAY,CAACR,IAAI,CAAC,CAAC;EAC3E;EACA,OACED,aAAa,CAACC,IAAI,EAAEH,0BAA0B,CAAC,IAC/CE,aAAa,CAACC,IAAI,EAAEF,qBAAqB,CAAC;AAE9C;AAIO,SAASY,gBAAgBA,CAACC,IAAY,EAAW;EACtD,IAAIC,OAAO,GAAG,IAAI;EAClB,KAAK,IAAIT,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGQ,IAAI,CAACP,MAAM,EAAED,CAAC,EAAE,EAAE;IAKpC,IAAIU,EAAE,GAAGF,IAAI,CAACG,UAAU,CAACX,CAAC,CAAC;IAC3B,IAAI,CAACU,EAAE,GAAG,MAAM,MAAM,MAAM,IAAIV,CAAC,GAAG,CAAC,GAAGQ,IAAI,CAACP,MAAM,EAAE;MACnD,MAAMW,KAAK,GAAGJ,IAAI,CAACG,UAAU,CAAC,EAAEX,CAAC,CAAC;MAClC,IAAI,CAACY,KAAK,GAAG,MAAM,MAAM,MAAM,EAAE;QAC/BF,EAAE,GAAG,OAAO,IAAI,CAACA,EAAE,GAAG,KAAK,KAAK,EAAE,CAAC,IAAIE,KAAK,GAAG,KAAK,CAAC;MACvD;IACF;IACA,IAAIH,OAAO,EAAE;MACXA,OAAO,GAAG,KAAK;MACf,IAAI,CAACP,iBAAiB,CAACQ,EAAE,CAAC,EAAE;QAC1B,OAAO,KAAK;MACd;IACF,CAAC,MAAM,IAAI,CAACJ,gBAAgB,CAACI,EAAE,CAAC,EAAE;MAChC,OAAO,KAAK;IACd;EACF;EACA,OAAO,CAACD,OAAO;AACjB","ignoreList":[]} \ No newline at end of file diff --git a/libcore/node_modules/@babel/helper-validator-identifier/lib/index.js b/libcore/node_modules/@babel/helper-validator-identifier/lib/index.js new file mode 100644 index 0000000..76b2282 --- /dev/null +++ b/libcore/node_modules/@babel/helper-validator-identifier/lib/index.js @@ -0,0 +1,57 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "isIdentifierChar", { + enumerable: true, + get: function () { + return _identifier.isIdentifierChar; + } +}); +Object.defineProperty(exports, "isIdentifierName", { + enumerable: true, + get: function () { + return _identifier.isIdentifierName; + } +}); +Object.defineProperty(exports, "isIdentifierStart", { + enumerable: true, + get: function () { + return _identifier.isIdentifierStart; + } +}); +Object.defineProperty(exports, "isKeyword", { + enumerable: true, + get: function () { + return _keyword.isKeyword; + } +}); +Object.defineProperty(exports, "isReservedWord", { + enumerable: true, + get: function () { + return _keyword.isReservedWord; + } +}); +Object.defineProperty(exports, "isStrictBindOnlyReservedWord", { + enumerable: true, + get: function () { + return _keyword.isStrictBindOnlyReservedWord; + } +}); +Object.defineProperty(exports, "isStrictBindReservedWord", { + enumerable: true, + get: function () { + return _keyword.isStrictBindReservedWord; + } +}); +Object.defineProperty(exports, "isStrictReservedWord", { + enumerable: true, + get: function () { + return _keyword.isStrictReservedWord; + } +}); +var _identifier = require("./identifier.js"); +var _keyword = require("./keyword.js"); + +//# sourceMappingURL=index.js.map diff --git a/libcore/node_modules/@babel/helper-validator-identifier/lib/index.js.map b/libcore/node_modules/@babel/helper-validator-identifier/lib/index.js.map new file mode 100644 index 0000000..d985f3b --- /dev/null +++ b/libcore/node_modules/@babel/helper-validator-identifier/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_identifier","require","_keyword"],"sources":["../src/index.ts"],"sourcesContent":["export {\n isIdentifierName,\n isIdentifierChar,\n isIdentifierStart,\n} from \"./identifier.ts\";\nexport {\n isReservedWord,\n isStrictBindOnlyReservedWord,\n isStrictBindReservedWord,\n isStrictReservedWord,\n isKeyword,\n} from \"./keyword.ts\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAAA,WAAA,GAAAC,OAAA;AAKA,IAAAC,QAAA,GAAAD,OAAA","ignoreList":[]} \ No newline at end of file diff --git a/libcore/node_modules/@babel/helper-validator-identifier/lib/keyword.js b/libcore/node_modules/@babel/helper-validator-identifier/lib/keyword.js new file mode 100644 index 0000000..054cf84 --- /dev/null +++ b/libcore/node_modules/@babel/helper-validator-identifier/lib/keyword.js @@ -0,0 +1,35 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isKeyword = isKeyword; +exports.isReservedWord = isReservedWord; +exports.isStrictBindOnlyReservedWord = isStrictBindOnlyReservedWord; +exports.isStrictBindReservedWord = isStrictBindReservedWord; +exports.isStrictReservedWord = isStrictReservedWord; +const reservedWords = { + keyword: ["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete"], + strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"], + strictBind: ["eval", "arguments"] +}; +const keywords = new Set(reservedWords.keyword); +const reservedWordsStrictSet = new Set(reservedWords.strict); +const reservedWordsStrictBindSet = new Set(reservedWords.strictBind); +function isReservedWord(word, inModule) { + return inModule && word === "await" || word === "enum"; +} +function isStrictReservedWord(word, inModule) { + return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word); +} +function isStrictBindOnlyReservedWord(word) { + return reservedWordsStrictBindSet.has(word); +} +function isStrictBindReservedWord(word, inModule) { + return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word); +} +function isKeyword(word) { + return keywords.has(word); +} + +//# sourceMappingURL=keyword.js.map diff --git a/libcore/node_modules/@babel/helper-validator-identifier/lib/keyword.js.map b/libcore/node_modules/@babel/helper-validator-identifier/lib/keyword.js.map new file mode 100644 index 0000000..3471f78 --- /dev/null +++ b/libcore/node_modules/@babel/helper-validator-identifier/lib/keyword.js.map @@ -0,0 +1 @@ +{"version":3,"names":["reservedWords","keyword","strict","strictBind","keywords","Set","reservedWordsStrictSet","reservedWordsStrictBindSet","isReservedWord","word","inModule","isStrictReservedWord","has","isStrictBindOnlyReservedWord","isStrictBindReservedWord","isKeyword"],"sources":["../src/keyword.ts"],"sourcesContent":["const reservedWords = {\n keyword: [\n \"break\",\n \"case\",\n \"catch\",\n \"continue\",\n \"debugger\",\n \"default\",\n \"do\",\n \"else\",\n \"finally\",\n \"for\",\n \"function\",\n \"if\",\n \"return\",\n \"switch\",\n \"throw\",\n \"try\",\n \"var\",\n \"const\",\n \"while\",\n \"with\",\n \"new\",\n \"this\",\n \"super\",\n \"class\",\n \"extends\",\n \"export\",\n \"import\",\n \"null\",\n \"true\",\n \"false\",\n \"in\",\n \"instanceof\",\n \"typeof\",\n \"void\",\n \"delete\",\n ],\n strict: [\n \"implements\",\n \"interface\",\n \"let\",\n \"package\",\n \"private\",\n \"protected\",\n \"public\",\n \"static\",\n \"yield\",\n ],\n strictBind: [\"eval\", \"arguments\"],\n};\nconst keywords = new Set(reservedWords.keyword);\nconst reservedWordsStrictSet = new Set(reservedWords.strict);\nconst reservedWordsStrictBindSet = new Set(reservedWords.strictBind);\n\n/**\n * Checks if word is a reserved word in non-strict mode\n */\nexport function isReservedWord(word: string, inModule: boolean): boolean {\n return (inModule && word === \"await\") || word === \"enum\";\n}\n\n/**\n * Checks if word is a reserved word in non-binding strict mode\n *\n * Includes non-strict reserved words\n */\nexport function isStrictReservedWord(word: string, inModule: boolean): boolean {\n return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);\n}\n\n/**\n * Checks if word is a reserved word in binding strict mode, but it is allowed as\n * a normal identifier.\n */\nexport function isStrictBindOnlyReservedWord(word: string): boolean {\n return reservedWordsStrictBindSet.has(word);\n}\n\n/**\n * Checks if word is a reserved word in binding strict mode\n *\n * Includes non-strict reserved words and non-binding strict reserved words\n */\nexport function isStrictBindReservedWord(\n word: string,\n inModule: boolean,\n): boolean {\n return (\n isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word)\n );\n}\n\nexport function isKeyword(word: string): boolean {\n return keywords.has(word);\n}\n"],"mappings":";;;;;;;;;;AAAA,MAAMA,aAAa,GAAG;EACpBC,OAAO,EAAE,CACP,OAAO,EACP,MAAM,EACN,OAAO,EACP,UAAU,EACV,UAAU,EACV,SAAS,EACT,IAAI,EACJ,MAAM,EACN,SAAS,EACT,KAAK,EACL,UAAU,EACV,IAAI,EACJ,QAAQ,EACR,QAAQ,EACR,OAAO,EACP,KAAK,EACL,KAAK,EACL,OAAO,EACP,OAAO,EACP,MAAM,EACN,KAAK,EACL,MAAM,EACN,OAAO,EACP,OAAO,EACP,SAAS,EACT,QAAQ,EACR,QAAQ,EACR,MAAM,EACN,MAAM,EACN,OAAO,EACP,IAAI,EACJ,YAAY,EACZ,QAAQ,EACR,MAAM,EACN,QAAQ,CACT;EACDC,MAAM,EAAE,CACN,YAAY,EACZ,WAAW,EACX,KAAK,EACL,SAAS,EACT,SAAS,EACT,WAAW,EACX,QAAQ,EACR,QAAQ,EACR,OAAO,CACR;EACDC,UAAU,EAAE,CAAC,MAAM,EAAE,WAAW;AAClC,CAAC;AACD,MAAMC,QAAQ,GAAG,IAAIC,GAAG,CAACL,aAAa,CAACC,OAAO,CAAC;AAC/C,MAAMK,sBAAsB,GAAG,IAAID,GAAG,CAACL,aAAa,CAACE,MAAM,CAAC;AAC5D,MAAMK,0BAA0B,GAAG,IAAIF,GAAG,CAACL,aAAa,CAACG,UAAU,CAAC;AAK7D,SAASK,cAAcA,CAACC,IAAY,EAAEC,QAAiB,EAAW;EACvE,OAAQA,QAAQ,IAAID,IAAI,KAAK,OAAO,IAAKA,IAAI,KAAK,MAAM;AAC1D;AAOO,SAASE,oBAAoBA,CAACF,IAAY,EAAEC,QAAiB,EAAW;EAC7E,OAAOF,cAAc,CAACC,IAAI,EAAEC,QAAQ,CAAC,IAAIJ,sBAAsB,CAACM,GAAG,CAACH,IAAI,CAAC;AAC3E;AAMO,SAASI,4BAA4BA,CAACJ,IAAY,EAAW;EAClE,OAAOF,0BAA0B,CAACK,GAAG,CAACH,IAAI,CAAC;AAC7C;AAOO,SAASK,wBAAwBA,CACtCL,IAAY,EACZC,QAAiB,EACR;EACT,OACEC,oBAAoB,CAACF,IAAI,EAAEC,QAAQ,CAAC,IAAIG,4BAA4B,CAACJ,IAAI,CAAC;AAE9E;AAEO,SAASM,SAASA,CAACN,IAAY,EAAW;EAC/C,OAAOL,QAAQ,CAACQ,GAAG,CAACH,IAAI,CAAC;AAC3B","ignoreList":[]} \ No newline at end of file diff --git a/libcore/node_modules/@babel/helper-validator-identifier/package.json b/libcore/node_modules/@babel/helper-validator-identifier/package.json new file mode 100644 index 0000000..0e2e01b --- /dev/null +++ b/libcore/node_modules/@babel/helper-validator-identifier/package.json @@ -0,0 +1,31 @@ +{ + "name": "@babel/helper-validator-identifier", + "version": "7.24.7", + "description": "Validate identifier/keywords name", + "repository": { + "type": "git", + "url": "https://github.com/babel/babel.git", + "directory": "packages/babel-helper-validator-identifier" + }, + "license": "MIT", + "publishConfig": { + "access": "public" + }, + "main": "./lib/index.js", + "exports": { + ".": { + "types": "./lib/index.d.ts", + "default": "./lib/index.js" + }, + "./package.json": "./package.json" + }, + "devDependencies": { + "@unicode/unicode-15.1.0": "^1.5.2", + "charcodes": "^0.2.0" + }, + "engines": { + "node": ">=6.9.0" + }, + "author": "The Babel Team (https://babel.dev/team)", + "type": "commonjs" +} \ No newline at end of file diff --git a/libcore/node_modules/@babel/helper-validator-identifier/scripts/generate-identifier-regex.js b/libcore/node_modules/@babel/helper-validator-identifier/scripts/generate-identifier-regex.js new file mode 100644 index 0000000..f3fd9e9 --- /dev/null +++ b/libcore/node_modules/@babel/helper-validator-identifier/scripts/generate-identifier-regex.js @@ -0,0 +1,73 @@ +"use strict"; + +// Always use the latest available version of Unicode! +// https://tc39.github.io/ecma262/#sec-conformance +const version = "15.1.0"; + +const start = require( + "@unicode/unicode-" + version + "/Binary_Property/ID_Start/code-points.js" +).filter(function (ch) { + return ch > 0x7f; +}); +let last = -1; +const cont = require( + "@unicode/unicode-" + version + "/Binary_Property/ID_Continue/code-points.js" +).filter(function (ch) { + return ch > 0x7f && search(start, ch, last + 1) === -1; +}); + +function search(arr, ch, starting) { + for (let i = starting; arr[i] <= ch && i < arr.length; last = i++) { + if (arr[i] === ch) return i; + } + return -1; +} + +function pad(str, width) { + while (str.length < width) str = "0" + str; + return str; +} + +function esc(code) { + const hex = code.toString(16); + if (hex.length <= 2) return "\\x" + pad(hex, 2); + else return "\\u" + pad(hex, 4); +} + +function generate(chars) { + const astral = []; + let re = ""; + for (let i = 0, at = 0x10000; i < chars.length; i++) { + const from = chars[i]; + let to = from; + while (i < chars.length - 1 && chars[i + 1] === to + 1) { + i++; + to++; + } + if (to <= 0xffff) { + if (from === to) re += esc(from); + else if (from + 1 === to) re += esc(from) + esc(to); + else re += esc(from) + "-" + esc(to); + } else { + astral.push(from - at, to - from); + at = to; + } + } + return { nonASCII: re, astral: astral }; +} + +const startData = generate(start); +const contData = generate(cont); + +console.log("/* prettier-ignore */"); +console.log('let nonASCIIidentifierStartChars = "' + startData.nonASCII + '";'); +console.log("/* prettier-ignore */"); +console.log('let nonASCIIidentifierChars = "' + contData.nonASCII + '";'); +console.log("/* prettier-ignore */"); +console.log( + "const astralIdentifierStartCodes = " + JSON.stringify(startData.astral) + ";" +); +console.log("/* prettier-ignore */"); +console.log( + "const astralIdentifierCodes = " + JSON.stringify(contData.astral) + ";" +); diff --git a/libcore/node_modules/@babel/parser/CHANGELOG.md b/libcore/node_modules/@babel/parser/CHANGELOG.md new file mode 100644 index 0000000..b3840ac --- /dev/null +++ b/libcore/node_modules/@babel/parser/CHANGELOG.md @@ -0,0 +1,1073 @@ +# Changelog + +> **Tags:** +> - :boom: [Breaking Change] +> - :eyeglasses: [Spec Compliance] +> - :rocket: [New Feature] +> - :bug: [Bug Fix] +> - :memo: [Documentation] +> - :house: [Internal] +> - :nail_care: [Polish] + +> Semver Policy: https://github.com/babel/babel/tree/main/packages/babel-parser#semver + +_Note: Gaps between patch versions are faulty, broken or test releases._ + +See the [Babel Changelog](https://github.com/babel/babel/blob/main/CHANGELOG.md) for the pre-6.8.0 version Changelog. + +## 6.17.1 (2017-05-10) + +### :bug: Bug Fix + * Fix typo in flow spread operator error (Brian Ng) + * Fixed invalid number literal parsing ([#473](https://github.com/babel/babylon/pull/473)) (Alex Kuzmenko) + * Fix number parser ([#433](https://github.com/babel/babylon/pull/433)) (Alex Kuzmenko) + * Ensure non pattern shorthand props are checked for reserved words ([#479](https://github.com/babel/babylon/pull/479)) (Brian Ng) + * Remove jsx context when parsing arrow functions ([#475](https://github.com/babel/babylon/pull/475)) (Brian Ng) + * Allow super in class properties ([#499](https://github.com/babel/babylon/pull/499)) (Brian Ng) + * Allow flow class field to be named constructor ([#510](https://github.com/babel/babylon/pull/510)) (Brian Ng) + +## 6.17.0 (2017-04-20) + +### :bug: Bug Fix + * Cherry-pick #418 to 6.x ([#476](https://github.com/babel/babylon/pull/476)) (Sebastian McKenzie) + * Add support for invalid escapes in tagged templates ([#274](https://github.com/babel/babylon/pull/274)) (Kevin Gibbons) + * Throw error if new.target is used outside of a function ([#402](https://github.com/babel/babylon/pull/402)) (Brian Ng) + * Fix parsing of class properties ([#351](https://github.com/babel/babylon/pull/351)) (Kevin Gibbons) + * Fix parsing yield with dynamicImport ([#383](https://github.com/babel/babylon/pull/383)) (Brian Ng) + * Ensure consistent start args for parseParenItem ([#386](https://github.com/babel/babylon/pull/386)) (Brian Ng) + +## 7.0.0-beta.8 (2017-04-04) + +### New Feature +* Add support for flow type spread (#418) (Conrad Buck) +* Allow statics in flow interfaces (#427) (Brian Ng) + +### Bug Fix +* Fix predicate attachment to match flow parser (#428) (Brian Ng) +* Add extra.raw back to JSXText and JSXAttribute (#344) (Alex Rattray) +* Fix rest parameters with array and objects (#424) (Brian Ng) +* Fix number parser (#433) (Alex Kuzmenko) + +### Docs +* Fix CONTRIBUTING.md [skip ci] (#432) (Alex Kuzmenko) + +### Internal +* Use babel-register script when running babel smoke tests (#442) (Brian Ng) + +## 7.0.0-beta.7 (2017-03-22) + +### Spec Compliance +* Remove babylon plugin for template revision since it's stage-4 (#426) (Henry Zhu) + +### Bug Fix + +* Fix push-pop logic in flow (#405) (Daniel Tschinder) + +## 7.0.0-beta.6 (2017-03-21) + +### New Feature +* Add support for invalid escapes in tagged templates (#274) (Kevin Gibbons) + +### Polish +* Improves error message when super is called outside of constructor (#408) (Arshabh Kumar Agarwal) + +### Docs + +* [7.0] Moved value field in spec from ObjectMember to ObjectProperty as ObjectMethod's don't have it (#415) [skip ci] (James Browning) + +## 7.0.0-beta.5 (2017-03-21) + +### Bug Fix +* Throw error if new.target is used outside of a function (#402) (Brian Ng) +* Fix parsing of class properties (#351) (Kevin Gibbons) + +### Other + * Test runner: Detect extra property in 'actual' but not in 'expected'. (#407) (Andy) + * Optimize travis builds (#419) (Daniel Tschinder) + * Update codecov to 2.0 (#412) (Daniel Tschinder) + * Fix spec for ClassMethod: It doesn't have a function, it *is* a function. (#406) [skip ci] (Andy) + * Changed Non-existent RestPattern to RestElement which is what is actually parsed (#409) [skip ci] (James Browning) + * Upgrade flow to 0.41 (Daniel Tschinder) + * Fix watch command (#403) (Brian Ng) + * Update yarn lock (Daniel Tschinder) + * Fix watch command (#403) (Brian Ng) + * chore(package): update flow-bin to version 0.41.0 (#395) (greenkeeper[bot]) + * Add estree test for correct order of directives (Daniel Tschinder) + * Add DoExpression to spec (#364) (Alex Kuzmenko) + * Mention cloning of repository in CONTRIBUTING.md (#391) [skip ci] (Sumedh Nimkarde) + * Explain how to run only one test (#389) [skip ci] (Aaron Ang) + + ## 7.0.0-beta.4 (2017-03-01) + +* Don't consume async when checking for async func decl (#377) (Brian Ng) +* add `ranges` option [skip ci] (Henry Zhu) +* Don't parse class properties without initializers when classProperties is disabled and Flow is enabled (#300) (Andrew Levine) + +## 7.0.0-beta.3 (2017-02-28) + +- [7.0] Change RestProperty/SpreadProperty to RestElement/SpreadElement (#384) +- Merge changes from 6.x + +## 7.0.0-beta.2 (2017-02-20) + +- estree: correctly change literals in all cases (#368) (Daniel Tschinder) + +## 7.0.0-beta.1 (2017-02-20) + +- Fix negative number literal typeannotations (#366) (Daniel Tschinder) +- Update contributing with more test info [skip ci] (#355) (Brian Ng) + +## 7.0.0-beta.0 (2017-02-15) + +- Reintroduce Variance node (#333) (Daniel Tschinder) +- Rename NumericLiteralTypeAnnotation to NumberLiteralTypeAnnotation (#332) (Charles Pick) +- [7.0] Remove ForAwaitStatement, add await flag to ForOfStatement (#349) (Brandon Dail) +- chore(package): update ava to version 0.18.0 (#345) (greenkeeper[bot]) +- chore(package): update babel-plugin-istanbul to version 4.0.0 (#350) (greenkeeper[bot]) +- Change location of ObjectTypeIndexer to match flow (#228) (Daniel Tschinder) +- Rename flow AST Type ExistentialTypeParam to ExistsTypeAnnotation (#322) (Toru Kobayashi) +- Revert "Temporary rollback for erroring on trailing comma with spread (#154)" (#290) (Daniel Tschinder) +- Remove classConstructorCall plugin (#291) (Brian Ng) +- Update yarn.lock (Daniel Tschinder) +- Update cross-env to 3.x (Daniel Tschinder) +- [7.0] Remove node 0.10, 0.12 and 5 from Travis (#284) (Sergey Rubanov) +- Remove `String.fromCodePoint` shim (#279) (Mathias Bynens) + +## 6.16.1 (2017-02-23) + +### :bug: Regression + +- Revert "Fix export default async function to be FunctionDeclaration" ([#375](https://github.com/babel/babylon/pull/375)) + +Need to modify Babel for this AST node change, so moving to 7.0. + +- Revert "Don't parse class properties without initializers when classProperties plugin is disabled, and Flow is enabled" ([#376](https://github.com/babel/babylon/pull/376)) + +[react-native](https://github.com/facebook/react-native/issues/12542) broke with this so we reverted. + +## 6.16.0 (2017-02-23) + +### :rocket: New Feature + +***ESTree*** compatibility as plugin ([#277](https://github.com/babel/babylon/pull/277)) (Daniel Tschinder) + +We finally introduce a new compatibility layer for ESTree. To put babylon into ESTree-compatible mode the new plugin `estree` can be enabled. In this mode the parser will output an AST that is compliant to the specs of [ESTree](https://github.com/estree/estree/) + +We highly recommend everyone who uses babylon outside of babel to use this plugin. This will make it much easier for users to switch between different ESTree-compatible parsers. We so far tested several projects with different parsers and exchanged their parser to babylon and in nearly all cases it worked out of the box. Some other estree-compatible parsers include `acorn`, `esprima`, `espree`, `flow-parser`, etc. + +To enable `estree` mode simply add the plugin in the config: +```json +{ + "plugins": [ "estree" ] +} +``` + +If you want to migrate your project from non-ESTree mode to ESTree, have a look at our [Readme](https://github.com/babel/babylon/#output), where all deviations are mentioned. + +Add a parseExpression public method ([#213](https://github.com/babel/babylon/pull/213)) (jeromew) + +Babylon exports a new function to parse a single expression + +```js +import { parseExpression } from 'babylon'; + +const ast = parseExpression('x || y && z', options); +``` + +The returned AST will only consist of the expression. The options are the same as for `parse()` + +Add startLine option ([#346](https://github.com/babel/babylon/pull/346)) (Raphael Mu) + +A new option was added to babylon allowing to change the initial linenumber for the first line which is usually `1`. +Changing this for example to `100` will make line `1` of the input source to be marked as line `100`, line `2` as `101`, line `3` as `102`, ... + +Function predicate declaration ([#103](https://github.com/babel/babylon/pull/103)) (Panagiotis Vekris) + +Added support for function predicates which flow introduced in version 0.33.0 + +```js +declare function is_number(x: mixed): boolean %checks(typeof x === "number"); +``` + +Allow imports in declare module ([#315](https://github.com/babel/babylon/pull/315)) (Daniel Tschinder) + +Added support for imports within module declarations which flow introduced in version 0.37.0 + +```js +declare module "C" { + import type { DT } from "D"; + declare export type CT = { D: DT }; +} +``` + +### :eyeglasses: Spec Compliance + +Forbid semicolons after decorators in classes ([#352](https://github.com/babel/babylon/pull/352)) (Kevin Gibbons) + +This example now correctly throws an error when there is a semicolon after the decorator: + +```js +class A { +@a; +foo(){} +} +``` + +Keywords are not allowed as local specifier ([#307](https://github.com/babel/babylon/pull/307)) (Daniel Tschinder) + +Using keywords in imports is not allowed anymore: + +```js +import { default } from "foo"; +import { a as debugger } from "foo"; +``` + +Do not allow overwritting of primitive types ([#314](https://github.com/babel/babylon/pull/314)) (Daniel Tschinder) + +In flow it is now forbidden to overwrite the primitive types `"any"`, `"mixed"`, `"empty"`, `"bool"`, `"boolean"`, `"number"`, `"string"`, `"void"` and `"null"` with your own type declaration. + +Disallow import type { type a } from … ([#305](https://github.com/babel/babylon/pull/305)) (Daniel Tschinder) + +The following code now correctly throws an error + +```js +import type { type a } from "foo"; +``` + +Don't parse class properties without initializers when classProperties is disabled and Flow is enabled ([#300](https://github.com/babel/babylon/pull/300)) (Andrew Levine) + +Ensure that you enable the `classProperties` plugin in order to enable correct parsing of class properties. Prior to this version it was possible to parse them by enabling the `flow` plugin but this was not intended the behaviour. + +If you enable the flow plugin you can only define the type of the class properties, but not initialize them. + +Fix export default async function to be FunctionDeclaration ([#324](https://github.com/babel/babylon/pull/324)) (Daniel Tschinder) + +Parsing the following code now returns a `FunctionDeclaration` AST node instead of `FunctionExpression`. + +```js +export default async function bar() {}; +``` + +### :nail_care: Polish + +Improve error message on attempt to destructure named import ([#288](https://github.com/babel/babylon/pull/288)) (Brian Ng) + +### :bug: Bug Fix + +Fix negative number literal typeannotations ([#366](https://github.com/babel/babylon/pull/366)) (Daniel Tschinder) + +Ensure takeDecorators is called on exported class ([#358](https://github.com/babel/babylon/pull/358)) (Brian Ng) + +ESTree: correctly change literals in all cases ([#368](https://github.com/babel/babylon/pull/368)) (Daniel Tschinder) + +Correctly convert RestProperty to Assignable ([#339](https://github.com/babel/babylon/pull/339)) (Daniel Tschinder) + +Fix #321 by allowing question marks in type params ([#338](https://github.com/babel/babylon/pull/338)) (Daniel Tschinder) + +Fix #336 by correctly setting arrow-param ([#337](https://github.com/babel/babylon/pull/337)) (Daniel Tschinder) + +Fix parse error when destructuring `set` with default value ([#317](https://github.com/babel/babylon/pull/317)) (Brian Ng) + +Fix ObjectTypeCallProperty static ([#298](https://github.com/babel/babylon/pull/298)) (Dan Harper) + + +### :house: Internal + +Fix generator-method-with-computed-name spec ([#360](https://github.com/babel/babylon/pull/360)) (Alex Rattray) + +Fix flow type-parameter-declaration test with unintended semantic ([#361](https://github.com/babel/babylon/pull/361)) (Alex Rattray) + +Cleanup and splitup parser functions ([#295](https://github.com/babel/babylon/pull/295)) (Daniel Tschinder) + +chore(package): update flow-bin to version 0.38.0 ([#313](https://github.com/babel/babylon/pull/313)) (greenkeeper[bot]) + +Call inner function instead of 1:1 copy to plugin ([#294](https://github.com/babel/babylon/pull/294)) (Daniel Tschinder) + +Update eslint-config-babel to the latest version 🚀 ([#299](https://github.com/babel/babylon/pull/299)) (greenkeeper[bot]) + +Update eslint-config-babel to the latest version 🚀 ([#293](https://github.com/babel/babylon/pull/293)) (greenkeeper[bot]) + +devDeps: remove eslint-plugin-babel ([#292](https://github.com/babel/babylon/pull/292)) (Kai Cataldo) + +Correct indent eslint rule config ([#276](https://github.com/babel/babylon/pull/276)) (Daniel Tschinder) + +Fail tests that have expected.json and throws-option ([#285](https://github.com/babel/babylon/pull/285)) (Daniel Tschinder) + +### :memo: Documentation + +Update contributing with more test info [skip ci] ([#355](https://github.com/babel/babylon/pull/355)) (Brian Ng) + +Update API documentation ([#330](https://github.com/babel/babylon/pull/330)) (Timothy Gu) + +Added keywords to package.json ([#323](https://github.com/babel/babylon/pull/323)) (Dmytro) + +AST spec: fix casing of `RegExpLiteral` ([#318](https://github.com/babel/babylon/pull/318)) (Mathias Bynens) + +## 6.15.0 (2017-01-10) + +### :eyeglasses: Spec Compliance + +Add support for Flow shorthand import type ([#267](https://github.com/babel/babylon/pull/267)) (Jeff Morrison) + +This change implements flows new shorthand import syntax +and where previously you had to write this code: + +```js +import {someValue} from "blah"; +import type {someType} from "blah"; +import typeof {someOtherValue} from "blah"; +``` + +you can now write it like this: + +```js +import { + someValue, + type someType, + typeof someOtherValue, +} from "blah"; +``` + +For more information look at [this](https://github.com/facebook/flow/pull/2890) pull request. + +flow: allow leading pipes in all positions ([#256](https://github.com/babel/babylon/pull/256)) (Vladimir Kurchatkin) + +This change now allows a leading pipe everywhere types can be used: +```js +var f = (x): | 1 | 2 => 1; +``` + +Throw error when exporting non-declaration ([#241](https://github.com/babel/babylon/pull/241)) (Kai Cataldo) + +Previously babylon parsed the following exports, although they are not valid: +```js +export typeof foo; +export new Foo(); +export function() {}; +export for (;;); +export while(foo); +``` + +### :bug: Bug Fix + +Don't set inType flag when parsing property names ([#266](https://github.com/babel/babylon/pull/266)) (Vladimir Kurchatkin) + +This fixes parsing of this case: + +```js +const map = { + [age <= 17] : 'Too young' +}; +``` + +Fix source location for JSXEmptyExpression nodes (fixes #248) ([#249](https://github.com/babel/babylon/pull/249)) (James Long) + +The following case produced an invalid AST +```js +
{/* foo */}
+``` + +Use fromCodePoint to convert high value unicode entities ([#243](https://github.com/babel/babylon/pull/243)) (Ryan Duffy) + +When high value unicode entities (e.g. 💩) were used in the input source code they are now correctly encoded in the resulting AST. + +Rename folder to avoid Windows-illegal characters ([#281](https://github.com/babel/babylon/pull/281)) (Ryan Plant) + +Allow this.state.clone() when parsing decorators ([#262](https://github.com/babel/babylon/pull/262)) (Alex Rattray) + +### :house: Internal + +User external-helpers ([#254](https://github.com/babel/babylon/pull/254)) (Daniel Tschinder) + +Add watch script for dev ([#234](https://github.com/babel/babylon/pull/234)) (Kai Cataldo) + +Freeze current plugins list for "*" option, and remove from README.md ([#245](https://github.com/babel/babylon/pull/245)) (Andrew Levine) + +Prepare tests for multiple fixture runners. ([#240](https://github.com/babel/babylon/pull/240)) (Daniel Tschinder) + +Add some test coverage for decorators stage-0 plugin ([#250](https://github.com/babel/babylon/pull/250)) (Andrew Levine) + +Refactor tokenizer types file ([#263](https://github.com/babel/babylon/pull/263)) (Sven SAULEAU) + +Update eslint-config-babel to the latest version 🚀 ([#273](https://github.com/babel/babylon/pull/273)) (greenkeeper[bot]) + +chore(package): update rollup to version 0.41.0 ([#272](https://github.com/babel/babylon/pull/272)) (greenkeeper[bot]) + +chore(package): update flow-bin to version 0.37.0 ([#255](https://github.com/babel/babylon/pull/255)) (greenkeeper[bot]) + +## 6.14.1 (2016-11-17) + +### :bug: Bug Fix + +Allow `"plugins": ["*"]` ([#229](https://github.com/babel/babylon/pull/229)) (Daniel Tschinder) + +```js +{ + "plugins": ["*"] +} +``` + +Will include all parser plugins instead of specifying each one individually. Useful for tools like babel-eslint, jscodeshift, and ast-explorer. + +## 6.14.0 (2016-11-16) + +### :eyeglasses: Spec Compliance + +Throw error for reserved words `enum` and `await` ([#195](https://github.com/babel/babylon/pull/195)) (Kai Cataldo) + +[11.6.2.2 Future Reserved Words](http://www.ecma-international.org/ecma-262/6.0/#sec-future-reserved-words) + +Babylon will throw for more reserved words such as `enum` or `await` (in strict mode). + +``` +class enum {} // throws +class await {} // throws in strict mode (module) +``` + +Optional names for function types and object type indexers ([#197](https://github.com/babel/babylon/pull/197)) (Gabe Levi) + +So where you used to have to write + +```js +type A = (x: string, y: boolean) => number; +type B = (z: string) => number; +type C = { [key: string]: number }; +``` + +you can now write (with flow 0.34.0) + +```js +type A = (string, boolean) => number; +type B = string => number; +type C = { [string]: number }; +``` + +Parse flow nested array type annotations like `number[][]` ([#219](https://github.com/babel/babylon/pull/219)) (Bernhard Häussner) + +Supports these form now of specifying array types: + +```js +var a: number[][][][]; +var b: string[][]; +``` + +### :bug: Bug Fix + +Correctly eat semicolon at the end of `DelcareModuleExports` ([#223](https://github.com/babel/babylon/pull/223)) (Daniel Tschinder) + +``` +declare module "foo" { declare module.exports: number } +declare module "foo" { declare module.exports: number; } // also allowed now +``` + +### :house: Internal + + * Count Babel tests towards Babylon code coverage ([#182](https://github.com/babel/babylon/pull/182)) (Moti Zilberman) + * Fix strange line endings ([#214](https://github.com/babel/babylon/pull/214)) (Thomas Grainger) + * Add node 7 (Daniel Tschinder) + * chore(package): update flow-bin to version 0.34.0 ([#204](https://github.com/babel/babylon/pull/204)) (Greenkeeper) + +## v6.13.1 (2016-10-26) + +### :nail_care: Polish + +- Use rollup for bundling to speed up startup time ([#190](https://github.com/babel/babylon/pull/190)) ([@drewml](https://github.com/DrewML)) + +```js +const babylon = require('babylon'); +const ast = babylon.parse('var foo = "lol";'); +``` + +With that test case, there was a ~95ms savings by removing the need for node to build/traverse the dependency graph. + +**Without bundling** +![image](https://cloud.githubusercontent.com/assets/5233399/19420264/3133497e-93ad-11e6-9a6a-2da59c4f5c13.png) + +**With bundling** +![image](https://cloud.githubusercontent.com/assets/5233399/19420267/388f556e-93ad-11e6-813e-7c5c396be322.png) + +- add clean command [skip ci] ([#201](https://github.com/babel/babylon/pull/201)) (Henry Zhu) +- add ForAwaitStatement (async generator already added) [skip ci] ([#196](https://github.com/babel/babylon/pull/196)) (Henry Zhu) + +## v6.13.0 (2016-10-21) + +### :eyeglasses: Spec Compliance + +Property variance type annotations for Flow plugin ([#161](https://github.com/babel/babylon/pull/161)) (Sam Goldman) + +> See https://flowtype.org/docs/variance.html for more information + +```js +type T = { +p: T }; +interface T { -p: T }; +declare class T { +[k:K]: V }; +class T { -[k:K]: V }; +class C2 { +p: T = e }; +``` + +Raise error on duplicate definition of __proto__ ([#183](https://github.com/babel/babylon/pull/183)) (Moti Zilberman) + +```js +({ __proto__: 1, __proto__: 2 }) // Throws an error now +``` + +### :bug: Bug Fix + +Flow: Allow class properties to be named `static` ([#184](https://github.com/babel/babylon/pull/184)) (Moti Zilberman) + +```js +declare class A { + static: T; +} +``` + +Allow "async" as identifier for object literal property shorthand ([#187](https://github.com/babel/babylon/pull/187)) (Andrew Levine) + +```js +var foo = { async, bar }; +``` + +### :nail_care: Polish + +Fix flowtype and add inType to state ([#189](https://github.com/babel/babylon/pull/189)) (Daniel Tschinder) + +> This improves the performance slightly (because of hidden classes) + +### :house: Internal + +Fix .gitattributes line ending setting ([#191](https://github.com/babel/babylon/pull/191)) (Moti Zilberman) + +Increase test coverage ([#175](https://github.com/babel/babylon/pull/175) (Moti Zilberman) + +Readd missin .eslinignore for IDEs (Daniel Tschinder) + +Error on missing expected.json fixture in CI ([#188](https://github.com/babel/babylon/pull/188)) (Moti Zilberman) + +Add .gitattributes and .editorconfig for LF line endings ([#179](https://github.com/babel/babylon/pull/179)) (Moti Zilberman) + +Fixes two tests that are failing after the merge of #172 ([#177](https://github.com/babel/babylon/pull/177)) (Moti Zilberman) + +## v6.12.0 (2016-10-14) + +### :eyeglasses: Spec Compliance + +Implement import() syntax ([#163](https://github.com/babel/babylon/pull/163)) (Jordan Gensler) + +#### Dynamic Import + +- Proposal Repo: https://github.com/domenic/proposal-dynamic-import +- Championed by [@domenic](https://github.com/domenic) +- stage-2 +- [sept-28 tc39 notes](https://github.com/rwaldron/tc39-notes/blob/master/es7/2016-09/sept-28.md#113a-import) + +> This repository contains a proposal for adding a "function-like" import() module loading syntactic form to JavaScript + +```js +import(`./section-modules/${link.dataset.entryModule}.js`) +.then(module => { + module.loadPageInto(main); +}) +``` + +Add EmptyTypeAnnotation ([#171](https://github.com/babel/babylon/pull/171)) (Sam Goldman) + +#### EmptyTypeAnnotation + +Just wasn't covered before. + +```js +type T = empty; +``` + +### :bug: Bug Fix + +Fix crash when exporting with destructuring and sparse array ([#170](https://github.com/babel/babylon/pull/170)) (Jeroen Engels) + +```js +// was failing due to sparse array +export const { foo: [ ,, qux7 ] } = bar; +``` + +Allow keyword in Flow object declaration property names with type parameters ([#146](https://github.com/babel/babylon/pull/146)) (Dan Harper) + +```js +declare class X { + foobar(): void; + static foobar(): void; +} +``` + +Allow keyword in object/class property names with Flow type parameters ([#145](https://github.com/babel/babylon/pull/145)) (Dan Harper) + +```js +class Foo { + delete(item: T): T { + return item; + } +} +``` + +Allow typeAnnotations for yield expressions ([#174](https://github.com/babel/babylon/pull/174))) (Daniel Tschinder) + +```js +function *foo() { + const x = (yield 5: any); +} +``` + +### :nail_care: Polish + +Annotate more errors with expected token ([#172](https://github.com/babel/babylon/pull/172))) (Moti Zilberman) + +```js +// Unexpected token, expected ; (1:6) +{ set 1 } +``` + +### :house: Internal + +Remove kcheck ([#173](https://github.com/babel/babylon/pull/173))) (Daniel Tschinder) + +Also run flow, linting, babel tests on separate instances (add back node 0.10) + +## v6.11.6 (2016-10-12) + +### :bug: Bug Fix/Regression + +Fix crash when exporting with destructuring and sparse array ([#170](https://github.com/babel/babylon/pull/170)) (Jeroen Engels) + +```js +// was failing with `Cannot read property 'type' of null` because of null identifiers +export const { foo: [ ,, qux7 ] } = bar; +``` + +## v6.11.5 (2016-10-12) + +### :eyeglasses: Spec Compliance + +Fix: Check for duplicate named exports in exported destructuring assignments ([#144](https://github.com/babel/babylon/pull/144)) (Kai Cataldo) + +```js +// `foo` has already been exported. Exported identifiers must be unique. (2:20) +export function foo() {}; +export const { a: [{foo}] } = bar; +``` + +Fix: Check for duplicate named exports in exported rest elements/properties ([#164](https://github.com/babel/babylon/pull/164)) (Kai Cataldo) + +```js +// `foo` has already been exported. Exported identifiers must be unique. (2:22) +export const foo = 1; +export const [bar, ...foo] = baz; +``` + +### :bug: Bug Fix + +Fix: Allow identifier `async` for default param in arrow expression ([#165](https://github.com/babel/babylon/pull/165)) (Kai Cataldo) + +```js +// this is ok now +const test = ({async = true}) => {}; +``` + +### :nail_care: Polish + +Babylon will now print out the token it's expecting if there's a `SyntaxError` ([#150](https://github.com/babel/babylon/pull/150)) (Daniel Tschinder) + +```bash +# So in the case of a missing ending curly (`}`) +Module build failed: SyntaxError: Unexpected token, expected } (30:0) + 28 | } + 29 | +> 30 | + | ^ +``` + +## v6.11.4 (2016-10-03) + +Temporary rollback for erroring on trailing comma with spread (#154) (Henry Zhu) + +## v6.11.3 (2016-10-01) + +### :eyeglasses: Spec Compliance + +Add static errors for object rest (#149) ([@danez](https://github.com/danez)) + +> https://github.com/sebmarkbage/ecmascript-rest-spread + +Object rest copies the *rest* of properties from the right hand side `obj` starting from the left to right. + +```js +let { x, y, ...z } = { x: 1, y: 2, z: 3 }; +// x = 1 +// y = 2 +// z = { z: 3 } +``` + +#### New Syntax Errors: + +**SyntaxError**: The rest element has to be the last element when destructuring (1:10) +```bash +> 1 | let { ...x, y, z } = { x: 1, y: 2, z: 3}; + | ^ +# Previous behavior: +# x = { x: 1, y: 2, z: 3 } +# y = 2 +# z = 3 +``` + +Before, this was just a more verbose way of shallow copying `obj` since it doesn't actually do what you think. + +**SyntaxError**: Cannot have multiple rest elements when destructuring (1:13) + +```bash +> 1 | let { x, ...y, ...z } = { x: 1, y: 2, z: 3}; + | ^ +# Previous behavior: +# x = 1 +# y = { y: 2, z: 3 } +# z = { y: 2, z: 3 } +``` + +Before y and z would just be the same value anyway so there is no reason to need to have both. + +**SyntaxError**: A trailing comma is not permitted after the rest element (1:16) + +```js +let { x, y, ...z, } = obj; +``` + +The rationale for this is that the use case for trailing comma is that you can add something at the end without affecting the line above. Since a RestProperty always has to be the last property it doesn't make sense. + +--- + +get / set are valid property names in default assignment (#142) ([@jezell](https://github.com/jezell)) + +```js +// valid +function something({ set = null, get = null }) {} +``` + +## v6.11.2 (2016-09-23) + +### Bug Fix + +- [#139](https://github.com/babel/babylon/issues/139) Don't do the duplicate check if not an identifier (#140) @hzoo + +```js +// regression with duplicate export check +SyntaxError: ./typography.js: `undefined` has already been exported. Exported identifiers must be unique. (22:13) + 20 | + 21 | export const { rhythm } = typography; +> 22 | export const { TypographyStyle } = typography +``` + +Bail out for now, and make a change to account for destructuring in the next release. + +## 6.11.1 (2016-09-22) + +### Bug Fix +- [#137](https://github.com/babel/babylon/pull/137) - Fix a regression with duplicate exports - it was erroring on all keys in `Object.prototype`. @danez + +```javascript +export toString from './toString'; +``` + +```bash +`toString` has already been exported. Exported identifiers must be unique. (1:7) +> 1 | export toString from './toString'; + | ^ + 2 | +``` + +## 6.11.0 (2016-09-22) + +### Spec Compliance (will break CI) + +- Disallow duplicate named exports ([#107](https://github.com/babel/babylon/pull/107)) @kaicataldo + +```js +// Only one default export allowed per module. (2:9) +export default function() {}; +export { foo as default }; + +// Only one default export allowed per module. (2:0) +export default {}; +export default function() {}; + +// `Foo` has already been exported. Exported identifiers must be unique. (2:0) +export { Foo }; +export class Foo {}; +``` + +### New Feature (Syntax) + +- Add support for computed class property names ([#121](https://github.com/babel/babylon/pull/121)) @motiz88 + +```js +// AST +interface ClassProperty <: Node { + type: "ClassProperty"; + key: Identifier; + value: Expression; + computed: boolean; // added +} +``` + +```js +// with "plugins": ["classProperties"] +class Foo { + [x] + ['y'] +} + +class Bar { + [p] + [m] () {} +} + ``` + +### Bug Fix + +- Fix `static` property falling through in the declare class Flow AST ([#135](https://github.com/babel/babylon/pull/135)) @danharper + +```js +declare class X { + a: number; + static b: number; // static + c: number; // this was being marked as static in the AST as well +} +``` + +### Polish + +- Rephrase "assigning/binding to rvalue" errors to include context ([#119](https://github.com/babel/babylon/pull/119)) @motiz88 + +```js +// Used to error with: +// SyntaxError: Assigning to rvalue (1:0) + +// Now: +// Invalid left-hand side in assignment expression (1:0) +3 = 4 + +// Invalid left-hand side in for-in statement (1:5) +for (+i in {}); +``` + +### Internal + +- Fix call to `this.parseMaybeAssign` with correct arguments ([#133](https://github.com/babel/babylon/pull/133)) @danez +- Add semver note to changelog ([#131](https://github.com/babel/babylon/pull/131)) @hzoo + +## 6.10.0 (2016-09-19) + +> We plan to include some spec compliance bugs in patch versions. An example was the multiple default exports issue. + +### Spec Compliance + +* Implement ES2016 check for simple parameter list in strict mode ([#106](https://github.com/babel/babylon/pull/106)) (Timothy Gu) + +> It is a Syntax Error if ContainsUseStrict of FunctionBody is true and IsSimpleParameterList of FormalParameters is false. https://tc39.github.io/ecma262/2016/#sec-function-definitions-static-semantics-early-errors + +More Context: [tc39-notes](https://github.com/rwaldron/tc39-notes/blob/master/es7/2015-07/july-29.md#611-the-scope-of-use-strict-with-respect-to-destructuring-in-parameter-lists) + +For example: + +```js +// this errors because it uses destructuring and default parameters +// in a function with a "use strict" directive +function a([ option1, option2 ] = []) { + "use strict"; +} + ``` + +The solution would be to use a top level "use strict" or to remove the destructuring or default parameters when using a function + "use strict" or to. + +### New Feature + +* Exact object type annotations for Flow plugin ([#104](https://github.com/babel/babylon/pull/104)) (Basil Hosmer) + +Added to flow in https://github.com/facebook/flow/commit/c710c40aa2a115435098d6c0dfeaadb023cd39b8 + +Looks like: + +```js +var a : {| x: number, y: string |} = { x: 0, y: 'foo' }; +``` + +### Bug Fixes + +* Include `typeParameter` location in `ArrowFunctionExpression` ([#126](https://github.com/babel/babylon/pull/126)) (Daniel Tschinder) +* Error on invalid flow type annotation with default assignment ([#122](https://github.com/babel/babylon/pull/122)) (Dan Harper) +* Fix Flow return types on arrow functions ([#124](https://github.com/babel/babylon/pull/124)) (Dan Harper) + +### Misc + +* Add tests for export extensions ([#127](https://github.com/babel/babylon/pull/127)) (Daniel Tschinder) +* Fix Contributing guidelines [skip ci] (Daniel Tschinder) + +## 6.9.2 (2016-09-09) + +The only change is to remove the `babel-runtime` dependency by compiling with Babel's ES2015 loose mode. So using babylon standalone should be smaller. + +## 6.9.1 (2016-08-23) + +This release contains mainly small bugfixes but also updates babylons default mode to es2017. The features for `exponentiationOperator`, `asyncFunctions` and `trailingFunctionCommas` which previously needed to be activated via plugin are now enabled by default and the plugins are now no-ops. + +### Bug Fixes + +- Fix issues with default object params in async functions ([#96](https://github.com/babel/babylon/pull/96)) @danez +- Fix issues with flow-types and async function ([#95](https://github.com/babel/babylon/pull/95)) @danez +- Fix arrow functions with destructuring, types & default value ([#94](https://github.com/babel/babylon/pull/94)) @danharper +- Fix declare class with qualified type identifier ([#97](https://github.com/babel/babylon/pull/97)) @danez +- Remove exponentiationOperator, asyncFunctions, trailingFunctionCommas plugins and enable them by default ([#98](https://github.com/babel/babylon/pull/98)) @danez + +## 6.9.0 (2016-08-16) + +### New syntax support + +- Add JSX spread children ([#42](https://github.com/babel/babylon/pull/42)) @calebmer + +(Be aware that React is not going to support this syntax) + +```js +
+ {...todos.map(todo => )} +
+``` + +- Add support for declare module.exports ([#72](https://github.com/babel/babylon/pull/72)) @danez + +```js +declare module "foo" { + declare module.exports: {} +} +``` + +### New Features + +- If supplied, attach filename property to comment node loc. ([#80](https://github.com/babel/babylon/pull/80)) @divmain +- Add identifier name to node loc field ([#90](https://github.com/babel/babylon/pull/90)) @kittens + +### Bug Fixes + +- Fix exponential operator to behave according to spec ([#75](https://github.com/babel/babylon/pull/75)) @danez +- Fix lookahead to not add comments to arrays which are not cloned ([#76](https://github.com/babel/babylon/pull/76)) @danez +- Fix accidental fall-through in Flow type parsing. ([#82](https://github.com/babel/babylon/pull/82)) @xiemaisi +- Only allow declares inside declare module ([#73](https://github.com/babel/babylon/pull/73)) @danez +- Small fix for parsing type parameter declarations ([#83](https://github.com/babel/babylon/pull/83)) @gabelevi +- Fix arrow param locations with flow types ([#57](https://github.com/babel/babylon/pull/57)) @danez +- Fixes SyntaxError position with flow optional type ([#65](https://github.com/babel/babylon/pull/65)) @danez + +### Internal + +- Add codecoverage to tests @danez +- Fix tests to not save expected output if we expect the test to fail @danez +- Make a shallow clone of babel for testing @danez +- chore(package): update cross-env to version 2.0.0 ([#77](https://github.com/babel/babylon/pull/77)) @greenkeeperio-bot +- chore(package): update ava to version 0.16.0 ([#86](https://github.com/babel/babylon/pull/86)) @greenkeeperio-bot +- chore(package): update babel-plugin-istanbul to version 2.0.0 ([#89](https://github.com/babel/babylon/pull/89)) @greenkeeperio-bot +- chore(package): update nyc to version 8.0.0 ([#88](https://github.com/babel/babylon/pull/88)) @greenkeeperio-bot + +## 6.8.4 (2016-07-06) + +### Bug Fixes + +- Fix the location of params, when flow and default value used ([#68](https://github.com/babel/babylon/pull/68)) @danez + +## 6.8.3 (2016-07-02) + +### Bug Fixes + +- Fix performance regression introduced in 6.8.2 with conditionals ([#63](https://github.com/babel/babylon/pull/63)) @danez + +## 6.8.2 (2016-06-24) + +### Bug Fixes + +- Fix parse error with yielding jsx elements in generators `function* it() { yield ; }` ([#31](https://github.com/babel/babylon/pull/31)) @eldereal +- When cloning nodes do not clone its comments ([#24](https://github.com/babel/babylon/pull/24)) @danez +- Fix parse errors when using arrow functions with an spread element and return type `(...props): void => {}` ([#10](https://github.com/babel/babylon/pull/10)) @danez +- Fix leading comments added from previous node ([#23](https://github.com/babel/babylon/pull/23)) @danez +- Fix parse errors with flow's optional arguments `(arg?) => {}` ([#19](https://github.com/babel/babylon/pull/19)) @danez +- Support negative numeric type literals @kittens +- Remove line terminator restriction after await keyword @kittens +- Remove grouped type arrow restriction as it seems flow no longer has it @kittens +- Fix parse error with generic methods that have the name `get` or `set` `class foo { get() {} }` ([#55](https://github.com/babel/babylon/pull/55)) @vkurchatkin +- Fix parse error with arrow functions that have flow type parameter declarations `(x: T): T => x;` ([#54](https://github.com/babel/babylon/pull/54)) @gabelevi + +### Documentation + +- Document AST differences from ESTree ([#41](https://github.com/babel/babylon/pull/41)) @nene +- Move ast spec from babel/babel ([#46](https://github.com/babel/babylon/pull/46)) @hzoo + +### Internal + +- Enable skipped tests ([#16](https://github.com/babel/babylon/pull/16)) @danez +- Add script to test latest version of babylon with babel ([#21](https://github.com/babel/babylon/pull/21)) @danez +- Upgrade test runner ava @kittens +- Add missing generate-identifier-regex script @kittens +- Rename parser context types @kittens +- Add node v6 to travis testing @hzoo +- Update to Unicode v9 ([#45](https://github.com/babel/babylon/pull/45)) @mathiasbynens + +## 6.8.1 (2016-06-06) + +### New Feature + +- Parse type parameter declarations with defaults like `type Foo = T` + +### Bug Fixes +- Type parameter declarations need 1 or more type parameters. +- The existential type `*` is not a valid type parameter. +- The existential type `*` is a primary type + +### Spec Compliance +- The param list for type parameter declarations now consists of `TypeParameter` nodes +- New `TypeParameter` AST Node (replaces using the `Identifier` node before) + +``` +interface TypeParameter <: Node { + bound: TypeAnnotation; + default: TypeAnnotation; + name: string; + variance: "plus" | "minus"; +} +``` + +## 6.8.0 (2016-05-02) + +#### New Feature + +##### Parse Method Parameter Decorators ([#12](https://github.com/babel/babylon/pull/12)) + +> [Method Parameter Decorators](https://goo.gl/8MmCMG) is now a TC39 [stage 0 proposal](https://github.com/tc39/ecma262/blob/master/stage0.md). + +Examples: + +```js +class Foo { + constructor(@foo() x, @bar({ a: 123 }) @baz() y) {} +} + +export default function func(@foo() x, @bar({ a: 123 }) @baz() y) {} + +var obj = { + method(@foo() x, @bar({ a: 123 }) @baz() y) {} +}; +``` + +##### Parse for-await statements (w/ `asyncGenerators` plugin) ([#17](https://github.com/babel/babylon/pull/17)) + +There is also a new node type, `ForAwaitStatement`. + +> [Async generators and for-await](https://github.com/tc39/proposal-async-iteration) are now a [stage 2 proposal](https://github.com/tc39/ecma262#current-proposals). + +Example: + +```js +async function f() { + for await (let x of y); +} +``` diff --git a/libcore/node_modules/@babel/parser/LICENSE b/libcore/node_modules/@babel/parser/LICENSE new file mode 100644 index 0000000..d4c7fc5 --- /dev/null +++ b/libcore/node_modules/@babel/parser/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2012-2014 by various contributors (see AUTHORS) + +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. diff --git a/libcore/node_modules/@babel/parser/README.md b/libcore/node_modules/@babel/parser/README.md new file mode 100644 index 0000000..a9463e8 --- /dev/null +++ b/libcore/node_modules/@babel/parser/README.md @@ -0,0 +1,19 @@ +# @babel/parser + +> A JavaScript parser + +See our website [@babel/parser](https://babeljs.io/docs/babel-parser) for more information or the [issues](https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+label%3A%22pkg%3A%20parser%22+is%3Aopen) associated with this package. + +## Install + +Using npm: + +```sh +npm install --save-dev @babel/parser +``` + +or using yarn: + +```sh +yarn add @babel/parser --dev +``` diff --git a/libcore/node_modules/@babel/parser/bin/babel-parser.js b/libcore/node_modules/@babel/parser/bin/babel-parser.js new file mode 100755 index 0000000..3aca314 --- /dev/null +++ b/libcore/node_modules/@babel/parser/bin/babel-parser.js @@ -0,0 +1,15 @@ +#!/usr/bin/env node +/* eslint no-var: 0 */ + +var parser = require(".."); +var fs = require("fs"); + +var filename = process.argv[2]; +if (!filename) { + console.error("no filename specified"); +} else { + var file = fs.readFileSync(filename, "utf8"); + var ast = parser.parse(file); + + console.log(JSON.stringify(ast, null, " ")); +} diff --git a/libcore/node_modules/@babel/parser/index.cjs b/libcore/node_modules/@babel/parser/index.cjs new file mode 100644 index 0000000..89863a9 --- /dev/null +++ b/libcore/node_modules/@babel/parser/index.cjs @@ -0,0 +1,5 @@ +try { + module.exports = require("./lib/index.cjs"); +} catch { + module.exports = require("./lib/index.js"); +} diff --git a/libcore/node_modules/@babel/parser/lib/index.js b/libcore/node_modules/@babel/parser/lib/index.js new file mode 100644 index 0000000..3b5c6bc --- /dev/null +++ b/libcore/node_modules/@babel/parser/lib/index.js @@ -0,0 +1,14009 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +function _objectWithoutPropertiesLoose(r, e) { + if (null == r) return {}; + var t = {}; + for (var n in r) if ({}.hasOwnProperty.call(r, n)) { + if (e.includes(n)) continue; + t[n] = r[n]; + } + return t; +} +class Position { + constructor(line, col, index) { + this.line = void 0; + this.column = void 0; + this.index = void 0; + this.line = line; + this.column = col; + this.index = index; + } +} +class SourceLocation { + constructor(start, end) { + this.start = void 0; + this.end = void 0; + this.filename = void 0; + this.identifierName = void 0; + this.start = start; + this.end = end; + } +} +function createPositionWithColumnOffset(position, columnOffset) { + const { + line, + column, + index + } = position; + return new Position(line, column + columnOffset, index + columnOffset); +} +const code = "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"; +var ModuleErrors = { + ImportMetaOutsideModule: { + message: `import.meta may appear only with 'sourceType: "module"'`, + code + }, + ImportOutsideModule: { + message: `'import' and 'export' may appear only with 'sourceType: "module"'`, + code + } +}; +const NodeDescriptions = { + ArrayPattern: "array destructuring pattern", + AssignmentExpression: "assignment expression", + AssignmentPattern: "assignment expression", + ArrowFunctionExpression: "arrow function expression", + ConditionalExpression: "conditional expression", + CatchClause: "catch clause", + ForOfStatement: "for-of statement", + ForInStatement: "for-in statement", + ForStatement: "for-loop", + FormalParameters: "function parameter list", + Identifier: "identifier", + ImportSpecifier: "import specifier", + ImportDefaultSpecifier: "import default specifier", + ImportNamespaceSpecifier: "import namespace specifier", + ObjectPattern: "object destructuring pattern", + ParenthesizedExpression: "parenthesized expression", + RestElement: "rest element", + UpdateExpression: { + true: "prefix operation", + false: "postfix operation" + }, + VariableDeclarator: "variable declaration", + YieldExpression: "yield expression" +}; +const toNodeDescription = node => node.type === "UpdateExpression" ? NodeDescriptions.UpdateExpression[`${node.prefix}`] : NodeDescriptions[node.type]; +var StandardErrors = { + AccessorIsGenerator: ({ + kind + }) => `A ${kind}ter cannot be a generator.`, + ArgumentsInClass: "'arguments' is only allowed in functions and class methods.", + AsyncFunctionInSingleStatementContext: "Async functions can only be declared at the top level or inside a block.", + AwaitBindingIdentifier: "Can not use 'await' as identifier inside an async function.", + AwaitBindingIdentifierInStaticBlock: "Can not use 'await' as identifier inside a static block.", + AwaitExpressionFormalParameter: "'await' is not allowed in async function parameters.", + AwaitUsingNotInAsyncContext: "'await using' is only allowed within async functions and at the top levels of modules.", + AwaitNotInAsyncContext: "'await' is only allowed within async functions and at the top levels of modules.", + AwaitNotInAsyncFunction: "'await' is only allowed within async functions.", + BadGetterArity: "A 'get' accessor must not have any formal parameters.", + BadSetterArity: "A 'set' accessor must have exactly one formal parameter.", + BadSetterRestParameter: "A 'set' accessor function argument must not be a rest parameter.", + ConstructorClassField: "Classes may not have a field named 'constructor'.", + ConstructorClassPrivateField: "Classes may not have a private field named '#constructor'.", + ConstructorIsAccessor: "Class constructor may not be an accessor.", + ConstructorIsAsync: "Constructor can't be an async function.", + ConstructorIsGenerator: "Constructor can't be a generator.", + DeclarationMissingInitializer: ({ + kind + }) => `Missing initializer in ${kind} declaration.`, + DecoratorArgumentsOutsideParentheses: "Decorator arguments must be moved inside parentheses: use '@(decorator(args))' instead of '@(decorator)(args)'.", + DecoratorBeforeExport: "Decorators must be placed *before* the 'export' keyword. Remove the 'decoratorsBeforeExport: true' option to use the 'export @decorator class {}' syntax.", + DecoratorsBeforeAfterExport: "Decorators can be placed *either* before or after the 'export' keyword, but not in both locations at the same time.", + DecoratorConstructor: "Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?", + DecoratorExportClass: "Decorators must be placed *after* the 'export' keyword. Remove the 'decoratorsBeforeExport: false' option to use the '@decorator export class {}' syntax.", + DecoratorSemicolon: "Decorators must not be followed by a semicolon.", + DecoratorStaticBlock: "Decorators can't be used with a static block.", + DeferImportRequiresNamespace: 'Only `import defer * as x from "./module"` is valid.', + DeletePrivateField: "Deleting a private field is not allowed.", + DestructureNamedImport: "ES2015 named imports do not destructure. Use another statement for destructuring after the import.", + DuplicateConstructor: "Duplicate constructor in the same class.", + DuplicateDefaultExport: "Only one default export allowed per module.", + DuplicateExport: ({ + exportName + }) => `\`${exportName}\` has already been exported. Exported identifiers must be unique.`, + DuplicateProto: "Redefinition of __proto__ property.", + DuplicateRegExpFlags: "Duplicate regular expression flag.", + DynamicImportPhaseRequiresImportExpressions: ({ + phase + }) => `'import.${phase}(...)' can only be parsed when using the 'createImportExpressions' option.`, + ElementAfterRest: "Rest element must be last element.", + EscapedCharNotAnIdentifier: "Invalid Unicode escape.", + ExportBindingIsString: ({ + localName, + exportName + }) => `A string literal cannot be used as an exported binding without \`from\`.\n- Did you mean \`export { '${localName}' as '${exportName}' } from 'some-module'\`?`, + ExportDefaultFromAsIdentifier: "'from' is not allowed as an identifier after 'export default'.", + ForInOfLoopInitializer: ({ + type + }) => `'${type === "ForInStatement" ? "for-in" : "for-of"}' loop variable declaration may not have an initializer.`, + ForInUsing: "For-in loop may not start with 'using' declaration.", + ForOfAsync: "The left-hand side of a for-of loop may not be 'async'.", + ForOfLet: "The left-hand side of a for-of loop may not start with 'let'.", + GeneratorInSingleStatementContext: "Generators can only be declared at the top level or inside a block.", + IllegalBreakContinue: ({ + type + }) => `Unsyntactic ${type === "BreakStatement" ? "break" : "continue"}.`, + IllegalLanguageModeDirective: "Illegal 'use strict' directive in function with non-simple parameter list.", + IllegalReturn: "'return' outside of function.", + ImportAttributesUseAssert: "The `assert` keyword in import attributes is deprecated and it has been replaced by the `with` keyword. You can enable the `deprecatedAssertSyntax: true` option in the import attributes plugin to suppress this error.", + ImportBindingIsString: ({ + importName + }) => `A string literal cannot be used as an imported binding.\n- Did you mean \`import { "${importName}" as foo }\`?`, + ImportCallArgumentTrailingComma: "Trailing comma is disallowed inside import(...) arguments.", + ImportCallArity: ({ + maxArgumentCount + }) => `\`import()\` requires exactly ${maxArgumentCount === 1 ? "one argument" : "one or two arguments"}.`, + ImportCallNotNewExpression: "Cannot use new with import(...).", + ImportCallSpreadArgument: "`...` is not allowed in `import()`.", + ImportJSONBindingNotDefault: "A JSON module can only be imported with `default`.", + ImportReflectionHasAssertion: "`import module x` cannot have assertions.", + ImportReflectionNotBinding: 'Only `import module x from "./module"` is valid.', + IncompatibleRegExpUVFlags: "The 'u' and 'v' regular expression flags cannot be enabled at the same time.", + InvalidBigIntLiteral: "Invalid BigIntLiteral.", + InvalidCodePoint: "Code point out of bounds.", + InvalidCoverInitializedName: "Invalid shorthand property initializer.", + InvalidDecimal: "Invalid decimal.", + InvalidDigit: ({ + radix + }) => `Expected number in radix ${radix}.`, + InvalidEscapeSequence: "Bad character escape sequence.", + InvalidEscapeSequenceTemplate: "Invalid escape sequence in template.", + InvalidEscapedReservedWord: ({ + reservedWord + }) => `Escape sequence in keyword ${reservedWord}.`, + InvalidIdentifier: ({ + identifierName + }) => `Invalid identifier ${identifierName}.`, + InvalidLhs: ({ + ancestor + }) => `Invalid left-hand side in ${toNodeDescription(ancestor)}.`, + InvalidLhsBinding: ({ + ancestor + }) => `Binding invalid left-hand side in ${toNodeDescription(ancestor)}.`, + InvalidLhsOptionalChaining: ({ + ancestor + }) => `Invalid optional chaining in the left-hand side of ${toNodeDescription(ancestor)}.`, + InvalidNumber: "Invalid number.", + InvalidOrMissingExponent: "Floating-point numbers require a valid exponent after the 'e'.", + InvalidOrUnexpectedToken: ({ + unexpected + }) => `Unexpected character '${unexpected}'.`, + InvalidParenthesizedAssignment: "Invalid parenthesized assignment pattern.", + InvalidPrivateFieldResolution: ({ + identifierName + }) => `Private name #${identifierName} is not defined.`, + InvalidPropertyBindingPattern: "Binding member expression.", + InvalidRecordProperty: "Only properties and spread elements are allowed in record definitions.", + InvalidRestAssignmentPattern: "Invalid rest operator's argument.", + LabelRedeclaration: ({ + labelName + }) => `Label '${labelName}' is already declared.`, + LetInLexicalBinding: "'let' is disallowed as a lexically bound name.", + LineTerminatorBeforeArrow: "No line break is allowed before '=>'.", + MalformedRegExpFlags: "Invalid regular expression flag.", + MissingClassName: "A class name is required.", + MissingEqInAssignment: "Only '=' operator can be used for specifying default value.", + MissingSemicolon: "Missing semicolon.", + MissingPlugin: ({ + missingPlugin + }) => `This experimental syntax requires enabling the parser plugin: ${missingPlugin.map(name => JSON.stringify(name)).join(", ")}.`, + MissingOneOfPlugins: ({ + missingPlugin + }) => `This experimental syntax requires enabling one of the following parser plugin(s): ${missingPlugin.map(name => JSON.stringify(name)).join(", ")}.`, + MissingUnicodeEscape: "Expecting Unicode escape sequence \\uXXXX.", + MixingCoalesceWithLogical: "Nullish coalescing operator(??) requires parens when mixing with logical operators.", + ModuleAttributeDifferentFromType: "The only accepted module attribute is `type`.", + ModuleAttributeInvalidValue: "Only string literals are allowed as module attribute values.", + ModuleAttributesWithDuplicateKeys: ({ + key + }) => `Duplicate key "${key}" is not allowed in module attributes.`, + ModuleExportNameHasLoneSurrogate: ({ + surrogateCharCode + }) => `An export name cannot include a lone surrogate, found '\\u${surrogateCharCode.toString(16)}'.`, + ModuleExportUndefined: ({ + localName + }) => `Export '${localName}' is not defined.`, + MultipleDefaultsInSwitch: "Multiple default clauses.", + NewlineAfterThrow: "Illegal newline after throw.", + NoCatchOrFinally: "Missing catch or finally clause.", + NumberIdentifier: "Identifier directly after number.", + NumericSeparatorInEscapeSequence: "Numeric separators are not allowed inside unicode escape sequences or hex escape sequences.", + ObsoleteAwaitStar: "'await*' has been removed from the async functions proposal. Use Promise.all() instead.", + OptionalChainingNoNew: "Constructors in/after an Optional Chain are not allowed.", + OptionalChainingNoTemplate: "Tagged Template Literals are not allowed in optionalChain.", + OverrideOnConstructor: "'override' modifier cannot appear on a constructor declaration.", + ParamDupe: "Argument name clash.", + PatternHasAccessor: "Object pattern can't contain getter or setter.", + PatternHasMethod: "Object pattern can't contain methods.", + PrivateInExpectedIn: ({ + identifierName + }) => `Private names are only allowed in property accesses (\`obj.#${identifierName}\`) or in \`in\` expressions (\`#${identifierName} in obj\`).`, + PrivateNameRedeclaration: ({ + identifierName + }) => `Duplicate private name #${identifierName}.`, + RecordExpressionBarIncorrectEndSyntaxType: "Record expressions ending with '|}' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.", + RecordExpressionBarIncorrectStartSyntaxType: "Record expressions starting with '{|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.", + RecordExpressionHashIncorrectStartSyntaxType: "Record expressions starting with '#{' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.", + RecordNoProto: "'__proto__' is not allowed in Record expressions.", + RestTrailingComma: "Unexpected trailing comma after rest element.", + SloppyFunction: "In non-strict mode code, functions can only be declared at top level or inside a block.", + SloppyFunctionAnnexB: "In non-strict mode code, functions can only be declared at top level, inside a block, or as the body of an if statement.", + SourcePhaseImportRequiresDefault: 'Only `import source x from "./module"` is valid.', + StaticPrototype: "Classes may not have static property named prototype.", + SuperNotAllowed: "`super()` is only valid inside a class constructor of a subclass. Maybe a typo in the method name ('constructor') or not extending another class?", + SuperPrivateField: "Private fields can't be accessed on super.", + TrailingDecorator: "Decorators must be attached to a class element.", + TupleExpressionBarIncorrectEndSyntaxType: "Tuple expressions ending with '|]' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.", + TupleExpressionBarIncorrectStartSyntaxType: "Tuple expressions starting with '[|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.", + TupleExpressionHashIncorrectStartSyntaxType: "Tuple expressions starting with '#[' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.", + UnexpectedArgumentPlaceholder: "Unexpected argument placeholder.", + UnexpectedAwaitAfterPipelineBody: 'Unexpected "await" after pipeline body; await must have parentheses in minimal proposal.', + UnexpectedDigitAfterHash: "Unexpected digit after hash token.", + UnexpectedImportExport: "'import' and 'export' may only appear at the top level.", + UnexpectedKeyword: ({ + keyword + }) => `Unexpected keyword '${keyword}'.`, + UnexpectedLeadingDecorator: "Leading decorators must be attached to a class declaration.", + UnexpectedLexicalDeclaration: "Lexical declaration cannot appear in a single-statement context.", + UnexpectedNewTarget: "`new.target` can only be used in functions or class properties.", + UnexpectedNumericSeparator: "A numeric separator is only allowed between two digits.", + UnexpectedPrivateField: "Unexpected private name.", + UnexpectedReservedWord: ({ + reservedWord + }) => `Unexpected reserved word '${reservedWord}'.`, + UnexpectedSuper: "'super' is only allowed in object methods and classes.", + UnexpectedToken: ({ + expected, + unexpected + }) => `Unexpected token${unexpected ? ` '${unexpected}'.` : ""}${expected ? `, expected "${expected}"` : ""}`, + UnexpectedTokenUnaryExponentiation: "Illegal expression. Wrap left hand side or entire exponentiation in parentheses.", + UnexpectedUsingDeclaration: "Using declaration cannot appear in the top level when source type is `script`.", + UnsupportedBind: "Binding should be performed on object property.", + UnsupportedDecoratorExport: "A decorated export must export a class declaration.", + UnsupportedDefaultExport: "Only expressions, functions or classes are allowed as the `default` export.", + UnsupportedImport: "`import` can only be used in `import()` or `import.meta`.", + UnsupportedMetaProperty: ({ + target, + onlyValidPropertyName + }) => `The only valid meta property for ${target} is ${target}.${onlyValidPropertyName}.`, + UnsupportedParameterDecorator: "Decorators cannot be used to decorate parameters.", + UnsupportedPropertyDecorator: "Decorators cannot be used to decorate object literal properties.", + UnsupportedSuper: "'super' can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop]).", + UnterminatedComment: "Unterminated comment.", + UnterminatedRegExp: "Unterminated regular expression.", + UnterminatedString: "Unterminated string constant.", + UnterminatedTemplate: "Unterminated template.", + UsingDeclarationExport: "Using declaration cannot be exported.", + UsingDeclarationHasBindingPattern: "Using declaration cannot have destructuring patterns.", + VarRedeclaration: ({ + identifierName + }) => `Identifier '${identifierName}' has already been declared.`, + YieldBindingIdentifier: "Can not use 'yield' as identifier inside a generator.", + YieldInParameter: "Yield expression is not allowed in formal parameters.", + ZeroDigitNumericSeparator: "Numeric separator can not be used after leading 0." +}; +var StrictModeErrors = { + StrictDelete: "Deleting local variable in strict mode.", + StrictEvalArguments: ({ + referenceName + }) => `Assigning to '${referenceName}' in strict mode.`, + StrictEvalArgumentsBinding: ({ + bindingName + }) => `Binding '${bindingName}' in strict mode.`, + StrictFunction: "In strict mode code, functions can only be declared at top level or inside a block.", + StrictNumericEscape: "The only valid numeric escape in strict mode is '\\0'.", + StrictOctalLiteral: "Legacy octal literals are not allowed in strict mode.", + StrictWith: "'with' in strict mode." +}; +const UnparenthesizedPipeBodyDescriptions = new Set(["ArrowFunctionExpression", "AssignmentExpression", "ConditionalExpression", "YieldExpression"]); +var PipelineOperatorErrors = { + PipeBodyIsTighter: "Unexpected yield after pipeline body; any yield expression acting as Hack-style pipe body must be parenthesized due to its loose operator precedence.", + PipeTopicRequiresHackPipes: 'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.', + PipeTopicUnbound: "Topic reference is unbound; it must be inside a pipe body.", + PipeTopicUnconfiguredToken: ({ + token + }) => `Invalid topic token ${token}. In order to use ${token} as a topic reference, the pipelineOperator plugin must be configured with { "proposal": "hack", "topicToken": "${token}" }.`, + PipeTopicUnused: "Hack-style pipe body does not contain a topic reference; Hack-style pipes must use topic at least once.", + PipeUnparenthesizedBody: ({ + type + }) => `Hack-style pipe body cannot be an unparenthesized ${toNodeDescription({ + type + })}; please wrap it in parentheses.`, + PipelineBodyNoArrow: 'Unexpected arrow "=>" after pipeline body; arrow function in pipeline body must be parenthesized.', + PipelineBodySequenceExpression: "Pipeline body may not be a comma-separated sequence expression.", + PipelineHeadSequenceExpression: "Pipeline head should not be a comma-separated sequence expression.", + PipelineTopicUnused: "Pipeline is in topic style but does not use topic reference.", + PrimaryTopicNotAllowed: "Topic reference was used in a lexical context without topic binding.", + PrimaryTopicRequiresSmartPipeline: 'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.' +}; +const _excluded = ["message"]; +function defineHidden(obj, key, value) { + Object.defineProperty(obj, key, { + enumerable: false, + configurable: true, + value + }); +} +function toParseErrorConstructor({ + toMessage, + code, + reasonCode, + syntaxPlugin +}) { + const hasMissingPlugin = reasonCode === "MissingPlugin" || reasonCode === "MissingOneOfPlugins"; + { + const oldReasonCodes = { + AccessorCannotDeclareThisParameter: "AccesorCannotDeclareThisParameter", + AccessorCannotHaveTypeParameters: "AccesorCannotHaveTypeParameters", + ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference: "ConstInitiailizerMustBeStringOrNumericLiteralOrLiteralEnumReference", + SetAccessorCannotHaveOptionalParameter: "SetAccesorCannotHaveOptionalParameter", + SetAccessorCannotHaveRestParameter: "SetAccesorCannotHaveRestParameter", + SetAccessorCannotHaveReturnType: "SetAccesorCannotHaveReturnType" + }; + if (oldReasonCodes[reasonCode]) { + reasonCode = oldReasonCodes[reasonCode]; + } + } + return function constructor(loc, details) { + const error = new SyntaxError(); + error.code = code; + error.reasonCode = reasonCode; + error.loc = loc; + error.pos = loc.index; + error.syntaxPlugin = syntaxPlugin; + if (hasMissingPlugin) { + error.missingPlugin = details.missingPlugin; + } + defineHidden(error, "clone", function clone(overrides = {}) { + var _overrides$loc; + const { + line, + column, + index + } = (_overrides$loc = overrides.loc) != null ? _overrides$loc : loc; + return constructor(new Position(line, column, index), Object.assign({}, details, overrides.details)); + }); + defineHidden(error, "details", details); + Object.defineProperty(error, "message", { + configurable: true, + get() { + const message = `${toMessage(details)} (${loc.line}:${loc.column})`; + this.message = message; + return message; + }, + set(value) { + Object.defineProperty(this, "message", { + value, + writable: true + }); + } + }); + return error; + }; +} +function ParseErrorEnum(argument, syntaxPlugin) { + if (Array.isArray(argument)) { + return parseErrorTemplates => ParseErrorEnum(parseErrorTemplates, argument[0]); + } + const ParseErrorConstructors = {}; + for (const reasonCode of Object.keys(argument)) { + const template = argument[reasonCode]; + const _ref = typeof template === "string" ? { + message: () => template + } : typeof template === "function" ? { + message: template + } : template, + { + message + } = _ref, + rest = _objectWithoutPropertiesLoose(_ref, _excluded); + const toMessage = typeof message === "string" ? () => message : message; + ParseErrorConstructors[reasonCode] = toParseErrorConstructor(Object.assign({ + code: "BABEL_PARSER_SYNTAX_ERROR", + reasonCode, + toMessage + }, syntaxPlugin ? { + syntaxPlugin + } : {}, rest)); + } + return ParseErrorConstructors; +} +const Errors = Object.assign({}, ParseErrorEnum(ModuleErrors), ParseErrorEnum(StandardErrors), ParseErrorEnum(StrictModeErrors), ParseErrorEnum`pipelineOperator`(PipelineOperatorErrors)); +const { + defineProperty +} = Object; +const toUnenumerable = (object, key) => { + if (object) { + defineProperty(object, key, { + enumerable: false, + value: object[key] + }); + } +}; +function toESTreeLocation(node) { + toUnenumerable(node.loc.start, "index"); + toUnenumerable(node.loc.end, "index"); + return node; +} +var estree = superClass => class ESTreeParserMixin extends superClass { + parse() { + const file = toESTreeLocation(super.parse()); + if (this.options.tokens) { + file.tokens = file.tokens.map(toESTreeLocation); + } + return file; + } + parseRegExpLiteral({ + pattern, + flags + }) { + let regex = null; + try { + regex = new RegExp(pattern, flags); + } catch (_) {} + const node = this.estreeParseLiteral(regex); + node.regex = { + pattern, + flags + }; + return node; + } + parseBigIntLiteral(value) { + let bigInt; + try { + bigInt = BigInt(value); + } catch (_unused) { + bigInt = null; + } + const node = this.estreeParseLiteral(bigInt); + node.bigint = String(node.value || value); + return node; + } + parseDecimalLiteral(value) { + const decimal = null; + const node = this.estreeParseLiteral(decimal); + node.decimal = String(node.value || value); + return node; + } + estreeParseLiteral(value) { + return this.parseLiteral(value, "Literal"); + } + parseStringLiteral(value) { + return this.estreeParseLiteral(value); + } + parseNumericLiteral(value) { + return this.estreeParseLiteral(value); + } + parseNullLiteral() { + return this.estreeParseLiteral(null); + } + parseBooleanLiteral(value) { + return this.estreeParseLiteral(value); + } + directiveToStmt(directive) { + const expression = directive.value; + delete directive.value; + expression.type = "Literal"; + expression.raw = expression.extra.raw; + expression.value = expression.extra.expressionValue; + const stmt = directive; + stmt.type = "ExpressionStatement"; + stmt.expression = expression; + stmt.directive = expression.extra.rawValue; + delete expression.extra; + return stmt; + } + initFunction(node, isAsync) { + super.initFunction(node, isAsync); + node.expression = false; + } + checkDeclaration(node) { + if (node != null && this.isObjectProperty(node)) { + this.checkDeclaration(node.value); + } else { + super.checkDeclaration(node); + } + } + getObjectOrClassMethodParams(method) { + return method.value.params; + } + isValidDirective(stmt) { + var _stmt$expression$extr; + return stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && typeof stmt.expression.value === "string" && !((_stmt$expression$extr = stmt.expression.extra) != null && _stmt$expression$extr.parenthesized); + } + parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse) { + super.parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse); + const directiveStatements = node.directives.map(d => this.directiveToStmt(d)); + node.body = directiveStatements.concat(node.body); + delete node.directives; + } + pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) { + this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true); + if (method.typeParameters) { + method.value.typeParameters = method.typeParameters; + delete method.typeParameters; + } + classBody.body.push(method); + } + parsePrivateName() { + const node = super.parsePrivateName(); + { + if (!this.getPluginOption("estree", "classFeatures")) { + return node; + } + } + return this.convertPrivateNameToPrivateIdentifier(node); + } + convertPrivateNameToPrivateIdentifier(node) { + const name = super.getPrivateNameSV(node); + node = node; + delete node.id; + node.name = name; + node.type = "PrivateIdentifier"; + return node; + } + isPrivateName(node) { + { + if (!this.getPluginOption("estree", "classFeatures")) { + return super.isPrivateName(node); + } + } + return node.type === "PrivateIdentifier"; + } + getPrivateNameSV(node) { + { + if (!this.getPluginOption("estree", "classFeatures")) { + return super.getPrivateNameSV(node); + } + } + return node.name; + } + parseLiteral(value, type) { + const node = super.parseLiteral(value, type); + node.raw = node.extra.raw; + delete node.extra; + return node; + } + parseFunctionBody(node, allowExpression, isMethod = false) { + super.parseFunctionBody(node, allowExpression, isMethod); + node.expression = node.body.type !== "BlockStatement"; + } + parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) { + let funcNode = this.startNode(); + funcNode.kind = node.kind; + funcNode = super.parseMethod(funcNode, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope); + funcNode.type = "FunctionExpression"; + delete funcNode.kind; + node.value = funcNode; + if (type === "ClassPrivateMethod") { + node.computed = false; + } + return this.finishNode(node, "MethodDefinition"); + } + nameIsConstructor(key) { + if (key.type === "Literal") return key.value === "constructor"; + return super.nameIsConstructor(key); + } + parseClassProperty(...args) { + const propertyNode = super.parseClassProperty(...args); + { + if (!this.getPluginOption("estree", "classFeatures")) { + return propertyNode; + } + } + propertyNode.type = "PropertyDefinition"; + return propertyNode; + } + parseClassPrivateProperty(...args) { + const propertyNode = super.parseClassPrivateProperty(...args); + { + if (!this.getPluginOption("estree", "classFeatures")) { + return propertyNode; + } + } + propertyNode.type = "PropertyDefinition"; + propertyNode.computed = false; + return propertyNode; + } + parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) { + const node = super.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor); + if (node) { + node.type = "Property"; + if (node.kind === "method") { + node.kind = "init"; + } + node.shorthand = false; + } + return node; + } + parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors) { + const node = super.parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors); + if (node) { + node.kind = "init"; + node.type = "Property"; + } + return node; + } + isValidLVal(type, isUnparenthesizedInAssign, binding) { + return type === "Property" ? "value" : super.isValidLVal(type, isUnparenthesizedInAssign, binding); + } + isAssignable(node, isBinding) { + if (node != null && this.isObjectProperty(node)) { + return this.isAssignable(node.value, isBinding); + } + return super.isAssignable(node, isBinding); + } + toAssignable(node, isLHS = false) { + if (node != null && this.isObjectProperty(node)) { + const { + key, + value + } = node; + if (this.isPrivateName(key)) { + this.classScope.usePrivateName(this.getPrivateNameSV(key), key.loc.start); + } + this.toAssignable(value, isLHS); + } else { + super.toAssignable(node, isLHS); + } + } + toAssignableObjectExpressionProp(prop, isLast, isLHS) { + if (prop.type === "Property" && (prop.kind === "get" || prop.kind === "set")) { + this.raise(Errors.PatternHasAccessor, prop.key); + } else if (prop.type === "Property" && prop.method) { + this.raise(Errors.PatternHasMethod, prop.key); + } else { + super.toAssignableObjectExpressionProp(prop, isLast, isLHS); + } + } + finishCallExpression(unfinished, optional) { + const node = super.finishCallExpression(unfinished, optional); + if (node.callee.type === "Import") { + node.type = "ImportExpression"; + node.source = node.arguments[0]; + if (this.hasPlugin("importAttributes") || this.hasPlugin("importAssertions")) { + var _ref, _ref2; + node.options = (_ref = node.arguments[1]) != null ? _ref : null; + node.attributes = (_ref2 = node.arguments[1]) != null ? _ref2 : null; + } + delete node.arguments; + delete node.callee; + } + return node; + } + toReferencedArguments(node) { + if (node.type === "ImportExpression") { + return; + } + super.toReferencedArguments(node); + } + parseExport(unfinished, decorators) { + const exportStartLoc = this.state.lastTokStartLoc; + const node = super.parseExport(unfinished, decorators); + switch (node.type) { + case "ExportAllDeclaration": + node.exported = null; + break; + case "ExportNamedDeclaration": + if (node.specifiers.length === 1 && node.specifiers[0].type === "ExportNamespaceSpecifier") { + node.type = "ExportAllDeclaration"; + node.exported = node.specifiers[0].exported; + delete node.specifiers; + } + case "ExportDefaultDeclaration": + { + var _declaration$decorato; + const { + declaration + } = node; + if ((declaration == null ? void 0 : declaration.type) === "ClassDeclaration" && ((_declaration$decorato = declaration.decorators) == null ? void 0 : _declaration$decorato.length) > 0 && declaration.start === node.start) { + this.resetStartLocation(node, exportStartLoc); + } + } + break; + } + return node; + } + parseSubscript(base, startLoc, noCalls, state) { + const node = super.parseSubscript(base, startLoc, noCalls, state); + if (state.optionalChainMember) { + if (node.type === "OptionalMemberExpression" || node.type === "OptionalCallExpression") { + node.type = node.type.substring(8); + } + if (state.stop) { + const chain = this.startNodeAtNode(node); + chain.expression = node; + return this.finishNode(chain, "ChainExpression"); + } + } else if (node.type === "MemberExpression" || node.type === "CallExpression") { + node.optional = false; + } + return node; + } + isOptionalMemberExpression(node) { + if (node.type === "ChainExpression") { + return node.expression.type === "MemberExpression"; + } + return super.isOptionalMemberExpression(node); + } + hasPropertyAsPrivateName(node) { + if (node.type === "ChainExpression") { + node = node.expression; + } + return super.hasPropertyAsPrivateName(node); + } + isObjectProperty(node) { + return node.type === "Property" && node.kind === "init" && !node.method; + } + isObjectMethod(node) { + return node.type === "Property" && (node.method || node.kind === "get" || node.kind === "set"); + } + finishNodeAt(node, type, endLoc) { + return toESTreeLocation(super.finishNodeAt(node, type, endLoc)); + } + resetStartLocation(node, startLoc) { + super.resetStartLocation(node, startLoc); + toESTreeLocation(node); + } + resetEndLocation(node, endLoc = this.state.lastTokEndLoc) { + super.resetEndLocation(node, endLoc); + toESTreeLocation(node); + } +}; +class TokContext { + constructor(token, preserveSpace) { + this.token = void 0; + this.preserveSpace = void 0; + this.token = token; + this.preserveSpace = !!preserveSpace; + } +} +const types = { + brace: new TokContext("{"), + j_oTag: new TokContext("...", true) +}; +{ + types.template = new TokContext("`", true); +} +const beforeExpr = true; +const startsExpr = true; +const isLoop = true; +const isAssign = true; +const prefix = true; +const postfix = true; +class ExportedTokenType { + constructor(label, conf = {}) { + this.label = void 0; + this.keyword = void 0; + this.beforeExpr = void 0; + this.startsExpr = void 0; + this.rightAssociative = void 0; + this.isLoop = void 0; + this.isAssign = void 0; + this.prefix = void 0; + this.postfix = void 0; + this.binop = void 0; + this.label = label; + this.keyword = conf.keyword; + this.beforeExpr = !!conf.beforeExpr; + this.startsExpr = !!conf.startsExpr; + this.rightAssociative = !!conf.rightAssociative; + this.isLoop = !!conf.isLoop; + this.isAssign = !!conf.isAssign; + this.prefix = !!conf.prefix; + this.postfix = !!conf.postfix; + this.binop = conf.binop != null ? conf.binop : null; + { + this.updateContext = null; + } + } +} +const keywords$1 = new Map(); +function createKeyword(name, options = {}) { + options.keyword = name; + const token = createToken(name, options); + keywords$1.set(name, token); + return token; +} +function createBinop(name, binop) { + return createToken(name, { + beforeExpr, + binop + }); +} +let tokenTypeCounter = -1; +const tokenTypes = []; +const tokenLabels = []; +const tokenBinops = []; +const tokenBeforeExprs = []; +const tokenStartsExprs = []; +const tokenPrefixes = []; +function createToken(name, options = {}) { + var _options$binop, _options$beforeExpr, _options$startsExpr, _options$prefix; + ++tokenTypeCounter; + tokenLabels.push(name); + tokenBinops.push((_options$binop = options.binop) != null ? _options$binop : -1); + tokenBeforeExprs.push((_options$beforeExpr = options.beforeExpr) != null ? _options$beforeExpr : false); + tokenStartsExprs.push((_options$startsExpr = options.startsExpr) != null ? _options$startsExpr : false); + tokenPrefixes.push((_options$prefix = options.prefix) != null ? _options$prefix : false); + tokenTypes.push(new ExportedTokenType(name, options)); + return tokenTypeCounter; +} +function createKeywordLike(name, options = {}) { + var _options$binop2, _options$beforeExpr2, _options$startsExpr2, _options$prefix2; + ++tokenTypeCounter; + keywords$1.set(name, tokenTypeCounter); + tokenLabels.push(name); + tokenBinops.push((_options$binop2 = options.binop) != null ? _options$binop2 : -1); + tokenBeforeExprs.push((_options$beforeExpr2 = options.beforeExpr) != null ? _options$beforeExpr2 : false); + tokenStartsExprs.push((_options$startsExpr2 = options.startsExpr) != null ? _options$startsExpr2 : false); + tokenPrefixes.push((_options$prefix2 = options.prefix) != null ? _options$prefix2 : false); + tokenTypes.push(new ExportedTokenType("name", options)); + return tokenTypeCounter; +} +const tt = { + bracketL: createToken("[", { + beforeExpr, + startsExpr + }), + bracketHashL: createToken("#[", { + beforeExpr, + startsExpr + }), + bracketBarL: createToken("[|", { + beforeExpr, + startsExpr + }), + bracketR: createToken("]"), + bracketBarR: createToken("|]"), + braceL: createToken("{", { + beforeExpr, + startsExpr + }), + braceBarL: createToken("{|", { + beforeExpr, + startsExpr + }), + braceHashL: createToken("#{", { + beforeExpr, + startsExpr + }), + braceR: createToken("}"), + braceBarR: createToken("|}"), + parenL: createToken("(", { + beforeExpr, + startsExpr + }), + parenR: createToken(")"), + comma: createToken(",", { + beforeExpr + }), + semi: createToken(";", { + beforeExpr + }), + colon: createToken(":", { + beforeExpr + }), + doubleColon: createToken("::", { + beforeExpr + }), + dot: createToken("."), + question: createToken("?", { + beforeExpr + }), + questionDot: createToken("?."), + arrow: createToken("=>", { + beforeExpr + }), + template: createToken("template"), + ellipsis: createToken("...", { + beforeExpr + }), + backQuote: createToken("`", { + startsExpr + }), + dollarBraceL: createToken("${", { + beforeExpr, + startsExpr + }), + templateTail: createToken("...`", { + startsExpr + }), + templateNonTail: createToken("...${", { + beforeExpr, + startsExpr + }), + at: createToken("@"), + hash: createToken("#", { + startsExpr + }), + interpreterDirective: createToken("#!..."), + eq: createToken("=", { + beforeExpr, + isAssign + }), + assign: createToken("_=", { + beforeExpr, + isAssign + }), + slashAssign: createToken("_=", { + beforeExpr, + isAssign + }), + xorAssign: createToken("_=", { + beforeExpr, + isAssign + }), + moduloAssign: createToken("_=", { + beforeExpr, + isAssign + }), + incDec: createToken("++/--", { + prefix, + postfix, + startsExpr + }), + bang: createToken("!", { + beforeExpr, + prefix, + startsExpr + }), + tilde: createToken("~", { + beforeExpr, + prefix, + startsExpr + }), + doubleCaret: createToken("^^", { + startsExpr + }), + doubleAt: createToken("@@", { + startsExpr + }), + pipeline: createBinop("|>", 0), + nullishCoalescing: createBinop("??", 1), + logicalOR: createBinop("||", 1), + logicalAND: createBinop("&&", 2), + bitwiseOR: createBinop("|", 3), + bitwiseXOR: createBinop("^", 4), + bitwiseAND: createBinop("&", 5), + equality: createBinop("==/!=/===/!==", 6), + lt: createBinop("/<=/>=", 7), + gt: createBinop("/<=/>=", 7), + relational: createBinop("/<=/>=", 7), + bitShift: createBinop("<>/>>>", 8), + bitShiftL: createBinop("<>/>>>", 8), + bitShiftR: createBinop("<>/>>>", 8), + plusMin: createToken("+/-", { + beforeExpr, + binop: 9, + prefix, + startsExpr + }), + modulo: createToken("%", { + binop: 10, + startsExpr + }), + star: createToken("*", { + binop: 10 + }), + slash: createBinop("/", 10), + exponent: createToken("**", { + beforeExpr, + binop: 11, + rightAssociative: true + }), + _in: createKeyword("in", { + beforeExpr, + binop: 7 + }), + _instanceof: createKeyword("instanceof", { + beforeExpr, + binop: 7 + }), + _break: createKeyword("break"), + _case: createKeyword("case", { + beforeExpr + }), + _catch: createKeyword("catch"), + _continue: createKeyword("continue"), + _debugger: createKeyword("debugger"), + _default: createKeyword("default", { + beforeExpr + }), + _else: createKeyword("else", { + beforeExpr + }), + _finally: createKeyword("finally"), + _function: createKeyword("function", { + startsExpr + }), + _if: createKeyword("if"), + _return: createKeyword("return", { + beforeExpr + }), + _switch: createKeyword("switch"), + _throw: createKeyword("throw", { + beforeExpr, + prefix, + startsExpr + }), + _try: createKeyword("try"), + _var: createKeyword("var"), + _const: createKeyword("const"), + _with: createKeyword("with"), + _new: createKeyword("new", { + beforeExpr, + startsExpr + }), + _this: createKeyword("this", { + startsExpr + }), + _super: createKeyword("super", { + startsExpr + }), + _class: createKeyword("class", { + startsExpr + }), + _extends: createKeyword("extends", { + beforeExpr + }), + _export: createKeyword("export"), + _import: createKeyword("import", { + startsExpr + }), + _null: createKeyword("null", { + startsExpr + }), + _true: createKeyword("true", { + startsExpr + }), + _false: createKeyword("false", { + startsExpr + }), + _typeof: createKeyword("typeof", { + beforeExpr, + prefix, + startsExpr + }), + _void: createKeyword("void", { + beforeExpr, + prefix, + startsExpr + }), + _delete: createKeyword("delete", { + beforeExpr, + prefix, + startsExpr + }), + _do: createKeyword("do", { + isLoop, + beforeExpr + }), + _for: createKeyword("for", { + isLoop + }), + _while: createKeyword("while", { + isLoop + }), + _as: createKeywordLike("as", { + startsExpr + }), + _assert: createKeywordLike("assert", { + startsExpr + }), + _async: createKeywordLike("async", { + startsExpr + }), + _await: createKeywordLike("await", { + startsExpr + }), + _defer: createKeywordLike("defer", { + startsExpr + }), + _from: createKeywordLike("from", { + startsExpr + }), + _get: createKeywordLike("get", { + startsExpr + }), + _let: createKeywordLike("let", { + startsExpr + }), + _meta: createKeywordLike("meta", { + startsExpr + }), + _of: createKeywordLike("of", { + startsExpr + }), + _sent: createKeywordLike("sent", { + startsExpr + }), + _set: createKeywordLike("set", { + startsExpr + }), + _source: createKeywordLike("source", { + startsExpr + }), + _static: createKeywordLike("static", { + startsExpr + }), + _using: createKeywordLike("using", { + startsExpr + }), + _yield: createKeywordLike("yield", { + startsExpr + }), + _asserts: createKeywordLike("asserts", { + startsExpr + }), + _checks: createKeywordLike("checks", { + startsExpr + }), + _exports: createKeywordLike("exports", { + startsExpr + }), + _global: createKeywordLike("global", { + startsExpr + }), + _implements: createKeywordLike("implements", { + startsExpr + }), + _intrinsic: createKeywordLike("intrinsic", { + startsExpr + }), + _infer: createKeywordLike("infer", { + startsExpr + }), + _is: createKeywordLike("is", { + startsExpr + }), + _mixins: createKeywordLike("mixins", { + startsExpr + }), + _proto: createKeywordLike("proto", { + startsExpr + }), + _require: createKeywordLike("require", { + startsExpr + }), + _satisfies: createKeywordLike("satisfies", { + startsExpr + }), + _keyof: createKeywordLike("keyof", { + startsExpr + }), + _readonly: createKeywordLike("readonly", { + startsExpr + }), + _unique: createKeywordLike("unique", { + startsExpr + }), + _abstract: createKeywordLike("abstract", { + startsExpr + }), + _declare: createKeywordLike("declare", { + startsExpr + }), + _enum: createKeywordLike("enum", { + startsExpr + }), + _module: createKeywordLike("module", { + startsExpr + }), + _namespace: createKeywordLike("namespace", { + startsExpr + }), + _interface: createKeywordLike("interface", { + startsExpr + }), + _type: createKeywordLike("type", { + startsExpr + }), + _opaque: createKeywordLike("opaque", { + startsExpr + }), + name: createToken("name", { + startsExpr + }), + string: createToken("string", { + startsExpr + }), + num: createToken("num", { + startsExpr + }), + bigint: createToken("bigint", { + startsExpr + }), + decimal: createToken("decimal", { + startsExpr + }), + regexp: createToken("regexp", { + startsExpr + }), + privateName: createToken("#name", { + startsExpr + }), + eof: createToken("eof"), + jsxName: createToken("jsxName"), + jsxText: createToken("jsxText", { + beforeExpr: true + }), + jsxTagStart: createToken("jsxTagStart", { + startsExpr: true + }), + jsxTagEnd: createToken("jsxTagEnd"), + placeholder: createToken("%%", { + startsExpr: true + }) +}; +function tokenIsIdentifier(token) { + return token >= 93 && token <= 132; +} +function tokenKeywordOrIdentifierIsKeyword(token) { + return token <= 92; +} +function tokenIsKeywordOrIdentifier(token) { + return token >= 58 && token <= 132; +} +function tokenIsLiteralPropertyName(token) { + return token >= 58 && token <= 136; +} +function tokenComesBeforeExpression(token) { + return tokenBeforeExprs[token]; +} +function tokenCanStartExpression(token) { + return tokenStartsExprs[token]; +} +function tokenIsAssignment(token) { + return token >= 29 && token <= 33; +} +function tokenIsFlowInterfaceOrTypeOrOpaque(token) { + return token >= 129 && token <= 131; +} +function tokenIsLoop(token) { + return token >= 90 && token <= 92; +} +function tokenIsKeyword(token) { + return token >= 58 && token <= 92; +} +function tokenIsOperator(token) { + return token >= 39 && token <= 59; +} +function tokenIsPostfix(token) { + return token === 34; +} +function tokenIsPrefix(token) { + return tokenPrefixes[token]; +} +function tokenIsTSTypeOperator(token) { + return token >= 121 && token <= 123; +} +function tokenIsTSDeclarationStart(token) { + return token >= 124 && token <= 130; +} +function tokenLabelName(token) { + return tokenLabels[token]; +} +function tokenOperatorPrecedence(token) { + return tokenBinops[token]; +} +function tokenIsRightAssociative(token) { + return token === 57; +} +function tokenIsTemplate(token) { + return token >= 24 && token <= 25; +} +function getExportedToken(token) { + return tokenTypes[token]; +} +{ + tokenTypes[8].updateContext = context => { + context.pop(); + }; + tokenTypes[5].updateContext = tokenTypes[7].updateContext = tokenTypes[23].updateContext = context => { + context.push(types.brace); + }; + tokenTypes[22].updateContext = context => { + if (context[context.length - 1] === types.template) { + context.pop(); + } else { + context.push(types.template); + } + }; + tokenTypes[142].updateContext = context => { + context.push(types.j_expr, types.j_oTag); + }; +} +let nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7ca\ua7d0\ua7d1\ua7d3\ua7d5-\ua7d9\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"; +let nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0898-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\u30fb\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f\uff65"; +const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); +const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); +nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; +const astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 68, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 4026, 582, 8634, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8936, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 757, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4153, 7, 221, 3, 5761, 15, 7472, 16, 621, 2467, 541, 1507, 4938, 6, 4191]; +const astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 81, 2, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 9, 5351, 0, 7, 14, 13835, 9, 87, 9, 39, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4706, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 983, 6, 110, 6, 6, 9, 4759, 9, 787719, 239]; +function isInAstralSet(code, set) { + let pos = 0x10000; + for (let i = 0, length = set.length; i < length; i += 2) { + pos += set[i]; + if (pos > code) return false; + pos += set[i + 1]; + if (pos >= code) return true; + } + return false; +} +function isIdentifierStart(code) { + if (code < 65) return code === 36; + if (code <= 90) return true; + if (code < 97) return code === 95; + if (code <= 122) return true; + if (code <= 0xffff) { + return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)); + } + return isInAstralSet(code, astralIdentifierStartCodes); +} +function isIdentifierChar(code) { + if (code < 48) return code === 36; + if (code < 58) return true; + if (code < 65) return false; + if (code <= 90) return true; + if (code < 97) return code === 95; + if (code <= 122) return true; + if (code <= 0xffff) { + return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)); + } + return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes); +} +const reservedWords = { + keyword: ["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete"], + strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"], + strictBind: ["eval", "arguments"] +}; +const keywords = new Set(reservedWords.keyword); +const reservedWordsStrictSet = new Set(reservedWords.strict); +const reservedWordsStrictBindSet = new Set(reservedWords.strictBind); +function isReservedWord(word, inModule) { + return inModule && word === "await" || word === "enum"; +} +function isStrictReservedWord(word, inModule) { + return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word); +} +function isStrictBindOnlyReservedWord(word) { + return reservedWordsStrictBindSet.has(word); +} +function isStrictBindReservedWord(word, inModule) { + return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word); +} +function isKeyword(word) { + return keywords.has(word); +} +function isIteratorStart(current, next, next2) { + return current === 64 && next === 64 && isIdentifierStart(next2); +} +const reservedWordLikeSet = new Set(["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete", "implements", "interface", "let", "package", "private", "protected", "public", "static", "yield", "eval", "arguments", "enum", "await"]); +function canBeReservedWord(word) { + return reservedWordLikeSet.has(word); +} +class Scope { + constructor(flags) { + this.flags = 0; + this.names = new Map(); + this.firstLexicalName = ""; + this.flags = flags; + } +} +class ScopeHandler { + constructor(parser, inModule) { + this.parser = void 0; + this.scopeStack = []; + this.inModule = void 0; + this.undefinedExports = new Map(); + this.parser = parser; + this.inModule = inModule; + } + get inTopLevel() { + return (this.currentScope().flags & 1) > 0; + } + get inFunction() { + return (this.currentVarScopeFlags() & 2) > 0; + } + get allowSuper() { + return (this.currentThisScopeFlags() & 16) > 0; + } + get allowDirectSuper() { + return (this.currentThisScopeFlags() & 32) > 0; + } + get inClass() { + return (this.currentThisScopeFlags() & 64) > 0; + } + get inClassAndNotInNonArrowFunction() { + const flags = this.currentThisScopeFlags(); + return (flags & 64) > 0 && (flags & 2) === 0; + } + get inStaticBlock() { + for (let i = this.scopeStack.length - 1;; i--) { + const { + flags + } = this.scopeStack[i]; + if (flags & 128) { + return true; + } + if (flags & (387 | 64)) { + return false; + } + } + } + get inNonArrowFunction() { + return (this.currentThisScopeFlags() & 2) > 0; + } + get treatFunctionsAsVar() { + return this.treatFunctionsAsVarInScope(this.currentScope()); + } + createScope(flags) { + return new Scope(flags); + } + enter(flags) { + this.scopeStack.push(this.createScope(flags)); + } + exit() { + const scope = this.scopeStack.pop(); + return scope.flags; + } + treatFunctionsAsVarInScope(scope) { + return !!(scope.flags & (2 | 128) || !this.parser.inModule && scope.flags & 1); + } + declareName(name, bindingType, loc) { + let scope = this.currentScope(); + if (bindingType & 8 || bindingType & 16) { + this.checkRedeclarationInScope(scope, name, bindingType, loc); + let type = scope.names.get(name) || 0; + if (bindingType & 16) { + type = type | 4; + } else { + if (!scope.firstLexicalName) { + scope.firstLexicalName = name; + } + type = type | 2; + } + scope.names.set(name, type); + if (bindingType & 8) { + this.maybeExportDefined(scope, name); + } + } else if (bindingType & 4) { + for (let i = this.scopeStack.length - 1; i >= 0; --i) { + scope = this.scopeStack[i]; + this.checkRedeclarationInScope(scope, name, bindingType, loc); + scope.names.set(name, (scope.names.get(name) || 0) | 1); + this.maybeExportDefined(scope, name); + if (scope.flags & 387) break; + } + } + if (this.parser.inModule && scope.flags & 1) { + this.undefinedExports.delete(name); + } + } + maybeExportDefined(scope, name) { + if (this.parser.inModule && scope.flags & 1) { + this.undefinedExports.delete(name); + } + } + checkRedeclarationInScope(scope, name, bindingType, loc) { + if (this.isRedeclaredInScope(scope, name, bindingType)) { + this.parser.raise(Errors.VarRedeclaration, loc, { + identifierName: name + }); + } + } + isRedeclaredInScope(scope, name, bindingType) { + if (!(bindingType & 1)) return false; + if (bindingType & 8) { + return scope.names.has(name); + } + const type = scope.names.get(name); + if (bindingType & 16) { + return (type & 2) > 0 || !this.treatFunctionsAsVarInScope(scope) && (type & 1) > 0; + } + return (type & 2) > 0 && !(scope.flags & 8 && scope.firstLexicalName === name) || !this.treatFunctionsAsVarInScope(scope) && (type & 4) > 0; + } + checkLocalExport(id) { + const { + name + } = id; + const topLevelScope = this.scopeStack[0]; + if (!topLevelScope.names.has(name)) { + this.undefinedExports.set(name, id.loc.start); + } + } + currentScope() { + return this.scopeStack[this.scopeStack.length - 1]; + } + currentVarScopeFlags() { + for (let i = this.scopeStack.length - 1;; i--) { + const { + flags + } = this.scopeStack[i]; + if (flags & 387) { + return flags; + } + } + } + currentThisScopeFlags() { + for (let i = this.scopeStack.length - 1;; i--) { + const { + flags + } = this.scopeStack[i]; + if (flags & (387 | 64) && !(flags & 4)) { + return flags; + } + } + } +} +class FlowScope extends Scope { + constructor(...args) { + super(...args); + this.declareFunctions = new Set(); + } +} +class FlowScopeHandler extends ScopeHandler { + createScope(flags) { + return new FlowScope(flags); + } + declareName(name, bindingType, loc) { + const scope = this.currentScope(); + if (bindingType & 2048) { + this.checkRedeclarationInScope(scope, name, bindingType, loc); + this.maybeExportDefined(scope, name); + scope.declareFunctions.add(name); + return; + } + super.declareName(name, bindingType, loc); + } + isRedeclaredInScope(scope, name, bindingType) { + if (super.isRedeclaredInScope(scope, name, bindingType)) return true; + if (bindingType & 2048 && !scope.declareFunctions.has(name)) { + const type = scope.names.get(name); + return (type & 4) > 0 || (type & 2) > 0; + } + return false; + } + checkLocalExport(id) { + if (!this.scopeStack[0].declareFunctions.has(id.name)) { + super.checkLocalExport(id); + } + } +} +class BaseParser { + constructor() { + this.sawUnambiguousESM = false; + this.ambiguousScriptDifferentAst = false; + } + hasPlugin(pluginConfig) { + if (typeof pluginConfig === "string") { + return this.plugins.has(pluginConfig); + } else { + const [pluginName, pluginOptions] = pluginConfig; + if (!this.hasPlugin(pluginName)) { + return false; + } + const actualOptions = this.plugins.get(pluginName); + for (const key of Object.keys(pluginOptions)) { + if ((actualOptions == null ? void 0 : actualOptions[key]) !== pluginOptions[key]) { + return false; + } + } + return true; + } + } + getPluginOption(plugin, name) { + var _this$plugins$get; + return (_this$plugins$get = this.plugins.get(plugin)) == null ? void 0 : _this$plugins$get[name]; + } +} +function setTrailingComments(node, comments) { + if (node.trailingComments === undefined) { + node.trailingComments = comments; + } else { + node.trailingComments.unshift(...comments); + } +} +function setLeadingComments(node, comments) { + if (node.leadingComments === undefined) { + node.leadingComments = comments; + } else { + node.leadingComments.unshift(...comments); + } +} +function setInnerComments(node, comments) { + if (node.innerComments === undefined) { + node.innerComments = comments; + } else { + node.innerComments.unshift(...comments); + } +} +function adjustInnerComments(node, elements, commentWS) { + let lastElement = null; + let i = elements.length; + while (lastElement === null && i > 0) { + lastElement = elements[--i]; + } + if (lastElement === null || lastElement.start > commentWS.start) { + setInnerComments(node, commentWS.comments); + } else { + setTrailingComments(lastElement, commentWS.comments); + } +} +class CommentsParser extends BaseParser { + addComment(comment) { + if (this.filename) comment.loc.filename = this.filename; + const { + commentsLen + } = this.state; + if (this.comments.length !== commentsLen) { + this.comments.length = commentsLen; + } + this.comments.push(comment); + this.state.commentsLen++; + } + processComment(node) { + const { + commentStack + } = this.state; + const commentStackLength = commentStack.length; + if (commentStackLength === 0) return; + let i = commentStackLength - 1; + const lastCommentWS = commentStack[i]; + if (lastCommentWS.start === node.end) { + lastCommentWS.leadingNode = node; + i--; + } + const { + start: nodeStart + } = node; + for (; i >= 0; i--) { + const commentWS = commentStack[i]; + const commentEnd = commentWS.end; + if (commentEnd > nodeStart) { + commentWS.containingNode = node; + this.finalizeComment(commentWS); + commentStack.splice(i, 1); + } else { + if (commentEnd === nodeStart) { + commentWS.trailingNode = node; + } + break; + } + } + } + finalizeComment(commentWS) { + const { + comments + } = commentWS; + if (commentWS.leadingNode !== null || commentWS.trailingNode !== null) { + if (commentWS.leadingNode !== null) { + setTrailingComments(commentWS.leadingNode, comments); + } + if (commentWS.trailingNode !== null) { + setLeadingComments(commentWS.trailingNode, comments); + } + } else { + const { + containingNode: node, + start: commentStart + } = commentWS; + if (this.input.charCodeAt(commentStart - 1) === 44) { + switch (node.type) { + case "ObjectExpression": + case "ObjectPattern": + case "RecordExpression": + adjustInnerComments(node, node.properties, commentWS); + break; + case "CallExpression": + case "OptionalCallExpression": + adjustInnerComments(node, node.arguments, commentWS); + break; + case "FunctionDeclaration": + case "FunctionExpression": + case "ArrowFunctionExpression": + case "ObjectMethod": + case "ClassMethod": + case "ClassPrivateMethod": + adjustInnerComments(node, node.params, commentWS); + break; + case "ArrayExpression": + case "ArrayPattern": + case "TupleExpression": + adjustInnerComments(node, node.elements, commentWS); + break; + case "ExportNamedDeclaration": + case "ImportDeclaration": + adjustInnerComments(node, node.specifiers, commentWS); + break; + default: + { + setInnerComments(node, comments); + } + } + } else { + setInnerComments(node, comments); + } + } + } + finalizeRemainingComments() { + const { + commentStack + } = this.state; + for (let i = commentStack.length - 1; i >= 0; i--) { + this.finalizeComment(commentStack[i]); + } + this.state.commentStack = []; + } + resetPreviousNodeTrailingComments(node) { + const { + commentStack + } = this.state; + const { + length + } = commentStack; + if (length === 0) return; + const commentWS = commentStack[length - 1]; + if (commentWS.leadingNode === node) { + commentWS.leadingNode = null; + } + } + resetPreviousIdentifierLeadingComments(node) { + const { + commentStack + } = this.state; + const { + length + } = commentStack; + if (length === 0) return; + if (commentStack[length - 1].trailingNode === node) { + commentStack[length - 1].trailingNode = null; + } else if (length >= 2 && commentStack[length - 2].trailingNode === node) { + commentStack[length - 2].trailingNode = null; + } + } + takeSurroundingComments(node, start, end) { + const { + commentStack + } = this.state; + const commentStackLength = commentStack.length; + if (commentStackLength === 0) return; + let i = commentStackLength - 1; + for (; i >= 0; i--) { + const commentWS = commentStack[i]; + const commentEnd = commentWS.end; + const commentStart = commentWS.start; + if (commentStart === end) { + commentWS.leadingNode = node; + } else if (commentEnd === start) { + commentWS.trailingNode = node; + } else if (commentEnd < start) { + break; + } + } + } +} +const lineBreak = /\r\n|[\r\n\u2028\u2029]/; +const lineBreakG = new RegExp(lineBreak.source, "g"); +function isNewLine(code) { + switch (code) { + case 10: + case 13: + case 8232: + case 8233: + return true; + default: + return false; + } +} +function hasNewLine(input, start, end) { + for (let i = start; i < end; i++) { + if (isNewLine(input.charCodeAt(i))) { + return true; + } + } + return false; +} +const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; +const skipWhiteSpaceInLine = /(?:[^\S\n\r\u2028\u2029]|\/\/.*|\/\*.*?\*\/)*/g; +function isWhitespace(code) { + switch (code) { + case 0x0009: + case 0x000b: + case 0x000c: + case 32: + case 160: + case 5760: + case 0x2000: + case 0x2001: + case 0x2002: + case 0x2003: + case 0x2004: + case 0x2005: + case 0x2006: + case 0x2007: + case 0x2008: + case 0x2009: + case 0x200a: + case 0x202f: + case 0x205f: + case 0x3000: + case 0xfeff: + return true; + default: + return false; + } +} +class State { + constructor() { + this.flags = 1024; + this.curLine = void 0; + this.lineStart = void 0; + this.startLoc = void 0; + this.endLoc = void 0; + this.errors = []; + this.potentialArrowAt = -1; + this.noArrowAt = []; + this.noArrowParamsConversionAt = []; + this.topicContext = { + maxNumOfResolvableTopics: 0, + maxTopicIndex: null + }; + this.labels = []; + this.commentsLen = 0; + this.commentStack = []; + this.pos = 0; + this.type = 139; + this.value = null; + this.start = 0; + this.end = 0; + this.lastTokEndLoc = null; + this.lastTokStartLoc = null; + this.context = [types.brace]; + this.firstInvalidTemplateEscapePos = null; + this.strictErrors = new Map(); + this.tokensLength = 0; + } + get strict() { + return (this.flags & 1) > 0; + } + set strict(v) { + if (v) this.flags |= 1;else this.flags &= -2; + } + init({ + strictMode, + sourceType, + startLine, + startColumn + }) { + this.strict = strictMode === false ? false : strictMode === true ? true : sourceType === "module"; + this.curLine = startLine; + this.lineStart = -startColumn; + this.startLoc = this.endLoc = new Position(startLine, startColumn, 0); + } + get maybeInArrowParameters() { + return (this.flags & 2) > 0; + } + set maybeInArrowParameters(v) { + if (v) this.flags |= 2;else this.flags &= -3; + } + get inType() { + return (this.flags & 4) > 0; + } + set inType(v) { + if (v) this.flags |= 4;else this.flags &= -5; + } + get noAnonFunctionType() { + return (this.flags & 8) > 0; + } + set noAnonFunctionType(v) { + if (v) this.flags |= 8;else this.flags &= -9; + } + get hasFlowComment() { + return (this.flags & 16) > 0; + } + set hasFlowComment(v) { + if (v) this.flags |= 16;else this.flags &= -17; + } + get isAmbientContext() { + return (this.flags & 32) > 0; + } + set isAmbientContext(v) { + if (v) this.flags |= 32;else this.flags &= -33; + } + get inAbstractClass() { + return (this.flags & 64) > 0; + } + set inAbstractClass(v) { + if (v) this.flags |= 64;else this.flags &= -65; + } + get inDisallowConditionalTypesContext() { + return (this.flags & 128) > 0; + } + set inDisallowConditionalTypesContext(v) { + if (v) this.flags |= 128;else this.flags &= -129; + } + get soloAwait() { + return (this.flags & 256) > 0; + } + set soloAwait(v) { + if (v) this.flags |= 256;else this.flags &= -257; + } + get inFSharpPipelineDirectBody() { + return (this.flags & 512) > 0; + } + set inFSharpPipelineDirectBody(v) { + if (v) this.flags |= 512;else this.flags &= -513; + } + get canStartJSXElement() { + return (this.flags & 1024) > 0; + } + set canStartJSXElement(v) { + if (v) this.flags |= 1024;else this.flags &= -1025; + } + get containsEsc() { + return (this.flags & 2048) > 0; + } + set containsEsc(v) { + if (v) this.flags |= 2048;else this.flags &= -2049; + } + get hasTopLevelAwait() { + return (this.flags & 4096) > 0; + } + set hasTopLevelAwait(v) { + if (v) this.flags |= 4096;else this.flags &= -4097; + } + curPosition() { + return new Position(this.curLine, this.pos - this.lineStart, this.pos); + } + clone() { + const state = new State(); + state.flags = this.flags; + state.curLine = this.curLine; + state.lineStart = this.lineStart; + state.startLoc = this.startLoc; + state.endLoc = this.endLoc; + state.errors = this.errors.slice(); + state.potentialArrowAt = this.potentialArrowAt; + state.noArrowAt = this.noArrowAt.slice(); + state.noArrowParamsConversionAt = this.noArrowParamsConversionAt.slice(); + state.topicContext = this.topicContext; + state.labels = this.labels.slice(); + state.commentsLen = this.commentsLen; + state.commentStack = this.commentStack.slice(); + state.pos = this.pos; + state.type = this.type; + state.value = this.value; + state.start = this.start; + state.end = this.end; + state.lastTokEndLoc = this.lastTokEndLoc; + state.lastTokStartLoc = this.lastTokStartLoc; + state.context = this.context.slice(); + state.firstInvalidTemplateEscapePos = this.firstInvalidTemplateEscapePos; + state.strictErrors = this.strictErrors; + state.tokensLength = this.tokensLength; + return state; + } +} +var _isDigit = function isDigit(code) { + return code >= 48 && code <= 57; +}; +const forbiddenNumericSeparatorSiblings = { + decBinOct: new Set([46, 66, 69, 79, 95, 98, 101, 111]), + hex: new Set([46, 88, 95, 120]) +}; +const isAllowedNumericSeparatorSibling = { + bin: ch => ch === 48 || ch === 49, + oct: ch => ch >= 48 && ch <= 55, + dec: ch => ch >= 48 && ch <= 57, + hex: ch => ch >= 48 && ch <= 57 || ch >= 65 && ch <= 70 || ch >= 97 && ch <= 102 +}; +function readStringContents(type, input, pos, lineStart, curLine, errors) { + const initialPos = pos; + const initialLineStart = lineStart; + const initialCurLine = curLine; + let out = ""; + let firstInvalidLoc = null; + let chunkStart = pos; + const { + length + } = input; + for (;;) { + if (pos >= length) { + errors.unterminated(initialPos, initialLineStart, initialCurLine); + out += input.slice(chunkStart, pos); + break; + } + const ch = input.charCodeAt(pos); + if (isStringEnd(type, ch, input, pos)) { + out += input.slice(chunkStart, pos); + break; + } + if (ch === 92) { + out += input.slice(chunkStart, pos); + const res = readEscapedChar(input, pos, lineStart, curLine, type === "template", errors); + if (res.ch === null && !firstInvalidLoc) { + firstInvalidLoc = { + pos, + lineStart, + curLine + }; + } else { + out += res.ch; + } + ({ + pos, + lineStart, + curLine + } = res); + chunkStart = pos; + } else if (ch === 8232 || ch === 8233) { + ++pos; + ++curLine; + lineStart = pos; + } else if (ch === 10 || ch === 13) { + if (type === "template") { + out += input.slice(chunkStart, pos) + "\n"; + ++pos; + if (ch === 13 && input.charCodeAt(pos) === 10) { + ++pos; + } + ++curLine; + chunkStart = lineStart = pos; + } else { + errors.unterminated(initialPos, initialLineStart, initialCurLine); + } + } else { + ++pos; + } + } + return { + pos, + str: out, + firstInvalidLoc, + lineStart, + curLine, + containsInvalid: !!firstInvalidLoc + }; +} +function isStringEnd(type, ch, input, pos) { + if (type === "template") { + return ch === 96 || ch === 36 && input.charCodeAt(pos + 1) === 123; + } + return ch === (type === "double" ? 34 : 39); +} +function readEscapedChar(input, pos, lineStart, curLine, inTemplate, errors) { + const throwOnInvalid = !inTemplate; + pos++; + const res = ch => ({ + pos, + ch, + lineStart, + curLine + }); + const ch = input.charCodeAt(pos++); + switch (ch) { + case 110: + return res("\n"); + case 114: + return res("\r"); + case 120: + { + let code; + ({ + code, + pos + } = readHexChar(input, pos, lineStart, curLine, 2, false, throwOnInvalid, errors)); + return res(code === null ? null : String.fromCharCode(code)); + } + case 117: + { + let code; + ({ + code, + pos + } = readCodePoint(input, pos, lineStart, curLine, throwOnInvalid, errors)); + return res(code === null ? null : String.fromCodePoint(code)); + } + case 116: + return res("\t"); + case 98: + return res("\b"); + case 118: + return res("\u000b"); + case 102: + return res("\f"); + case 13: + if (input.charCodeAt(pos) === 10) { + ++pos; + } + case 10: + lineStart = pos; + ++curLine; + case 8232: + case 8233: + return res(""); + case 56: + case 57: + if (inTemplate) { + return res(null); + } else { + errors.strictNumericEscape(pos - 1, lineStart, curLine); + } + default: + if (ch >= 48 && ch <= 55) { + const startPos = pos - 1; + const match = /^[0-7]+/.exec(input.slice(startPos, pos + 2)); + let octalStr = match[0]; + let octal = parseInt(octalStr, 8); + if (octal > 255) { + octalStr = octalStr.slice(0, -1); + octal = parseInt(octalStr, 8); + } + pos += octalStr.length - 1; + const next = input.charCodeAt(pos); + if (octalStr !== "0" || next === 56 || next === 57) { + if (inTemplate) { + return res(null); + } else { + errors.strictNumericEscape(startPos, lineStart, curLine); + } + } + return res(String.fromCharCode(octal)); + } + return res(String.fromCharCode(ch)); + } +} +function readHexChar(input, pos, lineStart, curLine, len, forceLen, throwOnInvalid, errors) { + const initialPos = pos; + let n; + ({ + n, + pos + } = readInt(input, pos, lineStart, curLine, 16, len, forceLen, false, errors, !throwOnInvalid)); + if (n === null) { + if (throwOnInvalid) { + errors.invalidEscapeSequence(initialPos, lineStart, curLine); + } else { + pos = initialPos - 1; + } + } + return { + code: n, + pos + }; +} +function readInt(input, pos, lineStart, curLine, radix, len, forceLen, allowNumSeparator, errors, bailOnError) { + const start = pos; + const forbiddenSiblings = radix === 16 ? forbiddenNumericSeparatorSiblings.hex : forbiddenNumericSeparatorSiblings.decBinOct; + const isAllowedSibling = radix === 16 ? isAllowedNumericSeparatorSibling.hex : radix === 10 ? isAllowedNumericSeparatorSibling.dec : radix === 8 ? isAllowedNumericSeparatorSibling.oct : isAllowedNumericSeparatorSibling.bin; + let invalid = false; + let total = 0; + for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) { + const code = input.charCodeAt(pos); + let val; + if (code === 95 && allowNumSeparator !== "bail") { + const prev = input.charCodeAt(pos - 1); + const next = input.charCodeAt(pos + 1); + if (!allowNumSeparator) { + if (bailOnError) return { + n: null, + pos + }; + errors.numericSeparatorInEscapeSequence(pos, lineStart, curLine); + } else if (Number.isNaN(next) || !isAllowedSibling(next) || forbiddenSiblings.has(prev) || forbiddenSiblings.has(next)) { + if (bailOnError) return { + n: null, + pos + }; + errors.unexpectedNumericSeparator(pos, lineStart, curLine); + } + ++pos; + continue; + } + if (code >= 97) { + val = code - 97 + 10; + } else if (code >= 65) { + val = code - 65 + 10; + } else if (_isDigit(code)) { + val = code - 48; + } else { + val = Infinity; + } + if (val >= radix) { + if (val <= 9 && bailOnError) { + return { + n: null, + pos + }; + } else if (val <= 9 && errors.invalidDigit(pos, lineStart, curLine, radix)) { + val = 0; + } else if (forceLen) { + val = 0; + invalid = true; + } else { + break; + } + } + ++pos; + total = total * radix + val; + } + if (pos === start || len != null && pos - start !== len || invalid) { + return { + n: null, + pos + }; + } + return { + n: total, + pos + }; +} +function readCodePoint(input, pos, lineStart, curLine, throwOnInvalid, errors) { + const ch = input.charCodeAt(pos); + let code; + if (ch === 123) { + ++pos; + ({ + code, + pos + } = readHexChar(input, pos, lineStart, curLine, input.indexOf("}", pos) - pos, true, throwOnInvalid, errors)); + ++pos; + if (code !== null && code > 0x10ffff) { + if (throwOnInvalid) { + errors.invalidCodePoint(pos, lineStart, curLine); + } else { + return { + code: null, + pos + }; + } + } + } else { + ({ + code, + pos + } = readHexChar(input, pos, lineStart, curLine, 4, false, throwOnInvalid, errors)); + } + return { + code, + pos + }; +} +function buildPosition(pos, lineStart, curLine) { + return new Position(curLine, pos - lineStart, pos); +} +const VALID_REGEX_FLAGS = new Set([103, 109, 115, 105, 121, 117, 100, 118]); +class Token { + constructor(state) { + this.type = state.type; + this.value = state.value; + this.start = state.start; + this.end = state.end; + this.loc = new SourceLocation(state.startLoc, state.endLoc); + } +} +class Tokenizer extends CommentsParser { + constructor(options, input) { + super(); + this.isLookahead = void 0; + this.tokens = []; + this.errorHandlers_readInt = { + invalidDigit: (pos, lineStart, curLine, radix) => { + if (!this.options.errorRecovery) return false; + this.raise(Errors.InvalidDigit, buildPosition(pos, lineStart, curLine), { + radix + }); + return true; + }, + numericSeparatorInEscapeSequence: this.errorBuilder(Errors.NumericSeparatorInEscapeSequence), + unexpectedNumericSeparator: this.errorBuilder(Errors.UnexpectedNumericSeparator) + }; + this.errorHandlers_readCodePoint = Object.assign({}, this.errorHandlers_readInt, { + invalidEscapeSequence: this.errorBuilder(Errors.InvalidEscapeSequence), + invalidCodePoint: this.errorBuilder(Errors.InvalidCodePoint) + }); + this.errorHandlers_readStringContents_string = Object.assign({}, this.errorHandlers_readCodePoint, { + strictNumericEscape: (pos, lineStart, curLine) => { + this.recordStrictModeErrors(Errors.StrictNumericEscape, buildPosition(pos, lineStart, curLine)); + }, + unterminated: (pos, lineStart, curLine) => { + throw this.raise(Errors.UnterminatedString, buildPosition(pos - 1, lineStart, curLine)); + } + }); + this.errorHandlers_readStringContents_template = Object.assign({}, this.errorHandlers_readCodePoint, { + strictNumericEscape: this.errorBuilder(Errors.StrictNumericEscape), + unterminated: (pos, lineStart, curLine) => { + throw this.raise(Errors.UnterminatedTemplate, buildPosition(pos, lineStart, curLine)); + } + }); + this.state = new State(); + this.state.init(options); + this.input = input; + this.length = input.length; + this.comments = []; + this.isLookahead = false; + } + pushToken(token) { + this.tokens.length = this.state.tokensLength; + this.tokens.push(token); + ++this.state.tokensLength; + } + next() { + this.checkKeywordEscapes(); + if (this.options.tokens) { + this.pushToken(new Token(this.state)); + } + this.state.lastTokEndLoc = this.state.endLoc; + this.state.lastTokStartLoc = this.state.startLoc; + this.nextToken(); + } + eat(type) { + if (this.match(type)) { + this.next(); + return true; + } else { + return false; + } + } + match(type) { + return this.state.type === type; + } + createLookaheadState(state) { + return { + pos: state.pos, + value: null, + type: state.type, + start: state.start, + end: state.end, + context: [this.curContext()], + inType: state.inType, + startLoc: state.startLoc, + lastTokEndLoc: state.lastTokEndLoc, + curLine: state.curLine, + lineStart: state.lineStart, + curPosition: state.curPosition + }; + } + lookahead() { + const old = this.state; + this.state = this.createLookaheadState(old); + this.isLookahead = true; + this.nextToken(); + this.isLookahead = false; + const curr = this.state; + this.state = old; + return curr; + } + nextTokenStart() { + return this.nextTokenStartSince(this.state.pos); + } + nextTokenStartSince(pos) { + skipWhiteSpace.lastIndex = pos; + return skipWhiteSpace.test(this.input) ? skipWhiteSpace.lastIndex : pos; + } + lookaheadCharCode() { + return this.input.charCodeAt(this.nextTokenStart()); + } + nextTokenInLineStart() { + return this.nextTokenInLineStartSince(this.state.pos); + } + nextTokenInLineStartSince(pos) { + skipWhiteSpaceInLine.lastIndex = pos; + return skipWhiteSpaceInLine.test(this.input) ? skipWhiteSpaceInLine.lastIndex : pos; + } + lookaheadInLineCharCode() { + return this.input.charCodeAt(this.nextTokenInLineStart()); + } + codePointAtPos(pos) { + let cp = this.input.charCodeAt(pos); + if ((cp & 0xfc00) === 0xd800 && ++pos < this.input.length) { + const trail = this.input.charCodeAt(pos); + if ((trail & 0xfc00) === 0xdc00) { + cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff); + } + } + return cp; + } + setStrict(strict) { + this.state.strict = strict; + if (strict) { + this.state.strictErrors.forEach(([toParseError, at]) => this.raise(toParseError, at)); + this.state.strictErrors.clear(); + } + } + curContext() { + return this.state.context[this.state.context.length - 1]; + } + nextToken() { + this.skipSpace(); + this.state.start = this.state.pos; + if (!this.isLookahead) this.state.startLoc = this.state.curPosition(); + if (this.state.pos >= this.length) { + this.finishToken(139); + return; + } + this.getTokenFromCode(this.codePointAtPos(this.state.pos)); + } + skipBlockComment(commentEnd) { + let startLoc; + if (!this.isLookahead) startLoc = this.state.curPosition(); + const start = this.state.pos; + const end = this.input.indexOf(commentEnd, start + 2); + if (end === -1) { + throw this.raise(Errors.UnterminatedComment, this.state.curPosition()); + } + this.state.pos = end + commentEnd.length; + lineBreakG.lastIndex = start + 2; + while (lineBreakG.test(this.input) && lineBreakG.lastIndex <= end) { + ++this.state.curLine; + this.state.lineStart = lineBreakG.lastIndex; + } + if (this.isLookahead) return; + const comment = { + type: "CommentBlock", + value: this.input.slice(start + 2, end), + start, + end: end + commentEnd.length, + loc: new SourceLocation(startLoc, this.state.curPosition()) + }; + if (this.options.tokens) this.pushToken(comment); + return comment; + } + skipLineComment(startSkip) { + const start = this.state.pos; + let startLoc; + if (!this.isLookahead) startLoc = this.state.curPosition(); + let ch = this.input.charCodeAt(this.state.pos += startSkip); + if (this.state.pos < this.length) { + while (!isNewLine(ch) && ++this.state.pos < this.length) { + ch = this.input.charCodeAt(this.state.pos); + } + } + if (this.isLookahead) return; + const end = this.state.pos; + const value = this.input.slice(start + startSkip, end); + const comment = { + type: "CommentLine", + value, + start, + end, + loc: new SourceLocation(startLoc, this.state.curPosition()) + }; + if (this.options.tokens) this.pushToken(comment); + return comment; + } + skipSpace() { + const spaceStart = this.state.pos; + const comments = []; + loop: while (this.state.pos < this.length) { + const ch = this.input.charCodeAt(this.state.pos); + switch (ch) { + case 32: + case 160: + case 9: + ++this.state.pos; + break; + case 13: + if (this.input.charCodeAt(this.state.pos + 1) === 10) { + ++this.state.pos; + } + case 10: + case 8232: + case 8233: + ++this.state.pos; + ++this.state.curLine; + this.state.lineStart = this.state.pos; + break; + case 47: + switch (this.input.charCodeAt(this.state.pos + 1)) { + case 42: + { + const comment = this.skipBlockComment("*/"); + if (comment !== undefined) { + this.addComment(comment); + if (this.options.attachComment) comments.push(comment); + } + break; + } + case 47: + { + const comment = this.skipLineComment(2); + if (comment !== undefined) { + this.addComment(comment); + if (this.options.attachComment) comments.push(comment); + } + break; + } + default: + break loop; + } + break; + default: + if (isWhitespace(ch)) { + ++this.state.pos; + } else if (ch === 45 && !this.inModule && this.options.annexB) { + const pos = this.state.pos; + if (this.input.charCodeAt(pos + 1) === 45 && this.input.charCodeAt(pos + 2) === 62 && (spaceStart === 0 || this.state.lineStart > spaceStart)) { + const comment = this.skipLineComment(3); + if (comment !== undefined) { + this.addComment(comment); + if (this.options.attachComment) comments.push(comment); + } + } else { + break loop; + } + } else if (ch === 60 && !this.inModule && this.options.annexB) { + const pos = this.state.pos; + if (this.input.charCodeAt(pos + 1) === 33 && this.input.charCodeAt(pos + 2) === 45 && this.input.charCodeAt(pos + 3) === 45) { + const comment = this.skipLineComment(4); + if (comment !== undefined) { + this.addComment(comment); + if (this.options.attachComment) comments.push(comment); + } + } else { + break loop; + } + } else { + break loop; + } + } + } + if (comments.length > 0) { + const end = this.state.pos; + const commentWhitespace = { + start: spaceStart, + end, + comments, + leadingNode: null, + trailingNode: null, + containingNode: null + }; + this.state.commentStack.push(commentWhitespace); + } + } + finishToken(type, val) { + this.state.end = this.state.pos; + this.state.endLoc = this.state.curPosition(); + const prevType = this.state.type; + this.state.type = type; + this.state.value = val; + if (!this.isLookahead) { + this.updateContext(prevType); + } + } + replaceToken(type) { + this.state.type = type; + this.updateContext(); + } + readToken_numberSign() { + if (this.state.pos === 0 && this.readToken_interpreter()) { + return; + } + const nextPos = this.state.pos + 1; + const next = this.codePointAtPos(nextPos); + if (next >= 48 && next <= 57) { + throw this.raise(Errors.UnexpectedDigitAfterHash, this.state.curPosition()); + } + if (next === 123 || next === 91 && this.hasPlugin("recordAndTuple")) { + this.expectPlugin("recordAndTuple"); + if (this.getPluginOption("recordAndTuple", "syntaxType") === "bar") { + throw this.raise(next === 123 ? Errors.RecordExpressionHashIncorrectStartSyntaxType : Errors.TupleExpressionHashIncorrectStartSyntaxType, this.state.curPosition()); + } + this.state.pos += 2; + if (next === 123) { + this.finishToken(7); + } else { + this.finishToken(1); + } + } else if (isIdentifierStart(next)) { + ++this.state.pos; + this.finishToken(138, this.readWord1(next)); + } else if (next === 92) { + ++this.state.pos; + this.finishToken(138, this.readWord1()); + } else { + this.finishOp(27, 1); + } + } + readToken_dot() { + const next = this.input.charCodeAt(this.state.pos + 1); + if (next >= 48 && next <= 57) { + this.readNumber(true); + return; + } + if (next === 46 && this.input.charCodeAt(this.state.pos + 2) === 46) { + this.state.pos += 3; + this.finishToken(21); + } else { + ++this.state.pos; + this.finishToken(16); + } + } + readToken_slash() { + const next = this.input.charCodeAt(this.state.pos + 1); + if (next === 61) { + this.finishOp(31, 2); + } else { + this.finishOp(56, 1); + } + } + readToken_interpreter() { + if (this.state.pos !== 0 || this.length < 2) return false; + let ch = this.input.charCodeAt(this.state.pos + 1); + if (ch !== 33) return false; + const start = this.state.pos; + this.state.pos += 1; + while (!isNewLine(ch) && ++this.state.pos < this.length) { + ch = this.input.charCodeAt(this.state.pos); + } + const value = this.input.slice(start + 2, this.state.pos); + this.finishToken(28, value); + return true; + } + readToken_mult_modulo(code) { + let type = code === 42 ? 55 : 54; + let width = 1; + let next = this.input.charCodeAt(this.state.pos + 1); + if (code === 42 && next === 42) { + width++; + next = this.input.charCodeAt(this.state.pos + 2); + type = 57; + } + if (next === 61 && !this.state.inType) { + width++; + type = code === 37 ? 33 : 30; + } + this.finishOp(type, width); + } + readToken_pipe_amp(code) { + const next = this.input.charCodeAt(this.state.pos + 1); + if (next === code) { + if (this.input.charCodeAt(this.state.pos + 2) === 61) { + this.finishOp(30, 3); + } else { + this.finishOp(code === 124 ? 41 : 42, 2); + } + return; + } + if (code === 124) { + if (next === 62) { + this.finishOp(39, 2); + return; + } + if (this.hasPlugin("recordAndTuple") && next === 125) { + if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") { + throw this.raise(Errors.RecordExpressionBarIncorrectEndSyntaxType, this.state.curPosition()); + } + this.state.pos += 2; + this.finishToken(9); + return; + } + if (this.hasPlugin("recordAndTuple") && next === 93) { + if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") { + throw this.raise(Errors.TupleExpressionBarIncorrectEndSyntaxType, this.state.curPosition()); + } + this.state.pos += 2; + this.finishToken(4); + return; + } + } + if (next === 61) { + this.finishOp(30, 2); + return; + } + this.finishOp(code === 124 ? 43 : 45, 1); + } + readToken_caret() { + const next = this.input.charCodeAt(this.state.pos + 1); + if (next === 61 && !this.state.inType) { + this.finishOp(32, 2); + } else if (next === 94 && this.hasPlugin(["pipelineOperator", { + proposal: "hack", + topicToken: "^^" + }])) { + this.finishOp(37, 2); + const lookaheadCh = this.input.codePointAt(this.state.pos); + if (lookaheadCh === 94) { + this.unexpected(); + } + } else { + this.finishOp(44, 1); + } + } + readToken_atSign() { + const next = this.input.charCodeAt(this.state.pos + 1); + if (next === 64 && this.hasPlugin(["pipelineOperator", { + proposal: "hack", + topicToken: "@@" + }])) { + this.finishOp(38, 2); + } else { + this.finishOp(26, 1); + } + } + readToken_plus_min(code) { + const next = this.input.charCodeAt(this.state.pos + 1); + if (next === code) { + this.finishOp(34, 2); + return; + } + if (next === 61) { + this.finishOp(30, 2); + } else { + this.finishOp(53, 1); + } + } + readToken_lt() { + const { + pos + } = this.state; + const next = this.input.charCodeAt(pos + 1); + if (next === 60) { + if (this.input.charCodeAt(pos + 2) === 61) { + this.finishOp(30, 3); + return; + } + this.finishOp(51, 2); + return; + } + if (next === 61) { + this.finishOp(49, 2); + return; + } + this.finishOp(47, 1); + } + readToken_gt() { + const { + pos + } = this.state; + const next = this.input.charCodeAt(pos + 1); + if (next === 62) { + const size = this.input.charCodeAt(pos + 2) === 62 ? 3 : 2; + if (this.input.charCodeAt(pos + size) === 61) { + this.finishOp(30, size + 1); + return; + } + this.finishOp(52, size); + return; + } + if (next === 61) { + this.finishOp(49, 2); + return; + } + this.finishOp(48, 1); + } + readToken_eq_excl(code) { + const next = this.input.charCodeAt(this.state.pos + 1); + if (next === 61) { + this.finishOp(46, this.input.charCodeAt(this.state.pos + 2) === 61 ? 3 : 2); + return; + } + if (code === 61 && next === 62) { + this.state.pos += 2; + this.finishToken(19); + return; + } + this.finishOp(code === 61 ? 29 : 35, 1); + } + readToken_question() { + const next = this.input.charCodeAt(this.state.pos + 1); + const next2 = this.input.charCodeAt(this.state.pos + 2); + if (next === 63) { + if (next2 === 61) { + this.finishOp(30, 3); + } else { + this.finishOp(40, 2); + } + } else if (next === 46 && !(next2 >= 48 && next2 <= 57)) { + this.state.pos += 2; + this.finishToken(18); + } else { + ++this.state.pos; + this.finishToken(17); + } + } + getTokenFromCode(code) { + switch (code) { + case 46: + this.readToken_dot(); + return; + case 40: + ++this.state.pos; + this.finishToken(10); + return; + case 41: + ++this.state.pos; + this.finishToken(11); + return; + case 59: + ++this.state.pos; + this.finishToken(13); + return; + case 44: + ++this.state.pos; + this.finishToken(12); + return; + case 91: + if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) { + if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") { + throw this.raise(Errors.TupleExpressionBarIncorrectStartSyntaxType, this.state.curPosition()); + } + this.state.pos += 2; + this.finishToken(2); + } else { + ++this.state.pos; + this.finishToken(0); + } + return; + case 93: + ++this.state.pos; + this.finishToken(3); + return; + case 123: + if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) { + if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") { + throw this.raise(Errors.RecordExpressionBarIncorrectStartSyntaxType, this.state.curPosition()); + } + this.state.pos += 2; + this.finishToken(6); + } else { + ++this.state.pos; + this.finishToken(5); + } + return; + case 125: + ++this.state.pos; + this.finishToken(8); + return; + case 58: + if (this.hasPlugin("functionBind") && this.input.charCodeAt(this.state.pos + 1) === 58) { + this.finishOp(15, 2); + } else { + ++this.state.pos; + this.finishToken(14); + } + return; + case 63: + this.readToken_question(); + return; + case 96: + this.readTemplateToken(); + return; + case 48: + { + const next = this.input.charCodeAt(this.state.pos + 1); + if (next === 120 || next === 88) { + this.readRadixNumber(16); + return; + } + if (next === 111 || next === 79) { + this.readRadixNumber(8); + return; + } + if (next === 98 || next === 66) { + this.readRadixNumber(2); + return; + } + } + case 49: + case 50: + case 51: + case 52: + case 53: + case 54: + case 55: + case 56: + case 57: + this.readNumber(false); + return; + case 34: + case 39: + this.readString(code); + return; + case 47: + this.readToken_slash(); + return; + case 37: + case 42: + this.readToken_mult_modulo(code); + return; + case 124: + case 38: + this.readToken_pipe_amp(code); + return; + case 94: + this.readToken_caret(); + return; + case 43: + case 45: + this.readToken_plus_min(code); + return; + case 60: + this.readToken_lt(); + return; + case 62: + this.readToken_gt(); + return; + case 61: + case 33: + this.readToken_eq_excl(code); + return; + case 126: + this.finishOp(36, 1); + return; + case 64: + this.readToken_atSign(); + return; + case 35: + this.readToken_numberSign(); + return; + case 92: + this.readWord(); + return; + default: + if (isIdentifierStart(code)) { + this.readWord(code); + return; + } + } + throw this.raise(Errors.InvalidOrUnexpectedToken, this.state.curPosition(), { + unexpected: String.fromCodePoint(code) + }); + } + finishOp(type, size) { + const str = this.input.slice(this.state.pos, this.state.pos + size); + this.state.pos += size; + this.finishToken(type, str); + } + readRegexp() { + const startLoc = this.state.startLoc; + const start = this.state.start + 1; + let escaped, inClass; + let { + pos + } = this.state; + for (;; ++pos) { + if (pos >= this.length) { + throw this.raise(Errors.UnterminatedRegExp, createPositionWithColumnOffset(startLoc, 1)); + } + const ch = this.input.charCodeAt(pos); + if (isNewLine(ch)) { + throw this.raise(Errors.UnterminatedRegExp, createPositionWithColumnOffset(startLoc, 1)); + } + if (escaped) { + escaped = false; + } else { + if (ch === 91) { + inClass = true; + } else if (ch === 93 && inClass) { + inClass = false; + } else if (ch === 47 && !inClass) { + break; + } + escaped = ch === 92; + } + } + const content = this.input.slice(start, pos); + ++pos; + let mods = ""; + const nextPos = () => createPositionWithColumnOffset(startLoc, pos + 2 - start); + while (pos < this.length) { + const cp = this.codePointAtPos(pos); + const char = String.fromCharCode(cp); + if (VALID_REGEX_FLAGS.has(cp)) { + if (cp === 118) { + if (mods.includes("u")) { + this.raise(Errors.IncompatibleRegExpUVFlags, nextPos()); + } + } else if (cp === 117) { + if (mods.includes("v")) { + this.raise(Errors.IncompatibleRegExpUVFlags, nextPos()); + } + } + if (mods.includes(char)) { + this.raise(Errors.DuplicateRegExpFlags, nextPos()); + } + } else if (isIdentifierChar(cp) || cp === 92) { + this.raise(Errors.MalformedRegExpFlags, nextPos()); + } else { + break; + } + ++pos; + mods += char; + } + this.state.pos = pos; + this.finishToken(137, { + pattern: content, + flags: mods + }); + } + readInt(radix, len, forceLen = false, allowNumSeparator = true) { + const { + n, + pos + } = readInt(this.input, this.state.pos, this.state.lineStart, this.state.curLine, radix, len, forceLen, allowNumSeparator, this.errorHandlers_readInt, false); + this.state.pos = pos; + return n; + } + readRadixNumber(radix) { + const startLoc = this.state.curPosition(); + let isBigInt = false; + this.state.pos += 2; + const val = this.readInt(radix); + if (val == null) { + this.raise(Errors.InvalidDigit, createPositionWithColumnOffset(startLoc, 2), { + radix + }); + } + const next = this.input.charCodeAt(this.state.pos); + if (next === 110) { + ++this.state.pos; + isBigInt = true; + } else if (next === 109) { + throw this.raise(Errors.InvalidDecimal, startLoc); + } + if (isIdentifierStart(this.codePointAtPos(this.state.pos))) { + throw this.raise(Errors.NumberIdentifier, this.state.curPosition()); + } + if (isBigInt) { + const str = this.input.slice(startLoc.index, this.state.pos).replace(/[_n]/g, ""); + this.finishToken(135, str); + return; + } + this.finishToken(134, val); + } + readNumber(startsWithDot) { + const start = this.state.pos; + const startLoc = this.state.curPosition(); + let isFloat = false; + let isBigInt = false; + let isDecimal = false; + let hasExponent = false; + let isOctal = false; + if (!startsWithDot && this.readInt(10) === null) { + this.raise(Errors.InvalidNumber, this.state.curPosition()); + } + const hasLeadingZero = this.state.pos - start >= 2 && this.input.charCodeAt(start) === 48; + if (hasLeadingZero) { + const integer = this.input.slice(start, this.state.pos); + this.recordStrictModeErrors(Errors.StrictOctalLiteral, startLoc); + if (!this.state.strict) { + const underscorePos = integer.indexOf("_"); + if (underscorePos > 0) { + this.raise(Errors.ZeroDigitNumericSeparator, createPositionWithColumnOffset(startLoc, underscorePos)); + } + } + isOctal = hasLeadingZero && !/[89]/.test(integer); + } + let next = this.input.charCodeAt(this.state.pos); + if (next === 46 && !isOctal) { + ++this.state.pos; + this.readInt(10); + isFloat = true; + next = this.input.charCodeAt(this.state.pos); + } + if ((next === 69 || next === 101) && !isOctal) { + next = this.input.charCodeAt(++this.state.pos); + if (next === 43 || next === 45) { + ++this.state.pos; + } + if (this.readInt(10) === null) { + this.raise(Errors.InvalidOrMissingExponent, startLoc); + } + isFloat = true; + hasExponent = true; + next = this.input.charCodeAt(this.state.pos); + } + if (next === 110) { + if (isFloat || hasLeadingZero) { + this.raise(Errors.InvalidBigIntLiteral, startLoc); + } + ++this.state.pos; + isBigInt = true; + } + if (next === 109) { + this.expectPlugin("decimal", this.state.curPosition()); + if (hasExponent || hasLeadingZero) { + this.raise(Errors.InvalidDecimal, startLoc); + } + ++this.state.pos; + isDecimal = true; + } + if (isIdentifierStart(this.codePointAtPos(this.state.pos))) { + throw this.raise(Errors.NumberIdentifier, this.state.curPosition()); + } + const str = this.input.slice(start, this.state.pos).replace(/[_mn]/g, ""); + if (isBigInt) { + this.finishToken(135, str); + return; + } + if (isDecimal) { + this.finishToken(136, str); + return; + } + const val = isOctal ? parseInt(str, 8) : parseFloat(str); + this.finishToken(134, val); + } + readCodePoint(throwOnInvalid) { + const { + code, + pos + } = readCodePoint(this.input, this.state.pos, this.state.lineStart, this.state.curLine, throwOnInvalid, this.errorHandlers_readCodePoint); + this.state.pos = pos; + return code; + } + readString(quote) { + const { + str, + pos, + curLine, + lineStart + } = readStringContents(quote === 34 ? "double" : "single", this.input, this.state.pos + 1, this.state.lineStart, this.state.curLine, this.errorHandlers_readStringContents_string); + this.state.pos = pos + 1; + this.state.lineStart = lineStart; + this.state.curLine = curLine; + this.finishToken(133, str); + } + readTemplateContinuation() { + if (!this.match(8)) { + this.unexpected(null, 8); + } + this.state.pos--; + this.readTemplateToken(); + } + readTemplateToken() { + const opening = this.input[this.state.pos]; + const { + str, + firstInvalidLoc, + pos, + curLine, + lineStart + } = readStringContents("template", this.input, this.state.pos + 1, this.state.lineStart, this.state.curLine, this.errorHandlers_readStringContents_template); + this.state.pos = pos + 1; + this.state.lineStart = lineStart; + this.state.curLine = curLine; + if (firstInvalidLoc) { + this.state.firstInvalidTemplateEscapePos = new Position(firstInvalidLoc.curLine, firstInvalidLoc.pos - firstInvalidLoc.lineStart, firstInvalidLoc.pos); + } + if (this.input.codePointAt(pos) === 96) { + this.finishToken(24, firstInvalidLoc ? null : opening + str + "`"); + } else { + this.state.pos++; + this.finishToken(25, firstInvalidLoc ? null : opening + str + "${"); + } + } + recordStrictModeErrors(toParseError, at) { + const index = at.index; + if (this.state.strict && !this.state.strictErrors.has(index)) { + this.raise(toParseError, at); + } else { + this.state.strictErrors.set(index, [toParseError, at]); + } + } + readWord1(firstCode) { + this.state.containsEsc = false; + let word = ""; + const start = this.state.pos; + let chunkStart = this.state.pos; + if (firstCode !== undefined) { + this.state.pos += firstCode <= 0xffff ? 1 : 2; + } + while (this.state.pos < this.length) { + const ch = this.codePointAtPos(this.state.pos); + if (isIdentifierChar(ch)) { + this.state.pos += ch <= 0xffff ? 1 : 2; + } else if (ch === 92) { + this.state.containsEsc = true; + word += this.input.slice(chunkStart, this.state.pos); + const escStart = this.state.curPosition(); + const identifierCheck = this.state.pos === start ? isIdentifierStart : isIdentifierChar; + if (this.input.charCodeAt(++this.state.pos) !== 117) { + this.raise(Errors.MissingUnicodeEscape, this.state.curPosition()); + chunkStart = this.state.pos - 1; + continue; + } + ++this.state.pos; + const esc = this.readCodePoint(true); + if (esc !== null) { + if (!identifierCheck(esc)) { + this.raise(Errors.EscapedCharNotAnIdentifier, escStart); + } + word += String.fromCodePoint(esc); + } + chunkStart = this.state.pos; + } else { + break; + } + } + return word + this.input.slice(chunkStart, this.state.pos); + } + readWord(firstCode) { + const word = this.readWord1(firstCode); + const type = keywords$1.get(word); + if (type !== undefined) { + this.finishToken(type, tokenLabelName(type)); + } else { + this.finishToken(132, word); + } + } + checkKeywordEscapes() { + const { + type + } = this.state; + if (tokenIsKeyword(type) && this.state.containsEsc) { + this.raise(Errors.InvalidEscapedReservedWord, this.state.startLoc, { + reservedWord: tokenLabelName(type) + }); + } + } + raise(toParseError, at, details = {}) { + const loc = at instanceof Position ? at : at.loc.start; + const error = toParseError(loc, details); + if (!this.options.errorRecovery) throw error; + if (!this.isLookahead) this.state.errors.push(error); + return error; + } + raiseOverwrite(toParseError, at, details = {}) { + const loc = at instanceof Position ? at : at.loc.start; + const pos = loc.index; + const errors = this.state.errors; + for (let i = errors.length - 1; i >= 0; i--) { + const error = errors[i]; + if (error.loc.index === pos) { + return errors[i] = toParseError(loc, details); + } + if (error.loc.index < pos) break; + } + return this.raise(toParseError, at, details); + } + updateContext(prevType) {} + unexpected(loc, type) { + throw this.raise(Errors.UnexpectedToken, loc != null ? loc : this.state.startLoc, { + expected: type ? tokenLabelName(type) : null + }); + } + expectPlugin(pluginName, loc) { + if (this.hasPlugin(pluginName)) { + return true; + } + throw this.raise(Errors.MissingPlugin, loc != null ? loc : this.state.startLoc, { + missingPlugin: [pluginName] + }); + } + expectOnePlugin(pluginNames) { + if (!pluginNames.some(name => this.hasPlugin(name))) { + throw this.raise(Errors.MissingOneOfPlugins, this.state.startLoc, { + missingPlugin: pluginNames + }); + } + } + errorBuilder(error) { + return (pos, lineStart, curLine) => { + this.raise(error, buildPosition(pos, lineStart, curLine)); + }; + } +} +class ClassScope { + constructor() { + this.privateNames = new Set(); + this.loneAccessors = new Map(); + this.undefinedPrivateNames = new Map(); + } +} +class ClassScopeHandler { + constructor(parser) { + this.parser = void 0; + this.stack = []; + this.undefinedPrivateNames = new Map(); + this.parser = parser; + } + current() { + return this.stack[this.stack.length - 1]; + } + enter() { + this.stack.push(new ClassScope()); + } + exit() { + const oldClassScope = this.stack.pop(); + const current = this.current(); + for (const [name, loc] of Array.from(oldClassScope.undefinedPrivateNames)) { + if (current) { + if (!current.undefinedPrivateNames.has(name)) { + current.undefinedPrivateNames.set(name, loc); + } + } else { + this.parser.raise(Errors.InvalidPrivateFieldResolution, loc, { + identifierName: name + }); + } + } + } + declarePrivateName(name, elementType, loc) { + const { + privateNames, + loneAccessors, + undefinedPrivateNames + } = this.current(); + let redefined = privateNames.has(name); + if (elementType & 3) { + const accessor = redefined && loneAccessors.get(name); + if (accessor) { + const oldStatic = accessor & 4; + const newStatic = elementType & 4; + const oldKind = accessor & 3; + const newKind = elementType & 3; + redefined = oldKind === newKind || oldStatic !== newStatic; + if (!redefined) loneAccessors.delete(name); + } else if (!redefined) { + loneAccessors.set(name, elementType); + } + } + if (redefined) { + this.parser.raise(Errors.PrivateNameRedeclaration, loc, { + identifierName: name + }); + } + privateNames.add(name); + undefinedPrivateNames.delete(name); + } + usePrivateName(name, loc) { + let classScope; + for (classScope of this.stack) { + if (classScope.privateNames.has(name)) return; + } + if (classScope) { + classScope.undefinedPrivateNames.set(name, loc); + } else { + this.parser.raise(Errors.InvalidPrivateFieldResolution, loc, { + identifierName: name + }); + } + } +} +class ExpressionScope { + constructor(type = 0) { + this.type = type; + } + canBeArrowParameterDeclaration() { + return this.type === 2 || this.type === 1; + } + isCertainlyParameterDeclaration() { + return this.type === 3; + } +} +class ArrowHeadParsingScope extends ExpressionScope { + constructor(type) { + super(type); + this.declarationErrors = new Map(); + } + recordDeclarationError(ParsingErrorClass, at) { + const index = at.index; + this.declarationErrors.set(index, [ParsingErrorClass, at]); + } + clearDeclarationError(index) { + this.declarationErrors.delete(index); + } + iterateErrors(iterator) { + this.declarationErrors.forEach(iterator); + } +} +class ExpressionScopeHandler { + constructor(parser) { + this.parser = void 0; + this.stack = [new ExpressionScope()]; + this.parser = parser; + } + enter(scope) { + this.stack.push(scope); + } + exit() { + this.stack.pop(); + } + recordParameterInitializerError(toParseError, node) { + const origin = node.loc.start; + const { + stack + } = this; + let i = stack.length - 1; + let scope = stack[i]; + while (!scope.isCertainlyParameterDeclaration()) { + if (scope.canBeArrowParameterDeclaration()) { + scope.recordDeclarationError(toParseError, origin); + } else { + return; + } + scope = stack[--i]; + } + this.parser.raise(toParseError, origin); + } + recordArrowParameterBindingError(error, node) { + const { + stack + } = this; + const scope = stack[stack.length - 1]; + const origin = node.loc.start; + if (scope.isCertainlyParameterDeclaration()) { + this.parser.raise(error, origin); + } else if (scope.canBeArrowParameterDeclaration()) { + scope.recordDeclarationError(error, origin); + } else { + return; + } + } + recordAsyncArrowParametersError(at) { + const { + stack + } = this; + let i = stack.length - 1; + let scope = stack[i]; + while (scope.canBeArrowParameterDeclaration()) { + if (scope.type === 2) { + scope.recordDeclarationError(Errors.AwaitBindingIdentifier, at); + } + scope = stack[--i]; + } + } + validateAsPattern() { + const { + stack + } = this; + const currentScope = stack[stack.length - 1]; + if (!currentScope.canBeArrowParameterDeclaration()) return; + currentScope.iterateErrors(([toParseError, loc]) => { + this.parser.raise(toParseError, loc); + let i = stack.length - 2; + let scope = stack[i]; + while (scope.canBeArrowParameterDeclaration()) { + scope.clearDeclarationError(loc.index); + scope = stack[--i]; + } + }); + } +} +function newParameterDeclarationScope() { + return new ExpressionScope(3); +} +function newArrowHeadScope() { + return new ArrowHeadParsingScope(1); +} +function newAsyncArrowScope() { + return new ArrowHeadParsingScope(2); +} +function newExpressionScope() { + return new ExpressionScope(); +} +class ProductionParameterHandler { + constructor() { + this.stacks = []; + } + enter(flags) { + this.stacks.push(flags); + } + exit() { + this.stacks.pop(); + } + currentFlags() { + return this.stacks[this.stacks.length - 1]; + } + get hasAwait() { + return (this.currentFlags() & 2) > 0; + } + get hasYield() { + return (this.currentFlags() & 1) > 0; + } + get hasReturn() { + return (this.currentFlags() & 4) > 0; + } + get hasIn() { + return (this.currentFlags() & 8) > 0; + } +} +function functionFlags(isAsync, isGenerator) { + return (isAsync ? 2 : 0) | (isGenerator ? 1 : 0); +} +class UtilParser extends Tokenizer { + addExtra(node, key, value, enumerable = true) { + if (!node) return; + let { + extra + } = node; + if (extra == null) { + extra = {}; + node.extra = extra; + } + if (enumerable) { + extra[key] = value; + } else { + Object.defineProperty(extra, key, { + enumerable, + value + }); + } + } + isContextual(token) { + return this.state.type === token && !this.state.containsEsc; + } + isUnparsedContextual(nameStart, name) { + const nameEnd = nameStart + name.length; + if (this.input.slice(nameStart, nameEnd) === name) { + const nextCh = this.input.charCodeAt(nameEnd); + return !(isIdentifierChar(nextCh) || (nextCh & 0xfc00) === 0xd800); + } + return false; + } + isLookaheadContextual(name) { + const next = this.nextTokenStart(); + return this.isUnparsedContextual(next, name); + } + eatContextual(token) { + if (this.isContextual(token)) { + this.next(); + return true; + } + return false; + } + expectContextual(token, toParseError) { + if (!this.eatContextual(token)) { + if (toParseError != null) { + throw this.raise(toParseError, this.state.startLoc); + } + this.unexpected(null, token); + } + } + canInsertSemicolon() { + return this.match(139) || this.match(8) || this.hasPrecedingLineBreak(); + } + hasPrecedingLineBreak() { + return hasNewLine(this.input, this.state.lastTokEndLoc.index, this.state.start); + } + hasFollowingLineBreak() { + return hasNewLine(this.input, this.state.end, this.nextTokenStart()); + } + isLineTerminator() { + return this.eat(13) || this.canInsertSemicolon(); + } + semicolon(allowAsi = true) { + if (allowAsi ? this.isLineTerminator() : this.eat(13)) return; + this.raise(Errors.MissingSemicolon, this.state.lastTokEndLoc); + } + expect(type, loc) { + if (!this.eat(type)) { + this.unexpected(loc, type); + } + } + tryParse(fn, oldState = this.state.clone()) { + const abortSignal = { + node: null + }; + try { + const node = fn((node = null) => { + abortSignal.node = node; + throw abortSignal; + }); + if (this.state.errors.length > oldState.errors.length) { + const failState = this.state; + this.state = oldState; + this.state.tokensLength = failState.tokensLength; + return { + node, + error: failState.errors[oldState.errors.length], + thrown: false, + aborted: false, + failState + }; + } + return { + node, + error: null, + thrown: false, + aborted: false, + failState: null + }; + } catch (error) { + const failState = this.state; + this.state = oldState; + if (error instanceof SyntaxError) { + return { + node: null, + error, + thrown: true, + aborted: false, + failState + }; + } + if (error === abortSignal) { + return { + node: abortSignal.node, + error: null, + thrown: false, + aborted: true, + failState + }; + } + throw error; + } + } + checkExpressionErrors(refExpressionErrors, andThrow) { + if (!refExpressionErrors) return false; + const { + shorthandAssignLoc, + doubleProtoLoc, + privateKeyLoc, + optionalParametersLoc + } = refExpressionErrors; + const hasErrors = !!shorthandAssignLoc || !!doubleProtoLoc || !!optionalParametersLoc || !!privateKeyLoc; + if (!andThrow) { + return hasErrors; + } + if (shorthandAssignLoc != null) { + this.raise(Errors.InvalidCoverInitializedName, shorthandAssignLoc); + } + if (doubleProtoLoc != null) { + this.raise(Errors.DuplicateProto, doubleProtoLoc); + } + if (privateKeyLoc != null) { + this.raise(Errors.UnexpectedPrivateField, privateKeyLoc); + } + if (optionalParametersLoc != null) { + this.unexpected(optionalParametersLoc); + } + } + isLiteralPropertyName() { + return tokenIsLiteralPropertyName(this.state.type); + } + isPrivateName(node) { + return node.type === "PrivateName"; + } + getPrivateNameSV(node) { + return node.id.name; + } + hasPropertyAsPrivateName(node) { + return (node.type === "MemberExpression" || node.type === "OptionalMemberExpression") && this.isPrivateName(node.property); + } + isObjectProperty(node) { + return node.type === "ObjectProperty"; + } + isObjectMethod(node) { + return node.type === "ObjectMethod"; + } + initializeScopes(inModule = this.options.sourceType === "module") { + const oldLabels = this.state.labels; + this.state.labels = []; + const oldExportedIdentifiers = this.exportedIdentifiers; + this.exportedIdentifiers = new Set(); + const oldInModule = this.inModule; + this.inModule = inModule; + const oldScope = this.scope; + const ScopeHandler = this.getScopeHandler(); + this.scope = new ScopeHandler(this, inModule); + const oldProdParam = this.prodParam; + this.prodParam = new ProductionParameterHandler(); + const oldClassScope = this.classScope; + this.classScope = new ClassScopeHandler(this); + const oldExpressionScope = this.expressionScope; + this.expressionScope = new ExpressionScopeHandler(this); + return () => { + this.state.labels = oldLabels; + this.exportedIdentifiers = oldExportedIdentifiers; + this.inModule = oldInModule; + this.scope = oldScope; + this.prodParam = oldProdParam; + this.classScope = oldClassScope; + this.expressionScope = oldExpressionScope; + }; + } + enterInitialScopes() { + let paramFlags = 0; + if (this.inModule) { + paramFlags |= 2; + } + this.scope.enter(1); + this.prodParam.enter(paramFlags); + } + checkDestructuringPrivate(refExpressionErrors) { + const { + privateKeyLoc + } = refExpressionErrors; + if (privateKeyLoc !== null) { + this.expectPlugin("destructuringPrivate", privateKeyLoc); + } + } +} +class ExpressionErrors { + constructor() { + this.shorthandAssignLoc = null; + this.doubleProtoLoc = null; + this.privateKeyLoc = null; + this.optionalParametersLoc = null; + } +} +class Node { + constructor(parser, pos, loc) { + this.type = ""; + this.start = pos; + this.end = 0; + this.loc = new SourceLocation(loc); + if (parser != null && parser.options.ranges) this.range = [pos, 0]; + if (parser != null && parser.filename) this.loc.filename = parser.filename; + } +} +const NodePrototype = Node.prototype; +{ + NodePrototype.__clone = function () { + const newNode = new Node(undefined, this.start, this.loc.start); + const keys = Object.keys(this); + for (let i = 0, length = keys.length; i < length; i++) { + const key = keys[i]; + if (key !== "leadingComments" && key !== "trailingComments" && key !== "innerComments") { + newNode[key] = this[key]; + } + } + return newNode; + }; +} +function clonePlaceholder(node) { + return cloneIdentifier(node); +} +function cloneIdentifier(node) { + const { + type, + start, + end, + loc, + range, + extra, + name + } = node; + const cloned = Object.create(NodePrototype); + cloned.type = type; + cloned.start = start; + cloned.end = end; + cloned.loc = loc; + cloned.range = range; + cloned.extra = extra; + cloned.name = name; + if (type === "Placeholder") { + cloned.expectedNode = node.expectedNode; + } + return cloned; +} +function cloneStringLiteral(node) { + const { + type, + start, + end, + loc, + range, + extra + } = node; + if (type === "Placeholder") { + return clonePlaceholder(node); + } + const cloned = Object.create(NodePrototype); + cloned.type = type; + cloned.start = start; + cloned.end = end; + cloned.loc = loc; + cloned.range = range; + if (node.raw !== undefined) { + cloned.raw = node.raw; + } else { + cloned.extra = extra; + } + cloned.value = node.value; + return cloned; +} +class NodeUtils extends UtilParser { + startNode() { + const loc = this.state.startLoc; + return new Node(this, loc.index, loc); + } + startNodeAt(loc) { + return new Node(this, loc.index, loc); + } + startNodeAtNode(type) { + return this.startNodeAt(type.loc.start); + } + finishNode(node, type) { + return this.finishNodeAt(node, type, this.state.lastTokEndLoc); + } + finishNodeAt(node, type, endLoc) { + node.type = type; + node.end = endLoc.index; + node.loc.end = endLoc; + if (this.options.ranges) node.range[1] = endLoc.index; + if (this.options.attachComment) this.processComment(node); + return node; + } + resetStartLocation(node, startLoc) { + node.start = startLoc.index; + node.loc.start = startLoc; + if (this.options.ranges) node.range[0] = startLoc.index; + } + resetEndLocation(node, endLoc = this.state.lastTokEndLoc) { + node.end = endLoc.index; + node.loc.end = endLoc; + if (this.options.ranges) node.range[1] = endLoc.index; + } + resetStartLocationFromNode(node, locationNode) { + this.resetStartLocation(node, locationNode.loc.start); + } +} +const reservedTypes = new Set(["_", "any", "bool", "boolean", "empty", "extends", "false", "interface", "mixed", "null", "number", "static", "string", "true", "typeof", "void"]); +const FlowErrors = ParseErrorEnum`flow`({ + AmbiguousConditionalArrow: "Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.", + AmbiguousDeclareModuleKind: "Found both `declare module.exports` and `declare export` in the same module. Modules can only have 1 since they are either an ES module or they are a CommonJS module.", + AssignReservedType: ({ + reservedType + }) => `Cannot overwrite reserved type ${reservedType}.`, + DeclareClassElement: "The `declare` modifier can only appear on class fields.", + DeclareClassFieldInitializer: "Initializers are not allowed in fields with the `declare` modifier.", + DuplicateDeclareModuleExports: "Duplicate `declare module.exports` statement.", + EnumBooleanMemberNotInitialized: ({ + memberName, + enumName + }) => `Boolean enum members need to be initialized. Use either \`${memberName} = true,\` or \`${memberName} = false,\` in enum \`${enumName}\`.`, + EnumDuplicateMemberName: ({ + memberName, + enumName + }) => `Enum member names need to be unique, but the name \`${memberName}\` has already been used before in enum \`${enumName}\`.`, + EnumInconsistentMemberValues: ({ + enumName + }) => `Enum \`${enumName}\` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.`, + EnumInvalidExplicitType: ({ + invalidEnumType, + enumName + }) => `Enum type \`${invalidEnumType}\` is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${enumName}\`.`, + EnumInvalidExplicitTypeUnknownSupplied: ({ + enumName + }) => `Supplied enum type is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${enumName}\`.`, + EnumInvalidMemberInitializerPrimaryType: ({ + enumName, + memberName, + explicitType + }) => `Enum \`${enumName}\` has type \`${explicitType}\`, so the initializer of \`${memberName}\` needs to be a ${explicitType} literal.`, + EnumInvalidMemberInitializerSymbolType: ({ + enumName, + memberName + }) => `Symbol enum members cannot be initialized. Use \`${memberName},\` in enum \`${enumName}\`.`, + EnumInvalidMemberInitializerUnknownType: ({ + enumName, + memberName + }) => `The enum member initializer for \`${memberName}\` needs to be a literal (either a boolean, number, or string) in enum \`${enumName}\`.`, + EnumInvalidMemberName: ({ + enumName, + memberName, + suggestion + }) => `Enum member names cannot start with lowercase 'a' through 'z'. Instead of using \`${memberName}\`, consider using \`${suggestion}\`, in enum \`${enumName}\`.`, + EnumNumberMemberNotInitialized: ({ + enumName, + memberName + }) => `Number enum members need to be initialized, e.g. \`${memberName} = 1\` in enum \`${enumName}\`.`, + EnumStringMemberInconsistentlyInitialized: ({ + enumName + }) => `String enum members need to consistently either all use initializers, or use no initializers, in enum \`${enumName}\`.`, + GetterMayNotHaveThisParam: "A getter cannot have a `this` parameter.", + ImportReflectionHasImportType: "An `import module` declaration can not use `type` or `typeof` keyword.", + ImportTypeShorthandOnlyInPureImport: "The `type` and `typeof` keywords on named imports can only be used on regular `import` statements. It cannot be used with `import type` or `import typeof` statements.", + InexactInsideExact: "Explicit inexact syntax cannot appear inside an explicit exact object type.", + InexactInsideNonObject: "Explicit inexact syntax cannot appear in class or interface definitions.", + InexactVariance: "Explicit inexact syntax cannot have variance.", + InvalidNonTypeImportInDeclareModule: "Imports within a `declare module` body must always be `import type` or `import typeof`.", + MissingTypeParamDefault: "Type parameter declaration needs a default, since a preceding type parameter declaration has a default.", + NestedDeclareModule: "`declare module` cannot be used inside another `declare module`.", + NestedFlowComment: "Cannot have a flow comment inside another flow comment.", + PatternIsOptional: Object.assign({ + message: "A binding pattern parameter cannot be optional in an implementation signature." + }, { + reasonCode: "OptionalBindingPattern" + }), + SetterMayNotHaveThisParam: "A setter cannot have a `this` parameter.", + SpreadVariance: "Spread properties cannot have variance.", + ThisParamAnnotationRequired: "A type annotation is required for the `this` parameter.", + ThisParamBannedInConstructor: "Constructors cannot have a `this` parameter; constructors don't bind `this` like other functions.", + ThisParamMayNotBeOptional: "The `this` parameter cannot be optional.", + ThisParamMustBeFirst: "The `this` parameter must be the first function parameter.", + ThisParamNoDefault: "The `this` parameter may not have a default value.", + TypeBeforeInitializer: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.", + TypeCastInPattern: "The type cast expression is expected to be wrapped with parenthesis.", + UnexpectedExplicitInexactInObject: "Explicit inexact syntax must appear at the end of an inexact object.", + UnexpectedReservedType: ({ + reservedType + }) => `Unexpected reserved type ${reservedType}.`, + UnexpectedReservedUnderscore: "`_` is only allowed as a type argument to call or new.", + UnexpectedSpaceBetweenModuloChecks: "Spaces between `%` and `checks` are not allowed here.", + UnexpectedSpreadType: "Spread operator cannot appear in class or interface definitions.", + UnexpectedSubtractionOperand: 'Unexpected token, expected "number" or "bigint".', + UnexpectedTokenAfterTypeParameter: "Expected an arrow function after this type parameter declaration.", + UnexpectedTypeParameterBeforeAsyncArrowFunction: "Type parameters must come after the async keyword, e.g. instead of ` async () => {}`, use `async () => {}`.", + UnsupportedDeclareExportKind: ({ + unsupportedExportKind, + suggestion + }) => `\`declare export ${unsupportedExportKind}\` is not supported. Use \`${suggestion}\` instead.`, + UnsupportedStatementInDeclareModule: "Only declares and type imports are allowed inside declare module.", + UnterminatedFlowComment: "Unterminated flow-comment." +}); +function isEsModuleType(bodyElement) { + return bodyElement.type === "DeclareExportAllDeclaration" || bodyElement.type === "DeclareExportDeclaration" && (!bodyElement.declaration || bodyElement.declaration.type !== "TypeAlias" && bodyElement.declaration.type !== "InterfaceDeclaration"); +} +function hasTypeImportKind(node) { + return node.importKind === "type" || node.importKind === "typeof"; +} +const exportSuggestions = { + const: "declare export var", + let: "declare export var", + type: "export type", + interface: "export interface" +}; +function partition(list, test) { + const list1 = []; + const list2 = []; + for (let i = 0; i < list.length; i++) { + (test(list[i], i, list) ? list1 : list2).push(list[i]); + } + return [list1, list2]; +} +const FLOW_PRAGMA_REGEX = /\*?\s*@((?:no)?flow)\b/; +var flow = superClass => class FlowParserMixin extends superClass { + constructor(...args) { + super(...args); + this.flowPragma = undefined; + } + getScopeHandler() { + return FlowScopeHandler; + } + shouldParseTypes() { + return this.getPluginOption("flow", "all") || this.flowPragma === "flow"; + } + shouldParseEnums() { + return !!this.getPluginOption("flow", "enums"); + } + finishToken(type, val) { + if (type !== 133 && type !== 13 && type !== 28) { + if (this.flowPragma === undefined) { + this.flowPragma = null; + } + } + super.finishToken(type, val); + } + addComment(comment) { + if (this.flowPragma === undefined) { + const matches = FLOW_PRAGMA_REGEX.exec(comment.value); + if (!matches) ;else if (matches[1] === "flow") { + this.flowPragma = "flow"; + } else if (matches[1] === "noflow") { + this.flowPragma = "noflow"; + } else { + throw new Error("Unexpected flow pragma"); + } + } + super.addComment(comment); + } + flowParseTypeInitialiser(tok) { + const oldInType = this.state.inType; + this.state.inType = true; + this.expect(tok || 14); + const type = this.flowParseType(); + this.state.inType = oldInType; + return type; + } + flowParsePredicate() { + const node = this.startNode(); + const moduloLoc = this.state.startLoc; + this.next(); + this.expectContextual(110); + if (this.state.lastTokStartLoc.index > moduloLoc.index + 1) { + this.raise(FlowErrors.UnexpectedSpaceBetweenModuloChecks, moduloLoc); + } + if (this.eat(10)) { + node.value = super.parseExpression(); + this.expect(11); + return this.finishNode(node, "DeclaredPredicate"); + } else { + return this.finishNode(node, "InferredPredicate"); + } + } + flowParseTypeAndPredicateInitialiser() { + const oldInType = this.state.inType; + this.state.inType = true; + this.expect(14); + let type = null; + let predicate = null; + if (this.match(54)) { + this.state.inType = oldInType; + predicate = this.flowParsePredicate(); + } else { + type = this.flowParseType(); + this.state.inType = oldInType; + if (this.match(54)) { + predicate = this.flowParsePredicate(); + } + } + return [type, predicate]; + } + flowParseDeclareClass(node) { + this.next(); + this.flowParseInterfaceish(node, true); + return this.finishNode(node, "DeclareClass"); + } + flowParseDeclareFunction(node) { + this.next(); + const id = node.id = this.parseIdentifier(); + const typeNode = this.startNode(); + const typeContainer = this.startNode(); + if (this.match(47)) { + typeNode.typeParameters = this.flowParseTypeParameterDeclaration(); + } else { + typeNode.typeParameters = null; + } + this.expect(10); + const tmp = this.flowParseFunctionTypeParams(); + typeNode.params = tmp.params; + typeNode.rest = tmp.rest; + typeNode.this = tmp._this; + this.expect(11); + [typeNode.returnType, node.predicate] = this.flowParseTypeAndPredicateInitialiser(); + typeContainer.typeAnnotation = this.finishNode(typeNode, "FunctionTypeAnnotation"); + id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation"); + this.resetEndLocation(id); + this.semicolon(); + this.scope.declareName(node.id.name, 2048, node.id.loc.start); + return this.finishNode(node, "DeclareFunction"); + } + flowParseDeclare(node, insideModule) { + if (this.match(80)) { + return this.flowParseDeclareClass(node); + } else if (this.match(68)) { + return this.flowParseDeclareFunction(node); + } else if (this.match(74)) { + return this.flowParseDeclareVariable(node); + } else if (this.eatContextual(127)) { + if (this.match(16)) { + return this.flowParseDeclareModuleExports(node); + } else { + if (insideModule) { + this.raise(FlowErrors.NestedDeclareModule, this.state.lastTokStartLoc); + } + return this.flowParseDeclareModule(node); + } + } else if (this.isContextual(130)) { + return this.flowParseDeclareTypeAlias(node); + } else if (this.isContextual(131)) { + return this.flowParseDeclareOpaqueType(node); + } else if (this.isContextual(129)) { + return this.flowParseDeclareInterface(node); + } else if (this.match(82)) { + return this.flowParseDeclareExportDeclaration(node, insideModule); + } else { + this.unexpected(); + } + } + flowParseDeclareVariable(node) { + this.next(); + node.id = this.flowParseTypeAnnotatableIdentifier(true); + this.scope.declareName(node.id.name, 5, node.id.loc.start); + this.semicolon(); + return this.finishNode(node, "DeclareVariable"); + } + flowParseDeclareModule(node) { + this.scope.enter(0); + if (this.match(133)) { + node.id = super.parseExprAtom(); + } else { + node.id = this.parseIdentifier(); + } + const bodyNode = node.body = this.startNode(); + const body = bodyNode.body = []; + this.expect(5); + while (!this.match(8)) { + let bodyNode = this.startNode(); + if (this.match(83)) { + this.next(); + if (!this.isContextual(130) && !this.match(87)) { + this.raise(FlowErrors.InvalidNonTypeImportInDeclareModule, this.state.lastTokStartLoc); + } + super.parseImport(bodyNode); + } else { + this.expectContextual(125, FlowErrors.UnsupportedStatementInDeclareModule); + bodyNode = this.flowParseDeclare(bodyNode, true); + } + body.push(bodyNode); + } + this.scope.exit(); + this.expect(8); + this.finishNode(bodyNode, "BlockStatement"); + let kind = null; + let hasModuleExport = false; + body.forEach(bodyElement => { + if (isEsModuleType(bodyElement)) { + if (kind === "CommonJS") { + this.raise(FlowErrors.AmbiguousDeclareModuleKind, bodyElement); + } + kind = "ES"; + } else if (bodyElement.type === "DeclareModuleExports") { + if (hasModuleExport) { + this.raise(FlowErrors.DuplicateDeclareModuleExports, bodyElement); + } + if (kind === "ES") { + this.raise(FlowErrors.AmbiguousDeclareModuleKind, bodyElement); + } + kind = "CommonJS"; + hasModuleExport = true; + } + }); + node.kind = kind || "CommonJS"; + return this.finishNode(node, "DeclareModule"); + } + flowParseDeclareExportDeclaration(node, insideModule) { + this.expect(82); + if (this.eat(65)) { + if (this.match(68) || this.match(80)) { + node.declaration = this.flowParseDeclare(this.startNode()); + } else { + node.declaration = this.flowParseType(); + this.semicolon(); + } + node.default = true; + return this.finishNode(node, "DeclareExportDeclaration"); + } else { + if (this.match(75) || this.isLet() || (this.isContextual(130) || this.isContextual(129)) && !insideModule) { + const label = this.state.value; + throw this.raise(FlowErrors.UnsupportedDeclareExportKind, this.state.startLoc, { + unsupportedExportKind: label, + suggestion: exportSuggestions[label] + }); + } + if (this.match(74) || this.match(68) || this.match(80) || this.isContextual(131)) { + node.declaration = this.flowParseDeclare(this.startNode()); + node.default = false; + return this.finishNode(node, "DeclareExportDeclaration"); + } else if (this.match(55) || this.match(5) || this.isContextual(129) || this.isContextual(130) || this.isContextual(131)) { + node = this.parseExport(node, null); + if (node.type === "ExportNamedDeclaration") { + node.type = "ExportDeclaration"; + node.default = false; + delete node.exportKind; + } + node.type = "Declare" + node.type; + return node; + } + } + this.unexpected(); + } + flowParseDeclareModuleExports(node) { + this.next(); + this.expectContextual(111); + node.typeAnnotation = this.flowParseTypeAnnotation(); + this.semicolon(); + return this.finishNode(node, "DeclareModuleExports"); + } + flowParseDeclareTypeAlias(node) { + this.next(); + const finished = this.flowParseTypeAlias(node); + finished.type = "DeclareTypeAlias"; + return finished; + } + flowParseDeclareOpaqueType(node) { + this.next(); + const finished = this.flowParseOpaqueType(node, true); + finished.type = "DeclareOpaqueType"; + return finished; + } + flowParseDeclareInterface(node) { + this.next(); + this.flowParseInterfaceish(node, false); + return this.finishNode(node, "DeclareInterface"); + } + flowParseInterfaceish(node, isClass) { + node.id = this.flowParseRestrictedIdentifier(!isClass, true); + this.scope.declareName(node.id.name, isClass ? 17 : 8201, node.id.loc.start); + if (this.match(47)) { + node.typeParameters = this.flowParseTypeParameterDeclaration(); + } else { + node.typeParameters = null; + } + node.extends = []; + if (this.eat(81)) { + do { + node.extends.push(this.flowParseInterfaceExtends()); + } while (!isClass && this.eat(12)); + } + if (isClass) { + node.implements = []; + node.mixins = []; + if (this.eatContextual(117)) { + do { + node.mixins.push(this.flowParseInterfaceExtends()); + } while (this.eat(12)); + } + if (this.eatContextual(113)) { + do { + node.implements.push(this.flowParseInterfaceExtends()); + } while (this.eat(12)); + } + } + node.body = this.flowParseObjectType({ + allowStatic: isClass, + allowExact: false, + allowSpread: false, + allowProto: isClass, + allowInexact: false + }); + } + flowParseInterfaceExtends() { + const node = this.startNode(); + node.id = this.flowParseQualifiedTypeIdentifier(); + if (this.match(47)) { + node.typeParameters = this.flowParseTypeParameterInstantiation(); + } else { + node.typeParameters = null; + } + return this.finishNode(node, "InterfaceExtends"); + } + flowParseInterface(node) { + this.flowParseInterfaceish(node, false); + return this.finishNode(node, "InterfaceDeclaration"); + } + checkNotUnderscore(word) { + if (word === "_") { + this.raise(FlowErrors.UnexpectedReservedUnderscore, this.state.startLoc); + } + } + checkReservedType(word, startLoc, declaration) { + if (!reservedTypes.has(word)) return; + this.raise(declaration ? FlowErrors.AssignReservedType : FlowErrors.UnexpectedReservedType, startLoc, { + reservedType: word + }); + } + flowParseRestrictedIdentifier(liberal, declaration) { + this.checkReservedType(this.state.value, this.state.startLoc, declaration); + return this.parseIdentifier(liberal); + } + flowParseTypeAlias(node) { + node.id = this.flowParseRestrictedIdentifier(false, true); + this.scope.declareName(node.id.name, 8201, node.id.loc.start); + if (this.match(47)) { + node.typeParameters = this.flowParseTypeParameterDeclaration(); + } else { + node.typeParameters = null; + } + node.right = this.flowParseTypeInitialiser(29); + this.semicolon(); + return this.finishNode(node, "TypeAlias"); + } + flowParseOpaqueType(node, declare) { + this.expectContextual(130); + node.id = this.flowParseRestrictedIdentifier(true, true); + this.scope.declareName(node.id.name, 8201, node.id.loc.start); + if (this.match(47)) { + node.typeParameters = this.flowParseTypeParameterDeclaration(); + } else { + node.typeParameters = null; + } + node.supertype = null; + if (this.match(14)) { + node.supertype = this.flowParseTypeInitialiser(14); + } + node.impltype = null; + if (!declare) { + node.impltype = this.flowParseTypeInitialiser(29); + } + this.semicolon(); + return this.finishNode(node, "OpaqueType"); + } + flowParseTypeParameter(requireDefault = false) { + const nodeStartLoc = this.state.startLoc; + const node = this.startNode(); + const variance = this.flowParseVariance(); + const ident = this.flowParseTypeAnnotatableIdentifier(); + node.name = ident.name; + node.variance = variance; + node.bound = ident.typeAnnotation; + if (this.match(29)) { + this.eat(29); + node.default = this.flowParseType(); + } else { + if (requireDefault) { + this.raise(FlowErrors.MissingTypeParamDefault, nodeStartLoc); + } + } + return this.finishNode(node, "TypeParameter"); + } + flowParseTypeParameterDeclaration() { + const oldInType = this.state.inType; + const node = this.startNode(); + node.params = []; + this.state.inType = true; + if (this.match(47) || this.match(142)) { + this.next(); + } else { + this.unexpected(); + } + let defaultRequired = false; + do { + const typeParameter = this.flowParseTypeParameter(defaultRequired); + node.params.push(typeParameter); + if (typeParameter.default) { + defaultRequired = true; + } + if (!this.match(48)) { + this.expect(12); + } + } while (!this.match(48)); + this.expect(48); + this.state.inType = oldInType; + return this.finishNode(node, "TypeParameterDeclaration"); + } + flowParseTypeParameterInstantiation() { + const node = this.startNode(); + const oldInType = this.state.inType; + node.params = []; + this.state.inType = true; + this.expect(47); + const oldNoAnonFunctionType = this.state.noAnonFunctionType; + this.state.noAnonFunctionType = false; + while (!this.match(48)) { + node.params.push(this.flowParseType()); + if (!this.match(48)) { + this.expect(12); + } + } + this.state.noAnonFunctionType = oldNoAnonFunctionType; + this.expect(48); + this.state.inType = oldInType; + return this.finishNode(node, "TypeParameterInstantiation"); + } + flowParseTypeParameterInstantiationCallOrNew() { + const node = this.startNode(); + const oldInType = this.state.inType; + node.params = []; + this.state.inType = true; + this.expect(47); + while (!this.match(48)) { + node.params.push(this.flowParseTypeOrImplicitInstantiation()); + if (!this.match(48)) { + this.expect(12); + } + } + this.expect(48); + this.state.inType = oldInType; + return this.finishNode(node, "TypeParameterInstantiation"); + } + flowParseInterfaceType() { + const node = this.startNode(); + this.expectContextual(129); + node.extends = []; + if (this.eat(81)) { + do { + node.extends.push(this.flowParseInterfaceExtends()); + } while (this.eat(12)); + } + node.body = this.flowParseObjectType({ + allowStatic: false, + allowExact: false, + allowSpread: false, + allowProto: false, + allowInexact: false + }); + return this.finishNode(node, "InterfaceTypeAnnotation"); + } + flowParseObjectPropertyKey() { + return this.match(134) || this.match(133) ? super.parseExprAtom() : this.parseIdentifier(true); + } + flowParseObjectTypeIndexer(node, isStatic, variance) { + node.static = isStatic; + if (this.lookahead().type === 14) { + node.id = this.flowParseObjectPropertyKey(); + node.key = this.flowParseTypeInitialiser(); + } else { + node.id = null; + node.key = this.flowParseType(); + } + this.expect(3); + node.value = this.flowParseTypeInitialiser(); + node.variance = variance; + return this.finishNode(node, "ObjectTypeIndexer"); + } + flowParseObjectTypeInternalSlot(node, isStatic) { + node.static = isStatic; + node.id = this.flowParseObjectPropertyKey(); + this.expect(3); + this.expect(3); + if (this.match(47) || this.match(10)) { + node.method = true; + node.optional = false; + node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.loc.start)); + } else { + node.method = false; + if (this.eat(17)) { + node.optional = true; + } + node.value = this.flowParseTypeInitialiser(); + } + return this.finishNode(node, "ObjectTypeInternalSlot"); + } + flowParseObjectTypeMethodish(node) { + node.params = []; + node.rest = null; + node.typeParameters = null; + node.this = null; + if (this.match(47)) { + node.typeParameters = this.flowParseTypeParameterDeclaration(); + } + this.expect(10); + if (this.match(78)) { + node.this = this.flowParseFunctionTypeParam(true); + node.this.name = null; + if (!this.match(11)) { + this.expect(12); + } + } + while (!this.match(11) && !this.match(21)) { + node.params.push(this.flowParseFunctionTypeParam(false)); + if (!this.match(11)) { + this.expect(12); + } + } + if (this.eat(21)) { + node.rest = this.flowParseFunctionTypeParam(false); + } + this.expect(11); + node.returnType = this.flowParseTypeInitialiser(); + return this.finishNode(node, "FunctionTypeAnnotation"); + } + flowParseObjectTypeCallProperty(node, isStatic) { + const valueNode = this.startNode(); + node.static = isStatic; + node.value = this.flowParseObjectTypeMethodish(valueNode); + return this.finishNode(node, "ObjectTypeCallProperty"); + } + flowParseObjectType({ + allowStatic, + allowExact, + allowSpread, + allowProto, + allowInexact + }) { + const oldInType = this.state.inType; + this.state.inType = true; + const nodeStart = this.startNode(); + nodeStart.callProperties = []; + nodeStart.properties = []; + nodeStart.indexers = []; + nodeStart.internalSlots = []; + let endDelim; + let exact; + let inexact = false; + if (allowExact && this.match(6)) { + this.expect(6); + endDelim = 9; + exact = true; + } else { + this.expect(5); + endDelim = 8; + exact = false; + } + nodeStart.exact = exact; + while (!this.match(endDelim)) { + let isStatic = false; + let protoStartLoc = null; + let inexactStartLoc = null; + const node = this.startNode(); + if (allowProto && this.isContextual(118)) { + const lookahead = this.lookahead(); + if (lookahead.type !== 14 && lookahead.type !== 17) { + this.next(); + protoStartLoc = this.state.startLoc; + allowStatic = false; + } + } + if (allowStatic && this.isContextual(106)) { + const lookahead = this.lookahead(); + if (lookahead.type !== 14 && lookahead.type !== 17) { + this.next(); + isStatic = true; + } + } + const variance = this.flowParseVariance(); + if (this.eat(0)) { + if (protoStartLoc != null) { + this.unexpected(protoStartLoc); + } + if (this.eat(0)) { + if (variance) { + this.unexpected(variance.loc.start); + } + nodeStart.internalSlots.push(this.flowParseObjectTypeInternalSlot(node, isStatic)); + } else { + nodeStart.indexers.push(this.flowParseObjectTypeIndexer(node, isStatic, variance)); + } + } else if (this.match(10) || this.match(47)) { + if (protoStartLoc != null) { + this.unexpected(protoStartLoc); + } + if (variance) { + this.unexpected(variance.loc.start); + } + nodeStart.callProperties.push(this.flowParseObjectTypeCallProperty(node, isStatic)); + } else { + let kind = "init"; + if (this.isContextual(99) || this.isContextual(104)) { + const lookahead = this.lookahead(); + if (tokenIsLiteralPropertyName(lookahead.type)) { + kind = this.state.value; + this.next(); + } + } + const propOrInexact = this.flowParseObjectTypeProperty(node, isStatic, protoStartLoc, variance, kind, allowSpread, allowInexact != null ? allowInexact : !exact); + if (propOrInexact === null) { + inexact = true; + inexactStartLoc = this.state.lastTokStartLoc; + } else { + nodeStart.properties.push(propOrInexact); + } + } + this.flowObjectTypeSemicolon(); + if (inexactStartLoc && !this.match(8) && !this.match(9)) { + this.raise(FlowErrors.UnexpectedExplicitInexactInObject, inexactStartLoc); + } + } + this.expect(endDelim); + if (allowSpread) { + nodeStart.inexact = inexact; + } + const out = this.finishNode(nodeStart, "ObjectTypeAnnotation"); + this.state.inType = oldInType; + return out; + } + flowParseObjectTypeProperty(node, isStatic, protoStartLoc, variance, kind, allowSpread, allowInexact) { + if (this.eat(21)) { + const isInexactToken = this.match(12) || this.match(13) || this.match(8) || this.match(9); + if (isInexactToken) { + if (!allowSpread) { + this.raise(FlowErrors.InexactInsideNonObject, this.state.lastTokStartLoc); + } else if (!allowInexact) { + this.raise(FlowErrors.InexactInsideExact, this.state.lastTokStartLoc); + } + if (variance) { + this.raise(FlowErrors.InexactVariance, variance); + } + return null; + } + if (!allowSpread) { + this.raise(FlowErrors.UnexpectedSpreadType, this.state.lastTokStartLoc); + } + if (protoStartLoc != null) { + this.unexpected(protoStartLoc); + } + if (variance) { + this.raise(FlowErrors.SpreadVariance, variance); + } + node.argument = this.flowParseType(); + return this.finishNode(node, "ObjectTypeSpreadProperty"); + } else { + node.key = this.flowParseObjectPropertyKey(); + node.static = isStatic; + node.proto = protoStartLoc != null; + node.kind = kind; + let optional = false; + if (this.match(47) || this.match(10)) { + node.method = true; + if (protoStartLoc != null) { + this.unexpected(protoStartLoc); + } + if (variance) { + this.unexpected(variance.loc.start); + } + node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.loc.start)); + if (kind === "get" || kind === "set") { + this.flowCheckGetterSetterParams(node); + } + if (!allowSpread && node.key.name === "constructor" && node.value.this) { + this.raise(FlowErrors.ThisParamBannedInConstructor, node.value.this); + } + } else { + if (kind !== "init") this.unexpected(); + node.method = false; + if (this.eat(17)) { + optional = true; + } + node.value = this.flowParseTypeInitialiser(); + node.variance = variance; + } + node.optional = optional; + return this.finishNode(node, "ObjectTypeProperty"); + } + } + flowCheckGetterSetterParams(property) { + const paramCount = property.kind === "get" ? 0 : 1; + const length = property.value.params.length + (property.value.rest ? 1 : 0); + if (property.value.this) { + this.raise(property.kind === "get" ? FlowErrors.GetterMayNotHaveThisParam : FlowErrors.SetterMayNotHaveThisParam, property.value.this); + } + if (length !== paramCount) { + this.raise(property.kind === "get" ? Errors.BadGetterArity : Errors.BadSetterArity, property); + } + if (property.kind === "set" && property.value.rest) { + this.raise(Errors.BadSetterRestParameter, property); + } + } + flowObjectTypeSemicolon() { + if (!this.eat(13) && !this.eat(12) && !this.match(8) && !this.match(9)) { + this.unexpected(); + } + } + flowParseQualifiedTypeIdentifier(startLoc, id) { + var _startLoc; + (_startLoc = startLoc) != null ? _startLoc : startLoc = this.state.startLoc; + let node = id || this.flowParseRestrictedIdentifier(true); + while (this.eat(16)) { + const node2 = this.startNodeAt(startLoc); + node2.qualification = node; + node2.id = this.flowParseRestrictedIdentifier(true); + node = this.finishNode(node2, "QualifiedTypeIdentifier"); + } + return node; + } + flowParseGenericType(startLoc, id) { + const node = this.startNodeAt(startLoc); + node.typeParameters = null; + node.id = this.flowParseQualifiedTypeIdentifier(startLoc, id); + if (this.match(47)) { + node.typeParameters = this.flowParseTypeParameterInstantiation(); + } + return this.finishNode(node, "GenericTypeAnnotation"); + } + flowParseTypeofType() { + const node = this.startNode(); + this.expect(87); + node.argument = this.flowParsePrimaryType(); + return this.finishNode(node, "TypeofTypeAnnotation"); + } + flowParseTupleType() { + const node = this.startNode(); + node.types = []; + this.expect(0); + while (this.state.pos < this.length && !this.match(3)) { + node.types.push(this.flowParseType()); + if (this.match(3)) break; + this.expect(12); + } + this.expect(3); + return this.finishNode(node, "TupleTypeAnnotation"); + } + flowParseFunctionTypeParam(first) { + let name = null; + let optional = false; + let typeAnnotation = null; + const node = this.startNode(); + const lh = this.lookahead(); + const isThis = this.state.type === 78; + if (lh.type === 14 || lh.type === 17) { + if (isThis && !first) { + this.raise(FlowErrors.ThisParamMustBeFirst, node); + } + name = this.parseIdentifier(isThis); + if (this.eat(17)) { + optional = true; + if (isThis) { + this.raise(FlowErrors.ThisParamMayNotBeOptional, node); + } + } + typeAnnotation = this.flowParseTypeInitialiser(); + } else { + typeAnnotation = this.flowParseType(); + } + node.name = name; + node.optional = optional; + node.typeAnnotation = typeAnnotation; + return this.finishNode(node, "FunctionTypeParam"); + } + reinterpretTypeAsFunctionTypeParam(type) { + const node = this.startNodeAt(type.loc.start); + node.name = null; + node.optional = false; + node.typeAnnotation = type; + return this.finishNode(node, "FunctionTypeParam"); + } + flowParseFunctionTypeParams(params = []) { + let rest = null; + let _this = null; + if (this.match(78)) { + _this = this.flowParseFunctionTypeParam(true); + _this.name = null; + if (!this.match(11)) { + this.expect(12); + } + } + while (!this.match(11) && !this.match(21)) { + params.push(this.flowParseFunctionTypeParam(false)); + if (!this.match(11)) { + this.expect(12); + } + } + if (this.eat(21)) { + rest = this.flowParseFunctionTypeParam(false); + } + return { + params, + rest, + _this + }; + } + flowIdentToTypeAnnotation(startLoc, node, id) { + switch (id.name) { + case "any": + return this.finishNode(node, "AnyTypeAnnotation"); + case "bool": + case "boolean": + return this.finishNode(node, "BooleanTypeAnnotation"); + case "mixed": + return this.finishNode(node, "MixedTypeAnnotation"); + case "empty": + return this.finishNode(node, "EmptyTypeAnnotation"); + case "number": + return this.finishNode(node, "NumberTypeAnnotation"); + case "string": + return this.finishNode(node, "StringTypeAnnotation"); + case "symbol": + return this.finishNode(node, "SymbolTypeAnnotation"); + default: + this.checkNotUnderscore(id.name); + return this.flowParseGenericType(startLoc, id); + } + } + flowParsePrimaryType() { + const startLoc = this.state.startLoc; + const node = this.startNode(); + let tmp; + let type; + let isGroupedType = false; + const oldNoAnonFunctionType = this.state.noAnonFunctionType; + switch (this.state.type) { + case 5: + return this.flowParseObjectType({ + allowStatic: false, + allowExact: false, + allowSpread: true, + allowProto: false, + allowInexact: true + }); + case 6: + return this.flowParseObjectType({ + allowStatic: false, + allowExact: true, + allowSpread: true, + allowProto: false, + allowInexact: false + }); + case 0: + this.state.noAnonFunctionType = false; + type = this.flowParseTupleType(); + this.state.noAnonFunctionType = oldNoAnonFunctionType; + return type; + case 47: + { + const node = this.startNode(); + node.typeParameters = this.flowParseTypeParameterDeclaration(); + this.expect(10); + tmp = this.flowParseFunctionTypeParams(); + node.params = tmp.params; + node.rest = tmp.rest; + node.this = tmp._this; + this.expect(11); + this.expect(19); + node.returnType = this.flowParseType(); + return this.finishNode(node, "FunctionTypeAnnotation"); + } + case 10: + { + const node = this.startNode(); + this.next(); + if (!this.match(11) && !this.match(21)) { + if (tokenIsIdentifier(this.state.type) || this.match(78)) { + const token = this.lookahead().type; + isGroupedType = token !== 17 && token !== 14; + } else { + isGroupedType = true; + } + } + if (isGroupedType) { + this.state.noAnonFunctionType = false; + type = this.flowParseType(); + this.state.noAnonFunctionType = oldNoAnonFunctionType; + if (this.state.noAnonFunctionType || !(this.match(12) || this.match(11) && this.lookahead().type === 19)) { + this.expect(11); + return type; + } else { + this.eat(12); + } + } + if (type) { + tmp = this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(type)]); + } else { + tmp = this.flowParseFunctionTypeParams(); + } + node.params = tmp.params; + node.rest = tmp.rest; + node.this = tmp._this; + this.expect(11); + this.expect(19); + node.returnType = this.flowParseType(); + node.typeParameters = null; + return this.finishNode(node, "FunctionTypeAnnotation"); + } + case 133: + return this.parseLiteral(this.state.value, "StringLiteralTypeAnnotation"); + case 85: + case 86: + node.value = this.match(85); + this.next(); + return this.finishNode(node, "BooleanLiteralTypeAnnotation"); + case 53: + if (this.state.value === "-") { + this.next(); + if (this.match(134)) { + return this.parseLiteralAtNode(-this.state.value, "NumberLiteralTypeAnnotation", node); + } + if (this.match(135)) { + return this.parseLiteralAtNode(-this.state.value, "BigIntLiteralTypeAnnotation", node); + } + throw this.raise(FlowErrors.UnexpectedSubtractionOperand, this.state.startLoc); + } + this.unexpected(); + return; + case 134: + return this.parseLiteral(this.state.value, "NumberLiteralTypeAnnotation"); + case 135: + return this.parseLiteral(this.state.value, "BigIntLiteralTypeAnnotation"); + case 88: + this.next(); + return this.finishNode(node, "VoidTypeAnnotation"); + case 84: + this.next(); + return this.finishNode(node, "NullLiteralTypeAnnotation"); + case 78: + this.next(); + return this.finishNode(node, "ThisTypeAnnotation"); + case 55: + this.next(); + return this.finishNode(node, "ExistsTypeAnnotation"); + case 87: + return this.flowParseTypeofType(); + default: + if (tokenIsKeyword(this.state.type)) { + const label = tokenLabelName(this.state.type); + this.next(); + return super.createIdentifier(node, label); + } else if (tokenIsIdentifier(this.state.type)) { + if (this.isContextual(129)) { + return this.flowParseInterfaceType(); + } + return this.flowIdentToTypeAnnotation(startLoc, node, this.parseIdentifier()); + } + } + this.unexpected(); + } + flowParsePostfixType() { + const startLoc = this.state.startLoc; + let type = this.flowParsePrimaryType(); + let seenOptionalIndexedAccess = false; + while ((this.match(0) || this.match(18)) && !this.canInsertSemicolon()) { + const node = this.startNodeAt(startLoc); + const optional = this.eat(18); + seenOptionalIndexedAccess = seenOptionalIndexedAccess || optional; + this.expect(0); + if (!optional && this.match(3)) { + node.elementType = type; + this.next(); + type = this.finishNode(node, "ArrayTypeAnnotation"); + } else { + node.objectType = type; + node.indexType = this.flowParseType(); + this.expect(3); + if (seenOptionalIndexedAccess) { + node.optional = optional; + type = this.finishNode(node, "OptionalIndexedAccessType"); + } else { + type = this.finishNode(node, "IndexedAccessType"); + } + } + } + return type; + } + flowParsePrefixType() { + const node = this.startNode(); + if (this.eat(17)) { + node.typeAnnotation = this.flowParsePrefixType(); + return this.finishNode(node, "NullableTypeAnnotation"); + } else { + return this.flowParsePostfixType(); + } + } + flowParseAnonFunctionWithoutParens() { + const param = this.flowParsePrefixType(); + if (!this.state.noAnonFunctionType && this.eat(19)) { + const node = this.startNodeAt(param.loc.start); + node.params = [this.reinterpretTypeAsFunctionTypeParam(param)]; + node.rest = null; + node.this = null; + node.returnType = this.flowParseType(); + node.typeParameters = null; + return this.finishNode(node, "FunctionTypeAnnotation"); + } + return param; + } + flowParseIntersectionType() { + const node = this.startNode(); + this.eat(45); + const type = this.flowParseAnonFunctionWithoutParens(); + node.types = [type]; + while (this.eat(45)) { + node.types.push(this.flowParseAnonFunctionWithoutParens()); + } + return node.types.length === 1 ? type : this.finishNode(node, "IntersectionTypeAnnotation"); + } + flowParseUnionType() { + const node = this.startNode(); + this.eat(43); + const type = this.flowParseIntersectionType(); + node.types = [type]; + while (this.eat(43)) { + node.types.push(this.flowParseIntersectionType()); + } + return node.types.length === 1 ? type : this.finishNode(node, "UnionTypeAnnotation"); + } + flowParseType() { + const oldInType = this.state.inType; + this.state.inType = true; + const type = this.flowParseUnionType(); + this.state.inType = oldInType; + return type; + } + flowParseTypeOrImplicitInstantiation() { + if (this.state.type === 132 && this.state.value === "_") { + const startLoc = this.state.startLoc; + const node = this.parseIdentifier(); + return this.flowParseGenericType(startLoc, node); + } else { + return this.flowParseType(); + } + } + flowParseTypeAnnotation() { + const node = this.startNode(); + node.typeAnnotation = this.flowParseTypeInitialiser(); + return this.finishNode(node, "TypeAnnotation"); + } + flowParseTypeAnnotatableIdentifier(allowPrimitiveOverride) { + const ident = allowPrimitiveOverride ? this.parseIdentifier() : this.flowParseRestrictedIdentifier(); + if (this.match(14)) { + ident.typeAnnotation = this.flowParseTypeAnnotation(); + this.resetEndLocation(ident); + } + return ident; + } + typeCastToParameter(node) { + node.expression.typeAnnotation = node.typeAnnotation; + this.resetEndLocation(node.expression, node.typeAnnotation.loc.end); + return node.expression; + } + flowParseVariance() { + let variance = null; + if (this.match(53)) { + variance = this.startNode(); + if (this.state.value === "+") { + variance.kind = "plus"; + } else { + variance.kind = "minus"; + } + this.next(); + return this.finishNode(variance, "Variance"); + } + return variance; + } + parseFunctionBody(node, allowExpressionBody, isMethod = false) { + if (allowExpressionBody) { + this.forwardNoArrowParamsConversionAt(node, () => super.parseFunctionBody(node, true, isMethod)); + return; + } + super.parseFunctionBody(node, false, isMethod); + } + parseFunctionBodyAndFinish(node, type, isMethod = false) { + if (this.match(14)) { + const typeNode = this.startNode(); + [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser(); + node.returnType = typeNode.typeAnnotation ? this.finishNode(typeNode, "TypeAnnotation") : null; + } + return super.parseFunctionBodyAndFinish(node, type, isMethod); + } + parseStatementLike(flags) { + if (this.state.strict && this.isContextual(129)) { + const lookahead = this.lookahead(); + if (tokenIsKeywordOrIdentifier(lookahead.type)) { + const node = this.startNode(); + this.next(); + return this.flowParseInterface(node); + } + } else if (this.shouldParseEnums() && this.isContextual(126)) { + const node = this.startNode(); + this.next(); + return this.flowParseEnumDeclaration(node); + } + const stmt = super.parseStatementLike(flags); + if (this.flowPragma === undefined && !this.isValidDirective(stmt)) { + this.flowPragma = null; + } + return stmt; + } + parseExpressionStatement(node, expr, decorators) { + if (expr.type === "Identifier") { + if (expr.name === "declare") { + if (this.match(80) || tokenIsIdentifier(this.state.type) || this.match(68) || this.match(74) || this.match(82)) { + return this.flowParseDeclare(node); + } + } else if (tokenIsIdentifier(this.state.type)) { + if (expr.name === "interface") { + return this.flowParseInterface(node); + } else if (expr.name === "type") { + return this.flowParseTypeAlias(node); + } else if (expr.name === "opaque") { + return this.flowParseOpaqueType(node, false); + } + } + } + return super.parseExpressionStatement(node, expr, decorators); + } + shouldParseExportDeclaration() { + const { + type + } = this.state; + if (tokenIsFlowInterfaceOrTypeOrOpaque(type) || this.shouldParseEnums() && type === 126) { + return !this.state.containsEsc; + } + return super.shouldParseExportDeclaration(); + } + isExportDefaultSpecifier() { + const { + type + } = this.state; + if (tokenIsFlowInterfaceOrTypeOrOpaque(type) || this.shouldParseEnums() && type === 126) { + return this.state.containsEsc; + } + return super.isExportDefaultSpecifier(); + } + parseExportDefaultExpression() { + if (this.shouldParseEnums() && this.isContextual(126)) { + const node = this.startNode(); + this.next(); + return this.flowParseEnumDeclaration(node); + } + return super.parseExportDefaultExpression(); + } + parseConditional(expr, startLoc, refExpressionErrors) { + if (!this.match(17)) return expr; + if (this.state.maybeInArrowParameters) { + const nextCh = this.lookaheadCharCode(); + if (nextCh === 44 || nextCh === 61 || nextCh === 58 || nextCh === 41) { + this.setOptionalParametersError(refExpressionErrors); + return expr; + } + } + this.expect(17); + const state = this.state.clone(); + const originalNoArrowAt = this.state.noArrowAt; + const node = this.startNodeAt(startLoc); + let { + consequent, + failed + } = this.tryParseConditionalConsequent(); + let [valid, invalid] = this.getArrowLikeExpressions(consequent); + if (failed || invalid.length > 0) { + const noArrowAt = [...originalNoArrowAt]; + if (invalid.length > 0) { + this.state = state; + this.state.noArrowAt = noArrowAt; + for (let i = 0; i < invalid.length; i++) { + noArrowAt.push(invalid[i].start); + } + ({ + consequent, + failed + } = this.tryParseConditionalConsequent()); + [valid, invalid] = this.getArrowLikeExpressions(consequent); + } + if (failed && valid.length > 1) { + this.raise(FlowErrors.AmbiguousConditionalArrow, state.startLoc); + } + if (failed && valid.length === 1) { + this.state = state; + noArrowAt.push(valid[0].start); + this.state.noArrowAt = noArrowAt; + ({ + consequent, + failed + } = this.tryParseConditionalConsequent()); + } + } + this.getArrowLikeExpressions(consequent, true); + this.state.noArrowAt = originalNoArrowAt; + this.expect(14); + node.test = expr; + node.consequent = consequent; + node.alternate = this.forwardNoArrowParamsConversionAt(node, () => this.parseMaybeAssign(undefined, undefined)); + return this.finishNode(node, "ConditionalExpression"); + } + tryParseConditionalConsequent() { + this.state.noArrowParamsConversionAt.push(this.state.start); + const consequent = this.parseMaybeAssignAllowIn(); + const failed = !this.match(14); + this.state.noArrowParamsConversionAt.pop(); + return { + consequent, + failed + }; + } + getArrowLikeExpressions(node, disallowInvalid) { + const stack = [node]; + const arrows = []; + while (stack.length !== 0) { + const node = stack.pop(); + if (node.type === "ArrowFunctionExpression" && node.body.type !== "BlockStatement") { + if (node.typeParameters || !node.returnType) { + this.finishArrowValidation(node); + } else { + arrows.push(node); + } + stack.push(node.body); + } else if (node.type === "ConditionalExpression") { + stack.push(node.consequent); + stack.push(node.alternate); + } + } + if (disallowInvalid) { + arrows.forEach(node => this.finishArrowValidation(node)); + return [arrows, []]; + } + return partition(arrows, node => node.params.every(param => this.isAssignable(param, true))); + } + finishArrowValidation(node) { + var _node$extra; + this.toAssignableList(node.params, (_node$extra = node.extra) == null ? void 0 : _node$extra.trailingCommaLoc, false); + this.scope.enter(2 | 4); + super.checkParams(node, false, true); + this.scope.exit(); + } + forwardNoArrowParamsConversionAt(node, parse) { + let result; + if (this.state.noArrowParamsConversionAt.includes(node.start)) { + this.state.noArrowParamsConversionAt.push(this.state.start); + result = parse(); + this.state.noArrowParamsConversionAt.pop(); + } else { + result = parse(); + } + return result; + } + parseParenItem(node, startLoc) { + const newNode = super.parseParenItem(node, startLoc); + if (this.eat(17)) { + newNode.optional = true; + this.resetEndLocation(node); + } + if (this.match(14)) { + const typeCastNode = this.startNodeAt(startLoc); + typeCastNode.expression = newNode; + typeCastNode.typeAnnotation = this.flowParseTypeAnnotation(); + return this.finishNode(typeCastNode, "TypeCastExpression"); + } + return newNode; + } + assertModuleNodeAllowed(node) { + if (node.type === "ImportDeclaration" && (node.importKind === "type" || node.importKind === "typeof") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "ExportAllDeclaration" && node.exportKind === "type") { + return; + } + super.assertModuleNodeAllowed(node); + } + parseExportDeclaration(node) { + if (this.isContextual(130)) { + node.exportKind = "type"; + const declarationNode = this.startNode(); + this.next(); + if (this.match(5)) { + node.specifiers = this.parseExportSpecifiers(true); + super.parseExportFrom(node); + return null; + } else { + return this.flowParseTypeAlias(declarationNode); + } + } else if (this.isContextual(131)) { + node.exportKind = "type"; + const declarationNode = this.startNode(); + this.next(); + return this.flowParseOpaqueType(declarationNode, false); + } else if (this.isContextual(129)) { + node.exportKind = "type"; + const declarationNode = this.startNode(); + this.next(); + return this.flowParseInterface(declarationNode); + } else if (this.shouldParseEnums() && this.isContextual(126)) { + node.exportKind = "value"; + const declarationNode = this.startNode(); + this.next(); + return this.flowParseEnumDeclaration(declarationNode); + } else { + return super.parseExportDeclaration(node); + } + } + eatExportStar(node) { + if (super.eatExportStar(node)) return true; + if (this.isContextual(130) && this.lookahead().type === 55) { + node.exportKind = "type"; + this.next(); + this.next(); + return true; + } + return false; + } + maybeParseExportNamespaceSpecifier(node) { + const { + startLoc + } = this.state; + const hasNamespace = super.maybeParseExportNamespaceSpecifier(node); + if (hasNamespace && node.exportKind === "type") { + this.unexpected(startLoc); + } + return hasNamespace; + } + parseClassId(node, isStatement, optionalId) { + super.parseClassId(node, isStatement, optionalId); + if (this.match(47)) { + node.typeParameters = this.flowParseTypeParameterDeclaration(); + } + } + parseClassMember(classBody, member, state) { + const { + startLoc + } = this.state; + if (this.isContextual(125)) { + if (super.parseClassMemberFromModifier(classBody, member)) { + return; + } + member.declare = true; + } + super.parseClassMember(classBody, member, state); + if (member.declare) { + if (member.type !== "ClassProperty" && member.type !== "ClassPrivateProperty" && member.type !== "PropertyDefinition") { + this.raise(FlowErrors.DeclareClassElement, startLoc); + } else if (member.value) { + this.raise(FlowErrors.DeclareClassFieldInitializer, member.value); + } + } + } + isIterator(word) { + return word === "iterator" || word === "asyncIterator"; + } + readIterator() { + const word = super.readWord1(); + const fullWord = "@@" + word; + if (!this.isIterator(word) || !this.state.inType) { + this.raise(Errors.InvalidIdentifier, this.state.curPosition(), { + identifierName: fullWord + }); + } + this.finishToken(132, fullWord); + } + getTokenFromCode(code) { + const next = this.input.charCodeAt(this.state.pos + 1); + if (code === 123 && next === 124) { + this.finishOp(6, 2); + } else if (this.state.inType && (code === 62 || code === 60)) { + this.finishOp(code === 62 ? 48 : 47, 1); + } else if (this.state.inType && code === 63) { + if (next === 46) { + this.finishOp(18, 2); + } else { + this.finishOp(17, 1); + } + } else if (isIteratorStart(code, next, this.input.charCodeAt(this.state.pos + 2))) { + this.state.pos += 2; + this.readIterator(); + } else { + super.getTokenFromCode(code); + } + } + isAssignable(node, isBinding) { + if (node.type === "TypeCastExpression") { + return this.isAssignable(node.expression, isBinding); + } else { + return super.isAssignable(node, isBinding); + } + } + toAssignable(node, isLHS = false) { + if (!isLHS && node.type === "AssignmentExpression" && node.left.type === "TypeCastExpression") { + node.left = this.typeCastToParameter(node.left); + } + super.toAssignable(node, isLHS); + } + toAssignableList(exprList, trailingCommaLoc, isLHS) { + for (let i = 0; i < exprList.length; i++) { + const expr = exprList[i]; + if ((expr == null ? void 0 : expr.type) === "TypeCastExpression") { + exprList[i] = this.typeCastToParameter(expr); + } + } + super.toAssignableList(exprList, trailingCommaLoc, isLHS); + } + toReferencedList(exprList, isParenthesizedExpr) { + for (let i = 0; i < exprList.length; i++) { + var _expr$extra; + const expr = exprList[i]; + if (expr && expr.type === "TypeCastExpression" && !((_expr$extra = expr.extra) != null && _expr$extra.parenthesized) && (exprList.length > 1 || !isParenthesizedExpr)) { + this.raise(FlowErrors.TypeCastInPattern, expr.typeAnnotation); + } + } + return exprList; + } + parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) { + const node = super.parseArrayLike(close, canBePattern, isTuple, refExpressionErrors); + if (canBePattern && !this.state.maybeInArrowParameters) { + this.toReferencedList(node.elements); + } + return node; + } + isValidLVal(type, isParenthesized, binding) { + return type === "TypeCastExpression" || super.isValidLVal(type, isParenthesized, binding); + } + parseClassProperty(node) { + if (this.match(14)) { + node.typeAnnotation = this.flowParseTypeAnnotation(); + } + return super.parseClassProperty(node); + } + parseClassPrivateProperty(node) { + if (this.match(14)) { + node.typeAnnotation = this.flowParseTypeAnnotation(); + } + return super.parseClassPrivateProperty(node); + } + isClassMethod() { + return this.match(47) || super.isClassMethod(); + } + isClassProperty() { + return this.match(14) || super.isClassProperty(); + } + isNonstaticConstructor(method) { + return !this.match(14) && super.isNonstaticConstructor(method); + } + pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) { + if (method.variance) { + this.unexpected(method.variance.loc.start); + } + delete method.variance; + if (this.match(47)) { + method.typeParameters = this.flowParseTypeParameterDeclaration(); + } + super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper); + if (method.params && isConstructor) { + const params = method.params; + if (params.length > 0 && this.isThisParam(params[0])) { + this.raise(FlowErrors.ThisParamBannedInConstructor, method); + } + } else if (method.type === "MethodDefinition" && isConstructor && method.value.params) { + const params = method.value.params; + if (params.length > 0 && this.isThisParam(params[0])) { + this.raise(FlowErrors.ThisParamBannedInConstructor, method); + } + } + } + pushClassPrivateMethod(classBody, method, isGenerator, isAsync) { + if (method.variance) { + this.unexpected(method.variance.loc.start); + } + delete method.variance; + if (this.match(47)) { + method.typeParameters = this.flowParseTypeParameterDeclaration(); + } + super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync); + } + parseClassSuper(node) { + super.parseClassSuper(node); + if (node.superClass && this.match(47)) { + node.superTypeParameters = this.flowParseTypeParameterInstantiation(); + } + if (this.isContextual(113)) { + this.next(); + const implemented = node.implements = []; + do { + const node = this.startNode(); + node.id = this.flowParseRestrictedIdentifier(true); + if (this.match(47)) { + node.typeParameters = this.flowParseTypeParameterInstantiation(); + } else { + node.typeParameters = null; + } + implemented.push(this.finishNode(node, "ClassImplements")); + } while (this.eat(12)); + } + } + checkGetterSetterParams(method) { + super.checkGetterSetterParams(method); + const params = this.getObjectOrClassMethodParams(method); + if (params.length > 0) { + const param = params[0]; + if (this.isThisParam(param) && method.kind === "get") { + this.raise(FlowErrors.GetterMayNotHaveThisParam, param); + } else if (this.isThisParam(param)) { + this.raise(FlowErrors.SetterMayNotHaveThisParam, param); + } + } + } + parsePropertyNamePrefixOperator(node) { + node.variance = this.flowParseVariance(); + } + parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) { + if (prop.variance) { + this.unexpected(prop.variance.loc.start); + } + delete prop.variance; + let typeParameters; + if (this.match(47) && !isAccessor) { + typeParameters = this.flowParseTypeParameterDeclaration(); + if (!this.match(10)) this.unexpected(); + } + const result = super.parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors); + if (typeParameters) { + (result.value || result).typeParameters = typeParameters; + } + return result; + } + parseAssignableListItemTypes(param) { + if (this.eat(17)) { + if (param.type !== "Identifier") { + this.raise(FlowErrors.PatternIsOptional, param); + } + if (this.isThisParam(param)) { + this.raise(FlowErrors.ThisParamMayNotBeOptional, param); + } + param.optional = true; + } + if (this.match(14)) { + param.typeAnnotation = this.flowParseTypeAnnotation(); + } else if (this.isThisParam(param)) { + this.raise(FlowErrors.ThisParamAnnotationRequired, param); + } + if (this.match(29) && this.isThisParam(param)) { + this.raise(FlowErrors.ThisParamNoDefault, param); + } + this.resetEndLocation(param); + return param; + } + parseMaybeDefault(startLoc, left) { + const node = super.parseMaybeDefault(startLoc, left); + if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) { + this.raise(FlowErrors.TypeBeforeInitializer, node.typeAnnotation); + } + return node; + } + checkImportReflection(node) { + super.checkImportReflection(node); + if (node.module && node.importKind !== "value") { + this.raise(FlowErrors.ImportReflectionHasImportType, node.specifiers[0].loc.start); + } + } + parseImportSpecifierLocal(node, specifier, type) { + specifier.local = hasTypeImportKind(node) ? this.flowParseRestrictedIdentifier(true, true) : this.parseIdentifier(); + node.specifiers.push(this.finishImportSpecifier(specifier, type)); + } + isPotentialImportPhase(isExport) { + if (super.isPotentialImportPhase(isExport)) return true; + if (this.isContextual(130)) { + if (!isExport) return true; + const ch = this.lookaheadCharCode(); + return ch === 123 || ch === 42; + } + return !isExport && this.isContextual(87); + } + applyImportPhase(node, isExport, phase, loc) { + super.applyImportPhase(node, isExport, phase, loc); + if (isExport) { + if (!phase && this.match(65)) { + return; + } + node.exportKind = phase === "type" ? phase : "value"; + } else { + if (phase === "type" && this.match(55)) this.unexpected(); + node.importKind = phase === "type" || phase === "typeof" ? phase : "value"; + } + } + parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, bindingType) { + const firstIdent = specifier.imported; + let specifierTypeKind = null; + if (firstIdent.type === "Identifier") { + if (firstIdent.name === "type") { + specifierTypeKind = "type"; + } else if (firstIdent.name === "typeof") { + specifierTypeKind = "typeof"; + } + } + let isBinding = false; + if (this.isContextual(93) && !this.isLookaheadContextual("as")) { + const as_ident = this.parseIdentifier(true); + if (specifierTypeKind !== null && !tokenIsKeywordOrIdentifier(this.state.type)) { + specifier.imported = as_ident; + specifier.importKind = specifierTypeKind; + specifier.local = cloneIdentifier(as_ident); + } else { + specifier.imported = firstIdent; + specifier.importKind = null; + specifier.local = this.parseIdentifier(); + } + } else { + if (specifierTypeKind !== null && tokenIsKeywordOrIdentifier(this.state.type)) { + specifier.imported = this.parseIdentifier(true); + specifier.importKind = specifierTypeKind; + } else { + if (importedIsString) { + throw this.raise(Errors.ImportBindingIsString, specifier, { + importName: firstIdent.value + }); + } + specifier.imported = firstIdent; + specifier.importKind = null; + } + if (this.eatContextual(93)) { + specifier.local = this.parseIdentifier(); + } else { + isBinding = true; + specifier.local = cloneIdentifier(specifier.imported); + } + } + const specifierIsTypeImport = hasTypeImportKind(specifier); + if (isInTypeOnlyImport && specifierIsTypeImport) { + this.raise(FlowErrors.ImportTypeShorthandOnlyInPureImport, specifier); + } + if (isInTypeOnlyImport || specifierIsTypeImport) { + this.checkReservedType(specifier.local.name, specifier.local.loc.start, true); + } + if (isBinding && !isInTypeOnlyImport && !specifierIsTypeImport) { + this.checkReservedWord(specifier.local.name, specifier.loc.start, true, true); + } + return this.finishImportSpecifier(specifier, "ImportSpecifier"); + } + parseBindingAtom() { + switch (this.state.type) { + case 78: + return this.parseIdentifier(true); + default: + return super.parseBindingAtom(); + } + } + parseFunctionParams(node, isConstructor) { + const kind = node.kind; + if (kind !== "get" && kind !== "set" && this.match(47)) { + node.typeParameters = this.flowParseTypeParameterDeclaration(); + } + super.parseFunctionParams(node, isConstructor); + } + parseVarId(decl, kind) { + super.parseVarId(decl, kind); + if (this.match(14)) { + decl.id.typeAnnotation = this.flowParseTypeAnnotation(); + this.resetEndLocation(decl.id); + } + } + parseAsyncArrowFromCallExpression(node, call) { + if (this.match(14)) { + const oldNoAnonFunctionType = this.state.noAnonFunctionType; + this.state.noAnonFunctionType = true; + node.returnType = this.flowParseTypeAnnotation(); + this.state.noAnonFunctionType = oldNoAnonFunctionType; + } + return super.parseAsyncArrowFromCallExpression(node, call); + } + shouldParseAsyncArrow() { + return this.match(14) || super.shouldParseAsyncArrow(); + } + parseMaybeAssign(refExpressionErrors, afterLeftParse) { + var _jsx; + let state = null; + let jsx; + if (this.hasPlugin("jsx") && (this.match(142) || this.match(47))) { + state = this.state.clone(); + jsx = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state); + if (!jsx.error) return jsx.node; + const { + context + } = this.state; + const currentContext = context[context.length - 1]; + if (currentContext === types.j_oTag || currentContext === types.j_expr) { + context.pop(); + } + } + if ((_jsx = jsx) != null && _jsx.error || this.match(47)) { + var _jsx2, _jsx3; + state = state || this.state.clone(); + let typeParameters; + const arrow = this.tryParse(abort => { + var _arrowExpression$extr; + typeParameters = this.flowParseTypeParameterDeclaration(); + const arrowExpression = this.forwardNoArrowParamsConversionAt(typeParameters, () => { + const result = super.parseMaybeAssign(refExpressionErrors, afterLeftParse); + this.resetStartLocationFromNode(result, typeParameters); + return result; + }); + if ((_arrowExpression$extr = arrowExpression.extra) != null && _arrowExpression$extr.parenthesized) abort(); + const expr = this.maybeUnwrapTypeCastExpression(arrowExpression); + if (expr.type !== "ArrowFunctionExpression") abort(); + expr.typeParameters = typeParameters; + this.resetStartLocationFromNode(expr, typeParameters); + return arrowExpression; + }, state); + let arrowExpression = null; + if (arrow.node && this.maybeUnwrapTypeCastExpression(arrow.node).type === "ArrowFunctionExpression") { + if (!arrow.error && !arrow.aborted) { + if (arrow.node.async) { + this.raise(FlowErrors.UnexpectedTypeParameterBeforeAsyncArrowFunction, typeParameters); + } + return arrow.node; + } + arrowExpression = arrow.node; + } + if ((_jsx2 = jsx) != null && _jsx2.node) { + this.state = jsx.failState; + return jsx.node; + } + if (arrowExpression) { + this.state = arrow.failState; + return arrowExpression; + } + if ((_jsx3 = jsx) != null && _jsx3.thrown) throw jsx.error; + if (arrow.thrown) throw arrow.error; + throw this.raise(FlowErrors.UnexpectedTokenAfterTypeParameter, typeParameters); + } + return super.parseMaybeAssign(refExpressionErrors, afterLeftParse); + } + parseArrow(node) { + if (this.match(14)) { + const result = this.tryParse(() => { + const oldNoAnonFunctionType = this.state.noAnonFunctionType; + this.state.noAnonFunctionType = true; + const typeNode = this.startNode(); + [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser(); + this.state.noAnonFunctionType = oldNoAnonFunctionType; + if (this.canInsertSemicolon()) this.unexpected(); + if (!this.match(19)) this.unexpected(); + return typeNode; + }); + if (result.thrown) return null; + if (result.error) this.state = result.failState; + node.returnType = result.node.typeAnnotation ? this.finishNode(result.node, "TypeAnnotation") : null; + } + return super.parseArrow(node); + } + shouldParseArrow(params) { + return this.match(14) || super.shouldParseArrow(params); + } + setArrowFunctionParameters(node, params) { + if (this.state.noArrowParamsConversionAt.includes(node.start)) { + node.params = params; + } else { + super.setArrowFunctionParameters(node, params); + } + } + checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged = true) { + if (isArrowFunction && this.state.noArrowParamsConversionAt.includes(node.start)) { + return; + } + for (let i = 0; i < node.params.length; i++) { + if (this.isThisParam(node.params[i]) && i > 0) { + this.raise(FlowErrors.ThisParamMustBeFirst, node.params[i]); + } + } + super.checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged); + } + parseParenAndDistinguishExpression(canBeArrow) { + return super.parseParenAndDistinguishExpression(canBeArrow && !this.state.noArrowAt.includes(this.state.start)); + } + parseSubscripts(base, startLoc, noCalls) { + if (base.type === "Identifier" && base.name === "async" && this.state.noArrowAt.includes(startLoc.index)) { + this.next(); + const node = this.startNodeAt(startLoc); + node.callee = base; + node.arguments = super.parseCallExpressionArguments(11, false); + base = this.finishNode(node, "CallExpression"); + } else if (base.type === "Identifier" && base.name === "async" && this.match(47)) { + const state = this.state.clone(); + const arrow = this.tryParse(abort => this.parseAsyncArrowWithTypeParameters(startLoc) || abort(), state); + if (!arrow.error && !arrow.aborted) return arrow.node; + const result = this.tryParse(() => super.parseSubscripts(base, startLoc, noCalls), state); + if (result.node && !result.error) return result.node; + if (arrow.node) { + this.state = arrow.failState; + return arrow.node; + } + if (result.node) { + this.state = result.failState; + return result.node; + } + throw arrow.error || result.error; + } + return super.parseSubscripts(base, startLoc, noCalls); + } + parseSubscript(base, startLoc, noCalls, subscriptState) { + if (this.match(18) && this.isLookaheadToken_lt()) { + subscriptState.optionalChainMember = true; + if (noCalls) { + subscriptState.stop = true; + return base; + } + this.next(); + const node = this.startNodeAt(startLoc); + node.callee = base; + node.typeArguments = this.flowParseTypeParameterInstantiation(); + this.expect(10); + node.arguments = this.parseCallExpressionArguments(11, false); + node.optional = true; + return this.finishCallExpression(node, true); + } else if (!noCalls && this.shouldParseTypes() && this.match(47)) { + const node = this.startNodeAt(startLoc); + node.callee = base; + const result = this.tryParse(() => { + node.typeArguments = this.flowParseTypeParameterInstantiationCallOrNew(); + this.expect(10); + node.arguments = super.parseCallExpressionArguments(11, false); + if (subscriptState.optionalChainMember) { + node.optional = false; + } + return this.finishCallExpression(node, subscriptState.optionalChainMember); + }); + if (result.node) { + if (result.error) this.state = result.failState; + return result.node; + } + } + return super.parseSubscript(base, startLoc, noCalls, subscriptState); + } + parseNewCallee(node) { + super.parseNewCallee(node); + let targs = null; + if (this.shouldParseTypes() && this.match(47)) { + targs = this.tryParse(() => this.flowParseTypeParameterInstantiationCallOrNew()).node; + } + node.typeArguments = targs; + } + parseAsyncArrowWithTypeParameters(startLoc) { + const node = this.startNodeAt(startLoc); + this.parseFunctionParams(node, false); + if (!this.parseArrow(node)) return; + return super.parseArrowExpression(node, undefined, true); + } + readToken_mult_modulo(code) { + const next = this.input.charCodeAt(this.state.pos + 1); + if (code === 42 && next === 47 && this.state.hasFlowComment) { + this.state.hasFlowComment = false; + this.state.pos += 2; + this.nextToken(); + return; + } + super.readToken_mult_modulo(code); + } + readToken_pipe_amp(code) { + const next = this.input.charCodeAt(this.state.pos + 1); + if (code === 124 && next === 125) { + this.finishOp(9, 2); + return; + } + super.readToken_pipe_amp(code); + } + parseTopLevel(file, program) { + const fileNode = super.parseTopLevel(file, program); + if (this.state.hasFlowComment) { + this.raise(FlowErrors.UnterminatedFlowComment, this.state.curPosition()); + } + return fileNode; + } + skipBlockComment() { + if (this.hasPlugin("flowComments") && this.skipFlowComment()) { + if (this.state.hasFlowComment) { + throw this.raise(FlowErrors.NestedFlowComment, this.state.startLoc); + } + this.hasFlowCommentCompletion(); + const commentSkip = this.skipFlowComment(); + if (commentSkip) { + this.state.pos += commentSkip; + this.state.hasFlowComment = true; + } + return; + } + return super.skipBlockComment(this.state.hasFlowComment ? "*-/" : "*/"); + } + skipFlowComment() { + const { + pos + } = this.state; + let shiftToFirstNonWhiteSpace = 2; + while ([32, 9].includes(this.input.charCodeAt(pos + shiftToFirstNonWhiteSpace))) { + shiftToFirstNonWhiteSpace++; + } + const ch2 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos); + const ch3 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos + 1); + if (ch2 === 58 && ch3 === 58) { + return shiftToFirstNonWhiteSpace + 2; + } + if (this.input.slice(shiftToFirstNonWhiteSpace + pos, shiftToFirstNonWhiteSpace + pos + 12) === "flow-include") { + return shiftToFirstNonWhiteSpace + 12; + } + if (ch2 === 58 && ch3 !== 58) { + return shiftToFirstNonWhiteSpace; + } + return false; + } + hasFlowCommentCompletion() { + const end = this.input.indexOf("*/", this.state.pos); + if (end === -1) { + throw this.raise(Errors.UnterminatedComment, this.state.curPosition()); + } + } + flowEnumErrorBooleanMemberNotInitialized(loc, { + enumName, + memberName + }) { + this.raise(FlowErrors.EnumBooleanMemberNotInitialized, loc, { + memberName, + enumName + }); + } + flowEnumErrorInvalidMemberInitializer(loc, enumContext) { + return this.raise(!enumContext.explicitType ? FlowErrors.EnumInvalidMemberInitializerUnknownType : enumContext.explicitType === "symbol" ? FlowErrors.EnumInvalidMemberInitializerSymbolType : FlowErrors.EnumInvalidMemberInitializerPrimaryType, loc, enumContext); + } + flowEnumErrorNumberMemberNotInitialized(loc, details) { + this.raise(FlowErrors.EnumNumberMemberNotInitialized, loc, details); + } + flowEnumErrorStringMemberInconsistentlyInitialized(node, details) { + this.raise(FlowErrors.EnumStringMemberInconsistentlyInitialized, node, details); + } + flowEnumMemberInit() { + const startLoc = this.state.startLoc; + const endOfInit = () => this.match(12) || this.match(8); + switch (this.state.type) { + case 134: + { + const literal = this.parseNumericLiteral(this.state.value); + if (endOfInit()) { + return { + type: "number", + loc: literal.loc.start, + value: literal + }; + } + return { + type: "invalid", + loc: startLoc + }; + } + case 133: + { + const literal = this.parseStringLiteral(this.state.value); + if (endOfInit()) { + return { + type: "string", + loc: literal.loc.start, + value: literal + }; + } + return { + type: "invalid", + loc: startLoc + }; + } + case 85: + case 86: + { + const literal = this.parseBooleanLiteral(this.match(85)); + if (endOfInit()) { + return { + type: "boolean", + loc: literal.loc.start, + value: literal + }; + } + return { + type: "invalid", + loc: startLoc + }; + } + default: + return { + type: "invalid", + loc: startLoc + }; + } + } + flowEnumMemberRaw() { + const loc = this.state.startLoc; + const id = this.parseIdentifier(true); + const init = this.eat(29) ? this.flowEnumMemberInit() : { + type: "none", + loc + }; + return { + id, + init + }; + } + flowEnumCheckExplicitTypeMismatch(loc, context, expectedType) { + const { + explicitType + } = context; + if (explicitType === null) { + return; + } + if (explicitType !== expectedType) { + this.flowEnumErrorInvalidMemberInitializer(loc, context); + } + } + flowEnumMembers({ + enumName, + explicitType + }) { + const seenNames = new Set(); + const members = { + booleanMembers: [], + numberMembers: [], + stringMembers: [], + defaultedMembers: [] + }; + let hasUnknownMembers = false; + while (!this.match(8)) { + if (this.eat(21)) { + hasUnknownMembers = true; + break; + } + const memberNode = this.startNode(); + const { + id, + init + } = this.flowEnumMemberRaw(); + const memberName = id.name; + if (memberName === "") { + continue; + } + if (/^[a-z]/.test(memberName)) { + this.raise(FlowErrors.EnumInvalidMemberName, id, { + memberName, + suggestion: memberName[0].toUpperCase() + memberName.slice(1), + enumName + }); + } + if (seenNames.has(memberName)) { + this.raise(FlowErrors.EnumDuplicateMemberName, id, { + memberName, + enumName + }); + } + seenNames.add(memberName); + const context = { + enumName, + explicitType, + memberName + }; + memberNode.id = id; + switch (init.type) { + case "boolean": + { + this.flowEnumCheckExplicitTypeMismatch(init.loc, context, "boolean"); + memberNode.init = init.value; + members.booleanMembers.push(this.finishNode(memberNode, "EnumBooleanMember")); + break; + } + case "number": + { + this.flowEnumCheckExplicitTypeMismatch(init.loc, context, "number"); + memberNode.init = init.value; + members.numberMembers.push(this.finishNode(memberNode, "EnumNumberMember")); + break; + } + case "string": + { + this.flowEnumCheckExplicitTypeMismatch(init.loc, context, "string"); + memberNode.init = init.value; + members.stringMembers.push(this.finishNode(memberNode, "EnumStringMember")); + break; + } + case "invalid": + { + throw this.flowEnumErrorInvalidMemberInitializer(init.loc, context); + } + case "none": + { + switch (explicitType) { + case "boolean": + this.flowEnumErrorBooleanMemberNotInitialized(init.loc, context); + break; + case "number": + this.flowEnumErrorNumberMemberNotInitialized(init.loc, context); + break; + default: + members.defaultedMembers.push(this.finishNode(memberNode, "EnumDefaultedMember")); + } + } + } + if (!this.match(8)) { + this.expect(12); + } + } + return { + members, + hasUnknownMembers + }; + } + flowEnumStringMembers(initializedMembers, defaultedMembers, { + enumName + }) { + if (initializedMembers.length === 0) { + return defaultedMembers; + } else if (defaultedMembers.length === 0) { + return initializedMembers; + } else if (defaultedMembers.length > initializedMembers.length) { + for (const member of initializedMembers) { + this.flowEnumErrorStringMemberInconsistentlyInitialized(member, { + enumName + }); + } + return defaultedMembers; + } else { + for (const member of defaultedMembers) { + this.flowEnumErrorStringMemberInconsistentlyInitialized(member, { + enumName + }); + } + return initializedMembers; + } + } + flowEnumParseExplicitType({ + enumName + }) { + if (!this.eatContextual(102)) return null; + if (!tokenIsIdentifier(this.state.type)) { + throw this.raise(FlowErrors.EnumInvalidExplicitTypeUnknownSupplied, this.state.startLoc, { + enumName + }); + } + const { + value + } = this.state; + this.next(); + if (value !== "boolean" && value !== "number" && value !== "string" && value !== "symbol") { + this.raise(FlowErrors.EnumInvalidExplicitType, this.state.startLoc, { + enumName, + invalidEnumType: value + }); + } + return value; + } + flowEnumBody(node, id) { + const enumName = id.name; + const nameLoc = id.loc.start; + const explicitType = this.flowEnumParseExplicitType({ + enumName + }); + this.expect(5); + const { + members, + hasUnknownMembers + } = this.flowEnumMembers({ + enumName, + explicitType + }); + node.hasUnknownMembers = hasUnknownMembers; + switch (explicitType) { + case "boolean": + node.explicitType = true; + node.members = members.booleanMembers; + this.expect(8); + return this.finishNode(node, "EnumBooleanBody"); + case "number": + node.explicitType = true; + node.members = members.numberMembers; + this.expect(8); + return this.finishNode(node, "EnumNumberBody"); + case "string": + node.explicitType = true; + node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, { + enumName + }); + this.expect(8); + return this.finishNode(node, "EnumStringBody"); + case "symbol": + node.members = members.defaultedMembers; + this.expect(8); + return this.finishNode(node, "EnumSymbolBody"); + default: + { + const empty = () => { + node.members = []; + this.expect(8); + return this.finishNode(node, "EnumStringBody"); + }; + node.explicitType = false; + const boolsLen = members.booleanMembers.length; + const numsLen = members.numberMembers.length; + const strsLen = members.stringMembers.length; + const defaultedLen = members.defaultedMembers.length; + if (!boolsLen && !numsLen && !strsLen && !defaultedLen) { + return empty(); + } else if (!boolsLen && !numsLen) { + node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, { + enumName + }); + this.expect(8); + return this.finishNode(node, "EnumStringBody"); + } else if (!numsLen && !strsLen && boolsLen >= defaultedLen) { + for (const member of members.defaultedMembers) { + this.flowEnumErrorBooleanMemberNotInitialized(member.loc.start, { + enumName, + memberName: member.id.name + }); + } + node.members = members.booleanMembers; + this.expect(8); + return this.finishNode(node, "EnumBooleanBody"); + } else if (!boolsLen && !strsLen && numsLen >= defaultedLen) { + for (const member of members.defaultedMembers) { + this.flowEnumErrorNumberMemberNotInitialized(member.loc.start, { + enumName, + memberName: member.id.name + }); + } + node.members = members.numberMembers; + this.expect(8); + return this.finishNode(node, "EnumNumberBody"); + } else { + this.raise(FlowErrors.EnumInconsistentMemberValues, nameLoc, { + enumName + }); + return empty(); + } + } + } + } + flowParseEnumDeclaration(node) { + const id = this.parseIdentifier(); + node.id = id; + node.body = this.flowEnumBody(this.startNode(), id); + return this.finishNode(node, "EnumDeclaration"); + } + isLookaheadToken_lt() { + const next = this.nextTokenStart(); + if (this.input.charCodeAt(next) === 60) { + const afterNext = this.input.charCodeAt(next + 1); + return afterNext !== 60 && afterNext !== 61; + } + return false; + } + maybeUnwrapTypeCastExpression(node) { + return node.type === "TypeCastExpression" ? node.expression : node; + } +}; +const entities = { + __proto__: null, + quot: "\u0022", + amp: "&", + apos: "\u0027", + lt: "<", + gt: ">", + nbsp: "\u00A0", + iexcl: "\u00A1", + cent: "\u00A2", + pound: "\u00A3", + curren: "\u00A4", + yen: "\u00A5", + brvbar: "\u00A6", + sect: "\u00A7", + uml: "\u00A8", + copy: "\u00A9", + ordf: "\u00AA", + laquo: "\u00AB", + not: "\u00AC", + shy: "\u00AD", + reg: "\u00AE", + macr: "\u00AF", + deg: "\u00B0", + plusmn: "\u00B1", + sup2: "\u00B2", + sup3: "\u00B3", + acute: "\u00B4", + micro: "\u00B5", + para: "\u00B6", + middot: "\u00B7", + cedil: "\u00B8", + sup1: "\u00B9", + ordm: "\u00BA", + raquo: "\u00BB", + frac14: "\u00BC", + frac12: "\u00BD", + frac34: "\u00BE", + iquest: "\u00BF", + Agrave: "\u00C0", + Aacute: "\u00C1", + Acirc: "\u00C2", + Atilde: "\u00C3", + Auml: "\u00C4", + Aring: "\u00C5", + AElig: "\u00C6", + Ccedil: "\u00C7", + Egrave: "\u00C8", + Eacute: "\u00C9", + Ecirc: "\u00CA", + Euml: "\u00CB", + Igrave: "\u00CC", + Iacute: "\u00CD", + Icirc: "\u00CE", + Iuml: "\u00CF", + ETH: "\u00D0", + Ntilde: "\u00D1", + Ograve: "\u00D2", + Oacute: "\u00D3", + Ocirc: "\u00D4", + Otilde: "\u00D5", + Ouml: "\u00D6", + times: "\u00D7", + Oslash: "\u00D8", + Ugrave: "\u00D9", + Uacute: "\u00DA", + Ucirc: "\u00DB", + Uuml: "\u00DC", + Yacute: "\u00DD", + THORN: "\u00DE", + szlig: "\u00DF", + agrave: "\u00E0", + aacute: "\u00E1", + acirc: "\u00E2", + atilde: "\u00E3", + auml: "\u00E4", + aring: "\u00E5", + aelig: "\u00E6", + ccedil: "\u00E7", + egrave: "\u00E8", + eacute: "\u00E9", + ecirc: "\u00EA", + euml: "\u00EB", + igrave: "\u00EC", + iacute: "\u00ED", + icirc: "\u00EE", + iuml: "\u00EF", + eth: "\u00F0", + ntilde: "\u00F1", + ograve: "\u00F2", + oacute: "\u00F3", + ocirc: "\u00F4", + otilde: "\u00F5", + ouml: "\u00F6", + divide: "\u00F7", + oslash: "\u00F8", + ugrave: "\u00F9", + uacute: "\u00FA", + ucirc: "\u00FB", + uuml: "\u00FC", + yacute: "\u00FD", + thorn: "\u00FE", + yuml: "\u00FF", + OElig: "\u0152", + oelig: "\u0153", + Scaron: "\u0160", + scaron: "\u0161", + Yuml: "\u0178", + fnof: "\u0192", + circ: "\u02C6", + tilde: "\u02DC", + Alpha: "\u0391", + Beta: "\u0392", + Gamma: "\u0393", + Delta: "\u0394", + Epsilon: "\u0395", + Zeta: "\u0396", + Eta: "\u0397", + Theta: "\u0398", + Iota: "\u0399", + Kappa: "\u039A", + Lambda: "\u039B", + Mu: "\u039C", + Nu: "\u039D", + Xi: "\u039E", + Omicron: "\u039F", + Pi: "\u03A0", + Rho: "\u03A1", + Sigma: "\u03A3", + Tau: "\u03A4", + Upsilon: "\u03A5", + Phi: "\u03A6", + Chi: "\u03A7", + Psi: "\u03A8", + Omega: "\u03A9", + alpha: "\u03B1", + beta: "\u03B2", + gamma: "\u03B3", + delta: "\u03B4", + epsilon: "\u03B5", + zeta: "\u03B6", + eta: "\u03B7", + theta: "\u03B8", + iota: "\u03B9", + kappa: "\u03BA", + lambda: "\u03BB", + mu: "\u03BC", + nu: "\u03BD", + xi: "\u03BE", + omicron: "\u03BF", + pi: "\u03C0", + rho: "\u03C1", + sigmaf: "\u03C2", + sigma: "\u03C3", + tau: "\u03C4", + upsilon: "\u03C5", + phi: "\u03C6", + chi: "\u03C7", + psi: "\u03C8", + omega: "\u03C9", + thetasym: "\u03D1", + upsih: "\u03D2", + piv: "\u03D6", + ensp: "\u2002", + emsp: "\u2003", + thinsp: "\u2009", + zwnj: "\u200C", + zwj: "\u200D", + lrm: "\u200E", + rlm: "\u200F", + ndash: "\u2013", + mdash: "\u2014", + lsquo: "\u2018", + rsquo: "\u2019", + sbquo: "\u201A", + ldquo: "\u201C", + rdquo: "\u201D", + bdquo: "\u201E", + dagger: "\u2020", + Dagger: "\u2021", + bull: "\u2022", + hellip: "\u2026", + permil: "\u2030", + prime: "\u2032", + Prime: "\u2033", + lsaquo: "\u2039", + rsaquo: "\u203A", + oline: "\u203E", + frasl: "\u2044", + euro: "\u20AC", + image: "\u2111", + weierp: "\u2118", + real: "\u211C", + trade: "\u2122", + alefsym: "\u2135", + larr: "\u2190", + uarr: "\u2191", + rarr: "\u2192", + darr: "\u2193", + harr: "\u2194", + crarr: "\u21B5", + lArr: "\u21D0", + uArr: "\u21D1", + rArr: "\u21D2", + dArr: "\u21D3", + hArr: "\u21D4", + forall: "\u2200", + part: "\u2202", + exist: "\u2203", + empty: "\u2205", + nabla: "\u2207", + isin: "\u2208", + notin: "\u2209", + ni: "\u220B", + prod: "\u220F", + sum: "\u2211", + minus: "\u2212", + lowast: "\u2217", + radic: "\u221A", + prop: "\u221D", + infin: "\u221E", + ang: "\u2220", + and: "\u2227", + or: "\u2228", + cap: "\u2229", + cup: "\u222A", + int: "\u222B", + there4: "\u2234", + sim: "\u223C", + cong: "\u2245", + asymp: "\u2248", + ne: "\u2260", + equiv: "\u2261", + le: "\u2264", + ge: "\u2265", + sub: "\u2282", + sup: "\u2283", + nsub: "\u2284", + sube: "\u2286", + supe: "\u2287", + oplus: "\u2295", + otimes: "\u2297", + perp: "\u22A5", + sdot: "\u22C5", + lceil: "\u2308", + rceil: "\u2309", + lfloor: "\u230A", + rfloor: "\u230B", + lang: "\u2329", + rang: "\u232A", + loz: "\u25CA", + spades: "\u2660", + clubs: "\u2663", + hearts: "\u2665", + diams: "\u2666" +}; +const JsxErrors = ParseErrorEnum`jsx`({ + AttributeIsEmpty: "JSX attributes must only be assigned a non-empty expression.", + MissingClosingTagElement: ({ + openingTagName + }) => `Expected corresponding JSX closing tag for <${openingTagName}>.`, + MissingClosingTagFragment: "Expected corresponding JSX closing tag for <>.", + UnexpectedSequenceExpression: "Sequence expressions cannot be directly nested inside JSX. Did you mean to wrap it in parentheses (...)?", + UnexpectedToken: ({ + unexpected, + HTMLEntity + }) => `Unexpected token \`${unexpected}\`. Did you mean \`${HTMLEntity}\` or \`{'${unexpected}'}\`?`, + UnsupportedJsxValue: "JSX value should be either an expression or a quoted JSX text.", + UnterminatedJsxContent: "Unterminated JSX contents.", + UnwrappedAdjacentJSXElements: "Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...?" +}); +function isFragment(object) { + return object ? object.type === "JSXOpeningFragment" || object.type === "JSXClosingFragment" : false; +} +function getQualifiedJSXName(object) { + if (object.type === "JSXIdentifier") { + return object.name; + } + if (object.type === "JSXNamespacedName") { + return object.namespace.name + ":" + object.name.name; + } + if (object.type === "JSXMemberExpression") { + return getQualifiedJSXName(object.object) + "." + getQualifiedJSXName(object.property); + } + throw new Error("Node had unexpected type: " + object.type); +} +var jsx = superClass => class JSXParserMixin extends superClass { + jsxReadToken() { + let out = ""; + let chunkStart = this.state.pos; + for (;;) { + if (this.state.pos >= this.length) { + throw this.raise(JsxErrors.UnterminatedJsxContent, this.state.startLoc); + } + const ch = this.input.charCodeAt(this.state.pos); + switch (ch) { + case 60: + case 123: + if (this.state.pos === this.state.start) { + if (ch === 60 && this.state.canStartJSXElement) { + ++this.state.pos; + this.finishToken(142); + } else { + super.getTokenFromCode(ch); + } + return; + } + out += this.input.slice(chunkStart, this.state.pos); + this.finishToken(141, out); + return; + case 38: + out += this.input.slice(chunkStart, this.state.pos); + out += this.jsxReadEntity(); + chunkStart = this.state.pos; + break; + case 62: + case 125: + default: + if (isNewLine(ch)) { + out += this.input.slice(chunkStart, this.state.pos); + out += this.jsxReadNewLine(true); + chunkStart = this.state.pos; + } else { + ++this.state.pos; + } + } + } + } + jsxReadNewLine(normalizeCRLF) { + const ch = this.input.charCodeAt(this.state.pos); + let out; + ++this.state.pos; + if (ch === 13 && this.input.charCodeAt(this.state.pos) === 10) { + ++this.state.pos; + out = normalizeCRLF ? "\n" : "\r\n"; + } else { + out = String.fromCharCode(ch); + } + ++this.state.curLine; + this.state.lineStart = this.state.pos; + return out; + } + jsxReadString(quote) { + let out = ""; + let chunkStart = ++this.state.pos; + for (;;) { + if (this.state.pos >= this.length) { + throw this.raise(Errors.UnterminatedString, this.state.startLoc); + } + const ch = this.input.charCodeAt(this.state.pos); + if (ch === quote) break; + if (ch === 38) { + out += this.input.slice(chunkStart, this.state.pos); + out += this.jsxReadEntity(); + chunkStart = this.state.pos; + } else if (isNewLine(ch)) { + out += this.input.slice(chunkStart, this.state.pos); + out += this.jsxReadNewLine(false); + chunkStart = this.state.pos; + } else { + ++this.state.pos; + } + } + out += this.input.slice(chunkStart, this.state.pos++); + this.finishToken(133, out); + } + jsxReadEntity() { + const startPos = ++this.state.pos; + if (this.codePointAtPos(this.state.pos) === 35) { + ++this.state.pos; + let radix = 10; + if (this.codePointAtPos(this.state.pos) === 120) { + radix = 16; + ++this.state.pos; + } + const codePoint = this.readInt(radix, undefined, false, "bail"); + if (codePoint !== null && this.codePointAtPos(this.state.pos) === 59) { + ++this.state.pos; + return String.fromCodePoint(codePoint); + } + } else { + let count = 0; + let semi = false; + while (count++ < 10 && this.state.pos < this.length && !(semi = this.codePointAtPos(this.state.pos) === 59)) { + ++this.state.pos; + } + if (semi) { + const desc = this.input.slice(startPos, this.state.pos); + const entity = entities[desc]; + ++this.state.pos; + if (entity) { + return entity; + } + } + } + this.state.pos = startPos; + return "&"; + } + jsxReadWord() { + let ch; + const start = this.state.pos; + do { + ch = this.input.charCodeAt(++this.state.pos); + } while (isIdentifierChar(ch) || ch === 45); + this.finishToken(140, this.input.slice(start, this.state.pos)); + } + jsxParseIdentifier() { + const node = this.startNode(); + if (this.match(140)) { + node.name = this.state.value; + } else if (tokenIsKeyword(this.state.type)) { + node.name = tokenLabelName(this.state.type); + } else { + this.unexpected(); + } + this.next(); + return this.finishNode(node, "JSXIdentifier"); + } + jsxParseNamespacedName() { + const startLoc = this.state.startLoc; + const name = this.jsxParseIdentifier(); + if (!this.eat(14)) return name; + const node = this.startNodeAt(startLoc); + node.namespace = name; + node.name = this.jsxParseIdentifier(); + return this.finishNode(node, "JSXNamespacedName"); + } + jsxParseElementName() { + const startLoc = this.state.startLoc; + let node = this.jsxParseNamespacedName(); + if (node.type === "JSXNamespacedName") { + return node; + } + while (this.eat(16)) { + const newNode = this.startNodeAt(startLoc); + newNode.object = node; + newNode.property = this.jsxParseIdentifier(); + node = this.finishNode(newNode, "JSXMemberExpression"); + } + return node; + } + jsxParseAttributeValue() { + let node; + switch (this.state.type) { + case 5: + node = this.startNode(); + this.setContext(types.brace); + this.next(); + node = this.jsxParseExpressionContainer(node, types.j_oTag); + if (node.expression.type === "JSXEmptyExpression") { + this.raise(JsxErrors.AttributeIsEmpty, node); + } + return node; + case 142: + case 133: + return this.parseExprAtom(); + default: + throw this.raise(JsxErrors.UnsupportedJsxValue, this.state.startLoc); + } + } + jsxParseEmptyExpression() { + const node = this.startNodeAt(this.state.lastTokEndLoc); + return this.finishNodeAt(node, "JSXEmptyExpression", this.state.startLoc); + } + jsxParseSpreadChild(node) { + this.next(); + node.expression = this.parseExpression(); + this.setContext(types.j_expr); + this.state.canStartJSXElement = true; + this.expect(8); + return this.finishNode(node, "JSXSpreadChild"); + } + jsxParseExpressionContainer(node, previousContext) { + if (this.match(8)) { + node.expression = this.jsxParseEmptyExpression(); + } else { + const expression = this.parseExpression(); + node.expression = expression; + } + this.setContext(previousContext); + this.state.canStartJSXElement = true; + this.expect(8); + return this.finishNode(node, "JSXExpressionContainer"); + } + jsxParseAttribute() { + const node = this.startNode(); + if (this.match(5)) { + this.setContext(types.brace); + this.next(); + this.expect(21); + node.argument = this.parseMaybeAssignAllowIn(); + this.setContext(types.j_oTag); + this.state.canStartJSXElement = true; + this.expect(8); + return this.finishNode(node, "JSXSpreadAttribute"); + } + node.name = this.jsxParseNamespacedName(); + node.value = this.eat(29) ? this.jsxParseAttributeValue() : null; + return this.finishNode(node, "JSXAttribute"); + } + jsxParseOpeningElementAt(startLoc) { + const node = this.startNodeAt(startLoc); + if (this.eat(143)) { + return this.finishNode(node, "JSXOpeningFragment"); + } + node.name = this.jsxParseElementName(); + return this.jsxParseOpeningElementAfterName(node); + } + jsxParseOpeningElementAfterName(node) { + const attributes = []; + while (!this.match(56) && !this.match(143)) { + attributes.push(this.jsxParseAttribute()); + } + node.attributes = attributes; + node.selfClosing = this.eat(56); + this.expect(143); + return this.finishNode(node, "JSXOpeningElement"); + } + jsxParseClosingElementAt(startLoc) { + const node = this.startNodeAt(startLoc); + if (this.eat(143)) { + return this.finishNode(node, "JSXClosingFragment"); + } + node.name = this.jsxParseElementName(); + this.expect(143); + return this.finishNode(node, "JSXClosingElement"); + } + jsxParseElementAt(startLoc) { + const node = this.startNodeAt(startLoc); + const children = []; + const openingElement = this.jsxParseOpeningElementAt(startLoc); + let closingElement = null; + if (!openingElement.selfClosing) { + contents: for (;;) { + switch (this.state.type) { + case 142: + startLoc = this.state.startLoc; + this.next(); + if (this.eat(56)) { + closingElement = this.jsxParseClosingElementAt(startLoc); + break contents; + } + children.push(this.jsxParseElementAt(startLoc)); + break; + case 141: + children.push(this.parseLiteral(this.state.value, "JSXText")); + break; + case 5: + { + const node = this.startNode(); + this.setContext(types.brace); + this.next(); + if (this.match(21)) { + children.push(this.jsxParseSpreadChild(node)); + } else { + children.push(this.jsxParseExpressionContainer(node, types.j_expr)); + } + break; + } + default: + this.unexpected(); + } + } + if (isFragment(openingElement) && !isFragment(closingElement) && closingElement !== null) { + this.raise(JsxErrors.MissingClosingTagFragment, closingElement); + } else if (!isFragment(openingElement) && isFragment(closingElement)) { + this.raise(JsxErrors.MissingClosingTagElement, closingElement, { + openingTagName: getQualifiedJSXName(openingElement.name) + }); + } else if (!isFragment(openingElement) && !isFragment(closingElement)) { + if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) { + this.raise(JsxErrors.MissingClosingTagElement, closingElement, { + openingTagName: getQualifiedJSXName(openingElement.name) + }); + } + } + } + if (isFragment(openingElement)) { + node.openingFragment = openingElement; + node.closingFragment = closingElement; + } else { + node.openingElement = openingElement; + node.closingElement = closingElement; + } + node.children = children; + if (this.match(47)) { + throw this.raise(JsxErrors.UnwrappedAdjacentJSXElements, this.state.startLoc); + } + return isFragment(openingElement) ? this.finishNode(node, "JSXFragment") : this.finishNode(node, "JSXElement"); + } + jsxParseElement() { + const startLoc = this.state.startLoc; + this.next(); + return this.jsxParseElementAt(startLoc); + } + setContext(newContext) { + const { + context + } = this.state; + context[context.length - 1] = newContext; + } + parseExprAtom(refExpressionErrors) { + if (this.match(142)) { + return this.jsxParseElement(); + } else if (this.match(47) && this.input.charCodeAt(this.state.pos) !== 33) { + this.replaceToken(142); + return this.jsxParseElement(); + } else { + return super.parseExprAtom(refExpressionErrors); + } + } + skipSpace() { + const curContext = this.curContext(); + if (!curContext.preserveSpace) super.skipSpace(); + } + getTokenFromCode(code) { + const context = this.curContext(); + if (context === types.j_expr) { + this.jsxReadToken(); + return; + } + if (context === types.j_oTag || context === types.j_cTag) { + if (isIdentifierStart(code)) { + this.jsxReadWord(); + return; + } + if (code === 62) { + ++this.state.pos; + this.finishToken(143); + return; + } + if ((code === 34 || code === 39) && context === types.j_oTag) { + this.jsxReadString(code); + return; + } + } + if (code === 60 && this.state.canStartJSXElement && this.input.charCodeAt(this.state.pos + 1) !== 33) { + ++this.state.pos; + this.finishToken(142); + return; + } + super.getTokenFromCode(code); + } + updateContext(prevType) { + const { + context, + type + } = this.state; + if (type === 56 && prevType === 142) { + context.splice(-2, 2, types.j_cTag); + this.state.canStartJSXElement = false; + } else if (type === 142) { + context.push(types.j_oTag); + } else if (type === 143) { + const out = context[context.length - 1]; + if (out === types.j_oTag && prevType === 56 || out === types.j_cTag) { + context.pop(); + this.state.canStartJSXElement = context[context.length - 1] === types.j_expr; + } else { + this.setContext(types.j_expr); + this.state.canStartJSXElement = true; + } + } else { + this.state.canStartJSXElement = tokenComesBeforeExpression(type); + } + } +}; +class TypeScriptScope extends Scope { + constructor(...args) { + super(...args); + this.tsNames = new Map(); + } +} +class TypeScriptScopeHandler extends ScopeHandler { + constructor(...args) { + super(...args); + this.importsStack = []; + } + createScope(flags) { + this.importsStack.push(new Set()); + return new TypeScriptScope(flags); + } + enter(flags) { + if (flags === 256) { + this.importsStack.push(new Set()); + } + super.enter(flags); + } + exit() { + const flags = super.exit(); + if (flags === 256) { + this.importsStack.pop(); + } + return flags; + } + hasImport(name, allowShadow) { + const len = this.importsStack.length; + if (this.importsStack[len - 1].has(name)) { + return true; + } + if (!allowShadow && len > 1) { + for (let i = 0; i < len - 1; i++) { + if (this.importsStack[i].has(name)) return true; + } + } + return false; + } + declareName(name, bindingType, loc) { + if (bindingType & 4096) { + if (this.hasImport(name, true)) { + this.parser.raise(Errors.VarRedeclaration, loc, { + identifierName: name + }); + } + this.importsStack[this.importsStack.length - 1].add(name); + return; + } + const scope = this.currentScope(); + let type = scope.tsNames.get(name) || 0; + if (bindingType & 1024) { + this.maybeExportDefined(scope, name); + scope.tsNames.set(name, type | 16); + return; + } + super.declareName(name, bindingType, loc); + if (bindingType & 2) { + if (!(bindingType & 1)) { + this.checkRedeclarationInScope(scope, name, bindingType, loc); + this.maybeExportDefined(scope, name); + } + type = type | 1; + } + if (bindingType & 256) { + type = type | 2; + } + if (bindingType & 512) { + type = type | 4; + } + if (bindingType & 128) { + type = type | 8; + } + if (type) scope.tsNames.set(name, type); + } + isRedeclaredInScope(scope, name, bindingType) { + const type = scope.tsNames.get(name); + if ((type & 2) > 0) { + if (bindingType & 256) { + const isConst = !!(bindingType & 512); + const wasConst = (type & 4) > 0; + return isConst !== wasConst; + } + return true; + } + if (bindingType & 128 && (type & 8) > 0) { + if (scope.names.get(name) & 2) { + return !!(bindingType & 1); + } else { + return false; + } + } + if (bindingType & 2 && (type & 1) > 0) { + return true; + } + return super.isRedeclaredInScope(scope, name, bindingType); + } + checkLocalExport(id) { + const { + name + } = id; + if (this.hasImport(name)) return; + const len = this.scopeStack.length; + for (let i = len - 1; i >= 0; i--) { + const scope = this.scopeStack[i]; + const type = scope.tsNames.get(name); + if ((type & 1) > 0 || (type & 16) > 0) { + return; + } + } + super.checkLocalExport(id); + } +} +const unwrapParenthesizedExpression = node => { + return node.type === "ParenthesizedExpression" ? unwrapParenthesizedExpression(node.expression) : node; +}; +class LValParser extends NodeUtils { + toAssignable(node, isLHS = false) { + var _node$extra, _node$extra3; + let parenthesized = undefined; + if (node.type === "ParenthesizedExpression" || (_node$extra = node.extra) != null && _node$extra.parenthesized) { + parenthesized = unwrapParenthesizedExpression(node); + if (isLHS) { + if (parenthesized.type === "Identifier") { + this.expressionScope.recordArrowParameterBindingError(Errors.InvalidParenthesizedAssignment, node); + } else if (parenthesized.type !== "MemberExpression" && !this.isOptionalMemberExpression(parenthesized)) { + this.raise(Errors.InvalidParenthesizedAssignment, node); + } + } else { + this.raise(Errors.InvalidParenthesizedAssignment, node); + } + } + switch (node.type) { + case "Identifier": + case "ObjectPattern": + case "ArrayPattern": + case "AssignmentPattern": + case "RestElement": + break; + case "ObjectExpression": + node.type = "ObjectPattern"; + for (let i = 0, length = node.properties.length, last = length - 1; i < length; i++) { + var _node$extra2; + const prop = node.properties[i]; + const isLast = i === last; + this.toAssignableObjectExpressionProp(prop, isLast, isLHS); + if (isLast && prop.type === "RestElement" && (_node$extra2 = node.extra) != null && _node$extra2.trailingCommaLoc) { + this.raise(Errors.RestTrailingComma, node.extra.trailingCommaLoc); + } + } + break; + case "ObjectProperty": + { + const { + key, + value + } = node; + if (this.isPrivateName(key)) { + this.classScope.usePrivateName(this.getPrivateNameSV(key), key.loc.start); + } + this.toAssignable(value, isLHS); + break; + } + case "SpreadElement": + { + throw new Error("Internal @babel/parser error (this is a bug, please report it)." + " SpreadElement should be converted by .toAssignable's caller."); + } + case "ArrayExpression": + node.type = "ArrayPattern"; + this.toAssignableList(node.elements, (_node$extra3 = node.extra) == null ? void 0 : _node$extra3.trailingCommaLoc, isLHS); + break; + case "AssignmentExpression": + if (node.operator !== "=") { + this.raise(Errors.MissingEqInAssignment, node.left.loc.end); + } + node.type = "AssignmentPattern"; + delete node.operator; + this.toAssignable(node.left, isLHS); + break; + case "ParenthesizedExpression": + this.toAssignable(parenthesized, isLHS); + break; + } + } + toAssignableObjectExpressionProp(prop, isLast, isLHS) { + if (prop.type === "ObjectMethod") { + this.raise(prop.kind === "get" || prop.kind === "set" ? Errors.PatternHasAccessor : Errors.PatternHasMethod, prop.key); + } else if (prop.type === "SpreadElement") { + prop.type = "RestElement"; + const arg = prop.argument; + this.checkToRestConversion(arg, false); + this.toAssignable(arg, isLHS); + if (!isLast) { + this.raise(Errors.RestTrailingComma, prop); + } + } else { + this.toAssignable(prop, isLHS); + } + } + toAssignableList(exprList, trailingCommaLoc, isLHS) { + const end = exprList.length - 1; + for (let i = 0; i <= end; i++) { + const elt = exprList[i]; + if (!elt) continue; + if (elt.type === "SpreadElement") { + elt.type = "RestElement"; + const arg = elt.argument; + this.checkToRestConversion(arg, true); + this.toAssignable(arg, isLHS); + } else { + this.toAssignable(elt, isLHS); + } + if (elt.type === "RestElement") { + if (i < end) { + this.raise(Errors.RestTrailingComma, elt); + } else if (trailingCommaLoc) { + this.raise(Errors.RestTrailingComma, trailingCommaLoc); + } + } + } + } + isAssignable(node, isBinding) { + switch (node.type) { + case "Identifier": + case "ObjectPattern": + case "ArrayPattern": + case "AssignmentPattern": + case "RestElement": + return true; + case "ObjectExpression": + { + const last = node.properties.length - 1; + return node.properties.every((prop, i) => { + return prop.type !== "ObjectMethod" && (i === last || prop.type !== "SpreadElement") && this.isAssignable(prop); + }); + } + case "ObjectProperty": + return this.isAssignable(node.value); + case "SpreadElement": + return this.isAssignable(node.argument); + case "ArrayExpression": + return node.elements.every(element => element === null || this.isAssignable(element)); + case "AssignmentExpression": + return node.operator === "="; + case "ParenthesizedExpression": + return this.isAssignable(node.expression); + case "MemberExpression": + case "OptionalMemberExpression": + return !isBinding; + default: + return false; + } + } + toReferencedList(exprList, isParenthesizedExpr) { + return exprList; + } + toReferencedListDeep(exprList, isParenthesizedExpr) { + this.toReferencedList(exprList, isParenthesizedExpr); + for (const expr of exprList) { + if ((expr == null ? void 0 : expr.type) === "ArrayExpression") { + this.toReferencedListDeep(expr.elements); + } + } + } + parseSpread(refExpressionErrors) { + const node = this.startNode(); + this.next(); + node.argument = this.parseMaybeAssignAllowIn(refExpressionErrors, undefined); + return this.finishNode(node, "SpreadElement"); + } + parseRestBinding() { + const node = this.startNode(); + this.next(); + node.argument = this.parseBindingAtom(); + return this.finishNode(node, "RestElement"); + } + parseBindingAtom() { + switch (this.state.type) { + case 0: + { + const node = this.startNode(); + this.next(); + node.elements = this.parseBindingList(3, 93, 1); + return this.finishNode(node, "ArrayPattern"); + } + case 5: + return this.parseObjectLike(8, true); + } + return this.parseIdentifier(); + } + parseBindingList(close, closeCharCode, flags) { + const allowEmpty = flags & 1; + const elts = []; + let first = true; + while (!this.eat(close)) { + if (first) { + first = false; + } else { + this.expect(12); + } + if (allowEmpty && this.match(12)) { + elts.push(null); + } else if (this.eat(close)) { + break; + } else if (this.match(21)) { + elts.push(this.parseAssignableListItemTypes(this.parseRestBinding(), flags)); + if (!this.checkCommaAfterRest(closeCharCode)) { + this.expect(close); + break; + } + } else { + const decorators = []; + if (this.match(26) && this.hasPlugin("decorators")) { + this.raise(Errors.UnsupportedParameterDecorator, this.state.startLoc); + } + while (this.match(26)) { + decorators.push(this.parseDecorator()); + } + elts.push(this.parseAssignableListItem(flags, decorators)); + } + } + return elts; + } + parseBindingRestProperty(prop) { + this.next(); + prop.argument = this.parseIdentifier(); + this.checkCommaAfterRest(125); + return this.finishNode(prop, "RestElement"); + } + parseBindingProperty() { + const { + type, + startLoc + } = this.state; + if (type === 21) { + return this.parseBindingRestProperty(this.startNode()); + } + const prop = this.startNode(); + if (type === 138) { + this.expectPlugin("destructuringPrivate", startLoc); + this.classScope.usePrivateName(this.state.value, startLoc); + prop.key = this.parsePrivateName(); + } else { + this.parsePropertyName(prop); + } + prop.method = false; + return this.parseObjPropValue(prop, startLoc, false, false, true, false); + } + parseAssignableListItem(flags, decorators) { + const left = this.parseMaybeDefault(); + this.parseAssignableListItemTypes(left, flags); + const elt = this.parseMaybeDefault(left.loc.start, left); + if (decorators.length) { + left.decorators = decorators; + } + return elt; + } + parseAssignableListItemTypes(param, flags) { + return param; + } + parseMaybeDefault(startLoc, left) { + var _startLoc, _left; + (_startLoc = startLoc) != null ? _startLoc : startLoc = this.state.startLoc; + left = (_left = left) != null ? _left : this.parseBindingAtom(); + if (!this.eat(29)) return left; + const node = this.startNodeAt(startLoc); + node.left = left; + node.right = this.parseMaybeAssignAllowIn(); + return this.finishNode(node, "AssignmentPattern"); + } + isValidLVal(type, isUnparenthesizedInAssign, binding) { + switch (type) { + case "AssignmentPattern": + return "left"; + case "RestElement": + return "argument"; + case "ObjectProperty": + return "value"; + case "ParenthesizedExpression": + return "expression"; + case "ArrayPattern": + return "elements"; + case "ObjectPattern": + return "properties"; + } + return false; + } + isOptionalMemberExpression(expression) { + return expression.type === "OptionalMemberExpression"; + } + checkLVal(expression, ancestor, binding = 64, checkClashes = false, strictModeChanged = false, hasParenthesizedAncestor = false) { + var _expression$extra; + const type = expression.type; + if (this.isObjectMethod(expression)) return; + const isOptionalMemberExpression = this.isOptionalMemberExpression(expression); + if (isOptionalMemberExpression || type === "MemberExpression") { + if (isOptionalMemberExpression) { + this.expectPlugin("optionalChainingAssign", expression.loc.start); + if (ancestor.type !== "AssignmentExpression") { + this.raise(Errors.InvalidLhsOptionalChaining, expression, { + ancestor + }); + } + } + if (binding !== 64) { + this.raise(Errors.InvalidPropertyBindingPattern, expression); + } + return; + } + if (type === "Identifier") { + this.checkIdentifier(expression, binding, strictModeChanged); + const { + name + } = expression; + if (checkClashes) { + if (checkClashes.has(name)) { + this.raise(Errors.ParamDupe, expression); + } else { + checkClashes.add(name); + } + } + return; + } + const validity = this.isValidLVal(type, !(hasParenthesizedAncestor || (_expression$extra = expression.extra) != null && _expression$extra.parenthesized) && ancestor.type === "AssignmentExpression", binding); + if (validity === true) return; + if (validity === false) { + const ParseErrorClass = binding === 64 ? Errors.InvalidLhs : Errors.InvalidLhsBinding; + this.raise(ParseErrorClass, expression, { + ancestor + }); + return; + } + let key, isParenthesizedExpression; + if (typeof validity === "string") { + key = validity; + isParenthesizedExpression = type === "ParenthesizedExpression"; + } else { + [key, isParenthesizedExpression] = validity; + } + const nextAncestor = type === "ArrayPattern" || type === "ObjectPattern" ? { + type + } : ancestor; + const val = expression[key]; + if (Array.isArray(val)) { + for (const child of val) { + if (child) { + this.checkLVal(child, nextAncestor, binding, checkClashes, strictModeChanged, isParenthesizedExpression); + } + } + } else if (val) { + this.checkLVal(val, nextAncestor, binding, checkClashes, strictModeChanged, isParenthesizedExpression); + } + } + checkIdentifier(at, bindingType, strictModeChanged = false) { + if (this.state.strict && (strictModeChanged ? isStrictBindReservedWord(at.name, this.inModule) : isStrictBindOnlyReservedWord(at.name))) { + if (bindingType === 64) { + this.raise(Errors.StrictEvalArguments, at, { + referenceName: at.name + }); + } else { + this.raise(Errors.StrictEvalArgumentsBinding, at, { + bindingName: at.name + }); + } + } + if (bindingType & 8192 && at.name === "let") { + this.raise(Errors.LetInLexicalBinding, at); + } + if (!(bindingType & 64)) { + this.declareNameFromIdentifier(at, bindingType); + } + } + declareNameFromIdentifier(identifier, binding) { + this.scope.declareName(identifier.name, binding, identifier.loc.start); + } + checkToRestConversion(node, allowPattern) { + switch (node.type) { + case "ParenthesizedExpression": + this.checkToRestConversion(node.expression, allowPattern); + break; + case "Identifier": + case "MemberExpression": + break; + case "ArrayExpression": + case "ObjectExpression": + if (allowPattern) break; + default: + this.raise(Errors.InvalidRestAssignmentPattern, node); + } + } + checkCommaAfterRest(close) { + if (!this.match(12)) { + return false; + } + this.raise(this.lookaheadCharCode() === close ? Errors.RestTrailingComma : Errors.ElementAfterRest, this.state.startLoc); + return true; + } +} +function nonNull(x) { + if (x == null) { + throw new Error(`Unexpected ${x} value.`); + } + return x; +} +function assert(x) { + if (!x) { + throw new Error("Assert fail"); + } +} +const TSErrors = ParseErrorEnum`typescript`({ + AbstractMethodHasImplementation: ({ + methodName + }) => `Method '${methodName}' cannot have an implementation because it is marked abstract.`, + AbstractPropertyHasInitializer: ({ + propertyName + }) => `Property '${propertyName}' cannot have an initializer because it is marked abstract.`, + AccessorCannotBeOptional: "An 'accessor' property cannot be declared optional.", + AccessorCannotDeclareThisParameter: "'get' and 'set' accessors cannot declare 'this' parameters.", + AccessorCannotHaveTypeParameters: "An accessor cannot have type parameters.", + ClassMethodHasDeclare: "Class methods cannot have the 'declare' modifier.", + ClassMethodHasReadonly: "Class methods cannot have the 'readonly' modifier.", + ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference: "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference.", + ConstructorHasTypeParameters: "Type parameters cannot appear on a constructor declaration.", + DeclareAccessor: ({ + kind + }) => `'declare' is not allowed in ${kind}ters.`, + DeclareClassFieldHasInitializer: "Initializers are not allowed in ambient contexts.", + DeclareFunctionHasImplementation: "An implementation cannot be declared in ambient contexts.", + DuplicateAccessibilityModifier: ({ + modifier + }) => `Accessibility modifier already seen.`, + DuplicateModifier: ({ + modifier + }) => `Duplicate modifier: '${modifier}'.`, + EmptyHeritageClauseType: ({ + token + }) => `'${token}' list cannot be empty.`, + EmptyTypeArguments: "Type argument list cannot be empty.", + EmptyTypeParameters: "Type parameter list cannot be empty.", + ExpectedAmbientAfterExportDeclare: "'export declare' must be followed by an ambient declaration.", + ImportAliasHasImportType: "An import alias can not use 'import type'.", + ImportReflectionHasImportType: "An `import module` declaration can not use `type` modifier", + IncompatibleModifiers: ({ + modifiers + }) => `'${modifiers[0]}' modifier cannot be used with '${modifiers[1]}' modifier.`, + IndexSignatureHasAbstract: "Index signatures cannot have the 'abstract' modifier.", + IndexSignatureHasAccessibility: ({ + modifier + }) => `Index signatures cannot have an accessibility modifier ('${modifier}').`, + IndexSignatureHasDeclare: "Index signatures cannot have the 'declare' modifier.", + IndexSignatureHasOverride: "'override' modifier cannot appear on an index signature.", + IndexSignatureHasStatic: "Index signatures cannot have the 'static' modifier.", + InitializerNotAllowedInAmbientContext: "Initializers are not allowed in ambient contexts.", + InvalidModifierOnTypeMember: ({ + modifier + }) => `'${modifier}' modifier cannot appear on a type member.`, + InvalidModifierOnTypeParameter: ({ + modifier + }) => `'${modifier}' modifier cannot appear on a type parameter.`, + InvalidModifierOnTypeParameterPositions: ({ + modifier + }) => `'${modifier}' modifier can only appear on a type parameter of a class, interface or type alias.`, + InvalidModifiersOrder: ({ + orderedModifiers + }) => `'${orderedModifiers[0]}' modifier must precede '${orderedModifiers[1]}' modifier.`, + InvalidPropertyAccessAfterInstantiationExpression: "Invalid property access after an instantiation expression. " + "You can either wrap the instantiation expression in parentheses, or delete the type arguments.", + InvalidTupleMemberLabel: "Tuple members must be labeled with a simple identifier.", + MissingInterfaceName: "'interface' declarations must be followed by an identifier.", + NonAbstractClassHasAbstractMethod: "Abstract methods can only appear within an abstract class.", + NonClassMethodPropertyHasAbstractModifer: "'abstract' modifier can only appear on a class, method, or property declaration.", + OptionalTypeBeforeRequired: "A required element cannot follow an optional element.", + OverrideNotInSubClass: "This member cannot have an 'override' modifier because its containing class does not extend another class.", + PatternIsOptional: "A binding pattern parameter cannot be optional in an implementation signature.", + PrivateElementHasAbstract: "Private elements cannot have the 'abstract' modifier.", + PrivateElementHasAccessibility: ({ + modifier + }) => `Private elements cannot have an accessibility modifier ('${modifier}').`, + ReadonlyForMethodSignature: "'readonly' modifier can only appear on a property declaration or index signature.", + ReservedArrowTypeParam: "This syntax is reserved in files with the .mts or .cts extension. Add a trailing comma, as in `() => ...`.", + ReservedTypeAssertion: "This syntax is reserved in files with the .mts or .cts extension. Use an `as` expression instead.", + SetAccessorCannotHaveOptionalParameter: "A 'set' accessor cannot have an optional parameter.", + SetAccessorCannotHaveRestParameter: "A 'set' accessor cannot have rest parameter.", + SetAccessorCannotHaveReturnType: "A 'set' accessor cannot have a return type annotation.", + SingleTypeParameterWithoutTrailingComma: ({ + typeParameterName + }) => `Single type parameter ${typeParameterName} should have a trailing comma. Example usage: <${typeParameterName},>.`, + StaticBlockCannotHaveModifier: "Static class blocks cannot have any modifier.", + TupleOptionalAfterType: "A labeled tuple optional element must be declared using a question mark after the name and before the colon (`name?: type`), rather than after the type (`name: type?`).", + TypeAnnotationAfterAssign: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.", + TypeImportCannotSpecifyDefaultAndNamed: "A type-only import can specify a default import or named bindings, but not both.", + TypeModifierIsUsedInTypeExports: "The 'type' modifier cannot be used on a named export when 'export type' is used on its export statement.", + TypeModifierIsUsedInTypeImports: "The 'type' modifier cannot be used on a named import when 'import type' is used on its import statement.", + UnexpectedParameterModifier: "A parameter property is only allowed in a constructor implementation.", + UnexpectedReadonly: "'readonly' type modifier is only permitted on array and tuple literal types.", + UnexpectedTypeAnnotation: "Did not expect a type annotation here.", + UnexpectedTypeCastInParameter: "Unexpected type cast in parameter position.", + UnsupportedImportTypeArgument: "Argument in a type import must be a string literal.", + UnsupportedParameterPropertyKind: "A parameter property may not be declared using a binding pattern.", + UnsupportedSignatureParameterKind: ({ + type + }) => `Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got ${type}.` +}); +function keywordTypeFromName(value) { + switch (value) { + case "any": + return "TSAnyKeyword"; + case "boolean": + return "TSBooleanKeyword"; + case "bigint": + return "TSBigIntKeyword"; + case "never": + return "TSNeverKeyword"; + case "number": + return "TSNumberKeyword"; + case "object": + return "TSObjectKeyword"; + case "string": + return "TSStringKeyword"; + case "symbol": + return "TSSymbolKeyword"; + case "undefined": + return "TSUndefinedKeyword"; + case "unknown": + return "TSUnknownKeyword"; + default: + return undefined; + } +} +function tsIsAccessModifier(modifier) { + return modifier === "private" || modifier === "public" || modifier === "protected"; +} +function tsIsVarianceAnnotations(modifier) { + return modifier === "in" || modifier === "out"; +} +var typescript = superClass => class TypeScriptParserMixin extends superClass { + constructor(...args) { + super(...args); + this.tsParseInOutModifiers = this.tsParseModifiers.bind(this, { + allowedModifiers: ["in", "out"], + disallowedModifiers: ["const", "public", "private", "protected", "readonly", "declare", "abstract", "override"], + errorTemplate: TSErrors.InvalidModifierOnTypeParameter + }); + this.tsParseConstModifier = this.tsParseModifiers.bind(this, { + allowedModifiers: ["const"], + disallowedModifiers: ["in", "out"], + errorTemplate: TSErrors.InvalidModifierOnTypeParameterPositions + }); + this.tsParseInOutConstModifiers = this.tsParseModifiers.bind(this, { + allowedModifiers: ["in", "out", "const"], + disallowedModifiers: ["public", "private", "protected", "readonly", "declare", "abstract", "override"], + errorTemplate: TSErrors.InvalidModifierOnTypeParameter + }); + } + getScopeHandler() { + return TypeScriptScopeHandler; + } + tsIsIdentifier() { + return tokenIsIdentifier(this.state.type); + } + tsTokenCanFollowModifier() { + return this.match(0) || this.match(5) || this.match(55) || this.match(21) || this.match(138) || this.isLiteralPropertyName(); + } + tsNextTokenOnSameLineAndCanFollowModifier() { + this.next(); + if (this.hasPrecedingLineBreak()) { + return false; + } + return this.tsTokenCanFollowModifier(); + } + tsNextTokenCanFollowModifier() { + if (this.match(106)) { + this.next(); + return this.tsTokenCanFollowModifier(); + } + return this.tsNextTokenOnSameLineAndCanFollowModifier(); + } + tsParseModifier(allowedModifiers, stopOnStartOfClassStaticBlock) { + if (!tokenIsIdentifier(this.state.type) && this.state.type !== 58 && this.state.type !== 75) { + return undefined; + } + const modifier = this.state.value; + if (allowedModifiers.includes(modifier)) { + if (stopOnStartOfClassStaticBlock && this.tsIsStartOfStaticBlocks()) { + return undefined; + } + if (this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this))) { + return modifier; + } + } + return undefined; + } + tsParseModifiers({ + allowedModifiers, + disallowedModifiers, + stopOnStartOfClassStaticBlock, + errorTemplate = TSErrors.InvalidModifierOnTypeMember + }, modified) { + const enforceOrder = (loc, modifier, before, after) => { + if (modifier === before && modified[after]) { + this.raise(TSErrors.InvalidModifiersOrder, loc, { + orderedModifiers: [before, after] + }); + } + }; + const incompatible = (loc, modifier, mod1, mod2) => { + if (modified[mod1] && modifier === mod2 || modified[mod2] && modifier === mod1) { + this.raise(TSErrors.IncompatibleModifiers, loc, { + modifiers: [mod1, mod2] + }); + } + }; + for (;;) { + const { + startLoc + } = this.state; + const modifier = this.tsParseModifier(allowedModifiers.concat(disallowedModifiers != null ? disallowedModifiers : []), stopOnStartOfClassStaticBlock); + if (!modifier) break; + if (tsIsAccessModifier(modifier)) { + if (modified.accessibility) { + this.raise(TSErrors.DuplicateAccessibilityModifier, startLoc, { + modifier + }); + } else { + enforceOrder(startLoc, modifier, modifier, "override"); + enforceOrder(startLoc, modifier, modifier, "static"); + enforceOrder(startLoc, modifier, modifier, "readonly"); + modified.accessibility = modifier; + } + } else if (tsIsVarianceAnnotations(modifier)) { + if (modified[modifier]) { + this.raise(TSErrors.DuplicateModifier, startLoc, { + modifier + }); + } + modified[modifier] = true; + enforceOrder(startLoc, modifier, "in", "out"); + } else { + if (hasOwnProperty.call(modified, modifier)) { + this.raise(TSErrors.DuplicateModifier, startLoc, { + modifier + }); + } else { + enforceOrder(startLoc, modifier, "static", "readonly"); + enforceOrder(startLoc, modifier, "static", "override"); + enforceOrder(startLoc, modifier, "override", "readonly"); + enforceOrder(startLoc, modifier, "abstract", "override"); + incompatible(startLoc, modifier, "declare", "override"); + incompatible(startLoc, modifier, "static", "abstract"); + } + modified[modifier] = true; + } + if (disallowedModifiers != null && disallowedModifiers.includes(modifier)) { + this.raise(errorTemplate, startLoc, { + modifier + }); + } + } + } + tsIsListTerminator(kind) { + switch (kind) { + case "EnumMembers": + case "TypeMembers": + return this.match(8); + case "HeritageClauseElement": + return this.match(5); + case "TupleElementTypes": + return this.match(3); + case "TypeParametersOrArguments": + return this.match(48); + } + } + tsParseList(kind, parseElement) { + const result = []; + while (!this.tsIsListTerminator(kind)) { + result.push(parseElement()); + } + return result; + } + tsParseDelimitedList(kind, parseElement, refTrailingCommaPos) { + return nonNull(this.tsParseDelimitedListWorker(kind, parseElement, true, refTrailingCommaPos)); + } + tsParseDelimitedListWorker(kind, parseElement, expectSuccess, refTrailingCommaPos) { + const result = []; + let trailingCommaPos = -1; + for (;;) { + if (this.tsIsListTerminator(kind)) { + break; + } + trailingCommaPos = -1; + const element = parseElement(); + if (element == null) { + return undefined; + } + result.push(element); + if (this.eat(12)) { + trailingCommaPos = this.state.lastTokStartLoc.index; + continue; + } + if (this.tsIsListTerminator(kind)) { + break; + } + if (expectSuccess) { + this.expect(12); + } + return undefined; + } + if (refTrailingCommaPos) { + refTrailingCommaPos.value = trailingCommaPos; + } + return result; + } + tsParseBracketedList(kind, parseElement, bracket, skipFirstToken, refTrailingCommaPos) { + if (!skipFirstToken) { + if (bracket) { + this.expect(0); + } else { + this.expect(47); + } + } + const result = this.tsParseDelimitedList(kind, parseElement, refTrailingCommaPos); + if (bracket) { + this.expect(3); + } else { + this.expect(48); + } + return result; + } + tsParseImportType() { + const node = this.startNode(); + this.expect(83); + this.expect(10); + if (!this.match(133)) { + this.raise(TSErrors.UnsupportedImportTypeArgument, this.state.startLoc); + } + node.argument = super.parseExprAtom(); + if (this.hasPlugin("importAttributes") || this.hasPlugin("importAssertions")) { + node.options = null; + } + if (this.eat(12)) { + this.expectImportAttributesPlugin(); + if (!this.match(11)) { + node.options = super.parseMaybeAssignAllowIn(); + this.eat(12); + } + } + this.expect(11); + if (this.eat(16)) { + node.qualifier = this.tsParseEntityName(); + } + if (this.match(47)) { + node.typeParameters = this.tsParseTypeArguments(); + } + return this.finishNode(node, "TSImportType"); + } + tsParseEntityName(allowReservedWords = true) { + let entity = this.parseIdentifier(allowReservedWords); + while (this.eat(16)) { + const node = this.startNodeAtNode(entity); + node.left = entity; + node.right = this.parseIdentifier(allowReservedWords); + entity = this.finishNode(node, "TSQualifiedName"); + } + return entity; + } + tsParseTypeReference() { + const node = this.startNode(); + node.typeName = this.tsParseEntityName(); + if (!this.hasPrecedingLineBreak() && this.match(47)) { + node.typeParameters = this.tsParseTypeArguments(); + } + return this.finishNode(node, "TSTypeReference"); + } + tsParseThisTypePredicate(lhs) { + this.next(); + const node = this.startNodeAtNode(lhs); + node.parameterName = lhs; + node.typeAnnotation = this.tsParseTypeAnnotation(false); + node.asserts = false; + return this.finishNode(node, "TSTypePredicate"); + } + tsParseThisTypeNode() { + const node = this.startNode(); + this.next(); + return this.finishNode(node, "TSThisType"); + } + tsParseTypeQuery() { + const node = this.startNode(); + this.expect(87); + if (this.match(83)) { + node.exprName = this.tsParseImportType(); + } else { + node.exprName = this.tsParseEntityName(); + } + if (!this.hasPrecedingLineBreak() && this.match(47)) { + node.typeParameters = this.tsParseTypeArguments(); + } + return this.finishNode(node, "TSTypeQuery"); + } + tsParseTypeParameter(parseModifiers) { + const node = this.startNode(); + parseModifiers(node); + node.name = this.tsParseTypeParameterName(); + node.constraint = this.tsEatThenParseType(81); + node.default = this.tsEatThenParseType(29); + return this.finishNode(node, "TSTypeParameter"); + } + tsTryParseTypeParameters(parseModifiers) { + if (this.match(47)) { + return this.tsParseTypeParameters(parseModifiers); + } + } + tsParseTypeParameters(parseModifiers) { + const node = this.startNode(); + if (this.match(47) || this.match(142)) { + this.next(); + } else { + this.unexpected(); + } + const refTrailingCommaPos = { + value: -1 + }; + node.params = this.tsParseBracketedList("TypeParametersOrArguments", this.tsParseTypeParameter.bind(this, parseModifiers), false, true, refTrailingCommaPos); + if (node.params.length === 0) { + this.raise(TSErrors.EmptyTypeParameters, node); + } + if (refTrailingCommaPos.value !== -1) { + this.addExtra(node, "trailingComma", refTrailingCommaPos.value); + } + return this.finishNode(node, "TSTypeParameterDeclaration"); + } + tsFillSignature(returnToken, signature) { + const returnTokenRequired = returnToken === 19; + const paramsKey = "parameters"; + const returnTypeKey = "typeAnnotation"; + signature.typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier); + this.expect(10); + signature[paramsKey] = this.tsParseBindingListForSignature(); + if (returnTokenRequired) { + signature[returnTypeKey] = this.tsParseTypeOrTypePredicateAnnotation(returnToken); + } else if (this.match(returnToken)) { + signature[returnTypeKey] = this.tsParseTypeOrTypePredicateAnnotation(returnToken); + } + } + tsParseBindingListForSignature() { + const list = super.parseBindingList(11, 41, 2); + for (const pattern of list) { + const { + type + } = pattern; + if (type === "AssignmentPattern" || type === "TSParameterProperty") { + this.raise(TSErrors.UnsupportedSignatureParameterKind, pattern, { + type + }); + } + } + return list; + } + tsParseTypeMemberSemicolon() { + if (!this.eat(12) && !this.isLineTerminator()) { + this.expect(13); + } + } + tsParseSignatureMember(kind, node) { + this.tsFillSignature(14, node); + this.tsParseTypeMemberSemicolon(); + return this.finishNode(node, kind); + } + tsIsUnambiguouslyIndexSignature() { + this.next(); + if (tokenIsIdentifier(this.state.type)) { + this.next(); + return this.match(14); + } + return false; + } + tsTryParseIndexSignature(node) { + if (!(this.match(0) && this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this)))) { + return; + } + this.expect(0); + const id = this.parseIdentifier(); + id.typeAnnotation = this.tsParseTypeAnnotation(); + this.resetEndLocation(id); + this.expect(3); + node.parameters = [id]; + const type = this.tsTryParseTypeAnnotation(); + if (type) node.typeAnnotation = type; + this.tsParseTypeMemberSemicolon(); + return this.finishNode(node, "TSIndexSignature"); + } + tsParsePropertyOrMethodSignature(node, readonly) { + if (this.eat(17)) node.optional = true; + const nodeAny = node; + if (this.match(10) || this.match(47)) { + if (readonly) { + this.raise(TSErrors.ReadonlyForMethodSignature, node); + } + const method = nodeAny; + if (method.kind && this.match(47)) { + this.raise(TSErrors.AccessorCannotHaveTypeParameters, this.state.curPosition()); + } + this.tsFillSignature(14, method); + this.tsParseTypeMemberSemicolon(); + const paramsKey = "parameters"; + const returnTypeKey = "typeAnnotation"; + if (method.kind === "get") { + if (method[paramsKey].length > 0) { + this.raise(Errors.BadGetterArity, this.state.curPosition()); + if (this.isThisParam(method[paramsKey][0])) { + this.raise(TSErrors.AccessorCannotDeclareThisParameter, this.state.curPosition()); + } + } + } else if (method.kind === "set") { + if (method[paramsKey].length !== 1) { + this.raise(Errors.BadSetterArity, this.state.curPosition()); + } else { + const firstParameter = method[paramsKey][0]; + if (this.isThisParam(firstParameter)) { + this.raise(TSErrors.AccessorCannotDeclareThisParameter, this.state.curPosition()); + } + if (firstParameter.type === "Identifier" && firstParameter.optional) { + this.raise(TSErrors.SetAccessorCannotHaveOptionalParameter, this.state.curPosition()); + } + if (firstParameter.type === "RestElement") { + this.raise(TSErrors.SetAccessorCannotHaveRestParameter, this.state.curPosition()); + } + } + if (method[returnTypeKey]) { + this.raise(TSErrors.SetAccessorCannotHaveReturnType, method[returnTypeKey]); + } + } else { + method.kind = "method"; + } + return this.finishNode(method, "TSMethodSignature"); + } else { + const property = nodeAny; + if (readonly) property.readonly = true; + const type = this.tsTryParseTypeAnnotation(); + if (type) property.typeAnnotation = type; + this.tsParseTypeMemberSemicolon(); + return this.finishNode(property, "TSPropertySignature"); + } + } + tsParseTypeMember() { + const node = this.startNode(); + if (this.match(10) || this.match(47)) { + return this.tsParseSignatureMember("TSCallSignatureDeclaration", node); + } + if (this.match(77)) { + const id = this.startNode(); + this.next(); + if (this.match(10) || this.match(47)) { + return this.tsParseSignatureMember("TSConstructSignatureDeclaration", node); + } else { + node.key = this.createIdentifier(id, "new"); + return this.tsParsePropertyOrMethodSignature(node, false); + } + } + this.tsParseModifiers({ + allowedModifiers: ["readonly"], + disallowedModifiers: ["declare", "abstract", "private", "protected", "public", "static", "override"] + }, node); + const idx = this.tsTryParseIndexSignature(node); + if (idx) { + return idx; + } + super.parsePropertyName(node); + if (!node.computed && node.key.type === "Identifier" && (node.key.name === "get" || node.key.name === "set") && this.tsTokenCanFollowModifier()) { + node.kind = node.key.name; + super.parsePropertyName(node); + } + return this.tsParsePropertyOrMethodSignature(node, !!node.readonly); + } + tsParseTypeLiteral() { + const node = this.startNode(); + node.members = this.tsParseObjectTypeMembers(); + return this.finishNode(node, "TSTypeLiteral"); + } + tsParseObjectTypeMembers() { + this.expect(5); + const members = this.tsParseList("TypeMembers", this.tsParseTypeMember.bind(this)); + this.expect(8); + return members; + } + tsIsStartOfMappedType() { + this.next(); + if (this.eat(53)) { + return this.isContextual(122); + } + if (this.isContextual(122)) { + this.next(); + } + if (!this.match(0)) { + return false; + } + this.next(); + if (!this.tsIsIdentifier()) { + return false; + } + this.next(); + return this.match(58); + } + tsParseMappedType() { + const node = this.startNode(); + this.expect(5); + if (this.match(53)) { + node.readonly = this.state.value; + this.next(); + this.expectContextual(122); + } else if (this.eatContextual(122)) { + node.readonly = true; + } + this.expect(0); + { + const typeParameter = this.startNode(); + typeParameter.name = this.tsParseTypeParameterName(); + typeParameter.constraint = this.tsExpectThenParseType(58); + node.typeParameter = this.finishNode(typeParameter, "TSTypeParameter"); + } + node.nameType = this.eatContextual(93) ? this.tsParseType() : null; + this.expect(3); + if (this.match(53)) { + node.optional = this.state.value; + this.next(); + this.expect(17); + } else if (this.eat(17)) { + node.optional = true; + } + node.typeAnnotation = this.tsTryParseType(); + this.semicolon(); + this.expect(8); + return this.finishNode(node, "TSMappedType"); + } + tsParseTupleType() { + const node = this.startNode(); + node.elementTypes = this.tsParseBracketedList("TupleElementTypes", this.tsParseTupleElementType.bind(this), true, false); + let seenOptionalElement = false; + node.elementTypes.forEach(elementNode => { + const { + type + } = elementNode; + if (seenOptionalElement && type !== "TSRestType" && type !== "TSOptionalType" && !(type === "TSNamedTupleMember" && elementNode.optional)) { + this.raise(TSErrors.OptionalTypeBeforeRequired, elementNode); + } + seenOptionalElement || (seenOptionalElement = type === "TSNamedTupleMember" && elementNode.optional || type === "TSOptionalType"); + }); + return this.finishNode(node, "TSTupleType"); + } + tsParseTupleElementType() { + const { + startLoc + } = this.state; + const rest = this.eat(21); + let labeled; + let label; + let optional; + let type; + const isWord = tokenIsKeywordOrIdentifier(this.state.type); + const chAfterWord = isWord ? this.lookaheadCharCode() : null; + if (chAfterWord === 58) { + labeled = true; + optional = false; + label = this.parseIdentifier(true); + this.expect(14); + type = this.tsParseType(); + } else if (chAfterWord === 63) { + optional = true; + const startLoc = this.state.startLoc; + const wordName = this.state.value; + const typeOrLabel = this.tsParseNonArrayType(); + if (this.lookaheadCharCode() === 58) { + labeled = true; + label = this.createIdentifier(this.startNodeAt(startLoc), wordName); + this.expect(17); + this.expect(14); + type = this.tsParseType(); + } else { + labeled = false; + type = typeOrLabel; + this.expect(17); + } + } else { + type = this.tsParseType(); + optional = this.eat(17); + labeled = this.eat(14); + } + if (labeled) { + let labeledNode; + if (label) { + labeledNode = this.startNodeAtNode(label); + labeledNode.optional = optional; + labeledNode.label = label; + labeledNode.elementType = type; + if (this.eat(17)) { + labeledNode.optional = true; + this.raise(TSErrors.TupleOptionalAfterType, this.state.lastTokStartLoc); + } + } else { + labeledNode = this.startNodeAtNode(type); + labeledNode.optional = optional; + this.raise(TSErrors.InvalidTupleMemberLabel, type); + labeledNode.label = type; + labeledNode.elementType = this.tsParseType(); + } + type = this.finishNode(labeledNode, "TSNamedTupleMember"); + } else if (optional) { + const optionalTypeNode = this.startNodeAtNode(type); + optionalTypeNode.typeAnnotation = type; + type = this.finishNode(optionalTypeNode, "TSOptionalType"); + } + if (rest) { + const restNode = this.startNodeAt(startLoc); + restNode.typeAnnotation = type; + type = this.finishNode(restNode, "TSRestType"); + } + return type; + } + tsParseParenthesizedType() { + const node = this.startNode(); + this.expect(10); + node.typeAnnotation = this.tsParseType(); + this.expect(11); + return this.finishNode(node, "TSParenthesizedType"); + } + tsParseFunctionOrConstructorType(type, abstract) { + const node = this.startNode(); + if (type === "TSConstructorType") { + node.abstract = !!abstract; + if (abstract) this.next(); + this.next(); + } + this.tsInAllowConditionalTypesContext(() => this.tsFillSignature(19, node)); + return this.finishNode(node, type); + } + tsParseLiteralTypeNode() { + const node = this.startNode(); + switch (this.state.type) { + case 134: + case 135: + case 133: + case 85: + case 86: + node.literal = super.parseExprAtom(); + break; + default: + this.unexpected(); + } + return this.finishNode(node, "TSLiteralType"); + } + tsParseTemplateLiteralType() { + const node = this.startNode(); + node.literal = super.parseTemplate(false); + return this.finishNode(node, "TSLiteralType"); + } + parseTemplateSubstitution() { + if (this.state.inType) return this.tsParseType(); + return super.parseTemplateSubstitution(); + } + tsParseThisTypeOrThisTypePredicate() { + const thisKeyword = this.tsParseThisTypeNode(); + if (this.isContextual(116) && !this.hasPrecedingLineBreak()) { + return this.tsParseThisTypePredicate(thisKeyword); + } else { + return thisKeyword; + } + } + tsParseNonArrayType() { + switch (this.state.type) { + case 133: + case 134: + case 135: + case 85: + case 86: + return this.tsParseLiteralTypeNode(); + case 53: + if (this.state.value === "-") { + const node = this.startNode(); + const nextToken = this.lookahead(); + if (nextToken.type !== 134 && nextToken.type !== 135) { + this.unexpected(); + } + node.literal = this.parseMaybeUnary(); + return this.finishNode(node, "TSLiteralType"); + } + break; + case 78: + return this.tsParseThisTypeOrThisTypePredicate(); + case 87: + return this.tsParseTypeQuery(); + case 83: + return this.tsParseImportType(); + case 5: + return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this)) ? this.tsParseMappedType() : this.tsParseTypeLiteral(); + case 0: + return this.tsParseTupleType(); + case 10: + return this.tsParseParenthesizedType(); + case 25: + case 24: + return this.tsParseTemplateLiteralType(); + default: + { + const { + type + } = this.state; + if (tokenIsIdentifier(type) || type === 88 || type === 84) { + const nodeType = type === 88 ? "TSVoidKeyword" : type === 84 ? "TSNullKeyword" : keywordTypeFromName(this.state.value); + if (nodeType !== undefined && this.lookaheadCharCode() !== 46) { + const node = this.startNode(); + this.next(); + return this.finishNode(node, nodeType); + } + return this.tsParseTypeReference(); + } + } + } + this.unexpected(); + } + tsParseArrayTypeOrHigher() { + let type = this.tsParseNonArrayType(); + while (!this.hasPrecedingLineBreak() && this.eat(0)) { + if (this.match(3)) { + const node = this.startNodeAtNode(type); + node.elementType = type; + this.expect(3); + type = this.finishNode(node, "TSArrayType"); + } else { + const node = this.startNodeAtNode(type); + node.objectType = type; + node.indexType = this.tsParseType(); + this.expect(3); + type = this.finishNode(node, "TSIndexedAccessType"); + } + } + return type; + } + tsParseTypeOperator() { + const node = this.startNode(); + const operator = this.state.value; + this.next(); + node.operator = operator; + node.typeAnnotation = this.tsParseTypeOperatorOrHigher(); + if (operator === "readonly") { + this.tsCheckTypeAnnotationForReadOnly(node); + } + return this.finishNode(node, "TSTypeOperator"); + } + tsCheckTypeAnnotationForReadOnly(node) { + switch (node.typeAnnotation.type) { + case "TSTupleType": + case "TSArrayType": + return; + default: + this.raise(TSErrors.UnexpectedReadonly, node); + } + } + tsParseInferType() { + const node = this.startNode(); + this.expectContextual(115); + const typeParameter = this.startNode(); + typeParameter.name = this.tsParseTypeParameterName(); + typeParameter.constraint = this.tsTryParse(() => this.tsParseConstraintForInferType()); + node.typeParameter = this.finishNode(typeParameter, "TSTypeParameter"); + return this.finishNode(node, "TSInferType"); + } + tsParseConstraintForInferType() { + if (this.eat(81)) { + const constraint = this.tsInDisallowConditionalTypesContext(() => this.tsParseType()); + if (this.state.inDisallowConditionalTypesContext || !this.match(17)) { + return constraint; + } + } + } + tsParseTypeOperatorOrHigher() { + const isTypeOperator = tokenIsTSTypeOperator(this.state.type) && !this.state.containsEsc; + return isTypeOperator ? this.tsParseTypeOperator() : this.isContextual(115) ? this.tsParseInferType() : this.tsInAllowConditionalTypesContext(() => this.tsParseArrayTypeOrHigher()); + } + tsParseUnionOrIntersectionType(kind, parseConstituentType, operator) { + const node = this.startNode(); + const hasLeadingOperator = this.eat(operator); + const types = []; + do { + types.push(parseConstituentType()); + } while (this.eat(operator)); + if (types.length === 1 && !hasLeadingOperator) { + return types[0]; + } + node.types = types; + return this.finishNode(node, kind); + } + tsParseIntersectionTypeOrHigher() { + return this.tsParseUnionOrIntersectionType("TSIntersectionType", this.tsParseTypeOperatorOrHigher.bind(this), 45); + } + tsParseUnionTypeOrHigher() { + return this.tsParseUnionOrIntersectionType("TSUnionType", this.tsParseIntersectionTypeOrHigher.bind(this), 43); + } + tsIsStartOfFunctionType() { + if (this.match(47)) { + return true; + } + return this.match(10) && this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this)); + } + tsSkipParameterStart() { + if (tokenIsIdentifier(this.state.type) || this.match(78)) { + this.next(); + return true; + } + if (this.match(5)) { + const { + errors + } = this.state; + const previousErrorCount = errors.length; + try { + this.parseObjectLike(8, true); + return errors.length === previousErrorCount; + } catch (_unused) { + return false; + } + } + if (this.match(0)) { + this.next(); + const { + errors + } = this.state; + const previousErrorCount = errors.length; + try { + super.parseBindingList(3, 93, 1); + return errors.length === previousErrorCount; + } catch (_unused2) { + return false; + } + } + return false; + } + tsIsUnambiguouslyStartOfFunctionType() { + this.next(); + if (this.match(11) || this.match(21)) { + return true; + } + if (this.tsSkipParameterStart()) { + if (this.match(14) || this.match(12) || this.match(17) || this.match(29)) { + return true; + } + if (this.match(11)) { + this.next(); + if (this.match(19)) { + return true; + } + } + } + return false; + } + tsParseTypeOrTypePredicateAnnotation(returnToken) { + return this.tsInType(() => { + const t = this.startNode(); + this.expect(returnToken); + const node = this.startNode(); + const asserts = !!this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this)); + if (asserts && this.match(78)) { + let thisTypePredicate = this.tsParseThisTypeOrThisTypePredicate(); + if (thisTypePredicate.type === "TSThisType") { + node.parameterName = thisTypePredicate; + node.asserts = true; + node.typeAnnotation = null; + thisTypePredicate = this.finishNode(node, "TSTypePredicate"); + } else { + this.resetStartLocationFromNode(thisTypePredicate, node); + thisTypePredicate.asserts = true; + } + t.typeAnnotation = thisTypePredicate; + return this.finishNode(t, "TSTypeAnnotation"); + } + const typePredicateVariable = this.tsIsIdentifier() && this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this)); + if (!typePredicateVariable) { + if (!asserts) { + return this.tsParseTypeAnnotation(false, t); + } + node.parameterName = this.parseIdentifier(); + node.asserts = asserts; + node.typeAnnotation = null; + t.typeAnnotation = this.finishNode(node, "TSTypePredicate"); + return this.finishNode(t, "TSTypeAnnotation"); + } + const type = this.tsParseTypeAnnotation(false); + node.parameterName = typePredicateVariable; + node.typeAnnotation = type; + node.asserts = asserts; + t.typeAnnotation = this.finishNode(node, "TSTypePredicate"); + return this.finishNode(t, "TSTypeAnnotation"); + }); + } + tsTryParseTypeOrTypePredicateAnnotation() { + if (this.match(14)) { + return this.tsParseTypeOrTypePredicateAnnotation(14); + } + } + tsTryParseTypeAnnotation() { + if (this.match(14)) { + return this.tsParseTypeAnnotation(); + } + } + tsTryParseType() { + return this.tsEatThenParseType(14); + } + tsParseTypePredicatePrefix() { + const id = this.parseIdentifier(); + if (this.isContextual(116) && !this.hasPrecedingLineBreak()) { + this.next(); + return id; + } + } + tsParseTypePredicateAsserts() { + if (this.state.type !== 109) { + return false; + } + const containsEsc = this.state.containsEsc; + this.next(); + if (!tokenIsIdentifier(this.state.type) && !this.match(78)) { + return false; + } + if (containsEsc) { + this.raise(Errors.InvalidEscapedReservedWord, this.state.lastTokStartLoc, { + reservedWord: "asserts" + }); + } + return true; + } + tsParseTypeAnnotation(eatColon = true, t = this.startNode()) { + this.tsInType(() => { + if (eatColon) this.expect(14); + t.typeAnnotation = this.tsParseType(); + }); + return this.finishNode(t, "TSTypeAnnotation"); + } + tsParseType() { + assert(this.state.inType); + const type = this.tsParseNonConditionalType(); + if (this.state.inDisallowConditionalTypesContext || this.hasPrecedingLineBreak() || !this.eat(81)) { + return type; + } + const node = this.startNodeAtNode(type); + node.checkType = type; + node.extendsType = this.tsInDisallowConditionalTypesContext(() => this.tsParseNonConditionalType()); + this.expect(17); + node.trueType = this.tsInAllowConditionalTypesContext(() => this.tsParseType()); + this.expect(14); + node.falseType = this.tsInAllowConditionalTypesContext(() => this.tsParseType()); + return this.finishNode(node, "TSConditionalType"); + } + isAbstractConstructorSignature() { + return this.isContextual(124) && this.lookahead().type === 77; + } + tsParseNonConditionalType() { + if (this.tsIsStartOfFunctionType()) { + return this.tsParseFunctionOrConstructorType("TSFunctionType"); + } + if (this.match(77)) { + return this.tsParseFunctionOrConstructorType("TSConstructorType"); + } else if (this.isAbstractConstructorSignature()) { + return this.tsParseFunctionOrConstructorType("TSConstructorType", true); + } + return this.tsParseUnionTypeOrHigher(); + } + tsParseTypeAssertion() { + if (this.getPluginOption("typescript", "disallowAmbiguousJSXLike")) { + this.raise(TSErrors.ReservedTypeAssertion, this.state.startLoc); + } + const node = this.startNode(); + node.typeAnnotation = this.tsInType(() => { + this.next(); + return this.match(75) ? this.tsParseTypeReference() : this.tsParseType(); + }); + this.expect(48); + node.expression = this.parseMaybeUnary(); + return this.finishNode(node, "TSTypeAssertion"); + } + tsParseHeritageClause(token) { + const originalStartLoc = this.state.startLoc; + const delimitedList = this.tsParseDelimitedList("HeritageClauseElement", () => { + const node = this.startNode(); + node.expression = this.tsParseEntityName(); + if (this.match(47)) { + node.typeParameters = this.tsParseTypeArguments(); + } + return this.finishNode(node, "TSExpressionWithTypeArguments"); + }); + if (!delimitedList.length) { + this.raise(TSErrors.EmptyHeritageClauseType, originalStartLoc, { + token + }); + } + return delimitedList; + } + tsParseInterfaceDeclaration(node, properties = {}) { + if (this.hasFollowingLineBreak()) return null; + this.expectContextual(129); + if (properties.declare) node.declare = true; + if (tokenIsIdentifier(this.state.type)) { + node.id = this.parseIdentifier(); + this.checkIdentifier(node.id, 130); + } else { + node.id = null; + this.raise(TSErrors.MissingInterfaceName, this.state.startLoc); + } + node.typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers); + if (this.eat(81)) { + node.extends = this.tsParseHeritageClause("extends"); + } + const body = this.startNode(); + body.body = this.tsInType(this.tsParseObjectTypeMembers.bind(this)); + node.body = this.finishNode(body, "TSInterfaceBody"); + return this.finishNode(node, "TSInterfaceDeclaration"); + } + tsParseTypeAliasDeclaration(node) { + node.id = this.parseIdentifier(); + this.checkIdentifier(node.id, 2); + node.typeAnnotation = this.tsInType(() => { + node.typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutModifiers); + this.expect(29); + if (this.isContextual(114) && this.lookahead().type !== 16) { + const node = this.startNode(); + this.next(); + return this.finishNode(node, "TSIntrinsicKeyword"); + } + return this.tsParseType(); + }); + this.semicolon(); + return this.finishNode(node, "TSTypeAliasDeclaration"); + } + tsInNoContext(cb) { + const oldContext = this.state.context; + this.state.context = [oldContext[0]]; + try { + return cb(); + } finally { + this.state.context = oldContext; + } + } + tsInType(cb) { + const oldInType = this.state.inType; + this.state.inType = true; + try { + return cb(); + } finally { + this.state.inType = oldInType; + } + } + tsInDisallowConditionalTypesContext(cb) { + const oldInDisallowConditionalTypesContext = this.state.inDisallowConditionalTypesContext; + this.state.inDisallowConditionalTypesContext = true; + try { + return cb(); + } finally { + this.state.inDisallowConditionalTypesContext = oldInDisallowConditionalTypesContext; + } + } + tsInAllowConditionalTypesContext(cb) { + const oldInDisallowConditionalTypesContext = this.state.inDisallowConditionalTypesContext; + this.state.inDisallowConditionalTypesContext = false; + try { + return cb(); + } finally { + this.state.inDisallowConditionalTypesContext = oldInDisallowConditionalTypesContext; + } + } + tsEatThenParseType(token) { + if (this.match(token)) { + return this.tsNextThenParseType(); + } + } + tsExpectThenParseType(token) { + return this.tsInType(() => { + this.expect(token); + return this.tsParseType(); + }); + } + tsNextThenParseType() { + return this.tsInType(() => { + this.next(); + return this.tsParseType(); + }); + } + tsParseEnumMember() { + const node = this.startNode(); + node.id = this.match(133) ? super.parseStringLiteral(this.state.value) : this.parseIdentifier(true); + if (this.eat(29)) { + node.initializer = super.parseMaybeAssignAllowIn(); + } + return this.finishNode(node, "TSEnumMember"); + } + tsParseEnumDeclaration(node, properties = {}) { + if (properties.const) node.const = true; + if (properties.declare) node.declare = true; + this.expectContextual(126); + node.id = this.parseIdentifier(); + this.checkIdentifier(node.id, node.const ? 8971 : 8459); + this.expect(5); + node.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this)); + this.expect(8); + return this.finishNode(node, "TSEnumDeclaration"); + } + tsParseModuleBlock() { + const node = this.startNode(); + this.scope.enter(0); + this.expect(5); + super.parseBlockOrModuleBlockBody(node.body = [], undefined, true, 8); + this.scope.exit(); + return this.finishNode(node, "TSModuleBlock"); + } + tsParseModuleOrNamespaceDeclaration(node, nested = false) { + node.id = this.parseIdentifier(); + if (!nested) { + this.checkIdentifier(node.id, 1024); + } + if (this.eat(16)) { + const inner = this.startNode(); + this.tsParseModuleOrNamespaceDeclaration(inner, true); + node.body = inner; + } else { + this.scope.enter(256); + this.prodParam.enter(0); + node.body = this.tsParseModuleBlock(); + this.prodParam.exit(); + this.scope.exit(); + } + return this.finishNode(node, "TSModuleDeclaration"); + } + tsParseAmbientExternalModuleDeclaration(node) { + if (this.isContextual(112)) { + node.global = true; + node.id = this.parseIdentifier(); + } else if (this.match(133)) { + node.id = super.parseStringLiteral(this.state.value); + } else { + this.unexpected(); + } + if (this.match(5)) { + this.scope.enter(256); + this.prodParam.enter(0); + node.body = this.tsParseModuleBlock(); + this.prodParam.exit(); + this.scope.exit(); + } else { + this.semicolon(); + } + return this.finishNode(node, "TSModuleDeclaration"); + } + tsParseImportEqualsDeclaration(node, maybeDefaultIdentifier, isExport) { + node.isExport = isExport || false; + node.id = maybeDefaultIdentifier || this.parseIdentifier(); + this.checkIdentifier(node.id, 4096); + this.expect(29); + const moduleReference = this.tsParseModuleReference(); + if (node.importKind === "type" && moduleReference.type !== "TSExternalModuleReference") { + this.raise(TSErrors.ImportAliasHasImportType, moduleReference); + } + node.moduleReference = moduleReference; + this.semicolon(); + return this.finishNode(node, "TSImportEqualsDeclaration"); + } + tsIsExternalModuleReference() { + return this.isContextual(119) && this.lookaheadCharCode() === 40; + } + tsParseModuleReference() { + return this.tsIsExternalModuleReference() ? this.tsParseExternalModuleReference() : this.tsParseEntityName(false); + } + tsParseExternalModuleReference() { + const node = this.startNode(); + this.expectContextual(119); + this.expect(10); + if (!this.match(133)) { + this.unexpected(); + } + node.expression = super.parseExprAtom(); + this.expect(11); + this.sawUnambiguousESM = true; + return this.finishNode(node, "TSExternalModuleReference"); + } + tsLookAhead(f) { + const state = this.state.clone(); + const res = f(); + this.state = state; + return res; + } + tsTryParseAndCatch(f) { + const result = this.tryParse(abort => f() || abort()); + if (result.aborted || !result.node) return; + if (result.error) this.state = result.failState; + return result.node; + } + tsTryParse(f) { + const state = this.state.clone(); + const result = f(); + if (result !== undefined && result !== false) { + return result; + } + this.state = state; + } + tsTryParseDeclare(nany) { + if (this.isLineTerminator()) { + return; + } + let startType = this.state.type; + let kind; + if (this.isContextual(100)) { + startType = 74; + kind = "let"; + } + return this.tsInAmbientContext(() => { + switch (startType) { + case 68: + nany.declare = true; + return super.parseFunctionStatement(nany, false, false); + case 80: + nany.declare = true; + return this.parseClass(nany, true, false); + case 126: + return this.tsParseEnumDeclaration(nany, { + declare: true + }); + case 112: + return this.tsParseAmbientExternalModuleDeclaration(nany); + case 75: + case 74: + if (!this.match(75) || !this.isLookaheadContextual("enum")) { + nany.declare = true; + return this.parseVarStatement(nany, kind || this.state.value, true); + } + this.expect(75); + return this.tsParseEnumDeclaration(nany, { + const: true, + declare: true + }); + case 129: + { + const result = this.tsParseInterfaceDeclaration(nany, { + declare: true + }); + if (result) return result; + } + default: + if (tokenIsIdentifier(startType)) { + return this.tsParseDeclaration(nany, this.state.value, true, null); + } + } + }); + } + tsTryParseExportDeclaration() { + return this.tsParseDeclaration(this.startNode(), this.state.value, true, null); + } + tsParseExpressionStatement(node, expr, decorators) { + switch (expr.name) { + case "declare": + { + const declaration = this.tsTryParseDeclare(node); + if (declaration) { + declaration.declare = true; + } + return declaration; + } + case "global": + if (this.match(5)) { + this.scope.enter(256); + this.prodParam.enter(0); + const mod = node; + mod.global = true; + mod.id = expr; + mod.body = this.tsParseModuleBlock(); + this.scope.exit(); + this.prodParam.exit(); + return this.finishNode(mod, "TSModuleDeclaration"); + } + break; + default: + return this.tsParseDeclaration(node, expr.name, false, decorators); + } + } + tsParseDeclaration(node, value, next, decorators) { + switch (value) { + case "abstract": + if (this.tsCheckLineTerminator(next) && (this.match(80) || tokenIsIdentifier(this.state.type))) { + return this.tsParseAbstractDeclaration(node, decorators); + } + break; + case "module": + if (this.tsCheckLineTerminator(next)) { + if (this.match(133)) { + return this.tsParseAmbientExternalModuleDeclaration(node); + } else if (tokenIsIdentifier(this.state.type)) { + return this.tsParseModuleOrNamespaceDeclaration(node); + } + } + break; + case "namespace": + if (this.tsCheckLineTerminator(next) && tokenIsIdentifier(this.state.type)) { + return this.tsParseModuleOrNamespaceDeclaration(node); + } + break; + case "type": + if (this.tsCheckLineTerminator(next) && tokenIsIdentifier(this.state.type)) { + return this.tsParseTypeAliasDeclaration(node); + } + break; + } + } + tsCheckLineTerminator(next) { + if (next) { + if (this.hasFollowingLineBreak()) return false; + this.next(); + return true; + } + return !this.isLineTerminator(); + } + tsTryParseGenericAsyncArrowFunction(startLoc) { + if (!this.match(47)) return; + const oldMaybeInArrowParameters = this.state.maybeInArrowParameters; + this.state.maybeInArrowParameters = true; + const res = this.tsTryParseAndCatch(() => { + const node = this.startNodeAt(startLoc); + node.typeParameters = this.tsParseTypeParameters(this.tsParseConstModifier); + super.parseFunctionParams(node); + node.returnType = this.tsTryParseTypeOrTypePredicateAnnotation(); + this.expect(19); + return node; + }); + this.state.maybeInArrowParameters = oldMaybeInArrowParameters; + if (!res) return; + return super.parseArrowExpression(res, null, true); + } + tsParseTypeArgumentsInExpression() { + if (this.reScan_lt() !== 47) return; + return this.tsParseTypeArguments(); + } + tsParseTypeArguments() { + const node = this.startNode(); + node.params = this.tsInType(() => this.tsInNoContext(() => { + this.expect(47); + return this.tsParseDelimitedList("TypeParametersOrArguments", this.tsParseType.bind(this)); + })); + if (node.params.length === 0) { + this.raise(TSErrors.EmptyTypeArguments, node); + } else if (!this.state.inType && this.curContext() === types.brace) { + this.reScan_lt_gt(); + } + this.expect(48); + return this.finishNode(node, "TSTypeParameterInstantiation"); + } + tsIsDeclarationStart() { + return tokenIsTSDeclarationStart(this.state.type); + } + isExportDefaultSpecifier() { + if (this.tsIsDeclarationStart()) return false; + return super.isExportDefaultSpecifier(); + } + parseAssignableListItem(flags, decorators) { + const startLoc = this.state.startLoc; + const modified = {}; + this.tsParseModifiers({ + allowedModifiers: ["public", "private", "protected", "override", "readonly"] + }, modified); + const accessibility = modified.accessibility; + const override = modified.override; + const readonly = modified.readonly; + if (!(flags & 4) && (accessibility || readonly || override)) { + this.raise(TSErrors.UnexpectedParameterModifier, startLoc); + } + const left = this.parseMaybeDefault(); + this.parseAssignableListItemTypes(left, flags); + const elt = this.parseMaybeDefault(left.loc.start, left); + if (accessibility || readonly || override) { + const pp = this.startNodeAt(startLoc); + if (decorators.length) { + pp.decorators = decorators; + } + if (accessibility) pp.accessibility = accessibility; + if (readonly) pp.readonly = readonly; + if (override) pp.override = override; + if (elt.type !== "Identifier" && elt.type !== "AssignmentPattern") { + this.raise(TSErrors.UnsupportedParameterPropertyKind, pp); + } + pp.parameter = elt; + return this.finishNode(pp, "TSParameterProperty"); + } + if (decorators.length) { + left.decorators = decorators; + } + return elt; + } + isSimpleParameter(node) { + return node.type === "TSParameterProperty" && super.isSimpleParameter(node.parameter) || super.isSimpleParameter(node); + } + tsDisallowOptionalPattern(node) { + for (const param of node.params) { + if (param.type !== "Identifier" && param.optional && !this.state.isAmbientContext) { + this.raise(TSErrors.PatternIsOptional, param); + } + } + } + setArrowFunctionParameters(node, params, trailingCommaLoc) { + super.setArrowFunctionParameters(node, params, trailingCommaLoc); + this.tsDisallowOptionalPattern(node); + } + parseFunctionBodyAndFinish(node, type, isMethod = false) { + if (this.match(14)) { + node.returnType = this.tsParseTypeOrTypePredicateAnnotation(14); + } + const bodilessType = type === "FunctionDeclaration" ? "TSDeclareFunction" : type === "ClassMethod" || type === "ClassPrivateMethod" ? "TSDeclareMethod" : undefined; + if (bodilessType && !this.match(5) && this.isLineTerminator()) { + return this.finishNode(node, bodilessType); + } + if (bodilessType === "TSDeclareFunction" && this.state.isAmbientContext) { + this.raise(TSErrors.DeclareFunctionHasImplementation, node); + if (node.declare) { + return super.parseFunctionBodyAndFinish(node, bodilessType, isMethod); + } + } + this.tsDisallowOptionalPattern(node); + return super.parseFunctionBodyAndFinish(node, type, isMethod); + } + registerFunctionStatementId(node) { + if (!node.body && node.id) { + this.checkIdentifier(node.id, 1024); + } else { + super.registerFunctionStatementId(node); + } + } + tsCheckForInvalidTypeCasts(items) { + items.forEach(node => { + if ((node == null ? void 0 : node.type) === "TSTypeCastExpression") { + this.raise(TSErrors.UnexpectedTypeAnnotation, node.typeAnnotation); + } + }); + } + toReferencedList(exprList, isInParens) { + this.tsCheckForInvalidTypeCasts(exprList); + return exprList; + } + parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) { + const node = super.parseArrayLike(close, canBePattern, isTuple, refExpressionErrors); + if (node.type === "ArrayExpression") { + this.tsCheckForInvalidTypeCasts(node.elements); + } + return node; + } + parseSubscript(base, startLoc, noCalls, state) { + if (!this.hasPrecedingLineBreak() && this.match(35)) { + this.state.canStartJSXElement = false; + this.next(); + const nonNullExpression = this.startNodeAt(startLoc); + nonNullExpression.expression = base; + return this.finishNode(nonNullExpression, "TSNonNullExpression"); + } + let isOptionalCall = false; + if (this.match(18) && this.lookaheadCharCode() === 60) { + if (noCalls) { + state.stop = true; + return base; + } + state.optionalChainMember = isOptionalCall = true; + this.next(); + } + if (this.match(47) || this.match(51)) { + let missingParenErrorLoc; + const result = this.tsTryParseAndCatch(() => { + if (!noCalls && this.atPossibleAsyncArrow(base)) { + const asyncArrowFn = this.tsTryParseGenericAsyncArrowFunction(startLoc); + if (asyncArrowFn) { + return asyncArrowFn; + } + } + const typeArguments = this.tsParseTypeArgumentsInExpression(); + if (!typeArguments) return; + if (isOptionalCall && !this.match(10)) { + missingParenErrorLoc = this.state.curPosition(); + return; + } + if (tokenIsTemplate(this.state.type)) { + const result = super.parseTaggedTemplateExpression(base, startLoc, state); + result.typeParameters = typeArguments; + return result; + } + if (!noCalls && this.eat(10)) { + const node = this.startNodeAt(startLoc); + node.callee = base; + node.arguments = this.parseCallExpressionArguments(11, false); + this.tsCheckForInvalidTypeCasts(node.arguments); + node.typeParameters = typeArguments; + if (state.optionalChainMember) { + node.optional = isOptionalCall; + } + return this.finishCallExpression(node, state.optionalChainMember); + } + const tokenType = this.state.type; + if (tokenType === 48 || tokenType === 52 || tokenType !== 10 && tokenCanStartExpression(tokenType) && !this.hasPrecedingLineBreak()) { + return; + } + const node = this.startNodeAt(startLoc); + node.expression = base; + node.typeParameters = typeArguments; + return this.finishNode(node, "TSInstantiationExpression"); + }); + if (missingParenErrorLoc) { + this.unexpected(missingParenErrorLoc, 10); + } + if (result) { + if (result.type === "TSInstantiationExpression" && (this.match(16) || this.match(18) && this.lookaheadCharCode() !== 40)) { + this.raise(TSErrors.InvalidPropertyAccessAfterInstantiationExpression, this.state.startLoc); + } + return result; + } + } + return super.parseSubscript(base, startLoc, noCalls, state); + } + parseNewCallee(node) { + var _callee$extra; + super.parseNewCallee(node); + const { + callee + } = node; + if (callee.type === "TSInstantiationExpression" && !((_callee$extra = callee.extra) != null && _callee$extra.parenthesized)) { + node.typeParameters = callee.typeParameters; + node.callee = callee.expression; + } + } + parseExprOp(left, leftStartLoc, minPrec) { + let isSatisfies; + if (tokenOperatorPrecedence(58) > minPrec && !this.hasPrecedingLineBreak() && (this.isContextual(93) || (isSatisfies = this.isContextual(120)))) { + const node = this.startNodeAt(leftStartLoc); + node.expression = left; + node.typeAnnotation = this.tsInType(() => { + this.next(); + if (this.match(75)) { + if (isSatisfies) { + this.raise(Errors.UnexpectedKeyword, this.state.startLoc, { + keyword: "const" + }); + } + return this.tsParseTypeReference(); + } + return this.tsParseType(); + }); + this.finishNode(node, isSatisfies ? "TSSatisfiesExpression" : "TSAsExpression"); + this.reScan_lt_gt(); + return this.parseExprOp(node, leftStartLoc, minPrec); + } + return super.parseExprOp(left, leftStartLoc, minPrec); + } + checkReservedWord(word, startLoc, checkKeywords, isBinding) { + if (!this.state.isAmbientContext) { + super.checkReservedWord(word, startLoc, checkKeywords, isBinding); + } + } + checkImportReflection(node) { + super.checkImportReflection(node); + if (node.module && node.importKind !== "value") { + this.raise(TSErrors.ImportReflectionHasImportType, node.specifiers[0].loc.start); + } + } + checkDuplicateExports() {} + isPotentialImportPhase(isExport) { + if (super.isPotentialImportPhase(isExport)) return true; + if (this.isContextual(130)) { + const ch = this.lookaheadCharCode(); + return isExport ? ch === 123 || ch === 42 : ch !== 61; + } + return !isExport && this.isContextual(87); + } + applyImportPhase(node, isExport, phase, loc) { + super.applyImportPhase(node, isExport, phase, loc); + if (isExport) { + node.exportKind = phase === "type" ? "type" : "value"; + } else { + node.importKind = phase === "type" || phase === "typeof" ? phase : "value"; + } + } + parseImport(node) { + if (this.match(133)) { + node.importKind = "value"; + return super.parseImport(node); + } + let importNode; + if (tokenIsIdentifier(this.state.type) && this.lookaheadCharCode() === 61) { + node.importKind = "value"; + return this.tsParseImportEqualsDeclaration(node); + } else if (this.isContextual(130)) { + const maybeDefaultIdentifier = this.parseMaybeImportPhase(node, false); + if (this.lookaheadCharCode() === 61) { + return this.tsParseImportEqualsDeclaration(node, maybeDefaultIdentifier); + } else { + importNode = super.parseImportSpecifiersAndAfter(node, maybeDefaultIdentifier); + } + } else { + importNode = super.parseImport(node); + } + if (importNode.importKind === "type" && importNode.specifiers.length > 1 && importNode.specifiers[0].type === "ImportDefaultSpecifier") { + this.raise(TSErrors.TypeImportCannotSpecifyDefaultAndNamed, importNode); + } + return importNode; + } + parseExport(node, decorators) { + if (this.match(83)) { + this.next(); + const nodeImportEquals = node; + let maybeDefaultIdentifier = null; + if (this.isContextual(130) && this.isPotentialImportPhase(false)) { + maybeDefaultIdentifier = this.parseMaybeImportPhase(nodeImportEquals, false); + } else { + nodeImportEquals.importKind = "value"; + } + return this.tsParseImportEqualsDeclaration(nodeImportEquals, maybeDefaultIdentifier, true); + } else if (this.eat(29)) { + const assign = node; + assign.expression = super.parseExpression(); + this.semicolon(); + this.sawUnambiguousESM = true; + return this.finishNode(assign, "TSExportAssignment"); + } else if (this.eatContextual(93)) { + const decl = node; + this.expectContextual(128); + decl.id = this.parseIdentifier(); + this.semicolon(); + return this.finishNode(decl, "TSNamespaceExportDeclaration"); + } else { + return super.parseExport(node, decorators); + } + } + isAbstractClass() { + return this.isContextual(124) && this.lookahead().type === 80; + } + parseExportDefaultExpression() { + if (this.isAbstractClass()) { + const cls = this.startNode(); + this.next(); + cls.abstract = true; + return this.parseClass(cls, true, true); + } + if (this.match(129)) { + const result = this.tsParseInterfaceDeclaration(this.startNode()); + if (result) return result; + } + return super.parseExportDefaultExpression(); + } + parseVarStatement(node, kind, allowMissingInitializer = false) { + const { + isAmbientContext + } = this.state; + const declaration = super.parseVarStatement(node, kind, allowMissingInitializer || isAmbientContext); + if (!isAmbientContext) return declaration; + for (const { + id, + init + } of declaration.declarations) { + if (!init) continue; + if (kind !== "const" || !!id.typeAnnotation) { + this.raise(TSErrors.InitializerNotAllowedInAmbientContext, init); + } else if (!isValidAmbientConstInitializer(init, this.hasPlugin("estree"))) { + this.raise(TSErrors.ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference, init); + } + } + return declaration; + } + parseStatementContent(flags, decorators) { + if (this.match(75) && this.isLookaheadContextual("enum")) { + const node = this.startNode(); + this.expect(75); + return this.tsParseEnumDeclaration(node, { + const: true + }); + } + if (this.isContextual(126)) { + return this.tsParseEnumDeclaration(this.startNode()); + } + if (this.isContextual(129)) { + const result = this.tsParseInterfaceDeclaration(this.startNode()); + if (result) return result; + } + return super.parseStatementContent(flags, decorators); + } + parseAccessModifier() { + return this.tsParseModifier(["public", "protected", "private"]); + } + tsHasSomeModifiers(member, modifiers) { + return modifiers.some(modifier => { + if (tsIsAccessModifier(modifier)) { + return member.accessibility === modifier; + } + return !!member[modifier]; + }); + } + tsIsStartOfStaticBlocks() { + return this.isContextual(106) && this.lookaheadCharCode() === 123; + } + parseClassMember(classBody, member, state) { + const modifiers = ["declare", "private", "public", "protected", "override", "abstract", "readonly", "static"]; + this.tsParseModifiers({ + allowedModifiers: modifiers, + disallowedModifiers: ["in", "out"], + stopOnStartOfClassStaticBlock: true, + errorTemplate: TSErrors.InvalidModifierOnTypeParameterPositions + }, member); + const callParseClassMemberWithIsStatic = () => { + if (this.tsIsStartOfStaticBlocks()) { + this.next(); + this.next(); + if (this.tsHasSomeModifiers(member, modifiers)) { + this.raise(TSErrors.StaticBlockCannotHaveModifier, this.state.curPosition()); + } + super.parseClassStaticBlock(classBody, member); + } else { + this.parseClassMemberWithIsStatic(classBody, member, state, !!member.static); + } + }; + if (member.declare) { + this.tsInAmbientContext(callParseClassMemberWithIsStatic); + } else { + callParseClassMemberWithIsStatic(); + } + } + parseClassMemberWithIsStatic(classBody, member, state, isStatic) { + const idx = this.tsTryParseIndexSignature(member); + if (idx) { + classBody.body.push(idx); + if (member.abstract) { + this.raise(TSErrors.IndexSignatureHasAbstract, member); + } + if (member.accessibility) { + this.raise(TSErrors.IndexSignatureHasAccessibility, member, { + modifier: member.accessibility + }); + } + if (member.declare) { + this.raise(TSErrors.IndexSignatureHasDeclare, member); + } + if (member.override) { + this.raise(TSErrors.IndexSignatureHasOverride, member); + } + return; + } + if (!this.state.inAbstractClass && member.abstract) { + this.raise(TSErrors.NonAbstractClassHasAbstractMethod, member); + } + if (member.override) { + if (!state.hadSuperClass) { + this.raise(TSErrors.OverrideNotInSubClass, member); + } + } + super.parseClassMemberWithIsStatic(classBody, member, state, isStatic); + } + parsePostMemberNameModifiers(methodOrProp) { + const optional = this.eat(17); + if (optional) methodOrProp.optional = true; + if (methodOrProp.readonly && this.match(10)) { + this.raise(TSErrors.ClassMethodHasReadonly, methodOrProp); + } + if (methodOrProp.declare && this.match(10)) { + this.raise(TSErrors.ClassMethodHasDeclare, methodOrProp); + } + } + parseExpressionStatement(node, expr, decorators) { + const decl = expr.type === "Identifier" ? this.tsParseExpressionStatement(node, expr, decorators) : undefined; + return decl || super.parseExpressionStatement(node, expr, decorators); + } + shouldParseExportDeclaration() { + if (this.tsIsDeclarationStart()) return true; + return super.shouldParseExportDeclaration(); + } + parseConditional(expr, startLoc, refExpressionErrors) { + if (!this.state.maybeInArrowParameters || !this.match(17)) { + return super.parseConditional(expr, startLoc, refExpressionErrors); + } + const result = this.tryParse(() => super.parseConditional(expr, startLoc)); + if (!result.node) { + if (result.error) { + super.setOptionalParametersError(refExpressionErrors, result.error); + } + return expr; + } + if (result.error) this.state = result.failState; + return result.node; + } + parseParenItem(node, startLoc) { + const newNode = super.parseParenItem(node, startLoc); + if (this.eat(17)) { + newNode.optional = true; + this.resetEndLocation(node); + } + if (this.match(14)) { + const typeCastNode = this.startNodeAt(startLoc); + typeCastNode.expression = node; + typeCastNode.typeAnnotation = this.tsParseTypeAnnotation(); + return this.finishNode(typeCastNode, "TSTypeCastExpression"); + } + return node; + } + parseExportDeclaration(node) { + if (!this.state.isAmbientContext && this.isContextual(125)) { + return this.tsInAmbientContext(() => this.parseExportDeclaration(node)); + } + const startLoc = this.state.startLoc; + const isDeclare = this.eatContextual(125); + if (isDeclare && (this.isContextual(125) || !this.shouldParseExportDeclaration())) { + throw this.raise(TSErrors.ExpectedAmbientAfterExportDeclare, this.state.startLoc); + } + const isIdentifier = tokenIsIdentifier(this.state.type); + const declaration = isIdentifier && this.tsTryParseExportDeclaration() || super.parseExportDeclaration(node); + if (!declaration) return null; + if (declaration.type === "TSInterfaceDeclaration" || declaration.type === "TSTypeAliasDeclaration" || isDeclare) { + node.exportKind = "type"; + } + if (isDeclare) { + this.resetStartLocation(declaration, startLoc); + declaration.declare = true; + } + return declaration; + } + parseClassId(node, isStatement, optionalId, bindingType) { + if ((!isStatement || optionalId) && this.isContextual(113)) { + return; + } + super.parseClassId(node, isStatement, optionalId, node.declare ? 1024 : 8331); + const typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers); + if (typeParameters) node.typeParameters = typeParameters; + } + parseClassPropertyAnnotation(node) { + if (!node.optional) { + if (this.eat(35)) { + node.definite = true; + } else if (this.eat(17)) { + node.optional = true; + } + } + const type = this.tsTryParseTypeAnnotation(); + if (type) node.typeAnnotation = type; + } + parseClassProperty(node) { + this.parseClassPropertyAnnotation(node); + if (this.state.isAmbientContext && !(node.readonly && !node.typeAnnotation) && this.match(29)) { + this.raise(TSErrors.DeclareClassFieldHasInitializer, this.state.startLoc); + } + if (node.abstract && this.match(29)) { + const { + key + } = node; + this.raise(TSErrors.AbstractPropertyHasInitializer, this.state.startLoc, { + propertyName: key.type === "Identifier" && !node.computed ? key.name : `[${this.input.slice(key.start, key.end)}]` + }); + } + return super.parseClassProperty(node); + } + parseClassPrivateProperty(node) { + if (node.abstract) { + this.raise(TSErrors.PrivateElementHasAbstract, node); + } + if (node.accessibility) { + this.raise(TSErrors.PrivateElementHasAccessibility, node, { + modifier: node.accessibility + }); + } + this.parseClassPropertyAnnotation(node); + return super.parseClassPrivateProperty(node); + } + parseClassAccessorProperty(node) { + this.parseClassPropertyAnnotation(node); + if (node.optional) { + this.raise(TSErrors.AccessorCannotBeOptional, node); + } + return super.parseClassAccessorProperty(node); + } + pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) { + const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier); + if (typeParameters && isConstructor) { + this.raise(TSErrors.ConstructorHasTypeParameters, typeParameters); + } + const { + declare = false, + kind + } = method; + if (declare && (kind === "get" || kind === "set")) { + this.raise(TSErrors.DeclareAccessor, method, { + kind + }); + } + if (typeParameters) method.typeParameters = typeParameters; + super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper); + } + pushClassPrivateMethod(classBody, method, isGenerator, isAsync) { + const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier); + if (typeParameters) method.typeParameters = typeParameters; + super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync); + } + declareClassPrivateMethodInScope(node, kind) { + if (node.type === "TSDeclareMethod") return; + if (node.type === "MethodDefinition" && !hasOwnProperty.call(node.value, "body")) { + return; + } + super.declareClassPrivateMethodInScope(node, kind); + } + parseClassSuper(node) { + super.parseClassSuper(node); + if (node.superClass && (this.match(47) || this.match(51))) { + node.superTypeParameters = this.tsParseTypeArgumentsInExpression(); + } + if (this.eatContextual(113)) { + node.implements = this.tsParseHeritageClause("implements"); + } + } + parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) { + const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier); + if (typeParameters) prop.typeParameters = typeParameters; + return super.parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors); + } + parseFunctionParams(node, isConstructor) { + const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier); + if (typeParameters) node.typeParameters = typeParameters; + super.parseFunctionParams(node, isConstructor); + } + parseVarId(decl, kind) { + super.parseVarId(decl, kind); + if (decl.id.type === "Identifier" && !this.hasPrecedingLineBreak() && this.eat(35)) { + decl.definite = true; + } + const type = this.tsTryParseTypeAnnotation(); + if (type) { + decl.id.typeAnnotation = type; + this.resetEndLocation(decl.id); + } + } + parseAsyncArrowFromCallExpression(node, call) { + if (this.match(14)) { + node.returnType = this.tsParseTypeAnnotation(); + } + return super.parseAsyncArrowFromCallExpression(node, call); + } + parseMaybeAssign(refExpressionErrors, afterLeftParse) { + var _jsx, _jsx2, _typeCast, _jsx3, _typeCast2; + let state; + let jsx; + let typeCast; + if (this.hasPlugin("jsx") && (this.match(142) || this.match(47))) { + state = this.state.clone(); + jsx = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state); + if (!jsx.error) return jsx.node; + const { + context + } = this.state; + const currentContext = context[context.length - 1]; + if (currentContext === types.j_oTag || currentContext === types.j_expr) { + context.pop(); + } + } + if (!((_jsx = jsx) != null && _jsx.error) && !this.match(47)) { + return super.parseMaybeAssign(refExpressionErrors, afterLeftParse); + } + if (!state || state === this.state) state = this.state.clone(); + let typeParameters; + const arrow = this.tryParse(abort => { + var _expr$extra, _typeParameters; + typeParameters = this.tsParseTypeParameters(this.tsParseConstModifier); + const expr = super.parseMaybeAssign(refExpressionErrors, afterLeftParse); + if (expr.type !== "ArrowFunctionExpression" || (_expr$extra = expr.extra) != null && _expr$extra.parenthesized) { + abort(); + } + if (((_typeParameters = typeParameters) == null ? void 0 : _typeParameters.params.length) !== 0) { + this.resetStartLocationFromNode(expr, typeParameters); + } + expr.typeParameters = typeParameters; + return expr; + }, state); + if (!arrow.error && !arrow.aborted) { + if (typeParameters) this.reportReservedArrowTypeParam(typeParameters); + return arrow.node; + } + if (!jsx) { + assert(!this.hasPlugin("jsx")); + typeCast = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state); + if (!typeCast.error) return typeCast.node; + } + if ((_jsx2 = jsx) != null && _jsx2.node) { + this.state = jsx.failState; + return jsx.node; + } + if (arrow.node) { + this.state = arrow.failState; + if (typeParameters) this.reportReservedArrowTypeParam(typeParameters); + return arrow.node; + } + if ((_typeCast = typeCast) != null && _typeCast.node) { + this.state = typeCast.failState; + return typeCast.node; + } + throw ((_jsx3 = jsx) == null ? void 0 : _jsx3.error) || arrow.error || ((_typeCast2 = typeCast) == null ? void 0 : _typeCast2.error); + } + reportReservedArrowTypeParam(node) { + var _node$extra; + if (node.params.length === 1 && !node.params[0].constraint && !((_node$extra = node.extra) != null && _node$extra.trailingComma) && this.getPluginOption("typescript", "disallowAmbiguousJSXLike")) { + this.raise(TSErrors.ReservedArrowTypeParam, node); + } + } + parseMaybeUnary(refExpressionErrors, sawUnary) { + if (!this.hasPlugin("jsx") && this.match(47)) { + return this.tsParseTypeAssertion(); + } + return super.parseMaybeUnary(refExpressionErrors, sawUnary); + } + parseArrow(node) { + if (this.match(14)) { + const result = this.tryParse(abort => { + const returnType = this.tsParseTypeOrTypePredicateAnnotation(14); + if (this.canInsertSemicolon() || !this.match(19)) abort(); + return returnType; + }); + if (result.aborted) return; + if (!result.thrown) { + if (result.error) this.state = result.failState; + node.returnType = result.node; + } + } + return super.parseArrow(node); + } + parseAssignableListItemTypes(param, flags) { + if (!(flags & 2)) return param; + if (this.eat(17)) { + param.optional = true; + } + const type = this.tsTryParseTypeAnnotation(); + if (type) param.typeAnnotation = type; + this.resetEndLocation(param); + return param; + } + isAssignable(node, isBinding) { + switch (node.type) { + case "TSTypeCastExpression": + return this.isAssignable(node.expression, isBinding); + case "TSParameterProperty": + return true; + default: + return super.isAssignable(node, isBinding); + } + } + toAssignable(node, isLHS = false) { + switch (node.type) { + case "ParenthesizedExpression": + this.toAssignableParenthesizedExpression(node, isLHS); + break; + case "TSAsExpression": + case "TSSatisfiesExpression": + case "TSNonNullExpression": + case "TSTypeAssertion": + if (isLHS) { + this.expressionScope.recordArrowParameterBindingError(TSErrors.UnexpectedTypeCastInParameter, node); + } else { + this.raise(TSErrors.UnexpectedTypeCastInParameter, node); + } + this.toAssignable(node.expression, isLHS); + break; + case "AssignmentExpression": + if (!isLHS && node.left.type === "TSTypeCastExpression") { + node.left = this.typeCastToParameter(node.left); + } + default: + super.toAssignable(node, isLHS); + } + } + toAssignableParenthesizedExpression(node, isLHS) { + switch (node.expression.type) { + case "TSAsExpression": + case "TSSatisfiesExpression": + case "TSNonNullExpression": + case "TSTypeAssertion": + case "ParenthesizedExpression": + this.toAssignable(node.expression, isLHS); + break; + default: + super.toAssignable(node, isLHS); + } + } + checkToRestConversion(node, allowPattern) { + switch (node.type) { + case "TSAsExpression": + case "TSSatisfiesExpression": + case "TSTypeAssertion": + case "TSNonNullExpression": + this.checkToRestConversion(node.expression, false); + break; + default: + super.checkToRestConversion(node, allowPattern); + } + } + isValidLVal(type, isUnparenthesizedInAssign, binding) { + switch (type) { + case "TSTypeCastExpression": + return true; + case "TSParameterProperty": + return "parameter"; + case "TSNonNullExpression": + case "TSInstantiationExpression": + return "expression"; + case "TSAsExpression": + case "TSSatisfiesExpression": + case "TSTypeAssertion": + return (binding !== 64 || !isUnparenthesizedInAssign) && ["expression", true]; + default: + return super.isValidLVal(type, isUnparenthesizedInAssign, binding); + } + } + parseBindingAtom() { + if (this.state.type === 78) { + return this.parseIdentifier(true); + } + return super.parseBindingAtom(); + } + parseMaybeDecoratorArguments(expr) { + if (this.match(47) || this.match(51)) { + const typeArguments = this.tsParseTypeArgumentsInExpression(); + if (this.match(10)) { + const call = super.parseMaybeDecoratorArguments(expr); + call.typeParameters = typeArguments; + return call; + } + this.unexpected(null, 10); + } + return super.parseMaybeDecoratorArguments(expr); + } + checkCommaAfterRest(close) { + if (this.state.isAmbientContext && this.match(12) && this.lookaheadCharCode() === close) { + this.next(); + return false; + } + return super.checkCommaAfterRest(close); + } + isClassMethod() { + return this.match(47) || super.isClassMethod(); + } + isClassProperty() { + return this.match(35) || this.match(14) || super.isClassProperty(); + } + parseMaybeDefault(startLoc, left) { + const node = super.parseMaybeDefault(startLoc, left); + if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) { + this.raise(TSErrors.TypeAnnotationAfterAssign, node.typeAnnotation); + } + return node; + } + getTokenFromCode(code) { + if (this.state.inType) { + if (code === 62) { + this.finishOp(48, 1); + return; + } + if (code === 60) { + this.finishOp(47, 1); + return; + } + } + super.getTokenFromCode(code); + } + reScan_lt_gt() { + const { + type + } = this.state; + if (type === 47) { + this.state.pos -= 1; + this.readToken_lt(); + } else if (type === 48) { + this.state.pos -= 1; + this.readToken_gt(); + } + } + reScan_lt() { + const { + type + } = this.state; + if (type === 51) { + this.state.pos -= 2; + this.finishOp(47, 1); + return 47; + } + return type; + } + toAssignableList(exprList, trailingCommaLoc, isLHS) { + for (let i = 0; i < exprList.length; i++) { + const expr = exprList[i]; + if ((expr == null ? void 0 : expr.type) === "TSTypeCastExpression") { + exprList[i] = this.typeCastToParameter(expr); + } + } + super.toAssignableList(exprList, trailingCommaLoc, isLHS); + } + typeCastToParameter(node) { + node.expression.typeAnnotation = node.typeAnnotation; + this.resetEndLocation(node.expression, node.typeAnnotation.loc.end); + return node.expression; + } + shouldParseArrow(params) { + if (this.match(14)) { + return params.every(expr => this.isAssignable(expr, true)); + } + return super.shouldParseArrow(params); + } + shouldParseAsyncArrow() { + return this.match(14) || super.shouldParseAsyncArrow(); + } + canHaveLeadingDecorator() { + return super.canHaveLeadingDecorator() || this.isAbstractClass(); + } + jsxParseOpeningElementAfterName(node) { + if (this.match(47) || this.match(51)) { + const typeArguments = this.tsTryParseAndCatch(() => this.tsParseTypeArgumentsInExpression()); + if (typeArguments) node.typeParameters = typeArguments; + } + return super.jsxParseOpeningElementAfterName(node); + } + getGetterSetterExpectedParamCount(method) { + const baseCount = super.getGetterSetterExpectedParamCount(method); + const params = this.getObjectOrClassMethodParams(method); + const firstParam = params[0]; + const hasContextParam = firstParam && this.isThisParam(firstParam); + return hasContextParam ? baseCount + 1 : baseCount; + } + parseCatchClauseParam() { + const param = super.parseCatchClauseParam(); + const type = this.tsTryParseTypeAnnotation(); + if (type) { + param.typeAnnotation = type; + this.resetEndLocation(param); + } + return param; + } + tsInAmbientContext(cb) { + const { + isAmbientContext: oldIsAmbientContext, + strict: oldStrict + } = this.state; + this.state.isAmbientContext = true; + this.state.strict = false; + try { + return cb(); + } finally { + this.state.isAmbientContext = oldIsAmbientContext; + this.state.strict = oldStrict; + } + } + parseClass(node, isStatement, optionalId) { + const oldInAbstractClass = this.state.inAbstractClass; + this.state.inAbstractClass = !!node.abstract; + try { + return super.parseClass(node, isStatement, optionalId); + } finally { + this.state.inAbstractClass = oldInAbstractClass; + } + } + tsParseAbstractDeclaration(node, decorators) { + if (this.match(80)) { + node.abstract = true; + return this.maybeTakeDecorators(decorators, this.parseClass(node, true, false)); + } else if (this.isContextual(129)) { + if (!this.hasFollowingLineBreak()) { + node.abstract = true; + this.raise(TSErrors.NonClassMethodPropertyHasAbstractModifer, node); + return this.tsParseInterfaceDeclaration(node); + } + } else { + this.unexpected(null, 80); + } + } + parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope) { + const method = super.parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope); + if (method.abstract) { + const hasBody = this.hasPlugin("estree") ? !!method.value.body : !!method.body; + if (hasBody) { + const { + key + } = method; + this.raise(TSErrors.AbstractMethodHasImplementation, method, { + methodName: key.type === "Identifier" && !method.computed ? key.name : `[${this.input.slice(key.start, key.end)}]` + }); + } + } + return method; + } + tsParseTypeParameterName() { + const typeName = this.parseIdentifier(); + return typeName.name; + } + shouldParseAsAmbientContext() { + return !!this.getPluginOption("typescript", "dts"); + } + parse() { + if (this.shouldParseAsAmbientContext()) { + this.state.isAmbientContext = true; + } + return super.parse(); + } + getExpression() { + if (this.shouldParseAsAmbientContext()) { + this.state.isAmbientContext = true; + } + return super.getExpression(); + } + parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly) { + if (!isString && isMaybeTypeOnly) { + this.parseTypeOnlyImportExportSpecifier(node, false, isInTypeExport); + return this.finishNode(node, "ExportSpecifier"); + } + node.exportKind = "value"; + return super.parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly); + } + parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, bindingType) { + if (!importedIsString && isMaybeTypeOnly) { + this.parseTypeOnlyImportExportSpecifier(specifier, true, isInTypeOnlyImport); + return this.finishNode(specifier, "ImportSpecifier"); + } + specifier.importKind = "value"; + return super.parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, isInTypeOnlyImport ? 4098 : 4096); + } + parseTypeOnlyImportExportSpecifier(node, isImport, isInTypeOnlyImportExport) { + const leftOfAsKey = isImport ? "imported" : "local"; + const rightOfAsKey = isImport ? "local" : "exported"; + let leftOfAs = node[leftOfAsKey]; + let rightOfAs; + let hasTypeSpecifier = false; + let canParseAsKeyword = true; + const loc = leftOfAs.loc.start; + if (this.isContextual(93)) { + const firstAs = this.parseIdentifier(); + if (this.isContextual(93)) { + const secondAs = this.parseIdentifier(); + if (tokenIsKeywordOrIdentifier(this.state.type)) { + hasTypeSpecifier = true; + leftOfAs = firstAs; + rightOfAs = isImport ? this.parseIdentifier() : this.parseModuleExportName(); + canParseAsKeyword = false; + } else { + rightOfAs = secondAs; + canParseAsKeyword = false; + } + } else if (tokenIsKeywordOrIdentifier(this.state.type)) { + canParseAsKeyword = false; + rightOfAs = isImport ? this.parseIdentifier() : this.parseModuleExportName(); + } else { + hasTypeSpecifier = true; + leftOfAs = firstAs; + } + } else if (tokenIsKeywordOrIdentifier(this.state.type)) { + hasTypeSpecifier = true; + if (isImport) { + leftOfAs = this.parseIdentifier(true); + if (!this.isContextual(93)) { + this.checkReservedWord(leftOfAs.name, leftOfAs.loc.start, true, true); + } + } else { + leftOfAs = this.parseModuleExportName(); + } + } + if (hasTypeSpecifier && isInTypeOnlyImportExport) { + this.raise(isImport ? TSErrors.TypeModifierIsUsedInTypeImports : TSErrors.TypeModifierIsUsedInTypeExports, loc); + } + node[leftOfAsKey] = leftOfAs; + node[rightOfAsKey] = rightOfAs; + const kindKey = isImport ? "importKind" : "exportKind"; + node[kindKey] = hasTypeSpecifier ? "type" : "value"; + if (canParseAsKeyword && this.eatContextual(93)) { + node[rightOfAsKey] = isImport ? this.parseIdentifier() : this.parseModuleExportName(); + } + if (!node[rightOfAsKey]) { + node[rightOfAsKey] = cloneIdentifier(node[leftOfAsKey]); + } + if (isImport) { + this.checkIdentifier(node[rightOfAsKey], hasTypeSpecifier ? 4098 : 4096); + } + } +}; +function isPossiblyLiteralEnum(expression) { + if (expression.type !== "MemberExpression") return false; + const { + computed, + property + } = expression; + if (computed && property.type !== "StringLiteral" && (property.type !== "TemplateLiteral" || property.expressions.length > 0)) { + return false; + } + return isUncomputedMemberExpressionChain(expression.object); +} +function isValidAmbientConstInitializer(expression, estree) { + var _expression$extra; + const { + type + } = expression; + if ((_expression$extra = expression.extra) != null && _expression$extra.parenthesized) { + return false; + } + if (estree) { + if (type === "Literal") { + const { + value + } = expression; + if (typeof value === "string" || typeof value === "boolean") { + return true; + } + } + } else { + if (type === "StringLiteral" || type === "BooleanLiteral") { + return true; + } + } + if (isNumber(expression, estree) || isNegativeNumber(expression, estree)) { + return true; + } + if (type === "TemplateLiteral" && expression.expressions.length === 0) { + return true; + } + if (isPossiblyLiteralEnum(expression)) { + return true; + } + return false; +} +function isNumber(expression, estree) { + if (estree) { + return expression.type === "Literal" && (typeof expression.value === "number" || "bigint" in expression); + } + return expression.type === "NumericLiteral" || expression.type === "BigIntLiteral"; +} +function isNegativeNumber(expression, estree) { + if (expression.type === "UnaryExpression") { + const { + operator, + argument + } = expression; + if (operator === "-" && isNumber(argument, estree)) { + return true; + } + } + return false; +} +function isUncomputedMemberExpressionChain(expression) { + if (expression.type === "Identifier") return true; + if (expression.type !== "MemberExpression" || expression.computed) { + return false; + } + return isUncomputedMemberExpressionChain(expression.object); +} +const PlaceholderErrors = ParseErrorEnum`placeholders`({ + ClassNameIsRequired: "A class name is required.", + UnexpectedSpace: "Unexpected space in placeholder." +}); +var placeholders = superClass => class PlaceholdersParserMixin extends superClass { + parsePlaceholder(expectedNode) { + if (this.match(144)) { + const node = this.startNode(); + this.next(); + this.assertNoSpace(); + node.name = super.parseIdentifier(true); + this.assertNoSpace(); + this.expect(144); + return this.finishPlaceholder(node, expectedNode); + } + } + finishPlaceholder(node, expectedNode) { + let placeholder = node; + if (!placeholder.expectedNode || !placeholder.type) { + placeholder = this.finishNode(placeholder, "Placeholder"); + } + placeholder.expectedNode = expectedNode; + return placeholder; + } + getTokenFromCode(code) { + if (code === 37 && this.input.charCodeAt(this.state.pos + 1) === 37) { + this.finishOp(144, 2); + } else { + super.getTokenFromCode(code); + } + } + parseExprAtom(refExpressionErrors) { + return this.parsePlaceholder("Expression") || super.parseExprAtom(refExpressionErrors); + } + parseIdentifier(liberal) { + return this.parsePlaceholder("Identifier") || super.parseIdentifier(liberal); + } + checkReservedWord(word, startLoc, checkKeywords, isBinding) { + if (word !== undefined) { + super.checkReservedWord(word, startLoc, checkKeywords, isBinding); + } + } + parseBindingAtom() { + return this.parsePlaceholder("Pattern") || super.parseBindingAtom(); + } + isValidLVal(type, isParenthesized, binding) { + return type === "Placeholder" || super.isValidLVal(type, isParenthesized, binding); + } + toAssignable(node, isLHS) { + if (node && node.type === "Placeholder" && node.expectedNode === "Expression") { + node.expectedNode = "Pattern"; + } else { + super.toAssignable(node, isLHS); + } + } + chStartsBindingIdentifier(ch, pos) { + if (super.chStartsBindingIdentifier(ch, pos)) { + return true; + } + const nextToken = this.lookahead(); + if (nextToken.type === 144) { + return true; + } + return false; + } + verifyBreakContinue(node, isBreak) { + if (node.label && node.label.type === "Placeholder") return; + super.verifyBreakContinue(node, isBreak); + } + parseExpressionStatement(node, expr) { + var _expr$extra; + if (expr.type !== "Placeholder" || (_expr$extra = expr.extra) != null && _expr$extra.parenthesized) { + return super.parseExpressionStatement(node, expr); + } + if (this.match(14)) { + const stmt = node; + stmt.label = this.finishPlaceholder(expr, "Identifier"); + this.next(); + stmt.body = super.parseStatementOrSloppyAnnexBFunctionDeclaration(); + return this.finishNode(stmt, "LabeledStatement"); + } + this.semicolon(); + const stmtPlaceholder = node; + stmtPlaceholder.name = expr.name; + return this.finishPlaceholder(stmtPlaceholder, "Statement"); + } + parseBlock(allowDirectives, createNewLexicalScope, afterBlockParse) { + return this.parsePlaceholder("BlockStatement") || super.parseBlock(allowDirectives, createNewLexicalScope, afterBlockParse); + } + parseFunctionId(requireId) { + return this.parsePlaceholder("Identifier") || super.parseFunctionId(requireId); + } + parseClass(node, isStatement, optionalId) { + const type = isStatement ? "ClassDeclaration" : "ClassExpression"; + this.next(); + const oldStrict = this.state.strict; + const placeholder = this.parsePlaceholder("Identifier"); + if (placeholder) { + if (this.match(81) || this.match(144) || this.match(5)) { + node.id = placeholder; + } else if (optionalId || !isStatement) { + node.id = null; + node.body = this.finishPlaceholder(placeholder, "ClassBody"); + return this.finishNode(node, type); + } else { + throw this.raise(PlaceholderErrors.ClassNameIsRequired, this.state.startLoc); + } + } else { + this.parseClassId(node, isStatement, optionalId); + } + super.parseClassSuper(node); + node.body = this.parsePlaceholder("ClassBody") || super.parseClassBody(!!node.superClass, oldStrict); + return this.finishNode(node, type); + } + parseExport(node, decorators) { + const placeholder = this.parsePlaceholder("Identifier"); + if (!placeholder) return super.parseExport(node, decorators); + const node2 = node; + if (!this.isContextual(98) && !this.match(12)) { + node2.specifiers = []; + node2.source = null; + node2.declaration = this.finishPlaceholder(placeholder, "Declaration"); + return this.finishNode(node2, "ExportNamedDeclaration"); + } + this.expectPlugin("exportDefaultFrom"); + const specifier = this.startNode(); + specifier.exported = placeholder; + node2.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")]; + return super.parseExport(node2, decorators); + } + isExportDefaultSpecifier() { + if (this.match(65)) { + const next = this.nextTokenStart(); + if (this.isUnparsedContextual(next, "from")) { + if (this.input.startsWith(tokenLabelName(144), this.nextTokenStartSince(next + 4))) { + return true; + } + } + } + return super.isExportDefaultSpecifier(); + } + maybeParseExportDefaultSpecifier(node, maybeDefaultIdentifier) { + var _specifiers; + if ((_specifiers = node.specifiers) != null && _specifiers.length) { + return true; + } + return super.maybeParseExportDefaultSpecifier(node, maybeDefaultIdentifier); + } + checkExport(node) { + const { + specifiers + } = node; + if (specifiers != null && specifiers.length) { + node.specifiers = specifiers.filter(node => node.exported.type === "Placeholder"); + } + super.checkExport(node); + node.specifiers = specifiers; + } + parseImport(node) { + const placeholder = this.parsePlaceholder("Identifier"); + if (!placeholder) return super.parseImport(node); + node.specifiers = []; + if (!this.isContextual(98) && !this.match(12)) { + node.source = this.finishPlaceholder(placeholder, "StringLiteral"); + this.semicolon(); + return this.finishNode(node, "ImportDeclaration"); + } + const specifier = this.startNodeAtNode(placeholder); + specifier.local = placeholder; + node.specifiers.push(this.finishNode(specifier, "ImportDefaultSpecifier")); + if (this.eat(12)) { + const hasStarImport = this.maybeParseStarImportSpecifier(node); + if (!hasStarImport) this.parseNamedImportSpecifiers(node); + } + this.expectContextual(98); + node.source = this.parseImportSource(); + this.semicolon(); + return this.finishNode(node, "ImportDeclaration"); + } + parseImportSource() { + return this.parsePlaceholder("StringLiteral") || super.parseImportSource(); + } + assertNoSpace() { + if (this.state.start > this.state.lastTokEndLoc.index) { + this.raise(PlaceholderErrors.UnexpectedSpace, this.state.lastTokEndLoc); + } + } +}; +var v8intrinsic = superClass => class V8IntrinsicMixin extends superClass { + parseV8Intrinsic() { + if (this.match(54)) { + const v8IntrinsicStartLoc = this.state.startLoc; + const node = this.startNode(); + this.next(); + if (tokenIsIdentifier(this.state.type)) { + const name = this.parseIdentifierName(); + const identifier = this.createIdentifier(node, name); + identifier.type = "V8IntrinsicIdentifier"; + if (this.match(10)) { + return identifier; + } + } + this.unexpected(v8IntrinsicStartLoc); + } + } + parseExprAtom(refExpressionErrors) { + return this.parseV8Intrinsic() || super.parseExprAtom(refExpressionErrors); + } +}; +const PIPELINE_PROPOSALS = ["minimal", "fsharp", "hack", "smart"]; +const TOPIC_TOKENS = ["^^", "@@", "^", "%", "#"]; +function validatePlugins(pluginsMap) { + if (pluginsMap.has("decorators")) { + if (pluginsMap.has("decorators-legacy")) { + throw new Error("Cannot use the decorators and decorators-legacy plugin together"); + } + const decoratorsBeforeExport = pluginsMap.get("decorators").decoratorsBeforeExport; + if (decoratorsBeforeExport != null && typeof decoratorsBeforeExport !== "boolean") { + throw new Error("'decoratorsBeforeExport' must be a boolean, if specified."); + } + const allowCallParenthesized = pluginsMap.get("decorators").allowCallParenthesized; + if (allowCallParenthesized != null && typeof allowCallParenthesized !== "boolean") { + throw new Error("'allowCallParenthesized' must be a boolean."); + } + } + if (pluginsMap.has("flow") && pluginsMap.has("typescript")) { + throw new Error("Cannot combine flow and typescript plugins."); + } + if (pluginsMap.has("placeholders") && pluginsMap.has("v8intrinsic")) { + throw new Error("Cannot combine placeholders and v8intrinsic plugins."); + } + if (pluginsMap.has("pipelineOperator")) { + var _pluginsMap$get; + const proposal = pluginsMap.get("pipelineOperator").proposal; + if (!PIPELINE_PROPOSALS.includes(proposal)) { + const proposalList = PIPELINE_PROPOSALS.map(p => `"${p}"`).join(", "); + throw new Error(`"pipelineOperator" requires "proposal" option whose value must be one of: ${proposalList}.`); + } + const tupleSyntaxIsHash = ((_pluginsMap$get = pluginsMap.get("recordAndTuple")) == null ? void 0 : _pluginsMap$get.syntaxType) === "hash"; + if (proposal === "hack") { + if (pluginsMap.has("placeholders")) { + throw new Error("Cannot combine placeholders plugin and Hack-style pipes."); + } + if (pluginsMap.has("v8intrinsic")) { + throw new Error("Cannot combine v8intrinsic plugin and Hack-style pipes."); + } + const topicToken = pluginsMap.get("pipelineOperator").topicToken; + if (!TOPIC_TOKENS.includes(topicToken)) { + const tokenList = TOPIC_TOKENS.map(t => `"${t}"`).join(", "); + throw new Error(`"pipelineOperator" in "proposal": "hack" mode also requires a "topicToken" option whose value must be one of: ${tokenList}.`); + } + if (topicToken === "#" && tupleSyntaxIsHash) { + throw new Error(`Plugin conflict between \`["pipelineOperator", { proposal: "hack", topicToken: "#" }]\` and \`${JSON.stringify(["recordAndTuple", pluginsMap.get("recordAndTuple")])}\`.`); + } + } else if (proposal === "smart" && tupleSyntaxIsHash) { + throw new Error(`Plugin conflict between \`["pipelineOperator", { proposal: "smart" }]\` and \`${JSON.stringify(["recordAndTuple", pluginsMap.get("recordAndTuple")])}\`.`); + } + } + if (pluginsMap.has("moduleAttributes")) { + { + if (pluginsMap.has("importAttributes") || pluginsMap.has("importAssertions")) { + throw new Error("Cannot combine importAssertions, importAttributes and moduleAttributes plugins."); + } + const moduleAttributesVersionPluginOption = pluginsMap.get("moduleAttributes").version; + if (moduleAttributesVersionPluginOption !== "may-2020") { + throw new Error("The 'moduleAttributes' plugin requires a 'version' option," + " representing the last proposal update. Currently, the" + " only supported value is 'may-2020'."); + } + } + } + if (pluginsMap.has("importAttributes") && pluginsMap.has("importAssertions")) { + throw new Error("Cannot combine importAssertions and importAttributes plugins."); + } + if (pluginsMap.has("recordAndTuple")) { + const syntaxType = pluginsMap.get("recordAndTuple").syntaxType; + if (syntaxType != null) { + { + const RECORD_AND_TUPLE_SYNTAX_TYPES = ["hash", "bar"]; + if (!RECORD_AND_TUPLE_SYNTAX_TYPES.includes(syntaxType)) { + throw new Error("The 'syntaxType' option of the 'recordAndTuple' plugin must be one of: " + RECORD_AND_TUPLE_SYNTAX_TYPES.map(p => `'${p}'`).join(", ")); + } + } + } + } + if (pluginsMap.has("asyncDoExpressions") && !pluginsMap.has("doExpressions")) { + const error = new Error("'asyncDoExpressions' requires 'doExpressions', please add 'doExpressions' to parser plugins."); + error.missingPlugins = "doExpressions"; + throw error; + } + if (pluginsMap.has("optionalChainingAssign") && pluginsMap.get("optionalChainingAssign").version !== "2023-07") { + throw new Error("The 'optionalChainingAssign' plugin requires a 'version' option," + " representing the last proposal update. Currently, the" + " only supported value is '2023-07'."); + } +} +const mixinPlugins = { + estree, + jsx, + flow, + typescript, + v8intrinsic, + placeholders +}; +const mixinPluginNames = Object.keys(mixinPlugins); +const defaultOptions = { + sourceType: "script", + sourceFilename: undefined, + startColumn: 0, + startLine: 1, + allowAwaitOutsideFunction: false, + allowReturnOutsideFunction: false, + allowNewTargetOutsideFunction: false, + allowImportExportEverywhere: false, + allowSuperOutsideMethod: false, + allowUndeclaredExports: false, + plugins: [], + strictMode: null, + ranges: false, + tokens: false, + createImportExpressions: false, + createParenthesizedExpressions: false, + errorRecovery: false, + attachComment: true, + annexB: true +}; +function getOptions(opts) { + if (opts == null) { + return Object.assign({}, defaultOptions); + } + if (opts.annexB != null && opts.annexB !== false) { + throw new Error("The `annexB` option can only be set to `false`."); + } + const options = {}; + for (const key of Object.keys(defaultOptions)) { + var _opts$key; + options[key] = (_opts$key = opts[key]) != null ? _opts$key : defaultOptions[key]; + } + return options; +} +class ExpressionParser extends LValParser { + checkProto(prop, isRecord, protoRef, refExpressionErrors) { + if (prop.type === "SpreadElement" || this.isObjectMethod(prop) || prop.computed || prop.shorthand) { + return; + } + const key = prop.key; + const name = key.type === "Identifier" ? key.name : key.value; + if (name === "__proto__") { + if (isRecord) { + this.raise(Errors.RecordNoProto, key); + return; + } + if (protoRef.used) { + if (refExpressionErrors) { + if (refExpressionErrors.doubleProtoLoc === null) { + refExpressionErrors.doubleProtoLoc = key.loc.start; + } + } else { + this.raise(Errors.DuplicateProto, key); + } + } + protoRef.used = true; + } + } + shouldExitDescending(expr, potentialArrowAt) { + return expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt; + } + getExpression() { + this.enterInitialScopes(); + this.nextToken(); + const expr = this.parseExpression(); + if (!this.match(139)) { + this.unexpected(); + } + this.finalizeRemainingComments(); + expr.comments = this.comments; + expr.errors = this.state.errors; + if (this.options.tokens) { + expr.tokens = this.tokens; + } + return expr; + } + parseExpression(disallowIn, refExpressionErrors) { + if (disallowIn) { + return this.disallowInAnd(() => this.parseExpressionBase(refExpressionErrors)); + } + return this.allowInAnd(() => this.parseExpressionBase(refExpressionErrors)); + } + parseExpressionBase(refExpressionErrors) { + const startLoc = this.state.startLoc; + const expr = this.parseMaybeAssign(refExpressionErrors); + if (this.match(12)) { + const node = this.startNodeAt(startLoc); + node.expressions = [expr]; + while (this.eat(12)) { + node.expressions.push(this.parseMaybeAssign(refExpressionErrors)); + } + this.toReferencedList(node.expressions); + return this.finishNode(node, "SequenceExpression"); + } + return expr; + } + parseMaybeAssignDisallowIn(refExpressionErrors, afterLeftParse) { + return this.disallowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse)); + } + parseMaybeAssignAllowIn(refExpressionErrors, afterLeftParse) { + return this.allowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse)); + } + setOptionalParametersError(refExpressionErrors, resultError) { + var _resultError$loc; + refExpressionErrors.optionalParametersLoc = (_resultError$loc = resultError == null ? void 0 : resultError.loc) != null ? _resultError$loc : this.state.startLoc; + } + parseMaybeAssign(refExpressionErrors, afterLeftParse) { + const startLoc = this.state.startLoc; + if (this.isContextual(108)) { + if (this.prodParam.hasYield) { + let left = this.parseYield(); + if (afterLeftParse) { + left = afterLeftParse.call(this, left, startLoc); + } + return left; + } + } + let ownExpressionErrors; + if (refExpressionErrors) { + ownExpressionErrors = false; + } else { + refExpressionErrors = new ExpressionErrors(); + ownExpressionErrors = true; + } + const { + type + } = this.state; + if (type === 10 || tokenIsIdentifier(type)) { + this.state.potentialArrowAt = this.state.start; + } + let left = this.parseMaybeConditional(refExpressionErrors); + if (afterLeftParse) { + left = afterLeftParse.call(this, left, startLoc); + } + if (tokenIsAssignment(this.state.type)) { + const node = this.startNodeAt(startLoc); + const operator = this.state.value; + node.operator = operator; + if (this.match(29)) { + this.toAssignable(left, true); + node.left = left; + const startIndex = startLoc.index; + if (refExpressionErrors.doubleProtoLoc != null && refExpressionErrors.doubleProtoLoc.index >= startIndex) { + refExpressionErrors.doubleProtoLoc = null; + } + if (refExpressionErrors.shorthandAssignLoc != null && refExpressionErrors.shorthandAssignLoc.index >= startIndex) { + refExpressionErrors.shorthandAssignLoc = null; + } + if (refExpressionErrors.privateKeyLoc != null && refExpressionErrors.privateKeyLoc.index >= startIndex) { + this.checkDestructuringPrivate(refExpressionErrors); + refExpressionErrors.privateKeyLoc = null; + } + } else { + node.left = left; + } + this.next(); + node.right = this.parseMaybeAssign(); + this.checkLVal(left, this.finishNode(node, "AssignmentExpression")); + return node; + } else if (ownExpressionErrors) { + this.checkExpressionErrors(refExpressionErrors, true); + } + return left; + } + parseMaybeConditional(refExpressionErrors) { + const startLoc = this.state.startLoc; + const potentialArrowAt = this.state.potentialArrowAt; + const expr = this.parseExprOps(refExpressionErrors); + if (this.shouldExitDescending(expr, potentialArrowAt)) { + return expr; + } + return this.parseConditional(expr, startLoc, refExpressionErrors); + } + parseConditional(expr, startLoc, refExpressionErrors) { + if (this.eat(17)) { + const node = this.startNodeAt(startLoc); + node.test = expr; + node.consequent = this.parseMaybeAssignAllowIn(); + this.expect(14); + node.alternate = this.parseMaybeAssign(); + return this.finishNode(node, "ConditionalExpression"); + } + return expr; + } + parseMaybeUnaryOrPrivate(refExpressionErrors) { + return this.match(138) ? this.parsePrivateName() : this.parseMaybeUnary(refExpressionErrors); + } + parseExprOps(refExpressionErrors) { + const startLoc = this.state.startLoc; + const potentialArrowAt = this.state.potentialArrowAt; + const expr = this.parseMaybeUnaryOrPrivate(refExpressionErrors); + if (this.shouldExitDescending(expr, potentialArrowAt)) { + return expr; + } + return this.parseExprOp(expr, startLoc, -1); + } + parseExprOp(left, leftStartLoc, minPrec) { + if (this.isPrivateName(left)) { + const value = this.getPrivateNameSV(left); + if (minPrec >= tokenOperatorPrecedence(58) || !this.prodParam.hasIn || !this.match(58)) { + this.raise(Errors.PrivateInExpectedIn, left, { + identifierName: value + }); + } + this.classScope.usePrivateName(value, left.loc.start); + } + const op = this.state.type; + if (tokenIsOperator(op) && (this.prodParam.hasIn || !this.match(58))) { + let prec = tokenOperatorPrecedence(op); + if (prec > minPrec) { + if (op === 39) { + this.expectPlugin("pipelineOperator"); + if (this.state.inFSharpPipelineDirectBody) { + return left; + } + this.checkPipelineAtInfixOperator(left, leftStartLoc); + } + const node = this.startNodeAt(leftStartLoc); + node.left = left; + node.operator = this.state.value; + const logical = op === 41 || op === 42; + const coalesce = op === 40; + if (coalesce) { + prec = tokenOperatorPrecedence(42); + } + this.next(); + if (op === 39 && this.hasPlugin(["pipelineOperator", { + proposal: "minimal" + }])) { + if (this.state.type === 96 && this.prodParam.hasAwait) { + throw this.raise(Errors.UnexpectedAwaitAfterPipelineBody, this.state.startLoc); + } + } + node.right = this.parseExprOpRightExpr(op, prec); + const finishedNode = this.finishNode(node, logical || coalesce ? "LogicalExpression" : "BinaryExpression"); + const nextOp = this.state.type; + if (coalesce && (nextOp === 41 || nextOp === 42) || logical && nextOp === 40) { + throw this.raise(Errors.MixingCoalesceWithLogical, this.state.startLoc); + } + return this.parseExprOp(finishedNode, leftStartLoc, minPrec); + } + } + return left; + } + parseExprOpRightExpr(op, prec) { + const startLoc = this.state.startLoc; + switch (op) { + case 39: + switch (this.getPluginOption("pipelineOperator", "proposal")) { + case "hack": + return this.withTopicBindingContext(() => { + return this.parseHackPipeBody(); + }); + case "smart": + return this.withTopicBindingContext(() => { + if (this.prodParam.hasYield && this.isContextual(108)) { + throw this.raise(Errors.PipeBodyIsTighter, this.state.startLoc); + } + return this.parseSmartPipelineBodyInStyle(this.parseExprOpBaseRightExpr(op, prec), startLoc); + }); + case "fsharp": + return this.withSoloAwaitPermittingContext(() => { + return this.parseFSharpPipelineBody(prec); + }); + } + default: + return this.parseExprOpBaseRightExpr(op, prec); + } + } + parseExprOpBaseRightExpr(op, prec) { + const startLoc = this.state.startLoc; + return this.parseExprOp(this.parseMaybeUnaryOrPrivate(), startLoc, tokenIsRightAssociative(op) ? prec - 1 : prec); + } + parseHackPipeBody() { + var _body$extra; + const { + startLoc + } = this.state; + const body = this.parseMaybeAssign(); + const requiredParentheses = UnparenthesizedPipeBodyDescriptions.has(body.type); + if (requiredParentheses && !((_body$extra = body.extra) != null && _body$extra.parenthesized)) { + this.raise(Errors.PipeUnparenthesizedBody, startLoc, { + type: body.type + }); + } + if (!this.topicReferenceWasUsedInCurrentContext()) { + this.raise(Errors.PipeTopicUnused, startLoc); + } + return body; + } + checkExponentialAfterUnary(node) { + if (this.match(57)) { + this.raise(Errors.UnexpectedTokenUnaryExponentiation, node.argument); + } + } + parseMaybeUnary(refExpressionErrors, sawUnary) { + const startLoc = this.state.startLoc; + const isAwait = this.isContextual(96); + if (isAwait && this.recordAwaitIfAllowed()) { + this.next(); + const expr = this.parseAwait(startLoc); + if (!sawUnary) this.checkExponentialAfterUnary(expr); + return expr; + } + const update = this.match(34); + const node = this.startNode(); + if (tokenIsPrefix(this.state.type)) { + node.operator = this.state.value; + node.prefix = true; + if (this.match(72)) { + this.expectPlugin("throwExpressions"); + } + const isDelete = this.match(89); + this.next(); + node.argument = this.parseMaybeUnary(null, true); + this.checkExpressionErrors(refExpressionErrors, true); + if (this.state.strict && isDelete) { + const arg = node.argument; + if (arg.type === "Identifier") { + this.raise(Errors.StrictDelete, node); + } else if (this.hasPropertyAsPrivateName(arg)) { + this.raise(Errors.DeletePrivateField, node); + } + } + if (!update) { + if (!sawUnary) { + this.checkExponentialAfterUnary(node); + } + return this.finishNode(node, "UnaryExpression"); + } + } + const expr = this.parseUpdate(node, update, refExpressionErrors); + if (isAwait) { + const { + type + } = this.state; + const startsExpr = this.hasPlugin("v8intrinsic") ? tokenCanStartExpression(type) : tokenCanStartExpression(type) && !this.match(54); + if (startsExpr && !this.isAmbiguousAwait()) { + this.raiseOverwrite(Errors.AwaitNotInAsyncContext, startLoc); + return this.parseAwait(startLoc); + } + } + return expr; + } + parseUpdate(node, update, refExpressionErrors) { + if (update) { + const updateExpressionNode = node; + this.checkLVal(updateExpressionNode.argument, this.finishNode(updateExpressionNode, "UpdateExpression")); + return node; + } + const startLoc = this.state.startLoc; + let expr = this.parseExprSubscripts(refExpressionErrors); + if (this.checkExpressionErrors(refExpressionErrors, false)) return expr; + while (tokenIsPostfix(this.state.type) && !this.canInsertSemicolon()) { + const node = this.startNodeAt(startLoc); + node.operator = this.state.value; + node.prefix = false; + node.argument = expr; + this.next(); + this.checkLVal(expr, expr = this.finishNode(node, "UpdateExpression")); + } + return expr; + } + parseExprSubscripts(refExpressionErrors) { + const startLoc = this.state.startLoc; + const potentialArrowAt = this.state.potentialArrowAt; + const expr = this.parseExprAtom(refExpressionErrors); + if (this.shouldExitDescending(expr, potentialArrowAt)) { + return expr; + } + return this.parseSubscripts(expr, startLoc); + } + parseSubscripts(base, startLoc, noCalls) { + const state = { + optionalChainMember: false, + maybeAsyncArrow: this.atPossibleAsyncArrow(base), + stop: false + }; + do { + base = this.parseSubscript(base, startLoc, noCalls, state); + state.maybeAsyncArrow = false; + } while (!state.stop); + return base; + } + parseSubscript(base, startLoc, noCalls, state) { + const { + type + } = this.state; + if (!noCalls && type === 15) { + return this.parseBind(base, startLoc, noCalls, state); + } else if (tokenIsTemplate(type)) { + return this.parseTaggedTemplateExpression(base, startLoc, state); + } + let optional = false; + if (type === 18) { + if (noCalls) { + this.raise(Errors.OptionalChainingNoNew, this.state.startLoc); + if (this.lookaheadCharCode() === 40) { + state.stop = true; + return base; + } + } + state.optionalChainMember = optional = true; + this.next(); + } + if (!noCalls && this.match(10)) { + return this.parseCoverCallAndAsyncArrowHead(base, startLoc, state, optional); + } else { + const computed = this.eat(0); + if (computed || optional || this.eat(16)) { + return this.parseMember(base, startLoc, state, computed, optional); + } else { + state.stop = true; + return base; + } + } + } + parseMember(base, startLoc, state, computed, optional) { + const node = this.startNodeAt(startLoc); + node.object = base; + node.computed = computed; + if (computed) { + node.property = this.parseExpression(); + this.expect(3); + } else if (this.match(138)) { + if (base.type === "Super") { + this.raise(Errors.SuperPrivateField, startLoc); + } + this.classScope.usePrivateName(this.state.value, this.state.startLoc); + node.property = this.parsePrivateName(); + } else { + node.property = this.parseIdentifier(true); + } + if (state.optionalChainMember) { + node.optional = optional; + return this.finishNode(node, "OptionalMemberExpression"); + } else { + return this.finishNode(node, "MemberExpression"); + } + } + parseBind(base, startLoc, noCalls, state) { + const node = this.startNodeAt(startLoc); + node.object = base; + this.next(); + node.callee = this.parseNoCallExpr(); + state.stop = true; + return this.parseSubscripts(this.finishNode(node, "BindExpression"), startLoc, noCalls); + } + parseCoverCallAndAsyncArrowHead(base, startLoc, state, optional) { + const oldMaybeInArrowParameters = this.state.maybeInArrowParameters; + let refExpressionErrors = null; + this.state.maybeInArrowParameters = true; + this.next(); + const node = this.startNodeAt(startLoc); + node.callee = base; + const { + maybeAsyncArrow, + optionalChainMember + } = state; + if (maybeAsyncArrow) { + this.expressionScope.enter(newAsyncArrowScope()); + refExpressionErrors = new ExpressionErrors(); + } + if (optionalChainMember) { + node.optional = optional; + } + if (optional) { + node.arguments = this.parseCallExpressionArguments(11); + } else { + node.arguments = this.parseCallExpressionArguments(11, base.type === "Import", base.type !== "Super", node, refExpressionErrors); + } + let finishedNode = this.finishCallExpression(node, optionalChainMember); + if (maybeAsyncArrow && this.shouldParseAsyncArrow() && !optional) { + state.stop = true; + this.checkDestructuringPrivate(refExpressionErrors); + this.expressionScope.validateAsPattern(); + this.expressionScope.exit(); + finishedNode = this.parseAsyncArrowFromCallExpression(this.startNodeAt(startLoc), finishedNode); + } else { + if (maybeAsyncArrow) { + this.checkExpressionErrors(refExpressionErrors, true); + this.expressionScope.exit(); + } + this.toReferencedArguments(finishedNode); + } + this.state.maybeInArrowParameters = oldMaybeInArrowParameters; + return finishedNode; + } + toReferencedArguments(node, isParenthesizedExpr) { + this.toReferencedListDeep(node.arguments, isParenthesizedExpr); + } + parseTaggedTemplateExpression(base, startLoc, state) { + const node = this.startNodeAt(startLoc); + node.tag = base; + node.quasi = this.parseTemplate(true); + if (state.optionalChainMember) { + this.raise(Errors.OptionalChainingNoTemplate, startLoc); + } + return this.finishNode(node, "TaggedTemplateExpression"); + } + atPossibleAsyncArrow(base) { + return base.type === "Identifier" && base.name === "async" && this.state.lastTokEndLoc.index === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && base.start === this.state.potentialArrowAt; + } + expectImportAttributesPlugin() { + if (!this.hasPlugin("importAssertions")) { + this.expectPlugin("importAttributes"); + } + } + finishCallExpression(node, optional) { + if (node.callee.type === "Import") { + if (node.arguments.length === 2) { + { + if (!this.hasPlugin("moduleAttributes")) { + this.expectImportAttributesPlugin(); + } + } + } + if (node.arguments.length === 0 || node.arguments.length > 2) { + this.raise(Errors.ImportCallArity, node, { + maxArgumentCount: this.hasPlugin("importAttributes") || this.hasPlugin("importAssertions") || this.hasPlugin("moduleAttributes") ? 2 : 1 + }); + } else { + for (const arg of node.arguments) { + if (arg.type === "SpreadElement") { + this.raise(Errors.ImportCallSpreadArgument, arg); + } + } + } + } + return this.finishNode(node, optional ? "OptionalCallExpression" : "CallExpression"); + } + parseCallExpressionArguments(close, dynamicImport, allowPlaceholder, nodeForExtra, refExpressionErrors) { + const elts = []; + let first = true; + const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody; + this.state.inFSharpPipelineDirectBody = false; + while (!this.eat(close)) { + if (first) { + first = false; + } else { + this.expect(12); + if (this.match(close)) { + if (dynamicImport && !this.hasPlugin("importAttributes") && !this.hasPlugin("importAssertions") && !this.hasPlugin("moduleAttributes")) { + this.raise(Errors.ImportCallArgumentTrailingComma, this.state.lastTokStartLoc); + } + if (nodeForExtra) { + this.addTrailingCommaExtraToNode(nodeForExtra); + } + this.next(); + break; + } + } + elts.push(this.parseExprListItem(false, refExpressionErrors, allowPlaceholder)); + } + this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody; + return elts; + } + shouldParseAsyncArrow() { + return this.match(19) && !this.canInsertSemicolon(); + } + parseAsyncArrowFromCallExpression(node, call) { + var _call$extra; + this.resetPreviousNodeTrailingComments(call); + this.expect(19); + this.parseArrowExpression(node, call.arguments, true, (_call$extra = call.extra) == null ? void 0 : _call$extra.trailingCommaLoc); + if (call.innerComments) { + setInnerComments(node, call.innerComments); + } + if (call.callee.trailingComments) { + setInnerComments(node, call.callee.trailingComments); + } + return node; + } + parseNoCallExpr() { + const startLoc = this.state.startLoc; + return this.parseSubscripts(this.parseExprAtom(), startLoc, true); + } + parseExprAtom(refExpressionErrors) { + let node; + let decorators = null; + const { + type + } = this.state; + switch (type) { + case 79: + return this.parseSuper(); + case 83: + node = this.startNode(); + this.next(); + if (this.match(16)) { + return this.parseImportMetaProperty(node); + } + if (this.match(10)) { + if (this.options.createImportExpressions) { + return this.parseImportCall(node); + } else { + return this.finishNode(node, "Import"); + } + } else { + this.raise(Errors.UnsupportedImport, this.state.lastTokStartLoc); + return this.finishNode(node, "Import"); + } + case 78: + node = this.startNode(); + this.next(); + return this.finishNode(node, "ThisExpression"); + case 90: + { + return this.parseDo(this.startNode(), false); + } + case 56: + case 31: + { + this.readRegexp(); + return this.parseRegExpLiteral(this.state.value); + } + case 134: + return this.parseNumericLiteral(this.state.value); + case 135: + return this.parseBigIntLiteral(this.state.value); + case 136: + return this.parseDecimalLiteral(this.state.value); + case 133: + return this.parseStringLiteral(this.state.value); + case 84: + return this.parseNullLiteral(); + case 85: + return this.parseBooleanLiteral(true); + case 86: + return this.parseBooleanLiteral(false); + case 10: + { + const canBeArrow = this.state.potentialArrowAt === this.state.start; + return this.parseParenAndDistinguishExpression(canBeArrow); + } + case 2: + case 1: + { + return this.parseArrayLike(this.state.type === 2 ? 4 : 3, false, true); + } + case 0: + { + return this.parseArrayLike(3, true, false, refExpressionErrors); + } + case 6: + case 7: + { + return this.parseObjectLike(this.state.type === 6 ? 9 : 8, false, true); + } + case 5: + { + return this.parseObjectLike(8, false, false, refExpressionErrors); + } + case 68: + return this.parseFunctionOrFunctionSent(); + case 26: + decorators = this.parseDecorators(); + case 80: + return this.parseClass(this.maybeTakeDecorators(decorators, this.startNode()), false); + case 77: + return this.parseNewOrNewTarget(); + case 25: + case 24: + return this.parseTemplate(false); + case 15: + { + node = this.startNode(); + this.next(); + node.object = null; + const callee = node.callee = this.parseNoCallExpr(); + if (callee.type === "MemberExpression") { + return this.finishNode(node, "BindExpression"); + } else { + throw this.raise(Errors.UnsupportedBind, callee); + } + } + case 138: + { + this.raise(Errors.PrivateInExpectedIn, this.state.startLoc, { + identifierName: this.state.value + }); + return this.parsePrivateName(); + } + case 33: + { + return this.parseTopicReferenceThenEqualsSign(54, "%"); + } + case 32: + { + return this.parseTopicReferenceThenEqualsSign(44, "^"); + } + case 37: + case 38: + { + return this.parseTopicReference("hack"); + } + case 44: + case 54: + case 27: + { + const pipeProposal = this.getPluginOption("pipelineOperator", "proposal"); + if (pipeProposal) { + return this.parseTopicReference(pipeProposal); + } + this.unexpected(); + break; + } + case 47: + { + const lookaheadCh = this.input.codePointAt(this.nextTokenStart()); + if (isIdentifierStart(lookaheadCh) || lookaheadCh === 62) { + this.expectOnePlugin(["jsx", "flow", "typescript"]); + } else { + this.unexpected(); + } + break; + } + default: + if (tokenIsIdentifier(type)) { + if (this.isContextual(127) && this.lookaheadInLineCharCode() === 123) { + return this.parseModuleExpression(); + } + const canBeArrow = this.state.potentialArrowAt === this.state.start; + const containsEsc = this.state.containsEsc; + const id = this.parseIdentifier(); + if (!containsEsc && id.name === "async" && !this.canInsertSemicolon()) { + const { + type + } = this.state; + if (type === 68) { + this.resetPreviousNodeTrailingComments(id); + this.next(); + return this.parseAsyncFunctionExpression(this.startNodeAtNode(id)); + } else if (tokenIsIdentifier(type)) { + if (this.lookaheadCharCode() === 61) { + return this.parseAsyncArrowUnaryFunction(this.startNodeAtNode(id)); + } else { + return id; + } + } else if (type === 90) { + this.resetPreviousNodeTrailingComments(id); + return this.parseDo(this.startNodeAtNode(id), true); + } + } + if (canBeArrow && this.match(19) && !this.canInsertSemicolon()) { + this.next(); + return this.parseArrowExpression(this.startNodeAtNode(id), [id], false); + } + return id; + } else { + this.unexpected(); + } + } + } + parseTopicReferenceThenEqualsSign(topicTokenType, topicTokenValue) { + const pipeProposal = this.getPluginOption("pipelineOperator", "proposal"); + if (pipeProposal) { + this.state.type = topicTokenType; + this.state.value = topicTokenValue; + this.state.pos--; + this.state.end--; + this.state.endLoc = createPositionWithColumnOffset(this.state.endLoc, -1); + return this.parseTopicReference(pipeProposal); + } else { + this.unexpected(); + } + } + parseTopicReference(pipeProposal) { + const node = this.startNode(); + const startLoc = this.state.startLoc; + const tokenType = this.state.type; + this.next(); + return this.finishTopicReference(node, startLoc, pipeProposal, tokenType); + } + finishTopicReference(node, startLoc, pipeProposal, tokenType) { + if (this.testTopicReferenceConfiguration(pipeProposal, startLoc, tokenType)) { + const nodeType = pipeProposal === "smart" ? "PipelinePrimaryTopicReference" : "TopicReference"; + if (!this.topicReferenceIsAllowedInCurrentContext()) { + this.raise(pipeProposal === "smart" ? Errors.PrimaryTopicNotAllowed : Errors.PipeTopicUnbound, startLoc); + } + this.registerTopicReference(); + return this.finishNode(node, nodeType); + } else { + throw this.raise(Errors.PipeTopicUnconfiguredToken, startLoc, { + token: tokenLabelName(tokenType) + }); + } + } + testTopicReferenceConfiguration(pipeProposal, startLoc, tokenType) { + switch (pipeProposal) { + case "hack": + { + return this.hasPlugin(["pipelineOperator", { + topicToken: tokenLabelName(tokenType) + }]); + } + case "smart": + return tokenType === 27; + default: + throw this.raise(Errors.PipeTopicRequiresHackPipes, startLoc); + } + } + parseAsyncArrowUnaryFunction(node) { + this.prodParam.enter(functionFlags(true, this.prodParam.hasYield)); + const params = [this.parseIdentifier()]; + this.prodParam.exit(); + if (this.hasPrecedingLineBreak()) { + this.raise(Errors.LineTerminatorBeforeArrow, this.state.curPosition()); + } + this.expect(19); + return this.parseArrowExpression(node, params, true); + } + parseDo(node, isAsync) { + this.expectPlugin("doExpressions"); + if (isAsync) { + this.expectPlugin("asyncDoExpressions"); + } + node.async = isAsync; + this.next(); + const oldLabels = this.state.labels; + this.state.labels = []; + if (isAsync) { + this.prodParam.enter(2); + node.body = this.parseBlock(); + this.prodParam.exit(); + } else { + node.body = this.parseBlock(); + } + this.state.labels = oldLabels; + return this.finishNode(node, "DoExpression"); + } + parseSuper() { + const node = this.startNode(); + this.next(); + if (this.match(10) && !this.scope.allowDirectSuper && !this.options.allowSuperOutsideMethod) { + this.raise(Errors.SuperNotAllowed, node); + } else if (!this.scope.allowSuper && !this.options.allowSuperOutsideMethod) { + this.raise(Errors.UnexpectedSuper, node); + } + if (!this.match(10) && !this.match(0) && !this.match(16)) { + this.raise(Errors.UnsupportedSuper, node); + } + return this.finishNode(node, "Super"); + } + parsePrivateName() { + const node = this.startNode(); + const id = this.startNodeAt(createPositionWithColumnOffset(this.state.startLoc, 1)); + const name = this.state.value; + this.next(); + node.id = this.createIdentifier(id, name); + return this.finishNode(node, "PrivateName"); + } + parseFunctionOrFunctionSent() { + const node = this.startNode(); + this.next(); + if (this.prodParam.hasYield && this.match(16)) { + const meta = this.createIdentifier(this.startNodeAtNode(node), "function"); + this.next(); + if (this.match(103)) { + this.expectPlugin("functionSent"); + } else if (!this.hasPlugin("functionSent")) { + this.unexpected(); + } + return this.parseMetaProperty(node, meta, "sent"); + } + return this.parseFunction(node); + } + parseMetaProperty(node, meta, propertyName) { + node.meta = meta; + const containsEsc = this.state.containsEsc; + node.property = this.parseIdentifier(true); + if (node.property.name !== propertyName || containsEsc) { + this.raise(Errors.UnsupportedMetaProperty, node.property, { + target: meta.name, + onlyValidPropertyName: propertyName + }); + } + return this.finishNode(node, "MetaProperty"); + } + parseImportMetaProperty(node) { + const id = this.createIdentifier(this.startNodeAtNode(node), "import"); + this.next(); + if (this.isContextual(101)) { + if (!this.inModule) { + this.raise(Errors.ImportMetaOutsideModule, id); + } + this.sawUnambiguousESM = true; + } else if (this.isContextual(105) || this.isContextual(97)) { + const isSource = this.isContextual(105); + if (!isSource) this.unexpected(); + this.expectPlugin(isSource ? "sourcePhaseImports" : "deferredImportEvaluation"); + if (!this.options.createImportExpressions) { + throw this.raise(Errors.DynamicImportPhaseRequiresImportExpressions, this.state.startLoc, { + phase: this.state.value + }); + } + this.next(); + node.phase = isSource ? "source" : "defer"; + return this.parseImportCall(node); + } + return this.parseMetaProperty(node, id, "meta"); + } + parseLiteralAtNode(value, type, node) { + this.addExtra(node, "rawValue", value); + this.addExtra(node, "raw", this.input.slice(node.start, this.state.end)); + node.value = value; + this.next(); + return this.finishNode(node, type); + } + parseLiteral(value, type) { + const node = this.startNode(); + return this.parseLiteralAtNode(value, type, node); + } + parseStringLiteral(value) { + return this.parseLiteral(value, "StringLiteral"); + } + parseNumericLiteral(value) { + return this.parseLiteral(value, "NumericLiteral"); + } + parseBigIntLiteral(value) { + return this.parseLiteral(value, "BigIntLiteral"); + } + parseDecimalLiteral(value) { + return this.parseLiteral(value, "DecimalLiteral"); + } + parseRegExpLiteral(value) { + const node = this.startNode(); + this.addExtra(node, "raw", this.input.slice(node.start, this.state.end)); + node.pattern = value.pattern; + node.flags = value.flags; + this.next(); + return this.finishNode(node, "RegExpLiteral"); + } + parseBooleanLiteral(value) { + const node = this.startNode(); + node.value = value; + this.next(); + return this.finishNode(node, "BooleanLiteral"); + } + parseNullLiteral() { + const node = this.startNode(); + this.next(); + return this.finishNode(node, "NullLiteral"); + } + parseParenAndDistinguishExpression(canBeArrow) { + const startLoc = this.state.startLoc; + let val; + this.next(); + this.expressionScope.enter(newArrowHeadScope()); + const oldMaybeInArrowParameters = this.state.maybeInArrowParameters; + const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody; + this.state.maybeInArrowParameters = true; + this.state.inFSharpPipelineDirectBody = false; + const innerStartLoc = this.state.startLoc; + const exprList = []; + const refExpressionErrors = new ExpressionErrors(); + let first = true; + let spreadStartLoc; + let optionalCommaStartLoc; + while (!this.match(11)) { + if (first) { + first = false; + } else { + this.expect(12, refExpressionErrors.optionalParametersLoc === null ? null : refExpressionErrors.optionalParametersLoc); + if (this.match(11)) { + optionalCommaStartLoc = this.state.startLoc; + break; + } + } + if (this.match(21)) { + const spreadNodeStartLoc = this.state.startLoc; + spreadStartLoc = this.state.startLoc; + exprList.push(this.parseParenItem(this.parseRestBinding(), spreadNodeStartLoc)); + if (!this.checkCommaAfterRest(41)) { + break; + } + } else { + exprList.push(this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem)); + } + } + const innerEndLoc = this.state.lastTokEndLoc; + this.expect(11); + this.state.maybeInArrowParameters = oldMaybeInArrowParameters; + this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody; + let arrowNode = this.startNodeAt(startLoc); + if (canBeArrow && this.shouldParseArrow(exprList) && (arrowNode = this.parseArrow(arrowNode))) { + this.checkDestructuringPrivate(refExpressionErrors); + this.expressionScope.validateAsPattern(); + this.expressionScope.exit(); + this.parseArrowExpression(arrowNode, exprList, false); + return arrowNode; + } + this.expressionScope.exit(); + if (!exprList.length) { + this.unexpected(this.state.lastTokStartLoc); + } + if (optionalCommaStartLoc) this.unexpected(optionalCommaStartLoc); + if (spreadStartLoc) this.unexpected(spreadStartLoc); + this.checkExpressionErrors(refExpressionErrors, true); + this.toReferencedListDeep(exprList, true); + if (exprList.length > 1) { + val = this.startNodeAt(innerStartLoc); + val.expressions = exprList; + this.finishNode(val, "SequenceExpression"); + this.resetEndLocation(val, innerEndLoc); + } else { + val = exprList[0]; + } + return this.wrapParenthesis(startLoc, val); + } + wrapParenthesis(startLoc, expression) { + if (!this.options.createParenthesizedExpressions) { + this.addExtra(expression, "parenthesized", true); + this.addExtra(expression, "parenStart", startLoc.index); + this.takeSurroundingComments(expression, startLoc.index, this.state.lastTokEndLoc.index); + return expression; + } + const parenExpression = this.startNodeAt(startLoc); + parenExpression.expression = expression; + return this.finishNode(parenExpression, "ParenthesizedExpression"); + } + shouldParseArrow(params) { + return !this.canInsertSemicolon(); + } + parseArrow(node) { + if (this.eat(19)) { + return node; + } + } + parseParenItem(node, startLoc) { + return node; + } + parseNewOrNewTarget() { + const node = this.startNode(); + this.next(); + if (this.match(16)) { + const meta = this.createIdentifier(this.startNodeAtNode(node), "new"); + this.next(); + const metaProp = this.parseMetaProperty(node, meta, "target"); + if (!this.scope.inNonArrowFunction && !this.scope.inClass && !this.options.allowNewTargetOutsideFunction) { + this.raise(Errors.UnexpectedNewTarget, metaProp); + } + return metaProp; + } + return this.parseNew(node); + } + parseNew(node) { + this.parseNewCallee(node); + if (this.eat(10)) { + const args = this.parseExprList(11); + this.toReferencedList(args); + node.arguments = args; + } else { + node.arguments = []; + } + return this.finishNode(node, "NewExpression"); + } + parseNewCallee(node) { + const isImport = this.match(83); + const callee = this.parseNoCallExpr(); + node.callee = callee; + if (isImport && (callee.type === "Import" || callee.type === "ImportExpression")) { + this.raise(Errors.ImportCallNotNewExpression, callee); + } + } + parseTemplateElement(isTagged) { + const { + start, + startLoc, + end, + value + } = this.state; + const elemStart = start + 1; + const elem = this.startNodeAt(createPositionWithColumnOffset(startLoc, 1)); + if (value === null) { + if (!isTagged) { + this.raise(Errors.InvalidEscapeSequenceTemplate, createPositionWithColumnOffset(this.state.firstInvalidTemplateEscapePos, 1)); + } + } + const isTail = this.match(24); + const endOffset = isTail ? -1 : -2; + const elemEnd = end + endOffset; + elem.value = { + raw: this.input.slice(elemStart, elemEnd).replace(/\r\n?/g, "\n"), + cooked: value === null ? null : value.slice(1, endOffset) + }; + elem.tail = isTail; + this.next(); + const finishedNode = this.finishNode(elem, "TemplateElement"); + this.resetEndLocation(finishedNode, createPositionWithColumnOffset(this.state.lastTokEndLoc, endOffset)); + return finishedNode; + } + parseTemplate(isTagged) { + const node = this.startNode(); + let curElt = this.parseTemplateElement(isTagged); + const quasis = [curElt]; + const substitutions = []; + while (!curElt.tail) { + substitutions.push(this.parseTemplateSubstitution()); + this.readTemplateContinuation(); + quasis.push(curElt = this.parseTemplateElement(isTagged)); + } + node.expressions = substitutions; + node.quasis = quasis; + return this.finishNode(node, "TemplateLiteral"); + } + parseTemplateSubstitution() { + return this.parseExpression(); + } + parseObjectLike(close, isPattern, isRecord, refExpressionErrors) { + if (isRecord) { + this.expectPlugin("recordAndTuple"); + } + const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody; + this.state.inFSharpPipelineDirectBody = false; + const propHash = Object.create(null); + let first = true; + const node = this.startNode(); + node.properties = []; + this.next(); + while (!this.match(close)) { + if (first) { + first = false; + } else { + this.expect(12); + if (this.match(close)) { + this.addTrailingCommaExtraToNode(node); + break; + } + } + let prop; + if (isPattern) { + prop = this.parseBindingProperty(); + } else { + prop = this.parsePropertyDefinition(refExpressionErrors); + this.checkProto(prop, isRecord, propHash, refExpressionErrors); + } + if (isRecord && !this.isObjectProperty(prop) && prop.type !== "SpreadElement") { + this.raise(Errors.InvalidRecordProperty, prop); + } + { + if (prop.shorthand) { + this.addExtra(prop, "shorthand", true); + } + } + node.properties.push(prop); + } + this.next(); + this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody; + let type = "ObjectExpression"; + if (isPattern) { + type = "ObjectPattern"; + } else if (isRecord) { + type = "RecordExpression"; + } + return this.finishNode(node, type); + } + addTrailingCommaExtraToNode(node) { + this.addExtra(node, "trailingComma", this.state.lastTokStartLoc.index); + this.addExtra(node, "trailingCommaLoc", this.state.lastTokStartLoc, false); + } + maybeAsyncOrAccessorProp(prop) { + return !prop.computed && prop.key.type === "Identifier" && (this.isLiteralPropertyName() || this.match(0) || this.match(55)); + } + parsePropertyDefinition(refExpressionErrors) { + let decorators = []; + if (this.match(26)) { + if (this.hasPlugin("decorators")) { + this.raise(Errors.UnsupportedPropertyDecorator, this.state.startLoc); + } + while (this.match(26)) { + decorators.push(this.parseDecorator()); + } + } + const prop = this.startNode(); + let isAsync = false; + let isAccessor = false; + let startLoc; + if (this.match(21)) { + if (decorators.length) this.unexpected(); + return this.parseSpread(); + } + if (decorators.length) { + prop.decorators = decorators; + decorators = []; + } + prop.method = false; + if (refExpressionErrors) { + startLoc = this.state.startLoc; + } + let isGenerator = this.eat(55); + this.parsePropertyNamePrefixOperator(prop); + const containsEsc = this.state.containsEsc; + this.parsePropertyName(prop, refExpressionErrors); + if (!isGenerator && !containsEsc && this.maybeAsyncOrAccessorProp(prop)) { + const { + key + } = prop; + const keyName = key.name; + if (keyName === "async" && !this.hasPrecedingLineBreak()) { + isAsync = true; + this.resetPreviousNodeTrailingComments(key); + isGenerator = this.eat(55); + this.parsePropertyName(prop); + } + if (keyName === "get" || keyName === "set") { + isAccessor = true; + this.resetPreviousNodeTrailingComments(key); + prop.kind = keyName; + if (this.match(55)) { + isGenerator = true; + this.raise(Errors.AccessorIsGenerator, this.state.curPosition(), { + kind: keyName + }); + this.next(); + } + this.parsePropertyName(prop); + } + } + return this.parseObjPropValue(prop, startLoc, isGenerator, isAsync, false, isAccessor, refExpressionErrors); + } + getGetterSetterExpectedParamCount(method) { + return method.kind === "get" ? 0 : 1; + } + getObjectOrClassMethodParams(method) { + return method.params; + } + checkGetterSetterParams(method) { + var _params; + const paramCount = this.getGetterSetterExpectedParamCount(method); + const params = this.getObjectOrClassMethodParams(method); + if (params.length !== paramCount) { + this.raise(method.kind === "get" ? Errors.BadGetterArity : Errors.BadSetterArity, method); + } + if (method.kind === "set" && ((_params = params[params.length - 1]) == null ? void 0 : _params.type) === "RestElement") { + this.raise(Errors.BadSetterRestParameter, method); + } + } + parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) { + if (isAccessor) { + const finishedProp = this.parseMethod(prop, isGenerator, false, false, false, "ObjectMethod"); + this.checkGetterSetterParams(finishedProp); + return finishedProp; + } + if (isAsync || isGenerator || this.match(10)) { + if (isPattern) this.unexpected(); + prop.kind = "method"; + prop.method = true; + return this.parseMethod(prop, isGenerator, isAsync, false, false, "ObjectMethod"); + } + } + parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors) { + prop.shorthand = false; + if (this.eat(14)) { + prop.value = isPattern ? this.parseMaybeDefault(this.state.startLoc) : this.parseMaybeAssignAllowIn(refExpressionErrors); + return this.finishNode(prop, "ObjectProperty"); + } + if (!prop.computed && prop.key.type === "Identifier") { + this.checkReservedWord(prop.key.name, prop.key.loc.start, true, false); + if (isPattern) { + prop.value = this.parseMaybeDefault(startLoc, cloneIdentifier(prop.key)); + } else if (this.match(29)) { + const shorthandAssignLoc = this.state.startLoc; + if (refExpressionErrors != null) { + if (refExpressionErrors.shorthandAssignLoc === null) { + refExpressionErrors.shorthandAssignLoc = shorthandAssignLoc; + } + } else { + this.raise(Errors.InvalidCoverInitializedName, shorthandAssignLoc); + } + prop.value = this.parseMaybeDefault(startLoc, cloneIdentifier(prop.key)); + } else { + prop.value = cloneIdentifier(prop.key); + } + prop.shorthand = true; + return this.finishNode(prop, "ObjectProperty"); + } + } + parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) { + const node = this.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) || this.parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors); + if (!node) this.unexpected(); + return node; + } + parsePropertyName(prop, refExpressionErrors) { + if (this.eat(0)) { + prop.computed = true; + prop.key = this.parseMaybeAssignAllowIn(); + this.expect(3); + } else { + const { + type, + value + } = this.state; + let key; + if (tokenIsKeywordOrIdentifier(type)) { + key = this.parseIdentifier(true); + } else { + switch (type) { + case 134: + key = this.parseNumericLiteral(value); + break; + case 133: + key = this.parseStringLiteral(value); + break; + case 135: + key = this.parseBigIntLiteral(value); + break; + case 136: + key = this.parseDecimalLiteral(value); + break; + case 138: + { + const privateKeyLoc = this.state.startLoc; + if (refExpressionErrors != null) { + if (refExpressionErrors.privateKeyLoc === null) { + refExpressionErrors.privateKeyLoc = privateKeyLoc; + } + } else { + this.raise(Errors.UnexpectedPrivateField, privateKeyLoc); + } + key = this.parsePrivateName(); + break; + } + default: + this.unexpected(); + } + } + prop.key = key; + if (type !== 138) { + prop.computed = false; + } + } + } + initFunction(node, isAsync) { + node.id = null; + node.generator = false; + node.async = isAsync; + } + parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) { + this.initFunction(node, isAsync); + node.generator = isGenerator; + this.scope.enter(2 | 16 | (inClassScope ? 64 : 0) | (allowDirectSuper ? 32 : 0)); + this.prodParam.enter(functionFlags(isAsync, node.generator)); + this.parseFunctionParams(node, isConstructor); + const finishedNode = this.parseFunctionBodyAndFinish(node, type, true); + this.prodParam.exit(); + this.scope.exit(); + return finishedNode; + } + parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) { + if (isTuple) { + this.expectPlugin("recordAndTuple"); + } + const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody; + this.state.inFSharpPipelineDirectBody = false; + const node = this.startNode(); + this.next(); + node.elements = this.parseExprList(close, !isTuple, refExpressionErrors, node); + this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody; + return this.finishNode(node, isTuple ? "TupleExpression" : "ArrayExpression"); + } + parseArrowExpression(node, params, isAsync, trailingCommaLoc) { + this.scope.enter(2 | 4); + let flags = functionFlags(isAsync, false); + if (!this.match(5) && this.prodParam.hasIn) { + flags |= 8; + } + this.prodParam.enter(flags); + this.initFunction(node, isAsync); + const oldMaybeInArrowParameters = this.state.maybeInArrowParameters; + if (params) { + this.state.maybeInArrowParameters = true; + this.setArrowFunctionParameters(node, params, trailingCommaLoc); + } + this.state.maybeInArrowParameters = false; + this.parseFunctionBody(node, true); + this.prodParam.exit(); + this.scope.exit(); + this.state.maybeInArrowParameters = oldMaybeInArrowParameters; + return this.finishNode(node, "ArrowFunctionExpression"); + } + setArrowFunctionParameters(node, params, trailingCommaLoc) { + this.toAssignableList(params, trailingCommaLoc, false); + node.params = params; + } + parseFunctionBodyAndFinish(node, type, isMethod = false) { + this.parseFunctionBody(node, false, isMethod); + return this.finishNode(node, type); + } + parseFunctionBody(node, allowExpression, isMethod = false) { + const isExpression = allowExpression && !this.match(5); + this.expressionScope.enter(newExpressionScope()); + if (isExpression) { + node.body = this.parseMaybeAssign(); + this.checkParams(node, false, allowExpression, false); + } else { + const oldStrict = this.state.strict; + const oldLabels = this.state.labels; + this.state.labels = []; + this.prodParam.enter(this.prodParam.currentFlags() | 4); + node.body = this.parseBlock(true, false, hasStrictModeDirective => { + const nonSimple = !this.isSimpleParamList(node.params); + if (hasStrictModeDirective && nonSimple) { + this.raise(Errors.IllegalLanguageModeDirective, (node.kind === "method" || node.kind === "constructor") && !!node.key ? node.key.loc.end : node); + } + const strictModeChanged = !oldStrict && this.state.strict; + this.checkParams(node, !this.state.strict && !allowExpression && !isMethod && !nonSimple, allowExpression, strictModeChanged); + if (this.state.strict && node.id) { + this.checkIdentifier(node.id, 65, strictModeChanged); + } + }); + this.prodParam.exit(); + this.state.labels = oldLabels; + } + this.expressionScope.exit(); + } + isSimpleParameter(node) { + return node.type === "Identifier"; + } + isSimpleParamList(params) { + for (let i = 0, len = params.length; i < len; i++) { + if (!this.isSimpleParameter(params[i])) return false; + } + return true; + } + checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged = true) { + const checkClashes = !allowDuplicates && new Set(); + const formalParameters = { + type: "FormalParameters" + }; + for (const param of node.params) { + this.checkLVal(param, formalParameters, 5, checkClashes, strictModeChanged); + } + } + parseExprList(close, allowEmpty, refExpressionErrors, nodeForExtra) { + const elts = []; + let first = true; + while (!this.eat(close)) { + if (first) { + first = false; + } else { + this.expect(12); + if (this.match(close)) { + if (nodeForExtra) { + this.addTrailingCommaExtraToNode(nodeForExtra); + } + this.next(); + break; + } + } + elts.push(this.parseExprListItem(allowEmpty, refExpressionErrors)); + } + return elts; + } + parseExprListItem(allowEmpty, refExpressionErrors, allowPlaceholder) { + let elt; + if (this.match(12)) { + if (!allowEmpty) { + this.raise(Errors.UnexpectedToken, this.state.curPosition(), { + unexpected: "," + }); + } + elt = null; + } else if (this.match(21)) { + const spreadNodeStartLoc = this.state.startLoc; + elt = this.parseParenItem(this.parseSpread(refExpressionErrors), spreadNodeStartLoc); + } else if (this.match(17)) { + this.expectPlugin("partialApplication"); + if (!allowPlaceholder) { + this.raise(Errors.UnexpectedArgumentPlaceholder, this.state.startLoc); + } + const node = this.startNode(); + this.next(); + elt = this.finishNode(node, "ArgumentPlaceholder"); + } else { + elt = this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem); + } + return elt; + } + parseIdentifier(liberal) { + const node = this.startNode(); + const name = this.parseIdentifierName(liberal); + return this.createIdentifier(node, name); + } + createIdentifier(node, name) { + node.name = name; + node.loc.identifierName = name; + return this.finishNode(node, "Identifier"); + } + parseIdentifierName(liberal) { + let name; + const { + startLoc, + type + } = this.state; + if (tokenIsKeywordOrIdentifier(type)) { + name = this.state.value; + } else { + this.unexpected(); + } + const tokenIsKeyword = tokenKeywordOrIdentifierIsKeyword(type); + if (liberal) { + if (tokenIsKeyword) { + this.replaceToken(132); + } + } else { + this.checkReservedWord(name, startLoc, tokenIsKeyword, false); + } + this.next(); + return name; + } + checkReservedWord(word, startLoc, checkKeywords, isBinding) { + if (word.length > 10) { + return; + } + if (!canBeReservedWord(word)) { + return; + } + if (checkKeywords && isKeyword(word)) { + this.raise(Errors.UnexpectedKeyword, startLoc, { + keyword: word + }); + return; + } + const reservedTest = !this.state.strict ? isReservedWord : isBinding ? isStrictBindReservedWord : isStrictReservedWord; + if (reservedTest(word, this.inModule)) { + this.raise(Errors.UnexpectedReservedWord, startLoc, { + reservedWord: word + }); + return; + } else if (word === "yield") { + if (this.prodParam.hasYield) { + this.raise(Errors.YieldBindingIdentifier, startLoc); + return; + } + } else if (word === "await") { + if (this.prodParam.hasAwait) { + this.raise(Errors.AwaitBindingIdentifier, startLoc); + return; + } + if (this.scope.inStaticBlock) { + this.raise(Errors.AwaitBindingIdentifierInStaticBlock, startLoc); + return; + } + this.expressionScope.recordAsyncArrowParametersError(startLoc); + } else if (word === "arguments") { + if (this.scope.inClassAndNotInNonArrowFunction) { + this.raise(Errors.ArgumentsInClass, startLoc); + return; + } + } + } + recordAwaitIfAllowed() { + const isAwaitAllowed = this.prodParam.hasAwait || this.options.allowAwaitOutsideFunction && !this.scope.inFunction; + if (isAwaitAllowed && !this.scope.inFunction) { + this.state.hasTopLevelAwait = true; + } + return isAwaitAllowed; + } + parseAwait(startLoc) { + const node = this.startNodeAt(startLoc); + this.expressionScope.recordParameterInitializerError(Errors.AwaitExpressionFormalParameter, node); + if (this.eat(55)) { + this.raise(Errors.ObsoleteAwaitStar, node); + } + if (!this.scope.inFunction && !this.options.allowAwaitOutsideFunction) { + if (this.isAmbiguousAwait()) { + this.ambiguousScriptDifferentAst = true; + } else { + this.sawUnambiguousESM = true; + } + } + if (!this.state.soloAwait) { + node.argument = this.parseMaybeUnary(null, true); + } + return this.finishNode(node, "AwaitExpression"); + } + isAmbiguousAwait() { + if (this.hasPrecedingLineBreak()) return true; + const { + type + } = this.state; + return type === 53 || type === 10 || type === 0 || tokenIsTemplate(type) || type === 102 && !this.state.containsEsc || type === 137 || type === 56 || this.hasPlugin("v8intrinsic") && type === 54; + } + parseYield() { + const node = this.startNode(); + this.expressionScope.recordParameterInitializerError(Errors.YieldInParameter, node); + this.next(); + let delegating = false; + let argument = null; + if (!this.hasPrecedingLineBreak()) { + delegating = this.eat(55); + switch (this.state.type) { + case 13: + case 139: + case 8: + case 11: + case 3: + case 9: + case 14: + case 12: + if (!delegating) break; + default: + argument = this.parseMaybeAssign(); + } + } + node.delegate = delegating; + node.argument = argument; + return this.finishNode(node, "YieldExpression"); + } + parseImportCall(node) { + this.next(); + node.source = this.parseMaybeAssignAllowIn(); + if (this.hasPlugin("importAttributes") || this.hasPlugin("importAssertions")) { + node.options = null; + } + if (this.eat(12)) { + this.expectImportAttributesPlugin(); + if (!this.match(11)) { + node.options = this.parseMaybeAssignAllowIn(); + this.eat(12); + } + } + this.expect(11); + return this.finishNode(node, "ImportExpression"); + } + checkPipelineAtInfixOperator(left, leftStartLoc) { + if (this.hasPlugin(["pipelineOperator", { + proposal: "smart" + }])) { + if (left.type === "SequenceExpression") { + this.raise(Errors.PipelineHeadSequenceExpression, leftStartLoc); + } + } + } + parseSmartPipelineBodyInStyle(childExpr, startLoc) { + if (this.isSimpleReference(childExpr)) { + const bodyNode = this.startNodeAt(startLoc); + bodyNode.callee = childExpr; + return this.finishNode(bodyNode, "PipelineBareFunction"); + } else { + const bodyNode = this.startNodeAt(startLoc); + this.checkSmartPipeTopicBodyEarlyErrors(startLoc); + bodyNode.expression = childExpr; + return this.finishNode(bodyNode, "PipelineTopicExpression"); + } + } + isSimpleReference(expression) { + switch (expression.type) { + case "MemberExpression": + return !expression.computed && this.isSimpleReference(expression.object); + case "Identifier": + return true; + default: + return false; + } + } + checkSmartPipeTopicBodyEarlyErrors(startLoc) { + if (this.match(19)) { + throw this.raise(Errors.PipelineBodyNoArrow, this.state.startLoc); + } + if (!this.topicReferenceWasUsedInCurrentContext()) { + this.raise(Errors.PipelineTopicUnused, startLoc); + } + } + withTopicBindingContext(callback) { + const outerContextTopicState = this.state.topicContext; + this.state.topicContext = { + maxNumOfResolvableTopics: 1, + maxTopicIndex: null + }; + try { + return callback(); + } finally { + this.state.topicContext = outerContextTopicState; + } + } + withSmartMixTopicForbiddingContext(callback) { + if (this.hasPlugin(["pipelineOperator", { + proposal: "smart" + }])) { + const outerContextTopicState = this.state.topicContext; + this.state.topicContext = { + maxNumOfResolvableTopics: 0, + maxTopicIndex: null + }; + try { + return callback(); + } finally { + this.state.topicContext = outerContextTopicState; + } + } else { + return callback(); + } + } + withSoloAwaitPermittingContext(callback) { + const outerContextSoloAwaitState = this.state.soloAwait; + this.state.soloAwait = true; + try { + return callback(); + } finally { + this.state.soloAwait = outerContextSoloAwaitState; + } + } + allowInAnd(callback) { + const flags = this.prodParam.currentFlags(); + const prodParamToSet = 8 & ~flags; + if (prodParamToSet) { + this.prodParam.enter(flags | 8); + try { + return callback(); + } finally { + this.prodParam.exit(); + } + } + return callback(); + } + disallowInAnd(callback) { + const flags = this.prodParam.currentFlags(); + const prodParamToClear = 8 & flags; + if (prodParamToClear) { + this.prodParam.enter(flags & ~8); + try { + return callback(); + } finally { + this.prodParam.exit(); + } + } + return callback(); + } + registerTopicReference() { + this.state.topicContext.maxTopicIndex = 0; + } + topicReferenceIsAllowedInCurrentContext() { + return this.state.topicContext.maxNumOfResolvableTopics >= 1; + } + topicReferenceWasUsedInCurrentContext() { + return this.state.topicContext.maxTopicIndex != null && this.state.topicContext.maxTopicIndex >= 0; + } + parseFSharpPipelineBody(prec) { + const startLoc = this.state.startLoc; + this.state.potentialArrowAt = this.state.start; + const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody; + this.state.inFSharpPipelineDirectBody = true; + const ret = this.parseExprOp(this.parseMaybeUnaryOrPrivate(), startLoc, prec); + this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody; + return ret; + } + parseModuleExpression() { + this.expectPlugin("moduleBlocks"); + const node = this.startNode(); + this.next(); + if (!this.match(5)) { + this.unexpected(null, 5); + } + const program = this.startNodeAt(this.state.endLoc); + this.next(); + const revertScopes = this.initializeScopes(true); + this.enterInitialScopes(); + try { + node.body = this.parseProgram(program, 8, "module"); + } finally { + revertScopes(); + } + return this.finishNode(node, "ModuleExpression"); + } + parsePropertyNamePrefixOperator(prop) {} +} +const loopLabel = { + kind: 1 + }, + switchLabel = { + kind: 2 + }; +const loneSurrogate = /[\uD800-\uDFFF]/u; +const keywordRelationalOperator = /in(?:stanceof)?/y; +function babel7CompatTokens(tokens, input) { + for (let i = 0; i < tokens.length; i++) { + const token = tokens[i]; + const { + type + } = token; + if (typeof type === "number") { + { + if (type === 138) { + const { + loc, + start, + value, + end + } = token; + const hashEndPos = start + 1; + const hashEndLoc = createPositionWithColumnOffset(loc.start, 1); + tokens.splice(i, 1, new Token({ + type: getExportedToken(27), + value: "#", + start: start, + end: hashEndPos, + startLoc: loc.start, + endLoc: hashEndLoc + }), new Token({ + type: getExportedToken(132), + value: value, + start: hashEndPos, + end: end, + startLoc: hashEndLoc, + endLoc: loc.end + })); + i++; + continue; + } + if (tokenIsTemplate(type)) { + const { + loc, + start, + value, + end + } = token; + const backquoteEnd = start + 1; + const backquoteEndLoc = createPositionWithColumnOffset(loc.start, 1); + let startToken; + if (input.charCodeAt(start) === 96) { + startToken = new Token({ + type: getExportedToken(22), + value: "`", + start: start, + end: backquoteEnd, + startLoc: loc.start, + endLoc: backquoteEndLoc + }); + } else { + startToken = new Token({ + type: getExportedToken(8), + value: "}", + start: start, + end: backquoteEnd, + startLoc: loc.start, + endLoc: backquoteEndLoc + }); + } + let templateValue, templateElementEnd, templateElementEndLoc, endToken; + if (type === 24) { + templateElementEnd = end - 1; + templateElementEndLoc = createPositionWithColumnOffset(loc.end, -1); + templateValue = value === null ? null : value.slice(1, -1); + endToken = new Token({ + type: getExportedToken(22), + value: "`", + start: templateElementEnd, + end: end, + startLoc: templateElementEndLoc, + endLoc: loc.end + }); + } else { + templateElementEnd = end - 2; + templateElementEndLoc = createPositionWithColumnOffset(loc.end, -2); + templateValue = value === null ? null : value.slice(1, -2); + endToken = new Token({ + type: getExportedToken(23), + value: "${", + start: templateElementEnd, + end: end, + startLoc: templateElementEndLoc, + endLoc: loc.end + }); + } + tokens.splice(i, 1, startToken, new Token({ + type: getExportedToken(20), + value: templateValue, + start: backquoteEnd, + end: templateElementEnd, + startLoc: backquoteEndLoc, + endLoc: templateElementEndLoc + }), endToken); + i += 2; + continue; + } + } + token.type = getExportedToken(type); + } + } + return tokens; +} +class StatementParser extends ExpressionParser { + parseTopLevel(file, program) { + file.program = this.parseProgram(program); + file.comments = this.comments; + if (this.options.tokens) { + file.tokens = babel7CompatTokens(this.tokens, this.input); + } + return this.finishNode(file, "File"); + } + parseProgram(program, end = 139, sourceType = this.options.sourceType) { + program.sourceType = sourceType; + program.interpreter = this.parseInterpreterDirective(); + this.parseBlockBody(program, true, true, end); + if (this.inModule) { + if (!this.options.allowUndeclaredExports && this.scope.undefinedExports.size > 0) { + for (const [localName, at] of Array.from(this.scope.undefinedExports)) { + this.raise(Errors.ModuleExportUndefined, at, { + localName + }); + } + } + this.addExtra(program, "topLevelAwait", this.state.hasTopLevelAwait); + } + let finishedProgram; + if (end === 139) { + finishedProgram = this.finishNode(program, "Program"); + } else { + finishedProgram = this.finishNodeAt(program, "Program", createPositionWithColumnOffset(this.state.startLoc, -1)); + } + return finishedProgram; + } + stmtToDirective(stmt) { + const directive = stmt; + directive.type = "Directive"; + directive.value = directive.expression; + delete directive.expression; + const directiveLiteral = directive.value; + const expressionValue = directiveLiteral.value; + const raw = this.input.slice(directiveLiteral.start, directiveLiteral.end); + const val = directiveLiteral.value = raw.slice(1, -1); + this.addExtra(directiveLiteral, "raw", raw); + this.addExtra(directiveLiteral, "rawValue", val); + this.addExtra(directiveLiteral, "expressionValue", expressionValue); + directiveLiteral.type = "DirectiveLiteral"; + return directive; + } + parseInterpreterDirective() { + if (!this.match(28)) { + return null; + } + const node = this.startNode(); + node.value = this.state.value; + this.next(); + return this.finishNode(node, "InterpreterDirective"); + } + isLet() { + if (!this.isContextual(100)) { + return false; + } + return this.hasFollowingBindingAtom(); + } + chStartsBindingIdentifier(ch, pos) { + if (isIdentifierStart(ch)) { + keywordRelationalOperator.lastIndex = pos; + if (keywordRelationalOperator.test(this.input)) { + const endCh = this.codePointAtPos(keywordRelationalOperator.lastIndex); + if (!isIdentifierChar(endCh) && endCh !== 92) { + return false; + } + } + return true; + } else if (ch === 92) { + return true; + } else { + return false; + } + } + chStartsBindingPattern(ch) { + return ch === 91 || ch === 123; + } + hasFollowingBindingAtom() { + const next = this.nextTokenStart(); + const nextCh = this.codePointAtPos(next); + return this.chStartsBindingPattern(nextCh) || this.chStartsBindingIdentifier(nextCh, next); + } + hasInLineFollowingBindingIdentifierOrBrace() { + const next = this.nextTokenInLineStart(); + const nextCh = this.codePointAtPos(next); + return nextCh === 123 || this.chStartsBindingIdentifier(nextCh, next); + } + startsUsingForOf() { + const { + type, + containsEsc + } = this.lookahead(); + if (type === 102 && !containsEsc) { + return false; + } else if (tokenIsIdentifier(type) && !this.hasFollowingLineBreak()) { + this.expectPlugin("explicitResourceManagement"); + return true; + } + } + startsAwaitUsing() { + let next = this.nextTokenInLineStart(); + if (this.isUnparsedContextual(next, "using")) { + next = this.nextTokenInLineStartSince(next + 5); + const nextCh = this.codePointAtPos(next); + if (this.chStartsBindingIdentifier(nextCh, next)) { + this.expectPlugin("explicitResourceManagement"); + return true; + } + } + return false; + } + parseModuleItem() { + return this.parseStatementLike(1 | 2 | 4 | 8); + } + parseStatementListItem() { + return this.parseStatementLike(2 | 4 | (!this.options.annexB || this.state.strict ? 0 : 8)); + } + parseStatementOrSloppyAnnexBFunctionDeclaration(allowLabeledFunction = false) { + let flags = 0; + if (this.options.annexB && !this.state.strict) { + flags |= 4; + if (allowLabeledFunction) { + flags |= 8; + } + } + return this.parseStatementLike(flags); + } + parseStatement() { + return this.parseStatementLike(0); + } + parseStatementLike(flags) { + let decorators = null; + if (this.match(26)) { + decorators = this.parseDecorators(true); + } + return this.parseStatementContent(flags, decorators); + } + parseStatementContent(flags, decorators) { + const startType = this.state.type; + const node = this.startNode(); + const allowDeclaration = !!(flags & 2); + const allowFunctionDeclaration = !!(flags & 4); + const topLevel = flags & 1; + switch (startType) { + case 60: + return this.parseBreakContinueStatement(node, true); + case 63: + return this.parseBreakContinueStatement(node, false); + case 64: + return this.parseDebuggerStatement(node); + case 90: + return this.parseDoWhileStatement(node); + case 91: + return this.parseForStatement(node); + case 68: + if (this.lookaheadCharCode() === 46) break; + if (!allowFunctionDeclaration) { + this.raise(this.state.strict ? Errors.StrictFunction : this.options.annexB ? Errors.SloppyFunctionAnnexB : Errors.SloppyFunction, this.state.startLoc); + } + return this.parseFunctionStatement(node, false, !allowDeclaration && allowFunctionDeclaration); + case 80: + if (!allowDeclaration) this.unexpected(); + return this.parseClass(this.maybeTakeDecorators(decorators, node), true); + case 69: + return this.parseIfStatement(node); + case 70: + return this.parseReturnStatement(node); + case 71: + return this.parseSwitchStatement(node); + case 72: + return this.parseThrowStatement(node); + case 73: + return this.parseTryStatement(node); + case 96: + if (!this.state.containsEsc && this.startsAwaitUsing()) { + if (!this.recordAwaitIfAllowed()) { + this.raise(Errors.AwaitUsingNotInAsyncContext, node); + } else if (!allowDeclaration) { + this.raise(Errors.UnexpectedLexicalDeclaration, node); + } + this.next(); + return this.parseVarStatement(node, "await using"); + } + break; + case 107: + if (this.state.containsEsc || !this.hasInLineFollowingBindingIdentifierOrBrace()) { + break; + } + this.expectPlugin("explicitResourceManagement"); + if (!this.scope.inModule && this.scope.inTopLevel) { + this.raise(Errors.UnexpectedUsingDeclaration, this.state.startLoc); + } else if (!allowDeclaration) { + this.raise(Errors.UnexpectedLexicalDeclaration, this.state.startLoc); + } + return this.parseVarStatement(node, "using"); + case 100: + { + if (this.state.containsEsc) { + break; + } + const next = this.nextTokenStart(); + const nextCh = this.codePointAtPos(next); + if (nextCh !== 91) { + if (!allowDeclaration && this.hasFollowingLineBreak()) break; + if (!this.chStartsBindingIdentifier(nextCh, next) && nextCh !== 123) { + break; + } + } + } + case 75: + { + if (!allowDeclaration) { + this.raise(Errors.UnexpectedLexicalDeclaration, this.state.startLoc); + } + } + case 74: + { + const kind = this.state.value; + return this.parseVarStatement(node, kind); + } + case 92: + return this.parseWhileStatement(node); + case 76: + return this.parseWithStatement(node); + case 5: + return this.parseBlock(); + case 13: + return this.parseEmptyStatement(node); + case 83: + { + const nextTokenCharCode = this.lookaheadCharCode(); + if (nextTokenCharCode === 40 || nextTokenCharCode === 46) { + break; + } + } + case 82: + { + if (!this.options.allowImportExportEverywhere && !topLevel) { + this.raise(Errors.UnexpectedImportExport, this.state.startLoc); + } + this.next(); + let result; + if (startType === 83) { + result = this.parseImport(node); + if (result.type === "ImportDeclaration" && (!result.importKind || result.importKind === "value")) { + this.sawUnambiguousESM = true; + } + } else { + result = this.parseExport(node, decorators); + if (result.type === "ExportNamedDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportAllDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportDefaultDeclaration") { + this.sawUnambiguousESM = true; + } + } + this.assertModuleNodeAllowed(result); + return result; + } + default: + { + if (this.isAsyncFunction()) { + if (!allowDeclaration) { + this.raise(Errors.AsyncFunctionInSingleStatementContext, this.state.startLoc); + } + this.next(); + return this.parseFunctionStatement(node, true, !allowDeclaration && allowFunctionDeclaration); + } + } + } + const maybeName = this.state.value; + const expr = this.parseExpression(); + if (tokenIsIdentifier(startType) && expr.type === "Identifier" && this.eat(14)) { + return this.parseLabeledStatement(node, maybeName, expr, flags); + } else { + return this.parseExpressionStatement(node, expr, decorators); + } + } + assertModuleNodeAllowed(node) { + if (!this.options.allowImportExportEverywhere && !this.inModule) { + this.raise(Errors.ImportOutsideModule, node); + } + } + decoratorsEnabledBeforeExport() { + if (this.hasPlugin("decorators-legacy")) return true; + return this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport") !== false; + } + maybeTakeDecorators(maybeDecorators, classNode, exportNode) { + if (maybeDecorators) { + if (classNode.decorators && classNode.decorators.length > 0) { + if (typeof this.getPluginOption("decorators", "decoratorsBeforeExport") !== "boolean") { + this.raise(Errors.DecoratorsBeforeAfterExport, classNode.decorators[0]); + } + classNode.decorators.unshift(...maybeDecorators); + } else { + classNode.decorators = maybeDecorators; + } + this.resetStartLocationFromNode(classNode, maybeDecorators[0]); + if (exportNode) this.resetStartLocationFromNode(exportNode, classNode); + } + return classNode; + } + canHaveLeadingDecorator() { + return this.match(80); + } + parseDecorators(allowExport) { + const decorators = []; + do { + decorators.push(this.parseDecorator()); + } while (this.match(26)); + if (this.match(82)) { + if (!allowExport) { + this.unexpected(); + } + if (!this.decoratorsEnabledBeforeExport()) { + this.raise(Errors.DecoratorExportClass, this.state.startLoc); + } + } else if (!this.canHaveLeadingDecorator()) { + throw this.raise(Errors.UnexpectedLeadingDecorator, this.state.startLoc); + } + return decorators; + } + parseDecorator() { + this.expectOnePlugin(["decorators", "decorators-legacy"]); + const node = this.startNode(); + this.next(); + if (this.hasPlugin("decorators")) { + const startLoc = this.state.startLoc; + let expr; + if (this.match(10)) { + const startLoc = this.state.startLoc; + this.next(); + expr = this.parseExpression(); + this.expect(11); + expr = this.wrapParenthesis(startLoc, expr); + const paramsStartLoc = this.state.startLoc; + node.expression = this.parseMaybeDecoratorArguments(expr); + if (this.getPluginOption("decorators", "allowCallParenthesized") === false && node.expression !== expr) { + this.raise(Errors.DecoratorArgumentsOutsideParentheses, paramsStartLoc); + } + } else { + expr = this.parseIdentifier(false); + while (this.eat(16)) { + const node = this.startNodeAt(startLoc); + node.object = expr; + if (this.match(138)) { + this.classScope.usePrivateName(this.state.value, this.state.startLoc); + node.property = this.parsePrivateName(); + } else { + node.property = this.parseIdentifier(true); + } + node.computed = false; + expr = this.finishNode(node, "MemberExpression"); + } + node.expression = this.parseMaybeDecoratorArguments(expr); + } + } else { + node.expression = this.parseExprSubscripts(); + } + return this.finishNode(node, "Decorator"); + } + parseMaybeDecoratorArguments(expr) { + if (this.eat(10)) { + const node = this.startNodeAtNode(expr); + node.callee = expr; + node.arguments = this.parseCallExpressionArguments(11, false); + this.toReferencedList(node.arguments); + return this.finishNode(node, "CallExpression"); + } + return expr; + } + parseBreakContinueStatement(node, isBreak) { + this.next(); + if (this.isLineTerminator()) { + node.label = null; + } else { + node.label = this.parseIdentifier(); + this.semicolon(); + } + this.verifyBreakContinue(node, isBreak); + return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement"); + } + verifyBreakContinue(node, isBreak) { + let i; + for (i = 0; i < this.state.labels.length; ++i) { + const lab = this.state.labels[i]; + if (node.label == null || lab.name === node.label.name) { + if (lab.kind != null && (isBreak || lab.kind === 1)) { + break; + } + if (node.label && isBreak) break; + } + } + if (i === this.state.labels.length) { + const type = isBreak ? "BreakStatement" : "ContinueStatement"; + this.raise(Errors.IllegalBreakContinue, node, { + type + }); + } + } + parseDebuggerStatement(node) { + this.next(); + this.semicolon(); + return this.finishNode(node, "DebuggerStatement"); + } + parseHeaderExpression() { + this.expect(10); + const val = this.parseExpression(); + this.expect(11); + return val; + } + parseDoWhileStatement(node) { + this.next(); + this.state.labels.push(loopLabel); + node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement()); + this.state.labels.pop(); + this.expect(92); + node.test = this.parseHeaderExpression(); + this.eat(13); + return this.finishNode(node, "DoWhileStatement"); + } + parseForStatement(node) { + this.next(); + this.state.labels.push(loopLabel); + let awaitAt = null; + if (this.isContextual(96) && this.recordAwaitIfAllowed()) { + awaitAt = this.state.startLoc; + this.next(); + } + this.scope.enter(0); + this.expect(10); + if (this.match(13)) { + if (awaitAt !== null) { + this.unexpected(awaitAt); + } + return this.parseFor(node, null); + } + const startsWithLet = this.isContextual(100); + { + const startsWithAwaitUsing = this.isContextual(96) && this.startsAwaitUsing(); + const starsWithUsingDeclaration = startsWithAwaitUsing || this.isContextual(107) && this.startsUsingForOf(); + const isLetOrUsing = startsWithLet && this.hasFollowingBindingAtom() || starsWithUsingDeclaration; + if (this.match(74) || this.match(75) || isLetOrUsing) { + const initNode = this.startNode(); + let kind; + if (startsWithAwaitUsing) { + kind = "await using"; + if (!this.recordAwaitIfAllowed()) { + this.raise(Errors.AwaitUsingNotInAsyncContext, this.state.startLoc); + } + this.next(); + } else { + kind = this.state.value; + } + this.next(); + this.parseVar(initNode, true, kind); + const init = this.finishNode(initNode, "VariableDeclaration"); + const isForIn = this.match(58); + if (isForIn && starsWithUsingDeclaration) { + this.raise(Errors.ForInUsing, init); + } + if ((isForIn || this.isContextual(102)) && init.declarations.length === 1) { + return this.parseForIn(node, init, awaitAt); + } + if (awaitAt !== null) { + this.unexpected(awaitAt); + } + return this.parseFor(node, init); + } + } + const startsWithAsync = this.isContextual(95); + const refExpressionErrors = new ExpressionErrors(); + const init = this.parseExpression(true, refExpressionErrors); + const isForOf = this.isContextual(102); + if (isForOf) { + if (startsWithLet) { + this.raise(Errors.ForOfLet, init); + } + if (awaitAt === null && startsWithAsync && init.type === "Identifier") { + this.raise(Errors.ForOfAsync, init); + } + } + if (isForOf || this.match(58)) { + this.checkDestructuringPrivate(refExpressionErrors); + this.toAssignable(init, true); + const type = isForOf ? "ForOfStatement" : "ForInStatement"; + this.checkLVal(init, { + type + }); + return this.parseForIn(node, init, awaitAt); + } else { + this.checkExpressionErrors(refExpressionErrors, true); + } + if (awaitAt !== null) { + this.unexpected(awaitAt); + } + return this.parseFor(node, init); + } + parseFunctionStatement(node, isAsync, isHangingDeclaration) { + this.next(); + return this.parseFunction(node, 1 | (isHangingDeclaration ? 2 : 0) | (isAsync ? 8 : 0)); + } + parseIfStatement(node) { + this.next(); + node.test = this.parseHeaderExpression(); + node.consequent = this.parseStatementOrSloppyAnnexBFunctionDeclaration(); + node.alternate = this.eat(66) ? this.parseStatementOrSloppyAnnexBFunctionDeclaration() : null; + return this.finishNode(node, "IfStatement"); + } + parseReturnStatement(node) { + if (!this.prodParam.hasReturn && !this.options.allowReturnOutsideFunction) { + this.raise(Errors.IllegalReturn, this.state.startLoc); + } + this.next(); + if (this.isLineTerminator()) { + node.argument = null; + } else { + node.argument = this.parseExpression(); + this.semicolon(); + } + return this.finishNode(node, "ReturnStatement"); + } + parseSwitchStatement(node) { + this.next(); + node.discriminant = this.parseHeaderExpression(); + const cases = node.cases = []; + this.expect(5); + this.state.labels.push(switchLabel); + this.scope.enter(0); + let cur; + for (let sawDefault; !this.match(8);) { + if (this.match(61) || this.match(65)) { + const isCase = this.match(61); + if (cur) this.finishNode(cur, "SwitchCase"); + cases.push(cur = this.startNode()); + cur.consequent = []; + this.next(); + if (isCase) { + cur.test = this.parseExpression(); + } else { + if (sawDefault) { + this.raise(Errors.MultipleDefaultsInSwitch, this.state.lastTokStartLoc); + } + sawDefault = true; + cur.test = null; + } + this.expect(14); + } else { + if (cur) { + cur.consequent.push(this.parseStatementListItem()); + } else { + this.unexpected(); + } + } + } + this.scope.exit(); + if (cur) this.finishNode(cur, "SwitchCase"); + this.next(); + this.state.labels.pop(); + return this.finishNode(node, "SwitchStatement"); + } + parseThrowStatement(node) { + this.next(); + if (this.hasPrecedingLineBreak()) { + this.raise(Errors.NewlineAfterThrow, this.state.lastTokEndLoc); + } + node.argument = this.parseExpression(); + this.semicolon(); + return this.finishNode(node, "ThrowStatement"); + } + parseCatchClauseParam() { + const param = this.parseBindingAtom(); + this.scope.enter(this.options.annexB && param.type === "Identifier" ? 8 : 0); + this.checkLVal(param, { + type: "CatchClause" + }, 9); + return param; + } + parseTryStatement(node) { + this.next(); + node.block = this.parseBlock(); + node.handler = null; + if (this.match(62)) { + const clause = this.startNode(); + this.next(); + if (this.match(10)) { + this.expect(10); + clause.param = this.parseCatchClauseParam(); + this.expect(11); + } else { + clause.param = null; + this.scope.enter(0); + } + clause.body = this.withSmartMixTopicForbiddingContext(() => this.parseBlock(false, false)); + this.scope.exit(); + node.handler = this.finishNode(clause, "CatchClause"); + } + node.finalizer = this.eat(67) ? this.parseBlock() : null; + if (!node.handler && !node.finalizer) { + this.raise(Errors.NoCatchOrFinally, node); + } + return this.finishNode(node, "TryStatement"); + } + parseVarStatement(node, kind, allowMissingInitializer = false) { + this.next(); + this.parseVar(node, false, kind, allowMissingInitializer); + this.semicolon(); + return this.finishNode(node, "VariableDeclaration"); + } + parseWhileStatement(node) { + this.next(); + node.test = this.parseHeaderExpression(); + this.state.labels.push(loopLabel); + node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement()); + this.state.labels.pop(); + return this.finishNode(node, "WhileStatement"); + } + parseWithStatement(node) { + if (this.state.strict) { + this.raise(Errors.StrictWith, this.state.startLoc); + } + this.next(); + node.object = this.parseHeaderExpression(); + node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement()); + return this.finishNode(node, "WithStatement"); + } + parseEmptyStatement(node) { + this.next(); + return this.finishNode(node, "EmptyStatement"); + } + parseLabeledStatement(node, maybeName, expr, flags) { + for (const label of this.state.labels) { + if (label.name === maybeName) { + this.raise(Errors.LabelRedeclaration, expr, { + labelName: maybeName + }); + } + } + const kind = tokenIsLoop(this.state.type) ? 1 : this.match(71) ? 2 : null; + for (let i = this.state.labels.length - 1; i >= 0; i--) { + const label = this.state.labels[i]; + if (label.statementStart === node.start) { + label.statementStart = this.state.start; + label.kind = kind; + } else { + break; + } + } + this.state.labels.push({ + name: maybeName, + kind: kind, + statementStart: this.state.start + }); + node.body = flags & 8 ? this.parseStatementOrSloppyAnnexBFunctionDeclaration(true) : this.parseStatement(); + this.state.labels.pop(); + node.label = expr; + return this.finishNode(node, "LabeledStatement"); + } + parseExpressionStatement(node, expr, decorators) { + node.expression = expr; + this.semicolon(); + return this.finishNode(node, "ExpressionStatement"); + } + parseBlock(allowDirectives = false, createNewLexicalScope = true, afterBlockParse) { + const node = this.startNode(); + if (allowDirectives) { + this.state.strictErrors.clear(); + } + this.expect(5); + if (createNewLexicalScope) { + this.scope.enter(0); + } + this.parseBlockBody(node, allowDirectives, false, 8, afterBlockParse); + if (createNewLexicalScope) { + this.scope.exit(); + } + return this.finishNode(node, "BlockStatement"); + } + isValidDirective(stmt) { + return stmt.type === "ExpressionStatement" && stmt.expression.type === "StringLiteral" && !stmt.expression.extra.parenthesized; + } + parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse) { + const body = node.body = []; + const directives = node.directives = []; + this.parseBlockOrModuleBlockBody(body, allowDirectives ? directives : undefined, topLevel, end, afterBlockParse); + } + parseBlockOrModuleBlockBody(body, directives, topLevel, end, afterBlockParse) { + const oldStrict = this.state.strict; + let hasStrictModeDirective = false; + let parsedNonDirective = false; + while (!this.match(end)) { + const stmt = topLevel ? this.parseModuleItem() : this.parseStatementListItem(); + if (directives && !parsedNonDirective) { + if (this.isValidDirective(stmt)) { + const directive = this.stmtToDirective(stmt); + directives.push(directive); + if (!hasStrictModeDirective && directive.value.value === "use strict") { + hasStrictModeDirective = true; + this.setStrict(true); + } + continue; + } + parsedNonDirective = true; + this.state.strictErrors.clear(); + } + body.push(stmt); + } + afterBlockParse == null || afterBlockParse.call(this, hasStrictModeDirective); + if (!oldStrict) { + this.setStrict(false); + } + this.next(); + } + parseFor(node, init) { + node.init = init; + this.semicolon(false); + node.test = this.match(13) ? null : this.parseExpression(); + this.semicolon(false); + node.update = this.match(11) ? null : this.parseExpression(); + this.expect(11); + node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement()); + this.scope.exit(); + this.state.labels.pop(); + return this.finishNode(node, "ForStatement"); + } + parseForIn(node, init, awaitAt) { + const isForIn = this.match(58); + this.next(); + if (isForIn) { + if (awaitAt !== null) this.unexpected(awaitAt); + } else { + node.await = awaitAt !== null; + } + if (init.type === "VariableDeclaration" && init.declarations[0].init != null && (!isForIn || !this.options.annexB || this.state.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier")) { + this.raise(Errors.ForInOfLoopInitializer, init, { + type: isForIn ? "ForInStatement" : "ForOfStatement" + }); + } + if (init.type === "AssignmentPattern") { + this.raise(Errors.InvalidLhs, init, { + ancestor: { + type: "ForStatement" + } + }); + } + node.left = init; + node.right = isForIn ? this.parseExpression() : this.parseMaybeAssignAllowIn(); + this.expect(11); + node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement()); + this.scope.exit(); + this.state.labels.pop(); + return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement"); + } + parseVar(node, isFor, kind, allowMissingInitializer = false) { + const declarations = node.declarations = []; + node.kind = kind; + for (;;) { + const decl = this.startNode(); + this.parseVarId(decl, kind); + decl.init = !this.eat(29) ? null : isFor ? this.parseMaybeAssignDisallowIn() : this.parseMaybeAssignAllowIn(); + if (decl.init === null && !allowMissingInitializer) { + if (decl.id.type !== "Identifier" && !(isFor && (this.match(58) || this.isContextual(102)))) { + this.raise(Errors.DeclarationMissingInitializer, this.state.lastTokEndLoc, { + kind: "destructuring" + }); + } else if ((kind === "const" || kind === "using" || kind === "await using") && !(this.match(58) || this.isContextual(102))) { + this.raise(Errors.DeclarationMissingInitializer, this.state.lastTokEndLoc, { + kind + }); + } + } + declarations.push(this.finishNode(decl, "VariableDeclarator")); + if (!this.eat(12)) break; + } + return node; + } + parseVarId(decl, kind) { + const id = this.parseBindingAtom(); + if (kind === "using" || kind === "await using") { + if (id.type === "ArrayPattern" || id.type === "ObjectPattern") { + this.raise(Errors.UsingDeclarationHasBindingPattern, id.loc.start); + } + } + this.checkLVal(id, { + type: "VariableDeclarator" + }, kind === "var" ? 5 : 8201); + decl.id = id; + } + parseAsyncFunctionExpression(node) { + return this.parseFunction(node, 8); + } + parseFunction(node, flags = 0) { + const hangingDeclaration = flags & 2; + const isDeclaration = !!(flags & 1); + const requireId = isDeclaration && !(flags & 4); + const isAsync = !!(flags & 8); + this.initFunction(node, isAsync); + if (this.match(55)) { + if (hangingDeclaration) { + this.raise(Errors.GeneratorInSingleStatementContext, this.state.startLoc); + } + this.next(); + node.generator = true; + } + if (isDeclaration) { + node.id = this.parseFunctionId(requireId); + } + const oldMaybeInArrowParameters = this.state.maybeInArrowParameters; + this.state.maybeInArrowParameters = false; + this.scope.enter(2); + this.prodParam.enter(functionFlags(isAsync, node.generator)); + if (!isDeclaration) { + node.id = this.parseFunctionId(); + } + this.parseFunctionParams(node, false); + this.withSmartMixTopicForbiddingContext(() => { + this.parseFunctionBodyAndFinish(node, isDeclaration ? "FunctionDeclaration" : "FunctionExpression"); + }); + this.prodParam.exit(); + this.scope.exit(); + if (isDeclaration && !hangingDeclaration) { + this.registerFunctionStatementId(node); + } + this.state.maybeInArrowParameters = oldMaybeInArrowParameters; + return node; + } + parseFunctionId(requireId) { + return requireId || tokenIsIdentifier(this.state.type) ? this.parseIdentifier() : null; + } + parseFunctionParams(node, isConstructor) { + this.expect(10); + this.expressionScope.enter(newParameterDeclarationScope()); + node.params = this.parseBindingList(11, 41, 2 | (isConstructor ? 4 : 0)); + this.expressionScope.exit(); + } + registerFunctionStatementId(node) { + if (!node.id) return; + this.scope.declareName(node.id.name, !this.options.annexB || this.state.strict || node.generator || node.async ? this.scope.treatFunctionsAsVar ? 5 : 8201 : 17, node.id.loc.start); + } + parseClass(node, isStatement, optionalId) { + this.next(); + const oldStrict = this.state.strict; + this.state.strict = true; + this.parseClassId(node, isStatement, optionalId); + this.parseClassSuper(node); + node.body = this.parseClassBody(!!node.superClass, oldStrict); + return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression"); + } + isClassProperty() { + return this.match(29) || this.match(13) || this.match(8); + } + isClassMethod() { + return this.match(10); + } + nameIsConstructor(key) { + return key.type === "Identifier" && key.name === "constructor" || key.type === "StringLiteral" && key.value === "constructor"; + } + isNonstaticConstructor(method) { + return !method.computed && !method.static && this.nameIsConstructor(method.key); + } + parseClassBody(hadSuperClass, oldStrict) { + this.classScope.enter(); + const state = { + hadConstructor: false, + hadSuperClass + }; + let decorators = []; + const classBody = this.startNode(); + classBody.body = []; + this.expect(5); + this.withSmartMixTopicForbiddingContext(() => { + while (!this.match(8)) { + if (this.eat(13)) { + if (decorators.length > 0) { + throw this.raise(Errors.DecoratorSemicolon, this.state.lastTokEndLoc); + } + continue; + } + if (this.match(26)) { + decorators.push(this.parseDecorator()); + continue; + } + const member = this.startNode(); + if (decorators.length) { + member.decorators = decorators; + this.resetStartLocationFromNode(member, decorators[0]); + decorators = []; + } + this.parseClassMember(classBody, member, state); + if (member.kind === "constructor" && member.decorators && member.decorators.length > 0) { + this.raise(Errors.DecoratorConstructor, member); + } + } + }); + this.state.strict = oldStrict; + this.next(); + if (decorators.length) { + throw this.raise(Errors.TrailingDecorator, this.state.startLoc); + } + this.classScope.exit(); + return this.finishNode(classBody, "ClassBody"); + } + parseClassMemberFromModifier(classBody, member) { + const key = this.parseIdentifier(true); + if (this.isClassMethod()) { + const method = member; + method.kind = "method"; + method.computed = false; + method.key = key; + method.static = false; + this.pushClassMethod(classBody, method, false, false, false, false); + return true; + } else if (this.isClassProperty()) { + const prop = member; + prop.computed = false; + prop.key = key; + prop.static = false; + classBody.body.push(this.parseClassProperty(prop)); + return true; + } + this.resetPreviousNodeTrailingComments(key); + return false; + } + parseClassMember(classBody, member, state) { + const isStatic = this.isContextual(106); + if (isStatic) { + if (this.parseClassMemberFromModifier(classBody, member)) { + return; + } + if (this.eat(5)) { + this.parseClassStaticBlock(classBody, member); + return; + } + } + this.parseClassMemberWithIsStatic(classBody, member, state, isStatic); + } + parseClassMemberWithIsStatic(classBody, member, state, isStatic) { + const publicMethod = member; + const privateMethod = member; + const publicProp = member; + const privateProp = member; + const accessorProp = member; + const method = publicMethod; + const publicMember = publicMethod; + member.static = isStatic; + this.parsePropertyNamePrefixOperator(member); + if (this.eat(55)) { + method.kind = "method"; + const isPrivateName = this.match(138); + this.parseClassElementName(method); + if (isPrivateName) { + this.pushClassPrivateMethod(classBody, privateMethod, true, false); + return; + } + if (this.isNonstaticConstructor(publicMethod)) { + this.raise(Errors.ConstructorIsGenerator, publicMethod.key); + } + this.pushClassMethod(classBody, publicMethod, true, false, false, false); + return; + } + const isContextual = !this.state.containsEsc && tokenIsIdentifier(this.state.type); + const key = this.parseClassElementName(member); + const maybeContextualKw = isContextual ? key.name : null; + const isPrivate = this.isPrivateName(key); + const maybeQuestionTokenStartLoc = this.state.startLoc; + this.parsePostMemberNameModifiers(publicMember); + if (this.isClassMethod()) { + method.kind = "method"; + if (isPrivate) { + this.pushClassPrivateMethod(classBody, privateMethod, false, false); + return; + } + const isConstructor = this.isNonstaticConstructor(publicMethod); + let allowsDirectSuper = false; + if (isConstructor) { + publicMethod.kind = "constructor"; + if (state.hadConstructor && !this.hasPlugin("typescript")) { + this.raise(Errors.DuplicateConstructor, key); + } + if (isConstructor && this.hasPlugin("typescript") && member.override) { + this.raise(Errors.OverrideOnConstructor, key); + } + state.hadConstructor = true; + allowsDirectSuper = state.hadSuperClass; + } + this.pushClassMethod(classBody, publicMethod, false, false, isConstructor, allowsDirectSuper); + } else if (this.isClassProperty()) { + if (isPrivate) { + this.pushClassPrivateProperty(classBody, privateProp); + } else { + this.pushClassProperty(classBody, publicProp); + } + } else if (maybeContextualKw === "async" && !this.isLineTerminator()) { + this.resetPreviousNodeTrailingComments(key); + const isGenerator = this.eat(55); + if (publicMember.optional) { + this.unexpected(maybeQuestionTokenStartLoc); + } + method.kind = "method"; + const isPrivate = this.match(138); + this.parseClassElementName(method); + this.parsePostMemberNameModifiers(publicMember); + if (isPrivate) { + this.pushClassPrivateMethod(classBody, privateMethod, isGenerator, true); + } else { + if (this.isNonstaticConstructor(publicMethod)) { + this.raise(Errors.ConstructorIsAsync, publicMethod.key); + } + this.pushClassMethod(classBody, publicMethod, isGenerator, true, false, false); + } + } else if ((maybeContextualKw === "get" || maybeContextualKw === "set") && !(this.match(55) && this.isLineTerminator())) { + this.resetPreviousNodeTrailingComments(key); + method.kind = maybeContextualKw; + const isPrivate = this.match(138); + this.parseClassElementName(publicMethod); + if (isPrivate) { + this.pushClassPrivateMethod(classBody, privateMethod, false, false); + } else { + if (this.isNonstaticConstructor(publicMethod)) { + this.raise(Errors.ConstructorIsAccessor, publicMethod.key); + } + this.pushClassMethod(classBody, publicMethod, false, false, false, false); + } + this.checkGetterSetterParams(publicMethod); + } else if (maybeContextualKw === "accessor" && !this.isLineTerminator()) { + this.expectPlugin("decoratorAutoAccessors"); + this.resetPreviousNodeTrailingComments(key); + const isPrivate = this.match(138); + this.parseClassElementName(publicProp); + this.pushClassAccessorProperty(classBody, accessorProp, isPrivate); + } else if (this.isLineTerminator()) { + if (isPrivate) { + this.pushClassPrivateProperty(classBody, privateProp); + } else { + this.pushClassProperty(classBody, publicProp); + } + } else { + this.unexpected(); + } + } + parseClassElementName(member) { + const { + type, + value + } = this.state; + if ((type === 132 || type === 133) && member.static && value === "prototype") { + this.raise(Errors.StaticPrototype, this.state.startLoc); + } + if (type === 138) { + if (value === "constructor") { + this.raise(Errors.ConstructorClassPrivateField, this.state.startLoc); + } + const key = this.parsePrivateName(); + member.key = key; + return key; + } + this.parsePropertyName(member); + return member.key; + } + parseClassStaticBlock(classBody, member) { + var _member$decorators; + this.scope.enter(64 | 128 | 16); + const oldLabels = this.state.labels; + this.state.labels = []; + this.prodParam.enter(0); + const body = member.body = []; + this.parseBlockOrModuleBlockBody(body, undefined, false, 8); + this.prodParam.exit(); + this.scope.exit(); + this.state.labels = oldLabels; + classBody.body.push(this.finishNode(member, "StaticBlock")); + if ((_member$decorators = member.decorators) != null && _member$decorators.length) { + this.raise(Errors.DecoratorStaticBlock, member); + } + } + pushClassProperty(classBody, prop) { + if (!prop.computed && this.nameIsConstructor(prop.key)) { + this.raise(Errors.ConstructorClassField, prop.key); + } + classBody.body.push(this.parseClassProperty(prop)); + } + pushClassPrivateProperty(classBody, prop) { + const node = this.parseClassPrivateProperty(prop); + classBody.body.push(node); + this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), 0, node.key.loc.start); + } + pushClassAccessorProperty(classBody, prop, isPrivate) { + if (!isPrivate && !prop.computed && this.nameIsConstructor(prop.key)) { + this.raise(Errors.ConstructorClassField, prop.key); + } + const node = this.parseClassAccessorProperty(prop); + classBody.body.push(node); + if (isPrivate) { + this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), 0, node.key.loc.start); + } + } + pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) { + classBody.body.push(this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true)); + } + pushClassPrivateMethod(classBody, method, isGenerator, isAsync) { + const node = this.parseMethod(method, isGenerator, isAsync, false, false, "ClassPrivateMethod", true); + classBody.body.push(node); + const kind = node.kind === "get" ? node.static ? 6 : 2 : node.kind === "set" ? node.static ? 5 : 1 : 0; + this.declareClassPrivateMethodInScope(node, kind); + } + declareClassPrivateMethodInScope(node, kind) { + this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), kind, node.key.loc.start); + } + parsePostMemberNameModifiers(methodOrProp) {} + parseClassPrivateProperty(node) { + this.parseInitializer(node); + this.semicolon(); + return this.finishNode(node, "ClassPrivateProperty"); + } + parseClassProperty(node) { + this.parseInitializer(node); + this.semicolon(); + return this.finishNode(node, "ClassProperty"); + } + parseClassAccessorProperty(node) { + this.parseInitializer(node); + this.semicolon(); + return this.finishNode(node, "ClassAccessorProperty"); + } + parseInitializer(node) { + this.scope.enter(64 | 16); + this.expressionScope.enter(newExpressionScope()); + this.prodParam.enter(0); + node.value = this.eat(29) ? this.parseMaybeAssignAllowIn() : null; + this.expressionScope.exit(); + this.prodParam.exit(); + this.scope.exit(); + } + parseClassId(node, isStatement, optionalId, bindingType = 8331) { + if (tokenIsIdentifier(this.state.type)) { + node.id = this.parseIdentifier(); + if (isStatement) { + this.declareNameFromIdentifier(node.id, bindingType); + } + } else { + if (optionalId || !isStatement) { + node.id = null; + } else { + throw this.raise(Errors.MissingClassName, this.state.startLoc); + } + } + } + parseClassSuper(node) { + node.superClass = this.eat(81) ? this.parseExprSubscripts() : null; + } + parseExport(node, decorators) { + const maybeDefaultIdentifier = this.parseMaybeImportPhase(node, true); + const hasDefault = this.maybeParseExportDefaultSpecifier(node, maybeDefaultIdentifier); + const parseAfterDefault = !hasDefault || this.eat(12); + const hasStar = parseAfterDefault && this.eatExportStar(node); + const hasNamespace = hasStar && this.maybeParseExportNamespaceSpecifier(node); + const parseAfterNamespace = parseAfterDefault && (!hasNamespace || this.eat(12)); + const isFromRequired = hasDefault || hasStar; + if (hasStar && !hasNamespace) { + if (hasDefault) this.unexpected(); + if (decorators) { + throw this.raise(Errors.UnsupportedDecoratorExport, node); + } + this.parseExportFrom(node, true); + return this.finishNode(node, "ExportAllDeclaration"); + } + const hasSpecifiers = this.maybeParseExportNamedSpecifiers(node); + if (hasDefault && parseAfterDefault && !hasStar && !hasSpecifiers) { + this.unexpected(null, 5); + } + if (hasNamespace && parseAfterNamespace) { + this.unexpected(null, 98); + } + let hasDeclaration; + if (isFromRequired || hasSpecifiers) { + hasDeclaration = false; + if (decorators) { + throw this.raise(Errors.UnsupportedDecoratorExport, node); + } + this.parseExportFrom(node, isFromRequired); + } else { + hasDeclaration = this.maybeParseExportDeclaration(node); + } + if (isFromRequired || hasSpecifiers || hasDeclaration) { + var _node2$declaration; + const node2 = node; + this.checkExport(node2, true, false, !!node2.source); + if (((_node2$declaration = node2.declaration) == null ? void 0 : _node2$declaration.type) === "ClassDeclaration") { + this.maybeTakeDecorators(decorators, node2.declaration, node2); + } else if (decorators) { + throw this.raise(Errors.UnsupportedDecoratorExport, node); + } + return this.finishNode(node2, "ExportNamedDeclaration"); + } + if (this.eat(65)) { + const node2 = node; + const decl = this.parseExportDefaultExpression(); + node2.declaration = decl; + if (decl.type === "ClassDeclaration") { + this.maybeTakeDecorators(decorators, decl, node2); + } else if (decorators) { + throw this.raise(Errors.UnsupportedDecoratorExport, node); + } + this.checkExport(node2, true, true); + return this.finishNode(node2, "ExportDefaultDeclaration"); + } + this.unexpected(null, 5); + } + eatExportStar(node) { + return this.eat(55); + } + maybeParseExportDefaultSpecifier(node, maybeDefaultIdentifier) { + if (maybeDefaultIdentifier || this.isExportDefaultSpecifier()) { + this.expectPlugin("exportDefaultFrom", maybeDefaultIdentifier == null ? void 0 : maybeDefaultIdentifier.loc.start); + const id = maybeDefaultIdentifier || this.parseIdentifier(true); + const specifier = this.startNodeAtNode(id); + specifier.exported = id; + node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")]; + return true; + } + return false; + } + maybeParseExportNamespaceSpecifier(node) { + if (this.isContextual(93)) { + var _ref, _ref$specifiers; + (_ref$specifiers = (_ref = node).specifiers) != null ? _ref$specifiers : _ref.specifiers = []; + const specifier = this.startNodeAt(this.state.lastTokStartLoc); + this.next(); + specifier.exported = this.parseModuleExportName(); + node.specifiers.push(this.finishNode(specifier, "ExportNamespaceSpecifier")); + return true; + } + return false; + } + maybeParseExportNamedSpecifiers(node) { + if (this.match(5)) { + const node2 = node; + if (!node2.specifiers) node2.specifiers = []; + const isTypeExport = node2.exportKind === "type"; + node2.specifiers.push(...this.parseExportSpecifiers(isTypeExport)); + node2.source = null; + node2.declaration = null; + if (this.hasPlugin("importAssertions")) { + node2.assertions = []; + } + return true; + } + return false; + } + maybeParseExportDeclaration(node) { + if (this.shouldParseExportDeclaration()) { + node.specifiers = []; + node.source = null; + if (this.hasPlugin("importAssertions")) { + node.assertions = []; + } + node.declaration = this.parseExportDeclaration(node); + return true; + } + return false; + } + isAsyncFunction() { + if (!this.isContextual(95)) return false; + const next = this.nextTokenInLineStart(); + return this.isUnparsedContextual(next, "function"); + } + parseExportDefaultExpression() { + const expr = this.startNode(); + if (this.match(68)) { + this.next(); + return this.parseFunction(expr, 1 | 4); + } else if (this.isAsyncFunction()) { + this.next(); + this.next(); + return this.parseFunction(expr, 1 | 4 | 8); + } + if (this.match(80)) { + return this.parseClass(expr, true, true); + } + if (this.match(26)) { + if (this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport") === true) { + this.raise(Errors.DecoratorBeforeExport, this.state.startLoc); + } + return this.parseClass(this.maybeTakeDecorators(this.parseDecorators(false), this.startNode()), true, true); + } + if (this.match(75) || this.match(74) || this.isLet()) { + throw this.raise(Errors.UnsupportedDefaultExport, this.state.startLoc); + } + const res = this.parseMaybeAssignAllowIn(); + this.semicolon(); + return res; + } + parseExportDeclaration(node) { + if (this.match(80)) { + const node = this.parseClass(this.startNode(), true, false); + return node; + } + return this.parseStatementListItem(); + } + isExportDefaultSpecifier() { + const { + type + } = this.state; + if (tokenIsIdentifier(type)) { + if (type === 95 && !this.state.containsEsc || type === 100) { + return false; + } + if ((type === 130 || type === 129) && !this.state.containsEsc) { + const { + type: nextType + } = this.lookahead(); + if (tokenIsIdentifier(nextType) && nextType !== 98 || nextType === 5) { + this.expectOnePlugin(["flow", "typescript"]); + return false; + } + } + } else if (!this.match(65)) { + return false; + } + const next = this.nextTokenStart(); + const hasFrom = this.isUnparsedContextual(next, "from"); + if (this.input.charCodeAt(next) === 44 || tokenIsIdentifier(this.state.type) && hasFrom) { + return true; + } + if (this.match(65) && hasFrom) { + const nextAfterFrom = this.input.charCodeAt(this.nextTokenStartSince(next + 4)); + return nextAfterFrom === 34 || nextAfterFrom === 39; + } + return false; + } + parseExportFrom(node, expect) { + if (this.eatContextual(98)) { + node.source = this.parseImportSource(); + this.checkExport(node); + this.maybeParseImportAttributes(node); + this.checkJSONModuleImport(node); + } else if (expect) { + this.unexpected(); + } + this.semicolon(); + } + shouldParseExportDeclaration() { + const { + type + } = this.state; + if (type === 26) { + this.expectOnePlugin(["decorators", "decorators-legacy"]); + if (this.hasPlugin("decorators")) { + if (this.getPluginOption("decorators", "decoratorsBeforeExport") === true) { + this.raise(Errors.DecoratorBeforeExport, this.state.startLoc); + } + return true; + } + } + if (this.isContextual(107)) { + this.raise(Errors.UsingDeclarationExport, this.state.startLoc); + return true; + } + if (this.isContextual(96) && this.startsAwaitUsing()) { + this.raise(Errors.UsingDeclarationExport, this.state.startLoc); + return true; + } + return type === 74 || type === 75 || type === 68 || type === 80 || this.isLet() || this.isAsyncFunction(); + } + checkExport(node, checkNames, isDefault, isFrom) { + if (checkNames) { + var _node$specifiers; + if (isDefault) { + this.checkDuplicateExports(node, "default"); + if (this.hasPlugin("exportDefaultFrom")) { + var _declaration$extra; + const declaration = node.declaration; + if (declaration.type === "Identifier" && declaration.name === "from" && declaration.end - declaration.start === 4 && !((_declaration$extra = declaration.extra) != null && _declaration$extra.parenthesized)) { + this.raise(Errors.ExportDefaultFromAsIdentifier, declaration); + } + } + } else if ((_node$specifiers = node.specifiers) != null && _node$specifiers.length) { + for (const specifier of node.specifiers) { + const { + exported + } = specifier; + const exportName = exported.type === "Identifier" ? exported.name : exported.value; + this.checkDuplicateExports(specifier, exportName); + if (!isFrom && specifier.local) { + const { + local + } = specifier; + if (local.type !== "Identifier") { + this.raise(Errors.ExportBindingIsString, specifier, { + localName: local.value, + exportName + }); + } else { + this.checkReservedWord(local.name, local.loc.start, true, false); + this.scope.checkLocalExport(local); + } + } + } + } else if (node.declaration) { + const decl = node.declaration; + if (decl.type === "FunctionDeclaration" || decl.type === "ClassDeclaration") { + const { + id + } = decl; + if (!id) throw new Error("Assertion failure"); + this.checkDuplicateExports(node, id.name); + } else if (decl.type === "VariableDeclaration") { + for (const declaration of decl.declarations) { + this.checkDeclaration(declaration.id); + } + } + } + } + } + checkDeclaration(node) { + if (node.type === "Identifier") { + this.checkDuplicateExports(node, node.name); + } else if (node.type === "ObjectPattern") { + for (const prop of node.properties) { + this.checkDeclaration(prop); + } + } else if (node.type === "ArrayPattern") { + for (const elem of node.elements) { + if (elem) { + this.checkDeclaration(elem); + } + } + } else if (node.type === "ObjectProperty") { + this.checkDeclaration(node.value); + } else if (node.type === "RestElement") { + this.checkDeclaration(node.argument); + } else if (node.type === "AssignmentPattern") { + this.checkDeclaration(node.left); + } + } + checkDuplicateExports(node, exportName) { + if (this.exportedIdentifiers.has(exportName)) { + if (exportName === "default") { + this.raise(Errors.DuplicateDefaultExport, node); + } else { + this.raise(Errors.DuplicateExport, node, { + exportName + }); + } + } + this.exportedIdentifiers.add(exportName); + } + parseExportSpecifiers(isInTypeExport) { + const nodes = []; + let first = true; + this.expect(5); + while (!this.eat(8)) { + if (first) { + first = false; + } else { + this.expect(12); + if (this.eat(8)) break; + } + const isMaybeTypeOnly = this.isContextual(130); + const isString = this.match(133); + const node = this.startNode(); + node.local = this.parseModuleExportName(); + nodes.push(this.parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly)); + } + return nodes; + } + parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly) { + if (this.eatContextual(93)) { + node.exported = this.parseModuleExportName(); + } else if (isString) { + node.exported = cloneStringLiteral(node.local); + } else if (!node.exported) { + node.exported = cloneIdentifier(node.local); + } + return this.finishNode(node, "ExportSpecifier"); + } + parseModuleExportName() { + if (this.match(133)) { + const result = this.parseStringLiteral(this.state.value); + const surrogate = loneSurrogate.exec(result.value); + if (surrogate) { + this.raise(Errors.ModuleExportNameHasLoneSurrogate, result, { + surrogateCharCode: surrogate[0].charCodeAt(0) + }); + } + return result; + } + return this.parseIdentifier(true); + } + isJSONModuleImport(node) { + if (node.assertions != null) { + return node.assertions.some(({ + key, + value + }) => { + return value.value === "json" && (key.type === "Identifier" ? key.name === "type" : key.value === "type"); + }); + } + return false; + } + checkImportReflection(node) { + const { + specifiers + } = node; + const singleBindingType = specifiers.length === 1 ? specifiers[0].type : null; + if (node.phase === "source") { + if (singleBindingType !== "ImportDefaultSpecifier") { + this.raise(Errors.SourcePhaseImportRequiresDefault, specifiers[0].loc.start); + } + } else if (node.phase === "defer") { + if (singleBindingType !== "ImportNamespaceSpecifier") { + this.raise(Errors.DeferImportRequiresNamespace, specifiers[0].loc.start); + } + } else if (node.module) { + var _node$assertions; + if (singleBindingType !== "ImportDefaultSpecifier") { + this.raise(Errors.ImportReflectionNotBinding, specifiers[0].loc.start); + } + if (((_node$assertions = node.assertions) == null ? void 0 : _node$assertions.length) > 0) { + this.raise(Errors.ImportReflectionHasAssertion, specifiers[0].loc.start); + } + } + } + checkJSONModuleImport(node) { + if (this.isJSONModuleImport(node) && node.type !== "ExportAllDeclaration") { + const { + specifiers + } = node; + if (specifiers != null) { + const nonDefaultNamedSpecifier = specifiers.find(specifier => { + let imported; + if (specifier.type === "ExportSpecifier") { + imported = specifier.local; + } else if (specifier.type === "ImportSpecifier") { + imported = specifier.imported; + } + if (imported !== undefined) { + return imported.type === "Identifier" ? imported.name !== "default" : imported.value !== "default"; + } + }); + if (nonDefaultNamedSpecifier !== undefined) { + this.raise(Errors.ImportJSONBindingNotDefault, nonDefaultNamedSpecifier.loc.start); + } + } + } + } + isPotentialImportPhase(isExport) { + if (isExport) return false; + return this.isContextual(105) || this.isContextual(97) || this.isContextual(127); + } + applyImportPhase(node, isExport, phase, loc) { + if (isExport) { + return; + } + if (phase === "module") { + this.expectPlugin("importReflection", loc); + node.module = true; + } else if (this.hasPlugin("importReflection")) { + node.module = false; + } + if (phase === "source") { + this.expectPlugin("sourcePhaseImports", loc); + node.phase = "source"; + } else if (phase === "defer") { + this.expectPlugin("deferredImportEvaluation", loc); + node.phase = "defer"; + } else if (this.hasPlugin("sourcePhaseImports")) { + node.phase = null; + } + } + parseMaybeImportPhase(node, isExport) { + if (!this.isPotentialImportPhase(isExport)) { + this.applyImportPhase(node, isExport, null); + return null; + } + const phaseIdentifier = this.parseIdentifier(true); + const { + type + } = this.state; + const isImportPhase = tokenIsKeywordOrIdentifier(type) ? type !== 98 || this.lookaheadCharCode() === 102 : type !== 12; + if (isImportPhase) { + this.resetPreviousIdentifierLeadingComments(phaseIdentifier); + this.applyImportPhase(node, isExport, phaseIdentifier.name, phaseIdentifier.loc.start); + return null; + } else { + this.applyImportPhase(node, isExport, null); + return phaseIdentifier; + } + } + isPrecedingIdImportPhase(phase) { + const { + type + } = this.state; + return tokenIsIdentifier(type) ? type !== 98 || this.lookaheadCharCode() === 102 : type !== 12; + } + parseImport(node) { + if (this.match(133)) { + return this.parseImportSourceAndAttributes(node); + } + return this.parseImportSpecifiersAndAfter(node, this.parseMaybeImportPhase(node, false)); + } + parseImportSpecifiersAndAfter(node, maybeDefaultIdentifier) { + node.specifiers = []; + const hasDefault = this.maybeParseDefaultImportSpecifier(node, maybeDefaultIdentifier); + const parseNext = !hasDefault || this.eat(12); + const hasStar = parseNext && this.maybeParseStarImportSpecifier(node); + if (parseNext && !hasStar) this.parseNamedImportSpecifiers(node); + this.expectContextual(98); + return this.parseImportSourceAndAttributes(node); + } + parseImportSourceAndAttributes(node) { + var _node$specifiers2; + (_node$specifiers2 = node.specifiers) != null ? _node$specifiers2 : node.specifiers = []; + node.source = this.parseImportSource(); + this.maybeParseImportAttributes(node); + this.checkImportReflection(node); + this.checkJSONModuleImport(node); + this.semicolon(); + return this.finishNode(node, "ImportDeclaration"); + } + parseImportSource() { + if (!this.match(133)) this.unexpected(); + return this.parseExprAtom(); + } + parseImportSpecifierLocal(node, specifier, type) { + specifier.local = this.parseIdentifier(); + node.specifiers.push(this.finishImportSpecifier(specifier, type)); + } + finishImportSpecifier(specifier, type, bindingType = 8201) { + this.checkLVal(specifier.local, { + type + }, bindingType); + return this.finishNode(specifier, type); + } + parseImportAttributes() { + this.expect(5); + const attrs = []; + const attrNames = new Set(); + do { + if (this.match(8)) { + break; + } + const node = this.startNode(); + const keyName = this.state.value; + if (attrNames.has(keyName)) { + this.raise(Errors.ModuleAttributesWithDuplicateKeys, this.state.startLoc, { + key: keyName + }); + } + attrNames.add(keyName); + if (this.match(133)) { + node.key = this.parseStringLiteral(keyName); + } else { + node.key = this.parseIdentifier(true); + } + this.expect(14); + if (!this.match(133)) { + throw this.raise(Errors.ModuleAttributeInvalidValue, this.state.startLoc); + } + node.value = this.parseStringLiteral(this.state.value); + attrs.push(this.finishNode(node, "ImportAttribute")); + } while (this.eat(12)); + this.expect(8); + return attrs; + } + parseModuleAttributes() { + const attrs = []; + const attributes = new Set(); + do { + const node = this.startNode(); + node.key = this.parseIdentifier(true); + if (node.key.name !== "type") { + this.raise(Errors.ModuleAttributeDifferentFromType, node.key); + } + if (attributes.has(node.key.name)) { + this.raise(Errors.ModuleAttributesWithDuplicateKeys, node.key, { + key: node.key.name + }); + } + attributes.add(node.key.name); + this.expect(14); + if (!this.match(133)) { + throw this.raise(Errors.ModuleAttributeInvalidValue, this.state.startLoc); + } + node.value = this.parseStringLiteral(this.state.value); + attrs.push(this.finishNode(node, "ImportAttribute")); + } while (this.eat(12)); + return attrs; + } + maybeParseImportAttributes(node) { + let attributes; + let useWith = false; + if (this.match(76)) { + if (this.hasPrecedingLineBreak() && this.lookaheadCharCode() === 40) { + return; + } + this.next(); + { + if (this.hasPlugin("moduleAttributes")) { + attributes = this.parseModuleAttributes(); + } else { + this.expectImportAttributesPlugin(); + attributes = this.parseImportAttributes(); + } + } + useWith = true; + } else if (this.isContextual(94) && !this.hasPrecedingLineBreak()) { + if (this.hasPlugin("importAttributes")) { + if (this.getPluginOption("importAttributes", "deprecatedAssertSyntax") !== true) { + this.raise(Errors.ImportAttributesUseAssert, this.state.startLoc); + } + this.addExtra(node, "deprecatedAssertSyntax", true); + } else { + this.expectOnePlugin(["importAttributes", "importAssertions"]); + } + this.next(); + attributes = this.parseImportAttributes(); + } else if (this.hasPlugin("importAttributes") || this.hasPlugin("importAssertions")) { + attributes = []; + } else { + if (this.hasPlugin("moduleAttributes")) { + attributes = []; + } else return; + } + if (!useWith && this.hasPlugin("importAssertions")) { + node.assertions = attributes; + } else { + node.attributes = attributes; + } + } + maybeParseDefaultImportSpecifier(node, maybeDefaultIdentifier) { + if (maybeDefaultIdentifier) { + const specifier = this.startNodeAtNode(maybeDefaultIdentifier); + specifier.local = maybeDefaultIdentifier; + node.specifiers.push(this.finishImportSpecifier(specifier, "ImportDefaultSpecifier")); + return true; + } else if (tokenIsKeywordOrIdentifier(this.state.type)) { + this.parseImportSpecifierLocal(node, this.startNode(), "ImportDefaultSpecifier"); + return true; + } + return false; + } + maybeParseStarImportSpecifier(node) { + if (this.match(55)) { + const specifier = this.startNode(); + this.next(); + this.expectContextual(93); + this.parseImportSpecifierLocal(node, specifier, "ImportNamespaceSpecifier"); + return true; + } + return false; + } + parseNamedImportSpecifiers(node) { + let first = true; + this.expect(5); + while (!this.eat(8)) { + if (first) { + first = false; + } else { + if (this.eat(14)) { + throw this.raise(Errors.DestructureNamedImport, this.state.startLoc); + } + this.expect(12); + if (this.eat(8)) break; + } + const specifier = this.startNode(); + const importedIsString = this.match(133); + const isMaybeTypeOnly = this.isContextual(130); + specifier.imported = this.parseModuleExportName(); + const importSpecifier = this.parseImportSpecifier(specifier, importedIsString, node.importKind === "type" || node.importKind === "typeof", isMaybeTypeOnly, undefined); + node.specifiers.push(importSpecifier); + } + } + parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, bindingType) { + if (this.eatContextual(93)) { + specifier.local = this.parseIdentifier(); + } else { + const { + imported + } = specifier; + if (importedIsString) { + throw this.raise(Errors.ImportBindingIsString, specifier, { + importName: imported.value + }); + } + this.checkReservedWord(imported.name, specifier.loc.start, true, true); + if (!specifier.local) { + specifier.local = cloneIdentifier(imported); + } + } + return this.finishImportSpecifier(specifier, "ImportSpecifier", bindingType); + } + isThisParam(param) { + return param.type === "Identifier" && param.name === "this"; + } +} +class Parser extends StatementParser { + constructor(options, input, pluginsMap) { + options = getOptions(options); + super(options, input); + this.options = options; + this.initializeScopes(); + this.plugins = pluginsMap; + this.filename = options.sourceFilename; + } + getScopeHandler() { + return ScopeHandler; + } + parse() { + this.enterInitialScopes(); + const file = this.startNode(); + const program = this.startNode(); + this.nextToken(); + file.errors = null; + this.parseTopLevel(file, program); + file.errors = this.state.errors; + file.comments.length = this.state.commentsLen; + return file; + } +} +function parse(input, options) { + var _options; + if (((_options = options) == null ? void 0 : _options.sourceType) === "unambiguous") { + options = Object.assign({}, options); + try { + options.sourceType = "module"; + const parser = getParser(options, input); + const ast = parser.parse(); + if (parser.sawUnambiguousESM) { + return ast; + } + if (parser.ambiguousScriptDifferentAst) { + try { + options.sourceType = "script"; + return getParser(options, input).parse(); + } catch (_unused) {} + } else { + ast.program.sourceType = "script"; + } + return ast; + } catch (moduleError) { + try { + options.sourceType = "script"; + return getParser(options, input).parse(); + } catch (_unused2) {} + throw moduleError; + } + } else { + return getParser(options, input).parse(); + } +} +function parseExpression(input, options) { + const parser = getParser(options, input); + if (parser.options.strictMode) { + parser.state.strict = true; + } + return parser.getExpression(); +} +function generateExportedTokenTypes(internalTokenTypes) { + const tokenTypes = {}; + for (const typeName of Object.keys(internalTokenTypes)) { + tokenTypes[typeName] = getExportedToken(internalTokenTypes[typeName]); + } + return tokenTypes; +} +const tokTypes = generateExportedTokenTypes(tt); +function getParser(options, input) { + let cls = Parser; + const pluginsMap = new Map(); + if (options != null && options.plugins) { + for (const plugin of options.plugins) { + let name, opts; + if (typeof plugin === "string") { + name = plugin; + } else { + [name, opts] = plugin; + } + if (!pluginsMap.has(name)) { + pluginsMap.set(name, opts || {}); + } + } + validatePlugins(pluginsMap); + cls = getParserClass(pluginsMap); + } + return new cls(options, input, pluginsMap); +} +const parserClassCache = new Map(); +function getParserClass(pluginsMap) { + const pluginList = []; + for (const name of mixinPluginNames) { + if (pluginsMap.has(name)) { + pluginList.push(name); + } + } + const key = pluginList.join("|"); + let cls = parserClassCache.get(key); + if (!cls) { + cls = Parser; + for (const plugin of pluginList) { + cls = mixinPlugins[plugin](cls); + } + parserClassCache.set(key, cls); + } + return cls; +} +exports.parse = parse; +exports.parseExpression = parseExpression; +exports.tokTypes = tokTypes; +//# sourceMappingURL=index.js.map diff --git a/libcore/node_modules/@babel/parser/lib/index.js.map b/libcore/node_modules/@babel/parser/lib/index.js.map new file mode 100644 index 0000000..3cdfa3d --- /dev/null +++ b/libcore/node_modules/@babel/parser/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sources":["../src/util/location.ts","../src/parse-error/module-errors.ts","../src/parse-error/to-node-description.ts","../src/parse-error/standard-errors.ts","../src/parse-error/strict-mode-errors.ts","../src/parse-error/pipeline-operator-errors.ts","../src/parse-error.ts","../src/plugins/estree.ts","../src/tokenizer/context.ts","../src/tokenizer/types.ts","../../babel-helper-validator-identifier/src/identifier.ts","../../babel-helper-validator-identifier/src/keyword.ts","../src/util/identifier.ts","../src/util/scope.ts","../src/plugins/flow/scope.ts","../src/parser/base.ts","../src/parser/comments.ts","../src/util/whitespace.ts","../src/tokenizer/state.ts","../../babel-helper-string-parser/src/index.ts","../src/tokenizer/index.ts","../src/util/class-scope.ts","../src/util/expression-scope.ts","../src/util/production-parameter.ts","../src/parser/util.ts","../src/parser/node.ts","../src/plugins/flow/index.ts","../src/plugins/jsx/xhtml.ts","../src/plugins/jsx/index.ts","../src/plugins/typescript/scope.ts","../src/parser/lval.ts","../src/plugins/typescript/index.ts","../src/plugins/placeholders.ts","../src/plugins/v8intrinsic.ts","../src/plugin-utils.ts","../src/options.ts","../src/parser/expression.ts","../src/parser/statement.ts","../src/parser/index.ts","../src/index.ts"],"sourcesContent":["export type Pos = {\n start: number;\n};\n\n// These are used when `options.locations` is on, for the\n// `startLoc` and `endLoc` properties.\n\nexport class Position {\n line: number;\n column: number;\n index: number;\n\n constructor(line: number, col: number, index: number) {\n this.line = line;\n this.column = col;\n this.index = index;\n }\n}\n\nexport class SourceLocation {\n start: Position;\n end: Position;\n filename: string;\n identifierName: string | undefined | null;\n\n constructor(start: Position, end?: Position) {\n this.start = start;\n // (may start as null, but initialized later)\n this.end = end;\n }\n}\n\n/**\n * creates a new position with a non-zero column offset from the given position.\n * This function should be only be used when we create AST node out of the token\n * boundaries, such as TemplateElement ends before tt.templateNonTail. This\n * function does not skip whitespaces.\n */\nexport function createPositionWithColumnOffset(\n position: Position,\n columnOffset: number,\n) {\n const { line, column, index } = position;\n return new Position(line, column + columnOffset, index + columnOffset);\n}\n","import type { ParseErrorTemplates } from \"../parse-error.ts\";\n\nconst code = \"BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED\";\n\nexport default {\n ImportMetaOutsideModule: {\n message: `import.meta may appear only with 'sourceType: \"module\"'`,\n code,\n },\n ImportOutsideModule: {\n message: `'import' and 'export' may appear only with 'sourceType: \"module\"'`,\n code,\n },\n} satisfies ParseErrorTemplates;\n","const NodeDescriptions = {\n ArrayPattern: \"array destructuring pattern\",\n AssignmentExpression: \"assignment expression\",\n AssignmentPattern: \"assignment expression\",\n ArrowFunctionExpression: \"arrow function expression\",\n ConditionalExpression: \"conditional expression\",\n CatchClause: \"catch clause\",\n ForOfStatement: \"for-of statement\",\n ForInStatement: \"for-in statement\",\n ForStatement: \"for-loop\",\n FormalParameters: \"function parameter list\",\n Identifier: \"identifier\",\n ImportSpecifier: \"import specifier\",\n ImportDefaultSpecifier: \"import default specifier\",\n ImportNamespaceSpecifier: \"import namespace specifier\",\n ObjectPattern: \"object destructuring pattern\",\n ParenthesizedExpression: \"parenthesized expression\",\n RestElement: \"rest element\",\n UpdateExpression: {\n true: \"prefix operation\",\n false: \"postfix operation\",\n },\n VariableDeclarator: \"variable declaration\",\n YieldExpression: \"yield expression\",\n};\n\ntype NodeTypesWithDescriptions = keyof Omit<\n typeof NodeDescriptions,\n \"UpdateExpression\"\n>;\n\ntype NodeWithDescription =\n | {\n type: \"UpdateExpression\";\n prefix: boolean;\n }\n | {\n type: NodeTypesWithDescriptions;\n };\n\n// eslint-disable-next-line no-confusing-arrow\nconst toNodeDescription = (node: NodeWithDescription) =>\n node.type === \"UpdateExpression\"\n ? NodeDescriptions.UpdateExpression[`${node.prefix}`]\n : NodeDescriptions[node.type];\n\nexport default toNodeDescription;\n","import type { ParseErrorTemplates } from \"../parse-error.ts\";\nimport toNodeDescription from \"./to-node-description.ts\";\n\nexport type LValAncestor =\n | { type: \"UpdateExpression\"; prefix: boolean }\n | {\n type:\n | \"ArrayPattern\"\n | \"AssignmentExpression\"\n | \"CatchClause\"\n | \"ForOfStatement\"\n | \"FormalParameters\"\n | \"ForInStatement\"\n | \"ForStatement\"\n | \"ImportSpecifier\"\n | \"ImportNamespaceSpecifier\"\n | \"ImportDefaultSpecifier\"\n | \"ParenthesizedExpression\"\n | \"ObjectPattern\"\n | \"RestElement\"\n | \"VariableDeclarator\";\n };\n\nexport default {\n AccessorIsGenerator: ({ kind }: { kind: \"get\" | \"set\" }) =>\n `A ${kind}ter cannot be a generator.`,\n ArgumentsInClass:\n \"'arguments' is only allowed in functions and class methods.\",\n AsyncFunctionInSingleStatementContext:\n \"Async functions can only be declared at the top level or inside a block.\",\n AwaitBindingIdentifier:\n \"Can not use 'await' as identifier inside an async function.\",\n AwaitBindingIdentifierInStaticBlock:\n \"Can not use 'await' as identifier inside a static block.\",\n AwaitExpressionFormalParameter:\n \"'await' is not allowed in async function parameters.\",\n AwaitUsingNotInAsyncContext:\n \"'await using' is only allowed within async functions and at the top levels of modules.\",\n AwaitNotInAsyncContext:\n \"'await' is only allowed within async functions and at the top levels of modules.\",\n AwaitNotInAsyncFunction: \"'await' is only allowed within async functions.\",\n BadGetterArity: \"A 'get' accessor must not have any formal parameters.\",\n BadSetterArity: \"A 'set' accessor must have exactly one formal parameter.\",\n BadSetterRestParameter:\n \"A 'set' accessor function argument must not be a rest parameter.\",\n ConstructorClassField: \"Classes may not have a field named 'constructor'.\",\n ConstructorClassPrivateField:\n \"Classes may not have a private field named '#constructor'.\",\n ConstructorIsAccessor: \"Class constructor may not be an accessor.\",\n ConstructorIsAsync: \"Constructor can't be an async function.\",\n ConstructorIsGenerator: \"Constructor can't be a generator.\",\n DeclarationMissingInitializer: ({\n kind,\n }: {\n kind: \"await using\" | \"const\" | \"destructuring\" | \"using\";\n }) => `Missing initializer in ${kind} declaration.`,\n DecoratorArgumentsOutsideParentheses:\n \"Decorator arguments must be moved inside parentheses: use '@(decorator(args))' instead of '@(decorator)(args)'.\",\n DecoratorBeforeExport:\n \"Decorators must be placed *before* the 'export' keyword. Remove the 'decoratorsBeforeExport: true' option to use the 'export @decorator class {}' syntax.\",\n DecoratorsBeforeAfterExport:\n \"Decorators can be placed *either* before or after the 'export' keyword, but not in both locations at the same time.\",\n DecoratorConstructor:\n \"Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?\",\n DecoratorExportClass:\n \"Decorators must be placed *after* the 'export' keyword. Remove the 'decoratorsBeforeExport: false' option to use the '@decorator export class {}' syntax.\",\n DecoratorSemicolon: \"Decorators must not be followed by a semicolon.\",\n DecoratorStaticBlock: \"Decorators can't be used with a static block.\",\n DeferImportRequiresNamespace:\n 'Only `import defer * as x from \"./module\"` is valid.',\n DeletePrivateField: \"Deleting a private field is not allowed.\",\n DestructureNamedImport:\n \"ES2015 named imports do not destructure. Use another statement for destructuring after the import.\",\n DuplicateConstructor: \"Duplicate constructor in the same class.\",\n DuplicateDefaultExport: \"Only one default export allowed per module.\",\n DuplicateExport: ({ exportName }: { exportName: string }) =>\n `\\`${exportName}\\` has already been exported. Exported identifiers must be unique.`,\n DuplicateProto: \"Redefinition of __proto__ property.\",\n DuplicateRegExpFlags: \"Duplicate regular expression flag.\",\n DynamicImportPhaseRequiresImportExpressions: ({ phase }: { phase: string }) =>\n `'import.${phase}(...)' can only be parsed when using the 'createImportExpressions' option.`,\n ElementAfterRest: \"Rest element must be last element.\",\n EscapedCharNotAnIdentifier: \"Invalid Unicode escape.\",\n ExportBindingIsString: ({\n localName,\n exportName,\n }: {\n localName: string;\n exportName: string;\n }) =>\n `A string literal cannot be used as an exported binding without \\`from\\`.\\n- Did you mean \\`export { '${localName}' as '${exportName}' } from 'some-module'\\`?`,\n ExportDefaultFromAsIdentifier:\n \"'from' is not allowed as an identifier after 'export default'.\",\n\n ForInOfLoopInitializer: ({\n type,\n }: {\n type: \"ForInStatement\" | \"ForOfStatement\";\n }) =>\n `'${\n type === \"ForInStatement\" ? \"for-in\" : \"for-of\"\n }' loop variable declaration may not have an initializer.`,\n ForInUsing: \"For-in loop may not start with 'using' declaration.\",\n\n ForOfAsync: \"The left-hand side of a for-of loop may not be 'async'.\",\n ForOfLet: \"The left-hand side of a for-of loop may not start with 'let'.\",\n GeneratorInSingleStatementContext:\n \"Generators can only be declared at the top level or inside a block.\",\n\n IllegalBreakContinue: ({\n type,\n }: {\n type: \"BreakStatement\" | \"ContinueStatement\";\n }) => `Unsyntactic ${type === \"BreakStatement\" ? \"break\" : \"continue\"}.`,\n\n IllegalLanguageModeDirective:\n \"Illegal 'use strict' directive in function with non-simple parameter list.\",\n IllegalReturn: \"'return' outside of function.\",\n ImportAttributesUseAssert:\n \"The `assert` keyword in import attributes is deprecated and it has been replaced by the `with` keyword. You can enable the `deprecatedAssertSyntax: true` option in the import attributes plugin to suppress this error.\",\n ImportBindingIsString: ({ importName }: { importName: string }) =>\n `A string literal cannot be used as an imported binding.\\n- Did you mean \\`import { \"${importName}\" as foo }\\`?`,\n ImportCallArgumentTrailingComma:\n \"Trailing comma is disallowed inside import(...) arguments.\",\n ImportCallArity: ({ maxArgumentCount }: { maxArgumentCount: 1 | 2 }) =>\n `\\`import()\\` requires exactly ${\n maxArgumentCount === 1 ? \"one argument\" : \"one or two arguments\"\n }.`,\n ImportCallNotNewExpression: \"Cannot use new with import(...).\",\n ImportCallSpreadArgument: \"`...` is not allowed in `import()`.\",\n ImportJSONBindingNotDefault:\n \"A JSON module can only be imported with `default`.\",\n ImportReflectionHasAssertion: \"`import module x` cannot have assertions.\",\n ImportReflectionNotBinding:\n 'Only `import module x from \"./module\"` is valid.',\n IncompatibleRegExpUVFlags:\n \"The 'u' and 'v' regular expression flags cannot be enabled at the same time.\",\n InvalidBigIntLiteral: \"Invalid BigIntLiteral.\",\n InvalidCodePoint: \"Code point out of bounds.\",\n InvalidCoverInitializedName: \"Invalid shorthand property initializer.\",\n InvalidDecimal: \"Invalid decimal.\",\n InvalidDigit: ({ radix }: { radix: number }) =>\n `Expected number in radix ${radix}.`,\n InvalidEscapeSequence: \"Bad character escape sequence.\",\n InvalidEscapeSequenceTemplate: \"Invalid escape sequence in template.\",\n InvalidEscapedReservedWord: ({ reservedWord }: { reservedWord: string }) =>\n `Escape sequence in keyword ${reservedWord}.`,\n InvalidIdentifier: ({ identifierName }: { identifierName: string }) =>\n `Invalid identifier ${identifierName}.`,\n InvalidLhs: ({ ancestor }: { ancestor: LValAncestor }) =>\n `Invalid left-hand side in ${toNodeDescription(ancestor)}.`,\n InvalidLhsBinding: ({ ancestor }: { ancestor: LValAncestor }) =>\n `Binding invalid left-hand side in ${toNodeDescription(ancestor)}.`,\n InvalidLhsOptionalChaining: ({ ancestor }: { ancestor: LValAncestor }) =>\n `Invalid optional chaining in the left-hand side of ${toNodeDescription(\n ancestor,\n )}.`,\n InvalidNumber: \"Invalid number.\",\n InvalidOrMissingExponent:\n \"Floating-point numbers require a valid exponent after the 'e'.\",\n InvalidOrUnexpectedToken: ({ unexpected }: { unexpected: string }) =>\n `Unexpected character '${unexpected}'.`,\n InvalidParenthesizedAssignment: \"Invalid parenthesized assignment pattern.\",\n InvalidPrivateFieldResolution: ({\n identifierName,\n }: {\n identifierName: string;\n }) => `Private name #${identifierName} is not defined.`,\n InvalidPropertyBindingPattern: \"Binding member expression.\",\n InvalidRecordProperty:\n \"Only properties and spread elements are allowed in record definitions.\",\n InvalidRestAssignmentPattern: \"Invalid rest operator's argument.\",\n LabelRedeclaration: ({ labelName }: { labelName: string }) =>\n `Label '${labelName}' is already declared.`,\n LetInLexicalBinding: \"'let' is disallowed as a lexically bound name.\",\n LineTerminatorBeforeArrow: \"No line break is allowed before '=>'.\",\n MalformedRegExpFlags: \"Invalid regular expression flag.\",\n MissingClassName: \"A class name is required.\",\n MissingEqInAssignment:\n \"Only '=' operator can be used for specifying default value.\",\n MissingSemicolon: \"Missing semicolon.\",\n MissingPlugin: ({ missingPlugin }: { missingPlugin: [string] }) =>\n `This experimental syntax requires enabling the parser plugin: ${missingPlugin\n .map(name => JSON.stringify(name))\n .join(\", \")}.`,\n // FIXME: Would be nice to make this \"missingPlugins\" instead.\n // Also, seems like we can drop the \"(s)\" from the message and just make it \"s\".\n MissingOneOfPlugins: ({ missingPlugin }: { missingPlugin: string[] }) =>\n `This experimental syntax requires enabling one of the following parser plugin(s): ${missingPlugin\n .map(name => JSON.stringify(name))\n .join(\", \")}.`,\n MissingUnicodeEscape: \"Expecting Unicode escape sequence \\\\uXXXX.\",\n MixingCoalesceWithLogical:\n \"Nullish coalescing operator(??) requires parens when mixing with logical operators.\",\n ModuleAttributeDifferentFromType:\n \"The only accepted module attribute is `type`.\",\n ModuleAttributeInvalidValue:\n \"Only string literals are allowed as module attribute values.\",\n ModuleAttributesWithDuplicateKeys: ({ key }: { key: string }) =>\n `Duplicate key \"${key}\" is not allowed in module attributes.`,\n ModuleExportNameHasLoneSurrogate: ({\n surrogateCharCode,\n }: {\n surrogateCharCode: number;\n }) =>\n `An export name cannot include a lone surrogate, found '\\\\u${surrogateCharCode.toString(\n 16,\n )}'.`,\n ModuleExportUndefined: ({ localName }: { localName: string }) =>\n `Export '${localName}' is not defined.`,\n MultipleDefaultsInSwitch: \"Multiple default clauses.\",\n NewlineAfterThrow: \"Illegal newline after throw.\",\n NoCatchOrFinally: \"Missing catch or finally clause.\",\n NumberIdentifier: \"Identifier directly after number.\",\n NumericSeparatorInEscapeSequence:\n \"Numeric separators are not allowed inside unicode escape sequences or hex escape sequences.\",\n ObsoleteAwaitStar:\n \"'await*' has been removed from the async functions proposal. Use Promise.all() instead.\",\n OptionalChainingNoNew:\n \"Constructors in/after an Optional Chain are not allowed.\",\n OptionalChainingNoTemplate:\n \"Tagged Template Literals are not allowed in optionalChain.\",\n OverrideOnConstructor:\n \"'override' modifier cannot appear on a constructor declaration.\",\n ParamDupe: \"Argument name clash.\",\n PatternHasAccessor: \"Object pattern can't contain getter or setter.\",\n PatternHasMethod: \"Object pattern can't contain methods.\",\n PrivateInExpectedIn: ({ identifierName }: { identifierName: string }) =>\n `Private names are only allowed in property accesses (\\`obj.#${identifierName}\\`) or in \\`in\\` expressions (\\`#${identifierName} in obj\\`).`,\n PrivateNameRedeclaration: ({ identifierName }: { identifierName: string }) =>\n `Duplicate private name #${identifierName}.`,\n RecordExpressionBarIncorrectEndSyntaxType:\n \"Record expressions ending with '|}' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.\",\n RecordExpressionBarIncorrectStartSyntaxType:\n \"Record expressions starting with '{|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.\",\n RecordExpressionHashIncorrectStartSyntaxType:\n \"Record expressions starting with '#{' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.\",\n RecordNoProto: \"'__proto__' is not allowed in Record expressions.\",\n RestTrailingComma: \"Unexpected trailing comma after rest element.\",\n SloppyFunction:\n \"In non-strict mode code, functions can only be declared at top level or inside a block.\",\n SloppyFunctionAnnexB:\n \"In non-strict mode code, functions can only be declared at top level, inside a block, or as the body of an if statement.\",\n SourcePhaseImportRequiresDefault:\n 'Only `import source x from \"./module\"` is valid.',\n StaticPrototype: \"Classes may not have static property named prototype.\",\n SuperNotAllowed:\n \"`super()` is only valid inside a class constructor of a subclass. Maybe a typo in the method name ('constructor') or not extending another class?\",\n SuperPrivateField: \"Private fields can't be accessed on super.\",\n TrailingDecorator: \"Decorators must be attached to a class element.\",\n TupleExpressionBarIncorrectEndSyntaxType:\n \"Tuple expressions ending with '|]' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.\",\n TupleExpressionBarIncorrectStartSyntaxType:\n \"Tuple expressions starting with '[|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.\",\n TupleExpressionHashIncorrectStartSyntaxType:\n \"Tuple expressions starting with '#[' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.\",\n UnexpectedArgumentPlaceholder: \"Unexpected argument placeholder.\",\n UnexpectedAwaitAfterPipelineBody:\n 'Unexpected \"await\" after pipeline body; await must have parentheses in minimal proposal.',\n UnexpectedDigitAfterHash: \"Unexpected digit after hash token.\",\n UnexpectedImportExport:\n \"'import' and 'export' may only appear at the top level.\",\n UnexpectedKeyword: ({ keyword }: { keyword: string }) =>\n `Unexpected keyword '${keyword}'.`,\n UnexpectedLeadingDecorator:\n \"Leading decorators must be attached to a class declaration.\",\n UnexpectedLexicalDeclaration:\n \"Lexical declaration cannot appear in a single-statement context.\",\n UnexpectedNewTarget:\n \"`new.target` can only be used in functions or class properties.\",\n UnexpectedNumericSeparator:\n \"A numeric separator is only allowed between two digits.\",\n UnexpectedPrivateField: \"Unexpected private name.\",\n UnexpectedReservedWord: ({ reservedWord }: { reservedWord: string }) =>\n `Unexpected reserved word '${reservedWord}'.`,\n UnexpectedSuper: \"'super' is only allowed in object methods and classes.\",\n UnexpectedToken: ({\n expected,\n unexpected,\n }: {\n expected?: string | null;\n unexpected?: string | null;\n }) =>\n `Unexpected token${unexpected ? ` '${unexpected}'.` : \"\"}${\n expected ? `, expected \"${expected}\"` : \"\"\n }`,\n UnexpectedTokenUnaryExponentiation:\n \"Illegal expression. Wrap left hand side or entire exponentiation in parentheses.\",\n UnexpectedUsingDeclaration:\n \"Using declaration cannot appear in the top level when source type is `script`.\",\n UnsupportedBind: \"Binding should be performed on object property.\",\n UnsupportedDecoratorExport:\n \"A decorated export must export a class declaration.\",\n UnsupportedDefaultExport:\n \"Only expressions, functions or classes are allowed as the `default` export.\",\n UnsupportedImport:\n \"`import` can only be used in `import()` or `import.meta`.\",\n UnsupportedMetaProperty: ({\n target,\n onlyValidPropertyName,\n }: {\n target: string;\n onlyValidPropertyName: string;\n }) =>\n `The only valid meta property for ${target} is ${target}.${onlyValidPropertyName}.`,\n UnsupportedParameterDecorator:\n \"Decorators cannot be used to decorate parameters.\",\n UnsupportedPropertyDecorator:\n \"Decorators cannot be used to decorate object literal properties.\",\n UnsupportedSuper:\n \"'super' can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop]).\",\n UnterminatedComment: \"Unterminated comment.\",\n UnterminatedRegExp: \"Unterminated regular expression.\",\n UnterminatedString: \"Unterminated string constant.\",\n UnterminatedTemplate: \"Unterminated template.\",\n UsingDeclarationExport: \"Using declaration cannot be exported.\",\n UsingDeclarationHasBindingPattern:\n \"Using declaration cannot have destructuring patterns.\",\n VarRedeclaration: ({ identifierName }: { identifierName: string }) =>\n `Identifier '${identifierName}' has already been declared.`,\n YieldBindingIdentifier:\n \"Can not use 'yield' as identifier inside a generator.\",\n YieldInParameter: \"Yield expression is not allowed in formal parameters.\",\n ZeroDigitNumericSeparator:\n \"Numeric separator can not be used after leading 0.\",\n} satisfies ParseErrorTemplates;\n","import type { ParseErrorTemplates } from \"../parse-error\";\n\nexport default {\n StrictDelete: \"Deleting local variable in strict mode.\",\n\n // `referenceName` is the StringValue[1] of an IdentifierReference[2], which\n // is represented as just an `Identifier`[3] in the Babel AST.\n // 1. https://tc39.es/ecma262/#sec-static-semantics-stringvalue\n // 2. https://tc39.es/ecma262/#prod-IdentifierReference\n // 3. https://github.com/babel/babel/blob/main/packages/babel-parser/ast/spec.md#identifier\n StrictEvalArguments: ({ referenceName }: { referenceName: string }) =>\n `Assigning to '${referenceName}' in strict mode.`,\n\n // `bindingName` is the StringValue[1] of a BindingIdentifier[2], which is\n // represented as just an `Identifier`[3] in the Babel AST.\n // 1. https://tc39.es/ecma262/#sec-static-semantics-stringvalue\n // 2. https://tc39.es/ecma262/#prod-BindingIdentifier\n // 3. https://github.com/babel/babel/blob/main/packages/babel-parser/ast/spec.md#identifier\n StrictEvalArgumentsBinding: ({ bindingName }: { bindingName: string }) =>\n `Binding '${bindingName}' in strict mode.`,\n\n StrictFunction:\n \"In strict mode code, functions can only be declared at top level or inside a block.\",\n\n StrictNumericEscape: \"The only valid numeric escape in strict mode is '\\\\0'.\",\n\n StrictOctalLiteral: \"Legacy octal literals are not allowed in strict mode.\",\n\n StrictWith: \"'with' in strict mode.\",\n} satisfies ParseErrorTemplates;\n","import type { ParseErrorTemplates } from \"../parse-error.ts\";\nimport toNodeDescription from \"./to-node-description.ts\";\n\nexport const UnparenthesizedPipeBodyDescriptions = new Set([\n \"ArrowFunctionExpression\",\n \"AssignmentExpression\",\n \"ConditionalExpression\",\n \"YieldExpression\",\n] as const);\n\ntype GetSetMemberType> =\n T extends Set ? M : unknown;\n\nexport type UnparenthesizedPipeBodyTypes = GetSetMemberType<\n typeof UnparenthesizedPipeBodyDescriptions\n>;\n\nexport default {\n // This error is only used by the smart-mix proposal\n PipeBodyIsTighter:\n \"Unexpected yield after pipeline body; any yield expression acting as Hack-style pipe body must be parenthesized due to its loose operator precedence.\",\n PipeTopicRequiresHackPipes:\n 'Topic reference is used, but the pipelineOperator plugin was not passed a \"proposal\": \"hack\" or \"smart\" option.',\n PipeTopicUnbound:\n \"Topic reference is unbound; it must be inside a pipe body.\",\n PipeTopicUnconfiguredToken: ({ token }: { token: string }) =>\n `Invalid topic token ${token}. In order to use ${token} as a topic reference, the pipelineOperator plugin must be configured with { \"proposal\": \"hack\", \"topicToken\": \"${token}\" }.`,\n PipeTopicUnused:\n \"Hack-style pipe body does not contain a topic reference; Hack-style pipes must use topic at least once.\",\n PipeUnparenthesizedBody: ({ type }: { type: UnparenthesizedPipeBodyTypes }) =>\n `Hack-style pipe body cannot be an unparenthesized ${toNodeDescription({\n type,\n })}; please wrap it in parentheses.`,\n\n // Messages whose codes start with “Pipeline” or “PrimaryTopic”\n // are retained for backwards compatibility\n // with the deprecated smart-mix pipe operator proposal plugin.\n // They are subject to removal in a future major version.\n PipelineBodyNoArrow:\n 'Unexpected arrow \"=>\" after pipeline body; arrow function in pipeline body must be parenthesized.',\n PipelineBodySequenceExpression:\n \"Pipeline body may not be a comma-separated sequence expression.\",\n PipelineHeadSequenceExpression:\n \"Pipeline head should not be a comma-separated sequence expression.\",\n PipelineTopicUnused:\n \"Pipeline is in topic style but does not use topic reference.\",\n PrimaryTopicNotAllowed:\n \"Topic reference was used in a lexical context without topic binding.\",\n PrimaryTopicRequiresSmartPipeline:\n 'Topic reference is used, but the pipelineOperator plugin was not passed a \"proposal\": \"hack\" or \"smart\" option.',\n} satisfies ParseErrorTemplates;\n","import { Position } from \"./util/location.ts\";\n\ntype SyntaxPlugin =\n | \"flow\"\n | \"typescript\"\n | \"jsx\"\n | \"pipelineOperator\"\n | \"placeholders\";\n\ntype ParseErrorCode =\n | \"BABEL_PARSER_SYNTAX_ERROR\"\n | \"BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED\";\n\n// Babel uses \"normal\" SyntaxErrors for it's errors, but adds some extra\n// functionality. This functionality is defined in the\n// `ParseErrorSpecification` interface below. We may choose to change to someday\n// give our errors their own full-blown class, but until then this allow us to\n// keep all the desirable properties of SyntaxErrors (like their name in stack\n// traces, etc.), and also allows us to punt on any publicly facing\n// class-hierarchy decisions until Babel 8.\ninterface ParseErrorSpecification {\n // Look, these *could* be readonly, but then Flow complains when we initially\n // set them. We could do a whole dance and make a special interface that's not\n // readonly for when we create the error, then cast it to the readonly\n // interface for public use, but the previous implementation didn't have them\n // as readonly, so let's just not worry about it for now.\n code: ParseErrorCode;\n reasonCode: string;\n syntaxPlugin?: SyntaxPlugin;\n missingPlugin?: string | string[];\n loc: Position;\n details: ErrorDetails;\n\n // We should consider removing this as it now just contains the same\n // information as `loc.index`.\n pos: number;\n}\n\nexport type ParseError = SyntaxError &\n ParseErrorSpecification;\n\n// By `ParseErrorConstructor`, we mean something like the new-less style\n// `ErrorConstructor`[1], since `ParseError`'s are not themselves actually\n// separate classes from `SyntaxError`'s.\n//\n// 1. https://github.com/microsoft/TypeScript/blob/v4.5.5/lib/lib.es5.d.ts#L1027\nexport type ParseErrorConstructor = (\n loc: Position,\n details: ErrorDetails,\n) => ParseError;\n\ntype ToMessage = (self: ErrorDetails) => string;\n\ntype ParseErrorCredentials = {\n code: string;\n reasonCode: string;\n syntaxPlugin?: SyntaxPlugin;\n toMessage: ToMessage;\n};\n\nfunction defineHidden(obj: object, key: string, value: unknown) {\n Object.defineProperty(obj, key, {\n enumerable: false,\n configurable: true,\n value,\n });\n}\n\nfunction toParseErrorConstructor({\n toMessage,\n code,\n reasonCode,\n syntaxPlugin,\n}: ParseErrorCredentials): ParseErrorConstructor {\n const hasMissingPlugin =\n reasonCode === \"MissingPlugin\" || reasonCode === \"MissingOneOfPlugins\";\n\n if (!process.env.BABEL_8_BREAKING) {\n const oldReasonCodes: Record = {\n AccessorCannotDeclareThisParameter: \"AccesorCannotDeclareThisParameter\",\n AccessorCannotHaveTypeParameters: \"AccesorCannotHaveTypeParameters\",\n ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference:\n \"ConstInitiailizerMustBeStringOrNumericLiteralOrLiteralEnumReference\",\n SetAccessorCannotHaveOptionalParameter:\n \"SetAccesorCannotHaveOptionalParameter\",\n SetAccessorCannotHaveRestParameter: \"SetAccesorCannotHaveRestParameter\",\n SetAccessorCannotHaveReturnType: \"SetAccesorCannotHaveReturnType\",\n };\n if (oldReasonCodes[reasonCode]) {\n reasonCode = oldReasonCodes[reasonCode];\n }\n }\n\n return function constructor(loc: Position, details: ErrorDetails) {\n const error: ParseError = new SyntaxError() as any;\n\n error.code = code as ParseErrorCode;\n error.reasonCode = reasonCode;\n error.loc = loc;\n error.pos = loc.index;\n\n error.syntaxPlugin = syntaxPlugin;\n if (hasMissingPlugin) {\n error.missingPlugin = (details as any).missingPlugin;\n }\n\n type Overrides = {\n loc?: Position;\n details?: ErrorDetails;\n };\n defineHidden(error, \"clone\", function clone(overrides: Overrides = {}) {\n const { line, column, index } = overrides.loc ?? loc;\n return constructor(new Position(line, column, index), {\n ...details,\n ...overrides.details,\n });\n });\n\n defineHidden(error, \"details\", details);\n\n Object.defineProperty(error, \"message\", {\n configurable: true,\n get(this: ParseError): string {\n const message = `${toMessage(details)} (${loc.line}:${loc.column})`;\n this.message = message;\n return message;\n },\n set(value: string) {\n Object.defineProperty(this, \"message\", { value, writable: true });\n },\n });\n\n return error;\n };\n}\n\ntype ParseErrorTemplate =\n | string\n | ToMessage\n | { message: string | ToMessage; code?: ParseErrorCode };\n\nexport type ParseErrorTemplates = { [reasonCode: string]: ParseErrorTemplate };\n\n// This is the templated form of `ParseErrorEnum`.\n//\n// Note: We could factor out the return type calculation into something like\n// `ParseErrorConstructor`, and then we could\n// reuse it in the non-templated form of `ParseErrorEnum`, but TypeScript\n// doesn't seem to drill down that far when showing you the computed type of\n// an object in an editor, so we'll leave it inlined for now.\nexport function ParseErrorEnum(a: TemplateStringsArray): <\n T extends ParseErrorTemplates,\n>(\n parseErrorTemplates: T,\n) => {\n [K in keyof T]: ParseErrorConstructor<\n T[K] extends { message: string | ToMessage }\n ? T[K][\"message\"] extends ToMessage\n ? Parameters[0]\n : object\n : T[K] extends ToMessage\n ? Parameters[0]\n : object\n >;\n};\n\nexport function ParseErrorEnum(\n parseErrorTemplates: T,\n syntaxPlugin?: SyntaxPlugin,\n): {\n [K in keyof T]: ParseErrorConstructor<\n T[K] extends { message: string | ToMessage }\n ? T[K][\"message\"] extends ToMessage\n ? Parameters[0]\n : object\n : T[K] extends ToMessage\n ? Parameters[0]\n : object\n >;\n};\n\n// You call `ParseErrorEnum` with a mapping from `ReasonCode`'s to either:\n//\n// 1. a static error message,\n// 2. `toMessage` functions that define additional necessary `details` needed by\n// the `ParseError`, or\n// 3. Objects that contain a `message` of one of the above and overridden `code`\n// and/or `reasonCode`:\n//\n// ParseErrorEnum `optionalSyntaxPlugin` ({\n// ErrorWithStaticMessage: \"message\",\n// ErrorWithDynamicMessage: ({ type } : { type: string }) => `${type}`),\n// ErrorWithOverriddenCodeAndOrReasonCode: {\n// message: ({ type }: { type: string }) => `${type}`),\n// code: \"AN_ERROR_CODE\",\n// ...(BABEL_8_BREAKING ? { } : { reasonCode: \"CustomErrorReasonCode\" })\n// }\n// });\n//\nexport function ParseErrorEnum(\n argument: TemplateStringsArray | ParseErrorTemplates,\n syntaxPlugin?: SyntaxPlugin,\n) {\n // If the first parameter is an array, that means we were called with a tagged\n // template literal. Extract the syntaxPlugin from this, and call again in\n // the \"normalized\" form.\n if (Array.isArray(argument)) {\n return (parseErrorTemplates: ParseErrorTemplates) =>\n ParseErrorEnum(parseErrorTemplates, argument[0]);\n }\n\n const ParseErrorConstructors = {} as Record<\n string,\n ParseErrorConstructor\n >;\n\n for (const reasonCode of Object.keys(argument)) {\n const template = (argument as ParseErrorTemplates)[reasonCode];\n const { message, ...rest } =\n typeof template === \"string\"\n ? { message: () => template }\n : typeof template === \"function\"\n ? { message: template }\n : template;\n const toMessage = typeof message === \"string\" ? () => message : message;\n\n ParseErrorConstructors[reasonCode] = toParseErrorConstructor({\n code: \"BABEL_PARSER_SYNTAX_ERROR\",\n reasonCode,\n toMessage,\n ...(syntaxPlugin ? { syntaxPlugin } : {}),\n ...rest,\n });\n }\n\n return ParseErrorConstructors;\n}\n\nimport ModuleErrors from \"./parse-error/module-errors.ts\";\nimport StandardErrors from \"./parse-error/standard-errors.ts\";\nimport StrictModeErrors from \"./parse-error/strict-mode-errors.ts\";\nimport PipelineOperatorErrors from \"./parse-error/pipeline-operator-errors.ts\";\n\nexport const Errors = {\n ...ParseErrorEnum(ModuleErrors),\n ...ParseErrorEnum(StandardErrors),\n ...ParseErrorEnum(StrictModeErrors),\n ...ParseErrorEnum`pipelineOperator`(PipelineOperatorErrors),\n};\n\nexport type { LValAncestor } from \"./parse-error/standard-errors.ts\";\n","import type { TokenType } from \"../tokenizer/types.ts\";\nimport type Parser from \"../parser/index.ts\";\nimport type { ExpressionErrors } from \"../parser/util.ts\";\nimport type * as N from \"../types.ts\";\nimport type { Node as NodeType, NodeBase, File } from \"../types.ts\";\nimport type { Position } from \"../util/location.ts\";\nimport { Errors } from \"../parse-error.ts\";\nimport type { Undone } from \"../parser/node.ts\";\nimport type { BindingFlag } from \"../util/scopeflags.ts\";\n\nconst { defineProperty } = Object;\nconst toUnenumerable = (object: any, key: string) => {\n if (object) {\n defineProperty(object, key, { enumerable: false, value: object[key] });\n }\n};\n\nfunction toESTreeLocation(node: any) {\n toUnenumerable(node.loc.start, \"index\");\n toUnenumerable(node.loc.end, \"index\");\n\n return node;\n}\n\nexport default (superClass: typeof Parser) =>\n class ESTreeParserMixin extends superClass implements Parser {\n parse(): File {\n const file = toESTreeLocation(super.parse());\n\n if (this.options.tokens) {\n file.tokens = file.tokens.map(toESTreeLocation);\n }\n\n return file;\n }\n\n // @ts-expect-error ESTree plugin changes node types\n parseRegExpLiteral({ pattern, flags }): N.EstreeRegExpLiteral {\n let regex: RegExp | null = null;\n try {\n regex = new RegExp(pattern, flags);\n } catch (_) {\n // In environments that don't support these flags value will\n // be null as the regex can't be represented natively.\n }\n const node = this.estreeParseLiteral(regex);\n node.regex = { pattern, flags };\n\n return node;\n }\n\n // @ts-expect-error ESTree plugin changes node types\n parseBigIntLiteral(value: any): N.Node {\n // https://github.com/estree/estree/blob/master/es2020.md#bigintliteral\n let bigInt: bigint | null;\n try {\n bigInt = BigInt(value);\n } catch {\n bigInt = null;\n }\n const node = this.estreeParseLiteral(bigInt);\n node.bigint = String(node.value || value);\n\n return node;\n }\n\n // @ts-expect-error ESTree plugin changes node types\n parseDecimalLiteral(value: any): N.Node {\n // https://github.com/estree/estree/blob/master/experimental/decimal.md\n // todo: use BigDecimal when node supports it.\n const decimal: null = null;\n const node = this.estreeParseLiteral(decimal);\n node.decimal = String(node.value || value);\n\n return node;\n }\n\n estreeParseLiteral(value: any) {\n // @ts-expect-error ESTree plugin changes node types\n return this.parseLiteral(value, \"Literal\");\n }\n\n // @ts-expect-error ESTree plugin changes node types\n parseStringLiteral(value: any): N.Node {\n return this.estreeParseLiteral(value);\n }\n\n parseNumericLiteral(value: any): any {\n return this.estreeParseLiteral(value);\n }\n\n // @ts-expect-error ESTree plugin changes node types\n parseNullLiteral(): N.Node {\n return this.estreeParseLiteral(null);\n }\n\n parseBooleanLiteral(value: boolean): N.BooleanLiteral {\n // @ts-expect-error ESTree plugin changes node types\n return this.estreeParseLiteral(value);\n }\n\n // Cast a Directive to an ExpressionStatement. Mutates the input Directive.\n directiveToStmt(directive: N.Directive): N.ExpressionStatement {\n const expression = directive.value as any as N.EstreeLiteral;\n delete directive.value;\n\n expression.type = \"Literal\";\n // @ts-expect-error N.EstreeLiteral.raw is not defined.\n expression.raw = expression.extra.raw;\n expression.value = expression.extra.expressionValue;\n\n const stmt = directive as any as N.ExpressionStatement;\n stmt.type = \"ExpressionStatement\";\n stmt.expression = expression;\n // @ts-expect-error N.ExpressionStatement.directive is not defined\n stmt.directive = expression.extra.rawValue;\n\n delete expression.extra;\n\n return stmt;\n }\n\n // ==================================\n // Overrides\n // ==================================\n\n initFunction(node: N.BodilessFunctionOrMethodBase, isAsync: boolean): void {\n super.initFunction(node, isAsync);\n node.expression = false;\n }\n\n checkDeclaration(node: N.Pattern | N.ObjectProperty): void {\n if (node != null && this.isObjectProperty(node)) {\n // @ts-expect-error plugin typings\n this.checkDeclaration((node as unknown as N.EstreeProperty).value);\n } else {\n super.checkDeclaration(node);\n }\n }\n\n getObjectOrClassMethodParams(method: N.ObjectMethod | N.ClassMethod) {\n return (method as unknown as N.EstreeMethodDefinition).value.params;\n }\n\n isValidDirective(stmt: N.Statement): boolean {\n return (\n stmt.type === \"ExpressionStatement\" &&\n stmt.expression.type === \"Literal\" &&\n typeof stmt.expression.value === \"string\" &&\n !stmt.expression.extra?.parenthesized\n );\n }\n\n parseBlockBody(\n node: N.BlockStatementLike,\n allowDirectives: boolean | undefined | null,\n topLevel: boolean,\n end: TokenType,\n afterBlockParse?: (hasStrictModeDirective: boolean) => void,\n ): void {\n super.parseBlockBody(\n node,\n allowDirectives,\n topLevel,\n end,\n afterBlockParse,\n );\n\n const directiveStatements = node.directives.map(d =>\n this.directiveToStmt(d),\n );\n // @ts-expect-error estree plugin typings\n node.body = directiveStatements.concat(node.body);\n delete node.directives;\n }\n\n pushClassMethod(\n classBody: N.ClassBody,\n method: N.ClassMethod,\n isGenerator: boolean,\n isAsync: boolean,\n isConstructor: boolean,\n allowsDirectSuper: boolean,\n ): void {\n this.parseMethod(\n method,\n isGenerator,\n isAsync,\n isConstructor,\n allowsDirectSuper,\n \"ClassMethod\",\n true,\n );\n if (method.typeParameters) {\n // @ts-expect-error mutate AST types\n method.value.typeParameters = method.typeParameters;\n delete method.typeParameters;\n }\n classBody.body.push(method);\n }\n\n parsePrivateName(): any {\n const node = super.parsePrivateName();\n if (!process.env.BABEL_8_BREAKING) {\n if (!this.getPluginOption(\"estree\", \"classFeatures\")) {\n return node;\n }\n }\n return this.convertPrivateNameToPrivateIdentifier(node);\n }\n\n convertPrivateNameToPrivateIdentifier(\n node: N.PrivateName,\n ): N.EstreePrivateIdentifier {\n const name = super.getPrivateNameSV(node);\n node = node as any;\n delete node.id;\n // @ts-expect-error mutate AST types\n node.name = name;\n // @ts-expect-error mutate AST types\n node.type = \"PrivateIdentifier\";\n return node as unknown as N.EstreePrivateIdentifier;\n }\n\n // @ts-expect-error ESTree plugin changes node types\n isPrivateName(node: N.Node): node is N.EstreePrivateIdentifier {\n if (!process.env.BABEL_8_BREAKING) {\n if (!this.getPluginOption(\"estree\", \"classFeatures\")) {\n return super.isPrivateName(node);\n }\n }\n return node.type === \"PrivateIdentifier\";\n }\n\n // @ts-expect-error ESTree plugin changes node types\n getPrivateNameSV(node: N.EstreePrivateIdentifier): string {\n if (!process.env.BABEL_8_BREAKING) {\n if (!this.getPluginOption(\"estree\", \"classFeatures\")) {\n return super.getPrivateNameSV(node as unknown as N.PrivateName);\n }\n }\n return node.name;\n }\n\n // @ts-expect-error plugin may override interfaces\n parseLiteral(value: any, type: T[\"type\"]): T {\n const node = super.parseLiteral(value, type);\n // @ts-expect-error mutating AST types\n node.raw = node.extra.raw;\n delete node.extra;\n\n return node;\n }\n\n parseFunctionBody(\n node: N.Function,\n allowExpression?: boolean | null,\n isMethod: boolean = false,\n ): void {\n super.parseFunctionBody(node, allowExpression, isMethod);\n node.expression = node.body.type !== \"BlockStatement\";\n }\n\n // @ts-expect-error plugin may override interfaces\n parseMethod<\n T extends N.ClassPrivateMethod | N.ObjectMethod | N.ClassMethod,\n >(\n node: Undone,\n isGenerator: boolean,\n isAsync: boolean,\n isConstructor: boolean,\n allowDirectSuper: boolean,\n type: T[\"type\"],\n inClassScope: boolean = false,\n ): N.EstreeMethodDefinition {\n let funcNode = this.startNode();\n funcNode.kind = node.kind; // provide kind, so super method correctly sets state\n funcNode = super.parseMethod(\n // @ts-expect-error todo(flow->ts)\n funcNode,\n isGenerator,\n isAsync,\n isConstructor,\n allowDirectSuper,\n type,\n inClassScope,\n );\n // @ts-expect-error mutate AST types\n funcNode.type = \"FunctionExpression\";\n delete funcNode.kind;\n // @ts-expect-error mutate AST types\n node.value = funcNode;\n if (type === \"ClassPrivateMethod\") {\n node.computed = false;\n }\n return this.finishNode(\n // @ts-expect-error cast methods to estree types\n node as Undone,\n \"MethodDefinition\",\n );\n }\n\n nameIsConstructor(key: N.Expression | N.PrivateName): boolean {\n if (key.type === \"Literal\") return key.value === \"constructor\";\n return super.nameIsConstructor(key);\n }\n\n parseClassProperty(...args: [N.ClassProperty]): any {\n const propertyNode = super.parseClassProperty(...args) as any;\n if (!process.env.BABEL_8_BREAKING) {\n if (!this.getPluginOption(\"estree\", \"classFeatures\")) {\n return propertyNode as N.EstreePropertyDefinition;\n }\n }\n propertyNode.type = \"PropertyDefinition\";\n return propertyNode as N.EstreePropertyDefinition;\n }\n\n parseClassPrivateProperty(...args: [N.ClassPrivateProperty]): any {\n const propertyNode = super.parseClassPrivateProperty(...args) as any;\n if (!process.env.BABEL_8_BREAKING) {\n if (!this.getPluginOption(\"estree\", \"classFeatures\")) {\n return propertyNode as N.EstreePropertyDefinition;\n }\n }\n propertyNode.type = \"PropertyDefinition\";\n propertyNode.computed = false;\n return propertyNode as N.EstreePropertyDefinition;\n }\n\n parseObjectMethod(\n prop: N.ObjectMethod,\n isGenerator: boolean,\n isAsync: boolean,\n isPattern: boolean,\n isAccessor: boolean,\n ): N.ObjectMethod | undefined | null {\n const node: N.EstreeProperty = super.parseObjectMethod(\n prop,\n isGenerator,\n isAsync,\n isPattern,\n isAccessor,\n ) as any;\n\n if (node) {\n node.type = \"Property\";\n if ((node as any as N.ClassMethod).kind === \"method\") {\n node.kind = \"init\";\n }\n node.shorthand = false;\n }\n\n return node as any;\n }\n\n parseObjectProperty(\n prop: N.ObjectProperty,\n startLoc: Position | undefined | null,\n isPattern: boolean,\n refExpressionErrors?: ExpressionErrors | null,\n ): N.ObjectProperty | undefined | null {\n const node: N.EstreeProperty = super.parseObjectProperty(\n prop,\n startLoc,\n isPattern,\n refExpressionErrors,\n ) as any;\n\n if (node) {\n node.kind = \"init\";\n node.type = \"Property\";\n }\n\n return node as any;\n }\n\n isValidLVal(\n type: string,\n isUnparenthesizedInAssign: boolean,\n binding: BindingFlag,\n ) {\n return type === \"Property\"\n ? \"value\"\n : super.isValidLVal(type, isUnparenthesizedInAssign, binding);\n }\n\n isAssignable(node: N.Node, isBinding?: boolean): boolean {\n if (node != null && this.isObjectProperty(node)) {\n return this.isAssignable(node.value, isBinding);\n }\n return super.isAssignable(node, isBinding);\n }\n\n toAssignable(node: N.Node, isLHS: boolean = false): void {\n if (node != null && this.isObjectProperty(node)) {\n const { key, value } = node;\n if (this.isPrivateName(key)) {\n this.classScope.usePrivateName(\n this.getPrivateNameSV(key),\n key.loc.start,\n );\n }\n this.toAssignable(value, isLHS);\n } else {\n super.toAssignable(node, isLHS);\n }\n }\n\n toAssignableObjectExpressionProp(\n prop: N.Node,\n isLast: boolean,\n isLHS: boolean,\n ) {\n if (\n prop.type === \"Property\" &&\n (prop.kind === \"get\" || prop.kind === \"set\")\n ) {\n this.raise(Errors.PatternHasAccessor, prop.key);\n } else if (prop.type === \"Property\" && prop.method) {\n this.raise(Errors.PatternHasMethod, prop.key);\n } else {\n super.toAssignableObjectExpressionProp(prop, isLast, isLHS);\n }\n }\n\n finishCallExpression(\n unfinished: Undone,\n optional: boolean,\n ): T {\n const node = super.finishCallExpression(unfinished, optional);\n\n if (node.callee.type === \"Import\") {\n (node as N.Node as N.EstreeImportExpression).type = \"ImportExpression\";\n (node as N.Node as N.EstreeImportExpression).source = node\n .arguments[0] as N.Expression;\n if (\n this.hasPlugin(\"importAttributes\") ||\n this.hasPlugin(\"importAssertions\")\n ) {\n (node as N.Node as N.EstreeImportExpression).options =\n (node.arguments[1] as N.Expression) ?? null;\n // compatibility with previous ESTree AST\n (node as N.Node as N.EstreeImportExpression).attributes =\n (node.arguments[1] as N.Expression) ?? null;\n }\n // arguments isn't optional in the type definition\n delete node.arguments;\n // callee isn't optional in the type definition\n delete node.callee;\n }\n\n return node;\n }\n\n toReferencedArguments(\n node:\n | N.CallExpression\n | N.OptionalCallExpression\n | N.EstreeImportExpression,\n /* isParenthesizedExpr?: boolean, */\n ) {\n // ImportExpressions do not have an arguments array.\n if (node.type === \"ImportExpression\") {\n return;\n }\n\n super.toReferencedArguments(node);\n }\n\n parseExport(\n unfinished: Undone,\n decorators: N.Decorator[] | null,\n ) {\n const exportStartLoc = this.state.lastTokStartLoc;\n const node = super.parseExport(unfinished, decorators);\n\n switch (node.type) {\n case \"ExportAllDeclaration\":\n // @ts-expect-error mutating AST types\n node.exported = null;\n break;\n\n case \"ExportNamedDeclaration\":\n if (\n node.specifiers.length === 1 &&\n node.specifiers[0].type === \"ExportNamespaceSpecifier\"\n ) {\n // @ts-expect-error mutating AST types\n node.type = \"ExportAllDeclaration\";\n // @ts-expect-error mutating AST types\n node.exported = node.specifiers[0].exported;\n delete node.specifiers;\n }\n\n // fallthrough\n case \"ExportDefaultDeclaration\":\n {\n const { declaration } = node;\n if (\n declaration?.type === \"ClassDeclaration\" &&\n declaration.decorators?.length > 0 &&\n // decorator comes before export\n declaration.start === node.start\n ) {\n this.resetStartLocation(\n node,\n // For compatibility with ESLint's keyword-spacing rule, which assumes that an\n // export declaration must start with export.\n // https://github.com/babel/babel/issues/15085\n // Here we reset export declaration's start to be the start of the export token\n exportStartLoc,\n );\n }\n }\n\n break;\n }\n\n return node;\n }\n\n parseSubscript(\n base: N.Expression,\n startLoc: Position,\n noCalls: boolean | undefined | null,\n state: N.ParseSubscriptState,\n ): N.Expression {\n const node = super.parseSubscript(base, startLoc, noCalls, state);\n\n if (state.optionalChainMember) {\n // https://github.com/estree/estree/blob/master/es2020.md#chainexpression\n if (\n node.type === \"OptionalMemberExpression\" ||\n node.type === \"OptionalCallExpression\"\n ) {\n // strip Optional prefix\n (node as unknown as N.CallExpression | N.MemberExpression).type =\n node.type.substring(8) as \"CallExpression\" | \"MemberExpression\";\n }\n if (state.stop) {\n const chain = this.startNodeAtNode(node);\n chain.expression = node;\n return this.finishNode(chain, \"ChainExpression\");\n }\n } else if (\n node.type === \"MemberExpression\" ||\n node.type === \"CallExpression\"\n ) {\n // @ts-expect-error not in the type definitions\n node.optional = false;\n }\n\n return node;\n }\n\n isOptionalMemberExpression(node: N.Node) {\n if (node.type === \"ChainExpression\") {\n return node.expression.type === \"MemberExpression\";\n }\n return super.isOptionalMemberExpression(node);\n }\n\n hasPropertyAsPrivateName(node: N.Node): boolean {\n if (node.type === \"ChainExpression\") {\n node = node.expression;\n }\n return super.hasPropertyAsPrivateName(node);\n }\n\n // @ts-expect-error ESTree plugin changes node types\n isObjectProperty(node: N.Node): node is N.EstreeProperty {\n return node.type === \"Property\" && node.kind === \"init\" && !node.method;\n }\n\n // @ts-expect-error ESTree plugin changes node types\n isObjectMethod(node: N.Node): node is N.EstreeProperty {\n return (\n node.type === \"Property\" &&\n (node.method || node.kind === \"get\" || node.kind === \"set\")\n );\n }\n\n finishNodeAt(\n node: Undone,\n type: T[\"type\"],\n endLoc: Position,\n ): T {\n return toESTreeLocation(super.finishNodeAt(node, type, endLoc));\n }\n\n resetStartLocation(node: N.Node, startLoc: Position) {\n super.resetStartLocation(node, startLoc);\n toESTreeLocation(node);\n }\n\n resetEndLocation(\n node: NodeBase,\n endLoc: Position = this.state.lastTokEndLoc,\n ): void {\n super.resetEndLocation(node, endLoc);\n toESTreeLocation(node);\n }\n };\n","// The token context is used in JSX plugin to track\n// jsx tag / jsx text / normal JavaScript expression\n\nexport class TokContext {\n constructor(token: string, preserveSpace?: boolean) {\n this.token = token;\n this.preserveSpace = !!preserveSpace;\n }\n\n token: string;\n preserveSpace: boolean;\n}\n\nconst types: {\n [key: string]: TokContext;\n} = {\n brace: new TokContext(\"{\"), // normal JavaScript expression\n j_oTag: new TokContext(\"...\", true), // JSX expressions\n};\n\nif (!process.env.BABEL_8_BREAKING) {\n types.template = new TokContext(\"`\", true);\n}\n\nexport { types };\n","import { types as tc, type TokContext } from \"./context.ts\";\n// ## Token types\n\n// The assignment of fine-grained, information-carrying type objects\n// allows the tokenizer to store the information it has about a\n// token in a way that is very cheap for the parser to look up.\n\n// All token type variables start with an underscore, to make them\n// easy to recognize.\n\n// The `beforeExpr` property is used to disambiguate between 1) binary\n// expression (<) and JSX Tag start (); 2) object literal and JSX\n// texts. It is set on the `updateContext` function in the JSX plugin.\n\n// The `startsExpr` property is used to determine whether an expression\n// may be the “argument” subexpression of a `yield` expression or\n// `yield` statement. It is set on all token types that may be at the\n// start of a subexpression.\n\n// `isLoop` marks a keyword as starting a loop, which is important\n// to know when parsing a label, in order to allow or disallow\n// continue jumps to that label.\n\nconst beforeExpr = true;\nconst startsExpr = true;\nconst isLoop = true;\nconst isAssign = true;\nconst prefix = true;\nconst postfix = true;\n\ntype TokenOptions = {\n keyword?: string;\n beforeExpr?: boolean;\n startsExpr?: boolean;\n rightAssociative?: boolean;\n isLoop?: boolean;\n isAssign?: boolean;\n prefix?: boolean;\n postfix?: boolean;\n binop?: number | null;\n};\n\n// Internally the tokenizer stores token as a number\nexport type TokenType = number;\n\n// The `ExportedTokenType` is exported via `tokTypes` and accessible\n// when `tokens: true` is enabled. Unlike internal token type, it provides\n// metadata of the tokens.\nexport class ExportedTokenType {\n label: string;\n keyword: string | undefined | null;\n beforeExpr: boolean;\n startsExpr: boolean;\n rightAssociative: boolean;\n isLoop: boolean;\n isAssign: boolean;\n prefix: boolean;\n postfix: boolean;\n binop: number | undefined | null;\n // todo(Babel 8): remove updateContext from exposed token layout\n declare updateContext:\n | ((context: Array) => void)\n | undefined\n | null;\n\n constructor(label: string, conf: TokenOptions = {}) {\n this.label = label;\n this.keyword = conf.keyword;\n this.beforeExpr = !!conf.beforeExpr;\n this.startsExpr = !!conf.startsExpr;\n this.rightAssociative = !!conf.rightAssociative;\n this.isLoop = !!conf.isLoop;\n this.isAssign = !!conf.isAssign;\n this.prefix = !!conf.prefix;\n this.postfix = !!conf.postfix;\n this.binop = conf.binop != null ? conf.binop : null;\n if (!process.env.BABEL_8_BREAKING) {\n this.updateContext = null;\n }\n }\n}\n\n// A map from keyword/keyword-like string value to the token type\nexport const keywords = new Map();\n\nfunction createKeyword(name: string, options: TokenOptions = {}): TokenType {\n options.keyword = name;\n const token = createToken(name, options);\n keywords.set(name, token);\n return token;\n}\n\nfunction createBinop(name: string, binop: number) {\n return createToken(name, { beforeExpr, binop });\n}\n\nlet tokenTypeCounter = -1;\nexport const tokenTypes: ExportedTokenType[] = [];\nconst tokenLabels: string[] = [];\nconst tokenBinops: number[] = [];\nconst tokenBeforeExprs: boolean[] = [];\nconst tokenStartsExprs: boolean[] = [];\nconst tokenPrefixes: boolean[] = [];\n\nfunction createToken(name: string, options: TokenOptions = {}): TokenType {\n ++tokenTypeCounter;\n tokenLabels.push(name);\n tokenBinops.push(options.binop ?? -1);\n tokenBeforeExprs.push(options.beforeExpr ?? false);\n tokenStartsExprs.push(options.startsExpr ?? false);\n tokenPrefixes.push(options.prefix ?? false);\n tokenTypes.push(new ExportedTokenType(name, options));\n\n return tokenTypeCounter;\n}\n\nfunction createKeywordLike(\n name: string,\n options: TokenOptions = {},\n): TokenType {\n ++tokenTypeCounter;\n keywords.set(name, tokenTypeCounter);\n tokenLabels.push(name);\n tokenBinops.push(options.binop ?? -1);\n tokenBeforeExprs.push(options.beforeExpr ?? false);\n tokenStartsExprs.push(options.startsExpr ?? false);\n tokenPrefixes.push(options.prefix ?? false);\n // In the exported token type, we set the label as \"name\" for backward compatibility with Babel 7\n tokenTypes.push(new ExportedTokenType(\"name\", options));\n\n return tokenTypeCounter;\n}\n\n// For performance the token type helpers depend on the following declarations order.\n// When adding new token types, please also check if the token helpers need update.\n\nexport type InternalTokenTypes = typeof tt;\n\nexport const tt = {\n // Punctuation token types.\n bracketL: createToken(\"[\", { beforeExpr, startsExpr }),\n bracketHashL: createToken(\"#[\", { beforeExpr, startsExpr }),\n bracketBarL: createToken(\"[|\", { beforeExpr, startsExpr }),\n bracketR: createToken(\"]\"),\n bracketBarR: createToken(\"|]\"),\n braceL: createToken(\"{\", { beforeExpr, startsExpr }),\n braceBarL: createToken(\"{|\", { beforeExpr, startsExpr }),\n braceHashL: createToken(\"#{\", { beforeExpr, startsExpr }),\n braceR: createToken(\"}\"),\n braceBarR: createToken(\"|}\"),\n parenL: createToken(\"(\", { beforeExpr, startsExpr }),\n parenR: createToken(\")\"),\n comma: createToken(\",\", { beforeExpr }),\n semi: createToken(\";\", { beforeExpr }),\n colon: createToken(\":\", { beforeExpr }),\n doubleColon: createToken(\"::\", { beforeExpr }),\n dot: createToken(\".\"),\n question: createToken(\"?\", { beforeExpr }),\n questionDot: createToken(\"?.\"),\n arrow: createToken(\"=>\", { beforeExpr }),\n template: createToken(\"template\"),\n ellipsis: createToken(\"...\", { beforeExpr }),\n backQuote: createToken(\"`\", { startsExpr }),\n dollarBraceL: createToken(\"${\", { beforeExpr, startsExpr }),\n // start: isTemplate\n templateTail: createToken(\"...`\", { startsExpr }),\n templateNonTail: createToken(\"...${\", { beforeExpr, startsExpr }),\n // end: isTemplate\n at: createToken(\"@\"),\n hash: createToken(\"#\", { startsExpr }),\n\n // Special hashbang token.\n interpreterDirective: createToken(\"#!...\"),\n\n // Operators. These carry several kinds of properties to help the\n // parser use them properly (the presence of these properties is\n // what categorizes them as operators).\n //\n // `binop`, when present, specifies that this operator is a binary\n // operator, and will refer to its precedence.\n //\n // `prefix` and `postfix` mark the operator as a prefix or postfix\n // unary operator.\n //\n // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as\n // binary operators with a very low precedence, that should result\n // in AssignmentExpression nodes.\n\n // start: isAssign\n eq: createToken(\"=\", { beforeExpr, isAssign }),\n assign: createToken(\"_=\", { beforeExpr, isAssign }),\n slashAssign: createToken(\"_=\", { beforeExpr, isAssign }),\n // These are only needed to support % and ^ as a Hack-pipe topic token.\n // When the proposal settles on a token, the others can be merged with\n // tt.assign.\n xorAssign: createToken(\"_=\", { beforeExpr, isAssign }),\n moduloAssign: createToken(\"_=\", { beforeExpr, isAssign }),\n // end: isAssign\n\n incDec: createToken(\"++/--\", { prefix, postfix, startsExpr }),\n bang: createToken(\"!\", { beforeExpr, prefix, startsExpr }),\n tilde: createToken(\"~\", { beforeExpr, prefix, startsExpr }),\n\n // More possible topic tokens.\n // When the proposal settles on a token, at least one of these may be removed.\n doubleCaret: createToken(\"^^\", { startsExpr }),\n doubleAt: createToken(\"@@\", { startsExpr }),\n\n // start: isBinop\n pipeline: createBinop(\"|>\", 0),\n nullishCoalescing: createBinop(\"??\", 1),\n logicalOR: createBinop(\"||\", 1),\n logicalAND: createBinop(\"&&\", 2),\n bitwiseOR: createBinop(\"|\", 3),\n bitwiseXOR: createBinop(\"^\", 4),\n bitwiseAND: createBinop(\"&\", 5),\n equality: createBinop(\"==/!=/===/!==\", 6),\n lt: createBinop(\"/<=/>=\", 7),\n gt: createBinop(\"/<=/>=\", 7),\n relational: createBinop(\"/<=/>=\", 7),\n bitShift: createBinop(\"<>/>>>\", 8),\n bitShiftL: createBinop(\"<>/>>>\", 8),\n bitShiftR: createBinop(\"<>/>>>\", 8),\n plusMin: createToken(\"+/-\", { beforeExpr, binop: 9, prefix, startsExpr }),\n // startsExpr: required by v8intrinsic plugin\n modulo: createToken(\"%\", { binop: 10, startsExpr }),\n // unset `beforeExpr` as it can be `function *`\n star: createToken(\"*\", { binop: 10 }),\n slash: createBinop(\"/\", 10),\n exponent: createToken(\"**\", {\n beforeExpr,\n binop: 11,\n rightAssociative: true,\n }),\n\n // Keywords\n // Don't forget to update packages/babel-helper-validator-identifier/src/keyword.js\n // when new keywords are added\n // start: isLiteralPropertyName\n // start: isKeyword\n _in: createKeyword(\"in\", { beforeExpr, binop: 7 }),\n _instanceof: createKeyword(\"instanceof\", { beforeExpr, binop: 7 }),\n // end: isBinop\n _break: createKeyword(\"break\"),\n _case: createKeyword(\"case\", { beforeExpr }),\n _catch: createKeyword(\"catch\"),\n _continue: createKeyword(\"continue\"),\n _debugger: createKeyword(\"debugger\"),\n _default: createKeyword(\"default\", { beforeExpr }),\n _else: createKeyword(\"else\", { beforeExpr }),\n _finally: createKeyword(\"finally\"),\n _function: createKeyword(\"function\", { startsExpr }),\n _if: createKeyword(\"if\"),\n _return: createKeyword(\"return\", { beforeExpr }),\n _switch: createKeyword(\"switch\"),\n _throw: createKeyword(\"throw\", { beforeExpr, prefix, startsExpr }),\n _try: createKeyword(\"try\"),\n _var: createKeyword(\"var\"),\n _const: createKeyword(\"const\"),\n _with: createKeyword(\"with\"),\n _new: createKeyword(\"new\", { beforeExpr, startsExpr }),\n _this: createKeyword(\"this\", { startsExpr }),\n _super: createKeyword(\"super\", { startsExpr }),\n _class: createKeyword(\"class\", { startsExpr }),\n _extends: createKeyword(\"extends\", { beforeExpr }),\n _export: createKeyword(\"export\"),\n _import: createKeyword(\"import\", { startsExpr }),\n _null: createKeyword(\"null\", { startsExpr }),\n _true: createKeyword(\"true\", { startsExpr }),\n _false: createKeyword(\"false\", { startsExpr }),\n _typeof: createKeyword(\"typeof\", { beforeExpr, prefix, startsExpr }),\n _void: createKeyword(\"void\", { beforeExpr, prefix, startsExpr }),\n _delete: createKeyword(\"delete\", { beforeExpr, prefix, startsExpr }),\n // start: isLoop\n _do: createKeyword(\"do\", { isLoop, beforeExpr }),\n _for: createKeyword(\"for\", { isLoop }),\n _while: createKeyword(\"while\", { isLoop }),\n // end: isLoop\n // end: isKeyword\n\n // Primary literals\n // start: isIdentifier\n _as: createKeywordLike(\"as\", { startsExpr }),\n _assert: createKeywordLike(\"assert\", { startsExpr }),\n _async: createKeywordLike(\"async\", { startsExpr }),\n _await: createKeywordLike(\"await\", { startsExpr }),\n _defer: createKeywordLike(\"defer\", { startsExpr }),\n _from: createKeywordLike(\"from\", { startsExpr }),\n _get: createKeywordLike(\"get\", { startsExpr }),\n _let: createKeywordLike(\"let\", { startsExpr }),\n _meta: createKeywordLike(\"meta\", { startsExpr }),\n _of: createKeywordLike(\"of\", { startsExpr }),\n _sent: createKeywordLike(\"sent\", { startsExpr }),\n _set: createKeywordLike(\"set\", { startsExpr }),\n _source: createKeywordLike(\"source\", { startsExpr }),\n _static: createKeywordLike(\"static\", { startsExpr }),\n _using: createKeywordLike(\"using\", { startsExpr }),\n _yield: createKeywordLike(\"yield\", { startsExpr }),\n\n // Flow and TypeScript Keywordlike\n _asserts: createKeywordLike(\"asserts\", { startsExpr }),\n _checks: createKeywordLike(\"checks\", { startsExpr }),\n _exports: createKeywordLike(\"exports\", { startsExpr }),\n _global: createKeywordLike(\"global\", { startsExpr }),\n _implements: createKeywordLike(\"implements\", { startsExpr }),\n _intrinsic: createKeywordLike(\"intrinsic\", { startsExpr }),\n _infer: createKeywordLike(\"infer\", { startsExpr }),\n _is: createKeywordLike(\"is\", { startsExpr }),\n _mixins: createKeywordLike(\"mixins\", { startsExpr }),\n _proto: createKeywordLike(\"proto\", { startsExpr }),\n _require: createKeywordLike(\"require\", { startsExpr }),\n _satisfies: createKeywordLike(\"satisfies\", { startsExpr }),\n // start: isTSTypeOperator\n _keyof: createKeywordLike(\"keyof\", { startsExpr }),\n _readonly: createKeywordLike(\"readonly\", { startsExpr }),\n _unique: createKeywordLike(\"unique\", { startsExpr }),\n // end: isTSTypeOperator\n // start: isTSDeclarationStart\n _abstract: createKeywordLike(\"abstract\", { startsExpr }),\n _declare: createKeywordLike(\"declare\", { startsExpr }),\n _enum: createKeywordLike(\"enum\", { startsExpr }),\n _module: createKeywordLike(\"module\", { startsExpr }),\n _namespace: createKeywordLike(\"namespace\", { startsExpr }),\n // start: isFlowInterfaceOrTypeOrOpaque\n _interface: createKeywordLike(\"interface\", { startsExpr }),\n _type: createKeywordLike(\"type\", { startsExpr }),\n // end: isTSDeclarationStart\n _opaque: createKeywordLike(\"opaque\", { startsExpr }),\n // end: isFlowInterfaceOrTypeOrOpaque\n name: createToken(\"name\", { startsExpr }),\n // end: isIdentifier\n\n string: createToken(\"string\", { startsExpr }),\n num: createToken(\"num\", { startsExpr }),\n bigint: createToken(\"bigint\", { startsExpr }),\n decimal: createToken(\"decimal\", { startsExpr }),\n // end: isLiteralPropertyName\n regexp: createToken(\"regexp\", { startsExpr }),\n privateName: createToken(\"#name\", { startsExpr }),\n eof: createToken(\"eof\"),\n\n // jsx plugin\n jsxName: createToken(\"jsxName\"),\n jsxText: createToken(\"jsxText\", { beforeExpr: true }),\n jsxTagStart: createToken(\"jsxTagStart\", { startsExpr: true }),\n jsxTagEnd: createToken(\"jsxTagEnd\"),\n\n // placeholder plugin\n placeholder: createToken(\"%%\", { startsExpr: true }),\n} as const;\n\nexport function tokenIsIdentifier(token: TokenType): boolean {\n return token >= tt._as && token <= tt.name;\n}\n\nexport function tokenKeywordOrIdentifierIsKeyword(token: TokenType): boolean {\n // we can remove the token >= tt._in check when we\n // know a token is either keyword or identifier\n return token <= tt._while;\n}\n\nexport function tokenIsKeywordOrIdentifier(token: TokenType): boolean {\n return token >= tt._in && token <= tt.name;\n}\n\nexport function tokenIsLiteralPropertyName(token: TokenType): boolean {\n return token >= tt._in && token <= tt.decimal;\n}\n\nexport function tokenComesBeforeExpression(token: TokenType): boolean {\n return tokenBeforeExprs[token];\n}\n\nexport function tokenCanStartExpression(token: TokenType): boolean {\n return tokenStartsExprs[token];\n}\n\nexport function tokenIsAssignment(token: TokenType): boolean {\n return token >= tt.eq && token <= tt.moduloAssign;\n}\n\nexport function tokenIsFlowInterfaceOrTypeOrOpaque(token: TokenType): boolean {\n return token >= tt._interface && token <= tt._opaque;\n}\n\nexport function tokenIsLoop(token: TokenType): boolean {\n return token >= tt._do && token <= tt._while;\n}\n\nexport function tokenIsKeyword(token: TokenType): boolean {\n return token >= tt._in && token <= tt._while;\n}\n\nexport function tokenIsOperator(token: TokenType): boolean {\n return token >= tt.pipeline && token <= tt._instanceof;\n}\n\nexport function tokenIsPostfix(token: TokenType): boolean {\n return token === tt.incDec;\n}\n\nexport function tokenIsPrefix(token: TokenType): boolean {\n return tokenPrefixes[token];\n}\n\nexport function tokenIsTSTypeOperator(token: TokenType): boolean {\n return token >= tt._keyof && token <= tt._unique;\n}\n\nexport function tokenIsTSDeclarationStart(token: TokenType): boolean {\n return token >= tt._abstract && token <= tt._type;\n}\n\nexport function tokenLabelName(token: TokenType): string {\n return tokenLabels[token];\n}\n\nexport function tokenOperatorPrecedence(token: TokenType): number {\n return tokenBinops[token];\n}\n\nexport function tokenIsBinaryOperator(token: TokenType): boolean {\n return tokenBinops[token] !== -1;\n}\n\nexport function tokenIsRightAssociative(token: TokenType): boolean {\n return token === tt.exponent;\n}\n\nexport function tokenIsTemplate(token: TokenType): boolean {\n return token >= tt.templateTail && token <= tt.templateNonTail;\n}\n\nexport function getExportedToken(token: TokenType): ExportedTokenType {\n return tokenTypes[token];\n}\n\nexport function isTokenType(obj: any): boolean {\n return typeof obj === \"number\";\n}\n\nif (!process.env.BABEL_8_BREAKING) {\n tokenTypes[tt.braceR].updateContext = context => {\n context.pop();\n };\n\n tokenTypes[tt.braceL].updateContext =\n tokenTypes[tt.braceHashL].updateContext =\n tokenTypes[tt.dollarBraceL].updateContext =\n context => {\n context.push(tc.brace);\n };\n\n tokenTypes[tt.backQuote].updateContext = context => {\n if (context[context.length - 1] === tc.template) {\n context.pop();\n } else {\n context.push(tc.template);\n }\n };\n\n tokenTypes[tt.jsxTagStart].updateContext = context => {\n context.push(tc.j_expr, tc.j_oTag);\n };\n}\n","// We inline this package\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport * as charCodes from \"charcodes\";\n\n// ## Character categories\n\n// Big ugly regular expressions that match characters in the\n// whitespace, identifier, and identifier-start categories. These\n// are only applied when a character is found to actually have a\n// code point between 0x80 and 0xffff.\n// Generated by `scripts/generate-identifier-regex.js`.\n\n/* prettier-ignore */\nlet nonASCIIidentifierStartChars = \"\\xaa\\xb5\\xba\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\u02c1\\u02c6-\\u02d1\\u02e0-\\u02e4\\u02ec\\u02ee\\u0370-\\u0374\\u0376\\u0377\\u037a-\\u037d\\u037f\\u0386\\u0388-\\u038a\\u038c\\u038e-\\u03a1\\u03a3-\\u03f5\\u03f7-\\u0481\\u048a-\\u052f\\u0531-\\u0556\\u0559\\u0560-\\u0588\\u05d0-\\u05ea\\u05ef-\\u05f2\\u0620-\\u064a\\u066e\\u066f\\u0671-\\u06d3\\u06d5\\u06e5\\u06e6\\u06ee\\u06ef\\u06fa-\\u06fc\\u06ff\\u0710\\u0712-\\u072f\\u074d-\\u07a5\\u07b1\\u07ca-\\u07ea\\u07f4\\u07f5\\u07fa\\u0800-\\u0815\\u081a\\u0824\\u0828\\u0840-\\u0858\\u0860-\\u086a\\u0870-\\u0887\\u0889-\\u088e\\u08a0-\\u08c9\\u0904-\\u0939\\u093d\\u0950\\u0958-\\u0961\\u0971-\\u0980\\u0985-\\u098c\\u098f\\u0990\\u0993-\\u09a8\\u09aa-\\u09b0\\u09b2\\u09b6-\\u09b9\\u09bd\\u09ce\\u09dc\\u09dd\\u09df-\\u09e1\\u09f0\\u09f1\\u09fc\\u0a05-\\u0a0a\\u0a0f\\u0a10\\u0a13-\\u0a28\\u0a2a-\\u0a30\\u0a32\\u0a33\\u0a35\\u0a36\\u0a38\\u0a39\\u0a59-\\u0a5c\\u0a5e\\u0a72-\\u0a74\\u0a85-\\u0a8d\\u0a8f-\\u0a91\\u0a93-\\u0aa8\\u0aaa-\\u0ab0\\u0ab2\\u0ab3\\u0ab5-\\u0ab9\\u0abd\\u0ad0\\u0ae0\\u0ae1\\u0af9\\u0b05-\\u0b0c\\u0b0f\\u0b10\\u0b13-\\u0b28\\u0b2a-\\u0b30\\u0b32\\u0b33\\u0b35-\\u0b39\\u0b3d\\u0b5c\\u0b5d\\u0b5f-\\u0b61\\u0b71\\u0b83\\u0b85-\\u0b8a\\u0b8e-\\u0b90\\u0b92-\\u0b95\\u0b99\\u0b9a\\u0b9c\\u0b9e\\u0b9f\\u0ba3\\u0ba4\\u0ba8-\\u0baa\\u0bae-\\u0bb9\\u0bd0\\u0c05-\\u0c0c\\u0c0e-\\u0c10\\u0c12-\\u0c28\\u0c2a-\\u0c39\\u0c3d\\u0c58-\\u0c5a\\u0c5d\\u0c60\\u0c61\\u0c80\\u0c85-\\u0c8c\\u0c8e-\\u0c90\\u0c92-\\u0ca8\\u0caa-\\u0cb3\\u0cb5-\\u0cb9\\u0cbd\\u0cdd\\u0cde\\u0ce0\\u0ce1\\u0cf1\\u0cf2\\u0d04-\\u0d0c\\u0d0e-\\u0d10\\u0d12-\\u0d3a\\u0d3d\\u0d4e\\u0d54-\\u0d56\\u0d5f-\\u0d61\\u0d7a-\\u0d7f\\u0d85-\\u0d96\\u0d9a-\\u0db1\\u0db3-\\u0dbb\\u0dbd\\u0dc0-\\u0dc6\\u0e01-\\u0e30\\u0e32\\u0e33\\u0e40-\\u0e46\\u0e81\\u0e82\\u0e84\\u0e86-\\u0e8a\\u0e8c-\\u0ea3\\u0ea5\\u0ea7-\\u0eb0\\u0eb2\\u0eb3\\u0ebd\\u0ec0-\\u0ec4\\u0ec6\\u0edc-\\u0edf\\u0f00\\u0f40-\\u0f47\\u0f49-\\u0f6c\\u0f88-\\u0f8c\\u1000-\\u102a\\u103f\\u1050-\\u1055\\u105a-\\u105d\\u1061\\u1065\\u1066\\u106e-\\u1070\\u1075-\\u1081\\u108e\\u10a0-\\u10c5\\u10c7\\u10cd\\u10d0-\\u10fa\\u10fc-\\u1248\\u124a-\\u124d\\u1250-\\u1256\\u1258\\u125a-\\u125d\\u1260-\\u1288\\u128a-\\u128d\\u1290-\\u12b0\\u12b2-\\u12b5\\u12b8-\\u12be\\u12c0\\u12c2-\\u12c5\\u12c8-\\u12d6\\u12d8-\\u1310\\u1312-\\u1315\\u1318-\\u135a\\u1380-\\u138f\\u13a0-\\u13f5\\u13f8-\\u13fd\\u1401-\\u166c\\u166f-\\u167f\\u1681-\\u169a\\u16a0-\\u16ea\\u16ee-\\u16f8\\u1700-\\u1711\\u171f-\\u1731\\u1740-\\u1751\\u1760-\\u176c\\u176e-\\u1770\\u1780-\\u17b3\\u17d7\\u17dc\\u1820-\\u1878\\u1880-\\u18a8\\u18aa\\u18b0-\\u18f5\\u1900-\\u191e\\u1950-\\u196d\\u1970-\\u1974\\u1980-\\u19ab\\u19b0-\\u19c9\\u1a00-\\u1a16\\u1a20-\\u1a54\\u1aa7\\u1b05-\\u1b33\\u1b45-\\u1b4c\\u1b83-\\u1ba0\\u1bae\\u1baf\\u1bba-\\u1be5\\u1c00-\\u1c23\\u1c4d-\\u1c4f\\u1c5a-\\u1c7d\\u1c80-\\u1c88\\u1c90-\\u1cba\\u1cbd-\\u1cbf\\u1ce9-\\u1cec\\u1cee-\\u1cf3\\u1cf5\\u1cf6\\u1cfa\\u1d00-\\u1dbf\\u1e00-\\u1f15\\u1f18-\\u1f1d\\u1f20-\\u1f45\\u1f48-\\u1f4d\\u1f50-\\u1f57\\u1f59\\u1f5b\\u1f5d\\u1f5f-\\u1f7d\\u1f80-\\u1fb4\\u1fb6-\\u1fbc\\u1fbe\\u1fc2-\\u1fc4\\u1fc6-\\u1fcc\\u1fd0-\\u1fd3\\u1fd6-\\u1fdb\\u1fe0-\\u1fec\\u1ff2-\\u1ff4\\u1ff6-\\u1ffc\\u2071\\u207f\\u2090-\\u209c\\u2102\\u2107\\u210a-\\u2113\\u2115\\u2118-\\u211d\\u2124\\u2126\\u2128\\u212a-\\u2139\\u213c-\\u213f\\u2145-\\u2149\\u214e\\u2160-\\u2188\\u2c00-\\u2ce4\\u2ceb-\\u2cee\\u2cf2\\u2cf3\\u2d00-\\u2d25\\u2d27\\u2d2d\\u2d30-\\u2d67\\u2d6f\\u2d80-\\u2d96\\u2da0-\\u2da6\\u2da8-\\u2dae\\u2db0-\\u2db6\\u2db8-\\u2dbe\\u2dc0-\\u2dc6\\u2dc8-\\u2dce\\u2dd0-\\u2dd6\\u2dd8-\\u2dde\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303c\\u3041-\\u3096\\u309b-\\u309f\\u30a1-\\u30fa\\u30fc-\\u30ff\\u3105-\\u312f\\u3131-\\u318e\\u31a0-\\u31bf\\u31f0-\\u31ff\\u3400-\\u4dbf\\u4e00-\\ua48c\\ua4d0-\\ua4fd\\ua500-\\ua60c\\ua610-\\ua61f\\ua62a\\ua62b\\ua640-\\ua66e\\ua67f-\\ua69d\\ua6a0-\\ua6ef\\ua717-\\ua71f\\ua722-\\ua788\\ua78b-\\ua7ca\\ua7d0\\ua7d1\\ua7d3\\ua7d5-\\ua7d9\\ua7f2-\\ua801\\ua803-\\ua805\\ua807-\\ua80a\\ua80c-\\ua822\\ua840-\\ua873\\ua882-\\ua8b3\\ua8f2-\\ua8f7\\ua8fb\\ua8fd\\ua8fe\\ua90a-\\ua925\\ua930-\\ua946\\ua960-\\ua97c\\ua984-\\ua9b2\\ua9cf\\ua9e0-\\ua9e4\\ua9e6-\\ua9ef\\ua9fa-\\ua9fe\\uaa00-\\uaa28\\uaa40-\\uaa42\\uaa44-\\uaa4b\\uaa60-\\uaa76\\uaa7a\\uaa7e-\\uaaaf\\uaab1\\uaab5\\uaab6\\uaab9-\\uaabd\\uaac0\\uaac2\\uaadb-\\uaadd\\uaae0-\\uaaea\\uaaf2-\\uaaf4\\uab01-\\uab06\\uab09-\\uab0e\\uab11-\\uab16\\uab20-\\uab26\\uab28-\\uab2e\\uab30-\\uab5a\\uab5c-\\uab69\\uab70-\\uabe2\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\uf900-\\ufa6d\\ufa70-\\ufad9\\ufb00-\\ufb06\\ufb13-\\ufb17\\ufb1d\\ufb1f-\\ufb28\\ufb2a-\\ufb36\\ufb38-\\ufb3c\\ufb3e\\ufb40\\ufb41\\ufb43\\ufb44\\ufb46-\\ufbb1\\ufbd3-\\ufd3d\\ufd50-\\ufd8f\\ufd92-\\ufdc7\\ufdf0-\\ufdfb\\ufe70-\\ufe74\\ufe76-\\ufefc\\uff21-\\uff3a\\uff41-\\uff5a\\uff66-\\uffbe\\uffc2-\\uffc7\\uffca-\\uffcf\\uffd2-\\uffd7\\uffda-\\uffdc\";\n/* prettier-ignore */\nlet nonASCIIidentifierChars = \"\\u200c\\u200d\\xb7\\u0300-\\u036f\\u0387\\u0483-\\u0487\\u0591-\\u05bd\\u05bf\\u05c1\\u05c2\\u05c4\\u05c5\\u05c7\\u0610-\\u061a\\u064b-\\u0669\\u0670\\u06d6-\\u06dc\\u06df-\\u06e4\\u06e7\\u06e8\\u06ea-\\u06ed\\u06f0-\\u06f9\\u0711\\u0730-\\u074a\\u07a6-\\u07b0\\u07c0-\\u07c9\\u07eb-\\u07f3\\u07fd\\u0816-\\u0819\\u081b-\\u0823\\u0825-\\u0827\\u0829-\\u082d\\u0859-\\u085b\\u0898-\\u089f\\u08ca-\\u08e1\\u08e3-\\u0903\\u093a-\\u093c\\u093e-\\u094f\\u0951-\\u0957\\u0962\\u0963\\u0966-\\u096f\\u0981-\\u0983\\u09bc\\u09be-\\u09c4\\u09c7\\u09c8\\u09cb-\\u09cd\\u09d7\\u09e2\\u09e3\\u09e6-\\u09ef\\u09fe\\u0a01-\\u0a03\\u0a3c\\u0a3e-\\u0a42\\u0a47\\u0a48\\u0a4b-\\u0a4d\\u0a51\\u0a66-\\u0a71\\u0a75\\u0a81-\\u0a83\\u0abc\\u0abe-\\u0ac5\\u0ac7-\\u0ac9\\u0acb-\\u0acd\\u0ae2\\u0ae3\\u0ae6-\\u0aef\\u0afa-\\u0aff\\u0b01-\\u0b03\\u0b3c\\u0b3e-\\u0b44\\u0b47\\u0b48\\u0b4b-\\u0b4d\\u0b55-\\u0b57\\u0b62\\u0b63\\u0b66-\\u0b6f\\u0b82\\u0bbe-\\u0bc2\\u0bc6-\\u0bc8\\u0bca-\\u0bcd\\u0bd7\\u0be6-\\u0bef\\u0c00-\\u0c04\\u0c3c\\u0c3e-\\u0c44\\u0c46-\\u0c48\\u0c4a-\\u0c4d\\u0c55\\u0c56\\u0c62\\u0c63\\u0c66-\\u0c6f\\u0c81-\\u0c83\\u0cbc\\u0cbe-\\u0cc4\\u0cc6-\\u0cc8\\u0cca-\\u0ccd\\u0cd5\\u0cd6\\u0ce2\\u0ce3\\u0ce6-\\u0cef\\u0cf3\\u0d00-\\u0d03\\u0d3b\\u0d3c\\u0d3e-\\u0d44\\u0d46-\\u0d48\\u0d4a-\\u0d4d\\u0d57\\u0d62\\u0d63\\u0d66-\\u0d6f\\u0d81-\\u0d83\\u0dca\\u0dcf-\\u0dd4\\u0dd6\\u0dd8-\\u0ddf\\u0de6-\\u0def\\u0df2\\u0df3\\u0e31\\u0e34-\\u0e3a\\u0e47-\\u0e4e\\u0e50-\\u0e59\\u0eb1\\u0eb4-\\u0ebc\\u0ec8-\\u0ece\\u0ed0-\\u0ed9\\u0f18\\u0f19\\u0f20-\\u0f29\\u0f35\\u0f37\\u0f39\\u0f3e\\u0f3f\\u0f71-\\u0f84\\u0f86\\u0f87\\u0f8d-\\u0f97\\u0f99-\\u0fbc\\u0fc6\\u102b-\\u103e\\u1040-\\u1049\\u1056-\\u1059\\u105e-\\u1060\\u1062-\\u1064\\u1067-\\u106d\\u1071-\\u1074\\u1082-\\u108d\\u108f-\\u109d\\u135d-\\u135f\\u1369-\\u1371\\u1712-\\u1715\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17b4-\\u17d3\\u17dd\\u17e0-\\u17e9\\u180b-\\u180d\\u180f-\\u1819\\u18a9\\u1920-\\u192b\\u1930-\\u193b\\u1946-\\u194f\\u19d0-\\u19da\\u1a17-\\u1a1b\\u1a55-\\u1a5e\\u1a60-\\u1a7c\\u1a7f-\\u1a89\\u1a90-\\u1a99\\u1ab0-\\u1abd\\u1abf-\\u1ace\\u1b00-\\u1b04\\u1b34-\\u1b44\\u1b50-\\u1b59\\u1b6b-\\u1b73\\u1b80-\\u1b82\\u1ba1-\\u1bad\\u1bb0-\\u1bb9\\u1be6-\\u1bf3\\u1c24-\\u1c37\\u1c40-\\u1c49\\u1c50-\\u1c59\\u1cd0-\\u1cd2\\u1cd4-\\u1ce8\\u1ced\\u1cf4\\u1cf7-\\u1cf9\\u1dc0-\\u1dff\\u200c\\u200d\\u203f\\u2040\\u2054\\u20d0-\\u20dc\\u20e1\\u20e5-\\u20f0\\u2cef-\\u2cf1\\u2d7f\\u2de0-\\u2dff\\u302a-\\u302f\\u3099\\u309a\\u30fb\\ua620-\\ua629\\ua66f\\ua674-\\ua67d\\ua69e\\ua69f\\ua6f0\\ua6f1\\ua802\\ua806\\ua80b\\ua823-\\ua827\\ua82c\\ua880\\ua881\\ua8b4-\\ua8c5\\ua8d0-\\ua8d9\\ua8e0-\\ua8f1\\ua8ff-\\ua909\\ua926-\\ua92d\\ua947-\\ua953\\ua980-\\ua983\\ua9b3-\\ua9c0\\ua9d0-\\ua9d9\\ua9e5\\ua9f0-\\ua9f9\\uaa29-\\uaa36\\uaa43\\uaa4c\\uaa4d\\uaa50-\\uaa59\\uaa7b-\\uaa7d\\uaab0\\uaab2-\\uaab4\\uaab7\\uaab8\\uaabe\\uaabf\\uaac1\\uaaeb-\\uaaef\\uaaf5\\uaaf6\\uabe3-\\uabea\\uabec\\uabed\\uabf0-\\uabf9\\ufb1e\\ufe00-\\ufe0f\\ufe20-\\ufe2f\\ufe33\\ufe34\\ufe4d-\\ufe4f\\uff10-\\uff19\\uff3f\\uff65\";\n\nconst nonASCIIidentifierStart = new RegExp(\n \"[\" + nonASCIIidentifierStartChars + \"]\",\n);\nconst nonASCIIidentifier = new RegExp(\n \"[\" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + \"]\",\n);\n\nnonASCIIidentifierStartChars = nonASCIIidentifierChars = null;\n\n// These are a run-length and offset-encoded representation of the\n// >0xffff code points that are a valid part of identifiers. The\n// offset starts at 0x10000, and each pair of numbers represents an\n// offset to the next range, and then a size of the range. They were\n// generated by `scripts/generate-identifier-regex.js`.\n/* prettier-ignore */\nconst astralIdentifierStartCodes = [0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,68,310,10,21,11,7,25,5,2,41,2,8,70,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,349,41,7,1,79,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,20,1,64,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,264,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,4026,582,8634,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,689,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,43,8,8936,3,2,6,2,1,2,290,16,0,30,2,3,0,15,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,30,7,5,262,61,147,44,11,6,17,0,322,29,19,43,485,27,757,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4153,7,221,3,5761,15,7472,16,621,2467,541,1507,4938,6,4191];\n/* prettier-ignore */\nconst astralIdentifierCodes = [509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,370,1,81,2,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,406,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,10,1,2,0,49,6,4,4,14,9,5351,0,7,14,13835,9,87,9,39,4,60,6,26,9,1014,0,2,54,8,3,82,0,12,1,19628,1,4706,45,3,22,543,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,101,0,161,6,10,9,357,0,62,13,499,13,983,6,110,6,6,9,4759,9,787719,239];\n\n// This has a complexity linear to the value of the code. The\n// assumption is that looking up astral identifier characters is\n// rare.\nfunction isInAstralSet(code: number, set: readonly number[]): boolean {\n let pos = 0x10000;\n for (let i = 0, length = set.length; i < length; i += 2) {\n pos += set[i];\n if (pos > code) return false;\n\n pos += set[i + 1];\n if (pos >= code) return true;\n }\n return false;\n}\n\n// Test whether a given character code starts an identifier.\n\nexport function isIdentifierStart(code: number): boolean {\n if (code < charCodes.uppercaseA) return code === charCodes.dollarSign;\n if (code <= charCodes.uppercaseZ) return true;\n if (code < charCodes.lowercaseA) return code === charCodes.underscore;\n if (code <= charCodes.lowercaseZ) return true;\n if (code <= 0xffff) {\n return (\n code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code))\n );\n }\n return isInAstralSet(code, astralIdentifierStartCodes);\n}\n\n// Test whether a given character is part of an identifier.\n\nexport function isIdentifierChar(code: number): boolean {\n if (code < charCodes.digit0) return code === charCodes.dollarSign;\n if (code < charCodes.colon) return true;\n if (code < charCodes.uppercaseA) return false;\n if (code <= charCodes.uppercaseZ) return true;\n if (code < charCodes.lowercaseA) return code === charCodes.underscore;\n if (code <= charCodes.lowercaseZ) return true;\n if (code <= 0xffff) {\n return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));\n }\n return (\n isInAstralSet(code, astralIdentifierStartCodes) ||\n isInAstralSet(code, astralIdentifierCodes)\n );\n}\n\n// Test whether a given string is a valid identifier name\n\nexport function isIdentifierName(name: string): boolean {\n let isFirst = true;\n for (let i = 0; i < name.length; i++) {\n // The implementation is based on\n // https://source.chromium.org/chromium/chromium/src/+/master:v8/src/builtins/builtins-string-gen.cc;l=1455;drc=221e331b49dfefadbc6fa40b0c68e6f97606d0b3;bpv=0;bpt=1\n // We reimplement `codePointAt` because `codePointAt` is a V8 builtin which is not inlined by TurboFan (as of M91)\n // since `name` is mostly ASCII, an inlined `charCodeAt` wins here\n let cp = name.charCodeAt(i);\n if ((cp & 0xfc00) === 0xd800 && i + 1 < name.length) {\n const trail = name.charCodeAt(++i);\n if ((trail & 0xfc00) === 0xdc00) {\n cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff);\n }\n }\n if (isFirst) {\n isFirst = false;\n if (!isIdentifierStart(cp)) {\n return false;\n }\n } else if (!isIdentifierChar(cp)) {\n return false;\n }\n }\n return !isFirst;\n}\n","const reservedWords = {\n keyword: [\n \"break\",\n \"case\",\n \"catch\",\n \"continue\",\n \"debugger\",\n \"default\",\n \"do\",\n \"else\",\n \"finally\",\n \"for\",\n \"function\",\n \"if\",\n \"return\",\n \"switch\",\n \"throw\",\n \"try\",\n \"var\",\n \"const\",\n \"while\",\n \"with\",\n \"new\",\n \"this\",\n \"super\",\n \"class\",\n \"extends\",\n \"export\",\n \"import\",\n \"null\",\n \"true\",\n \"false\",\n \"in\",\n \"instanceof\",\n \"typeof\",\n \"void\",\n \"delete\",\n ],\n strict: [\n \"implements\",\n \"interface\",\n \"let\",\n \"package\",\n \"private\",\n \"protected\",\n \"public\",\n \"static\",\n \"yield\",\n ],\n strictBind: [\"eval\", \"arguments\"],\n};\nconst keywords = new Set(reservedWords.keyword);\nconst reservedWordsStrictSet = new Set(reservedWords.strict);\nconst reservedWordsStrictBindSet = new Set(reservedWords.strictBind);\n\n/**\n * Checks if word is a reserved word in non-strict mode\n */\nexport function isReservedWord(word: string, inModule: boolean): boolean {\n return (inModule && word === \"await\") || word === \"enum\";\n}\n\n/**\n * Checks if word is a reserved word in non-binding strict mode\n *\n * Includes non-strict reserved words\n */\nexport function isStrictReservedWord(word: string, inModule: boolean): boolean {\n return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);\n}\n\n/**\n * Checks if word is a reserved word in binding strict mode, but it is allowed as\n * a normal identifier.\n */\nexport function isStrictBindOnlyReservedWord(word: string): boolean {\n return reservedWordsStrictBindSet.has(word);\n}\n\n/**\n * Checks if word is a reserved word in binding strict mode\n *\n * Includes non-strict reserved words and non-binding strict reserved words\n */\nexport function isStrictBindReservedWord(\n word: string,\n inModule: boolean,\n): boolean {\n return (\n isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word)\n );\n}\n\nexport function isKeyword(word: string): boolean {\n return keywords.has(word);\n}\n","import * as charCodes from \"charcodes\";\nimport { isIdentifierStart } from \"@babel/helper-validator-identifier\";\n\nexport {\n isIdentifierStart,\n isIdentifierChar,\n isReservedWord,\n isStrictBindOnlyReservedWord,\n isStrictBindReservedWord,\n isStrictReservedWord,\n isKeyword,\n} from \"@babel/helper-validator-identifier\";\n\nexport const keywordRelationalOperator = /^in(stanceof)?$/;\n\n// Test whether a current state character code and next character code is @\n\nexport function isIteratorStart(\n current: number,\n next: number,\n next2: number,\n): boolean {\n return (\n current === charCodes.atSign &&\n next === charCodes.atSign &&\n isIdentifierStart(next2)\n );\n}\n\n// This is the comprehensive set of JavaScript reserved words\n// If a word is in this set, it could be a reserved word,\n// depending on sourceType/strictMode/binding info. In other words\n// if a word is not in this set, it is not a reserved word under\n// any circumstance.\nconst reservedWordLikeSet = new Set([\n \"break\",\n \"case\",\n \"catch\",\n \"continue\",\n \"debugger\",\n \"default\",\n \"do\",\n \"else\",\n \"finally\",\n \"for\",\n \"function\",\n \"if\",\n \"return\",\n \"switch\",\n \"throw\",\n \"try\",\n \"var\",\n \"const\",\n \"while\",\n \"with\",\n \"new\",\n \"this\",\n \"super\",\n \"class\",\n \"extends\",\n \"export\",\n \"import\",\n \"null\",\n \"true\",\n \"false\",\n \"in\",\n \"instanceof\",\n \"typeof\",\n \"void\",\n \"delete\",\n // strict\n \"implements\",\n \"interface\",\n \"let\",\n \"package\",\n \"private\",\n \"protected\",\n \"public\",\n \"static\",\n \"yield\",\n // strictBind\n \"eval\",\n \"arguments\",\n // reservedWorkLike\n \"enum\",\n \"await\",\n]);\n\nexport function canBeReservedWord(word: string): boolean {\n return reservedWordLikeSet.has(word);\n}\n","import { ScopeFlag, BindingFlag } from \"./scopeflags.ts\";\nimport type { Position } from \"./location.ts\";\nimport type * as N from \"../types.ts\";\nimport { Errors } from \"../parse-error.ts\";\nimport type Tokenizer from \"../tokenizer/index.ts\";\n\nexport const enum NameType {\n // var-declared names in the current lexical scope\n Var = 1 << 0,\n // lexically-declared names in the current lexical scope\n Lexical = 1 << 1,\n // lexically-declared FunctionDeclaration names in the current lexical scope\n Function = 1 << 2,\n}\n\n// Start an AST node, attaching a start offset.\nexport class Scope {\n flags: ScopeFlag = 0;\n names: Map = new Map();\n firstLexicalName = \"\";\n\n constructor(flags: ScopeFlag) {\n this.flags = flags;\n }\n}\n\n// The functions in this module keep track of declared variables in the\n// current scope in order to detect duplicate variable names.\nexport default class ScopeHandler {\n parser: Tokenizer;\n scopeStack: Array = [];\n inModule: boolean;\n undefinedExports: Map = new Map();\n\n constructor(parser: Tokenizer, inModule: boolean) {\n this.parser = parser;\n this.inModule = inModule;\n }\n\n get inTopLevel() {\n return (this.currentScope().flags & ScopeFlag.PROGRAM) > 0;\n }\n get inFunction() {\n return (this.currentVarScopeFlags() & ScopeFlag.FUNCTION) > 0;\n }\n get allowSuper() {\n return (this.currentThisScopeFlags() & ScopeFlag.SUPER) > 0;\n }\n get allowDirectSuper() {\n return (this.currentThisScopeFlags() & ScopeFlag.DIRECT_SUPER) > 0;\n }\n get inClass() {\n return (this.currentThisScopeFlags() & ScopeFlag.CLASS) > 0;\n }\n get inClassAndNotInNonArrowFunction() {\n const flags = this.currentThisScopeFlags();\n return (flags & ScopeFlag.CLASS) > 0 && (flags & ScopeFlag.FUNCTION) === 0;\n }\n get inStaticBlock() {\n for (let i = this.scopeStack.length - 1; ; i--) {\n const { flags } = this.scopeStack[i];\n if (flags & ScopeFlag.STATIC_BLOCK) {\n return true;\n }\n if (flags & (ScopeFlag.VAR | ScopeFlag.CLASS)) {\n // function body, module body, class property initializers\n return false;\n }\n }\n }\n get inNonArrowFunction() {\n return (this.currentThisScopeFlags() & ScopeFlag.FUNCTION) > 0;\n }\n get treatFunctionsAsVar() {\n return this.treatFunctionsAsVarInScope(this.currentScope());\n }\n\n createScope(flags: ScopeFlag): Scope {\n return new Scope(flags);\n }\n\n enter(flags: ScopeFlag) {\n /*:: +createScope: (flags:ScopeFlag) => IScope; */\n // @ts-expect-error This method will be overwritten by subclasses\n this.scopeStack.push(this.createScope(flags));\n }\n\n exit(): ScopeFlag {\n const scope = this.scopeStack.pop();\n return scope.flags;\n }\n\n // The spec says:\n // > At the top level of a function, or script, function declarations are\n // > treated like var declarations rather than like lexical declarations.\n treatFunctionsAsVarInScope(scope: IScope): boolean {\n return !!(\n scope.flags & (ScopeFlag.FUNCTION | ScopeFlag.STATIC_BLOCK) ||\n (!this.parser.inModule && scope.flags & ScopeFlag.PROGRAM)\n );\n }\n\n declareName(name: string, bindingType: BindingFlag, loc: Position) {\n let scope = this.currentScope();\n if (\n bindingType & BindingFlag.SCOPE_LEXICAL ||\n bindingType & BindingFlag.SCOPE_FUNCTION\n ) {\n this.checkRedeclarationInScope(scope, name, bindingType, loc);\n\n let type = scope.names.get(name) || 0;\n\n if (bindingType & BindingFlag.SCOPE_FUNCTION) {\n type = type | NameType.Function;\n } else {\n if (!scope.firstLexicalName) {\n scope.firstLexicalName = name;\n }\n type = type | NameType.Lexical;\n }\n\n scope.names.set(name, type);\n\n if (bindingType & BindingFlag.SCOPE_LEXICAL) {\n this.maybeExportDefined(scope, name);\n }\n } else if (bindingType & BindingFlag.SCOPE_VAR) {\n for (let i = this.scopeStack.length - 1; i >= 0; --i) {\n scope = this.scopeStack[i];\n this.checkRedeclarationInScope(scope, name, bindingType, loc);\n scope.names.set(name, (scope.names.get(name) || 0) | NameType.Var);\n this.maybeExportDefined(scope, name);\n\n if (scope.flags & ScopeFlag.VAR) break;\n }\n }\n if (this.parser.inModule && scope.flags & ScopeFlag.PROGRAM) {\n this.undefinedExports.delete(name);\n }\n }\n\n maybeExportDefined(scope: IScope, name: string) {\n if (this.parser.inModule && scope.flags & ScopeFlag.PROGRAM) {\n this.undefinedExports.delete(name);\n }\n }\n\n checkRedeclarationInScope(\n scope: IScope,\n name: string,\n bindingType: BindingFlag,\n loc: Position,\n ) {\n if (this.isRedeclaredInScope(scope, name, bindingType)) {\n this.parser.raise(Errors.VarRedeclaration, loc, {\n identifierName: name,\n });\n }\n }\n\n isRedeclaredInScope(\n scope: IScope,\n name: string,\n bindingType: BindingFlag,\n ): boolean {\n if (!(bindingType & BindingFlag.KIND_VALUE)) return false;\n\n if (bindingType & BindingFlag.SCOPE_LEXICAL) {\n return scope.names.has(name);\n }\n\n const type = scope.names.get(name);\n\n if (bindingType & BindingFlag.SCOPE_FUNCTION) {\n return (\n (type & NameType.Lexical) > 0 ||\n (!this.treatFunctionsAsVarInScope(scope) && (type & NameType.Var) > 0)\n );\n }\n\n return (\n ((type & NameType.Lexical) > 0 &&\n // Annex B.3.4\n // https://tc39.es/ecma262/#sec-variablestatements-in-catch-blocks\n !(\n scope.flags & ScopeFlag.SIMPLE_CATCH &&\n scope.firstLexicalName === name\n )) ||\n (!this.treatFunctionsAsVarInScope(scope) &&\n (type & NameType.Function) > 0)\n );\n }\n\n checkLocalExport(id: N.Identifier) {\n const { name } = id;\n const topLevelScope = this.scopeStack[0];\n if (!topLevelScope.names.has(name)) {\n this.undefinedExports.set(name, id.loc.start);\n }\n }\n\n currentScope(): IScope {\n return this.scopeStack[this.scopeStack.length - 1];\n }\n\n currentVarScopeFlags(): ScopeFlag {\n for (let i = this.scopeStack.length - 1; ; i--) {\n const { flags } = this.scopeStack[i];\n if (flags & ScopeFlag.VAR) {\n return flags;\n }\n }\n }\n\n // Could be useful for `arguments`, `this`, `new.target`, `super()`, `super.property`, and `super[property]`.\n currentThisScopeFlags(): ScopeFlag {\n for (let i = this.scopeStack.length - 1; ; i--) {\n const { flags } = this.scopeStack[i];\n if (\n flags & (ScopeFlag.VAR | ScopeFlag.CLASS) &&\n !(flags & ScopeFlag.ARROW)\n ) {\n return flags;\n }\n }\n }\n}\n","import type { Position } from \"../../util/location.ts\";\nimport ScopeHandler, { NameType, Scope } from \"../../util/scope.ts\";\nimport { BindingFlag, type ScopeFlag } from \"../../util/scopeflags.ts\";\nimport type * as N from \"../../types.ts\";\n\n// Reference implementation: https://github.com/facebook/flow/blob/23aeb2a2ef6eb4241ce178fde5d8f17c5f747fb5/src/typing/env.ml#L536-L584\nclass FlowScope extends Scope {\n // declare function foo(): type;\n declareFunctions: Set = new Set();\n}\n\nexport default class FlowScopeHandler extends ScopeHandler {\n createScope(flags: ScopeFlag): FlowScope {\n return new FlowScope(flags);\n }\n\n declareName(name: string, bindingType: BindingFlag, loc: Position) {\n const scope = this.currentScope();\n if (bindingType & BindingFlag.FLAG_FLOW_DECLARE_FN) {\n this.checkRedeclarationInScope(scope, name, bindingType, loc);\n this.maybeExportDefined(scope, name);\n scope.declareFunctions.add(name);\n return;\n }\n\n super.declareName(name, bindingType, loc);\n }\n\n isRedeclaredInScope(\n scope: FlowScope,\n name: string,\n bindingType: BindingFlag,\n ): boolean {\n if (super.isRedeclaredInScope(scope, name, bindingType)) return true;\n\n if (\n bindingType & BindingFlag.FLAG_FLOW_DECLARE_FN &&\n !scope.declareFunctions.has(name)\n ) {\n const type = scope.names.get(name);\n return (type & NameType.Function) > 0 || (type & NameType.Lexical) > 0;\n }\n\n return false;\n }\n\n checkLocalExport(id: N.Identifier) {\n if (!this.scopeStack[0].declareFunctions.has(id.name)) {\n super.checkLocalExport(id);\n }\n }\n}\n","import type { Options } from \"../options.ts\";\nimport type State from \"../tokenizer/state.ts\";\nimport type { PluginsMap } from \"./index.ts\";\nimport type ScopeHandler from \"../util/scope.ts\";\nimport type ExpressionScopeHandler from \"../util/expression-scope.ts\";\nimport type ClassScopeHandler from \"../util/class-scope.ts\";\nimport type ProductionParameterHandler from \"../util/production-parameter.ts\";\nimport type {\n ParserPluginWithOptions,\n PluginConfig,\n PluginOptions,\n} from \"../typings.ts\";\nimport type * as N from \"../types.ts\";\n\nexport default class BaseParser {\n // Properties set by constructor in index.js\n declare options: Options;\n declare inModule: boolean;\n declare scope: ScopeHandler;\n declare classScope: ClassScopeHandler;\n declare prodParam: ProductionParameterHandler;\n declare expressionScope: ExpressionScopeHandler;\n declare plugins: PluginsMap;\n declare filename: string | undefined | null;\n // Names of exports store. `default` is stored as a name for both\n // `export default foo;` and `export { foo as default };`.\n declare exportedIdentifiers: Set;\n sawUnambiguousESM: boolean = false;\n ambiguousScriptDifferentAst: boolean = false;\n\n // Initialized by Tokenizer\n declare state: State;\n // input and length are not in state as they are constant and we do\n // not want to ever copy them, which happens if state gets cloned\n declare input: string;\n declare length: number;\n // Comment store for Program.comments\n declare comments: Array;\n\n // This method accepts either a string (plugin name) or an array pair\n // (plugin name and options object). If an options object is given,\n // then each value is non-recursively checked for identity with that\n // plugin’s actual option value.\n hasPlugin(pluginConfig: PluginConfig): boolean {\n if (typeof pluginConfig === \"string\") {\n return this.plugins.has(pluginConfig);\n } else {\n const [pluginName, pluginOptions] = pluginConfig;\n if (!this.hasPlugin(pluginName)) {\n return false;\n }\n const actualOptions = this.plugins.get(pluginName);\n for (const key of Object.keys(\n pluginOptions,\n ) as (keyof typeof pluginOptions)[]) {\n if (actualOptions?.[key] !== pluginOptions[key]) {\n return false;\n }\n }\n return true;\n }\n }\n\n getPluginOption<\n PluginName extends ParserPluginWithOptions[0],\n OptionName extends keyof PluginOptions,\n >(plugin: PluginName, name: OptionName) {\n return (this.plugins.get(plugin) as null | PluginOptions)?.[\n name\n ];\n }\n}\n","/*:: declare var invariant; */\n\nimport BaseParser from \"./base.ts\";\nimport type { Comment, Node, Identifier } from \"../types.ts\";\nimport * as charCodes from \"charcodes\";\nimport type { Undone } from \"./node.ts\";\n\n/**\n * A whitespace token containing comments\n */\nexport type CommentWhitespace = {\n /**\n * the start of the whitespace token.\n */\n start: number;\n /**\n * the end of the whitespace token.\n */\n end: number;\n /**\n * the containing comments\n */\n comments: Array;\n /**\n * the immediately preceding AST node of the whitespace token\n */\n leadingNode: Node | null;\n /**\n * the immediately following AST node of the whitespace token\n */\n trailingNode: Node | null;\n /**\n * the innermost AST node containing the whitespace with minimal size (|end - start|)\n */\n containingNode: Node | null;\n};\n\n/**\n * Merge comments with node's trailingComments or assign comments to be\n * trailingComments. New comments will be placed before old comments\n * because the commentStack is enumerated reversely.\n */\nfunction setTrailingComments(node: Undone, comments: Array) {\n if (node.trailingComments === undefined) {\n node.trailingComments = comments;\n } else {\n node.trailingComments.unshift(...comments);\n }\n}\n\n/**\n * Merge comments with node's leadingComments or assign comments to be\n * leadingComments. New comments will be placed before old comments\n * because the commentStack is enumerated reversely.\n */\nfunction setLeadingComments(node: Undone, comments: Array) {\n if (node.leadingComments === undefined) {\n node.leadingComments = comments;\n } else {\n node.leadingComments.unshift(...comments);\n }\n}\n\n/**\n * Merge comments with node's innerComments or assign comments to be\n * innerComments. New comments will be placed before old comments\n * because the commentStack is enumerated reversely.\n */\nexport function setInnerComments(\n node: Undone,\n comments?: Array,\n) {\n if (node.innerComments === undefined) {\n node.innerComments = comments;\n } else {\n node.innerComments.unshift(...comments);\n }\n}\n\n/**\n * Given node and elements array, if elements has non-null element,\n * merge comments to its trailingComments, otherwise merge comments\n * to node's innerComments\n */\nfunction adjustInnerComments(\n node: Undone,\n elements: Array,\n commentWS: CommentWhitespace,\n) {\n let lastElement = null;\n let i = elements.length;\n while (lastElement === null && i > 0) {\n lastElement = elements[--i];\n }\n if (lastElement === null || lastElement.start > commentWS.start) {\n setInnerComments(node, commentWS.comments);\n } else {\n setTrailingComments(lastElement, commentWS.comments);\n }\n}\n\nexport default class CommentsParser extends BaseParser {\n addComment(comment: Comment): void {\n if (this.filename) comment.loc.filename = this.filename;\n const { commentsLen } = this.state;\n if (this.comments.length !== commentsLen) {\n this.comments.length = commentsLen;\n }\n this.comments.push(comment);\n this.state.commentsLen++;\n }\n\n /**\n * Given a newly created AST node _n_, attach _n_ to a comment whitespace _w_ if applicable\n * {@see {@link CommentWhitespace}}\n */\n processComment(node: Node): void {\n const { commentStack } = this.state;\n const commentStackLength = commentStack.length;\n if (commentStackLength === 0) return;\n let i = commentStackLength - 1;\n const lastCommentWS = commentStack[i];\n\n if (lastCommentWS.start === node.end) {\n lastCommentWS.leadingNode = node;\n i--;\n }\n\n const { start: nodeStart } = node;\n // invariant: for all 0 <= j <= i, let c = commentStack[j], c must satisfy c.end < node.end\n for (; i >= 0; i--) {\n const commentWS = commentStack[i];\n const commentEnd = commentWS.end;\n if (commentEnd > nodeStart) {\n // by definition of commentWhiteSpace, this implies commentWS.start > nodeStart\n // so node can be a containingNode candidate. At this time we can finalize the comment\n // whitespace, because\n // 1) its leadingNode or trailingNode, if exists, will not change\n // 2) its containingNode have been assigned and will not change because it is the\n // innermost minimal-sized AST node\n commentWS.containingNode = node;\n this.finalizeComment(commentWS);\n commentStack.splice(i, 1);\n } else {\n if (commentEnd === nodeStart) {\n commentWS.trailingNode = node;\n }\n // stop the loop when commentEnd <= nodeStart\n break;\n }\n }\n }\n\n /**\n * Assign the comments of comment whitespaces to related AST nodes.\n * Also adjust innerComments following trailing comma.\n */\n finalizeComment(commentWS: CommentWhitespace) {\n const { comments } = commentWS;\n if (commentWS.leadingNode !== null || commentWS.trailingNode !== null) {\n if (commentWS.leadingNode !== null) {\n setTrailingComments(commentWS.leadingNode, comments);\n }\n if (commentWS.trailingNode !== null) {\n setLeadingComments(commentWS.trailingNode, comments);\n }\n } else {\n /*:: invariant(commentWS.containingNode !== null) */\n const { containingNode: node, start: commentStart } = commentWS;\n if (this.input.charCodeAt(commentStart - 1) === charCodes.comma) {\n // If a commentWhitespace follows a comma and the containingNode allows\n // list structures with trailing comma, merge it to the trailingComment\n // of the last non-null list element\n switch (node.type) {\n case \"ObjectExpression\":\n case \"ObjectPattern\":\n case \"RecordExpression\":\n adjustInnerComments(node, node.properties, commentWS);\n break;\n case \"CallExpression\":\n case \"OptionalCallExpression\":\n adjustInnerComments(node, node.arguments, commentWS);\n break;\n case \"FunctionDeclaration\":\n case \"FunctionExpression\":\n case \"ArrowFunctionExpression\":\n case \"ObjectMethod\":\n case \"ClassMethod\":\n case \"ClassPrivateMethod\":\n adjustInnerComments(node, node.params, commentWS);\n break;\n case \"ArrayExpression\":\n case \"ArrayPattern\":\n case \"TupleExpression\":\n adjustInnerComments(node, node.elements, commentWS);\n break;\n case \"ExportNamedDeclaration\":\n case \"ImportDeclaration\":\n adjustInnerComments(node, node.specifiers, commentWS);\n break;\n default: {\n setInnerComments(node, comments);\n }\n }\n } else {\n setInnerComments(node, comments);\n }\n }\n }\n\n /**\n * Drains remaining commentStack and applies finalizeComment\n * to each comment whitespace. Used only in parseExpression\n * where the top level AST node is _not_ Program\n * {@see {@link CommentsParser#finalizeComment}}\n */\n finalizeRemainingComments() {\n const { commentStack } = this.state;\n for (let i = commentStack.length - 1; i >= 0; i--) {\n this.finalizeComment(commentStack[i]);\n }\n this.state.commentStack = [];\n }\n\n /* eslint-disable no-irregular-whitespace */\n /**\n * Reset previous node trailing comments. Used in object / class\n * property parsing. We parse `async`, `static`, `set` and `get`\n * as an identifier but may reinterpret it into an async/static/accessor\n * method later. In this case the identifier is not part of the AST and we\n * should sync the knowledge to commentStacks\n *\n * For example, when parsing\n * ```\n * async /* 1 *​/ function f() {}\n * ```\n * the comment whitespace `/* 1 *​/` has leading node Identifier(async). When\n * we see the function token, we create a Function node and mark `/* 1 *​/` as\n * inner comments. So `/* 1 *​/` should be detached from the Identifier node.\n *\n * @param node the last finished AST node _before_ current token\n */\n /* eslint-enable no-irregular-whitespace */\n resetPreviousNodeTrailingComments(node: Node) {\n const { commentStack } = this.state;\n const { length } = commentStack;\n if (length === 0) return;\n const commentWS = commentStack[length - 1];\n if (commentWS.leadingNode === node) {\n commentWS.leadingNode = null;\n }\n }\n\n /* eslint-disable no-irregular-whitespace */\n /**\n * Reset previous node leading comments, assuming that `node` is a\n * single-token node. Used in import phase modifiers parsing. We parse\n * `module` in `import module foo from ...` as an identifier but may\n * reinterpret it into a phase modifier later. In this case the identifier is\n * not part of the AST and we should sync the knowledge to commentStacks\n *\n * For example, when parsing\n * ```\n * import /* 1 *​/ module a from \"a\";\n * ```\n * the comment whitespace `/* 1 *​/` has trailing node Identifier(module). When\n * we see that `module` is not a default import binding, we mark `/* 1 *​/` as\n * inner comments of the ImportDeclaration. So `/* 1 *​/` should be detached from\n * the Identifier node.\n *\n * @param node the last finished AST node _before_ current token\n */\n /* eslint-enable no-irregular-whitespace */\n resetPreviousIdentifierLeadingComments(node: Identifier) {\n const { commentStack } = this.state;\n const { length } = commentStack;\n if (length === 0) return;\n\n if (commentStack[length - 1].trailingNode === node) {\n commentStack[length - 1].trailingNode = null;\n } else if (length >= 2 && commentStack[length - 2].trailingNode === node) {\n commentStack[length - 2].trailingNode = null;\n }\n }\n\n /**\n * Attach a node to the comment whitespaces right before/after\n * the given range.\n *\n * This is used to properly attach comments around parenthesized\n * expressions as leading/trailing comments of the inner expression.\n */\n takeSurroundingComments(node: Node, start: number, end: number) {\n const { commentStack } = this.state;\n const commentStackLength = commentStack.length;\n if (commentStackLength === 0) return;\n let i = commentStackLength - 1;\n\n for (; i >= 0; i--) {\n const commentWS = commentStack[i];\n const commentEnd = commentWS.end;\n const commentStart = commentWS.start;\n\n if (commentStart === end) {\n commentWS.leadingNode = node;\n } else if (commentEnd === start) {\n commentWS.trailingNode = node;\n } else if (commentEnd < start) {\n break;\n }\n }\n }\n}\n","import * as charCodes from \"charcodes\";\n\n// Matches a whole line break (where CRLF is considered a single\n// line break). Used to count lines.\nexport const lineBreak = /\\r\\n|[\\r\\n\\u2028\\u2029]/;\nexport const lineBreakG = new RegExp(lineBreak.source, \"g\");\n\n// https://tc39.github.io/ecma262/#sec-line-terminators\nexport function isNewLine(code: number): boolean {\n switch (code) {\n case charCodes.lineFeed:\n case charCodes.carriageReturn:\n case charCodes.lineSeparator:\n case charCodes.paragraphSeparator:\n return true;\n\n default:\n return false;\n }\n}\n\nexport function hasNewLine(input: string, start: number, end: number): boolean {\n for (let i = start; i < end; i++) {\n if (isNewLine(input.charCodeAt(i))) {\n return true;\n }\n }\n return false;\n}\n\nexport const skipWhiteSpace = /(?:\\s|\\/\\/.*|\\/\\*[^]*?\\*\\/)*/g;\n\nexport const skipWhiteSpaceInLine =\n /(?:[^\\S\\n\\r\\u2028\\u2029]|\\/\\/.*|\\/\\*.*?\\*\\/)*/g;\n\n// https://tc39.github.io/ecma262/#sec-white-space\nexport function isWhitespace(code: number): boolean {\n switch (code) {\n case 0x0009: // CHARACTER TABULATION\n case 0x000b: // LINE TABULATION\n case 0x000c: // FORM FEED\n case charCodes.space:\n case charCodes.nonBreakingSpace:\n case charCodes.oghamSpaceMark:\n case 0x2000: // EN QUAD\n case 0x2001: // EM QUAD\n case 0x2002: // EN SPACE\n case 0x2003: // EM SPACE\n case 0x2004: // THREE-PER-EM SPACE\n case 0x2005: // FOUR-PER-EM SPACE\n case 0x2006: // SIX-PER-EM SPACE\n case 0x2007: // FIGURE SPACE\n case 0x2008: // PUNCTUATION SPACE\n case 0x2009: // THIN SPACE\n case 0x200a: // HAIR SPACE\n case 0x202f: // NARROW NO-BREAK SPACE\n case 0x205f: // MEDIUM MATHEMATICAL SPACE\n case 0x3000: // IDEOGRAPHIC SPACE\n case 0xfeff: // ZERO WIDTH NO-BREAK SPACE\n return true;\n\n default:\n return false;\n }\n}\n","import type { Options } from \"../options.ts\";\nimport type { CommentWhitespace } from \"../parser/comments\";\nimport { Position } from \"../util/location.ts\";\n\nimport { types as ct, type TokContext } from \"./context.ts\";\nimport { tt, type TokenType } from \"./types.ts\";\nimport type { Errors } from \"../parse-error.ts\";\nimport type { ParseError } from \"../parse-error.ts\";\n\nexport type DeferredStrictError =\n | typeof Errors.StrictNumericEscape\n | typeof Errors.StrictOctalLiteral;\n\ntype TopicContextState = {\n // When a topic binding has been currently established,\n // then this is 1. Otherwise, it is 0. This is forwards compatible\n // with a future plugin for multiple lexical topics.\n maxNumOfResolvableTopics: number;\n // When a topic binding has been currently established, and if that binding\n // has been used as a topic reference `#`, then this is 0. Otherwise, it is\n // `null`. This is forwards compatible with a future plugin for multiple\n // lexical topics.\n maxTopicIndex: null | 0;\n};\n\nexport const enum LoopLabelKind {\n Loop = 1,\n Switch = 2,\n}\n\ndeclare const bit: import(\"../../../../scripts/babel-plugin-bit-decorator/types.d.ts\").BitDecorator;\n\nexport default class State {\n @bit.storage flags: number;\n\n @bit accessor strict = false;\n\n curLine: number;\n lineStart: number;\n\n // And, if locations are used, the {line, column} object\n // corresponding to those offsets\n startLoc: Position;\n endLoc: Position;\n\n init({ strictMode, sourceType, startLine, startColumn }: Options): void {\n this.strict =\n strictMode === false\n ? false\n : strictMode === true\n ? true\n : sourceType === \"module\";\n\n this.curLine = startLine;\n this.lineStart = -startColumn;\n this.startLoc = this.endLoc = new Position(startLine, startColumn, 0);\n }\n\n errors: ParseError[] = [];\n\n // Used to signify the start of a potential arrow function\n potentialArrowAt: number = -1;\n\n // Used to signify the start of an expression which looks like a\n // typed arrow function, but it isn't\n // e.g. a ? (b) : c => d\n // ^\n noArrowAt: number[] = [];\n\n // Used to signify the start of an expression whose params, if it looks like\n // an arrow function, shouldn't be converted to assignable nodes.\n // This is used to defer the validation of typed arrow functions inside\n // conditional expressions.\n // e.g. a ? (b) : c => d\n // ^\n noArrowParamsConversionAt: number[] = [];\n\n // Flags to track\n @bit accessor maybeInArrowParameters = false;\n @bit accessor inType = false;\n @bit accessor noAnonFunctionType = false;\n @bit accessor hasFlowComment = false;\n @bit accessor isAmbientContext = false;\n @bit accessor inAbstractClass = false;\n @bit accessor inDisallowConditionalTypesContext = false;\n\n // For the Hack-style pipelines plugin\n topicContext: TopicContextState = {\n maxNumOfResolvableTopics: 0,\n maxTopicIndex: null,\n };\n\n // For the F#-style pipelines plugin\n @bit accessor soloAwait = false;\n @bit accessor inFSharpPipelineDirectBody = false;\n\n // Labels in scope.\n labels: Array<{\n kind: LoopLabelKind;\n name?: string | null;\n statementStart?: number;\n }> = [];\n\n commentsLen = 0;\n // Comment attachment store\n commentStack: Array = [];\n\n // The current position of the tokenizer in the input.\n pos: number = 0;\n\n // Properties of the current token:\n // Its type\n type: TokenType = tt.eof;\n\n // For tokens that include more information than their type, the value\n value: any = null;\n\n // Its start and end offset\n start: number = 0;\n end: number = 0;\n\n // Position information for the previous token\n // this is initialized when generating the second token.\n lastTokEndLoc: Position = null;\n // this is initialized when generating the second token.\n lastTokStartLoc: Position = null;\n\n // The context stack is used to track whether the apostrophe \"`\" starts\n // or ends a string template\n context: Array = [ct.brace];\n\n // Used to track whether a JSX element is allowed to form\n @bit accessor canStartJSXElement = true;\n\n // Used to signal to callers of `readWord1` whether the word\n // contained any escape sequences. This is needed because words with\n // escape sequences must not be interpreted as keywords.\n @bit accessor containsEsc = false;\n\n // Used to track invalid escape sequences in template literals,\n // that must be reported if the template is not tagged.\n firstInvalidTemplateEscapePos: null | Position = null;\n\n @bit accessor hasTopLevelAwait = false;\n\n // This property is used to track the following errors\n // - StrictNumericEscape\n // - StrictOctalLiteral\n //\n // in a literal that occurs prior to/immediately after a \"use strict\" directive.\n\n // todo(JLHwung): set strictErrors to null and avoid recording string errors\n // after a non-directive is parsed\n strictErrors: Map = new Map();\n\n // Tokens length in token store\n tokensLength: number = 0;\n\n /**\n * When we add a new property, we must manually update the `clone` method\n * @see State#clone\n */\n\n curPosition(): Position {\n return new Position(this.curLine, this.pos - this.lineStart, this.pos);\n }\n\n clone(): State {\n const state = new State();\n state.flags = this.flags;\n state.curLine = this.curLine;\n state.lineStart = this.lineStart;\n state.startLoc = this.startLoc;\n state.endLoc = this.endLoc;\n state.errors = this.errors.slice();\n state.potentialArrowAt = this.potentialArrowAt;\n state.noArrowAt = this.noArrowAt.slice();\n state.noArrowParamsConversionAt = this.noArrowParamsConversionAt.slice();\n state.topicContext = this.topicContext;\n state.labels = this.labels.slice();\n state.commentsLen = this.commentsLen;\n state.commentStack = this.commentStack.slice();\n state.pos = this.pos;\n state.type = this.type;\n state.value = this.value;\n state.start = this.start;\n state.end = this.end;\n state.lastTokEndLoc = this.lastTokEndLoc;\n state.lastTokStartLoc = this.lastTokStartLoc;\n state.context = this.context.slice();\n state.firstInvalidTemplateEscapePos = this.firstInvalidTemplateEscapePos;\n state.strictErrors = this.strictErrors;\n state.tokensLength = this.tokensLength;\n\n return state;\n }\n}\n\nexport type LookaheadState = {\n pos: number;\n value: any;\n type: TokenType;\n start: number;\n end: number;\n context: TokContext[];\n startLoc: Position;\n lastTokEndLoc: Position;\n curLine: number;\n lineStart: number;\n curPosition: () => Position;\n /* Used only in readToken_mult_modulo */\n inType: boolean;\n // These boolean properties are not initialized in createLookaheadState()\n // instead they will only be set by the tokenizer\n containsEsc?: boolean;\n};\n","// We inline this package\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport * as charCodes from \"charcodes\";\n\n// The following character codes are forbidden from being\n// an immediate sibling of NumericLiteralSeparator _\nconst forbiddenNumericSeparatorSiblings = {\n decBinOct: new Set([\n charCodes.dot,\n charCodes.uppercaseB,\n charCodes.uppercaseE,\n charCodes.uppercaseO,\n charCodes.underscore, // multiple separators are not allowed\n charCodes.lowercaseB,\n charCodes.lowercaseE,\n charCodes.lowercaseO,\n ]),\n hex: new Set([\n charCodes.dot,\n charCodes.uppercaseX,\n charCodes.underscore, // multiple separators are not allowed\n charCodes.lowercaseX,\n ]),\n};\n\nconst isAllowedNumericSeparatorSibling = {\n // 0 - 1\n bin: (ch: number) => ch === charCodes.digit0 || ch === charCodes.digit1,\n\n // 0 - 7\n oct: (ch: number) => ch >= charCodes.digit0 && ch <= charCodes.digit7,\n\n // 0 - 9\n dec: (ch: number) => ch >= charCodes.digit0 && ch <= charCodes.digit9,\n\n // 0 - 9, A - F, a - f,\n hex: (ch: number) =>\n (ch >= charCodes.digit0 && ch <= charCodes.digit9) ||\n (ch >= charCodes.uppercaseA && ch <= charCodes.uppercaseF) ||\n (ch >= charCodes.lowercaseA && ch <= charCodes.lowercaseF),\n};\n\nexport type StringContentsErrorHandlers = EscapedCharErrorHandlers & {\n unterminated(\n initialPos: number,\n initialLineStart: number,\n initialCurLine: number,\n ): void;\n};\n\nexport function readStringContents(\n type: \"single\" | \"double\" | \"template\",\n input: string,\n pos: number,\n lineStart: number,\n curLine: number,\n errors: StringContentsErrorHandlers,\n) {\n const initialPos = pos;\n const initialLineStart = lineStart;\n const initialCurLine = curLine;\n\n let out = \"\";\n let firstInvalidLoc = null;\n let chunkStart = pos;\n const { length } = input;\n for (;;) {\n if (pos >= length) {\n errors.unterminated(initialPos, initialLineStart, initialCurLine);\n out += input.slice(chunkStart, pos);\n break;\n }\n const ch = input.charCodeAt(pos);\n if (isStringEnd(type, ch, input, pos)) {\n out += input.slice(chunkStart, pos);\n break;\n }\n if (ch === charCodes.backslash) {\n out += input.slice(chunkStart, pos);\n const res = readEscapedChar(\n input,\n pos,\n lineStart,\n curLine,\n type === \"template\",\n errors,\n );\n if (res.ch === null && !firstInvalidLoc) {\n firstInvalidLoc = { pos, lineStart, curLine };\n } else {\n out += res.ch;\n }\n ({ pos, lineStart, curLine } = res);\n chunkStart = pos;\n } else if (\n ch === charCodes.lineSeparator ||\n ch === charCodes.paragraphSeparator\n ) {\n ++pos;\n ++curLine;\n lineStart = pos;\n } else if (ch === charCodes.lineFeed || ch === charCodes.carriageReturn) {\n if (type === \"template\") {\n out += input.slice(chunkStart, pos) + \"\\n\";\n ++pos;\n if (\n ch === charCodes.carriageReturn &&\n input.charCodeAt(pos) === charCodes.lineFeed\n ) {\n ++pos;\n }\n ++curLine;\n chunkStart = lineStart = pos;\n } else {\n errors.unterminated(initialPos, initialLineStart, initialCurLine);\n }\n } else {\n ++pos;\n }\n }\n return process.env.BABEL_8_BREAKING\n ? { pos, str: out, firstInvalidLoc, lineStart, curLine }\n : {\n pos,\n str: out,\n firstInvalidLoc,\n lineStart,\n curLine,\n containsInvalid: !!firstInvalidLoc,\n };\n}\n\nfunction isStringEnd(\n type: \"single\" | \"double\" | \"template\",\n ch: number,\n input: string,\n pos: number,\n) {\n if (type === \"template\") {\n return (\n ch === charCodes.graveAccent ||\n (ch === charCodes.dollarSign &&\n input.charCodeAt(pos + 1) === charCodes.leftCurlyBrace)\n );\n }\n return (\n ch === (type === \"double\" ? charCodes.quotationMark : charCodes.apostrophe)\n );\n}\n\ntype EscapedCharErrorHandlers = HexCharErrorHandlers &\n CodePointErrorHandlers & {\n strictNumericEscape(pos: number, lineStart: number, curLine: number): void;\n };\n\nfunction readEscapedChar(\n input: string,\n pos: number,\n lineStart: number,\n curLine: number,\n inTemplate: boolean,\n errors: EscapedCharErrorHandlers,\n) {\n const throwOnInvalid = !inTemplate;\n pos++; // skip '\\'\n\n const res = (ch: string | null) => ({ pos, ch, lineStart, curLine });\n\n const ch = input.charCodeAt(pos++);\n switch (ch) {\n case charCodes.lowercaseN:\n return res(\"\\n\");\n case charCodes.lowercaseR:\n return res(\"\\r\");\n case charCodes.lowercaseX: {\n let code;\n ({ code, pos } = readHexChar(\n input,\n pos,\n lineStart,\n curLine,\n 2,\n false,\n throwOnInvalid,\n errors,\n ));\n return res(code === null ? null : String.fromCharCode(code));\n }\n case charCodes.lowercaseU: {\n let code;\n ({ code, pos } = readCodePoint(\n input,\n pos,\n lineStart,\n curLine,\n throwOnInvalid,\n errors,\n ));\n return res(code === null ? null : String.fromCodePoint(code));\n }\n case charCodes.lowercaseT:\n return res(\"\\t\");\n case charCodes.lowercaseB:\n return res(\"\\b\");\n case charCodes.lowercaseV:\n return res(\"\\u000b\");\n case charCodes.lowercaseF:\n return res(\"\\f\");\n case charCodes.carriageReturn:\n if (input.charCodeAt(pos) === charCodes.lineFeed) {\n ++pos;\n }\n // fall through\n case charCodes.lineFeed:\n lineStart = pos;\n ++curLine;\n // fall through\n case charCodes.lineSeparator:\n case charCodes.paragraphSeparator:\n return res(\"\");\n case charCodes.digit8:\n case charCodes.digit9:\n if (inTemplate) {\n return res(null);\n } else {\n errors.strictNumericEscape(pos - 1, lineStart, curLine);\n }\n // fall through\n default:\n if (ch >= charCodes.digit0 && ch <= charCodes.digit7) {\n const startPos = pos - 1;\n const match = /^[0-7]+/.exec(input.slice(startPos, pos + 2));\n\n let octalStr = match[0];\n\n let octal = parseInt(octalStr, 8);\n if (octal > 255) {\n octalStr = octalStr.slice(0, -1);\n octal = parseInt(octalStr, 8);\n }\n pos += octalStr.length - 1;\n const next = input.charCodeAt(pos);\n if (\n octalStr !== \"0\" ||\n next === charCodes.digit8 ||\n next === charCodes.digit9\n ) {\n if (inTemplate) {\n return res(null);\n } else {\n errors.strictNumericEscape(startPos, lineStart, curLine);\n }\n }\n\n return res(String.fromCharCode(octal));\n }\n\n return res(String.fromCharCode(ch));\n }\n}\n\ntype HexCharErrorHandlers = IntErrorHandlers & {\n invalidEscapeSequence(pos: number, lineStart: number, curLine: number): void;\n};\n\n// Used to read character escape sequences ('\\x', '\\u').\nfunction readHexChar(\n input: string,\n pos: number,\n lineStart: number,\n curLine: number,\n len: number,\n forceLen: boolean,\n throwOnInvalid: boolean,\n errors: HexCharErrorHandlers,\n) {\n const initialPos = pos;\n let n;\n ({ n, pos } = readInt(\n input,\n pos,\n lineStart,\n curLine,\n 16,\n len,\n forceLen,\n false,\n errors,\n /* bailOnError */ !throwOnInvalid,\n ));\n if (n === null) {\n if (throwOnInvalid) {\n errors.invalidEscapeSequence(initialPos, lineStart, curLine);\n } else {\n pos = initialPos - 1;\n }\n }\n return { code: n, pos };\n}\n\nexport type IntErrorHandlers = {\n numericSeparatorInEscapeSequence(\n pos: number,\n lineStart: number,\n curLine: number,\n ): void;\n unexpectedNumericSeparator(\n pos: number,\n lineStart: number,\n curLine: number,\n ): void;\n // It can return \"true\" to indicate that the error was handled\n // and the int parsing should continue.\n invalidDigit(\n pos: number,\n lineStart: number,\n curLine: number,\n radix: number,\n ): boolean;\n};\n\nexport function readInt(\n input: string,\n pos: number,\n lineStart: number,\n curLine: number,\n radix: number,\n len: number | undefined,\n forceLen: boolean,\n allowNumSeparator: boolean | \"bail\",\n errors: IntErrorHandlers,\n bailOnError: boolean,\n) {\n const start = pos;\n const forbiddenSiblings =\n radix === 16\n ? forbiddenNumericSeparatorSiblings.hex\n : forbiddenNumericSeparatorSiblings.decBinOct;\n const isAllowedSibling =\n radix === 16\n ? isAllowedNumericSeparatorSibling.hex\n : radix === 10\n ? isAllowedNumericSeparatorSibling.dec\n : radix === 8\n ? isAllowedNumericSeparatorSibling.oct\n : isAllowedNumericSeparatorSibling.bin;\n\n let invalid = false;\n let total = 0;\n\n for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) {\n const code = input.charCodeAt(pos);\n let val;\n\n if (code === charCodes.underscore && allowNumSeparator !== \"bail\") {\n const prev = input.charCodeAt(pos - 1);\n const next = input.charCodeAt(pos + 1);\n\n if (!allowNumSeparator) {\n if (bailOnError) return { n: null, pos };\n errors.numericSeparatorInEscapeSequence(pos, lineStart, curLine);\n } else if (\n Number.isNaN(next) ||\n !isAllowedSibling(next) ||\n forbiddenSiblings.has(prev) ||\n forbiddenSiblings.has(next)\n ) {\n if (bailOnError) return { n: null, pos };\n errors.unexpectedNumericSeparator(pos, lineStart, curLine);\n }\n\n // Ignore this _ character\n ++pos;\n continue;\n }\n\n if (code >= charCodes.lowercaseA) {\n val = code - charCodes.lowercaseA + charCodes.lineFeed;\n } else if (code >= charCodes.uppercaseA) {\n val = code - charCodes.uppercaseA + charCodes.lineFeed;\n } else if (charCodes.isDigit(code)) {\n val = code - charCodes.digit0; // 0-9\n } else {\n val = Infinity;\n }\n if (val >= radix) {\n // If we found a digit which is too big, errors.invalidDigit can return true to avoid\n // breaking the loop (this is used for error recovery).\n if (val <= 9 && bailOnError) {\n return { n: null, pos };\n } else if (\n val <= 9 &&\n errors.invalidDigit(pos, lineStart, curLine, radix)\n ) {\n val = 0;\n } else if (forceLen) {\n val = 0;\n invalid = true;\n } else {\n break;\n }\n }\n ++pos;\n total = total * radix + val;\n }\n if (pos === start || (len != null && pos - start !== len) || invalid) {\n return { n: null, pos };\n }\n\n return { n: total, pos };\n}\n\nexport type CodePointErrorHandlers = HexCharErrorHandlers & {\n invalidCodePoint(pos: number, lineStart: number, curLine: number): void;\n};\n\nexport function readCodePoint(\n input: string,\n pos: number,\n lineStart: number,\n curLine: number,\n throwOnInvalid: boolean,\n errors: CodePointErrorHandlers,\n) {\n const ch = input.charCodeAt(pos);\n let code;\n\n if (ch === charCodes.leftCurlyBrace) {\n ++pos;\n ({ code, pos } = readHexChar(\n input,\n pos,\n lineStart,\n curLine,\n input.indexOf(\"}\", pos) - pos,\n true,\n throwOnInvalid,\n errors,\n ));\n ++pos;\n if (code !== null && code > 0x10ffff) {\n if (throwOnInvalid) {\n errors.invalidCodePoint(pos, lineStart, curLine);\n } else {\n return { code: null, pos };\n }\n }\n } else {\n ({ code, pos } = readHexChar(\n input,\n pos,\n lineStart,\n curLine,\n 4,\n false,\n throwOnInvalid,\n errors,\n ));\n }\n return { code, pos };\n}\n","/*:: declare var invariant; */\n\nimport type { Options } from \"../options.ts\";\nimport {\n Position,\n SourceLocation,\n createPositionWithColumnOffset,\n} from \"../util/location.ts\";\nimport CommentsParser, { type CommentWhitespace } from \"../parser/comments.ts\";\nimport type * as N from \"../types.ts\";\nimport * as charCodes from \"charcodes\";\nimport { isIdentifierStart, isIdentifierChar } from \"../util/identifier.ts\";\nimport {\n tokenIsKeyword,\n tokenLabelName,\n tt,\n keywords as keywordTypes,\n type TokenType,\n} from \"./types.ts\";\nimport type { TokContext } from \"./context.ts\";\nimport {\n Errors,\n type ParseError,\n type ParseErrorConstructor,\n} from \"../parse-error.ts\";\nimport {\n lineBreakG,\n isNewLine,\n isWhitespace,\n skipWhiteSpace,\n skipWhiteSpaceInLine,\n} from \"../util/whitespace.ts\";\nimport State from \"./state.ts\";\nimport type { LookaheadState, DeferredStrictError } from \"./state.ts\";\nimport type { Undone } from \"../parser/node.ts\";\nimport type { Node } from \"../types.ts\";\n\nimport {\n readInt,\n readCodePoint,\n readStringContents,\n type IntErrorHandlers,\n type CodePointErrorHandlers,\n type StringContentsErrorHandlers,\n} from \"@babel/helper-string-parser\";\n\nimport type { Plugin } from \"../typings.ts\";\n\nfunction buildPosition(pos: number, lineStart: number, curLine: number) {\n return new Position(curLine, pos - lineStart, pos);\n}\n\nconst VALID_REGEX_FLAGS = new Set([\n charCodes.lowercaseG,\n charCodes.lowercaseM,\n charCodes.lowercaseS,\n charCodes.lowercaseI,\n charCodes.lowercaseY,\n charCodes.lowercaseU,\n charCodes.lowercaseD,\n charCodes.lowercaseV,\n]);\n\n// Object type used to represent tokens. Note that normally, tokens\n// simply exist as properties on the parser object. This is only\n// used for the onToken callback and the external tokenizer.\n\nexport class Token {\n constructor(state: State) {\n this.type = state.type;\n this.value = state.value;\n this.start = state.start;\n this.end = state.end;\n this.loc = new SourceLocation(state.startLoc, state.endLoc);\n }\n\n declare type: TokenType;\n declare value: any;\n declare start: number;\n declare end: number;\n declare loc: SourceLocation;\n}\n\n// ## Tokenizer\n\nexport default abstract class Tokenizer extends CommentsParser {\n isLookahead: boolean;\n\n // Token store.\n tokens: Array = [];\n\n constructor(options: Options, input: string) {\n super();\n this.state = new State();\n this.state.init(options);\n this.input = input;\n this.length = input.length;\n this.comments = [];\n this.isLookahead = false;\n }\n\n pushToken(token: Token | N.Comment) {\n // Pop out invalid tokens trapped by try-catch parsing.\n // Those parsing branches are mainly created by typescript and flow plugins.\n this.tokens.length = this.state.tokensLength;\n this.tokens.push(token);\n ++this.state.tokensLength;\n }\n\n // Move to the next token\n\n next(): void {\n this.checkKeywordEscapes();\n if (this.options.tokens) {\n this.pushToken(new Token(this.state));\n }\n\n this.state.lastTokEndLoc = this.state.endLoc;\n this.state.lastTokStartLoc = this.state.startLoc;\n this.nextToken();\n }\n\n eat(type: TokenType): boolean {\n if (this.match(type)) {\n this.next();\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * Whether current token matches given type\n */\n match(type: TokenType): boolean {\n return this.state.type === type;\n }\n\n /**\n * Create a LookaheadState from current parser state\n */\n createLookaheadState(state: State): LookaheadState {\n return {\n pos: state.pos,\n value: null,\n type: state.type,\n start: state.start,\n end: state.end,\n context: [this.curContext()],\n inType: state.inType,\n startLoc: state.startLoc,\n lastTokEndLoc: state.lastTokEndLoc,\n curLine: state.curLine,\n lineStart: state.lineStart,\n curPosition: state.curPosition,\n };\n }\n\n /**\n * lookahead peeks the next token, skipping changes to token context and\n * comment stack. For performance it returns a limited LookaheadState\n * instead of full parser state.\n *\n * The { column, line } Loc info is not included in lookahead since such usage\n * is rare. Although it may return other location properties e.g. `curLine` and\n * `lineStart`, these properties are not listed in the LookaheadState interface\n * and thus the returned value is _NOT_ reliable.\n *\n * The tokenizer should make best efforts to avoid using any parser state\n * other than those defined in LookaheadState\n */\n lookahead(): LookaheadState {\n const old = this.state;\n // @ts-expect-error For performance we use a simplified tokenizer state structure\n this.state = this.createLookaheadState(old);\n\n this.isLookahead = true;\n this.nextToken();\n this.isLookahead = false;\n\n const curr = this.state;\n this.state = old;\n return curr;\n }\n\n nextTokenStart(): number {\n return this.nextTokenStartSince(this.state.pos);\n }\n\n nextTokenStartSince(pos: number): number {\n skipWhiteSpace.lastIndex = pos;\n return skipWhiteSpace.test(this.input) ? skipWhiteSpace.lastIndex : pos;\n }\n\n lookaheadCharCode(): number {\n return this.input.charCodeAt(this.nextTokenStart());\n }\n\n /**\n * Similar to nextToken, but it will stop at line break when it is seen before the next token\n *\n * @returns {number} position of the next token start or line break, whichever is seen first.\n * @memberof Tokenizer\n */\n nextTokenInLineStart(): number {\n return this.nextTokenInLineStartSince(this.state.pos);\n }\n\n nextTokenInLineStartSince(pos: number): number {\n skipWhiteSpaceInLine.lastIndex = pos;\n return skipWhiteSpaceInLine.test(this.input)\n ? skipWhiteSpaceInLine.lastIndex\n : pos;\n }\n\n /**\n * Similar to lookaheadCharCode, but it will return the char code of line break if it is\n * seen before the next token\n *\n * @returns {number} char code of the next token start or line break, whichever is seen first.\n * @memberof Tokenizer\n */\n lookaheadInLineCharCode(): number {\n return this.input.charCodeAt(this.nextTokenInLineStart());\n }\n\n codePointAtPos(pos: number): number {\n // The implementation is based on\n // https://source.chromium.org/chromium/chromium/src/+/master:v8/src/builtins/builtins-string-gen.cc;l=1455;drc=221e331b49dfefadbc6fa40b0c68e6f97606d0b3;bpv=0;bpt=1\n // We reimplement `codePointAt` because `codePointAt` is a V8 builtin which is not inlined by TurboFan (as of M91)\n // since `input` is mostly ASCII, an inlined `charCodeAt` wins here\n let cp = this.input.charCodeAt(pos);\n if ((cp & 0xfc00) === 0xd800 && ++pos < this.input.length) {\n const trail = this.input.charCodeAt(pos);\n if ((trail & 0xfc00) === 0xdc00) {\n cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff);\n }\n }\n return cp;\n }\n\n // Toggle strict mode. Re-reads the next number or string to please\n // pedantic tests (`\"use strict\"; 010;` should fail).\n\n setStrict(strict: boolean): void {\n this.state.strict = strict;\n if (strict) {\n // Throw an error for any string decimal escape found before/immediately\n // after a \"use strict\" directive. Strict mode will be set at parse\n // time for any literals that occur after the next node of the strict\n // directive.\n this.state.strictErrors.forEach(([toParseError, at]) =>\n this.raise(toParseError, at),\n );\n this.state.strictErrors.clear();\n }\n }\n\n curContext(): TokContext {\n return this.state.context[this.state.context.length - 1];\n }\n\n // Read a single token, updating the parser object's token-related properties.\n nextToken(): void {\n this.skipSpace();\n this.state.start = this.state.pos;\n if (!this.isLookahead) this.state.startLoc = this.state.curPosition();\n if (this.state.pos >= this.length) {\n this.finishToken(tt.eof);\n return;\n }\n\n this.getTokenFromCode(this.codePointAtPos(this.state.pos));\n }\n\n // Skips a block comment, whose end is marked by commentEnd.\n // *-/ is used by the Flow plugin, when parsing block comments nested\n // inside Flow comments.\n skipBlockComment(commentEnd: \"*/\" | \"*-/\"): N.CommentBlock | undefined {\n let startLoc;\n if (!this.isLookahead) startLoc = this.state.curPosition();\n const start = this.state.pos;\n const end = this.input.indexOf(commentEnd, start + 2);\n if (end === -1) {\n // We have to call this again here because startLoc may not be set...\n // This seems to be for performance reasons:\n // https://github.com/babel/babel/commit/acf2a10899f696a8aaf34df78bf9725b5ea7f2da\n throw this.raise(Errors.UnterminatedComment, this.state.curPosition());\n }\n\n this.state.pos = end + commentEnd.length;\n lineBreakG.lastIndex = start + 2;\n while (lineBreakG.test(this.input) && lineBreakG.lastIndex <= end) {\n ++this.state.curLine;\n this.state.lineStart = lineBreakG.lastIndex;\n }\n\n // If we are doing a lookahead right now we need to advance the position (above code)\n // but we do not want to push the comment to the state.\n if (this.isLookahead) return;\n /*:: invariant(startLoc) */\n\n const comment: N.CommentBlock = {\n type: \"CommentBlock\",\n value: this.input.slice(start + 2, end),\n start,\n end: end + commentEnd.length,\n loc: new SourceLocation(startLoc, this.state.curPosition()),\n };\n if (this.options.tokens) this.pushToken(comment);\n return comment;\n }\n\n skipLineComment(startSkip: number): N.CommentLine | undefined {\n const start = this.state.pos;\n let startLoc;\n if (!this.isLookahead) startLoc = this.state.curPosition();\n let ch = this.input.charCodeAt((this.state.pos += startSkip));\n if (this.state.pos < this.length) {\n while (!isNewLine(ch) && ++this.state.pos < this.length) {\n ch = this.input.charCodeAt(this.state.pos);\n }\n }\n\n // If we are doing a lookahead right now we need to advance the position (above code)\n // but we do not want to push the comment to the state.\n if (this.isLookahead) return;\n\n const end = this.state.pos;\n const value = this.input.slice(start + startSkip, end);\n\n const comment: N.CommentLine = {\n type: \"CommentLine\",\n value,\n start,\n end,\n loc: new SourceLocation(startLoc, this.state.curPosition()),\n };\n if (this.options.tokens) this.pushToken(comment);\n return comment;\n }\n\n // Called at the start of the parse and after every token. Skips\n // whitespace and comments, and.\n\n skipSpace(): void {\n const spaceStart = this.state.pos;\n const comments = [];\n loop: while (this.state.pos < this.length) {\n const ch = this.input.charCodeAt(this.state.pos);\n switch (ch) {\n case charCodes.space:\n case charCodes.nonBreakingSpace:\n case charCodes.tab:\n ++this.state.pos;\n break;\n case charCodes.carriageReturn:\n if (\n this.input.charCodeAt(this.state.pos + 1) === charCodes.lineFeed\n ) {\n ++this.state.pos;\n }\n // fall through\n case charCodes.lineFeed:\n case charCodes.lineSeparator:\n case charCodes.paragraphSeparator:\n ++this.state.pos;\n ++this.state.curLine;\n this.state.lineStart = this.state.pos;\n break;\n\n case charCodes.slash:\n switch (this.input.charCodeAt(this.state.pos + 1)) {\n case charCodes.asterisk: {\n const comment = this.skipBlockComment(\"*/\");\n if (comment !== undefined) {\n this.addComment(comment);\n if (this.options.attachComment) comments.push(comment);\n }\n break;\n }\n\n case charCodes.slash: {\n const comment = this.skipLineComment(2);\n if (comment !== undefined) {\n this.addComment(comment);\n if (this.options.attachComment) comments.push(comment);\n }\n break;\n }\n\n default:\n break loop;\n }\n break;\n\n default:\n if (isWhitespace(ch)) {\n ++this.state.pos;\n } else if (\n ch === charCodes.dash &&\n !this.inModule &&\n this.options.annexB\n ) {\n const pos = this.state.pos;\n if (\n this.input.charCodeAt(pos + 1) === charCodes.dash &&\n this.input.charCodeAt(pos + 2) === charCodes.greaterThan &&\n (spaceStart === 0 || this.state.lineStart > spaceStart)\n ) {\n // A `-->` line comment\n const comment = this.skipLineComment(3);\n if (comment !== undefined) {\n this.addComment(comment);\n if (this.options.attachComment) comments.push(comment);\n }\n } else {\n break loop;\n }\n } else if (\n ch === charCodes.lessThan &&\n !this.inModule &&\n this.options.annexB\n ) {\n const pos = this.state.pos;\n if (\n this.input.charCodeAt(pos + 1) === charCodes.exclamationMark &&\n this.input.charCodeAt(pos + 2) === charCodes.dash &&\n this.input.charCodeAt(pos + 3) === charCodes.dash\n ) {\n // ` true + * console.error(err.code); // --> 'ERR_INVALID_HTTP_TOKEN' + * console.error(err.message); // --> 'Header name must be a valid HTTP token [""]' + * } + * ``` + * @since v14.3.0 + * @param [label='Header name'] Label for error message. + */ + function validateHeaderName(name: string): void; + /** + * Performs the low-level validations on the provided `value` that are done when `res.setHeader(name, value)` is called. + * + * Passing illegal value as `value` will result in a `TypeError` being thrown. + * + * * Undefined value error is identified by `code: 'ERR_HTTP_INVALID_HEADER_VALUE'`. + * * Invalid value character error is identified by `code: 'ERR_INVALID_CHAR'`. + * + * It is not necessary to use this method before passing headers to an HTTP request + * or response. The HTTP module will automatically validate such headers. + * + * Examples: + * + * ```js + * import { validateHeaderValue } from 'node:http'; + * + * try { + * validateHeaderValue('x-my-header', undefined); + * } catch (err) { + * console.error(err instanceof TypeError); // --> true + * console.error(err.code === 'ERR_HTTP_INVALID_HEADER_VALUE'); // --> true + * console.error(err.message); // --> 'Invalid value "undefined" for header "x-my-header"' + * } + * + * try { + * validateHeaderValue('x-my-header', 'oʊmɪɡə'); + * } catch (err) { + * console.error(err instanceof TypeError); // --> true + * console.error(err.code === 'ERR_INVALID_CHAR'); // --> true + * console.error(err.message); // --> 'Invalid character in header content ["x-my-header"]' + * } + * ``` + * @since v14.3.0 + * @param name Header name + * @param value Header value + */ + function validateHeaderValue(name: string, value: string): void; + /** + * Set the maximum number of idle HTTP parsers. + * @since v18.8.0, v16.18.0 + * @param [max=1000] + */ + function setMaxIdleHTTPParsers(max: number): void; + /** + * Global instance of `Agent` which is used as the default for all HTTP client + * requests. Diverges from a default `Agent` configuration by having `keepAlive` + * enabled and a `timeout` of 5 seconds. + * @since v0.5.9 + */ + let globalAgent: Agent; + /** + * Read-only property specifying the maximum allowed size of HTTP headers in bytes. + * Defaults to 16KB. Configurable using the `--max-http-header-size` CLI option. + */ + const maxHeaderSize: number; + /** + * A browser-compatible implementation of [WebSocket](https://nodejs.org/docs/latest/api/http.html#websocket). + * @since v22.5.0 + */ + const WebSocket: import("undici-types").WebSocket; + /** + * @since v22.5.0 + */ + const CloseEvent: import("undici-types").CloseEvent; + /** + * @since v22.5.0 + */ + const MessageEvent: import("undici-types").MessageEvent; +} +declare module "node:http" { + export * from "http"; +} diff --git a/libcore/node_modules/@types/node/http2.d.ts b/libcore/node_modules/@types/node/http2.d.ts new file mode 100644 index 0000000..3e98e0d --- /dev/null +++ b/libcore/node_modules/@types/node/http2.d.ts @@ -0,0 +1,2418 @@ +/** + * The `node:http2` module provides an implementation of the [HTTP/2](https://tools.ietf.org/html/rfc7540) protocol. + * It can be accessed using: + * + * ```js + * const http2 = require('node:http2'); + * ``` + * @since v8.4.0 + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/http2.js) + */ +declare module "http2" { + import EventEmitter = require("node:events"); + import * as fs from "node:fs"; + import * as net from "node:net"; + import * as stream from "node:stream"; + import * as tls from "node:tls"; + import * as url from "node:url"; + import { + IncomingHttpHeaders as Http1IncomingHttpHeaders, + IncomingMessage, + OutgoingHttpHeaders, + ServerResponse, + } from "node:http"; + export { OutgoingHttpHeaders } from "node:http"; + export interface IncomingHttpStatusHeader { + ":status"?: number | undefined; + } + export interface IncomingHttpHeaders extends Http1IncomingHttpHeaders { + ":path"?: string | undefined; + ":method"?: string | undefined; + ":authority"?: string | undefined; + ":scheme"?: string | undefined; + } + // Http2Stream + export interface StreamPriorityOptions { + exclusive?: boolean | undefined; + parent?: number | undefined; + weight?: number | undefined; + silent?: boolean | undefined; + } + export interface StreamState { + localWindowSize?: number | undefined; + state?: number | undefined; + localClose?: number | undefined; + remoteClose?: number | undefined; + sumDependencyWeight?: number | undefined; + weight?: number | undefined; + } + export interface ServerStreamResponseOptions { + endStream?: boolean | undefined; + waitForTrailers?: boolean | undefined; + } + export interface StatOptions { + offset: number; + length: number; + } + export interface ServerStreamFileResponseOptions { + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + statCheck?(stats: fs.Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions): void | boolean; + waitForTrailers?: boolean | undefined; + offset?: number | undefined; + length?: number | undefined; + } + export interface ServerStreamFileResponseOptionsWithError extends ServerStreamFileResponseOptions { + onError?(err: NodeJS.ErrnoException): void; + } + export interface Http2Stream extends stream.Duplex { + /** + * Set to `true` if the `Http2Stream` instance was aborted abnormally. When set, + * the `'aborted'` event will have been emitted. + * @since v8.4.0 + */ + readonly aborted: boolean; + /** + * This property shows the number of characters currently buffered to be written. + * See `net.Socket.bufferSize` for details. + * @since v11.2.0, v10.16.0 + */ + readonly bufferSize: number; + /** + * Set to `true` if the `Http2Stream` instance has been closed. + * @since v9.4.0 + */ + readonly closed: boolean; + /** + * Set to `true` if the `Http2Stream` instance has been destroyed and is no longer + * usable. + * @since v8.4.0 + */ + readonly destroyed: boolean; + /** + * Set to `true` if the `END_STREAM` flag was set in the request or response + * HEADERS frame received, indicating that no additional data should be received + * and the readable side of the `Http2Stream` will be closed. + * @since v10.11.0 + */ + readonly endAfterHeaders: boolean; + /** + * The numeric stream identifier of this `Http2Stream` instance. Set to `undefined` if the stream identifier has not yet been assigned. + * @since v8.4.0 + */ + readonly id?: number | undefined; + /** + * Set to `true` if the `Http2Stream` instance has not yet been assigned a + * numeric stream identifier. + * @since v9.4.0 + */ + readonly pending: boolean; + /** + * Set to the `RST_STREAM` `error code` reported when the `Http2Stream` is + * destroyed after either receiving an `RST_STREAM` frame from the connected peer, + * calling `http2stream.close()`, or `http2stream.destroy()`. Will be `undefined` if the `Http2Stream` has not been closed. + * @since v8.4.0 + */ + readonly rstCode: number; + /** + * An object containing the outbound headers sent for this `Http2Stream`. + * @since v9.5.0 + */ + readonly sentHeaders: OutgoingHttpHeaders; + /** + * An array of objects containing the outbound informational (additional) headers + * sent for this `Http2Stream`. + * @since v9.5.0 + */ + readonly sentInfoHeaders?: OutgoingHttpHeaders[] | undefined; + /** + * An object containing the outbound trailers sent for this `HttpStream`. + * @since v9.5.0 + */ + readonly sentTrailers?: OutgoingHttpHeaders | undefined; + /** + * A reference to the `Http2Session` instance that owns this `Http2Stream`. The + * value will be `undefined` after the `Http2Stream` instance is destroyed. + * @since v8.4.0 + */ + readonly session: Http2Session | undefined; + /** + * Provides miscellaneous information about the current state of the `Http2Stream`. + * + * A current state of this `Http2Stream`. + * @since v8.4.0 + */ + readonly state: StreamState; + /** + * Closes the `Http2Stream` instance by sending an `RST_STREAM` frame to the + * connected HTTP/2 peer. + * @since v8.4.0 + * @param [code=http2.constants.NGHTTP2_NO_ERROR] Unsigned 32-bit integer identifying the error code. + * @param callback An optional function registered to listen for the `'close'` event. + */ + close(code?: number, callback?: () => void): void; + /** + * Updates the priority for this `Http2Stream` instance. + * @since v8.4.0 + */ + priority(options: StreamPriorityOptions): void; + /** + * ```js + * const http2 = require('node:http2'); + * const client = http2.connect('http://example.org:8000'); + * const { NGHTTP2_CANCEL } = http2.constants; + * const req = client.request({ ':path': '/' }); + * + * // Cancel the stream if there's no activity after 5 seconds + * req.setTimeout(5000, () => req.close(NGHTTP2_CANCEL)); + * ``` + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * Sends a trailing `HEADERS` frame to the connected HTTP/2 peer. This method + * will cause the `Http2Stream` to be immediately closed and must only be + * called after the `'wantTrailers'` event has been emitted. When sending a + * request or sending a response, the `options.waitForTrailers` option must be set + * in order to keep the `Http2Stream` open after the final `DATA` frame so that + * trailers can be sent. + * + * ```js + * const http2 = require('node:http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond(undefined, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ xyz: 'abc' }); + * }); + * stream.end('Hello World'); + * }); + * ``` + * + * The HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header + * fields (e.g. `':method'`, `':path'`, etc). + * @since v10.0.0 + */ + sendTrailers(headers: OutgoingHttpHeaders): void; + addListener(event: "aborted", listener: () => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: "streamClosed", listener: (code: number) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: "wantTrailers", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "aborted"): boolean; + emit(event: "close"): boolean; + emit(event: "data", chunk: Buffer | string): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "frameError", frameType: number, errorCode: number): boolean; + emit(event: "pipe", src: stream.Readable): boolean; + emit(event: "unpipe", src: stream.Readable): boolean; + emit(event: "streamClosed", code: number): boolean; + emit(event: "timeout"): boolean; + emit(event: "trailers", trailers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "wantTrailers"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "aborted", listener: () => void): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: "streamClosed", listener: (code: number) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + on(event: "wantTrailers", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "aborted", listener: () => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: "streamClosed", listener: (code: number) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + once(event: "wantTrailers", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "aborted", listener: () => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "streamClosed", listener: (code: number) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: "wantTrailers", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "aborted", listener: () => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "streamClosed", listener: (code: number) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: "wantTrailers", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ClientHttp2Stream extends Http2Stream { + addListener(event: "continue", listener: () => {}): this; + addListener( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + addListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + addListener( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "continue"): boolean; + emit(event: "headers", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: "push", headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "response", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "continue", listener: () => {}): this; + on( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + on(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + on( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "continue", listener: () => {}): this; + once( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + once(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + once( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "continue", listener: () => {}): this; + prependListener( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + prependListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "continue", listener: () => {}): this; + prependOnceListener( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + prependOnceListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ServerHttp2Stream extends Http2Stream { + /** + * True if headers were sent, false otherwise (read-only). + * @since v8.4.0 + */ + readonly headersSent: boolean; + /** + * Read-only property mapped to the `SETTINGS_ENABLE_PUSH` flag of the remote + * client's most recent `SETTINGS` frame. Will be `true` if the remote peer + * accepts push streams, `false` otherwise. Settings are the same for every `Http2Stream` in the same `Http2Session`. + * @since v8.4.0 + */ + readonly pushAllowed: boolean; + /** + * Sends an additional informational `HEADERS` frame to the connected HTTP/2 peer. + * @since v8.4.0 + */ + additionalHeaders(headers: OutgoingHttpHeaders): void; + /** + * Initiates a push stream. The callback is invoked with the new `Http2Stream` instance created for the push stream passed as the second argument, or an `Error` passed as the first argument. + * + * ```js + * const http2 = require('node:http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }); + * stream.pushStream({ ':path': '/' }, (err, pushStream, headers) => { + * if (err) throw err; + * pushStream.respond({ ':status': 200 }); + * pushStream.end('some pushed data'); + * }); + * stream.end('some data'); + * }); + * ``` + * + * Setting the weight of a push stream is not allowed in the `HEADERS` frame. Pass + * a `weight` value to `http2stream.priority` with the `silent` option set to `true` to enable server-side bandwidth balancing between concurrent streams. + * + * Calling `http2stream.pushStream()` from within a pushed stream is not permitted + * and will throw an error. + * @since v8.4.0 + * @param callback Callback that is called once the push stream has been initiated. + */ + pushStream( + headers: OutgoingHttpHeaders, + callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void, + ): void; + pushStream( + headers: OutgoingHttpHeaders, + options?: StreamPriorityOptions, + callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void, + ): void; + /** + * ```js + * const http2 = require('node:http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }); + * stream.end('some data'); + * }); + * ``` + * + * Initiates a response. When the `options.waitForTrailers` option is set, the`'wantTrailers'` event will be emitted immediately after queuing the last chunk + * of payload data to be sent. The `http2stream.sendTrailers()` method can then be + * used to sent trailing header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either `http2stream.sendTrailers()` or `http2stream.close()` to close the `Http2Stream`. + * + * ```js + * const http2 = require('node:http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * stream.end('some data'); + * }); + * ``` + * @since v8.4.0 + */ + respond(headers?: OutgoingHttpHeaders, options?: ServerStreamResponseOptions): void; + /** + * Initiates a response whose data is read from the given file descriptor. No + * validation is performed on the given file descriptor. If an error occurs while + * attempting to read data using the file descriptor, the `Http2Stream` will be + * closed using an `RST_STREAM` frame using the standard `INTERNAL_ERROR` code. + * + * When used, the `Http2Stream` object's `Duplex` interface will be closed + * automatically. + * + * ```js + * const http2 = require('node:http2'); + * const fs = require('node:fs'); + * + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * const fd = fs.openSync('/some/file', 'r'); + * + * const stat = fs.fstatSync(fd); + * const headers = { + * 'content-length': stat.size, + * 'last-modified': stat.mtime.toUTCString(), + * 'content-type': 'text/plain; charset=utf-8', + * }; + * stream.respondWithFD(fd, headers); + * stream.on('close', () => fs.closeSync(fd)); + * }); + * ``` + * + * The optional `options.statCheck` function may be specified to give user code + * an opportunity to set additional content headers based on the `fs.Stat` details + * of the given fd. If the `statCheck` function is provided, the `http2stream.respondWithFD()` method will perform an `fs.fstat()` call to + * collect details on the provided file descriptor. + * + * The `offset` and `length` options may be used to limit the response to a + * specific range subset. This can be used, for instance, to support HTTP Range + * requests. + * + * The file descriptor or `FileHandle` is not closed when the stream is closed, + * so it will need to be closed manually once it is no longer needed. + * Using the same file descriptor concurrently for multiple streams + * is not supported and may result in data loss. Re-using a file descriptor + * after a stream has finished is supported. + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be + * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code _must_ call either `http2stream.sendTrailers()` or `http2stream.close()` to close the `Http2Stream`. + * + * ```js + * const http2 = require('node:http2'); + * const fs = require('node:fs'); + * + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * const fd = fs.openSync('/some/file', 'r'); + * + * const stat = fs.fstatSync(fd); + * const headers = { + * 'content-length': stat.size, + * 'last-modified': stat.mtime.toUTCString(), + * 'content-type': 'text/plain; charset=utf-8', + * }; + * stream.respondWithFD(fd, headers, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * + * stream.on('close', () => fs.closeSync(fd)); + * }); + * ``` + * @since v8.4.0 + * @param fd A readable file descriptor. + */ + respondWithFD( + fd: number | fs.promises.FileHandle, + headers?: OutgoingHttpHeaders, + options?: ServerStreamFileResponseOptions, + ): void; + /** + * Sends a regular file as the response. The `path` must specify a regular file + * or an `'error'` event will be emitted on the `Http2Stream` object. + * + * When used, the `Http2Stream` object's `Duplex` interface will be closed + * automatically. + * + * The optional `options.statCheck` function may be specified to give user code + * an opportunity to set additional content headers based on the `fs.Stat` details + * of the given file: + * + * If an error occurs while attempting to read the file data, the `Http2Stream` will be closed using an `RST_STREAM` frame using the standard `INTERNAL_ERROR` code. If the `onError` callback is + * defined, then it will be called. Otherwise + * the stream will be destroyed. + * + * Example using a file path: + * + * ```js + * const http2 = require('node:http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * function statCheck(stat, headers) { + * headers['last-modified'] = stat.mtime.toUTCString(); + * } + * + * function onError(err) { + * // stream.respond() can throw if the stream has been destroyed by + * // the other side. + * try { + * if (err.code === 'ENOENT') { + * stream.respond({ ':status': 404 }); + * } else { + * stream.respond({ ':status': 500 }); + * } + * } catch (err) { + * // Perform actual error handling. + * console.error(err); + * } + * stream.end(); + * } + * + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { statCheck, onError }); + * }); + * ``` + * + * The `options.statCheck` function may also be used to cancel the send operation + * by returning `false`. For instance, a conditional request may check the stat + * results to determine if the file has been modified to return an appropriate `304` response: + * + * ```js + * const http2 = require('node:http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * function statCheck(stat, headers) { + * // Check the stat here... + * stream.respond({ ':status': 304 }); + * return false; // Cancel the send operation + * } + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { statCheck }); + * }); + * ``` + * + * The `content-length` header field will be automatically set. + * + * The `offset` and `length` options may be used to limit the response to a + * specific range subset. This can be used, for instance, to support HTTP Range + * requests. + * + * The `options.onError` function may also be used to handle all the errors + * that could happen before the delivery of the file is initiated. The + * default behavior is to destroy the stream. + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be + * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * ```js + * const http2 = require('node:http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * }); + * ``` + * @since v8.4.0 + */ + respondWithFile( + path: string, + headers?: OutgoingHttpHeaders, + options?: ServerStreamFileResponseOptionsWithError, + ): void; + } + // Http2Session + export interface Settings { + headerTableSize?: number | undefined; + enablePush?: boolean | undefined; + initialWindowSize?: number | undefined; + maxFrameSize?: number | undefined; + maxConcurrentStreams?: number | undefined; + maxHeaderListSize?: number | undefined; + enableConnectProtocol?: boolean | undefined; + } + export interface ClientSessionRequestOptions { + endStream?: boolean | undefined; + exclusive?: boolean | undefined; + parent?: number | undefined; + weight?: number | undefined; + waitForTrailers?: boolean | undefined; + signal?: AbortSignal | undefined; + } + export interface SessionState { + effectiveLocalWindowSize?: number | undefined; + effectiveRecvDataLength?: number | undefined; + nextStreamID?: number | undefined; + localWindowSize?: number | undefined; + lastProcStreamID?: number | undefined; + remoteWindowSize?: number | undefined; + outboundQueueSize?: number | undefined; + deflateDynamicTableSize?: number | undefined; + inflateDynamicTableSize?: number | undefined; + } + export interface Http2Session extends EventEmitter { + /** + * Value will be `undefined` if the `Http2Session` is not yet connected to a + * socket, `h2c` if the `Http2Session` is not connected to a `TLSSocket`, or + * will return the value of the connected `TLSSocket`'s own `alpnProtocol` property. + * @since v9.4.0 + */ + readonly alpnProtocol?: string | undefined; + /** + * Will be `true` if this `Http2Session` instance has been closed, otherwise `false`. + * @since v9.4.0 + */ + readonly closed: boolean; + /** + * Will be `true` if this `Http2Session` instance is still connecting, will be set + * to `false` before emitting `connect` event and/or calling the `http2.connect` callback. + * @since v10.0.0 + */ + readonly connecting: boolean; + /** + * Will be `true` if this `Http2Session` instance has been destroyed and must no + * longer be used, otherwise `false`. + * @since v8.4.0 + */ + readonly destroyed: boolean; + /** + * Value is `undefined` if the `Http2Session` session socket has not yet been + * connected, `true` if the `Http2Session` is connected with a `TLSSocket`, + * and `false` if the `Http2Session` is connected to any other kind of socket + * or stream. + * @since v9.4.0 + */ + readonly encrypted?: boolean | undefined; + /** + * A prototype-less object describing the current local settings of this `Http2Session`. The local settings are local to _this_`Http2Session` instance. + * @since v8.4.0 + */ + readonly localSettings: Settings; + /** + * If the `Http2Session` is connected to a `TLSSocket`, the `originSet` property + * will return an `Array` of origins for which the `Http2Session` may be + * considered authoritative. + * + * The `originSet` property is only available when using a secure TLS connection. + * @since v9.4.0 + */ + readonly originSet?: string[] | undefined; + /** + * Indicates whether the `Http2Session` is currently waiting for acknowledgment of + * a sent `SETTINGS` frame. Will be `true` after calling the `http2session.settings()` method. Will be `false` once all sent `SETTINGS` frames have been acknowledged. + * @since v8.4.0 + */ + readonly pendingSettingsAck: boolean; + /** + * A prototype-less object describing the current remote settings of this`Http2Session`. The remote settings are set by the _connected_ HTTP/2 peer. + * @since v8.4.0 + */ + readonly remoteSettings: Settings; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * limits available methods to ones safe to use with HTTP/2. + * + * `destroy`, `emit`, `end`, `pause`, `read`, `resume`, and `write` will throw + * an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for more information. + * + * `setTimeout` method will be called on this `Http2Session`. + * + * All other interactions will be routed directly to the socket. + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * Provides miscellaneous information about the current state of the`Http2Session`. + * + * An object describing the current status of this `Http2Session`. + * @since v8.4.0 + */ + readonly state: SessionState; + /** + * The `http2session.type` will be equal to `http2.constants.NGHTTP2_SESSION_SERVER` if this `Http2Session` instance is a + * server, and `http2.constants.NGHTTP2_SESSION_CLIENT` if the instance is a + * client. + * @since v8.4.0 + */ + readonly type: number; + /** + * Gracefully closes the `Http2Session`, allowing any existing streams to + * complete on their own and preventing new `Http2Stream` instances from being + * created. Once closed, `http2session.destroy()`_might_ be called if there + * are no open `Http2Stream` instances. + * + * If specified, the `callback` function is registered as a handler for the`'close'` event. + * @since v9.4.0 + */ + close(callback?: () => void): void; + /** + * Immediately terminates the `Http2Session` and the associated `net.Socket` or `tls.TLSSocket`. + * + * Once destroyed, the `Http2Session` will emit the `'close'` event. If `error` is not undefined, an `'error'` event will be emitted immediately before the `'close'` event. + * + * If there are any remaining open `Http2Streams` associated with the `Http2Session`, those will also be destroyed. + * @since v8.4.0 + * @param error An `Error` object if the `Http2Session` is being destroyed due to an error. + * @param code The HTTP/2 error code to send in the final `GOAWAY` frame. If unspecified, and `error` is not undefined, the default is `INTERNAL_ERROR`, otherwise defaults to `NO_ERROR`. + */ + destroy(error?: Error, code?: number): void; + /** + * Transmits a `GOAWAY` frame to the connected peer _without_ shutting down the`Http2Session`. + * @since v9.4.0 + * @param code An HTTP/2 error code + * @param lastStreamID The numeric ID of the last processed `Http2Stream` + * @param opaqueData A `TypedArray` or `DataView` instance containing additional data to be carried within the `GOAWAY` frame. + */ + goaway(code?: number, lastStreamID?: number, opaqueData?: NodeJS.ArrayBufferView): void; + /** + * Sends a `PING` frame to the connected HTTP/2 peer. A `callback` function must + * be provided. The method will return `true` if the `PING` was sent, `false` otherwise. + * + * The maximum number of outstanding (unacknowledged) pings is determined by the `maxOutstandingPings` configuration option. The default maximum is 10. + * + * If provided, the `payload` must be a `Buffer`, `TypedArray`, or `DataView` containing 8 bytes of data that will be transmitted with the `PING` and + * returned with the ping acknowledgment. + * + * The callback will be invoked with three arguments: an error argument that will + * be `null` if the `PING` was successfully acknowledged, a `duration` argument + * that reports the number of milliseconds elapsed since the ping was sent and the + * acknowledgment was received, and a `Buffer` containing the 8-byte `PING` payload. + * + * ```js + * session.ping(Buffer.from('abcdefgh'), (err, duration, payload) => { + * if (!err) { + * console.log(`Ping acknowledged in ${duration} milliseconds`); + * console.log(`With payload '${payload.toString()}'`); + * } + * }); + * ``` + * + * If the `payload` argument is not specified, the default payload will be the + * 64-bit timestamp (little endian) marking the start of the `PING` duration. + * @since v8.9.3 + * @param payload Optional ping payload. + */ + ping(callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean; + ping( + payload: NodeJS.ArrayBufferView, + callback: (err: Error | null, duration: number, payload: Buffer) => void, + ): boolean; + /** + * Calls `ref()` on this `Http2Session` instance's underlying `net.Socket`. + * @since v9.4.0 + */ + ref(): void; + /** + * Sets the local endpoint's window size. + * The `windowSize` is the total window size to set, not + * the delta. + * + * ```js + * const http2 = require('node:http2'); + * + * const server = http2.createServer(); + * const expectedWindowSize = 2 ** 20; + * server.on('connect', (session) => { + * + * // Set local window size to be 2 ** 20 + * session.setLocalWindowSize(expectedWindowSize); + * }); + * ``` + * @since v15.3.0, v14.18.0 + */ + setLocalWindowSize(windowSize: number): void; + /** + * Used to set a callback function that is called when there is no activity on + * the `Http2Session` after `msecs` milliseconds. The given `callback` is + * registered as a listener on the `'timeout'` event. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * Updates the current local settings for this `Http2Session` and sends a new `SETTINGS` frame to the connected HTTP/2 peer. + * + * Once called, the `http2session.pendingSettingsAck` property will be `true` while the session is waiting for the remote peer to acknowledge the new + * settings. + * + * The new settings will not become effective until the `SETTINGS` acknowledgment + * is received and the `'localSettings'` event is emitted. It is possible to send + * multiple `SETTINGS` frames while acknowledgment is still pending. + * @since v8.4.0 + * @param callback Callback that is called once the session is connected or right away if the session is already connected. + */ + settings( + settings: Settings, + callback?: (err: Error | null, settings: Settings, duration: number) => void, + ): void; + /** + * Calls `unref()` on this `Http2Session`instance's underlying `net.Socket`. + * @since v9.4.0 + */ + unref(): void; + addListener(event: "close", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener( + event: "frameError", + listener: (frameType: number, errorCode: number, streamID: number) => void, + ): this; + addListener( + event: "goaway", + listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void, + ): this; + addListener(event: "localSettings", listener: (settings: Settings) => void): this; + addListener(event: "ping", listener: () => void): this; + addListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "frameError", frameType: number, errorCode: number, streamID: number): boolean; + emit(event: "goaway", errorCode: number, lastStreamID: number, opaqueData?: Buffer): boolean; + emit(event: "localSettings", settings: Settings): boolean; + emit(event: "ping"): boolean; + emit(event: "remoteSettings", settings: Settings): boolean; + emit(event: "timeout"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + on(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void): this; + on(event: "localSettings", listener: (settings: Settings) => void): this; + on(event: "ping", listener: () => void): this; + on(event: "remoteSettings", listener: (settings: Settings) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + once(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void): this; + once(event: "localSettings", listener: (settings: Settings) => void): this; + once(event: "ping", listener: () => void): this; + once(event: "remoteSettings", listener: (settings: Settings) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener( + event: "frameError", + listener: (frameType: number, errorCode: number, streamID: number) => void, + ): this; + prependListener( + event: "goaway", + listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void, + ): this; + prependListener(event: "localSettings", listener: (settings: Settings) => void): this; + prependListener(event: "ping", listener: () => void): this; + prependListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener( + event: "frameError", + listener: (frameType: number, errorCode: number, streamID: number) => void, + ): this; + prependOnceListener( + event: "goaway", + listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void, + ): this; + prependOnceListener(event: "localSettings", listener: (settings: Settings) => void): this; + prependOnceListener(event: "ping", listener: () => void): this; + prependOnceListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ClientHttp2Session extends Http2Session { + /** + * For HTTP/2 Client `Http2Session` instances only, the `http2session.request()` creates and returns an `Http2Stream` instance that can be used to send an + * HTTP/2 request to the connected server. + * + * When a `ClientHttp2Session` is first created, the socket may not yet be + * connected. if `clienthttp2session.request()` is called during this time, the + * actual request will be deferred until the socket is ready to go. + * If the `session` is closed before the actual request be executed, an `ERR_HTTP2_GOAWAY_SESSION` is thrown. + * + * This method is only available if `http2session.type` is equal to `http2.constants.NGHTTP2_SESSION_CLIENT`. + * + * ```js + * const http2 = require('node:http2'); + * const clientSession = http2.connect('https://localhost:1234'); + * const { + * HTTP2_HEADER_PATH, + * HTTP2_HEADER_STATUS, + * } = http2.constants; + * + * const req = clientSession.request({ [HTTP2_HEADER_PATH]: '/' }); + * req.on('response', (headers) => { + * console.log(headers[HTTP2_HEADER_STATUS]); + * req.on('data', (chunk) => { // .. }); + * req.on('end', () => { // .. }); + * }); + * ``` + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * is emitted immediately after queuing the last chunk of payload data to be sent. + * The `http2stream.sendTrailers()` method can then be called to send trailing + * headers to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * When `options.signal` is set with an `AbortSignal` and then `abort` on the + * corresponding `AbortController` is called, the request will emit an `'error'`event with an `AbortError` error. + * + * The `:method` and `:path` pseudo-headers are not specified within `headers`, + * they respectively default to: + * + * * `:method` \= `'GET'` + * * `:path` \= `/` + * @since v8.4.0 + */ + request(headers?: OutgoingHttpHeaders, options?: ClientSessionRequestOptions): ClientHttp2Stream; + addListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + addListener(event: "origin", listener: (origins: string[]) => void): this; + addListener( + event: "connect", + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + addListener( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "altsvc", alt: string, origin: string, stream: number): boolean; + emit(event: "origin", origins: readonly string[]): boolean; + emit(event: "connect", session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; + emit( + event: "stream", + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + on(event: "origin", listener: (origins: string[]) => void): this; + on(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + on( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + once(event: "origin", listener: (origins: string[]) => void): this; + once( + event: "connect", + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + once( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + prependListener(event: "origin", listener: (origins: string[]) => void): this; + prependListener( + event: "connect", + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + prependListener( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + prependOnceListener(event: "origin", listener: (origins: string[]) => void): this; + prependOnceListener( + event: "connect", + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + prependOnceListener( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface AlternativeServiceOptions { + origin: number | string | url.URL; + } + export interface ServerHttp2Session extends Http2Session { + readonly server: Http2Server | Http2SecureServer; + /** + * Submits an `ALTSVC` frame (as defined by [RFC 7838](https://tools.ietf.org/html/rfc7838)) to the connected client. + * + * ```js + * const http2 = require('node:http2'); + * + * const server = http2.createServer(); + * server.on('session', (session) => { + * // Set altsvc for origin https://example.org:80 + * session.altsvc('h2=":8000"', 'https://example.org:80'); + * }); + * + * server.on('stream', (stream) => { + * // Set altsvc for a specific stream + * stream.session.altsvc('h2=":8000"', stream.id); + * }); + * ``` + * + * Sending an `ALTSVC` frame with a specific stream ID indicates that the alternate + * service is associated with the origin of the given `Http2Stream`. + * + * The `alt` and origin string _must_ contain only ASCII bytes and are + * strictly interpreted as a sequence of ASCII bytes. The special value `'clear'`may be passed to clear any previously set alternative service for a given + * domain. + * + * When a string is passed for the `originOrStream` argument, it will be parsed as + * a URL and the origin will be derived. For instance, the origin for the + * HTTP URL `'https://example.org/foo/bar'` is the ASCII string`'https://example.org'`. An error will be thrown if either the given string + * cannot be parsed as a URL or if a valid origin cannot be derived. + * + * A `URL` object, or any object with an `origin` property, may be passed as`originOrStream`, in which case the value of the `origin` property will be + * used. The value of the `origin` property _must_ be a properly serialized + * ASCII origin. + * @since v9.4.0 + * @param alt A description of the alternative service configuration as defined by `RFC 7838`. + * @param originOrStream Either a URL string specifying the origin (or an `Object` with an `origin` property) or the numeric identifier of an active `Http2Stream` as given by the + * `http2stream.id` property. + */ + altsvc(alt: string, originOrStream: number | string | url.URL | AlternativeServiceOptions): void; + /** + * Submits an `ORIGIN` frame (as defined by [RFC 8336](https://tools.ietf.org/html/rfc8336)) to the connected client + * to advertise the set of origins for which the server is capable of providing + * authoritative responses. + * + * ```js + * const http2 = require('node:http2'); + * const options = getSecureOptionsSomehow(); + * const server = http2.createSecureServer(options); + * server.on('stream', (stream) => { + * stream.respond(); + * stream.end('ok'); + * }); + * server.on('session', (session) => { + * session.origin('https://example.com', 'https://example.org'); + * }); + * ``` + * + * When a string is passed as an `origin`, it will be parsed as a URL and the + * origin will be derived. For instance, the origin for the HTTP URL `'https://example.org/foo/bar'` is the ASCII string` 'https://example.org'`. An error will be thrown if either the given + * string + * cannot be parsed as a URL or if a valid origin cannot be derived. + * + * A `URL` object, or any object with an `origin` property, may be passed as + * an `origin`, in which case the value of the `origin` property will be + * used. The value of the `origin` property _must_ be a properly serialized + * ASCII origin. + * + * Alternatively, the `origins` option may be used when creating a new HTTP/2 + * server using the `http2.createSecureServer()` method: + * + * ```js + * const http2 = require('node:http2'); + * const options = getSecureOptionsSomehow(); + * options.origins = ['https://example.com', 'https://example.org']; + * const server = http2.createSecureServer(options); + * server.on('stream', (stream) => { + * stream.respond(); + * stream.end('ok'); + * }); + * ``` + * @since v10.12.0 + * @param origins One or more URL Strings passed as separate arguments. + */ + origin( + ...origins: Array< + | string + | url.URL + | { + origin: string; + } + > + ): void; + addListener( + event: "connect", + listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + addListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "connect", session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + on( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once( + event: "connect", + listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + once( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + event: "connect", + listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + prependListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + event: "connect", + listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + prependOnceListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + // Http2Server + export interface SessionOptions { + maxDeflateDynamicTableSize?: number | undefined; + maxSessionMemory?: number | undefined; + maxHeaderListPairs?: number | undefined; + maxOutstandingPings?: number | undefined; + maxSendHeaderBlockLength?: number | undefined; + paddingStrategy?: number | undefined; + peerMaxConcurrentStreams?: number | undefined; + settings?: Settings | undefined; + remoteCustomSettings?: number[] | undefined; + /** + * Specifies a timeout in milliseconds that + * a server should wait when an [`'unknownProtocol'`][] is emitted. If the + * socket has not been destroyed by that time the server will destroy it. + * @default 100000 + */ + unknownProtocolTimeout?: number | undefined; + selectPadding?(frameLen: number, maxFrameLen: number): number; + } + export interface ClientSessionOptions extends SessionOptions { + maxReservedRemoteStreams?: number | undefined; + createConnection?: ((authority: url.URL, option: SessionOptions) => stream.Duplex) | undefined; + protocol?: "http:" | "https:" | undefined; + } + export interface ServerSessionOptions extends SessionOptions { + Http1IncomingMessage?: typeof IncomingMessage | undefined; + Http1ServerResponse?: typeof ServerResponse | undefined; + Http2ServerRequest?: typeof Http2ServerRequest | undefined; + Http2ServerResponse?: typeof Http2ServerResponse | undefined; + } + export interface SecureClientSessionOptions extends ClientSessionOptions, tls.ConnectionOptions {} + export interface SecureServerSessionOptions extends ServerSessionOptions, tls.TlsOptions {} + export interface ServerOptions extends ServerSessionOptions {} + export interface SecureServerOptions extends SecureServerSessionOptions { + allowHTTP1?: boolean | undefined; + origins?: string[] | undefined; + } + interface HTTP2ServerCommon { + setTimeout(msec?: number, callback?: () => void): this; + /** + * Throws ERR_HTTP2_INVALID_SETTING_VALUE for invalid settings values. + * Throws ERR_INVALID_ARG_TYPE for invalid settings argument. + */ + updateSettings(settings: Settings): void; + } + export interface Http2Server extends net.Server, HTTP2ServerCommon { + addListener( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + addListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + addListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + addListener(event: "sessionError", listener: (err: Error) => void): this; + addListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "checkContinue", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "session", session: ServerHttp2Session): boolean; + emit(event: "sessionError", err: Error): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "timeout"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: "session", listener: (session: ServerHttp2Session) => void): this; + on(event: "sessionError", listener: (err: Error) => void): this; + on( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + on(event: "timeout", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: "session", listener: (session: ServerHttp2Session) => void): this; + once(event: "sessionError", listener: (err: Error) => void): this; + once( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + once(event: "timeout", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + prependListener(event: "sessionError", listener: (err: Error) => void): this; + prependListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependOnceListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependOnceListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; + prependOnceListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface Http2SecureServer extends tls.Server, HTTP2ServerCommon { + addListener( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + addListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + addListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + addListener(event: "sessionError", listener: (err: Error) => void): this; + addListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "checkContinue", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "session", session: ServerHttp2Session): boolean; + emit(event: "sessionError", err: Error): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "timeout"): boolean; + emit(event: "unknownProtocol", socket: tls.TLSSocket): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: "session", listener: (session: ServerHttp2Session) => void): this; + on(event: "sessionError", listener: (err: Error) => void): this; + on( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + on(event: "timeout", listener: () => void): this; + on(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: "session", listener: (session: ServerHttp2Session) => void): this; + once(event: "sessionError", listener: (err: Error) => void): this; + once( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + once(event: "timeout", listener: () => void): this; + once(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + prependListener(event: "sessionError", listener: (err: Error) => void): this; + prependListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependOnceListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependOnceListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; + prependOnceListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * A `Http2ServerRequest` object is created by {@link Server} or {@link SecureServer} and passed as the first argument to the `'request'` event. It may be used to access a request status, + * headers, and + * data. + * @since v8.4.0 + */ + export class Http2ServerRequest extends stream.Readable { + constructor( + stream: ServerHttp2Stream, + headers: IncomingHttpHeaders, + options: stream.ReadableOptions, + rawHeaders: readonly string[], + ); + /** + * The `request.aborted` property will be `true` if the request has + * been aborted. + * @since v10.1.0 + */ + readonly aborted: boolean; + /** + * The request authority pseudo header field. Because HTTP/2 allows requests + * to set either `:authority` or `host`, this value is derived from `req.headers[':authority']` if present. Otherwise, it is derived from `req.headers['host']`. + * @since v8.4.0 + */ + readonly authority: string; + /** + * See `request.socket`. + * @since v8.4.0 + * @deprecated Since v13.0.0 - Use `socket`. + */ + readonly connection: net.Socket | tls.TLSSocket; + /** + * The `request.complete` property will be `true` if the request has + * been completed, aborted, or destroyed. + * @since v12.10.0 + */ + readonly complete: boolean; + /** + * The request/response headers object. + * + * Key-value pairs of header names and values. Header names are lower-cased. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': 'curl/7.22.0', + * // host: '127.0.0.1:8000', + * // accept: '*' } + * console.log(request.headers); + * ``` + * + * See `HTTP/2 Headers Object`. + * + * In HTTP/2, the request path, host name, protocol, and method are represented as + * special headers prefixed with the `:` character (e.g. `':path'`). These special + * headers will be included in the `request.headers` object. Care must be taken not + * to inadvertently modify these special headers or errors may occur. For instance, + * removing all headers from the request will cause errors to occur: + * + * ```js + * removeAllHeaders(request.headers); + * assert(request.url); // Fails because the :path header has been removed + * ``` + * @since v8.4.0 + */ + readonly headers: IncomingHttpHeaders; + /** + * In case of server request, the HTTP version sent by the client. In the case of + * client response, the HTTP version of the connected-to server. Returns `'2.0'`. + * + * Also `message.httpVersionMajor` is the first integer and `message.httpVersionMinor` is the second. + * @since v8.4.0 + */ + readonly httpVersion: string; + readonly httpVersionMinor: number; + readonly httpVersionMajor: number; + /** + * The request method as a string. Read-only. Examples: `'GET'`, `'DELETE'`. + * @since v8.4.0 + */ + readonly method: string; + /** + * The raw request/response headers list exactly as they were received. + * + * The keys and values are in the same list. It is _not_ a + * list of tuples. So, the even-numbered offsets are key values, and the + * odd-numbered offsets are the associated values. + * + * Header names are not lowercased, and duplicates are not merged. + * + * ```js + * // Prints something like: + * // + * // [ 'user-agent', + * // 'this is invalid because there can be only one', + * // 'User-Agent', + * // 'curl/7.22.0', + * // 'Host', + * // '127.0.0.1:8000', + * // 'ACCEPT', + * // '*' ] + * console.log(request.rawHeaders); + * ``` + * @since v8.4.0 + */ + readonly rawHeaders: string[]; + /** + * The raw request/response trailer keys and values exactly as they were + * received. Only populated at the `'end'` event. + * @since v8.4.0 + */ + readonly rawTrailers: string[]; + /** + * The request scheme pseudo header field indicating the scheme + * portion of the target URL. + * @since v8.4.0 + */ + readonly scheme: string; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * applies getters, setters, and methods based on HTTP/2 logic. + * + * `destroyed`, `readable`, and `writable` properties will be retrieved from and + * set on `request.stream`. + * + * `destroy`, `emit`, `end`, `on` and `once` methods will be called on `request.stream`. + * + * `setTimeout` method will be called on `request.stream.session`. + * + * `pause`, `read`, `resume`, and `write` will throw an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for + * more information. + * + * All other interactions will be routed directly to the socket. With TLS support, + * use `request.socket.getPeerCertificate()` to obtain the client's + * authentication details. + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * The `Http2Stream` object backing the request. + * @since v8.4.0 + */ + readonly stream: ServerHttp2Stream; + /** + * The request/response trailers object. Only populated at the `'end'` event. + * @since v8.4.0 + */ + readonly trailers: IncomingHttpHeaders; + /** + * Request URL string. This contains only the URL that is present in the actual + * HTTP request. If the request is: + * + * ```http + * GET /status?name=ryan HTTP/1.1 + * Accept: text/plain + * ``` + * + * Then `request.url` will be: + * + * ```js + * '/status?name=ryan' + * ``` + * + * To parse the url into its parts, `new URL()` can be used: + * + * ```console + * $ node + * > new URL('/status?name=ryan', 'http://example.com') + * URL { + * href: 'http://example.com/status?name=ryan', + * origin: 'http://example.com', + * protocol: 'http:', + * username: '', + * password: '', + * host: 'example.com', + * hostname: 'example.com', + * port: '', + * pathname: '/status', + * search: '?name=ryan', + * searchParams: URLSearchParams { 'name' => 'ryan' }, + * hash: '' + * } + * ``` + * @since v8.4.0 + */ + url: string; + /** + * Sets the `Http2Stream`'s timeout value to `msecs`. If a callback is + * provided, then it is added as a listener on the `'timeout'` event on + * the response object. + * + * If no `'timeout'` listener is added to the request, the response, or + * the server, then `Http2Stream`s are destroyed when they time out. If a + * handler is assigned to the request, the response, or the server's `'timeout'`events, timed out sockets must be handled explicitly. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + read(size?: number): Buffer | string | null; + addListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "aborted", hadError: boolean, code: number): boolean; + emit(event: "close"): boolean; + emit(event: "data", chunk: Buffer | string): boolean; + emit(event: "end"): boolean; + emit(event: "readable"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "end", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "end", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * This object is created internally by an HTTP server, not by the user. It is + * passed as the second parameter to the `'request'` event. + * @since v8.4.0 + */ + export class Http2ServerResponse extends stream.Writable { + constructor(stream: ServerHttp2Stream); + /** + * See `response.socket`. + * @since v8.4.0 + * @deprecated Since v13.0.0 - Use `socket`. + */ + readonly connection: net.Socket | tls.TLSSocket; + /** + * Append a single header value to the header object. + * + * If the value is an array, this is equivalent to calling this method multiple times. + * + * If there were no previous values for the header, this is equivalent to calling {@link setHeader}. + * + * Attempting to set a header field name or value that contains invalid characters will result in a + * [TypeError](https://nodejs.org/docs/latest-v22.x/api/errors.html#class-typeerror) being thrown. + * + * ```js + * // Returns headers including "set-cookie: a" and "set-cookie: b" + * const server = http2.createServer((req, res) => { + * res.setHeader('set-cookie', 'a'); + * res.appendHeader('set-cookie', 'b'); + * res.writeHead(200); + * res.end('ok'); + * }); + * ``` + * @since v20.12.0 + */ + appendHeader(name: string, value: string | string[]): void; + /** + * Boolean value that indicates whether the response has completed. Starts + * as `false`. After `response.end()` executes, the value will be `true`. + * @since v8.4.0 + * @deprecated Since v13.4.0,v12.16.0 - Use `writableEnded`. + */ + readonly finished: boolean; + /** + * True if headers were sent, false otherwise (read-only). + * @since v8.4.0 + */ + readonly headersSent: boolean; + /** + * A reference to the original HTTP2 `request` object. + * @since v15.7.0 + */ + readonly req: Http2ServerRequest; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * applies getters, setters, and methods based on HTTP/2 logic. + * + * `destroyed`, `readable`, and `writable` properties will be retrieved from and + * set on `response.stream`. + * + * `destroy`, `emit`, `end`, `on` and `once` methods will be called on `response.stream`. + * + * `setTimeout` method will be called on `response.stream.session`. + * + * `pause`, `read`, `resume`, and `write` will throw an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for + * more information. + * + * All other interactions will be routed directly to the socket. + * + * ```js + * const http2 = require('node:http2'); + * const server = http2.createServer((req, res) => { + * const ip = req.socket.remoteAddress; + * const port = req.socket.remotePort; + * res.end(`Your IP address is ${ip} and your source port is ${port}.`); + * }).listen(3000); + * ``` + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * The `Http2Stream` object backing the response. + * @since v8.4.0 + */ + readonly stream: ServerHttp2Stream; + /** + * When true, the Date header will be automatically generated and sent in + * the response if it is not already present in the headers. Defaults to true. + * + * This should only be disabled for testing; HTTP requires the Date header + * in responses. + * @since v8.4.0 + */ + sendDate: boolean; + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status code that will be sent to the client when + * the headers get flushed. + * + * ```js + * response.statusCode = 404; + * ``` + * + * After response header was sent to the client, this property indicates the + * status code which was sent out. + * @since v8.4.0 + */ + statusCode: number; + /** + * Status message is not supported by HTTP/2 (RFC 7540 8.1.2.4). It returns + * an empty string. + * @since v8.4.0 + */ + statusMessage: ""; + /** + * This method adds HTTP trailing headers (a header but at the end of the + * message) to the response. + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v8.4.0 + */ + addTrailers(trailers: OutgoingHttpHeaders): void; + /** + * This method signals to the server that all of the response headers and body + * have been sent; that server should consider this message complete. + * The method, `response.end()`, MUST be called on each response. + * + * If `data` is specified, it is equivalent to calling `response.write(data, encoding)` followed by `response.end(callback)`. + * + * If `callback` is specified, it will be called when the response stream + * is finished. + * @since v8.4.0 + */ + end(callback?: () => void): this; + end(data: string | Uint8Array, callback?: () => void): this; + end(data: string | Uint8Array, encoding: BufferEncoding, callback?: () => void): this; + /** + * Reads out a header that has already been queued but not sent to the client. + * The name is case-insensitive. + * + * ```js + * const contentType = response.getHeader('content-type'); + * ``` + * @since v8.4.0 + */ + getHeader(name: string): string; + /** + * Returns an array containing the unique names of the current outgoing headers. + * All header names are lowercase. + * + * ```js + * response.setHeader('Foo', 'bar'); + * response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headerNames = response.getHeaderNames(); + * // headerNames === ['foo', 'set-cookie'] + * ``` + * @since v8.4.0 + */ + getHeaderNames(): string[]; + /** + * Returns a shallow copy of the current outgoing headers. Since a shallow copy + * is used, array values may be mutated without additional calls to various + * header-related http module methods. The keys of the returned object are the + * header names and the values are the respective header values. All header names + * are lowercase. + * + * The object returned by the `response.getHeaders()` method _does not_ prototypically inherit from the JavaScript `Object`. This means that typical `Object` methods such as `obj.toString()`, + * `obj.hasOwnProperty()`, and others + * are not defined and _will not work_. + * + * ```js + * response.setHeader('Foo', 'bar'); + * response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headers = response.getHeaders(); + * // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } + * ``` + * @since v8.4.0 + */ + getHeaders(): OutgoingHttpHeaders; + /** + * Returns `true` if the header identified by `name` is currently set in the + * outgoing headers. The header name matching is case-insensitive. + * + * ```js + * const hasContentType = response.hasHeader('content-type'); + * ``` + * @since v8.4.0 + */ + hasHeader(name: string): boolean; + /** + * Removes a header that has been queued for implicit sending. + * + * ```js + * response.removeHeader('Content-Encoding'); + * ``` + * @since v8.4.0 + */ + removeHeader(name: string): void; + /** + * Sets a single header value for implicit headers. If this header already exists + * in the to-be-sent headers, its value will be replaced. Use an array of strings + * here to send multiple headers with the same name. + * + * ```js + * response.setHeader('Content-Type', 'text/html; charset=utf-8'); + * ``` + * + * or + * + * ```js + * response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * ```js + * // Returns content-type = text/plain + * const server = http2.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html; charset=utf-8'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); + * res.end('ok'); + * }); + * ``` + * @since v8.4.0 + */ + setHeader(name: string, value: number | string | readonly string[]): void; + /** + * Sets the `Http2Stream`'s timeout value to `msecs`. If a callback is + * provided, then it is added as a listener on the `'timeout'` event on + * the response object. + * + * If no `'timeout'` listener is added to the request, the response, or + * the server, then `Http2Stream` s are destroyed when they time out. If a + * handler is assigned to the request, the response, or the server's `'timeout'` events, timed out sockets must be handled explicitly. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * If this method is called and `response.writeHead()` has not been called, + * it will switch to implicit header mode and flush the implicit headers. + * + * This sends a chunk of the response body. This method may + * be called multiple times to provide successive parts of the body. + * + * In the `node:http` module, the response body is omitted when the + * request is a HEAD request. Similarly, the `204` and `304` responses _must not_ include a message body. + * + * `chunk` can be a string or a buffer. If `chunk` is a string, + * the second parameter specifies how to encode it into a byte stream. + * By default the `encoding` is `'utf8'`. `callback` will be called when this chunk + * of data is flushed. + * + * This is the raw HTTP body and has nothing to do with higher-level multi-part + * body encodings that may be used. + * + * The first time `response.write()` is called, it will send the buffered + * header information and the first chunk of the body to the client. The second + * time `response.write()` is called, Node.js assumes data will be streamed, + * and sends the new data separately. That is, the response is buffered up to the + * first chunk of the body. + * + * Returns `true` if the entire data was flushed successfully to the kernel + * buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is free again. + * @since v8.4.0 + */ + write(chunk: string | Uint8Array, callback?: (err: Error) => void): boolean; + write(chunk: string | Uint8Array, encoding: BufferEncoding, callback?: (err: Error) => void): boolean; + /** + * Sends a status `100 Continue` to the client, indicating that the request body + * should be sent. See the `'checkContinue'` event on `Http2Server` and `Http2SecureServer`. + * @since v8.4.0 + */ + writeContinue(): void; + /** + * Sends a status `103 Early Hints` to the client with a Link header, + * indicating that the user agent can preload/preconnect the linked resources. + * The `hints` is an object containing the values of headers to be sent with + * early hints message. + * + * **Example** + * + * ```js + * const earlyHintsLink = '; rel=preload; as=style'; + * response.writeEarlyHints({ + * 'link': earlyHintsLink, + * }); + * + * const earlyHintsLinks = [ + * '; rel=preload; as=style', + * '; rel=preload; as=script', + * ]; + * response.writeEarlyHints({ + * 'link': earlyHintsLinks, + * }); + * ``` + * @since v18.11.0 + */ + writeEarlyHints(hints: Record): void; + /** + * Sends a response header to the request. The status code is a 3-digit HTTP + * status code, like `404`. The last argument, `headers`, are the response headers. + * + * Returns a reference to the `Http2ServerResponse`, so that calls can be chained. + * + * For compatibility with `HTTP/1`, a human-readable `statusMessage` may be + * passed as the second argument. However, because the `statusMessage` has no + * meaning within HTTP/2, the argument will have no effect and a process warning + * will be emitted. + * + * ```js + * const body = 'hello world'; + * response.writeHead(200, { + * 'Content-Length': Buffer.byteLength(body), + * 'Content-Type': 'text/plain; charset=utf-8', + * }); + * ``` + * + * `Content-Length` is given in bytes not characters. The`Buffer.byteLength()` API may be used to determine the number of bytes in a + * given encoding. On outbound messages, Node.js does not check if Content-Length + * and the length of the body being transmitted are equal or not. However, when + * receiving messages, Node.js will automatically reject messages when the `Content-Length` does not match the actual payload size. + * + * This method may be called at most one time on a message before `response.end()` is called. + * + * If `response.write()` or `response.end()` are called before calling + * this, the implicit/mutable headers will be calculated and call this function. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * ```js + * // Returns content-type = text/plain + * const server = http2.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html; charset=utf-8'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); + * res.end('ok'); + * }); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v8.4.0 + */ + writeHead(statusCode: number, headers?: OutgoingHttpHeaders): this; + writeHead(statusCode: number, statusMessage: string, headers?: OutgoingHttpHeaders): this; + /** + * Call `http2stream.pushStream()` with the given headers, and wrap the + * given `Http2Stream` on a newly created `Http2ServerResponse` as the callback + * parameter if successful. When `Http2ServerRequest` is closed, the callback is + * called with an error `ERR_HTTP2_INVALID_STREAM`. + * @since v8.4.0 + * @param headers An object describing the headers + * @param callback Called once `http2stream.pushStream()` is finished, or either when the attempt to create the pushed `Http2Stream` has failed or has been rejected, or the state of + * `Http2ServerRequest` is closed prior to calling the `http2stream.pushStream()` method + */ + createPushResponse( + headers: OutgoingHttpHeaders, + callback: (err: Error | null, res: Http2ServerResponse) => void, + ): void; + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "drain"): boolean; + emit(event: "error", error: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pipe", src: stream.Readable): boolean; + emit(event: "unpipe", src: stream.Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (error: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (error: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export namespace constants { + const NGHTTP2_SESSION_SERVER: number; + const NGHTTP2_SESSION_CLIENT: number; + const NGHTTP2_STREAM_STATE_IDLE: number; + const NGHTTP2_STREAM_STATE_OPEN: number; + const NGHTTP2_STREAM_STATE_RESERVED_LOCAL: number; + const NGHTTP2_STREAM_STATE_RESERVED_REMOTE: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE: number; + const NGHTTP2_STREAM_STATE_CLOSED: number; + const NGHTTP2_NO_ERROR: number; + const NGHTTP2_PROTOCOL_ERROR: number; + const NGHTTP2_INTERNAL_ERROR: number; + const NGHTTP2_FLOW_CONTROL_ERROR: number; + const NGHTTP2_SETTINGS_TIMEOUT: number; + const NGHTTP2_STREAM_CLOSED: number; + const NGHTTP2_FRAME_SIZE_ERROR: number; + const NGHTTP2_REFUSED_STREAM: number; + const NGHTTP2_CANCEL: number; + const NGHTTP2_COMPRESSION_ERROR: number; + const NGHTTP2_CONNECT_ERROR: number; + const NGHTTP2_ENHANCE_YOUR_CALM: number; + const NGHTTP2_INADEQUATE_SECURITY: number; + const NGHTTP2_HTTP_1_1_REQUIRED: number; + const NGHTTP2_ERR_FRAME_SIZE_ERROR: number; + const NGHTTP2_FLAG_NONE: number; + const NGHTTP2_FLAG_END_STREAM: number; + const NGHTTP2_FLAG_END_HEADERS: number; + const NGHTTP2_FLAG_ACK: number; + const NGHTTP2_FLAG_PADDED: number; + const NGHTTP2_FLAG_PRIORITY: number; + const DEFAULT_SETTINGS_HEADER_TABLE_SIZE: number; + const DEFAULT_SETTINGS_ENABLE_PUSH: number; + const DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE: number; + const DEFAULT_SETTINGS_MAX_FRAME_SIZE: number; + const MAX_MAX_FRAME_SIZE: number; + const MIN_MAX_FRAME_SIZE: number; + const MAX_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_DEFAULT_WEIGHT: number; + const NGHTTP2_SETTINGS_HEADER_TABLE_SIZE: number; + const NGHTTP2_SETTINGS_ENABLE_PUSH: number; + const NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS: number; + const NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_SETTINGS_MAX_FRAME_SIZE: number; + const NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE: number; + const PADDING_STRATEGY_NONE: number; + const PADDING_STRATEGY_MAX: number; + const PADDING_STRATEGY_CALLBACK: number; + const HTTP2_HEADER_STATUS: string; + const HTTP2_HEADER_METHOD: string; + const HTTP2_HEADER_AUTHORITY: string; + const HTTP2_HEADER_SCHEME: string; + const HTTP2_HEADER_PATH: string; + const HTTP2_HEADER_ACCEPT_CHARSET: string; + const HTTP2_HEADER_ACCEPT_ENCODING: string; + const HTTP2_HEADER_ACCEPT_LANGUAGE: string; + const HTTP2_HEADER_ACCEPT_RANGES: string; + const HTTP2_HEADER_ACCEPT: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_HEADERS: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_METHODS: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN: string; + const HTTP2_HEADER_ACCESS_CONTROL_EXPOSE_HEADERS: string; + const HTTP2_HEADER_ACCESS_CONTROL_REQUEST_HEADERS: string; + const HTTP2_HEADER_ACCESS_CONTROL_REQUEST_METHOD: string; + const HTTP2_HEADER_AGE: string; + const HTTP2_HEADER_ALLOW: string; + const HTTP2_HEADER_AUTHORIZATION: string; + const HTTP2_HEADER_CACHE_CONTROL: string; + const HTTP2_HEADER_CONNECTION: string; + const HTTP2_HEADER_CONTENT_DISPOSITION: string; + const HTTP2_HEADER_CONTENT_ENCODING: string; + const HTTP2_HEADER_CONTENT_LANGUAGE: string; + const HTTP2_HEADER_CONTENT_LENGTH: string; + const HTTP2_HEADER_CONTENT_LOCATION: string; + const HTTP2_HEADER_CONTENT_MD5: string; + const HTTP2_HEADER_CONTENT_RANGE: string; + const HTTP2_HEADER_CONTENT_TYPE: string; + const HTTP2_HEADER_COOKIE: string; + const HTTP2_HEADER_DATE: string; + const HTTP2_HEADER_ETAG: string; + const HTTP2_HEADER_EXPECT: string; + const HTTP2_HEADER_EXPIRES: string; + const HTTP2_HEADER_FROM: string; + const HTTP2_HEADER_HOST: string; + const HTTP2_HEADER_IF_MATCH: string; + const HTTP2_HEADER_IF_MODIFIED_SINCE: string; + const HTTP2_HEADER_IF_NONE_MATCH: string; + const HTTP2_HEADER_IF_RANGE: string; + const HTTP2_HEADER_IF_UNMODIFIED_SINCE: string; + const HTTP2_HEADER_LAST_MODIFIED: string; + const HTTP2_HEADER_LINK: string; + const HTTP2_HEADER_LOCATION: string; + const HTTP2_HEADER_MAX_FORWARDS: string; + const HTTP2_HEADER_PREFER: string; + const HTTP2_HEADER_PROXY_AUTHENTICATE: string; + const HTTP2_HEADER_PROXY_AUTHORIZATION: string; + const HTTP2_HEADER_RANGE: string; + const HTTP2_HEADER_REFERER: string; + const HTTP2_HEADER_REFRESH: string; + const HTTP2_HEADER_RETRY_AFTER: string; + const HTTP2_HEADER_SERVER: string; + const HTTP2_HEADER_SET_COOKIE: string; + const HTTP2_HEADER_STRICT_TRANSPORT_SECURITY: string; + const HTTP2_HEADER_TRANSFER_ENCODING: string; + const HTTP2_HEADER_TE: string; + const HTTP2_HEADER_UPGRADE: string; + const HTTP2_HEADER_USER_AGENT: string; + const HTTP2_HEADER_VARY: string; + const HTTP2_HEADER_VIA: string; + const HTTP2_HEADER_WWW_AUTHENTICATE: string; + const HTTP2_HEADER_HTTP2_SETTINGS: string; + const HTTP2_HEADER_KEEP_ALIVE: string; + const HTTP2_HEADER_PROXY_CONNECTION: string; + const HTTP2_METHOD_ACL: string; + const HTTP2_METHOD_BASELINE_CONTROL: string; + const HTTP2_METHOD_BIND: string; + const HTTP2_METHOD_CHECKIN: string; + const HTTP2_METHOD_CHECKOUT: string; + const HTTP2_METHOD_CONNECT: string; + const HTTP2_METHOD_COPY: string; + const HTTP2_METHOD_DELETE: string; + const HTTP2_METHOD_GET: string; + const HTTP2_METHOD_HEAD: string; + const HTTP2_METHOD_LABEL: string; + const HTTP2_METHOD_LINK: string; + const HTTP2_METHOD_LOCK: string; + const HTTP2_METHOD_MERGE: string; + const HTTP2_METHOD_MKACTIVITY: string; + const HTTP2_METHOD_MKCALENDAR: string; + const HTTP2_METHOD_MKCOL: string; + const HTTP2_METHOD_MKREDIRECTREF: string; + const HTTP2_METHOD_MKWORKSPACE: string; + const HTTP2_METHOD_MOVE: string; + const HTTP2_METHOD_OPTIONS: string; + const HTTP2_METHOD_ORDERPATCH: string; + const HTTP2_METHOD_PATCH: string; + const HTTP2_METHOD_POST: string; + const HTTP2_METHOD_PRI: string; + const HTTP2_METHOD_PROPFIND: string; + const HTTP2_METHOD_PROPPATCH: string; + const HTTP2_METHOD_PUT: string; + const HTTP2_METHOD_REBIND: string; + const HTTP2_METHOD_REPORT: string; + const HTTP2_METHOD_SEARCH: string; + const HTTP2_METHOD_TRACE: string; + const HTTP2_METHOD_UNBIND: string; + const HTTP2_METHOD_UNCHECKOUT: string; + const HTTP2_METHOD_UNLINK: string; + const HTTP2_METHOD_UNLOCK: string; + const HTTP2_METHOD_UPDATE: string; + const HTTP2_METHOD_UPDATEREDIRECTREF: string; + const HTTP2_METHOD_VERSION_CONTROL: string; + const HTTP_STATUS_CONTINUE: number; + const HTTP_STATUS_SWITCHING_PROTOCOLS: number; + const HTTP_STATUS_PROCESSING: number; + const HTTP_STATUS_OK: number; + const HTTP_STATUS_CREATED: number; + const HTTP_STATUS_ACCEPTED: number; + const HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION: number; + const HTTP_STATUS_NO_CONTENT: number; + const HTTP_STATUS_RESET_CONTENT: number; + const HTTP_STATUS_PARTIAL_CONTENT: number; + const HTTP_STATUS_MULTI_STATUS: number; + const HTTP_STATUS_ALREADY_REPORTED: number; + const HTTP_STATUS_IM_USED: number; + const HTTP_STATUS_MULTIPLE_CHOICES: number; + const HTTP_STATUS_MOVED_PERMANENTLY: number; + const HTTP_STATUS_FOUND: number; + const HTTP_STATUS_SEE_OTHER: number; + const HTTP_STATUS_NOT_MODIFIED: number; + const HTTP_STATUS_USE_PROXY: number; + const HTTP_STATUS_TEMPORARY_REDIRECT: number; + const HTTP_STATUS_PERMANENT_REDIRECT: number; + const HTTP_STATUS_BAD_REQUEST: number; + const HTTP_STATUS_UNAUTHORIZED: number; + const HTTP_STATUS_PAYMENT_REQUIRED: number; + const HTTP_STATUS_FORBIDDEN: number; + const HTTP_STATUS_NOT_FOUND: number; + const HTTP_STATUS_METHOD_NOT_ALLOWED: number; + const HTTP_STATUS_NOT_ACCEPTABLE: number; + const HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED: number; + const HTTP_STATUS_REQUEST_TIMEOUT: number; + const HTTP_STATUS_CONFLICT: number; + const HTTP_STATUS_GONE: number; + const HTTP_STATUS_LENGTH_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_FAILED: number; + const HTTP_STATUS_PAYLOAD_TOO_LARGE: number; + const HTTP_STATUS_URI_TOO_LONG: number; + const HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE: number; + const HTTP_STATUS_RANGE_NOT_SATISFIABLE: number; + const HTTP_STATUS_EXPECTATION_FAILED: number; + const HTTP_STATUS_TEAPOT: number; + const HTTP_STATUS_MISDIRECTED_REQUEST: number; + const HTTP_STATUS_UNPROCESSABLE_ENTITY: number; + const HTTP_STATUS_LOCKED: number; + const HTTP_STATUS_FAILED_DEPENDENCY: number; + const HTTP_STATUS_UNORDERED_COLLECTION: number; + const HTTP_STATUS_UPGRADE_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_REQUIRED: number; + const HTTP_STATUS_TOO_MANY_REQUESTS: number; + const HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE: number; + const HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS: number; + const HTTP_STATUS_INTERNAL_SERVER_ERROR: number; + const HTTP_STATUS_NOT_IMPLEMENTED: number; + const HTTP_STATUS_BAD_GATEWAY: number; + const HTTP_STATUS_SERVICE_UNAVAILABLE: number; + const HTTP_STATUS_GATEWAY_TIMEOUT: number; + const HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED: number; + const HTTP_STATUS_VARIANT_ALSO_NEGOTIATES: number; + const HTTP_STATUS_INSUFFICIENT_STORAGE: number; + const HTTP_STATUS_LOOP_DETECTED: number; + const HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED: number; + const HTTP_STATUS_NOT_EXTENDED: number; + const HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED: number; + } + /** + * This symbol can be set as a property on the HTTP/2 headers object with + * an array value in order to provide a list of headers considered sensitive. + */ + export const sensitiveHeaders: symbol; + /** + * Returns an object containing the default settings for an `Http2Session` instance. This method returns a new object instance every time it is called + * so instances returned may be safely modified for use. + * @since v8.4.0 + */ + export function getDefaultSettings(): Settings; + /** + * Returns a `Buffer` instance containing serialized representation of the given + * HTTP/2 settings as specified in the [HTTP/2](https://tools.ietf.org/html/rfc7540) specification. This is intended + * for use with the `HTTP2-Settings` header field. + * + * ```js + * const http2 = require('node:http2'); + * + * const packed = http2.getPackedSettings({ enablePush: false }); + * + * console.log(packed.toString('base64')); + * // Prints: AAIAAAAA + * ``` + * @since v8.4.0 + */ + export function getPackedSettings(settings: Settings): Buffer; + /** + * Returns a `HTTP/2 Settings Object` containing the deserialized settings from + * the given `Buffer` as generated by `http2.getPackedSettings()`. + * @since v8.4.0 + * @param buf The packed settings. + */ + export function getUnpackedSettings(buf: Uint8Array): Settings; + /** + * Returns a `net.Server` instance that creates and manages `Http2Session` instances. + * + * Since there are no browsers known that support [unencrypted HTTP/2](https://http2.github.io/faq/#does-http2-require-encryption), the use of {@link createSecureServer} is necessary when + * communicating + * with browser clients. + * + * ```js + * const http2 = require('node:http2'); + * + * // Create an unencrypted HTTP/2 server. + * // Since there are no browsers known that support + * // unencrypted HTTP/2, the use of `http2.createSecureServer()` + * // is necessary when communicating with browser clients. + * const server = http2.createServer(); + * + * server.on('stream', (stream, headers) => { + * stream.respond({ + * 'content-type': 'text/html; charset=utf-8', + * ':status': 200, + * }); + * stream.end('

Hello World

'); + * }); + * + * server.listen(8000); + * ``` + * @since v8.4.0 + * @param onRequestHandler See `Compatibility API` + */ + export function createServer( + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2Server; + export function createServer( + options: ServerOptions, + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2Server; + /** + * Returns a `tls.Server` instance that creates and manages `Http2Session` instances. + * + * ```js + * const http2 = require('node:http2'); + * const fs = require('node:fs'); + * + * const options = { + * key: fs.readFileSync('server-key.pem'), + * cert: fs.readFileSync('server-cert.pem'), + * }; + * + * // Create a secure HTTP/2 server + * const server = http2.createSecureServer(options); + * + * server.on('stream', (stream, headers) => { + * stream.respond({ + * 'content-type': 'text/html; charset=utf-8', + * ':status': 200, + * }); + * stream.end('

Hello World

'); + * }); + * + * server.listen(8443); + * ``` + * @since v8.4.0 + * @param onRequestHandler See `Compatibility API` + */ + export function createSecureServer( + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2SecureServer; + export function createSecureServer( + options: SecureServerOptions, + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2SecureServer; + /** + * Returns a `ClientHttp2Session` instance. + * + * ```js + * const http2 = require('node:http2'); + * const client = http2.connect('https://localhost:1234'); + * + * // Use the client + * + * client.close(); + * ``` + * @since v8.4.0 + * @param authority The remote HTTP/2 server to connect to. This must be in the form of a minimal, valid URL with the `http://` or `https://` prefix, host name, and IP port (if a non-default port + * is used). Userinfo (user ID and password), path, querystring, and fragment details in the URL will be ignored. + * @param listener Will be registered as a one-time listener of the {@link 'connect'} event. + */ + export function connect( + authority: string | url.URL, + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): ClientHttp2Session; + export function connect( + authority: string | url.URL, + options?: ClientSessionOptions | SecureClientSessionOptions, + listener?: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): ClientHttp2Session; + /** + * Create an HTTP/2 server session from an existing socket. + * @param socket A Duplex Stream + * @param options Any `{@link createServer}` options can be provided. + * @since v20.12.0 + */ + export function performServerHandshake(socket: stream.Duplex, options?: ServerOptions): ServerHttp2Session; +} +declare module "node:http2" { + export * from "http2"; +} diff --git a/libcore/node_modules/@types/node/https.d.ts b/libcore/node_modules/@types/node/https.d.ts new file mode 100644 index 0000000..3a821e3 --- /dev/null +++ b/libcore/node_modules/@types/node/https.d.ts @@ -0,0 +1,550 @@ +/** + * HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a + * separate module. + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/https.js) + */ +declare module "https" { + import { Duplex } from "node:stream"; + import * as tls from "node:tls"; + import * as http from "node:http"; + import { URL } from "node:url"; + type ServerOptions< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse = typeof http.ServerResponse, + > = tls.SecureContextOptions & tls.TlsOptions & http.ServerOptions; + type RequestOptions = + & http.RequestOptions + & tls.SecureContextOptions + & { + checkServerIdentity?: typeof tls.checkServerIdentity | undefined; + rejectUnauthorized?: boolean | undefined; // Defaults to true + servername?: string | undefined; // SNI TLS Extension + }; + interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions { + rejectUnauthorized?: boolean | undefined; + maxCachedSessions?: number | undefined; + } + /** + * An `Agent` object for HTTPS similar to `http.Agent`. See {@link request} for more information. + * @since v0.4.5 + */ + class Agent extends http.Agent { + constructor(options?: AgentOptions); + options: AgentOptions; + } + interface Server< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse = typeof http.ServerResponse, + > extends http.Server {} + /** + * See `http.Server` for more information. + * @since v0.3.4 + */ + class Server< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse = typeof http.ServerResponse, + > extends tls.Server { + constructor(requestListener?: http.RequestListener); + constructor( + options: ServerOptions, + requestListener?: http.RequestListener, + ); + /** + * Closes all connections connected to this server. + * @since v18.2.0 + */ + closeAllConnections(): void; + /** + * Closes all connections connected to this server which are not sending a request or waiting for a response. + * @since v18.2.0 + */ + closeIdleConnections(): void; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + addListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, + ): this; + addListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + addListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, + ): this; + addListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connection", listener: (socket: Duplex) => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "checkContinue", listener: http.RequestListener): this; + addListener(event: "checkExpectation", listener: http.RequestListener): this; + addListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + addListener( + event: "connect", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + addListener(event: "request", listener: http.RequestListener): this; + addListener( + event: "upgrade", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + emit(event: string, ...args: any[]): boolean; + emit(event: "keylog", line: Buffer, tlsSocket: tls.TLSSocket): boolean; + emit( + event: "newSession", + sessionId: Buffer, + sessionData: Buffer, + callback: (err: Error, resp: Buffer) => void, + ): boolean; + emit( + event: "OCSPRequest", + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ): boolean; + emit(event: "resumeSession", sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void): boolean; + emit(event: "secureConnection", tlsSocket: tls.TLSSocket): boolean; + emit(event: "tlsClientError", err: Error, tlsSocket: tls.TLSSocket): boolean; + emit(event: "close"): boolean; + emit(event: "connection", socket: Duplex): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit( + event: "checkContinue", + req: InstanceType, + res: InstanceType & { + req: InstanceType; + }, + ): boolean; + emit( + event: "checkExpectation", + req: InstanceType, + res: InstanceType & { + req: InstanceType; + }, + ): boolean; + emit(event: "clientError", err: Error, socket: Duplex): boolean; + emit(event: "connect", req: InstanceType, socket: Duplex, head: Buffer): boolean; + emit( + event: "request", + req: InstanceType, + res: InstanceType & { + req: InstanceType; + }, + ): boolean; + emit(event: "upgrade", req: InstanceType, socket: Duplex, head: Buffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + on( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, + ): this; + on( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + on( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, + ): this; + on(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + on(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connection", listener: (socket: Duplex) => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "checkContinue", listener: http.RequestListener): this; + on(event: "checkExpectation", listener: http.RequestListener): this; + on(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + on(event: "connect", listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; + on(event: "request", listener: http.RequestListener): this; + on(event: "upgrade", listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + once( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, + ): this; + once( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + once( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, + ): this; + once(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + once(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connection", listener: (socket: Duplex) => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "checkContinue", listener: http.RequestListener): this; + once(event: "checkExpectation", listener: http.RequestListener): this; + once(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + once(event: "connect", listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; + once(event: "request", listener: http.RequestListener): this; + once(event: "upgrade", listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + prependListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, + ): this; + prependListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + prependListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, + ): this; + prependListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connection", listener: (socket: Duplex) => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "checkContinue", listener: http.RequestListener): this; + prependListener(event: "checkExpectation", listener: http.RequestListener): this; + prependListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + prependListener( + event: "connect", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + prependListener(event: "request", listener: http.RequestListener): this; + prependListener( + event: "upgrade", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, + ): this; + prependOnceListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + prependOnceListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, + ): this; + prependOnceListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connection", listener: (socket: Duplex) => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "checkContinue", listener: http.RequestListener): this; + prependOnceListener(event: "checkExpectation", listener: http.RequestListener): this; + prependOnceListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + prependOnceListener( + event: "connect", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + prependOnceListener(event: "request", listener: http.RequestListener): this; + prependOnceListener( + event: "upgrade", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + } + /** + * ```js + * // curl -k https://localhost:8000/ + * const https = require('node:https'); + * const fs = require('node:fs'); + * + * const options = { + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), + * }; + * + * https.createServer(options, (req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * ``` + * + * Or + * + * ```js + * const https = require('node:https'); + * const fs = require('node:fs'); + * + * const options = { + * pfx: fs.readFileSync('test/fixtures/test_cert.pfx'), + * passphrase: 'sample', + * }; + * + * https.createServer(options, (req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * ``` + * @since v0.3.4 + * @param options Accepts `options` from `createServer`, `createSecureContext` and `createServer`. + * @param requestListener A listener to be added to the `'request'` event. + */ + function createServer< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse = typeof http.ServerResponse, + >(requestListener?: http.RequestListener): Server; + function createServer< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse = typeof http.ServerResponse, + >( + options: ServerOptions, + requestListener?: http.RequestListener, + ): Server; + /** + * Makes a request to a secure web server. + * + * The following additional `options` from `tls.connect()` are also accepted: `ca`, `cert`, `ciphers`, `clientCertEngine`, `crl`, `dhparam`, `ecdhCurve`, `honorCipherOrder`, `key`, `passphrase`, + * `pfx`, `rejectUnauthorized`, `secureOptions`, `secureProtocol`, `servername`, `sessionIdContext`, `highWaterMark`. + * + * `options` can be an object, a string, or a `URL` object. If `options` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * `https.request()` returns an instance of the `http.ClientRequest` class. The `ClientRequest` instance is a writable stream. If one needs to + * upload a file with a POST request, then write to the `ClientRequest` object. + * + * ```js + * const https = require('node:https'); + * + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * }; + * + * const req = https.request(options, (res) => { + * console.log('statusCode:', res.statusCode); + * console.log('headers:', res.headers); + * + * res.on('data', (d) => { + * process.stdout.write(d); + * }); + * }); + * + * req.on('error', (e) => { + * console.error(e); + * }); + * req.end(); + * ``` + * + * Example using options from `tls.connect()`: + * + * ```js + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), + * }; + * options.agent = new https.Agent(options); + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Alternatively, opt out of connection pooling by not using an `Agent`. + * + * ```js + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), + * agent: false, + * }; + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Example using a `URL` as `options`: + * + * ```js + * const options = new URL('https://abc:xyz@example.com'); + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Example pinning on certificate fingerprint, or the public key (similar to`pin-sha256`): + * + * ```js + * const tls = require('node:tls'); + * const https = require('node:https'); + * const crypto = require('node:crypto'); + * + * function sha256(s) { + * return crypto.createHash('sha256').update(s).digest('base64'); + * } + * const options = { + * hostname: 'github.com', + * port: 443, + * path: '/', + * method: 'GET', + * checkServerIdentity: function(host, cert) { + * // Make sure the certificate is issued to the host we are connected to + * const err = tls.checkServerIdentity(host, cert); + * if (err) { + * return err; + * } + * + * // Pin the public key, similar to HPKP pin-sha256 pinning + * const pubkey256 = 'pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU='; + * if (sha256(cert.pubkey) !== pubkey256) { + * const msg = 'Certificate verification error: ' + + * `The public key of '${cert.subject.CN}' ` + + * 'does not match our pinned fingerprint'; + * return new Error(msg); + * } + * + * // Pin the exact certificate, rather than the pub key + * const cert256 = '25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:' + + * 'D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16'; + * if (cert.fingerprint256 !== cert256) { + * const msg = 'Certificate verification error: ' + + * `The certificate of '${cert.subject.CN}' ` + + * 'does not match our pinned fingerprint'; + * return new Error(msg); + * } + * + * // This loop is informational only. + * // Print the certificate and public key fingerprints of all certs in the + * // chain. Its common to pin the public key of the issuer on the public + * // internet, while pinning the public key of the service in sensitive + * // environments. + * do { + * console.log('Subject Common Name:', cert.subject.CN); + * console.log(' Certificate SHA256 fingerprint:', cert.fingerprint256); + * + * hash = crypto.createHash('sha256'); + * console.log(' Public key ping-sha256:', sha256(cert.pubkey)); + * + * lastprint256 = cert.fingerprint256; + * cert = cert.issuerCertificate; + * } while (cert.fingerprint256 !== lastprint256); + * + * }, + * }; + * + * options.agent = new https.Agent(options); + * const req = https.request(options, (res) => { + * console.log('All OK. Server matched our pinned cert or public key'); + * console.log('statusCode:', res.statusCode); + * // Print the HPKP values + * console.log('headers:', res.headers['public-key-pins']); + * + * res.on('data', (d) => {}); + * }); + * + * req.on('error', (e) => { + * console.error(e.message); + * }); + * req.end(); + * ``` + * + * Outputs for example: + * + * ```text + * Subject Common Name: github.com + * Certificate SHA256 fingerprint: 25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16 + * Public key ping-sha256: pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU= + * Subject Common Name: DigiCert SHA2 Extended Validation Server CA + * Certificate SHA256 fingerprint: 40:3E:06:2A:26:53:05:91:13:28:5B:AF:80:A0:D4:AE:42:2C:84:8C:9F:78:FA:D0:1F:C9:4B:C5:B8:7F:EF:1A + * Public key ping-sha256: RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho= + * Subject Common Name: DigiCert High Assurance EV Root CA + * Certificate SHA256 fingerprint: 74:31:E5:F4:C3:C1:CE:46:90:77:4F:0B:61:E0:54:40:88:3B:A9:A0:1E:D0:0B:A6:AB:D7:80:6E:D3:B1:18:CF + * Public key ping-sha256: WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18= + * All OK. Server matched our pinned cert or public key + * statusCode: 200 + * headers: max-age=0; pin-sha256="WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18="; pin-sha256="RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho="; + * pin-sha256="k2v657xBsOVe1PQRwOsHsw3bsGT2VzIqz5K+59sNQws="; pin-sha256="K87oWBWM9UZfyddvDfoxL+8lpNyoUB2ptGtn0fv6G2Q="; pin-sha256="IQBnNBEiFuhj+8x6X8XLgh01V9Ic5/V3IRQLNFFc7v4="; + * pin-sha256="iie1VXtL7HzAMF+/PVPR9xzT80kQxdZeJ+zduCB3uj0="; pin-sha256="LvRiGEjRqfzurezaWuj8Wie2gyHMrW5Q06LspMnox7A="; includeSubDomains + * ``` + * @since v0.3.6 + * @param options Accepts all `options` from `request`, with some differences in default values: + */ + function request( + options: RequestOptions | string | URL, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + function request( + url: string | URL, + options: RequestOptions, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + /** + * Like `http.get()` but for HTTPS. + * + * `options` can be an object, a string, or a `URL` object. If `options` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * ```js + * const https = require('node:https'); + * + * https.get('https://encrypted.google.com/', (res) => { + * console.log('statusCode:', res.statusCode); + * console.log('headers:', res.headers); + * + * res.on('data', (d) => { + * process.stdout.write(d); + * }); + * + * }).on('error', (e) => { + * console.error(e); + * }); + * ``` + * @since v0.3.6 + * @param options Accepts the same `options` as {@link request}, with the `method` always set to `GET`. + */ + function get( + options: RequestOptions | string | URL, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + function get( + url: string | URL, + options: RequestOptions, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + let globalAgent: Agent; +} +declare module "node:https" { + export * from "https"; +} diff --git a/libcore/node_modules/@types/node/index.d.ts b/libcore/node_modules/@types/node/index.d.ts new file mode 100644 index 0000000..e575985 --- /dev/null +++ b/libcore/node_modules/@types/node/index.d.ts @@ -0,0 +1,90 @@ +/** + * License for programmatically and manually incorporated + * documentation aka. `JSDoc` from https://github.com/nodejs/node/tree/master/doc + * + * Copyright Node.js contributors. All rights reserved. + * 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. + */ + +// NOTE: These definitions support NodeJS and TypeScript 4.9+. + +// Reference required types from the default lib: +/// +/// +/// +/// + +// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// + +/// diff --git a/libcore/node_modules/@types/node/inspector.d.ts b/libcore/node_modules/@types/node/inspector.d.ts new file mode 100644 index 0000000..a27ab04 --- /dev/null +++ b/libcore/node_modules/@types/node/inspector.d.ts @@ -0,0 +1,3696 @@ +// These definitions are automatically generated by the generate-inspector script. +// Do not edit this file directly. +// See scripts/generate-inspector/README.md for information on how to update the protocol definitions. +// Changes to the module itself should be added to the generator template (scripts/generate-inspector/inspector.d.ts.template). + +/** + * The `node:inspector` module provides an API for interacting with the V8 + * inspector. + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/inspector.js) + */ +declare module 'inspector' { + import EventEmitter = require('node:events'); + + interface InspectorNotification { + method: string; + params: T; + } + + namespace Schema { + /** + * Description of the protocol domain. + */ + interface Domain { + /** + * Domain name. + */ + name: string; + /** + * Domain version. + */ + version: string; + } + interface GetDomainsReturnType { + /** + * List of supported domains. + */ + domains: Domain[]; + } + } + namespace Runtime { + /** + * Unique script identifier. + */ + type ScriptId = string; + /** + * Unique object identifier. + */ + type RemoteObjectId = string; + /** + * Primitive value which cannot be JSON-stringified. + */ + type UnserializableValue = string; + /** + * Mirror object referencing original JavaScript object. + */ + interface RemoteObject { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + /** + * Object class (constructor) name. Specified for object type values only. + */ + className?: string | undefined; + /** + * Remote object value in case of primitive values or JSON values (if it was requested). + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified does not have value, but gets this property. + */ + unserializableValue?: UnserializableValue | undefined; + /** + * String representation of the object. + */ + description?: string | undefined; + /** + * Unique object identifier (for non-primitive values). + */ + objectId?: RemoteObjectId | undefined; + /** + * Preview containing abbreviated property values. Specified for object type values only. + * @experimental + */ + preview?: ObjectPreview | undefined; + /** + * @experimental + */ + customPreview?: CustomPreview | undefined; + } + /** + * @experimental + */ + interface CustomPreview { + header: string; + hasBody: boolean; + formatterObjectId: RemoteObjectId; + bindRemoteObjectFunctionId: RemoteObjectId; + configObjectId?: RemoteObjectId | undefined; + } + /** + * Object containing abbreviated remote object value. + * @experimental + */ + interface ObjectPreview { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + /** + * String representation of the object. + */ + description?: string | undefined; + /** + * True iff some of the properties or entries of the original object did not fit. + */ + overflow: boolean; + /** + * List of the properties. + */ + properties: PropertyPreview[]; + /** + * List of the entries. Specified for map and set subtype values only. + */ + entries?: EntryPreview[] | undefined; + } + /** + * @experimental + */ + interface PropertyPreview { + /** + * Property name. + */ + name: string; + /** + * Object type. Accessor means that the property itself is an accessor property. + */ + type: string; + /** + * User-friendly property value string. + */ + value?: string | undefined; + /** + * Nested value preview. + */ + valuePreview?: ObjectPreview | undefined; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + } + /** + * @experimental + */ + interface EntryPreview { + /** + * Preview of the key. Specified for map-like collection entries. + */ + key?: ObjectPreview | undefined; + /** + * Preview of the value. + */ + value: ObjectPreview; + } + /** + * Object property descriptor. + */ + interface PropertyDescriptor { + /** + * Property name or symbol description. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject | undefined; + /** + * True if the value associated with the property may be changed (data descriptors only). + */ + writable?: boolean | undefined; + /** + * A function which serves as a getter for the property, or undefined if there is no getter (accessor descriptors only). + */ + get?: RemoteObject | undefined; + /** + * A function which serves as a setter for the property, or undefined if there is no setter (accessor descriptors only). + */ + set?: RemoteObject | undefined; + /** + * True if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. + */ + configurable: boolean; + /** + * True if this property shows up during enumeration of the properties on the corresponding object. + */ + enumerable: boolean; + /** + * True if the result was thrown during the evaluation. + */ + wasThrown?: boolean | undefined; + /** + * True if the property is owned for the object. + */ + isOwn?: boolean | undefined; + /** + * Property symbol object, if the property is of the symbol type. + */ + symbol?: RemoteObject | undefined; + } + /** + * Object internal property descriptor. This property isn't normally visible in JavaScript code. + */ + interface InternalPropertyDescriptor { + /** + * Conventional property name. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject | undefined; + } + /** + * Represents function call argument. Either remote object id objectId, primitive value, unserializable primitive value or neither of (for undefined) them should be specified. + */ + interface CallArgument { + /** + * Primitive value or serializable javascript object. + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified. + */ + unserializableValue?: UnserializableValue | undefined; + /** + * Remote object handle. + */ + objectId?: RemoteObjectId | undefined; + } + /** + * Id of an execution context. + */ + type ExecutionContextId = number; + /** + * Description of an isolated world. + */ + interface ExecutionContextDescription { + /** + * Unique id of the execution context. It can be used to specify in which execution context script evaluation should be performed. + */ + id: ExecutionContextId; + /** + * Execution context origin. + */ + origin: string; + /** + * Human readable name describing given context. + */ + name: string; + /** + * Embedder-specific auxiliary data. + */ + auxData?: {} | undefined; + } + /** + * Detailed information about exception (or error) that was thrown during script compilation or execution. + */ + interface ExceptionDetails { + /** + * Exception id. + */ + exceptionId: number; + /** + * Exception text, which should be used together with exception object when available. + */ + text: string; + /** + * Line number of the exception location (0-based). + */ + lineNumber: number; + /** + * Column number of the exception location (0-based). + */ + columnNumber: number; + /** + * Script ID of the exception location. + */ + scriptId?: ScriptId | undefined; + /** + * URL of the exception location, to be used when the script was not reported. + */ + url?: string | undefined; + /** + * JavaScript stack trace if available. + */ + stackTrace?: StackTrace | undefined; + /** + * Exception object if available. + */ + exception?: RemoteObject | undefined; + /** + * Identifier of the context where exception happened. + */ + executionContextId?: ExecutionContextId | undefined; + } + /** + * Number of milliseconds since epoch. + */ + type Timestamp = number; + /** + * Stack entry for runtime errors and assertions. + */ + interface CallFrame { + /** + * JavaScript function name. + */ + functionName: string; + /** + * JavaScript script id. + */ + scriptId: ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * JavaScript script line number (0-based). + */ + lineNumber: number; + /** + * JavaScript script column number (0-based). + */ + columnNumber: number; + } + /** + * Call frames for assertions or error messages. + */ + interface StackTrace { + /** + * String label of this stack trace. For async traces this may be a name of the function that initiated the async call. + */ + description?: string | undefined; + /** + * JavaScript function name. + */ + callFrames: CallFrame[]; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + */ + parent?: StackTrace | undefined; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + * @experimental + */ + parentId?: StackTraceId | undefined; + } + /** + * Unique identifier of current debugger. + * @experimental + */ + type UniqueDebuggerId = string; + /** + * If debuggerId is set stack trace comes from another debugger and can be resolved there. This allows to track cross-debugger calls. See Runtime.StackTrace and Debugger.paused for usages. + * @experimental + */ + interface StackTraceId { + id: string; + debuggerId?: UniqueDebuggerId | undefined; + } + interface EvaluateParameterType { + /** + * Expression to evaluate. + */ + expression: string; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Specifies in which execution context to perform evaluation. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + contextId?: ExecutionContextId | undefined; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + } + interface AwaitPromiseParameterType { + /** + * Identifier of the promise. + */ + promiseObjectId: RemoteObjectId; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean | undefined; + } + interface CallFunctionOnParameterType { + /** + * Declaration of the function to call. + */ + functionDeclaration: string; + /** + * Identifier of the object to call function on. Either objectId or executionContextId should be specified. + */ + objectId?: RemoteObjectId | undefined; + /** + * Call arguments. All call arguments must belong to the same JavaScript world as the target object. + */ + arguments?: CallArgument[] | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + /** + * Specifies execution context which global object will be used to call function on. Either executionContextId or objectId should be specified. + */ + executionContextId?: ExecutionContextId | undefined; + /** + * Symbolic group name that can be used to release multiple objects. If objectGroup is not specified and objectId is, objectGroup will be inherited from object. + */ + objectGroup?: string | undefined; + } + interface GetPropertiesParameterType { + /** + * Identifier of the object to return properties for. + */ + objectId: RemoteObjectId; + /** + * If true, returns properties belonging only to the element itself, not to its prototype chain. + */ + ownProperties?: boolean | undefined; + /** + * If true, returns accessor properties (with getter/setter) only; internal properties are not returned either. + * @experimental + */ + accessorPropertiesOnly?: boolean | undefined; + /** + * Whether preview should be generated for the results. + * @experimental + */ + generatePreview?: boolean | undefined; + } + interface ReleaseObjectParameterType { + /** + * Identifier of the object to release. + */ + objectId: RemoteObjectId; + } + interface ReleaseObjectGroupParameterType { + /** + * Symbolic object group name. + */ + objectGroup: string; + } + interface SetCustomObjectFormatterEnabledParameterType { + enabled: boolean; + } + interface CompileScriptParameterType { + /** + * Expression to compile. + */ + expression: string; + /** + * Source url to be set for the script. + */ + sourceURL: string; + /** + * Specifies whether the compiled script should be persisted. + */ + persistScript: boolean; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId | undefined; + } + interface RunScriptParameterType { + /** + * Id of the script to run. + */ + scriptId: ScriptId; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId | undefined; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + } + interface QueryObjectsParameterType { + /** + * Identifier of the prototype to return objects for. + */ + prototypeObjectId: RemoteObjectId; + } + interface GlobalLexicalScopeNamesParameterType { + /** + * Specifies in which execution context to lookup global scope variables. + */ + executionContextId?: ExecutionContextId | undefined; + } + interface EvaluateReturnType { + /** + * Evaluation result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface AwaitPromiseReturnType { + /** + * Promise result. Will contain rejected value if promise was rejected. + */ + result: RemoteObject; + /** + * Exception details if stack strace is available. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface CallFunctionOnReturnType { + /** + * Call result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface GetPropertiesReturnType { + /** + * Object properties. + */ + result: PropertyDescriptor[]; + /** + * Internal object properties (only of the element itself). + */ + internalProperties?: InternalPropertyDescriptor[] | undefined; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface CompileScriptReturnType { + /** + * Id of the script. + */ + scriptId?: ScriptId | undefined; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface RunScriptReturnType { + /** + * Run result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface QueryObjectsReturnType { + /** + * Array with objects. + */ + objects: RemoteObject; + } + interface GlobalLexicalScopeNamesReturnType { + names: string[]; + } + interface ExecutionContextCreatedEventDataType { + /** + * A newly created execution context. + */ + context: ExecutionContextDescription; + } + interface ExecutionContextDestroyedEventDataType { + /** + * Id of the destroyed context + */ + executionContextId: ExecutionContextId; + } + interface ExceptionThrownEventDataType { + /** + * Timestamp of the exception. + */ + timestamp: Timestamp; + exceptionDetails: ExceptionDetails; + } + interface ExceptionRevokedEventDataType { + /** + * Reason describing why exception was revoked. + */ + reason: string; + /** + * The id of revoked exception, as reported in exceptionThrown. + */ + exceptionId: number; + } + interface ConsoleAPICalledEventDataType { + /** + * Type of the call. + */ + type: string; + /** + * Call arguments. + */ + args: RemoteObject[]; + /** + * Identifier of the context where the call was made. + */ + executionContextId: ExecutionContextId; + /** + * Call timestamp. + */ + timestamp: Timestamp; + /** + * Stack trace captured when the call was made. + */ + stackTrace?: StackTrace | undefined; + /** + * Console context descriptor for calls on non-default console context (not console.*): 'anonymous#unique-logger-id' for call on unnamed context, 'name#unique-logger-id' for call on named context. + * @experimental + */ + context?: string | undefined; + } + interface InspectRequestedEventDataType { + object: RemoteObject; + hints: {}; + } + } + namespace Debugger { + /** + * Breakpoint identifier. + */ + type BreakpointId = string; + /** + * Call frame identifier. + */ + type CallFrameId = string; + /** + * Location in the source code. + */ + interface Location { + /** + * Script identifier as reported in the Debugger.scriptParsed. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number | undefined; + } + /** + * Location in the source code. + * @experimental + */ + interface ScriptPosition { + lineNumber: number; + columnNumber: number; + } + /** + * JavaScript call frame. Array of call frames form the call stack. + */ + interface CallFrame { + /** + * Call frame identifier. This identifier is only valid while the virtual machine is paused. + */ + callFrameId: CallFrameId; + /** + * Name of the JavaScript function called on this call frame. + */ + functionName: string; + /** + * Location in the source code. + */ + functionLocation?: Location | undefined; + /** + * Location in the source code. + */ + location: Location; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Scope chain for this call frame. + */ + scopeChain: Scope[]; + /** + * this object for this call frame. + */ + this: Runtime.RemoteObject; + /** + * The value being returned, if the function is at return point. + */ + returnValue?: Runtime.RemoteObject | undefined; + } + /** + * Scope description. + */ + interface Scope { + /** + * Scope type. + */ + type: string; + /** + * Object representing the scope. For global and with scopes it represents the actual object; for the rest of the scopes, it is artificial transient object enumerating scope variables as its properties. + */ + object: Runtime.RemoteObject; + name?: string | undefined; + /** + * Location in the source code where scope starts + */ + startLocation?: Location | undefined; + /** + * Location in the source code where scope ends + */ + endLocation?: Location | undefined; + } + /** + * Search match for resource. + */ + interface SearchMatch { + /** + * Line number in resource content. + */ + lineNumber: number; + /** + * Line with match content. + */ + lineContent: string; + } + interface BreakLocation { + /** + * Script identifier as reported in the Debugger.scriptParsed. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number | undefined; + type?: string | undefined; + } + interface SetBreakpointsActiveParameterType { + /** + * New value for breakpoints active state. + */ + active: boolean; + } + interface SetSkipAllPausesParameterType { + /** + * New value for skip pauses state. + */ + skip: boolean; + } + interface SetBreakpointByUrlParameterType { + /** + * Line number to set breakpoint at. + */ + lineNumber: number; + /** + * URL of the resources to set breakpoint on. + */ + url?: string | undefined; + /** + * Regex pattern for the URLs of the resources to set breakpoints on. Either url or urlRegex must be specified. + */ + urlRegex?: string | undefined; + /** + * Script hash of the resources to set breakpoint on. + */ + scriptHash?: string | undefined; + /** + * Offset in the line to set breakpoint at. + */ + columnNumber?: number | undefined; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. + */ + condition?: string | undefined; + } + interface SetBreakpointParameterType { + /** + * Location to set breakpoint in. + */ + location: Location; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. + */ + condition?: string | undefined; + } + interface RemoveBreakpointParameterType { + breakpointId: BreakpointId; + } + interface GetPossibleBreakpointsParameterType { + /** + * Start of range to search possible breakpoint locations in. + */ + start: Location; + /** + * End of range to search possible breakpoint locations in (excluding). When not specified, end of scripts is used as end of range. + */ + end?: Location | undefined; + /** + * Only consider locations which are in the same (non-nested) function as start. + */ + restrictToFunction?: boolean | undefined; + } + interface ContinueToLocationParameterType { + /** + * Location to continue to. + */ + location: Location; + targetCallFrames?: string | undefined; + } + interface PauseOnAsyncCallParameterType { + /** + * Debugger will pause when async call with given stack trace is started. + */ + parentStackTraceId: Runtime.StackTraceId; + } + interface StepIntoParameterType { + /** + * Debugger will issue additional Debugger.paused notification if any async task is scheduled before next pause. + * @experimental + */ + breakOnAsyncCall?: boolean | undefined; + } + interface GetStackTraceParameterType { + stackTraceId: Runtime.StackTraceId; + } + interface SearchInContentParameterType { + /** + * Id of the script to search in. + */ + scriptId: Runtime.ScriptId; + /** + * String to search for. + */ + query: string; + /** + * If true, search is case sensitive. + */ + caseSensitive?: boolean | undefined; + /** + * If true, treats string parameter as regex. + */ + isRegex?: boolean | undefined; + } + interface SetScriptSourceParameterType { + /** + * Id of the script to edit. + */ + scriptId: Runtime.ScriptId; + /** + * New content of the script. + */ + scriptSource: string; + /** + * If true the change will not actually be applied. Dry run may be used to get result description without actually modifying the code. + */ + dryRun?: boolean | undefined; + } + interface RestartFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + } + interface GetScriptSourceParameterType { + /** + * Id of the script to get source for. + */ + scriptId: Runtime.ScriptId; + } + interface SetPauseOnExceptionsParameterType { + /** + * Pause on exceptions mode. + */ + state: string; + } + interface EvaluateOnCallFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + /** + * Expression to evaluate. + */ + expression: string; + /** + * String object group name to put result into (allows rapid releasing resulting object handles using releaseObjectGroup). + */ + objectGroup?: string | undefined; + /** + * Specifies whether command line API should be available to the evaluated expression, defaults to false. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether to throw an exception if side effect cannot be ruled out during evaluation. + */ + throwOnSideEffect?: boolean | undefined; + } + interface SetVariableValueParameterType { + /** + * 0-based number of scope as was listed in scope chain. Only 'local', 'closure' and 'catch' scope types are allowed. Other scopes could be manipulated manually. + */ + scopeNumber: number; + /** + * Variable name. + */ + variableName: string; + /** + * New variable value. + */ + newValue: Runtime.CallArgument; + /** + * Id of callframe that holds variable. + */ + callFrameId: CallFrameId; + } + interface SetReturnValueParameterType { + /** + * New return value. + */ + newValue: Runtime.CallArgument; + } + interface SetAsyncCallStackDepthParameterType { + /** + * Maximum depth of async call stacks. Setting to 0 will effectively disable collecting async call stacks (default). + */ + maxDepth: number; + } + interface SetBlackboxPatternsParameterType { + /** + * Array of regexps that will be used to check script url for blackbox state. + */ + patterns: string[]; + } + interface SetBlackboxedRangesParameterType { + /** + * Id of the script. + */ + scriptId: Runtime.ScriptId; + positions: ScriptPosition[]; + } + interface EnableReturnType { + /** + * Unique identifier of the debugger. + * @experimental + */ + debuggerId: Runtime.UniqueDebuggerId; + } + interface SetBreakpointByUrlReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * List of the locations this breakpoint resolved into upon addition. + */ + locations: Location[]; + } + interface SetBreakpointReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * Location this breakpoint resolved into. + */ + actualLocation: Location; + } + interface GetPossibleBreakpointsReturnType { + /** + * List of the possible breakpoint locations. + */ + locations: BreakLocation[]; + } + interface GetStackTraceReturnType { + stackTrace: Runtime.StackTrace; + } + interface SearchInContentReturnType { + /** + * List of search matches. + */ + result: SearchMatch[]; + } + interface SetScriptSourceReturnType { + /** + * New stack trace in case editing has happened while VM was stopped. + */ + callFrames?: CallFrame[] | undefined; + /** + * Whether current call stack was modified after applying the changes. + */ + stackChanged?: boolean | undefined; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + /** + * Exception details if any. + */ + exceptionDetails?: Runtime.ExceptionDetails | undefined; + } + interface RestartFrameReturnType { + /** + * New stack trace. + */ + callFrames: CallFrame[]; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + } + interface GetScriptSourceReturnType { + /** + * Script source. + */ + scriptSource: string; + } + interface EvaluateOnCallFrameReturnType { + /** + * Object wrapper for the evaluation result. + */ + result: Runtime.RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: Runtime.ExceptionDetails | undefined; + } + interface ScriptParsedEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: {} | undefined; + /** + * True, if this script is generated as a result of the live edit operation. + * @experimental + */ + isLiveEdit?: boolean | undefined; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string | undefined; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean | undefined; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean | undefined; + /** + * This script length. + */ + length?: number | undefined; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace | undefined; + } + interface ScriptFailedToParseEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: {} | undefined; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string | undefined; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean | undefined; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean | undefined; + /** + * This script length. + */ + length?: number | undefined; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace | undefined; + } + interface BreakpointResolvedEventDataType { + /** + * Breakpoint unique identifier. + */ + breakpointId: BreakpointId; + /** + * Actual breakpoint location. + */ + location: Location; + } + interface PausedEventDataType { + /** + * Call stack the virtual machine stopped on. + */ + callFrames: CallFrame[]; + /** + * Pause reason. + */ + reason: string; + /** + * Object containing break-specific auxiliary properties. + */ + data?: {} | undefined; + /** + * Hit breakpoints IDs + */ + hitBreakpoints?: string[] | undefined; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + /** + * Just scheduled async call will have this stack trace as parent stack during async execution. This field is available only after Debugger.stepInto call with breakOnAsynCall flag. + * @experimental + */ + asyncCallStackTraceId?: Runtime.StackTraceId | undefined; + } + } + namespace Console { + /** + * Console message. + */ + interface ConsoleMessage { + /** + * Message source. + */ + source: string; + /** + * Message severity. + */ + level: string; + /** + * Message text. + */ + text: string; + /** + * URL of the message origin. + */ + url?: string | undefined; + /** + * Line number in the resource that generated this message (1-based). + */ + line?: number | undefined; + /** + * Column number in the resource that generated this message (1-based). + */ + column?: number | undefined; + } + interface MessageAddedEventDataType { + /** + * Console message that has been added. + */ + message: ConsoleMessage; + } + } + namespace Profiler { + /** + * Profile node. Holds callsite information, execution statistics and child nodes. + */ + interface ProfileNode { + /** + * Unique id of the node. + */ + id: number; + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Number of samples where this node was on top of the call stack. + */ + hitCount?: number | undefined; + /** + * Child node ids. + */ + children?: number[] | undefined; + /** + * The reason of being not optimized. The function may be deoptimized or marked as don't optimize. + */ + deoptReason?: string | undefined; + /** + * An array of source position ticks. + */ + positionTicks?: PositionTickInfo[] | undefined; + } + /** + * Profile. + */ + interface Profile { + /** + * The list of profile nodes. First item is the root node. + */ + nodes: ProfileNode[]; + /** + * Profiling start timestamp in microseconds. + */ + startTime: number; + /** + * Profiling end timestamp in microseconds. + */ + endTime: number; + /** + * Ids of samples top nodes. + */ + samples?: number[] | undefined; + /** + * Time intervals between adjacent samples in microseconds. The first delta is relative to the profile startTime. + */ + timeDeltas?: number[] | undefined; + } + /** + * Specifies a number of samples attributed to a certain source position. + */ + interface PositionTickInfo { + /** + * Source line number (1-based). + */ + line: number; + /** + * Number of samples attributed to the source line. + */ + ticks: number; + } + /** + * Coverage data for a source range. + */ + interface CoverageRange { + /** + * JavaScript script source offset for the range start. + */ + startOffset: number; + /** + * JavaScript script source offset for the range end. + */ + endOffset: number; + /** + * Collected execution count of the source range. + */ + count: number; + } + /** + * Coverage data for a JavaScript function. + */ + interface FunctionCoverage { + /** + * JavaScript function name. + */ + functionName: string; + /** + * Source ranges inside the function with coverage data. + */ + ranges: CoverageRange[]; + /** + * Whether coverage data for this function has block granularity. + */ + isBlockCoverage: boolean; + } + /** + * Coverage data for a JavaScript script. + */ + interface ScriptCoverage { + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Functions contained in the script that has coverage data. + */ + functions: FunctionCoverage[]; + } + interface SetSamplingIntervalParameterType { + /** + * New sampling interval in microseconds. + */ + interval: number; + } + interface StartPreciseCoverageParameterType { + /** + * Collect accurate call counts beyond simple 'covered' or 'not covered'. + */ + callCount?: boolean | undefined; + /** + * Collect block-based coverage. + */ + detailed?: boolean | undefined; + } + interface StopReturnType { + /** + * Recorded profile. + */ + profile: Profile; + } + interface TakePreciseCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + interface GetBestEffortCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + interface ConsoleProfileStartedEventDataType { + id: string; + /** + * Location of console.profile(). + */ + location: Debugger.Location; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string | undefined; + } + interface ConsoleProfileFinishedEventDataType { + id: string; + /** + * Location of console.profileEnd(). + */ + location: Debugger.Location; + profile: Profile; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string | undefined; + } + } + namespace HeapProfiler { + /** + * Heap snapshot object id. + */ + type HeapSnapshotObjectId = string; + /** + * Sampling Heap Profile node. Holds callsite information, allocation statistics and child nodes. + */ + interface SamplingHeapProfileNode { + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Allocations size in bytes for the node excluding children. + */ + selfSize: number; + /** + * Child nodes. + */ + children: SamplingHeapProfileNode[]; + } + /** + * Profile. + */ + interface SamplingHeapProfile { + head: SamplingHeapProfileNode; + } + interface StartTrackingHeapObjectsParameterType { + trackAllocations?: boolean | undefined; + } + interface StopTrackingHeapObjectsParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken when the tracking is stopped. + */ + reportProgress?: boolean | undefined; + } + interface TakeHeapSnapshotParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken. + */ + reportProgress?: boolean | undefined; + } + interface GetObjectByHeapObjectIdParameterType { + objectId: HeapSnapshotObjectId; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + } + interface AddInspectedHeapObjectParameterType { + /** + * Heap snapshot object id to be accessible by means of $x command line API. + */ + heapObjectId: HeapSnapshotObjectId; + } + interface GetHeapObjectIdParameterType { + /** + * Identifier of the object to get heap object id for. + */ + objectId: Runtime.RemoteObjectId; + } + interface StartSamplingParameterType { + /** + * Average sample interval in bytes. Poisson distribution is used for the intervals. The default value is 32768 bytes. + */ + samplingInterval?: number | undefined; + } + interface GetObjectByHeapObjectIdReturnType { + /** + * Evaluation result. + */ + result: Runtime.RemoteObject; + } + interface GetHeapObjectIdReturnType { + /** + * Id of the heap snapshot object corresponding to the passed remote object id. + */ + heapSnapshotObjectId: HeapSnapshotObjectId; + } + interface StopSamplingReturnType { + /** + * Recorded sampling heap profile. + */ + profile: SamplingHeapProfile; + } + interface GetSamplingProfileReturnType { + /** + * Return the sampling profile being collected. + */ + profile: SamplingHeapProfile; + } + interface AddHeapSnapshotChunkEventDataType { + chunk: string; + } + interface ReportHeapSnapshotProgressEventDataType { + done: number; + total: number; + finished?: boolean | undefined; + } + interface LastSeenObjectIdEventDataType { + lastSeenObjectId: number; + timestamp: number; + } + interface HeapStatsUpdateEventDataType { + /** + * An array of triplets. Each triplet describes a fragment. The first integer is the fragment index, the second integer is a total count of objects for the fragment, the third integer is a total size of the objects for the fragment. + */ + statsUpdate: number[]; + } + } + namespace NodeTracing { + interface TraceConfig { + /** + * Controls how the trace buffer stores data. + */ + recordMode?: string | undefined; + /** + * Included category filters. + */ + includedCategories: string[]; + } + interface StartParameterType { + traceConfig: TraceConfig; + } + interface GetCategoriesReturnType { + /** + * A list of supported tracing categories. + */ + categories: string[]; + } + interface DataCollectedEventDataType { + value: Array<{}>; + } + } + namespace NodeWorker { + type WorkerID = string; + /** + * Unique identifier of attached debugging session. + */ + type SessionID = string; + interface WorkerInfo { + workerId: WorkerID; + type: string; + title: string; + url: string; + } + interface SendMessageToWorkerParameterType { + message: string; + /** + * Identifier of the session. + */ + sessionId: SessionID; + } + interface EnableParameterType { + /** + * Whether to new workers should be paused until the frontend sends `Runtime.runIfWaitingForDebugger` + * message to run them. + */ + waitForDebuggerOnStart: boolean; + } + interface DetachParameterType { + sessionId: SessionID; + } + interface AttachedToWorkerEventDataType { + /** + * Identifier assigned to the session used to send/receive messages. + */ + sessionId: SessionID; + workerInfo: WorkerInfo; + waitingForDebugger: boolean; + } + interface DetachedFromWorkerEventDataType { + /** + * Detached session identifier. + */ + sessionId: SessionID; + } + interface ReceivedMessageFromWorkerEventDataType { + /** + * Identifier of a session which sends a message. + */ + sessionId: SessionID; + message: string; + } + } + namespace NodeRuntime { + interface NotifyWhenWaitingForDisconnectParameterType { + enabled: boolean; + } + } + + /** + * The `inspector.Session` is used for dispatching messages to the V8 inspector + * back-end and receiving message responses and notifications. + */ + class Session extends EventEmitter { + /** + * Create a new instance of the inspector.Session class. + * The inspector session needs to be connected through `session.connect()` before the messages can be dispatched to the inspector backend. + */ + constructor(); + + /** + * Connects a session to the inspector back-end. + */ + connect(): void; + + /** + * Connects a session to the inspector back-end. + * An exception will be thrown if this API was not called on a Worker thread. + * @since v12.11.0 + */ + connectToMainThread(): void; + + /** + * Immediately close the session. All pending message callbacks will be called with an error. + * `session.connect()` will need to be called to be able to send messages again. + * Reconnected session will lose all inspector state, such as enabled agents or configured breakpoints. + */ + disconnect(): void; + + /** + * Posts a message to the inspector back-end. `callback` will be notified when + * a response is received. `callback` is a function that accepts two optional + * arguments: error and message-specific result. + * + * ```js + * session.post('Runtime.evaluate', { expression: '2 + 2' }, + * (error, { result }) => console.log(result)); + * // Output: { type: 'number', value: 4, description: '4' } + * ``` + * + * The latest version of the V8 inspector protocol is published on the + * [Chrome DevTools Protocol Viewer](https://chromedevtools.github.io/devtools-protocol/v8/). + * + * Node.js inspector supports all the Chrome DevTools Protocol domains declared + * by V8. Chrome DevTools Protocol domain provides an interface for interacting + * with one of the runtime agents used to inspect the application state and listen + * to the run-time events. + */ + post(method: string, callback?: (err: Error | null, params?: object) => void): void; + post(method: string, params?: object, callback?: (err: Error | null, params?: object) => void): void; + /** + * Returns supported domains. + */ + post(method: 'Schema.getDomains', callback?: (err: Error | null, params: Schema.GetDomainsReturnType) => void): void; + /** + * Evaluates expression on global object. + */ + post(method: 'Runtime.evaluate', params?: Runtime.EvaluateParameterType, callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + post(method: 'Runtime.evaluate', callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + /** + * Add handler to promise with given promise object id. + */ + post(method: 'Runtime.awaitPromise', params?: Runtime.AwaitPromiseParameterType, callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + post(method: 'Runtime.awaitPromise', callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + /** + * Calls function with given declaration on the given object. Object group of the result is inherited from the target object. + */ + post(method: 'Runtime.callFunctionOn', params?: Runtime.CallFunctionOnParameterType, callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + post(method: 'Runtime.callFunctionOn', callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + /** + * Returns properties of a given object. Object group of the result is inherited from the target object. + */ + post(method: 'Runtime.getProperties', params?: Runtime.GetPropertiesParameterType, callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + post(method: 'Runtime.getProperties', callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + /** + * Releases remote object with given id. + */ + post(method: 'Runtime.releaseObject', params?: Runtime.ReleaseObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Runtime.releaseObject', callback?: (err: Error | null) => void): void; + /** + * Releases all remote objects that belong to a given group. + */ + post(method: 'Runtime.releaseObjectGroup', params?: Runtime.ReleaseObjectGroupParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Runtime.releaseObjectGroup', callback?: (err: Error | null) => void): void; + /** + * Tells inspected instance to run if it was waiting for debugger to attach. + */ + post(method: 'Runtime.runIfWaitingForDebugger', callback?: (err: Error | null) => void): void; + /** + * Enables reporting of execution contexts creation by means of executionContextCreated event. When the reporting gets enabled the event will be sent immediately for each existing execution context. + */ + post(method: 'Runtime.enable', callback?: (err: Error | null) => void): void; + /** + * Disables reporting of execution contexts creation. + */ + post(method: 'Runtime.disable', callback?: (err: Error | null) => void): void; + /** + * Discards collected exceptions and console API calls. + */ + post(method: 'Runtime.discardConsoleEntries', callback?: (err: Error | null) => void): void; + /** + * @experimental + */ + post(method: 'Runtime.setCustomObjectFormatterEnabled', params?: Runtime.SetCustomObjectFormatterEnabledParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Runtime.setCustomObjectFormatterEnabled', callback?: (err: Error | null) => void): void; + /** + * Compiles expression. + */ + post(method: 'Runtime.compileScript', params?: Runtime.CompileScriptParameterType, callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + post(method: 'Runtime.compileScript', callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + /** + * Runs script with given id in a given context. + */ + post(method: 'Runtime.runScript', params?: Runtime.RunScriptParameterType, callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + post(method: 'Runtime.runScript', callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + post(method: 'Runtime.queryObjects', params?: Runtime.QueryObjectsParameterType, callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + post(method: 'Runtime.queryObjects', callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + /** + * Returns all let, const and class variables from global scope. + */ + post( + method: 'Runtime.globalLexicalScopeNames', + params?: Runtime.GlobalLexicalScopeNamesParameterType, + callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void + ): void; + post(method: 'Runtime.globalLexicalScopeNames', callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void): void; + /** + * Enables debugger for the given page. Clients should not assume that the debugging has been enabled until the result for this command is received. + */ + post(method: 'Debugger.enable', callback?: (err: Error | null, params: Debugger.EnableReturnType) => void): void; + /** + * Disables debugger for given page. + */ + post(method: 'Debugger.disable', callback?: (err: Error | null) => void): void; + /** + * Activates / deactivates all breakpoints on the page. + */ + post(method: 'Debugger.setBreakpointsActive', params?: Debugger.SetBreakpointsActiveParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setBreakpointsActive', callback?: (err: Error | null) => void): void; + /** + * Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc). + */ + post(method: 'Debugger.setSkipAllPauses', params?: Debugger.SetSkipAllPausesParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setSkipAllPauses', callback?: (err: Error | null) => void): void; + /** + * Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this command is issued, all existing parsed scripts will have breakpoints resolved and returned in locations property. Further matching script parsing will result in subsequent breakpointResolved events issued. This logical breakpoint will survive page reloads. + */ + post(method: 'Debugger.setBreakpointByUrl', params?: Debugger.SetBreakpointByUrlParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + post(method: 'Debugger.setBreakpointByUrl', callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + /** + * Sets JavaScript breakpoint at a given location. + */ + post(method: 'Debugger.setBreakpoint', params?: Debugger.SetBreakpointParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + post(method: 'Debugger.setBreakpoint', callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + /** + * Removes JavaScript breakpoint. + */ + post(method: 'Debugger.removeBreakpoint', params?: Debugger.RemoveBreakpointParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.removeBreakpoint', callback?: (err: Error | null) => void): void; + /** + * Returns possible locations for breakpoint. scriptId in start and end range locations should be the same. + */ + post( + method: 'Debugger.getPossibleBreakpoints', + params?: Debugger.GetPossibleBreakpointsParameterType, + callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void + ): void; + post(method: 'Debugger.getPossibleBreakpoints', callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void): void; + /** + * Continues execution until specific location is reached. + */ + post(method: 'Debugger.continueToLocation', params?: Debugger.ContinueToLocationParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.continueToLocation', callback?: (err: Error | null) => void): void; + /** + * @experimental + */ + post(method: 'Debugger.pauseOnAsyncCall', params?: Debugger.PauseOnAsyncCallParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.pauseOnAsyncCall', callback?: (err: Error | null) => void): void; + /** + * Steps over the statement. + */ + post(method: 'Debugger.stepOver', callback?: (err: Error | null) => void): void; + /** + * Steps into the function call. + */ + post(method: 'Debugger.stepInto', params?: Debugger.StepIntoParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.stepInto', callback?: (err: Error | null) => void): void; + /** + * Steps out of the function call. + */ + post(method: 'Debugger.stepOut', callback?: (err: Error | null) => void): void; + /** + * Stops on the next JavaScript statement. + */ + post(method: 'Debugger.pause', callback?: (err: Error | null) => void): void; + /** + * This method is deprecated - use Debugger.stepInto with breakOnAsyncCall and Debugger.pauseOnAsyncTask instead. Steps into next scheduled async task if any is scheduled before next pause. Returns success when async task is actually scheduled, returns error if no task were scheduled or another scheduleStepIntoAsync was called. + * @experimental + */ + post(method: 'Debugger.scheduleStepIntoAsync', callback?: (err: Error | null) => void): void; + /** + * Resumes JavaScript execution. + */ + post(method: 'Debugger.resume', callback?: (err: Error | null) => void): void; + /** + * Returns stack trace with given stackTraceId. + * @experimental + */ + post(method: 'Debugger.getStackTrace', params?: Debugger.GetStackTraceParameterType, callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + post(method: 'Debugger.getStackTrace', callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + /** + * Searches for given string in script content. + */ + post(method: 'Debugger.searchInContent', params?: Debugger.SearchInContentParameterType, callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + post(method: 'Debugger.searchInContent', callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + /** + * Edits JavaScript source live. + */ + post(method: 'Debugger.setScriptSource', params?: Debugger.SetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + post(method: 'Debugger.setScriptSource', callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + /** + * Restarts particular call frame from the beginning. + */ + post(method: 'Debugger.restartFrame', params?: Debugger.RestartFrameParameterType, callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + post(method: 'Debugger.restartFrame', callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + /** + * Returns source for the script with given id. + */ + post(method: 'Debugger.getScriptSource', params?: Debugger.GetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + post(method: 'Debugger.getScriptSource', callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + /** + * Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or no exceptions. Initial pause on exceptions state is none. + */ + post(method: 'Debugger.setPauseOnExceptions', params?: Debugger.SetPauseOnExceptionsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setPauseOnExceptions', callback?: (err: Error | null) => void): void; + /** + * Evaluates expression on a given call frame. + */ + post(method: 'Debugger.evaluateOnCallFrame', params?: Debugger.EvaluateOnCallFrameParameterType, callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + post(method: 'Debugger.evaluateOnCallFrame', callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + /** + * Changes value of variable in a callframe. Object-based scopes are not supported and must be mutated manually. + */ + post(method: 'Debugger.setVariableValue', params?: Debugger.SetVariableValueParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setVariableValue', callback?: (err: Error | null) => void): void; + /** + * Changes return value in top frame. Available only at return break position. + * @experimental + */ + post(method: 'Debugger.setReturnValue', params?: Debugger.SetReturnValueParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setReturnValue', callback?: (err: Error | null) => void): void; + /** + * Enables or disables async call stacks tracking. + */ + post(method: 'Debugger.setAsyncCallStackDepth', params?: Debugger.SetAsyncCallStackDepthParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setAsyncCallStackDepth', callback?: (err: Error | null) => void): void; + /** + * Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in scripts with url matching one of the patterns. VM will try to leave blackboxed script by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. + * @experimental + */ + post(method: 'Debugger.setBlackboxPatterns', params?: Debugger.SetBlackboxPatternsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setBlackboxPatterns', callback?: (err: Error | null) => void): void; + /** + * Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. Positions array contains positions where blackbox state is changed. First interval isn't blackboxed. Array should be sorted. + * @experimental + */ + post(method: 'Debugger.setBlackboxedRanges', params?: Debugger.SetBlackboxedRangesParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setBlackboxedRanges', callback?: (err: Error | null) => void): void; + /** + * Enables console domain, sends the messages collected so far to the client by means of the messageAdded notification. + */ + post(method: 'Console.enable', callback?: (err: Error | null) => void): void; + /** + * Disables console domain, prevents further console messages from being reported to the client. + */ + post(method: 'Console.disable', callback?: (err: Error | null) => void): void; + /** + * Does nothing. + */ + post(method: 'Console.clearMessages', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.enable', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.disable', callback?: (err: Error | null) => void): void; + /** + * Changes CPU profiler sampling interval. Must be called before CPU profiles recording started. + */ + post(method: 'Profiler.setSamplingInterval', params?: Profiler.SetSamplingIntervalParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Profiler.setSamplingInterval', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.start', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.stop', callback?: (err: Error | null, params: Profiler.StopReturnType) => void): void; + /** + * Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code coverage may be incomplete. Enabling prevents running optimized code and resets execution counters. + */ + post(method: 'Profiler.startPreciseCoverage', params?: Profiler.StartPreciseCoverageParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Profiler.startPreciseCoverage', callback?: (err: Error | null) => void): void; + /** + * Disable precise code coverage. Disabling releases unnecessary execution count records and allows executing optimized code. + */ + post(method: 'Profiler.stopPreciseCoverage', callback?: (err: Error | null) => void): void; + /** + * Collect coverage data for the current isolate, and resets execution counters. Precise code coverage needs to have started. + */ + post(method: 'Profiler.takePreciseCoverage', callback?: (err: Error | null, params: Profiler.TakePreciseCoverageReturnType) => void): void; + /** + * Collect coverage data for the current isolate. The coverage data may be incomplete due to garbage collection. + */ + post(method: 'Profiler.getBestEffortCoverage', callback?: (err: Error | null, params: Profiler.GetBestEffortCoverageReturnType) => void): void; + post(method: 'HeapProfiler.enable', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.disable', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.startTrackingHeapObjects', params?: HeapProfiler.StartTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.startTrackingHeapObjects', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.stopTrackingHeapObjects', params?: HeapProfiler.StopTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.stopTrackingHeapObjects', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.takeHeapSnapshot', params?: HeapProfiler.TakeHeapSnapshotParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.takeHeapSnapshot', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.collectGarbage', callback?: (err: Error | null) => void): void; + post( + method: 'HeapProfiler.getObjectByHeapObjectId', + params?: HeapProfiler.GetObjectByHeapObjectIdParameterType, + callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void + ): void; + post(method: 'HeapProfiler.getObjectByHeapObjectId', callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void): void; + /** + * Enables console to refer to the node with given id via $x (see Command Line API for more details $x functions). + */ + post(method: 'HeapProfiler.addInspectedHeapObject', params?: HeapProfiler.AddInspectedHeapObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.addInspectedHeapObject', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.getHeapObjectId', params?: HeapProfiler.GetHeapObjectIdParameterType, callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + post(method: 'HeapProfiler.getHeapObjectId', callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + post(method: 'HeapProfiler.startSampling', params?: HeapProfiler.StartSamplingParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.startSampling', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.stopSampling', callback?: (err: Error | null, params: HeapProfiler.StopSamplingReturnType) => void): void; + post(method: 'HeapProfiler.getSamplingProfile', callback?: (err: Error | null, params: HeapProfiler.GetSamplingProfileReturnType) => void): void; + /** + * Gets supported tracing categories. + */ + post(method: 'NodeTracing.getCategories', callback?: (err: Error | null, params: NodeTracing.GetCategoriesReturnType) => void): void; + /** + * Start trace events collection. + */ + post(method: 'NodeTracing.start', params?: NodeTracing.StartParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeTracing.start', callback?: (err: Error | null) => void): void; + /** + * Stop trace events collection. Remaining collected events will be sent as a sequence of + * dataCollected events followed by tracingComplete event. + */ + post(method: 'NodeTracing.stop', callback?: (err: Error | null) => void): void; + /** + * Sends protocol message over session with given id. + */ + post(method: 'NodeWorker.sendMessageToWorker', params?: NodeWorker.SendMessageToWorkerParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeWorker.sendMessageToWorker', callback?: (err: Error | null) => void): void; + /** + * Instructs the inspector to attach to running workers. Will also attach to new workers + * as they start + */ + post(method: 'NodeWorker.enable', params?: NodeWorker.EnableParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeWorker.enable', callback?: (err: Error | null) => void): void; + /** + * Detaches from all running workers and disables attaching to new workers as they are started. + */ + post(method: 'NodeWorker.disable', callback?: (err: Error | null) => void): void; + /** + * Detached from the worker with given sessionId. + */ + post(method: 'NodeWorker.detach', params?: NodeWorker.DetachParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeWorker.detach', callback?: (err: Error | null) => void): void; + /** + * Enable the NodeRuntime events except by `NodeRuntime.waitingForDisconnect`. + */ + post(method: 'NodeRuntime.enable', callback?: (err: Error | null) => void): void; + /** + * Disable NodeRuntime events + */ + post(method: 'NodeRuntime.disable', callback?: (err: Error | null) => void): void; + /** + * Enable the `NodeRuntime.waitingForDisconnect`. + */ + post(method: 'NodeRuntime.notifyWhenWaitingForDisconnect', params?: NodeRuntime.NotifyWhenWaitingForDisconnectParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeRuntime.notifyWhenWaitingForDisconnect', callback?: (err: Error | null) => void): void; + + addListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + addListener(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + addListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + addListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + addListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + addListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + addListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + addListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + addListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + addListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + addListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + addListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + addListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + addListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + addListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + addListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + addListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + addListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + addListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + addListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + addListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + addListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + addListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + addListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + addListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + addListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + addListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + addListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + addListener(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'inspectorNotification', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextCreated', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextDestroyed', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextsCleared'): boolean; + emit(event: 'Runtime.exceptionThrown', message: InspectorNotification): boolean; + emit(event: 'Runtime.exceptionRevoked', message: InspectorNotification): boolean; + emit(event: 'Runtime.consoleAPICalled', message: InspectorNotification): boolean; + emit(event: 'Runtime.inspectRequested', message: InspectorNotification): boolean; + emit(event: 'Debugger.scriptParsed', message: InspectorNotification): boolean; + emit(event: 'Debugger.scriptFailedToParse', message: InspectorNotification): boolean; + emit(event: 'Debugger.breakpointResolved', message: InspectorNotification): boolean; + emit(event: 'Debugger.paused', message: InspectorNotification): boolean; + emit(event: 'Debugger.resumed'): boolean; + emit(event: 'Console.messageAdded', message: InspectorNotification): boolean; + emit(event: 'Profiler.consoleProfileStarted', message: InspectorNotification): boolean; + emit(event: 'Profiler.consoleProfileFinished', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.addHeapSnapshotChunk', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.resetProfiles'): boolean; + emit(event: 'HeapProfiler.reportHeapSnapshotProgress', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.lastSeenObjectId', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.heapStatsUpdate', message: InspectorNotification): boolean; + emit(event: 'NodeTracing.dataCollected', message: InspectorNotification): boolean; + emit(event: 'NodeTracing.tracingComplete'): boolean; + emit(event: 'NodeWorker.attachedToWorker', message: InspectorNotification): boolean; + emit(event: 'NodeWorker.detachedFromWorker', message: InspectorNotification): boolean; + emit(event: 'NodeWorker.receivedMessageFromWorker', message: InspectorNotification): boolean; + emit(event: 'NodeRuntime.waitingForDisconnect'): boolean; + emit(event: 'NodeRuntime.waitingForDebugger'): boolean; + on(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + on(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + on(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + on(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + on(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + on(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + on(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + on(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + on(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + on(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + on(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + on(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + on(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + on(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + on(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + on(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + on(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + on(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + on(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + on(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + on(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + on(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + on(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + on(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + on(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + on(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + on(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + on(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + on(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + once(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + once(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + once(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + once(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + once(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + once(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + once(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + once(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + once(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + once(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + once(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + once(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + once(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + once(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + once(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + once(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + once(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + once(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + once(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + once(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + once(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + once(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + once(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + once(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + once(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + once(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + once(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + once(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependListener(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + prependListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + prependListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + prependListener(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependOnceListener(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + prependOnceListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependOnceListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependOnceListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependOnceListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependOnceListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependOnceListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependOnceListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependOnceListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependOnceListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependOnceListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependOnceListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependOnceListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependOnceListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependOnceListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + prependOnceListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependOnceListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependOnceListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependOnceListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependOnceListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependOnceListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependOnceListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependOnceListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependOnceListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + prependOnceListener(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + } + + /** + * Activate inspector on host and port. Equivalent to `node --inspect=[[host:]port]`, but can be done programmatically after node has + * started. + * + * If wait is `true`, will block until a client has connected to the inspect port + * and flow control has been passed to the debugger client. + * + * See the [security warning](https://nodejs.org/docs/latest-v22.x/api/cli.html#warning-binding-inspector-to-a-public-ipport-combination-is-insecure) + * regarding the `host` parameter usage. + * @param port Port to listen on for inspector connections. Defaults to what was specified on the CLI. + * @param host Host to listen on for inspector connections. Defaults to what was specified on the CLI. + * @param wait Block until a client has connected. Defaults to what was specified on the CLI. + * @returns Disposable that calls `inspector.close()`. + */ + function open(port?: number, host?: string, wait?: boolean): Disposable; + + /** + * Deactivate the inspector. Blocks until there are no active connections. + */ + function close(): void; + + /** + * Return the URL of the active inspector, or `undefined` if there is none. + * + * ```console + * $ node --inspect -p 'inspector.url()' + * Debugger listening on ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 + * For help, see: https://nodejs.org/en/docs/inspector + * ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 + * + * $ node --inspect=localhost:3000 -p 'inspector.url()' + * Debugger listening on ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a + * For help, see: https://nodejs.org/en/docs/inspector + * ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a + * + * $ node -p 'inspector.url()' + * undefined + * ``` + */ + function url(): string | undefined; + + /** + * Blocks until a client (existing or connected later) has sent `Runtime.runIfWaitingForDebugger` command. + * + * An exception will be thrown if there is no active inspector. + * @since v12.7.0 + */ + function waitForDebugger(): void; + + // These methods are exposed by the V8 inspector console API (inspector/v8-console.h). + // The method signatures differ from those of the Node.js console, and are deliberately + // typed permissively. + interface InspectorConsole { + debug(...data: any[]): void; + error(...data: any[]): void; + info(...data: any[]): void; + log(...data: any[]): void; + warn(...data: any[]): void; + dir(...data: any[]): void; + dirxml(...data: any[]): void; + table(...data: any[]): void; + trace(...data: any[]): void; + group(...data: any[]): void; + groupCollapsed(...data: any[]): void; + groupEnd(...data: any[]): void; + clear(...data: any[]): void; + count(label?: any): void; + countReset(label?: any): void; + assert(value?: any, ...data: any[]): void; + profile(label?: any): void; + profileEnd(label?: any): void; + time(label?: any): void; + timeLog(label?: any): void; + timeStamp(label?: any): void; + } + + /** + * An object to send messages to the remote inspector console. + * @since v11.0.0 + */ + const console: InspectorConsole; +} + +/** + * The `node:inspector` module provides an API for interacting with the V8 + * inspector. + */ +declare module 'node:inspector' { + export * from 'inspector'; +} + +/** + * The `node:inspector/promises` module provides an API for interacting with the V8 + * inspector. + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/inspector/promises.js) + * @since v19.0.0 + */ +declare module 'inspector/promises' { + import EventEmitter = require('node:events'); + import { + open, + close, + url, + waitForDebugger, + console, + InspectorNotification, + Schema, + Runtime, + Debugger, + Console, + Profiler, + HeapProfiler, + NodeTracing, + NodeWorker, + NodeRuntime, + } from 'inspector'; + + /** + * The `inspector.Session` is used for dispatching messages to the V8 inspector + * back-end and receiving message responses and notifications. + * @since v19.0.0 + */ + class Session extends EventEmitter { + /** + * Create a new instance of the `inspector.Session` class. + * The inspector session needs to be connected through `session.connect()` before the messages can be dispatched to the inspector backend. + */ + constructor(); + + /** + * Connects a session to the inspector back-end. + */ + connect(): void; + + /** + * Connects a session to the inspector back-end. + * An exception will be thrown if this API was not called on a Worker thread. + */ + connectToMainThread(): void; + + /** + * Immediately close the session. All pending message callbacks will be called with an error. + * `session.connect()` will need to be called to be able to send messages again. + * Reconnected session will lose all inspector state, such as enabled agents or configured breakpoints. + */ + disconnect(): void; + + /** + * Posts a message to the inspector back-end. + * + * ```js + * import { Session } from 'node:inspector/promises'; + * try { + * const session = new Session(); + * session.connect(); + * const result = await session.post('Runtime.evaluate', { expression: '2 + 2' }); + * console.log(result); + * } catch (error) { + * console.error(error); + * } + * // Output: { result: { type: 'number', value: 4, description: '4' } } + * ``` + * + * The latest version of the V8 inspector protocol is published on the + * [Chrome DevTools Protocol Viewer](https://chromedevtools.github.io/devtools-protocol/v8/). + * + * Node.js inspector supports all the Chrome DevTools Protocol domains declared + * by V8. Chrome DevTools Protocol domain provides an interface for interacting + * with one of the runtime agents used to inspect the application state and listen + * to the run-time events. + */ + post(method: string, params?: object): Promise; + /** + * Returns supported domains. + */ + post(method: 'Schema.getDomains'): Promise; + /** + * Evaluates expression on global object. + */ + post(method: 'Runtime.evaluate', params?: Runtime.EvaluateParameterType): Promise; + /** + * Add handler to promise with given promise object id. + */ + post(method: 'Runtime.awaitPromise', params?: Runtime.AwaitPromiseParameterType): Promise; + /** + * Calls function with given declaration on the given object. Object group of the result is inherited from the target object. + */ + post(method: 'Runtime.callFunctionOn', params?: Runtime.CallFunctionOnParameterType): Promise; + /** + * Returns properties of a given object. Object group of the result is inherited from the target object. + */ + post(method: 'Runtime.getProperties', params?: Runtime.GetPropertiesParameterType): Promise; + /** + * Releases remote object with given id. + */ + post(method: 'Runtime.releaseObject', params?: Runtime.ReleaseObjectParameterType): Promise; + /** + * Releases all remote objects that belong to a given group. + */ + post(method: 'Runtime.releaseObjectGroup', params?: Runtime.ReleaseObjectGroupParameterType): Promise; + /** + * Tells inspected instance to run if it was waiting for debugger to attach. + */ + post(method: 'Runtime.runIfWaitingForDebugger'): Promise; + /** + * Enables reporting of execution contexts creation by means of executionContextCreated event. When the reporting gets enabled the event will be sent immediately for each existing execution context. + */ + post(method: 'Runtime.enable'): Promise; + /** + * Disables reporting of execution contexts creation. + */ + post(method: 'Runtime.disable'): Promise; + /** + * Discards collected exceptions and console API calls. + */ + post(method: 'Runtime.discardConsoleEntries'): Promise; + /** + * @experimental + */ + post(method: 'Runtime.setCustomObjectFormatterEnabled', params?: Runtime.SetCustomObjectFormatterEnabledParameterType): Promise; + /** + * Compiles expression. + */ + post(method: 'Runtime.compileScript', params?: Runtime.CompileScriptParameterType): Promise; + /** + * Runs script with given id in a given context. + */ + post(method: 'Runtime.runScript', params?: Runtime.RunScriptParameterType): Promise; + post(method: 'Runtime.queryObjects', params?: Runtime.QueryObjectsParameterType): Promise; + /** + * Returns all let, const and class variables from global scope. + */ + post(method: 'Runtime.globalLexicalScopeNames', params?: Runtime.GlobalLexicalScopeNamesParameterType): Promise; + /** + * Enables debugger for the given page. Clients should not assume that the debugging has been enabled until the result for this command is received. + */ + post(method: 'Debugger.enable'): Promise; + /** + * Disables debugger for given page. + */ + post(method: 'Debugger.disable'): Promise; + /** + * Activates / deactivates all breakpoints on the page. + */ + post(method: 'Debugger.setBreakpointsActive', params?: Debugger.SetBreakpointsActiveParameterType): Promise; + /** + * Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc). + */ + post(method: 'Debugger.setSkipAllPauses', params?: Debugger.SetSkipAllPausesParameterType): Promise; + /** + * Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this command is issued, all existing parsed scripts will have breakpoints resolved and returned in locations property. Further matching script parsing will result in subsequent breakpointResolved events issued. This logical breakpoint will survive page reloads. + */ + post(method: 'Debugger.setBreakpointByUrl', params?: Debugger.SetBreakpointByUrlParameterType): Promise; + /** + * Sets JavaScript breakpoint at a given location. + */ + post(method: 'Debugger.setBreakpoint', params?: Debugger.SetBreakpointParameterType): Promise; + /** + * Removes JavaScript breakpoint. + */ + post(method: 'Debugger.removeBreakpoint', params?: Debugger.RemoveBreakpointParameterType): Promise; + /** + * Returns possible locations for breakpoint. scriptId in start and end range locations should be the same. + */ + post(method: 'Debugger.getPossibleBreakpoints', params?: Debugger.GetPossibleBreakpointsParameterType): Promise; + /** + * Continues execution until specific location is reached. + */ + post(method: 'Debugger.continueToLocation', params?: Debugger.ContinueToLocationParameterType): Promise; + /** + * @experimental + */ + post(method: 'Debugger.pauseOnAsyncCall', params?: Debugger.PauseOnAsyncCallParameterType): Promise; + /** + * Steps over the statement. + */ + post(method: 'Debugger.stepOver'): Promise; + /** + * Steps into the function call. + */ + post(method: 'Debugger.stepInto', params?: Debugger.StepIntoParameterType): Promise; + /** + * Steps out of the function call. + */ + post(method: 'Debugger.stepOut'): Promise; + /** + * Stops on the next JavaScript statement. + */ + post(method: 'Debugger.pause'): Promise; + /** + * This method is deprecated - use Debugger.stepInto with breakOnAsyncCall and Debugger.pauseOnAsyncTask instead. Steps into next scheduled async task if any is scheduled before next pause. Returns success when async task is actually scheduled, returns error if no task were scheduled or another scheduleStepIntoAsync was called. + * @experimental + */ + post(method: 'Debugger.scheduleStepIntoAsync'): Promise; + /** + * Resumes JavaScript execution. + */ + post(method: 'Debugger.resume'): Promise; + /** + * Returns stack trace with given stackTraceId. + * @experimental + */ + post(method: 'Debugger.getStackTrace', params?: Debugger.GetStackTraceParameterType): Promise; + /** + * Searches for given string in script content. + */ + post(method: 'Debugger.searchInContent', params?: Debugger.SearchInContentParameterType): Promise; + /** + * Edits JavaScript source live. + */ + post(method: 'Debugger.setScriptSource', params?: Debugger.SetScriptSourceParameterType): Promise; + /** + * Restarts particular call frame from the beginning. + */ + post(method: 'Debugger.restartFrame', params?: Debugger.RestartFrameParameterType): Promise; + /** + * Returns source for the script with given id. + */ + post(method: 'Debugger.getScriptSource', params?: Debugger.GetScriptSourceParameterType): Promise; + /** + * Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or no exceptions. Initial pause on exceptions state is none. + */ + post(method: 'Debugger.setPauseOnExceptions', params?: Debugger.SetPauseOnExceptionsParameterType): Promise; + /** + * Evaluates expression on a given call frame. + */ + post(method: 'Debugger.evaluateOnCallFrame', params?: Debugger.EvaluateOnCallFrameParameterType): Promise; + /** + * Changes value of variable in a callframe. Object-based scopes are not supported and must be mutated manually. + */ + post(method: 'Debugger.setVariableValue', params?: Debugger.SetVariableValueParameterType): Promise; + /** + * Changes return value in top frame. Available only at return break position. + * @experimental + */ + post(method: 'Debugger.setReturnValue', params?: Debugger.SetReturnValueParameterType): Promise; + /** + * Enables or disables async call stacks tracking. + */ + post(method: 'Debugger.setAsyncCallStackDepth', params?: Debugger.SetAsyncCallStackDepthParameterType): Promise; + /** + * Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in scripts with url matching one of the patterns. VM will try to leave blackboxed script by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. + * @experimental + */ + post(method: 'Debugger.setBlackboxPatterns', params?: Debugger.SetBlackboxPatternsParameterType): Promise; + /** + * Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. Positions array contains positions where blackbox state is changed. First interval isn't blackboxed. Array should be sorted. + * @experimental + */ + post(method: 'Debugger.setBlackboxedRanges', params?: Debugger.SetBlackboxedRangesParameterType): Promise; + /** + * Enables console domain, sends the messages collected so far to the client by means of the messageAdded notification. + */ + post(method: 'Console.enable'): Promise; + /** + * Disables console domain, prevents further console messages from being reported to the client. + */ + post(method: 'Console.disable'): Promise; + /** + * Does nothing. + */ + post(method: 'Console.clearMessages'): Promise; + post(method: 'Profiler.enable'): Promise; + post(method: 'Profiler.disable'): Promise; + /** + * Changes CPU profiler sampling interval. Must be called before CPU profiles recording started. + */ + post(method: 'Profiler.setSamplingInterval', params?: Profiler.SetSamplingIntervalParameterType): Promise; + post(method: 'Profiler.start'): Promise; + post(method: 'Profiler.stop'): Promise; + /** + * Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code coverage may be incomplete. Enabling prevents running optimized code and resets execution counters. + */ + post(method: 'Profiler.startPreciseCoverage', params?: Profiler.StartPreciseCoverageParameterType): Promise; + /** + * Disable precise code coverage. Disabling releases unnecessary execution count records and allows executing optimized code. + */ + post(method: 'Profiler.stopPreciseCoverage'): Promise; + /** + * Collect coverage data for the current isolate, and resets execution counters. Precise code coverage needs to have started. + */ + post(method: 'Profiler.takePreciseCoverage'): Promise; + /** + * Collect coverage data for the current isolate. The coverage data may be incomplete due to garbage collection. + */ + post(method: 'Profiler.getBestEffortCoverage'): Promise; + post(method: 'HeapProfiler.enable'): Promise; + post(method: 'HeapProfiler.disable'): Promise; + post(method: 'HeapProfiler.startTrackingHeapObjects', params?: HeapProfiler.StartTrackingHeapObjectsParameterType): Promise; + post(method: 'HeapProfiler.stopTrackingHeapObjects', params?: HeapProfiler.StopTrackingHeapObjectsParameterType): Promise; + post(method: 'HeapProfiler.takeHeapSnapshot', params?: HeapProfiler.TakeHeapSnapshotParameterType): Promise; + post(method: 'HeapProfiler.collectGarbage'): Promise; + post(method: 'HeapProfiler.getObjectByHeapObjectId', params?: HeapProfiler.GetObjectByHeapObjectIdParameterType): Promise; + /** + * Enables console to refer to the node with given id via $x (see Command Line API for more details $x functions). + */ + post(method: 'HeapProfiler.addInspectedHeapObject', params?: HeapProfiler.AddInspectedHeapObjectParameterType): Promise; + post(method: 'HeapProfiler.getHeapObjectId', params?: HeapProfiler.GetHeapObjectIdParameterType): Promise; + post(method: 'HeapProfiler.startSampling', params?: HeapProfiler.StartSamplingParameterType): Promise; + post(method: 'HeapProfiler.stopSampling'): Promise; + post(method: 'HeapProfiler.getSamplingProfile'): Promise; + /** + * Gets supported tracing categories. + */ + post(method: 'NodeTracing.getCategories'): Promise; + /** + * Start trace events collection. + */ + post(method: 'NodeTracing.start', params?: NodeTracing.StartParameterType): Promise; + /** + * Stop trace events collection. Remaining collected events will be sent as a sequence of + * dataCollected events followed by tracingComplete event. + */ + post(method: 'NodeTracing.stop'): Promise; + /** + * Sends protocol message over session with given id. + */ + post(method: 'NodeWorker.sendMessageToWorker', params?: NodeWorker.SendMessageToWorkerParameterType): Promise; + /** + * Instructs the inspector to attach to running workers. Will also attach to new workers + * as they start + */ + post(method: 'NodeWorker.enable', params?: NodeWorker.EnableParameterType): Promise; + /** + * Detaches from all running workers and disables attaching to new workers as they are started. + */ + post(method: 'NodeWorker.disable'): Promise; + /** + * Detached from the worker with given sessionId. + */ + post(method: 'NodeWorker.detach', params?: NodeWorker.DetachParameterType): Promise; + /** + * Enable the NodeRuntime events except by `NodeRuntime.waitingForDisconnect`. + */ + post(method: 'NodeRuntime.enable'): Promise; + /** + * Disable NodeRuntime events + */ + post(method: 'NodeRuntime.disable'): Promise; + /** + * Enable the `NodeRuntime.waitingForDisconnect`. + */ + post(method: 'NodeRuntime.notifyWhenWaitingForDisconnect', params?: NodeRuntime.NotifyWhenWaitingForDisconnectParameterType): Promise; + + addListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + addListener(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + addListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + addListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + addListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + addListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + addListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + addListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + addListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + addListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + addListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + addListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + addListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + addListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + addListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + addListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + addListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + addListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + addListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + addListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + addListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + addListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + addListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + addListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + addListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + addListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + addListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + addListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + addListener(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'inspectorNotification', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextCreated', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextDestroyed', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextsCleared'): boolean; + emit(event: 'Runtime.exceptionThrown', message: InspectorNotification): boolean; + emit(event: 'Runtime.exceptionRevoked', message: InspectorNotification): boolean; + emit(event: 'Runtime.consoleAPICalled', message: InspectorNotification): boolean; + emit(event: 'Runtime.inspectRequested', message: InspectorNotification): boolean; + emit(event: 'Debugger.scriptParsed', message: InspectorNotification): boolean; + emit(event: 'Debugger.scriptFailedToParse', message: InspectorNotification): boolean; + emit(event: 'Debugger.breakpointResolved', message: InspectorNotification): boolean; + emit(event: 'Debugger.paused', message: InspectorNotification): boolean; + emit(event: 'Debugger.resumed'): boolean; + emit(event: 'Console.messageAdded', message: InspectorNotification): boolean; + emit(event: 'Profiler.consoleProfileStarted', message: InspectorNotification): boolean; + emit(event: 'Profiler.consoleProfileFinished', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.addHeapSnapshotChunk', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.resetProfiles'): boolean; + emit(event: 'HeapProfiler.reportHeapSnapshotProgress', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.lastSeenObjectId', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.heapStatsUpdate', message: InspectorNotification): boolean; + emit(event: 'NodeTracing.dataCollected', message: InspectorNotification): boolean; + emit(event: 'NodeTracing.tracingComplete'): boolean; + emit(event: 'NodeWorker.attachedToWorker', message: InspectorNotification): boolean; + emit(event: 'NodeWorker.detachedFromWorker', message: InspectorNotification): boolean; + emit(event: 'NodeWorker.receivedMessageFromWorker', message: InspectorNotification): boolean; + emit(event: 'NodeRuntime.waitingForDisconnect'): boolean; + emit(event: 'NodeRuntime.waitingForDebugger'): boolean; + on(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + on(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + on(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + on(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + on(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + on(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + on(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + on(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + on(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + on(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + on(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + on(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + on(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + on(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + on(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + on(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + on(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + on(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + on(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + on(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + on(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + on(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + on(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + on(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + on(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + on(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + on(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + on(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + on(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + once(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + once(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + once(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + once(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + once(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + once(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + once(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + once(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + once(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + once(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + once(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + once(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + once(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + once(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + once(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + once(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + once(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + once(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + once(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + once(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + once(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + once(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + once(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + once(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + once(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + once(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + once(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + once(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependListener(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + prependListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + prependListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + prependListener(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependOnceListener(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + prependOnceListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependOnceListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependOnceListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependOnceListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependOnceListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependOnceListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependOnceListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependOnceListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependOnceListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependOnceListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependOnceListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependOnceListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependOnceListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependOnceListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + prependOnceListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependOnceListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependOnceListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependOnceListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependOnceListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependOnceListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependOnceListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependOnceListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependOnceListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + prependOnceListener(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + } + + export { + Session, + open, + close, + url, + waitForDebugger, + console, + InspectorNotification, + Schema, + Runtime, + Debugger, + Console, + Profiler, + HeapProfiler, + NodeTracing, + NodeWorker, + NodeRuntime, + }; +} + +/** + * The `node:inspector/promises` module provides an API for interacting with the V8 + * inspector. + * @since v19.0.0 + */ +declare module 'node:inspector/promises' { + export * from 'inspector/promises'; +} diff --git a/libcore/node_modules/@types/node/module.d.ts b/libcore/node_modules/@types/node/module.d.ts new file mode 100644 index 0000000..0d60bb1 --- /dev/null +++ b/libcore/node_modules/@types/node/module.d.ts @@ -0,0 +1,301 @@ +/** + * @since v0.3.7 + * @experimental + */ +declare module "module" { + import { URL } from "node:url"; + import { MessagePort } from "node:worker_threads"; + namespace Module { + /** + * The `module.syncBuiltinESMExports()` method updates all the live bindings for + * builtin `ES Modules` to match the properties of the `CommonJS` exports. It + * does not add or remove exported names from the `ES Modules`. + * + * ```js + * const fs = require('node:fs'); + * const assert = require('node:assert'); + * const { syncBuiltinESMExports } = require('node:module'); + * + * fs.readFile = newAPI; + * + * delete fs.readFileSync; + * + * function newAPI() { + * // ... + * } + * + * fs.newAPI = newAPI; + * + * syncBuiltinESMExports(); + * + * import('node:fs').then((esmFS) => { + * // It syncs the existing readFile property with the new value + * assert.strictEqual(esmFS.readFile, newAPI); + * // readFileSync has been deleted from the required fs + * assert.strictEqual('readFileSync' in fs, false); + * // syncBuiltinESMExports() does not remove readFileSync from esmFS + * assert.strictEqual('readFileSync' in esmFS, true); + * // syncBuiltinESMExports() does not add names + * assert.strictEqual(esmFS.newAPI, undefined); + * }); + * ``` + * @since v12.12.0 + */ + function syncBuiltinESMExports(): void; + /** + * `path` is the resolved path for the file for which a corresponding source map + * should be fetched. + * @since v13.7.0, v12.17.0 + * @return Returns `module.SourceMap` if a source map is found, `undefined` otherwise. + */ + function findSourceMap(path: string, error?: Error): SourceMap; + interface SourceMapPayload { + file: string; + version: number; + sources: string[]; + sourcesContent: string[]; + names: string[]; + mappings: string; + sourceRoot: string; + } + interface SourceMapping { + generatedLine: number; + generatedColumn: number; + originalSource: string; + originalLine: number; + originalColumn: number; + } + interface SourceOrigin { + /** + * The name of the range in the source map, if one was provided + */ + name?: string; + /** + * The file name of the original source, as reported in the SourceMap + */ + fileName: string; + /** + * The 1-indexed lineNumber of the corresponding call site in the original source + */ + lineNumber: number; + /** + * The 1-indexed columnNumber of the corresponding call site in the original source + */ + columnNumber: number; + } + /** + * @since v13.7.0, v12.17.0 + */ + class SourceMap { + /** + * Getter for the payload used to construct the `SourceMap` instance. + */ + readonly payload: SourceMapPayload; + constructor(payload: SourceMapPayload); + /** + * Given a line offset and column offset in the generated source + * file, returns an object representing the SourceMap range in the + * original file if found, or an empty object if not. + * + * The object returned contains the following keys: + * + * The returned value represents the raw range as it appears in the + * SourceMap, based on zero-indexed offsets, _not_ 1-indexed line and + * column numbers as they appear in Error messages and CallSite + * objects. + * + * To get the corresponding 1-indexed line and column numbers from a + * lineNumber and columnNumber as they are reported by Error stacks + * and CallSite objects, use `sourceMap.findOrigin(lineNumber, columnNumber)` + * @param lineOffset The zero-indexed line number offset in the generated source + * @param columnOffset The zero-indexed column number offset in the generated source + */ + findEntry(lineOffset: number, columnOffset: number): SourceMapping; + /** + * Given a 1-indexed `lineNumber` and `columnNumber` from a call site in the generated source, + * find the corresponding call site location in the original source. + * + * If the `lineNumber` and `columnNumber` provided are not found in any source map, + * then an empty object is returned. + * @param lineNumber The 1-indexed line number of the call site in the generated source + * @param columnNumber The 1-indexed column number of the call site in the generated source + */ + findOrigin(lineNumber: number, columnNumber: number): SourceOrigin | {}; + } + interface ImportAttributes extends NodeJS.Dict { + type?: string | undefined; + } + type ModuleFormat = "builtin" | "commonjs" | "json" | "module" | "wasm"; + type ModuleSource = string | ArrayBuffer | NodeJS.TypedArray; + interface GlobalPreloadContext { + port: MessagePort; + } + /** + * @deprecated This hook will be removed in a future version. + * Use `initialize` instead. When a loader has an `initialize` export, `globalPreload` will be ignored. + * + * Sometimes it might be necessary to run some code inside of the same global scope that the application runs in. + * This hook allows the return of a string that is run as a sloppy-mode script on startup. + * + * @param context Information to assist the preload code + * @return Code to run before application startup + */ + type GlobalPreloadHook = (context: GlobalPreloadContext) => string; + /** + * The `initialize` hook provides a way to define a custom function that runs in the hooks thread + * when the hooks module is initialized. Initialization happens when the hooks module is registered via `register`. + * + * This hook can receive data from a `register` invocation, including ports and other transferrable objects. + * The return value of `initialize` can be a `Promise`, in which case it will be awaited before the main application thread execution resumes. + */ + type InitializeHook = (data: Data) => void | Promise; + interface ResolveHookContext { + /** + * Export conditions of the relevant `package.json` + */ + conditions: string[]; + /** + * An object whose key-value pairs represent the assertions for the module to import + */ + importAttributes: ImportAttributes; + /** + * The module importing this one, or undefined if this is the Node.js entry point + */ + parentURL: string | undefined; + } + interface ResolveFnOutput { + /** + * A hint to the load hook (it might be ignored) + */ + format?: ModuleFormat | null | undefined; + /** + * The import attributes to use when caching the module (optional; if excluded the input will be used) + */ + importAttributes?: ImportAttributes | undefined; + /** + * A signal that this hook intends to terminate the chain of `resolve` hooks. + * @default false + */ + shortCircuit?: boolean | undefined; + /** + * The absolute URL to which this input resolves + */ + url: string; + } + /** + * The `resolve` hook chain is responsible for resolving file URL for a given module specifier and parent URL, and optionally its format (such as `'module'`) as a hint to the `load` hook. + * If a format is specified, the load hook is ultimately responsible for providing the final `format` value (and it is free to ignore the hint provided by `resolve`); + * if `resolve` provides a format, a custom `load` hook is required even if only to pass the value to the Node.js default `load` hook. + * + * @param specifier The specified URL path of the module to be resolved + * @param context + * @param nextResolve The subsequent `resolve` hook in the chain, or the Node.js default `resolve` hook after the last user-supplied resolve hook + */ + type ResolveHook = ( + specifier: string, + context: ResolveHookContext, + nextResolve: ( + specifier: string, + context?: ResolveHookContext, + ) => ResolveFnOutput | Promise, + ) => ResolveFnOutput | Promise; + interface LoadHookContext { + /** + * Export conditions of the relevant `package.json` + */ + conditions: string[]; + /** + * The format optionally supplied by the `resolve` hook chain + */ + format: ModuleFormat; + /** + * An object whose key-value pairs represent the assertions for the module to import + */ + importAttributes: ImportAttributes; + } + interface LoadFnOutput { + format: ModuleFormat; + /** + * A signal that this hook intends to terminate the chain of `resolve` hooks. + * @default false + */ + shortCircuit?: boolean | undefined; + /** + * The source for Node.js to evaluate + */ + source?: ModuleSource; + } + /** + * The `load` hook provides a way to define a custom method of determining how a URL should be interpreted, retrieved, and parsed. + * It is also in charge of validating the import assertion. + * + * @param url The URL/path of the module to be loaded + * @param context Metadata about the module + * @param nextLoad The subsequent `load` hook in the chain, or the Node.js default `load` hook after the last user-supplied `load` hook + */ + type LoadHook = ( + url: string, + context: LoadHookContext, + nextLoad: (url: string, context?: LoadHookContext) => LoadFnOutput | Promise, + ) => LoadFnOutput | Promise; + } + interface RegisterOptions { + parentURL: string | URL; + data?: Data | undefined; + transferList?: any[] | undefined; + } + interface Module extends NodeModule {} + class Module { + static runMain(): void; + static wrap(code: string): string; + static createRequire(path: string | URL): NodeRequire; + static builtinModules: string[]; + static isBuiltin(moduleName: string): boolean; + static Module: typeof Module; + static register( + specifier: string | URL, + parentURL?: string | URL, + options?: RegisterOptions, + ): void; + static register(specifier: string | URL, options?: RegisterOptions): void; + constructor(id: string, parent?: Module); + } + global { + interface ImportMeta { + /** + * The directory name of the current module. This is the same as the `path.dirname()` of the `import.meta.filename`. + * **Caveat:** only present on `file:` modules. + */ + dirname: string; + /** + * The full absolute path and filename of the current module, with symlinks resolved. + * This is the same as the `url.fileURLToPath()` of the `import.meta.url`. + * **Caveat:** only local modules support this property. Modules not using the `file:` protocol will not provide it. + */ + filename: string; + /** + * The absolute `file:` URL of the module. + */ + url: string; + /** + * Provides a module-relative resolution function scoped to each module, returning + * the URL string. + * + * Second `parent` parameter is only used when the `--experimental-import-meta-resolve` + * command flag enabled. + * + * @since v20.6.0 + * + * @param specifier The module specifier to resolve relative to `parent`. + * @param parent The absolute parent module URL to resolve from. + * @returns The absolute (`file:`) URL string for the resolved module. + */ + resolve(specifier: string, parent?: string | URL | undefined): string; + } + } + export = Module; +} +declare module "node:module" { + import module = require("module"); + export = module; +} diff --git a/libcore/node_modules/@types/node/net.d.ts b/libcore/node_modules/@types/node/net.d.ts new file mode 100644 index 0000000..15ed7b7 --- /dev/null +++ b/libcore/node_modules/@types/node/net.d.ts @@ -0,0 +1,999 @@ +/** + * > Stability: 2 - Stable + * + * The `node:net` module provides an asynchronous network API for creating stream-based + * TCP or `IPC` servers ({@link createServer}) and clients + * ({@link createConnection}). + * + * It can be accessed using: + * + * ```js + * const net = require('node:net'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/net.js) + */ +declare module "net" { + import * as stream from "node:stream"; + import { Abortable, EventEmitter } from "node:events"; + import * as dns from "node:dns"; + type LookupFunction = ( + hostname: string, + options: dns.LookupOptions, + callback: (err: NodeJS.ErrnoException | null, address: string | dns.LookupAddress[], family?: number) => void, + ) => void; + interface AddressInfo { + address: string; + family: string; + port: number; + } + interface SocketConstructorOpts { + fd?: number | undefined; + allowHalfOpen?: boolean | undefined; + readable?: boolean | undefined; + writable?: boolean | undefined; + signal?: AbortSignal; + } + interface OnReadOpts { + buffer: Uint8Array | (() => Uint8Array); + /** + * This function is called for every chunk of incoming data. + * Two arguments are passed to it: the number of bytes written to buffer and a reference to buffer. + * Return false from this function to implicitly pause() the socket. + */ + callback(bytesWritten: number, buf: Uint8Array): boolean; + } + interface ConnectOpts { + /** + * If specified, incoming data is stored in a single buffer and passed to the supplied callback when data arrives on the socket. + * Note: this will cause the streaming functionality to not provide any data, however events like 'error', 'end', and 'close' will + * still be emitted as normal and methods like pause() and resume() will also behave as expected. + */ + onread?: OnReadOpts | undefined; + } + interface TcpSocketConnectOpts extends ConnectOpts { + port: number; + host?: string | undefined; + localAddress?: string | undefined; + localPort?: number | undefined; + hints?: number | undefined; + family?: number | undefined; + lookup?: LookupFunction | undefined; + noDelay?: boolean | undefined; + keepAlive?: boolean | undefined; + keepAliveInitialDelay?: number | undefined; + /** + * @since v18.13.0 + */ + autoSelectFamily?: boolean | undefined; + /** + * @since v18.13.0 + */ + autoSelectFamilyAttemptTimeout?: number | undefined; + } + interface IpcSocketConnectOpts extends ConnectOpts { + path: string; + } + type SocketConnectOpts = TcpSocketConnectOpts | IpcSocketConnectOpts; + type SocketReadyState = "opening" | "open" | "readOnly" | "writeOnly" | "closed"; + /** + * This class is an abstraction of a TCP socket or a streaming `IPC` endpoint + * (uses named pipes on Windows, and Unix domain sockets otherwise). It is also + * an `EventEmitter`. + * + * A `net.Socket` can be created by the user and used directly to interact with + * a server. For example, it is returned by {@link createConnection}, + * so the user can use it to talk to the server. + * + * It can also be created by Node.js and passed to the user when a connection + * is received. For example, it is passed to the listeners of a `'connection'` event emitted on a {@link Server}, so the user can use + * it to interact with the client. + * @since v0.3.4 + */ + class Socket extends stream.Duplex { + constructor(options?: SocketConstructorOpts); + /** + * Destroys the socket after all data is written. If the `finish` event was already emitted the socket is destroyed immediately. + * If the socket is still writable it implicitly calls `socket.end()`. + * @since v0.3.4 + */ + destroySoon(): void; + /** + * Sends data on the socket. The second parameter specifies the encoding in the + * case of a string. It defaults to UTF8 encoding. + * + * Returns `true` if the entire data was flushed successfully to the kernel + * buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is again free. + * + * The optional `callback` parameter will be executed when the data is finally + * written out, which may not be immediately. + * + * See `Writable` stream `write()` method for more + * information. + * @since v0.1.90 + * @param [encoding='utf8'] Only used when data is `string`. + */ + write(buffer: Uint8Array | string, cb?: (err?: Error) => void): boolean; + write(str: Uint8Array | string, encoding?: BufferEncoding, cb?: (err?: Error) => void): boolean; + /** + * Initiate a connection on a given socket. + * + * Possible signatures: + * + * * `socket.connect(options[, connectListener])` + * * `socket.connect(path[, connectListener])` for `IPC` connections. + * * `socket.connect(port[, host][, connectListener])` for TCP connections. + * * Returns: `net.Socket` The socket itself. + * + * This function is asynchronous. When the connection is established, the `'connect'` event will be emitted. If there is a problem connecting, + * instead of a `'connect'` event, an `'error'` event will be emitted with + * the error passed to the `'error'` listener. + * The last parameter `connectListener`, if supplied, will be added as a listener + * for the `'connect'` event **once**. + * + * This function should only be used for reconnecting a socket after`'close'` has been emitted or otherwise it may lead to undefined + * behavior. + */ + connect(options: SocketConnectOpts, connectionListener?: () => void): this; + connect(port: number, host: string, connectionListener?: () => void): this; + connect(port: number, connectionListener?: () => void): this; + connect(path: string, connectionListener?: () => void): this; + /** + * Set the encoding for the socket as a `Readable Stream`. See `readable.setEncoding()` for more information. + * @since v0.1.90 + * @return The socket itself. + */ + setEncoding(encoding?: BufferEncoding): this; + /** + * Pauses the reading of data. That is, `'data'` events will not be emitted. + * Useful to throttle back an upload. + * @return The socket itself. + */ + pause(): this; + /** + * Close the TCP connection by sending an RST packet and destroy the stream. + * If this TCP socket is in connecting status, it will send an RST packet and destroy this TCP socket once it is connected. + * Otherwise, it will call `socket.destroy` with an `ERR_SOCKET_CLOSED` Error. + * If this is not a TCP socket (for example, a pipe), calling this method will immediately throw an `ERR_INVALID_HANDLE_TYPE` Error. + * @since v18.3.0, v16.17.0 + */ + resetAndDestroy(): this; + /** + * Resumes reading after a call to `socket.pause()`. + * @return The socket itself. + */ + resume(): this; + /** + * Sets the socket to timeout after `timeout` milliseconds of inactivity on + * the socket. By default `net.Socket` do not have a timeout. + * + * When an idle timeout is triggered the socket will receive a `'timeout'` event but the connection will not be severed. The user must manually call `socket.end()` or `socket.destroy()` to + * end the connection. + * + * ```js + * socket.setTimeout(3000); + * socket.on('timeout', () => { + * console.log('socket timeout'); + * socket.end(); + * }); + * ``` + * + * If `timeout` is 0, then the existing idle timeout is disabled. + * + * The optional `callback` parameter will be added as a one-time listener for the `'timeout'` event. + * @since v0.1.90 + * @return The socket itself. + */ + setTimeout(timeout: number, callback?: () => void): this; + /** + * Enable/disable the use of Nagle's algorithm. + * + * When a TCP connection is created, it will have Nagle's algorithm enabled. + * + * Nagle's algorithm delays data before it is sent via the network. It attempts + * to optimize throughput at the expense of latency. + * + * Passing `true` for `noDelay` or not passing an argument will disable Nagle's + * algorithm for the socket. Passing `false` for `noDelay` will enable Nagle's + * algorithm. + * @since v0.1.90 + * @param [noDelay=true] + * @return The socket itself. + */ + setNoDelay(noDelay?: boolean): this; + /** + * Enable/disable keep-alive functionality, and optionally set the initial + * delay before the first keepalive probe is sent on an idle socket. + * + * Set `initialDelay` (in milliseconds) to set the delay between the last + * data packet received and the first keepalive probe. Setting `0` for`initialDelay` will leave the value unchanged from the default + * (or previous) setting. + * + * Enabling the keep-alive functionality will set the following socket options: + * + * * `SO_KEEPALIVE=1` + * * `TCP_KEEPIDLE=initialDelay` + * * `TCP_KEEPCNT=10` + * * `TCP_KEEPINTVL=1` + * @since v0.1.92 + * @param [enable=false] + * @param [initialDelay=0] + * @return The socket itself. + */ + setKeepAlive(enable?: boolean, initialDelay?: number): this; + /** + * Returns the bound `address`, the address `family` name and `port` of the + * socket as reported by the operating system:`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }` + * @since v0.1.90 + */ + address(): AddressInfo | {}; + /** + * Calling `unref()` on a socket will allow the program to exit if this is the only + * active socket in the event system. If the socket is already `unref`ed calling`unref()` again will have no effect. + * @since v0.9.1 + * @return The socket itself. + */ + unref(): this; + /** + * Opposite of `unref()`, calling `ref()` on a previously `unref`ed socket will _not_ let the program exit if it's the only socket left (the default behavior). + * If the socket is `ref`ed calling `ref` again will have no effect. + * @since v0.9.1 + * @return The socket itself. + */ + ref(): this; + /** + * This property is only present if the family autoselection algorithm is enabled in `socket.connect(options)` + * and it is an array of the addresses that have been attempted. + * + * Each address is a string in the form of `$IP:$PORT`. + * If the connection was successful, then the last address is the one that the socket is currently connected to. + * @since v19.4.0 + */ + readonly autoSelectFamilyAttemptedAddresses: string[]; + /** + * This property shows the number of characters buffered for writing. The buffer + * may contain strings whose length after encoding is not yet known. So this number + * is only an approximation of the number of bytes in the buffer. + * + * `net.Socket` has the property that `socket.write()` always works. This is to + * help users get up and running quickly. The computer cannot always keep up + * with the amount of data that is written to a socket. The network connection + * simply might be too slow. Node.js will internally queue up the data written to a + * socket and send it out over the wire when it is possible. + * + * The consequence of this internal buffering is that memory may grow. + * Users who experience large or growing `bufferSize` should attempt to + * "throttle" the data flows in their program with `socket.pause()` and `socket.resume()`. + * @since v0.3.8 + * @deprecated Since v14.6.0 - Use `writableLength` instead. + */ + readonly bufferSize: number; + /** + * The amount of received bytes. + * @since v0.5.3 + */ + readonly bytesRead: number; + /** + * The amount of bytes sent. + * @since v0.5.3 + */ + readonly bytesWritten: number; + /** + * If `true`, `socket.connect(options[, connectListener])` was + * called and has not yet finished. It will stay `true` until the socket becomes + * connected, then it is set to `false` and the `'connect'` event is emitted. Note + * that the `socket.connect(options[, connectListener])` callback is a listener for the `'connect'` event. + * @since v6.1.0 + */ + readonly connecting: boolean; + /** + * This is `true` if the socket is not connected yet, either because `.connect()`has not yet been called or because it is still in the process of connecting + * (see `socket.connecting`). + * @since v11.2.0, v10.16.0 + */ + readonly pending: boolean; + /** + * See `writable.destroyed` for further details. + */ + readonly destroyed: boolean; + /** + * The string representation of the local IP address the remote client is + * connecting on. For example, in a server listening on `'0.0.0.0'`, if a client + * connects on `'192.168.1.1'`, the value of `socket.localAddress` would be`'192.168.1.1'`. + * @since v0.9.6 + */ + readonly localAddress?: string; + /** + * The numeric representation of the local port. For example, `80` or `21`. + * @since v0.9.6 + */ + readonly localPort?: number; + /** + * The string representation of the local IP family. `'IPv4'` or `'IPv6'`. + * @since v18.8.0, v16.18.0 + */ + readonly localFamily?: string; + /** + * This property represents the state of the connection as a string. + * + * * If the stream is connecting `socket.readyState` is `opening`. + * * If the stream is readable and writable, it is `open`. + * * If the stream is readable and not writable, it is `readOnly`. + * * If the stream is not readable and writable, it is `writeOnly`. + * @since v0.5.0 + */ + readonly readyState: SocketReadyState; + /** + * The string representation of the remote IP address. For example,`'74.125.127.100'` or `'2001:4860:a005::68'`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). + * @since v0.5.10 + */ + readonly remoteAddress?: string | undefined; + /** + * The string representation of the remote IP family. `'IPv4'` or `'IPv6'`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). + * @since v0.11.14 + */ + readonly remoteFamily?: string | undefined; + /** + * The numeric representation of the remote port. For example, `80` or `21`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). + * @since v0.5.10 + */ + readonly remotePort?: number | undefined; + /** + * The socket timeout in milliseconds as set by `socket.setTimeout()`. + * It is `undefined` if a timeout has not been set. + * @since v10.7.0 + */ + readonly timeout?: number | undefined; + /** + * Half-closes the socket. i.e., it sends a FIN packet. It is possible the + * server will still send some data. + * + * See `writable.end()` for further details. + * @since v0.1.90 + * @param [encoding='utf8'] Only used when data is `string`. + * @param callback Optional callback for when the socket is finished. + * @return The socket itself. + */ + end(callback?: () => void): this; + end(buffer: Uint8Array | string, callback?: () => void): this; + end(str: Uint8Array | string, encoding?: BufferEncoding, callback?: () => void): this; + /** + * events.EventEmitter + * 1. close + * 2. connect + * 3. connectionAttempt + * 4. connectionAttemptFailed + * 5. connectionAttemptTimeout + * 6. data + * 7. drain + * 8. end + * 9. error + * 10. lookup + * 11. ready + * 12. timeout + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: (hadError: boolean) => void): this; + addListener(event: "connect", listener: () => void): this; + addListener(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this; + addListener( + event: "connectionAttemptFailed", + listener: (ip: string, port: number, family: number) => void, + ): this; + addListener( + event: "connectionAttemptTimeout", + listener: (ip: string, port: number, family: number) => void, + ): this; + addListener(event: "data", listener: (data: Buffer) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + addListener(event: "ready", listener: () => void): this; + addListener(event: "timeout", listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close", hadError: boolean): boolean; + emit(event: "connect"): boolean; + emit(event: "connectionAttempt", ip: string, port: number, family: number): boolean; + emit(event: "connectionAttemptFailed", ip: string, port: number, family: number): boolean; + emit(event: "connectionAttemptTimeout", ip: string, port: number, family: number): boolean; + emit(event: "data", data: Buffer): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "lookup", err: Error, address: string, family: string | number, host: string): boolean; + emit(event: "ready"): boolean; + emit(event: "timeout"): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: (hadError: boolean) => void): this; + on(event: "connect", listener: () => void): this; + on(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this; + on(event: "connectionAttemptFailed", listener: (ip: string, port: number, family: number) => void): this; + on(event: "connectionAttemptTimeout", listener: (ip: string, port: number, family: number) => void): this; + on(event: "data", listener: (data: Buffer) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + on(event: "ready", listener: () => void): this; + on(event: "timeout", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: (hadError: boolean) => void): this; + once(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this; + once(event: "connectionAttemptFailed", listener: (ip: string, port: number, family: number) => void): this; + once(event: "connectionAttemptTimeout", listener: (ip: string, port: number, family: number) => void): this; + once(event: "connect", listener: () => void): this; + once(event: "data", listener: (data: Buffer) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + once(event: "ready", listener: () => void): this; + once(event: "timeout", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: (hadError: boolean) => void): this; + prependListener(event: "connect", listener: () => void): this; + prependListener(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this; + prependListener( + event: "connectionAttemptFailed", + listener: (ip: string, port: number, family: number) => void, + ): this; + prependListener( + event: "connectionAttemptTimeout", + listener: (ip: string, port: number, family: number) => void, + ): this; + prependListener(event: "data", listener: (data: Buffer) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + prependListener(event: "ready", listener: () => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: (hadError: boolean) => void): this; + prependOnceListener(event: "connect", listener: () => void): this; + prependOnceListener( + event: "connectionAttempt", + listener: (ip: string, port: number, family: number) => void, + ): this; + prependOnceListener( + event: "connectionAttemptFailed", + listener: (ip: string, port: number, family: number) => void, + ): this; + prependOnceListener( + event: "connectionAttemptTimeout", + listener: (ip: string, port: number, family: number) => void, + ): this; + prependOnceListener(event: "data", listener: (data: Buffer) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + prependOnceListener(event: "ready", listener: () => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + } + interface ListenOptions extends Abortable { + port?: number | undefined; + host?: string | undefined; + backlog?: number | undefined; + path?: string | undefined; + exclusive?: boolean | undefined; + readableAll?: boolean | undefined; + writableAll?: boolean | undefined; + /** + * @default false + */ + ipv6Only?: boolean | undefined; + } + interface ServerOpts { + /** + * Indicates whether half-opened TCP connections are allowed. + * @default false + */ + allowHalfOpen?: boolean | undefined; + /** + * Indicates whether the socket should be paused on incoming connections. + * @default false + */ + pauseOnConnect?: boolean | undefined; + /** + * If set to `true`, it disables the use of Nagle's algorithm immediately after a new incoming connection is received. + * @default false + * @since v16.5.0 + */ + noDelay?: boolean | undefined; + /** + * If set to `true`, it enables keep-alive functionality on the socket immediately after a new incoming connection is received, + * similarly on what is done in `socket.setKeepAlive([enable][, initialDelay])`. + * @default false + * @since v16.5.0 + */ + keepAlive?: boolean | undefined; + /** + * If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket. + * @default 0 + * @since v16.5.0 + */ + keepAliveInitialDelay?: number | undefined; + } + interface DropArgument { + localAddress?: string; + localPort?: number; + localFamily?: string; + remoteAddress?: string; + remotePort?: number; + remoteFamily?: string; + } + /** + * This class is used to create a TCP or `IPC` server. + * @since v0.1.90 + */ + class Server extends EventEmitter { + constructor(connectionListener?: (socket: Socket) => void); + constructor(options?: ServerOpts, connectionListener?: (socket: Socket) => void); + /** + * Start a server listening for connections. A `net.Server` can be a TCP or + * an `IPC` server depending on what it listens to. + * + * Possible signatures: + * + * * `server.listen(handle[, backlog][, callback])` + * * `server.listen(options[, callback])` + * * `server.listen(path[, backlog][, callback])` for `IPC` servers + * * `server.listen([port[, host[, backlog]]][, callback])` for TCP servers + * + * This function is asynchronous. When the server starts listening, the `'listening'` event will be emitted. The last parameter `callback`will be added as a listener for the `'listening'` + * event. + * + * All `listen()` methods can take a `backlog` parameter to specify the maximum + * length of the queue of pending connections. The actual length will be determined + * by the OS through sysctl settings such as `tcp_max_syn_backlog` and `somaxconn` on Linux. The default value of this parameter is 511 (not 512). + * + * All {@link Socket} are set to `SO_REUSEADDR` (see [`socket(7)`](https://man7.org/linux/man-pages/man7/socket.7.html) for + * details). + * + * The `server.listen()` method can be called again if and only if there was an + * error during the first `server.listen()` call or `server.close()` has been + * called. Otherwise, an `ERR_SERVER_ALREADY_LISTEN` error will be thrown. + * + * One of the most common errors raised when listening is `EADDRINUSE`. + * This happens when another server is already listening on the requested`port`/`path`/`handle`. One way to handle this would be to retry + * after a certain amount of time: + * + * ```js + * server.on('error', (e) => { + * if (e.code === 'EADDRINUSE') { + * console.error('Address in use, retrying...'); + * setTimeout(() => { + * server.close(); + * server.listen(PORT, HOST); + * }, 1000); + * } + * }); + * ``` + */ + listen(port?: number, hostname?: string, backlog?: number, listeningListener?: () => void): this; + listen(port?: number, hostname?: string, listeningListener?: () => void): this; + listen(port?: number, backlog?: number, listeningListener?: () => void): this; + listen(port?: number, listeningListener?: () => void): this; + listen(path: string, backlog?: number, listeningListener?: () => void): this; + listen(path: string, listeningListener?: () => void): this; + listen(options: ListenOptions, listeningListener?: () => void): this; + listen(handle: any, backlog?: number, listeningListener?: () => void): this; + listen(handle: any, listeningListener?: () => void): this; + /** + * Stops the server from accepting new connections and keeps existing + * connections. This function is asynchronous, the server is finally closed + * when all connections are ended and the server emits a `'close'` event. + * The optional `callback` will be called once the `'close'` event occurs. Unlike + * that event, it will be called with an `Error` as its only argument if the server + * was not open when it was closed. + * @since v0.1.90 + * @param callback Called when the server is closed. + */ + close(callback?: (err?: Error) => void): this; + /** + * Returns the bound `address`, the address `family` name, and `port` of the server + * as reported by the operating system if listening on an IP socket + * (useful to find which port was assigned when getting an OS-assigned address):`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`. + * + * For a server listening on a pipe or Unix domain socket, the name is returned + * as a string. + * + * ```js + * const server = net.createServer((socket) => { + * socket.end('goodbye\n'); + * }).on('error', (err) => { + * // Handle errors here. + * throw err; + * }); + * + * // Grab an arbitrary unused port. + * server.listen(() => { + * console.log('opened server on', server.address()); + * }); + * ``` + * + * `server.address()` returns `null` before the `'listening'` event has been + * emitted or after calling `server.close()`. + * @since v0.1.90 + */ + address(): AddressInfo | string | null; + /** + * Asynchronously get the number of concurrent connections on the server. Works + * when sockets were sent to forks. + * + * Callback should take two arguments `err` and `count`. + * @since v0.9.7 + */ + getConnections(cb: (error: Error | null, count: number) => void): void; + /** + * Opposite of `unref()`, calling `ref()` on a previously `unref`ed server will _not_ let the program exit if it's the only server left (the default behavior). + * If the server is `ref`ed calling `ref()` again will have no effect. + * @since v0.9.1 + */ + ref(): this; + /** + * Calling `unref()` on a server will allow the program to exit if this is the only + * active server in the event system. If the server is already `unref`ed calling`unref()` again will have no effect. + * @since v0.9.1 + */ + unref(): this; + /** + * Set this property to reject connections when the server's connection count gets + * high. + * + * It is not recommended to use this option once a socket has been sent to a child + * with `child_process.fork()`. + * @since v0.2.0 + */ + maxConnections: number; + connections: number; + /** + * Indicates whether or not the server is listening for connections. + * @since v5.7.0 + */ + readonly listening: boolean; + /** + * events.EventEmitter + * 1. close + * 2. connection + * 3. error + * 4. listening + * 5. drop + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connection", listener: (socket: Socket) => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "drop", listener: (data?: DropArgument) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "connection", socket: Socket): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit(event: "drop", data?: DropArgument): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connection", listener: (socket: Socket) => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "drop", listener: (data?: DropArgument) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connection", listener: (socket: Socket) => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "drop", listener: (data?: DropArgument) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connection", listener: (socket: Socket) => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "drop", listener: (data?: DropArgument) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connection", listener: (socket: Socket) => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "drop", listener: (data?: DropArgument) => void): this; + /** + * Calls {@link Server.close()} and returns a promise that fulfills when the server has closed. + * @since v20.5.0 + */ + [Symbol.asyncDispose](): Promise; + } + type IPVersion = "ipv4" | "ipv6"; + /** + * The `BlockList` object can be used with some network APIs to specify rules for + * disabling inbound or outbound access to specific IP addresses, IP ranges, or + * IP subnets. + * @since v15.0.0, v14.18.0 + */ + class BlockList { + /** + * Adds a rule to block the given IP address. + * @since v15.0.0, v14.18.0 + * @param address An IPv4 or IPv6 address. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addAddress(address: string, type?: IPVersion): void; + addAddress(address: SocketAddress): void; + /** + * Adds a rule to block a range of IP addresses from `start` (inclusive) to`end` (inclusive). + * @since v15.0.0, v14.18.0 + * @param start The starting IPv4 or IPv6 address in the range. + * @param end The ending IPv4 or IPv6 address in the range. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addRange(start: string, end: string, type?: IPVersion): void; + addRange(start: SocketAddress, end: SocketAddress): void; + /** + * Adds a rule to block a range of IP addresses specified as a subnet mask. + * @since v15.0.0, v14.18.0 + * @param net The network IPv4 or IPv6 address. + * @param prefix The number of CIDR prefix bits. For IPv4, this must be a value between `0` and `32`. For IPv6, this must be between `0` and `128`. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addSubnet(net: SocketAddress, prefix: number): void; + addSubnet(net: string, prefix: number, type?: IPVersion): void; + /** + * Returns `true` if the given IP address matches any of the rules added to the`BlockList`. + * + * ```js + * const blockList = new net.BlockList(); + * blockList.addAddress('123.123.123.123'); + * blockList.addRange('10.0.0.1', '10.0.0.10'); + * blockList.addSubnet('8592:757c:efae:4e45::', 64, 'ipv6'); + * + * console.log(blockList.check('123.123.123.123')); // Prints: true + * console.log(blockList.check('10.0.0.3')); // Prints: true + * console.log(blockList.check('222.111.111.222')); // Prints: false + * + * // IPv6 notation for IPv4 addresses works: + * console.log(blockList.check('::ffff:7b7b:7b7b', 'ipv6')); // Prints: true + * console.log(blockList.check('::ffff:123.123.123.123', 'ipv6')); // Prints: true + * ``` + * @since v15.0.0, v14.18.0 + * @param address The IP address to check + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + check(address: SocketAddress): boolean; + check(address: string, type?: IPVersion): boolean; + /** + * The list of rules added to the blocklist. + * @since v15.0.0, v14.18.0 + */ + rules: readonly string[]; + } + interface TcpNetConnectOpts extends TcpSocketConnectOpts, SocketConstructorOpts { + timeout?: number | undefined; + } + interface IpcNetConnectOpts extends IpcSocketConnectOpts, SocketConstructorOpts { + timeout?: number | undefined; + } + type NetConnectOpts = TcpNetConnectOpts | IpcNetConnectOpts; + /** + * Creates a new TCP or `IPC` server. + * + * If `allowHalfOpen` is set to `true`, when the other end of the socket + * signals the end of transmission, the server will only send back the end of + * transmission when `socket.end()` is explicitly called. For example, in the + * context of TCP, when a FIN packed is received, a FIN packed is sent + * back only when `socket.end()` is explicitly called. Until then the + * connection is half-closed (non-readable but still writable). See `'end'` event and [RFC 1122](https://tools.ietf.org/html/rfc1122) (section 4.2.2.13) for more information. + * + * If `pauseOnConnect` is set to `true`, then the socket associated with each + * incoming connection will be paused, and no data will be read from its handle. + * This allows connections to be passed between processes without any data being + * read by the original process. To begin reading data from a paused socket, call `socket.resume()`. + * + * The server can be a TCP server or an `IPC` server, depending on what it `listen()` to. + * + * Here is an example of a TCP echo server which listens for connections + * on port 8124: + * + * ```js + * const net = require('node:net'); + * const server = net.createServer((c) => { + * // 'connection' listener. + * console.log('client connected'); + * c.on('end', () => { + * console.log('client disconnected'); + * }); + * c.write('hello\r\n'); + * c.pipe(c); + * }); + * server.on('error', (err) => { + * throw err; + * }); + * server.listen(8124, () => { + * console.log('server bound'); + * }); + * ``` + * + * Test this by using `telnet`: + * + * ```bash + * telnet localhost 8124 + * ``` + * + * To listen on the socket `/tmp/echo.sock`: + * + * ```js + * server.listen('/tmp/echo.sock', () => { + * console.log('server bound'); + * }); + * ``` + * + * Use `nc` to connect to a Unix domain socket server: + * + * ```bash + * nc -U /tmp/echo.sock + * ``` + * @since v0.5.0 + * @param connectionListener Automatically set as a listener for the {@link 'connection'} event. + */ + function createServer(connectionListener?: (socket: Socket) => void): Server; + function createServer(options?: ServerOpts, connectionListener?: (socket: Socket) => void): Server; + /** + * Aliases to {@link createConnection}. + * + * Possible signatures: + * + * * {@link connect} + * * {@link connect} for `IPC` connections. + * * {@link connect} for TCP connections. + */ + function connect(options: NetConnectOpts, connectionListener?: () => void): Socket; + function connect(port: number, host?: string, connectionListener?: () => void): Socket; + function connect(path: string, connectionListener?: () => void): Socket; + /** + * A factory function, which creates a new {@link Socket}, + * immediately initiates connection with `socket.connect()`, + * then returns the `net.Socket` that starts the connection. + * + * When the connection is established, a `'connect'` event will be emitted + * on the returned socket. The last parameter `connectListener`, if supplied, + * will be added as a listener for the `'connect'` event **once**. + * + * Possible signatures: + * + * * {@link createConnection} + * * {@link createConnection} for `IPC` connections. + * * {@link createConnection} for TCP connections. + * + * The {@link connect} function is an alias to this function. + */ + function createConnection(options: NetConnectOpts, connectionListener?: () => void): Socket; + function createConnection(port: number, host?: string, connectionListener?: () => void): Socket; + function createConnection(path: string, connectionListener?: () => void): Socket; + /** + * Gets the current default value of the `autoSelectFamily` option of `socket.connect(options)`. + * The initial default value is `true`, unless the command line option`--no-network-family-autoselection` is provided. + * @since v19.4.0 + */ + function getDefaultAutoSelectFamily(): boolean; + /** + * Sets the default value of the `autoSelectFamily` option of `socket.connect(options)`. + * @since v19.4.0 + */ + function setDefaultAutoSelectFamily(value: boolean): void; + /** + * Gets the current default value of the `autoSelectFamilyAttemptTimeout` option of `socket.connect(options)`. + * The initial default value is `250` or the value specified via the command line option `--network-family-autoselection-attempt-timeout`. + * @returns The current default value of the `autoSelectFamilyAttemptTimeout` option. + * @since v19.8.0, v18.8.0 + */ + function getDefaultAutoSelectFamilyAttemptTimeout(): number; + /** + * Sets the default value of the `autoSelectFamilyAttemptTimeout` option of `socket.connect(options)`. + * @param value The new default value, which must be a positive number. If the number is less than `10`, the value `10` is used instead. The initial default value is `250` or the value specified via the command line + * option `--network-family-autoselection-attempt-timeout`. + * @since v19.8.0, v18.8.0 + */ + function setDefaultAutoSelectFamilyAttemptTimeout(value: number): void; + /** + * Returns `6` if `input` is an IPv6 address. Returns `4` if `input` is an IPv4 + * address in [dot-decimal notation](https://en.wikipedia.org/wiki/Dot-decimal_notation) with no leading zeroes. Otherwise, returns`0`. + * + * ```js + * net.isIP('::1'); // returns 6 + * net.isIP('127.0.0.1'); // returns 4 + * net.isIP('127.000.000.001'); // returns 0 + * net.isIP('127.0.0.1/24'); // returns 0 + * net.isIP('fhqwhgads'); // returns 0 + * ``` + * @since v0.3.0 + */ + function isIP(input: string): number; + /** + * Returns `true` if `input` is an IPv4 address in [dot-decimal notation](https://en.wikipedia.org/wiki/Dot-decimal_notation) with no + * leading zeroes. Otherwise, returns `false`. + * + * ```js + * net.isIPv4('127.0.0.1'); // returns true + * net.isIPv4('127.000.000.001'); // returns false + * net.isIPv4('127.0.0.1/24'); // returns false + * net.isIPv4('fhqwhgads'); // returns false + * ``` + * @since v0.3.0 + */ + function isIPv4(input: string): boolean; + /** + * Returns `true` if `input` is an IPv6 address. Otherwise, returns `false`. + * + * ```js + * net.isIPv6('::1'); // returns true + * net.isIPv6('fhqwhgads'); // returns false + * ``` + * @since v0.3.0 + */ + function isIPv6(input: string): boolean; + interface SocketAddressInitOptions { + /** + * The network address as either an IPv4 or IPv6 string. + * @default 127.0.0.1 + */ + address?: string | undefined; + /** + * @default `'ipv4'` + */ + family?: IPVersion | undefined; + /** + * An IPv6 flow-label used only if `family` is `'ipv6'`. + * @default 0 + */ + flowlabel?: number | undefined; + /** + * An IP port. + * @default 0 + */ + port?: number | undefined; + } + /** + * @since v15.14.0, v14.18.0 + */ + class SocketAddress { + constructor(options: SocketAddressInitOptions); + /** + * Either \`'ipv4'\` or \`'ipv6'\`. + * @since v15.14.0, v14.18.0 + */ + readonly address: string; + /** + * Either \`'ipv4'\` or \`'ipv6'\`. + * @since v15.14.0, v14.18.0 + */ + readonly family: IPVersion; + /** + * @since v15.14.0, v14.18.0 + */ + readonly port: number; + /** + * @since v15.14.0, v14.18.0 + */ + readonly flowlabel: number; + } +} +declare module "node:net" { + export * from "net"; +} diff --git a/libcore/node_modules/@types/node/os.d.ts b/libcore/node_modules/@types/node/os.d.ts new file mode 100644 index 0000000..d0593ff --- /dev/null +++ b/libcore/node_modules/@types/node/os.d.ts @@ -0,0 +1,495 @@ +/** + * The `node:os` module provides operating system-related utility methods and + * properties. It can be accessed using: + * + * ```js + * const os = require('node:os'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/os.js) + */ +declare module "os" { + interface CpuInfo { + model: string; + speed: number; + times: { + /** The number of milliseconds the CPU has spent in user mode. */ + user: number; + /** The number of milliseconds the CPU has spent in nice mode. */ + nice: number; + /** The number of milliseconds the CPU has spent in sys mode. */ + sys: number; + /** The number of milliseconds the CPU has spent in idle mode. */ + idle: number; + /** The number of milliseconds the CPU has spent in irq mode. */ + irq: number; + }; + } + interface NetworkInterfaceBase { + address: string; + netmask: string; + mac: string; + internal: boolean; + cidr: string | null; + } + interface NetworkInterfaceInfoIPv4 extends NetworkInterfaceBase { + family: "IPv4"; + scopeid?: undefined; + } + interface NetworkInterfaceInfoIPv6 extends NetworkInterfaceBase { + family: "IPv6"; + scopeid: number; + } + interface UserInfo { + username: T; + uid: number; + gid: number; + shell: T | null; + homedir: T; + } + type NetworkInterfaceInfo = NetworkInterfaceInfoIPv4 | NetworkInterfaceInfoIPv6; + /** + * Returns the host name of the operating system as a string. + * @since v0.3.3 + */ + function hostname(): string; + /** + * Returns an array containing the 1, 5, and 15 minute load averages. + * + * The load average is a measure of system activity calculated by the operating + * system and expressed as a fractional number. + * + * The load average is a Unix-specific concept. On Windows, the return value is + * always `[0, 0, 0]`. + * @since v0.3.3 + */ + function loadavg(): number[]; + /** + * Returns the system uptime in number of seconds. + * @since v0.3.3 + */ + function uptime(): number; + /** + * Returns the amount of free system memory in bytes as an integer. + * @since v0.3.3 + */ + function freemem(): number; + /** + * Returns the total amount of system memory in bytes as an integer. + * @since v0.3.3 + */ + function totalmem(): number; + /** + * Returns an array of objects containing information about each logical CPU core. + * The array will be empty if no CPU information is available, such as if the `/proc` file system is unavailable. + * + * The properties included on each object include: + * + * ```js + * [ + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 252020, + * nice: 0, + * sys: 30340, + * idle: 1070356870, + * irq: 0, + * }, + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 306960, + * nice: 0, + * sys: 26980, + * idle: 1071569080, + * irq: 0, + * }, + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 248450, + * nice: 0, + * sys: 21750, + * idle: 1070919370, + * irq: 0, + * }, + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 256880, + * nice: 0, + * sys: 19430, + * idle: 1070905480, + * irq: 20, + * }, + * }, + * ] + * ``` + * + * `nice` values are POSIX-only. On Windows, the `nice` values of all processors + * are always 0. + * + * `os.cpus().length` should not be used to calculate the amount of parallelism + * available to an application. Use {@link availableParallelism} for this purpose. + * @since v0.3.3 + */ + function cpus(): CpuInfo[]; + /** + * Returns an estimate of the default amount of parallelism a program should use. + * Always returns a value greater than zero. + * + * This function is a small wrapper about libuv's [`uv_available_parallelism()`](https://docs.libuv.org/en/v1.x/misc.html#c.uv_available_parallelism). + * @since v19.4.0, v18.14.0 + */ + function availableParallelism(): number; + /** + * Returns the operating system name as returned by [`uname(3)`](https://linux.die.net/man/3/uname). For example, it + * returns `'Linux'` on Linux, `'Darwin'` on macOS, and `'Windows_NT'` on Windows. + * + * See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for additional information + * about the output of running [`uname(3)`](https://linux.die.net/man/3/uname) on various operating systems. + * @since v0.3.3 + */ + function type(): string; + /** + * Returns the operating system as a string. + * + * On POSIX systems, the operating system release is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `GetVersionExW()` is used. See + * [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v0.3.3 + */ + function release(): string; + /** + * Returns an object containing network interfaces that have been assigned a + * network address. + * + * Each key on the returned object identifies a network interface. The associated + * value is an array of objects that each describe an assigned network address. + * + * The properties available on the assigned network address object include: + * + * ```js + * { + * lo: [ + * { + * address: '127.0.0.1', + * netmask: '255.0.0.0', + * family: 'IPv4', + * mac: '00:00:00:00:00:00', + * internal: true, + * cidr: '127.0.0.1/8' + * }, + * { + * address: '::1', + * netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', + * family: 'IPv6', + * mac: '00:00:00:00:00:00', + * scopeid: 0, + * internal: true, + * cidr: '::1/128' + * } + * ], + * eth0: [ + * { + * address: '192.168.1.108', + * netmask: '255.255.255.0', + * family: 'IPv4', + * mac: '01:02:03:0a:0b:0c', + * internal: false, + * cidr: '192.168.1.108/24' + * }, + * { + * address: 'fe80::a00:27ff:fe4e:66a1', + * netmask: 'ffff:ffff:ffff:ffff::', + * family: 'IPv6', + * mac: '01:02:03:0a:0b:0c', + * scopeid: 1, + * internal: false, + * cidr: 'fe80::a00:27ff:fe4e:66a1/64' + * } + * ] + * } + * ``` + * @since v0.6.0 + */ + function networkInterfaces(): NodeJS.Dict; + /** + * Returns the string path of the current user's home directory. + * + * On POSIX, it uses the `$HOME` environment variable if defined. Otherwise it + * uses the [effective UID](https://en.wikipedia.org/wiki/User_identifier#Effective_user_ID) to look up the user's home directory. + * + * On Windows, it uses the `USERPROFILE` environment variable if defined. + * Otherwise it uses the path to the profile directory of the current user. + * @since v2.3.0 + */ + function homedir(): string; + /** + * Returns information about the currently effective user. On POSIX platforms, + * this is typically a subset of the password file. The returned object includes + * the `username`, `uid`, `gid`, `shell`, and `homedir`. On Windows, the `uid` and `gid` fields are `-1`, and `shell` is `null`. + * + * The value of `homedir` returned by `os.userInfo()` is provided by the operating + * system. This differs from the result of `os.homedir()`, which queries + * environment variables for the home directory before falling back to the + * operating system response. + * + * Throws a [`SystemError`](https://nodejs.org/docs/latest-v22.x/api/errors.html#class-systemerror) if a user has no `username` or `homedir`. + * @since v6.0.0 + */ + function userInfo(options: { encoding: "buffer" }): UserInfo; + function userInfo(options?: { encoding: BufferEncoding }): UserInfo; + type SignalConstants = { + [key in NodeJS.Signals]: number; + }; + namespace constants { + const UV_UDP_REUSEADDR: number; + namespace signals {} + const signals: SignalConstants; + namespace errno { + const E2BIG: number; + const EACCES: number; + const EADDRINUSE: number; + const EADDRNOTAVAIL: number; + const EAFNOSUPPORT: number; + const EAGAIN: number; + const EALREADY: number; + const EBADF: number; + const EBADMSG: number; + const EBUSY: number; + const ECANCELED: number; + const ECHILD: number; + const ECONNABORTED: number; + const ECONNREFUSED: number; + const ECONNRESET: number; + const EDEADLK: number; + const EDESTADDRREQ: number; + const EDOM: number; + const EDQUOT: number; + const EEXIST: number; + const EFAULT: number; + const EFBIG: number; + const EHOSTUNREACH: number; + const EIDRM: number; + const EILSEQ: number; + const EINPROGRESS: number; + const EINTR: number; + const EINVAL: number; + const EIO: number; + const EISCONN: number; + const EISDIR: number; + const ELOOP: number; + const EMFILE: number; + const EMLINK: number; + const EMSGSIZE: number; + const EMULTIHOP: number; + const ENAMETOOLONG: number; + const ENETDOWN: number; + const ENETRESET: number; + const ENETUNREACH: number; + const ENFILE: number; + const ENOBUFS: number; + const ENODATA: number; + const ENODEV: number; + const ENOENT: number; + const ENOEXEC: number; + const ENOLCK: number; + const ENOLINK: number; + const ENOMEM: number; + const ENOMSG: number; + const ENOPROTOOPT: number; + const ENOSPC: number; + const ENOSR: number; + const ENOSTR: number; + const ENOSYS: number; + const ENOTCONN: number; + const ENOTDIR: number; + const ENOTEMPTY: number; + const ENOTSOCK: number; + const ENOTSUP: number; + const ENOTTY: number; + const ENXIO: number; + const EOPNOTSUPP: number; + const EOVERFLOW: number; + const EPERM: number; + const EPIPE: number; + const EPROTO: number; + const EPROTONOSUPPORT: number; + const EPROTOTYPE: number; + const ERANGE: number; + const EROFS: number; + const ESPIPE: number; + const ESRCH: number; + const ESTALE: number; + const ETIME: number; + const ETIMEDOUT: number; + const ETXTBSY: number; + const EWOULDBLOCK: number; + const EXDEV: number; + const WSAEINTR: number; + const WSAEBADF: number; + const WSAEACCES: number; + const WSAEFAULT: number; + const WSAEINVAL: number; + const WSAEMFILE: number; + const WSAEWOULDBLOCK: number; + const WSAEINPROGRESS: number; + const WSAEALREADY: number; + const WSAENOTSOCK: number; + const WSAEDESTADDRREQ: number; + const WSAEMSGSIZE: number; + const WSAEPROTOTYPE: number; + const WSAENOPROTOOPT: number; + const WSAEPROTONOSUPPORT: number; + const WSAESOCKTNOSUPPORT: number; + const WSAEOPNOTSUPP: number; + const WSAEPFNOSUPPORT: number; + const WSAEAFNOSUPPORT: number; + const WSAEADDRINUSE: number; + const WSAEADDRNOTAVAIL: number; + const WSAENETDOWN: number; + const WSAENETUNREACH: number; + const WSAENETRESET: number; + const WSAECONNABORTED: number; + const WSAECONNRESET: number; + const WSAENOBUFS: number; + const WSAEISCONN: number; + const WSAENOTCONN: number; + const WSAESHUTDOWN: number; + const WSAETOOMANYREFS: number; + const WSAETIMEDOUT: number; + const WSAECONNREFUSED: number; + const WSAELOOP: number; + const WSAENAMETOOLONG: number; + const WSAEHOSTDOWN: number; + const WSAEHOSTUNREACH: number; + const WSAENOTEMPTY: number; + const WSAEPROCLIM: number; + const WSAEUSERS: number; + const WSAEDQUOT: number; + const WSAESTALE: number; + const WSAEREMOTE: number; + const WSASYSNOTREADY: number; + const WSAVERNOTSUPPORTED: number; + const WSANOTINITIALISED: number; + const WSAEDISCON: number; + const WSAENOMORE: number; + const WSAECANCELLED: number; + const WSAEINVALIDPROCTABLE: number; + const WSAEINVALIDPROVIDER: number; + const WSAEPROVIDERFAILEDINIT: number; + const WSASYSCALLFAILURE: number; + const WSASERVICE_NOT_FOUND: number; + const WSATYPE_NOT_FOUND: number; + const WSA_E_NO_MORE: number; + const WSA_E_CANCELLED: number; + const WSAEREFUSED: number; + } + namespace dlopen { + const RTLD_LAZY: number; + const RTLD_NOW: number; + const RTLD_GLOBAL: number; + const RTLD_LOCAL: number; + const RTLD_DEEPBIND: number; + } + namespace priority { + const PRIORITY_LOW: number; + const PRIORITY_BELOW_NORMAL: number; + const PRIORITY_NORMAL: number; + const PRIORITY_ABOVE_NORMAL: number; + const PRIORITY_HIGH: number; + const PRIORITY_HIGHEST: number; + } + } + const devNull: string; + /** + * The operating system-specific end-of-line marker. + * * `\n` on POSIX + * * `\r\n` on Windows + */ + const EOL: string; + /** + * Returns the operating system CPU architecture for which the Node.js binary was + * compiled. Possible values are `'arm'`, `'arm64'`, `'ia32'`, `'loong64'`, `'mips'`, `'mipsel'`, `'ppc'`, `'ppc64'`, `'riscv64'`, `'s390'`, `'s390x'`, + * and `'x64'`. + * + * The return value is equivalent to [process.arch](https://nodejs.org/docs/latest-v22.x/api/process.html#processarch). + * @since v0.5.0 + */ + function arch(): string; + /** + * Returns a string identifying the kernel version. + * + * On POSIX systems, the operating system release is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `RtlGetVersion()` is used, and if it is not + * available, `GetVersionExW()` will be used. See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v13.11.0, v12.17.0 + */ + function version(): string; + /** + * Returns a string identifying the operating system platform for which + * the Node.js binary was compiled. The value is set at compile time. + * Possible values are `'aix'`, `'darwin'`, `'freebsd'`, `'linux'`, `'openbsd'`, `'sunos'`, and `'win32'`. + * + * The return value is equivalent to `process.platform`. + * + * The value `'android'` may also be returned if Node.js is built on the Android + * operating system. [Android support is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os). + * @since v0.5.0 + */ + function platform(): NodeJS.Platform; + /** + * Returns the machine type as a string, such as `arm`, `arm64`, `aarch64`, `mips`, `mips64`, `ppc64`, `ppc64le`, `s390`, `s390x`, `i386`, `i686`, `x86_64`. + * + * On POSIX systems, the machine type is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `RtlGetVersion()` is used, and if it is not + * available, `GetVersionExW()` will be used. See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v18.9.0, v16.18.0 + */ + function machine(): string; + /** + * Returns the operating system's default directory for temporary files as a + * string. + * @since v0.9.9 + */ + function tmpdir(): string; + /** + * Returns a string identifying the endianness of the CPU for which the Node.js + * binary was compiled. + * + * Possible values are `'BE'` for big endian and `'LE'` for little endian. + * @since v0.9.4 + */ + function endianness(): "BE" | "LE"; + /** + * Returns the scheduling priority for the process specified by `pid`. If `pid` is + * not provided or is `0`, the priority of the current process is returned. + * @since v10.10.0 + * @param [pid=0] The process ID to retrieve scheduling priority for. + */ + function getPriority(pid?: number): number; + /** + * Attempts to set the scheduling priority for the process specified by `pid`. If `pid` is not provided or is `0`, the process ID of the current process is used. + * + * The `priority` input must be an integer between `-20` (high priority) and `19` (low priority). Due to differences between Unix priority levels and Windows + * priority classes, `priority` is mapped to one of six priority constants in `os.constants.priority`. When retrieving a process priority level, this range + * mapping may cause the return value to be slightly different on Windows. To avoid + * confusion, set `priority` to one of the priority constants. + * + * On Windows, setting priority to `PRIORITY_HIGHEST` requires elevated user + * privileges. Otherwise the set priority will be silently reduced to `PRIORITY_HIGH`. + * @since v10.10.0 + * @param [pid=0] The process ID to set scheduling priority for. + * @param priority The scheduling priority to assign to the process. + */ + function setPriority(priority: number): void; + function setPriority(pid: number, priority: number): void; +} +declare module "node:os" { + export * from "os"; +} diff --git a/libcore/node_modules/@types/node/package.json b/libcore/node_modules/@types/node/package.json new file mode 100644 index 0000000..d0b303a --- /dev/null +++ b/libcore/node_modules/@types/node/package.json @@ -0,0 +1,217 @@ +{ + "name": "@types/node", + "version": "22.5.4", + "description": "TypeScript definitions for node", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node", + "license": "MIT", + "contributors": [ + { + "name": "Microsoft TypeScript", + "githubUsername": "Microsoft", + "url": "https://github.com/Microsoft" + }, + { + "name": "Alberto Schiabel", + "githubUsername": "jkomyno", + "url": "https://github.com/jkomyno" + }, + { + "name": "Alvis HT Tang", + "githubUsername": "alvis", + "url": "https://github.com/alvis" + }, + { + "name": "Andrew Makarov", + "githubUsername": "r3nya", + "url": "https://github.com/r3nya" + }, + { + "name": "Benjamin Toueg", + "githubUsername": "btoueg", + "url": "https://github.com/btoueg" + }, + { + "name": "Chigozirim C.", + "githubUsername": "smac89", + "url": "https://github.com/smac89" + }, + { + "name": "David Junger", + "githubUsername": "touffy", + "url": "https://github.com/touffy" + }, + { + "name": "Deividas Bakanas", + "githubUsername": "DeividasBakanas", + "url": "https://github.com/DeividasBakanas" + }, + { + "name": "Eugene Y. Q. Shen", + "githubUsername": "eyqs", + "url": "https://github.com/eyqs" + }, + { + "name": "Hannes Magnusson", + "githubUsername": "Hannes-Magnusson-CK", + "url": "https://github.com/Hannes-Magnusson-CK" + }, + { + "name": "Huw", + "githubUsername": "hoo29", + "url": "https://github.com/hoo29" + }, + { + "name": "Kelvin Jin", + "githubUsername": "kjin", + "url": "https://github.com/kjin" + }, + { + "name": "Klaus Meinhardt", + "githubUsername": "ajafff", + "url": "https://github.com/ajafff" + }, + { + "name": "Lishude", + "githubUsername": "islishude", + "url": "https://github.com/islishude" + }, + { + "name": "Mariusz Wiktorczyk", + "githubUsername": "mwiktorczyk", + "url": "https://github.com/mwiktorczyk" + }, + { + "name": "Mohsen Azimi", + "githubUsername": "mohsen1", + "url": "https://github.com/mohsen1" + }, + { + "name": "Nikita Galkin", + "githubUsername": "galkin", + "url": "https://github.com/galkin" + }, + { + "name": "Parambir Singh", + "githubUsername": "parambirs", + "url": "https://github.com/parambirs" + }, + { + "name": "Sebastian Silbermann", + "githubUsername": "eps1lon", + "url": "https://github.com/eps1lon" + }, + { + "name": "Thomas den Hollander", + "githubUsername": "ThomasdenH", + "url": "https://github.com/ThomasdenH" + }, + { + "name": "Wilco Bakker", + "githubUsername": "WilcoBakker", + "url": "https://github.com/WilcoBakker" + }, + { + "name": "wwwy3y3", + "githubUsername": "wwwy3y3", + "url": "https://github.com/wwwy3y3" + }, + { + "name": "Samuel Ainsworth", + "githubUsername": "samuela", + "url": "https://github.com/samuela" + }, + { + "name": "Kyle Uehlein", + "githubUsername": "kuehlein", + "url": "https://github.com/kuehlein" + }, + { + "name": "Thanik Bhongbhibhat", + "githubUsername": "bhongy", + "url": "https://github.com/bhongy" + }, + { + "name": "Marcin Kopacz", + "githubUsername": "chyzwar", + "url": "https://github.com/chyzwar" + }, + { + "name": "Trivikram Kamat", + "githubUsername": "trivikr", + "url": "https://github.com/trivikr" + }, + { + "name": "Junxiao Shi", + "githubUsername": "yoursunny", + "url": "https://github.com/yoursunny" + }, + { + "name": "Ilia Baryshnikov", + "githubUsername": "qwelias", + "url": "https://github.com/qwelias" + }, + { + "name": "ExE Boss", + "githubUsername": "ExE-Boss", + "url": "https://github.com/ExE-Boss" + }, + { + "name": "Piotr Błażejewicz", + "githubUsername": "peterblazejewicz", + "url": "https://github.com/peterblazejewicz" + }, + { + "name": "Anna Henningsen", + "githubUsername": "addaleax", + "url": "https://github.com/addaleax" + }, + { + "name": "Victor Perin", + "githubUsername": "victorperin", + "url": "https://github.com/victorperin" + }, + { + "name": "Yongsheng Zhang", + "githubUsername": "ZYSzys", + "url": "https://github.com/ZYSzys" + }, + { + "name": "NodeJS Contributors", + "githubUsername": "NodeJS", + "url": "https://github.com/NodeJS" + }, + { + "name": "Linus Unnebäck", + "githubUsername": "LinusU", + "url": "https://github.com/LinusU" + }, + { + "name": "wafuwafu13", + "githubUsername": "wafuwafu13", + "url": "https://github.com/wafuwafu13" + }, + { + "name": "Matteo Collina", + "githubUsername": "mcollina", + "url": "https://github.com/mcollina" + }, + { + "name": "Dmitry Semigradsky", + "githubUsername": "Semigradsky", + "url": "https://github.com/Semigradsky" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/node" + }, + "scripts": {}, + "dependencies": { + "undici-types": "~6.19.2" + }, + "typesPublisherContentHash": "6ee9a11eba834031423800320320aa873d6bf2b6f33603c13a2aa9d90b3803ee", + "typeScriptVersion": "4.8" +} \ No newline at end of file diff --git a/libcore/node_modules/@types/node/path.d.ts b/libcore/node_modules/@types/node/path.d.ts new file mode 100644 index 0000000..e66781f --- /dev/null +++ b/libcore/node_modules/@types/node/path.d.ts @@ -0,0 +1,200 @@ +declare module "path/posix" { + import path = require("path"); + export = path; +} +declare module "path/win32" { + import path = require("path"); + export = path; +} +/** + * The `node:path` module provides utilities for working with file and directory + * paths. It can be accessed using: + * + * ```js + * const path = require('node:path'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/path.js) + */ +declare module "path" { + namespace path { + /** + * A parsed path object generated by path.parse() or consumed by path.format(). + */ + interface ParsedPath { + /** + * The root of the path such as '/' or 'c:\' + */ + root: string; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir: string; + /** + * The file name including extension (if any) such as 'index.html' + */ + base: string; + /** + * The file extension (if any) such as '.html' + */ + ext: string; + /** + * The file name without extension (if any) such as 'index' + */ + name: string; + } + interface FormatInputPathObject { + /** + * The root of the path such as '/' or 'c:\' + */ + root?: string | undefined; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir?: string | undefined; + /** + * The file name including extension (if any) such as 'index.html' + */ + base?: string | undefined; + /** + * The file extension (if any) such as '.html' + */ + ext?: string | undefined; + /** + * The file name without extension (if any) such as 'index' + */ + name?: string | undefined; + } + interface PlatformPath { + /** + * Normalize a string path, reducing '..' and '.' parts. + * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. + * + * @param path string path to normalize. + * @throws {TypeError} if `path` is not a string. + */ + normalize(path: string): string; + /** + * Join all arguments together and normalize the resulting path. + * + * @param paths paths to join. + * @throws {TypeError} if any of the path segments is not a string. + */ + join(...paths: string[]): string; + /** + * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. + * + * Starting from leftmost {from} parameter, resolves {to} to an absolute path. + * + * If {to} isn't already absolute, {from} arguments are prepended in right to left order, + * until an absolute path is found. If after using all {from} paths still no absolute path is found, + * the current working directory is used as well. The resulting path is normalized, + * and trailing slashes are removed unless the path gets resolved to the root directory. + * + * @param paths A sequence of paths or path segments. + * @throws {TypeError} if any of the arguments is not a string. + */ + resolve(...paths: string[]): string; + /** + * The `path.matchesGlob()` method determines if `path` matches the `pattern`. + * @param path The path to glob-match against. + * @param pattern The glob to check the path against. + * @returns Whether or not the `path` matched the `pattern`. + * @throws {TypeError} if `path` or `pattern` are not strings. + * @since v22.5.0 + */ + matchesGlob(path: string, pattern: string): boolean; + /** + * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. + * + * If the given {path} is a zero-length string, `false` will be returned. + * + * @param path path to test. + * @throws {TypeError} if `path` is not a string. + */ + isAbsolute(path: string): boolean; + /** + * Solve the relative path from {from} to {to} based on the current working directory. + * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. + * + * @throws {TypeError} if either `from` or `to` is not a string. + */ + relative(from: string, to: string): string; + /** + * Return the directory name of a path. Similar to the Unix dirname command. + * + * @param path the path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + dirname(path: string): string; + /** + * Return the last portion of a path. Similar to the Unix basename command. + * Often used to extract the file name from a fully qualified path. + * + * @param path the path to evaluate. + * @param suffix optionally, an extension to remove from the result. + * @throws {TypeError} if `path` is not a string or if `ext` is given and is not a string. + */ + basename(path: string, suffix?: string): string; + /** + * Return the extension of the path, from the last '.' to end of string in the last portion of the path. + * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string. + * + * @param path the path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + extname(path: string): string; + /** + * The platform-specific file separator. '\\' or '/'. + */ + readonly sep: "\\" | "/"; + /** + * The platform-specific file delimiter. ';' or ':'. + */ + readonly delimiter: ";" | ":"; + /** + * Returns an object from a path string - the opposite of format(). + * + * @param path path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + parse(path: string): ParsedPath; + /** + * Returns a path string from an object - the opposite of parse(). + * + * @param pathObject path to evaluate. + */ + format(pathObject: FormatInputPathObject): string; + /** + * On Windows systems only, returns an equivalent namespace-prefixed path for the given path. + * If path is not a string, path will be returned without modifications. + * This method is meaningful only on Windows system. + * On POSIX systems, the method is non-operational and always returns path without modifications. + */ + toNamespacedPath(path: string): string; + /** + * Posix specific pathing. + * Same as parent object on posix. + */ + readonly posix: PlatformPath; + /** + * Windows specific pathing. + * Same as parent object on windows + */ + readonly win32: PlatformPath; + } + } + const path: path.PlatformPath; + export = path; +} +declare module "node:path" { + import path = require("path"); + export = path; +} +declare module "node:path/posix" { + import path = require("path/posix"); + export = path; +} +declare module "node:path/win32" { + import path = require("path/win32"); + export = path; +} diff --git a/libcore/node_modules/@types/node/perf_hooks.d.ts b/libcore/node_modules/@types/node/perf_hooks.d.ts new file mode 100644 index 0000000..6092bd4 --- /dev/null +++ b/libcore/node_modules/@types/node/perf_hooks.d.ts @@ -0,0 +1,941 @@ +/** + * This module provides an implementation of a subset of the W3C [Web Performance APIs](https://w3c.github.io/perf-timing-primer/) as well as additional APIs for + * Node.js-specific performance measurements. + * + * Node.js supports the following [Web Performance APIs](https://w3c.github.io/perf-timing-primer/): + * + * * [High Resolution Time](https://www.w3.org/TR/hr-time-2) + * * [Performance Timeline](https://w3c.github.io/performance-timeline/) + * * [User Timing](https://www.w3.org/TR/user-timing/) + * * [Resource Timing](https://www.w3.org/TR/resource-timing-2/) + * + * ```js + * const { PerformanceObserver, performance } = require('node:perf_hooks'); + * + * const obs = new PerformanceObserver((items) => { + * console.log(items.getEntries()[0].duration); + * performance.clearMarks(); + * }); + * obs.observe({ type: 'measure' }); + * performance.measure('Start to Now'); + * + * performance.mark('A'); + * doSomeLongRunningProcess(() => { + * performance.measure('A to Now', 'A'); + * + * performance.mark('B'); + * performance.measure('A to B', 'A', 'B'); + * }); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/perf_hooks.js) + */ +declare module "perf_hooks" { + import { AsyncResource } from "node:async_hooks"; + type EntryType = + | "dns" // Node.js only + | "function" // Node.js only + | "gc" // Node.js only + | "http2" // Node.js only + | "http" // Node.js only + | "mark" // available on the Web + | "measure" // available on the Web + | "net" // Node.js only + | "node" // Node.js only + | "resource"; // available on the Web + interface NodeGCPerformanceDetail { + /** + * When `performanceEntry.entryType` is equal to 'gc', the `performance.kind` property identifies + * the type of garbage collection operation that occurred. + * See perf_hooks.constants for valid values. + */ + readonly kind?: number | undefined; + /** + * When `performanceEntry.entryType` is equal to 'gc', the `performance.flags` + * property contains additional information about garbage collection operation. + * See perf_hooks.constants for valid values. + */ + readonly flags?: number | undefined; + } + /** + * The constructor of this class is not exposed to users directly. + * @since v8.5.0 + */ + class PerformanceEntry { + protected constructor(); + /** + * The total number of milliseconds elapsed for this entry. This value will not + * be meaningful for all Performance Entry types. + * @since v8.5.0 + */ + readonly duration: number; + /** + * The name of the performance entry. + * @since v8.5.0 + */ + readonly name: string; + /** + * The high resolution millisecond timestamp marking the starting time of the + * Performance Entry. + * @since v8.5.0 + */ + readonly startTime: number; + /** + * The type of the performance entry. It may be one of: + * + * * `'node'` (Node.js only) + * * `'mark'` (available on the Web) + * * `'measure'` (available on the Web) + * * `'gc'` (Node.js only) + * * `'function'` (Node.js only) + * * `'http2'` (Node.js only) + * * `'http'` (Node.js only) + * @since v8.5.0 + */ + readonly entryType: EntryType; + /** + * Additional detail specific to the `entryType`. + * @since v16.0.0 + */ + readonly detail?: NodeGCPerformanceDetail | unknown | undefined; // TODO: Narrow this based on entry type. + toJSON(): any; + } + /** + * Exposes marks created via the `Performance.mark()` method. + * @since v18.2.0, v16.17.0 + */ + class PerformanceMark extends PerformanceEntry { + readonly duration: 0; + readonly entryType: "mark"; + } + /** + * Exposes measures created via the `Performance.measure()` method. + * + * The constructor of this class is not exposed to users directly. + * @since v18.2.0, v16.17.0 + */ + class PerformanceMeasure extends PerformanceEntry { + readonly entryType: "measure"; + } + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Provides timing details for Node.js itself. The constructor of this class + * is not exposed to users. + * @since v8.5.0 + */ + class PerformanceNodeTiming extends PerformanceEntry { + readonly entryType: "node"; + /** + * The high resolution millisecond timestamp at which the Node.js process + * completed bootstrapping. If bootstrapping has not yet finished, the property + * has the value of -1. + * @since v8.5.0 + */ + readonly bootstrapComplete: number; + /** + * The high resolution millisecond timestamp at which the Node.js environment was + * initialized. + * @since v8.5.0 + */ + readonly environment: number; + /** + * The high resolution millisecond timestamp of the amount of time the event loop + * has been idle within the event loop's event provider (e.g. `epoll_wait`). This + * does not take CPU usage into consideration. If the event loop has not yet + * started (e.g., in the first tick of the main script), the property has the + * value of 0. + * @since v14.10.0, v12.19.0 + */ + readonly idleTime: number; + /** + * The high resolution millisecond timestamp at which the Node.js event loop + * exited. If the event loop has not yet exited, the property has the value of -1\. + * It can only have a value of not -1 in a handler of the `'exit'` event. + * @since v8.5.0 + */ + readonly loopExit: number; + /** + * The high resolution millisecond timestamp at which the Node.js event loop + * started. If the event loop has not yet started (e.g., in the first tick of the + * main script), the property has the value of -1. + * @since v8.5.0 + */ + readonly loopStart: number; + /** + * The high resolution millisecond timestamp at which the Node.js process was initialized. + * @since v8.5.0 + */ + readonly nodeStart: number; + /** + * The high resolution millisecond timestamp at which the V8 platform was + * initialized. + * @since v8.5.0 + */ + readonly v8Start: number; + } + interface EventLoopUtilization { + idle: number; + active: number; + utilization: number; + } + /** + * @param utilization1 The result of a previous call to `eventLoopUtilization()`. + * @param utilization2 The result of a previous call to `eventLoopUtilization()` prior to `utilization1`. + */ + type EventLoopUtilityFunction = ( + utilization1?: EventLoopUtilization, + utilization2?: EventLoopUtilization, + ) => EventLoopUtilization; + interface MarkOptions { + /** + * Additional optional detail to include with the mark. + */ + detail?: unknown | undefined; + /** + * An optional timestamp to be used as the mark time. + * @default `performance.now()` + */ + startTime?: number | undefined; + } + interface MeasureOptions { + /** + * Additional optional detail to include with the mark. + */ + detail?: unknown | undefined; + /** + * Duration between start and end times. + */ + duration?: number | undefined; + /** + * Timestamp to be used as the end time, or a string identifying a previously recorded mark. + */ + end?: number | string | undefined; + /** + * Timestamp to be used as the start time, or a string identifying a previously recorded mark. + */ + start?: number | string | undefined; + } + interface TimerifyOptions { + /** + * A histogram object created using `perf_hooks.createHistogram()` that will record runtime + * durations in nanoseconds. + */ + histogram?: RecordableHistogram | undefined; + } + interface Performance { + /** + * If `name` is not provided, removes all `PerformanceMark` objects from the Performance Timeline. + * If `name` is provided, removes only the named mark. + * @since v8.5.0 + */ + clearMarks(name?: string): void; + /** + * If `name` is not provided, removes all `PerformanceMeasure` objects from the Performance Timeline. + * If `name` is provided, removes only the named measure. + * @since v16.7.0 + */ + clearMeasures(name?: string): void; + /** + * If `name` is not provided, removes all `PerformanceResourceTiming` objects from the Resource Timeline. + * If `name` is provided, removes only the named resource. + * @since v18.2.0, v16.17.0 + */ + clearResourceTimings(name?: string): void; + /** + * eventLoopUtilization is similar to CPU utilization except that it is calculated using high precision wall-clock time. + * It represents the percentage of time the event loop has spent outside the event loop's event provider (e.g. epoll_wait). + * No other CPU idle time is taken into consideration. + */ + eventLoopUtilization: EventLoopUtilityFunction; + /** + * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime`. + * If you are only interested in performance entries of certain types or that have certain names, see + * `performance.getEntriesByType()` and `performance.getEntriesByName()`. + * @since v16.7.0 + */ + getEntries(): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime` + * whose `performanceEntry.name` is equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to `type`. + * @param name + * @param type + * @since v16.7.0 + */ + getEntriesByName(name: string, type?: EntryType): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime` + * whose `performanceEntry.entryType` is equal to `type`. + * @param type + * @since v16.7.0 + */ + getEntriesByType(type: EntryType): PerformanceEntry[]; + /** + * Creates a new `PerformanceMark` entry in the Performance Timeline. + * A `PerformanceMark` is a subclass of `PerformanceEntry` whose `performanceEntry.entryType` is always `'mark'`, + * and whose `performanceEntry.duration` is always `0`. + * Performance marks are used to mark specific significant moments in the Performance Timeline. + * + * The created `PerformanceMark` entry is put in the global Performance Timeline and can be queried with + * `performance.getEntries`, `performance.getEntriesByName`, and `performance.getEntriesByType`. When the observation is + * performed, the entries should be cleared from the global Performance Timeline manually with `performance.clearMarks`. + * @param name + */ + mark(name: string, options?: MarkOptions): PerformanceMark; + /** + * Creates a new `PerformanceResourceTiming` entry in the Resource Timeline. + * A `PerformanceResourceTiming` is a subclass of `PerformanceEntry` whose `performanceEntry.entryType` is always `'resource'`. + * Performance resources are used to mark moments in the Resource Timeline. + * @param timingInfo [Fetch Timing Info](https://fetch.spec.whatwg.org/#fetch-timing-info) + * @param requestedUrl The resource url + * @param initiatorType The initiator name, e.g: 'fetch' + * @param global + * @param cacheMode The cache mode must be an empty string ('') or 'local' + * @param bodyInfo [Fetch Response Body Info](https://fetch.spec.whatwg.org/#response-body-info) + * @param responseStatus The response's status code + * @param deliveryType The delivery type. Default: ''. + * @since v18.2.0, v16.17.0 + */ + markResourceTiming( + timingInfo: object, + requestedUrl: string, + initiatorType: string, + global: object, + cacheMode: "" | "local", + bodyInfo: object, + responseStatus: number, + deliveryType?: string, + ): PerformanceResourceTiming; + /** + * Creates a new PerformanceMeasure entry in the Performance Timeline. + * A PerformanceMeasure is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'measure', + * and whose performanceEntry.duration measures the number of milliseconds elapsed since startMark and endMark. + * + * The startMark argument may identify any existing PerformanceMark in the the Performance Timeline, or may identify + * any of the timestamp properties provided by the PerformanceNodeTiming class. If the named startMark does not exist, + * then startMark is set to timeOrigin by default. + * + * The endMark argument must identify any existing PerformanceMark in the the Performance Timeline or any of the timestamp + * properties provided by the PerformanceNodeTiming class. If the named endMark does not exist, an error will be thrown. + * @param name + * @param startMark + * @param endMark + * @return The PerformanceMeasure entry that was created + */ + measure(name: string, startMark?: string, endMark?: string): PerformanceMeasure; + measure(name: string, options: MeasureOptions): PerformanceMeasure; + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * An instance of the `PerformanceNodeTiming` class that provides performance metrics for specific Node.js operational milestones. + * @since v8.5.0 + */ + readonly nodeTiming: PerformanceNodeTiming; + /** + * Returns the current high resolution millisecond timestamp, where 0 represents the start of the current `node` process. + * @since v8.5.0 + */ + now(): number; + /** + * Sets the global performance resource timing buffer size to the specified number of "resource" type performance entry objects. + * + * By default the max buffer size is set to 250. + * @since v18.8.0 + */ + setResourceTimingBufferSize(maxSize: number): void; + /** + * The [`timeOrigin`](https://w3c.github.io/hr-time/#dom-performance-timeorigin) specifies the high resolution millisecond timestamp + * at which the current `node` process began, measured in Unix time. + * @since v8.5.0 + */ + readonly timeOrigin: number; + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Wraps a function within a new function that measures the running time of the wrapped function. + * A `PerformanceObserver` must be subscribed to the `'function'` event type in order for the timing details to be accessed. + * + * ```js + * const { + * performance, + * PerformanceObserver, + * } = require('node:perf_hooks'); + * + * function someFunction() { + * console.log('hello world'); + * } + * + * const wrapped = performance.timerify(someFunction); + * + * const obs = new PerformanceObserver((list) => { + * console.log(list.getEntries()[0].duration); + * + * performance.clearMarks(); + * performance.clearMeasures(); + * obs.disconnect(); + * }); + * obs.observe({ entryTypes: ['function'] }); + * + * // A performance timeline entry will be created + * wrapped(); + * ``` + * + * If the wrapped function returns a promise, a finally handler will be attached to the promise and the duration will be reported + * once the finally handler is invoked. + * @param fn + */ + timerify any>(fn: T, options?: TimerifyOptions): T; + /** + * An object which is JSON representation of the performance object. It is similar to + * [`window.performance.toJSON`](https://developer.mozilla.org/en-US/docs/Web/API/Performance/toJSON) in browsers. + * @since v16.1.0 + */ + toJSON(): any; + } + class PerformanceObserverEntryList { + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime`. + * + * ```js + * const { + * performance, + * PerformanceObserver, + * } = require('node:perf_hooks'); + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntries()); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 81.465639, + * * duration: 0, + * * detail: null + * * }, + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 81.860064, + * * duration: 0, + * * detail: null + * * } + * * ] + * + * performance.clearMarks(); + * performance.clearMeasures(); + * observer.disconnect(); + * }); + * obs.observe({ type: 'mark' }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntries(): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime` whose `performanceEntry.name` is + * equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to`type`. + * + * ```js + * const { + * performance, + * PerformanceObserver, + * } = require('node:perf_hooks'); + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntriesByName('meow')); + * + * * [ + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 98.545991, + * * duration: 0, + * * detail: null + * * } + * * ] + * + * console.log(perfObserverList.getEntriesByName('nope')); // [] + * + * console.log(perfObserverList.getEntriesByName('test', 'mark')); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 63.518931, + * * duration: 0, + * * detail: null + * * } + * * ] + * + * console.log(perfObserverList.getEntriesByName('test', 'measure')); // [] + * + * performance.clearMarks(); + * performance.clearMeasures(); + * observer.disconnect(); + * }); + * obs.observe({ entryTypes: ['mark', 'measure'] }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntriesByName(name: string, type?: EntryType): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime` whose `performanceEntry.entryType` is equal to `type`. + * + * ```js + * const { + * performance, + * PerformanceObserver, + * } = require('node:perf_hooks'); + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntriesByType('mark')); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 55.897834, + * * duration: 0, + * * detail: null + * * }, + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 56.350146, + * * duration: 0, + * * detail: null + * * } + * * ] + * + * performance.clearMarks(); + * performance.clearMeasures(); + * observer.disconnect(); + * }); + * obs.observe({ type: 'mark' }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntriesByType(type: EntryType): PerformanceEntry[]; + } + type PerformanceObserverCallback = (list: PerformanceObserverEntryList, observer: PerformanceObserver) => void; + /** + * @since v8.5.0 + */ + class PerformanceObserver extends AsyncResource { + constructor(callback: PerformanceObserverCallback); + /** + * Disconnects the `PerformanceObserver` instance from all notifications. + * @since v8.5.0 + */ + disconnect(): void; + /** + * Subscribes the `PerformanceObserver` instance to notifications of new `PerformanceEntry` instances identified either by `options.entryTypes` or `options.type`: + * + * ```js + * const { + * performance, + * PerformanceObserver, + * } = require('node:perf_hooks'); + * + * const obs = new PerformanceObserver((list, observer) => { + * // Called once asynchronously. `list` contains three items. + * }); + * obs.observe({ type: 'mark' }); + * + * for (let n = 0; n < 3; n++) + * performance.mark(`test${n}`); + * ``` + * @since v8.5.0 + */ + observe( + options: + | { + entryTypes: readonly EntryType[]; + buffered?: boolean | undefined; + } + | { + type: EntryType; + buffered?: boolean | undefined; + }, + ): void; + } + /** + * Provides detailed network timing data regarding the loading of an application's resources. + * + * The constructor of this class is not exposed to users directly. + * @since v18.2.0, v16.17.0 + */ + class PerformanceResourceTiming extends PerformanceEntry { + readonly entryType: "resource"; + protected constructor(); + /** + * The high resolution millisecond timestamp at immediately before dispatching the `fetch` + * request. If the resource is not intercepted by a worker the property will always return 0. + * @since v18.2.0, v16.17.0 + */ + readonly workerStart: number; + /** + * The high resolution millisecond timestamp that represents the start time of the fetch which + * initiates the redirect. + * @since v18.2.0, v16.17.0 + */ + readonly redirectStart: number; + /** + * The high resolution millisecond timestamp that will be created immediately after receiving + * the last byte of the response of the last redirect. + * @since v18.2.0, v16.17.0 + */ + readonly redirectEnd: number; + /** + * The high resolution millisecond timestamp immediately before the Node.js starts to fetch the resource. + * @since v18.2.0, v16.17.0 + */ + readonly fetchStart: number; + /** + * The high resolution millisecond timestamp immediately before the Node.js starts the domain name lookup + * for the resource. + * @since v18.2.0, v16.17.0 + */ + readonly domainLookupStart: number; + /** + * The high resolution millisecond timestamp representing the time immediately after the Node.js finished + * the domain name lookup for the resource. + * @since v18.2.0, v16.17.0 + */ + readonly domainLookupEnd: number; + /** + * The high resolution millisecond timestamp representing the time immediately before Node.js starts to + * establish the connection to the server to retrieve the resource. + * @since v18.2.0, v16.17.0 + */ + readonly connectStart: number; + /** + * The high resolution millisecond timestamp representing the time immediately after Node.js finishes + * establishing the connection to the server to retrieve the resource. + * @since v18.2.0, v16.17.0 + */ + readonly connectEnd: number; + /** + * The high resolution millisecond timestamp representing the time immediately before Node.js starts the + * handshake process to secure the current connection. + * @since v18.2.0, v16.17.0 + */ + readonly secureConnectionStart: number; + /** + * The high resolution millisecond timestamp representing the time immediately before Node.js receives the + * first byte of the response from the server. + * @since v18.2.0, v16.17.0 + */ + readonly requestStart: number; + /** + * The high resolution millisecond timestamp representing the time immediately after Node.js receives the + * last byte of the resource or immediately before the transport connection is closed, whichever comes first. + * @since v18.2.0, v16.17.0 + */ + readonly responseEnd: number; + /** + * A number representing the size (in octets) of the fetched resource. The size includes the response header + * fields plus the response payload body. + * @since v18.2.0, v16.17.0 + */ + readonly transferSize: number; + /** + * A number representing the size (in octets) received from the fetch (HTTP or cache), of the payload body, before + * removing any applied content-codings. + * @since v18.2.0, v16.17.0 + */ + readonly encodedBodySize: number; + /** + * A number representing the size (in octets) received from the fetch (HTTP or cache), of the message body, after + * removing any applied content-codings. + * @since v18.2.0, v16.17.0 + */ + readonly decodedBodySize: number; + /** + * Returns a `object` that is the JSON representation of the `PerformanceResourceTiming` object + * @since v18.2.0, v16.17.0 + */ + toJSON(): any; + } + namespace constants { + const NODE_PERFORMANCE_GC_MAJOR: number; + const NODE_PERFORMANCE_GC_MINOR: number; + const NODE_PERFORMANCE_GC_INCREMENTAL: number; + const NODE_PERFORMANCE_GC_WEAKCB: number; + const NODE_PERFORMANCE_GC_FLAGS_NO: number; + const NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED: number; + const NODE_PERFORMANCE_GC_FLAGS_FORCED: number; + const NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING: number; + const NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE: number; + const NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY: number; + const NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE: number; + } + const performance: Performance; + interface EventLoopMonitorOptions { + /** + * The sampling rate in milliseconds. + * Must be greater than zero. + * @default 10 + */ + resolution?: number | undefined; + } + interface Histogram { + /** + * The number of samples recorded by the histogram. + * @since v17.4.0, v16.14.0 + */ + readonly count: number; + /** + * The number of samples recorded by the histogram. + * v17.4.0, v16.14.0 + */ + readonly countBigInt: bigint; + /** + * The number of times the event loop delay exceeded the maximum 1 hour event + * loop delay threshold. + * @since v11.10.0 + */ + readonly exceeds: number; + /** + * The number of times the event loop delay exceeded the maximum 1 hour event loop delay threshold. + * @since v17.4.0, v16.14.0 + */ + readonly exceedsBigInt: bigint; + /** + * The maximum recorded event loop delay. + * @since v11.10.0 + */ + readonly max: number; + /** + * The maximum recorded event loop delay. + * v17.4.0, v16.14.0 + */ + readonly maxBigInt: number; + /** + * The mean of the recorded event loop delays. + * @since v11.10.0 + */ + readonly mean: number; + /** + * The minimum recorded event loop delay. + * @since v11.10.0 + */ + readonly min: number; + /** + * The minimum recorded event loop delay. + * v17.4.0, v16.14.0 + */ + readonly minBigInt: bigint; + /** + * Returns the value at the given percentile. + * @since v11.10.0 + * @param percentile A percentile value in the range (0, 100]. + */ + percentile(percentile: number): number; + /** + * Returns the value at the given percentile. + * @since v17.4.0, v16.14.0 + * @param percentile A percentile value in the range (0, 100]. + */ + percentileBigInt(percentile: number): bigint; + /** + * Returns a `Map` object detailing the accumulated percentile distribution. + * @since v11.10.0 + */ + readonly percentiles: Map; + /** + * Returns a `Map` object detailing the accumulated percentile distribution. + * @since v17.4.0, v16.14.0 + */ + readonly percentilesBigInt: Map; + /** + * Resets the collected histogram data. + * @since v11.10.0 + */ + reset(): void; + /** + * The standard deviation of the recorded event loop delays. + * @since v11.10.0 + */ + readonly stddev: number; + } + interface IntervalHistogram extends Histogram { + /** + * Enables the update interval timer. Returns `true` if the timer was + * started, `false` if it was already started. + * @since v11.10.0 + */ + enable(): boolean; + /** + * Disables the update interval timer. Returns `true` if the timer was + * stopped, `false` if it was already stopped. + * @since v11.10.0 + */ + disable(): boolean; + } + interface RecordableHistogram extends Histogram { + /** + * @since v15.9.0, v14.18.0 + * @param val The amount to record in the histogram. + */ + record(val: number | bigint): void; + /** + * Calculates the amount of time (in nanoseconds) that has passed since the + * previous call to `recordDelta()` and records that amount in the histogram. + * @since v15.9.0, v14.18.0 + */ + recordDelta(): void; + /** + * Adds the values from `other` to this histogram. + * @since v17.4.0, v16.14.0 + */ + add(other: RecordableHistogram): void; + } + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Creates an `IntervalHistogram` object that samples and reports the event loop + * delay over time. The delays will be reported in nanoseconds. + * + * Using a timer to detect approximate event loop delay works because the + * execution of timers is tied specifically to the lifecycle of the libuv + * event loop. That is, a delay in the loop will cause a delay in the execution + * of the timer, and those delays are specifically what this API is intended to + * detect. + * + * ```js + * const { monitorEventLoopDelay } = require('node:perf_hooks'); + * const h = monitorEventLoopDelay({ resolution: 20 }); + * h.enable(); + * // Do something. + * h.disable(); + * console.log(h.min); + * console.log(h.max); + * console.log(h.mean); + * console.log(h.stddev); + * console.log(h.percentiles); + * console.log(h.percentile(50)); + * console.log(h.percentile(99)); + * ``` + * @since v11.10.0 + */ + function monitorEventLoopDelay(options?: EventLoopMonitorOptions): IntervalHistogram; + interface CreateHistogramOptions { + /** + * The minimum recordable value. Must be an integer value greater than 0. + * @default 1 + */ + min?: number | bigint | undefined; + /** + * The maximum recordable value. Must be an integer value greater than min. + * @default Number.MAX_SAFE_INTEGER + */ + max?: number | bigint | undefined; + /** + * The number of accuracy digits. Must be a number between 1 and 5. + * @default 3 + */ + figures?: number | undefined; + } + /** + * Returns a `RecordableHistogram`. + * @since v15.9.0, v14.18.0 + */ + function createHistogram(options?: CreateHistogramOptions): RecordableHistogram; + import { + performance as _performance, + PerformanceEntry as _PerformanceEntry, + PerformanceMark as _PerformanceMark, + PerformanceMeasure as _PerformanceMeasure, + PerformanceObserver as _PerformanceObserver, + PerformanceObserverEntryList as _PerformanceObserverEntryList, + PerformanceResourceTiming as _PerformanceResourceTiming, + } from "perf_hooks"; + global { + /** + * `PerformanceEntry` is a global reference for `require('node:perf_hooks').PerformanceEntry` + * @see https://nodejs.org/docs/latest-v22.x/api/globals.html#performanceentry + * @since v19.0.0 + */ + var PerformanceEntry: typeof globalThis extends { + onmessage: any; + PerformanceEntry: infer T; + } ? T + : typeof _PerformanceEntry; + /** + * `PerformanceMark` is a global reference for `require('node:perf_hooks').PerformanceMark` + * @see https://nodejs.org/docs/latest-v22.x/api/globals.html#performancemark + * @since v19.0.0 + */ + var PerformanceMark: typeof globalThis extends { + onmessage: any; + PerformanceMark: infer T; + } ? T + : typeof _PerformanceMark; + /** + * `PerformanceMeasure` is a global reference for `require('node:perf_hooks').PerformanceMeasure` + * @see https://nodejs.org/docs/latest-v22.x/api/globals.html#performancemeasure + * @since v19.0.0 + */ + var PerformanceMeasure: typeof globalThis extends { + onmessage: any; + PerformanceMeasure: infer T; + } ? T + : typeof _PerformanceMeasure; + /** + * `PerformanceObserver` is a global reference for `require('node:perf_hooks').PerformanceObserver` + * @see https://nodejs.org/docs/latest-v22.x/api/globals.html#performanceobserver + * @since v19.0.0 + */ + var PerformanceObserver: typeof globalThis extends { + onmessage: any; + PerformanceObserver: infer T; + } ? T + : typeof _PerformanceObserver; + /** + * `PerformanceObserverEntryList` is a global reference for `require('node:perf_hooks').PerformanceObserverEntryList` + * @see https://nodejs.org/docs/latest-v22.x/api/globals.html#performanceobserverentrylist + * @since v19.0.0 + */ + var PerformanceObserverEntryList: typeof globalThis extends { + onmessage: any; + PerformanceObserverEntryList: infer T; + } ? T + : typeof _PerformanceObserverEntryList; + /** + * `PerformanceResourceTiming` is a global reference for `require('node:perf_hooks').PerformanceResourceTiming` + * @see https://nodejs.org/docs/latest-v22.x/api/globals.html#performanceresourcetiming + * @since v19.0.0 + */ + var PerformanceResourceTiming: typeof globalThis extends { + onmessage: any; + PerformanceResourceTiming: infer T; + } ? T + : typeof _PerformanceResourceTiming; + /** + * `performance` is a global reference for `require('node:perf_hooks').performance` + * @see https://nodejs.org/docs/latest-v22.x/api/globals.html#performance + * @since v16.0.0 + */ + var performance: typeof globalThis extends { + onmessage: any; + performance: infer T; + } ? T + : typeof _performance; + } +} +declare module "node:perf_hooks" { + export * from "perf_hooks"; +} diff --git a/libcore/node_modules/@types/node/process.d.ts b/libcore/node_modules/@types/node/process.d.ts new file mode 100644 index 0000000..e7fd20b --- /dev/null +++ b/libcore/node_modules/@types/node/process.d.ts @@ -0,0 +1,1912 @@ +declare module "process" { + import * as tty from "node:tty"; + import { Worker } from "node:worker_threads"; + + interface BuiltInModule { + "assert": typeof import("assert"); + "node:assert": typeof import("node:assert"); + "assert/strict": typeof import("assert/strict"); + "node:assert/strict": typeof import("node:assert/strict"); + "async_hooks": typeof import("async_hooks"); + "node:async_hooks": typeof import("node:async_hooks"); + "buffer": typeof import("buffer"); + "node:buffer": typeof import("node:buffer"); + "child_process": typeof import("child_process"); + "node:child_process": typeof import("node:child_process"); + "cluster": typeof import("cluster"); + "node:cluster": typeof import("node:cluster"); + "console": typeof import("console"); + "node:console": typeof import("node:console"); + "constants": typeof import("constants"); + "node:constants": typeof import("node:constants"); + "crypto": typeof import("crypto"); + "node:crypto": typeof import("node:crypto"); + "dgram": typeof import("dgram"); + "node:dgram": typeof import("node:dgram"); + "diagnostics_channel": typeof import("diagnostics_channel"); + "node:diagnostics_channel": typeof import("node:diagnostics_channel"); + "dns": typeof import("dns"); + "node:dns": typeof import("node:dns"); + "dns/promises": typeof import("dns/promises"); + "node:dns/promises": typeof import("node:dns/promises"); + "domain": typeof import("domain"); + "node:domain": typeof import("node:domain"); + "events": typeof import("events"); + "node:events": typeof import("node:events"); + "fs": typeof import("fs"); + "node:fs": typeof import("node:fs"); + "fs/promises": typeof import("fs/promises"); + "node:fs/promises": typeof import("node:fs/promises"); + "http": typeof import("http"); + "node:http": typeof import("node:http"); + "http2": typeof import("http2"); + "node:http2": typeof import("node:http2"); + "https": typeof import("https"); + "node:https": typeof import("node:https"); + "inspector": typeof import("inspector"); + "node:inspector": typeof import("node:inspector"); + "inspector/promises": typeof import("inspector/promises"); + "node:inspector/promises": typeof import("node:inspector/promises"); + "module": typeof import("module"); + "node:module": typeof import("node:module"); + "net": typeof import("net"); + "node:net": typeof import("node:net"); + "os": typeof import("os"); + "node:os": typeof import("node:os"); + "path": typeof import("path"); + "node:path": typeof import("node:path"); + "path/posix": typeof import("path/posix"); + "node:path/posix": typeof import("node:path/posix"); + "path/win32": typeof import("path/win32"); + "node:path/win32": typeof import("node:path/win32"); + "perf_hooks": typeof import("perf_hooks"); + "node:perf_hooks": typeof import("node:perf_hooks"); + "process": typeof import("process"); + "node:process": typeof import("node:process"); + "punycode": typeof import("punycode"); + "node:punycode": typeof import("node:punycode"); + "querystring": typeof import("querystring"); + "node:querystring": typeof import("node:querystring"); + "readline": typeof import("readline"); + "node:readline": typeof import("node:readline"); + "readline/promises": typeof import("readline/promises"); + "node:readline/promises": typeof import("node:readline/promises"); + "repl": typeof import("repl"); + "node:repl": typeof import("node:repl"); + "node:sea": typeof import("node:sea"); + "node:sqlite": typeof import("node:sqlite"); + "stream": typeof import("stream"); + "node:stream": typeof import("node:stream"); + "stream/consumers": typeof import("stream/consumers"); + "node:stream/consumers": typeof import("node:stream/consumers"); + "stream/promises": typeof import("stream/promises"); + "node:stream/promises": typeof import("node:stream/promises"); + "stream/web": typeof import("stream/web"); + "node:stream/web": typeof import("node:stream/web"); + "string_decoder": typeof import("string_decoder"); + "node:string_decoder": typeof import("node:string_decoder"); + "node:test": typeof import("node:test"); + "node:test/reporters": typeof import("node:test/reporters"); + "timers": typeof import("timers"); + "node:timers": typeof import("node:timers"); + "timers/promises": typeof import("timers/promises"); + "node:timers/promises": typeof import("node:timers/promises"); + "tls": typeof import("tls"); + "node:tls": typeof import("node:tls"); + "trace_events": typeof import("trace_events"); + "node:trace_events": typeof import("node:trace_events"); + "tty": typeof import("tty"); + "node:tty": typeof import("node:tty"); + "url": typeof import("url"); + "node:url": typeof import("node:url"); + "util": typeof import("util"); + "node:util": typeof import("node:util"); + "sys": typeof import("util"); + "node:sys": typeof import("node:util"); + "util/types": typeof import("util/types"); + "node:util/types": typeof import("node:util/types"); + "v8": typeof import("v8"); + "node:v8": typeof import("node:v8"); + "vm": typeof import("vm"); + "node:vm": typeof import("node:vm"); + "wasi": typeof import("wasi"); + "node:wasi": typeof import("node:wasi"); + "worker_threads": typeof import("worker_threads"); + "node:worker_threads": typeof import("node:worker_threads"); + "zlib": typeof import("zlib"); + "node:zlib": typeof import("node:zlib"); + } + global { + var process: NodeJS.Process; + namespace NodeJS { + // this namespace merge is here because these are specifically used + // as the type for process.stdin, process.stdout, and process.stderr. + // they can't live in tty.d.ts because we need to disambiguate the imported name. + interface ReadStream extends tty.ReadStream {} + interface WriteStream extends tty.WriteStream {} + interface MemoryUsageFn { + /** + * The `process.memoryUsage()` method iterate over each page to gather informations about memory + * usage which can be slow depending on the program memory allocations. + */ + (): MemoryUsage; + /** + * method returns an integer representing the Resident Set Size (RSS) in bytes. + */ + rss(): number; + } + interface MemoryUsage { + /** + * Resident Set Size, is the amount of space occupied in the main memory device (that is a subset of the total allocated memory) for the + * process, including all C++ and JavaScript objects and code. + */ + rss: number; + /** + * Refers to V8's memory usage. + */ + heapTotal: number; + /** + * Refers to V8's memory usage. + */ + heapUsed: number; + external: number; + /** + * Refers to memory allocated for `ArrayBuffer`s and `SharedArrayBuffer`s, including all Node.js Buffers. This is also included + * in the external value. When Node.js is used as an embedded library, this value may be `0` because allocations for `ArrayBuffer`s + * may not be tracked in that case. + */ + arrayBuffers: number; + } + interface CpuUsage { + user: number; + system: number; + } + interface ProcessRelease { + name: string; + sourceUrl?: string | undefined; + headersUrl?: string | undefined; + libUrl?: string | undefined; + lts?: string | undefined; + } + interface ProcessVersions extends Dict { + http_parser: string; + node: string; + v8: string; + ares: string; + uv: string; + zlib: string; + modules: string; + openssl: string; + } + type Platform = + | "aix" + | "android" + | "darwin" + | "freebsd" + | "haiku" + | "linux" + | "openbsd" + | "sunos" + | "win32" + | "cygwin" + | "netbsd"; + type Architecture = + | "arm" + | "arm64" + | "ia32" + | "loong64" + | "mips" + | "mipsel" + | "ppc" + | "ppc64" + | "riscv64" + | "s390" + | "s390x" + | "x64"; + type Signals = + | "SIGABRT" + | "SIGALRM" + | "SIGBUS" + | "SIGCHLD" + | "SIGCONT" + | "SIGFPE" + | "SIGHUP" + | "SIGILL" + | "SIGINT" + | "SIGIO" + | "SIGIOT" + | "SIGKILL" + | "SIGPIPE" + | "SIGPOLL" + | "SIGPROF" + | "SIGPWR" + | "SIGQUIT" + | "SIGSEGV" + | "SIGSTKFLT" + | "SIGSTOP" + | "SIGSYS" + | "SIGTERM" + | "SIGTRAP" + | "SIGTSTP" + | "SIGTTIN" + | "SIGTTOU" + | "SIGUNUSED" + | "SIGURG" + | "SIGUSR1" + | "SIGUSR2" + | "SIGVTALRM" + | "SIGWINCH" + | "SIGXCPU" + | "SIGXFSZ" + | "SIGBREAK" + | "SIGLOST" + | "SIGINFO"; + type UncaughtExceptionOrigin = "uncaughtException" | "unhandledRejection"; + type MultipleResolveType = "resolve" | "reject"; + type BeforeExitListener = (code: number) => void; + type DisconnectListener = () => void; + type ExitListener = (code: number) => void; + type RejectionHandledListener = (promise: Promise) => void; + type UncaughtExceptionListener = (error: Error, origin: UncaughtExceptionOrigin) => void; + /** + * Most of the time the unhandledRejection will be an Error, but this should not be relied upon + * as *anything* can be thrown/rejected, it is therefore unsafe to assume that the value is an Error. + */ + type UnhandledRejectionListener = (reason: unknown, promise: Promise) => void; + type WarningListener = (warning: Error) => void; + type MessageListener = (message: unknown, sendHandle: unknown) => void; + type SignalsListener = (signal: Signals) => void; + type MultipleResolveListener = ( + type: MultipleResolveType, + promise: Promise, + value: unknown, + ) => void; + type WorkerListener = (worker: Worker) => void; + interface Socket extends ReadWriteStream { + isTTY?: true | undefined; + } + // Alias for compatibility + interface ProcessEnv extends Dict { + /** + * Can be used to change the default timezone at runtime + */ + TZ?: string; + } + interface HRTime { + (time?: [number, number]): [number, number]; + /** + * The `bigint` version of the `{@link hrtime()}` method returning the current high-resolution real time in nanoseconds as a `bigint`. + * + * Unlike `{@link hrtime()}`, it does not support an additional time argument since the difference can just be computed directly by subtraction of the two `bigint`s. + * ```js + * import { hrtime } from 'node:process'; + * + * const start = hrtime.bigint(); + * // 191051479007711n + * + * setTimeout(() => { + * const end = hrtime.bigint(); + * // 191052633396993n + * + * console.log(`Benchmark took ${end - start} nanoseconds`); + * // Benchmark took 1154389282 nanoseconds + * }, 1000); + * ``` + */ + bigint(): bigint; + } + interface ProcessPermission { + /** + * Verifies that the process is able to access the given scope and reference. + * If no reference is provided, a global scope is assumed, for instance, `process.permission.has('fs.read')` + * will check if the process has ALL file system read permissions. + * + * The reference has a meaning based on the provided scope. For example, the reference when the scope is File System means files and folders. + * + * The available scopes are: + * + * * `fs` - All File System + * * `fs.read` - File System read operations + * * `fs.write` - File System write operations + * * `child` - Child process spawning operations + * * `worker` - Worker thread spawning operation + * + * ```js + * // Check if the process has permission to read the README file + * process.permission.has('fs.read', './README.md'); + * // Check if the process has read permission operations + * process.permission.has('fs.read'); + * ``` + * @since v20.0.0 + */ + has(scope: string, reference?: string): boolean; + } + interface ProcessReport { + /** + * Write reports in a compact format, single-line JSON, more easily consumable by log processing systems + * than the default multi-line format designed for human consumption. + * @since v13.12.0, v12.17.0 + */ + compact: boolean; + /** + * Directory where the report is written. + * The default value is the empty string, indicating that reports are written to the current + * working directory of the Node.js process. + */ + directory: string; + /** + * Filename where the report is written. If set to the empty string, the output filename will be comprised + * of a timestamp, PID, and sequence number. The default value is the empty string. + */ + filename: string; + /** + * Returns a JavaScript Object representation of a diagnostic report for the running process. + * The report's JavaScript stack trace is taken from `err`, if present. + */ + getReport(err?: Error): object; + /** + * If true, a diagnostic report is generated on fatal errors, + * such as out of memory errors or failed C++ assertions. + * @default false + */ + reportOnFatalError: boolean; + /** + * If true, a diagnostic report is generated when the process + * receives the signal specified by process.report.signal. + * @default false + */ + reportOnSignal: boolean; + /** + * If true, a diagnostic report is generated on uncaught exception. + * @default false + */ + reportOnUncaughtException: boolean; + /** + * The signal used to trigger the creation of a diagnostic report. + * @default 'SIGUSR2' + */ + signal: Signals; + /** + * Writes a diagnostic report to a file. If filename is not provided, the default filename + * includes the date, time, PID, and a sequence number. + * The report's JavaScript stack trace is taken from `err`, if present. + * + * If the value of filename is set to `'stdout'` or `'stderr'`, the report is written + * to the stdout or stderr of the process respectively. + * @param fileName Name of the file where the report is written. + * This should be a relative path, that will be appended to the directory specified in + * `process.report.directory`, or the current working directory of the Node.js process, + * if unspecified. + * @param err A custom error used for reporting the JavaScript stack. + * @return Filename of the generated report. + */ + writeReport(fileName?: string, err?: Error): string; + writeReport(err?: Error): string; + } + interface ResourceUsage { + fsRead: number; + fsWrite: number; + involuntaryContextSwitches: number; + ipcReceived: number; + ipcSent: number; + majorPageFault: number; + maxRSS: number; + minorPageFault: number; + sharedMemorySize: number; + signalsCount: number; + swappedOut: number; + systemCPUTime: number; + unsharedDataSize: number; + unsharedStackSize: number; + userCPUTime: number; + voluntaryContextSwitches: number; + } + interface EmitWarningOptions { + /** + * When `warning` is a `string`, `type` is the name to use for the _type_ of warning being emitted. + * + * @default 'Warning' + */ + type?: string | undefined; + /** + * A unique identifier for the warning instance being emitted. + */ + code?: string | undefined; + /** + * When `warning` is a `string`, `ctor` is an optional function used to limit the generated stack trace. + * + * @default process.emitWarning + */ + ctor?: Function | undefined; + /** + * Additional text to include with the error. + */ + detail?: string | undefined; + } + interface ProcessConfig { + readonly target_defaults: { + readonly cflags: any[]; + readonly default_configuration: string; + readonly defines: string[]; + readonly include_dirs: string[]; + readonly libraries: string[]; + }; + readonly variables: { + readonly clang: number; + readonly host_arch: string; + readonly node_install_npm: boolean; + readonly node_install_waf: boolean; + readonly node_prefix: string; + readonly node_shared_openssl: boolean; + readonly node_shared_v8: boolean; + readonly node_shared_zlib: boolean; + readonly node_use_dtrace: boolean; + readonly node_use_etw: boolean; + readonly node_use_openssl: boolean; + readonly target_arch: string; + readonly v8_no_strict_aliasing: number; + readonly v8_use_snapshot: boolean; + readonly visibility: string; + }; + } + interface Process extends EventEmitter { + /** + * The `process.stdout` property returns a stream connected to`stdout` (fd `1`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `1` refers to a file, in which case it is + * a `Writable` stream. + * + * For example, to copy `process.stdin` to `process.stdout`: + * + * ```js + * import { stdin, stdout } from 'node:process'; + * + * stdin.pipe(stdout); + * ``` + * + * `process.stdout` differs from other Node.js streams in important ways. See `note on process I/O` for more information. + */ + stdout: WriteStream & { + fd: 1; + }; + /** + * The `process.stderr` property returns a stream connected to`stderr` (fd `2`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `2` refers to a file, in which case it is + * a `Writable` stream. + * + * `process.stderr` differs from other Node.js streams in important ways. See `note on process I/O` for more information. + */ + stderr: WriteStream & { + fd: 2; + }; + /** + * The `process.stdin` property returns a stream connected to`stdin` (fd `0`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `0` refers to a file, in which case it is + * a `Readable` stream. + * + * For details of how to read from `stdin` see `readable.read()`. + * + * As a `Duplex` stream, `process.stdin` can also be used in "old" mode that + * is compatible with scripts written for Node.js prior to v0.10\. + * For more information see `Stream compatibility`. + * + * In "old" streams mode the `stdin` stream is paused by default, so one + * must call `process.stdin.resume()` to read from it. Note also that calling `process.stdin.resume()` itself would switch stream to "old" mode. + */ + stdin: ReadStream & { + fd: 0; + }; + /** + * The `process.argv` property returns an array containing the command-line + * arguments passed when the Node.js process was launched. The first element will + * be {@link execPath}. See `process.argv0` if access to the original value + * of `argv[0]` is needed. The second element will be the path to the JavaScript + * file being executed. The remaining elements will be any additional command-line + * arguments. + * + * For example, assuming the following script for `process-args.js`: + * + * ```js + * import { argv } from 'node:process'; + * + * // print process.argv + * argv.forEach((val, index) => { + * console.log(`${index}: ${val}`); + * }); + * ``` + * + * Launching the Node.js process as: + * + * ```bash + * node process-args.js one two=three four + * ``` + * + * Would generate the output: + * + * ```text + * 0: /usr/local/bin/node + * 1: /Users/mjr/work/node/process-args.js + * 2: one + * 3: two=three + * 4: four + * ``` + * @since v0.1.27 + */ + argv: string[]; + /** + * The `process.argv0` property stores a read-only copy of the original value of`argv[0]` passed when Node.js starts. + * + * ```console + * $ bash -c 'exec -a customArgv0 ./node' + * > process.argv[0] + * '/Volumes/code/external/node/out/Release/node' + * > process.argv0 + * 'customArgv0' + * ``` + * @since v6.4.0 + */ + argv0: string; + /** + * The `process.execArgv` property returns the set of Node.js-specific command-line + * options passed when the Node.js process was launched. These options do not + * appear in the array returned by the {@link argv} property, and do not + * include the Node.js executable, the name of the script, or any options following + * the script name. These options are useful in order to spawn child processes with + * the same execution environment as the parent. + * + * ```bash + * node --icu-data-dir=./foo --require ./bar.js script.js --version + * ``` + * + * Results in `process.execArgv`: + * + * ```js + * ["--icu-data-dir=./foo", "--require", "./bar.js"] + * ``` + * + * And `process.argv`: + * + * ```js + * ['/usr/local/bin/node', 'script.js', '--version'] + * ``` + * + * Refer to `Worker constructor` for the detailed behavior of worker + * threads with this property. + * @since v0.7.7 + */ + execArgv: string[]; + /** + * The `process.execPath` property returns the absolute pathname of the executable + * that started the Node.js process. Symbolic links, if any, are resolved. + * + * ```js + * '/usr/local/bin/node' + * ``` + * @since v0.1.100 + */ + execPath: string; + /** + * The `process.abort()` method causes the Node.js process to exit immediately and + * generate a core file. + * + * This feature is not available in `Worker` threads. + * @since v0.7.0 + */ + abort(): never; + /** + * The `process.chdir()` method changes the current working directory of the + * Node.js process or throws an exception if doing so fails (for instance, if + * the specified `directory` does not exist). + * + * ```js + * import { chdir, cwd } from 'node:process'; + * + * console.log(`Starting directory: ${cwd()}`); + * try { + * chdir('/tmp'); + * console.log(`New directory: ${cwd()}`); + * } catch (err) { + * console.error(`chdir: ${err}`); + * } + * ``` + * + * This feature is not available in `Worker` threads. + * @since v0.1.17 + */ + chdir(directory: string): void; + /** + * The `process.cwd()` method returns the current working directory of the Node.js + * process. + * + * ```js + * import { cwd } from 'node:process'; + * + * console.log(`Current directory: ${cwd()}`); + * ``` + * @since v0.1.8 + */ + cwd(): string; + /** + * The port used by the Node.js debugger when enabled. + * + * ```js + * import process from 'node:process'; + * + * process.debugPort = 5858; + * ``` + * @since v0.7.2 + */ + debugPort: number; + /** + * The `process.dlopen()` method allows dynamically loading shared objects. It is primarily used by `require()` to load C++ Addons, and + * should not be used directly, except in special cases. In other words, `require()` should be preferred over `process.dlopen()` + * unless there are specific reasons such as custom dlopen flags or loading from ES modules. + * + * The `flags` argument is an integer that allows to specify dlopen behavior. See the `[os.constants.dlopen](https://nodejs.org/docs/latest-v22.x/api/os.html#dlopen-constants)` + * documentation for details. + * + * An important requirement when calling `process.dlopen()` is that the `module` instance must be passed. Functions exported by the C++ Addon + * are then accessible via `module.exports`. + * + * The example below shows how to load a C++ Addon, named `local.node`, that exports a `foo` function. All the symbols are loaded before the call returns, by passing the `RTLD_NOW` constant. + * In this example the constant is assumed to be available. + * + * ```js + * import { dlopen } from 'node:process'; + * import { constants } from 'node:os'; + * import { fileURLToPath } from 'node:url'; + * + * const module = { exports: {} }; + * dlopen(module, fileURLToPath(new URL('local.node', import.meta.url)), + * constants.dlopen.RTLD_NOW); + * module.exports.foo(); + * ``` + */ + dlopen(module: object, filename: string, flags?: number): void; + /** + * The `process.emitWarning()` method can be used to emit custom or application + * specific process warnings. These can be listened for by adding a handler to the `'warning'` event. + * + * ```js + * import { emitWarning } from 'node:process'; + * + * // Emit a warning using a string. + * emitWarning('Something happened!'); + * // Emits: (node: 56338) Warning: Something happened! + * ``` + * + * ```js + * import { emitWarning } from 'node:process'; + * + * // Emit a warning using a string and a type. + * emitWarning('Something Happened!', 'CustomWarning'); + * // Emits: (node:56338) CustomWarning: Something Happened! + * ``` + * + * ```js + * import { emitWarning } from 'node:process'; + * + * emitWarning('Something happened!', 'CustomWarning', 'WARN001'); + * // Emits: (node:56338) [WARN001] CustomWarning: Something happened! + * ```js + * + * In each of the previous examples, an `Error` object is generated internally by `process.emitWarning()` and passed through to the `'warning'` handler. + * + * ```js + * import process from 'node:process'; + * + * process.on('warning', (warning) => { + * console.warn(warning.name); // 'Warning' + * console.warn(warning.message); // 'Something happened!' + * console.warn(warning.code); // 'MY_WARNING' + * console.warn(warning.stack); // Stack trace + * console.warn(warning.detail); // 'This is some additional information' + * }); + * ``` + * + * If `warning` is passed as an `Error` object, it will be passed through to the `'warning'` event handler + * unmodified (and the optional `type`, `code` and `ctor` arguments will be ignored): + * + * ```js + * import { emitWarning } from 'node:process'; + * + * // Emit a warning using an Error object. + * const myWarning = new Error('Something happened!'); + * // Use the Error name property to specify the type name + * myWarning.name = 'CustomWarning'; + * myWarning.code = 'WARN001'; + * + * emitWarning(myWarning); + * // Emits: (node:56338) [WARN001] CustomWarning: Something happened! + * ``` + * + * A `TypeError` is thrown if `warning` is anything other than a string or `Error` object. + * + * While process warnings use `Error` objects, the process warning mechanism is not a replacement for normal error handling mechanisms. + * + * The following additional handling is implemented if the warning `type` is `'DeprecationWarning'`: + * * If the `--throw-deprecation` command-line flag is used, the deprecation warning is thrown as an exception rather than being emitted as an event. + * * If the `--no-deprecation` command-line flag is used, the deprecation warning is suppressed. + * * If the `--trace-deprecation` command-line flag is used, the deprecation warning is printed to `stderr` along with the full stack trace. + * @since v8.0.0 + * @param warning The warning to emit. + */ + emitWarning(warning: string | Error, ctor?: Function): void; + emitWarning(warning: string | Error, type?: string, ctor?: Function): void; + emitWarning(warning: string | Error, type?: string, code?: string, ctor?: Function): void; + emitWarning(warning: string | Error, options?: EmitWarningOptions): void; + /** + * The `process.env` property returns an object containing the user environment. + * See [`environ(7)`](http://man7.org/linux/man-pages/man7/environ.7.html). + * + * An example of this object looks like: + * + * ```js + * { + * TERM: 'xterm-256color', + * SHELL: '/usr/local/bin/bash', + * USER: 'maciej', + * PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin', + * PWD: '/Users/maciej', + * EDITOR: 'vim', + * SHLVL: '1', + * HOME: '/Users/maciej', + * LOGNAME: 'maciej', + * _: '/usr/local/bin/node' + * } + * ``` + * + * It is possible to modify this object, but such modifications will not be + * reflected outside the Node.js process, or (unless explicitly requested) + * to other `Worker` threads. + * In other words, the following example would not work: + * + * ```bash + * node -e 'process.env.foo = "bar"' && echo $foo + * ``` + * + * While the following will: + * + * ```js + * import { env } from 'node:process'; + * + * env.foo = 'bar'; + * console.log(env.foo); + * ``` + * + * Assigning a property on `process.env` will implicitly convert the value + * to a string. **This behavior is deprecated.** Future versions of Node.js may + * throw an error when the value is not a string, number, or boolean. + * + * ```js + * import { env } from 'node:process'; + * + * env.test = null; + * console.log(env.test); + * // => 'null' + * env.test = undefined; + * console.log(env.test); + * // => 'undefined' + * ``` + * + * Use `delete` to delete a property from `process.env`. + * + * ```js + * import { env } from 'node:process'; + * + * env.TEST = 1; + * delete env.TEST; + * console.log(env.TEST); + * // => undefined + * ``` + * + * On Windows operating systems, environment variables are case-insensitive. + * + * ```js + * import { env } from 'node:process'; + * + * env.TEST = 1; + * console.log(env.test); + * // => 1 + * ``` + * + * Unless explicitly specified when creating a `Worker` instance, + * each `Worker` thread has its own copy of `process.env`, based on its + * parent thread's `process.env`, or whatever was specified as the `env` option + * to the `Worker` constructor. Changes to `process.env` will not be visible + * across `Worker` threads, and only the main thread can make changes that + * are visible to the operating system or to native add-ons. On Windows, a copy of `process.env` on a `Worker` instance operates in a case-sensitive manner + * unlike the main thread. + * @since v0.1.27 + */ + env: ProcessEnv; + /** + * The `process.exit()` method instructs Node.js to terminate the process + * synchronously with an exit status of `code`. If `code` is omitted, exit uses + * either the 'success' code `0` or the value of `process.exitCode` if it has been + * set. Node.js will not terminate until all the `'exit'` event listeners are + * called. + * + * To exit with a 'failure' code: + * + * ```js + * import { exit } from 'node:process'; + * + * exit(1); + * ``` + * + * The shell that executed Node.js should see the exit code as `1`. + * + * Calling `process.exit()` will force the process to exit as quickly as possible + * even if there are still asynchronous operations pending that have not yet + * completed fully, including I/O operations to `process.stdout` and `process.stderr`. + * + * In most situations, it is not actually necessary to call `process.exit()` explicitly. The Node.js process will exit on its own _if there is no additional_ + * _work pending_ in the event loop. The `process.exitCode` property can be set to + * tell the process which exit code to use when the process exits gracefully. + * + * For instance, the following example illustrates a _misuse_ of the `process.exit()` method that could lead to data printed to stdout being + * truncated and lost: + * + * ```js + * import { exit } from 'node:process'; + * + * // This is an example of what *not* to do: + * if (someConditionNotMet()) { + * printUsageToStdout(); + * exit(1); + * } + * ``` + * + * The reason this is problematic is because writes to `process.stdout` in Node.js + * are sometimes _asynchronous_ and may occur over multiple ticks of the Node.js + * event loop. Calling `process.exit()`, however, forces the process to exit _before_ those additional writes to `stdout` can be performed. + * + * Rather than calling `process.exit()` directly, the code _should_ set the `process.exitCode` and allow the process to exit naturally by avoiding + * scheduling any additional work for the event loop: + * + * ```js + * import process from 'node:process'; + * + * // How to properly set the exit code while letting + * // the process exit gracefully. + * if (someConditionNotMet()) { + * printUsageToStdout(); + * process.exitCode = 1; + * } + * ``` + * + * If it is necessary to terminate the Node.js process due to an error condition, + * throwing an _uncaught_ error and allowing the process to terminate accordingly + * is safer than calling `process.exit()`. + * + * In `Worker` threads, this function stops the current thread rather + * than the current process. + * @since v0.1.13 + * @param [code=0] The exit code. For string type, only integer strings (e.g.,'1') are allowed. + */ + exit(code?: number | string | null | undefined): never; + /** + * A number which will be the process exit code, when the process either + * exits gracefully, or is exited via {@link exit} without specifying + * a code. + * + * Specifying a code to {@link exit} will override any + * previous setting of `process.exitCode`. + * @default undefined + * @since v0.11.8 + */ + exitCode?: number | string | number | undefined; + finalization: { + /** + * This function registers a callback to be called when the process emits the `exit` event if the `ref` object was not garbage collected. + * If the object `ref` was garbage collected before the `exit` event is emitted, the callback will be removed from the finalization registry, and it will not be called on process exit. + * + * Inside the callback you can release the resources allocated by the `ref` object. + * Be aware that all limitations applied to the `beforeExit` event are also applied to the callback function, + * this means that there is a possibility that the callback will not be called under special circumstances. + * + * The idea of ​​this function is to help you free up resources when the starts process exiting, but also let the object be garbage collected if it is no longer being used. + * @param ref The reference to the resource that is being tracked. + * @param callback The callback function to be called when the resource is finalized. + * @since v22.5.0 + * @experimental + */ + register(ref: T, callback: (ref: T, event: "exit") => void): void; + /** + * This function behaves exactly like the `register`, except that the callback will be called when the process emits the `beforeExit` event if `ref` object was not garbage collected. + * + * Be aware that all limitations applied to the `beforeExit` event are also applied to the callback function, this means that there is a possibility that the callback will not be called under special circumstances. + * @param ref The reference to the resource that is being tracked. + * @param callback The callback function to be called when the resource is finalized. + * @since v22.5.0 + * @experimental + */ + registerBeforeExit(ref: T, callback: (ref: T, event: "beforeExit") => void): void; + /** + * This function remove the register of the object from the finalization registry, so the callback will not be called anymore. + * @param ref The reference to the resource that was registered previously. + * @since v22.5.0 + * @experimental + */ + unregister(ref: object): void; + }; + /** + * The `process.getActiveResourcesInfo()` method returns an array of strings containing + * the types of the active resources that are currently keeping the event loop alive. + * + * ```js + * import { getActiveResourcesInfo } from 'node:process'; + * import { setTimeout } from 'node:timers'; + + * console.log('Before:', getActiveResourcesInfo()); + * setTimeout(() => {}, 1000); + * console.log('After:', getActiveResourcesInfo()); + * // Prints: + * // Before: [ 'TTYWrap', 'TTYWrap', 'TTYWrap' ] + * // After: [ 'TTYWrap', 'TTYWrap', 'TTYWrap', 'Timeout' ] + * ``` + * @since v17.3.0, v16.14.0 + */ + getActiveResourcesInfo(): string[]; + /** + * Provides a way to load built-in modules in a globally available function. + * @param id ID of the built-in module being requested. + */ + getBuiltinModule(id: ID): BuiltInModule[ID]; + getBuiltinModule(id: string): object | undefined; + /** + * The `process.getgid()` method returns the numerical group identity of the + * process. (See [`getgid(2)`](http://man7.org/linux/man-pages/man2/getgid.2.html).) + * + * ```js + * import process from 'node:process'; + * + * if (process.getgid) { + * console.log(`Current gid: ${process.getgid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.1.31 + */ + getgid?: () => number; + /** + * The `process.setgid()` method sets the group identity of the process. (See [`setgid(2)`](http://man7.org/linux/man-pages/man2/setgid.2.html).) The `id` can be passed as either a + * numeric ID or a group name + * string. If a group name is specified, this method blocks while resolving the + * associated numeric ID. + * + * ```js + * import process from 'node:process'; + * + * if (process.getgid && process.setgid) { + * console.log(`Current gid: ${process.getgid()}`); + * try { + * process.setgid(501); + * console.log(`New gid: ${process.getgid()}`); + * } catch (err) { + * console.log(`Failed to set gid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.1.31 + * @param id The group name or ID + */ + setgid?: (id: number | string) => void; + /** + * The `process.getuid()` method returns the numeric user identity of the process. + * (See [`getuid(2)`](http://man7.org/linux/man-pages/man2/getuid.2.html).) + * + * ```js + * import process from 'node:process'; + * + * if (process.getuid) { + * console.log(`Current uid: ${process.getuid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.1.28 + */ + getuid?: () => number; + /** + * The `process.setuid(id)` method sets the user identity of the process. (See [`setuid(2)`](http://man7.org/linux/man-pages/man2/setuid.2.html).) The `id` can be passed as either a + * numeric ID or a username string. + * If a username is specified, the method blocks while resolving the associated + * numeric ID. + * + * ```js + * import process from 'node:process'; + * + * if (process.getuid && process.setuid) { + * console.log(`Current uid: ${process.getuid()}`); + * try { + * process.setuid(501); + * console.log(`New uid: ${process.getuid()}`); + * } catch (err) { + * console.log(`Failed to set uid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.1.28 + */ + setuid?: (id: number | string) => void; + /** + * The `process.geteuid()` method returns the numerical effective user identity of + * the process. (See [`geteuid(2)`](http://man7.org/linux/man-pages/man2/geteuid.2.html).) + * + * ```js + * import process from 'node:process'; + * + * if (process.geteuid) { + * console.log(`Current uid: ${process.geteuid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v2.0.0 + */ + geteuid?: () => number; + /** + * The `process.seteuid()` method sets the effective user identity of the process. + * (See [`seteuid(2)`](http://man7.org/linux/man-pages/man2/seteuid.2.html).) The `id` can be passed as either a numeric ID or a username + * string. If a username is specified, the method blocks while resolving the + * associated numeric ID. + * + * ```js + * import process from 'node:process'; + * + * if (process.geteuid && process.seteuid) { + * console.log(`Current uid: ${process.geteuid()}`); + * try { + * process.seteuid(501); + * console.log(`New uid: ${process.geteuid()}`); + * } catch (err) { + * console.log(`Failed to set uid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v2.0.0 + * @param id A user name or ID + */ + seteuid?: (id: number | string) => void; + /** + * The `process.getegid()` method returns the numerical effective group identity + * of the Node.js process. (See [`getegid(2)`](http://man7.org/linux/man-pages/man2/getegid.2.html).) + * + * ```js + * import process from 'node:process'; + * + * if (process.getegid) { + * console.log(`Current gid: ${process.getegid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v2.0.0 + */ + getegid?: () => number; + /** + * The `process.setegid()` method sets the effective group identity of the process. + * (See [`setegid(2)`](http://man7.org/linux/man-pages/man2/setegid.2.html).) The `id` can be passed as either a numeric ID or a group + * name string. If a group name is specified, this method blocks while resolving + * the associated a numeric ID. + * + * ```js + * import process from 'node:process'; + * + * if (process.getegid && process.setegid) { + * console.log(`Current gid: ${process.getegid()}`); + * try { + * process.setegid(501); + * console.log(`New gid: ${process.getegid()}`); + * } catch (err) { + * console.log(`Failed to set gid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v2.0.0 + * @param id A group name or ID + */ + setegid?: (id: number | string) => void; + /** + * The `process.getgroups()` method returns an array with the supplementary group + * IDs. POSIX leaves it unspecified if the effective group ID is included but + * Node.js ensures it always is. + * + * ```js + * import process from 'node:process'; + * + * if (process.getgroups) { + * console.log(process.getgroups()); // [ 16, 21, 297 ] + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.9.4 + */ + getgroups?: () => number[]; + /** + * The `process.setgroups()` method sets the supplementary group IDs for the + * Node.js process. This is a privileged operation that requires the Node.js + * process to have `root` or the `CAP_SETGID` capability. + * + * The `groups` array can contain numeric group IDs, group names, or both. + * + * ```js + * import process from 'node:process'; + * + * if (process.getgroups && process.setgroups) { + * try { + * process.setgroups([501]); + * console.log(process.getgroups()); // new groups + * } catch (err) { + * console.log(`Failed to set groups: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.9.4 + */ + setgroups?: (groups: ReadonlyArray) => void; + /** + * The `process.setUncaughtExceptionCaptureCallback()` function sets a function + * that will be invoked when an uncaught exception occurs, which will receive the + * exception value itself as its first argument. + * + * If such a function is set, the `'uncaughtException'` event will + * not be emitted. If `--abort-on-uncaught-exception` was passed from the + * command line or set through `v8.setFlagsFromString()`, the process will + * not abort. Actions configured to take place on exceptions such as report + * generations will be affected too + * + * To unset the capture function, `process.setUncaughtExceptionCaptureCallback(null)` may be used. Calling this + * method with a non-`null` argument while another capture function is set will + * throw an error. + * + * Using this function is mutually exclusive with using the deprecated `domain` built-in module. + * @since v9.3.0 + */ + setUncaughtExceptionCaptureCallback(cb: ((err: Error) => void) | null): void; + /** + * Indicates whether a callback has been set using {@link setUncaughtExceptionCaptureCallback}. + * @since v9.3.0 + */ + hasUncaughtExceptionCaptureCallback(): boolean; + /** + * The `process.sourceMapsEnabled` property returns whether the [Source Map v3](https://sourcemaps.info/spec.html) support for stack traces is enabled. + * @since v20.7.0 + * @experimental + */ + readonly sourceMapsEnabled: boolean; + /** + * This function enables or disables the [Source Map v3](https://sourcemaps.info/spec.html) support for + * stack traces. + * + * It provides same features as launching Node.js process with commandline options `--enable-source-maps`. + * + * Only source maps in JavaScript files that are loaded after source maps has been + * enabled will be parsed and loaded. + * @since v16.6.0, v14.18.0 + * @experimental + */ + setSourceMapsEnabled(value: boolean): void; + /** + * The `process.version` property contains the Node.js version string. + * + * ```js + * import { version } from 'node:process'; + * + * console.log(`Version: ${version}`); + * // Version: v14.8.0 + * ``` + * + * To get the version string without the prepended _v_, use`process.versions.node`. + * @since v0.1.3 + */ + readonly version: string; + /** + * The `process.versions` property returns an object listing the version strings of + * Node.js and its dependencies. `process.versions.modules` indicates the current + * ABI version, which is increased whenever a C++ API changes. Node.js will refuse + * to load modules that were compiled against a different module ABI version. + * + * ```js + * import { versions } from 'node:process'; + * + * console.log(versions); + * ``` + * + * Will generate an object similar to: + * + * ```console + * { node: '20.2.0', + * acorn: '8.8.2', + * ada: '2.4.0', + * ares: '1.19.0', + * base64: '0.5.0', + * brotli: '1.0.9', + * cjs_module_lexer: '1.2.2', + * cldr: '43.0', + * icu: '73.1', + * llhttp: '8.1.0', + * modules: '115', + * napi: '8', + * nghttp2: '1.52.0', + * nghttp3: '0.7.0', + * ngtcp2: '0.8.1', + * openssl: '3.0.8+quic', + * simdutf: '3.2.9', + * tz: '2023c', + * undici: '5.22.0', + * unicode: '15.0', + * uv: '1.44.2', + * uvwasi: '0.0.16', + * v8: '11.3.244.8-node.9', + * zlib: '1.2.13' } + * ``` + * @since v0.2.0 + */ + readonly versions: ProcessVersions; + /** + * The `process.config` property returns a frozen `Object` containing the + * JavaScript representation of the configure options used to compile the current + * Node.js executable. This is the same as the `config.gypi` file that was produced + * when running the `./configure` script. + * + * An example of the possible output looks like: + * + * ```js + * { + * target_defaults: + * { cflags: [], + * default_configuration: 'Release', + * defines: [], + * include_dirs: [], + * libraries: [] }, + * variables: + * { + * host_arch: 'x64', + * napi_build_version: 5, + * node_install_npm: 'true', + * node_prefix: '', + * node_shared_cares: 'false', + * node_shared_http_parser: 'false', + * node_shared_libuv: 'false', + * node_shared_zlib: 'false', + * node_use_openssl: 'true', + * node_shared_openssl: 'false', + * strict_aliasing: 'true', + * target_arch: 'x64', + * v8_use_snapshot: 1 + * } + * } + * ``` + * @since v0.7.7 + */ + readonly config: ProcessConfig; + /** + * The `process.kill()` method sends the `signal` to the process identified by`pid`. + * + * Signal names are strings such as `'SIGINT'` or `'SIGHUP'`. See `Signal Events` and [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) for more information. + * + * This method will throw an error if the target `pid` does not exist. As a special + * case, a signal of `0` can be used to test for the existence of a process. + * Windows platforms will throw an error if the `pid` is used to kill a process + * group. + * + * Even though the name of this function is `process.kill()`, it is really just a + * signal sender, like the `kill` system call. The signal sent may do something + * other than kill the target process. + * + * ```js + * import process, { kill } from 'node:process'; + * + * process.on('SIGHUP', () => { + * console.log('Got SIGHUP signal.'); + * }); + * + * setTimeout(() => { + * console.log('Exiting.'); + * process.exit(0); + * }, 100); + * + * kill(process.pid, 'SIGHUP'); + * ``` + * + * When `SIGUSR1` is received by a Node.js process, Node.js will start the + * debugger. See `Signal Events`. + * @since v0.0.6 + * @param pid A process ID + * @param [signal='SIGTERM'] The signal to send, either as a string or number. + */ + kill(pid: number, signal?: string | number): true; + /** + * Loads the environment configuration from a `.env` file into `process.env`. If + * the file is not found, error will be thrown. + * + * To load a specific .env file by specifying its path, use the following code: + * + * ```js + * import { loadEnvFile } from 'node:process'; + * + * loadEnvFile('./development.env') + * ``` + * @since v20.12.0 + * @param path The path to the .env file + */ + loadEnvFile(path?: string | URL | Buffer): void; + /** + * The `process.pid` property returns the PID of the process. + * + * ```js + * import { pid } from 'node:process'; + * + * console.log(`This process is pid ${pid}`); + * ``` + * @since v0.1.15 + */ + readonly pid: number; + /** + * The `process.ppid` property returns the PID of the parent of the + * current process. + * + * ```js + * import { ppid } from 'node:process'; + * + * console.log(`The parent process is pid ${ppid}`); + * ``` + * @since v9.2.0, v8.10.0, v6.13.0 + */ + readonly ppid: number; + /** + * The `process.title` property returns the current process title (i.e. returns + * the current value of `ps`). Assigning a new value to `process.title` modifies + * the current value of `ps`. + * + * When a new value is assigned, different platforms will impose different maximum + * length restrictions on the title. Usually such restrictions are quite limited. + * For instance, on Linux and macOS, `process.title` is limited to the size of the + * binary name plus the length of the command-line arguments because setting the `process.title` overwrites the `argv` memory of the process. Node.js v0.8 + * allowed for longer process title strings by also overwriting the `environ` memory but that was potentially insecure and confusing in some (rather obscure) + * cases. + * + * Assigning a value to `process.title` might not result in an accurate label + * within process manager applications such as macOS Activity Monitor or Windows + * Services Manager. + * @since v0.1.104 + */ + title: string; + /** + * The operating system CPU architecture for which the Node.js binary was compiled. + * Possible values are: `'arm'`, `'arm64'`, `'ia32'`, `'loong64'`, `'mips'`, `'mipsel'`, `'ppc'`, `'ppc64'`, `'riscv64'`, `'s390'`, `'s390x'`, and `'x64'`. + * + * ```js + * import { arch } from 'node:process'; + * + * console.log(`This processor architecture is ${arch}`); + * ``` + * @since v0.5.0 + */ + readonly arch: Architecture; + /** + * The `process.platform` property returns a string identifying the operating + * system platform for which the Node.js binary was compiled. + * + * Currently possible values are: + * + * * `'aix'` + * * `'darwin'` + * * `'freebsd'` + * * `'linux'` + * * `'openbsd'` + * * `'sunos'` + * * `'win32'` + * + * ```js + * import { platform } from 'node:process'; + * + * console.log(`This platform is ${platform}`); + * ``` + * + * The value `'android'` may also be returned if the Node.js is built on the + * Android operating system. However, Android support in Node.js [is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os). + * @since v0.1.16 + */ + readonly platform: Platform; + /** + * The `process.mainModule` property provides an alternative way of retrieving `require.main`. The difference is that if the main module changes at + * runtime, `require.main` may still refer to the original main module in + * modules that were required before the change occurred. Generally, it's + * safe to assume that the two refer to the same module. + * + * As with `require.main`, `process.mainModule` will be `undefined` if there + * is no entry script. + * @since v0.1.17 + * @deprecated Since v14.0.0 - Use `main` instead. + */ + mainModule?: Module | undefined; + memoryUsage: MemoryUsageFn; + /** + * Gets the amount of memory available to the process (in bytes) based on + * limits imposed by the OS. If there is no such constraint, or the constraint + * is unknown, `0` is returned. + * + * See [`uv_get_constrained_memory`](https://docs.libuv.org/en/v1.x/misc.html#c.uv_get_constrained_memory) for more + * information. + * @since v19.6.0, v18.15.0 + * @experimental + */ + constrainedMemory(): number; + /** + * Gets the amount of free memory that is still available to the process (in bytes). + * See [`uv_get_available_memory`](https://nodejs.org/docs/latest-v22.x/api/process.html#processavailablememory) for more information. + * @experimental + * @since v20.13.0 + */ + availableMemory(): number; + /** + * The `process.cpuUsage()` method returns the user and system CPU time usage of + * the current process, in an object with properties `user` and `system`, whose + * values are microsecond values (millionth of a second). These values measure time + * spent in user and system code respectively, and may end up being greater than + * actual elapsed time if multiple CPU cores are performing work for this process. + * + * The result of a previous call to `process.cpuUsage()` can be passed as the + * argument to the function, to get a diff reading. + * + * ```js + * import { cpuUsage } from 'node:process'; + * + * const startUsage = cpuUsage(); + * // { user: 38579, system: 6986 } + * + * // spin the CPU for 500 milliseconds + * const now = Date.now(); + * while (Date.now() - now < 500); + * + * console.log(cpuUsage(startUsage)); + * // { user: 514883, system: 11226 } + * ``` + * @since v6.1.0 + * @param previousValue A previous return value from calling `process.cpuUsage()` + */ + cpuUsage(previousValue?: CpuUsage): CpuUsage; + /** + * `process.nextTick()` adds `callback` to the "next tick queue". This queue is + * fully drained after the current operation on the JavaScript stack runs to + * completion and before the event loop is allowed to continue. It's possible to + * create an infinite loop if one were to recursively call `process.nextTick()`. + * See the [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#process-nexttick) guide for more background. + * + * ```js + * import { nextTick } from 'node:process'; + * + * console.log('start'); + * nextTick(() => { + * console.log('nextTick callback'); + * }); + * console.log('scheduled'); + * // Output: + * // start + * // scheduled + * // nextTick callback + * ``` + * + * This is important when developing APIs in order to give users the opportunity + * to assign event handlers _after_ an object has been constructed but before any + * I/O has occurred: + * + * ```js + * import { nextTick } from 'node:process'; + * + * function MyThing(options) { + * this.setupOptions(options); + * + * nextTick(() => { + * this.startDoingStuff(); + * }); + * } + * + * const thing = new MyThing(); + * thing.getReadyForStuff(); + * + * // thing.startDoingStuff() gets called now, not before. + * ``` + * + * It is very important for APIs to be either 100% synchronous or 100% + * asynchronous. Consider this example: + * + * ```js + * // WARNING! DO NOT USE! BAD UNSAFE HAZARD! + * function maybeSync(arg, cb) { + * if (arg) { + * cb(); + * return; + * } + * + * fs.stat('file', cb); + * } + * ``` + * + * This API is hazardous because in the following case: + * + * ```js + * const maybeTrue = Math.random() > 0.5; + * + * maybeSync(maybeTrue, () => { + * foo(); + * }); + * + * bar(); + * ``` + * + * It is not clear whether `foo()` or `bar()` will be called first. + * + * The following approach is much better: + * + * ```js + * import { nextTick } from 'node:process'; + * + * function definitelyAsync(arg, cb) { + * if (arg) { + * nextTick(cb); + * return; + * } + * + * fs.stat('file', cb); + * } + * ``` + * @since v0.1.26 + * @param args Additional arguments to pass when invoking the `callback` + */ + nextTick(callback: Function, ...args: any[]): void; + /** + * This API is available through the [--experimental-permission](https://nodejs.org/api/cli.html#--experimental-permission) flag. + * + * `process.permission` is an object whose methods are used to manage permissions for the current process. + * Additional documentation is available in the [Permission Model](https://nodejs.org/api/permissions.html#permission-model). + * @since v20.0.0 + */ + permission: ProcessPermission; + /** + * The `process.release` property returns an `Object` containing metadata related + * to the current release, including URLs for the source tarball and headers-only + * tarball. + * + * `process.release` contains the following properties: + * + * ```js + * { + * name: 'node', + * lts: 'Hydrogen', + * sourceUrl: 'https://nodejs.org/download/release/v18.12.0/node-v18.12.0.tar.gz', + * headersUrl: 'https://nodejs.org/download/release/v18.12.0/node-v18.12.0-headers.tar.gz', + * libUrl: 'https://nodejs.org/download/release/v18.12.0/win-x64/node.lib' + * } + * ``` + * + * In custom builds from non-release versions of the source tree, only the `name` property may be present. The additional properties should not be + * relied upon to exist. + * @since v3.0.0 + */ + readonly release: ProcessRelease; + features: { + inspector: boolean; + debug: boolean; + uv: boolean; + ipv6: boolean; + tls_alpn: boolean; + tls_sni: boolean; + tls_ocsp: boolean; + tls: boolean; + }; + /** + * `process.umask()` returns the Node.js process's file mode creation mask. Child + * processes inherit the mask from the parent process. + * @since v0.1.19 + * @deprecated Calling `process.umask()` with no argument causes the process-wide umask to be written twice. This introduces a race condition between threads, and is a potential + * security vulnerability. There is no safe, cross-platform alternative API. + */ + umask(): number; + /** + * Can only be set if not in worker thread. + */ + umask(mask: string | number): number; + /** + * The `process.uptime()` method returns the number of seconds the current Node.js + * process has been running. + * + * The return value includes fractions of a second. Use `Math.floor()` to get whole + * seconds. + * @since v0.5.0 + */ + uptime(): number; + hrtime: HRTime; + /** + * If the Node.js process was spawned with an IPC channel, the process.channel property is a reference to the IPC channel. + * If no IPC channel exists, this property is undefined. + * @since v7.1.0 + */ + channel?: { + /** + * This method makes the IPC channel keep the event loop of the process running if .unref() has been called before. + * @since v7.1.0 + */ + ref(): void; + /** + * This method makes the IPC channel not keep the event loop of the process running, and lets it finish even while the channel is open. + * @since v7.1.0 + */ + unref(): void; + }; + /** + * If Node.js is spawned with an IPC channel, the `process.send()` method can be + * used to send messages to the parent process. Messages will be received as a `'message'` event on the parent's `ChildProcess` object. + * + * If Node.js was not spawned with an IPC channel, `process.send` will be `undefined`. + * + * The message goes through serialization and parsing. The resulting message might + * not be the same as what is originally sent. + * @since v0.5.9 + * @param options used to parameterize the sending of certain types of handles. `options` supports the following properties: + */ + send?( + message: any, + sendHandle?: any, + options?: { + keepOpen?: boolean | undefined; + }, + callback?: (error: Error | null) => void, + ): boolean; + /** + * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.disconnect()` method will close the + * IPC channel to the parent process, allowing the child process to exit gracefully + * once there are no other connections keeping it alive. + * + * The effect of calling `process.disconnect()` is the same as calling `ChildProcess.disconnect()` from the parent process. + * + * If the Node.js process was not spawned with an IPC channel, `process.disconnect()` will be `undefined`. + * @since v0.7.2 + */ + disconnect(): void; + /** + * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.connected` property will return `true` so long as the IPC + * channel is connected and will return `false` after `process.disconnect()` is called. + * + * Once `process.connected` is `false`, it is no longer possible to send messages + * over the IPC channel using `process.send()`. + * @since v0.7.2 + */ + connected: boolean; + /** + * The `process.allowedNodeEnvironmentFlags` property is a special, + * read-only `Set` of flags allowable within the `NODE_OPTIONS` environment variable. + * + * `process.allowedNodeEnvironmentFlags` extends `Set`, but overrides `Set.prototype.has` to recognize several different possible flag + * representations. `process.allowedNodeEnvironmentFlags.has()` will + * return `true` in the following cases: + * + * * Flags may omit leading single (`-`) or double (`--`) dashes; e.g., `inspect-brk` for `--inspect-brk`, or `r` for `-r`. + * * Flags passed through to V8 (as listed in `--v8-options`) may replace + * one or more _non-leading_ dashes for an underscore, or vice-versa; + * e.g., `--perf_basic_prof`, `--perf-basic-prof`, `--perf_basic-prof`, + * etc. + * * Flags may contain one or more equals (`=`) characters; all + * characters after and including the first equals will be ignored; + * e.g., `--stack-trace-limit=100`. + * * Flags _must_ be allowable within `NODE_OPTIONS`. + * + * When iterating over `process.allowedNodeEnvironmentFlags`, flags will + * appear only _once_; each will begin with one or more dashes. Flags + * passed through to V8 will contain underscores instead of non-leading + * dashes: + * + * ```js + * import { allowedNodeEnvironmentFlags } from 'node:process'; + * + * allowedNodeEnvironmentFlags.forEach((flag) => { + * // -r + * // --inspect-brk + * // --abort_on_uncaught_exception + * // ... + * }); + * ``` + * + * The methods `add()`, `clear()`, and `delete()` of`process.allowedNodeEnvironmentFlags` do nothing, and will fail + * silently. + * + * If Node.js was compiled _without_ `NODE_OPTIONS` support (shown in {@link config}), `process.allowedNodeEnvironmentFlags` will + * contain what _would have_ been allowable. + * @since v10.10.0 + */ + allowedNodeEnvironmentFlags: ReadonlySet; + /** + * `process.report` is an object whose methods are used to generate diagnostic reports for the current process. + * Additional documentation is available in the [report documentation](https://nodejs.org/docs/latest-v22.x/api/report.html). + * @since v11.8.0 + */ + report: ProcessReport; + /** + * ```js + * import { resourceUsage } from 'node:process'; + * + * console.log(resourceUsage()); + * /* + * Will output: + * { + * userCPUTime: 82872, + * systemCPUTime: 4143, + * maxRSS: 33164, + * sharedMemorySize: 0, + * unsharedDataSize: 0, + * unsharedStackSize: 0, + * minorPageFault: 2469, + * majorPageFault: 0, + * swappedOut: 0, + * fsRead: 0, + * fsWrite: 8, + * ipcSent: 0, + * ipcReceived: 0, + * signalsCount: 0, + * voluntaryContextSwitches: 79, + * involuntaryContextSwitches: 1 + * } + * + * ``` + * @since v12.6.0 + * @return the resource usage for the current process. All of these values come from the `uv_getrusage` call which returns a [`uv_rusage_t` struct][uv_rusage_t]. + */ + resourceUsage(): ResourceUsage; + /** + * The initial value of `process.throwDeprecation` indicates whether the `--throw-deprecation` flag is set on the current Node.js process. `process.throwDeprecation` + * is mutable, so whether or not deprecation warnings result in errors may be altered at runtime. See the documentation for the 'warning' event and the emitWarning() + * method for more information. + * + * ```bash + * $ node --throw-deprecation -p "process.throwDeprecation" + * true + * $ node -p "process.throwDeprecation" + * undefined + * $ node + * > process.emitWarning('test', 'DeprecationWarning'); + * undefined + * > (node:26598) DeprecationWarning: test + * > process.throwDeprecation = true; + * true + * > process.emitWarning('test', 'DeprecationWarning'); + * Thrown: + * [DeprecationWarning: test] { name: 'DeprecationWarning' } + * ``` + * @since v0.9.12 + */ + throwDeprecation: boolean; + /** + * The `process.traceDeprecation` property indicates whether the `--trace-deprecation` flag is set on the current Node.js process. See the + * documentation for the `'warning' event` and the `emitWarning() method` for more information about this + * flag's behavior. + * @since v0.8.0 + */ + traceDeprecation: boolean; + /* EventEmitter */ + addListener(event: "beforeExit", listener: BeforeExitListener): this; + addListener(event: "disconnect", listener: DisconnectListener): this; + addListener(event: "exit", listener: ExitListener): this; + addListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + addListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + addListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + addListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + addListener(event: "warning", listener: WarningListener): this; + addListener(event: "message", listener: MessageListener): this; + addListener(event: Signals, listener: SignalsListener): this; + addListener(event: "multipleResolves", listener: MultipleResolveListener): this; + addListener(event: "worker", listener: WorkerListener): this; + emit(event: "beforeExit", code: number): boolean; + emit(event: "disconnect"): boolean; + emit(event: "exit", code: number): boolean; + emit(event: "rejectionHandled", promise: Promise): boolean; + emit(event: "uncaughtException", error: Error): boolean; + emit(event: "uncaughtExceptionMonitor", error: Error): boolean; + emit(event: "unhandledRejection", reason: unknown, promise: Promise): boolean; + emit(event: "warning", warning: Error): boolean; + emit(event: "message", message: unknown, sendHandle: unknown): this; + emit(event: Signals, signal?: Signals): boolean; + emit( + event: "multipleResolves", + type: MultipleResolveType, + promise: Promise, + value: unknown, + ): this; + emit(event: "worker", listener: WorkerListener): this; + on(event: "beforeExit", listener: BeforeExitListener): this; + on(event: "disconnect", listener: DisconnectListener): this; + on(event: "exit", listener: ExitListener): this; + on(event: "rejectionHandled", listener: RejectionHandledListener): this; + on(event: "uncaughtException", listener: UncaughtExceptionListener): this; + on(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + on(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + on(event: "warning", listener: WarningListener): this; + on(event: "message", listener: MessageListener): this; + on(event: Signals, listener: SignalsListener): this; + on(event: "multipleResolves", listener: MultipleResolveListener): this; + on(event: "worker", listener: WorkerListener): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "beforeExit", listener: BeforeExitListener): this; + once(event: "disconnect", listener: DisconnectListener): this; + once(event: "exit", listener: ExitListener): this; + once(event: "rejectionHandled", listener: RejectionHandledListener): this; + once(event: "uncaughtException", listener: UncaughtExceptionListener): this; + once(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + once(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + once(event: "warning", listener: WarningListener): this; + once(event: "message", listener: MessageListener): this; + once(event: Signals, listener: SignalsListener): this; + once(event: "multipleResolves", listener: MultipleResolveListener): this; + once(event: "worker", listener: WorkerListener): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "beforeExit", listener: BeforeExitListener): this; + prependListener(event: "disconnect", listener: DisconnectListener): this; + prependListener(event: "exit", listener: ExitListener): this; + prependListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + prependListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependListener(event: "warning", listener: WarningListener): this; + prependListener(event: "message", listener: MessageListener): this; + prependListener(event: Signals, listener: SignalsListener): this; + prependListener(event: "multipleResolves", listener: MultipleResolveListener): this; + prependListener(event: "worker", listener: WorkerListener): this; + prependOnceListener(event: "beforeExit", listener: BeforeExitListener): this; + prependOnceListener(event: "disconnect", listener: DisconnectListener): this; + prependOnceListener(event: "exit", listener: ExitListener): this; + prependOnceListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependOnceListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependOnceListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + prependOnceListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependOnceListener(event: "warning", listener: WarningListener): this; + prependOnceListener(event: "message", listener: MessageListener): this; + prependOnceListener(event: Signals, listener: SignalsListener): this; + prependOnceListener(event: "multipleResolves", listener: MultipleResolveListener): this; + prependOnceListener(event: "worker", listener: WorkerListener): this; + listeners(event: "beforeExit"): BeforeExitListener[]; + listeners(event: "disconnect"): DisconnectListener[]; + listeners(event: "exit"): ExitListener[]; + listeners(event: "rejectionHandled"): RejectionHandledListener[]; + listeners(event: "uncaughtException"): UncaughtExceptionListener[]; + listeners(event: "uncaughtExceptionMonitor"): UncaughtExceptionListener[]; + listeners(event: "unhandledRejection"): UnhandledRejectionListener[]; + listeners(event: "warning"): WarningListener[]; + listeners(event: "message"): MessageListener[]; + listeners(event: Signals): SignalsListener[]; + listeners(event: "multipleResolves"): MultipleResolveListener[]; + listeners(event: "worker"): WorkerListener[]; + } + } + } + export = process; +} +declare module "node:process" { + import process = require("process"); + export = process; +} diff --git a/libcore/node_modules/@types/node/punycode.d.ts b/libcore/node_modules/@types/node/punycode.d.ts new file mode 100644 index 0000000..e788577 --- /dev/null +++ b/libcore/node_modules/@types/node/punycode.d.ts @@ -0,0 +1,117 @@ +/** + * **The version of the punycode module bundled in Node.js is being deprecated. **In a future major version of Node.js this module will be removed. Users + * currently depending on the `punycode` module should switch to using the + * userland-provided [Punycode.js](https://github.com/bestiejs/punycode.js) module instead. For punycode-based URL + * encoding, see `url.domainToASCII` or, more generally, the `WHATWG URL API`. + * + * The `punycode` module is a bundled version of the [Punycode.js](https://github.com/bestiejs/punycode.js) module. It + * can be accessed using: + * + * ```js + * const punycode = require('punycode'); + * ``` + * + * [Punycode](https://tools.ietf.org/html/rfc3492) is a character encoding scheme defined by RFC 3492 that is + * primarily intended for use in Internationalized Domain Names. Because host + * names in URLs are limited to ASCII characters only, Domain Names that contain + * non-ASCII characters must be converted into ASCII using the Punycode scheme. + * For instance, the Japanese character that translates into the English word, `'example'` is `'例'`. The Internationalized Domain Name, `'例.com'` (equivalent + * to `'example.com'`) is represented by Punycode as the ASCII string `'xn--fsq.com'`. + * + * The `punycode` module provides a simple implementation of the Punycode standard. + * + * The `punycode` module is a third-party dependency used by Node.js and + * made available to developers as a convenience. Fixes or other modifications to + * the module must be directed to the [Punycode.js](https://github.com/bestiejs/punycode.js) project. + * @deprecated Since v7.0.0 - Deprecated + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/punycode.js) + */ +declare module "punycode" { + /** + * The `punycode.decode()` method converts a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only + * characters to the equivalent string of Unicode codepoints. + * + * ```js + * punycode.decode('maana-pta'); // 'mañana' + * punycode.decode('--dqo34k'); // '☃-⌘' + * ``` + * @since v0.5.1 + */ + function decode(string: string): string; + /** + * The `punycode.encode()` method converts a string of Unicode codepoints to a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only characters. + * + * ```js + * punycode.encode('mañana'); // 'maana-pta' + * punycode.encode('☃-⌘'); // '--dqo34k' + * ``` + * @since v0.5.1 + */ + function encode(string: string): string; + /** + * The `punycode.toUnicode()` method converts a string representing a domain name + * containing [Punycode](https://tools.ietf.org/html/rfc3492) encoded characters into Unicode. Only the [Punycode](https://tools.ietf.org/html/rfc3492) encoded parts of the domain name are be + * converted. + * + * ```js + * // decode domain names + * punycode.toUnicode('xn--maana-pta.com'); // 'mañana.com' + * punycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com' + * punycode.toUnicode('example.com'); // 'example.com' + * ``` + * @since v0.6.1 + */ + function toUnicode(domain: string): string; + /** + * The `punycode.toASCII()` method converts a Unicode string representing an + * Internationalized Domain Name to [Punycode](https://tools.ietf.org/html/rfc3492). Only the non-ASCII parts of the + * domain name will be converted. Calling `punycode.toASCII()` on a string that + * already only contains ASCII characters will have no effect. + * + * ```js + * // encode domain names + * punycode.toASCII('mañana.com'); // 'xn--maana-pta.com' + * punycode.toASCII('☃-⌘.com'); // 'xn----dqo34k.com' + * punycode.toASCII('example.com'); // 'example.com' + * ``` + * @since v0.6.1 + */ + function toASCII(domain: string): string; + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + const ucs2: ucs2; + interface ucs2 { + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + decode(string: string): number[]; + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + encode(codePoints: readonly number[]): string; + } + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + const version: string; +} +declare module "node:punycode" { + export * from "punycode"; +} diff --git a/libcore/node_modules/@types/node/querystring.d.ts b/libcore/node_modules/@types/node/querystring.d.ts new file mode 100644 index 0000000..cb919ca --- /dev/null +++ b/libcore/node_modules/@types/node/querystring.d.ts @@ -0,0 +1,153 @@ +/** + * The `node:querystring` module provides utilities for parsing and formatting URL + * query strings. It can be accessed using: + * + * ```js + * const querystring = require('node:querystring'); + * ``` + * + * `querystring` is more performant than `URLSearchParams` but is not a + * standardized API. Use `URLSearchParams` when performance is not critical or + * when compatibility with browser code is desirable. + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/querystring.js) + */ +declare module "querystring" { + interface StringifyOptions { + /** + * The function to use when converting URL-unsafe characters to percent-encoding in the query string. + * @default `querystring.escape()` + */ + encodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParseOptions { + /** + * Specifies the maximum number of keys to parse. Specify `0` to remove key counting limitations. + * @default 1000 + */ + maxKeys?: number | undefined; + /** + * The function to use when decoding percent-encoded characters in the query string. + * @default `querystring.unescape()` + */ + decodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParsedUrlQuery extends NodeJS.Dict {} + interface ParsedUrlQueryInput extends + NodeJS.Dict< + | string + | number + | boolean + | readonly string[] + | readonly number[] + | readonly boolean[] + | null + > + {} + /** + * The `querystring.stringify()` method produces a URL query string from a + * given `obj` by iterating through the object's "own properties". + * + * It serializes the following types of values passed in `obj`: [string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | + * [number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) | + * [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | + * [string\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | + * [number\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | + * [bigint\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) | + * [boolean\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) The numeric values must be finite. Any other input values will be coerced to + * empty strings. + * + * ```js + * querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' }); + * // Returns 'foo=bar&baz=qux&baz=quux&corge=' + * + * querystring.stringify({ foo: 'bar', baz: 'qux' }, ';', ':'); + * // Returns 'foo:bar;baz:qux' + * ``` + * + * By default, characters requiring percent-encoding within the query string will + * be encoded as UTF-8\. If an alternative encoding is required, then an alternative `encodeURIComponent` option will need to be specified: + * + * ```js + * // Assuming gbkEncodeURIComponent function already exists, + * + * querystring.stringify({ w: '中文', foo: 'bar' }, null, null, + * { encodeURIComponent: gbkEncodeURIComponent }); + * ``` + * @since v0.1.25 + * @param obj The object to serialize into a URL query string + * @param [sep='&'] The substring used to delimit key and value pairs in the query string. + * @param [eq='='] . The substring used to delimit keys and values in the query string. + */ + function stringify(obj?: ParsedUrlQueryInput, sep?: string, eq?: string, options?: StringifyOptions): string; + /** + * The `querystring.parse()` method parses a URL query string (`str`) into a + * collection of key and value pairs. + * + * For example, the query string `'foo=bar&abc=xyz&abc=123'` is parsed into: + * + * ```json + * { + * "foo": "bar", + * "abc": ["xyz", "123"] + * } + * ``` + * + * The object returned by the `querystring.parse()` method _does not_ prototypically inherit from the JavaScript `Object`. This means that typical `Object` methods such as `obj.toString()`, + * `obj.hasOwnProperty()`, and others + * are not defined and _will not work_. + * + * By default, percent-encoded characters within the query string will be assumed + * to use UTF-8 encoding. If an alternative character encoding is used, then an + * alternative `decodeURIComponent` option will need to be specified: + * + * ```js + * // Assuming gbkDecodeURIComponent function already exists... + * + * querystring.parse('w=%D6%D0%CE%C4&foo=bar', null, null, + * { decodeURIComponent: gbkDecodeURIComponent }); + * ``` + * @since v0.1.25 + * @param str The URL query string to parse + * @param [sep='&'] The substring used to delimit key and value pairs in the query string. + * @param [eq='='] The substring used to delimit keys and values in the query string. + */ + function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): ParsedUrlQuery; + /** + * The querystring.encode() function is an alias for querystring.stringify(). + */ + const encode: typeof stringify; + /** + * The querystring.decode() function is an alias for querystring.parse(). + */ + const decode: typeof parse; + /** + * The `querystring.escape()` method performs URL percent-encoding on the given `str` in a manner that is optimized for the specific requirements of URL + * query strings. + * + * The `querystring.escape()` method is used by `querystring.stringify()` and is + * generally not expected to be used directly. It is exported primarily to allow + * application code to provide a replacement percent-encoding implementation if + * necessary by assigning `querystring.escape` to an alternative function. + * @since v0.1.25 + */ + function escape(str: string): string; + /** + * The `querystring.unescape()` method performs decoding of URL percent-encoded + * characters on the given `str`. + * + * The `querystring.unescape()` method is used by `querystring.parse()` and is + * generally not expected to be used directly. It is exported primarily to allow + * application code to provide a replacement decoding implementation if + * necessary by assigning `querystring.unescape` to an alternative function. + * + * By default, the `querystring.unescape()` method will attempt to use the + * JavaScript built-in `decodeURIComponent()` method to decode. If that fails, + * a safer equivalent that does not throw on malformed URLs will be used. + * @since v0.1.25 + */ + function unescape(str: string): string; +} +declare module "node:querystring" { + export * from "querystring"; +} diff --git a/libcore/node_modules/@types/node/readline.d.ts b/libcore/node_modules/@types/node/readline.d.ts new file mode 100644 index 0000000..b40c61f --- /dev/null +++ b/libcore/node_modules/@types/node/readline.d.ts @@ -0,0 +1,540 @@ +/** + * The `node:readline` module provides an interface for reading data from a [Readable](https://nodejs.org/docs/latest-v22.x/api/stream.html#readable-streams) stream + * (such as [`process.stdin`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdin)) one line at a time. + * + * To use the promise-based APIs: + * + * ```js + * import * as readline from 'node:readline/promises'; + * ``` + * + * To use the callback and sync APIs: + * + * ```js + * import * as readline from 'node:readline'; + * ``` + * + * The following simple example illustrates the basic use of the `node:readline` module. + * + * ```js + * import * as readline from 'node:readline/promises'; + * import { stdin as input, stdout as output } from 'node:process'; + * + * const rl = readline.createInterface({ input, output }); + * + * const answer = await rl.question('What do you think of Node.js? '); + * + * console.log(`Thank you for your valuable feedback: ${answer}`); + * + * rl.close(); + * ``` + * + * Once this code is invoked, the Node.js application will not terminate until the `readline.Interface` is closed because the interface waits for data to be + * received on the `input` stream. + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/readline.js) + */ +declare module "readline" { + import { Abortable, EventEmitter } from "node:events"; + import * as promises from "node:readline/promises"; + export { promises }; + export interface Key { + sequence?: string | undefined; + name?: string | undefined; + ctrl?: boolean | undefined; + meta?: boolean | undefined; + shift?: boolean | undefined; + } + /** + * Instances of the `readline.Interface` class are constructed using the `readline.createInterface()` method. Every instance is associated with a + * single `input` [Readable](https://nodejs.org/docs/latest-v22.x/api/stream.html#readable-streams) stream and a single `output` [Writable](https://nodejs.org/docs/latest-v22.x/api/stream.html#writable-streams) stream. + * The `output` stream is used to print prompts for user input that arrives on, + * and is read from, the `input` stream. + * @since v0.1.104 + */ + export class Interface extends EventEmitter { + readonly terminal: boolean; + /** + * The current input data being processed by node. + * + * This can be used when collecting input from a TTY stream to retrieve the + * current value that has been processed thus far, prior to the `line` event + * being emitted. Once the `line` event has been emitted, this property will + * be an empty string. + * + * Be aware that modifying the value during the instance runtime may have + * unintended consequences if `rl.cursor` is not also controlled. + * + * **If not using a TTY stream for input, use the `'line'` event.** + * + * One possible use case would be as follows: + * + * ```js + * const values = ['lorem ipsum', 'dolor sit amet']; + * const rl = readline.createInterface(process.stdin); + * const showResults = debounce(() => { + * console.log( + * '\n', + * values.filter((val) => val.startsWith(rl.line)).join(' '), + * ); + * }, 300); + * process.stdin.on('keypress', (c, k) => { + * showResults(); + * }); + * ``` + * @since v0.1.98 + */ + readonly line: string; + /** + * The cursor position relative to `rl.line`. + * + * This will track where the current cursor lands in the input string, when + * reading input from a TTY stream. The position of cursor determines the + * portion of the input string that will be modified as input is processed, + * as well as the column where the terminal caret will be rendered. + * @since v0.1.98 + */ + readonly cursor: number; + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v22.x/docs/api/readline.html#class-interfaceconstructor + */ + protected constructor( + input: NodeJS.ReadableStream, + output?: NodeJS.WritableStream, + completer?: Completer | AsyncCompleter, + terminal?: boolean, + ); + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v22.x/docs/api/readline.html#class-interfaceconstructor + */ + protected constructor(options: ReadLineOptions); + /** + * The `rl.getPrompt()` method returns the current prompt used by `rl.prompt()`. + * @since v15.3.0, v14.17.0 + * @return the current prompt string + */ + getPrompt(): string; + /** + * The `rl.setPrompt()` method sets the prompt that will be written to `output` whenever `rl.prompt()` is called. + * @since v0.1.98 + */ + setPrompt(prompt: string): void; + /** + * The `rl.prompt()` method writes the `Interface` instances configured`prompt` to a new line in `output` in order to provide a user with a new + * location at which to provide input. + * + * When called, `rl.prompt()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or `undefined` the prompt is not written. + * @since v0.1.98 + * @param preserveCursor If `true`, prevents the cursor placement from being reset to `0`. + */ + prompt(preserveCursor?: boolean): void; + /** + * The `rl.question()` method displays the `query` by writing it to the `output`, + * waits for user input to be provided on `input`, then invokes the `callback` function passing the provided input as the first argument. + * + * When called, `rl.question()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or `undefined` the `query` is not written. + * + * The `callback` function passed to `rl.question()` does not follow the typical + * pattern of accepting an `Error` object or `null` as the first argument. + * The `callback` is called with the provided answer as the only argument. + * + * An error will be thrown if calling `rl.question()` after `rl.close()`. + * + * Example usage: + * + * ```js + * rl.question('What is your favorite food? ', (answer) => { + * console.log(`Oh, so your favorite food is ${answer}`); + * }); + * ``` + * + * Using an `AbortController` to cancel a question. + * + * ```js + * const ac = new AbortController(); + * const signal = ac.signal; + * + * rl.question('What is your favorite food? ', { signal }, (answer) => { + * console.log(`Oh, so your favorite food is ${answer}`); + * }); + * + * signal.addEventListener('abort', () => { + * console.log('The food question timed out'); + * }, { once: true }); + * + * setTimeout(() => ac.abort(), 10000); + * ``` + * @since v0.3.3 + * @param query A statement or query to write to `output`, prepended to the prompt. + * @param callback A callback function that is invoked with the user's input in response to the `query`. + */ + question(query: string, callback: (answer: string) => void): void; + question(query: string, options: Abortable, callback: (answer: string) => void): void; + /** + * The `rl.pause()` method pauses the `input` stream, allowing it to be resumed + * later if necessary. + * + * Calling `rl.pause()` does not immediately pause other events (including `'line'`) from being emitted by the `Interface` instance. + * @since v0.3.4 + */ + pause(): this; + /** + * The `rl.resume()` method resumes the `input` stream if it has been paused. + * @since v0.3.4 + */ + resume(): this; + /** + * The `rl.close()` method closes the `Interface` instance and + * relinquishes control over the `input` and `output` streams. When called, + * the `'close'` event will be emitted. + * + * Calling `rl.close()` does not immediately stop other events (including `'line'`) + * from being emitted by the `Interface` instance. + * @since v0.1.98 + */ + close(): void; + /** + * The `rl.write()` method will write either `data` or a key sequence identified + * by `key` to the `output`. The `key` argument is supported only if `output` is + * a `TTY` text terminal. See `TTY keybindings` for a list of key + * combinations. + * + * If `key` is specified, `data` is ignored. + * + * When called, `rl.write()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or `undefined` the `data` and `key` are not written. + * + * ```js + * rl.write('Delete this!'); + * // Simulate Ctrl+U to delete the line written previously + * rl.write(null, { ctrl: true, name: 'u' }); + * ``` + * + * The `rl.write()` method will write the data to the `readline` `Interface`'s `input` _as if it were provided by the user_. + * @since v0.1.98 + */ + write(data: string | Buffer, key?: Key): void; + write(data: undefined | null | string | Buffer, key: Key): void; + /** + * Returns the real position of the cursor in relation to the input + * prompt + string. Long input (wrapping) strings, as well as multiple + * line prompts are included in the calculations. + * @since v13.5.0, v12.16.0 + */ + getCursorPos(): CursorPos; + /** + * events.EventEmitter + * 1. close + * 2. line + * 3. pause + * 4. resume + * 5. SIGCONT + * 6. SIGINT + * 7. SIGTSTP + * 8. history + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "line", listener: (input: string) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "SIGCONT", listener: () => void): this; + addListener(event: "SIGINT", listener: () => void): this; + addListener(event: "SIGTSTP", listener: () => void): this; + addListener(event: "history", listener: (history: string[]) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "line", input: string): boolean; + emit(event: "pause"): boolean; + emit(event: "resume"): boolean; + emit(event: "SIGCONT"): boolean; + emit(event: "SIGINT"): boolean; + emit(event: "SIGTSTP"): boolean; + emit(event: "history", history: string[]): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "line", listener: (input: string) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "SIGCONT", listener: () => void): this; + on(event: "SIGINT", listener: () => void): this; + on(event: "SIGTSTP", listener: () => void): this; + on(event: "history", listener: (history: string[]) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "line", listener: (input: string) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "SIGCONT", listener: () => void): this; + once(event: "SIGINT", listener: () => void): this; + once(event: "SIGTSTP", listener: () => void): this; + once(event: "history", listener: (history: string[]) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "line", listener: (input: string) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "SIGCONT", listener: () => void): this; + prependListener(event: "SIGINT", listener: () => void): this; + prependListener(event: "SIGTSTP", listener: () => void): this; + prependListener(event: "history", listener: (history: string[]) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "line", listener: (input: string) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "SIGCONT", listener: () => void): this; + prependOnceListener(event: "SIGINT", listener: () => void): this; + prependOnceListener(event: "SIGTSTP", listener: () => void): this; + prependOnceListener(event: "history", listener: (history: string[]) => void): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + export type ReadLine = Interface; // type forwarded for backwards compatibility + export type Completer = (line: string) => CompleterResult; + export type AsyncCompleter = ( + line: string, + callback: (err?: null | Error, result?: CompleterResult) => void, + ) => void; + export type CompleterResult = [string[], string]; + export interface ReadLineOptions { + input: NodeJS.ReadableStream; + output?: NodeJS.WritableStream | undefined; + completer?: Completer | AsyncCompleter | undefined; + terminal?: boolean | undefined; + /** + * Initial list of history lines. This option makes sense + * only if `terminal` is set to `true` by the user or by an internal `output` + * check, otherwise the history caching mechanism is not initialized at all. + * @default [] + */ + history?: string[] | undefined; + historySize?: number | undefined; + prompt?: string | undefined; + crlfDelay?: number | undefined; + /** + * If `true`, when a new input line added + * to the history list duplicates an older one, this removes the older line + * from the list. + * @default false + */ + removeHistoryDuplicates?: boolean | undefined; + escapeCodeTimeout?: number | undefined; + tabSize?: number | undefined; + } + /** + * The `readline.createInterface()` method creates a new `readline.Interface` instance. + * + * ```js + * const readline = require('node:readline'); + * const rl = readline.createInterface({ + * input: process.stdin, + * output: process.stdout, + * }); + * ``` + * + * Once the `readline.Interface` instance is created, the most common case is to + * listen for the `'line'` event: + * + * ```js + * rl.on('line', (line) => { + * console.log(`Received: ${line}`); + * }); + * ``` + * + * If `terminal` is `true` for this instance then the `output` stream will get + * the best compatibility if it defines an `output.columns` property and emits + * a `'resize'` event on the `output` if or when the columns ever change + * (`process.stdout` does this automatically when it is a TTY). + * + * When creating a `readline.Interface` using `stdin` as input, the program + * will not terminate until it receives an [EOF character](https://en.wikipedia.org/wiki/End-of-file#EOF_character). To exit without + * waiting for user input, call `process.stdin.unref()`. + * @since v0.1.98 + */ + export function createInterface( + input: NodeJS.ReadableStream, + output?: NodeJS.WritableStream, + completer?: Completer | AsyncCompleter, + terminal?: boolean, + ): Interface; + export function createInterface(options: ReadLineOptions): Interface; + /** + * The `readline.emitKeypressEvents()` method causes the given `Readable` stream to begin emitting `'keypress'` events corresponding to received input. + * + * Optionally, `interface` specifies a `readline.Interface` instance for which + * autocompletion is disabled when copy-pasted input is detected. + * + * If the `stream` is a `TTY`, then it must be in raw mode. + * + * This is automatically called by any readline instance on its `input` if the `input` is a terminal. Closing the `readline` instance does not stop + * the `input` from emitting `'keypress'` events. + * + * ```js + * readline.emitKeypressEvents(process.stdin); + * if (process.stdin.isTTY) + * process.stdin.setRawMode(true); + * ``` + * + * ## Example: Tiny CLI + * + * The following example illustrates the use of `readline.Interface` class to + * implement a small command-line interface: + * + * ```js + * const readline = require('node:readline'); + * const rl = readline.createInterface({ + * input: process.stdin, + * output: process.stdout, + * prompt: 'OHAI> ', + * }); + * + * rl.prompt(); + * + * rl.on('line', (line) => { + * switch (line.trim()) { + * case 'hello': + * console.log('world!'); + * break; + * default: + * console.log(`Say what? I might have heard '${line.trim()}'`); + * break; + * } + * rl.prompt(); + * }).on('close', () => { + * console.log('Have a great day!'); + * process.exit(0); + * }); + * ``` + * + * ## Example: Read file stream line-by-Line + * + * A common use case for `readline` is to consume an input file one line at a + * time. The easiest way to do so is leveraging the `fs.ReadStream` API as + * well as a `for await...of` loop: + * + * ```js + * const fs = require('node:fs'); + * const readline = require('node:readline'); + * + * async function processLineByLine() { + * const fileStream = fs.createReadStream('input.txt'); + * + * const rl = readline.createInterface({ + * input: fileStream, + * crlfDelay: Infinity, + * }); + * // Note: we use the crlfDelay option to recognize all instances of CR LF + * // ('\r\n') in input.txt as a single line break. + * + * for await (const line of rl) { + * // Each line in input.txt will be successively available here as `line`. + * console.log(`Line from file: ${line}`); + * } + * } + * + * processLineByLine(); + * ``` + * + * Alternatively, one could use the `'line'` event: + * + * ```js + * const fs = require('node:fs'); + * const readline = require('node:readline'); + * + * const rl = readline.createInterface({ + * input: fs.createReadStream('sample.txt'), + * crlfDelay: Infinity, + * }); + * + * rl.on('line', (line) => { + * console.log(`Line from file: ${line}`); + * }); + * ``` + * + * Currently, `for await...of` loop can be a bit slower. If `async` / `await` flow and speed are both essential, a mixed approach can be applied: + * + * ```js + * const { once } = require('node:events'); + * const { createReadStream } = require('node:fs'); + * const { createInterface } = require('node:readline'); + * + * (async function processLineByLine() { + * try { + * const rl = createInterface({ + * input: createReadStream('big-file.txt'), + * crlfDelay: Infinity, + * }); + * + * rl.on('line', (line) => { + * // Process the line. + * }); + * + * await once(rl, 'close'); + * + * console.log('File processed.'); + * } catch (err) { + * console.error(err); + * } + * })(); + * ``` + * @since v0.7.7 + */ + export function emitKeypressEvents(stream: NodeJS.ReadableStream, readlineInterface?: Interface): void; + export type Direction = -1 | 0 | 1; + export interface CursorPos { + rows: number; + cols: number; + } + /** + * The `readline.clearLine()` method clears current line of given [TTY](https://nodejs.org/docs/latest-v22.x/api/tty.html) stream + * in a specified direction identified by `dir`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function clearLine(stream: NodeJS.WritableStream, dir: Direction, callback?: () => void): boolean; + /** + * The `readline.clearScreenDown()` method clears the given [TTY](https://nodejs.org/docs/latest-v22.x/api/tty.html) stream from + * the current position of the cursor down. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function clearScreenDown(stream: NodeJS.WritableStream, callback?: () => void): boolean; + /** + * The `readline.cursorTo()` method moves cursor to the specified position in a + * given [TTY](https://nodejs.org/docs/latest-v22.x/api/tty.html) `stream`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function cursorTo(stream: NodeJS.WritableStream, x: number, y?: number, callback?: () => void): boolean; + /** + * The `readline.moveCursor()` method moves the cursor _relative_ to its current + * position in a given [TTY](https://nodejs.org/docs/latest-v22.x/api/tty.html) `stream`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function moveCursor(stream: NodeJS.WritableStream, dx: number, dy: number, callback?: () => void): boolean; +} +declare module "node:readline" { + export * from "readline"; +} diff --git a/libcore/node_modules/@types/node/readline/promises.d.ts b/libcore/node_modules/@types/node/readline/promises.d.ts new file mode 100644 index 0000000..f2826bb --- /dev/null +++ b/libcore/node_modules/@types/node/readline/promises.d.ts @@ -0,0 +1,150 @@ +/** + * @since v17.0.0 + * @experimental + */ +declare module "readline/promises" { + import { AsyncCompleter, Completer, Direction, Interface as _Interface, ReadLineOptions } from "node:readline"; + import { Abortable } from "node:events"; + /** + * Instances of the `readlinePromises.Interface` class are constructed using the `readlinePromises.createInterface()` method. Every instance is associated with a + * single `input` `Readable` stream and a single `output` `Writable` stream. + * The `output` stream is used to print prompts for user input that arrives on, + * and is read from, the `input` stream. + * @since v17.0.0 + */ + class Interface extends _Interface { + /** + * The `rl.question()` method displays the `query` by writing it to the `output`, + * waits for user input to be provided on `input`, then invokes the `callback` function passing the provided input as the first argument. + * + * When called, `rl.question()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or `undefined` the `query` is not written. + * + * If the question is called after `rl.close()`, it returns a rejected promise. + * + * Example usage: + * + * ```js + * const answer = await rl.question('What is your favorite food? '); + * console.log(`Oh, so your favorite food is ${answer}`); + * ``` + * + * Using an `AbortSignal` to cancel a question. + * + * ```js + * const signal = AbortSignal.timeout(10_000); + * + * signal.addEventListener('abort', () => { + * console.log('The food question timed out'); + * }, { once: true }); + * + * const answer = await rl.question('What is your favorite food? ', { signal }); + * console.log(`Oh, so your favorite food is ${answer}`); + * ``` + * @since v17.0.0 + * @param query A statement or query to write to `output`, prepended to the prompt. + * @return A promise that is fulfilled with the user's input in response to the `query`. + */ + question(query: string): Promise; + question(query: string, options: Abortable): Promise; + } + /** + * @since v17.0.0 + */ + class Readline { + /** + * @param stream A TTY stream. + */ + constructor( + stream: NodeJS.WritableStream, + options?: { + autoCommit?: boolean; + }, + ); + /** + * The `rl.clearLine()` method adds to the internal list of pending action an + * action that clears current line of the associated `stream` in a specified + * direction identified by `dir`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * @since v17.0.0 + * @return this + */ + clearLine(dir: Direction): this; + /** + * The `rl.clearScreenDown()` method adds to the internal list of pending action an + * action that clears the associated stream from the current position of the + * cursor down. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * @since v17.0.0 + * @return this + */ + clearScreenDown(): this; + /** + * The `rl.commit()` method sends all the pending actions to the associated `stream` and clears the internal list of pending actions. + * @since v17.0.0 + */ + commit(): Promise; + /** + * The `rl.cursorTo()` method adds to the internal list of pending action an action + * that moves cursor to the specified position in the associated `stream`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * @since v17.0.0 + * @return this + */ + cursorTo(x: number, y?: number): this; + /** + * The `rl.moveCursor()` method adds to the internal list of pending action an + * action that moves the cursor _relative_ to its current position in the + * associated `stream`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * @since v17.0.0 + * @return this + */ + moveCursor(dx: number, dy: number): this; + /** + * The `rl.rollback` methods clears the internal list of pending actions without + * sending it to the associated `stream`. + * @since v17.0.0 + * @return this + */ + rollback(): this; + } + /** + * The `readlinePromises.createInterface()` method creates a new `readlinePromises.Interface` instance. + * + * ```js + * const readlinePromises = require('node:readline/promises'); + * const rl = readlinePromises.createInterface({ + * input: process.stdin, + * output: process.stdout, + * }); + * ``` + * + * Once the `readlinePromises.Interface` instance is created, the most common case + * is to listen for the `'line'` event: + * + * ```js + * rl.on('line', (line) => { + * console.log(`Received: ${line}`); + * }); + * ``` + * + * If `terminal` is `true` for this instance then the `output` stream will get + * the best compatibility if it defines an `output.columns` property and emits + * a `'resize'` event on the `output` if or when the columns ever change + * (`process.stdout` does this automatically when it is a TTY). + * @since v17.0.0 + */ + function createInterface( + input: NodeJS.ReadableStream, + output?: NodeJS.WritableStream, + completer?: Completer | AsyncCompleter, + terminal?: boolean, + ): Interface; + function createInterface(options: ReadLineOptions): Interface; +} +declare module "node:readline/promises" { + export * from "readline/promises"; +} diff --git a/libcore/node_modules/@types/node/repl.d.ts b/libcore/node_modules/@types/node/repl.d.ts new file mode 100644 index 0000000..c2b340c --- /dev/null +++ b/libcore/node_modules/@types/node/repl.d.ts @@ -0,0 +1,430 @@ +/** + * The `node:repl` module provides a Read-Eval-Print-Loop (REPL) implementation + * that is available both as a standalone program or includible in other + * applications. It can be accessed using: + * + * ```js + * const repl = require('node:repl'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/repl.js) + */ +declare module "repl" { + import { AsyncCompleter, Completer, Interface } from "node:readline"; + import { Context } from "node:vm"; + import { InspectOptions } from "node:util"; + interface ReplOptions { + /** + * The input prompt to display. + * @default "> " + */ + prompt?: string | undefined; + /** + * The `Readable` stream from which REPL input will be read. + * @default process.stdin + */ + input?: NodeJS.ReadableStream | undefined; + /** + * The `Writable` stream to which REPL output will be written. + * @default process.stdout + */ + output?: NodeJS.WritableStream | undefined; + /** + * If `true`, specifies that the output should be treated as a TTY terminal, and have + * ANSI/VT100 escape codes written to it. + * Default: checking the value of the `isTTY` property on the output stream upon + * instantiation. + */ + terminal?: boolean | undefined; + /** + * The function to be used when evaluating each given line of input. + * Default: an async wrapper for the JavaScript `eval()` function. An `eval` function can + * error with `repl.Recoverable` to indicate the input was incomplete and prompt for + * additional lines. + * + * @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_default_evaluation + * @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_custom_evaluation_functions + */ + eval?: REPLEval | undefined; + /** + * Defines if the repl prints output previews or not. + * @default `true` Always `false` in case `terminal` is falsy. + */ + preview?: boolean | undefined; + /** + * If `true`, specifies that the default `writer` function should include ANSI color + * styling to REPL output. If a custom `writer` function is provided then this has no + * effect. + * @default the REPL instance's `terminal` value + */ + useColors?: boolean | undefined; + /** + * If `true`, specifies that the default evaluation function will use the JavaScript + * `global` as the context as opposed to creating a new separate context for the REPL + * instance. The node CLI REPL sets this value to `true`. + * @default false + */ + useGlobal?: boolean | undefined; + /** + * If `true`, specifies that the default writer will not output the return value of a + * command if it evaluates to `undefined`. + * @default false + */ + ignoreUndefined?: boolean | undefined; + /** + * The function to invoke to format the output of each command before writing to `output`. + * @default a wrapper for `util.inspect` + * + * @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_customizing_repl_output + */ + writer?: REPLWriter | undefined; + /** + * An optional function used for custom Tab auto completion. + * + * @see https://nodejs.org/dist/latest-v22.x/docs/api/readline.html#readline_use_of_the_completer_function + */ + completer?: Completer | AsyncCompleter | undefined; + /** + * A flag that specifies whether the default evaluator executes all JavaScript commands in + * strict mode or default (sloppy) mode. + * Accepted values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + replMode?: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT | undefined; + /** + * Stop evaluating the current piece of code when `SIGINT` is received, i.e. `Ctrl+C` is + * pressed. This cannot be used together with a custom `eval` function. + * @default false + */ + breakEvalOnSigint?: boolean | undefined; + } + type REPLEval = ( + this: REPLServer, + evalCmd: string, + context: Context, + file: string, + cb: (err: Error | null, result: any) => void, + ) => void; + type REPLWriter = (this: REPLServer, obj: any) => string; + /** + * This is the default "writer" value, if none is passed in the REPL options, + * and it can be overridden by custom print functions. + */ + const writer: REPLWriter & { + options: InspectOptions; + }; + type REPLCommandAction = (this: REPLServer, text: string) => void; + interface REPLCommand { + /** + * Help text to be displayed when `.help` is entered. + */ + help?: string | undefined; + /** + * The function to execute, optionally accepting a single string argument. + */ + action: REPLCommandAction; + } + /** + * Instances of `repl.REPLServer` are created using the {@link start} method + * or directly using the JavaScript `new` keyword. + * + * ```js + * const repl = require('node:repl'); + * + * const options = { useColors: true }; + * + * const firstInstance = repl.start(options); + * const secondInstance = new repl.REPLServer(options); + * ``` + * @since v0.1.91 + */ + class REPLServer extends Interface { + /** + * The `vm.Context` provided to the `eval` function to be used for JavaScript + * evaluation. + */ + readonly context: Context; + /** + * @deprecated since v14.3.0 - Use `input` instead. + */ + readonly inputStream: NodeJS.ReadableStream; + /** + * @deprecated since v14.3.0 - Use `output` instead. + */ + readonly outputStream: NodeJS.WritableStream; + /** + * The `Readable` stream from which REPL input will be read. + */ + readonly input: NodeJS.ReadableStream; + /** + * The `Writable` stream to which REPL output will be written. + */ + readonly output: NodeJS.WritableStream; + /** + * The commands registered via `replServer.defineCommand()`. + */ + readonly commands: NodeJS.ReadOnlyDict; + /** + * A value indicating whether the REPL is currently in "editor mode". + * + * @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_commands_and_special_keys + */ + readonly editorMode: boolean; + /** + * A value indicating whether the `_` variable has been assigned. + * + * @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreAssigned: boolean; + /** + * The last evaluation result from the REPL (assigned to the `_` variable inside of the REPL). + * + * @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly last: any; + /** + * A value indicating whether the `_error` variable has been assigned. + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreErrAssigned: boolean; + /** + * The last error raised inside the REPL (assigned to the `_error` variable inside of the REPL). + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly lastError: any; + /** + * Specified in the REPL options, this is the function to be used when evaluating each + * given line of input. If not specified in the REPL options, this is an async wrapper + * for the JavaScript `eval()` function. + */ + readonly eval: REPLEval; + /** + * Specified in the REPL options, this is a value indicating whether the default + * `writer` function should include ANSI color styling to REPL output. + */ + readonly useColors: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `eval` + * function will use the JavaScript `global` as the context as opposed to creating a new + * separate context for the REPL instance. + */ + readonly useGlobal: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `writer` + * function should output the result of a command if it evaluates to `undefined`. + */ + readonly ignoreUndefined: boolean; + /** + * Specified in the REPL options, this is the function to invoke to format the output of + * each command before writing to `outputStream`. If not specified in the REPL options, + * this will be a wrapper for `util.inspect`. + */ + readonly writer: REPLWriter; + /** + * Specified in the REPL options, this is the function to use for custom Tab auto-completion. + */ + readonly completer: Completer | AsyncCompleter; + /** + * Specified in the REPL options, this is a flag that specifies whether the default `eval` + * function should execute all JavaScript commands in strict mode or default (sloppy) mode. + * Possible values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + readonly replMode: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT; + /** + * NOTE: According to the documentation: + * + * > Instances of `repl.REPLServer` are created using the `repl.start()` method and + * > _should not_ be created directly using the JavaScript `new` keyword. + * + * `REPLServer` cannot be subclassed due to implementation specifics in NodeJS. + * + * @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_class_replserver + */ + private constructor(); + /** + * The `replServer.defineCommand()` method is used to add new `.`\-prefixed commands + * to the REPL instance. Such commands are invoked by typing a `.` followed by the `keyword`. The `cmd` is either a `Function` or an `Object` with the following + * properties: + * + * The following example shows two new commands added to the REPL instance: + * + * ```js + * const repl = require('node:repl'); + * + * const replServer = repl.start({ prompt: '> ' }); + * replServer.defineCommand('sayhello', { + * help: 'Say hello', + * action(name) { + * this.clearBufferedCommand(); + * console.log(`Hello, ${name}!`); + * this.displayPrompt(); + * }, + * }); + * replServer.defineCommand('saybye', function saybye() { + * console.log('Goodbye!'); + * this.close(); + * }); + * ``` + * + * The new commands can then be used from within the REPL instance: + * + * ```console + * > .sayhello Node.js User + * Hello, Node.js User! + * > .saybye + * Goodbye! + * ``` + * @since v0.3.0 + * @param keyword The command keyword (_without_ a leading `.` character). + * @param cmd The function to invoke when the command is processed. + */ + defineCommand(keyword: string, cmd: REPLCommandAction | REPLCommand): void; + /** + * The `replServer.displayPrompt()` method readies the REPL instance for input + * from the user, printing the configured `prompt` to a new line in the `output` and resuming the `input` to accept new input. + * + * When multi-line input is being entered, an ellipsis is printed rather than the + * 'prompt'. + * + * When `preserveCursor` is `true`, the cursor placement will not be reset to `0`. + * + * The `replServer.displayPrompt` method is primarily intended to be called from + * within the action function for commands registered using the `replServer.defineCommand()` method. + * @since v0.1.91 + */ + displayPrompt(preserveCursor?: boolean): void; + /** + * The `replServer.clearBufferedCommand()` method clears any command that has been + * buffered but not yet executed. This method is primarily intended to be + * called from within the action function for commands registered using the `replServer.defineCommand()` method. + * @since v9.0.0 + */ + clearBufferedCommand(): void; + /** + * Initializes a history log file for the REPL instance. When executing the + * Node.js binary and using the command-line REPL, a history file is initialized + * by default. However, this is not the case when creating a REPL + * programmatically. Use this method to initialize a history log file when working + * with REPL instances programmatically. + * @since v11.10.0 + * @param historyPath the path to the history file + * @param callback called when history writes are ready or upon error + */ + setupHistory(path: string, callback: (err: Error | null, repl: this) => void): void; + /** + * events.EventEmitter + * 1. close - inherited from `readline.Interface` + * 2. line - inherited from `readline.Interface` + * 3. pause - inherited from `readline.Interface` + * 4. resume - inherited from `readline.Interface` + * 5. SIGCONT - inherited from `readline.Interface` + * 6. SIGINT - inherited from `readline.Interface` + * 7. SIGTSTP - inherited from `readline.Interface` + * 8. exit + * 9. reset + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "line", listener: (input: string) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "SIGCONT", listener: () => void): this; + addListener(event: "SIGINT", listener: () => void): this; + addListener(event: "SIGTSTP", listener: () => void): this; + addListener(event: "exit", listener: () => void): this; + addListener(event: "reset", listener: (context: Context) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "line", input: string): boolean; + emit(event: "pause"): boolean; + emit(event: "resume"): boolean; + emit(event: "SIGCONT"): boolean; + emit(event: "SIGINT"): boolean; + emit(event: "SIGTSTP"): boolean; + emit(event: "exit"): boolean; + emit(event: "reset", context: Context): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "line", listener: (input: string) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "SIGCONT", listener: () => void): this; + on(event: "SIGINT", listener: () => void): this; + on(event: "SIGTSTP", listener: () => void): this; + on(event: "exit", listener: () => void): this; + on(event: "reset", listener: (context: Context) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "line", listener: (input: string) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "SIGCONT", listener: () => void): this; + once(event: "SIGINT", listener: () => void): this; + once(event: "SIGTSTP", listener: () => void): this; + once(event: "exit", listener: () => void): this; + once(event: "reset", listener: (context: Context) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "line", listener: (input: string) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "SIGCONT", listener: () => void): this; + prependListener(event: "SIGINT", listener: () => void): this; + prependListener(event: "SIGTSTP", listener: () => void): this; + prependListener(event: "exit", listener: () => void): this; + prependListener(event: "reset", listener: (context: Context) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "line", listener: (input: string) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "SIGCONT", listener: () => void): this; + prependOnceListener(event: "SIGINT", listener: () => void): this; + prependOnceListener(event: "SIGTSTP", listener: () => void): this; + prependOnceListener(event: "exit", listener: () => void): this; + prependOnceListener(event: "reset", listener: (context: Context) => void): this; + } + /** + * A flag passed in the REPL options. Evaluates expressions in sloppy mode. + */ + const REPL_MODE_SLOPPY: unique symbol; + /** + * A flag passed in the REPL options. Evaluates expressions in strict mode. + * This is equivalent to prefacing every repl statement with `'use strict'`. + */ + const REPL_MODE_STRICT: unique symbol; + /** + * The `repl.start()` method creates and starts a {@link REPLServer} instance. + * + * If `options` is a string, then it specifies the input prompt: + * + * ```js + * const repl = require('node:repl'); + * + * // a Unix style prompt + * repl.start('$ '); + * ``` + * @since v0.1.91 + */ + function start(options?: string | ReplOptions): REPLServer; + /** + * Indicates a recoverable error that a `REPLServer` can use to support multi-line input. + * + * @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_recoverable_errors + */ + class Recoverable extends SyntaxError { + err: Error; + constructor(err: Error); + } +} +declare module "node:repl" { + export * from "repl"; +} diff --git a/libcore/node_modules/@types/node/sea.d.ts b/libcore/node_modules/@types/node/sea.d.ts new file mode 100644 index 0000000..0bedc62 --- /dev/null +++ b/libcore/node_modules/@types/node/sea.d.ts @@ -0,0 +1,153 @@ +/** + * This feature allows the distribution of a Node.js application conveniently to a + * system that does not have Node.js installed. + * + * Node.js supports the creation of [single executable applications](https://github.com/nodejs/single-executable) by allowing + * the injection of a blob prepared by Node.js, which can contain a bundled script, + * into the `node` binary. During start up, the program checks if anything has been + * injected. If the blob is found, it executes the script in the blob. Otherwise + * Node.js operates as it normally does. + * + * The single executable application feature currently only supports running a + * single embedded script using the `CommonJS` module system. + * + * Users can create a single executable application from their bundled script + * with the `node` binary itself and any tool which can inject resources into the + * binary. + * + * Here are the steps for creating a single executable application using one such + * tool, [postject](https://github.com/nodejs/postject): + * + * 1. Create a JavaScript file: + * ```bash + * echo 'console.log(`Hello, ${process.argv[2]}!`);' > hello.js + * ``` + * 2. Create a configuration file building a blob that can be injected into the + * single executable application (see `Generating single executable preparation blobs` for details): + * ```bash + * echo '{ "main": "hello.js", "output": "sea-prep.blob" }' > sea-config.json + * ``` + * 3. Generate the blob to be injected: + * ```bash + * node --experimental-sea-config sea-config.json + * ``` + * 4. Create a copy of the `node` executable and name it according to your needs: + * * On systems other than Windows: + * ```bash + * cp $(command -v node) hello + * ``` + * * On Windows: + * ```text + * node -e "require('fs').copyFileSync(process.execPath, 'hello.exe')" + * ``` + * The `.exe` extension is necessary. + * 5. Remove the signature of the binary (macOS and Windows only): + * * On macOS: + * ```bash + * codesign --remove-signature hello + * ``` + * * On Windows (optional): + * [signtool](https://learn.microsoft.com/en-us/windows/win32/seccrypto/signtool) can be used from the installed [Windows SDK](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/). + * If this step is + * skipped, ignore any signature-related warning from postject. + * ```powershell + * signtool remove /s hello.exe + * ``` + * 6. Inject the blob into the copied binary by running `postject` with + * the following options: + * * `hello` / `hello.exe` \- The name of the copy of the `node` executable + * created in step 4. + * * `NODE_SEA_BLOB` \- The name of the resource / note / section in the binary + * where the contents of the blob will be stored. + * * `sea-prep.blob` \- The name of the blob created in step 1. + * * `--sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2` \- The [fuse](https://www.electronjs.org/docs/latest/tutorial/fuses) used by the Node.js project to detect if a file has been + * injected. + * * `--macho-segment-name NODE_SEA` (only needed on macOS) - The name of the + * segment in the binary where the contents of the blob will be + * stored. + * To summarize, here is the required command for each platform: + * * On Linux: + * ```bash + * npx postject hello NODE_SEA_BLOB sea-prep.blob \ + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 + * ``` + * * On Windows - PowerShell: + * ```powershell + * npx postject hello.exe NODE_SEA_BLOB sea-prep.blob ` + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 + * ``` + * * On Windows - Command Prompt: + * ```text + * npx postject hello.exe NODE_SEA_BLOB sea-prep.blob ^ + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 + * ``` + * * On macOS: + * ```bash + * npx postject hello NODE_SEA_BLOB sea-prep.blob \ + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 \ + * --macho-segment-name NODE_SEA + * ``` + * 7. Sign the binary (macOS and Windows only): + * * On macOS: + * ```bash + * codesign --sign - hello + * ``` + * * On Windows (optional): + * A certificate needs to be present for this to work. However, the unsigned + * binary would still be runnable. + * ```powershell + * signtool sign /fd SHA256 hello.exe + * ``` + * 8. Run the binary: + * * On systems other than Windows + * ```console + * $ ./hello world + * Hello, world! + * ``` + * * On Windows + * ```console + * $ .\hello.exe world + * Hello, world! + * ``` + * @since v19.7.0, v18.16.0 + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v22.x/src/node_sea.cc) + */ +declare module "node:sea" { + type AssetKey = string; + /** + * @since v20.12.0 + * @return Whether this script is running inside a single-executable application. + */ + function isSea(): boolean; + /** + * This method can be used to retrieve the assets configured to be bundled into the + * single-executable application at build time. + * An error is thrown when no matching asset can be found. + * @since v20.12.0 + */ + function getAsset(key: AssetKey): ArrayBuffer; + function getAsset(key: AssetKey, encoding: string): string; + /** + * Similar to `sea.getAsset()`, but returns the result in a [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob). + * An error is thrown when no matching asset can be found. + * @since v20.12.0 + */ + function getAssetAsBlob(key: AssetKey, options?: { + type: string; + }): Blob; + /** + * This method can be used to retrieve the assets configured to be bundled into the + * single-executable application at build time. + * An error is thrown when no matching asset can be found. + * + * Unlike `sea.getRawAsset()` or `sea.getAssetAsBlob()`, this method does not + * return a copy. Instead, it returns the raw asset bundled inside the executable. + * + * For now, users should avoid writing to the returned array buffer. If the + * injected section is not marked as writable or not aligned properly, + * writes to the returned array buffer is likely to result in a crash. + * @since v20.12.0 + */ + function getRawAsset(key: AssetKey): string | ArrayBuffer; +} diff --git a/libcore/node_modules/@types/node/sqlite.d.ts b/libcore/node_modules/@types/node/sqlite.d.ts new file mode 100644 index 0000000..006a25b --- /dev/null +++ b/libcore/node_modules/@types/node/sqlite.d.ts @@ -0,0 +1,213 @@ +/** + * The `node:sqlite` module facilitates working with SQLite databases. + * To access it: + * + * ```js + * import sqlite from 'node:sqlite'; + * ``` + * + * This module is only available under the `node:` scheme. The following will not + * work: + * + * ```js + * import sqlite from 'sqlite'; + * ``` + * + * The following example shows the basic usage of the `node:sqlite` module to open + * an in-memory database, write data to the database, and then read the data back. + * + * ```js + * import { DatabaseSync } from 'node:sqlite'; + * const database = new DatabaseSync(':memory:'); + * + * // Execute SQL statements from strings. + * database.exec(` + * CREATE TABLE data( + * key INTEGER PRIMARY KEY, + * value TEXT + * ) STRICT + * `); + * // Create a prepared statement to insert data into the database. + * const insert = database.prepare('INSERT INTO data (key, value) VALUES (?, ?)'); + * // Execute the prepared statement with bound values. + * insert.run(1, 'hello'); + * insert.run(2, 'world'); + * // Create a prepared statement to read data from the database. + * const query = database.prepare('SELECT * FROM data ORDER BY key'); + * // Execute the prepared statement and log the result set. + * console.log(query.all()); + * // Prints: [ { key: 1, value: 'hello' }, { key: 2, value: 'world' } ] + * ``` + * @since v22.5.0 + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/sqlite.js) + */ +declare module "node:sqlite" { + interface DatabaseSyncOptions { + /** + * If `true`, the database is opened by the constructor. + * When this value is `false`, the database must be opened via the `open()` method. + */ + open?: boolean | undefined; + } + /** + * This class represents a single [connection](https://www.sqlite.org/c3ref/sqlite3.html) to a SQLite database. All APIs + * exposed by this class execute synchronously. + * @since v22.5.0 + */ + class DatabaseSync { + /** + * Constructs a new `DatabaseSync` instance. + * @param location The location of the database. + * A SQLite database can be stored in a file or completely [in memory](https://www.sqlite.org/inmemorydb.html). + * To use a file-backed database, the location should be a file path. + * To use an in-memory database, the location should be the special name `':memory:'`. + * @param options Configuration options for the database connection. + */ + constructor(location: string, options?: DatabaseSyncOptions); + /** + * Closes the database connection. An exception is thrown if the database is not + * open. This method is a wrapper around [`sqlite3_close_v2()`](https://www.sqlite.org/c3ref/close.html). + * @since v22.5.0 + */ + close(): void; + /** + * This method allows one or more SQL statements to be executed without returning + * any results. This method is useful when executing SQL statements read from a + * file. This method is a wrapper around [`sqlite3_exec()`](https://www.sqlite.org/c3ref/exec.html). + * @since v22.5.0 + * @param sql A SQL string to execute. + */ + exec(sql: string): void; + /** + * Opens the database specified in the `location` argument of the `DatabaseSync`constructor. This method should only be used when the database is not opened via + * the constructor. An exception is thrown if the database is already open. + * @since v22.5.0 + */ + open(): void; + /** + * Compiles a SQL statement into a [prepared statement](https://www.sqlite.org/c3ref/stmt.html). This method is a wrapper + * around [`sqlite3_prepare_v2()`](https://www.sqlite.org/c3ref/prepare.html). + * @since v22.5.0 + * @param sql A SQL string to compile to a prepared statement. + * @return The prepared statement. + */ + prepare(sql: string): StatementSync; + } + type SupportedValueType = null | number | bigint | string | Uint8Array; + interface StatementResultingChanges { + /** + * The number of rows modified, inserted, or deleted by the most recently completed `INSERT`, `UPDATE`, or `DELETE` statement. + * This field is either a number or a `BigInt` depending on the prepared statement's configuration. + * This property is the result of [`sqlite3_changes64()`](https://www.sqlite.org/c3ref/changes.html). + */ + changes: number | bigint; + /** + * The most recently inserted rowid. + * This field is either a number or a `BigInt` depending on the prepared statement's configuration. + * This property is the result of [`sqlite3_last_insert_rowid()`](https://www.sqlite.org/c3ref/last_insert_rowid.html). + */ + lastInsertRowid: number | bigint; + } + /** + * This class represents a single [prepared statement](https://www.sqlite.org/c3ref/stmt.html). This class cannot be + * instantiated via its constructor. Instead, instances are created via the`database.prepare()` method. All APIs exposed by this class execute + * synchronously. + * + * A prepared statement is an efficient binary representation of the SQL used to + * create it. Prepared statements are parameterizable, and can be invoked multiple + * times with different bound values. Parameters also offer protection against [SQL injection](https://en.wikipedia.org/wiki/SQL_injection) attacks. For these reasons, prepared statements are + * preferred + * over hand-crafted SQL strings when handling user input. + * @since v22.5.0 + */ + class StatementSync { + private constructor(); + /** + * This method executes a prepared statement and returns all results as an array of + * objects. If the prepared statement does not return any results, this method + * returns an empty array. The prepared statement [parameters are bound](https://www.sqlite.org/c3ref/bind_blob.html) using + * the values in `namedParameters` and `anonymousParameters`. + * @since v22.5.0 + * @param namedParameters An optional object used to bind named parameters. The keys of this object are used to configure the mapping. + * @param anonymousParameters Zero or more values to bind to anonymous parameters. + * @return An array of objects. Each object corresponds to a row returned by executing the prepared statement. The keys and values of each object correspond to the column names and values of + * the row. + */ + all(...anonymousParameters: SupportedValueType[]): unknown[]; + all( + namedParameters: Record, + ...anonymousParameters: SupportedValueType[] + ): unknown[]; + /** + * This method returns the source SQL of the prepared statement with parameter + * placeholders replaced by values. This method is a wrapper around [`sqlite3_expanded_sql()`](https://www.sqlite.org/c3ref/expanded_sql.html). + * @since v22.5.0 + * @return The source SQL expanded to include parameter values. + */ + expandedSQL(): string; + /** + * This method executes a prepared statement and returns the first result as an + * object. If the prepared statement does not return any results, this method + * returns `undefined`. The prepared statement [parameters are bound](https://www.sqlite.org/c3ref/bind_blob.html) using the + * values in `namedParameters` and `anonymousParameters`. + * @since v22.5.0 + * @param namedParameters An optional object used to bind named parameters. The keys of this object are used to configure the mapping. + * @param anonymousParameters Zero or more values to bind to anonymous parameters. + * @return An object corresponding to the first row returned by executing the prepared statement. The keys and values of the object correspond to the column names and values of the row. If no + * rows were returned from the database then this method returns `undefined`. + */ + get(...anonymousParameters: SupportedValueType[]): unknown; + get(namedParameters: Record, ...anonymousParameters: SupportedValueType[]): unknown; + /** + * This method executes a prepared statement and returns an object summarizing the + * resulting changes. The prepared statement [parameters are bound](https://www.sqlite.org/c3ref/bind_blob.html) using the + * values in `namedParameters` and `anonymousParameters`. + * @since v22.5.0 + * @param namedParameters An optional object used to bind named parameters. The keys of this object are used to configure the mapping. + * @param anonymousParameters Zero or more values to bind to anonymous parameters. + */ + run(...anonymousParameters: SupportedValueType[]): StatementResultingChanges; + run( + namedParameters: Record, + ...anonymousParameters: SupportedValueType[] + ): StatementResultingChanges; + /** + * The names of SQLite parameters begin with a prefix character. By default,`node:sqlite` requires that this prefix character is present when binding + * parameters. However, with the exception of dollar sign character, these + * prefix characters also require extra quoting when used in object keys. + * + * To improve ergonomics, this method can be used to also allow bare named + * parameters, which do not require the prefix character in JavaScript code. There + * are several caveats to be aware of when enabling bare named parameters: + * + * * The prefix character is still required in SQL. + * * The prefix character is still allowed in JavaScript. In fact, prefixed names + * will have slightly better binding performance. + * * Using ambiguous named parameters, such as `$k` and `@k`, in the same prepared + * statement will result in an exception as it cannot be determined how to bind + * a bare name. + * @since v22.5.0 + * @param enabled Enables or disables support for binding named parameters without the prefix character. + */ + setAllowBareNamedParameters(enabled: boolean): void; + /** + * When reading from the database, SQLite `INTEGER`s are mapped to JavaScript + * numbers by default. However, SQLite `INTEGER`s can store values larger than + * JavaScript numbers are capable of representing. In such cases, this method can + * be used to read `INTEGER` data using JavaScript `BigInt`s. This method has no + * impact on database write operations where numbers and `BigInt`s are both + * supported at all times. + * @since v22.5.0 + * @param enabled Enables or disables the use of `BigInt`s when reading `INTEGER` fields from the database. + */ + setReadBigInts(enabled: boolean): void; + /** + * This method returns the source SQL of the prepared statement. This method is a + * wrapper around [`sqlite3_sql()`](https://www.sqlite.org/c3ref/expanded_sql.html). + * @since v22.5.0 + * @return The source SQL used to create this prepared statement. + */ + sourceSQL(): string; + } +} diff --git a/libcore/node_modules/@types/node/stream.d.ts b/libcore/node_modules/@types/node/stream.d.ts new file mode 100644 index 0000000..a5f6ede --- /dev/null +++ b/libcore/node_modules/@types/node/stream.d.ts @@ -0,0 +1,1707 @@ +/** + * A stream is an abstract interface for working with streaming data in Node.js. + * The `node:stream` module provides an API for implementing the stream interface. + * + * There are many stream objects provided by Node.js. For instance, a [request to an HTTP server](https://nodejs.org/docs/latest-v22.x/api/http.html#class-httpincomingmessage) + * and [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) are both stream instances. + * + * Streams can be readable, writable, or both. All streams are instances of [`EventEmitter`](https://nodejs.org/docs/latest-v22.x/api/events.html#class-eventemitter). + * + * To access the `node:stream` module: + * + * ```js + * const stream = require('node:stream'); + * ``` + * + * The `node:stream` module is useful for creating new types of stream instances. + * It is usually not necessary to use the `node:stream` module to consume streams. + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/stream.js) + */ +declare module "stream" { + import { Abortable, EventEmitter } from "node:events"; + import { Blob as NodeBlob } from "node:buffer"; + import * as streamPromises from "node:stream/promises"; + import * as streamConsumers from "node:stream/consumers"; + import * as streamWeb from "node:stream/web"; + + type ComposeFnParam = (source: any) => void; + + class internal extends EventEmitter { + pipe( + destination: T, + options?: { + end?: boolean | undefined; + }, + ): T; + compose( + stream: T | ComposeFnParam | Iterable | AsyncIterable, + options?: { signal: AbortSignal }, + ): T; + } + import Stream = internal.Stream; + import Readable = internal.Readable; + import ReadableOptions = internal.ReadableOptions; + interface ArrayOptions { + /** + * The maximum concurrent invocations of `fn` to call on the stream at once. + * @default 1 + */ + concurrency?: number; + /** Allows destroying the stream if the signal is aborted. */ + signal?: AbortSignal; + } + class ReadableBase extends Stream implements NodeJS.ReadableStream { + /** + * A utility method for creating Readable Streams out of iterators. + * @since v12.3.0, v10.17.0 + * @param iterable Object implementing the `Symbol.asyncIterator` or `Symbol.iterator` iterable protocol. Emits an 'error' event if a null value is passed. + * @param options Options provided to `new stream.Readable([options])`. By default, `Readable.from()` will set `options.objectMode` to `true`, unless this is explicitly opted out by setting `options.objectMode` to `false`. + */ + static from(iterable: Iterable | AsyncIterable, options?: ReadableOptions): Readable; + /** + * Returns whether the stream has been read from or cancelled. + * @since v16.8.0 + */ + static isDisturbed(stream: Readable | NodeJS.ReadableStream): boolean; + /** + * Returns whether the stream was destroyed or errored before emitting `'end'`. + * @since v16.8.0 + * @experimental + */ + readonly readableAborted: boolean; + /** + * Is `true` if it is safe to call {@link read}, which means + * the stream has not been destroyed or emitted `'error'` or `'end'`. + * @since v11.4.0 + */ + readable: boolean; + /** + * Returns whether `'data'` has been emitted. + * @since v16.7.0, v14.18.0 + * @experimental + */ + readonly readableDidRead: boolean; + /** + * Getter for the property `encoding` of a given `Readable` stream. The `encoding` property can be set using the {@link setEncoding} method. + * @since v12.7.0 + */ + readonly readableEncoding: BufferEncoding | null; + /** + * Becomes `true` when [`'end'`](https://nodejs.org/docs/latest-v22.x/api/stream.html#event-end) event is emitted. + * @since v12.9.0 + */ + readonly readableEnded: boolean; + /** + * This property reflects the current state of a `Readable` stream as described + * in the [Three states](https://nodejs.org/docs/latest-v22.x/api/stream.html#three-states) section. + * @since v9.4.0 + */ + readonly readableFlowing: boolean | null; + /** + * Returns the value of `highWaterMark` passed when creating this `Readable`. + * @since v9.3.0 + */ + readonly readableHighWaterMark: number; + /** + * This property contains the number of bytes (or objects) in the queue + * ready to be read. The value provides introspection data regarding + * the status of the `highWaterMark`. + * @since v9.4.0 + */ + readonly readableLength: number; + /** + * Getter for the property `objectMode` of a given `Readable` stream. + * @since v12.3.0 + */ + readonly readableObjectMode: boolean; + /** + * Is `true` after `readable.destroy()` has been called. + * @since v8.0.0 + */ + destroyed: boolean; + /** + * Is `true` after `'close'` has been emitted. + * @since v18.0.0 + */ + readonly closed: boolean; + /** + * Returns error if the stream has been destroyed with an error. + * @since v18.0.0 + */ + readonly errored: Error | null; + constructor(opts?: ReadableOptions); + _construct?(callback: (error?: Error | null) => void): void; + _read(size: number): void; + /** + * The `readable.read()` method reads data out of the internal buffer and + * returns it. If no data is available to be read, `null` is returned. By default, + * the data is returned as a `Buffer` object unless an encoding has been + * specified using the `readable.setEncoding()` method or the stream is operating + * in object mode. + * + * The optional `size` argument specifies a specific number of bytes to read. If + * `size` bytes are not available to be read, `null` will be returned _unless_ the + * stream has ended, in which case all of the data remaining in the internal buffer + * will be returned. + * + * If the `size` argument is not specified, all of the data contained in the + * internal buffer will be returned. + * + * The `size` argument must be less than or equal to 1 GiB. + * + * The `readable.read()` method should only be called on `Readable` streams + * operating in paused mode. In flowing mode, `readable.read()` is called + * automatically until the internal buffer is fully drained. + * + * ```js + * const readable = getReadableStreamSomehow(); + * + * // 'readable' may be triggered multiple times as data is buffered in + * readable.on('readable', () => { + * let chunk; + * console.log('Stream is readable (new data received in buffer)'); + * // Use a loop to make sure we read all currently available data + * while (null !== (chunk = readable.read())) { + * console.log(`Read ${chunk.length} bytes of data...`); + * } + * }); + * + * // 'end' will be triggered once when there is no more data available + * readable.on('end', () => { + * console.log('Reached end of stream.'); + * }); + * ``` + * + * Each call to `readable.read()` returns a chunk of data, or `null`. The chunks + * are not concatenated. A `while` loop is necessary to consume all data + * currently in the buffer. When reading a large file `.read()` may return `null`, + * having consumed all buffered content so far, but there is still more data to + * come not yet buffered. In this case a new `'readable'` event will be emitted + * when there is more data in the buffer. Finally the `'end'` event will be + * emitted when there is no more data to come. + * + * Therefore to read a file's whole contents from a `readable`, it is necessary + * to collect chunks across multiple `'readable'` events: + * + * ```js + * const chunks = []; + * + * readable.on('readable', () => { + * let chunk; + * while (null !== (chunk = readable.read())) { + * chunks.push(chunk); + * } + * }); + * + * readable.on('end', () => { + * const content = chunks.join(''); + * }); + * ``` + * + * A `Readable` stream in object mode will always return a single item from + * a call to `readable.read(size)`, regardless of the value of the `size` argument. + * + * If the `readable.read()` method returns a chunk of data, a `'data'` event will + * also be emitted. + * + * Calling {@link read} after the `'end'` event has + * been emitted will return `null`. No runtime error will be raised. + * @since v0.9.4 + * @param size Optional argument to specify how much data to read. + */ + read(size?: number): any; + /** + * The `readable.setEncoding()` method sets the character encoding for + * data read from the `Readable` stream. + * + * By default, no encoding is assigned and stream data will be returned as `Buffer` objects. Setting an encoding causes the stream data + * to be returned as strings of the specified encoding rather than as `Buffer` objects. For instance, calling `readable.setEncoding('utf8')` will cause the + * output data to be interpreted as UTF-8 data, and passed as strings. Calling `readable.setEncoding('hex')` will cause the data to be encoded in hexadecimal + * string format. + * + * The `Readable` stream will properly handle multi-byte characters delivered + * through the stream that would otherwise become improperly decoded if simply + * pulled from the stream as `Buffer` objects. + * + * ```js + * const readable = getReadableStreamSomehow(); + * readable.setEncoding('utf8'); + * readable.on('data', (chunk) => { + * assert.equal(typeof chunk, 'string'); + * console.log('Got %d characters of string data:', chunk.length); + * }); + * ``` + * @since v0.9.4 + * @param encoding The encoding to use. + */ + setEncoding(encoding: BufferEncoding): this; + /** + * The `readable.pause()` method will cause a stream in flowing mode to stop + * emitting `'data'` events, switching out of flowing mode. Any data that + * becomes available will remain in the internal buffer. + * + * ```js + * const readable = getReadableStreamSomehow(); + * readable.on('data', (chunk) => { + * console.log(`Received ${chunk.length} bytes of data.`); + * readable.pause(); + * console.log('There will be no additional data for 1 second.'); + * setTimeout(() => { + * console.log('Now data will start flowing again.'); + * readable.resume(); + * }, 1000); + * }); + * ``` + * + * The `readable.pause()` method has no effect if there is a `'readable'` event listener. + * @since v0.9.4 + */ + pause(): this; + /** + * The `readable.resume()` method causes an explicitly paused `Readable` stream to + * resume emitting `'data'` events, switching the stream into flowing mode. + * + * The `readable.resume()` method can be used to fully consume the data from a + * stream without actually processing any of that data: + * + * ```js + * getReadableStreamSomehow() + * .resume() + * .on('end', () => { + * console.log('Reached the end, but did not read anything.'); + * }); + * ``` + * + * The `readable.resume()` method has no effect if there is a `'readable'` event listener. + * @since v0.9.4 + */ + resume(): this; + /** + * The `readable.isPaused()` method returns the current operating state of the `Readable`. + * This is used primarily by the mechanism that underlies the `readable.pipe()` method. + * In most typical cases, there will be no reason to use this method directly. + * + * ```js + * const readable = new stream.Readable(); + * + * readable.isPaused(); // === false + * readable.pause(); + * readable.isPaused(); // === true + * readable.resume(); + * readable.isPaused(); // === false + * ``` + * @since v0.11.14 + */ + isPaused(): boolean; + /** + * The `readable.unpipe()` method detaches a `Writable` stream previously attached + * using the {@link pipe} method. + * + * If the `destination` is not specified, then _all_ pipes are detached. + * + * If the `destination` is specified, but no pipe is set up for it, then + * the method does nothing. + * + * ```js + * const fs = require('node:fs'); + * const readable = getReadableStreamSomehow(); + * const writable = fs.createWriteStream('file.txt'); + * // All the data from readable goes into 'file.txt', + * // but only for the first second. + * readable.pipe(writable); + * setTimeout(() => { + * console.log('Stop writing to file.txt.'); + * readable.unpipe(writable); + * console.log('Manually close the file stream.'); + * writable.end(); + * }, 1000); + * ``` + * @since v0.9.4 + * @param destination Optional specific stream to unpipe + */ + unpipe(destination?: NodeJS.WritableStream): this; + /** + * Passing `chunk` as `null` signals the end of the stream (EOF) and behaves the + * same as `readable.push(null)`, after which no more data can be written. The EOF + * signal is put at the end of the buffer and any buffered data will still be + * flushed. + * + * The `readable.unshift()` method pushes a chunk of data back into the internal + * buffer. This is useful in certain situations where a stream is being consumed by + * code that needs to "un-consume" some amount of data that it has optimistically + * pulled out of the source, so that the data can be passed on to some other party. + * + * The `stream.unshift(chunk)` method cannot be called after the `'end'` event + * has been emitted or a runtime error will be thrown. + * + * Developers using `stream.unshift()` often should consider switching to + * use of a `Transform` stream instead. See the `API for stream implementers` section for more information. + * + * ```js + * // Pull off a header delimited by \n\n. + * // Use unshift() if we get too much. + * // Call the callback with (error, header, stream). + * const { StringDecoder } = require('node:string_decoder'); + * function parseHeader(stream, callback) { + * stream.on('error', callback); + * stream.on('readable', onReadable); + * const decoder = new StringDecoder('utf8'); + * let header = ''; + * function onReadable() { + * let chunk; + * while (null !== (chunk = stream.read())) { + * const str = decoder.write(chunk); + * if (str.includes('\n\n')) { + * // Found the header boundary. + * const split = str.split(/\n\n/); + * header += split.shift(); + * const remaining = split.join('\n\n'); + * const buf = Buffer.from(remaining, 'utf8'); + * stream.removeListener('error', callback); + * // Remove the 'readable' listener before unshifting. + * stream.removeListener('readable', onReadable); + * if (buf.length) + * stream.unshift(buf); + * // Now the body of the message can be read from the stream. + * callback(null, header, stream); + * return; + * } + * // Still reading the header. + * header += str; + * } + * } + * } + * ``` + * + * Unlike {@link push}, `stream.unshift(chunk)` will not + * end the reading process by resetting the internal reading state of the stream. + * This can cause unexpected results if `readable.unshift()` is called during a + * read (i.e. from within a {@link _read} implementation on a + * custom stream). Following the call to `readable.unshift()` with an immediate {@link push} will reset the reading state appropriately, + * however it is best to simply avoid calling `readable.unshift()` while in the + * process of performing a read. + * @since v0.9.11 + * @param chunk Chunk of data to unshift onto the read queue. For streams not operating in object mode, `chunk` must + * be a {string}, {Buffer}, {TypedArray}, {DataView} or `null`. For object mode streams, `chunk` may be any JavaScript value. + * @param encoding Encoding of string chunks. Must be a valid `Buffer` encoding, such as `'utf8'` or `'ascii'`. + */ + unshift(chunk: any, encoding?: BufferEncoding): void; + /** + * Prior to Node.js 0.10, streams did not implement the entire `node:stream` module API as it is currently defined. (See `Compatibility` for more + * information.) + * + * When using an older Node.js library that emits `'data'` events and has a {@link pause} method that is advisory only, the `readable.wrap()` method can be used to create a `Readable` + * stream that uses + * the old stream as its data source. + * + * It will rarely be necessary to use `readable.wrap()` but the method has been + * provided as a convenience for interacting with older Node.js applications and + * libraries. + * + * ```js + * const { OldReader } = require('./old-api-module.js'); + * const { Readable } = require('node:stream'); + * const oreader = new OldReader(); + * const myReader = new Readable().wrap(oreader); + * + * myReader.on('readable', () => { + * myReader.read(); // etc. + * }); + * ``` + * @since v0.9.4 + * @param stream An "old style" readable stream + */ + wrap(stream: NodeJS.ReadableStream): this; + push(chunk: any, encoding?: BufferEncoding): boolean; + /** + * The iterator created by this method gives users the option to cancel the destruction + * of the stream if the `for await...of` loop is exited by `return`, `break`, or `throw`, + * or if the iterator should destroy the stream if the stream emitted an error during iteration. + * @since v16.3.0 + * @param options.destroyOnReturn When set to `false`, calling `return` on the async iterator, + * or exiting a `for await...of` iteration using a `break`, `return`, or `throw` will not destroy the stream. + * **Default: `true`**. + */ + iterator(options?: { destroyOnReturn?: boolean }): AsyncIterableIterator; + /** + * This method allows mapping over the stream. The *fn* function will be called for every chunk in the stream. + * If the *fn* function returns a promise - that promise will be `await`ed before being passed to the result stream. + * @since v17.4.0, v16.14.0 + * @param fn a function to map over every chunk in the stream. Async or not. + * @returns a stream mapped with the function *fn*. + */ + map(fn: (data: any, options?: Pick) => any, options?: ArrayOptions): Readable; + /** + * This method allows filtering the stream. For each chunk in the stream the *fn* function will be called + * and if it returns a truthy value, the chunk will be passed to the result stream. + * If the *fn* function returns a promise - that promise will be `await`ed. + * @since v17.4.0, v16.14.0 + * @param fn a function to filter chunks from the stream. Async or not. + * @returns a stream filtered with the predicate *fn*. + */ + filter( + fn: (data: any, options?: Pick) => boolean | Promise, + options?: ArrayOptions, + ): Readable; + /** + * This method allows iterating a stream. For each chunk in the stream the *fn* function will be called. + * If the *fn* function returns a promise - that promise will be `await`ed. + * + * This method is different from `for await...of` loops in that it can optionally process chunks concurrently. + * In addition, a `forEach` iteration can only be stopped by having passed a `signal` option + * and aborting the related AbortController while `for await...of` can be stopped with `break` or `return`. + * In either case the stream will be destroyed. + * + * This method is different from listening to the `'data'` event in that it uses the `readable` event + * in the underlying machinary and can limit the number of concurrent *fn* calls. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise for when the stream has finished. + */ + forEach( + fn: (data: any, options?: Pick) => void | Promise, + options?: ArrayOptions, + ): Promise; + /** + * This method allows easily obtaining the contents of a stream. + * + * As this method reads the entire stream into memory, it negates the benefits of streams. It's intended + * for interoperability and convenience, not as the primary way to consume streams. + * @since v17.5.0 + * @returns a promise containing an array with the contents of the stream. + */ + toArray(options?: Pick): Promise; + /** + * This method is similar to `Array.prototype.some` and calls *fn* on each chunk in the stream + * until the awaited return value is `true` (or any truthy value). Once an *fn* call on a chunk + * `await`ed return value is truthy, the stream is destroyed and the promise is fulfilled with `true`. + * If none of the *fn* calls on the chunks return a truthy value, the promise is fulfilled with `false`. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise evaluating to `true` if *fn* returned a truthy value for at least one of the chunks. + */ + some( + fn: (data: any, options?: Pick) => boolean | Promise, + options?: ArrayOptions, + ): Promise; + /** + * This method is similar to `Array.prototype.find` and calls *fn* on each chunk in the stream + * to find a chunk with a truthy value for *fn*. Once an *fn* call's awaited return value is truthy, + * the stream is destroyed and the promise is fulfilled with value for which *fn* returned a truthy value. + * If all of the *fn* calls on the chunks return a falsy value, the promise is fulfilled with `undefined`. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise evaluating to the first chunk for which *fn* evaluated with a truthy value, + * or `undefined` if no element was found. + */ + find( + fn: (data: any, options?: Pick) => data is T, + options?: ArrayOptions, + ): Promise; + find( + fn: (data: any, options?: Pick) => boolean | Promise, + options?: ArrayOptions, + ): Promise; + /** + * This method is similar to `Array.prototype.every` and calls *fn* on each chunk in the stream + * to check if all awaited return values are truthy value for *fn*. Once an *fn* call on a chunk + * `await`ed return value is falsy, the stream is destroyed and the promise is fulfilled with `false`. + * If all of the *fn* calls on the chunks return a truthy value, the promise is fulfilled with `true`. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise evaluating to `true` if *fn* returned a truthy value for every one of the chunks. + */ + every( + fn: (data: any, options?: Pick) => boolean | Promise, + options?: ArrayOptions, + ): Promise; + /** + * This method returns a new stream by applying the given callback to each chunk of the stream + * and then flattening the result. + * + * It is possible to return a stream or another iterable or async iterable from *fn* and the result streams + * will be merged (flattened) into the returned stream. + * @since v17.5.0 + * @param fn a function to map over every chunk in the stream. May be async. May be a stream or generator. + * @returns a stream flat-mapped with the function *fn*. + */ + flatMap(fn: (data: any, options?: Pick) => any, options?: ArrayOptions): Readable; + /** + * This method returns a new stream with the first *limit* chunks dropped from the start. + * @since v17.5.0 + * @param limit the number of chunks to drop from the readable. + * @returns a stream with *limit* chunks dropped from the start. + */ + drop(limit: number, options?: Pick): Readable; + /** + * This method returns a new stream with the first *limit* chunks. + * @since v17.5.0 + * @param limit the number of chunks to take from the readable. + * @returns a stream with *limit* chunks taken. + */ + take(limit: number, options?: Pick): Readable; + /** + * This method returns a new stream with chunks of the underlying stream paired with a counter + * in the form `[index, chunk]`. The first index value is `0` and it increases by 1 for each chunk produced. + * @since v17.5.0 + * @returns a stream of indexed pairs. + */ + asIndexedPairs(options?: Pick): Readable; + /** + * This method calls *fn* on each chunk of the stream in order, passing it the result from the calculation + * on the previous element. It returns a promise for the final value of the reduction. + * + * If no *initial* value is supplied the first chunk of the stream is used as the initial value. + * If the stream is empty, the promise is rejected with a `TypeError` with the `ERR_INVALID_ARGS` code property. + * + * The reducer function iterates the stream element-by-element which means that there is no *concurrency* parameter + * or parallelism. To perform a reduce concurrently, you can extract the async function to `readable.map` method. + * @since v17.5.0 + * @param fn a reducer function to call over every chunk in the stream. Async or not. + * @param initial the initial value to use in the reduction. + * @returns a promise for the final value of the reduction. + */ + reduce( + fn: (previous: any, data: any, options?: Pick) => T, + initial?: undefined, + options?: Pick, + ): Promise; + reduce( + fn: (previous: T, data: any, options?: Pick) => T, + initial: T, + options?: Pick, + ): Promise; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + /** + * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'` event (unless `emitClose` is set to `false`). After this call, the readable + * stream will release any internal resources and subsequent calls to `push()` will be ignored. + * + * Once `destroy()` has been called any further calls will be a no-op and no + * further errors except from `_destroy()` may be emitted as `'error'`. + * + * Implementors should not override this method, but instead implement `readable._destroy()`. + * @since v8.0.0 + * @param error Error which will be passed as payload in `'error'` event + */ + destroy(error?: Error): this; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. data + * 3. end + * 4. error + * 5. pause + * 6. readable + * 7. resume + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: any) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "data", chunk: any): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "pause"): boolean; + emit(event: "readable"): boolean; + emit(event: "resume"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: any) => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: any) => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: any) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: any) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "data", listener: (chunk: any) => void): this; + removeListener(event: "end", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "pause", listener: () => void): this; + removeListener(event: "readable", listener: () => void): this; + removeListener(event: "resume", listener: () => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + /** + * Calls `readable.destroy()` with an `AbortError` and returns a promise that fulfills when the stream is finished. + * @since v20.4.0 + */ + [Symbol.asyncDispose](): Promise; + } + import WritableOptions = internal.WritableOptions; + class WritableBase extends Stream implements NodeJS.WritableStream { + /** + * Is `true` if it is safe to call `writable.write()`, which means + * the stream has not been destroyed, errored, or ended. + * @since v11.4.0 + */ + readonly writable: boolean; + /** + * Is `true` after `writable.end()` has been called. This property + * does not indicate whether the data has been flushed, for this use `writable.writableFinished` instead. + * @since v12.9.0 + */ + readonly writableEnded: boolean; + /** + * Is set to `true` immediately before the `'finish'` event is emitted. + * @since v12.6.0 + */ + readonly writableFinished: boolean; + /** + * Return the value of `highWaterMark` passed when creating this `Writable`. + * @since v9.3.0 + */ + readonly writableHighWaterMark: number; + /** + * This property contains the number of bytes (or objects) in the queue + * ready to be written. The value provides introspection data regarding + * the status of the `highWaterMark`. + * @since v9.4.0 + */ + readonly writableLength: number; + /** + * Getter for the property `objectMode` of a given `Writable` stream. + * @since v12.3.0 + */ + readonly writableObjectMode: boolean; + /** + * Number of times `writable.uncork()` needs to be + * called in order to fully uncork the stream. + * @since v13.2.0, v12.16.0 + */ + readonly writableCorked: number; + /** + * Is `true` after `writable.destroy()` has been called. + * @since v8.0.0 + */ + destroyed: boolean; + /** + * Is `true` after `'close'` has been emitted. + * @since v18.0.0 + */ + readonly closed: boolean; + /** + * Returns error if the stream has been destroyed with an error. + * @since v18.0.0 + */ + readonly errored: Error | null; + /** + * Is `true` if the stream's buffer has been full and stream will emit `'drain'`. + * @since v15.2.0, v14.17.0 + */ + readonly writableNeedDrain: boolean; + constructor(opts?: WritableOptions); + _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + _writev?( + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + _construct?(callback: (error?: Error | null) => void): void; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + /** + * The `writable.write()` method writes some data to the stream, and calls the + * supplied `callback` once the data has been fully handled. If an error + * occurs, the `callback` will be called with the error as its + * first argument. The `callback` is called asynchronously and before `'error'` is + * emitted. + * + * The return value is `true` if the internal buffer is less than the `highWaterMark` configured when the stream was created after admitting `chunk`. + * If `false` is returned, further attempts to write data to the stream should + * stop until the `'drain'` event is emitted. + * + * While a stream is not draining, calls to `write()` will buffer `chunk`, and + * return false. Once all currently buffered chunks are drained (accepted for + * delivery by the operating system), the `'drain'` event will be emitted. + * Once `write()` returns false, do not write more chunks + * until the `'drain'` event is emitted. While calling `write()` on a stream that + * is not draining is allowed, Node.js will buffer all written chunks until + * maximum memory usage occurs, at which point it will abort unconditionally. + * Even before it aborts, high memory usage will cause poor garbage collector + * performance and high RSS (which is not typically released back to the system, + * even after the memory is no longer required). Since TCP sockets may never + * drain if the remote peer does not read the data, writing a socket that is + * not draining may lead to a remotely exploitable vulnerability. + * + * Writing data while the stream is not draining is particularly + * problematic for a `Transform`, because the `Transform` streams are paused + * by default until they are piped or a `'data'` or `'readable'` event handler + * is added. + * + * If the data to be written can be generated or fetched on demand, it is + * recommended to encapsulate the logic into a `Readable` and use {@link pipe}. However, if calling `write()` is preferred, it is + * possible to respect backpressure and avoid memory issues using the `'drain'` event: + * + * ```js + * function write(data, cb) { + * if (!stream.write(data)) { + * stream.once('drain', cb); + * } else { + * process.nextTick(cb); + * } + * } + * + * // Wait for cb to be called before doing any other write. + * write('hello', () => { + * console.log('Write completed, do more writes now.'); + * }); + * ``` + * + * A `Writable` stream in object mode will always ignore the `encoding` argument. + * @since v0.9.4 + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a {string}, {Buffer}, + * {TypedArray} or {DataView}. For object mode streams, `chunk` may be any JavaScript value other than `null`. + * @param [encoding='utf8'] The encoding, if `chunk` is a string. + * @param callback Callback for when this chunk of data is flushed. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + write(chunk: any, callback?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, encoding: BufferEncoding, callback?: (error: Error | null | undefined) => void): boolean; + /** + * The `writable.setDefaultEncoding()` method sets the default `encoding` for a `Writable` stream. + * @since v0.11.15 + * @param encoding The new default encoding + */ + setDefaultEncoding(encoding: BufferEncoding): this; + /** + * Calling the `writable.end()` method signals that no more data will be written + * to the `Writable`. The optional `chunk` and `encoding` arguments allow one + * final additional chunk of data to be written immediately before closing the + * stream. + * + * Calling the {@link write} method after calling {@link end} will raise an error. + * + * ```js + * // Write 'hello, ' and then end with 'world!'. + * const fs = require('node:fs'); + * const file = fs.createWriteStream('example.txt'); + * file.write('hello, '); + * file.end('world!'); + * // Writing more now is not allowed! + * ``` + * @since v0.9.4 + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a {string}, {Buffer}, + * {TypedArray} or {DataView}. For object mode streams, `chunk` may be any JavaScript value other than `null`. + * @param encoding The encoding if `chunk` is a string + * @param callback Callback for when the stream is finished. + */ + end(cb?: () => void): this; + end(chunk: any, cb?: () => void): this; + end(chunk: any, encoding: BufferEncoding, cb?: () => void): this; + /** + * The `writable.cork()` method forces all written data to be buffered in memory. + * The buffered data will be flushed when either the {@link uncork} or {@link end} methods are called. + * + * The primary intent of `writable.cork()` is to accommodate a situation in which + * several small chunks are written to the stream in rapid succession. Instead of + * immediately forwarding them to the underlying destination, `writable.cork()` buffers all the chunks until `writable.uncork()` is called, which will pass them + * all to `writable._writev()`, if present. This prevents a head-of-line blocking + * situation where data is being buffered while waiting for the first small chunk + * to be processed. However, use of `writable.cork()` without implementing `writable._writev()` may have an adverse effect on throughput. + * + * See also: `writable.uncork()`, `writable._writev()`. + * @since v0.11.2 + */ + cork(): void; + /** + * The `writable.uncork()` method flushes all data buffered since {@link cork} was called. + * + * When using `writable.cork()` and `writable.uncork()` to manage the buffering + * of writes to a stream, defer calls to `writable.uncork()` using `process.nextTick()`. Doing so allows batching of all `writable.write()` calls that occur within a given Node.js event + * loop phase. + * + * ```js + * stream.cork(); + * stream.write('some '); + * stream.write('data '); + * process.nextTick(() => stream.uncork()); + * ``` + * + * If the `writable.cork()` method is called multiple times on a stream, the + * same number of calls to `writable.uncork()` must be called to flush the buffered + * data. + * + * ```js + * stream.cork(); + * stream.write('some '); + * stream.cork(); + * stream.write('data '); + * process.nextTick(() => { + * stream.uncork(); + * // The data will not be flushed until uncork() is called a second time. + * stream.uncork(); + * }); + * ``` + * + * See also: `writable.cork()`. + * @since v0.11.2 + */ + uncork(): void; + /** + * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'` event (unless `emitClose` is set to `false`). After this call, the writable + * stream has ended and subsequent calls to `write()` or `end()` will result in + * an `ERR_STREAM_DESTROYED` error. + * This is a destructive and immediate way to destroy a stream. Previous calls to `write()` may not have drained, and may trigger an `ERR_STREAM_DESTROYED` error. + * Use `end()` instead of destroy if data should flush before close, or wait for + * the `'drain'` event before destroying the stream. + * + * Once `destroy()` has been called any further calls will be a no-op and no + * further errors except from `_destroy()` may be emitted as `'error'`. + * + * Implementors should not override this method, + * but instead implement `writable._destroy()`. + * @since v8.0.0 + * @param error Optional, an error to emit with `'error'` event. + */ + destroy(error?: Error): this; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. drain + * 3. error + * 4. finish + * 5. pipe + * 6. unpipe + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: Readable) => void): this; + addListener(event: "unpipe", listener: (src: Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "drain"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pipe", src: Readable): boolean; + emit(event: "unpipe", src: Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: Readable) => void): this; + on(event: "unpipe", listener: (src: Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: Readable) => void): this; + once(event: "unpipe", listener: (src: Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: Readable) => void): this; + prependListener(event: "unpipe", listener: (src: Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "drain", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "finish", listener: () => void): this; + removeListener(event: "pipe", listener: (src: Readable) => void): this; + removeListener(event: "unpipe", listener: (src: Readable) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + namespace internal { + class Stream extends internal { + constructor(opts?: ReadableOptions); + } + interface StreamOptions extends Abortable { + emitClose?: boolean | undefined; + highWaterMark?: number | undefined; + objectMode?: boolean | undefined; + construct?(this: T, callback: (error?: Error | null) => void): void; + destroy?(this: T, error: Error | null, callback: (error?: Error | null) => void): void; + autoDestroy?: boolean | undefined; + } + interface ReadableOptions extends StreamOptions { + encoding?: BufferEncoding | undefined; + read?(this: Readable, size: number): void; + } + /** + * @since v0.9.4 + */ + class Readable extends ReadableBase { + /** + * A utility method for creating a `Readable` from a web `ReadableStream`. + * @since v17.0.0 + * @experimental + */ + static fromWeb( + readableStream: streamWeb.ReadableStream, + options?: Pick, + ): Readable; + /** + * A utility method for creating a web `ReadableStream` from a `Readable`. + * @since v17.0.0 + * @experimental + */ + static toWeb(streamReadable: Readable): streamWeb.ReadableStream; + } + interface WritableOptions extends StreamOptions { + decodeStrings?: boolean | undefined; + defaultEncoding?: BufferEncoding | undefined; + write?( + this: Writable, + chunk: any, + encoding: BufferEncoding, + callback: (error?: Error | null) => void, + ): void; + writev?( + this: Writable, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + final?(this: Writable, callback: (error?: Error | null) => void): void; + } + /** + * @since v0.9.4 + */ + class Writable extends WritableBase { + /** + * A utility method for creating a `Writable` from a web `WritableStream`. + * @since v17.0.0 + * @experimental + */ + static fromWeb( + writableStream: streamWeb.WritableStream, + options?: Pick, + ): Writable; + /** + * A utility method for creating a web `WritableStream` from a `Writable`. + * @since v17.0.0 + * @experimental + */ + static toWeb(streamWritable: Writable): streamWeb.WritableStream; + } + interface DuplexOptions extends ReadableOptions, WritableOptions { + allowHalfOpen?: boolean | undefined; + readableObjectMode?: boolean | undefined; + writableObjectMode?: boolean | undefined; + readableHighWaterMark?: number | undefined; + writableHighWaterMark?: number | undefined; + writableCorked?: number | undefined; + construct?(this: Duplex, callback: (error?: Error | null) => void): void; + read?(this: Duplex, size: number): void; + write?(this: Duplex, chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + writev?( + this: Duplex, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + final?(this: Duplex, callback: (error?: Error | null) => void): void; + destroy?(this: Duplex, error: Error | null, callback: (error?: Error | null) => void): void; + } + /** + * Duplex streams are streams that implement both the `Readable` and `Writable` interfaces. + * + * Examples of `Duplex` streams include: + * + * * `TCP sockets` + * * `zlib streams` + * * `crypto streams` + * @since v0.9.4 + */ + class Duplex extends ReadableBase implements WritableBase { + readonly writable: boolean; + readonly writableEnded: boolean; + readonly writableFinished: boolean; + readonly writableHighWaterMark: number; + readonly writableLength: number; + readonly writableObjectMode: boolean; + readonly writableCorked: number; + readonly writableNeedDrain: boolean; + readonly closed: boolean; + readonly errored: Error | null; + /** + * If `false` then the stream will automatically end the writable side when the + * readable side ends. Set initially by the `allowHalfOpen` constructor option, + * which defaults to `true`. + * + * This can be changed manually to change the half-open behavior of an existing + * `Duplex` stream instance, but must be changed before the `'end'` event is emitted. + * @since v0.9.4 + */ + allowHalfOpen: boolean; + constructor(opts?: DuplexOptions); + /** + * A utility method for creating duplex streams. + * + * - `Stream` converts writable stream into writable `Duplex` and readable stream + * to `Duplex`. + * - `Blob` converts into readable `Duplex`. + * - `string` converts into readable `Duplex`. + * - `ArrayBuffer` converts into readable `Duplex`. + * - `AsyncIterable` converts into a readable `Duplex`. Cannot yield `null`. + * - `AsyncGeneratorFunction` converts into a readable/writable transform + * `Duplex`. Must take a source `AsyncIterable` as first parameter. Cannot yield + * `null`. + * - `AsyncFunction` converts into a writable `Duplex`. Must return + * either `null` or `undefined` + * - `Object ({ writable, readable })` converts `readable` and + * `writable` into `Stream` and then combines them into `Duplex` where the + * `Duplex` will write to the `writable` and read from the `readable`. + * - `Promise` converts into readable `Duplex`. Value `null` is ignored. + * + * @since v16.8.0 + */ + static from( + src: + | Stream + | NodeBlob + | ArrayBuffer + | string + | Iterable + | AsyncIterable + | AsyncGeneratorFunction + | Promise + | Object, + ): Duplex; + _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + _writev?( + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + write(chunk: any, encoding?: BufferEncoding, cb?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, cb?: (error: Error | null | undefined) => void): boolean; + setDefaultEncoding(encoding: BufferEncoding): this; + end(cb?: () => void): this; + end(chunk: any, cb?: () => void): this; + end(chunk: any, encoding?: BufferEncoding, cb?: () => void): this; + cork(): void; + uncork(): void; + /** + * A utility method for creating a web `ReadableStream` and `WritableStream` from a `Duplex`. + * @since v17.0.0 + * @experimental + */ + static toWeb(streamDuplex: Duplex): { + readable: streamWeb.ReadableStream; + writable: streamWeb.WritableStream; + }; + /** + * A utility method for creating a `Duplex` from a web `ReadableStream` and `WritableStream`. + * @since v17.0.0 + * @experimental + */ + static fromWeb( + duplexStream: { + readable: streamWeb.ReadableStream; + writable: streamWeb.WritableStream; + }, + options?: Pick< + DuplexOptions, + "allowHalfOpen" | "decodeStrings" | "encoding" | "highWaterMark" | "objectMode" | "signal" + >, + ): Duplex; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. data + * 3. drain + * 4. end + * 5. error + * 6. finish + * 7. pause + * 8. pipe + * 9. readable + * 10. resume + * 11. unpipe + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: any) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "pipe", listener: (src: Readable) => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "unpipe", listener: (src: Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "data", chunk: any): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pause"): boolean; + emit(event: "pipe", src: Readable): boolean; + emit(event: "readable"): boolean; + emit(event: "resume"): boolean; + emit(event: "unpipe", src: Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: any) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pause", listener: () => void): this; + on(event: "pipe", listener: (src: Readable) => void): this; + on(event: "readable", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "unpipe", listener: (src: Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: any) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pause", listener: () => void): this; + once(event: "pipe", listener: (src: Readable) => void): this; + once(event: "readable", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "unpipe", listener: (src: Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: any) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "pipe", listener: (src: Readable) => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "unpipe", listener: (src: Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: any) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "data", listener: (chunk: any) => void): this; + removeListener(event: "drain", listener: () => void): this; + removeListener(event: "end", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "finish", listener: () => void): this; + removeListener(event: "pause", listener: () => void): this; + removeListener(event: "pipe", listener: (src: Readable) => void): this; + removeListener(event: "readable", listener: () => void): this; + removeListener(event: "resume", listener: () => void): this; + removeListener(event: "unpipe", listener: (src: Readable) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + type TransformCallback = (error?: Error | null, data?: any) => void; + interface TransformOptions extends DuplexOptions { + construct?(this: Transform, callback: (error?: Error | null) => void): void; + read?(this: Transform, size: number): void; + write?( + this: Transform, + chunk: any, + encoding: BufferEncoding, + callback: (error?: Error | null) => void, + ): void; + writev?( + this: Transform, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + final?(this: Transform, callback: (error?: Error | null) => void): void; + destroy?(this: Transform, error: Error | null, callback: (error?: Error | null) => void): void; + transform?(this: Transform, chunk: any, encoding: BufferEncoding, callback: TransformCallback): void; + flush?(this: Transform, callback: TransformCallback): void; + } + /** + * Transform streams are `Duplex` streams where the output is in some way + * related to the input. Like all `Duplex` streams, `Transform` streams + * implement both the `Readable` and `Writable` interfaces. + * + * Examples of `Transform` streams include: + * + * * `zlib streams` + * * `crypto streams` + * @since v0.9.4 + */ + class Transform extends Duplex { + constructor(opts?: TransformOptions); + _transform(chunk: any, encoding: BufferEncoding, callback: TransformCallback): void; + _flush(callback: TransformCallback): void; + } + /** + * The `stream.PassThrough` class is a trivial implementation of a `Transform` stream that simply passes the input bytes across to the output. Its purpose is + * primarily for examples and testing, but there are some use cases where `stream.PassThrough` is useful as a building block for novel sorts of streams. + */ + class PassThrough extends Transform {} + /** + * A stream to attach a signal to. + * + * Attaches an AbortSignal to a readable or writeable stream. This lets code + * control stream destruction using an `AbortController`. + * + * Calling `abort` on the `AbortController` corresponding to the passed `AbortSignal` will behave the same way as calling `.destroy(new AbortError())` on the + * stream, and `controller.error(new AbortError())` for webstreams. + * + * ```js + * const fs = require('node:fs'); + * + * const controller = new AbortController(); + * const read = addAbortSignal( + * controller.signal, + * fs.createReadStream(('object.json')), + * ); + * // Later, abort the operation closing the stream + * controller.abort(); + * ``` + * + * Or using an `AbortSignal` with a readable stream as an async iterable: + * + * ```js + * const controller = new AbortController(); + * setTimeout(() => controller.abort(), 10_000); // set a timeout + * const stream = addAbortSignal( + * controller.signal, + * fs.createReadStream(('object.json')), + * ); + * (async () => { + * try { + * for await (const chunk of stream) { + * await process(chunk); + * } + * } catch (e) { + * if (e.name === 'AbortError') { + * // The operation was cancelled + * } else { + * throw e; + * } + * } + * })(); + * ``` + * + * Or using an `AbortSignal` with a ReadableStream: + * + * ```js + * const controller = new AbortController(); + * const rs = new ReadableStream({ + * start(controller) { + * controller.enqueue('hello'); + * controller.enqueue('world'); + * controller.close(); + * }, + * }); + * + * addAbortSignal(controller.signal, rs); + * + * finished(rs, (err) => { + * if (err) { + * if (err.name === 'AbortError') { + * // The operation was cancelled + * } + * } + * }); + * + * const reader = rs.getReader(); + * + * reader.read().then(({ value, done }) => { + * console.log(value); // hello + * console.log(done); // false + * controller.abort(); + * }); + * ``` + * @since v15.4.0 + * @param signal A signal representing possible cancellation + * @param stream A stream to attach a signal to. + */ + function addAbortSignal(signal: AbortSignal, stream: T): T; + /** + * Returns the default highWaterMark used by streams. + * Defaults to `65536` (64 KiB), or `16` for `objectMode`. + * @since v19.9.0 + */ + function getDefaultHighWaterMark(objectMode: boolean): number; + /** + * Sets the default highWaterMark used by streams. + * @since v19.9.0 + * @param value highWaterMark value + */ + function setDefaultHighWaterMark(objectMode: boolean, value: number): void; + interface FinishedOptions extends Abortable { + error?: boolean | undefined; + readable?: boolean | undefined; + writable?: boolean | undefined; + } + /** + * A readable and/or writable stream/webstream. + * + * A function to get notified when a stream is no longer readable, writable + * or has experienced an error or a premature close event. + * + * ```js + * const { finished } = require('node:stream'); + * const fs = require('node:fs'); + * + * const rs = fs.createReadStream('archive.tar'); + * + * finished(rs, (err) => { + * if (err) { + * console.error('Stream failed.', err); + * } else { + * console.log('Stream is done reading.'); + * } + * }); + * + * rs.resume(); // Drain the stream. + * ``` + * + * Especially useful in error handling scenarios where a stream is destroyed + * prematurely (like an aborted HTTP request), and will not emit `'end'` or `'finish'`. + * + * The `finished` API provides [`promise version`](https://nodejs.org/docs/latest-v22.x/api/stream.html#streamfinishedstream-options). + * + * `stream.finished()` leaves dangling event listeners (in particular `'error'`, `'end'`, `'finish'` and `'close'`) after `callback` has been + * invoked. The reason for this is so that unexpected `'error'` events (due to + * incorrect stream implementations) do not cause unexpected crashes. + * If this is unwanted behavior then the returned cleanup function needs to be + * invoked in the callback: + * + * ```js + * const cleanup = finished(rs, (err) => { + * cleanup(); + * // ... + * }); + * ``` + * @since v10.0.0 + * @param stream A readable and/or writable stream. + * @param callback A callback function that takes an optional error argument. + * @returns A cleanup function which removes all registered listeners. + */ + function finished( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, + options: FinishedOptions, + callback: (err?: NodeJS.ErrnoException | null) => void, + ): () => void; + function finished( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, + callback: (err?: NodeJS.ErrnoException | null) => void, + ): () => void; + namespace finished { + function __promisify__( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, + options?: FinishedOptions, + ): Promise; + } + type PipelineSourceFunction = () => Iterable | AsyncIterable; + type PipelineSource = Iterable | AsyncIterable | NodeJS.ReadableStream | PipelineSourceFunction; + type PipelineTransform, U> = + | NodeJS.ReadWriteStream + | (( + source: S extends (...args: any[]) => Iterable | AsyncIterable ? AsyncIterable + : S, + ) => AsyncIterable); + type PipelineTransformSource = PipelineSource | PipelineTransform; + type PipelineDestinationIterableFunction = (source: AsyncIterable) => AsyncIterable; + type PipelineDestinationPromiseFunction = (source: AsyncIterable) => Promise

; + type PipelineDestination, P> = S extends + PipelineTransformSource ? + | NodeJS.WritableStream + | PipelineDestinationIterableFunction + | PipelineDestinationPromiseFunction + : never; + type PipelineCallback> = S extends + PipelineDestinationPromiseFunction ? (err: NodeJS.ErrnoException | null, value: P) => void + : (err: NodeJS.ErrnoException | null) => void; + type PipelinePromise> = S extends + PipelineDestinationPromiseFunction ? Promise

: Promise; + interface PipelineOptions { + signal?: AbortSignal | undefined; + end?: boolean | undefined; + } + /** + * A module method to pipe between streams and generators forwarding errors and + * properly cleaning up and provide a callback when the pipeline is complete. + * + * ```js + * const { pipeline } = require('node:stream'); + * const fs = require('node:fs'); + * const zlib = require('node:zlib'); + * + * // Use the pipeline API to easily pipe a series of streams + * // together and get notified when the pipeline is fully done. + * + * // A pipeline to gzip a potentially huge tar file efficiently: + * + * pipeline( + * fs.createReadStream('archive.tar'), + * zlib.createGzip(), + * fs.createWriteStream('archive.tar.gz'), + * (err) => { + * if (err) { + * console.error('Pipeline failed.', err); + * } else { + * console.log('Pipeline succeeded.'); + * } + * }, + * ); + * ``` + * + * The `pipeline` API provides a [`promise version`](https://nodejs.org/docs/latest-v22.x/api/stream.html#streampipelinesource-transforms-destination-options). + * + * `stream.pipeline()` will call `stream.destroy(err)` on all streams except: + * + * * `Readable` streams which have emitted `'end'` or `'close'`. + * * `Writable` streams which have emitted `'finish'` or `'close'`. + * + * `stream.pipeline()` leaves dangling event listeners on the streams + * after the `callback` has been invoked. In the case of reuse of streams after + * failure, this can cause event listener leaks and swallowed errors. If the last + * stream is readable, dangling event listeners will be removed so that the last + * stream can be consumed later. + * + * `stream.pipeline()` closes all the streams when an error is raised. + * The `IncomingRequest` usage with `pipeline` could lead to an unexpected behavior + * once it would destroy the socket without sending the expected response. + * See the example below: + * + * ```js + * const fs = require('node:fs'); + * const http = require('node:http'); + * const { pipeline } = require('node:stream'); + * + * const server = http.createServer((req, res) => { + * const fileStream = fs.createReadStream('./fileNotExist.txt'); + * pipeline(fileStream, res, (err) => { + * if (err) { + * console.log(err); // No such file + * // this message can't be sent once `pipeline` already destroyed the socket + * return res.end('error!!!'); + * } + * }); + * }); + * ``` + * @since v10.0.0 + * @param callback Called when the pipeline is fully done. + */ + function pipeline, B extends PipelineDestination>( + source: A, + destination: B, + callback: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + destination: B, + callback: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + destination: B, + callback: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + destination: B, + callback: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + transform4: T4, + destination: B, + callback: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline( + streams: ReadonlyArray, + callback: (err: NodeJS.ErrnoException | null) => void, + ): NodeJS.WritableStream; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array< + NodeJS.ReadWriteStream | NodeJS.WritableStream | ((err: NodeJS.ErrnoException | null) => void) + > + ): NodeJS.WritableStream; + namespace pipeline { + function __promisify__, B extends PipelineDestination>( + source: A, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + transform4: T4, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__( + streams: ReadonlyArray, + options?: PipelineOptions, + ): Promise; + function __promisify__( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array + ): Promise; + } + interface Pipe { + close(): void; + hasRef(): boolean; + ref(): void; + unref(): void; + } + /** + * Returns whether the stream has encountered an error. + * @since v17.3.0, v16.14.0 + * @experimental + */ + function isErrored(stream: Readable | Writable | NodeJS.ReadableStream | NodeJS.WritableStream): boolean; + /** + * Returns whether the stream is readable. + * @since v17.4.0, v16.14.0 + * @experimental + */ + function isReadable(stream: Readable | NodeJS.ReadableStream): boolean; + const promises: typeof streamPromises; + const consumers: typeof streamConsumers; + } + export = internal; +} +declare module "node:stream" { + import stream = require("stream"); + export = stream; +} diff --git a/libcore/node_modules/@types/node/stream/consumers.d.ts b/libcore/node_modules/@types/node/stream/consumers.d.ts new file mode 100644 index 0000000..5ad9cba --- /dev/null +++ b/libcore/node_modules/@types/node/stream/consumers.d.ts @@ -0,0 +1,12 @@ +declare module "stream/consumers" { + import { Blob as NodeBlob } from "node:buffer"; + import { Readable } from "node:stream"; + function buffer(stream: NodeJS.ReadableStream | Readable | AsyncIterable): Promise; + function text(stream: NodeJS.ReadableStream | Readable | AsyncIterable): Promise; + function arrayBuffer(stream: NodeJS.ReadableStream | Readable | AsyncIterable): Promise; + function blob(stream: NodeJS.ReadableStream | Readable | AsyncIterable): Promise; + function json(stream: NodeJS.ReadableStream | Readable | AsyncIterable): Promise; +} +declare module "node:stream/consumers" { + export * from "stream/consumers"; +} diff --git a/libcore/node_modules/@types/node/stream/promises.d.ts b/libcore/node_modules/@types/node/stream/promises.d.ts new file mode 100644 index 0000000..6eac5b7 --- /dev/null +++ b/libcore/node_modules/@types/node/stream/promises.d.ts @@ -0,0 +1,83 @@ +declare module "stream/promises" { + import { + FinishedOptions, + PipelineDestination, + PipelineOptions, + PipelinePromise, + PipelineSource, + PipelineTransform, + } from "node:stream"; + function finished( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, + options?: FinishedOptions, + ): Promise; + function pipeline, B extends PipelineDestination>( + source: A, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + transform4: T4, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline( + streams: ReadonlyArray, + options?: PipelineOptions, + ): Promise; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array + ): Promise; +} +declare module "node:stream/promises" { + export * from "stream/promises"; +} diff --git a/libcore/node_modules/@types/node/stream/web.d.ts b/libcore/node_modules/@types/node/stream/web.d.ts new file mode 100644 index 0000000..35e2a31 --- /dev/null +++ b/libcore/node_modules/@types/node/stream/web.d.ts @@ -0,0 +1,606 @@ +type _ByteLengthQueuingStrategy = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ByteLengthQueuingStrategy; +type _CompressionStream = typeof globalThis extends { onmessage: any; ReportingObserver: any } ? {} + : import("stream/web").CompressionStream; +type _CountQueuingStrategy = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").CountQueuingStrategy; +type _DecompressionStream = typeof globalThis extends { onmessage: any; ReportingObserver: any } ? {} + : import("stream/web").DecompressionStream; +type _ReadableByteStreamController = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableByteStreamController; +type _ReadableStream = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableStream; +type _ReadableStreamBYOBReader = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableStreamBYOBReader; +type _ReadableStreamBYOBRequest = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableStreamBYOBRequest; +type _ReadableStreamDefaultController = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableStreamDefaultController; +type _ReadableStreamDefaultReader = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableStreamDefaultReader; +type _TextDecoderStream = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").TextDecoderStream; +type _TextEncoderStream = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").TextEncoderStream; +type _TransformStream = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").TransformStream; +type _TransformStreamDefaultController = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").TransformStreamDefaultController; +type _WritableStream = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").WritableStream; +type _WritableStreamDefaultController = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").WritableStreamDefaultController; +type _WritableStreamDefaultWriter = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").WritableStreamDefaultWriter; + +declare module "stream/web" { + // stub module, pending copy&paste from .d.ts or manual impl + // copy from lib.dom.d.ts + interface ReadableWritablePair { + readable: ReadableStream; + /** + * Provides a convenient, chainable way of piping this readable stream + * through a transform stream (or any other { writable, readable } + * pair). It simply pipes the stream into the writable side of the + * supplied pair, and returns the readable side for further use. + * + * Piping a stream will lock it for the duration of the pipe, preventing + * any other consumer from acquiring a reader. + */ + writable: WritableStream; + } + interface StreamPipeOptions { + preventAbort?: boolean; + preventCancel?: boolean; + /** + * Pipes this readable stream to a given writable stream destination. + * The way in which the piping process behaves under various error + * conditions can be customized with a number of passed options. It + * returns a promise that fulfills when the piping process completes + * successfully, or rejects if any errors were encountered. + * + * Piping a stream will lock it for the duration of the pipe, preventing + * any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate + * as follows: + * + * An error in this source readable stream will abort destination, + * unless preventAbort is truthy. The returned promise will be rejected + * with the source's error, or with any error that occurs during + * aborting the destination. + * + * An error in destination will cancel this source readable stream, + * unless preventCancel is truthy. The returned promise will be rejected + * with the destination's error, or with any error that occurs during + * canceling the source. + * + * When this source readable stream closes, destination will be closed, + * unless preventClose is truthy. The returned promise will be fulfilled + * once this process completes, unless an error is encountered while + * closing the destination, in which case it will be rejected with that + * error. + * + * If destination starts out closed or closing, this source readable + * stream will be canceled, unless preventCancel is true. The returned + * promise will be rejected with an error indicating piping to a closed + * stream failed, or with any error that occurs during canceling the + * source. + * + * The signal option can be set to an AbortSignal to allow aborting an + * ongoing pipe operation via the corresponding AbortController. In this + * case, this source readable stream will be canceled, and destination + * aborted, unless the respective options preventCancel or preventAbort + * are set. + */ + preventClose?: boolean; + signal?: AbortSignal; + } + interface ReadableStreamGenericReader { + readonly closed: Promise; + cancel(reason?: any): Promise; + } + type ReadableStreamController = ReadableStreamDefaultController; + interface ReadableStreamReadValueResult { + done: false; + value: T; + } + interface ReadableStreamReadDoneResult { + done: true; + value?: T; + } + type ReadableStreamReadResult = ReadableStreamReadValueResult | ReadableStreamReadDoneResult; + interface ReadableByteStreamControllerCallback { + (controller: ReadableByteStreamController): void | PromiseLike; + } + interface UnderlyingSinkAbortCallback { + (reason?: any): void | PromiseLike; + } + interface UnderlyingSinkCloseCallback { + (): void | PromiseLike; + } + interface UnderlyingSinkStartCallback { + (controller: WritableStreamDefaultController): any; + } + interface UnderlyingSinkWriteCallback { + (chunk: W, controller: WritableStreamDefaultController): void | PromiseLike; + } + interface UnderlyingSourceCancelCallback { + (reason?: any): void | PromiseLike; + } + interface UnderlyingSourcePullCallback { + (controller: ReadableStreamController): void | PromiseLike; + } + interface UnderlyingSourceStartCallback { + (controller: ReadableStreamController): any; + } + interface TransformerFlushCallback { + (controller: TransformStreamDefaultController): void | PromiseLike; + } + interface TransformerStartCallback { + (controller: TransformStreamDefaultController): any; + } + interface TransformerTransformCallback { + (chunk: I, controller: TransformStreamDefaultController): void | PromiseLike; + } + interface UnderlyingByteSource { + autoAllocateChunkSize?: number; + cancel?: ReadableStreamErrorCallback; + pull?: ReadableByteStreamControllerCallback; + start?: ReadableByteStreamControllerCallback; + type: "bytes"; + } + interface UnderlyingSource { + cancel?: UnderlyingSourceCancelCallback; + pull?: UnderlyingSourcePullCallback; + start?: UnderlyingSourceStartCallback; + type?: undefined; + } + interface UnderlyingSink { + abort?: UnderlyingSinkAbortCallback; + close?: UnderlyingSinkCloseCallback; + start?: UnderlyingSinkStartCallback; + type?: undefined; + write?: UnderlyingSinkWriteCallback; + } + interface ReadableStreamErrorCallback { + (reason: any): void | PromiseLike; + } + /** This Streams API interface represents a readable stream of byte data. */ + interface ReadableStream { + readonly locked: boolean; + cancel(reason?: any): Promise; + getReader(options: { mode: "byob" }): ReadableStreamBYOBReader; + getReader(): ReadableStreamDefaultReader; + getReader(options?: ReadableStreamGetReaderOptions): ReadableStreamReader; + pipeThrough(transform: ReadableWritablePair, options?: StreamPipeOptions): ReadableStream; + pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; + tee(): [ReadableStream, ReadableStream]; + values(options?: { preventCancel?: boolean }): AsyncIterableIterator; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + const ReadableStream: { + prototype: ReadableStream; + from(iterable: Iterable | AsyncIterable): ReadableStream; + new(underlyingSource: UnderlyingByteSource, strategy?: QueuingStrategy): ReadableStream; + new(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; + }; + type ReadableStreamReaderMode = "byob"; + interface ReadableStreamGetReaderOptions { + /** + * Creates a ReadableStreamBYOBReader and locks the stream to the new reader. + * + * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams, i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading. The returned BYOB reader provides the ability to directly read individual chunks from the stream via its read() method, into developer-supplied buffers, allowing more precise control over allocation. + */ + mode?: ReadableStreamReaderMode; + } + type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader; + interface ReadableStreamDefaultReader extends ReadableStreamGenericReader { + read(): Promise>; + releaseLock(): void; + } + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader) */ + interface ReadableStreamBYOBReader extends ReadableStreamGenericReader { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) */ + read(view: T): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) */ + releaseLock(): void; + } + const ReadableStreamDefaultReader: { + prototype: ReadableStreamDefaultReader; + new(stream: ReadableStream): ReadableStreamDefaultReader; + }; + const ReadableStreamBYOBReader: { + prototype: ReadableStreamBYOBReader; + new(stream: ReadableStream): ReadableStreamBYOBReader; + }; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) */ + interface ReadableStreamBYOBRequest { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) */ + readonly view: ArrayBufferView | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) */ + respond(bytesWritten: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) */ + respondWithNewView(view: ArrayBufferView): void; + } + const ReadableStreamBYOBRequest: { + prototype: ReadableStreamBYOBRequest; + new(): ReadableStreamBYOBRequest; + }; + interface ReadableByteStreamController { + readonly byobRequest: undefined; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: ArrayBufferView): void; + error(error?: any): void; + } + const ReadableByteStreamController: { + prototype: ReadableByteStreamController; + new(): ReadableByteStreamController; + }; + interface ReadableStreamDefaultController { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk?: R): void; + error(e?: any): void; + } + const ReadableStreamDefaultController: { + prototype: ReadableStreamDefaultController; + new(): ReadableStreamDefaultController; + }; + interface Transformer { + flush?: TransformerFlushCallback; + readableType?: undefined; + start?: TransformerStartCallback; + transform?: TransformerTransformCallback; + writableType?: undefined; + } + interface TransformStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; + } + const TransformStream: { + prototype: TransformStream; + new( + transformer?: Transformer, + writableStrategy?: QueuingStrategy, + readableStrategy?: QueuingStrategy, + ): TransformStream; + }; + interface TransformStreamDefaultController { + readonly desiredSize: number | null; + enqueue(chunk?: O): void; + error(reason?: any): void; + terminate(): void; + } + const TransformStreamDefaultController: { + prototype: TransformStreamDefaultController; + new(): TransformStreamDefaultController; + }; + /** + * This Streams API interface provides a standard abstraction for writing + * streaming data to a destination, known as a sink. This object comes with + * built-in back pressure and queuing. + */ + interface WritableStream { + readonly locked: boolean; + abort(reason?: any): Promise; + close(): Promise; + getWriter(): WritableStreamDefaultWriter; + } + const WritableStream: { + prototype: WritableStream; + new(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy): WritableStream; + }; + /** + * This Streams API interface is the object returned by + * WritableStream.getWriter() and once created locks the < writer to the + * WritableStream ensuring that no other streams can write to the underlying + * sink. + */ + interface WritableStreamDefaultWriter { + readonly closed: Promise; + readonly desiredSize: number | null; + readonly ready: Promise; + abort(reason?: any): Promise; + close(): Promise; + releaseLock(): void; + write(chunk?: W): Promise; + } + const WritableStreamDefaultWriter: { + prototype: WritableStreamDefaultWriter; + new(stream: WritableStream): WritableStreamDefaultWriter; + }; + /** + * This Streams API interface represents a controller allowing control of a + * WritableStream's state. When constructing a WritableStream, the + * underlying sink is given a corresponding WritableStreamDefaultController + * instance to manipulate. + */ + interface WritableStreamDefaultController { + error(e?: any): void; + } + const WritableStreamDefaultController: { + prototype: WritableStreamDefaultController; + new(): WritableStreamDefaultController; + }; + interface QueuingStrategy { + highWaterMark?: number; + size?: QueuingStrategySize; + } + interface QueuingStrategySize { + (chunk?: T): number; + } + interface QueuingStrategyInit { + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water + * mark. + * + * Note that the provided high water mark will not be validated ahead of + * time. Instead, if it is negative, NaN, or not a number, the resulting + * ByteLengthQueuingStrategy will cause the corresponding stream + * constructor to throw. + */ + highWaterMark: number; + } + /** + * This Streams API interface provides a built-in byte length queuing + * strategy that can be used when constructing streams. + */ + interface ByteLengthQueuingStrategy extends QueuingStrategy { + readonly highWaterMark: number; + readonly size: QueuingStrategySize; + } + const ByteLengthQueuingStrategy: { + prototype: ByteLengthQueuingStrategy; + new(init: QueuingStrategyInit): ByteLengthQueuingStrategy; + }; + /** + * This Streams API interface provides a built-in byte length queuing + * strategy that can be used when constructing streams. + */ + interface CountQueuingStrategy extends QueuingStrategy { + readonly highWaterMark: number; + readonly size: QueuingStrategySize; + } + const CountQueuingStrategy: { + prototype: CountQueuingStrategy; + new(init: QueuingStrategyInit): CountQueuingStrategy; + }; + interface TextEncoderStream { + /** Returns "utf-8". */ + readonly encoding: "utf-8"; + readonly readable: ReadableStream; + readonly writable: WritableStream; + readonly [Symbol.toStringTag]: string; + } + const TextEncoderStream: { + prototype: TextEncoderStream; + new(): TextEncoderStream; + }; + interface TextDecoderOptions { + fatal?: boolean; + ignoreBOM?: boolean; + } + type BufferSource = ArrayBufferView | ArrayBuffer; + interface TextDecoderStream { + /** Returns encoding's name, lower cased. */ + readonly encoding: string; + /** Returns `true` if error mode is "fatal", and `false` otherwise. */ + readonly fatal: boolean; + /** Returns `true` if ignore BOM flag is set, and `false` otherwise. */ + readonly ignoreBOM: boolean; + readonly readable: ReadableStream; + readonly writable: WritableStream; + readonly [Symbol.toStringTag]: string; + } + const TextDecoderStream: { + prototype: TextDecoderStream; + new(encoding?: string, options?: TextDecoderOptions): TextDecoderStream; + }; + interface CompressionStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; + } + const CompressionStream: { + prototype: CompressionStream; + new(format: "deflate" | "deflate-raw" | "gzip"): CompressionStream; + }; + interface DecompressionStream { + readonly writable: WritableStream; + readonly readable: ReadableStream; + } + const DecompressionStream: { + prototype: DecompressionStream; + new(format: "deflate" | "deflate-raw" | "gzip"): DecompressionStream; + }; + + global { + interface ByteLengthQueuingStrategy extends _ByteLengthQueuingStrategy {} + /** + * `ByteLengthQueuingStrategy` class is a global reference for `require('stream/web').ByteLengthQueuingStrategy`. + * https://nodejs.org/api/globals.html#class-bytelengthqueuingstrategy + * @since v18.0.0 + */ + var ByteLengthQueuingStrategy: typeof globalThis extends { onmessage: any; ByteLengthQueuingStrategy: infer T } + ? T + : typeof import("stream/web").ByteLengthQueuingStrategy; + + interface CompressionStream extends _CompressionStream {} + /** + * `CompressionStream` class is a global reference for `require('stream/web').CompressionStream`. + * https://nodejs.org/api/globals.html#class-compressionstream + * @since v18.0.0 + */ + var CompressionStream: typeof globalThis extends { + onmessage: any; + // CompressionStream, DecompressionStream and ReportingObserver was introduced in the same commit. + // If ReportingObserver check is removed, the type here will form a circular reference in TS5.0+lib.dom.d.ts + ReportingObserver: any; + CompressionStream: infer T; + } ? T + // TS 4.8, 4.9, 5.0 + : typeof globalThis extends { onmessage: any; TransformStream: { prototype: infer T } } ? { + prototype: T; + new(format: "deflate" | "deflate-raw" | "gzip"): T; + } + : typeof import("stream/web").CompressionStream; + + interface CountQueuingStrategy extends _CountQueuingStrategy {} + /** + * `CountQueuingStrategy` class is a global reference for `require('stream/web').CountQueuingStrategy`. + * https://nodejs.org/api/globals.html#class-countqueuingstrategy + * @since v18.0.0 + */ + var CountQueuingStrategy: typeof globalThis extends { onmessage: any; CountQueuingStrategy: infer T } ? T + : typeof import("stream/web").CountQueuingStrategy; + + interface DecompressionStream extends _DecompressionStream {} + /** + * `DecompressionStream` class is a global reference for `require('stream/web').DecompressionStream`. + * https://nodejs.org/api/globals.html#class-decompressionstream + * @since v18.0.0 + */ + var DecompressionStream: typeof globalThis extends { + onmessage: any; + // CompressionStream, DecompressionStream and ReportingObserver was introduced in the same commit. + // If ReportingObserver check is removed, the type here will form a circular reference in TS5.0+lib.dom.d.ts + ReportingObserver: any; + DecompressionStream: infer T extends object; + } ? T + // TS 4.8, 4.9, 5.0 + : typeof globalThis extends { onmessage: any; TransformStream: { prototype: infer T } } ? { + prototype: T; + new(format: "deflate" | "deflate-raw" | "gzip"): T; + } + : typeof import("stream/web").DecompressionStream; + + interface ReadableByteStreamController extends _ReadableByteStreamController {} + /** + * `ReadableByteStreamController` class is a global reference for `require('stream/web').ReadableByteStreamController`. + * https://nodejs.org/api/globals.html#class-readablebytestreamcontroller + * @since v18.0.0 + */ + var ReadableByteStreamController: typeof globalThis extends + { onmessage: any; ReadableByteStreamController: infer T } ? T + : typeof import("stream/web").ReadableByteStreamController; + + interface ReadableStream extends _ReadableStream {} + /** + * `ReadableStream` class is a global reference for `require('stream/web').ReadableStream`. + * https://nodejs.org/api/globals.html#class-readablestream + * @since v18.0.0 + */ + var ReadableStream: typeof globalThis extends { onmessage: any; ReadableStream: infer T } ? T + : typeof import("stream/web").ReadableStream; + + interface ReadableStreamBYOBReader extends _ReadableStreamBYOBReader {} + /** + * `ReadableStreamBYOBReader` class is a global reference for `require('stream/web').ReadableStreamBYOBReader`. + * https://nodejs.org/api/globals.html#class-readablestreambyobreader + * @since v18.0.0 + */ + var ReadableStreamBYOBReader: typeof globalThis extends { onmessage: any; ReadableStreamBYOBReader: infer T } + ? T + : typeof import("stream/web").ReadableStreamBYOBReader; + + interface ReadableStreamBYOBRequest extends _ReadableStreamBYOBRequest {} + /** + * `ReadableStreamBYOBRequest` class is a global reference for `require('stream/web').ReadableStreamBYOBRequest`. + * https://nodejs.org/api/globals.html#class-readablestreambyobrequest + * @since v18.0.0 + */ + var ReadableStreamBYOBRequest: typeof globalThis extends { onmessage: any; ReadableStreamBYOBRequest: infer T } + ? T + : typeof import("stream/web").ReadableStreamBYOBRequest; + + interface ReadableStreamDefaultController extends _ReadableStreamDefaultController {} + /** + * `ReadableStreamDefaultController` class is a global reference for `require('stream/web').ReadableStreamDefaultController`. + * https://nodejs.org/api/globals.html#class-readablestreamdefaultcontroller + * @since v18.0.0 + */ + var ReadableStreamDefaultController: typeof globalThis extends + { onmessage: any; ReadableStreamDefaultController: infer T } ? T + : typeof import("stream/web").ReadableStreamDefaultController; + + interface ReadableStreamDefaultReader extends _ReadableStreamDefaultReader {} + /** + * `ReadableStreamDefaultReader` class is a global reference for `require('stream/web').ReadableStreamDefaultReader`. + * https://nodejs.org/api/globals.html#class-readablestreamdefaultreader + * @since v18.0.0 + */ + var ReadableStreamDefaultReader: typeof globalThis extends + { onmessage: any; ReadableStreamDefaultReader: infer T } ? T + : typeof import("stream/web").ReadableStreamDefaultReader; + + interface TextDecoderStream extends _TextDecoderStream {} + /** + * `TextDecoderStream` class is a global reference for `require('stream/web').TextDecoderStream`. + * https://nodejs.org/api/globals.html#class-textdecoderstream + * @since v18.0.0 + */ + var TextDecoderStream: typeof globalThis extends { onmessage: any; TextDecoderStream: infer T } ? T + : typeof import("stream/web").TextDecoderStream; + + interface TextEncoderStream extends _TextEncoderStream {} + /** + * `TextEncoderStream` class is a global reference for `require('stream/web').TextEncoderStream`. + * https://nodejs.org/api/globals.html#class-textencoderstream + * @since v18.0.0 + */ + var TextEncoderStream: typeof globalThis extends { onmessage: any; TextEncoderStream: infer T } ? T + : typeof import("stream/web").TextEncoderStream; + + interface TransformStream extends _TransformStream {} + /** + * `TransformStream` class is a global reference for `require('stream/web').TransformStream`. + * https://nodejs.org/api/globals.html#class-transformstream + * @since v18.0.0 + */ + var TransformStream: typeof globalThis extends { onmessage: any; TransformStream: infer T } ? T + : typeof import("stream/web").TransformStream; + + interface TransformStreamDefaultController extends _TransformStreamDefaultController {} + /** + * `TransformStreamDefaultController` class is a global reference for `require('stream/web').TransformStreamDefaultController`. + * https://nodejs.org/api/globals.html#class-transformstreamdefaultcontroller + * @since v18.0.0 + */ + var TransformStreamDefaultController: typeof globalThis extends + { onmessage: any; TransformStreamDefaultController: infer T } ? T + : typeof import("stream/web").TransformStreamDefaultController; + + interface WritableStream extends _WritableStream {} + /** + * `WritableStream` class is a global reference for `require('stream/web').WritableStream`. + * https://nodejs.org/api/globals.html#class-writablestream + * @since v18.0.0 + */ + var WritableStream: typeof globalThis extends { onmessage: any; WritableStream: infer T } ? T + : typeof import("stream/web").WritableStream; + + interface WritableStreamDefaultController extends _WritableStreamDefaultController {} + /** + * `WritableStreamDefaultController` class is a global reference for `require('stream/web').WritableStreamDefaultController`. + * https://nodejs.org/api/globals.html#class-writablestreamdefaultcontroller + * @since v18.0.0 + */ + var WritableStreamDefaultController: typeof globalThis extends + { onmessage: any; WritableStreamDefaultController: infer T } ? T + : typeof import("stream/web").WritableStreamDefaultController; + + interface WritableStreamDefaultWriter extends _WritableStreamDefaultWriter {} + /** + * `WritableStreamDefaultWriter` class is a global reference for `require('stream/web').WritableStreamDefaultWriter`. + * https://nodejs.org/api/globals.html#class-writablestreamdefaultwriter + * @since v18.0.0 + */ + var WritableStreamDefaultWriter: typeof globalThis extends + { onmessage: any; WritableStreamDefaultWriter: infer T } ? T + : typeof import("stream/web").WritableStreamDefaultWriter; + } +} +declare module "node:stream/web" { + export * from "stream/web"; +} diff --git a/libcore/node_modules/@types/node/string_decoder.d.ts b/libcore/node_modules/@types/node/string_decoder.d.ts new file mode 100644 index 0000000..31f68ac --- /dev/null +++ b/libcore/node_modules/@types/node/string_decoder.d.ts @@ -0,0 +1,67 @@ +/** + * The `node:string_decoder` module provides an API for decoding `Buffer` objects + * into strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16 + * characters. It can be accessed using: + * + * ```js + * const { StringDecoder } = require('node:string_decoder'); + * ``` + * + * The following example shows the basic use of the `StringDecoder` class. + * + * ```js + * const { StringDecoder } = require('node:string_decoder'); + * const decoder = new StringDecoder('utf8'); + * + * const cent = Buffer.from([0xC2, 0xA2]); + * console.log(decoder.write(cent)); // Prints: ¢ + * + * const euro = Buffer.from([0xE2, 0x82, 0xAC]); + * console.log(decoder.write(euro)); // Prints: € + * ``` + * + * When a `Buffer` instance is written to the `StringDecoder` instance, an + * internal buffer is used to ensure that the decoded string does not contain + * any incomplete multibyte characters. These are held in the buffer until the + * next call to `stringDecoder.write()` or until `stringDecoder.end()` is called. + * + * In the following example, the three UTF-8 encoded bytes of the European Euro + * symbol (`€`) are written over three separate operations: + * + * ```js + * const { StringDecoder } = require('node:string_decoder'); + * const decoder = new StringDecoder('utf8'); + * + * decoder.write(Buffer.from([0xE2])); + * decoder.write(Buffer.from([0x82])); + * console.log(decoder.end(Buffer.from([0xAC]))); // Prints: € + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/string_decoder.js) + */ +declare module "string_decoder" { + class StringDecoder { + constructor(encoding?: BufferEncoding); + /** + * Returns a decoded string, ensuring that any incomplete multibyte characters at + * the end of the `Buffer`, or `TypedArray`, or `DataView` are omitted from the + * returned string and stored in an internal buffer for the next call to `stringDecoder.write()` or `stringDecoder.end()`. + * @since v0.1.99 + * @param buffer The bytes to decode. + */ + write(buffer: string | Buffer | NodeJS.ArrayBufferView): string; + /** + * Returns any remaining input stored in the internal buffer as a string. Bytes + * representing incomplete UTF-8 and UTF-16 characters will be replaced with + * substitution characters appropriate for the character encoding. + * + * If the `buffer` argument is provided, one final call to `stringDecoder.write()` is performed before returning the remaining input. + * After `end()` is called, the `stringDecoder` object can be reused for new input. + * @since v0.9.3 + * @param buffer The bytes to decode. + */ + end(buffer?: string | Buffer | NodeJS.ArrayBufferView): string; + } +} +declare module "node:string_decoder" { + export * from "string_decoder"; +} diff --git a/libcore/node_modules/@types/node/test.d.ts b/libcore/node_modules/@types/node/test.d.ts new file mode 100644 index 0000000..91524dc --- /dev/null +++ b/libcore/node_modules/@types/node/test.d.ts @@ -0,0 +1,2015 @@ +/** + * The `node:test` module facilitates the creation of JavaScript tests. + * To access it: + * + * ```js + * import test from 'node:test'; + * ``` + * + * This module is only available under the `node:` scheme. The following will not + * work: + * + * ```js + * import test from 'test'; + * ``` + * + * Tests created via the `test` module consist of a single function that is + * processed in one of three ways: + * + * 1. A synchronous function that is considered failing if it throws an exception, + * and is considered passing otherwise. + * 2. A function that returns a `Promise` that is considered failing if the `Promise` rejects, and is considered passing if the `Promise` fulfills. + * 3. A function that receives a callback function. If the callback receives any + * truthy value as its first argument, the test is considered failing. If a + * falsy value is passed as the first argument to the callback, the test is + * considered passing. If the test function receives a callback function and + * also returns a `Promise`, the test will fail. + * + * The following example illustrates how tests are written using the `test` module. + * + * ```js + * test('synchronous passing test', (t) => { + * // This test passes because it does not throw an exception. + * assert.strictEqual(1, 1); + * }); + * + * test('synchronous failing test', (t) => { + * // This test fails because it throws an exception. + * assert.strictEqual(1, 2); + * }); + * + * test('asynchronous passing test', async (t) => { + * // This test passes because the Promise returned by the async + * // function is settled and not rejected. + * assert.strictEqual(1, 1); + * }); + * + * test('asynchronous failing test', async (t) => { + * // This test fails because the Promise returned by the async + * // function is rejected. + * assert.strictEqual(1, 2); + * }); + * + * test('failing test using Promises', (t) => { + * // Promises can be used directly as well. + * return new Promise((resolve, reject) => { + * setImmediate(() => { + * reject(new Error('this will cause the test to fail')); + * }); + * }); + * }); + * + * test('callback passing test', (t, done) => { + * // done() is the callback function. When the setImmediate() runs, it invokes + * // done() with no arguments. + * setImmediate(done); + * }); + * + * test('callback failing test', (t, done) => { + * // When the setImmediate() runs, done() is invoked with an Error object and + * // the test fails. + * setImmediate(() => { + * done(new Error('callback failure')); + * }); + * }); + * ``` + * + * If any tests fail, the process exit code is set to `1`. + * @since v18.0.0, v16.17.0 + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/test.js) + */ +declare module "node:test" { + import { Readable } from "node:stream"; + /** + * **Note:** `shard` is used to horizontally parallelize test running across + * machines or processes, ideal for large-scale executions across varied + * environments. It's incompatible with `watch` mode, tailored for rapid + * code iteration by automatically rerunning tests on file changes. + * + * ```js + * import { tap } from 'node:test/reporters'; + * import { run } from 'node:test'; + * import process from 'node:process'; + * import path from 'node:path'; + * + * run({ files: [path.resolve('./tests/test.js')] }) + * .compose(tap) + * .pipe(process.stdout); + * ``` + * @since v18.9.0, v16.19.0 + * @param options Configuration options for running tests. + */ + function run(options?: RunOptions): TestsStream; + /** + * The `test()` function is the value imported from the `test` module. Each + * invocation of this function results in reporting the test to the `TestsStream`. + * + * The `TestContext` object passed to the `fn` argument can be used to perform + * actions related to the current test. Examples include skipping the test, adding + * additional diagnostic information, or creating subtests. + * + * `test()` returns a `Promise` that fulfills once the test completes. + * if `test()` is called within a suite, it fulfills immediately. + * The return value can usually be discarded for top level tests. + * However, the return value from subtests should be used to prevent the parent + * test from finishing first and cancelling the subtest + * as shown in the following example. + * + * ```js + * test('top level test', async (t) => { + * // The setTimeout() in the following subtest would cause it to outlive its + * // parent test if 'await' is removed on the next line. Once the parent test + * // completes, it will cancel any outstanding subtests. + * await t.test('longer running subtest', async (t) => { + * return new Promise((resolve, reject) => { + * setTimeout(resolve, 1000); + * }); + * }); + * }); + * ``` + * + * The `timeout` option can be used to fail the test if it takes longer than `timeout` milliseconds to complete. However, it is not a reliable mechanism for + * canceling tests because a running test might block the application thread and + * thus prevent the scheduled cancellation. + * @since v18.0.0, v16.17.0 + * @param name The name of the test, which is displayed when reporting test results. + * Defaults to the `name` property of `fn`, or `''` if `fn` does not have a name. + * @param options Configuration options for the test. + * @param fn The function under test. The first argument to this function is a {@link TestContext} object. + * If the test uses callbacks, the callback function is passed as the second argument. + * @return Fulfilled with `undefined` once the test completes, or immediately if the test runs within a suite. + */ + function test(name?: string, fn?: TestFn): Promise; + function test(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function test(options?: TestOptions, fn?: TestFn): Promise; + function test(fn?: TestFn): Promise; + namespace test { + export { + after, + afterEach, + before, + beforeEach, + describe, + it, + mock, + only, + run, + skip, + snapshot, + suite, + test, + todo, + }; + } + /** + * The `suite()` function is imported from the `node:test` module. + * @param name The name of the suite, which is displayed when reporting test results. + * Defaults to the `name` property of `fn`, or `''` if `fn` does not have a name. + * @param options Configuration options for the suite. This supports the same options as {@link test}. + * @param fn The suite function declaring nested tests and suites. The first argument to this function is a {@link SuiteContext} object. + * @return Immediately fulfilled with `undefined`. + * @since v20.13.0 + */ + function suite(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function suite(name?: string, fn?: SuiteFn): Promise; + function suite(options?: TestOptions, fn?: SuiteFn): Promise; + function suite(fn?: SuiteFn): Promise; + namespace suite { + /** + * Shorthand for skipping a suite. This is the same as calling {@link suite} with `options.skip` set to `true`. + * @since v20.13.0 + */ + function skip(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function skip(name?: string, fn?: SuiteFn): Promise; + function skip(options?: TestOptions, fn?: SuiteFn): Promise; + function skip(fn?: SuiteFn): Promise; + /** + * Shorthand for marking a suite as `TODO`. This is the same as calling {@link suite} with `options.todo` set to `true`. + * @since v20.13.0 + */ + function todo(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function todo(name?: string, fn?: SuiteFn): Promise; + function todo(options?: TestOptions, fn?: SuiteFn): Promise; + function todo(fn?: SuiteFn): Promise; + /** + * Shorthand for marking a suite as `only`. This is the same as calling {@link suite} with `options.only` set to `true`. + * @since v20.13.0 + */ + function only(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function only(name?: string, fn?: SuiteFn): Promise; + function only(options?: TestOptions, fn?: SuiteFn): Promise; + function only(fn?: SuiteFn): Promise; + } + /** + * Alias for {@link suite}. + * + * The `describe()` function is imported from the `node:test` module. + */ + function describe(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function describe(name?: string, fn?: SuiteFn): Promise; + function describe(options?: TestOptions, fn?: SuiteFn): Promise; + function describe(fn?: SuiteFn): Promise; + namespace describe { + /** + * Shorthand for skipping a suite. This is the same as calling {@link describe} with `options.skip` set to `true`. + * @since v18.15.0 + */ + function skip(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function skip(name?: string, fn?: SuiteFn): Promise; + function skip(options?: TestOptions, fn?: SuiteFn): Promise; + function skip(fn?: SuiteFn): Promise; + /** + * Shorthand for marking a suite as `TODO`. This is the same as calling {@link describe} with `options.todo` set to `true`. + * @since v18.15.0 + */ + function todo(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function todo(name?: string, fn?: SuiteFn): Promise; + function todo(options?: TestOptions, fn?: SuiteFn): Promise; + function todo(fn?: SuiteFn): Promise; + /** + * Shorthand for marking a suite as `only`. This is the same as calling {@link describe} with `options.only` set to `true`. + * @since v18.15.0 + */ + function only(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function only(name?: string, fn?: SuiteFn): Promise; + function only(options?: TestOptions, fn?: SuiteFn): Promise; + function only(fn?: SuiteFn): Promise; + } + /** + * Alias for {@link test}. + * + * The `it()` function is imported from the `node:test` module. + * @since v18.6.0, v16.17.0 + */ + function it(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function it(name?: string, fn?: TestFn): Promise; + function it(options?: TestOptions, fn?: TestFn): Promise; + function it(fn?: TestFn): Promise; + namespace it { + /** + * Shorthand for skipping a test. This is the same as calling {@link it} with `options.skip` set to `true`. + */ + function skip(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function skip(name?: string, fn?: TestFn): Promise; + function skip(options?: TestOptions, fn?: TestFn): Promise; + function skip(fn?: TestFn): Promise; + /** + * Shorthand for marking a test as `TODO`. This is the same as calling {@link it} with `options.todo` set to `true`. + */ + function todo(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function todo(name?: string, fn?: TestFn): Promise; + function todo(options?: TestOptions, fn?: TestFn): Promise; + function todo(fn?: TestFn): Promise; + /** + * Shorthand for marking a test as `only`. This is the same as calling {@link it} with `options.only` set to `true`. + * @since v18.15.0 + */ + function only(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function only(name?: string, fn?: TestFn): Promise; + function only(options?: TestOptions, fn?: TestFn): Promise; + function only(fn?: TestFn): Promise; + } + /** + * Shorthand for skipping a test. This is the same as calling {@link test} with `options.skip` set to `true`. + * @since v20.2.0 + */ + function skip(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function skip(name?: string, fn?: TestFn): Promise; + function skip(options?: TestOptions, fn?: TestFn): Promise; + function skip(fn?: TestFn): Promise; + /** + * Shorthand for marking a test as `TODO`. This is the same as calling {@link test} with `options.todo` set to `true`. + * @since v20.2.0 + */ + function todo(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function todo(name?: string, fn?: TestFn): Promise; + function todo(options?: TestOptions, fn?: TestFn): Promise; + function todo(fn?: TestFn): Promise; + /** + * Shorthand for marking a test as `only`. This is the same as calling {@link test} with `options.only` set to `true`. + * @since v20.2.0 + */ + function only(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function only(name?: string, fn?: TestFn): Promise; + function only(options?: TestOptions, fn?: TestFn): Promise; + function only(fn?: TestFn): Promise; + /** + * The type of a function passed to {@link test}. The first argument to this function is a {@link TestContext} object. + * If the test uses callbacks, the callback function is passed as the second argument. + */ + type TestFn = (t: TestContext, done: (result?: any) => void) => void | Promise; + /** + * The type of a suite test function. The argument to this function is a {@link SuiteContext} object. + */ + type SuiteFn = (s: SuiteContext) => void | Promise; + interface TestShard { + /** + * A positive integer between 1 and `total` that specifies the index of the shard to run. + */ + index: number; + /** + * A positive integer that specifies the total number of shards to split the test files to. + */ + total: number; + } + interface RunOptions { + /** + * If a number is provided, then that many test processes would run in parallel, where each process corresponds to one test file. + * If `true`, it would run `os.availableParallelism() - 1` test files in parallel. If `false`, it would only run one test file at a time. + * @default false + */ + concurrency?: number | boolean | undefined; + /** + * An array containing the list of files to run. If omitted, files are run according to the + * [test runner execution model](https://nodejs.org/docs/latest-v22.x/api/test.html#test-runner-execution-model). + */ + files?: readonly string[] | undefined; + /** + * Configures the test runner to exit the process once all known + * tests have finished executing even if the event loop would + * otherwise remain active. + * @default false + */ + forceExit?: boolean | undefined; + /** + * Sets inspector port of test child process. + * If a nullish value is provided, each process gets its own port, + * incremented from the primary's `process.debugPort`. + * @default undefined + */ + inspectPort?: number | (() => number) | undefined; + /** + * If truthy, the test context will only run tests that have the `only` option set + */ + only?: boolean | undefined; + /** + * A function that accepts the `TestsStream` instance and can be used to setup listeners before any tests are run. + * @default undefined + */ + setup?: ((reporter: TestsStream) => void | Promise) | undefined; + /** + * Allows aborting an in-progress test execution. + */ + signal?: AbortSignal | undefined; + /** + * If provided, only run tests whose name matches the provided pattern. + * Strings are interpreted as JavaScript regular expressions. + * @default undefined + */ + testNamePatterns?: string | RegExp | ReadonlyArray | undefined; + /** + * A String, RegExp or a RegExp Array, that can be used to exclude running tests whose + * name matches the provided pattern. Test name patterns are interpreted as JavaScript + * regular expressions. For each test that is executed, any corresponding test hooks, + * such as `beforeEach()`, are also run. + * @default undefined + * @since v22.1.0 + */ + testSkipPatterns?: string | RegExp | ReadonlyArray | undefined; + /** + * The number of milliseconds after which the test execution will fail. + * If unspecified, subtests inherit this value from their parent. + * @default Infinity + */ + timeout?: number | undefined; + /** + * Whether to run in watch mode or not. + * @default false + */ + watch?: boolean | undefined; + /** + * Running tests in a specific shard. + * @default undefined + */ + shard?: TestShard | undefined; + } + /** + * A successful call to `run()` will return a new `TestsStream` object, streaming a series of events representing the execution of the tests. + * + * Some of the events are guaranteed to be emitted in the same order as the tests are defined, while others are emitted in the order that the tests execute. + * @since v18.9.0, v16.19.0 + */ + class TestsStream extends Readable implements NodeJS.ReadableStream { + addListener(event: "test:coverage", listener: (data: TestCoverage) => void): this; + addListener(event: "test:complete", listener: (data: TestComplete) => void): this; + addListener(event: "test:dequeue", listener: (data: TestDequeue) => void): this; + addListener(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + addListener(event: "test:enqueue", listener: (data: TestEnqueue) => void): this; + addListener(event: "test:fail", listener: (data: TestFail) => void): this; + addListener(event: "test:pass", listener: (data: TestPass) => void): this; + addListener(event: "test:plan", listener: (data: TestPlan) => void): this; + addListener(event: "test:start", listener: (data: TestStart) => void): this; + addListener(event: "test:stderr", listener: (data: TestStderr) => void): this; + addListener(event: "test:stdout", listener: (data: TestStdout) => void): this; + addListener(event: "test:watch:drained", listener: () => void): this; + addListener(event: string, listener: (...args: any[]) => void): this; + emit(event: "test:coverage", data: TestCoverage): boolean; + emit(event: "test:complete", data: TestComplete): boolean; + emit(event: "test:dequeue", data: TestDequeue): boolean; + emit(event: "test:diagnostic", data: DiagnosticData): boolean; + emit(event: "test:enqueue", data: TestEnqueue): boolean; + emit(event: "test:fail", data: TestFail): boolean; + emit(event: "test:pass", data: TestPass): boolean; + emit(event: "test:plan", data: TestPlan): boolean; + emit(event: "test:start", data: TestStart): boolean; + emit(event: "test:stderr", data: TestStderr): boolean; + emit(event: "test:stdout", data: TestStdout): boolean; + emit(event: "test:watch:drained"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "test:coverage", listener: (data: TestCoverage) => void): this; + on(event: "test:complete", listener: (data: TestComplete) => void): this; + on(event: "test:dequeue", listener: (data: TestDequeue) => void): this; + on(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + on(event: "test:enqueue", listener: (data: TestEnqueue) => void): this; + on(event: "test:fail", listener: (data: TestFail) => void): this; + on(event: "test:pass", listener: (data: TestPass) => void): this; + on(event: "test:plan", listener: (data: TestPlan) => void): this; + on(event: "test:start", listener: (data: TestStart) => void): this; + on(event: "test:stderr", listener: (data: TestStderr) => void): this; + on(event: "test:stdout", listener: (data: TestStdout) => void): this; + on(event: "test:watch:drained", listener: () => void): this; + on(event: string, listener: (...args: any[]) => void): this; + once(event: "test:coverage", listener: (data: TestCoverage) => void): this; + once(event: "test:complete", listener: (data: TestComplete) => void): this; + once(event: "test:dequeue", listener: (data: TestDequeue) => void): this; + once(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + once(event: "test:enqueue", listener: (data: TestEnqueue) => void): this; + once(event: "test:fail", listener: (data: TestFail) => void): this; + once(event: "test:pass", listener: (data: TestPass) => void): this; + once(event: "test:plan", listener: (data: TestPlan) => void): this; + once(event: "test:start", listener: (data: TestStart) => void): this; + once(event: "test:stderr", listener: (data: TestStderr) => void): this; + once(event: "test:stdout", listener: (data: TestStdout) => void): this; + once(event: "test:watch:drained", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "test:coverage", listener: (data: TestCoverage) => void): this; + prependListener(event: "test:complete", listener: (data: TestComplete) => void): this; + prependListener(event: "test:dequeue", listener: (data: TestDequeue) => void): this; + prependListener(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + prependListener(event: "test:enqueue", listener: (data: TestEnqueue) => void): this; + prependListener(event: "test:fail", listener: (data: TestFail) => void): this; + prependListener(event: "test:pass", listener: (data: TestPass) => void): this; + prependListener(event: "test:plan", listener: (data: TestPlan) => void): this; + prependListener(event: "test:start", listener: (data: TestStart) => void): this; + prependListener(event: "test:stderr", listener: (data: TestStderr) => void): this; + prependListener(event: "test:stdout", listener: (data: TestStdout) => void): this; + prependListener(event: "test:watch:drained", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "test:coverage", listener: (data: TestCoverage) => void): this; + prependOnceListener(event: "test:complete", listener: (data: TestComplete) => void): this; + prependOnceListener(event: "test:dequeue", listener: (data: TestDequeue) => void): this; + prependOnceListener(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + prependOnceListener(event: "test:enqueue", listener: (data: TestEnqueue) => void): this; + prependOnceListener(event: "test:fail", listener: (data: TestFail) => void): this; + prependOnceListener(event: "test:pass", listener: (data: TestPass) => void): this; + prependOnceListener(event: "test:plan", listener: (data: TestPlan) => void): this; + prependOnceListener(event: "test:start", listener: (data: TestStart) => void): this; + prependOnceListener(event: "test:stderr", listener: (data: TestStderr) => void): this; + prependOnceListener(event: "test:stdout", listener: (data: TestStdout) => void): this; + prependOnceListener(event: "test:watch:drained", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + } + /** + * An instance of `TestContext` is passed to each test function in order to + * interact with the test runner. However, the `TestContext` constructor is not + * exposed as part of the API. + * @since v18.0.0, v16.17.0 + */ + class TestContext { + /** + * An object containing assertion methods bound to the test context. + * The top-level functions from the `node:assert` module are exposed here for the purpose of creating test plans. + * @since v22.2.0 + */ + readonly assert: TestContextAssert; + /** + * This function is used to create a hook running before subtest of the current test. + * @param fn The hook function. The first argument to this function is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + * @since v20.1.0, v18.17.0 + */ + before(fn?: TestContextHookFn, options?: HookOptions): void; + /** + * This function is used to create a hook running before each subtest of the current test. + * @param fn The hook function. The first argument to this function is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + beforeEach(fn?: TestContextHookFn, options?: HookOptions): void; + /** + * This function is used to create a hook that runs after the current test finishes. + * @param fn The hook function. The first argument to this function is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + * @since v18.13.0 + */ + after(fn?: TestContextHookFn, options?: HookOptions): void; + /** + * This function is used to create a hook running after each subtest of the current test. + * @param fn The hook function. The first argument to this function is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + afterEach(fn?: TestContextHookFn, options?: HookOptions): void; + /** + * This function is used to write diagnostics to the output. Any diagnostic + * information is included at the end of the test's results. This function does + * not return a value. + * + * ```js + * test('top level test', (t) => { + * t.diagnostic('A diagnostic message'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Message to be reported. + */ + diagnostic(message: string): void; + /** + * The name of the test and each of its ancestors, separated by `>`. + * @since v22.3.0 + */ + readonly fullName: string; + /** + * The name of the test. + * @since v18.8.0, v16.18.0 + */ + readonly name: string; + /** + * Used to set the number of assertions and subtests that are expected to run within the test. + * If the number of assertions and subtests that run does not match the expected count, the test will fail. + * + * To make sure assertions are tracked, the assert functions on `context.assert` must be used, + * instead of importing from the `node:assert` module. + * ```js + * test('top level test', (t) => { + * t.plan(2); + * t.assert.ok('some relevant assertion here'); + * t.test('subtest', () => {}); + * }); + * ``` + * + * When working with asynchronous code, the `plan` function can be used to ensure that the correct number of assertions are run: + * ```js + * test('planning with streams', (t, done) => { + * function* generate() { + * yield 'a'; + * yield 'b'; + * yield 'c'; + * } + * const expected = ['a', 'b', 'c']; + * t.plan(expected.length); + * const stream = Readable.from(generate()); + * stream.on('data', (chunk) => { + * t.assert.strictEqual(chunk, expected.shift()); + * }); + * stream.on('end', () => { + * done(); + * }); + * }); + * ``` + * @since v22.2.0 + */ + plan(count: number): void; + /** + * If `shouldRunOnlyTests` is truthy, the test context will only run tests that + * have the `only` option set. Otherwise, all tests are run. If Node.js was not + * started with the `--test-only` command-line option, this function is a + * no-op. + * + * ```js + * test('top level test', (t) => { + * // The test context can be set to run subtests with the 'only' option. + * t.runOnly(true); + * return Promise.all([ + * t.test('this subtest is now skipped'), + * t.test('this subtest is run', { only: true }), + * ]); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param shouldRunOnlyTests Whether or not to run `only` tests. + */ + runOnly(shouldRunOnlyTests: boolean): void; + /** + * ```js + * test('top level test', async (t) => { + * await fetch('some/uri', { signal: t.signal }); + * }); + * ``` + * @since v18.7.0, v16.17.0 + */ + readonly signal: AbortSignal; + /** + * This function causes the test's output to indicate the test as skipped. If `message` is provided, it is included in the output. Calling `skip()` does + * not terminate execution of the test function. This function does not return a + * value. + * + * ```js + * test('top level test', (t) => { + * // Make sure to return here as well if the test contains additional logic. + * t.skip('this is skipped'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Optional skip message. + */ + skip(message?: string): void; + /** + * This function adds a `TODO` directive to the test's output. If `message` is + * provided, it is included in the output. Calling `todo()` does not terminate + * execution of the test function. This function does not return a value. + * + * ```js + * test('top level test', (t) => { + * // This test is marked as `TODO` + * t.todo('this is a todo'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Optional `TODO` message. + */ + todo(message?: string): void; + /** + * This function is used to create subtests under the current test. This function behaves in + * the same fashion as the top level {@link test} function. + * @since v18.0.0 + * @param name The name of the test, which is displayed when reporting test results. + * Defaults to the `name` property of `fn`, or `''` if `fn` does not have a name. + * @param options Configuration options for the test. + * @param fn The function under test. This first argument to this function is a {@link TestContext} object. + * If the test uses callbacks, the callback function is passed as the second argument. + * @returns A {@link Promise} resolved with `undefined` once the test completes. + */ + test: typeof test; + /** + * Each test provides its own MockTracker instance. + */ + readonly mock: MockTracker; + } + interface TestContextAssert { + /** + * Identical to the `deepEqual` function from the `node:assert` module, but bound to the test context. + */ + deepEqual: typeof import("node:assert").deepEqual; + /** + * Identical to the `deepStrictEqual` function from the `node:assert` module, but bound to the test context. + */ + deepStrictEqual: typeof import("node:assert").deepStrictEqual; + /** + * Identical to the `doesNotMatch` function from the `node:assert` module, but bound to the test context. + */ + doesNotMatch: typeof import("node:assert").doesNotMatch; + /** + * Identical to the `doesNotReject` function from the `node:assert` module, but bound to the test context. + */ + doesNotReject: typeof import("node:assert").doesNotReject; + /** + * Identical to the `doesNotThrow` function from the `node:assert` module, but bound to the test context. + */ + doesNotThrow: typeof import("node:assert").doesNotThrow; + /** + * Identical to the `equal` function from the `node:assert` module, but bound to the test context. + */ + equal: typeof import("node:assert").equal; + /** + * Identical to the `fail` function from the `node:assert` module, but bound to the test context. + */ + fail: typeof import("node:assert").fail; + /** + * Identical to the `ifError` function from the `node:assert` module, but bound to the test context. + */ + ifError: typeof import("node:assert").ifError; + /** + * Identical to the `match` function from the `node:assert` module, but bound to the test context. + */ + match: typeof import("node:assert").match; + /** + * Identical to the `notDeepEqual` function from the `node:assert` module, but bound to the test context. + */ + notDeepEqual: typeof import("node:assert").notDeepEqual; + /** + * Identical to the `notDeepStrictEqual` function from the `node:assert` module, but bound to the test context. + */ + notDeepStrictEqual: typeof import("node:assert").notDeepStrictEqual; + /** + * Identical to the `notEqual` function from the `node:assert` module, but bound to the test context. + */ + notEqual: typeof import("node:assert").notEqual; + /** + * Identical to the `notStrictEqual` function from the `node:assert` module, but bound to the test context. + */ + notStrictEqual: typeof import("node:assert").notStrictEqual; + /** + * Identical to the `ok` function from the `node:assert` module, but bound to the test context. + */ + ok: typeof import("node:assert").ok; + /** + * Identical to the `rejects` function from the `node:assert` module, but bound to the test context. + */ + rejects: typeof import("node:assert").rejects; + /** + * Identical to the `strictEqual` function from the `node:assert` module, but bound to the test context. + */ + strictEqual: typeof import("node:assert").strictEqual; + /** + * Identical to the `throws` function from the `node:assert` module, but bound to the test context. + */ + throws: typeof import("node:assert").throws; + /** + * This function implements assertions for snapshot testing. + * ```js + * test('snapshot test with default serialization', (t) => { + * t.assert.snapshot({ value1: 1, value2: 2 }); + * }); + * + * test('snapshot test with custom serialization', (t) => { + * t.assert.snapshot({ value3: 3, value4: 4 }, { + * serializers: [(value) => JSON.stringify(value)] + * }); + * }); + * ``` + * + * Only available through the [--experimental-test-snapshots](https://nodejs.org/api/cli.html#--experimental-test-snapshots) flag. + * @since v22.3.0 + * @experimental + */ + snapshot(value: any, options?: AssertSnapshotOptions): void; + } + interface AssertSnapshotOptions { + /** + * An array of synchronous functions used to serialize `value` into a string. + * `value` is passed as the only argument to the first serializer function. + * The return value of each serializer is passed as input to the next serializer. + * Once all serializers have run, the resulting value is coerced to a string. + * + * If no serializers are provided, the test runner's default serializers are used. + */ + serializers?: ReadonlyArray<(value: any) => any> | undefined; + } + + /** + * An instance of `SuiteContext` is passed to each suite function in order to + * interact with the test runner. However, the `SuiteContext` constructor is not + * exposed as part of the API. + * @since v18.7.0, v16.17.0 + */ + class SuiteContext { + /** + * The name of the suite. + * @since v18.8.0, v16.18.0 + */ + readonly name: string; + /** + * Can be used to abort test subtasks when the test has been aborted. + * @since v18.7.0, v16.17.0 + */ + readonly signal: AbortSignal; + } + interface TestOptions { + /** + * If a number is provided, then that many tests would run in parallel. + * If truthy, it would run (number of cpu cores - 1) tests in parallel. + * For subtests, it will be `Infinity` tests in parallel. + * If falsy, it would only run one test at a time. + * If unspecified, subtests inherit this value from their parent. + * @default false + */ + concurrency?: number | boolean | undefined; + /** + * If truthy, and the test context is configured to run `only` tests, then this test will be + * run. Otherwise, the test is skipped. + * @default false + */ + only?: boolean | undefined; + /** + * Allows aborting an in-progress test. + * @since v18.8.0 + */ + signal?: AbortSignal | undefined; + /** + * If truthy, the test is skipped. If a string is provided, that string is displayed in the + * test results as the reason for skipping the test. + * @default false + */ + skip?: boolean | string | undefined; + /** + * A number of milliseconds the test will fail after. If unspecified, subtests inherit this + * value from their parent. + * @default Infinity + * @since v18.7.0 + */ + timeout?: number | undefined; + /** + * If truthy, the test marked as `TODO`. If a string is provided, that string is displayed in + * the test results as the reason why the test is `TODO`. + * @default false + */ + todo?: boolean | string | undefined; + /** + * The number of assertions and subtests expected to be run in the test. + * If the number of assertions run in the test does not match the number + * specified in the plan, the test will fail. + * @default undefined + * @since v22.2.0 + */ + plan?: number | undefined; + } + /** + * This function creates a hook that runs before executing a suite. + * + * ```js + * describe('tests', async () => { + * before(() => console.log('about to run some test')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + */ + function before(fn?: HookFn, options?: HookOptions): void; + /** + * This function creates a hook that runs after executing a suite. + * + * ```js + * describe('tests', async () => { + * after(() => console.log('finished running tests')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + */ + function after(fn?: HookFn, options?: HookOptions): void; + /** + * This function creates a hook that runs before each test in the current suite. + * + * ```js + * describe('tests', async () => { + * beforeEach(() => console.log('about to run a test')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + */ + function beforeEach(fn?: HookFn, options?: HookOptions): void; + /** + * This function creates a hook that runs after each test in the current suite. + * The `afterEach()` hook is run even if the test fails. + * + * ```js + * describe('tests', async () => { + * afterEach(() => console.log('finished running a test')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + */ + function afterEach(fn?: HookFn, options?: HookOptions): void; + /** + * The hook function. The first argument is the context in which the hook is called. + * If the hook uses callbacks, the callback function is passed as the second argument. + */ + type HookFn = (c: TestContext | SuiteContext, done: (result?: any) => void) => any; + /** + * The hook function. The first argument is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + */ + type TestContextHookFn = (t: TestContext, done: (result?: any) => void) => any; + /** + * Configuration options for hooks. + * @since v18.8.0 + */ + interface HookOptions { + /** + * Allows aborting an in-progress hook. + */ + signal?: AbortSignal | undefined; + /** + * A number of milliseconds the hook will fail after. If unspecified, subtests inherit this + * value from their parent. + * @default Infinity + */ + timeout?: number | undefined; + } + interface MockFunctionOptions { + /** + * The number of times that the mock will use the behavior of `implementation`. + * Once the mock function has been called `times` times, + * it will automatically restore the behavior of `original`. + * This value must be an integer greater than zero. + * @default Infinity + */ + times?: number | undefined; + } + interface MockMethodOptions extends MockFunctionOptions { + /** + * If `true`, `object[methodName]` is treated as a getter. + * This option cannot be used with the `setter` option. + */ + getter?: boolean | undefined; + /** + * If `true`, `object[methodName]` is treated as a setter. + * This option cannot be used with the `getter` option. + */ + setter?: boolean | undefined; + } + type Mock = F & { + mock: MockFunctionContext; + }; + type NoOpFunction = (...args: any[]) => undefined; + type FunctionPropertyNames = { + [K in keyof T]: T[K] extends Function ? K : never; + }[keyof T]; + interface MockModuleOptions { + /** + * If false, each call to `require()` or `import()` generates a new mock module. + * If true, subsequent calls will return the same module mock, and the mock module is inserted into the CommonJS cache. + * @default false + */ + cache?: boolean | undefined; + /** + * The value to use as the mocked module's default export. + * + * If this value is not provided, ESM mocks do not include a default export. + * If the mock is a CommonJS or builtin module, this setting is used as the value of `module.exports`. + * If this value is not provided, CJS and builtin mocks use an empty object as the value of `module.exports`. + */ + defaultExport?: any; + /** + * An object whose keys and values are used to create the named exports of the mock module. + * + * If the mock is a CommonJS or builtin module, these values are copied onto `module.exports`. + * Therefore, if a mock is created with both named exports and a non-object default export, + * the mock will throw an exception when used as a CJS or builtin module. + */ + namedExports?: object | undefined; + } + /** + * The `MockTracker` class is used to manage mocking functionality. The test runner + * module provides a top level `mock` export which is a `MockTracker` instance. + * Each test also provides its own `MockTracker` instance via the test context's `mock` property. + * @since v19.1.0, v18.13.0 + */ + class MockTracker { + /** + * This function is used to create a mock function. + * + * The following example creates a mock function that increments a counter by one + * on each invocation. The `times` option is used to modify the mock behavior such + * that the first two invocations add two to the counter instead of one. + * + * ```js + * test('mocks a counting function', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne, addTwo, { times: 2 }); + * + * assert.strictEqual(fn(), 2); + * assert.strictEqual(fn(), 4); + * assert.strictEqual(fn(), 5); + * assert.strictEqual(fn(), 6); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param original An optional function to create a mock on. + * @param implementation An optional function used as the mock implementation for `original`. This is useful for creating mocks that exhibit one behavior for a specified number of calls and + * then restore the behavior of `original`. + * @param options Optional configuration options for the mock function. + * @return The mocked function. The mocked function contains a special `mock` property, which is an instance of {@link MockFunctionContext}, and can be used for inspecting and changing the + * behavior of the mocked function. + */ + fn(original?: F, options?: MockFunctionOptions): Mock; + fn( + original?: F, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock; + /** + * This function is used to create a mock on an existing object method. The + * following example demonstrates how a mock is created on an existing object + * method. + * + * ```js + * test('spies on an object method', (t) => { + * const number = { + * value: 5, + * subtract(a) { + * return this.value - a; + * }, + * }; + * + * t.mock.method(number, 'subtract'); + * assert.strictEqual(number.subtract.mock.calls.length, 0); + * assert.strictEqual(number.subtract(3), 2); + * assert.strictEqual(number.subtract.mock.calls.length, 1); + * + * const call = number.subtract.mock.calls[0]; + * + * assert.deepStrictEqual(call.arguments, [3]); + * assert.strictEqual(call.result, 2); + * assert.strictEqual(call.error, undefined); + * assert.strictEqual(call.target, undefined); + * assert.strictEqual(call.this, number); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param object The object whose method is being mocked. + * @param methodName The identifier of the method on `object` to mock. If `object[methodName]` is not a function, an error is thrown. + * @param implementation An optional function used as the mock implementation for `object[methodName]`. + * @param options Optional configuration options for the mock method. + * @return The mocked method. The mocked method contains a special `mock` property, which is an instance of {@link MockFunctionContext}, and can be used for inspecting and changing the + * behavior of the mocked method. + */ + method< + MockedObject extends object, + MethodName extends FunctionPropertyNames, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): MockedObject[MethodName] extends Function ? Mock + : never; + method< + MockedObject extends object, + MethodName extends FunctionPropertyNames, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation: Implementation, + options?: MockFunctionOptions, + ): MockedObject[MethodName] extends Function ? Mock + : never; + method( + object: MockedObject, + methodName: keyof MockedObject, + options: MockMethodOptions, + ): Mock; + method( + object: MockedObject, + methodName: keyof MockedObject, + implementation: Function, + options: MockMethodOptions, + ): Mock; + + /** + * This function is syntax sugar for `MockTracker.method` with `options.getter` set to `true`. + * @since v19.3.0, v18.13.0 + */ + getter< + MockedObject extends object, + MethodName extends keyof MockedObject, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): Mock<() => MockedObject[MethodName]>; + getter< + MockedObject extends object, + MethodName extends keyof MockedObject, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock<(() => MockedObject[MethodName]) | Implementation>; + /** + * This function is syntax sugar for `MockTracker.method` with `options.setter` set to `true`. + * @since v19.3.0, v18.13.0 + */ + setter< + MockedObject extends object, + MethodName extends keyof MockedObject, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): Mock<(value: MockedObject[MethodName]) => void>; + setter< + MockedObject extends object, + MethodName extends keyof MockedObject, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock<((value: MockedObject[MethodName]) => void) | Implementation>; + + /** + * This function is used to mock the exports of ECMAScript modules, CommonJS modules, and Node.js builtin modules. + * Any references to the original module prior to mocking are not impacted. + * + * Only available through the [--experimental-test-module-mocks](https://nodejs.org/api/cli.html#--experimental-test-module-mocks) flag. + * @since v22.3.0 + * @experimental + * @param specifier A string identifying the module to mock. + * @param options Optional configuration options for the mock module. + */ + module(specifier: string, options?: MockModuleOptions): MockModuleContext; + + /** + * This function restores the default behavior of all mocks that were previously + * created by this `MockTracker` and disassociates the mocks from the `MockTracker` instance. Once disassociated, the mocks can still be used, but the `MockTracker` instance can no longer be + * used to reset their behavior or + * otherwise interact with them. + * + * After each test completes, this function is called on the test context's `MockTracker`. If the global `MockTracker` is used extensively, calling this + * function manually is recommended. + * @since v19.1.0, v18.13.0 + */ + reset(): void; + /** + * This function restores the default behavior of all mocks that were previously + * created by this `MockTracker`. Unlike `mock.reset()`, `mock.restoreAll()` does + * not disassociate the mocks from the `MockTracker` instance. + * @since v19.1.0, v18.13.0 + */ + restoreAll(): void; + + timers: MockTimers; + } + const mock: MockTracker; + interface MockFunctionCall< + F extends Function, + ReturnType = F extends (...args: any) => infer T ? T + : F extends abstract new(...args: any) => infer T ? T + : unknown, + Args = F extends (...args: infer Y) => any ? Y + : F extends abstract new(...args: infer Y) => any ? Y + : unknown[], + > { + /** + * An array of the arguments passed to the mock function. + */ + arguments: Args; + /** + * If the mocked function threw then this property contains the thrown value. + */ + error: unknown | undefined; + /** + * The value returned by the mocked function. + * + * If the mocked function threw, it will be `undefined`. + */ + result: ReturnType | undefined; + /** + * An `Error` object whose stack can be used to determine the callsite of the mocked function invocation. + */ + stack: Error; + /** + * If the mocked function is a constructor, this field contains the class being constructed. + * Otherwise this will be `undefined`. + */ + target: F extends abstract new(...args: any) => any ? F : undefined; + /** + * The mocked function's `this` value. + */ + this: unknown; + } + /** + * The `MockFunctionContext` class is used to inspect or manipulate the behavior of + * mocks created via the `MockTracker` APIs. + * @since v19.1.0, v18.13.0 + */ + class MockFunctionContext { + /** + * A getter that returns a copy of the internal array used to track calls to the + * mock. Each entry in the array is an object with the following properties. + * @since v19.1.0, v18.13.0 + */ + readonly calls: Array>; + /** + * This function returns the number of times that this mock has been invoked. This + * function is more efficient than checking `ctx.calls.length` because `ctx.calls` is a getter that creates a copy of the internal call tracking array. + * @since v19.1.0, v18.13.0 + * @return The number of times that this mock has been invoked. + */ + callCount(): number; + /** + * This function is used to change the behavior of an existing mock. + * + * The following example creates a mock function using `t.mock.fn()`, calls the + * mock function, and then changes the mock implementation to a different function. + * + * ```js + * test('changes a mock behavior', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne); + * + * assert.strictEqual(fn(), 1); + * fn.mock.mockImplementation(addTwo); + * assert.strictEqual(fn(), 3); + * assert.strictEqual(fn(), 5); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param implementation The function to be used as the mock's new implementation. + */ + mockImplementation(implementation: F): void; + /** + * This function is used to change the behavior of an existing mock for a single + * invocation. Once invocation `onCall` has occurred, the mock will revert to + * whatever behavior it would have used had `mockImplementationOnce()` not been + * called. + * + * The following example creates a mock function using `t.mock.fn()`, calls the + * mock function, changes the mock implementation to a different function for the + * next invocation, and then resumes its previous behavior. + * + * ```js + * test('changes a mock behavior once', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne); + * + * assert.strictEqual(fn(), 1); + * fn.mock.mockImplementationOnce(addTwo); + * assert.strictEqual(fn(), 3); + * assert.strictEqual(fn(), 4); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param implementation The function to be used as the mock's implementation for the invocation number specified by `onCall`. + * @param onCall The invocation number that will use `implementation`. If the specified invocation has already occurred then an exception is thrown. + */ + mockImplementationOnce(implementation: F, onCall?: number): void; + /** + * Resets the call history of the mock function. + * @since v19.3.0, v18.13.0 + */ + resetCalls(): void; + /** + * Resets the implementation of the mock function to its original behavior. The + * mock can still be used after calling this function. + * @since v19.1.0, v18.13.0 + */ + restore(): void; + } + /** + * @since v22.3.0 + * @experimental + */ + class MockModuleContext { + /** + * Resets the implementation of the mock module. + * @since v22.3.0 + */ + restore(): void; + } + + type Timer = "setInterval" | "setTimeout" | "setImmediate" | "Date"; + interface MockTimersOptions { + apis: Timer[]; + now?: number | Date | undefined; + } + /** + * Mocking timers is a technique commonly used in software testing to simulate and + * control the behavior of timers, such as `setInterval` and `setTimeout`, + * without actually waiting for the specified time intervals. + * + * The MockTimers API also allows for mocking of the `Date` constructor and + * `setImmediate`/`clearImmediate` functions. + * + * The `MockTracker` provides a top-level `timers` export + * which is a `MockTimers` instance. + * @since v20.4.0 + * @experimental + */ + class MockTimers { + /** + * Enables timer mocking for the specified timers. + * + * **Note:** When you enable mocking for a specific timer, its associated + * clear function will also be implicitly mocked. + * + * **Note:** Mocking `Date` will affect the behavior of the mocked timers + * as they use the same internal clock. + * + * Example usage without setting initial time: + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.enable({ apis: ['setInterval', 'Date'], now: 1234 }); + * ``` + * + * The above example enables mocking for the `Date` constructor, `setInterval` timer and + * implicitly mocks the `clearInterval` function. Only the `Date` constructor from `globalThis`, + * `setInterval` and `clearInterval` functions from `node:timers`, `node:timers/promises`, and `globalThis` will be mocked. + * + * Example usage with initial time set + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.enable({ apis: ['Date'], now: 1000 }); + * ``` + * + * Example usage with initial Date object as time set + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.enable({ apis: ['Date'], now: new Date() }); + * ``` + * + * Alternatively, if you call `mock.timers.enable()` without any parameters: + * + * All timers (`'setInterval'`, `'clearInterval'`, `'Date'`, `'setImmediate'`, `'clearImmediate'`, `'setTimeout'`, and `'clearTimeout'`) + * will be mocked. + * + * The `setInterval`, `clearInterval`, `setTimeout`, and `clearTimeout` functions from `node:timers`, `node:timers/promises`, + * and `globalThis` will be mocked. + * The `Date` constructor from `globalThis` will be mocked. + * + * If there is no initial epoch set, the initial date will be based on 0 in the Unix epoch. This is `January 1st, 1970, 00:00:00 UTC`. You can + * set an initial date by passing a now property to the `.enable()` method. This value will be used as the initial date for the mocked Date + * object. It can either be a positive integer, or another Date object. + * @since v20.4.0 + */ + enable(options?: MockTimersOptions): void; + /** + * You can use the `.setTime()` method to manually move the mocked date to another time. This method only accepts a positive integer. + * Note: This method will execute any mocked timers that are in the past from the new time. + * In the below example we are setting a new time for the mocked date. + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * test('sets the time of a date object', (context) => { + * // Optionally choose what to mock + * context.mock.timers.enable({ apis: ['Date'], now: 100 }); + * assert.strictEqual(Date.now(), 100); + * // Advance in time will also advance the date + * context.mock.timers.setTime(1000); + * context.mock.timers.tick(200); + * assert.strictEqual(Date.now(), 1200); + * }); + * ``` + */ + setTime(time: number): void; + /** + * This function restores the default behavior of all mocks that were previously + * created by this `MockTimers` instance and disassociates the mocks + * from the `MockTracker` instance. + * + * **Note:** After each test completes, this function is called on + * the test context's `MockTracker`. + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.reset(); + * ``` + * @since v20.4.0 + */ + reset(): void; + /** + * Advances time for all mocked timers. + * + * **Note:** This diverges from how `setTimeout` in Node.js behaves and accepts + * only positive numbers. In Node.js, `setTimeout` with negative numbers is + * only supported for web compatibility reasons. + * + * The following example mocks a `setTimeout` function and + * by using `.tick` advances in + * time triggering all pending timers. + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { + * const fn = context.mock.fn(); + * + * context.mock.timers.enable({ apis: ['setTimeout'] }); + * + * setTimeout(fn, 9999); + * + * assert.strictEqual(fn.mock.callCount(), 0); + * + * // Advance in time + * context.mock.timers.tick(9999); + * + * assert.strictEqual(fn.mock.callCount(), 1); + * }); + * ``` + * + * Alternativelly, the `.tick` function can be called many times + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { + * const fn = context.mock.fn(); + * context.mock.timers.enable({ apis: ['setTimeout'] }); + * const nineSecs = 9000; + * setTimeout(fn, nineSecs); + * + * const twoSeconds = 3000; + * context.mock.timers.tick(twoSeconds); + * context.mock.timers.tick(twoSeconds); + * context.mock.timers.tick(twoSeconds); + * + * assert.strictEqual(fn.mock.callCount(), 1); + * }); + * ``` + * + * Advancing time using `.tick` will also advance the time for any `Date` object + * created after the mock was enabled (if `Date` was also set to be mocked). + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { + * const fn = context.mock.fn(); + * + * context.mock.timers.enable({ apis: ['setTimeout', 'Date'] }); + * setTimeout(fn, 9999); + * + * assert.strictEqual(fn.mock.callCount(), 0); + * assert.strictEqual(Date.now(), 0); + * + * // Advance in time + * context.mock.timers.tick(9999); + * assert.strictEqual(fn.mock.callCount(), 1); + * assert.strictEqual(Date.now(), 9999); + * }); + * ``` + * @since v20.4.0 + */ + tick(milliseconds: number): void; + /** + * Triggers all pending mocked timers immediately. If the `Date` object is also + * mocked, it will also advance the `Date` object to the furthest timer's time. + * + * The example below triggers all pending timers immediately, + * causing them to execute without any delay. + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('runAll functions following the given order', (context) => { + * context.mock.timers.enable({ apis: ['setTimeout', 'Date'] }); + * const results = []; + * setTimeout(() => results.push(1), 9999); + * + * // Notice that if both timers have the same timeout, + * // the order of execution is guaranteed + * setTimeout(() => results.push(3), 8888); + * setTimeout(() => results.push(2), 8888); + * + * assert.deepStrictEqual(results, []); + * + * context.mock.timers.runAll(); + * assert.deepStrictEqual(results, [3, 2, 1]); + * // The Date object is also advanced to the furthest timer's time + * assert.strictEqual(Date.now(), 9999); + * }); + * ``` + * + * **Note:** The `runAll()` function is specifically designed for + * triggering timers in the context of timer mocking. + * It does not have any effect on real-time system + * clocks or actual timers outside of the mocking environment. + * @since v20.4.0 + */ + runAll(): void; + /** + * Calls {@link MockTimers.reset()}. + */ + [Symbol.dispose](): void; + } + /** + * Only available through the [--experimental-test-snapshots](https://nodejs.org/api/cli.html#--experimental-test-snapshots) flag. + * @since v22.3.0 + * @experimental + */ + namespace snapshot { + /** + * This function is used to customize the default serialization mechanism used by the test runner. + * + * By default, the test runner performs serialization by calling `JSON.stringify(value, null, 2)` on the provided value. + * `JSON.stringify()` does have limitations regarding circular structures and supported data types. + * If a more robust serialization mechanism is required, this function should be used to specify a list of custom serializers. + * + * Serializers are called in order, with the output of the previous serializer passed as input to the next. + * The final result must be a string value. + * @since v22.3.0 + * @param serializers An array of synchronous functions used as the default serializers for snapshot tests. + */ + function setDefaultSnapshotSerializers(serializers: ReadonlyArray<(value: any) => any>): void; + /** + * This function is used to set a custom resolver for the location of the snapshot file used for snapshot testing. + * By default, the snapshot filename is the same as the entry point filename with `.snapshot` appended. + * @since v22.3.0 + * @param fn A function which returns a string specifying the location of the snapshot file. + * The function receives the path of the test file as its only argument. + * If `process.argv[1]` is not associated with a file (for example in the REPL), the input is undefined. + */ + function setResolveSnapshotPath(fn: (path: string | undefined) => string): void; + } + export { + after, + afterEach, + before, + beforeEach, + describe, + it, + Mock, + mock, + only, + run, + skip, + snapshot, + suite, + SuiteContext, + test, + test as default, + TestContext, + todo, + }; +} + +interface TestError extends Error { + cause: Error; +} +interface TestLocationInfo { + /** + * The column number where the test is defined, or + * `undefined` if the test was run through the REPL. + */ + column?: number; + /** + * The path of the test file, `undefined` if test was run through the REPL. + */ + file?: string; + /** + * The line number where the test is defined, or `undefined` if the test was run through the REPL. + */ + line?: number; +} +interface DiagnosticData extends TestLocationInfo { + /** + * The diagnostic message. + */ + message: string; + /** + * The nesting level of the test. + */ + nesting: number; +} +interface TestCoverage { + /** + * An object containing the coverage report. + */ + summary: { + /** + * An array of coverage reports for individual files. + */ + files: Array<{ + /** + * The absolute path of the file. + */ + path: string; + /** + * The total number of lines. + */ + totalLineCount: number; + /** + * The total number of branches. + */ + totalBranchCount: number; + /** + * The total number of functions. + */ + totalFunctionCount: number; + /** + * The number of covered lines. + */ + coveredLineCount: number; + /** + * The number of covered branches. + */ + coveredBranchCount: number; + /** + * The number of covered functions. + */ + coveredFunctionCount: number; + /** + * The percentage of lines covered. + */ + coveredLinePercent: number; + /** + * The percentage of branches covered. + */ + coveredBranchPercent: number; + /** + * The percentage of functions covered. + */ + coveredFunctionPercent: number; + /** + * An array of functions representing function coverage. + */ + functions: Array<{ + /** + * The name of the function. + */ + name: string; + /** + * The line number where the function is defined. + */ + line: number; + /** + * The number of times the function was called. + */ + count: number; + }>; + /** + * An array of branches representing branch coverage. + */ + branches: Array<{ + /** + * The line number where the branch is defined. + */ + line: number; + /** + * The number of times the branch was taken. + */ + count: number; + }>; + /** + * An array of lines representing line numbers and the number of times they were covered. + */ + lines: Array<{ + /** + * The line number. + */ + line: number; + /** + * The number of times the line was covered. + */ + count: number; + }>; + }>; + /** + * An object containing a summary of coverage for all files. + */ + totals: { + /** + * The total number of lines. + */ + totalLineCount: number; + /** + * The total number of branches. + */ + totalBranchCount: number; + /** + * The total number of functions. + */ + totalFunctionCount: number; + /** + * The number of covered lines. + */ + coveredLineCount: number; + /** + * The number of covered branches. + */ + coveredBranchCount: number; + /** + * The number of covered functions. + */ + coveredFunctionCount: number; + /** + * The percentage of lines covered. + */ + coveredLinePercent: number; + /** + * The percentage of branches covered. + */ + coveredBranchPercent: number; + /** + * The percentage of functions covered. + */ + coveredFunctionPercent: number; + }; + /** + * The working directory when code coverage began. This + * is useful for displaying relative path names in case + * the tests changed the working directory of the Node.js process. + */ + workingDirectory: string; + }; + /** + * The nesting level of the test. + */ + nesting: number; +} +interface TestComplete extends TestLocationInfo { + /** + * Additional execution metadata. + */ + details: { + /** + * Whether the test passed or not. + */ + passed: boolean; + /** + * The duration of the test in milliseconds. + */ + duration_ms: number; + /** + * An error wrapping the error thrown by the test if it did not pass. + */ + error?: TestError; + /** + * The type of the test, used to denote whether this is a suite. + */ + type?: "suite"; + }; + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The ordinal number of the test. + */ + testNumber: number; + /** + * Present if `context.todo` is called. + */ + todo?: string | boolean; + /** + * Present if `context.skip` is called. + */ + skip?: string | boolean; +} +interface TestDequeue extends TestLocationInfo { + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; +} +interface TestEnqueue extends TestLocationInfo { + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; +} +interface TestFail extends TestLocationInfo { + /** + * Additional execution metadata. + */ + details: { + /** + * The duration of the test in milliseconds. + */ + duration_ms: number; + /** + * An error wrapping the error thrown by the test. + */ + error: TestError; + /** + * The type of the test, used to denote whether this is a suite. + * @since v20.0.0, v19.9.0, v18.17.0 + */ + type?: "suite"; + }; + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The ordinal number of the test. + */ + testNumber: number; + /** + * Present if `context.todo` is called. + */ + todo?: string | boolean; + /** + * Present if `context.skip` is called. + */ + skip?: string | boolean; +} +interface TestPass extends TestLocationInfo { + /** + * Additional execution metadata. + */ + details: { + /** + * The duration of the test in milliseconds. + */ + duration_ms: number; + /** + * The type of the test, used to denote whether this is a suite. + * @since 20.0.0, 19.9.0, 18.17.0 + */ + type?: "suite"; + }; + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The ordinal number of the test. + */ + testNumber: number; + /** + * Present if `context.todo` is called. + */ + todo?: string | boolean; + /** + * Present if `context.skip` is called. + */ + skip?: string | boolean; +} +interface TestPlan extends TestLocationInfo { + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The number of subtests that have ran. + */ + count: number; +} +interface TestStart extends TestLocationInfo { + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; +} +interface TestStderr { + /** + * The path of the test file. + */ + file: string; + /** + * The message written to `stderr`. + */ + message: string; +} +interface TestStdout { + /** + * The path of the test file. + */ + file: string; + /** + * The message written to `stdout`. + */ + message: string; +} + +/** + * The `node:test/reporters` module exposes the builtin-reporters for `node:test`. + * To access it: + * + * ```js + * import test from 'node:test/reporters'; + * ``` + * + * This module is only available under the `node:` scheme. The following will not + * work: + * + * ```js + * import test from 'test/reporters'; + * ``` + * @since v19.9.0 + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/test/reporters.js) + */ +declare module "node:test/reporters" { + import { Transform, TransformOptions } from "node:stream"; + + type TestEvent = + | { type: "test:coverage"; data: TestCoverage } + | { type: "test:complete"; data: TestComplete } + | { type: "test:dequeue"; data: TestDequeue } + | { type: "test:diagnostic"; data: DiagnosticData } + | { type: "test:enqueue"; data: TestEnqueue } + | { type: "test:fail"; data: TestFail } + | { type: "test:pass"; data: TestPass } + | { type: "test:plan"; data: TestPlan } + | { type: "test:start"; data: TestStart } + | { type: "test:stderr"; data: TestStderr } + | { type: "test:stdout"; data: TestStdout } + | { type: "test:watch:drained"; data: undefined }; + type TestEventGenerator = AsyncGenerator; + + interface ReporterConstructorWrapper Transform> { + new(...args: ConstructorParameters): InstanceType; + (...args: ConstructorParameters): InstanceType; + } + + /** + * The `dot` reporter outputs the test results in a compact format, + * where each passing test is represented by a `.`, + * and each failing test is represented by a `X`. + * @since v20.0.0 + */ + function dot(source: TestEventGenerator): AsyncGenerator<"\n" | "." | "X", void>; + /** + * The `tap` reporter outputs the test results in the [TAP](https://testanything.org/) format. + * @since v20.0.0 + */ + function tap(source: TestEventGenerator): AsyncGenerator; + class SpecReporter extends Transform { + constructor(); + } + /** + * The `spec` reporter outputs the test results in a human-readable format. + * @since v20.0.0 + */ + const spec: ReporterConstructorWrapper; + /** + * The `junit` reporter outputs test results in a jUnit XML format. + * @since v21.0.0 + */ + function junit(source: TestEventGenerator): AsyncGenerator; + class LcovReporter extends Transform { + constructor(opts?: Omit); + } + /** + * The `lcov` reporter outputs test coverage when used with the + * [`--experimental-test-coverage`](https://nodejs.org/docs/latest-v22.x/api/cli.html#--experimental-test-coverage) flag. + * @since v22.0.0 + */ + // TODO: change the export to a wrapper function once node@0db38f0 is merged (breaking change) + // const lcov: ReporterConstructorWrapper; + const lcov: LcovReporter; + + export { dot, junit, lcov, spec, tap, TestEvent }; +} diff --git a/libcore/node_modules/@types/node/timers.d.ts b/libcore/node_modules/@types/node/timers.d.ts new file mode 100644 index 0000000..624f962 --- /dev/null +++ b/libcore/node_modules/@types/node/timers.d.ts @@ -0,0 +1,240 @@ +/** + * The `timer` module exposes a global API for scheduling functions to + * be called at some future period of time. Because the timer functions are + * globals, there is no need to call `require('node:timers')` to use the API. + * + * The timer functions within Node.js implement a similar API as the timers API + * provided by Web Browsers but use a different internal implementation that is + * built around the Node.js [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout). + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/timers.js) + */ +declare module "timers" { + import { Abortable } from "node:events"; + import { + setImmediate as setImmediatePromise, + setInterval as setIntervalPromise, + setTimeout as setTimeoutPromise, + } from "node:timers/promises"; + interface TimerOptions extends Abortable { + /** + * Set to `false` to indicate that the scheduled `Timeout` + * should not require the Node.js event loop to remain active. + * @default true + */ + ref?: boolean | undefined; + } + let setTimeout: typeof global.setTimeout; + let clearTimeout: typeof global.clearTimeout; + let setInterval: typeof global.setInterval; + let clearInterval: typeof global.clearInterval; + let setImmediate: typeof global.setImmediate; + let clearImmediate: typeof global.clearImmediate; + global { + namespace NodeJS { + // compatibility with older typings + interface Timer extends RefCounted { + hasRef(): boolean; + refresh(): this; + [Symbol.toPrimitive](): number; + } + /** + * This object is created internally and is returned from `setImmediate()`. It + * can be passed to `clearImmediate()` in order to cancel the scheduled + * actions. + * + * By default, when an immediate is scheduled, the Node.js event loop will continue + * running as long as the immediate is active. The `Immediate` object returned by `setImmediate()` exports both `immediate.ref()` and `immediate.unref()` functions that can be used to + * control this default behavior. + */ + class Immediate implements RefCounted { + /** + * When called, requests that the Node.js event loop _not_ exit so long as the `Immediate` is active. Calling `immediate.ref()` multiple times will have no + * effect. + * + * By default, all `Immediate` objects are "ref'ed", making it normally unnecessary + * to call `immediate.ref()` unless `immediate.unref()` had been called previously. + * @since v9.7.0 + * @return a reference to `immediate` + */ + ref(): this; + /** + * When called, the active `Immediate` object will not require the Node.js event + * loop to remain active. If there is no other activity keeping the event loop + * running, the process may exit before the `Immediate` object's callback is + * invoked. Calling `immediate.unref()` multiple times will have no effect. + * @since v9.7.0 + * @return a reference to `immediate` + */ + unref(): this; + /** + * If true, the `Immediate` object will keep the Node.js event loop active. + * @since v11.0.0 + */ + hasRef(): boolean; + _onImmediate: Function; // to distinguish it from the Timeout class + /** + * Cancels the immediate. This is similar to calling `clearImmediate()`. + * @since v20.5.0 + */ + [Symbol.dispose](): void; + } + /** + * This object is created internally and is returned from `setTimeout()` and `setInterval()`. It can be passed to either `clearTimeout()` or `clearInterval()` in order to cancel the + * scheduled actions. + * + * By default, when a timer is scheduled using either `setTimeout()` or `setInterval()`, the Node.js event loop will continue running as long as the + * timer is active. Each of the `Timeout` objects returned by these functions + * export both `timeout.ref()` and `timeout.unref()` functions that can be used to + * control this default behavior. + */ + class Timeout implements Timer { + /** + * When called, requests that the Node.js event loop _not_ exit so long as the`Timeout` is active. Calling `timeout.ref()` multiple times will have no effect. + * + * By default, all `Timeout` objects are "ref'ed", making it normally unnecessary + * to call `timeout.ref()` unless `timeout.unref()` had been called previously. + * @since v0.9.1 + * @return a reference to `timeout` + */ + ref(): this; + /** + * When called, the active `Timeout` object will not require the Node.js event loop + * to remain active. If there is no other activity keeping the event loop running, + * the process may exit before the `Timeout` object's callback is invoked. Calling `timeout.unref()` multiple times will have no effect. + * @since v0.9.1 + * @return a reference to `timeout` + */ + unref(): this; + /** + * If true, the `Timeout` object will keep the Node.js event loop active. + * @since v11.0.0 + */ + hasRef(): boolean; + /** + * Sets the timer's start time to the current time, and reschedules the timer to + * call its callback at the previously specified duration adjusted to the current + * time. This is useful for refreshing a timer without allocating a new + * JavaScript object. + * + * Using this on a timer that has already called its callback will reactivate the + * timer. + * @since v10.2.0 + * @return a reference to `timeout` + */ + refresh(): this; + [Symbol.toPrimitive](): number; + /** + * Cancels the timeout. + * @since v20.5.0 + */ + [Symbol.dispose](): void; + } + } + /** + * Schedules execution of a one-time `callback` after `delay` milliseconds. + * + * The `callback` will likely not be invoked in precisely `delay` milliseconds. + * Node.js makes no guarantees about the exact timing of when callbacks will fire, + * nor of their ordering. The callback will be called as close as possible to the + * time specified. + * + * When `delay` is larger than `2147483647` or less than `1`, the `delay` will be set to `1`. Non-integer delays are truncated to an integer. + * + * If `callback` is not a function, a `TypeError` will be thrown. + * + * This method has a custom variant for promises that is available using `timersPromises.setTimeout()`. + * @since v0.0.1 + * @param callback The function to call when the timer elapses. + * @param [delay=1] The number of milliseconds to wait before calling the `callback`. + * @param args Optional arguments to pass when the `callback` is called. + * @return for use with {@link clearTimeout} + */ + function setTimeout( + callback: (...args: TArgs) => void, + ms?: number, + ...args: TArgs + ): NodeJS.Timeout; + // util.promisify no rest args compability + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + function setTimeout(callback: (args: void) => void, ms?: number): NodeJS.Timeout; + namespace setTimeout { + const __promisify__: typeof setTimeoutPromise; + } + /** + * Cancels a `Timeout` object created by `setTimeout()`. + * @since v0.0.1 + * @param timeout A `Timeout` object as returned by {@link setTimeout} or the `primitive` of the `Timeout` object as a string or a number. + */ + function clearTimeout(timeoutId: NodeJS.Timeout | string | number | undefined): void; + /** + * Schedules repeated execution of `callback` every `delay` milliseconds. + * + * When `delay` is larger than `2147483647` or less than `1`, the `delay` will be + * set to `1`. Non-integer delays are truncated to an integer. + * + * If `callback` is not a function, a `TypeError` will be thrown. + * + * This method has a custom variant for promises that is available using `timersPromises.setInterval()`. + * @since v0.0.1 + * @param callback The function to call when the timer elapses. + * @param [delay=1] The number of milliseconds to wait before calling the `callback`. + * @param args Optional arguments to pass when the `callback` is called. + * @return for use with {@link clearInterval} + */ + function setInterval( + callback: (...args: TArgs) => void, + ms?: number, + ...args: TArgs + ): NodeJS.Timeout; + // util.promisify no rest args compability + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + function setInterval(callback: (args: void) => void, ms?: number): NodeJS.Timeout; + namespace setInterval { + const __promisify__: typeof setIntervalPromise; + } + /** + * Cancels a `Timeout` object created by `setInterval()`. + * @since v0.0.1 + * @param timeout A `Timeout` object as returned by {@link setInterval} or the `primitive` of the `Timeout` object as a string or a number. + */ + function clearInterval(intervalId: NodeJS.Timeout | string | number | undefined): void; + /** + * Schedules the "immediate" execution of the `callback` after I/O events' + * callbacks. + * + * When multiple calls to `setImmediate()` are made, the `callback` functions are + * queued for execution in the order in which they are created. The entire callback + * queue is processed every event loop iteration. If an immediate timer is queued + * from inside an executing callback, that timer will not be triggered until the + * next event loop iteration. + * + * If `callback` is not a function, a `TypeError` will be thrown. + * + * This method has a custom variant for promises that is available using `timersPromises.setImmediate()`. + * @since v0.9.1 + * @param callback The function to call at the end of this turn of the Node.js `Event Loop` + * @param args Optional arguments to pass when the `callback` is called. + * @return for use with {@link clearImmediate} + */ + function setImmediate( + callback: (...args: TArgs) => void, + ...args: TArgs + ): NodeJS.Immediate; + // util.promisify no rest args compability + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + function setImmediate(callback: (args: void) => void): NodeJS.Immediate; + namespace setImmediate { + const __promisify__: typeof setImmediatePromise; + } + /** + * Cancels an `Immediate` object created by `setImmediate()`. + * @since v0.9.1 + * @param immediate An `Immediate` object as returned by {@link setImmediate}. + */ + function clearImmediate(immediateId: NodeJS.Immediate | undefined): void; + function queueMicrotask(callback: () => void): void; + } +} +declare module "node:timers" { + export * from "timers"; +} diff --git a/libcore/node_modules/@types/node/timers/promises.d.ts b/libcore/node_modules/@types/node/timers/promises.d.ts new file mode 100644 index 0000000..50cee98 --- /dev/null +++ b/libcore/node_modules/@types/node/timers/promises.d.ts @@ -0,0 +1,97 @@ +/** + * The `timers/promises` API provides an alternative set of timer functions + * that return `Promise` objects. The API is accessible via `require('node:timers/promises')`. + * + * ```js + * import { + * setTimeout, + * setImmediate, + * setInterval, + * } from 'timers/promises'; + * ``` + * @since v15.0.0 + */ +declare module "timers/promises" { + import { TimerOptions } from "node:timers"; + /** + * ```js + * import { + * setTimeout, + * } from 'timers/promises'; + * + * const res = await setTimeout(100, 'result'); + * + * console.log(res); // Prints 'result' + * ``` + * @since v15.0.0 + * @param [delay=1] The number of milliseconds to wait before fulfilling the promise. + * @param value A value with which the promise is fulfilled. + */ + function setTimeout(delay?: number, value?: T, options?: TimerOptions): Promise; + /** + * ```js + * import { + * setImmediate, + * } from 'timers/promises'; + * + * const res = await setImmediate('result'); + * + * console.log(res); // Prints 'result' + * ``` + * @since v15.0.0 + * @param value A value with which the promise is fulfilled. + */ + function setImmediate(value?: T, options?: TimerOptions): Promise; + /** + * Returns an async iterator that generates values in an interval of `delay` ms. + * If `ref` is `true`, you need to call `next()` of async iterator explicitly + * or implicitly to keep the event loop alive. + * + * ```js + * import { + * setInterval, + * } from 'timers/promises'; + * + * const interval = 100; + * for await (const startTime of setInterval(interval, Date.now())) { + * const now = Date.now(); + * console.log(now); + * if ((now - startTime) > 1000) + * break; + * } + * console.log(Date.now()); + * ``` + * @since v15.9.0 + */ + function setInterval(delay?: number, value?: T, options?: TimerOptions): AsyncIterable; + interface Scheduler { + /** + * An experimental API defined by the [Scheduling APIs](https://github.com/WICG/scheduling-apis) draft specification being developed as a standard Web Platform API. + * + * Calling `timersPromises.scheduler.wait(delay, options)` is roughly equivalent to calling `timersPromises.setTimeout(delay, undefined, options)` except that the `ref` + * option is not supported. + * + * ```js + * import { scheduler } from 'node:timers/promises'; + * + * await scheduler.wait(1000); // Wait one second before continuing + * ``` + * @since v16.14.0 + * @experimental + * @param [delay=1] The number of milliseconds to wait before fulfilling the promise. + */ + wait: (delay?: number, options?: Pick) => Promise; + /** + * An experimental API defined by the [Scheduling APIs](https://nodejs.org/docs/latest-v20.x/api/async_hooks.html#promise-execution-tracking) draft specification + * being developed as a standard Web Platform API. + * Calling `timersPromises.scheduler.yield()` is equivalent to calling `timersPromises.setImmediate()` with no arguments. + * @since v16.14.0 + * @experimental + */ + yield: () => Promise; + } + const scheduler: Scheduler; +} +declare module "node:timers/promises" { + export * from "timers/promises"; +} diff --git a/libcore/node_modules/@types/node/tls.d.ts b/libcore/node_modules/@types/node/tls.d.ts new file mode 100644 index 0000000..a409856 --- /dev/null +++ b/libcore/node_modules/@types/node/tls.d.ts @@ -0,0 +1,1220 @@ +/** + * The `node:tls` module provides an implementation of the Transport Layer Security + * (TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL. + * The module can be accessed using: + * + * ```js + * const tls = require('node:tls'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/tls.js) + */ +declare module "tls" { + import { X509Certificate } from "node:crypto"; + import * as net from "node:net"; + import * as stream from "stream"; + const CLIENT_RENEG_LIMIT: number; + const CLIENT_RENEG_WINDOW: number; + interface Certificate { + /** + * Country code. + */ + C: string; + /** + * Street. + */ + ST: string; + /** + * Locality. + */ + L: string; + /** + * Organization. + */ + O: string; + /** + * Organizational unit. + */ + OU: string; + /** + * Common name. + */ + CN: string; + } + interface PeerCertificate { + /** + * `true` if a Certificate Authority (CA), `false` otherwise. + * @since v18.13.0 + */ + ca: boolean; + /** + * The DER encoded X.509 certificate data. + */ + raw: Buffer; + /** + * The certificate subject. + */ + subject: Certificate; + /** + * The certificate issuer, described in the same terms as the `subject`. + */ + issuer: Certificate; + /** + * The date-time the certificate is valid from. + */ + valid_from: string; + /** + * The date-time the certificate is valid to. + */ + valid_to: string; + /** + * The certificate serial number, as a hex string. + */ + serialNumber: string; + /** + * The SHA-1 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint: string; + /** + * The SHA-256 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint256: string; + /** + * The SHA-512 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint512: string; + /** + * The extended key usage, a set of OIDs. + */ + ext_key_usage?: string[]; + /** + * A string containing concatenated names for the subject, + * an alternative to the `subject` names. + */ + subjectaltname?: string; + /** + * An array describing the AuthorityInfoAccess, used with OCSP. + */ + infoAccess?: NodeJS.Dict; + /** + * For RSA keys: The RSA bit size. + * + * For EC keys: The key size in bits. + */ + bits?: number; + /** + * The RSA exponent, as a string in hexadecimal number notation. + */ + exponent?: string; + /** + * The RSA modulus, as a hexadecimal string. + */ + modulus?: string; + /** + * The public key. + */ + pubkey?: Buffer; + /** + * The ASN.1 name of the OID of the elliptic curve. + * Well-known curves are identified by an OID. + * While it is unusual, it is possible that the curve + * is identified by its mathematical properties, + * in which case it will not have an OID. + */ + asn1Curve?: string; + /** + * The NIST name for the elliptic curve, if it has one + * (not all well-known curves have been assigned names by NIST). + */ + nistCurve?: string; + } + interface DetailedPeerCertificate extends PeerCertificate { + /** + * The issuer certificate object. + * For self-signed certificates, this may be a circular reference. + */ + issuerCertificate: DetailedPeerCertificate; + } + interface CipherNameAndProtocol { + /** + * The cipher name. + */ + name: string; + /** + * SSL/TLS protocol version. + */ + version: string; + /** + * IETF name for the cipher suite. + */ + standardName: string; + } + interface EphemeralKeyInfo { + /** + * The supported types are 'DH' and 'ECDH'. + */ + type: string; + /** + * The name property is available only when type is 'ECDH'. + */ + name?: string | undefined; + /** + * The size of parameter of an ephemeral key exchange. + */ + size: number; + } + interface KeyObject { + /** + * Private keys in PEM format. + */ + pem: string | Buffer; + /** + * Optional passphrase. + */ + passphrase?: string | undefined; + } + interface PxfObject { + /** + * PFX or PKCS12 encoded private key and certificate chain. + */ + buf: string | Buffer; + /** + * Optional passphrase. + */ + passphrase?: string | undefined; + } + interface TLSSocketOptions extends SecureContextOptions, CommonConnectionOptions { + /** + * If true the TLS socket will be instantiated in server-mode. + * Defaults to false. + */ + isServer?: boolean | undefined; + /** + * An optional net.Server instance. + */ + server?: net.Server | undefined; + /** + * An optional Buffer instance containing a TLS session. + */ + session?: Buffer | undefined; + /** + * If true, specifies that the OCSP status request extension will be + * added to the client hello and an 'OCSPResponse' event will be + * emitted on the socket before establishing a secure communication + */ + requestOCSP?: boolean | undefined; + } + /** + * Performs transparent encryption of written data and all required TLS + * negotiation. + * + * Instances of `tls.TLSSocket` implement the duplex `Stream` interface. + * + * Methods that return TLS connection metadata (e.g.{@link TLSSocket.getPeerCertificate}) will only return data while the + * connection is open. + * @since v0.11.4 + */ + class TLSSocket extends net.Socket { + /** + * Construct a new tls.TLSSocket object from an existing TCP socket. + */ + constructor(socket: net.Socket | stream.Duplex, options?: TLSSocketOptions); + /** + * This property is `true` if the peer certificate was signed by one of the CAs + * specified when creating the `tls.TLSSocket` instance, otherwise `false`. + * @since v0.11.4 + */ + authorized: boolean; + /** + * Returns the reason why the peer's certificate was not been verified. This + * property is set only when `tlsSocket.authorized === false`. + * @since v0.11.4 + */ + authorizationError: Error; + /** + * Always returns `true`. This may be used to distinguish TLS sockets from regular`net.Socket` instances. + * @since v0.11.4 + */ + encrypted: true; + /** + * String containing the selected ALPN protocol. + * Before a handshake has completed, this value is always null. + * When a handshake is completed but not ALPN protocol was selected, tlsSocket.alpnProtocol equals false. + */ + alpnProtocol: string | false | null; + /** + * Returns an object representing the local certificate. The returned object has + * some properties corresponding to the fields of the certificate. + * + * See {@link TLSSocket.getPeerCertificate} for an example of the certificate + * structure. + * + * If there is no local certificate, an empty object will be returned. If the + * socket has been destroyed, `null` will be returned. + * @since v11.2.0 + */ + getCertificate(): PeerCertificate | object | null; + /** + * Returns an object containing information on the negotiated cipher suite. + * + * For example, a TLSv1.2 protocol with AES256-SHA cipher: + * + * ```json + * { + * "name": "AES256-SHA", + * "standardName": "TLS_RSA_WITH_AES_256_CBC_SHA", + * "version": "SSLv3" + * } + * ``` + * + * See [SSL\_CIPHER\_get\_name](https://www.openssl.org/docs/man1.1.1/man3/SSL_CIPHER_get_name.html) for more information. + * @since v0.11.4 + */ + getCipher(): CipherNameAndProtocol; + /** + * Returns an object representing the type, name, and size of parameter of + * an ephemeral key exchange in `perfect forward secrecy` on a client + * connection. It returns an empty object when the key exchange is not + * ephemeral. As this is only supported on a client socket; `null` is returned + * if called on a server socket. The supported types are `'DH'` and `'ECDH'`. The `name` property is available only when type is `'ECDH'`. + * + * For example: `{ type: 'ECDH', name: 'prime256v1', size: 256 }`. + * @since v5.0.0 + */ + getEphemeralKeyInfo(): EphemeralKeyInfo | object | null; + /** + * As the `Finished` messages are message digests of the complete handshake + * (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can + * be used for external authentication procedures when the authentication + * provided by SSL/TLS is not desired or is not enough. + * + * Corresponds to the `SSL_get_finished` routine in OpenSSL and may be used + * to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929). + * @since v9.9.0 + * @return The latest `Finished` message that has been sent to the socket as part of a SSL/TLS handshake, or `undefined` if no `Finished` message has been sent yet. + */ + getFinished(): Buffer | undefined; + /** + * Returns an object representing the peer's certificate. If the peer does not + * provide a certificate, an empty object will be returned. If the socket has been + * destroyed, `null` will be returned. + * + * If the full certificate chain was requested, each certificate will include an`issuerCertificate` property containing an object representing its issuer's + * certificate. + * @since v0.11.4 + * @param detailed Include the full certificate chain if `true`, otherwise include just the peer's certificate. + * @return A certificate object. + */ + getPeerCertificate(detailed: true): DetailedPeerCertificate; + getPeerCertificate(detailed?: false): PeerCertificate; + getPeerCertificate(detailed?: boolean): PeerCertificate | DetailedPeerCertificate; + /** + * As the `Finished` messages are message digests of the complete handshake + * (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can + * be used for external authentication procedures when the authentication + * provided by SSL/TLS is not desired or is not enough. + * + * Corresponds to the `SSL_get_peer_finished` routine in OpenSSL and may be used + * to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929). + * @since v9.9.0 + * @return The latest `Finished` message that is expected or has actually been received from the socket as part of a SSL/TLS handshake, or `undefined` if there is no `Finished` message so + * far. + */ + getPeerFinished(): Buffer | undefined; + /** + * Returns a string containing the negotiated SSL/TLS protocol version of the + * current connection. The value `'unknown'` will be returned for connected + * sockets that have not completed the handshaking process. The value `null` will + * be returned for server sockets or disconnected client sockets. + * + * Protocol versions are: + * + * * `'SSLv3'` + * * `'TLSv1'` + * * `'TLSv1.1'` + * * `'TLSv1.2'` + * * `'TLSv1.3'` + * + * See the OpenSSL [`SSL_get_version`](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_version.html) documentation for more information. + * @since v5.7.0 + */ + getProtocol(): string | null; + /** + * Returns the TLS session data or `undefined` if no session was + * negotiated. On the client, the data can be provided to the `session` option of {@link connect} to resume the connection. On the server, it may be useful + * for debugging. + * + * See `Session Resumption` for more information. + * + * Note: `getSession()` works only for TLSv1.2 and below. For TLSv1.3, applications + * must use the `'session'` event (it also works for TLSv1.2 and below). + * @since v0.11.4 + */ + getSession(): Buffer | undefined; + /** + * See [SSL\_get\_shared\_sigalgs](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_shared_sigalgs.html) for more information. + * @since v12.11.0 + * @return List of signature algorithms shared between the server and the client in the order of decreasing preference. + */ + getSharedSigalgs(): string[]; + /** + * For a client, returns the TLS session ticket if one is available, or`undefined`. For a server, always returns `undefined`. + * + * It may be useful for debugging. + * + * See `Session Resumption` for more information. + * @since v0.11.4 + */ + getTLSTicket(): Buffer | undefined; + /** + * See `Session Resumption` for more information. + * @since v0.5.6 + * @return `true` if the session was reused, `false` otherwise. + */ + isSessionReused(): boolean; + /** + * The `tlsSocket.renegotiate()` method initiates a TLS renegotiation process. + * Upon completion, the `callback` function will be passed a single argument + * that is either an `Error` (if the request failed) or `null`. + * + * This method can be used to request a peer's certificate after the secure + * connection has been established. + * + * When running as the server, the socket will be destroyed with an error after `handshakeTimeout` timeout. + * + * For TLSv1.3, renegotiation cannot be initiated, it is not supported by the + * protocol. + * @since v0.11.8 + * @param callback If `renegotiate()` returned `true`, callback is attached once to the `'secure'` event. If `renegotiate()` returned `false`, `callback` will be called in the next tick with + * an error, unless the `tlsSocket` has been destroyed, in which case `callback` will not be called at all. + * @return `true` if renegotiation was initiated, `false` otherwise. + */ + renegotiate( + options: { + rejectUnauthorized?: boolean | undefined; + requestCert?: boolean | undefined; + }, + callback: (err: Error | null) => void, + ): undefined | boolean; + /** + * The `tlsSocket.setMaxSendFragment()` method sets the maximum TLS fragment size. + * Returns `true` if setting the limit succeeded; `false` otherwise. + * + * Smaller fragment sizes decrease the buffering latency on the client: larger + * fragments are buffered by the TLS layer until the entire fragment is received + * and its integrity is verified; large fragments can span multiple roundtrips + * and their processing can be delayed due to packet loss or reordering. However, + * smaller fragments add extra TLS framing bytes and CPU overhead, which may + * decrease overall server throughput. + * @since v0.11.11 + * @param [size=16384] The maximum TLS fragment size. The maximum value is `16384`. + */ + setMaxSendFragment(size: number): boolean; + /** + * Disables TLS renegotiation for this `TLSSocket` instance. Once called, attempts + * to renegotiate will trigger an `'error'` event on the `TLSSocket`. + * @since v8.4.0 + */ + disableRenegotiation(): void; + /** + * When enabled, TLS packet trace information is written to `stderr`. This can be + * used to debug TLS connection problems. + * + * The format of the output is identical to the output of`openssl s_client -trace` or `openssl s_server -trace`. While it is produced by + * OpenSSL's `SSL_trace()` function, the format is undocumented, can change + * without notice, and should not be relied on. + * @since v12.2.0 + */ + enableTrace(): void; + /** + * Returns the peer certificate as an `X509Certificate` object. + * + * If there is no peer certificate, or the socket has been destroyed,`undefined` will be returned. + * @since v15.9.0 + */ + getPeerX509Certificate(): X509Certificate | undefined; + /** + * Returns the local certificate as an `X509Certificate` object. + * + * If there is no local certificate, or the socket has been destroyed,`undefined` will be returned. + * @since v15.9.0 + */ + getX509Certificate(): X509Certificate | undefined; + /** + * Keying material is used for validations to prevent different kind of attacks in + * network protocols, for example in the specifications of IEEE 802.1X. + * + * Example + * + * ```js + * const keyingMaterial = tlsSocket.exportKeyingMaterial( + * 128, + * 'client finished'); + * + * /* + * Example return value of keyingMaterial: + * + * + * ``` + * + * See the OpenSSL [`SSL_export_keying_material`](https://www.openssl.org/docs/man1.1.1/man3/SSL_export_keying_material.html) documentation for more + * information. + * @since v13.10.0, v12.17.0 + * @param length number of bytes to retrieve from keying material + * @param label an application specific label, typically this will be a value from the [IANA Exporter Label + * Registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#exporter-labels). + * @param context Optionally provide a context. + * @return requested bytes of the keying material + */ + exportKeyingMaterial(length: number, label: string, context: Buffer): Buffer; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + addListener(event: "secureConnect", listener: () => void): this; + addListener(event: "session", listener: (session: Buffer) => void): this; + addListener(event: "keylog", listener: (line: Buffer) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "OCSPResponse", response: Buffer): boolean; + emit(event: "secureConnect"): boolean; + emit(event: "session", session: Buffer): boolean; + emit(event: "keylog", line: Buffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "OCSPResponse", listener: (response: Buffer) => void): this; + on(event: "secureConnect", listener: () => void): this; + on(event: "session", listener: (session: Buffer) => void): this; + on(event: "keylog", listener: (line: Buffer) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "OCSPResponse", listener: (response: Buffer) => void): this; + once(event: "secureConnect", listener: () => void): this; + once(event: "session", listener: (session: Buffer) => void): this; + once(event: "keylog", listener: (line: Buffer) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + prependListener(event: "secureConnect", listener: () => void): this; + prependListener(event: "session", listener: (session: Buffer) => void): this; + prependListener(event: "keylog", listener: (line: Buffer) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + prependOnceListener(event: "secureConnect", listener: () => void): this; + prependOnceListener(event: "session", listener: (session: Buffer) => void): this; + prependOnceListener(event: "keylog", listener: (line: Buffer) => void): this; + } + interface CommonConnectionOptions { + /** + * An optional TLS context object from tls.createSecureContext() + */ + secureContext?: SecureContext | undefined; + /** + * When enabled, TLS packet trace information is written to `stderr`. This can be + * used to debug TLS connection problems. + * @default false + */ + enableTrace?: boolean | undefined; + /** + * If true the server will request a certificate from clients that + * connect and attempt to verify that certificate. Defaults to + * false. + */ + requestCert?: boolean | undefined; + /** + * An array of strings or a Buffer naming possible ALPN protocols. + * (Protocols should be ordered by their priority.) + */ + ALPNProtocols?: string[] | Uint8Array[] | Uint8Array | undefined; + /** + * SNICallback(servername, cb) A function that will be + * called if the client supports SNI TLS extension. Two arguments + * will be passed when called: servername and cb. SNICallback should + * invoke cb(null, ctx), where ctx is a SecureContext instance. + * (tls.createSecureContext(...) can be used to get a proper + * SecureContext.) If SNICallback wasn't provided the default callback + * with high-level API will be used (see below). + */ + SNICallback?: ((servername: string, cb: (err: Error | null, ctx?: SecureContext) => void) => void) | undefined; + /** + * If true the server will reject any connection which is not + * authorized with the list of supplied CAs. This option only has an + * effect if requestCert is true. + * @default true + */ + rejectUnauthorized?: boolean | undefined; + } + interface TlsOptions extends SecureContextOptions, CommonConnectionOptions, net.ServerOpts { + /** + * Abort the connection if the SSL/TLS handshake does not finish in the + * specified number of milliseconds. A 'tlsClientError' is emitted on + * the tls.Server object whenever a handshake times out. Default: + * 120000 (120 seconds). + */ + handshakeTimeout?: number | undefined; + /** + * The number of seconds after which a TLS session created by the + * server will no longer be resumable. See Session Resumption for more + * information. Default: 300. + */ + sessionTimeout?: number | undefined; + /** + * 48-bytes of cryptographically strong pseudo-random data. + */ + ticketKeys?: Buffer | undefined; + /** + * @param socket + * @param identity identity parameter sent from the client. + * @return pre-shared key that must either be + * a buffer or `null` to stop the negotiation process. Returned PSK must be + * compatible with the selected cipher's digest. + * + * When negotiating TLS-PSK (pre-shared keys), this function is called + * with the identity provided by the client. + * If the return value is `null` the negotiation process will stop and an + * "unknown_psk_identity" alert message will be sent to the other party. + * If the server wishes to hide the fact that the PSK identity was not known, + * the callback must provide some random data as `psk` to make the connection + * fail with "decrypt_error" before negotiation is finished. + * PSK ciphers are disabled by default, and using TLS-PSK thus + * requires explicitly specifying a cipher suite with the `ciphers` option. + * More information can be found in the RFC 4279. + */ + pskCallback?(socket: TLSSocket, identity: string): DataView | NodeJS.TypedArray | null; + /** + * hint to send to a client to help + * with selecting the identity during TLS-PSK negotiation. Will be ignored + * in TLS 1.3. Upon failing to set pskIdentityHint `tlsClientError` will be + * emitted with `ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED` code. + */ + pskIdentityHint?: string | undefined; + } + interface PSKCallbackNegotation { + psk: DataView | NodeJS.TypedArray; + identity: string; + } + interface ConnectionOptions extends SecureContextOptions, CommonConnectionOptions { + host?: string | undefined; + port?: number | undefined; + path?: string | undefined; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored. + socket?: stream.Duplex | undefined; // Establish secure connection on a given socket rather than creating a new socket + checkServerIdentity?: typeof checkServerIdentity | undefined; + servername?: string | undefined; // SNI TLS Extension + session?: Buffer | undefined; + minDHSize?: number | undefined; + lookup?: net.LookupFunction | undefined; + timeout?: number | undefined; + /** + * When negotiating TLS-PSK (pre-shared keys), this function is called + * with optional identity `hint` provided by the server or `null` + * in case of TLS 1.3 where `hint` was removed. + * It will be necessary to provide a custom `tls.checkServerIdentity()` + * for the connection as the default one will try to check hostname/IP + * of the server against the certificate but that's not applicable for PSK + * because there won't be a certificate present. + * More information can be found in the RFC 4279. + * + * @param hint message sent from the server to help client + * decide which identity to use during negotiation. + * Always `null` if TLS 1.3 is used. + * @returns Return `null` to stop the negotiation process. `psk` must be + * compatible with the selected cipher's digest. + * `identity` must use UTF-8 encoding. + */ + pskCallback?(hint: string | null): PSKCallbackNegotation | null; + } + /** + * Accepts encrypted connections using TLS or SSL. + * @since v0.3.2 + */ + class Server extends net.Server { + constructor(secureConnectionListener?: (socket: TLSSocket) => void); + constructor(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void); + /** + * The `server.addContext()` method adds a secure context that will be used if + * the client request's SNI name matches the supplied `hostname` (or wildcard). + * + * When there are multiple matching contexts, the most recently added one is + * used. + * @since v0.5.3 + * @param hostname A SNI host name or wildcard (e.g. `'*'`) + * @param context An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc), or a TLS context object created + * with {@link createSecureContext} itself. + */ + addContext(hostname: string, context: SecureContextOptions): void; + /** + * Returns the session ticket keys. + * + * See `Session Resumption` for more information. + * @since v3.0.0 + * @return A 48-byte buffer containing the session ticket keys. + */ + getTicketKeys(): Buffer; + /** + * The `server.setSecureContext()` method replaces the secure context of an + * existing server. Existing connections to the server are not interrupted. + * @since v11.0.0 + * @param options An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc). + */ + setSecureContext(options: SecureContextOptions): void; + /** + * Sets the session ticket keys. + * + * Changes to the ticket keys are effective only for future server connections. + * Existing or currently pending server connections will use the previous keys. + * + * See `Session Resumption` for more information. + * @since v3.0.0 + * @param keys A 48-byte buffer containing the session ticket keys. + */ + setTicketKeys(keys: Buffer): void; + /** + * events.EventEmitter + * 1. tlsClientError + * 2. newSession + * 3. OCSPRequest + * 4. resumeSession + * 5. secureConnection + * 6. keylog + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + addListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, + ): this; + addListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + addListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, + ): this; + addListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + addListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "tlsClientError", err: Error, tlsSocket: TLSSocket): boolean; + emit(event: "newSession", sessionId: Buffer, sessionData: Buffer, callback: () => void): boolean; + emit( + event: "OCSPRequest", + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ): boolean; + emit( + event: "resumeSession", + sessionId: Buffer, + callback: (err: Error | null, sessionData: Buffer | null) => void, + ): boolean; + emit(event: "secureConnection", tlsSocket: TLSSocket): boolean; + emit(event: "keylog", line: Buffer, tlsSocket: TLSSocket): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + on(event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void): this; + on( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + on( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, + ): this; + on(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + on(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + once( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, + ): this; + once( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + once( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, + ): this; + once(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + once(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, + ): this; + prependListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + prependListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, + ): this; + prependListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + prependListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependOnceListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, + ): this; + prependOnceListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + prependOnceListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, + ): this; + prependOnceListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + } + /** + * @deprecated since v0.11.3 Use `tls.TLSSocket` instead. + */ + interface SecurePair { + encrypted: TLSSocket; + cleartext: TLSSocket; + } + type SecureVersion = "TLSv1.3" | "TLSv1.2" | "TLSv1.1" | "TLSv1"; + interface SecureContextOptions { + /** + * If set, this will be called when a client opens a connection using the ALPN extension. + * One argument will be passed to the callback: an object containing `servername` and `protocols` fields, + * respectively containing the server name from the SNI extension (if any) and an array of + * ALPN protocol name strings. The callback must return either one of the strings listed in `protocols`, + * which will be returned to the client as the selected ALPN protocol, or `undefined`, + * to reject the connection with a fatal alert. If a string is returned that does not match one of + * the client's ALPN protocols, an error will be thrown. + * This option cannot be used with the `ALPNProtocols` option, and setting both options will throw an error. + */ + ALPNCallback?: ((arg: { servername: string; protocols: string[] }) => string | undefined) | undefined; + /** + * Optionally override the trusted CA certificates. Default is to trust + * the well-known CAs curated by Mozilla. Mozilla's CAs are completely + * replaced when CAs are explicitly specified using this option. + */ + ca?: string | Buffer | Array | undefined; + /** + * Cert chains in PEM format. One cert chain should be provided per + * private key. Each cert chain should consist of the PEM formatted + * certificate for a provided private key, followed by the PEM + * formatted intermediate certificates (if any), in order, and not + * including the root CA (the root CA must be pre-known to the peer, + * see ca). When providing multiple cert chains, they do not have to + * be in the same order as their private keys in key. If the + * intermediate certificates are not provided, the peer will not be + * able to validate the certificate, and the handshake will fail. + */ + cert?: string | Buffer | Array | undefined; + /** + * Colon-separated list of supported signature algorithms. The list + * can contain digest algorithms (SHA256, MD5 etc.), public key + * algorithms (RSA-PSS, ECDSA etc.), combination of both (e.g + * 'RSA+SHA384') or TLS v1.3 scheme names (e.g. rsa_pss_pss_sha512). + */ + sigalgs?: string | undefined; + /** + * Cipher suite specification, replacing the default. For more + * information, see modifying the default cipher suite. Permitted + * ciphers can be obtained via tls.getCiphers(). Cipher names must be + * uppercased in order for OpenSSL to accept them. + */ + ciphers?: string | undefined; + /** + * Name of an OpenSSL engine which can provide the client certificate. + * @deprecated + */ + clientCertEngine?: string | undefined; + /** + * PEM formatted CRLs (Certificate Revocation Lists). + */ + crl?: string | Buffer | Array | undefined; + /** + * `'auto'` or custom Diffie-Hellman parameters, required for non-ECDHE perfect forward secrecy. + * If omitted or invalid, the parameters are silently discarded and DHE ciphers will not be available. + * ECDHE-based perfect forward secrecy will still be available. + */ + dhparam?: string | Buffer | undefined; + /** + * A string describing a named curve or a colon separated list of curve + * NIDs or names, for example P-521:P-384:P-256, to use for ECDH key + * agreement. Set to auto to select the curve automatically. Use + * crypto.getCurves() to obtain a list of available curve names. On + * recent releases, openssl ecparam -list_curves will also display the + * name and description of each available elliptic curve. Default: + * tls.DEFAULT_ECDH_CURVE. + */ + ecdhCurve?: string | undefined; + /** + * Attempt to use the server's cipher suite preferences instead of the + * client's. When true, causes SSL_OP_CIPHER_SERVER_PREFERENCE to be + * set in secureOptions + */ + honorCipherOrder?: boolean | undefined; + /** + * Private keys in PEM format. PEM allows the option of private keys + * being encrypted. Encrypted keys will be decrypted with + * options.passphrase. Multiple keys using different algorithms can be + * provided either as an array of unencrypted key strings or buffers, + * or an array of objects in the form {pem: [, + * passphrase: ]}. The object form can only occur in an array. + * object.passphrase is optional. Encrypted keys will be decrypted with + * object.passphrase if provided, or options.passphrase if it is not. + */ + key?: string | Buffer | Array | undefined; + /** + * Name of an OpenSSL engine to get private key from. Should be used + * together with privateKeyIdentifier. + * @deprecated + */ + privateKeyEngine?: string | undefined; + /** + * Identifier of a private key managed by an OpenSSL engine. Should be + * used together with privateKeyEngine. Should not be set together with + * key, because both options define a private key in different ways. + * @deprecated + */ + privateKeyIdentifier?: string | undefined; + /** + * Optionally set the maximum TLS version to allow. One + * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the + * `secureProtocol` option, use one or the other. + * **Default:** `'TLSv1.3'`, unless changed using CLI options. Using + * `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using `--tls-max-v1.3` sets the default to + * `'TLSv1.3'`. If multiple of the options are provided, the highest maximum is used. + */ + maxVersion?: SecureVersion | undefined; + /** + * Optionally set the minimum TLS version to allow. One + * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the + * `secureProtocol` option, use one or the other. It is not recommended to use + * less than TLSv1.2, but it may be required for interoperability. + * **Default:** `'TLSv1.2'`, unless changed using CLI options. Using + * `--tls-v1.0` sets the default to `'TLSv1'`. Using `--tls-v1.1` sets the default to + * `'TLSv1.1'`. Using `--tls-min-v1.3` sets the default to + * 'TLSv1.3'. If multiple of the options are provided, the lowest minimum is used. + */ + minVersion?: SecureVersion | undefined; + /** + * Shared passphrase used for a single private key and/or a PFX. + */ + passphrase?: string | undefined; + /** + * PFX or PKCS12 encoded private key and certificate chain. pfx is an + * alternative to providing key and cert individually. PFX is usually + * encrypted, if it is, passphrase will be used to decrypt it. Multiple + * PFX can be provided either as an array of unencrypted PFX buffers, + * or an array of objects in the form {buf: [, + * passphrase: ]}. The object form can only occur in an array. + * object.passphrase is optional. Encrypted PFX will be decrypted with + * object.passphrase if provided, or options.passphrase if it is not. + */ + pfx?: string | Buffer | Array | undefined; + /** + * Optionally affect the OpenSSL protocol behavior, which is not + * usually necessary. This should be used carefully if at all! Value is + * a numeric bitmask of the SSL_OP_* options from OpenSSL Options + */ + secureOptions?: number | undefined; // Value is a numeric bitmask of the `SSL_OP_*` options + /** + * Legacy mechanism to select the TLS protocol version to use, it does + * not support independent control of the minimum and maximum version, + * and does not support limiting the protocol to TLSv1.3. Use + * minVersion and maxVersion instead. The possible values are listed as + * SSL_METHODS, use the function names as strings. For example, use + * 'TLSv1_1_method' to force TLS version 1.1, or 'TLS_method' to allow + * any TLS protocol version up to TLSv1.3. It is not recommended to use + * TLS versions less than 1.2, but it may be required for + * interoperability. Default: none, see minVersion. + */ + secureProtocol?: string | undefined; + /** + * Opaque identifier used by servers to ensure session state is not + * shared between applications. Unused by clients. + */ + sessionIdContext?: string | undefined; + /** + * 48-bytes of cryptographically strong pseudo-random data. + * See Session Resumption for more information. + */ + ticketKeys?: Buffer | undefined; + /** + * The number of seconds after which a TLS session created by the + * server will no longer be resumable. See Session Resumption for more + * information. Default: 300. + */ + sessionTimeout?: number | undefined; + } + interface SecureContext { + context: any; + } + /** + * Verifies the certificate `cert` is issued to `hostname`. + * + * Returns [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object, populating it with `reason`, `host`, and `cert` on + * failure. On success, returns [undefined](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type). + * + * This function is intended to be used in combination with the`checkServerIdentity` option that can be passed to {@link connect} and as + * such operates on a `certificate object`. For other purposes, consider using `x509.checkHost()` instead. + * + * This function can be overwritten by providing an alternative function as the `options.checkServerIdentity` option that is passed to `tls.connect()`. The + * overwriting function can call `tls.checkServerIdentity()` of course, to augment + * the checks done with additional verification. + * + * This function is only called if the certificate passed all other checks, such as + * being issued by trusted CA (`options.ca`). + * + * Earlier versions of Node.js incorrectly accepted certificates for a given`hostname` if a matching `uniformResourceIdentifier` subject alternative name + * was present (see [CVE-2021-44531](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44531)). Applications that wish to accept`uniformResourceIdentifier` subject alternative names can use + * a custom `options.checkServerIdentity` function that implements the desired behavior. + * @since v0.8.4 + * @param hostname The host name or IP address to verify the certificate against. + * @param cert A `certificate object` representing the peer's certificate. + */ + function checkServerIdentity(hostname: string, cert: PeerCertificate): Error | undefined; + /** + * Creates a new {@link Server}. The `secureConnectionListener`, if provided, is + * automatically set as a listener for the `'secureConnection'` event. + * + * The `ticketKeys` options is automatically shared between `node:cluster` module + * workers. + * + * The following illustrates a simple echo server: + * + * ```js + * const tls = require('node:tls'); + * const fs = require('node:fs'); + * + * const options = { + * key: fs.readFileSync('server-key.pem'), + * cert: fs.readFileSync('server-cert.pem'), + * + * // This is necessary only if using client certificate authentication. + * requestCert: true, + * + * // This is necessary only if the client uses a self-signed certificate. + * ca: [ fs.readFileSync('client-cert.pem') ], + * }; + * + * const server = tls.createServer(options, (socket) => { + * console.log('server connected', + * socket.authorized ? 'authorized' : 'unauthorized'); + * socket.write('welcome!\n'); + * socket.setEncoding('utf8'); + * socket.pipe(socket); + * }); + * server.listen(8000, () => { + * console.log('server bound'); + * }); + * ``` + * + * The server can be tested by connecting to it using the example client from {@link connect}. + * @since v0.3.2 + */ + function createServer(secureConnectionListener?: (socket: TLSSocket) => void): Server; + function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server; + /** + * The `callback` function, if specified, will be added as a listener for the `'secureConnect'` event. + * + * `tls.connect()` returns a {@link TLSSocket} object. + * + * Unlike the `https` API, `tls.connect()` does not enable the + * SNI (Server Name Indication) extension by default, which may cause some + * servers to return an incorrect certificate or reject the connection + * altogether. To enable SNI, set the `servername` option in addition + * to `host`. + * + * The following illustrates a client for the echo server example from {@link createServer}: + * + * ```js + * // Assumes an echo server that is listening on port 8000. + * const tls = require('node:tls'); + * const fs = require('node:fs'); + * + * const options = { + * // Necessary only if the server requires client certificate authentication. + * key: fs.readFileSync('client-key.pem'), + * cert: fs.readFileSync('client-cert.pem'), + * + * // Necessary only if the server uses a self-signed certificate. + * ca: [ fs.readFileSync('server-cert.pem') ], + * + * // Necessary only if the server's cert isn't for "localhost". + * checkServerIdentity: () => { return null; }, + * }; + * + * const socket = tls.connect(8000, options, () => { + * console.log('client connected', + * socket.authorized ? 'authorized' : 'unauthorized'); + * process.stdin.pipe(socket); + * process.stdin.resume(); + * }); + * socket.setEncoding('utf8'); + * socket.on('data', (data) => { + * console.log(data); + * }); + * socket.on('end', () => { + * console.log('server ends connection'); + * }); + * ``` + * @since v0.11.3 + */ + function connect(options: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + function connect( + port: number, + host?: string, + options?: ConnectionOptions, + secureConnectListener?: () => void, + ): TLSSocket; + function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + /** + * Creates a new secure pair object with two streams, one of which reads and writes + * the encrypted data and the other of which reads and writes the cleartext data. + * Generally, the encrypted stream is piped to/from an incoming encrypted data + * stream and the cleartext one is used as a replacement for the initial encrypted + * stream. + * + * `tls.createSecurePair()` returns a `tls.SecurePair` object with `cleartext` and `encrypted` stream properties. + * + * Using `cleartext` has the same API as {@link TLSSocket}. + * + * The `tls.createSecurePair()` method is now deprecated in favor of`tls.TLSSocket()`. For example, the code: + * + * ```js + * pair = tls.createSecurePair(// ... ); + * pair.encrypted.pipe(socket); + * socket.pipe(pair.encrypted); + * ``` + * + * can be replaced by: + * + * ```js + * secureSocket = tls.TLSSocket(socket, options); + * ``` + * + * where `secureSocket` has the same API as `pair.cleartext`. + * @since v0.3.2 + * @deprecated Since v0.11.3 - Use {@link TLSSocket} instead. + * @param context A secure context object as returned by `tls.createSecureContext()` + * @param isServer `true` to specify that this TLS connection should be opened as a server. + * @param requestCert `true` to specify whether a server should request a certificate from a connecting client. Only applies when `isServer` is `true`. + * @param rejectUnauthorized If not `false` a server automatically reject clients with invalid certificates. Only applies when `isServer` is `true`. + */ + function createSecurePair( + context?: SecureContext, + isServer?: boolean, + requestCert?: boolean, + rejectUnauthorized?: boolean, + ): SecurePair; + /** + * `{@link createServer}` sets the default value of the `honorCipherOrder` option + * to `true`, other APIs that create secure contexts leave it unset. + * + * `{@link createServer}` uses a 128 bit truncated SHA1 hash value generated + * from `process.argv` as the default value of the `sessionIdContext` option, other + * APIs that create secure contexts have no default value. + * + * The `tls.createSecureContext()` method creates a `SecureContext` object. It is + * usable as an argument to several `tls` APIs, such as `server.addContext()`, + * but has no public methods. The {@link Server} constructor and the {@link createServer} method do not support the `secureContext` option. + * + * A key is _required_ for ciphers that use certificates. Either `key` or `pfx` can be used to provide it. + * + * If the `ca` option is not given, then Node.js will default to using [Mozilla's publicly trusted list of + * CAs](https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt). + * + * Custom DHE parameters are discouraged in favor of the new `dhparam: 'auto' `option. When set to `'auto'`, well-known DHE parameters of sufficient strength + * will be selected automatically. Otherwise, if necessary, `openssl dhparam` can + * be used to create custom parameters. The key length must be greater than or + * equal to 1024 bits or else an error will be thrown. Although 1024 bits is + * permissible, use 2048 bits or larger for stronger security. + * @since v0.11.13 + */ + function createSecureContext(options?: SecureContextOptions): SecureContext; + /** + * Returns an array with the names of the supported TLS ciphers. The names are + * lower-case for historical reasons, but must be uppercased to be used in + * the `ciphers` option of `{@link createSecureContext}`. + * + * Not all supported ciphers are enabled by default. See + * [Modifying the default TLS cipher suite](https://nodejs.org/docs/latest-v22.x/api/tls.html#modifying-the-default-tls-cipher-suite). + * + * Cipher names that start with `'tls_'` are for TLSv1.3, all the others are for + * TLSv1.2 and below. + * + * ```js + * console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...] + * ``` + * @since v0.10.2 + */ + function getCiphers(): string[]; + /** + * The default curve name to use for ECDH key agreement in a tls server. + * The default value is `'auto'`. See `{@link createSecureContext()}` for further + * information. + * @since v0.11.13 + */ + let DEFAULT_ECDH_CURVE: string; + /** + * The default value of the `maxVersion` option of `{@link createSecureContext()}`. + * It can be assigned any of the supported TLS protocol versions, + * `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. **Default:** `'TLSv1.3'`, unless + * changed using CLI options. Using `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using + * `--tls-max-v1.3` sets the default to `'TLSv1.3'`. If multiple of the options + * are provided, the highest maximum is used. + * @since v11.4.0 + */ + let DEFAULT_MAX_VERSION: SecureVersion; + /** + * The default value of the `minVersion` option of `{@link createSecureContext()}`. + * It can be assigned any of the supported TLS protocol versions, + * `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. **Default:** `'TLSv1.2'`, unless + * changed using CLI options. Using `--tls-min-v1.0` sets the default to + * `'TLSv1'`. Using `--tls-min-v1.1` sets the default to `'TLSv1.1'`. Using + * `--tls-min-v1.3` sets the default to `'TLSv1.3'`. If multiple of the options + * are provided, the lowest minimum is used. + * @since v11.4.0 + */ + let DEFAULT_MIN_VERSION: SecureVersion; + /** + * The default value of the `ciphers` option of `{@link createSecureContext()}`. + * It can be assigned any of the supported OpenSSL ciphers. + * Defaults to the content of `crypto.constants.defaultCoreCipherList`, unless + * changed using CLI options using `--tls-default-ciphers`. + * @since v19.8.0 + */ + let DEFAULT_CIPHERS: string; + /** + * An immutable array of strings representing the root certificates (in PEM format) + * from the bundled Mozilla CA store as supplied by the current Node.js version. + * + * The bundled CA store, as supplied by Node.js, is a snapshot of Mozilla CA store + * that is fixed at release time. It is identical on all supported platforms. + * @since v12.3.0 + */ + const rootCertificates: readonly string[]; +} +declare module "node:tls" { + export * from "tls"; +} diff --git a/libcore/node_modules/@types/node/trace_events.d.ts b/libcore/node_modules/@types/node/trace_events.d.ts new file mode 100644 index 0000000..f339455 --- /dev/null +++ b/libcore/node_modules/@types/node/trace_events.d.ts @@ -0,0 +1,197 @@ +/** + * The `node:trace_events` module provides a mechanism to centralize tracing information + * generated by V8, Node.js core, and userspace code. + * + * Tracing can be enabled with the `--trace-event-categories` command-line flag + * or by using the `trace_events` module. The `--trace-event-categories` flag + * accepts a list of comma-separated category names. + * + * The available categories are: + * + * * `node`: An empty placeholder. + * * `node.async_hooks`: Enables capture of detailed [`async_hooks`](https://nodejs.org/docs/latest-v22.x/api/async_hooks.html) trace data. + * The [`async_hooks`](https://nodejs.org/docs/latest-v22.x/api/async_hooks.html) events have a unique `asyncId` and a special `triggerId` `triggerAsyncId` property. + * * `node.bootstrap`: Enables capture of Node.js bootstrap milestones. + * * `node.console`: Enables capture of `console.time()` and `console.count()` output. + * * `node.threadpoolwork.sync`: Enables capture of trace data for threadpool synchronous operations, such as `blob`, `zlib`, `crypto` and `node_api`. + * * `node.threadpoolwork.async`: Enables capture of trace data for threadpool asynchronous operations, such as `blob`, `zlib`, `crypto` and `node_api`. + * * `node.dns.native`: Enables capture of trace data for DNS queries. + * * `node.net.native`: Enables capture of trace data for network. + * * `node.environment`: Enables capture of Node.js Environment milestones. + * * `node.fs.sync`: Enables capture of trace data for file system sync methods. + * * `node.fs_dir.sync`: Enables capture of trace data for file system sync directory methods. + * * `node.fs.async`: Enables capture of trace data for file system async methods. + * * `node.fs_dir.async`: Enables capture of trace data for file system async directory methods. + * * `node.perf`: Enables capture of [Performance API](https://nodejs.org/docs/latest-v22.x/api/perf_hooks.html) measurements. + * * `node.perf.usertiming`: Enables capture of only Performance API User Timing + * measures and marks. + * * `node.perf.timerify`: Enables capture of only Performance API timerify + * measurements. + * * `node.promises.rejections`: Enables capture of trace data tracking the number + * of unhandled Promise rejections and handled-after-rejections. + * * `node.vm.script`: Enables capture of trace data for the `node:vm` module's `runInNewContext()`, `runInContext()`, and `runInThisContext()` methods. + * * `v8`: The [V8](https://nodejs.org/docs/latest-v22.x/api/v8.html) events are GC, compiling, and execution related. + * * `node.http`: Enables capture of trace data for http request / response. + * + * By default the `node`, `node.async_hooks`, and `v8` categories are enabled. + * + * ```bash + * node --trace-event-categories v8,node,node.async_hooks server.js + * ``` + * + * Prior versions of Node.js required the use of the `--trace-events-enabled` flag to enable trace events. This requirement has been removed. However, the `--trace-events-enabled` flag _may_ still be + * used and will enable the `node`, `node.async_hooks`, and `v8` trace event categories by default. + * + * ```bash + * node --trace-events-enabled + * + * # is equivalent to + * + * node --trace-event-categories v8,node,node.async_hooks + * ``` + * + * Alternatively, trace events may be enabled using the `node:trace_events` module: + * + * ```js + * const trace_events = require('node:trace_events'); + * const tracing = trace_events.createTracing({ categories: ['node.perf'] }); + * tracing.enable(); // Enable trace event capture for the 'node.perf' category + * + * // do work + * + * tracing.disable(); // Disable trace event capture for the 'node.perf' category + * ``` + * + * Running Node.js with tracing enabled will produce log files that can be opened + * in the [`chrome://tracing`](https://www.chromium.org/developers/how-tos/trace-event-profiling-tool) tab of Chrome. + * + * The logging file is by default called `node_trace.${rotation}.log`, where `${rotation}` is an incrementing log-rotation id. The filepath pattern can + * be specified with `--trace-event-file-pattern` that accepts a template + * string that supports `${rotation}` and `${pid}`: + * + * ```bash + * node --trace-event-categories v8 --trace-event-file-pattern '${pid}-${rotation}.log' server.js + * ``` + * + * To guarantee that the log file is properly generated after signal events like `SIGINT`, `SIGTERM`, or `SIGBREAK`, make sure to have the appropriate handlers + * in your code, such as: + * + * ```js + * process.on('SIGINT', function onSigint() { + * console.info('Received SIGINT.'); + * process.exit(130); // Or applicable exit code depending on OS and signal + * }); + * ``` + * + * The tracing system uses the same time source + * as the one used by `process.hrtime()`. + * However the trace-event timestamps are expressed in microseconds, + * unlike `process.hrtime()` which returns nanoseconds. + * + * The features from this module are not available in [`Worker`](https://nodejs.org/docs/latest-v22.x/api/worker_threads.html#class-worker) threads. + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/trace_events.js) + */ +declare module "trace_events" { + /** + * The `Tracing` object is used to enable or disable tracing for sets of + * categories. Instances are created using the + * `trace_events.createTracing()` method. + * + * When created, the `Tracing` object is disabled. Calling the + * `tracing.enable()` method adds the categories to the set of enabled trace + * event categories. Calling `tracing.disable()` will remove the categories + * from the set of enabled trace event categories. + */ + interface Tracing { + /** + * A comma-separated list of the trace event categories covered by this + * `Tracing` object. + * @since v10.0.0 + */ + readonly categories: string; + /** + * Disables this `Tracing` object. + * + * Only trace event categories _not_ covered by other enabled `Tracing` + * objects and _not_ specified by the `--trace-event-categories` flag + * will be disabled. + * + * ```js + * const trace_events = require('node:trace_events'); + * const t1 = trace_events.createTracing({ categories: ['node', 'v8'] }); + * const t2 = trace_events.createTracing({ categories: ['node.perf', 'node'] }); + * t1.enable(); + * t2.enable(); + * + * // Prints 'node,node.perf,v8' + * console.log(trace_events.getEnabledCategories()); + * + * t2.disable(); // Will only disable emission of the 'node.perf' category + * + * // Prints 'node,v8' + * console.log(trace_events.getEnabledCategories()); + * ``` + * @since v10.0.0 + */ + disable(): void; + /** + * Enables this `Tracing` object for the set of categories covered by + * the `Tracing` object. + * @since v10.0.0 + */ + enable(): void; + /** + * `true` only if the `Tracing` object has been enabled. + * @since v10.0.0 + */ + readonly enabled: boolean; + } + interface CreateTracingOptions { + /** + * An array of trace category names. Values included in the array are + * coerced to a string when possible. An error will be thrown if the + * value cannot be coerced. + */ + categories: string[]; + } + /** + * Creates and returns a `Tracing` object for the given set of `categories`. + * + * ```js + * const trace_events = require('node:trace_events'); + * const categories = ['node.perf', 'node.async_hooks']; + * const tracing = trace_events.createTracing({ categories }); + * tracing.enable(); + * // do stuff + * tracing.disable(); + * ``` + * @since v10.0.0 + */ + function createTracing(options: CreateTracingOptions): Tracing; + /** + * Returns a comma-separated list of all currently-enabled trace event + * categories. The current set of enabled trace event categories is determined + * by the _union_ of all currently-enabled `Tracing` objects and any categories + * enabled using the `--trace-event-categories` flag. + * + * Given the file `test.js` below, the command `node --trace-event-categories node.perf test.js` will print `'node.async_hooks,node.perf'` to the console. + * + * ```js + * const trace_events = require('node:trace_events'); + * const t1 = trace_events.createTracing({ categories: ['node.async_hooks'] }); + * const t2 = trace_events.createTracing({ categories: ['node.perf'] }); + * const t3 = trace_events.createTracing({ categories: ['v8'] }); + * + * t1.enable(); + * t2.enable(); + * + * console.log(trace_events.getEnabledCategories()); + * ``` + * @since v10.0.0 + */ + function getEnabledCategories(): string | undefined; +} +declare module "node:trace_events" { + export * from "trace_events"; +} diff --git a/libcore/node_modules/@types/node/tty.d.ts b/libcore/node_modules/@types/node/tty.d.ts new file mode 100644 index 0000000..b88dbbd --- /dev/null +++ b/libcore/node_modules/@types/node/tty.d.ts @@ -0,0 +1,208 @@ +/** + * The `node:tty` module provides the `tty.ReadStream` and `tty.WriteStream` classes. In most cases, it will not be necessary or possible to use this module + * directly. However, it can be accessed using: + * + * ```js + * const tty = require('node:tty'); + * ``` + * + * When Node.js detects that it is being run with a text terminal ("TTY") + * attached, `process.stdin` will, by default, be initialized as an instance of `tty.ReadStream` and both `process.stdout` and `process.stderr` will, by + * default, be instances of `tty.WriteStream`. The preferred method of determining + * whether Node.js is being run within a TTY context is to check that the value of + * the `process.stdout.isTTY` property is `true`: + * + * ```console + * $ node -p -e "Boolean(process.stdout.isTTY)" + * true + * $ node -p -e "Boolean(process.stdout.isTTY)" | cat + * false + * ``` + * + * In most cases, there should be little to no reason for an application to + * manually create instances of the `tty.ReadStream` and `tty.WriteStream` classes. + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/tty.js) + */ +declare module "tty" { + import * as net from "node:net"; + /** + * The `tty.isatty()` method returns `true` if the given `fd` is associated with + * a TTY and `false` if it is not, including whenever `fd` is not a non-negative + * integer. + * @since v0.5.8 + * @param fd A numeric file descriptor + */ + function isatty(fd: number): boolean; + /** + * Represents the readable side of a TTY. In normal circumstances `process.stdin` will be the only `tty.ReadStream` instance in a Node.js + * process and there should be no reason to create additional instances. + * @since v0.5.8 + */ + class ReadStream extends net.Socket { + constructor(fd: number, options?: net.SocketConstructorOpts); + /** + * A `boolean` that is `true` if the TTY is currently configured to operate as a + * raw device. + * + * This flag is always `false` when a process starts, even if the terminal is + * operating in raw mode. Its value will change with subsequent calls to `setRawMode`. + * @since v0.7.7 + */ + isRaw: boolean; + /** + * Allows configuration of `tty.ReadStream` so that it operates as a raw device. + * + * When in raw mode, input is always available character-by-character, not + * including modifiers. Additionally, all special processing of characters by the + * terminal is disabled, including echoing input + * characters. Ctrl+C will no longer cause a `SIGINT` when + * in this mode. + * @since v0.7.7 + * @param mode If `true`, configures the `tty.ReadStream` to operate as a raw device. If `false`, configures the `tty.ReadStream` to operate in its default mode. The `readStream.isRaw` + * property will be set to the resulting mode. + * @return The read stream instance. + */ + setRawMode(mode: boolean): this; + /** + * A `boolean` that is always `true` for `tty.ReadStream` instances. + * @since v0.5.8 + */ + isTTY: boolean; + } + /** + * -1 - to the left from cursor + * 0 - the entire line + * 1 - to the right from cursor + */ + type Direction = -1 | 0 | 1; + /** + * Represents the writable side of a TTY. In normal circumstances, `process.stdout` and `process.stderr` will be the only`tty.WriteStream` instances created for a Node.js process and there + * should be no reason to create additional instances. + * @since v0.5.8 + */ + class WriteStream extends net.Socket { + constructor(fd: number); + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "resize", listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "resize"): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "resize", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "resize", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "resize", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "resize", listener: () => void): this; + /** + * `writeStream.clearLine()` clears the current line of this `WriteStream` in a + * direction identified by `dir`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + clearLine(dir: Direction, callback?: () => void): boolean; + /** + * `writeStream.clearScreenDown()` clears this `WriteStream` from the current + * cursor down. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + clearScreenDown(callback?: () => void): boolean; + /** + * `writeStream.cursorTo()` moves this `WriteStream`'s cursor to the specified + * position. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + cursorTo(x: number, y?: number, callback?: () => void): boolean; + cursorTo(x: number, callback: () => void): boolean; + /** + * `writeStream.moveCursor()` moves this `WriteStream`'s cursor _relative_ to its + * current position. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + moveCursor(dx: number, dy: number, callback?: () => void): boolean; + /** + * Returns: + * + * * `1` for 2, + * * `4` for 16, + * * `8` for 256, + * * `24` for 16,777,216 colors supported. + * + * Use this to determine what colors the terminal supports. Due to the nature of + * colors in terminals it is possible to either have false positives or false + * negatives. It depends on process information and the environment variables that + * may lie about what terminal is used. + * It is possible to pass in an `env` object to simulate the usage of a specific + * terminal. This can be useful to check how specific environment settings behave. + * + * To enforce a specific color support, use one of the below environment settings. + * + * * 2 colors: `FORCE_COLOR = 0` (Disables colors) + * * 16 colors: `FORCE_COLOR = 1` + * * 256 colors: `FORCE_COLOR = 2` + * * 16,777,216 colors: `FORCE_COLOR = 3` + * + * Disabling color support is also possible by using the `NO_COLOR` and `NODE_DISABLE_COLORS` environment variables. + * @since v9.9.0 + * @param [env=process.env] An object containing the environment variables to check. This enables simulating the usage of a specific terminal. + */ + getColorDepth(env?: object): number; + /** + * Returns `true` if the `writeStream` supports at least as many colors as provided + * in `count`. Minimum support is 2 (black and white). + * + * This has the same false positives and negatives as described in `writeStream.getColorDepth()`. + * + * ```js + * process.stdout.hasColors(); + * // Returns true or false depending on if `stdout` supports at least 16 colors. + * process.stdout.hasColors(256); + * // Returns true or false depending on if `stdout` supports at least 256 colors. + * process.stdout.hasColors({ TMUX: '1' }); + * // Returns true. + * process.stdout.hasColors(2 ** 24, { TMUX: '1' }); + * // Returns false (the environment setting pretends to support 2 ** 8 colors). + * ``` + * @since v11.13.0, v10.16.0 + * @param [count=16] The number of colors that are requested (minimum 2). + * @param [env=process.env] An object containing the environment variables to check. This enables simulating the usage of a specific terminal. + */ + hasColors(count?: number): boolean; + hasColors(env?: object): boolean; + hasColors(count: number, env?: object): boolean; + /** + * `writeStream.getWindowSize()` returns the size of the TTY + * corresponding to this `WriteStream`. The array is of the type `[numColumns, numRows]` where `numColumns` and `numRows` represent the number + * of columns and rows in the corresponding TTY. + * @since v0.7.7 + */ + getWindowSize(): [number, number]; + /** + * A `number` specifying the number of columns the TTY currently has. This property + * is updated whenever the `'resize'` event is emitted. + * @since v0.7.7 + */ + columns: number; + /** + * A `number` specifying the number of rows the TTY currently has. This property + * is updated whenever the `'resize'` event is emitted. + * @since v0.7.7 + */ + rows: number; + /** + * A `boolean` that is always `true`. + * @since v0.5.8 + */ + isTTY: boolean; + } +} +declare module "node:tty" { + export * from "tty"; +} diff --git a/libcore/node_modules/@types/node/url.d.ts b/libcore/node_modules/@types/node/url.d.ts new file mode 100644 index 0000000..cb06e06 --- /dev/null +++ b/libcore/node_modules/@types/node/url.d.ts @@ -0,0 +1,969 @@ +/** + * The `node:url` module provides utilities for URL resolution and parsing. It can + * be accessed using: + * + * ```js + * import url from 'node:url'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/url.js) + */ +declare module "url" { + import { Blob as NodeBlob } from "node:buffer"; + import { ClientRequestArgs } from "node:http"; + import { ParsedUrlQuery, ParsedUrlQueryInput } from "node:querystring"; + // Input to `url.format` + interface UrlObject { + auth?: string | null | undefined; + hash?: string | null | undefined; + host?: string | null | undefined; + hostname?: string | null | undefined; + href?: string | null | undefined; + pathname?: string | null | undefined; + protocol?: string | null | undefined; + search?: string | null | undefined; + slashes?: boolean | null | undefined; + port?: string | number | null | undefined; + query?: string | null | ParsedUrlQueryInput | undefined; + } + // Output of `url.parse` + interface Url { + auth: string | null; + hash: string | null; + host: string | null; + hostname: string | null; + href: string; + path: string | null; + pathname: string | null; + protocol: string | null; + search: string | null; + slashes: boolean | null; + port: string | null; + query: string | null | ParsedUrlQuery; + } + interface UrlWithParsedQuery extends Url { + query: ParsedUrlQuery; + } + interface UrlWithStringQuery extends Url { + query: string | null; + } + interface FileUrlToPathOptions { + /** + * `true` if the `path` should be return as a windows filepath, `false` for posix, and `undefined` for the system default. + * @default undefined + * @since v22.1.0 + */ + windows?: boolean | undefined; + } + interface PathToFileUrlOptions { + /** + * `true` if the `path` should be return as a windows filepath, `false` for posix, and `undefined` for the system default. + * @default undefined + * @since v22.1.0 + */ + windows?: boolean | undefined; + } + /** + * The `url.parse()` method takes a URL string, parses it, and returns a URL + * object. + * + * A `TypeError` is thrown if `urlString` is not a string. + * + * A `URIError` is thrown if the `auth` property is present but cannot be decoded. + * + * `url.parse()` uses a lenient, non-standard algorithm for parsing URL + * strings. It is prone to security issues such as [host name spoofing](https://hackerone.com/reports/678487) and incorrect handling of usernames and passwords. Do not use with untrusted + * input. CVEs are not issued for `url.parse()` vulnerabilities. Use the `WHATWG URL` API instead. + * @since v0.1.25 + * @deprecated Use the WHATWG URL API instead. + * @param urlString The URL string to parse. + * @param [parseQueryString=false] If `true`, the `query` property will always be set to an object returned by the {@link querystring} module's `parse()` method. If `false`, the `query` property + * on the returned URL object will be an unparsed, undecoded string. + * @param [slashesDenoteHost=false] If `true`, the first token after the literal string `//` and preceding the next `/` will be interpreted as the `host`. For instance, given `//foo/bar`, the + * result would be `{host: 'foo', pathname: '/bar'}` rather than `{pathname: '//foo/bar'}`. + */ + function parse(urlString: string): UrlWithStringQuery; + function parse( + urlString: string, + parseQueryString: false | undefined, + slashesDenoteHost?: boolean, + ): UrlWithStringQuery; + function parse(urlString: string, parseQueryString: true, slashesDenoteHost?: boolean): UrlWithParsedQuery; + function parse(urlString: string, parseQueryString: boolean, slashesDenoteHost?: boolean): Url; + /** + * The `url.format()` method returns a formatted URL string derived from `urlObject`. + * + * ```js + * const url = require('node:url'); + * url.format({ + * protocol: 'https', + * hostname: 'example.com', + * pathname: '/some/path', + * query: { + * page: 1, + * format: 'json', + * }, + * }); + * + * // => 'https://example.com/some/path?page=1&format=json' + * ``` + * + * If `urlObject` is not an object or a string, `url.format()` will throw a `TypeError`. + * + * The formatting process operates as follows: + * + * * A new empty string `result` is created. + * * If `urlObject.protocol` is a string, it is appended as-is to `result`. + * * Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an `Error` is thrown. + * * For all string values of `urlObject.protocol` that _do not end_ with an ASCII + * colon (`:`) character, the literal string `:` will be appended to `result`. + * * If either of the following conditions is true, then the literal string `//` will be appended to `result`: + * * `urlObject.slashes` property is true; + * * `urlObject.protocol` begins with `http`, `https`, `ftp`, `gopher`, or `file`; + * * If the value of the `urlObject.auth` property is truthy, and either `urlObject.host` or `urlObject.hostname` are not `undefined`, the value of `urlObject.auth` will be coerced into a string + * and appended to `result` followed by the literal string `@`. + * * If the `urlObject.host` property is `undefined` then: + * * If the `urlObject.hostname` is a string, it is appended to `result`. + * * Otherwise, if `urlObject.hostname` is not `undefined` and is not a string, + * an `Error` is thrown. + * * If the `urlObject.port` property value is truthy, and `urlObject.hostname` is not `undefined`: + * * The literal string `:` is appended to `result`, and + * * The value of `urlObject.port` is coerced to a string and appended to `result`. + * * Otherwise, if the `urlObject.host` property value is truthy, the value of `urlObject.host` is coerced to a string and appended to `result`. + * * If the `urlObject.pathname` property is a string that is not an empty string: + * * If the `urlObject.pathname` _does not start_ with an ASCII forward slash + * (`/`), then the literal string `'/'` is appended to `result`. + * * The value of `urlObject.pathname` is appended to `result`. + * * Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.search` property is `undefined` and if the `urlObject.query`property is an `Object`, the literal string `?` is appended to `result` followed by the output of calling the + * `querystring` module's `stringify()` method passing the value of `urlObject.query`. + * * Otherwise, if `urlObject.search` is a string: + * * If the value of `urlObject.search` _does not start_ with the ASCII question + * mark (`?`) character, the literal string `?` is appended to `result`. + * * The value of `urlObject.search` is appended to `result`. + * * Otherwise, if `urlObject.search` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.hash` property is a string: + * * If the value of `urlObject.hash` _does not start_ with the ASCII hash (`#`) + * character, the literal string `#` is appended to `result`. + * * The value of `urlObject.hash` is appended to `result`. + * * Otherwise, if the `urlObject.hash` property is not `undefined` and is not a + * string, an `Error` is thrown. + * * `result` is returned. + * @since v0.1.25 + * @legacy Use the WHATWG URL API instead. + * @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. + */ + function format(urlObject: URL, options?: URLFormatOptions): string; + /** + * The `url.format()` method returns a formatted URL string derived from `urlObject`. + * + * ```js + * const url = require('node:url'); + * url.format({ + * protocol: 'https', + * hostname: 'example.com', + * pathname: '/some/path', + * query: { + * page: 1, + * format: 'json', + * }, + * }); + * + * // => 'https://example.com/some/path?page=1&format=json' + * ``` + * + * If `urlObject` is not an object or a string, `url.format()` will throw a `TypeError`. + * + * The formatting process operates as follows: + * + * * A new empty string `result` is created. + * * If `urlObject.protocol` is a string, it is appended as-is to `result`. + * * Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an `Error` is thrown. + * * For all string values of `urlObject.protocol` that _do not end_ with an ASCII + * colon (`:`) character, the literal string `:` will be appended to `result`. + * * If either of the following conditions is true, then the literal string `//` will be appended to `result`: + * * `urlObject.slashes` property is true; + * * `urlObject.protocol` begins with `http`, `https`, `ftp`, `gopher`, or `file`; + * * If the value of the `urlObject.auth` property is truthy, and either `urlObject.host` or `urlObject.hostname` are not `undefined`, the value of `urlObject.auth` will be coerced into a string + * and appended to `result` followed by the literal string `@`. + * * If the `urlObject.host` property is `undefined` then: + * * If the `urlObject.hostname` is a string, it is appended to `result`. + * * Otherwise, if `urlObject.hostname` is not `undefined` and is not a string, + * an `Error` is thrown. + * * If the `urlObject.port` property value is truthy, and `urlObject.hostname` is not `undefined`: + * * The literal string `:` is appended to `result`, and + * * The value of `urlObject.port` is coerced to a string and appended to `result`. + * * Otherwise, if the `urlObject.host` property value is truthy, the value of `urlObject.host` is coerced to a string and appended to `result`. + * * If the `urlObject.pathname` property is a string that is not an empty string: + * * If the `urlObject.pathname` _does not start_ with an ASCII forward slash + * (`/`), then the literal string `'/'` is appended to `result`. + * * The value of `urlObject.pathname` is appended to `result`. + * * Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.search` property is `undefined` and if the `urlObject.query`property is an `Object`, the literal string `?` is appended to `result` followed by the output of calling the + * `querystring` module's `stringify()` method passing the value of `urlObject.query`. + * * Otherwise, if `urlObject.search` is a string: + * * If the value of `urlObject.search` _does not start_ with the ASCII question + * mark (`?`) character, the literal string `?` is appended to `result`. + * * The value of `urlObject.search` is appended to `result`. + * * Otherwise, if `urlObject.search` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.hash` property is a string: + * * If the value of `urlObject.hash` _does not start_ with the ASCII hash (`#`) + * character, the literal string `#` is appended to `result`. + * * The value of `urlObject.hash` is appended to `result`. + * * Otherwise, if the `urlObject.hash` property is not `undefined` and is not a + * string, an `Error` is thrown. + * * `result` is returned. + * @since v0.1.25 + * @legacy Use the WHATWG URL API instead. + * @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. + */ + function format(urlObject: UrlObject | string): string; + /** + * The `url.resolve()` method resolves a target URL relative to a base URL in a + * manner similar to that of a web browser resolving an anchor tag. + * + * ```js + * const url = require('node:url'); + * url.resolve('/one/two/three', 'four'); // '/one/two/four' + * url.resolve('http://example.com/', '/one'); // 'http://example.com/one' + * url.resolve('http://example.com/one', '/two'); // 'http://example.com/two' + * ``` + * + * To achieve the same result using the WHATWG URL API: + * + * ```js + * function resolve(from, to) { + * const resolvedUrl = new URL(to, new URL(from, 'resolve://')); + * if (resolvedUrl.protocol === 'resolve:') { + * // `from` is a relative URL. + * const { pathname, search, hash } = resolvedUrl; + * return pathname + search + hash; + * } + * return resolvedUrl.toString(); + * } + * + * resolve('/one/two/three', 'four'); // '/one/two/four' + * resolve('http://example.com/', '/one'); // 'http://example.com/one' + * resolve('http://example.com/one', '/two'); // 'http://example.com/two' + * ``` + * @since v0.1.25 + * @legacy Use the WHATWG URL API instead. + * @param from The base URL to use if `to` is a relative URL. + * @param to The target URL to resolve. + */ + function resolve(from: string, to: string): string; + /** + * Returns the [Punycode](https://tools.ietf.org/html/rfc5891#section-4.4) ASCII serialization of the `domain`. If `domain` is an + * invalid domain, the empty string is returned. + * + * It performs the inverse operation to {@link domainToUnicode}. + * + * ```js + * import url from 'node:url'; + * + * console.log(url.domainToASCII('español.com')); + * // Prints xn--espaol-zwa.com + * console.log(url.domainToASCII('中文.com')); + * // Prints xn--fiq228c.com + * console.log(url.domainToASCII('xn--iñvalid.com')); + * // Prints an empty string + * ``` + * @since v7.4.0, v6.13.0 + */ + function domainToASCII(domain: string): string; + /** + * Returns the Unicode serialization of the `domain`. If `domain` is an invalid + * domain, the empty string is returned. + * + * It performs the inverse operation to {@link domainToASCII}. + * + * ```js + * import url from 'node:url'; + * + * console.log(url.domainToUnicode('xn--espaol-zwa.com')); + * // Prints español.com + * console.log(url.domainToUnicode('xn--fiq228c.com')); + * // Prints 中文.com + * console.log(url.domainToUnicode('xn--iñvalid.com')); + * // Prints an empty string + * ``` + * @since v7.4.0, v6.13.0 + */ + function domainToUnicode(domain: string): string; + /** + * This function ensures the correct decodings of percent-encoded characters as + * well as ensuring a cross-platform valid absolute path string. + * + * ```js + * import { fileURLToPath } from 'node:url'; + * + * const __filename = fileURLToPath(import.meta.url); + * + * new URL('file:///C:/path/').pathname; // Incorrect: /C:/path/ + * fileURLToPath('file:///C:/path/'); // Correct: C:\path\ (Windows) + * + * new URL('file://nas/foo.txt').pathname; // Incorrect: /foo.txt + * fileURLToPath('file://nas/foo.txt'); // Correct: \\nas\foo.txt (Windows) + * + * new URL('file:///你好.txt').pathname; // Incorrect: /%E4%BD%A0%E5%A5%BD.txt + * fileURLToPath('file:///你好.txt'); // Correct: /你好.txt (POSIX) + * + * new URL('file:///hello world').pathname; // Incorrect: /hello%20world + * fileURLToPath('file:///hello world'); // Correct: /hello world (POSIX) + * ``` + * @since v10.12.0 + * @param url The file URL string or URL object to convert to a path. + * @return The fully-resolved platform-specific Node.js file path. + */ + function fileURLToPath(url: string | URL, options?: FileUrlToPathOptions): string; + /** + * This function ensures that `path` is resolved absolutely, and that the URL + * control characters are correctly encoded when converting into a File URL. + * + * ```js + * import { pathToFileURL } from 'node:url'; + * + * new URL('/foo#1', 'file:'); // Incorrect: file:///foo#1 + * pathToFileURL('/foo#1'); // Correct: file:///foo%231 (POSIX) + * + * new URL('/some/path%.c', 'file:'); // Incorrect: file:///some/path%.c + * pathToFileURL('/some/path%.c'); // Correct: file:///some/path%25.c (POSIX) + * ``` + * @since v10.12.0 + * @param path The path to convert to a File URL. + * @return The file URL object. + */ + function pathToFileURL(path: string, options?: PathToFileUrlOptions): URL; + /** + * This utility function converts a URL object into an ordinary options object as + * expected by the `http.request()` and `https.request()` APIs. + * + * ```js + * import { urlToHttpOptions } from 'node:url'; + * const myURL = new URL('https://a:b@測試?abc#foo'); + * + * console.log(urlToHttpOptions(myURL)); + * /* + * { + * protocol: 'https:', + * hostname: 'xn--g6w251d', + * hash: '#foo', + * search: '?abc', + * pathname: '/', + * path: '/?abc', + * href: 'https://a:b@xn--g6w251d/?abc#foo', + * auth: 'a:b' + * } + * + * ``` + * @since v15.7.0, v14.18.0 + * @param url The `WHATWG URL` object to convert to an options object. + * @return Options object + */ + function urlToHttpOptions(url: URL): ClientRequestArgs; + interface URLFormatOptions { + /** + * `true` if the serialized URL string should include the username and password, `false` otherwise. + * @default true + */ + auth?: boolean | undefined; + /** + * `true` if the serialized URL string should include the fragment, `false` otherwise. + * @default true + */ + fragment?: boolean | undefined; + /** + * `true` if the serialized URL string should include the search query, `false` otherwise. + * @default true + */ + search?: boolean | undefined; + /** + * `true` if Unicode characters appearing in the host component of the URL string should be encoded directly as opposed to + * being Punycode encoded. + * @default false + */ + unicode?: boolean | undefined; + } + /** + * Browser-compatible `URL` class, implemented by following the WHATWG URL + * Standard. [Examples of parsed URLs](https://url.spec.whatwg.org/#example-url-parsing) may be found in the Standard itself. + * The `URL` class is also available on the global object. + * + * In accordance with browser conventions, all properties of `URL` objects + * are implemented as getters and setters on the class prototype, rather than as + * data properties on the object itself. Thus, unlike `legacy urlObject`s, + * using the `delete` keyword on any properties of `URL` objects (e.g. `delete myURL.protocol`, `delete myURL.pathname`, etc) has no effect but will still + * return `true`. + * @since v7.0.0, v6.13.0 + */ + class URL { + /** + * Creates a `'blob:nodedata:...'` URL string that represents the given `Blob` object and can be used to retrieve the `Blob` later. + * + * ```js + * const { + * Blob, + * resolveObjectURL, + * } = require('node:buffer'); + * + * const blob = new Blob(['hello']); + * const id = URL.createObjectURL(blob); + * + * // later... + * + * const otherBlob = resolveObjectURL(id); + * console.log(otherBlob.size); + * ``` + * + * The data stored by the registered `Blob` will be retained in memory until `URL.revokeObjectURL()` is called to remove it. + * + * `Blob` objects are registered within the current thread. If using Worker + * Threads, `Blob` objects registered within one Worker will not be available + * to other workers or the main thread. + * @since v16.7.0 + * @experimental + */ + static createObjectURL(blob: NodeBlob): string; + /** + * Removes the stored `Blob` identified by the given ID. Attempting to revoke a + * ID that isn't registered will silently fail. + * @since v16.7.0 + * @experimental + * @param id A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`. + */ + static revokeObjectURL(id: string): void; + /** + * Checks if an `input` relative to the `base` can be parsed to a `URL`. + * + * ```js + * const isValid = URL.canParse('/foo', 'https://example.org/'); // true + * + * const isNotValid = URL.canParse('/foo'); // false + * ``` + * @since v19.9.0 + * @param input The absolute or relative input URL to parse. If `input` is relative, then `base` is required. If `input` is absolute, the `base` is ignored. If `input` is not a string, it is + * `converted to a string` first. + * @param base The base URL to resolve against if the `input` is not absolute. If `base` is not a string, it is `converted to a string` first. + */ + static canParse(input: string, base?: string): boolean; + /** + * Parses a string as a URL. If `base` is provided, it will be used as the base URL for the purpose of resolving non-absolute `input` URLs. + * Returns `null` if `input` is not a valid. + * @param input The absolute or relative input URL to parse. If `input` is relative, then `base` is required. If `input` is absolute, the `base` is ignored. If `input` is not a string, it is + * `converted to a string` first. + * @param base The base URL to resolve against if the `input` is not absolute. If `base` is not a string, it is `converted to a string` first. + * @since v22.1.0 + */ + static parse(input: string, base?: string): URL | null; + constructor(input: string | { toString: () => string }, base?: string | URL); + /** + * Gets and sets the fragment portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/foo#bar'); + * console.log(myURL.hash); + * // Prints #bar + * + * myURL.hash = 'baz'; + * console.log(myURL.href); + * // Prints https://example.org/foo#baz + * ``` + * + * Invalid URL characters included in the value assigned to the `hash` property + * are `percent-encoded`. The selection of which characters to + * percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + hash: string; + /** + * Gets and sets the host portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org:81/foo'); + * console.log(myURL.host); + * // Prints example.org:81 + * + * myURL.host = 'example.com:82'; + * console.log(myURL.href); + * // Prints https://example.com:82/foo + * ``` + * + * Invalid host values assigned to the `host` property are ignored. + */ + host: string; + /** + * Gets and sets the host name portion of the URL. The key difference between`url.host` and `url.hostname` is that `url.hostname` does _not_ include the + * port. + * + * ```js + * const myURL = new URL('https://example.org:81/foo'); + * console.log(myURL.hostname); + * // Prints example.org + * + * // Setting the hostname does not change the port + * myURL.hostname = 'example.com'; + * console.log(myURL.href); + * // Prints https://example.com:81/foo + * + * // Use myURL.host to change the hostname and port + * myURL.host = 'example.org:82'; + * console.log(myURL.href); + * // Prints https://example.org:82/foo + * ``` + * + * Invalid host name values assigned to the `hostname` property are ignored. + */ + hostname: string; + /** + * Gets and sets the serialized URL. + * + * ```js + * const myURL = new URL('https://example.org/foo'); + * console.log(myURL.href); + * // Prints https://example.org/foo + * + * myURL.href = 'https://example.com/bar'; + * console.log(myURL.href); + * // Prints https://example.com/bar + * ``` + * + * Getting the value of the `href` property is equivalent to calling {@link toString}. + * + * Setting the value of this property to a new value is equivalent to creating a + * new `URL` object using `new URL(value)`. Each of the `URL` object's properties will be modified. + * + * If the value assigned to the `href` property is not a valid URL, a `TypeError` will be thrown. + */ + href: string; + /** + * Gets the read-only serialization of the URL's origin. + * + * ```js + * const myURL = new URL('https://example.org/foo/bar?baz'); + * console.log(myURL.origin); + * // Prints https://example.org + * ``` + * + * ```js + * const idnURL = new URL('https://測試'); + * console.log(idnURL.origin); + * // Prints https://xn--g6w251d + * + * console.log(idnURL.hostname); + * // Prints xn--g6w251d + * ``` + */ + readonly origin: string; + /** + * Gets and sets the password portion of the URL. + * + * ```js + * const myURL = new URL('https://abc:xyz@example.com'); + * console.log(myURL.password); + * // Prints xyz + * + * myURL.password = '123'; + * console.log(myURL.href); + * // Prints https://abc:123@example.com/ + * ``` + * + * Invalid URL characters included in the value assigned to the `password` property + * are `percent-encoded`. The selection of which characters to + * percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + password: string; + /** + * Gets and sets the path portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/abc/xyz?123'); + * console.log(myURL.pathname); + * // Prints /abc/xyz + * + * myURL.pathname = '/abcdef'; + * console.log(myURL.href); + * // Prints https://example.org/abcdef?123 + * ``` + * + * Invalid URL characters included in the value assigned to the `pathname` property are `percent-encoded`. The selection of which characters + * to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + pathname: string; + /** + * Gets and sets the port portion of the URL. + * + * The port value may be a number or a string containing a number in the range `0` to `65535` (inclusive). Setting the value to the default port of the `URL` objects given `protocol` will + * result in the `port` value becoming + * the empty string (`''`). + * + * The port value can be an empty string in which case the port depends on + * the protocol/scheme: + * + * + * + * Upon assigning a value to the port, the value will first be converted to a + * string using `.toString()`. + * + * If that string is invalid but it begins with a number, the leading number is + * assigned to `port`. + * If the number lies outside the range denoted above, it is ignored. + * + * ```js + * const myURL = new URL('https://example.org:8888'); + * console.log(myURL.port); + * // Prints 8888 + * + * // Default ports are automatically transformed to the empty string + * // (HTTPS protocol's default port is 443) + * myURL.port = '443'; + * console.log(myURL.port); + * // Prints the empty string + * console.log(myURL.href); + * // Prints https://example.org/ + * + * myURL.port = 1234; + * console.log(myURL.port); + * // Prints 1234 + * console.log(myURL.href); + * // Prints https://example.org:1234/ + * + * // Completely invalid port strings are ignored + * myURL.port = 'abcd'; + * console.log(myURL.port); + * // Prints 1234 + * + * // Leading numbers are treated as a port number + * myURL.port = '5678abcd'; + * console.log(myURL.port); + * // Prints 5678 + * + * // Non-integers are truncated + * myURL.port = 1234.5678; + * console.log(myURL.port); + * // Prints 1234 + * + * // Out-of-range numbers which are not represented in scientific notation + * // will be ignored. + * myURL.port = 1e10; // 10000000000, will be range-checked as described below + * console.log(myURL.port); + * // Prints 1234 + * ``` + * + * Numbers which contain a decimal point, + * such as floating-point numbers or numbers in scientific notation, + * are not an exception to this rule. + * Leading numbers up to the decimal point will be set as the URL's port, + * assuming they are valid: + * + * ```js + * myURL.port = 4.567e21; + * console.log(myURL.port); + * // Prints 4 (because it is the leading number in the string '4.567e21') + * ``` + */ + port: string; + /** + * Gets and sets the protocol portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org'); + * console.log(myURL.protocol); + * // Prints https: + * + * myURL.protocol = 'ftp'; + * console.log(myURL.href); + * // Prints ftp://example.org/ + * ``` + * + * Invalid URL protocol values assigned to the `protocol` property are ignored. + */ + protocol: string; + /** + * Gets and sets the serialized query portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/abc?123'); + * console.log(myURL.search); + * // Prints ?123 + * + * myURL.search = 'abc=xyz'; + * console.log(myURL.href); + * // Prints https://example.org/abc?abc=xyz + * ``` + * + * Any invalid URL characters appearing in the value assigned the `search` property will be `percent-encoded`. The selection of which + * characters to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + search: string; + /** + * Gets the `URLSearchParams` object representing the query parameters of the + * URL. This property is read-only but the `URLSearchParams` object it provides + * can be used to mutate the URL instance; to replace the entirety of query + * parameters of the URL, use the {@link search} setter. See `URLSearchParams` documentation for details. + * + * Use care when using `.searchParams` to modify the `URL` because, + * per the WHATWG specification, the `URLSearchParams` object uses + * different rules to determine which characters to percent-encode. For + * instance, the `URL` object will not percent encode the ASCII tilde (`~`) + * character, while `URLSearchParams` will always encode it: + * + * ```js + * const myURL = new URL('https://example.org/abc?foo=~bar'); + * + * console.log(myURL.search); // prints ?foo=~bar + * + * // Modify the URL via searchParams... + * myURL.searchParams.sort(); + * + * console.log(myURL.search); // prints ?foo=%7Ebar + * ``` + */ + readonly searchParams: URLSearchParams; + /** + * Gets and sets the username portion of the URL. + * + * ```js + * const myURL = new URL('https://abc:xyz@example.com'); + * console.log(myURL.username); + * // Prints abc + * + * myURL.username = '123'; + * console.log(myURL.href); + * // Prints https://123:xyz@example.com/ + * ``` + * + * Any invalid URL characters appearing in the value assigned the `username` property will be `percent-encoded`. The selection of which + * characters to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + username: string; + /** + * The `toString()` method on the `URL` object returns the serialized URL. The + * value returned is equivalent to that of {@link href} and {@link toJSON}. + */ + toString(): string; + /** + * The `toJSON()` method on the `URL` object returns the serialized URL. The + * value returned is equivalent to that of {@link href} and {@link toString}. + * + * This method is automatically called when an `URL` object is serialized + * with [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). + * + * ```js + * const myURLs = [ + * new URL('https://www.example.com'), + * new URL('https://test.example.org'), + * ]; + * console.log(JSON.stringify(myURLs)); + * // Prints ["https://www.example.com/","https://test.example.org/"] + * ``` + */ + toJSON(): string; + } + /** + * The `URLSearchParams` API provides read and write access to the query of a `URL`. The `URLSearchParams` class can also be used standalone with one of the + * four following constructors. + * The `URLSearchParams` class is also available on the global object. + * + * The WHATWG `URLSearchParams` interface and the `querystring` module have + * similar purpose, but the purpose of the `querystring` module is more + * general, as it allows the customization of delimiter characters (`&` and `=`). + * On the other hand, this API is designed purely for URL query strings. + * + * ```js + * const myURL = new URL('https://example.org/?abc=123'); + * console.log(myURL.searchParams.get('abc')); + * // Prints 123 + * + * myURL.searchParams.append('abc', 'xyz'); + * console.log(myURL.href); + * // Prints https://example.org/?abc=123&abc=xyz + * + * myURL.searchParams.delete('abc'); + * myURL.searchParams.set('a', 'b'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b + * + * const newSearchParams = new URLSearchParams(myURL.searchParams); + * // The above is equivalent to + * // const newSearchParams = new URLSearchParams(myURL.search); + * + * newSearchParams.append('a', 'c'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b + * console.log(newSearchParams.toString()); + * // Prints a=b&a=c + * + * // newSearchParams.toString() is implicitly called + * myURL.search = newSearchParams; + * console.log(myURL.href); + * // Prints https://example.org/?a=b&a=c + * newSearchParams.delete('a'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b&a=c + * ``` + * @since v7.5.0, v6.13.0 + */ + class URLSearchParams implements Iterable<[string, string]> { + constructor( + init?: + | URLSearchParams + | string + | Record + | Iterable<[string, string]> + | ReadonlyArray<[string, string]>, + ); + /** + * Append a new name-value pair to the query string. + */ + append(name: string, value: string): void; + /** + * If `value` is provided, removes all name-value pairs + * where name is `name` and value is `value`. + * + * If `value` is not provided, removes all name-value pairs whose name is `name`. + */ + delete(name: string, value?: string): void; + /** + * Returns an ES6 `Iterator` over each of the name-value pairs in the query. + * Each item of the iterator is a JavaScript `Array`. The first item of the `Array` is the `name`, the second item of the `Array` is the `value`. + * + * Alias for `urlSearchParams[@@iterator]()`. + */ + entries(): IterableIterator<[string, string]>; + /** + * Iterates over each name-value pair in the query and invokes the given function. + * + * ```js + * const myURL = new URL('https://example.org/?a=b&c=d'); + * myURL.searchParams.forEach((value, name, searchParams) => { + * console.log(name, value, myURL.searchParams === searchParams); + * }); + * // Prints: + * // a b true + * // c d true + * ``` + * @param fn Invoked for each name-value pair in the query + * @param thisArg To be used as `this` value for when `fn` is called + */ + forEach( + fn: (this: TThis, value: string, name: string, searchParams: URLSearchParams) => void, + thisArg?: TThis, + ): void; + /** + * Returns the value of the first name-value pair whose name is `name`. If there + * are no such pairs, `null` is returned. + * @return or `null` if there is no name-value pair with the given `name`. + */ + get(name: string): string | null; + /** + * Returns the values of all name-value pairs whose name is `name`. If there are + * no such pairs, an empty array is returned. + */ + getAll(name: string): string[]; + /** + * Checks if the `URLSearchParams` object contains key-value pair(s) based on `name` and an optional `value` argument. + * + * If `value` is provided, returns `true` when name-value pair with + * same `name` and `value` exists. + * + * If `value` is not provided, returns `true` if there is at least one name-value + * pair whose name is `name`. + */ + has(name: string, value?: string): boolean; + /** + * Returns an ES6 `Iterator` over the names of each name-value pair. + * + * ```js + * const params = new URLSearchParams('foo=bar&foo=baz'); + * for (const name of params.keys()) { + * console.log(name); + * } + * // Prints: + * // foo + * // foo + * ``` + */ + keys(): IterableIterator; + /** + * Sets the value in the `URLSearchParams` object associated with `name` to `value`. If there are any pre-existing name-value pairs whose names are `name`, + * set the first such pair's value to `value` and remove all others. If not, + * append the name-value pair to the query string. + * + * ```js + * const params = new URLSearchParams(); + * params.append('foo', 'bar'); + * params.append('foo', 'baz'); + * params.append('abc', 'def'); + * console.log(params.toString()); + * // Prints foo=bar&foo=baz&abc=def + * + * params.set('foo', 'def'); + * params.set('xyz', 'opq'); + * console.log(params.toString()); + * // Prints foo=def&abc=def&xyz=opq + * ``` + */ + set(name: string, value: string): void; + /** + * The total number of parameter entries. + * @since v19.8.0 + */ + readonly size: number; + /** + * Sort all existing name-value pairs in-place by their names. Sorting is done + * with a [stable sorting algorithm](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability), so relative order between name-value pairs + * with the same name is preserved. + * + * This method can be used, in particular, to increase cache hits. + * + * ```js + * const params = new URLSearchParams('query[]=abc&type=search&query[]=123'); + * params.sort(); + * console.log(params.toString()); + * // Prints query%5B%5D=abc&query%5B%5D=123&type=search + * ``` + * @since v7.7.0, v6.13.0 + */ + sort(): void; + /** + * Returns the search parameters serialized as a string, with characters + * percent-encoded where necessary. + */ + toString(): string; + /** + * Returns an ES6 `Iterator` over the values of each name-value pair. + */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[string, string]>; + } + import { URL as _URL, URLSearchParams as _URLSearchParams } from "url"; + global { + interface URLSearchParams extends _URLSearchParams {} + interface URL extends _URL {} + interface Global { + URL: typeof _URL; + URLSearchParams: typeof _URLSearchParams; + } + /** + * `URL` class is a global reference for `require('url').URL` + * https://nodejs.org/api/url.html#the-whatwg-url-api + * @since v10.0.0 + */ + var URL: typeof globalThis extends { + onmessage: any; + URL: infer T; + } ? T + : typeof _URL; + /** + * `URLSearchParams` class is a global reference for `require('url').URLSearchParams` + * https://nodejs.org/api/url.html#class-urlsearchparams + * @since v10.0.0 + */ + var URLSearchParams: typeof globalThis extends { + onmessage: any; + URLSearchParams: infer T; + } ? T + : typeof _URLSearchParams; + } +} +declare module "node:url" { + export * from "url"; +} diff --git a/libcore/node_modules/@types/node/util.d.ts b/libcore/node_modules/@types/node/util.d.ts new file mode 100644 index 0000000..ab1f609 --- /dev/null +++ b/libcore/node_modules/@types/node/util.d.ts @@ -0,0 +1,2298 @@ +/** + * The `node:util` module supports the needs of Node.js internal APIs. Many of the + * utilities are useful for application and module developers as well. To access + * it: + * + * ```js + * const util = require('node:util'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/util.js) + */ +declare module "util" { + import * as types from "node:util/types"; + export interface InspectOptions { + /** + * If `true`, object's non-enumerable symbols and properties are included in the formatted result. + * `WeakMap` and `WeakSet` entries are also included as well as user defined prototype properties (excluding method properties). + * @default false + */ + showHidden?: boolean | undefined; + /** + * Specifies the number of times to recurse while formatting object. + * This is useful for inspecting large objects. + * To recurse up to the maximum call stack size pass `Infinity` or `null`. + * @default 2 + */ + depth?: number | null | undefined; + /** + * If `true`, the output is styled with ANSI color codes. Colors are customizable. + */ + colors?: boolean | undefined; + /** + * If `false`, `[util.inspect.custom](depth, opts, inspect)` functions are not invoked. + * @default true + */ + customInspect?: boolean | undefined; + /** + * If `true`, `Proxy` inspection includes the target and handler objects. + * @default false + */ + showProxy?: boolean | undefined; + /** + * Specifies the maximum number of `Array`, `TypedArray`, `WeakMap`, and `WeakSet` elements + * to include when formatting. Set to `null` or `Infinity` to show all elements. + * Set to `0` or negative to show no elements. + * @default 100 + */ + maxArrayLength?: number | null | undefined; + /** + * Specifies the maximum number of characters to + * include when formatting. Set to `null` or `Infinity` to show all elements. + * Set to `0` or negative to show no characters. + * @default 10000 + */ + maxStringLength?: number | null | undefined; + /** + * The length at which input values are split across multiple lines. + * Set to `Infinity` to format the input as a single line + * (in combination with `compact` set to `true` or any number >= `1`). + * @default 80 + */ + breakLength?: number | undefined; + /** + * Setting this to `false` causes each object key + * to be displayed on a new line. It will also add new lines to text that is + * longer than `breakLength`. If set to a number, the most `n` inner elements + * are united on a single line as long as all properties fit into + * `breakLength`. Short array elements are also grouped together. Note that no + * text will be reduced below 16 characters, no matter the `breakLength` size. + * For more information, see the example below. + * @default true + */ + compact?: boolean | number | undefined; + /** + * If set to `true` or a function, all properties of an object, and `Set` and `Map` + * entries are sorted in the resulting string. + * If set to `true` the default sort is used. + * If set to a function, it is used as a compare function. + */ + sorted?: boolean | ((a: string, b: string) => number) | undefined; + /** + * If set to `true`, getters are going to be + * inspected as well. If set to `'get'` only getters without setter are going + * to be inspected. If set to `'set'` only getters having a corresponding + * setter are going to be inspected. This might cause side effects depending on + * the getter function. + * @default false + */ + getters?: "get" | "set" | boolean | undefined; + /** + * If set to `true`, an underscore is used to separate every three digits in all bigints and numbers. + * @default false + */ + numericSeparator?: boolean | undefined; + } + export type Style = + | "special" + | "number" + | "bigint" + | "boolean" + | "undefined" + | "null" + | "string" + | "symbol" + | "date" + | "regexp" + | "module"; + export type CustomInspectFunction = (depth: number, options: InspectOptionsStylized) => any; // TODO: , inspect: inspect + export interface InspectOptionsStylized extends InspectOptions { + stylize(text: string, styleType: Style): string; + } + /** + * The `util.format()` method returns a formatted string using the first argument + * as a `printf`-like format string which can contain zero or more format + * specifiers. Each specifier is replaced with the converted value from the + * corresponding argument. Supported specifiers are: + * + * If a specifier does not have a corresponding argument, it is not replaced: + * + * ```js + * util.format('%s:%s', 'foo'); + * // Returns: 'foo:%s' + * ``` + * + * Values that are not part of the format string are formatted using `util.inspect()` if their type is not `string`. + * + * If there are more arguments passed to the `util.format()` method than the + * number of specifiers, the extra arguments are concatenated to the returned + * string, separated by spaces: + * + * ```js + * util.format('%s:%s', 'foo', 'bar', 'baz'); + * // Returns: 'foo:bar baz' + * ``` + * + * If the first argument does not contain a valid format specifier, `util.format()` returns a string that is the concatenation of all arguments separated by spaces: + * + * ```js + * util.format(1, 2, 3); + * // Returns: '1 2 3' + * ``` + * + * If only one argument is passed to `util.format()`, it is returned as it is + * without any formatting: + * + * ```js + * util.format('%% %s'); + * // Returns: '%% %s' + * ``` + * + * `util.format()` is a synchronous method that is intended as a debugging tool. + * Some input values can have a significant performance overhead that can block the + * event loop. Use this function with care and never in a hot code path. + * @since v0.5.3 + * @param format A `printf`-like format string. + */ + export function format(format?: any, ...param: any[]): string; + /** + * This function is identical to {@link format}, except in that it takes + * an `inspectOptions` argument which specifies options that are passed along to {@link inspect}. + * + * ```js + * util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 }); + * // Returns 'See object { foo: 42 }', where `42` is colored as a number + * // when printed to a terminal. + * ``` + * @since v10.0.0 + */ + export function formatWithOptions(inspectOptions: InspectOptions, format?: any, ...param: any[]): string; + /** + * Returns the string name for a numeric error code that comes from a Node.js API. + * The mapping between error codes and error names is platform-dependent. + * See `Common System Errors` for the names of common errors. + * + * ```js + * fs.access('file/that/does/not/exist', (err) => { + * const name = util.getSystemErrorName(err.errno); + * console.error(name); // ENOENT + * }); + * ``` + * @since v9.7.0 + */ + export function getSystemErrorName(err: number): string; + /** + * Returns a Map of all system error codes available from the Node.js API. + * The mapping between error codes and error names is platform-dependent. + * See `Common System Errors` for the names of common errors. + * + * ```js + * fs.access('file/that/does/not/exist', (err) => { + * const errorMap = util.getSystemErrorMap(); + * const name = errorMap.get(err.errno); + * console.error(name); // ENOENT + * }); + * ``` + * @since v16.0.0, v14.17.0 + */ + export function getSystemErrorMap(): Map; + /** + * The `util.log()` method prints the given `string` to `stdout` with an included + * timestamp. + * + * ```js + * const util = require('node:util'); + * + * util.log('Timestamped message.'); + * ``` + * @since v0.3.0 + * @deprecated Since v6.0.0 - Use a third party module instead. + */ + export function log(string: string): void; + /** + * Returns the `string` after replacing any surrogate code points + * (or equivalently, any unpaired surrogate code units) with the + * Unicode "replacement character" U+FFFD. + * @since v16.8.0, v14.18.0 + */ + export function toUSVString(string: string): string; + /** + * Creates and returns an `AbortController` instance whose `AbortSignal` is marked + * as transferable and can be used with `structuredClone()` or `postMessage()`. + * @since v18.11.0 + * @experimental + * @returns A transferable AbortController + */ + export function transferableAbortController(): AbortController; + /** + * Marks the given `AbortSignal` as transferable so that it can be used with`structuredClone()` and `postMessage()`. + * + * ```js + * const signal = transferableAbortSignal(AbortSignal.timeout(100)); + * const channel = new MessageChannel(); + * channel.port2.postMessage(signal, [signal]); + * ``` + * @since v18.11.0 + * @experimental + * @param signal The AbortSignal + * @returns The same AbortSignal + */ + export function transferableAbortSignal(signal: AbortSignal): AbortSignal; + /** + * Listens to abort event on the provided `signal` and + * returns a promise that is fulfilled when the `signal` is + * aborted. If the passed `resource` is garbage collected before the `signal` is + * aborted, the returned promise shall remain pending indefinitely. + * + * ```js + * import { aborted } from 'node:util'; + * + * const dependent = obtainSomethingAbortable(); + * + * aborted(dependent.signal, dependent).then(() => { + * // Do something when dependent is aborted. + * }); + * + * dependent.on('event', () => { + * dependent.abort(); + * }); + * ``` + * @since v19.7.0 + * @experimental + * @param resource Any non-null entity, reference to which is held weakly. + */ + export function aborted(signal: AbortSignal, resource: any): Promise; + /** + * The `util.inspect()` method returns a string representation of `object` that is + * intended for debugging. The output of `util.inspect` may change at any time + * and should not be depended upon programmatically. Additional `options` may be + * passed that alter the result. `util.inspect()` will use the constructor's name and/or `@@toStringTag` to make + * an identifiable tag for an inspected value. + * + * ```js + * class Foo { + * get [Symbol.toStringTag]() { + * return 'bar'; + * } + * } + * + * class Bar {} + * + * const baz = Object.create(null, { [Symbol.toStringTag]: { value: 'foo' } }); + * + * util.inspect(new Foo()); // 'Foo [bar] {}' + * util.inspect(new Bar()); // 'Bar {}' + * util.inspect(baz); // '[foo] {}' + * ``` + * + * Circular references point to their anchor by using a reference index: + * + * ```js + * const { inspect } = require('node:util'); + * + * const obj = {}; + * obj.a = [obj]; + * obj.b = {}; + * obj.b.inner = obj.b; + * obj.b.obj = obj; + * + * console.log(inspect(obj)); + * // { + * // a: [ [Circular *1] ], + * // b: { inner: [Circular *2], obj: [Circular *1] } + * // } + * ``` + * + * The following example inspects all properties of the `util` object: + * + * ```js + * const util = require('node:util'); + * + * console.log(util.inspect(util, { showHidden: true, depth: null })); + * ``` + * + * The following example highlights the effect of the `compact` option: + * + * ```js + * const util = require('node:util'); + * + * const o = { + * a: [1, 2, [[ + * 'Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit, sed do ' + + * 'eiusmod \ntempor incididunt ut labore et dolore magna aliqua.', + * 'test', + * 'foo']], 4], + * b: new Map([['za', 1], ['zb', 'test']]), + * }; + * console.log(util.inspect(o, { compact: true, depth: 5, breakLength: 80 })); + * + * // { a: + * // [ 1, + * // 2, + * // [ [ 'Lorem ipsum dolor sit amet,\nconsectetur [...]', // A long line + * // 'test', + * // 'foo' ] ], + * // 4 ], + * // b: Map(2) { 'za' => 1, 'zb' => 'test' } } + * + * // Setting `compact` to false or an integer creates more reader friendly output. + * console.log(util.inspect(o, { compact: false, depth: 5, breakLength: 80 })); + * + * // { + * // a: [ + * // 1, + * // 2, + * // [ + * // [ + * // 'Lorem ipsum dolor sit amet,\n' + + * // 'consectetur adipiscing elit, sed do eiusmod \n' + + * // 'tempor incididunt ut labore et dolore magna aliqua.', + * // 'test', + * // 'foo' + * // ] + * // ], + * // 4 + * // ], + * // b: Map(2) { + * // 'za' => 1, + * // 'zb' => 'test' + * // } + * // } + * + * // Setting `breakLength` to e.g. 150 will print the "Lorem ipsum" text in a + * // single line. + * ``` + * + * The `showHidden` option allows [`WeakMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) and + * [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) entries to be + * inspected. If there are more entries than `maxArrayLength`, there is no + * guarantee which entries are displayed. That means retrieving the same [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) entries twice may + * result in different output. Furthermore, entries + * with no remaining strong references may be garbage collected at any time. + * + * ```js + * const { inspect } = require('node:util'); + * + * const obj = { a: 1 }; + * const obj2 = { b: 2 }; + * const weakSet = new WeakSet([obj, obj2]); + * + * console.log(inspect(weakSet, { showHidden: true })); + * // WeakSet { { a: 1 }, { b: 2 } } + * ``` + * + * The `sorted` option ensures that an object's property insertion order does not + * impact the result of `util.inspect()`. + * + * ```js + * const { inspect } = require('node:util'); + * const assert = require('node:assert'); + * + * const o1 = { + * b: [2, 3, 1], + * a: '`a` comes before `b`', + * c: new Set([2, 3, 1]), + * }; + * console.log(inspect(o1, { sorted: true })); + * // { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set(3) { 1, 2, 3 } } + * console.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) })); + * // { c: Set(3) { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' } + * + * const o2 = { + * c: new Set([2, 1, 3]), + * a: '`a` comes before `b`', + * b: [2, 3, 1], + * }; + * assert.strict.equal( + * inspect(o1, { sorted: true }), + * inspect(o2, { sorted: true }), + * ); + * ``` + * + * The `numericSeparator` option adds an underscore every three digits to all + * numbers. + * + * ```js + * const { inspect } = require('node:util'); + * + * const thousand = 1_000; + * const million = 1_000_000; + * const bigNumber = 123_456_789n; + * const bigDecimal = 1_234.123_45; + * + * console.log(inspect(thousand, { numericSeparator: true })); + * // 1_000 + * console.log(inspect(million, { numericSeparator: true })); + * // 1_000_000 + * console.log(inspect(bigNumber, { numericSeparator: true })); + * // 123_456_789n + * console.log(inspect(bigDecimal, { numericSeparator: true })); + * // 1_234.123_45 + * ``` + * + * `util.inspect()` is a synchronous method intended for debugging. Its maximum + * output length is approximately 128 MiB. Inputs that result in longer output will + * be truncated. + * @since v0.3.0 + * @param object Any JavaScript primitive or `Object`. + * @return The representation of `object`. + */ + export function inspect(object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; + export function inspect(object: any, options?: InspectOptions): string; + export namespace inspect { + let colors: NodeJS.Dict<[number, number]>; + let styles: { + [K in Style]: string; + }; + let defaultOptions: InspectOptions; + /** + * Allows changing inspect settings from the repl. + */ + let replDefaults: InspectOptions; + /** + * That can be used to declare custom inspect functions. + */ + const custom: unique symbol; + } + /** + * Alias for [`Array.isArray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray). + * + * Returns `true` if the given `object` is an `Array`. Otherwise, returns `false`. + * + * ```js + * const util = require('node:util'); + * + * util.isArray([]); + * // Returns: true + * util.isArray(new Array()); + * // Returns: true + * util.isArray({}); + * // Returns: false + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Use `isArray` instead. + */ + export function isArray(object: unknown): object is unknown[]; + /** + * Returns `true` if the given `object` is a `RegExp`. Otherwise, returns `false`. + * + * ```js + * const util = require('node:util'); + * + * util.isRegExp(/some regexp/); + * // Returns: true + * util.isRegExp(new RegExp('another regexp')); + * // Returns: true + * util.isRegExp({}); + * // Returns: false + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Deprecated + */ + export function isRegExp(object: unknown): object is RegExp; + /** + * Returns `true` if the given `object` is a `Date`. Otherwise, returns `false`. + * + * ```js + * const util = require('node:util'); + * + * util.isDate(new Date()); + * // Returns: true + * util.isDate(Date()); + * // false (without 'new' returns a String) + * util.isDate({}); + * // Returns: false + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Use {@link types.isDate} instead. + */ + export function isDate(object: unknown): object is Date; + /** + * Returns `true` if the given `object` is an `Error`. Otherwise, returns `false`. + * + * ```js + * const util = require('node:util'); + * + * util.isError(new Error()); + * // Returns: true + * util.isError(new TypeError()); + * // Returns: true + * util.isError({ name: 'Error', message: 'an error occurred' }); + * // Returns: false + * ``` + * + * This method relies on `Object.prototype.toString()` behavior. It is + * possible to obtain an incorrect result when the `object` argument manipulates `@@toStringTag`. + * + * ```js + * const util = require('node:util'); + * const obj = { name: 'Error', message: 'an error occurred' }; + * + * util.isError(obj); + * // Returns: false + * obj[Symbol.toStringTag] = 'Error'; + * util.isError(obj); + * // Returns: true + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Use {@link types.isNativeError} instead. + */ + export function isError(object: unknown): object is Error; + /** + * Usage of `util.inherits()` is discouraged. Please use the ES6 `class` and `extends` keywords to get language level inheritance support. Also note + * that the two styles are [semantically incompatible](https://github.com/nodejs/node/issues/4179). + * + * Inherit the prototype methods from one [constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor) into another. The + * prototype of `constructor` will be set to a new object created from `superConstructor`. + * + * This mainly adds some input validation on top of`Object.setPrototypeOf(constructor.prototype, superConstructor.prototype)`. + * As an additional convenience, `superConstructor` will be accessible + * through the `constructor.super_` property. + * + * ```js + * const util = require('node:util'); + * const EventEmitter = require('node:events'); + * + * function MyStream() { + * EventEmitter.call(this); + * } + * + * util.inherits(MyStream, EventEmitter); + * + * MyStream.prototype.write = function(data) { + * this.emit('data', data); + * }; + * + * const stream = new MyStream(); + * + * console.log(stream instanceof EventEmitter); // true + * console.log(MyStream.super_ === EventEmitter); // true + * + * stream.on('data', (data) => { + * console.log(`Received data: "${data}"`); + * }); + * stream.write('It works!'); // Received data: "It works!" + * ``` + * + * ES6 example using `class` and `extends`: + * + * ```js + * const EventEmitter = require('node:events'); + * + * class MyStream extends EventEmitter { + * write(data) { + * this.emit('data', data); + * } + * } + * + * const stream = new MyStream(); + * + * stream.on('data', (data) => { + * console.log(`Received data: "${data}"`); + * }); + * stream.write('With ES6'); + * ``` + * @since v0.3.0 + * @legacy Use ES2015 class syntax and `extends` keyword instead. + */ + export function inherits(constructor: unknown, superConstructor: unknown): void; + export type DebugLoggerFunction = (msg: string, ...param: unknown[]) => void; + export interface DebugLogger extends DebugLoggerFunction { + enabled: boolean; + } + /** + * The `util.debuglog()` method is used to create a function that conditionally + * writes debug messages to `stderr` based on the existence of the `NODE_DEBUG`environment variable. If the `section` name appears within the value of that + * environment variable, then the returned function operates similar to `console.error()`. If not, then the returned function is a no-op. + * + * ```js + * const util = require('node:util'); + * const debuglog = util.debuglog('foo'); + * + * debuglog('hello from foo [%d]', 123); + * ``` + * + * If this program is run with `NODE_DEBUG=foo` in the environment, then + * it will output something like: + * + * ```console + * FOO 3245: hello from foo [123] + * ``` + * + * where `3245` is the process id. If it is not run with that + * environment variable set, then it will not print anything. + * + * The `section` supports wildcard also: + * + * ```js + * const util = require('node:util'); + * const debuglog = util.debuglog('foo-bar'); + * + * debuglog('hi there, it\'s foo-bar [%d]', 2333); + * ``` + * + * if it is run with `NODE_DEBUG=foo*` in the environment, then it will output + * something like: + * + * ```console + * FOO-BAR 3257: hi there, it's foo-bar [2333] + * ``` + * + * Multiple comma-separated `section` names may be specified in the `NODE_DEBUG`environment variable: `NODE_DEBUG=fs,net,tls`. + * + * The optional `callback` argument can be used to replace the logging function + * with a different function that doesn't have any initialization or + * unnecessary wrapping. + * + * ```js + * const util = require('node:util'); + * let debuglog = util.debuglog('internals', (debug) => { + * // Replace with a logging function that optimizes out + * // testing if the section is enabled + * debuglog = debug; + * }); + * ``` + * @since v0.11.3 + * @param section A string identifying the portion of the application for which the `debuglog` function is being created. + * @param callback A callback invoked the first time the logging function is called with a function argument that is a more optimized logging function. + * @return The logging function + */ + export function debuglog(section: string, callback?: (fn: DebugLoggerFunction) => void): DebugLogger; + export const debug: typeof debuglog; + /** + * Returns `true` if the given `object` is a `Boolean`. Otherwise, returns `false`. + * + * ```js + * const util = require('node:util'); + * + * util.isBoolean(1); + * // Returns: false + * util.isBoolean(0); + * // Returns: false + * util.isBoolean(false); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'boolean'` instead. + */ + export function isBoolean(object: unknown): object is boolean; + /** + * Returns `true` if the given `object` is a `Buffer`. Otherwise, returns `false`. + * + * ```js + * const util = require('node:util'); + * + * util.isBuffer({ length: 0 }); + * // Returns: false + * util.isBuffer([]); + * // Returns: false + * util.isBuffer(Buffer.from('hello world')); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `isBuffer` instead. + */ + export function isBuffer(object: unknown): object is Buffer; + /** + * Returns `true` if the given `object` is a `Function`. Otherwise, returns `false`. + * + * ```js + * const util = require('node:util'); + * + * function Foo() {} + * const Bar = () => {}; + * + * util.isFunction({}); + * // Returns: false + * util.isFunction(Foo); + * // Returns: true + * util.isFunction(Bar); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'function'` instead. + */ + export function isFunction(object: unknown): boolean; + /** + * Returns `true` if the given `object` is strictly `null`. Otherwise, returns`false`. + * + * ```js + * const util = require('node:util'); + * + * util.isNull(0); + * // Returns: false + * util.isNull(undefined); + * // Returns: false + * util.isNull(null); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value === null` instead. + */ + export function isNull(object: unknown): object is null; + /** + * Returns `true` if the given `object` is `null` or `undefined`. Otherwise, + * returns `false`. + * + * ```js + * const util = require('node:util'); + * + * util.isNullOrUndefined(0); + * // Returns: false + * util.isNullOrUndefined(undefined); + * // Returns: true + * util.isNullOrUndefined(null); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value === undefined || value === null` instead. + */ + export function isNullOrUndefined(object: unknown): object is null | undefined; + /** + * Returns `true` if the given `object` is a `Number`. Otherwise, returns `false`. + * + * ```js + * const util = require('node:util'); + * + * util.isNumber(false); + * // Returns: false + * util.isNumber(Infinity); + * // Returns: true + * util.isNumber(0); + * // Returns: true + * util.isNumber(NaN); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'number'` instead. + */ + export function isNumber(object: unknown): object is number; + /** + * Returns `true` if the given `object` is strictly an `Object`**and** not a`Function` (even though functions are objects in JavaScript). + * Otherwise, returns `false`. + * + * ```js + * const util = require('node:util'); + * + * util.isObject(5); + * // Returns: false + * util.isObject(null); + * // Returns: false + * util.isObject({}); + * // Returns: true + * util.isObject(() => {}); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value !== null && typeof value === 'object'` instead. + */ + export function isObject(object: unknown): boolean; + /** + * Returns `true` if the given `object` is a primitive type. Otherwise, returns`false`. + * + * ```js + * const util = require('node:util'); + * + * util.isPrimitive(5); + * // Returns: true + * util.isPrimitive('foo'); + * // Returns: true + * util.isPrimitive(false); + * // Returns: true + * util.isPrimitive(null); + * // Returns: true + * util.isPrimitive(undefined); + * // Returns: true + * util.isPrimitive({}); + * // Returns: false + * util.isPrimitive(() => {}); + * // Returns: false + * util.isPrimitive(/^$/); + * // Returns: false + * util.isPrimitive(new Date()); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `(typeof value !== 'object' && typeof value !== 'function') || value === null` instead. + */ + export function isPrimitive(object: unknown): boolean; + /** + * Returns `true` if the given `object` is a `string`. Otherwise, returns `false`. + * + * ```js + * const util = require('node:util'); + * + * util.isString(''); + * // Returns: true + * util.isString('foo'); + * // Returns: true + * util.isString(String('foo')); + * // Returns: true + * util.isString(5); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'string'` instead. + */ + export function isString(object: unknown): object is string; + /** + * Returns `true` if the given `object` is a `Symbol`. Otherwise, returns `false`. + * + * ```js + * const util = require('node:util'); + * + * util.isSymbol(5); + * // Returns: false + * util.isSymbol('foo'); + * // Returns: false + * util.isSymbol(Symbol('foo')); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'symbol'` instead. + */ + export function isSymbol(object: unknown): object is symbol; + /** + * Returns `true` if the given `object` is `undefined`. Otherwise, returns `false`. + * + * ```js + * const util = require('node:util'); + * + * const foo = undefined; + * util.isUndefined(5); + * // Returns: false + * util.isUndefined(foo); + * // Returns: true + * util.isUndefined(null); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value === undefined` instead. + */ + export function isUndefined(object: unknown): object is undefined; + /** + * The `util.deprecate()` method wraps `fn` (which may be a function or class) in + * such a way that it is marked as deprecated. + * + * ```js + * const util = require('node:util'); + * + * exports.obsoleteFunction = util.deprecate(() => { + * // Do something here. + * }, 'obsoleteFunction() is deprecated. Use newShinyFunction() instead.'); + * ``` + * + * When called, `util.deprecate()` will return a function that will emit a `DeprecationWarning` using the `'warning'` event. The warning will + * be emitted and printed to `stderr` the first time the returned function is + * called. After the warning is emitted, the wrapped function is called without + * emitting a warning. + * + * If the same optional `code` is supplied in multiple calls to `util.deprecate()`, + * the warning will be emitted only once for that `code`. + * + * ```js + * const util = require('node:util'); + * + * const fn1 = util.deprecate(someFunction, someMessage, 'DEP0001'); + * const fn2 = util.deprecate(someOtherFunction, someOtherMessage, 'DEP0001'); + * fn1(); // Emits a deprecation warning with code DEP0001 + * fn2(); // Does not emit a deprecation warning because it has the same code + * ``` + * + * If either the `--no-deprecation` or `--no-warnings` command-line flags are + * used, or if the `process.noDeprecation` property is set to `true`_prior_ to + * the first deprecation warning, the `util.deprecate()` method does nothing. + * + * If the `--trace-deprecation` or `--trace-warnings` command-line flags are set, + * or the `process.traceDeprecation` property is set to `true`, a warning and a + * stack trace are printed to `stderr` the first time the deprecated function is + * called. + * + * If the `--throw-deprecation` command-line flag is set, or the `process.throwDeprecation` property is set to `true`, then an exception will be + * thrown when the deprecated function is called. + * + * The `--throw-deprecation` command-line flag and `process.throwDeprecation` property take precedence over `--trace-deprecation` and `process.traceDeprecation`. + * @since v0.8.0 + * @param fn The function that is being deprecated. + * @param msg A warning message to display when the deprecated function is invoked. + * @param code A deprecation code. See the `list of deprecated APIs` for a list of codes. + * @return The deprecated function wrapped to emit a warning. + */ + export function deprecate(fn: T, msg: string, code?: string): T; + /** + * Returns `true` if there is deep strict equality between `val1` and `val2`. + * Otherwise, returns `false`. + * + * See `assert.deepStrictEqual()` for more information about deep strict + * equality. + * @since v9.0.0 + */ + export function isDeepStrictEqual(val1: unknown, val2: unknown): boolean; + /** + * Returns `str` with any ANSI escape codes removed. + * + * ```js + * console.log(util.stripVTControlCharacters('\u001B[4mvalue\u001B[0m')); + * // Prints "value" + * ``` + * @since v16.11.0 + */ + export function stripVTControlCharacters(str: string): string; + /** + * Takes an `async` function (or a function that returns a `Promise`) and returns a + * function following the error-first callback style, i.e. taking + * an `(err, value) => ...` callback as the last argument. In the callback, the + * first argument will be the rejection reason (or `null` if the `Promise` resolved), and the second argument will be the resolved value. + * + * ```js + * const util = require('node:util'); + * + * async function fn() { + * return 'hello world'; + * } + * const callbackFunction = util.callbackify(fn); + * + * callbackFunction((err, ret) => { + * if (err) throw err; + * console.log(ret); + * }); + * ``` + * + * Will print: + * + * ```text + * hello world + * ``` + * + * The callback is executed asynchronously, and will have a limited stack trace. + * If the callback throws, the process will emit an `'uncaughtException'` event, and if not handled will exit. + * + * Since `null` has a special meaning as the first argument to a callback, if a + * wrapped function rejects a `Promise` with a falsy value as a reason, the value + * is wrapped in an `Error` with the original value stored in a field named `reason`. + * + * ```js + * function fn() { + * return Promise.reject(null); + * } + * const callbackFunction = util.callbackify(fn); + * + * callbackFunction((err, ret) => { + * // When the Promise was rejected with `null` it is wrapped with an Error and + * // the original value is stored in `reason`. + * err && Object.hasOwn(err, 'reason') && err.reason === null; // true + * }); + * ``` + * @since v8.2.0 + * @param fn An `async` function + * @return a callback style function + */ + export function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: () => Promise, + ): (callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1) => Promise, + ): (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1) => Promise, + ): (arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2) => Promise, + ): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2) => Promise, + ): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + callback: (err: NodeJS.ErrnoException | null, result: TResult) => void, + ) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + arg5: T5, + callback: (err: NodeJS.ErrnoException | null, result: TResult) => void, + ) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + arg5: T5, + arg6: T6, + callback: (err: NodeJS.ErrnoException) => void, + ) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + arg5: T5, + arg6: T6, + callback: (err: NodeJS.ErrnoException | null, result: TResult) => void, + ) => void; + export interface CustomPromisifyLegacy extends Function { + __promisify__: TCustom; + } + export interface CustomPromisifySymbol extends Function { + [promisify.custom]: TCustom; + } + export type CustomPromisify = + | CustomPromisifySymbol + | CustomPromisifyLegacy; + /** + * Takes a function following the common error-first callback style, i.e. taking + * an `(err, value) => ...` callback as the last argument, and returns a version + * that returns promises. + * + * ```js + * const util = require('node:util'); + * const fs = require('node:fs'); + * + * const stat = util.promisify(fs.stat); + * stat('.').then((stats) => { + * // Do something with `stats` + * }).catch((error) => { + * // Handle the error. + * }); + * ``` + * + * Or, equivalently using `async function`s: + * + * ```js + * const util = require('node:util'); + * const fs = require('node:fs'); + * + * const stat = util.promisify(fs.stat); + * + * async function callStat() { + * const stats = await stat('.'); + * console.log(`This directory is owned by ${stats.uid}`); + * } + * + * callStat(); + * ``` + * + * If there is an `original[util.promisify.custom]` property present, `promisify` will return its value, see `Custom promisified functions`. + * + * `promisify()` assumes that `original` is a function taking a callback as its + * final argument in all cases. If `original` is not a function, `promisify()` will throw an error. If `original` is a function but its last argument is not + * an error-first callback, it will still be passed an error-first + * callback as its last argument. + * + * Using `promisify()` on class methods or other methods that use `this` may not + * work as expected unless handled specially: + * + * ```js + * const util = require('node:util'); + * + * class Foo { + * constructor() { + * this.a = 42; + * } + * + * bar(callback) { + * callback(null, this.a); + * } + * } + * + * const foo = new Foo(); + * + * const naiveBar = util.promisify(foo.bar); + * // TypeError: Cannot read property 'a' of undefined + * // naiveBar().then(a => console.log(a)); + * + * naiveBar.call(foo).then((a) => console.log(a)); // '42' + * + * const bindBar = naiveBar.bind(foo); + * bindBar().then((a) => console.log(a)); // '42' + * ``` + * @since v8.0.0 + */ + export function promisify(fn: CustomPromisify): TCustom; + export function promisify( + fn: (callback: (err: any, result: TResult) => void) => void, + ): () => Promise; + export function promisify(fn: (callback: (err?: any) => void) => void): () => Promise; + export function promisify( + fn: (arg1: T1, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1) => Promise; + export function promisify(fn: (arg1: T1, callback: (err?: any) => void) => void): (arg1: T1) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + export function promisify(fn: Function): Function; + export namespace promisify { + /** + * That can be used to declare custom promisified variants of functions. + */ + const custom: unique symbol; + } + /** + * Stability: 1.1 - Active development + * Given an example `.env` file: + * + * ```js + * const { parseEnv } = require('node:util'); + * + * parseEnv('HELLO=world\nHELLO=oh my\n'); + * // Returns: { HELLO: 'oh my' } + * ``` + * @param content The raw contents of a `.env` file. + * @since v20.12.0 + */ + export function parseEnv(content: string): object; + // https://nodejs.org/docs/latest/api/util.html#foreground-colors + type ForegroundColors = + | "black" + | "blackBright" + | "blue" + | "blueBright" + | "cyan" + | "cyanBright" + | "gray" + | "green" + | "greenBright" + | "grey" + | "magenta" + | "magentaBright" + | "red" + | "redBright" + | "white" + | "whiteBright" + | "yellow" + | "yellowBright"; + // https://nodejs.org/docs/latest/api/util.html#background-colors + type BackgroundColors = + | "bgBlack" + | "bgBlackBright" + | "bgBlue" + | "bgBlueBright" + | "bgCyan" + | "bgCyanBright" + | "bgGray" + | "bgGreen" + | "bgGreenBright" + | "bgGrey" + | "bgMagenta" + | "bgMagentaBright" + | "bgRed" + | "bgRedBright" + | "bgWhite" + | "bgWhiteBright" + | "bgYellow" + | "bgYellowBright"; + // https://nodejs.org/docs/latest/api/util.html#modifiers + type Modifiers = + | "blink" + | "bold" + | "dim" + | "doubleunderline" + | "framed" + | "hidden" + | "inverse" + | "italic" + | "overlined" + | "reset" + | "strikethrough" + | "underline"; + /** + * Stability: 1.1 - Active development + * + * This function returns a formatted text considering the `format` passed. + * + * ```js + * const { styleText } = require('node:util'); + * const errorMessage = styleText('red', 'Error! Error!'); + * console.log(errorMessage); + * ``` + * + * `util.inspect.colors` also provides text formats such as `italic`, and `underline` and you can combine both: + * + * ```js + * console.log( + * util.styleText(['underline', 'italic'], 'My italic underlined message'), + * ); + * ``` + * + * When passing an array of formats, the order of the format applied is left to right so the following style + * might overwrite the previous one. + * + * ```js + * console.log( + * util.styleText(['red', 'green'], 'text'), // green + * ); + * ``` + * + * The full list of formats can be found in [modifiers](https://nodejs.org/docs/latest-v22.x/api/util.html#modifiers). + * @param format A text format or an Array of text formats defined in `util.inspect.colors`. + * @param text The text to to be formatted. + * @since v20.12.0 + */ + export function styleText( + format: + | ForegroundColors + | BackgroundColors + | Modifiers + | Array, + text: string, + ): string; + /** + * An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextDecoder` API. + * + * ```js + * const decoder = new TextDecoder(); + * const u8arr = new Uint8Array([72, 101, 108, 108, 111]); + * console.log(decoder.decode(u8arr)); // Hello + * ``` + * @since v8.3.0 + */ + export class TextDecoder { + /** + * The encoding supported by the `TextDecoder` instance. + */ + readonly encoding: string; + /** + * The value will be `true` if decoding errors result in a `TypeError` being + * thrown. + */ + readonly fatal: boolean; + /** + * The value will be `true` if the decoding result will include the byte order + * mark. + */ + readonly ignoreBOM: boolean; + constructor( + encoding?: string, + options?: { + fatal?: boolean | undefined; + ignoreBOM?: boolean | undefined; + }, + ); + /** + * Decodes the `input` and returns a string. If `options.stream` is `true`, any + * incomplete byte sequences occurring at the end of the `input` are buffered + * internally and emitted after the next call to `textDecoder.decode()`. + * + * If `textDecoder.fatal` is `true`, decoding errors that occur will result in a `TypeError` being thrown. + * @param input An `ArrayBuffer`, `DataView`, or `TypedArray` instance containing the encoded data. + */ + decode( + input?: NodeJS.ArrayBufferView | ArrayBuffer | null, + options?: { + stream?: boolean | undefined; + }, + ): string; + } + export interface EncodeIntoResult { + /** + * The read Unicode code units of input. + */ + read: number; + /** + * The written UTF-8 bytes of output. + */ + written: number; + } + export { types }; + + //// TextEncoder/Decoder + /** + * An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextEncoder` API. All + * instances of `TextEncoder` only support UTF-8 encoding. + * + * ```js + * const encoder = new TextEncoder(); + * const uint8array = encoder.encode('this is some data'); + * ``` + * + * The `TextEncoder` class is also available on the global object. + * @since v8.3.0 + */ + export class TextEncoder { + /** + * The encoding supported by the `TextEncoder` instance. Always set to `'utf-8'`. + */ + readonly encoding: string; + /** + * UTF-8 encodes the `input` string and returns a `Uint8Array` containing the + * encoded bytes. + * @param [input='an empty string'] The text to encode. + */ + encode(input?: string): Uint8Array; + /** + * UTF-8 encodes the `src` string to the `dest` Uint8Array and returns an object + * containing the read Unicode code units and written UTF-8 bytes. + * + * ```js + * const encoder = new TextEncoder(); + * const src = 'this is some data'; + * const dest = new Uint8Array(10); + * const { read, written } = encoder.encodeInto(src, dest); + * ``` + * @param src The text to encode. + * @param dest The array to hold the encode result. + */ + encodeInto(src: string, dest: Uint8Array): EncodeIntoResult; + } + import { TextDecoder as _TextDecoder, TextEncoder as _TextEncoder } from "util"; + global { + /** + * `TextDecoder` class is a global reference for `require('util').TextDecoder` + * https://nodejs.org/api/globals.html#textdecoder + * @since v11.0.0 + */ + var TextDecoder: typeof globalThis extends { + onmessage: any; + TextDecoder: infer TextDecoder; + } ? TextDecoder + : typeof _TextDecoder; + /** + * `TextEncoder` class is a global reference for `require('util').TextEncoder` + * https://nodejs.org/api/globals.html#textencoder + * @since v11.0.0 + */ + var TextEncoder: typeof globalThis extends { + onmessage: any; + TextEncoder: infer TextEncoder; + } ? TextEncoder + : typeof _TextEncoder; + } + + //// parseArgs + /** + * Provides a higher level API for command-line argument parsing than interacting + * with `process.argv` directly. Takes a specification for the expected arguments + * and returns a structured object with the parsed options and positionals. + * + * ```js + * import { parseArgs } from 'node:util'; + * const args = ['-f', '--bar', 'b']; + * const options = { + * foo: { + * type: 'boolean', + * short: 'f', + * }, + * bar: { + * type: 'string', + * }, + * }; + * const { + * values, + * positionals, + * } = parseArgs({ args, options }); + * console.log(values, positionals); + * // Prints: [Object: null prototype] { foo: true, bar: 'b' } [] + * ``` + * @since v18.3.0, v16.17.0 + * @param config Used to provide arguments for parsing and to configure the parser. `config` supports the following properties: + * @return The parsed command line arguments: + */ + export function parseArgs(config?: T): ParsedResults; + interface ParseArgsOptionConfig { + /** + * Type of argument. + */ + type: "string" | "boolean"; + /** + * Whether this option can be provided multiple times. + * If `true`, all values will be collected in an array. + * If `false`, values for the option are last-wins. + * @default false. + */ + multiple?: boolean | undefined; + /** + * A single character alias for the option. + */ + short?: string | undefined; + /** + * The default option value when it is not set by args. + * It must be of the same type as the the `type` property. + * When `multiple` is `true`, it must be an array. + * @since v18.11.0 + */ + default?: string | boolean | string[] | boolean[] | undefined; + } + interface ParseArgsOptionsConfig { + [longOption: string]: ParseArgsOptionConfig; + } + export interface ParseArgsConfig { + /** + * Array of argument strings. + */ + args?: string[] | undefined; + /** + * Used to describe arguments known to the parser. + */ + options?: ParseArgsOptionsConfig | undefined; + /** + * Should an error be thrown when unknown arguments are encountered, + * or when arguments are passed that do not match the `type` configured in `options`. + * @default true + */ + strict?: boolean | undefined; + /** + * Whether this command accepts positional arguments. + */ + allowPositionals?: boolean | undefined; + /** + * If `true`, allows explicitly setting boolean options to `false` by prefixing the option name with `--no-`. + * @default false + * @since v22.4.0 + */ + allowNegative?: boolean | undefined; + /** + * Return the parsed tokens. This is useful for extending the built-in behavior, + * from adding additional checks through to reprocessing the tokens in different ways. + * @default false + */ + tokens?: boolean | undefined; + } + /* + IfDefaultsTrue and IfDefaultsFalse are helpers to handle default values for missing boolean properties. + TypeScript does not have exact types for objects: https://github.com/microsoft/TypeScript/issues/12936 + This means it is impossible to distinguish between "field X is definitely not present" and "field X may or may not be present". + But we expect users to generally provide their config inline or `as const`, which means TS will always know whether a given field is present. + So this helper treats "not definitely present" (i.e., not `extends boolean`) as being "definitely not present", i.e. it should have its default value. + This is technically incorrect but is a much nicer UX for the common case. + The IfDefaultsTrue version is for things which default to true; the IfDefaultsFalse version is for things which default to false. + */ + type IfDefaultsTrue = T extends true ? IfTrue + : T extends false ? IfFalse + : IfTrue; + + // we put the `extends false` condition first here because `undefined` compares like `any` when `strictNullChecks: false` + type IfDefaultsFalse = T extends false ? IfFalse + : T extends true ? IfTrue + : IfFalse; + + type ExtractOptionValue = IfDefaultsTrue< + T["strict"], + O["type"] extends "string" ? string : O["type"] extends "boolean" ? boolean : string | boolean, + string | boolean + >; + + type ParsedValues = + & IfDefaultsTrue + & (T["options"] extends ParseArgsOptionsConfig ? { + -readonly [LongOption in keyof T["options"]]: IfDefaultsFalse< + T["options"][LongOption]["multiple"], + undefined | Array>, + undefined | ExtractOptionValue + >; + } + : {}); + + type ParsedPositionals = IfDefaultsTrue< + T["strict"], + IfDefaultsFalse, + IfDefaultsTrue + >; + + type PreciseTokenForOptions< + K extends string, + O extends ParseArgsOptionConfig, + > = O["type"] extends "string" ? { + kind: "option"; + index: number; + name: K; + rawName: string; + value: string; + inlineValue: boolean; + } + : O["type"] extends "boolean" ? { + kind: "option"; + index: number; + name: K; + rawName: string; + value: undefined; + inlineValue: undefined; + } + : OptionToken & { name: K }; + + type TokenForOptions< + T extends ParseArgsConfig, + K extends keyof T["options"] = keyof T["options"], + > = K extends unknown + ? T["options"] extends ParseArgsOptionsConfig ? PreciseTokenForOptions + : OptionToken + : never; + + type ParsedOptionToken = IfDefaultsTrue, OptionToken>; + + type ParsedPositionalToken = IfDefaultsTrue< + T["strict"], + IfDefaultsFalse, + IfDefaultsTrue + >; + + type ParsedTokens = Array< + ParsedOptionToken | ParsedPositionalToken | { kind: "option-terminator"; index: number } + >; + + type PreciseParsedResults = IfDefaultsFalse< + T["tokens"], + { + values: ParsedValues; + positionals: ParsedPositionals; + tokens: ParsedTokens; + }, + { + values: ParsedValues; + positionals: ParsedPositionals; + } + >; + + type OptionToken = + | { kind: "option"; index: number; name: string; rawName: string; value: string; inlineValue: boolean } + | { + kind: "option"; + index: number; + name: string; + rawName: string; + value: undefined; + inlineValue: undefined; + }; + + type Token = + | OptionToken + | { kind: "positional"; index: number; value: string } + | { kind: "option-terminator"; index: number }; + + // If ParseArgsConfig extends T, then the user passed config constructed elsewhere. + // So we can't rely on the `"not definitely present" implies "definitely not present"` assumption mentioned above. + type ParsedResults = ParseArgsConfig extends T ? { + values: { + [longOption: string]: undefined | string | boolean | Array; + }; + positionals: string[]; + tokens?: Token[]; + } + : PreciseParsedResults; + + /** + * An implementation of [the MIMEType class](https://bmeck.github.io/node-proposal-mime-api/). + * + * In accordance with browser conventions, all properties of `MIMEType` objects + * are implemented as getters and setters on the class prototype, rather than as + * data properties on the object itself. + * + * A MIME string is a structured string containing multiple meaningful + * components. When parsed, a `MIMEType` object is returned containing + * properties for each of these components. + * @since v19.1.0, v18.13.0 + * @experimental + */ + export class MIMEType { + /** + * Creates a new MIMEType object by parsing the input. + * + * A `TypeError` will be thrown if the `input` is not a valid MIME. + * Note that an effort will be made to coerce the given values into strings. + * @param input The input MIME to parse. + */ + constructor(input: string | { toString: () => string }); + + /** + * Gets and sets the type portion of the MIME. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const myMIME = new MIMEType('text/javascript'); + * console.log(myMIME.type); + * // Prints: text + * myMIME.type = 'application'; + * console.log(myMIME.type); + * // Prints: application + * console.log(String(myMIME)); + * // Prints: application/javascript + * ``` + */ + type: string; + /** + * Gets and sets the subtype portion of the MIME. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const myMIME = new MIMEType('text/ecmascript'); + * console.log(myMIME.subtype); + * // Prints: ecmascript + * myMIME.subtype = 'javascript'; + * console.log(myMIME.subtype); + * // Prints: javascript + * console.log(String(myMIME)); + * // Prints: text/javascript + * ``` + */ + subtype: string; + /** + * Gets the essence of the MIME. This property is read only. + * Use `mime.type` or `mime.subtype` to alter the MIME. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const myMIME = new MIMEType('text/javascript;key=value'); + * console.log(myMIME.essence); + * // Prints: text/javascript + * myMIME.type = 'application'; + * console.log(myMIME.essence); + * // Prints: application/javascript + * console.log(String(myMIME)); + * // Prints: application/javascript;key=value + * ``` + */ + readonly essence: string; + /** + * Gets the `MIMEParams` object representing the + * parameters of the MIME. This property is read-only. See `MIMEParams` documentation for details. + */ + readonly params: MIMEParams; + /** + * The `toString()` method on the `MIMEType` object returns the serialized MIME. + * + * Because of the need for standard compliance, this method does not allow users + * to customize the serialization process of the MIME. + */ + toString(): string; + } + /** + * The `MIMEParams` API provides read and write access to the parameters of a `MIMEType`. + * @since v19.1.0, v18.13.0 + */ + export class MIMEParams { + /** + * Remove all name-value pairs whose name is `name`. + */ + delete(name: string): void; + /** + * Returns an iterator over each of the name-value pairs in the parameters. + * Each item of the iterator is a JavaScript `Array`. The first item of the array + * is the `name`, the second item of the array is the `value`. + */ + entries(): IterableIterator<[name: string, value: string]>; + /** + * Returns the value of the first name-value pair whose name is `name`. If there + * are no such pairs, `null` is returned. + * @return or `null` if there is no name-value pair with the given `name`. + */ + get(name: string): string | null; + /** + * Returns `true` if there is at least one name-value pair whose name is `name`. + */ + has(name: string): boolean; + /** + * Returns an iterator over the names of each name-value pair. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const { params } = new MIMEType('text/plain;foo=0;bar=1'); + * for (const name of params.keys()) { + * console.log(name); + * } + * // Prints: + * // foo + * // bar + * ``` + */ + keys(): IterableIterator; + /** + * Sets the value in the `MIMEParams` object associated with `name` to `value`. If there are any pre-existing name-value pairs whose names are `name`, + * set the first such pair's value to `value`. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const { params } = new MIMEType('text/plain;foo=0;bar=1'); + * params.set('foo', 'def'); + * params.set('baz', 'xyz'); + * console.log(params.toString()); + * // Prints: foo=def;bar=1;baz=xyz + * ``` + */ + set(name: string, value: string): void; + /** + * Returns an iterator over the values of each name-value pair. + */ + values(): IterableIterator; + /** + * Returns an iterator over each of the name-value pairs in the parameters. + */ + [Symbol.iterator]: typeof MIMEParams.prototype.entries; + } +} +declare module "util/types" { + import { KeyObject, webcrypto } from "node:crypto"; + /** + * Returns `true` if the value is a built-in [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) or + * [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instance. + * + * See also `util.types.isArrayBuffer()` and `util.types.isSharedArrayBuffer()`. + * + * ```js + * util.types.isAnyArrayBuffer(new ArrayBuffer()); // Returns true + * util.types.isAnyArrayBuffer(new SharedArrayBuffer()); // Returns true + * ``` + * @since v10.0.0 + */ + function isAnyArrayBuffer(object: unknown): object is ArrayBufferLike; + /** + * Returns `true` if the value is an `arguments` object. + * + * ```js + * function foo() { + * util.types.isArgumentsObject(arguments); // Returns true + * } + * ``` + * @since v10.0.0 + */ + function isArgumentsObject(object: unknown): object is IArguments; + /** + * Returns `true` if the value is a built-in [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) instance. + * This does _not_ include [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instances. Usually, it is + * desirable to test for both; See `util.types.isAnyArrayBuffer()` for that. + * + * ```js + * util.types.isArrayBuffer(new ArrayBuffer()); // Returns true + * util.types.isArrayBuffer(new SharedArrayBuffer()); // Returns false + * ``` + * @since v10.0.0 + */ + function isArrayBuffer(object: unknown): object is ArrayBuffer; + /** + * Returns `true` if the value is an instance of one of the [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) views, such as typed + * array objects or [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView). Equivalent to + * [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * + * ```js + * util.types.isArrayBufferView(new Int8Array()); // true + * util.types.isArrayBufferView(Buffer.from('hello world')); // true + * util.types.isArrayBufferView(new DataView(new ArrayBuffer(16))); // true + * util.types.isArrayBufferView(new ArrayBuffer()); // false + * ``` + * @since v10.0.0 + */ + function isArrayBufferView(object: unknown): object is NodeJS.ArrayBufferView; + /** + * Returns `true` if the value is an [async function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function). + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * util.types.isAsyncFunction(function foo() {}); // Returns false + * util.types.isAsyncFunction(async function foo() {}); // Returns true + * ``` + * @since v10.0.0 + */ + function isAsyncFunction(object: unknown): boolean; + /** + * Returns `true` if the value is a `BigInt64Array` instance. + * + * ```js + * util.types.isBigInt64Array(new BigInt64Array()); // Returns true + * util.types.isBigInt64Array(new BigUint64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isBigInt64Array(value: unknown): value is BigInt64Array; + /** + * Returns `true` if the value is a `BigUint64Array` instance. + * + * ```js + * util.types.isBigUint64Array(new BigInt64Array()); // Returns false + * util.types.isBigUint64Array(new BigUint64Array()); // Returns true + * ``` + * @since v10.0.0 + */ + function isBigUint64Array(value: unknown): value is BigUint64Array; + /** + * Returns `true` if the value is a boolean object, e.g. created + * by `new Boolean()`. + * + * ```js + * util.types.isBooleanObject(false); // Returns false + * util.types.isBooleanObject(true); // Returns false + * util.types.isBooleanObject(new Boolean(false)); // Returns true + * util.types.isBooleanObject(new Boolean(true)); // Returns true + * util.types.isBooleanObject(Boolean(false)); // Returns false + * util.types.isBooleanObject(Boolean(true)); // Returns false + * ``` + * @since v10.0.0 + */ + function isBooleanObject(object: unknown): object is Boolean; + /** + * Returns `true` if the value is any boxed primitive object, e.g. created + * by `new Boolean()`, `new String()` or `Object(Symbol())`. + * + * For example: + * + * ```js + * util.types.isBoxedPrimitive(false); // Returns false + * util.types.isBoxedPrimitive(new Boolean(false)); // Returns true + * util.types.isBoxedPrimitive(Symbol('foo')); // Returns false + * util.types.isBoxedPrimitive(Object(Symbol('foo'))); // Returns true + * util.types.isBoxedPrimitive(Object(BigInt(5))); // Returns true + * ``` + * @since v10.11.0 + */ + function isBoxedPrimitive(object: unknown): object is String | Number | BigInt | Boolean | Symbol; + /** + * Returns `true` if the value is a built-in [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) instance. + * + * ```js + * const ab = new ArrayBuffer(20); + * util.types.isDataView(new DataView(ab)); // Returns true + * util.types.isDataView(new Float64Array()); // Returns false + * ``` + * + * See also [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * @since v10.0.0 + */ + function isDataView(object: unknown): object is DataView; + /** + * Returns `true` if the value is a built-in [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) instance. + * + * ```js + * util.types.isDate(new Date()); // Returns true + * ``` + * @since v10.0.0 + */ + function isDate(object: unknown): object is Date; + /** + * Returns `true` if the value is a native `External` value. + * + * A native `External` value is a special type of object that contains a + * raw C++ pointer (`void*`) for access from native code, and has no other + * properties. Such objects are created either by Node.js internals or native + * addons. In JavaScript, they are [frozen](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) objects with a`null` prototype. + * + * ```c + * #include + * #include + * napi_value result; + * static napi_value MyNapi(napi_env env, napi_callback_info info) { + * int* raw = (int*) malloc(1024); + * napi_status status = napi_create_external(env, (void*) raw, NULL, NULL, &result); + * if (status != napi_ok) { + * napi_throw_error(env, NULL, "napi_create_external failed"); + * return NULL; + * } + * return result; + * } + * ... + * DECLARE_NAPI_PROPERTY("myNapi", MyNapi) + * ... + * ``` + * + * ```js + * const native = require('napi_addon.node'); + * const data = native.myNapi(); + * util.types.isExternal(data); // returns true + * util.types.isExternal(0); // returns false + * util.types.isExternal(new String('foo')); // returns false + * ``` + * + * For further information on `napi_create_external`, refer to `napi_create_external()`. + * @since v10.0.0 + */ + function isExternal(object: unknown): boolean; + /** + * Returns `true` if the value is a built-in [`Float32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array) instance. + * + * ```js + * util.types.isFloat32Array(new ArrayBuffer()); // Returns false + * util.types.isFloat32Array(new Float32Array()); // Returns true + * util.types.isFloat32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isFloat32Array(object: unknown): object is Float32Array; + /** + * Returns `true` if the value is a built-in [`Float64Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float64Array) instance. + * + * ```js + * util.types.isFloat64Array(new ArrayBuffer()); // Returns false + * util.types.isFloat64Array(new Uint8Array()); // Returns false + * util.types.isFloat64Array(new Float64Array()); // Returns true + * ``` + * @since v10.0.0 + */ + function isFloat64Array(object: unknown): object is Float64Array; + /** + * Returns `true` if the value is a generator function. + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * util.types.isGeneratorFunction(function foo() {}); // Returns false + * util.types.isGeneratorFunction(function* foo() {}); // Returns true + * ``` + * @since v10.0.0 + */ + function isGeneratorFunction(object: unknown): object is GeneratorFunction; + /** + * Returns `true` if the value is a generator object as returned from a + * built-in generator function. + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * function* foo() {} + * const generator = foo(); + * util.types.isGeneratorObject(generator); // Returns true + * ``` + * @since v10.0.0 + */ + function isGeneratorObject(object: unknown): object is Generator; + /** + * Returns `true` if the value is a built-in [`Int8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int8Array) instance. + * + * ```js + * util.types.isInt8Array(new ArrayBuffer()); // Returns false + * util.types.isInt8Array(new Int8Array()); // Returns true + * util.types.isInt8Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt8Array(object: unknown): object is Int8Array; + /** + * Returns `true` if the value is a built-in [`Int16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int16Array) instance. + * + * ```js + * util.types.isInt16Array(new ArrayBuffer()); // Returns false + * util.types.isInt16Array(new Int16Array()); // Returns true + * util.types.isInt16Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt16Array(object: unknown): object is Int16Array; + /** + * Returns `true` if the value is a built-in [`Int32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array) instance. + * + * ```js + * util.types.isInt32Array(new ArrayBuffer()); // Returns false + * util.types.isInt32Array(new Int32Array()); // Returns true + * util.types.isInt32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt32Array(object: unknown): object is Int32Array; + /** + * Returns `true` if the value is a built-in [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instance. + * + * ```js + * util.types.isMap(new Map()); // Returns true + * ``` + * @since v10.0.0 + */ + function isMap( + object: T | {}, + ): object is T extends ReadonlyMap ? (unknown extends T ? never : ReadonlyMap) + : Map; + /** + * Returns `true` if the value is an iterator returned for a built-in [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instance. + * + * ```js + * const map = new Map(); + * util.types.isMapIterator(map.keys()); // Returns true + * util.types.isMapIterator(map.values()); // Returns true + * util.types.isMapIterator(map.entries()); // Returns true + * util.types.isMapIterator(map[Symbol.iterator]()); // Returns true + * ``` + * @since v10.0.0 + */ + function isMapIterator(object: unknown): boolean; + /** + * Returns `true` if the value is an instance of a [Module Namespace Object](https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects). + * + * ```js + * import * as ns from './a.js'; + * + * util.types.isModuleNamespaceObject(ns); // Returns true + * ``` + * @since v10.0.0 + */ + function isModuleNamespaceObject(value: unknown): boolean; + /** + * Returns `true` if the value was returned by the constructor of a [built-in `Error` type](https://tc39.es/ecma262/#sec-error-objects). + * + * ```js + * console.log(util.types.isNativeError(new Error())); // true + * console.log(util.types.isNativeError(new TypeError())); // true + * console.log(util.types.isNativeError(new RangeError())); // true + * ``` + * + * Subclasses of the native error types are also native errors: + * + * ```js + * class MyError extends Error {} + * console.log(util.types.isNativeError(new MyError())); // true + * ``` + * + * A value being `instanceof` a native error class is not equivalent to `isNativeError()` returning `true` for that value. `isNativeError()` returns `true` for errors + * which come from a different [realm](https://tc39.es/ecma262/#realm) while `instanceof Error` returns `false` for these errors: + * + * ```js + * const vm = require('node:vm'); + * const context = vm.createContext({}); + * const myError = vm.runInContext('new Error()', context); + * console.log(util.types.isNativeError(myError)); // true + * console.log(myError instanceof Error); // false + * ``` + * + * Conversely, `isNativeError()` returns `false` for all objects which were not + * returned by the constructor of a native error. That includes values + * which are `instanceof` native errors: + * + * ```js + * const myError = { __proto__: Error.prototype }; + * console.log(util.types.isNativeError(myError)); // false + * console.log(myError instanceof Error); // true + * ``` + * @since v10.0.0 + */ + function isNativeError(object: unknown): object is Error; + /** + * Returns `true` if the value is a number object, e.g. created + * by `new Number()`. + * + * ```js + * util.types.isNumberObject(0); // Returns false + * util.types.isNumberObject(new Number(0)); // Returns true + * ``` + * @since v10.0.0 + */ + function isNumberObject(object: unknown): object is Number; + /** + * Returns `true` if the value is a built-in [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). + * + * ```js + * util.types.isPromise(Promise.resolve(42)); // Returns true + * ``` + * @since v10.0.0 + */ + function isPromise(object: unknown): object is Promise; + /** + * Returns `true` if the value is a [`Proxy`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) instance. + * + * ```js + * const target = {}; + * const proxy = new Proxy(target, {}); + * util.types.isProxy(target); // Returns false + * util.types.isProxy(proxy); // Returns true + * ``` + * @since v10.0.0 + */ + function isProxy(object: unknown): boolean; + /** + * Returns `true` if the value is a regular expression object. + * + * ```js + * util.types.isRegExp(/abc/); // Returns true + * util.types.isRegExp(new RegExp('abc')); // Returns true + * ``` + * @since v10.0.0 + */ + function isRegExp(object: unknown): object is RegExp; + /** + * Returns `true` if the value is a built-in [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) instance. + * + * ```js + * util.types.isSet(new Set()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSet( + object: T | {}, + ): object is T extends ReadonlySet ? (unknown extends T ? never : ReadonlySet) : Set; + /** + * Returns `true` if the value is an iterator returned for a built-in [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) instance. + * + * ```js + * const set = new Set(); + * util.types.isSetIterator(set.keys()); // Returns true + * util.types.isSetIterator(set.values()); // Returns true + * util.types.isSetIterator(set.entries()); // Returns true + * util.types.isSetIterator(set[Symbol.iterator]()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSetIterator(object: unknown): boolean; + /** + * Returns `true` if the value is a built-in [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instance. + * This does _not_ include [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) instances. Usually, it is + * desirable to test for both; See `util.types.isAnyArrayBuffer()` for that. + * + * ```js + * util.types.isSharedArrayBuffer(new ArrayBuffer()); // Returns false + * util.types.isSharedArrayBuffer(new SharedArrayBuffer()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSharedArrayBuffer(object: unknown): object is SharedArrayBuffer; + /** + * Returns `true` if the value is a string object, e.g. created + * by `new String()`. + * + * ```js + * util.types.isStringObject('foo'); // Returns false + * util.types.isStringObject(new String('foo')); // Returns true + * ``` + * @since v10.0.0 + */ + function isStringObject(object: unknown): object is String; + /** + * Returns `true` if the value is a symbol object, created + * by calling `Object()` on a `Symbol` primitive. + * + * ```js + * const symbol = Symbol('foo'); + * util.types.isSymbolObject(symbol); // Returns false + * util.types.isSymbolObject(Object(symbol)); // Returns true + * ``` + * @since v10.0.0 + */ + function isSymbolObject(object: unknown): object is Symbol; + /** + * Returns `true` if the value is a built-in [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) instance. + * + * ```js + * util.types.isTypedArray(new ArrayBuffer()); // Returns false + * util.types.isTypedArray(new Uint8Array()); // Returns true + * util.types.isTypedArray(new Float64Array()); // Returns true + * ``` + * + * See also [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * @since v10.0.0 + */ + function isTypedArray(object: unknown): object is NodeJS.TypedArray; + /** + * Returns `true` if the value is a built-in [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) instance. + * + * ```js + * util.types.isUint8Array(new ArrayBuffer()); // Returns false + * util.types.isUint8Array(new Uint8Array()); // Returns true + * util.types.isUint8Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint8Array(object: unknown): object is Uint8Array; + /** + * Returns `true` if the value is a built-in [`Uint8ClampedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray) instance. + * + * ```js + * util.types.isUint8ClampedArray(new ArrayBuffer()); // Returns false + * util.types.isUint8ClampedArray(new Uint8ClampedArray()); // Returns true + * util.types.isUint8ClampedArray(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint8ClampedArray(object: unknown): object is Uint8ClampedArray; + /** + * Returns `true` if the value is a built-in [`Uint16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array) instance. + * + * ```js + * util.types.isUint16Array(new ArrayBuffer()); // Returns false + * util.types.isUint16Array(new Uint16Array()); // Returns true + * util.types.isUint16Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint16Array(object: unknown): object is Uint16Array; + /** + * Returns `true` if the value is a built-in [`Uint32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array) instance. + * + * ```js + * util.types.isUint32Array(new ArrayBuffer()); // Returns false + * util.types.isUint32Array(new Uint32Array()); // Returns true + * util.types.isUint32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint32Array(object: unknown): object is Uint32Array; + /** + * Returns `true` if the value is a built-in [`WeakMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) instance. + * + * ```js + * util.types.isWeakMap(new WeakMap()); // Returns true + * ``` + * @since v10.0.0 + */ + function isWeakMap(object: unknown): object is WeakMap; + /** + * Returns `true` if the value is a built-in [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) instance. + * + * ```js + * util.types.isWeakSet(new WeakSet()); // Returns true + * ``` + * @since v10.0.0 + */ + function isWeakSet(object: unknown): object is WeakSet; + /** + * Returns `true` if `value` is a `KeyObject`, `false` otherwise. + * @since v16.2.0 + */ + function isKeyObject(object: unknown): object is KeyObject; + /** + * Returns `true` if `value` is a `CryptoKey`, `false` otherwise. + * @since v16.2.0 + */ + function isCryptoKey(object: unknown): object is webcrypto.CryptoKey; +} +declare module "node:util" { + export * from "util"; +} +declare module "node:util/types" { + export * from "util/types"; +} diff --git a/libcore/node_modules/@types/node/v8.d.ts b/libcore/node_modules/@types/node/v8.d.ts new file mode 100644 index 0000000..58b8bb3 --- /dev/null +++ b/libcore/node_modules/@types/node/v8.d.ts @@ -0,0 +1,808 @@ +/** + * The `node:v8` module exposes APIs that are specific to the version of [V8](https://developers.google.com/v8/) built into the Node.js binary. It can be accessed using: + * + * ```js + * const v8 = require('node:v8'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/v8.js) + */ +declare module "v8" { + import { Readable } from "node:stream"; + interface HeapSpaceInfo { + space_name: string; + space_size: number; + space_used_size: number; + space_available_size: number; + physical_space_size: number; + } + // ** Signifies if the --zap_code_space option is enabled or not. 1 == enabled, 0 == disabled. */ + type DoesZapCodeSpaceFlag = 0 | 1; + interface HeapInfo { + total_heap_size: number; + total_heap_size_executable: number; + total_physical_size: number; + total_available_size: number; + used_heap_size: number; + heap_size_limit: number; + malloced_memory: number; + peak_malloced_memory: number; + does_zap_garbage: DoesZapCodeSpaceFlag; + number_of_native_contexts: number; + number_of_detached_contexts: number; + total_global_handles_size: number; + used_global_handles_size: number; + external_memory: number; + } + interface HeapCodeStatistics { + code_and_metadata_size: number; + bytecode_and_metadata_size: number; + external_script_source_size: number; + } + interface HeapSnapshotOptions { + /** + * If true, expose internals in the heap snapshot. + * @default false + */ + exposeInternals?: boolean; + /** + * If true, expose numeric values in artificial fields. + * @default false + */ + exposeNumericValues?: boolean; + } + /** + * Returns an integer representing a version tag derived from the V8 version, + * command-line flags, and detected CPU features. This is useful for determining + * whether a `vm.Script` `cachedData` buffer is compatible with this instance + * of V8. + * + * ```js + * console.log(v8.cachedDataVersionTag()); // 3947234607 + * // The value returned by v8.cachedDataVersionTag() is derived from the V8 + * // version, command-line flags, and detected CPU features. Test that the value + * // does indeed update when flags are toggled. + * v8.setFlagsFromString('--allow_natives_syntax'); + * console.log(v8.cachedDataVersionTag()); // 183726201 + * ``` + * @since v8.0.0 + */ + function cachedDataVersionTag(): number; + /** + * Returns an object with the following properties: + * + * `does_zap_garbage` is a 0/1 boolean, which signifies whether the `--zap_code_space` option is enabled or not. This makes V8 overwrite heap + * garbage with a bit pattern. The RSS footprint (resident set size) gets bigger + * because it continuously touches all heap pages and that makes them less likely + * to get swapped out by the operating system. + * + * `number_of_native_contexts` The value of native\_context is the number of the + * top-level contexts currently active. Increase of this number over time indicates + * a memory leak. + * + * `number_of_detached_contexts` The value of detached\_context is the number + * of contexts that were detached and not yet garbage collected. This number + * being non-zero indicates a potential memory leak. + * + * `total_global_handles_size` The value of total\_global\_handles\_size is the + * total memory size of V8 global handles. + * + * `used_global_handles_size` The value of used\_global\_handles\_size is the + * used memory size of V8 global handles. + * + * `external_memory` The value of external\_memory is the memory size of array + * buffers and external strings. + * + * ```js + * { + * total_heap_size: 7326976, + * total_heap_size_executable: 4194304, + * total_physical_size: 7326976, + * total_available_size: 1152656, + * used_heap_size: 3476208, + * heap_size_limit: 1535115264, + * malloced_memory: 16384, + * peak_malloced_memory: 1127496, + * does_zap_garbage: 0, + * number_of_native_contexts: 1, + * number_of_detached_contexts: 0, + * total_global_handles_size: 8192, + * used_global_handles_size: 3296, + * external_memory: 318824 + * } + * ``` + * @since v1.0.0 + */ + function getHeapStatistics(): HeapInfo; + /** + * Returns statistics about the V8 heap spaces, i.e. the segments which make up + * the V8 heap. Neither the ordering of heap spaces, nor the availability of a + * heap space can be guaranteed as the statistics are provided via the + * V8 [`GetHeapSpaceStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#ac673576f24fdc7a33378f8f57e1d13a4) function and may change from one V8 version to the + * next. + * + * The value returned is an array of objects containing the following properties: + * + * ```json + * [ + * { + * "space_name": "new_space", + * "space_size": 2063872, + * "space_used_size": 951112, + * "space_available_size": 80824, + * "physical_space_size": 2063872 + * }, + * { + * "space_name": "old_space", + * "space_size": 3090560, + * "space_used_size": 2493792, + * "space_available_size": 0, + * "physical_space_size": 3090560 + * }, + * { + * "space_name": "code_space", + * "space_size": 1260160, + * "space_used_size": 644256, + * "space_available_size": 960, + * "physical_space_size": 1260160 + * }, + * { + * "space_name": "map_space", + * "space_size": 1094160, + * "space_used_size": 201608, + * "space_available_size": 0, + * "physical_space_size": 1094160 + * }, + * { + * "space_name": "large_object_space", + * "space_size": 0, + * "space_used_size": 0, + * "space_available_size": 1490980608, + * "physical_space_size": 0 + * } + * ] + * ``` + * @since v6.0.0 + */ + function getHeapSpaceStatistics(): HeapSpaceInfo[]; + /** + * The `v8.setFlagsFromString()` method can be used to programmatically set + * V8 command-line flags. This method should be used with care. Changing settings + * after the VM has started may result in unpredictable behavior, including + * crashes and data loss; or it may simply do nothing. + * + * The V8 options available for a version of Node.js may be determined by running `node --v8-options`. + * + * Usage: + * + * ```js + * // Print GC events to stdout for one minute. + * const v8 = require('node:v8'); + * v8.setFlagsFromString('--trace_gc'); + * setTimeout(() => { v8.setFlagsFromString('--notrace_gc'); }, 60e3); + * ``` + * @since v1.0.0 + */ + function setFlagsFromString(flags: string): void; + /** + * This is similar to the [`queryObjects()` console API](https://developer.chrome.com/docs/devtools/console/utilities#queryObjects-function) + * provided by the Chromium DevTools console. It can be used to search for objects that have the matching constructor on its prototype chain + * in the heap after a full garbage collection, which can be useful for memory leak regression tests. To avoid surprising results, users should + * avoid using this API on constructors whose implementation they don't control, or on constructors that can be invoked by other parties in the + * application. + * + * To avoid accidental leaks, this API does not return raw references to the objects found. By default, it returns the count of the objects + * found. If `options.format` is `'summary'`, it returns an array containing brief string representations for each object. The visibility provided + * in this API is similar to what the heap snapshot provides, while users can save the cost of serialization and parsing and directly filter the + * target objects during the search. + * + * Only objects created in the current execution context are included in the results. + * + * ```js + * import { queryObjects } from 'node:v8'; + * class A { foo = 'bar'; } + * console.log(queryObjects(A)); // 0 + * const a = new A(); + * console.log(queryObjects(A)); // 1 + * // [ "A { foo: 'bar' }" ] + * console.log(queryObjects(A, { format: 'summary' })); + * + * class B extends A { bar = 'qux'; } + * const b = new B(); + * console.log(queryObjects(B)); // 1 + * // [ "B { foo: 'bar', bar: 'qux' }" ] + * console.log(queryObjects(B, { format: 'summary' })); + * + * // Note that, when there are child classes inheriting from a constructor, + * // the constructor also shows up in the prototype chain of the child + * // classes's prototoype, so the child classes's prototoype would also be + * // included in the result. + * console.log(queryObjects(A)); // 3 + * // [ "B { foo: 'bar', bar: 'qux' }", 'A {}', "A { foo: 'bar' }" ] + * console.log(queryObjects(A, { format: 'summary' })); + * ``` + * @param ctor The constructor that can be used to search on the prototype chain in order to filter target objects in the heap. + * @since v20.13.0 + * @experimental + */ + function queryObjects(ctor: Function): number | string[]; + function queryObjects(ctor: Function, options: { format: "count" }): number; + function queryObjects(ctor: Function, options: { format: "summary" }): string[]; + /** + * Generates a snapshot of the current V8 heap and returns a Readable + * Stream that may be used to read the JSON serialized representation. + * This JSON stream format is intended to be used with tools such as + * Chrome DevTools. The JSON schema is undocumented and specific to the + * V8 engine. Therefore, the schema may change from one version of V8 to the next. + * + * Creating a heap snapshot requires memory about twice the size of the heap at + * the time the snapshot is created. This results in the risk of OOM killers + * terminating the process. + * + * Generating a snapshot is a synchronous operation which blocks the event loop + * for a duration depending on the heap size. + * + * ```js + * // Print heap snapshot to the console + * const v8 = require('node:v8'); + * const stream = v8.getHeapSnapshot(); + * stream.pipe(process.stdout); + * ``` + * @since v11.13.0 + * @return A Readable containing the V8 heap snapshot. + */ + function getHeapSnapshot(options?: HeapSnapshotOptions): Readable; + /** + * Generates a snapshot of the current V8 heap and writes it to a JSON + * file. This file is intended to be used with tools such as Chrome + * DevTools. The JSON schema is undocumented and specific to the V8 + * engine, and may change from one version of V8 to the next. + * + * A heap snapshot is specific to a single V8 isolate. When using `worker threads`, a heap snapshot generated from the main thread will + * not contain any information about the workers, and vice versa. + * + * Creating a heap snapshot requires memory about twice the size of the heap at + * the time the snapshot is created. This results in the risk of OOM killers + * terminating the process. + * + * Generating a snapshot is a synchronous operation which blocks the event loop + * for a duration depending on the heap size. + * + * ```js + * const { writeHeapSnapshot } = require('node:v8'); + * const { + * Worker, + * isMainThread, + * parentPort, + * } = require('node:worker_threads'); + * + * if (isMainThread) { + * const worker = new Worker(__filename); + * + * worker.once('message', (filename) => { + * console.log(`worker heapdump: ${filename}`); + * // Now get a heapdump for the main thread. + * console.log(`main thread heapdump: ${writeHeapSnapshot()}`); + * }); + * + * // Tell the worker to create a heapdump. + * worker.postMessage('heapdump'); + * } else { + * parentPort.once('message', (message) => { + * if (message === 'heapdump') { + * // Generate a heapdump for the worker + * // and return the filename to the parent. + * parentPort.postMessage(writeHeapSnapshot()); + * } + * }); + * } + * ``` + * @since v11.13.0 + * @param filename The file path where the V8 heap snapshot is to be saved. If not specified, a file name with the pattern `'Heap-${yyyymmdd}-${hhmmss}-${pid}-${thread_id}.heapsnapshot'` will be + * generated, where `{pid}` will be the PID of the Node.js process, `{thread_id}` will be `0` when `writeHeapSnapshot()` is called from the main Node.js thread or the id of a + * worker thread. + * @return The filename where the snapshot was saved. + */ + function writeHeapSnapshot(filename?: string, options?: HeapSnapshotOptions): string; + /** + * Get statistics about code and its metadata in the heap, see + * V8 [`GetHeapCodeAndMetadataStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#a6079122af17612ef54ef3348ce170866) API. Returns an object with the + * following properties: + * + * ```js + * { + * code_and_metadata_size: 212208, + * bytecode_and_metadata_size: 161368, + * external_script_source_size: 1410794, + * cpu_profiler_metadata_size: 0, + * } + * ``` + * @since v12.8.0 + */ + function getHeapCodeStatistics(): HeapCodeStatistics; + /** + * @since v8.0.0 + */ + class Serializer { + /** + * Writes out a header, which includes the serialization format version. + */ + writeHeader(): void; + /** + * Serializes a JavaScript value and adds the serialized representation to the + * internal buffer. + * + * This throws an error if `value` cannot be serialized. + */ + writeValue(val: any): boolean; + /** + * Returns the stored internal buffer. This serializer should not be used once + * the buffer is released. Calling this method results in undefined behavior + * if a previous write has failed. + */ + releaseBuffer(): Buffer; + /** + * Marks an `ArrayBuffer` as having its contents transferred out of band. + * Pass the corresponding `ArrayBuffer` in the deserializing context to `deserializer.transferArrayBuffer()`. + * @param id A 32-bit unsigned integer. + * @param arrayBuffer An `ArrayBuffer` instance. + */ + transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void; + /** + * Write a raw 32-bit unsigned integer. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeUint32(value: number): void; + /** + * Write a raw 64-bit unsigned integer, split into high and low 32-bit parts. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeUint64(hi: number, lo: number): void; + /** + * Write a JS `number` value. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeDouble(value: number): void; + /** + * Write raw bytes into the serializer's internal buffer. The deserializer + * will require a way to compute the length of the buffer. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeRawBytes(buffer: NodeJS.TypedArray): void; + } + /** + * A subclass of `Serializer` that serializes `TypedArray`(in particular `Buffer`) and `DataView` objects as host objects, and only + * stores the part of their underlying `ArrayBuffer`s that they are referring to. + * @since v8.0.0 + */ + class DefaultSerializer extends Serializer {} + /** + * @since v8.0.0 + */ + class Deserializer { + constructor(data: NodeJS.TypedArray); + /** + * Reads and validates a header (including the format version). + * May, for example, reject an invalid or unsupported wire format. In that case, + * an `Error` is thrown. + */ + readHeader(): boolean; + /** + * Deserializes a JavaScript value from the buffer and returns it. + */ + readValue(): any; + /** + * Marks an `ArrayBuffer` as having its contents transferred out of band. + * Pass the corresponding `ArrayBuffer` in the serializing context to `serializer.transferArrayBuffer()` (or return the `id` from `serializer._getSharedArrayBufferId()` in the case of + * `SharedArrayBuffer`s). + * @param id A 32-bit unsigned integer. + * @param arrayBuffer An `ArrayBuffer` instance. + */ + transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void; + /** + * Reads the underlying wire format version. Likely mostly to be useful to + * legacy code reading old wire format versions. May not be called before `.readHeader()`. + */ + getWireFormatVersion(): number; + /** + * Read a raw 32-bit unsigned integer and return it. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readUint32(): number; + /** + * Read a raw 64-bit unsigned integer and return it as an array `[hi, lo]` with two 32-bit unsigned integer entries. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readUint64(): [number, number]; + /** + * Read a JS `number` value. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readDouble(): number; + /** + * Read raw bytes from the deserializer's internal buffer. The `length` parameter + * must correspond to the length of the buffer that was passed to `serializer.writeRawBytes()`. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readRawBytes(length: number): Buffer; + } + /** + * A subclass of `Deserializer` corresponding to the format written by `DefaultSerializer`. + * @since v8.0.0 + */ + class DefaultDeserializer extends Deserializer {} + /** + * Uses a `DefaultSerializer` to serialize `value` into a buffer. + * + * `ERR_BUFFER_TOO_LARGE` will be thrown when trying to + * serialize a huge object which requires buffer + * larger than `buffer.constants.MAX_LENGTH`. + * @since v8.0.0 + */ + function serialize(value: any): Buffer; + /** + * Uses a `DefaultDeserializer` with default options to read a JS value + * from a buffer. + * @since v8.0.0 + * @param buffer A buffer returned by {@link serialize}. + */ + function deserialize(buffer: NodeJS.TypedArray): any; + /** + * The `v8.takeCoverage()` method allows the user to write the coverage started by `NODE_V8_COVERAGE` to disk on demand. This method can be invoked multiple + * times during the lifetime of the process. Each time the execution counter will + * be reset and a new coverage report will be written to the directory specified + * by `NODE_V8_COVERAGE`. + * + * When the process is about to exit, one last coverage will still be written to + * disk unless {@link stopCoverage} is invoked before the process exits. + * @since v15.1.0, v14.18.0, v12.22.0 + */ + function takeCoverage(): void; + /** + * The `v8.stopCoverage()` method allows the user to stop the coverage collection + * started by `NODE_V8_COVERAGE`, so that V8 can release the execution count + * records and optimize code. This can be used in conjunction with {@link takeCoverage} if the user wants to collect the coverage on demand. + * @since v15.1.0, v14.18.0, v12.22.0 + */ + function stopCoverage(): void; + /** + * The API is a no-op if `--heapsnapshot-near-heap-limit` is already set from the command line or the API is called more than once. + * `limit` must be a positive integer. See [`--heapsnapshot-near-heap-limit`](https://nodejs.org/docs/latest-v22.x/api/cli.html#--heapsnapshot-near-heap-limitmax_count) for more information. + * @experimental + * @since v18.10.0, v16.18.0 + */ + function setHeapSnapshotNearHeapLimit(limit: number): void; + /** + * This API collects GC data in current thread. + * @since v19.6.0, v18.15.0 + */ + class GCProfiler { + /** + * Start collecting GC data. + * @since v19.6.0, v18.15.0 + */ + start(): void; + /** + * Stop collecting GC data and return an object. The content of object + * is as follows. + * + * ```json + * { + * "version": 1, + * "startTime": 1674059033862, + * "statistics": [ + * { + * "gcType": "Scavenge", + * "beforeGC": { + * "heapStatistics": { + * "totalHeapSize": 5005312, + * "totalHeapSizeExecutable": 524288, + * "totalPhysicalSize": 5226496, + * "totalAvailableSize": 4341325216, + * "totalGlobalHandlesSize": 8192, + * "usedGlobalHandlesSize": 2112, + * "usedHeapSize": 4883840, + * "heapSizeLimit": 4345298944, + * "mallocedMemory": 254128, + * "externalMemory": 225138, + * "peakMallocedMemory": 181760 + * }, + * "heapSpaceStatistics": [ + * { + * "spaceName": "read_only_space", + * "spaceSize": 0, + * "spaceUsedSize": 0, + * "spaceAvailableSize": 0, + * "physicalSpaceSize": 0 + * } + * ] + * }, + * "cost": 1574.14, + * "afterGC": { + * "heapStatistics": { + * "totalHeapSize": 6053888, + * "totalHeapSizeExecutable": 524288, + * "totalPhysicalSize": 5500928, + * "totalAvailableSize": 4341101384, + * "totalGlobalHandlesSize": 8192, + * "usedGlobalHandlesSize": 2112, + * "usedHeapSize": 4059096, + * "heapSizeLimit": 4345298944, + * "mallocedMemory": 254128, + * "externalMemory": 225138, + * "peakMallocedMemory": 181760 + * }, + * "heapSpaceStatistics": [ + * { + * "spaceName": "read_only_space", + * "spaceSize": 0, + * "spaceUsedSize": 0, + * "spaceAvailableSize": 0, + * "physicalSpaceSize": 0 + * } + * ] + * } + * } + * ], + * "endTime": 1674059036865 + * } + * ``` + * + * Here's an example. + * + * ```js + * const { GCProfiler } = require('v8'); + * const profiler = new GCProfiler(); + * profiler.start(); + * setTimeout(() => { + * console.log(profiler.stop()); + * }, 1000); + * ``` + * @since v19.6.0, v18.15.0 + */ + stop(): GCProfilerResult; + } + interface GCProfilerResult { + version: number; + startTime: number; + endTime: number; + statistics: Array<{ + gcType: string; + cost: number; + beforeGC: { + heapStatistics: HeapStatistics; + heapSpaceStatistics: HeapSpaceStatistics[]; + }; + afterGC: { + heapStatistics: HeapStatistics; + heapSpaceStatistics: HeapSpaceStatistics[]; + }; + }>; + } + interface HeapStatistics { + totalHeapSize: number; + totalHeapSizeExecutable: number; + totalPhysicalSize: number; + totalAvailableSize: number; + totalGlobalHandlesSize: number; + usedGlobalHandlesSize: number; + usedHeapSize: number; + heapSizeLimit: number; + mallocedMemory: number; + externalMemory: number; + peakMallocedMemory: number; + } + interface HeapSpaceStatistics { + spaceName: string; + spaceSize: number; + spaceUsedSize: number; + spaceAvailableSize: number; + physicalSpaceSize: number; + } + /** + * Called when a promise is constructed. This does not mean that corresponding before/after events will occur, only that the possibility exists. This will + * happen if a promise is created without ever getting a continuation. + * @since v17.1.0, v16.14.0 + * @param promise The promise being created. + * @param parent The promise continued from, if applicable. + */ + interface Init { + (promise: Promise, parent: Promise): void; + } + /** + * Called before a promise continuation executes. This can be in the form of `then()`, `catch()`, or `finally()` handlers or an await resuming. + * + * The before callback will be called 0 to N times. The before callback will typically be called 0 times if no continuation was ever made for the promise. + * The before callback may be called many times in the case where many continuations have been made from the same promise. + * @since v17.1.0, v16.14.0 + */ + interface Before { + (promise: Promise): void; + } + /** + * Called immediately after a promise continuation executes. This may be after a `then()`, `catch()`, or `finally()` handler or before an await after another await. + * @since v17.1.0, v16.14.0 + */ + interface After { + (promise: Promise): void; + } + /** + * Called when the promise receives a resolution or rejection value. This may occur synchronously in the case of {@link Promise.resolve()} or + * {@link Promise.reject()}. + * @since v17.1.0, v16.14.0 + */ + interface Settled { + (promise: Promise): void; + } + /** + * Key events in the lifetime of a promise have been categorized into four areas: creation of a promise, before/after a continuation handler is called or + * around an await, and when the promise resolves or rejects. + * + * Because promises are asynchronous resources whose lifecycle is tracked via the promise hooks mechanism, the `init()`, `before()`, `after()`, and + * `settled()` callbacks must not be async functions as they create more promises which would produce an infinite loop. + * @since v17.1.0, v16.14.0 + */ + interface HookCallbacks { + init?: Init; + before?: Before; + after?: After; + settled?: Settled; + } + interface PromiseHooks { + /** + * The `init` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param init The {@link Init | `init` callback} to call when a promise is created. + * @return Call to stop the hook. + */ + onInit: (init: Init) => Function; + /** + * The `settled` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param settled The {@link Settled | `settled` callback} to call when a promise is created. + * @return Call to stop the hook. + */ + onSettled: (settled: Settled) => Function; + /** + * The `before` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param before The {@link Before | `before` callback} to call before a promise continuation executes. + * @return Call to stop the hook. + */ + onBefore: (before: Before) => Function; + /** + * The `after` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param after The {@link After | `after` callback} to call after a promise continuation executes. + * @return Call to stop the hook. + */ + onAfter: (after: After) => Function; + /** + * Registers functions to be called for different lifetime events of each promise. + * The callbacks `init()`/`before()`/`after()`/`settled()` are called for the respective events during a promise's lifetime. + * All callbacks are optional. For example, if only promise creation needs to be tracked, then only the init callback needs to be passed. + * The hook callbacks must be plain functions. Providing async functions will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param callbacks The {@link HookCallbacks | Hook Callbacks} to register + * @return Used for disabling hooks + */ + createHook: (callbacks: HookCallbacks) => Function; + } + /** + * The `promiseHooks` interface can be used to track promise lifecycle events. + * @since v17.1.0, v16.14.0 + */ + const promiseHooks: PromiseHooks; + type StartupSnapshotCallbackFn = (args: any) => any; + interface StartupSnapshot { + /** + * Add a callback that will be called when the Node.js instance is about to get serialized into a snapshot and exit. + * This can be used to release resources that should not or cannot be serialized or to convert user data into a form more suitable for serialization. + * @since v18.6.0, v16.17.0 + */ + addSerializeCallback(callback: StartupSnapshotCallbackFn, data?: any): void; + /** + * Add a callback that will be called when the Node.js instance is deserialized from a snapshot. + * The `callback` and the `data` (if provided) will be serialized into the snapshot, they can be used to re-initialize the state of the application or + * to re-acquire resources that the application needs when the application is restarted from the snapshot. + * @since v18.6.0, v16.17.0 + */ + addDeserializeCallback(callback: StartupSnapshotCallbackFn, data?: any): void; + /** + * This sets the entry point of the Node.js application when it is deserialized from a snapshot. This can be called only once in the snapshot building script. + * If called, the deserialized application no longer needs an additional entry point script to start up and will simply invoke the callback along with the deserialized + * data (if provided), otherwise an entry point script still needs to be provided to the deserialized application. + * @since v18.6.0, v16.17.0 + */ + setDeserializeMainFunction(callback: StartupSnapshotCallbackFn, data?: any): void; + /** + * Returns true if the Node.js instance is run to build a snapshot. + * @since v18.6.0, v16.17.0 + */ + isBuildingSnapshot(): boolean; + } + /** + * The `v8.startupSnapshot` interface can be used to add serialization and deserialization hooks for custom startup snapshots. + * + * ```bash + * $ node --snapshot-blob snapshot.blob --build-snapshot entry.js + * # This launches a process with the snapshot + * $ node --snapshot-blob snapshot.blob + * ``` + * + * In the example above, `entry.js` can use methods from the `v8.startupSnapshot` interface to specify how to save information for custom objects + * in the snapshot during serialization and how the information can be used to synchronize these objects during deserialization of the snapshot. + * For example, if the `entry.js` contains the following script: + * + * ```js + * 'use strict'; + * + * const fs = require('node:fs'); + * const zlib = require('node:zlib'); + * const path = require('node:path'); + * const assert = require('node:assert'); + * + * const v8 = require('node:v8'); + * + * class BookShelf { + * storage = new Map(); + * + * // Reading a series of files from directory and store them into storage. + * constructor(directory, books) { + * for (const book of books) { + * this.storage.set(book, fs.readFileSync(path.join(directory, book))); + * } + * } + * + * static compressAll(shelf) { + * for (const [ book, content ] of shelf.storage) { + * shelf.storage.set(book, zlib.gzipSync(content)); + * } + * } + * + * static decompressAll(shelf) { + * for (const [ book, content ] of shelf.storage) { + * shelf.storage.set(book, zlib.gunzipSync(content)); + * } + * } + * } + * + * // __dirname here is where the snapshot script is placed + * // during snapshot building time. + * const shelf = new BookShelf(__dirname, [ + * 'book1.en_US.txt', + * 'book1.es_ES.txt', + * 'book2.zh_CN.txt', + * ]); + * + * assert(v8.startupSnapshot.isBuildingSnapshot()); + * // On snapshot serialization, compress the books to reduce size. + * v8.startupSnapshot.addSerializeCallback(BookShelf.compressAll, shelf); + * // On snapshot deserialization, decompress the books. + * v8.startupSnapshot.addDeserializeCallback(BookShelf.decompressAll, shelf); + * v8.startupSnapshot.setDeserializeMainFunction((shelf) => { + * // process.env and process.argv are refreshed during snapshot + * // deserialization. + * const lang = process.env.BOOK_LANG || 'en_US'; + * const book = process.argv[1]; + * const name = `${book}.${lang}.txt`; + * console.log(shelf.storage.get(name)); + * }, shelf); + * ``` + * + * The resulted binary will get print the data deserialized from the snapshot during start up, using the refreshed `process.env` and `process.argv` of the launched process: + * + * ```bash + * $ BOOK_LANG=es_ES node --snapshot-blob snapshot.blob book1 + * # Prints content of book1.es_ES.txt deserialized from the snapshot. + * ``` + * + * Currently the application deserialized from a user-land snapshot cannot be snapshotted again, so these APIs are only available to applications that are not deserialized from a user-land snapshot. + * + * @experimental + * @since v18.6.0, v16.17.0 + */ + const startupSnapshot: StartupSnapshot; +} +declare module "node:v8" { + export * from "v8"; +} diff --git a/libcore/node_modules/@types/node/vm.d.ts b/libcore/node_modules/@types/node/vm.d.ts new file mode 100644 index 0000000..82d53a5 --- /dev/null +++ b/libcore/node_modules/@types/node/vm.d.ts @@ -0,0 +1,922 @@ +/** + * The `node:vm` module enables compiling and running code within V8 Virtual + * Machine contexts. + * + * **The `node:vm` module is not a security** + * **mechanism. Do not use it to run untrusted code.** + * + * JavaScript code can be compiled and run immediately or + * compiled, saved, and run later. + * + * A common use case is to run the code in a different V8 Context. This means + * invoked code has a different global object than the invoking code. + * + * One can provide the context by `contextifying` an + * object. The invoked code treats any property in the context like a + * global variable. Any changes to global variables caused by the invoked + * code are reflected in the context object. + * + * ```js + * const vm = require('node:vm'); + * + * const x = 1; + * + * const context = { x: 2 }; + * vm.createContext(context); // Contextify the object. + * + * const code = 'x += 40; var y = 17;'; + * // `x` and `y` are global variables in the context. + * // Initially, x has the value 2 because that is the value of context.x. + * vm.runInContext(code, context); + * + * console.log(context.x); // 42 + * console.log(context.y); // 17 + * + * console.log(x); // 1; y is not defined. + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/vm.js) + */ +declare module "vm" { + import { ImportAttributes } from "node:module"; + interface Context extends NodeJS.Dict {} + interface BaseOptions { + /** + * Specifies the filename used in stack traces produced by this script. + * @default '' + */ + filename?: string | undefined; + /** + * Specifies the line number offset that is displayed in stack traces produced by this script. + * @default 0 + */ + lineOffset?: number | undefined; + /** + * Specifies the column number offset that is displayed in stack traces produced by this script. + * @default 0 + */ + columnOffset?: number | undefined; + } + interface ScriptOptions extends BaseOptions { + /** + * V8's code cache data for the supplied source. + */ + cachedData?: Buffer | NodeJS.ArrayBufferView | undefined; + /** @deprecated in favor of `script.createCachedData()` */ + produceCachedData?: boolean | undefined; + /** + * Used to specify how the modules should be loaded during the evaluation of this script when `import()` is called. This option is + * part of the experimental modules API. We do not recommend using it in a production environment. For detailed information, see + * [Support of dynamic `import()` in compilation APIs](https://nodejs.org/docs/latest-v22.x/api/vm.html#support-of-dynamic-import-in-compilation-apis). + */ + importModuleDynamically?: + | ((specifier: string, script: Script, importAttributes: ImportAttributes) => Module) + | typeof constants.USE_MAIN_CONTEXT_DEFAULT_LOADER + | undefined; + } + interface RunningScriptOptions extends BaseOptions { + /** + * When `true`, if an `Error` occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. + * @default true + */ + displayErrors?: boolean | undefined; + /** + * Specifies the number of milliseconds to execute code before terminating execution. + * If execution is terminated, an `Error` will be thrown. This value must be a strictly positive integer. + */ + timeout?: number | undefined; + /** + * If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. + * Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. + * If execution is terminated, an `Error` will be thrown. + * @default false + */ + breakOnSigint?: boolean | undefined; + } + interface RunningScriptInNewContextOptions extends RunningScriptOptions { + /** + * Human-readable name of the newly created context. + */ + contextName?: CreateContextOptions["name"]; + /** + * Origin corresponding to the newly created context for display purposes. The origin should be formatted like a URL, + * but with only the scheme, host, and port (if necessary), like the value of the `url.origin` property of a `URL` object. + * Most notably, this string should omit the trailing slash, as that denotes a path. + */ + contextOrigin?: CreateContextOptions["origin"]; + contextCodeGeneration?: CreateContextOptions["codeGeneration"]; + /** + * If set to `afterEvaluate`, microtasks will be run immediately after the script has run. + */ + microtaskMode?: CreateContextOptions["microtaskMode"]; + } + interface RunningCodeOptions extends RunningScriptOptions { + cachedData?: ScriptOptions["cachedData"]; + importModuleDynamically?: ScriptOptions["importModuleDynamically"]; + } + interface RunningCodeInNewContextOptions extends RunningScriptInNewContextOptions { + cachedData?: ScriptOptions["cachedData"]; + importModuleDynamically?: ScriptOptions["importModuleDynamically"]; + } + interface CompileFunctionOptions extends BaseOptions { + /** + * Provides an optional data with V8's code cache data for the supplied source. + */ + cachedData?: Buffer | undefined; + /** + * Specifies whether to produce new cache data. + * @default false + */ + produceCachedData?: boolean | undefined; + /** + * The sandbox/context in which the said function should be compiled in. + */ + parsingContext?: Context | undefined; + /** + * An array containing a collection of context extensions (objects wrapping the current scope) to be applied while compiling + */ + contextExtensions?: Object[] | undefined; + } + interface CreateContextOptions { + /** + * Human-readable name of the newly created context. + * @default 'VM Context i' Where i is an ascending numerical index of the created context. + */ + name?: string | undefined; + /** + * Corresponds to the newly created context for display purposes. + * The origin should be formatted like a `URL`, but with only the scheme, host, and port (if necessary), + * like the value of the `url.origin` property of a URL object. + * Most notably, this string should omit the trailing slash, as that denotes a path. + * @default '' + */ + origin?: string | undefined; + codeGeneration?: + | { + /** + * If set to false any calls to eval or function constructors (Function, GeneratorFunction, etc) + * will throw an EvalError. + * @default true + */ + strings?: boolean | undefined; + /** + * If set to false any attempt to compile a WebAssembly module will throw a WebAssembly.CompileError. + * @default true + */ + wasm?: boolean | undefined; + } + | undefined; + /** + * If set to `afterEvaluate`, microtasks will be run immediately after the script has run. + */ + microtaskMode?: "afterEvaluate" | undefined; + } + type MeasureMemoryMode = "summary" | "detailed"; + interface MeasureMemoryOptions { + /** + * @default 'summary' + */ + mode?: MeasureMemoryMode | undefined; + /** + * @default 'default' + */ + execution?: "default" | "eager" | undefined; + } + interface MemoryMeasurement { + total: { + jsMemoryEstimate: number; + jsMemoryRange: [number, number]; + }; + } + /** + * Instances of the `vm.Script` class contain precompiled scripts that can be + * executed in specific contexts. + * @since v0.3.1 + */ + class Script { + constructor(code: string, options?: ScriptOptions | string); + /** + * Runs the compiled code contained by the `vm.Script` object within the given `contextifiedObject` and returns the result. Running code does not have access + * to local scope. + * + * The following example compiles code that increments a global variable, sets + * the value of another global variable, then execute the code multiple times. + * The globals are contained in the `context` object. + * + * ```js + * const vm = require('node:vm'); + * + * const context = { + * animal: 'cat', + * count: 2, + * }; + * + * const script = new vm.Script('count += 1; name = "kitty";'); + * + * vm.createContext(context); + * for (let i = 0; i < 10; ++i) { + * script.runInContext(context); + * } + * + * console.log(context); + * // Prints: { animal: 'cat', count: 12, name: 'kitty' } + * ``` + * + * Using the `timeout` or `breakOnSigint` options will result in new event loops + * and corresponding threads being started, which have a non-zero performance + * overhead. + * @since v0.3.1 + * @param contextifiedObject A `contextified` object as returned by the `vm.createContext()` method. + * @return the result of the very last statement executed in the script. + */ + runInContext(contextifiedObject: Context, options?: RunningScriptOptions): any; + /** + * First contextifies the given `contextObject`, runs the compiled code contained + * by the `vm.Script` object within the created context, and returns the result. + * Running code does not have access to local scope. + * + * The following example compiles code that sets a global variable, then executes + * the code multiple times in different contexts. The globals are set on and + * contained within each individual `context`. + * + * ```js + * const vm = require('node:vm'); + * + * const script = new vm.Script('globalVar = "set"'); + * + * const contexts = [{}, {}, {}]; + * contexts.forEach((context) => { + * script.runInNewContext(context); + * }); + * + * console.log(contexts); + * // Prints: [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }] + * ``` + * @since v0.3.1 + * @param contextObject An object that will be `contextified`. If `undefined`, a new object will be created. + * @return the result of the very last statement executed in the script. + */ + runInNewContext(contextObject?: Context, options?: RunningScriptInNewContextOptions): any; + /** + * Runs the compiled code contained by the `vm.Script` within the context of the + * current `global` object. Running code does not have access to local scope, but _does_ have access to the current `global` object. + * + * The following example compiles code that increments a `global` variable then + * executes that code multiple times: + * + * ```js + * const vm = require('node:vm'); + * + * global.globalVar = 0; + * + * const script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' }); + * + * for (let i = 0; i < 1000; ++i) { + * script.runInThisContext(); + * } + * + * console.log(globalVar); + * + * // 1000 + * ``` + * @since v0.3.1 + * @return the result of the very last statement executed in the script. + */ + runInThisContext(options?: RunningScriptOptions): any; + /** + * Creates a code cache that can be used with the `Script` constructor's `cachedData` option. Returns a `Buffer`. This method may be called at any + * time and any number of times. + * + * The code cache of the `Script` doesn't contain any JavaScript observable + * states. The code cache is safe to be saved along side the script source and + * used to construct new `Script` instances multiple times. + * + * Functions in the `Script` source can be marked as lazily compiled and they are + * not compiled at construction of the `Script`. These functions are going to be + * compiled when they are invoked the first time. The code cache serializes the + * metadata that V8 currently knows about the `Script` that it can use to speed up + * future compilations. + * + * ```js + * const script = new vm.Script(` + * function add(a, b) { + * return a + b; + * } + * + * const x = add(1, 2); + * `); + * + * const cacheWithoutAdd = script.createCachedData(); + * // In `cacheWithoutAdd` the function `add()` is marked for full compilation + * // upon invocation. + * + * script.runInThisContext(); + * + * const cacheWithAdd = script.createCachedData(); + * // `cacheWithAdd` contains fully compiled function `add()`. + * ``` + * @since v10.6.0 + */ + createCachedData(): Buffer; + /** @deprecated in favor of `script.createCachedData()` */ + cachedDataProduced?: boolean | undefined; + /** + * When `cachedData` is supplied to create the `vm.Script`, this value will be set + * to either `true` or `false` depending on acceptance of the data by V8. + * Otherwise the value is `undefined`. + * @since v5.7.0 + */ + cachedDataRejected?: boolean | undefined; + cachedData?: Buffer | undefined; + /** + * When the script is compiled from a source that contains a source map magic + * comment, this property will be set to the URL of the source map. + * + * ```js + * import vm from 'node:vm'; + * + * const script = new vm.Script(` + * function myFunc() {} + * //# sourceMappingURL=sourcemap.json + * `); + * + * console.log(script.sourceMapURL); + * // Prints: sourcemap.json + * ``` + * @since v19.1.0, v18.13.0 + */ + sourceMapURL?: string | undefined; + } + /** + * If given a `contextObject`, the `vm.createContext()` method will + * [prepare that object](https://nodejs.org/docs/latest-v22.x/api/vm.html#what-does-it-mean-to-contextify-an-object) + * and return a reference to it so that it can be used in `{@link runInContext}` or + * [`script.runInContext()`](https://nodejs.org/docs/latest-v22.x/api/vm.html#scriptrunincontextcontextifiedobject-options). Inside such + * scripts, the `contextObject` will be the global object, retaining all of its + * existing properties but also having the built-in objects and functions any + * standard [global object](https://es5.github.io/#x15.1) has. Outside of scripts run by the vm module, global + * variables will remain unchanged. + * + * ```js + * const vm = require('node:vm'); + * + * global.globalVar = 3; + * + * const context = { globalVar: 1 }; + * vm.createContext(context); + * + * vm.runInContext('globalVar *= 2;', context); + * + * console.log(context); + * // Prints: { globalVar: 2 } + * + * console.log(global.globalVar); + * // Prints: 3 + * ``` + * + * If `contextObject` is omitted (or passed explicitly as `undefined`), a new, + * empty `contextified` object will be returned. + * + * The `vm.createContext()` method is primarily useful for creating a single + * context that can be used to run multiple scripts. For instance, if emulating a + * web browser, the method can be used to create a single context representing a + * window's global object, then run all `` into your +html! + +# install + +With [npm](https://www.npmjs.com/) do: + +``` +npm install -g browserify +``` + +# usage + +``` +Usage: browserify [entry files] {OPTIONS} + +Standard Options: + + --outfile, -o Write the browserify bundle to this file. + If unspecified, browserify prints to stdout. + + --require, -r A module name or file to bundle.require() + Optionally use a colon separator to set the target. + + --entry, -e An entry point of your app + + --ignore, -i Replace a file with an empty stub. Files can be globs. + + --exclude, -u Omit a file from the output bundle. Files can be globs. + + --external, -x Reference a file from another bundle. Files can be globs. + + --transform, -t Use a transform module on top-level files. + + --command, -c Use a transform command on top-level files. + + --standalone -s Generate a UMD bundle for the supplied export name. + This bundle works with other module systems and sets the name + given as a window global if no module system is found. + + --debug -d Enable source maps that allow you to debug your files + separately. + + --help, -h Show this message + +For advanced options, type `browserify --help advanced`. + +Specify a parameter. +``` + +``` +Advanced Options: + + --insert-globals, --ig, --fast [default: false] + + Skip detection and always insert definitions for process, global, + __filename, and __dirname. + + benefit: faster builds + cost: extra bytes + + --insert-global-vars, --igv + + Comma-separated list of global variables to detect and define. + Default: __filename,__dirname,process,Buffer,global + + --detect-globals, --dg [default: true] + + Detect the presence of process, global, __filename, and __dirname and define + these values when present. + + benefit: npm modules more likely to work + cost: slower builds + + --ignore-missing, --im [default: false] + + Ignore `require()` statements that don't resolve to anything. + + --noparse=FILE + + Don't parse FILE at all. This will make bundling much, much faster for giant + libs like jquery or threejs. + + --no-builtins + + Turn off builtins. This is handy when you want to run a bundle in node which + provides the core builtins. + + --no-commondir + + Turn off setting a commondir. This is useful if you want to preserve the + original paths that a bundle was generated with. + + --no-bundle-external + + Turn off bundling of all external modules. This is useful if you only want + to bundle your local files. + + --bare + + Alias for both --no-builtins, --no-commondir, and sets --insert-global-vars + to just "__filename,__dirname". This is handy if you want to run bundles in + node. + + --no-browser-field, --no-bf + + Turn off package.json browser field resolution. This is also handy if you + need to run a bundle in node. + + --transform-key + + Instead of the default package.json#browserify#transform field to list + all transforms to apply when running browserify, a custom field, like, e.g. + package.json#browserify#production or package.json#browserify#staging + can be used, by for example running: + * `browserify index.js --transform-key=production > bundle.js` + * `browserify index.js --transform-key=staging > bundle.js` + + --node + + Alias for --bare and --no-browser-field. + + --full-paths + + Turn off converting module ids into numerical indexes. This is useful for + preserving the original paths that a bundle was generated with. + + --deps + + Instead of standard bundle output, print the dependency array generated by + module-deps. + + --no-dedupe + + Turn off deduping. + + --list + + Print each file in the dependency graph. Useful for makefiles. + + --extension=EXTENSION + + Consider files with specified EXTENSION as modules, this option can used + multiple times. + + --global-transform=MODULE, -g MODULE + + Use a transform module on all files after any ordinary transforms have run. + + --ignore-transform=MODULE, -it MODULE + + Do not run certain transformations, even if specified elsewhere. + + --plugin=MODULE, -p MODULE + + Register MODULE as a plugin. + +Passing arguments to transforms and plugins: + + For -t, -g, and -p, you may use subarg syntax to pass options to the + transforms or plugin function as the second parameter. For example: + + -t [ foo -x 3 --beep ] + + will call the `foo` transform for each applicable file by calling: + + foo(file, { x: 3, beep: true }) + +``` + +# compatibility + +Many [npm](https://www.npmjs.com/) modules that don't do IO will just work after being +browserified. Others take more work. + +Many node built-in modules have been wrapped to work in the browser, but only +when you explicitly `require()` or use their functionality. + +When you `require()` any of these modules, you will get a browser-specific shim: + +* [assert](https://www.npmjs.com/package/assert) +* [buffer](https://www.npmjs.com/package/buffer) +* [console](https://www.npmjs.com/package/console-browserify) +* [constants](https://www.npmjs.com/package/constants-browserify) +* [crypto](https://www.npmjs.com/package/crypto-browserify) +* [domain](https://www.npmjs.com/package/domain-browser) +* [events](https://www.npmjs.com/package/events) +* [http](https://www.npmjs.com/package/stream-http) +* [https](https://www.npmjs.com/package/https-browserify) +* [os](https://www.npmjs.com/package/os-browserify) +* [path](https://www.npmjs.com/package/path-browserify) +* [punycode](https://www.npmjs.com/package/punycode) +* [querystring](https://www.npmjs.com/package/querystring-es3) +* [stream](https://www.npmjs.com/package/stream-browserify) +* [string_decoder](https://www.npmjs.com/package/string_decoder) +* [timers](https://www.npmjs.com/package/timers-browserify) +* [tty](https://www.npmjs.com/package/tty-browserify) +* [url](https://www.npmjs.com/package/url) +* [util](https://www.npmjs.com/package/util) +* [vm](https://www.npmjs.com/package/vm-browserify) +* [zlib](https://www.npmjs.com/package/browserify-zlib) + +Additionally, if you use any of these variables, they +[will be defined](https://github.com/browserify/insert-module-globals) +in the bundled output in a browser-appropriate way: + +* [process](https://www.npmjs.com/package/process) +* [Buffer](https://www.npmjs.com/package/buffer) +* global - top-level scope object (window) +* __filename - file path of the currently executing file +* __dirname - directory path of the currently executing file + +# more examples + +## external requires + +You can just as easily create a bundle that will export a `require()` function so +you can `require()` modules from another script tag. Here we'll create a +`bundle.js` with the [through](https://www.npmjs.com/package/through) +and [duplexer](https://www.npmjs.com/package/duplexer) modules. + +``` +$ browserify -r through -r duplexer -r ./my-file.js:my-module > bundle.js +``` + +Then in your page you can do: + +``` html + + +``` + +## external source maps + +If you prefer the source maps be saved to a separate `.js.map` source map file, you may use +[exorcist](https://github.com/thlorenz/exorcist) in order to achieve that. It's as simple as: + +``` +$ browserify main.js --debug | exorcist bundle.js.map > bundle.js +``` + +Learn about additional options [here](https://github.com/thlorenz/exorcist#usage). + +## multiple bundles + +If browserify finds a `require`d function already defined in the page scope, it +will fall back to that function if it didn't find any matches in its own set of +bundled modules. + +In this way, you can use browserify to split up bundles among multiple pages to +get the benefit of caching for shared, infrequently-changing modules, while +still being able to use `require()`. Just use a combination of `--external` and +`--require` to factor out common dependencies. + +For example, if a website with 2 pages, `beep.js`: + +``` js +var robot = require('./robot.js'); +console.log(robot('beep')); +``` + +and `boop.js`: + +``` js +var robot = require('./robot.js'); +console.log(robot('boop')); +``` + +both depend on `robot.js`: + +``` js +module.exports = function (s) { return s.toUpperCase() + '!' }; +``` + +``` +$ browserify -r ./robot.js > static/common.js +$ browserify -x ./robot.js beep.js > static/beep.js +$ browserify -x ./robot.js boop.js > static/boop.js +``` + +Then on the beep page you can have: + +``` html + + +``` + +while the boop page can have: + +``` html + + +``` + +This approach using `-r` and `-x` works fine for a small number of split assets, +but there are plugins for automatically factoring out components which are +described in the +[partitioning section of the browserify handbook](https://github.com/browserify/browserify-handbook#partitioning). + +## api example + +You can use the API directly too: + +``` js +var browserify = require('browserify'); +var b = browserify(); +b.add('./browser/main.js'); +b.bundle().pipe(process.stdout); +``` + +# methods + +``` js +var browserify = require('browserify') +``` + +## `browserify([files] [, opts])` + +Returns a new browserify instance. + +
+
+files +
+ +
+String, file object, or array of those types (they may be mixed) specifying entry file(s). +
+ +
+opts +
+ +
+Object. +
+
+ +`files` and `opts` are both optional, but must be in the order shown if both are +passed. + +Entry files may be passed in `files` and / or `opts.entries`. + +External requires may be specified in `opts.require`, accepting the same formats +that the `files` argument does. + +If an entry file is a stream, its contents will be used. You should pass +`opts.basedir` when using streaming files so that relative requires can be +resolved. + +`opts.entries` has the same definition as `files`. + +`opts.noParse` is an array which will skip all require() and global parsing for +each file in the array. Use this for giant libs like jquery or threejs that +don't have any requires or node-style globals but take forever to parse. + +`opts.transform` is an array of transform functions or modules names which will +transform the source code before the parsing. + +`opts.ignoreTransform` is an array of transformations that will not be run, +even if specified elsewhere. + +`opts.plugin` is an array of plugin functions or module names to use. See the +plugins section below for details. + +`opts.extensions` is an array of optional extra extensions for the module lookup +machinery to use when the extension has not been specified. +By default browserify considers only `.js` and `.json` files in such cases. + +`opts.basedir` is the directory that browserify starts bundling from for +filenames that start with `.`. + +`opts.paths` is an array of directories that browserify searches when looking +for modules which are not referenced using relative path. Can be absolute or +relative to `basedir`. Equivalent of setting `NODE_PATH` environmental variable +when calling `browserify` command. + +`opts.commondir` sets the algorithm used to parse out the common paths. Use +`false` to turn this off, otherwise it uses the +[commondir](https://www.npmjs.com/package/commondir) module. + +`opts.fullPaths` disables converting module ids into numerical indexes. This is +useful for preserving the original paths that a bundle was generated with. + +`opts.builtins` sets the list of built-ins to use, which by default is set in +`lib/builtins.js` in this distribution. + +`opts.bundleExternal` boolean option to set if external modules should be +bundled. Defaults to true. + +When `opts.browserField` is false, the package.json browser field will be +ignored. When `opts.browserField` is set to a `string`, then a custom field name +can be used instead of the default `"browser"` field. + +When `opts.insertGlobals` is true, always insert `process`, `global`, +`__filename`, and `__dirname` without analyzing the AST for faster builds but +larger output bundles. Default false. + +When `opts.detectGlobals` is true, scan all files for `process`, `global`, +`__filename`, and `__dirname`, defining as necessary. With this option npm +modules are more likely to work but bundling takes longer. Default true. + +When `opts.ignoreMissing` is true, ignore `require()` statements that don't +resolve to anything. + +When `opts.debug` is true, add a source map inline to the end of the bundle. +This makes debugging easier because you can see all the original files if +you are in a modern enough browser. + +When `opts.standalone` is a non-empty string, a standalone module is created +with that name and a [umd](https://github.com/forbeslindesay/umd) wrapper. +You can use namespaces in the standalone global export using a `.` in the string +name as a separator, for example `'A.B.C'`. The global export will be [sanitized +and camel cased](https://github.com/ForbesLindesay/umd#name-casing-and-characters). + +Note that in standalone mode the `require()` calls from the original source will +still be around, which may trip up AMD loaders scanning for `require()` calls. +You can remove these calls with +[derequire](https://www.npmjs.com/package/derequire): + +``` +$ npm install -g derequire +$ browserify main.js --standalone Foo | derequire > bundle.js +``` + +`opts.insertGlobalVars` will be passed to +[insert-module-globals](https://www.npmjs.com/package/insert-module-globals) +as the `opts.vars` parameter. + +`opts.externalRequireName` defaults to `'require'` in `expose` mode but you can +use another name. + +`opts.bare` creates a bundle that does not include Node builtins, and does not +replace global Node variables except for `__dirname` and `__filename`. + +`opts.node` creates a bundle that runs in Node and does not use the browser +versions of dependencies. Same as passing `{ bare: true, browserField: false }`. + +Note that if files do not contain javascript source code then you also need to +specify a corresponding transform for them. + +All other options are forwarded along to +[module-deps](https://www.npmjs.com/package/module-deps) +and [browser-pack](https://www.npmjs.com/package/browser-pack) directly. + +## b.add(file, opts) + +Add an entry file from `file` that will be executed when the bundle loads. + +If `file` is an array, each item in `file` will be added as an entry file. + +## b.require(file, opts) + +Make `file` available from outside the bundle with `require(file)`. + +The `file` param is anything that can be resolved by `require.resolve()`, +including files from `node_modules`. Like with `require.resolve()`, you must +prefix `file` with `./` to require a local file (not in `node_modules`). + +`file` can also be a stream, but you should also use `opts.basedir` so that +relative requires will be resolvable. + +If `file` is an array, each item in `file` will be required. +In `file` array form, you can use a string or object for each item. Object items +should have a `file` property and the rest of the parameters will be used for +the `opts`. + +Use the `expose` property of opts to specify a custom dependency name. +`require('./vendor/angular/angular.js', {expose: 'angular'})` enables `require('angular')` + +## b.bundle(cb) + +Bundle the files and their dependencies into a single javascript file. + +Return a readable stream with the javascript file contents or +optionally specify a `cb(err, buf)` to get the buffered results. + +## b.external(file) + +Prevent `file` from being loaded into the current bundle, instead referencing +from another bundle. + +If `file` is an array, each item in `file` will be externalized. + +If `file` is another bundle, that bundle's contents will be read and excluded +from the current bundle as the bundle in `file` gets bundled. + +## b.ignore(file) + +Prevent the module name or file at `file` from showing up in the output bundle. + +If `file` is an array, each item in `file` will be ignored. + +Instead you will get a file with `module.exports = {}`. + +## b.exclude(file) + +Prevent the module name or file at `file` from showing up in the output bundle. + +If `file` is an array, each item in `file` will be excluded. + +If your code tries to `require()` that file it will throw unless you've provided +another mechanism for loading it. + +## b.transform(tr, opts={}) + +Transform source code before parsing it for `require()` calls with the transform +function or module name `tr`. + +If `tr` is a function, it will be called with `tr(file)` and it should return a +[through-stream](https://github.com/substack/stream-handbook#through) +that takes the raw file contents and produces the transformed source. + +If `tr` is a string, it should be a module name or file path of a +[transform module](https://github.com/browserify/module-deps#transforms) +with a signature of: + +``` js +var through = require('through'); +module.exports = function (file) { return through() }; +``` + +You don't need to necessarily use the +[through](https://www.npmjs.com/package/through) module. +Browserify is compatible with the newer, more verbose +[Transform streams](http://nodejs.org/api/stream.html#stream_class_stream_transform_1) +built into Node v0.10. + +Here's how you might compile coffee script on the fly using `.transform()`: + +``` js +var coffee = require('coffee-script'); +var through = require('through'); + +b.transform(function (file) { + var data = ''; + return through(write, end); + + function write (buf) { data += buf } + function end () { + this.queue(coffee.compile(data)); + this.queue(null); + } +}); +``` + +Note that on the command-line with the `-c` flag you can just do: + +``` +$ browserify -c 'coffee -sc' main.coffee > bundle.js +``` + +Or better still, use the [coffeeify](https://github.com/jnordberg/coffeeify) +module: + +``` +$ npm install coffeeify +$ browserify -t coffeeify main.coffee > bundle.js +``` + +If `opts.global` is `true`, the transform will operate on ALL files, despite +whether they exist up a level in a `node_modules/` directory. Use global +transforms cautiously and sparingly, since most of the time an ordinary +transform will suffice. You can also not configure global transforms in a +`package.json` like you can with ordinary transforms. + +Global transforms always run after any ordinary transforms have run. + +Transforms may obtain options from the command-line with +[subarg](https://www.npmjs.com/package/subarg) syntax: + +``` +$ browserify -t [ foo --bar=555 ] main.js +``` + +or from the api: + +``` +b.transform('foo', { bar: 555 }) +``` + +In both cases, these options are provided as the second argument to the +transform function: + +``` +module.exports = function (file, opts) { /* opts.bar === 555 */ } +``` + +Options sent to the browserify constructor are also provided under +`opts._flags`. These browserify options are sometimes required if your transform +needs to do something different when browserify is run in debug mode, for +example. + +## b.plugin(plugin, opts) + +Register a `plugin` with `opts`. Plugins can be a string module name or a +function the same as transforms. + +`plugin(b, opts)` is called with the browserify instance `b`. + +For more information, consult the plugins section below. + +## b.pipeline + +There is an internal +[labeled-stream-splicer](https://www.npmjs.com/package/labeled-stream-splicer) +pipeline with these labels: + +* `'record'` - save inputs to play back later on subsequent `bundle()` calls +* `'deps'` - [module-deps](https://www.npmjs.com/package/module-deps) +* `'json'` - adds `module.exports=` to the beginning of json files +* `'unbom'` - remove byte-order markers +* `'unshebang'` - remove #! labels on the first line +* `'syntax'` - check for syntax errors +* `'sort'` - sort the dependencies for deterministic bundles +* `'dedupe'` - remove duplicate source contents +* `'label'` - apply integer labels to files +* `'emit-deps'` - emit `'dep'` event +* `'debug'` - apply source maps +* `'pack'` - [browser-pack](https://www.npmjs.com/package/browser-pack) +* `'wrap'` - apply final wrapping, `require=` and a newline and semicolon + +You can call `b.pipeline.get()` with a label name to get a handle on a stream pipeline +that you can `push()`, `unshift()`, or `splice()` to insert your own transform +streams. + +## b.reset(opts) + +Reset the pipeline back to a normal state. This function is called automatically +when `bundle()` is called multiple times. + +This function triggers a 'reset' event. + +# package.json + +browserify uses the `package.json` in its module resolution algorithm, just like +node. If there is a `"main"` field, browserify will start resolving the package +at that point. If there is no `"main"` field, browserify will look for an +`"index.js"` file in the module root directory. Here are some more +sophisticated things you can do in the package.json: + +## browser field + +There is a special "[browser](https://github.com/defunctzombie/package-browser-field-spec)" field you can +set in your package.json on a per-module basis to override file resolution for +browser-specific versions of files. + +For example, if you want to have a browser-specific module entry point for your +`"main"` field you can just set the `"browser"` field to a string: + +``` json +"browser": "./browser.js" +``` + +or you can have overrides on a per-file basis: + +``` json +"browser": { + "fs": "level-fs", + "./lib/ops.js": "./browser/opts.js" +} +``` + +Note that the browser field only applies to files in the local module, and like +transforms, it doesn't apply into `node_modules` directories. + +## browserify.transform + +You can specify source transforms in the package.json in the +`browserify.transform` field. There is more information about how source +transforms work in package.json on the +[module-deps readme](https://github.com/browserify/module-deps#transforms). + +For example, if your module requires [brfs](https://www.npmjs.com/package/brfs), you +can add + +``` json +"browserify": { "transform": [ "brfs" ] } +``` + +to your package.json. Now when somebody `require()`s your module, brfs will +automatically be applied to the files in your module without explicit +intervention by the person using your module. Make sure to add transforms to +your package.json dependencies field. + +# events + +## b.on('file', function (file, id, parent) {}) +## b.pipeline.on('file', function (file, id, parent) {}) + +When a file is resolved for the bundle, the bundle emits a `'file'` event with +the full `file` path, the `id` string passed to `require()`, and the `parent` +object used by +[browser-resolve](https://github.com/defunctzombie/node-browser-resolve). + +You could use the `file` event to implement a file watcher to regenerate bundles +when files change. + +## b.on('package', function (pkg) {}) +## b.pipeline.on('package', function (pkg) {}) + +When a package file is read, this event fires with the contents. The package +directory is available at `pkg.__dirname`. + +## b.on('bundle', function (bundle) {}) + +When `.bundle()` is called, this event fires with the `bundle` output stream. + +## b.on('reset', function () {}) + +When the `.reset()` method is called or implicitly called by another call to +`.bundle()`, this event fires. + +## b.on('transform', function (tr, file) {}) +## b.pipeline.on('transform', function (tr, file) {}) + +When a transform is applied to a file, the `'transform'` event fires on the +bundle stream with the transform stream `tr` and the `file` that the transform +is being applied to. + +# plugins + +For some more advanced use-cases, a transform is not sufficiently extensible. +Plugins are modules that take the bundle instance as their first parameter and +an option hash as their second. + +Plugins can be used to do perform some fancy features that transforms can't do. +For example, [factor-bundle](https://www.npmjs.com/package/factor-bundle) is a +plugin that can factor out common dependencies from multiple entry-points into a +common bundle. Use plugins with `-p` and pass options to plugins with +[subarg](https://www.npmjs.com/package/subarg) syntax: + +``` +browserify x.js y.js -p [ factor-bundle -o bundle/x.js -o bundle/y.js ] \ + > bundle/common.js +``` + +For a list of plugins, consult the +[browserify-plugin tag](https://www.npmjs.com/browse/keyword/browserify-plugin) +on npm. + +# list of source transforms + +There is a [wiki page that lists the known browserify +transforms](https://github.com/browserify/browserify/wiki/list-of-transforms). + +If you write a transform, make sure to add your transform to that wiki page and +add a package.json keyword of `browserify-transform` so that +[people can browse for all the browserify +transforms](https://www.npmjs.com/browse/keyword/browserify-transform) on npmjs.org. + +# third-party tools + +There is a [wiki page that lists the known browserify +tools](https://github.com/browserify/browserify/wiki/browserify-tools). + +If you write a tool, make sure to add it to that wiki page and +add a package.json keyword of `browserify-tool` so that +[people can browse for all the browserify +tools](https://www.npmjs.com/browse/keyword/browserify-tool) on npmjs.org. + +# changelog + +Releases are documented in +[changelog.markdown](changelog.markdown) and on the +[browserify twitter feed](https://twitter.com/browserify). + +# license + +[MIT](./LICENSE) + +![browserify!](./assets/browserify.png) diff --git a/libcore/node_modules/browserify/security.md b/libcore/node_modules/browserify/security.md new file mode 100644 index 0000000..a14ace6 --- /dev/null +++ b/libcore/node_modules/browserify/security.md @@ -0,0 +1,10 @@ +# Security Policy + +## Supported Versions +Only the latest major version is supported at any given time. + +## Reporting a Vulnerability + +To report a security vulnerability, please use the +[Tidelift security contact](https://tidelift.com/security). +Tidelift will coordinate the fix and disclosure. diff --git a/libcore/node_modules/browserify/test/args.js b/libcore/node_modules/browserify/test/args.js new file mode 100644 index 0000000..6f8cb02 --- /dev/null +++ b/libcore/node_modules/browserify/test/args.js @@ -0,0 +1,72 @@ +var test = require('tap').test; +var fromArgs = require('../bin/args.js'); +var path = require('path'); +var vm = require('vm'); + +test('bundle from an arguments array', function (t) { + t.plan(2); + + var b = fromArgs([ __dirname + '/entry/two.js', '-s', 'XYZ' ]); + b.bundle(function (err, src) { + t.ifError(err); + var c = { window: {} }; + vm.runInNewContext(src, c); + t.equal(c.window.XYZ, 2); + }); +}); + +test('external flag for node modules', function(t) { + t.plan(2); + + var b = fromArgs([ __dirname + '/external_args/main.js', '-x', 'backbone' ]); + b.bundle(function (err, src) { + t.ifError(err); + vm.runInNewContext(src, {t: t}); + }); +}); + +test('bundle from an arguments with --insert-global-vars', function (t) { + t.plan(4); + + var b = fromArgs([ + __dirname + '/global/filename.js', + '--insert-global-vars=__filename,__dirname', + '--basedir', __dirname + ]); + b.require(__dirname + '/global/filename.js', { expose: 'x' }); + b.bundle(function (err, src) { + t.ifError(err, 'b.bundle()'); + var c = {}, x; + vm.runInNewContext(src, c); + t.doesNotThrow(function() { + x = c.require('x'); + }, 'x = c.require(\'x\')'); + t.equal(x && x.filename, '/global/filename.js', 'x.filename'); + t.equal(x && x.dirname, '/global', 'x.dirname'); + }) +}); + +test('numeric module names', function(t) { + t.plan(1); + + var b = fromArgs([ '-x', '1337' ]); + b.bundle(function (err, src) { + t.ifError(err); + }); +}); + +test('entry expose', function (t) { + t.plan(3) + + var b = fromArgs([ + path.join(__dirname, '/entry_expose/main.js'), + '--require', path.join(__dirname, '/entry_expose/main.js') + ':x', + ]); + b.bundle(function (err, src) { + t.ifError(err); + var c = { console: { log: log } }; + function log (msg) { t.equal(msg, 'wow') } + vm.runInNewContext(src, c); + t.equal(c.require('x'), 555); + }) +}); diff --git a/libcore/node_modules/browserify/test/array.js b/libcore/node_modules/browserify/test/array.js new file mode 100644 index 0000000..31d4c89 --- /dev/null +++ b/libcore/node_modules/browserify/test/array.js @@ -0,0 +1,74 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; + +test('array add', function (t) { + var expected = [ 'ONE', 'TWO', 'THREE' ]; + t.plan(expected.length); + + var b = browserify(); + var files = [ + __dirname + '/array/one.js', + __dirname + '/array/two.js', + __dirname + '/array/three.js' + ]; + b.add(files); + b.bundle(function (err, src) { + vm.runInNewContext(src, { console: { log: log } }); + function log (msg) { + t.equal(msg, expected.shift()); + } + }); +}); + +test('array require', function (t) { + t.plan(3); + + var b = browserify(); + var files = [ 'defined', 'subarg' ]; + b.require(files); + b.bundle(function (err, src) { + var c = {}; + vm.runInNewContext(src, c); + + t.equal(c.require('defined')(undefined, true), true); + t.equal(c.require('defined')(undefined, false), false); + t.deepEqual(c.require('subarg')(['-x', '3']), { x: 3, _: [] }); + }); +}); + +test('array require opts', function (t) { + t.plan(3); + + var b = browserify(); + var files = [ + { file: require.resolve('defined'), expose: 'abc' }, + { file: require.resolve('subarg'), expose: 'def' } + ]; + b.require(files); + b.bundle(function (err, src) { + var c = {}; + vm.runInNewContext(src, c); + + t.equal(c.require('abc')(undefined, true), true); + t.equal(c.require('abc')(undefined, false), false); + t.deepEqual(c.require('def')(['-x', '3']), { x: 3, _: [] }); + }); +}); + +test('array external', function (t) { + t.plan(2); + + var b = browserify(__dirname + '/external/main.js'); + b.external(['util','freelist']); + b.bundle(function (err, src) { + if (err) return t.fail(err); + vm.runInNewContext( + 'function require (x) {' + + 'if (x==="freelist") return function (n) { return n + 1000 }' + + '}' + + src, + { t: t } + ); + }); +}); diff --git a/libcore/node_modules/browserify/test/array/one.js b/libcore/node_modules/browserify/test/array/one.js new file mode 100644 index 0000000..c6312fd --- /dev/null +++ b/libcore/node_modules/browserify/test/array/one.js @@ -0,0 +1 @@ +console.log('ONE'); diff --git a/libcore/node_modules/browserify/test/array/three.js b/libcore/node_modules/browserify/test/array/three.js new file mode 100644 index 0000000..77a6c3a --- /dev/null +++ b/libcore/node_modules/browserify/test/array/three.js @@ -0,0 +1 @@ +console.log('THREE'); diff --git a/libcore/node_modules/browserify/test/array/two.js b/libcore/node_modules/browserify/test/array/two.js new file mode 100644 index 0000000..fa60b5a --- /dev/null +++ b/libcore/node_modules/browserify/test/array/two.js @@ -0,0 +1 @@ +console.log('TWO'); diff --git a/libcore/node_modules/browserify/test/async.js b/libcore/node_modules/browserify/test/async.js new file mode 100644 index 0000000..e9bd246 --- /dev/null +++ b/libcore/node_modules/browserify/test/async.js @@ -0,0 +1,24 @@ +var browserify = require('../'); +var fs = require('fs'); +var vm = require('vm'); +var test = require('tap').test; + +var src = fs.readFileSync(__dirname + '/async/src.js','utf8'); +var canAsync = true; +try { Function(src) } catch (err) { canAsync = false } + +if (!canAsync) console.error('# async/await unsupported in this environment') +else test('async/await', function (t) { + t.plan(2); + var b = browserify(__dirname + '/async/src.js'); + b.bundle(function (err, src) { + t.error(err) + var c = { + console: { log: log }, + setTimeout: setTimeout, + clearTimeout: clearTimeout + } + vm.runInNewContext(src, c); + function log (msg) { t.equal(msg, 60) } + }); +}); diff --git a/libcore/node_modules/browserify/test/async/src.js b/libcore/node_modules/browserify/test/async/src.js new file mode 100644 index 0000000..7a50fbc --- /dev/null +++ b/libcore/node_modules/browserify/test/async/src.js @@ -0,0 +1,8 @@ +function f (x) { return new Promise(resolve => { + process.nextTick(() => { resolve(x) }) }) } + +async function add (x) { + return x + await f(20) + await f(30) +} + +add(10).then(v => { console.log(v) }) diff --git a/libcore/node_modules/browserify/test/backbone.js b/libcore/node_modules/browserify/test/backbone.js new file mode 100644 index 0000000..03e6f69 --- /dev/null +++ b/libcore/node_modules/browserify/test/backbone.js @@ -0,0 +1,23 @@ +var browserify = require('../'); +var vm = require('vm'); +var backbone = require('backbone'); +var test = require('tap').test; + +test('backbone', function (t) { + t.plan(3); + var b = browserify(); + b.require('backbone'); + b.bundle(function (err, buf) { + t.ok(Buffer.isBuffer(buf)); + var src = buf.toString('utf8'); + t.ok(src.length > 0); + + var c = { console: console }; + vm.runInNewContext(src, c); + t.deepEqual( + Object.keys(backbone).sort(), + Object.keys(c.require('backbone')).sort() + ); + t.end(); + }); +}); diff --git a/libcore/node_modules/browserify/test/bare.js b/libcore/node_modules/browserify/test/bare.js new file mode 100644 index 0000000..039c587 --- /dev/null +++ b/libcore/node_modules/browserify/test/bare.js @@ -0,0 +1,173 @@ +var test = require('tap').test; +var spawn = require('child_process').spawn; +var browserify = require('../'); +var path = require('path'); +var concat = require('concat-stream'); +var vm = require('vm'); +var fs = require('fs'); +var through = require('through2'); +var temp = require('temp'); +temp.track(); +var tmpdir = temp.mkdirSync({prefix: 'browserify-test'}); + +test('bare', function (t) { + t.plan(4); + + var cwd = process.cwd(); + process.chdir(__dirname); + + var ps = spawn(process.execPath, [ + path.resolve(__dirname, '../bin/cmd.js'), + '-', '--bare' + ]); + ps.stdout.pipe(concat(function (body) { + vm.runInNewContext(body, { + Buffer: function (s) { return s.toLowerCase() }, + console: { + log: function (msg) { t.equal(msg, 'abc') } + } + }); + vm.runInNewContext(body, { + Buffer: Buffer, + console: { + log: function (msg) { + t.ok(Buffer.isBuffer(msg)); + t.equal(msg.toString('utf8'), 'ABC') + } + } + }); + })); + ps.stdin.end('console.log(Buffer("ABC"))'); + + ps.on('exit', function (code) { + t.equal(code, 0); + }); +}); + +test('bare api', function (t) { + t.plan(3); + + var input = through(); + var b = browserify(input, { bare: true }); + b.bundle().pipe(concat(function (body) { + vm.runInNewContext(body, { + Buffer: function (s) { return s.toLowerCase() }, + console: { + log: function (msg) { t.equal(msg, 'abc') } + } + }); + vm.runInNewContext(body, { + Buffer: Buffer, + console: { + log: function (msg) { + t.ok(Buffer.isBuffer(msg)); + t.equal(msg.toString('utf8'), 'ABC') + } + } + }); + })); + input.end('console.log(Buffer("ABC"))'); +}); + +test('bare inserts __filename,__dirname but not process,global,Buffer', function (t) { + t.plan(2); + + var file = path.resolve(__dirname, 'bare/main.js'); + var ps = spawn(process.execPath, [ + path.resolve(__dirname, '../bin/cmd.js'), + file, + '--bare' + ]); + + ps.stdout.pipe(concat(function (body) { + vm.runInNewContext(body, { + require: require, + __dirname: process.cwd(), + console: { + log: function (msg) { + t.same(msg, [ + path.join(__dirname, 'bare'), + path.join(__dirname, 'bare/main.js'), + 'undefined', + 'undefined', + 'undefined' + ]); + } + } + }); + })); + ps.stdin.end(); + + ps.on('exit', function (code) { + t.equal(code, 0); + }); +}); + +test('bare inserts dynamic __filename,__dirname', function (t) { + t.plan(2); + + var file = path.join(tmpdir, 'dirname-filename.js'); + + fs.writeFileSync( + file, + fs.readFileSync(path.resolve(__dirname, 'bare/dirname-filename.js')) + ); + + var ps = spawn(process.execPath, [ + path.resolve(__dirname, '../bin/cmd.js'), + file, + '--bare' + ]); + + ps.stdout.pipe(concat(function (body) { + vm.runInNewContext(body, { + require: require, + __dirname: process.cwd(), + console: { + log: function (msg) { + t.same(msg, [ + path.dirname(file), + file + ]); + } + } + }); + })); + ps.stdin.end(); + + ps.on('exit', function (code) { + t.equal(code, 0); + }); +}); + +test('bare inserts dynamic __filename,__dirname with basedir', function (t) { + t.plan(2); + + var file = 'dirname-filename.js'; + var ps = spawn(process.execPath, [ + path.resolve(__dirname, '../bin/cmd.js'), + file, + '--bare', + '--basedir=' + path.join(__dirname, 'bare') + ]); + + ps.stdout.pipe(concat(function (body) { + vm.runInNewContext(body, { + require: require, + __dirname: process.cwd(), + console: { + log: function (msg) { + t.same(msg, [ + __dirname, + path.join(__dirname, file) + ]); + } + } + }); + })); + ps.stdin.end(); + + ps.on('exit', function (code) { + t.equal(code, 0); + }); +}); diff --git a/libcore/node_modules/browserify/test/bare/dirname-filename.js b/libcore/node_modules/browserify/test/bare/dirname-filename.js new file mode 100644 index 0000000..c10337d --- /dev/null +++ b/libcore/node_modules/browserify/test/bare/dirname-filename.js @@ -0,0 +1,4 @@ +console.log([ + __dirname, + __filename +]); diff --git a/libcore/node_modules/browserify/test/bare/main.js b/libcore/node_modules/browserify/test/bare/main.js new file mode 100644 index 0000000..e791743 --- /dev/null +++ b/libcore/node_modules/browserify/test/bare/main.js @@ -0,0 +1,7 @@ +console.log([ + __dirname, + __filename, + typeof process, + typeof global, + typeof Buffer +]); diff --git a/libcore/node_modules/browserify/test/bare_shebang.js b/libcore/node_modules/browserify/test/bare_shebang.js new file mode 100644 index 0000000..c47bf44 --- /dev/null +++ b/libcore/node_modules/browserify/test/bare_shebang.js @@ -0,0 +1,37 @@ +var test = require('tap').test; +var spawn = require('child_process').spawn; +var path = require('path'); +var concat = require('concat-stream'); +var vm = require('vm'); + +test('bare shebang', function (t) { + t.plan(4); + + var ps = spawn(process.execPath, [ + path.resolve(__dirname, '../bin/cmd.js'), + '-', '--bare' + ]); + ps.stderr.pipe(process.stderr); + ps.stdout.pipe(concat(function (body) { + vm.runInNewContext(body, { + Buffer: function (s) { return s.toLowerCase() }, + console: { + log: function (msg) { t.equal(msg, 'woo') } + } + }); + vm.runInNewContext(body, { + Buffer: Buffer, + console: { + log: function (msg) { + t.ok(Buffer.isBuffer(msg)); + t.equal(msg.toString('utf8'), 'WOO') + } + } + }); + })); + ps.stdin.end('#!/usr/bin/env node\nconsole.log(Buffer("WOO"))'); + + ps.on('exit', function (code) { + t.equal(code, 0); + }); +}); diff --git a/libcore/node_modules/browserify/test/bin.js b/libcore/node_modules/browserify/test/bin.js new file mode 100644 index 0000000..cb7b17a --- /dev/null +++ b/libcore/node_modules/browserify/test/bin.js @@ -0,0 +1,31 @@ +var test = require('tap').test; +var spawn = require('child_process').spawn; +var path = require('path'); +var vm = require('vm'); + +test('bin', function (t) { + t.plan(3); + + var cwd = process.cwd(); + process.chdir(__dirname); + + var ps = spawn(process.execPath, [ + path.resolve(__dirname, '../bin/cmd.js'), + 'entry/main.js' + ]); + var src = ''; + var err = ''; + ps.stdout.on('data', function (buf) { src += buf }); + ps.stderr.on('data', function (buf) { err += buf }); + + ps.on('exit', function (code) { + t.equal(code, 0); + t.equal(err, ''); + + var allDone = false; + var c = { done : function () { allDone = true } }; + + vm.runInNewContext(src, c); + t.ok(allDone); + }); +}); diff --git a/libcore/node_modules/browserify/test/bin_entry.js b/libcore/node_modules/browserify/test/bin_entry.js new file mode 100644 index 0000000..f7e9af3 --- /dev/null +++ b/libcore/node_modules/browserify/test/bin_entry.js @@ -0,0 +1,31 @@ +var test = require('tap').test; +var spawn = require('child_process').spawn; +var path = require('path'); +var vm = require('vm'); + +test('bin --entry', function (t) { + t.plan(3); + + var cwd = process.cwd(); + process.chdir(__dirname); + + var ps = spawn(process.execPath, [ + path.resolve(__dirname, '../bin/cmd.js'), + '--entry', 'entry/main.js' + ]); + var src = ''; + var err = ''; + ps.stdout.on('data', function (buf) { src += buf }); + ps.stderr.on('data', function (buf) { err += buf }); + + ps.on('exit', function (code) { + t.equal(code, 0); + t.equal(err, ''); + + var allDone = false; + var c = { done : function () { allDone = true } }; + + vm.runInNewContext(src, c); + t.ok(allDone); + }); +}); diff --git a/libcore/node_modules/browserify/test/bin_tr_error.js b/libcore/node_modules/browserify/test/bin_tr_error.js new file mode 100644 index 0000000..a681275 --- /dev/null +++ b/libcore/node_modules/browserify/test/bin_tr_error.js @@ -0,0 +1,27 @@ +var browserify = require('../'); +var spawn = require('child_process').spawn; +var test = require('tap').test; +var path = require('path') +var semver = require('semver'); + +// TODO this should be fixable I guess +var flaky = process.platform === 'win32' && semver.satisfies(process.version, 'v0.10.x'); + +test('function transform', { skip: flaky }, function (t) { + t.plan(3); + var ps = spawn(process.execPath, [ + path.resolve(__dirname, '../bin/cmd.js'), + '-t', './tr.js', './main.js' + ], {cwd: path.resolve(__dirname, 'bin_tr_error')}); + var src = ''; + var err = ''; + ps.stdout.on('data', function (buf) { src += buf }); + ps.stderr.on('data', function (buf) { err += buf }); + + ps.on('exit', function (code) { + t.notEqual(code, 0); + var errorFile = path.resolve(__dirname, 'bin_tr_error', 'tr.js'); + t.notEqual(err.indexOf('there was error'), -1, 'Error should contain error message') + t.notEqual(err.indexOf(errorFile), -1, 'Error should contain stack trace') + }); +}); diff --git a/libcore/node_modules/browserify/test/bin_tr_error/main.js b/libcore/node_modules/browserify/test/bin_tr_error/main.js new file mode 100644 index 0000000..ec448ae --- /dev/null +++ b/libcore/node_modules/browserify/test/bin_tr_error/main.js @@ -0,0 +1 @@ +t.equal(XXX * 5, 555); diff --git a/libcore/node_modules/browserify/test/bin_tr_error/tr.js b/libcore/node_modules/browserify/test/bin_tr_error/tr.js new file mode 100644 index 0000000..c4e537e --- /dev/null +++ b/libcore/node_modules/browserify/test/bin_tr_error/tr.js @@ -0,0 +1,12 @@ +var through = require('through2'); + +module.exports = function (file, opts) { + var data = ''; + return through(write, end); + + function write (buf, enc, next) { data += buf; next() } + function end () { + this.emit('error', new Error('there was error')) + this.push(null); + } +}; diff --git a/libcore/node_modules/browserify/test/bom.js b/libcore/node_modules/browserify/test/bom.js new file mode 100644 index 0000000..78cca51 --- /dev/null +++ b/libcore/node_modules/browserify/test/bom.js @@ -0,0 +1,19 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; + +test('byte order marker', function (t) { + t.plan(2); + + var b = browserify(__dirname + '/bom/hello.js'); + b.bundle(function (err, src) { + if (err) t.fail(err); + var c = { + console: { log: function (msg) { + t.equal(msg, 'hello'); + } } + }; + vm.runInNewContext(src, c); + t.notOk(/\ufeff/.test(src.toString('utf8'))); + }); +}); diff --git a/libcore/node_modules/browserify/test/bom/hello.js b/libcore/node_modules/browserify/test/bom/hello.js new file mode 100644 index 0000000..03b374a --- /dev/null +++ b/libcore/node_modules/browserify/test/bom/hello.js @@ -0,0 +1 @@ +console.log('hello') diff --git a/libcore/node_modules/browserify/test/browser_field_file.js b/libcore/node_modules/browserify/test/browser_field_file.js new file mode 100644 index 0000000..cecaef2 --- /dev/null +++ b/libcore/node_modules/browserify/test/browser_field_file.js @@ -0,0 +1,13 @@ +var test = require('tap').test; +var vm = require('vm'); +var browserify = require('../'); + +test('browser field file no ext', function (t) { + t.plan(2); + var b = browserify(__dirname + '/browser_field_file/xyz'); + b.bundle(function (err, src) { + t.ifError(err); + vm.runInNewContext(src, { console: { log: log } }); + function log (msg) { t.equal(msg, 'cool beans') } + }); +}); diff --git a/libcore/node_modules/browserify/test/browser_field_file/package.json b/libcore/node_modules/browserify/test/browser_field_file/package.json new file mode 100644 index 0000000..f146bcc --- /dev/null +++ b/libcore/node_modules/browserify/test/browser_field_file/package.json @@ -0,0 +1,5 @@ +{ + "browser": { + "./xyz": "wow.js" + } +} diff --git a/libcore/node_modules/browserify/test/browser_field_file/wow.js b/libcore/node_modules/browserify/test/browser_field_file/wow.js new file mode 100644 index 0000000..eca0d75 --- /dev/null +++ b/libcore/node_modules/browserify/test/browser_field_file/wow.js @@ -0,0 +1 @@ +console.log('cool beans'); diff --git a/libcore/node_modules/browserify/test/browser_field_resolve.js b/libcore/node_modules/browserify/test/browser_field_resolve.js new file mode 100644 index 0000000..0b26fef --- /dev/null +++ b/libcore/node_modules/browserify/test/browser_field_resolve.js @@ -0,0 +1,124 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; + +test('browser field resolve (a)', function (t) { + t.plan(2); + var b = browserify(__dirname + '/browser_field_resolve/a/main.js'); + b.bundle(function (err, src) { + t.ifError(err); + vm.runInNewContext(src, { console: { log: log } }); + function log (x) { t.equal(x, 555) } + }); +}); + +test('browser field resolve (b)', function (t) { + t.plan(2); + var b = browserify(__dirname + '/browser_field_resolve/b/main.js'); + b.bundle(function (err, src) { + t.ifError(err); + vm.runInNewContext(src, { console: { log: log } }); + function log (x) { t.equal(x, 444) } + }); +}); + +test('browser field resolve (c)', function (t) { + t.plan(2); + var b = browserify(__dirname + '/browser_field_resolve/c/main.js'); + b.bundle(function (err, src) { + t.ifError(err); + vm.runInNewContext(src, { console: { log: log } }); + function log (x) { t.equal(x, 333) } + }); + +}); + +test('browser field resolve (d)', function (t) { + t.plan(2); + var b = browserify(__dirname + '/browser_field_resolve/d/main.js'); + b.bundle(function (err, src) { + t.ifError(err); + vm.runInNewContext(src, { console: { log: log } }); + function log (x) { t.equal(x, 222) } + }); +}); + +test('browser field resolve (e)', function (t) { + t.plan(2); + var b = browserify(__dirname + '/browser_field_resolve/e/main.js'); + b.bundle(function (err, src) { + t.ifError(err); + vm.runInNewContext(src, { console: { log: log } }); + function log (x) { t.equal(x, 111) } + }); +}); + +test('browser field resolve (f)', function (t) { + t.plan(2); + var b = browserify(__dirname + '/browser_field_resolve/f/main.js'); + b.bundle(function (err, src) { + t.ifError(err); + vm.runInNewContext(src, { console: { log: log } }); + function log (x) { t.equal(x, 999) } + }); +}); + +test('browser field resolve (g)', function (t) { + t.plan(2); + var b = browserify(__dirname + '/browser_field_resolve/g/main.js'); + b.bundle(function (err, src) { + t.ifError(err); + vm.runInNewContext(src, { console: { log: log } }); + function log (x) { t.deepEqual(x, {}) } + }); +}); + +test('browser field resolve (h)', function (t) { + t.plan(2); + var b = browserify(__dirname + '/browser_field_resolve/h/main.js'); + b.bundle(function (err, src) { + t.ifError(err); + vm.runInNewContext(src, { console: { log: log } }); + function log (x) { t.deepEqual(x, {}) } + }); +}); + +test('browser field resolve (i)', function (t) { + t.plan(2); + var b = browserify(__dirname + '/browser_field_resolve/i/main.js'); + b.bundle(function (err, src) { + t.ifError(err); + vm.runInNewContext(src, { console: { log: log } }); + function log (x) { t.deepEqual(x, 5000) } + }); +}); + +test('browser field resolve (j)', function (t) { + t.plan(2); + var b = browserify(__dirname + '/browser_field_resolve/j/main.js'); + b.bundle(function (err, src) { + t.ifError(err); + vm.runInNewContext(src, { console: { log: log } }); + function log (x) { t.deepEqual(x, 5000) } + }); +}); + +test('browser field resolve (k)', function (t) { + t.plan(2); + var b = browserify(__dirname + '/browser_field_resolve/k/main.js'); + b.bundle(function (err, src) { + t.ifError(err); + vm.runInNewContext(src, { console: { log: log } }); + function log (x) { t.deepEqual(x, 3000) } + }); +}); + +test('browser field resolve (l)', function (t) { + t.plan(2); + var b = browserify(__dirname + '/browser_field_resolve/l/main.js'); + b.bundle(function (err, src) { + t.ifError(err); + vm.runInNewContext(src, { console: { log: log } }); + function log (x) { t.deepEqual(x, 3000) } + }); +}); diff --git a/libcore/node_modules/browserify/test/browser_field_resolve/a/main.js b/libcore/node_modules/browserify/test/browser_field_resolve/a/main.js new file mode 100644 index 0000000..04798b6 --- /dev/null +++ b/libcore/node_modules/browserify/test/browser_field_resolve/a/main.js @@ -0,0 +1 @@ +console.log(require('zzz')) diff --git a/libcore/node_modules/browserify/test/browser_field_resolve/a/package.json b/libcore/node_modules/browserify/test/browser_field_resolve/a/package.json new file mode 100644 index 0000000..36ad486 --- /dev/null +++ b/libcore/node_modules/browserify/test/browser_field_resolve/a/package.json @@ -0,0 +1,5 @@ +{ + "browser": { + "zzz": "aaa" + } +} diff --git a/libcore/node_modules/browserify/test/browser_field_resolve/b/main.js b/libcore/node_modules/browserify/test/browser_field_resolve/b/main.js new file mode 100644 index 0000000..04798b6 --- /dev/null +++ b/libcore/node_modules/browserify/test/browser_field_resolve/b/main.js @@ -0,0 +1 @@ +console.log(require('zzz')) diff --git a/libcore/node_modules/browserify/test/browser_field_resolve/b/package.json b/libcore/node_modules/browserify/test/browser_field_resolve/b/package.json new file mode 100644 index 0000000..ed91400 --- /dev/null +++ b/libcore/node_modules/browserify/test/browser_field_resolve/b/package.json @@ -0,0 +1,5 @@ +{ + "browser": { + "zzz": "./x" + } +} diff --git a/libcore/node_modules/browserify/test/browser_field_resolve/b/x.js b/libcore/node_modules/browserify/test/browser_field_resolve/b/x.js new file mode 100644 index 0000000..41a4973 --- /dev/null +++ b/libcore/node_modules/browserify/test/browser_field_resolve/b/x.js @@ -0,0 +1 @@ +module.exports = 444 diff --git a/libcore/node_modules/browserify/test/browser_field_resolve/c/main.js b/libcore/node_modules/browserify/test/browser_field_resolve/c/main.js new file mode 100644 index 0000000..d2bbb53 --- /dev/null +++ b/libcore/node_modules/browserify/test/browser_field_resolve/c/main.js @@ -0,0 +1 @@ +console.log(require('./z.js')) diff --git a/libcore/node_modules/browserify/test/browser_field_resolve/c/package.json b/libcore/node_modules/browserify/test/browser_field_resolve/c/package.json new file mode 100644 index 0000000..2bd5e9d --- /dev/null +++ b/libcore/node_modules/browserify/test/browser_field_resolve/c/package.json @@ -0,0 +1,5 @@ +{ + "browser": { + "./z": "./x" + } +} diff --git a/libcore/node_modules/browserify/test/browser_field_resolve/c/x.js b/libcore/node_modules/browserify/test/browser_field_resolve/c/x.js new file mode 100644 index 0000000..9123882 --- /dev/null +++ b/libcore/node_modules/browserify/test/browser_field_resolve/c/x.js @@ -0,0 +1 @@ +module.exports = 333 diff --git a/libcore/node_modules/browserify/test/browser_field_resolve/d/main.js b/libcore/node_modules/browserify/test/browser_field_resolve/d/main.js new file mode 100644 index 0000000..d2bbb53 --- /dev/null +++ b/libcore/node_modules/browserify/test/browser_field_resolve/d/main.js @@ -0,0 +1 @@ +console.log(require('./z.js')) diff --git a/libcore/node_modules/browserify/test/browser_field_resolve/d/package.json b/libcore/node_modules/browserify/test/browser_field_resolve/d/package.json new file mode 100644 index 0000000..deeed56 --- /dev/null +++ b/libcore/node_modules/browserify/test/browser_field_resolve/d/package.json @@ -0,0 +1,5 @@ +{ + "browser": { + "./z.js": "./x.js" + } +} diff --git a/libcore/node_modules/browserify/test/browser_field_resolve/d/x.js b/libcore/node_modules/browserify/test/browser_field_resolve/d/x.js new file mode 100644 index 0000000..fb98b13 --- /dev/null +++ b/libcore/node_modules/browserify/test/browser_field_resolve/d/x.js @@ -0,0 +1 @@ +module.exports = 222 diff --git a/libcore/node_modules/browserify/test/browser_field_resolve/e/main.js b/libcore/node_modules/browserify/test/browser_field_resolve/e/main.js new file mode 100644 index 0000000..d2bbb53 --- /dev/null +++ b/libcore/node_modules/browserify/test/browser_field_resolve/e/main.js @@ -0,0 +1 @@ +console.log(require('./z.js')) diff --git a/libcore/node_modules/browserify/test/browser_field_resolve/e/package.json b/libcore/node_modules/browserify/test/browser_field_resolve/e/package.json new file mode 100644 index 0000000..8538725 --- /dev/null +++ b/libcore/node_modules/browserify/test/browser_field_resolve/e/package.json @@ -0,0 +1,5 @@ +{ + "browser": { + "./z": "./x.js" + } +} diff --git a/libcore/node_modules/browserify/test/browser_field_resolve/e/x.js b/libcore/node_modules/browserify/test/browser_field_resolve/e/x.js new file mode 100644 index 0000000..409ecf4 --- /dev/null +++ b/libcore/node_modules/browserify/test/browser_field_resolve/e/x.js @@ -0,0 +1 @@ +module.exports = 111 diff --git a/libcore/node_modules/browserify/test/browser_field_resolve/f/main.js b/libcore/node_modules/browserify/test/browser_field_resolve/f/main.js new file mode 100644 index 0000000..9e1be00 --- /dev/null +++ b/libcore/node_modules/browserify/test/browser_field_resolve/f/main.js @@ -0,0 +1 @@ +console.log(require('aaa/what.js')) diff --git a/libcore/node_modules/browserify/test/browser_field_resolve/f/package.json b/libcore/node_modules/browserify/test/browser_field_resolve/f/package.json new file mode 100644 index 0000000..3390040 --- /dev/null +++ b/libcore/node_modules/browserify/test/browser_field_resolve/f/package.json @@ -0,0 +1,5 @@ +{ + "browser": { + "aaa/what": "./x.js" + } +} diff --git a/libcore/node_modules/browserify/test/browser_field_resolve/f/x.js b/libcore/node_modules/browserify/test/browser_field_resolve/f/x.js new file mode 100644 index 0000000..95c041e --- /dev/null +++ b/libcore/node_modules/browserify/test/browser_field_resolve/f/x.js @@ -0,0 +1 @@ +module.exports = 999 diff --git a/libcore/node_modules/browserify/test/browser_field_resolve/g/main.js b/libcore/node_modules/browserify/test/browser_field_resolve/g/main.js new file mode 100644 index 0000000..3100f1d --- /dev/null +++ b/libcore/node_modules/browserify/test/browser_field_resolve/g/main.js @@ -0,0 +1,2 @@ +try { var x = require('./x') } catch (err) {} +console.log(x) diff --git a/libcore/node_modules/browserify/test/browser_field_resolve/g/package.json b/libcore/node_modules/browserify/test/browser_field_resolve/g/package.json new file mode 100644 index 0000000..3d0142c --- /dev/null +++ b/libcore/node_modules/browserify/test/browser_field_resolve/g/package.json @@ -0,0 +1,5 @@ +{ + "browser": { + "./x.js": false + } +} diff --git a/libcore/node_modules/browserify/test/browser_field_resolve/g/x.js b/libcore/node_modules/browserify/test/browser_field_resolve/g/x.js new file mode 100644 index 0000000..ae629b6 --- /dev/null +++ b/libcore/node_modules/browserify/test/browser_field_resolve/g/x.js @@ -0,0 +1 @@ +module.exports = 1000 diff --git a/libcore/node_modules/browserify/test/browser_field_resolve/h/main.js b/libcore/node_modules/browserify/test/browser_field_resolve/h/main.js new file mode 100644 index 0000000..29ad627 --- /dev/null +++ b/libcore/node_modules/browserify/test/browser_field_resolve/h/main.js @@ -0,0 +1,2 @@ +try { var x = require('./x.js') } catch (err) {} +console.log(x) diff --git a/libcore/node_modules/browserify/test/browser_field_resolve/h/package.json b/libcore/node_modules/browserify/test/browser_field_resolve/h/package.json new file mode 100644 index 0000000..d8bf9d1 --- /dev/null +++ b/libcore/node_modules/browserify/test/browser_field_resolve/h/package.json @@ -0,0 +1,5 @@ +{ + "browser": { + "./x": false + } +} diff --git a/libcore/node_modules/browserify/test/browser_field_resolve/h/x.js b/libcore/node_modules/browserify/test/browser_field_resolve/h/x.js new file mode 100644 index 0000000..ae629b6 --- /dev/null +++ b/libcore/node_modules/browserify/test/browser_field_resolve/h/x.js @@ -0,0 +1 @@ +module.exports = 1000 diff --git a/libcore/node_modules/browserify/test/browser_field_resolve/i/browser.js b/libcore/node_modules/browserify/test/browser_field_resolve/i/browser.js new file mode 100644 index 0000000..7651b1a --- /dev/null +++ b/libcore/node_modules/browserify/test/browser_field_resolve/i/browser.js @@ -0,0 +1 @@ +module.exports = 5000 diff --git a/libcore/node_modules/browserify/test/browser_field_resolve/i/main.js b/libcore/node_modules/browserify/test/browser_field_resolve/i/main.js new file mode 100644 index 0000000..164cd23 --- /dev/null +++ b/libcore/node_modules/browserify/test/browser_field_resolve/i/main.js @@ -0,0 +1,2 @@ +var x = require('./x.js') +console.log(x) diff --git a/libcore/node_modules/browserify/test/browser_field_resolve/i/package.json b/libcore/node_modules/browserify/test/browser_field_resolve/i/package.json new file mode 100644 index 0000000..aac08b0 --- /dev/null +++ b/libcore/node_modules/browserify/test/browser_field_resolve/i/package.json @@ -0,0 +1,5 @@ +{ + "browser": { + "./x": "./browser" + } +} diff --git a/libcore/node_modules/browserify/test/browser_field_resolve/i/x.js b/libcore/node_modules/browserify/test/browser_field_resolve/i/x.js new file mode 100644 index 0000000..ae629b6 --- /dev/null +++ b/libcore/node_modules/browserify/test/browser_field_resolve/i/x.js @@ -0,0 +1 @@ +module.exports = 1000 diff --git a/libcore/node_modules/browserify/test/browser_field_resolve/j/browser.js b/libcore/node_modules/browserify/test/browser_field_resolve/j/browser.js new file mode 100644 index 0000000..7651b1a --- /dev/null +++ b/libcore/node_modules/browserify/test/browser_field_resolve/j/browser.js @@ -0,0 +1 @@ +module.exports = 5000 diff --git a/libcore/node_modules/browserify/test/browser_field_resolve/j/main.js b/libcore/node_modules/browserify/test/browser_field_resolve/j/main.js new file mode 100644 index 0000000..b9f4055 --- /dev/null +++ b/libcore/node_modules/browserify/test/browser_field_resolve/j/main.js @@ -0,0 +1,2 @@ +var x = require('./x') +console.log(x) diff --git a/libcore/node_modules/browserify/test/browser_field_resolve/j/package.json b/libcore/node_modules/browserify/test/browser_field_resolve/j/package.json new file mode 100644 index 0000000..8f61728 --- /dev/null +++ b/libcore/node_modules/browserify/test/browser_field_resolve/j/package.json @@ -0,0 +1,5 @@ +{ + "browser": { + "./x.js": "./browser.js" + } +} diff --git a/libcore/node_modules/browserify/test/browser_field_resolve/j/x.js b/libcore/node_modules/browserify/test/browser_field_resolve/j/x.js new file mode 100644 index 0000000..ae629b6 --- /dev/null +++ b/libcore/node_modules/browserify/test/browser_field_resolve/j/x.js @@ -0,0 +1 @@ +module.exports = 1000 diff --git a/libcore/node_modules/browserify/test/browser_field_resolve/k/main.js b/libcore/node_modules/browserify/test/browser_field_resolve/k/main.js new file mode 100644 index 0000000..993b834 --- /dev/null +++ b/libcore/node_modules/browserify/test/browser_field_resolve/k/main.js @@ -0,0 +1,2 @@ +var zzz = require('x/zzz') +console.log(zzz) diff --git a/libcore/node_modules/browserify/test/browser_field_resolve/l/main.js b/libcore/node_modules/browserify/test/browser_field_resolve/l/main.js new file mode 100644 index 0000000..993b834 --- /dev/null +++ b/libcore/node_modules/browserify/test/browser_field_resolve/l/main.js @@ -0,0 +1,2 @@ +var zzz = require('x/zzz') +console.log(zzz) diff --git a/libcore/node_modules/browserify/test/buffer.js b/libcore/node_modules/browserify/test/buffer.js new file mode 100644 index 0000000..7cfdb1c --- /dev/null +++ b/libcore/node_modules/browserify/test/buffer.js @@ -0,0 +1,144 @@ +var browserify = require('../'); +var test = require('tap').test; +var vm = require('vm'); + +if (!ArrayBuffer.isView) ArrayBuffer.isView = function () { return false; }; + +test('utf8 buffer to base64', function (t) { + t.plan(1); + var b = browserify(); + b.require('buffer'); + b.bundle(function (err, src) { + if (err) return t.fail(err); + var c = context(); + vm.runInNewContext(src, c); + t.equal( + new c.require('buffer').Buffer("Ձאab", "utf8").toString("base64"), + new Buffer("Ձאab", "utf8").toString("base64") + ); + }); +}); + +test('utf8 buffer to hex', function (t) { + t.plan(1); + var b = browserify(); + b.require('buffer'); + b.bundle(function (err, src) { + var c = context(); + vm.runInNewContext(src, c); + t.equal( + new c.require('buffer').Buffer("Ձאab", "utf8").toString("hex"), + new Buffer("Ձאab", "utf8").toString("hex") + ); + }); +}); + +test('ascii buffer to base64', function (t) { + t.plan(1); + var b = browserify(); + b.require('buffer'); + + b.bundle(function (err, src) { + var c = context(); + vm.runInNewContext(src, c); + t.equal( + new c.require('buffer').Buffer("123456!@#$%^", "ascii").toString("base64"), + new Buffer("123456!@#$%^", "ascii").toString("base64") + ); + }); +}); + +test('ascii buffer to hex', function (t) { + t.plan(1); + var b = browserify(); + b.require('buffer'); + b.bundle(function (err, src) { + var c = context(); + vm.runInNewContext(src, c); + t.equal( + new c.require('buffer').Buffer("123456!@#$%^", "ascii").toString("hex"), + new Buffer("123456!@#$%^", "ascii").toString("hex") + ); + }); +}); + +test('base64 buffer to utf8', function (t) { + t.plan(1); + var b = browserify(); + b.require('buffer'); + b.bundle(function (err, src) { + var c = context(); + vm.runInNewContext(src, c); + t.equal( + new c.require('buffer').Buffer("1YHXkGFi", "base64").toString("utf8"), + new Buffer("1YHXkGFi", "base64").toString("utf8") + ); + }); +}); + +test('hex buffer to utf8', function (t) { + t.plan(1); + var b = browserify(); + b.require('buffer'); + b.bundle(function (err, src) { + var c = context(); + vm.runInNewContext(src, c); + var B = c.require('buffer'); + t.equal( + new B.Buffer("d581d7906162", "hex").toString("utf8"), + new Buffer("d581d7906162", "hex").toString("utf8") + ); + }); +}); + +test('base64 buffer to ascii', function (t) { + t.plan(1); + var b = browserify(); + b.require('buffer'); + b.bundle(function (err, src) { + var c = context(); + vm.runInNewContext(src, c); + t.equal( + new c.require('buffer').Buffer("MTIzNDU2IUAjJCVe", "base64").toString("ascii"), + new Buffer("MTIzNDU2IUAjJCVe", "base64").toString("ascii") + ); + }); +}); + +test('hex buffer to ascii', function (t) { + t.plan(1); + var b = browserify(); + b.require('buffer'); + b.bundle(function (err, src) { + var c = context(); + vm.runInNewContext(src, c); + t.equal( + new c.require('buffer').Buffer("31323334353621402324255e", "hex").toString("ascii"), + new Buffer("31323334353621402324255e", "hex").toString("ascii") + ); + }); +}); + +test('indexing a buffer', function (t) { + t.plan(5); + var b = browserify(); + b.require('buffer'); + b.bundle(function (err, src) { + var c = context(); + vm.runInNewContext(src, c); + var buf = c.require('buffer').Buffer('abc'); + t.equal(buf[0], 97); + t.equal(buf[1], 98); + t.equal(buf[2], 99); + t.equal(buf[3], undefined); + t.equal(buf.toString('utf8'), 'abc'); + }); +}); + +function context () { + return { + ArrayBuffer: ArrayBuffer, + Uint8Array: Uint8Array, + DataView: DataView + }; +} diff --git a/libcore/node_modules/browserify/test/bundle-bundle-external.js b/libcore/node_modules/browserify/test/bundle-bundle-external.js new file mode 100644 index 0000000..559e7f1 --- /dev/null +++ b/libcore/node_modules/browserify/test/bundle-bundle-external.js @@ -0,0 +1,31 @@ +var browserify = require('../'); +var test = require('tap').test; + +var pubdir = __dirname; +var dir = pubdir + '/bundle-bundle-external'; + +var opt = { + debug: true, + basedir: pubdir, + exposeAll: true +}; + +test('bundle bundle external', function (t) { + t.plan(1); + var bundle1 = browserify(opt); + var name = dir + '/foo.js'; + bundle1.require(name, { entry: true, expose: name, basedir: pubdir }); + + var bundle2 = browserify({ + debug: true, + basedir: pubdir, + entries: [ dir + '/baz.js' ] + }); + + // adding and removing this line causes failure // + //bundle2.external(bundle1); + + bundle2.bundle(function(err, src) { + t.ifError(err); + }); +}); diff --git a/libcore/node_modules/browserify/test/bundle-bundle-external/bar.js b/libcore/node_modules/browserify/test/bundle-bundle-external/bar.js new file mode 100644 index 0000000..8079379 --- /dev/null +++ b/libcore/node_modules/browserify/test/bundle-bundle-external/bar.js @@ -0,0 +1,2 @@ +module.exports = 'bar'; +done(); diff --git a/libcore/node_modules/browserify/test/bundle-bundle-external/baz.js b/libcore/node_modules/browserify/test/bundle-bundle-external/baz.js new file mode 100644 index 0000000..1dda5de --- /dev/null +++ b/libcore/node_modules/browserify/test/bundle-bundle-external/baz.js @@ -0,0 +1,3 @@ +var foo = require('./foo'); +assert.equal(foo, 'foo'); +done(); diff --git a/libcore/node_modules/browserify/test/bundle-bundle-external/foo.js b/libcore/node_modules/browserify/test/bundle-bundle-external/foo.js new file mode 100644 index 0000000..99cf946 --- /dev/null +++ b/libcore/node_modules/browserify/test/bundle-bundle-external/foo.js @@ -0,0 +1,5 @@ +var bar = require('./bar'); +assert.equal(bar, 'bar'); + +module.exports = 'foo'; +done(); diff --git a/libcore/node_modules/browserify/test/bundle-stream.js b/libcore/node_modules/browserify/test/bundle-stream.js new file mode 100644 index 0000000..4193b33 --- /dev/null +++ b/libcore/node_modules/browserify/test/bundle-stream.js @@ -0,0 +1,18 @@ +var browserify = require('../'); +var test = require('tap').test; + +var isReadable = require('isstream').isReadable; +var isWritable = require('isstream').isWritable; + +test('bundle is readable stream', function (t) { + t.plan(4); + var b = browserify(__dirname + '/entry/main.js'); + b.on('bundle', function(bundle) { + t.ok(isReadable(bundle)); + t.notok(isWritable(bundle)); + }); + + var stream = b.bundle(); + t.ok(isReadable(stream)); + t.notok(isWritable(stream)); +}); diff --git a/libcore/node_modules/browserify/test/bundle.js b/libcore/node_modules/browserify/test/bundle.js new file mode 100644 index 0000000..115317a --- /dev/null +++ b/libcore/node_modules/browserify/test/bundle.js @@ -0,0 +1,33 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; + +test('bundle', function (t) { + var b = browserify(); + b.require('seq'); + b.bundle(function (err, src) { + t.plan(3); + + t.ifError(err); + t.ok(src.length > 0); + + var c = { + setTimeout : setTimeout, + clearTimeout : clearTimeout, + console : console + }; + vm.runInNewContext(src, c); + + c.require('seq')([1,2,3]) + .parMap_(function (next, x) { + setTimeout(function () { + next.ok(x * 100) + }, 10) + }) + .seq(function (x,y,z) { + t.deepEqual([x,y,z], [100,200,300]); + t.end(); + }) + ; + }); +}); diff --git a/libcore/node_modules/browserify/test/bundle_external.js b/libcore/node_modules/browserify/test/bundle_external.js new file mode 100644 index 0000000..05a0ac2 --- /dev/null +++ b/libcore/node_modules/browserify/test/bundle_external.js @@ -0,0 +1,26 @@ +var test = require('tap').test; +var browserify = require('../'); +var vm = require('vm'); + +test('bundle external', function (t) { + t.plan(3); + + var expected = [ + { name: 'beep', value: 111 }, + { name: 't-rex', value: 5 } + ]; + + var b = browserify({ bundleExternal: false }); + b.add(__dirname + '/bundle_external/main.js'); + b.bundle(function (err, src) { + var c = { + t: t, + require: function (name) { + var r = expected.shift(); + t.equal(name, r.name); + return r.value; + } + }; + vm.runInNewContext(src, c); + }); +}); diff --git a/libcore/node_modules/browserify/test/bundle_external/boop.js b/libcore/node_modules/browserify/test/bundle_external/boop.js new file mode 100644 index 0000000..e785264 --- /dev/null +++ b/libcore/node_modules/browserify/test/bundle_external/boop.js @@ -0,0 +1,4 @@ +var robot = require('./robot.js'); +var trex = require('t-rex'); + +module.exports = function (n) { return robot(n) * trex }; diff --git a/libcore/node_modules/browserify/test/bundle_external/main.js b/libcore/node_modules/browserify/test/bundle_external/main.js new file mode 100644 index 0000000..88e3f1d --- /dev/null +++ b/libcore/node_modules/browserify/test/bundle_external/main.js @@ -0,0 +1,4 @@ +var beep = require('beep'); +var boop = require('./boop.js'); + +t.equal(boop(beep), 560); diff --git a/libcore/node_modules/browserify/test/bundle_external/robot.js b/libcore/node_modules/browserify/test/bundle_external/robot.js new file mode 100644 index 0000000..2a569dd --- /dev/null +++ b/libcore/node_modules/browserify/test/bundle_external/robot.js @@ -0,0 +1 @@ +module.exports = function (n) { return n + 1 }; diff --git a/libcore/node_modules/browserify/test/bundle_external_global.js b/libcore/node_modules/browserify/test/bundle_external_global.js new file mode 100644 index 0000000..ae02b81 --- /dev/null +++ b/libcore/node_modules/browserify/test/bundle_external_global.js @@ -0,0 +1,24 @@ +var test = require('tap').test; +var browserify = require('../'); +var through = require('through2'); +var vm = require('vm'); + +test('bundle external global', function (t) { + t.plan(1); + + var stream = through(); + stream.push('console.log(process)'); + stream.push(null); + + var b = browserify({ bundleExternal: false }); + b.add(stream); + b.bundle(function (err, src) { + vm.runInNewContext(src, { + console: { log: log }, + process: process + }); + function log (msg) { + t.equal(msg, process); + } + }); +}); diff --git a/libcore/node_modules/browserify/test/bundle_sourcemap.js b/libcore/node_modules/browserify/test/bundle_sourcemap.js new file mode 100644 index 0000000..02b8f43 --- /dev/null +++ b/libcore/node_modules/browserify/test/bundle_sourcemap.js @@ -0,0 +1,32 @@ +var browserify = require('../'); +var test = require('tap').test; + +test('bundle in debug mode', function (t) { + t.plan(3); + + var b = browserify({ debug: true }); + b.require('seq'); + b.bundle(function (err, buf) { + var src = buf.toString('utf8'); + var secondtolastLine = src.split('\n').slice(-2); + + t.ok(typeof src === 'string'); + t.ok(src.length > 0); + t.ok(/^\/\/# sourceMappingURL=/.test(secondtolastLine), 'includes sourcemap'); + }); +}); + +test('bundle in non debug mode', function (t) { + t.plan(3); + + var b = browserify(); + b.require('seq'); + b.bundle(function (err, buf) { + var src = buf.toString('utf8'); + var secondtolastLine = src.split('\n').slice(-2); + + t.ok(typeof src === 'string'); + t.ok(src.length > 0); + t.notOk(/^\/\/# sourceMappingURL=/.test(secondtolastLine), 'includes no sourcemap'); + }); +}); diff --git a/libcore/node_modules/browserify/test/catch.js b/libcore/node_modules/browserify/test/catch.js new file mode 100644 index 0000000..f85b67b --- /dev/null +++ b/libcore/node_modules/browserify/test/catch.js @@ -0,0 +1,22 @@ +var browserify = require('../'); +var test = require('tap').test; + +test('catch pipeline errors with a callback', function (t) { + t.plan(2); + + var b = browserify(__dirname + '/catch/main.js'); + b.bundle(function (err, src) { + t.ok(err); + t.ok(/no_such_file/.test(err)); + }); +}); + +test('catch pipeline errors with an event', function (t) { + t.plan(2); + + var b = browserify(__dirname + '/catch/main.js').bundle(); + b.on('error', function (err) { + t.ok(err); + t.ok(/no_such_file/.test(err)); + }); +}); diff --git a/libcore/node_modules/browserify/test/catch/main.js b/libcore/node_modules/browserify/test/catch/main.js new file mode 100644 index 0000000..a522a65 --- /dev/null +++ b/libcore/node_modules/browserify/test/catch/main.js @@ -0,0 +1 @@ +require('./no_such_file'); diff --git a/libcore/node_modules/browserify/test/circular.js b/libcore/node_modules/browserify/test/circular.js new file mode 100644 index 0000000..92efade --- /dev/null +++ b/libcore/node_modules/browserify/test/circular.js @@ -0,0 +1,34 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; + +test('circular', function (t) { + t.plan(1); + + var b = browserify(__dirname + '/circular/main.js'); + b.bundle(function (err, src) { + vm.runInNewContext(src, { t: t }); + }); +}); + +test('circular expose', function (t) { + t.plan(1); + + var b = browserify(__dirname + '/circular/main.js'); + b.require(__dirname + '/circular/a.js', { expose: './a.js' }); + b.require(__dirname + '/circular/b.js', { expose: './b.js' }); + b.bundle(function (err, src) { + vm.runInNewContext(src, { t: t }); + }); +}); + +test('circular require', function (t) { + t.plan(1); + + var b = browserify(__dirname + '/circular/main.js'); + b.require(__dirname + '/circular/a.js'); + b.require(__dirname + '/circular/b.js'); + b.bundle(function (err, src) { + vm.runInNewContext(src, { t: t }); + }); +}); diff --git a/libcore/node_modules/browserify/test/circular/a.js b/libcore/node_modules/browserify/test/circular/a.js new file mode 100644 index 0000000..f3adf1d --- /dev/null +++ b/libcore/node_modules/browserify/test/circular/a.js @@ -0,0 +1,3 @@ +exports.a = 1; +exports.b = require('./b'); +exports.a = 5; diff --git a/libcore/node_modules/browserify/test/circular/b.js b/libcore/node_modules/browserify/test/circular/b.js new file mode 100644 index 0000000..f342a84 --- /dev/null +++ b/libcore/node_modules/browserify/test/circular/b.js @@ -0,0 +1 @@ +module.exports = 2 + require('./a').a diff --git a/libcore/node_modules/browserify/test/circular/main.js b/libcore/node_modules/browserify/test/circular/main.js new file mode 100644 index 0000000..cbabf97 --- /dev/null +++ b/libcore/node_modules/browserify/test/circular/main.js @@ -0,0 +1 @@ +t.deepEqual(require('./a.js'), { a: 5, b: 3 }); diff --git a/libcore/node_modules/browserify/test/coffee_bin.js b/libcore/node_modules/browserify/test/coffee_bin.js new file mode 100644 index 0000000..e505692 --- /dev/null +++ b/libcore/node_modules/browserify/test/coffee_bin.js @@ -0,0 +1,36 @@ +var test = require('tap').test; +var spawn = require('child_process').spawn; +var path = require('path'); +var vm = require('vm'); + +test('compiling coffee with -c', function (t) { + t.plan(4); + + var cwd = process.cwd(); + process.chdir(__dirname); + + var ps = spawn(process.execPath, [ + path.resolve(__dirname, '../bin/cmd.js'), + '-c', '"' + process.execPath + '" "' + __dirname + '/../node_modules/coffee-script/bin/coffee" -sc', + 'coffee_bin/main.coffee' + ]); + var src = ''; + var err = ''; + ps.stdout.on('data', function (buf) { src += buf }); + ps.stderr.on('data', function (buf) { err += buf }); + + ps.on('exit', function (code) { + t.equal(code, 0); + t.equal(err, ''); + + var msgs = [ 'hello world!', 'from x!' ]; + var c = { + console: { + log: function (msg) { + t.equal(msg, msgs.shift()); + } + } + }; + vm.runInNewContext(src, c); + }); +}); diff --git a/libcore/node_modules/browserify/test/coffee_bin/main.coffee b/libcore/node_modules/browserify/test/coffee_bin/main.coffee new file mode 100644 index 0000000..e9b9dc9 --- /dev/null +++ b/libcore/node_modules/browserify/test/coffee_bin/main.coffee @@ -0,0 +1,2 @@ +console.log "hello world!" +require './x.coffee' diff --git a/libcore/node_modules/browserify/test/coffee_bin/x.coffee b/libcore/node_modules/browserify/test/coffee_bin/x.coffee new file mode 100644 index 0000000..3bbf3ca --- /dev/null +++ b/libcore/node_modules/browserify/test/coffee_bin/x.coffee @@ -0,0 +1 @@ +console.log "from x!" diff --git a/libcore/node_modules/browserify/test/coffeeify.js b/libcore/node_modules/browserify/test/coffeeify.js new file mode 100644 index 0000000..176008c --- /dev/null +++ b/libcore/node_modules/browserify/test/coffeeify.js @@ -0,0 +1,19 @@ +var test = require('tap').test; +var browserify = require('../'); +var vm = require('vm'); + +test('coffeeify with an implicit global', function (t) { + t.plan(1); + + var b = browserify(__dirname + '/coffeeify/main.coffee'); + b.transform('coffeeify'); + b.bundle(function (err, src) { + if (err) t.fail(err); + vm.runInNewContext(src, { + console: { log: log }, + setTimeout: setTimeout, + clearTimeout: clearTimeout + }); + function log (msg) { t.equal(msg, 'eyo') } + }); +}); diff --git a/libcore/node_modules/browserify/test/coffeeify/main.coffee b/libcore/node_modules/browserify/test/coffeeify/main.coffee new file mode 100644 index 0000000..3e6a9e8 --- /dev/null +++ b/libcore/node_modules/browserify/test/coffeeify/main.coffee @@ -0,0 +1,2 @@ +process.nextTick -> + console.log 'eyo' diff --git a/libcore/node_modules/browserify/test/comment.js b/libcore/node_modules/browserify/test/comment.js new file mode 100644 index 0000000..f22278f --- /dev/null +++ b/libcore/node_modules/browserify/test/comment.js @@ -0,0 +1,16 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; + +test('trailing comment', function (t) { + t.plan(1); + var b = browserify(__dirname + '/comment/main.js'); + b.bundle(function (err, src) { + var c = { + ex : function (obj) { + t.same(obj, 1234); + } + }; + vm.runInNewContext(src, c); + }); +}); diff --git a/libcore/node_modules/browserify/test/comment/main.js b/libcore/node_modules/browserify/test/comment/main.js new file mode 100644 index 0000000..2eca526 --- /dev/null +++ b/libcore/node_modules/browserify/test/comment/main.js @@ -0,0 +1,2 @@ +ex(1234) +// test \ No newline at end of file diff --git a/libcore/node_modules/browserify/test/constants.js b/libcore/node_modules/browserify/test/constants.js new file mode 100644 index 0000000..0efbc6d --- /dev/null +++ b/libcore/node_modules/browserify/test/constants.js @@ -0,0 +1,18 @@ +var browserify = require('../'); +var test = require('tap').test; +var vm = require('vm'); +var through = require('through2'); + +test('constants', function (t) { + t.plan(2); + var stream = through(); + stream.push('console.log(require("constants").ENOENT)'); + stream.push(null); + var b = browserify(stream); + + b.bundle(function (err, src) { + t.ifError(err); + vm.runInNewContext(src, { console: { log: log } }); + function log (msg) { t.equal(msg, 2) } + }); +}); diff --git a/libcore/node_modules/browserify/test/crypto.js b/libcore/node_modules/browserify/test/crypto.js new file mode 100644 index 0000000..453ddb3 --- /dev/null +++ b/libcore/node_modules/browserify/test/crypto.js @@ -0,0 +1,43 @@ +var test = require('tap').test; +var spawn = require('child_process').spawn; +var path = require('path'); +var fs = require('fs'); +var vm = require('vm'); +var concat = require('concat-stream'); +var semver = require('semver'); + +var temp = require('temp'); +temp.track(); +var tmpdir = temp.mkdirSync({prefix: 'browserify-test'}); + +fs.writeFileSync(tmpdir + '/main.js', 'beep(require("crypto"))\n'); + +if (!ArrayBuffer.isView) ArrayBuffer.isView = function () { return false; }; + +// `crypto-browserify` no longer works in node.js <4 +test('*-browserify libs from node_modules/', { skip: semver.lt(process.version, 'v4.0.0') }, function (t) { + t.plan(2); + + var bin = __dirname + '/../bin/cmd.js'; + var ps = spawn(process.execPath, [ bin, 'main.js' ], { cwd : tmpdir }); + + ps.stderr.pipe(process.stderr, { end : false }); + + ps.on('exit', function (code) { + t.equal(code, 0); + }); + + ps.stdout.pipe(concat(function (src) { + var c = { + Int32Array: Int32Array, + ArrayBuffer: ArrayBuffer, + Uint8Array: Uint8Array, + DataView: DataView, + beep : function (c) { + t.equal(typeof c.createHash, 'function'); + }, + require: function () {} + }; + vm.runInNewContext(src.toString('utf8'), c); + })); +}); diff --git a/libcore/node_modules/browserify/test/crypto_ig.js b/libcore/node_modules/browserify/test/crypto_ig.js new file mode 100644 index 0000000..932ee9e --- /dev/null +++ b/libcore/node_modules/browserify/test/crypto_ig.js @@ -0,0 +1,43 @@ +var test = require('tap').test; +var spawn = require('child_process').spawn; +var path = require('path'); +var fs = require('fs'); +var vm = require('vm'); +var concat = require('concat-stream'); +var semver = require('semver'); + +var temp = require('temp'); +temp.track(); +var tmpdir = temp.mkdirSync({prefix: 'browserify-test'}); + +fs.writeFileSync(tmpdir + '/main.js', 'beep(require("crypto"))\n'); + +if (!ArrayBuffer.isView) ArrayBuffer.isView = function () { return false; }; + +// `crypto-browserify` no longer works in node.js <4 +test('crypto --insertGlobals', { skip: semver.lt(process.version, 'v4.0.0') }, function (t) { + t.plan(2); + + var bin = __dirname + '/../bin/cmd.js'; + var ps = spawn(process.execPath, [ bin, 'main.js', '--ig' ], { cwd : tmpdir }); + + ps.stderr.pipe(process.stderr, { end : false }); + + ps.on('exit', function (code) { + t.equal(code, 0); + }); + + ps.stdout.pipe(concat(function (src) { + var c = { + Int32Array: Int32Array, + ArrayBuffer: ArrayBuffer, + Uint8Array: Uint8Array, + DataView: DataView, + beep : function (c) { + t.equal(typeof c.createHash, 'function'); + }, + require: function () {} + }; + vm.runInNewContext(src.toString('utf8'), c); + })); +}); diff --git a/libcore/node_modules/browserify/test/cycle.js b/libcore/node_modules/browserify/test/cycle.js new file mode 100644 index 0000000..6cfd3c2 --- /dev/null +++ b/libcore/node_modules/browserify/test/cycle.js @@ -0,0 +1,13 @@ +var test = require('tap').test; +var browserify = require('../'); +var vm = require('vm'); + +test('cycle', function (t) { + t.plan(2); + var b = browserify(__dirname + '/cycle/entry.js'); + b.bundle(function (err, body) { + t.ifError(err); + vm.runInNewContext(body); + t.ok(true); + }); +}); diff --git a/libcore/node_modules/browserify/test/cycle/README.md b/libcore/node_modules/browserify/test/cycle/README.md new file mode 100644 index 0000000..d41c397 --- /dev/null +++ b/libcore/node_modules/browserify/test/cycle/README.md @@ -0,0 +1,16 @@ +browserify-bug-713 +================== + +substack/node-browserify#713 breaks resolving an identical module multiple time from different locations when the module has a circular require. + +## Reproduce + +Module requires two copies of the same module (identical apart from path) and the sub module has a circular require. + +## Example + +This is the case with [readable-stream](https://github.com/isaacs/readable-stream). If two different modules depend on the same version readable-stream (and no npm dedupe), then both of those modules are required in the same project, browserify throws a `RangeError: Maximum call stack size exceeded` + +See https://github.com/isaacs/readable-stream/blob/master/lib/_stream_writable.js#L134 and https://github.com/isaacs/readable-stream/blob/master/lib/_stream_duplex.js#L44 + +This issue is most likely related: substack/node-browserify#735 diff --git a/libcore/node_modules/browserify/test/cycle/entry.js b/libcore/node_modules/browserify/test/cycle/entry.js new file mode 100644 index 0000000..6a8dd8e --- /dev/null +++ b/libcore/node_modules/browserify/test/cycle/entry.js @@ -0,0 +1,15 @@ +// RE: substack/node-browserify#713 + +// https://github.com/substack/node-browserify/pull/713 breaks resolving +// an identical module multiple time from different locations when the +// module has a circular require. + +// other than path, mod1 and mod2 are identical + +require('./mod1/a') +require('./mod2/a') + +// browserify entry.js + +// works in 3.37.2 +// >= 3.38 throws RangeError: Maximum call stack size exceeded \ No newline at end of file diff --git a/libcore/node_modules/browserify/test/cycle/mod1/a.js b/libcore/node_modules/browserify/test/cycle/mod1/a.js new file mode 100644 index 0000000..c40d2fe --- /dev/null +++ b/libcore/node_modules/browserify/test/cycle/mod1/a.js @@ -0,0 +1 @@ +require('./b') \ No newline at end of file diff --git a/libcore/node_modules/browserify/test/cycle/mod1/b.js b/libcore/node_modules/browserify/test/cycle/mod1/b.js new file mode 100644 index 0000000..54c7b9c --- /dev/null +++ b/libcore/node_modules/browserify/test/cycle/mod1/b.js @@ -0,0 +1 @@ +require('./a') \ No newline at end of file diff --git a/libcore/node_modules/browserify/test/cycle/mod2/a.js b/libcore/node_modules/browserify/test/cycle/mod2/a.js new file mode 100644 index 0000000..c40d2fe --- /dev/null +++ b/libcore/node_modules/browserify/test/cycle/mod2/a.js @@ -0,0 +1 @@ +require('./b') \ No newline at end of file diff --git a/libcore/node_modules/browserify/test/cycle/mod2/b.js b/libcore/node_modules/browserify/test/cycle/mod2/b.js new file mode 100644 index 0000000..54c7b9c --- /dev/null +++ b/libcore/node_modules/browserify/test/cycle/mod2/b.js @@ -0,0 +1 @@ +require('./a') \ No newline at end of file diff --git a/libcore/node_modules/browserify/test/debug_standalone.js b/libcore/node_modules/browserify/test/debug_standalone.js new file mode 100644 index 0000000..207090c --- /dev/null +++ b/libcore/node_modules/browserify/test/debug_standalone.js @@ -0,0 +1,64 @@ +var test = require('tap').test; +var browserify = require('../'); +var through = require('through2'); +var vm = require('vm'); + +test('ordinary debug', function (t) { + t.plan(1); + + var stream = through(); + stream.push('console.log(1+2)'); + stream.push(null); + + var b = browserify({ debug: true }); + b.add(stream); + b.bundle(function (err, buf) { + var src = buf.toString('utf8'); + var last = src.split('\n').slice(-2)[0]; + t.ok( + /\/\/# sourceMappingURL=data:application\/json;charset=utf-8;base64,[\w+\/=]+$/ + .test(last) + ); + }); +}); + +test('debug standalone', function (t) { + t.plan(1); + + var stream = through(); + stream.push('console.log(1+2)'); + stream.push(null); + + var b = browserify({ debug: true, standalone: 'xyz' }); + b.add(stream); + b.bundle(function (err, buf) { + var src = buf.toString('utf8'); + var last = src.split('\n').slice(-2)[0]; + t.ok( + /\/\/# sourceMappingURL=data:application\/json;charset=utf-8;base64,[\w+\/=]+$/ + .test(last) + ); + }); +}); + +test('debug standalone exposed', function (t) { + t.plan(2); + + var stream = through(); + stream.push('console.log(1+2)'); + stream.push(null); + + var b = browserify({ debug: true, standalone: 'xyz' }); + b.require(__dirname + '/debug_standalone/x.js', { expose: 'xxx' }); + b.bundle(function (err, buf) { + var src = buf.toString('utf8'); + var last = src.split('\n').slice(-2)[0]; + t.ok( + /\/\/# sourceMappingURL=data:application\/json;charset=utf-8;base64,[\w+\/=]+$/ + .test(last) + ); + var c = { window: {} }; + vm.runInNewContext(src, c); + t.equal(c.window.xyz, 555); + }); +}); diff --git a/libcore/node_modules/browserify/test/debug_standalone/x.js b/libcore/node_modules/browserify/test/debug_standalone/x.js new file mode 100644 index 0000000..3e842e7 --- /dev/null +++ b/libcore/node_modules/browserify/test/debug_standalone/x.js @@ -0,0 +1 @@ +module.exports = 555 diff --git a/libcore/node_modules/browserify/test/dedupe-deps.js b/libcore/node_modules/browserify/test/dedupe-deps.js new file mode 100644 index 0000000..ebb6ded --- /dev/null +++ b/libcore/node_modules/browserify/test/dedupe-deps.js @@ -0,0 +1,59 @@ +var browserify = require('../'); +var test = require('tap').test; + +test('identical content gets deduped and the row gets an implicit dep on the original source', function (t) { + t.plan(1) + + var rows = []; + browserify() + .on('dep', [].push.bind(rows)) + .require(require.resolve('./dup'), { entry: true }) + .bundle(check); + + function check(err, src) { + if (err) return t.fail(err); + var deduped = rows.filter(function (x) { return x.dedupeIndex }); + var d = deduped[0]; + + t.deepEqual(d.deps, { 'dup': d.dedupeIndex }, "adds implicit dep"); + } +}) + +test('identical content gets deduped with fullPaths', function (t) { + t.plan(1) + + var rows = []; + browserify({fullPaths: true}) + .on('dep', [].push.bind(rows)) + .require(require.resolve('./dup'), { entry: true }) + .bundle(check); + + function check(err, src) { + if (err) return t.fail(err); + var deduped = rows.filter(function (x) { return x.dedupe }); + var d = deduped[0]; + + t.deepEqual( + d.source, + 'arguments[4]['+ JSON.stringify(d.dedupe) + '][0]' + + '.apply(exports,arguments)', + "dedupes content" + ); + } +}) + +test('identical content does not get deduped with dedupe option false', function (t) { + t.plan(1) + + var rows = []; + browserify({fullPaths: true, dedupe: false}) + .on('dep', [].push.bind(rows)) + .require(require.resolve('./dup'), { entry: true }) + .bundle(check); + + function check(err, src) { + if (err) return t.fail(err); + var deduped = rows.filter(function (x) { return x.dedupe }); + t.equal(deduped.length, 0, 'does not dedupe'); + } +}) diff --git a/libcore/node_modules/browserify/test/dedupe-nomap.js b/libcore/node_modules/browserify/test/dedupe-nomap.js new file mode 100644 index 0000000..906fadc --- /dev/null +++ b/libcore/node_modules/browserify/test/dedupe-nomap.js @@ -0,0 +1,64 @@ +var browserify = require('../'); +var test = require('tap').test; + +test('identical content gets deduped and the row gets a "nomap" flag set when sourcemaps are turned on', function (t) { + t.plan(4) + + var rows = []; + browserify({ debug: true }) + .on('dep', [].push.bind(rows)) + .require(require.resolve('./dup'), { entry: true }) + .bundle(check); + + function check(err, src) { + if (err) return t.fail(err); + var nomappeds = rows.filter(function (x) { return x.nomap }); + var nm = nomappeds[0]; + + t.equal(rows.length, 3, 'packs 3 rows'); + t.equal(nomappeds.length, 1, 'one of has nomapped flag set'); + t.equal( + rows.filter(function (x) { + return x.id == nm.dedupeIndex + }).length, + 1, + '2 rows with the same hash as the duplicate exist' + ); + t.similar( + nm.source, + /arguments\[4\]\[.+\]\[0\]\.apply\(exports,arguments\)$/, + 'redirects duplicate to original via require call' + ); + } +}) + +test('identical content gets deduped and the row gets a "nomap" flag set when sourcemaps are turned off', function (t) { + t.plan(4) + + var rows = []; + browserify({ debug: false }) + .on('dep', [].push.bind(rows)) + .require(require.resolve('./dup'), { entry: true }) + .bundle(check); + + function check(err, src) { + if (err) return t.fail(err); + var nomappeds = rows.filter(function (x) { return x.nomap }); + var nm = nomappeds[0]; + + t.equal(rows.length, 3, 'packs 3 rows'); + t.equal(nomappeds.length, 1, 'one of has nomapped flag set'); + t.equal( + rows.filter(function (x) { + return x.id == nm.dedupeIndex + }).length, + 1, + '2 rows with the same hash as the duplicate exist' + ); + t.similar( + nm.source, + /arguments\[4\]\[.+\]\[0\]\.apply\(exports,arguments\)$/, + 'redirects duplicate to original via require call' + ); + } +}) diff --git a/libcore/node_modules/browserify/test/delay.js b/libcore/node_modules/browserify/test/delay.js new file mode 100644 index 0000000..63c1d87 --- /dev/null +++ b/libcore/node_modules/browserify/test/delay.js @@ -0,0 +1,25 @@ +var browserify = require('../'); +var vm = require('vm'); +var path = require('path'); +var test = require('tap').test; +var through = require('through2'); + +test('delay for pipelines', function (t) { + t.plan(3); + + var b = browserify(__dirname + '/delay/main.js'); + b.pipeline.get('record').push(through.obj(function (row, enc, next) { + if (row.file) { + t.equal(row.file, path.join(__dirname, 'delay/main.js')); + row.file = path.join(__dirname, 'delay/diverted.js'); + } + this.push(row); + next(); + })); + + b.bundle(function (err, src) { + t.ifError(err); + vm.runInNewContext(src, { console: { log: log } }); + function log (msg) { t.equal(msg, 900) } + }); +}); diff --git a/libcore/node_modules/browserify/test/delay/diverted.js b/libcore/node_modules/browserify/test/delay/diverted.js new file mode 100644 index 0000000..3037cd9 --- /dev/null +++ b/libcore/node_modules/browserify/test/delay/diverted.js @@ -0,0 +1 @@ +console.log(900) diff --git a/libcore/node_modules/browserify/test/delay/main.js b/libcore/node_modules/browserify/test/delay/main.js new file mode 100644 index 0000000..67eaa25 --- /dev/null +++ b/libcore/node_modules/browserify/test/delay/main.js @@ -0,0 +1 @@ +console.log(500) diff --git a/libcore/node_modules/browserify/test/dep.js b/libcore/node_modules/browserify/test/dep.js new file mode 100644 index 0000000..13ee026 --- /dev/null +++ b/libcore/node_modules/browserify/test/dep.js @@ -0,0 +1,25 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; + +test('dependency events', function (t) { + t.plan(4); + var b = browserify(__dirname + '/entry/main.js'); + var deps = []; + b.on('dep', function (row) { + deps.push({ id: row.id, deps: row.deps }); + t.equal(typeof row.source, 'string'); + }); + + b.bundle(function (err, src) { + t.deepEqual(deps.sort(cmp), [ + { id: 1, deps: { './one': 2, './two': 3 } }, + { id: 2, deps: {} }, + { id: 3, deps: {} } + ]); + }); + + function cmp (a, b) { + return a.id < b.id ? -1 : 1; + } +}); diff --git a/libcore/node_modules/browserify/test/dollar.js b/libcore/node_modules/browserify/test/dollar.js new file mode 100644 index 0000000..872cee5 --- /dev/null +++ b/libcore/node_modules/browserify/test/dollar.js @@ -0,0 +1,17 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; + +test('dollar', function (t) { + t.plan(2); + var b = browserify(); + b.require(__dirname + '/dollar/dollar/index.js', { expose: 'dollar' }); + b.bundle(function (err, src) { + t.ok(src.length > 0); + + var c = {}; + vm.runInNewContext(src, c); + var res = vm.runInNewContext('require("dollar")(100)', c); + t.equal(res, 10000); + }); +}); diff --git a/libcore/node_modules/browserify/test/dollar/dollar/index.js b/libcore/node_modules/browserify/test/dollar/dollar/index.js new file mode 100644 index 0000000..a6012aa --- /dev/null +++ b/libcore/node_modules/browserify/test/dollar/dollar/index.js @@ -0,0 +1,7 @@ +// foo $ bar $ baz + +var $ = function (x) { + return x * 100; +}; + +module.exports = $; diff --git a/libcore/node_modules/browserify/test/double_buffer.js b/libcore/node_modules/browserify/test/double_buffer.js new file mode 100644 index 0000000..dfda808 --- /dev/null +++ b/libcore/node_modules/browserify/test/double_buffer.js @@ -0,0 +1,16 @@ +var browserify = require('../'); +var test = require('tap').test; +var vm = require('vm'); + +if (!ArrayBuffer.isView) ArrayBuffer.isView = function () { return false; }; + +test('double buffer', function (t) { + t.plan(1); + + var b = browserify(__dirname + '/double_buffer/main.js'); + b.require('buffer'); + b.bundle(function (err, src) { + if (err) return t.fail(err); + vm.runInNewContext(src, { t: t, Uint8Array: Uint8Array }); + }); +}); diff --git a/libcore/node_modules/browserify/test/double_buffer/explicit.js b/libcore/node_modules/browserify/test/double_buffer/explicit.js new file mode 100644 index 0000000..fa76b1f --- /dev/null +++ b/libcore/node_modules/browserify/test/double_buffer/explicit.js @@ -0,0 +1 @@ +module.exports = require('buffer').Buffer diff --git a/libcore/node_modules/browserify/test/double_buffer/implicit.js b/libcore/node_modules/browserify/test/double_buffer/implicit.js new file mode 100644 index 0000000..70c9e75 --- /dev/null +++ b/libcore/node_modules/browserify/test/double_buffer/implicit.js @@ -0,0 +1 @@ +module.exports = Buffer diff --git a/libcore/node_modules/browserify/test/double_buffer/main.js b/libcore/node_modules/browserify/test/double_buffer/main.js new file mode 100644 index 0000000..bf124fd --- /dev/null +++ b/libcore/node_modules/browserify/test/double_buffer/main.js @@ -0,0 +1,4 @@ +var implicit = require('./implicit.js'); +var explicit = require('./explicit.js'); + +t.equal(implicit, explicit); diff --git a/libcore/node_modules/browserify/test/double_bundle.js b/libcore/node_modules/browserify/test/double_bundle.js new file mode 100644 index 0000000..d5b9a1b --- /dev/null +++ b/libcore/node_modules/browserify/test/double_bundle.js @@ -0,0 +1,24 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; + +test('double bundle', function (t) { + t.plan(5); + + var b = browserify(__dirname + '/entry/main.js'); + b.bundle(function (err, src0) { + t.ifError(err); + var c = { + done : function (one, two) { + t.equal(one, 1); + t.equal(two, 2); + } + }; + vm.runInNewContext(src0, c); + + b.bundle(function (err, src1) { + t.ifError(err); + t.equal(src1.toString('utf8'), src0.toString('utf8')); + }); + }); +}); diff --git a/libcore/node_modules/browserify/test/double_bundle_error.js b/libcore/node_modules/browserify/test/double_bundle_error.js new file mode 100644 index 0000000..02ff015 --- /dev/null +++ b/libcore/node_modules/browserify/test/double_bundle_error.js @@ -0,0 +1,17 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; + +test('double bundle error', function (t) { + t.plan(2); + + var b = browserify(__dirname + '/double_bundle_error/main.js'); + var x = b.bundle(); + x.on('error', function (err) { + t.ok(err); + var y = b.bundle(); + y.on('error', function (err) { + t.ok(err); + }); + }); +}); diff --git a/libcore/node_modules/browserify/test/double_bundle_error/main.js b/libcore/node_modules/browserify/test/double_bundle_error/main.js new file mode 100644 index 0000000..89bb8a0 --- /dev/null +++ b/libcore/node_modules/browserify/test/double_bundle_error/main.js @@ -0,0 +1 @@ +done(require('./one'), require('./two')); \ No newline at end of file diff --git a/libcore/node_modules/browserify/test/double_bundle_error/needs_three.js b/libcore/node_modules/browserify/test/double_bundle_error/needs_three.js new file mode 100644 index 0000000..9def415 --- /dev/null +++ b/libcore/node_modules/browserify/test/double_bundle_error/needs_three.js @@ -0,0 +1 @@ +require("three"); diff --git a/libcore/node_modules/browserify/test/double_bundle_error/one.js b/libcore/node_modules/browserify/test/double_bundle_error/one.js new file mode 100644 index 0000000..bd816ea --- /dev/null +++ b/libcore/node_modules/browserify/test/double_bundle_error/one.js @@ -0,0 +1 @@ +module.exports = 1; diff --git a/libcore/node_modules/browserify/test/double_bundle_error/package.json b/libcore/node_modules/browserify/test/double_bundle_error/package.json new file mode 100644 index 0000000..ad2f403 --- /dev/null +++ b/libcore/node_modules/browserify/test/double_bundle_error/package.json @@ -0,0 +1,5 @@ +{ + "browser": { + "three": "./three.js" + } +} diff --git a/libcore/node_modules/browserify/test/double_bundle_error/three.js b/libcore/node_modules/browserify/test/double_bundle_error/three.js new file mode 100644 index 0000000..b15da27 --- /dev/null +++ b/libcore/node_modules/browserify/test/double_bundle_error/three.js @@ -0,0 +1,3 @@ +require('./nosuchfile.js'); + +module.exports = 3; diff --git a/libcore/node_modules/browserify/test/double_bundle_error/two.js b/libcore/node_modules/browserify/test/double_bundle_error/two.js new file mode 100644 index 0000000..72461a5 --- /dev/null +++ b/libcore/node_modules/browserify/test/double_bundle_error/two.js @@ -0,0 +1 @@ +module.exports = require('./three.js') - 1; diff --git a/libcore/node_modules/browserify/test/double_bundle_json.js b/libcore/node_modules/browserify/test/double_bundle_json.js new file mode 100644 index 0000000..ac72709 --- /dev/null +++ b/libcore/node_modules/browserify/test/double_bundle_json.js @@ -0,0 +1,37 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; +var through = require('through2'); +var xtend = require('xtend'); + +test('double bundle json', function (t) { + t.plan(6); + var expected0 = [ 'a=500', 'b=500' ]; + var expected1 = [ 'a=500', 'b=500' ]; + + function log0 (msg) { t.equal(msg, expected0.shift()) } + function log1 (msg) { t.equal(msg, expected1.shift()) } + + var cache = {}; + var b = browserify(__dirname + '/double_bundle_json/index.js', { + cache: cache + }); + b.pipeline.get('deps').push(through.obj(function(row, enc, next) { + cache[row.file] = { + source: row.source, + deps: xtend(row.deps) + }; + this.push(row); + next(); + })); + b.bundle(function (err, src0) { + t.ifError(err); + vm.runInNewContext(src0, { console: { log: log0 } }); + delete cache[__dirname + '/double_bundle_json/index.js']; + + b.bundle(function (err, src1) { + t.ifError(err); + vm.runInNewContext(src1, { console: { log: log1 } }); + }); + }); +}); diff --git a/libcore/node_modules/browserify/test/double_bundle_json/a.json b/libcore/node_modules/browserify/test/double_bundle_json/a.json new file mode 100644 index 0000000..bf0cf63 --- /dev/null +++ b/libcore/node_modules/browserify/test/double_bundle_json/a.json @@ -0,0 +1 @@ +{"x":500} diff --git a/libcore/node_modules/browserify/test/double_bundle_json/b.json b/libcore/node_modules/browserify/test/double_bundle_json/b.json new file mode 100644 index 0000000..bf0cf63 --- /dev/null +++ b/libcore/node_modules/browserify/test/double_bundle_json/b.json @@ -0,0 +1 @@ +{"x":500} diff --git a/libcore/node_modules/browserify/test/double_bundle_json/index.js b/libcore/node_modules/browserify/test/double_bundle_json/index.js new file mode 100644 index 0000000..fd8f682 --- /dev/null +++ b/libcore/node_modules/browserify/test/double_bundle_json/index.js @@ -0,0 +1,5 @@ +var a = require('./a.json'); +var b = require('./b.json'); + +console.log('a=' + a.x); +console.log('b=' + b.x); diff --git a/libcore/node_modules/browserify/test/double_bundle_parallel.js b/libcore/node_modules/browserify/test/double_bundle_parallel.js new file mode 100644 index 0000000..ffeed20 --- /dev/null +++ b/libcore/node_modules/browserify/test/double_bundle_parallel.js @@ -0,0 +1,33 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; + +test('double bundle parallel', function (t) { + t.plan(7); + + var sources = []; + var b = browserify(__dirname + '/entry/main.js'); + + var pending = 2; + b.bundle(check(0)); + b.bundle(check(1)); + + function check (index) { + return function (err, src) { + t.ifError(err); + var c = { + done : function (one, two) { + t.equal(one, 1); + t.equal(two, 2); + } + }; + vm.runInNewContext(src, c); + sources[index] = src.toString('utf8'); + if (--pending === 0) done(); + }; + } + + function done () { + t.equal(sources[0], sources[1]); + } +}); diff --git a/libcore/node_modules/browserify/test/double_bundle_parallel_cache.js b/libcore/node_modules/browserify/test/double_bundle_parallel_cache.js new file mode 100644 index 0000000..521eda4 --- /dev/null +++ b/libcore/node_modules/browserify/test/double_bundle_parallel_cache.js @@ -0,0 +1,35 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; + +test('double bundle parallel cached', function (t) { + t.plan(7); + + var sources = []; + var b = browserify(__dirname + '/entry/main.js', { + cache: {} + }); + + var pending = 2; + b.bundle(check(0)); + b.bundle(check(1)); + + function check (index) { + return function (err, src) { + t.ifError(err); + var c = { + done : function (one, two) { + t.equal(one, 1); + t.equal(two, 2); + } + }; + vm.runInNewContext(src, c); + sources[index] = src.toString('utf8'); + if (--pending === 0) done(); + }; + } + + function done () { + t.equal(sources[0], sources[1]); + } +}); diff --git a/libcore/node_modules/browserify/test/dup/foo-dup.js b/libcore/node_modules/browserify/test/dup/foo-dup.js new file mode 100644 index 0000000..8fadf88 --- /dev/null +++ b/libcore/node_modules/browserify/test/dup/foo-dup.js @@ -0,0 +1,4 @@ +// something on first line +module.exports = function () { + console.log('I like to duplicate myself'); +}; diff --git a/libcore/node_modules/browserify/test/dup/foo.js b/libcore/node_modules/browserify/test/dup/foo.js new file mode 100644 index 0000000..8fadf88 --- /dev/null +++ b/libcore/node_modules/browserify/test/dup/foo.js @@ -0,0 +1,4 @@ +// something on first line +module.exports = function () { + console.log('I like to duplicate myself'); +}; diff --git a/libcore/node_modules/browserify/test/dup/index.js b/libcore/node_modules/browserify/test/dup/index.js new file mode 100644 index 0000000..ea44288 --- /dev/null +++ b/libcore/node_modules/browserify/test/dup/index.js @@ -0,0 +1,5 @@ +var foo = require('./foo'); +var foodup = require('./foo-dup'); + +foo(); +foodup(); diff --git a/libcore/node_modules/browserify/test/entry.js b/libcore/node_modules/browserify/test/entry.js new file mode 100644 index 0000000..23a2ee2 --- /dev/null +++ b/libcore/node_modules/browserify/test/entry.js @@ -0,0 +1,43 @@ +var browserify = require('../'); +var vm = require('vm'); +var path = require('path'); +var test = require('tap').test; + +test('entry', function (t) { + t.plan(3); + + var b = browserify(__dirname + '/entry/main.js'); + b.on('dep', function(row) { + if (row.entry) t.equal(row.file, path.join(__dirname, 'entry/main.js')); + }); + b.bundle(function (err, src) { + var c = { + done : function (one, two) { + t.equal(one, 1); + t.equal(two, 2); + t.end(); + } + }; + vm.runInNewContext(src, c); + }); +}); + +test('entry via add', function (t) { + t.plan(3); + + var b = browserify(); + b.add(__dirname + '/entry/main.js'); + b.on('dep', function(row) { + if (row.entry) t.equal(row.file, path.join(__dirname, 'entry/main.js')); + }); + b.bundle(function (err, src) { + var c = { + done : function (one, two) { + t.equal(one, 1); + t.equal(two, 2); + t.end(); + } + }; + vm.runInNewContext(src, c); + }); +}); diff --git a/libcore/node_modules/browserify/test/entry/main.js b/libcore/node_modules/browserify/test/entry/main.js new file mode 100644 index 0000000..89bb8a0 --- /dev/null +++ b/libcore/node_modules/browserify/test/entry/main.js @@ -0,0 +1 @@ +done(require('./one'), require('./two')); \ No newline at end of file diff --git a/libcore/node_modules/browserify/test/entry/needs_three.js b/libcore/node_modules/browserify/test/entry/needs_three.js new file mode 100644 index 0000000..9def415 --- /dev/null +++ b/libcore/node_modules/browserify/test/entry/needs_three.js @@ -0,0 +1 @@ +require("three"); diff --git a/libcore/node_modules/browserify/test/entry/one.js b/libcore/node_modules/browserify/test/entry/one.js new file mode 100644 index 0000000..bd816ea --- /dev/null +++ b/libcore/node_modules/browserify/test/entry/one.js @@ -0,0 +1 @@ +module.exports = 1; diff --git a/libcore/node_modules/browserify/test/entry/package.json b/libcore/node_modules/browserify/test/entry/package.json new file mode 100644 index 0000000..ad2f403 --- /dev/null +++ b/libcore/node_modules/browserify/test/entry/package.json @@ -0,0 +1,5 @@ +{ + "browser": { + "three": "./three.js" + } +} diff --git a/libcore/node_modules/browserify/test/entry/three.js b/libcore/node_modules/browserify/test/entry/three.js new file mode 100644 index 0000000..690aad3 --- /dev/null +++ b/libcore/node_modules/browserify/test/entry/three.js @@ -0,0 +1 @@ +module.exports = 3; diff --git a/libcore/node_modules/browserify/test/entry/two.js b/libcore/node_modules/browserify/test/entry/two.js new file mode 100644 index 0000000..4bbffde --- /dev/null +++ b/libcore/node_modules/browserify/test/entry/two.js @@ -0,0 +1 @@ +module.exports = 2; diff --git a/libcore/node_modules/browserify/test/entry_exec.js b/libcore/node_modules/browserify/test/entry_exec.js new file mode 100644 index 0000000..c70281e --- /dev/null +++ b/libcore/node_modules/browserify/test/entry_exec.js @@ -0,0 +1,15 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; + +test('only execute entry files', function (t) { + t.plan(1); + + var b = browserify(); + b.add(__dirname + '/entry_exec/main.js'); + b.require(__dirname + '/entry_exec/fail.js'); + b.bundle(function (err, src) { + var c = { t: t }; + vm.runInNewContext(src, c); + }); +}); diff --git a/libcore/node_modules/browserify/test/entry_exec/fail.js b/libcore/node_modules/browserify/test/entry_exec/fail.js new file mode 100644 index 0000000..8da5557 --- /dev/null +++ b/libcore/node_modules/browserify/test/entry_exec/fail.js @@ -0,0 +1 @@ +t.fail('only entry files should get executed right away'); diff --git a/libcore/node_modules/browserify/test/entry_exec/main.js b/libcore/node_modules/browserify/test/entry_exec/main.js new file mode 100644 index 0000000..98331f4 --- /dev/null +++ b/libcore/node_modules/browserify/test/entry_exec/main.js @@ -0,0 +1 @@ +t.ok(true); diff --git a/libcore/node_modules/browserify/test/entry_expose.js b/libcore/node_modules/browserify/test/entry_expose.js new file mode 100644 index 0000000..381bdc5 --- /dev/null +++ b/libcore/node_modules/browserify/test/entry_expose.js @@ -0,0 +1,18 @@ +var test = require('tap').test; +var browserify = require('../'); +var vm = require('vm'); + +test('entry expose', function (t) { + t.plan(3) + + var b = browserify(); + b.add(__dirname + '/entry_expose/main.js'); + b.require(__dirname + '/entry_expose/main.js', { expose: 'x' }); + b.bundle(function (err, src) { + t.ifError(err); + var c = { console: { log: log } }; + function log (msg) { t.equal(msg, 'wow') } + vm.runInNewContext(src, c); + t.equal(c.require('x'), 555); + }) +}); diff --git a/libcore/node_modules/browserify/test/entry_expose/main.js b/libcore/node_modules/browserify/test/entry_expose/main.js new file mode 100644 index 0000000..bf2b2d6 --- /dev/null +++ b/libcore/node_modules/browserify/test/entry_expose/main.js @@ -0,0 +1,2 @@ +console.log('wow'); +module.exports = 555; diff --git a/libcore/node_modules/browserify/test/entry_relative.js b/libcore/node_modules/browserify/test/entry_relative.js new file mode 100644 index 0000000..178a8ac --- /dev/null +++ b/libcore/node_modules/browserify/test/entry_relative.js @@ -0,0 +1,45 @@ +var browserify = require('../'); +var vm = require('vm'); +var path = require('path'); +var test = require('tap').test; + +test('entry - relative path', function (t) { + process.chdir(__dirname); + + t.plan(3); + + var b = browserify('entry/main.js'); + b.on('dep', function(row) { + if (row.entry) t.equal(row.file, path.join(__dirname, 'entry/main.js')); + }); + b.bundle(function (err, src) { + var c = { + done : function (one, two) { + t.equal(one, 1); + t.equal(two, 2); + t.end(); + } + }; + vm.runInNewContext(src, c); + }); +}); + +test('entry - relative path via add', function (t) { + t.plan(3); + + var b = browserify({basedir: __dirname}); + b.add('entry/main.js'); + b.on('dep', function(row) { + if (row.entry) t.equal(row.file, path.join(__dirname, 'entry/main.js')); + }); + b.bundle(function (err, src) { + var c = { + done : function (one, two) { + t.equal(one, 1); + t.equal(two, 2); + t.end(); + } + }; + vm.runInNewContext(src, c); + }); +}); diff --git a/libcore/node_modules/browserify/test/error_code.js b/libcore/node_modules/browserify/test/error_code.js new file mode 100644 index 0000000..5d0b2b1 --- /dev/null +++ b/libcore/node_modules/browserify/test/error_code.js @@ -0,0 +1,28 @@ +var test = require('tap').test; +var spawn = require('child_process').spawn; +var path = require('path'); +var semver = require('semver'); + +// TODO this should be fixable I guess +var knownFailure = process.platform === 'win32' && semver.satisfies(process.version, 'v0.10.x'); + +test('error code', { skip: knownFailure }, function (t) { + t.plan(2); + + var cwd = process.cwd(); + process.chdir(__dirname); + + var ps = spawn(process.execPath, [ + path.resolve(__dirname, '../bin/cmd.js'), + path.resolve(__dirname, 'error_code/src.js') + ]); + var err = ''; + ps.stderr.on('data', function (buf) { err += buf }); + ps.stderr.on('end', function () { + t.ok(/^(Syntax|Parse)Error:/m.test(err)); + }); + + ps.on('exit', function (code) { + t.notEqual(code, 0); + }); +}); diff --git a/libcore/node_modules/browserify/test/error_code/src.js b/libcore/node_modules/browserify/test/error_code/src.js new file mode 100644 index 0000000..e85c07c --- /dev/null +++ b/libcore/node_modules/browserify/test/error_code/src.js @@ -0,0 +1,2 @@ +var x = { +var y = 6; diff --git a/libcore/node_modules/browserify/test/exclude.js b/libcore/node_modules/browserify/test/exclude.js new file mode 100644 index 0000000..3829677 --- /dev/null +++ b/libcore/node_modules/browserify/test/exclude.js @@ -0,0 +1,21 @@ +var browserify = require('../'); +var test = require('tap').test; +var vm = require('vm'); + +test('exclude array', function(t) { + t.plan(2); + + var b = browserify(); + b.add(__dirname + '/exclude/array.js'); + b.exclude([ + __dirname + '/exclude/skip.js', + __dirname + '/exclude/skip2.js' + ]); + + b.bundle(function (err, src) { + if (err) { + t.fail(err); + } + vm.runInNewContext(src, { t: t }); + }); +}); diff --git a/libcore/node_modules/browserify/test/exclude/array.js b/libcore/node_modules/browserify/test/exclude/array.js new file mode 100644 index 0000000..de417c4 --- /dev/null +++ b/libcore/node_modules/browserify/test/exclude/array.js @@ -0,0 +1,2 @@ +t.throws(function () { require('./skip.js') }); +t.throws(function () { require('./skip2.js') }); diff --git a/libcore/node_modules/browserify/test/exclude/skip.js b/libcore/node_modules/browserify/test/exclude/skip.js new file mode 100644 index 0000000..006521e --- /dev/null +++ b/libcore/node_modules/browserify/test/exclude/skip.js @@ -0,0 +1 @@ +t.fail('this file should have been skipped'); diff --git a/libcore/node_modules/browserify/test/exclude/skip2.js b/libcore/node_modules/browserify/test/exclude/skip2.js new file mode 100644 index 0000000..006521e --- /dev/null +++ b/libcore/node_modules/browserify/test/exclude/skip2.js @@ -0,0 +1 @@ +t.fail('this file should have been skipped'); diff --git a/libcore/node_modules/browserify/test/export.js b/libcore/node_modules/browserify/test/export.js new file mode 100644 index 0000000..def4dfd --- /dev/null +++ b/libcore/node_modules/browserify/test/export.js @@ -0,0 +1,35 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; + +test('no exports when no files are loaded', function (t) { + t.plan(1); + var b = browserify(); + b.bundle(function (err, src) { + var c = {}; + vm.runInNewContext(src, c); + t.same(Object.keys(c), []); + }); +}); + +test('no exports when entries are defined', function (t) { + t.plan(1); + var b = browserify(); + b.add(__dirname + '/export/entry.js'); + b.bundle(function (err, src) { + var c = {}; + vm.runInNewContext(src, c); + t.same(c, {}); + }); +}); + +test('require export when files are required', function (t) { + t.plan(1); + var b = browserify(); + b.require(__dirname + '/export/entry.js'); + b.bundle(function (err, src) { + var c = {}; + vm.runInNewContext(src, c); + t.same(Object.keys(c), [ 'require' ]); + }); +}); diff --git a/libcore/node_modules/browserify/test/export/entry.js b/libcore/node_modules/browserify/test/export/entry.js new file mode 100644 index 0000000..6f037f8 --- /dev/null +++ b/libcore/node_modules/browserify/test/export/entry.js @@ -0,0 +1 @@ +// nop diff --git a/libcore/node_modules/browserify/test/external.js b/libcore/node_modules/browserify/test/external.js new file mode 100644 index 0000000..a107a4c --- /dev/null +++ b/libcore/node_modules/browserify/test/external.js @@ -0,0 +1,20 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; + +test('external', function (t) { + t.plan(2); + + var b = browserify(__dirname + '/external/main.js'); + b.external('freelist'); + b.bundle(function (err, src) { + if (err) return t.fail(err); + vm.runInNewContext( + 'function require (x) {' + + 'if (x==="freelist") return function (n) { return n + 1000 }' + + '}' + + src, + { t: t } + ); + }); +}); diff --git a/libcore/node_modules/browserify/test/external/main.js b/libcore/node_modules/browserify/test/external/main.js new file mode 100644 index 0000000..82ceeda --- /dev/null +++ b/libcore/node_modules/browserify/test/external/main.js @@ -0,0 +1,2 @@ +t.equal(require('freelist')(5), 1005); +t.equal(require('./x.js')(6), 1016); diff --git a/libcore/node_modules/browserify/test/external/x.js b/libcore/node_modules/browserify/test/external/x.js new file mode 100644 index 0000000..a587ef4 --- /dev/null +++ b/libcore/node_modules/browserify/test/external/x.js @@ -0,0 +1,3 @@ +var fl = require('freelist'); + +module.exports = function (n) { return fl(n) + 10 }; diff --git a/libcore/node_modules/browserify/test/external_args/main.js b/libcore/node_modules/browserify/test/external_args/main.js new file mode 100644 index 0000000..b19e6c1 --- /dev/null +++ b/libcore/node_modules/browserify/test/external_args/main.js @@ -0,0 +1,10 @@ +try { + var Backbone = require('backbone'); + throw new Error('module included'); +} catch (e) { + if (e.message === 'module included') { + throw e; + } else { + t.ok(true); + } +} \ No newline at end of file diff --git a/libcore/node_modules/browserify/test/external_shim.js b/libcore/node_modules/browserify/test/external_shim.js new file mode 100644 index 0000000..1c25124 --- /dev/null +++ b/libcore/node_modules/browserify/test/external_shim.js @@ -0,0 +1,27 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; + +test('requiring a shimmed module name from an external bundle', function (t) { + t.plan(1); + var b1 = browserify(); + var b2 = browserify(); + + b1.require(__dirname + '/external_shim/bundle1.js', { expose: 'bundle1' }); + b2.external(b1); + b2.require(__dirname + '/external_shim/bundle2.js', { expose: 'bundle2' }); + + b1.bundle(function (err, src1) { + b2.bundle(function (err, src2) { + + var c = { + console: console, + setTimeout: setTimeout, + clearTimeout: clearTimeout + }; + vm.runInNewContext(src1 + src2, c); + + t.ok(c.require('bundle1').shim === c.require('bundle2').shim); + }); + }); +}); diff --git a/libcore/node_modules/browserify/test/external_shim/bundle1.js b/libcore/node_modules/browserify/test/external_shim/bundle1.js new file mode 100644 index 0000000..4753f09 --- /dev/null +++ b/libcore/node_modules/browserify/test/external_shim/bundle1.js @@ -0,0 +1 @@ +exports.shim = require('shim'); diff --git a/libcore/node_modules/browserify/test/external_shim/bundle2.js b/libcore/node_modules/browserify/test/external_shim/bundle2.js new file mode 100644 index 0000000..4753f09 --- /dev/null +++ b/libcore/node_modules/browserify/test/external_shim/bundle2.js @@ -0,0 +1 @@ +exports.shim = require('shim'); diff --git a/libcore/node_modules/browserify/test/external_shim/package.json b/libcore/node_modules/browserify/test/external_shim/package.json new file mode 100644 index 0000000..2047ac6 --- /dev/null +++ b/libcore/node_modules/browserify/test/external_shim/package.json @@ -0,0 +1,5 @@ +{ + "browser": { + "shim": "./shim.js" + } +} \ No newline at end of file diff --git a/libcore/node_modules/browserify/test/external_shim/shim.js b/libcore/node_modules/browserify/test/external_shim/shim.js new file mode 100644 index 0000000..e69de29 diff --git a/libcore/node_modules/browserify/test/externalize.js b/libcore/node_modules/browserify/test/externalize.js new file mode 100644 index 0000000..8d76055 --- /dev/null +++ b/libcore/node_modules/browserify/test/externalize.js @@ -0,0 +1,59 @@ +var test = require('tap').test; +var spawn = require('child_process').spawn; +var concat = require('concat-stream'); +var path = require('path'); +var fs = require('fs'); +var vm = require('vm'); + +var temp = require('temp'); +temp.track(); +var tmpdir = temp.mkdirSync({prefix: 'browserify-test'}); +var pubdir = path.join(tmpdir, 'public'); + +fs.mkdirSync(pubdir); +fs.writeFileSync( + path.join(tmpdir, 'robot.js'), + fs.readFileSync(path.join(__dirname, 'externalize/robot.js')) +); +fs.writeFileSync( + path.join(tmpdir, 'beep.js'), + fs.readFileSync(path.join(__dirname, 'externalize/beep.js')) +); +fs.writeFileSync( + path.join(tmpdir, 'boop.js'), + fs.readFileSync(path.join(__dirname, 'externalize/boop.js')) +); + +test('externalize bin', function (t) { + t.plan(5); + + var commands = [ + [ '-r', './robot.js', '-o', path.join(pubdir, 'common.js') ], + [ '-x', './robot.js', 'beep.js', '-o', path.join(pubdir, 'beep.js') ], + [ '-x', './robot.js', 'boop.js', '-o', path.join(pubdir, 'boop/bop.js') ] + ]; + (function next () { + if (commands.length === 0) { + var common = fs.readFileSync(path.join(pubdir, 'common.js')); + var beep = fs.readFileSync(path.join(pubdir, 'beep.js')); + var boop = fs.readFileSync(path.join(pubdir, 'boop/bop.js')); + + vm.runInNewContext(common + beep, { + console: { log: function (msg) { t.equal(msg, 'BEEP!') } } + }); + vm.runInNewContext(common + boop, { + console: { log: function (msg) { t.equal(msg, 'BOOP!') } } + }); + } + else { + var args = commands.shift(); + args.unshift(path.join(__dirname, '../bin/cmd.js')); + var ps = spawn(process.execPath, args, { cwd: tmpdir }); + ps.stderr.pipe(process.stderr); + ps.on('exit', function (code) { + t.equal(code, 0, 'exit code'); + next() + }); + } + })(); +}); diff --git a/libcore/node_modules/browserify/test/externalize/beep.js b/libcore/node_modules/browserify/test/externalize/beep.js new file mode 100644 index 0000000..4daf2bd --- /dev/null +++ b/libcore/node_modules/browserify/test/externalize/beep.js @@ -0,0 +1,2 @@ +var robot = require('./robot.js'); +console.log(robot('beep')); \ No newline at end of file diff --git a/libcore/node_modules/browserify/test/externalize/boop.js b/libcore/node_modules/browserify/test/externalize/boop.js new file mode 100644 index 0000000..586e87f --- /dev/null +++ b/libcore/node_modules/browserify/test/externalize/boop.js @@ -0,0 +1,2 @@ +var robot = require('./robot.js'); +console.log(robot('boop')); \ No newline at end of file diff --git a/libcore/node_modules/browserify/test/externalize/robot.js b/libcore/node_modules/browserify/test/externalize/robot.js new file mode 100644 index 0000000..8a7ccd8 --- /dev/null +++ b/libcore/node_modules/browserify/test/externalize/robot.js @@ -0,0 +1 @@ +module.exports = function (s) { return s.toUpperCase() + '!' }; \ No newline at end of file diff --git a/libcore/node_modules/browserify/test/fake.js b/libcore/node_modules/browserify/test/fake.js new file mode 100644 index 0000000..a62fb93 --- /dev/null +++ b/libcore/node_modules/browserify/test/fake.js @@ -0,0 +1,15 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; + +test('fake', function (t) { + t.plan(1); + + var b = browserify(); + b.require(__dirname + '/fake/fake_fs.js', { expose: 'fs' }); + b.add(__dirname + '/fake/main.js'); + b.bundle(function (err, src) { + var c = { t: t }; + vm.runInNewContext(src, c); + }); +}); diff --git a/libcore/node_modules/browserify/test/fake/fake_fs.js b/libcore/node_modules/browserify/test/fake/fake_fs.js new file mode 100644 index 0000000..1ebc261 --- /dev/null +++ b/libcore/node_modules/browserify/test/fake/fake_fs.js @@ -0,0 +1 @@ +exports.party = function () { return 'PaRtY!1!1!' }; diff --git a/libcore/node_modules/browserify/test/fake/main.js b/libcore/node_modules/browserify/test/fake/main.js new file mode 100644 index 0000000..fd4339a --- /dev/null +++ b/libcore/node_modules/browserify/test/fake/main.js @@ -0,0 +1,2 @@ +var fs = require('fs'); +t.equal(fs.party(), 'PaRtY!1!1!'); diff --git a/libcore/node_modules/browserify/test/field.js b/libcore/node_modules/browserify/test/field.js new file mode 100644 index 0000000..8353504 --- /dev/null +++ b/libcore/node_modules/browserify/test/field.js @@ -0,0 +1,72 @@ +var assert = require('assert'); +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; + +test('fieldString', function (t) { + t.plan(1); + + var b = browserify(); + b.require(__dirname + '/field/string.js', { expose: './string.js' }); + b.bundle(function (err, src) { + if (err) return t.fail(err); + + var c = {}; + vm.runInNewContext(src, c); + t.equal( + c.require('./string.js'), + 'browser' + ); + }); +}); + +test('fieldObject', function (t) { + t.plan(1); + + var b = browserify(); + b.require(__dirname + '/field/object.js', { expose: './object.js' }); + b.bundle(function (err, src) { + if (err) return t.fail(err); + + var c = {}; + vm.runInNewContext(src, c); + t.equal( + c.require('./object.js'), + '!browser' + ); + }); +}); + +test('missObject', function (t) { + t.plan(1); + + var b = browserify(); + b.require(__dirname + '/field/miss.js', { expose: './miss.js' }); + b.bundle(function (err, src) { + if (err) return t.fail(err); + + var c = {}; + vm.runInNewContext(src, c); + t.equal( + c.require('./miss.js'), + '!browser' + ); + }); +}); + +test('fieldSub', function (t) { + t.plan(1); + + var b = browserify(); + b.require(__dirname + '/field/sub.js', { expose: './sub.js' }); + b.bundle(function (err, src) { + if (err) return t.fail(err); + + var c = {}; + vm.runInNewContext(src, c); + t.equal( + c.require('./sub.js'), + 'browser' + ); + }); +}); diff --git a/libcore/node_modules/browserify/test/field/miss.js b/libcore/node_modules/browserify/test/field/miss.js new file mode 100644 index 0000000..3619990 --- /dev/null +++ b/libcore/node_modules/browserify/test/field/miss.js @@ -0,0 +1 @@ +module.exports = require('z-miss') diff --git a/libcore/node_modules/browserify/test/field/object.js b/libcore/node_modules/browserify/test/field/object.js new file mode 100644 index 0000000..c373dc9 --- /dev/null +++ b/libcore/node_modules/browserify/test/field/object.js @@ -0,0 +1 @@ +module.exports = require('z-object') diff --git a/libcore/node_modules/browserify/test/field/string.js b/libcore/node_modules/browserify/test/field/string.js new file mode 100644 index 0000000..ee4c65d --- /dev/null +++ b/libcore/node_modules/browserify/test/field/string.js @@ -0,0 +1 @@ +module.exports = require('z-string') diff --git a/libcore/node_modules/browserify/test/field/sub.js b/libcore/node_modules/browserify/test/field/sub.js new file mode 100644 index 0000000..8c662a9 --- /dev/null +++ b/libcore/node_modules/browserify/test/field/sub.js @@ -0,0 +1 @@ +module.exports = require('z-sub') diff --git a/libcore/node_modules/browserify/test/file_event.js b/libcore/node_modules/browserify/test/file_event.js new file mode 100644 index 0000000..33ac36c --- /dev/null +++ b/libcore/node_modules/browserify/test/file_event.js @@ -0,0 +1,33 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; +var path = require('path'); + +test('file event', function (t) { + t.plan(8); + + var b = browserify(__dirname + '/entry/main.js'); + var files = { + 'main.js': path.join(__dirname, 'entry/main.js'), + 'one.js': './one', + 'two.js': './two' + }; + + b.on('file', function (file, id) { + var key = path.basename(file); + t.equal(file, path.join(__dirname, 'entry', key)); + t.equal(id, files[key]); + delete files[key]; + }); + + b.bundle(function (err, src) { + var c = { + done : function (one, two) { + t.equal(one, 1); + t.equal(two, 2); + t.end(); + } + }; + vm.runInNewContext(src, c); + }); +}); diff --git a/libcore/node_modules/browserify/test/five_bundle.js b/libcore/node_modules/browserify/test/five_bundle.js new file mode 100644 index 0000000..473f037 --- /dev/null +++ b/libcore/node_modules/browserify/test/five_bundle.js @@ -0,0 +1,30 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; + +test('five bundle', function (t) { + t.plan(3+4*2); + + var b = browserify(__dirname + '/entry/main.js'); + var source; + + b.bundle(function (err, src0) { + t.ifError(err); + var c = { + done : function (one, two) { + t.equal(one, 1); + t.equal(two, 2); + } + }; + vm.runInNewContext(src0, c); + + (function next (count) { + if (count === 5) return; + b.bundle(function (err, src1) { + t.ifError(err); + t.equal(src1.toString('utf8'), src0.toString('utf8')); + next(count+1); + }); + })(1); + }); +}); diff --git a/libcore/node_modules/browserify/test/full_paths.js b/libcore/node_modules/browserify/test/full_paths.js new file mode 100644 index 0000000..11431be --- /dev/null +++ b/libcore/node_modules/browserify/test/full_paths.js @@ -0,0 +1,58 @@ +var unpack = require('browser-unpack'); +var browserify = require('../'); +var test = require('tap').test; +var vm = require('vm'); +var path = require('path'); + +var deps = [ + path.join(__dirname, '/entry/main.js'), + path.join(__dirname, '/entry/one.js'), + path.join(__dirname, '/entry/two.js') +]; + +test('fullPaths enabled', function (t) { + t.plan(3); + + var b = browserify({ + entries: [ deps[0] ], + fullPaths: true + }); + + b.bundle(function (err, src) { + unpack(src).forEach(function(dep) { + t.notEqual(deps.indexOf(dep.id), -1, 'full path name for dep.id'); + }); + }); +}); + +test('fullPaths disabled', function (t) { + t.plan(3); + + var b = browserify({ + entries: [ deps[0] ], + fullPaths: false + }); + + b.bundle(function (err, src) { + unpack(src).forEach(function(dep) { + t.equal(deps.indexOf(dep.id), -1, 'full path name no longer available'); + }); + }); +}); + +test('fullPaths enabled, with custom exposed dependency name', function (t) { + t.plan(1); + + var b = browserify({ + entries: [__dirname + '/entry/needs_three.js'], + fullPaths: true + }); + + b.require(__dirname + '/entry/three.js', { expose: 'three' }); + + b.bundle(function (err, src) { + t.doesNotThrow(function () { + vm.runInNewContext(src, { console: console, t: t }); + }); + }); +}); diff --git a/libcore/node_modules/browserify/test/glob.js b/libcore/node_modules/browserify/test/glob.js new file mode 100644 index 0000000..4ac8093 --- /dev/null +++ b/libcore/node_modules/browserify/test/glob.js @@ -0,0 +1,29 @@ +var test = require('tap').test; +var spawn = require('child_process').spawn; +var path = require('path'); +var concat = require('concat-stream'); +var vm = require('vm'); + +test('glob', function (t) { + var expected = [ 'a', '!x', 'z', 'b', '!y' ]; + t.plan(expected.length + 1); + + var cwd = process.cwd(); + process.chdir(__dirname); + + var ps = spawn(process.execPath, [ + path.resolve(__dirname, '../bin/cmd.js'), + 'a.js', 'b.js', + '-u', 'vendor/*.js' + ], { cwd: __dirname + '/glob' }); + ps.stderr.pipe(process.stderr); + ps.stdout.pipe(concat(function (body) { + var c = { console: { log: log } }; + vm.runInNewContext(body.toString('utf8'), c); + function log (msg) { t.equal(msg, expected.shift()) } + })); + + ps.on('exit', function (code) { + t.equal(code, 0); + }); +}); diff --git a/libcore/node_modules/browserify/test/glob/a.js b/libcore/node_modules/browserify/test/glob/a.js new file mode 100644 index 0000000..97fe11a --- /dev/null +++ b/libcore/node_modules/browserify/test/glob/a.js @@ -0,0 +1,6 @@ +console.log('a'); + +try { require('./vendor/x.js') } +catch (err) { console.log('!x') } + +require('./lib/z.js') diff --git a/libcore/node_modules/browserify/test/glob/b.js b/libcore/node_modules/browserify/test/glob/b.js new file mode 100644 index 0000000..fedd5f4 --- /dev/null +++ b/libcore/node_modules/browserify/test/glob/b.js @@ -0,0 +1,5 @@ +console.log('b'); + +try { require('./vendor/y.js') } +catch (err) { console.log('!y') } + diff --git a/libcore/node_modules/browserify/test/glob/lib/z.js b/libcore/node_modules/browserify/test/glob/lib/z.js new file mode 100644 index 0000000..0475609 --- /dev/null +++ b/libcore/node_modules/browserify/test/glob/lib/z.js @@ -0,0 +1 @@ +console.log('z'); diff --git a/libcore/node_modules/browserify/test/glob/vendor/x.js b/libcore/node_modules/browserify/test/glob/vendor/x.js new file mode 100644 index 0000000..5eee864 --- /dev/null +++ b/libcore/node_modules/browserify/test/glob/vendor/x.js @@ -0,0 +1 @@ +console.log('x'); diff --git a/libcore/node_modules/browserify/test/glob/vendor/y.js b/libcore/node_modules/browserify/test/glob/vendor/y.js new file mode 100644 index 0000000..78a89b3 --- /dev/null +++ b/libcore/node_modules/browserify/test/glob/vendor/y.js @@ -0,0 +1 @@ +console.log('y'); diff --git a/libcore/node_modules/browserify/test/global.js b/libcore/node_modules/browserify/test/global.js new file mode 100644 index 0000000..8026bcf --- /dev/null +++ b/libcore/node_modules/browserify/test/global.js @@ -0,0 +1,92 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; + +if (!ArrayBuffer.isView) ArrayBuffer.isView = function () { return false; }; + +test('global', function (t) { + t.plan(2); + + var b = browserify(); + b.add(__dirname + '/global/main.js'); + b.bundle(function (err, src) { + var c = { + t : t, + a : 555, + }; + c.self = c; + vm.runInNewContext(src, c); + }); +}); + +test('__filename and __dirname with insertGlobals: true', function (t) { + t.plan(2); + + var b = browserify({ + insertGlobals: true, + basedir: __dirname + '/global' + }); + b.require(__dirname + '/global/filename.js', { expose: 'x' }); + b.bundle(function (err, src) { + var c = { Uint8Array: Uint8Array }; + c.self = c; + vm.runInNewContext(src, c); + var x = c.require('x'); + t.equal(x.filename, '/filename.js'); + t.equal(x.dirname, '/'); + }); +}); + +test('__filename and __dirname', function (t) { + t.plan(2); + + var b = browserify({ basedir: __dirname + '/global' }); + b.require(__dirname + '/global/filename.js', { expose: 'x' }); + b.bundle(function (err, src) { + var c = {}; + vm.runInNewContext(src, c); + var x = c.require('x'); + t.equal(x.filename, '/filename.js'); + t.equal(x.dirname, '/'); + }); +}); + +test('__filename and __dirname with basedir', function (t) { + t.plan(2); + + var b = browserify({ basedir: __dirname }); + b.require(__dirname + '/global/filename.js', { expose: 'x' }); + b.bundle(function (err, src) { + var c = {}; + vm.runInNewContext(src, c); + var x = c.require('x'); + t.equal(x.filename, '/global/filename.js'); + t.equal(x.dirname, '/global'); + }); +}); + +test('process.nextTick', function (t) { + t.plan(1); + + var b = browserify(); + b.add(__dirname + '/global/tick.js'); + b.bundle(function (err, src) { + var c = { t: t, setTimeout: setTimeout, clearTimeout: clearTimeout }; + vm.runInNewContext(src, c); + }); +}); + +test('Buffer', function (t) { + t.plan(2); + + var b = browserify(); + b.add(__dirname + '/global/buffer.js'); + b.bundle(function (err, src) { + var c = { + t: t, + Uint8Array: Uint8Array, + ArrayBuffer: ArrayBuffer + }; + vm.runInNewContext(src, c); + }); +}); diff --git a/libcore/node_modules/browserify/test/global/buffer.js b/libcore/node_modules/browserify/test/global/buffer.js new file mode 100644 index 0000000..fec6eeb --- /dev/null +++ b/libcore/node_modules/browserify/test/global/buffer.js @@ -0,0 +1,2 @@ +t.equal(Buffer('xyz').toString('base64'), 'eHl6'); +t.equal(Buffer('eHl6', 'base64').toString(), 'xyz'); diff --git a/libcore/node_modules/browserify/test/global/filename.js b/libcore/node_modules/browserify/test/global/filename.js new file mode 100644 index 0000000..85dc112 --- /dev/null +++ b/libcore/node_modules/browserify/test/global/filename.js @@ -0,0 +1,2 @@ +exports.filename = __filename; +exports.dirname = __dirname; diff --git a/libcore/node_modules/browserify/test/global/main.js b/libcore/node_modules/browserify/test/global/main.js new file mode 100644 index 0000000..d77852b --- /dev/null +++ b/libcore/node_modules/browserify/test/global/main.js @@ -0,0 +1,2 @@ +t.equal(a, 555); +t.equal(a, global.a); diff --git a/libcore/node_modules/browserify/test/global/tick.js b/libcore/node_modules/browserify/test/global/tick.js new file mode 100644 index 0000000..428f3ef --- /dev/null +++ b/libcore/node_modules/browserify/test/global/tick.js @@ -0,0 +1,3 @@ +process.nextTick(function () { + t.ok(true); +}); diff --git a/libcore/node_modules/browserify/test/global_coffeeify.js b/libcore/node_modules/browserify/test/global_coffeeify.js new file mode 100644 index 0000000..00aa54a --- /dev/null +++ b/libcore/node_modules/browserify/test/global_coffeeify.js @@ -0,0 +1,19 @@ +var test = require('tap').test; +var browserify = require('../'); +var vm = require('vm'); + +test('coffeeify globally', function (t) { + t.plan(1); + + var b = browserify(__dirname + '/coffeeify/main.coffee'); + b.transform('coffeeify', { global: true }); + b.bundle(function (err, src) { + if (err) t.fail(err); + vm.runInNewContext(src, { + console: { log: log }, + setTimeout: setTimeout, + clearTimeout: clearTimeout + }); + function log (msg) { t.equal(msg, 'eyo') } + }); +}); diff --git a/libcore/node_modules/browserify/test/global_noparse.js b/libcore/node_modules/browserify/test/global_noparse.js new file mode 100644 index 0000000..a4e5a70 --- /dev/null +++ b/libcore/node_modules/browserify/test/global_noparse.js @@ -0,0 +1,102 @@ +var browserify = require('../'); +var vm = require('vm'); +var path = require('path'); +var test = require('tap').test; + +test('global noparse module', function (t) { + t.plan(2); + + var b = browserify({ + noParse: 'aaa' + }); + b.require(__dirname + '/global/node_modules/aaa', { expose: 'x' }); + b.bundle(function (err, src) { + var c = { + __filename: __filename, + __dirname: __dirname + }; + vm.runInNewContext(src, c); + var x = c.require('x'); + t.equal(x.filename, __filename); + t.equal(x.dirname, __dirname); + }); +}); + +test('global noparse module file', function (t) { + t.plan(2); + + var b = browserify({ + noParse: 'aaa/index.js' + }); + b.require(__dirname + '/global/node_modules/aaa', { expose: 'x' }); + b.bundle(function (err, src) { + var c = { + __filename: __filename, + __dirname: __dirname + }; + vm.runInNewContext(src, c); + var x = c.require('x'); + t.equal(x.filename, __filename); + t.equal(x.dirname, __dirname); + }); +}); + +test('global noparse module deep file', function (t) { + t.plan(2); + + var b = browserify({ + noParse: 'robot/lib/beep.js' + }); + b.require(__dirname + '/global/node_modules/robot', { expose: 'x' }); + b.bundle(function (err, src) { + var c = { + __filename: __filename, + __dirname: __dirname + }; + vm.runInNewContext(src, c); + var x = c.require('x'); + t.equal(x.filename, __filename); + t.equal(x.dirname, __dirname); + }); +}); + +test('global noparse basedir', function (t) { + t.plan(2); + + var b = browserify({ + basedir: __dirname + '/global', + noParse: 'filename.js' + }); + b.require(__dirname + '/global/filename.js', { expose: 'x' }); + b.bundle(function (err, src) { + var c = { + __filename: __filename, + __dirname: __dirname + }; + vm.runInNewContext(src, c); + var x = c.require('x'); + t.equal(x.filename, __filename); + t.equal(x.dirname, __dirname); + }); +}); + +test('global noparse function', function (t) { + t.plan(2); + + var b = browserify({ + noParse: function(file) { + return file === path.join(__dirname, 'global/filename.js'); + } + }); + b.require(__dirname + '/global/filename.js', { expose: 'x' }); + b.bundle(function (err, src) { + var c = { + __filename: __filename, + __dirname: __dirname + }; + vm.runInNewContext(src, c); + var x = c.require('x'); + t.equal(x.filename, __filename); + t.equal(x.dirname, __dirname); + }); +}); diff --git a/libcore/node_modules/browserify/test/global_recorder.js b/libcore/node_modules/browserify/test/global_recorder.js new file mode 100644 index 0000000..7fdc07f --- /dev/null +++ b/libcore/node_modules/browserify/test/global_recorder.js @@ -0,0 +1,22 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; + +test('recorded global tr', function (t) { + t.plan(6); + + var b = browserify(__dirname + '/global_recorder/main.js'); + var context = { + console: { log: function (msg) { t.equal(msg, 'wow') } } + }; + b.bundle(function (err, src) { + t.ifError(err); + vm.runInNewContext(src, context); + t.equal(b._recorded.length, 2); + b.bundle(function (err, src) { + t.ifError(err); + vm.runInNewContext(src, context); + t.equal(b._recorded.length, 2); + }); + }); +}); diff --git a/libcore/node_modules/browserify/test/global_recorder/main.js b/libcore/node_modules/browserify/test/global_recorder/main.js new file mode 100644 index 0000000..6036bec --- /dev/null +++ b/libcore/node_modules/browserify/test/global_recorder/main.js @@ -0,0 +1 @@ +console.log('wow'); diff --git a/libcore/node_modules/browserify/test/hash.js b/libcore/node_modules/browserify/test/hash.js new file mode 100644 index 0000000..a459a40 --- /dev/null +++ b/libcore/node_modules/browserify/test/hash.js @@ -0,0 +1,15 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; + +test('hash', function (t) { + t.plan(3); + + var b = browserify(__dirname + '/hash/main.js'); + b.bundle(function (err, buf) { + var c = { t: t }; + var src = buf.toString('utf8'); + t.equal(src.match(RegExp('// FILE CONTENTS', 'g')).length, 1); + vm.runInNewContext(src, c); + }); +}); diff --git a/libcore/node_modules/browserify/test/hash/foo/other.js b/libcore/node_modules/browserify/test/hash/foo/other.js new file mode 100644 index 0000000..f4e8d9d --- /dev/null +++ b/libcore/node_modules/browserify/test/hash/foo/other.js @@ -0,0 +1 @@ +module.exports = 5; diff --git a/libcore/node_modules/browserify/test/hash/foo/two.js b/libcore/node_modules/browserify/test/hash/foo/two.js new file mode 100644 index 0000000..86c05b9 --- /dev/null +++ b/libcore/node_modules/browserify/test/hash/foo/two.js @@ -0,0 +1,2 @@ +// FILE CONTENTS +module.exports = 111 * require('./other.js'); diff --git a/libcore/node_modules/browserify/test/hash/main.js b/libcore/node_modules/browserify/test/hash/main.js new file mode 100644 index 0000000..b37dd88 --- /dev/null +++ b/libcore/node_modules/browserify/test/hash/main.js @@ -0,0 +1,2 @@ +t.equal(require('./foo/two.js'), 555); +t.equal(require('./one.js'), 333); diff --git a/libcore/node_modules/browserify/test/hash/one.js b/libcore/node_modules/browserify/test/hash/one.js new file mode 100644 index 0000000..86c05b9 --- /dev/null +++ b/libcore/node_modules/browserify/test/hash/one.js @@ -0,0 +1,2 @@ +// FILE CONTENTS +module.exports = 111 * require('./other.js'); diff --git a/libcore/node_modules/browserify/test/hash/other.js b/libcore/node_modules/browserify/test/hash/other.js new file mode 100644 index 0000000..690aad3 --- /dev/null +++ b/libcore/node_modules/browserify/test/hash/other.js @@ -0,0 +1 @@ +module.exports = 3; diff --git a/libcore/node_modules/browserify/test/hash_instance_context.js b/libcore/node_modules/browserify/test/hash_instance_context.js new file mode 100644 index 0000000..dda45aa --- /dev/null +++ b/libcore/node_modules/browserify/test/hash_instance_context.js @@ -0,0 +1,25 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; + +test('hash instances with hashed contexts', function (t) { + t.plan(17); + + var b = browserify(__dirname + '/hash_instance_context/main.js'); + b.bundle(function (err, buf) { + var c = { t: t }; + var src = buf.toString('utf8'); + t.equal(src.match(RegExp('// FILE F ONE', 'g')).length, 1); + t.equal(src.match(RegExp('// FILE G ONE', 'g')).length, 2); + + t.equal(src.match(RegExp('// FILE F TWO', 'g')).length, 1); + t.equal(src.match(RegExp('// FILE G TWO', 'g')).length, 1); + t.equal(src.match(RegExp('// FILE H TWO', 'g')).length, 2); + + t.equal(src.match(RegExp('// FILE F THREE', 'g')).length, 1); + t.equal(src.match(RegExp('// FILE G THREE', 'g')).length, 1); + t.equal(src.match(RegExp('// FILE H THREE', 'g')).length, 1); + + vm.runInNewContext(src, c); + }); +}); diff --git a/libcore/node_modules/browserify/test/hash_instance_context/main.js b/libcore/node_modules/browserify/test/hash_instance_context/main.js new file mode 100644 index 0000000..db1e23e --- /dev/null +++ b/libcore/node_modules/browserify/test/hash_instance_context/main.js @@ -0,0 +1,17 @@ +var A = require('./one/f.js'); +var B = require('./one/dir/f.js'); +t.notEqual(A, B); +t.equal(A(), 555); +t.equal(B(), 333); + +var C = require('./two/f.js'); +var D = require('./two/dir/f.js'); +t.notEqual(C, D); +t.equal(C(), 555); +t.equal(D(), 333); + +var E = require('./three/f.js'); +var F = require('./three/dir/f.js'); +t.notEqual(E, F); +t.equal(E(), 555); +t.equal(F(), 555); diff --git a/libcore/node_modules/browserify/test/hash_instance_context/one/dir/f.js b/libcore/node_modules/browserify/test/hash_instance_context/one/dir/f.js new file mode 100644 index 0000000..a315c1e --- /dev/null +++ b/libcore/node_modules/browserify/test/hash_instance_context/one/dir/f.js @@ -0,0 +1,3 @@ +// FILE F ONE +var G = require('./g.js'); +module.exports = function () { return 111 * G }; diff --git a/libcore/node_modules/browserify/test/hash_instance_context/one/dir/g.js b/libcore/node_modules/browserify/test/hash_instance_context/one/dir/g.js new file mode 100644 index 0000000..9cab61b --- /dev/null +++ b/libcore/node_modules/browserify/test/hash_instance_context/one/dir/g.js @@ -0,0 +1,2 @@ +// FILE G ONE +module.exports = 3 diff --git a/libcore/node_modules/browserify/test/hash_instance_context/one/f.js b/libcore/node_modules/browserify/test/hash_instance_context/one/f.js new file mode 100644 index 0000000..a315c1e --- /dev/null +++ b/libcore/node_modules/browserify/test/hash_instance_context/one/f.js @@ -0,0 +1,3 @@ +// FILE F ONE +var G = require('./g.js'); +module.exports = function () { return 111 * G }; diff --git a/libcore/node_modules/browserify/test/hash_instance_context/one/g.js b/libcore/node_modules/browserify/test/hash_instance_context/one/g.js new file mode 100644 index 0000000..8373032 --- /dev/null +++ b/libcore/node_modules/browserify/test/hash_instance_context/one/g.js @@ -0,0 +1,2 @@ +// FILE G ONE +module.exports = 5 diff --git a/libcore/node_modules/browserify/test/hash_instance_context/three/dir/f.js b/libcore/node_modules/browserify/test/hash_instance_context/three/dir/f.js new file mode 100644 index 0000000..51b1e73 --- /dev/null +++ b/libcore/node_modules/browserify/test/hash_instance_context/three/dir/f.js @@ -0,0 +1,3 @@ +// FILE F THREE +var G = require('./g.js'); +module.exports = function () { return 111 * G }; diff --git a/libcore/node_modules/browserify/test/hash_instance_context/three/dir/g.js b/libcore/node_modules/browserify/test/hash_instance_context/three/dir/g.js new file mode 100644 index 0000000..654f021 --- /dev/null +++ b/libcore/node_modules/browserify/test/hash_instance_context/three/dir/g.js @@ -0,0 +1,2 @@ +// FILE G THREE +module.exports = require('./h.js') + 1; diff --git a/libcore/node_modules/browserify/test/hash_instance_context/three/dir/h.js b/libcore/node_modules/browserify/test/hash_instance_context/three/dir/h.js new file mode 100644 index 0000000..afcc80f --- /dev/null +++ b/libcore/node_modules/browserify/test/hash_instance_context/three/dir/h.js @@ -0,0 +1,2 @@ +// FILE H THREE +module.exports = 4 diff --git a/libcore/node_modules/browserify/test/hash_instance_context/three/f.js b/libcore/node_modules/browserify/test/hash_instance_context/three/f.js new file mode 100644 index 0000000..51b1e73 --- /dev/null +++ b/libcore/node_modules/browserify/test/hash_instance_context/three/f.js @@ -0,0 +1,3 @@ +// FILE F THREE +var G = require('./g.js'); +module.exports = function () { return 111 * G }; diff --git a/libcore/node_modules/browserify/test/hash_instance_context/three/g.js b/libcore/node_modules/browserify/test/hash_instance_context/three/g.js new file mode 100644 index 0000000..654f021 --- /dev/null +++ b/libcore/node_modules/browserify/test/hash_instance_context/three/g.js @@ -0,0 +1,2 @@ +// FILE G THREE +module.exports = require('./h.js') + 1; diff --git a/libcore/node_modules/browserify/test/hash_instance_context/three/h.js b/libcore/node_modules/browserify/test/hash_instance_context/three/h.js new file mode 100644 index 0000000..afcc80f --- /dev/null +++ b/libcore/node_modules/browserify/test/hash_instance_context/three/h.js @@ -0,0 +1,2 @@ +// FILE H THREE +module.exports = 4 diff --git a/libcore/node_modules/browserify/test/hash_instance_context/two/dir/f.js b/libcore/node_modules/browserify/test/hash_instance_context/two/dir/f.js new file mode 100644 index 0000000..1178f93 --- /dev/null +++ b/libcore/node_modules/browserify/test/hash_instance_context/two/dir/f.js @@ -0,0 +1,3 @@ +// FILE F TWO +var G = require('./g.js'); +module.exports = function () { return 111 * G }; diff --git a/libcore/node_modules/browserify/test/hash_instance_context/two/dir/g.js b/libcore/node_modules/browserify/test/hash_instance_context/two/dir/g.js new file mode 100644 index 0000000..b940ee7 --- /dev/null +++ b/libcore/node_modules/browserify/test/hash_instance_context/two/dir/g.js @@ -0,0 +1,2 @@ +// FILE G TWO +module.exports = require('./h.js') + 1; diff --git a/libcore/node_modules/browserify/test/hash_instance_context/two/dir/h.js b/libcore/node_modules/browserify/test/hash_instance_context/two/dir/h.js new file mode 100644 index 0000000..74a8a7a --- /dev/null +++ b/libcore/node_modules/browserify/test/hash_instance_context/two/dir/h.js @@ -0,0 +1,2 @@ +// FILE H TWO +module.exports = 2 diff --git a/libcore/node_modules/browserify/test/hash_instance_context/two/f.js b/libcore/node_modules/browserify/test/hash_instance_context/two/f.js new file mode 100644 index 0000000..1178f93 --- /dev/null +++ b/libcore/node_modules/browserify/test/hash_instance_context/two/f.js @@ -0,0 +1,3 @@ +// FILE F TWO +var G = require('./g.js'); +module.exports = function () { return 111 * G }; diff --git a/libcore/node_modules/browserify/test/hash_instance_context/two/g.js b/libcore/node_modules/browserify/test/hash_instance_context/two/g.js new file mode 100644 index 0000000..b940ee7 --- /dev/null +++ b/libcore/node_modules/browserify/test/hash_instance_context/two/g.js @@ -0,0 +1,2 @@ +// FILE G TWO +module.exports = require('./h.js') + 1; diff --git a/libcore/node_modules/browserify/test/hash_instance_context/two/h.js b/libcore/node_modules/browserify/test/hash_instance_context/two/h.js new file mode 100644 index 0000000..42684f0 --- /dev/null +++ b/libcore/node_modules/browserify/test/hash_instance_context/two/h.js @@ -0,0 +1,2 @@ +// FILE H TWO +module.exports = 4 diff --git a/libcore/node_modules/browserify/test/identical.js b/libcore/node_modules/browserify/test/identical.js new file mode 100644 index 0000000..7d0deae --- /dev/null +++ b/libcore/node_modules/browserify/test/identical.js @@ -0,0 +1,19 @@ +var browserify = require('../'); +var test = require('tap').test; +var vm = require('vm'); + +test('identical', function (t) { + var expected = [ 0, 1, 0, 1 ]; + t.plan(expected.length + 1); + + var b = browserify(__dirname + '/identical/main.js'); + b.bundle(function (err, src) { + t.ifError(err); + vm.runInNewContext(src.toString('utf8'), { + console: { log: log } + }); + function log (msg) { + t.equal(msg, expected.shift()); + } + }); +}); diff --git a/libcore/node_modules/browserify/test/identical/main.js b/libcore/node_modules/browserify/test/identical/main.js new file mode 100644 index 0000000..c2e83ed --- /dev/null +++ b/libcore/node_modules/browserify/test/identical/main.js @@ -0,0 +1,6 @@ +var x = require('./x'); +var y = require('./y'); +console.log(x()); +console.log(x()); +console.log(y()); +console.log(y()); diff --git a/libcore/node_modules/browserify/test/identical/x.js b/libcore/node_modules/browserify/test/identical/x.js new file mode 100644 index 0000000..13c441d --- /dev/null +++ b/libcore/node_modules/browserify/test/identical/x.js @@ -0,0 +1,2 @@ +var i = 0; +module.exports = function () { return i++ }; diff --git a/libcore/node_modules/browserify/test/identical/y.js b/libcore/node_modules/browserify/test/identical/y.js new file mode 100644 index 0000000..13c441d --- /dev/null +++ b/libcore/node_modules/browserify/test/identical/y.js @@ -0,0 +1,2 @@ +var i = 0; +module.exports = function () { return i++ }; diff --git a/libcore/node_modules/browserify/test/identical_different.js b/libcore/node_modules/browserify/test/identical_different.js new file mode 100644 index 0000000..a2e7911 --- /dev/null +++ b/libcore/node_modules/browserify/test/identical_different.js @@ -0,0 +1,19 @@ +var browserify = require('../'); +var test = require('tap').test; +var vm = require('vm'); + +test('identical', function (t) { + var expected = [ 1, 2, 10, 110 ]; + t.plan(expected.length + 1); + + var b = browserify(__dirname + '/identical_different/main.js'); + b.bundle(function (err, src) { + t.ifError(err); + vm.runInNewContext(src.toString('utf8'), { + console: { log: log } + }); + function log (msg) { + t.equal(msg, expected.shift()); + } + }); +}); diff --git a/libcore/node_modules/browserify/test/identical_different/main.js b/libcore/node_modules/browserify/test/identical_different/main.js new file mode 100644 index 0000000..5a4154b --- /dev/null +++ b/libcore/node_modules/browserify/test/identical_different/main.js @@ -0,0 +1,6 @@ +var x = require('./x'); +var y = require('./wow/y'); +console.log(x()); +console.log(x()); +console.log(y()); +console.log(y()); diff --git a/libcore/node_modules/browserify/test/identical_different/wow/y.js b/libcore/node_modules/browserify/test/identical_different/wow/y.js new file mode 100644 index 0000000..0b8636f --- /dev/null +++ b/libcore/node_modules/browserify/test/identical_different/wow/y.js @@ -0,0 +1,3 @@ +var op = require('op'); +var i = 0; +module.exports = function () { i = op(i); return i }; diff --git a/libcore/node_modules/browserify/test/identical_different/x.js b/libcore/node_modules/browserify/test/identical_different/x.js new file mode 100644 index 0000000..0b8636f --- /dev/null +++ b/libcore/node_modules/browserify/test/identical_different/x.js @@ -0,0 +1,3 @@ +var op = require('op'); +var i = 0; +module.exports = function () { i = op(i); return i }; diff --git a/libcore/node_modules/browserify/test/ignore.js b/libcore/node_modules/browserify/test/ignore.js new file mode 100644 index 0000000..4cb7097 --- /dev/null +++ b/libcore/node_modules/browserify/test/ignore.js @@ -0,0 +1,91 @@ +var browserify = require('../'); +var test = require('tap').test; +var vm = require('vm'); +var path = require('path'); + +test('ignore', function (t) { + t.plan(1); + + var b = browserify(); + b.add(__dirname + '/ignore/main.js'); + b.ignore(path.join(__dirname, 'ignore/skip.js')); + + b.bundle(function (err, src) { + if (err) t.fail(err); + vm.runInNewContext(src, { t: t }); + }); +}); + +test('ignore array', function(t) { + t.plan(2); + + var b = browserify(); + b.add(__dirname + '/ignore/array.js'); + b.ignore([ + path.join(__dirname, 'ignore/skip.js'), + path.join(__dirname, 'ignore/skip2.js') + ]); + + b.bundle(function (err, src) { + if (err) { + t.fail(err); + } + vm.runInNewContext(src, { t: t }); + }); +}); + +test('ignore by package or id', function (t) { + t.plan(3); + + var b = browserify(); + b.add(__dirname + '/ignore/by-id.js'); + b.ignore('events'); + b.ignore('beep'); + b.ignore('bad id'); + + b.bundle(function (err, src) { + if (err) t.fail(err); + vm.runInNewContext(src, { t: t }); + }); +}); + +test('ignore files referenced by relative path', function (t) { + // Change the current working directory relative to this file + var cwd = process.cwd(); + process.chdir(__dirname); + + t.plan(1); + + var b = browserify(); + b.add(__dirname + '/ignore/by-relative.js'); + b.ignore('./ignore/ignored/skip.js'); + + b.bundle(function (err, src) { + if (err) t.fail(err); + vm.runInNewContext(src, { t: t }); + }); + + // Revert CWD + process.chdir(cwd); +}); + +test('do not ignore files with relative paths that do not resolve', function (t) { + // Change the current working directory to the ignore folder + var cwd = process.cwd(); + process.chdir(__dirname + '/ignore'); + + t.plan(2); + + var b = browserify(); + b.add(__dirname + '/ignore/double-skip.js'); + + b.ignore('./skip.js'); + + b.bundle(function (err, src) { + if (err) t.fail(err); + vm.runInNewContext(src, { t: t }); + }); + + // Revert CWD + process.chdir(cwd); +}); diff --git a/libcore/node_modules/browserify/test/ignore/array.js b/libcore/node_modules/browserify/test/ignore/array.js new file mode 100644 index 0000000..837e179 --- /dev/null +++ b/libcore/node_modules/browserify/test/ignore/array.js @@ -0,0 +1,2 @@ +t.deepEqual(require('./skip.js'), {}); +t.deepEqual(require('./skip2.js'), {}); diff --git a/libcore/node_modules/browserify/test/ignore/by-id.js b/libcore/node_modules/browserify/test/ignore/by-id.js new file mode 100644 index 0000000..61c0baa --- /dev/null +++ b/libcore/node_modules/browserify/test/ignore/by-id.js @@ -0,0 +1,3 @@ +t.deepEqual(require('events'), {}); +t.deepEqual(require('bad id'), {}); +t.deepEqual(require('beep'), {}); \ No newline at end of file diff --git a/libcore/node_modules/browserify/test/ignore/by-relative.js b/libcore/node_modules/browserify/test/ignore/by-relative.js new file mode 100644 index 0000000..e50676e --- /dev/null +++ b/libcore/node_modules/browserify/test/ignore/by-relative.js @@ -0,0 +1,5 @@ +/** + * This test is to check to make sure that files that are ignored do not get + * bundled when referenced with a nested relative path. + */ +t.deepEqual(require('./relative'), {}); diff --git a/libcore/node_modules/browserify/test/ignore/double-skip.js b/libcore/node_modules/browserify/test/ignore/double-skip.js new file mode 100644 index 0000000..ad61cce --- /dev/null +++ b/libcore/node_modules/browserify/test/ignore/double-skip.js @@ -0,0 +1,2 @@ +t.deepEqual(require('./skip.js'), {}); +t.deepEqual(require('./double-skip/index'), {foo: 'bar'}); \ No newline at end of file diff --git a/libcore/node_modules/browserify/test/ignore/double-skip/index.js b/libcore/node_modules/browserify/test/ignore/double-skip/index.js new file mode 100644 index 0000000..affe2f2 --- /dev/null +++ b/libcore/node_modules/browserify/test/ignore/double-skip/index.js @@ -0,0 +1 @@ +module.exports = require('./skip.js'); \ No newline at end of file diff --git a/libcore/node_modules/browserify/test/ignore/double-skip/skip.js b/libcore/node_modules/browserify/test/ignore/double-skip/skip.js new file mode 100644 index 0000000..1922194 --- /dev/null +++ b/libcore/node_modules/browserify/test/ignore/double-skip/skip.js @@ -0,0 +1,5 @@ +// this module should return something + +module.exports = { + foo: 'bar' +}; diff --git a/libcore/node_modules/browserify/test/ignore/ignored/skip.js b/libcore/node_modules/browserify/test/ignore/ignored/skip.js new file mode 100644 index 0000000..006521e --- /dev/null +++ b/libcore/node_modules/browserify/test/ignore/ignored/skip.js @@ -0,0 +1 @@ +t.fail('this file should have been skipped'); diff --git a/libcore/node_modules/browserify/test/ignore/main.js b/libcore/node_modules/browserify/test/ignore/main.js new file mode 100644 index 0000000..0149b75 --- /dev/null +++ b/libcore/node_modules/browserify/test/ignore/main.js @@ -0,0 +1 @@ +t.deepEqual(require('./skip.js'), {}); diff --git a/libcore/node_modules/browserify/test/ignore/relative/index.js b/libcore/node_modules/browserify/test/ignore/relative/index.js new file mode 100644 index 0000000..3f73c32 --- /dev/null +++ b/libcore/node_modules/browserify/test/ignore/relative/index.js @@ -0,0 +1 @@ +module.exports = require('../ignored/skip.js'); \ No newline at end of file diff --git a/libcore/node_modules/browserify/test/ignore/skip.js b/libcore/node_modules/browserify/test/ignore/skip.js new file mode 100644 index 0000000..006521e --- /dev/null +++ b/libcore/node_modules/browserify/test/ignore/skip.js @@ -0,0 +1 @@ +t.fail('this file should have been skipped'); diff --git a/libcore/node_modules/browserify/test/ignore/skip2.js b/libcore/node_modules/browserify/test/ignore/skip2.js new file mode 100644 index 0000000..006521e --- /dev/null +++ b/libcore/node_modules/browserify/test/ignore/skip2.js @@ -0,0 +1 @@ +t.fail('this file should have been skipped'); diff --git a/libcore/node_modules/browserify/test/ignore_browser_field.js b/libcore/node_modules/browserify/test/ignore_browser_field.js new file mode 100644 index 0000000..a925f2e --- /dev/null +++ b/libcore/node_modules/browserify/test/ignore_browser_field.js @@ -0,0 +1,21 @@ +var test = require('tap').test; +var browserify = require('../'); +var path = require('path'); +var mainfile = path.join(__dirname, 'ignore_browser_field/main.js'); +var vm = require('vm'); + +test('ignore browser field', function (t) { + t.plan(3); + var b = browserify(mainfile, { browserField: false }); + var expected = [ 'A:NODE', 'B:X.JS' ]; + + b.bundle(function (err, src) { + t.ifError(err); + var c = { console: { log: log } }; + vm.runInNewContext(src, c); + + function log (msg) { + t.equal(msg, expected.shift()); + } + }); +}); diff --git a/libcore/node_modules/browserify/test/ignore_browser_field/main.js b/libcore/node_modules/browserify/test/ignore_browser_field/main.js new file mode 100644 index 0000000..bae4a22 --- /dev/null +++ b/libcore/node_modules/browserify/test/ignore_browser_field/main.js @@ -0,0 +1,2 @@ +console.log(require('a')); +console.log(require('b')); diff --git a/libcore/node_modules/browserify/test/ignore_missing.js b/libcore/node_modules/browserify/test/ignore_missing.js new file mode 100644 index 0000000..ddf72ed --- /dev/null +++ b/libcore/node_modules/browserify/test/ignore_missing.js @@ -0,0 +1,41 @@ +var browserify = require('../'); +var test = require('tap').test; + +test('ignoreMissing option', function (t) { + t.test('on browserify', function(t) { + t.plan(1); + + var ignored = browserify({ + entries: [__dirname + '/ignore_missing/main.js'], + ignoreMissing: true + }); + + ignored.bundle(function(err) { + t.ok(!err, "bundle completed with missing file ignored"); + }); + }); + + t.test('on .bundle', function(t) { + t.plan(1); + + var ignored = browserify(__dirname + '/ignore_missing/main.js', { + ignoreMissing: true + }); + + ignored.bundle(function(err) { + t.ok(!err, "bundle completed with missing file ignored"); + }); + }); + + t.test('defaults to false', function (t) { + t.plan(1); + + var expected = browserify(__dirname + '/ignore_missing/main.js'); + + expected.bundle(function(err) { + t.ok(err, 'ignoreMissing was false, an error was raised'); + }); + }); + + t.end(); +}); diff --git a/libcore/node_modules/browserify/test/ignore_missing/main.js b/libcore/node_modules/browserify/test/ignore_missing/main.js new file mode 100644 index 0000000..a522a65 --- /dev/null +++ b/libcore/node_modules/browserify/test/ignore_missing/main.js @@ -0,0 +1 @@ +require('./no_such_file'); diff --git a/libcore/node_modules/browserify/test/ignore_transform_key.js b/libcore/node_modules/browserify/test/ignore_transform_key.js new file mode 100644 index 0000000..34e6d49 --- /dev/null +++ b/libcore/node_modules/browserify/test/ignore_transform_key.js @@ -0,0 +1,17 @@ +var browserify = require('../'); +var test = require('tap').test; +var vm = require('vm'); + +test('ignore transform', function(t) { + t.plan(1); + + var b = browserify({ + transformKey: false + }); + b.add(__dirname + '/ignore_transform_key/main.js'); + + b.bundle(function(err, src) { + if (err) t.fail(err); + vm.runInNewContext(src, {t: t}); + }); +}); diff --git a/libcore/node_modules/browserify/test/ignore_transform_key/main.js b/libcore/node_modules/browserify/test/ignore_transform_key/main.js new file mode 100644 index 0000000..97be0ea --- /dev/null +++ b/libcore/node_modules/browserify/test/ignore_transform_key/main.js @@ -0,0 +1,3 @@ +var a = require('a'); + +t.equal(a, 'good'); diff --git a/libcore/node_modules/browserify/test/json.js b/libcore/node_modules/browserify/test/json.js new file mode 100644 index 0000000..0ec7220 --- /dev/null +++ b/libcore/node_modules/browserify/test/json.js @@ -0,0 +1,57 @@ +var browserify = require('../'); +var fs = require('fs'); +var vm = require('vm'); +var semver = require('semver'); +var test = require('tap').test; + +test('json', function (t) { + t.plan(2); + var b = browserify(); + b.add(__dirname + '/json/main.js'); + b.bundle(function (err, src) { + if (err) t.fail(err); + var c = { + ex : function (obj) { + t.same(obj, { beep : 'boop', x : 555 }); + } + }; + vm.runInNewContext(src, c); + }); +}); + +// This works in Node v10 and up thanks to the JSON superset proposal, which +// allows the evil chars in javascript strings. +// https://github.com/tc39/proposal-json-superset +test('verify evil json', { skip: semver.gte(process.version, 'v10.0.0') }, function(t) { + t.plan(1); + fs.readFile(__dirname + '/json/evil-chars.json', function(err, data) { + if (err) t.fail(err); + t.throws(function() { + vm.runInNewContext('(' + data.toString() + ')'); + }); + }); +}); + +test('evil json', function (t) { + t.plan(2); + var b = browserify(); + b.add(__dirname + '/json/evil.js'); + b.bundle(function (err, src) { + if (err) t.fail(err); + var c = { + ex : function (obj) { + t.same(obj, { evil : '\u2028\u2029' }); + } + }; + vm.runInNewContext(src, c); + }); +}); + +test('invalid json', function (t) { + var b = browserify(); + t.plan(1); + b.add(__dirname + '/json/invalid.js'); + b.bundle(function (err, src) { + t.ok(err); + }); +}); diff --git a/libcore/node_modules/browserify/test/json/beep.json b/libcore/node_modules/browserify/test/json/beep.json new file mode 100644 index 0000000..d85cfe5 --- /dev/null +++ b/libcore/node_modules/browserify/test/json/beep.json @@ -0,0 +1,4 @@ +{ + "beep" : "boop", + "x" : 555 +} diff --git a/libcore/node_modules/browserify/test/json/evil-chars.json b/libcore/node_modules/browserify/test/json/evil-chars.json new file mode 100644 index 0000000..4a5851b --- /dev/null +++ b/libcore/node_modules/browserify/test/json/evil-chars.json @@ -0,0 +1,3 @@ +{ + "evil": "

" +} diff --git a/libcore/node_modules/browserify/test/json/evil.js b/libcore/node_modules/browserify/test/json/evil.js new file mode 100644 index 0000000..767e9cb --- /dev/null +++ b/libcore/node_modules/browserify/test/json/evil.js @@ -0,0 +1,2 @@ +ex(require('./evil-chars.json')); +ex(require('./evil-chars')); diff --git a/libcore/node_modules/browserify/test/json/invalid.js b/libcore/node_modules/browserify/test/json/invalid.js new file mode 100644 index 0000000..36ef338 --- /dev/null +++ b/libcore/node_modules/browserify/test/json/invalid.js @@ -0,0 +1,2 @@ +ex(require('./invalid.json')); +ex(require('./invalid')); diff --git a/libcore/node_modules/browserify/test/json/invalid.json b/libcore/node_modules/browserify/test/json/invalid.json new file mode 100644 index 0000000..fb73e57 --- /dev/null +++ b/libcore/node_modules/browserify/test/json/invalid.json @@ -0,0 +1,3 @@ +{ + key: "value" +} \ No newline at end of file diff --git a/libcore/node_modules/browserify/test/json/main.js b/libcore/node_modules/browserify/test/json/main.js new file mode 100644 index 0000000..f459f30 --- /dev/null +++ b/libcore/node_modules/browserify/test/json/main.js @@ -0,0 +1,2 @@ +ex(require('./beep.json')); +ex(require('./beep')); diff --git a/libcore/node_modules/browserify/test/leak.js b/libcore/node_modules/browserify/test/leak.js new file mode 100644 index 0000000..0688165 --- /dev/null +++ b/libcore/node_modules/browserify/test/leak.js @@ -0,0 +1,59 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; +var path = require('path'); +var through = require('through2'); + +var os = require('os'); +var tmpdir = (os.tmpdir || os.tmpDir)(); +var dir = path.join( + tmpdir, + 'browserify-test-' + Math.random(), + 'aaabbbzzz' +); +var dirstring = dir.split(path.sep).slice(-2).join(path.sep); + +if (!ArrayBuffer.isView) ArrayBuffer.isView = function () { return false; }; + +test('leaking information about system paths (process)', function (t) { + t.plan(4); + + var b = browserify({ basedir: dir }); + var stream = through(); + stream.push('process.nextTick(function () {' + + 't.ok(true)' + + '})' + ); + stream.push(null); + b.add(stream); + + b.bundle(function (err, buf) { + var src = buf.toString('utf8'); + t.equal(src.indexOf(dirstring), -1, 'temp directory visible'); + t.equal(src.indexOf(process.cwd()), -1, 'cwd directory visible'); + t.equal(src.indexOf('/home'), -1, 'home directory visible'); + vm.runInNewContext(src, { + t: t, + setTimeout: setTimeout, + clearTimeout: clearTimeout + }); + }); +}); + +test('leaking information about system paths (Buffer)', function (t) { + t.plan(4); + + var b = browserify({ basedir: dir }); + var stream = through(); + stream.push('t.equal(Buffer("eHl6", "base64").toString(), "xyz")'); + stream.push(null); + b.add(stream); + + b.bundle(function (err, buf) { + var src = buf.toString('utf8'); + t.equal(src.indexOf(dirstring), -1, 'temp directory visible'); + t.equal(src.indexOf(process.cwd()), -1, 'cwd directory visible'); + t.equal(src.indexOf('/home'), -1, 'home directory visible'); + vm.runInNewContext(src, { t: t, setTimeout: setTimeout, Uint8Array: Uint8Array, ArrayBuffer: ArrayBuffer }); + }); +}); diff --git a/libcore/node_modules/browserify/test/maxlisteners.js b/libcore/node_modules/browserify/test/maxlisteners.js new file mode 100644 index 0000000..11cfd82 --- /dev/null +++ b/libcore/node_modules/browserify/test/maxlisteners.js @@ -0,0 +1,13 @@ +var test = require('tap').test; +var browserify = require('../'); +var vm = require('vm'); + +test('setMaxListener', function (t) { + t.plan(1); + var b = browserify(); + b.add(__dirname + '/maxlisteners/main.js'); + b.bundle(function (err, src) { + vm.runInNewContext(src); + t.ok(true); // didn't crash + }); +}); diff --git a/libcore/node_modules/browserify/test/maxlisteners/main.js b/libcore/node_modules/browserify/test/maxlisteners/main.js new file mode 100644 index 0000000..a5496a6 --- /dev/null +++ b/libcore/node_modules/browserify/test/maxlisteners/main.js @@ -0,0 +1,3 @@ +var EventEmitter = require('events').EventEmitter +var ee = new EventEmitter; +ee.setMaxListeners(5); diff --git a/libcore/node_modules/browserify/test/multi_bundle.js b/libcore/node_modules/browserify/test/multi_bundle.js new file mode 100644 index 0000000..05411d3 --- /dev/null +++ b/libcore/node_modules/browserify/test/multi_bundle.js @@ -0,0 +1,86 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; + +test('multi bundle', function (t) { + t.plan(5); + + var core = browserify(); + core.require(__dirname + '/multi_bundle/b.js', { expose: true }); + + var app = browserify([__dirname + '/multi_bundle/a.js']); + // inform this bundle that b exists in another bundle + app.external(__dirname + '/multi_bundle/b.js'); + + core.bundle(function (err, src) { + var c = { + console: console, + t : t, + baton: { + times: 0 + } + }; + + // loading core will cause no require to run + vm.runInNewContext(src, c); + t.equal(c.baton.times, 0); + + // loading the app will require + app.bundle(function (err, src) { + vm.runInNewContext(src, c); + + // b required for the first time + t.equal(c.baton.times, 1); + + // running the file again + // because it is using the same b, no reloading + vm.runInNewContext(src, c); + + // b should not have been required again + // because it was part of the core bundle + t.equal(c.baton.times, 1); + }); + }); +}); + +// re-enable this in future releases +test('multi bundle', function (t) { + t.plan(8); + + var core = browserify({ exposeAll: true }); + core.require(__dirname + '/multi_bundle/a.js', { expose: true }); + + var app = browserify([__dirname + '/multi_bundle/c.js']); + // inform this bundle that b exists in another bundle + app.external(core); + + core.bundle(function (err, src) { + var c = { + console: console, + t : t, + baton: { + times: 0 + } + }; + + // loading core will cause no require to run + vm.runInNewContext(src, c); + t.equal(c.baton.times, 0); + + // loading the app will require + app.bundle(function (err, src) { + vm.runInNewContext(src, c); + + // b required for the first time + t.equal(c.baton.times, 1); + + // running the file again + // because it is using the same b, no reloading + vm.runInNewContext(src, c); + + // b should not have been required again + // because it was part of the core bundle + t.equal(c.baton.times, 1); + }); + }); +}); diff --git a/libcore/node_modules/browserify/test/multi_bundle/_prelude.js b/libcore/node_modules/browserify/test/multi_bundle/_prelude.js new file mode 100644 index 0000000..95eb4bc --- /dev/null +++ b/libcore/node_modules/browserify/test/multi_bundle/_prelude.js @@ -0,0 +1 @@ +(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof unique_require=="function"&&unique_require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof unique_require=="function"&&unique_require;for(var o=0;o -1, 'should contain full entry path'); + } + }); + + b.bundle(function (err, src) { + var c = { + times : 0, + t : t + }; + vm.runInNewContext(src, c); + }); +}); + +test('multi entry relative', function (t) { + t.plan(6); + + var rTestFiles = testFiles.map(function(x) { + return x.replace(__dirname + '/', ''); + }); + + var b = browserify({ + entries: [rTestFiles[0], rTestFiles[1]], + basedir: __dirname + }); + b.add(rTestFiles[2]); + + b.on('dep', function(row) { + if (row.entry) { + t.ok(testFiles.indexOf(row.file) > -1, 'should contain full entry path'); + } + }); + + b.bundle(function (err, src) { + var c = { + times : 0, + t : t + }; + vm.runInNewContext(src, c); + }); +}); + +test('multi entry relative cwd', function (t) { + t.plan(6); + + var rTestFiles = testFiles.map(function(x) { + return x.replace(__dirname + '/', './'); + }); + + var b = browserify({ + entries: [rTestFiles[0], rTestFiles[1]], + basedir: __dirname + }); + b.add(rTestFiles[2]); + + b.on('dep', function(row) { + if (row.entry) { + t.ok(testFiles.indexOf(row.file) > -1, 'should contain full entry path'); + } + }); + + b.bundle(function (err, src) { + var c = { + times : 0, + t : t + }; + vm.runInNewContext(src, c); + }); +}); + +test('entries as streams', function (t) { + t.plan(6); + + // commondir blows up with streams and without basedir + var opts = { basedir: __dirname + '/multi_entry' }; + + var b = browserify([ + fs.createReadStream(testFiles[0]), + fs.createReadStream(testFiles[1]) + ], opts); + b.add(fs.createReadStream(testFiles[2])); + + b.on('dep', function(row) { + if (row.entry) { + t.similar( + row.file, + RegExp(path.join(__dirname, 'multi_entry/_stream_').replace(/\\/g, '\\\\') + '[\\d].js'), + 'should be full entry path' + ); + } + }); + + b.bundle(function (err, src) { + var c = { + times : 0, + t : t + }; + vm.runInNewContext(src, c); + }); +}); diff --git a/libcore/node_modules/browserify/test/multi_entry/a.js b/libcore/node_modules/browserify/test/multi_entry/a.js new file mode 100644 index 0000000..d4e250e --- /dev/null +++ b/libcore/node_modules/browserify/test/multi_entry/a.js @@ -0,0 +1,2 @@ +times ++; +t.equal(times, 1); diff --git a/libcore/node_modules/browserify/test/multi_entry/b.js b/libcore/node_modules/browserify/test/multi_entry/b.js new file mode 100644 index 0000000..bed7bbb --- /dev/null +++ b/libcore/node_modules/browserify/test/multi_entry/b.js @@ -0,0 +1,2 @@ +times ++; +t.equal(times, 2); diff --git a/libcore/node_modules/browserify/test/multi_entry/c.js b/libcore/node_modules/browserify/test/multi_entry/c.js new file mode 100644 index 0000000..ac3c174 --- /dev/null +++ b/libcore/node_modules/browserify/test/multi_entry/c.js @@ -0,0 +1,2 @@ +times ++; +t.equal(times, 3); diff --git a/libcore/node_modules/browserify/test/multi_entry_cross_require.js b/libcore/node_modules/browserify/test/multi_entry_cross_require.js new file mode 100644 index 0000000..43f04ea --- /dev/null +++ b/libcore/node_modules/browserify/test/multi_entry_cross_require.js @@ -0,0 +1,93 @@ +var browserify = require('../'); +var vm = require('vm'); +var path = require('path'); +var test = require('tap').test; + +var testFiles = [ + path.join(__dirname, 'multi_entry_cross_require/a.js'), + path.join(__dirname, 'multi_entry_cross_require/lib/b.js'), + path.join(__dirname, 'multi_entry_cross_require/c.js') +]; + +test('multi entry cross require', function (t) { + t.plan(8); + + var b = browserify([ + testFiles[0], + testFiles[1] + ]); + b.add(testFiles[2]); + + b.on('dep', function(row) { + if (row.entry) { + t.ok(testFiles.indexOf(row.file) > -1, 'should contain full entry path'); + } + }); + + b.bundle(function (err, src) { + if (err) throw err; + var c = { + times : 0, + t : t + }; + vm.runInNewContext(src, c); + }); +}); + +test('multi entry cross require - relative cwd', function (t) { + t.plan(8); + + var dsTestFiles = testFiles.map(function(x) { + return x.replace(__dirname + '/', './'); + }); + + var b = browserify({ + entries: [dsTestFiles[0], dsTestFiles[1]], + basedir: __dirname + }); + b.add(dsTestFiles[2]); + + b.on('dep', function(row) { + if (row.entry) { + t.ok(testFiles.indexOf(row.file) > -1, 'should contain full entry path'); + } + }); + + b.bundle(function (err, src) { + if (err) throw err; + var c = { + times : 0, + t : t + }; + vm.runInNewContext(src, c); + }); +}); + +test('multi entry cross require - relative', function (t) { + t.plan(8); + + var rTestFiles = testFiles.map(function(x) { + return x.replace(__dirname + '/', ''); + }); + + var b = browserify({ + entries: [rTestFiles[0], rTestFiles[1]], + basedir: __dirname + }); + b.add(rTestFiles[2]); + + b.on('dep', function(row) { + if (row.entry) { + t.ok(testFiles.indexOf(row.file) > -1, 'should contain full entry path'); + } + }); + + b.bundle(function (err, src) { + if (err) throw err; + var c = { + times : 0, + t : t + }; + vm.runInNewContext(src, c); + }); +}); diff --git a/libcore/node_modules/browserify/test/multi_entry_cross_require/a.js b/libcore/node_modules/browserify/test/multi_entry_cross_require/a.js new file mode 100644 index 0000000..0223daf --- /dev/null +++ b/libcore/node_modules/browserify/test/multi_entry_cross_require/a.js @@ -0,0 +1,8 @@ +times ++; +t.equal(times, 1); + +var b = require('./lib/b'); +t.equal(times, 2); + +b.foo(); +t.equal(times, 3); diff --git a/libcore/node_modules/browserify/test/multi_entry_cross_require/c.js b/libcore/node_modules/browserify/test/multi_entry_cross_require/c.js new file mode 100644 index 0000000..e191838 --- /dev/null +++ b/libcore/node_modules/browserify/test/multi_entry_cross_require/c.js @@ -0,0 +1,7 @@ +times++; +t.equal(times, 4); + +var b = require('./lib/b'); +b.foo(); + +t.equal(times, 5); diff --git a/libcore/node_modules/browserify/test/multi_entry_cross_require/lib/b.js b/libcore/node_modules/browserify/test/multi_entry_cross_require/lib/b.js new file mode 100644 index 0000000..e7d2dad --- /dev/null +++ b/libcore/node_modules/browserify/test/multi_entry_cross_require/lib/b.js @@ -0,0 +1,5 @@ +times++; + +module.exports.foo = function() { + times++; +}; diff --git a/libcore/node_modules/browserify/test/multi_require.js b/libcore/node_modules/browserify/test/multi_require.js new file mode 100644 index 0000000..a1b3f64 --- /dev/null +++ b/libcore/node_modules/browserify/test/multi_require.js @@ -0,0 +1,18 @@ +var browserify = require('../'); +var test = require('tap').test; +var vm = require('vm'); + +test('require same file locally and globally', function (t) { + t.plan(2); + + var b = browserify(__dirname + '/multi_require/main.js', { + basedir: __dirname + }); + b.require('./multi_require/a.js', {expose: 'a'}); + + b.bundle(function (err, src) { + t.ifError(err); + var c = {t: t}; + vm.runInNewContext(src, c); + }); +}); diff --git a/libcore/node_modules/browserify/test/multi_require/a.js b/libcore/node_modules/browserify/test/multi_require/a.js new file mode 100644 index 0000000..18dea67 --- /dev/null +++ b/libcore/node_modules/browserify/test/multi_require/a.js @@ -0,0 +1,3 @@ +module.exports = function() { + return 'a'; +} diff --git a/libcore/node_modules/browserify/test/multi_require/main.js b/libcore/node_modules/browserify/test/multi_require/main.js new file mode 100644 index 0000000..6f548ec --- /dev/null +++ b/libcore/node_modules/browserify/test/multi_require/main.js @@ -0,0 +1,4 @@ +var localA = require('./a.js'); +var globalA = require('a'); + +t.equal(localA, globalA); diff --git a/libcore/node_modules/browserify/test/multi_symlink.js b/libcore/node_modules/browserify/test/multi_symlink.js new file mode 100644 index 0000000..08a5b1d --- /dev/null +++ b/libcore/node_modules/browserify/test/multi_symlink.js @@ -0,0 +1,13 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; + +test('multiple symlink execution', { skip: process.platform === 'win32' }, function (t) { + t.plan(1); + var b = browserify(__dirname + '/multi_symlink/main.js'); + b.bundle(function (err, src) { + var c = { console: { log: log } }; + vm.runInNewContext(src, c); + function log (msg) { t.equal(msg, 'X') } + }); +}); diff --git a/libcore/node_modules/browserify/test/multi_symlink/main.js b/libcore/node_modules/browserify/test/multi_symlink/main.js new file mode 100644 index 0000000..0f904dc --- /dev/null +++ b/libcore/node_modules/browserify/test/multi_symlink/main.js @@ -0,0 +1,2 @@ +require('./x.js'); +require('./y.js'); diff --git a/libcore/node_modules/browserify/test/multi_symlink/x.js b/libcore/node_modules/browserify/test/multi_symlink/x.js new file mode 100644 index 0000000..e894542 --- /dev/null +++ b/libcore/node_modules/browserify/test/multi_symlink/x.js @@ -0,0 +1 @@ +console.log('X'); diff --git a/libcore/node_modules/browserify/test/no_builtins.js b/libcore/node_modules/browserify/test/no_builtins.js new file mode 100644 index 0000000..4a25c93 --- /dev/null +++ b/libcore/node_modules/browserify/test/no_builtins.js @@ -0,0 +1,66 @@ +var browserify = require('../'); +var test = require('tap').test; +var path = require('path'); +var vm = require('vm'); + +test('builtins false', function (t) { + t.plan(1); + + var file = __dirname + '/no_builtins/main.js'; + var b = browserify({ + entries: [ file ], + commondir: false, + builtins: false + }); + b.bundle(function (err, src) { + var c = { + console: { log: function (msg) { + t.equal(msg, 'beep boop\n'); + } }, + require: require, + __dirname: process.cwd() + }; + vm.runInNewContext(src, c); + }); +}); + +test('builtins []', function (t) { + t.plan(1); + var b = browserify({ + entries: [ __dirname + '/no_builtins/main.js' ], + commondir: false, + builtins: [] + }); + b.bundle(function (err, src) { + var c = { + console: { log: function (msg) { + t.equal(msg, 'beep boop\n'); + } }, + require: require + }; + vm.runInNewContext(src, c); + }); +}); + +test('builtins object', function (t) { + t.plan(2); + var b = browserify({ + entries: [ __dirname + '/no_builtins/main.js' ], + commondir: false, + builtins: { + fs: require.resolve('./no_builtins/extra/fs.js'), + tls: require.resolve('./no_builtins/extra/tls.js') + } + }); + var expected = [ + 'WRITE CODE EVERY DAY', + 'WHATEVER' + ]; + b.bundle(function (err, src) { + var c = { console: { log: log }, require: require }; + function log (msg) { + t.equal(msg, expected.shift()); + } + vm.runInNewContext(src, c); + }); +}); diff --git a/libcore/node_modules/browserify/test/no_builtins/extra/fs.js b/libcore/node_modules/browserify/test/no_builtins/extra/fs.js new file mode 100644 index 0000000..b8bdd44 --- /dev/null +++ b/libcore/node_modules/browserify/test/no_builtins/extra/fs.js @@ -0,0 +1 @@ +exports.readFileSync = function () { return 'WHATEVER' }; diff --git a/libcore/node_modules/browserify/test/no_builtins/extra/tls.js b/libcore/node_modules/browserify/test/no_builtins/extra/tls.js new file mode 100644 index 0000000..ceea2a6 --- /dev/null +++ b/libcore/node_modules/browserify/test/no_builtins/extra/tls.js @@ -0,0 +1 @@ +console.log('WRITE CODE EVERY DAY'); diff --git a/libcore/node_modules/browserify/test/no_builtins/main.js b/libcore/node_modules/browserify/test/no_builtins/main.js new file mode 100644 index 0000000..f2dadc6 --- /dev/null +++ b/libcore/node_modules/browserify/test/no_builtins/main.js @@ -0,0 +1,4 @@ +var fs = require('fs'); +var tls = require('tls'); + +console.log(fs.readFileSync(__dirname + '/x.txt', 'utf8')); diff --git a/libcore/node_modules/browserify/test/no_builtins/x.txt b/libcore/node_modules/browserify/test/no_builtins/x.txt new file mode 100644 index 0000000..fae06e3 --- /dev/null +++ b/libcore/node_modules/browserify/test/no_builtins/x.txt @@ -0,0 +1 @@ +beep boop diff --git a/libcore/node_modules/browserify/test/noparse.js b/libcore/node_modules/browserify/test/noparse.js new file mode 100644 index 0000000..ddb024d --- /dev/null +++ b/libcore/node_modules/browserify/test/noparse.js @@ -0,0 +1,31 @@ +var browserify = require('../'); +var test = require('tap').test; +var path = require('path'); + +test('noParse array', function (t) { + process.chdir(__dirname); + + t.plan(2); + + var actual = []; + var expected = [ + 'noparse/a.js', + 'noparse/b.js', + 'noparse/dir1/1.js', + 'noparse/node_modules/robot/main.js' + ].map(function (x) {return path.resolve(x);}).sort(); + + var b = browserify({ + entries: [ __dirname + '/noparse/a.js' ], + noParse: [ + path.join(__dirname, 'noparse/dir1/1.js'), + path.join(__dirname, 'noparse/node_modules/robot/main.js') + ] + }); + b.on('dep', function(dep) { actual.push(dep.file); }); + b.bundle(function (err, src) { + actual.sort(); + t.ifError(err); + t.deepEqual(actual, expected); + }); +}); diff --git a/libcore/node_modules/browserify/test/noparse/a.js b/libcore/node_modules/browserify/test/noparse/a.js new file mode 100644 index 0000000..076812a --- /dev/null +++ b/libcore/node_modules/browserify/test/noparse/a.js @@ -0,0 +1,4 @@ +module.exports = { + a: true, + b: require('./b') +}; diff --git a/libcore/node_modules/browserify/test/noparse/b.js b/libcore/node_modules/browserify/test/noparse/b.js new file mode 100644 index 0000000..de0ba55 --- /dev/null +++ b/libcore/node_modules/browserify/test/noparse/b.js @@ -0,0 +1,5 @@ +module.exports = { + b: true, + 1: require('./dir1/1'), + robot: require('robot') +}; diff --git a/libcore/node_modules/browserify/test/noparse/dir1/1.js b/libcore/node_modules/browserify/test/noparse/dir1/1.js new file mode 100644 index 0000000..960968b --- /dev/null +++ b/libcore/node_modules/browserify/test/noparse/dir1/1.js @@ -0,0 +1,4 @@ +module.exports = { + 1: true, + 2: require('./dir2/2') +}; diff --git a/libcore/node_modules/browserify/test/noparse/dir1/dir2/2.js b/libcore/node_modules/browserify/test/noparse/dir1/dir2/2.js new file mode 100644 index 0000000..ef4ba19 --- /dev/null +++ b/libcore/node_modules/browserify/test/noparse/dir1/dir2/2.js @@ -0,0 +1,3 @@ +module.exports = { + 2: true +}; diff --git a/libcore/node_modules/browserify/test/pack.js b/libcore/node_modules/browserify/test/pack.js new file mode 100644 index 0000000..68a6e2c --- /dev/null +++ b/libcore/node_modules/browserify/test/pack.js @@ -0,0 +1,33 @@ +var browserify = require('../'); +var vm = require('vm'); +var through = require('through2'); +var test = require('tap').test; + +var fs = require('fs'); +var sources = { + 1: fs.readFileSync(__dirname + '/entry/main.js', 'utf8'), + 2: fs.readFileSync(__dirname + '/entry/one.js', 'utf8'), + 3: fs.readFileSync(__dirname + '/entry/two.js', 'utf8') +}; + +var deps = { + 1: { './two': 3, './one': 2 }, + 2: {}, + 3: {} +}; + +test('custom packer', function (t) { + t.plan(7); + + var b = browserify(__dirname + '/entry/main.js'); + b.pipeline.get('pack').splice(0,1, through.obj(function (row, enc, next) { + t.equal(sources[row.id], row.source); + t.deepEqual(deps[row.id], row.deps); + this.push(row.id + '\n'); + next(); + })); + b.pipeline.get('wrap').splice(0); + b.bundle(function (err, src) { + t.equal(src.toString('utf8'), '1\n2\n3\n'); + }); +}); diff --git a/libcore/node_modules/browserify/test/paths.js b/libcore/node_modules/browserify/test/paths.js new file mode 100644 index 0000000..c3d5728 --- /dev/null +++ b/libcore/node_modules/browserify/test/paths.js @@ -0,0 +1,32 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; + +test('$NODE_PATHS', function (t) { + t.plan(3); + var paths = [ __dirname + '/paths/x', __dirname + '/paths/y' ]; + var sep = /^win/i.test(process.platform) ? ';' : ':'; + + process.env.NODE_PATH = (process.env.NODE_PATHS || '') + .split(sep).concat(paths).join(sep) + ; + + var b = browserify(__dirname + '/paths/main.js'); + b.bundle(function (err, src) { + if (err) t.fail(err); + vm.runInNewContext(src, { t: t }); + }); +}); + +test('opts.paths', function (t) { + t.plan(3); + + var b = browserify({ + paths: [ __dirname + '/paths/x', __dirname + '/paths/y' ], + entries: __dirname + '/paths/main.js' + }); + b.bundle(function (err, src) { + if (err) t.fail(err); + vm.runInNewContext(src, { t: t }); + }); +}); diff --git a/libcore/node_modules/browserify/test/paths/main.js b/libcore/node_modules/browserify/test/paths/main.js new file mode 100644 index 0000000..ec0d8a1 --- /dev/null +++ b/libcore/node_modules/browserify/test/paths/main.js @@ -0,0 +1,3 @@ +t.equal(require('aaa'), 'AX'); +t.equal(require('bbb'), 'BY'); +t.equal(require('ccc'), 'CX'); diff --git a/libcore/node_modules/browserify/test/paths/x/aaa/index.js b/libcore/node_modules/browserify/test/paths/x/aaa/index.js new file mode 100644 index 0000000..b76ce87 --- /dev/null +++ b/libcore/node_modules/browserify/test/paths/x/aaa/index.js @@ -0,0 +1 @@ +module.exports = 'AX' diff --git a/libcore/node_modules/browserify/test/paths/x/ccc/index.js b/libcore/node_modules/browserify/test/paths/x/ccc/index.js new file mode 100644 index 0000000..882058e --- /dev/null +++ b/libcore/node_modules/browserify/test/paths/x/ccc/index.js @@ -0,0 +1 @@ +module.exports = 'CX' diff --git a/libcore/node_modules/browserify/test/paths/y/bbb/index.js b/libcore/node_modules/browserify/test/paths/y/bbb/index.js new file mode 100644 index 0000000..5dbca44 --- /dev/null +++ b/libcore/node_modules/browserify/test/paths/y/bbb/index.js @@ -0,0 +1 @@ +module.exports = 'BY' diff --git a/libcore/node_modules/browserify/test/paths/y/ccc/index.js b/libcore/node_modules/browserify/test/paths/y/ccc/index.js new file mode 100644 index 0000000..d0043d1 --- /dev/null +++ b/libcore/node_modules/browserify/test/paths/y/ccc/index.js @@ -0,0 +1 @@ +module.exports = 'CY' diff --git a/libcore/node_modules/browserify/test/paths_transform.js b/libcore/node_modules/browserify/test/paths_transform.js new file mode 100644 index 0000000..bd06070 --- /dev/null +++ b/libcore/node_modules/browserify/test/paths_transform.js @@ -0,0 +1,76 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; + +function ensureTransform(t, buf) { + var srcAsString = (buf||'').toString('utf-8'), + containsAX = srcAsString.indexOf('AX') > -1, + containsAZ = srcAsString.indexOf('AZ') > -1; + t.notOk(containsAX,"should not contain AX's"); + t.ok(containsAZ,"should contain AZ's"); +} + +test('absolute paths with transform property', function (t) { + t.plan(6); + + var b = browserify({ + transform: ['tr'], + basedir: __dirname, + paths: [ __dirname + '/paths/x', __dirname + '/paths/y' ], + entries: __dirname + '/paths/main.js' + }); + b.bundle(function (err, src) { + t.ifError(err); + ensureTransform(t,src); + vm.runInNewContext(src, { t: t }); + }); +}); + +test('relative paths with transform property', function (t) { + t.plan(6); + + var b = browserify({ + transform: ['tr'], + basedir: __dirname, + paths: [ './paths/x', './paths/y' ], + entries: __dirname + '/paths/main.js' + }); + b.bundle(function (err, src) { + t.ifError(err); + ensureTransform(t,src); + vm.runInNewContext(src, { t: t }); + }); +}); + + +test('absolute paths with transform method', function (t) { + t.plan(6); + + var b = browserify({ + basedir: __dirname, + paths: [ __dirname + '/paths/x', __dirname + '/paths/y' ], + entries: __dirname + '/paths/main.js' + }); + b.transform('tr'); + b.bundle(function (err, src) { + t.ifError(err); + ensureTransform(t,src); + vm.runInNewContext(src, { t: t }); + }); +}); + + +test('relative paths with transform method', function (t) { + t.plan(6); + var b = browserify({ + basedir: __dirname, + paths: ['./paths/x', './paths/y' ], + entries: __dirname + '/paths/main.js' + }); + b.transform('tr'); + b.bundle(function (err, src) { + t.ifError(err); + ensureTransform(t,src); + vm.runInNewContext(src, { t: t }); + }); +}); diff --git a/libcore/node_modules/browserify/test/pipeline_deps.js b/libcore/node_modules/browserify/test/pipeline_deps.js new file mode 100644 index 0000000..8f847a7 --- /dev/null +++ b/libcore/node_modules/browserify/test/pipeline_deps.js @@ -0,0 +1,22 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; +var through = require('through2'); + +test('deps pipeline', function (t) { + t.plan(1); + + var b = browserify(__dirname + '/pipeline_deps/main.js'); + b.pipeline.get('deps').push(through.obj(function (row, enc, next) { + row.source = row.source.replace(/111/g, '11111'); + this.push(row); + next(); + })); + + b.bundle(function (err, src) { + Function([ 'console' ], src)({ log: log }); + function log (msg) { + t.equal(msg, 'main: 56055'); + } + }); +}); diff --git a/libcore/node_modules/browserify/test/pipeline_deps/bar.js b/libcore/node_modules/browserify/test/pipeline_deps/bar.js new file mode 100644 index 0000000..c57fa53 --- /dev/null +++ b/libcore/node_modules/browserify/test/pipeline_deps/bar.js @@ -0,0 +1,3 @@ +module.exports = function (n) { + return n * 100; +}; diff --git a/libcore/node_modules/browserify/test/pipeline_deps/foo.js b/libcore/node_modules/browserify/test/pipeline_deps/foo.js new file mode 100644 index 0000000..c62e638 --- /dev/null +++ b/libcore/node_modules/browserify/test/pipeline_deps/foo.js @@ -0,0 +1,5 @@ +var bar = require('./bar'); + +module.exports = function (n) { + return n * 111 + bar(n); +}; diff --git a/libcore/node_modules/browserify/test/pipeline_deps/main.js b/libcore/node_modules/browserify/test/pipeline_deps/main.js new file mode 100644 index 0000000..8c71d79 --- /dev/null +++ b/libcore/node_modules/browserify/test/pipeline_deps/main.js @@ -0,0 +1,2 @@ +var foo = require('./foo'); +console.log('main: ' + foo(5)); diff --git a/libcore/node_modules/browserify/test/pipeline_deps/xyz.js b/libcore/node_modules/browserify/test/pipeline_deps/xyz.js new file mode 100644 index 0000000..dff6877 --- /dev/null +++ b/libcore/node_modules/browserify/test/pipeline_deps/xyz.js @@ -0,0 +1,2 @@ +var foo = require('./foo'); +console.log('xyz: ' + foo(6)); diff --git a/libcore/node_modules/browserify/test/pkg.js b/libcore/node_modules/browserify/test/pkg.js new file mode 100644 index 0000000..753e6d8 --- /dev/null +++ b/libcore/node_modules/browserify/test/pkg.js @@ -0,0 +1,20 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; +var path = require('path'); + +var pkg = require('./pkg/package.json'); +pkg.__dirname = path.join(__dirname, 'pkg'); + +test('package', function (t) { + t.plan(2); + + var b = browserify(__dirname + '/pkg/main.js'); + b.on('package', function (pkg_) { + t.deepEqual(pkg_, pkg); + }); + + b.bundle(function (err) { + t.ifError(err); + }); +}); diff --git a/libcore/node_modules/browserify/test/pkg/main.js b/libcore/node_modules/browserify/test/pkg/main.js new file mode 100644 index 0000000..07a8fbf --- /dev/null +++ b/libcore/node_modules/browserify/test/pkg/main.js @@ -0,0 +1 @@ +console.log(555) diff --git a/libcore/node_modules/browserify/test/pkg/package.json b/libcore/node_modules/browserify/test/pkg/package.json new file mode 100644 index 0000000..cc806a7 --- /dev/null +++ b/libcore/node_modules/browserify/test/pkg/package.json @@ -0,0 +1 @@ +{ "beep": "boop" } diff --git a/libcore/node_modules/browserify/test/pkg_event.js b/libcore/node_modules/browserify/test/pkg_event.js new file mode 100644 index 0000000..77ada96 --- /dev/null +++ b/libcore/node_modules/browserify/test/pkg_event.js @@ -0,0 +1,31 @@ +var browserify = require('../'); +var path = require('path'); +var vm = require('vm'); +var test = require('tap').test; + +var expected = [ + readpkg('pkg_event'), + readpkg('pkg_event/node_modules/aaa'), + readpkg('pkg_event/node_modules/aaa/lib') +]; + +test('package event', function (t) { + t.plan(2 + expected.length); + + var b = browserify(__dirname + '/pkg_event/main.js'); + b.on('package', function (pkg) { + t.deepEqual(pkg, expected.shift()); + }); + + b.bundle(function (err, src) { + t.ifError(err); + vm.runInNewContext(src, { console: { log: log } }); + function log (msg) { t.equal(msg, 555) } + }); +}); + +function readpkg (dir) { + var pkg = require(path.join(__dirname, dir, 'package.json')); + pkg.__dirname = path.join(__dirname, dir); + return pkg; +} diff --git a/libcore/node_modules/browserify/test/pkg_event/main.js b/libcore/node_modules/browserify/test/pkg_event/main.js new file mode 100644 index 0000000..bef366a --- /dev/null +++ b/libcore/node_modules/browserify/test/pkg_event/main.js @@ -0,0 +1 @@ +console.log(require('aaa')) diff --git a/libcore/node_modules/browserify/test/pkg_event/package.json b/libcore/node_modules/browserify/test/pkg_event/package.json new file mode 100644 index 0000000..21d82d8 --- /dev/null +++ b/libcore/node_modules/browserify/test/pkg_event/package.json @@ -0,0 +1,3 @@ +{ + "name": "pkg_event" +} diff --git a/libcore/node_modules/browserify/test/plugin.js b/libcore/node_modules/browserify/test/plugin.js new file mode 100644 index 0000000..be143a3 --- /dev/null +++ b/libcore/node_modules/browserify/test/plugin.js @@ -0,0 +1,28 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; + +test('plugin fn', function (t) { + t.plan(2); + + var b = browserify(__dirname + '/plugin/main.js', { basedir: __dirname }); + b.plugin(function (b_) { + t.equal(b, b_); + }); + + b.bundle(function (err, src) { + t.ifError(err); + }); +}); + +test('plugin module', function (t) { + t.plan(2); + + var b = browserify(__dirname + '/plugin/main.js', { basedir: __dirname }); + b.plugin('plugin-foo', { msg: 'beep boop' }); + + b.bundle(function (err, src) { + t.ifError(err); + t.equal(src.toString('utf8'), 'beep boop'); + }); +}); diff --git a/libcore/node_modules/browserify/test/plugin/main.js b/libcore/node_modules/browserify/test/plugin/main.js new file mode 100644 index 0000000..3e842e7 --- /dev/null +++ b/libcore/node_modules/browserify/test/plugin/main.js @@ -0,0 +1 @@ +module.exports = 555 diff --git a/libcore/node_modules/browserify/test/preserve-symlinks.js b/libcore/node_modules/browserify/test/preserve-symlinks.js new file mode 100644 index 0000000..83940dd --- /dev/null +++ b/libcore/node_modules/browserify/test/preserve-symlinks.js @@ -0,0 +1,27 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; + +test('optionally preserves symlinks', { skip: process.platform === 'win32' }, function (t) { + t.plan(2); + + var b = browserify(__dirname + '/preserve_symlinks/a/index.js', {preserveSymlinks: true}); + b.bundle(function (err, buf) { + t.ifError(err); + t.ok(buf); + var src = buf.toString('utf8'); + vm.runInNewContext(src, {}); + }); +}); + +test('always resolve entry point symlink', { skip: process.platform === 'win32' }, function (t) { + t.plan(2); + + var b = browserify(__dirname + '/preserve_symlinks/linked-entry.js', {preserveSymlinks: true}); + b.bundle(function (err, buf) { + t.ifError(err); + t.ok(buf); + var src = buf.toString('utf8'); + vm.runInNewContext(src, {}); + }); +}) diff --git a/libcore/node_modules/browserify/test/preserve_symlinks/a/index.js b/libcore/node_modules/browserify/test/preserve_symlinks/a/index.js new file mode 100644 index 0000000..5f6937c --- /dev/null +++ b/libcore/node_modules/browserify/test/preserve_symlinks/a/index.js @@ -0,0 +1 @@ +require('b'); diff --git a/libcore/node_modules/browserify/test/preserve_symlinks/b/index.js b/libcore/node_modules/browserify/test/preserve_symlinks/b/index.js new file mode 100644 index 0000000..a56a508 --- /dev/null +++ b/libcore/node_modules/browserify/test/preserve_symlinks/b/index.js @@ -0,0 +1 @@ +require('c'); diff --git a/libcore/node_modules/browserify/test/process.js b/libcore/node_modules/browserify/test/process.js new file mode 100644 index 0000000..83ffa14 --- /dev/null +++ b/libcore/node_modules/browserify/test/process.js @@ -0,0 +1,21 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; + +test('implicit process global', function (t) { + t.plan(2); + + var b = browserify(__dirname + '/process/main.js'); + b.bundle(function (err, src) { + var c = { + done : function (one, two) { + t.equal(one, 1); + t.equal(two, 2); + t.end(); + }, + setTimeout: setTimeout, + clearTimeout: clearTimeout + }; + vm.runInNewContext(src, c); + }); +}); diff --git a/libcore/node_modules/browserify/test/process/main.js b/libcore/node_modules/browserify/test/process/main.js new file mode 100644 index 0000000..0895579 --- /dev/null +++ b/libcore/node_modules/browserify/test/process/main.js @@ -0,0 +1,3 @@ +process.nextTick(function () { + done(require('./one'), require('./two')); +}); diff --git a/libcore/node_modules/browserify/test/process/one.js b/libcore/node_modules/browserify/test/process/one.js new file mode 100644 index 0000000..bd816ea --- /dev/null +++ b/libcore/node_modules/browserify/test/process/one.js @@ -0,0 +1 @@ +module.exports = 1; diff --git a/libcore/node_modules/browserify/test/process/two.js b/libcore/node_modules/browserify/test/process/two.js new file mode 100644 index 0000000..4bbffde --- /dev/null +++ b/libcore/node_modules/browserify/test/process/two.js @@ -0,0 +1 @@ +module.exports = 2; diff --git a/libcore/node_modules/browserify/test/quotes.js b/libcore/node_modules/browserify/test/quotes.js new file mode 100644 index 0000000..4c82b7e --- /dev/null +++ b/libcore/node_modules/browserify/test/quotes.js @@ -0,0 +1,38 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; + +var hasTemplateLiterals = require('has-template-literals')(); + +test('quotes', function (t) { + t.plan(2); + + var b = browserify(__dirname + '/quotes/main.js'); + b.bundle(function (err, src) { + var c = { + done : function (single, double) { + t.equal(single, 'success', 'single quotes'); + t.equal(double, 'success', 'double quotes'); + t.end(); + } + }; + vm.runInNewContext(src, c); + }); +}); + +test('interpolation literals', { skip: !hasTemplateLiterals }, function (t) { + t.plan(3); + + var b = browserify(__dirname + '/quotes/backtick.js'); + b.bundle(function (err, src) { + var c = { + done : function (single, double, backtick) { + t.equal(single, 'success', 'single quotes'); + t.equal(double, 'success', 'double quotes'); + t.equal(backtick, 'success', 'backtick quotes'); + t.end(); + } + }; + vm.runInNewContext(src, c); + }); +}); diff --git a/libcore/node_modules/browserify/test/quotes/backtick.js b/libcore/node_modules/browserify/test/quotes/backtick.js new file mode 100644 index 0000000..7dd85f1 --- /dev/null +++ b/libcore/node_modules/browserify/test/quotes/backtick.js @@ -0,0 +1 @@ +done(require('./one.js'), require("./two.js"), require(`./three.js`)); diff --git a/libcore/node_modules/browserify/test/quotes/main.js b/libcore/node_modules/browserify/test/quotes/main.js new file mode 100644 index 0000000..327b582 --- /dev/null +++ b/libcore/node_modules/browserify/test/quotes/main.js @@ -0,0 +1 @@ +done(require('./one.js'), require("./two.js")); diff --git a/libcore/node_modules/browserify/test/quotes/one.js b/libcore/node_modules/browserify/test/quotes/one.js new file mode 100644 index 0000000..52b5cbb --- /dev/null +++ b/libcore/node_modules/browserify/test/quotes/one.js @@ -0,0 +1 @@ +module.exports = 'success'; diff --git a/libcore/node_modules/browserify/test/quotes/three.js b/libcore/node_modules/browserify/test/quotes/three.js new file mode 100644 index 0000000..52b5cbb --- /dev/null +++ b/libcore/node_modules/browserify/test/quotes/three.js @@ -0,0 +1 @@ +module.exports = 'success'; diff --git a/libcore/node_modules/browserify/test/quotes/two.js b/libcore/node_modules/browserify/test/quotes/two.js new file mode 100644 index 0000000..52b5cbb --- /dev/null +++ b/libcore/node_modules/browserify/test/quotes/two.js @@ -0,0 +1 @@ +module.exports = 'success'; diff --git a/libcore/node_modules/browserify/test/relative_dedupe.js b/libcore/node_modules/browserify/test/relative_dedupe.js new file mode 100644 index 0000000..5a4a252 --- /dev/null +++ b/libcore/node_modules/browserify/test/relative_dedupe.js @@ -0,0 +1,17 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; + +test('relative dedupe', function (t) { + var expected = [ 'a a', 'a b', 'b a', 'b b' ]; + t.plan(expected.length + 1); + + var b = browserify(__dirname + '/relative_dedupe/main.js'); + b.bundle(function (err, src) { + t.ifError(err); + var c = { console: { log: log } }; + vm.runInNewContext(src, c); + }); + + function log (msg) { t.equal(msg, expected.shift()) } +}); diff --git a/libcore/node_modules/browserify/test/relative_dedupe/a/a.js b/libcore/node_modules/browserify/test/relative_dedupe/a/a.js new file mode 100644 index 0000000..fd6bd94 --- /dev/null +++ b/libcore/node_modules/browserify/test/relative_dedupe/a/a.js @@ -0,0 +1,3 @@ +module.exports = function() { + console.log("a a") +}; diff --git a/libcore/node_modules/browserify/test/relative_dedupe/a/b.js b/libcore/node_modules/browserify/test/relative_dedupe/a/b.js new file mode 100644 index 0000000..3bdfe50 --- /dev/null +++ b/libcore/node_modules/browserify/test/relative_dedupe/a/b.js @@ -0,0 +1,3 @@ +module.exports = function() { + console.log("a b") +}; diff --git a/libcore/node_modules/browserify/test/relative_dedupe/a/index.js b/libcore/node_modules/browserify/test/relative_dedupe/a/index.js new file mode 100644 index 0000000..5002ffc --- /dev/null +++ b/libcore/node_modules/browserify/test/relative_dedupe/a/index.js @@ -0,0 +1,4 @@ +module.exports = { + a: require("./a"), + b: require("./b") +}; diff --git a/libcore/node_modules/browserify/test/relative_dedupe/b/a.js b/libcore/node_modules/browserify/test/relative_dedupe/b/a.js new file mode 100644 index 0000000..eb66e54 --- /dev/null +++ b/libcore/node_modules/browserify/test/relative_dedupe/b/a.js @@ -0,0 +1,3 @@ +module.exports = function() { + console.log("b a") +}; diff --git a/libcore/node_modules/browserify/test/relative_dedupe/b/b.js b/libcore/node_modules/browserify/test/relative_dedupe/b/b.js new file mode 100644 index 0000000..94faa62 --- /dev/null +++ b/libcore/node_modules/browserify/test/relative_dedupe/b/b.js @@ -0,0 +1,3 @@ +module.exports = function() { + console.log("b b") +}; diff --git a/libcore/node_modules/browserify/test/relative_dedupe/b/index.js b/libcore/node_modules/browserify/test/relative_dedupe/b/index.js new file mode 100644 index 0000000..5002ffc --- /dev/null +++ b/libcore/node_modules/browserify/test/relative_dedupe/b/index.js @@ -0,0 +1,4 @@ +module.exports = { + a: require("./a"), + b: require("./b") +}; diff --git a/libcore/node_modules/browserify/test/relative_dedupe/index.js b/libcore/node_modules/browserify/test/relative_dedupe/index.js new file mode 100644 index 0000000..69ce41b --- /dev/null +++ b/libcore/node_modules/browserify/test/relative_dedupe/index.js @@ -0,0 +1,4 @@ +module.exports = { + a: require("./a"), + b: require("./b") +}; diff --git a/libcore/node_modules/browserify/test/relative_dedupe/main.js b/libcore/node_modules/browserify/test/relative_dedupe/main.js new file mode 100644 index 0000000..deb9370 --- /dev/null +++ b/libcore/node_modules/browserify/test/relative_dedupe/main.js @@ -0,0 +1,5 @@ +var ix = require('./'); +ix.a.a(); +ix.a.b(); +ix.b.a(); +ix.b.b(); diff --git a/libcore/node_modules/browserify/test/require_cache.js b/libcore/node_modules/browserify/test/require_cache.js new file mode 100644 index 0000000..871e055 --- /dev/null +++ b/libcore/node_modules/browserify/test/require_cache.js @@ -0,0 +1,19 @@ +var vm = require('vm'); +var browserify = require('../'); +var test = require('tap').test; + +test('cached require results', function (t) { + t.plan(1); + + var b = browserify(); + b.require('seq'); + b.bundle(function (err, src) { + var c = {}; + vm.runInNewContext(src, c); + + var seq0 = c.require('seq'); + var seq1 = c.require('seq'); + + t.ok(seq0 === seq1); + }); +}); diff --git a/libcore/node_modules/browserify/test/require_expose.js b/libcore/node_modules/browserify/test/require_expose.js new file mode 100644 index 0000000..60f9383 --- /dev/null +++ b/libcore/node_modules/browserify/test/require_expose.js @@ -0,0 +1,53 @@ +var browserify = require('../'); +var test = require('tap').test; +var vm = require('vm'); + +test('require expose external module', function (t) { + t.plan(2); + + var b = browserify({ basedir: __dirname }); + b.require('beep', { expose: 'bip' }); + b.bundle(function (err, src) { + t.ifError(err); + var c = { }; + vm.runInNewContext(src, c); + t.equal(c.require('bip'), 'boop'); + }) +}); + +test('renaming builtin', function (t) { + t.plan(2); + + var b = browserify({ basedir: __dirname }); + b.require('os', { expose: 'bone' }); + b.bundle(function (err, src) { + t.ifError(err); + var c = { }; + vm.runInNewContext(src, c); + t.equal(c.require('bone').platform(), 'browser'); + }) +}); + +test('exposed modules do not leak across bundles', function (t) { + var bundle1, bundle2; + + bundle1 = browserify(); + bundle1.add(__dirname + '/require_expose/main.js'); + bundle1.require(__dirname + '/require_expose/some_dep.js', { expose: 'foo' }); + + bundle1.bundle(function (err, src) { + if (err) t.fail(err); + + var c = {}; + vm.runInNewContext(src, c); + t.equal(c.foo, 'some_dep'); + + bundle2 = browserify(); + bundle2.add(__dirname + '/require_expose/main.js'); + + bundle2.bundle(function (err) { + t.ok(err && err.message.match(/Cannot find module 'foo'/), 'should fail with missing module'); + t.end(); + }); + }); +}); diff --git a/libcore/node_modules/browserify/test/require_expose/main.js b/libcore/node_modules/browserify/test/require_expose/main.js new file mode 100644 index 0000000..f99908f --- /dev/null +++ b/libcore/node_modules/browserify/test/require_expose/main.js @@ -0,0 +1 @@ +foo = require('foo'); diff --git a/libcore/node_modules/browserify/test/require_expose/some_dep.js b/libcore/node_modules/browserify/test/require_expose/some_dep.js new file mode 100644 index 0000000..353c90d --- /dev/null +++ b/libcore/node_modules/browserify/test/require_expose/some_dep.js @@ -0,0 +1 @@ +module.exports = 'some_dep'; diff --git a/libcore/node_modules/browserify/test/reset.js b/libcore/node_modules/browserify/test/reset.js new file mode 100644 index 0000000..dad18b3 --- /dev/null +++ b/libcore/node_modules/browserify/test/reset.js @@ -0,0 +1,31 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; + +test('reset', function (t) { + t.plan(4); + + var b = browserify(); + b.require('path'); + b.bundle(function (err, src) { + check(err, src); + b.bundle(function (err, src) { + check(err, src); + }); + }); + + function check (err, src) { + t.ifError(err); + var c = { + setTimeout : setTimeout, + clearTimeout : clearTimeout, + console : console + }; + vm.runInNewContext(src, c); + + t.equal( + c.require('path').join('/a', 'b'), + '/a/b' + ); + } +}); diff --git a/libcore/node_modules/browserify/test/resolve_exposed.js b/libcore/node_modules/browserify/test/resolve_exposed.js new file mode 100644 index 0000000..1dbea42 --- /dev/null +++ b/libcore/node_modules/browserify/test/resolve_exposed.js @@ -0,0 +1,88 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; + +test('resolve exposed files', function (t) { + t.plan(2); + + var b = browserify(__dirname + '/resolve_exposed/main.js', { + basedir: __dirname + '/resolve_exposed' + }); + b.require('./x.js', { expose: 'xyz' }); + b.bundle(function (err, src) { + t.ifError(err); + var c = { console: { log: log } }; + vm.runInNewContext(src, c); + function log (x) { + t.equal(x, 333); + } + }); +}); + +test('resolve exposed files without extension', function (t) { + t.plan(2); + + var b = browserify(__dirname + '/resolve_exposed/main.js', { + basedir: __dirname + '/resolve_exposed' + }); + b.require('./x', {expose: 'xyz'}); + b.bundle(function (err, src) { + t.ifError(err); + var c = {console: {log: log}}; + vm.runInNewContext(src, c); + function log(x) { + t.equal(x, 333); + } + }); +}); + +test('resolve exposed directories', function (t) { + t.plan(2); + + var b = browserify(__dirname + '/resolve_exposed/main.js', { + basedir: __dirname + '/resolve_exposed' + }); + b.require('./y', {expose: 'xyz'}); + b.bundle(function (err, src) { + t.ifError(err); + var c = {console: {log: log}}; + vm.runInNewContext(src, c); + function log(x) { + t.equal(x, 555); + } + }); +}); + +test('resolve exposed index from directories', function (t) { + t.plan(2); + + var b = browserify(__dirname + '/resolve_exposed/main.js', { + basedir: __dirname + '/resolve_exposed' + }); + b.require('./y/index', {expose: 'xyz'}); + b.bundle(function (err, src) { + t.ifError(err); + var c = {console: {log: log}}; + vm.runInNewContext(src, c); + function log(x) { + t.equal(x, 555); + } + }); +}); + +test('resolve exposed index.js from directories', function (t) { + t.plan(2); + + var b = browserify(__dirname + '/resolve_exposed/main.js', { + basedir: __dirname + '/resolve_exposed' + }); + b.require('./y/index.js', {expose: 'xyz'}); + b.bundle(function (err, src) { + t.ifError(err); + var c = {console: {log: log}}; + vm.runInNewContext(src, c); + function log(x) { + t.equal(x, 555); + } + }); +}); diff --git a/libcore/node_modules/browserify/test/resolve_exposed/main.js b/libcore/node_modules/browserify/test/resolve_exposed/main.js new file mode 100644 index 0000000..08a137d --- /dev/null +++ b/libcore/node_modules/browserify/test/resolve_exposed/main.js @@ -0,0 +1,2 @@ +var xyz = require('xyz'); +console.log(xyz * 111); diff --git a/libcore/node_modules/browserify/test/resolve_exposed/x.js b/libcore/node_modules/browserify/test/resolve_exposed/x.js new file mode 100644 index 0000000..6887896 --- /dev/null +++ b/libcore/node_modules/browserify/test/resolve_exposed/x.js @@ -0,0 +1 @@ +module.exports = 3 diff --git a/libcore/node_modules/browserify/test/resolve_exposed/y/index.js b/libcore/node_modules/browserify/test/resolve_exposed/y/index.js new file mode 100644 index 0000000..caedade --- /dev/null +++ b/libcore/node_modules/browserify/test/resolve_exposed/y/index.js @@ -0,0 +1 @@ +module.exports = 5 diff --git a/libcore/node_modules/browserify/test/retarget.js b/libcore/node_modules/browserify/test/retarget.js new file mode 100644 index 0000000..7670bc0 --- /dev/null +++ b/libcore/node_modules/browserify/test/retarget.js @@ -0,0 +1,25 @@ +var test = require('tap').test; +var spawn = require('child_process').spawn; +var path = require('path'); +var vm = require('vm'); + +test('retarget with -r', function (t) { + t.plan(2); + + var ps = spawn(process.execPath, [ + path.resolve(__dirname, '../bin/cmd.js'), + '-r', 'beep' + ], { cwd: __dirname }); + var src = ''; + ps.stdout.on('data', function (buf) { src += buf }); + ps.stderr.pipe(process.stderr); + + ps.on('exit', function (code) { + t.equal(code, 0); + + var c = {}; + vm.runInNewContext(src, c); + t.equal(c.require('beep'), 'boop'); + }); + ps.stdin.end(); +}); diff --git a/libcore/node_modules/browserify/test/reverse_multi_bundle.js b/libcore/node_modules/browserify/test/reverse_multi_bundle.js new file mode 100644 index 0000000..1a7537e --- /dev/null +++ b/libcore/node_modules/browserify/test/reverse_multi_bundle.js @@ -0,0 +1,47 @@ +/** + * To be able to lazy load bundles with script loaders the loaded bundles + * must have access to modules exposed by previous bundles. + * + * In effect this is the same as adding the bundles in reverse order + **/ + +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; + +test('reverse multi bundle', function (t) { + t.plan(5); + + // Main app bundle has the main app code and the shared library code + var app = browserify([__dirname + '/reverse_multi_bundle/app.js']) + .external(__dirname + '/reverse_multi_bundle/lazy.js') + .require(__dirname + '/reverse_multi_bundle/shared.js', { expose: true }) + .require(__dirname + '/reverse_multi_bundle/arbitrary.js', {expose: 'not/real'}); + + // Lazily loaded bundle has only its own code even it uses code from the + // shared library. + var lazy = browserify({ + filter: function (id) { + return id !== 'not/real'; + } + }) + .require(__dirname + '/reverse_multi_bundle/lazy.js', { expose: true }) + .external(__dirname + '/reverse_multi_bundle/shared.js') + .external('not/real'); + + + app.bundle(function (err, appSrc) { + if (err) throw err; + lazy.bundle(function(err, lazySrc) { + if (err) throw err; + + var src = appSrc + ';' + lazySrc; + var c = { + setTimeout: setTimeout, + clearTimeout: clearTimeout, + t: t + }; + vm.runInNewContext(src, c); + }); + }); +}); diff --git a/libcore/node_modules/browserify/test/reverse_multi_bundle/app.js b/libcore/node_modules/browserify/test/reverse_multi_bundle/app.js new file mode 100644 index 0000000..ab6b101 --- /dev/null +++ b/libcore/node_modules/browserify/test/reverse_multi_bundle/app.js @@ -0,0 +1,22 @@ + +t.equal( + require("./shared")(), 1, + "the main app bundle can already use the shared library" +); + +t.throws(function() { + require("./lazy"); +}, "lazy bundle is not executed yet so the lazy module cannot be required yet"); + +// Use setTimeout as script loader simulator as in real use case this would be +// a call to one. Now we just let the rest of the source code string we build +// to execute. +setTimeout(function() { + // After lazy bundle is executed we can require the lazy.js module + require("./lazy"); + t.equal( + require("./shared")(),3, + "lazy module was able to use shared code" + ); +}, 1); + diff --git a/libcore/node_modules/browserify/test/reverse_multi_bundle/arbitrary.js b/libcore/node_modules/browserify/test/reverse_multi_bundle/arbitrary.js new file mode 100644 index 0000000..ba7d872 --- /dev/null +++ b/libcore/node_modules/browserify/test/reverse_multi_bundle/arbitrary.js @@ -0,0 +1,6 @@ +var i = 0; +module.exports = function() { + return ++i; +}; + +// 175e62 diff --git a/libcore/node_modules/browserify/test/reverse_multi_bundle/lazy.js b/libcore/node_modules/browserify/test/reverse_multi_bundle/lazy.js new file mode 100644 index 0000000..012cdeb --- /dev/null +++ b/libcore/node_modules/browserify/test/reverse_multi_bundle/lazy.js @@ -0,0 +1,9 @@ +t.equal( + require("./shared")(),2, + "lazy.js can use the shared library" +); +t.equal( + require("not/real")(),1, + "lazy.js can use library code with arbitrary names" +); + diff --git a/libcore/node_modules/browserify/test/reverse_multi_bundle/shared.js b/libcore/node_modules/browserify/test/reverse_multi_bundle/shared.js new file mode 100644 index 0000000..6bb03fb --- /dev/null +++ b/libcore/node_modules/browserify/test/reverse_multi_bundle/shared.js @@ -0,0 +1,6 @@ +var i = 0; +module.exports = function() { + return ++i; +}; + +// 77aa70 diff --git a/libcore/node_modules/browserify/test/shared_symlink.js b/libcore/node_modules/browserify/test/shared_symlink.js new file mode 100644 index 0000000..7b37f2a --- /dev/null +++ b/libcore/node_modules/browserify/test/shared_symlink.js @@ -0,0 +1,17 @@ +// https://github.com/substack/node-browserify/issues/1325 + +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; + +test('shared symlink', { skip: process.platform === 'win32' }, function (t) { + t.plan(1); + var b = browserify(__dirname + '/shared_symlink/main.js'); + b.bundle(function (err, src) { + // does the same thing as node: crashes + t.equal(err.message, "Can't walk dependency graph: Cannot find module 'foo' " + + "from '" + __dirname + "/shared_symlink/shared/index.js'\n" + + " required by " + __dirname + "/shared_symlink/shared/index.js" + ); + }); +}); diff --git a/libcore/node_modules/browserify/test/shared_symlink/app/index.js b/libcore/node_modules/browserify/test/shared_symlink/app/index.js new file mode 100644 index 0000000..489c017 --- /dev/null +++ b/libcore/node_modules/browserify/test/shared_symlink/app/index.js @@ -0,0 +1 @@ +module.exports = require('shared') + require('foo') diff --git a/libcore/node_modules/browserify/test/shared_symlink/main.js b/libcore/node_modules/browserify/test/shared_symlink/main.js new file mode 100644 index 0000000..a13f524 --- /dev/null +++ b/libcore/node_modules/browserify/test/shared_symlink/main.js @@ -0,0 +1 @@ +console.log(require('./app')) diff --git a/libcore/node_modules/browserify/test/shared_symlink/shared/index.js b/libcore/node_modules/browserify/test/shared_symlink/shared/index.js new file mode 100644 index 0000000..1766764 --- /dev/null +++ b/libcore/node_modules/browserify/test/shared_symlink/shared/index.js @@ -0,0 +1 @@ +module.exports = require('foo') * 2 diff --git a/libcore/node_modules/browserify/test/shebang.js b/libcore/node_modules/browserify/test/shebang.js new file mode 100644 index 0000000..5965ac9 --- /dev/null +++ b/libcore/node_modules/browserify/test/shebang.js @@ -0,0 +1,11 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; + +test('files with shebangs', function (t) { + t.plan(1); + var b = browserify(__dirname + '/shebang/main.js'); + b.bundle(function (err, src) { + vm.runInNewContext(src, { t: t }); + }); +}); diff --git a/libcore/node_modules/browserify/test/shebang/foo.js b/libcore/node_modules/browserify/test/shebang/foo.js new file mode 100644 index 0000000..3ec10cd --- /dev/null +++ b/libcore/node_modules/browserify/test/shebang/foo.js @@ -0,0 +1,2 @@ +#!/blah +module.exports = 1234; diff --git a/libcore/node_modules/browserify/test/shebang/main.js b/libcore/node_modules/browserify/test/shebang/main.js new file mode 100644 index 0000000..eb41711 --- /dev/null +++ b/libcore/node_modules/browserify/test/shebang/main.js @@ -0,0 +1,4 @@ +#!/usr/bin/env node + +var foo = require('./foo'); +t.equal(foo, 1234); diff --git a/libcore/node_modules/browserify/test/spread.js b/libcore/node_modules/browserify/test/spread.js new file mode 100644 index 0000000..ba4fd37 --- /dev/null +++ b/libcore/node_modules/browserify/test/spread.js @@ -0,0 +1,14 @@ +var browserify = require('../'); +var test = require('tap').test; +var vm = require('vm'); +var hasObjectSpread = require('has-object-spread')(); + +test('yield', { skip: !hasObjectSpread }, function (t) { + t.plan(2); + var b = browserify(__dirname + '/spread/main.js'); + + b.bundle(function (err, src) { + t.error(err); + t.notEqual(src.indexOf('...b'), -1, 'passed through spread syntax') + }); +}); diff --git a/libcore/node_modules/browserify/test/spread/main.js b/libcore/node_modules/browserify/test/spread/main.js new file mode 100644 index 0000000..c3e1a40 --- /dev/null +++ b/libcore/node_modules/browserify/test/spread/main.js @@ -0,0 +1 @@ +var a = { ...b } diff --git a/libcore/node_modules/browserify/test/standalone.js b/libcore/node_modules/browserify/test/standalone.js new file mode 100644 index 0000000..16c105a --- /dev/null +++ b/libcore/node_modules/browserify/test/standalone.js @@ -0,0 +1,85 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; + +test('standalone', function (t) { + t.plan(3); + + var b = browserify(__dirname + '/standalone/main.js', { + standalone: 'stand-test' + }); + b.bundle(function (err, src) { + t.test('window global', function (t) { + t.plan(2); + var c = { + window: {}, + done : done(t) + }; + vm.runInNewContext(src + 'window.standTest(done)', c); + }); + t.test('CommonJS', function (t) { + t.plan(2); + var exp = {}; + var c = { + module: { exports: exp }, + exports: exp, + done : done(t) + }; + vm.runInNewContext(src + 'module.exports(done)', c); + }); + t.test('RequireJS', function (t) { + t.plan(2); + var c = { + define: function (dependencies, fn) { + fn()(done(t)); + } + }; + c.define.amd = true; + vm.runInNewContext(src, c); + }); + }); +}); + +test('A.B.C standalone', function (t) { + t.plan(3); + + var b = browserify(__dirname + '/standalone/main.js', { + standalone: 'A.B.C' + }); + b.bundle(function (err, src) { + t.test('window global', function (t) { + t.plan(2); + var c = { window: {} }; + vm.runInNewContext(src, c); + c.window.A.B.C(done(t)); + }); + t.test('CommonJS', function (t) { + t.plan(2); + var exp = {}; + var c = { + module: { exports: exp }, + exports: exp + }; + vm.runInNewContext(src, c); + c.module.exports(done(t)); + }); + t.test('RequireJS', function (t) { + t.plan(2); + var c = { + define: function (dependencies, fn) { + fn()(done(t)); + } + }; + c.define.amd = true; + vm.runInNewContext(src, c); + }); + }); +}); + +function done(t) { + return function (one, two) { + t.equal(one, 1); + t.equal(two, 2); + t.end(); + }; +} diff --git a/libcore/node_modules/browserify/test/standalone/main.js b/libcore/node_modules/browserify/test/standalone/main.js new file mode 100644 index 0000000..400038d --- /dev/null +++ b/libcore/node_modules/browserify/test/standalone/main.js @@ -0,0 +1,3 @@ +module.exports = function (cb) { + cb(require('./one'), require('./two')); +}; \ No newline at end of file diff --git a/libcore/node_modules/browserify/test/standalone/one.js b/libcore/node_modules/browserify/test/standalone/one.js new file mode 100644 index 0000000..bd816ea --- /dev/null +++ b/libcore/node_modules/browserify/test/standalone/one.js @@ -0,0 +1 @@ +module.exports = 1; diff --git a/libcore/node_modules/browserify/test/standalone/two.js b/libcore/node_modules/browserify/test/standalone/two.js new file mode 100644 index 0000000..4bbffde --- /dev/null +++ b/libcore/node_modules/browserify/test/standalone/two.js @@ -0,0 +1 @@ +module.exports = 2; diff --git a/libcore/node_modules/browserify/test/standalone_events.js b/libcore/node_modules/browserify/test/standalone_events.js new file mode 100644 index 0000000..eb42afb --- /dev/null +++ b/libcore/node_modules/browserify/test/standalone_events.js @@ -0,0 +1,19 @@ +var browserify = require('../'); +var test = require('tap').test; + +test('standalone bundle close event', {timeout: 1000}, function (t) { + t.plan(1); + + var ended = false; + + var b = browserify(__dirname + '/standalone/main.js', { + standalone: 'stand-test' + }); + var r = b.bundle(); + r.resume(); + r.on('end', function() { + t.ok(!ended); + ended = true; + t.end(); + }); +}); diff --git a/libcore/node_modules/browserify/test/standalone_sourcemap.js b/libcore/node_modules/browserify/test/standalone_sourcemap.js new file mode 100644 index 0000000..a11c454 --- /dev/null +++ b/libcore/node_modules/browserify/test/standalone_sourcemap.js @@ -0,0 +1,55 @@ +var browserify = require('../'); +var fs = require('fs'); +var vm = require('vm'); +var test = require('tap').test; + +test('standalone in debug mode', function (t) { + t.plan(3); + + var main = fs.readFileSync(__dirname + '/standalone/main.js'); + + var b = browserify(__dirname + '/standalone/main.js', { + standalone: 'stand-test', + debug: true + }); + b.bundle(function (err, buf) { + var src = buf.toString('utf8'); + t.test('window global', function (t) { + t.plan(2); + var c = { + window: {}, + done : done(t) + }; + vm.runInNewContext(src + '\nwindow.standTest(done)', c); + }); + t.test('CommonJS', function (t) { + t.plan(2); + var exp = {}; + var c = { + module: { exports: exp }, + exports: exp, + done : done(t) + }; + vm.runInNewContext(src + '\nmodule.exports(done)', c); + }); + t.test('RequireJS', function (t) { + t.plan(2); + var c = { + define: function (dependencies, fn) { + fn()(done(t)); + } + }; + c.define.amd = true; + vm.runInNewContext(src, c); + }); + }); +}); + +function done(t) { + return function (one, two) { + t.equal(one, 1); + t.equal(two, 2); + t.end(); + }; +} + diff --git a/libcore/node_modules/browserify/test/stdin.js b/libcore/node_modules/browserify/test/stdin.js new file mode 100644 index 0000000..da5415d --- /dev/null +++ b/libcore/node_modules/browserify/test/stdin.js @@ -0,0 +1,35 @@ +var test = require('tap').test; +var spawn = require('child_process').spawn; +var concat = require('concat-stream'); +var path = require('path'); +var vm = require('vm'); + +test('stdin', function (t) { + t.plan(2); + + var cwd = process.cwd(); + process.chdir(__dirname); + + var ps = spawn(process.execPath, [ + path.resolve(__dirname, '../bin/cmd.js'), + '-' + ]); + + ps.stdout.pipe(concat(function (body) { + var c = { console: { + log: function (msg) { + t.equal(msg, 'hello'); + } + } }; + vm.runInNewContext(body, c); + })); + ps.stderr.pipe(process.stderr); + + ps.on('exit', function (code) { + t.equal(code, 0); + }); + + ps.stdin.write("console.log('hello')"); + ps.stdin.end(); + +}); diff --git a/libcore/node_modules/browserify/test/stream.js b/libcore/node_modules/browserify/test/stream.js new file mode 100644 index 0000000..a15a5ee --- /dev/null +++ b/libcore/node_modules/browserify/test/stream.js @@ -0,0 +1,15 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; +var fs = require('fs'); + +test('stream', function (t) { + t.plan(2); + + var stream = fs.createReadStream(__dirname + '/stream/main.js'); + var b = browserify(stream, { basedir: __dirname + '/stream' }); + + b.bundle(function (err, src) { + vm.runInNewContext(src, { t: t }); + }); +}); diff --git a/libcore/node_modules/browserify/test/stream/bar.js b/libcore/node_modules/browserify/test/stream/bar.js new file mode 100644 index 0000000..5828b13 --- /dev/null +++ b/libcore/node_modules/browserify/test/stream/bar.js @@ -0,0 +1 @@ +module.exports = require('./foo.js') * 4 / 3 diff --git a/libcore/node_modules/browserify/test/stream/foo.js b/libcore/node_modules/browserify/test/stream/foo.js new file mode 100644 index 0000000..9123882 --- /dev/null +++ b/libcore/node_modules/browserify/test/stream/foo.js @@ -0,0 +1 @@ +module.exports = 333 diff --git a/libcore/node_modules/browserify/test/stream/main.js b/libcore/node_modules/browserify/test/stream/main.js new file mode 100644 index 0000000..33063b2 --- /dev/null +++ b/libcore/node_modules/browserify/test/stream/main.js @@ -0,0 +1,2 @@ +t.equal(require('./foo.js'), 333); +t.equal(require('./bar.js'), 444); diff --git a/libcore/node_modules/browserify/test/stream_file.js b/libcore/node_modules/browserify/test/stream_file.js new file mode 100644 index 0000000..100471c --- /dev/null +++ b/libcore/node_modules/browserify/test/stream_file.js @@ -0,0 +1,29 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; +var fs = require('fs'); +var through = require('through2'); +var path = require('path'); + +test('stream file', function (t) { + var expected = {}; + expected[ path.join(__dirname, 'stream/fake.js') ] = true; + expected[ path.join(__dirname, 'stream/bar.js' ) ] = true; + expected[ path.join(__dirname, 'stream/foo.js' ) ] = true; + + t.plan(5); + + var stream = fs.createReadStream(__dirname + '/stream/main.js'); + stream.file = path.join(__dirname, '/stream/fake.js'); + + var b = browserify(stream, { basedir: __dirname + '/stream' }); + b.transform(function (file) { + t.ok(expected[file]); + delete expected[file]; + return through(); + }); + + b.bundle(function (err, src) { + vm.runInNewContext(src, { t: t }); + }); +}); diff --git a/libcore/node_modules/browserify/test/subdep.js b/libcore/node_modules/browserify/test/subdep.js new file mode 100644 index 0000000..fd58d6e --- /dev/null +++ b/libcore/node_modules/browserify/test/subdep.js @@ -0,0 +1,16 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; + +test('subdep', function (t) { + t.plan(1); + + var b = browserify(); + b.require(__dirname + '/subdep/index.js', { expose: 'subdep' }); + + b.bundle(function (err, src) { + var c = {}; + vm.runInNewContext(src, c); + t.equal(c.require('subdep'), 'zzz'); + }); +}); diff --git a/libcore/node_modules/browserify/test/subdep/index.js b/libcore/node_modules/browserify/test/subdep/index.js new file mode 100644 index 0000000..f05301b --- /dev/null +++ b/libcore/node_modules/browserify/test/subdep/index.js @@ -0,0 +1 @@ +module.exports = require('qq'); diff --git a/libcore/node_modules/browserify/test/subdep/package.json b/libcore/node_modules/browserify/test/subdep/package.json new file mode 100644 index 0000000..518d22a --- /dev/null +++ b/libcore/node_modules/browserify/test/subdep/package.json @@ -0,0 +1,6 @@ +{ + "dependencies" : { + "qq" : "*" + }, + "main" : "index.js" +} diff --git a/libcore/node_modules/browserify/test/symlink_dedupe.js b/libcore/node_modules/browserify/test/symlink_dedupe.js new file mode 100644 index 0000000..dbc7afe --- /dev/null +++ b/libcore/node_modules/browserify/test/symlink_dedupe.js @@ -0,0 +1,16 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; + +test('hash instances with hashed contexts', { skip: process.platform === 'win32' }, function (t) { + t.plan(5); + + var b = browserify(__dirname + '/symlink_dedupe/main.js'); + b.bundle(function (err, buf) { + var c = { t: t }; + var src = buf.toString('utf8'); + t.equal(src.match(RegExp('// FILE F ONE', 'g')).length, 1); + t.equal(src.match(RegExp('// FILE G ONE', 'g')).length, 1); + vm.runInNewContext(src, c); + }); +}); diff --git a/libcore/node_modules/browserify/test/symlink_dedupe/main.js b/libcore/node_modules/browserify/test/symlink_dedupe/main.js new file mode 100644 index 0000000..92ff18d --- /dev/null +++ b/libcore/node_modules/browserify/test/symlink_dedupe/main.js @@ -0,0 +1,6 @@ +var A = require('./one/f.js'); +var B = require('./one/dir/f.js'); +t.equal(A, B); +t.equal(A(), 555); +t.equal(B(), 555); + diff --git a/libcore/node_modules/browserify/test/symlink_dedupe/one/f.js b/libcore/node_modules/browserify/test/symlink_dedupe/one/f.js new file mode 100644 index 0000000..a315c1e --- /dev/null +++ b/libcore/node_modules/browserify/test/symlink_dedupe/one/f.js @@ -0,0 +1,3 @@ +// FILE F ONE +var G = require('./g.js'); +module.exports = function () { return 111 * G }; diff --git a/libcore/node_modules/browserify/test/symlink_dedupe/one/g.js b/libcore/node_modules/browserify/test/symlink_dedupe/one/g.js new file mode 100644 index 0000000..8373032 --- /dev/null +++ b/libcore/node_modules/browserify/test/symlink_dedupe/one/g.js @@ -0,0 +1,2 @@ +// FILE G ONE +module.exports = 5 diff --git a/libcore/node_modules/browserify/test/syntax_cache.js b/libcore/node_modules/browserify/test/syntax_cache.js new file mode 100644 index 0000000..202e5f6 --- /dev/null +++ b/libcore/node_modules/browserify/test/syntax_cache.js @@ -0,0 +1,47 @@ +var Seq = require('seq'); +var browserify = require('../'); +var test = require('tap').test; +var shasum = require('shasum-object'); + +test('syntax cache - valid', function (t) { + t.plan(2); + + var expectedCache = {} + var cacheKey; + + var b = browserify(__dirname + '/syntax_cache/valid.js'); + b.once('dep', function(row) { + cacheKey = shasum(row.source); + expectedCache[cacheKey] = true; + }); + + Seq() + .seq(function() { b.bundle(this); }) + .seq(function() { + t.deepEqual(b._syntaxCache, expectedCache); + b._syntaxCache[cacheKey] = expectedCache[cacheKey] = 'beep'; + b.bundle(function(err, src) { + // if the cache worked, the "cacheKey" + // should not be reset to "true" + t.deepEqual(b._syntaxCache, expectedCache); + }); + }); +}); + +test('syntax cache - skip invalid', function (t) { + t.plan(5); + + var b = browserify(__dirname + '/syntax_cache/invalid.js'); + + Seq() + .seq(function() { b.bundle(this); }) + .catch(function(lastErr) { + t.deepEqual(b._syntaxCache, {}); + t.similar(String(lastErr), /ParseError/); + b.bundle(function(err, src) { + t.deepEqual(b._syntaxCache, {}); + t.similar(String(err), /ParseError/); + t.notEqual(lastErr, err, 'errors should be unique'); + }); + }); +}); diff --git a/libcore/node_modules/browserify/test/syntax_cache/invalid.js b/libcore/node_modules/browserify/test/syntax_cache/invalid.js new file mode 100644 index 0000000..e85c07c --- /dev/null +++ b/libcore/node_modules/browserify/test/syntax_cache/invalid.js @@ -0,0 +1,2 @@ +var x = { +var y = 6; diff --git a/libcore/node_modules/browserify/test/syntax_cache/valid.js b/libcore/node_modules/browserify/test/syntax_cache/valid.js new file mode 100644 index 0000000..cf4f426 --- /dev/null +++ b/libcore/node_modules/browserify/test/syntax_cache/valid.js @@ -0,0 +1,2 @@ +var x = {}; +var y = 6; diff --git a/libcore/node_modules/browserify/test/tr.js b/libcore/node_modules/browserify/test/tr.js new file mode 100644 index 0000000..69c7248 --- /dev/null +++ b/libcore/node_modules/browserify/test/tr.js @@ -0,0 +1,28 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; +var through = require('through2'); + +test('function transform', function (t) { + t.plan(7); + + var b = browserify(__dirname + '/tr/main.js'); + b.transform({ global: true }, function (file) { + return through(function (buf, enc, next) { + this.push(String(buf).replace(/ZZZ/g, '1')); + next(); + }); + }); + b.transform(function (file) { + return through(function (buf, enc, next) { + this.push(String(buf) + .replace(/AAA/g, '5') + .replace(/BBB/g, '50') + ); + next(); + }) + }); + b.bundle(function (err, src) { + vm.runInNewContext(src, { t: t }); + }); +}); diff --git a/libcore/node_modules/browserify/test/tr/f.js b/libcore/node_modules/browserify/test/tr/f.js new file mode 100644 index 0000000..a56a097 --- /dev/null +++ b/libcore/node_modules/browserify/test/tr/f.js @@ -0,0 +1,2 @@ +t.equal(XYZ, 909); +module.exports = function (x) { return x + BBB } diff --git a/libcore/node_modules/browserify/test/tr/main.js b/libcore/node_modules/browserify/test/tr/main.js new file mode 100644 index 0000000..8503c47 --- /dev/null +++ b/libcore/node_modules/browserify/test/tr/main.js @@ -0,0 +1,9 @@ +var f = require('./f.js'); +var m = require('m'); +var g = require('g'); +t.equal(require('./subdir/g.js'), 999); + +t.equal(m(f(AAA)), 555, 'transformation scope'); +t.equal(g(3), 332, 'sub-transformation applied'); +t.equal(typeof GGG, 'undefined', 'GGG leak'); +t.equal(XYZ, 909); diff --git a/libcore/node_modules/browserify/test/tr/package.json b/libcore/node_modules/browserify/test/tr/package.json new file mode 100644 index 0000000..6687fa1 --- /dev/null +++ b/libcore/node_modules/browserify/test/tr/package.json @@ -0,0 +1,5 @@ +{ + "browserify": { + "transform": [ "xyz" ] + } +} diff --git a/libcore/node_modules/browserify/test/tr/subdir/g.js b/libcore/node_modules/browserify/test/tr/subdir/g.js new file mode 100644 index 0000000..047280d --- /dev/null +++ b/libcore/node_modules/browserify/test/tr/subdir/g.js @@ -0,0 +1 @@ +module.exports = XYZ + 90; diff --git a/libcore/node_modules/browserify/test/tr_args.js b/libcore/node_modules/browserify/test/tr_args.js new file mode 100644 index 0000000..ace4530 --- /dev/null +++ b/libcore/node_modules/browserify/test/tr_args.js @@ -0,0 +1,24 @@ +var test = require('tap').test; +var spawn = require('child_process').spawn; +var path = require('path'); +var concat = require('concat-stream'); +var vm = require('vm'); + +test('transform arguments', function (t) { + t.plan(2); + + var ps = spawn(process.execPath, [ + path.resolve(__dirname, '../bin/cmd.js'), + __dirname + '/tr_args/main.js', + '-t', '[', __dirname + '/tr_args/tr.js', '-x', '1', ']' + ]); + + ps.stderr.pipe(process.stderr); + ps.stdout.pipe(concat(function (body) { + vm.runInNewContext(body.toString('utf8'), { t: t }); + })); + + ps.on('exit', function (code) { + t.equal(code, 0); + }); +}); diff --git a/libcore/node_modules/browserify/test/tr_args/main.js b/libcore/node_modules/browserify/test/tr_args/main.js new file mode 100644 index 0000000..ec448ae --- /dev/null +++ b/libcore/node_modules/browserify/test/tr_args/main.js @@ -0,0 +1 @@ +t.equal(XXX * 5, 555); diff --git a/libcore/node_modules/browserify/test/tr_args/tr.js b/libcore/node_modules/browserify/test/tr_args/tr.js new file mode 100644 index 0000000..6d0a1a8 --- /dev/null +++ b/libcore/node_modules/browserify/test/tr_args/tr.js @@ -0,0 +1,12 @@ +var through = require('through2'); + +module.exports = function (file, opts) { + var data = ''; + return through(write, end); + + function write (buf, enc, next) { data += buf; next() } + function end () { + this.push(data.replace(/X/g, opts.x)); + this.push(null); + } +}; diff --git a/libcore/node_modules/browserify/test/tr_error.js b/libcore/node_modules/browserify/test/tr_error.js new file mode 100644 index 0000000..e7d857c --- /dev/null +++ b/libcore/node_modules/browserify/test/tr_error.js @@ -0,0 +1,33 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; +var through = require('through2'); + +test('transform errors errback', function (t) { + t.plan(2); + + var b = browserify(__dirname + '/tr/main.js'); + b.transform(function (file) { + return through(function (buf) { + this.emit('error', new Error('blah')); + }) + }); + b.bundle(function (err, src) { + t.ok(/^blah/.test(err.message)); + t.equal(src, undefined); + }); +}); + +test('transform errors propagate', function (t) { + t.plan(1); + + var b = browserify(__dirname + '/tr/main.js'); + b.transform(function (file) { + return through(function (buf) { + this.emit('error', new Error('blah')); + }); + }); + b.bundle().on('error', function (err) { + t.ok(/^blah/.test(err.message)); + }); +}); diff --git a/libcore/node_modules/browserify/test/tr_flags.js b/libcore/node_modules/browserify/test/tr_flags.js new file mode 100644 index 0000000..b6bff92 --- /dev/null +++ b/libcore/node_modules/browserify/test/tr_flags.js @@ -0,0 +1,36 @@ +var through = require('through2'); +var browserify = require('../'); +var test = require('tap').test; +var vm = require('vm'); + +test('--debug passed to transforms', function (t) { + var empty = require.resolve('../lib/_empty'); + + t.plan(3); + + [true, false].forEach(function(debug) { + var b = browserify(empty, { debug: debug }); + + b.transform(function(file, opts) { + t.equal(opts._flags.debug, debug, 'debug: ' + debug); + return through(); + }); + + b.bundle(function (err, src) { + if (err) return t.fail(err.message); + }); + }); + + var b = browserify(empty, { debug: true }); + + b.transform({ + _flags: Infinity + }, function(file, opts) { + t.equal(opts._flags, Infinity, 'transform arguents are preserved'); + return through(); + }); + + b.bundle(function(err, src) { + if (err) return t.fail(err.message); + }); +}); diff --git a/libcore/node_modules/browserify/test/tr_global.js b/libcore/node_modules/browserify/test/tr_global.js new file mode 100644 index 0000000..941eaf4 --- /dev/null +++ b/libcore/node_modules/browserify/test/tr_global.js @@ -0,0 +1,17 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; +var through = require('through2'); + +test('global transform precedence', function (t) { + t.plan(1); + + var b = browserify(__dirname + '/tr_global/main.js', { + basedir: __dirname + '/tr_global' + }); + b.transform('tr', { global: true }); + b.bundle(function (err, src) { + vm.runInNewContext(src, { console: { log: log } }); + function log (msg) { t.equal(msg, 444) } + }); +}); diff --git a/libcore/node_modules/browserify/test/tr_global/main.js b/libcore/node_modules/browserify/test/tr_global/main.js new file mode 100644 index 0000000..208d369 --- /dev/null +++ b/libcore/node_modules/browserify/test/tr_global/main.js @@ -0,0 +1 @@ +console.log(require('x')); diff --git a/libcore/node_modules/browserify/test/tr_no_entry.js b/libcore/node_modules/browserify/test/tr_no_entry.js new file mode 100644 index 0000000..f41d9ce --- /dev/null +++ b/libcore/node_modules/browserify/test/tr_no_entry.js @@ -0,0 +1,20 @@ +var browserify = require('../'); +var test = require('tap').test; +var path = require('path') + +test('transform with no entry files', function (t) { + process.chdir(__dirname); + + t.plan(2); + var b = browserify(); + b.transform('tr'); + b.require(path.join(__dirname, 'tr_no_entry/main.js'), { + expose: 'yoyo' + }); + b.bundle(function (err, body) { + t.ifError(err); + var src = body.toString('utf8') + 'require("yoyo")'; + var con = { log: function (msg) { t.equal(msg, 'ZZZ') } }; + Function('console', src)(con); + }); +}); diff --git a/libcore/node_modules/browserify/test/tr_no_entry/main.js b/libcore/node_modules/browserify/test/tr_no_entry/main.js new file mode 100644 index 0000000..3dce908 --- /dev/null +++ b/libcore/node_modules/browserify/test/tr_no_entry/main.js @@ -0,0 +1 @@ +console.log('XXX'); diff --git a/libcore/node_modules/browserify/test/tr_once.js b/libcore/node_modules/browserify/test/tr_once.js new file mode 100644 index 0000000..a892189 --- /dev/null +++ b/libcore/node_modules/browserify/test/tr_once.js @@ -0,0 +1,21 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; +var through = require('through2'); +var path = require('path'); + +test('transform exactly once', function (t) { + t.plan(3); + + var b = browserify(__dirname + '/tr_once/main.js', { + transform: function (file) { + t.equal(file, path.join(__dirname, 'tr_once/main.js') ); + return through(); + } + }); + b.bundle(function (err, src) { + t.ifError(err); + vm.runInNewContext(src, { console: { log: log } }); + function log (msg) { t.equal(msg, 'wow') } + }); +}); diff --git a/libcore/node_modules/browserify/test/tr_once/main.js b/libcore/node_modules/browserify/test/tr_once/main.js new file mode 100644 index 0000000..6036bec --- /dev/null +++ b/libcore/node_modules/browserify/test/tr_once/main.js @@ -0,0 +1 @@ +console.log('wow'); diff --git a/libcore/node_modules/browserify/test/tr_order.js b/libcore/node_modules/browserify/test/tr_order.js new file mode 100644 index 0000000..020b86e --- /dev/null +++ b/libcore/node_modules/browserify/test/tr_order.js @@ -0,0 +1,23 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; +var through = require('through2'); + +test('function transform', function (t) { + debugger; + t.plan(8); + + var b = browserify(__dirname + '/tr/main.js'); + b.transform({ global: true }, function (file) { + return through(function (buf, enc, next) { + this.push(String(buf).replace(/ZZZ/g, '1')); + next(); + }); + }); + b.transform(__dirname + '/tr_order/replace_aaa'); + b.transform(__dirname + '/tr_order/replace_bbb.js'); + b.bundle(function (err, src) { + t.ifError(err); + vm.runInNewContext(src, { t: t }); + }); +}); diff --git a/libcore/node_modules/browserify/test/tr_order/replace_aaa.js b/libcore/node_modules/browserify/test/tr_order/replace_aaa.js new file mode 100644 index 0000000..f1af976 --- /dev/null +++ b/libcore/node_modules/browserify/test/tr_order/replace_aaa.js @@ -0,0 +1,10 @@ +var through = require('through2'); + +module.exports = function(file) { + return through(function (buf, enc, next) { + this.push(String(buf) + .replace(/AAA/g, '5') + ); + next(); + }) +} diff --git a/libcore/node_modules/browserify/test/tr_order/replace_bbb.js b/libcore/node_modules/browserify/test/tr_order/replace_bbb.js new file mode 100644 index 0000000..cf57725 --- /dev/null +++ b/libcore/node_modules/browserify/test/tr_order/replace_bbb.js @@ -0,0 +1,11 @@ +var through = require('through2'); + +module.exports = function(file) { + return through(function (buf, enc, next) { + this.push(String(buf) + .replace(/AAA/g, '6') + .replace(/BBB/g, '50') + ); + next(); + }) +} diff --git a/libcore/node_modules/browserify/test/tr_symlink.js b/libcore/node_modules/browserify/test/tr_symlink.js new file mode 100644 index 0000000..9fcca56 --- /dev/null +++ b/libcore/node_modules/browserify/test/tr_symlink.js @@ -0,0 +1,27 @@ +// based on this scenario: +// https://github.com/substack/node-browserify/pull/831#issuecomment-49546902 + +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; +var through = require('through2'); + +test('transform symlink', { skip: process.platform === 'win32' }, function (t) { + t.plan(4); + var expected = [ 9, 555, 777 ]; + var b = browserify(__dirname + '/tr_symlink/app/main.js', { + basedir: __dirname + '/tr_symlink/app' + }); + b.transform(function (file) { + return through(function (buf, enc, next) { + this.push(String(buf).replace(/7/g, 9)); + next(); + }) + }); + b.bundle(function (err, src) { + t.ifError(err); + var c = { console: { log: log } }; + vm.runInNewContext(src, c); + function log (msg) { t.equal(msg, expected.shift()) } + }); +}); diff --git a/libcore/node_modules/browserify/test/tr_symlink/a-module/index.js b/libcore/node_modules/browserify/test/tr_symlink/a-module/index.js new file mode 100644 index 0000000..3e842e7 --- /dev/null +++ b/libcore/node_modules/browserify/test/tr_symlink/a-module/index.js @@ -0,0 +1 @@ +module.exports = 555 diff --git a/libcore/node_modules/browserify/test/tr_symlink/app/main.js b/libcore/node_modules/browserify/test/tr_symlink/app/main.js new file mode 100644 index 0000000..da0ac76 --- /dev/null +++ b/libcore/node_modules/browserify/test/tr_symlink/app/main.js @@ -0,0 +1,6 @@ +var a = require('aaa'); +var b = require('bbb'); + +console.log(5); +console.log(a); +console.log(b); diff --git a/libcore/node_modules/browserify/test/tr_symlink/app/package.json b/libcore/node_modules/browserify/test/tr_symlink/app/package.json new file mode 100644 index 0000000..2f2bbff --- /dev/null +++ b/libcore/node_modules/browserify/test/tr_symlink/app/package.json @@ -0,0 +1,5 @@ +{ + "browserify": { + "transform": [ "tr" ] + } +} diff --git a/libcore/node_modules/browserify/test/tr_symlink/b-module/ext.js b/libcore/node_modules/browserify/test/tr_symlink/b-module/ext.js new file mode 100644 index 0000000..2fad987 --- /dev/null +++ b/libcore/node_modules/browserify/test/tr_symlink/b-module/ext.js @@ -0,0 +1 @@ +module.exports = 777; diff --git a/libcore/node_modules/browserify/test/tr_symlink/b-module/index.js b/libcore/node_modules/browserify/test/tr_symlink/b-module/index.js new file mode 100644 index 0000000..dae6275 --- /dev/null +++ b/libcore/node_modules/browserify/test/tr_symlink/b-module/index.js @@ -0,0 +1,2 @@ +var ext = require('./ext'); +module.exports = ext; diff --git a/libcore/node_modules/browserify/test/unicode.js b/libcore/node_modules/browserify/test/unicode.js new file mode 100644 index 0000000..2b68515 --- /dev/null +++ b/libcore/node_modules/browserify/test/unicode.js @@ -0,0 +1,19 @@ +var browserify = require('../'); +var vm = require('vm'); +var test = require('tap').test; + +test('unicode entry', function (t) { + t.plan(2); + + var b = browserify(__dirname + '/unicode/main.js'); + b.bundle(function (err, src) { + var c = { + done : function (one, two) { + t.equal(one, 1); + t.equal(two, 2); + t.end(); + } + }; + vm.runInNewContext(src, c); + }); +}); diff --git a/libcore/node_modules/browserify/test/unicode/main.js b/libcore/node_modules/browserify/test/unicode/main.js new file mode 100644 index 0000000..89bb8a0 --- /dev/null +++ b/libcore/node_modules/browserify/test/unicode/main.js @@ -0,0 +1 @@ +done(require('./one'), require('./two')); \ No newline at end of file diff --git a/libcore/node_modules/browserify/test/unicode/one.js b/libcore/node_modules/browserify/test/unicode/one.js new file mode 100644 index 0000000..bd816ea --- /dev/null +++ b/libcore/node_modules/browserify/test/unicode/one.js @@ -0,0 +1 @@ +module.exports = 1; diff --git a/libcore/node_modules/browserify/test/unicode/two.js b/libcore/node_modules/browserify/test/unicode/two.js new file mode 100644 index 0000000..4bbffde --- /dev/null +++ b/libcore/node_modules/browserify/test/unicode/two.js @@ -0,0 +1 @@ +module.exports = 2; diff --git a/libcore/node_modules/browserify/test/util.js b/libcore/node_modules/browserify/test/util.js new file mode 100644 index 0000000..a5cc8cd --- /dev/null +++ b/libcore/node_modules/browserify/test/util.js @@ -0,0 +1,64 @@ +var browserify = require('../'); +var test = require('tap').test; +var util = require('util'); +var xtend = require('xtend'); +var vm = require('vm'); + +test('util.inspect', function (t) { + t.plan(1); + + var b = browserify(); + b.require('util'); + b.bundle(function (err ,src) { + var c = {}; + vm.runInNewContext(src, c); + t.equal( + c.require('util').inspect([1,2,3]), + util.inspect([1,2,3]) + ); + }); +}); + +test('util.inherits', function (t) { + t.plan(2); + + var b = browserify(); + b.require('util'); + b.require('events'); + + b.bundle(function (err, src) { + var c = {}; + vm.runInNewContext(src, c); + var EE = c.require('events').EventEmitter; + + function Beep () {} + c.require('util').inherits(Beep, EE); + var beep = new Beep; + + t.ok(beep instanceof Beep); + t.ok(beep instanceof EE); + }); +}); + +test('util.inherits without Object.create', function (t) { + t.plan(2); + var b = browserify(); + b.require('util'); + b.require('events'); + + b.bundle(function (err, src) { + var c = xtend({}, Object); + delete c.create; + vm.runInNewContext(src, c); + var EE = c.require('events').EventEmitter; + + function Beep () {} + Beep.prototype = {}; + + c.require('util').inherits(Beep, EE); + var beep = new Beep; + + t.ok(beep instanceof Beep); + t.ok(beep instanceof EE); + }); +}); diff --git a/libcore/node_modules/browserify/test/yield.js b/libcore/node_modules/browserify/test/yield.js new file mode 100644 index 0000000..164a5aa --- /dev/null +++ b/libcore/node_modules/browserify/test/yield.js @@ -0,0 +1,20 @@ +var browserify = require('../'); +var test = require('tap').test; +var vm = require('vm'); +var generatorFunction = require('make-generator-function'); + +test('yield', { skip: !generatorFunction }, function (t) { + t.plan(6); + var b = browserify(__dirname + '/yield/main.js'); + + b.bundle(function (err, src) { + t.error(err); + var c = { console: { log: log } }; + var index = 0; + vm.runInNewContext(src, c); + + function log (msg) { + t.equal(index++, msg); + } + }); +}); diff --git a/libcore/node_modules/browserify/test/yield/f.js b/libcore/node_modules/browserify/test/yield/f.js new file mode 100644 index 0000000..8bb123b --- /dev/null +++ b/libcore/node_modules/browserify/test/yield/f.js @@ -0,0 +1,5 @@ +module.exports = function *() { + for (var i = 0; i < 5; i++) { + yield i; + } +} diff --git a/libcore/node_modules/browserify/test/yield/main.js b/libcore/node_modules/browserify/test/yield/main.js new file mode 100644 index 0000000..5a2e6bb --- /dev/null +++ b/libcore/node_modules/browserify/test/yield/main.js @@ -0,0 +1,4 @@ +var f = require('./f.js')(); +for (var r = f.next(); !r.done; r = f.next()) { + console.log(r.value); +} diff --git a/libcore/node_modules/buffer-from/LICENSE b/libcore/node_modules/buffer-from/LICENSE new file mode 100644 index 0000000..e4bf1d6 --- /dev/null +++ b/libcore/node_modules/buffer-from/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2016, 2018 Linus Unnebäck + +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. diff --git a/libcore/node_modules/buffer-from/index.js b/libcore/node_modules/buffer-from/index.js new file mode 100644 index 0000000..e1a58b5 --- /dev/null +++ b/libcore/node_modules/buffer-from/index.js @@ -0,0 +1,72 @@ +/* eslint-disable node/no-deprecated-api */ + +var toString = Object.prototype.toString + +var isModern = ( + typeof Buffer !== 'undefined' && + typeof Buffer.alloc === 'function' && + typeof Buffer.allocUnsafe === 'function' && + typeof Buffer.from === 'function' +) + +function isArrayBuffer (input) { + return toString.call(input).slice(8, -1) === 'ArrayBuffer' +} + +function fromArrayBuffer (obj, byteOffset, length) { + byteOffset >>>= 0 + + var maxLength = obj.byteLength - byteOffset + + if (maxLength < 0) { + throw new RangeError("'offset' is out of bounds") + } + + if (length === undefined) { + length = maxLength + } else { + length >>>= 0 + + if (length > maxLength) { + throw new RangeError("'length' is out of bounds") + } + } + + return isModern + ? Buffer.from(obj.slice(byteOffset, byteOffset + length)) + : new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length))) +} + +function fromString (string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + return isModern + ? Buffer.from(string, encoding) + : new Buffer(string, encoding) +} + +function bufferFrom (value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (isArrayBuffer(value)) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(value, encodingOrOffset) + } + + return isModern + ? Buffer.from(value) + : new Buffer(value) +} + +module.exports = bufferFrom diff --git a/libcore/node_modules/buffer-from/package.json b/libcore/node_modules/buffer-from/package.json new file mode 100644 index 0000000..6ac5327 --- /dev/null +++ b/libcore/node_modules/buffer-from/package.json @@ -0,0 +1,19 @@ +{ + "name": "buffer-from", + "version": "1.1.2", + "license": "MIT", + "repository": "LinusU/buffer-from", + "files": [ + "index.js" + ], + "scripts": { + "test": "standard && node test" + }, + "devDependencies": { + "standard": "^12.0.1" + }, + "keywords": [ + "buffer", + "buffer from" + ] +} diff --git a/libcore/node_modules/buffer-from/readme.md b/libcore/node_modules/buffer-from/readme.md new file mode 100644 index 0000000..9880a55 --- /dev/null +++ b/libcore/node_modules/buffer-from/readme.md @@ -0,0 +1,69 @@ +# Buffer From + +A [ponyfill](https://ponyfill.com) for `Buffer.from`, uses native implementation if available. + +## Installation + +```sh +npm install --save buffer-from +``` + +## Usage + +```js +const bufferFrom = require('buffer-from') + +console.log(bufferFrom([1, 2, 3, 4])) +//=> + +const arr = new Uint8Array([1, 2, 3, 4]) +console.log(bufferFrom(arr.buffer, 1, 2)) +//=> + +console.log(bufferFrom('test', 'utf8')) +//=> + +const buf = bufferFrom('test') +console.log(bufferFrom(buf)) +//=> +``` + +## API + +### bufferFrom(array) + +- `array` <Array> + +Allocates a new `Buffer` using an `array` of octets. + +### bufferFrom(arrayBuffer[, byteOffset[, length]]) + +- `arrayBuffer` <ArrayBuffer> The `.buffer` property of a TypedArray or ArrayBuffer +- `byteOffset` <Integer> Where to start copying from `arrayBuffer`. **Default:** `0` +- `length` <Integer> How many bytes to copy from `arrayBuffer`. **Default:** `arrayBuffer.length - byteOffset` + +When passed a reference to the `.buffer` property of a TypedArray instance, the +newly created `Buffer` will share the same allocated memory as the TypedArray. + +The optional `byteOffset` and `length` arguments specify a memory range within +the `arrayBuffer` that will be shared by the `Buffer`. + +### bufferFrom(buffer) + +- `buffer` <Buffer> An existing `Buffer` to copy data from + +Copies the passed `buffer` data onto a new `Buffer` instance. + +### bufferFrom(string[, encoding]) + +- `string` <String> A string to encode. +- `encoding` <String> The encoding of `string`. **Default:** `'utf8'` + +Creates a new `Buffer` containing the given JavaScript string `string`. If +provided, the `encoding` parameter identifies the character encoding of +`string`. + +## See also + +- [buffer-alloc](https://github.com/LinusU/buffer-alloc) A ponyfill for `Buffer.alloc` +- [buffer-alloc-unsafe](https://github.com/LinusU/buffer-alloc-unsafe) A ponyfill for `Buffer.allocUnsafe` diff --git a/libcore/node_modules/buffer-xor/.npmignore b/libcore/node_modules/buffer-xor/.npmignore new file mode 100644 index 0000000..3c3629e --- /dev/null +++ b/libcore/node_modules/buffer-xor/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/libcore/node_modules/buffer-xor/.travis.yml b/libcore/node_modules/buffer-xor/.travis.yml new file mode 100644 index 0000000..d9f695b --- /dev/null +++ b/libcore/node_modules/buffer-xor/.travis.yml @@ -0,0 +1,9 @@ +language: node_js +before_install: + - "npm install npm -g" +node_js: + - "0.12" +env: + - TEST_SUITE=standard + - TEST_SUITE=unit +script: "npm run-script $TEST_SUITE" diff --git a/libcore/node_modules/buffer-xor/LICENSE b/libcore/node_modules/buffer-xor/LICENSE new file mode 100644 index 0000000..bba5218 --- /dev/null +++ b/libcore/node_modules/buffer-xor/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Daniel Cousens + +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. diff --git a/libcore/node_modules/buffer-xor/README.md b/libcore/node_modules/buffer-xor/README.md new file mode 100644 index 0000000..007f058 --- /dev/null +++ b/libcore/node_modules/buffer-xor/README.md @@ -0,0 +1,41 @@ +# buffer-xor + +[![TRAVIS](https://secure.travis-ci.org/crypto-browserify/buffer-xor.png)](http://travis-ci.org/crypto-browserify/buffer-xor) +[![NPM](http://img.shields.io/npm/v/buffer-xor.svg)](https://www.npmjs.org/package/buffer-xor) + +[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) + +A simple module for bitwise-xor on buffers. + + +## Examples + +``` javascript +var xor = require("buffer-xor") +var a = new Buffer('00ff0f', 'hex') +var b = new Buffer('f0f0', 'hex') + +console.log(xor(a, b)) +// => +``` + + +Or for those seeking those few extra cycles, perform the operation in place: + +``` javascript +var xorInplace = require("buffer-xor/inplace") +var a = new Buffer('00ff0f', 'hex') +var b = new Buffer('f0f0', 'hex') + +console.log(xorInplace(a, b)) +// => +// NOTE: xorInplace will return the shorter slice of its parameters + +// See that a has been mutated +console.log(a) +// => +``` + + +## License [MIT](LICENSE) + diff --git a/libcore/node_modules/buffer-xor/index.js b/libcore/node_modules/buffer-xor/index.js new file mode 100644 index 0000000..85ee6f6 --- /dev/null +++ b/libcore/node_modules/buffer-xor/index.js @@ -0,0 +1,10 @@ +module.exports = function xor (a, b) { + var length = Math.min(a.length, b.length) + var buffer = new Buffer(length) + + for (var i = 0; i < length; ++i) { + buffer[i] = a[i] ^ b[i] + } + + return buffer +} diff --git a/libcore/node_modules/buffer-xor/inline.js b/libcore/node_modules/buffer-xor/inline.js new file mode 100644 index 0000000..8797570 --- /dev/null +++ b/libcore/node_modules/buffer-xor/inline.js @@ -0,0 +1 @@ +module.exports = require('./inplace') diff --git a/libcore/node_modules/buffer-xor/inplace.js b/libcore/node_modules/buffer-xor/inplace.js new file mode 100644 index 0000000..d71c172 --- /dev/null +++ b/libcore/node_modules/buffer-xor/inplace.js @@ -0,0 +1,9 @@ +module.exports = function xorInplace (a, b) { + var length = Math.min(a.length, b.length) + + for (var i = 0; i < length; ++i) { + a[i] = a[i] ^ b[i] + } + + return a.slice(0, length) +} diff --git a/libcore/node_modules/buffer-xor/package.json b/libcore/node_modules/buffer-xor/package.json new file mode 100644 index 0000000..5074b02 --- /dev/null +++ b/libcore/node_modules/buffer-xor/package.json @@ -0,0 +1,37 @@ +{ + "name": "buffer-xor", + "version": "1.0.3", + "description": "A simple module for bitwise-xor on buffers", + "main": "index.js", + "scripts": { + "standard": "standard", + "test": "npm run-script unit", + "unit": "mocha" + }, + "repository": { + "type": "git", + "url": "https://github.com/crypto-browserify/buffer-xor.git" + }, + "bugs": { + "url": "https://github.com/crypto-browserify/buffer-xor/issues" + }, + "homepage": "https://github.com/crypto-browserify/buffer-xor", + "keywords": [ + "bits", + "bitwise", + "buffer", + "buffer-xor", + "crypto", + "inline", + "math", + "memory", + "performance", + "xor" + ], + "author": "Daniel Cousens", + "license": "MIT", + "devDependencies": { + "mocha": "*", + "standard": "*" + } +} diff --git a/libcore/node_modules/buffer-xor/test/fixtures.json b/libcore/node_modules/buffer-xor/test/fixtures.json new file mode 100644 index 0000000..6f3431e --- /dev/null +++ b/libcore/node_modules/buffer-xor/test/fixtures.json @@ -0,0 +1,23 @@ +[ + { + "a": "000f", + "b": "f0ff", + "expected": "f0f0" + }, + { + "a": "000f0f", + "b": "f0ff", + "mutated": "f0f00f", + "expected": "f0f0" + }, + { + "a": "000f", + "b": "f0ffff", + "expected": "f0f0" + }, + { + "a": "000000", + "b": "000000", + "expected": "000000" + } +] diff --git a/libcore/node_modules/buffer-xor/test/index.js b/libcore/node_modules/buffer-xor/test/index.js new file mode 100644 index 0000000..06eacab --- /dev/null +++ b/libcore/node_modules/buffer-xor/test/index.js @@ -0,0 +1,38 @@ +/* global describe, it */ + +var assert = require('assert') +var xor = require('../') +var xorInplace = require('../inplace') +var fixtures = require('./fixtures') + +describe('xor', function () { + fixtures.forEach(function (f) { + it('returns ' + f.expected + ' for ' + f.a + '/' + f.b, function () { + var a = new Buffer(f.a, 'hex') + var b = new Buffer(f.b, 'hex') + var actual = xor(a, b) + + assert.equal(actual.toString('hex'), f.expected) + + // a/b unchanged + assert.equal(a.toString('hex'), f.a) + assert.equal(b.toString('hex'), f.b) + }) + }) +}) + +describe('xor/inplace', function () { + fixtures.forEach(function (f) { + it('returns ' + f.expected + ' for ' + f.a + '/' + f.b, function () { + var a = new Buffer(f.a, 'hex') + var b = new Buffer(f.b, 'hex') + var actual = xorInplace(a, b) + + assert.equal(actual.toString('hex'), f.expected) + + // a mutated, b unchanged + assert.equal(a.toString('hex'), f.mutated || f.expected) + assert.equal(b.toString('hex'), f.b) + }) + }) +}) diff --git a/libcore/node_modules/buffer/AUTHORS.md b/libcore/node_modules/buffer/AUTHORS.md new file mode 100644 index 0000000..2aa07bf --- /dev/null +++ b/libcore/node_modules/buffer/AUTHORS.md @@ -0,0 +1,55 @@ +# Authors + +#### Ordered by first contribution. + +- Romain Beauxis (toots@rastageeks.org) +- Tobias Koppers (tobias.koppers@googlemail.com) +- Janus (ysangkok@gmail.com) +- Rainer Dreyer (rdrey1@gmail.com) +- Tõnis Tiigi (tonistiigi@gmail.com) +- James Halliday (mail@substack.net) +- Michael Williamson (mike@zwobble.org) +- elliottcable (github@elliottcable.name) +- rafael (rvalle@livelens.net) +- Andrew Kelley (superjoe30@gmail.com) +- Andreas Madsen (amwebdk@gmail.com) +- Mike Brevoort (mike.brevoort@pearson.com) +- Brian White (mscdex@mscdex.net) +- Feross Aboukhadijeh (feross@feross.org) +- Ruben Verborgh (ruben@verborgh.org) +- eliang (eliang.cs@gmail.com) +- Jesse Tane (jesse.tane@gmail.com) +- Alfonso Boza (alfonso@cloud.com) +- Mathias Buus (mathiasbuus@gmail.com) +- Devon Govett (devongovett@gmail.com) +- Daniel Cousens (github@dcousens.com) +- Joseph Dykstra (josephdykstra@gmail.com) +- Parsha Pourkhomami (parshap+git@gmail.com) +- Damjan Košir (damjan.kosir@gmail.com) +- daverayment (dave.rayment@gmail.com) +- kawanet (u-suke@kawa.net) +- Linus Unnebäck (linus@folkdatorn.se) +- Nolan Lawson (nolan.lawson@gmail.com) +- Calvin Metcalf (calvin.metcalf@gmail.com) +- Koki Takahashi (hakatasiloving@gmail.com) +- Guy Bedford (guybedford@gmail.com) +- Jan Schär (jscissr@gmail.com) +- RaulTsc (tomescu.raul@gmail.com) +- Matthieu Monsch (monsch@alum.mit.edu) +- Dan Ehrenberg (littledan@chromium.org) +- Kirill Fomichev (fanatid@ya.ru) +- Yusuke Kawasaki (u-suke@kawa.net) +- DC (dcposch@dcpos.ch) +- John-David Dalton (john.david.dalton@gmail.com) +- adventure-yunfei (adventure030@gmail.com) +- Emil Bay (github@tixz.dk) +- Sam Sudar (sudar.sam@gmail.com) +- Volker Mische (volker.mische@gmail.com) +- David Walton (support@geekstocks.com) +- Сковорода Никита Андреевич (chalkerx@gmail.com) +- greenkeeper[bot] (greenkeeper[bot]@users.noreply.github.com) +- ukstv (sergey.ukustov@machinomy.com) +- ranbochen (ranbochen@qq.com) +- Vladimir Borovik (bobahbdb@gmail.com) + +#### Generated by bin/update-authors.sh. diff --git a/libcore/node_modules/buffer/LICENSE b/libcore/node_modules/buffer/LICENSE new file mode 100644 index 0000000..d6bf75d --- /dev/null +++ b/libcore/node_modules/buffer/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Feross Aboukhadijeh, and other contributors. + +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. diff --git a/libcore/node_modules/buffer/README.md b/libcore/node_modules/buffer/README.md new file mode 100644 index 0000000..a2d9f87 --- /dev/null +++ b/libcore/node_modules/buffer/README.md @@ -0,0 +1,409 @@ +# buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] + +[travis-image]: https://img.shields.io/travis/feross/buffer/master.svg +[travis-url]: https://travis-ci.org/feross/buffer +[npm-image]: https://img.shields.io/npm/v/buffer.svg +[npm-url]: https://npmjs.org/package/buffer +[downloads-image]: https://img.shields.io/npm/dm/buffer.svg +[downloads-url]: https://npmjs.org/package/buffer +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com + +#### The buffer module from [node.js](https://nodejs.org/), for the browser. + +[![saucelabs][saucelabs-image]][saucelabs-url] + +[saucelabs-image]: https://saucelabs.com/browser-matrix/buffer.svg +[saucelabs-url]: https://saucelabs.com/u/buffer + +With [browserify](http://browserify.org), simply `require('buffer')` or use the `Buffer` global and you will get this module. + +The goal is to provide an API that is 100% identical to +[node's Buffer API](https://nodejs.org/api/buffer.html). Read the +[official docs](https://nodejs.org/api/buffer.html) for the full list of properties, +instance methods, and class methods that are supported. + +## features + +- Manipulate binary data like a boss, in all browsers! +- Super fast. Backed by Typed Arrays (`Uint8Array`/`ArrayBuffer`, not `Object`) +- Extremely small bundle size (**6.75KB minified + gzipped**, 51.9KB with comments) +- Excellent browser support (Chrome, Firefox, Edge, Safari 9+, IE 11, iOS 9+, Android, etc.) +- Preserves Node API exactly, with one minor difference (see below) +- Square-bracket `buf[4]` notation works! +- Does not modify any browser prototypes or put anything on `window` +- Comprehensive test suite (including all buffer tests from node.js core) + + +## install + +To use this module directly (without browserify), install it: + +```bash +npm install buffer +``` + +This module was previously called **native-buffer-browserify**, but please use **buffer** +from now on. + +A standalone bundle is available [here](https://wzrd.in/standalone/buffer), for non-browserify users. + + +## usage + +The module's API is identical to node's `Buffer` API. Read the +[official docs](https://nodejs.org/api/buffer.html) for the full list of properties, +instance methods, and class methods that are supported. + +As mentioned above, `require('buffer')` or use the `Buffer` global with +[browserify](http://browserify.org) and this module will automatically be included +in your bundle. Almost any npm module will work in the browser, even if it assumes that +the node `Buffer` API will be available. + +To depend on this module explicitly (without browserify), require it like this: + +```js +var Buffer = require('buffer/').Buffer // note: the trailing slash is important! +``` + +To require this module explicitly, use `require('buffer/')` which tells the node.js module +lookup algorithm (also used by browserify) to use the **npm module** named `buffer` +instead of the **node.js core** module named `buffer`! + + +## how does it work? + +The Buffer constructor returns instances of `Uint8Array` that have their prototype +changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of `Uint8Array`, +so the returned instances will have all the node `Buffer` methods and the +`Uint8Array` methods. Square bracket notation works as expected -- it returns a +single octet. + +The `Uint8Array` prototype remains unmodified. + + +## tracking the latest node api + +This module tracks the Buffer API in the latest (unstable) version of node.js. The Buffer +API is considered **stable** in the +[node stability index](https://nodejs.org/docs/latest/api/documentation.html#documentation_stability_index), +so it is unlikely that there will ever be breaking changes. +Nonetheless, when/if the Buffer API changes in node, this module's API will change +accordingly. + +## related packages + +- [`buffer-reverse`](https://www.npmjs.com/package/buffer-reverse) - Reverse a buffer +- [`buffer-xor`](https://www.npmjs.com/package/buffer-xor) - Bitwise xor a buffer +- [`is-buffer`](https://www.npmjs.com/package/is-buffer) - Determine if an object is a Buffer without including the whole `Buffer` package + +## conversion packages + +### convert typed array to buffer + +Use [`typedarray-to-buffer`](https://www.npmjs.com/package/typedarray-to-buffer) to convert any kind of typed array to a `Buffer`. Does not perform a copy, so it's super fast. + +### convert buffer to typed array + +`Buffer` is a subclass of `Uint8Array` (which is a typed array). So there is no need to explicitly convert to typed array. Just use the buffer as a `Uint8Array`. + +### convert blob to buffer + +Use [`blob-to-buffer`](https://www.npmjs.com/package/blob-to-buffer) to convert a `Blob` to a `Buffer`. + +### convert buffer to blob + +To convert a `Buffer` to a `Blob`, use the `Blob` constructor: + +```js +var blob = new Blob([ buffer ]) +``` + +Optionally, specify a mimetype: + +```js +var blob = new Blob([ buffer ], { type: 'text/html' }) +``` + +### convert arraybuffer to buffer + +To convert an `ArrayBuffer` to a `Buffer`, use the `Buffer.from` function. Does not perform a copy, so it's super fast. + +```js +var buffer = Buffer.from(arrayBuffer) +``` + +### convert buffer to arraybuffer + +To convert a `Buffer` to an `ArrayBuffer`, use the `.buffer` property (which is present on all `Uint8Array` objects): + +```js +var arrayBuffer = buffer.buffer.slice( + buffer.byteOffset, buffer.byteOffset + buffer.byteLength +) +``` + +Alternatively, use the [`to-arraybuffer`](https://www.npmjs.com/package/to-arraybuffer) module. + +## performance + +See perf tests in `/perf`. + +`BrowserBuffer` is the browser `buffer` module (this repo). `Uint8Array` is included as a +sanity check (since `BrowserBuffer` uses `Uint8Array` under the hood, `Uint8Array` will +always be at least a bit faster). Finally, `NodeBuffer` is the node.js buffer module, +which is included to compare against. + +NOTE: Performance has improved since these benchmarks were taken. PR welcome to update the README. + +### Chrome 38 + +| Method | Operations | Accuracy | Sampled | Fastest | +|:-------|:-----------|:---------|:--------|:-------:| +| BrowserBuffer#bracket-notation | 11,457,464 ops/sec | ±0.86% | 66 | ✓ | +| Uint8Array#bracket-notation | 10,824,332 ops/sec | ±0.74% | 65 | | +| | | | | +| BrowserBuffer#concat | 450,532 ops/sec | ±0.76% | 68 | | +| Uint8Array#concat | 1,368,911 ops/sec | ±1.50% | 62 | ✓ | +| | | | | +| BrowserBuffer#copy(16000) | 903,001 ops/sec | ±0.96% | 67 | | +| Uint8Array#copy(16000) | 1,422,441 ops/sec | ±1.04% | 66 | ✓ | +| | | | | +| BrowserBuffer#copy(16) | 11,431,358 ops/sec | ±0.46% | 69 | | +| Uint8Array#copy(16) | 13,944,163 ops/sec | ±1.12% | 68 | ✓ | +| | | | | +| BrowserBuffer#new(16000) | 106,329 ops/sec | ±6.70% | 44 | | +| Uint8Array#new(16000) | 131,001 ops/sec | ±2.85% | 31 | ✓ | +| | | | | +| BrowserBuffer#new(16) | 1,554,491 ops/sec | ±1.60% | 65 | | +| Uint8Array#new(16) | 6,623,930 ops/sec | ±1.66% | 65 | ✓ | +| | | | | +| BrowserBuffer#readDoubleBE | 112,830 ops/sec | ±0.51% | 69 | ✓ | +| DataView#getFloat64 | 93,500 ops/sec | ±0.57% | 68 | | +| | | | | +| BrowserBuffer#readFloatBE | 146,678 ops/sec | ±0.95% | 68 | ✓ | +| DataView#getFloat32 | 99,311 ops/sec | ±0.41% | 67 | | +| | | | | +| BrowserBuffer#readUInt32LE | 843,214 ops/sec | ±0.70% | 69 | ✓ | +| DataView#getUint32 | 103,024 ops/sec | ±0.64% | 67 | | +| | | | | +| BrowserBuffer#slice | 1,013,941 ops/sec | ±0.75% | 67 | | +| Uint8Array#subarray | 1,903,928 ops/sec | ±0.53% | 67 | ✓ | +| | | | | +| BrowserBuffer#writeFloatBE | 61,387 ops/sec | ±0.90% | 67 | | +| DataView#setFloat32 | 141,249 ops/sec | ±0.40% | 66 | ✓ | + + +### Firefox 33 + +| Method | Operations | Accuracy | Sampled | Fastest | +|:-------|:-----------|:---------|:--------|:-------:| +| BrowserBuffer#bracket-notation | 20,800,421 ops/sec | ±1.84% | 60 | | +| Uint8Array#bracket-notation | 20,826,235 ops/sec | ±2.02% | 61 | ✓ | +| | | | | +| BrowserBuffer#concat | 153,076 ops/sec | ±2.32% | 61 | | +| Uint8Array#concat | 1,255,674 ops/sec | ±8.65% | 52 | ✓ | +| | | | | +| BrowserBuffer#copy(16000) | 1,105,312 ops/sec | ±1.16% | 63 | | +| Uint8Array#copy(16000) | 1,615,911 ops/sec | ±0.55% | 66 | ✓ | +| | | | | +| BrowserBuffer#copy(16) | 16,357,599 ops/sec | ±0.73% | 68 | | +| Uint8Array#copy(16) | 31,436,281 ops/sec | ±1.05% | 68 | ✓ | +| | | | | +| BrowserBuffer#new(16000) | 52,995 ops/sec | ±6.01% | 35 | | +| Uint8Array#new(16000) | 87,686 ops/sec | ±5.68% | 45 | ✓ | +| | | | | +| BrowserBuffer#new(16) | 252,031 ops/sec | ±1.61% | 66 | | +| Uint8Array#new(16) | 8,477,026 ops/sec | ±0.49% | 68 | ✓ | +| | | | | +| BrowserBuffer#readDoubleBE | 99,871 ops/sec | ±0.41% | 69 | | +| DataView#getFloat64 | 285,663 ops/sec | ±0.70% | 68 | ✓ | +| | | | | +| BrowserBuffer#readFloatBE | 115,540 ops/sec | ±0.42% | 69 | | +| DataView#getFloat32 | 288,722 ops/sec | ±0.82% | 68 | ✓ | +| | | | | +| BrowserBuffer#readUInt32LE | 633,926 ops/sec | ±1.08% | 67 | ✓ | +| DataView#getUint32 | 294,808 ops/sec | ±0.79% | 64 | | +| | | | | +| BrowserBuffer#slice | 349,425 ops/sec | ±0.46% | 69 | | +| Uint8Array#subarray | 5,965,819 ops/sec | ±0.60% | 65 | ✓ | +| | | | | +| BrowserBuffer#writeFloatBE | 59,980 ops/sec | ±0.41% | 67 | | +| DataView#setFloat32 | 317,634 ops/sec | ±0.63% | 68 | ✓ | + +### Safari 8 + +| Method | Operations | Accuracy | Sampled | Fastest | +|:-------|:-----------|:---------|:--------|:-------:| +| BrowserBuffer#bracket-notation | 10,279,729 ops/sec | ±2.25% | 56 | ✓ | +| Uint8Array#bracket-notation | 10,030,767 ops/sec | ±2.23% | 59 | | +| | | | | +| BrowserBuffer#concat | 144,138 ops/sec | ±1.38% | 65 | | +| Uint8Array#concat | 4,950,764 ops/sec | ±1.70% | 63 | ✓ | +| | | | | +| BrowserBuffer#copy(16000) | 1,058,548 ops/sec | ±1.51% | 64 | | +| Uint8Array#copy(16000) | 1,409,666 ops/sec | ±1.17% | 65 | ✓ | +| | | | | +| BrowserBuffer#copy(16) | 6,282,529 ops/sec | ±1.88% | 58 | | +| Uint8Array#copy(16) | 11,907,128 ops/sec | ±2.87% | 58 | ✓ | +| | | | | +| BrowserBuffer#new(16000) | 101,663 ops/sec | ±3.89% | 57 | | +| Uint8Array#new(16000) | 22,050,818 ops/sec | ±6.51% | 46 | ✓ | +| | | | | +| BrowserBuffer#new(16) | 176,072 ops/sec | ±2.13% | 64 | | +| Uint8Array#new(16) | 24,385,731 ops/sec | ±5.01% | 51 | ✓ | +| | | | | +| BrowserBuffer#readDoubleBE | 41,341 ops/sec | ±1.06% | 67 | | +| DataView#getFloat64 | 322,280 ops/sec | ±0.84% | 68 | ✓ | +| | | | | +| BrowserBuffer#readFloatBE | 46,141 ops/sec | ±1.06% | 65 | | +| DataView#getFloat32 | 337,025 ops/sec | ±0.43% | 69 | ✓ | +| | | | | +| BrowserBuffer#readUInt32LE | 151,551 ops/sec | ±1.02% | 66 | | +| DataView#getUint32 | 308,278 ops/sec | ±0.94% | 67 | ✓ | +| | | | | +| BrowserBuffer#slice | 197,365 ops/sec | ±0.95% | 66 | | +| Uint8Array#subarray | 9,558,024 ops/sec | ±3.08% | 58 | ✓ | +| | | | | +| BrowserBuffer#writeFloatBE | 17,518 ops/sec | ±1.03% | 63 | | +| DataView#setFloat32 | 319,751 ops/sec | ±0.48% | 68 | ✓ | + + +### Node 0.11.14 + +| Method | Operations | Accuracy | Sampled | Fastest | +|:-------|:-----------|:---------|:--------|:-------:| +| BrowserBuffer#bracket-notation | 10,489,828 ops/sec | ±3.25% | 90 | | +| Uint8Array#bracket-notation | 10,534,884 ops/sec | ±0.81% | 92 | ✓ | +| NodeBuffer#bracket-notation | 10,389,910 ops/sec | ±0.97% | 87 | | +| | | | | +| BrowserBuffer#concat | 487,830 ops/sec | ±2.58% | 88 | | +| Uint8Array#concat | 1,814,327 ops/sec | ±1.28% | 88 | ✓ | +| NodeBuffer#concat | 1,636,523 ops/sec | ±1.88% | 73 | | +| | | | | +| BrowserBuffer#copy(16000) | 1,073,665 ops/sec | ±0.77% | 90 | | +| Uint8Array#copy(16000) | 1,348,517 ops/sec | ±0.84% | 89 | ✓ | +| NodeBuffer#copy(16000) | 1,289,533 ops/sec | ±0.82% | 93 | | +| | | | | +| BrowserBuffer#copy(16) | 12,782,706 ops/sec | ±0.74% | 85 | | +| Uint8Array#copy(16) | 14,180,427 ops/sec | ±0.93% | 92 | ✓ | +| NodeBuffer#copy(16) | 11,083,134 ops/sec | ±1.06% | 89 | | +| | | | | +| BrowserBuffer#new(16000) | 141,678 ops/sec | ±3.30% | 67 | | +| Uint8Array#new(16000) | 161,491 ops/sec | ±2.96% | 60 | | +| NodeBuffer#new(16000) | 292,699 ops/sec | ±3.20% | 55 | ✓ | +| | | | | +| BrowserBuffer#new(16) | 1,655,466 ops/sec | ±2.41% | 82 | | +| Uint8Array#new(16) | 14,399,926 ops/sec | ±0.91% | 94 | ✓ | +| NodeBuffer#new(16) | 3,894,696 ops/sec | ±0.88% | 92 | | +| | | | | +| BrowserBuffer#readDoubleBE | 109,582 ops/sec | ±0.75% | 93 | ✓ | +| DataView#getFloat64 | 91,235 ops/sec | ±0.81% | 90 | | +| NodeBuffer#readDoubleBE | 88,593 ops/sec | ±0.96% | 81 | | +| | | | | +| BrowserBuffer#readFloatBE | 139,854 ops/sec | ±1.03% | 85 | ✓ | +| DataView#getFloat32 | 98,744 ops/sec | ±0.80% | 89 | | +| NodeBuffer#readFloatBE | 92,769 ops/sec | ±0.94% | 93 | | +| | | | | +| BrowserBuffer#readUInt32LE | 710,861 ops/sec | ±0.82% | 92 | | +| DataView#getUint32 | 117,893 ops/sec | ±0.84% | 91 | | +| NodeBuffer#readUInt32LE | 851,412 ops/sec | ±0.72% | 93 | ✓ | +| | | | | +| BrowserBuffer#slice | 1,673,877 ops/sec | ±0.73% | 94 | | +| Uint8Array#subarray | 6,919,243 ops/sec | ±0.67% | 90 | ✓ | +| NodeBuffer#slice | 4,617,604 ops/sec | ±0.79% | 93 | | +| | | | | +| BrowserBuffer#writeFloatBE | 66,011 ops/sec | ±0.75% | 93 | | +| DataView#setFloat32 | 127,760 ops/sec | ±0.72% | 93 | ✓ | +| NodeBuffer#writeFloatBE | 103,352 ops/sec | ±0.83% | 93 | | + +### iojs 1.8.1 + +| Method | Operations | Accuracy | Sampled | Fastest | +|:-------|:-----------|:---------|:--------|:-------:| +| BrowserBuffer#bracket-notation | 10,990,488 ops/sec | ±1.11% | 91 | | +| Uint8Array#bracket-notation | 11,268,757 ops/sec | ±0.65% | 97 | | +| NodeBuffer#bracket-notation | 11,353,260 ops/sec | ±0.83% | 94 | ✓ | +| | | | | +| BrowserBuffer#concat | 378,954 ops/sec | ±0.74% | 94 | | +| Uint8Array#concat | 1,358,288 ops/sec | ±0.97% | 87 | | +| NodeBuffer#concat | 1,934,050 ops/sec | ±1.11% | 78 | ✓ | +| | | | | +| BrowserBuffer#copy(16000) | 894,538 ops/sec | ±0.56% | 84 | | +| Uint8Array#copy(16000) | 1,442,656 ops/sec | ±0.71% | 96 | | +| NodeBuffer#copy(16000) | 1,457,898 ops/sec | ±0.53% | 92 | ✓ | +| | | | | +| BrowserBuffer#copy(16) | 12,870,457 ops/sec | ±0.67% | 95 | | +| Uint8Array#copy(16) | 16,643,989 ops/sec | ±0.61% | 93 | ✓ | +| NodeBuffer#copy(16) | 14,885,848 ops/sec | ±0.74% | 94 | | +| | | | | +| BrowserBuffer#new(16000) | 109,264 ops/sec | ±4.21% | 63 | | +| Uint8Array#new(16000) | 138,916 ops/sec | ±1.87% | 61 | | +| NodeBuffer#new(16000) | 281,449 ops/sec | ±3.58% | 51 | ✓ | +| | | | | +| BrowserBuffer#new(16) | 1,362,935 ops/sec | ±0.56% | 99 | | +| Uint8Array#new(16) | 6,193,090 ops/sec | ±0.64% | 95 | ✓ | +| NodeBuffer#new(16) | 4,745,425 ops/sec | ±1.56% | 90 | | +| | | | | +| BrowserBuffer#readDoubleBE | 118,127 ops/sec | ±0.59% | 93 | ✓ | +| DataView#getFloat64 | 107,332 ops/sec | ±0.65% | 91 | | +| NodeBuffer#readDoubleBE | 116,274 ops/sec | ±0.94% | 95 | | +| | | | | +| BrowserBuffer#readFloatBE | 150,326 ops/sec | ±0.58% | 95 | ✓ | +| DataView#getFloat32 | 110,541 ops/sec | ±0.57% | 98 | | +| NodeBuffer#readFloatBE | 121,599 ops/sec | ±0.60% | 87 | | +| | | | | +| BrowserBuffer#readUInt32LE | 814,147 ops/sec | ±0.62% | 93 | | +| DataView#getUint32 | 137,592 ops/sec | ±0.64% | 90 | | +| NodeBuffer#readUInt32LE | 931,650 ops/sec | ±0.71% | 96 | ✓ | +| | | | | +| BrowserBuffer#slice | 878,590 ops/sec | ±0.68% | 93 | | +| Uint8Array#subarray | 2,843,308 ops/sec | ±1.02% | 90 | | +| NodeBuffer#slice | 4,998,316 ops/sec | ±0.68% | 90 | ✓ | +| | | | | +| BrowserBuffer#writeFloatBE | 65,927 ops/sec | ±0.74% | 93 | | +| DataView#setFloat32 | 139,823 ops/sec | ±0.97% | 89 | ✓ | +| NodeBuffer#writeFloatBE | 135,763 ops/sec | ±0.65% | 96 | | +| | | | | + +## Testing the project + +First, install the project: + + npm install + +Then, to run tests in Node.js, run: + + npm run test-node + +To test locally in a browser, you can run: + + npm run test-browser-es5-local # For ES5 browsers that don't support ES6 + npm run test-browser-es6-local # For ES6 compliant browsers + +This will print out a URL that you can then open in a browser to run the tests, using [airtap](https://www.npmjs.com/package/airtap). + +To run automated browser tests using Saucelabs, ensure that your `SAUCE_USERNAME` and `SAUCE_ACCESS_KEY` environment variables are set, then run: + + npm test + +This is what's run in Travis, to check against various browsers. The list of browsers is kept in the `bin/airtap-es5.yml` and `bin/airtap-es6.yml` files. + +## JavaScript Standard Style + +This module uses [JavaScript Standard Style](https://github.com/feross/standard). + +[![JavaScript Style Guide](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) + +To test that the code conforms to the style, `npm install` and run: + + ./node_modules/.bin/standard + +## credit + +This was originally forked from [buffer-browserify](https://github.com/toots/buffer-browserify). + + +## license + +MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org), and other contributors. Originally forked from an MIT-licensed module by Romain Beauxis. diff --git a/libcore/node_modules/buffer/index.d.ts b/libcore/node_modules/buffer/index.d.ts new file mode 100644 index 0000000..623a661 --- /dev/null +++ b/libcore/node_modules/buffer/index.d.ts @@ -0,0 +1,185 @@ +export class Buffer extends Uint8Array { + length: number + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): { type: 'Buffer', data: any[] }; + equals(otherBuffer: Buffer): boolean; + compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset: number, noAssert?: boolean): number; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeInt8(value: number, offset: number, noAssert?: boolean): number; + writeInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeFloatLE(value: number, offset: number, noAssert?: boolean): number; + writeFloatBE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; + fill(value: any, offset?: number, end?: number): this; + indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; + + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + */ + constructor (str: string, encoding?: string); + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + */ + constructor (size: number); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: Uint8Array); + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + */ + constructor (arrayBuffer: ArrayBuffer); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: any[]); + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + */ + constructor (buffer: Buffer); + prototype: Buffer; + /** + * Allocates a new Buffer using an {array} of octets. + * + * @param array + */ + static from(array: any[]): Buffer; + /** + * When passed a reference to the .buffer property of a TypedArray instance, + * the newly created Buffer will share the same allocated memory as the TypedArray. + * The optional {byteOffset} and {length} arguments specify a memory range + * within the {arrayBuffer} that will be shared by the Buffer. + * + * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() + * @param byteOffset + * @param length + */ + static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; + /** + * Copies the passed {buffer} data onto a new Buffer instance. + * + * @param buffer + */ + static from(buffer: Buffer): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + * + * @param str + */ + static from(str: string, encoding?: string): Buffer; + /** + * Returns true if {obj} is a Buffer + * + * @param obj object to test. + */ + static isBuffer(obj: any): obj is Buffer; + /** + * Returns true if {encoding} is a valid encoding argument. + * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + * + * @param encoding string to test. + */ + static isEncoding(encoding: string): boolean; + /** + * Gives the actual byte length of a string. encoding defaults to 'utf8'. + * This is not the same as String.prototype.length since that returns the number of characters in a string. + * + * @param string string to test. + * @param encoding encoding used to evaluate (defaults to 'utf8') + */ + static byteLength(string: string, encoding?: string): number; + /** + * Returns a buffer which is the result of concatenating all the buffers in the list together. + * + * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. + * If the list has exactly one item, then the first item of the list is returned. + * If the list has more than one item, then a new Buffer is created. + * + * @param list An array of Buffer objects to concatenate + * @param totalLength Total length of the buffers when concatenated. + * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. + */ + static concat(list: Buffer[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + static compare(buf1: Buffer, buf2: Buffer): number; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @param fill if specified, buffer will be initialized by calling buf.fill(fill). + * If parameter is omitted, buffer will be filled with zeros. + * @param encoding encoding used for call to buf.fill while initalizing + */ + static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafe(size: number): Buffer; + /** + * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafeSlow(size: number): Buffer; +} \ No newline at end of file diff --git a/libcore/node_modules/buffer/index.js b/libcore/node_modules/buffer/index.js new file mode 100644 index 0000000..c1719db --- /dev/null +++ b/libcore/node_modules/buffer/index.js @@ -0,0 +1,1777 @@ +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +/* eslint-disable no-proto */ + +'use strict' + +var base64 = require('base64-js') +var ieee754 = require('ieee754') + +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 + +var K_MAX_LENGTH = 0x7fffffff +exports.kMaxLength = K_MAX_LENGTH + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Print warning and recommend using `buffer` v4.x which has an Object + * implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * We report that the browser does not support typed arrays if the are not subclassable + * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` + * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support + * for __proto__ and has a buggy typed array implementation. + */ +Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() + +if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && + typeof console.error === 'function') { + console.error( + 'This browser lacks typed array (Uint8Array) support which is required by ' + + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' + ) +} + +function typedArraySupport () { + // Can typed array instances can be augmented? + try { + var arr = new Uint8Array(1) + arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } } + return arr.foo() === 42 + } catch (e) { + return false + } +} + +Object.defineProperty(Buffer.prototype, 'parent', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.buffer + } +}) + +Object.defineProperty(Buffer.prototype, 'offset', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.byteOffset + } +}) + +function createBuffer (length) { + if (length > K_MAX_LENGTH) { + throw new RangeError('The value "' + length + '" is invalid for option "size"') + } + // Return an augmented `Uint8Array` instance + var buf = new Uint8Array(length) + buf.__proto__ = Buffer.prototype + return buf +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer (arg, encodingOrOffset, length) { + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new TypeError( + 'The "string" argument must be of type string. Received type number' + ) + } + return allocUnsafe(arg) + } + return from(arg, encodingOrOffset, length) +} + +// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 +if (typeof Symbol !== 'undefined' && Symbol.species != null && + Buffer[Symbol.species] === Buffer) { + Object.defineProperty(Buffer, Symbol.species, { + value: null, + configurable: true, + enumerable: false, + writable: false + }) +} + +Buffer.poolSize = 8192 // not used by this implementation + +function from (value, encodingOrOffset, length) { + if (typeof value === 'string') { + return fromString(value, encodingOrOffset) + } + + if (ArrayBuffer.isView(value)) { + return fromArrayLike(value) + } + + if (value == null) { + throw TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) + } + + if (isInstance(value, ArrayBuffer) || + (value && isInstance(value.buffer, ArrayBuffer))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof value === 'number') { + throw new TypeError( + 'The "value" argument must not be of type number. Received type number' + ) + } + + var valueOf = value.valueOf && value.valueOf() + if (valueOf != null && valueOf !== value) { + return Buffer.from(valueOf, encodingOrOffset, length) + } + + var b = fromObject(value) + if (b) return b + + if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && + typeof value[Symbol.toPrimitive] === 'function') { + return Buffer.from( + value[Symbol.toPrimitive]('string'), encodingOrOffset, length + ) + } + + throw new TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(value, encodingOrOffset, length) +} + +// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: +// https://github.com/feross/buffer/pull/148 +Buffer.prototype.__proto__ = Uint8Array.prototype +Buffer.__proto__ = Uint8Array + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be of type number') + } else if (size < 0) { + throw new RangeError('The value "' + size + '" is invalid for option "size"') + } +} + +function alloc (size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(size).fill(fill, encoding) + : createBuffer(size).fill(fill) + } + return createBuffer(size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(size, fill, encoding) +} + +function allocUnsafe (size) { + assertSize(size) + return createBuffer(size < 0 ? 0 : checked(size) | 0) +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(size) +} +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(size) +} + +function fromString (string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + + var length = byteLength(string, encoding) | 0 + var buf = createBuffer(length) + + var actual = buf.write(string, encoding) + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + buf = buf.slice(0, actual) + } + + return buf +} + +function fromArrayLike (array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0 + var buf = createBuffer(length) + for (var i = 0; i < length; i += 1) { + buf[i] = array[i] & 255 + } + return buf +} + +function fromArrayBuffer (array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('"offset" is outside of buffer bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('"length" is outside of buffer bounds') + } + + var buf + if (byteOffset === undefined && length === undefined) { + buf = new Uint8Array(array) + } else if (length === undefined) { + buf = new Uint8Array(array, byteOffset) + } else { + buf = new Uint8Array(array, byteOffset, length) + } + + // Return an augmented `Uint8Array` instance + buf.__proto__ = Buffer.prototype + return buf +} + +function fromObject (obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0 + var buf = createBuffer(len) + + if (buf.length === 0) { + return buf + } + + obj.copy(buf, 0, 0, len) + return buf + } + + if (obj.length !== undefined) { + if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { + return createBuffer(0) + } + return fromArrayLike(obj) + } + + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { + return fromArrayLike(obj.data) + } +} + +function checked (length) { + // Note: cannot use `length < K_MAX_LENGTH` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= K_MAX_LENGTH) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') + } + return length | 0 +} + +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) +} + +Buffer.isBuffer = function isBuffer (b) { + return b != null && b._isBuffer === true && + b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false +} + +Buffer.compare = function compare (a, b) { + if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) + if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError( + 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' + ) + } + + if (a === b) return 0 + + var x = a.length + var y = b.length + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} + +Buffer.concat = function concat (list, length) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length + } + } + + var buffer = Buffer.allocUnsafe(length) + var pos = 0 + for (i = 0; i < list.length; ++i) { + var buf = list[i] + if (isInstance(buf, Uint8Array)) { + buf = Buffer.from(buf) + } + if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos) + pos += buf.length + } + return buffer +} + +function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + throw new TypeError( + 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + + 'Received type ' + typeof string + ) + } + + var len = string.length + var mustMatch = (arguments.length > 2 && arguments[2] === true) + if (!mustMatch && len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) { + return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 + } + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} +Buffer.byteLength = byteLength + +function slowToString (encoding, start, end) { + var loweredCase = false + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } +} + +// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) +// to detect a Buffer instance. It's not possible to use `instanceof Buffer` +// reliably in a browserify context because there could be multiple different +// copies of the 'buffer' package in use. This method works even for Buffer +// instances that were created from another copy of the `buffer` package. +// See: https://github.com/feross/buffer/issues/154 +Buffer.prototype._isBuffer = true + +function swap (b, n, m) { + var i = b[n] + b[n] = b[m] + b[m] = i +} + +Buffer.prototype.swap16 = function swap16 () { + var len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this +} + +Buffer.prototype.swap32 = function swap32 () { + var len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this +} + +Buffer.prototype.swap64 = function swap64 () { + var len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this +} + +Buffer.prototype.toString = function toString () { + var length = this.length + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +} + +Buffer.prototype.toLocaleString = Buffer.prototype.toString + +Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +} + +Buffer.prototype.inspect = function inspect () { + var str = '' + var max = exports.INSPECT_MAX_BYTES + str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() + if (this.length > max) str += ' ... ' + return '' +} + +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (isInstance(target, Uint8Array)) { + target = Buffer.from(target, target.offset, target.byteLength) + } + if (!Buffer.isBuffer(target)) { + throw new TypeError( + 'The "target" argument must be one of type Buffer or Uint8Array. ' + + 'Received type ' + (typeof target) + ) + } + + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + var x = thisEnd - thisStart + var y = end - start + var len = Math.min(x, y) + + var thisCopy = this.slice(thisStart, thisEnd) + var targetCopy = target.slice(start, end) + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (numberIsNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1 + var arrLength = arr.length + var valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i + if (dir) { + var foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + var found = true + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +} + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +} + +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +} + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + var strLen = string.length + + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16) + if (numberIsNaN(parsed)) return i + buf[offset + i] = parsed + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset >>> 0 + if (isFinite(length)) { + length = length >>> 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +} + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + var res = [] + + var i = start + while (i < end) { + var firstByte = buf[i] + var codePoint = null + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } + + res.push(codePoint) + i += bytesPerSequence + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000 + +function decodeCodePointsArray (codePoints) { + var len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = '' + var i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res +} + +function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret +} + +function latin1Slice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret +} + +function hexSlice (buf, start, end) { + var len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + var out = '' + for (var i = start; i < end; ++i) { + out += toHex(buf[i]) + } + return out +} + +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + var newBuf = this.subarray(start, end) + // Return an augmented `Uint8Array` instance + newBuf.__proto__ = Buffer.prototype + return newBuf +} + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val +} + +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } + + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val +} + +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} + +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} + +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} + +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} + +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +} + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +} + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) +} + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) +} + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) +} + +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + return offset + 4 +} + +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = 0 + var mul = 1 + var sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = byteLength - 1 + var mul = 1 + var sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + return offset + 4 +} + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +} + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('Index out of range') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + var len = end - start + + if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { + // Use built-in when available, missing from IE11 + this.copyWithin(targetStart, start, end) + } else if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (var i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start] + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, end), + targetStart + ) + } + + return len +} + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + if (val.length === 1) { + var code = val.charCodeAt(0) + if ((encoding === 'utf8' && code < 128) || + encoding === 'latin1') { + // Fast path: If `val` fits into a single byte, use that numeric value. + val = code + } + } + } else if (typeof val === 'number') { + val = val & 255 + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 + + if (!val) val = 0 + + var i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + var bytes = Buffer.isBuffer(val) + ? val + : Buffer.from(val, encoding) + var len = bytes.length + if (len === 0) { + throw new TypeError('The value "' + val + + '" is invalid for argument "value"') + } + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] + } + } + + return this +} + +// HELPER FUNCTIONS +// ================ + +var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g + +function base64clean (str) { + // Node takes equal signs as end of the Base64 encoding + str = str.split('=')[0] + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = str.trim().replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} + +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +function utf8ToBytes (string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} + +function utf16leToBytes (str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray +} + +function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i +} + +// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass +// the `instanceof` check but they should be treated as of that type. +// See: https://github.com/feross/buffer/issues/166 +function isInstance (obj, type) { + return obj instanceof type || + (obj != null && obj.constructor != null && obj.constructor.name != null && + obj.constructor.name === type.name) +} +function numberIsNaN (obj) { + // For IE11 support + return obj !== obj // eslint-disable-line no-self-compare +} diff --git a/libcore/node_modules/buffer/package.json b/libcore/node_modules/buffer/package.json new file mode 100644 index 0000000..aa77ac8 --- /dev/null +++ b/libcore/node_modules/buffer/package.json @@ -0,0 +1,79 @@ +{ + "name": "buffer", + "description": "Node.js Buffer API, for the browser", + "version": "5.2.1", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "http://feross.org" + }, + "bugs": { + "url": "https://github.com/feross/buffer/issues" + }, + "contributors": [ + "Romain Beauxis ", + "James Halliday " + ], + "dependencies": { + "base64-js": "^1.0.2", + "ieee754": "^1.1.4" + }, + "devDependencies": { + "airtap": "0.1.0", + "benchmark": "^2.0.0", + "browserify": "^16.1.0", + "concat-stream": "^1.4.7", + "hyperquest": "^2.0.0", + "is-buffer": "^2.0.0", + "is-nan": "^1.0.1", + "split": "^1.0.0", + "standard": "*", + "tape": "^4.0.0", + "through2": "^2.0.0", + "uglify-js": "^3.4.5" + }, + "homepage": "https://github.com/feross/buffer", + "jspm": { + "map": { + "./index.js": { + "node": "@node/buffer" + } + } + }, + "keywords": [ + "arraybuffer", + "browser", + "browserify", + "buffer", + "compatible", + "dataview", + "uint8array" + ], + "license": "MIT", + "main": "index.js", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "git://github.com/feross/buffer.git" + }, + "scripts": { + "perf": "browserify --debug perf/bracket-notation.js > perf/bundle.js && open perf/index.html", + "perf-node": "node perf/bracket-notation.js && node perf/concat.js && node perf/copy-big.js && node perf/copy.js && node perf/new-big.js && node perf/new.js && node perf/readDoubleBE.js && node perf/readFloatBE.js && node perf/readUInt32LE.js && node perf/slice.js && node perf/writeFloatBE.js", + "size": "browserify -r ./ | uglifyjs -c -m | gzip | wc -c", + "test": "standard && node ./bin/test.js", + "test-browser-es5": "airtap -- test/*.js", + "test-browser-es5-local": "airtap --local -- test/*.js", + "test-browser-es6": "airtap -- test/*.js test/node/*.js", + "test-browser-es6-local": "airtap --local -- test/*.js test/node/*.js", + "test-node": "tape test/*.js test/node/*.js", + "update-authors": "./bin/update-authors.sh" + }, + "standard": { + "ignore": [ + "test/node/**/*.js", + "test/common.js", + "test/_polyfill.js", + "perf/**/*.js" + ] + } +} diff --git a/libcore/node_modules/builtin-status-codes/browser.js b/libcore/node_modules/builtin-status-codes/browser.js new file mode 100644 index 0000000..4ee0d11 --- /dev/null +++ b/libcore/node_modules/builtin-status-codes/browser.js @@ -0,0 +1,64 @@ +module.exports = { + "100": "Continue", + "101": "Switching Protocols", + "102": "Processing", + "200": "OK", + "201": "Created", + "202": "Accepted", + "203": "Non-Authoritative Information", + "204": "No Content", + "205": "Reset Content", + "206": "Partial Content", + "207": "Multi-Status", + "208": "Already Reported", + "226": "IM Used", + "300": "Multiple Choices", + "301": "Moved Permanently", + "302": "Found", + "303": "See Other", + "304": "Not Modified", + "305": "Use Proxy", + "307": "Temporary Redirect", + "308": "Permanent Redirect", + "400": "Bad Request", + "401": "Unauthorized", + "402": "Payment Required", + "403": "Forbidden", + "404": "Not Found", + "405": "Method Not Allowed", + "406": "Not Acceptable", + "407": "Proxy Authentication Required", + "408": "Request Timeout", + "409": "Conflict", + "410": "Gone", + "411": "Length Required", + "412": "Precondition Failed", + "413": "Payload Too Large", + "414": "URI Too Long", + "415": "Unsupported Media Type", + "416": "Range Not Satisfiable", + "417": "Expectation Failed", + "418": "I'm a teapot", + "421": "Misdirected Request", + "422": "Unprocessable Entity", + "423": "Locked", + "424": "Failed Dependency", + "425": "Unordered Collection", + "426": "Upgrade Required", + "428": "Precondition Required", + "429": "Too Many Requests", + "431": "Request Header Fields Too Large", + "451": "Unavailable For Legal Reasons", + "500": "Internal Server Error", + "501": "Not Implemented", + "502": "Bad Gateway", + "503": "Service Unavailable", + "504": "Gateway Timeout", + "505": "HTTP Version Not Supported", + "506": "Variant Also Negotiates", + "507": "Insufficient Storage", + "508": "Loop Detected", + "509": "Bandwidth Limit Exceeded", + "510": "Not Extended", + "511": "Network Authentication Required" +} diff --git a/libcore/node_modules/builtin-status-codes/build.js b/libcore/node_modules/builtin-status-codes/build.js new file mode 100644 index 0000000..8fc305c --- /dev/null +++ b/libcore/node_modules/builtin-status-codes/build.js @@ -0,0 +1,8 @@ +'use strict' + +var fs = require('fs') +var statusCodes = require('./') + +var code = 'module.exports = ' + JSON.stringify(statusCodes, null, 2) + '\n' + +fs.writeFileSync('browser.js', code) diff --git a/libcore/node_modules/builtin-status-codes/index.js b/libcore/node_modules/builtin-status-codes/index.js new file mode 100644 index 0000000..4a158ac --- /dev/null +++ b/libcore/node_modules/builtin-status-codes/index.js @@ -0,0 +1,3 @@ +'use strict' + +module.exports = require('http').STATUS_CODES diff --git a/libcore/node_modules/builtin-status-codes/license b/libcore/node_modules/builtin-status-codes/license new file mode 100644 index 0000000..25c6247 --- /dev/null +++ b/libcore/node_modules/builtin-status-codes/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Ben Drucker (bendrucker.me) + +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. diff --git a/libcore/node_modules/builtin-status-codes/package.json b/libcore/node_modules/builtin-status-codes/package.json new file mode 100644 index 0000000..d20dcd8 --- /dev/null +++ b/libcore/node_modules/builtin-status-codes/package.json @@ -0,0 +1,39 @@ +{ + "name": "builtin-status-codes", + "main": "index.js", + "browser": "browser.js", + "version": "3.0.0", + "description": "The map of HTTP status codes from the builtin http module", + "license": "MIT", + "repository": "bendrucker/builtin-status-codes", + "author": { + "name": "Ben Drucker", + "email": "bvdrucker@gmail.com", + "url": "bendrucker.me" + }, + "scripts": { + "test": "standard && tape test.js", + "build": "node build.js" + }, + "keywords": [ + "http", + "status", + "codes", + "builtin", + "map" + ], + "devDependencies": { + "tape": "^4.0.0", + "standard": "^4.0.0" + }, + "files": [ + "index.js", + "browser.js", + "build.js" + ], + "standard": { + "ignore": [ + "browser.js" + ] + } +} diff --git a/libcore/node_modules/builtin-status-codes/readme.md b/libcore/node_modules/builtin-status-codes/readme.md new file mode 100644 index 0000000..9a2353d --- /dev/null +++ b/libcore/node_modules/builtin-status-codes/readme.md @@ -0,0 +1,31 @@ +# builtin-status-codes [![Build Status](https://travis-ci.org/bendrucker/builtin-status-codes.svg?branch=master)](https://travis-ci.org/bendrucker/builtin-status-codes) + +> The map of HTTP status codes from the builtin http module. Exposes the latest directly from `http` in Node, with a zero-dependencies version for the browser. + + +## Install + +``` +$ npm install --save builtin-status-codes +``` + + +## Usage + +```js +var codes = require('builtin-status-codes') +codes[100] +//=> Continue +``` + +## Build + +To create a new browser build: + +```sh +$ npm run build +``` + +## License + +MIT © [Ben Drucker](http://bendrucker.me) diff --git a/libcore/node_modules/cached-path-relative/History.md b/libcore/node_modules/cached-path-relative/History.md new file mode 100644 index 0000000..e69de29 diff --git a/libcore/node_modules/cached-path-relative/Makefile b/libcore/node_modules/cached-path-relative/Makefile new file mode 100644 index 0000000..5a8f21d --- /dev/null +++ b/libcore/node_modules/cached-path-relative/Makefile @@ -0,0 +1,20 @@ +# +# Vars +# + +BIN = ./node_modules/.bin + +# +# Tasks +# + +node_modules: package.json + @npm install + +test: node_modules + @${BIN}/tape test/* + +validate: node_modules + @${BIN}/standard + +.PHONY: test validate diff --git a/libcore/node_modules/cached-path-relative/Readme.md b/libcore/node_modules/cached-path-relative/Readme.md new file mode 100644 index 0000000..7b3d4c4 --- /dev/null +++ b/libcore/node_modules/cached-path-relative/Readme.md @@ -0,0 +1,41 @@ + +# cached-path-relative + +[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](https://github.com/feross/standard) + +Memoize the results of the path.relative function. `path.relative` can be an expensive operation if it happens a lot, and its results shouldn't change for the same arguments. + +## Installation + + $ npm install cached-path-relative + +## Usage + +Use it just like your normal path.relative, but it's memoized: + +```javascript +var relative = require('cached-path-relative') + + +relative('test/index.js', '.') === '../..' +``` + +## Shim + +If you want to shim path.relative globally so that you can optimize things that don't know about this module (browserify rebuild times are a good use-case here), you can just import the shim: + +`require('cached-path-relative/shim')` + +This will globally shim `path.relative` so that its results are cached. + +## License + +The MIT License + +Copyright © 2016, Weo.io <info@weo.io> + +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. diff --git a/libcore/node_modules/cached-path-relative/lib/index.js b/libcore/node_modules/cached-path-relative/lib/index.js new file mode 100644 index 0000000..cb74bec --- /dev/null +++ b/libcore/node_modules/cached-path-relative/lib/index.js @@ -0,0 +1,43 @@ +/** + * Modules + */ + +var path = require('path') + +/** + * Vars + */ + +var relative = path.relative +var lastCwd = process.cwd() +var cache = Object.create(null) + +/** + * Expose cachedPathRelative + */ + +module.exports = cachedPathRelative + +/** + * cachedPathRelative + */ + +function cachedPathRelative (from, to) { + // If the current working directory changes, we need + // to invalidate the cache + var cwd = process.cwd() + if (cwd !== lastCwd) { + cache = Object.create(null) + lastCwd = cwd + } + + if (cache[from] && cache[from][to]) return cache[from][to] + + var result = relative.call(path, from, to) + + cache[from] = cache[from] || Object.create(null) + cache[from][to] = result + + return result + +} diff --git a/libcore/node_modules/cached-path-relative/package.json b/libcore/node_modules/cached-path-relative/package.json new file mode 100644 index 0000000..9d97c5b --- /dev/null +++ b/libcore/node_modules/cached-path-relative/package.json @@ -0,0 +1,13 @@ +{ + "name": "cached-path-relative", + "description": "Memoize the results of the path.relative function", + "repository": "git://github.com/ashaffer/cached-path-relative.git", + "version": "1.1.0", + "license": "MIT", + "main": "lib/index.js", + "dependencies": {}, + "devDependencies": { + "tape": "^4.2.0", + "standard": "^4.0.0" + } +} diff --git a/libcore/node_modules/cached-path-relative/shim.js b/libcore/node_modules/cached-path-relative/shim.js new file mode 100644 index 0000000..3d3b67a --- /dev/null +++ b/libcore/node_modules/cached-path-relative/shim.js @@ -0,0 +1,12 @@ +/** + * Modules + */ + +var path = require('path') +var cachedPathRelative = require('.') + +/** + * Install shim + */ + +path.relative = cachedPathRelative diff --git a/libcore/node_modules/cached-path-relative/test/index.js b/libcore/node_modules/cached-path-relative/test/index.js new file mode 100644 index 0000000..c0258f9 --- /dev/null +++ b/libcore/node_modules/cached-path-relative/test/index.js @@ -0,0 +1,17 @@ +/** + * Imports + */ + +var relative = require('..') +var path = require('path') +var test = require('tape') + +/** + * Tests + */ + +test('should work', function (t) { + t.equal(relative('test/index.js', '.'), path.relative('test/index.js', '.')) + t.equal(relative('test/index.js', '.'), path.relative('test/index.js', '.')) + t.end() +}) diff --git a/libcore/node_modules/call-bind/.eslintignore b/libcore/node_modules/call-bind/.eslintignore new file mode 100644 index 0000000..404abb2 --- /dev/null +++ b/libcore/node_modules/call-bind/.eslintignore @@ -0,0 +1 @@ +coverage/ diff --git a/libcore/node_modules/call-bind/.eslintrc b/libcore/node_modules/call-bind/.eslintrc new file mode 100644 index 0000000..dfa9a6c --- /dev/null +++ b/libcore/node_modules/call-bind/.eslintrc @@ -0,0 +1,16 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "func-name-matching": 0, + "id-length": 0, + "new-cap": [2, { + "capIsNewExceptions": [ + "GetIntrinsic", + ], + }], + "no-magic-numbers": 0, + }, +} diff --git a/libcore/node_modules/call-bind/.github/FUNDING.yml b/libcore/node_modules/call-bind/.github/FUNDING.yml new file mode 100644 index 0000000..c70c2ec --- /dev/null +++ b/libcore/node_modules/call-bind/.github/FUNDING.yml @@ -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 +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'] diff --git a/libcore/node_modules/call-bind/.nycrc b/libcore/node_modules/call-bind/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/libcore/node_modules/call-bind/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/libcore/node_modules/call-bind/CHANGELOG.md b/libcore/node_modules/call-bind/CHANGELOG.md new file mode 100644 index 0000000..c653f70 --- /dev/null +++ b/libcore/node_modules/call-bind/CHANGELOG.md @@ -0,0 +1,93 @@ +# 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.7](https://github.com/ljharb/call-bind/compare/v1.0.6...v1.0.7) - 2024-02-12 + +### Commits + +- [Refactor] use `es-define-property` [`09b76a0`](https://github.com/ljharb/call-bind/commit/09b76a01634440461d44a80c9924ec4b500f3b03) +- [Deps] update `get-intrinsic`, `set-function-length` [`ad5136d`](https://github.com/ljharb/call-bind/commit/ad5136ddda2a45c590959829ad3dce0c9f4e3590) + +## [v1.0.6](https://github.com/ljharb/call-bind/compare/v1.0.5...v1.0.6) - 2024-02-05 + +### Commits + +- [Dev Deps] update `aud`, `npmignore`, `tape` [`d564d5c`](https://github.com/ljharb/call-bind/commit/d564d5ce3e06a19df4d499c77f8d1a9da44e77aa) +- [Deps] update `get-intrinsic`, `set-function-length` [`cfc2bdc`](https://github.com/ljharb/call-bind/commit/cfc2bdca7b633df0e0e689e6b637f668f1c6792e) +- [Refactor] use `es-errors`, so things that only need those do not need `get-intrinsic` [`64cd289`](https://github.com/ljharb/call-bind/commit/64cd289ae5862c250a4ca80aa8d461047c166af5) +- [meta] add missing `engines.node` [`32a4038`](https://github.com/ljharb/call-bind/commit/32a4038857b62179f7f9b7b3df2c5260036be582) + +## [v1.0.5](https://github.com/ljharb/call-bind/compare/v1.0.4...v1.0.5) - 2023-10-19 + +### Commits + +- [Fix] throw an error on non-functions as early as possible [`f262408`](https://github.com/ljharb/call-bind/commit/f262408f822c840fbc268080f3ad7c429611066d) +- [Deps] update `set-function-length` [`3fff271`](https://github.com/ljharb/call-bind/commit/3fff27145a1e3a76a5b74f1d7c3c43d0fa3b9871) + +## [v1.0.4](https://github.com/ljharb/call-bind/compare/v1.0.3...v1.0.4) - 2023-10-19 + +## [v1.0.3](https://github.com/ljharb/call-bind/compare/v1.0.2...v1.0.3) - 2023-10-19 + +### Commits + +- [actions] reuse common workflows [`a994df6`](https://github.com/ljharb/call-bind/commit/a994df69f401f4bf735a4ccd77029b85d1549453) +- [meta] use `npmignore` to autogenerate an npmignore file [`eef3ef2`](https://github.com/ljharb/call-bind/commit/eef3ef21e1f002790837fedb8af2679c761fbdf5) +- [readme] flesh out content [`1845ccf`](https://github.com/ljharb/call-bind/commit/1845ccfd9976a607884cfc7157c93192cc16cf22) +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`5b47d53`](https://github.com/ljharb/call-bind/commit/5b47d53d2fd74af5ea0a44f1d51e503cd42f7a90) +- [Refactor] use `set-function-length` [`a0e165c`](https://github.com/ljharb/call-bind/commit/a0e165c5dc61db781cbc919b586b1c2b8da0b150) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `tape` [`9c50103`](https://github.com/ljharb/call-bind/commit/9c50103f44137279a817317cf6cc421a658f85b4) +- [meta] simplify "exports" [`019c6d0`](https://github.com/ljharb/call-bind/commit/019c6d06b0e1246ceed8e579f57e44441cbbf6d9) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `safe-publish-latest`, `tape` [`23bd718`](https://github.com/ljharb/call-bind/commit/23bd718a288d3b03042062b4ef5153b3cea83f11) +- [actions] update codecov uploader [`62552d7`](https://github.com/ljharb/call-bind/commit/62552d79cc79e05825e99aaba134ae5b37f33da5) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`ec81665`](https://github.com/ljharb/call-bind/commit/ec81665b300f87eabff597afdc8b8092adfa7afd) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `tape` [`35d67fc`](https://github.com/ljharb/call-bind/commit/35d67fcea883e686650f736f61da5ddca2592de8) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`0266d8d`](https://github.com/ljharb/call-bind/commit/0266d8d2a45086a922db366d0c2932fa463662ff) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `tape` [`43a5b28`](https://github.com/ljharb/call-bind/commit/43a5b28a444e710e1bbf92adb8afb5cf7523a223) +- [Deps] update `define-data-property`, `function-bind`, `get-intrinsic` [`780eb36`](https://github.com/ljharb/call-bind/commit/780eb36552514f8cc99c70821ce698697c2726a5) +- [Dev Deps] update `aud`, `tape` [`90d50ad`](https://github.com/ljharb/call-bind/commit/90d50ad03b061e0268b3380b0065fcaec183dc05) +- [meta] use `prepublishOnly` script for npm 7+ [`44c5433`](https://github.com/ljharb/call-bind/commit/44c5433b7980e02b4870007046407cf6fc543329) +- [Deps] update `get-intrinsic` [`86bfbfc`](https://github.com/ljharb/call-bind/commit/86bfbfcf34afdc6eabc93ce3d408548d0e27d958) +- [Deps] update `get-intrinsic` [`5c53354`](https://github.com/ljharb/call-bind/commit/5c5335489be0294c18cd7a8bb6e08226ee019ff5) +- [actions] update checkout action [`4c393a8`](https://github.com/ljharb/call-bind/commit/4c393a8173b3c8e5b30d5b3297b3b94d48bf87f3) +- [Deps] update `get-intrinsic` [`4e70bde`](https://github.com/ljharb/call-bind/commit/4e70bdec0626acb11616d66250fc14565e716e91) +- [Deps] update `get-intrinsic` [`55ae803`](https://github.com/ljharb/call-bind/commit/55ae803a920bd93c369cd798c20de31f91e9fc60) + +## [v1.0.2](https://github.com/ljharb/call-bind/compare/v1.0.1...v1.0.2) - 2021-01-11 + +### Commits + +- [Fix] properly include the receiver in the bound length [`dbae7bc`](https://github.com/ljharb/call-bind/commit/dbae7bc676c079a0d33c0a43e9ef92cb7b01345d) + +## [v1.0.1](https://github.com/ljharb/call-bind/compare/v1.0.0...v1.0.1) - 2021-01-08 + +### Commits + +- [Tests] migrate tests to Github Actions [`b6db284`](https://github.com/ljharb/call-bind/commit/b6db284c36f8ccd195b88a6764fe84b7223a0da1) +- [meta] do not publish github action workflow files [`ec7fe46`](https://github.com/ljharb/call-bind/commit/ec7fe46e60cfa4764ee943d2755f5e5a366e578e) +- [Fix] preserve original function’s length when possible [`adbceaa`](https://github.com/ljharb/call-bind/commit/adbceaa3cac4b41ea78bb19d7ccdbaaf7e0bdadb) +- [Tests] gather coverage data on every job [`d69e23c`](https://github.com/ljharb/call-bind/commit/d69e23cc65f101ba1d4c19bb07fa8eb0ec624be8) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`2fd3586`](https://github.com/ljharb/call-bind/commit/2fd3586c5d47b335364c14293114c6b625ae1f71) +- [Deps] update `get-intrinsic` [`f23e931`](https://github.com/ljharb/call-bind/commit/f23e9318cc271c2add8bb38cfded85ee7baf8eee) +- [Deps] update `get-intrinsic` [`72d9f44`](https://github.com/ljharb/call-bind/commit/72d9f44e184465ba8dd3fb48260bbcff234985f2) +- [meta] fix FUNDING.yml [`e723573`](https://github.com/ljharb/call-bind/commit/e723573438c5a68dcec31fb5d96ea6b7e4a93be8) +- [eslint] ignore coverage output [`15e76d2`](https://github.com/ljharb/call-bind/commit/15e76d28a5f43e504696401e5b31ebb78ee1b532) +- [meta] add Automatic Rebase and Require Allow Edits workflows [`8fa4dab`](https://github.com/ljharb/call-bind/commit/8fa4dabb23ba3dd7bb92c9571c1241c08b56e4b6) + +## v1.0.0 - 2020-10-30 + +### Commits + +- Initial commit [`306cf98`](https://github.com/ljharb/call-bind/commit/306cf98c7ec9e7ef66b653ec152277ac1381eb50) +- Tests [`e10d0bb`](https://github.com/ljharb/call-bind/commit/e10d0bbdadc7a10ecedc9a1c035112d3e368b8df) +- Implementation [`43852ed`](https://github.com/ljharb/call-bind/commit/43852eda0f187327b7fad2423ca972149a52bd65) +- npm init [`408f860`](https://github.com/ljharb/call-bind/commit/408f860b773a2f610805fd3613d0d71bac1b6249) +- [meta] add Automatic Rebase and Require Allow Edits workflows [`fb349b2`](https://github.com/ljharb/call-bind/commit/fb349b2e48defbec8b5ec8a8395cc8f69f220b13) +- [meta] add `auto-changelog` [`c4001fc`](https://github.com/ljharb/call-bind/commit/c4001fc43031799ef908211c98d3b0fb2b60fde4) +- [meta] add "funding"; create `FUNDING.yml` [`d4d6d29`](https://github.com/ljharb/call-bind/commit/d4d6d2974a14bc2e98830468eda7fe6d6a776717) +- [Tests] add `npm run lint` [`dedfb98`](https://github.com/ljharb/call-bind/commit/dedfb98bd0ecefb08ddb9a94061bd10cde4332af) +- Only apps should have lockfiles [`54ac776`](https://github.com/ljharb/call-bind/commit/54ac77653db45a7361dc153d2f478e743f110650) +- [meta] add `safe-publish-latest` [`9ea8e43`](https://github.com/ljharb/call-bind/commit/9ea8e435b950ce9b705559cd651039f9bf40140f) diff --git a/libcore/node_modules/call-bind/LICENSE b/libcore/node_modules/call-bind/LICENSE new file mode 100644 index 0000000..48f05d0 --- /dev/null +++ b/libcore/node_modules/call-bind/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 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. diff --git a/libcore/node_modules/call-bind/README.md b/libcore/node_modules/call-bind/README.md new file mode 100644 index 0000000..48e9047 --- /dev/null +++ b/libcore/node_modules/call-bind/README.md @@ -0,0 +1,64 @@ +# call-bind [![Version Badge][npm-version-svg]][package-url] + +[![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] + +Robustly `.call.bind()` a function. + +## Getting started + +```sh +npm install --save call-bind +``` + +## Usage/Examples + +```js +const assert = require('assert'); +const callBind = require('call-bind'); +const callBound = require('call-bind/callBound'); + +function f(a, b) { + assert.equal(this, 1); + assert.equal(a, 2); + assert.equal(b, 3); + assert.equal(arguments.length, 2); +} + +const fBound = callBind(f); + +const slice = callBound('Array.prototype.slice'); + +delete Function.prototype.call; +delete Function.prototype.bind; + +fBound(1, 2, 3); + +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-bind +[npm-version-svg]: https://versionbadg.es/ljharb/call-bind.svg +[deps-svg]: https://david-dm.org/ljharb/call-bind.svg +[deps-url]: https://david-dm.org/ljharb/call-bind +[dev-deps-svg]: https://david-dm.org/ljharb/call-bind/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/call-bind#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/call-bind.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/call-bind.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/call-bind.svg +[downloads-url]: https://npm-stat.com/charts.html?package=call-bind +[codecov-image]: https://codecov.io/gh/ljharb/call-bind/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/call-bind/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/call-bind +[actions-url]: https://github.com/ljharb/call-bind/actions diff --git a/libcore/node_modules/call-bind/callBound.js b/libcore/node_modules/call-bind/callBound.js new file mode 100644 index 0000000..8374adf --- /dev/null +++ b/libcore/node_modules/call-bind/callBound.js @@ -0,0 +1,15 @@ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); + +var callBind = require('./'); + +var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf')); + +module.exports = function callBoundIntrinsic(name, allowMissing) { + var intrinsic = GetIntrinsic(name, !!allowMissing); + if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { + return callBind(intrinsic); + } + return intrinsic; +}; diff --git a/libcore/node_modules/call-bind/index.js b/libcore/node_modules/call-bind/index.js new file mode 100644 index 0000000..01c5b3d --- /dev/null +++ b/libcore/node_modules/call-bind/index.js @@ -0,0 +1,35 @@ +'use strict'; + +var bind = require('function-bind'); +var GetIntrinsic = require('get-intrinsic'); +var setFunctionLength = require('set-function-length'); + +var $TypeError = require('es-errors/type'); +var $apply = GetIntrinsic('%Function.prototype.apply%'); +var $call = GetIntrinsic('%Function.prototype.call%'); +var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply); + +var $defineProperty = require('es-define-property'); +var $max = GetIntrinsic('%Math.max%'); + +module.exports = function callBind(originalFunction) { + if (typeof originalFunction !== 'function') { + throw new $TypeError('a function is required'); + } + var func = $reflectApply(bind, $call, arguments); + return setFunctionLength( + func, + 1 + $max(0, originalFunction.length - (arguments.length - 1)), + true + ); +}; + +var applyBind = function applyBind() { + return $reflectApply(bind, $apply, arguments); +}; + +if ($defineProperty) { + $defineProperty(module.exports, 'apply', { value: applyBind }); +} else { + module.exports.apply = applyBind; +} diff --git a/libcore/node_modules/call-bind/package.json b/libcore/node_modules/call-bind/package.json new file mode 100644 index 0000000..5ba88ff --- /dev/null +++ b/libcore/node_modules/call-bind/package.json @@ -0,0 +1,95 @@ +{ + "name": "call-bind", + "version": "1.0.7", + "description": "Robustly `.call.bind()` a function", + "main": "index.js", + "exports": { + ".": "./index.js", + "./callBound": "./callBound.js", + "./package.json": "./package.json" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=auto", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "lint": "eslint --ext=.js,.mjs .", + "postlint": "evalmd README.md", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --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.git" + }, + "keywords": [ + "javascript", + "ecmascript", + "es", + "js", + "callbind", + "callbound", + "call", + "bind", + "bound", + "call-bind", + "call-bound", + "function", + "es-abstract" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/call-bind/issues" + }, + "homepage": "https://github.com/ljharb/call-bind#readme", + "devDependencies": { + "@ljharb/eslint-config": "^21.1.0", + "aud": "^2.0.4", + "auto-changelog": "^2.4.0", + "es-value-fixtures": "^1.4.2", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "for-each": "^0.3.3", + "gopd": "^1.0.1", + "has-strict-mode": "^1.0.1", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "object-inspect": "^1.13.1", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.4" + }, + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "set-function-length": "^1.2.1" + }, + "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" + } +} diff --git a/libcore/node_modules/call-bind/test/callBound.js b/libcore/node_modules/call-bind/test/callBound.js new file mode 100644 index 0000000..c32319d --- /dev/null +++ b/libcore/node_modules/call-bind/test/callBound.js @@ -0,0 +1,54 @@ +'use strict'; + +var test = require('tape'); + +var callBound = require('../callBound'); + +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'); + + // prototype function + t.notEqual(callBound('Object.prototype.toString'), Object.prototype.toString, 'Object.prototype.toString does not yield itself'); + t.notEqual(callBound('%Object.prototype.toString%'), Object.prototype.toString, '%Object.prototype.toString% does not yield itself'); + t.equal(callBound('Object.prototype.toString')(true), Object.prototype.toString.call(true), 'call-bound Object.prototype.toString calls into the original'); + t.equal(callBound('%Object.prototype.toString%')(true), Object.prototype.toString.call(true), 'call-bound %Object.prototype.toString% calls into the original'); + + t['throws']( + function () { callBound('does not exist'); }, + SyntaxError, + 'nonexistent intrinsic throws' + ); + t['throws']( + 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(); +}); diff --git a/libcore/node_modules/call-bind/test/index.js b/libcore/node_modules/call-bind/test/index.js new file mode 100644 index 0000000..1fd4668 --- /dev/null +++ b/libcore/node_modules/call-bind/test/index.js @@ -0,0 +1,80 @@ +'use strict'; + +var callBind = require('../'); +var bind = require('function-bind'); +var gOPD = require('gopd'); +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'); + +/* + * older engines have length nonconfigurable + * in io.js v3, it is configurable except on bound functions, hence the .bind() + */ +var functionsHaveConfigurableLengths = !!( + gOPD + && Object.getOwnPropertyDescriptor + && Object.getOwnPropertyDescriptor(bind.call(function () {}), 'length').configurable +); + +test('callBind', function (t) { + forEach(v.nonFunctions, function (nonFunction) { + t['throws']( + function () { callBind(nonFunction); }, + TypeError, + inspect(nonFunction) + ' is not a function' + ); + }); + + var sentinel = { sentinel: true }; + 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'); + t.deepEqual(func(), [undefined, undefined, undefined], 'unbound func with too few args'); + t.deepEqual(func(1, 2), [undefined, 1, 2], 'unbound func with right args'); + t.deepEqual(func(1, 2, 3), [undefined, 1, 2], 'unbound func with too many args'); + + var bound = callBind(func); + t.equal(bound.length, func.length + 1, 'function length is preserved', { skip: !functionsHaveConfigurableLengths }); + t.deepEqual(bound(), [undefined, undefined, undefined], 'bound func with too few args'); + t.deepEqual(bound(1, 2), [hasStrictMode ? 1 : Object(1), 2, undefined], 'bound func with right args'); + t.deepEqual(bound(1, 2, 3), [hasStrictMode ? 1 : Object(1), 2, 3], 'bound func with too many args'); + + var boundR = callBind(func, sentinel); + t.equal(boundR.length, func.length, 'function length is preserved', { skip: !functionsHaveConfigurableLengths }); + t.deepEqual(boundR(), [sentinel, undefined, undefined], 'bound func with receiver, with too few args'); + t.deepEqual(boundR(1, 2), [sentinel, 1, 2], 'bound func with receiver, with right args'); + t.deepEqual(boundR(1, 2, 3), [sentinel, 1, 2], 'bound func with receiver, with too many args'); + + var boundArg = callBind(func, sentinel, 1); + t.equal(boundArg.length, func.length - 1, 'function length is preserved', { skip: !functionsHaveConfigurableLengths }); + t.deepEqual(boundArg(), [sentinel, 1, undefined], 'bound func with receiver and arg, with too few args'); + t.deepEqual(boundArg(2), [sentinel, 1, 2], 'bound func with receiver and arg, with right arg'); + t.deepEqual(boundArg(2, 3), [sentinel, 1, 2], 'bound func with receiver and arg, with too many args'); + + t.test('callBind.apply', function (st) { + var aBound = callBind.apply(func); + st.deepEqual(aBound(sentinel), [sentinel, undefined, undefined], 'apply-bound func with no args'); + st.deepEqual(aBound(sentinel, [1], 4), [sentinel, 1, undefined], 'apply-bound func with too few args'); + st.deepEqual(aBound(sentinel, [1, 2], 4), [sentinel, 1, 2], 'apply-bound func with right args'); + + var aBoundArg = callBind.apply(func); + st.deepEqual(aBoundArg(sentinel, [1, 2, 3], 4), [sentinel, 1, 2], 'apply-bound func with too many args'); + st.deepEqual(aBoundArg(sentinel, [1, 2], 4), [sentinel, 1, 2], 'apply-bound func with right args'); + st.deepEqual(aBoundArg(sentinel, [1], 4), [sentinel, 1, undefined], 'apply-bound func with too few args'); + + var aBoundR = callBind.apply(func, sentinel); + st.deepEqual(aBoundR([1, 2, 3], 4), [sentinel, 1, 2], 'apply-bound func with receiver and too many args'); + st.deepEqual(aBoundR([1, 2], 4), [sentinel, 1, 2], 'apply-bound func with receiver and right args'); + st.deepEqual(aBoundR([1], 4), [sentinel, 1, undefined], 'apply-bound func with receiver and too few args'); + + st.end(); + }); + + t.end(); +}); diff --git a/libcore/node_modules/catharsis/LICENSE b/libcore/node_modules/catharsis/LICENSE new file mode 100644 index 0000000..6fdbb08 --- /dev/null +++ b/libcore/node_modules/catharsis/LICENSE @@ -0,0 +1,17 @@ +Copyright (c) 2014 Google Inc. +Copyright (c) 2012-2014 Jeff Williams + +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. \ No newline at end of file diff --git a/libcore/node_modules/catharsis/README.md b/libcore/node_modules/catharsis/README.md new file mode 100644 index 0000000..050c3d1 --- /dev/null +++ b/libcore/node_modules/catharsis/README.md @@ -0,0 +1,393 @@ +# Catharsis + +[![Build Status][travis-img]][travis-url] + +[travis-img]: https://travis-ci.com/hegemonic/catharsis.svg?branch=master +[travis-url]: https://travis-ci.com/hegemonic/catharsis + +A JavaScript parser for +[Google Closure Compiler](https://github.com/google/closure-compiler/wiki/Annotating-JavaScript-for-the-Closure-Compiler#type-expressions) +and [JSDoc](https://github.com/jsdoc/jsdoc) type expressions. + +Catharsis is designed to be: + ++ **Accurate**. Catharsis is based on a [PEG.js](https://pegjs.org/) grammar +that's designed to handle any valid type expression. It uses a thorough test +suite to verify the parser's accuracy. ++ **Fast**. Parse results are cached, so the parser is invoked only when +necessary. ++ **Flexible**. Catharsis can convert a parse result back into a type +expression, or into a description of the type expression. In addition, Catharsis +can parse [JSDoc](https://github.com/jsdoc/jsdoc)-style type expressions. + + +## Example + +```js +const catharsis = require('catharsis'); + +// Closure Compiler parsing +const type = '!Object'; +let parsedType; +try { + parsedType = catharsis.parse(type); // {"type":"NameExpression,"name":"Object","nullable":false} +} catch(e) { + console.error('unable to parse %s: %s', type, e); +} + +// JSDoc-style type expressions enabled +const jsdocType = 'string[]'; // Closure Compiler expects Array. +let parsedJsdocType; +try { + parsedJsdocType = catharsis.parse(jsdocType, {jsdoc: true}); +} catch (e) { + console.error('unable to parse %s: %s', jsdocType, e); +} + +// Converting parse results back to type expressions +catharsis.stringify(parsedType); // !Object +catharsis.stringify(parsedJsdocType); // string[] +catharsis.stringify(parsedJsdocType, {restringify: true}); // Array. + +// Converting parse results to descriptions of the type expression +catharsis.describe(parsedType).simple; // non-null Object +catharsis.describe(parsedJsdocType).simple; // Array of string +``` + +See the +[`test/specs` directory](https://github.com/hegemonic/catharsis/tree/master/test/specs) +for more examples of Catharsis' parse results. + +## Methods + +### `parse(typeExpression, options)` + +Parse a type expression, and return the parse results. Throws an error if the +type expression cannot be parsed. + +When called without options, Catharsis attempts to parse type expressions in the +same way as Closure Compiler. When the `jsdoc` option is enabled, Catharsis can +also parse several kinds of type expressions that are permitted in +[JSDoc](https://github.com/jsdoc/jsdoc): + ++ The string `function` is treated as a function type with no parameters. ++ You can omit the period from type applications. For example, +`Array.` and `Array` are parsed in the same way. ++ If can append `[]` to a name expression (for example, `string[]`), it is +interpreted as a type application with the expression `Array` (for example, +`Array.`). ++ Name expressions can contain the characters `#`, `~`, `:`, and `/`. ++ Name expressions can contain a suffix that is similar to a function signature +(for example, `MyClass(foo, bar)`). ++ Name expressions can contain a reserved word. ++ Record types can use types other than name expressions for keys. + +#### Parameters + ++ `type`: A string containing a Closure Compiler type expression. ++ `options`: Options for parsing the type expression. + + `options.jsdoc`: Specifies whether to enable parsing of JSDoc-style type + expressions. Defaults to `false`. + + `options.useCache`: Specifies whether to use the cache of parsed types. + Defaults to `true`. + +#### Returns + +An object containing the parse results. See the +[`test/specs` directory](https://github.com/hegemonic/catharsis/tree/master/test/specs) +for examples of the parse results for different type expressions. + +The object also includes two non-enumerable properties: + ++ `jsdoc`: A boolean that indicates whether the type expression was parsed with +JSDoc support enabled. ++ `typeExpression`: A string that contains the type expression that was parsed. + +### `stringify(parsedType, options)` + +Stringify `parsedType`, and return the type expression. If validation is +enabled, throws an error if the stringified type expression cannot be parsed. + +#### Parameters #### ++ `parsedType`: An object containing a parsed Closure Compiler type expression. ++ `options`: Options for stringifying the parse results. + + `options.cssClass`: Synonym for `options.linkClass`. Deprecated in version + 0.8.0; will be removed in a future version. + + `options.htmlSafe`: Specifies whether to return an HTML-safe string that + replaces left angle brackets (`<`) with the corresponding entity (`<`). + **Note**: Characters in name expressions are not escaped. + + `options.linkClass`: A CSS class to add to HTML links. Used only if + `options.links` is provided. By default, no CSS class is added. + + `options.links`: An object or map whose keys are name expressions and + whose values are URIs. If a name expression matches a key in + `options.links`, the name expression will be wrapped in an HTML `` tag + that links to the URI. If you also specify `options.linkClass`, the `` + tag includes a `class` attribute. **Note**: When using this option, parsed + types are always restringified, and the resulting string is not cached. + + `options.restringify`: Forces Catharsis to restringify the parsed type. If + this option is not specified, and the parsed type object includes a + `typeExpression` property, Catharsis returns the `typeExpression` property + without modification when possible. Defaults to `false`. + + `options.useCache`: Specifies whether to use the cache of stringified type + expressions. Defaults to `true`. + + `options.validate`: Specifies whether to validate the stringified parse + results by attempting to parse them as a type expression. If the stringified + results are not parsable with the default options, you must also provide the + appropriate options to pass to the `parse()` method. Defaults to `false`. + +#### Returns + +A string containing the type expression. + +### `describe(parsedType, options)` + +Convert a parsed type to a description of the type expression. This method is +especially useful if your users are not familiar with the syntax for type +expressions. + +The `describe()` method returns the description in two formats: + ++ **Simple format**. A string that provides a complete description of the type +expression. ++ **Extended format**. An object that separates out some of the details about +the outermost type expression, such as whether the type is optional, nullable, +or repeatable. + +For example, when you call `describe('?function(new:MyObject, string)=')`, the +method returns the following data: + +```js +{ + simple: 'optional nullable function(constructs MyObject, string)', + extended: { + description: 'function(string)', + modifiers: { + functionNew: 'Returns MyObject when called with new.', + functionThis: '', + optional: 'Optional.', + nullable: 'May be null.', + repeatable: '' + }, + returns: '' + } +} +``` + +#### Parameters + ++ `parsedType`: An object containing a parsed Closure Compiler type expression. ++ `options`: Options for creating the description. + + `options.codeClass`: A CSS class to add to the tag that is wrapped around + type names. Used only if you specify `options.codeTag`. By default, no CSS + class is added. + + `options.codeTag`: The name of an HTML tag (for example, `code`) to wrap + around type names. For example, if this option is set to `code`, the type + expression `Array.` would have the simple description + `Array of string`. + + `options.language`: A string identifying the language in which to generate + the description. The identifier should be an + [ISO 639-1 language code](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) + (for example, `en`). It can optionally be followed by a hyphen and an + [ISO 3166-1 alpha-2 country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) + (for example, `en-US`). If you use values other than `en`, you must provide + translation resources in `options.resources`. Defaults to `en`. + + `options.linkClass`: A CSS class to add to HTML links. Used only if + `options.links` is provided. By default, no CSS class is added. + + `options.links`: An object or map whose keys are name expressions and + whose values are URIs. If a name expression matches a key in + `options.links`, the name expression will be wrapped in an HTML `` tag + that links to the URI. If you also specify `options.linkClass`, the `` + tag includes a `class` attribute. **Note**: When you use this option, the + description is not cached. + + `options.resources`: An object that specifies how to describe type + expressions for a given language. The object's property names should use the + same format as `options.language`. Each property should contain an object in + the same format as the translation resources in + [`res/en.json`](https://github.com/hegemonic/catharsis/blob/master/res/en.json). + If you specify a value for `options.resources.en`, that value overrides the + defaults in `res/en.json`. + + `options.useCache`: Specifies whether to use the cache of descriptions. + Defaults to `true`. + +### Returns + +An object with the following properties: + ++ `simple`: A string that provides a complete description of the type +expression. ++ `extended`: An object containing details about the outermost type expression. + + `extended.description`: A string that provides a basic description of the + type expression, excluding the information contained in other properties. + + `extended.modifiers`: Information about modifiers that apply to the type + expression. + + `extended.modifiers.functionNew`: A string that describes what a + function returns when called with `new`. Returned only for function + types. + + `extended.modifiers.functionThis`: A string that describes what the + keyword `this` refers to within a function. Returned only for function + types. + + `extended.modifiers.nullable`: A string that indicates whether the + type is nullable or non-nullable. + + `extended.modifiers.optional`: A string that indicates whether the + type is optional. + + `extended.modifiers.repeatable`: A string that indicates whether the + type can be repeated. + + `extended.returns`: A string that describes the function's return value. + Returned only for function types. + +## Changelog + ++ 0.9.0 (June 2020): + + For the `describe()` and `stringify()` methods, the `options.links` + parameter now accepts either a map or an object. + + Catharsis now requires Node.js 10 or later. ++ 0.8.11 (July 2019): Updated dependencies. ++ 0.8.10 (May 2019): Updated dependencies. ++ 0.8.9 (July 2017): Type expressions that include an `@` sign (for example, +`module:@prefix/mymodule~myCallback`) are now supported. ++ 0.8.8 (April 2016): Corrected the description of type applications other than +arrays that contain a single type (for example, `Promise.`). ++ 0.8.7 (June 2015): + + Record types that use numeric literals as property names (for example, + `{0: string}`) are now parsed correctly. + + Record types with a property that contains a function, with no space after + the preceding colon (for example, `{foo:function()}`), are now parsed + correctly. + + Repeatable function parameters are no longer required to be enclosed in + brackets, regardless of whether JSDoc-style type expressions are enabled. In + addition, the brackets are omitted when stringifying a parsed type + expression. ++ 0.8.6 (December 2014): Improved the description of the unknown type. ++ 0.8.5 (December 2014): Added support for postfix nullable/non-nullable +operators combined with the optional operator (for example, `foo?=`). ++ 0.8.4 (December 2014): JSDoc-style nested arrays (for example, `number[][]`) +are now parsed correctly when JSDoc-style type expressions are enabled. ++ 0.8.3 (October 2014): + + Type applications are no longer required to include a period (`.`) as a + separator, regardless of whether JSDoc-style type expressions are enabled. + + Type unions that are not enclosed in parentheses can now include the + repeatable (`...`) modifier when JSDoc-style type expressions are enabled. + + Name expressions may now be enclosed in single or double quotation marks + when JSDoc-style type expressions are enabled. ++ 0.8.2 (June 2014): Fixed a compatibility issue with the JSDoc fork of Mozilla +Rhino. ++ 0.8.1 (June 2014): Added support for type unions that are not enclosed in +parentheses, and that contain nullable or non-nullable modifiers (for example, +`!string|!number`). ++ 0.8.0 (May 2014): + + Added a `describe()` method, which converts a parsed type to a description + of the type. + + Added a `linkClass` option to the `stringify()` method, and deprecated the + existing `cssClass` option. The `cssClass` option will be removed in a + future release. + + Clarified and corrected several sections in the `README`. ++ 0.7.1 (April 2014): In record types, property names that begin with a keyword +(for example, `undefinedHTML`) are now parsed correctly when JSDoc-style type +expressions are enabled. ++ 0.7.0 (October 2013): + + Repeatable type expressions other than name expressions (for example, + `...function()`) are now parsed and stringified correctly. + + Type expressions that are both repeatable and either nullable or + non-nullable (for example, `...!number`) are now parsed and stringified + correctly. + + Name expressions are now parsed correctly when they match a property name + in an object instance (for example, `constructor`). ++ 0.6.0 (September 2013): Added support for the type expression `function[]` +when JSDoc-style type expressions are enabled. ++ 0.5.6 (April 2013): + + For consistency with Closure Compiler, parentheses are no longer required + around type unions, regardless of whether JSDoc-style type expressions are + enabled. + + For consistency with Closure Compiler, you can now use postfix notation + for the `?` (nullable) and `!` (non-nullable) modifiers. For example, + `?string` and `string?` are now treated as equivalent. + + String literals and numeric literals are now allowed as property names + within name expressions. For example, the name expression `Foo."bar"` is now + parsed correctly. ++ 0.5.5 (April 2013): Corrected a parsing issue with name expressions that end +with a value enclosed in parentheses. ++ 0.5.4 (April 2013): + + Repeatable literals (for example, `...*`) are now parsed correctly. + + When JSDoc-style type expressions are enabled, a name expression can now + contain a value enclosed in parentheses at the end of the name expression + (for example, `MyClass(2)`). ++ 0.5.3 (March 2013): The `parse()` method now correctly parses name expressions +that contain hyphens. ++ 0.5.2 (March 2013): The `parse()` method now correctly parses function types +when JSDoc-style type expressions are enabled. ++ 0.5.1 (March 2013): Newlines and extra spaces are now removed from type +expressions before they are parsed. ++ 0.5.0 (March 2013): + + The `parse()` method's `lenient` option has been renamed to `jsdoc`. + **Note**: This change is not backwards-compatible with previous versions. + + The `stringify()` method now accepts `cssClass` and `links` options, which + you can use to add HTML links to a type expression. ++ 0.4.3 (March 2013): + + The `stringify()` method no longer caches HTML-safe type expressions as if + they were normal type expressions. + + The `stringify()` method's options parameter may now include an + `options.restringify` property, and the behavior of the `options.useCache` + property has changed. ++ 0.4.2 (March 2013): + + When lenient parsing is enabled, name expressions can now contain the + characters `:` and `/`. + + When lenient parsing is enabled, a name expression followed by `[]` (for + example, `string[]`) will be interpreted as a type application with the + expression `Array` (for example, `Array.`). ++ 0.4.1 (March 2013): + + The `parse()` and `stringify()` methods now honor all of the specified + options. + + When lenient parsing is enabled, name expressions can now contain a + reserved word. ++ 0.4.0 (March 2013): + + Catharsis now supports a lenient parsing option that can parse several + kinds of malformed type expressions. See the documentation for details. + + The objects containing parse results are now frozen. + + The objects containing parse results now have two non-enumerable + properties: + + `lenient`: A boolean indicating whether the type expression was parsed + in lenient mode. + + `typeExpression`: A string containing the original type expression. + + The `stringify()` method now honors the `useCache` option. If a parsed + type includes a `typeExpression` property, and `useCache` is not set to + `false`, the stringified type will be identical to the original type + expression. ++ 0.3.1 (March 2013): Type expressions that begin with a reserved word, such as +`integer`, are now parsed correctly. ++ 0.3.0 (March 2013): + + The `parse()` and `stringify()` methods are now synchronous, and the + `parseSync()` and `stringifySync()` methods have been removed. **Note**: + This change is not backwards-compatible with previous versions. + + The parse results now use a significantly different format from previous + versions. The new format is more expressive and is similar, but not + identical, to the format used by the + [doctrine](https://github.com/eslint/doctrine) parser. **Note**: This change + is not backwards-compatible with previous versions. + + Name expressions that contain a reserved word now include a + `reservedWord: true` property. + + Union types that are optional or nullable, or that can be repeated, are + now parsed and stringified correctly. + + Optional function types and record types are now parsed and stringified + correctly. + + Function types now longer include `new` or `this` properties unless the + properties are defined in the type expression. In addition, the `new` and + `this` properties can now use any type expression. + + In record types, the key for a field type can now use any type expression. + + Standalone single-character literals, such as ALL (`*`), are now parsed + and stringified correctly. + + `null` and `undefined` literals with additional properties, such as + `repeatable`, are now stringified correctly. ++ 0.2.0 (November 2012): + + Added `stringify()` and `stringifySync()` methods, which convert a parsed + type to a type expression. + + Simplified the parse results for function signatures. **Note**: This + change is not backwards-compatible with previous versions. + + Corrected minor errors in README.md. ++ 0.1.1 (November 2012): Added `opts` argument to `parse()` and `parseSync()` +methods. **Note**: The change to `parse()` is not backwards-compatible with +previous versions. ++ 0.1.0 (November 2012): Initial release. + +## License + +[MIT license](https://github.com/hegemonic/catharsis/blob/master/LICENSE). diff --git a/libcore/node_modules/catharsis/bin/parse.js b/libcore/node_modules/catharsis/bin/parse.js new file mode 100755 index 0000000..1c93307 --- /dev/null +++ b/libcore/node_modules/catharsis/bin/parse.js @@ -0,0 +1,55 @@ +#!/usr/bin/env node + +// Command-line tool that parses a type expression and dumps a JSON version of the parse tree. +const catharsis = require('../catharsis'); +const path = require('path'); +const util = require('util'); + +const command = path.basename(process.argv[1]); +const typeExpression = process.argv[2]; +const opts = { + describe: false, + jsdoc: false +}; +let parsedType; + +function usage() { + console.log(util.format('Usage:\n %s typeExpression [--jsdoc] [--describe]', command)); +} + +function done(err) { + /* eslint-disable no-process-exit */ + process.exit(err === undefined ? 0 : err); + /* eslint-enable no-process-exit */ +} + +process.argv.slice(3).forEach(arg => { + const parsedArg = arg.replace(/^-{2}/, ''); + + if (opts[parsedArg] !== undefined) { + opts[parsedArg] = true; + } else { + console.error('Unknown option "%s"', arg); + usage(); + done(1); + } +}); + +if (!typeExpression) { + usage(); + done(1); +} else { + try { + parsedType = catharsis.parse(typeExpression, opts); + if (opts.describe) { + parsedType = catharsis.describe(parsedType); + } + } catch (e) { + console.error(util.format('Unable to parse "%s" (exception follows):', typeExpression)); + console.error(e.stack || e.message); + done(1); + } + + console.log(JSON.stringify(parsedType, null, 2)); + done(); +} diff --git a/libcore/node_modules/catharsis/catharsis.js b/libcore/node_modules/catharsis/catharsis.js new file mode 100644 index 0000000..19c5a67 --- /dev/null +++ b/libcore/node_modules/catharsis/catharsis.js @@ -0,0 +1,169 @@ +/** + * Catharsis + * A parser for Google Closure Compiler type expressions, powered by PEG.js. + * + * @author Jeff Williams + * @license MIT + */ + +const describe = require('./lib/describe'); +const { parse } = require('./lib/parser'); +const stringify = require('./lib/stringify'); + +const typeExpressionCache = { + normal: new Map(), + jsdoc: new Map() +}; + +const parsedTypeCache = { + normal: new Map(), + htmlSafe: new Map() +}; + +const descriptionCache = { + normal: new Map() +}; + +function getTypeExpressionCache({useCache, jsdoc}) { + if (useCache === false) { + return null; + } else if (jsdoc === true) { + return typeExpressionCache.jsdoc; + } else { + return typeExpressionCache.normal; + } +} + +function getParsedTypeCache({useCache, links, htmlSafe}) { + if (useCache === false || links !== null || links !== undefined) { + return null; + } else if (htmlSafe === true) { + return parsedTypeCache.htmlSafe; + } else { + return parsedTypeCache.normal; + } +} + +function getDescriptionCache({useCache, links}) { + if (useCache === false || links !== null || links !== undefined) { + return null; + } else { + return descriptionCache.normal; + } +} + +// can't return the original if any of the following are true: +// 1. restringification was requested +// 2. htmlSafe option was requested +// 3. links option was provided +// 4. typeExpression property is missing +function canReturnOriginalExpression(parsedType, {restringify, htmlSafe, links}) { + return restringify !== true && htmlSafe !== true && + (links === null || links === undefined) && + Object.prototype.hasOwnProperty.call(parsedType, 'typeExpression'); +} + +// Add non-enumerable properties to a result object, then freeze it. +function prepareFrozenObject(obj, expr, {jsdoc}) { + Object.defineProperty(obj, 'jsdoc', { + value: jsdoc === true ? jsdoc : false + }); + + if (expr) { + Object.defineProperty(obj, 'typeExpression', { + value: expr + }); + } + + return Object.freeze(obj); +} + +function cachedParse(expr, options) { + const cache = getTypeExpressionCache(options); + let parsedType = cache ? cache.get(expr) : null; + + if (parsedType) { + return parsedType; + } else { + parsedType = parse(expr, options); + parsedType = prepareFrozenObject(parsedType, expr, options); + + if (cache) { + cache.set(expr, parsedType); + } + + return parsedType; + } +} + +function cachedStringify(parsedType, options) { + const cache = getParsedTypeCache(options); + let stringified; + + if (canReturnOriginalExpression(parsedType, options)) { + return parsedType.typeExpression; + } else if (cache) { + stringified = cache.get(parsedType); + if (!stringified) { + stringified = stringify(parsedType, options); + cache.set(parsedType, stringified); + } + + return stringified; + } else { + return stringify(parsedType, options); + } +} + +function cachedDescribe(parsedType, options) { + const cache = getDescriptionCache(options); + let description = cache ? cache.get(parsedType) : null; + + if (description) { + return description; + } else { + description = describe(parsedType, options); + description = prepareFrozenObject(description, null, options); + + if (cache) { + cache.set(parsedType, description); + } + + return description; + } +} + +/* eslint-disable class-methods-use-this */ +class Catharsis { + constructor() { + this.Types = require('./lib/types'); + } + + parse(typeExpr, options = {}) { + typeExpr = typeExpr.replace(/[\r\n]/g, '') + .replace(/\s+/g, ' ') + .trim(); + + return cachedParse(typeExpr, options); + } + + stringify(parsedType, options) { + let result; + + options = options || {}; + + result = cachedStringify(parsedType, options); + if (options.validate) { + this.parse(result, options); + } + + return result; + } + + describe(parsedType, options = {}) { + return cachedDescribe(parsedType, options); + } +} +/* eslint-enable class-methods-use-this */ + +module.exports = new Catharsis(); diff --git a/libcore/node_modules/catharsis/lib/describe.js b/libcore/node_modules/catharsis/lib/describe.js new file mode 100644 index 0000000..53f058a --- /dev/null +++ b/libcore/node_modules/catharsis/lib/describe.js @@ -0,0 +1,563 @@ +const _ = require('lodash'); +const fs = require('fs'); +const path = require('path'); +const stringify = require('./stringify'); +const Types = require('./types'); + +const DEFAULT_OPTIONS = { + language: 'en', + resources: { + en: JSON.parse(fs.readFileSync(path.join(__dirname, '../res/en.json'), 'utf8')) + } +}; + +// order matters for these! +const FUNCTION_DETAILS = ['new', 'this']; +const FUNCTION_DETAILS_VARIABLES = ['functionNew', 'functionThis']; +const MODIFIERS = ['optional', 'nullable', 'repeatable']; + +const TEMPLATE_VARIABLES = [ + 'application', + 'codeTagClose', + 'codeTagOpen', + 'element', + 'field', + 'functionNew', + 'functionParams', + 'functionReturns', + 'functionThis', + 'keyApplication', + 'name', + 'nullable', + 'optional', + 'param', + 'prefix', + 'repeatable', + 'suffix', + 'type' +]; + +const FORMATS = { + EXTENDED: 'extended', + SIMPLE: 'simple' +}; + +function makeTagOpen(codeTag, codeClass) { + let tagOpen = ''; + const tags = codeTag ? codeTag.split(' ') : []; + + tags.forEach(tag => { + const tagClass = codeClass ? ` class="${codeClass}"` : ''; + + tagOpen += `<${tag}${tagClass}>`; + }); + + return tagOpen; +} + +function makeTagClose(codeTag) { + let tagClose = ''; + const tags = codeTag ? codeTag.split(' ') : []; + + tags.reverse(); + tags.forEach(tag => { + tagClose += ``; + }); + + return tagClose; +} + +function reduceMultiple(context, keyName, contextName, translate, previous, current, index, items) { + let key; + + switch (index) { + case 0: + key = '.first.many'; + break; + + case (items.length - 1): + key = '.last.many'; + break; + + default: + key = '.middle.many'; + } + + key = keyName + key; + context[contextName] = items[index]; + + return previous + translate(key, context); +} + +function modifierKind(useLongFormat) { + return useLongFormat ? FORMATS.EXTENDED : FORMATS.SIMPLE; +} + +function buildModifierStrings(describer, modifiers, type, useLongFormat) { + const result = {}; + + modifiers.forEach(modifier => { + const key = modifierKind(useLongFormat); + const modifierStrings = describer[modifier](type[modifier]); + + result[modifier] = modifierStrings[key]; + }); + + return result; +} + +function addModifiers(describer, context, result, type, useLongFormat) { + const keyPrefix = `modifiers.${modifierKind(useLongFormat)}`; + const modifiers = buildModifierStrings(describer, MODIFIERS, type, useLongFormat); + + MODIFIERS.forEach(modifier => { + const modifierText = modifiers[modifier] || ''; + + result.modifiers[modifier] = modifierText; + if (!useLongFormat) { + context[modifier] = modifierText; + } + }); + + context.prefix = describer._translate(`${keyPrefix}.prefix`, context); + context.suffix = describer._translate(`${keyPrefix}.suffix`, context); +} + +function addFunctionModifiers(describer, context, {modifiers}, type, useLongFormat) { + const functionDetails = buildModifierStrings(describer, FUNCTION_DETAILS, type, useLongFormat); + + FUNCTION_DETAILS.forEach((functionDetail, i) => { + const functionExtraInfo = functionDetails[functionDetail] || ''; + const functionDetailsVariable = FUNCTION_DETAILS_VARIABLES[i]; + + modifiers[functionDetailsVariable] = functionExtraInfo; + if (!useLongFormat) { + context[functionDetailsVariable] += functionExtraInfo; + } + }); +} + +// Replace 2+ whitespace characters with a single whitespace character. +function collapseSpaces(string) { + return string.replace(/(\s)+/g, '$1'); +} + +function getApplicationKey({expression}, applications) { + if (applications.length === 1) { + if (/[Aa]rray/.test(expression.name)) { + return 'array'; + } else { + return 'other'; + } + } else if (/[Ss]tring/.test(applications[0].name)) { + // object with string keys + return 'object'; + } else { + // object with non-string keys + return 'objectNonString'; + } +} + +class Result { + constructor() { + this.description = ''; + this.modifiers = { + functionNew: '', + functionThis: '', + optional: '', + nullable: '', + repeatable: '' + }; + this.returns = ''; + } +} + +class Context { + constructor(props) { + props = props || {}; + + TEMPLATE_VARIABLES.forEach(variable => { + this[variable] = props[variable] || ''; + }); + } +} + +class Describer { + constructor(opts) { + let options; + + this._useLongFormat = true; + options = this._options = _.defaults(opts || {}, DEFAULT_OPTIONS); + this._stringifyOptions = _.defaults(options, { _ignoreModifiers: true }); + + // use a dictionary, not a Context object, so we can more easily merge this into Context objects + this._i18nContext = { + codeTagClose: makeTagClose(options.codeTag), + codeTagOpen: makeTagOpen(options.codeTag, options.codeClass) + }; + + // templates start out as strings; we lazily replace them with template functions + this._templates = options.resources[options.language]; + if (!this._templates) { + throw new Error(`I18N resources are not available for the language ${options.language}`); + } + } + + _stringify(type, typeString, useLongFormat) { + const context = new Context({ + type: typeString || stringify(type, this._stringifyOptions) + }); + const result = new Result(); + + addModifiers(this, context, result, type, useLongFormat); + result.description = this._translate('type', context).trim(); + + return result; + } + + _translate(key, context) { + let result; + let templateFunction = _.get(this._templates, key); + + context = context || new Context(); + + if (templateFunction === undefined) { + throw new Error(`The template ${key} does not exist for the ` + + `language ${this._options.language}`); + } + + // compile and cache the template function if necessary + if (typeof templateFunction === 'string') { + // force the templates to use the `context` object + templateFunction = templateFunction.replace(/<%= /g, '<%= context.'); + templateFunction = _.template(templateFunction, {variable: 'context'}); + _.set(this._templates, key, templateFunction); + } + + result = (templateFunction(_.extend(context, this._i18nContext)) || '') + // strip leading spaces + .replace(/^\s+/, ''); + result = collapseSpaces(result); + + return result; + } + + _modifierHelper(key, modifierPrefix = '', context) { + return { + extended: key ? + this._translate(`${modifierPrefix}.${FORMATS.EXTENDED}.${key}`, context) : + '', + simple: key ? + this._translate(`${modifierPrefix}.${FORMATS.SIMPLE}.${key}`, context) : + '' + }; + } + + _translateModifier(key, context) { + return this._modifierHelper(key, 'modifiers', context); + } + + _translateFunctionModifier(key, context) { + return this._modifierHelper(key, 'function', context); + } + + application(type, useLongFormat) { + const applications = type.applications.slice(0); + const context = new Context(); + const key = `application.${getApplicationKey(type, applications)}`; + const result = new Result(); + + addModifiers(this, context, result, type, useLongFormat); + + context.type = this.type(type.expression).description; + context.application = this.type(applications.pop()).description; + context.keyApplication = applications.length ? this.type(applications.pop()).description : ''; + + result.description = this._translate(key, context).trim(); + + return result; + } + + elements(type, useLongFormat) { + const context = new Context(); + const items = type.elements.slice(0); + const result = new Result(); + + addModifiers(this, context, result, type, useLongFormat); + result.description = this._combineMultiple(items, context, 'union', 'element'); + + return result; + } + + new(funcNew) { + const context = new Context({'functionNew': this.type(funcNew).description}); + const key = funcNew ? 'new' : ''; + + return this._translateFunctionModifier(key, context); + } + + nullable(nullable) { + let key; + + switch (nullable) { + case true: + key = 'nullable'; + break; + + case false: + key = 'nonNullable'; + break; + + default: + key = ''; + } + + return this._translateModifier(key); + } + + optional(optional) { + const key = (optional === true) ? 'optional' : ''; + + return this._translateModifier(key); + } + + repeatable(repeatable) { + const key = (repeatable === true) ? 'repeatable' : ''; + + return this._translateModifier(key); + } + + _combineMultiple(items, context, keyName, contextName) { + const result = new Result(); + const self = this; + let strings; + + strings = typeof items[0] === 'string' ? + items.slice(0) : + items.map(item => self.type(item).description); + + switch (strings.length) { + case 0: + // falls through + case 1: + context[contextName] = strings[0] || ''; + result.description = this._translate(`${keyName}.first.one`, context); + break; + case 2: + strings.forEach((item, idx) => { + const key = `${keyName + (idx === 0 ? '.first' : '.last' )}.two`; + + context[contextName] = item; + result.description += self._translate(key, context); + }); + break; + default: + result.description = strings.reduce(reduceMultiple.bind(null, context, keyName, + contextName, this._translate.bind(this)), ''); + } + + return result.description.trim(); + } + + /* eslint-enable no-unused-vars */ + + params(params, functionContext) { + const context = new Context(); + const result = new Result(); + const self = this; + let strings; + + // TODO: this hardcodes the order and placement of functionNew and functionThis; need to move + // this to the template (and also track whether to put a comma after the last modifier) + functionContext = functionContext || {}; + params = params || []; + strings = params.map(param => self.type(param).description); + + if (functionContext.functionThis) { + strings.unshift(functionContext.functionThis); + } + if (functionContext.functionNew) { + strings.unshift(functionContext.functionNew); + } + result.description = this._combineMultiple(strings, context, 'params', 'param'); + + return result; + } + + this(funcThis) { + const context = new Context({'functionThis': this.type(funcThis).description}); + const key = funcThis ? 'this' : ''; + + return this._translateFunctionModifier(key, context); + } + + type(type, useLongFormat) { + let result = new Result(); + + if (useLongFormat === undefined) { + useLongFormat = this._useLongFormat; + } + // ensure we don't use the long format for inner types + this._useLongFormat = false; + + if (!type) { + return result; + } + + switch (type.type) { + case Types.AllLiteral: + result = this._stringify(type, this._translate('all'), useLongFormat); + break; + case Types.FunctionType: + result = this._signature(type, useLongFormat); + break; + case Types.NameExpression: + result = this._stringify(type, null, useLongFormat); + break; + case Types.NullLiteral: + result = this._stringify(type, this._translate('null'), useLongFormat); + break; + case Types.RecordType: + result = this._record(type, useLongFormat); + break; + case Types.TypeApplication: + result = this.application(type, useLongFormat); + break; + case Types.TypeUnion: + result = this.elements(type, useLongFormat); + break; + case Types.UndefinedLiteral: + result = this._stringify(type, this._translate('undefined'), useLongFormat); + break; + case Types.UnknownLiteral: + result = this._stringify(type, this._translate('unknown'), useLongFormat); + break; + default: + throw new Error(`Unknown type: ${JSON.stringify(type)}`); + } + + return result; + } + + _record(type, useLongFormat) { + const context = new Context(); + let items; + const result = new Result(); + + items = this._recordFields(type.fields); + + addModifiers(this, context, result, type, useLongFormat); + result.description = this._combineMultiple(items, context, 'record', 'field'); + + return result; + } + + _recordFields(fields) { + const context = new Context(); + let result = []; + const self = this; + + if (!fields.length) { + return result; + } + + result = fields.map(field => { + const key = `field.${field.value ? 'typed' : 'untyped'}`; + + context.name = self.type(field.key).description; + if (field.value) { + context.type = self.type(field.value).description; + } + + return self._translate(key, context); + }); + + return result; + } + + _getHrefForString(nameString) { + let href = ''; + const links = this._options.links; + + if (!links) { + return href; + } + + // accept a map or an object + if (links instanceof Map) { + href = links.get(nameString); + } else if ({}.hasOwnProperty.call(links, nameString)) { + href = links[nameString]; + } + + return href; + } + + _addLinks(nameString) { + const href = this._getHrefForString(nameString); + let link = nameString; + let linkClass = this._options.linkClass || ''; + + if (href) { + if (linkClass) { + linkClass = ` class="${linkClass}"`; + } + + link = `${nameString}`; + } + + return link; + } + + result(type, useLongFormat) { + const context = new Context(); + const key = `function.${modifierKind(useLongFormat)}.returns`; + const result = new Result(); + + context.type = this.type(type).description; + + addModifiers(this, context, result, type, useLongFormat); + result.description = this._translate(key, context); + + return result; + } + + _signature(type, useLongFormat) { + const context = new Context(); + const kind = modifierKind(useLongFormat); + const result = new Result(); + let returns; + + addModifiers(this, context, result, type, useLongFormat); + addFunctionModifiers(this, context, result, type, useLongFormat); + + context.functionParams = this.params(type.params || [], context).description; + + if (type.result) { + returns = this.result(type.result, useLongFormat); + if (useLongFormat) { + result.returns = returns.description; + } else { + context.functionReturns = returns.description; + } + } + + result.description += this._translate(`function.${kind}.signature`, context).trim(); + + return result; + } +} + +module.exports = (type, options) => { + const simple = new Describer(options).type(type, false); + const extended = new Describer(options).type(type); + + [simple, extended].forEach(result => { + result.description = collapseSpaces(result.description.trim()); + }); + + return { + simple: simple.description, + extended + }; +}; diff --git a/libcore/node_modules/catharsis/lib/parser.js b/libcore/node_modules/catharsis/lib/parser.js new file mode 100644 index 0000000..2b348d8 --- /dev/null +++ b/libcore/node_modules/catharsis/lib/parser.js @@ -0,0 +1,5776 @@ +/* + * Generated by PEG.js 0.10.0. + * + * http://pegjs.org/ + */ + +"use strict"; + +function peg$subclass(child, parent) { + function ctor() { this.constructor = child; } + ctor.prototype = parent.prototype; + child.prototype = new ctor(); +} + +function peg$SyntaxError(message, expected, found, location) { + this.message = message; + this.expected = expected; + this.found = found; + this.location = location; + this.name = "SyntaxError"; + + if (typeof Error.captureStackTrace === "function") { + Error.captureStackTrace(this, peg$SyntaxError); + } +} + +peg$subclass(peg$SyntaxError, Error); + +peg$SyntaxError.buildMessage = function(expected, found) { + var DESCRIBE_EXPECTATION_FNS = { + literal: function(expectation) { + return "\"" + literalEscape(expectation.text) + "\""; + }, + + "class": function(expectation) { + var escapedParts = "", + i; + + for (i = 0; i < expectation.parts.length; i++) { + escapedParts += expectation.parts[i] instanceof Array + ? classEscape(expectation.parts[i][0]) + "-" + classEscape(expectation.parts[i][1]) + : classEscape(expectation.parts[i]); + } + + return "[" + (expectation.inverted ? "^" : "") + escapedParts + "]"; + }, + + any: function(expectation) { + return "any character"; + }, + + end: function(expectation) { + return "end of input"; + }, + + other: function(expectation) { + return expectation.description; + } + }; + + function hex(ch) { + return ch.charCodeAt(0).toString(16).toUpperCase(); + } + + function literalEscape(s) { + return s + .replace(/\\/g, '\\\\') + .replace(/"/g, '\\"') + .replace(/\0/g, '\\0') + .replace(/\t/g, '\\t') + .replace(/\n/g, '\\n') + .replace(/\r/g, '\\r') + .replace(/[\x00-\x0F]/g, function(ch) { return '\\x0' + hex(ch); }) + .replace(/[\x10-\x1F\x7F-\x9F]/g, function(ch) { return '\\x' + hex(ch); }); + } + + function classEscape(s) { + return s + .replace(/\\/g, '\\\\') + .replace(/\]/g, '\\]') + .replace(/\^/g, '\\^') + .replace(/-/g, '\\-') + .replace(/\0/g, '\\0') + .replace(/\t/g, '\\t') + .replace(/\n/g, '\\n') + .replace(/\r/g, '\\r') + .replace(/[\x00-\x0F]/g, function(ch) { return '\\x0' + hex(ch); }) + .replace(/[\x10-\x1F\x7F-\x9F]/g, function(ch) { return '\\x' + hex(ch); }); + } + + function describeExpectation(expectation) { + return DESCRIBE_EXPECTATION_FNS[expectation.type](expectation); + } + + function describeExpected(expected) { + var descriptions = new Array(expected.length), + i, j; + + for (i = 0; i < expected.length; i++) { + descriptions[i] = describeExpectation(expected[i]); + } + + descriptions.sort(); + + if (descriptions.length > 0) { + for (i = 1, j = 1; i < descriptions.length; i++) { + if (descriptions[i - 1] !== descriptions[i]) { + descriptions[j] = descriptions[i]; + j++; + } + } + descriptions.length = j; + } + + switch (descriptions.length) { + case 1: + return descriptions[0]; + + case 2: + return descriptions[0] + " or " + descriptions[1]; + + default: + return descriptions.slice(0, -1).join(", ") + + ", or " + + descriptions[descriptions.length - 1]; + } + } + + function describeFound(found) { + return found ? "\"" + literalEscape(found) + "\"" : "end of input"; + } + + return "Expected " + describeExpected(expected) + " but " + describeFound(found) + " found."; +}; + +function peg$parse(input, options) { + options = options !== void 0 ? options : {}; + + var peg$FAILED = {}, + + peg$startRuleFunctions = { TypeExpression: peg$parseTypeExpression }, + peg$startRuleFunction = peg$parseTypeExpression, + + peg$c0 = function(r, unk) { + let result = unk; + + if (r) { + result = repeatable(result); + } + + return result; + }, + peg$c1 = "?", + peg$c2 = peg$literalExpectation("?", false), + peg$c3 = "!", + peg$c4 = peg$literalExpectation("!", false), + peg$c5 = function(r, prefix, expr) { + let result = expr; + + if (r) { + result = repeatable(result); + } + + return nullable(result, prefix); + }, + peg$c6 = function(expr, optionalPre, postfix, optionalPost) { + let result = expr; + + // we only allow one optional operator + if (optionalPre && optionalPost) { + return null; + } + + // "non-nullable, yet optional" makes no sense, but we allow it + result = nullable(result, postfix); + + if (optionalPre || optionalPost) { + result = optional(result); + } + + return result; + }, + peg$c7 = function(expr, postfix) { + return nullable(expr, postfix); + }, + peg$c8 = function(prefix, expr) { + prefix = prefix || ''; + + return nullable(expr, prefix); + }, + peg$c9 = function(expr, postfix) { + postfix = postfix || ''; + + return nullable(expr, postfix); + }, + peg$c10 = function(expr) { + return repeatable(expr); + }, + peg$c11 = function(lit, opt) { + let result = lit; + + if (opt) { + result = optional(result); + } + + return result; + }, + peg$c12 = function(lit) { + return repeatable(lit); + }, + peg$c13 = "*", + peg$c14 = peg$literalExpectation("*", false), + peg$c15 = function() { + return { + type: Types.AllLiteral + }; + }, + peg$c16 = function() { + return { + type: Types.NullLiteral + }; + }, + peg$c17 = function() { + return { + type: Types.UndefinedLiteral + }; + }, + peg$c18 = "...", + peg$c19 = peg$literalExpectation("...", false), + peg$c20 = function() { + return { + repeatable: true + }; + }, + peg$c21 = "=", + peg$c22 = peg$literalExpectation("=", false), + peg$c23 = function() { + return { + optional: true + }; + }, + peg$c24 = "[]", + peg$c25 = peg$literalExpectation("[]", false), + peg$c26 = function(name, brackets) { + let result; + + function nest(obj) { + return { + type: Types.TypeApplication, + expression: { + type: Types.NameExpression, + name: 'Array' + }, + applications: [obj] + }; + } + + // we only allow this if JSDoc parsing is enabled + if (!options.jsdoc) { + return null; + } + + result = nest(name); + result.applications[0].type = Types.NameExpression; + + for (let i = 0, l = brackets.length - 1; i < l; i++) { + result = nest(result); + } + + return result; + }, + peg$c27 = function(exp, appl, opt) { + let result = {}; + + const nameExp = { + type: Types.NameExpression, + name: exp.name + }; + + if (appl && appl.length) { + result.type = Types.TypeApplication; + result.expression = nameExp; + result.applications = appl; + } else { + result = nameExp; + } + + if (opt) { + result = optional(result); + } + + return result; + }, + peg$c28 = function(t) { + return repeatable(t); + }, + peg$c29 = function(exp, opt) { + let result = { + type: Types.NameExpression, + name: exp.name, + reservedWord: true + }; + + if (opt) { + result = optional(result); + } + + return result; + }, + peg$c30 = ".", + peg$c31 = peg$literalExpectation(".", false), + peg$c32 = "<", + peg$c33 = peg$literalExpectation("<", false), + peg$c34 = ">", + peg$c35 = peg$literalExpectation(">", false), + peg$c36 = function(sep, l) { + return l; + }, + peg$c37 = ",", + peg$c38 = peg$literalExpectation(",", false), + peg$c39 = function(expr, list) { + let result = [expr]; + + for (let i = 0, l = list.length; i < l; i++) { + result.push(list[i][3]); + } + return result; + }, + peg$c40 = function() { + let result; + + // we only allow this if JSDoc parsing is enabled + if (!options.jsdoc) { + return null; + } + + result = { + type: Types.TypeApplication, + expression: { + type: Types.NameExpression, + name: 'Array' + }, + applications: [ + { + type: Types.FunctionType, + params: [] + } + ] + }; + + return result; + }, + peg$c41 = function(sig, opt) { + // signature is required unless JSDoc parsing is enabled + if (!sig && !options.jsdoc) { + return null; + } else if (sig === null) { + sig = { + params: [] + }; + } + + let result = { + type: Types.FunctionType + }; + + Object.keys(sig).forEach(function(key) { + result[key] = sig[key]; + }); + + if (opt) { + result = optional(result); + } + + return result; + }, + peg$c42 = "(", + peg$c43 = peg$literalExpectation("(", false), + peg$c44 = ")", + peg$c45 = peg$literalExpectation(")", false), + peg$c46 = ":", + peg$c47 = peg$literalExpectation(":", false), + peg$c48 = function(sig, returns) { + const result = {}; + + result.params = sig ? sig.params : []; + if (sig && sig['new']) { + result['new'] = sig['new']; + } + if (sig && sig['this']) { + result['this'] = sig['this'] + } + + if (returns && returns[3]) { + result.result = returns[3]; + } + + return result; + }, + peg$c49 = function(funcNew, funcThis, params) { + const result = { + params: params ? params[3] : [], + 'new': funcNew + }; + if (funcThis) { + result['this'] = funcThis[3]; + } + + return result; + }, + peg$c50 = function(funcThis, funcNew, params) { + const result = { + params: params ? params[3] : [], + 'this': funcThis + }; + + if (funcNew) { + result['new'] = funcNew[3]; + } + + return result; + }, + peg$c51 = function(params) { + return { params }; + }, + peg$c52 = "new", + peg$c53 = peg$literalExpectation("new", false), + peg$c54 = function(expr) { return expr; }, + peg$c55 = "this", + peg$c56 = peg$literalExpectation("this", false), + peg$c57 = function(rp) { + return [rp]; + }, + peg$c58 = function(nrp, rp) { + let result = []; + + if (nrp !== '') { + result = nrp; + } + if (rp && rp[3]) { + result.push(rp[3]); + } + return result; + }, + peg$c59 = function(p, list) { + const result = [p]; + + for (let i = 0, l = list.length; i < l; i++) { + result.push(list[i][3]); + } + + return result; + }, + peg$c60 = function(op, list) { + const result = [op]; + + for (let i = 0, l = list.length; i < l; i++) { + result.push(list[i][3]); + } + + return result; + }, + peg$c61 = function(paramType) { return paramType; }, + peg$c62 = function(t) { + t = optional(t); + return t; + }, + peg$c63 = "[", + peg$c64 = peg$literalExpectation("[", false), + peg$c65 = "]", + peg$c66 = peg$literalExpectation("]", false), + peg$c67 = function(t) { + return repeatable(t || ''); + }, + peg$c68 = function() { + return repeatable({}); + }, + peg$c69 = function(t, opt) { + let result = { + type: Types.TypeUnion, + elements: t + }; + + if (opt) { + result = optional(result); + } + + return result; + }, + peg$c70 = function(tu) { + return repeatable(tu); + }, + peg$c71 = function(expr, list) { + const result = [expr]; + + for (let i = 0, l = list.length; i < l; i++) { + result.push(list[i][1]); + } + + return result; + }, + peg$c72 = function(list) { + return { + type: Types.TypeUnion, + elements: list + }; + }, + peg$c73 = "|", + peg$c74 = peg$literalExpectation("|", false), + peg$c75 = function() { + return ''; + }, + peg$c76 = "{", + peg$c77 = peg$literalExpectation("{", false), + peg$c78 = "}", + peg$c79 = peg$literalExpectation("}", false), + peg$c80 = function(list, opt) { + let result = { + type: Types.RecordType, + fields: list || [] + }; + + if (opt) { + result = optional(result); + } + + return result; + }, + peg$c81 = function(type, list) { + const result = [type]; + + list = list || []; + + for (let i = 0, l = list.length; i < l; i++) { + result.push(list[i][3]); + } + + return result; + }, + peg$c82 = function(key, expr) { + const result = { + type: Types.FieldType, + key: key, + value: undefined + }; + + if (expr && expr[3]) { + result.value = expr[3]; + } + + return result; + }, + peg$c83 = function(t) { + if (!options.jsdoc) { + return null; + } + + return t; + }, + peg$c84 = function(lit) { + if (!options.jsdoc) { + return null; + } + + return { + name: `"${lit.join('')}"` + }; + }, + peg$c85 = function(lit) { + if (!options.jsdoc) { + return null; + } + + return { + name: `'${lit.join('')}'` + }; + }, + peg$c86 = function(id, props) { + props = props || ''; + + return { + name: id + props + }; + }, + peg$c87 = function(rw) { + return { + name: rw + }; + }, + peg$c88 = function(lit) { + return `"${lit}"`; + }, + peg$c89 = function(lit) { + return `'${lit}'`; + }, + peg$c90 = "#", + peg$c91 = peg$literalExpectation("#", false), + peg$c92 = "~", + peg$c93 = peg$literalExpectation("~", false), + peg$c94 = "/", + peg$c95 = peg$literalExpectation("/", false), + peg$c96 = function(sep, prop) { + // we only allow '.' unless JSDoc parsing is enabled + if (sep !== '.' && !options.jsdoc) { + return null; + } + + return sep + prop; + }, + peg$c97 = function(name) { return name; }, + peg$c98 = "$", + peg$c99 = peg$literalExpectation("$", false), + peg$c100 = "_", + peg$c101 = peg$literalExpectation("_", false), + peg$c102 = "@", + peg$c103 = peg$literalExpectation("@", false), + peg$c104 = "-", + peg$c105 = peg$literalExpectation("-", false), + peg$c106 = "\u200C", + peg$c107 = peg$literalExpectation("\u200C", false), + peg$c108 = "\u200D", + peg$c109 = peg$literalExpectation("\u200D", false), + peg$c110 = function(parts) { + if (!options.jsdoc) { + return null; + } + + parts = parts || []; + + return `(${parts.join(', ')})`; + + }, + peg$c111 = function(params) { + if (!options.jsdoc) { + return null; + } + + params = params || []; + + return `(${params.join(', ')})`; + }, + peg$c112 = "break", + peg$c113 = peg$literalExpectation("break", false), + peg$c114 = "case", + peg$c115 = peg$literalExpectation("case", false), + peg$c116 = "catch", + peg$c117 = peg$literalExpectation("catch", false), + peg$c118 = "continue", + peg$c119 = peg$literalExpectation("continue", false), + peg$c120 = "debugger", + peg$c121 = peg$literalExpectation("debugger", false), + peg$c122 = "default", + peg$c123 = peg$literalExpectation("default", false), + peg$c124 = "delete", + peg$c125 = peg$literalExpectation("delete", false), + peg$c126 = "do", + peg$c127 = peg$literalExpectation("do", false), + peg$c128 = "else", + peg$c129 = peg$literalExpectation("else", false), + peg$c130 = "finally", + peg$c131 = peg$literalExpectation("finally", false), + peg$c132 = "for", + peg$c133 = peg$literalExpectation("for", false), + peg$c134 = "if", + peg$c135 = peg$literalExpectation("if", false), + peg$c136 = "in", + peg$c137 = peg$literalExpectation("in", false), + peg$c138 = "instanceof", + peg$c139 = peg$literalExpectation("instanceof", false), + peg$c140 = "return", + peg$c141 = peg$literalExpectation("return", false), + peg$c142 = "switch", + peg$c143 = peg$literalExpectation("switch", false), + peg$c144 = "throw", + peg$c145 = peg$literalExpectation("throw", false), + peg$c146 = "try", + peg$c147 = peg$literalExpectation("try", false), + peg$c148 = "typeof", + peg$c149 = peg$literalExpectation("typeof", false), + peg$c150 = "var", + peg$c151 = peg$literalExpectation("var", false), + peg$c152 = "void", + peg$c153 = peg$literalExpectation("void", false), + peg$c154 = "while", + peg$c155 = peg$literalExpectation("while", false), + peg$c156 = "with", + peg$c157 = peg$literalExpectation("with", false), + peg$c158 = function(kw) { + return kw; + }, + peg$c159 = "class", + peg$c160 = peg$literalExpectation("class", false), + peg$c161 = "const", + peg$c162 = peg$literalExpectation("const", false), + peg$c163 = "enum", + peg$c164 = peg$literalExpectation("enum", false), + peg$c165 = "export", + peg$c166 = peg$literalExpectation("export", false), + peg$c167 = "extends", + peg$c168 = peg$literalExpectation("extends", false), + peg$c169 = "import", + peg$c170 = peg$literalExpectation("import", false), + peg$c171 = "super", + peg$c172 = peg$literalExpectation("super", false), + peg$c173 = "implements", + peg$c174 = peg$literalExpectation("implements", false), + peg$c175 = "interface", + peg$c176 = peg$literalExpectation("interface", false), + peg$c177 = "let", + peg$c178 = peg$literalExpectation("let", false), + peg$c179 = "package", + peg$c180 = peg$literalExpectation("package", false), + peg$c181 = "private", + peg$c182 = peg$literalExpectation("private", false), + peg$c183 = "protected", + peg$c184 = peg$literalExpectation("protected", false), + peg$c185 = "public", + peg$c186 = peg$literalExpectation("public", false), + peg$c187 = "static", + peg$c188 = peg$literalExpectation("static", false), + peg$c189 = "yield", + peg$c190 = peg$literalExpectation("yield", false), + peg$c191 = function(frw) { + return frw; + }, + peg$c192 = "\"", + peg$c193 = peg$literalExpectation("\"", false), + peg$c194 = function(str) { + return str; + }, + peg$c195 = "'", + peg$c196 = peg$literalExpectation("'", false), + peg$c197 = function(lit, digits, exp) { + return parseFloat(lit + '.' + (digits || '') + (exp || '')); + }, + peg$c198 = function(digits, exp) { + return parseFloat('.' + digits + (exp || '')); + }, + peg$c199 = function(lit, exp) { + return parseFloat(lit + (exp || '')); + }, + peg$c200 = "0", + peg$c201 = peg$literalExpectation("0", false), + peg$c202 = /^[eE]/, + peg$c203 = peg$classExpectation(["e", "E"], false, false), + peg$c204 = /^[+\-]/, + peg$c205 = peg$classExpectation(["+", "-"], false, false), + peg$c206 = /^[xX]/, + peg$c207 = peg$classExpectation(["x", "X"], false, false), + peg$c208 = function(hex) { + return parseInt('0x' + hex, 16); + }, + peg$c209 = "null", + peg$c210 = peg$literalExpectation("null", false), + peg$c211 = "undefined", + peg$c212 = peg$literalExpectation("undefined", false), + peg$c213 = function() { + return { + type: Types.UnknownLiteral + }; + }, + peg$c214 = "true", + peg$c215 = peg$literalExpectation("true", false), + peg$c216 = "false", + peg$c217 = peg$literalExpectation("false", false), + peg$c218 = "Function", + peg$c219 = peg$literalExpectation("Function", false), + peg$c220 = "function", + peg$c221 = peg$literalExpectation("function", false), + peg$c222 = "\\", + peg$c223 = peg$literalExpectation("\\", false), + peg$c224 = "u", + peg$c225 = peg$literalExpectation("u", false), + peg$c226 = function(hex) { + return String.fromCharCode(parseInt('0x' + hex), 16); + }, + peg$c227 = /^[0-9]/, + peg$c228 = peg$classExpectation([["0", "9"]], false, false), + peg$c229 = /^[1-9]/, + peg$c230 = peg$classExpectation([["1", "9"]], false, false), + peg$c231 = /^[0-9a-fA-F]/, + peg$c232 = peg$classExpectation([["0", "9"], ["a", "f"], ["A", "F"]], false, false), + peg$c233 = peg$otherExpectation("Unicode combining mark"), + peg$c234 = /^[\u0903\u093E\u093F\u0940\u0949\u094A\u094B\u094C\u0982\u0983\u09BE\u09BF\u09C0\u09C7\u09C8\u09CB\u09CC\u09D7\u0A03\u0A3E\u0A3F\u0A40\u0A83\u0ABE\u0ABF\u0AC0\u0AC9\u0ACB\u0ACC\u0B02\u0B03\u0B3E\u0B40\u0B47\u0B48\u0B4B\u0B4C\u0B57\u0BBE\u0BBF\u0BC1\u0BC2\u0BC6\u0BC7\u0BC8\u0BCA\u0BCB\u0BCC\u0BD7\u0C01\u0C02\u0C03\u0C41\u0C42\u0C43\u0C44\u0C82\u0C83\u0CBE\u0CC0\u0CC1\u0CC2\u0CC3\u0CC4\u0CC7\u0CC8\u0CCA\u0CCB\u0CD5\u0CD6\u0D02\u0D03\u0D3E\u0D3F\u0D40\u0D46\u0D47\u0D48\u0D4A\u0D4B\u0D4C\u0D57\u0D82\u0D83\u0DCF\u0DD0\u0DD1\u0DD8\u0DD9\u0DDA\u0DDB\u0DDC\u0DDD\u0DDE\u0DDF\u0DF2\u0DF3\u0F3E\u0F3F\u0F7F\u102B\u102C\u1031\u1038\u103B\u103C\u1056\u1057\u1062\u1063\u1064\u1067\u1068\u1069\u106A\u106B\u106C\u106D\u1083\u1084\u1087\u1088\u1089\u108A\u108B\u108C\u108F\u17B6\u17BE\u17BF\u17C0\u17C1\u17C2\u17C3\u17C4\u17C5\u17C7\u17C8\u1923\u1924\u1925\u1926\u1929\u192A\u192B\u1930\u1931\u1933\u1934\u1935\u1936\u1937\u1938\u19B0\u19B1\u19B2\u19B3\u19B4\u19B5\u19B6\u19B7\u19B8\u19B9\u19BA\u19BB\u19BC\u19BD\u19BE\u19BF\u19C0\u19C8\u19C9\u1A19\u1A1A\u1A1B\u1B04\u1B35\u1B3B\u1B3D\u1B3E\u1B3F\u1B40\u1B41\u1B43\u1B44\u1B82\u1BA1\u1BA6\u1BA7\u1BAA\u1C24\u1C25\u1C26\u1C27\u1C28\u1C29\u1C2A\u1C2B\u1C34\u1C35\uA823\uA824\uA827\uA880\uA881\uA8B4\uA8B5\uA8B6\uA8B7\uA8B8\uA8B9\uA8BA\uA8BB\uA8BC\uA8BD\uA8BE\uA8BF\uA8C0\uA8C1\uA8C2\uA8C3\uA952\uA953\uAA2F\uAA30\uAA33\uAA34\uAA4D]/, + peg$c235 = peg$classExpectation(["\u0903", "\u093E", "\u093F", "\u0940", "\u0949", "\u094A", "\u094B", "\u094C", "\u0982", "\u0983", "\u09BE", "\u09BF", "\u09C0", "\u09C7", "\u09C8", "\u09CB", "\u09CC", "\u09D7", "\u0A03", "\u0A3E", "\u0A3F", "\u0A40", "\u0A83", "\u0ABE", "\u0ABF", "\u0AC0", "\u0AC9", "\u0ACB", "\u0ACC", "\u0B02", "\u0B03", "\u0B3E", "\u0B40", "\u0B47", "\u0B48", "\u0B4B", "\u0B4C", "\u0B57", "\u0BBE", "\u0BBF", "\u0BC1", "\u0BC2", "\u0BC6", "\u0BC7", "\u0BC8", "\u0BCA", "\u0BCB", "\u0BCC", "\u0BD7", "\u0C01", "\u0C02", "\u0C03", "\u0C41", "\u0C42", "\u0C43", "\u0C44", "\u0C82", "\u0C83", "\u0CBE", "\u0CC0", "\u0CC1", "\u0CC2", "\u0CC3", "\u0CC4", "\u0CC7", "\u0CC8", "\u0CCA", "\u0CCB", "\u0CD5", "\u0CD6", "\u0D02", "\u0D03", "\u0D3E", "\u0D3F", "\u0D40", "\u0D46", "\u0D47", "\u0D48", "\u0D4A", "\u0D4B", "\u0D4C", "\u0D57", "\u0D82", "\u0D83", "\u0DCF", "\u0DD0", "\u0DD1", "\u0DD8", "\u0DD9", "\u0DDA", "\u0DDB", "\u0DDC", "\u0DDD", "\u0DDE", "\u0DDF", "\u0DF2", "\u0DF3", "\u0F3E", "\u0F3F", "\u0F7F", "\u102B", "\u102C", "\u1031", "\u1038", "\u103B", "\u103C", "\u1056", "\u1057", "\u1062", "\u1063", "\u1064", "\u1067", "\u1068", "\u1069", "\u106A", "\u106B", "\u106C", "\u106D", "\u1083", "\u1084", "\u1087", "\u1088", "\u1089", "\u108A", "\u108B", "\u108C", "\u108F", "\u17B6", "\u17BE", "\u17BF", "\u17C0", "\u17C1", "\u17C2", "\u17C3", "\u17C4", "\u17C5", "\u17C7", "\u17C8", "\u1923", "\u1924", "\u1925", "\u1926", "\u1929", "\u192A", "\u192B", "\u1930", "\u1931", "\u1933", "\u1934", "\u1935", "\u1936", "\u1937", "\u1938", "\u19B0", "\u19B1", "\u19B2", "\u19B3", "\u19B4", "\u19B5", "\u19B6", "\u19B7", "\u19B8", "\u19B9", "\u19BA", "\u19BB", "\u19BC", "\u19BD", "\u19BE", "\u19BF", "\u19C0", "\u19C8", "\u19C9", "\u1A19", "\u1A1A", "\u1A1B", "\u1B04", "\u1B35", "\u1B3B", "\u1B3D", "\u1B3E", "\u1B3F", "\u1B40", "\u1B41", "\u1B43", "\u1B44", "\u1B82", "\u1BA1", "\u1BA6", "\u1BA7", "\u1BAA", "\u1C24", "\u1C25", "\u1C26", "\u1C27", "\u1C28", "\u1C29", "\u1C2A", "\u1C2B", "\u1C34", "\u1C35", "\uA823", "\uA824", "\uA827", "\uA880", "\uA881", "\uA8B4", "\uA8B5", "\uA8B6", "\uA8B7", "\uA8B8", "\uA8B9", "\uA8BA", "\uA8BB", "\uA8BC", "\uA8BD", "\uA8BE", "\uA8BF", "\uA8C0", "\uA8C1", "\uA8C2", "\uA8C3", "\uA952", "\uA953", "\uAA2F", "\uAA30", "\uAA33", "\uAA34", "\uAA4D"], false, false), + peg$c236 = peg$otherExpectation("Unicode decimal number"), + peg$c237 = /^[0123456789\u0660\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669\u06F0\u06F1\u06F2\u06F3\u06F4\u06F5\u06F6\u06F7\u06F8\u06F9\u07C0\u07C1\u07C2\u07C3\u07C4\u07C5\u07C6\u07C7\u07C8\u07C9\u0966\u0967\u0968\u0969\u096A\u096B\u096C\u096D\u096E\u096F\u09E6\u09E7\u09E8\u09E9\u09EA\u09EB\u09EC\u09ED\u09EE\u09EF\u0A66\u0A67\u0A68\u0A69\u0A6A\u0A6B\u0A6C\u0A6D\u0A6E\u0A6F\u0AE6\u0AE7\u0AE8\u0AE9\u0AEA\u0AEB\u0AEC\u0AED\u0AEE\u0AEF\u0B66\u0B67\u0B68\u0B69\u0B6A\u0B6B\u0B6C\u0B6D\u0B6E\u0B6F\u0BE6\u0BE7\u0BE8\u0BE9\u0BEA\u0BEB\u0BEC\u0BED\u0BEE\u0BEF\u0C66\u0C67\u0C68\u0C69\u0C6A\u0C6B\u0C6C\u0C6D\u0C6E\u0C6F\u0CE6\u0CE7\u0CE8\u0CE9\u0CEA\u0CEB\u0CEC\u0CED\u0CEE\u0CEF\u0D66\u0D67\u0D68\u0D69\u0D6A\u0D6B\u0D6C\u0D6D\u0D6E\u0D6F\u0E50\u0E51\u0E52\u0E53\u0E54\u0E55\u0E56\u0E57\u0E58\u0E59\u0ED0\u0ED1\u0ED2\u0ED3\u0ED4\u0ED5\u0ED6\u0ED7\u0ED8\u0ED9\u0F20\u0F21\u0F22\u0F23\u0F24\u0F25\u0F26\u0F27\u0F28\u0F29\u1040\u1041\u1042\u1043\u1044\u1045\u1046\u1047\u1048\u1049\u1090\u1091\u1092\u1093\u1094\u1095\u1096\u1097\u1098\u1099\u17E0\u17E1\u17E2\u17E3\u17E4\u17E5\u17E6\u17E7\u17E8\u17E9\u1810\u1811\u1812\u1813\u1814\u1815\u1816\u1817\u1818\u1819\u1946\u1947\u1948\u1949\u194A\u194B\u194C\u194D\u194E\u194F\u19D0\u19D1\u19D2\u19D3\u19D4\u19D5\u19D6\u19D7\u19D8\u19D9\u1B50\u1B51\u1B52\u1B53\u1B54\u1B55\u1B56\u1B57\u1B58\u1B59\u1BB0\u1BB1\u1BB2\u1BB3\u1BB4\u1BB5\u1BB6\u1BB7\u1BB8\u1BB9\u1C40\u1C41\u1C42\u1C43\u1C44\u1C45\u1C46\u1C47\u1C48\u1C49\u1C50\u1C51\u1C52\u1C53\u1C54\u1C55\u1C56\u1C57\u1C58\u1C59\uA620\uA621\uA622\uA623\uA624\uA625\uA626\uA627\uA628\uA629\uA8D0\uA8D1\uA8D2\uA8D3\uA8D4\uA8D5\uA8D6\uA8D7\uA8D8\uA8D9\uA900\uA901\uA902\uA903\uA904\uA905\uA906\uA907\uA908\uA909\uAA50\uAA51\uAA52\uAA53\uAA54\uAA55\uAA56\uAA57\uAA58\uAA59\uFF10\uFF11\uFF12\uFF13\uFF14\uFF15\uFF16\uFF17\uFF18\uFF19]/, + peg$c238 = peg$classExpectation(["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "\u0660", "\u0661", "\u0662", "\u0663", "\u0664", "\u0665", "\u0666", "\u0667", "\u0668", "\u0669", "\u06F0", "\u06F1", "\u06F2", "\u06F3", "\u06F4", "\u06F5", "\u06F6", "\u06F7", "\u06F8", "\u06F9", "\u07C0", "\u07C1", "\u07C2", "\u07C3", "\u07C4", "\u07C5", "\u07C6", "\u07C7", "\u07C8", "\u07C9", "\u0966", "\u0967", "\u0968", "\u0969", "\u096A", "\u096B", "\u096C", "\u096D", "\u096E", "\u096F", "\u09E6", "\u09E7", "\u09E8", "\u09E9", "\u09EA", "\u09EB", "\u09EC", "\u09ED", "\u09EE", "\u09EF", "\u0A66", "\u0A67", "\u0A68", "\u0A69", "\u0A6A", "\u0A6B", "\u0A6C", "\u0A6D", "\u0A6E", "\u0A6F", "\u0AE6", "\u0AE7", "\u0AE8", "\u0AE9", "\u0AEA", "\u0AEB", "\u0AEC", "\u0AED", "\u0AEE", "\u0AEF", "\u0B66", "\u0B67", "\u0B68", "\u0B69", "\u0B6A", "\u0B6B", "\u0B6C", "\u0B6D", "\u0B6E", "\u0B6F", "\u0BE6", "\u0BE7", "\u0BE8", "\u0BE9", "\u0BEA", "\u0BEB", "\u0BEC", "\u0BED", "\u0BEE", "\u0BEF", "\u0C66", "\u0C67", "\u0C68", "\u0C69", "\u0C6A", "\u0C6B", "\u0C6C", "\u0C6D", "\u0C6E", "\u0C6F", "\u0CE6", "\u0CE7", "\u0CE8", "\u0CE9", "\u0CEA", "\u0CEB", "\u0CEC", "\u0CED", "\u0CEE", "\u0CEF", "\u0D66", "\u0D67", "\u0D68", "\u0D69", "\u0D6A", "\u0D6B", "\u0D6C", "\u0D6D", "\u0D6E", "\u0D6F", "\u0E50", "\u0E51", "\u0E52", "\u0E53", "\u0E54", "\u0E55", "\u0E56", "\u0E57", "\u0E58", "\u0E59", "\u0ED0", "\u0ED1", "\u0ED2", "\u0ED3", "\u0ED4", "\u0ED5", "\u0ED6", "\u0ED7", "\u0ED8", "\u0ED9", "\u0F20", "\u0F21", "\u0F22", "\u0F23", "\u0F24", "\u0F25", "\u0F26", "\u0F27", "\u0F28", "\u0F29", "\u1040", "\u1041", "\u1042", "\u1043", "\u1044", "\u1045", "\u1046", "\u1047", "\u1048", "\u1049", "\u1090", "\u1091", "\u1092", "\u1093", "\u1094", "\u1095", "\u1096", "\u1097", "\u1098", "\u1099", "\u17E0", "\u17E1", "\u17E2", "\u17E3", "\u17E4", "\u17E5", "\u17E6", "\u17E7", "\u17E8", "\u17E9", "\u1810", "\u1811", "\u1812", "\u1813", "\u1814", "\u1815", "\u1816", "\u1817", "\u1818", "\u1819", "\u1946", "\u1947", "\u1948", "\u1949", "\u194A", "\u194B", "\u194C", "\u194D", "\u194E", "\u194F", "\u19D0", "\u19D1", "\u19D2", "\u19D3", "\u19D4", "\u19D5", "\u19D6", "\u19D7", "\u19D8", "\u19D9", "\u1B50", "\u1B51", "\u1B52", "\u1B53", "\u1B54", "\u1B55", "\u1B56", "\u1B57", "\u1B58", "\u1B59", "\u1BB0", "\u1BB1", "\u1BB2", "\u1BB3", "\u1BB4", "\u1BB5", "\u1BB6", "\u1BB7", "\u1BB8", "\u1BB9", "\u1C40", "\u1C41", "\u1C42", "\u1C43", "\u1C44", "\u1C45", "\u1C46", "\u1C47", "\u1C48", "\u1C49", "\u1C50", "\u1C51", "\u1C52", "\u1C53", "\u1C54", "\u1C55", "\u1C56", "\u1C57", "\u1C58", "\u1C59", "\uA620", "\uA621", "\uA622", "\uA623", "\uA624", "\uA625", "\uA626", "\uA627", "\uA628", "\uA629", "\uA8D0", "\uA8D1", "\uA8D2", "\uA8D3", "\uA8D4", "\uA8D5", "\uA8D6", "\uA8D7", "\uA8D8", "\uA8D9", "\uA900", "\uA901", "\uA902", "\uA903", "\uA904", "\uA905", "\uA906", "\uA907", "\uA908", "\uA909", "\uAA50", "\uAA51", "\uAA52", "\uAA53", "\uAA54", "\uAA55", "\uAA56", "\uAA57", "\uAA58", "\uAA59", "\uFF10", "\uFF11", "\uFF12", "\uFF13", "\uFF14", "\uFF15", "\uFF16", "\uFF17", "\uFF18", "\uFF19"], false, false), + peg$c239 = peg$otherExpectation("Unicode punctuation connector"), + peg$c240 = /^[_\u203F\u2040\u2054\uFE33\uFE34\uFE4D\uFE4E\uFE4F\uFF3F]/, + peg$c241 = peg$classExpectation(["_", "\u203F", "\u2040", "\u2054", "\uFE33", "\uFE34", "\uFE4D", "\uFE4E", "\uFE4F", "\uFF3F"], false, false), + peg$c242 = peg$otherExpectation("Unicode uppercase letter"), + peg$c243 = /^[ABCDEFGHIJKLMNOPQRSTUVWXYZ\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD8\xD9\xDA\xDB\xDC\xDD\xDE\u0100\u0102\u0104\u0106\u0108\u010A\u010C\u010E\u0110\u0112\u0114\u0116\u0118\u011A\u011C\u011E\u0120\u0122\u0124\u0126\u0128\u012A\u012C\u012E\u0130\u0132\u0134\u0136\u0139\u013B\u013D\u013F\u0141\u0143\u0145\u0147\u014A\u014C\u014E\u0150\u0152\u0154\u0156\u0158\u015A\u015C\u015E\u0160\u0162\u0164\u0166\u0168\u016A\u016C\u016E\u0170\u0172\u0174\u0176\u0178\u0179\u017B\u017D\u0181\u0182\u0184\u0186\u0187\u0189\u018A\u018B\u018E\u018F\u0190\u0191\u0193\u0194\u0196\u0197\u0198\u019C\u019D\u019F\u01A0\u01A2\u01A4\u01A6\u01A7\u01A9\u01AC\u01AE\u01AF\u01B1\u01B2\u01B3\u01B5\u01B7\u01B8\u01BC\u01C4\u01C7\u01CA\u01CD\u01CF\u01D1\u01D3\u01D5\u01D7\u01D9\u01DB\u01DE\u01E0\u01E2\u01E4\u01E6\u01E8\u01EA\u01EC\u01EE\u01F1\u01F4\u01F6\u01F7\u01F8\u01FA\u01FC\u01FE\u0200\u0202\u0204\u0206\u0208\u020A\u020C\u020E\u0210\u0212\u0214\u0216\u0218\u021A\u021C\u021E\u0220\u0222\u0224\u0226\u0228\u022A\u022C\u022E\u0230\u0232\u023A\u023B\u023D\u023E\u0241\u0243\u0244\u0245\u0246\u0248\u024A\u024C\u024E\u0370\u0372\u0376\u0386\u0388\u0389\u038A\u038C\u038E\u038F\u0391\u0392\u0393\u0394\u0395\u0396\u0397\u0398\u0399\u039A\u039B\u039C\u039D\u039E\u039F\u03A0\u03A1\u03A3\u03A4\u03A5\u03A6\u03A7\u03A8\u03A9\u03AA\u03AB\u03CF\u03D2\u03D3\u03D4\u03D8\u03DA\u03DC\u03DE\u03E0\u03E2\u03E4\u03E6\u03E8\u03EA\u03EC\u03EE\u03F4\u03F7\u03F9\u03FA\u03FD\u03FE\u03FF\u0400\u0401\u0402\u0403\u0404\u0405\u0406\u0407\u0408\u0409\u040A\u040B\u040C\u040D\u040E\u040F\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0460\u0462\u0464\u0466\u0468\u046A\u046C\u046E\u0470\u0472\u0474\u0476\u0478\u047A\u047C\u047E\u0480\u048A\u048C\u048E\u0490\u0492\u0494\u0496\u0498\u049A\u049C\u049E\u04A0\u04A2\u04A4\u04A6\u04A8\u04AA\u04AC\u04AE\u04B0\u04B2\u04B4\u04B6\u04B8\u04BA\u04BC\u04BE\u04C0\u04C1\u04C3\u04C5\u04C7\u04C9\u04CB\u04CD\u04D0\u04D2\u04D4\u04D6\u04D8\u04DA\u04DC\u04DE\u04E0\u04E2\u04E4\u04E6\u04E8\u04EA\u04EC\u04EE\u04F0\u04F2\u04F4\u04F6\u04F8\u04FA\u04FC\u04FE\u0500\u0502\u0504\u0506\u0508\u050A\u050C\u050E\u0510\u0512\u0514\u0516\u0518\u051A\u051C\u051E\u0520\u0522\u0531\u0532\u0533\u0534\u0535\u0536\u0537\u0538\u0539\u053A\u053B\u053C\u053D\u053E\u053F\u0540\u0541\u0542\u0543\u0544\u0545\u0546\u0547\u0548\u0549\u054A\u054B\u054C\u054D\u054E\u054F\u0550\u0551\u0552\u0553\u0554\u0555\u0556\u10A0\u10A1\u10A2\u10A3\u10A4\u10A5\u10A6\u10A7\u10A8\u10A9\u10AA\u10AB\u10AC\u10AD\u10AE\u10AF\u10B0\u10B1\u10B2\u10B3\u10B4\u10B5\u10B6\u10B7\u10B8\u10B9\u10BA\u10BB\u10BC\u10BD\u10BE\u10BF\u10C0\u10C1\u10C2\u10C3\u10C4\u10C5\u1E00\u1E02\u1E04\u1E06\u1E08\u1E0A\u1E0C\u1E0E\u1E10\u1E12\u1E14\u1E16\u1E18\u1E1A\u1E1C\u1E1E\u1E20\u1E22\u1E24\u1E26\u1E28\u1E2A\u1E2C\u1E2E\u1E30\u1E32\u1E34\u1E36\u1E38\u1E3A\u1E3C\u1E3E\u1E40\u1E42\u1E44\u1E46\u1E48\u1E4A\u1E4C\u1E4E\u1E50\u1E52\u1E54\u1E56\u1E58\u1E5A\u1E5C\u1E5E\u1E60\u1E62\u1E64\u1E66\u1E68\u1E6A\u1E6C\u1E6E\u1E70\u1E72\u1E74\u1E76\u1E78\u1E7A\u1E7C\u1E7E\u1E80\u1E82\u1E84\u1E86\u1E88\u1E8A\u1E8C\u1E8E\u1E90\u1E92\u1E94\u1E9E\u1EA0\u1EA2\u1EA4\u1EA6\u1EA8\u1EAA\u1EAC\u1EAE\u1EB0\u1EB2\u1EB4\u1EB6\u1EB8\u1EBA\u1EBC\u1EBE\u1EC0\u1EC2\u1EC4\u1EC6\u1EC8\u1ECA\u1ECC\u1ECE\u1ED0\u1ED2\u1ED4\u1ED6\u1ED8\u1EDA\u1EDC\u1EDE\u1EE0\u1EE2\u1EE4\u1EE6\u1EE8\u1EEA\u1EEC\u1EEE\u1EF0\u1EF2\u1EF4\u1EF6\u1EF8\u1EFA\u1EFC\u1EFE\u1F08\u1F09\u1F0A\u1F0B\u1F0C\u1F0D\u1F0E\u1F0F\u1F18\u1F19\u1F1A\u1F1B\u1F1C\u1F1D\u1F28\u1F29\u1F2A\u1F2B\u1F2C\u1F2D\u1F2E\u1F2F\u1F38\u1F39\u1F3A\u1F3B\u1F3C\u1F3D\u1F3E\u1F3F\u1F48\u1F49\u1F4A\u1F4B\u1F4C\u1F4D\u1F59\u1F5B\u1F5D\u1F5F\u1F68\u1F69\u1F6A\u1F6B\u1F6C\u1F6D\u1F6E\u1F6F\u1FB8\u1FB9\u1FBA\u1FBB\u1FC8\u1FC9\u1FCA\u1FCB\u1FD8\u1FD9\u1FDA\u1FDB\u1FE8\u1FE9\u1FEA\u1FEB\u1FEC\u1FF8\u1FF9\u1FFA\u1FFB\u2102\u2107\u210B\u210C\u210D\u2110\u2111\u2112\u2115\u2119\u211A\u211B\u211C\u211D\u2124\u2126\u2128\u212A\u212B\u212C\u212D\u2130\u2131\u2132\u2133\u213E\u213F\u2145\u2183\u2C00\u2C01\u2C02\u2C03\u2C04\u2C05\u2C06\u2C07\u2C08\u2C09\u2C0A\u2C0B\u2C0C\u2C0D\u2C0E\u2C0F\u2C10\u2C11\u2C12\u2C13\u2C14\u2C15\u2C16\u2C17\u2C18\u2C19\u2C1A\u2C1B\u2C1C\u2C1D\u2C1E\u2C1F\u2C20\u2C21\u2C22\u2C23\u2C24\u2C25\u2C26\u2C27\u2C28\u2C29\u2C2A\u2C2B\u2C2C\u2C2D\u2C2E\u2C60\u2C62\u2C63\u2C64\u2C67\u2C69\u2C6B\u2C6D\u2C6E\u2C6F\u2C72\u2C75\u2C80\u2C82\u2C84\u2C86\u2C88\u2C8A\u2C8C\u2C8E\u2C90\u2C92\u2C94\u2C96\u2C98\u2C9A\u2C9C\u2C9E\u2CA0\u2CA2\u2CA4\u2CA6\u2CA8\u2CAA\u2CAC\u2CAE\u2CB0\u2CB2\u2CB4\u2CB6\u2CB8\u2CBA\u2CBC\u2CBE\u2CC0\u2CC2\u2CC4\u2CC6\u2CC8\u2CCA\u2CCC\u2CCE\u2CD0\u2CD2\u2CD4\u2CD6\u2CD8\u2CDA\u2CDC\u2CDE\u2CE0\u2CE2\uA640\uA642\uA644\uA646\uA648\uA64A\uA64C\uA64E\uA650\uA652\uA654\uA656\uA658\uA65A\uA65C\uA65E\uA662\uA664\uA666\uA668\uA66A\uA66C\uA680\uA682\uA684\uA686\uA688\uA68A\uA68C\uA68E\uA690\uA692\uA694\uA696\uA722\uA724\uA726\uA728\uA72A\uA72C\uA72E\uA732\uA734\uA736\uA738\uA73A\uA73C\uA73E\uA740\uA742\uA744\uA746\uA748\uA74A\uA74C\uA74E\uA750\uA752\uA754\uA756\uA758\uA75A\uA75C\uA75E\uA760\uA762\uA764\uA766\uA768\uA76A\uA76C\uA76E\uA779\uA77B\uA77D\uA77E\uA780\uA782\uA784\uA786\uA78B\uFF21\uFF22\uFF23\uFF24\uFF25\uFF26\uFF27\uFF28\uFF29\uFF2A\uFF2B\uFF2C\uFF2D\uFF2E\uFF2F\uFF30\uFF31\uFF32\uFF33\uFF34\uFF35\uFF36\uFF37\uFF38\uFF39\uFF3A]/, + peg$c244 = peg$classExpectation(["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "\xC0", "\xC1", "\xC2", "\xC3", "\xC4", "\xC5", "\xC6", "\xC7", "\xC8", "\xC9", "\xCA", "\xCB", "\xCC", "\xCD", "\xCE", "\xCF", "\xD0", "\xD1", "\xD2", "\xD3", "\xD4", "\xD5", "\xD6", "\xD8", "\xD9", "\xDA", "\xDB", "\xDC", "\xDD", "\xDE", "\u0100", "\u0102", "\u0104", "\u0106", "\u0108", "\u010A", "\u010C", "\u010E", "\u0110", "\u0112", "\u0114", "\u0116", "\u0118", "\u011A", "\u011C", "\u011E", "\u0120", "\u0122", "\u0124", "\u0126", "\u0128", "\u012A", "\u012C", "\u012E", "\u0130", "\u0132", "\u0134", "\u0136", "\u0139", "\u013B", "\u013D", "\u013F", "\u0141", "\u0143", "\u0145", "\u0147", "\u014A", "\u014C", "\u014E", "\u0150", "\u0152", "\u0154", "\u0156", "\u0158", "\u015A", "\u015C", "\u015E", "\u0160", "\u0162", "\u0164", "\u0166", "\u0168", "\u016A", "\u016C", "\u016E", "\u0170", "\u0172", "\u0174", "\u0176", "\u0178", "\u0179", "\u017B", "\u017D", "\u0181", "\u0182", "\u0184", "\u0186", "\u0187", "\u0189", "\u018A", "\u018B", "\u018E", "\u018F", "\u0190", "\u0191", "\u0193", "\u0194", "\u0196", "\u0197", "\u0198", "\u019C", "\u019D", "\u019F", "\u01A0", "\u01A2", "\u01A4", "\u01A6", "\u01A7", "\u01A9", "\u01AC", "\u01AE", "\u01AF", "\u01B1", "\u01B2", "\u01B3", "\u01B5", "\u01B7", "\u01B8", "\u01BC", "\u01C4", "\u01C7", "\u01CA", "\u01CD", "\u01CF", "\u01D1", "\u01D3", "\u01D5", "\u01D7", "\u01D9", "\u01DB", "\u01DE", "\u01E0", "\u01E2", "\u01E4", "\u01E6", "\u01E8", "\u01EA", "\u01EC", "\u01EE", "\u01F1", "\u01F4", "\u01F6", "\u01F7", "\u01F8", "\u01FA", "\u01FC", "\u01FE", "\u0200", "\u0202", "\u0204", "\u0206", "\u0208", "\u020A", "\u020C", "\u020E", "\u0210", "\u0212", "\u0214", "\u0216", "\u0218", "\u021A", "\u021C", "\u021E", "\u0220", "\u0222", "\u0224", "\u0226", "\u0228", "\u022A", "\u022C", "\u022E", "\u0230", "\u0232", "\u023A", "\u023B", "\u023D", "\u023E", "\u0241", "\u0243", "\u0244", "\u0245", "\u0246", "\u0248", "\u024A", "\u024C", "\u024E", "\u0370", "\u0372", "\u0376", "\u0386", "\u0388", "\u0389", "\u038A", "\u038C", "\u038E", "\u038F", "\u0391", "\u0392", "\u0393", "\u0394", "\u0395", "\u0396", "\u0397", "\u0398", "\u0399", "\u039A", "\u039B", "\u039C", "\u039D", "\u039E", "\u039F", "\u03A0", "\u03A1", "\u03A3", "\u03A4", "\u03A5", "\u03A6", "\u03A7", "\u03A8", "\u03A9", "\u03AA", "\u03AB", "\u03CF", "\u03D2", "\u03D3", "\u03D4", "\u03D8", "\u03DA", "\u03DC", "\u03DE", "\u03E0", "\u03E2", "\u03E4", "\u03E6", "\u03E8", "\u03EA", "\u03EC", "\u03EE", "\u03F4", "\u03F7", "\u03F9", "\u03FA", "\u03FD", "\u03FE", "\u03FF", "\u0400", "\u0401", "\u0402", "\u0403", "\u0404", "\u0405", "\u0406", "\u0407", "\u0408", "\u0409", "\u040A", "\u040B", "\u040C", "\u040D", "\u040E", "\u040F", "\u0410", "\u0411", "\u0412", "\u0413", "\u0414", "\u0415", "\u0416", "\u0417", "\u0418", "\u0419", "\u041A", "\u041B", "\u041C", "\u041D", "\u041E", "\u041F", "\u0420", "\u0421", "\u0422", "\u0423", "\u0424", "\u0425", "\u0426", "\u0427", "\u0428", "\u0429", "\u042A", "\u042B", "\u042C", "\u042D", "\u042E", "\u042F", "\u0460", "\u0462", "\u0464", "\u0466", "\u0468", "\u046A", "\u046C", "\u046E", "\u0470", "\u0472", "\u0474", "\u0476", "\u0478", "\u047A", "\u047C", "\u047E", "\u0480", "\u048A", "\u048C", "\u048E", "\u0490", "\u0492", "\u0494", "\u0496", "\u0498", "\u049A", "\u049C", "\u049E", "\u04A0", "\u04A2", "\u04A4", "\u04A6", "\u04A8", "\u04AA", "\u04AC", "\u04AE", "\u04B0", "\u04B2", "\u04B4", "\u04B6", "\u04B8", "\u04BA", "\u04BC", "\u04BE", "\u04C0", "\u04C1", "\u04C3", "\u04C5", "\u04C7", "\u04C9", "\u04CB", "\u04CD", "\u04D0", "\u04D2", "\u04D4", "\u04D6", "\u04D8", "\u04DA", "\u04DC", "\u04DE", "\u04E0", "\u04E2", "\u04E4", "\u04E6", "\u04E8", "\u04EA", "\u04EC", "\u04EE", "\u04F0", "\u04F2", "\u04F4", "\u04F6", "\u04F8", "\u04FA", "\u04FC", "\u04FE", "\u0500", "\u0502", "\u0504", "\u0506", "\u0508", "\u050A", "\u050C", "\u050E", "\u0510", "\u0512", "\u0514", "\u0516", "\u0518", "\u051A", "\u051C", "\u051E", "\u0520", "\u0522", "\u0531", "\u0532", "\u0533", "\u0534", "\u0535", "\u0536", "\u0537", "\u0538", "\u0539", "\u053A", "\u053B", "\u053C", "\u053D", "\u053E", "\u053F", "\u0540", "\u0541", "\u0542", "\u0543", "\u0544", "\u0545", "\u0546", "\u0547", "\u0548", "\u0549", "\u054A", "\u054B", "\u054C", "\u054D", "\u054E", "\u054F", "\u0550", "\u0551", "\u0552", "\u0553", "\u0554", "\u0555", "\u0556", "\u10A0", "\u10A1", "\u10A2", "\u10A3", "\u10A4", "\u10A5", "\u10A6", "\u10A7", "\u10A8", "\u10A9", "\u10AA", "\u10AB", "\u10AC", "\u10AD", "\u10AE", "\u10AF", "\u10B0", "\u10B1", "\u10B2", "\u10B3", "\u10B4", "\u10B5", "\u10B6", "\u10B7", "\u10B8", "\u10B9", "\u10BA", "\u10BB", "\u10BC", "\u10BD", "\u10BE", "\u10BF", "\u10C0", "\u10C1", "\u10C2", "\u10C3", "\u10C4", "\u10C5", "\u1E00", "\u1E02", "\u1E04", "\u1E06", "\u1E08", "\u1E0A", "\u1E0C", "\u1E0E", "\u1E10", "\u1E12", "\u1E14", "\u1E16", "\u1E18", "\u1E1A", "\u1E1C", "\u1E1E", "\u1E20", "\u1E22", "\u1E24", "\u1E26", "\u1E28", "\u1E2A", "\u1E2C", "\u1E2E", "\u1E30", "\u1E32", "\u1E34", "\u1E36", "\u1E38", "\u1E3A", "\u1E3C", "\u1E3E", "\u1E40", "\u1E42", "\u1E44", "\u1E46", "\u1E48", "\u1E4A", "\u1E4C", "\u1E4E", "\u1E50", "\u1E52", "\u1E54", "\u1E56", "\u1E58", "\u1E5A", "\u1E5C", "\u1E5E", "\u1E60", "\u1E62", "\u1E64", "\u1E66", "\u1E68", "\u1E6A", "\u1E6C", "\u1E6E", "\u1E70", "\u1E72", "\u1E74", "\u1E76", "\u1E78", "\u1E7A", "\u1E7C", "\u1E7E", "\u1E80", "\u1E82", "\u1E84", "\u1E86", "\u1E88", "\u1E8A", "\u1E8C", "\u1E8E", "\u1E90", "\u1E92", "\u1E94", "\u1E9E", "\u1EA0", "\u1EA2", "\u1EA4", "\u1EA6", "\u1EA8", "\u1EAA", "\u1EAC", "\u1EAE", "\u1EB0", "\u1EB2", "\u1EB4", "\u1EB6", "\u1EB8", "\u1EBA", "\u1EBC", "\u1EBE", "\u1EC0", "\u1EC2", "\u1EC4", "\u1EC6", "\u1EC8", "\u1ECA", "\u1ECC", "\u1ECE", "\u1ED0", "\u1ED2", "\u1ED4", "\u1ED6", "\u1ED8", "\u1EDA", "\u1EDC", "\u1EDE", "\u1EE0", "\u1EE2", "\u1EE4", "\u1EE6", "\u1EE8", "\u1EEA", "\u1EEC", "\u1EEE", "\u1EF0", "\u1EF2", "\u1EF4", "\u1EF6", "\u1EF8", "\u1EFA", "\u1EFC", "\u1EFE", "\u1F08", "\u1F09", "\u1F0A", "\u1F0B", "\u1F0C", "\u1F0D", "\u1F0E", "\u1F0F", "\u1F18", "\u1F19", "\u1F1A", "\u1F1B", "\u1F1C", "\u1F1D", "\u1F28", "\u1F29", "\u1F2A", "\u1F2B", "\u1F2C", "\u1F2D", "\u1F2E", "\u1F2F", "\u1F38", "\u1F39", "\u1F3A", "\u1F3B", "\u1F3C", "\u1F3D", "\u1F3E", "\u1F3F", "\u1F48", "\u1F49", "\u1F4A", "\u1F4B", "\u1F4C", "\u1F4D", "\u1F59", "\u1F5B", "\u1F5D", "\u1F5F", "\u1F68", "\u1F69", "\u1F6A", "\u1F6B", "\u1F6C", "\u1F6D", "\u1F6E", "\u1F6F", "\u1FB8", "\u1FB9", "\u1FBA", "\u1FBB", "\u1FC8", "\u1FC9", "\u1FCA", "\u1FCB", "\u1FD8", "\u1FD9", "\u1FDA", "\u1FDB", "\u1FE8", "\u1FE9", "\u1FEA", "\u1FEB", "\u1FEC", "\u1FF8", "\u1FF9", "\u1FFA", "\u1FFB", "\u2102", "\u2107", "\u210B", "\u210C", "\u210D", "\u2110", "\u2111", "\u2112", "\u2115", "\u2119", "\u211A", "\u211B", "\u211C", "\u211D", "\u2124", "\u2126", "\u2128", "\u212A", "\u212B", "\u212C", "\u212D", "\u2130", "\u2131", "\u2132", "\u2133", "\u213E", "\u213F", "\u2145", "\u2183", "\u2C00", "\u2C01", "\u2C02", "\u2C03", "\u2C04", "\u2C05", "\u2C06", "\u2C07", "\u2C08", "\u2C09", "\u2C0A", "\u2C0B", "\u2C0C", "\u2C0D", "\u2C0E", "\u2C0F", "\u2C10", "\u2C11", "\u2C12", "\u2C13", "\u2C14", "\u2C15", "\u2C16", "\u2C17", "\u2C18", "\u2C19", "\u2C1A", "\u2C1B", "\u2C1C", "\u2C1D", "\u2C1E", "\u2C1F", "\u2C20", "\u2C21", "\u2C22", "\u2C23", "\u2C24", "\u2C25", "\u2C26", "\u2C27", "\u2C28", "\u2C29", "\u2C2A", "\u2C2B", "\u2C2C", "\u2C2D", "\u2C2E", "\u2C60", "\u2C62", "\u2C63", "\u2C64", "\u2C67", "\u2C69", "\u2C6B", "\u2C6D", "\u2C6E", "\u2C6F", "\u2C72", "\u2C75", "\u2C80", "\u2C82", "\u2C84", "\u2C86", "\u2C88", "\u2C8A", "\u2C8C", "\u2C8E", "\u2C90", "\u2C92", "\u2C94", "\u2C96", "\u2C98", "\u2C9A", "\u2C9C", "\u2C9E", "\u2CA0", "\u2CA2", "\u2CA4", "\u2CA6", "\u2CA8", "\u2CAA", "\u2CAC", "\u2CAE", "\u2CB0", "\u2CB2", "\u2CB4", "\u2CB6", "\u2CB8", "\u2CBA", "\u2CBC", "\u2CBE", "\u2CC0", "\u2CC2", "\u2CC4", "\u2CC6", "\u2CC8", "\u2CCA", "\u2CCC", "\u2CCE", "\u2CD0", "\u2CD2", "\u2CD4", "\u2CD6", "\u2CD8", "\u2CDA", "\u2CDC", "\u2CDE", "\u2CE0", "\u2CE2", "\uA640", "\uA642", "\uA644", "\uA646", "\uA648", "\uA64A", "\uA64C", "\uA64E", "\uA650", "\uA652", "\uA654", "\uA656", "\uA658", "\uA65A", "\uA65C", "\uA65E", "\uA662", "\uA664", "\uA666", "\uA668", "\uA66A", "\uA66C", "\uA680", "\uA682", "\uA684", "\uA686", "\uA688", "\uA68A", "\uA68C", "\uA68E", "\uA690", "\uA692", "\uA694", "\uA696", "\uA722", "\uA724", "\uA726", "\uA728", "\uA72A", "\uA72C", "\uA72E", "\uA732", "\uA734", "\uA736", "\uA738", "\uA73A", "\uA73C", "\uA73E", "\uA740", "\uA742", "\uA744", "\uA746", "\uA748", "\uA74A", "\uA74C", "\uA74E", "\uA750", "\uA752", "\uA754", "\uA756", "\uA758", "\uA75A", "\uA75C", "\uA75E", "\uA760", "\uA762", "\uA764", "\uA766", "\uA768", "\uA76A", "\uA76C", "\uA76E", "\uA779", "\uA77B", "\uA77D", "\uA77E", "\uA780", "\uA782", "\uA784", "\uA786", "\uA78B", "\uFF21", "\uFF22", "\uFF23", "\uFF24", "\uFF25", "\uFF26", "\uFF27", "\uFF28", "\uFF29", "\uFF2A", "\uFF2B", "\uFF2C", "\uFF2D", "\uFF2E", "\uFF2F", "\uFF30", "\uFF31", "\uFF32", "\uFF33", "\uFF34", "\uFF35", "\uFF36", "\uFF37", "\uFF38", "\uFF39", "\uFF3A"], false, false), + peg$c245 = peg$otherExpectation("Unicode lowercase letter"), + peg$c246 = /^[abcdefghijklmnopqrstuvwxyz\xAA\xB5\xBA\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF\u0101\u0103\u0105\u0107\u0109\u010B\u010D\u010F\u0111\u0113\u0115\u0117\u0119\u011B\u011D\u011F\u0121\u0123\u0125\u0127\u0129\u012B\u012D\u012F\u0131\u0133\u0135\u0137\u0138\u013A\u013C\u013E\u0140\u0142\u0144\u0146\u0148\u0149\u014B\u014D\u014F\u0151\u0153\u0155\u0157\u0159\u015B\u015D\u015F\u0161\u0163\u0165\u0167\u0169\u016B\u016D\u016F\u0171\u0173\u0175\u0177\u017A\u017C\u017E\u017F\u0180\u0183\u0185\u0188\u018C\u018D\u0192\u0195\u0199\u019A\u019B\u019E\u01A1\u01A3\u01A5\u01A8\u01AA\u01AB\u01AD\u01B0\u01B4\u01B6\u01B9\u01BA\u01BD\u01BE\u01BF\u01C6\u01C9\u01CC\u01CE\u01D0\u01D2\u01D4\u01D6\u01D8\u01DA\u01DC\u01DD\u01DF\u01E1\u01E3\u01E5\u01E7\u01E9\u01EB\u01ED\u01EF\u01F0\u01F3\u01F5\u01F9\u01FB\u01FD\u01FF\u0201\u0203\u0205\u0207\u0209\u020B\u020D\u020F\u0211\u0213\u0215\u0217\u0219\u021B\u021D\u021F\u0221\u0223\u0225\u0227\u0229\u022B\u022D\u022F\u0231\u0233\u0234\u0235\u0236\u0237\u0238\u0239\u023C\u023F\u0240\u0242\u0247\u0249\u024B\u024D\u024F\u0250\u0251\u0252\u0253\u0254\u0255\u0256\u0257\u0258\u0259\u025A\u025B\u025C\u025D\u025E\u025F\u0260\u0261\u0262\u0263\u0264\u0265\u0266\u0267\u0268\u0269\u026A\u026B\u026C\u026D\u026E\u026F\u0270\u0271\u0272\u0273\u0274\u0275\u0276\u0277\u0278\u0279\u027A\u027B\u027C\u027D\u027E\u027F\u0280\u0281\u0282\u0283\u0284\u0285\u0286\u0287\u0288\u0289\u028A\u028B\u028C\u028D\u028E\u028F\u0290\u0291\u0292\u0293\u0295\u0296\u0297\u0298\u0299\u029A\u029B\u029C\u029D\u029E\u029F\u02A0\u02A1\u02A2\u02A3\u02A4\u02A5\u02A6\u02A7\u02A8\u02A9\u02AA\u02AB\u02AC\u02AD\u02AE\u02AF\u0371\u0373\u0377\u037B\u037C\u037D\u0390\u03AC\u03AD\u03AE\u03AF\u03B0\u03B1\u03B2\u03B3\u03B4\u03B5\u03B6\u03B7\u03B8\u03B9\u03BA\u03BB\u03BC\u03BD\u03BE\u03BF\u03C0\u03C1\u03C2\u03C3\u03C4\u03C5\u03C6\u03C7\u03C8\u03C9\u03CA\u03CB\u03CC\u03CD\u03CE\u03D0\u03D1\u03D5\u03D6\u03D7\u03D9\u03DB\u03DD\u03DF\u03E1\u03E3\u03E5\u03E7\u03E9\u03EB\u03ED\u03EF\u03F0\u03F1\u03F2\u03F3\u03F5\u03F8\u03FB\u03FC\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F\u0450\u0451\u0452\u0453\u0454\u0455\u0456\u0457\u0458\u0459\u045A\u045B\u045C\u045D\u045E\u045F\u0461\u0463\u0465\u0467\u0469\u046B\u046D\u046F\u0471\u0473\u0475\u0477\u0479\u047B\u047D\u047F\u0481\u048B\u048D\u048F\u0491\u0493\u0495\u0497\u0499\u049B\u049D\u049F\u04A1\u04A3\u04A5\u04A7\u04A9\u04AB\u04AD\u04AF\u04B1\u04B3\u04B5\u04B7\u04B9\u04BB\u04BD\u04BF\u04C2\u04C4\u04C6\u04C8\u04CA\u04CC\u04CE\u04CF\u04D1\u04D3\u04D5\u04D7\u04D9\u04DB\u04DD\u04DF\u04E1\u04E3\u04E5\u04E7\u04E9\u04EB\u04ED\u04EF\u04F1\u04F3\u04F5\u04F7\u04F9\u04FB\u04FD\u04FF\u0501\u0503\u0505\u0507\u0509\u050B\u050D\u050F\u0511\u0513\u0515\u0517\u0519\u051B\u051D\u051F\u0521\u0523\u0561\u0562\u0563\u0564\u0565\u0566\u0567\u0568\u0569\u056A\u056B\u056C\u056D\u056E\u056F\u0570\u0571\u0572\u0573\u0574\u0575\u0576\u0577\u0578\u0579\u057A\u057B\u057C\u057D\u057E\u057F\u0580\u0581\u0582\u0583\u0584\u0585\u0586\u0587\u1D00\u1D01\u1D02\u1D03\u1D04\u1D05\u1D06\u1D07\u1D08\u1D09\u1D0A\u1D0B\u1D0C\u1D0D\u1D0E\u1D0F\u1D10\u1D11\u1D12\u1D13\u1D14\u1D15\u1D16\u1D17\u1D18\u1D19\u1D1A\u1D1B\u1D1C\u1D1D\u1D1E\u1D1F\u1D20\u1D21\u1D22\u1D23\u1D24\u1D25\u1D26\u1D27\u1D28\u1D29\u1D2A\u1D2B\u1D62\u1D63\u1D64\u1D65\u1D66\u1D67\u1D68\u1D69\u1D6A\u1D6B\u1D6C\u1D6D\u1D6E\u1D6F\u1D70\u1D71\u1D72\u1D73\u1D74\u1D75\u1D76\u1D77\u1D79\u1D7A\u1D7B\u1D7C\u1D7D\u1D7E\u1D7F\u1D80\u1D81\u1D82\u1D83\u1D84\u1D85\u1D86\u1D87\u1D88\u1D89\u1D8A\u1D8B\u1D8C\u1D8D\u1D8E\u1D8F\u1D90\u1D91\u1D92\u1D93\u1D94\u1D95\u1D96\u1D97\u1D98\u1D99\u1D9A\u1E01\u1E03\u1E05\u1E07\u1E09\u1E0B\u1E0D\u1E0F\u1E11\u1E13\u1E15\u1E17\u1E19\u1E1B\u1E1D\u1E1F\u1E21\u1E23\u1E25\u1E27\u1E29\u1E2B\u1E2D\u1E2F\u1E31\u1E33\u1E35\u1E37\u1E39\u1E3B\u1E3D\u1E3F\u1E41\u1E43\u1E45\u1E47\u1E49\u1E4B\u1E4D\u1E4F\u1E51\u1E53\u1E55\u1E57\u1E59\u1E5B\u1E5D\u1E5F\u1E61\u1E63\u1E65\u1E67\u1E69\u1E6B\u1E6D\u1E6F\u1E71\u1E73\u1E75\u1E77\u1E79\u1E7B\u1E7D\u1E7F\u1E81\u1E83\u1E85\u1E87\u1E89\u1E8B\u1E8D\u1E8F\u1E91\u1E93\u1E95\u1E96\u1E97\u1E98\u1E99\u1E9A\u1E9B\u1E9C\u1E9D\u1E9F\u1EA1\u1EA3\u1EA5\u1EA7\u1EA9\u1EAB\u1EAD\u1EAF\u1EB1\u1EB3\u1EB5\u1EB7\u1EB9\u1EBB\u1EBD\u1EBF\u1EC1\u1EC3\u1EC5\u1EC7\u1EC9\u1ECB\u1ECD\u1ECF\u1ED1\u1ED3\u1ED5\u1ED7\u1ED9\u1EDB\u1EDD\u1EDF\u1EE1\u1EE3\u1EE5\u1EE7\u1EE9\u1EEB\u1EED\u1EEF\u1EF1\u1EF3\u1EF5\u1EF7\u1EF9\u1EFB\u1EFD\u1EFF\u1F00\u1F01\u1F02\u1F03\u1F04\u1F05\u1F06\u1F07\u1F10\u1F11\u1F12\u1F13\u1F14\u1F15\u1F20\u1F21\u1F22\u1F23\u1F24\u1F25\u1F26\u1F27\u1F30\u1F31\u1F32\u1F33\u1F34\u1F35\u1F36\u1F37\u1F40\u1F41\u1F42\u1F43\u1F44\u1F45\u1F50\u1F51\u1F52\u1F53\u1F54\u1F55\u1F56\u1F57\u1F60\u1F61\u1F62\u1F63\u1F64\u1F65\u1F66\u1F67\u1F70\u1F71\u1F72\u1F73\u1F74\u1F75\u1F76\u1F77\u1F78\u1F79\u1F7A\u1F7B\u1F7C\u1F7D\u1F80\u1F81\u1F82\u1F83\u1F84\u1F85\u1F86\u1F87\u1F90\u1F91\u1F92\u1F93\u1F94\u1F95\u1F96\u1F97\u1FA0\u1FA1\u1FA2\u1FA3\u1FA4\u1FA5\u1FA6\u1FA7\u1FB0\u1FB1\u1FB2\u1FB3\u1FB4\u1FB6\u1FB7\u1FBE\u1FC2\u1FC3\u1FC4\u1FC6\u1FC7\u1FD0\u1FD1\u1FD2\u1FD3\u1FD6\u1FD7\u1FE0\u1FE1\u1FE2\u1FE3\u1FE4\u1FE5\u1FE6\u1FE7\u1FF2\u1FF3\u1FF4\u1FF6\u1FF7\u2071\u207F\u210A\u210E\u210F\u2113\u212F\u2134\u2139\u213C\u213D\u2146\u2147\u2148\u2149\u214E\u2184\u2C30\u2C31\u2C32\u2C33\u2C34\u2C35\u2C36\u2C37\u2C38\u2C39\u2C3A\u2C3B\u2C3C\u2C3D\u2C3E\u2C3F\u2C40\u2C41\u2C42\u2C43\u2C44\u2C45\u2C46\u2C47\u2C48\u2C49\u2C4A\u2C4B\u2C4C\u2C4D\u2C4E\u2C4F\u2C50\u2C51\u2C52\u2C53\u2C54\u2C55\u2C56\u2C57\u2C58\u2C59\u2C5A\u2C5B\u2C5C\u2C5D\u2C5E\u2C61\u2C65\u2C66\u2C68\u2C6A\u2C6C\u2C71\u2C73\u2C74\u2C76\u2C77\u2C78\u2C79\u2C7A\u2C7B\u2C7C\u2C81\u2C83\u2C85\u2C87\u2C89\u2C8B\u2C8D\u2C8F\u2C91\u2C93\u2C95\u2C97\u2C99\u2C9B\u2C9D\u2C9F\u2CA1\u2CA3\u2CA5\u2CA7\u2CA9\u2CAB\u2CAD\u2CAF\u2CB1\u2CB3\u2CB5\u2CB7\u2CB9\u2CBB\u2CBD\u2CBF\u2CC1\u2CC3\u2CC5\u2CC7\u2CC9\u2CCB\u2CCD\u2CCF\u2CD1\u2CD3\u2CD5\u2CD7\u2CD9\u2CDB\u2CDD\u2CDF\u2CE1\u2CE3\u2CE4\u2D00\u2D01\u2D02\u2D03\u2D04\u2D05\u2D06\u2D07\u2D08\u2D09\u2D0A\u2D0B\u2D0C\u2D0D\u2D0E\u2D0F\u2D10\u2D11\u2D12\u2D13\u2D14\u2D15\u2D16\u2D17\u2D18\u2D19\u2D1A\u2D1B\u2D1C\u2D1D\u2D1E\u2D1F\u2D20\u2D21\u2D22\u2D23\u2D24\u2D25\uA641\uA643\uA645\uA647\uA649\uA64B\uA64D\uA64F\uA651\uA653\uA655\uA657\uA659\uA65B\uA65D\uA65F\uA663\uA665\uA667\uA669\uA66B\uA66D\uA681\uA683\uA685\uA687\uA689\uA68B\uA68D\uA68F\uA691\uA693\uA695\uA697\uA723\uA725\uA727\uA729\uA72B\uA72D\uA72F\uA730\uA731\uA733\uA735\uA737\uA739\uA73B\uA73D\uA73F\uA741\uA743\uA745\uA747\uA749\uA74B\uA74D\uA74F\uA751\uA753\uA755\uA757\uA759\uA75B\uA75D\uA75F\uA761\uA763\uA765\uA767\uA769\uA76B\uA76D\uA76F\uA771\uA772\uA773\uA774\uA775\uA776\uA777\uA778\uA77A\uA77C\uA77F\uA781\uA783\uA785\uA787\uA78C\uFB00\uFB01\uFB02\uFB03\uFB04\uFB05\uFB06\uFB13\uFB14\uFB15\uFB16\uFB17\uFF41\uFF42\uFF43\uFF44\uFF45\uFF46\uFF47\uFF48\uFF49\uFF4A\uFF4B\uFF4C\uFF4D\uFF4E\uFF4F\uFF50\uFF51\uFF52\uFF53\uFF54\uFF55\uFF56\uFF57\uFF58\uFF59\uFF5A]/, + peg$c247 = peg$classExpectation(["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "\xAA", "\xB5", "\xBA", "\xDF", "\xE0", "\xE1", "\xE2", "\xE3", "\xE4", "\xE5", "\xE6", "\xE7", "\xE8", "\xE9", "\xEA", "\xEB", "\xEC", "\xED", "\xEE", "\xEF", "\xF0", "\xF1", "\xF2", "\xF3", "\xF4", "\xF5", "\xF6", "\xF8", "\xF9", "\xFA", "\xFB", "\xFC", "\xFD", "\xFE", "\xFF", "\u0101", "\u0103", "\u0105", "\u0107", "\u0109", "\u010B", "\u010D", "\u010F", "\u0111", "\u0113", "\u0115", "\u0117", "\u0119", "\u011B", "\u011D", "\u011F", "\u0121", "\u0123", "\u0125", "\u0127", "\u0129", "\u012B", "\u012D", "\u012F", "\u0131", "\u0133", "\u0135", "\u0137", "\u0138", "\u013A", "\u013C", "\u013E", "\u0140", "\u0142", "\u0144", "\u0146", "\u0148", "\u0149", "\u014B", "\u014D", "\u014F", "\u0151", "\u0153", "\u0155", "\u0157", "\u0159", "\u015B", "\u015D", "\u015F", "\u0161", "\u0163", "\u0165", "\u0167", "\u0169", "\u016B", "\u016D", "\u016F", "\u0171", "\u0173", "\u0175", "\u0177", "\u017A", "\u017C", "\u017E", "\u017F", "\u0180", "\u0183", "\u0185", "\u0188", "\u018C", "\u018D", "\u0192", "\u0195", "\u0199", "\u019A", "\u019B", "\u019E", "\u01A1", "\u01A3", "\u01A5", "\u01A8", "\u01AA", "\u01AB", "\u01AD", "\u01B0", "\u01B4", "\u01B6", "\u01B9", "\u01BA", "\u01BD", "\u01BE", "\u01BF", "\u01C6", "\u01C9", "\u01CC", "\u01CE", "\u01D0", "\u01D2", "\u01D4", "\u01D6", "\u01D8", "\u01DA", "\u01DC", "\u01DD", "\u01DF", "\u01E1", "\u01E3", "\u01E5", "\u01E7", "\u01E9", "\u01EB", "\u01ED", "\u01EF", "\u01F0", "\u01F3", "\u01F5", "\u01F9", "\u01FB", "\u01FD", "\u01FF", "\u0201", "\u0203", "\u0205", "\u0207", "\u0209", "\u020B", "\u020D", "\u020F", "\u0211", "\u0213", "\u0215", "\u0217", "\u0219", "\u021B", "\u021D", "\u021F", "\u0221", "\u0223", "\u0225", "\u0227", "\u0229", "\u022B", "\u022D", "\u022F", "\u0231", "\u0233", "\u0234", "\u0235", "\u0236", "\u0237", "\u0238", "\u0239", "\u023C", "\u023F", "\u0240", "\u0242", "\u0247", "\u0249", "\u024B", "\u024D", "\u024F", "\u0250", "\u0251", "\u0252", "\u0253", "\u0254", "\u0255", "\u0256", "\u0257", "\u0258", "\u0259", "\u025A", "\u025B", "\u025C", "\u025D", "\u025E", "\u025F", "\u0260", "\u0261", "\u0262", "\u0263", "\u0264", "\u0265", "\u0266", "\u0267", "\u0268", "\u0269", "\u026A", "\u026B", "\u026C", "\u026D", "\u026E", "\u026F", "\u0270", "\u0271", "\u0272", "\u0273", "\u0274", "\u0275", "\u0276", "\u0277", "\u0278", "\u0279", "\u027A", "\u027B", "\u027C", "\u027D", "\u027E", "\u027F", "\u0280", "\u0281", "\u0282", "\u0283", "\u0284", "\u0285", "\u0286", "\u0287", "\u0288", "\u0289", "\u028A", "\u028B", "\u028C", "\u028D", "\u028E", "\u028F", "\u0290", "\u0291", "\u0292", "\u0293", "\u0295", "\u0296", "\u0297", "\u0298", "\u0299", "\u029A", "\u029B", "\u029C", "\u029D", "\u029E", "\u029F", "\u02A0", "\u02A1", "\u02A2", "\u02A3", "\u02A4", "\u02A5", "\u02A6", "\u02A7", "\u02A8", "\u02A9", "\u02AA", "\u02AB", "\u02AC", "\u02AD", "\u02AE", "\u02AF", "\u0371", "\u0373", "\u0377", "\u037B", "\u037C", "\u037D", "\u0390", "\u03AC", "\u03AD", "\u03AE", "\u03AF", "\u03B0", "\u03B1", "\u03B2", "\u03B3", "\u03B4", "\u03B5", "\u03B6", "\u03B7", "\u03B8", "\u03B9", "\u03BA", "\u03BB", "\u03BC", "\u03BD", "\u03BE", "\u03BF", "\u03C0", "\u03C1", "\u03C2", "\u03C3", "\u03C4", "\u03C5", "\u03C6", "\u03C7", "\u03C8", "\u03C9", "\u03CA", "\u03CB", "\u03CC", "\u03CD", "\u03CE", "\u03D0", "\u03D1", "\u03D5", "\u03D6", "\u03D7", "\u03D9", "\u03DB", "\u03DD", "\u03DF", "\u03E1", "\u03E3", "\u03E5", "\u03E7", "\u03E9", "\u03EB", "\u03ED", "\u03EF", "\u03F0", "\u03F1", "\u03F2", "\u03F3", "\u03F5", "\u03F8", "\u03FB", "\u03FC", "\u0430", "\u0431", "\u0432", "\u0433", "\u0434", "\u0435", "\u0436", "\u0437", "\u0438", "\u0439", "\u043A", "\u043B", "\u043C", "\u043D", "\u043E", "\u043F", "\u0440", "\u0441", "\u0442", "\u0443", "\u0444", "\u0445", "\u0446", "\u0447", "\u0448", "\u0449", "\u044A", "\u044B", "\u044C", "\u044D", "\u044E", "\u044F", "\u0450", "\u0451", "\u0452", "\u0453", "\u0454", "\u0455", "\u0456", "\u0457", "\u0458", "\u0459", "\u045A", "\u045B", "\u045C", "\u045D", "\u045E", "\u045F", "\u0461", "\u0463", "\u0465", "\u0467", "\u0469", "\u046B", "\u046D", "\u046F", "\u0471", "\u0473", "\u0475", "\u0477", "\u0479", "\u047B", "\u047D", "\u047F", "\u0481", "\u048B", "\u048D", "\u048F", "\u0491", "\u0493", "\u0495", "\u0497", "\u0499", "\u049B", "\u049D", "\u049F", "\u04A1", "\u04A3", "\u04A5", "\u04A7", "\u04A9", "\u04AB", "\u04AD", "\u04AF", "\u04B1", "\u04B3", "\u04B5", "\u04B7", "\u04B9", "\u04BB", "\u04BD", "\u04BF", "\u04C2", "\u04C4", "\u04C6", "\u04C8", "\u04CA", "\u04CC", "\u04CE", "\u04CF", "\u04D1", "\u04D3", "\u04D5", "\u04D7", "\u04D9", "\u04DB", "\u04DD", "\u04DF", "\u04E1", "\u04E3", "\u04E5", "\u04E7", "\u04E9", "\u04EB", "\u04ED", "\u04EF", "\u04F1", "\u04F3", "\u04F5", "\u04F7", "\u04F9", "\u04FB", "\u04FD", "\u04FF", "\u0501", "\u0503", "\u0505", "\u0507", "\u0509", "\u050B", "\u050D", "\u050F", "\u0511", "\u0513", "\u0515", "\u0517", "\u0519", "\u051B", "\u051D", "\u051F", "\u0521", "\u0523", "\u0561", "\u0562", "\u0563", "\u0564", "\u0565", "\u0566", "\u0567", "\u0568", "\u0569", "\u056A", "\u056B", "\u056C", "\u056D", "\u056E", "\u056F", "\u0570", "\u0571", "\u0572", "\u0573", "\u0574", "\u0575", "\u0576", "\u0577", "\u0578", "\u0579", "\u057A", "\u057B", "\u057C", "\u057D", "\u057E", "\u057F", "\u0580", "\u0581", "\u0582", "\u0583", "\u0584", "\u0585", "\u0586", "\u0587", "\u1D00", "\u1D01", "\u1D02", "\u1D03", "\u1D04", "\u1D05", "\u1D06", "\u1D07", "\u1D08", "\u1D09", "\u1D0A", "\u1D0B", "\u1D0C", "\u1D0D", "\u1D0E", "\u1D0F", "\u1D10", "\u1D11", "\u1D12", "\u1D13", "\u1D14", "\u1D15", "\u1D16", "\u1D17", "\u1D18", "\u1D19", "\u1D1A", "\u1D1B", "\u1D1C", "\u1D1D", "\u1D1E", "\u1D1F", "\u1D20", "\u1D21", "\u1D22", "\u1D23", "\u1D24", "\u1D25", "\u1D26", "\u1D27", "\u1D28", "\u1D29", "\u1D2A", "\u1D2B", "\u1D62", "\u1D63", "\u1D64", "\u1D65", "\u1D66", "\u1D67", "\u1D68", "\u1D69", "\u1D6A", "\u1D6B", "\u1D6C", "\u1D6D", "\u1D6E", "\u1D6F", "\u1D70", "\u1D71", "\u1D72", "\u1D73", "\u1D74", "\u1D75", "\u1D76", "\u1D77", "\u1D79", "\u1D7A", "\u1D7B", "\u1D7C", "\u1D7D", "\u1D7E", "\u1D7F", "\u1D80", "\u1D81", "\u1D82", "\u1D83", "\u1D84", "\u1D85", "\u1D86", "\u1D87", "\u1D88", "\u1D89", "\u1D8A", "\u1D8B", "\u1D8C", "\u1D8D", "\u1D8E", "\u1D8F", "\u1D90", "\u1D91", "\u1D92", "\u1D93", "\u1D94", "\u1D95", "\u1D96", "\u1D97", "\u1D98", "\u1D99", "\u1D9A", "\u1E01", "\u1E03", "\u1E05", "\u1E07", "\u1E09", "\u1E0B", "\u1E0D", "\u1E0F", "\u1E11", "\u1E13", "\u1E15", "\u1E17", "\u1E19", "\u1E1B", "\u1E1D", "\u1E1F", "\u1E21", "\u1E23", "\u1E25", "\u1E27", "\u1E29", "\u1E2B", "\u1E2D", "\u1E2F", "\u1E31", "\u1E33", "\u1E35", "\u1E37", "\u1E39", "\u1E3B", "\u1E3D", "\u1E3F", "\u1E41", "\u1E43", "\u1E45", "\u1E47", "\u1E49", "\u1E4B", "\u1E4D", "\u1E4F", "\u1E51", "\u1E53", "\u1E55", "\u1E57", "\u1E59", "\u1E5B", "\u1E5D", "\u1E5F", "\u1E61", "\u1E63", "\u1E65", "\u1E67", "\u1E69", "\u1E6B", "\u1E6D", "\u1E6F", "\u1E71", "\u1E73", "\u1E75", "\u1E77", "\u1E79", "\u1E7B", "\u1E7D", "\u1E7F", "\u1E81", "\u1E83", "\u1E85", "\u1E87", "\u1E89", "\u1E8B", "\u1E8D", "\u1E8F", "\u1E91", "\u1E93", "\u1E95", "\u1E96", "\u1E97", "\u1E98", "\u1E99", "\u1E9A", "\u1E9B", "\u1E9C", "\u1E9D", "\u1E9F", "\u1EA1", "\u1EA3", "\u1EA5", "\u1EA7", "\u1EA9", "\u1EAB", "\u1EAD", "\u1EAF", "\u1EB1", "\u1EB3", "\u1EB5", "\u1EB7", "\u1EB9", "\u1EBB", "\u1EBD", "\u1EBF", "\u1EC1", "\u1EC3", "\u1EC5", "\u1EC7", "\u1EC9", "\u1ECB", "\u1ECD", "\u1ECF", "\u1ED1", "\u1ED3", "\u1ED5", "\u1ED7", "\u1ED9", "\u1EDB", "\u1EDD", "\u1EDF", "\u1EE1", "\u1EE3", "\u1EE5", "\u1EE7", "\u1EE9", "\u1EEB", "\u1EED", "\u1EEF", "\u1EF1", "\u1EF3", "\u1EF5", "\u1EF7", "\u1EF9", "\u1EFB", "\u1EFD", "\u1EFF", "\u1F00", "\u1F01", "\u1F02", "\u1F03", "\u1F04", "\u1F05", "\u1F06", "\u1F07", "\u1F10", "\u1F11", "\u1F12", "\u1F13", "\u1F14", "\u1F15", "\u1F20", "\u1F21", "\u1F22", "\u1F23", "\u1F24", "\u1F25", "\u1F26", "\u1F27", "\u1F30", "\u1F31", "\u1F32", "\u1F33", "\u1F34", "\u1F35", "\u1F36", "\u1F37", "\u1F40", "\u1F41", "\u1F42", "\u1F43", "\u1F44", "\u1F45", "\u1F50", "\u1F51", "\u1F52", "\u1F53", "\u1F54", "\u1F55", "\u1F56", "\u1F57", "\u1F60", "\u1F61", "\u1F62", "\u1F63", "\u1F64", "\u1F65", "\u1F66", "\u1F67", "\u1F70", "\u1F71", "\u1F72", "\u1F73", "\u1F74", "\u1F75", "\u1F76", "\u1F77", "\u1F78", "\u1F79", "\u1F7A", "\u1F7B", "\u1F7C", "\u1F7D", "\u1F80", "\u1F81", "\u1F82", "\u1F83", "\u1F84", "\u1F85", "\u1F86", "\u1F87", "\u1F90", "\u1F91", "\u1F92", "\u1F93", "\u1F94", "\u1F95", "\u1F96", "\u1F97", "\u1FA0", "\u1FA1", "\u1FA2", "\u1FA3", "\u1FA4", "\u1FA5", "\u1FA6", "\u1FA7", "\u1FB0", "\u1FB1", "\u1FB2", "\u1FB3", "\u1FB4", "\u1FB6", "\u1FB7", "\u1FBE", "\u1FC2", "\u1FC3", "\u1FC4", "\u1FC6", "\u1FC7", "\u1FD0", "\u1FD1", "\u1FD2", "\u1FD3", "\u1FD6", "\u1FD7", "\u1FE0", "\u1FE1", "\u1FE2", "\u1FE3", "\u1FE4", "\u1FE5", "\u1FE6", "\u1FE7", "\u1FF2", "\u1FF3", "\u1FF4", "\u1FF6", "\u1FF7", "\u2071", "\u207F", "\u210A", "\u210E", "\u210F", "\u2113", "\u212F", "\u2134", "\u2139", "\u213C", "\u213D", "\u2146", "\u2147", "\u2148", "\u2149", "\u214E", "\u2184", "\u2C30", "\u2C31", "\u2C32", "\u2C33", "\u2C34", "\u2C35", "\u2C36", "\u2C37", "\u2C38", "\u2C39", "\u2C3A", "\u2C3B", "\u2C3C", "\u2C3D", "\u2C3E", "\u2C3F", "\u2C40", "\u2C41", "\u2C42", "\u2C43", "\u2C44", "\u2C45", "\u2C46", "\u2C47", "\u2C48", "\u2C49", "\u2C4A", "\u2C4B", "\u2C4C", "\u2C4D", "\u2C4E", "\u2C4F", "\u2C50", "\u2C51", "\u2C52", "\u2C53", "\u2C54", "\u2C55", "\u2C56", "\u2C57", "\u2C58", "\u2C59", "\u2C5A", "\u2C5B", "\u2C5C", "\u2C5D", "\u2C5E", "\u2C61", "\u2C65", "\u2C66", "\u2C68", "\u2C6A", "\u2C6C", "\u2C71", "\u2C73", "\u2C74", "\u2C76", "\u2C77", "\u2C78", "\u2C79", "\u2C7A", "\u2C7B", "\u2C7C", "\u2C81", "\u2C83", "\u2C85", "\u2C87", "\u2C89", "\u2C8B", "\u2C8D", "\u2C8F", "\u2C91", "\u2C93", "\u2C95", "\u2C97", "\u2C99", "\u2C9B", "\u2C9D", "\u2C9F", "\u2CA1", "\u2CA3", "\u2CA5", "\u2CA7", "\u2CA9", "\u2CAB", "\u2CAD", "\u2CAF", "\u2CB1", "\u2CB3", "\u2CB5", "\u2CB7", "\u2CB9", "\u2CBB", "\u2CBD", "\u2CBF", "\u2CC1", "\u2CC3", "\u2CC5", "\u2CC7", "\u2CC9", "\u2CCB", "\u2CCD", "\u2CCF", "\u2CD1", "\u2CD3", "\u2CD5", "\u2CD7", "\u2CD9", "\u2CDB", "\u2CDD", "\u2CDF", "\u2CE1", "\u2CE3", "\u2CE4", "\u2D00", "\u2D01", "\u2D02", "\u2D03", "\u2D04", "\u2D05", "\u2D06", "\u2D07", "\u2D08", "\u2D09", "\u2D0A", "\u2D0B", "\u2D0C", "\u2D0D", "\u2D0E", "\u2D0F", "\u2D10", "\u2D11", "\u2D12", "\u2D13", "\u2D14", "\u2D15", "\u2D16", "\u2D17", "\u2D18", "\u2D19", "\u2D1A", "\u2D1B", "\u2D1C", "\u2D1D", "\u2D1E", "\u2D1F", "\u2D20", "\u2D21", "\u2D22", "\u2D23", "\u2D24", "\u2D25", "\uA641", "\uA643", "\uA645", "\uA647", "\uA649", "\uA64B", "\uA64D", "\uA64F", "\uA651", "\uA653", "\uA655", "\uA657", "\uA659", "\uA65B", "\uA65D", "\uA65F", "\uA663", "\uA665", "\uA667", "\uA669", "\uA66B", "\uA66D", "\uA681", "\uA683", "\uA685", "\uA687", "\uA689", "\uA68B", "\uA68D", "\uA68F", "\uA691", "\uA693", "\uA695", "\uA697", "\uA723", "\uA725", "\uA727", "\uA729", "\uA72B", "\uA72D", "\uA72F", "\uA730", "\uA731", "\uA733", "\uA735", "\uA737", "\uA739", "\uA73B", "\uA73D", "\uA73F", "\uA741", "\uA743", "\uA745", "\uA747", "\uA749", "\uA74B", "\uA74D", "\uA74F", "\uA751", "\uA753", "\uA755", "\uA757", "\uA759", "\uA75B", "\uA75D", "\uA75F", "\uA761", "\uA763", "\uA765", "\uA767", "\uA769", "\uA76B", "\uA76D", "\uA76F", "\uA771", "\uA772", "\uA773", "\uA774", "\uA775", "\uA776", "\uA777", "\uA778", "\uA77A", "\uA77C", "\uA77F", "\uA781", "\uA783", "\uA785", "\uA787", "\uA78C", "\uFB00", "\uFB01", "\uFB02", "\uFB03", "\uFB04", "\uFB05", "\uFB06", "\uFB13", "\uFB14", "\uFB15", "\uFB16", "\uFB17", "\uFF41", "\uFF42", "\uFF43", "\uFF44", "\uFF45", "\uFF46", "\uFF47", "\uFF48", "\uFF49", "\uFF4A", "\uFF4B", "\uFF4C", "\uFF4D", "\uFF4E", "\uFF4F", "\uFF50", "\uFF51", "\uFF52", "\uFF53", "\uFF54", "\uFF55", "\uFF56", "\uFF57", "\uFF58", "\uFF59", "\uFF5A"], false, false), + peg$c248 = peg$otherExpectation("Unicode titlecase letter"), + peg$c249 = /^[\u01C5\u01C8\u01CB\u01F2\u1F88\u1F89\u1F8A\u1F8B\u1F8C\u1F8D\u1F8E\u1F8F\u1F98\u1F99\u1F9A\u1F9B\u1F9C\u1F9D\u1F9E\u1F9F\u1FA8\u1FA9\u1FAA\u1FAB\u1FAC\u1FAD\u1FAE\u1FAF\u1FBC\u1FCC]/, + peg$c250 = peg$classExpectation(["\u01C5", "\u01C8", "\u01CB", "\u01F2", "\u1F88", "\u1F89", "\u1F8A", "\u1F8B", "\u1F8C", "\u1F8D", "\u1F8E", "\u1F8F", "\u1F98", "\u1F99", "\u1F9A", "\u1F9B", "\u1F9C", "\u1F9D", "\u1F9E", "\u1F9F", "\u1FA8", "\u1FA9", "\u1FAA", "\u1FAB", "\u1FAC", "\u1FAD", "\u1FAE", "\u1FAF", "\u1FBC", "\u1FCC"], false, false), + peg$c251 = peg$otherExpectation("Unicode modifier letter"), + peg$c252 = /^[\u02B0\u02B1\u02B2\u02B3\u02B4\u02B5\u02B6\u02B7\u02B8\u02B9\u02BA\u02BB\u02BC\u02BD\u02BE\u02BF\u02C0\u02C1\u02C6\u02C7\u02C8\u02C9\u02CA\u02CB\u02CC\u02CD\u02CE\u02CF\u02D0\u02D1\u02E0\u02E1\u02E2\u02E3\u02E4\u02EC\u02EE\u0374\u037A\u0559\u0640\u06E5\u06E6\u07F4\u07F5\u07FA\u0971\u0E46\u0EC6\u10FC\u17D7\u1843\u1C78\u1C79\u1C7A\u1C7B\u1C7C\u1C7D\u1D2C\u1D2D\u1D2E\u1D2F\u1D30\u1D31\u1D32\u1D33\u1D34\u1D35\u1D36\u1D37\u1D38\u1D39\u1D3A\u1D3B\u1D3C\u1D3D\u1D3E\u1D3F\u1D40\u1D41\u1D42\u1D43\u1D44\u1D45\u1D46\u1D47\u1D48\u1D49\u1D4A\u1D4B\u1D4C\u1D4D\u1D4E\u1D4F\u1D50\u1D51\u1D52\u1D53\u1D54\u1D55\u1D56\u1D57\u1D58\u1D59\u1D5A\u1D5B\u1D5C\u1D5D\u1D5E\u1D5F\u1D60\u1D61\u1D78\u1D9B\u1D9C\u1D9D\u1D9E\u1D9F\u1DA0\u1DA1\u1DA2\u1DA3\u1DA4\u1DA5\u1DA6\u1DA7\u1DA8\u1DA9\u1DAA\u1DAB\u1DAC\u1DAD\u1DAE\u1DAF\u1DB0\u1DB1\u1DB2\u1DB3\u1DB4\u1DB5\u1DB6\u1DB7\u1DB8\u1DB9\u1DBA\u1DBB\u1DBC\u1DBD\u1DBE\u1DBF\u2090\u2091\u2092\u2093\u2094\u2C7D\u2D6F\u2E2F\u3005\u3031\u3032\u3033\u3034\u3035\u303B\u309D\u309E\u30FC\u30FD\u30FE\uA015\uA60C\uA67F\uA717\uA718\uA719\uA71A\uA71B\uA71C\uA71D\uA71E\uA71F\uA770\uA788\uFF70\uFF9E\uFF9F]/, + peg$c253 = peg$classExpectation(["\u02B0", "\u02B1", "\u02B2", "\u02B3", "\u02B4", "\u02B5", "\u02B6", "\u02B7", "\u02B8", "\u02B9", "\u02BA", "\u02BB", "\u02BC", "\u02BD", "\u02BE", "\u02BF", "\u02C0", "\u02C1", "\u02C6", "\u02C7", "\u02C8", "\u02C9", "\u02CA", "\u02CB", "\u02CC", "\u02CD", "\u02CE", "\u02CF", "\u02D0", "\u02D1", "\u02E0", "\u02E1", "\u02E2", "\u02E3", "\u02E4", "\u02EC", "\u02EE", "\u0374", "\u037A", "\u0559", "\u0640", "\u06E5", "\u06E6", "\u07F4", "\u07F5", "\u07FA", "\u0971", "\u0E46", "\u0EC6", "\u10FC", "\u17D7", "\u1843", "\u1C78", "\u1C79", "\u1C7A", "\u1C7B", "\u1C7C", "\u1C7D", "\u1D2C", "\u1D2D", "\u1D2E", "\u1D2F", "\u1D30", "\u1D31", "\u1D32", "\u1D33", "\u1D34", "\u1D35", "\u1D36", "\u1D37", "\u1D38", "\u1D39", "\u1D3A", "\u1D3B", "\u1D3C", "\u1D3D", "\u1D3E", "\u1D3F", "\u1D40", "\u1D41", "\u1D42", "\u1D43", "\u1D44", "\u1D45", "\u1D46", "\u1D47", "\u1D48", "\u1D49", "\u1D4A", "\u1D4B", "\u1D4C", "\u1D4D", "\u1D4E", "\u1D4F", "\u1D50", "\u1D51", "\u1D52", "\u1D53", "\u1D54", "\u1D55", "\u1D56", "\u1D57", "\u1D58", "\u1D59", "\u1D5A", "\u1D5B", "\u1D5C", "\u1D5D", "\u1D5E", "\u1D5F", "\u1D60", "\u1D61", "\u1D78", "\u1D9B", "\u1D9C", "\u1D9D", "\u1D9E", "\u1D9F", "\u1DA0", "\u1DA1", "\u1DA2", "\u1DA3", "\u1DA4", "\u1DA5", "\u1DA6", "\u1DA7", "\u1DA8", "\u1DA9", "\u1DAA", "\u1DAB", "\u1DAC", "\u1DAD", "\u1DAE", "\u1DAF", "\u1DB0", "\u1DB1", "\u1DB2", "\u1DB3", "\u1DB4", "\u1DB5", "\u1DB6", "\u1DB7", "\u1DB8", "\u1DB9", "\u1DBA", "\u1DBB", "\u1DBC", "\u1DBD", "\u1DBE", "\u1DBF", "\u2090", "\u2091", "\u2092", "\u2093", "\u2094", "\u2C7D", "\u2D6F", "\u2E2F", "\u3005", "\u3031", "\u3032", "\u3033", "\u3034", "\u3035", "\u303B", "\u309D", "\u309E", "\u30FC", "\u30FD", "\u30FE", "\uA015", "\uA60C", "\uA67F", "\uA717", "\uA718", "\uA719", "\uA71A", "\uA71B", "\uA71C", "\uA71D", "\uA71E", "\uA71F", "\uA770", "\uA788", "\uFF70", "\uFF9E", "\uFF9F"], false, false), + peg$c254 = peg$otherExpectation("Unicode other letter"), + peg$c255 = /^[\u01BB\u01C0\u01C1\u01C2\u01C3\u0294\u05D0\u05D1\u05D2\u05D3\u05D4\u05D5\u05D6\u05D7\u05D8\u05D9\u05DA\u05DB\u05DC\u05DD\u05DE\u05DF\u05E0\u05E1\u05E2\u05E3\u05E4\u05E5\u05E6\u05E7\u05E8\u05E9\u05EA\u05F0\u05F1\u05F2\u0621\u0622\u0623\u0624\u0625\u0626\u0627\u0628\u0629\u062A\u062B\u062C\u062D\u062E\u062F\u0630\u0631\u0632\u0633\u0634\u0635\u0636\u0637\u0638\u0639\u063A\u063B\u063C\u063D\u063E\u063F\u0641\u0642\u0643\u0644\u0645\u0646\u0647\u0648\u0649\u064A\u066E\u066F\u0671\u0672\u0673\u0674\u0675\u0676\u0677\u0678\u0679\u067A\u067B\u067C\u067D\u067E\u067F\u0680\u0681\u0682\u0683\u0684\u0685\u0686\u0687\u0688\u0689\u068A\u068B\u068C\u068D\u068E\u068F\u0690\u0691\u0692\u0693\u0694\u0695\u0696\u0697\u0698\u0699\u069A\u069B\u069C\u069D\u069E\u069F\u06A0\u06A1\u06A2\u06A3\u06A4\u06A5\u06A6\u06A7\u06A8\u06A9\u06AA\u06AB\u06AC\u06AD\u06AE\u06AF\u06B0\u06B1\u06B2\u06B3\u06B4\u06B5\u06B6\u06B7\u06B8\u06B9\u06BA\u06BB\u06BC\u06BD\u06BE\u06BF\u06C0\u06C1\u06C2\u06C3\u06C4\u06C5\u06C6\u06C7\u06C8\u06C9\u06CA\u06CB\u06CC\u06CD\u06CE\u06CF\u06D0\u06D1\u06D2\u06D3\u06D5\u06EE\u06EF\u06FA\u06FB\u06FC\u06FF\u0710\u0712\u0713\u0714\u0715\u0716\u0717\u0718\u0719\u071A\u071B\u071C\u071D\u071E\u071F\u0720\u0721\u0722\u0723\u0724\u0725\u0726\u0727\u0728\u0729\u072A\u072B\u072C\u072D\u072E\u072F\u074D\u074E\u074F\u0750\u0751\u0752\u0753\u0754\u0755\u0756\u0757\u0758\u0759\u075A\u075B\u075C\u075D\u075E\u075F\u0760\u0761\u0762\u0763\u0764\u0765\u0766\u0767\u0768\u0769\u076A\u076B\u076C\u076D\u076E\u076F\u0770\u0771\u0772\u0773\u0774\u0775\u0776\u0777\u0778\u0779\u077A\u077B\u077C\u077D\u077E\u077F\u0780\u0781\u0782\u0783\u0784\u0785\u0786\u0787\u0788\u0789\u078A\u078B\u078C\u078D\u078E\u078F\u0790\u0791\u0792\u0793\u0794\u0795\u0796\u0797\u0798\u0799\u079A\u079B\u079C\u079D\u079E\u079F\u07A0\u07A1\u07A2\u07A3\u07A4\u07A5\u07B1\u07CA\u07CB\u07CC\u07CD\u07CE\u07CF\u07D0\u07D1\u07D2\u07D3\u07D4\u07D5\u07D6\u07D7\u07D8\u07D9\u07DA\u07DB\u07DC\u07DD\u07DE\u07DF\u07E0\u07E1\u07E2\u07E3\u07E4\u07E5\u07E6\u07E7\u07E8\u07E9\u07EA\u0904\u0905\u0906\u0907\u0908\u0909\u090A\u090B\u090C\u090D\u090E\u090F\u0910\u0911\u0912\u0913\u0914\u0915\u0916\u0917\u0918\u0919\u091A\u091B\u091C\u091D\u091E\u091F\u0920\u0921\u0922\u0923\u0924\u0925\u0926\u0927\u0928\u0929\u092A\u092B\u092C\u092D\u092E\u092F\u0930\u0931\u0932\u0933\u0934\u0935\u0936\u0937\u0938\u0939\u093D\u0950\u0958\u0959\u095A\u095B\u095C\u095D\u095E\u095F\u0960\u0961\u0972\u097B\u097C\u097D\u097E\u097F\u0985\u0986\u0987\u0988\u0989\u098A\u098B\u098C\u098F\u0990\u0993\u0994\u0995\u0996\u0997\u0998\u0999\u099A\u099B\u099C\u099D\u099E\u099F\u09A0\u09A1\u09A2\u09A3\u09A4\u09A5\u09A6\u09A7\u09A8\u09AA\u09AB\u09AC\u09AD\u09AE\u09AF\u09B0\u09B2\u09B6\u09B7\u09B8\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF\u09E0\u09E1\u09F0\u09F1\u0A05\u0A06\u0A07\u0A08\u0A09\u0A0A\u0A0F\u0A10\u0A13\u0A14\u0A15\u0A16\u0A17\u0A18\u0A19\u0A1A\u0A1B\u0A1C\u0A1D\u0A1E\u0A1F\u0A20\u0A21\u0A22\u0A23\u0A24\u0A25\u0A26\u0A27\u0A28\u0A2A\u0A2B\u0A2C\u0A2D\u0A2E\u0A2F\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59\u0A5A\u0A5B\u0A5C\u0A5E\u0A72\u0A73\u0A74\u0A85\u0A86\u0A87\u0A88\u0A89\u0A8A\u0A8B\u0A8C\u0A8D\u0A8F\u0A90\u0A91\u0A93\u0A94\u0A95\u0A96\u0A97\u0A98\u0A99\u0A9A\u0A9B\u0A9C\u0A9D\u0A9E\u0A9F\u0AA0\u0AA1\u0AA2\u0AA3\u0AA4\u0AA5\u0AA6\u0AA7\u0AA8\u0AAA\u0AAB\u0AAC\u0AAD\u0AAE\u0AAF\u0AB0\u0AB2\u0AB3\u0AB5\u0AB6\u0AB7\u0AB8\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05\u0B06\u0B07\u0B08\u0B09\u0B0A\u0B0B\u0B0C\u0B0F\u0B10\u0B13\u0B14\u0B15\u0B16\u0B17\u0B18\u0B19\u0B1A\u0B1B\u0B1C\u0B1D\u0B1E\u0B1F\u0B20\u0B21\u0B22\u0B23\u0B24\u0B25\u0B26\u0B27\u0B28\u0B2A\u0B2B\u0B2C\u0B2D\u0B2E\u0B2F\u0B30\u0B32\u0B33\u0B35\u0B36\u0B37\u0B38\u0B39\u0B3D\u0B5C\u0B5D\u0B5F\u0B60\u0B61\u0B71\u0B83\u0B85\u0B86\u0B87\u0B88\u0B89\u0B8A\u0B8E\u0B8F\u0B90\u0B92\u0B93\u0B94\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8\u0BA9\u0BAA\u0BAE\u0BAF\u0BB0\u0BB1\u0BB2\u0BB3\u0BB4\u0BB5\u0BB6\u0BB7\u0BB8\u0BB9\u0BD0\u0C05\u0C06\u0C07\u0C08\u0C09\u0C0A\u0C0B\u0C0C\u0C0E\u0C0F\u0C10\u0C12\u0C13\u0C14\u0C15\u0C16\u0C17\u0C18\u0C19\u0C1A\u0C1B\u0C1C\u0C1D\u0C1E\u0C1F\u0C20\u0C21\u0C22\u0C23\u0C24\u0C25\u0C26\u0C27\u0C28\u0C2A\u0C2B\u0C2C\u0C2D\u0C2E\u0C2F\u0C30\u0C31\u0C32\u0C33\u0C35\u0C36\u0C37\u0C38\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85\u0C86\u0C87\u0C88\u0C89\u0C8A\u0C8B\u0C8C\u0C8E\u0C8F\u0C90\u0C92\u0C93\u0C94\u0C95\u0C96\u0C97\u0C98\u0C99\u0C9A\u0C9B\u0C9C\u0C9D\u0C9E\u0C9F\u0CA0\u0CA1\u0CA2\u0CA3\u0CA4\u0CA5\u0CA6\u0CA7\u0CA8\u0CAA\u0CAB\u0CAC\u0CAD\u0CAE\u0CAF\u0CB0\u0CB1\u0CB2\u0CB3\u0CB5\u0CB6\u0CB7\u0CB8\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0D05\u0D06\u0D07\u0D08\u0D09\u0D0A\u0D0B\u0D0C\u0D0E\u0D0F\u0D10\u0D12\u0D13\u0D14\u0D15\u0D16\u0D17\u0D18\u0D19\u0D1A\u0D1B\u0D1C\u0D1D\u0D1E\u0D1F\u0D20\u0D21\u0D22\u0D23\u0D24\u0D25\u0D26\u0D27\u0D28\u0D2A\u0D2B\u0D2C\u0D2D\u0D2E\u0D2F\u0D30\u0D31\u0D32\u0D33\u0D34\u0D35\u0D36\u0D37\u0D38\u0D39\u0D3D\u0D60\u0D61\u0D7A\u0D7B\u0D7C\u0D7D\u0D7E\u0D7F\u0D85\u0D86\u0D87\u0D88\u0D89\u0D8A\u0D8B\u0D8C\u0D8D\u0D8E\u0D8F\u0D90\u0D91\u0D92\u0D93\u0D94\u0D95\u0D96\u0D9A\u0D9B\u0D9C\u0D9D\u0D9E\u0D9F\u0DA0\u0DA1\u0DA2\u0DA3\u0DA4\u0DA5\u0DA6\u0DA7\u0DA8\u0DA9\u0DAA\u0DAB\u0DAC\u0DAD\u0DAE\u0DAF\u0DB0\u0DB1\u0DB3\u0DB4\u0DB5\u0DB6\u0DB7\u0DB8\u0DB9\u0DBA\u0DBB\u0DBD\u0DC0\u0DC1\u0DC2\u0DC3\u0DC4\u0DC5\u0DC6\u0E01\u0E02\u0E03\u0E04\u0E05\u0E06\u0E07\u0E08\u0E09\u0E0A\u0E0B\u0E0C\u0E0D\u0E0E\u0E0F\u0E10\u0E11\u0E12\u0E13\u0E14\u0E15\u0E16\u0E17\u0E18\u0E19\u0E1A\u0E1B\u0E1C\u0E1D\u0E1E\u0E1F\u0E20\u0E21\u0E22\u0E23\u0E24\u0E25\u0E26\u0E27\u0E28\u0E29\u0E2A\u0E2B\u0E2C\u0E2D\u0E2E\u0E2F\u0E30\u0E32\u0E33\u0E40\u0E41\u0E42\u0E43\u0E44\u0E45\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94\u0E95\u0E96\u0E97\u0E99\u0E9A\u0E9B\u0E9C\u0E9D\u0E9E\u0E9F\u0EA1\u0EA2\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD\u0EAE\u0EAF\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0\u0EC1\u0EC2\u0EC3\u0EC4\u0EDC\u0EDD\u0F00\u0F40\u0F41\u0F42\u0F43\u0F44\u0F45\u0F46\u0F47\u0F49\u0F4A\u0F4B\u0F4C\u0F4D\u0F4E\u0F4F\u0F50\u0F51\u0F52\u0F53\u0F54\u0F55\u0F56\u0F57\u0F58\u0F59\u0F5A\u0F5B\u0F5C\u0F5D\u0F5E\u0F5F\u0F60\u0F61\u0F62\u0F63\u0F64\u0F65\u0F66\u0F67\u0F68\u0F69\u0F6A\u0F6B\u0F6C\u0F88\u0F89\u0F8A\u0F8B\u1000\u1001\u1002\u1003\u1004\u1005\u1006\u1007\u1008\u1009\u100A\u100B\u100C\u100D\u100E\u100F\u1010\u1011\u1012\u1013\u1014\u1015\u1016\u1017\u1018\u1019\u101A\u101B\u101C\u101D\u101E\u101F\u1020\u1021\u1022\u1023\u1024\u1025\u1026\u1027\u1028\u1029\u102A\u103F\u1050\u1051\u1052\u1053\u1054\u1055\u105A\u105B\u105C\u105D\u1061\u1065\u1066\u106E\u106F\u1070\u1075\u1076\u1077\u1078\u1079\u107A\u107B\u107C\u107D\u107E\u107F\u1080\u1081\u108E\u10D0\u10D1\u10D2\u10D3\u10D4\u10D5\u10D6\u10D7\u10D8\u10D9\u10DA\u10DB\u10DC\u10DD\u10DE\u10DF\u10E0\u10E1\u10E2\u10E3\u10E4\u10E5\u10E6\u10E7\u10E8\u10E9\u10EA\u10EB\u10EC\u10ED\u10EE\u10EF\u10F0\u10F1\u10F2\u10F3\u10F4\u10F5\u10F6\u10F7\u10F8\u10F9\u10FA\u1100\u1101\u1102\u1103\u1104\u1105\u1106\u1107\u1108\u1109\u110A\u110B\u110C\u110D\u110E\u110F\u1110\u1111\u1112\u1113\u1114\u1115\u1116\u1117\u1118\u1119\u111A\u111B\u111C\u111D\u111E\u111F\u1120\u1121\u1122\u1123\u1124\u1125\u1126\u1127\u1128\u1129\u112A\u112B\u112C\u112D\u112E\u112F\u1130\u1131\u1132\u1133\u1134\u1135\u1136\u1137\u1138\u1139\u113A\u113B\u113C\u113D\u113E\u113F\u1140\u1141\u1142\u1143\u1144\u1145\u1146\u1147\u1148\u1149\u114A\u114B\u114C\u114D\u114E\u114F\u1150\u1151\u1152\u1153\u1154\u1155\u1156\u1157\u1158\u1159\u115F\u1160\u1161\u1162\u1163\u1164\u1165\u1166\u1167\u1168\u1169\u116A\u116B\u116C\u116D\u116E\u116F\u1170\u1171\u1172\u1173\u1174\u1175\u1176\u1177\u1178\u1179\u117A\u117B\u117C\u117D\u117E\u117F\u1180\u1181\u1182\u1183\u1184\u1185\u1186\u1187\u1188\u1189\u118A\u118B\u118C\u118D\u118E\u118F\u1190\u1191\u1192\u1193\u1194\u1195\u1196\u1197\u1198\u1199\u119A\u119B\u119C\u119D\u119E\u119F\u11A0\u11A1\u11A2\u11A8\u11A9\u11AA\u11AB\u11AC\u11AD\u11AE\u11AF\u11B0\u11B1\u11B2\u11B3\u11B4\u11B5\u11B6\u11B7\u11B8\u11B9\u11BA\u11BB\u11BC\u11BD\u11BE\u11BF\u11C0\u11C1\u11C2\u11C3\u11C4\u11C5\u11C6\u11C7\u11C8\u11C9\u11CA\u11CB\u11CC\u11CD\u11CE\u11CF\u11D0\u11D1\u11D2\u11D3\u11D4\u11D5\u11D6\u11D7\u11D8\u11D9\u11DA\u11DB\u11DC\u11DD\u11DE\u11DF\u11E0\u11E1\u11E2\u11E3\u11E4\u11E5\u11E6\u11E7\u11E8\u11E9\u11EA\u11EB\u11EC\u11ED\u11EE\u11EF\u11F0\u11F1\u11F2\u11F3\u11F4\u11F5\u11F6\u11F7\u11F8\u11F9\u1200\u1201\u1202\u1203\u1204\u1205\u1206\u1207\u1208\u1209\u120A\u120B\u120C\u120D\u120E\u120F\u1210\u1211\u1212\u1213\u1214\u1215\u1216\u1217\u1218\u1219\u121A\u121B\u121C\u121D\u121E\u121F\u1220\u1221\u1222\u1223\u1224\u1225\u1226\u1227\u1228\u1229\u122A\u122B\u122C\u122D\u122E\u122F\u1230\u1231\u1232\u1233\u1234\u1235\u1236\u1237\u1238\u1239\u123A\u123B\u123C\u123D\u123E\u123F\u1240\u1241\u1242\u1243\u1244\u1245\u1246\u1247\u1248\u124A\u124B\u124C\u124D\u1250\u1251\u1252\u1253\u1254\u1255\u1256\u1258\u125A\u125B\u125C\u125D\u1260\u1261\u1262\u1263\u1264\u1265\u1266\u1267\u1268\u1269\u126A\u126B\u126C\u126D\u126E\u126F\u1270\u1271\u1272\u1273\u1274\u1275\u1276\u1277\u1278\u1279\u127A\u127B\u127C\u127D\u127E\u127F\u1280\u1281\u1282\u1283\u1284\u1285\u1286\u1287\u1288\u128A\u128B\u128C\u128D\u1290\u1291\u1292\u1293\u1294\u1295\u1296\u1297\u1298\u1299\u129A\u129B\u129C\u129D\u129E\u129F\u12A0\u12A1\u12A2\u12A3\u12A4\u12A5\u12A6\u12A7\u12A8\u12A9\u12AA\u12AB\u12AC\u12AD\u12AE\u12AF\u12B0\u12B2\u12B3\u12B4\u12B5\u12B8\u12B9\u12BA\u12BB\u12BC\u12BD\u12BE\u12C0\u12C2\u12C3\u12C4\u12C5\u12C8\u12C9\u12CA\u12CB\u12CC\u12CD\u12CE\u12CF\u12D0\u12D1\u12D2\u12D3\u12D4\u12D5\u12D6\u12D8\u12D9\u12DA\u12DB\u12DC\u12DD\u12DE\u12DF\u12E0\u12E1\u12E2\u12E3\u12E4\u12E5\u12E6\u12E7\u12E8\u12E9\u12EA\u12EB\u12EC\u12ED\u12EE\u12EF\u12F0\u12F1\u12F2\u12F3\u12F4\u12F5\u12F6\u12F7\u12F8\u12F9\u12FA\u12FB\u12FC\u12FD\u12FE\u12FF\u1300\u1301\u1302\u1303\u1304\u1305\u1306\u1307\u1308\u1309\u130A\u130B\u130C\u130D\u130E\u130F\u1310\u1312\u1313\u1314\u1315\u1318\u1319\u131A\u131B\u131C\u131D\u131E\u131F\u1320\u1321\u1322\u1323\u1324\u1325\u1326\u1327\u1328\u1329\u132A\u132B\u132C\u132D\u132E\u132F\u1330\u1331\u1332\u1333\u1334\u1335\u1336\u1337\u1338\u1339\u133A\u133B\u133C\u133D\u133E\u133F\u1340\u1341\u1342\u1343\u1344\u1345\u1346\u1347\u1348\u1349\u134A\u134B\u134C\u134D\u134E\u134F\u1350\u1351\u1352\u1353\u1354\u1355\u1356\u1357\u1358\u1359\u135A\u1380\u1381\u1382\u1383\u1384\u1385\u1386\u1387\u1388\u1389\u138A\u138B\u138C\u138D\u138E\u138F\u13A0\u13A1\u13A2\u13A3\u13A4\u13A5\u13A6\u13A7\u13A8\u13A9\u13AA\u13AB\u13AC\u13AD\u13AE\u13AF\u13B0\u13B1\u13B2\u13B3\u13B4\u13B5\u13B6\u13B7\u13B8\u13B9\u13BA\u13BB\u13BC\u13BD\u13BE\u13BF\u13C0\u13C1\u13C2\u13C3\u13C4\u13C5\u13C6\u13C7\u13C8\u13C9\u13CA\u13CB\u13CC\u13CD\u13CE\u13CF\u13D0\u13D1\u13D2\u13D3\u13D4\u13D5\u13D6\u13D7\u13D8\u13D9\u13DA\u13DB\u13DC\u13DD\u13DE\u13DF\u13E0\u13E1\u13E2\u13E3\u13E4\u13E5\u13E6\u13E7\u13E8\u13E9\u13EA\u13EB\u13EC\u13ED\u13EE\u13EF\u13F0\u13F1\u13F2\u13F3\u13F4\u1401\u1402\u1403\u1404\u1405\u1406\u1407\u1408\u1409\u140A\u140B\u140C\u140D\u140E\u140F\u1410\u1411\u1412\u1413\u1414\u1415\u1416\u1417\u1418\u1419\u141A\u141B\u141C\u141D\u141E\u141F\u1420\u1421\u1422\u1423\u1424\u1425\u1426\u1427\u1428\u1429\u142A\u142B\u142C\u142D\u142E\u142F\u1430\u1431\u1432\u1433\u1434\u1435\u1436\u1437\u1438\u1439\u143A\u143B\u143C\u143D\u143E\u143F\u1440\u1441\u1442\u1443\u1444\u1445\u1446\u1447\u1448\u1449\u144A\u144B\u144C\u144D\u144E\u144F\u1450\u1451\u1452\u1453\u1454\u1455\u1456\u1457\u1458\u1459\u145A\u145B\u145C\u145D\u145E\u145F\u1460\u1461\u1462\u1463\u1464\u1465\u1466\u1467\u1468\u1469\u146A\u146B\u146C\u146D\u146E\u146F\u1470\u1471\u1472\u1473\u1474\u1475\u1476\u1477\u1478\u1479\u147A\u147B\u147C\u147D\u147E\u147F\u1480\u1481\u1482\u1483\u1484\u1485\u1486\u1487\u1488\u1489\u148A\u148B\u148C\u148D\u148E\u148F\u1490\u1491\u1492\u1493\u1494\u1495\u1496\u1497\u1498\u1499\u149A\u149B\u149C\u149D\u149E\u149F\u14A0\u14A1\u14A2\u14A3\u14A4\u14A5\u14A6\u14A7\u14A8\u14A9\u14AA\u14AB\u14AC\u14AD\u14AE\u14AF\u14B0\u14B1\u14B2\u14B3\u14B4\u14B5\u14B6\u14B7\u14B8\u14B9\u14BA\u14BB\u14BC\u14BD\u14BE\u14BF\u14C0\u14C1\u14C2\u14C3\u14C4\u14C5\u14C6\u14C7\u14C8\u14C9\u14CA\u14CB\u14CC\u14CD\u14CE\u14CF\u14D0\u14D1\u14D2\u14D3\u14D4\u14D5\u14D6\u14D7\u14D8\u14D9\u14DA\u14DB\u14DC\u14DD\u14DE\u14DF\u14E0\u14E1\u14E2\u14E3\u14E4\u14E5\u14E6\u14E7\u14E8\u14E9\u14EA\u14EB\u14EC\u14ED\u14EE\u14EF\u14F0\u14F1\u14F2\u14F3\u14F4\u14F5\u14F6\u14F7\u14F8\u14F9\u14FA\u14FB\u14FC\u14FD\u14FE\u14FF\u1500\u1501\u1502\u1503\u1504\u1505\u1506\u1507\u1508\u1509\u150A\u150B\u150C\u150D\u150E\u150F\u1510\u1511\u1512\u1513\u1514\u1515\u1516\u1517\u1518\u1519\u151A\u151B\u151C\u151D\u151E\u151F\u1520\u1521\u1522\u1523\u1524\u1525\u1526\u1527\u1528\u1529\u152A\u152B\u152C\u152D\u152E\u152F\u1530\u1531\u1532\u1533\u1534\u1535\u1536\u1537\u1538\u1539\u153A\u153B\u153C\u153D\u153E\u153F\u1540\u1541\u1542\u1543\u1544\u1545\u1546\u1547\u1548\u1549\u154A\u154B\u154C\u154D\u154E\u154F\u1550\u1551\u1552\u1553\u1554\u1555\u1556\u1557\u1558\u1559\u155A\u155B\u155C\u155D\u155E\u155F\u1560\u1561\u1562\u1563\u1564\u1565\u1566\u1567\u1568\u1569\u156A\u156B\u156C\u156D\u156E\u156F\u1570\u1571\u1572\u1573\u1574\u1575\u1576\u1577\u1578\u1579\u157A\u157B\u157C\u157D\u157E\u157F\u1580\u1581\u1582\u1583\u1584\u1585\u1586\u1587\u1588\u1589\u158A\u158B\u158C\u158D\u158E\u158F\u1590\u1591\u1592\u1593\u1594\u1595\u1596\u1597\u1598\u1599\u159A\u159B\u159C\u159D\u159E\u159F\u15A0\u15A1\u15A2\u15A3\u15A4\u15A5\u15A6\u15A7\u15A8\u15A9\u15AA\u15AB\u15AC\u15AD\u15AE\u15AF\u15B0\u15B1\u15B2\u15B3\u15B4\u15B5\u15B6\u15B7\u15B8\u15B9\u15BA\u15BB\u15BC\u15BD\u15BE\u15BF\u15C0\u15C1\u15C2\u15C3\u15C4\u15C5\u15C6\u15C7\u15C8\u15C9\u15CA\u15CB\u15CC\u15CD\u15CE\u15CF\u15D0\u15D1\u15D2\u15D3\u15D4\u15D5\u15D6\u15D7\u15D8\u15D9\u15DA\u15DB\u15DC\u15DD\u15DE\u15DF\u15E0\u15E1\u15E2\u15E3\u15E4\u15E5\u15E6\u15E7\u15E8\u15E9\u15EA\u15EB\u15EC\u15ED\u15EE\u15EF\u15F0\u15F1\u15F2\u15F3\u15F4\u15F5\u15F6\u15F7\u15F8\u15F9\u15FA\u15FB\u15FC\u15FD\u15FE\u15FF\u1600\u1601\u1602\u1603\u1604\u1605\u1606\u1607\u1608\u1609\u160A\u160B\u160C\u160D\u160E\u160F\u1610\u1611\u1612\u1613\u1614\u1615\u1616\u1617\u1618\u1619\u161A\u161B\u161C\u161D\u161E\u161F\u1620\u1621\u1622\u1623\u1624\u1625\u1626\u1627\u1628\u1629\u162A\u162B\u162C\u162D\u162E\u162F\u1630\u1631\u1632\u1633\u1634\u1635\u1636\u1637\u1638\u1639\u163A\u163B\u163C\u163D\u163E\u163F\u1640\u1641\u1642\u1643\u1644\u1645\u1646\u1647\u1648\u1649\u164A\u164B\u164C\u164D\u164E\u164F\u1650\u1651\u1652\u1653\u1654\u1655\u1656\u1657\u1658\u1659\u165A\u165B\u165C\u165D\u165E\u165F\u1660\u1661\u1662\u1663\u1664\u1665\u1666\u1667\u1668\u1669\u166A\u166B\u166C\u166F\u1670\u1671\u1672\u1673\u1674\u1675\u1676\u1681\u1682\u1683\u1684\u1685\u1686\u1687\u1688\u1689\u168A\u168B\u168C\u168D\u168E\u168F\u1690\u1691\u1692\u1693\u1694\u1695\u1696\u1697\u1698\u1699\u169A\u16A0\u16A1\u16A2\u16A3\u16A4\u16A5\u16A6\u16A7\u16A8\u16A9\u16AA\u16AB\u16AC\u16AD\u16AE\u16AF\u16B0\u16B1\u16B2\u16B3\u16B4\u16B5\u16B6\u16B7\u16B8\u16B9\u16BA\u16BB\u16BC\u16BD\u16BE\u16BF\u16C0\u16C1\u16C2\u16C3\u16C4\u16C5\u16C6\u16C7\u16C8\u16C9\u16CA\u16CB\u16CC\u16CD\u16CE\u16CF\u16D0\u16D1\u16D2\u16D3\u16D4\u16D5\u16D6\u16D7\u16D8\u16D9\u16DA\u16DB\u16DC\u16DD\u16DE\u16DF\u16E0\u16E1\u16E2\u16E3\u16E4\u16E5\u16E6\u16E7\u16E8\u16E9\u16EA\u1700\u1701\u1702\u1703\u1704\u1705\u1706\u1707\u1708\u1709\u170A\u170B\u170C\u170E\u170F\u1710\u1711\u1720\u1721\u1722\u1723\u1724\u1725\u1726\u1727\u1728\u1729\u172A\u172B\u172C\u172D\u172E\u172F\u1730\u1731\u1740\u1741\u1742\u1743\u1744\u1745\u1746\u1747\u1748\u1749\u174A\u174B\u174C\u174D\u174E\u174F\u1750\u1751\u1760\u1761\u1762\u1763\u1764\u1765\u1766\u1767\u1768\u1769\u176A\u176B\u176C\u176E\u176F\u1770\u1780\u1781\u1782\u1783\u1784\u1785\u1786\u1787\u1788\u1789\u178A\u178B\u178C\u178D\u178E\u178F\u1790\u1791\u1792\u1793\u1794\u1795\u1796\u1797\u1798\u1799\u179A\u179B\u179C\u179D\u179E\u179F\u17A0\u17A1\u17A2\u17A3\u17A4\u17A5\u17A6\u17A7\u17A8\u17A9\u17AA\u17AB\u17AC\u17AD\u17AE\u17AF\u17B0\u17B1\u17B2\u17B3\u17DC\u1820\u1821\u1822\u1823\u1824\u1825\u1826\u1827\u1828\u1829\u182A\u182B\u182C\u182D\u182E\u182F\u1830\u1831\u1832\u1833\u1834\u1835\u1836\u1837\u1838\u1839\u183A\u183B\u183C\u183D\u183E\u183F\u1840\u1841\u1842\u1844\u1845\u1846\u1847\u1848\u1849\u184A\u184B\u184C\u184D\u184E\u184F\u1850\u1851\u1852\u1853\u1854\u1855\u1856\u1857\u1858\u1859\u185A\u185B\u185C\u185D\u185E\u185F\u1860\u1861\u1862\u1863\u1864\u1865\u1866\u1867\u1868\u1869\u186A\u186B\u186C\u186D\u186E\u186F\u1870\u1871\u1872\u1873\u1874\u1875\u1876\u1877\u1880\u1881\u1882\u1883\u1884\u1885\u1886\u1887\u1888\u1889\u188A\u188B\u188C\u188D\u188E\u188F\u1890\u1891\u1892\u1893\u1894\u1895\u1896\u1897\u1898\u1899\u189A\u189B\u189C\u189D\u189E\u189F\u18A0\u18A1\u18A2\u18A3\u18A4\u18A5\u18A6\u18A7\u18A8\u18AA\u1900\u1901\u1902\u1903\u1904\u1905\u1906\u1907\u1908\u1909\u190A\u190B\u190C\u190D\u190E\u190F\u1910\u1911\u1912\u1913\u1914\u1915\u1916\u1917\u1918\u1919\u191A\u191B\u191C\u1950\u1951\u1952\u1953\u1954\u1955\u1956\u1957\u1958\u1959\u195A\u195B\u195C\u195D\u195E\u195F\u1960\u1961\u1962\u1963\u1964\u1965\u1966\u1967\u1968\u1969\u196A\u196B\u196C\u196D\u1970\u1971\u1972\u1973\u1974\u1980\u1981\u1982\u1983\u1984\u1985\u1986\u1987\u1988\u1989\u198A\u198B\u198C\u198D\u198E\u198F\u1990\u1991\u1992\u1993\u1994\u1995\u1996\u1997\u1998\u1999\u199A\u199B\u199C\u199D\u199E\u199F\u19A0\u19A1\u19A2\u19A3\u19A4\u19A5\u19A6\u19A7\u19A8\u19A9\u19C1\u19C2\u19C3\u19C4\u19C5\u19C6\u19C7\u1A00\u1A01\u1A02\u1A03\u1A04\u1A05\u1A06\u1A07\u1A08\u1A09\u1A0A\u1A0B\u1A0C\u1A0D\u1A0E\u1A0F\u1A10\u1A11\u1A12\u1A13\u1A14\u1A15\u1A16\u1B05\u1B06\u1B07\u1B08\u1B09\u1B0A\u1B0B\u1B0C\u1B0D\u1B0E\u1B0F\u1B10\u1B11\u1B12\u1B13\u1B14\u1B15\u1B16\u1B17\u1B18\u1B19\u1B1A\u1B1B\u1B1C\u1B1D\u1B1E\u1B1F\u1B20\u1B21\u1B22\u1B23\u1B24\u1B25\u1B26\u1B27\u1B28\u1B29\u1B2A\u1B2B\u1B2C\u1B2D\u1B2E\u1B2F\u1B30\u1B31\u1B32\u1B33\u1B45\u1B46\u1B47\u1B48\u1B49\u1B4A\u1B4B\u1B83\u1B84\u1B85\u1B86\u1B87\u1B88\u1B89\u1B8A\u1B8B\u1B8C\u1B8D\u1B8E\u1B8F\u1B90\u1B91\u1B92\u1B93\u1B94\u1B95\u1B96\u1B97\u1B98\u1B99\u1B9A\u1B9B\u1B9C\u1B9D\u1B9E\u1B9F\u1BA0\u1BAE\u1BAF\u1C00\u1C01\u1C02\u1C03\u1C04\u1C05\u1C06\u1C07\u1C08\u1C09\u1C0A\u1C0B\u1C0C\u1C0D\u1C0E\u1C0F\u1C10\u1C11\u1C12\u1C13\u1C14\u1C15\u1C16\u1C17\u1C18\u1C19\u1C1A\u1C1B\u1C1C\u1C1D\u1C1E\u1C1F\u1C20\u1C21\u1C22\u1C23\u1C4D\u1C4E\u1C4F\u1C5A\u1C5B\u1C5C\u1C5D\u1C5E\u1C5F\u1C60\u1C61\u1C62\u1C63\u1C64\u1C65\u1C66\u1C67\u1C68\u1C69\u1C6A\u1C6B\u1C6C\u1C6D\u1C6E\u1C6F\u1C70\u1C71\u1C72\u1C73\u1C74\u1C75\u1C76\u1C77\u2135\u2136\u2137\u2138\u2D30\u2D31\u2D32\u2D33\u2D34\u2D35\u2D36\u2D37\u2D38\u2D39\u2D3A\u2D3B\u2D3C\u2D3D\u2D3E\u2D3F\u2D40\u2D41\u2D42\u2D43\u2D44\u2D45\u2D46\u2D47\u2D48\u2D49\u2D4A\u2D4B\u2D4C\u2D4D\u2D4E\u2D4F\u2D50\u2D51\u2D52\u2D53\u2D54\u2D55\u2D56\u2D57\u2D58\u2D59\u2D5A\u2D5B\u2D5C\u2D5D\u2D5E\u2D5F\u2D60\u2D61\u2D62\u2D63\u2D64\u2D65\u2D80\u2D81\u2D82\u2D83\u2D84\u2D85\u2D86\u2D87\u2D88\u2D89\u2D8A\u2D8B\u2D8C\u2D8D\u2D8E\u2D8F\u2D90\u2D91\u2D92\u2D93\u2D94\u2D95\u2D96\u2DA0\u2DA1\u2DA2\u2DA3\u2DA4\u2DA5\u2DA6\u2DA8\u2DA9\u2DAA\u2DAB\u2DAC\u2DAD\u2DAE\u2DB0\u2DB1\u2DB2\u2DB3\u2DB4\u2DB5\u2DB6\u2DB8\u2DB9\u2DBA\u2DBB\u2DBC\u2DBD\u2DBE\u2DC0\u2DC1\u2DC2\u2DC3\u2DC4\u2DC5\u2DC6\u2DC8\u2DC9\u2DCA\u2DCB\u2DCC\u2DCD\u2DCE\u2DD0\u2DD1\u2DD2\u2DD3\u2DD4\u2DD5\u2DD6\u2DD8\u2DD9\u2DDA\u2DDB\u2DDC\u2DDD\u2DDE\u3006\u303C\u3041\u3042\u3043\u3044\u3045\u3046\u3047\u3048\u3049\u304A\u304B\u304C\u304D\u304E\u304F\u3050\u3051\u3052\u3053\u3054\u3055\u3056\u3057\u3058\u3059\u305A\u305B\u305C\u305D\u305E\u305F\u3060\u3061\u3062\u3063\u3064\u3065\u3066\u3067\u3068\u3069\u306A\u306B\u306C\u306D\u306E\u306F\u3070\u3071\u3072\u3073\u3074\u3075\u3076\u3077\u3078\u3079\u307A\u307B\u307C\u307D\u307E\u307F\u3080\u3081\u3082\u3083\u3084\u3085\u3086\u3087\u3088\u3089\u308A\u308B\u308C\u308D\u308E\u308F\u3090\u3091\u3092\u3093\u3094\u3095\u3096\u309F\u30A1\u30A2\u30A3\u30A4\u30A5\u30A6\u30A7\u30A8\u30A9\u30AA\u30AB\u30AC\u30AD\u30AE\u30AF\u30B0\u30B1\u30B2\u30B3\u30B4\u30B5\u30B6\u30B7\u30B8\u30B9\u30BA\u30BB\u30BC\u30BD\u30BE\u30BF\u30C0\u30C1\u30C2\u30C3\u30C4\u30C5\u30C6\u30C7\u30C8\u30C9\u30CA\u30CB\u30CC\u30CD\u30CE\u30CF\u30D0\u30D1\u30D2\u30D3\u30D4\u30D5\u30D6\u30D7\u30D8\u30D9\u30DA\u30DB\u30DC\u30DD\u30DE\u30DF\u30E0\u30E1\u30E2\u30E3\u30E4\u30E5\u30E6\u30E7\u30E8\u30E9\u30EA\u30EB\u30EC\u30ED\u30EE\u30EF\u30F0\u30F1\u30F2\u30F3\u30F4\u30F5\u30F6\u30F7\u30F8\u30F9\u30FA\u30FF\u3105\u3106\u3107\u3108\u3109\u310A\u310B\u310C\u310D\u310E\u310F\u3110\u3111\u3112\u3113\u3114\u3115\u3116\u3117\u3118\u3119\u311A\u311B\u311C\u311D\u311E\u311F\u3120\u3121\u3122\u3123\u3124\u3125\u3126\u3127\u3128\u3129\u312A\u312B\u312C\u312D\u3131\u3132\u3133\u3134\u3135\u3136\u3137\u3138\u3139\u313A\u313B\u313C\u313D\u313E\u313F\u3140\u3141\u3142\u3143\u3144\u3145\u3146\u3147\u3148\u3149\u314A\u314B\u314C\u314D\u314E\u314F\u3150\u3151\u3152\u3153\u3154\u3155\u3156\u3157\u3158\u3159\u315A\u315B\u315C\u315D\u315E\u315F\u3160\u3161\u3162\u3163\u3164\u3165\u3166\u3167\u3168\u3169\u316A\u316B\u316C\u316D\u316E\u316F\u3170\u3171\u3172\u3173\u3174\u3175\u3176\u3177\u3178\u3179\u317A\u317B\u317C\u317D\u317E\u317F\u3180\u3181\u3182\u3183\u3184\u3185\u3186\u3187\u3188\u3189\u318A\u318B\u318C\u318D\u318E\u31A0\u31A1\u31A2\u31A3\u31A4\u31A5\u31A6\u31A7\u31A8\u31A9\u31AA\u31AB\u31AC\u31AD\u31AE\u31AF\u31B0\u31B1\u31B2\u31B3\u31B4\u31B5\u31B6\u31B7\u31F0\u31F1\u31F2\u31F3\u31F4\u31F5\u31F6\u31F7\u31F8\u31F9\u31FA\u31FB\u31FC\u31FD\u31FE\u31FF\u3400\u4DB5\u4E00\u9FC3\uA000\uA001\uA002\uA003\uA004\uA005\uA006\uA007\uA008\uA009\uA00A\uA00B\uA00C\uA00D\uA00E\uA00F\uA010\uA011\uA012\uA013\uA014\uA016\uA017\uA018\uA019\uA01A\uA01B\uA01C\uA01D\uA01E\uA01F\uA020\uA021\uA022\uA023\uA024\uA025\uA026\uA027\uA028\uA029\uA02A\uA02B\uA02C\uA02D\uA02E\uA02F\uA030\uA031\uA032\uA033\uA034\uA035\uA036\uA037\uA038\uA039\uA03A\uA03B\uA03C\uA03D\uA03E\uA03F\uA040\uA041\uA042\uA043\uA044\uA045\uA046\uA047\uA048\uA049\uA04A\uA04B\uA04C\uA04D\uA04E\uA04F\uA050\uA051\uA052\uA053\uA054\uA055\uA056\uA057\uA058\uA059\uA05A\uA05B\uA05C\uA05D\uA05E\uA05F\uA060\uA061\uA062\uA063\uA064\uA065\uA066\uA067\uA068\uA069\uA06A\uA06B\uA06C\uA06D\uA06E\uA06F\uA070\uA071\uA072\uA073\uA074\uA075\uA076\uA077\uA078\uA079\uA07A\uA07B\uA07C\uA07D\uA07E\uA07F\uA080\uA081\uA082\uA083\uA084\uA085\uA086\uA087\uA088\uA089\uA08A\uA08B\uA08C\uA08D\uA08E\uA08F\uA090\uA091\uA092\uA093\uA094\uA095\uA096\uA097\uA098\uA099\uA09A\uA09B\uA09C\uA09D\uA09E\uA09F\uA0A0\uA0A1\uA0A2\uA0A3\uA0A4\uA0A5\uA0A6\uA0A7\uA0A8\uA0A9\uA0AA\uA0AB\uA0AC\uA0AD\uA0AE\uA0AF\uA0B0\uA0B1\uA0B2\uA0B3\uA0B4\uA0B5\uA0B6\uA0B7\uA0B8\uA0B9\uA0BA\uA0BB\uA0BC\uA0BD\uA0BE\uA0BF\uA0C0\uA0C1\uA0C2\uA0C3\uA0C4\uA0C5\uA0C6\uA0C7\uA0C8\uA0C9\uA0CA\uA0CB\uA0CC\uA0CD\uA0CE\uA0CF\uA0D0\uA0D1\uA0D2\uA0D3\uA0D4\uA0D5\uA0D6\uA0D7\uA0D8\uA0D9\uA0DA\uA0DB\uA0DC\uA0DD\uA0DE\uA0DF\uA0E0\uA0E1\uA0E2\uA0E3\uA0E4\uA0E5\uA0E6\uA0E7\uA0E8\uA0E9\uA0EA\uA0EB\uA0EC\uA0ED\uA0EE\uA0EF\uA0F0\uA0F1\uA0F2\uA0F3\uA0F4\uA0F5\uA0F6\uA0F7\uA0F8\uA0F9\uA0FA\uA0FB\uA0FC\uA0FD\uA0FE\uA0FF\uA100\uA101\uA102\uA103\uA104\uA105\uA106\uA107\uA108\uA109\uA10A\uA10B\uA10C\uA10D\uA10E\uA10F\uA110\uA111\uA112\uA113\uA114\uA115\uA116\uA117\uA118\uA119\uA11A\uA11B\uA11C\uA11D\uA11E\uA11F\uA120\uA121\uA122\uA123\uA124\uA125\uA126\uA127\uA128\uA129\uA12A\uA12B\uA12C\uA12D\uA12E\uA12F\uA130\uA131\uA132\uA133\uA134\uA135\uA136\uA137\uA138\uA139\uA13A\uA13B\uA13C\uA13D\uA13E\uA13F\uA140\uA141\uA142\uA143\uA144\uA145\uA146\uA147\uA148\uA149\uA14A\uA14B\uA14C\uA14D\uA14E\uA14F\uA150\uA151\uA152\uA153\uA154\uA155\uA156\uA157\uA158\uA159\uA15A\uA15B\uA15C\uA15D\uA15E\uA15F\uA160\uA161\uA162\uA163\uA164\uA165\uA166\uA167\uA168\uA169\uA16A\uA16B\uA16C\uA16D\uA16E\uA16F\uA170\uA171\uA172\uA173\uA174\uA175\uA176\uA177\uA178\uA179\uA17A\uA17B\uA17C\uA17D\uA17E\uA17F\uA180\uA181\uA182\uA183\uA184\uA185\uA186\uA187\uA188\uA189\uA18A\uA18B\uA18C\uA18D\uA18E\uA18F\uA190\uA191\uA192\uA193\uA194\uA195\uA196\uA197\uA198\uA199\uA19A\uA19B\uA19C\uA19D\uA19E\uA19F\uA1A0\uA1A1\uA1A2\uA1A3\uA1A4\uA1A5\uA1A6\uA1A7\uA1A8\uA1A9\uA1AA\uA1AB\uA1AC\uA1AD\uA1AE\uA1AF]/, + peg$c256 = peg$classExpectation(["\u01BB", "\u01C0", "\u01C1", "\u01C2", "\u01C3", "\u0294", "\u05D0", "\u05D1", "\u05D2", "\u05D3", "\u05D4", "\u05D5", "\u05D6", "\u05D7", "\u05D8", "\u05D9", "\u05DA", "\u05DB", "\u05DC", "\u05DD", "\u05DE", "\u05DF", "\u05E0", "\u05E1", "\u05E2", "\u05E3", "\u05E4", "\u05E5", "\u05E6", "\u05E7", "\u05E8", "\u05E9", "\u05EA", "\u05F0", "\u05F1", "\u05F2", "\u0621", "\u0622", "\u0623", "\u0624", "\u0625", "\u0626", "\u0627", "\u0628", "\u0629", "\u062A", "\u062B", "\u062C", "\u062D", "\u062E", "\u062F", "\u0630", "\u0631", "\u0632", "\u0633", "\u0634", "\u0635", "\u0636", "\u0637", "\u0638", "\u0639", "\u063A", "\u063B", "\u063C", "\u063D", "\u063E", "\u063F", "\u0641", "\u0642", "\u0643", "\u0644", "\u0645", "\u0646", "\u0647", "\u0648", "\u0649", "\u064A", "\u066E", "\u066F", "\u0671", "\u0672", "\u0673", "\u0674", "\u0675", "\u0676", "\u0677", "\u0678", "\u0679", "\u067A", "\u067B", "\u067C", "\u067D", "\u067E", "\u067F", "\u0680", "\u0681", "\u0682", "\u0683", "\u0684", "\u0685", "\u0686", "\u0687", "\u0688", "\u0689", "\u068A", "\u068B", "\u068C", "\u068D", "\u068E", "\u068F", "\u0690", "\u0691", "\u0692", "\u0693", "\u0694", "\u0695", "\u0696", "\u0697", "\u0698", "\u0699", "\u069A", "\u069B", "\u069C", "\u069D", "\u069E", "\u069F", "\u06A0", "\u06A1", "\u06A2", "\u06A3", "\u06A4", "\u06A5", "\u06A6", "\u06A7", "\u06A8", "\u06A9", "\u06AA", "\u06AB", "\u06AC", "\u06AD", "\u06AE", "\u06AF", "\u06B0", "\u06B1", "\u06B2", "\u06B3", "\u06B4", "\u06B5", "\u06B6", "\u06B7", "\u06B8", "\u06B9", "\u06BA", "\u06BB", "\u06BC", "\u06BD", "\u06BE", "\u06BF", "\u06C0", "\u06C1", "\u06C2", "\u06C3", "\u06C4", "\u06C5", "\u06C6", "\u06C7", "\u06C8", "\u06C9", "\u06CA", "\u06CB", "\u06CC", "\u06CD", "\u06CE", "\u06CF", "\u06D0", "\u06D1", "\u06D2", "\u06D3", "\u06D5", "\u06EE", "\u06EF", "\u06FA", "\u06FB", "\u06FC", "\u06FF", "\u0710", "\u0712", "\u0713", "\u0714", "\u0715", "\u0716", "\u0717", "\u0718", "\u0719", "\u071A", "\u071B", "\u071C", "\u071D", "\u071E", "\u071F", "\u0720", "\u0721", "\u0722", "\u0723", "\u0724", "\u0725", "\u0726", "\u0727", "\u0728", "\u0729", "\u072A", "\u072B", "\u072C", "\u072D", "\u072E", "\u072F", "\u074D", "\u074E", "\u074F", "\u0750", "\u0751", "\u0752", "\u0753", "\u0754", "\u0755", "\u0756", "\u0757", "\u0758", "\u0759", "\u075A", "\u075B", "\u075C", "\u075D", "\u075E", "\u075F", "\u0760", "\u0761", "\u0762", "\u0763", "\u0764", "\u0765", "\u0766", "\u0767", "\u0768", "\u0769", "\u076A", "\u076B", "\u076C", "\u076D", "\u076E", "\u076F", "\u0770", "\u0771", "\u0772", "\u0773", "\u0774", "\u0775", "\u0776", "\u0777", "\u0778", "\u0779", "\u077A", "\u077B", "\u077C", "\u077D", "\u077E", "\u077F", "\u0780", "\u0781", "\u0782", "\u0783", "\u0784", "\u0785", "\u0786", "\u0787", "\u0788", "\u0789", "\u078A", "\u078B", "\u078C", "\u078D", "\u078E", "\u078F", "\u0790", "\u0791", "\u0792", "\u0793", "\u0794", "\u0795", "\u0796", "\u0797", "\u0798", "\u0799", "\u079A", "\u079B", "\u079C", "\u079D", "\u079E", "\u079F", "\u07A0", "\u07A1", "\u07A2", "\u07A3", "\u07A4", "\u07A5", "\u07B1", "\u07CA", "\u07CB", "\u07CC", "\u07CD", "\u07CE", "\u07CF", "\u07D0", "\u07D1", "\u07D2", "\u07D3", "\u07D4", "\u07D5", "\u07D6", "\u07D7", "\u07D8", "\u07D9", "\u07DA", "\u07DB", "\u07DC", "\u07DD", "\u07DE", "\u07DF", "\u07E0", "\u07E1", "\u07E2", "\u07E3", "\u07E4", "\u07E5", "\u07E6", "\u07E7", "\u07E8", "\u07E9", "\u07EA", "\u0904", "\u0905", "\u0906", "\u0907", "\u0908", "\u0909", "\u090A", "\u090B", "\u090C", "\u090D", "\u090E", "\u090F", "\u0910", "\u0911", "\u0912", "\u0913", "\u0914", "\u0915", "\u0916", "\u0917", "\u0918", "\u0919", "\u091A", "\u091B", "\u091C", "\u091D", "\u091E", "\u091F", "\u0920", "\u0921", "\u0922", "\u0923", "\u0924", "\u0925", "\u0926", "\u0927", "\u0928", "\u0929", "\u092A", "\u092B", "\u092C", "\u092D", "\u092E", "\u092F", "\u0930", "\u0931", "\u0932", "\u0933", "\u0934", "\u0935", "\u0936", "\u0937", "\u0938", "\u0939", "\u093D", "\u0950", "\u0958", "\u0959", "\u095A", "\u095B", "\u095C", "\u095D", "\u095E", "\u095F", "\u0960", "\u0961", "\u0972", "\u097B", "\u097C", "\u097D", "\u097E", "\u097F", "\u0985", "\u0986", "\u0987", "\u0988", "\u0989", "\u098A", "\u098B", "\u098C", "\u098F", "\u0990", "\u0993", "\u0994", "\u0995", "\u0996", "\u0997", "\u0998", "\u0999", "\u099A", "\u099B", "\u099C", "\u099D", "\u099E", "\u099F", "\u09A0", "\u09A1", "\u09A2", "\u09A3", "\u09A4", "\u09A5", "\u09A6", "\u09A7", "\u09A8", "\u09AA", "\u09AB", "\u09AC", "\u09AD", "\u09AE", "\u09AF", "\u09B0", "\u09B2", "\u09B6", "\u09B7", "\u09B8", "\u09B9", "\u09BD", "\u09CE", "\u09DC", "\u09DD", "\u09DF", "\u09E0", "\u09E1", "\u09F0", "\u09F1", "\u0A05", "\u0A06", "\u0A07", "\u0A08", "\u0A09", "\u0A0A", "\u0A0F", "\u0A10", "\u0A13", "\u0A14", "\u0A15", "\u0A16", "\u0A17", "\u0A18", "\u0A19", "\u0A1A", "\u0A1B", "\u0A1C", "\u0A1D", "\u0A1E", "\u0A1F", "\u0A20", "\u0A21", "\u0A22", "\u0A23", "\u0A24", "\u0A25", "\u0A26", "\u0A27", "\u0A28", "\u0A2A", "\u0A2B", "\u0A2C", "\u0A2D", "\u0A2E", "\u0A2F", "\u0A30", "\u0A32", "\u0A33", "\u0A35", "\u0A36", "\u0A38", "\u0A39", "\u0A59", "\u0A5A", "\u0A5B", "\u0A5C", "\u0A5E", "\u0A72", "\u0A73", "\u0A74", "\u0A85", "\u0A86", "\u0A87", "\u0A88", "\u0A89", "\u0A8A", "\u0A8B", "\u0A8C", "\u0A8D", "\u0A8F", "\u0A90", "\u0A91", "\u0A93", "\u0A94", "\u0A95", "\u0A96", "\u0A97", "\u0A98", "\u0A99", "\u0A9A", "\u0A9B", "\u0A9C", "\u0A9D", "\u0A9E", "\u0A9F", "\u0AA0", "\u0AA1", "\u0AA2", "\u0AA3", "\u0AA4", "\u0AA5", "\u0AA6", "\u0AA7", "\u0AA8", "\u0AAA", "\u0AAB", "\u0AAC", "\u0AAD", "\u0AAE", "\u0AAF", "\u0AB0", "\u0AB2", "\u0AB3", "\u0AB5", "\u0AB6", "\u0AB7", "\u0AB8", "\u0AB9", "\u0ABD", "\u0AD0", "\u0AE0", "\u0AE1", "\u0B05", "\u0B06", "\u0B07", "\u0B08", "\u0B09", "\u0B0A", "\u0B0B", "\u0B0C", "\u0B0F", "\u0B10", "\u0B13", "\u0B14", "\u0B15", "\u0B16", "\u0B17", "\u0B18", "\u0B19", "\u0B1A", "\u0B1B", "\u0B1C", "\u0B1D", "\u0B1E", "\u0B1F", "\u0B20", "\u0B21", "\u0B22", "\u0B23", "\u0B24", "\u0B25", "\u0B26", "\u0B27", "\u0B28", "\u0B2A", "\u0B2B", "\u0B2C", "\u0B2D", "\u0B2E", "\u0B2F", "\u0B30", "\u0B32", "\u0B33", "\u0B35", "\u0B36", "\u0B37", "\u0B38", "\u0B39", "\u0B3D", "\u0B5C", "\u0B5D", "\u0B5F", "\u0B60", "\u0B61", "\u0B71", "\u0B83", "\u0B85", "\u0B86", "\u0B87", "\u0B88", "\u0B89", "\u0B8A", "\u0B8E", "\u0B8F", "\u0B90", "\u0B92", "\u0B93", "\u0B94", "\u0B95", "\u0B99", "\u0B9A", "\u0B9C", "\u0B9E", "\u0B9F", "\u0BA3", "\u0BA4", "\u0BA8", "\u0BA9", "\u0BAA", "\u0BAE", "\u0BAF", "\u0BB0", "\u0BB1", "\u0BB2", "\u0BB3", "\u0BB4", "\u0BB5", "\u0BB6", "\u0BB7", "\u0BB8", "\u0BB9", "\u0BD0", "\u0C05", "\u0C06", "\u0C07", "\u0C08", "\u0C09", "\u0C0A", "\u0C0B", "\u0C0C", "\u0C0E", "\u0C0F", "\u0C10", "\u0C12", "\u0C13", "\u0C14", "\u0C15", "\u0C16", "\u0C17", "\u0C18", "\u0C19", "\u0C1A", "\u0C1B", "\u0C1C", "\u0C1D", "\u0C1E", "\u0C1F", "\u0C20", "\u0C21", "\u0C22", "\u0C23", "\u0C24", "\u0C25", "\u0C26", "\u0C27", "\u0C28", "\u0C2A", "\u0C2B", "\u0C2C", "\u0C2D", "\u0C2E", "\u0C2F", "\u0C30", "\u0C31", "\u0C32", "\u0C33", "\u0C35", "\u0C36", "\u0C37", "\u0C38", "\u0C39", "\u0C3D", "\u0C58", "\u0C59", "\u0C60", "\u0C61", "\u0C85", "\u0C86", "\u0C87", "\u0C88", "\u0C89", "\u0C8A", "\u0C8B", "\u0C8C", "\u0C8E", "\u0C8F", "\u0C90", "\u0C92", "\u0C93", "\u0C94", "\u0C95", "\u0C96", "\u0C97", "\u0C98", "\u0C99", "\u0C9A", "\u0C9B", "\u0C9C", "\u0C9D", "\u0C9E", "\u0C9F", "\u0CA0", "\u0CA1", "\u0CA2", "\u0CA3", "\u0CA4", "\u0CA5", "\u0CA6", "\u0CA7", "\u0CA8", "\u0CAA", "\u0CAB", "\u0CAC", "\u0CAD", "\u0CAE", "\u0CAF", "\u0CB0", "\u0CB1", "\u0CB2", "\u0CB3", "\u0CB5", "\u0CB6", "\u0CB7", "\u0CB8", "\u0CB9", "\u0CBD", "\u0CDE", "\u0CE0", "\u0CE1", "\u0D05", "\u0D06", "\u0D07", "\u0D08", "\u0D09", "\u0D0A", "\u0D0B", "\u0D0C", "\u0D0E", "\u0D0F", "\u0D10", "\u0D12", "\u0D13", "\u0D14", "\u0D15", "\u0D16", "\u0D17", "\u0D18", "\u0D19", "\u0D1A", "\u0D1B", "\u0D1C", "\u0D1D", "\u0D1E", "\u0D1F", "\u0D20", "\u0D21", "\u0D22", "\u0D23", "\u0D24", "\u0D25", "\u0D26", "\u0D27", "\u0D28", "\u0D2A", "\u0D2B", "\u0D2C", "\u0D2D", "\u0D2E", "\u0D2F", "\u0D30", "\u0D31", "\u0D32", "\u0D33", "\u0D34", "\u0D35", "\u0D36", "\u0D37", "\u0D38", "\u0D39", "\u0D3D", "\u0D60", "\u0D61", "\u0D7A", "\u0D7B", "\u0D7C", "\u0D7D", "\u0D7E", "\u0D7F", "\u0D85", "\u0D86", "\u0D87", "\u0D88", "\u0D89", "\u0D8A", "\u0D8B", "\u0D8C", "\u0D8D", "\u0D8E", "\u0D8F", "\u0D90", "\u0D91", "\u0D92", "\u0D93", "\u0D94", "\u0D95", "\u0D96", "\u0D9A", "\u0D9B", "\u0D9C", "\u0D9D", "\u0D9E", "\u0D9F", "\u0DA0", "\u0DA1", "\u0DA2", "\u0DA3", "\u0DA4", "\u0DA5", "\u0DA6", "\u0DA7", "\u0DA8", "\u0DA9", "\u0DAA", "\u0DAB", "\u0DAC", "\u0DAD", "\u0DAE", "\u0DAF", "\u0DB0", "\u0DB1", "\u0DB3", "\u0DB4", "\u0DB5", "\u0DB6", "\u0DB7", "\u0DB8", "\u0DB9", "\u0DBA", "\u0DBB", "\u0DBD", "\u0DC0", "\u0DC1", "\u0DC2", "\u0DC3", "\u0DC4", "\u0DC5", "\u0DC6", "\u0E01", "\u0E02", "\u0E03", "\u0E04", "\u0E05", "\u0E06", "\u0E07", "\u0E08", "\u0E09", "\u0E0A", "\u0E0B", "\u0E0C", "\u0E0D", "\u0E0E", "\u0E0F", "\u0E10", "\u0E11", "\u0E12", "\u0E13", "\u0E14", "\u0E15", "\u0E16", "\u0E17", "\u0E18", "\u0E19", "\u0E1A", "\u0E1B", "\u0E1C", "\u0E1D", "\u0E1E", "\u0E1F", "\u0E20", "\u0E21", "\u0E22", "\u0E23", "\u0E24", "\u0E25", "\u0E26", "\u0E27", "\u0E28", "\u0E29", "\u0E2A", "\u0E2B", "\u0E2C", "\u0E2D", "\u0E2E", "\u0E2F", "\u0E30", "\u0E32", "\u0E33", "\u0E40", "\u0E41", "\u0E42", "\u0E43", "\u0E44", "\u0E45", "\u0E81", "\u0E82", "\u0E84", "\u0E87", "\u0E88", "\u0E8A", "\u0E8D", "\u0E94", "\u0E95", "\u0E96", "\u0E97", "\u0E99", "\u0E9A", "\u0E9B", "\u0E9C", "\u0E9D", "\u0E9E", "\u0E9F", "\u0EA1", "\u0EA2", "\u0EA3", "\u0EA5", "\u0EA7", "\u0EAA", "\u0EAB", "\u0EAD", "\u0EAE", "\u0EAF", "\u0EB0", "\u0EB2", "\u0EB3", "\u0EBD", "\u0EC0", "\u0EC1", "\u0EC2", "\u0EC3", "\u0EC4", "\u0EDC", "\u0EDD", "\u0F00", "\u0F40", "\u0F41", "\u0F42", "\u0F43", "\u0F44", "\u0F45", "\u0F46", "\u0F47", "\u0F49", "\u0F4A", "\u0F4B", "\u0F4C", "\u0F4D", "\u0F4E", "\u0F4F", "\u0F50", "\u0F51", "\u0F52", "\u0F53", "\u0F54", "\u0F55", "\u0F56", "\u0F57", "\u0F58", "\u0F59", "\u0F5A", "\u0F5B", "\u0F5C", "\u0F5D", "\u0F5E", "\u0F5F", "\u0F60", "\u0F61", "\u0F62", "\u0F63", "\u0F64", "\u0F65", "\u0F66", "\u0F67", "\u0F68", "\u0F69", "\u0F6A", "\u0F6B", "\u0F6C", "\u0F88", "\u0F89", "\u0F8A", "\u0F8B", "\u1000", "\u1001", "\u1002", "\u1003", "\u1004", "\u1005", "\u1006", "\u1007", "\u1008", "\u1009", "\u100A", "\u100B", "\u100C", "\u100D", "\u100E", "\u100F", "\u1010", "\u1011", "\u1012", "\u1013", "\u1014", "\u1015", "\u1016", "\u1017", "\u1018", "\u1019", "\u101A", "\u101B", "\u101C", "\u101D", "\u101E", "\u101F", "\u1020", "\u1021", "\u1022", "\u1023", "\u1024", "\u1025", "\u1026", "\u1027", "\u1028", "\u1029", "\u102A", "\u103F", "\u1050", "\u1051", "\u1052", "\u1053", "\u1054", "\u1055", "\u105A", "\u105B", "\u105C", "\u105D", "\u1061", "\u1065", "\u1066", "\u106E", "\u106F", "\u1070", "\u1075", "\u1076", "\u1077", "\u1078", "\u1079", "\u107A", "\u107B", "\u107C", "\u107D", "\u107E", "\u107F", "\u1080", "\u1081", "\u108E", "\u10D0", "\u10D1", "\u10D2", "\u10D3", "\u10D4", "\u10D5", "\u10D6", "\u10D7", "\u10D8", "\u10D9", "\u10DA", "\u10DB", "\u10DC", "\u10DD", "\u10DE", "\u10DF", "\u10E0", "\u10E1", "\u10E2", "\u10E3", "\u10E4", "\u10E5", "\u10E6", "\u10E7", "\u10E8", "\u10E9", "\u10EA", "\u10EB", "\u10EC", "\u10ED", "\u10EE", "\u10EF", "\u10F0", "\u10F1", "\u10F2", "\u10F3", "\u10F4", "\u10F5", "\u10F6", "\u10F7", "\u10F8", "\u10F9", "\u10FA", "\u1100", "\u1101", "\u1102", "\u1103", "\u1104", "\u1105", "\u1106", "\u1107", "\u1108", "\u1109", "\u110A", "\u110B", "\u110C", "\u110D", "\u110E", "\u110F", "\u1110", "\u1111", "\u1112", "\u1113", "\u1114", "\u1115", "\u1116", "\u1117", "\u1118", "\u1119", "\u111A", "\u111B", "\u111C", "\u111D", "\u111E", "\u111F", "\u1120", "\u1121", "\u1122", "\u1123", "\u1124", "\u1125", "\u1126", "\u1127", "\u1128", "\u1129", "\u112A", "\u112B", "\u112C", "\u112D", "\u112E", "\u112F", "\u1130", "\u1131", "\u1132", "\u1133", "\u1134", "\u1135", "\u1136", "\u1137", "\u1138", "\u1139", "\u113A", "\u113B", "\u113C", "\u113D", "\u113E", "\u113F", "\u1140", "\u1141", "\u1142", "\u1143", "\u1144", "\u1145", "\u1146", "\u1147", "\u1148", "\u1149", "\u114A", "\u114B", "\u114C", "\u114D", "\u114E", "\u114F", "\u1150", "\u1151", "\u1152", "\u1153", "\u1154", "\u1155", "\u1156", "\u1157", "\u1158", "\u1159", "\u115F", "\u1160", "\u1161", "\u1162", "\u1163", "\u1164", "\u1165", "\u1166", "\u1167", "\u1168", "\u1169", "\u116A", "\u116B", "\u116C", "\u116D", "\u116E", "\u116F", "\u1170", "\u1171", "\u1172", "\u1173", "\u1174", "\u1175", "\u1176", "\u1177", "\u1178", "\u1179", "\u117A", "\u117B", "\u117C", "\u117D", "\u117E", "\u117F", "\u1180", "\u1181", "\u1182", "\u1183", "\u1184", "\u1185", "\u1186", "\u1187", "\u1188", "\u1189", "\u118A", "\u118B", "\u118C", "\u118D", "\u118E", "\u118F", "\u1190", "\u1191", "\u1192", "\u1193", "\u1194", "\u1195", "\u1196", "\u1197", "\u1198", "\u1199", "\u119A", "\u119B", "\u119C", "\u119D", "\u119E", "\u119F", "\u11A0", "\u11A1", "\u11A2", "\u11A8", "\u11A9", "\u11AA", "\u11AB", "\u11AC", "\u11AD", "\u11AE", "\u11AF", "\u11B0", "\u11B1", "\u11B2", "\u11B3", "\u11B4", "\u11B5", "\u11B6", "\u11B7", "\u11B8", "\u11B9", "\u11BA", "\u11BB", "\u11BC", "\u11BD", "\u11BE", "\u11BF", "\u11C0", "\u11C1", "\u11C2", "\u11C3", "\u11C4", "\u11C5", "\u11C6", "\u11C7", "\u11C8", "\u11C9", "\u11CA", "\u11CB", "\u11CC", "\u11CD", "\u11CE", "\u11CF", "\u11D0", "\u11D1", "\u11D2", "\u11D3", "\u11D4", "\u11D5", "\u11D6", "\u11D7", "\u11D8", "\u11D9", "\u11DA", "\u11DB", "\u11DC", "\u11DD", "\u11DE", "\u11DF", "\u11E0", "\u11E1", "\u11E2", "\u11E3", "\u11E4", "\u11E5", "\u11E6", "\u11E7", "\u11E8", "\u11E9", "\u11EA", "\u11EB", "\u11EC", "\u11ED", "\u11EE", "\u11EF", "\u11F0", "\u11F1", "\u11F2", "\u11F3", "\u11F4", "\u11F5", "\u11F6", "\u11F7", "\u11F8", "\u11F9", "\u1200", "\u1201", "\u1202", "\u1203", "\u1204", "\u1205", "\u1206", "\u1207", "\u1208", "\u1209", "\u120A", "\u120B", "\u120C", "\u120D", "\u120E", "\u120F", "\u1210", "\u1211", "\u1212", "\u1213", "\u1214", "\u1215", "\u1216", "\u1217", "\u1218", "\u1219", "\u121A", "\u121B", "\u121C", "\u121D", "\u121E", "\u121F", "\u1220", "\u1221", "\u1222", "\u1223", "\u1224", "\u1225", "\u1226", "\u1227", "\u1228", "\u1229", "\u122A", "\u122B", "\u122C", "\u122D", "\u122E", "\u122F", "\u1230", "\u1231", "\u1232", "\u1233", "\u1234", "\u1235", "\u1236", "\u1237", "\u1238", "\u1239", "\u123A", "\u123B", "\u123C", "\u123D", "\u123E", "\u123F", "\u1240", "\u1241", "\u1242", "\u1243", "\u1244", "\u1245", "\u1246", "\u1247", "\u1248", "\u124A", "\u124B", "\u124C", "\u124D", "\u1250", "\u1251", "\u1252", "\u1253", "\u1254", "\u1255", "\u1256", "\u1258", "\u125A", "\u125B", "\u125C", "\u125D", "\u1260", "\u1261", "\u1262", "\u1263", "\u1264", "\u1265", "\u1266", "\u1267", "\u1268", "\u1269", "\u126A", "\u126B", "\u126C", "\u126D", "\u126E", "\u126F", "\u1270", "\u1271", "\u1272", "\u1273", "\u1274", "\u1275", "\u1276", "\u1277", "\u1278", "\u1279", "\u127A", "\u127B", "\u127C", "\u127D", "\u127E", "\u127F", "\u1280", "\u1281", "\u1282", "\u1283", "\u1284", "\u1285", "\u1286", "\u1287", "\u1288", "\u128A", "\u128B", "\u128C", "\u128D", "\u1290", "\u1291", "\u1292", "\u1293", "\u1294", "\u1295", "\u1296", "\u1297", "\u1298", "\u1299", "\u129A", "\u129B", "\u129C", "\u129D", "\u129E", "\u129F", "\u12A0", "\u12A1", "\u12A2", "\u12A3", "\u12A4", "\u12A5", "\u12A6", "\u12A7", "\u12A8", "\u12A9", "\u12AA", "\u12AB", "\u12AC", "\u12AD", "\u12AE", "\u12AF", "\u12B0", "\u12B2", "\u12B3", "\u12B4", "\u12B5", "\u12B8", "\u12B9", "\u12BA", "\u12BB", "\u12BC", "\u12BD", "\u12BE", "\u12C0", "\u12C2", "\u12C3", "\u12C4", "\u12C5", "\u12C8", "\u12C9", "\u12CA", "\u12CB", "\u12CC", "\u12CD", "\u12CE", "\u12CF", "\u12D0", "\u12D1", "\u12D2", "\u12D3", "\u12D4", "\u12D5", "\u12D6", "\u12D8", "\u12D9", "\u12DA", "\u12DB", "\u12DC", "\u12DD", "\u12DE", "\u12DF", "\u12E0", "\u12E1", "\u12E2", "\u12E3", "\u12E4", "\u12E5", "\u12E6", "\u12E7", "\u12E8", "\u12E9", "\u12EA", "\u12EB", "\u12EC", "\u12ED", "\u12EE", "\u12EF", "\u12F0", "\u12F1", "\u12F2", "\u12F3", "\u12F4", "\u12F5", "\u12F6", "\u12F7", "\u12F8", "\u12F9", "\u12FA", "\u12FB", "\u12FC", "\u12FD", "\u12FE", "\u12FF", "\u1300", "\u1301", "\u1302", "\u1303", "\u1304", "\u1305", "\u1306", "\u1307", "\u1308", "\u1309", "\u130A", "\u130B", "\u130C", "\u130D", "\u130E", "\u130F", "\u1310", "\u1312", "\u1313", "\u1314", "\u1315", "\u1318", "\u1319", "\u131A", "\u131B", "\u131C", "\u131D", "\u131E", "\u131F", "\u1320", "\u1321", "\u1322", "\u1323", "\u1324", "\u1325", "\u1326", "\u1327", "\u1328", "\u1329", "\u132A", "\u132B", "\u132C", "\u132D", "\u132E", "\u132F", "\u1330", "\u1331", "\u1332", "\u1333", "\u1334", "\u1335", "\u1336", "\u1337", "\u1338", "\u1339", "\u133A", "\u133B", "\u133C", "\u133D", "\u133E", "\u133F", "\u1340", "\u1341", "\u1342", "\u1343", "\u1344", "\u1345", "\u1346", "\u1347", "\u1348", "\u1349", "\u134A", "\u134B", "\u134C", "\u134D", "\u134E", "\u134F", "\u1350", "\u1351", "\u1352", "\u1353", "\u1354", "\u1355", "\u1356", "\u1357", "\u1358", "\u1359", "\u135A", "\u1380", "\u1381", "\u1382", "\u1383", "\u1384", "\u1385", "\u1386", "\u1387", "\u1388", "\u1389", "\u138A", "\u138B", "\u138C", "\u138D", "\u138E", "\u138F", "\u13A0", "\u13A1", "\u13A2", "\u13A3", "\u13A4", "\u13A5", "\u13A6", "\u13A7", "\u13A8", "\u13A9", "\u13AA", "\u13AB", "\u13AC", "\u13AD", "\u13AE", "\u13AF", "\u13B0", "\u13B1", "\u13B2", "\u13B3", "\u13B4", "\u13B5", "\u13B6", "\u13B7", "\u13B8", "\u13B9", "\u13BA", "\u13BB", "\u13BC", "\u13BD", "\u13BE", "\u13BF", "\u13C0", "\u13C1", "\u13C2", "\u13C3", "\u13C4", "\u13C5", "\u13C6", "\u13C7", "\u13C8", "\u13C9", "\u13CA", "\u13CB", "\u13CC", "\u13CD", "\u13CE", "\u13CF", "\u13D0", "\u13D1", "\u13D2", "\u13D3", "\u13D4", "\u13D5", "\u13D6", "\u13D7", "\u13D8", "\u13D9", "\u13DA", "\u13DB", "\u13DC", "\u13DD", "\u13DE", "\u13DF", "\u13E0", "\u13E1", "\u13E2", "\u13E3", "\u13E4", "\u13E5", "\u13E6", "\u13E7", "\u13E8", "\u13E9", "\u13EA", "\u13EB", "\u13EC", "\u13ED", "\u13EE", "\u13EF", "\u13F0", "\u13F1", "\u13F2", "\u13F3", "\u13F4", "\u1401", "\u1402", "\u1403", "\u1404", "\u1405", "\u1406", "\u1407", "\u1408", "\u1409", "\u140A", "\u140B", "\u140C", "\u140D", "\u140E", "\u140F", "\u1410", "\u1411", "\u1412", "\u1413", "\u1414", "\u1415", "\u1416", "\u1417", "\u1418", "\u1419", "\u141A", "\u141B", "\u141C", "\u141D", "\u141E", "\u141F", "\u1420", "\u1421", "\u1422", "\u1423", "\u1424", "\u1425", "\u1426", "\u1427", "\u1428", "\u1429", "\u142A", "\u142B", "\u142C", "\u142D", "\u142E", "\u142F", "\u1430", "\u1431", "\u1432", "\u1433", "\u1434", "\u1435", "\u1436", "\u1437", "\u1438", "\u1439", "\u143A", "\u143B", "\u143C", "\u143D", "\u143E", "\u143F", "\u1440", "\u1441", "\u1442", "\u1443", "\u1444", "\u1445", "\u1446", "\u1447", "\u1448", "\u1449", "\u144A", "\u144B", "\u144C", "\u144D", "\u144E", "\u144F", "\u1450", "\u1451", "\u1452", "\u1453", "\u1454", "\u1455", "\u1456", "\u1457", "\u1458", "\u1459", "\u145A", "\u145B", "\u145C", "\u145D", "\u145E", "\u145F", "\u1460", "\u1461", "\u1462", "\u1463", "\u1464", "\u1465", "\u1466", "\u1467", "\u1468", "\u1469", "\u146A", "\u146B", "\u146C", "\u146D", "\u146E", "\u146F", "\u1470", "\u1471", "\u1472", "\u1473", "\u1474", "\u1475", "\u1476", "\u1477", "\u1478", "\u1479", "\u147A", "\u147B", "\u147C", "\u147D", "\u147E", "\u147F", "\u1480", "\u1481", "\u1482", "\u1483", "\u1484", "\u1485", "\u1486", "\u1487", "\u1488", "\u1489", "\u148A", "\u148B", "\u148C", "\u148D", "\u148E", "\u148F", "\u1490", "\u1491", "\u1492", "\u1493", "\u1494", "\u1495", "\u1496", "\u1497", "\u1498", "\u1499", "\u149A", "\u149B", "\u149C", "\u149D", "\u149E", "\u149F", "\u14A0", "\u14A1", "\u14A2", "\u14A3", "\u14A4", "\u14A5", "\u14A6", "\u14A7", "\u14A8", "\u14A9", "\u14AA", "\u14AB", "\u14AC", "\u14AD", "\u14AE", "\u14AF", "\u14B0", "\u14B1", "\u14B2", "\u14B3", "\u14B4", "\u14B5", "\u14B6", "\u14B7", "\u14B8", "\u14B9", "\u14BA", "\u14BB", "\u14BC", "\u14BD", "\u14BE", "\u14BF", "\u14C0", "\u14C1", "\u14C2", "\u14C3", "\u14C4", "\u14C5", "\u14C6", "\u14C7", "\u14C8", "\u14C9", "\u14CA", "\u14CB", "\u14CC", "\u14CD", "\u14CE", "\u14CF", "\u14D0", "\u14D1", "\u14D2", "\u14D3", "\u14D4", "\u14D5", "\u14D6", "\u14D7", "\u14D8", "\u14D9", "\u14DA", "\u14DB", "\u14DC", "\u14DD", "\u14DE", "\u14DF", "\u14E0", "\u14E1", "\u14E2", "\u14E3", "\u14E4", "\u14E5", "\u14E6", "\u14E7", "\u14E8", "\u14E9", "\u14EA", "\u14EB", "\u14EC", "\u14ED", "\u14EE", "\u14EF", "\u14F0", "\u14F1", "\u14F2", "\u14F3", "\u14F4", "\u14F5", "\u14F6", "\u14F7", "\u14F8", "\u14F9", "\u14FA", "\u14FB", "\u14FC", "\u14FD", "\u14FE", "\u14FF", "\u1500", "\u1501", "\u1502", "\u1503", "\u1504", "\u1505", "\u1506", "\u1507", "\u1508", "\u1509", "\u150A", "\u150B", "\u150C", "\u150D", "\u150E", "\u150F", "\u1510", "\u1511", "\u1512", "\u1513", "\u1514", "\u1515", "\u1516", "\u1517", "\u1518", "\u1519", "\u151A", "\u151B", "\u151C", "\u151D", "\u151E", "\u151F", "\u1520", "\u1521", "\u1522", "\u1523", "\u1524", "\u1525", "\u1526", "\u1527", "\u1528", "\u1529", "\u152A", "\u152B", "\u152C", "\u152D", "\u152E", "\u152F", "\u1530", "\u1531", "\u1532", "\u1533", "\u1534", "\u1535", "\u1536", "\u1537", "\u1538", "\u1539", "\u153A", "\u153B", "\u153C", "\u153D", "\u153E", "\u153F", "\u1540", "\u1541", "\u1542", "\u1543", "\u1544", "\u1545", "\u1546", "\u1547", "\u1548", "\u1549", "\u154A", "\u154B", "\u154C", "\u154D", "\u154E", "\u154F", "\u1550", "\u1551", "\u1552", "\u1553", "\u1554", "\u1555", "\u1556", "\u1557", "\u1558", "\u1559", "\u155A", "\u155B", "\u155C", "\u155D", "\u155E", "\u155F", "\u1560", "\u1561", "\u1562", "\u1563", "\u1564", "\u1565", "\u1566", "\u1567", "\u1568", "\u1569", "\u156A", "\u156B", "\u156C", "\u156D", "\u156E", "\u156F", "\u1570", "\u1571", "\u1572", "\u1573", "\u1574", "\u1575", "\u1576", "\u1577", "\u1578", "\u1579", "\u157A", "\u157B", "\u157C", "\u157D", "\u157E", "\u157F", "\u1580", "\u1581", "\u1582", "\u1583", "\u1584", "\u1585", "\u1586", "\u1587", "\u1588", "\u1589", "\u158A", "\u158B", "\u158C", "\u158D", "\u158E", "\u158F", "\u1590", "\u1591", "\u1592", "\u1593", "\u1594", "\u1595", "\u1596", "\u1597", "\u1598", "\u1599", "\u159A", "\u159B", "\u159C", "\u159D", "\u159E", "\u159F", "\u15A0", "\u15A1", "\u15A2", "\u15A3", "\u15A4", "\u15A5", "\u15A6", "\u15A7", "\u15A8", "\u15A9", "\u15AA", "\u15AB", "\u15AC", "\u15AD", "\u15AE", "\u15AF", "\u15B0", "\u15B1", "\u15B2", "\u15B3", "\u15B4", "\u15B5", "\u15B6", "\u15B7", "\u15B8", "\u15B9", "\u15BA", "\u15BB", "\u15BC", "\u15BD", "\u15BE", "\u15BF", "\u15C0", "\u15C1", "\u15C2", "\u15C3", "\u15C4", "\u15C5", "\u15C6", "\u15C7", "\u15C8", "\u15C9", "\u15CA", "\u15CB", "\u15CC", "\u15CD", "\u15CE", "\u15CF", "\u15D0", "\u15D1", "\u15D2", "\u15D3", "\u15D4", "\u15D5", "\u15D6", "\u15D7", "\u15D8", "\u15D9", "\u15DA", "\u15DB", "\u15DC", "\u15DD", "\u15DE", "\u15DF", "\u15E0", "\u15E1", "\u15E2", "\u15E3", "\u15E4", "\u15E5", "\u15E6", "\u15E7", "\u15E8", "\u15E9", "\u15EA", "\u15EB", "\u15EC", "\u15ED", "\u15EE", "\u15EF", "\u15F0", "\u15F1", "\u15F2", "\u15F3", "\u15F4", "\u15F5", "\u15F6", "\u15F7", "\u15F8", "\u15F9", "\u15FA", "\u15FB", "\u15FC", "\u15FD", "\u15FE", "\u15FF", "\u1600", "\u1601", "\u1602", "\u1603", "\u1604", "\u1605", "\u1606", "\u1607", "\u1608", "\u1609", "\u160A", "\u160B", "\u160C", "\u160D", "\u160E", "\u160F", "\u1610", "\u1611", "\u1612", "\u1613", "\u1614", "\u1615", "\u1616", "\u1617", "\u1618", "\u1619", "\u161A", "\u161B", "\u161C", "\u161D", "\u161E", "\u161F", "\u1620", "\u1621", "\u1622", "\u1623", "\u1624", "\u1625", "\u1626", "\u1627", "\u1628", "\u1629", "\u162A", "\u162B", "\u162C", "\u162D", "\u162E", "\u162F", "\u1630", "\u1631", "\u1632", "\u1633", "\u1634", "\u1635", "\u1636", "\u1637", "\u1638", "\u1639", "\u163A", "\u163B", "\u163C", "\u163D", "\u163E", "\u163F", "\u1640", "\u1641", "\u1642", "\u1643", "\u1644", "\u1645", "\u1646", "\u1647", "\u1648", "\u1649", "\u164A", "\u164B", "\u164C", "\u164D", "\u164E", "\u164F", "\u1650", "\u1651", "\u1652", "\u1653", "\u1654", "\u1655", "\u1656", "\u1657", "\u1658", "\u1659", "\u165A", "\u165B", "\u165C", "\u165D", "\u165E", "\u165F", "\u1660", "\u1661", "\u1662", "\u1663", "\u1664", "\u1665", "\u1666", "\u1667", "\u1668", "\u1669", "\u166A", "\u166B", "\u166C", "\u166F", "\u1670", "\u1671", "\u1672", "\u1673", "\u1674", "\u1675", "\u1676", "\u1681", "\u1682", "\u1683", "\u1684", "\u1685", "\u1686", "\u1687", "\u1688", "\u1689", "\u168A", "\u168B", "\u168C", "\u168D", "\u168E", "\u168F", "\u1690", "\u1691", "\u1692", "\u1693", "\u1694", "\u1695", "\u1696", "\u1697", "\u1698", "\u1699", "\u169A", "\u16A0", "\u16A1", "\u16A2", "\u16A3", "\u16A4", "\u16A5", "\u16A6", "\u16A7", "\u16A8", "\u16A9", "\u16AA", "\u16AB", "\u16AC", "\u16AD", "\u16AE", "\u16AF", "\u16B0", "\u16B1", "\u16B2", "\u16B3", "\u16B4", "\u16B5", "\u16B6", "\u16B7", "\u16B8", "\u16B9", "\u16BA", "\u16BB", "\u16BC", "\u16BD", "\u16BE", "\u16BF", "\u16C0", "\u16C1", "\u16C2", "\u16C3", "\u16C4", "\u16C5", "\u16C6", "\u16C7", "\u16C8", "\u16C9", "\u16CA", "\u16CB", "\u16CC", "\u16CD", "\u16CE", "\u16CF", "\u16D0", "\u16D1", "\u16D2", "\u16D3", "\u16D4", "\u16D5", "\u16D6", "\u16D7", "\u16D8", "\u16D9", "\u16DA", "\u16DB", "\u16DC", "\u16DD", "\u16DE", "\u16DF", "\u16E0", "\u16E1", "\u16E2", "\u16E3", "\u16E4", "\u16E5", "\u16E6", "\u16E7", "\u16E8", "\u16E9", "\u16EA", "\u1700", "\u1701", "\u1702", "\u1703", "\u1704", "\u1705", "\u1706", "\u1707", "\u1708", "\u1709", "\u170A", "\u170B", "\u170C", "\u170E", "\u170F", "\u1710", "\u1711", "\u1720", "\u1721", "\u1722", "\u1723", "\u1724", "\u1725", "\u1726", "\u1727", "\u1728", "\u1729", "\u172A", "\u172B", "\u172C", "\u172D", "\u172E", "\u172F", "\u1730", "\u1731", "\u1740", "\u1741", "\u1742", "\u1743", "\u1744", "\u1745", "\u1746", "\u1747", "\u1748", "\u1749", "\u174A", "\u174B", "\u174C", "\u174D", "\u174E", "\u174F", "\u1750", "\u1751", "\u1760", "\u1761", "\u1762", "\u1763", "\u1764", "\u1765", "\u1766", "\u1767", "\u1768", "\u1769", "\u176A", "\u176B", "\u176C", "\u176E", "\u176F", "\u1770", "\u1780", "\u1781", "\u1782", "\u1783", "\u1784", "\u1785", "\u1786", "\u1787", "\u1788", "\u1789", "\u178A", "\u178B", "\u178C", "\u178D", "\u178E", "\u178F", "\u1790", "\u1791", "\u1792", "\u1793", "\u1794", "\u1795", "\u1796", "\u1797", "\u1798", "\u1799", "\u179A", "\u179B", "\u179C", "\u179D", "\u179E", "\u179F", "\u17A0", "\u17A1", "\u17A2", "\u17A3", "\u17A4", "\u17A5", "\u17A6", "\u17A7", "\u17A8", "\u17A9", "\u17AA", "\u17AB", "\u17AC", "\u17AD", "\u17AE", "\u17AF", "\u17B0", "\u17B1", "\u17B2", "\u17B3", "\u17DC", "\u1820", "\u1821", "\u1822", "\u1823", "\u1824", "\u1825", "\u1826", "\u1827", "\u1828", "\u1829", "\u182A", "\u182B", "\u182C", "\u182D", "\u182E", "\u182F", "\u1830", "\u1831", "\u1832", "\u1833", "\u1834", "\u1835", "\u1836", "\u1837", "\u1838", "\u1839", "\u183A", "\u183B", "\u183C", "\u183D", "\u183E", "\u183F", "\u1840", "\u1841", "\u1842", "\u1844", "\u1845", "\u1846", "\u1847", "\u1848", "\u1849", "\u184A", "\u184B", "\u184C", "\u184D", "\u184E", "\u184F", "\u1850", "\u1851", "\u1852", "\u1853", "\u1854", "\u1855", "\u1856", "\u1857", "\u1858", "\u1859", "\u185A", "\u185B", "\u185C", "\u185D", "\u185E", "\u185F", "\u1860", "\u1861", "\u1862", "\u1863", "\u1864", "\u1865", "\u1866", "\u1867", "\u1868", "\u1869", "\u186A", "\u186B", "\u186C", "\u186D", "\u186E", "\u186F", "\u1870", "\u1871", "\u1872", "\u1873", "\u1874", "\u1875", "\u1876", "\u1877", "\u1880", "\u1881", "\u1882", "\u1883", "\u1884", "\u1885", "\u1886", "\u1887", "\u1888", "\u1889", "\u188A", "\u188B", "\u188C", "\u188D", "\u188E", "\u188F", "\u1890", "\u1891", "\u1892", "\u1893", "\u1894", "\u1895", "\u1896", "\u1897", "\u1898", "\u1899", "\u189A", "\u189B", "\u189C", "\u189D", "\u189E", "\u189F", "\u18A0", "\u18A1", "\u18A2", "\u18A3", "\u18A4", "\u18A5", "\u18A6", "\u18A7", "\u18A8", "\u18AA", "\u1900", "\u1901", "\u1902", "\u1903", "\u1904", "\u1905", "\u1906", "\u1907", "\u1908", "\u1909", "\u190A", "\u190B", "\u190C", "\u190D", "\u190E", "\u190F", "\u1910", "\u1911", "\u1912", "\u1913", "\u1914", "\u1915", "\u1916", "\u1917", "\u1918", "\u1919", "\u191A", "\u191B", "\u191C", "\u1950", "\u1951", "\u1952", "\u1953", "\u1954", "\u1955", "\u1956", "\u1957", "\u1958", "\u1959", "\u195A", "\u195B", "\u195C", "\u195D", "\u195E", "\u195F", "\u1960", "\u1961", "\u1962", "\u1963", "\u1964", "\u1965", "\u1966", "\u1967", "\u1968", "\u1969", "\u196A", "\u196B", "\u196C", "\u196D", "\u1970", "\u1971", "\u1972", "\u1973", "\u1974", "\u1980", "\u1981", "\u1982", "\u1983", "\u1984", "\u1985", "\u1986", "\u1987", "\u1988", "\u1989", "\u198A", "\u198B", "\u198C", "\u198D", "\u198E", "\u198F", "\u1990", "\u1991", "\u1992", "\u1993", "\u1994", "\u1995", "\u1996", "\u1997", "\u1998", "\u1999", "\u199A", "\u199B", "\u199C", "\u199D", "\u199E", "\u199F", "\u19A0", "\u19A1", "\u19A2", "\u19A3", "\u19A4", "\u19A5", "\u19A6", "\u19A7", "\u19A8", "\u19A9", "\u19C1", "\u19C2", "\u19C3", "\u19C4", "\u19C5", "\u19C6", "\u19C7", "\u1A00", "\u1A01", "\u1A02", "\u1A03", "\u1A04", "\u1A05", "\u1A06", "\u1A07", "\u1A08", "\u1A09", "\u1A0A", "\u1A0B", "\u1A0C", "\u1A0D", "\u1A0E", "\u1A0F", "\u1A10", "\u1A11", "\u1A12", "\u1A13", "\u1A14", "\u1A15", "\u1A16", "\u1B05", "\u1B06", "\u1B07", "\u1B08", "\u1B09", "\u1B0A", "\u1B0B", "\u1B0C", "\u1B0D", "\u1B0E", "\u1B0F", "\u1B10", "\u1B11", "\u1B12", "\u1B13", "\u1B14", "\u1B15", "\u1B16", "\u1B17", "\u1B18", "\u1B19", "\u1B1A", "\u1B1B", "\u1B1C", "\u1B1D", "\u1B1E", "\u1B1F", "\u1B20", "\u1B21", "\u1B22", "\u1B23", "\u1B24", "\u1B25", "\u1B26", "\u1B27", "\u1B28", "\u1B29", "\u1B2A", "\u1B2B", "\u1B2C", "\u1B2D", "\u1B2E", "\u1B2F", "\u1B30", "\u1B31", "\u1B32", "\u1B33", "\u1B45", "\u1B46", "\u1B47", "\u1B48", "\u1B49", "\u1B4A", "\u1B4B", "\u1B83", "\u1B84", "\u1B85", "\u1B86", "\u1B87", "\u1B88", "\u1B89", "\u1B8A", "\u1B8B", "\u1B8C", "\u1B8D", "\u1B8E", "\u1B8F", "\u1B90", "\u1B91", "\u1B92", "\u1B93", "\u1B94", "\u1B95", "\u1B96", "\u1B97", "\u1B98", "\u1B99", "\u1B9A", "\u1B9B", "\u1B9C", "\u1B9D", "\u1B9E", "\u1B9F", "\u1BA0", "\u1BAE", "\u1BAF", "\u1C00", "\u1C01", "\u1C02", "\u1C03", "\u1C04", "\u1C05", "\u1C06", "\u1C07", "\u1C08", "\u1C09", "\u1C0A", "\u1C0B", "\u1C0C", "\u1C0D", "\u1C0E", "\u1C0F", "\u1C10", "\u1C11", "\u1C12", "\u1C13", "\u1C14", "\u1C15", "\u1C16", "\u1C17", "\u1C18", "\u1C19", "\u1C1A", "\u1C1B", "\u1C1C", "\u1C1D", "\u1C1E", "\u1C1F", "\u1C20", "\u1C21", "\u1C22", "\u1C23", "\u1C4D", "\u1C4E", "\u1C4F", "\u1C5A", "\u1C5B", "\u1C5C", "\u1C5D", "\u1C5E", "\u1C5F", "\u1C60", "\u1C61", "\u1C62", "\u1C63", "\u1C64", "\u1C65", "\u1C66", "\u1C67", "\u1C68", "\u1C69", "\u1C6A", "\u1C6B", "\u1C6C", "\u1C6D", "\u1C6E", "\u1C6F", "\u1C70", "\u1C71", "\u1C72", "\u1C73", "\u1C74", "\u1C75", "\u1C76", "\u1C77", "\u2135", "\u2136", "\u2137", "\u2138", "\u2D30", "\u2D31", "\u2D32", "\u2D33", "\u2D34", "\u2D35", "\u2D36", "\u2D37", "\u2D38", "\u2D39", "\u2D3A", "\u2D3B", "\u2D3C", "\u2D3D", "\u2D3E", "\u2D3F", "\u2D40", "\u2D41", "\u2D42", "\u2D43", "\u2D44", "\u2D45", "\u2D46", "\u2D47", "\u2D48", "\u2D49", "\u2D4A", "\u2D4B", "\u2D4C", "\u2D4D", "\u2D4E", "\u2D4F", "\u2D50", "\u2D51", "\u2D52", "\u2D53", "\u2D54", "\u2D55", "\u2D56", "\u2D57", "\u2D58", "\u2D59", "\u2D5A", "\u2D5B", "\u2D5C", "\u2D5D", "\u2D5E", "\u2D5F", "\u2D60", "\u2D61", "\u2D62", "\u2D63", "\u2D64", "\u2D65", "\u2D80", "\u2D81", "\u2D82", "\u2D83", "\u2D84", "\u2D85", "\u2D86", "\u2D87", "\u2D88", "\u2D89", "\u2D8A", "\u2D8B", "\u2D8C", "\u2D8D", "\u2D8E", "\u2D8F", "\u2D90", "\u2D91", "\u2D92", "\u2D93", "\u2D94", "\u2D95", "\u2D96", "\u2DA0", "\u2DA1", "\u2DA2", "\u2DA3", "\u2DA4", "\u2DA5", "\u2DA6", "\u2DA8", "\u2DA9", "\u2DAA", "\u2DAB", "\u2DAC", "\u2DAD", "\u2DAE", "\u2DB0", "\u2DB1", "\u2DB2", "\u2DB3", "\u2DB4", "\u2DB5", "\u2DB6", "\u2DB8", "\u2DB9", "\u2DBA", "\u2DBB", "\u2DBC", "\u2DBD", "\u2DBE", "\u2DC0", "\u2DC1", "\u2DC2", "\u2DC3", "\u2DC4", "\u2DC5", "\u2DC6", "\u2DC8", "\u2DC9", "\u2DCA", "\u2DCB", "\u2DCC", "\u2DCD", "\u2DCE", "\u2DD0", "\u2DD1", "\u2DD2", "\u2DD3", "\u2DD4", "\u2DD5", "\u2DD6", "\u2DD8", "\u2DD9", "\u2DDA", "\u2DDB", "\u2DDC", "\u2DDD", "\u2DDE", "\u3006", "\u303C", "\u3041", "\u3042", "\u3043", "\u3044", "\u3045", "\u3046", "\u3047", "\u3048", "\u3049", "\u304A", "\u304B", "\u304C", "\u304D", "\u304E", "\u304F", "\u3050", "\u3051", "\u3052", "\u3053", "\u3054", "\u3055", "\u3056", "\u3057", "\u3058", "\u3059", "\u305A", "\u305B", "\u305C", "\u305D", "\u305E", "\u305F", "\u3060", "\u3061", "\u3062", "\u3063", "\u3064", "\u3065", "\u3066", "\u3067", "\u3068", "\u3069", "\u306A", "\u306B", "\u306C", "\u306D", "\u306E", "\u306F", "\u3070", "\u3071", "\u3072", "\u3073", "\u3074", "\u3075", "\u3076", "\u3077", "\u3078", "\u3079", "\u307A", "\u307B", "\u307C", "\u307D", "\u307E", "\u307F", "\u3080", "\u3081", "\u3082", "\u3083", "\u3084", "\u3085", "\u3086", "\u3087", "\u3088", "\u3089", "\u308A", "\u308B", "\u308C", "\u308D", "\u308E", "\u308F", "\u3090", "\u3091", "\u3092", "\u3093", "\u3094", "\u3095", "\u3096", "\u309F", "\u30A1", "\u30A2", "\u30A3", "\u30A4", "\u30A5", "\u30A6", "\u30A7", "\u30A8", "\u30A9", "\u30AA", "\u30AB", "\u30AC", "\u30AD", "\u30AE", "\u30AF", "\u30B0", "\u30B1", "\u30B2", "\u30B3", "\u30B4", "\u30B5", "\u30B6", "\u30B7", "\u30B8", "\u30B9", "\u30BA", "\u30BB", "\u30BC", "\u30BD", "\u30BE", "\u30BF", "\u30C0", "\u30C1", "\u30C2", "\u30C3", "\u30C4", "\u30C5", "\u30C6", "\u30C7", "\u30C8", "\u30C9", "\u30CA", "\u30CB", "\u30CC", "\u30CD", "\u30CE", "\u30CF", "\u30D0", "\u30D1", "\u30D2", "\u30D3", "\u30D4", "\u30D5", "\u30D6", "\u30D7", "\u30D8", "\u30D9", "\u30DA", "\u30DB", "\u30DC", "\u30DD", "\u30DE", "\u30DF", "\u30E0", "\u30E1", "\u30E2", "\u30E3", "\u30E4", "\u30E5", "\u30E6", "\u30E7", "\u30E8", "\u30E9", "\u30EA", "\u30EB", "\u30EC", "\u30ED", "\u30EE", "\u30EF", "\u30F0", "\u30F1", "\u30F2", "\u30F3", "\u30F4", "\u30F5", "\u30F6", "\u30F7", "\u30F8", "\u30F9", "\u30FA", "\u30FF", "\u3105", "\u3106", "\u3107", "\u3108", "\u3109", "\u310A", "\u310B", "\u310C", "\u310D", "\u310E", "\u310F", "\u3110", "\u3111", "\u3112", "\u3113", "\u3114", "\u3115", "\u3116", "\u3117", "\u3118", "\u3119", "\u311A", "\u311B", "\u311C", "\u311D", "\u311E", "\u311F", "\u3120", "\u3121", "\u3122", "\u3123", "\u3124", "\u3125", "\u3126", "\u3127", "\u3128", "\u3129", "\u312A", "\u312B", "\u312C", "\u312D", "\u3131", "\u3132", "\u3133", "\u3134", "\u3135", "\u3136", "\u3137", "\u3138", "\u3139", "\u313A", "\u313B", "\u313C", "\u313D", "\u313E", "\u313F", "\u3140", "\u3141", "\u3142", "\u3143", "\u3144", "\u3145", "\u3146", "\u3147", "\u3148", "\u3149", "\u314A", "\u314B", "\u314C", "\u314D", "\u314E", "\u314F", "\u3150", "\u3151", "\u3152", "\u3153", "\u3154", "\u3155", "\u3156", "\u3157", "\u3158", "\u3159", "\u315A", "\u315B", "\u315C", "\u315D", "\u315E", "\u315F", "\u3160", "\u3161", "\u3162", "\u3163", "\u3164", "\u3165", "\u3166", "\u3167", "\u3168", "\u3169", "\u316A", "\u316B", "\u316C", "\u316D", "\u316E", "\u316F", "\u3170", "\u3171", "\u3172", "\u3173", "\u3174", "\u3175", "\u3176", "\u3177", "\u3178", "\u3179", "\u317A", "\u317B", "\u317C", "\u317D", "\u317E", "\u317F", "\u3180", "\u3181", "\u3182", "\u3183", "\u3184", "\u3185", "\u3186", "\u3187", "\u3188", "\u3189", "\u318A", "\u318B", "\u318C", "\u318D", "\u318E", "\u31A0", "\u31A1", "\u31A2", "\u31A3", "\u31A4", "\u31A5", "\u31A6", "\u31A7", "\u31A8", "\u31A9", "\u31AA", "\u31AB", "\u31AC", "\u31AD", "\u31AE", "\u31AF", "\u31B0", "\u31B1", "\u31B2", "\u31B3", "\u31B4", "\u31B5", "\u31B6", "\u31B7", "\u31F0", "\u31F1", "\u31F2", "\u31F3", "\u31F4", "\u31F5", "\u31F6", "\u31F7", "\u31F8", "\u31F9", "\u31FA", "\u31FB", "\u31FC", "\u31FD", "\u31FE", "\u31FF", "\u3400", "\u4DB5", "\u4E00", "\u9FC3", "\uA000", "\uA001", "\uA002", "\uA003", "\uA004", "\uA005", "\uA006", "\uA007", "\uA008", "\uA009", "\uA00A", "\uA00B", "\uA00C", "\uA00D", "\uA00E", "\uA00F", "\uA010", "\uA011", "\uA012", "\uA013", "\uA014", "\uA016", "\uA017", "\uA018", "\uA019", "\uA01A", "\uA01B", "\uA01C", "\uA01D", "\uA01E", "\uA01F", "\uA020", "\uA021", "\uA022", "\uA023", "\uA024", "\uA025", "\uA026", "\uA027", "\uA028", "\uA029", "\uA02A", "\uA02B", "\uA02C", "\uA02D", "\uA02E", "\uA02F", "\uA030", "\uA031", "\uA032", "\uA033", "\uA034", "\uA035", "\uA036", "\uA037", "\uA038", "\uA039", "\uA03A", "\uA03B", "\uA03C", "\uA03D", "\uA03E", "\uA03F", "\uA040", "\uA041", "\uA042", "\uA043", "\uA044", "\uA045", "\uA046", "\uA047", "\uA048", "\uA049", "\uA04A", "\uA04B", "\uA04C", "\uA04D", "\uA04E", "\uA04F", "\uA050", "\uA051", "\uA052", "\uA053", "\uA054", "\uA055", "\uA056", "\uA057", "\uA058", "\uA059", "\uA05A", "\uA05B", "\uA05C", "\uA05D", "\uA05E", "\uA05F", "\uA060", "\uA061", "\uA062", "\uA063", "\uA064", "\uA065", "\uA066", "\uA067", "\uA068", "\uA069", "\uA06A", "\uA06B", "\uA06C", "\uA06D", "\uA06E", "\uA06F", "\uA070", "\uA071", "\uA072", "\uA073", "\uA074", "\uA075", "\uA076", "\uA077", "\uA078", "\uA079", "\uA07A", "\uA07B", "\uA07C", "\uA07D", "\uA07E", "\uA07F", "\uA080", "\uA081", "\uA082", "\uA083", "\uA084", "\uA085", "\uA086", "\uA087", "\uA088", "\uA089", "\uA08A", "\uA08B", "\uA08C", "\uA08D", "\uA08E", "\uA08F", "\uA090", "\uA091", "\uA092", "\uA093", "\uA094", "\uA095", "\uA096", "\uA097", "\uA098", "\uA099", "\uA09A", "\uA09B", "\uA09C", "\uA09D", "\uA09E", "\uA09F", "\uA0A0", "\uA0A1", "\uA0A2", "\uA0A3", "\uA0A4", "\uA0A5", "\uA0A6", "\uA0A7", "\uA0A8", "\uA0A9", "\uA0AA", "\uA0AB", "\uA0AC", "\uA0AD", "\uA0AE", "\uA0AF", "\uA0B0", "\uA0B1", "\uA0B2", "\uA0B3", "\uA0B4", "\uA0B5", "\uA0B6", "\uA0B7", "\uA0B8", "\uA0B9", "\uA0BA", "\uA0BB", "\uA0BC", "\uA0BD", "\uA0BE", "\uA0BF", "\uA0C0", "\uA0C1", "\uA0C2", "\uA0C3", "\uA0C4", "\uA0C5", "\uA0C6", "\uA0C7", "\uA0C8", "\uA0C9", "\uA0CA", "\uA0CB", "\uA0CC", "\uA0CD", "\uA0CE", "\uA0CF", "\uA0D0", "\uA0D1", "\uA0D2", "\uA0D3", "\uA0D4", "\uA0D5", "\uA0D6", "\uA0D7", "\uA0D8", "\uA0D9", "\uA0DA", "\uA0DB", "\uA0DC", "\uA0DD", "\uA0DE", "\uA0DF", "\uA0E0", "\uA0E1", "\uA0E2", "\uA0E3", "\uA0E4", "\uA0E5", "\uA0E6", "\uA0E7", "\uA0E8", "\uA0E9", "\uA0EA", "\uA0EB", "\uA0EC", "\uA0ED", "\uA0EE", "\uA0EF", "\uA0F0", "\uA0F1", "\uA0F2", "\uA0F3", "\uA0F4", "\uA0F5", "\uA0F6", "\uA0F7", "\uA0F8", "\uA0F9", "\uA0FA", "\uA0FB", "\uA0FC", "\uA0FD", "\uA0FE", "\uA0FF", "\uA100", "\uA101", "\uA102", "\uA103", "\uA104", "\uA105", "\uA106", "\uA107", "\uA108", "\uA109", "\uA10A", "\uA10B", "\uA10C", "\uA10D", "\uA10E", "\uA10F", "\uA110", "\uA111", "\uA112", "\uA113", "\uA114", "\uA115", "\uA116", "\uA117", "\uA118", "\uA119", "\uA11A", "\uA11B", "\uA11C", "\uA11D", "\uA11E", "\uA11F", "\uA120", "\uA121", "\uA122", "\uA123", "\uA124", "\uA125", "\uA126", "\uA127", "\uA128", "\uA129", "\uA12A", "\uA12B", "\uA12C", "\uA12D", "\uA12E", "\uA12F", "\uA130", "\uA131", "\uA132", "\uA133", "\uA134", "\uA135", "\uA136", "\uA137", "\uA138", "\uA139", "\uA13A", "\uA13B", "\uA13C", "\uA13D", "\uA13E", "\uA13F", "\uA140", "\uA141", "\uA142", "\uA143", "\uA144", "\uA145", "\uA146", "\uA147", "\uA148", "\uA149", "\uA14A", "\uA14B", "\uA14C", "\uA14D", "\uA14E", "\uA14F", "\uA150", "\uA151", "\uA152", "\uA153", "\uA154", "\uA155", "\uA156", "\uA157", "\uA158", "\uA159", "\uA15A", "\uA15B", "\uA15C", "\uA15D", "\uA15E", "\uA15F", "\uA160", "\uA161", "\uA162", "\uA163", "\uA164", "\uA165", "\uA166", "\uA167", "\uA168", "\uA169", "\uA16A", "\uA16B", "\uA16C", "\uA16D", "\uA16E", "\uA16F", "\uA170", "\uA171", "\uA172", "\uA173", "\uA174", "\uA175", "\uA176", "\uA177", "\uA178", "\uA179", "\uA17A", "\uA17B", "\uA17C", "\uA17D", "\uA17E", "\uA17F", "\uA180", "\uA181", "\uA182", "\uA183", "\uA184", "\uA185", "\uA186", "\uA187", "\uA188", "\uA189", "\uA18A", "\uA18B", "\uA18C", "\uA18D", "\uA18E", "\uA18F", "\uA190", "\uA191", "\uA192", "\uA193", "\uA194", "\uA195", "\uA196", "\uA197", "\uA198", "\uA199", "\uA19A", "\uA19B", "\uA19C", "\uA19D", "\uA19E", "\uA19F", "\uA1A0", "\uA1A1", "\uA1A2", "\uA1A3", "\uA1A4", "\uA1A5", "\uA1A6", "\uA1A7", "\uA1A8", "\uA1A9", "\uA1AA", "\uA1AB", "\uA1AC", "\uA1AD", "\uA1AE", "\uA1AF"], false, false), + peg$c257 = peg$otherExpectation("Unicode letter number"), + peg$c258 = /^[\u16EE\u16EF\u16F0\u2160\u2161\u2162\u2163\u2164\u2165\u2166\u2167\u2168\u2169\u216A\u216B\u216C\u216D\u216E\u216F\u2170\u2171\u2172\u2173\u2174\u2175\u2176\u2177\u2178\u2179\u217A\u217B\u217C\u217D\u217E\u217F\u2180\u2181\u2182\u2185\u2186\u2187\u2188\u3007\u3021\u3022\u3023\u3024\u3025\u3026\u3027\u3028\u3029\u3038\u3039\u303A]/, + peg$c259 = peg$classExpectation(["\u16EE", "\u16EF", "\u16F0", "\u2160", "\u2161", "\u2162", "\u2163", "\u2164", "\u2165", "\u2166", "\u2167", "\u2168", "\u2169", "\u216A", "\u216B", "\u216C", "\u216D", "\u216E", "\u216F", "\u2170", "\u2171", "\u2172", "\u2173", "\u2174", "\u2175", "\u2176", "\u2177", "\u2178", "\u2179", "\u217A", "\u217B", "\u217C", "\u217D", "\u217E", "\u217F", "\u2180", "\u2181", "\u2182", "\u2185", "\u2186", "\u2187", "\u2188", "\u3007", "\u3021", "\u3022", "\u3023", "\u3024", "\u3025", "\u3026", "\u3027", "\u3028", "\u3029", "\u3038", "\u3039", "\u303A"], false, false), + peg$c260 = peg$otherExpectation("Unicode separator, space"), + peg$c261 = /^[ \xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000]/, + peg$c262 = peg$classExpectation([" ", "\xA0", "\u1680", "\u180E", "\u2000", "\u2001", "\u2002", "\u2003", "\u2004", "\u2005", "\u2006", "\u2007", "\u2008", "\u2009", "\u200A", "\u202F", "\u205F", "\u3000"], false, false), + peg$c263 = function(c) { + return c; + }, + peg$c264 = function(seq) { + return seq; + }, + peg$c265 = "\n", + peg$c266 = peg$literalExpectation("\n", false), + peg$c267 = "\r", + peg$c268 = peg$literalExpectation("\r", false), + peg$c269 = "\u2028", + peg$c270 = peg$literalExpectation("\u2028", false), + peg$c271 = "\u2029", + peg$c272 = peg$literalExpectation("\u2029", false), + peg$c273 = "\r\n", + peg$c274 = peg$literalExpectation("\r\n", false), + peg$c275 = function() { + return '0'; + }, + peg$c276 = /^['"\\bfnrtv]/, + peg$c277 = peg$classExpectation(["'", "\"", "\\", "b", "f", "n", "r", "t", "v"], false, false), + peg$c278 = "x", + peg$c279 = peg$literalExpectation("x", false), + peg$c280 = peg$anyExpectation(), + peg$c281 = peg$otherExpectation("whitespace"), + peg$c282 = peg$otherExpectation("empty"), + peg$c283 = "", + peg$c284 = /^[\t\x0B\f \xA0\uFEFF]/, + peg$c285 = peg$classExpectation(["\t", "\x0B", "\f", " ", "\xA0", "\uFEFF"], false, false), + + peg$currPos = 0, + peg$savedPos = 0, + peg$posDetailsCache = [{ line: 1, column: 1 }], + peg$maxFailPos = 0, + peg$maxFailExpected = [], + peg$silentFails = 0, + + peg$result; + + if ("startRule" in options) { + if (!(options.startRule in peg$startRuleFunctions)) { + throw new Error("Can't start parsing from rule \"" + options.startRule + "\"."); + } + + peg$startRuleFunction = peg$startRuleFunctions[options.startRule]; + } + + function text() { + return input.substring(peg$savedPos, peg$currPos); + } + + function location() { + return peg$computeLocation(peg$savedPos, peg$currPos); + } + + function expected(description, location) { + location = location !== void 0 ? location : peg$computeLocation(peg$savedPos, peg$currPos) + + throw peg$buildStructuredError( + [peg$otherExpectation(description)], + input.substring(peg$savedPos, peg$currPos), + location + ); + } + + function error(message, location) { + location = location !== void 0 ? location : peg$computeLocation(peg$savedPos, peg$currPos) + + throw peg$buildSimpleError(message, location); + } + + function peg$literalExpectation(text, ignoreCase) { + return { type: "literal", text: text, ignoreCase: ignoreCase }; + } + + function peg$classExpectation(parts, inverted, ignoreCase) { + return { type: "class", parts: parts, inverted: inverted, ignoreCase: ignoreCase }; + } + + function peg$anyExpectation() { + return { type: "any" }; + } + + function peg$endExpectation() { + return { type: "end" }; + } + + function peg$otherExpectation(description) { + return { type: "other", description: description }; + } + + function peg$computePosDetails(pos) { + var details = peg$posDetailsCache[pos], p; + + if (details) { + return details; + } else { + p = pos - 1; + while (!peg$posDetailsCache[p]) { + p--; + } + + details = peg$posDetailsCache[p]; + details = { + line: details.line, + column: details.column + }; + + while (p < pos) { + if (input.charCodeAt(p) === 10) { + details.line++; + details.column = 1; + } else { + details.column++; + } + + p++; + } + + peg$posDetailsCache[pos] = details; + return details; + } + } + + function peg$computeLocation(startPos, endPos) { + var startPosDetails = peg$computePosDetails(startPos), + endPosDetails = peg$computePosDetails(endPos); + + return { + start: { + offset: startPos, + line: startPosDetails.line, + column: startPosDetails.column + }, + end: { + offset: endPos, + line: endPosDetails.line, + column: endPosDetails.column + } + }; + } + + function peg$fail(expected) { + if (peg$currPos < peg$maxFailPos) { return; } + + if (peg$currPos > peg$maxFailPos) { + peg$maxFailPos = peg$currPos; + peg$maxFailExpected = []; + } + + peg$maxFailExpected.push(expected); + } + + function peg$buildSimpleError(message, location) { + return new peg$SyntaxError(message, null, null, location); + } + + function peg$buildStructuredError(expected, found, location) { + return new peg$SyntaxError( + peg$SyntaxError.buildMessage(expected, found), + expected, + found, + location + ); + } + + function peg$parseTypeExpression() { + var s0, s1, s2, s3, s4; + + s0 = peg$parseTypeUnionLegacySyntax(); + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseRepeatable(); + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = peg$parseUnknownLiteral(); + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + peg$silentFails++; + s4 = peg$parseBasicTypeExpression(); + peg$silentFails--; + if (s4 === peg$FAILED) { + s3 = void 0; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c0(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseRepeatable(); + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 63) { + s2 = peg$c1; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c2); } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 33) { + s2 = peg$c3; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c4); } + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseBasicTypeExpressionNonRepeatable(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c5(s1, s2, s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseBasicTypeExpression(); + if (s1 !== peg$FAILED) { + s2 = peg$parseOptional(); + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 63) { + s3 = peg$c1; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c2); } + } + if (s3 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 33) { + s3 = peg$c3; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c4); } + } + } + if (s3 !== peg$FAILED) { + s4 = peg$parseOptional(); + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c6(s1, s2, s3, s4); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseBasicTypeExpression(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 63) { + s2 = peg$c1; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c2); } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 33) { + s2 = peg$c3; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c4); } + } + } + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c7(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + } + } + } + + return s0; + } + + function peg$parseBasicTypeExpression() { + var s0; + + s0 = peg$parseTypeUnion(); + if (s0 === peg$FAILED) { + s0 = peg$parseRestrictedTypeExpression(); + } + + return s0; + } + + function peg$parseRestrictedTypeExpression() { + var s0; + + s0 = peg$parseFunctionType(); + if (s0 === peg$FAILED) { + s0 = peg$parseRecordType(); + if (s0 === peg$FAILED) { + s0 = peg$parseLiteralType(); + if (s0 === peg$FAILED) { + s0 = peg$parseNameExpressionType(); + } + } + } + + return s0; + } + + function peg$parseBasicTypeExpressionNonRepeatable() { + var s0; + + s0 = peg$parseTypeUnionNonRepeatable(); + if (s0 === peg$FAILED) { + s0 = peg$parseRestrictedTypeExpressionNonRepeatable(); + } + + return s0; + } + + function peg$parseRestrictedTypeExpressionNonRepeatable() { + var s0; + + s0 = peg$parseFunctionTypeNonRepeatable(); + if (s0 === peg$FAILED) { + s0 = peg$parseRecordTypeNonRepeatable(); + if (s0 === peg$FAILED) { + s0 = peg$parseLiteralTypeNonRepeatable(); + if (s0 === peg$FAILED) { + s0 = peg$parseNameExpressionTypeNonRepeatable(); + } + } + } + + return s0; + } + + function peg$parseModifiedRestrictedTypeExpression() { + var s0; + + s0 = peg$parseModifiedRestrictedTypeExpressionRepeatable(); + if (s0 === peg$FAILED) { + s0 = peg$parseModifiedRestrictedTypeExpressionNonRepeatable(); + } + + return s0; + } + + function peg$parseModifiedRestrictedTypeExpressionNonRepeatable() { + var s0, s1, s2; + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 63) { + s1 = peg$c1; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c2); } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 33) { + s1 = peg$c3; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c4); } + } + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = peg$parseRestrictedTypeExpressionNonRepeatable(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c8(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseRestrictedTypeExpressionNonRepeatable(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 63) { + s2 = peg$c1; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c2); } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 33) { + s2 = peg$c3; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c4); } + } + } + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c9(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + + return s0; + } + + function peg$parseModifiedRestrictedTypeExpressionRepeatable() { + var s0, s1, s2; + + s0 = peg$currPos; + s1 = peg$parseRepeatable(); + if (s1 !== peg$FAILED) { + s2 = peg$parseModifiedRestrictedTypeExpressionNonRepeatable(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c10(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseLiteralType() { + var s0; + + s0 = peg$parseLiteralTypeRepeatable(); + if (s0 === peg$FAILED) { + s0 = peg$parseLiteralTypeNonRepeatable(); + } + + return s0; + } + + function peg$parseLiteralTypeNonRepeatable() { + var s0, s1, s2; + + s0 = peg$currPos; + s1 = peg$parseLiteral(); + if (s1 !== peg$FAILED) { + s2 = peg$parseOptional(); + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c11(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseLiteralTypeRepeatable() { + var s0, s1, s2; + + s0 = peg$currPos; + s1 = peg$parseRepeatable(); + if (s1 !== peg$FAILED) { + s2 = peg$parseLiteralTypeNonRepeatable(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c12(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseLiteral() { + var s0, s1; + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 42) { + s1 = peg$c13; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c14); } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c15(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$parseUnknownLiteral(); + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseNullLiteral(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c16(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseUndefinedLiteral(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c17(); + } + s0 = s1; + } + } + } + + return s0; + } + + function peg$parseRepeatable() { + var s0, s1; + + s0 = peg$currPos; + if (input.substr(peg$currPos, 3) === peg$c18) { + s1 = peg$c18; + peg$currPos += 3; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c19); } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c20(); + } + s0 = s1; + + return s0; + } + + function peg$parseOptional() { + var s0, s1; + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 61) { + s1 = peg$c21; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c22); } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c23(); + } + s0 = s1; + + return s0; + } + + function peg$parseNameExpressionType() { + var s0; + + s0 = peg$parseNameExpressionTypeRepeatable(); + if (s0 === peg$FAILED) { + s0 = peg$parseNameExpressionTypeNonRepeatable(); + } + + return s0; + } + + function peg$parseNameExpressionTypeNonRepeatable() { + var s0, s1, s2, s3; + + s0 = peg$currPos; + s1 = peg$parseNameExpression(); + if (s1 === peg$FAILED) { + s1 = peg$parseReservedWordNameExpressionTypeNonRepeatable(); + } + if (s1 !== peg$FAILED) { + s2 = []; + if (input.substr(peg$currPos, 2) === peg$c24) { + s3 = peg$c24; + peg$currPos += 2; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c25); } + } + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + if (input.substr(peg$currPos, 2) === peg$c24) { + s3 = peg$c24; + peg$currPos += 2; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c25); } + } + } + } else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c26(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseNameExpression(); + if (s1 !== peg$FAILED) { + s2 = peg$parseTypeApplication(); + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + s3 = peg$parseOptional(); + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c27(s1, s2, s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$parseReservedWordNameExpressionTypeNonRepeatable(); + } + } + + return s0; + } + + function peg$parseNameExpressionTypeRepeatable() { + var s0, s1, s2; + + s0 = peg$currPos; + s1 = peg$parseRepeatable(); + if (s1 !== peg$FAILED) { + s2 = peg$parseNameExpressionTypeNonRepeatable(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c28(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseReservedWordNameExpressionType() { + var s0; + + s0 = peg$parseReservedWordNameExpressionTypeRepeatable(); + if (s0 === peg$FAILED) { + s0 = peg$parseReservedWordNameExpressionTypeNonRepeatable(); + } + + return s0; + } + + function peg$parseReservedWordNameExpressionTypeNonRepeatable() { + var s0, s1, s2; + + s0 = peg$currPos; + s1 = peg$parseReservedWordNameExpression(); + if (s1 !== peg$FAILED) { + s2 = peg$parseOptional(); + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c29(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseReservedWordNameExpressionTypeRepeatable() { + var s0, s1, s2; + + s0 = peg$currPos; + s1 = peg$parseRepeatable(); + if (s1 !== peg$FAILED) { + s2 = peg$parseReservedWordNameExpressionTypeNonRepeatable(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c28(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseTypeApplication() { + var s0, s1, s2, s3, s4, s5, s6; + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s1 = peg$c30; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c31); } + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 60) { + s2 = peg$c32; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c33); } + } + if (s2 !== peg$FAILED) { + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + s4 = peg$parseTypeExpressionList(); + if (s4 !== peg$FAILED) { + s5 = peg$parse_(); + if (s5 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 62) { + s6 = peg$c34; + peg$currPos++; + } else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c35); } + } + if (s6 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c36(s1, s4); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseTypeExpressionList() { + var s0, s1, s2, s3, s4, s5, s6, s7; + + s0 = peg$currPos; + s1 = peg$parseTypeExpression(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s5 = peg$c37; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c38); } + } + if (s5 !== peg$FAILED) { + s6 = peg$parse_(); + if (s6 !== peg$FAILED) { + s7 = peg$parseTypeExpression(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s5 = peg$c37; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c38); } + } + if (s5 !== peg$FAILED) { + s6 = peg$parse_(); + if (s6 !== peg$FAILED) { + s7 = peg$parseTypeExpression(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c39(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseFunctionType() { + var s0; + + s0 = peg$parseFunctionTypeRepeatable(); + if (s0 === peg$FAILED) { + s0 = peg$parseFunctionTypeNonRepeatable(); + } + + return s0; + } + + function peg$parseFunctionTypeNonRepeatable() { + var s0, s1, s2, s3, s4, s5; + + s0 = peg$currPos; + s1 = peg$parseFunctionLiteral(); + if (s1 !== peg$FAILED) { + if (input.substr(peg$currPos, 2) === peg$c24) { + s2 = peg$c24; + peg$currPos += 2; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c25); } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c40(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseFunctionLiteral(); + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + peg$silentFails++; + s3 = peg$parseNameExpression(); + peg$silentFails--; + if (s3 === peg$FAILED) { + s2 = void 0; + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + s4 = peg$parseFunctionSignatureType(); + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s5 = peg$parseOptional(); + if (s5 === peg$FAILED) { + s5 = null; + } + if (s5 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c41(s4, s5); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + + return s0; + } + + function peg$parseFunctionTypeRepeatable() { + var s0, s1, s2; + + s0 = peg$currPos; + s1 = peg$parseRepeatable(); + if (s1 !== peg$FAILED) { + s2 = peg$parseFunctionTypeNonRepeatable(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c28(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseFunctionSignatureType() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10; + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 40) { + s1 = peg$c42; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c43); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseFunctionSignature(); + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c44; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c45); } + } + if (s5 !== peg$FAILED) { + s6 = peg$currPos; + s7 = peg$parse_(); + if (s7 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s8 = peg$c46; + peg$currPos++; + } else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c47); } + } + if (s8 !== peg$FAILED) { + s9 = peg$parse_(); + if (s9 !== peg$FAILED) { + s10 = peg$parseTypeExpression(); + if (s10 !== peg$FAILED) { + s7 = [s7, s8, s9, s10]; + s6 = s7; + } else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } else { + peg$currPos = s6; + s6 = peg$FAILED; + } + if (s6 === peg$FAILED) { + s6 = null; + } + if (s6 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c48(s3, s6); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseFunctionSignature() { + var s0, s1, s2, s3, s4, s5, s6, s7; + + s0 = peg$currPos; + s1 = peg$parseFunctionSignatureNew(); + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s4 = peg$c37; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c38); } + } + if (s4 !== peg$FAILED) { + s5 = peg$parse_(); + if (s5 !== peg$FAILED) { + s6 = peg$parseFunctionSignatureThis(); + if (s6 !== peg$FAILED) { + s3 = [s3, s4, s5, s6]; + s2 = s3; + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s5 = peg$c37; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c38); } + } + if (s5 !== peg$FAILED) { + s6 = peg$parse_(); + if (s6 !== peg$FAILED) { + s7 = peg$parseParametersType(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c49(s1, s2, s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseFunctionSignatureThis(); + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s4 = peg$c37; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c38); } + } + if (s4 !== peg$FAILED) { + s5 = peg$parse_(); + if (s5 !== peg$FAILED) { + s6 = peg$parseFunctionSignatureNew(); + if (s6 !== peg$FAILED) { + s3 = [s3, s4, s5, s6]; + s2 = s3; + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s5 = peg$c37; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c38); } + } + if (s5 !== peg$FAILED) { + s6 = peg$parse_(); + if (s6 !== peg$FAILED) { + s7 = peg$parseParametersType(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c50(s1, s2, s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseParametersType(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c51(s1); + } + s0 = s1; + } + } + + return s0; + } + + function peg$parseFunctionSignatureNew() { + var s0, s1, s2, s3, s4, s5; + + s0 = peg$currPos; + if (input.substr(peg$currPos, 3) === peg$c52) { + s1 = peg$c52; + peg$currPos += 3; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c53); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s3 = peg$c46; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c47); } + } + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + s5 = peg$parseTypeExpression(); + if (s5 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c54(s5); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseFunctionSignatureThis() { + var s0, s1, s2, s3, s4, s5; + + s0 = peg$currPos; + if (input.substr(peg$currPos, 4) === peg$c55) { + s1 = peg$c55; + peg$currPos += 4; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c56); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s3 = peg$c46; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c47); } + } + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + s5 = peg$parseTypeExpression(); + if (s5 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c54(s5); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseParametersType() { + var s0, s1, s2, s3, s4, s5, s6; + + s0 = peg$currPos; + s1 = peg$parseRestParameterType(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c57(s1); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseNonRestParametersType(); + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s4 = peg$c37; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c38); } + } + if (s4 !== peg$FAILED) { + s5 = peg$parse_(); + if (s5 !== peg$FAILED) { + s6 = peg$parseRestParameterType(); + if (s6 !== peg$FAILED) { + s3 = [s3, s4, s5, s6]; + s2 = s3; + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c58(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + + return s0; + } + + function peg$parseNonRestParametersType() { + var s0, s1, s2, s3, s4, s5, s6, s7; + + s0 = peg$currPos; + s1 = peg$parseParameterType(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s5 = peg$c37; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c38); } + } + if (s5 !== peg$FAILED) { + s6 = peg$parse_(); + if (s6 !== peg$FAILED) { + s7 = peg$parseParameterType(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s5 = peg$c37; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c38); } + } + if (s5 !== peg$FAILED) { + s6 = peg$parse_(); + if (s6 !== peg$FAILED) { + s7 = peg$parseParameterType(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c59(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$parseOptionalParametersType(); + } + + return s0; + } + + function peg$parseOptionalParametersType() { + var s0, s1, s2, s3, s4, s5, s6, s7; + + s0 = peg$currPos; + s1 = peg$parseOptionalParameterType(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s5 = peg$c37; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c38); } + } + if (s5 !== peg$FAILED) { + s6 = peg$parse_(); + if (s6 !== peg$FAILED) { + s7 = peg$parseOptionalParameterType(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s5 = peg$c37; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c38); } + } + if (s5 !== peg$FAILED) { + s6 = peg$parse_(); + if (s6 !== peg$FAILED) { + s7 = peg$parseOptionalParameterType(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c60(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseParameterType() { + var s0, s1; + + s0 = peg$currPos; + s1 = peg$parseTypeExpression(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c61(s1); + } + s0 = s1; + + return s0; + } + + function peg$parseOptionalParameterType() { + var s0, s1, s2; + + s0 = peg$currPos; + s1 = peg$parseParameterType(); + if (s1 !== peg$FAILED) { + s2 = peg$parseOptional(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c62(s1); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseRestParameterType() { + var s0, s1, s2, s3, s4, s5, s6; + + s0 = peg$currPos; + s1 = peg$parseRepeatable(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 91) { + s2 = peg$c63; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c64); } + } + if (s2 !== peg$FAILED) { + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + s4 = peg$parseParameterType(); + if (s4 !== peg$FAILED) { + s5 = peg$parse_(); + if (s5 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s6 = peg$c65; + peg$currPos++; + } else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c66); } + } + if (s6 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c28(s4); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseRepeatable(); + if (s1 !== peg$FAILED) { + s2 = peg$parseParameterType(); + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c67(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseRepeatable(); + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 91) { + s3 = peg$c63; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c64); } + } + peg$silentFails--; + if (s3 === peg$FAILED) { + s2 = void 0; + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c68(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + } + + return s0; + } + + function peg$parseTypeUnion() { + var s0; + + s0 = peg$parseTypeUnionRepeatable(); + if (s0 === peg$FAILED) { + s0 = peg$parseTypeUnionNonRepeatable(); + } + + return s0; + } + + function peg$parseTypeUnionNonRepeatable() { + var s0, s1, s2, s3, s4, s5, s6, s7; + + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 40) { + s2 = peg$c42; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c43); } + } + if (s2 !== peg$FAILED) { + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + s4 = peg$parseTypeUnionList(); + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s5 = peg$parse_(); + if (s5 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s6 = peg$c44; + peg$currPos++; + } else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c45); } + } + if (s6 !== peg$FAILED) { + s7 = peg$parseOptional(); + if (s7 === peg$FAILED) { + s7 = null; + } + if (s7 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c69(s4, s7); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseTypeUnionRepeatable() { + var s0, s1, s2; + + s0 = peg$currPos; + s1 = peg$parseRepeatable(); + if (s1 !== peg$FAILED) { + s2 = peg$parseTypeUnionNonRepeatable(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c70(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseTypeUnionList() { + var s0, s1, s2, s3, s4, s5; + + s0 = peg$currPos; + s1 = peg$parseTypeExpression(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseTypeUnionSeparator(); + if (s4 !== peg$FAILED) { + s5 = peg$parseTypeExpression(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseTypeUnionSeparator(); + if (s4 !== peg$FAILED) { + s5 = peg$parseTypeExpression(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c71(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseRestrictedTypeUnionList() { + var s0, s1, s2, s3, s4, s5; + + s0 = peg$currPos; + s1 = peg$parseModifiedRestrictedTypeExpression(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseTypeUnionSeparator(); + if (s4 !== peg$FAILED) { + s5 = peg$parseModifiedRestrictedTypeExpression(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseTypeUnionSeparator(); + if (s4 !== peg$FAILED) { + s5 = peg$parseModifiedRestrictedTypeExpression(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + } else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c71(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseTypeUnionLegacySyntax() { + var s0, s1, s2, s3, s4, s5, s6, s7; + + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 40) { + s3 = peg$c42; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c43); } + } + peg$silentFails--; + if (s3 === peg$FAILED) { + s2 = void 0; + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + s4 = peg$parseRestrictedTypeUnionList(); + if (s4 !== peg$FAILED) { + s5 = peg$parse_(); + if (s5 !== peg$FAILED) { + s6 = peg$currPos; + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 41) { + s7 = peg$c44; + peg$currPos++; + } else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c45); } + } + peg$silentFails--; + if (s7 === peg$FAILED) { + s6 = void 0; + } else { + peg$currPos = s6; + s6 = peg$FAILED; + } + if (s6 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c72(s4); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseTypeUnionSeparator() { + var s0, s1, s2, s3; + + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 124) { + s2 = peg$c73; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c74); } + } + if (s2 !== peg$FAILED) { + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c75(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseRecordType() { + var s0; + + s0 = peg$parseRecordTypeRepeatable(); + if (s0 === peg$FAILED) { + s0 = peg$parseRecordTypeNonRepeatable(); + } + + return s0; + } + + function peg$parseRecordTypeNonRepeatable() { + var s0, s1, s2, s3, s4, s5, s6, s7; + + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 123) { + s2 = peg$c76; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c77); } + } + if (s2 !== peg$FAILED) { + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + s4 = peg$parseFieldTypeList(); + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s5 = peg$parse_(); + if (s5 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 125) { + s6 = peg$c78; + peg$currPos++; + } else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c79); } + } + if (s6 !== peg$FAILED) { + s7 = peg$parseOptional(); + if (s7 === peg$FAILED) { + s7 = null; + } + if (s7 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c80(s4, s7); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseRecordTypeRepeatable() { + var s0, s1, s2; + + s0 = peg$currPos; + s1 = peg$parseRepeatable(); + if (s1 !== peg$FAILED) { + s2 = peg$parseRecordTypeNonRepeatable(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c28(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseFieldTypeList() { + var s0, s1, s2, s3, s4, s5, s6, s7; + + s0 = peg$currPos; + s1 = peg$parseFieldType(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s5 = peg$c37; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c38); } + } + if (s5 !== peg$FAILED) { + s6 = peg$parse_(); + if (s6 !== peg$FAILED) { + s7 = peg$parseFieldType(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s5 = peg$c37; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c38); } + } + if (s5 !== peg$FAILED) { + s6 = peg$parse_(); + if (s6 !== peg$FAILED) { + s7 = peg$parseFieldType(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c81(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseFieldType() { + var s0, s1, s2, s3, s4, s5, s6; + + s0 = peg$currPos; + s1 = peg$parseFieldName(); + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c46; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c47); } + } + if (s4 !== peg$FAILED) { + s5 = peg$parse_(); + if (s5 !== peg$FAILED) { + s6 = peg$parseTypeExpression(); + if (s6 !== peg$FAILED) { + s3 = [s3, s4, s5, s6]; + s2 = s3; + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c82(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseFieldName() { + var s0, s1; + + s0 = peg$parseNameExpressionTypeNonRepeatable(); + if (s0 === peg$FAILED) { + s0 = peg$parseReservedWordNameExpressionTypeNonRepeatable(); + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseTypeExpression(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c83(s1); + } + s0 = s1; + } + } + + return s0; + } + + function peg$parseNameExpression() { + var s0, s1, s2; + + s0 = peg$currPos; + s1 = peg$parseDoubleStringLiteral(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c84(s1); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseSingleStringLiteral(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c85(s1); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseIdentifier(); + if (s1 !== peg$FAILED) { + s2 = peg$parsePropertyChain(); + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c86(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + } + + return s0; + } + + function peg$parseReservedWordNameExpression() { + var s0, s1; + + s0 = peg$currPos; + s1 = peg$parseReservedWord(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c87(s1); + } + s0 = s1; + + return s0; + } + + function peg$parsePropertyIdentifier() { + var s0, s1, s2, s3; + + s0 = peg$parseIdentifier(); + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseDoubleStringLiteral(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c88(s1); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseSingleStringLiteral(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c89(s1); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$parseNumericLiteral(); + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseKeyword(); + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 40) { + s3 = peg$c42; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c43); } + } + peg$silentFails--; + if (s3 === peg$FAILED) { + s2 = void 0; + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$parseFutureReservedWord(); + } + } + } + } + } + + return s0; + } + + function peg$parsePropertyChain() { + var s0, s1, s2; + + s0 = peg$currPos; + s1 = []; + s2 = peg$parsePropertyChainItem(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parsePropertyChainItem(); + } + } else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s0 = input.substring(s0, peg$currPos); + } else { + s0 = s1; + } + + return s0; + } + + function peg$parsePropertyChainItem() { + var s0, s1, s2, s3; + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s1 = peg$c30; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c31); } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 35) { + s1 = peg$c90; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c91); } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 126) { + s1 = peg$c92; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c93); } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s1 = peg$c46; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c47); } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 47) { + s1 = peg$c94; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c95); } + } + } + } + } + } + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 60) { + s3 = peg$c32; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c33); } + } + peg$silentFails--; + if (s3 === peg$FAILED) { + s2 = void 0; + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + s3 = peg$parsePropertyIdentifier(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c96(s1, s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseNamespaceExpression() { + var s0; + + s0 = peg$parseNameExpression(); + if (s0 === peg$FAILED) { + s0 = peg$parseStringLiteral(); + } + + return s0; + } + + function peg$parseIdentifier() { + var s0, s1, s2; + + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + s2 = peg$parseReservedWord(); + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = void 0; + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s2 = peg$parseIdentifierName(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c97(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseIdentifierName() { + var s0, s1, s2, s3, s4; + + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parseIdentifierStart(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseIdentifierPart(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseIdentifierPart(); + } + if (s3 !== peg$FAILED) { + s4 = peg$parseIdentifierEnd(); + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s2 = [s2, s3, s4]; + s1 = s2; + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s0 = input.substring(s0, peg$currPos); + } else { + s0 = s1; + } + + return s0; + } + + function peg$parseIdentifierStart() { + var s0; + + s0 = peg$parseUnicodeLetter(); + if (s0 === peg$FAILED) { + s0 = peg$parseNumericLiteral(); + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 36) { + s0 = peg$c98; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c99); } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 95) { + s0 = peg$c100; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c101); } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 64) { + s0 = peg$c102; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c103); } + } + if (s0 === peg$FAILED) { + s0 = peg$parseUnicodeEscapeSequenceLiteral(); + } + } + } + } + } + + return s0; + } + + function peg$parseIdentifierPart() { + var s0; + + s0 = peg$parseIdentifierStart(); + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s0 = peg$c104; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c105); } + } + if (s0 === peg$FAILED) { + s0 = peg$parseUnicodeMc(); + if (s0 === peg$FAILED) { + s0 = peg$parseUnicodeNd(); + if (s0 === peg$FAILED) { + s0 = peg$parseUnicodePc(); + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 8204) { + s0 = peg$c106; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c107); } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 8205) { + s0 = peg$c108; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c109); } + } + } + } + } + } + } + } + + return s0; + } + + function peg$parseIdentifierEnd() { + var s0, s1, s2, s3, s4, s5; + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 40) { + s1 = peg$c42; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c43); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseIdentifierPart(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseIdentifierPart(); + } + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c44; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c45); } + } + if (s5 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c110(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 40) { + s1 = peg$c42; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c43); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseParametersType(); + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c44; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c45); } + } + if (s5 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c111(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$parseIdentifierPart(); + } + } + + return s0; + } + + function peg$parseReservedWord() { + var s0; + + s0 = peg$parseKeyword(); + if (s0 === peg$FAILED) { + s0 = peg$parseFutureReservedWord(); + if (s0 === peg$FAILED) { + s0 = peg$parseNullLiteral(); + if (s0 === peg$FAILED) { + s0 = peg$parseBooleanLiteral(); + } + } + } + + return s0; + } + + function peg$parseKeyword() { + var s0, s1, s2, s3; + + s0 = peg$currPos; + s1 = peg$currPos; + if (input.substr(peg$currPos, 5) === peg$c112) { + s2 = peg$c112; + peg$currPos += 5; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c113); } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 4) === peg$c114) { + s2 = peg$c114; + peg$currPos += 4; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c115); } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 5) === peg$c116) { + s2 = peg$c116; + peg$currPos += 5; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c117); } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 8) === peg$c118) { + s2 = peg$c118; + peg$currPos += 8; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c119); } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 8) === peg$c120) { + s2 = peg$c120; + peg$currPos += 8; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c121); } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 7) === peg$c122) { + s2 = peg$c122; + peg$currPos += 7; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c123); } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 6) === peg$c124) { + s2 = peg$c124; + peg$currPos += 6; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c125); } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 2) === peg$c126) { + s2 = peg$c126; + peg$currPos += 2; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c127); } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 4) === peg$c128) { + s2 = peg$c128; + peg$currPos += 4; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c129); } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 7) === peg$c130) { + s2 = peg$c130; + peg$currPos += 7; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c131); } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 3) === peg$c132) { + s2 = peg$c132; + peg$currPos += 3; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c133); } + } + if (s2 === peg$FAILED) { + s2 = peg$parseFunctionLiteralLc(); + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 2) === peg$c134) { + s2 = peg$c134; + peg$currPos += 2; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c135); } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 2) === peg$c136) { + s2 = peg$c136; + peg$currPos += 2; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c137); } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 10) === peg$c138) { + s2 = peg$c138; + peg$currPos += 10; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c139); } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 3) === peg$c52) { + s2 = peg$c52; + peg$currPos += 3; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c53); } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 6) === peg$c140) { + s2 = peg$c140; + peg$currPos += 6; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c141); } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 6) === peg$c142) { + s2 = peg$c142; + peg$currPos += 6; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c143); } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 4) === peg$c55) { + s2 = peg$c55; + peg$currPos += 4; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c56); } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 5) === peg$c144) { + s2 = peg$c144; + peg$currPos += 5; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c145); } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 3) === peg$c146) { + s2 = peg$c146; + peg$currPos += 3; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c147); } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 6) === peg$c148) { + s2 = peg$c148; + peg$currPos += 6; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c149); } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 3) === peg$c150) { + s2 = peg$c150; + peg$currPos += 3; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c151); } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 4) === peg$c152) { + s2 = peg$c152; + peg$currPos += 4; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c153); } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 5) === peg$c154) { + s2 = peg$c154; + peg$currPos += 5; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c155); } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 4) === peg$c156) { + s2 = peg$c156; + peg$currPos += 4; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c157); } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + if (s2 !== peg$FAILED) { + s1 = input.substring(s1, peg$currPos); + } else { + s1 = s2; + } + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + peg$silentFails++; + s3 = peg$parseIdentifierPart(); + peg$silentFails--; + if (s3 === peg$FAILED) { + s2 = void 0; + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c158(s1); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseFutureReservedWord() { + var s0, s1, s2, s3; + + s0 = peg$currPos; + s1 = peg$currPos; + if (input.substr(peg$currPos, 5) === peg$c159) { + s2 = peg$c159; + peg$currPos += 5; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c160); } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 5) === peg$c161) { + s2 = peg$c161; + peg$currPos += 5; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c162); } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 4) === peg$c163) { + s2 = peg$c163; + peg$currPos += 4; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c164); } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 6) === peg$c165) { + s2 = peg$c165; + peg$currPos += 6; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c166); } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 7) === peg$c167) { + s2 = peg$c167; + peg$currPos += 7; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c168); } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 6) === peg$c169) { + s2 = peg$c169; + peg$currPos += 6; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c170); } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 5) === peg$c171) { + s2 = peg$c171; + peg$currPos += 5; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c172); } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 10) === peg$c173) { + s2 = peg$c173; + peg$currPos += 10; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c174); } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 9) === peg$c175) { + s2 = peg$c175; + peg$currPos += 9; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c176); } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 3) === peg$c177) { + s2 = peg$c177; + peg$currPos += 3; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c178); } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 7) === peg$c179) { + s2 = peg$c179; + peg$currPos += 7; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c180); } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 7) === peg$c181) { + s2 = peg$c181; + peg$currPos += 7; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c182); } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 9) === peg$c183) { + s2 = peg$c183; + peg$currPos += 9; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c184); } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 6) === peg$c185) { + s2 = peg$c185; + peg$currPos += 6; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c186); } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 6) === peg$c187) { + s2 = peg$c187; + peg$currPos += 6; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c188); } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 5) === peg$c189) { + s2 = peg$c189; + peg$currPos += 5; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c190); } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + if (s2 !== peg$FAILED) { + s1 = input.substring(s1, peg$currPos); + } else { + s1 = s2; + } + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + peg$silentFails++; + s3 = peg$parseIdentifierPart(); + peg$silentFails--; + if (s3 === peg$FAILED) { + s2 = void 0; + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c191(s1); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseStringLiteral() { + var s0; + + s0 = peg$parseDoubleStringLiteral(); + if (s0 === peg$FAILED) { + s0 = peg$parseSingleStringLiteral(); + } + + return s0; + } + + function peg$parseDoubleStringLiteral() { + var s0, s1, s2, s3; + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 34) { + s1 = peg$c192; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c193); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseDoubleStringCharacter(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseDoubleStringCharacter(); + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 34) { + s3 = peg$c192; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c193); } + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c194(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseSingleStringLiteral() { + var s0, s1, s2, s3; + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 39) { + s1 = peg$c195; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c196); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseSingleStringCharacter(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseSingleStringCharacter(); + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 39) { + s3 = peg$c195; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c196); } + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c194(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseNumericLiteral() { + var s0; + + s0 = peg$parseDecimalLiteral(); + if (s0 === peg$FAILED) { + s0 = peg$parseHexIntegerLiteral(); + } + + return s0; + } + + function peg$parseDecimalLiteral() { + var s0, s1, s2, s3, s4; + + s0 = peg$currPos; + s1 = peg$parseDecimalIntegerLiteral(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s2 = peg$c30; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c31); } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseDecimalDigits(); + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + s4 = peg$parseExponentPart(); + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c197(s1, s3, s4); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s1 = peg$c30; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c31); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseDecimalDigits(); + if (s2 !== peg$FAILED) { + s3 = peg$parseExponentPart(); + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c198(s2, s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseDecimalIntegerLiteral(); + if (s1 !== peg$FAILED) { + s2 = peg$parseExponentPart(); + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c199(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + } + + return s0; + } + + function peg$parseDecimalIntegerLiteral() { + var s0, s1, s2, s3; + + if (input.charCodeAt(peg$currPos) === 48) { + s0 = peg$c200; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c201); } + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parseNonZeroDigit(); + if (s2 !== peg$FAILED) { + s3 = peg$parseDecimalDigits(); + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + s2 = [s2, s3]; + s1 = s2; + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s0 = input.substring(s0, peg$currPos); + } else { + s0 = s1; + } + } + + return s0; + } + + function peg$parseDecimalDigits() { + var s0, s1, s2; + + s0 = peg$currPos; + s1 = []; + s2 = peg$parseDecimalDigit(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseDecimalDigit(); + } + } else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s0 = input.substring(s0, peg$currPos); + } else { + s0 = s1; + } + + return s0; + } + + function peg$parseExponentPart() { + var s0, s1, s2, s3; + + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parseExponentIndicator(); + if (s2 !== peg$FAILED) { + s3 = peg$parseSignedInteger(); + if (s3 !== peg$FAILED) { + s2 = [s2, s3]; + s1 = s2; + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s0 = input.substring(s0, peg$currPos); + } else { + s0 = s1; + } + + return s0; + } + + function peg$parseExponentIndicator() { + var s0; + + if (peg$c202.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c203); } + } + + return s0; + } + + function peg$parseSignedInteger() { + var s0, s1, s2, s3; + + s0 = peg$currPos; + s1 = peg$currPos; + if (peg$c204.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c205); } + } + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + s3 = peg$parseDecimalDigits(); + if (s3 !== peg$FAILED) { + s2 = [s2, s3]; + s1 = s2; + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s0 = input.substring(s0, peg$currPos); + } else { + s0 = s1; + } + + return s0; + } + + function peg$parseHexIntegerLiteral() { + var s0, s1, s2, s3, s4, s5; + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 48) { + s1 = peg$c200; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c201); } + } + if (s1 !== peg$FAILED) { + if (peg$c206.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c207); } + } + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + s4 = []; + s5 = peg$parseHexDigit(); + if (s5 !== peg$FAILED) { + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$parseHexDigit(); + } + } else { + s4 = peg$FAILED; + } + if (s4 !== peg$FAILED) { + s3 = input.substring(s3, peg$currPos); + } else { + s3 = s4; + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c208(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseNullLiteral() { + var s0; + + if (input.substr(peg$currPos, 4) === peg$c209) { + s0 = peg$c209; + peg$currPos += 4; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c210); } + } + + return s0; + } + + function peg$parseUndefinedLiteral() { + var s0; + + if (input.substr(peg$currPos, 9) === peg$c211) { + s0 = peg$c211; + peg$currPos += 9; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c212); } + } + + return s0; + } + + function peg$parseUnknownLiteral() { + var s0, s1; + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 63) { + s1 = peg$c1; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c2); } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c213(); + } + s0 = s1; + + return s0; + } + + function peg$parseBooleanLiteral() { + var s0; + + if (input.substr(peg$currPos, 4) === peg$c214) { + s0 = peg$c214; + peg$currPos += 4; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c215); } + } + if (s0 === peg$FAILED) { + if (input.substr(peg$currPos, 5) === peg$c216) { + s0 = peg$c216; + peg$currPos += 5; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c217); } + } + } + + return s0; + } + + function peg$parseFunctionLiteral() { + var s0; + + s0 = peg$parseFunctionLiteralUc(); + if (s0 === peg$FAILED) { + s0 = peg$parseFunctionLiteralLc(); + } + + return s0; + } + + function peg$parseFunctionLiteralUc() { + var s0; + + if (input.substr(peg$currPos, 8) === peg$c218) { + s0 = peg$c218; + peg$currPos += 8; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c219); } + } + + return s0; + } + + function peg$parseFunctionLiteralLc() { + var s0; + + if (input.substr(peg$currPos, 8) === peg$c220) { + s0 = peg$c220; + peg$currPos += 8; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c221); } + } + + return s0; + } + + function peg$parseUnicodeLetter() { + var s0; + + s0 = peg$parseUnicodeLu(); + if (s0 === peg$FAILED) { + s0 = peg$parseUnicodeLl(); + if (s0 === peg$FAILED) { + s0 = peg$parseUnicodeLt(); + if (s0 === peg$FAILED) { + s0 = peg$parseUnicodeLm(); + if (s0 === peg$FAILED) { + s0 = peg$parseUnicodeLo(); + if (s0 === peg$FAILED) { + s0 = peg$parseUnicodeLn(); + } + } + } + } + } + + return s0; + } + + function peg$parseUnicodeEscapeSequenceLiteral() { + var s0, s1, s2, s3; + + s0 = peg$currPos; + s1 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s2 = peg$c222; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c223); } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseUnicodeEscapeSequence(); + if (s3 !== peg$FAILED) { + s2 = [s2, s3]; + s1 = s2; + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s0 = input.substring(s0, peg$currPos); + } else { + s0 = s1; + } + + return s0; + } + + function peg$parseUnicodeEscapeSequence() { + var s0, s1, s2, s3, s4, s5, s6, s7; + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 117) { + s1 = peg$c224; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c225); } + } + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + s3 = peg$currPos; + s4 = peg$parseHexDigit(); + if (s4 !== peg$FAILED) { + s5 = peg$parseHexDigit(); + if (s5 !== peg$FAILED) { + s6 = peg$parseHexDigit(); + if (s6 !== peg$FAILED) { + s7 = peg$parseHexDigit(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + if (s3 !== peg$FAILED) { + s2 = input.substring(s2, peg$currPos); + } else { + s2 = s3; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c226(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseDecimalDigit() { + var s0; + + if (peg$c227.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c228); } + } + + return s0; + } + + function peg$parseNonZeroDigit() { + var s0; + + if (peg$c229.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c230); } + } + + return s0; + } + + function peg$parseHexDigit() { + var s0; + + if (peg$c231.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c232); } + } + + return s0; + } + + function peg$parseUnicodeMc() { + var s0, s1; + + peg$silentFails++; + if (peg$c234.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c235); } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c233); } + } + + return s0; + } + + function peg$parseUnicodeNd() { + var s0, s1; + + peg$silentFails++; + if (peg$c237.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c238); } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c236); } + } + + return s0; + } + + function peg$parseUnicodePc() { + var s0, s1; + + peg$silentFails++; + if (peg$c240.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c241); } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c239); } + } + + return s0; + } + + function peg$parseUnicodeLu() { + var s0, s1; + + peg$silentFails++; + if (peg$c243.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c244); } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c242); } + } + + return s0; + } + + function peg$parseUnicodeLl() { + var s0, s1; + + peg$silentFails++; + if (peg$c246.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c247); } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c245); } + } + + return s0; + } + + function peg$parseUnicodeLt() { + var s0, s1; + + peg$silentFails++; + if (peg$c249.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c250); } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c248); } + } + + return s0; + } + + function peg$parseUnicodeLm() { + var s0, s1; + + peg$silentFails++; + if (peg$c252.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c253); } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c251); } + } + + return s0; + } + + function peg$parseUnicodeLo() { + var s0, s1; + + peg$silentFails++; + if (peg$c255.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c256); } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c254); } + } + + return s0; + } + + function peg$parseUnicodeLn() { + var s0, s1; + + peg$silentFails++; + if (peg$c258.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c259); } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c257); } + } + + return s0; + } + + function peg$parseUnicodeZs() { + var s0, s1; + + peg$silentFails++; + if (peg$c261.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c262); } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c260); } + } + + return s0; + } + + function peg$parseDoubleStringCharacter() { + var s0, s1, s2; + + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 34) { + s2 = peg$c192; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c193); } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 92) { + s2 = peg$c222; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c223); } + } + if (s2 === peg$FAILED) { + s2 = peg$parseLineTerminator(); + } + } + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = void 0; + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s2 = peg$parseSourceCharacter(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c263(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s1 = peg$c222; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c223); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEscapeSequence(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c264(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$parseLineContinuation(); + } + } + + return s0; + } + + function peg$parseSingleStringCharacter() { + var s0, s1, s2; + + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 39) { + s2 = peg$c195; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c196); } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 92) { + s2 = peg$c222; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c223); } + } + if (s2 === peg$FAILED) { + s2 = peg$parseLineTerminator(); + } + } + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = void 0; + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s2 = peg$parseSourceCharacter(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c263(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s1 = peg$c222; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c223); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEscapeSequence(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c264(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$parseLineContinuation(); + } + } + + return s0; + } + + function peg$parseLineTerminatorSequence() { + var s0, s1, s2, s3; + + if (input.charCodeAt(peg$currPos) === 10) { + s0 = peg$c265; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c266); } + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 13) { + s1 = peg$c267; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c268); } + } + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 10) { + s3 = peg$c265; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c266); } + } + peg$silentFails--; + if (s3 === peg$FAILED) { + s2 = void 0; + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 8232) { + s0 = peg$c269; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c270); } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 8233) { + s0 = peg$c271; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c272); } + } + if (s0 === peg$FAILED) { + if (input.substr(peg$currPos, 2) === peg$c273) { + s0 = peg$c273; + peg$currPos += 2; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c274); } + } + } + } + } + } + + return s0; + } + + function peg$parseLineTerminator() { + var s0; + + if (input.charCodeAt(peg$currPos) === 10) { + s0 = peg$c265; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c266); } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 13) { + s0 = peg$c267; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c268); } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 8232) { + s0 = peg$c269; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c270); } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 8233) { + s0 = peg$c271; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c272); } + } + } + } + } + + return s0; + } + + function peg$parseEscapeSequence() { + var s0, s1, s2, s3; + + s0 = peg$parseCharacterEscapeSequence(); + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 48) { + s1 = peg$c200; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c201); } + } + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + peg$silentFails++; + s3 = peg$parseDecimalDigit(); + peg$silentFails--; + if (s3 === peg$FAILED) { + s2 = void 0; + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c275(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$parseHexEscapeSequence(); + if (s0 === peg$FAILED) { + s0 = peg$parseUnicodeEscapeSequence(); + } + } + } + + return s0; + } + + function peg$parseCharacterEscapeSequence() { + var s0; + + s0 = peg$parseSingleEscapeCharacter(); + if (s0 === peg$FAILED) { + s0 = peg$parseNonEscapeCharacter(); + } + + return s0; + } + + function peg$parseSingleEscapeCharacter() { + var s0; + + if (peg$c276.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c277); } + } + + return s0; + } + + function peg$parseNonEscapeCharacter() { + var s0, s1, s2; + + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + s2 = peg$parseEscapeCharacter(); + if (s2 === peg$FAILED) { + s2 = peg$parseLineTerminator(); + } + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = void 0; + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s2 = peg$parseSourceCharacter(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c263(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseEscapeCharacter() { + var s0; + + s0 = peg$parseSingleEscapeCharacter(); + if (s0 === peg$FAILED) { + s0 = peg$parseDecimalDigit(); + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 120) { + s0 = peg$c278; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c279); } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 117) { + s0 = peg$c224; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c225); } + } + } + } + } + + return s0; + } + + function peg$parseSourceCharacter() { + var s0; + + if (input.length > peg$currPos) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c280); } + } + + return s0; + } + + function peg$parseHexEscapeSequence() { + var s0, s1, s2, s3, s4, s5; + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 120) { + s1 = peg$c278; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c279); } + } + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + s3 = peg$currPos; + s4 = peg$parseHexDigit(); + if (s4 !== peg$FAILED) { + s5 = peg$parseHexDigit(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + if (s3 !== peg$FAILED) { + s2 = input.substring(s2, peg$currPos); + } else { + s2 = s3; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c226(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseLineContinuation() { + var s0, s1, s2; + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s1 = peg$c222; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c223); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseLineTerminatorSequence(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c264(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parse_() { + var s0, s1; + + peg$silentFails++; + s0 = []; + s1 = peg$parseWhitespace(); + while (s1 !== peg$FAILED) { + s0.push(s1); + s1 = peg$parseWhitespace(); + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c281); } + } + + return s0; + } + + function peg$parse__() { + var s0, s1; + + peg$silentFails++; + s0 = peg$c283; + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c282); } + } + + return s0; + } + + function peg$parseWhitespace() { + var s0; + + if (peg$c284.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c285); } + } + if (s0 === peg$FAILED) { + s0 = peg$parseUnicodeZs(); + } + + return s0; + } + + + const Types = require('./types'); + + function optional(obj) { + obj.optional = true; + return obj; + } + + function repeatable(obj) { + obj.repeatable = true; + return obj; + } + + function nullable(obj, modifier) { + if (modifier) { + obj.nullable = (modifier === '?' ? true : false); + } + + return obj; + } + + + peg$result = peg$startRuleFunction(); + + if (peg$result !== peg$FAILED && peg$currPos === input.length) { + return peg$result; + } else { + if (peg$result !== peg$FAILED && peg$currPos < input.length) { + peg$fail(peg$endExpectation()); + } + + throw peg$buildStructuredError( + peg$maxFailExpected, + peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null, + peg$maxFailPos < input.length + ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1) + : peg$computeLocation(peg$maxFailPos, peg$maxFailPos) + ); + } +} + +module.exports = { + SyntaxError: peg$SyntaxError, + parse: peg$parse +}; diff --git a/libcore/node_modules/catharsis/lib/schema.js b/libcore/node_modules/catharsis/lib/schema.js new file mode 100644 index 0000000..7143850 --- /dev/null +++ b/libcore/node_modules/catharsis/lib/schema.js @@ -0,0 +1,72 @@ +const _ = require('lodash'); + +// JSON schema types +const ARRAY = 'array'; +const BOOLEAN = 'boolean'; +const OBJECT = 'object'; +const STRING = 'string'; + +const BOOLEAN_SCHEMA = { + type: BOOLEAN +}; +const STRING_SCHEMA = { + type: STRING +}; + +const TYPES = require('./types'); +const TYPE_NAMES = _.values(TYPES); + +module.exports = { + type: OBJECT, + additionalProperties: false, + properties: { + type: { + type: STRING, + enum: TYPE_NAMES + }, + + // field type + key: { '$ref': '#' }, + value: { '$ref': '#' }, + + // function type + params: { + type: ARRAY, + items: { '$ref': '#' } + }, + 'new': { '$ref': '#' }, + 'this': { '$ref': '#' }, + result: {'$ref': '#' }, + + // name expression + name: STRING_SCHEMA, + + // record type + fields: { + type: ARRAY, + items: { '$ref': '#' } + }, + + // type application + expression: { '$ref': '#' }, + applications: { + type: ARRAY, + minItems: 1, + maxItems: 2, + items: { '$ref': '#' } + }, + + // type union + elements: { + type: ARRAY, + minItems: 1, + items: { '$ref': '#' } + }, + + optional: BOOLEAN_SCHEMA, + nullable: BOOLEAN_SCHEMA, + repeatable: BOOLEAN_SCHEMA, + reservedWord: BOOLEAN_SCHEMA + }, + required: ['type'] +}; diff --git a/libcore/node_modules/catharsis/lib/stringify.js b/libcore/node_modules/catharsis/lib/stringify.js new file mode 100644 index 0000000..441d103 --- /dev/null +++ b/libcore/node_modules/catharsis/lib/stringify.js @@ -0,0 +1,277 @@ +/* eslint-disable class-methods-use-this */ + +const Types = require('./types'); + +function combineNameAndType(nameString, typeString) { + const separator = (nameString && typeString) ? ':' : ''; + + return nameString + separator + typeString; +} + +class Stringifier { + constructor(options) { + this._options = options || {}; + this._options.linkClass = this._options.linkClass || this._options.cssClass; + } + + applications(applications) { + let result = ''; + const strings = []; + + if (!applications) { + return result; + } + + for (let i = 0, l = applications.length; i < l; i++) { + strings.push(this.type(applications[i])); + } + + if (this._options.htmlSafe) { + result = '.<'; + } else { + result = '.<'; + } + + result += `${strings.join(', ')}>`; + + return result; + } + + elements(elements) { + let result = ''; + const strings = []; + + if (!elements) { + return result; + } + + for (let i = 0, l = elements.length; i < l; i++) { + strings.push(this.type(elements[i])); + } + + result = `(${strings.join('|')})`; + + return result; + } + + key(type) { + return this.type(type); + } + + name(name) { + return name || ''; + } + + new(funcNew) { + return funcNew ? `new:${this.type(funcNew)}` : ''; + } + + nullable(nullable) { + switch (nullable) { + case true: + return '?'; + case false: + return '!'; + default: + return ''; + } + } + + optional(optional) { + if (optional === true) { + return '='; + } else { + return ''; + } + } + + params(params) { + let result = ''; + const strings = []; + + if (!params || params.length === 0) { + return result; + } + + for (let i = 0, l = params.length; i < l; i++) { + strings.push(this.type(params[i])); + } + + result = strings.join(', '); + + return result; + } + + result(result) { + return result ? `: ${this.type(result)}` : ''; + } + + stringify(type) { + return this.type(type); + } + + this(funcThis) { + return funcThis ? `this:${this.type(funcThis)}` : ''; + } + + type(type) { + let typeString = ''; + + if (!type) { + return typeString; + } + + switch (type.type) { + case Types.AllLiteral: + typeString = this._formatNameAndType(type, '*'); + break; + case Types.FunctionType: + typeString = this._signature(type); + break; + case Types.NullLiteral: + typeString = this._formatNameAndType(type, 'null'); + break; + case Types.RecordType: + typeString = this._record(type); + break; + case Types.TypeApplication: + typeString = this.type(type.expression) + this.applications(type.applications); + break; + case Types.UndefinedLiteral: + typeString = this._formatNameAndType(type, 'undefined'); + break; + case Types.TypeUnion: + typeString = this.elements(type.elements); + break; + case Types.UnknownLiteral: + typeString = this._formatNameAndType(type, '?'); + break; + default: + typeString = this._formatNameAndType(type); + } + + // add optional/nullable/repeatable modifiers + if (!this._options._ignoreModifiers) { + typeString = this._addModifiers(type, typeString); + } + + return typeString; + } + + _record(type) { + const fields = this._recordFields(type.fields); + + return `{${fields.join(', ')}}`; + } + + _recordFields(fields) { + let field; + let keyAndValue; + + const result = []; + + if (!fields) { + return result; + } + + for (let i = 0, l = fields.length; i < l; i++) { + field = fields[i]; + + keyAndValue = this.key(field.key); + keyAndValue += field.value ? `: ${this.type(field.value)}` : ''; + + result.push(keyAndValue); + } + + return result; + } + + // Adds optional, nullable, and repeatable modifiers if necessary. + _addModifiers(type, typeString) { + let combined; + + let optional = ''; + let repeatable = ''; + + if (type.repeatable) { + repeatable = '...'; + } + + combined = this.nullable(type.nullable) + combineNameAndType('', typeString); + optional = this.optional(type.optional); + + return repeatable + combined + optional; + } + + _addLinks(nameString) { + const href = this._getHrefForString(nameString); + let link = nameString; + let linkClass = this._options.linkClass || ''; + + if (href) { + if (linkClass) { + linkClass = ` class="${linkClass}"`; + } + + link = `${nameString}`; + } + + return link; + } + + _formatNameAndType(type, literal) { + let nameString = type.name || literal || ''; + const typeString = type.type ? this.type(type.type) : ''; + + nameString = this._addLinks(nameString); + + return combineNameAndType(nameString, typeString); + } + + _getHrefForString(nameString) { + let href = ''; + const links = this._options.links; + + if (!links) { + return href; + } + + // accept a map or an object + if (links instanceof Map) { + href = links.get(nameString); + } else if ({}.hasOwnProperty.call(links, nameString)) { + href = links[nameString]; + } + + return href; + } + + _signature(type) { + let param; + let prop; + let signature; + + const params = []; + // these go within the signature's parens, in this order + const props = [ + 'new', + 'this', + 'params' + ]; + + for (let i = 0, l = props.length; i < l; i++) { + prop = props[i]; + param = this[prop](type[prop]); + if (param.length > 0) { + params.push(param); + } + } + + signature = `function(${params.join(', ')})`; + signature += this.result(type.result); + + return signature; + } +} + +module.exports = (type, options) => new Stringifier(options).stringify(type); diff --git a/libcore/node_modules/catharsis/lib/types.js b/libcore/node_modules/catharsis/lib/types.js new file mode 100644 index 0000000..6d9b40a --- /dev/null +++ b/libcore/node_modules/catharsis/lib/types.js @@ -0,0 +1,22 @@ +module.exports = Object.freeze({ + // `*` + AllLiteral: 'AllLiteral', + // like `blah` in `{blah: string}` + FieldType: 'FieldType', + // like `function(string): string` + FunctionType: 'FunctionType', + // any string literal, such as `string` or `My.Namespace` + NameExpression: 'NameExpression', + // null + NullLiteral: 'NullLiteral', + // like `{foo: string}` + RecordType: 'RecordType', + // like `Array.` + TypeApplication: 'TypeApplication', + // like `(number|string)` + TypeUnion: 'TypeUnion', + // undefined + UndefinedLiteral: 'UndefinedLiteral', + // `?` + UnknownLiteral: 'UnknownLiteral' +}); diff --git a/libcore/node_modules/catharsis/package.json b/libcore/node_modules/catharsis/package.json new file mode 100644 index 0000000..10565eb --- /dev/null +++ b/libcore/node_modules/catharsis/package.json @@ -0,0 +1,30 @@ +{ + "version": "0.9.0", + "name": "catharsis", + "description": "A JavaScript parser for Google Closure Compiler and JSDoc type expressions.", + "author": "Jeff Williams ", + "repository": { + "type": "git", + "url": "https://github.com/hegemonic/catharsis" + }, + "bugs": "https://github.com/hegemonic/catharsis/issues", + "main": "catharsis.js", + "dependencies": { + "lodash": "^4.17.15" + }, + "devDependencies": { + "ajv": "^6.12.2", + "mocha": "^8.0.1", + "pegjs": "^0.10.0", + "should": "^13.2.3", + "should-equal": "^2.0.0" + }, + "engines": { + "node": ">= 10" + }, + "scripts": { + "prepare": "./node_modules/pegjs/bin/pegjs ./lib/parser.pegjs", + "test": "./node_modules/mocha/bin/mocha" + }, + "license": "MIT" +} diff --git a/libcore/node_modules/catharsis/res/en.json b/libcore/node_modules/catharsis/res/en.json new file mode 100644 index 0000000..673d511 --- /dev/null +++ b/libcore/node_modules/catharsis/res/en.json @@ -0,0 +1,92 @@ +{ + "all": "any type", + "application": { + "array": "<%= prefix %> <%= codeTagOpen %>Array<%= codeTagClose %> of <%= application %> <%= suffix %>", + "object": "<%= prefix %> <%= codeTagOpen %>Object<%= codeTagClose %> with <%= application %> properties <%= suffix %>", + "objectNonString": "<%= prefix %> <%= codeTagOpen %>Object<%= codeTagClose %> with <%= keyApplication %> keys and <%= application %> properties <%= suffix %>", + "other": "<%= prefix %> <%= codeTagOpen %><%= type %> containing <%= application %> <%= suffix %>" + }, + "function": { + "extended": { + "new": "Returns <%= functionNew %> when called with <%= codeTagOpen %>new<%= codeTagClose %>.", + "returns": "Returns <%= type %>.", + "signature": "function(<%= functionParams %>)", + "this": "Within the function, <%= codeTagOpen %>this<%= codeTagClose %> refers to <%= functionThis %>." + }, + "simple": { + "new": "constructs <%= functionNew %>", + "returns": "returns <%= type %>", + "signature": "<%= prefix %> function(<%= functionParams %>) <%= functionReturns %>", + "this": "<%= codeTagOpen %>this<%= codeTagClose %> = <%= functionThis %>" + } + }, + "modifiers": { + "extended": { + "nonNullable": "Must not be null.", + "nullable": "May be null.", + "optional": "Optional.", + "prefix": "", + "repeatable": "May be provided more than once.", + "suffix": "" + }, + "simple": { + "nonNullable": "non-null", + "nullable": "nullable", + "optional": "optional", + "prefix": "<%= optional %> <%= nullable %> <%= repeatable %>", + "repeatable": "repeatable", + "suffix": "" + } + }, + "name": "<%= codeTagOpen %>{{ name }}<%= codeTagClose %> <%= suffix %>", + "null": "null", + "params": { + "first": { + "one": "<%= param %>", + "two": "<%= param %>, ", + "many": "<%= param %>, " + }, + "middle": { + "many": "<%= param %>, " + }, + "last": { + "two": "<%= param %>", + "many": "<%= param %>" + } + }, + "record": { + "first": { + "one": "<%= prefix %> {<%= field %>} <%= suffix %>", + "two": "<%= prefix %> {<%= field %>, ", + "many": "<%= prefix %> {<%= field %>, " + }, + "middle": { + "many": "<%= field %>, " + }, + "last": { + "two": "<%= field %>} <%= suffix %>", + "many": "<%= field %>} <%= suffix %>" + } + }, + "field": { + "typed": "<%= name %>: <%= type %>", + "untyped": "<%= name %>" + }, + "type": "<%= prefix %> <%= codeTagOpen %><%= type %><%= codeTagClose %> <%= suffix %>", + "undefined": "undefined", + "union": { + "first": { + "one": "<%= prefix %> <%= element %> <%= suffix %>", + "two": "<%= prefix %> (<%= element %> ", + "many": "<%= prefix %> (<%= element %>, " + }, + "middle": { + "many": "<%= element %>, " + }, + "last": { + "two": "or <%= element %>) <%= suffix %>", + "many": "or <%= element %>) <%= suffix %>" + } + }, + "unknown": "unknown" +} diff --git a/libcore/node_modules/chalk/index.d.ts b/libcore/node_modules/chalk/index.d.ts new file mode 100644 index 0000000..9cd88f3 --- /dev/null +++ b/libcore/node_modules/chalk/index.d.ts @@ -0,0 +1,415 @@ +/** +Basic foreground colors. + +[More colors here.](https://github.com/chalk/chalk/blob/master/readme.md#256-and-truecolor-color-support) +*/ +declare type ForegroundColor = + | 'black' + | 'red' + | 'green' + | 'yellow' + | 'blue' + | 'magenta' + | 'cyan' + | 'white' + | 'gray' + | 'grey' + | 'blackBright' + | 'redBright' + | 'greenBright' + | 'yellowBright' + | 'blueBright' + | 'magentaBright' + | 'cyanBright' + | 'whiteBright'; + +/** +Basic background colors. + +[More colors here.](https://github.com/chalk/chalk/blob/master/readme.md#256-and-truecolor-color-support) +*/ +declare type BackgroundColor = + | 'bgBlack' + | 'bgRed' + | 'bgGreen' + | 'bgYellow' + | 'bgBlue' + | 'bgMagenta' + | 'bgCyan' + | 'bgWhite' + | 'bgGray' + | 'bgGrey' + | 'bgBlackBright' + | 'bgRedBright' + | 'bgGreenBright' + | 'bgYellowBright' + | 'bgBlueBright' + | 'bgMagentaBright' + | 'bgCyanBright' + | 'bgWhiteBright'; + +/** +Basic colors. + +[More colors here.](https://github.com/chalk/chalk/blob/master/readme.md#256-and-truecolor-color-support) +*/ +declare type Color = ForegroundColor | BackgroundColor; + +declare type Modifiers = + | 'reset' + | 'bold' + | 'dim' + | 'italic' + | 'underline' + | 'inverse' + | 'hidden' + | 'strikethrough' + | 'visible'; + +declare namespace chalk { + /** + Levels: + - `0` - All colors disabled. + - `1` - Basic 16 colors support. + - `2` - ANSI 256 colors support. + - `3` - Truecolor 16 million colors support. + */ + type Level = 0 | 1 | 2 | 3; + + interface Options { + /** + Specify the color support for Chalk. + + By default, color support is automatically detected based on the environment. + + Levels: + - `0` - All colors disabled. + - `1` - Basic 16 colors support. + - `2` - ANSI 256 colors support. + - `3` - Truecolor 16 million colors support. + */ + level?: Level; + } + + /** + Return a new Chalk instance. + */ + type Instance = new (options?: Options) => Chalk; + + /** + Detect whether the terminal supports color. + */ + interface ColorSupport { + /** + The color level used by Chalk. + */ + level: Level; + + /** + Return whether Chalk supports basic 16 colors. + */ + hasBasic: boolean; + + /** + Return whether Chalk supports ANSI 256 colors. + */ + has256: boolean; + + /** + Return whether Chalk supports Truecolor 16 million colors. + */ + has16m: boolean; + } + + interface ChalkFunction { + /** + Use a template string. + + @remarks Template literals are unsupported for nested calls (see [issue #341](https://github.com/chalk/chalk/issues/341)) + + @example + ``` + import chalk = require('chalk'); + + log(chalk` + CPU: {red ${cpu.totalPercent}%} + RAM: {green ${ram.used / ram.total * 100}%} + DISK: {rgb(255,131,0) ${disk.used / disk.total * 100}%} + `); + ``` + + @example + ``` + import chalk = require('chalk'); + + log(chalk.red.bgBlack`2 + 3 = {bold ${2 + 3}}`) + ``` + */ + (text: TemplateStringsArray, ...placeholders: unknown[]): string; + + (...text: unknown[]): string; + } + + interface Chalk extends ChalkFunction { + /** + Return a new Chalk instance. + */ + Instance: Instance; + + /** + The color support for Chalk. + + By default, color support is automatically detected based on the environment. + + Levels: + - `0` - All colors disabled. + - `1` - Basic 16 colors support. + - `2` - ANSI 256 colors support. + - `3` - Truecolor 16 million colors support. + */ + level: Level; + + /** + Use HEX value to set text color. + + @param color - Hexadecimal value representing the desired color. + + @example + ``` + import chalk = require('chalk'); + + chalk.hex('#DEADED'); + ``` + */ + hex(color: string): Chalk; + + /** + Use keyword color value to set text color. + + @param color - Keyword value representing the desired color. + + @example + ``` + import chalk = require('chalk'); + + chalk.keyword('orange'); + ``` + */ + keyword(color: string): Chalk; + + /** + Use RGB values to set text color. + */ + rgb(red: number, green: number, blue: number): Chalk; + + /** + Use HSL values to set text color. + */ + hsl(hue: number, saturation: number, lightness: number): Chalk; + + /** + Use HSV values to set text color. + */ + hsv(hue: number, saturation: number, value: number): Chalk; + + /** + Use HWB values to set text color. + */ + hwb(hue: number, whiteness: number, blackness: number): Chalk; + + /** + Use a [Select/Set Graphic Rendition](https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters) (SGR) [color code number](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit) to set text color. + + 30 <= code && code < 38 || 90 <= code && code < 98 + For example, 31 for red, 91 for redBright. + */ + ansi(code: number): Chalk; + + /** + Use a [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set text color. + */ + ansi256(index: number): Chalk; + + /** + Use HEX value to set background color. + + @param color - Hexadecimal value representing the desired color. + + @example + ``` + import chalk = require('chalk'); + + chalk.bgHex('#DEADED'); + ``` + */ + bgHex(color: string): Chalk; + + /** + Use keyword color value to set background color. + + @param color - Keyword value representing the desired color. + + @example + ``` + import chalk = require('chalk'); + + chalk.bgKeyword('orange'); + ``` + */ + bgKeyword(color: string): Chalk; + + /** + Use RGB values to set background color. + */ + bgRgb(red: number, green: number, blue: number): Chalk; + + /** + Use HSL values to set background color. + */ + bgHsl(hue: number, saturation: number, lightness: number): Chalk; + + /** + Use HSV values to set background color. + */ + bgHsv(hue: number, saturation: number, value: number): Chalk; + + /** + Use HWB values to set background color. + */ + bgHwb(hue: number, whiteness: number, blackness: number): Chalk; + + /** + Use a [Select/Set Graphic Rendition](https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters) (SGR) [color code number](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit) to set background color. + + 30 <= code && code < 38 || 90 <= code && code < 98 + For example, 31 for red, 91 for redBright. + Use the foreground code, not the background code (for example, not 41, nor 101). + */ + bgAnsi(code: number): Chalk; + + /** + Use a [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set background color. + */ + bgAnsi256(index: number): Chalk; + + /** + Modifier: Resets the current color chain. + */ + readonly reset: Chalk; + + /** + Modifier: Make text bold. + */ + readonly bold: Chalk; + + /** + Modifier: Emitting only a small amount of light. + */ + readonly dim: Chalk; + + /** + Modifier: Make text italic. (Not widely supported) + */ + readonly italic: Chalk; + + /** + Modifier: Make text underline. (Not widely supported) + */ + readonly underline: Chalk; + + /** + Modifier: Inverse background and foreground colors. + */ + readonly inverse: Chalk; + + /** + Modifier: Prints the text, but makes it invisible. + */ + readonly hidden: Chalk; + + /** + Modifier: Puts a horizontal line through the center of the text. (Not widely supported) + */ + readonly strikethrough: Chalk; + + /** + Modifier: Prints the text only when Chalk has a color support level > 0. + Can be useful for things that are purely cosmetic. + */ + readonly visible: Chalk; + + readonly black: Chalk; + readonly red: Chalk; + readonly green: Chalk; + readonly yellow: Chalk; + readonly blue: Chalk; + readonly magenta: Chalk; + readonly cyan: Chalk; + readonly white: Chalk; + + /* + Alias for `blackBright`. + */ + readonly gray: Chalk; + + /* + Alias for `blackBright`. + */ + readonly grey: Chalk; + + readonly blackBright: Chalk; + readonly redBright: Chalk; + readonly greenBright: Chalk; + readonly yellowBright: Chalk; + readonly blueBright: Chalk; + readonly magentaBright: Chalk; + readonly cyanBright: Chalk; + readonly whiteBright: Chalk; + + readonly bgBlack: Chalk; + readonly bgRed: Chalk; + readonly bgGreen: Chalk; + readonly bgYellow: Chalk; + readonly bgBlue: Chalk; + readonly bgMagenta: Chalk; + readonly bgCyan: Chalk; + readonly bgWhite: Chalk; + + /* + Alias for `bgBlackBright`. + */ + readonly bgGray: Chalk; + + /* + Alias for `bgBlackBright`. + */ + readonly bgGrey: Chalk; + + readonly bgBlackBright: Chalk; + readonly bgRedBright: Chalk; + readonly bgGreenBright: Chalk; + readonly bgYellowBright: Chalk; + readonly bgBlueBright: Chalk; + readonly bgMagentaBright: Chalk; + readonly bgCyanBright: Chalk; + readonly bgWhiteBright: Chalk; + } +} + +/** +Main Chalk object that allows to chain styles together. +Call the last one as a method with a string argument. +Order doesn't matter, and later styles take precedent in case of a conflict. +This simply means that `chalk.red.yellow.green` is equivalent to `chalk.green`. +*/ +declare const chalk: chalk.Chalk & chalk.ChalkFunction & { + supportsColor: chalk.ColorSupport | false; + Level: chalk.Level; + Color: Color; + ForegroundColor: ForegroundColor; + BackgroundColor: BackgroundColor; + Modifiers: Modifiers; + stderr: chalk.Chalk & {supportsColor: chalk.ColorSupport | false}; +}; + +export = chalk; diff --git a/libcore/node_modules/chalk/license b/libcore/node_modules/chalk/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/libcore/node_modules/chalk/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.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. diff --git a/libcore/node_modules/chalk/package.json b/libcore/node_modules/chalk/package.json new file mode 100644 index 0000000..47c23f2 --- /dev/null +++ b/libcore/node_modules/chalk/package.json @@ -0,0 +1,68 @@ +{ + "name": "chalk", + "version": "4.1.2", + "description": "Terminal string styling done right", + "license": "MIT", + "repository": "chalk/chalk", + "funding": "https://github.com/chalk/chalk?sponsor=1", + "main": "source", + "engines": { + "node": ">=10" + }, + "scripts": { + "test": "xo && nyc ava && tsd", + "bench": "matcha benchmark.js" + }, + "files": [ + "source", + "index.d.ts" + ], + "keywords": [ + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "string", + "str", + "ansi", + "style", + "styles", + "tty", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "log", + "logging", + "command-line", + "text" + ], + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "devDependencies": { + "ava": "^2.4.0", + "coveralls": "^3.0.7", + "execa": "^4.0.0", + "import-fresh": "^3.1.0", + "matcha": "^0.7.0", + "nyc": "^15.0.0", + "resolve-from": "^5.0.0", + "tsd": "^0.7.4", + "xo": "^0.28.2" + }, + "xo": { + "rules": { + "unicorn/prefer-string-slice": "off", + "unicorn/prefer-includes": "off", + "@typescript-eslint/member-ordering": "off", + "no-redeclare": "off", + "unicorn/string-content": "off", + "unicorn/better-regex": "off" + } + } +} diff --git a/libcore/node_modules/chalk/readme.md b/libcore/node_modules/chalk/readme.md new file mode 100644 index 0000000..a055d21 --- /dev/null +++ b/libcore/node_modules/chalk/readme.md @@ -0,0 +1,341 @@ +

+
+
+ Chalk +
+
+
+

+ +> Terminal string styling done right + +[![Build Status](https://travis-ci.org/chalk/chalk.svg?branch=master)](https://travis-ci.org/chalk/chalk) [![Coverage Status](https://coveralls.io/repos/github/chalk/chalk/badge.svg?branch=master)](https://coveralls.io/github/chalk/chalk?branch=master) [![npm dependents](https://badgen.net/npm/dependents/chalk)](https://www.npmjs.com/package/chalk?activeTab=dependents) [![Downloads](https://badgen.net/npm/dt/chalk)](https://www.npmjs.com/package/chalk) [![](https://img.shields.io/badge/unicorn-approved-ff69b4.svg)](https://www.youtube.com/watch?v=9auOCbH5Ns4) [![XO code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/xojs/xo) ![TypeScript-ready](https://img.shields.io/npm/types/chalk.svg) [![run on repl.it](https://repl.it/badge/github/chalk/chalk)](https://repl.it/github/chalk/chalk) + + + +
+ +--- + + + +--- + +
+ +## Highlights + +- Expressive API +- Highly performant +- Ability to nest styles +- [256/Truecolor color support](#256-and-truecolor-color-support) +- Auto-detects color support +- Doesn't extend `String.prototype` +- Clean and focused +- Actively maintained +- [Used by ~50,000 packages](https://www.npmjs.com/browse/depended/chalk) as of January 1, 2020 + +## Install + +```console +$ npm install chalk +``` + +## Usage + +```js +const chalk = require('chalk'); + +console.log(chalk.blue('Hello world!')); +``` + +Chalk comes with an easy to use composable API where you just chain and nest the styles you want. + +```js +const chalk = require('chalk'); +const log = console.log; + +// Combine styled and normal strings +log(chalk.blue('Hello') + ' World' + chalk.red('!')); + +// Compose multiple styles using the chainable API +log(chalk.blue.bgRed.bold('Hello world!')); + +// Pass in multiple arguments +log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz')); + +// Nest styles +log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!')); + +// Nest styles of the same type even (color, underline, background) +log(chalk.green( + 'I am a green line ' + + chalk.blue.underline.bold('with a blue substring') + + ' that becomes green again!' +)); + +// ES2015 template literal +log(` +CPU: ${chalk.red('90%')} +RAM: ${chalk.green('40%')} +DISK: ${chalk.yellow('70%')} +`); + +// ES2015 tagged template literal +log(chalk` +CPU: {red ${cpu.totalPercent}%} +RAM: {green ${ram.used / ram.total * 100}%} +DISK: {rgb(255,131,0) ${disk.used / disk.total * 100}%} +`); + +// Use RGB colors in terminal emulators that support it. +log(chalk.keyword('orange')('Yay for orange colored text!')); +log(chalk.rgb(123, 45, 67).underline('Underlined reddish color')); +log(chalk.hex('#DEADED').bold('Bold gray!')); +``` + +Easily define your own themes: + +```js +const chalk = require('chalk'); + +const error = chalk.bold.red; +const warning = chalk.keyword('orange'); + +console.log(error('Error!')); +console.log(warning('Warning!')); +``` + +Take advantage of console.log [string substitution](https://nodejs.org/docs/latest/api/console.html#console_console_log_data_args): + +```js +const name = 'Sindre'; +console.log(chalk.green('Hello %s'), name); +//=> 'Hello Sindre' +``` + +## API + +### chalk.`