From 5fad3a6e876eb2400afa62150840b02d7312360b Mon Sep 17 00:00:00 2001 From: Reditus <33814724+ReditusDraco@users.noreply.github.com> Date: Fri, 22 May 2026 21:55:05 +0100 Subject: [PATCH 01/12] New systems, dashboard reforctoring starts here --- AI_DASHBOARD_CAPABILITIES_REFERENCE.md | 857 ++++++++++++++++ AI_DUNE_AWAKENING_SYSTEM_CONTEXT.md | 1224 ++++++++++++++++++++++ app/routes/api.py | 532 ++++++++++ app/routes/main.py | 6 + app/services/admin.py | 856 +++++++++++++++- app/utils/constants.py | 1 + templates/admin_experimental.html | 1282 ++++++++++++++++++++++++ 7 files changed, 4756 insertions(+), 2 deletions(-) create mode 100644 AI_DASHBOARD_CAPABILITIES_REFERENCE.md create mode 100644 AI_DUNE_AWAKENING_SYSTEM_CONTEXT.md create mode 100644 templates/admin_experimental.html diff --git a/AI_DASHBOARD_CAPABILITIES_REFERENCE.md b/AI_DASHBOARD_CAPABILITIES_REFERENCE.md new file mode 100644 index 0000000..54cc066 --- /dev/null +++ b/AI_DASHBOARD_CAPABILITIES_REFERENCE.md @@ -0,0 +1,857 @@ +# Dune Dashboard — Complete Capabilities Reference + +> **Generated:** 2026-05-22 +> **Purpose:** Comprehensive reference of all dashboard features, database functions, and admin tools +> **⚠️ SECURITY:** This document contains sensitive operational information. Do not commit to GitHub. + +--- + +## Table of Contents + +1. [Dashboard Admin Features](#1-dashboard-admin-features) +2. [Database Functions Catalog](#2-database-functions-catalog) +3. [RabbitMQ Exchanges & Queues](#3-rabbitmq-exchanges--queues) +4. [BGD Director API Endpoints](#4-bgd-director-api-endpoints) +5. [Kubernetes Resources](#5-kubernetes-resources) +6. [Game Tables Reference](#6-game-tables-reference) + +--- + +## 1. Dashboard Admin Features + +### 1.1 Player Management + +| Feature | Purpose | API Endpoint | DB Function / Query | +|---------|---------|--------------|---------------------| +| **Search Players** | Find players by character name or FLS ID | `POST /api/admin-experimental/search-players` | Query on `encrypted_accounts` + `player_state` | +| **Online Players** | List currently online players | `GET /api/admin-experimental/online-players` | `get_all_online_or_recently_disconnected_player_online_state()` | +| **Teleport Player** | Move offline player to partition + coordinates | `POST /api/admin-experimental/teleport` | `admin_move_offline_player_to_partition(fls_id, partition_id, vector)` | +| **Change Faction** | Switch player's faction allegiance | `POST /api/admin-experimental/change-faction` | Direct SQL on `player_faction` table | +| **Faction Reputation** | View/set reputation with factions | `POST /api/admin-experimental/faction-reputation` | `get_player_current_faction_reputation()`, `set_player_faction_reputation()` | +| **Adjust Currency** | Add/remove Solari, House Script, Spice | `POST /api/admin-experimental/adjust-currency` | Direct INSERT/UPDATE on `player_virtual_currency_balances` | +| **View Currency** | Check player's currency balances | `POST /api/admin-experimental/currency-balances` | Query `player_virtual_currency_balances` | +| **Player Tags** | Add/remove metadata tags on accounts | `POST /api/admin-experimental/player-tags` | `admin_read_player_tags()`, `update_player_tags()` | +| **Flag Cheater** | Mark account for cheating | `POST /api/admin-experimental/flag-cheater` | `flag_player_as_cheater(account_id, cheat_type_enum)` | +| **Player Stats** | View health, hydration, spice exposure | `POST /api/admin-experimental/player-stats` | Query `actors.properties` JSONB | +| **Player Vehicles** | List owned vehicles | `POST /api/admin-experimental/player-vehicles` | `get_player_owned_vehicles_data()` | +| **Inventory Lookup** | View player inventory items | `POST /api/admin-experimental/inventory` | `admin_get_inventory_details()` | +| **Set Character Name** | Rename a character | `POST /api/admin-experimental/set-character-name` | `set_character_name(account_id, name)` | +| **Delete Character** | Remove character from account | `POST /api/admin-experimental/delete-character` | `delete_character(actor_id)` | +| **Delete Account** | Full account deletion | `POST /api/admin-experimental/delete-account` | `delete_account(user_id, reason)` | +| **Set Demo State** | Force demo mode state | `POST /api/admin-experimental/set-demo-state` | `set_demo_state(user_id, demo_state_enum)` | + +### 1.2 Guild Management + +| Feature | Purpose | API Endpoint | DB Function | +|---------|---------|--------------|-------------| +| **List Guilds** | Show all guilds on server | `GET /api/admin-experimental/guilds` | Query `guilds` table | +| **View Guild** | Get guild details + members | `POST /api/admin-experimental/guild-data` | `get_guild_data(guild_id)` | +| **Disband Guild** | Delete guild entirely | `POST /api/admin-experimental/disband-guild` | `disband_guild(guild_id)` | +| **Kick Member** | Remove player from guild | `POST /api/admin-experimental/remove-guild-member` | `remove_guild_members([player_id], guild_id, reason)` | +| **Guild Members** | List guild roster | `POST /api/admin-experimental/guild-members` | `get_guild_members(guild_id)` | +| **Promote Member** | Change guild role | `POST /api/admin-experimental/promote-guild-member` | `promote_guild_member(guild_id, player_id, role_id)` | +| **Demote Member** | Lower guild role | `POST /api/admin-experimental/demote-guild-member` | `demote_guild_member(guild_id, player_id, role_id)` | + +### 1.3 Journey & Progression + +| Feature | Purpose | API Endpoint | DB Function | +|---------|---------|--------------|-------------| +| **Complete Story Nodes** | Mark journey nodes complete | `POST /api/admin-experimental/journey` (action=complete) | `complete_journey_story_nodes_for_player(player_id, [node_ids])` | +| **Reveal Story Nodes** | Unlock hidden nodes | `POST /api/admin-experimental/journey` (action=reveal) | `reveal_journey_story_nodes_for_player(player_id, [node_ids])` | +| **Reset Story Nodes** | Reset progression | `POST /api/admin-experimental/journey` (action=reset) | `delete_journey_story_nodes_for_player(player_id, [node_ids])` | +| **Set Specialization** | Set XP/level for track | `POST /api/admin-experimental/specialization` | `set_specialization_xp_and_level(player_id, track_type, xp, level)` | +| **Reset Specialization** | Clear spec progress | `POST /api/admin-experimental/reset-specialization` | `reset_specialization_tracks(player_id)` | +| **View Inventory** | See player items | `POST /api/admin-experimental/inventory` | `admin_get_inventory_details(account_id)` | + +### 1.4 Economy & World + +| Feature | Purpose | API Endpoint | DB Function | +|---------|---------|--------------|-------------| +| **Reset Vendor Stock** | Refresh vendor inventory | `POST /api/admin-experimental/clean-vendor-stock` | `clean_stock_for_player(player_id)` | +| **View Tax Invoices** | Check player tax bills | `POST /api/admin-experimental/tax-invoices` | `taxation_get_all_invoices_for_player(player_id)` | +| **Reset Spice Fields** | Reset spice state on map | `POST /api/admin-experimental/spice` | `reset_global_spice_field_state(map, dim)` | +| **Force Spice Spawn** | Trigger spice field spawn | `POST /api/admin-experimental/spice` | `try_spawn_spicefield(server_id, spicefield_id)` | +| **List Partitions** | Show all world partitions | `GET /api/admin-experimental/partitions` | Query `world_partition` table | +| **Battlegroup Info** | Full server status | `GET /api/admin-experimental/battlegroup` | BGD API `/v0/battlegroup` | + +### 1.5 Server Administration + +| Feature | Purpose | API Endpoint | DB Function | +|---------|---------|--------------|-------------| +| **Set Players Offline** | Force all players offline | `POST /api/admin-experimental/server-tools` | `set_players_from_server_ids_offline([server_ids])` | +| **Cleanup Orphans** | Remove orphaned entities | `POST /api/admin-experimental/server-tools` | `cleanup_orphaned_entities()` | +| **View Permissions** | Check actor permissions | `POST /api/admin-experimental/permissions` | `get_permission_for_actors([actor_ids])` | +| **Set Player Rank** | Set permission rank | `POST /api/admin-experimental/permissions` | `permission_set_player_rank(actor_id, player_id, rank, map_id)` | +| **In-Game Broadcast** | Send notification to all players | `POST /api/admin-experimental/broadcast` | `rabbitmqctl eval` on RMQ pod (Erlang) | +| **Ban Player** | Ban with duration | `POST /api/ban_player` | Insert into `dashboard.bans` + iptables | +| **Unban Player** | Remove ban | `POST /api/unban_player` | Delete from `dashboard.bans` + iptables | +| **Kick Player** | Temporary kick | `POST /api/kick_player` | iptables DROP for 60 seconds | +| **Detect Player IPs** | Parse logs for IPs | `POST /api/detect_player_ips` | SSH + kubectl to read game logs | + +### 1.6 Item & Entity Editing + +| Feature | Purpose | API Endpoint | DB Function | +|---------|---------|--------------|-------------| +| **Edit Item** | Modify stack size, quality, durability | `POST /api/edit_item` | Direct UPDATE on `items` table | +| **Delete Item** | Remove item | `POST /api/delete_item` | `DELETE FROM items WHERE id = ?` | +| **Add Item** | Spawn item to inventory | `POST /api/add_item` | `INSERT INTO items ...` | +| **Edit Vitals** | Change health, hydration, spice | `POST /api/edit_vitals` | UPDATE `actors.properties` + `gas_attributes` | +| **Edit Tech Knowledge** | Set tech points | `POST /api/edit_tech_knowledge` | UPDATE `actors.properties` (TechKnowledgePlayerComponent) | +| **Edit XP** | Set specialization XP | `POST /api/edit_xp` | UPSERT on `specialization_tracks` | +| **Edit Faction** | Change faction directly | `POST /api/edit_faction` | UPSERT on `player_faction` | +| **Edit Currency** | Set exact balance | `POST /api/edit_currency` | UPSERT on `player_virtual_currency_balances` | + +### 1.7 Function Explorer + +| Feature | Purpose | API Endpoint | +|---------|---------|--------------| +| **List Functions** | Get all 517 DB functions | `GET /api/admin-experimental/functions` | +| **Get Function** | View function definition | `GET /api/admin-experimental/functions/:name` | +| **Execute Function** | Call function with params | `POST /api/admin-experimental/functions/:name/execute` | +| **Execute SQL** | Run raw SQL (admin only) | `POST /api/admin-experimental/execute` | + +### 1.8 File Browser + +| Feature | Purpose | API Endpoint | +|---------|---------|--------------| +| **List Files** | Browse `/srv` directory | `POST /api/files/list` | +| **View File** | Read file content | `GET /api/files/view` | +| **Save File** | Edit file content | `POST /api/files/save` | + +--- + +## 2. Database Functions Catalog + +### 2.1 Admin & Debug Functions (24 functions) + +| Function | Purpose | +|----------|---------| +| `admin_get_character_details(in_account_id bigint)` | Get full character data for account | +| `admin_get_character_ids(in_search_term text)` | Search characters by name pattern | +| `admin_get_inventory_details(in_account_id bigint)` | Get all inventory items for account | +| `admin_get_journey_details(in_player_id text, in_story_node_id text)` | Get journey node progress | +| `admin_get_mnemonic_recall_details(in_account_id bigint)` | Get mnemonic recall lessons | +| `admin_get_partitions()` | List all world partitions | +| `admin_move_offline_player(in_fls_id text, in_target_partition_name text, in_target_location vector)` | Teleport by partition name | +| `admin_move_offline_player_to_partition(in_fls_id text, in_target_partition_id bigint, in_target_location vector)` | Teleport by partition ID | +| `admin_read_player_tags(in_account_id bigint)` | Get tags for account | +| `debug_add_test_table_data(in_entry text)` | Debug: insert test data | +| `debug_collect_test_table_data()` | Debug: collect test data | +| `debug_echo(in_text text, in_notices text[])` | Debug: echo with notices | +| `debug_get_coriolis_seeds()` | Debug: get all Coriolis seeds | +| `debug_raise_exception(in_exception text, in_notices text[])` | Debug: raise exception | +| `debug_raise_notices(in_notices text[])` | Debug: raise notices | +| `debug_reset_test_table()` | Debug: reset test table | +| `debug_set_farm_seed(in_new_coriolis_seed integer)` | Debug: set farm seed | +| `debug_set_map_seed(in_map text, in_new_coriolis_seed integer)` | Debug: set map seed | +| `debug_set_partition_seed(in_partition_id bigint, in_new_coriolis_seed integer)` | Debug: set partition seed | +| `get_all_demo_players()` | Get all demo state players | +| `get_all_faction_members()` | Get all faction members | +| `get_all_guild_members()` | Get all guild members | +| `get_all_online_or_recently_disconnected_player_online_state()` | Get online players | +| `get_schema_version()` | Get DB schema version | + +### 2.2 Character Transfer Functions (22 functions) + +| Function | Purpose | +|----------|---------| +| `_character_transfer_allocate_id(kind dune._charactertransferentrykind, data jsonb)` | Allocate transfer ID | +| `_character_transfer_create_data_table()` | Create transfer data table | +| `_character_transfer_data_filter(id text, removed text[], VARIADIC refs dune._charactertransferdatafilterref[])` | Filter transfer data | +| `_character_transfer_data_table_load(entries jsonb)` | Load transfer data table | +| `_character_transfer_data_table_save()` | Save transfer data table | +| `_character_transfer_ensure_player_is_owner_of_vbt_vehicle(in_vehicle_id bigint[])` | Validate vehicle ownership | +| `_character_transfer_get_filter(kind dune._charactertransferentrykind)` | Get transfer filter | +| `_character_transfer_get_patches_checksum()` | Get patches checksum | +| `_character_transfer_pre_export_validation(in_fls_id text)` | Pre-export validation | +| `_character_transfer_property_not_exported_is_expected(path text)` | Check property export | +| `_character_transfer_replace_local_id_with_transfer_id(data text, path text)` | Replace IDs for export | +| `_character_transfer_replace_local_id_with_transfer_id_in_json(data jsonb, path text)` | Replace IDs in JSON | +| `_character_transfer_replace_transfer_id_with_local_id(data text, path text)` | Replace IDs for import | +| `_character_transfer_replace_transfer_id_with_local_id_in_json(data jsonb, path text)` | Replace IDs in JSON | +| `_character_transfer_store_in_world_owned_vehicles_into_recovery(in_player_id bigint)` | Store vehicles in recovery | +| `_character_transfer_top_level_export(in_kind dune._charactertransferentrykind, data jsonb)` | Export character data | +| `_character_transfer_top_level_import(in_kind dune._charactertransferentrykind, data jsonb, in_id bigint)` | Import character data | +| `character_migration_export(in_fls_id text)` | Export for migration | +| `character_migration_import(in_data jsonb, in_fls_id text, in_character_name text)` | Import migration data | +| `character_transfer_export(in_fls_id text)` | Export character | +| `character_transfer_get_unsaved_counts(in_fls_id text)` | Get unsaved counts | +| `character_transfer_import(in_data jsonb, in_fls_id text, in_character_name text)` | Import character | + +### 2.3 Guild & Faction Functions (28 functions) + +| Function | Purpose | +|----------|---------| +| `accept_guild_invite(in_invite_id bigint, in_role_id smallint, ...)` | Accept guild invite | +| `add_guild_invite(in_player_id bigint, in_guild_id bigint, ...)` | Create guild invite | +| `add_guild_member(in_player_id bigint, in_guild_id bigint, ...)` | Add member to guild | +| `break_guild_allegiance(in_guild_id bigint, in_neutral_faction_id smallint)` | Break guild allegiance | +| `change_player_faction(in_player_id bigint, in_faction_id smallint, ...)` | Change player faction | +| `clean_guild_invites_with_incompatible_faction(in_player_id bigint, in_faction_id smallint, ...)` | Clean incompatible invites | +| `clean_old_guild_invites(in_cutoff_timespan bigint)` | Clean old guild invites | +| `create_guild(in_player_id bigint, in_neutral_faction smallint, ...)` | Create new guild | +| `demote_guild_member(in_guild_id bigint, in_player_id bigint, in_new_role smallint)` | Demote guild member | +| `disband_guild(in_guild_id bigint)` | Disband guild | +| `get_guild_data(in_guild_id bigint)` | Get guild details | +| `get_guild_data_for_player(in_player_id bigint)` | Get guild for player | +| `get_guild_for_player(in_player_id bigint)` | Get guild ID for player | +| `get_guild_invites(in_guild_id bigint)` | Get guild invites | +| `get_guild_members(in_guild_id bigint)` | Get guild member list | +| `guild_handle_actor_delete(in_player_id bigint)` | Handle actor delete | +| `guilds_get_exclusive_operation_lock()` | Get guild operation lock | +| `handle_player_faction_guild_effects(in_player_id bigint, in_faction_id smallint, ...)` | Apply faction effects | +| `is_player_guild_admin(in_player_id bigint, in_guild_id bigint)` | Check if guild admin | +| `pledge_guild_allegiance(in_guild_id bigint, in_guild_leader_player_id bigint, ...)` | Pledge allegiance | +| `promote_guild_member(in_guild_id bigint, in_player_id bigint, in_new_role smallint)` | Promote guild member | +| `remove_guild_members(in_player_ids bigint[], in_guild_id bigint, in_remove_reason smallint)` | Remove members | +| `get_player_current_faction_reputation(in_actor_id bigint)` | Get faction reputation | +| `get_player_faction(in_player_id bigint, in_neutral_faction_id smallint)` | Get player faction | +| `get_player_faction_name(in_actor_id bigint)` | Get faction name | +| `set_player_faction_reputation(in_actor_id bigint, in_faction_id smallint, in_reputation_amount integer)` | Set reputation | +| `get_all_player_in_guild_online_state(in_guild_id bigint)` | Get guild online members | +| `get_player_ids_online_state(in_player_ids bigint[])` | Get player online status | + +### 2.4 Party Functions (13 functions) + +| Function | Purpose | +|----------|---------| +| `accept_party_invite(in_invite_id bigint, in_platform_session_id text, in_max_party_member_count integer)` | Accept party invite | +| `add_party_invite(in_sender_player_id bigint, in_sender_platform_name text, ...)` | Create party invite | +| `clean_expired_party_invites(in_invite_expire_seconds integer)` | Clean expired invites | +| `disband_party(in_party_id bigint)` | Disband party | +| `get_all_parties()` | Get all parties | +| `get_all_party_invites()` | Get all party invites | +| `get_all_party_members()` | Get all party members | +| `get_party_members(in_party_id bigint)` | Get party members | +| `internal_add_party_member(in_invite_id bigint, in_party_id bigint, ...)` | Add party member | +| `internal_create_party(in_invite_id bigint, in_leader_id bigint, ...)` | Create party | +| `join_platform_session_party(in_leader_platform_id text, in_player_platform_id text, ...)` | Join platform party | +| `parties_get_exclusive_operation_lock()` | Get party operation lock | +| `promote_new_party_leader(in_party_id bigint)` | Promote new leader | +| `promote_party_leader_to(in_party_id bigint, in_player_id bigint)` | Set party leader | +| `remove_party_invite(in_invite_id bigint, in_remove_reason smallint)` | Remove party invite | +| `remove_party_member(in_player_id bigint, in_remove_reason smallint)` | Remove party member | +| `update_party_platform_session(in_party_id bigint, in_platform_session_id text, in_platform_name text)` | Update platform session | + +### 2.5 Inventory & Items (42 functions) + +| Function | Purpose | +|----------|---------| +| `add_item_delete_log(in_item_id bigint, in_inventory_id bigint, in_template_id text)` | Log item delete | +| `add_item_trace_log(...)` | Log item movement | +| `advance_items_id_sequencer(count bigint)` | Advance item ID sequence | +| `delete_inventory_item(in_item_id bigint, in_count bigint)` | Delete inventory item | +| `get_inventory_data(in_inventory_id bigint)` | Get inventory data | +| `get_inventory_id(in_actor_id bigint, in_component_name_hash integer)` | Get inventory ID | +| `get_items_to_remove(items_to_remove text[])` | Get items to remove | +| `get_sub_inventory_id(in_owner_item_id bigint)` | Get sub-inventory ID | +| `load_items(in_inventory_id bigint)` | Load inventory items | +| `merge_inventory_items(in_item_id bigint, in_dst_inventory_id bigint, ...)` | Merge item stacks | +| `merge_or_move_inventory_item(in_item_id bigint, in_dst_inventory_id bigint, ...)` | Merge or move item | +| `move_inventory_item(in_item_id bigint, in_dst_inventory_id bigint, ...)` | Move item | +| `save_item(in_item dune.inventoryitem)` | Save item | +| `update_inventories_data(in_inventory_data_list dune.inventorydata[])` | Update inventories | +| `update_inventory(in_delete_list bigint[], in_stack_update dune.itemstackupdate[], ...)` | Update inventory | +| `update_item_locations(in_item_locations dune.inventoryitemlocation[])` | Update item locations | +| `admin_get_inventory_details(in_account_id bigint)` | Get inventory for account | +| `get_exchange_inventory_id(in_exchange_id bigint)` | Get exchange inventory | +| `get_vehicle_module_inventory_id(in_vehicle_module_id bigint, in_vehicle_module_inventory_type integer)` | Get module inventory | +| `load_building(in_building_id bigint)` | Load building data | +| `load_placeable(in_placeable_id bigint)` | Load placeable data | +| `load_totem(in_id bigint)` | Load totem data | +| `load_vehicle_modules(in_vehicle_id bigint)` | Load vehicle modules | +| `save_building(in_building_id bigint, in_data dune.buildingsavedata)` | Save building | +| `save_placeable(in_placeable_id bigint, in_data dune.placeablesavedata)` | Save placeable | +| `save_totem(in_id bigint, in_data dune.totemsavedata)` | Save totem | +| `save_vehicle_modules(in_add_list dune.vehiclemodule[], in_delete_list bigint[], ...)` | Save vehicle modules | +| `base_backup_delete(in_base_backup_id bigint)` | Delete base backup | +| `base_backup_find_totems_from_player_owner(in_player_id bigint)` | Find totems for backup | +| `base_backup_finish_placing(in_base_backup_id bigint)` | Finish placing backup | +| `base_backup_get_actors_to_spawn(in_base_backup_id bigint)` | Get actors to spawn | +| `base_backup_get_available_backups(in_player_id bigint)` | Get available backups | +| `base_backup_get_buildable_data(in_base_backup_id bigint)` | Get buildable data | +| `base_backup_get_data(in_base_backup_id bigint)` | Get backup data | +| `base_backup_get_totem_data(in_base_backup_id bigint)` | Get totem data | +| `base_backup_get_totem_data_from_totem_id(in_totem_id bigint)` | Get totem data by ID | +| `base_backup_get_totem_id(backup_id bigint)` | Get totem ID | +| `base_backup_recycle(in_base_backup_id bigint, in_target_inventory_id bigint)` | Recycle backup | +| `base_backup_save(in_player_actor_id bigint, in_base_backup_name text, ...)` | Save base backup | +| `base_backup_save_all_totems_from_player_owner(in_player_id bigint)` | Save all totems | +| `base_backup_save_from_totem(in_player_id bigint, totem_id bigint)` | Save from totem | +| `get_unbacked_up_vehicle_ids_for_account(in_account_id bigint)` | Get unbacked vehicles | + +### 2.6 Currency & Economy (21 functions) + +| Function | Purpose | +|----------|---------| +| `adjust_player_virtual_currency_balance(in_controller_id bigint, in_currency_id smallint, in_delta bigint)` | Adjust currency | +| `dune_exchange_add_sell_order(...)` | Add exchange sell order | +| `dune_exchange_cancel_order(in_order_id bigint, in_purge_time bigint, in_completion_type integer)` | Cancel order | +| `dune_exchange_expire_orders(in_exchange_id bigint, in_current_time bigint, ...)` | Expire orders | +| `dune_exchange_fulfill_sell_order(...)` | Fulfill sell order | +| `dune_exchange_get_item_price_stats(in_template_ids text[])` | Get price stats | +| `dune_exchange_get_user_id(in_owner_id bigint)` | Get exchange user ID | +| `dune_exchange_get_used_order_slots(in_controller_id bigint)` | Get used slots | +| `dune_exchange_modify_user_solari_balance(in_controller_id bigint, in_solari_delta bigint)` | Modify Solari | +| `dune_exchange_purge_completed_orders(in_exchange_id bigint, in_current_time bigint)` | Purge completed | +| `dune_exchange_query_storage_item(in_order_id bigint)` | Query storage item | +| `dune_exchange_query_storage_items(in_exchange_id bigint, in_owner_id bigint)` | Query storage items | +| `dune_exchange_relist_order(in_order_id bigint, in_expiration_time bigint, ...)` | Relist order | +| `dune_exchange_retrieve_solari_balance(in_owner_id bigint)` | Retrieve Solari | +| `dune_exchange_retrieve_solaris_from_item(in_controller_id bigint, in_order_id bigint)` | Retrieve from item | +| `dune_exchange_retrieve_storage_item(in_exchange_id bigint, in_order_id bigint, ...)` | Retrieve storage item | +| `dune_exchange_update_recurring_sell_order(...)` | Update recurring order | +| `get_dune_exchange_accesspoint_id(in_exchange_id bigint, in_name text)` | Get access point | +| `get_dune_exchange_data(in_exchange_id bigint, in_controller_id bigint)` | Get exchange data | +| `get_dune_exchange_id(in_name text)` | Get exchange ID | +| `get_player_virtual_currency_balances(in_controller_id bigint)` | Get currency balances | +| `get_solaris_id()` | Get Solari currency ID | +| `taxation_emit_invoices(new_tax_invoices dune.taxinvoicedata[])` | Emit tax invoices | +| `taxation_get_all_invoices_for_player(in_player_id bigint)` | Get player invoices | +| `taxation_get_all_invoices_for_server(map_name text, in_dimension_index integer, in_partition_id bigint)` | Get server invoices | +| `taxation_get_all_invoices_for_totem(in_totem_id bigint)` | Get totem invoices | +| `taxation_pay_invoice(invoice_id bigint, paid_invoice_status smallint)` | Pay invoice | +| `taxation_remove_invoices(invoices_to_remove bigint[])` | Remove invoices | +| `taxation_remove_invoices_from_totem(totem_actor_id bigint)` | Remove totem invoices | +| `taxation_update_invoice_status(...)` | Update invoice status | + +### 2.7 Journey & Progression (26 functions) + +| Function | Purpose | +|----------|---------| +| `complete_journey_nodes_where_prerequisite_nodes_are_complete(story_ids_to_complete text[], prerequisite_completed_story_ids text[])` | Complete nodes | +| `complete_journey_story_nodes_for_player(in_player_id text, in_story_node_ids text[])` | Complete for player | +| `create_or_update_tutorial_entry(in_player_id bigint, in_tutorial_id smallint, in_tutorial_state smallint)` | Create tutorial | +| `delete_all_journey_story_nodes(in_account_id bigint)` | Delete all nodes | +| `delete_all_tutorial_entries(in_player_id bigint)` | Delete tutorials | +| `delete_journey_story_ids(story_ids text[])` | Delete story IDs | +| `delete_journey_story_node(in_account_id bigint, in_story_node_id text)` | Delete node | +| `delete_journey_story_nodes_for_group_for_player(in_account_id bigint, in_reset_group dune.journeystoryresetgroup)` | Delete group | +| `delete_journey_story_nodes_for_player(in_player_id text, in_story_node_ids text[])` | Delete for player | +| `delete_journey_story_nodes_for_player_account(in_account_id bigint, in_story_node_ids text[])` | Delete for account | +| `get_all_tutorial_entries(in_player_id bigint)` | Get tutorials | +| `get_login_journey_nodes(in_account_id bigint)` | Get login nodes | +| `get_login_journey_nodes_cooldown(in_account_id bigint)` | Get cooldown | +| `journey_story_node_cooldown_add(in_account_id bigint, in_story_node_id text, in_time_to_expire timestamp)` | Add cooldown | +| `journey_story_node_cooldown_delete_expired(in_time_to_check timestamp)` | Delete expired | +| `load_actors(in_actor_ids bigint[], in_actor_state dune.actorstate)` | Load actors | +| `reset_journey_story_nodes_for_player(in_player_id text, in_story_node_ids text[])` | Reset nodes | +| `reveal_journey_story_nodes_for_player(in_player_id text, in_story_node_ids text[])` | Reveal nodes | +| `save_journey_story_node(in_account_id bigint, in_story_node_id text, ...)` | Save node | +| `save_journey_story_nodes(in_account_id bigint, in_journey_data dune.savejourneydata[])` | Save nodes | +| `update_journey_story_ids(old_story_ids text[], new_story_ids text[])` | Update IDs | +| `get_character_import_state(in_fls_id text)` | Get import state | +| `get_unresolved_character_imports()` | Get unresolved imports | +| `set_character_import_state(in_fls_id text, in_state dune.transferimportstate)` | Set import state | +| `remove_character_transfer_state(in_fls_id text)` | Remove transfer state | +| `get_character_transfer_related_items(in_fls_id text)` | Get transfer items | + +### 2.8 Specialization & Skills (7 functions) + +| Function | Purpose | +|----------|---------| +| `get_learned_building_sets(in_account_id bigint)` | Get learned sets | +| `get_learned_new_buildable_pieces(in_account_id bigint)` | Get learned pieces | +| `initialize_specialization_keystones(in_keystones text[])` | Initialize keystones | +| `purchase_specialization_keystone(in_player_id bigint, in_keystone text)` | Purchase keystone | +| `reset_specialization_keystones(in_player_id bigint)` | Reset keystones | +| `reset_specialization_tracks(in_player_id bigint)` | Reset tracks | +| `set_specialization_xp_and_level(in_player_id bigint, in_track_type dune.specializationtracktype, in_xp_amount integer, in_level real)` | Set XP/level | +| `update_specialization_refund_id(in_player_id bigint, in_refund_id smallint, in_removed_keystones smallint[])` | Update refund | +| `get_player_specialization(in_player_controller_id bigint)` | Get specialization | +| `get_player_keystones(in_player_controller_id bigint)` | Get keystones | + +### 2.9 Landsraad & Politics (25 functions) + +| Function | Purpose | +|----------|---------| +| `landsraad_cast_vote(in_term_id bigint, in_player_id bigint, in_decree_name text)` | Cast vote | +| `landsraad_change_term_end_time(end_term_id bigint, new_end_time timestamp, in_test_term boolean)` | Change term end | +| `landsraad_check_task_completion()` | Check task completion | +| `landsraad_check_term_won()` | Check term won | +| `landsraad_collect_task_telemetry_for_faction(in_term_id bigint, in_faction_name text)` | Collect telemetry | +| `landsraad_collect_term_telemetry(in_term_id bigint, in_faction_names text[])` | Collect term telemetry | +| `landsraad_collect_term_telemetry_for_faction(in_term_id bigint, in_faction_name text)` | Collect for faction | +| `landsraad_collect_vote_telemetry(in_term_id bigint, in_winning_faction_id integer)` | Collect vote telemetry | +| `landsraad_collect_votes(in_term_id bigint)` | Collect votes | +| `landsraad_determine_winner(in_term_id bigint)` | Determine winner | +| `landsraad_force_end_term(end_term_id bigint)` | Force end term | +| `landsraad_has_term_of_task_ended(in_task_id bigint)` | Check task ended | +| `landsraad_initialize_system(...)` | Initialize system | +| `landsraad_initialize_term(...)` | Initialize term | +| `landsraad_insert_task_progress(in_term_id bigint, in_player_id bigint, ...)` | Insert progress | +| `landsraad_insert_task_progress_batched(in_term_id bigint, in_task_progress dune.landsraadtaskprogress[])` | Batch insert | +| `landsraad_insert_task_progress_faction(in_term_id bigint, in_faction_name text, ...)` | Insert faction progress | +| `landsraad_insert_task_progress_random(in_term_id bigint, in_faction_names text[], in_num_rows integer)` | Random progress | +| `landsraad_load_current_rotation(in_term_id bigint)` | Load rotation | +| `landsraad_load_current_term()` | Load current term | +| `landsraad_load_guild_contribution(in_term_id bigint, in_guild_id bigint, in_faction_id bigint)` | Load guild contribution | +| `landsraad_load_guild_contributions(in_term_id bigint, in_num_guilds integer, in_faction_names text[])` | Load contributions | +| `landsraad_load_guild_vote(in_term_id bigint, in_player_id bigint)` | Load guild vote | +| `landsraad_load_house_rewards(in_player_id bigint)` | Load house rewards | +| `landsraad_load_player_contributions(in_term_id bigint, in_player_ids bigint[])` | Load contributions | +| `landsraad_load_task_faction_progress(in_term_id bigint)` | Load task progress | +| `landsraad_load_task_faction_reveal_state(in_term_id bigint)` | Load reveal state | +| `landsraad_load_term_progress(in_term_id bigint, in_num_guilds integer, ...)` | Load term progress | +| `landsraad_notify_house_rewards_changed()` | Notify rewards | +| `landsraad_perform_daily_task_reveal(in_term_id bigint, in_faction_names text[], ...)` | Daily reveal | +| `landsraad_process_house_rewards()` | Process rewards | +| `landsraad_process_task_progress(max_rows integer)` | Process progress | +| `landsraad_task_has_been_completed(in_task_id bigint)` | Check completed | +| `landsraad_update_task_faction_reveal_state(in_term_id bigint, in_task_board_index integer, faction_name text, reveal_state boolean)` | Update reveal | +| `landsraad_withdraw_house_reward(in_player_id bigint, in_house_rewards dune.landsraadplayerhousereward[])` | Withdraw reward | +| `get_player_landsraad(in_player_controller_id bigint)` | Get Landsraad data | + +### 2.10 World & Partitions (30 functions) + +| Function | Purpose | +|----------|---------| +| `add_partition_unique(in_map text, in_definition jsonb, in_dimension bigint, in_label text)` | Add partition | +| `determine_partition_label(in_map text, in_dimension_index integer, in_label text, in_allow_overwrite boolean, in_partition_id bigint)` | Determine label | +| `determine_partition_label_trigger()` | Label trigger | +| `get_partition_presets()` | Get presets | +| `get_partitions(in_map text)` | Get partitions for map | +| `igwo_delete_world_partitions(in_partition_ids bigint[])` | Delete partitions | +| `igwo_get_partition_id_seq_last_value()` | Get sequence value | +| `igwo_get_partition_ids()` | Get partition IDs | +| `igwo_get_partitions()` | Get all partitions | +| `igwo_get_server_details()` | Get server details | +| `igwo_insert_world_partition(in_partition_id bigint, in_map text, in_partition_definition jsonb, ...)` | Insert partition | +| `igwo_next_partition_id_seq()` | Next sequence | +| `igwo_notify_world_partition_update()` | Notify update | +| `igwo_restart_partition_id_seq(in_restart_with bigint)` | Restart sequence | +| `igwo_update_world_partition(in_map text, in_partition_definition jsonb, in_partition_id bigint, ...)` | Update partition | +| `initialize_partitions_basic_battlegroup()` | Init basic BG | +| `initialize_partitions_basic_survival_1()` | Init survival | +| `initialize_partitions_development_battlegroup()` | Init development | +| `initialize_partitions_editor_default_1x1()` | Init editor | +| `initialize_partitions_full_battlegroup()` | Init full BG | +| `initialize_partitions_igw_test_small_2x1()` | Init test 2x1 | +| `initialize_partitions_igw_test_small_2x2()` | Init test 2x2 | +| `initialize_partitions_igw_training()` | Init training | +| `initialize_world_partition(in_map_name text, in_num_servers integer, in_dimension_index integer)` | Init partition | +| `load_dimension_index(in_map text, in_partition_id bigint)` | Load dimension | +| `load_partition_definition_map()` | Load definition map | +| `load_world_partition(in_map_name text, in_server_id text, in_desired_dimension_index bigint, in_desired_partition_id bigint)` | Load partition | +| `save_world_partition(in_map_name text, in_server_id text, in_dimension_index bigint, ...)` | Save partition | +| `unassign_partition(in_server_id text)` | Unassign partition | +| `update_partition_labels(in_allow_overwrite boolean)` | Update labels | +| `get_battlegroup_close_date()` | Get close date | +| `set_battlegroup_close_date(in_close_date timestamp)` | Set close date | + +### 2.11 Spice Fields & Coriolis (24 functions) + +| Function | Purpose | +|----------|---------| +| `corilis_cleanup_map(in_server_info dune.serverinfo, in_map_info dune.coriolismapinfo)` | Cleanup map | +| `coriolis_cleanup_farm(in_server_info dune.serverinfo, in_map_info dune.coriolismapinfo)` | Cleanup farm | +| `coriolis_cleanup_partition(in_server_info dune.serverinfo, in_map_info dune.coriolismapinfo)` | Cleanup partition | +| `coriolis_update_seed(in_server_info dune.serverinfo, in_new_coriolis_seed integer, in_map_info dune.coriolismapinfo)` | Update seed | +| `debug_set_farm_seed(in_new_coriolis_seed integer)` | Set farm seed | +| `debug_set_map_seed(in_map text, in_new_coriolis_seed integer)` | Set map seed | +| `debug_set_partition_seed(in_partition_id bigint, in_new_coriolis_seed integer)` | Set partition seed | +| `fetch_resourcefield_state(in_map text, in_dimension_index integer, in_field_kind_id smallint)` | Fetch field state | +| `fetch_server_spice_field_manifest(in_server_id text)` | Fetch spice manifest | +| `fetch_spicefie_id_types_with_global_info(in_map_name text, in_dimension_index integer)` | Fetch spice types | +| `get_farm_state()` | Get farm state | +| `get_stored_user_data_encryption_key_hash()` | Get encryption key | +| `get_stored_user_data_encryption_status()` | Get encryption status | +| `get_stored_user_data_encryption_taint_xmax()` | Get taint status | +| `produce_spicefield_manifest(in_map_name text, in_dimension_index integer)` | Produce manifest | +| `record_deactivated_spice_field(in_server_id text, in_spicefield_type_id integer)` | Record deactivated | +| `record_static_shifting_sand(in_id text, in_alpha double precision, ...)` | Record shifting sand | +| `record_unreadied_spice_fields(in_server_id text, in_spicefield_type_id integer, in_num_unreadied integer)` | Record unreadied | +| `request_spawn_spice_field(in_server_id text, in_spicefield_type_id integer)` | Request spawn | +| `reset_global_spice_field_state(in_map_name text, in_dimension_index integer)` | Reset state | +| `retrieve_all_static_shifting_sand()` | Retrieve all sand | +| `try_prime_spicefield(in_source_server_id text, in_spicefield_id integer)` | Try prime | +| `try_restart_spicefield(in_server_id text, in_spicefield_type_id integer)` | Try restart | +| `try_spawn_spicefield(in_source_server_id text, in_spicefield_id integer)` | Try spawn | +| `try_update_exchange_categories_hash(in_new_hash integer)` | Update hash | +| `update_global_spice_field_rules(in_max_globally_primed integer, in_max_globally_active integer, in_spicefield_type_id integer)` | Update rules | +| `update_spice_field_spawn_state(in_is_spawning_active boolean, in_spicefield_type_id integer)` | Update spawn state | +| `upsert_spicefield_types(in_max_globally_active integer[], ...)` | Upsert types | + +### 2.12 Chat & Communication (18 functions) + +| Function | Purpose | +|----------|---------| +| `add_event_log_data(in_game_event_owner bigint, in_universe_time bigint, ...)` | Add event log | +| `add_event_log_data_batched(in_data dune.eventlogbulkentrydata[])` | Batch add events | +| `add_map_areas_surveyed_items(in_account_id bigint, in_area_id smallint, ...)` | Add surveyed items | +| `add_map_areas_time_discovered(in_account_id bigint, in_area_id smallint, ...)` | Add discovered time | +| `add_map_areas_time_first_entered(in_account_id bigint, in_area_id smallint, ...)` | Add first entered | +| `clean_expired_party_invites(in_invite_expire_seconds integer)` | Clean expired invites | +| `create_event_log_partition()` | Create log partition | +| `delete_all_static_shifting_sand()` | Delete all sand | +| `get_all_player_travel_states()` | Get travel states | +| `get_online_player_controller_ids(in_map text)` | Get online on map | +| `get_online_player_controller_ids_on_farm()` | Get online on farm | +| `get_player_online_state_within_grace_period_for_each_server()` | Get grace period | +| `load_events_log_data_from_player(in_actor_id bigint, in_limit_entries_num integer)` | Load player events | +| `log_cheating(in_fls_id text, in_cheat_type dune.cheat_type_enum, in_event_time timestamp)` | Log cheating | +| `log_event_solaris(in_function_oid oid, in_message dune.logmessagetype, ...)` | Log Solari event | +| `set_all_inactive_players_in_farm_offline()` | Set inactive offline | +| `set_players_from_server_ids_offline(in_server_ids text[])` | Set servers offline | +| `wipe_old_events_log(in_days_limit integer)` | Wipe old logs | +| `get_active_servers_for_gateway()` | Get active servers | + +### 2.13 Account & Authentication (25 functions) + +| Function | Purpose | +|----------|---------| +| `can_takeover_account(in_user_id text)` | Check takeover | +| `cleanup_account_log_and_orphaned_actors()` | Cleanup orphans | +| `cleanup_accounts_marked_for_deletion_in_fls(in_account_ids text[])` | Cleanup FLS deletes | +| `decrypt_user_data(in_encrypted_data bytea)` | Decrypt data | +| `delete_account(in_user_id text, in_reason text)` | Delete account | +| `dune_get_account_id_by_user(in_user text)` | Get account by user | +| `encrypt_user_data(in_data text)` | Encrypt data | +| `get_account_actor_ids(in_account_id bigint)` | Get account actors | +| `get_controller_id_from_platform_id(in_platform_id text)` | Get controller ID | +| `get_encrypted_account(...)` | Get encrypted account | +| `get_friends_search(in_player_name text, in_max_players_count integer)` | Search friends | +| `get_player_infos_for_character_names(in_character_names text[])` | Get by character name | +| `get_player_infos_for_fls_ids(in_fls_ids text[])` | Get by FLS ID | +| `get_player_infos_for_funcom_ids(in_funcom_ids text[])` | Get by Funcom ID | +| `get_player_pawn(in_account_id bigint)` | Get player pawn | +| `get_takeoverable_user_ids()` | Get takeoverable IDs | +| `load_takeoverable_user_ids()` | Load takeoverable | +| `login_account(in_user_id text, in_funcom_id text, ...)` | Login account | +| `perform_notify_on_character_delete(in_user_id text)` | Notify on delete | +| `set_account_as_takeoverable(in_user_id text, in_new_user_id text)` | Set takeoverable | +| `takeover_account(in_user_to_takeover text, in_current_user text)` | Takeover account | +| `update_returning_player_status(in_user_id text, in_minimum_returning_player_time_seconds integer)` | Update returning | +| `get_demo_state(in_user_id text)` | Get demo state | +| `set_demo_state(in_user_id text, in_demo_state dune.demostate)` | Set demo state | +| `save_demo_account_time(in_fls_id text, in_demo_playtime_seconds integer)` | Save demo time | + +### 2.14 Markers & Map Data (20 functions) + +| Function | Purpose | +|----------|---------| +| `create_sinkchart_for_map_area_id(in_item_id bigint, in_creator_id bigint, ...)` | Create sinkchart | +| `delete_map_markers(in_dimension_index integer, in_map_name text, in_player_marker_data dune.deleteplayermarkerdata[])` | Delete markers | +| `delete_markers_by_id(in_marker_ids integer[])` | Delete by ID | +| `delete_markers_by_static_location_key(p_location_key text)` | Delete by location | +| `delete_markers_for_all_players(in_marker_types_to_keep text[], in_map text)` | Delete for all | +| `delete_markers_return_actor_ids(in_dimension_index integer, in_map_name text, in_marker_ids integer[])` | Delete and return | +| `delete_static_location_markers(p_location_keys text[])` | Delete static | +| `load_markers(in_player_id bigint, in_dimension_id integer, in_map_name text)` | Load markers | +| `load_map_areas_entries(in_account_id bigint, in_map_name text)` | Load map areas | +| `save_markers(in_player_marker_data dune.saveplayermarkerdata[], in_marker_data dune.savemarkerdata[])` | Save markers | +| `update_marker_ids(in_old_ids integer[], in_new_ids integer[])` | Update marker IDs | +| `use_sinkchart(in_player_id bigint, in_account_id bigint, in_area_id smallint, ...)` | Use sinkchart | +| `clear_map_areas_data_for_player(in_id bigint)` | Clear map data | +| `get_map_areas_entries(in_account_id bigint, in_map_name text)` | Get map areas | +| `load_static_encounter_name(in_map_name text, in_package_name text, in_actor_name text)` | Load encounter | +| `save_static_encounter_name(in_map_name text, in_package_name text, in_actor_name text, in_encounter_name text)` | Save encounter | +| `save_static_encounter_waiting_for_reset(in_map_name text, in_package_name text, in_actor_name text, in_waiting_for_reset boolean)` | Save waiting reset | +| `upgrade_location_data_list(in_location_data_list jsonb, in_map_field_name text)` | Upgrade location | +| `upgrade_map_name(in_map_name text)` | Upgrade map name | +| `upgrade_map_value(in_value jsonb)` | Upgrade map value | +| `downgrade_map_name(in_map_name text)` | Downgrade map name | + +### 2.15 Permissions & Ownership (16 functions) + +| Function | Purpose | +|----------|---------| +| `get_permission_actors_for_server(in_server_info dune.serverinfo)` | Get server permissions | +| `get_permission_for_actor(in_actor_id bigint)` | Get actor permission | +| `get_permission_for_actors(in_actor_id bigint[])` | Get actors permissions | +| `get_permission_for_player_actors(in_player_id bigint, in_min_rank smallint)` | Get player permissions | +| `ownership_handle_actor_delete(in_player_id bigint)` | Handle ownership delete | +| `permission_actor_create_or_update_base_marker(in_actor_id bigint, in_player_id bigint, in_rank smallint)` | Create marker | +| `permission_actor_destroy(in_actor_id bigint)` | Destroy permission | +| `permission_actor_register(in_entry dune.actorpermissionentry, in_owner_rank dune.actorpermissionrankdata)` | Register permission | +| `permission_actor_takeover(in_entry dune.actorpermissionentry, in_owner_rank dune.actorpermissionrankdata)` | Takeover permission | +| `permission_actor_update_marker_location(in_actor_id bigint, in_location_x real, in_location_y real, in_location_z real)` | Update location | +| `permission_remove_player_rank(in_actor_id bigint, in_player_id bigint)` | Remove rank | +| `permission_set_access_level(in_actor_id bigint, in_access_level smallint)` | Set access level | +| `permission_set_name(in_actor_id bigint, in_name text)` | Set name | +| `permission_set_player_rank(in_actor_id bigint, in_player_id bigint, in_rank smallint, in_map_id text)` | Set player rank | +| `gather_ownerless_actors_on_server(in_server_info dune.serverinfo)` | Gather ownerless | +| `gather_player_linked_actors(in_player_pawn_id bigint)` | Gather linked actors | +| `gather_removed_accounts_that_left_orphaned_actors_on_server(in_server_info dune.serverinfo)` | Gather orphans | +| `cleanup_orphaned_entities()` | Cleanup orphans | + +### 2.16 Travel & Movement (17 functions) + +| Function | Purpose | +|----------|---------| +| `get_traveling_actor_id_and_types(in_actor_id bigint)` | Get traveling actor | +| `get_traveling_actor_ids(in_actor_id bigint, in_max_recursion_level integer)` | Get traveling IDs | +| `get_traveling_actors_fls_ids(in_actor_id bigint)` | Get traveling FLS IDs | +| `get_traveling_non_player_actor_ids(in_actor_id bigint)` | Get non-player IDs | +| `load_travel_return_info(in_player_controller_id bigint)` | Load return info | +| `load_travel_to_player_info(in_player_controller_id bigint)` | Load travel info | +| `remove_aborted_authority_transfer_actors(in_partition_id bigint)` | Remove aborted | +| `save_aborted_authority_transfer_actors(in_actor_ids bigint[], in_partition_id bigint)` | Save aborted | +| `save_actor_dislocation(in_actor_id bigint, in_current_server_info dune.serverinfo, in_target_location vector, in_target_dimension_index integer)` | Save dislocation | +| `save_travel_return_info(in_player_controller_id bigint, in_map text, in_transform dune.transform)` | Save return info | +| `update_traveling_actor_dependencies(in_dep dune.traveldependency[])` | Update dependencies | +| `update_traveling_actor_tree(in_actor_id bigint, in_target_transform dune.transform, ...)` | Update actor tree | +| `get_actors_location_data_with_permission(in_actor_ids bigint[])` | Get location data | +| `get_actor_server_info(in_id bigint)` | Get server info | +| `server_info_match(in_actor dune.actors, in_server_info dune.serverinfo)` | Match server info | +| `delete_actors_and_respawns_on_server(in_server_info dune.serverinfo, ...)` | Delete on server | +| `mark_server_dead(in_server_id text)` | Mark server dead | + +### 2.17 Utility & Helper Functions (30+ functions) + +| Function | Purpose | +|----------|---------| +| `assign_actor_id(in_class text)` | Assign actor ID | +| `add_actor_audit(in_id bigint, in_class text)` | Add actor audit | +| `delete_actors(in_ids bigint[])` | Delete actors | +| `delete_actor_states_travel(in_actor_id bigint)` | Delete travel state | +| `delete_all_dungeon_completions(in_dungeon_id text)` | Delete completions | +| `delete_all_dungeon_completions_by_player(in_dungeon_id text, in_player_id bigint, ...)` | Delete by player | +| `delete_all_dungeon_completions_for_all_dungeons_by_player(in_player_id bigint, ...)` | Delete all dungeons | +| `delete_dialogue_data(in_player_controller_id bigint)` | Delete dialogue | +| `delete_world_partition_by_map_id(in_map_id text)` | Delete partition | +| `find_actor_by_id(in_id bigint)` | Find actor | +| `fix_broken_harkonnen_players_due_to_fooled_thufir()` | Fix Harkonnen bug | +| `get_actor_server_info(in_id bigint)` | Get actor server | +| `get_all_player_character_home_dimensions()` | Get home dimensions | +| `get_best_dungeon_completion(in_dungeon_id text)` | Get best completion | +| `get_best_dungeons_completions_for_player(in_player_id bigint)` | Get best dungeons | +| `get_dungeon_completion(in_dungeon_id text, in_player_id bigint)` | Get completion | +| `get_partition_id_for_server(in_server_id text)` | Get partition ID | +| `get_player_partition_id(in_fls_id text)` | Get player partition | +| `get_registered_spawned_actor(in_spawner_id bigint)` | Get spawned actor | +| `get_respawn_locations(in_account_id bigint)` | Get respawn locations | +| `get_universe_time()` | Get universe time | +| `get_vehicle_id(in_actor_id bigint, in_class text)` | Get vehicle ID | +| `load_full_actors(in_ids bigint[])` | Load full actors | +| `record_dungeon_completion(in_dungeon_id text, in_difficulty integer, in_duration_ms integer, players_ids bigint[])` | Record completion | +| `register_spawned_actor(in_spawner_id bigint, in_actor_id bigint)` | Register spawned | +| `reset_all_players_from_server_ids_grace_period_and_logoff_timer(in_server_id text, in_reset_time timestamp)` | Reset grace period | +| `save_actors(in_server_info dune.serverinfo, in_actors dune.actordescription[], in_actor_state dune.actorstate)` | Save actors | +| `save_player(in_player dune.playerdescription)` | Save player | +| `save_player_pawn(in_pawn dune.actordescription, in_server_info dune.serverinfo, in_life_state dune.playerlifestate)` | Save pawn | +| `update_farm_state(in_server_id text, in_outgoing_s2s_connections integer, ...)` | Update farm state | +| `update_server_building_favorites(in_account_id bigint, in_building_types text[])` | Update favorites | +| `update_server_learned_building_sets(in_account_id bigint, in_learned_building_sets text[])` | Update learned sets | +| `update_server_learned_new_buildable_pieces(in_account_id bigint, in_new_buildable_pieces text[])` | Update learned pieces | +| `update_universe_time(in_farm_id text)` | Update universe time | +| `zero_transform()` | Zero transform | +| `get_applied_patches()` | Get applied patches | +| `get_universe_time()` | Get universe time | + +--- + +## 3. RabbitMQ Exchanges & Queues + +### 3.1 Game Exchanges (mq-game at port 32716) + +| Exchange | Type | Purpose | +|----------|------|---------| +| `heartbeats` | direct | In-game broadcasts and notifications | +| `rpc` | direct | Server RPC calls (currently no bindings) | +| `notifications` | topic | General notifications | +| `chat.faction.1-4` | fanout | Faction chat channels (4 factions) | +| `chat.guild.*` | fanout | Guild chat channels | +| `chat.intercept` | topic | Chat intercept/filtering | +| `chat.proximity` | direct | Proximity-based chat | +| `chat.whispers` | direct | Private whispers | +| `chat.map` | direct | Map-wide chat | +| `login_grant` | direct | Login grant messages | +| `login_request` | direct | Login requests | +| `login_response` | direct | Login responses | +| `status.*` | fanout | Per-map status (Overmap, Survival_1, DeepDesert_1, etc.) | +| `travel_queue_status` | topic | Travel queue updates | +| `director_respawned` | fanout | Respawn events from director | + +### 3.2 Admin Exchanges (mq-admin at port 30325) + +| Exchange | Type | Messages Published | Purpose | +|----------|------|-------------------|---------| +| `completions` | direct | 723 | Completion events | +| `response` | direct | 64K+ | Response routing | +| `settingsUpdate` | fanout | 71 | Server settings updates | +| `travel` | topic | - | Travel messages | +| `travelQueueStatus` | fanout | 1K+ | Travel queue status | +| `grant` | direct | - | Grant messages | +| `heartbeats` | direct | 2K+ | Heartbeat messages | +| `rpc` | direct | - | RPC messages | +| `director_respawned` | fanout | - | Respawn events | + +### 3.3 Game Queues + +| Queue | Consumers | Purpose | +|-------|-----------|---------| +| `B17A5F036D1F7882_queue` | - | Host-specific queue | +| `bgdRpc` | 1 | BGD RPC responses | +| `loginRequests` | 1 | Login request queue | +| `queue.intercept` | 1 | Chat intercept queue | +| `queue.server.*` (5 queues) | 1 each | Per-server queues | + +--- + +## 4. BGD Director API Endpoints + +### 4.1 Player Endpoints + +| Endpoint | Method | Response | Purpose | +|----------|--------|----------|---------| +| `/v0/players` | GET | `["FLS_ID"]` | List all player FLS IDs | +| `/v0/players/online` | GET | `["FLS_ID"]` | List online players | +| `/v0/players/intransit` | GET | `[]` | Players in transit | +| `/v0/players/graceperiod` | GET | `[]` | Players in grace period | +| `/v0/players/completion` | GET | `[]` | Completion queue | +| `/v0/players/queued` | GET | `[]` | Queued players | + +### 4.2 Battlegroup Endpoints + +| Endpoint | Method | Response | Purpose | +|----------|--------|----------|---------| +| `/v0/battlegroup` | GET | Full JSON | Complete battlegroup state (maps, servers, players, configs) | +| `/` | GET | HTML | Web dashboard UI | + +### 4.3 FLS Settings Endpoints + +| Endpoint | Method | Purpose | +|----------|--------|---------| +| `/v0/BattlegroupFetchFlsReportSettings` | GET | Fetch FLS report settings | +| `/v0/BattlegroupUpdateFlsReportSettings` | POST | Update FLS report settings | +| `/v0/BattlegroupClearFlsReportOverrides` | POST | Clear FLS overrides | + +### 4.4 Battlegroup JSON Structure + +The `/v0/battlegroup` endpoint returns: +- `dimensionMaps[]` — Multi-server maps with partitions +- `singleServerMaps[]` — Single-server maps +- `instancedMaps[]` — Instanced content (dungeons, gyms, etc.) +- Per-server data: `partition`, `ip`, `gamePort`, `numPlayers*`, `status`, `cfg`, `lastServerState` +- `serverGameplaySettings`: hydration, sandstorm, sandworm, PvP, security zones, mining multiplier, durability + +### 4.5 Map Types Managed by BGD + +- **Survival** — Survival mode maps +- **Story** — Story mission maps +- **Challenge Rooms** — Combat challenges +- **CB (Combat Block)** — PvP combat zones +- **DLC Content** — DLC-specific maps +- **Test Gyms** — Testing/training areas +- **Overmap** — Main overworld +- **Deep Desert** — Endgame PvP zone +- **Arrakeen** — City zone +- **Harko Village** — NPC village + +--- + +## 5. Kubernetes Resources + +### 5.1 World Namespace Pods + +| Pod Pattern | Purpose | +|-------------|---------| +| `{world}-mq-admin-sts-0` | RabbitMQ admin instance | +| `{world}-mq-game-sts-0` | RabbitMQ game instance | +| `{world}-tr-deploy-*` | Text Router (RMQ auth) | +| `{world}-bgd-deploy-*` | Battlegroup Director | +| `{world}-sgw-deploy-*` | Server Gateway | +| `{world}-db-dbdepl-*` | PostgreSQL database | +| `{world}-fb-deploy-*` | File Browser | +| `{world}-sg-overmap-pod-*` | Overmap game server | +| `{world}-sg-survival-1-pod-*` | Survival game server | +| `{world}-sg-deepdesert-1-pod-*` | Deep Desert server | +| `{world}-sg-arrakeen-pod-*` | Arrakeen server | +| `{world}-sg-harkovillage-pod-*` | Harko Village server | + +### 5.2 Operator Deployments (funcom-operators namespace) + +| Deployment | Purpose | +|------------|---------| +| `battlegroupoperator-controller-manager` | Manages BattleGroup CRDs | +| `databaseoperator-controller-manager` | Manages database lifecycle | +| `serveroperator-controller-manager` | Manages ServerGroup CRDs | +| `utilitiesoperator-controller-manager` | Manages utility services | + +### 5.3 Services (NodePort) + +| Service | NodePort | Purpose | +|---------|----------|---------| +| `bgd-svc` | 30553 | BGD Director API | +| `mq-admin-svc` | 30325 | RMQ Admin Management UI | +| `mq-admin-svc` | 32729 | RMQ Admin AMQP (TLS) | +| `mq-game-svc` | 32716 | RMQ Game Management UI | +| `mq-game-svc` | 31982 | RMQ Game AMQP (TLS) | + +--- + +## 6. Game Tables Reference + +### 6.1 Core Tables + +| Table | Rows | Purpose | +|-------|------|---------| +| `encrypted_accounts` | 10 | Encrypted account data | +| `encrypted_player_state` | 10 | Encrypted player state | +| `actors` | 411 | All game entities (players, NPCs, vehicles, buildings) | +| `items` | 1,482 | Inventory items | +| `inventories` | 459 | Inventory containers | +| `buildings` | 8 | Player buildings | +| `vehicles` | 16 | Player vehicles | +| `guilds` | 1 | Guilds | +| `factions` | 4 | Factions (Atreides, Harkonnen, Fremen, Corrino) | +| `bans` | 0 | Banned players | +| `game_events` | 76 | Game event log | + +### 6.2 Configuration Tables + +| Table | Rows | Purpose | +|-------|------|---------| +| `world_partition` | 30 | Server partition configuration | +| `dune_exchanges` | 1 | Exchange configuration | +| `landsraad_decrees` | 11 | Landsraad decrees | +| `landsraad_tasks` | 25 | Landsraad tasks | + +### 6.3 Dashboard Tables + +| Table | Purpose | +|-------|---------| +| `dashboard.bans` | Ban records with duration/reason | +| `dashboard.player_actions` | Admin action audit log | +| `dashboard.player_ips` | Player IP address tracking | +| `dashboard.chat_history` | Chat message archive | + +--- + +## Appendix: Common Admin Workflows + +### A.1 Ban a Player +1. Search for player by name +2. Get player_controller_id +3. Call `POST /api/ban_player` with duration and reason +4. Optionally detect player IP and apply iptables block + +### A.2 Teleport a Player +1. Ensure player is offline (check online status) +2. Get partition ID from `GET /api/admin-experimental/partitions` +3. Call `POST /api/admin-experimental/teleport` with FLS ID, partition ID, coordinates + +### A.3 Send In-Game Broadcast +1. Go to Admin Experimental tab +2. Enter title, message, duration +3. Click "Send Broadcast" +4. Message appears for all connected players + +### A.4 Fix a Stuck Player +1. Search for player +2. Check online status +3. If stuck: set offline via `set_players_from_server_ids_offline` +4. Teleport to safe location +5. Reset vitals if needed + +### A.5 Investigate Cheating +1. Search for player +2. View player stats (check for impossible values) +3. View inventory (check for duped items) +4. If confirmed: `flag_player_as_cheater` +5. Ban player and block IP + +--- + +**End of Reference** diff --git a/AI_DUNE_AWAKENING_SYSTEM_CONTEXT.md b/AI_DUNE_AWAKENING_SYSTEM_CONTEXT.md new file mode 100644 index 0000000..86eb833 --- /dev/null +++ b/AI_DUNE_AWAKENING_SYSTEM_CONTEXT.md @@ -0,0 +1,1224 @@ +# Dune Awakening — Full System Context for AI Continuation + +> **Last updated:** 2026-05-22 (production VPS at 65.21.198.100, cluster fully running) +> **VM Hostname:** `duneawakening` (Alpine Linux 3.23.4, K3s single-node) +> **Server IP:** `65.21.198.100` +> **Dashboard repo:** `C:\Users\Reditus\OneDrive\Documents\GitHub\dune-dashboard-private` +> **This doc path:** `C:\Users\Reditus\Downloads\DUNE_AWAKENING_SYSTEM_CONTEXT.md` +> **⚠️ SECURITY: NEVER commit this doc or any credentials to GitHub.** + +--- + +## ⚠️ YOUR MISSION (read this first) + +You are continuing work on a **Dune Awakening private game server**. Your job is to help access and configure admin settings on the game server. Everything you need is in this document. + +### What to do +1. **Read this entire document** — it contains the full architecture, credentials, connection methods, and what's been tried. +2. **Connect to the VM** via SSH (see section 1), run kubectl commands, explore the cluster. +3. **Continue from section 12** ("What's Still Unknown / Next Steps") — that's the active work queue. +4. **Update this document** with any new findings, credentials discovered, or progress made. +5. **Ask the user** only when you genuinely need a decision or something is blocked. Otherwise, just do it. + +### How to work +- All kubectl commands need `sudo` on the VM. +- PowerShell has tricky quoting — use script files piped via SSH for complex commands (`tr -d '\r'` to strip CRLF). +- The SSH tunnel for the dashboard (localhost:15433 → DB, localhost:32479 → BGD) may need restarting if down. +- When you find new credentials or endpoints, **add them to this document immediately**. +- **NEVER commit or push to GitHub.** The doc lives in Downloads for a reason. + +### Current priorities +- ✅ **DONE:** DB schema migration succeeded — cluster is fully running. See finding #19. +- ✅ **DONE:** RMQ Management UI accessible with `admin:admin123`. See finding #20. +- ✅ **DONE:** `send-dune-broadcast` tested and working on live server. See finding #21. +- **High:** Add custom broadcast title/identity (e.g., "Dune Admin" instead of hardcoded FLS backend) +- **Medium:** Integrate broadcast functionality into the dashboard admin panel. +- **Medium:** Scale operators back up (currently scaled to 0). + +--- + +## 1. HOW TO CONNECT + +### SSH to VM +```powershell +ssh -i "$env:LOCALAPPDATA\DuneAwakeningServer\sshKey" -o StrictHostKeyChecking=accept-new dune@65.21.198.100 +``` +**Note:** Production VPS at `65.21.198.100`. Hostname: `duneawakening`, Alpine Linux 3.23.4, K3s single-node. No longer a local Hyper-V VM. + +**Installed tools on VM (2026-05-22):** `curl`, `python3`, `py3-pip` (via `apk add`) + +**⚠️ SCP does not work on this VM** (no `sftp-server`). Use pipe method instead: +```powershell +Get-Content -Raw script.sh | ssh -i "" dune@65.21.198.100 "cat > /tmp/script.sh && tr -d '\r' < /tmp/script.sh > /tmp/script_clean.sh && mv /tmp/script_clean.sh /tmp/script.sh && chmod +x /tmp/script.sh && bash /tmp/script.sh" +``` + +### SSH Tunnel (maintained by dashboard launcher, PID 31172) +| Local Port | Forwards To | Purpose | +|-----------|-------------|---------| +| `localhost:15433` | VM:DB cluster IP (15432) | PostgreSQL | +| `localhost:32479` | VM:BGD NodePort 31403 | BGD Director API | + +### Kubectl on VM +```bash +# All commands need sudo +sudo kubectl get pods -A +sudo kubectl get svc -A +sudo kubectl get secrets -A +sudo kubectl logs -n +sudo kubectl exec -n -- +``` + +### BGD Web UI +- `http://192.168.0.101:31403/` — web dashboard with player stats +- `http://10.43.173.27:11717/` — via cluster IP (from inside VM) + +--- + +## 2. ARCHITECTURE OVERVIEW + +``` +Windows Host Hyper-V VM (192.168.0.101 / dune-awakening) +┌────────────────────┐ ┌─────────────────────────────────────────────┐ +│ Dashboard │ │ K3s Cluster (single node) │ +│ (Flask/SocketIO) │ ───SSH─────→ │ │ +│ Port 5050 │ tunnel │ ┌──────────────────────────────────────┐ │ +│ │ │ │ funcom-seabass-{WORLD_ID}-whxlri │ │ +│ RabbitMQ UI: │ │ │ │ │ +│ 192.168.0.101: │ │ │ mq-admin-sts (RabbitMQ admin) │ │ +│ 32253 (admin) │ │ │ mq-game-sts (RabbitMQ game) │ │ +│ 31745 (game) │ │ │ tr-deploy (Text Router / Auth) │ │ +│ │ │ │ bgd-deploy (Battlegroup Director) │ │ +│ │ │ │ sgw-deploy (Server Gateway) │ │ +│ │ │ │ db-dbdepl (PostgreSQL) │ │ +│ │ │ │ sg-overmap (Overmap game server) │ │ +│ │ │ │ sg-survival-1 (Pending - unsched) │ │ +│ │ │ │ fb-deploy (File Browser) │ │ +│ │ │ │ │ │ +│ │ │ │ funcom-operators namespace: │ │ +│ │ │ │ battlegroupoperator │ │ +│ │ │ │ databaseoperator │ │ +│ │ │ │ serveroperator │ │ +│ │ │ │ utilitiesoperator │ │ +│ │ │ └──────────────────────────────────────┘ │ +│ │ │ │ +│ │ │ VM Scripts: /home/dune/.dune/download/ │ +│ │ │ scripts/{battlegroup.sh, bg-util, ...} │ +│ │ │ images/battlegroup/*.tar (Docker images) │ +│ │ └─────────────────────────────────────────────┘ +``` + +--- + +## 3. ALL EXPOSED SERVICES (NodePort on 65.21.198.100) + +| Service | Type | ClusterIP | NodePort | Internal Ports | Purpose | +|---------|------|-----------|----------|---------------|---------| +| bgd-svc | NodePort | 10.43.92.250 | **30553** | 11717 | BGD Director web UI + API | +| mq-admin-svc | NodePort | 10.43.78.227 | **30325** | 15672 (HTTP) | RMQ Admin Management UI ✅ | +| mq-admin-svc | NodePort | 10.43.78.227 | **32729** | 5672 (AMQP) | RMQ Admin AMQP (TLS) | +| mq-game-svc | NodePort | 10.43.79.0 | **32716** | 15672 (HTTP) | RMQ Game Management UI ✅ | +| mq-game-svc | NodePort | 10.43.79.0 | **31982** | 5672 (AMQP) | RMQ Game AMQP (TLS) | +| db-dbdepl-svc | ClusterIP | 10.43.14.243 | - | 15432 | PostgreSQL | +| tr-svc | ClusterIP | 10.43.40.75 | - | 5059 | Text Router (RMQ auth) | + +**Note:** NodePorts are dynamically assigned and change on each install. Always check with `sudo kubectl get svc -n `. + +**Current (2026-05-22 production):** RMQ Admin UI at `http://65.21.198.100:30325`, RMQ Game UI at `http://65.21.198.100:32716`. Both accessible from outside the server. + +--- + +## 4. CREDENTIALS FOUND + +### RMQ HTTP Token Auth Secret (SIGNING KEY — NOT a password) +``` +gZQbpwOA6ow190HgLKDfxy9zZoRWejTJ1Trp+fnMQkNapY7TEdQ6RIXbLUVAlpPtbaz9pGLW8M8LWnjOfsCTKQ== +``` +- Base64-decoded: 64 bytes +- Used by: TR (Text Router) service to validate RMQ authentication tokens +- Stored in: `rmq-game-secret` Kubernetes secret +- Also present as env var in: BGD pod, SGW pod, TR pod, mq-admin pod, mq-game pod + +### FuncomLiveServices Service Auth Token (JWT) +``` +eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJIb3N0SWQiOiJCMTdBNUYwMzZEMUY3ODgyIiwiVG9rZW5JbmRleCI6IjEiLCJTZXJ2aWNlQXV0aEtleSI6IjI4RVVGOFMyM2dnQXdNWjQwUjRCQUZ1TTVFbkswM3RHeDZLY1h3Q0Vkc3FEcmVoUExxWFhGS0ZNcUIyYlNCUmYiLCJTZXJ2aWNlSG9zdFR5cGUiOiIyIiwibmJmIjoxNzc5MzE4MjQ1LCJleHAiOjE4MTA4NTQyNDUsImlhdCI6MTc3OTMxODI0NX0.yNenOJVmshIg1OcTEt0UeEmdUBnTQn2Gov098znvHMg +``` +**Decoded payload:** +```json +{ + "HostId": "B17A5F036D1F7882", + "TokenIndex": "1", + "ServiceAuthKey": "28EUGFS2M23ggAWMjQ0jR4BAFuM5VEbKsM3tGd6KYXh7CFKcsDqchPLxxXFGKFNqB2bNCBRf", + "ServiceHostType": "2", + "nbf": 1779318245, + "exp": 1810854245, + "iat": 1779318245 +} +``` +- Used by: BGD, SGW, TR for service-to-service authentication +- Expires: 2027-05-15 + +### Database Password +- **User:** `dune` +- **Password:** `qEJ1xJUedRJCv5qnAPJEnFnR` +- **Superuser:** `postgres` (no password needed from inside cluster) +- **Database:** `dune` +- **Schema:** `dune` (main game data), `ext` (extensions), `public` +- **Note:** Database is essentially empty (0 players, fresh install) + +### RabbitMQ Users (from RMQ logs — user format: `{service}.{world}.{token}.{role}`) +| User | Purpose | Pod | +|------|---------|-----| +| `sg.{WORLD}.wlP+pNNSRYeatInPivYEjw.admin` | Server Gateway admin | on mq-admin | +| `sg.{WORLD}.wlP+pNNSRYeatInPivYEjw.game` | Server Gateway game | on mq-game | +| `bgd.{WORLD}.Y_WL2MEd406KLEg5Lu+Bpw.admin` | BGD Director admin | on mq-admin | +| `bgd.{WORLD}.Y_WL2MEd406KLEg5Lu+Bpw.game` | BGD Director game | on mq-game | +| `tr.{POD}.iKkgMO91kEOlvCGqBwT3dg` | Text Router | on mq-game | + +### FLS API Key +- **Value:** `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` (masked/placeholder) +- Stored as `fls-apikey` in server-gateway-secret + +### RabbitMQ Management UI Credentials (RESOLVED 2026-05-22) +- **Username:** `admin` +- **Password:** `admin123` +- **Admin UI:** `http://65.21.198.100:30325` — ✅ Working +- **Game UI:** `http://65.21.198.100:32716` — ✅ Working +- **How it was done (new approach, 2026-05-22 production):** + 1. Scaled down all 4 operators to 0 replicas (prevents ConfigMap reconciliation) + 2. Modified `mq-admin-cm` and `mq-game-cm` ConfigMaps: changed `auth_backends.1 = $(RMQ_AUTH_BACKEND_1)` to `auth_backends.1 = internal` + `auth_backends.2 = $(RMQ_AUTH_BACKEND_1)` + 3. Restarted RMQ StatefulSet pods (they pick up new config) + 4. Created admin users on both mq-admin and mq-game via `rabbitmqctl add_user admin admin123` + 5. Set `administrator` tag and full permissions on both +- **Key difference from old approach:** Kept HTTP auth plugin enabled (needed for game services), just added `internal` as primary auth backend so the admin user is checked first. Game service tokens still authenticate via HTTP→TR fallback. +- **Note:** Admin users are LOST on pod restart (PV doesn't persist user data reliably). Must recreate via `rabbitmqctl` after each restart. + +--- + +## 5. RABBITMQ AUTHENTICATION ARCHITECTURE + +### How RMQ Auth Works +1. RabbitMQ is configured with `rabbitmq_auth_backend_http` + `rabbitmq_auth_backend_cache` +2. When a client connects via AMQP, RabbitMQ makes an HTTP POST to the TR service +3. **TR endpoint:** `POST /v0/auth/user` with `username` and `password` form params +4. TR validates the password as a structured/signed token using `RMQ_HTTP_TOKEN_AUTH_SECRET` +5. Returns `allow` or `deny` + +### TR Service Details +- **Pod:** `{WORLD}-tr-deploy` +- **Image:** `seabass-server-text-router` +- **Port:** 5059 +- **Type:** .NET 8 ASP.NET Core application (112MB binary at `/Tools/Battlegroups/TextRouter/TextRouter`) +- **Auth endpoints:** `/v0/auth/user` (GetUserAuth), `/v0/auth/vhost`, `/v0/auth/resource`, `/v0/auth/topic` +- **Config:** Minimal — `appsettings.json` only has Serilog settings + +### AMQP is TLS-only +Both mq-admin and mq-game are configured with: +``` +listeners.tcp = none +listeners.ssl.default = 5672 +``` +All AMQP connections use TLS. The Management UI (port 15672) is plain HTTP. + +### Token Format (from TR logs) +The TR extracts a "token" from the password and parses it as: +- **Created** (DateTime, 8 bytes) — was `01/01/0001` for invalid tokens +- **TTL** (duration) — was `00:00:00` for invalid tokens + +The token is validated using `RMQ_HTTP_TOKEN_AUTH_SECRET` as the HMAC signing key. +The 16-byte tokens in the usernames (`wlP+pNNSRYeatInPivYEjw` decoded) are too short and don't contain proper timestamp data. + +### Management UI Login +- URL: `http://192.168.0.101:32253` (admin) or `http://192.168.0.101:31745` (game) +- Uses HTTP Basic Auth +- **Status:** ✅ RESOLVED — Use `admin:admin123` (see section 4) +- The default HTTP auth backend (TR service) intercepts all login attempts. Internal RMQ users bypass this. + +--- + +## 6. BGD DIRECTOR API + +### Web UI +The BGD has a Bootstrap web UI at its root (`/`) with: +- Player count (total, online, in-transit, grace period) +- Links to API endpoints + +### API Endpoints Found +| Endpoint | Method | Response | +|----------|--------|----------| +| `/` | GET | HTML web UI | +| `/v0/players` | GET | `[]` (empty array) | +| `/v0/players/online` | GET | `[]` | +| `/v0/players/intransit` | GET | `[]` | +| `/v0/players/graceperiod` | GET | `[]` | +| Everything else | ANY | 404 Not Found | + +### BGD Pod +- **Args:** `--RMQGameHostname`, `--RMQGamePort`, `--RMQAdminHostname`, `--RMQAdminPort` +- **Env:** Has `FuncomLiveServices__ServiceAuthToken` (JWT) and `RMQ_HTTP_TOKEN_AUTH_SECRET` +- The BGD connects to both mq-admin and mq-game via AMQP internally + +--- + +## 6.5. SEND-DUNE-BROADCAST UTILITY (DISCOVERED 2026-05-22) + +### Location +- **File:** `F:\Downloads\send-dune-broadcast` +- **Type:** Bash script (177 lines) +- **Purpose:** Sends in-game broadcast notifications to all connected players via RabbitMQ + +### How It Works +The script publishes a message directly to the **`heartbeats` exchange** on the **mq-game** RabbitMQ instance using `rabbitmqctl eval` (Erlang code executed inside the RMQ pod). + +**Message structure:** +```erlang +Outer = #{ + <<"Version">> => 2, + <<"AuthToken">> => <<"Nu6VmPWUMvdPMeB7qErr">>, %% ⚠️ HARDCODED TOKEN + <<"MessageContent">> => Inner +} + +Inner = #{ + <<"ServerCommand">> => <<"ServiceBroadcast">>, + <<"BroadcastType">> => <<"Generic">>, + <<"BroadcastPayload">> => #{ + <<"BroadcastDuration">> => Duration, + <<"LocalizedText">> => [ + #{<<"Key">> => <<"en">>, <<"Title">> => Title, <<"Body">> => Body}, + #{<<"Key">> => <<"en-US">>, <<"Title">> => Title, <<"Body">> => Body} + ] + } +} +``` + +**Publishing details:** +- **Exchange:** `heartbeats` +- **Routing key:** `notifications` +- **App ID:** `fls` +- **User ID:** `fls_backend` +- **Message ID:** `manual-service-broadcast-{timestamp}` + +### Usage +```bash +send-dune-broadcast --title "Server Notice" --message "Maintenance in 10 minutes" --duration 60 +# or positional: +send-dune-broadcast "Server Notice" "Maintenance in 10 minutes" 60 +``` + +### Key Findings +1. **Hardcoded AuthToken:** `Nu6VmPWUMvdPMeB7qErr` — this is the FLS (Funcom Live Services) backend auth token used to authenticate broadcast messages +2. **Direct RMQ access:** Bypasses the TR auth entirely by executing Erlang code inside the RMQ pod via `rabbitmqctl eval` +3. **No AMQP connection needed:** Uses RMQ's internal APIs (`rabbit_exchange:lookup_or_die`, `rabbit_queue_type:publish_at_most_once`) +4. **Localized text:** Supports multiple locales (en, en-US) — could be extended +5. **BroadcastType:** Currently hardcoded as `Generic` — there may be other types + +### How to Run on Our Server +```bash +# Copy script to VM +scp -i "$env:LOCALAPPDATA\DuneAwakeningServer\sshKey" F:\Downloads\send-dune-broadcast dune@192.168.0.101:/home/dune/ + +# Make executable and run +ssh -i "$env:LOCALAPPDATA\DuneAwakeningServer\sshKey" dune@192.168.0.101 'chmod +x /home/dune/send-dune-broadcast && /home/dune/send-dune-broadcast --title "Test" --message "Hello from admin!" --duration 30' +``` + +### Potential Uses +- **Server announcements** (maintenance, events, restarts) +- **Emergency alerts** (crashes, rollbacks) +- **Welcome messages** for new players +- **Event notifications** (sandstorms, landsraad votes, etc.) +- **Integration with dashboard** — add a broadcast UI to the admin panel + +### Integration with Dashboard +The dashboard's `send_global_broadcast()` in `app/services/admin.py:668` currently only publishes to SocketIO (dashboard clients). This script shows how to reach **actual game clients** via RMQ. We can: +1. Port the Erlang logic to Python using `pika` or `aio-pika` +2. Or wrap this script and call it via SSH from the dashboard +3. Add a broadcast UI to the admin panel with title/message/duration fields + +### ⚠️ Important Notes +- The `heartbeats` exchange may not exist on our RMQ instance (it's created dynamically when the message is published) +- The AuthToken `Nu6VmPWUMvdPMeB7qErr` may need to match what the game clients expect +- This script requires `python3` on the VM for JSON escaping (already installed) +- The script uses `rabbitmqctl eval` which requires root/sudo access to the RMQ pod + +--- + +## 7. TEXT ROUTER (TR) POD DETAILS + +### Env Vars +``` +FuncomLiveServices__RmqTlsEnabled=true +FuncomLiveServices__ServiceAuthToken= +RMQ_HTTP_TOKEN_AUTH_SECRET= +Database_address={WORLD}-db-dbdepl-svc:15432 +Database_name=dune +Database_password=qEJ1xJUedRJCv5qnAPJEnFnR +Database_user=dune +``` + +### Args +``` +--RMQAdminHostname={WORLD}-mq-admin-svc --RMQAdminPort=5672 +--RMQGameHostname={WORLD}-mq-game-svc --RMQGamePort=5672 +``` +The TR itself connects to RabbitMQ. It uses the JWT (or signed tokens) to authenticate. + +--- + +## 8. DASHBOARD REPO CODE REFERENCES + +| File | Key Content | +|------|-------------| +| `app/services/director.py` | BGD Director integration | +| `app/services/k8s.py` | `get_rabbitmq_pod()` — finds `mq-admin`/`mq-game` | +| `app/services/admin.py:668` | `send_global_broadcast()` — "simulates the administrative `send-dune-broadcast` utility" | +| `app/routes/api.py` | Health checks (RabbitMQ pod status) | +| `app/utils/event_manager.py` | SocketIO event publishing | +| `launcher.ps1:81` | Redacts `RMQ_HTTP_TOKEN_AUTH_SECRET` from logs | +| `settings.yaml.example` | Config template with SSH, DB, K8s settings | + +**Note:** `send_global_broadcast()` is defined but NOT called by any route, websocket handler, or template — it's backend scaffolding. + +--- + +## 9. VM SCRIPTS + +| File | Location | Purpose | +|------|----------|---------| +| `setup.sh` | `/home/dune/.dune/download/scripts/` | Full setup orchestration | +| `battlegroup.sh` | Same dir | Battlegroup management CLI | +| `bg-util` | Same dir | 7MB Go binary (interactive, needs TTY) | +| `setup/helper.sh` | Same dir | Shared bash helpers | +| `setup/templates/world-template.yaml` | Same dir | Funcom CRD `BattleGroup` template | +| `setup/config/User*.ini` | Same dir | Default game user settings | + +### battlegroup.sh Commands +`list`, `status`, `start`, `restart`, `stop`, `edit`, `edit-advanced`, `update`, `update-from-downloads`, `backup`, `import`, `logs-export`, `operator-logs-export`, `apply-default-usersettings`, `enable-experimental-swap` + +### bg-util +- Interactive Go binary for editing battlegroup resources +- Requires a `world-template.yaml` path as argument +- Needs TTY (`error: could not open a new TTY` when run via SSH without `-t`) + +--- + +## 10. DATABASE SCHEMA + +### Schemas +- `dune` — Main game data (~160 tables) +- `ext` — Extensions +- `public` — Default schema +- `dashboard` — Dashboard's own tables (not yet created in this fresh install) + +### Notable Tables (all empty on fresh install) +- `accounts`, `actors`, `buildings`, `items`, `vehicles`, `player_state` +- `guilds`, `factions`, `parties` +- `landsraad_decrees`, `landsraad_tasks` (with data: 11 decrees, 25 tasks) +- `event_log*` (partitioned — empty) +- `world_partition` (30 rows — server config) +- `dune_exchanges` (1 row — exchange config) + +### Database Roles +| Role | Superuser | Login | +|------|-----------|-------| +| `dune` | No | Yes | +| `postgres` | Yes | Yes | + +--- + +## 11. INTERESTING LOG ENTRIES + +### RMQ mq-admin Errors +``` +operation basic.publish caused a channel exception not_found: +no exchange 'completions' in vhost '/' +``` +This occurs when the BGD or SGW tries to publish to a `completions` exchange that doesn't exist yet. Likely an initialization race condition or config issue. + +### TR Malformed Token +``` +Malformed token for user sg...wlP+pNNSRYeatInPivYEjw.game: + wlP+pNNSRYeatInPivYEjw: created: 01/01/0001 00:00:00, TTL: 00:00:00 +``` +Indicates the token in the username is NOT a valid signed credential. The SGW/BGD must be using something else as the actual password (probably the JWT). + +--- + +## 12. WHAT'S STILL UNKNOWN / NEXT STEPS + +### ✅ Completed +1. **DB Schema Migration Failure** — ✅ **RESOLVED** (happened automatically between installs or was unrelated to current cluster) +2. **RMQ Management UI credentials** — ✅ **RESOLVED** — `admin:admin123` working on both admin (30325) and game (32716) UIs +3. **`send-dune-broadcast`** — ✅ **TESTED AND WORKING** on live production server + +### Next Steps +1. **Scale operators back up** — Currently scaled to 0. They need to be restored: + - `for op in battlegroupoperator databaseoperator serveroperator utilitiesoperator; do sudo kubectl scale deployment -n funcom-operators $op-controller-manager --replicas=1; done` + - **Risk:** Operators will reconcile ConfigMaps back to defaults, reverting the `auth_backends` change. May need to: + a. Leave operators at 0 (manual management only) + b. Or accept that RMQ admin UI access breaks after reconciliation (recreate admin users on each RMQ restart) + +2. **Custom broadcast identity** — Currently broadcasts appear as `fls_backend`. Want to change title to "Dune Admin" or similar. Modify the hardcoded values in the script or change the message structure. + +3. **Integrate broadcast into dashboard** — Add a broadcast UI to the dashboard admin panel (title/message/duration fields) that calls the script via SSH. + +4. **BGD API expansion** — Currently only player endpoints. Check if there are undocumented endpoints or if the dashboard's director.py adds functionality. + +5. **Database backup/import** — `battlegroup.sh backup` and `import` commands exist. + +6. **`completions` exchange** — RMQ error that may be benign or indicate a missing exchange declaration. + +7. **SG Overmap pod** — Check TLS connection issues. + +### New Findings (2026-05-22) +8. **Installed tools on VM:** `curl`, `python3`, `py3-pip` added to Alpine VM for easier debugging +9. **TR Binary analysis:** Extracted from `server-text-router.tar` Docker image. Found classes: `RmqHttpTokenAuthApi`, `RmqHttpTokenGenerator`, `ShaTokenGenerator` with `TimeSkew` config. Token validation uses HMAC with the signing key. +10. **Battlegroup Operator behavior:** All 4 operators continuously reconcile ConfigMaps. To make config changes, must scale operators to 0 replicas first, then restore after changes. +11. **World namespace:** `funcom-seabass-sh-b17a5f036d1f7882-ooaeyc` (3rd install). Changes on each install — auto-detect with: `kubectl get pods -A --no-headers | grep mq-game-sts-0 | awk '{print $1}'` +12. **BGD Map Config:** BGD manages 50+ maps/instances including Survival, Story, Challenge Rooms, CB (Combat Block), DLC content, and test gyms +13. **send-dune-broadcast utility:** Found at `F:\Downloads\send-dune-broadcast`. Sends in-game announcements via RMQ `heartbeats` exchange using `rabbitmqctl eval`. Uses hardcoded AuthToken `Nu6VmPWUMvdPMeB7qErr`. See section 6.5 for full analysis. +14. **RMQ admin user persistence:** Admin users created via `rabbitmqctl add_user` are lost when RMQ pods restart. The PV may not be persisting user data, or the StatefulSet may be using a fresh volume each time. Need to investigate PV configuration. +15. **CRITICAL — RMQ TLS config missing on fresh install:** The default RMQ ConfigMaps on a fresh install are **missing TLS configuration**. Game services connect via TLS (`-RMQGameTlsEnabled=true`) but RMQ only listens on plain TCP, causing `{bad_header,<<22,3,1...>>}` errors and immediate connection drops. **Fix:** Add TLS config to both `mq-admin-cm` and `mq-game-cm` ConfigMaps: +```yaml +system.conf: | + listeners.tcp = none + listeners.ssl.default = 5672 + ssl_options.cacertfile = /etc/rabbitmq/cacert.pem + ssl_options.certfile = /etc/rabbitmq/cert.pem + ssl_options.keyfile = /etc/rabbitmq/key.pem + ssl_options.verify = verify_none + ssl_options.fail_if_no_peer_cert = false + auth_backends.1 = internal + auth_backends.2 = $(RMQ_AUTH_BACKEND_1) + # ... rest of auth config +``` +16. **Fresh install details (2026-05-22 #2):** VM IP `192.168.0.102`. World namespace: `funcom-seabass-sh-b17a5f036d1f7882-vvgcmr`. All pods running including survival. NodePorts: BGD 30086, RMQ admin 32560, RMQ game 31834. +17. **Fresh install details (2026-05-22 #3):** VM IP `192.168.0.103`. World namespace: `funcom-seabass-sh-b17a5f036d1f7882-ooaeyc`. **CRITICAL ISSUE:** Game servers not starting — DB schema migration failing. + - **Error:** `Failed to apply schema 1968181-0-shipping` — database operator keeps retrying + - **Root cause:** DB util pods (`db-dbdepl-util-*`) hang during schema migration. They connect to DB but never complete. + - **Effect:** BattleGroup stuck in `Stopped` phase, ServerGroup stuck in `Starting`, no game server pods (bgd, sg-overmap, sg-survival, sgw, tr) are created + - **Server operator logs:** `Cannot execute pod creation since database sh-b17a5f036d1f7882-ooaeyc-db is not ready to receive connections` + - **DB pod itself is Running** — the issue is specifically with the schema migration util pods + - **DB password:** `IgNybVaa7xbtBYz7kCvf7LbF` (changes each install) + - **DB util image:** `seabass-server-db-utils:1968181-0-shipping` + - **Workaround needed:** Investigate why schema migration hangs. May need to check DB connectivity, schema files, or manually apply schema. + +### New Findings (2026-05-22 — Production VPS Session) +18. **Server is a production VPS, not local Hyper-V:** IP `65.21.198.100`, hostname `duneawakening`, Alpine Linux 3.23.4. K3s single-node cluster is fully running with all game servers operational (overmap, survival-1, deepdesert-1, arrakeen, harkovillage, bgd, sgw, tr, fb, db). Schema migration eventually succeeded. + - **World namespace:** `funcom-seabass-sh-b17a5f036d1f7882-ccdijf` (different from the failed #3 install) + - **SSH key:** `$env:LOCALAPPDATA\DuneAwakeningServer\sshKey` + - **⚠️ SCP doesn't work** (no `sftp-server`). Use pipe method with `tr -d '\r'` to strip CRLF. +19. **RMQ ConfigMap auth fix applied:** + - Operators scaled to 0 (still at 0 as of end of session) + - Changed both `mq-admin-cm` and `mq-game-cm`: `auth_backends.1 = internal`, `auth_backends.2 = $(RMQ_AUTH_BACKEND_1)` + - RMQ pods restarted, admin users `admin:admin123` created with full permissions on both instances + - **RMQ Admin UI:** `http://65.21.198.100:30325` ✅ + - **RMQ Game UI:** `http://65.21.198.100:32716` ✅ + - **Note:** The game ConfigMap also needed the fix applied separately (first run only got admin, not game) +20. **`send-dune-broadcast` tested and confirmed working on live server:** + - Script copied to `/tmp/send-dune-broadcast` on the VM + - `python3` was not pre-installed — had to `apk add python3 py3-pip` first + - Test 1: `--title Notice --message Test --duration 30` → ✅ Success + - Test 2: `--title "YEY got it working!" --message "How are ya?" --duration 30` → ✅ Success + - Messages appear in-game as expected with hardcoded `fls_backend` identity + - The `heartbeats` exchange exists and accepts messages from `rabbitmqctl eval` +21. **No GitHub commits/pushes made — security enforced.** +22. **"Admin Experimental" dashboard tab created:** + - New nav entry at end of NAV_PAGES in `constants.py` + - Route `/admin-experimental` added in `main.py` + - Template `templates/admin_experimental.html` with broadcast form + - API endpoint `POST /api/admin-experimental/broadcast` in `api.py` + - `send_global_broadcast()` method added to `AdminService` in `admin.py` + - Uses base64 encoding to write Erlang script on VM host, then pipes via `cat | kubectl exec -i` into the pod + - **Note:** The original approach using heredoc failed through paramiko. Final working approach: write erl file on VM host via base64 decode, then `cat file | kubectl exec -i pod -- sh -lc 'cat > /tmp/pod.erl && rabbitmqctl eval "$(cat /tmp/pod.erl)"'` +23. **RMQ Game Exchanges discovered (via RMQ Management API at :32716):** + - `heartbeats` (direct) — broadcasts + - `rpc` (direct) — server RPC (no bindings currently) + - `notifications` (topic) — notifications + - `chat.faction.1-4` (fanout) — faction chat + - `chat.guild.*` (fanout) — guild chat + - `chat.intercept` (topic) — chat intercept + - `chat.proximity`, `chat.whispers`, `chat.map` (direct) — chat channels + - `login_grant`, `login_request`, `login_response` (direct) — auth flow + - `status.*` (fanout) — per-map status (Overmap, Survival_1, DeepDesert_1, SH_Arrakeen, SH_HarkoVillage, CB_*, DLC_*, Story_*) + - `travel_queue_status` (topic) — travel queue + - `director_respawned` (fanout) — respawn events +24. **RMQ Admin Exchanges discovered (via RMQ Management API at :30325):** + - `completions` (direct) — 723 messages published (completion events) + - `response` (direct) — 64K+ messages published (response routing) + - `settingsUpdate` (fanout) — 71 messages published (server settings updates) + - `travel` (topic) — travel messages + - `travelQueueStatus` (fanout) — 1K+ messages published + - `grant` (direct) — grant messages + - `heartbeats` (direct) — 2K+ messages published + - `rpc` (direct) — RPC messages + - `director_respawned` (fanout) — respawn events +25. **RMQ Game Queues discovered:** + - `B17A5F036D1F7882_queue` — host-specific queue + - `bgdRpc` — BGD RPC queue (1 consumer) + - `loginRequests` — login requests (1 consumer) + - `queue.intercept` — intercept queue (1 consumer) + - `queue.server.*` (5 queues) — server-specific queues (1 consumer each) +26. **BGD API Full Discovery:** + - `/v0/battlegroup` — **Full battlegroup JSON** with all server/player data (dimension maps, servers, configs, player counts, gameplay settings) + - `/v0/players` — returns `["B17A5F036D1F7882"]` (FLS IDs) + - `/v0/players/online` — online FLS IDs + - `/v0/players/intransit`, `/v0/graceperiod`, `/v0/completion`, `/v0/queued` — player status endpoints + - `/v0/BattlegroupFetchFlsReportSettings` — FLS report config + - `/v0/BattlegroupUpdateFlsReportSettings` — POST to update FLS settings + - `/v0/BattlegroupClearFlsReportOverrides` — POST to clear overrides + - BGD Web UI at `/` shows: player stats, FLS settings, character transfer settings, per-map server overview with player counts/queue/status, per-server settings (force lock, caps), instance scaling config + - `/v0/battlegroup` JSON contains: `dimensionMaps[]`, `singleServerMaps[]`, `instancedMaps[]` with per-server `partition`, `ip`, `gamePort`, `numPlayers*`, `status`, `cfg`, `lastServerState` (includes `serverGameplaySettings`: hydration, sandstorm, sandworm, PvP, security zones, mining multiplier, durability, etc.) +27. **PostgreSQL Database Admin Functions discovered (517 total in `dune` schema):** + - `_add_item_delete_log(in_item_id bigint, in_inventory_id bigint, in_template_id text)` + - `_add_item_trace_log(in_function_name dune.itemtrackingfunctiontype, in_item_locations dune.inventoryitemlocation[])` + - `_add_item_trace_log(in_function_name dune.itemtrackingfunctiontype, in_item_id bigint, in_inventory_id bigint, in_template_id text, in_position_index bigint)` + - `_building_validate_totem_owner_id(in_totem_owner_id bigint)` + - `_character_transfer_allocate_id(kind dune._charactertransferentrykind, data jsonb)` + - `_character_transfer_create_data_table()` + - `_character_transfer_data_filter(id text, removed text[], VARIADIC refs dune._charactertransferdatafilterref[])` + - `_character_transfer_data_table_load(entries jsonb)` + - `_character_transfer_data_table_save()` + - `_character_transfer_ensure_player_is_owner_of_vbt_vehicle(in_vehicle_id bigint[])` + - `_character_transfer_get_filter(kind dune._charactertransferentrykind)` + - `_character_transfer_get_patches_checksum()` + - `_character_transfer_pre_export_validation(in_fls_id text)` + - `_character_transfer_property_not_exported_is_expected(path text)` + - `_character_transfer_replace_local_id_with_transfer_id(data text, path text)` + - `_character_transfer_replace_local_id_with_transfer_id_in_json(data jsonb, path text)` + - `_character_transfer_replace_transfer_id_with_local_id(data text, path text)` + - `_character_transfer_replace_transfer_id_with_local_id_in_json(data jsonb, path text)` + - `_character_transfer_store_in_world_owned_vehicles_into_recovery(in_player_id bigint)` + - `_character_transfer_top_level_export(in_kind dune._charactertransferentrykind, data jsonb)` + - `_character_transfer_top_level_import(in_kind dune._charactertransferentrykind, data jsonb, in_id bigint)` + - `_placeable_validate_totem_owner_id(in_totem_owner_id bigint)` + - `_user_data_encryption_initially_encrypt_existing_data()` + - `_user_data_encryption_setup_enabled(key_hash bytea)` + - `_user_data_encryption_setup_tainted()` + - `accept_guild_invite(in_invite_id bigint, in_role_id smallint, in_max_guild_count_per_player integer, in_max_members_per_guild integer, in_neutral_faction_id smallint)` + - `accept_party_invite(in_invite_id bigint, in_platform_session_id text, in_max_party_member_count integer)` + - `add_actor_audit(in_id bigint, in_class text)` + - `add_event_log_data(in_game_event_owner bigint, in_universe_time bigint, in_map_name text, in_partition_id bigint, in_event_type integer, in_x_location double precisio...)` + - `add_event_log_data_batched(in_data dune.eventlogbulkentrydata[])` + - `add_guild_invite(in_player_id bigint, in_guild_id bigint, in_sender_player_id bigint, in_invite_sent_timespan bigint, in_max_guild_invites_per_guild integer)` + - `add_guild_member(in_player_id bigint, in_guild_id bigint, in_role_id smallint, in_max_guild_count_per_player integer, in_max_members_per_guild integer, in_neutral_f...)` + - `add_landclaim_segment(in_totem_id bigint, in_grid_location_x bigint, in_grid_location_y bigint)` + - `add_map_areas_surveyed_items(in_account_id bigint, in_area_id smallint, in_survey_point_marker_id bigint, in_surveyed_items_target jsonb, in_surveyed_items_progress jsonb, in_m...)` + - `add_map_areas_time_discovered(in_account_id bigint, in_area_id smallint, in_time_discovered timestamp without time zone, in_map_name text)` + - `add_map_areas_time_first_entered(in_account_id bigint, in_area_id smallint, in_time_first_entered timestamp without time zone, in_map_name text)` + - `add_partition_unique(in_map text, in_definition jsonb, in_dimension bigint, in_label text)` + - `add_party_invite(in_sender_player_id bigint, in_sender_platform_name text, in_sender_platform_session_id text, in_player_id bigint, in_max_party_member_count intege...)` + - `adjust_player_virtual_currency_balance(in_controller_id bigint, in_currency_id smallint, in_delta bigint)` + - `admin_get_character_details(in_account_id bigint)` + - `admin_get_character_ids(in_search_term text)` + - `admin_get_inventory_details(in_account_id bigint)` + - `admin_get_journey_details(in_player_id text, in_story_node_id text)` + - `admin_get_mnemonic_recall_details(in_account_id bigint)` + - `admin_get_partitions()` + - `admin_move_offline_player(in_fls_id text, in_target_partition_name text, in_target_location dune.vector)` + - `admin_move_offline_player_to_partition(in_fls_id text, in_target_partition_id bigint, in_target_location dune.vector)` + - `admin_read_player_tags(in_account_id bigint)` + - `advance_items_id_sequencer(count bigint)` + - `assign_actor_id(in_class text)` + - `base_backup_delete(in_base_backup_id bigint)` + - `base_backup_find_totems_from_player_owner(in_player_id bigint)` + - `base_backup_finish_placing(in_base_backup_id bigint)` + - `base_backup_get_actors_to_spawn(in_base_backup_id bigint)` + - `base_backup_get_available_backups(in_player_id bigint)` + - `base_backup_get_buildable_data(in_base_backup_id bigint)` + - `base_backup_get_data(in_base_backup_id bigint)` + - `base_backup_get_totem_data(in_base_backup_id bigint)` + - `base_backup_get_totem_data_from_totem_id(in_totem_id bigint)` + - `base_backup_get_totem_id(backup_id bigint)` + - `base_backup_recycle(in_base_backup_id bigint, in_target_inventory_id bigint)` + - `base_backup_save(in_player_actor_id bigint, in_base_backup_name text, in_building_pieces_to_link dune.basebackupbuildingitem[], in_placeables_to_link bigint[], in_p...)` + - `base_backup_save_all_totems_from_player_owner(in_player_id bigint)` + - `base_backup_save_from_totem(in_player_id bigint, totem_id bigint)` + - `break_guild_allegiance(in_guild_id bigint, in_neutral_faction_id smallint)` + - `can_takeover_account(in_user_id text)` + - `change_player_faction(in_player_id bigint, in_faction_id smallint, neutral_faction_id smallint, in_utc_time_faction_change timestamp without time zone)` + - `character_migration_export(in_fls_id text)` + - `character_migration_import(in_data jsonb, in_fls_id text, in_character_name text)` + - `character_transfer_export(in_fls_id text)` + - `character_transfer_get_unsaved_counts(in_fls_id text)` + - `character_transfer_import(in_data jsonb, in_fls_id text, in_character_name text)` + - `clean_expired_party_invites(in_invite_expire_seconds integer)` + - `clean_guild_invites_with_incompatible_faction(in_player_id bigint, in_faction_id smallint, neutral_faction_id smallint)` + - `clean_old_guild_invites(in_cutoff_timespan bigint)` + - `clean_stock_for_player(in_player_id bigint)` + - `clean_stock_for_vendors(in_vendor_ids text[])` + - `clean_vendors_older_than_timestamp(in_reference_timestamp bigint)` + - `cleanup_account_log_and_orphaned_actors()` + - `cleanup_accounts_marked_for_deletion_in_fls(in_account_ids text[])` + - `cleanup_orphaned_entities()` + - `clear_map_areas_data_for_player(in_id bigint)` + - `complete_journey_nodes_where_prerequisite_nodes_are_complete(story_ids_to_complete text[], prerequisite_completed_story_ids text[])` + - `complete_journey_story_nodes_for_player(in_player_id text, in_story_node_ids text[])` + - `corilis_cleanup_map(in_server_info dune.serverinfo, in_map_info dune.coriolismapinfo)` + - `coriolis_cleanup_farm(in_server_info dune.serverinfo, in_map_info dune.coriolismapinfo)` + - `coriolis_cleanup_partition(in_server_info dune.serverinfo, in_map_info dune.coriolismapinfo)` + - `coriolis_update_seed(in_server_info dune.serverinfo, in_new_coriolis_seed integer, in_map_info dune.coriolismapinfo)` + - `create_event_log_partition()` + - `create_guild(in_player_id bigint, in_neutral_faction smallint, in_guild_name text, in_guild_desc text, in_max_guild_count_per_player integer, OUT out_guild_id b...)` + - `create_or_update_tutorial_entry(in_player_id bigint, in_tutorial_id smallint, in_tutorial_state smallint)` + - `create_server_player_access_codes(in_account_id bigint, in_access_code integer, in_access_code_type integer, in_is_resettable boolean)` + - `create_sinkchart_for_map_area_id(in_item_id bigint, in_creator_id bigint, in_map_name text, in_area_id smallint)` + - `debug_add_test_table_data(in_entry text)` + - `debug_collect_test_table_data()` + - `debug_echo(in_text text, in_notices text[])` + - `debug_get_coriolis_seeds()` + - `debug_raise_exception(in_exception text, in_notices text[])` + - `debug_raise_notices(in_notices text[])` + - `debug_reset_test_table()` + - `debug_set_farm_seed(in_new_coriolis_seed integer)` + - `debug_set_map_seed(in_map text, in_new_coriolis_seed integer)` + - `debug_set_partition_seed(in_partition_id bigint, in_new_coriolis_seed integer)` + - `decrypt_user_data(in_encrypted_data bytea)` + - `delete_account(in_user_id text, in_reason text)` + - `delete_actor_states_travel(in_actor_id bigint)` + - `delete_actors(in_ids bigint[])` + - `delete_actors_and_respawns_on_server(in_server_info dune.serverinfo, in_vehicle_classes_spawned_on_map text[], in_allow_vehicle_recovery boolean)` + - `delete_all_dungeon_completions(in_dungeon_id text)` + - `delete_all_dungeon_completions_by_player(in_dungeon_id text, in_player_id bigint, in_keep_completion_for_other_players boolean)` + - `delete_all_dungeon_completions_for_all_dungeons_by_player(in_player_id bigint, in_keep_completion_for_other_players boolean)` + - `delete_all_inactive_farms()` + - `delete_all_journey_story_nodes(in_account_id bigint)` + - `delete_all_static_shifting_sand()` + - `delete_all_tutorial_entries(in_player_id bigint)` + - `delete_building_blueprint(in_building_item_id bigint)` + - `delete_character(in_actor_id bigint)` + - `delete_crafted_map(in_item_id bigint)` + - `delete_dialogue_data(in_player_controller_id bigint)` + - `delete_inventory_item(in_item_id bigint, in_count bigint)` + - `delete_item(in_id bigint)` + - `delete_items(in_ids bigint[])` + - `delete_items_from_actor(in_actor_id bigint)` + - `delete_journey_story_ids(story_ids text[])` + - `delete_journey_story_node(in_account_id bigint, in_story_node_id text)` + - `delete_journey_story_nodes_for_group_for_player(in_account_id bigint, in_reset_group dune.journeystoryresetgroup)` + - `delete_journey_story_nodes_for_player(in_player_id text, in_story_node_ids text[])` + - `delete_journey_story_nodes_for_player_account(in_account_id bigint, in_story_node_ids text[])` + - `delete_map_markers(in_dimension_index integer, in_map_name text, in_player_marker_data dune.deleteplayermarkerdata[])` + - `delete_markers_by_id(in_marker_ids integer[])` + - `delete_markers_by_static_location_key(p_location_key text)` + - `delete_markers_for_all_players(in_marker_types_to_keep text[], in_map text)` + - `delete_markers_return_actor_ids(in_dimension_index integer, in_map_name text, in_marker_ids integer[])` + - `delete_mnemonic_recall_lesson(in_account_id bigint, in_lesson_id text)` + - `delete_mnemonic_recall_lesson_all(in_account_id bigint)` + - `delete_server_player_access_codes(in_account_id bigint, in_access_code integer, in_access_code_type integer)` + - `delete_spawner(in_map text, in_name text, in_dimension_index integer)` + - `delete_static_location_markers(p_location_keys text[])` + - `delete_world_partition_by_map_id(in_map_id text)` + - `demote_guild_member(in_guild_id bigint, in_player_id bigint, in_new_role smallint)` + - `determine_partition_label(in_map text, in_dimension_index integer, in_label text, in_allow_overwrite boolean, in_partition_id bigint)` + - `determine_partition_label_trigger()` + - `disband_guild(in_guild_id bigint)` + - `disband_party(in_party_id bigint)` + - `downgrade_map_name(in_map_name text)` + - `drain_item_tracking_data()` + - `dune_exchange_add_sell_order(in_exchange_id bigint, in_access_point_id bigint, in_owner_id bigint, in_max_orders_per_player integer, in_expiration_time bigint, in_item_id bigin...)` + - `dune_exchange_cancel_order(in_order_id bigint, in_purge_time bigint, in_completion_type integer)` + - `dune_exchange_expire_orders(in_exchange_id bigint, in_current_time bigint, in_purge_time bigint, in_expired_completion_type integer)` + - `dune_exchange_fulfill_sell_order(in_exchange_id bigint, in_max_orders_per_player integer, in_purchased_completion_type integer, in_sold_completion_type integer, in_instigator_id bi...)` + - `dune_exchange_get_item_price_stats(in_template_ids text[])` + - `dune_exchange_get_user_id(in_owner_id bigint)` + - `dune_exchange_modify_user_solari_balance(in_controller_id bigint, in_solari_delta bigint)` + - `dune_exchange_purge_completed_orders(in_exchange_id bigint, in_current_time bigint)` + - `dune_exchange_query_storage_item(in_order_id bigint)` + - `dune_exchange_query_storage_items(in_exchange_id bigint, in_owner_id bigint)` + - `dune_exchange_relist_order(in_order_id bigint, in_expiration_time bigint, in_item_price bigint, in_wear_normalized_item_price bigint, in_solari_cost bigint)` + - `dune_exchange_retrieve_solari_balance(in_owner_id bigint)` + - `dune_exchange_retrieve_solaris_from_item(in_controller_id bigint, in_order_id bigint)` + - `dune_exchange_retrieve_storage_item(in_exchange_id bigint, in_order_id bigint, in_dst_inventory_id bigint, in_dst_index bigint, in_count bigint)` + - `dune_exchange_update_recurring_sell_order(in_exchange_id bigint, in_expiration_time bigint, in_access_point_id bigint, in_owner_id bigint, in_item_id bigint, in_increment bigint, in_max_cou...)` + - `dune_get_account_id_by_user(in_user text)` + - `edit_guild_description(in_guild_id bigint, in_guild_desc text)` + - `encrypt_user_data(in_data text)` + - `fetch_resourcefield_state(in_map text, in_dimension_index integer, in_field_kind_id smallint)` + - `fetch_server_spice_field_manifest(in_server_id text)` + - `fetch_spicefie_id_types_with_global_info(in_map_name text, in_dimension_index integer)` + - `find_actor_by_id(in_id bigint)` + - `fix_broken_harkonnen_players_due_to_fooled_thufir()` + - `flag_player_as_cheater(in_account_id bigint, in_cheat_type dune.cheat_type_enum)` + - `gather_ownerless_actors_on_server(in_server_info dune.serverinfo)` + - `gather_player_linked_actors(in_player_pawn_id bigint)` + - `gather_removed_accounts_that_left_orphaned_actors_on_server(in_server_info dune.serverinfo)` + - `get_account_actor_ids(in_account_id bigint)` + - `get_active_servers_for_gateway()` + - `get_actor_server_info(in_id bigint)` + - `get_actors_location_data_with_permission(in_actor_ids bigint[])` + - `get_all_demo_players()` + - `get_all_faction_members()` + - `get_all_guild_members()` + - `get_all_online_or_recently_disconnected_player_online_state()` + - `get_all_parties()` + - `get_all_party_invites()` + - `get_all_party_members()` + - `get_all_player_character_home_dimensions()` + - `get_all_player_in_guild_online_state(in_guild_id bigint)` + - `get_all_player_travel_states()` + - `get_all_tutorial_entries(in_player_id bigint)` + - `get_all_unresolved_character_imports()` + - `get_applied_patches()` + - `get_battlegroup_close_date()` + - `get_best_dungeon_completion(in_dungeon_id text)` + - `get_best_dungeons_completions_for_player(in_player_id bigint)` + - `get_building_blueprint_copy_data(in_building_blueprint_id bigint)` + - `get_building_favorites(in_account_id bigint)` + - `get_building_id(in_actor_id bigint, in_class text)` + - `get_character_import_state(in_fls_id text)` + - `get_character_transfer_related_items(in_fls_id text)` + - `get_consumed_lore_pickups(in_actor_id bigint, in_use_temporary boolean)` + - `get_controller_id_from_platform_id(in_platform_id text)` + - `get_dune_exchange_accesspoint_id(in_exchange_id bigint, in_name text)` + - `get_dune_exchange_data(in_exchange_id bigint, in_controller_id bigint)` + - `get_dune_exchange_id(in_name text)` + - `get_dune_exchange_used_order_slots(in_controller_id bigint)` + - `get_exchange_inventory_id(in_exchange_id bigint)` + - `get_exchange_orders_by_mask(in_mask integer, in_depth smallint)` + - `get_exchange_sell_orders(in_id bigint, in_exchange_id bigint, in_min_item_price bigint, in_max_item_price bigint, in_template_id text, in_mask integer, in_depth smallint)` + - `get_exchange_sell_orders_by_item_type(in_exchange_id bigint, in_template_ids text[])` + - `get_exchange_sell_orders_by_owner(in_exchange_id bigint, in_owner_id bigint)` + - `get_farm_state()` + - `get_friends_search(in_player_name text, in_max_players_count integer)` + - `get_guild_data(in_guild_id bigint)` + - `get_guild_data_for_player(in_player_id bigint)` + - `get_guild_for_player(in_player_id bigint)` + - `get_guild_invites(in_guild_id bigint)` + - `get_guild_members(in_guild_id bigint)` + - `get_inventory_data(in_inventory_id bigint)` + - `get_inventory_id(in_actor_id bigint, in_component_name_hash integer)` + - `get_items_to_remove(items_to_remove text[])` + - `get_landclaim_segments(in_totem_id bigint)` + - `get_learned_building_sets(in_account_id bigint)` + - `get_learned_new_buildable_pieces(in_account_id bigint)` + - `get_login_journey_nodes(in_account_id bigint)` + - `get_login_journey_nodes_cooldown(in_account_id bigint)` + - `get_mnemonic_recall_lessons(in_account_id bigint)` + - `get_online_player_controller_ids(in_map text)` + - `get_online_player_controller_ids_on_farm()` + - `get_partition_presets()` + - `get_partitions(in_map text)` + - `get_party_members(in_party_id bigint)` + - `get_permission_actors_for_server(in_server_info dune.serverinfo)` + - `get_permission_for_actor(in_actor_id bigint)` + - `get_permission_for_actors(in_actor_id bigint[])` + - `get_permission_for_player_actors(in_player_id bigint, in_min_rank smallint)` + - `get_placeable_id(in_actor_id bigint, in_class text, in_building_type text)` + - `get_player_access_codes(in_account_id bigint)` + - `get_player_current_faction_reputation(in_actor_id bigint, OUT out_faction_id smallint, OUT out_reputation_amount integer)` + - `get_player_faction(in_player_id bigint, in_neutral_faction_id smallint)` + - `get_player_faction_name(in_actor_id bigint, OUT player_faction_name text, OUT utc_time_faction_change timestamp without time zone)` + - `get_player_guild_invites(in_player_id bigint)` + - `get_player_ids_online_state(in_player_ids bigint[])` + - `get_player_infos_for_actor_ids(in_actor_ids bigint[])` + - `get_player_infos_for_character_names(in_character_names text[])` + - `get_player_infos_for_fls_ids(in_fls_ids text[])` + - `get_player_infos_for_funcom_ids(in_funcom_ids text[])` + - `get_player_online_state_within_grace_period_for_each_server()` + - `get_player_owned_vehicles_data(in_player_id bigint, in_account_id bigint)` + - `get_player_partition_id(in_fls_id text)` + - `get_player_pawn(in_account_id bigint)` + - `get_player_virtual_currency_balances(in_controller_id bigint)` + - `get_players_demo_data(in_controller_ids bigint[])` + - `get_recipes_to_remove(recipes_to_remove text[])` + - `get_registered_spawned_actor(in_spawner_id bigint)` + - `get_respawn_locations(in_account_id bigint)` + - `get_schema_version()` + - `get_solaris_id()` + - `get_spawner_id(in_map text, in_name text, in_dimension_index integer)` + - `get_stored_user_data_encryption_key_hash()` + - `get_stored_user_data_encryption_status()` + - `get_stored_user_data_encryption_taint_xmax()` + - `get_sub_inventory_id(in_owner_item_id bigint)` + - `get_traveling_actor_id_and_types(in_actor_id bigint)` + - `get_traveling_actor_ids(in_actor_id bigint, in_max_recursion_level integer)` + - `get_traveling_actors_fls_ids(in_actor_id bigint)` + - `get_traveling_non_player_actor_ids(in_actor_id bigint)` + - `get_unbacked_up_vehicle_ids_for_account(in_account_id bigint)` + - `get_universe_time()` + - `get_unsaved_base_totem_ids_for_account(in_account_id bigint)` + - `get_vehicle_id(in_actor_id bigint, in_class text)` + - `get_vehicle_module_inventory_id(in_vehicle_module_id bigint, in_vehicle_module_inventory_type integer)` + - `guild_handle_actor_delete(in_player_id bigint)` + - `guilds_get_exclusive_operation_lock()` + - `handle_player_faction_guild_effects(in_player_id bigint, in_faction_id smallint, neutral_faction_id smallint)` + - `igwo_delete_world_partitions(in_partition_ids bigint[])` + - `igwo_get_partition_id_seq_last_value()` + - `igwo_get_partition_ids()` + - `igwo_get_partitions()` + - `igwo_get_server_details()` + - `igwo_insert_world_partition(in_partition_id bigint, in_map text, in_partition_definition jsonb, in_dimension_index integer, in_partition_label text)` + - `igwo_next_partition_id_seq()` + - `igwo_notify_world_partition_update()` + - `igwo_restart_partition_id_seq(in_restart_with bigint)` + - `igwo_update_world_partition(in_map text, in_partition_definition jsonb, in_partition_id bigint, in_dimension_index integer, in_label text)` + - `init_event_log(in_partition_id bigint)` + - `initialize_partitions_basic_battlegroup()` + - `initialize_partitions_basic_survival_1()` + - `initialize_partitions_development_battlegroup()` + - `initialize_partitions_editor_default_1x1()` + - `initialize_partitions_full_battlegroup()` + - `initialize_partitions_igw_test_small_2x1()` + - `initialize_partitions_igw_test_small_2x2()` + - `initialize_partitions_igw_training()` + - `initialize_specialization_keystones(in_keystones text[])` + - `initialize_world_partition(in_map_name text, in_num_servers integer, in_dimension_index integer)` + - `interact_get_vendor_items_bought_from_player(in_vendor_id text, in_player_id bigint, in_current_cycle_start_timestamp bigint)` + - `internal_add_party_member(in_invite_id bigint, in_party_id bigint, in_player_id bigint, in_platform_session_id text, in_platform_name text, in_max_party_member_count integer)` + - `internal_create_party(in_invite_id bigint, in_leader_id bigint, in_leader_platform_session_id text, in_leader_platform_name text, in_member_id bigint, in_platform_sessio...)` + - `is_player_guild_admin(in_player_id bigint, in_guild_id bigint)` + - `is_player_offline(in_fls_id text)` + - `is_player_party_leader(in_player_id bigint, in_party_id bigint)` + - `join_platform_session_party(in_leader_platform_id text, in_player_platform_id text, in_platform_session_id text, in_platform_name text, in_max_party_member_count integer)` + - `journey_story_node_cooldown_add(in_account_id bigint, in_story_node_id text, in_time_to_expire timestamp without time zone)` + - `journey_story_node_cooldown_delete_expired(in_time_to_check timestamp without time zone)` + - `landsraad_cast_vote(in_term_id bigint, in_player_id bigint, in_decree_name text)` + - `landsraad_change_term_end_time(end_term_id bigint, new_end_time timestamp without time zone, in_test_term boolean)` + - `landsraad_check_task_completion()` + - `landsraad_check_term_won()` + - `landsraad_collect_task_telemetry_for_faction(in_term_id bigint, in_faction_name text)` + - `landsraad_collect_term_telemetry(in_term_id bigint, in_faction_names text[])` + - `landsraad_collect_term_telemetry_for_faction(in_term_id bigint, in_faction_name text)` + - `landsraad_collect_vote_telemetry(in_term_id bigint, in_winning_faction_id integer)` + - `landsraad_collect_votes(in_term_id bigint)` + - `landsraad_determine_winner(in_term_id bigint)` + - `landsraad_force_end_term(end_term_id bigint)` + - `landsraad_has_term_of_task_ended(in_task_id bigint)` + - `landsraad_initialize_system(number_of_weeks_term_retention integer, number_of_nominated_decrees integer, in_end_time timestamp without time zone, in_test_term boolean, faction...)` + - `landsraad_initialize_term(number_of_weeks_term_retention integer, number_of_nominated_decrees integer, in_end_time timestamp without time zone, in_test_term boolean, tasks d...)` + - `landsraad_insert_task_progress(in_term_id bigint, in_player_id bigint, in_guild_id bigint, in_house_name text, in_faction_progress integer, in_guild_progress real, in_player_prog...)` + - `landsraad_insert_task_progress_batched(in_term_id bigint, in_task_progress dune.landsraadtaskprogress[])` + - `landsraad_insert_task_progress_faction(in_term_id bigint, in_faction_name text, in_house_name text, in_faction_progress integer, in_guild_progress real, in_player_progress real)` + - `landsraad_insert_task_progress_random(in_term_id bigint, in_faction_names text[], in_num_rows integer)` + - `landsraad_load_current_rotation(in_term_id bigint)` + - `landsraad_load_current_term()` + - `landsraad_load_guild_contribution(in_term_id bigint, in_guild_id bigint, in_faction_id bigint)` + - `landsraad_load_guild_contributions(in_term_id bigint, in_num_guilds integer, in_faction_names text[])` + - `landsraad_load_guild_vote(in_term_id bigint, in_player_id bigint)` + - `landsraad_load_house_rewards(in_player_id bigint)` + - `landsraad_load_player_contributions(in_term_id bigint, in_player_ids bigint[])` + - `landsraad_load_task_faction_progress(in_term_id bigint)` + - `landsraad_load_task_faction_reveal_state(in_term_id bigint)` + - `landsraad_load_term_progress(in_term_id bigint, in_num_guilds integer, in_faction_names text[], in_player_ids bigint[])` + - `landsraad_notify_house_rewards_changed()` + - `landsraad_perform_daily_task_reveal(in_term_id bigint, in_faction_names text[], in_house_names_to_reveal text[], in_reveal_day integer)` + - `landsraad_process_house_rewards()` + - `landsraad_process_task_progress(max_rows integer)` + - `landsraad_task_has_been_completed(in_task_id bigint)` + - `landsraad_update_task_faction_reveal_state(in_term_id bigint, in_task_board_index integer, faction_name text, reveal_state boolean)` + - `landsraad_withdraw_house_reward(in_player_id bigint, in_house_rewards dune.landsraadplayerhousereward[])` + - `load_actors(in_actor_ids bigint[], in_actor_state dune.actorstate)` + - `load_backup_vehicle(in_account_id bigint)` + - `load_building(in_building_id bigint)` + - `load_communinet_player_data(in_account_id bigint)` + - `load_dialogue_data(in_player_controller_id bigint, OUT met_npcs text[], OUT taken_nodes integer[])` + - `load_dimension_index(in_map text, in_partition_id bigint)` + - `load_events_log_data_from_player(in_actor_id bigint, in_limit_entries_num integer)` + - `load_full_actors(in_ids bigint[])` + - `load_item(in_item_id bigint)` + - `load_items(in_inventory_id bigint)` + - `load_map_areas_entries(in_account_id bigint, in_map_name text)` + - `load_markers(in_player_id bigint, in_dimension_id integer, in_map_name text)` + - `load_partition_definition_map()` + - `load_placeable(in_placeable_id bigint)` + - `load_recovered_vehicles(in_account_id bigint, in_restore_time_limit integer)` + - `load_static_encounter_name(in_map_name text, in_package_name text, in_actor_name text)` + - `load_takeoverable_user_ids()` + - `load_totem(in_id bigint)` + - `load_travel_return_info(in_player_controller_id bigint)` + - `load_travel_to_player_info(in_player_controller_id bigint)` + - `load_vehicle_modules(in_vehicle_id bigint)` + - `load_world_partition(in_map_name text, in_server_id text, in_desired_dimension_index bigint, in_desired_partition_id bigint)` + - `log_cheating(in_fls_id text, in_cheat_type dune.cheat_type_enum, in_event_time timestamp with time zone)` + - `log_event_solaris(in_function_oid oid, in_message dune.logmessagetype, in_controller_id bigint, in_solaris_balance bigint, in_solaris_delta bigint)` + - `login_account(in_user_id text, in_funcom_id text, in_platform_id text, in_platform_name text, in_minimum_returning_player_time_seconds integer, in_character_name...)` + - `mark_server_dead(in_server_id text)` + - `merge_inventory_items(in_item_id bigint, in_dst_inventory_id bigint, in_dst_index bigint, in_count bigint)` + - `merge_or_move_inventory_item(in_item_id bigint, in_dst_inventory_id bigint, in_dst_index bigint, in_count bigint)` + - `migrate_character(in_account_id bigint, home_dimension integer, max_solaris_allowed bigint)` + - `migrate_clamp_max_allow_solaris(in_pawn_id bigint, max_solaris_allowed bigint)` + - `move_inventory_item(in_item_id bigint, in_dst_inventory_id bigint, in_dst_index bigint, in_count bigint)` + - `overmap_delete_player_survival_data(in_player_id bigint)` + - `overmap_load_player_survival_data(in_player_id bigint)` + - `overmap_save_player_survival_data(in_player_id bigint, in_vehicle_id bigint, in_has_polar_psu boolean, in_overmap_location dune.vector)` + - `ownership_handle_actor_delete(in_player_id bigint)` + - `parties_get_exclusive_operation_lock()` + - `perform_notify_on_character_delete(in_user_id text)` + - `permission_actor_create_or_update_base_marker(in_actor_id bigint, in_player_id bigint, in_rank smallint)` + - `permission_actor_destroy(in_actor_id bigint)` + - `permission_actor_register(in_entry dune.actorpermissionentry, in_owner_rank dune.actorpermissionrankdata)` + - `permission_actor_takeover(in_entry dune.actorpermissionentry, in_owner_rank dune.actorpermissionrankdata)` + - `permission_actor_update_marker_location(in_actor_id bigint, in_location_x real, in_location_y real, in_location_z real)` + - `permission_remove_player_rank(in_actor_id bigint, in_player_id bigint)` + - `permission_set_access_level(in_actor_id bigint, in_access_level smallint)` + - `permission_set_name(in_actor_id bigint, in_name text)` + - `permission_set_player_rank(in_actor_id bigint, in_player_id bigint, in_rank smallint, in_map_id text)` + - `player_purchased_item_from_vendor(in_vendor_id text, in_player_id bigint, in_template_id text, in_amount_bought integer)` + - `player_state_update(in_data dune.playerstateupdatedata[])` + - `pledge_guild_allegiance(in_guild_id bigint, in_guild_leader_player_id bigint, in_neutral_faction_id smallint)` + - `produce_spicefield_manifest(in_map_name text, in_dimension_index integer)` + - `promote_guild_member(in_guild_id bigint, in_player_id bigint, in_new_role smallint)` + - `promote_new_party_leader(in_party_id bigint)` + - `promote_party_leader_to(in_party_id bigint, in_player_id bigint)` + - `purchase_specialization_keystone(in_player_id bigint, in_keystone text)` + - `record_deactivated_spice_field(in_server_id text, in_spicefield_type_id integer)` + - `record_dungeon_completion(in_dungeon_id text, in_difficulty integer, in_duration_ms integer, players_ids bigint[])` + - `record_logoff_persistence_end_time(in_player_pawn_id bigint, in_logoff_persistence_end_time timestamp without time zone)` + - `record_static_shifting_sand(in_id text, in_alpha double precision, in_x double precision, in_y double precision, in_last_modified_time bigint)` + - `record_unreadied_spice_fields(in_server_id text, in_spicefield_type_id integer, in_num_unreadied integer)` + - `register_lore_pickup(in_lore_pickup_ids text[])` + - `register_new_factions(factions text[])` + - `register_new_tutorials(tutorials text[])` + - `register_per_player_lore_pickup(in_lore_pickup_ids text[], in_use_temporary boolean)` + - `register_spawned_actor(in_spawner_id bigint, in_actor_id bigint)` + - `register_spice_field_server_resources(in_server_id text, in_spicefield_type_ids integer[], in_inactive_fields_of_types integer[])` + - `register_temporary_lore_pickup(in_lore_pickup_ids text[])` + - `reject_guild_invite(in_invite_id bigint)` + - `remove_aborted_authority_transfer_actors(in_partition_id bigint)` + - `remove_character_transfer_state(in_fls_id text)` + - `remove_communinet_player_channel(in_account_id bigint, in_channel_name text)` + - `remove_guild_members(in_player_ids bigint[], in_guild_id bigint, in_remove_reason smallint)` + - `remove_items(items_to_remove text[])` + - `remove_items_and_recipes(items_to_remove text[], recipes_to_remove text[])` + - `remove_items_or_recipes_from_fgl_entities(item_or_recipes text[])` + - `remove_members_offline_for(in_interval_seconds integer)` + - `remove_party_invite(in_invite_id bigint, in_remove_reason smallint)` + - `remove_party_member(in_player_id bigint, in_remove_reason smallint)` + - `remove_recipes_from_actor_properties(recipes_to_remove text[])` + - `remove_resourcefield_states(in_map text, in_dimension_index integer, in_field_ids bigint[])` + - `request_spawn_spice_field(in_server_id text, in_spicefield_type_id integer)` + - `reset_all_players_from_server_ids_grace_period_and_logoff_timer(in_server_id text, in_reset_time timestamp without time zone)` + - `reset_global_spice_field_state(in_map_name text, in_dimension_index integer)` + - `reset_journey_story_nodes_for_player(in_player_id text, in_story_node_ids text[])` + - `reset_server_all_player_access_codes(in_account_id bigint)` + - `reset_specialization_keystones(in_player_id bigint)` + - `reset_specialization_tracks(in_player_id bigint)` + - `restore_backup_vehicle(in_account_id bigint, in_server_info dune.serverinfo, in_transform dune.transform)` + - `restore_recovered_vehicle(in_account_id bigint, in_vehicle_id bigint, in_server_info dune.serverinfo, in_transform dune.transform, in_restore_time_limit integer)` + - `retrieve_all_static_shifting_sand()` + - `returning_player_award_given(in_account_id bigint)` + - `reveal_journey_story_nodes_for_player(in_player_id text, in_story_node_ids text[])` + - `save_aborted_authority_transfer_actors(in_actor_ids bigint[], in_partition_id bigint)` + - `save_actor_dislocation(in_actor_id bigint, in_current_server_info dune.serverinfo, in_target_location dune.vector, in_target_dimension_index integer)` + - `save_actors(in_server_info dune.serverinfo, in_actors dune.actordescription[], in_actor_state dune.actorstate)` + - `save_building(in_building_id bigint, in_data dune.buildingsavedata)` + - `save_building_blueprint_copy(in_building_item_id bigint, in_building_blueprint_id bigint, in_building_blueprint_building_data dune.buildingblueprintpiecesaveitemcontainer[], in...)` + - `save_demo_account_time(in_fls_id text, in_demo_playtime_seconds integer)` + - `save_dialogue_data(in_player_controller_id bigint, in_met_npcs text[], in_taken_nodes integer[])` + - `save_item(in_item dune.inventoryitem)` + - `save_journey_story_node(in_account_id bigint, in_story_node_id text, in_override_reward_block boolean, in_has_pending_reward boolean, in_complete_condition_state jsonb, in...)` + - `save_journey_story_nodes(in_account_id bigint, in_journey_data dune.savejourneydata[])` + - `save_login_target_dimension(in_fls_id text, in_login_target_dimension_index integer)` + - `save_markers(in_player_marker_data dune.saveplayermarkerdata[], in_marker_data dune.savemarkerdata[])` + - `save_mnemonic_recall_lesson(in_account_id bigint, in_lesson_id text, in_lesson_state bigint, in_lesson_progress integer, in_is_new boolean)` + - `save_placeable(in_placeable_id bigint, in_data dune.placeablesavedata)` + - `save_player(in_player dune.playerdescription)` + - `save_player_pawn(in_pawn dune.actordescription, in_server_info dune.serverinfo, in_life_state dune.playerlifestate)` + - `save_static_encounter_name(in_map_name text, in_package_name text, in_actor_name text, in_encounter_name text)` + - `save_static_encounter_waiting_for_reset(in_map_name text, in_package_name text, in_actor_name text, in_waiting_for_reset boolean)` + - `save_totem(in_id bigint, in_data dune.totemsavedata)` + - `save_tracked_journey_cards(in_player_id bigint, in_tracked_journey_card text, in_tracked_landsraad_card text)` + - `save_travel_return_info(in_player_controller_id bigint, in_map text, in_transform dune.transform)` + - `save_vehicle_modules(in_add_list dune.vehiclemodule[], in_delete_list bigint[], in_stat_update dune.itemstatupdate[])` + - `save_world_partition(in_map_name text, in_server_id text, in_dimension_index bigint, in_partition_definition jsonb, in_blocked boolean, in_label text)` + - `server_info_match(in_actor dune.actors, in_server_info dune.serverinfo)` + - `set_account_as_takeoverable(in_user_id text, in_new_user_id text)` + - `set_all_inactive_players_in_farm_offline()` + - `set_battlegroup_close_date(in_close_date timestamp without time zone)` + - `set_character_import_state(in_fls_id text, in_state dune.transferimportstate)` + - `set_character_name(in_account_id bigint, in_name text)` + - `set_demo_state(in_user_id text, in_demo_state dune.demostate)` + - `set_item_tracking_enabled(in_enabled boolean)` + - `set_player_faction_reputation(in_actor_id bigint, in_faction_id smallint, in_reputation_amount integer)` + - `set_players_from_server_ids_offline(in_server_ids text[])` + - `set_specialization_xp_and_level(in_player_id bigint, in_track_type dune.specializationtracktype, in_xp_amount integer, in_level real)` + - `store_backup_vehicle(in_vehicle_id bigint, in_account_id bigint, in_customization_id text)` + - `store_recovered_vehicle(in_vehicle_id bigint, in_chassis_durability real, in_customization_id text, in_is_migration boolean)` + - `store_recovered_vehicles_wiped_before_spawn(in_vehicle_ids bigint[], in_delete_items boolean)` + - `takeover_account(in_user_to_takeover text, in_current_user text)` + - `taxation_emit_invoices(new_tax_invoices dune.taxinvoicedata[])` + - `taxation_get_all_invoices_for_player(in_player_id bigint)` + - `taxation_get_all_invoices_for_server(map_name text, in_dimension_index integer, in_partition_id bigint)` + - `taxation_get_all_invoices_for_totem(in_totem_id bigint)` + - `taxation_pay_invoice(invoice_id bigint, paid_invoice_status smallint)` + - `taxation_remove_invoices(invoices_to_remove bigint[])` + - `taxation_remove_invoices_from_totem(totem_actor_id bigint)` + - `taxation_update_invoice_status(invoices_to_overdue bigint[], invoices_to_defaulted bigint[], overdue_invoice_status smallint, defaulted_invoice_status smallint)` + - `try_prime_spicefield(in_source_server_id text, in_spicefield_id integer)` + - `try_restart_spicefield(in_server_id text, in_spicefield_type_id integer)` + - `try_spawn_spicefield(in_source_server_id text, in_spicefield_id integer)` + - `try_update_exchange_categories_hash(in_new_hash integer)` + - `unassign_partition(in_server_id text)` + - `update_communinet_player_channel(in_account_id bigint, in_channel_name text, in_is_tuned boolean)` + - `update_communinet_player_data(in_account_id bigint, in_is_active boolean, in_selected_channel_name text)` + - `update_consumed_per_player_lore(in_actor_id bigint, in_consumed_bit_array bit, in_use_temporary boolean)` + - `update_coriolis_for_player(in_controller_id bigint, OUT out_was_coriolis_processed boolean)` + - `update_death_location(in_pawn dune.actordescription, in_server_info dune.serverinfo, in_life_state dune.playerlifestate)` + - `update_farm_state(in_server_id text, in_outgoing_s2s_connections integer, in_incoming_s2s_connections integer, in_connected_players integer, in_farm_id text, in_igw_...)` + - `update_global_spice_field_rules(in_max_globally_primed integer, in_max_globally_active integer, in_spicefield_type_id integer)` + - `update_inventories_data(in_inventory_data_list dune.inventorydata[])` + - `update_inventory(in_delete_list bigint[], in_stack_update dune.itemstackupdate[], in_quality_update dune.itemqualityupdate[], in_stat_update dune.itemstatupdate[], ...)` + - `update_item_locations(in_item_locations dune.inventoryitemlocation[])` + - `update_journey_story_ids(old_story_ids text[], new_story_ids text[])` + - `update_marker_ids(in_old_ids integer[], in_new_ids integer[])` + - `update_partition_labels(in_allow_overwrite boolean)` + - `update_party_platform_session(in_party_id bigint, in_platform_session_id text, in_platform_name text)` + - `update_player_tags(in_account_id bigint, tags_to_add text[], tags_to_remove text[])` + - `update_removed_items_and_recipes(items_removed text[], recipes_removed text[])` + - `update_resourcefield_states(in_map text, in_dimension_index integer, in_field_kind_id smallint, in_field_states dune.resourcefieldstateentry[])` + - `update_respawn_locations(player_id bigint, respawn_locations dune.respawnlocation[])` + - `update_returning_player_status(in_user_id text, in_minimum_returning_player_time_seconds integer)` + - `update_sell_orders_categories(category_update_data dune.exchangecategoryupdatedata[])` + - `update_server_building_favorites(in_account_id bigint, in_building_types text[])` + - `update_server_learned_building_sets(in_account_id bigint, in_learned_building_sets text[])` + - `update_server_learned_new_buildable_pieces(in_account_id bigint, in_new_buildable_pieces text[])` + - `update_specialization_refund_id(in_player_id bigint, in_refund_id smallint, in_removed_keystones smallint[])` + - `update_spice_field_spawn_state(in_is_spawning_active boolean, in_spicefield_type_id integer)` + - `update_traveling_actor_dependencies(in_dep dune.traveldependency[])` + - `update_traveling_actor_tree(in_actor_id bigint, in_target_transform dune.transform, in_target_map text, in_target_dimension_index integer, in_target_partition_id bigint)` + - `update_universe_time(in_farm_id text)` + - `update_vendor_timestamp_for_player(in_vendor_id text, in_player_id bigint, in_timestamp bigint)` + - `upgrade_location_data_list(in_location_data_list jsonb, in_map_field_name text)` + - `upgrade_map_name(in_map_name text)` + - `upgrade_map_value(in_value jsonb)` + - `upsert_spicefield_types(in_max_globally_active integer[], in_max_globally_primed integer[], in_field_types text[], in_map_name text, in_dimension_index integer)` + - `use_sinkchart(in_player_id bigint, in_account_id bigint, in_area_id smallint, in_item_id bigint, in_sinkchart_map_name text, in_player_map_name text, in_player_c...)` + - `verify_item_dup_backup_tool(in_account_id bigint, in_vehicle_id bigint, in_cheat_type dune.cheat_type_enum)` + - `wipe_old_events_log(in_days_limit integer)` + - `zero_transform()` + +28. **Database table counts (active server):** + - `encrypted_accounts`: 10 rows, `encrypted_player_state`: 10 rows + - `actors`: 411 rows, `items`: 1,482, `inventories`: 459 + - `buildings`: 8, `vehicles`: 16, `guilds`: 1 (4 members) + - `bans`: 0, `factions`: 4 (Atreides, Harkonnen, Fremen, Corrino) + - `game_events`: 76, `chat_history`: unknown + - `dashboard.*` tables: `bans`, `chat_history`, `player_actions`, `player_ips` +29. **Dashboard Admin Experimental tab expanded with tools:** + - Search Players (via `admin_get_character_ids`) + - Online Players list (via `get_all_online_or_recently_disconnected_player_online_state()`) + - Adjust Currency (via direct SQL to `player_virtual_currency_balances`) + - View Currency Balances (via `get_player_virtual_currency_balances`) + - Change Faction (via direct SQL to `player_faction`) + - Faction Reputation View/Set (via `get_player_current_faction_reputation` / `set_player_faction_reputation`) + - Inventory Lookup (via `admin_get_inventory_details`) + - Teleport Player (via `admin_move_offline_player_to_partition`) + - Guild Tools: List, View, Disband, Kick Member (via `get_guild_data`, `disband_guild`, `remove_guild_members`) + - Player Tags: View & Update (via `admin_read_player_tags`, `update_player_tags`) + - Flag Cheater (via `flag_player_as_cheater`) + - Player Vehicles (via `get_player_owned_vehicles_data`) + - Player Stats Viewer (health, spice exposure, etc. from `actors.properties` JSONB) + - Character Management: rename, delete character, delete account, set demo state + - Journey & Specialization: complete/reveal/reset story nodes, set/reset specialization tracks + - Guild Roster: list members, promote/demote + - Economy: reset vendor stock for player, view tax invoices + - Spice Fields: force spice spawn, reset spice state + - Server Tools: set players offline, cleanup orphans + - Permissions: view actor permissions, set player rank + - Function Explorer: browse and execute all 517 DB functions dynamically with parameter input + - Battlegroup Info viewer (via BGD API `/v0/battlegroup`) + - (Broadcast via RMQ was already done in finding #22) + - API endpoints in `routes/api.py`: + - `POST /api/admin-experimental/broadcast` + - `POST /api/admin-experimental/query` (read-only SQL) + - `POST /api/admin-experimental/search-players` + - `GET /api/admin-experimental/online-players` + - `POST /api/admin-experimental/adjust-currency` + - `POST /api/admin-experimental/currency-balances` + - `POST /api/admin-experimental/change-faction` + - `POST /api/admin-experimental/faction-reputation` + - `POST /api/admin-experimental/inventory` + - `POST /api/admin-experimental/teleport` + - `GET /api/admin-experimental/partitions` + - `GET /api/admin-experimental/guilds` + - `POST /api/admin-experimental/guild-data` + - `POST /api/admin-experimental/disband-guild` + - `POST /api/admin-experimental/remove-guild-member` + - `POST /api/admin-experimental/player-tags` + - `POST /api/admin-experimental/flag-cheater` + - `POST /api/admin-experimental/player-vehicles` + - `POST /api/admin-experimental/player-stats` + - `POST /api/admin-experimental/set-character-name` + - `POST /api/admin-experimental/delete-character` + - `POST /api/admin-experimental/delete-account` + - `POST /api/admin-experimental/set-demo-state` + - `POST /api/admin-experimental/journey` + - `POST /api/admin-experimental/specialization` + - `POST /api/admin-experimental/guild-members` + - `POST /api/admin-experimental/clean-vendor-stock` + - `POST /api/admin-experimental/tax-invoices` + - `POST /api/admin-experimental/spice` + - `POST /api/admin-experimental/server-tools` + - `POST /api/admin-experimental/permissions` + - `GET /api/admin-experimental/functions` + - `GET /api/admin-experimental/functions/` + - `POST /api/admin-experimental/functions//execute` + - `GET /api/admin-experimental/battlegroup` + - `POST /api/admin-experimental/execute` (admin functions) +30. **Key insight about kubectl exec from dashboard:** The paramiko SSH `exec_command` doesn't support heredocs well. The working pattern for piping content into pods is: + - Write content to a temp file on VM host via `echo base64 | base64 -d | sudo tee /tmp/file` + - Then pipe into pod: `cat /tmp/file | sudo kubectl exec -i -n ns pod -- sh -lc 'cat > /tmp/pod_file && command "$(cat /tmp/pod_file)"'` + - Clean up both temp files after + +31. **`search_path` issue with DB functions:** PostgreSQL's default `search_path` is `"$user", public` — the `dune` schema is NOT on it. Any function defined in the `dune` schema that references tables without the `dune.` prefix (e.g., `accounts`, `player_state`, `actors`, `world_partition`) will fail when called from outside the schema. Our `teleport_player()` fix: run `SET search_path TO dune, public` before calling the function. This affects the teleport function `admin_move_offline_player_to_partition` and likely many of the 517 functions. + +32. **Table name correction:** The table is `dune.world_partition` (singular), NOT `dune.world_partitions` (plural). `accounts` and `player_state` are **views** in the `dune` schema, not physical tables. Other notable tables: + - `dune.actors` (physical) — id, class, map, owner_account_id, properties JSONB + - `dune.world_partition` — partition_id, server_id, map, dimension_index, label, blocked, partition_definition JSONB + - `dune.player_virtual_currency_balances` — player_controller_id, currency_id, balance + - `dune.player_faction` — actor_id, faction_id + - `dune.player_faction_reputation` — actor_id, faction_id, reputation_amount + - `dune.player_tags` — account_id, tag + - `dune.vehicles` — id, actor_id + - `dune.player_state` (view) — account_id, character_name, player_controller_id, player_pawn_id, online_status + - `dune.accounts` (view) — id, user + - `dune.encrypted_accounts` — id, user, platform_id + +--- + +## 13. TROUBLESHOOTING TIPS + +### PowerShell Quoting for SSH Commands +PowerShell interprets `$`, `|`, `>`, `<`, `&&`, `;`, `(`, `)` in SSH command strings. Workarounds: +```powershell +# Use single quotes for outer string +ssh -i user@host 'command with $vars' + +# Or pipe scripts via stdin +Get-Content script.sh -Raw | ssh "cat > /tmp/scr.sh && bash /tmp/scr.sh" +``` + +### TR Auth Testing +```bash +# From inside the VM: +sudo kubectl exec -n -- wget -q -O- \ + --post-data="username=&password=" \ + http://-tr-svc:5059/v0/auth/user +``` +Returns `allow` or `deny`. + +### Common NodePort Connection Issues +- SSH tunnel may drop (restart via dashboard launcher) +- Windows firewall may block connections to VM IP on non-standard ports +- AMQP connections require TLS (certificate from `/etc/rabbitmq/`) + +### Modifying RMQ ConfigMaps +The battlegroup operators continuously reconcile ConfigMaps. To make changes: +```bash +# 1. Scale down all operators +sudo kubectl scale deployment -n funcom-operators --replicas=0 \ + battlegroupoperator-controller-manager \ + databaseoperator-controller-manager \ + serveroperator-controller-manager \ + utilitiesoperator-controller-manager + +# 2. Make your ConfigMap changes (use kubectl replace with YAML file) +# 3. Restart affected pods +sudo kubectl delete pod -n + +# 4. Scale operators back up +sudo kubectl scale deployment -n funcom-operators --replicas=1 \ + battlegroupoperator-controller-manager \ + databaseoperator-controller-manager \ + serveroperator-controller-manager \ + utilitiesoperator-controller-manager +``` diff --git a/app/routes/api.py b/app/routes/api.py index b433140..fa13901 100644 --- a/app/routes/api.py +++ b/app/routes/api.py @@ -1215,3 +1215,535 @@ def register_api_routes(app, services, settings): except Exception as e: logger.error(f"Failed to toggle debug: {e}") return jsonify({'success': False, 'error': str(e)}), 500 + + # ── Admin Experimental: Broadcast ───────────────────────────────── + @app.route('/api/admin-experimental/broadcast', methods=['POST']) + @auth_req + @limiter.limit("100 per hour") + def admin_broadcast(): + data = request.get_json() or {} + title = (data.get('title') or '').strip() + message = (data.get('message') or '').strip() + try: + duration = int(data.get('duration', 30)) + except (ValueError, TypeError): + duration = 30 + if not title or not message: + return jsonify({'success': False, 'error': 'Title and message are required'}) + success, result = admin_svc.send_global_broadcast(title, message, duration) + return jsonify({'success': success, 'output': result}) + + # ── Admin Experimental: Query Database ──────────────────────────── + @app.route('/api/admin-experimental/query', methods=['POST']) + @auth_req + @limiter.limit("300 per hour") + def admin_query(): + data = request.get_json() or {} + sql = (data.get('sql') or '').strip() + if not sql: + return jsonify({'success': False, 'error': 'SQL is required'}) + lower = sql.strip().lower() + if not any(lower.startswith(w) for w in ('select', 'with', 'show', 'explain')): + return jsonify({'success': False, 'error': 'Only SELECT/WITH queries allowed'}) + result = admin_svc.admin_db_query(sql) + return jsonify({'success': True, 'rows': result or []}) + + # ── Admin Experimental: Search Players ──────────────────────────── + @app.route('/api/admin-experimental/search-players', methods=['POST']) + @auth_req + def admin_search_players(): + data = request.get_json() or {} + term = (data.get('term') or '').strip() + if not term: + return jsonify({'success': False, 'error': 'Search term required'}) + try: + results = admin_svc.search_players(term) + return jsonify({'success': True, 'players': results}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + # ── Admin Experimental: Online Players ───────────────────────────── + @app.route('/api/admin-experimental/online-players', methods=['GET']) + @auth_req + def admin_online_players(): + try: + players = admin_svc.get_online_players() + return jsonify({'success': True, 'players': players}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + # ── Admin Experimental: Adjust Currency ─────────────────────────── + @app.route('/api/admin-experimental/adjust-currency', methods=['POST']) + @auth_req + @limiter.limit("200 per hour") + def admin_adjust_currency(): + data = request.get_json() or {} + pid = data.get('player_controller_id') + cid = data.get('currency_id') + delta = data.get('delta') + if pid is None or cid is None or delta is None: + return jsonify({'success': False, 'error': 'player_controller_id, currency_id, and delta required'}) + success, result = admin_svc.adjust_currency(pid, int(cid), int(delta)) + return jsonify({'success': success, 'output': result}) + + # ── Admin Experimental: Change Faction ──────────────────────────── + @app.route('/api/admin-experimental/change-faction', methods=['POST']) + @auth_req + @limiter.limit("100 per hour") + def admin_change_faction(): + data = request.get_json() or {} + pid = data.get('player_id') + fid = data.get('faction_id') + if pid is None or fid is None: + return jsonify({'success': False, 'error': 'player_id and faction_id required'}) + success, result = admin_svc.change_faction(pid, int(fid)) + return jsonify({'success': success, 'output': result}) + + # ── Admin Experimental: Battlegroup Info ────────────────────────── + @app.route('/api/admin-experimental/battlegroup', methods=['GET']) + @auth_req + def admin_battlegroup(): + try: + out, err, rc = ssh.run("wget -qO- http://10.43.135.0:11717/v0/battlegroup", timeout=15) + if rc != 0 or not out: + return jsonify({'success': False, 'error': f'BGD unreachable: {err}'}) + parsed = json.loads(out) + return jsonify({'success': True, 'data': parsed}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + # ── Admin Experimental: View Currency Balances ──────────────────── + @app.route('/api/admin-experimental/currency-balances', methods=['POST']) + @auth_req + def admin_currency_balances(): + data = request.get_json() or {} + pcid = data.get('player_controller_id') + if not pcid: + return jsonify({'success': False, 'error': 'player_controller_id required'}) + try: + result = admin_svc.get_currency_balances(pcid) + return jsonify({'success': True, 'balances': result}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + # ── Admin Experimental: Teleport Player ─────────────────────────── + @app.route('/api/admin-experimental/teleport', methods=['POST']) + @auth_req + @limiter.limit("100 per hour") + def admin_teleport(): + data = request.get_json() or {} + fls_id = data.get('fls_id') + partition_id = data.get('partition_id') + x = data.get('x', 0) + y = data.get('y', 0) + z = data.get('z', 0) + if not fls_id or not partition_id: + return jsonify({'success': False, 'error': 'fls_id and partition_id required'}) + try: + success, msg = admin_svc.teleport_player(fls_id, int(partition_id), float(x), float(y), float(z)) + return jsonify({'success': success, 'output': msg}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + @app.route('/api/admin-experimental/partitions', methods=['GET']) + @auth_req + def admin_partitions(): + try: + partitions = admin_svc.get_partitions() + return jsonify({'success': True, 'partitions': partitions}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + # ── Admin Experimental: Faction Reputation ──────────────────────── + @app.route('/api/admin-experimental/faction-reputation', methods=['POST']) + @auth_req + def admin_faction_reputation(): + data = request.get_json() or {} + actor_id = data.get('actor_id') + if not actor_id: + return jsonify({'success': False, 'error': 'actor_id required'}) + try: + # GET mode + if 'set' not in data: + result = admin_svc.get_faction_reputation(actor_id) + return jsonify({'success': True, 'reputation': result}) + else: + success, msg = admin_svc.set_faction_reputation(actor_id, int(data['faction_id']), int(data['amount'])) + return jsonify({'success': success, 'output': msg}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + # ── Admin Experimental: Inventory Lookup ────────────────────────── + @app.route('/api/admin-experimental/inventory', methods=['POST']) + @auth_req + def admin_inventory(): + data = request.get_json() or {} + account_id = data.get('account_id') + if not account_id: + return jsonify({'success': False, 'error': 'account_id required'}) + try: + inv = admin_svc.get_inventory(account_id) + pawn = admin_svc.get_player_pawn(account_id) + return jsonify({'success': True, 'inventory': inv, 'pawn': pawn}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + # ── Admin Experimental: Guild Tools ──────────────────────────────── + @app.route('/api/admin-experimental/guilds', methods=['GET']) + @auth_req + def admin_guilds(): + try: + guilds = admin_svc.get_all_guilds() + return jsonify({'success': True, 'guilds': guilds}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + @app.route('/api/admin-experimental/guild-data', methods=['POST']) + @auth_req + def admin_guild_data(): + data = request.get_json() or {} + guild_id = data.get('guild_id') + if not guild_id: + return jsonify({'success': False, 'error': 'guild_id required'}) + try: + guild = admin_svc.get_guild_data(guild_id) + return jsonify({'success': True, 'guild': guild}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + @app.route('/api/admin-experimental/disband-guild', methods=['POST']) + @auth_req + @limiter.limit("50 per hour") + def admin_disband_guild(): + data = request.get_json() or {} + guild_id = data.get('guild_id') + if not guild_id: + return jsonify({'success': False, 'error': 'guild_id required'}) + try: + success, msg = admin_svc.disband_guild(guild_id) + return jsonify({'success': success, 'output': msg}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + @app.route('/api/admin-experimental/remove-guild-member', methods=['POST']) + @auth_req + @limiter.limit("100 per hour") + def admin_remove_guild_member(): + data = request.get_json() or {} + guild_id = data.get('guild_id') + player_id = data.get('player_id') + if not guild_id or not player_id: + return jsonify({'success': False, 'error': 'guild_id and player_id required'}) + try: + success, msg = admin_svc.remove_guild_member(guild_id, player_id) + return jsonify({'success': success, 'output': msg}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + # ── Admin Experimental: Player Tags ──────────────────────────────── + @app.route('/api/admin-experimental/player-tags', methods=['POST']) + @auth_req + def admin_player_tags(): + data = request.get_json() or {} + account_id = data.get('account_id') + if not account_id: + return jsonify({'success': False, 'error': 'account_id required'}) + try: + if 'tags_to_add' in data or 'tags_to_remove' in data: + success, msg = admin_svc.update_player_tags(account_id, data.get('tags_to_add', []), data.get('tags_to_remove', [])) + return jsonify({'success': success, 'output': msg}) + else: + tags = admin_svc.get_player_tags(account_id) + return jsonify({'success': True, 'tags': tags}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + @app.route('/api/admin-experimental/flag-cheater', methods=['POST']) + @auth_req + @limiter.limit("50 per hour") + def admin_flag_cheater(): + data = request.get_json() or {} + account_id = data.get('account_id') + cheat_type = data.get('cheat_type', 'manual') + if not account_id: + return jsonify({'success': False, 'error': 'account_id required'}) + try: + success, msg = admin_svc.flag_cheater(account_id, cheat_type) + return jsonify({'success': success, 'output': msg}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + # ── Admin Experimental: Player Vehicles ─────────────────────────── + @app.route('/api/admin-experimental/player-vehicles', methods=['POST']) + @auth_req + def admin_player_vehicles(): + data = request.get_json() or {} + player_id = data.get('player_id') + account_id = data.get('account_id') + if not player_id or not account_id: + return jsonify({'success': False, 'error': 'player_id and account_id required'}) + try: + vehicles = admin_svc.get_player_vehicles(player_id, account_id) + return jsonify({'success': True, 'vehicles': vehicles}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + # ── Admin Experimental: Player Stats ────────────────────────────── + @app.route('/api/admin-experimental/player-stats', methods=['POST']) + @auth_req + def admin_player_stats(): + data = request.get_json() or {} + pcid = data.get('player_controller_id') + if not pcid: + return jsonify({'success': False, 'error': 'player_controller_id required'}) + try: + stats = admin_svc.get_player_stats(pcid) + return jsonify({'success': True, 'stats': stats}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + # ── Admin Experimental: Character Management ────────────────────── + @app.route('/api/admin-experimental/set-character-name', methods=['POST']) + @auth_req + def admin_set_character_name(): + data = request.get_json() or {} + account_id = data.get('account_id') + name = data.get('name', '').strip() + if not account_id or not name: + return jsonify({'success': False, 'error': 'account_id and name required'}) + try: + success, msg = admin_svc.set_character_name(account_id, name) + return jsonify({'success': success, 'output': msg}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + @app.route('/api/admin-experimental/delete-character', methods=['POST']) + @auth_req + @limiter.limit("20 per hour") + def admin_delete_character(): + data = request.get_json() or {} + actor_id = data.get('actor_id') + if not actor_id: + return jsonify({'success': False, 'error': 'actor_id required'}) + try: + success, msg = admin_svc.delete_character(actor_id) + return jsonify({'success': success, 'output': msg}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + @app.route('/api/admin-experimental/delete-account', methods=['POST']) + @auth_req + @limiter.limit("10 per hour") + def admin_delete_account(): + data = request.get_json() or {} + user_id = data.get('user_id') + reason = data.get('reason', 'admin') + if not user_id: + return jsonify({'success': False, 'error': 'user_id required'}) + try: + success, msg = admin_svc.delete_account(user_id, reason) + return jsonify({'success': success, 'output': msg}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + @app.route('/api/admin-experimental/set-demo-state', methods=['POST']) + @auth_req + def admin_set_demo_state(): + data = request.get_json() or {} + user_id = data.get('user_id') + demo_state = data.get('demo_state', 'none') + if not user_id: + return jsonify({'success': False, 'error': 'user_id required'}) + try: + success, msg = admin_svc.set_demo_state(user_id, demo_state) + return jsonify({'success': success, 'output': msg}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + # ── Admin Experimental: Journey / Progression ───────────────────── + @app.route('/api/admin-experimental/journey', methods=['POST']) + @auth_req + def admin_journey(): + data = request.get_json() or {} + account_id = data.get('account_id') + node_ids = data.get('node_ids', []) + action = data.get('action', 'complete') + if not account_id or not node_ids: + return jsonify({'success': False, 'error': 'account_id and node_ids required'}) + try: + if action == 'complete': + success, msg = admin_svc.complete_journey_nodes(account_id, node_ids) + elif action == 'reveal': + success, msg = admin_svc.reveal_journey_nodes(account_id, node_ids) + elif action == 'reset': + success, msg = admin_svc.reset_journey_nodes(account_id, node_ids) + else: + return jsonify({'success': False, 'error': 'Invalid action'}) + return jsonify({'success': success, 'output': msg}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + @app.route('/api/admin-experimental/specialization', methods=['POST']) + @auth_req + def admin_specialization(): + data = request.get_json() or {} + player_id = data.get('player_id') + if not player_id: + return jsonify({'success': False, 'error': 'player_id required'}) + try: + if 'reset' in data: + success, msg = admin_svc.reset_specialization(player_id) + else: + track = data.get('track_type', 'combat') + xp = data.get('xp', 0) + level = data.get('level', 1) + success, msg = admin_svc.set_specialization(player_id, track, xp, level) + return jsonify({'success': success, 'output': msg}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + # ── Admin Experimental: Guild Roster ────────────────────────────── + @app.route('/api/admin-experimental/guild-members', methods=['POST']) + @auth_req + def admin_guild_members(): + data = request.get_json() or {} + guild_id = data.get('guild_id') + if not guild_id: + return jsonify({'success': False, 'error': 'guild_id required'}) + try: + if 'promote' in data: + success, msg = admin_svc.promote_guild_member(guild_id, data['player_id'], data['new_role']) + return jsonify({'success': success, 'output': msg}) + else: + members = admin_svc.get_guild_members(guild_id) + return jsonify({'success': True, 'members': members}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + # ── Admin Experimental: Economy ─────────────────────────────────── + @app.route('/api/admin-experimental/clean-vendor-stock', methods=['POST']) + @auth_req + def admin_clean_vendor_stock(): + data = request.get_json() or {} + player_id = data.get('player_id') + if not player_id: + return jsonify({'success': False, 'error': 'player_id required'}) + try: + success, msg = admin_svc.clean_player_vendor_stock(player_id) + return jsonify({'success': success, 'output': msg}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + @app.route('/api/admin-experimental/tax-invoices', methods=['POST']) + @auth_req + def admin_tax_invoices(): + data = request.get_json() or {} + player_id = data.get('player_id') + if not player_id: + return jsonify({'success': False, 'error': 'player_id required'}) + try: + invoices = admin_svc.get_player_tax_invoices(player_id) + return jsonify({'success': True, 'invoices': invoices}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + # ── Admin Experimental: Spice Fields ────────────────────────────── + @app.route('/api/admin-experimental/spice', methods=['POST']) + @auth_req + @limiter.limit("30 per hour") + def admin_spice(): + data = request.get_json() or {} + try: + if data.get('action') == 'reset': + success, msg = admin_svc.reset_spice_state(data['map_name'], data.get('dimension_index', 0)) + else: + success, msg = admin_svc.force_spice_spawn(data['server_id'], data['spicefield_type_id']) + return jsonify({'success': success, 'output': msg}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + # ── Admin Experimental: Server Tools ────────────────────────────── + @app.route('/api/admin-experimental/server-tools', methods=['POST']) + @auth_req + @limiter.limit("30 per hour") + def admin_server_tools(): + data = request.get_json() or {} + try: + if data.get('action') == 'set_offline': + success, msg = admin_svc.set_players_offline(data.get('server_ids', [])) + elif data.get('action') == 'cleanup_orphans': + success, msg = admin_svc.cleanup_orphaned() + else: + return jsonify({'success': False, 'error': 'Invalid action'}) + return jsonify({'success': success, 'output': msg}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + # ── Admin Experimental: Permissions ────────────────────────────── + @app.route('/api/admin-experimental/permissions', methods=['POST']) + @auth_req + def admin_permissions(): + data = request.get_json() or {} + try: + if 'set_rank' in data: + success, msg = admin_svc.set_player_rank(data['actor_id'], data['player_id'], data['rank'], data.get('map_id', '')) + return jsonify({'success': success, 'output': msg}) + elif data.get('actor_id'): + perms = admin_svc.get_actor_permissions(data['actor_id']) + return jsonify({'success': True, 'permissions': perms}) + else: + return jsonify({'success': False, 'error': 'actor_id required'}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + # ── Admin Experimental: Function Explorer ───────────────────────── + @app.route('/api/admin-experimental/functions', methods=['GET']) + @auth_req + def admin_list_functions(): + try: + funcs = admin_svc.list_all_functions() + return jsonify({'success': True, 'functions': funcs}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + @app.route('/api/admin-experimental/functions/', methods=['GET']) + @auth_req + def admin_function_details(name): + try: + detail = admin_svc.get_function_details(name) + if not detail: + return jsonify({'success': False, 'error': 'Function not found'}) + return jsonify({'success': True, 'function': detail}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + @app.route('/api/admin-experimental/functions//execute', methods=['POST']) + @auth_req + @limiter.limit("200 per hour") + def admin_execute_function(name): + data = request.get_json() or {} + params = data.get('params', []) + try: + success, result, error = admin_svc.execute_function(name, params) + if success: + return jsonify({'success': True, 'result': result}) + else: + return jsonify({'success': False, 'error': error}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + # ── Admin Experimental: SQL Execute (admin functions) ───────────── + @app.route('/api/admin-experimental/execute', methods=['POST']) + @auth_req + @limiter.limit("200 per hour") + def admin_execute(): + data = request.get_json() or {} + sql = (data.get('sql') or '').strip() + if not sql: + return jsonify({'success': False, 'error': 'SQL is required'}) + lower = sql.strip().lower() + allowed_prefixes = ('select', 'with', 'insert', 'update', 'delete', 'call', 'show', 'explain') + if not any(lower.startswith(w) for w in allowed_prefixes): + return jsonify({'success': False, 'error': 'SQL prefix not allowed'}) + success, result = admin_svc.admin_db_execute(sql) + return jsonify({'success': success, 'result': result if success else str(result)}) diff --git a/app/routes/main.py b/app/routes/main.py index 6cac187..db429d8 100644 --- a/app/routes/main.py +++ b/app/routes/main.py @@ -488,6 +488,12 @@ def register_routes(app, services, settings): logger.exception("Error in server_status route") return render_template('server.html', db_error=f"{type(e).__name__}: {e}") + # Admin Experimental + @app.route('/admin-experimental') + @login_required + def admin_experimental(): + return render_template('admin_experimental.html') + # Map - shows locations of players, vehicles, buildings @app.route('/map') @login_required diff --git a/app/services/admin.py b/app/services/admin.py index 769213e..654dd0a 100644 --- a/app/services/admin.py +++ b/app/services/admin.py @@ -1,10 +1,14 @@ -"""Admin service - ban, kick, unban, vitals, IP detection""" - +"""Admin service - ban, kick, unban, vitals, IP detection, broadcast""" + import re import time import threading import logging import ipaddress +import tempfile +import os +import json +import psycopg2.extras logger = logging.getLogger(__name__) audit_logger = logging.getLogger('audit') @@ -803,3 +807,851 @@ class AdminService: if cur: cur.close() self.db.return_connection(conn) + + def send_global_broadcast(self, title, message, duration=30): + """Send an in-game broadcast via RabbitMQ rabbitmqctl eval on the VM.""" + try: + import base64 + import json as _json + title_json = _json.dumps(title)[1:-1] + message_json = _json.dumps(message)[1:-1] + + erl = ( + f'Title = unicode:characters_to_binary(<<"{title_json}">>, utf8), ' + f'Body = unicode:characters_to_binary(<<"{message_json}">>, utf8), ' + f'Duration = {duration}, ' + 'EntryEn = #{<<"Key">> => <<"en">>, <<"Title">> => Title, <<"Body">> => Body}, ' + 'EntryEnUs = #{<<"Key">> => <<"en-US">>, <<"Title">> => Title, <<"Body">> => Body}, ' + 'Inner = iolist_to_binary(rabbit_json:encode(#{<<"ServerCommand">> => <<"ServiceBroadcast">>, <<"BroadcastType">> => <<"Generic">>, <<"BroadcastPayload">> => #{<<"BroadcastDuration">> => Duration, <<"LocalizedText">> => [EntryEn, EntryEnUs]}})), ' + 'Outer = iolist_to_binary(rabbit_json:encode(#{<<"Version">> => 2, <<"AuthToken">> => <<"Nu6VmPWUMvdPMeB7qErr">>, <<"MessageContent">> => Inner})), ' + 'XName = rabbit_misc:r(<<"/">>, exchange, <<"heartbeats">>), ' + 'X = rabbit_exchange:lookup_or_die(XName), ' + 'MsgId = list_to_binary("manual-service-broadcast-" ++ integer_to_list(erlang:system_time(millisecond))), ' + 'P = {list_to_atom("P_basic"), <<"Content">>, undefined, [], undefined, undefined, undefined, undefined, undefined, MsgId, undefined, undefined, <<"fls">>, <<"fls_backend">>, undefined}, ' + 'Content = rabbit_basic:build_content(P, Outer), ' + '{ok, Msg} = rabbit_basic:message(XName, <<"notifications">>, Content), ' + 'Result = rabbit_queue_type:publish_at_most_once(X, Msg), ' + 'io:format("broadcast=~p duration=~p~n", [Result, Duration]).' + ) + + ns = self._detect_namespace() + pod_name = ns.replace('funcom-seabass-', '') + '-mq-game-sts-0' + b64 = base64.b64encode(erl.encode()).decode() + + # Write erl on VM host, then pipe it into the pod via kubectl exec -i + wcmd = f"echo {b64} | base64 -d | sudo tee /tmp/dune_bc.erl > /dev/null" + wout, werr, wrc = self.ssh.run(wcmd) + if wrc != 0: + return False, f"write failed: {werr}" + + # Cat the host file and pipe into kubectl exec -i to write inside the pod + ecmd = ( + f"cat /tmp/dune_bc.erl | sudo kubectl exec -i -n {ns} {pod_name} -- sh -lc '" + "cat > /tmp/dune_bc.erl; " + "export PATH=/opt/rabbitmq/sbin:/opt/erlang/lib/erlang/bin:/opt/erlang/lib/erlang/erts-14.2.5.12/bin:/bin:/usr/bin:/usr/local/bin:$PATH; " + 'rabbitmqctl eval "$(cat /tmp/dune_bc.erl)"; ' + "rm -f /tmp/dune_bc.erl'" + ) + out, err, rc = self.ssh.run(ecmd) + + self.ssh.run("rm -f /tmp/dune_bc.erl") + + if rc != 0: + return False, f"Broadcast failed (rc={rc}): {err}" + + audit_logger.info(f"BROADCAST: title={title} message={message} duration={duration}") + return True, "Broadcast sent successfully" + except Exception as e: + logger.error(f"Broadcast error: {e}") + try: + self.ssh.run("rm -f /tmp/dune_bc.erl") + except Exception: + pass + return False, str(e) + + def admin_db_query(self, sql, params=None): + """Execute a read-only SQL query and return results.""" + return self.db.query(sql, params) + + def admin_db_execute(self, sql, params=None): + """Execute a SQL statement (insert/update/delete/call) and commit.""" + conn = self.db.get_connection() + if not conn: + return False, "DB connection failed" + cur = None + try: + cur = conn.cursor() + cur.execute(sql, params or []) + conn.commit() + if cur.description: + rows = cur.fetchall() + if rows and isinstance(rows[0], dict): + return True, rows + cols = [d.name for d in cur.description] + return True, [dict(zip(cols, r)) for r in rows] + return True, f"Executed, rows affected: {cur.rowcount}" + except Exception as e: + conn.rollback() + return False, str(e) + finally: + if cur: + cur.close() + self.db.return_connection(conn) + + def search_players(self, term): + """Search characters by name.""" + like = f'%{term}%' + result = self.db.query(""" + SELECT ea.id, ea.user, + COALESCE(NULLIF(ps.character_name, ''), 'Unknown') as character_name + FROM dune.encrypted_accounts ea + LEFT JOIN dune.player_state ps ON ea.id = ps.account_id + WHERE lower(ea.user) LIKE lower(%s) + OR lower(ps.character_name) LIKE lower(%s) + ORDER BY ea.user + LIMIT 50 + """, [like, like]) + return result or [] + + def get_online_players(self): + """Get all online or recently disconnected players.""" + result = self.db.query(""" + SELECT a.id as player_controller_id, + COALESCE(NULLIF(ps.character_name, ''), 'Unknown') as character_name, + a.map, + ps.online_status, + ps.last_avatar_activity + FROM dune.actors a + JOIN dune.player_state ps ON ps.player_controller_id = a.id + WHERE ps.online_status = 'Online' + OR ps.last_avatar_activity > NOW() - INTERVAL '1 minute' + ORDER BY ps.character_name + """) + return result or [] + + def adjust_currency(self, player_controller_id, currency_id, delta): + """Add/remove virtual currency from a player.""" + try: + conn = self.db.get_connection() + if not conn: + return False, "DB connection failed" + cur = None + try: + cur = conn.cursor() + cur.execute(""" + INSERT INTO dune.player_virtual_currency_balances (player_controller_id, currency_id, balance) + VALUES (%s, %s, %s) + ON CONFLICT (player_controller_id, currency_id) DO UPDATE SET balance = (dune.player_virtual_currency_balances.balance + %s) + RETURNING balance + """, [player_controller_id, currency_id, delta, delta]) + new_balance = cur.fetchone()[0] + conn.commit() + audit_logger.info(f"CURRENCY_ADJUST: player={player_controller_id} currency={currency_id} delta={delta} new_balance={new_balance}") + return True, f"Currency {currency_id} adjusted by {delta}. New balance: {new_balance}" + except Exception as e: + conn.rollback() + return False, str(e) + finally: + if cur: + cur.close() + self.db.return_connection(conn) + except Exception as e: + return False, str(e) + + def change_faction(self, player_id, faction_id): + """Change a player's faction.""" + try: + conn = self.db.get_connection() + if not conn: + return False, "DB connection failed" + cur = None + try: + cur = conn.cursor() + cur.execute(""" + INSERT INTO dune.player_faction (actor_id, faction_id, utc_time_faction_change) + VALUES (%s, %s, NOW()) + ON CONFLICT (actor_id) DO UPDATE SET faction_id = %s, utc_time_faction_change = NOW() + """, [player_id, faction_id, faction_id]) + conn.commit() + audit_logger.info(f"FACTION_CHANGE: player={player_id} faction={faction_id}") + return True, f"Faction changed to {faction_id}" + except Exception as e: + conn.rollback() + return False, str(e) + finally: + if cur: + cur.close() + self.db.return_connection(conn) + except Exception as e: + return False, str(e) + + # ── View Currency Balances ───────────────────────────────────────── + def get_currency_balances(self, player_controller_id): + """Get virtual currency balances for a player.""" + result = self.db.query( + "SELECT currency_id, balance FROM dune.player_virtual_currency_balances WHERE player_controller_id = %s ORDER BY currency_id", + [player_controller_id] + ) + return result or [] + + # ── Teleport Player ──────────────────────────────────────────────── + def teleport_player(self, fls_id, partition_id, x, y, z): + """Teleport an offline player to a partition using direct SQL.""" + conn = self.db.get_connection() + if not conn: + return False, "DB connection failed" + cur = None + try: + cur = conn.cursor() + # Set search_path so unqualified references in the function resolve + cur.execute("SET search_path TO dune, public") + cur.execute(""" + SELECT dune.admin_move_offline_player_to_partition( + %s, %s, ROW(%s, %s, %s)::dune.vector + ) + """, [fls_id, int(partition_id), float(x), float(y), float(z)]) + conn.commit() + audit_logger.info(f"TELEPORT: fls_id={fls_id} partition={partition_id} loc=({x},{y},{z})") + return True, f"Teleported to partition {partition_id}" + except Exception as e: + conn.rollback() + return False, str(e) + finally: + if cur: cur.close() + self.db.return_connection(conn) + + def get_partitions(self): + """List all available partitions.""" + result = self.db.query(""" + SELECT partition_id as id, map, dimension_index, label, partition_definition::text + FROM dune.world_partition + ORDER BY map, dimension_index, partition_id + LIMIT 100 + """) + return result or [] + + # ── Faction Reputation (direct SQL) ──────────────────────────────── + def get_faction_reputation(self, actor_id): + """Get faction reputation for a player.""" + result = self.db.query(""" + SELECT pf.faction_id, COALESCE(pfr.reputation_amount, 0) as reputation_amount + FROM dune.player_faction pf + LEFT JOIN dune.player_faction_reputation pfr ON pfr.actor_id = pf.actor_id AND pfr.faction_id = pf.faction_id + WHERE pf.actor_id = %s + LIMIT 1 + """, [actor_id]) + return result or [] + + def set_faction_reputation(self, actor_id, faction_id, amount): + """Set faction reputation for a player.""" + try: + conn = self.db.get_connection() + if not conn: + return False, "DB connection failed" + cur = None + try: + cur = conn.cursor() + cur.execute(""" + INSERT INTO dune.player_faction_reputation (actor_id, faction_id, reputation_amount) + VALUES (%s, %s, %s) + ON CONFLICT (actor_id, faction_id) DO UPDATE SET reputation_amount = %s + """, [actor_id, faction_id, amount, amount]) + conn.commit() + audit_logger.info(f"FACTION_REP: actor={actor_id} faction={faction_id} amount={amount}") + return True, f"Reputation set to {amount}" + except Exception as e: + conn.rollback() + return False, str(e) + finally: + if cur: cur.close() + self.db.return_connection(conn) + except Exception as e: + return False, str(e) + + # ── Inventory Lookup (direct SQL) ───────────────────────────────── + def get_inventory(self, account_id): + """Get inventory details for an account.""" + result = self.db.query(""" + SELECT inv.id as inventory_id, inv.actor_id, i.id as item_id, i.template_id, i.stack_size as count, i.position_index + FROM dune.inventories inv + JOIN dune.items i ON i.inventory_id = inv.id + WHERE inv.actor_id IN (SELECT id FROM dune.actors WHERE owner_account_id = %s) + ORDER BY inv.id, i.position_index + LIMIT 200 + """, [account_id]) + return result or [] + + def get_player_pawn(self, account_id): + """Get player pawn info by account id.""" + result = self.db.query(""" + SELECT a.id, a.class, a.map, a.owner_account_id as account_id + FROM dune.actors a + WHERE a.owner_account_id = %s AND a.class LIKE '%%PlayerPawn_C%%' + LIMIT 5 + """, [account_id]) + return result or [] + + # ── Guild Tools (direct SQL) ─────────────────────────────────────── + def get_guild_data(self, guild_id): + """Get guild data.""" + result = self.db.query(""" + SELECT g.*, + (SELECT COUNT(*) FROM dune.guild_members gm WHERE gm.guild_id = g.id) as member_count + FROM dune.guilds g WHERE g.id = %s + """, [guild_id]) + return result or [] + + def get_all_guilds(self): + """Get all guilds.""" + result = self.db.query(""" + SELECT g.*, + (SELECT COUNT(*) FROM dune.guild_members gm WHERE gm.guild_id = g.id) as member_count + FROM dune.guilds g + ORDER BY g.id + """) + return result or [] + + def disband_guild(self, guild_id): + """Disband a guild via function.""" + try: + conn = self.db.get_connection() + if not conn: + return False, "DB connection failed" + cur = None + try: + cur = conn.cursor() + cur.execute("SELECT dune.disband_guild(%s)", [guild_id]) + conn.commit() + audit_logger.info(f"GUILD_DISBAND: guild_id={guild_id}") + return True, f"Guild {guild_id} disbanded" + except Exception as e: + conn.rollback() + return False, str(e) + finally: + if cur: cur.close() + self.db.return_connection(conn) + except Exception as e: + return False, str(e) + + def remove_guild_member(self, guild_id, player_id): + """Remove a member from a guild.""" + try: + conn = self.db.get_connection() + if not conn: + return False, "DB connection failed" + cur = None + try: + cur = conn.cursor() + cur.execute("DELETE FROM dune.guild_members WHERE guild_id = %s AND player_id = %s", [guild_id, player_id]) + conn.commit() + audit_logger.info(f"GUILD_KICK: guild={guild_id} player={player_id}") + return True, f"Player {player_id} removed from guild" + except Exception as e: + conn.rollback() + return False, str(e) + finally: + if cur: cur.close() + self.db.return_connection(conn) + except Exception as e: + return False, str(e) + + # ── Player Tags (direct SQL) ─────────────────────────────────────── + def get_player_tags(self, account_id): + """Read player tags.""" + result = self.db.query( + "SELECT tag FROM dune.player_tags WHERE account_id = %s ORDER BY tag", + [account_id] + ) + return result or [] + + def update_player_tags(self, account_id, tags_to_add, tags_to_remove): + """Update player tags.""" + try: + conn = self.db.get_connection() + if not conn: + return False, "DB connection failed" + cur = None + try: + cur = conn.cursor() + for tag in tags_to_add: + cur.execute( + "INSERT INTO dune.player_tags (account_id, tag) VALUES (%s, %s) ON CONFLICT DO NOTHING", + [account_id, tag] + ) + if tags_to_remove: + cur.execute( + "DELETE FROM dune.player_tags WHERE account_id = %s AND tag = ANY(%s)", + [account_id, tags_to_remove] + ) + conn.commit() + audit_logger.info(f"TAGS_UPDATE: account={account_id} add={tags_to_add} remove={tags_to_remove}") + return True, "Tags updated" + except Exception as e: + conn.rollback() + return False, str(e) + finally: + if cur: cur.close() + self.db.return_connection(conn) + except Exception as e: + return False, str(e) + + def flag_cheater(self, account_id, cheat_type): + """Flag a player as cheater.""" + try: + conn = self.db.get_connection() + if not conn: + return False, "DB connection failed" + cur = None + try: + cur = conn.cursor() + # Add cheater tag + cur.execute( + "INSERT INTO dune.player_tags (account_id, tag) VALUES (%s, %s) ON CONFLICT DO NOTHING", + [account_id, f'cheater_{cheat_type}'] + ) + conn.commit() + audit_logger.info(f"CHEATER_FLAG: account={account_id} type={cheat_type}") + return True, f"Flagged as {cheat_type}" + except Exception as e: + conn.rollback() + return False, str(e) + finally: + if cur: cur.close() + self.db.return_connection(conn) + except Exception as e: + return False, str(e) + + # ── Vehicles (direct SQL) ───────────────────────────────────────── + def get_player_vehicles(self, player_id, account_id): + """Get vehicles owned by a player.""" + result = self.db.query(""" + SELECT v.id as vehicle_id, v.actor_id, a.class, a.map, a.owner_account_id as account_id + FROM dune.vehicles v + JOIN dune.actors a ON a.id = v.actor_id + WHERE a.owner_account_id = %s + ORDER BY v.id + LIMIT 50 + """, [account_id]) + return result or [] + + # ── Character Management ─────────────────────────────────────────── + def set_character_name(self, account_id, new_name): + """Rename a character.""" + try: + conn = self.db.get_connection() + if not conn: return False, "DB connection failed" + cur = None + try: + cur = conn.cursor() + cur.execute("UPDATE dune.player_state SET character_name = %s WHERE account_id = %s", [new_name, account_id]) + conn.commit() + audit_logger.info(f"RENAME: account={account_id} new_name={new_name}") + return True, f"Renamed to {new_name}" + except Exception as e: + conn.rollback(); return False, str(e) + finally: + if cur: cur.close(); self.db.return_connection(conn) + except Exception as e: return False, str(e) + + def delete_character(self, actor_id): + """Delete a character.""" + try: + conn = self.db.get_connection() + if not conn: return False, "DB connection failed" + cur = None + try: + cur = conn.cursor() + cur.execute("SELECT dune.delete_character(%s)", [actor_id]) + conn.commit() + audit_logger.info(f"DELETE_CHAR: actor_id={actor_id}") + return True, f"Character {actor_id} deleted" + except Exception as e: + conn.rollback(); return False, str(e) + finally: + if cur: cur.close(); self.db.return_connection(conn) + except Exception as e: return False, str(e) + + def delete_account(self, user_id, reason='admin'): + """Delete an account.""" + try: + conn = self.db.get_connection() + if not conn: return False, "DB connection failed" + cur = None + try: + cur = conn.cursor() + cur.execute("SELECT dune.delete_account(%s, %s)", [user_id, reason]) + conn.commit() + audit_logger.info(f"DELETE_ACCOUNT: user={user_id} reason={reason}") + return True, f"Account {user_id} deleted" + except Exception as e: + conn.rollback(); return False, str(e) + finally: + if cur: cur.close(); self.db.return_connection(conn) + except Exception as e: return False, str(e) + + def set_demo_state(self, user_id, demo_state): + """Set demo state for an account.""" + try: + conn = self.db.get_connection() + if not conn: return False, "DB connection failed" + cur = None + try: + cur = conn.cursor() + cur.execute("SELECT dune.set_demo_state(%s, %s::dune.demostate)", [user_id, demo_state]) + conn.commit() + audit_logger.info(f"DEMO: user={user_id} state={demo_state}") + return True, f"Demo state set to {demo_state}" + except Exception as e: + conn.rollback(); return False, str(e) + finally: + if cur: cur.close(); self.db.return_connection(conn) + except Exception as e: return False, str(e) + + # ── Journey / Progression ───────────────────────────────────────── + def complete_journey_nodes(self, account_id, node_ids): + """Complete journey story nodes for a player.""" + try: + conn = self.db.get_connection() + if not conn: return False, "DB connection failed" + cur = None + try: + cur = conn.cursor() + cur.execute("SELECT dune.complete_journey_story_nodes_for_player(%s, %s)", [str(account_id), node_ids]) + conn.commit() + audit_logger.info(f"JOURNEY_COMPLETE: account={account_id} nodes={node_ids}") + return True, f"Completed {len(node_ids)} nodes" + except Exception as e: + conn.rollback(); return False, str(e) + finally: + if cur: cur.close(); self.db.return_connection(conn) + except Exception as e: return False, str(e) + + def reveal_journey_nodes(self, account_id, node_ids): + """Reveal journey story nodes for a player.""" + try: + conn = self.db.get_connection() + if not conn: return False, "DB connection failed" + cur = None + try: + cur = conn.cursor() + cur.execute("SELECT dune.reveal_journey_story_nodes_for_player(%s, %s)", [str(account_id), node_ids]) + conn.commit() + audit_logger.info(f"JOURNEY_REVEAL: account={account_id} nodes={node_ids}") + return True, f"Revealed {len(node_ids)} nodes" + except Exception as e: + conn.rollback(); return False, str(e) + finally: + if cur: cur.close(); self.db.return_connection(conn) + except Exception as e: return False, str(e) + + def reset_journey_nodes(self, account_id, node_ids): + """Reset journey story nodes for a player.""" + try: + conn = self.db.get_connection() + if not conn: return False, "DB connection failed" + cur = None + try: + cur = conn.cursor() + cur.execute("SELECT dune.reset_journey_story_nodes_for_player(%s, %s)", [str(account_id), node_ids]) + conn.commit() + audit_logger.info(f"JOURNEY_RESET: account={account_id} nodes={node_ids}") + return True, f"Reset {len(node_ids)} nodes" + except Exception as e: + conn.rollback(); return False, str(e) + finally: + if cur: cur.close(); self.db.return_connection(conn) + except Exception as e: return False, str(e) + + def set_specialization(self, player_id, track_type, xp, level): + """Set specialization XP and level.""" + try: + conn = self.db.get_connection() + if not conn: return False, "DB connection failed" + cur = None + try: + cur = conn.cursor() + # track_type is a dune.specializationtracktype enum + cur.execute( + "SELECT dune.set_specialization_xp_and_level(%s, %s::dune.specializationtracktype, %s, %s)", + [player_id, track_type, xp, level] + ) + conn.commit() + audit_logger.info(f"SPEC_SET: player={player_id} track={track_type} xp={xp} level={level}") + return True, f"Specialization {track_type} set to level {level}" + except Exception as e: + conn.rollback(); return False, str(e) + finally: + if cur: cur.close(); self.db.return_connection(conn) + except Exception as e: return False, str(e) + + def reset_specialization(self, player_id): + """Reset all specialization tracks for a player.""" + try: + conn = self.db.get_connection() + if not conn: return False, "DB connection failed" + cur = None + try: + cur = conn.cursor() + cur.execute("SELECT dune.reset_specialization_tracks(%s)", [player_id]) + conn.commit() + audit_logger.info(f"SPEC_RESET: player={player_id}") + return True, "Specialization tracks reset" + except Exception as e: + conn.rollback(); return False, str(e) + finally: + if cur: cur.close(); self.db.return_connection(conn) + except Exception as e: return False, str(e) + + # ── Guild Roster ─────────────────────────────────────────────────── + def get_guild_members(self, guild_id): + """Get all members of a guild.""" + result = self.db.query(""" + SELECT gm.player_id, gm.role_id, COALESCE(NULLIF(ps.character_name, ''), 'Unknown') as name + FROM dune.guild_members gm + LEFT JOIN dune.player_state ps ON ps.player_controller_id = gm.player_id + WHERE gm.guild_id = %s + ORDER BY gm.role_id, ps.character_name + """, [guild_id]) + return result or [] + + def promote_guild_member(self, guild_id, player_id, new_role): + """Promote/demote a guild member.""" + try: + conn = self.db.get_connection() + if not conn: return False, "DB connection failed" + cur = None + try: + cur = conn.cursor() + cur.execute("SELECT dune.promote_guild_member(%s, %s, %s)", [guild_id, player_id, new_role]) + conn.commit() + audit_logger.info(f"GUILD_PROMOTE: guild={guild_id} player={player_id} role={new_role}") + return True, f"Player {player_id} now role {new_role}" + except Exception as e: + conn.rollback(); return False, str(e) + finally: + if cur: cur.close(); self.db.return_connection(conn) + except Exception as e: return False, str(e) + + # ── Economy / Vendors ────────────────────────────────────────────── + def clean_player_vendor_stock(self, player_id): + """Reset vendor buy limits for a player.""" + try: + conn = self.db.get_connection() + if not conn: return False, "DB connection failed" + cur = None + try: + cur = conn.cursor() + cur.execute("SELECT dune.clean_stock_for_player(%s)", [player_id]) + conn.commit() + audit_logger.info(f"VENDOR_CLEAN: player={player_id}") + return True, f"Vendor stock reset for player {player_id}" + except Exception as e: + conn.rollback(); return False, str(e) + finally: + if cur: cur.close(); self.db.return_connection(conn) + except Exception as e: return False, str(e) + + def get_player_tax_invoices(self, player_id): + """Get tax invoices for a player.""" + result = self.db.query( + "SELECT * FROM dune.taxation_get_all_invoices_for_player(%s)", + [player_id] + ) + return result or [] + + # ── Spice Fields ─────────────────────────────────────────────────── + def force_spice_spawn(self, server_id, spicefield_type_id): + """Request a spice field spawn.""" + try: + conn = self.db.get_connection() + if not conn: return False, "DB connection failed" + cur = None + try: + cur = conn.cursor() + cur.execute("SELECT dune.request_spawn_spice_field(%s, %s)", [server_id, spicefield_type_id]) + conn.commit() + audit_logger.info(f"SPICE_SPAWN: server={server_id} type={spicefield_type_id}") + return True, f"Spice field spawn requested on {server_id}" + except Exception as e: + conn.rollback(); return False, str(e) + finally: + if cur: cur.close(); self.db.return_connection(conn) + except Exception as e: return False, str(e) + + def reset_spice_state(self, map_name, dimension_index): + """Reset global spice field state.""" + try: + conn = self.db.get_connection() + if not conn: return False, "DB connection failed" + cur = None + try: + cur = conn.cursor() + cur.execute("SELECT dune.reset_global_spice_field_state(%s, %s)", [map_name, dimension_index]) + conn.commit() + audit_logger.info(f"SPICE_RESET: map={map_name} dim={dimension_index}") + return True, f"Spice state reset on {map_name}" + except Exception as e: + conn.rollback(); return False, str(e) + finally: + if cur: cur.close(); self.db.return_connection(conn) + except Exception as e: return False, str(e) + + # ── Server Tools ─────────────────────────────────────────────────── + def set_players_offline(self, server_ids): + """Set all players on given servers to offline.""" + try: + conn = self.db.get_connection() + if not conn: return False, "DB connection failed" + cur = None + try: + cur = conn.cursor() + cur.execute("SELECT dune.set_players_from_server_ids_offline(%s)", [server_ids]) + conn.commit() + audit_logger.info(f"SET_OFFLINE: servers={server_ids}") + return True, f"Players set offline on {len(server_ids)} servers" + except Exception as e: + conn.rollback(); return False, str(e) + finally: + if cur: cur.close(); self.db.return_connection(conn) + except Exception as e: return False, str(e) + + def cleanup_orphaned(self): + """Clean up orphaned entities in the database.""" + try: + conn = self.db.get_connection() + if not conn: return False, "DB connection failed" + cur = None + try: + cur = conn.cursor() + cur.execute("SELECT dune.cleanup_orphaned_entities()") + conn.commit() + audit_logger.info("CLEANUP_ORPHANS") + return True, "Orphaned entities cleaned up" + except Exception as e: + conn.rollback(); return False, str(e) + finally: + if cur: cur.close(); self.db.return_connection(conn) + except Exception as e: return False, str(e) + + # ── Permission Management ───────────────────────────────────────── + def get_actor_permissions(self, actor_id): + """Get permissions for an actor.""" + result = self.db.query( + "SELECT * FROM dune.get_permission_for_actor(%s)", + [actor_id] + ) + return result or [] + + def set_player_rank(self, actor_id, player_id, rank, map_id=''): + """Set a player's rank on an actor.""" + try: + conn = self.db.get_connection() + if not conn: return False, "DB connection failed" + cur = None + try: + cur = conn.cursor() + cur.execute("SELECT dune.permission_set_player_rank(%s, %s, %s, %s)", [actor_id, player_id, rank, map_id]) + conn.commit() + audit_logger.info(f"RANK_SET: actor={actor_id} player={player_id} rank={rank}") + return True, f"Rank {rank} set for player {player_id}" + except Exception as e: + conn.rollback(); return False, str(e) + finally: + if cur: cur.close(); self.db.return_connection(conn) + except Exception as e: return False, str(e) + + # ── Player Stats (from actors.properties JSONB) ─────────────────── + def get_player_stats(self, player_controller_id): + """Get player health and stats from actor properties.""" + result = self.db.query(""" + WITH pawn AS ( + SELECT id, properties FROM dune.actors + WHERE id = (SELECT player_pawn_id FROM dune.player_state WHERE player_controller_id = %s) + ), + ctrl AS ( + SELECT properties FROM dune.actors WHERE id = %s + ) + SELECT + pawn.id as pawn_id, + pawn.properties::text as pawn_props, + ctrl.properties::text as ctrl_props + FROM pawn, ctrl + """, [player_controller_id, player_controller_id]) + if not result: + return None + row = result[0] + import json + pawn = json.loads(row.get('pawn_props') or '{}') + ctrl = json.loads(row.get('ctrl_props') or '{}') + stats = {'pawn_id': row['pawn_id']} + + # Health + dmg = pawn.get('DamageableActorComponent', {}) + stats['health'] = {'current': dmg.get('m_CurrentMaxHealth'), 'max': dmg.get('m_TotalMaxHealth')} + + # Character stats + char = pawn.get('BP_DunePlayerCharacter_C', {}) + stats['eyes_of_ibad'] = char.get('m_EyesOfIbadValue') + stats['heatstroke'] = char.get('m_bHeatstroke') + stats['is_driving'] = char.get('m_bIsDriving') + + # Journey / Spice exposure + journey = ctrl.get('BP_JourneyComponent_C', {}) + stats['spice_exposure_level'] = journey.get('CurrentSpiceExposureThresholdLevel') + + # Landsraad + landsraad = ctrl.get('LandsraadCharacterComponent', {}) + stats['daily_reward_charges'] = landsraad.get('m_DailyRewardCharges') + stats['last_viewed_term'] = landsraad.get('m_LastViewedLandsraadTermId') + + return stats + + # ── Dynamic Function Explorer ───────────────────────────────────── + def list_all_functions(self): + """List all dune schema functions with signatures.""" + result = self.db.query(""" + SELECT p.proname as name, + pg_get_function_identity_arguments(p.oid) as args, + l.lanname as language, + p.prokind as kind + FROM pg_proc p + JOIN pg_namespace n ON n.oid = p.pronamespace + JOIN pg_language l ON l.oid = p.prolang + WHERE n.nspname = 'dune' AND p.prokind = 'f' + ORDER BY p.proname + """) + return result or [] + + def execute_function(self, function_name, params): + """Execute any dune schema function dynamically.""" + try: + param_placeholders = ','.join(['%s'] * len(params)) + sql = f"SELECT * FROM dune.{function_name}({param_placeholders})" + result = self.db.query(sql, params) + audit_logger.info(f"EXEC_FUNC: {function_name}({params})") + return True, result, None + except Exception as e: + return False, None, str(e) + + def get_function_details(self, function_name): + """Get full definition of a function.""" + result = self.db.query(""" + SELECT pg_get_functiondef(p.oid) as definition, + p.proname as name, + pg_get_function_identity_arguments(p.oid) as args + FROM pg_proc p + JOIN pg_namespace n ON n.oid = p.pronamespace + WHERE n.nspname = 'dune' AND p.proname = %s AND p.prokind = 'f' + """, [function_name]) + return result[0] if result else None + + def _detect_namespace(self): + out, err, rc = self.ssh.run( + "sudo kubectl get pods -A --no-headers -o custom-columns=NS:.metadata.namespace,NAME:.metadata.name " + "| awk '$1 ~ /^funcom-seabass-/ && $2 ~ /-mq-game-sts-0$/ { print $1 }' | sort -u" + ) + if out: + ns = out.strip().split('\n')[0] + if ns: + return ns + return "funcom-seabass-sh-b17a5f036d1f7882-ccdijf" diff --git a/app/utils/constants.py b/app/utils/constants.py index 3c53c1f..b79d6f3 100644 --- a/app/utils/constants.py +++ b/app/utils/constants.py @@ -81,4 +81,5 @@ NAV_PAGES = [ ('/guilds', 'Guilds'), ('/buildings', 'Buildings'), ('/map', 'Map'), + ('/admin-experimental', 'Admin Experimental'), ] diff --git a/templates/admin_experimental.html b/templates/admin_experimental.html new file mode 100644 index 0000000..c3ab684 --- /dev/null +++ b/templates/admin_experimental.html @@ -0,0 +1,1282 @@ +{% extends "base.html" %} +{% block title %}Admin Experimental - Dune Awakening Dashboard{% endblock %} +{% block content %} + + + +
+
In-Game Broadcast
+
+

+ Send a broadcast notification to all connected players. Uses RabbitMQ heartbeats exchange. +

+ +
+
+ + +
+
+ + +
+
+ + +
+ +
+
+
+ +
+ +
+
Search Players
+
+

Search characters by name.

+ +
+ + +
+
+
+
+ +
+
Online Players
+
+

Currently online or recently disconnected players.

+ + +
+
+
+ +
+ +
+ +
+
Adjust Currency
+
+

Add or remove virtual currency from a player.

+ +
+ + +
+
+
+ + +
+
+ + +
+
+
+ + +
+
+
+
+ +
+
Change Faction
+
+

Change a player's faction allegiance.

+ +
+ + +
+
+ + +
+ +
+
+ +
+
Teleport Player
+
+

Teleport an offline player to a partition.

+ +
+ + +
+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+
+ + +
+
+
+
+ +
+ +
+ +
+
Faction Reputation
+
+

View or set faction reputation.

+ +
+ + +
+
+
+ + +
+
+ + +
+
+
+ + +
+
+
+
+ +
+
Player Stats / Health
+
+

View player health, spice exposure, and other stats from actor properties.

+ +
+ + +
+ +
+
+
+ +
+
Inventory Lookup
+
+

View player inventory by account ID.

+ +
+ + +
+ +
+
+
+ +
+ +
+ +
+
Player Tags
+
+

Read or update player tags. Comma-separated lists.

+ +
+ + +
+
+
+ + +
+
+ + +
+
+
+ + +
+
+
+
+ +
+
Flag Cheater
+
+

Flag a player as cheater.

+ +
+ + +
+
+ + +
+ +
+
+ +
+ +
+ +
+
Guild Tools
+
+

List guilds, view details, disband, kick members.

+ +
+
+ + +
+
+ + +
+
+
+ + + + +
+
+
+
+ +
+
Player Vehicles
+
+

View vehicles owned by a player.

+ +
+
+ + +
+
+ + +
+
+ +
+
+
+ +
+ +
+ +
+
Character Management
+
+

Rename, delete, force demo state.

+ +
+
+ + +
+
+ + +
+
+
+ + + +
+
+
+ + +
+
+ + +
+
+ +
+
+ +
+
Journey & Specialization
+
+

Manage story nodes and specialization tracks.

+ +
+ +
+ + +
+
+
+ + + +
+
+ + + + +
+
+ + +
+
+
+ +
+ +
+ +
+
Economy & Spice Fields
+
+

Vendor stock, tax invoices, spice field control.

+ +
+ + + +
+
+
+ + + +
+
+
+ +
+
Server Tools
+
+

Force players offline, cleanup orphans, manage permissions.

+ +
+ + +
+
+ + +
+
+
+
+ +
+ +
+ +
+
Battlegroup Info
+
+

Full battlegroup status from BGD API.

+ + +

+    
+
+ +
+ +
+ +
+
Function Explorer — All 517 DB Functions
+
+

+ Browse and execute any PostgreSQL function in the dune schema. Type to filter. Click a function to see its definition and enter parameters. +

+ +
+ + +
+
+
+
+

Select a function from the list to see details and execute it.

+
+
+
+
+ +
+ + + + + +{% endblock %} From fa620f4da97252bcd01f641fb8f45009120b92f7 Mon Sep 17 00:00:00 2001 From: Reditus <33814724+ReditusDraco@users.noreply.github.com> Date: Fri, 22 May 2026 22:21:50 +0100 Subject: [PATCH 02/12] Start of a refactor for new endpoints It's gonna be a long night! --- AI_DASHBOARD_CAPABILITIES_REFERENCE.md | 857 ----------------- AI_DUNE_AWAKENING_SYSTEM_CONTEXT.md | 1224 ------------------------ 2 files changed, 2081 deletions(-) delete mode 100644 AI_DASHBOARD_CAPABILITIES_REFERENCE.md delete mode 100644 AI_DUNE_AWAKENING_SYSTEM_CONTEXT.md diff --git a/AI_DASHBOARD_CAPABILITIES_REFERENCE.md b/AI_DASHBOARD_CAPABILITIES_REFERENCE.md deleted file mode 100644 index 54cc066..0000000 --- a/AI_DASHBOARD_CAPABILITIES_REFERENCE.md +++ /dev/null @@ -1,857 +0,0 @@ -# Dune Dashboard — Complete Capabilities Reference - -> **Generated:** 2026-05-22 -> **Purpose:** Comprehensive reference of all dashboard features, database functions, and admin tools -> **⚠️ SECURITY:** This document contains sensitive operational information. Do not commit to GitHub. - ---- - -## Table of Contents - -1. [Dashboard Admin Features](#1-dashboard-admin-features) -2. [Database Functions Catalog](#2-database-functions-catalog) -3. [RabbitMQ Exchanges & Queues](#3-rabbitmq-exchanges--queues) -4. [BGD Director API Endpoints](#4-bgd-director-api-endpoints) -5. [Kubernetes Resources](#5-kubernetes-resources) -6. [Game Tables Reference](#6-game-tables-reference) - ---- - -## 1. Dashboard Admin Features - -### 1.1 Player Management - -| Feature | Purpose | API Endpoint | DB Function / Query | -|---------|---------|--------------|---------------------| -| **Search Players** | Find players by character name or FLS ID | `POST /api/admin-experimental/search-players` | Query on `encrypted_accounts` + `player_state` | -| **Online Players** | List currently online players | `GET /api/admin-experimental/online-players` | `get_all_online_or_recently_disconnected_player_online_state()` | -| **Teleport Player** | Move offline player to partition + coordinates | `POST /api/admin-experimental/teleport` | `admin_move_offline_player_to_partition(fls_id, partition_id, vector)` | -| **Change Faction** | Switch player's faction allegiance | `POST /api/admin-experimental/change-faction` | Direct SQL on `player_faction` table | -| **Faction Reputation** | View/set reputation with factions | `POST /api/admin-experimental/faction-reputation` | `get_player_current_faction_reputation()`, `set_player_faction_reputation()` | -| **Adjust Currency** | Add/remove Solari, House Script, Spice | `POST /api/admin-experimental/adjust-currency` | Direct INSERT/UPDATE on `player_virtual_currency_balances` | -| **View Currency** | Check player's currency balances | `POST /api/admin-experimental/currency-balances` | Query `player_virtual_currency_balances` | -| **Player Tags** | Add/remove metadata tags on accounts | `POST /api/admin-experimental/player-tags` | `admin_read_player_tags()`, `update_player_tags()` | -| **Flag Cheater** | Mark account for cheating | `POST /api/admin-experimental/flag-cheater` | `flag_player_as_cheater(account_id, cheat_type_enum)` | -| **Player Stats** | View health, hydration, spice exposure | `POST /api/admin-experimental/player-stats` | Query `actors.properties` JSONB | -| **Player Vehicles** | List owned vehicles | `POST /api/admin-experimental/player-vehicles` | `get_player_owned_vehicles_data()` | -| **Inventory Lookup** | View player inventory items | `POST /api/admin-experimental/inventory` | `admin_get_inventory_details()` | -| **Set Character Name** | Rename a character | `POST /api/admin-experimental/set-character-name` | `set_character_name(account_id, name)` | -| **Delete Character** | Remove character from account | `POST /api/admin-experimental/delete-character` | `delete_character(actor_id)` | -| **Delete Account** | Full account deletion | `POST /api/admin-experimental/delete-account` | `delete_account(user_id, reason)` | -| **Set Demo State** | Force demo mode state | `POST /api/admin-experimental/set-demo-state` | `set_demo_state(user_id, demo_state_enum)` | - -### 1.2 Guild Management - -| Feature | Purpose | API Endpoint | DB Function | -|---------|---------|--------------|-------------| -| **List Guilds** | Show all guilds on server | `GET /api/admin-experimental/guilds` | Query `guilds` table | -| **View Guild** | Get guild details + members | `POST /api/admin-experimental/guild-data` | `get_guild_data(guild_id)` | -| **Disband Guild** | Delete guild entirely | `POST /api/admin-experimental/disband-guild` | `disband_guild(guild_id)` | -| **Kick Member** | Remove player from guild | `POST /api/admin-experimental/remove-guild-member` | `remove_guild_members([player_id], guild_id, reason)` | -| **Guild Members** | List guild roster | `POST /api/admin-experimental/guild-members` | `get_guild_members(guild_id)` | -| **Promote Member** | Change guild role | `POST /api/admin-experimental/promote-guild-member` | `promote_guild_member(guild_id, player_id, role_id)` | -| **Demote Member** | Lower guild role | `POST /api/admin-experimental/demote-guild-member` | `demote_guild_member(guild_id, player_id, role_id)` | - -### 1.3 Journey & Progression - -| Feature | Purpose | API Endpoint | DB Function | -|---------|---------|--------------|-------------| -| **Complete Story Nodes** | Mark journey nodes complete | `POST /api/admin-experimental/journey` (action=complete) | `complete_journey_story_nodes_for_player(player_id, [node_ids])` | -| **Reveal Story Nodes** | Unlock hidden nodes | `POST /api/admin-experimental/journey` (action=reveal) | `reveal_journey_story_nodes_for_player(player_id, [node_ids])` | -| **Reset Story Nodes** | Reset progression | `POST /api/admin-experimental/journey` (action=reset) | `delete_journey_story_nodes_for_player(player_id, [node_ids])` | -| **Set Specialization** | Set XP/level for track | `POST /api/admin-experimental/specialization` | `set_specialization_xp_and_level(player_id, track_type, xp, level)` | -| **Reset Specialization** | Clear spec progress | `POST /api/admin-experimental/reset-specialization` | `reset_specialization_tracks(player_id)` | -| **View Inventory** | See player items | `POST /api/admin-experimental/inventory` | `admin_get_inventory_details(account_id)` | - -### 1.4 Economy & World - -| Feature | Purpose | API Endpoint | DB Function | -|---------|---------|--------------|-------------| -| **Reset Vendor Stock** | Refresh vendor inventory | `POST /api/admin-experimental/clean-vendor-stock` | `clean_stock_for_player(player_id)` | -| **View Tax Invoices** | Check player tax bills | `POST /api/admin-experimental/tax-invoices` | `taxation_get_all_invoices_for_player(player_id)` | -| **Reset Spice Fields** | Reset spice state on map | `POST /api/admin-experimental/spice` | `reset_global_spice_field_state(map, dim)` | -| **Force Spice Spawn** | Trigger spice field spawn | `POST /api/admin-experimental/spice` | `try_spawn_spicefield(server_id, spicefield_id)` | -| **List Partitions** | Show all world partitions | `GET /api/admin-experimental/partitions` | Query `world_partition` table | -| **Battlegroup Info** | Full server status | `GET /api/admin-experimental/battlegroup` | BGD API `/v0/battlegroup` | - -### 1.5 Server Administration - -| Feature | Purpose | API Endpoint | DB Function | -|---------|---------|--------------|-------------| -| **Set Players Offline** | Force all players offline | `POST /api/admin-experimental/server-tools` | `set_players_from_server_ids_offline([server_ids])` | -| **Cleanup Orphans** | Remove orphaned entities | `POST /api/admin-experimental/server-tools` | `cleanup_orphaned_entities()` | -| **View Permissions** | Check actor permissions | `POST /api/admin-experimental/permissions` | `get_permission_for_actors([actor_ids])` | -| **Set Player Rank** | Set permission rank | `POST /api/admin-experimental/permissions` | `permission_set_player_rank(actor_id, player_id, rank, map_id)` | -| **In-Game Broadcast** | Send notification to all players | `POST /api/admin-experimental/broadcast` | `rabbitmqctl eval` on RMQ pod (Erlang) | -| **Ban Player** | Ban with duration | `POST /api/ban_player` | Insert into `dashboard.bans` + iptables | -| **Unban Player** | Remove ban | `POST /api/unban_player` | Delete from `dashboard.bans` + iptables | -| **Kick Player** | Temporary kick | `POST /api/kick_player` | iptables DROP for 60 seconds | -| **Detect Player IPs** | Parse logs for IPs | `POST /api/detect_player_ips` | SSH + kubectl to read game logs | - -### 1.6 Item & Entity Editing - -| Feature | Purpose | API Endpoint | DB Function | -|---------|---------|--------------|-------------| -| **Edit Item** | Modify stack size, quality, durability | `POST /api/edit_item` | Direct UPDATE on `items` table | -| **Delete Item** | Remove item | `POST /api/delete_item` | `DELETE FROM items WHERE id = ?` | -| **Add Item** | Spawn item to inventory | `POST /api/add_item` | `INSERT INTO items ...` | -| **Edit Vitals** | Change health, hydration, spice | `POST /api/edit_vitals` | UPDATE `actors.properties` + `gas_attributes` | -| **Edit Tech Knowledge** | Set tech points | `POST /api/edit_tech_knowledge` | UPDATE `actors.properties` (TechKnowledgePlayerComponent) | -| **Edit XP** | Set specialization XP | `POST /api/edit_xp` | UPSERT on `specialization_tracks` | -| **Edit Faction** | Change faction directly | `POST /api/edit_faction` | UPSERT on `player_faction` | -| **Edit Currency** | Set exact balance | `POST /api/edit_currency` | UPSERT on `player_virtual_currency_balances` | - -### 1.7 Function Explorer - -| Feature | Purpose | API Endpoint | -|---------|---------|--------------| -| **List Functions** | Get all 517 DB functions | `GET /api/admin-experimental/functions` | -| **Get Function** | View function definition | `GET /api/admin-experimental/functions/:name` | -| **Execute Function** | Call function with params | `POST /api/admin-experimental/functions/:name/execute` | -| **Execute SQL** | Run raw SQL (admin only) | `POST /api/admin-experimental/execute` | - -### 1.8 File Browser - -| Feature | Purpose | API Endpoint | -|---------|---------|--------------| -| **List Files** | Browse `/srv` directory | `POST /api/files/list` | -| **View File** | Read file content | `GET /api/files/view` | -| **Save File** | Edit file content | `POST /api/files/save` | - ---- - -## 2. Database Functions Catalog - -### 2.1 Admin & Debug Functions (24 functions) - -| Function | Purpose | -|----------|---------| -| `admin_get_character_details(in_account_id bigint)` | Get full character data for account | -| `admin_get_character_ids(in_search_term text)` | Search characters by name pattern | -| `admin_get_inventory_details(in_account_id bigint)` | Get all inventory items for account | -| `admin_get_journey_details(in_player_id text, in_story_node_id text)` | Get journey node progress | -| `admin_get_mnemonic_recall_details(in_account_id bigint)` | Get mnemonic recall lessons | -| `admin_get_partitions()` | List all world partitions | -| `admin_move_offline_player(in_fls_id text, in_target_partition_name text, in_target_location vector)` | Teleport by partition name | -| `admin_move_offline_player_to_partition(in_fls_id text, in_target_partition_id bigint, in_target_location vector)` | Teleport by partition ID | -| `admin_read_player_tags(in_account_id bigint)` | Get tags for account | -| `debug_add_test_table_data(in_entry text)` | Debug: insert test data | -| `debug_collect_test_table_data()` | Debug: collect test data | -| `debug_echo(in_text text, in_notices text[])` | Debug: echo with notices | -| `debug_get_coriolis_seeds()` | Debug: get all Coriolis seeds | -| `debug_raise_exception(in_exception text, in_notices text[])` | Debug: raise exception | -| `debug_raise_notices(in_notices text[])` | Debug: raise notices | -| `debug_reset_test_table()` | Debug: reset test table | -| `debug_set_farm_seed(in_new_coriolis_seed integer)` | Debug: set farm seed | -| `debug_set_map_seed(in_map text, in_new_coriolis_seed integer)` | Debug: set map seed | -| `debug_set_partition_seed(in_partition_id bigint, in_new_coriolis_seed integer)` | Debug: set partition seed | -| `get_all_demo_players()` | Get all demo state players | -| `get_all_faction_members()` | Get all faction members | -| `get_all_guild_members()` | Get all guild members | -| `get_all_online_or_recently_disconnected_player_online_state()` | Get online players | -| `get_schema_version()` | Get DB schema version | - -### 2.2 Character Transfer Functions (22 functions) - -| Function | Purpose | -|----------|---------| -| `_character_transfer_allocate_id(kind dune._charactertransferentrykind, data jsonb)` | Allocate transfer ID | -| `_character_transfer_create_data_table()` | Create transfer data table | -| `_character_transfer_data_filter(id text, removed text[], VARIADIC refs dune._charactertransferdatafilterref[])` | Filter transfer data | -| `_character_transfer_data_table_load(entries jsonb)` | Load transfer data table | -| `_character_transfer_data_table_save()` | Save transfer data table | -| `_character_transfer_ensure_player_is_owner_of_vbt_vehicle(in_vehicle_id bigint[])` | Validate vehicle ownership | -| `_character_transfer_get_filter(kind dune._charactertransferentrykind)` | Get transfer filter | -| `_character_transfer_get_patches_checksum()` | Get patches checksum | -| `_character_transfer_pre_export_validation(in_fls_id text)` | Pre-export validation | -| `_character_transfer_property_not_exported_is_expected(path text)` | Check property export | -| `_character_transfer_replace_local_id_with_transfer_id(data text, path text)` | Replace IDs for export | -| `_character_transfer_replace_local_id_with_transfer_id_in_json(data jsonb, path text)` | Replace IDs in JSON | -| `_character_transfer_replace_transfer_id_with_local_id(data text, path text)` | Replace IDs for import | -| `_character_transfer_replace_transfer_id_with_local_id_in_json(data jsonb, path text)` | Replace IDs in JSON | -| `_character_transfer_store_in_world_owned_vehicles_into_recovery(in_player_id bigint)` | Store vehicles in recovery | -| `_character_transfer_top_level_export(in_kind dune._charactertransferentrykind, data jsonb)` | Export character data | -| `_character_transfer_top_level_import(in_kind dune._charactertransferentrykind, data jsonb, in_id bigint)` | Import character data | -| `character_migration_export(in_fls_id text)` | Export for migration | -| `character_migration_import(in_data jsonb, in_fls_id text, in_character_name text)` | Import migration data | -| `character_transfer_export(in_fls_id text)` | Export character | -| `character_transfer_get_unsaved_counts(in_fls_id text)` | Get unsaved counts | -| `character_transfer_import(in_data jsonb, in_fls_id text, in_character_name text)` | Import character | - -### 2.3 Guild & Faction Functions (28 functions) - -| Function | Purpose | -|----------|---------| -| `accept_guild_invite(in_invite_id bigint, in_role_id smallint, ...)` | Accept guild invite | -| `add_guild_invite(in_player_id bigint, in_guild_id bigint, ...)` | Create guild invite | -| `add_guild_member(in_player_id bigint, in_guild_id bigint, ...)` | Add member to guild | -| `break_guild_allegiance(in_guild_id bigint, in_neutral_faction_id smallint)` | Break guild allegiance | -| `change_player_faction(in_player_id bigint, in_faction_id smallint, ...)` | Change player faction | -| `clean_guild_invites_with_incompatible_faction(in_player_id bigint, in_faction_id smallint, ...)` | Clean incompatible invites | -| `clean_old_guild_invites(in_cutoff_timespan bigint)` | Clean old guild invites | -| `create_guild(in_player_id bigint, in_neutral_faction smallint, ...)` | Create new guild | -| `demote_guild_member(in_guild_id bigint, in_player_id bigint, in_new_role smallint)` | Demote guild member | -| `disband_guild(in_guild_id bigint)` | Disband guild | -| `get_guild_data(in_guild_id bigint)` | Get guild details | -| `get_guild_data_for_player(in_player_id bigint)` | Get guild for player | -| `get_guild_for_player(in_player_id bigint)` | Get guild ID for player | -| `get_guild_invites(in_guild_id bigint)` | Get guild invites | -| `get_guild_members(in_guild_id bigint)` | Get guild member list | -| `guild_handle_actor_delete(in_player_id bigint)` | Handle actor delete | -| `guilds_get_exclusive_operation_lock()` | Get guild operation lock | -| `handle_player_faction_guild_effects(in_player_id bigint, in_faction_id smallint, ...)` | Apply faction effects | -| `is_player_guild_admin(in_player_id bigint, in_guild_id bigint)` | Check if guild admin | -| `pledge_guild_allegiance(in_guild_id bigint, in_guild_leader_player_id bigint, ...)` | Pledge allegiance | -| `promote_guild_member(in_guild_id bigint, in_player_id bigint, in_new_role smallint)` | Promote guild member | -| `remove_guild_members(in_player_ids bigint[], in_guild_id bigint, in_remove_reason smallint)` | Remove members | -| `get_player_current_faction_reputation(in_actor_id bigint)` | Get faction reputation | -| `get_player_faction(in_player_id bigint, in_neutral_faction_id smallint)` | Get player faction | -| `get_player_faction_name(in_actor_id bigint)` | Get faction name | -| `set_player_faction_reputation(in_actor_id bigint, in_faction_id smallint, in_reputation_amount integer)` | Set reputation | -| `get_all_player_in_guild_online_state(in_guild_id bigint)` | Get guild online members | -| `get_player_ids_online_state(in_player_ids bigint[])` | Get player online status | - -### 2.4 Party Functions (13 functions) - -| Function | Purpose | -|----------|---------| -| `accept_party_invite(in_invite_id bigint, in_platform_session_id text, in_max_party_member_count integer)` | Accept party invite | -| `add_party_invite(in_sender_player_id bigint, in_sender_platform_name text, ...)` | Create party invite | -| `clean_expired_party_invites(in_invite_expire_seconds integer)` | Clean expired invites | -| `disband_party(in_party_id bigint)` | Disband party | -| `get_all_parties()` | Get all parties | -| `get_all_party_invites()` | Get all party invites | -| `get_all_party_members()` | Get all party members | -| `get_party_members(in_party_id bigint)` | Get party members | -| `internal_add_party_member(in_invite_id bigint, in_party_id bigint, ...)` | Add party member | -| `internal_create_party(in_invite_id bigint, in_leader_id bigint, ...)` | Create party | -| `join_platform_session_party(in_leader_platform_id text, in_player_platform_id text, ...)` | Join platform party | -| `parties_get_exclusive_operation_lock()` | Get party operation lock | -| `promote_new_party_leader(in_party_id bigint)` | Promote new leader | -| `promote_party_leader_to(in_party_id bigint, in_player_id bigint)` | Set party leader | -| `remove_party_invite(in_invite_id bigint, in_remove_reason smallint)` | Remove party invite | -| `remove_party_member(in_player_id bigint, in_remove_reason smallint)` | Remove party member | -| `update_party_platform_session(in_party_id bigint, in_platform_session_id text, in_platform_name text)` | Update platform session | - -### 2.5 Inventory & Items (42 functions) - -| Function | Purpose | -|----------|---------| -| `add_item_delete_log(in_item_id bigint, in_inventory_id bigint, in_template_id text)` | Log item delete | -| `add_item_trace_log(...)` | Log item movement | -| `advance_items_id_sequencer(count bigint)` | Advance item ID sequence | -| `delete_inventory_item(in_item_id bigint, in_count bigint)` | Delete inventory item | -| `get_inventory_data(in_inventory_id bigint)` | Get inventory data | -| `get_inventory_id(in_actor_id bigint, in_component_name_hash integer)` | Get inventory ID | -| `get_items_to_remove(items_to_remove text[])` | Get items to remove | -| `get_sub_inventory_id(in_owner_item_id bigint)` | Get sub-inventory ID | -| `load_items(in_inventory_id bigint)` | Load inventory items | -| `merge_inventory_items(in_item_id bigint, in_dst_inventory_id bigint, ...)` | Merge item stacks | -| `merge_or_move_inventory_item(in_item_id bigint, in_dst_inventory_id bigint, ...)` | Merge or move item | -| `move_inventory_item(in_item_id bigint, in_dst_inventory_id bigint, ...)` | Move item | -| `save_item(in_item dune.inventoryitem)` | Save item | -| `update_inventories_data(in_inventory_data_list dune.inventorydata[])` | Update inventories | -| `update_inventory(in_delete_list bigint[], in_stack_update dune.itemstackupdate[], ...)` | Update inventory | -| `update_item_locations(in_item_locations dune.inventoryitemlocation[])` | Update item locations | -| `admin_get_inventory_details(in_account_id bigint)` | Get inventory for account | -| `get_exchange_inventory_id(in_exchange_id bigint)` | Get exchange inventory | -| `get_vehicle_module_inventory_id(in_vehicle_module_id bigint, in_vehicle_module_inventory_type integer)` | Get module inventory | -| `load_building(in_building_id bigint)` | Load building data | -| `load_placeable(in_placeable_id bigint)` | Load placeable data | -| `load_totem(in_id bigint)` | Load totem data | -| `load_vehicle_modules(in_vehicle_id bigint)` | Load vehicle modules | -| `save_building(in_building_id bigint, in_data dune.buildingsavedata)` | Save building | -| `save_placeable(in_placeable_id bigint, in_data dune.placeablesavedata)` | Save placeable | -| `save_totem(in_id bigint, in_data dune.totemsavedata)` | Save totem | -| `save_vehicle_modules(in_add_list dune.vehiclemodule[], in_delete_list bigint[], ...)` | Save vehicle modules | -| `base_backup_delete(in_base_backup_id bigint)` | Delete base backup | -| `base_backup_find_totems_from_player_owner(in_player_id bigint)` | Find totems for backup | -| `base_backup_finish_placing(in_base_backup_id bigint)` | Finish placing backup | -| `base_backup_get_actors_to_spawn(in_base_backup_id bigint)` | Get actors to spawn | -| `base_backup_get_available_backups(in_player_id bigint)` | Get available backups | -| `base_backup_get_buildable_data(in_base_backup_id bigint)` | Get buildable data | -| `base_backup_get_data(in_base_backup_id bigint)` | Get backup data | -| `base_backup_get_totem_data(in_base_backup_id bigint)` | Get totem data | -| `base_backup_get_totem_data_from_totem_id(in_totem_id bigint)` | Get totem data by ID | -| `base_backup_get_totem_id(backup_id bigint)` | Get totem ID | -| `base_backup_recycle(in_base_backup_id bigint, in_target_inventory_id bigint)` | Recycle backup | -| `base_backup_save(in_player_actor_id bigint, in_base_backup_name text, ...)` | Save base backup | -| `base_backup_save_all_totems_from_player_owner(in_player_id bigint)` | Save all totems | -| `base_backup_save_from_totem(in_player_id bigint, totem_id bigint)` | Save from totem | -| `get_unbacked_up_vehicle_ids_for_account(in_account_id bigint)` | Get unbacked vehicles | - -### 2.6 Currency & Economy (21 functions) - -| Function | Purpose | -|----------|---------| -| `adjust_player_virtual_currency_balance(in_controller_id bigint, in_currency_id smallint, in_delta bigint)` | Adjust currency | -| `dune_exchange_add_sell_order(...)` | Add exchange sell order | -| `dune_exchange_cancel_order(in_order_id bigint, in_purge_time bigint, in_completion_type integer)` | Cancel order | -| `dune_exchange_expire_orders(in_exchange_id bigint, in_current_time bigint, ...)` | Expire orders | -| `dune_exchange_fulfill_sell_order(...)` | Fulfill sell order | -| `dune_exchange_get_item_price_stats(in_template_ids text[])` | Get price stats | -| `dune_exchange_get_user_id(in_owner_id bigint)` | Get exchange user ID | -| `dune_exchange_get_used_order_slots(in_controller_id bigint)` | Get used slots | -| `dune_exchange_modify_user_solari_balance(in_controller_id bigint, in_solari_delta bigint)` | Modify Solari | -| `dune_exchange_purge_completed_orders(in_exchange_id bigint, in_current_time bigint)` | Purge completed | -| `dune_exchange_query_storage_item(in_order_id bigint)` | Query storage item | -| `dune_exchange_query_storage_items(in_exchange_id bigint, in_owner_id bigint)` | Query storage items | -| `dune_exchange_relist_order(in_order_id bigint, in_expiration_time bigint, ...)` | Relist order | -| `dune_exchange_retrieve_solari_balance(in_owner_id bigint)` | Retrieve Solari | -| `dune_exchange_retrieve_solaris_from_item(in_controller_id bigint, in_order_id bigint)` | Retrieve from item | -| `dune_exchange_retrieve_storage_item(in_exchange_id bigint, in_order_id bigint, ...)` | Retrieve storage item | -| `dune_exchange_update_recurring_sell_order(...)` | Update recurring order | -| `get_dune_exchange_accesspoint_id(in_exchange_id bigint, in_name text)` | Get access point | -| `get_dune_exchange_data(in_exchange_id bigint, in_controller_id bigint)` | Get exchange data | -| `get_dune_exchange_id(in_name text)` | Get exchange ID | -| `get_player_virtual_currency_balances(in_controller_id bigint)` | Get currency balances | -| `get_solaris_id()` | Get Solari currency ID | -| `taxation_emit_invoices(new_tax_invoices dune.taxinvoicedata[])` | Emit tax invoices | -| `taxation_get_all_invoices_for_player(in_player_id bigint)` | Get player invoices | -| `taxation_get_all_invoices_for_server(map_name text, in_dimension_index integer, in_partition_id bigint)` | Get server invoices | -| `taxation_get_all_invoices_for_totem(in_totem_id bigint)` | Get totem invoices | -| `taxation_pay_invoice(invoice_id bigint, paid_invoice_status smallint)` | Pay invoice | -| `taxation_remove_invoices(invoices_to_remove bigint[])` | Remove invoices | -| `taxation_remove_invoices_from_totem(totem_actor_id bigint)` | Remove totem invoices | -| `taxation_update_invoice_status(...)` | Update invoice status | - -### 2.7 Journey & Progression (26 functions) - -| Function | Purpose | -|----------|---------| -| `complete_journey_nodes_where_prerequisite_nodes_are_complete(story_ids_to_complete text[], prerequisite_completed_story_ids text[])` | Complete nodes | -| `complete_journey_story_nodes_for_player(in_player_id text, in_story_node_ids text[])` | Complete for player | -| `create_or_update_tutorial_entry(in_player_id bigint, in_tutorial_id smallint, in_tutorial_state smallint)` | Create tutorial | -| `delete_all_journey_story_nodes(in_account_id bigint)` | Delete all nodes | -| `delete_all_tutorial_entries(in_player_id bigint)` | Delete tutorials | -| `delete_journey_story_ids(story_ids text[])` | Delete story IDs | -| `delete_journey_story_node(in_account_id bigint, in_story_node_id text)` | Delete node | -| `delete_journey_story_nodes_for_group_for_player(in_account_id bigint, in_reset_group dune.journeystoryresetgroup)` | Delete group | -| `delete_journey_story_nodes_for_player(in_player_id text, in_story_node_ids text[])` | Delete for player | -| `delete_journey_story_nodes_for_player_account(in_account_id bigint, in_story_node_ids text[])` | Delete for account | -| `get_all_tutorial_entries(in_player_id bigint)` | Get tutorials | -| `get_login_journey_nodes(in_account_id bigint)` | Get login nodes | -| `get_login_journey_nodes_cooldown(in_account_id bigint)` | Get cooldown | -| `journey_story_node_cooldown_add(in_account_id bigint, in_story_node_id text, in_time_to_expire timestamp)` | Add cooldown | -| `journey_story_node_cooldown_delete_expired(in_time_to_check timestamp)` | Delete expired | -| `load_actors(in_actor_ids bigint[], in_actor_state dune.actorstate)` | Load actors | -| `reset_journey_story_nodes_for_player(in_player_id text, in_story_node_ids text[])` | Reset nodes | -| `reveal_journey_story_nodes_for_player(in_player_id text, in_story_node_ids text[])` | Reveal nodes | -| `save_journey_story_node(in_account_id bigint, in_story_node_id text, ...)` | Save node | -| `save_journey_story_nodes(in_account_id bigint, in_journey_data dune.savejourneydata[])` | Save nodes | -| `update_journey_story_ids(old_story_ids text[], new_story_ids text[])` | Update IDs | -| `get_character_import_state(in_fls_id text)` | Get import state | -| `get_unresolved_character_imports()` | Get unresolved imports | -| `set_character_import_state(in_fls_id text, in_state dune.transferimportstate)` | Set import state | -| `remove_character_transfer_state(in_fls_id text)` | Remove transfer state | -| `get_character_transfer_related_items(in_fls_id text)` | Get transfer items | - -### 2.8 Specialization & Skills (7 functions) - -| Function | Purpose | -|----------|---------| -| `get_learned_building_sets(in_account_id bigint)` | Get learned sets | -| `get_learned_new_buildable_pieces(in_account_id bigint)` | Get learned pieces | -| `initialize_specialization_keystones(in_keystones text[])` | Initialize keystones | -| `purchase_specialization_keystone(in_player_id bigint, in_keystone text)` | Purchase keystone | -| `reset_specialization_keystones(in_player_id bigint)` | Reset keystones | -| `reset_specialization_tracks(in_player_id bigint)` | Reset tracks | -| `set_specialization_xp_and_level(in_player_id bigint, in_track_type dune.specializationtracktype, in_xp_amount integer, in_level real)` | Set XP/level | -| `update_specialization_refund_id(in_player_id bigint, in_refund_id smallint, in_removed_keystones smallint[])` | Update refund | -| `get_player_specialization(in_player_controller_id bigint)` | Get specialization | -| `get_player_keystones(in_player_controller_id bigint)` | Get keystones | - -### 2.9 Landsraad & Politics (25 functions) - -| Function | Purpose | -|----------|---------| -| `landsraad_cast_vote(in_term_id bigint, in_player_id bigint, in_decree_name text)` | Cast vote | -| `landsraad_change_term_end_time(end_term_id bigint, new_end_time timestamp, in_test_term boolean)` | Change term end | -| `landsraad_check_task_completion()` | Check task completion | -| `landsraad_check_term_won()` | Check term won | -| `landsraad_collect_task_telemetry_for_faction(in_term_id bigint, in_faction_name text)` | Collect telemetry | -| `landsraad_collect_term_telemetry(in_term_id bigint, in_faction_names text[])` | Collect term telemetry | -| `landsraad_collect_term_telemetry_for_faction(in_term_id bigint, in_faction_name text)` | Collect for faction | -| `landsraad_collect_vote_telemetry(in_term_id bigint, in_winning_faction_id integer)` | Collect vote telemetry | -| `landsraad_collect_votes(in_term_id bigint)` | Collect votes | -| `landsraad_determine_winner(in_term_id bigint)` | Determine winner | -| `landsraad_force_end_term(end_term_id bigint)` | Force end term | -| `landsraad_has_term_of_task_ended(in_task_id bigint)` | Check task ended | -| `landsraad_initialize_system(...)` | Initialize system | -| `landsraad_initialize_term(...)` | Initialize term | -| `landsraad_insert_task_progress(in_term_id bigint, in_player_id bigint, ...)` | Insert progress | -| `landsraad_insert_task_progress_batched(in_term_id bigint, in_task_progress dune.landsraadtaskprogress[])` | Batch insert | -| `landsraad_insert_task_progress_faction(in_term_id bigint, in_faction_name text, ...)` | Insert faction progress | -| `landsraad_insert_task_progress_random(in_term_id bigint, in_faction_names text[], in_num_rows integer)` | Random progress | -| `landsraad_load_current_rotation(in_term_id bigint)` | Load rotation | -| `landsraad_load_current_term()` | Load current term | -| `landsraad_load_guild_contribution(in_term_id bigint, in_guild_id bigint, in_faction_id bigint)` | Load guild contribution | -| `landsraad_load_guild_contributions(in_term_id bigint, in_num_guilds integer, in_faction_names text[])` | Load contributions | -| `landsraad_load_guild_vote(in_term_id bigint, in_player_id bigint)` | Load guild vote | -| `landsraad_load_house_rewards(in_player_id bigint)` | Load house rewards | -| `landsraad_load_player_contributions(in_term_id bigint, in_player_ids bigint[])` | Load contributions | -| `landsraad_load_task_faction_progress(in_term_id bigint)` | Load task progress | -| `landsraad_load_task_faction_reveal_state(in_term_id bigint)` | Load reveal state | -| `landsraad_load_term_progress(in_term_id bigint, in_num_guilds integer, ...)` | Load term progress | -| `landsraad_notify_house_rewards_changed()` | Notify rewards | -| `landsraad_perform_daily_task_reveal(in_term_id bigint, in_faction_names text[], ...)` | Daily reveal | -| `landsraad_process_house_rewards()` | Process rewards | -| `landsraad_process_task_progress(max_rows integer)` | Process progress | -| `landsraad_task_has_been_completed(in_task_id bigint)` | Check completed | -| `landsraad_update_task_faction_reveal_state(in_term_id bigint, in_task_board_index integer, faction_name text, reveal_state boolean)` | Update reveal | -| `landsraad_withdraw_house_reward(in_player_id bigint, in_house_rewards dune.landsraadplayerhousereward[])` | Withdraw reward | -| `get_player_landsraad(in_player_controller_id bigint)` | Get Landsraad data | - -### 2.10 World & Partitions (30 functions) - -| Function | Purpose | -|----------|---------| -| `add_partition_unique(in_map text, in_definition jsonb, in_dimension bigint, in_label text)` | Add partition | -| `determine_partition_label(in_map text, in_dimension_index integer, in_label text, in_allow_overwrite boolean, in_partition_id bigint)` | Determine label | -| `determine_partition_label_trigger()` | Label trigger | -| `get_partition_presets()` | Get presets | -| `get_partitions(in_map text)` | Get partitions for map | -| `igwo_delete_world_partitions(in_partition_ids bigint[])` | Delete partitions | -| `igwo_get_partition_id_seq_last_value()` | Get sequence value | -| `igwo_get_partition_ids()` | Get partition IDs | -| `igwo_get_partitions()` | Get all partitions | -| `igwo_get_server_details()` | Get server details | -| `igwo_insert_world_partition(in_partition_id bigint, in_map text, in_partition_definition jsonb, ...)` | Insert partition | -| `igwo_next_partition_id_seq()` | Next sequence | -| `igwo_notify_world_partition_update()` | Notify update | -| `igwo_restart_partition_id_seq(in_restart_with bigint)` | Restart sequence | -| `igwo_update_world_partition(in_map text, in_partition_definition jsonb, in_partition_id bigint, ...)` | Update partition | -| `initialize_partitions_basic_battlegroup()` | Init basic BG | -| `initialize_partitions_basic_survival_1()` | Init survival | -| `initialize_partitions_development_battlegroup()` | Init development | -| `initialize_partitions_editor_default_1x1()` | Init editor | -| `initialize_partitions_full_battlegroup()` | Init full BG | -| `initialize_partitions_igw_test_small_2x1()` | Init test 2x1 | -| `initialize_partitions_igw_test_small_2x2()` | Init test 2x2 | -| `initialize_partitions_igw_training()` | Init training | -| `initialize_world_partition(in_map_name text, in_num_servers integer, in_dimension_index integer)` | Init partition | -| `load_dimension_index(in_map text, in_partition_id bigint)` | Load dimension | -| `load_partition_definition_map()` | Load definition map | -| `load_world_partition(in_map_name text, in_server_id text, in_desired_dimension_index bigint, in_desired_partition_id bigint)` | Load partition | -| `save_world_partition(in_map_name text, in_server_id text, in_dimension_index bigint, ...)` | Save partition | -| `unassign_partition(in_server_id text)` | Unassign partition | -| `update_partition_labels(in_allow_overwrite boolean)` | Update labels | -| `get_battlegroup_close_date()` | Get close date | -| `set_battlegroup_close_date(in_close_date timestamp)` | Set close date | - -### 2.11 Spice Fields & Coriolis (24 functions) - -| Function | Purpose | -|----------|---------| -| `corilis_cleanup_map(in_server_info dune.serverinfo, in_map_info dune.coriolismapinfo)` | Cleanup map | -| `coriolis_cleanup_farm(in_server_info dune.serverinfo, in_map_info dune.coriolismapinfo)` | Cleanup farm | -| `coriolis_cleanup_partition(in_server_info dune.serverinfo, in_map_info dune.coriolismapinfo)` | Cleanup partition | -| `coriolis_update_seed(in_server_info dune.serverinfo, in_new_coriolis_seed integer, in_map_info dune.coriolismapinfo)` | Update seed | -| `debug_set_farm_seed(in_new_coriolis_seed integer)` | Set farm seed | -| `debug_set_map_seed(in_map text, in_new_coriolis_seed integer)` | Set map seed | -| `debug_set_partition_seed(in_partition_id bigint, in_new_coriolis_seed integer)` | Set partition seed | -| `fetch_resourcefield_state(in_map text, in_dimension_index integer, in_field_kind_id smallint)` | Fetch field state | -| `fetch_server_spice_field_manifest(in_server_id text)` | Fetch spice manifest | -| `fetch_spicefie_id_types_with_global_info(in_map_name text, in_dimension_index integer)` | Fetch spice types | -| `get_farm_state()` | Get farm state | -| `get_stored_user_data_encryption_key_hash()` | Get encryption key | -| `get_stored_user_data_encryption_status()` | Get encryption status | -| `get_stored_user_data_encryption_taint_xmax()` | Get taint status | -| `produce_spicefield_manifest(in_map_name text, in_dimension_index integer)` | Produce manifest | -| `record_deactivated_spice_field(in_server_id text, in_spicefield_type_id integer)` | Record deactivated | -| `record_static_shifting_sand(in_id text, in_alpha double precision, ...)` | Record shifting sand | -| `record_unreadied_spice_fields(in_server_id text, in_spicefield_type_id integer, in_num_unreadied integer)` | Record unreadied | -| `request_spawn_spice_field(in_server_id text, in_spicefield_type_id integer)` | Request spawn | -| `reset_global_spice_field_state(in_map_name text, in_dimension_index integer)` | Reset state | -| `retrieve_all_static_shifting_sand()` | Retrieve all sand | -| `try_prime_spicefield(in_source_server_id text, in_spicefield_id integer)` | Try prime | -| `try_restart_spicefield(in_server_id text, in_spicefield_type_id integer)` | Try restart | -| `try_spawn_spicefield(in_source_server_id text, in_spicefield_id integer)` | Try spawn | -| `try_update_exchange_categories_hash(in_new_hash integer)` | Update hash | -| `update_global_spice_field_rules(in_max_globally_primed integer, in_max_globally_active integer, in_spicefield_type_id integer)` | Update rules | -| `update_spice_field_spawn_state(in_is_spawning_active boolean, in_spicefield_type_id integer)` | Update spawn state | -| `upsert_spicefield_types(in_max_globally_active integer[], ...)` | Upsert types | - -### 2.12 Chat & Communication (18 functions) - -| Function | Purpose | -|----------|---------| -| `add_event_log_data(in_game_event_owner bigint, in_universe_time bigint, ...)` | Add event log | -| `add_event_log_data_batched(in_data dune.eventlogbulkentrydata[])` | Batch add events | -| `add_map_areas_surveyed_items(in_account_id bigint, in_area_id smallint, ...)` | Add surveyed items | -| `add_map_areas_time_discovered(in_account_id bigint, in_area_id smallint, ...)` | Add discovered time | -| `add_map_areas_time_first_entered(in_account_id bigint, in_area_id smallint, ...)` | Add first entered | -| `clean_expired_party_invites(in_invite_expire_seconds integer)` | Clean expired invites | -| `create_event_log_partition()` | Create log partition | -| `delete_all_static_shifting_sand()` | Delete all sand | -| `get_all_player_travel_states()` | Get travel states | -| `get_online_player_controller_ids(in_map text)` | Get online on map | -| `get_online_player_controller_ids_on_farm()` | Get online on farm | -| `get_player_online_state_within_grace_period_for_each_server()` | Get grace period | -| `load_events_log_data_from_player(in_actor_id bigint, in_limit_entries_num integer)` | Load player events | -| `log_cheating(in_fls_id text, in_cheat_type dune.cheat_type_enum, in_event_time timestamp)` | Log cheating | -| `log_event_solaris(in_function_oid oid, in_message dune.logmessagetype, ...)` | Log Solari event | -| `set_all_inactive_players_in_farm_offline()` | Set inactive offline | -| `set_players_from_server_ids_offline(in_server_ids text[])` | Set servers offline | -| `wipe_old_events_log(in_days_limit integer)` | Wipe old logs | -| `get_active_servers_for_gateway()` | Get active servers | - -### 2.13 Account & Authentication (25 functions) - -| Function | Purpose | -|----------|---------| -| `can_takeover_account(in_user_id text)` | Check takeover | -| `cleanup_account_log_and_orphaned_actors()` | Cleanup orphans | -| `cleanup_accounts_marked_for_deletion_in_fls(in_account_ids text[])` | Cleanup FLS deletes | -| `decrypt_user_data(in_encrypted_data bytea)` | Decrypt data | -| `delete_account(in_user_id text, in_reason text)` | Delete account | -| `dune_get_account_id_by_user(in_user text)` | Get account by user | -| `encrypt_user_data(in_data text)` | Encrypt data | -| `get_account_actor_ids(in_account_id bigint)` | Get account actors | -| `get_controller_id_from_platform_id(in_platform_id text)` | Get controller ID | -| `get_encrypted_account(...)` | Get encrypted account | -| `get_friends_search(in_player_name text, in_max_players_count integer)` | Search friends | -| `get_player_infos_for_character_names(in_character_names text[])` | Get by character name | -| `get_player_infos_for_fls_ids(in_fls_ids text[])` | Get by FLS ID | -| `get_player_infos_for_funcom_ids(in_funcom_ids text[])` | Get by Funcom ID | -| `get_player_pawn(in_account_id bigint)` | Get player pawn | -| `get_takeoverable_user_ids()` | Get takeoverable IDs | -| `load_takeoverable_user_ids()` | Load takeoverable | -| `login_account(in_user_id text, in_funcom_id text, ...)` | Login account | -| `perform_notify_on_character_delete(in_user_id text)` | Notify on delete | -| `set_account_as_takeoverable(in_user_id text, in_new_user_id text)` | Set takeoverable | -| `takeover_account(in_user_to_takeover text, in_current_user text)` | Takeover account | -| `update_returning_player_status(in_user_id text, in_minimum_returning_player_time_seconds integer)` | Update returning | -| `get_demo_state(in_user_id text)` | Get demo state | -| `set_demo_state(in_user_id text, in_demo_state dune.demostate)` | Set demo state | -| `save_demo_account_time(in_fls_id text, in_demo_playtime_seconds integer)` | Save demo time | - -### 2.14 Markers & Map Data (20 functions) - -| Function | Purpose | -|----------|---------| -| `create_sinkchart_for_map_area_id(in_item_id bigint, in_creator_id bigint, ...)` | Create sinkchart | -| `delete_map_markers(in_dimension_index integer, in_map_name text, in_player_marker_data dune.deleteplayermarkerdata[])` | Delete markers | -| `delete_markers_by_id(in_marker_ids integer[])` | Delete by ID | -| `delete_markers_by_static_location_key(p_location_key text)` | Delete by location | -| `delete_markers_for_all_players(in_marker_types_to_keep text[], in_map text)` | Delete for all | -| `delete_markers_return_actor_ids(in_dimension_index integer, in_map_name text, in_marker_ids integer[])` | Delete and return | -| `delete_static_location_markers(p_location_keys text[])` | Delete static | -| `load_markers(in_player_id bigint, in_dimension_id integer, in_map_name text)` | Load markers | -| `load_map_areas_entries(in_account_id bigint, in_map_name text)` | Load map areas | -| `save_markers(in_player_marker_data dune.saveplayermarkerdata[], in_marker_data dune.savemarkerdata[])` | Save markers | -| `update_marker_ids(in_old_ids integer[], in_new_ids integer[])` | Update marker IDs | -| `use_sinkchart(in_player_id bigint, in_account_id bigint, in_area_id smallint, ...)` | Use sinkchart | -| `clear_map_areas_data_for_player(in_id bigint)` | Clear map data | -| `get_map_areas_entries(in_account_id bigint, in_map_name text)` | Get map areas | -| `load_static_encounter_name(in_map_name text, in_package_name text, in_actor_name text)` | Load encounter | -| `save_static_encounter_name(in_map_name text, in_package_name text, in_actor_name text, in_encounter_name text)` | Save encounter | -| `save_static_encounter_waiting_for_reset(in_map_name text, in_package_name text, in_actor_name text, in_waiting_for_reset boolean)` | Save waiting reset | -| `upgrade_location_data_list(in_location_data_list jsonb, in_map_field_name text)` | Upgrade location | -| `upgrade_map_name(in_map_name text)` | Upgrade map name | -| `upgrade_map_value(in_value jsonb)` | Upgrade map value | -| `downgrade_map_name(in_map_name text)` | Downgrade map name | - -### 2.15 Permissions & Ownership (16 functions) - -| Function | Purpose | -|----------|---------| -| `get_permission_actors_for_server(in_server_info dune.serverinfo)` | Get server permissions | -| `get_permission_for_actor(in_actor_id bigint)` | Get actor permission | -| `get_permission_for_actors(in_actor_id bigint[])` | Get actors permissions | -| `get_permission_for_player_actors(in_player_id bigint, in_min_rank smallint)` | Get player permissions | -| `ownership_handle_actor_delete(in_player_id bigint)` | Handle ownership delete | -| `permission_actor_create_or_update_base_marker(in_actor_id bigint, in_player_id bigint, in_rank smallint)` | Create marker | -| `permission_actor_destroy(in_actor_id bigint)` | Destroy permission | -| `permission_actor_register(in_entry dune.actorpermissionentry, in_owner_rank dune.actorpermissionrankdata)` | Register permission | -| `permission_actor_takeover(in_entry dune.actorpermissionentry, in_owner_rank dune.actorpermissionrankdata)` | Takeover permission | -| `permission_actor_update_marker_location(in_actor_id bigint, in_location_x real, in_location_y real, in_location_z real)` | Update location | -| `permission_remove_player_rank(in_actor_id bigint, in_player_id bigint)` | Remove rank | -| `permission_set_access_level(in_actor_id bigint, in_access_level smallint)` | Set access level | -| `permission_set_name(in_actor_id bigint, in_name text)` | Set name | -| `permission_set_player_rank(in_actor_id bigint, in_player_id bigint, in_rank smallint, in_map_id text)` | Set player rank | -| `gather_ownerless_actors_on_server(in_server_info dune.serverinfo)` | Gather ownerless | -| `gather_player_linked_actors(in_player_pawn_id bigint)` | Gather linked actors | -| `gather_removed_accounts_that_left_orphaned_actors_on_server(in_server_info dune.serverinfo)` | Gather orphans | -| `cleanup_orphaned_entities()` | Cleanup orphans | - -### 2.16 Travel & Movement (17 functions) - -| Function | Purpose | -|----------|---------| -| `get_traveling_actor_id_and_types(in_actor_id bigint)` | Get traveling actor | -| `get_traveling_actor_ids(in_actor_id bigint, in_max_recursion_level integer)` | Get traveling IDs | -| `get_traveling_actors_fls_ids(in_actor_id bigint)` | Get traveling FLS IDs | -| `get_traveling_non_player_actor_ids(in_actor_id bigint)` | Get non-player IDs | -| `load_travel_return_info(in_player_controller_id bigint)` | Load return info | -| `load_travel_to_player_info(in_player_controller_id bigint)` | Load travel info | -| `remove_aborted_authority_transfer_actors(in_partition_id bigint)` | Remove aborted | -| `save_aborted_authority_transfer_actors(in_actor_ids bigint[], in_partition_id bigint)` | Save aborted | -| `save_actor_dislocation(in_actor_id bigint, in_current_server_info dune.serverinfo, in_target_location vector, in_target_dimension_index integer)` | Save dislocation | -| `save_travel_return_info(in_player_controller_id bigint, in_map text, in_transform dune.transform)` | Save return info | -| `update_traveling_actor_dependencies(in_dep dune.traveldependency[])` | Update dependencies | -| `update_traveling_actor_tree(in_actor_id bigint, in_target_transform dune.transform, ...)` | Update actor tree | -| `get_actors_location_data_with_permission(in_actor_ids bigint[])` | Get location data | -| `get_actor_server_info(in_id bigint)` | Get server info | -| `server_info_match(in_actor dune.actors, in_server_info dune.serverinfo)` | Match server info | -| `delete_actors_and_respawns_on_server(in_server_info dune.serverinfo, ...)` | Delete on server | -| `mark_server_dead(in_server_id text)` | Mark server dead | - -### 2.17 Utility & Helper Functions (30+ functions) - -| Function | Purpose | -|----------|---------| -| `assign_actor_id(in_class text)` | Assign actor ID | -| `add_actor_audit(in_id bigint, in_class text)` | Add actor audit | -| `delete_actors(in_ids bigint[])` | Delete actors | -| `delete_actor_states_travel(in_actor_id bigint)` | Delete travel state | -| `delete_all_dungeon_completions(in_dungeon_id text)` | Delete completions | -| `delete_all_dungeon_completions_by_player(in_dungeon_id text, in_player_id bigint, ...)` | Delete by player | -| `delete_all_dungeon_completions_for_all_dungeons_by_player(in_player_id bigint, ...)` | Delete all dungeons | -| `delete_dialogue_data(in_player_controller_id bigint)` | Delete dialogue | -| `delete_world_partition_by_map_id(in_map_id text)` | Delete partition | -| `find_actor_by_id(in_id bigint)` | Find actor | -| `fix_broken_harkonnen_players_due_to_fooled_thufir()` | Fix Harkonnen bug | -| `get_actor_server_info(in_id bigint)` | Get actor server | -| `get_all_player_character_home_dimensions()` | Get home dimensions | -| `get_best_dungeon_completion(in_dungeon_id text)` | Get best completion | -| `get_best_dungeons_completions_for_player(in_player_id bigint)` | Get best dungeons | -| `get_dungeon_completion(in_dungeon_id text, in_player_id bigint)` | Get completion | -| `get_partition_id_for_server(in_server_id text)` | Get partition ID | -| `get_player_partition_id(in_fls_id text)` | Get player partition | -| `get_registered_spawned_actor(in_spawner_id bigint)` | Get spawned actor | -| `get_respawn_locations(in_account_id bigint)` | Get respawn locations | -| `get_universe_time()` | Get universe time | -| `get_vehicle_id(in_actor_id bigint, in_class text)` | Get vehicle ID | -| `load_full_actors(in_ids bigint[])` | Load full actors | -| `record_dungeon_completion(in_dungeon_id text, in_difficulty integer, in_duration_ms integer, players_ids bigint[])` | Record completion | -| `register_spawned_actor(in_spawner_id bigint, in_actor_id bigint)` | Register spawned | -| `reset_all_players_from_server_ids_grace_period_and_logoff_timer(in_server_id text, in_reset_time timestamp)` | Reset grace period | -| `save_actors(in_server_info dune.serverinfo, in_actors dune.actordescription[], in_actor_state dune.actorstate)` | Save actors | -| `save_player(in_player dune.playerdescription)` | Save player | -| `save_player_pawn(in_pawn dune.actordescription, in_server_info dune.serverinfo, in_life_state dune.playerlifestate)` | Save pawn | -| `update_farm_state(in_server_id text, in_outgoing_s2s_connections integer, ...)` | Update farm state | -| `update_server_building_favorites(in_account_id bigint, in_building_types text[])` | Update favorites | -| `update_server_learned_building_sets(in_account_id bigint, in_learned_building_sets text[])` | Update learned sets | -| `update_server_learned_new_buildable_pieces(in_account_id bigint, in_new_buildable_pieces text[])` | Update learned pieces | -| `update_universe_time(in_farm_id text)` | Update universe time | -| `zero_transform()` | Zero transform | -| `get_applied_patches()` | Get applied patches | -| `get_universe_time()` | Get universe time | - ---- - -## 3. RabbitMQ Exchanges & Queues - -### 3.1 Game Exchanges (mq-game at port 32716) - -| Exchange | Type | Purpose | -|----------|------|---------| -| `heartbeats` | direct | In-game broadcasts and notifications | -| `rpc` | direct | Server RPC calls (currently no bindings) | -| `notifications` | topic | General notifications | -| `chat.faction.1-4` | fanout | Faction chat channels (4 factions) | -| `chat.guild.*` | fanout | Guild chat channels | -| `chat.intercept` | topic | Chat intercept/filtering | -| `chat.proximity` | direct | Proximity-based chat | -| `chat.whispers` | direct | Private whispers | -| `chat.map` | direct | Map-wide chat | -| `login_grant` | direct | Login grant messages | -| `login_request` | direct | Login requests | -| `login_response` | direct | Login responses | -| `status.*` | fanout | Per-map status (Overmap, Survival_1, DeepDesert_1, etc.) | -| `travel_queue_status` | topic | Travel queue updates | -| `director_respawned` | fanout | Respawn events from director | - -### 3.2 Admin Exchanges (mq-admin at port 30325) - -| Exchange | Type | Messages Published | Purpose | -|----------|------|-------------------|---------| -| `completions` | direct | 723 | Completion events | -| `response` | direct | 64K+ | Response routing | -| `settingsUpdate` | fanout | 71 | Server settings updates | -| `travel` | topic | - | Travel messages | -| `travelQueueStatus` | fanout | 1K+ | Travel queue status | -| `grant` | direct | - | Grant messages | -| `heartbeats` | direct | 2K+ | Heartbeat messages | -| `rpc` | direct | - | RPC messages | -| `director_respawned` | fanout | - | Respawn events | - -### 3.3 Game Queues - -| Queue | Consumers | Purpose | -|-------|-----------|---------| -| `B17A5F036D1F7882_queue` | - | Host-specific queue | -| `bgdRpc` | 1 | BGD RPC responses | -| `loginRequests` | 1 | Login request queue | -| `queue.intercept` | 1 | Chat intercept queue | -| `queue.server.*` (5 queues) | 1 each | Per-server queues | - ---- - -## 4. BGD Director API Endpoints - -### 4.1 Player Endpoints - -| Endpoint | Method | Response | Purpose | -|----------|--------|----------|---------| -| `/v0/players` | GET | `["FLS_ID"]` | List all player FLS IDs | -| `/v0/players/online` | GET | `["FLS_ID"]` | List online players | -| `/v0/players/intransit` | GET | `[]` | Players in transit | -| `/v0/players/graceperiod` | GET | `[]` | Players in grace period | -| `/v0/players/completion` | GET | `[]` | Completion queue | -| `/v0/players/queued` | GET | `[]` | Queued players | - -### 4.2 Battlegroup Endpoints - -| Endpoint | Method | Response | Purpose | -|----------|--------|----------|---------| -| `/v0/battlegroup` | GET | Full JSON | Complete battlegroup state (maps, servers, players, configs) | -| `/` | GET | HTML | Web dashboard UI | - -### 4.3 FLS Settings Endpoints - -| Endpoint | Method | Purpose | -|----------|--------|---------| -| `/v0/BattlegroupFetchFlsReportSettings` | GET | Fetch FLS report settings | -| `/v0/BattlegroupUpdateFlsReportSettings` | POST | Update FLS report settings | -| `/v0/BattlegroupClearFlsReportOverrides` | POST | Clear FLS overrides | - -### 4.4 Battlegroup JSON Structure - -The `/v0/battlegroup` endpoint returns: -- `dimensionMaps[]` — Multi-server maps with partitions -- `singleServerMaps[]` — Single-server maps -- `instancedMaps[]` — Instanced content (dungeons, gyms, etc.) -- Per-server data: `partition`, `ip`, `gamePort`, `numPlayers*`, `status`, `cfg`, `lastServerState` -- `serverGameplaySettings`: hydration, sandstorm, sandworm, PvP, security zones, mining multiplier, durability - -### 4.5 Map Types Managed by BGD - -- **Survival** — Survival mode maps -- **Story** — Story mission maps -- **Challenge Rooms** — Combat challenges -- **CB (Combat Block)** — PvP combat zones -- **DLC Content** — DLC-specific maps -- **Test Gyms** — Testing/training areas -- **Overmap** — Main overworld -- **Deep Desert** — Endgame PvP zone -- **Arrakeen** — City zone -- **Harko Village** — NPC village - ---- - -## 5. Kubernetes Resources - -### 5.1 World Namespace Pods - -| Pod Pattern | Purpose | -|-------------|---------| -| `{world}-mq-admin-sts-0` | RabbitMQ admin instance | -| `{world}-mq-game-sts-0` | RabbitMQ game instance | -| `{world}-tr-deploy-*` | Text Router (RMQ auth) | -| `{world}-bgd-deploy-*` | Battlegroup Director | -| `{world}-sgw-deploy-*` | Server Gateway | -| `{world}-db-dbdepl-*` | PostgreSQL database | -| `{world}-fb-deploy-*` | File Browser | -| `{world}-sg-overmap-pod-*` | Overmap game server | -| `{world}-sg-survival-1-pod-*` | Survival game server | -| `{world}-sg-deepdesert-1-pod-*` | Deep Desert server | -| `{world}-sg-arrakeen-pod-*` | Arrakeen server | -| `{world}-sg-harkovillage-pod-*` | Harko Village server | - -### 5.2 Operator Deployments (funcom-operators namespace) - -| Deployment | Purpose | -|------------|---------| -| `battlegroupoperator-controller-manager` | Manages BattleGroup CRDs | -| `databaseoperator-controller-manager` | Manages database lifecycle | -| `serveroperator-controller-manager` | Manages ServerGroup CRDs | -| `utilitiesoperator-controller-manager` | Manages utility services | - -### 5.3 Services (NodePort) - -| Service | NodePort | Purpose | -|---------|----------|---------| -| `bgd-svc` | 30553 | BGD Director API | -| `mq-admin-svc` | 30325 | RMQ Admin Management UI | -| `mq-admin-svc` | 32729 | RMQ Admin AMQP (TLS) | -| `mq-game-svc` | 32716 | RMQ Game Management UI | -| `mq-game-svc` | 31982 | RMQ Game AMQP (TLS) | - ---- - -## 6. Game Tables Reference - -### 6.1 Core Tables - -| Table | Rows | Purpose | -|-------|------|---------| -| `encrypted_accounts` | 10 | Encrypted account data | -| `encrypted_player_state` | 10 | Encrypted player state | -| `actors` | 411 | All game entities (players, NPCs, vehicles, buildings) | -| `items` | 1,482 | Inventory items | -| `inventories` | 459 | Inventory containers | -| `buildings` | 8 | Player buildings | -| `vehicles` | 16 | Player vehicles | -| `guilds` | 1 | Guilds | -| `factions` | 4 | Factions (Atreides, Harkonnen, Fremen, Corrino) | -| `bans` | 0 | Banned players | -| `game_events` | 76 | Game event log | - -### 6.2 Configuration Tables - -| Table | Rows | Purpose | -|-------|------|---------| -| `world_partition` | 30 | Server partition configuration | -| `dune_exchanges` | 1 | Exchange configuration | -| `landsraad_decrees` | 11 | Landsraad decrees | -| `landsraad_tasks` | 25 | Landsraad tasks | - -### 6.3 Dashboard Tables - -| Table | Purpose | -|-------|---------| -| `dashboard.bans` | Ban records with duration/reason | -| `dashboard.player_actions` | Admin action audit log | -| `dashboard.player_ips` | Player IP address tracking | -| `dashboard.chat_history` | Chat message archive | - ---- - -## Appendix: Common Admin Workflows - -### A.1 Ban a Player -1. Search for player by name -2. Get player_controller_id -3. Call `POST /api/ban_player` with duration and reason -4. Optionally detect player IP and apply iptables block - -### A.2 Teleport a Player -1. Ensure player is offline (check online status) -2. Get partition ID from `GET /api/admin-experimental/partitions` -3. Call `POST /api/admin-experimental/teleport` with FLS ID, partition ID, coordinates - -### A.3 Send In-Game Broadcast -1. Go to Admin Experimental tab -2. Enter title, message, duration -3. Click "Send Broadcast" -4. Message appears for all connected players - -### A.4 Fix a Stuck Player -1. Search for player -2. Check online status -3. If stuck: set offline via `set_players_from_server_ids_offline` -4. Teleport to safe location -5. Reset vitals if needed - -### A.5 Investigate Cheating -1. Search for player -2. View player stats (check for impossible values) -3. View inventory (check for duped items) -4. If confirmed: `flag_player_as_cheater` -5. Ban player and block IP - ---- - -**End of Reference** diff --git a/AI_DUNE_AWAKENING_SYSTEM_CONTEXT.md b/AI_DUNE_AWAKENING_SYSTEM_CONTEXT.md deleted file mode 100644 index 86eb833..0000000 --- a/AI_DUNE_AWAKENING_SYSTEM_CONTEXT.md +++ /dev/null @@ -1,1224 +0,0 @@ -# Dune Awakening — Full System Context for AI Continuation - -> **Last updated:** 2026-05-22 (production VPS at 65.21.198.100, cluster fully running) -> **VM Hostname:** `duneawakening` (Alpine Linux 3.23.4, K3s single-node) -> **Server IP:** `65.21.198.100` -> **Dashboard repo:** `C:\Users\Reditus\OneDrive\Documents\GitHub\dune-dashboard-private` -> **This doc path:** `C:\Users\Reditus\Downloads\DUNE_AWAKENING_SYSTEM_CONTEXT.md` -> **⚠️ SECURITY: NEVER commit this doc or any credentials to GitHub.** - ---- - -## ⚠️ YOUR MISSION (read this first) - -You are continuing work on a **Dune Awakening private game server**. Your job is to help access and configure admin settings on the game server. Everything you need is in this document. - -### What to do -1. **Read this entire document** — it contains the full architecture, credentials, connection methods, and what's been tried. -2. **Connect to the VM** via SSH (see section 1), run kubectl commands, explore the cluster. -3. **Continue from section 12** ("What's Still Unknown / Next Steps") — that's the active work queue. -4. **Update this document** with any new findings, credentials discovered, or progress made. -5. **Ask the user** only when you genuinely need a decision or something is blocked. Otherwise, just do it. - -### How to work -- All kubectl commands need `sudo` on the VM. -- PowerShell has tricky quoting — use script files piped via SSH for complex commands (`tr -d '\r'` to strip CRLF). -- The SSH tunnel for the dashboard (localhost:15433 → DB, localhost:32479 → BGD) may need restarting if down. -- When you find new credentials or endpoints, **add them to this document immediately**. -- **NEVER commit or push to GitHub.** The doc lives in Downloads for a reason. - -### Current priorities -- ✅ **DONE:** DB schema migration succeeded — cluster is fully running. See finding #19. -- ✅ **DONE:** RMQ Management UI accessible with `admin:admin123`. See finding #20. -- ✅ **DONE:** `send-dune-broadcast` tested and working on live server. See finding #21. -- **High:** Add custom broadcast title/identity (e.g., "Dune Admin" instead of hardcoded FLS backend) -- **Medium:** Integrate broadcast functionality into the dashboard admin panel. -- **Medium:** Scale operators back up (currently scaled to 0). - ---- - -## 1. HOW TO CONNECT - -### SSH to VM -```powershell -ssh -i "$env:LOCALAPPDATA\DuneAwakeningServer\sshKey" -o StrictHostKeyChecking=accept-new dune@65.21.198.100 -``` -**Note:** Production VPS at `65.21.198.100`. Hostname: `duneawakening`, Alpine Linux 3.23.4, K3s single-node. No longer a local Hyper-V VM. - -**Installed tools on VM (2026-05-22):** `curl`, `python3`, `py3-pip` (via `apk add`) - -**⚠️ SCP does not work on this VM** (no `sftp-server`). Use pipe method instead: -```powershell -Get-Content -Raw script.sh | ssh -i "" dune@65.21.198.100 "cat > /tmp/script.sh && tr -d '\r' < /tmp/script.sh > /tmp/script_clean.sh && mv /tmp/script_clean.sh /tmp/script.sh && chmod +x /tmp/script.sh && bash /tmp/script.sh" -``` - -### SSH Tunnel (maintained by dashboard launcher, PID 31172) -| Local Port | Forwards To | Purpose | -|-----------|-------------|---------| -| `localhost:15433` | VM:DB cluster IP (15432) | PostgreSQL | -| `localhost:32479` | VM:BGD NodePort 31403 | BGD Director API | - -### Kubectl on VM -```bash -# All commands need sudo -sudo kubectl get pods -A -sudo kubectl get svc -A -sudo kubectl get secrets -A -sudo kubectl logs -n -sudo kubectl exec -n -- -``` - -### BGD Web UI -- `http://192.168.0.101:31403/` — web dashboard with player stats -- `http://10.43.173.27:11717/` — via cluster IP (from inside VM) - ---- - -## 2. ARCHITECTURE OVERVIEW - -``` -Windows Host Hyper-V VM (192.168.0.101 / dune-awakening) -┌────────────────────┐ ┌─────────────────────────────────────────────┐ -│ Dashboard │ │ K3s Cluster (single node) │ -│ (Flask/SocketIO) │ ───SSH─────→ │ │ -│ Port 5050 │ tunnel │ ┌──────────────────────────────────────┐ │ -│ │ │ │ funcom-seabass-{WORLD_ID}-whxlri │ │ -│ RabbitMQ UI: │ │ │ │ │ -│ 192.168.0.101: │ │ │ mq-admin-sts (RabbitMQ admin) │ │ -│ 32253 (admin) │ │ │ mq-game-sts (RabbitMQ game) │ │ -│ 31745 (game) │ │ │ tr-deploy (Text Router / Auth) │ │ -│ │ │ │ bgd-deploy (Battlegroup Director) │ │ -│ │ │ │ sgw-deploy (Server Gateway) │ │ -│ │ │ │ db-dbdepl (PostgreSQL) │ │ -│ │ │ │ sg-overmap (Overmap game server) │ │ -│ │ │ │ sg-survival-1 (Pending - unsched) │ │ -│ │ │ │ fb-deploy (File Browser) │ │ -│ │ │ │ │ │ -│ │ │ │ funcom-operators namespace: │ │ -│ │ │ │ battlegroupoperator │ │ -│ │ │ │ databaseoperator │ │ -│ │ │ │ serveroperator │ │ -│ │ │ │ utilitiesoperator │ │ -│ │ │ └──────────────────────────────────────┘ │ -│ │ │ │ -│ │ │ VM Scripts: /home/dune/.dune/download/ │ -│ │ │ scripts/{battlegroup.sh, bg-util, ...} │ -│ │ │ images/battlegroup/*.tar (Docker images) │ -│ │ └─────────────────────────────────────────────┘ -``` - ---- - -## 3. ALL EXPOSED SERVICES (NodePort on 65.21.198.100) - -| Service | Type | ClusterIP | NodePort | Internal Ports | Purpose | -|---------|------|-----------|----------|---------------|---------| -| bgd-svc | NodePort | 10.43.92.250 | **30553** | 11717 | BGD Director web UI + API | -| mq-admin-svc | NodePort | 10.43.78.227 | **30325** | 15672 (HTTP) | RMQ Admin Management UI ✅ | -| mq-admin-svc | NodePort | 10.43.78.227 | **32729** | 5672 (AMQP) | RMQ Admin AMQP (TLS) | -| mq-game-svc | NodePort | 10.43.79.0 | **32716** | 15672 (HTTP) | RMQ Game Management UI ✅ | -| mq-game-svc | NodePort | 10.43.79.0 | **31982** | 5672 (AMQP) | RMQ Game AMQP (TLS) | -| db-dbdepl-svc | ClusterIP | 10.43.14.243 | - | 15432 | PostgreSQL | -| tr-svc | ClusterIP | 10.43.40.75 | - | 5059 | Text Router (RMQ auth) | - -**Note:** NodePorts are dynamically assigned and change on each install. Always check with `sudo kubectl get svc -n `. - -**Current (2026-05-22 production):** RMQ Admin UI at `http://65.21.198.100:30325`, RMQ Game UI at `http://65.21.198.100:32716`. Both accessible from outside the server. - ---- - -## 4. CREDENTIALS FOUND - -### RMQ HTTP Token Auth Secret (SIGNING KEY — NOT a password) -``` -gZQbpwOA6ow190HgLKDfxy9zZoRWejTJ1Trp+fnMQkNapY7TEdQ6RIXbLUVAlpPtbaz9pGLW8M8LWnjOfsCTKQ== -``` -- Base64-decoded: 64 bytes -- Used by: TR (Text Router) service to validate RMQ authentication tokens -- Stored in: `rmq-game-secret` Kubernetes secret -- Also present as env var in: BGD pod, SGW pod, TR pod, mq-admin pod, mq-game pod - -### FuncomLiveServices Service Auth Token (JWT) -``` -eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJIb3N0SWQiOiJCMTdBNUYwMzZEMUY3ODgyIiwiVG9rZW5JbmRleCI6IjEiLCJTZXJ2aWNlQXV0aEtleSI6IjI4RVVGOFMyM2dnQXdNWjQwUjRCQUZ1TTVFbkswM3RHeDZLY1h3Q0Vkc3FEcmVoUExxWFhGS0ZNcUIyYlNCUmYiLCJTZXJ2aWNlSG9zdFR5cGUiOiIyIiwibmJmIjoxNzc5MzE4MjQ1LCJleHAiOjE4MTA4NTQyNDUsImlhdCI6MTc3OTMxODI0NX0.yNenOJVmshIg1OcTEt0UeEmdUBnTQn2Gov098znvHMg -``` -**Decoded payload:** -```json -{ - "HostId": "B17A5F036D1F7882", - "TokenIndex": "1", - "ServiceAuthKey": "28EUGFS2M23ggAWMjQ0jR4BAFuM5VEbKsM3tGd6KYXh7CFKcsDqchPLxxXFGKFNqB2bNCBRf", - "ServiceHostType": "2", - "nbf": 1779318245, - "exp": 1810854245, - "iat": 1779318245 -} -``` -- Used by: BGD, SGW, TR for service-to-service authentication -- Expires: 2027-05-15 - -### Database Password -- **User:** `dune` -- **Password:** `qEJ1xJUedRJCv5qnAPJEnFnR` -- **Superuser:** `postgres` (no password needed from inside cluster) -- **Database:** `dune` -- **Schema:** `dune` (main game data), `ext` (extensions), `public` -- **Note:** Database is essentially empty (0 players, fresh install) - -### RabbitMQ Users (from RMQ logs — user format: `{service}.{world}.{token}.{role}`) -| User | Purpose | Pod | -|------|---------|-----| -| `sg.{WORLD}.wlP+pNNSRYeatInPivYEjw.admin` | Server Gateway admin | on mq-admin | -| `sg.{WORLD}.wlP+pNNSRYeatInPivYEjw.game` | Server Gateway game | on mq-game | -| `bgd.{WORLD}.Y_WL2MEd406KLEg5Lu+Bpw.admin` | BGD Director admin | on mq-admin | -| `bgd.{WORLD}.Y_WL2MEd406KLEg5Lu+Bpw.game` | BGD Director game | on mq-game | -| `tr.{POD}.iKkgMO91kEOlvCGqBwT3dg` | Text Router | on mq-game | - -### FLS API Key -- **Value:** `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` (masked/placeholder) -- Stored as `fls-apikey` in server-gateway-secret - -### RabbitMQ Management UI Credentials (RESOLVED 2026-05-22) -- **Username:** `admin` -- **Password:** `admin123` -- **Admin UI:** `http://65.21.198.100:30325` — ✅ Working -- **Game UI:** `http://65.21.198.100:32716` — ✅ Working -- **How it was done (new approach, 2026-05-22 production):** - 1. Scaled down all 4 operators to 0 replicas (prevents ConfigMap reconciliation) - 2. Modified `mq-admin-cm` and `mq-game-cm` ConfigMaps: changed `auth_backends.1 = $(RMQ_AUTH_BACKEND_1)` to `auth_backends.1 = internal` + `auth_backends.2 = $(RMQ_AUTH_BACKEND_1)` - 3. Restarted RMQ StatefulSet pods (they pick up new config) - 4. Created admin users on both mq-admin and mq-game via `rabbitmqctl add_user admin admin123` - 5. Set `administrator` tag and full permissions on both -- **Key difference from old approach:** Kept HTTP auth plugin enabled (needed for game services), just added `internal` as primary auth backend so the admin user is checked first. Game service tokens still authenticate via HTTP→TR fallback. -- **Note:** Admin users are LOST on pod restart (PV doesn't persist user data reliably). Must recreate via `rabbitmqctl` after each restart. - ---- - -## 5. RABBITMQ AUTHENTICATION ARCHITECTURE - -### How RMQ Auth Works -1. RabbitMQ is configured with `rabbitmq_auth_backend_http` + `rabbitmq_auth_backend_cache` -2. When a client connects via AMQP, RabbitMQ makes an HTTP POST to the TR service -3. **TR endpoint:** `POST /v0/auth/user` with `username` and `password` form params -4. TR validates the password as a structured/signed token using `RMQ_HTTP_TOKEN_AUTH_SECRET` -5. Returns `allow` or `deny` - -### TR Service Details -- **Pod:** `{WORLD}-tr-deploy` -- **Image:** `seabass-server-text-router` -- **Port:** 5059 -- **Type:** .NET 8 ASP.NET Core application (112MB binary at `/Tools/Battlegroups/TextRouter/TextRouter`) -- **Auth endpoints:** `/v0/auth/user` (GetUserAuth), `/v0/auth/vhost`, `/v0/auth/resource`, `/v0/auth/topic` -- **Config:** Minimal — `appsettings.json` only has Serilog settings - -### AMQP is TLS-only -Both mq-admin and mq-game are configured with: -``` -listeners.tcp = none -listeners.ssl.default = 5672 -``` -All AMQP connections use TLS. The Management UI (port 15672) is plain HTTP. - -### Token Format (from TR logs) -The TR extracts a "token" from the password and parses it as: -- **Created** (DateTime, 8 bytes) — was `01/01/0001` for invalid tokens -- **TTL** (duration) — was `00:00:00` for invalid tokens - -The token is validated using `RMQ_HTTP_TOKEN_AUTH_SECRET` as the HMAC signing key. -The 16-byte tokens in the usernames (`wlP+pNNSRYeatInPivYEjw` decoded) are too short and don't contain proper timestamp data. - -### Management UI Login -- URL: `http://192.168.0.101:32253` (admin) or `http://192.168.0.101:31745` (game) -- Uses HTTP Basic Auth -- **Status:** ✅ RESOLVED — Use `admin:admin123` (see section 4) -- The default HTTP auth backend (TR service) intercepts all login attempts. Internal RMQ users bypass this. - ---- - -## 6. BGD DIRECTOR API - -### Web UI -The BGD has a Bootstrap web UI at its root (`/`) with: -- Player count (total, online, in-transit, grace period) -- Links to API endpoints - -### API Endpoints Found -| Endpoint | Method | Response | -|----------|--------|----------| -| `/` | GET | HTML web UI | -| `/v0/players` | GET | `[]` (empty array) | -| `/v0/players/online` | GET | `[]` | -| `/v0/players/intransit` | GET | `[]` | -| `/v0/players/graceperiod` | GET | `[]` | -| Everything else | ANY | 404 Not Found | - -### BGD Pod -- **Args:** `--RMQGameHostname`, `--RMQGamePort`, `--RMQAdminHostname`, `--RMQAdminPort` -- **Env:** Has `FuncomLiveServices__ServiceAuthToken` (JWT) and `RMQ_HTTP_TOKEN_AUTH_SECRET` -- The BGD connects to both mq-admin and mq-game via AMQP internally - ---- - -## 6.5. SEND-DUNE-BROADCAST UTILITY (DISCOVERED 2026-05-22) - -### Location -- **File:** `F:\Downloads\send-dune-broadcast` -- **Type:** Bash script (177 lines) -- **Purpose:** Sends in-game broadcast notifications to all connected players via RabbitMQ - -### How It Works -The script publishes a message directly to the **`heartbeats` exchange** on the **mq-game** RabbitMQ instance using `rabbitmqctl eval` (Erlang code executed inside the RMQ pod). - -**Message structure:** -```erlang -Outer = #{ - <<"Version">> => 2, - <<"AuthToken">> => <<"Nu6VmPWUMvdPMeB7qErr">>, %% ⚠️ HARDCODED TOKEN - <<"MessageContent">> => Inner -} - -Inner = #{ - <<"ServerCommand">> => <<"ServiceBroadcast">>, - <<"BroadcastType">> => <<"Generic">>, - <<"BroadcastPayload">> => #{ - <<"BroadcastDuration">> => Duration, - <<"LocalizedText">> => [ - #{<<"Key">> => <<"en">>, <<"Title">> => Title, <<"Body">> => Body}, - #{<<"Key">> => <<"en-US">>, <<"Title">> => Title, <<"Body">> => Body} - ] - } -} -``` - -**Publishing details:** -- **Exchange:** `heartbeats` -- **Routing key:** `notifications` -- **App ID:** `fls` -- **User ID:** `fls_backend` -- **Message ID:** `manual-service-broadcast-{timestamp}` - -### Usage -```bash -send-dune-broadcast --title "Server Notice" --message "Maintenance in 10 minutes" --duration 60 -# or positional: -send-dune-broadcast "Server Notice" "Maintenance in 10 minutes" 60 -``` - -### Key Findings -1. **Hardcoded AuthToken:** `Nu6VmPWUMvdPMeB7qErr` — this is the FLS (Funcom Live Services) backend auth token used to authenticate broadcast messages -2. **Direct RMQ access:** Bypasses the TR auth entirely by executing Erlang code inside the RMQ pod via `rabbitmqctl eval` -3. **No AMQP connection needed:** Uses RMQ's internal APIs (`rabbit_exchange:lookup_or_die`, `rabbit_queue_type:publish_at_most_once`) -4. **Localized text:** Supports multiple locales (en, en-US) — could be extended -5. **BroadcastType:** Currently hardcoded as `Generic` — there may be other types - -### How to Run on Our Server -```bash -# Copy script to VM -scp -i "$env:LOCALAPPDATA\DuneAwakeningServer\sshKey" F:\Downloads\send-dune-broadcast dune@192.168.0.101:/home/dune/ - -# Make executable and run -ssh -i "$env:LOCALAPPDATA\DuneAwakeningServer\sshKey" dune@192.168.0.101 'chmod +x /home/dune/send-dune-broadcast && /home/dune/send-dune-broadcast --title "Test" --message "Hello from admin!" --duration 30' -``` - -### Potential Uses -- **Server announcements** (maintenance, events, restarts) -- **Emergency alerts** (crashes, rollbacks) -- **Welcome messages** for new players -- **Event notifications** (sandstorms, landsraad votes, etc.) -- **Integration with dashboard** — add a broadcast UI to the admin panel - -### Integration with Dashboard -The dashboard's `send_global_broadcast()` in `app/services/admin.py:668` currently only publishes to SocketIO (dashboard clients). This script shows how to reach **actual game clients** via RMQ. We can: -1. Port the Erlang logic to Python using `pika` or `aio-pika` -2. Or wrap this script and call it via SSH from the dashboard -3. Add a broadcast UI to the admin panel with title/message/duration fields - -### ⚠️ Important Notes -- The `heartbeats` exchange may not exist on our RMQ instance (it's created dynamically when the message is published) -- The AuthToken `Nu6VmPWUMvdPMeB7qErr` may need to match what the game clients expect -- This script requires `python3` on the VM for JSON escaping (already installed) -- The script uses `rabbitmqctl eval` which requires root/sudo access to the RMQ pod - ---- - -## 7. TEXT ROUTER (TR) POD DETAILS - -### Env Vars -``` -FuncomLiveServices__RmqTlsEnabled=true -FuncomLiveServices__ServiceAuthToken= -RMQ_HTTP_TOKEN_AUTH_SECRET= -Database_address={WORLD}-db-dbdepl-svc:15432 -Database_name=dune -Database_password=qEJ1xJUedRJCv5qnAPJEnFnR -Database_user=dune -``` - -### Args -``` ---RMQAdminHostname={WORLD}-mq-admin-svc --RMQAdminPort=5672 ---RMQGameHostname={WORLD}-mq-game-svc --RMQGamePort=5672 -``` -The TR itself connects to RabbitMQ. It uses the JWT (or signed tokens) to authenticate. - ---- - -## 8. DASHBOARD REPO CODE REFERENCES - -| File | Key Content | -|------|-------------| -| `app/services/director.py` | BGD Director integration | -| `app/services/k8s.py` | `get_rabbitmq_pod()` — finds `mq-admin`/`mq-game` | -| `app/services/admin.py:668` | `send_global_broadcast()` — "simulates the administrative `send-dune-broadcast` utility" | -| `app/routes/api.py` | Health checks (RabbitMQ pod status) | -| `app/utils/event_manager.py` | SocketIO event publishing | -| `launcher.ps1:81` | Redacts `RMQ_HTTP_TOKEN_AUTH_SECRET` from logs | -| `settings.yaml.example` | Config template with SSH, DB, K8s settings | - -**Note:** `send_global_broadcast()` is defined but NOT called by any route, websocket handler, or template — it's backend scaffolding. - ---- - -## 9. VM SCRIPTS - -| File | Location | Purpose | -|------|----------|---------| -| `setup.sh` | `/home/dune/.dune/download/scripts/` | Full setup orchestration | -| `battlegroup.sh` | Same dir | Battlegroup management CLI | -| `bg-util` | Same dir | 7MB Go binary (interactive, needs TTY) | -| `setup/helper.sh` | Same dir | Shared bash helpers | -| `setup/templates/world-template.yaml` | Same dir | Funcom CRD `BattleGroup` template | -| `setup/config/User*.ini` | Same dir | Default game user settings | - -### battlegroup.sh Commands -`list`, `status`, `start`, `restart`, `stop`, `edit`, `edit-advanced`, `update`, `update-from-downloads`, `backup`, `import`, `logs-export`, `operator-logs-export`, `apply-default-usersettings`, `enable-experimental-swap` - -### bg-util -- Interactive Go binary for editing battlegroup resources -- Requires a `world-template.yaml` path as argument -- Needs TTY (`error: could not open a new TTY` when run via SSH without `-t`) - ---- - -## 10. DATABASE SCHEMA - -### Schemas -- `dune` — Main game data (~160 tables) -- `ext` — Extensions -- `public` — Default schema -- `dashboard` — Dashboard's own tables (not yet created in this fresh install) - -### Notable Tables (all empty on fresh install) -- `accounts`, `actors`, `buildings`, `items`, `vehicles`, `player_state` -- `guilds`, `factions`, `parties` -- `landsraad_decrees`, `landsraad_tasks` (with data: 11 decrees, 25 tasks) -- `event_log*` (partitioned — empty) -- `world_partition` (30 rows — server config) -- `dune_exchanges` (1 row — exchange config) - -### Database Roles -| Role | Superuser | Login | -|------|-----------|-------| -| `dune` | No | Yes | -| `postgres` | Yes | Yes | - ---- - -## 11. INTERESTING LOG ENTRIES - -### RMQ mq-admin Errors -``` -operation basic.publish caused a channel exception not_found: -no exchange 'completions' in vhost '/' -``` -This occurs when the BGD or SGW tries to publish to a `completions` exchange that doesn't exist yet. Likely an initialization race condition or config issue. - -### TR Malformed Token -``` -Malformed token for user sg...wlP+pNNSRYeatInPivYEjw.game: - wlP+pNNSRYeatInPivYEjw: created: 01/01/0001 00:00:00, TTL: 00:00:00 -``` -Indicates the token in the username is NOT a valid signed credential. The SGW/BGD must be using something else as the actual password (probably the JWT). - ---- - -## 12. WHAT'S STILL UNKNOWN / NEXT STEPS - -### ✅ Completed -1. **DB Schema Migration Failure** — ✅ **RESOLVED** (happened automatically between installs or was unrelated to current cluster) -2. **RMQ Management UI credentials** — ✅ **RESOLVED** — `admin:admin123` working on both admin (30325) and game (32716) UIs -3. **`send-dune-broadcast`** — ✅ **TESTED AND WORKING** on live production server - -### Next Steps -1. **Scale operators back up** — Currently scaled to 0. They need to be restored: - - `for op in battlegroupoperator databaseoperator serveroperator utilitiesoperator; do sudo kubectl scale deployment -n funcom-operators $op-controller-manager --replicas=1; done` - - **Risk:** Operators will reconcile ConfigMaps back to defaults, reverting the `auth_backends` change. May need to: - a. Leave operators at 0 (manual management only) - b. Or accept that RMQ admin UI access breaks after reconciliation (recreate admin users on each RMQ restart) - -2. **Custom broadcast identity** — Currently broadcasts appear as `fls_backend`. Want to change title to "Dune Admin" or similar. Modify the hardcoded values in the script or change the message structure. - -3. **Integrate broadcast into dashboard** — Add a broadcast UI to the dashboard admin panel (title/message/duration fields) that calls the script via SSH. - -4. **BGD API expansion** — Currently only player endpoints. Check if there are undocumented endpoints or if the dashboard's director.py adds functionality. - -5. **Database backup/import** — `battlegroup.sh backup` and `import` commands exist. - -6. **`completions` exchange** — RMQ error that may be benign or indicate a missing exchange declaration. - -7. **SG Overmap pod** — Check TLS connection issues. - -### New Findings (2026-05-22) -8. **Installed tools on VM:** `curl`, `python3`, `py3-pip` added to Alpine VM for easier debugging -9. **TR Binary analysis:** Extracted from `server-text-router.tar` Docker image. Found classes: `RmqHttpTokenAuthApi`, `RmqHttpTokenGenerator`, `ShaTokenGenerator` with `TimeSkew` config. Token validation uses HMAC with the signing key. -10. **Battlegroup Operator behavior:** All 4 operators continuously reconcile ConfigMaps. To make config changes, must scale operators to 0 replicas first, then restore after changes. -11. **World namespace:** `funcom-seabass-sh-b17a5f036d1f7882-ooaeyc` (3rd install). Changes on each install — auto-detect with: `kubectl get pods -A --no-headers | grep mq-game-sts-0 | awk '{print $1}'` -12. **BGD Map Config:** BGD manages 50+ maps/instances including Survival, Story, Challenge Rooms, CB (Combat Block), DLC content, and test gyms -13. **send-dune-broadcast utility:** Found at `F:\Downloads\send-dune-broadcast`. Sends in-game announcements via RMQ `heartbeats` exchange using `rabbitmqctl eval`. Uses hardcoded AuthToken `Nu6VmPWUMvdPMeB7qErr`. See section 6.5 for full analysis. -14. **RMQ admin user persistence:** Admin users created via `rabbitmqctl add_user` are lost when RMQ pods restart. The PV may not be persisting user data, or the StatefulSet may be using a fresh volume each time. Need to investigate PV configuration. -15. **CRITICAL — RMQ TLS config missing on fresh install:** The default RMQ ConfigMaps on a fresh install are **missing TLS configuration**. Game services connect via TLS (`-RMQGameTlsEnabled=true`) but RMQ only listens on plain TCP, causing `{bad_header,<<22,3,1...>>}` errors and immediate connection drops. **Fix:** Add TLS config to both `mq-admin-cm` and `mq-game-cm` ConfigMaps: -```yaml -system.conf: | - listeners.tcp = none - listeners.ssl.default = 5672 - ssl_options.cacertfile = /etc/rabbitmq/cacert.pem - ssl_options.certfile = /etc/rabbitmq/cert.pem - ssl_options.keyfile = /etc/rabbitmq/key.pem - ssl_options.verify = verify_none - ssl_options.fail_if_no_peer_cert = false - auth_backends.1 = internal - auth_backends.2 = $(RMQ_AUTH_BACKEND_1) - # ... rest of auth config -``` -16. **Fresh install details (2026-05-22 #2):** VM IP `192.168.0.102`. World namespace: `funcom-seabass-sh-b17a5f036d1f7882-vvgcmr`. All pods running including survival. NodePorts: BGD 30086, RMQ admin 32560, RMQ game 31834. -17. **Fresh install details (2026-05-22 #3):** VM IP `192.168.0.103`. World namespace: `funcom-seabass-sh-b17a5f036d1f7882-ooaeyc`. **CRITICAL ISSUE:** Game servers not starting — DB schema migration failing. - - **Error:** `Failed to apply schema 1968181-0-shipping` — database operator keeps retrying - - **Root cause:** DB util pods (`db-dbdepl-util-*`) hang during schema migration. They connect to DB but never complete. - - **Effect:** BattleGroup stuck in `Stopped` phase, ServerGroup stuck in `Starting`, no game server pods (bgd, sg-overmap, sg-survival, sgw, tr) are created - - **Server operator logs:** `Cannot execute pod creation since database sh-b17a5f036d1f7882-ooaeyc-db is not ready to receive connections` - - **DB pod itself is Running** — the issue is specifically with the schema migration util pods - - **DB password:** `IgNybVaa7xbtBYz7kCvf7LbF` (changes each install) - - **DB util image:** `seabass-server-db-utils:1968181-0-shipping` - - **Workaround needed:** Investigate why schema migration hangs. May need to check DB connectivity, schema files, or manually apply schema. - -### New Findings (2026-05-22 — Production VPS Session) -18. **Server is a production VPS, not local Hyper-V:** IP `65.21.198.100`, hostname `duneawakening`, Alpine Linux 3.23.4. K3s single-node cluster is fully running with all game servers operational (overmap, survival-1, deepdesert-1, arrakeen, harkovillage, bgd, sgw, tr, fb, db). Schema migration eventually succeeded. - - **World namespace:** `funcom-seabass-sh-b17a5f036d1f7882-ccdijf` (different from the failed #3 install) - - **SSH key:** `$env:LOCALAPPDATA\DuneAwakeningServer\sshKey` - - **⚠️ SCP doesn't work** (no `sftp-server`). Use pipe method with `tr -d '\r'` to strip CRLF. -19. **RMQ ConfigMap auth fix applied:** - - Operators scaled to 0 (still at 0 as of end of session) - - Changed both `mq-admin-cm` and `mq-game-cm`: `auth_backends.1 = internal`, `auth_backends.2 = $(RMQ_AUTH_BACKEND_1)` - - RMQ pods restarted, admin users `admin:admin123` created with full permissions on both instances - - **RMQ Admin UI:** `http://65.21.198.100:30325` ✅ - - **RMQ Game UI:** `http://65.21.198.100:32716` ✅ - - **Note:** The game ConfigMap also needed the fix applied separately (first run only got admin, not game) -20. **`send-dune-broadcast` tested and confirmed working on live server:** - - Script copied to `/tmp/send-dune-broadcast` on the VM - - `python3` was not pre-installed — had to `apk add python3 py3-pip` first - - Test 1: `--title Notice --message Test --duration 30` → ✅ Success - - Test 2: `--title "YEY got it working!" --message "How are ya?" --duration 30` → ✅ Success - - Messages appear in-game as expected with hardcoded `fls_backend` identity - - The `heartbeats` exchange exists and accepts messages from `rabbitmqctl eval` -21. **No GitHub commits/pushes made — security enforced.** -22. **"Admin Experimental" dashboard tab created:** - - New nav entry at end of NAV_PAGES in `constants.py` - - Route `/admin-experimental` added in `main.py` - - Template `templates/admin_experimental.html` with broadcast form - - API endpoint `POST /api/admin-experimental/broadcast` in `api.py` - - `send_global_broadcast()` method added to `AdminService` in `admin.py` - - Uses base64 encoding to write Erlang script on VM host, then pipes via `cat | kubectl exec -i` into the pod - - **Note:** The original approach using heredoc failed through paramiko. Final working approach: write erl file on VM host via base64 decode, then `cat file | kubectl exec -i pod -- sh -lc 'cat > /tmp/pod.erl && rabbitmqctl eval "$(cat /tmp/pod.erl)"'` -23. **RMQ Game Exchanges discovered (via RMQ Management API at :32716):** - - `heartbeats` (direct) — broadcasts - - `rpc` (direct) — server RPC (no bindings currently) - - `notifications` (topic) — notifications - - `chat.faction.1-4` (fanout) — faction chat - - `chat.guild.*` (fanout) — guild chat - - `chat.intercept` (topic) — chat intercept - - `chat.proximity`, `chat.whispers`, `chat.map` (direct) — chat channels - - `login_grant`, `login_request`, `login_response` (direct) — auth flow - - `status.*` (fanout) — per-map status (Overmap, Survival_1, DeepDesert_1, SH_Arrakeen, SH_HarkoVillage, CB_*, DLC_*, Story_*) - - `travel_queue_status` (topic) — travel queue - - `director_respawned` (fanout) — respawn events -24. **RMQ Admin Exchanges discovered (via RMQ Management API at :30325):** - - `completions` (direct) — 723 messages published (completion events) - - `response` (direct) — 64K+ messages published (response routing) - - `settingsUpdate` (fanout) — 71 messages published (server settings updates) - - `travel` (topic) — travel messages - - `travelQueueStatus` (fanout) — 1K+ messages published - - `grant` (direct) — grant messages - - `heartbeats` (direct) — 2K+ messages published - - `rpc` (direct) — RPC messages - - `director_respawned` (fanout) — respawn events -25. **RMQ Game Queues discovered:** - - `B17A5F036D1F7882_queue` — host-specific queue - - `bgdRpc` — BGD RPC queue (1 consumer) - - `loginRequests` — login requests (1 consumer) - - `queue.intercept` — intercept queue (1 consumer) - - `queue.server.*` (5 queues) — server-specific queues (1 consumer each) -26. **BGD API Full Discovery:** - - `/v0/battlegroup` — **Full battlegroup JSON** with all server/player data (dimension maps, servers, configs, player counts, gameplay settings) - - `/v0/players` — returns `["B17A5F036D1F7882"]` (FLS IDs) - - `/v0/players/online` — online FLS IDs - - `/v0/players/intransit`, `/v0/graceperiod`, `/v0/completion`, `/v0/queued` — player status endpoints - - `/v0/BattlegroupFetchFlsReportSettings` — FLS report config - - `/v0/BattlegroupUpdateFlsReportSettings` — POST to update FLS settings - - `/v0/BattlegroupClearFlsReportOverrides` — POST to clear overrides - - BGD Web UI at `/` shows: player stats, FLS settings, character transfer settings, per-map server overview with player counts/queue/status, per-server settings (force lock, caps), instance scaling config - - `/v0/battlegroup` JSON contains: `dimensionMaps[]`, `singleServerMaps[]`, `instancedMaps[]` with per-server `partition`, `ip`, `gamePort`, `numPlayers*`, `status`, `cfg`, `lastServerState` (includes `serverGameplaySettings`: hydration, sandstorm, sandworm, PvP, security zones, mining multiplier, durability, etc.) -27. **PostgreSQL Database Admin Functions discovered (517 total in `dune` schema):** - - `_add_item_delete_log(in_item_id bigint, in_inventory_id bigint, in_template_id text)` - - `_add_item_trace_log(in_function_name dune.itemtrackingfunctiontype, in_item_locations dune.inventoryitemlocation[])` - - `_add_item_trace_log(in_function_name dune.itemtrackingfunctiontype, in_item_id bigint, in_inventory_id bigint, in_template_id text, in_position_index bigint)` - - `_building_validate_totem_owner_id(in_totem_owner_id bigint)` - - `_character_transfer_allocate_id(kind dune._charactertransferentrykind, data jsonb)` - - `_character_transfer_create_data_table()` - - `_character_transfer_data_filter(id text, removed text[], VARIADIC refs dune._charactertransferdatafilterref[])` - - `_character_transfer_data_table_load(entries jsonb)` - - `_character_transfer_data_table_save()` - - `_character_transfer_ensure_player_is_owner_of_vbt_vehicle(in_vehicle_id bigint[])` - - `_character_transfer_get_filter(kind dune._charactertransferentrykind)` - - `_character_transfer_get_patches_checksum()` - - `_character_transfer_pre_export_validation(in_fls_id text)` - - `_character_transfer_property_not_exported_is_expected(path text)` - - `_character_transfer_replace_local_id_with_transfer_id(data text, path text)` - - `_character_transfer_replace_local_id_with_transfer_id_in_json(data jsonb, path text)` - - `_character_transfer_replace_transfer_id_with_local_id(data text, path text)` - - `_character_transfer_replace_transfer_id_with_local_id_in_json(data jsonb, path text)` - - `_character_transfer_store_in_world_owned_vehicles_into_recovery(in_player_id bigint)` - - `_character_transfer_top_level_export(in_kind dune._charactertransferentrykind, data jsonb)` - - `_character_transfer_top_level_import(in_kind dune._charactertransferentrykind, data jsonb, in_id bigint)` - - `_placeable_validate_totem_owner_id(in_totem_owner_id bigint)` - - `_user_data_encryption_initially_encrypt_existing_data()` - - `_user_data_encryption_setup_enabled(key_hash bytea)` - - `_user_data_encryption_setup_tainted()` - - `accept_guild_invite(in_invite_id bigint, in_role_id smallint, in_max_guild_count_per_player integer, in_max_members_per_guild integer, in_neutral_faction_id smallint)` - - `accept_party_invite(in_invite_id bigint, in_platform_session_id text, in_max_party_member_count integer)` - - `add_actor_audit(in_id bigint, in_class text)` - - `add_event_log_data(in_game_event_owner bigint, in_universe_time bigint, in_map_name text, in_partition_id bigint, in_event_type integer, in_x_location double precisio...)` - - `add_event_log_data_batched(in_data dune.eventlogbulkentrydata[])` - - `add_guild_invite(in_player_id bigint, in_guild_id bigint, in_sender_player_id bigint, in_invite_sent_timespan bigint, in_max_guild_invites_per_guild integer)` - - `add_guild_member(in_player_id bigint, in_guild_id bigint, in_role_id smallint, in_max_guild_count_per_player integer, in_max_members_per_guild integer, in_neutral_f...)` - - `add_landclaim_segment(in_totem_id bigint, in_grid_location_x bigint, in_grid_location_y bigint)` - - `add_map_areas_surveyed_items(in_account_id bigint, in_area_id smallint, in_survey_point_marker_id bigint, in_surveyed_items_target jsonb, in_surveyed_items_progress jsonb, in_m...)` - - `add_map_areas_time_discovered(in_account_id bigint, in_area_id smallint, in_time_discovered timestamp without time zone, in_map_name text)` - - `add_map_areas_time_first_entered(in_account_id bigint, in_area_id smallint, in_time_first_entered timestamp without time zone, in_map_name text)` - - `add_partition_unique(in_map text, in_definition jsonb, in_dimension bigint, in_label text)` - - `add_party_invite(in_sender_player_id bigint, in_sender_platform_name text, in_sender_platform_session_id text, in_player_id bigint, in_max_party_member_count intege...)` - - `adjust_player_virtual_currency_balance(in_controller_id bigint, in_currency_id smallint, in_delta bigint)` - - `admin_get_character_details(in_account_id bigint)` - - `admin_get_character_ids(in_search_term text)` - - `admin_get_inventory_details(in_account_id bigint)` - - `admin_get_journey_details(in_player_id text, in_story_node_id text)` - - `admin_get_mnemonic_recall_details(in_account_id bigint)` - - `admin_get_partitions()` - - `admin_move_offline_player(in_fls_id text, in_target_partition_name text, in_target_location dune.vector)` - - `admin_move_offline_player_to_partition(in_fls_id text, in_target_partition_id bigint, in_target_location dune.vector)` - - `admin_read_player_tags(in_account_id bigint)` - - `advance_items_id_sequencer(count bigint)` - - `assign_actor_id(in_class text)` - - `base_backup_delete(in_base_backup_id bigint)` - - `base_backup_find_totems_from_player_owner(in_player_id bigint)` - - `base_backup_finish_placing(in_base_backup_id bigint)` - - `base_backup_get_actors_to_spawn(in_base_backup_id bigint)` - - `base_backup_get_available_backups(in_player_id bigint)` - - `base_backup_get_buildable_data(in_base_backup_id bigint)` - - `base_backup_get_data(in_base_backup_id bigint)` - - `base_backup_get_totem_data(in_base_backup_id bigint)` - - `base_backup_get_totem_data_from_totem_id(in_totem_id bigint)` - - `base_backup_get_totem_id(backup_id bigint)` - - `base_backup_recycle(in_base_backup_id bigint, in_target_inventory_id bigint)` - - `base_backup_save(in_player_actor_id bigint, in_base_backup_name text, in_building_pieces_to_link dune.basebackupbuildingitem[], in_placeables_to_link bigint[], in_p...)` - - `base_backup_save_all_totems_from_player_owner(in_player_id bigint)` - - `base_backup_save_from_totem(in_player_id bigint, totem_id bigint)` - - `break_guild_allegiance(in_guild_id bigint, in_neutral_faction_id smallint)` - - `can_takeover_account(in_user_id text)` - - `change_player_faction(in_player_id bigint, in_faction_id smallint, neutral_faction_id smallint, in_utc_time_faction_change timestamp without time zone)` - - `character_migration_export(in_fls_id text)` - - `character_migration_import(in_data jsonb, in_fls_id text, in_character_name text)` - - `character_transfer_export(in_fls_id text)` - - `character_transfer_get_unsaved_counts(in_fls_id text)` - - `character_transfer_import(in_data jsonb, in_fls_id text, in_character_name text)` - - `clean_expired_party_invites(in_invite_expire_seconds integer)` - - `clean_guild_invites_with_incompatible_faction(in_player_id bigint, in_faction_id smallint, neutral_faction_id smallint)` - - `clean_old_guild_invites(in_cutoff_timespan bigint)` - - `clean_stock_for_player(in_player_id bigint)` - - `clean_stock_for_vendors(in_vendor_ids text[])` - - `clean_vendors_older_than_timestamp(in_reference_timestamp bigint)` - - `cleanup_account_log_and_orphaned_actors()` - - `cleanup_accounts_marked_for_deletion_in_fls(in_account_ids text[])` - - `cleanup_orphaned_entities()` - - `clear_map_areas_data_for_player(in_id bigint)` - - `complete_journey_nodes_where_prerequisite_nodes_are_complete(story_ids_to_complete text[], prerequisite_completed_story_ids text[])` - - `complete_journey_story_nodes_for_player(in_player_id text, in_story_node_ids text[])` - - `corilis_cleanup_map(in_server_info dune.serverinfo, in_map_info dune.coriolismapinfo)` - - `coriolis_cleanup_farm(in_server_info dune.serverinfo, in_map_info dune.coriolismapinfo)` - - `coriolis_cleanup_partition(in_server_info dune.serverinfo, in_map_info dune.coriolismapinfo)` - - `coriolis_update_seed(in_server_info dune.serverinfo, in_new_coriolis_seed integer, in_map_info dune.coriolismapinfo)` - - `create_event_log_partition()` - - `create_guild(in_player_id bigint, in_neutral_faction smallint, in_guild_name text, in_guild_desc text, in_max_guild_count_per_player integer, OUT out_guild_id b...)` - - `create_or_update_tutorial_entry(in_player_id bigint, in_tutorial_id smallint, in_tutorial_state smallint)` - - `create_server_player_access_codes(in_account_id bigint, in_access_code integer, in_access_code_type integer, in_is_resettable boolean)` - - `create_sinkchart_for_map_area_id(in_item_id bigint, in_creator_id bigint, in_map_name text, in_area_id smallint)` - - `debug_add_test_table_data(in_entry text)` - - `debug_collect_test_table_data()` - - `debug_echo(in_text text, in_notices text[])` - - `debug_get_coriolis_seeds()` - - `debug_raise_exception(in_exception text, in_notices text[])` - - `debug_raise_notices(in_notices text[])` - - `debug_reset_test_table()` - - `debug_set_farm_seed(in_new_coriolis_seed integer)` - - `debug_set_map_seed(in_map text, in_new_coriolis_seed integer)` - - `debug_set_partition_seed(in_partition_id bigint, in_new_coriolis_seed integer)` - - `decrypt_user_data(in_encrypted_data bytea)` - - `delete_account(in_user_id text, in_reason text)` - - `delete_actor_states_travel(in_actor_id bigint)` - - `delete_actors(in_ids bigint[])` - - `delete_actors_and_respawns_on_server(in_server_info dune.serverinfo, in_vehicle_classes_spawned_on_map text[], in_allow_vehicle_recovery boolean)` - - `delete_all_dungeon_completions(in_dungeon_id text)` - - `delete_all_dungeon_completions_by_player(in_dungeon_id text, in_player_id bigint, in_keep_completion_for_other_players boolean)` - - `delete_all_dungeon_completions_for_all_dungeons_by_player(in_player_id bigint, in_keep_completion_for_other_players boolean)` - - `delete_all_inactive_farms()` - - `delete_all_journey_story_nodes(in_account_id bigint)` - - `delete_all_static_shifting_sand()` - - `delete_all_tutorial_entries(in_player_id bigint)` - - `delete_building_blueprint(in_building_item_id bigint)` - - `delete_character(in_actor_id bigint)` - - `delete_crafted_map(in_item_id bigint)` - - `delete_dialogue_data(in_player_controller_id bigint)` - - `delete_inventory_item(in_item_id bigint, in_count bigint)` - - `delete_item(in_id bigint)` - - `delete_items(in_ids bigint[])` - - `delete_items_from_actor(in_actor_id bigint)` - - `delete_journey_story_ids(story_ids text[])` - - `delete_journey_story_node(in_account_id bigint, in_story_node_id text)` - - `delete_journey_story_nodes_for_group_for_player(in_account_id bigint, in_reset_group dune.journeystoryresetgroup)` - - `delete_journey_story_nodes_for_player(in_player_id text, in_story_node_ids text[])` - - `delete_journey_story_nodes_for_player_account(in_account_id bigint, in_story_node_ids text[])` - - `delete_map_markers(in_dimension_index integer, in_map_name text, in_player_marker_data dune.deleteplayermarkerdata[])` - - `delete_markers_by_id(in_marker_ids integer[])` - - `delete_markers_by_static_location_key(p_location_key text)` - - `delete_markers_for_all_players(in_marker_types_to_keep text[], in_map text)` - - `delete_markers_return_actor_ids(in_dimension_index integer, in_map_name text, in_marker_ids integer[])` - - `delete_mnemonic_recall_lesson(in_account_id bigint, in_lesson_id text)` - - `delete_mnemonic_recall_lesson_all(in_account_id bigint)` - - `delete_server_player_access_codes(in_account_id bigint, in_access_code integer, in_access_code_type integer)` - - `delete_spawner(in_map text, in_name text, in_dimension_index integer)` - - `delete_static_location_markers(p_location_keys text[])` - - `delete_world_partition_by_map_id(in_map_id text)` - - `demote_guild_member(in_guild_id bigint, in_player_id bigint, in_new_role smallint)` - - `determine_partition_label(in_map text, in_dimension_index integer, in_label text, in_allow_overwrite boolean, in_partition_id bigint)` - - `determine_partition_label_trigger()` - - `disband_guild(in_guild_id bigint)` - - `disband_party(in_party_id bigint)` - - `downgrade_map_name(in_map_name text)` - - `drain_item_tracking_data()` - - `dune_exchange_add_sell_order(in_exchange_id bigint, in_access_point_id bigint, in_owner_id bigint, in_max_orders_per_player integer, in_expiration_time bigint, in_item_id bigin...)` - - `dune_exchange_cancel_order(in_order_id bigint, in_purge_time bigint, in_completion_type integer)` - - `dune_exchange_expire_orders(in_exchange_id bigint, in_current_time bigint, in_purge_time bigint, in_expired_completion_type integer)` - - `dune_exchange_fulfill_sell_order(in_exchange_id bigint, in_max_orders_per_player integer, in_purchased_completion_type integer, in_sold_completion_type integer, in_instigator_id bi...)` - - `dune_exchange_get_item_price_stats(in_template_ids text[])` - - `dune_exchange_get_user_id(in_owner_id bigint)` - - `dune_exchange_modify_user_solari_balance(in_controller_id bigint, in_solari_delta bigint)` - - `dune_exchange_purge_completed_orders(in_exchange_id bigint, in_current_time bigint)` - - `dune_exchange_query_storage_item(in_order_id bigint)` - - `dune_exchange_query_storage_items(in_exchange_id bigint, in_owner_id bigint)` - - `dune_exchange_relist_order(in_order_id bigint, in_expiration_time bigint, in_item_price bigint, in_wear_normalized_item_price bigint, in_solari_cost bigint)` - - `dune_exchange_retrieve_solari_balance(in_owner_id bigint)` - - `dune_exchange_retrieve_solaris_from_item(in_controller_id bigint, in_order_id bigint)` - - `dune_exchange_retrieve_storage_item(in_exchange_id bigint, in_order_id bigint, in_dst_inventory_id bigint, in_dst_index bigint, in_count bigint)` - - `dune_exchange_update_recurring_sell_order(in_exchange_id bigint, in_expiration_time bigint, in_access_point_id bigint, in_owner_id bigint, in_item_id bigint, in_increment bigint, in_max_cou...)` - - `dune_get_account_id_by_user(in_user text)` - - `edit_guild_description(in_guild_id bigint, in_guild_desc text)` - - `encrypt_user_data(in_data text)` - - `fetch_resourcefield_state(in_map text, in_dimension_index integer, in_field_kind_id smallint)` - - `fetch_server_spice_field_manifest(in_server_id text)` - - `fetch_spicefie_id_types_with_global_info(in_map_name text, in_dimension_index integer)` - - `find_actor_by_id(in_id bigint)` - - `fix_broken_harkonnen_players_due_to_fooled_thufir()` - - `flag_player_as_cheater(in_account_id bigint, in_cheat_type dune.cheat_type_enum)` - - `gather_ownerless_actors_on_server(in_server_info dune.serverinfo)` - - `gather_player_linked_actors(in_player_pawn_id bigint)` - - `gather_removed_accounts_that_left_orphaned_actors_on_server(in_server_info dune.serverinfo)` - - `get_account_actor_ids(in_account_id bigint)` - - `get_active_servers_for_gateway()` - - `get_actor_server_info(in_id bigint)` - - `get_actors_location_data_with_permission(in_actor_ids bigint[])` - - `get_all_demo_players()` - - `get_all_faction_members()` - - `get_all_guild_members()` - - `get_all_online_or_recently_disconnected_player_online_state()` - - `get_all_parties()` - - `get_all_party_invites()` - - `get_all_party_members()` - - `get_all_player_character_home_dimensions()` - - `get_all_player_in_guild_online_state(in_guild_id bigint)` - - `get_all_player_travel_states()` - - `get_all_tutorial_entries(in_player_id bigint)` - - `get_all_unresolved_character_imports()` - - `get_applied_patches()` - - `get_battlegroup_close_date()` - - `get_best_dungeon_completion(in_dungeon_id text)` - - `get_best_dungeons_completions_for_player(in_player_id bigint)` - - `get_building_blueprint_copy_data(in_building_blueprint_id bigint)` - - `get_building_favorites(in_account_id bigint)` - - `get_building_id(in_actor_id bigint, in_class text)` - - `get_character_import_state(in_fls_id text)` - - `get_character_transfer_related_items(in_fls_id text)` - - `get_consumed_lore_pickups(in_actor_id bigint, in_use_temporary boolean)` - - `get_controller_id_from_platform_id(in_platform_id text)` - - `get_dune_exchange_accesspoint_id(in_exchange_id bigint, in_name text)` - - `get_dune_exchange_data(in_exchange_id bigint, in_controller_id bigint)` - - `get_dune_exchange_id(in_name text)` - - `get_dune_exchange_used_order_slots(in_controller_id bigint)` - - `get_exchange_inventory_id(in_exchange_id bigint)` - - `get_exchange_orders_by_mask(in_mask integer, in_depth smallint)` - - `get_exchange_sell_orders(in_id bigint, in_exchange_id bigint, in_min_item_price bigint, in_max_item_price bigint, in_template_id text, in_mask integer, in_depth smallint)` - - `get_exchange_sell_orders_by_item_type(in_exchange_id bigint, in_template_ids text[])` - - `get_exchange_sell_orders_by_owner(in_exchange_id bigint, in_owner_id bigint)` - - `get_farm_state()` - - `get_friends_search(in_player_name text, in_max_players_count integer)` - - `get_guild_data(in_guild_id bigint)` - - `get_guild_data_for_player(in_player_id bigint)` - - `get_guild_for_player(in_player_id bigint)` - - `get_guild_invites(in_guild_id bigint)` - - `get_guild_members(in_guild_id bigint)` - - `get_inventory_data(in_inventory_id bigint)` - - `get_inventory_id(in_actor_id bigint, in_component_name_hash integer)` - - `get_items_to_remove(items_to_remove text[])` - - `get_landclaim_segments(in_totem_id bigint)` - - `get_learned_building_sets(in_account_id bigint)` - - `get_learned_new_buildable_pieces(in_account_id bigint)` - - `get_login_journey_nodes(in_account_id bigint)` - - `get_login_journey_nodes_cooldown(in_account_id bigint)` - - `get_mnemonic_recall_lessons(in_account_id bigint)` - - `get_online_player_controller_ids(in_map text)` - - `get_online_player_controller_ids_on_farm()` - - `get_partition_presets()` - - `get_partitions(in_map text)` - - `get_party_members(in_party_id bigint)` - - `get_permission_actors_for_server(in_server_info dune.serverinfo)` - - `get_permission_for_actor(in_actor_id bigint)` - - `get_permission_for_actors(in_actor_id bigint[])` - - `get_permission_for_player_actors(in_player_id bigint, in_min_rank smallint)` - - `get_placeable_id(in_actor_id bigint, in_class text, in_building_type text)` - - `get_player_access_codes(in_account_id bigint)` - - `get_player_current_faction_reputation(in_actor_id bigint, OUT out_faction_id smallint, OUT out_reputation_amount integer)` - - `get_player_faction(in_player_id bigint, in_neutral_faction_id smallint)` - - `get_player_faction_name(in_actor_id bigint, OUT player_faction_name text, OUT utc_time_faction_change timestamp without time zone)` - - `get_player_guild_invites(in_player_id bigint)` - - `get_player_ids_online_state(in_player_ids bigint[])` - - `get_player_infos_for_actor_ids(in_actor_ids bigint[])` - - `get_player_infos_for_character_names(in_character_names text[])` - - `get_player_infos_for_fls_ids(in_fls_ids text[])` - - `get_player_infos_for_funcom_ids(in_funcom_ids text[])` - - `get_player_online_state_within_grace_period_for_each_server()` - - `get_player_owned_vehicles_data(in_player_id bigint, in_account_id bigint)` - - `get_player_partition_id(in_fls_id text)` - - `get_player_pawn(in_account_id bigint)` - - `get_player_virtual_currency_balances(in_controller_id bigint)` - - `get_players_demo_data(in_controller_ids bigint[])` - - `get_recipes_to_remove(recipes_to_remove text[])` - - `get_registered_spawned_actor(in_spawner_id bigint)` - - `get_respawn_locations(in_account_id bigint)` - - `get_schema_version()` - - `get_solaris_id()` - - `get_spawner_id(in_map text, in_name text, in_dimension_index integer)` - - `get_stored_user_data_encryption_key_hash()` - - `get_stored_user_data_encryption_status()` - - `get_stored_user_data_encryption_taint_xmax()` - - `get_sub_inventory_id(in_owner_item_id bigint)` - - `get_traveling_actor_id_and_types(in_actor_id bigint)` - - `get_traveling_actor_ids(in_actor_id bigint, in_max_recursion_level integer)` - - `get_traveling_actors_fls_ids(in_actor_id bigint)` - - `get_traveling_non_player_actor_ids(in_actor_id bigint)` - - `get_unbacked_up_vehicle_ids_for_account(in_account_id bigint)` - - `get_universe_time()` - - `get_unsaved_base_totem_ids_for_account(in_account_id bigint)` - - `get_vehicle_id(in_actor_id bigint, in_class text)` - - `get_vehicle_module_inventory_id(in_vehicle_module_id bigint, in_vehicle_module_inventory_type integer)` - - `guild_handle_actor_delete(in_player_id bigint)` - - `guilds_get_exclusive_operation_lock()` - - `handle_player_faction_guild_effects(in_player_id bigint, in_faction_id smallint, neutral_faction_id smallint)` - - `igwo_delete_world_partitions(in_partition_ids bigint[])` - - `igwo_get_partition_id_seq_last_value()` - - `igwo_get_partition_ids()` - - `igwo_get_partitions()` - - `igwo_get_server_details()` - - `igwo_insert_world_partition(in_partition_id bigint, in_map text, in_partition_definition jsonb, in_dimension_index integer, in_partition_label text)` - - `igwo_next_partition_id_seq()` - - `igwo_notify_world_partition_update()` - - `igwo_restart_partition_id_seq(in_restart_with bigint)` - - `igwo_update_world_partition(in_map text, in_partition_definition jsonb, in_partition_id bigint, in_dimension_index integer, in_label text)` - - `init_event_log(in_partition_id bigint)` - - `initialize_partitions_basic_battlegroup()` - - `initialize_partitions_basic_survival_1()` - - `initialize_partitions_development_battlegroup()` - - `initialize_partitions_editor_default_1x1()` - - `initialize_partitions_full_battlegroup()` - - `initialize_partitions_igw_test_small_2x1()` - - `initialize_partitions_igw_test_small_2x2()` - - `initialize_partitions_igw_training()` - - `initialize_specialization_keystones(in_keystones text[])` - - `initialize_world_partition(in_map_name text, in_num_servers integer, in_dimension_index integer)` - - `interact_get_vendor_items_bought_from_player(in_vendor_id text, in_player_id bigint, in_current_cycle_start_timestamp bigint)` - - `internal_add_party_member(in_invite_id bigint, in_party_id bigint, in_player_id bigint, in_platform_session_id text, in_platform_name text, in_max_party_member_count integer)` - - `internal_create_party(in_invite_id bigint, in_leader_id bigint, in_leader_platform_session_id text, in_leader_platform_name text, in_member_id bigint, in_platform_sessio...)` - - `is_player_guild_admin(in_player_id bigint, in_guild_id bigint)` - - `is_player_offline(in_fls_id text)` - - `is_player_party_leader(in_player_id bigint, in_party_id bigint)` - - `join_platform_session_party(in_leader_platform_id text, in_player_platform_id text, in_platform_session_id text, in_platform_name text, in_max_party_member_count integer)` - - `journey_story_node_cooldown_add(in_account_id bigint, in_story_node_id text, in_time_to_expire timestamp without time zone)` - - `journey_story_node_cooldown_delete_expired(in_time_to_check timestamp without time zone)` - - `landsraad_cast_vote(in_term_id bigint, in_player_id bigint, in_decree_name text)` - - `landsraad_change_term_end_time(end_term_id bigint, new_end_time timestamp without time zone, in_test_term boolean)` - - `landsraad_check_task_completion()` - - `landsraad_check_term_won()` - - `landsraad_collect_task_telemetry_for_faction(in_term_id bigint, in_faction_name text)` - - `landsraad_collect_term_telemetry(in_term_id bigint, in_faction_names text[])` - - `landsraad_collect_term_telemetry_for_faction(in_term_id bigint, in_faction_name text)` - - `landsraad_collect_vote_telemetry(in_term_id bigint, in_winning_faction_id integer)` - - `landsraad_collect_votes(in_term_id bigint)` - - `landsraad_determine_winner(in_term_id bigint)` - - `landsraad_force_end_term(end_term_id bigint)` - - `landsraad_has_term_of_task_ended(in_task_id bigint)` - - `landsraad_initialize_system(number_of_weeks_term_retention integer, number_of_nominated_decrees integer, in_end_time timestamp without time zone, in_test_term boolean, faction...)` - - `landsraad_initialize_term(number_of_weeks_term_retention integer, number_of_nominated_decrees integer, in_end_time timestamp without time zone, in_test_term boolean, tasks d...)` - - `landsraad_insert_task_progress(in_term_id bigint, in_player_id bigint, in_guild_id bigint, in_house_name text, in_faction_progress integer, in_guild_progress real, in_player_prog...)` - - `landsraad_insert_task_progress_batched(in_term_id bigint, in_task_progress dune.landsraadtaskprogress[])` - - `landsraad_insert_task_progress_faction(in_term_id bigint, in_faction_name text, in_house_name text, in_faction_progress integer, in_guild_progress real, in_player_progress real)` - - `landsraad_insert_task_progress_random(in_term_id bigint, in_faction_names text[], in_num_rows integer)` - - `landsraad_load_current_rotation(in_term_id bigint)` - - `landsraad_load_current_term()` - - `landsraad_load_guild_contribution(in_term_id bigint, in_guild_id bigint, in_faction_id bigint)` - - `landsraad_load_guild_contributions(in_term_id bigint, in_num_guilds integer, in_faction_names text[])` - - `landsraad_load_guild_vote(in_term_id bigint, in_player_id bigint)` - - `landsraad_load_house_rewards(in_player_id bigint)` - - `landsraad_load_player_contributions(in_term_id bigint, in_player_ids bigint[])` - - `landsraad_load_task_faction_progress(in_term_id bigint)` - - `landsraad_load_task_faction_reveal_state(in_term_id bigint)` - - `landsraad_load_term_progress(in_term_id bigint, in_num_guilds integer, in_faction_names text[], in_player_ids bigint[])` - - `landsraad_notify_house_rewards_changed()` - - `landsraad_perform_daily_task_reveal(in_term_id bigint, in_faction_names text[], in_house_names_to_reveal text[], in_reveal_day integer)` - - `landsraad_process_house_rewards()` - - `landsraad_process_task_progress(max_rows integer)` - - `landsraad_task_has_been_completed(in_task_id bigint)` - - `landsraad_update_task_faction_reveal_state(in_term_id bigint, in_task_board_index integer, faction_name text, reveal_state boolean)` - - `landsraad_withdraw_house_reward(in_player_id bigint, in_house_rewards dune.landsraadplayerhousereward[])` - - `load_actors(in_actor_ids bigint[], in_actor_state dune.actorstate)` - - `load_backup_vehicle(in_account_id bigint)` - - `load_building(in_building_id bigint)` - - `load_communinet_player_data(in_account_id bigint)` - - `load_dialogue_data(in_player_controller_id bigint, OUT met_npcs text[], OUT taken_nodes integer[])` - - `load_dimension_index(in_map text, in_partition_id bigint)` - - `load_events_log_data_from_player(in_actor_id bigint, in_limit_entries_num integer)` - - `load_full_actors(in_ids bigint[])` - - `load_item(in_item_id bigint)` - - `load_items(in_inventory_id bigint)` - - `load_map_areas_entries(in_account_id bigint, in_map_name text)` - - `load_markers(in_player_id bigint, in_dimension_id integer, in_map_name text)` - - `load_partition_definition_map()` - - `load_placeable(in_placeable_id bigint)` - - `load_recovered_vehicles(in_account_id bigint, in_restore_time_limit integer)` - - `load_static_encounter_name(in_map_name text, in_package_name text, in_actor_name text)` - - `load_takeoverable_user_ids()` - - `load_totem(in_id bigint)` - - `load_travel_return_info(in_player_controller_id bigint)` - - `load_travel_to_player_info(in_player_controller_id bigint)` - - `load_vehicle_modules(in_vehicle_id bigint)` - - `load_world_partition(in_map_name text, in_server_id text, in_desired_dimension_index bigint, in_desired_partition_id bigint)` - - `log_cheating(in_fls_id text, in_cheat_type dune.cheat_type_enum, in_event_time timestamp with time zone)` - - `log_event_solaris(in_function_oid oid, in_message dune.logmessagetype, in_controller_id bigint, in_solaris_balance bigint, in_solaris_delta bigint)` - - `login_account(in_user_id text, in_funcom_id text, in_platform_id text, in_platform_name text, in_minimum_returning_player_time_seconds integer, in_character_name...)` - - `mark_server_dead(in_server_id text)` - - `merge_inventory_items(in_item_id bigint, in_dst_inventory_id bigint, in_dst_index bigint, in_count bigint)` - - `merge_or_move_inventory_item(in_item_id bigint, in_dst_inventory_id bigint, in_dst_index bigint, in_count bigint)` - - `migrate_character(in_account_id bigint, home_dimension integer, max_solaris_allowed bigint)` - - `migrate_clamp_max_allow_solaris(in_pawn_id bigint, max_solaris_allowed bigint)` - - `move_inventory_item(in_item_id bigint, in_dst_inventory_id bigint, in_dst_index bigint, in_count bigint)` - - `overmap_delete_player_survival_data(in_player_id bigint)` - - `overmap_load_player_survival_data(in_player_id bigint)` - - `overmap_save_player_survival_data(in_player_id bigint, in_vehicle_id bigint, in_has_polar_psu boolean, in_overmap_location dune.vector)` - - `ownership_handle_actor_delete(in_player_id bigint)` - - `parties_get_exclusive_operation_lock()` - - `perform_notify_on_character_delete(in_user_id text)` - - `permission_actor_create_or_update_base_marker(in_actor_id bigint, in_player_id bigint, in_rank smallint)` - - `permission_actor_destroy(in_actor_id bigint)` - - `permission_actor_register(in_entry dune.actorpermissionentry, in_owner_rank dune.actorpermissionrankdata)` - - `permission_actor_takeover(in_entry dune.actorpermissionentry, in_owner_rank dune.actorpermissionrankdata)` - - `permission_actor_update_marker_location(in_actor_id bigint, in_location_x real, in_location_y real, in_location_z real)` - - `permission_remove_player_rank(in_actor_id bigint, in_player_id bigint)` - - `permission_set_access_level(in_actor_id bigint, in_access_level smallint)` - - `permission_set_name(in_actor_id bigint, in_name text)` - - `permission_set_player_rank(in_actor_id bigint, in_player_id bigint, in_rank smallint, in_map_id text)` - - `player_purchased_item_from_vendor(in_vendor_id text, in_player_id bigint, in_template_id text, in_amount_bought integer)` - - `player_state_update(in_data dune.playerstateupdatedata[])` - - `pledge_guild_allegiance(in_guild_id bigint, in_guild_leader_player_id bigint, in_neutral_faction_id smallint)` - - `produce_spicefield_manifest(in_map_name text, in_dimension_index integer)` - - `promote_guild_member(in_guild_id bigint, in_player_id bigint, in_new_role smallint)` - - `promote_new_party_leader(in_party_id bigint)` - - `promote_party_leader_to(in_party_id bigint, in_player_id bigint)` - - `purchase_specialization_keystone(in_player_id bigint, in_keystone text)` - - `record_deactivated_spice_field(in_server_id text, in_spicefield_type_id integer)` - - `record_dungeon_completion(in_dungeon_id text, in_difficulty integer, in_duration_ms integer, players_ids bigint[])` - - `record_logoff_persistence_end_time(in_player_pawn_id bigint, in_logoff_persistence_end_time timestamp without time zone)` - - `record_static_shifting_sand(in_id text, in_alpha double precision, in_x double precision, in_y double precision, in_last_modified_time bigint)` - - `record_unreadied_spice_fields(in_server_id text, in_spicefield_type_id integer, in_num_unreadied integer)` - - `register_lore_pickup(in_lore_pickup_ids text[])` - - `register_new_factions(factions text[])` - - `register_new_tutorials(tutorials text[])` - - `register_per_player_lore_pickup(in_lore_pickup_ids text[], in_use_temporary boolean)` - - `register_spawned_actor(in_spawner_id bigint, in_actor_id bigint)` - - `register_spice_field_server_resources(in_server_id text, in_spicefield_type_ids integer[], in_inactive_fields_of_types integer[])` - - `register_temporary_lore_pickup(in_lore_pickup_ids text[])` - - `reject_guild_invite(in_invite_id bigint)` - - `remove_aborted_authority_transfer_actors(in_partition_id bigint)` - - `remove_character_transfer_state(in_fls_id text)` - - `remove_communinet_player_channel(in_account_id bigint, in_channel_name text)` - - `remove_guild_members(in_player_ids bigint[], in_guild_id bigint, in_remove_reason smallint)` - - `remove_items(items_to_remove text[])` - - `remove_items_and_recipes(items_to_remove text[], recipes_to_remove text[])` - - `remove_items_or_recipes_from_fgl_entities(item_or_recipes text[])` - - `remove_members_offline_for(in_interval_seconds integer)` - - `remove_party_invite(in_invite_id bigint, in_remove_reason smallint)` - - `remove_party_member(in_player_id bigint, in_remove_reason smallint)` - - `remove_recipes_from_actor_properties(recipes_to_remove text[])` - - `remove_resourcefield_states(in_map text, in_dimension_index integer, in_field_ids bigint[])` - - `request_spawn_spice_field(in_server_id text, in_spicefield_type_id integer)` - - `reset_all_players_from_server_ids_grace_period_and_logoff_timer(in_server_id text, in_reset_time timestamp without time zone)` - - `reset_global_spice_field_state(in_map_name text, in_dimension_index integer)` - - `reset_journey_story_nodes_for_player(in_player_id text, in_story_node_ids text[])` - - `reset_server_all_player_access_codes(in_account_id bigint)` - - `reset_specialization_keystones(in_player_id bigint)` - - `reset_specialization_tracks(in_player_id bigint)` - - `restore_backup_vehicle(in_account_id bigint, in_server_info dune.serverinfo, in_transform dune.transform)` - - `restore_recovered_vehicle(in_account_id bigint, in_vehicle_id bigint, in_server_info dune.serverinfo, in_transform dune.transform, in_restore_time_limit integer)` - - `retrieve_all_static_shifting_sand()` - - `returning_player_award_given(in_account_id bigint)` - - `reveal_journey_story_nodes_for_player(in_player_id text, in_story_node_ids text[])` - - `save_aborted_authority_transfer_actors(in_actor_ids bigint[], in_partition_id bigint)` - - `save_actor_dislocation(in_actor_id bigint, in_current_server_info dune.serverinfo, in_target_location dune.vector, in_target_dimension_index integer)` - - `save_actors(in_server_info dune.serverinfo, in_actors dune.actordescription[], in_actor_state dune.actorstate)` - - `save_building(in_building_id bigint, in_data dune.buildingsavedata)` - - `save_building_blueprint_copy(in_building_item_id bigint, in_building_blueprint_id bigint, in_building_blueprint_building_data dune.buildingblueprintpiecesaveitemcontainer[], in...)` - - `save_demo_account_time(in_fls_id text, in_demo_playtime_seconds integer)` - - `save_dialogue_data(in_player_controller_id bigint, in_met_npcs text[], in_taken_nodes integer[])` - - `save_item(in_item dune.inventoryitem)` - - `save_journey_story_node(in_account_id bigint, in_story_node_id text, in_override_reward_block boolean, in_has_pending_reward boolean, in_complete_condition_state jsonb, in...)` - - `save_journey_story_nodes(in_account_id bigint, in_journey_data dune.savejourneydata[])` - - `save_login_target_dimension(in_fls_id text, in_login_target_dimension_index integer)` - - `save_markers(in_player_marker_data dune.saveplayermarkerdata[], in_marker_data dune.savemarkerdata[])` - - `save_mnemonic_recall_lesson(in_account_id bigint, in_lesson_id text, in_lesson_state bigint, in_lesson_progress integer, in_is_new boolean)` - - `save_placeable(in_placeable_id bigint, in_data dune.placeablesavedata)` - - `save_player(in_player dune.playerdescription)` - - `save_player_pawn(in_pawn dune.actordescription, in_server_info dune.serverinfo, in_life_state dune.playerlifestate)` - - `save_static_encounter_name(in_map_name text, in_package_name text, in_actor_name text, in_encounter_name text)` - - `save_static_encounter_waiting_for_reset(in_map_name text, in_package_name text, in_actor_name text, in_waiting_for_reset boolean)` - - `save_totem(in_id bigint, in_data dune.totemsavedata)` - - `save_tracked_journey_cards(in_player_id bigint, in_tracked_journey_card text, in_tracked_landsraad_card text)` - - `save_travel_return_info(in_player_controller_id bigint, in_map text, in_transform dune.transform)` - - `save_vehicle_modules(in_add_list dune.vehiclemodule[], in_delete_list bigint[], in_stat_update dune.itemstatupdate[])` - - `save_world_partition(in_map_name text, in_server_id text, in_dimension_index bigint, in_partition_definition jsonb, in_blocked boolean, in_label text)` - - `server_info_match(in_actor dune.actors, in_server_info dune.serverinfo)` - - `set_account_as_takeoverable(in_user_id text, in_new_user_id text)` - - `set_all_inactive_players_in_farm_offline()` - - `set_battlegroup_close_date(in_close_date timestamp without time zone)` - - `set_character_import_state(in_fls_id text, in_state dune.transferimportstate)` - - `set_character_name(in_account_id bigint, in_name text)` - - `set_demo_state(in_user_id text, in_demo_state dune.demostate)` - - `set_item_tracking_enabled(in_enabled boolean)` - - `set_player_faction_reputation(in_actor_id bigint, in_faction_id smallint, in_reputation_amount integer)` - - `set_players_from_server_ids_offline(in_server_ids text[])` - - `set_specialization_xp_and_level(in_player_id bigint, in_track_type dune.specializationtracktype, in_xp_amount integer, in_level real)` - - `store_backup_vehicle(in_vehicle_id bigint, in_account_id bigint, in_customization_id text)` - - `store_recovered_vehicle(in_vehicle_id bigint, in_chassis_durability real, in_customization_id text, in_is_migration boolean)` - - `store_recovered_vehicles_wiped_before_spawn(in_vehicle_ids bigint[], in_delete_items boolean)` - - `takeover_account(in_user_to_takeover text, in_current_user text)` - - `taxation_emit_invoices(new_tax_invoices dune.taxinvoicedata[])` - - `taxation_get_all_invoices_for_player(in_player_id bigint)` - - `taxation_get_all_invoices_for_server(map_name text, in_dimension_index integer, in_partition_id bigint)` - - `taxation_get_all_invoices_for_totem(in_totem_id bigint)` - - `taxation_pay_invoice(invoice_id bigint, paid_invoice_status smallint)` - - `taxation_remove_invoices(invoices_to_remove bigint[])` - - `taxation_remove_invoices_from_totem(totem_actor_id bigint)` - - `taxation_update_invoice_status(invoices_to_overdue bigint[], invoices_to_defaulted bigint[], overdue_invoice_status smallint, defaulted_invoice_status smallint)` - - `try_prime_spicefield(in_source_server_id text, in_spicefield_id integer)` - - `try_restart_spicefield(in_server_id text, in_spicefield_type_id integer)` - - `try_spawn_spicefield(in_source_server_id text, in_spicefield_id integer)` - - `try_update_exchange_categories_hash(in_new_hash integer)` - - `unassign_partition(in_server_id text)` - - `update_communinet_player_channel(in_account_id bigint, in_channel_name text, in_is_tuned boolean)` - - `update_communinet_player_data(in_account_id bigint, in_is_active boolean, in_selected_channel_name text)` - - `update_consumed_per_player_lore(in_actor_id bigint, in_consumed_bit_array bit, in_use_temporary boolean)` - - `update_coriolis_for_player(in_controller_id bigint, OUT out_was_coriolis_processed boolean)` - - `update_death_location(in_pawn dune.actordescription, in_server_info dune.serverinfo, in_life_state dune.playerlifestate)` - - `update_farm_state(in_server_id text, in_outgoing_s2s_connections integer, in_incoming_s2s_connections integer, in_connected_players integer, in_farm_id text, in_igw_...)` - - `update_global_spice_field_rules(in_max_globally_primed integer, in_max_globally_active integer, in_spicefield_type_id integer)` - - `update_inventories_data(in_inventory_data_list dune.inventorydata[])` - - `update_inventory(in_delete_list bigint[], in_stack_update dune.itemstackupdate[], in_quality_update dune.itemqualityupdate[], in_stat_update dune.itemstatupdate[], ...)` - - `update_item_locations(in_item_locations dune.inventoryitemlocation[])` - - `update_journey_story_ids(old_story_ids text[], new_story_ids text[])` - - `update_marker_ids(in_old_ids integer[], in_new_ids integer[])` - - `update_partition_labels(in_allow_overwrite boolean)` - - `update_party_platform_session(in_party_id bigint, in_platform_session_id text, in_platform_name text)` - - `update_player_tags(in_account_id bigint, tags_to_add text[], tags_to_remove text[])` - - `update_removed_items_and_recipes(items_removed text[], recipes_removed text[])` - - `update_resourcefield_states(in_map text, in_dimension_index integer, in_field_kind_id smallint, in_field_states dune.resourcefieldstateentry[])` - - `update_respawn_locations(player_id bigint, respawn_locations dune.respawnlocation[])` - - `update_returning_player_status(in_user_id text, in_minimum_returning_player_time_seconds integer)` - - `update_sell_orders_categories(category_update_data dune.exchangecategoryupdatedata[])` - - `update_server_building_favorites(in_account_id bigint, in_building_types text[])` - - `update_server_learned_building_sets(in_account_id bigint, in_learned_building_sets text[])` - - `update_server_learned_new_buildable_pieces(in_account_id bigint, in_new_buildable_pieces text[])` - - `update_specialization_refund_id(in_player_id bigint, in_refund_id smallint, in_removed_keystones smallint[])` - - `update_spice_field_spawn_state(in_is_spawning_active boolean, in_spicefield_type_id integer)` - - `update_traveling_actor_dependencies(in_dep dune.traveldependency[])` - - `update_traveling_actor_tree(in_actor_id bigint, in_target_transform dune.transform, in_target_map text, in_target_dimension_index integer, in_target_partition_id bigint)` - - `update_universe_time(in_farm_id text)` - - `update_vendor_timestamp_for_player(in_vendor_id text, in_player_id bigint, in_timestamp bigint)` - - `upgrade_location_data_list(in_location_data_list jsonb, in_map_field_name text)` - - `upgrade_map_name(in_map_name text)` - - `upgrade_map_value(in_value jsonb)` - - `upsert_spicefield_types(in_max_globally_active integer[], in_max_globally_primed integer[], in_field_types text[], in_map_name text, in_dimension_index integer)` - - `use_sinkchart(in_player_id bigint, in_account_id bigint, in_area_id smallint, in_item_id bigint, in_sinkchart_map_name text, in_player_map_name text, in_player_c...)` - - `verify_item_dup_backup_tool(in_account_id bigint, in_vehicle_id bigint, in_cheat_type dune.cheat_type_enum)` - - `wipe_old_events_log(in_days_limit integer)` - - `zero_transform()` - -28. **Database table counts (active server):** - - `encrypted_accounts`: 10 rows, `encrypted_player_state`: 10 rows - - `actors`: 411 rows, `items`: 1,482, `inventories`: 459 - - `buildings`: 8, `vehicles`: 16, `guilds`: 1 (4 members) - - `bans`: 0, `factions`: 4 (Atreides, Harkonnen, Fremen, Corrino) - - `game_events`: 76, `chat_history`: unknown - - `dashboard.*` tables: `bans`, `chat_history`, `player_actions`, `player_ips` -29. **Dashboard Admin Experimental tab expanded with tools:** - - Search Players (via `admin_get_character_ids`) - - Online Players list (via `get_all_online_or_recently_disconnected_player_online_state()`) - - Adjust Currency (via direct SQL to `player_virtual_currency_balances`) - - View Currency Balances (via `get_player_virtual_currency_balances`) - - Change Faction (via direct SQL to `player_faction`) - - Faction Reputation View/Set (via `get_player_current_faction_reputation` / `set_player_faction_reputation`) - - Inventory Lookup (via `admin_get_inventory_details`) - - Teleport Player (via `admin_move_offline_player_to_partition`) - - Guild Tools: List, View, Disband, Kick Member (via `get_guild_data`, `disband_guild`, `remove_guild_members`) - - Player Tags: View & Update (via `admin_read_player_tags`, `update_player_tags`) - - Flag Cheater (via `flag_player_as_cheater`) - - Player Vehicles (via `get_player_owned_vehicles_data`) - - Player Stats Viewer (health, spice exposure, etc. from `actors.properties` JSONB) - - Character Management: rename, delete character, delete account, set demo state - - Journey & Specialization: complete/reveal/reset story nodes, set/reset specialization tracks - - Guild Roster: list members, promote/demote - - Economy: reset vendor stock for player, view tax invoices - - Spice Fields: force spice spawn, reset spice state - - Server Tools: set players offline, cleanup orphans - - Permissions: view actor permissions, set player rank - - Function Explorer: browse and execute all 517 DB functions dynamically with parameter input - - Battlegroup Info viewer (via BGD API `/v0/battlegroup`) - - (Broadcast via RMQ was already done in finding #22) - - API endpoints in `routes/api.py`: - - `POST /api/admin-experimental/broadcast` - - `POST /api/admin-experimental/query` (read-only SQL) - - `POST /api/admin-experimental/search-players` - - `GET /api/admin-experimental/online-players` - - `POST /api/admin-experimental/adjust-currency` - - `POST /api/admin-experimental/currency-balances` - - `POST /api/admin-experimental/change-faction` - - `POST /api/admin-experimental/faction-reputation` - - `POST /api/admin-experimental/inventory` - - `POST /api/admin-experimental/teleport` - - `GET /api/admin-experimental/partitions` - - `GET /api/admin-experimental/guilds` - - `POST /api/admin-experimental/guild-data` - - `POST /api/admin-experimental/disband-guild` - - `POST /api/admin-experimental/remove-guild-member` - - `POST /api/admin-experimental/player-tags` - - `POST /api/admin-experimental/flag-cheater` - - `POST /api/admin-experimental/player-vehicles` - - `POST /api/admin-experimental/player-stats` - - `POST /api/admin-experimental/set-character-name` - - `POST /api/admin-experimental/delete-character` - - `POST /api/admin-experimental/delete-account` - - `POST /api/admin-experimental/set-demo-state` - - `POST /api/admin-experimental/journey` - - `POST /api/admin-experimental/specialization` - - `POST /api/admin-experimental/guild-members` - - `POST /api/admin-experimental/clean-vendor-stock` - - `POST /api/admin-experimental/tax-invoices` - - `POST /api/admin-experimental/spice` - - `POST /api/admin-experimental/server-tools` - - `POST /api/admin-experimental/permissions` - - `GET /api/admin-experimental/functions` - - `GET /api/admin-experimental/functions/` - - `POST /api/admin-experimental/functions//execute` - - `GET /api/admin-experimental/battlegroup` - - `POST /api/admin-experimental/execute` (admin functions) -30. **Key insight about kubectl exec from dashboard:** The paramiko SSH `exec_command` doesn't support heredocs well. The working pattern for piping content into pods is: - - Write content to a temp file on VM host via `echo base64 | base64 -d | sudo tee /tmp/file` - - Then pipe into pod: `cat /tmp/file | sudo kubectl exec -i -n ns pod -- sh -lc 'cat > /tmp/pod_file && command "$(cat /tmp/pod_file)"'` - - Clean up both temp files after - -31. **`search_path` issue with DB functions:** PostgreSQL's default `search_path` is `"$user", public` — the `dune` schema is NOT on it. Any function defined in the `dune` schema that references tables without the `dune.` prefix (e.g., `accounts`, `player_state`, `actors`, `world_partition`) will fail when called from outside the schema. Our `teleport_player()` fix: run `SET search_path TO dune, public` before calling the function. This affects the teleport function `admin_move_offline_player_to_partition` and likely many of the 517 functions. - -32. **Table name correction:** The table is `dune.world_partition` (singular), NOT `dune.world_partitions` (plural). `accounts` and `player_state` are **views** in the `dune` schema, not physical tables. Other notable tables: - - `dune.actors` (physical) — id, class, map, owner_account_id, properties JSONB - - `dune.world_partition` — partition_id, server_id, map, dimension_index, label, blocked, partition_definition JSONB - - `dune.player_virtual_currency_balances` — player_controller_id, currency_id, balance - - `dune.player_faction` — actor_id, faction_id - - `dune.player_faction_reputation` — actor_id, faction_id, reputation_amount - - `dune.player_tags` — account_id, tag - - `dune.vehicles` — id, actor_id - - `dune.player_state` (view) — account_id, character_name, player_controller_id, player_pawn_id, online_status - - `dune.accounts` (view) — id, user - - `dune.encrypted_accounts` — id, user, platform_id - ---- - -## 13. TROUBLESHOOTING TIPS - -### PowerShell Quoting for SSH Commands -PowerShell interprets `$`, `|`, `>`, `<`, `&&`, `;`, `(`, `)` in SSH command strings. Workarounds: -```powershell -# Use single quotes for outer string -ssh -i user@host 'command with $vars' - -# Or pipe scripts via stdin -Get-Content script.sh -Raw | ssh "cat > /tmp/scr.sh && bash /tmp/scr.sh" -``` - -### TR Auth Testing -```bash -# From inside the VM: -sudo kubectl exec -n -- wget -q -O- \ - --post-data="username=&password=" \ - http://-tr-svc:5059/v0/auth/user -``` -Returns `allow` or `deny`. - -### Common NodePort Connection Issues -- SSH tunnel may drop (restart via dashboard launcher) -- Windows firewall may block connections to VM IP on non-standard ports -- AMQP connections require TLS (certificate from `/etc/rabbitmq/`) - -### Modifying RMQ ConfigMaps -The battlegroup operators continuously reconcile ConfigMaps. To make changes: -```bash -# 1. Scale down all operators -sudo kubectl scale deployment -n funcom-operators --replicas=0 \ - battlegroupoperator-controller-manager \ - databaseoperator-controller-manager \ - serveroperator-controller-manager \ - utilitiesoperator-controller-manager - -# 2. Make your ConfigMap changes (use kubectl replace with YAML file) -# 3. Restart affected pods -sudo kubectl delete pod -n - -# 4. Scale operators back up -sudo kubectl scale deployment -n funcom-operators --replicas=1 \ - battlegroupoperator-controller-manager \ - databaseoperator-controller-manager \ - serveroperator-controller-manager \ - utilitiesoperator-controller-manager -``` From be845f76f134a01a7de4e27fef301aab2fb333fd Mon Sep 17 00:00:00 2001 From: Reditus <33814724+ReditusDraco@users.noreply.github.com> Date: Sat, 23 May 2026 07:08:30 +0100 Subject: [PATCH 03/12] feat: complete React + Flask rebuild of dashboard Backend: - New Flask 3 app with service-layer architecture - Pydantic v2 models and unified API response format - psycopg3 connection pool with stored procedure support - 14 services: DB, SSH, K8s, BGD, RMQ (admin + game), realtime, player, economy, guild, world, progression, character, audit, chat - 30+ API endpoints covering players, guilds, economy, world, admin, server, files, director, chat - SSE real-time events for battlegroup, chat, metrics, connection status - SocketIO remote shell (xterm.js compatible) - Settings CRUD, moderation (ban/kick/unban), audit logging - Security: CSRF, rate limiting, CSP, HSTS, read-only SQL enforcement Frontend: - Vite + React 18 + TypeScript + Tailwind CSS - 14 Dune house themes via CSS custom properties - SWR for server state, Axios API client with interceptors - 14 pages: Overview, Player Explorer + Detail, Guild Manager, Vehicles, Buildings, Map Viewer, Accounts, Server Control, Admin Tools (7 tabs), Chat Monitor, Remote Shell, File Browser, Director, Settings - Player Detail with 6 tabs: overview, inventory, vehicles, buildings, progression, actions - Admin Tools: broadcast, economy, world, character, functions, raw query, audit log - Interactive canvas map viewer with zoom/pan/filter - Toast notifications, connection badges, theme switcher Other: - Updated .gitignore for frontend/backend structure - Updated README with new architecture, development guide, and project structure - Legacy app/ templates/ static/ remain untouched --- .gitignore | 13 +- README.md | 105 +- backend/app/__init__.py | 1 + backend/app/config.py | 286 ++++++ backend/app/factory.py | 303 ++++++ backend/app/models/__init__.py | 232 +++++ backend/app/routes/__init__.py | 1 + backend/app/routes/api.py | 971 ++++++++++++++++++ backend/app/routes/auth.py | 131 +++ backend/app/routes/chat.py | 24 + backend/app/routes/debug.py | 43 + backend/app/routes/director.py | 147 +++ backend/app/routes/files.py | 120 +++ backend/app/routes/health.py | 84 ++ backend/app/routes/server.py | 218 ++++ backend/app/services/__init__.py | 1 + backend/app/services/audit.py | 64 ++ backend/app/services/bg_director.py | 141 +++ backend/app/services/character.py | 50 + backend/app/services/chat.py | 148 +++ backend/app/services/database.py | 210 ++++ backend/app/services/economy.py | 182 ++++ backend/app/services/guild.py | 64 ++ backend/app/services/k8s.py | 142 +++ backend/app/services/player.py | 269 +++++ backend/app/services/progression.py | 32 + backend/app/services/realtime.py | 164 +++ backend/app/services/rmq_admin.py | 146 +++ backend/app/services/rmq_game.py | 126 +++ backend/app/services/ssh.py | 103 ++ backend/app/services/world.py | 35 + backend/app/utils/__init__.py | 1 + backend/app/utils/constants.py | 71 ++ backend/app/websocket/__init__.py | 1 + backend/app/websocket/shell.py | 131 +++ backend/requirements.txt | 17 + backend/run.py | 22 + frontend/dist/assets/index-9_PploUA.js | 94 ++ frontend/dist/assets/index-BwISaj0y.css | 32 + frontend/dist/index.html | 16 + frontend/index.html | 15 + frontend/package.json | 31 + frontend/postcss.config.js | 6 + frontend/src/App.tsx | 39 + frontend/src/api/client.ts | 21 + frontend/src/components/admin/AdminTools.tsx | 419 ++++++++ .../src/components/buildings/Buildings.tsx | 72 ++ frontend/src/components/chat/ChatMonitor.tsx | 88 ++ frontend/src/components/common/Badge.tsx | 20 + frontend/src/components/common/DataTable.tsx | 117 +++ frontend/src/components/common/Modal.tsx | 30 + .../src/components/common/ToastProvider.tsx | 39 + frontend/src/components/files/FileBrowser.tsx | 165 +++ .../src/components/guilds/GuildManager.tsx | 172 ++++ frontend/src/components/layout/AppShell.tsx | 15 + .../src/components/layout/ConnectionBadge.tsx | 21 + frontend/src/components/layout/NavBar.tsx | 52 + .../src/components/layout/ThemeSwitcher.tsx | 68 ++ frontend/src/components/map/MapViewer.tsx | 157 +++ frontend/src/components/overview/Overview.tsx | 128 +++ .../src/components/players/PlayerDetail.tsx | 575 +++++++++++ .../src/components/players/PlayerExplorer.tsx | 122 +++ .../src/components/server/ServerControl.tsx | 241 +++++ frontend/src/components/settings/Settings.tsx | 98 ++ frontend/src/components/shell/Terminal.tsx | 106 ++ frontend/src/components/vehicles/Vehicles.tsx | 93 ++ frontend/src/hooks/useDebounce.ts | 10 + frontend/src/hooks/useRealtime.ts | 52 + frontend/src/main.tsx | 10 + frontend/src/stores/AppContext.tsx | 83 ++ frontend/src/styles/index.css | 39 + frontend/src/styles/themes.css | 281 +++++ frontend/tailwind.config.js | 36 + frontend/tsconfig.json | 25 + frontend/tsconfig.node.json | 10 + frontend/vite.config.ts | 23 + 76 files changed, 8410 insertions(+), 10 deletions(-) create mode 100644 backend/app/__init__.py create mode 100644 backend/app/config.py create mode 100644 backend/app/factory.py create mode 100644 backend/app/models/__init__.py create mode 100644 backend/app/routes/__init__.py create mode 100644 backend/app/routes/api.py create mode 100644 backend/app/routes/auth.py create mode 100644 backend/app/routes/chat.py create mode 100644 backend/app/routes/debug.py create mode 100644 backend/app/routes/director.py create mode 100644 backend/app/routes/files.py create mode 100644 backend/app/routes/health.py create mode 100644 backend/app/routes/server.py create mode 100644 backend/app/services/__init__.py create mode 100644 backend/app/services/audit.py create mode 100644 backend/app/services/bg_director.py create mode 100644 backend/app/services/character.py create mode 100644 backend/app/services/chat.py create mode 100644 backend/app/services/database.py create mode 100644 backend/app/services/economy.py create mode 100644 backend/app/services/guild.py create mode 100644 backend/app/services/k8s.py create mode 100644 backend/app/services/player.py create mode 100644 backend/app/services/progression.py create mode 100644 backend/app/services/realtime.py create mode 100644 backend/app/services/rmq_admin.py create mode 100644 backend/app/services/rmq_game.py create mode 100644 backend/app/services/ssh.py create mode 100644 backend/app/services/world.py create mode 100644 backend/app/utils/__init__.py create mode 100644 backend/app/utils/constants.py create mode 100644 backend/app/websocket/__init__.py create mode 100644 backend/app/websocket/shell.py create mode 100644 backend/requirements.txt create mode 100644 backend/run.py create mode 100644 frontend/dist/assets/index-9_PploUA.js create mode 100644 frontend/dist/assets/index-BwISaj0y.css create mode 100644 frontend/dist/index.html create mode 100644 frontend/index.html create mode 100644 frontend/package.json create mode 100644 frontend/postcss.config.js create mode 100644 frontend/src/App.tsx create mode 100644 frontend/src/api/client.ts create mode 100644 frontend/src/components/admin/AdminTools.tsx create mode 100644 frontend/src/components/buildings/Buildings.tsx create mode 100644 frontend/src/components/chat/ChatMonitor.tsx create mode 100644 frontend/src/components/common/Badge.tsx create mode 100644 frontend/src/components/common/DataTable.tsx create mode 100644 frontend/src/components/common/Modal.tsx create mode 100644 frontend/src/components/common/ToastProvider.tsx create mode 100644 frontend/src/components/files/FileBrowser.tsx create mode 100644 frontend/src/components/guilds/GuildManager.tsx create mode 100644 frontend/src/components/layout/AppShell.tsx create mode 100644 frontend/src/components/layout/ConnectionBadge.tsx create mode 100644 frontend/src/components/layout/NavBar.tsx create mode 100644 frontend/src/components/layout/ThemeSwitcher.tsx create mode 100644 frontend/src/components/map/MapViewer.tsx create mode 100644 frontend/src/components/overview/Overview.tsx create mode 100644 frontend/src/components/players/PlayerDetail.tsx create mode 100644 frontend/src/components/players/PlayerExplorer.tsx create mode 100644 frontend/src/components/server/ServerControl.tsx create mode 100644 frontend/src/components/settings/Settings.tsx create mode 100644 frontend/src/components/shell/Terminal.tsx create mode 100644 frontend/src/components/vehicles/Vehicles.tsx create mode 100644 frontend/src/hooks/useDebounce.ts create mode 100644 frontend/src/hooks/useRealtime.ts create mode 100644 frontend/src/main.tsx create mode 100644 frontend/src/stores/AppContext.tsx create mode 100644 frontend/src/styles/index.css create mode 100644 frontend/src/styles/themes.css create mode 100644 frontend/tailwind.config.js create mode 100644 frontend/tsconfig.json create mode 100644 frontend/tsconfig.node.json create mode 100644 frontend/vite.config.ts diff --git a/.gitignore b/.gitignore index c491ac6..95724ce 100644 --- a/.gitignore +++ b/.gitignore @@ -4,10 +4,15 @@ __pycache__/ *$py.class *.egg-info/ *.egg -dist/ +dist/*.egg build/ *.whl +# Frontend +frontend/node_modules/ +frontend/.pnpm-store/ +frontend/.vite/ + # Virtual environments venv/ env/ @@ -103,3 +108,9 @@ app/logs/ # Local settings with real credentials app/settings.yaml + +# Node artifacts +node_modules/ +package-lock.json +yarn.lock +pnpm-lock.yaml diff --git a/README.md b/README.md index 3d0140d..750010e 100644 --- a/README.md +++ b/README.md @@ -32,12 +32,12 @@ If you're testing this project, grab builds from nightly for the latest features ## Features - **Map Features**: Interactive maps with real-world coordinate calibration for Hagga Basin and The Deep Desert. Default view centers on Hagga Basin at 15% zoom. Zoom range: 15%–100%. -- **Player Management**: View, search, and filter players. Track online status, factions, guilds, and locations. +- **Player Management**: View, search, and filter players. Track online status, factions, guilds, and locations. Rich detail view with vitals, currency, inventory, vehicles, buildings, landclaims, specialization, keystones, and faction reputation. - **Chat Logs**: Parsed from text-router pod logs with channel filtering and auto-refresh. - **Director Controls**: Live battlegroup stats, world state management, and server transfer controls. - **File Browser**: Secure SSH-based file browser for server configuration and logs. - **Shell Access**: Interactive VM and Kubernetes pod shells directly in the browser. -- **Admin Tools**: Ban management, IP detection, kick/unban functionality, and player history. +- **Admin Tools**: Ban management, IP detection, kick/unban functionality, player history, item/currency/vitals editing, and raw SQL query interface. - **Firewall Security**: Block unauthenticated game server ports (File Browser, Director) from external internet access. Applied via iptables on the game server VM across INPUT, FORWARD, and mangle PREROUTING chains to cover both host services and Kubernetes NodePort traffic. Configurable per-port during setup or from the Server page. - **Vehicles & Buildings**: Track owned vehicles, modules, and player structures. - **Auto-Update**: Background checker polls GitHub for new commits. Safe file replacement preserves your settings, logs, and SSH keys. One-click update from the dashboard. @@ -59,6 +59,7 @@ This project is **Source Available** under the [Dune Dashboard Source License (D ## Requirements - Python 3.8+ +- Node.js 18+ (for frontend development/build) - OpenSSH client - `kubectl` access to the Dune: Awakening Kubernetes cluster - SSH access to the game server VM @@ -207,13 +208,36 @@ SSL certificates are automatically regenerated when they approach expiry: ``` DuneDashboard/ -├── app/ # Core application package -│ ├── routes/ # HTTP route handlers -│ ├── services/ # Business logic (DB, SSH, K8s, etc.) -│ ├── utils/ # Helpers and constants -│ └── websocket/ # Socket.IO handlers -├── templates/ # Jinja2 HTML templates -├── static/ # CSS and frontend assets +├── backend/ # New Flask backend (API + services) +│ ├── app/ +│ │ ├── routes/ # HTTP route handlers (API, auth, health, server, files, director, chat) +│ │ ├── services/ # Business logic (DB, SSH, K8s, BGD, RMQ, player, economy, guild, world, etc.) +│ │ ├── models/ # Pydantic v2 models +│ │ ├── websocket/ # Socket.IO shell handler +│ │ ├── config.py # Settings loader +│ │ └── factory.py # App factory (services, blueprints, security) +│ ├── run.py # Entry point +│ └── requirements.txt # Python dependencies +│ +├── frontend/ # New React SPA (Vite + TypeScript + Tailwind) +│ ├── src/ +│ │ ├── components/ # Pages (overview, players, guilds, vehicles, buildings, map, accounts, server, admin, chat, shell, files, director, settings) +│ │ ├── api/ # Axios client +│ │ ├── stores/ # React Context (app state, auth, theme) +│ │ ├── hooks/ # Custom hooks (realtime, debounce) +│ │ └── styles/ # Tailwind + 14 Dune themes +│ ├── index.html +│ ├── package.json +│ ├── vite.config.ts +│ └── tsconfig.json +│ +├── app/ # Legacy Flask/Jinja2 dashboard (untouched, still functional) +│ ├── routes/ +│ ├── services/ +│ ├── utils/ +│ └── websocket/ +├── templates/ # Legacy Jinja2 HTML templates +├── static/ # Legacy CSS and frontend assets ├── scripts/ # Pre-flight utilities (db_check.py) ├── launcher.ps1 # Unified launcher (setup, start, diagnostics, CA tools) ├── start.sh # Linux/macOS entry point @@ -221,12 +245,49 @@ DuneDashboard/ └── settings.yaml.example # Reference configuration ``` +> **Note**: The legacy `app/`, `templates/`, and `static/` directories remain untouched and functional. The new system lives in `backend/` and `frontend/`. Both can coexist during migration. + +## Architecture + +### Frontend +- **React 18** with TypeScript +- **Vite** for fast builds and HMR +- **Tailwind CSS** for styling with 14 Dune house themes +- **SWR** for server state caching and revalidation +- **Axios** for HTTP requests with 401 redirect handling +- **Socket.IO Client** for the remote terminal +- **xterm.js** for the in-browser shell + +### Backend +- **Flask 3** with Blueprint-based routing +- **Pydantic v2** for request/response validation +- **psycopg3** with connection pooling for PostgreSQL +- **Flask-SocketIO** for the interactive shell +- **Flask-Login** for session-based authentication (Argon2 password hashing) +- **Flask-Limiter** for rate limiting +- **SSE (Server-Sent Events)** for real-time updates (battlegroup, chat, metrics) + +### Services +- `DatabaseService` — psycopg3 pool, stored procedure executor, audit table DDL +- `SSHService` — paramiko SSH client for tunneling and remote commands +- `K8sService` — kubectl-over-SSH for pod/deployment management +- `BgDirectorService` — HTTP client for the Battlegroup Director API +- `RmqAdminService` — RabbitMQ Management HTTP API client +- `RmqGameService` — RabbitMQ Game HTTP API client (broadcasts, chat intercept) +- `RealtimeService` — SSE broadcaster with background polling loops +- `PlayerService` / `EconomyService` / `GuildService` / `WorldService` / `ProgressionService` / `CharacterService` — DB-function-only domain services +- `AuditService` — persistent PostgreSQL audit logging +- `ChatService` — chat history + pod log catch-up + ## Security Notes - Never commit `settings.yaml` to version control. - SSH keys are copied to `%TEMP%` with restricted permissions during startup. - All database queries use parameterized statements to prevent SQL injection. - Dashboard authentication is required by default. +- Raw SQL query endpoint (`/api/query`) is **read-only SELECT** — INSERT/UPDATE/DELETE/DROP/CREATE/ALTER/GRANT/TRUNCATE are blocked. +- All mutations are audited to PostgreSQL. +- CSP, HSTS, X-Frame-Options, and other security headers are enforced in production mode. ## Logging @@ -268,3 +329,29 @@ Console output is **not** sanitized so you can see full details during operation - Files exceeding **10 MB** are truncated (keeps last 5000 lines) - Empty category directories are removed - Cleanup runs automatically on every launcher start + +## Development + +### Frontend Development + +```bash +cd frontend +npm install +npm run dev # Vite dev server with API proxy to localhost:5050 +npm run build # Production build to frontend/dist/ +``` + +### Backend Development + +```bash +cd backend +pip install -r requirements.txt +python run.py # Or: flask --app run:app run +``` + +### Themes + +The dashboard supports 14 Dune house themes. Switch via the theme picker in the top-right nav bar: +Classic Dune, House Atreides, House Harkonnen, Fremen, Bene Gesserit, Spacing Guild, Emperor, House Corrino, Mentat, Sardaukar, Bene Tleilax, House Ordos, Ix, CHOAM. + +Themes are implemented via CSS custom properties (`var(--primary)`, `var(--bg)`, etc.) and switched by setting `data-theme` on the `` element. diff --git a/backend/app/__init__.py b/backend/app/__init__.py new file mode 100644 index 0000000..84af166 --- /dev/null +++ b/backend/app/__init__.py @@ -0,0 +1 @@ +# Backend package init. diff --git a/backend/app/config.py b/backend/app/config.py new file mode 100644 index 0000000..de0d564 --- /dev/null +++ b/backend/app/config.py @@ -0,0 +1,286 @@ +"""Settings loader — reads settings.yaml with env var overrides.""" + +import os +import socket +import yaml +import logging +import copy +import secrets + +logger = logging.getLogger(__name__) + +DEFAULTS = { + "server": { + "host": "127.0.0.1", + "user": "dune", + "ssh_key": None, + "local_ip": None, + }, + "dashboard": { + "host": "127.0.0.1", + "port": 5050, + "debug": False, + "secret_key": None, + "ssl_cert": None, + "ssl_key": None, + "ssl_domain": None, + "ssl_email": None, + "http_redirect": False, + "http_redirect_port": 80, + }, + "database": { + "host": "127.0.0.1", + "port": 15433, + "user": "postgres", + "password": None, + "name": "dune", + "schema": "dune", + "min_connections": 2, + "max_connections": 10, + "owner": "dune", + "dashboard_schema": "dashboard", + }, + "kubernetes": { + "namespace": "", + "battlegroup_script": "/home/dune/.dune/bin/battlegroup", + }, + "director": { + "port": 32479, + "host": "127.0.0.1", + }, + "rmq": { + "admin_host": "127.0.0.1", + "admin_port": 32686, + "game_host": "127.0.0.1", + "game_port": 32021, + "username": "admin", + "password": "@5bkR636nz3TxML@", + "vhost": "%2f", + }, + "filebrowser": { + "port": 18888, + }, + "firewall": { + "block_filebrowser": True, + "block_director": True, + }, + "cache": { + "chat_pod_ttl": 60, + "chat_messages_ttl": 10, + "static_data_ttl": 300, + "bgd_ttl": 10, + "rmq_ttl": 15, + }, + "auth": { + "enabled": True, + "username": None, + "password_hash": None, + "shell_enabled": True, + }, + "logging": { + "level": "INFO", + "file": "logs/dashboard.log", + "debug_file": "logs/debug.log", + "debug_enabled": False, + "max_bytes": 10485760, + "backup_count": 5, + }, + "ssl": { + "check_interval_hours": 24, + "renewal_days_before_expiry": 30, + }, + "maps": { + "default_map": "HaggaBasin", + "DeepDesert": { + "image": "maps/Deep_Desert.webp", + "label": "The Deep Desert", + "bounds": { + "min_x": -1268624.82, + "max_x": 1163312.83, + "min_y": -1266548.17, + "max_y": 1162416.13, + }, + "flip_y": False, + "image_size": {"width": 8000, "height": 8000}, + "default_zoom": 0.15, + }, + "HaggaBasin": { + "image": "maps/HaggaBasin_8k.webp", + "label": "Hagga Basin", + "bounds": { + "min_x": -456752.21, + "max_x": 354547.46, + "min_y": -450630.14, + "max_y": 353821.95, + }, + "flip_y": False, + "image_size": {"width": 8000, "height": 8000}, + "default_zoom": 0.15, + }, + }, +} + + +def deep_merge(base, override): + """Deep merge override dict into base dict.""" + result = base.copy() + for key, value in override.items(): + if key in result and isinstance(result[key], dict) and isinstance(value, dict): + result[key] = deep_merge(result[key], value) + else: + result[key] = value + return result + + +def _detect_local_ip(): + """Detect local IP address for VM connectivity.""" + try: + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + s.settimeout(1) + s.connect(("8.8.8.8", 80)) + local_ip = s.getsockname()[0] + s.close() + if local_ip: + logger.debug(f"Detected local IP: {local_ip}") + return local_ip + except Exception as e: + logger.debug(f"Could not detect local IP: {e}") + return "127.0.0.1" + + +def _validate_server_host(settings): + """Validate and fix server.host if invalid or placeholder.""" + server = settings.setdefault("server", {}) + host = server.get("host", "") + + local_ip = server.get("local_ip") + if local_ip: + local_ip_str = str(local_ip).strip() + if local_ip_str and local_ip_str not in ("", "null", "None", "YOUR_SERVER_IP", "YOUR_VM_IP"): + if local_ip_str.count(".") == 3 and all(part.isdigit() and 0 <= int(part) <= 255 for part in local_ip_str.split(".")): + server["host"] = local_ip_str + logger.info(f"Using server.local_ip override: {server['host']}") + return settings + + host_str = str(host).strip() if host else "" + invalid_hosts = ("", "YOUR_SERVER_IP", "YOUR_VM_IP", "null", "None") + + if host_str in invalid_hosts or not host_str: + detected_ip = _detect_local_ip() + server["host"] = detected_ip + logger.warning(f"Invalid server.host detected, using auto-detected IP: {detected_ip}") + logger.warning("To fix: Edit settings.yaml and set server.host to your VM's IP address") + + return settings + + +def _find_missing_keys(defaults, current, path=""): + """Find keys present in defaults but missing in current.""" + missing = [] + for key, val in defaults.items(): + new_path = f"{path}.{key}" if path else key + if key not in current: + missing.append(new_path) + elif isinstance(val, dict) and isinstance(current.get(key), dict): + missing.extend(_find_missing_keys(val, current[key], new_path)) + return missing + + +def load_settings(settings_path=None): + """Load settings from YAML file with defaults and env var overrides.""" + if settings_path is None: + settings_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "settings.yaml") + + settings = copy.deepcopy(DEFAULTS) + + if os.path.exists(settings_path): + try: + with open(settings_path, "r") as f: + file_settings = yaml.safe_load(f) or {} + settings = deep_merge(settings, file_settings) + logger.info(f"Settings loaded from {settings_path}") + except Exception as e: + logger.error(f"Failed to load settings from {settings_path}: {e}") + logger.warning("Using default settings") + else: + logger.warning(f"Settings file not found at {settings_path}, using defaults") + + env_overrides = {} + + if os.environ.get("DUNE_SERVER_HOST"): + env_overrides.setdefault("server", {})["host"] = os.environ["DUNE_SERVER_HOST"] + if os.environ.get("DUNE_SERVER_USER"): + env_overrides.setdefault("server", {})["user"] = os.environ["DUNE_SERVER_USER"] + if os.environ.get("DUNE_DB_PASSWORD"): + env_overrides.setdefault("database", {})["password"] = os.environ["DUNE_DB_PASSWORD"] + if os.environ.get("DUNE_K8S_NAMESPACE"): + env_overrides.setdefault("kubernetes", {})["namespace"] = os.environ["DUNE_K8S_NAMESPACE"] + if os.environ.get("DUNE_AUTH_PASSWORD"): + env_overrides.setdefault("auth", {})["password"] = os.environ["DUNE_AUTH_PASSWORD"] + if os.environ.get("DUNE_DASHBOARD_PORT"): + env_overrides.setdefault("dashboard", {})["port"] = int(os.environ["DUNE_DASHBOARD_PORT"]) + if os.environ.get("DUNE_RMQ_PASSWORD"): + env_overrides.setdefault("rmq", {})["password"] = os.environ["DUNE_RMQ_PASSWORD"] + + if env_overrides: + settings = deep_merge(settings, env_overrides) + logger.info("Environment variable overrides applied") + + if not settings["dashboard"].get("secret_key"): + settings["dashboard"]["secret_key"] = secrets.token_hex(32) + logger.info("Generated secure SECRET_KEY") + + auth = settings.get("auth", {}) + password_migrated = False + if auth.get("password") and not auth.get("password_hash"): + try: + from argon2 import PasswordHasher + ph = PasswordHasher(time_cost=3, memory_cost=65536) + settings["auth"]["password_hash"] = ph.hash(str(auth["password"])) + del settings["auth"]["password"] + password_migrated = True + logger.info("Migrated plaintext password to Argon2 hash") + except ImportError: + logger.error("argon2-cffi not installed. Password hashing unavailable.") + settings["auth"]["password_hash"] = None + + if password_migrated: + settings["dashboard"]["secret_key"] = secrets.token_hex(32) + logger.warning("Rotated secret_key to invalidate sessions after password migration") + + settings = _validate_server_host(settings) + + return settings + + +_settings_cache = None + + +def get_settings(): + """Get current settings (cached for performance).""" + global _settings_cache + if _settings_cache is None: + _settings_cache = load_settings() + return _settings_cache + + +def save_settings(settings): + """Save settings to YAML file.""" + global _settings_cache + settings_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "settings.yaml") + try: + with open(settings_path, "w") as f: + yaml.safe_dump(settings, f, default_flow_style=False, sort_keys=False) + _settings_cache = settings + logger.info(f"Settings saved to {settings_path}") + return True + except Exception as e: + logger.error(f"Failed to save settings to {settings_path}: {e}") + return False + + +def reload_settings(): + """Force reload settings from file.""" + global _settings_cache + _settings_cache = load_settings() + return _settings_cache diff --git a/backend/app/factory.py b/backend/app/factory.py new file mode 100644 index 0000000..a0e5ba1 --- /dev/null +++ b/backend/app/factory.py @@ -0,0 +1,303 @@ +# Application factory — creates and configures the Flask app. + +import os +import sys +import logging +import logging.handlers +from datetime import datetime + +from flask import Flask, jsonify, request, g, send_from_directory +from flask_cors import CORS +from flask_login import current_user +from flask_socketio import SocketIO +from flask_limiter import Limiter +from flask_limiter.util import get_remote_address + +from app.config import load_settings +from app.routes.auth import auth_bp, init_auth +from app.routes.health import health_bp +from app.routes.api import api_bp +from app.routes.director import director_bp +from app.routes.server import server_bp +from app.routes.files import files_bp +from app.routes.debug import debug_bp +from app.routes.chat import chat_bp +from app.websocket.shell import register_websocket_handlers + +from app.services.database import DatabaseService +from app.services.ssh import SSHService +from app.services.k8s import K8sService +from app.services.bg_director import BgDirectorService +from app.services.rmq_admin import RmqAdminService +from app.services.rmq_game import RmqGameService +from app.services.realtime import RealtimeService +from app.services.player import PlayerService +from app.services.economy import EconomyService +from app.services.guild import GuildService +from app.services.world import WorldService +from app.services.progression import ProgressionService +from app.services.character import CharacterService +from app.services.audit import AuditService +from app.services.chat import ChatService + +_services = None + + +def get_services(): + global _services + return _services + + +def create_app(settings_path=None): + global _services + + settings = load_settings(settings_path) + base_dir = os.path.dirname(os.path.dirname(__file__)) + + app = Flask( + __name__, + template_folder=os.path.join(base_dir, "frontend", "dist"), + static_folder=os.path.join(base_dir, "frontend", "dist", "assets"), + static_url_path="/assets", + ) + app.config["SECRET_KEY"] = settings["dashboard"]["secret_key"] + app.config["SESSION_COOKIE_HTTPONLY"] = True + app.config["SESSION_COOKIE_SAMESITE"] = "Lax" + app.config["WTF_CSRF_ENABLED"] = True + app.config["WTF_CSRF_TIME_LIMIT"] = None + + CORS(app, resources={r"/api/*": {"origins": "*"}}) + + ssl_enabled = bool( + settings["dashboard"].get("ssl_cert") + and settings["dashboard"].get("ssl_key") + and settings["dashboard"]["ssl_cert"] != "null" + and settings["dashboard"]["ssl_key"] != "null" + ) + app.config["SESSION_COOKIE_SECURE"] = ssl_enabled + + if not settings["dashboard"]["debug"]: + @app.after_request + def add_security_headers(response): + if ssl_enabled: + response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains" + response.headers["X-Frame-Options"] = "SAMEORIGIN" + response.headers["X-Content-Type-Options"] = "nosniff" + response.headers["X-XSS-Protection"] = "1; mode=block" + response.headers["Content-Security-Policy"] = ( + "default-src 'self'; " + "script-src 'self' 'unsafe-inline'; " + "style-src 'self' 'unsafe-inline'; " + "img-src 'self' data:; " + "connect-src 'self' ws: wss:; " + "frame-ancestors 'self'; " + "base-uri 'self'; " + "form-action 'self'" + ) + response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin" + return response + + # Error handlers + @app.errorhandler(Exception) + def handle_exception(e): + logging.exception("Unhandled exception: %s", e) + from app.models import ApiResponse, ErrorDetail + if settings["dashboard"].get("debug", False): + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="InternalError", message=str(e)), + ).model_dump()), 500 + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="InternalError", message="An internal error occurred"), + ).model_dump()), 500 + + @app.errorhandler(404) + def handle_not_found(e): + from app.models import ApiResponse, ErrorDetail + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="NotFound", message="Resource not found"), + ).model_dump()), 404 + + @app.errorhandler(405) + def handle_method_not_allowed(e): + from app.models import ApiResponse, ErrorDetail + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="MethodNotAllowed", message="Method not allowed"), + ).model_dump()), 405 + + # Request logging + @app.before_request + def before_request_logging(): + import time as _time + g._request_start_time = _time.time() + + @app.after_request + def after_request_logging(response): + import time as _time + duration = _time.time() - g.get("_request_start_time", _time.time()) + user = current_user.id if current_user.is_authenticated else "anonymous" + if request.path.startswith("/api") or request.path.startswith("/server"): + logging.info("%s %s %d %.3fs user=%s", request.method, request.path, response.status_code, duration, user) + response.headers["X-Response-Time"] = f"{duration:.3f}s" + return response + + _setup_logging(settings) + + # ── Services ───────────────────────────────────────────────── + + db_config = { + "host": settings["database"]["host"], + "port": settings["database"]["port"], + "user": settings["database"]["user"], + "password": settings["database"]["password"], + "database": settings["database"]["name"], + } + + db_service = DatabaseService( + db_config, + min_conn=settings["database"]["min_connections"], + max_conn=settings["database"]["max_connections"], + dashboard_schema=settings["database"].get("dashboard_schema", "dashboard"), + ) + db_service.ensure_tables() + + ssh_service = SSHService( + host=settings["server"]["host"], + user=settings["server"]["user"], + ssh_key=settings["server"].get("ssh_key"), + ) + + k8s_service = K8sService( + ssh_service=ssh_service, + namespace=settings["kubernetes"]["namespace"], + ) + + bg_director = BgDirectorService( + host=settings["director"].get("host", "127.0.0.1"), + node_port=settings["director"].get("port", 32479), + ) + + rmq_admin = RmqAdminService( + host=settings["rmq"]["admin_host"], + port=settings["rmq"]["admin_port"], + username=settings["rmq"]["username"], + password=settings["rmq"]["password"], + ) + + rmq_game = RmqGameService( + host=settings["rmq"]["game_host"], + port=settings["rmq"]["game_port"], + username=settings["rmq"]["username"], + password=settings["rmq"]["password"], + ) + + player_svc = PlayerService(db_service) + economy_svc = EconomyService(db_service) + guild_svc = GuildService(db_service) + world_svc = WorldService(db_service) + progression_svc = ProgressionService(db_service) + character_svc = CharacterService(db_service) + audit_svc = AuditService(db_service) + chat_svc = ChatService(db_service, k8s_service, ssh_service) + + realtime_svc = RealtimeService(bg_director, rmq_admin, chat_svc) + realtime_svc.start() + + _services = { + "db": db_service, + "ssh": ssh_service, + "k8s": k8s_service, + "bg_director": bg_director, + "rmq_admin": rmq_admin, + "rmq_game": rmq_game, + "realtime": realtime_svc, + "player": player_svc, + "economy": economy_svc, + "guild": guild_svc, + "world": world_svc, + "progression": progression_svc, + "character": character_svc, + "audit": audit_svc, + "chat": chat_svc, + } + + app.dune_settings = settings + app.dune_services = _services + + # ── Blueprints ─────────────────────────────────────────────── + + init_auth(app, settings) + + app.register_blueprint(auth_bp, url_prefix="/api/auth") + app.register_blueprint(health_bp, url_prefix="/api") + app.register_blueprint(api_bp, url_prefix="/api") + app.register_blueprint(director_bp, url_prefix="/api/director") + app.register_blueprint(server_bp, url_prefix="/api/server") + app.register_blueprint(files_bp, url_prefix="/api/files") + app.register_blueprint(chat_bp, url_prefix="/api/chat") + app.register_blueprint(debug_bp, url_prefix="/api/debug") + + # ── SocketIO ───────────────────────────────────────────────── + socketio = SocketIO(app, cors_allowed_origins="*", async_mode="threading") + register_websocket_handlers(socketio, settings) + app.socketio = socketio + + # ── Rate Limiter ───────────────────────────────────────────── + limiter = Limiter( + app=app, + key_func=get_remote_address, + default_limits=[], + storage_uri="memory://", + ) + app.limiter = limiter + + # ── Catch-all for React SPA ───────────────────────────────── + @app.route("/", defaults={"path": ""}) + @app.route("/") + def serve_react(path): + if path.startswith("api/") or path.startswith("server/") or path.startswith("static/") or path.startswith("assets/"): + from app.models import ApiResponse, ErrorDetail + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="NotFound", message="Resource not found"), + ).model_dump()), 404 + return send_from_directory(os.path.join(base_dir, "frontend", "dist"), "index.html") + + # ── Auto-detect namespace if empty ─────────────────────────── + if settings["kubernetes"]["namespace"] == "": + try: + k8s_service.auto_detect_namespace() + if k8s_service.namespace: + settings["kubernetes"]["namespace"] = k8s_service.namespace + except Exception as e: + logging.warning("Could not auto-detect K8s namespace: %s", e) + + return app + + +def _setup_logging(settings): + log_level = getattr(logging, settings["logging"]["level"].upper(), logging.INFO) + log_file = settings["logging"]["file"] + os.makedirs(os.path.dirname(log_file), exist_ok=True) + + handler = logging.handlers.RotatingFileHandler( + log_file, + maxBytes=settings["logging"]["max_bytes"], + backupCount=settings["logging"]["backup_count"], + ) + handler.setFormatter(logging.Formatter( + "%(asctime)s - %(name)s - %(levelname)s - %(message)s" + )) + handler.setLevel(log_level) + + console = logging.StreamHandler(sys.stdout) + console.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")) + console.setLevel(log_level) + + root = logging.getLogger() + root.setLevel(log_level) + root.addHandler(handler) + root.addHandler(console) diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py new file mode 100644 index 0000000..b73c491 --- /dev/null +++ b/backend/app/models/__init__.py @@ -0,0 +1,232 @@ +# Pydantic models for the Dune Admin Dashboard API. + +from pydantic import BaseModel, Field +from typing import Any, List, Optional + + +class ErrorDetail(BaseModel): + code: str + message: str + details: Optional[Any] = None + + +class ApiResponse(BaseModel): + success: bool + data: Optional[Any] = None + error: Optional[ErrorDetail] = None + + +# ── Player Models ─────────────────────────────────────────────── + +class Vitals(BaseModel): + current_health: Optional[float] = None + max_health: Optional[float] = None + current_hydration: Optional[float] = None + dehydration_penalty: Optional[float] = None + current_spice: Optional[float] = None + spice_addiction_level: Optional[float] = None + spice_tolerance: Optional[float] = None + + +class CurrencyBalance(BaseModel): + currency_id: int + currency_label: str + balance: float = 0.0 + + +class Item(BaseModel): + id: Optional[int] = None + template_id: str = "" + stack_size: int = 1 + quality_level: int = 0 + is_new: bool = False + position_index: int = 0 + stats: Optional[Any] = None + durability: Optional[float] = None + max_durability: Optional[float] = None + ammo: Optional[int] = None + + +class Inventory(BaseModel): + inventory_id: int + actor_id: Optional[int] = None + inventory_type: int = 0 + inventory_type_label: str = "" + max_item_count: Optional[int] = None + max_item_volume: Optional[float] = None + items: List[Item] = [] + + +class VehicleSummary(BaseModel): + id: Optional[int] = None + class_name: str = "" + display_name: str = "" + map: Optional[str] = None + + +class BuildingSummary(BaseModel): + id: Optional[int] = None + class_name: str = "" + map: Optional[str] = None + owner_name: str = "" + instance_count: int = 0 + is_powered: bool = False + power_level: Optional[Any] = None + + +class Landclaim(BaseModel): + id: Optional[int] = None + class_name: str = "" + map: Optional[str] = None + + +class SpecializationTrack(BaseModel): + track_type: str = "" + xp_amount: int = 0 + level: int = 0 + + +class Keystone(BaseModel): + id: int + name: str = "" + + +class FactionReputation(BaseModel): + faction_id: Optional[int] = None + faction_name: str = "" + reputation_amount: int = 0 + + +class LandsraadInfo(BaseModel): + daily_reward_charges: Optional[int] = None + last_viewed_term_id: Optional[int] = None + daily_reward_last_processed: Optional[Any] = None + + +class PlayerSummary(BaseModel): + player_controller_id: Optional[int] = None + character_name: str = "Unknown" + account_email: Optional[str] = None + funcom_id: Optional[str] = None + faction_name: Optional[str] = None + faction_id: Optional[int] = None + map: Optional[str] = None + online_status: str = "Unknown" + life_state: Optional[str] = None + last_login_time: Optional[str] = None + last_avatar_activity: Optional[str] = None + + +class PlayerDetail(BaseModel): + id: Optional[int] = None + account_id: int + player_controller_id: Optional[int] = None + player_pawn_id: Optional[int] = None + character_name: str = "Unknown" + account_email: Optional[str] = None + funcom_id: Optional[str] = None + faction_name: Optional[str] = None + faction_id: Optional[int] = None + map: Optional[str] = None + online_status: str = "Unknown" + life_state: Optional[str] = None + last_login_time: Optional[str] = None + last_avatar_activity: Optional[str] = None + vitals: Optional[Vitals] = None + currency: List[CurrencyBalance] = [] + inventories: List[Inventory] = [] + vehicles: List[VehicleSummary] = [] + buildings: List[BuildingSummary] = [] + landclaims: List[Landclaim] = [] + specialization: List[SpecializationTrack] = [] + keystones: List[Keystone] = [] + faction_reputation: List[FactionReputation] = [] + landsraad: Optional[LandsraadInfo] = None + tags: List[str] = [] + is_online: bool = False + + +# ── Guild Models ──────────────────────────────────────────────── + +class GuildMember(BaseModel): + player_id: int + role_id: int = 50 + role_name: str = "Member" + player_name: str = "Unknown" + online_status: str = "Unknown" + + +class GuildSummary(BaseModel): + guild_id: int + guild_name: str = "" + guild_description: Optional[str] = None + faction_name: Optional[str] = None + member_count: int = 0 + online_count: int = 0 + + +class GuildDetail(BaseModel): + guild_id: int + guild_name: str = "" + guild_description: Optional[str] = None + faction_name: Optional[str] = None + faction_id: Optional[int] = None + members: List[GuildMember] = [] + + +# ── World Models ─────────────────────────────────────────────── + +class PartitionInfo(BaseModel): + partition_id: int + name: str = "" + map: Optional[str] = None + player_count: int = 0 + status: str = "unknown" + + +# ── RMQ Models ──────────────────────────────────────────────── + +class RmqQueueInfo(BaseModel): + name: str + messages: int = 0 + consumers: int = 0 + state: str = "" + + +class RmqOverview(BaseModel): + queues: List[RmqQueueInfo] = [] + total_messages: int = 0 + total_consumers: int = 0 + + +# ── BGD Models ──────────────────────────────────────────────── + +class BattlegroupState(BaseModel): + battlegroup_id: Optional[int] = None + name: Optional[str] = None + status: Optional[str] = None + player_count: Optional[int] = None + servers: Optional[List[Any]] = None + + +# ── Request Models ───────────────────────────────────────────── + +class BroadcastRequest(BaseModel): + message: str = Field(..., min_length=1, max_length=500) + server: Optional[str] = None + partition: Optional[str] = None + + +class TeleportRequest(BaseModel): + player_id: int + destination: str = Field(..., min_length=1) + + +class FunctionExecuteRequest(BaseModel): + schema_name: Optional[str] = Field(default=None, alias="schema") + function: str = Field(..., min_length=1) + args: dict = {} + + +class RawQueryRequest(BaseModel): + query: str = Field(..., min_length=1) diff --git a/backend/app/routes/__init__.py b/backend/app/routes/__init__.py new file mode 100644 index 0000000..2c0c88b --- /dev/null +++ b/backend/app/routes/__init__.py @@ -0,0 +1 @@ +# Routes package init. diff --git a/backend/app/routes/api.py b/backend/app/routes/api.py new file mode 100644 index 0000000..9cbb722 --- /dev/null +++ b/backend/app/routes/api.py @@ -0,0 +1,971 @@ +# Main API routes — players, guilds, economy, world, progression, character, admin. + +import logging + +from flask import Blueprint, request, jsonify +from flask_login import login_required, current_user +from pydantic import ValidationError + +from app.models import ( + ApiResponse, ErrorDetail, PlayerDetail, BroadcastRequest, + TeleportRequest, FunctionExecuteRequest, RawQueryRequest, +) + +api_bp = Blueprint("api", __name__) +logger = logging.getLogger(__name__) + + +def _audit(action: str, details: dict | None = None, target_player_id: int | None = None, severity: str = "info"): + from app.factory import get_services + services = get_services() + audit = services.get("audit") + if audit: + audit.log( + action=action, + user=current_user.id if current_user.is_authenticated else "anonymous", + details=details, + target_player_id=target_player_id, + severity=severity, + source_ip=request.remote_addr, + ) + + +@api_bp.errorhandler(ValidationError) +def handle_validation_error(e): + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="ValidationError", message=str(e)), + ).model_dump()), 400 + + +# ── Player Endpoints ────────────────────────────────────────────── + +@api_bp.route("/players", methods=["GET"]) +@login_required +def list_players(): + term = request.args.get("q", "") + limit = int(request.args.get("limit", 50)) + from app.factory import get_services + svc = get_services()["player"] + results = svc.search(term, limit=limit) + return jsonify(ApiResponse(success=True, data=[r.model_dump() for r in results]).model_dump()) + + +@api_bp.route("/players/search", methods=["POST"]) +@login_required +def search_players(): + data = request.get_json() or {} + term = data.get("term", "") + from app.factory import get_services + svc = get_services()["player"] + results = svc.search(term) + return jsonify(ApiResponse(success=True, data=[r.model_dump() for r in results]).model_dump()) + + +@api_bp.route("/players/", methods=["GET"]) +@login_required +def get_player(account_id): + from app.factory import get_services + svc = get_services()["player"] + detail = svc.get_detail(account_id) + if not detail: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="NotFound", message="Player not found"), + ).model_dump()), 404 + return jsonify(ApiResponse(success=True, data=detail.model_dump()).model_dump()) + + +@api_bp.route("/players//inventory", methods=["GET"]) +@login_required +def get_player_inventory(account_id): + from app.factory import get_services + svc = get_services()["economy"] + inventories = svc.get_inventory(account_id) + return jsonify(ApiResponse(success=True, data=[inv.model_dump() for inv in inventories]).model_dump()) + + +@api_bp.route("/players//currency", methods=["GET"]) +@login_required +def get_player_currency(account_id): + from app.factory import get_services + player_svc = get_services()["player"] + detail = player_svc.get_detail(account_id) + if not detail or not detail.player_controller_id: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="NotFound", message="Player controller not found"), + ).model_dump()), 404 + econ = get_services()["economy"] + currency = econ.get_currency(detail.player_controller_id) + return jsonify(ApiResponse(success=True, data=[c.model_dump() for c in currency]).model_dump()) + + +@api_bp.route("/players//vitals", methods=["GET"]) +@login_required +def get_player_vitals(account_id): + from app.factory import get_services + player_svc = get_services()["player"] + detail = player_svc.get_detail(account_id) + if not detail or not detail.player_pawn_id: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="NotFound", message="Player pawn not found"), + ).model_dump()), 404 + econ = get_services()["economy"] + vitals = econ.get_vitals(detail.player_pawn_id) + return jsonify(ApiResponse(success=True, data=vitals.model_dump()).model_dump()) + + +# ── Economy Mutations ──────────────────────────────────────────── + +@api_bp.route("/items/add", methods=["POST"]) +@login_required +def add_item(): + data = request.get_json() or {} + inventory_id = data.get("inventory_id") + template_id = data.get("template_id") + stack_size = data.get("stack_size", 1) + quality_level = data.get("quality_level", 0) + if not inventory_id or not template_id: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="ValidationError", message="Missing inventory_id or template_id"), + ).model_dump()), 400 + from app.factory import get_services + svc = get_services()["economy"] + item_id = svc.add_item(inventory_id, template_id, stack_size, quality_level) + _audit("item_add", {"inventory_id": inventory_id, "template_id": template_id, "item_id": item_id}) + return jsonify(ApiResponse(success=True, data={"item_id": item_id}).model_dump()) + + +@api_bp.route("/items/", methods=["DELETE"]) +@login_required +def delete_item(item_id): + from app.factory import get_services + svc = get_services()["economy"] + svc.delete_item(item_id) + _audit("item_delete", {"item_id": item_id}) + return jsonify(ApiResponse(success=True).model_dump()) + + +@api_bp.route("/items/", methods=["PATCH"]) +@login_required +def edit_item(item_id): + data = request.get_json() or {} + field = data.get("field") + value = data.get("value") + if not field or value is None: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="ValidationError", message="Missing field or value"), + ).model_dump()), 400 + from app.factory import get_services + svc = get_services()["economy"] + svc.edit_item_field(item_id, field, value) + _audit("item_edit", {"item_id": item_id, "field": field, "value": value}) + return jsonify(ApiResponse(success=True).model_dump()) + + +@api_bp.route("/currency/adjust", methods=["POST"]) +@login_required +def adjust_currency(): + data = request.get_json() or {} + controller_id = data.get("controller_id") + currency_id = data.get("currency_id") + delta = data.get("delta") + if controller_id is None or currency_id is None or delta is None: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="ValidationError", message="Missing required parameters"), + ).model_dump()), 400 + from app.factory import get_services + svc = get_services()["economy"] + new_balance = svc.adjust_currency(controller_id, currency_id, delta) + _audit("currency_adjust", {"controller_id": controller_id, "currency_id": currency_id, "delta": delta, "new_balance": new_balance}, target_player_id=controller_id) + return jsonify(ApiResponse(success=True, data={"new_balance": new_balance}).model_dump()) + + +@api_bp.route("/currency/set", methods=["POST"]) +@login_required +def set_currency(): + data = request.get_json() or {} + controller_id = data.get("controller_id") + currency_id = data.get("currency_id") + balance = data.get("balance") + if controller_id is None or currency_id is None or balance is None: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="ValidationError", message="Missing required parameters"), + ).model_dump()), 400 + from app.factory import get_services + svc = get_services()["economy"] + svc.set_currency(controller_id, currency_id, balance) + _audit("currency_set", {"controller_id": controller_id, "currency_id": currency_id, "balance": balance}, target_player_id=controller_id) + return jsonify(ApiResponse(success=True).model_dump()) + + +@api_bp.route("/vitals/set", methods=["POST"]) +@login_required +def set_vitals(): + data = request.get_json() or {} + pawn_id = data.get("pawn_id") + health = data.get("health") + max_health = data.get("max_health") + hydration = data.get("hydration") + spice = data.get("spice") + if pawn_id is None or hydration is None or spice is None: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="ValidationError", message="Missing required parameters"), + ).model_dump()), 400 + from app.factory import get_services + svc = get_services()["economy"] + svc.set_vitals(pawn_id, health, max_health, hydration, spice) + _audit("vitals_edit", {"pawn_id": pawn_id, "health": health, "max_health": max_health, "hydration": hydration, "spice": spice}) + return jsonify(ApiResponse(success=True).model_dump()) + + +# ── Guild Endpoints ────────────────────────────────────────────── + +@api_bp.route("/guilds", methods=["GET"]) +@login_required +def list_guilds(): + term = request.args.get("q", "") + limit = int(request.args.get("limit", 50)) + from app.factory import get_services + svc = get_services()["guild"] + guilds = svc.list_all() + if term: + guilds = [g for g in guilds if term.lower() in g.guild_name.lower()] + return jsonify(ApiResponse(success=True, data=[g.model_dump() for g in guilds[:limit]]).model_dump()) + + +@api_bp.route("/guilds/", methods=["GET"]) +@login_required +def get_guild(guild_id): + from app.factory import get_services + svc = get_services()["guild"] + guild = svc.get_detail(guild_id) + if not guild: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="NotFound", message="Guild not found"), + ).model_dump()), 404 + return jsonify(ApiResponse(success=True, data=guild.model_dump()).model_dump()) + + +@api_bp.route("/guilds/", methods=["DELETE"]) +@login_required +def disband_guild(guild_id): + from app.factory import get_services + svc = get_services()["guild"] + svc.disband(guild_id) + _audit("guild_disband", {"guild_id": guild_id}) + return jsonify(ApiResponse(success=True).model_dump()) + + +@api_bp.route("/guilds//members/", methods=["DELETE"]) +@login_required +def remove_guild_member(guild_id, player_id): + from app.factory import get_services + svc = get_services()["guild"] + svc.remove_member(guild_id, player_id) + _audit("guild_kick", {"guild_id": guild_id, "player_id": player_id}) + return jsonify(ApiResponse(success=True).model_dump()) + + +@api_bp.route("/guilds//members//role", methods=["PUT"]) +@login_required +def set_guild_role(guild_id, player_id): + data = request.get_json() or {} + role_id = data.get("role_id") + action = data.get("action", "promote") + if role_id is None: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="ValidationError", message="Missing role_id"), + ).model_dump()), 400 + from app.factory import get_services + svc = get_services()["guild"] + if action == "promote": + svc.promote(guild_id, player_id, role_id) + else: + svc.demote(guild_id, player_id, role_id) + _audit(f"guild_{action}", {"guild_id": guild_id, "player_id": player_id, "role_id": role_id}) + return jsonify(ApiResponse(success=True).model_dump()) + + +# ── World Endpoints ────────────────────────────────────────────── + +@api_bp.route("/partitions", methods=["GET"]) +@login_required +def list_partitions(): + map_name = request.args.get("map", "") + from app.factory import get_services + svc = get_services()["world"] + partitions = svc.get_partitions(map_name) + return jsonify(ApiResponse(success=True, data=[p.model_dump() for p in partitions]).model_dump()) + + +@api_bp.route("/teleport", methods=["POST"]) +@login_required +def teleport(): + data = request.get_json() or {} + try: + req = TeleportRequest(**data) + except ValidationError as e: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="ValidationError", message=str(e)), + ).model_dump()), 400 + from app.factory import get_services + svc = get_services()["world"] + svc.teleport(req.fls_id, req.partition_id, req.x, req.y, req.z) + _audit("player_teleport", {"fls_id": req.fls_id, "partition_id": req.partition_id, "coords": [req.x, req.y, req.z]}) + return jsonify(ApiResponse(success=True).model_dump()) + + +@api_bp.route("/spice/reset", methods=["POST"]) +@login_required +def reset_spice(): + data = request.get_json() or {} + map_name = data.get("map_name") + dimension_index = data.get("dimension_index", 0) + if not map_name: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="ValidationError", message="Missing map_name"), + ).model_dump()), 400 + from app.factory import get_services + svc = get_services()["world"] + svc.reset_spice(map_name, dimension_index) + _audit("spice_reset", {"map": map_name, "dimension": dimension_index}) + return jsonify(ApiResponse(success=True).model_dump()) + + +@api_bp.route("/spice/spawn", methods=["POST"]) +@login_required +def force_spice_spawn(): + data = request.get_json() or {} + server_id = data.get("server_id") + spicefield_type_id = data.get("spicefield_type_id") + if not server_id or spicefield_type_id is None: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="ValidationError", message="Missing required parameters"), + ).model_dump()), 400 + from app.factory import get_services + svc = get_services()["world"] + svc.force_spice_spawn(server_id, spicefield_type_id) + _audit("spice_spawn", {"server_id": server_id, "spicefield_type_id": spicefield_type_id}) + return jsonify(ApiResponse(success=True).model_dump()) + + +# ── Progression Endpoints ──────────────────────────────────────── + +@api_bp.route("/progression/journey", methods=["POST"]) +@login_required +def journey_action(): + data = request.get_json() or {} + player_id = data.get("player_id") + node_ids = data.get("node_ids", []) + action = data.get("action", "complete") + if not player_id or not node_ids: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="ValidationError", message="Missing player_id or node_ids"), + ).model_dump()), 400 + from app.factory import get_services + svc = get_services()["progression"] + if action == "complete": + svc.complete_nodes(player_id, node_ids) + elif action == "reveal": + svc.reveal_nodes(player_id, node_ids) + elif action == "reset": + svc.reset_nodes(player_id, node_ids) + else: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="ValidationError", message="Invalid action"), + ).model_dump()), 400 + _audit(f"journey_{action}", {"player_id": player_id, "node_ids": node_ids}) + return jsonify(ApiResponse(success=True).model_dump()) + + +@api_bp.route("/progression/specialization", methods=["POST"]) +@login_required +def set_specialization(): + data = request.get_json() or {} + player_id = data.get("player_id") + track_type = data.get("track_type") + xp = data.get("xp") + level = data.get("level") + if player_id is None or not track_type or xp is None: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="ValidationError", message="Missing required parameters"), + ).model_dump()), 400 + from app.factory import get_services + svc = get_services()["progression"] + svc.set_specialization(player_id, track_type, xp, level or 0) + _audit("specialization_set", {"player_id": player_id, "track": track_type, "xp": xp, "level": level}) + return jsonify(ApiResponse(success=True).model_dump()) + + +@api_bp.route("/progression/specialization/reset", methods=["POST"]) +@login_required +def reset_specializations(): + data = request.get_json() or {} + player_id = data.get("player_id") + if player_id is None: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="ValidationError", message="Missing player_id"), + ).model_dump()), 400 + from app.factory import get_services + svc = get_services()["progression"] + svc.reset_specializations(player_id) + _audit("specialization_reset", {"player_id": player_id}) + return jsonify(ApiResponse(success=True).model_dump()) + + +# ── Character Management Endpoints ────────────────────────────── + +@api_bp.route("/characters//name", methods=["PUT"]) +@login_required +def rename_character(account_id): + data = request.get_json() or {} + name = data.get("name", "").strip() + if not name: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="ValidationError", message="Missing name"), + ).model_dump()), 400 + from app.factory import get_services + svc = get_services()["character"] + svc.rename(account_id, name) + _audit("character_rename", {"account_id": account_id, "new_name": name}) + return jsonify(ApiResponse(success=True).model_dump()) + + +@api_bp.route("/characters/", methods=["DELETE"]) +@login_required +def delete_character(actor_id): + from app.factory import get_services + svc = get_services()["character"] + svc.delete_character(actor_id) + _audit("character_delete", {"actor_id": actor_id}) + return jsonify(ApiResponse(success=True).model_dump()) + + +@api_bp.route("/accounts/", methods=["DELETE"]) +@login_required +def delete_account(user_id): + data = request.get_json() or {} + reason = data.get("reason", "admin") + from app.factory import get_services + svc = get_services()["character"] + svc.delete_account(user_id, reason) + _audit("account_delete", {"user_id": user_id, "reason": reason}) + return jsonify(ApiResponse(success=True).model_dump()) + + +@api_bp.route("/accounts//demo", methods=["PUT"]) +@login_required +def set_demo_state(user_id): + data = request.get_json() or {} + state = data.get("demo") + if state is None: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="ValidationError", message="Missing demo"), + ).model_dump()), 400 + from app.factory import get_services + svc = get_services()["character"] + svc.set_demo(user_id, state) + _audit("demo_set", {"user_id": user_id, "state": state}) + return jsonify(ApiResponse(success=True).model_dump()) + + +# ── Vehicles ──────────────────────────────────────────────────── + +@api_bp.route("/vehicles", methods=["GET"]) +@login_required +def list_vehicles(): + from app.factory import get_services + db = get_services()["db"] + term = request.args.get("q", "") + limit = int(request.args.get("limit", 100)) + rows = db.execute_readonly( + """SELECT a.id, a.class, a.map, c.character_name as owner_name + FROM dune.actors a + JOIN dune.vehicle_instances vi ON a.id = vi.actor_id + LEFT JOIN public.characters c ON vi.owner_id = c.id + WHERE a.class ILIKE %s OR c.character_name ILIKE %s + ORDER BY a.id DESC LIMIT %s""", + [f"%{term}%", f"%{term}%", limit], + ) + vehicles = [{ + "id": r["id"], + "class_name": r["class"], + "display_name": (r["class"] or "").split("/")[-1].replace("_C", "").replace("BP_", "").replace("_", " "), + "map": r["map"], + "owner_name": r["owner_name"] or "Unknown", + } for r in rows] + return jsonify(ApiResponse(success=True, data=vehicles).model_dump()) + + +@api_bp.route("/vehicles//", methods=["POST"]) +@login_required +def vehicle_action(vehicle_id, action): + from app.factory import get_services + db = get_services()["db"] + if action == "repair": + db.call_procedure("repair_vehicle", [vehicle_id]) + _audit("vehicle_repair", {"vehicle_id": vehicle_id}) + elif action == "destroy": + db.call_procedure("destroy_vehicle", [vehicle_id]) + _audit("vehicle_destroy", {"vehicle_id": vehicle_id}) + else: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="ValidationError", message=f"Unknown action: {action}"), + ).model_dump()), 400 + return jsonify(ApiResponse(success=True).model_dump()) + + +# ── Buildings ─────────────────────────────────────────────────── + +@api_bp.route("/buildings", methods=["GET"]) +@login_required +def list_buildings(): + from app.factory import get_services + db = get_services()["db"] + term = request.args.get("q", "") + limit = int(request.args.get("limit", 100)) + rows = db.execute_readonly( + """SELECT a.id, a.class, a.map, a.properties->>'m_bIsPowered' as is_powered, + a.properties->>'m_PowerLevel' as power_level, + c.character_name as owner_name + FROM dune.actors a + JOIN dune.buildings b ON a.id = b.id + LEFT JOIN public.characters c ON b.owner_id = c.id + WHERE a.class ILIKE %s OR c.character_name ILIKE %s + ORDER BY a.id DESC LIMIT %s""", + [f"%{term}%", f"%{term}%", limit], + ) + buildings = [{ + "id": r["id"], + "class_name": r["class"], + "map": r["map"], + "owner_name": r["owner_name"] or "Unknown", + "is_powered": r.get("is_powered") == "True", + "power_level": r.get("power_level"), + "instance_count": 1, + } for r in rows] + return jsonify(ApiResponse(success=True, data=buildings).model_dump()) + + +# ── Accounts ──────────────────────────────────────────────────── + +@api_bp.route("/accounts", methods=["GET"]) +@login_required +def list_accounts(): + from app.factory import get_services + db = get_services()["db"] + term = request.args.get("q", "") + limit = int(request.args.get("limit", 100)) + rows = db.execute_readonly( + """SELECT a.id, a.email, a.funcom_id, + (SELECT COUNT(*) FROM public.characters c WHERE c.account_id = a.id) as character_count, + a.is_demo, a.is_cheater, a.last_login + FROM public.accounts a + WHERE a.email ILIKE %s OR a.funcom_id ILIKE %s + ORDER BY a.last_login DESC NULLS LAST LIMIT %s""", + [f"%{term}%", f"%{term}%", limit], + ) + accounts = [{ + "id": r["id"], + "email": r["email"], + "funcom_id": r["funcom_id"], + "character_count": r["character_count"], + "is_demo": r["is_demo"], + "is_cheater": r["is_cheater"], + "last_login": r["last_login"].isoformat() if r["last_login"] else None, + } for r in rows] + return jsonify(ApiResponse(success=True, data=accounts).model_dump()) + + +@api_bp.route("/players//cheater", methods=["POST"]) +@login_required +def flag_cheater(account_id): + data = request.get_json() or {} + cheat_type = data.get("cheat_type") + if not cheat_type: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="ValidationError", message="Missing cheat_type"), + ).model_dump()), 400 + from app.factory import get_services + svc = get_services()["character"] + svc.flag_cheater(account_id, cheat_type) + _audit("cheater_flag", {"account_id": account_id, "cheat_type": cheat_type}) + return jsonify(ApiResponse(success=True).model_dump()) + + +@api_bp.route("/players//tags", methods=["GET"]) +@login_required +def get_player_tags(account_id): + from app.factory import get_services + svc = get_services()["character"] + tags = svc.get_tags(account_id) + return jsonify(ApiResponse(success=True, data={"tags": tags}).model_dump()) + + +@api_bp.route("/players//tags", methods=["PUT"]) +@login_required +def update_player_tags(account_id): + data = request.get_json() or {} + add = data.get("add", []) + remove = data.get("remove", []) + from app.factory import get_services + svc = get_services()["character"] + svc.update_tags(account_id, add, remove) + _audit("tags_update", {"account_id": account_id, "add": add, "remove": remove}) + return jsonify(ApiResponse(success=True).model_dump()) + + +# ── Broadcast ─────────────────────────────────────────────────── + +@api_bp.route("/broadcast", methods=["POST"]) +@login_required +def send_broadcast(): + data = request.get_json() or {} + try: + req = BroadcastRequest(**data) + except ValidationError as e: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="ValidationError", message=str(e)), + ).model_dump()), 400 + from app.factory import get_services + svc = get_services()["rmq_game"] + success = svc.send_broadcast(req.message, server=req.server, partition=req.partition) + if success: + _audit("broadcast_sent", {"message": req.message, "server": req.server, "partition": req.partition}) + return jsonify(ApiResponse(success=True).model_dump()) + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="BroadcastFailed", message="Failed to send broadcast via RMQ"), + ).model_dump()), 502 + + +# ── Vendor / Economy ──────────────────────────────────────────── + +@api_bp.route("/vendors/clean", methods=["POST"]) +@login_required +def clean_vendor_stock(): + data = request.get_json() or {} + player_id = data.get("player_id") + if not player_id: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="ValidationError", message="Missing player_id"), + ).model_dump()), 400 + from app.factory import get_services + svc = get_services()["economy"] + svc.clean_vendor_stock(player_id) + _audit("vendor_clean", {"player_id": player_id}) + return jsonify(ApiResponse(success=True).model_dump()) + + +@api_bp.route("/tax/invoices", methods=["POST"]) +@login_required +def get_tax_invoices(): + data = request.get_json() or {} + player_id = data.get("player_id") + if not player_id: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="ValidationError", message="Missing player_id"), + ).model_dump()), 400 + from app.factory import get_services + svc = get_services()["economy"] + invoices = svc.get_tax_invoices(player_id) + return jsonify(ApiResponse(success=True, data=invoices).model_dump()) + + +# ── Function Explorer ──────────────────────────────────────────── + +@api_bp.route("/functions", methods=["GET"]) +@login_required +def list_functions(): + from app.factory import get_services + db = get_services()["db"] + rows = db.execute_readonly( + """SELECT p.proname as name, + pg_get_function_identity_arguments(p.oid) as args, + l.lanname as language, + p.prokind as kind + FROM pg_proc p + JOIN pg_namespace n ON n.oid = p.pronamespace + JOIN pg_language l ON l.oid = p.prolang + WHERE n.nspname = 'dune' AND p.prokind = 'f' + ORDER BY p.proname""" + ) + return jsonify(ApiResponse(success=True, data=rows).model_dump()) + + +@api_bp.route("/functions/", methods=["GET"]) +@login_required +def get_function_detail(name): + from app.factory import get_services + db = get_services()["db"] + rows = db.execute_readonly( + """SELECT pg_get_functiondef(p.oid) as definition, + p.proname as name, + pg_get_function_identity_arguments(p.oid) as args + FROM pg_proc p + JOIN pg_namespace n ON n.oid = p.pronamespace + WHERE n.nspname = 'dune' AND p.proname = %s AND p.prokind = 'f'""", + [name], + ) + if not rows: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="NotFound", message="Function not found"), + ).model_dump()), 404 + return jsonify(ApiResponse(success=True, data=rows[0]).model_dump()) + + +@api_bp.route("/functions/execute", methods=["POST"]) +@login_required +def execute_function_v2(): + data = request.get_json() or {} + schema = data.get("schema") + func_name = data.get("function", "") + args = data.get("args", {}) + if not func_name: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="ValidationError", message="Missing function name"), + ).model_dump()), 400 + from app.factory import get_services + db = get_services()["db"] + try: + full_name = f"{schema}.{func_name}" if schema else func_name + if isinstance(args, dict): + params = list(args.values()) + elif isinstance(args, list): + params = args + else: + params = [args] + result = db.call_function(full_name, params) + _audit("function_execute", {"function": full_name, "params": params}) + return jsonify(ApiResponse(success=True, data=result).model_dump()) + except Exception as e: + logger.exception("Function execution failed") + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="ExecutionError", message=str(e)), + ).model_dump()), 500 + + +@api_bp.route("/functions//execute", methods=["POST"]) +@login_required +def execute_function(name): + data = request.get_json() or {} + params = data.get("params", []) + from app.factory import get_services + db = get_services()["db"] + try: + result = db.call_function(name, params) + _audit("function_execute", {"function": name, "params": params}) + return jsonify(ApiResponse(success=True, data=result).model_dump()) + except Exception as e: + logger.exception("Function execution failed") + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="ExecutionError", message=str(e)), + ).model_dump()), 500 + + +# ── Raw Query (SELECT only) ────────────────────────────────────── + +@api_bp.route("/query", methods=["POST"]) +@login_required +def raw_query(): + data = request.get_json() or {} + sql = (data.get("query") or data.get("sql", "")).strip() + if not sql: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="ValidationError", message="Missing SQL"), + ).model_dump()), 400 + upper = sql.upper() + if any(kw in upper for kw in ("INSERT", "UPDATE", "DELETE", "DROP", "CREATE", "ALTER", "GRANT", "TRUNCATE")): + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="Forbidden", message="Only SELECT queries are allowed"), + ).model_dump()), 403 + from app.factory import get_services + db = get_services()["db"] + try: + result = db.execute_readonly(sql) + _audit("raw_query", {"sql": sql[:200]}) + return jsonify(ApiResponse(success=True, data=result).model_dump()) + except Exception as e: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="QueryError", message=str(e)), + ).model_dump()), 500 + + +# ── Audit Logs ────────────────────────────────────────────────── + +@api_bp.route("/audit/logs", methods=["GET"]) +@login_required +def get_audit_logs(): + action = request.args.get("action") + user = request.args.get("user") + limit = int(request.args.get("limit", 100)) + offset = int(request.args.get("offset", 0)) + from app.factory import get_services + svc = get_services()["audit"] + logs = svc.get_logs(action=action, user=user, limit=limit, offset=offset) + return jsonify(ApiResponse(success=True, data=logs).model_dump()) + + +@api_bp.route("/stats", methods=["GET"]) +@login_required +def get_stats(): + from app.factory import get_services + db = get_services()["db"] + try: + stats = db.execute_readonly(""" + SELECT + (SELECT COUNT(*) FROM public.characters) AS total_players, + (SELECT COUNT(*) FROM public.characters WHERE is_online = true) AS online_players, + (SELECT COUNT(*) FROM public.guilds) AS guild_count, + (SELECT COUNT(*) FROM public.guilds WHERE active = true) AS active_guilds, + (SELECT COUNT(*) FROM public.game_servers) AS server_count, + (SELECT COUNT(*) FROM public.partitions) AS partition_count, + (SELECT COALESCE(SUM(worth), 0) FROM public.player_economy) AS total_worth, + (SELECT COUNT(*) FROM public.flavor_text) AS total_flavor_text + """) + return jsonify(ApiResponse(success=True, data=stats[0] if stats else {}).model_dump()) + except Exception as e: + logger.exception("Failed to get stats") + return jsonify(ApiResponse(success=False, error=ErrorDetail(code="StatsError", message=str(e))).model_dump()), 500 + + +@api_bp.route("/audit/stats", methods=["GET"]) +@login_required +def get_audit_stats(): + from app.factory import get_services + svc = get_services()["audit"] + stats = svc.get_stats() + return jsonify(ApiResponse(success=True, data=stats).model_dump()) + + +# ── Settings ──────────────────────────────────────────────────── + +@api_bp.route("/settings", methods=["GET"]) +@login_required +def get_settings(): + from app.factory import get_services + settings = get_services()["db"].execute_readonly( + "SELECT key, value, updated_at FROM dashboard.settings ORDER BY key" + ) + return jsonify(ApiResponse(success=True, data={r["key"]: r["value"] for r in settings}).model_dump()) + + +@api_bp.route("/settings", methods=["POST"]) +@login_required +def update_settings(): + data = request.get_json() or {} + if not isinstance(data, dict): + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="ValidationError", message="Expected JSON object"), + ).model_dump()), 400 + from app.factory import get_services + db = get_services()["db"] + for key, value in data.items(): + db.execute_mutation( + """INSERT INTO dashboard.settings (key, value, updated_at) + VALUES (%s, %s, NOW()) + ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = NOW()""", + [key, str(value)], + ) + _audit("settings_update", {"keys": list(data.keys())}) + return jsonify(ApiResponse(success=True).model_dump()) + + +# ── Moderation (Ban / Kick) ──────────────────────────────────── + +@api_bp.route("/players//ban", methods=["POST"]) +@login_required +def ban_player(player_id): + data = request.get_json() or {} + reason = data.get("reason", "admin") + duration = data.get("duration_hours", 0) + from app.factory import get_services + db = get_services()["db"] + db.execute_mutation( + """INSERT INTO dashboard.bans (player_id, reason, duration, banned_at, expires_at, active) + VALUES (%s, %s, %s, NOW(), CASE WHEN %s > 0 THEN NOW() + INTERVAL '%s hours' ELSE NULL END, TRUE) + ON CONFLICT (player_id) DO UPDATE SET reason = EXCLUDED.reason, duration = EXCLUDED.duration, banned_at = NOW(), expires_at = EXCLUDED.expires_at, active = TRUE""", + [player_id, reason, duration, duration, duration], + ) + _audit("player_ban", {"player_id": player_id, "reason": reason, "duration": duration}) + return jsonify(ApiResponse(success=True).model_dump()) + + +@api_bp.route("/players//unban", methods=["POST"]) +@login_required +def unban_player(player_id): + from app.factory import get_services + db = get_services()["db"] + db.execute_mutation( + "UPDATE dashboard.bans SET active = FALSE WHERE player_id = %s", + [player_id], + ) + _audit("player_unban", {"player_id": player_id}) + return jsonify(ApiResponse(success=True).model_dump()) + + +@api_bp.route("/players//ban", methods=["GET"]) +@login_required +def get_player_ban(player_id): + from app.factory import get_services + db = get_services()["db"] + rows = db.execute_readonly( + "SELECT * FROM dashboard.bans WHERE player_id = %s AND active = TRUE", + [player_id], + ) + return jsonify(ApiResponse(success=True, data=rows[0] if rows else None).model_dump()) + + +@api_bp.route("/players//kick", methods=["POST"]) +@login_required +def kick_player(player_id): + data = request.get_json() or {} + reason = data.get("reason", "admin") + _audit("player_kick", {"player_id": player_id, "reason": reason}) + return jsonify(ApiResponse(success=True).model_dump()) + + +@api_bp.route("/players//history", methods=["GET"]) +@login_required +def get_player_history(player_id): + from app.factory import get_services + db = get_services()["db"] + logs = db.execute_readonly( + """SELECT * FROM dashboard.audit_log + WHERE target_player_id = %s OR (details->>'player_id')::bigint = %s + ORDER BY created_at DESC LIMIT 100""", + [player_id, player_id], + ) + return jsonify(ApiResponse(success=True, data=logs).model_dump()) diff --git a/backend/app/routes/auth.py b/backend/app/routes/auth.py new file mode 100644 index 0000000..e29d38d --- /dev/null +++ b/backend/app/routes/auth.py @@ -0,0 +1,131 @@ +# Authentication routes — login, logout. + +import time +import threading +from functools import wraps + +from flask import Blueprint, request, jsonify, session +from flask_login import LoginManager, UserMixin, login_user, logout_user, login_required, current_user + +from app.models import ApiResponse, ErrorDetail + +auth_bp = Blueprint("auth", __name__) +login_manager = LoginManager() + +_failed_attempts = {} +_failed_lock = threading.Lock() +_MAX_FAILED_ATTEMPTS = 5 +_BLOCK_DURATION = 900 + + +class AdminUser(UserMixin): + def __init__(self, username): + self.id = username + + +def _is_ip_blocked(ip): + with _failed_lock: + record = _failed_attempts.get(ip) + if record and record["count"] >= _MAX_FAILED_ATTEMPTS: + elapsed = time.time() - record["first_attempt"] + if elapsed < _BLOCK_DURATION: + return True + del _failed_attempts[ip] + return False + + +def _record_failed_attempt(ip): + with _failed_lock: + now = time.time() + record = _failed_attempts.get(ip) + if record: + record["count"] += 1 + else: + _failed_attempts[ip] = {"count": 1, "first_attempt": now} + return _failed_attempts[ip]["count"] >= _MAX_FAILED_ATTEMPTS + + +def _clear_failed_attempts(ip): + with _failed_lock: + _failed_attempts.pop(ip, None) + + +def init_auth(app, settings): + login_manager.init_app(app) + login_manager.login_view = "auth.login" + login_manager.login_message = "Please log in." + + @login_manager.user_loader + def load_user(user_id): + auth = settings.get("auth", {}) + if str(auth.get("username")) == str(user_id): + return AdminUser(user_id) + return None + + +def get_audit_user(): + return current_user.id if current_user.is_authenticated else "anonymous" + + +@auth_bp.route("/login", methods=["POST"]) +def login(): + data = request.get_json() or {} + username = data.get("username", "").strip() + password = data.get("password", "") + client_ip = request.remote_addr or "unknown" + + if _is_ip_blocked(client_ip): + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="IpBlocked", message="Too many failed attempts. Try again later."), + ).model_dump()), 429 + + auth = request.app.dune_settings.get("auth", {}) + cfg_u = str(auth.get("username", "")) + password_hash = auth.get("password_hash") + + if username != cfg_u: + _record_failed_attempt(client_ip) + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="InvalidCredentials", message="Invalid username or password"), + ).model_dump()), 401 + + if password_hash: + try: + from argon2 import PasswordHasher, exceptions + ph = PasswordHasher(time_cost=3, memory_cost=65536) + ph.verify(password_hash, password) + _clear_failed_attempts(client_ip) + login_user(AdminUser(username)) + return jsonify(ApiResponse(success=True, data={"user": username}).model_dump()) + except exceptions.VerifyMismatchError: + _record_failed_attempt(client_ip) + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="InvalidCredentials", message="Invalid username or password"), + ).model_dump()), 401 + except Exception: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="AuthError", message="Authentication error"), + ).model_dump()), 500 + else: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="NotConfigured", message="Authentication not configured"), + ).model_dump()), 403 + + +@auth_bp.route("/logout", methods=["POST"]) +@login_required +def logout(): + logout_user() + return jsonify(ApiResponse(success=True).model_dump()) + + +@auth_bp.route("/me", methods=["GET"]) +def me(): + if current_user.is_authenticated: + return jsonify(ApiResponse(success=True, data={"user": current_user.id}).model_dump()) + return jsonify(ApiResponse(success=False, error=ErrorDetail(code="Unauthorized", message="Not authenticated")).model_dump()), 401 diff --git a/backend/app/routes/chat.py b/backend/app/routes/chat.py new file mode 100644 index 0000000..3e98bae --- /dev/null +++ b/backend/app/routes/chat.py @@ -0,0 +1,24 @@ +# Chat routes. + +import logging + +from flask import Blueprint, jsonify, request +from flask_login import login_required + +from app.models import ApiResponse, ErrorDetail + +chat_bp = Blueprint("chat", __name__) +logger = logging.getLogger(__name__) + + +@chat_bp.route("/history", methods=["GET"]) +@login_required +def chat_history(): + channel = request.args.get("channel", "") + limit = int(request.args.get("limit", 100)) + from app.factory import get_services + svc = get_services()["chat"] + rows = svc.get_history(limit=limit) + if channel: + rows = [r for r in rows if r.get("channel", "").lower() == channel.lower()] + return jsonify(ApiResponse(success=True, data=rows).model_dump()) diff --git a/backend/app/routes/debug.py b/backend/app/routes/debug.py new file mode 100644 index 0000000..3bb113c --- /dev/null +++ b/backend/app/routes/debug.py @@ -0,0 +1,43 @@ +# Debug routes — restricted to admin. + +import logging + +from flask import Blueprint, jsonify +from flask_login import login_required + +from app.models import ApiResponse, ErrorDetail + +debug_bp = Blueprint("debug", __name__) +logger = logging.getLogger(__name__) + + +def _get_services(): + from app.factory import get_services + return get_services() + + +@debug_bp.route("/tables", methods=["GET"]) +@login_required +def list_tables(): + db = _get_services()["db"] + rows = db.execute_readonly( + "SELECT table_name FROM information_schema.tables WHERE table_schema = 'dune' ORDER BY table_name" + ) + return jsonify(ApiResponse(success=True, data={"tables": [r["table_name"] for r in rows]}).model_dump()) + + +@debug_bp.route("/vehicle/", methods=["GET"]) +@login_required +def debug_vehicle(vehicle_id): + db = _get_services()["db"] + vehicle = db.execute_readonly( + """SELECT a.id, a.class, a.properties + FROM dune.actors a JOIN dune.vehicles v ON a.id = v.id WHERE a.id = %s""", + [vehicle_id], + ) + if not vehicle: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="NotFound", message="Vehicle not found"), + ).model_dump()), 404 + return jsonify(ApiResponse(success=True, data=vehicle[0]).model_dump()) diff --git a/backend/app/routes/director.py b/backend/app/routes/director.py new file mode 100644 index 0000000..887fe99 --- /dev/null +++ b/backend/app/routes/director.py @@ -0,0 +1,147 @@ +# BGD Director proxy routes. + +import logging + +from flask import Blueprint, jsonify, request +from flask_login import login_required + +from app.models import ApiResponse, ErrorDetail + +director_bp = Blueprint("director", __name__) +logger = logging.getLogger(__name__) + + +def _get_service(): + from app.factory import get_services + return get_services()["bg_director"] + + +@director_bp.route("/battlegroup", methods=["GET"]) +@login_required +def director_battlegroup(): + try: + svc = _get_service() + data = svc.get_battlegroup() + return jsonify(ApiResponse(success=True, data=data.model_dump()).model_dump()) + except Exception as e: + logger.error("Director battlegroup error: %s", e) + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="DirectorUnavailable", message=str(e), hint="Check BGD pod logs"), + ).model_dump()), 503 + + +@director_bp.route("/config", methods=["POST"]) +@login_required +def director_update_config(): + data = request.get_json() or {} + try: + svc = _get_service() + result = svc.update_server_config(data) + return jsonify(ApiResponse(success=True, data={"result": result}).model_dump()) + except Exception as e: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="DirectorUnavailable", message=str(e)), + ).model_dump()), 503 + + +@director_bp.route("/config/clear", methods=["POST"]) +@login_required +def director_clear_config(): + map_name = request.get_data(as_text=True).strip() + try: + svc = _get_service() + result = svc.clear_map_config(map_name) + return jsonify(ApiResponse(success=True, data={"result": result}).model_dump()) + except Exception as e: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="DirectorUnavailable", message=str(e)), + ).model_dump()), 503 + + +@director_bp.route("/transfer", methods=["GET"]) +@login_required +def director_transfer_get(): + try: + svc = _get_service() + data = svc.get_transfer_rules() + return jsonify(ApiResponse(success=True, data=data).model_dump()) + except Exception as e: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="DirectorUnavailable", message=str(e)), + ).model_dump()), 503 + + +@director_bp.route("/transfer", methods=["POST"]) +@login_required +def director_transfer_update(): + data = request.get_json() or {} + try: + svc = _get_service() + result = svc.update_transfer_settings(data) + return jsonify(ApiResponse(success=True, data={"result": result}).model_dump()) + except Exception as e: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="DirectorUnavailable", message=str(e)), + ).model_dump()), 503 + + +@director_bp.route("/transfer/clear", methods=["POST"]) +@login_required +def director_transfer_clear(): + try: + svc = _get_service() + result = svc.clear_transfer_overrides() + return jsonify(ApiResponse(success=True, data={"result": result}).model_dump()) + except Exception as e: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="DirectorUnavailable", message=str(e)), + ).model_dump()), 503 + + +@director_bp.route("/fls", methods=["GET"]) +@login_required +def director_fls_get(): + try: + svc = _get_service() + data = svc.get_fls_settings() + return jsonify(ApiResponse(success=True, data=data).model_dump()) + except Exception as e: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="DirectorUnavailable", message=str(e)), + ).model_dump()), 503 + + +@director_bp.route("/fls", methods=["POST"]) +@login_required +def director_fls_update(): + data = request.get_json() or {} + try: + svc = _get_service() + result = svc.update_fls_settings(data) + return jsonify(ApiResponse(success=True, data={"result": result}).model_dump()) + except Exception as e: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="DirectorUnavailable", message=str(e)), + ).model_dump()), 503 + + +@director_bp.route("/fls/clear", methods=["POST"]) +@login_required +def director_fls_clear(): + try: + svc = _get_service() + result = svc.clear_fls_overrides() + return jsonify(ApiResponse(success=True, data={"result": result}).model_dump()) + except Exception as e: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="DirectorUnavailable", message=str(e)), + ).model_dump()), 503 diff --git a/backend/app/routes/files.py b/backend/app/routes/files.py new file mode 100644 index 0000000..16027c0 --- /dev/null +++ b/backend/app/routes/files.py @@ -0,0 +1,120 @@ +# File browser routes. + +import base64 +import logging +import posixpath + +from flask import Blueprint, jsonify, request +from flask_login import login_required + +from app.models import ApiResponse, ErrorDetail + +files_bp = Blueprint("files", __name__) +logger = logging.getLogger(__name__) + +FILEBROWSER_BASE_PATH = "/srv" + + +def _validate_fb_path(path: str) -> bool: + path_str = str(path or "").lstrip("/") + if ".." in path_str or "\x00" in path_str: + return False + normalized = posixpath.normpath("/" + path_str) + return normalized == FILEBROWSER_BASE_PATH or normalized.startswith(FILEBROWSER_BASE_PATH + "/") + + +def _get_services(): + from app.factory import get_services + return get_services() + + +def _fb_exec(command: str, timeout: int = 10): + services = _get_services() + k8s = services["k8s"] + pod = k8s.get_filebrowser_pod() + if not pod: + return "", "FileBrowser pod not found", 1 + full_cmd = f"sudo kubectl exec {pod} -n {k8s.namespace} -- {command}" + return k8s.ssh.run(full_cmd, timeout=timeout) + + +@files_bp.route("/list", methods=["POST"]) +@login_required +def files_list(): + data = request.get_json() or {} + path = data.get("path", "/srv") + if not _validate_fb_path(path): + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="AccessDenied", message="Invalid path"), + ).model_dump()), 403 + import shlex + safe_path = shlex.quote(path) + out, err, rc = _fb_exec(f"ls -la {safe_path}", timeout=10) + if rc != 0: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="CommandError", message=err or "Failed to list directory"), + ).model_dump()), 500 + + files = [] + for line in out.strip().split("\n")[1:]: + parts = line.split(None, 8) + if len(parts) >= 9: + name = parts[8] + if name in (".", ".."): + continue + files.append({ + "name": name, + "is_dir": parts[0].startswith("d"), + "size": parts[4] if not parts[0].startswith("d") else "", + "perms": parts[0], + "date": " ".join(parts[5:8]), + }) + return jsonify(ApiResponse(success=True, data={"files": files}).model_dump()) + + +@files_bp.route("/view", methods=["GET"]) +@login_required +def files_view(): + path = request.args.get("path", "") + if not path or not _validate_fb_path(path): + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="AccessDenied", message="Invalid path"), + ).model_dump()), 403 + import shlex + safe_path = shlex.quote(path) + out, err, rc = _fb_exec(f"head -c 100000 {safe_path}", timeout=10) + if rc != 0: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="CommandError", message=err or "Failed to read file"), + ).model_dump()), 500 + return jsonify(ApiResponse(success=True, data={"content": out, "path": path}).model_dump()) + + +@files_bp.route("/save", methods=["POST"]) +@login_required +def files_save(): + data = request.get_json() or {} + path = data.get("path", "") + content = data.get("content", "") + if not path or not _validate_fb_path(path): + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="AccessDenied", message="Invalid path"), + ).model_dump()), 403 + import shlex + import base64 + content_b64 = base64.b64encode(content.encode()).decode() + safe_path = shlex.quote(path) + # Write via base64 decode inside pod + cmd = f"echo {content_b64} | base64 -d > {safe_path}" + out, err, rc = _fb_exec(cmd, timeout=15) + if rc != 0: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="CommandError", message=err or "Failed to save file"), + ).model_dump()), 500 + return jsonify(ApiResponse(success=True).model_dump()) diff --git a/backend/app/routes/health.py b/backend/app/routes/health.py new file mode 100644 index 0000000..0229de7 --- /dev/null +++ b/backend/app/routes/health.py @@ -0,0 +1,84 @@ +# Health and SSE routes. + +import asyncio +import json +import logging + +from flask import Blueprint, jsonify, Response, request, stream_with_context +from flask_login import login_required, current_user + +from app.models import ApiResponse, ErrorDetail + +health_bp = Blueprint("health", __name__) +logger = logging.getLogger(__name__) + + +@health_bp.route("/health", methods=["GET"]) +def health_check(): + from app.factory import get_services + services = get_services() + health = {"status": "healthy", "timestamp": __import__("datetime").datetime.now().isoformat(), "checks": {}} + status_code = 200 + + try: + services["db"].health_check() + health["checks"]["database"] = "ok" + except Exception as e: + health["checks"]["database"] = f"error: {e}" + health["status"] = "degraded" + status_code = 503 + + try: + services["ssh"].check_connection() + health["checks"]["ssh"] = "ok" + except Exception as e: + health["checks"]["ssh"] = f"error: {e}" + health["status"] = "degraded" + status_code = 503 + + try: + services["bg_director"].get_battlegroup() + health["checks"]["bgd"] = "ok" + except Exception as e: + health["checks"]["bgd"] = f"error: {e}" + health["status"] = "degraded" + status_code = 503 + + try: + services["rmq_admin"].get_overview() + health["checks"]["rmq"] = "ok" + except Exception as e: + health["checks"]["rmq"] = f"error: {e}" + health["status"] = "degraded" + status_code = 503 + + return jsonify(health), status_code + + +@health_bp.route("/events/stream", methods=["GET"]) +@login_required +def sse_stream(): + from app.factory import get_services + services = get_services() + realtime = services["realtime"] + + queue = asyncio.Queue(maxsize=100) + realtime.add_client(queue) + + def event_stream(): + try: + yield "event: connected\ndata: {}\n\n" + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + while True: + try: + msg = loop.run_until_complete(asyncio.wait_for(queue.get(), timeout=30)) + yield msg + except asyncio.TimeoutError: + yield ":ping\n\n" + except Exception: + break + finally: + realtime.remove_client(queue) + + return Response(stream_with_context(event_stream()), mimetype="text/event-stream") diff --git a/backend/app/routes/server.py b/backend/app/routes/server.py new file mode 100644 index 0000000..c4a9a96 --- /dev/null +++ b/backend/app/routes/server.py @@ -0,0 +1,218 @@ +# Server and infrastructure routes. + +import logging + +from flask import Blueprint, jsonify, request +from flask_login import login_required + +from app.models import ApiResponse, ErrorDetail + +server_bp = Blueprint("server", __name__) +logger = logging.getLogger(__name__) + + +def _get_services(): + from app.factory import get_services + return get_services() + + +@server_bp.route("/pods", methods=["GET"]) +@login_required +def server_pods(): + services = _get_services() + pods = services["k8s"].get_pods() + return jsonify(ApiResponse(success=True, data=pods).model_dump()) + + +@server_bp.route("/deployments", methods=["GET"]) +@login_required +def server_deployments(): + services = _get_services() + deployments = services["k8s"].get_deployments() + return jsonify(ApiResponse(success=True, data=deployments).model_dump()) + + +@server_bp.route("/metrics", methods=["GET"]) +@login_required +def server_metrics(): + services = _get_services() + raw = services["k8s"].get_node_metrics() + from datetime import datetime, timezone + metrics = [] + if raw: + cpu_str = raw.get("cpu", "0m").replace("m", "").replace("%", "") + mem_str = raw.get("memory", "0Mi").replace("Mi", "").replace("Gi", "000") + try: + cpu_val = float(cpu_str) + mem_val = float(mem_str) + metrics.append({ + "timestamp": datetime.now(timezone.utc).isoformat(), + "cpu_percent": min(100, round(cpu_val / 10, 1)), # rough estimate + "memory_percent": min(100, round(mem_val / 100, 1)), # rough estimate + }) + except ValueError: + pass + return jsonify(ApiResponse(success=True, data=metrics).model_dump()) + + +@server_bp.route("/deployments//restart", methods=["POST"]) +@login_required +def restart_deployment(name: str): + services = _get_services() + out, err, rc = services["k8s"].run(f"rollout restart deployment/{name}") + return jsonify(ApiResponse( + success=rc == 0, + data={"output": out, "error": err, "rc": rc}, + ).model_dump()) + + +@server_bp.route("/deployments//scale", methods=["POST"]) +@login_required +def scale_deployment(name: str): + data = request.get_json() or {} + replicas = data.get("replicas") + if replicas is None: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="ValidationError", message="Missing replicas"), + ).model_dump()), 400 + services = _get_services() + out, err, rc = services["k8s"].run(f"scale deployment/{name} --replicas={replicas}") + return jsonify(ApiResponse( + success=rc == 0, + data={"output": out, "error": err, "rc": rc}, + ).model_dump()) + + +@server_bp.route("/action", methods=["POST"]) +@login_required +def server_action(): + data = request.get_json() or {} + deployment = data.get("deployment", "") + action = data.get("action", "") + if not deployment or not action: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="ValidationError", message="Missing deployment or action"), + ).model_dump()), 400 + + actions = { + "restart": f"rollout restart deployment/{deployment}", + "status": f"rollout status deployment/{deployment}", + "scale_0": f"scale deployment/{deployment} --replicas=0", + "scale_1": f"scale deployment/{deployment} --replicas=1", + "describe": f"describe deployment/{deployment}", + } + cmd = actions.get(action) + if not cmd: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="ValidationError", message=f"Unknown action: {action}"), + ).model_dump()), 400 + + services = _get_services() + out, err, rc = services["k8s"].run(cmd) + return jsonify(ApiResponse( + success=rc == 0, + data={"output": out, "error": err, "rc": rc}, + ).model_dump()) + + +@server_bp.route("/firewall", methods=["GET"]) +@server_bp.route("/firewall/status", methods=["GET"]) +@login_required +def firewall_status(): + services = _get_services() + ssh = services["ssh"] + out, _, _ = ssh.run( + "sudo iptables -L INPUT -n 2>/dev/null | grep -E 'dpt:(18888|32479)'; " + "sudo iptables -L FORWARD -n 2>/dev/null | grep -E 'dpt:(18888|32479)'; " + "sudo iptables -t mangle -L PREROUTING -n 2>/dev/null | grep -E 'dpt:(18888|32479)'", + timeout=15, + ) + blocked_ports = set() + for line in out.split("\n"): + for port in ("18888", "32479"): + if f"dpt:{port}" in line and "DROP" in line: + blocked_ports.add(port) + return jsonify(ApiResponse( + success=True, + data={ + "18888_blocked": "18888" in blocked_ports, + "32479_blocked": "32479" in blocked_ports, + }, + ).model_dump()) + + +@server_bp.route("/firewall/toggle", methods=["POST"]) +@login_required +def firewall_toggle(): + data = request.get_json() or {} + port = data.get("port") + block = data.get("block", True) + if not port: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="ValidationError", message="Missing port"), + ).model_dump()), 400 + services = _get_services() + ssh = services["ssh"] + if block: + cmd = ( + f"sudo iptables -I INPUT 1 -p tcp --dport {port} -s 127.0.0.1 -j ACCEPT && " + f"sudo iptables -I INPUT 2 -p tcp --dport {port} -j DROP && " + f"sudo iptables -I FORWARD 1 -p tcp --dport {port} -s 127.0.0.1 -j ACCEPT && " + f"sudo iptables -I FORWARD 2 -p tcp --dport {port} -j DROP && " + f"sudo iptables -t mangle -I PREROUTING 1 -p tcp --dport {port} -s 127.0.0.1 -j ACCEPT && " + f"sudo iptables -t mangle -I PREROUTING 2 -p tcp --dport {port} -j DROP" + ) + else: + cmd = ( + f"sudo iptables -D INPUT -p tcp --dport {port} -j DROP 2>/dev/null; " + f"sudo iptables -D INPUT -p tcp --dport {port} -s 127.0.0.1 -j ACCEPT 2>/dev/null; " + f"sudo iptables -D FORWARD -p tcp --dport {port} -j DROP 2>/dev/null; " + f"sudo iptables -D FORWARD -p tcp --dport {port} -s 127.0.0.1 -j ACCEPT 2>/dev/null; " + f"sudo iptables -t mangle -D PREROUTING -p tcp --dport {port} -j DROP 2>/dev/null; " + f"sudo iptables -t mangle -D PREROUTING -p tcp --dport {port} -s 127.0.0.1 -j ACCEPT 2>/dev/null; " + f"echo DONE" + ) + out, err, rc = ssh.run(cmd, timeout=20) + success = rc == 0 or "DONE" in out + return jsonify(ApiResponse( + success=success, + data={"output": out, "error": err}, + ).model_dump()) + + +@server_bp.route("/rmq/queues", methods=["GET"]) +@login_required +def rmq_queues(): + services = _get_services() + try: + queues = services["rmq_admin"].get_queue_depths() + return jsonify(ApiResponse( + success=True, + data=[q.model_dump() for q in queues], + ).model_dump()) + except Exception as e: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="RmqError", message=str(e)), + ).model_dump()), 503 + + +@server_bp.route("/rmq/overview", methods=["GET"]) +@login_required +def rmq_overview(): + services = _get_services() + try: + overview = services["rmq_admin"].get_overview() + return jsonify(ApiResponse( + success=True, + data=overview.model_dump(), + ).model_dump()) + except Exception as e: + return jsonify(ApiResponse( + success=False, + error=ErrorDetail(code="RmqError", message=str(e)), + ).model_dump()), 503 diff --git a/backend/app/services/__init__.py b/backend/app/services/__init__.py new file mode 100644 index 0000000..7d8bdeb --- /dev/null +++ b/backend/app/services/__init__.py @@ -0,0 +1 @@ +# Services package init. diff --git a/backend/app/services/audit.py b/backend/app/services/audit.py new file mode 100644 index 0000000..0520132 --- /dev/null +++ b/backend/app/services/audit.py @@ -0,0 +1,64 @@ +# Audit logging service — persistent PostgreSQL storage. + +import logging +from datetime import datetime + +from app.services.database import DatabaseService + +logger = logging.getLogger(__name__) + + +class AuditService: + def __init__(self, db: DatabaseService): + self.db = db + + def log(self, action: str, user: str, details: dict | None = None, + target_player_id: int | None = None, severity: str = "info", + source_ip: str | None = None) -> bool: + try: + self.db.execute_mutation( + """INSERT INTO dashboard.audit_log + (action_type, user_name, target_player_id, details, source_ip, severity, created_at) + VALUES (%s, %s, %s, %s, %s, %s, NOW())""", + [action, user, target_player_id, details or {}, source_ip, severity], + ) + logger.info("Audit: %s by %s", action, user) + return True + except Exception as e: + logger.error("Audit log failed: %s", e) + return False + + def get_logs(self, action: str | None = None, user: str | None = None, + target_player_id: int | None = None, limit: int = 100, + offset: int = 0) -> list[dict]: + sql = """SELECT id, action_type, user_name, target_player_id, details, + source_ip, severity, created_at + FROM dashboard.audit_log WHERE 1=1""" + params = [] + if action: + sql += " AND action_type = %s" + params.append(action) + if user: + sql += " AND user_name = %s" + params.append(user) + if target_player_id: + sql += " AND target_player_id = %s" + params.append(target_player_id) + sql += " ORDER BY created_at DESC LIMIT %s OFFSET %s" + params.extend([limit, offset]) + return self.db.execute_readonly(sql, params) + + def get_stats(self) -> dict: + rows = self.db.execute_readonly( + """SELECT action_type, COUNT(*) as cnt FROM dashboard.audit_log + GROUP BY action_type""" + ) + return {r["action_type"]: r["cnt"] for r in rows} + + def cleanup_old(self, days: int = 90) -> int: + result = self.db.execute_mutation( + "DELETE FROM dashboard.audit_log WHERE created_at < NOW() - INTERVAL '%s days'", + [days], + ) + logger.info("Audit cleanup: removed %d entries older than %d days", result, days) + return result diff --git a/backend/app/services/bg_director.py b/backend/app/services/bg_director.py new file mode 100644 index 0000000..a1a6393 --- /dev/null +++ b/backend/app/services/bg_director.py @@ -0,0 +1,141 @@ +"""Battlegroup Director HTTP API client.""" + +import json +import logging +from typing import Any, Dict + +import httpx + +from app.models import BattlegroupState, ErrorDetail + +logger = logging.getLogger(__name__) + + +class BgDirectorService: + def __init__(self, host: str, node_port: int): + self.base_url = f"http://{host}:{node_port}" + self.client = httpx.Client(base_url=self.base_url, timeout=15) + logger.debug("BgDirectorService initialized: %s", self.base_url) + + def _request(self, method: str, path: str, data: Any = None, timeout: int = 15) -> dict | str: + try: + if method == "GET": + resp = self.client.get(path, timeout=timeout) + else: + if isinstance(data, str): + resp = self.client.request(method, path, content=data, headers={"Content-Type": "application/json"}, timeout=timeout) + else: + resp = self.client.request(method, path, json=data, timeout=timeout) + resp.raise_for_status() + if resp.headers.get("content-type", "").startswith("application/json"): + return resp.json() + return resp.text + except httpx.HTTPStatusError as e: + logger.error("BGD HTTP error %s %s: %s", method, path, e) + raise DirectorUnavailableError(f"BGD returned {e.response.status_code}") + except httpx.ConnectError as e: + logger.error("BGD connection error %s %s: %s", method, path, e) + raise DirectorUnavailableError("The Battlegroup Director is not responding. Check BGD pod logs.") + except Exception as e: + logger.error("BGD request error %s %s: %s", method, path, e) + raise DirectorUnavailableError(str(e)) + + # ── Player Endpoints ────────────────────────────────────────── + + def get_battlegroup(self) -> BattlegroupState: + data = self._request("GET", "/v0/battlegroup", timeout=15) + if isinstance(data, str): + data = json.loads(data) + return _parse_battlegroup(data) + + def get_all_players(self) -> list[str]: + data = self._request("GET", "/v0/players") + return data if isinstance(data, list) else [] + + def get_online_players(self) -> list[str]: + data = self._request("GET", "/v0/players/online") + return data if isinstance(data, list) else [] + + def get_intransit_players(self) -> list[str]: + data = self._request("GET", "/v0/players/intransit") + return data if isinstance(data, list) else [] + + def get_graceperiod_players(self) -> list[str]: + data = self._request("GET", "/v0/players/graceperiod") + return data if isinstance(data, list) else [] + + def get_completion_players(self) -> list[str]: + data = self._request("GET", "/v0/players/completion") + return data if isinstance(data, list) else [] + + def get_queued_players(self) -> list[str]: + data = self._request("GET", "/v0/players/queued") + return data if isinstance(data, list) else [] + + # ── FLS Settings ─────────────────────────────────────────────── + + def get_fls_settings(self) -> dict: + return self._request("GET", "/v0/BattlegroupFetchFlsReportSettings") + + def update_fls_settings(self, settings: dict) -> str: + return self._request("POST", "/v0/BattlegroupUpdateFlsReportSettings", data=settings, timeout=30) + + def clear_fls_overrides(self) -> str: + return self._request("POST", "/v0/BattlegroupClearFlsReportOverrides", timeout=30) + + # ── Server Config ────────────────────────────────────────────── + + def update_server_config(self, config: dict) -> str: + return self._request("POST", "/v0/BattlegroupUpdateServerGroupConfig", data=config, timeout=30) + + def clear_map_config(self, map_name: str) -> str: + return self._request("POST", "/v0/BattlegroupClearMapConfigOverrides", data=map_name, timeout=30) + + # ── Character Transfer ────────────────────────────────────────── + + def get_transfer_rules(self) -> dict: + return self._request("GET", "/v0/BattlegroupFetchCharacterTransferRules") + + def update_transfer_settings(self, config: dict) -> str: + return self._request("POST", "/v0/BattlegroupUpdateCharacterTransferSettings", data=config, timeout=30) + + def clear_transfer_overrides(self) -> str: + return self._request("POST", "/v0/BattlegroupClearCharacterTransferOverrides", timeout=30) + + def close(self): + self.client.close() + + +class DirectorUnavailableError(Exception): + pass + + +def _parse_battlegroup(data: dict) -> BattlegroupState: + """Parse raw BGD JSON into BattlegroupState model.""" + state = BattlegroupState() + + for key in ["dimensionMaps", "singleServerMaps", "instancedMaps"]: + if key in data: + target = "dimension_maps" if key == "dimensionMaps" else "single_server_maps" if key == "singleServerMaps" else "instanced_maps" + for mg in data[key]: + group = {"name": mg.get("name", ""), "servers": []} + for sv in mg.get("servers", []): + sst = sv.get("lastServerState", {}) + sgs = sst.get("serverGameplaySettings", {}) + server = { + "partition": sv.get("partition", ""), + "ip": sv.get("ip", ""), + "game_port": sv.get("gamePort", 7777), + "num_players": sv.get("numPlayers", 0), + "status": sv.get("status", "unknown"), + "hydration": sgs.get("hydration", 1.0), + "sandstorm": sgs.get("sandstorm", False), + "sandworm": sgs.get("sandworm", True), + "pvp_enabled": sgs.get("pvpEnabled", False), + "mining_multiplier": sgs.get("miningMultiplier", 1.0), + "durability": sgs.get("durability", 1.0), + } + group["servers"].append(server) + getattr(state, target).append(group) + + return state diff --git a/backend/app/services/character.py b/backend/app/services/character.py new file mode 100644 index 0000000..ba882ad --- /dev/null +++ b/backend/app/services/character.py @@ -0,0 +1,50 @@ +# Character service — rename, delete, demo, cheater flags using DB functions. + +import logging + +from app.services.database import DatabaseService + +logger = logging.getLogger(__name__) + + +class CharacterService: + def __init__(self, db: DatabaseService): + self.db = db + + def rename(self, account_id: int, name: str) -> bool: + self.db.call_procedure("set_character_name", [account_id, name]) + return True + + def delete_character(self, actor_id: int) -> bool: + self.db.call_procedure("delete_character", [actor_id]) + return True + + def delete_account(self, user_id: str, reason: str = "admin") -> bool: + self.db.call_procedure("delete_account", [user_id, reason]) + return True + + def set_demo(self, user_id: str, state: str) -> bool: + self.db.call_procedure("set_demo_state", [user_id, state]) + return True + + def flag_cheater(self, account_id: int, cheat_type: str) -> bool: + self.db.call_procedure("flag_player_as_cheater", [account_id, cheat_type]) + return True + + def get_tags(self, account_id: int) -> list[str]: + rows = self.db.call_function("admin_read_player_tags", [account_id]) + return [r.get("tag", "") for r in rows if r.get("tag")] + + def update_tags(self, account_id: int, add: list[str], remove: list[str]) -> bool: + # DB-ONLY direct SQL — no function exists for tag management + for tag in add: + self.db.execute_mutation( + "INSERT INTO dune.player_tags (account_id, tag) VALUES (%s, %s) ON CONFLICT DO NOTHING", + [account_id, tag], + ) + if remove: + self.db.execute_mutation( + "DELETE FROM dune.player_tags WHERE account_id = %s AND tag = ANY(%s)", + [account_id, remove], + ) + return True diff --git a/backend/app/services/chat.py b/backend/app/services/chat.py new file mode 100644 index 0000000..0b7eb07 --- /dev/null +++ b/backend/app/services/chat.py @@ -0,0 +1,148 @@ +# Chat service — chat history and log parsing. + +import json +import logging +from datetime import datetime + +from app.services.database import DatabaseService + +logger = logging.getLogger(__name__) + + +class ChatService: + def __init__(self, db: DatabaseService, k8s_service, ssh_service): + self.db = db + self.k8s = k8s_service + self.ssh = ssh_service + self.ensured_table = False + + def ensure_history_table(self): + if self.ensured_table: + return True + try: + self.db.execute_mutation(""" + CREATE TABLE IF NOT EXISTS dashboard.chat_history ( + id SERIAL PRIMARY KEY, + timestamp TIMESTAMP DEFAULT NOW(), + channel VARCHAR(50), + sender VARCHAR(255), + message TEXT, + target VARCHAR(255), + location_x FLOAT, + location_y FLOAT, + location_z FLOAT, + is_admin BOOLEAN DEFAULT FALSE + ) + """) + self.db.execute_mutation( + "CREATE INDEX IF NOT EXISTS idx_chat_history_timestamp ON dashboard.chat_history (timestamp DESC)" + ) + self.ensured_table = True + logger.info("Chat history table ready") + return True + except Exception as e: + logger.error("Failed to create chat history table: %s", e) + return False + + def save_message(self, channel, sender, message, target="", location=None, is_admin=False): + loc_x = location.get("X", 0) if location else 0 + loc_y = location.get("Y", 0) if location else 0 + loc_z = location.get("Z", 0) if location else 0 + return self.db.execute_mutation( + """INSERT INTO dashboard.chat_history + (channel, sender, message, target, location_x, location_y, location_z, is_admin) + VALUES (%s, %s, %s, %s, %s, %s, %s, %s)""", + [channel, sender, message, target, loc_x, loc_y, loc_z, is_admin], + ) + + def get_history(self, limit: int = 200) -> list[dict]: + return self.db.execute_readonly( + """SELECT id, timestamp, channel, sender, message, target, + location_x, location_y, location_z, is_admin + FROM dashboard.chat_history ORDER BY timestamp DESC LIMIT %s""", + [limit], + ) + + def catch_up(self, namespace: str) -> int: + db_messages = self.get_history(1) + has_history = db_messages and len(db_messages) >= 10 + if has_history: + return 0 + + if not namespace: + logger.warning("Cannot catch up — kubernetes namespace not set") + return 0 + + pod_name = self.k8s.get_text_router_pod() + if not pod_name: + logger.warning("Cannot catch up — no text-router pod found") + return 0 + + log_cmd = f"sudo kubectl logs -n {namespace} {pod_name} --tail=2000 2>/dev/null" + out, err, rc = self.ssh.run(log_cmd, timeout=30) + if rc != 0 or not out: + logger.debug("Cannot catch up — failed to get pod logs (rc=%d)", rc) + return 0 + + lines = [line for line in out.split("\n") if "CLOG" in line and "TextChat" in line] + lines = [line for line in lines if "Starting filtering" not in line] + lines = [line for line in lines if "Skipping filtering" not in line] + lines = [line for line in lines if "Redirected message" not in line] + + messages = [] + seen = set() + for line in lines: + if not line.strip(): + continue + try: + idx = line.index("received message from ") + rest = line[idx + len("received message from "):] + parts = rest.split(" to ", 1) + if len(parts) < 2: + continue + sender_id = parts[0].strip() + target_and_json = parts[1] + target_idx = target_and_json.index(": ") + target = target_and_json[:target_idx].strip() + msg_str = target_and_json[target_idx + 2:].strip() + + msg_data = json.loads(msg_str) + content = json.loads(msg_data.get("content", "{}")) + + dedup_key = ( + content.get("m_ChannelType", ""), + content.get("m_FuncomIdFrom", ""), + content.get("m_Message", {}).get("m_UnlocalizedMessage", ""), + ) + if dedup_key in seen: + continue + seen.add(dedup_key) + + messages.append({ + "channel": content.get("m_ChannelType", "Unknown"), + "sender": content.get("m_FuncomIdFrom", sender_id), + "message": content.get("m_Message", {}).get("m_UnlocalizedMessage", ""), + "target": target, + "location": content.get("m_OriginLocation", {}), + "is_admin": False, + }) + except (ValueError, KeyError, json.JSONDecodeError, IndexError): + continue + + if messages: + saved = self._save_batch(messages) + logger.info("Caught up %d chat messages from pod logs", saved) + return saved + return 0 + + def _save_batch(self, messages: list[dict]) -> int: + if not messages: + return 0 + count = 0 + for msg in messages: + if self.save_message( + msg["channel"], msg["sender"], msg["message"], + msg.get("target", ""), msg.get("location"), msg.get("is_admin", False), + ): + count += 1 + return count diff --git a/backend/app/services/database.py b/backend/app/services/database.py new file mode 100644 index 0000000..ffb9b28 --- /dev/null +++ b/backend/app/services/database.py @@ -0,0 +1,210 @@ +"""Database service — psycopg3 connection pool and stored procedure executor.""" + +import logging +import time +from typing import Any, List + +import psycopg +from psycopg.rows import dict_row +from psycopg_pool import ConnectionPool + +logger = logging.getLogger(__name__) + + +class DatabaseService: + def __init__(self, db_config, min_conn=2, max_conn=10, dashboard_schema="dashboard"): + self.db_config = db_config + self.min_conn = min_conn + self.max_conn = max_conn + self.dashboard_schema = dashboard_schema + self.pool = None + + def init_pool(self): + if self.pool is not None: + return self.pool + + conninfo = ( + f"host={self.db_config['host']} " + f"port={self.db_config['port']} " + f"dbname={self.db_config['database']} " + f"user={self.db_config['user']} " + f"password={self.db_config['password']}" + ) + + for attempt in range(10): + try: + self.pool = ConnectionPool( + conninfo=conninfo, + min_size=self.min_conn, + max_size=self.max_conn, + open=False, + ) + self.pool.open(wait=True, timeout=20) + logger.info("Database connection pool initialized (psycopg3)") + return self.pool + except Exception as e: + if attempt < 9: + logger.warning(f"DB pool attempt {attempt + 1}/10 failed, retrying in 2s: {e}") + time.sleep(2) + else: + logger.error(f"Failed to initialize database pool after 10 attempts: {e}") + self.pool = None + return self.pool + + def call_function(self, name: str, args: List[Any]) -> List[dict]: + """Call a dune schema function and return rows as dicts.""" + pool = self.init_pool() + if not pool: + raise ConnectionError("Database pool not available") + + placeholders = ",".join(["%s"] * len(args)) + sql = f"SELECT * FROM dune.{name}({placeholders})" + + with pool.connection() as conn: + with conn.cursor(row_factory=dict_row) as cur: + cur.execute(sql, args) + rows = cur.fetchall() + return rows if rows else [] + + def call_procedure(self, name: str, args: List[Any]) -> None: + """Call a dune schema procedure (void return).""" + pool = self.init_pool() + if not pool: + raise ConnectionError("Database pool not available") + + placeholders = ",".join(["%s"] * len(args)) + sql = f"CALL dune.{name}({placeholders})" + + with pool.connection() as conn: + with conn.cursor() as cur: + cur.execute(sql, args) + conn.commit() + + def execute_readonly(self, sql: str, params: List[Any] | None = None) -> List[dict]: + """Execute a read-only SELECT query.""" + pool = self.init_pool() + if not pool: + raise ConnectionError("Database pool not available") + + with pool.connection() as conn: + with conn.cursor(row_factory=dict_row) as cur: + cur.execute(sql, params or []) + rows = cur.fetchall() + return rows if rows else [] + + def execute_mutation(self, sql: str, params: List[Any] | None = None) -> int: + """Execute a direct mutation (UPDATE/INSERT/DELETE) with validation.""" + pool = self.init_pool() + if not pool: + raise ConnectionError("Database pool not available") + + with pool.connection() as conn: + with conn.cursor() as cur: + cur.execute(sql, params or []) + conn.commit() + return cur.rowcount + + def health_check(self) -> bool: + try: + pool = self.init_pool() + if not pool: + return False + with pool.connection() as conn: + with conn.cursor() as cur: + cur.execute("SELECT 1") + cur.fetchone() + return True + except Exception as e: + logger.warning(f"Database health check FAILED: {e}") + return False + + def ensure_tables(self): + """Ensure dashboard schema tables exist.""" + pool = self.init_pool() + if not pool: + return + + schema = self.dashboard_schema + ddl = f""" + CREATE SCHEMA IF NOT EXISTS {schema}; + + CREATE TABLE IF NOT EXISTS {schema}.audit_log ( + id BIGSERIAL PRIMARY KEY, + action_type VARCHAR(50) NOT NULL, + user_name VARCHAR(100) NOT NULL, + target_player_id BIGINT, + details JSONB DEFAULT '{{}}', + source_ip INET, + severity VARCHAR(20) DEFAULT 'info', + created_at TIMESTAMP NOT NULL DEFAULT NOW() + ); + + CREATE INDEX IF NOT EXISTS idx_audit_created_at ON {schema}.audit_log (created_at DESC); + CREATE INDEX IF NOT EXISTS idx_audit_action ON {schema}.audit_log (action_type); + CREATE INDEX IF NOT EXISTS idx_audit_user ON {schema}.audit_log (user_name); + + CREATE TABLE IF NOT EXISTS {schema}.player_ips ( + player_id BIGINT PRIMARY KEY, + ip_address INET NOT NULL, + updated_at TIMESTAMP NOT NULL DEFAULT NOW() + ); + + CREATE TABLE IF NOT EXISTS {schema}.bans ( + id SERIAL PRIMARY KEY, + player_id BIGINT UNIQUE, + account_id BIGINT, + reason TEXT DEFAULT '', + note TEXT DEFAULT '', + duration INT DEFAULT 0, + banned_at TIMESTAMP NOT NULL DEFAULT NOW(), + expires_at TIMESTAMP, + active BOOLEAN DEFAULT TRUE + ); + + CREATE TABLE IF NOT EXISTS {schema}.player_actions ( + id SERIAL PRIMARY KEY, + player_id BIGINT NOT NULL, + action_type VARCHAR(50) NOT NULL, + reason TEXT DEFAULT '', + note TEXT DEFAULT '', + duration_minutes INT DEFAULT 0, + ip_address INET, + created_at TIMESTAMP NOT NULL DEFAULT NOW() + ); + + CREATE TABLE IF NOT EXISTS {schema}.chat_history ( + id SERIAL PRIMARY KEY, + timestamp TIMESTAMP DEFAULT NOW(), + channel VARCHAR(50), + sender VARCHAR(255), + message TEXT, + target VARCHAR(255), + location_x FLOAT, + location_y FLOAT, + location_z FLOAT, + is_admin BOOLEAN DEFAULT FALSE + ); + + CREATE INDEX IF NOT EXISTS idx_chat_history_timestamp ON {schema}.chat_history (timestamp DESC); + + CREATE TABLE IF NOT EXISTS {schema}.settings ( + key VARCHAR(255) PRIMARY KEY, + value TEXT DEFAULT '', + updated_at TIMESTAMP DEFAULT NOW() + ); + """ + + with pool.connection() as conn: + with conn.cursor() as cur: + cur.execute(ddl) + conn.commit() + logger.info(f"Dashboard tables ensured in schema '{schema}'") + + def close(self): + if self.pool: + try: + self.pool.close() + logger.info("Database pool closed") + except Exception as e: + logger.error(f"Error closing pool: {e}") + self.pool = None diff --git a/backend/app/services/economy.py b/backend/app/services/economy.py new file mode 100644 index 0000000..d29c06e --- /dev/null +++ b/backend/app/services/economy.py @@ -0,0 +1,182 @@ +# Economy service — items, currency, vitals, vendors. + +import logging +from typing import Any + +from app.models import Inventory, Item, CurrencyBalance, Vitals +from app.services.database import DatabaseService + +logger = logging.getLogger(__name__) + +ALLOWED_ITEM_FIELDS = {"stack_size", "quality_level", "is_new", "durability", "max_durability", "ammo"} + + +class EconomyService: + def __init__(self, db: DatabaseService): + self.db = db + + # ── Inventory ───────────────────────────────────────────────── + + def get_inventory(self, account_id: int) -> list[Inventory]: + return PlayerService(self.db)._get_inventory(account_id) + + def add_item(self, inventory_id: int, template_id: str, stack_size: int = 1, quality_level: int = 0) -> int: + rows = self.db.call_function("add_item", [inventory_id, template_id, stack_size, quality_level]) + if rows and rows[0].get("id"): + return rows[0]["id"] + raise ValueError("Item add failed: no ID returned") + + def delete_item(self, item_id: int) -> bool: + self.db.call_procedure("delete_item", [item_id]) + return True + + def delete_inventory_item(self, item_id: int, count: int) -> bool: + self.db.call_procedure("delete_inventory_item", [item_id, count]) + return True + + # ── Item Editing (DB-ONLY direct UPDATE — validated) ────────── + + def edit_item_field(self, item_id: int, field: str, value: Any) -> bool: + if field not in ALLOWED_ITEM_FIELDS: + raise ValueError(f"Invalid field. Allowed: {', '.join(sorted(ALLOWED_ITEM_FIELDS))}") + + if field == "is_new": + self.db.execute_mutation( + "UPDATE dune.items SET is_new = %s WHERE id = %s", + [bool(value), item_id], + ) + elif field in ("durability", "max_durability", "ammo"): + stats_path = { + "durability": "{FItemStackAndDurabilityStats,CurrentDurability}", + "max_durability": "{FItemStackAndDurabilityStats,DecayedMaxDurability}", + "ammo": "{FWeaponItemStats,CurrentAmmo}", + }[field] + self.db.execute_mutation( + "UPDATE dune.items SET stats = jsonb_set(stats, %s, to_jsonb(%s::text), true) WHERE id = %s", + [stats_path.split(","), str(value), item_id], + ) + else: + self.db.execute_mutation( + f"UPDATE dune.items SET {field} = %s WHERE id = %s", + [int(value), item_id], + ) + return True + + # ── Currency ────────────────────────────────────────────────── + + def get_currency(self, controller_id: int) -> list[CurrencyBalance]: + rows = self.db.call_function("get_player_virtual_currency_balances", [controller_id]) + labels = {0: "Solari Credits", 1: "House Script", 2: "Spice"} + return [CurrencyBalance( + currency_id=r["currency_id"], + currency_label=labels.get(r["currency_id"], f"Currency {r['currency_id']}"), + balance=r.get("balance", 0), + ) for r in rows] + + def adjust_currency(self, controller_id: int, currency_id: int, delta: int) -> int: + rows = self.db.call_function("adjust_player_virtual_currency_balance", [controller_id, currency_id, delta]) + if rows and len(rows) > 0: + return rows[0].get("balance", 0) + raise ValueError("Currency adjustment failed") + + def set_currency(self, controller_id: int, currency_id: int, balance: int) -> bool: + # DB-ONLY direct UPSERT — validated + if balance < 0: + raise ValueError("Balance cannot be negative") + self.db.execute_mutation( + """INSERT INTO dune.player_virtual_currency_balances (player_controller_id, currency_id, balance) + VALUES (%s, %s, %s) + ON CONFLICT (player_controller_id, currency_id) DO UPDATE SET balance = EXCLUDED.balance""", + [controller_id, currency_id, balance], + ) + return True + + # ── Vitals (DB-ONLY direct UPDATE — validated + offline check) ─ + + def get_vitals(self, pawn_id: int) -> Vitals: + rows = self.db.call_function("admin_get_character_details", [pawn_id]) + if not rows: + return Vitals() + # Character details returns by account_id, but we need pawn data + # Fallback to actors query for vitals + actor_rows = self.db.execute_readonly( + """SELECT properties, gas_attributes FROM dune.actors WHERE id = %s""", + [pawn_id], + ) + if not actor_rows: + return Vitals() + row = actor_rows[0] + props = row.get("properties") or {} + gas = row.get("gas_attributes") or {} + dmg = props.get("DamageableActorComponent") or {} + hyd = gas.get("DuneHydrationAttributeSet") or {} + spc = gas.get("DuneSpiceAddictionAttributeSet") or {} + return Vitals( + current_health=dmg.get("m_CurrentMaxHealth"), + max_health=dmg.get("m_TotalMaxHealth"), + current_hydration=(hyd.get("CurrentHydration") or {}).get("CurrentValue"), + dehydration_penalty=(hyd.get("DehydrationPenalty") or {}).get("CurrentValue"), + current_spice=(spc.get("CurrentSpice") or {}).get("CurrentValue"), + spice_addiction_level=(spc.get("SpiceAddictionLevel") or {}).get("CurrentValue"), + spice_tolerance=(spc.get("SpiceTolerance") or {}).get("CurrentValue"), + ) + + def set_vitals(self, pawn_id: int, health: float | None, max_health: float | None, + hydration: float, spice: float) -> bool: + # DB-ONLY: Validate player is offline + offline_check = self.db.execute_readonly( + """SELECT 1 FROM dune.player_state + WHERE player_pawn_id = %s AND online_status::text = 'Online'""", + [pawn_id], + ) + if offline_check: + raise ValueError("Player must be offline to edit vitals") + + if health is not None and health < 0: + raise ValueError("Health cannot be negative") + if max_health is not None and max_health < 0: + raise ValueError("Max health cannot be negative") + if hydration < 0: + raise ValueError("Hydration cannot be negative") + if spice < 0: + raise ValueError("Spice cannot be negative") + + if health is not None: + self.db.execute_mutation( + """UPDATE dune.actors SET properties = jsonb_set( + properties, '{DamageableActorComponent,m_CurrentMaxHealth}', to_jsonb(%s::float) + ) WHERE id = %s""", + [health, pawn_id], + ) + if max_health is not None: + self.db.execute_mutation( + """UPDATE dune.actors SET properties = jsonb_set( + properties, '{DamageableActorComponent,m_TotalMaxHealth}', to_jsonb(%s::float) + ) WHERE id = %s""", + [max_health, pawn_id], + ) + + self.db.execute_mutation( + """UPDATE dune.actors SET gas_attributes = jsonb_set( + jsonb_set(jsonb_set(jsonb_set(gas_attributes, + '{DuneHydrationAttributeSet,CurrentHydration,CurrentValue}', to_jsonb(%s::float)), + '{DuneHydrationAttributeSet,CurrentHydration,BaseValue}', to_jsonb(%s::float)), + '{DuneSpiceAddictionAttributeSet,CurrentSpice,CurrentValue}', to_jsonb(%s::float)), + '{DuneSpiceAddictionAttributeSet,CurrentSpice,BaseValue}', to_jsonb(%s::float) + ) WHERE id = %s""", + [hydration, hydration, spice, spice, pawn_id], + ) + return True + + # ── Vendors ─────────────────────────────────────────────────── + + def clean_vendor_stock(self, player_id: int) -> bool: + self.db.call_procedure("clean_stock_for_player", [player_id]) + return True + + def get_tax_invoices(self, player_id: int) -> list[dict]: + return self.db.call_function("taxation_get_all_invoices_for_player", [player_id]) + + +# Import here to avoid circular dependency at module load time +from app.services.player import PlayerService diff --git a/backend/app/services/guild.py b/backend/app/services/guild.py new file mode 100644 index 0000000..6cda352 --- /dev/null +++ b/backend/app/services/guild.py @@ -0,0 +1,64 @@ +# Guild service — guild operations using DB functions only. + +import logging + +from app.models import GuildDetail, GuildMember, GuildSummary +from app.services.database import DatabaseService + +logger = logging.getLogger(__name__) + +GUILD_ROLES = {100: "Leader", 90: "Officer", 80: "Officer", 50: "Member", 1: "Member"} + + +class GuildService: + def __init__(self, db: DatabaseService): + self.db = db + + def list_all(self) -> list[GuildSummary]: + rows = self.db.call_function("get_all_guilds", []) + return [GuildSummary( + guild_id=r.get("guild_id", 0), + guild_name=r.get("guild_name", ""), + guild_description=r.get("guild_description"), + faction_name=r.get("faction_name"), + member_count=r.get("member_count", 0), + online_count=0, # requires additional query if needed + ) for r in rows] + + def get_detail(self, guild_id: int) -> GuildDetail | None: + guild_rows = self.db.call_function("get_guild_data", [guild_id]) + if not guild_rows: + return None + g = guild_rows[0] + member_rows = self.db.call_function("get_guild_members", [guild_id]) + members = [GuildMember( + player_id=r.get("player_id", 0), + role_id=r.get("role_id", 50), + role_name=GUILD_ROLES.get(r.get("role_id", 50), f"Role {r.get('role_id', 50)}"), + player_name=r.get("name", "Unknown"), + online_status=r.get("online_status", "Unknown"), + ) for r in member_rows] + return GuildDetail( + guild_id=g.get("guild_id", guild_id), + guild_name=g.get("guild_name", ""), + guild_description=g.get("guild_description"), + faction_name=g.get("faction_name"), + faction_id=g.get("guild_faction"), + members=members, + ) + + def disband(self, guild_id: int) -> bool: + self.db.call_procedure("disband_guild", [guild_id]) + return True + + def remove_member(self, guild_id: int, player_id: int, reason: int = 0) -> bool: + self.db.call_procedure("remove_guild_members", [[player_id], guild_id, reason]) + return True + + def promote(self, guild_id: int, player_id: int, role_id: int) -> bool: + self.db.call_procedure("promote_guild_member", [guild_id, player_id, role_id]) + return True + + def demote(self, guild_id: int, player_id: int, role_id: int) -> bool: + self.db.call_procedure("demote_guild_member", [guild_id, player_id, role_id]) + return True diff --git a/backend/app/services/k8s.py b/backend/app/services/k8s.py new file mode 100644 index 0000000..6867cb0 --- /dev/null +++ b/backend/app/services/k8s.py @@ -0,0 +1,142 @@ +"""Kubernetes service — kubectl operations via SSH.""" + +import logging + +logger = logging.getLogger(__name__) + + +class K8sService: + def __init__(self, ssh_service, namespace): + self.ssh = ssh_service + self.namespace = namespace + + def run(self, kubectl_command, timeout=30): + full_cmd = f"sudo kubectl {kubectl_command} -n {self.namespace}" + logger.debug("K8s executing: %s", full_cmd) + result = self.ssh.run(full_cmd, timeout=timeout) + out, err, rc = result + if rc != 0: + logger.debug("K8s command failed (rc=%d): %s", rc, err[:100] if err else "no error") + else: + logger.debug("K8s command OK, output lines: %d", len(out.split("\n")) if out else 0) + return result + + def get_pods(self): + out, err, rc = self.run("get pods -o json") + if rc != 0: + logger.error("Failed to get pods: %s", err) + return [] + try: + import json + data = json.loads(out or "{}") + items = data.get("items", []) + pods = [] + for item in items: + metadata = item.get("metadata", {}) + status = item.get("status", {}) + container_statuses = status.get("containerStatuses", []) + restarts = sum(c.get("restartCount", 0) for c in container_statuses) + pods.append({ + "name": metadata.get("name", ""), + "namespace": metadata.get("namespace", self.namespace), + "status": status.get("phase", "Unknown"), + "restarts": restarts, + "age": self._age_from_creation(metadata.get("creationTimestamp")), + }) + logger.debug("Found %d pods in namespace %s", len(pods), self.namespace) + return pods + except Exception as e: + logger.error("Failed to parse pods: %s", e) + return [] + + def find_pod_by_pattern(self, pattern): + pods = self.get_pods() + for pod in pods: + if pattern.lower() in pod.lower(): + return pod + return None + + def get_text_router_pod(self): + pod = self.find_pod_by_pattern("tr-deploy") + if pod: + return pod + pod = self.find_pod_by_pattern("text") + if pod: + return pod + return self.find_pod_by_pattern("router") + + def get_rabbitmq_pod(self, admin=True): + if admin: + return self.find_pod_by_pattern("mq-admin") + return self.find_pod_by_pattern("mq-game") + + def get_filebrowser_pod(self): + return self.find_pod_by_pattern("fb-deploy") + + def get_deployments(self): + out, err, rc = self.run("get deployments -o json") + if rc != 0: + return [] + try: + import json + data = json.loads(out or "{}") + items = data.get("items", []) + deployments = [] + for item in items: + metadata = item.get("metadata", {}) + spec = item.get("spec", {}) + status = item.get("status", {}) + deployments.append({ + "name": metadata.get("name", ""), + "namespace": metadata.get("namespace", self.namespace), + "replicas": spec.get("replicas", 0), + "available": status.get("availableReplicas", 0), + }) + return deployments + except Exception as e: + logger.error("Failed to parse deployments: %s", e) + return [] + + def get_node_metrics(self): + out, err, rc = self.run("top nodes") + if rc == 0 and out.strip(): + lines = out.strip().split("\n") + if len(lines) >= 2: + parts = lines[1].split() + if len(parts) >= 4: + return { + "cpu": parts[2], + "memory": parts[3], + "cpu_pct": parts[1], + } + return {} + + @staticmethod + def _age_from_creation(timestamp: str | None) -> str: + if not timestamp: + return "Unknown" + from datetime import datetime, timezone + try: + created = datetime.fromisoformat(timestamp.replace("Z", "+00:00")) + delta = datetime.now(timezone.utc) - created + days = delta.days + hours = delta.seconds // 3600 + minutes = (delta.seconds % 3600) // 60 + if days > 0: + return f"{days}d" + if hours > 0: + return f"{hours}h" + return f"{minutes}m" + except Exception: + return "Unknown" + + def auto_detect_namespace(self): + out, err, rc = self.ssh.run("sudo kubectl get namespaces -o name", timeout=10) + if rc == 0: + for line in (out or "").strip().split("\n"): + ns = line.replace("namespace/", "").strip() + if ns.startswith("funcom-seabass-"): + logger.info("Auto-detected K8s namespace: %s", ns) + self.namespace = ns + return ns + return None diff --git a/backend/app/services/player.py b/backend/app/services/player.py new file mode 100644 index 0000000..963533c --- /dev/null +++ b/backend/app/services/player.py @@ -0,0 +1,269 @@ +# Player service — player queries using DB functions only. + +import logging +from typing import List + +from app.models import PlayerDetail, PlayerSummary, Vitals, Inventory, Item +from app.models import CurrencyBalance, SpecializationTrack, Keystone +from app.models import FactionReputation, LandsraadInfo +from app.models import VehicleSummary, BuildingSummary, Landclaim +from app.services.database import DatabaseService + +logger = logging.getLogger(__name__) + + +class PlayerService: + def __init__(self, db: DatabaseService): + self.db = db + + # ── Search & List ───────────────────────────────────────────── + + def search(self, term: str, limit: int = 50) -> list[PlayerSummary]: + rows = self.db.call_function("admin_get_character_ids", [f"%{term}%"]) + if not rows: + return [] + + account_ids = [r.get("id") for r in rows if r.get("id")] + if not account_ids: + return [] + + return self._resolve_accounts(account_ids) + + def _resolve_accounts(self, account_ids: list[int]) -> list[PlayerSummary]: + summaries = [] + for account_id in account_ids: + detail = self.db.call_function("admin_get_character_details", [account_id]) + if detail: + row = detail[0] + summaries.append(PlayerSummary( + player_controller_id=row.get("player_controller_id"), + character_name=row.get("character_name") or "Unknown", + account_email=row.get("account_email"), + funcom_id=row.get("funcom_id"), + faction_name=row.get("faction_name"), + faction_id=row.get("faction_id"), + map=row.get("map"), + online_status=row.get("online_status") or "Unknown", + life_state=row.get("life_state"), + last_login_time=row.get("last_login_time"), + last_avatar_activity=row.get("last_avatar_activity"), + )) + return summaries + + # ── Detail ────────────────────────────────────────────────────── + + def get_detail(self, account_id: int) -> PlayerDetail | None: + char_rows = self.db.call_function("admin_get_character_details", [account_id]) + if not char_rows: + return None + row = char_rows[0] + + controller_id = row.get("player_controller_id") + pawn_id = row.get("player_pawn_id") + + vitals = self._extract_vitals(row) + currency = self._get_currency(controller_id) + inventories = self._get_inventory(account_id) + vehicles = self._get_vehicles(controller_id, account_id) + buildings = self._get_buildings(pawn_id) + landclaims = self._get_landclaims(account_id) + spec = self._get_specialization(controller_id) + keystones = self._get_keystones(controller_id) + faction_rep = self._get_faction_reputation(controller_id) + landsraad = self._get_landsraad(controller_id) + tags = self._get_tags(account_id) + is_online = self._check_online(controller_id) + + return PlayerDetail( + id=row.get("id"), + account_id=account_id, + player_controller_id=controller_id, + player_pawn_id=pawn_id, + character_name=row.get("character_name") or "Unknown", + account_email=row.get("account_email"), + funcom_id=row.get("funcom_id"), + faction_name=row.get("faction_name"), + faction_id=row.get("faction_id"), + map=row.get("map"), + online_status=row.get("online_status") or "Unknown", + life_state=row.get("life_state"), + last_login_time=row.get("last_login_time"), + last_avatar_activity=row.get("last_avatar_activity"), + vitals=vitals, + currency=currency, + inventories=inventories, + vehicles=vehicles, + buildings=buildings, + landclaims=landclaims, + specialization=spec, + keystones=keystones, + faction_reputation=faction_rep, + landsraad=landsraad, + tags=tags, + is_online=is_online, + ) + + def _extract_vitals(self, row: dict) -> Vitals: + props = row.get("properties") or {} + gas = row.get("gas_attributes") or {} + dmg = props.get("DamageableActorComponent") or {} + hyd = gas.get("DuneHydrationAttributeSet") or {} + spc = gas.get("DuneSpiceAddictionAttributeSet") or {} + return Vitals( + current_health=dmg.get("m_CurrentMaxHealth"), + max_health=dmg.get("m_TotalMaxHealth"), + current_hydration=(hyd.get("CurrentHydration") or {}).get("CurrentValue"), + dehydration_penalty=(hyd.get("DehydrationPenalty") or {}).get("CurrentValue"), + current_spice=(spc.get("CurrentSpice") or {}).get("CurrentValue"), + spice_addiction_level=(spc.get("SpiceAddictionLevel") or {}).get("CurrentValue"), + spice_tolerance=(spc.get("SpiceTolerance") or {}).get("CurrentValue"), + ) + + def _get_currency(self, controller_id: int | None) -> list[CurrencyBalance]: + if not controller_id: + return [] + rows = self.db.call_function("get_player_virtual_currency_balances", [controller_id]) + labels = {0: "Solari Credits", 1: "House Script", 2: "Spice"} + return [CurrencyBalance( + currency_id=r["currency_id"], + currency_label=labels.get(r["currency_id"], f"Currency {r['currency_id']}"), + balance=r.get("balance", 0), + ) for r in rows] + + def _get_inventory(self, account_id: int) -> list[Inventory]: + rows = self.db.call_function("admin_get_inventory_details", [account_id]) + if not rows: + return [] + + from app.utils.constants import INVENTORY_TYPE_LABELS + inventories = {} + for r in rows: + inv_id = r.get("inventory_id") + if inv_id not in inventories: + inv_type = r.get("inventory_type", 0) + inventories[inv_id] = Inventory( + inventory_id=inv_id, + actor_id=r.get("actor_id"), + inventory_type=inv_type, + inventory_type_label=INVENTORY_TYPE_LABELS.get(inv_type, f"Type {inv_type}"), + max_item_count=r.get("max_item_count"), + max_item_volume=r.get("max_item_volume"), + items=[], + ) + stats = r.get("stats") or {} + dur = stats.get("FItemStackAndDurabilityStats") or {} + wpn = stats.get("FWeaponItemStats") or {} + inventories[inv_id].items.append(Item( + id=r.get("item_id"), + template_id=r.get("template_id", ""), + stack_size=r.get("count", 1), + quality_level=r.get("quality_level", 0), + is_new=r.get("is_new", False), + position_index=r.get("position_index", 0), + stats=stats, + durability=dur.get("CurrentDurability") if isinstance(dur, dict) else None, + max_durability=dur.get("DecayedMaxDurability") if isinstance(dur, dict) else None, + ammo=wpn.get("CurrentAmmo") if isinstance(wpn, dict) else None, + )) + return list(inventories.values()) + + def _get_vehicles(self, controller_id: int | None, account_id: int) -> list[VehicleSummary]: + if not controller_id: + return [] + rows = self.db.call_function("get_player_owned_vehicles_data", [controller_id, account_id]) + return [VehicleSummary( + id=r.get("vehicle_id"), + class_name=r.get("class", ""), + display_name=self._vehicle_display_name(r.get("class", "")), + map=r.get("map"), + ) for r in rows] + + def _get_buildings(self, player_id: int | None) -> list[BuildingSummary]: + if not player_id: + return [] + # DB-READ: no function for buildings-by-owner + rows = self.db.execute_readonly( + """SELECT a.id, a.class, a.map, a.properties->>'m_bIsPowered' as is_powered, + a.properties->>'m_PowerLevel' as power_level + FROM dune.buildings b JOIN dune.actors a ON b.id = a.id + WHERE b.owner_id = %s ORDER BY a.map""", + [player_id], + ) + return [BuildingSummary( + id=r["id"], + class_name=r["class"], + map=r["map"], + owner_name="", # known from context + instance_count=0, + is_powered=r.get("is_powered") == "True", + power_level=r.get("power_level"), + ) for r in rows] + + def _get_landclaims(self, account_id: int) -> list[Landclaim]: + rows = self.db.execute_readonly( + """SELECT DISTINCT a.id, a.class, a.map + FROM dune.landclaim_segments lcs + JOIN dune.actors a ON lcs.totem_id = a.id + WHERE a.owner_account_id = %s""", + [account_id], + ) + return [Landclaim(id=r["id"], class_name=r["class"], map=r["map"]) for r in rows] + + def _get_specialization(self, controller_id: int | None) -> list[SpecializationTrack]: + if not controller_id: + return [] + rows = self.db.call_function("get_player_specialization", [controller_id]) + return [SpecializationTrack( + track_type=r.get("track_type", ""), + xp_amount=r.get("xp_amount", 0), + level=r.get("level", 0), + ) for r in rows] + + def _get_keystones(self, controller_id: int | None) -> list[Keystone]: + if not controller_id: + return [] + rows = self.db.call_function("get_player_keystones", [controller_id]) + return [Keystone(id=r.get("id", 0), name=r.get("name", "")) for r in rows] + + def _get_faction_reputation(self, controller_id: int | None) -> list[FactionReputation]: + if not controller_id: + return [] + rows = self.db.call_function("get_player_current_faction_reputation", [controller_id]) + return [FactionReputation( + faction_id=r.get("out_faction_id"), + faction_name="", # resolved later if needed + reputation_amount=r.get("out_reputation_amount", 0), + ) for r in rows] + + def _get_landsraad(self, controller_id: int | None) -> LandsraadInfo: + if not controller_id: + return LandsraadInfo() + rows = self.db.call_function("get_player_landsraad", [controller_id]) + if rows: + r = rows[0] + return LandsraadInfo( + daily_reward_charges=r.get("daily_reward_charges"), + last_viewed_term_id=r.get("last_viewed_term_id"), + daily_reward_last_processed=r.get("daily_reward_last_processed"), + ) + return LandsraadInfo() + + def _get_tags(self, account_id: int) -> list[str]: + rows = self.db.call_function("admin_read_player_tags", [account_id]) + return [r.get("tag", "") for r in rows if r.get("tag")] + + def _check_online(self, controller_id: int | None) -> bool: + if not controller_id: + return False + rows = self.db.call_function("get_player_ids_online_state", [[controller_id]]) + return bool(rows) + + # ── Utilities ───────────────────────────────────────────────── + + @staticmethod + def _vehicle_display_name(cls: str) -> str: + if "/" in cls: + short = cls.split("/")[-1].replace("_C", "") + else: + short = cls.replace("_C", "") + return short.replace("BP_", "").replace("_CHOAM", "").replace("_", " ") diff --git a/backend/app/services/progression.py b/backend/app/services/progression.py new file mode 100644 index 0000000..36a478c --- /dev/null +++ b/backend/app/services/progression.py @@ -0,0 +1,32 @@ +# Progression service — journey and specialization using DB functions. + +import logging + +from app.services.database import DatabaseService + +logger = logging.getLogger(__name__) + + +class ProgressionService: + def __init__(self, db: DatabaseService): + self.db = db + + def complete_nodes(self, player_id: str, node_ids: list[str]) -> bool: + self.db.call_procedure("complete_journey_story_nodes_for_player", [player_id, node_ids]) + return True + + def reveal_nodes(self, player_id: str, node_ids: list[str]) -> bool: + self.db.call_procedure("reveal_journey_story_nodes_for_player", [player_id, node_ids]) + return True + + def reset_nodes(self, player_id: str, node_ids: list[str]) -> bool: + self.db.call_procedure("delete_journey_story_nodes_for_player", [player_id, node_ids]) + return True + + def set_specialization(self, player_id: int, track_type: str, xp: int, level: float) -> bool: + self.db.call_procedure("set_specialization_xp_and_level", [player_id, track_type, xp, level]) + return True + + def reset_specializations(self, player_id: int) -> bool: + self.db.call_procedure("reset_specialization_tracks", [player_id]) + return True diff --git a/backend/app/services/realtime.py b/backend/app/services/realtime.py new file mode 100644 index 0000000..2dcfb07 --- /dev/null +++ b/backend/app/services/realtime.py @@ -0,0 +1,164 @@ +"""Realtime service — SSE broadcaster + BGD/RMQ poller.""" + +import asyncio +import json +import logging +import threading +import time +from typing import Any, Callable, Dict, Set + +logger = logging.getLogger(__name__) + + +class SseClient: + """Simple wrapper for an SSE client connection.""" + def __init__(self, queue: asyncio.Queue): + self.queue = queue + self.connected_at = time.time() + + +class RealtimeService: + def __init__(self, bg_director, rmq_admin, chat_service): + self.bg_director = bg_director + self.rmq_admin = rmq_admin + self.chat_service = chat_service + self._clients: Set[asyncio.Queue] = set() + self._lock = threading.Lock() + self._previous_bg: dict | None = None + self._running = False + self._bgd_task = None + self._rmq_task = None + + # ── Client Management ───────────────────────────────────────── + + def add_client(self, queue: asyncio.Queue): + with self._lock: + self._clients.add(queue) + logger.debug("SSE client added. Total: %d", len(self._clients)) + + def remove_client(self, queue: asyncio.Queue): + with self._lock: + self._clients.discard(queue) + logger.debug("SSE client removed. Total: %d", len(self._clients)) + + async def _broadcast(self, event: str, data: dict): + """Broadcast an event to all connected SSE clients.""" + payload = f"event: {event}\ndata: {json.dumps(data)}\n\n" + with self._lock: + dead = set() + for queue in self._clients: + try: + queue.put_nowait(payload) + except asyncio.QueueFull: + dead.add(queue) + except Exception: + dead.add(queue) + self._clients -= dead + + # ── Background Polling ────────────────────────────────────── + + def start(self): + if self._running: + return + self._running = True + self._bgd_task = threading.Thread(target=self._bgd_poll_loop, daemon=True) + self._bgd_task.start() + self._rmq_task = threading.Thread(target=self._rmq_poll_loop, daemon=True) + self._rmq_task.start() + logger.info("RealtimeService started") + + def stop(self): + self._running = False + logger.info("RealtimeService stopped") + + def _bgd_poll_loop(self): + """Poll BGD every 10 seconds and broadcast deltas.""" + while self._running: + try: + bg = self.bg_director.get_battlegroup() + current = bg.model_dump() if hasattr(bg, "model_dump") else bg.__dict__ + delta = self._compute_bg_delta(self._previous_bg, current) + if delta: + asyncio.run(self._broadcast("battlegroup_update", delta)) + self._previous_bg = current + except Exception as e: + logger.warning("BGD poll failed: %s", e) + asyncio.run(self._broadcast("connection_status", {"bgd": False})) + time.sleep(10) + + def _rmq_poll_loop(self): + """Poll RMQ every 30 seconds and broadcast health.""" + while self._running: + try: + overview = self.rmq_admin.get_overview() + data = { + "cluster_name": overview.cluster_name, + "queue_totals": overview.queue_totals, + "message_stats": overview.message_stats, + } + asyncio.run(self._broadcast("rmq_health", data)) + except Exception as e: + logger.warning("RMQ poll failed: %s", e) + asyncio.run(self._broadcast("connection_status", {"rmq": False})) + time.sleep(30) + + def _compute_bg_delta(self, previous: dict | None, current: dict) -> dict | None: + """Compute meaningful deltas between battlegroup states.""" + if not previous: + return { + "online_count": self._count_online(current), + "intransit_count": len(current.get("intransit_players", [])), + "server_statuses": self._extract_server_statuses(current), + "map_counts": self._extract_map_counts(current), + } + + prev_online = self._count_online(previous) + curr_online = self._count_online(current) + prev_statuses = self._extract_server_statuses(previous) + curr_statuses = self._extract_server_statuses(current) + + delta = {} + if curr_online != prev_online: + delta["online_count"] = curr_online + if len(current.get("intransit_players", [])) != len(previous.get("intransit_players", [])): + delta["intransit_count"] = len(current.get("intransit_players", [])) + if curr_statuses != prev_statuses: + delta["server_statuses"] = curr_statuses + + return delta if delta else None + + def _count_online(self, state: dict) -> int: + return len(state.get("online_players", [])) + + def _extract_server_statuses(self, state: dict) -> dict: + statuses = {} + for key in ["dimension_maps", "single_server_maps", "instanced_maps"]: + for mg in state.get(key, []): + for sv in mg.get("servers", []): + partition = sv.get("partition", "") + if partition: + statuses[partition] = sv.get("status", "unknown") + return statuses + + def _extract_map_counts(self, state: dict) -> dict: + counts = {} + for key in ["dimension_maps", "single_server_maps", "instanced_maps"]: + for mg in state.get(key, []): + name = mg.get("name", "") + if name: + counts[name] = sum(sv.get("num_players", 0) for sv in mg.get("servers", [])) + return counts + + # ── Event Helpers ─────────────────────────────────────────── + + async def notify_chat_message(self, msg: dict): + await self._broadcast("chat_message", msg) + + async def notify_server_event(self, event: dict): + await self._broadcast("server_event", event) + + async def notify_player_event(self, event: dict): + await self._broadcast("player_event", event) + + async def notify_connection_status(self, status: dict): + await self._broadcast("connection_status", status) diff --git a/backend/app/services/rmq_admin.py b/backend/app/services/rmq_admin.py new file mode 100644 index 0000000..bd256ae --- /dev/null +++ b/backend/app/services/rmq_admin.py @@ -0,0 +1,146 @@ +"""RabbitMQ Admin Management HTTP API client.""" + +import json +import logging +from typing import Any, Dict, List + +import httpx + +from app.models import RmqOverview, RmqQueueInfo + +logger = logging.getLogger(__name__) + + +class RmqAdminService: + def __init__(self, host: str, port: int, username: str, password: str): + self.base_url = f"http://{host}:{port}" + self.auth = (username, password) + self.client = httpx.Client(base_url=self.base_url, auth=self.auth, timeout=15) + logger.debug("RmqAdminService initialized: %s", self.base_url) + + def _get(self, path: str) -> dict | list: + try: + resp = self.client.get(path) + resp.raise_for_status() + return resp.json() + except httpx.HTTPStatusError as e: + logger.error("RMQ Admin GET %s failed: %s", path, e) + raise RmqError(f"RMQ Admin HTTP {e.response.status_code}") + except httpx.ConnectError as e: + logger.error("RMQ Admin connection failed: %s", e) + raise RmqError("Cannot connect to RMQ Admin API") + + def _post(self, path: str, data: dict) -> dict: + try: + resp = self.client.post(path, json=data) + resp.raise_for_status() + return resp.json() + except httpx.HTTPStatusError as e: + logger.error("RMQ Admin POST %s failed: %s", path, e) + raise RmqError(f"RMQ Admin HTTP {e.response.status_code}") + except httpx.ConnectError as e: + logger.error("RMQ Admin connection failed: %s", e) + raise RmqError("Cannot connect to RMQ Admin API") + + # ── Overview & Health ─────────────────────────────────────────── + + def get_overview(self) -> RmqOverview: + data = self._get("/api/overview") + return RmqOverview( + cluster_name=data.get("cluster_name", ""), + node=data.get("node", ""), + message_stats=data.get("message_stats", {}), + queue_totals=data.get("queue_totals", {}), + object_totals=data.get("object_totals", {}), + ) + + def get_nodes(self) -> list[dict]: + return self._get("/api/nodes") + + def health_check(self) -> dict: + return self._get("/api/health/checks/alarms") + + # ── Exchanges & Queues ──────────────────────────────────────── + + def get_exchanges(self) -> list[dict]: + return self._get("/api/exchanges") + + def get_queues(self) -> list[dict]: + return self._get("/api/queues") + + def get_queue_info(self, name: str) -> dict: + return self._get(f"/api/queues/%2f/{name}") + + def get_bindings(self) -> list[dict]: + return self._get("/api/bindings") + + def get_consumers(self) -> list[dict]: + return self._get("/api/consumers") + + def get_connections(self) -> list[dict]: + return self._get("/api/connections") + + def get_channels(self) -> list[dict]: + return self._get("/api/channels") + + # ── Publish / Consume ───────────────────────────────────────── + + def publish( + self, + exchange: str, + routing_key: str, + payload: str | dict, + payload_encoding: str = "string", + properties: dict | None = None, + ) -> bool: + body_payload = payload if isinstance(payload, str) else json.dumps(payload) + body = { + "routing_key": routing_key, + "payload": body_payload, + "payload_encoding": payload_encoding, + } + if properties: + body["properties"] = properties + result = self._post(f"/api/exchanges/%2f/{exchange}/publish", body) + return result.get("routed", False) + + def peek_messages(self, queue: str, count: int = 5, ackmode: str = "ack_requeue_true") -> list[dict]: + body = {"count": count, "ackmode": ackmode, "encoding": "auto"} + return self._post(f"/api/queues/%2f/{queue}/get", body) + + def get_exchange_bindings(self, exchange: str) -> list[dict]: + return self._get(f"/api/exchanges/%2f/{exchange}/bindings/source") + + def get_queue_bindings(self, queue: str) -> list[dict]: + return self._get(f"/api/queues/%2f/{queue}/bindings") + + # ── Helpers ─────────────────────────────────────────────────── + + def get_queue_depths(self) -> list[RmqQueueInfo]: + queues = self.get_queues() + return [ + RmqQueueInfo( + name=q.get("name", ""), + messages_ready=q.get("messages_ready", 0), + messages_unacknowledged=q.get("messages_unacknowledged", 0), + consumer_count=q.get("consumers", 0), + state=q.get("state", ""), + ) + for q in queues + ] + + def publish_settings_update(self, payload: dict) -> bool: + """Publish to the settingsUpdate fanout exchange.""" + return self.publish( + exchange="settingsUpdate", + routing_key="", + payload=json.dumps(payload), + properties={"content_type": "application/json"}, + ) + + def close(self): + self.client.close() + + +class RmqError(Exception): + pass diff --git a/backend/app/services/rmq_game.py b/backend/app/services/rmq_game.py new file mode 100644 index 0000000..e128d8b --- /dev/null +++ b/backend/app/services/rmq_game.py @@ -0,0 +1,126 @@ +"""RabbitMQ Game Management HTTP API client.""" + +import json +import logging + +import httpx + +logger = logging.getLogger(__name__) + + +class RmqGameService: + def __init__(self, host: str, port: int, username: str, password: str): + self.base_url = f"http://{host}:{port}" + self.auth = (username, password) + self.client = httpx.Client(base_url=self.base_url, auth=self.auth, timeout=15) + logger.debug("RmqGameService initialized: %s", self.base_url) + + def _get(self, path: str) -> dict | list: + try: + resp = self.client.get(path) + resp.raise_for_status() + return resp.json() + except httpx.HTTPStatusError as e: + logger.error("RMQ Game GET %s failed: %s", path, e) + raise RmqGameError(f"RMQ Game HTTP {e.response.status_code}") + except httpx.ConnectError as e: + logger.error("RMQ Game connection failed: %s", e) + raise RmqGameError("Cannot connect to RMQ Game API") + + def _post(self, path: str, data: dict) -> dict: + try: + resp = self.client.post(path, json=data) + resp.raise_for_status() + return resp.json() + except httpx.HTTPStatusError as e: + logger.error("RMQ Game POST %s failed: %s", path, e) + raise RmqGameError(f"RMQ Game HTTP {e.response.status_code}") + except httpx.ConnectError as e: + logger.error("RMQ Game connection failed: %s", e) + raise RmqGameError("Cannot connect to RMQ Game API") + + # ── Overview ────────────────────────────────────────────────── + + def get_overview(self) -> dict: + return self._get("/api/overview") + + def get_exchanges(self) -> list[dict]: + return self._get("/api/exchanges") + + def get_queues(self) -> list[dict]: + return self._get("/api/queues") + + # ── Publish ─────────────────────────────────────────────────── + + def publish( + self, + exchange: str, + routing_key: str, + payload: str | dict, + payload_encoding: str = "string", + properties: dict | None = None, + ) -> bool: + body_payload = payload if isinstance(payload, str) else json.dumps(payload) + body = { + "routing_key": routing_key, + "payload": body_payload, + "payload_encoding": payload_encoding, + } + if properties: + body["properties"] = properties + result = self._post(f"/api/exchanges/%2f/{exchange}/publish", body) + return result.get("routed", False) + + def peek_messages(self, queue: str, count: int = 5, ackmode: str = "ack_requeue_true") -> list[dict]: + body = {"count": count, "ackmode": ackmode, "encoding": "auto"} + return self._post(f"/api/queues/%2f/{queue}/get", body) + + # ── Broadcast ───────────────────────────────────────────────── + + def send_broadcast(self, message: str, title: str = "", duration: int = 30, server: str | None = None, partition: str | None = None) -> bool: + """Send an in-game broadcast via the heartbeats exchange.""" + display_title = title or "Admin Broadcast" + inner = { + "ServerCommand": "ServiceBroadcast", + "BroadcastType": "Generic", + "BroadcastPayload": { + "BroadcastDuration": duration, + "LocalizedText": [ + {"Key": "en", "Title": display_title, "Body": message}, + {"Key": "en-US", "Title": display_title, "Body": message}, + ], + }, + } + body = { + "Version": 2, + "AuthToken": "Nu6VmPWUMvdPMeB7qErr", + "MessageContent": inner, + } + return self.publish( + exchange="heartbeats", + routing_key="notifications", + payload=json.dumps(body), + payload_encoding="string", + properties={ + "content_type": "application/json", + "message_id": f"manual-service-broadcast-{int(time.time() * 1000)}", + "app_id": "fls", + "user_id": "fls_backend", + }, + ) + + # ── Chat Intercept ──────────────────────────────────────────── + + def peek_chat_intercept(self, count: int = 10) -> list[dict]: + """Peek messages from the chat.intercept queue.""" + return self.peek_messages("queue.intercept", count=count) + + def close(self): + self.client.close() + + +class RmqGameError(Exception): + pass + + +import time diff --git a/backend/app/services/ssh.py b/backend/app/services/ssh.py new file mode 100644 index 0000000..362d643 --- /dev/null +++ b/backend/app/services/ssh.py @@ -0,0 +1,103 @@ +"""SSH service — remote command execution via paramiko.""" + +import logging +import threading +import paramiko + +logger = logging.getLogger(__name__) + + +class SSHService: + def __init__(self, host, user, ssh_key=None): + self.host = host + self.user = user + self.ssh_key = ssh_key + self._client = None + self._lock = threading.Lock() + key_status = self.ssh_key if self.ssh_key else "default ssh identity/agent" + logger.info("SSHService initialized: %s@%s using %s", user, host, key_status) + + def _get_client(self): + with self._lock: + if self._client is not None: + transport = self._client.get_transport() + if transport and transport.is_active(): + return self._client + self._client = None + + client = paramiko.SSHClient() + client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + + connect_kwargs = { + "hostname": self.host, + "username": self.user, + "timeout": 15, + "allow_agent": True, + "look_for_keys": True, + } + if self.ssh_key: + connect_kwargs["key_filename"] = self.ssh_key + + try: + client.connect(**connect_kwargs) + logger.debug("SSH connection established to %s@%s", self.user, self.host) + except paramiko.AuthenticationException: + logger.error("SSH authentication failed for %s@%s", self.user, self.host) + raise + except paramiko.SSHException as e: + logger.error("SSH connection error: %s", e) + raise + except Exception as e: + logger.error("Unexpected SSH error: %s", e) + raise + + self._client = client + return self._client + + def run(self, command, timeout=30): + cmd_display = command[:150] + "..." if len(command) > 150 else command + logger.debug("SSH executing: %s", cmd_display) + + try: + client = self._get_client() + stdin, stdout, stderr = client.exec_command(command, timeout=timeout) + out = stdout.read().decode("utf-8", errors="replace") + err = stderr.read().decode("utf-8", errors="replace") + rc = stdout.channel.recv_exit_status() + + logger.debug("SSH result: rc=%d, stdout_len=%d, stderr_len=%d", rc, len(out), len(err)) + if err and rc != 0: + logger.warning("SSH stderr (rc=%d): %s", rc, err[:200]) + if rc != 0: + logger.warning("SSH command failed (rc=%d): cmd=%s err=%s", rc, cmd_display, err[:100] if err else "none") + return out, err, rc + except paramiko.SSHException as e: + logger.error("SSH command error (%s): %s", self.host, e) + self._client = None + return "", str(e), -1 + except Exception as ex: + logger.error("Unexpected SSH command error (%s): %s", self.host, ex) + self._client = None + return "", str(ex), -1 + + def check_connection(self): + try: + out, err, rc = self.run("echo ok", timeout=10) + if rc == 0 and "ok" in out: + logger.debug("SSH connection check passed") + return True + logger.warning("SSH connection check failed: rc=%d, out=%s", rc, out[:50]) + return False + except Exception: + logger.warning("SSH connection check failed with exception") + return False + + def close(self): + with self._lock: + if self._client: + try: + self._client.close() + logger.debug("SSH connection closed") + except Exception as e: + logger.debug("Error closing SSH connection: %s", e) + self._client = None diff --git a/backend/app/services/world.py b/backend/app/services/world.py new file mode 100644 index 0000000..dbd820f --- /dev/null +++ b/backend/app/services/world.py @@ -0,0 +1,35 @@ +# World service — partitions, spice, teleport. + +import logging + +from app.models import PartitionInfo +from app.services.database import DatabaseService + +logger = logging.getLogger(__name__) + + +class WorldService: + def __init__(self, db: DatabaseService): + self.db = db + + def get_partitions(self, map_name: str = "") -> list[PartitionInfo]: + rows = self.db.call_function("get_partitions", [map_name]) + return [PartitionInfo( + id=r.get("partition_id", 0), + map=r.get("map", ""), + dimension_index=r.get("dimension_index", 0), + label=r.get("label", ""), + definition=str(r.get("partition_definition", "")), + ) for r in rows] + + def teleport(self, fls_id: str, partition_id: int, x: float, y: float, z: float) -> bool: + self.db.call_procedure("admin_move_offline_player_to_partition", [fls_id, partition_id, (x, y, z)]) + return True + + def reset_spice(self, map_name: str, dimension_index: int) -> bool: + self.db.call_procedure("reset_global_spice_field_state", [map_name, dimension_index]) + return True + + def force_spice_spawn(self, server_id: str, spicefield_type_id: int) -> bool: + self.db.call_procedure("try_spawn_spicefield", [server_id, spicefield_type_id]) + return True diff --git a/backend/app/utils/__init__.py b/backend/app/utils/__init__.py new file mode 100644 index 0000000..8314821 --- /dev/null +++ b/backend/app/utils/__init__.py @@ -0,0 +1 @@ +# Utils package init. diff --git a/backend/app/utils/constants.py b/backend/app/utils/constants.py new file mode 100644 index 0000000..53bcb31 --- /dev/null +++ b/backend/app/utils/constants.py @@ -0,0 +1,71 @@ +# Shared constants and helpers. + +INVENTORY_TYPE_LABELS = { + 0: "Main Inventory", + 1: "Equipped Items", + 5: "Hotbar", + 12: "Storage", + 14: "Recipes", + 15: "Key Items", + 20: "Crafting Queue", + 25: "Schematics", + 27: "Emotes", + 29: "Quest Items", + 30: "Bank", + 31: "Power Pack Slots", + 32: "Module Slots", + 33: "Augment Slots", +} + +INVENTORY_HIDDEN_TYPES = {14, 27} +INVENTORY_UNKNOWN_TYPES = {12, 20, 25, 29, 30, 31, 32, 33} +INVENTORY_PRIMARY_TYPES = {0, 1, 5, 15} + +EQUIPPED_SLOT_LABELS = { + 0: "Head", + 1: "Chest", + 2: "Legs", + 3: "Gloves", + 4: "Feet", + 5: "Unknown Spare Slot", + 6: "Portable Light", + 7: "Suspensor Belt", + 8: "Power Pack", + 9: "Shield", +} + +QUALITY_TIERS = { + 0: {"label": "Common", "color": "#9a8a7a"}, + 1: {"label": "Uncommon", "color": "#27ae60"}, + 2: {"label": "Rare", "color": "#3498db"}, + 3: {"label": "Epic", "color": "#9b59b6"}, + 4: {"label": "Legendary", "color": "#f39c12"}, +} + +CURRENCY_ID_LABELS = { + 0: "Solari Credits", + 1: "House Script", + 2: "Spice", +} + +GUILD_ROLES = {100: "Leader", 90: "Officer", 80: "Officer", 50: "Member", 1: "Member"} + +VEHICLE_TYPE_MAP = { + "BP_MediumOrnithopter_CHOAM": "Medium Ornithopter", + "BP_TransportOrnithopter_CHOAM": "Transport Ornithopter", + "BP_Buggy_CHOAM": "Buggy", + "BP_LightOrnithopter_Choam": "Light Ornithopter", + "BP_Sandbike_CHOAM": "Sandbike", +} + +NAV_PAGES = [ + ("/", "Overview"), + ("/server", "Server"), + ("/players", "Players"), + ("/guilds", "Guilds"), + ("/vehicles", "Vehicles"), + ("/map", "Map"), + ("/chat", "Chat"), + ("/admin", "Admin"), + ("/shell", "Shell"), +] diff --git a/backend/app/websocket/__init__.py b/backend/app/websocket/__init__.py new file mode 100644 index 0000000..fef6024 --- /dev/null +++ b/backend/app/websocket/__init__.py @@ -0,0 +1 @@ +# WebSocket package init. diff --git a/backend/app/websocket/shell.py b/backend/app/websocket/shell.py new file mode 100644 index 0000000..92e85bc --- /dev/null +++ b/backend/app/websocket/shell.py @@ -0,0 +1,131 @@ +# WebSocket shell handler — interactive terminal via SSH. + +import os +import time +import threading +import logging +import re +import shlex + +import paramiko +from flask import request, session +from flask_socketio import emit + +logger = logging.getLogger(__name__) + +shell_processes = {} +K8S_NAME_RE = re.compile(r"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$") + + +def require_k8s_name(value, label): + value = str(value or "").strip() + if not value or not K8S_NAME_RE.fullmatch(value): + raise ValueError(f"Invalid {label}") + return value + + +def quote_remote(value): + return shlex.quote(str(value)) + + +def register_websocket_handlers(socketio, settings): + @socketio.on("shell_create") + def handle_shell_create(data): + shell_enabled = settings.get("auth", {}).get("shell_enabled", True) + if not shell_enabled: + return emit("shell_created", {"success": False, "error": "Shell access is disabled"}) + + auth_enabled = settings.get("auth", {}).get("enabled", True) + if auth_enabled and not session.get("_user_id"): + return emit("shell_created", {"success": False, "error": "Authentication required"}) + + shell_type = data.get("type", "vm") + shell_id = request.sid + + try: + ssh_key = _find_ssh_key(settings) + if not ssh_key: + return emit("shell_created", {"success": False, "error": "SSH key not found"}) + + client = paramiko.SSHClient() + client.set_missing_host_key_policy(paramiko.WarningPolicy()) + server_host = settings["server"]["host"] + server_user = settings["server"]["user"] + + if shell_type == "vm": + client.connect(server_host, username=server_user, key_filename=ssh_key, timeout=10) + chan = client.invoke_shell(term="xterm-256color", width=80, height=24) + else: + namespace = settings["kubernetes"]["namespace"] + pod = data.get("pod", "") + pod = require_k8s_name(pod, "pod") + client.connect(server_host, username=server_user, key_filename=ssh_key, timeout=10) + transport = client.get_transport() + chan = transport.open_session() + chan.get_pty(term="xterm-256color", width=80, height=24) + safe_pod = quote_remote(pod) + safe_ns = quote_remote(namespace) + chan.exec_command(f"sudo kubectl exec -it {safe_pod} -n {safe_ns} -- /bin/bash") + + shell_processes[shell_id] = {"client": client, "channel": chan, "type": shell_type} + + def read_channel(): + time.sleep(0.5) + socketio.emit("shell_output", {"data": "\r\nConnected. Press Enter...\r\n", "type": "stdout", "target": shell_type}, room=shell_id) + while shell_id in shell_processes: + try: + while chan.recv_ready(): + data = chan.recv(65535).decode("utf-8", errors="replace") + if data: + socketio.emit("shell_output", {"data": data, "type": "stdout", "target": shell_type}, room=shell_id) + while chan.recv_stderr_ready(): + data = chan.recv_stderr(65535).decode("utf-8", errors="replace") + if data: + socketio.emit("shell_output", {"data": data, "type": "stderr", "target": shell_type}, room=shell_id) + if chan.closed: + socketio.emit("shell_output", {"data": "\r\n[Disconnected]\r\n", "type": "stdout", "target": shell_type}, room=shell_id) + break + except Exception as e: + logger.error("Shell read error: %s", e) + break + time.sleep(0.1) + + threading.Thread(target=read_channel, daemon=True).start() + socketio.emit("shell_created", {"success": True, "shell_id": shell_id}, room=shell_id) + except Exception as e: + logger.error("Shell creation failed: %s", e) + socketio.emit("shell_created", {"success": False, "error": str(e)}, room=shell_id) + + @socketio.on("shell_input") + def handle_shell_input(data): + shell_id = request.sid + if shell_id in shell_processes: + try: + chan = shell_processes[shell_id]["channel"] + if chan and chan.send_ready(): + chan.send(data.get("data", "")) + except Exception as e: + logger.error("Shell input error: %s", e) + + @socketio.on("shell_disconnect") + def handle_shell_disconnect(data=None): + shell_id = request.sid + if shell_id in shell_processes: + try: + if "client" in shell_processes[shell_id]: + shell_processes[shell_id]["client"].close() + except Exception as e: + logger.error("Shell disconnect error: %s", e) + del shell_processes[shell_id] + + +def _find_ssh_key(settings): + ssh_key = settings["server"].get("ssh_key") + if ssh_key: + return ssh_key + local_appdata = os.environ.get("LOCALAPPDATA") + if local_appdata: + default_key = os.path.join(local_appdata, "DuneAwakeningServer", "sshKey") + if os.path.exists(default_key): + return default_key + return None diff --git a/backend/requirements.txt b/backend/requirements.txt new file mode 100644 index 0000000..300e84f --- /dev/null +++ b/backend/requirements.txt @@ -0,0 +1,17 @@ +flask>=3.0.0 +flask-socketio>=5.3.0 +flask-login>=0.6.3 +flask-limiter>=3.5.0 +flask-cors>=4.0.0 +flask-wtf>=1.2.0 +pydantic>=2.5.0 +httpx>=0.27.0 +psycopg>=3.1.0 +psycopg_pool>=3.2.0 +cachetools>=5.3.0 +argon2-cffi>=23.1.0 +pyyaml>=6.0 +python-socketio>=5.10.0 +paramiko>=3.4.0 +Werkzeug>=3.0.0 +itsdangerous>=2.1.0 diff --git a/backend/run.py b/backend/run.py new file mode 100644 index 0000000..5909b95 --- /dev/null +++ b/backend/run.py @@ -0,0 +1,22 @@ +"""Entry point for the new backend.""" + +import sys +import os + +# Add backend to path +backend_dir = os.path.dirname(os.path.abspath(__file__)) +if backend_dir not in sys.path: + sys.path.insert(0, backend_dir) + +from app.factory import create_app + +app = create_app() + +if __name__ == "__main__": + import logging + logging.basicConfig(level=logging.INFO) + app.run( + host=app.dune_settings["dashboard"]["host"], + port=app.dune_settings["dashboard"]["port"], + debug=app.dune_settings["dashboard"]["debug"], + ) diff --git a/frontend/dist/assets/index-9_PploUA.js b/frontend/dist/assets/index-9_PploUA.js new file mode 100644 index 0000000..e52829b --- /dev/null +++ b/frontend/dist/assets/index-9_PploUA.js @@ -0,0 +1,94 @@ +function Kp(e,t){for(var r=0;rs[i]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))s(i);new MutationObserver(i=>{for(const o of i)if(o.type==="childList")for(const c of o.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&s(c)}).observe(document,{childList:!0,subtree:!0});function r(i){const o={};return i.integrity&&(o.integrity=i.integrity),i.referrerPolicy&&(o.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?o.credentials="include":i.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function s(i){if(i.ep)return;i.ep=!0;const o=r(i);fetch(i.href,o)}})();function Xp(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Th={exports:{}},Zn={},Lh={exports:{}},re={};/** + * @license React + * react.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var xi=Symbol.for("react.element"),Gp=Symbol.for("react.portal"),Jp=Symbol.for("react.fragment"),Qp=Symbol.for("react.strict_mode"),Yp=Symbol.for("react.profiler"),Zp=Symbol.for("react.provider"),em=Symbol.for("react.context"),tm=Symbol.for("react.forward_ref"),rm=Symbol.for("react.suspense"),sm=Symbol.for("react.memo"),im=Symbol.for("react.lazy"),Ic=Symbol.iterator;function nm(e){return e===null||typeof e!="object"?null:(e=Ic&&e[Ic]||e["@@iterator"],typeof e=="function"?e:null)}var Dh={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Ah=Object.assign,Oh={};function ws(e,t,r){this.props=e,this.context=t,this.refs=Oh,this.updater=r||Dh}ws.prototype.isReactComponent={};ws.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};ws.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function Nh(){}Nh.prototype=ws.prototype;function Rl(e,t,r){this.props=e,this.context=t,this.refs=Oh,this.updater=r||Dh}var Tl=Rl.prototype=new Nh;Tl.constructor=Rl;Ah(Tl,ws.prototype);Tl.isPureReactComponent=!0;var Fc=Array.isArray,Ph=Object.prototype.hasOwnProperty,Ll={current:null},Bh={key:!0,ref:!0,__self:!0,__source:!0};function jh(e,t,r){var s,i={},o=null,c=null;if(t!=null)for(s in t.ref!==void 0&&(c=t.ref),t.key!==void 0&&(o=""+t.key),t)Ph.call(t,s)&&!Bh.hasOwnProperty(s)&&(i[s]=t[s]);var n=arguments.length-2;if(n===1)i.children=r;else if(1>>1,H=R[B];if(0>>1;Bi(X,A))tei(T,X)?(R[B]=T,R[te]=A,B=te):(R[B]=X,R[G]=A,B=G);else if(tei(T,A))R[B]=T,R[te]=A,B=te;else break e}}return D}function i(R,D){var A=R.sortIndex-D.sortIndex;return A!==0?A:R.id-D.id}if(typeof performance=="object"&&typeof performance.now=="function"){var o=performance;e.unstable_now=function(){return o.now()}}else{var c=Date,n=c.now();e.unstable_now=function(){return c.now()-n}}var a=[],f=[],m=1,p=null,_=3,S=!1,b=!1,y=!1,u=typeof setTimeout=="function"?setTimeout:null,h=typeof clearTimeout=="function"?clearTimeout:null,l=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function d(R){for(var D=r(f);D!==null;){if(D.callback===null)s(f);else if(D.startTime<=R)s(f),D.sortIndex=D.expirationTime,t(a,D);else break;D=r(f)}}function g(R){if(y=!1,d(R),!b)if(r(a)!==null)b=!0,W(x);else{var D=r(f);D!==null&&V(g,D.startTime-R)}}function x(R,D){b=!1,y&&(y=!1,h(w),w=-1),S=!0;var A=_;try{for(d(D),p=r(a);p!==null&&(!(p.expirationTime>D)||R&&!N());){var B=p.callback;if(typeof B=="function"){p.callback=null,_=p.priorityLevel;var H=B(p.expirationTime<=D);D=e.unstable_now(),typeof H=="function"?p.callback=H:p===r(a)&&s(a),d(D)}else s(a);p=r(a)}if(p!==null)var q=!0;else{var G=r(f);G!==null&&V(g,G.startTime-D),q=!1}return q}finally{p=null,_=A,S=!1}}var C=!1,k=null,w=-1,E=5,L=-1;function N(){return!(e.unstable_now()-LR||125B?(R.sortIndex=A,t(f,R),r(a)===null&&R===r(f)&&(y?(h(w),w=-1):y=!0,V(g,A-B))):(R.sortIndex=H,t(a,R),b||S||(b=!0,W(x))),R},e.unstable_shouldYield=N,e.unstable_wrapCallback=function(R){var D=_;return function(){var A=_;_=D;try{return R.apply(this,arguments)}finally{_=A}}}})(Uh);Hh.exports=Uh;var gm=Hh.exports;/** + * @license React + * react-dom.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var vm=M,dt=gm;function K(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,r=1;r"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),fa=Object.prototype.hasOwnProperty,ym=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,Uc={},zc={};function Sm(e){return fa.call(zc,e)?!0:fa.call(Uc,e)?!1:ym.test(e)?zc[e]=!0:(Uc[e]=!0,!1)}function xm(e,t,r,s){if(r!==null&&r.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return s?!1:r!==null?!r.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function bm(e,t,r,s){if(t===null||typeof t>"u"||xm(e,t,r,s))return!0;if(s)return!1;if(r!==null)switch(r.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function et(e,t,r,s,i,o,c){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=s,this.attributeNamespace=i,this.mustUseProperty=r,this.propertyName=e,this.type=t,this.sanitizeURL=o,this.removeEmptyString=c}var Ie={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){Ie[e]=new et(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];Ie[t]=new et(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){Ie[e]=new et(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){Ie[e]=new et(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){Ie[e]=new et(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){Ie[e]=new et(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){Ie[e]=new et(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){Ie[e]=new et(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){Ie[e]=new et(e,5,!1,e.toLowerCase(),null,!1,!1)});var Al=/[\-:]([a-z])/g;function Ol(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(Al,Ol);Ie[t]=new et(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(Al,Ol);Ie[t]=new et(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(Al,Ol);Ie[t]=new et(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){Ie[e]=new et(e,1,!1,e.toLowerCase(),null,!1,!1)});Ie.xlinkHref=new et("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){Ie[e]=new et(e,1,!1,e.toLowerCase(),null,!0,!0)});function Nl(e,t,r,s){var i=Ie.hasOwnProperty(t)?Ie[t]:null;(i!==null?i.type!==0:s||!(2n||i[c]!==o[n]){var a=` +`+i[c].replace(" at new "," at ");return e.displayName&&a.includes("")&&(a=a.replace("",e.displayName)),a}while(1<=c&&0<=n);break}}}finally{Ro=!1,Error.prepareStackTrace=r}return(e=e?e.displayName||e.name:"")?zs(e):""}function wm(e){switch(e.tag){case 5:return zs(e.type);case 16:return zs("Lazy");case 13:return zs("Suspense");case 19:return zs("SuspenseList");case 0:case 2:case 15:return e=To(e.type,!1),e;case 11:return e=To(e.type.render,!1),e;case 1:return e=To(e.type,!0),e;default:return""}}function ga(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case Jr:return"Fragment";case Gr:return"Portal";case pa:return"Profiler";case Pl:return"StrictMode";case ma:return"Suspense";case _a:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case Wh:return(e.displayName||"Context")+".Consumer";case $h:return(e._context.displayName||"Context")+".Provider";case Bl:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case jl:return t=e.displayName||null,t!==null?t:ga(e.type)||"Memo";case sr:t=e._payload,e=e._init;try{return ga(e(t))}catch{}}return null}function Cm(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return ga(t);case 8:return t===Pl?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function Sr(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function qh(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function Em(e){var t=qh(e)?"checked":"value",r=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),s=""+e[t];if(!e.hasOwnProperty(t)&&typeof r<"u"&&typeof r.get=="function"&&typeof r.set=="function"){var i=r.get,o=r.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return i.call(this)},set:function(c){s=""+c,o.call(this,c)}}),Object.defineProperty(e,t,{enumerable:r.enumerable}),{getValue:function(){return s},setValue:function(c){s=""+c},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Ii(e){e._valueTracker||(e._valueTracker=Em(e))}function Kh(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var r=t.getValue(),s="";return e&&(s=qh(e)?e.checked?"true":"false":e.value),e=s,e!==r?(t.setValue(e),!0):!1}function Rn(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function va(e,t){var r=t.checked;return xe({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:r??e._wrapperState.initialChecked})}function Wc(e,t){var r=t.defaultValue==null?"":t.defaultValue,s=t.checked!=null?t.checked:t.defaultChecked;r=Sr(t.value!=null?t.value:r),e._wrapperState={initialChecked:s,initialValue:r,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function Xh(e,t){t=t.checked,t!=null&&Nl(e,"checked",t,!1)}function ya(e,t){Xh(e,t);var r=Sr(t.value),s=t.type;if(r!=null)s==="number"?(r===0&&e.value===""||e.value!=r)&&(e.value=""+r):e.value!==""+r&&(e.value=""+r);else if(s==="submit"||s==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?Sa(e,t.type,r):t.hasOwnProperty("defaultValue")&&Sa(e,t.type,Sr(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Vc(e,t,r){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var s=t.type;if(!(s!=="submit"&&s!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,r||t===e.value||(e.value=t),e.defaultValue=t}r=e.name,r!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,r!==""&&(e.name=r)}function Sa(e,t,r){(t!=="number"||Rn(e.ownerDocument)!==e)&&(r==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+r&&(e.defaultValue=""+r))}var $s=Array.isArray;function as(e,t,r,s){if(e=e.options,t){t={};for(var i=0;i"+t.valueOf().toString()+"",t=Fi.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function si(e,t){if(t){var r=e.firstChild;if(r&&r===e.lastChild&&r.nodeType===3){r.nodeValue=t;return}}e.textContent=t}var Ks={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},km=["Webkit","ms","Moz","O"];Object.keys(Ks).forEach(function(e){km.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Ks[t]=Ks[e]})});function Yh(e,t,r){return t==null||typeof t=="boolean"||t===""?"":r||typeof t!="number"||t===0||Ks.hasOwnProperty(e)&&Ks[e]?(""+t).trim():t+"px"}function Zh(e,t){e=e.style;for(var r in t)if(t.hasOwnProperty(r)){var s=r.indexOf("--")===0,i=Yh(r,t[r],s);r==="float"&&(r="cssFloat"),s?e.setProperty(r,i):e[r]=i}}var Rm=xe({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function wa(e,t){if(t){if(Rm[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(K(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(K(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(K(61))}if(t.style!=null&&typeof t.style!="object")throw Error(K(62))}}function Ca(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var Ea=null;function Ml(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var ka=null,ls=null,cs=null;function Xc(e){if(e=Ei(e)){if(typeof ka!="function")throw Error(K(280));var t=e.stateNode;t&&(t=io(t),ka(e.stateNode,e.type,t))}}function ed(e){ls?cs?cs.push(e):cs=[e]:ls=e}function td(){if(ls){var e=ls,t=cs;if(cs=ls=null,Xc(e),t)for(e=0;e>>=0,e===0?32:31-(Im(e)/Fm|0)|0}var Hi=64,Ui=4194304;function Ws(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function An(e,t){var r=e.pendingLanes;if(r===0)return 0;var s=0,i=e.suspendedLanes,o=e.pingedLanes,c=r&268435455;if(c!==0){var n=c&~i;n!==0?s=Ws(n):(o&=c,o!==0&&(s=Ws(o)))}else c=r&~i,c!==0?s=Ws(c):o!==0&&(s=Ws(o));if(s===0)return 0;if(t!==0&&t!==s&&!(t&i)&&(i=s&-s,o=t&-t,i>=o||i===16&&(o&4194240)!==0))return t;if(s&4&&(s|=r&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=s;0r;r++)t.push(e);return t}function wi(e,t,r){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Dt(t),e[t]=r}function $m(e,t){var r=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var s=e.eventTimes;for(e=e.expirationTimes;0=Gs),su=" ",iu=!1;function xd(e,t){switch(e){case"keyup":return g_.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function bd(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Qr=!1;function y_(e,t){switch(e){case"compositionend":return bd(t);case"keypress":return t.which!==32?null:(iu=!0,su);case"textInput":return e=t.data,e===su&&iu?null:e;default:return null}}function S_(e,t){if(Qr)return e==="compositionend"||!Vl&&xd(e,t)?(e=yd(),hn=zl=ar=null,Qr=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:r,offset:t-e};e=s}e:{for(;r;){if(r.nextSibling){r=r.nextSibling;break e}r=r.parentNode}r=void 0}r=lu(r)}}function kd(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?kd(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Rd(){for(var e=window,t=Rn();t instanceof e.HTMLIFrameElement;){try{var r=typeof t.contentWindow.location.href=="string"}catch{r=!1}if(r)e=t.contentWindow;else break;t=Rn(e.document)}return t}function ql(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function L_(e){var t=Rd(),r=e.focusedElem,s=e.selectionRange;if(t!==r&&r&&r.ownerDocument&&kd(r.ownerDocument.documentElement,r)){if(s!==null&&ql(r)){if(t=s.start,e=s.end,e===void 0&&(e=t),"selectionStart"in r)r.selectionStart=t,r.selectionEnd=Math.min(e,r.value.length);else if(e=(t=r.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var i=r.textContent.length,o=Math.min(s.start,i);s=s.end===void 0?o:Math.min(s.end,i),!e.extend&&o>s&&(i=s,s=o,o=i),i=cu(r,o);var c=cu(r,s);i&&c&&(e.rangeCount!==1||e.anchorNode!==i.node||e.anchorOffset!==i.offset||e.focusNode!==c.node||e.focusOffset!==c.offset)&&(t=t.createRange(),t.setStart(i.node,i.offset),e.removeAllRanges(),o>s?(e.addRange(t),e.extend(c.node,c.offset)):(t.setEnd(c.node,c.offset),e.addRange(t)))}}for(t=[],e=r;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof r.focus=="function"&&r.focus(),r=0;r=document.documentMode,Yr=null,Oa=null,Qs=null,Na=!1;function uu(e,t,r){var s=r.window===r?r.document:r.nodeType===9?r:r.ownerDocument;Na||Yr==null||Yr!==Rn(s)||(s=Yr,"selectionStart"in s&&ql(s)?s={start:s.selectionStart,end:s.selectionEnd}:(s=(s.ownerDocument&&s.ownerDocument.defaultView||window).getSelection(),s={anchorNode:s.anchorNode,anchorOffset:s.anchorOffset,focusNode:s.focusNode,focusOffset:s.focusOffset}),Qs&&ci(Qs,s)||(Qs=s,s=Pn(Oa,"onSelect"),0ts||(e.current=Fa[ts],Fa[ts]=null,ts--)}function de(e,t){ts++,Fa[ts]=e.current,e.current=t}var xr={},Ge=Cr(xr),it=Cr(!1),Mr=xr;function ms(e,t){var r=e.type.contextTypes;if(!r)return xr;var s=e.stateNode;if(s&&s.__reactInternalMemoizedUnmaskedChildContext===t)return s.__reactInternalMemoizedMaskedChildContext;var i={},o;for(o in r)i[o]=t[o];return s&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=i),i}function nt(e){return e=e.childContextTypes,e!=null}function jn(){ge(it),ge(Ge)}function gu(e,t,r){if(Ge.current!==xr)throw Error(K(168));de(Ge,t),de(it,r)}function jd(e,t,r){var s=e.stateNode;if(t=t.childContextTypes,typeof s.getChildContext!="function")return r;s=s.getChildContext();for(var i in s)if(!(i in t))throw Error(K(108,Cm(e)||"Unknown",i));return xe({},r,s)}function Mn(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||xr,Mr=Ge.current,de(Ge,e),de(it,it.current),!0}function vu(e,t,r){var s=e.stateNode;if(!s)throw Error(K(169));r?(e=jd(e,t,Mr),s.__reactInternalMemoizedMergedChildContext=e,ge(it),ge(Ge),de(Ge,e)):ge(it),de(it,r)}var Vt=null,no=!1,zo=!1;function Md(e){Vt===null?Vt=[e]:Vt.push(e)}function U_(e){no=!0,Md(e)}function Er(){if(!zo&&Vt!==null){zo=!0;var e=0,t=ue;try{var r=Vt;for(ue=1;e>=c,i-=c,Kt=1<<32-Dt(t)+i|r<w?(E=k,k=null):E=k.sibling;var L=_(h,k,d[w],g);if(L===null){k===null&&(k=E);break}e&&k&&L.alternate===null&&t(h,k),l=o(L,l,w),C===null?x=L:C.sibling=L,C=L,k=E}if(w===d.length)return r(h,k),ve&&Tr(h,w),x;if(k===null){for(;ww?(E=k,k=null):E=k.sibling;var N=_(h,k,L.value,g);if(N===null){k===null&&(k=E);break}e&&k&&N.alternate===null&&t(h,k),l=o(N,l,w),C===null?x=N:C.sibling=N,C=N,k=E}if(L.done)return r(h,k),ve&&Tr(h,w),x;if(k===null){for(;!L.done;w++,L=d.next())L=p(h,L.value,g),L!==null&&(l=o(L,l,w),C===null?x=L:C.sibling=L,C=L);return ve&&Tr(h,w),x}for(k=s(h,k);!L.done;w++,L=d.next())L=S(k,h,w,L.value,g),L!==null&&(e&&L.alternate!==null&&k.delete(L.key===null?w:L.key),l=o(L,l,w),C===null?x=L:C.sibling=L,C=L);return e&&k.forEach(function(O){return t(h,O)}),ve&&Tr(h,w),x}function u(h,l,d,g){if(typeof d=="object"&&d!==null&&d.type===Jr&&d.key===null&&(d=d.props.children),typeof d=="object"&&d!==null){switch(d.$$typeof){case Mi:e:{for(var x=d.key,C=l;C!==null;){if(C.key===x){if(x=d.type,x===Jr){if(C.tag===7){r(h,C.sibling),l=i(C,d.props.children),l.return=h,h=l;break e}}else if(C.elementType===x||typeof x=="object"&&x!==null&&x.$$typeof===sr&&xu(x)===C.type){r(h,C.sibling),l=i(C,d.props),l.ref=Bs(h,C,d),l.return=h,h=l;break e}r(h,C);break}else t(h,C);C=C.sibling}d.type===Jr?(l=Br(d.props.children,h.mode,g,d.key),l.return=h,h=l):(g=yn(d.type,d.key,d.props,null,h.mode,g),g.ref=Bs(h,l,d),g.return=h,h=g)}return c(h);case Gr:e:{for(C=d.key;l!==null;){if(l.key===C)if(l.tag===4&&l.stateNode.containerInfo===d.containerInfo&&l.stateNode.implementation===d.implementation){r(h,l.sibling),l=i(l,d.children||[]),l.return=h,h=l;break e}else{r(h,l);break}else t(h,l);l=l.sibling}l=Jo(d,h.mode,g),l.return=h,h=l}return c(h);case sr:return C=d._init,u(h,l,C(d._payload),g)}if($s(d))return b(h,l,d,g);if(Ds(d))return y(h,l,d,g);Xi(h,d)}return typeof d=="string"&&d!==""||typeof d=="number"?(d=""+d,l!==null&&l.tag===6?(r(h,l.sibling),l=i(l,d),l.return=h,h=l):(r(h,l),l=Go(d,h.mode,g),l.return=h,h=l),c(h)):r(h,l)}return u}var gs=Ud(!0),zd=Ud(!1),Hn=Cr(null),Un=null,is=null,Jl=null;function Ql(){Jl=is=Un=null}function Yl(e){var t=Hn.current;ge(Hn),e._currentValue=t}function za(e,t,r){for(;e!==null;){var s=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,s!==null&&(s.childLanes|=t)):s!==null&&(s.childLanes&t)!==t&&(s.childLanes|=t),e===r)break;e=e.return}}function hs(e,t){Un=e,Jl=is=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(st=!0),e.firstContext=null)}function xt(e){var t=e._currentValue;if(Jl!==e)if(e={context:e,memoizedValue:t,next:null},is===null){if(Un===null)throw Error(K(308));is=e,Un.dependencies={lanes:0,firstContext:e}}else is=is.next=e;return t}var Ar=null;function Zl(e){Ar===null?Ar=[e]:Ar.push(e)}function $d(e,t,r,s){var i=t.interleaved;return i===null?(r.next=r,Zl(t)):(r.next=i.next,i.next=r),t.interleaved=r,Zt(e,s)}function Zt(e,t){e.lanes|=t;var r=e.alternate;for(r!==null&&(r.lanes|=t),r=e,e=e.return;e!==null;)e.childLanes|=t,r=e.alternate,r!==null&&(r.childLanes|=t),r=e,e=e.return;return r.tag===3?r.stateNode:null}var ir=!1;function ec(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Wd(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function Jt(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function pr(e,t,r){var s=e.updateQueue;if(s===null)return null;if(s=s.shared,ae&2){var i=s.pending;return i===null?t.next=t:(t.next=i.next,i.next=t),s.pending=t,Zt(e,r)}return i=s.interleaved,i===null?(t.next=t,Zl(s)):(t.next=i.next,i.next=t),s.interleaved=t,Zt(e,r)}function fn(e,t,r){if(t=t.updateQueue,t!==null&&(t=t.shared,(r&4194240)!==0)){var s=t.lanes;s&=e.pendingLanes,r|=s,t.lanes=r,Fl(e,r)}}function bu(e,t){var r=e.updateQueue,s=e.alternate;if(s!==null&&(s=s.updateQueue,r===s)){var i=null,o=null;if(r=r.firstBaseUpdate,r!==null){do{var c={eventTime:r.eventTime,lane:r.lane,tag:r.tag,payload:r.payload,callback:r.callback,next:null};o===null?i=o=c:o=o.next=c,r=r.next}while(r!==null);o===null?i=o=t:o=o.next=t}else i=o=t;r={baseState:s.baseState,firstBaseUpdate:i,lastBaseUpdate:o,shared:s.shared,effects:s.effects},e.updateQueue=r;return}e=r.lastBaseUpdate,e===null?r.firstBaseUpdate=t:e.next=t,r.lastBaseUpdate=t}function zn(e,t,r,s){var i=e.updateQueue;ir=!1;var o=i.firstBaseUpdate,c=i.lastBaseUpdate,n=i.shared.pending;if(n!==null){i.shared.pending=null;var a=n,f=a.next;a.next=null,c===null?o=f:c.next=f,c=a;var m=e.alternate;m!==null&&(m=m.updateQueue,n=m.lastBaseUpdate,n!==c&&(n===null?m.firstBaseUpdate=f:n.next=f,m.lastBaseUpdate=a))}if(o!==null){var p=i.baseState;c=0,m=f=a=null,n=o;do{var _=n.lane,S=n.eventTime;if((s&_)===_){m!==null&&(m=m.next={eventTime:S,lane:0,tag:n.tag,payload:n.payload,callback:n.callback,next:null});e:{var b=e,y=n;switch(_=t,S=r,y.tag){case 1:if(b=y.payload,typeof b=="function"){p=b.call(S,p,_);break e}p=b;break e;case 3:b.flags=b.flags&-65537|128;case 0:if(b=y.payload,_=typeof b=="function"?b.call(S,p,_):b,_==null)break e;p=xe({},p,_);break e;case 2:ir=!0}}n.callback!==null&&n.lane!==0&&(e.flags|=64,_=i.effects,_===null?i.effects=[n]:_.push(n))}else S={eventTime:S,lane:_,tag:n.tag,payload:n.payload,callback:n.callback,next:null},m===null?(f=m=S,a=p):m=m.next=S,c|=_;if(n=n.next,n===null){if(n=i.shared.pending,n===null)break;_=n,n=_.next,_.next=null,i.lastBaseUpdate=_,i.shared.pending=null}}while(!0);if(m===null&&(a=p),i.baseState=a,i.firstBaseUpdate=f,i.lastBaseUpdate=m,t=i.shared.interleaved,t!==null){i=t;do c|=i.lane,i=i.next;while(i!==t)}else o===null&&(i.shared.lanes=0);Hr|=c,e.lanes=c,e.memoizedState=p}}function wu(e,t,r){if(e=t.effects,t.effects=null,e!==null)for(t=0;tr?r:4,e(!0);var s=Wo.transition;Wo.transition={};try{e(!1),t()}finally{ue=r,Wo.transition=s}}function lf(){return bt().memoizedState}function V_(e,t,r){var s=_r(e);if(r={lane:s,action:r,hasEagerState:!1,eagerState:null,next:null},cf(e))uf(t,r);else if(r=$d(e,t,r,s),r!==null){var i=Qe();At(r,e,s,i),hf(r,t,s)}}function q_(e,t,r){var s=_r(e),i={lane:s,action:r,hasEagerState:!1,eagerState:null,next:null};if(cf(e))uf(t,i);else{var o=e.alternate;if(e.lanes===0&&(o===null||o.lanes===0)&&(o=t.lastRenderedReducer,o!==null))try{var c=t.lastRenderedState,n=o(c,r);if(i.hasEagerState=!0,i.eagerState=n,Nt(n,c)){var a=t.interleaved;a===null?(i.next=i,Zl(t)):(i.next=a.next,a.next=i),t.interleaved=i;return}}catch{}finally{}r=$d(e,t,i,s),r!==null&&(i=Qe(),At(r,e,s,i),hf(r,t,s))}}function cf(e){var t=e.alternate;return e===Se||t!==null&&t===Se}function uf(e,t){Ys=Wn=!0;var r=e.pending;r===null?t.next=t:(t.next=r.next,r.next=t),e.pending=t}function hf(e,t,r){if(r&4194240){var s=t.lanes;s&=e.pendingLanes,r|=s,t.lanes=r,Fl(e,r)}}var Vn={readContext:xt,useCallback:ze,useContext:ze,useEffect:ze,useImperativeHandle:ze,useInsertionEffect:ze,useLayoutEffect:ze,useMemo:ze,useReducer:ze,useRef:ze,useState:ze,useDebugValue:ze,useDeferredValue:ze,useTransition:ze,useMutableSource:ze,useSyncExternalStore:ze,useId:ze,unstable_isNewReconciler:!1},K_={readContext:xt,useCallback:function(e,t){return jt().memoizedState=[e,t===void 0?null:t],e},useContext:xt,useEffect:Eu,useImperativeHandle:function(e,t,r){return r=r!=null?r.concat([e]):null,mn(4194308,4,rf.bind(null,t,e),r)},useLayoutEffect:function(e,t){return mn(4194308,4,e,t)},useInsertionEffect:function(e,t){return mn(4,2,e,t)},useMemo:function(e,t){var r=jt();return t=t===void 0?null:t,e=e(),r.memoizedState=[e,t],e},useReducer:function(e,t,r){var s=jt();return t=r!==void 0?r(t):t,s.memoizedState=s.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},s.queue=e,e=e.dispatch=V_.bind(null,Se,e),[s.memoizedState,e]},useRef:function(e){var t=jt();return e={current:e},t.memoizedState=e},useState:Cu,useDebugValue:lc,useDeferredValue:function(e){return jt().memoizedState=e},useTransition:function(){var e=Cu(!1),t=e[0];return e=W_.bind(null,e[1]),jt().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,r){var s=Se,i=jt();if(ve){if(r===void 0)throw Error(K(407));r=r()}else{if(r=t(),Oe===null)throw Error(K(349));Fr&30||Xd(s,t,r)}i.memoizedState=r;var o={value:r,getSnapshot:t};return i.queue=o,Eu(Jd.bind(null,s,o,e),[e]),s.flags|=2048,gi(9,Gd.bind(null,s,o,r,t),void 0,null),r},useId:function(){var e=jt(),t=Oe.identifierPrefix;if(ve){var r=Xt,s=Kt;r=(s&~(1<<32-Dt(s)-1)).toString(32)+r,t=":"+t+"R"+r,r=mi++,0<\/script>",e=e.removeChild(e.firstChild)):typeof s.is=="string"?e=c.createElement(r,{is:s.is}):(e=c.createElement(r),r==="select"&&(c=e,s.multiple?c.multiple=!0:s.size&&(c.size=s.size))):e=c.createElementNS(e,r),e[Mt]=t,e[di]=s,xf(e,t,!1,!1),t.stateNode=e;e:{switch(c=Ca(r,s),r){case"dialog":_e("cancel",e),_e("close",e),i=s;break;case"iframe":case"object":case"embed":_e("load",e),i=s;break;case"video":case"audio":for(i=0;iSs&&(t.flags|=128,s=!0,js(o,!1),t.lanes=4194304)}else{if(!s)if(e=$n(c),e!==null){if(t.flags|=128,s=!0,r=e.updateQueue,r!==null&&(t.updateQueue=r,t.flags|=4),js(o,!0),o.tail===null&&o.tailMode==="hidden"&&!c.alternate&&!ve)return $e(t),null}else 2*we()-o.renderingStartTime>Ss&&r!==1073741824&&(t.flags|=128,s=!0,js(o,!1),t.lanes=4194304);o.isBackwards?(c.sibling=t.child,t.child=c):(r=o.last,r!==null?r.sibling=c:t.child=c,o.last=c)}return o.tail!==null?(t=o.tail,o.rendering=t,o.tail=t.sibling,o.renderingStartTime=we(),t.sibling=null,r=ye.current,de(ye,s?r&1|2:r&1),t):($e(t),null);case 22:case 23:return pc(),s=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==s&&(t.flags|=8192),s&&t.mode&1?lt&1073741824&&($e(t),t.subtreeFlags&6&&(t.flags|=8192)):$e(t),null;case 24:return null;case 25:return null}throw Error(K(156,t.tag))}function tg(e,t){switch(Xl(t),t.tag){case 1:return nt(t.type)&&jn(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return vs(),ge(it),ge(Ge),sc(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return rc(t),null;case 13:if(ge(ye),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(K(340));_s()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return ge(ye),null;case 4:return vs(),null;case 10:return Yl(t.type._context),null;case 22:case 23:return pc(),null;case 24:return null;default:return null}}var Ji=!1,qe=!1,rg=typeof WeakSet=="function"?WeakSet:Set,Q=null;function ns(e,t){var r=e.ref;if(r!==null)if(typeof r=="function")try{r(null)}catch(s){be(e,t,s)}else r.current=null}function Qa(e,t,r){try{r()}catch(s){be(e,t,s)}}var ju=!1;function sg(e,t){if(Pa=On,e=Rd(),ql(e)){if("selectionStart"in e)var r={start:e.selectionStart,end:e.selectionEnd};else e:{r=(r=e.ownerDocument)&&r.defaultView||window;var s=r.getSelection&&r.getSelection();if(s&&s.rangeCount!==0){r=s.anchorNode;var i=s.anchorOffset,o=s.focusNode;s=s.focusOffset;try{r.nodeType,o.nodeType}catch{r=null;break e}var c=0,n=-1,a=-1,f=0,m=0,p=e,_=null;t:for(;;){for(var S;p!==r||i!==0&&p.nodeType!==3||(n=c+i),p!==o||s!==0&&p.nodeType!==3||(a=c+s),p.nodeType===3&&(c+=p.nodeValue.length),(S=p.firstChild)!==null;)_=p,p=S;for(;;){if(p===e)break t;if(_===r&&++f===i&&(n=c),_===o&&++m===s&&(a=c),(S=p.nextSibling)!==null)break;p=_,_=p.parentNode}p=S}r=n===-1||a===-1?null:{start:n,end:a}}else r=null}r=r||{start:0,end:0}}else r=null;for(Ba={focusedElem:e,selectionRange:r},On=!1,Q=t;Q!==null;)if(t=Q,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,Q=e;else for(;Q!==null;){t=Q;try{var b=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(b!==null){var y=b.memoizedProps,u=b.memoizedState,h=t.stateNode,l=h.getSnapshotBeforeUpdate(t.elementType===t.type?y:kt(t.type,y),u);h.__reactInternalSnapshotBeforeUpdate=l}break;case 3:var d=t.stateNode.containerInfo;d.nodeType===1?d.textContent="":d.nodeType===9&&d.documentElement&&d.removeChild(d.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(K(163))}}catch(g){be(t,t.return,g)}if(e=t.sibling,e!==null){e.return=t.return,Q=e;break}Q=t.return}return b=ju,ju=!1,b}function Zs(e,t,r){var s=t.updateQueue;if(s=s!==null?s.lastEffect:null,s!==null){var i=s=s.next;do{if((i.tag&e)===e){var o=i.destroy;i.destroy=void 0,o!==void 0&&Qa(t,r,o)}i=i.next}while(i!==s)}}function lo(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var r=t=t.next;do{if((r.tag&e)===e){var s=r.create;r.destroy=s()}r=r.next}while(r!==t)}}function Ya(e){var t=e.ref;if(t!==null){var r=e.stateNode;switch(e.tag){case 5:e=r;break;default:e=r}typeof t=="function"?t(e):t.current=e}}function Cf(e){var t=e.alternate;t!==null&&(e.alternate=null,Cf(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Mt],delete t[di],delete t[Ia],delete t[F_],delete t[H_])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Ef(e){return e.tag===5||e.tag===3||e.tag===4}function Mu(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Ef(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Za(e,t,r){var s=e.tag;if(s===5||s===6)e=e.stateNode,t?r.nodeType===8?r.parentNode.insertBefore(e,t):r.insertBefore(e,t):(r.nodeType===8?(t=r.parentNode,t.insertBefore(e,r)):(t=r,t.appendChild(e)),r=r._reactRootContainer,r!=null||t.onclick!==null||(t.onclick=Bn));else if(s!==4&&(e=e.child,e!==null))for(Za(e,t,r),e=e.sibling;e!==null;)Za(e,t,r),e=e.sibling}function el(e,t,r){var s=e.tag;if(s===5||s===6)e=e.stateNode,t?r.insertBefore(e,t):r.appendChild(e);else if(s!==4&&(e=e.child,e!==null))for(el(e,t,r),e=e.sibling;e!==null;)el(e,t,r),e=e.sibling}var je=null,Rt=!1;function rr(e,t,r){for(r=r.child;r!==null;)kf(e,t,r),r=r.sibling}function kf(e,t,r){if(Ft&&typeof Ft.onCommitFiberUnmount=="function")try{Ft.onCommitFiberUnmount(eo,r)}catch{}switch(r.tag){case 5:qe||ns(r,t);case 6:var s=je,i=Rt;je=null,rr(e,t,r),je=s,Rt=i,je!==null&&(Rt?(e=je,r=r.stateNode,e.nodeType===8?e.parentNode.removeChild(r):e.removeChild(r)):je.removeChild(r.stateNode));break;case 18:je!==null&&(Rt?(e=je,r=r.stateNode,e.nodeType===8?Uo(e.parentNode,r):e.nodeType===1&&Uo(e,r),ai(e)):Uo(je,r.stateNode));break;case 4:s=je,i=Rt,je=r.stateNode.containerInfo,Rt=!0,rr(e,t,r),je=s,Rt=i;break;case 0:case 11:case 14:case 15:if(!qe&&(s=r.updateQueue,s!==null&&(s=s.lastEffect,s!==null))){i=s=s.next;do{var o=i,c=o.destroy;o=o.tag,c!==void 0&&(o&2||o&4)&&Qa(r,t,c),i=i.next}while(i!==s)}rr(e,t,r);break;case 1:if(!qe&&(ns(r,t),s=r.stateNode,typeof s.componentWillUnmount=="function"))try{s.props=r.memoizedProps,s.state=r.memoizedState,s.componentWillUnmount()}catch(n){be(r,t,n)}rr(e,t,r);break;case 21:rr(e,t,r);break;case 22:r.mode&1?(qe=(s=qe)||r.memoizedState!==null,rr(e,t,r),qe=s):rr(e,t,r);break;default:rr(e,t,r)}}function Iu(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var r=e.stateNode;r===null&&(r=e.stateNode=new rg),t.forEach(function(s){var i=dg.bind(null,e,s);r.has(s)||(r.add(s),s.then(i,i))})}}function Et(e,t){var r=t.deletions;if(r!==null)for(var s=0;si&&(i=c),s&=~o}if(s=i,s=we()-s,s=(120>s?120:480>s?480:1080>s?1080:1920>s?1920:3e3>s?3e3:4320>s?4320:1960*ng(s/1960))-s,10e?16:e,lr===null)var s=!1;else{if(e=lr,lr=null,Xn=0,ae&6)throw Error(K(331));var i=ae;for(ae|=4,Q=e.current;Q!==null;){var o=Q,c=o.child;if(Q.flags&16){var n=o.deletions;if(n!==null){for(var a=0;awe()-dc?Pr(e,0):hc|=r),ot(e,t)}function Pf(e,t){t===0&&(e.mode&1?(t=Ui,Ui<<=1,!(Ui&130023424)&&(Ui=4194304)):t=1);var r=Qe();e=Zt(e,t),e!==null&&(wi(e,t,r),ot(e,r))}function hg(e){var t=e.memoizedState,r=0;t!==null&&(r=t.retryLane),Pf(e,r)}function dg(e,t){var r=0;switch(e.tag){case 13:var s=e.stateNode,i=e.memoizedState;i!==null&&(r=i.retryLane);break;case 19:s=e.stateNode;break;default:throw Error(K(314))}s!==null&&s.delete(t),Pf(e,r)}var Bf;Bf=function(e,t,r){if(e!==null)if(e.memoizedProps!==t.pendingProps||it.current)st=!0;else{if(!(e.lanes&r)&&!(t.flags&128))return st=!1,Z_(e,t,r);st=!!(e.flags&131072)}else st=!1,ve&&t.flags&1048576&&Id(t,Fn,t.index);switch(t.lanes=0,t.tag){case 2:var s=t.type;_n(e,t),e=t.pendingProps;var i=ms(t,Ge.current);hs(t,r),i=nc(null,t,s,e,i,r);var o=oc();return t.flags|=1,typeof i=="object"&&i!==null&&typeof i.render=="function"&&i.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,nt(s)?(o=!0,Mn(t)):o=!1,t.memoizedState=i.state!==null&&i.state!==void 0?i.state:null,ec(t),i.updater=ao,t.stateNode=i,i._reactInternals=t,Wa(t,s,e,r),t=Ka(null,t,s,!0,o,r)):(t.tag=0,ve&&o&&Kl(t),Je(null,t,i,r),t=t.child),t;case 16:s=t.elementType;e:{switch(_n(e,t),e=t.pendingProps,i=s._init,s=i(s._payload),t.type=s,i=t.tag=pg(s),e=kt(s,e),i){case 0:t=qa(null,t,s,e,r);break e;case 1:t=Nu(null,t,s,e,r);break e;case 11:t=Au(null,t,s,e,r);break e;case 14:t=Ou(null,t,s,kt(s.type,e),r);break e}throw Error(K(306,s,""))}return t;case 0:return s=t.type,i=t.pendingProps,i=t.elementType===s?i:kt(s,i),qa(e,t,s,i,r);case 1:return s=t.type,i=t.pendingProps,i=t.elementType===s?i:kt(s,i),Nu(e,t,s,i,r);case 3:e:{if(vf(t),e===null)throw Error(K(387));s=t.pendingProps,o=t.memoizedState,i=o.element,Wd(e,t),zn(t,s,null,r);var c=t.memoizedState;if(s=c.element,o.isDehydrated)if(o={element:s,isDehydrated:!1,cache:c.cache,pendingSuspenseBoundaries:c.pendingSuspenseBoundaries,transitions:c.transitions},t.updateQueue.baseState=o,t.memoizedState=o,t.flags&256){i=ys(Error(K(423)),t),t=Pu(e,t,s,r,i);break e}else if(s!==i){i=ys(Error(K(424)),t),t=Pu(e,t,s,r,i);break e}else for(ut=fr(t.stateNode.containerInfo.firstChild),ht=t,ve=!0,Lt=null,r=zd(t,null,s,r),t.child=r;r;)r.flags=r.flags&-3|4096,r=r.sibling;else{if(_s(),s===i){t=er(e,t,r);break e}Je(e,t,s,r)}t=t.child}return t;case 5:return Vd(t),e===null&&Ua(t),s=t.type,i=t.pendingProps,o=e!==null?e.memoizedProps:null,c=i.children,ja(s,i)?c=null:o!==null&&ja(s,o)&&(t.flags|=32),gf(e,t),Je(e,t,c,r),t.child;case 6:return e===null&&Ua(t),null;case 13:return yf(e,t,r);case 4:return tc(t,t.stateNode.containerInfo),s=t.pendingProps,e===null?t.child=gs(t,null,s,r):Je(e,t,s,r),t.child;case 11:return s=t.type,i=t.pendingProps,i=t.elementType===s?i:kt(s,i),Au(e,t,s,i,r);case 7:return Je(e,t,t.pendingProps,r),t.child;case 8:return Je(e,t,t.pendingProps.children,r),t.child;case 12:return Je(e,t,t.pendingProps.children,r),t.child;case 10:e:{if(s=t.type._context,i=t.pendingProps,o=t.memoizedProps,c=i.value,de(Hn,s._currentValue),s._currentValue=c,o!==null)if(Nt(o.value,c)){if(o.children===i.children&&!it.current){t=er(e,t,r);break e}}else for(o=t.child,o!==null&&(o.return=t);o!==null;){var n=o.dependencies;if(n!==null){c=o.child;for(var a=n.firstContext;a!==null;){if(a.context===s){if(o.tag===1){a=Jt(-1,r&-r),a.tag=2;var f=o.updateQueue;if(f!==null){f=f.shared;var m=f.pending;m===null?a.next=a:(a.next=m.next,m.next=a),f.pending=a}}o.lanes|=r,a=o.alternate,a!==null&&(a.lanes|=r),za(o.return,r,t),n.lanes|=r;break}a=a.next}}else if(o.tag===10)c=o.type===t.type?null:o.child;else if(o.tag===18){if(c=o.return,c===null)throw Error(K(341));c.lanes|=r,n=c.alternate,n!==null&&(n.lanes|=r),za(c,r,t),c=o.sibling}else c=o.child;if(c!==null)c.return=o;else for(c=o;c!==null;){if(c===t){c=null;break}if(o=c.sibling,o!==null){o.return=c.return,c=o;break}c=c.return}o=c}Je(e,t,i.children,r),t=t.child}return t;case 9:return i=t.type,s=t.pendingProps.children,hs(t,r),i=xt(i),s=s(i),t.flags|=1,Je(e,t,s,r),t.child;case 14:return s=t.type,i=kt(s,t.pendingProps),i=kt(s.type,i),Ou(e,t,s,i,r);case 15:return mf(e,t,t.type,t.pendingProps,r);case 17:return s=t.type,i=t.pendingProps,i=t.elementType===s?i:kt(s,i),_n(e,t),t.tag=1,nt(s)?(e=!0,Mn(t)):e=!1,hs(t,r),df(t,s,i),Wa(t,s,i,r),Ka(null,t,s,!0,e,r);case 19:return Sf(e,t,r);case 22:return _f(e,t,r)}throw Error(K(156,t.tag))};function jf(e,t){return ld(e,t)}function fg(e,t,r,s){this.tag=e,this.key=r,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=s,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function yt(e,t,r,s){return new fg(e,t,r,s)}function _c(e){return e=e.prototype,!(!e||!e.isReactComponent)}function pg(e){if(typeof e=="function")return _c(e)?1:0;if(e!=null){if(e=e.$$typeof,e===Bl)return 11;if(e===jl)return 14}return 2}function gr(e,t){var r=e.alternate;return r===null?(r=yt(e.tag,t,e.key,e.mode),r.elementType=e.elementType,r.type=e.type,r.stateNode=e.stateNode,r.alternate=e,e.alternate=r):(r.pendingProps=t,r.type=e.type,r.flags=0,r.subtreeFlags=0,r.deletions=null),r.flags=e.flags&14680064,r.childLanes=e.childLanes,r.lanes=e.lanes,r.child=e.child,r.memoizedProps=e.memoizedProps,r.memoizedState=e.memoizedState,r.updateQueue=e.updateQueue,t=e.dependencies,r.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},r.sibling=e.sibling,r.index=e.index,r.ref=e.ref,r}function yn(e,t,r,s,i,o){var c=2;if(s=e,typeof e=="function")_c(e)&&(c=1);else if(typeof e=="string")c=5;else e:switch(e){case Jr:return Br(r.children,i,o,t);case Pl:c=8,i|=8;break;case pa:return e=yt(12,r,t,i|2),e.elementType=pa,e.lanes=o,e;case ma:return e=yt(13,r,t,i),e.elementType=ma,e.lanes=o,e;case _a:return e=yt(19,r,t,i),e.elementType=_a,e.lanes=o,e;case Vh:return uo(r,i,o,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case $h:c=10;break e;case Wh:c=9;break e;case Bl:c=11;break e;case jl:c=14;break e;case sr:c=16,s=null;break e}throw Error(K(130,e==null?e:typeof e,""))}return t=yt(c,r,t,i),t.elementType=e,t.type=s,t.lanes=o,t}function Br(e,t,r,s){return e=yt(7,e,s,t),e.lanes=r,e}function uo(e,t,r,s){return e=yt(22,e,s,t),e.elementType=Vh,e.lanes=r,e.stateNode={isHidden:!1},e}function Go(e,t,r){return e=yt(6,e,null,t),e.lanes=r,e}function Jo(e,t,r){return t=yt(4,e.children!==null?e.children:[],e.key,t),t.lanes=r,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function mg(e,t,r,s,i){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Do(0),this.expirationTimes=Do(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Do(0),this.identifierPrefix=s,this.onRecoverableError=i,this.mutableSourceEagerHydrationData=null}function gc(e,t,r,s,i,o,c,n,a){return e=new mg(e,t,r,n,a),t===1?(t=1,o===!0&&(t|=8)):t=0,o=yt(3,null,null,t),e.current=o,o.stateNode=e,o.memoizedState={element:s,isDehydrated:r,cache:null,transitions:null,pendingSuspenseBoundaries:null},ec(o),e}function _g(e,t,r){var s=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(Hf)}catch(e){console.error(e)}}Hf(),Fh.exports=ft;var xg=Fh.exports,qu=xg;da.createRoot=qu.createRoot,da.hydrateRoot=qu.hydrateRoot;/** + * @remix-run/router v1.23.2 + * + * Copyright (c) Remix Software Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license MIT + */function yi(){return yi=Object.assign?Object.assign.bind():function(e){for(var t=1;t"u")throw new Error(t)}function xc(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function wg(){return Math.random().toString(36).substr(2,8)}function Xu(e,t){return{usr:e.state,key:e.key,idx:t}}function nl(e,t,r,s){return r===void 0&&(r=null),yi({pathname:typeof e=="string"?e:e.pathname,search:"",hash:""},typeof t=="string"?ks(t):t,{state:r,key:t&&t.key||s||wg()})}function Qn(e){let{pathname:t="/",search:r="",hash:s=""}=e;return r&&r!=="?"&&(t+=r.charAt(0)==="?"?r:"?"+r),s&&s!=="#"&&(t+=s.charAt(0)==="#"?s:"#"+s),t}function ks(e){let t={};if(e){let r=e.indexOf("#");r>=0&&(t.hash=e.substr(r),e=e.substr(0,r));let s=e.indexOf("?");s>=0&&(t.search=e.substr(s),e=e.substr(0,s)),e&&(t.pathname=e)}return t}function Cg(e,t,r,s){s===void 0&&(s={});let{window:i=document.defaultView,v5Compat:o=!1}=s,c=i.history,n=cr.Pop,a=null,f=m();f==null&&(f=0,c.replaceState(yi({},c.state,{idx:f}),""));function m(){return(c.state||{idx:null}).idx}function p(){n=cr.Pop;let u=m(),h=u==null?null:u-f;f=u,a&&a({action:n,location:y.location,delta:h})}function _(u,h){n=cr.Push;let l=nl(y.location,u,h);f=m()+1;let d=Xu(l,f),g=y.createHref(l);try{c.pushState(d,"",g)}catch(x){if(x instanceof DOMException&&x.name==="DataCloneError")throw x;i.location.assign(g)}o&&a&&a({action:n,location:y.location,delta:1})}function S(u,h){n=cr.Replace;let l=nl(y.location,u,h);f=m();let d=Xu(l,f),g=y.createHref(l);c.replaceState(d,"",g),o&&a&&a({action:n,location:y.location,delta:0})}function b(u){let h=i.location.origin!=="null"?i.location.origin:i.location.href,l=typeof u=="string"?u:Qn(u);return l=l.replace(/ $/,"%20"),Re(h,"No window.location.(origin|href) available to create URL for href: "+l),new URL(l,h)}let y={get action(){return n},get location(){return e(i,c)},listen(u){if(a)throw new Error("A history only accepts one active listener");return i.addEventListener(Ku,p),a=u,()=>{i.removeEventListener(Ku,p),a=null}},createHref(u){return t(i,u)},createURL:b,encodeLocation(u){let h=b(u);return{pathname:h.pathname,search:h.search,hash:h.hash}},push:_,replace:S,go(u){return c.go(u)}};return y}var Gu;(function(e){e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error"})(Gu||(Gu={}));function Eg(e,t,r){return r===void 0&&(r="/"),kg(e,t,r)}function kg(e,t,r,s){let i=typeof t=="string"?ks(t):t,o=bc(i.pathname||"/",r);if(o==null)return null;let c=Uf(e);Rg(c);let n=null;for(let a=0;n==null&&a{let a={relativePath:n===void 0?o.path||"":n,caseSensitive:o.caseSensitive===!0,childrenIndex:c,route:o};a.relativePath.startsWith("/")&&(Re(a.relativePath.startsWith(s),'Absolute route path "'+a.relativePath+'" nested under path '+('"'+s+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),a.relativePath=a.relativePath.slice(s.length));let f=vr([s,a.relativePath]),m=r.concat(a);o.children&&o.children.length>0&&(Re(o.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+f+'".')),Uf(o.children,t,m,f)),!(o.path==null&&!o.index)&&t.push({path:f,score:Pg(f,o.index),routesMeta:m})};return e.forEach((o,c)=>{var n;if(o.path===""||!((n=o.path)!=null&&n.includes("?")))i(o,c);else for(let a of zf(o.path))i(o,c,a)}),t}function zf(e){let t=e.split("/");if(t.length===0)return[];let[r,...s]=t,i=r.endsWith("?"),o=r.replace(/\?$/,"");if(s.length===0)return i?[o,""]:[o];let c=zf(s.join("/")),n=[];return n.push(...c.map(a=>a===""?o:[o,a].join("/"))),i&&n.push(...c),n.map(a=>e.startsWith("/")&&a===""?"/":a)}function Rg(e){e.sort((t,r)=>t.score!==r.score?r.score-t.score:Bg(t.routesMeta.map(s=>s.childrenIndex),r.routesMeta.map(s=>s.childrenIndex)))}const Tg=/^:[\w-]+$/,Lg=3,Dg=2,Ag=1,Og=10,Ng=-2,Ju=e=>e==="*";function Pg(e,t){let r=e.split("/"),s=r.length;return r.some(Ju)&&(s+=Ng),t&&(s+=Dg),r.filter(i=>!Ju(i)).reduce((i,o)=>i+(Tg.test(o)?Lg:o===""?Ag:Og),s)}function Bg(e,t){return e.length===t.length&&e.slice(0,-1).every((s,i)=>s===t[i])?e[e.length-1]-t[t.length-1]:0}function jg(e,t,r){let{routesMeta:s}=e,i={},o="/",c=[];for(let n=0;n{let{paramName:_,isOptional:S}=m;if(_==="*"){let y=n[p]||"";c=o.slice(0,o.length-y.length).replace(/(.)\/+$/,"$1")}const b=n[p];return S&&!b?f[_]=void 0:f[_]=(b||"").replace(/%2F/g,"/"),f},{}),pathname:o,pathnameBase:c,pattern:e}}function Ig(e,t,r){t===void 0&&(t=!1),r===void 0&&(r=!0),xc(e==="*"||!e.endsWith("*")||e.endsWith("/*"),'Route path "'+e+'" will be treated as if it were '+('"'+e.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+e.replace(/\*$/,"/*")+'".'));let s=[],i="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(c,n,a)=>(s.push({paramName:n,isOptional:a!=null}),a?"/?([^\\/]+)?":"/([^\\/]+)"));return e.endsWith("*")?(s.push({paramName:"*"}),i+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):r?i+="\\/*$":e!==""&&e!=="/"&&(i+="(?:(?=\\/|$))"),[new RegExp(i,t?void 0:"i"),s]}function Fg(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return xc(!1,'The URL path "'+e+'" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent '+("encoding ("+t+").")),e}}function bc(e,t){if(t==="/")return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let r=t.endsWith("/")?t.length-1:t.length,s=e.charAt(r);return s&&s!=="/"?null:e.slice(r)||"/"}const Hg=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,Ug=e=>Hg.test(e);function zg(e,t){t===void 0&&(t="/");let{pathname:r,search:s="",hash:i=""}=typeof e=="string"?ks(e):e,o;if(r)if(Ug(r))o=r;else{if(r.includes("//")){let c=r;r=r.replace(/\/\/+/g,"/"),xc(!1,"Pathnames cannot have embedded double slashes - normalizing "+(c+" -> "+r))}r.startsWith("/")?o=Qu(r.substring(1),"/"):o=Qu(r,t)}else o=t;return{pathname:o,search:Vg(s),hash:qg(i)}}function Qu(e,t){let r=t.replace(/\/+$/,"").split("/");return e.split("/").forEach(i=>{i===".."?r.length>1&&r.pop():i!=="."&&r.push(i)}),r.length>1?r.join("/"):"/"}function Qo(e,t,r,s){return"Cannot include a '"+e+"' character in a manually specified "+("`to."+t+"` field ["+JSON.stringify(s)+"]. Please separate it out to the ")+("`to."+r+"` field. Alternatively you may provide the full path as ")+'a string in and the router will parse it for you.'}function $g(e){return e.filter((t,r)=>r===0||t.route.path&&t.route.path.length>0)}function $f(e,t){let r=$g(e);return t?r.map((s,i)=>i===r.length-1?s.pathname:s.pathnameBase):r.map(s=>s.pathnameBase)}function Wf(e,t,r,s){s===void 0&&(s=!1);let i;typeof e=="string"?i=ks(e):(i=yi({},e),Re(!i.pathname||!i.pathname.includes("?"),Qo("?","pathname","search",i)),Re(!i.pathname||!i.pathname.includes("#"),Qo("#","pathname","hash",i)),Re(!i.search||!i.search.includes("#"),Qo("#","search","hash",i)));let o=e===""||i.pathname==="",c=o?"/":i.pathname,n;if(c==null)n=r;else{let p=t.length-1;if(!s&&c.startsWith("..")){let _=c.split("/");for(;_[0]==="..";)_.shift(),p-=1;i.pathname=_.join("/")}n=p>=0?t[p]:"/"}let a=zg(i,n),f=c&&c!=="/"&&c.endsWith("/"),m=(o||c===".")&&r.endsWith("/");return!a.pathname.endsWith("/")&&(f||m)&&(a.pathname+="/"),a}const vr=e=>e.join("/").replace(/\/\/+/g,"/"),Wg=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),Vg=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,qg=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e;function Kg(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}const Vf=["post","put","patch","delete"];new Set(Vf);const Xg=["get",...Vf];new Set(Xg);/** + * React Router v6.30.3 + * + * Copyright (c) Remix Software Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license MIT + */function Si(){return Si=Object.assign?Object.assign.bind():function(e){for(var t=1;t{n.current=!0}),M.useCallback(function(f,m){if(m===void 0&&(m={}),!n.current)return;if(typeof f=="number"){s.go(f);return}let p=Wf(f,JSON.parse(c),o,m.relative==="path");e==null&&t!=="/"&&(p.pathname=p.pathname==="/"?t:vr([t,p.pathname])),(m.replace?s.replace:s.push)(p,m.state,m)},[t,s,c,o,e])}function Yg(){let{matches:e}=M.useContext(kr),t=e[e.length-1];return t?t.params:{}}function Xf(e,t){let{relative:r}=t===void 0?{}:t,{future:s}=M.useContext(Vr),{matches:i}=M.useContext(kr),{pathname:o}=Ti(),c=JSON.stringify($f(i,s.v7_relativeSplatPath));return M.useMemo(()=>Wf(e,JSON.parse(c),o,r==="path"),[e,c,o,r])}function Zg(e,t){return ev(e,t)}function ev(e,t,r,s){Ri()||Re(!1);let{navigator:i}=M.useContext(Vr),{matches:o}=M.useContext(kr),c=o[o.length-1],n=c?c.params:{};c&&c.pathname;let a=c?c.pathnameBase:"/";c&&c.route;let f=Ti(),m;if(t){var p;let u=typeof t=="string"?ks(t):t;a==="/"||(p=u.pathname)!=null&&p.startsWith(a)||Re(!1),m=u}else m=f;let _=m.pathname||"/",S=_;if(a!=="/"){let u=a.replace(/^\//,"").split("/");S="/"+_.replace(/^\//,"").split("/").slice(u.length).join("/")}let b=Eg(e,{pathname:S}),y=nv(b&&b.map(u=>Object.assign({},u,{params:Object.assign({},n,u.params),pathname:vr([a,i.encodeLocation?i.encodeLocation(u.pathname).pathname:u.pathname]),pathnameBase:u.pathnameBase==="/"?a:vr([a,i.encodeLocation?i.encodeLocation(u.pathnameBase).pathname:u.pathnameBase])})),o,r,s);return t&&y?M.createElement(_o.Provider,{value:{location:Si({pathname:"/",search:"",hash:"",state:null,key:"default"},m),navigationType:cr.Pop}},y):y}function tv(){let e=cv(),t=Kg(e)?e.status+" "+e.statusText:e instanceof Error?e.message:JSON.stringify(e),r=e instanceof Error?e.stack:null,i={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return M.createElement(M.Fragment,null,M.createElement("h2",null,"Unexpected Application Error!"),M.createElement("h3",{style:{fontStyle:"italic"}},t),r?M.createElement("pre",{style:i},r):null,null)}const rv=M.createElement(tv,null);class sv extends M.Component{constructor(t){super(t),this.state={location:t.location,revalidation:t.revalidation,error:t.error}}static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,r){return r.location!==t.location||r.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:r.error,location:r.location,revalidation:t.revalidation||r.revalidation}}componentDidCatch(t,r){console.error("React Router caught the following error during render",t,r)}render(){return this.state.error!==void 0?M.createElement(kr.Provider,{value:this.props.routeContext},M.createElement(qf.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function iv(e){let{routeContext:t,match:r,children:s}=e,i=M.useContext(wc);return i&&i.static&&i.staticContext&&(r.route.errorElement||r.route.ErrorBoundary)&&(i.staticContext._deepestRenderedBoundaryId=r.route.id),M.createElement(kr.Provider,{value:t},s)}function nv(e,t,r,s){var i;if(t===void 0&&(t=[]),r===void 0&&(r=null),s===void 0&&(s=null),e==null){var o;if(!r)return null;if(r.errors)e=r.matches;else if((o=s)!=null&&o.v7_partialHydration&&t.length===0&&!r.initialized&&r.matches.length>0)e=r.matches;else return null}let c=e,n=(i=r)==null?void 0:i.errors;if(n!=null){let m=c.findIndex(p=>p.route.id&&(n==null?void 0:n[p.route.id])!==void 0);m>=0||Re(!1),c=c.slice(0,Math.min(c.length,m+1))}let a=!1,f=-1;if(r&&s&&s.v7_partialHydration)for(let m=0;m=0?c=c.slice(0,f+1):c=[c[0]];break}}}return c.reduceRight((m,p,_)=>{let S,b=!1,y=null,u=null;r&&(S=n&&p.route.id?n[p.route.id]:void 0,y=p.route.errorElement||rv,a&&(f<0&&_===0?(hv("route-fallback"),b=!0,u=null):f===_&&(b=!0,u=p.route.hydrateFallbackElement||null)));let h=t.concat(c.slice(0,_+1)),l=()=>{let d;return S?d=y:b?d=u:p.route.Component?d=M.createElement(p.route.Component,null):p.route.element?d=p.route.element:d=m,M.createElement(iv,{match:p,routeContext:{outlet:m,matches:h,isDataRoute:r!=null},children:d})};return r&&(p.route.ErrorBoundary||p.route.errorElement||_===0)?M.createElement(sv,{location:r.location,revalidation:r.revalidation,component:y,error:S,children:l(),routeContext:{outlet:null,matches:h,isDataRoute:!0}}):l()},null)}var Gf=function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e}(Gf||{}),Jf=function(e){return e.UseBlocker="useBlocker",e.UseLoaderData="useLoaderData",e.UseActionData="useActionData",e.UseRouteError="useRouteError",e.UseNavigation="useNavigation",e.UseRouteLoaderData="useRouteLoaderData",e.UseMatches="useMatches",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e.UseRouteId="useRouteId",e}(Jf||{});function ov(e){let t=M.useContext(wc);return t||Re(!1),t}function av(e){let t=M.useContext(Gg);return t||Re(!1),t}function lv(e){let t=M.useContext(kr);return t||Re(!1),t}function Qf(e){let t=lv(),r=t.matches[t.matches.length-1];return r.route.id||Re(!1),r.route.id}function cv(){var e;let t=M.useContext(qf),r=av(),s=Qf();return t!==void 0?t:(e=r.errors)==null?void 0:e[s]}function uv(){let{router:e}=ov(Gf.UseNavigateStable),t=Qf(Jf.UseNavigateStable),r=M.useRef(!1);return Kf(()=>{r.current=!0}),M.useCallback(function(i,o){o===void 0&&(o={}),r.current&&(typeof i=="number"?e.navigate(i):e.navigate(i,Si({fromRouteId:t},o)))},[e,t])}const Yu={};function hv(e,t,r){Yu[e]||(Yu[e]=!0)}function dv(e,t){e==null||e.v7_startTransition,e==null||e.v7_relativeSplatPath}function Ve(e){Re(!1)}function fv(e){let{basename:t="/",children:r=null,location:s,navigationType:i=cr.Pop,navigator:o,static:c=!1,future:n}=e;Ri()&&Re(!1);let a=t.replace(/^\/*/,"/"),f=M.useMemo(()=>({basename:a,navigator:o,static:c,future:Si({v7_relativeSplatPath:!1},n)}),[a,n,o,c]);typeof s=="string"&&(s=ks(s));let{pathname:m="/",search:p="",hash:_="",state:S=null,key:b="default"}=s,y=M.useMemo(()=>{let u=bc(m,a);return u==null?null:{location:{pathname:u,search:p,hash:_,state:S,key:b},navigationType:i}},[a,m,p,_,S,b,i]);return y==null?null:M.createElement(Vr.Provider,{value:f},M.createElement(_o.Provider,{children:r,value:y}))}function pv(e){let{children:t,location:r}=e;return Zg(ol(t),r)}new Promise(()=>{});function ol(e,t){t===void 0&&(t=[]);let r=[];return M.Children.forEach(e,(s,i)=>{if(!M.isValidElement(s))return;let o=[...t,i];if(s.type===M.Fragment){r.push.apply(r,ol(s.props.children,o));return}s.type!==Ve&&Re(!1),!s.props.index||!s.props.children||Re(!1);let c={id:s.props.id||o.join("-"),caseSensitive:s.props.caseSensitive,element:s.props.element,Component:s.props.Component,index:s.props.index,path:s.props.path,loader:s.props.loader,action:s.props.action,errorElement:s.props.errorElement,ErrorBoundary:s.props.ErrorBoundary,hasErrorBoundary:s.props.ErrorBoundary!=null||s.props.errorElement!=null,shouldRevalidate:s.props.shouldRevalidate,handle:s.props.handle,lazy:s.props.lazy};s.props.children&&(c.children=ol(s.props.children,o)),r.push(c)}),r}/** + * React Router DOM v6.30.3 + * + * Copyright (c) Remix Software Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license MIT + */function al(){return al=Object.assign?Object.assign.bind():function(e){for(var t=1;t=0)&&(r[i]=e[i]);return r}function _v(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function gv(e,t){return e.button===0&&(!t||t==="_self")&&!_v(e)}const vv=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],yv="6";try{window.__reactRouterVersion=yv}catch{}const Sv="startTransition",Zu=um[Sv];function xv(e){let{basename:t,children:r,future:s,window:i}=e,o=M.useRef();o.current==null&&(o.current=bg({window:i,v5Compat:!0}));let c=o.current,[n,a]=M.useState({action:c.action,location:c.location}),{v7_startTransition:f}=s||{},m=M.useCallback(p=>{f&&Zu?Zu(()=>a(p)):a(p)},[a,f]);return M.useLayoutEffect(()=>c.listen(m),[c,m]),M.useEffect(()=>dv(s),[s]),M.createElement(fv,{basename:t,children:r,location:n.location,navigationType:n.action,navigator:c,future:s})}const bv=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",wv=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,Cv=M.forwardRef(function(t,r){let{onClick:s,relative:i,reloadDocument:o,replace:c,state:n,target:a,to:f,preventScrollReset:m,viewTransition:p}=t,_=mv(t,vv),{basename:S}=M.useContext(Vr),b,y=!1;if(typeof f=="string"&&wv.test(f)&&(b=f,bv))try{let d=new URL(window.location.href),g=f.startsWith("//")?new URL(d.protocol+f):new URL(f),x=bc(g.pathname,S);g.origin===d.origin&&x!=null?f=x+g.search+g.hash:y=!0}catch{}let u=Jg(f,{relative:i}),h=Ev(f,{replace:c,state:n,target:a,preventScrollReset:m,relative:i,viewTransition:p});function l(d){s&&s(d),d.defaultPrevented||h(d)}return M.createElement("a",al({},_,{href:b||u,onClick:y||o?s:l,ref:r,target:a}))});var eh;(function(e){e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e.useViewTransitionState="useViewTransitionState"})(eh||(eh={}));var th;(function(e){e.UseFetcher="useFetcher",e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration"})(th||(th={}));function Ev(e,t){let{target:r,replace:s,state:i,preventScrollReset:o,relative:c,viewTransition:n}=t===void 0?{}:t,a=Cc(),f=Ti(),m=Xf(e,{relative:c});return M.useCallback(p=>{if(gv(p,r)){p.preventDefault();let _=s!==void 0?s:Qn(f)===Qn(m);a(e,{replace:_,state:i,preventScrollReset:o,relative:c,viewTransition:n})}},[f,a,m,s,i,r,e,o,c,n])}const kv={user:null,theme:localStorage.getItem("dune-theme")||"emperor",connectionStatus:{database:!0,ssh:!0,bgd:!0,rmq:!0},toasts:[]};let Rv=0;function Tv(e,t){switch(t.type){case"SET_USER":return{...e,user:t.payload};case"SET_THEME":return{...e,theme:t.payload};case"SET_CONNECTION":return{...e,connectionStatus:{...e.connectionStatus,...t.payload}};case"ADD_TOAST":return{...e,toasts:[...e.toasts.slice(-2),{...t.payload,id:++Rv}]};case"REMOVE_TOAST":return{...e,toasts:e.toasts.filter(r=>r.id!==t.payload)};default:return e}}const Yf=M.createContext(null);function Lv({children:e}){const[t,r]=M.useReducer(Tv,kv);return M.useEffect(()=>{document.documentElement.dataset.theme=t.theme,localStorage.setItem("dune-theme",t.theme)},[t.theme]),v.jsx(Yf.Provider,{value:{state:t,dispatch:r},children:e})}function Fe(){const e=M.useContext(Yf);if(!e)throw new Error("useApp must be used within AppProvider");return e}function Dv(){const{dispatch:e}=Fe(),t=M.useRef(null);M.useEffect(()=>{const r=new EventSource("/api/events/stream");return t.current=r,r.onopen=()=>{console.log("[SSE] Connected")},r.addEventListener("battlegroup_update",s=>{try{const i=JSON.parse(s.data);console.log("[SSE] battlegroup_update",i)}catch{}}),r.addEventListener("rmq_health",s=>{try{const i=JSON.parse(s.data);console.log("[SSE] rmq_health",i)}catch{}}),r.addEventListener("connection_status",s=>{try{const i=JSON.parse(s.data);e({type:"SET_CONNECTION",payload:i})}catch{}}),r.addEventListener("chat_message",s=>{try{const i=JSON.parse(s.data);console.log("[SSE] chat_message",i)}catch{}}),r.onerror=()=>{console.warn("[SSE] Connection error")},()=>{r.close()}},[e])}const Av=[{key:"default",label:"Classic Dune"},{key:"atreides",label:"House Atreides"},{key:"harkonnen",label:"House Harkonnen"},{key:"fremen",label:"Fremen"},{key:"bene-gesserit",label:"Bene Gesserit"},{key:"spacing-guild",label:"Spacing Guild"},{key:"emperor",label:"Emperor"},{key:"corrino",label:"House Corrino"},{key:"mentat",label:"Mentat"},{key:"sardaukar",label:"Sardaukar"},{key:"tleilax",label:"Bene Tleilax"},{key:"ordos",label:"House Ordos"},{key:"ix",label:"Ix"},{key:"choam",label:"CHOAM"}];function Ov(){const{state:e,dispatch:t}=Fe(),[r,s]=M.useState(!1),i=M.useRef(null);return M.useEffect(()=>{function o(c){i.current&&!i.current.contains(c.target)&&s(!1)}return document.addEventListener("mousedown",o),()=>document.removeEventListener("mousedown",o)},[]),v.jsxs("div",{className:"relative",ref:i,children:[v.jsx("button",{onClick:()=>s(!r),className:"w-6 h-6 rounded-full",style:{background:"linear-gradient(135deg, var(--primary) 50%, var(--bg) 50%)"},title:"Change theme"}),r&&v.jsx("div",{className:"absolute right-0 mt-2 w-56 bg-card-bg border border-border rounded-lg shadow-xl z-50 py-2",children:Av.map(o=>v.jsxs("button",{onClick:()=>{t({type:"SET_THEME",payload:o.key}),s(!1)},className:`w-full text-left px-4 py-2 text-sm flex items-center gap-3 hover:bg-hover transition-colors ${e.theme===o.key?"text-primary font-semibold":"text-text-secondary"}`,children:[v.jsx("span",{className:"w-4 h-4 rounded border border-border",style:{background:"linear-gradient(135deg, var(--primary) 50%, var(--bg) 50%)"}}),o.label]},o.key))})]})}function Nv(){const{state:e}=Fe(),{database:t,ssh:r,bgd:s,rmq:i}=e.connectionStatus,o=t&&r&&s&&i,c=!o&&(t||r||s||i);return v.jsx("div",{className:"flex items-center gap-2",children:v.jsx("div",{className:"w-2.5 h-2.5 rounded-full",style:{backgroundColor:o?"#27ae60":c?"#f39c12":"#c0392b",boxShadow:`0 0 6px ${o?"#27ae60":c?"#f39c12":"#c0392b"}`},title:`DB: ${t?"OK":"DOWN"} | SSH: ${r?"OK":"DOWN"} | BGD: ${s?"OK":"DOWN"} | RMQ: ${i?"OK":"DOWN"}`})})}const Pv=[{path:"/",label:"Overview"},{path:"/players",label:"Players"},{path:"/guilds",label:"Guilds"},{path:"/vehicles",label:"Vehicles"},{path:"/buildings",label:"Buildings"},{path:"/map",label:"Map"},{path:"/accounts",label:"Accounts"},{path:"/server",label:"Server"},{path:"/chat",label:"Chat"},{path:"/admin",label:"Admin"},{path:"/files",label:"Files"},{path:"/director",label:"Director"},{path:"/settings",label:"Settings"},{path:"/shell",label:"Shell"}];function Bv(){const e=Ti(),{state:t}=Fe();return v.jsxs("nav",{className:"sticky top-0 z-50 h-[52px] bg-nav-bg flex items-center px-6 shadow-md border-b border-border",children:[v.jsxs("div",{className:"flex items-center gap-2 mr-8",children:[v.jsx("span",{className:"text-primary font-serif font-bold text-lg tracking-wide",children:"Dune"}),v.jsx("span",{className:"text-nav-text text-xs uppercase tracking-widest",children:"Admin"})]}),v.jsx("div",{className:"flex items-center gap-1 overflow-x-auto no-scrollbar",children:Pv.map(r=>v.jsx(Cv,{to:r.path,className:`px-4 h-[52px] flex items-center text-[13px] font-medium border-b-2 transition-colors whitespace-nowrap ${e.pathname===r.path||r.path!=="/"&&e.pathname.startsWith(r.path)?"text-nav-active border-nav-active":"text-nav-text border-transparent hover:text-white hover:bg-white/5"}`,children:r.label},r.path))}),v.jsxs("div",{className:"ml-auto flex items-center gap-4",children:[v.jsx(Nv,{}),v.jsx(Ov,{}),t.user&&v.jsx("span",{className:"text-nav-text text-xs",children:t.user})]})]})}function jv(){const{state:e,dispatch:t}=Fe();return M.useEffect(()=>{if(e.toasts.length===0)return;const r=e.toasts.map(s=>setTimeout(()=>{t({type:"REMOVE_TOAST",payload:s.id})},4e3));return()=>r.forEach(clearTimeout)},[e.toasts,t]),e.toasts.length===0?null:v.jsx("div",{className:"fixed top-16 right-6 z-[100] flex flex-col gap-2",children:e.toasts.map(r=>v.jsx("div",{className:`px-4 py-3 rounded-lg shadow-lg text-sm font-medium min-w-[240px] max-w-md border ${r.type==="success"?"bg-success/10 border-success/30 text-success":r.type==="error"?"bg-danger/10 border-danger/30 text-danger":r.type==="warning"?"bg-yellow-500/10 border-yellow-500/30 text-yellow-400":"bg-primary/10 border-primary/30 text-primary"}`,children:r.message},r.id))})}function Mv({children:e}){return v.jsxs("div",{className:"min-h-screen bg-background text-text-primary",children:[v.jsx(Bv,{}),v.jsxs("main",{className:"p-6 max-w-[1600px] mx-auto",children:[v.jsx(jv,{}),e]})]})}function Zf(e,t){return function(){return e.apply(t,arguments)}}const{toString:Iv}=Object.prototype,{getPrototypeOf:go}=Object,{iterator:vo,toStringTag:ep}=Symbol,yo=(e=>t=>{const r=Iv.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),Pt=e=>(e=e.toLowerCase(),t=>yo(t)===e),So=e=>t=>typeof t===e,{isArray:Rs}=Array,xs=So("undefined");function Li(e){return e!==null&&!xs(e)&&e.constructor!==null&&!xs(e.constructor)&&at(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const tp=Pt("ArrayBuffer");function Fv(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&tp(e.buffer),t}const Hv=So("string"),at=So("function"),rp=So("number"),Di=e=>e!==null&&typeof e=="object",Uv=e=>e===!0||e===!1,Sn=e=>{if(yo(e)!=="object")return!1;const t=go(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(ep in e)&&!(vo in e)},zv=e=>{if(!Di(e)||Li(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},$v=Pt("Date"),Wv=Pt("File"),Vv=e=>!!(e&&typeof e.uri<"u"),qv=e=>e&&typeof e.getParts<"u",Kv=Pt("Blob"),Xv=Pt("FileList"),Gv=e=>Di(e)&&at(e.pipe);function Jv(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}}const rh=Jv(),sh=typeof rh.FormData<"u"?rh.FormData:void 0,Qv=e=>{if(!e)return!1;if(sh&&e instanceof sh)return!0;const t=go(e);if(!t||t===Object.prototype||!at(e.append))return!1;const r=yo(e);return r==="formdata"||r==="object"&&at(e.toString)&&e.toString()==="[object FormData]"},Yv=Pt("URLSearchParams"),[Zv,ey,ty,ry]=["ReadableStream","Request","Response","Headers"].map(Pt),sy=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Ai(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let s,i;if(typeof e!="object"&&(e=[e]),Rs(e))for(s=0,i=e.length;s0;)if(i=r[s],t===i.toLowerCase())return i;return null}const Nr=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,ip=e=>!xs(e)&&e!==Nr;function ll(...e){const{caseless:t,skipUndefined:r}=ip(this)&&this||{},s={},i=(o,c)=>{if(c==="__proto__"||c==="constructor"||c==="prototype")return;const n=t&&sp(s,c)||c,a=cl(s,n)?s[n]:void 0;Sn(a)&&Sn(o)?s[n]=ll(a,o):Sn(o)?s[n]=ll({},o):Rs(o)?s[n]=o.slice():(!r||!xs(o))&&(s[n]=o)};for(let o=0,c=e.length;o(Ai(t,(i,o)=>{r&&at(i)?Object.defineProperty(e,o,{__proto__:null,value:Zf(i,r),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(e,o,{__proto__:null,value:i,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:s}),e),ny=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),oy=(e,t,r,s)=>{e.prototype=Object.create(t.prototype,s),Object.defineProperty(e.prototype,"constructor",{__proto__:null,value:e,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(e,"super",{__proto__:null,value:t.prototype}),r&&Object.assign(e.prototype,r)},ay=(e,t,r,s)=>{let i,o,c;const n={};if(t=t||{},e==null)return t;do{for(i=Object.getOwnPropertyNames(e),o=i.length;o-- >0;)c=i[o],(!s||s(c,e,t))&&!n[c]&&(t[c]=e[c],n[c]=!0);e=r!==!1&&go(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},ly=(e,t,r)=>{e=String(e),(r===void 0||r>e.length)&&(r=e.length),r-=t.length;const s=e.indexOf(t,r);return s!==-1&&s===r},cy=e=>{if(!e)return null;if(Rs(e))return e;let t=e.length;if(!rp(t))return null;const r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},uy=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&go(Uint8Array)),hy=(e,t)=>{const s=(e&&e[vo]).call(e);let i;for(;(i=s.next())&&!i.done;){const o=i.value;t.call(e,o[0],o[1])}},dy=(e,t)=>{let r;const s=[];for(;(r=e.exec(t))!==null;)s.push(r);return s},fy=Pt("HTMLFormElement"),py=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,s,i){return s.toUpperCase()+i}),cl=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),my=Pt("RegExp"),np=(e,t)=>{const r=Object.getOwnPropertyDescriptors(e),s={};Ai(r,(i,o)=>{let c;(c=t(i,o,e))!==!1&&(s[o]=c||i)}),Object.defineProperties(e,s)},_y=e=>{np(e,(t,r)=>{if(at(e)&&["arguments","caller","callee"].includes(r))return!1;const s=e[r];if(at(s)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},gy=(e,t)=>{const r={},s=i=>{i.forEach(o=>{r[o]=!0})};return Rs(e)?s(e):s(String(e).split(t)),r},vy=()=>{},yy=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function Sy(e){return!!(e&&at(e.append)&&e[ep]==="FormData"&&e[vo])}const xy=e=>{const t=new WeakSet,r=s=>{if(Di(s)){if(t.has(s))return;if(Li(s))return s;if(!("toJSON"in s)){t.add(s);const i=Rs(s)?[]:{};return Ai(s,(o,c)=>{const n=r(o);!xs(n)&&(i[c]=n)}),t.delete(s),i}}return s};return r(e)},by=Pt("AsyncFunction"),wy=e=>e&&(Di(e)||at(e))&&at(e.then)&&at(e.catch),op=((e,t)=>e?setImmediate:t?((r,s)=>(Nr.addEventListener("message",({source:i,data:o})=>{i===Nr&&o===r&&s.length&&s.shift()()},!1),i=>{s.push(i),Nr.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",at(Nr.postMessage)),Cy=typeof queueMicrotask<"u"?queueMicrotask.bind(Nr):typeof process<"u"&&process.nextTick||op,Ey=e=>e!=null&&at(e[vo]),I={isArray:Rs,isArrayBuffer:tp,isBuffer:Li,isFormData:Qv,isArrayBufferView:Fv,isString:Hv,isNumber:rp,isBoolean:Uv,isObject:Di,isPlainObject:Sn,isEmptyObject:zv,isReadableStream:Zv,isRequest:ey,isResponse:ty,isHeaders:ry,isUndefined:xs,isDate:$v,isFile:Wv,isReactNativeBlob:Vv,isReactNative:qv,isBlob:Kv,isRegExp:my,isFunction:at,isStream:Gv,isURLSearchParams:Yv,isTypedArray:uy,isFileList:Xv,forEach:Ai,merge:ll,extend:iy,trim:sy,stripBOM:ny,inherits:oy,toFlatObject:ay,kindOf:yo,kindOfTest:Pt,endsWith:ly,toArray:cy,forEachEntry:hy,matchAll:dy,isHTMLForm:fy,hasOwnProperty:cl,hasOwnProp:cl,reduceDescriptors:np,freezeMethods:_y,toObjectSet:gy,toCamelCase:py,noop:vy,toFiniteNumber:yy,findKey:sp,global:Nr,isContextDefined:ip,isSpecCompliantForm:Sy,toJSONObject:xy,isAsyncFn:by,isThenable:wy,setImmediate:op,asap:Cy,isIterable:Ey},ky=I.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),Ry=e=>{const t={};let r,s,i;return e&&e.split(` +`).forEach(function(c){i=c.indexOf(":"),r=c.substring(0,i).trim().toLowerCase(),s=c.substring(i+1).trim(),!(!r||t[r]&&ky[r])&&(r==="set-cookie"?t[r]?t[r].push(s):t[r]=[s]:t[r]=t[r]?t[r]+", "+s:s)}),t};function Ty(e){let t=0,r=e.length;for(;tt;){const s=e.charCodeAt(r-1);if(s!==9&&s!==32)break;r-=1}return t===0&&r===e.length?e:e.slice(t,r)}const Ly=new RegExp("[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+","g"),Dy=new RegExp("[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+","g");function Ec(e,t){return I.isArray(e)?e.map(r=>Ec(r,t)):Ty(String(e).replace(t,""))}const Ay=e=>Ec(e,Ly),Oy=e=>Ec(e,Dy);function ap(e){const t=Object.create(null);return I.forEach(e.toJSON(),(r,s)=>{t[s]=Oy(r)}),t}const ih=Symbol("internals");function Is(e){return e&&String(e).trim().toLowerCase()}function xn(e){return e===!1||e==null?e:I.isArray(e)?e.map(xn):Ay(String(e))}function Ny(e){const t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let s;for(;s=r.exec(e);)t[s[1]]=s[2];return t}const Py=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function Yo(e,t,r,s,i){if(I.isFunction(s))return s.call(this,t,r);if(i&&(t=r),!!I.isString(t)){if(I.isString(s))return t.indexOf(s)!==-1;if(I.isRegExp(s))return s.test(t)}}function By(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,r,s)=>r.toUpperCase()+s)}function jy(e,t){const r=I.toCamelCase(" "+t);["get","set","has"].forEach(s=>{Object.defineProperty(e,s+r,{__proto__:null,value:function(i,o,c){return this[s].call(this,t,i,o,c)},configurable:!0})})}let Ye=class{constructor(t){t&&this.set(t)}set(t,r,s){const i=this;function o(n,a,f){const m=Is(a);if(!m)throw new Error("header name must be a non-empty string");const p=I.findKey(i,m);(!p||i[p]===void 0||f===!0||f===void 0&&i[p]!==!1)&&(i[p||a]=xn(n))}const c=(n,a)=>I.forEach(n,(f,m)=>o(f,m,a));if(I.isPlainObject(t)||t instanceof this.constructor)c(t,r);else if(I.isString(t)&&(t=t.trim())&&!Py(t))c(Ry(t),r);else if(I.isObject(t)&&I.isIterable(t)){let n={},a,f;for(const m of t){if(!I.isArray(m))throw TypeError("Object iterator must return a key-value pair");n[f=m[0]]=(a=n[f])?I.isArray(a)?[...a,m[1]]:[a,m[1]]:m[1]}c(n,r)}else t!=null&&o(r,t,s);return this}get(t,r){if(t=Is(t),t){const s=I.findKey(this,t);if(s){const i=this[s];if(!r)return i;if(r===!0)return Ny(i);if(I.isFunction(r))return r.call(this,i,s);if(I.isRegExp(r))return r.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,r){if(t=Is(t),t){const s=I.findKey(this,t);return!!(s&&this[s]!==void 0&&(!r||Yo(this,this[s],s,r)))}return!1}delete(t,r){const s=this;let i=!1;function o(c){if(c=Is(c),c){const n=I.findKey(s,c);n&&(!r||Yo(s,s[n],n,r))&&(delete s[n],i=!0)}}return I.isArray(t)?t.forEach(o):o(t),i}clear(t){const r=Object.keys(this);let s=r.length,i=!1;for(;s--;){const o=r[s];(!t||Yo(this,this[o],o,t,!0))&&(delete this[o],i=!0)}return i}normalize(t){const r=this,s={};return I.forEach(this,(i,o)=>{const c=I.findKey(s,o);if(c){r[c]=xn(i),delete r[o];return}const n=t?By(o):String(o).trim();n!==o&&delete r[o],r[n]=xn(i),s[n]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const r=Object.create(null);return I.forEach(this,(s,i)=>{s!=null&&s!==!1&&(r[i]=t&&I.isArray(s)?s.join(", "):s)}),r}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,r])=>t+": "+r).join(` +`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...r){const s=new this(t);return r.forEach(i=>s.set(i)),s}static accessor(t){const s=(this[ih]=this[ih]={accessors:{}}).accessors,i=this.prototype;function o(c){const n=Is(c);s[n]||(jy(i,c),s[n]=!0)}return I.isArray(t)?t.forEach(o):o(t),this}};Ye.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);I.reduceDescriptors(Ye.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(s){this[r]=s}}});I.freezeMethods(Ye);const My="[REDACTED ****]";function Iy(e){if(I.hasOwnProp(e,"toJSON"))return!0;let t=Object.getPrototypeOf(e);for(;t&&t!==Object.prototype;){if(I.hasOwnProp(t,"toJSON"))return!0;t=Object.getPrototypeOf(t)}return!1}function Fy(e,t){const r=new Set(t.map(o=>String(o).toLowerCase())),s=[],i=o=>{if(o===null||typeof o!="object"||I.isBuffer(o))return o;if(s.indexOf(o)!==-1)return;o instanceof Ye&&(o=o.toJSON()),s.push(o);let c;if(I.isArray(o))c=[],o.forEach((n,a)=>{const f=i(n);I.isUndefined(f)||(c[a]=f)});else{if(!I.isPlainObject(o)&&Iy(o))return s.pop(),o;c=Object.create(null);for(const[n,a]of Object.entries(o)){const f=r.has(n.toLowerCase())?My:i(a);I.isUndefined(f)||(c[n]=f)}}return s.pop(),c};return i(e)}let Z=class lp extends Error{static from(t,r,s,i,o,c){const n=new lp(t.message,r||t.code,s,i,o);return n.cause=t,n.name=t.name,t.status!=null&&n.status==null&&(n.status=t.status),c&&Object.assign(n,c),n}constructor(t,r,s,i,o){super(t),Object.defineProperty(this,"message",{__proto__:null,value:t,enumerable:!0,writable:!0,configurable:!0}),this.name="AxiosError",this.isAxiosError=!0,r&&(this.code=r),s&&(this.config=s),i&&(this.request=i),o&&(this.response=o,this.status=o.status)}toJSON(){const t=this.config,r=t&&I.hasOwnProp(t,"redact")?t.redact:void 0,s=I.isArray(r)&&r.length>0?Fy(t,r):I.toJSONObject(t);return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:s,code:this.code,status:this.status}}};Z.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE";Z.ERR_BAD_OPTION="ERR_BAD_OPTION";Z.ECONNABORTED="ECONNABORTED";Z.ETIMEDOUT="ETIMEDOUT";Z.ECONNREFUSED="ECONNREFUSED";Z.ERR_NETWORK="ERR_NETWORK";Z.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS";Z.ERR_DEPRECATED="ERR_DEPRECATED";Z.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE";Z.ERR_BAD_REQUEST="ERR_BAD_REQUEST";Z.ERR_CANCELED="ERR_CANCELED";Z.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT";Z.ERR_INVALID_URL="ERR_INVALID_URL";Z.ERR_FORM_DATA_DEPTH_EXCEEDED="ERR_FORM_DATA_DEPTH_EXCEEDED";const Hy=null;function ul(e){return I.isPlainObject(e)||I.isArray(e)}function cp(e){return I.endsWith(e,"[]")?e.slice(0,-2):e}function Zo(e,t,r){return e?e.concat(t).map(function(i,o){return i=cp(i),!r&&o?"["+i+"]":i}).join(r?".":""):t}function Uy(e){return I.isArray(e)&&!e.some(ul)}const zy=I.toFlatObject(I,{},null,function(t){return/^is[A-Z]/.test(t)});function xo(e,t,r){if(!I.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,r=I.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(u,h){return!I.isUndefined(h[u])});const s=r.metaTokens,i=r.visitor||p,o=r.dots,c=r.indexes,n=r.Blob||typeof Blob<"u"&&Blob,a=r.maxDepth===void 0?100:r.maxDepth,f=n&&I.isSpecCompliantForm(t);if(!I.isFunction(i))throw new TypeError("visitor must be a function");function m(y){if(y===null)return"";if(I.isDate(y))return y.toISOString();if(I.isBoolean(y))return y.toString();if(!f&&I.isBlob(y))throw new Z("Blob is not supported. Use a Buffer instead.");return I.isArrayBuffer(y)||I.isTypedArray(y)?f&&typeof Blob=="function"?new Blob([y]):Buffer.from(y):y}function p(y,u,h){let l=y;if(I.isReactNative(t)&&I.isReactNativeBlob(y))return t.append(Zo(h,u,o),m(y)),!1;if(y&&!h&&typeof y=="object"){if(I.endsWith(u,"{}"))u=s?u:u.slice(0,-2),y=JSON.stringify(y);else if(I.isArray(y)&&Uy(y)||(I.isFileList(y)||I.endsWith(u,"[]"))&&(l=I.toArray(y)))return u=cp(u),l.forEach(function(g,x){!(I.isUndefined(g)||g===null)&&t.append(c===!0?Zo([u],x,o):c===null?u:u+"[]",m(g))}),!1}return ul(y)?!0:(t.append(Zo(h,u,o),m(y)),!1)}const _=[],S=Object.assign(zy,{defaultVisitor:p,convertValue:m,isVisitable:ul});function b(y,u,h=0){if(!I.isUndefined(y)){if(h>a)throw new Z("Object is too deeply nested ("+h+" levels). Max depth: "+a,Z.ERR_FORM_DATA_DEPTH_EXCEEDED);if(_.indexOf(y)!==-1)throw Error("Circular reference detected in "+u.join("."));_.push(y),I.forEach(y,function(d,g){(!(I.isUndefined(d)||d===null)&&i.call(t,d,I.isString(g)?g.trim():g,u,S))===!0&&b(d,u?u.concat(g):[g],h+1)}),_.pop()}}if(!I.isObject(e))throw new TypeError("data must be an object");return b(e),t}function nh(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"};return encodeURIComponent(e).replace(/[!'()~]|%20/g,function(s){return t[s]})}function kc(e,t){this._pairs=[],e&&xo(e,this,t)}const up=kc.prototype;up.append=function(t,r){this._pairs.push([t,r])};up.toString=function(t){const r=t?function(s){return t.call(this,s,nh)}:nh;return this._pairs.map(function(i){return r(i[0])+"="+r(i[1])},"").join("&")};function $y(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function hp(e,t,r){if(!t)return e;const s=r&&r.encode||$y,i=I.isFunction(r)?{serialize:r}:r,o=i&&i.serialize;let c;if(o?c=o(t,i):c=I.isURLSearchParams(t)?t.toString():new kc(t,i).toString(s),c){const n=e.indexOf("#");n!==-1&&(e=e.slice(0,n)),e+=(e.indexOf("?")===-1?"?":"&")+c}return e}class oh{constructor(){this.handlers=[]}use(t,r,s){return this.handlers.push({fulfilled:t,rejected:r,synchronous:s?s.synchronous:!1,runWhen:s?s.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){I.forEach(this.handlers,function(s){s!==null&&t(s)})}}const Rc={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0},Wy=typeof URLSearchParams<"u"?URLSearchParams:kc,Vy=typeof FormData<"u"?FormData:null,qy=typeof Blob<"u"?Blob:null,Ky={isBrowser:!0,classes:{URLSearchParams:Wy,FormData:Vy,Blob:qy},protocols:["http","https","file","blob","url","data"]},Tc=typeof window<"u"&&typeof document<"u",hl=typeof navigator=="object"&&navigator||void 0,Xy=Tc&&(!hl||["ReactNative","NativeScript","NS"].indexOf(hl.product)<0),Gy=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",Jy=Tc&&window.location.href||"http://localhost",Qy=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Tc,hasStandardBrowserEnv:Xy,hasStandardBrowserWebWorkerEnv:Gy,navigator:hl,origin:Jy},Symbol.toStringTag,{value:"Module"})),Xe={...Qy,...Ky};function Yy(e,t){return xo(e,new Xe.classes.URLSearchParams,{visitor:function(r,s,i,o){return Xe.isNode&&I.isBuffer(r)?(this.append(s,r.toString("base64")),!1):o.defaultVisitor.apply(this,arguments)},...t})}function Zy(e){return I.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function e0(e){const t={},r=Object.keys(e);let s;const i=r.length;let o;for(s=0;s=r.length;return c=!c&&I.isArray(i)?i.length:c,a?(I.hasOwnProp(i,c)?i[c]=I.isArray(i[c])?i[c].concat(s):[i[c],s]:i[c]=s,!n):((!I.hasOwnProp(i,c)||!I.isObject(i[c]))&&(i[c]=[]),t(r,s,i[c],o)&&I.isArray(i[c])&&(i[c]=e0(i[c])),!n)}if(I.isFormData(e)&&I.isFunction(e.entries)){const r={};return I.forEachEntry(e,(s,i)=>{t(Zy(s),i,r,0)}),r}return null}const Xr=(e,t)=>e!=null&&I.hasOwnProp(e,t)?e[t]:void 0;function t0(e,t,r){if(I.isString(e))try{return(t||JSON.parse)(e),I.trim(e)}catch(s){if(s.name!=="SyntaxError")throw s}return(r||JSON.stringify)(e)}const Oi={transitional:Rc,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){const s=r.getContentType()||"",i=s.indexOf("application/json")>-1,o=I.isObject(t);if(o&&I.isHTMLForm(t)&&(t=new FormData(t)),I.isFormData(t))return i?JSON.stringify(dp(t)):t;if(I.isArrayBuffer(t)||I.isBuffer(t)||I.isStream(t)||I.isFile(t)||I.isBlob(t)||I.isReadableStream(t))return t;if(I.isArrayBufferView(t))return t.buffer;if(I.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let n;if(o){const a=Xr(this,"formSerializer");if(s.indexOf("application/x-www-form-urlencoded")>-1)return Yy(t,a).toString();if((n=I.isFileList(t))||s.indexOf("multipart/form-data")>-1){const f=Xr(this,"env"),m=f&&f.FormData;return xo(n?{"files[]":t}:t,m&&new m,a)}}return o||i?(r.setContentType("application/json",!1),t0(t)):t}],transformResponse:[function(t){const r=Xr(this,"transitional")||Oi.transitional,s=r&&r.forcedJSONParsing,i=Xr(this,"responseType"),o=i==="json";if(I.isResponse(t)||I.isReadableStream(t))return t;if(t&&I.isString(t)&&(s&&!i||o)){const n=!(r&&r.silentJSONParsing)&&o;try{return JSON.parse(t,Xr(this,"parseReviver"))}catch(a){if(n)throw a.name==="SyntaxError"?Z.from(a,Z.ERR_BAD_RESPONSE,this,null,Xr(this,"response")):a}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Xe.classes.FormData,Blob:Xe.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};I.forEach(["delete","get","head","post","put","patch","query"],e=>{Oi.headers[e]={}});function ea(e,t){const r=this||Oi,s=t||r,i=Ye.from(s.headers);let o=s.data;return I.forEach(e,function(n){o=n.call(r,o,i.normalize(),t?t.status:void 0)}),i.normalize(),o}function fp(e){return!!(e&&e.__CANCEL__)}let Ni=class extends Z{constructor(t,r,s){super(t??"canceled",Z.ERR_CANCELED,r,s),this.name="CanceledError",this.__CANCEL__=!0}};function pp(e,t,r){const s=r.config.validateStatus;!r.status||!s||s(r.status)?e(r):t(new Z("Request failed with status code "+r.status,r.status>=400&&r.status<500?Z.ERR_BAD_REQUEST:Z.ERR_BAD_RESPONSE,r.config,r.request,r))}function r0(e){const t=/^([-+\w]{1,25}):(?:\/\/)?/.exec(e);return t&&t[1]||""}function s0(e,t){e=e||10;const r=new Array(e),s=new Array(e);let i=0,o=0,c;return t=t!==void 0?t:1e3,function(a){const f=Date.now(),m=s[o];c||(c=f),r[i]=a,s[i]=f;let p=o,_=0;for(;p!==i;)_+=r[p++],p=p%e;if(i=(i+1)%e,i===o&&(o=(o+1)%e),f-c{r=m,i=null,o&&(clearTimeout(o),o=null),e(...f)};return[(...f)=>{const m=Date.now(),p=m-r;p>=s?c(f,m):(i=f,o||(o=setTimeout(()=>{o=null,c(i)},s-p)))},()=>i&&c(i)]}const Yn=(e,t,r=3)=>{let s=0;const i=s0(50,250);return i0(o=>{if(!o||typeof o.loaded!="number")return;const c=o.loaded,n=o.lengthComputable?o.total:void 0,a=n!=null?Math.min(c,n):c,f=Math.max(0,a-s),m=i(f);s=Math.max(s,a);const p={loaded:a,total:n,progress:n?a/n:void 0,bytes:f,rate:m||void 0,estimated:m&&n?(n-a)/m:void 0,event:o,lengthComputable:n!=null,[t?"download":"upload"]:!0};e(p)},r)},ah=(e,t)=>{const r=e!=null;return[s=>t[0]({lengthComputable:r,total:e,loaded:s}),t[1]]},lh=e=>(...t)=>I.asap(()=>e(...t)),n0=Xe.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,Xe.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(Xe.origin),Xe.navigator&&/(msie|trident)/i.test(Xe.navigator.userAgent)):()=>!0,o0=Xe.hasStandardBrowserEnv?{write(e,t,r,s,i,o,c){if(typeof document>"u")return;const n=[`${e}=${encodeURIComponent(t)}`];I.isNumber(r)&&n.push(`expires=${new Date(r).toUTCString()}`),I.isString(s)&&n.push(`path=${s}`),I.isString(i)&&n.push(`domain=${i}`),o===!0&&n.push("secure"),I.isString(c)&&n.push(`SameSite=${c}`),document.cookie=n.join("; ")},read(e){if(typeof document>"u")return null;const t=document.cookie.split(";");for(let r=0;re instanceof Ye?{...e}:e;function zr(e,t){t=t||{};const r=Object.create(null);Object.defineProperty(r,"hasOwnProperty",{__proto__:null,value:Object.prototype.hasOwnProperty,enumerable:!1,writable:!0,configurable:!0});function s(f,m,p,_){return I.isPlainObject(f)&&I.isPlainObject(m)?I.merge.call({caseless:_},f,m):I.isPlainObject(m)?I.merge({},m):I.isArray(m)?m.slice():m}function i(f,m,p,_){if(I.isUndefined(m)){if(!I.isUndefined(f))return s(void 0,f,p,_)}else return s(f,m,p,_)}function o(f,m){if(!I.isUndefined(m))return s(void 0,m)}function c(f,m){if(I.isUndefined(m)){if(!I.isUndefined(f))return s(void 0,f)}else return s(void 0,m)}function n(f,m,p){if(I.hasOwnProp(t,p))return s(f,m);if(I.hasOwnProp(e,p))return s(void 0,f)}const a={url:o,method:o,data:o,baseURL:c,transformRequest:c,transformResponse:c,paramsSerializer:c,timeout:c,timeoutMessage:c,withCredentials:c,withXSRFToken:c,adapter:c,responseType:c,xsrfCookieName:c,xsrfHeaderName:c,onUploadProgress:c,onDownloadProgress:c,decompress:c,maxContentLength:c,maxBodyLength:c,beforeRedirect:c,transport:c,httpAgent:c,httpsAgent:c,cancelToken:c,socketPath:c,allowedSocketPaths:c,responseEncoding:c,validateStatus:n,headers:(f,m,p)=>i(ch(f),ch(m),p,!0)};return I.forEach(Object.keys({...e,...t}),function(m){if(m==="__proto__"||m==="constructor"||m==="prototype")return;const p=I.hasOwnProp(a,m)?a[m]:i,_=I.hasOwnProp(e,m)?e[m]:void 0,S=I.hasOwnProp(t,m)?t[m]:void 0,b=p(_,S,m);I.isUndefined(b)&&p!==n||(r[m]=b)}),r}const c0=["content-type","content-length"];function u0(e,t,r){if(r!=="content-only"){e.set(t);return}Object.entries(t).forEach(([s,i])=>{c0.includes(s.toLowerCase())&&e.set(s,i)})}const h0=e=>encodeURIComponent(e).replace(/%([0-9A-F]{2})/gi,(t,r)=>String.fromCharCode(parseInt(r,16))),_p=e=>{const t=zr({},e),r=_=>I.hasOwnProp(t,_)?t[_]:void 0,s=r("data");let i=r("withXSRFToken");const o=r("xsrfHeaderName"),c=r("xsrfCookieName");let n=r("headers");const a=r("auth"),f=r("baseURL"),m=r("allowAbsoluteUrls"),p=r("url");if(t.headers=n=Ye.from(n),t.url=hp(mp(f,p,m),e.params,e.paramsSerializer),a&&n.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?h0(a.password):""))),I.isFormData(s)&&(Xe.hasStandardBrowserEnv||Xe.hasStandardBrowserWebWorkerEnv?n.setContentType(void 0):I.isFunction(s.getHeaders)&&u0(n,s.getHeaders(),r("formDataHeaderPolicy"))),Xe.hasStandardBrowserEnv&&(I.isFunction(i)&&(i=i(t)),i===!0||i==null&&n0(t.url))){const S=o&&c&&o0.read(c);S&&n.set(o,S)}return t},d0=typeof XMLHttpRequest<"u",f0=d0&&function(e){return new Promise(function(r,s){const i=_p(e);let o=i.data;const c=Ye.from(i.headers).normalize();let{responseType:n,onUploadProgress:a,onDownloadProgress:f}=i,m,p,_,S,b;function y(){S&&S(),b&&b(),i.cancelToken&&i.cancelToken.unsubscribe(m),i.signal&&i.signal.removeEventListener("abort",m)}let u=new XMLHttpRequest;u.open(i.method.toUpperCase(),i.url,!0),u.timeout=i.timeout;function h(){if(!u)return;const d=Ye.from("getAllResponseHeaders"in u&&u.getAllResponseHeaders()),x={data:!n||n==="text"||n==="json"?u.responseText:u.response,status:u.status,statusText:u.statusText,headers:d,config:e,request:u};pp(function(k){r(k),y()},function(k){s(k),y()},x),u=null}"onloadend"in u?u.onloadend=h:u.onreadystatechange=function(){!u||u.readyState!==4||u.status===0&&!(u.responseURL&&u.responseURL.startsWith("file:"))||setTimeout(h)},u.onabort=function(){u&&(s(new Z("Request aborted",Z.ECONNABORTED,e,u)),y(),u=null)},u.onerror=function(g){const x=g&&g.message?g.message:"Network Error",C=new Z(x,Z.ERR_NETWORK,e,u);C.event=g||null,s(C),y(),u=null},u.ontimeout=function(){let g=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const x=i.transitional||Rc;i.timeoutErrorMessage&&(g=i.timeoutErrorMessage),s(new Z(g,x.clarifyTimeoutError?Z.ETIMEDOUT:Z.ECONNABORTED,e,u)),y(),u=null},o===void 0&&c.setContentType(null),"setRequestHeader"in u&&I.forEach(ap(c),function(g,x){u.setRequestHeader(x,g)}),I.isUndefined(i.withCredentials)||(u.withCredentials=!!i.withCredentials),n&&n!=="json"&&(u.responseType=i.responseType),f&&([_,b]=Yn(f,!0),u.addEventListener("progress",_)),a&&u.upload&&([p,S]=Yn(a),u.upload.addEventListener("progress",p),u.upload.addEventListener("loadend",S)),(i.cancelToken||i.signal)&&(m=d=>{u&&(s(!d||d.type?new Ni(null,e,u):d),u.abort(),y(),u=null)},i.cancelToken&&i.cancelToken.subscribe(m),i.signal&&(i.signal.aborted?m():i.signal.addEventListener("abort",m)));const l=r0(i.url);if(l&&!Xe.protocols.includes(l)){s(new Z("Unsupported protocol "+l+":",Z.ERR_BAD_REQUEST,e));return}u.send(o||null)})},p0=(e,t)=>{if(e=e?e.filter(Boolean):[],!t&&!e.length)return;const r=new AbortController;let s=!1;const i=function(a){if(!s){s=!0,c();const f=a instanceof Error?a:this.reason;r.abort(f instanceof Z?f:new Ni(f instanceof Error?f.message:f))}};let o=t&&setTimeout(()=>{o=null,i(new Z(`timeout of ${t}ms exceeded`,Z.ETIMEDOUT))},t);const c=()=>{e&&(o&&clearTimeout(o),o=null,e.forEach(a=>{a.unsubscribe?a.unsubscribe(i):a.removeEventListener("abort",i)}),e=null)};e.forEach(a=>a.addEventListener("abort",i));const{signal:n}=r;return n.unsubscribe=()=>I.asap(c),n},m0=function*(e,t){let r=e.byteLength;if(r{const i=_0(e,t);let o=0,c,n=a=>{c||(c=!0,s&&s(a))};return new ReadableStream({async pull(a){try{const{done:f,value:m}=await i.next();if(f){n(),a.close();return}let p=m.byteLength;if(r){let _=o+=p;r(_)}a.enqueue(new Uint8Array(m))}catch(f){throw n(f),f}},cancel(a){return n(a),i.return()}},{highWaterMark:2})};function v0(e){if(!e||typeof e!="string"||!e.startsWith("data:"))return 0;const t=e.indexOf(",");if(t<0)return 0;const r=e.slice(5,t),s=e.slice(t+1);if(/;base64/i.test(r)){let c=s.length;const n=s.length;for(let S=0;S=48&&b<=57||b>=65&&b<=70||b>=97&&b<=102)&&(y>=48&&y<=57||y>=65&&y<=70||y>=97&&y<=102)&&(c-=2,S+=2)}let a=0,f=n-1;const m=S=>S>=2&&s.charCodeAt(S-2)===37&&s.charCodeAt(S-1)===51&&(s.charCodeAt(S)===68||s.charCodeAt(S)===100);f>=0&&(s.charCodeAt(f)===61?(a++,f--):m(f)&&(a++,f-=3)),a===1&&f>=0&&(s.charCodeAt(f)===61||m(f))&&a++;const _=Math.floor(c/4)*3-(a||0);return _>0?_:0}if(typeof Buffer<"u"&&typeof Buffer.byteLength=="function")return Buffer.byteLength(s,"utf8");let o=0;for(let c=0,n=s.length;c=55296&&a<=56319&&c+1=56320&&f<=57343?(o+=4,c++):o+=3}else o+=3}return o}const Lc="1.16.1",hh=64*1024,{isFunction:Zi}=I,dh=(e,...t)=>{try{return!!e(...t)}catch{return!1}},y0=e=>{const t=I.global!==void 0&&I.global!==null?I.global:globalThis,{ReadableStream:r,TextEncoder:s}=t;e=I.merge.call({skipUndefined:!0},{Request:t.Request,Response:t.Response},e);const{fetch:i,Request:o,Response:c}=e,n=i?Zi(i):typeof fetch=="function",a=Zi(o),f=Zi(c);if(!n)return!1;const m=n&&Zi(r),p=n&&(typeof s=="function"?(h=>l=>h.encode(l))(new s):async h=>new Uint8Array(await new o(h).arrayBuffer())),_=a&&m&&dh(()=>{let h=!1;const l=new o(Xe.origin,{body:new r,method:"POST",get duplex(){return h=!0,"half"}}),d=l.headers.has("Content-Type");return l.body!=null&&l.body.cancel(),h&&!d}),S=f&&m&&dh(()=>I.isReadableStream(new c("").body)),b={stream:S&&(h=>h.body)};n&&["text","arrayBuffer","blob","formData","stream"].forEach(h=>{!b[h]&&(b[h]=(l,d)=>{let g=l&&l[h];if(g)return g.call(l);throw new Z(`Response type '${h}' is not supported`,Z.ERR_NOT_SUPPORT,d)})});const y=async h=>{if(h==null)return 0;if(I.isBlob(h))return h.size;if(I.isSpecCompliantForm(h))return(await new o(Xe.origin,{method:"POST",body:h}).arrayBuffer()).byteLength;if(I.isArrayBufferView(h)||I.isArrayBuffer(h))return h.byteLength;if(I.isURLSearchParams(h)&&(h=h+""),I.isString(h))return(await p(h)).byteLength},u=async(h,l)=>{const d=I.toFiniteNumber(h.getContentLength());return d??y(l)};return async h=>{let{url:l,method:d,data:g,signal:x,cancelToken:C,timeout:k,onDownloadProgress:w,onUploadProgress:E,responseType:L,headers:N,withCredentials:O="same-origin",fetchOptions:P,maxContentLength:F,maxBodyLength:z}=_p(h);const W=I.isNumber(F)&&F>-1,V=I.isNumber(z)&&z>-1;let R=i||fetch;L=L?(L+"").toLowerCase():"text";let D=p0([x,C&&C.toAbortSignal()],k),A=null;const B=D&&D.unsubscribe&&(()=>{D.unsubscribe()});let H;try{if(W&&typeof l=="string"&&l.startsWith("data:")&&v0(l)>F)throw new Z("maxContentLength size of "+F+" exceeded",Z.ERR_BAD_RESPONSE,h,A);if(V&&d!=="get"&&d!=="head"){const j=await u(N,g);if(typeof j=="number"&&isFinite(j)&&j>z)throw new Z("Request body larger than maxBodyLength limit",Z.ERR_BAD_REQUEST,h,A)}if(E&&_&&d!=="get"&&d!=="head"&&(H=await u(N,g))!==0){let j=new o(l,{method:"POST",body:g,duplex:"half"}),$;if(I.isFormData(g)&&($=j.headers.get("content-type"))&&N.setContentType($),j.body){const[U,ee]=ah(H,Yn(lh(E)));g=uh(j.body,hh,U,ee)}}I.isString(O)||(O=O?"include":"omit");const q=a&&"credentials"in o.prototype;if(I.isFormData(g)){const j=N.getContentType();j&&/^multipart\/form-data/i.test(j)&&!/boundary=/i.test(j)&&N.delete("content-type")}N.set("User-Agent","axios/"+Lc,!1);const G={...P,signal:D,method:d.toUpperCase(),headers:ap(N.normalize()),body:g,duplex:"half",credentials:q?O:void 0};A=a&&new o(l,G);let X=await(a?R(A,P):R(l,G));if(W){const j=I.toFiniteNumber(X.headers.get("content-length"));if(j!=null&&j>F)throw new Z("maxContentLength size of "+F+" exceeded",Z.ERR_BAD_RESPONSE,h,A)}const te=S&&(L==="stream"||L==="response");if(S&&X.body&&(w||W||te&&B)){const j={};["status","statusText","headers"].forEach(ce=>{j[ce]=X[ce]});const $=I.toFiniteNumber(X.headers.get("content-length")),[U,ee]=w&&ah($,Yn(lh(w),!0))||[];let J=0;const oe=ce=>{if(W&&(J=ce,J>F))throw new Z("maxContentLength size of "+F+" exceeded",Z.ERR_BAD_RESPONSE,h,A);U&&U(ce)};X=new c(uh(X.body,hh,oe,()=>{ee&&ee(),B&&B()}),j)}L=L||"text";let T=await b[I.findKey(b,L)||"text"](X,h);if(W&&!S&&!te){let j;if(T!=null&&(typeof T.byteLength=="number"?j=T.byteLength:typeof T.size=="number"?j=T.size:typeof T=="string"&&(j=typeof s=="function"?new s().encode(T).byteLength:T.length)),typeof j=="number"&&j>F)throw new Z("maxContentLength size of "+F+" exceeded",Z.ERR_BAD_RESPONSE,h,A)}return!te&&B&&B(),await new Promise((j,$)=>{pp(j,$,{data:T,headers:Ye.from(X.headers),status:X.status,statusText:X.statusText,config:h,request:A})})}catch(q){if(B&&B(),D&&D.aborted&&D.reason instanceof Z){const G=D.reason;throw G.config=h,A&&(G.request=A),q!==G&&(G.cause=q),G}throw q&&q.name==="TypeError"&&/Load failed|fetch/i.test(q.message)?Object.assign(new Z("Network Error",Z.ERR_NETWORK,h,A,q&&q.response),{cause:q.cause||q}):Z.from(q,q&&q.code,h,A,q&&q.response)}}},S0=new Map,gp=e=>{let t=e&&e.env||{};const{fetch:r,Request:s,Response:i}=t,o=[s,i,r];let c=o.length,n=c,a,f,m=S0;for(;n--;)a=o[n],f=m.get(a),f===void 0&&m.set(a,f=n?new Map:y0(t)),m=f;return f};gp();const Dc={http:Hy,xhr:f0,fetch:{get:gp}};I.forEach(Dc,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{__proto__:null,value:t})}catch{}Object.defineProperty(e,"adapterName",{__proto__:null,value:t})}});const fh=e=>`- ${e}`,x0=e=>I.isFunction(e)||e===null||e===!1;function b0(e,t){e=I.isArray(e)?e:[e];const{length:r}=e;let s,i;const o={};for(let c=0;c`adapter ${a} `+(f===!1?"is not supported by the environment":"is not available in the build"));let n=r?c.length>1?`since : +`+c.map(fh).join(` +`):" "+fh(c[0]):"as no adapter specified";throw new Z("There is no suitable adapter to dispatch the request "+n,"ERR_NOT_SUPPORT")}return i}const vp={getAdapter:b0,adapters:Dc};function ta(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Ni(null,e)}function ph(e){return ta(e),e.headers=Ye.from(e.headers),e.data=ea.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),vp.getAdapter(e.adapter||Oi.adapter,e)(e).then(function(s){ta(e),e.response=s;try{s.data=ea.call(e,e.transformResponse,s)}finally{delete e.response}return s.headers=Ye.from(s.headers),s},function(s){if(!fp(s)&&(ta(e),s&&s.response)){e.response=s.response;try{s.response.data=ea.call(e,e.transformResponse,s.response)}finally{delete e.response}s.response.headers=Ye.from(s.response.headers)}return Promise.reject(s)})}const bo={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{bo[e]=function(s){return typeof s===e||"a"+(t<1?"n ":" ")+e}});const mh={};bo.transitional=function(t,r,s){function i(o,c){return"[Axios v"+Lc+"] Transitional option '"+o+"'"+c+(s?". "+s:"")}return(o,c,n)=>{if(t===!1)throw new Z(i(c," has been removed"+(r?" in "+r:"")),Z.ERR_DEPRECATED);return r&&!mh[c]&&(mh[c]=!0,console.warn(i(c," has been deprecated since v"+r+" and will be removed in the near future"))),t?t(o,c,n):!0}};bo.spelling=function(t){return(r,s)=>(console.warn(`${s} is likely a misspelling of ${t}`),!0)};function w0(e,t,r){if(typeof e!="object")throw new Z("options must be an object",Z.ERR_BAD_OPTION_VALUE);const s=Object.keys(e);let i=s.length;for(;i-- >0;){const o=s[i],c=Object.prototype.hasOwnProperty.call(t,o)?t[o]:void 0;if(c){const n=e[o],a=n===void 0||c(n,o,e);if(a!==!0)throw new Z("option "+o+" must be "+a,Z.ERR_BAD_OPTION_VALUE);continue}if(r!==!0)throw new Z("Unknown option "+o,Z.ERR_BAD_OPTION)}}const bn={assertOptions:w0,validators:bo},mt=bn.validators;let jr=class{constructor(t){this.defaults=t||{},this.interceptors={request:new oh,response:new oh}}async request(t,r){try{return await this._request(t,r)}catch(s){if(s instanceof Error){let i={};Error.captureStackTrace?Error.captureStackTrace(i):i=new Error;const o=(()=>{if(!i.stack)return"";const c=i.stack.indexOf(` +`);return c===-1?"":i.stack.slice(c+1)})();try{if(!s.stack)s.stack=o;else if(o){const c=o.indexOf(` +`),n=c===-1?-1:o.indexOf(` +`,c+1),a=n===-1?"":o.slice(n+1);String(s.stack).endsWith(a)||(s.stack+=` +`+o)}}catch{}}throw s}}_request(t,r){typeof t=="string"?(r=r||{},r.url=t):r=t||{},r=zr(this.defaults,r);const{transitional:s,paramsSerializer:i,headers:o}=r;s!==void 0&&bn.assertOptions(s,{silentJSONParsing:mt.transitional(mt.boolean),forcedJSONParsing:mt.transitional(mt.boolean),clarifyTimeoutError:mt.transitional(mt.boolean),legacyInterceptorReqResOrdering:mt.transitional(mt.boolean)},!1),i!=null&&(I.isFunction(i)?r.paramsSerializer={serialize:i}:bn.assertOptions(i,{encode:mt.function,serialize:mt.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),bn.assertOptions(r,{baseUrl:mt.spelling("baseURL"),withXsrfToken:mt.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let c=o&&I.merge(o.common,o[r.method]);o&&I.forEach(["delete","get","head","post","put","patch","query","common"],b=>{delete o[b]}),r.headers=Ye.concat(c,o);const n=[];let a=!0;this.interceptors.request.forEach(function(y){if(typeof y.runWhen=="function"&&y.runWhen(r)===!1)return;a=a&&y.synchronous;const u=r.transitional||Rc;u&&u.legacyInterceptorReqResOrdering?n.unshift(y.fulfilled,y.rejected):n.push(y.fulfilled,y.rejected)});const f=[];this.interceptors.response.forEach(function(y){f.push(y.fulfilled,y.rejected)});let m,p=0,_;if(!a){const b=[ph.bind(this),void 0];for(b.unshift(...n),b.push(...f),_=b.length,m=Promise.resolve(r);p<_;)m=m.then(b[p++],b[p++]);return m}_=n.length;let S=r;for(;p<_;){const b=n[p++],y=n[p++];try{S=b(S)}catch(u){y.call(this,u);break}}try{m=ph.call(this,S)}catch(b){return Promise.reject(b)}for(p=0,_=f.length;p<_;)m=m.then(f[p++],f[p++]);return m}getUri(t){t=zr(this.defaults,t);const r=mp(t.baseURL,t.url,t.allowAbsoluteUrls);return hp(r,t.params,t.paramsSerializer)}};I.forEach(["delete","get","head","options"],function(t){jr.prototype[t]=function(r,s){return this.request(zr(s||{},{method:t,url:r,data:(s||{}).data}))}});I.forEach(["post","put","patch","query"],function(t){function r(s){return function(o,c,n){return this.request(zr(n||{},{method:t,headers:s?{"Content-Type":"multipart/form-data"}:{},url:o,data:c}))}}jr.prototype[t]=r(),t!=="query"&&(jr.prototype[t+"Form"]=r(!0))});let C0=class yp{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let r;this.promise=new Promise(function(o){r=o});const s=this;this.promise.then(i=>{if(!s._listeners)return;let o=s._listeners.length;for(;o-- >0;)s._listeners[o](i);s._listeners=null}),this.promise.then=i=>{let o;const c=new Promise(n=>{s.subscribe(n),o=n}).then(i);return c.cancel=function(){s.unsubscribe(o)},c},t(function(o,c,n){s.reason||(s.reason=new Ni(o,c,n),r(s.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const r=this._listeners.indexOf(t);r!==-1&&this._listeners.splice(r,1)}toAbortSignal(){const t=new AbortController,r=s=>{t.abort(s)};return this.subscribe(r),t.signal.unsubscribe=()=>this.unsubscribe(r),t.signal}static source(){let t;return{token:new yp(function(i){t=i}),cancel:t}}};function E0(e){return function(r){return e.apply(null,r)}}function k0(e){return I.isObject(e)&&e.isAxiosError===!0}const dl={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(dl).forEach(([e,t])=>{dl[t]=e});function Sp(e){const t=new jr(e),r=Zf(jr.prototype.request,t);return I.extend(r,jr.prototype,t,{allOwnKeys:!0}),I.extend(r,t,null,{allOwnKeys:!0}),r.create=function(i){return Sp(zr(e,i))},r}const Ce=Sp(Oi);Ce.Axios=jr;Ce.CanceledError=Ni;Ce.CancelToken=C0;Ce.isCancel=fp;Ce.VERSION=Lc;Ce.toFormData=xo;Ce.AxiosError=Z;Ce.Cancel=Ce.CanceledError;Ce.all=function(t){return Promise.all(t)};Ce.spread=E0;Ce.isAxiosError=k0;Ce.mergeConfig=zr;Ce.AxiosHeaders=Ye;Ce.formToJSON=e=>dp(I.isHTMLForm(e)?new FormData(e):e);Ce.getAdapter=vp.getAdapter;Ce.HttpStatusCode=dl;Ce.default=Ce;const{Axios:t1,AxiosError:r1,CanceledError:s1,isCancel:i1,CancelToken:n1,VERSION:o1,all:a1,Cancel:l1,isAxiosError:c1,spread:u1,toFormData:h1,AxiosHeaders:d1,HttpStatusCode:f1,formToJSON:p1,getAdapter:m1,mergeConfig:_1,create:g1}=Ce,ne=Ce.create({baseURL:"/api",headers:{"Content-Type":"application/json"},timeout:3e4});ne.interceptors.response.use(e=>e,e=>{var t;return((t=e.response)==null?void 0:t.status)===401&&(window.location.href="/login"),Promise.reject(e)});function R0(){const[e,t]=M.useState(null),[r,s]=M.useState(!0),{dispatch:i}=Fe();M.useEffect(()=>{async function c(){try{const a=await ne.get("/stats");a.data.success&&t(a.data.data)}catch(a){console.error(a)}finally{s(!1)}}c();const n=new EventSource("/api/events/stream");return n.addEventListener("metrics",a=>{try{t(JSON.parse(a.data))}catch{}}),()=>n.close()},[]);const o=e?[{label:"Total Players",value:e.total_players.toLocaleString(),icon:"👥"},{label:"Online Players",value:e.online_players.toLocaleString(),icon:"🟢"},{label:"Guilds",value:e.guild_count.toLocaleString(),icon:"🛡️"},{label:"Active Guilds",value:e.active_guilds.toLocaleString(),icon:"⚔️"},{label:"Servers",value:e.server_count.toLocaleString(),icon:"🖥️"},{label:"Partitions",value:e.partition_count.toLocaleString(),icon:"🗺️"},{label:"Total Worth",value:"$"+Math.round(e.total_worth).toLocaleString(),icon:"💰"},{label:"Flavor Text",value:e.total_flavor_text.toLocaleString(),icon:"📝"}]:[];return v.jsxs("div",{children:[v.jsx("h1",{className:"font-serif text-3xl text-primary mb-6",children:"Dashboard Overview"}),r?v.jsx("div",{className:"text-text-muted",children:"Loading metrics..."}):v.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4",children:o.map(c=>v.jsxs("div",{className:"bg-card-bg border border-border rounded-lg p-5 shadow-card",children:[v.jsx("div",{className:"flex items-center justify-between mb-2",children:v.jsx("span",{className:"text-2xl",children:c.icon})}),v.jsx("div",{className:"text-2xl font-bold text-text-primary mb-1",children:c.value}),v.jsx("div",{className:"text-sm text-text-muted",children:c.label})]},c.label))}),v.jsxs("div",{className:"mt-8 grid grid-cols-1 lg:grid-cols-2 gap-6",children:[v.jsxs("div",{className:"bg-card-bg border border-border rounded-lg p-5 shadow-card",children:[v.jsx("h2",{className:"font-serif text-xl text-primary mb-4",children:"Quick Actions"}),v.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[v.jsx(en,{label:"Broadcast Message",onClick:()=>{}}),v.jsx(en,{label:"Player Search",onClick:()=>{}}),v.jsx(en,{label:"Guild Lookup",onClick:()=>{}}),v.jsx(en,{label:"Server Restart",onClick:()=>{}})]})]}),v.jsxs("div",{className:"bg-card-bg border border-border rounded-lg p-5 shadow-card",children:[v.jsx("h2",{className:"font-serif text-xl text-primary mb-4",children:"System Health"}),v.jsxs("div",{className:"space-y-3",children:[v.jsx(tn,{label:"Database",status:"ok",detail:"Connected"}),v.jsx(tn,{label:"SSH Tunnel",status:"ok",detail:"Connected"}),v.jsx(tn,{label:"BG Director",status:"ok",detail:"Connected"}),v.jsx(tn,{label:"RMQ Game",status:"ok",detail:"Connected"})]})]})]})]})}function en({label:e,onClick:t}){return v.jsx("button",{onClick:t,className:"px-4 py-3 bg-primary/10 border border-primary/20 rounded-lg text-primary text-sm font-medium hover:bg-primary/20 transition-colors text-left",children:e})}function tn({label:e,status:t,detail:r}){const s=t==="ok"?"#27ae60":t==="warn"?"#f39c12":"#c0392b";return v.jsxs("div",{className:"flex items-center justify-between text-sm",children:[v.jsxs("div",{className:"flex items-center gap-2",children:[v.jsx("div",{className:"w-2 h-2 rounded-full",style:{backgroundColor:s}}),v.jsx("span",{className:"text-text-secondary",children:e})]}),v.jsx("span",{className:"text-text-muted",children:r})]})}var xp={exports:{}},bp={};/** + * @license React + * use-sync-external-store-shim.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var bs=M;function T0(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var L0=typeof Object.is=="function"?Object.is:T0,D0=bs.useState,A0=bs.useEffect,O0=bs.useLayoutEffect,N0=bs.useDebugValue;function P0(e,t){var r=t(),s=D0({inst:{value:r,getSnapshot:t}}),i=s[0].inst,o=s[1];return O0(function(){i.value=r,i.getSnapshot=t,ra(i)&&o({inst:i})},[e,r,t]),A0(function(){return ra(i)&&o({inst:i}),e(function(){ra(i)&&o({inst:i})})},[e]),N0(r),r}function ra(e){var t=e.getSnapshot;e=e.value;try{var r=t();return!L0(e,r)}catch{return!0}}function B0(e,t){return t()}var j0=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?B0:P0;bp.useSyncExternalStore=bs.useSyncExternalStore!==void 0?bs.useSyncExternalStore:j0;xp.exports=bp;var _h=xp.exports;const wp=0,Cp=1,Ep=2,gh=3;var vh=Object.prototype.hasOwnProperty;function fl(e,t){var r,s;if(e===t)return!0;if(e&&t&&(r=e.constructor)===t.constructor){if(r===Date)return e.getTime()===t.getTime();if(r===RegExp)return e.toString()===t.toString();if(r===Array){if((s=e.length)===t.length)for(;s--&&fl(e[s],t[s]););return s===-1}if(!r||typeof e=="object"){s=0;for(r in e)if(vh.call(e,r)&&++s&&!vh.call(t,r)||!(r in t)||!fl(e[r],t[r]))return!1;return Object.keys(t).length===s}}return e!==e&&t!==t}const qt=new WeakMap,Gt=()=>{},Ke=Gt(),pl=Object,se=e=>e===Ke,It=e=>typeof e=="function",br=(e,t)=>({...e,...t}),kp=e=>It(e.then),sa={},rn={},Ac="undefined",Pi=typeof window!=Ac,ml=typeof document!=Ac,M0=Pi&&"Deno"in window,I0=()=>Pi&&typeof window.requestAnimationFrame!=Ac,Rp=(e,t)=>{const r=qt.get(e);return[()=>!se(t)&&e.get(t)||sa,s=>{if(!se(t)){const i=e.get(t);t in rn||(rn[t]=i),r[5](t,br(i,s),i||sa)}},r[6],()=>!se(t)&&t in rn?rn[t]:!se(t)&&e.get(t)||sa]};let _l=!0;const F0=()=>_l,[gl,vl]=Pi&&window.addEventListener?[window.addEventListener.bind(window),window.removeEventListener.bind(window)]:[Gt,Gt],H0=()=>{const e=ml&&document.visibilityState;return se(e)||e!=="hidden"},U0=e=>(ml&&document.addEventListener("visibilitychange",e),gl("focus",e),()=>{ml&&document.removeEventListener("visibilitychange",e),vl("focus",e)}),z0=e=>{const t=()=>{_l=!0,e()},r=()=>{_l=!1};return gl("online",t),gl("offline",r),()=>{vl("online",t),vl("offline",r)}},$0={isOnline:F0,isVisible:H0},W0={initFocus:U0,initReconnect:z0},yh=!bi.useId,fs=!Pi||M0,V0=e=>I0()?window.requestAnimationFrame(e):setTimeout(e,1),ia=fs?M.useEffect:M.useLayoutEffect,na=typeof navigator<"u"&&navigator.connection,Sh=!fs&&na&&(["slow-2g","2g"].includes(na.effectiveType)||na.saveData),sn=new WeakMap,q0=e=>pl.prototype.toString.call(e),oa=(e,t)=>e===`[object ${t}]`;let K0=0;const yl=e=>{const t=typeof e,r=q0(e),s=oa(r,"Date"),i=oa(r,"RegExp"),o=oa(r,"Object");let c,n;if(pl(e)===e&&!s&&!i){if(c=sn.get(e),c)return c;if(c=++K0+"~",sn.set(e,c),Array.isArray(e)){for(c="@",n=0;n{if(It(e))try{e=e()}catch{e=""}const t=e;return e=typeof e=="string"?e:(Array.isArray(e)?e.length:e)?yl(e):"",[e,t]};let X0=0;const Sl=()=>++X0;async function Tp(...e){const[t,r,s,i]=e,o=br({populateCache:!0,throwOnError:!0},typeof i=="boolean"?{revalidate:i}:i||{});let c=o.populateCache;const n=o.rollbackOnError;let a=o.optimisticData;const f=_=>typeof n=="function"?n(_):n!==!1,m=o.throwOnError;if(It(r)){const _=r,S=[],b=t.keys();for(const y of b)!/^\$(inf|sub)\$/.test(y)&&_(t.get(y)._k)&&S.push(y);return Promise.all(S.map(p))}return p(r);async function p(_){const[S]=Oc(_);if(!S)return;const[b,y]=Rp(t,S),[u,h,l,d]=qt.get(t),g=()=>{const F=u[S];return(It(o.revalidate)?o.revalidate(b().data,_):o.revalidate!==!1)&&(delete l[S],delete d[S],F&&F[0])?F[0](Ep).then(()=>b().data):b().data};if(e.length<3)return g();let x=s,C,k=!1;const w=Sl();h[S]=[w,0];const E=!se(a),L=b(),N=L.data,O=L._c,P=se(O)?N:O;if(E&&(a=It(a)?a(P,N):a,y({data:a,_c:P})),It(x))try{x=x(P)}catch(F){C=F,k=!0}if(x&&kp(x))if(x=await x.catch(F=>{C=F,k=!0}),w!==h[S][0]){if(k)throw C;return x}else k&&E&&f(C)&&(c=!0,y({data:P,_c:Ke}));if(c&&!k)if(It(c)){const F=c(x,P);y({data:F,error:Ke,_c:Ke})}else y({data:x,error:Ke,_c:Ke});if(h[S][1]=Sl(),Promise.resolve(g()).then(()=>{y({_c:Ke})}),k){if(m)throw C;return}return x}}const xh=(e,t)=>{for(const r in e)e[r][0]&&e[r][0](t)},G0=(e,t)=>{if(!qt.has(e)){const r=br(W0,t),s=Object.create(null),i=Tp.bind(Ke,e);let o=Gt;const c=Object.create(null),n=(m,p)=>{const _=c[m]||[];return c[m]=_,_.push(p),()=>_.splice(_.indexOf(p),1)},a=(m,p,_)=>{e.set(m,p);const S=c[m];if(S)for(const b of S)b(p,_)},f=()=>{if(!qt.has(e)&&(qt.set(e,[s,Object.create(null),Object.create(null),Object.create(null),i,a,n]),!fs)){const m=r.initFocus(setTimeout.bind(Ke,xh.bind(Ke,s,wp))),p=r.initReconnect(setTimeout.bind(Ke,xh.bind(Ke,s,Cp)));o=()=>{m&&m(),p&&p(),qt.delete(e)}}};return f(),[e,i,f,o]}return[e,qt.get(e)[4]]},J0=(e,t,r,s,i)=>{const o=r.errorRetryCount,c=i.retryCount,n=~~((Math.random()+.5)*(1<<(c<8?c:8)))*r.errorRetryInterval;!se(o)&&c>o||setTimeout(s,n,i)},Q0=fl,[Lp,Y0]=G0(new Map),Z0=br({onLoadingSlow:Gt,onSuccess:Gt,onError:Gt,onErrorRetry:J0,onDiscarded:Gt,revalidateOnFocus:!0,revalidateOnReconnect:!0,revalidateIfStale:!0,shouldRetryOnError:!0,errorRetryInterval:Sh?1e4:5e3,focusThrottleInterval:5*1e3,dedupingInterval:2*1e3,loadingTimeout:Sh?5e3:3e3,compare:Q0,isPaused:()=>!1,cache:Lp,mutate:Y0,fallback:{}},$0),eS=(e,t)=>{const r=br(e,t);if(t){const{use:s,fallback:i}=e,{use:o,fallback:c}=t;s&&o&&(r.use=s.concat(o)),i&&c&&(r.fallback=br(i,c))}return r},tS=M.createContext({}),rS="$inf$",Dp=Pi&&window.__SWR_DEVTOOLS_USE__,sS=Dp?window.__SWR_DEVTOOLS_USE__:[],iS=()=>{Dp&&(window.__SWR_DEVTOOLS_REACT__=bi)},nS=e=>It(e[1])?[e[0],e[1],e[2]||{}]:[e[0],null,(e[1]===null?e[2]:e[1])||{}],oS=()=>{const e=M.useContext(tS);return M.useMemo(()=>br(Z0,e),[e])},aS=e=>(t,r,s)=>e(t,r&&((...o)=>{const[c]=Oc(t),[,,,n]=qt.get(Lp);if(c.startsWith(rS))return r(...o);const a=n[c];return se(a)?r(...o):(delete n[c],a)}),s),lS=sS.concat(aS),cS=e=>function(...r){const s=oS(),[i,o,c]=nS(r),n=eS(s,c);let a=e;const{use:f}=n,m=(f||[]).concat(lS);for(let p=m.length;p--;)a=m[p](a);return a(i,o||n.fetcher||null,n)},uS=(e,t,r)=>{const s=t[e]||(t[e]=[]);return s.push(r),()=>{const i=s.indexOf(r);i>=0&&(s[i]=s[s.length-1],s.pop())}};iS();const aa=bi.use||(e=>{switch(e.status){case"pending":throw e;case"fulfilled":return e.value;case"rejected":throw e.reason;default:throw e.status="pending",e.then(t=>{e.status="fulfilled",e.value=t},t=>{e.status="rejected",e.reason=t}),e}}),la={dedupe:!0},bh=Promise.resolve(Ke),hS=()=>Gt,dS=(e,t,r)=>{const{cache:s,compare:i,suspense:o,fallbackData:c,revalidateOnMount:n,revalidateIfStale:a,refreshInterval:f,refreshWhenHidden:m,refreshWhenOffline:p,keepPreviousData:_,strictServerPrefetchWarning:S}=r,[b,y,u,h]=qt.get(s),[l,d]=Oc(e),g=M.useRef(!1),x=M.useRef(!1),C=M.useRef(l),k=M.useRef(t),w=M.useRef(r),E=()=>w.current,L=()=>E().isVisible()&&E().isOnline(),[N,O,P,F]=Rp(s,l),z=M.useRef({}).current,W=se(c)?se(r.fallback)?Ke:r.fallback[l]:c,V=(Y,he)=>{for(const fe in z){const pe=fe;if(pe==="data"){if(!i(Y[pe],he[pe])&&(!se(Y[pe])||!i(te,he[pe])))return!1}else if(he[pe]!==Y[pe])return!1}return!0},R=!g.current,D=M.useMemo(()=>{const Y=N(),he=F(),fe=le=>{const Be=br(le);return delete Be._k,(()=>{if(!l||!t||E().isPaused())return!1;if(R&&!se(n))return n;const wt=se(W)?Be.data:W;return se(wt)||a})()?{isValidating:!0,isLoading:!0,...Be}:Be},pe=fe(Y),tt=Y===he?pe:fe(he);let Pe=pe;return[()=>{const le=fe(N());return V(le,Pe)?(Pe.data=le.data,Pe.isLoading=le.isLoading,Pe.isValidating=le.isValidating,Pe.error=le.error,Pe):(Pe=le,le)},()=>tt]},[s,l]),A=_h.useSyncExternalStore(M.useCallback(Y=>P(l,(he,fe)=>{V(fe,he)||Y()}),[s,l]),D[0],D[1]),B=b[l]&&b[l].length>0,H=A.data,q=se(H)?W&&kp(W)?aa(W):W:H,G=A.error,X=M.useRef(q),te=_?se(H)?se(X.current)?q:X.current:H:q,T=l&&se(q),j=M.useRef(null);!fs&&_h.useSyncExternalStore(hS,()=>(j.current=!1,j),()=>(j.current=!0,j));const $=j.current;S&&$&&!o&&T&&console.warn(`Missing pre-initiated data for serialized key "${l}" during server-side rendering. Data fetching should be initiated on the server and provided to SWR via fallback data. You can set "strictServerPrefetchWarning: false" to disable this warning.`);const U=!l||!t||E().isPaused()||B&&!se(G)?!1:R&&!se(n)?n:o?se(q)?!1:a:se(q)||a,ee=R&&U,J=se(A.isValidating)?ee:A.isValidating,oe=se(A.isLoading)?ee:A.isLoading,ce=M.useCallback(async Y=>{const he=k.current;if(!l||!he||x.current||E().isPaused())return!1;let fe,pe,tt=!0;const Pe=Y||{},le=!u[l]||!Pe.dedupe,Be=()=>yh?!x.current&&l===C.current&&g.current:l===C.current,He={isValidating:!1,isLoading:!1},wt=()=>{O(He)},qr=()=>{const Ue=u[l];Ue&&Ue[1]===pe&&delete u[l]},Ct={isValidating:!0};se(N().data)&&(Ct.isLoading=!0);try{if(le&&(O(Ct),r.loadingTimeout&&se(N().data)&&setTimeout(()=>{tt&&Be()&&E().onLoadingSlow(l,r)},r.loadingTimeout),u[l]=[he(d),Sl()]),[fe,pe]=u[l],fe=await fe,le&&setTimeout(qr,r.dedupingInterval),!u[l]||u[l][1]!==pe)return le&&Be()&&E().onDiscarded(l),!1;He.error=Ke;const Ue=y[l];if(!se(Ue)&&(pe<=Ue[0]||pe<=Ue[1]||Ue[1]===0))return wt(),le&&Be()&&E().onDiscarded(l),!1;const De=N().data;He.data=i(De,fe)?De:fe,le&&Be()&&E().onSuccess(fe,l,r)}catch(Ue){qr();const De=E(),{shouldRetryOnError:$t}=De;De.isPaused()||(He.error=Ue,le&&Be()&&(De.onError(Ue,l,De),($t===!0||It($t)&&$t(Ue))&&(!E().revalidateOnFocus||!E().revalidateOnReconnect||L())&&De.onErrorRetry(Ue,l,De,me=>{const Ls=b[l];Ls&&Ls[0]&&Ls[0](gh,me)},{retryCount:(Pe.retryCount||0)+1,dedupe:!0})))}return tt=!1,wt(),!0},[l,s]),Ne=M.useCallback((...Y)=>Tp(s,C.current,...Y),[]);if(ia(()=>{k.current=t,w.current=r,se(H)||(X.current=H)}),ia(()=>{if(!l)return;const Y=ce.bind(Ke,la);let he=0;E().revalidateOnFocus&&(he=Date.now()+E().focusThrottleInterval);const pe=uS(l,b,(tt,Pe={})=>{if(tt==wp){const le=Date.now();E().revalidateOnFocus&&le>he&&L()&&(he=le+E().focusThrottleInterval,Y())}else if(tt==Cp)E().revalidateOnReconnect&&L()&&Y();else{if(tt==Ep)return ce();if(tt==gh)return ce(Pe)}});return x.current=!1,C.current=l,g.current=!0,O({_k:d}),U&&(u[l]||(se(q)||fs?Y():V0(Y))),()=>{x.current=!0,pe()}},[l]),ia(()=>{let Y;function he(){const pe=It(f)?f(N().data):f;pe&&Y!==-1&&(Y=setTimeout(fe,pe))}function fe(){!N().error&&(m||E().isVisible())&&(p||E().isOnline())?ce(la).then(he):he()}return he(),()=>{Y&&(clearTimeout(Y),Y=-1)}},[f,m,p,l]),M.useDebugValue(te),o){if(!yh&&fs&&T)throw new Error("Fallback data is required when using Suspense in SSR.");T&&(k.current=t,w.current=r,x.current=!1);const Y=h[l],he=!se(Y)&&T?Ne(Y):bh;if(aa(he),!se(G)&&T)throw G;const fe=T?ce(la):bh;!se(te)&&T&&(fe.status="fulfilled",fe.value=!0),aa(fe)}return{mutate:Ne,get data(){return z.data=!0,te},get error(){return z.error=!0,G},get isValidating(){return z.isValidating=!0,J},get isLoading(){return z.isLoading=!0,oe}}},ct=cS(dS);function fS(e,t=300){const[r,s]=M.useState(e);return M.useEffect(()=>{const i=setTimeout(()=>s(e),t);return()=>clearTimeout(i)},[e,t]),r}function Bi({columns:e,data:t,onRowClick:r,loading:s}){const[i,o]=M.useState(null),[c,n]=M.useState("asc"),a=m=>{i===m?n(c==="asc"?"desc":"asc"):(o(m),n("asc"))};let f=[...t];if(i){const m=e.find(p=>p.header===i);m&&typeof m.accessor=="string"&&f.sort((p,_)=>{const S=p[m.accessor],b=_[m.accessor];return S==null&&b==null?0:S==null?c==="asc"?1:-1:b==null?c==="asc"?-1:1:typeof S=="string"?c==="asc"?S.localeCompare(b):b.localeCompare(S):typeof S=="number"?c==="asc"?S-b:b-S:0})}return v.jsx("div",{className:"overflow-x-auto rounded-lg border border-border",children:v.jsxs("table",{className:"w-full text-sm",children:[v.jsx("thead",{children:v.jsx("tr",{className:"border-b border-border",children:e.map(m=>v.jsx("th",{className:"text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase tracking-wider cursor-pointer hover:text-text-primary select-none",style:{width:m.width},onClick:()=>a(m.header),children:v.jsxs("div",{className:"flex items-center gap-1",children:[m.header,i===m.header&&v.jsx("span",{className:"text-primary",children:c==="asc"?" ▲":" ▼"})]})},m.header))})}),v.jsx("tbody",{children:s?v.jsx("tr",{children:v.jsx("td",{colSpan:e.length,className:"px-4 py-8 text-center text-text-muted",children:"Loading..."})}):f.length===0?v.jsx("tr",{children:v.jsx("td",{colSpan:e.length,className:"px-4 py-8 text-center text-text-muted",children:"No results found"})}):f.map((m,p)=>v.jsx("tr",{onClick:()=>r==null?void 0:r(m),className:`border-b border-border last:border-0 transition-colors ${r?"cursor-pointer hover:bg-hover":"hover:bg-hover/50"}`,children:e.map(_=>v.jsx("td",{className:"px-4 py-3 whitespace-nowrap",children:typeof _.accessor=="function"?_.accessor(m):String(m[_.accessor]??"")},_.header))},p))})]})})}function Ot({label:e,variant:t="default"}){const r={default:"bg-primary/10 text-primary border-primary/20",success:"bg-success/10 text-success border-success/20",warning:"bg-yellow-500/10 text-yellow-400 border-yellow-500/20",danger:"bg-danger/10 text-danger border-danger/20"};return v.jsx("span",{className:`inline-block px-2 py-0.5 rounded text-[11px] font-semibold border uppercase tracking-wide ${r[t]}`,children:e})}const pS=e=>ne.get(e).then(t=>t.data);function mS(){const[e,t]=M.useState(""),r=fS(e,300),s=Cc(),{dispatch:i}=Fe(),{data:o,isLoading:c}=ct(r.length>=2?`/players?q=${encodeURIComponent(r)}&limit=25`:null,pS,{refreshInterval:3e4}),n=async(f,m,p={})=>{var _,S;try{let b;if(m==="cheater")b=await ne.post(`/players/${f}/cheater`,p);else if(m==="tags")b=await ne.put(`/players/${f}/tags`,p);else{i({type:"ADD_TOAST",payload:{message:`Action "${m}" not yet implemented`,type:"warning"}});return}b.data.success?i({type:"ADD_TOAST",payload:{message:"Action successful",type:"success"}}):i({type:"ADD_TOAST",payload:{message:b.data.error||"Action failed",type:"error"}})}catch(b){i({type:"ADD_TOAST",payload:{message:((S=(_=b.response)==null?void 0:_.data)==null?void 0:S.error)||"Action failed",type:"error"}})}},a=o!=null&&o.success?o.data:[];return v.jsxs("div",{children:[v.jsx("h1",{className:"font-serif text-3xl text-primary mb-6",children:"Player Explorer"}),v.jsx("div",{className:"mb-6",children:v.jsxs("div",{className:"relative max-w-md",children:[v.jsx("input",{type:"text",value:e,onChange:f=>t(f.target.value),placeholder:"Search by name, email, or Funcom ID...",className:"w-full bg-card-bg border border-border rounded-lg px-4 py-2.5 pl-10 text-sm text-text-primary placeholder-text-muted focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary"}),v.jsx("svg",{className:"absolute left-3 top-3 w-4 h-4 text-text-muted",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:v.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0"})})]})}),v.jsx(Bi,{columns:[{header:"Name",accessor:"character_name"},{header:"Status",accessor:f=>v.jsx(Ot,{label:f.online_status,variant:f.online_status==="Online"?"success":"default"})},{header:"Funcom ID",accessor:"funcom_id"},{header:"Faction",accessor:"faction_name"},{header:"Map",accessor:"map"},{header:"Quick Actions",accessor:f=>v.jsxs("div",{className:"flex gap-2",children:[v.jsx("button",{onClick:m=>{m.stopPropagation(),n(f.account_id||f.player_controller_id||0,"cheater",{cheat_type:"exploit"})},className:"text-[10px] text-primary hover:underline",children:"Cheater"}),v.jsx("button",{onClick:m=>{m.stopPropagation(),n(f.account_id||f.player_controller_id||0,"tags",{add:["reviewed"]})},className:"text-[10px] text-primary hover:underline",children:"Tag"})]})}],data:a,onRowClick:f=>s(`/players/${f.account_id||f.player_controller_id||0}`),loading:c})]})}const _S=e=>ne.get(e).then(t=>t.data);function gS(){var f;const{accountId:e}=Yg(),t=Cc(),{dispatch:r}=Fe(),[s,i]=M.useState("overview"),{data:o}=ct(e?`/players/${e}`:null,_S,{refreshInterval:3e4}),c=o!=null&&o.success?o.data:null,n=async(m,p={})=>{var _,S;try{const b=await ne.post(m,p);b.data.success?r({type:"ADD_TOAST",payload:{message:"Action successful",type:"success"}}):r({type:"ADD_TOAST",payload:{message:b.data.error||"Failed",type:"error"}})}catch(b){r({type:"ADD_TOAST",payload:{message:((S=(_=b.response)==null?void 0:_.data)==null?void 0:S.error)||"Action failed",type:"error"}})}};if(!c)return v.jsx("div",{className:"text-text-muted",children:"Loading player details..."});const a=[{key:"overview",label:"Overview"},{key:"inventory",label:"Inventory"},{key:"vehicles",label:"Vehicles"},{key:"buildings",label:"Buildings"},{key:"progression",label:"Progression"},{key:"actions",label:"Actions"}];return v.jsxs("div",{children:[v.jsx("div",{className:"flex items-center gap-4 mb-6",children:v.jsx("button",{onClick:()=>t("/players"),className:"text-text-muted hover:text-text-primary text-sm",children:"← Back to Players"})}),v.jsx("div",{className:"flex items-center justify-between mb-6",children:v.jsxs("div",{children:[v.jsx("h1",{className:"font-serif text-3xl text-primary",children:c.character_name}),v.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[v.jsx(Ot,{label:c.online_status,variant:c.is_online?"success":"default"}),c.faction_name&&v.jsx("span",{className:"text-sm text-text-secondary",children:c.faction_name}),(f=c.tags)==null?void 0:f.map(m=>v.jsx(Ot,{label:m,variant:"warning"},m))]})]})}),v.jsx("div",{className:"flex gap-1 mb-6 border-b border-border",children:a.map(m=>v.jsx("button",{onClick:()=>i(m.key),className:`px-4 py-2.5 text-sm font-medium border-b-2 transition-colors ${s===m.key?"text-primary border-primary":"text-text-muted border-transparent hover:text-text-primary"}`,children:m.label},m.key))}),s==="overview"&&v.jsx(vS,{player:c}),s==="inventory"&&v.jsx(yS,{player:c}),s==="vehicles"&&v.jsx(SS,{player:c}),s==="buildings"&&v.jsx(xS,{player:c}),s==="progression"&&v.jsx(bS,{player:c}),s==="actions"&&v.jsx(wS,{player:c,onAction:n})]})}function vS({player:e}){const t=e.vitals||{},r=e.currency||[];return v.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[v.jsxs("div",{className:"bg-card-bg border border-border rounded-lg p-5",children:[v.jsx("h3",{className:"font-serif text-lg text-primary mb-4",children:"Character Info"}),v.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[v.jsx(We,{label:"Account ID",value:e.account_id}),v.jsx(We,{label:"Controller ID",value:e.player_controller_id}),v.jsx(We,{label:"Pawn ID",value:e.player_pawn_id}),v.jsx(We,{label:"Email",value:e.account_email}),v.jsx(We,{label:"Funcom ID",value:e.funcom_id}),v.jsx(We,{label:"Map",value:e.map}),v.jsx(We,{label:"Life State",value:e.life_state}),v.jsx(We,{label:"Last Login",value:e.last_login_time})]})]}),v.jsxs("div",{className:"bg-card-bg border border-border rounded-lg p-5",children:[v.jsx("h3",{className:"font-serif text-lg text-primary mb-4",children:"Vitals"}),v.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[v.jsx(We,{label:"Health",value:`${t.current_health??"?"}/${t.max_health??"?"}`}),v.jsx(We,{label:"Hydration",value:t.current_hydration??"?"}),v.jsx(We,{label:"Dehydration",value:t.dehydration_penalty??"?"}),v.jsx(We,{label:"Spice",value:t.current_spice??"?"}),v.jsx(We,{label:"Addiction",value:t.spice_addiction_level??"?"}),v.jsx(We,{label:"Tolerance",value:t.spice_tolerance??"?"})]})]}),v.jsxs("div",{className:"bg-card-bg border border-border rounded-lg p-5",children:[v.jsx("h3",{className:"font-serif text-lg text-primary mb-4",children:"Currency"}),v.jsxs("div",{className:"space-y-2",children:[r.length===0&&v.jsx("span",{className:"text-text-muted text-sm",children:"No currency data"}),r.map(s=>v.jsxs("div",{className:"flex justify-between text-sm",children:[v.jsx("span",{className:"text-text-secondary",children:s.currency_label}),v.jsx("span",{className:"text-text-primary font-mono",children:s.balance})]},s.currency_id))]})]}),v.jsxs("div",{className:"bg-card-bg border border-border rounded-lg p-5",children:[v.jsx("h3",{className:"font-serif text-lg text-primary mb-4",children:"Landsraad"}),v.jsx("div",{className:"grid grid-cols-2 gap-4 text-sm",children:e.landsraad?v.jsxs(v.Fragment,{children:[v.jsx(We,{label:"Daily Charges",value:e.landsraad.daily_reward_charges}),v.jsx(We,{label:"Last Term",value:e.landsraad.last_viewed_term_id})]}):v.jsx("span",{className:"text-text-muted",children:"No landsraad data"})})]}),v.jsxs("div",{className:"bg-card-bg border border-border rounded-lg p-5",children:[v.jsx("h3",{className:"font-serif text-lg text-primary mb-4",children:"Faction Reputation"}),v.jsxs("div",{className:"space-y-2",children:[(e.faction_reputation||[]).length===0&&v.jsx("span",{className:"text-text-muted text-sm",children:"No reputation data"}),(e.faction_reputation||[]).map(s=>v.jsxs("div",{className:"flex justify-between text-sm",children:[v.jsx("span",{className:"text-text-secondary",children:s.faction_name||`Faction ${s.faction_id}`}),v.jsx("span",{className:"text-text-primary font-mono",children:s.reputation_amount})]},s.faction_id))]})]})]})}function We({label:e,value:t}){return v.jsxs("div",{children:[v.jsx("div",{className:"text-text-muted text-xs uppercase tracking-wider",children:e}),v.jsx("div",{className:"text-text-primary font-mono",children:t??"N/A"})]})}function yS({player:e}){const t=e.inventories||[],[r,s]=M.useState(null);return v.jsxs("div",{children:[v.jsx("h3",{className:"font-serif text-xl text-primary mb-4",children:"Inventories"}),v.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 mb-6",children:t.map(i=>{var o;return v.jsxs("button",{onClick:()=>s(i),className:`text-left p-4 rounded-lg border transition-colors ${(r==null?void 0:r.inventory_id)===i.inventory_id?"bg-primary/10 border-primary":"bg-card-bg border-border hover:bg-hover"}`,children:[v.jsx("div",{className:"text-sm font-medium text-text-primary",children:i.inventory_type_label}),v.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["ID: ",i.inventory_id]}),v.jsxs("div",{className:"text-xs text-text-muted",children:["Items: ",((o=i.items)==null?void 0:o.length)||0]})]},i.inventory_id)})}),r&&v.jsxs("div",{className:"bg-card-bg border border-border rounded-lg p-5",children:[v.jsxs("h4",{className:"text-text-primary font-medium mb-3",children:[r.inventory_type_label," Items"]}),v.jsx("div",{className:"overflow-x-auto",children:v.jsxs("table",{className:"w-full text-sm",children:[v.jsx("thead",{children:v.jsxs("tr",{className:"border-b border-border",children:[v.jsx("th",{className:"text-left px-3 py-2 text-text-muted text-[11px] uppercase",children:"Item"}),v.jsx("th",{className:"text-left px-3 py-2 text-text-muted text-[11px] uppercase",children:"Stack"}),v.jsx("th",{className:"text-left px-3 py-2 text-text-muted text-[11px] uppercase",children:"Quality"}),v.jsx("th",{className:"text-left px-3 py-2 text-text-muted text-[11px] uppercase",children:"Durability"})]})}),v.jsx("tbody",{children:(r.items||[]).map((i,o)=>v.jsxs("tr",{className:"border-b border-border last:border-0",children:[v.jsx("td",{className:"px-3 py-2",children:i.template_id}),v.jsx("td",{className:"px-3 py-2 font-mono",children:i.stack_size}),v.jsx("td",{className:"px-3 py-2 font-mono",children:i.quality_level}),v.jsx("td",{className:"px-3 py-2 font-mono",children:i.durability!=null?`${Math.round(i.durability)}/${Math.round(i.max_durability)}`:"N/A"})]},o))})]})})]})]})}function SS({player:e}){const t=e.vehicles||[];return v.jsxs("div",{children:[v.jsx("h3",{className:"font-serif text-xl text-primary mb-4",children:"Vehicles"}),t.length===0?v.jsx("div",{className:"text-text-muted",children:"No vehicles found."}):v.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:t.map(r=>v.jsxs("div",{className:"bg-card-bg border border-border rounded-lg p-4",children:[v.jsx("div",{className:"text-text-primary font-medium",children:r.display_name||r.class_name}),v.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Map: ",r.map||"Unknown"]}),v.jsxs("div",{className:"text-xs text-text-muted font-mono",children:["ID: ",r.id]})]},r.id))})]})}function xS({player:e}){const t=e.buildings||[],r=e.landclaims||[];return v.jsxs("div",{className:"space-y-6",children:[v.jsxs("div",{children:[v.jsx("h3",{className:"font-serif text-xl text-primary mb-4",children:"Buildings"}),t.length===0?v.jsx("div",{className:"text-text-muted",children:"No buildings found."}):v.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:t.map(s=>v.jsxs("div",{className:"bg-card-bg border border-border rounded-lg p-4",children:[v.jsx("div",{className:"text-text-primary font-medium",children:s.class_name}),v.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Map: ",s.map||"Unknown"]}),v.jsxs("div",{className:"flex gap-2 mt-2",children:[s.is_powered&&v.jsx(Ot,{label:"Powered",variant:"success"}),s.power_level!=null&&v.jsx(Ot,{label:`Power ${s.power_level}`,variant:"default"})]})]},s.id))})]}),v.jsxs("div",{children:[v.jsx("h3",{className:"font-serif text-xl text-primary mb-4",children:"Landclaims"}),r.length===0?v.jsx("div",{className:"text-text-muted",children:"No landclaims found."}):v.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:r.map(s=>v.jsxs("div",{className:"bg-card-bg border border-border rounded-lg p-4",children:[v.jsx("div",{className:"text-text-primary font-medium",children:s.class_name}),v.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Map: ",s.map||"Unknown"]})]},s.id))})]})]})}function bS({player:e}){const t=e.specialization||[],r=e.keystones||[];return v.jsxs("div",{className:"space-y-6",children:[v.jsxs("div",{className:"bg-card-bg border border-border rounded-lg p-5",children:[v.jsx("h3",{className:"font-serif text-lg text-primary mb-4",children:"Specialization Tracks"}),t.length===0?v.jsx("div",{className:"text-text-muted",children:"No specialization data."}):v.jsx("div",{className:"space-y-3",children:t.map((s,i)=>v.jsxs("div",{className:"flex items-center justify-between",children:[v.jsx("span",{className:"text-text-secondary text-sm",children:s.track_type}),v.jsxs("div",{className:"flex items-center gap-4",children:[v.jsxs("span",{className:"text-text-muted text-xs",children:["XP: ",s.xp_amount]}),v.jsx(Ot,{label:`Lv ${s.level}`,variant:"default"})]})]},i))})]}),v.jsxs("div",{className:"bg-card-bg border border-border rounded-lg p-5",children:[v.jsx("h3",{className:"font-serif text-lg text-primary mb-4",children:"Keystones"}),r.length===0?v.jsx("div",{className:"text-text-muted",children:"No keystones."}):v.jsx("div",{className:"flex flex-wrap gap-2",children:r.map(s=>v.jsx(Ot,{label:s.name,variant:"default"},s.id))})]})]})}function wS({player:e,onAction:t}){const r=e.account_id,[s,i]=M.useState(""),[o,c]=M.useState({currency_id:"0",amount:""}),[n,a]=M.useState({health:"",hydration:"",spice:""}),[f,m]=M.useState({partition:"",x:"",y:"",z:""}),[p,_]=M.useState(""),[S,b]=M.useState("0");return v.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[v.jsx(Fs,{title:"Currency",children:v.jsxs("div",{className:"space-y-2",children:[v.jsxs("select",{value:o.currency_id,onChange:y=>c({...o,currency_id:y.target.value}),className:"w-full bg-card-bg border border-border rounded px-3 py-2 text-sm",children:[v.jsx("option",{value:"0",children:"Solari Credits"}),v.jsx("option",{value:"1",children:"House Script"}),v.jsx("option",{value:"2",children:"Spice"})]}),v.jsx("input",{type:"number",value:o.amount,onChange:y=>c({...o,amount:y.target.value}),placeholder:"Amount",className:"w-full bg-card-bg border border-border rounded px-3 py-2 text-sm"}),v.jsxs("div",{className:"flex gap-2",children:[v.jsx("button",{onClick:()=>t("/currency/adjust",{player_id:r,currency_id:parseInt(o.currency_id),amount:parseFloat(o.amount)}),className:"px-3 py-1.5 rounded text-xs bg-primary/10 border border-primary/20 text-primary",children:"Adjust"}),v.jsx("button",{onClick:()=>t("/currency/set",{player_id:r,currency_id:parseInt(o.currency_id),amount:parseFloat(o.amount)}),className:"px-3 py-1.5 rounded text-xs bg-primary/10 border border-primary/20 text-primary",children:"Set Exact"})]})]})}),v.jsx(Fs,{title:"Vitals",children:v.jsxs("div",{className:"space-y-2",children:[v.jsx("input",{type:"number",value:n.health,onChange:y=>a({...n,health:y.target.value}),placeholder:"Health",className:"w-full bg-card-bg border border-border rounded px-3 py-2 text-sm"}),v.jsx("input",{type:"number",value:n.hydration,onChange:y=>a({...n,hydration:y.target.value}),placeholder:"Hydration",className:"w-full bg-card-bg border border-border rounded px-3 py-2 text-sm"}),v.jsx("input",{type:"number",value:n.spice,onChange:y=>a({...n,spice:y.target.value}),placeholder:"Spice",className:"w-full bg-card-bg border border-border rounded px-3 py-2 text-sm"}),v.jsx("button",{onClick:()=>t("/vitals/set",{player_id:r,health:parseFloat(n.health)||void 0,hydration:parseFloat(n.hydration)||void 0,spice:parseFloat(n.spice)||void 0}),className:"px-3 py-1.5 rounded text-xs bg-primary/10 border border-primary/20 text-primary",children:"Set Vitals"})]})}),v.jsx(Fs,{title:"Teleport",children:v.jsxs("div",{className:"space-y-2",children:[v.jsx("input",{value:f.partition,onChange:y=>m({...f,partition:y.target.value}),placeholder:"Partition ID",className:"w-full bg-card-bg border border-border rounded px-3 py-2 text-sm"}),v.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[v.jsx("input",{type:"number",value:f.x,onChange:y=>m({...f,x:y.target.value}),placeholder:"X",className:"bg-card-bg border border-border rounded px-3 py-2 text-sm"}),v.jsx("input",{type:"number",value:f.y,onChange:y=>m({...f,y:y.target.value}),placeholder:"Y",className:"bg-card-bg border border-border rounded px-3 py-2 text-sm"}),v.jsx("input",{type:"number",value:f.z,onChange:y=>m({...f,z:y.target.value}),placeholder:"Z",className:"bg-card-bg border border-border rounded px-3 py-2 text-sm"})]}),v.jsx("button",{onClick:()=>t("/teleport",{fls_id:r,partition_id:f.partition,x:parseFloat(f.x)||0,y:parseFloat(f.y)||0,z:parseFloat(f.z)||0}),className:"px-3 py-1.5 rounded text-xs bg-primary/10 border border-primary/20 text-primary",children:"Teleport"})]})}),v.jsx(Fs,{title:"Character",children:v.jsxs("div",{className:"space-y-2",children:[v.jsx("input",{value:s,onChange:y=>i(y.target.value),placeholder:"New character name",className:"w-full bg-card-bg border border-border rounded px-3 py-2 text-sm"}),v.jsxs("div",{className:"flex flex-wrap gap-2",children:[v.jsx("button",{onClick:()=>t(`/characters/${r}/name`,{name:s}),className:"px-3 py-1.5 rounded text-xs bg-primary/10 border border-primary/20 text-primary",children:"Rename"}),v.jsx("button",{onClick:()=>t(`/accounts/${r}/demo`,{demo:!0}),className:"px-3 py-1.5 rounded text-xs bg-warning/10 border border-warning/20 text-warning",children:"Set Demo"}),v.jsx("button",{onClick:()=>t(`/accounts/${r}/demo`,{demo:!1}),className:"px-3 py-1.5 rounded text-xs bg-warning/10 border border-warning/20 text-warning",children:"Clear Demo"}),v.jsx("button",{onClick:()=>{confirm("Delete this character? This cannot be undone.")&&t(`/characters/${r}`,{})},className:"px-3 py-1.5 rounded text-xs bg-danger/10 border border-danger/30 text-danger",children:"Delete Character"}),v.jsx("button",{onClick:()=>{confirm("Delete this entire account? This cannot be undone.")&&t(`/accounts/${r}`,{})},className:"px-3 py-1.5 rounded text-xs bg-danger/10 border border-danger/30 text-danger",children:"Delete Account"})]})]})}),v.jsx(Fs,{title:"Moderation",children:v.jsxs("div",{className:"space-y-2",children:[v.jsx("input",{value:p,onChange:y=>_(y.target.value),placeholder:"Ban reason",className:"w-full bg-card-bg border border-border rounded px-3 py-2 text-sm"}),v.jsx("input",{type:"number",value:S,onChange:y=>b(y.target.value),placeholder:"Duration (hours, 0 = permanent)",className:"w-full bg-card-bg border border-border rounded px-3 py-2 text-sm"}),v.jsxs("div",{className:"flex flex-wrap gap-2",children:[v.jsx("button",{onClick:()=>t(`/players/${r}/ban`,{reason:p,duration_hours:parseInt(S)||0}),className:"px-3 py-1.5 rounded text-xs bg-danger/10 border border-danger/30 text-danger",children:"Ban Player"}),v.jsx("button",{onClick:()=>t(`/players/${r}/unban`,{}),className:"px-3 py-1.5 rounded text-xs bg-success/10 border border-success/30 text-success",children:"Unban Player"}),v.jsx("button",{onClick:()=>t(`/players/${r}/kick`,{reason:p}),className:"px-3 py-1.5 rounded text-xs bg-warning/10 border border-warning/20 text-warning",children:"Kick Player"})]})]})})]})}function Fs({title:e,children:t}){return v.jsxs("div",{className:"bg-card-bg border border-border rounded-lg p-5",children:[v.jsx("h4",{className:"text-text-primary font-medium mb-3",children:e}),t]})}function CS({open:e,title:t,onClose:r,children:s,maxWidth:i="500px"}){return e?v.jsx("div",{className:"fixed inset-0 z-[70] flex items-center justify-center bg-black/60 backdrop-blur-sm",children:v.jsxs("div",{className:"bg-card-bg border border-border rounded-xl shadow-2xl w-full mx-4",style:{maxWidth:i},children:[v.jsxs("div",{className:"flex items-center justify-between px-5 py-4 border-b border-border",children:[v.jsx("h3",{className:"font-serif text-lg text-text-primary",children:t}),v.jsx("button",{onClick:r,className:"text-text-muted hover:text-text-primary text-xl leading-none",children:"×"})]}),v.jsx("div",{className:"p-5 max-h-[80vh] overflow-auto",children:s})]})}):null}const ES=e=>ne.get(e).then(t=>t.data);function kS(){const[e,t]=M.useState(""),[r,s]=M.useState(null),[i,o]=M.useState(null),{dispatch:c}=Fe(),{data:n,isLoading:a}=ct(e.length>=2?`/guilds?q=${encodeURIComponent(e)}&limit=25`:null,ES,{refreshInterval:3e4}),f=async S=>{var b,y;try{const u=await ne.get(`/guilds/${S}`);u.data.success&&o(u.data.data)}catch(u){c({type:"ADD_TOAST",payload:{message:((y=(b=u.response)==null?void 0:b.data)==null?void 0:y.error)||"Failed",type:"error"}})}},m=async()=>{var S,b;try{const y=await ne.delete(`/guilds/${r.guild_id}`);y.data.success?(c({type:"ADD_TOAST",payload:{message:"Guild disbanded",type:"success"}}),s(null),o(null)):c({type:"ADD_TOAST",payload:{message:y.data.error||"Failed",type:"error"}})}catch(y){c({type:"ADD_TOAST",payload:{message:((b=(S=y.response)==null?void 0:S.data)==null?void 0:b.error)||"Failed",type:"error"}})}},p=async(S,b,y)=>{var u,h;try{let l;S==="remove"?l=await ne.delete(`/guilds/${r.guild_id}/members/${b}`):l=await ne.put(`/guilds/${r.guild_id}/members/${b}/role`,{action:S,role_id:y}),l.data.success?(c({type:"ADD_TOAST",payload:{message:"Member updated",type:"success"}}),f(r.guild_id)):c({type:"ADD_TOAST",payload:{message:l.data.error||"Failed",type:"error"}})}catch(l){c({type:"ADD_TOAST",payload:{message:((h=(u=l.response)==null?void 0:u.data)==null?void 0:h.error)||"Failed",type:"error"}})}},_=n!=null&&n.success?n.data:[];return v.jsxs("div",{children:[v.jsx("h1",{className:"font-serif text-3xl text-primary mb-6",children:"Guild Manager"}),v.jsx("div",{className:"mb-6",children:v.jsxs("div",{className:"relative max-w-md",children:[v.jsx("input",{type:"text",value:e,onChange:S=>t(S.target.value),placeholder:"Search guilds...",className:"w-full bg-card-bg border border-border rounded-lg px-4 py-2.5 pl-10 text-sm text-text-primary placeholder-text-muted focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary"}),v.jsx("svg",{className:"absolute left-3 top-3 w-4 h-4 text-text-muted",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:v.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0"})})]})}),v.jsx(Bi,{columns:[{header:"Name",accessor:"guild_name"},{header:"Faction",accessor:"faction_name"},{header:"Members",accessor:"member_count"},{header:"Online",accessor:"online_count"}],data:_,onRowClick:S=>{s(S),f(S.guild_id)},loading:a}),v.jsx(CS,{open:!!r,title:(r==null?void 0:r.guild_name)||"",onClose:()=>{s(null),o(null)},maxWidth:"700px",children:r&&i&&v.jsxs("div",{className:"space-y-4",children:[v.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[v.jsx(nn,{label:"Guild ID",value:r.guild_id}),v.jsx(nn,{label:"Members",value:r.member_count}),v.jsx(nn,{label:"Faction",value:r.faction_name||"None"}),v.jsx(nn,{label:"Description",value:r.guild_description||"None"})]}),v.jsxs("div",{className:"border-t border-border pt-4",children:[v.jsx("h4",{className:"text-text-muted text-xs uppercase tracking-wider mb-3",children:"Members"}),v.jsx("div",{className:"overflow-x-auto rounded-lg border border-border max-h-64 overflow-y-auto",children:v.jsxs("table",{className:"w-full text-sm",children:[v.jsx("thead",{className:"sticky top-0 bg-card-bg",children:v.jsxs("tr",{className:"border-b border-border",children:[v.jsx("th",{className:"text-left px-3 py-2 text-text-muted text-[11px] uppercase",children:"Name"}),v.jsx("th",{className:"text-left px-3 py-2 text-text-muted text-[11px] uppercase",children:"Role"}),v.jsx("th",{className:"text-left px-3 py-2 text-text-muted text-[11px] uppercase",children:"Status"}),v.jsx("th",{className:"text-left px-3 py-2 text-text-muted text-[11px] uppercase",children:"Actions"})]})}),v.jsx("tbody",{children:(i.members||[]).map(S=>v.jsxs("tr",{className:"border-b border-border last:border-0",children:[v.jsx("td",{className:"px-3 py-2",children:S.player_name}),v.jsx("td",{className:"px-3 py-2",children:v.jsx("span",{className:"px-2 py-0.5 rounded text-[10px] bg-primary/10 text-primary border border-primary/20",children:S.role_name})}),v.jsx("td",{className:"px-3 py-2 text-xs",children:S.online_status}),v.jsxs("td",{className:"px-3 py-2 flex gap-1",children:[v.jsx("button",{onClick:()=>p("promote",S.player_id,90),className:"text-[10px] text-primary hover:underline",children:"Promote"}),v.jsx("button",{onClick:()=>p("demote",S.player_id,50),className:"text-[10px] text-text-muted hover:underline",children:"Demote"}),v.jsx("button",{onClick:()=>p("remove",S.player_id),className:"text-[10px] text-danger hover:underline",children:"Remove"})]})]},S.player_id))})]})})]}),v.jsx("div",{className:"flex gap-2 pt-4 border-t border-border",children:v.jsx("button",{onClick:m,className:"px-3 py-1.5 rounded text-xs font-medium bg-danger/10 border border-danger/30 text-danger hover:bg-danger/20",children:"Disband Guild"})})]})})]})}function nn({label:e,value:t}){return v.jsxs("div",{children:[v.jsx("div",{className:"text-text-muted text-xs uppercase tracking-wider",children:e}),v.jsx("div",{className:"text-text-primary font-mono",children:t??"N/A"})]})}const RS=e=>ne.get(e).then(t=>t.data);function TS(){const[e,t]=M.useState(""),{dispatch:r}=Fe(),{data:s,isLoading:i}=ct(e.length>=2?`/vehicles?q=${encodeURIComponent(e)}&limit=50`:"/vehicles?limit=100",RS,{refreshInterval:3e4}),o=s!=null&&s.success?s.data:[],c=async(n,a)=>{var f,m;try{const p=await ne.post(`/vehicles/${n}/${a}`,{});p.data.success?r({type:"ADD_TOAST",payload:{message:"Action successful",type:"success"}}):r({type:"ADD_TOAST",payload:{message:p.data.error||"Failed",type:"error"}})}catch(p){r({type:"ADD_TOAST",payload:{message:((m=(f=p.response)==null?void 0:f.data)==null?void 0:m.error)||"Failed",type:"error"}})}};return v.jsxs("div",{children:[v.jsx("h1",{className:"font-serif text-3xl text-primary mb-6",children:"Vehicles"}),v.jsx("div",{className:"mb-6",children:v.jsxs("div",{className:"relative max-w-md",children:[v.jsx("input",{type:"text",value:e,onChange:n=>t(n.target.value),placeholder:"Search vehicles...",className:"w-full bg-card-bg border border-border rounded-lg px-4 py-2.5 pl-10 text-sm text-text-primary placeholder-text-muted focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary"}),v.jsx("svg",{className:"absolute left-3 top-3 w-4 h-4 text-text-muted",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:v.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0"})})]})}),v.jsx(Bi,{columns:[{header:"Name",accessor:"display_name"},{header:"Class",accessor:"class_name"},{header:"Map",accessor:"map"},{header:"Owner",accessor:"owner_name"},{header:"Actions",accessor:n=>v.jsxs("div",{className:"flex gap-2",children:[v.jsx("button",{onClick:a=>{a.stopPropagation(),c(n.id,"repair")},className:"text-xs text-primary hover:underline",children:"Repair"}),v.jsx("button",{onClick:a=>{a.stopPropagation(),c(n.id,"destroy")},className:"text-xs text-danger hover:underline",children:"Destroy"})]})}],data:o,loading:i})]})}const LS=e=>ne.get(e).then(t=>t.data);function DS(){const[e,t]=M.useState(""),{dispatch:r}=Fe(),{data:s,isLoading:i}=ct(e.length>=2?`/buildings?q=${encodeURIComponent(e)}&limit=50`:"/buildings?limit=100",LS,{refreshInterval:3e4}),o=s!=null&&s.success?s.data:[];return v.jsxs("div",{children:[v.jsx("h1",{className:"font-serif text-3xl text-primary mb-6",children:"Buildings"}),v.jsx("div",{className:"mb-6",children:v.jsxs("div",{className:"relative max-w-md",children:[v.jsx("input",{type:"text",value:e,onChange:c=>t(c.target.value),placeholder:"Search buildings...",className:"w-full bg-card-bg border border-border rounded-lg px-4 py-2.5 pl-10 text-sm text-text-primary placeholder-text-muted focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary"}),v.jsx("svg",{className:"absolute left-3 top-3 w-4 h-4 text-text-muted",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:v.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0"})})]})}),v.jsx(Bi,{columns:[{header:"Class",accessor:"class_name"},{header:"Map",accessor:"map"},{header:"Owner",accessor:"owner_name"},{header:"Power",accessor:c=>v.jsxs("div",{className:"flex gap-1",children:[c.is_powered?v.jsx(Ot,{label:"Powered",variant:"success"}):v.jsx(Ot,{label:"Unpowered",variant:"default"}),c.power_level!=null&&v.jsx(Ot,{label:`Lv ${c.power_level}`,variant:"default"})]})},{header:"Instances",accessor:"instance_count"}],data:o,loading:i})]})}const AS=e=>ne.get(e).then(t=>t.data);function OS(){const e=M.useRef(null),[t,r]=M.useState([]),[s,i]=M.useState("all"),[o,c]=M.useState(null),[n,a]=M.useState(1),[f,m]=M.useState({x:0,y:0}),[p,_]=M.useState(!1),S=M.useRef({x:0,y:0}),{data:b}=ct("/partitions",AS,{refreshInterval:6e4});M.useEffect(()=>{const d=[];b!=null&&b.success&&(b.data||[]).forEach(g=>{g.center_x!=null&&g.center_y!=null&&d.push({id:`partition-${g.partition_id}`,name:g.name||`Partition ${g.partition_id}`,x:g.center_x,y:g.center_y,type:"building"})}),r(d)},[b]),M.useEffect(()=>{const d=e.current;if(!d)return;const g=d.getContext("2d");if(!g)return;const x=window.devicePixelRatio||1,C=d.getBoundingClientRect();d.width=C.width*x,d.height=C.height*x,g.scale(x,x),g.fillStyle="#1a1a1a",g.fillRect(0,0,C.width,C.height),g.strokeStyle="#333",g.lineWidth=1;const k=50*n;for(let E=f.x%k;EE.type===s)).forEach(E=>{const L=C.width/2+E.x*.001*n+f.x,N=C.height/2+E.y*.001*n+f.y;g.beginPath(),g.arc(L,N,6,0,Math.PI*2),g.fillStyle=E.type==="player"?"#27ae60":E.type==="vehicle"?"#4a90d9":"#d4af37",g.fill(),g.strokeStyle="#fff",g.lineWidth=1,g.stroke(),g.fillStyle="#c0c0c0",g.font="10px Inter",g.fillText(E.name,L+10,N+3)})},[t,s,n,f]);const y=d=>{d.preventDefault();const g=Math.max(.1,Math.min(10,n+(d.deltaY>0?-.1:.1)));a(g)},u=d=>{_(!0),S.current={x:d.clientX-f.x,y:d.clientY-f.y}},h=d=>{p&&m({x:d.clientX-S.current.x,y:d.clientY-S.current.y})},l=()=>_(!1);return v.jsxs("div",{className:"h-[calc(100vh-140px)] flex flex-col",children:[v.jsxs("div",{className:"flex items-center justify-between mb-4",children:[v.jsx("h1",{className:"font-serif text-3xl text-primary",children:"Map Viewer"}),v.jsxs("div",{className:"flex gap-2",children:[["all","player","vehicle","building"].map(d=>v.jsx("button",{onClick:()=>i(d),className:`px-3 py-1.5 rounded text-xs font-medium border capitalize ${s===d?"bg-primary/10 border-primary text-primary":"bg-card-bg border-border text-text-muted hover:text-text-primary"}`,children:d},d)),v.jsx("button",{onClick:()=>{a(1),m({x:0,y:0})},className:"px-3 py-1.5 rounded text-xs font-medium border bg-card-bg border-border text-text-muted hover:text-text-primary",children:"Reset View"})]})]}),v.jsxs("div",{className:"flex-1 bg-card-bg border border-border rounded-lg overflow-hidden relative",children:[v.jsx("canvas",{ref:e,className:"w-full h-full cursor-grab active:cursor-grabbing",onWheel:y,onMouseDown:u,onMouseMove:h,onMouseUp:l,onMouseLeave:l}),v.jsxs("div",{className:"absolute bottom-4 left-4 bg-card-bg/90 border border-border rounded px-3 py-2 text-xs text-text-muted",children:["Zoom: ",n.toFixed(1),"x | Markers: ",t.length]})]})]})}const NS=e=>ne.get(e).then(t=>t.data);function PS(){const[e,t]=M.useState(""),{dispatch:r}=Fe(),{data:s,isLoading:i}=ct(e.length>=2?`/accounts?q=${encodeURIComponent(e)}&limit=50`:"/accounts?limit=100",NS,{refreshInterval:3e4}),o=s!=null&&s.success?s.data:[];return v.jsxs("div",{children:[v.jsx("h1",{className:"font-serif text-3xl text-primary mb-6",children:"Accounts"}),v.jsx("div",{className:"mb-6",children:v.jsxs("div",{className:"relative max-w-md",children:[v.jsx("input",{type:"text",value:e,onChange:c=>t(c.target.value),placeholder:"Search accounts...",className:"w-full bg-card-bg border border-border rounded-lg px-4 py-2.5 pl-10 text-sm text-text-primary placeholder-text-muted focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary"}),v.jsx("svg",{className:"absolute left-3 top-3 w-4 h-4 text-text-muted",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:v.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0"})})]})}),v.jsx(Bi,{columns:[{header:"Email",accessor:"email"},{header:"Funcom ID",accessor:"funcom_id"},{header:"Characters",accessor:"character_count"},{header:"Last Login",accessor:"last_login"}],data:o,loading:i})]})}const Hs=e=>ne.get(e).then(t=>t.data);function BS(){const[e,t]=M.useState("pods"),{dispatch:r}=Fe(),{data:s,mutate:i}=ct("/server/pods",Hs,{refreshInterval:15e3}),{data:o}=ct("/server/deployments",Hs,{refreshInterval:3e4}),{data:c}=ct("/server/metrics?hours=24",Hs,{refreshInterval:6e4}),{data:n}=ct("/server/firewall/status",Hs,{refreshInterval:3e4}),{data:a}=ct("/server/rmq/overview",Hs,{refreshInterval:3e4}),f=s!=null&&s.success?s.data:[],m=o!=null&&o.success?o.data:[],p=c!=null&&c.success?c.data:[],_=async b=>{var y,u;try{const h=await ne.post(`/server/deployments/${b}/restart`);h.data.success?r({type:"ADD_TOAST",payload:{message:"Restart initiated",type:"success"}}):r({type:"ADD_TOAST",payload:{message:h.data.error||"Failed",type:"error"}})}catch(h){r({type:"ADD_TOAST",payload:{message:((u=(y=h.response)==null?void 0:y.data)==null?void 0:u.error)||"Failed",type:"error"}})}},S=async(b,y)=>{var u,h;try{const l=await ne.post(`/server/deployments/${b}/scale`,{replicas:y});l.data.success?r({type:"ADD_TOAST",payload:{message:"Scaled successfully",type:"success"}}):r({type:"ADD_TOAST",payload:{message:l.data.error||"Failed",type:"error"}})}catch(l){r({type:"ADD_TOAST",payload:{message:((h=(u=l.response)==null?void 0:u.data)==null?void 0:h.error)||"Failed",type:"error"}})}};return v.jsxs("div",{children:[v.jsx("h1",{className:"font-serif text-3xl text-primary mb-6",children:"Server Control"}),v.jsx("div",{className:"flex gap-1 mb-6 border-b border-border",children:["pods","deployments","metrics","firewall","rmq"].map(b=>v.jsx("button",{onClick:()=>t(b),className:`px-4 py-2.5 text-sm font-medium border-b-2 transition-colors capitalize ${e===b?"text-primary border-primary":"text-text-muted border-transparent hover:text-text-primary"}`,children:b},b))}),e==="pods"&&v.jsx("div",{className:"overflow-x-auto rounded-lg border border-border",children:v.jsxs("table",{className:"w-full text-sm",children:[v.jsx("thead",{children:v.jsxs("tr",{className:"border-b border-border",children:[v.jsx("th",{className:"text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase",children:"Name"}),v.jsx("th",{className:"text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase",children:"Namespace"}),v.jsx("th",{className:"text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase",children:"Status"}),v.jsx("th",{className:"text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase",children:"Restarts"}),v.jsx("th",{className:"text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase",children:"Age"}),v.jsx("th",{className:"text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase",children:"Actions"})]})}),v.jsx("tbody",{children:f.map(b=>v.jsxs("tr",{className:"border-b border-border last:border-0 hover:bg-hover/50",children:[v.jsx("td",{className:"px-4 py-3 font-mono text-xs",children:b.name}),v.jsx("td",{className:"px-4 py-3",children:b.namespace}),v.jsx("td",{className:"px-4 py-3",children:v.jsx(Ot,{label:b.status,variant:b.status==="Running"?"success":b.status==="Pending"?"warning":"danger"})}),v.jsx("td",{className:"px-4 py-3",children:b.restarts}),v.jsx("td",{className:"px-4 py-3",children:b.age}),v.jsx("td",{className:"px-4 py-3",children:v.jsx("button",{onClick:()=>_(b.name),className:"text-xs text-primary hover:underline",children:"Restart"})})]},b.name))})]})}),e==="deployments"&&v.jsx("div",{className:"overflow-x-auto rounded-lg border border-border",children:v.jsxs("table",{className:"w-full text-sm",children:[v.jsx("thead",{children:v.jsxs("tr",{className:"border-b border-border",children:[v.jsx("th",{className:"text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase",children:"Name"}),v.jsx("th",{className:"text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase",children:"Namespace"}),v.jsx("th",{className:"text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase",children:"Replicas"}),v.jsx("th",{className:"text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase",children:"Available"}),v.jsx("th",{className:"text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase",children:"Actions"})]})}),v.jsx("tbody",{children:m.map(b=>v.jsxs("tr",{className:"border-b border-border last:border-0 hover:bg-hover/50",children:[v.jsx("td",{className:"px-4 py-3 font-mono text-xs",children:b.name}),v.jsx("td",{className:"px-4 py-3",children:b.namespace}),v.jsx("td",{className:"px-4 py-3",children:b.replicas}),v.jsx("td",{className:"px-4 py-3",children:b.available}),v.jsxs("td",{className:"px-4 py-3 flex gap-2",children:[v.jsx("button",{onClick:()=>S(b.name,b.replicas+1),className:"text-xs px-2 py-1 bg-primary/10 border border-primary/20 rounded text-primary",children:"+1"}),v.jsx("button",{onClick:()=>S(b.name,Math.max(0,b.replicas-1)),className:"text-xs px-2 py-1 bg-primary/10 border border-primary/20 rounded text-primary",children:"-1"}),v.jsx("button",{onClick:()=>_(b.name),className:"text-xs px-2 py-1 bg-danger/10 border border-danger/20 rounded text-danger",children:"Restart"})]})]},b.name))})]})}),e==="metrics"&&v.jsxs("div",{className:"bg-card-bg border border-border rounded-lg p-5",children:[v.jsx("h3",{className:"text-text-muted text-xs uppercase tracking-wider mb-4",children:"Server Metrics (24h)"}),p.length===0?v.jsx("div",{className:"text-text-muted text-sm",children:"No metrics available"}):v.jsx("div",{className:"space-y-2",children:p.slice(-20).map((b,y)=>v.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[v.jsx("span",{className:"text-text-muted w-32",children:new Date(b.timestamp).toLocaleTimeString()}),v.jsxs("div",{className:"flex-1 flex items-center gap-2",children:[v.jsx("span",{className:"text-text-muted w-8",children:"CPU"}),v.jsx("div",{className:"flex-1 h-2 bg-border rounded overflow-hidden",children:v.jsx("div",{className:"h-full bg-primary",style:{width:`${Math.min(100,b.cpu_percent)}%`}})}),v.jsxs("span",{className:"text-text-secondary w-10 text-right",children:[b.cpu_percent,"%"]})]}),v.jsxs("div",{className:"flex-1 flex items-center gap-2",children:[v.jsx("span",{className:"text-text-muted w-12",children:"Mem"}),v.jsx("div",{className:"flex-1 h-2 bg-border rounded overflow-hidden",children:v.jsx("div",{className:"h-full bg-success",style:{width:`${Math.min(100,b.memory_percent)}%`}})}),v.jsxs("span",{className:"text-text-secondary w-10 text-right",children:[b.memory_percent,"%"]})]})]},y))})]}),e==="firewall"&&v.jsxs("div",{className:"bg-card-bg border border-border rounded-lg p-5",children:[v.jsx("h3",{className:"text-text-muted text-xs uppercase tracking-wider mb-4",children:"Firewall Status"}),n!=null&&n.success?v.jsx("pre",{className:"text-xs text-text-secondary font-mono bg-code-bg p-4 rounded overflow-auto",children:JSON.stringify(n.data,null,2)}):v.jsx("div",{className:"text-text-muted text-sm",children:"No firewall data available"})]}),e==="rmq"&&v.jsxs("div",{className:"bg-card-bg border border-border rounded-lg p-5",children:[v.jsx("h3",{className:"text-text-muted text-xs uppercase tracking-wider mb-4",children:"RMQ Overview"}),a!=null&&a.success?v.jsx("pre",{className:"text-xs text-text-secondary font-mono bg-code-bg p-4 rounded overflow-auto",children:JSON.stringify(a.data,null,2)}):v.jsx("div",{className:"text-text-muted text-sm",children:"No RMQ data available"})]})]})}const jS=["all","server","partition"],MS=["na","eu","sea","sa","oc"],IS=["parrish","sietch","bazar"];function FS(){const[e,t]=M.useState("broadcast"),{dispatch:r}=Fe();return v.jsxs("div",{children:[v.jsx("h1",{className:"font-serif text-3xl text-primary mb-6",children:"Admin Tools"}),v.jsx("div",{className:"flex gap-1 mb-6 border-b border-border overflow-x-auto no-scrollbar",children:[{key:"broadcast",label:"Broadcast"},{key:"economy",label:"Economy"},{key:"world",label:"World"},{key:"character",label:"Character"},{key:"functions",label:"Functions"},{key:"raw",label:"Raw Query"},{key:"audit",label:"Audit Log"}].map(s=>v.jsx("button",{onClick:()=>t(s.key),className:`px-4 py-2.5 text-sm font-medium border-b-2 transition-colors whitespace-nowrap ${e===s.key?"text-primary border-primary":"text-text-muted border-transparent hover:text-text-primary"}`,children:s.label},s.key))}),e==="broadcast"&&v.jsx(HS,{dispatch:r}),e==="economy"&&v.jsx(US,{dispatch:r}),e==="world"&&v.jsx(zS,{dispatch:r}),e==="character"&&v.jsx($S,{dispatch:r}),e==="functions"&&v.jsx(WS,{dispatch:r}),e==="raw"&&v.jsx(VS,{dispatch:r}),e==="audit"&&v.jsx(qS,{dispatch:r})]})}function HS({dispatch:e}){const[t,r]=M.useState(""),[s,i]=M.useState("all"),[o,c]=M.useState("na"),[n,a]=M.useState("parrish"),[f,m]=M.useState(!1),p=async()=>{var _,S;if(t.trim()){m(!0);try{const b={message:t.trim()};s==="server"&&(b.server=o),s==="partition"&&(b.server=o,b.partition=n);const y=await ne.post("/broadcast",b);y.data.success?(e({type:"ADD_TOAST",payload:{message:"Broadcast sent",type:"success"}}),r("")):e({type:"ADD_TOAST",payload:{message:y.data.error||"Failed",type:"error"}})}catch(b){e({type:"ADD_TOAST",payload:{message:((S=(_=b.response)==null?void 0:_.data)==null?void 0:S.error)||"Failed",type:"error"}})}finally{m(!1)}}};return v.jsx("div",{className:"max-w-xl",children:v.jsxs("div",{className:"bg-card-bg border border-border rounded-lg p-5 space-y-4",children:[v.jsxs("div",{children:[v.jsx("label",{className:"block text-sm text-text-muted mb-2",children:"Scope"}),v.jsx("div",{className:"flex gap-2",children:jS.map(_=>v.jsx("button",{onClick:()=>i(_),className:`px-3 py-1.5 rounded text-xs font-medium border capitalize ${s===_?"bg-primary/10 border-primary text-primary":"bg-card-bg border-border text-text-muted hover:text-text-primary"}`,children:_},_))})]}),s!=="all"&&v.jsxs("div",{children:[v.jsx("label",{className:"block text-sm text-text-muted mb-2",children:"Server"}),v.jsx("select",{value:o,onChange:_=>c(_.target.value),className:"bg-card-bg border border-border rounded px-3 py-2 text-sm text-text-primary",children:MS.map(_=>v.jsx("option",{value:_,children:_.toUpperCase()},_))})]}),s==="partition"&&v.jsxs("div",{children:[v.jsx("label",{className:"block text-sm text-text-muted mb-2",children:"Partition"}),v.jsx("select",{value:n,onChange:_=>a(_.target.value),className:"bg-card-bg border border-border rounded px-3 py-2 text-sm text-text-primary",children:IS.map(_=>v.jsx("option",{value:_,children:_},_))})]}),v.jsxs("div",{children:[v.jsx("label",{className:"block text-sm text-text-muted mb-2",children:"Message"}),v.jsx("textarea",{value:t,onChange:_=>r(_.target.value),rows:4,className:"w-full bg-card-bg border border-border rounded-lg px-4 py-3 text-sm text-text-primary placeholder-text-muted focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary resize-y",placeholder:"Enter broadcast message..."})]}),v.jsx("button",{onClick:p,disabled:f||!t.trim(),className:"px-4 py-2 bg-primary text-white rounded-lg text-sm font-medium hover:bg-primary-dark disabled:opacity-50 transition-colors",children:f?"Sending...":"Send Broadcast"})]})})}function US({dispatch:e}){const[t,r]=M.useState(""),[s,i]=M.useState({template_id:"",stack_size:"1",quality:"0",inventory_id:""}),[o,c]=M.useState({item_id:"",field:"stack_size",value:""}),n=async(a,f)=>{var m,p;try{const _=await ne.post(a,f);_.data.success?e({type:"ADD_TOAST",payload:{message:"Success",type:"success"}}):e({type:"ADD_TOAST",payload:{message:_.data.error||"Failed",type:"error"}})}catch(_){e({type:"ADD_TOAST",payload:{message:((p=(m=_.response)==null?void 0:m.data)==null?void 0:p.error)||"Failed",type:"error"}})}};return v.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[v.jsxs("div",{className:"bg-card-bg border border-border rounded-lg p-5 space-y-3",children:[v.jsx("h3",{className:"font-medium text-text-primary",children:"Add Item"}),v.jsx("input",{value:t,onChange:a=>r(a.target.value),placeholder:"Player ID",className:"w-full bg-card-bg border border-border rounded px-3 py-2 text-sm"}),v.jsx("input",{value:s.template_id,onChange:a=>i({...s,template_id:a.target.value}),placeholder:"Template ID",className:"w-full bg-card-bg border border-border rounded px-3 py-2 text-sm"}),v.jsx("input",{value:s.stack_size,onChange:a=>i({...s,stack_size:a.target.value}),placeholder:"Stack Size",className:"w-full bg-card-bg border border-border rounded px-3 py-2 text-sm"}),v.jsx("input",{value:s.quality,onChange:a=>i({...s,quality:a.target.value}),placeholder:"Quality",className:"w-full bg-card-bg border border-border rounded px-3 py-2 text-sm"}),v.jsx("input",{value:s.inventory_id,onChange:a=>i({...s,inventory_id:a.target.value}),placeholder:"Inventory ID",className:"w-full bg-card-bg border border-border rounded px-3 py-2 text-sm"}),v.jsx("button",{onClick:()=>n("/items/add",{player_id:parseInt(t),template_id:s.template_id,stack_size:parseInt(s.stack_size),quality_level:parseInt(s.quality),inventory_id:parseInt(s.inventory_id)||void 0}),className:"px-3 py-1.5 rounded text-xs bg-primary/10 border border-primary/20 text-primary",children:"Add Item"})]}),v.jsxs("div",{className:"bg-card-bg border border-border rounded-lg p-5 space-y-3",children:[v.jsx("h3",{className:"font-medium text-text-primary",children:"Edit Item"}),v.jsx("input",{value:o.item_id,onChange:a=>c({...o,item_id:a.target.value}),placeholder:"Item ID",className:"w-full bg-card-bg border border-border rounded px-3 py-2 text-sm"}),v.jsx("select",{value:o.field,onChange:a=>c({...o,field:a.target.value}),className:"w-full bg-card-bg border border-border rounded px-3 py-2 text-sm",children:["stack_size","quality_level","durability","ammo"].map(a=>v.jsx("option",{value:a,children:a},a))}),v.jsx("input",{value:o.value,onChange:a=>c({...o,value:a.target.value}),placeholder:"New value",className:"w-full bg-card-bg border border-border rounded px-3 py-2 text-sm"}),v.jsxs("div",{className:"flex gap-2",children:[v.jsx("button",{onClick:()=>n(`/items/${o.item_id}`,{[o.field]:o.value}),className:"px-3 py-1.5 rounded text-xs bg-primary/10 border border-primary/20 text-primary",children:"Update"}),v.jsx("button",{onClick:()=>n(`/items/${o.item_id}`,{}),className:"px-3 py-1.5 rounded text-xs bg-danger/10 border border-danger/30 text-danger",children:"Delete"})]})]})]})}function zS({dispatch:e}){const[t,r]=M.useState({fls_id:"",partition:"",x:"",y:"",z:""}),s=async(i,o)=>{var c,n;try{const a=await ne.post(i,o);a.data.success?e({type:"ADD_TOAST",payload:{message:"Success",type:"success"}}):e({type:"ADD_TOAST",payload:{message:a.data.error||"Failed",type:"error"}})}catch(a){e({type:"ADD_TOAST",payload:{message:((n=(c=a.response)==null?void 0:c.data)==null?void 0:n.error)||"Failed",type:"error"}})}};return v.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[v.jsxs("div",{className:"bg-card-bg border border-border rounded-lg p-5 space-y-3",children:[v.jsx("h3",{className:"font-medium text-text-primary",children:"Teleport Player"}),v.jsx("input",{value:t.fls_id,onChange:i=>r({...t,fls_id:i.target.value}),placeholder:"FLS ID / Account ID",className:"w-full bg-card-bg border border-border rounded px-3 py-2 text-sm"}),v.jsx("input",{value:t.partition,onChange:i=>r({...t,partition:i.target.value}),placeholder:"Partition ID",className:"w-full bg-card-bg border border-border rounded px-3 py-2 text-sm"}),v.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[v.jsx("input",{type:"number",value:t.x,onChange:i=>r({...t,x:i.target.value}),placeholder:"X",className:"bg-card-bg border border-border rounded px-3 py-2 text-sm"}),v.jsx("input",{type:"number",value:t.y,onChange:i=>r({...t,y:i.target.value}),placeholder:"Y",className:"bg-card-bg border border-border rounded px-3 py-2 text-sm"}),v.jsx("input",{type:"number",value:t.z,onChange:i=>r({...t,z:i.target.value}),placeholder:"Z",className:"bg-card-bg border border-border rounded px-3 py-2 text-sm"})]}),v.jsx("button",{onClick:()=>s("/teleport",{fls_id:parseInt(t.fls_id),partition_id:t.partition,x:parseFloat(t.x)||0,y:parseFloat(t.y)||0,z:parseFloat(t.z)||0}),className:"px-3 py-1.5 rounded text-xs bg-primary/10 border border-primary/20 text-primary",children:"Teleport"})]}),v.jsxs("div",{className:"bg-card-bg border border-border rounded-lg p-5 space-y-3",children:[v.jsx("h3",{className:"font-medium text-text-primary",children:"Spice Control"}),v.jsxs("div",{className:"flex gap-2",children:[v.jsx("button",{onClick:()=>s("/spice/reset",{}),className:"px-3 py-1.5 rounded text-xs bg-primary/10 border border-primary/20 text-primary",children:"Reset Spice Fields"}),v.jsx("button",{onClick:()=>s("/spice/spawn",{}),className:"px-3 py-1.5 rounded text-xs bg-primary/10 border border-primary/20 text-primary",children:"Force Spawn"})]})]}),v.jsxs("div",{className:"bg-card-bg border border-border rounded-lg p-5 space-y-3",children:[v.jsx("h3",{className:"font-medium text-text-primary",children:"Partitions"}),v.jsx("button",{onClick:()=>ne.get("/partitions").then(i=>e({type:"ADD_TOAST",payload:{message:"Partitions loaded",type:"info"}})),className:"px-3 py-1.5 rounded text-xs bg-primary/10 border border-primary/20 text-primary",children:"List Partitions"})]})]})}function $S({dispatch:e}){const[t,r]=M.useState(""),[s,i]=M.useState(""),[o,c]=M.useState("true"),n=async(a,f)=>{var m,p;try{const _=await ne.post(a,f);_.data.success?e({type:"ADD_TOAST",payload:{message:"Success",type:"success"}}):e({type:"ADD_TOAST",payload:{message:_.data.error||"Failed",type:"error"}})}catch(_){e({type:"ADD_TOAST",payload:{message:((p=(m=_.response)==null?void 0:m.data)==null?void 0:p.error)||"Failed",type:"error"}})}};return v.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[v.jsxs("div",{className:"bg-card-bg border border-border rounded-lg p-5 space-y-3",children:[v.jsx("h3",{className:"font-medium text-text-primary",children:"Rename Character"}),v.jsx("input",{value:t,onChange:a=>r(a.target.value),placeholder:"Account ID / Character ID",className:"w-full bg-card-bg border border-border rounded px-3 py-2 text-sm"}),v.jsx("input",{value:s,onChange:a=>i(a.target.value),placeholder:"New Name",className:"w-full bg-card-bg border border-border rounded px-3 py-2 text-sm"}),v.jsx("button",{onClick:()=>n(`/characters/${t}/name`,{name:s}),className:"px-3 py-1.5 rounded text-xs bg-primary/10 border border-primary/20 text-primary",children:"Rename"})]}),v.jsxs("div",{className:"bg-card-bg border border-border rounded-lg p-5 space-y-3",children:[v.jsx("h3",{className:"font-medium text-text-primary",children:"Demo State"}),v.jsx("input",{value:t,onChange:a=>r(a.target.value),placeholder:"Account ID",className:"w-full bg-card-bg border border-border rounded px-3 py-2 text-sm"}),v.jsxs("select",{value:o,onChange:a=>c(a.target.value),className:"w-full bg-card-bg border border-border rounded px-3 py-2 text-sm",children:[v.jsx("option",{value:"true",children:"Demo"}),v.jsx("option",{value:"false",children:"Normal"})]}),v.jsx("button",{onClick:()=>n(`/accounts/${t}/demo`,{demo:o==="true"}),className:"px-3 py-1.5 rounded text-xs bg-primary/10 border border-primary/20 text-primary",children:"Set Demo State"})]}),v.jsxs("div",{className:"bg-card-bg border border-border rounded-lg p-5 space-y-3",children:[v.jsx("h3",{className:"font-medium text-text-primary",children:"Danger Zone"}),v.jsxs("div",{className:"flex flex-wrap gap-2",children:[v.jsx("button",{onClick:()=>{confirm("Delete character?")&&n(`/characters/${t}`,{})},className:"px-3 py-1.5 rounded text-xs bg-danger/10 border border-danger/30 text-danger",children:"Delete Character"}),v.jsx("button",{onClick:()=>{confirm("Delete account?")&&n(`/accounts/${t}`,{})},className:"px-3 py-1.5 rounded text-xs bg-danger/10 border border-danger/30 text-danger",children:"Delete Account"})]})]})]})}function WS({dispatch:e}){const[t,r]=M.useState(""),[s,i]=M.useState(""),[o,c]=M.useState("{}"),[n,a]=M.useState(""),[f,m]=M.useState(!1),p=async()=>{m(!0);try{const _=JSON.parse(o||"{}"),S=await ne.post("/functions/execute",{schema:t||void 0,function:s,args:_});S.data.success?(a(JSON.stringify(S.data.data,null,2)),e({type:"ADD_TOAST",payload:{message:"Function executed",type:"success"}})):e({type:"ADD_TOAST",payload:{message:S.data.error||"Failed",type:"error"}})}catch(_){e({type:"ADD_TOAST",payload:{message:_.message,type:"error"}})}finally{m(!1)}};return v.jsx("div",{className:"max-w-2xl",children:v.jsxs("div",{className:"bg-card-bg border border-border rounded-lg p-5 space-y-4",children:[v.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[v.jsxs("div",{children:[v.jsx("label",{className:"block text-sm text-text-muted mb-2",children:"Schema (optional)"}),v.jsx("input",{value:t,onChange:_=>r(_.target.value),className:"w-full bg-card-bg border border-border rounded-lg px-4 py-2 text-sm text-text-primary",placeholder:"e.g., public"})]}),v.jsxs("div",{children:[v.jsx("label",{className:"block text-sm text-text-muted mb-2",children:"Function Name"}),v.jsx("input",{value:s,onChange:_=>i(_.target.value),className:"w-full bg-card-bg border border-border rounded-lg px-4 py-2 text-sm text-text-primary",placeholder:"e.g., get_player_stats"})]})]}),v.jsxs("div",{children:[v.jsx("label",{className:"block text-sm text-text-muted mb-2",children:"Arguments (JSON)"}),v.jsx("textarea",{value:o,onChange:_=>c(_.target.value),rows:4,className:"w-full bg-card-bg border border-border rounded-lg px-4 py-3 text-sm font-mono text-text-primary focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary resize-y"})]}),v.jsx("button",{onClick:p,disabled:f||!s,className:"px-4 py-2 bg-primary text-white rounded-lg text-sm font-medium hover:bg-primary-dark disabled:opacity-50 transition-colors",children:f?"Running...":"Execute"}),n&&v.jsx("pre",{className:"mt-4 text-xs font-mono bg-code-bg p-4 rounded overflow-auto text-text-secondary",children:n})]})})}function VS({dispatch:e}){const[t,r]=M.useState(""),[s,i]=M.useState(""),[o,c]=M.useState(!1),n=async()=>{var a,f;c(!0);try{const m=await ne.post("/query",{query:t});m.data.success?(i(JSON.stringify(m.data.data,null,2)),e({type:"ADD_TOAST",payload:{message:"Query executed",type:"success"}})):e({type:"ADD_TOAST",payload:{message:m.data.error||"Failed",type:"error"}})}catch(m){e({type:"ADD_TOAST",payload:{message:((f=(a=m.response)==null?void 0:a.data)==null?void 0:f.error)||m.message,type:"error"}})}finally{c(!1)}};return v.jsx("div",{className:"max-w-3xl",children:v.jsxs("div",{className:"bg-card-bg border border-border rounded-lg p-5 space-y-4",children:[v.jsxs("div",{className:"flex items-center justify-between",children:[v.jsx("label",{className:"text-sm text-text-muted",children:"SQL Query (Read-Only SELECT)"}),v.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wider bg-danger/10 px-2 py-0.5 rounded border border-danger/20",children:"Read Only"})]}),v.jsx("textarea",{value:t,onChange:a=>r(a.target.value),rows:6,className:"w-full bg-card-bg border border-border rounded-lg px-4 py-3 text-sm font-mono text-text-primary focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary resize-y",placeholder:"SELECT * FROM public.characters LIMIT 10;"}),v.jsx("button",{onClick:n,disabled:o||!t.trim(),className:"px-4 py-2 bg-primary text-white rounded-lg text-sm font-medium hover:bg-primary-dark disabled:opacity-50 transition-colors",children:o?"Running...":"Run Query"}),s&&v.jsx("pre",{className:"mt-4 text-xs font-mono bg-code-bg p-4 rounded overflow-auto text-text-secondary",children:s})]})})}function qS({dispatch:e}){const[t,r]=M.useState(50),[s,i]=M.useState([]),[o,c]=M.useState(!1),n=async()=>{var a,f;c(!0);try{const m=await ne.get(`/audit/logs?limit=${t}`);m.data.success&&i(m.data.data)}catch(m){e({type:"ADD_TOAST",payload:{message:((f=(a=m.response)==null?void 0:a.data)==null?void 0:f.error)||"Failed",type:"error"}})}finally{c(!1)}};return v.jsxs("div",{children:[v.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[v.jsx("button",{onClick:n,disabled:o,className:"px-4 py-2 bg-primary text-white rounded-lg text-sm font-medium hover:bg-primary-dark disabled:opacity-50 transition-colors",children:o?"Loading...":"Load Logs"}),v.jsx("select",{value:t,onChange:a=>r(Number(a.target.value)),className:"bg-card-bg border border-border rounded px-3 py-2 text-sm text-text-primary",children:[10,25,50,100,250].map(a=>v.jsxs("option",{value:a,children:[a," entries"]},a))})]}),v.jsx("div",{className:"overflow-x-auto rounded-lg border border-border",children:v.jsxs("table",{className:"w-full text-sm",children:[v.jsx("thead",{children:v.jsxs("tr",{className:"border-b border-border",children:[v.jsx("th",{className:"text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase",children:"Time"}),v.jsx("th",{className:"text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase",children:"Admin"}),v.jsx("th",{className:"text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase",children:"Action"}),v.jsx("th",{className:"text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase",children:"Target"}),v.jsx("th",{className:"text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase",children:"Details"})]})}),v.jsx("tbody",{children:s.map((a,f)=>v.jsxs("tr",{className:"border-b border-border last:border-0 hover:bg-hover/50",children:[v.jsx("td",{className:"px-4 py-3 text-text-muted text-xs",children:new Date(a.timestamp).toLocaleString()}),v.jsx("td",{className:"px-4 py-3",children:a.admin_name}),v.jsx("td",{className:"px-4 py-3",children:v.jsx("span",{className:"px-2 py-0.5 rounded text-[11px] font-semibold bg-primary/10 text-primary border border-primary/20",children:a.action})}),v.jsxs("td",{className:"px-4 py-3",children:[a.target_type,": ",a.target_id]}),v.jsx("td",{className:"px-4 py-3 text-xs text-text-muted max-w-md truncate",children:JSON.stringify(a.details)})]},f))})]})})]})}const KS=["Global","Guild","System","Combat"];function XS(){const[e,t]=M.useState("Global"),[r,s]=M.useState([]),i=M.useRef(null);return M.useEffect(()=>{async function o(){try{const c=await ne.get(`/chat/history?channel=${e}&limit=100`);c.data.success&&s(c.data.data)}catch(c){console.error(c)}}o()},[e]),M.useEffect(()=>{const o=new EventSource("/api/events/stream");return o.addEventListener("chat_message",c=>{try{const n=JSON.parse(c.data);(n.channel===e||e==="Global")&&s(a=>[...a.slice(-199),n])}catch{}}),()=>o.close()},[e]),M.useEffect(()=>{var o;(o=i.current)==null||o.scrollIntoView({behavior:"smooth"})},[r]),v.jsxs("div",{className:"h-[calc(100vh-140px)] flex flex-col",children:[v.jsxs("div",{className:"flex items-center justify-between mb-4",children:[v.jsx("h1",{className:"font-serif text-3xl text-primary",children:"Chat Monitor"}),v.jsx("div",{className:"flex gap-2",children:KS.map(o=>v.jsx("button",{onClick:()=>t(o),className:`px-3 py-1.5 rounded text-xs font-medium border ${e===o?"bg-primary/10 border-primary text-primary":"bg-card-bg border-border text-text-muted hover:text-text-primary"}`,children:o},o))})]}),v.jsx("div",{className:"flex-1 bg-card-bg border border-border rounded-lg overflow-hidden flex flex-col",children:v.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-2 font-mono text-sm",children:[r.map(o=>v.jsxs("div",{className:"flex gap-3",children:[v.jsx("span",{className:"text-text-muted text-xs whitespace-nowrap",children:new Date(o.timestamp).toLocaleTimeString()}),v.jsxs("span",{className:"text-primary font-semibold whitespace-nowrap",children:["[",o.channel,"]"]}),v.jsxs("span",{className:"text-accent font-semibold whitespace-nowrap",children:[o.sender,":"]}),v.jsx("span",{className:"text-text-secondary break-all",children:o.message})]},o.id)),v.jsx("div",{ref:i})]})})]})}var Ap={exports:{}};(function(e,t){(function(r,s){e.exports=s()})(self,()=>(()=>{var r={4567:function(c,n,a){var f=this&&this.__decorate||function(d,g,x,C){var k,w=arguments.length,E=w<3?g:C===null?C=Object.getOwnPropertyDescriptor(g,x):C;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")E=Reflect.decorate(d,g,x,C);else for(var L=d.length-1;L>=0;L--)(k=d[L])&&(E=(w<3?k(E):w>3?k(g,x,E):k(g,x))||E);return w>3&&E&&Object.defineProperty(g,x,E),E},m=this&&this.__param||function(d,g){return function(x,C){g(x,C,d)}};Object.defineProperty(n,"__esModule",{value:!0}),n.AccessibilityManager=void 0;const p=a(9042),_=a(6114),S=a(9924),b=a(844),y=a(5596),u=a(4725),h=a(3656);let l=n.AccessibilityManager=class extends b.Disposable{constructor(d,g){super(),this._terminal=d,this._renderService=g,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="",this._accessibilityContainer=document.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=document.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let x=0;xthis._handleBoundaryFocus(x,0),this._bottomBoundaryFocusListener=x=>this._handleBoundaryFocus(x,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions(),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=document.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this.register(new S.TimeBasedDebouncer(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this.register(this._terminal.onResize(x=>this._handleResize(x.rows))),this.register(this._terminal.onRender(x=>this._refreshRows(x.start,x.end))),this.register(this._terminal.onScroll(()=>this._refreshRows())),this.register(this._terminal.onA11yChar(x=>this._handleChar(x))),this.register(this._terminal.onLineFeed(()=>this._handleChar(` +`))),this.register(this._terminal.onA11yTab(x=>this._handleTab(x))),this.register(this._terminal.onKey(x=>this._handleKey(x.key))),this.register(this._terminal.onBlur(()=>this._clearLiveRegion())),this.register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._screenDprMonitor=new y.ScreenDprMonitor(window),this.register(this._screenDprMonitor),this._screenDprMonitor.setListener(()=>this._refreshRowsDimensions()),this.register((0,h.addDisposableDomListener)(window,"resize",()=>this._refreshRowsDimensions())),this._refreshRows(),this.register((0,b.toDisposable)(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(d){for(let g=0;g0?this._charsToConsume.shift()!==d&&(this._charsToAnnounce+=d):this._charsToAnnounce+=d,d===` +`&&(this._liveRegionLineCount++,this._liveRegionLineCount===21&&(this._liveRegion.textContent+=p.tooMuchOutput)),_.isMac&&this._liveRegion.textContent&&this._liveRegion.textContent.length>0&&!this._liveRegion.parentNode&&setTimeout(()=>{this._accessibilityContainer.appendChild(this._liveRegion)},0))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0,_.isMac&&this._liveRegion.remove()}_handleKey(d){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(d)||this._charsToConsume.push(d)}_refreshRows(d,g){this._liveRegionDebouncer.refresh(d,g,this._terminal.rows)}_renderRows(d,g){const x=this._terminal.buffer,C=x.lines.length.toString();for(let k=d;k<=g;k++){const w=x.translateBufferLineToString(x.ydisp+k,!0),E=(x.ydisp+k+1).toString(),L=this._rowElements[k];L&&(w.length===0?L.innerText=" ":L.textContent=w,L.setAttribute("aria-posinset",E),L.setAttribute("aria-setsize",C))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(d,g){const x=d.target,C=this._rowElements[g===0?1:this._rowElements.length-2];if(x.getAttribute("aria-posinset")===(g===0?"1":`${this._terminal.buffer.lines.length}`)||d.relatedTarget!==C)return;let k,w;if(g===0?(k=x,w=this._rowElements.pop(),this._rowContainer.removeChild(w)):(k=this._rowElements.shift(),w=x,this._rowContainer.removeChild(k)),k.removeEventListener("focus",this._topBoundaryFocusListener),w.removeEventListener("focus",this._bottomBoundaryFocusListener),g===0){const E=this._createAccessibilityTreeNode();this._rowElements.unshift(E),this._rowContainer.insertAdjacentElement("afterbegin",E)}else{const E=this._createAccessibilityTreeNode();this._rowElements.push(E),this._rowContainer.appendChild(E)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(g===0?-1:1),this._rowElements[g===0?1:this._rowElements.length-2].focus(),d.preventDefault(),d.stopImmediatePropagation()}_handleResize(d){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let g=this._rowContainer.children.length;gd;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){const d=document.createElement("div");return d.setAttribute("role","listitem"),d.tabIndex=-1,this._refreshRowDimensions(d),d}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){this._accessibilityContainer.style.width=`${this._renderService.dimensions.css.canvas.width}px`,this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let d=0;d{function a(_){return _.replace(/\r?\n/g,"\r")}function f(_,S){return S?"\x1B[200~"+_+"\x1B[201~":_}function m(_,S,b,y){_=f(_=a(_),b.decPrivateModes.bracketedPasteMode&&y.rawOptions.ignoreBracketedPasteMode!==!0),b.triggerDataEvent(_,!0),S.value=""}function p(_,S,b){const y=b.getBoundingClientRect(),u=_.clientX-y.left-10,h=_.clientY-y.top-10;S.style.width="20px",S.style.height="20px",S.style.left=`${u}px`,S.style.top=`${h}px`,S.style.zIndex="1000",S.focus()}Object.defineProperty(n,"__esModule",{value:!0}),n.rightClickHandler=n.moveTextAreaUnderMouseCursor=n.paste=n.handlePasteEvent=n.copyHandler=n.bracketTextForPaste=n.prepareTextForTerminal=void 0,n.prepareTextForTerminal=a,n.bracketTextForPaste=f,n.copyHandler=function(_,S){_.clipboardData&&_.clipboardData.setData("text/plain",S.selectionText),_.preventDefault()},n.handlePasteEvent=function(_,S,b,y){_.stopPropagation(),_.clipboardData&&m(_.clipboardData.getData("text/plain"),S,b,y)},n.paste=m,n.moveTextAreaUnderMouseCursor=p,n.rightClickHandler=function(_,S,b,y,u){p(_,S,b),u&&y.rightClickSelect(_),S.value=y.selectionText,S.select()}},7239:(c,n,a)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.ColorContrastCache=void 0;const f=a(1505);n.ColorContrastCache=class{constructor(){this._color=new f.TwoKeyMap,this._css=new f.TwoKeyMap}setCss(m,p,_){this._css.set(m,p,_)}getCss(m,p){return this._css.get(m,p)}setColor(m,p,_){this._color.set(m,p,_)}getColor(m,p){return this._color.get(m,p)}clear(){this._color.clear(),this._css.clear()}}},3656:(c,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.addDisposableDomListener=void 0,n.addDisposableDomListener=function(a,f,m,p){a.addEventListener(f,m,p);let _=!1;return{dispose:()=>{_||(_=!0,a.removeEventListener(f,m,p))}}}},6465:function(c,n,a){var f=this&&this.__decorate||function(u,h,l,d){var g,x=arguments.length,C=x<3?h:d===null?d=Object.getOwnPropertyDescriptor(h,l):d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")C=Reflect.decorate(u,h,l,d);else for(var k=u.length-1;k>=0;k--)(g=u[k])&&(C=(x<3?g(C):x>3?g(h,l,C):g(h,l))||C);return x>3&&C&&Object.defineProperty(h,l,C),C},m=this&&this.__param||function(u,h){return function(l,d){h(l,d,u)}};Object.defineProperty(n,"__esModule",{value:!0}),n.Linkifier2=void 0;const p=a(3656),_=a(8460),S=a(844),b=a(2585);let y=n.Linkifier2=class extends S.Disposable{get currentLink(){return this._currentLink}constructor(u){super(),this._bufferService=u,this._linkProviders=[],this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this.register(new _.EventEmitter),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this.register(new _.EventEmitter),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this.register((0,S.getDisposeArrayDisposable)(this._linkCacheDisposables)),this.register((0,S.toDisposable)(()=>{this._lastMouseEvent=void 0})),this.register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0}))}registerLinkProvider(u){return this._linkProviders.push(u),{dispose:()=>{const h=this._linkProviders.indexOf(u);h!==-1&&this._linkProviders.splice(h,1)}}}attachToDom(u,h,l){this._element=u,this._mouseService=h,this._renderService=l,this.register((0,p.addDisposableDomListener)(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this.register((0,p.addDisposableDomListener)(this._element,"mousemove",this._handleMouseMove.bind(this))),this.register((0,p.addDisposableDomListener)(this._element,"mousedown",this._handleMouseDown.bind(this))),this.register((0,p.addDisposableDomListener)(this._element,"mouseup",this._handleMouseUp.bind(this)))}_handleMouseMove(u){if(this._lastMouseEvent=u,!this._element||!this._mouseService)return;const h=this._positionFromMouseEvent(u,this._element,this._mouseService);if(!h)return;this._isMouseOut=!1;const l=u.composedPath();for(let d=0;d{x==null||x.forEach(C=>{C.link.dispose&&C.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=u.y);let g=!1;for(const[x,C]of this._linkProviders.entries())h?!((d=this._activeProviderReplies)===null||d===void 0)&&d.get(x)&&(g=this._checkLinkProviderResult(x,u,g)):C.provideLinks(u.y,k=>{var w,E;if(this._isMouseOut)return;const L=k==null?void 0:k.map(N=>({link:N}));(w=this._activeProviderReplies)===null||w===void 0||w.set(x,L),g=this._checkLinkProviderResult(x,u,g),((E=this._activeProviderReplies)===null||E===void 0?void 0:E.size)===this._linkProviders.length&&this._removeIntersectingLinks(u.y,this._activeProviderReplies)})}_removeIntersectingLinks(u,h){const l=new Set;for(let d=0;du?this._bufferService.cols:C.link.range.end.x;for(let E=k;E<=w;E++){if(l.has(E)){g.splice(x--,1);break}l.add(E)}}}}_checkLinkProviderResult(u,h,l){var d;if(!this._activeProviderReplies)return l;const g=this._activeProviderReplies.get(u);let x=!1;for(let C=0;Cthis._linkAtPosition(k.link,h));C&&(l=!0,this._handleNewLink(C))}if(this._activeProviderReplies.size===this._linkProviders.length&&!l)for(let C=0;Cthis._linkAtPosition(w.link,h));if(k){l=!0,this._handleNewLink(k);break}}return l}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(u){if(!this._element||!this._mouseService||!this._currentLink)return;const h=this._positionFromMouseEvent(u,this._element,this._mouseService);h&&this._mouseDownLink===this._currentLink&&this._linkAtPosition(this._currentLink.link,h)&&this._currentLink.link.activate(u,this._currentLink.link.text)}_clearCurrentLink(u,h){this._element&&this._currentLink&&this._lastMouseEvent&&(!u||!h||this._currentLink.link.range.start.y>=u&&this._currentLink.link.range.end.y<=h)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,(0,S.disposeArray)(this._linkCacheDisposables))}_handleNewLink(u){if(!this._element||!this._lastMouseEvent||!this._mouseService)return;const h=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);h&&this._linkAtPosition(u.link,h)&&(this._currentLink=u,this._currentLink.state={decorations:{underline:u.link.decorations===void 0||u.link.decorations.underline,pointerCursor:u.link.decorations===void 0||u.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,u.link,this._lastMouseEvent),u.link.decorations={},Object.defineProperties(u.link.decorations,{pointerCursor:{get:()=>{var l,d;return(d=(l=this._currentLink)===null||l===void 0?void 0:l.state)===null||d===void 0?void 0:d.decorations.pointerCursor},set:l=>{var d,g;!((d=this._currentLink)===null||d===void 0)&&d.state&&this._currentLink.state.decorations.pointerCursor!==l&&(this._currentLink.state.decorations.pointerCursor=l,this._currentLink.state.isHovered&&((g=this._element)===null||g===void 0||g.classList.toggle("xterm-cursor-pointer",l)))}},underline:{get:()=>{var l,d;return(d=(l=this._currentLink)===null||l===void 0?void 0:l.state)===null||d===void 0?void 0:d.decorations.underline},set:l=>{var d,g,x;!((d=this._currentLink)===null||d===void 0)&&d.state&&((x=(g=this._currentLink)===null||g===void 0?void 0:g.state)===null||x===void 0?void 0:x.decorations.underline)!==l&&(this._currentLink.state.decorations.underline=l,this._currentLink.state.isHovered&&this._fireUnderlineEvent(u.link,l))}}}),this._renderService&&this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(l=>{if(!this._currentLink)return;const d=l.start===0?0:l.start+1+this._bufferService.buffer.ydisp,g=this._bufferService.buffer.ydisp+1+l.end;if(this._currentLink.link.range.start.y>=d&&this._currentLink.link.range.end.y<=g&&(this._clearCurrentLink(d,g),this._lastMouseEvent&&this._element)){const x=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);x&&this._askForLink(x,!1)}})))}_linkHover(u,h,l){var d;!((d=this._currentLink)===null||d===void 0)&&d.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(h,!0),this._currentLink.state.decorations.pointerCursor&&u.classList.add("xterm-cursor-pointer")),h.hover&&h.hover(l,h.text)}_fireUnderlineEvent(u,h){const l=u.range,d=this._bufferService.buffer.ydisp,g=this._createLinkUnderlineEvent(l.start.x-1,l.start.y-d-1,l.end.x,l.end.y-d-1,void 0);(h?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(g)}_linkLeave(u,h,l){var d;!((d=this._currentLink)===null||d===void 0)&&d.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(h,!1),this._currentLink.state.decorations.pointerCursor&&u.classList.remove("xterm-cursor-pointer")),h.leave&&h.leave(l,h.text)}_linkAtPosition(u,h){const l=u.range.start.y*this._bufferService.cols+u.range.start.x,d=u.range.end.y*this._bufferService.cols+u.range.end.x,g=h.y*this._bufferService.cols+h.x;return l<=g&&g<=d}_positionFromMouseEvent(u,h,l){const d=l.getCoords(u,h,this._bufferService.cols,this._bufferService.rows);if(d)return{x:d[0],y:d[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(u,h,l,d,g){return{x1:u,y1:h,x2:l,y2:d,cols:this._bufferService.cols,fg:g}}};n.Linkifier2=y=f([m(0,b.IBufferService)],y)},9042:(c,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.tooMuchOutput=n.promptLabel=void 0,n.promptLabel="Terminal input",n.tooMuchOutput="Too much output to announce, navigate to rows manually to read"},3730:function(c,n,a){var f=this&&this.__decorate||function(y,u,h,l){var d,g=arguments.length,x=g<3?u:l===null?l=Object.getOwnPropertyDescriptor(u,h):l;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")x=Reflect.decorate(y,u,h,l);else for(var C=y.length-1;C>=0;C--)(d=y[C])&&(x=(g<3?d(x):g>3?d(u,h,x):d(u,h))||x);return g>3&&x&&Object.defineProperty(u,h,x),x},m=this&&this.__param||function(y,u){return function(h,l){u(h,l,y)}};Object.defineProperty(n,"__esModule",{value:!0}),n.OscLinkProvider=void 0;const p=a(511),_=a(2585);let S=n.OscLinkProvider=class{constructor(y,u,h){this._bufferService=y,this._optionsService=u,this._oscLinkService=h}provideLinks(y,u){var h;const l=this._bufferService.buffer.lines.get(y-1);if(!l)return void u(void 0);const d=[],g=this._optionsService.rawOptions.linkHandler,x=new p.CellData,C=l.getTrimmedLength();let k=-1,w=-1,E=!1;for(let L=0;Lg?g.activate(F,z,O):b(0,z),hover:(F,z)=>{var W;return(W=g==null?void 0:g.hover)===null||W===void 0?void 0:W.call(g,F,z,O)},leave:(F,z)=>{var W;return(W=g==null?void 0:g.leave)===null||W===void 0?void 0:W.call(g,F,z,O)}})}E=!1,x.hasExtendedAttrs()&&x.extended.urlId?(w=L,k=x.extended.urlId):(w=-1,k=-1)}}u(d)}};function b(y,u){if(confirm(`Do you want to navigate to ${u}? + +WARNING: This link could potentially be dangerous`)){const h=window.open();if(h){try{h.opener=null}catch{}h.location.href=u}else console.warn("Opening link blocked as opener could not be cleared")}}n.OscLinkProvider=S=f([m(0,_.IBufferService),m(1,_.IOptionsService),m(2,_.IOscLinkService)],S)},6193:(c,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.RenderDebouncer=void 0,n.RenderDebouncer=class{constructor(a,f){this._parentWindow=a,this._renderCallback=f,this._refreshCallbacks=[]}dispose(){this._animationFrame&&(this._parentWindow.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)}addRefreshCallback(a){return this._refreshCallbacks.push(a),this._animationFrame||(this._animationFrame=this._parentWindow.requestAnimationFrame(()=>this._innerRefresh())),this._animationFrame}refresh(a,f,m){this._rowCount=m,a=a!==void 0?a:0,f=f!==void 0?f:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,a):a,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,f):f,this._animationFrame||(this._animationFrame=this._parentWindow.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return void this._runRefreshCallbacks();const a=Math.max(this._rowStart,0),f=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(a,f),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(const a of this._refreshCallbacks)a(0);this._refreshCallbacks=[]}}},5596:(c,n,a)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.ScreenDprMonitor=void 0;const f=a(844);class m extends f.Disposable{constructor(_){super(),this._parentWindow=_,this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this.register((0,f.toDisposable)(()=>{this.clearListener()}))}setListener(_){this._listener&&this.clearListener(),this._listener=_,this._outerListener=()=>{this._listener&&(this._listener(this._parentWindow.devicePixelRatio,this._currentDevicePixelRatio),this._updateDpr())},this._updateDpr()}_updateDpr(){var _;this._outerListener&&((_=this._resolutionMediaMatchList)===null||_===void 0||_.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){this._resolutionMediaMatchList&&this._listener&&this._outerListener&&(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._listener=void 0,this._outerListener=void 0)}}n.ScreenDprMonitor=m},3236:(c,n,a)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Terminal=void 0;const f=a(3614),m=a(3656),p=a(6465),_=a(9042),S=a(3730),b=a(1680),y=a(3107),u=a(5744),h=a(2950),l=a(1296),d=a(428),g=a(4269),x=a(5114),C=a(8934),k=a(3230),w=a(9312),E=a(4725),L=a(6731),N=a(8055),O=a(8969),P=a(8460),F=a(844),z=a(6114),W=a(8437),V=a(2584),R=a(7399),D=a(5941),A=a(9074),B=a(2585),H=a(5435),q=a(4567),G=typeof window<"u"?window.document:null;class X extends O.CoreTerminal{get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}constructor(T={}){super(T),this.browser=z,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this.register(new F.MutableDisposable),this._onCursorMove=this.register(new P.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onKey=this.register(new P.EventEmitter),this.onKey=this._onKey.event,this._onRender=this.register(new P.EventEmitter),this.onRender=this._onRender.event,this._onSelectionChange=this.register(new P.EventEmitter),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this.register(new P.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onBell=this.register(new P.EventEmitter),this.onBell=this._onBell.event,this._onFocus=this.register(new P.EventEmitter),this._onBlur=this.register(new P.EventEmitter),this._onA11yCharEmitter=this.register(new P.EventEmitter),this._onA11yTabEmitter=this.register(new P.EventEmitter),this._onWillOpen=this.register(new P.EventEmitter),this._setup(),this.linkifier2=this.register(this._instantiationService.createInstance(p.Linkifier2)),this.linkifier2.registerLinkProvider(this._instantiationService.createInstance(S.OscLinkProvider)),this._decorationService=this._instantiationService.createInstance(A.DecorationService),this._instantiationService.setService(B.IDecorationService,this._decorationService),this.register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this.register(this._inputHandler.onRequestRefreshRows((j,$)=>this.refresh(j,$))),this.register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this.register(this._inputHandler.onRequestReset(()=>this.reset())),this.register(this._inputHandler.onRequestWindowsOptionsReport(j=>this._reportWindowsOptions(j))),this.register(this._inputHandler.onColor(j=>this._handleColorEvent(j))),this.register((0,P.forwardEvent)(this._inputHandler.onCursorMove,this._onCursorMove)),this.register((0,P.forwardEvent)(this._inputHandler.onTitleChange,this._onTitleChange)),this.register((0,P.forwardEvent)(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this.register((0,P.forwardEvent)(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this.register(this._bufferService.onResize(j=>this._afterResize(j.cols,j.rows))),this.register((0,F.toDisposable)(()=>{var j,$;this._customKeyEventHandler=void 0,($=(j=this.element)===null||j===void 0?void 0:j.parentNode)===null||$===void 0||$.removeChild(this.element)}))}_handleColorEvent(T){if(this._themeService)for(const j of T){let $,U="";switch(j.index){case 256:$="foreground",U="10";break;case 257:$="background",U="11";break;case 258:$="cursor",U="12";break;default:$="ansi",U="4;"+j.index}switch(j.type){case 0:const ee=N.color.toColorRGB($==="ansi"?this._themeService.colors.ansi[j.index]:this._themeService.colors[$]);this.coreService.triggerDataEvent(`${V.C0.ESC}]${U};${(0,D.toRgbString)(ee)}${V.C1_ESCAPED.ST}`);break;case 1:if($==="ansi")this._themeService.modifyColors(J=>J.ansi[j.index]=N.rgba.toColor(...j.color));else{const J=$;this._themeService.modifyColors(oe=>oe[J]=N.rgba.toColor(...j.color))}break;case 2:this._themeService.restoreColor(j.index)}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(T){T?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(q.AccessibilityManager,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(T){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(V.C0.ESC+"[I"),this.updateCursorStyle(T),this.element.classList.add("focus"),this._showCursor(),this._onFocus.fire()}blur(){var T;return(T=this.textarea)===null||T===void 0?void 0:T.blur()}_handleTextAreaBlur(){this.textarea.value="",this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(V.C0.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;const T=this.buffer.ybase+this.buffer.y,j=this.buffer.lines.get(T);if(!j)return;const $=Math.min(this.buffer.x,this.cols-1),U=this._renderService.dimensions.css.cell.height,ee=j.getWidth($),J=this._renderService.dimensions.css.cell.width*ee,oe=this.buffer.y*this._renderService.dimensions.css.cell.height,ce=$*this._renderService.dimensions.css.cell.width;this.textarea.style.left=ce+"px",this.textarea.style.top=oe+"px",this.textarea.style.width=J+"px",this.textarea.style.height=U+"px",this.textarea.style.lineHeight=U+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this.register((0,m.addDisposableDomListener)(this.element,"copy",j=>{this.hasSelection()&&(0,f.copyHandler)(j,this._selectionService)}));const T=j=>(0,f.handlePasteEvent)(j,this.textarea,this.coreService,this.optionsService);this.register((0,m.addDisposableDomListener)(this.textarea,"paste",T)),this.register((0,m.addDisposableDomListener)(this.element,"paste",T)),z.isFirefox?this.register((0,m.addDisposableDomListener)(this.element,"mousedown",j=>{j.button===2&&(0,f.rightClickHandler)(j,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this.register((0,m.addDisposableDomListener)(this.element,"contextmenu",j=>{(0,f.rightClickHandler)(j,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),z.isLinux&&this.register((0,m.addDisposableDomListener)(this.element,"auxclick",j=>{j.button===1&&(0,f.moveTextAreaUnderMouseCursor)(j,this.textarea,this.screenElement)}))}_bindKeys(){this.register((0,m.addDisposableDomListener)(this.textarea,"keyup",T=>this._keyUp(T),!0)),this.register((0,m.addDisposableDomListener)(this.textarea,"keydown",T=>this._keyDown(T),!0)),this.register((0,m.addDisposableDomListener)(this.textarea,"keypress",T=>this._keyPress(T),!0)),this.register((0,m.addDisposableDomListener)(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this.register((0,m.addDisposableDomListener)(this.textarea,"compositionupdate",T=>this._compositionHelper.compositionupdate(T))),this.register((0,m.addDisposableDomListener)(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this.register((0,m.addDisposableDomListener)(this.textarea,"input",T=>this._inputEvent(T),!0)),this.register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(T){var j;if(!T)throw new Error("Terminal requires a parent element.");T.isConnected||this._logService.debug("Terminal.open was called on an element that was not attached to the DOM"),this._document=T.ownerDocument,this.element=this._document.createElement("div"),this.element.dir="ltr",this.element.classList.add("terminal"),this.element.classList.add("xterm"),T.appendChild(this.element);const $=G.createDocumentFragment();this._viewportElement=G.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),$.appendChild(this._viewportElement),this._viewportScrollArea=G.createElement("div"),this._viewportScrollArea.classList.add("xterm-scroll-area"),this._viewportElement.appendChild(this._viewportScrollArea),this.screenElement=G.createElement("div"),this.screenElement.classList.add("xterm-screen"),this._helperContainer=G.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),$.appendChild(this.screenElement),this.textarea=G.createElement("textarea"),this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",_.promptLabel),z.isChromeOS||this.textarea.setAttribute("aria-multiline","false"),this.textarea.setAttribute("autocorrect","off"),this.textarea.setAttribute("autocapitalize","off"),this.textarea.setAttribute("spellcheck","false"),this.textarea.tabIndex=0,this._coreBrowserService=this._instantiationService.createInstance(x.CoreBrowserService,this.textarea,(j=this._document.defaultView)!==null&&j!==void 0?j:window),this._instantiationService.setService(E.ICoreBrowserService,this._coreBrowserService),this.register((0,m.addDisposableDomListener)(this.textarea,"focus",U=>this._handleTextAreaFocus(U))),this.register((0,m.addDisposableDomListener)(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(d.CharSizeService,this._document,this._helperContainer),this._instantiationService.setService(E.ICharSizeService,this._charSizeService),this._themeService=this._instantiationService.createInstance(L.ThemeService),this._instantiationService.setService(E.IThemeService,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(g.CharacterJoinerService),this._instantiationService.setService(E.ICharacterJoinerService,this._characterJoinerService),this._renderService=this.register(this._instantiationService.createInstance(k.RenderService,this.rows,this.screenElement)),this._instantiationService.setService(E.IRenderService,this._renderService),this.register(this._renderService.onRenderedViewportChange(U=>this._onRender.fire(U))),this.onResize(U=>this._renderService.resize(U.cols,U.rows)),this._compositionView=G.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(h.CompositionHelper,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this.element.appendChild($);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._mouseService=this._instantiationService.createInstance(C.MouseService),this._instantiationService.setService(E.IMouseService,this._mouseService),this.viewport=this._instantiationService.createInstance(b.Viewport,this._viewportElement,this._viewportScrollArea),this.viewport.onRequestScrollLines(U=>this.scrollLines(U.amount,U.suppressScrollEvent,1)),this.register(this._inputHandler.onRequestSyncScrollBar(()=>this.viewport.syncScrollArea())),this.register(this.viewport),this.register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this.register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this.register(this.onBlur(()=>this._renderService.handleBlur())),this.register(this.onFocus(()=>this._renderService.handleFocus())),this.register(this._renderService.onDimensionsChange(()=>this.viewport.syncScrollArea())),this._selectionService=this.register(this._instantiationService.createInstance(w.SelectionService,this.element,this.screenElement,this.linkifier2)),this._instantiationService.setService(E.ISelectionService,this._selectionService),this.register(this._selectionService.onRequestScrollLines(U=>this.scrollLines(U.amount,U.suppressScrollEvent))),this.register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this.register(this._selectionService.onRequestRedraw(U=>this._renderService.handleSelectionChanged(U.start,U.end,U.columnSelectMode))),this.register(this._selectionService.onLinuxMouseSelection(U=>{this.textarea.value=U,this.textarea.focus(),this.textarea.select()})),this.register(this._onScroll.event(U=>{this.viewport.syncScrollArea(),this._selectionService.refresh()})),this.register((0,m.addDisposableDomListener)(this._viewportElement,"scroll",()=>this._selectionService.refresh())),this.linkifier2.attachToDom(this.screenElement,this._mouseService,this._renderService),this.register(this._instantiationService.createInstance(y.BufferDecorationRenderer,this.screenElement)),this.register((0,m.addDisposableDomListener)(this.element,"mousedown",U=>this._selectionService.handleMouseDown(U))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add("enable-mouse-events")):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(q.AccessibilityManager,this)),this.register(this.optionsService.onSpecificOptionChange("screenReaderMode",U=>this._handleScreenReaderModeOptionChange(U))),this.options.overviewRulerWidth&&(this._overviewRulerRenderer=this.register(this._instantiationService.createInstance(u.OverviewRulerRenderer,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRulerWidth",U=>{!this._overviewRulerRenderer&&U&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this.register(this._instantiationService.createInstance(u.OverviewRulerRenderer,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(l.DomRenderer,this.element,this.screenElement,this._viewportElement,this.linkifier2)}bindMouse(){const T=this,j=this.element;function $(J){const oe=T._mouseService.getMouseReportCoords(J,T.screenElement);if(!oe)return!1;let ce,Ne;switch(J.overrideType||J.type){case"mousemove":Ne=32,J.buttons===void 0?(ce=3,J.button!==void 0&&(ce=J.button<3?J.button:3)):ce=1&J.buttons?0:4&J.buttons?1:2&J.buttons?2:3;break;case"mouseup":Ne=0,ce=J.button<3?J.button:3;break;case"mousedown":Ne=1,ce=J.button<3?J.button:3;break;case"wheel":if(T.viewport.getLinesScrolled(J)===0)return!1;Ne=J.deltaY<0?0:1,ce=4;break;default:return!1}return!(Ne===void 0||ce===void 0||ce>4)&&T.coreMouseService.triggerMouseEvent({col:oe.col,row:oe.row,x:oe.x,y:oe.y,button:ce,action:Ne,ctrl:J.ctrlKey,alt:J.altKey,shift:J.shiftKey})}const U={mouseup:null,wheel:null,mousedrag:null,mousemove:null},ee={mouseup:J=>($(J),J.buttons||(this._document.removeEventListener("mouseup",U.mouseup),U.mousedrag&&this._document.removeEventListener("mousemove",U.mousedrag)),this.cancel(J)),wheel:J=>($(J),this.cancel(J,!0)),mousedrag:J=>{J.buttons&&$(J)},mousemove:J=>{J.buttons||$(J)}};this.register(this.coreMouseService.onProtocolChange(J=>{J?(this.optionsService.rawOptions.logLevel==="debug"&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(J)),this.element.classList.add("enable-mouse-events"),this._selectionService.disable()):(this._logService.debug("Unbinding from mouse events."),this.element.classList.remove("enable-mouse-events"),this._selectionService.enable()),8&J?U.mousemove||(j.addEventListener("mousemove",ee.mousemove),U.mousemove=ee.mousemove):(j.removeEventListener("mousemove",U.mousemove),U.mousemove=null),16&J?U.wheel||(j.addEventListener("wheel",ee.wheel,{passive:!1}),U.wheel=ee.wheel):(j.removeEventListener("wheel",U.wheel),U.wheel=null),2&J?U.mouseup||(j.addEventListener("mouseup",ee.mouseup),U.mouseup=ee.mouseup):(this._document.removeEventListener("mouseup",U.mouseup),j.removeEventListener("mouseup",U.mouseup),U.mouseup=null),4&J?U.mousedrag||(U.mousedrag=ee.mousedrag):(this._document.removeEventListener("mousemove",U.mousedrag),U.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this.register((0,m.addDisposableDomListener)(j,"mousedown",J=>{if(J.preventDefault(),this.focus(),this.coreMouseService.areMouseEventsActive&&!this._selectionService.shouldForceSelection(J))return $(J),U.mouseup&&this._document.addEventListener("mouseup",U.mouseup),U.mousedrag&&this._document.addEventListener("mousemove",U.mousedrag),this.cancel(J)})),this.register((0,m.addDisposableDomListener)(j,"wheel",J=>{if(!U.wheel){if(!this.buffer.hasScrollback){const oe=this.viewport.getLinesScrolled(J);if(oe===0)return;const ce=V.C0.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(J.deltaY<0?"A":"B");let Ne="";for(let Rr=0;Rr{if(!this.coreMouseService.areMouseEventsActive)return this.viewport.handleTouchStart(J),this.cancel(J)},{passive:!0})),this.register((0,m.addDisposableDomListener)(j,"touchmove",J=>{if(!this.coreMouseService.areMouseEventsActive)return this.viewport.handleTouchMove(J)?void 0:this.cancel(J)},{passive:!1}))}refresh(T,j){var $;($=this._renderService)===null||$===void 0||$.refreshRows(T,j)}updateCursorStyle(T){var j;!((j=this._selectionService)===null||j===void 0)&&j.shouldColumnSelect(T)?this.element.classList.add("column-select"):this.element.classList.remove("column-select")}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(T,j,$=0){var U;$===1?(super.scrollLines(T,j,$),this.refresh(0,this.rows-1)):(U=this.viewport)===null||U===void 0||U.scrollLines(T)}paste(T){(0,f.paste)(T,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(T){this._customKeyEventHandler=T}registerLinkProvider(T){return this.linkifier2.registerLinkProvider(T)}registerCharacterJoiner(T){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");const j=this._characterJoinerService.register(T);return this.refresh(0,this.rows-1),j}deregisterCharacterJoiner(T){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");this._characterJoinerService.deregister(T)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(T){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+T)}registerDecoration(T){return this._decorationService.registerDecoration(T)}hasSelection(){return!!this._selectionService&&this._selectionService.hasSelection}select(T,j,$){this._selectionService.setSelection(T,j,$)}getSelection(){return this._selectionService?this._selectionService.selectionText:""}getSelectionPosition(){if(this._selectionService&&this._selectionService.hasSelection)return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){var T;(T=this._selectionService)===null||T===void 0||T.clearSelection()}selectAll(){var T;(T=this._selectionService)===null||T===void 0||T.selectAll()}selectLines(T,j){var $;($=this._selectionService)===null||$===void 0||$.selectLines(T,j)}_keyDown(T){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(T)===!1)return!1;const j=this.browser.isMac&&this.options.macOptionIsMeta&&T.altKey;if(!j&&!this._compositionHelper.keydown(T))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(),!1;j||T.key!=="Dead"&&T.key!=="AltGraph"||(this._unprocessedDeadKey=!0);const $=(0,R.evaluateKeyboardEvent)(T,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(T),$.type===3||$.type===2){const U=this.rows-1;return this.scrollLines($.type===2?-U:U),this.cancel(T,!0)}return $.type===1&&this.selectAll(),!!this._isThirdLevelShift(this.browser,T)||($.cancel&&this.cancel(T,!0),!$.key||!!(T.key&&!T.ctrlKey&&!T.altKey&&!T.metaKey&&T.key.length===1&&T.key.charCodeAt(0)>=65&&T.key.charCodeAt(0)<=90)||(this._unprocessedDeadKey?(this._unprocessedDeadKey=!1,!0):($.key!==V.C0.ETX&&$.key!==V.C0.CR||(this.textarea.value=""),this._onKey.fire({key:$.key,domEvent:T}),this._showCursor(),this.coreService.triggerDataEvent($.key,!0),!this.optionsService.rawOptions.screenReaderMode||T.altKey||T.ctrlKey?this.cancel(T,!0):void(this._keyDownHandled=!0))))}_isThirdLevelShift(T,j){const $=T.isMac&&!this.options.macOptionIsMeta&&j.altKey&&!j.ctrlKey&&!j.metaKey||T.isWindows&&j.altKey&&j.ctrlKey&&!j.metaKey||T.isWindows&&j.getModifierState("AltGraph");return j.type==="keypress"?$:$&&(!j.keyCode||j.keyCode>47)}_keyUp(T){this._keyDownSeen=!1,this._customKeyEventHandler&&this._customKeyEventHandler(T)===!1||(function(j){return j.keyCode===16||j.keyCode===17||j.keyCode===18}(T)||this.focus(),this.updateCursorStyle(T),this._keyPressHandled=!1)}_keyPress(T){let j;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(T)===!1)return!1;if(this.cancel(T),T.charCode)j=T.charCode;else if(T.which===null||T.which===void 0)j=T.keyCode;else{if(T.which===0||T.charCode===0)return!1;j=T.which}return!(!j||(T.altKey||T.ctrlKey||T.metaKey)&&!this._isThirdLevelShift(this.browser,T)||(j=String.fromCharCode(j),this._onKey.fire({key:j,domEvent:T}),this._showCursor(),this.coreService.triggerDataEvent(j,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,0))}_inputEvent(T){if(T.data&&T.inputType==="insertText"&&(!T.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;const j=T.data;return this.coreService.triggerDataEvent(j,!0),this.cancel(T),!0}return!1}resize(T,j){T!==this.cols||j!==this.rows?super.resize(T,j):this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure()}_afterResize(T,j){var $,U;($=this._charSizeService)===null||$===void 0||$.measure(),(U=this.viewport)===null||U===void 0||U.syncScrollArea(!0)}clear(){var T;if(this.buffer.ybase!==0||this.buffer.y!==0){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let j=1;j{Object.defineProperty(n,"__esModule",{value:!0}),n.TimeBasedDebouncer=void 0,n.TimeBasedDebouncer=class{constructor(a,f=1e3){this._renderCallback=a,this._debounceThresholdMS=f,this._lastRefreshMs=0,this._additionalRefreshRequested=!1}dispose(){this._refreshTimeoutID&&clearTimeout(this._refreshTimeoutID)}refresh(a,f,m){this._rowCount=m,a=a!==void 0?a:0,f=f!==void 0?f:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,a):a,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,f):f;const p=Date.now();if(p-this._lastRefreshMs>=this._debounceThresholdMS)this._lastRefreshMs=p,this._innerRefresh();else if(!this._additionalRefreshRequested){const _=p-this._lastRefreshMs,S=this._debounceThresholdMS-_;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=Date.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},S)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;const a=Math.max(this._rowStart,0),f=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(a,f)}}},1680:function(c,n,a){var f=this&&this.__decorate||function(h,l,d,g){var x,C=arguments.length,k=C<3?l:g===null?g=Object.getOwnPropertyDescriptor(l,d):g;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")k=Reflect.decorate(h,l,d,g);else for(var w=h.length-1;w>=0;w--)(x=h[w])&&(k=(C<3?x(k):C>3?x(l,d,k):x(l,d))||k);return C>3&&k&&Object.defineProperty(l,d,k),k},m=this&&this.__param||function(h,l){return function(d,g){l(d,g,h)}};Object.defineProperty(n,"__esModule",{value:!0}),n.Viewport=void 0;const p=a(3656),_=a(4725),S=a(8460),b=a(844),y=a(2585);let u=n.Viewport=class extends b.Disposable{constructor(h,l,d,g,x,C,k,w){super(),this._viewportElement=h,this._scrollArea=l,this._bufferService=d,this._optionsService=g,this._charSizeService=x,this._renderService=C,this._coreBrowserService=k,this.scrollBarWidth=0,this._currentRowHeight=0,this._currentDeviceCellHeight=0,this._lastRecordedBufferLength=0,this._lastRecordedViewportHeight=0,this._lastRecordedBufferHeight=0,this._lastTouchY=0,this._lastScrollTop=0,this._wheelPartialScroll=0,this._refreshAnimationFrame=null,this._ignoreNextScrollEvent=!1,this._smoothScrollState={startTime:0,origin:-1,target:-1},this._onRequestScrollLines=this.register(new S.EventEmitter),this.onRequestScrollLines=this._onRequestScrollLines.event,this.scrollBarWidth=this._viewportElement.offsetWidth-this._scrollArea.offsetWidth||15,this.register((0,p.addDisposableDomListener)(this._viewportElement,"scroll",this._handleScroll.bind(this))),this._activeBuffer=this._bufferService.buffer,this.register(this._bufferService.buffers.onBufferActivate(E=>this._activeBuffer=E.activeBuffer)),this._renderDimensions=this._renderService.dimensions,this.register(this._renderService.onDimensionsChange(E=>this._renderDimensions=E)),this._handleThemeChange(w.colors),this.register(w.onChangeColors(E=>this._handleThemeChange(E))),this.register(this._optionsService.onSpecificOptionChange("scrollback",()=>this.syncScrollArea())),setTimeout(()=>this.syncScrollArea())}_handleThemeChange(h){this._viewportElement.style.backgroundColor=h.background.css}reset(){this._currentRowHeight=0,this._currentDeviceCellHeight=0,this._lastRecordedBufferLength=0,this._lastRecordedViewportHeight=0,this._lastRecordedBufferHeight=0,this._lastTouchY=0,this._lastScrollTop=0,this._coreBrowserService.window.requestAnimationFrame(()=>this.syncScrollArea())}_refresh(h){if(h)return this._innerRefresh(),void(this._refreshAnimationFrame!==null&&this._coreBrowserService.window.cancelAnimationFrame(this._refreshAnimationFrame));this._refreshAnimationFrame===null&&(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._charSizeService.height>0){this._currentRowHeight=this._renderService.dimensions.device.cell.height/this._coreBrowserService.dpr,this._currentDeviceCellHeight=this._renderService.dimensions.device.cell.height,this._lastRecordedViewportHeight=this._viewportElement.offsetHeight;const l=Math.round(this._currentRowHeight*this._lastRecordedBufferLength)+(this._lastRecordedViewportHeight-this._renderService.dimensions.css.canvas.height);this._lastRecordedBufferHeight!==l&&(this._lastRecordedBufferHeight=l,this._scrollArea.style.height=this._lastRecordedBufferHeight+"px")}const h=this._bufferService.buffer.ydisp*this._currentRowHeight;this._viewportElement.scrollTop!==h&&(this._ignoreNextScrollEvent=!0,this._viewportElement.scrollTop=h),this._refreshAnimationFrame=null}syncScrollArea(h=!1){if(this._lastRecordedBufferLength!==this._bufferService.buffer.lines.length)return this._lastRecordedBufferLength=this._bufferService.buffer.lines.length,void this._refresh(h);this._lastRecordedViewportHeight===this._renderService.dimensions.css.canvas.height&&this._lastScrollTop===this._activeBuffer.ydisp*this._currentRowHeight&&this._renderDimensions.device.cell.height===this._currentDeviceCellHeight||this._refresh(h)}_handleScroll(h){if(this._lastScrollTop=this._viewportElement.scrollTop,!this._viewportElement.offsetParent)return;if(this._ignoreNextScrollEvent)return this._ignoreNextScrollEvent=!1,void this._onRequestScrollLines.fire({amount:0,suppressScrollEvent:!0});const l=Math.round(this._lastScrollTop/this._currentRowHeight)-this._bufferService.buffer.ydisp;this._onRequestScrollLines.fire({amount:l,suppressScrollEvent:!0})}_smoothScroll(){if(this._isDisposed||this._smoothScrollState.origin===-1||this._smoothScrollState.target===-1)return;const h=this._smoothScrollPercent();this._viewportElement.scrollTop=this._smoothScrollState.origin+Math.round(h*(this._smoothScrollState.target-this._smoothScrollState.origin)),h<1?this._coreBrowserService.window.requestAnimationFrame(()=>this._smoothScroll()):this._clearSmoothScrollState()}_smoothScrollPercent(){return this._optionsService.rawOptions.smoothScrollDuration&&this._smoothScrollState.startTime?Math.max(Math.min((Date.now()-this._smoothScrollState.startTime)/this._optionsService.rawOptions.smoothScrollDuration,1),0):1}_clearSmoothScrollState(){this._smoothScrollState.startTime=0,this._smoothScrollState.origin=-1,this._smoothScrollState.target=-1}_bubbleScroll(h,l){const d=this._viewportElement.scrollTop+this._lastRecordedViewportHeight;return!(l<0&&this._viewportElement.scrollTop!==0||l>0&&d0&&(g=O),x=""}}return{bufferElements:C,cursorElement:g}}getLinesScrolled(h){if(h.deltaY===0||h.shiftKey)return 0;let l=this._applyScrollModifier(h.deltaY,h);return h.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(l/=this._currentRowHeight+0,this._wheelPartialScroll+=l,l=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):h.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(l*=this._bufferService.rows),l}_applyScrollModifier(h,l){const d=this._optionsService.rawOptions.fastScrollModifier;return d==="alt"&&l.altKey||d==="ctrl"&&l.ctrlKey||d==="shift"&&l.shiftKey?h*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:h*this._optionsService.rawOptions.scrollSensitivity}handleTouchStart(h){this._lastTouchY=h.touches[0].pageY}handleTouchMove(h){const l=this._lastTouchY-h.touches[0].pageY;return this._lastTouchY=h.touches[0].pageY,l!==0&&(this._viewportElement.scrollTop+=l,this._bubbleScroll(h,l))}};n.Viewport=u=f([m(2,y.IBufferService),m(3,y.IOptionsService),m(4,_.ICharSizeService),m(5,_.IRenderService),m(6,_.ICoreBrowserService),m(7,_.IThemeService)],u)},3107:function(c,n,a){var f=this&&this.__decorate||function(u,h,l,d){var g,x=arguments.length,C=x<3?h:d===null?d=Object.getOwnPropertyDescriptor(h,l):d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")C=Reflect.decorate(u,h,l,d);else for(var k=u.length-1;k>=0;k--)(g=u[k])&&(C=(x<3?g(C):x>3?g(h,l,C):g(h,l))||C);return x>3&&C&&Object.defineProperty(h,l,C),C},m=this&&this.__param||function(u,h){return function(l,d){h(l,d,u)}};Object.defineProperty(n,"__esModule",{value:!0}),n.BufferDecorationRenderer=void 0;const p=a(3656),_=a(4725),S=a(844),b=a(2585);let y=n.BufferDecorationRenderer=class extends S.Disposable{constructor(u,h,l,d){super(),this._screenElement=u,this._bufferService=h,this._decorationService=l,this._renderService=d,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement("div"),this._container.classList.add("xterm-decoration-container"),this._screenElement.appendChild(this._container),this.register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this.register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this.register((0,p.addDisposableDomListener)(window,"resize",()=>this._queueRefresh())),this.register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this.register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this.register(this._decorationService.onDecorationRemoved(g=>this._removeDecoration(g))),this.register((0,S.toDisposable)(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(const u of this._decorationService.decorations)this._renderDecoration(u);this._dimensionsChanged=!1}_renderDecoration(u){this._refreshStyle(u),this._dimensionsChanged&&this._refreshXPosition(u)}_createElement(u){var h,l;const d=document.createElement("div");d.classList.add("xterm-decoration"),d.classList.toggle("xterm-decoration-top-layer",((h=u==null?void 0:u.options)===null||h===void 0?void 0:h.layer)==="top"),d.style.width=`${Math.round((u.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,d.style.height=(u.options.height||1)*this._renderService.dimensions.css.cell.height+"px",d.style.top=(u.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height+"px",d.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;const g=(l=u.options.x)!==null&&l!==void 0?l:0;return g&&g>this._bufferService.cols&&(d.style.display="none"),this._refreshXPosition(u,d),d}_refreshStyle(u){const h=u.marker.line-this._bufferService.buffers.active.ydisp;if(h<0||h>=this._bufferService.rows)u.element&&(u.element.style.display="none",u.onRenderEmitter.fire(u.element));else{let l=this._decorationElements.get(u);l||(l=this._createElement(u),u.element=l,this._decorationElements.set(u,l),this._container.appendChild(l),u.onDispose(()=>{this._decorationElements.delete(u),l.remove()})),l.style.top=h*this._renderService.dimensions.css.cell.height+"px",l.style.display=this._altBufferIsActive?"none":"block",u.onRenderEmitter.fire(l)}}_refreshXPosition(u,h=u.element){var l;if(!h)return;const d=(l=u.options.x)!==null&&l!==void 0?l:0;(u.options.anchor||"left")==="right"?h.style.right=d?d*this._renderService.dimensions.css.cell.width+"px":"":h.style.left=d?d*this._renderService.dimensions.css.cell.width+"px":""}_removeDecoration(u){var h;(h=this._decorationElements.get(u))===null||h===void 0||h.remove(),this._decorationElements.delete(u),u.dispose()}};n.BufferDecorationRenderer=y=f([m(1,b.IBufferService),m(2,b.IDecorationService),m(3,_.IRenderService)],y)},5871:(c,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.ColorZoneStore=void 0,n.ColorZoneStore=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(a){if(a.options.overviewRulerOptions){for(const f of this._zones)if(f.color===a.options.overviewRulerOptions.color&&f.position===a.options.overviewRulerOptions.position){if(this._lineIntersectsZone(f,a.marker.line))return;if(this._lineAdjacentToZone(f,a.marker.line,a.options.overviewRulerOptions.position))return void this._addLineToZone(f,a.marker.line)}if(this._zonePoolIndex=a.startBufferLine&&f<=a.endBufferLine}_lineAdjacentToZone(a,f,m){return f>=a.startBufferLine-this._linePadding[m||"full"]&&f<=a.endBufferLine+this._linePadding[m||"full"]}_addLineToZone(a,f){a.startBufferLine=Math.min(a.startBufferLine,f),a.endBufferLine=Math.max(a.endBufferLine,f)}}},5744:function(c,n,a){var f=this&&this.__decorate||function(g,x,C,k){var w,E=arguments.length,L=E<3?x:k===null?k=Object.getOwnPropertyDescriptor(x,C):k;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")L=Reflect.decorate(g,x,C,k);else for(var N=g.length-1;N>=0;N--)(w=g[N])&&(L=(E<3?w(L):E>3?w(x,C,L):w(x,C))||L);return E>3&&L&&Object.defineProperty(x,C,L),L},m=this&&this.__param||function(g,x){return function(C,k){x(C,k,g)}};Object.defineProperty(n,"__esModule",{value:!0}),n.OverviewRulerRenderer=void 0;const p=a(5871),_=a(3656),S=a(4725),b=a(844),y=a(2585),u={full:0,left:0,center:0,right:0},h={full:0,left:0,center:0,right:0},l={full:0,left:0,center:0,right:0};let d=n.OverviewRulerRenderer=class extends b.Disposable{get _width(){return this._optionsService.options.overviewRulerWidth||0}constructor(g,x,C,k,w,E,L){var N;super(),this._viewportElement=g,this._screenElement=x,this._bufferService=C,this._decorationService=k,this._renderService=w,this._optionsService=E,this._coreBrowseService=L,this._colorZoneStore=new p.ColorZoneStore,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=document.createElement("canvas"),this._canvas.classList.add("xterm-decoration-overview-ruler"),this._refreshCanvasDimensions(),(N=this._viewportElement.parentElement)===null||N===void 0||N.insertBefore(this._canvas,this._viewportElement);const O=this._canvas.getContext("2d");if(!O)throw new Error("Ctx cannot be null");this._ctx=O,this._registerDecorationListeners(),this._registerBufferChangeListeners(),this._registerDimensionChangeListeners(),this.register((0,b.toDisposable)(()=>{var P;(P=this._canvas)===null||P===void 0||P.remove()}))}_registerDecorationListeners(){this.register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this.register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0)))}_registerBufferChangeListeners(){this.register(this._renderService.onRenderedViewportChange(()=>this._queueRefresh())),this.register(this._bufferService.buffers.onBufferActivate(()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?"none":"block"})),this.register(this._bufferService.onScroll(()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())}))}_registerDimensionChangeListeners(){this.register(this._renderService.onRender(()=>{this._containerHeight&&this._containerHeight===this._screenElement.clientHeight||(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this.register(this._optionsService.onSpecificOptionChange("overviewRulerWidth",()=>this._queueRefresh(!0))),this.register((0,_.addDisposableDomListener)(this._coreBrowseService.window,"resize",()=>this._queueRefresh(!0))),this._queueRefresh(!0)}_refreshDrawConstants(){const g=Math.floor(this._canvas.width/3),x=Math.ceil(this._canvas.width/3);h.full=this._canvas.width,h.left=g,h.center=x,h.right=g,this._refreshDrawHeightConstants(),l.full=0,l.left=0,l.center=h.left,l.right=h.left+h.center}_refreshDrawHeightConstants(){u.full=Math.round(2*this._coreBrowseService.dpr);const g=this._canvas.height/this._bufferService.buffer.lines.length,x=Math.round(Math.max(Math.min(g,12),6)*this._coreBrowseService.dpr);u.left=x,u.center=x,u.right=x}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*u.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*u.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*u.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*u.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowseService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowseService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(const x of this._decorationService.decorations)this._colorZoneStore.addDecoration(x);this._ctx.lineWidth=1;const g=this._colorZoneStore.zones;for(const x of g)x.position!=="full"&&this._renderColorZone(x);for(const x of g)x.position==="full"&&this._renderColorZone(x);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderColorZone(g){this._ctx.fillStyle=g.color,this._ctx.fillRect(l[g.position||"full"],Math.round((this._canvas.height-1)*(g.startBufferLine/this._bufferService.buffers.active.lines.length)-u[g.position||"full"]/2),h[g.position||"full"],Math.round((this._canvas.height-1)*((g.endBufferLine-g.startBufferLine)/this._bufferService.buffers.active.lines.length)+u[g.position||"full"]))}_queueRefresh(g,x){this._shouldUpdateDimensions=g||this._shouldUpdateDimensions,this._shouldUpdateAnchor=x||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowseService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};n.OverviewRulerRenderer=d=f([m(2,y.IBufferService),m(3,y.IDecorationService),m(4,S.IRenderService),m(5,y.IOptionsService),m(6,S.ICoreBrowserService)],d)},2950:function(c,n,a){var f=this&&this.__decorate||function(y,u,h,l){var d,g=arguments.length,x=g<3?u:l===null?l=Object.getOwnPropertyDescriptor(u,h):l;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")x=Reflect.decorate(y,u,h,l);else for(var C=y.length-1;C>=0;C--)(d=y[C])&&(x=(g<3?d(x):g>3?d(u,h,x):d(u,h))||x);return g>3&&x&&Object.defineProperty(u,h,x),x},m=this&&this.__param||function(y,u){return function(h,l){u(h,l,y)}};Object.defineProperty(n,"__esModule",{value:!0}),n.CompositionHelper=void 0;const p=a(4725),_=a(2585),S=a(2584);let b=n.CompositionHelper=class{get isComposing(){return this._isComposing}constructor(y,u,h,l,d,g){this._textarea=y,this._compositionView=u,this._bufferService=h,this._optionsService=l,this._coreService=d,this._renderService=g,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=""}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent="",this._dataAlreadySent="",this._compositionView.classList.add("active")}compositionupdate(y){this._compositionView.textContent=y.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(y){if(this._isComposing||this._isSendingComposition){if(y.keyCode===229||y.keyCode===16||y.keyCode===17||y.keyCode===18)return!1;this._finalizeComposition(!1)}return y.keyCode!==229||(this._handleAnyTextareaChanges(),!1)}_finalizeComposition(y){if(this._compositionView.classList.remove("active"),this._isComposing=!1,y){const u={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){let h;this._isSendingComposition=!1,u.start+=this._dataAlreadySent.length,h=this._isComposing?this._textarea.value.substring(u.start,u.end):this._textarea.value.substring(u.start),h.length>0&&this._coreService.triggerDataEvent(h,!0)}},0)}else{this._isSendingComposition=!1;const u=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(u,!0)}}_handleAnyTextareaChanges(){const y=this._textarea.value;setTimeout(()=>{if(!this._isComposing){const u=this._textarea.value,h=u.replace(y,"");this._dataAlreadySent=h,u.length>y.length?this._coreService.triggerDataEvent(h,!0):u.lengththis.updateCompositionElements(!0),0)}}};n.CompositionHelper=b=f([m(2,_.IBufferService),m(3,_.IOptionsService),m(4,_.ICoreService),m(5,p.IRenderService)],b)},9806:(c,n)=>{function a(f,m,p){const _=p.getBoundingClientRect(),S=f.getComputedStyle(p),b=parseInt(S.getPropertyValue("padding-left")),y=parseInt(S.getPropertyValue("padding-top"));return[m.clientX-_.left-b,m.clientY-_.top-y]}Object.defineProperty(n,"__esModule",{value:!0}),n.getCoords=n.getCoordsRelativeToElement=void 0,n.getCoordsRelativeToElement=a,n.getCoords=function(f,m,p,_,S,b,y,u,h){if(!b)return;const l=a(f,m,p);return l?(l[0]=Math.ceil((l[0]+(h?y/2:0))/y),l[1]=Math.ceil(l[1]/u),l[0]=Math.min(Math.max(l[0],1),_+(h?1:0)),l[1]=Math.min(Math.max(l[1],1),S),l):void 0}},9504:(c,n,a)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.moveToCellSequence=void 0;const f=a(2584);function m(u,h,l,d){const g=u-p(u,l),x=h-p(h,l),C=Math.abs(g-x)-function(k,w,E){let L=0;const N=k-p(k,E),O=w-p(w,E);for(let P=0;P=0&&uh?"A":"B"}function S(u,h,l,d,g,x){let C=u,k=h,w="";for(;C!==l||k!==d;)C+=g?1:-1,g&&C>x.cols-1?(w+=x.buffer.translateBufferLineToString(k,!1,u,C),C=0,u=0,k++):!g&&C<0&&(w+=x.buffer.translateBufferLineToString(k,!1,0,u+1),C=x.cols-1,u=C,k--);return w+x.buffer.translateBufferLineToString(k,!1,u,C)}function b(u,h){const l=h?"O":"[";return f.C0.ESC+l+u}function y(u,h){u=Math.floor(u);let l="";for(let d=0;d0?N-p(N,O):E;const z=N,W=function(V,R,D,A,B,H){let q;return q=m(D,A,B,H).length>0?A-p(A,B):R,V=D&&qu?"D":"C",y(Math.abs(g-u),b(C,d));C=x>h?"D":"C";const k=Math.abs(x-h);return y(function(w,E){return E.cols-w}(x>h?u:g,l)+(k-1)*l.cols+1+((x>h?g:u)-1),b(C,d))}},1296:function(c,n,a){var f=this&&this.__decorate||function(O,P,F,z){var W,V=arguments.length,R=V<3?P:z===null?z=Object.getOwnPropertyDescriptor(P,F):z;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")R=Reflect.decorate(O,P,F,z);else for(var D=O.length-1;D>=0;D--)(W=O[D])&&(R=(V<3?W(R):V>3?W(P,F,R):W(P,F))||R);return V>3&&R&&Object.defineProperty(P,F,R),R},m=this&&this.__param||function(O,P){return function(F,z){P(F,z,O)}};Object.defineProperty(n,"__esModule",{value:!0}),n.DomRenderer=void 0;const p=a(3787),_=a(2550),S=a(2223),b=a(6171),y=a(4725),u=a(8055),h=a(8460),l=a(844),d=a(2585),g="xterm-dom-renderer-owner-",x="xterm-rows",C="xterm-fg-",k="xterm-bg-",w="xterm-focus",E="xterm-selection";let L=1,N=n.DomRenderer=class extends l.Disposable{constructor(O,P,F,z,W,V,R,D,A,B){super(),this._element=O,this._screenElement=P,this._viewportElement=F,this._linkifier2=z,this._charSizeService=V,this._optionsService=R,this._bufferService=D,this._coreBrowserService=A,this._themeService=B,this._terminalClass=L++,this._rowElements=[],this.onRequestRedraw=this.register(new h.EventEmitter).event,this._rowContainer=document.createElement("div"),this._rowContainer.classList.add(x),this._rowContainer.style.lineHeight="normal",this._rowContainer.setAttribute("aria-hidden","true"),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=document.createElement("div"),this._selectionContainer.classList.add(E),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=(0,b.createRenderDimensions)(),this._updateDimensions(),this.register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this.register(this._themeService.onChangeColors(H=>this._injectCss(H))),this._injectCss(this._themeService.colors),this._rowFactory=W.createInstance(p.DomRendererRowFactory,document),this._element.classList.add(g+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this.register(this._linkifier2.onShowLinkUnderline(H=>this._handleLinkHover(H))),this.register(this._linkifier2.onHideLinkUnderline(H=>this._handleLinkLeave(H))),this.register((0,l.toDisposable)(()=>{this._element.classList.remove(g+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new _.WidthCache(document),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){const O=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*O,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*O),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/O),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/O),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(const F of this._rowElements)F.style.width=`${this.dimensions.css.canvas.width}px`,F.style.height=`${this.dimensions.css.cell.height}px`,F.style.lineHeight=`${this.dimensions.css.cell.height}px`,F.style.overflow="hidden";this._dimensionsStyleElement||(this._dimensionsStyleElement=document.createElement("style"),this._screenElement.appendChild(this._dimensionsStyleElement));const P=`${this._terminalSelector} .${x} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=P,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(O){this._themeStyleElement||(this._themeStyleElement=document.createElement("style"),this._screenElement.appendChild(this._themeStyleElement));let P=`${this._terminalSelector} .${x} { color: ${O.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;P+=`${this._terminalSelector} .${x} .xterm-dim { color: ${u.color.multiplyOpacity(O.foreground,.5).css};}`,P+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`,P+="@keyframes blink_box_shadow_"+this._terminalClass+" { 50% { border-bottom-style: hidden; }}",P+="@keyframes blink_block_"+this._terminalClass+` { 0% { background-color: ${O.cursor.css}; color: ${O.cursorAccent.css}; } 50% { background-color: inherit; color: ${O.cursor.css}; }}`,P+=`${this._terminalSelector} .${x}.${w} .xterm-cursor.xterm-cursor-blink:not(.xterm-cursor-block) { animation: blink_box_shadow_`+this._terminalClass+` 1s step-end infinite;}${this._terminalSelector} .${x}.${w} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: blink_block_`+this._terminalClass+` 1s step-end infinite;}${this._terminalSelector} .${x} .xterm-cursor.xterm-cursor-block { background-color: ${O.cursor.css}; color: ${O.cursorAccent.css};}${this._terminalSelector} .${x} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${O.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${x} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${O.cursor.css} inset;}${this._terminalSelector} .${x} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${O.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,P+=`${this._terminalSelector} .${E} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${E} div { position: absolute; background-color: ${O.selectionBackgroundOpaque.css};}${this._terminalSelector} .${E} div { position: absolute; background-color: ${O.selectionInactiveBackgroundOpaque.css};}`;for(const[F,z]of O.ansi.entries())P+=`${this._terminalSelector} .${C}${F} { color: ${z.css}; }${this._terminalSelector} .${C}${F}.xterm-dim { color: ${u.color.multiplyOpacity(z,.5).css}; }${this._terminalSelector} .${k}${F} { background-color: ${z.css}; }`;P+=`${this._terminalSelector} .${C}${S.INVERTED_DEFAULT_COLOR} { color: ${u.color.opaque(O.background).css}; }${this._terminalSelector} .${C}${S.INVERTED_DEFAULT_COLOR}.xterm-dim { color: ${u.color.multiplyOpacity(u.color.opaque(O.background),.5).css}; }${this._terminalSelector} .${k}${S.INVERTED_DEFAULT_COLOR} { background-color: ${O.foreground.css}; }`,this._themeStyleElement.textContent=P}_setDefaultSpacing(){const O=this.dimensions.css.cell.width-this._widthCache.get("W",!1,!1);this._rowContainer.style.letterSpacing=`${O}px`,this._rowFactory.defaultSpacing=O}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(O,P){for(let F=this._rowElements.length;F<=P;F++){const z=document.createElement("div");this._rowContainer.appendChild(z),this._rowElements.push(z)}for(;this._rowElements.length>P;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(O,P){this._refreshRowElements(O,P),this._updateDimensions()}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(w)}handleFocus(){this._rowContainer.classList.add(w),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(O,P,F){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(O,P,F),this.renderRows(0,this._bufferService.rows-1),!O||!P)return;const z=O[1]-this._bufferService.buffer.ydisp,W=P[1]-this._bufferService.buffer.ydisp,V=Math.max(z,0),R=Math.min(W,this._bufferService.rows-1);if(V>=this._bufferService.rows||R<0)return;const D=document.createDocumentFragment();if(F){const A=O[0]>P[0];D.appendChild(this._createSelectionElement(V,A?P[0]:O[0],A?O[0]:P[0],R-V+1))}else{const A=z===V?O[0]:0,B=V===W?P[0]:this._bufferService.cols;D.appendChild(this._createSelectionElement(V,A,B));const H=R-V-1;if(D.appendChild(this._createSelectionElement(V+1,0,this._bufferService.cols,H)),V!==R){const q=W===R?P[0]:this._bufferService.cols;D.appendChild(this._createSelectionElement(R,0,q))}}this._selectionContainer.appendChild(D)}_createSelectionElement(O,P,F,z=1){const W=document.createElement("div");return W.style.height=z*this.dimensions.css.cell.height+"px",W.style.top=O*this.dimensions.css.cell.height+"px",W.style.left=P*this.dimensions.css.cell.width+"px",W.style.width=this.dimensions.css.cell.width*(F-P)+"px",W}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(const O of this._rowElements)O.replaceChildren()}renderRows(O,P){const F=this._bufferService.buffer,z=F.ybase+F.y,W=Math.min(F.x,this._bufferService.cols-1),V=this._optionsService.rawOptions.cursorBlink,R=this._optionsService.rawOptions.cursorStyle,D=this._optionsService.rawOptions.cursorInactiveStyle;for(let A=O;A<=P;A++){const B=A+F.ydisp,H=this._rowElements[A],q=F.lines.get(B);if(!H||!q)break;H.replaceChildren(...this._rowFactory.createRow(q,B,B===z,R,D,W,V,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${g}${this._terminalClass}`}_handleLinkHover(O){this._setCellUnderline(O.x1,O.x2,O.y1,O.y2,O.cols,!0)}_handleLinkLeave(O){this._setCellUnderline(O.x1,O.x2,O.y1,O.y2,O.cols,!1)}_setCellUnderline(O,P,F,z,W,V){F<0&&(O=0),z<0&&(P=0);const R=this._bufferService.rows-1;F=Math.max(Math.min(F,R),0),z=Math.max(Math.min(z,R),0),W=Math.min(W,this._bufferService.cols);const D=this._bufferService.buffer,A=D.ybase+D.y,B=Math.min(D.x,W-1),H=this._optionsService.rawOptions.cursorBlink,q=this._optionsService.rawOptions.cursorStyle,G=this._optionsService.rawOptions.cursorInactiveStyle;for(let X=F;X<=z;++X){const te=X+D.ydisp,T=this._rowElements[X],j=D.lines.get(te);if(!T||!j)break;T.replaceChildren(...this._rowFactory.createRow(j,te,te===A,q,G,B,H,this.dimensions.css.cell.width,this._widthCache,V?X===F?O:0:-1,V?(X===z?P:W)-1:-1))}}};n.DomRenderer=N=f([m(4,d.IInstantiationService),m(5,y.ICharSizeService),m(6,d.IOptionsService),m(7,d.IBufferService),m(8,y.ICoreBrowserService),m(9,y.IThemeService)],N)},3787:function(c,n,a){var f=this&&this.__decorate||function(C,k,w,E){var L,N=arguments.length,O=N<3?k:E===null?E=Object.getOwnPropertyDescriptor(k,w):E;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")O=Reflect.decorate(C,k,w,E);else for(var P=C.length-1;P>=0;P--)(L=C[P])&&(O=(N<3?L(O):N>3?L(k,w,O):L(k,w))||O);return N>3&&O&&Object.defineProperty(k,w,O),O},m=this&&this.__param||function(C,k){return function(w,E){k(w,E,C)}};Object.defineProperty(n,"__esModule",{value:!0}),n.DomRendererRowFactory=void 0;const p=a(2223),_=a(643),S=a(511),b=a(2585),y=a(8055),u=a(4725),h=a(4269),l=a(6171),d=a(3734);let g=n.DomRendererRowFactory=class{constructor(C,k,w,E,L,N,O){this._document=C,this._characterJoinerService=k,this._optionsService=w,this._coreBrowserService=E,this._coreService=L,this._decorationService=N,this._themeService=O,this._workCell=new S.CellData,this._columnSelectMode=!1,this.defaultSpacing=0}handleSelectionChanged(C,k,w){this._selectionStart=C,this._selectionEnd=k,this._columnSelectMode=w}createRow(C,k,w,E,L,N,O,P,F,z,W){const V=[],R=this._characterJoinerService.getJoinedCharacters(k),D=this._themeService.colors;let A,B=C.getNoBgTrimmedLength();w&&B0&&oe===R[0][0]){Ne=!0;const me=R.shift();Y=new h.JoinedCellData(this._workCell,C.translateToString(!0,me[0],me[1]),me[1]-me[0]),Rr=me[1]-1,ce=Y.getWidth()}const he=this._isCellInSelection(oe,k),fe=w&&oe===N,pe=J&&oe>=z&&oe<=W;let tt=!1;this._decorationService.forEachDecorationAtCell(oe,k,void 0,me=>{tt=!0});let Pe=Y.getChars()||_.WHITESPACE_CELL_CHAR;if(Pe===" "&&(Y.isUnderline()||Y.isOverline())&&(Pe=" "),U=ce*P-F.get(Pe,Y.isBold(),Y.isItalic()),A){if(H&&(he&&$||!he&&!$&&Y.bg===G)&&(he&&$&&D.selectionForeground||Y.fg===X)&&Y.extended.ext===te&&pe===T&&U===j&&!fe&&!Ne&&!tt){q+=Pe,H++;continue}H&&(A.textContent=q),A=this._document.createElement("span"),H=0,q=""}else A=this._document.createElement("span");if(G=Y.bg,X=Y.fg,te=Y.extended.ext,T=pe,j=U,$=he,Ne&&N>=oe&&N<=Rr&&(N=oe),!this._coreService.isCursorHidden&&fe){if(ee.push("xterm-cursor"),this._coreBrowserService.isFocused)O&&ee.push("xterm-cursor-blink"),ee.push(E==="bar"?"xterm-cursor-bar":E==="underline"?"xterm-cursor-underline":"xterm-cursor-block");else if(L)switch(L){case"outline":ee.push("xterm-cursor-outline");break;case"block":ee.push("xterm-cursor-block");break;case"bar":ee.push("xterm-cursor-bar");break;case"underline":ee.push("xterm-cursor-underline")}}if(Y.isBold()&&ee.push("xterm-bold"),Y.isItalic()&&ee.push("xterm-italic"),Y.isDim()&&ee.push("xterm-dim"),q=Y.isInvisible()?_.WHITESPACE_CELL_CHAR:Y.getChars()||_.WHITESPACE_CELL_CHAR,Y.isUnderline()&&(ee.push(`xterm-underline-${Y.extended.underlineStyle}`),q===" "&&(q=" "),!Y.isUnderlineColorDefault()))if(Y.isUnderlineColorRGB())A.style.textDecorationColor=`rgb(${d.AttributeData.toColorRGB(Y.getUnderlineColor()).join(",")})`;else{let me=Y.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&Y.isBold()&&me<8&&(me+=8),A.style.textDecorationColor=D.ansi[me].css}Y.isOverline()&&(ee.push("xterm-overline"),q===" "&&(q=" ")),Y.isStrikethrough()&&ee.push("xterm-strikethrough"),pe&&(A.style.textDecoration="underline");let le=Y.getFgColor(),Be=Y.getFgColorMode(),He=Y.getBgColor(),wt=Y.getBgColorMode();const qr=!!Y.isInverse();if(qr){const me=le;le=He,He=me;const Ls=Be;Be=wt,wt=Ls}let Ct,Ue,De,$t=!1;switch(this._decorationService.forEachDecorationAtCell(oe,k,void 0,me=>{me.options.layer!=="top"&&$t||(me.backgroundColorRGB&&(wt=50331648,He=me.backgroundColorRGB.rgba>>8&16777215,Ct=me.backgroundColorRGB),me.foregroundColorRGB&&(Be=50331648,le=me.foregroundColorRGB.rgba>>8&16777215,Ue=me.foregroundColorRGB),$t=me.options.layer==="top")}),!$t&&he&&(Ct=this._coreBrowserService.isFocused?D.selectionBackgroundOpaque:D.selectionInactiveBackgroundOpaque,He=Ct.rgba>>8&16777215,wt=50331648,$t=!0,D.selectionForeground&&(Be=50331648,le=D.selectionForeground.rgba>>8&16777215,Ue=D.selectionForeground)),$t&&ee.push("xterm-decoration-top"),wt){case 16777216:case 33554432:De=D.ansi[He],ee.push(`xterm-bg-${He}`);break;case 50331648:De=y.rgba.toColor(He>>16,He>>8&255,255&He),this._addStyle(A,`background-color:#${x((He>>>0).toString(16),"0",6)}`);break;default:qr?(De=D.foreground,ee.push(`xterm-bg-${p.INVERTED_DEFAULT_COLOR}`)):De=D.background}switch(Ct||Y.isDim()&&(Ct=y.color.multiplyOpacity(De,.5)),Be){case 16777216:case 33554432:Y.isBold()&&le<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(le+=8),this._applyMinimumContrast(A,De,D.ansi[le],Y,Ct,void 0)||ee.push(`xterm-fg-${le}`);break;case 50331648:const me=y.rgba.toColor(le>>16&255,le>>8&255,255&le);this._applyMinimumContrast(A,De,me,Y,Ct,Ue)||this._addStyle(A,`color:#${x(le.toString(16),"0",6)}`);break;default:this._applyMinimumContrast(A,De,D.foreground,Y,Ct,void 0)||qr&&ee.push(`xterm-fg-${p.INVERTED_DEFAULT_COLOR}`)}ee.length&&(A.className=ee.join(" "),ee.length=0),fe||Ne||tt?A.textContent=q:H++,U!==this.defaultSpacing&&(A.style.letterSpacing=`${U}px`),V.push(A),oe=Rr}return A&&H&&(A.textContent=q),V}_applyMinimumContrast(C,k,w,E,L,N){if(this._optionsService.rawOptions.minimumContrastRatio===1||(0,l.excludeFromContrastRatioDemands)(E.getCode()))return!1;const O=this._getContrastCache(E);let P;if(L||N||(P=O.getColor(k.rgba,w.rgba)),P===void 0){const F=this._optionsService.rawOptions.minimumContrastRatio/(E.isDim()?2:1);P=y.color.ensureContrastRatio(L||k,N||w,F),O.setColor((L||k).rgba,(N||w).rgba,P??null)}return!!P&&(this._addStyle(C,`color:${P.css}`),!0)}_getContrastCache(C){return C.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(C,k){C.setAttribute("style",`${C.getAttribute("style")||""}${k};`)}_isCellInSelection(C,k){const w=this._selectionStart,E=this._selectionEnd;return!(!w||!E)&&(this._columnSelectMode?w[0]<=E[0]?C>=w[0]&&k>=w[1]&&C=w[1]&&C>=E[0]&&k<=E[1]:k>w[1]&&k=w[0]&&C=w[0])}};function x(C,k,w){for(;C.length{Object.defineProperty(n,"__esModule",{value:!0}),n.WidthCache=void 0,n.WidthCache=class{constructor(a){this._flat=new Float32Array(256),this._font="",this._fontSize=0,this._weight="normal",this._weightBold="bold",this._measureElements=[],this._container=a.createElement("div"),this._container.style.position="absolute",this._container.style.top="-50000px",this._container.style.width="50000px",this._container.style.whiteSpace="pre",this._container.style.fontKerning="none";const f=a.createElement("span"),m=a.createElement("span");m.style.fontWeight="bold";const p=a.createElement("span");p.style.fontStyle="italic";const _=a.createElement("span");_.style.fontWeight="bold",_.style.fontStyle="italic",this._measureElements=[f,m,p,_],this._container.appendChild(f),this._container.appendChild(m),this._container.appendChild(p),this._container.appendChild(_),a.body.appendChild(this._container),this.clear()}dispose(){this._container.remove(),this._measureElements.length=0,this._holey=void 0}clear(){this._flat.fill(-9999),this._holey=new Map}setFont(a,f,m,p){a===this._font&&f===this._fontSize&&m===this._weight&&p===this._weightBold||(this._font=a,this._fontSize=f,this._weight=m,this._weightBold=p,this._container.style.fontFamily=this._font,this._container.style.fontSize=`${this._fontSize}px`,this._measureElements[0].style.fontWeight=`${m}`,this._measureElements[1].style.fontWeight=`${p}`,this._measureElements[2].style.fontWeight=`${m}`,this._measureElements[3].style.fontWeight=`${p}`,this.clear())}get(a,f,m){let p=0;if(!f&&!m&&a.length===1&&(p=a.charCodeAt(0))<256)return this._flat[p]!==-9999?this._flat[p]:this._flat[p]=this._measure(a,0);let _=a;f&&(_+="B"),m&&(_+="I");let S=this._holey.get(_);if(S===void 0){let b=0;f&&(b|=1),m&&(b|=2),S=this._measure(a,b),this._holey.set(_,S)}return S}_measure(a,f){const m=this._measureElements[f];return m.textContent=a.repeat(32),m.offsetWidth/32}}},2223:(c,n,a)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.TEXT_BASELINE=n.DIM_OPACITY=n.INVERTED_DEFAULT_COLOR=void 0;const f=a(6114);n.INVERTED_DEFAULT_COLOR=257,n.DIM_OPACITY=.5,n.TEXT_BASELINE=f.isFirefox||f.isLegacyEdge?"bottom":"ideographic"},6171:(c,n)=>{function a(f){return 57508<=f&&f<=57558}Object.defineProperty(n,"__esModule",{value:!0}),n.createRenderDimensions=n.excludeFromContrastRatioDemands=n.isRestrictedPowerlineGlyph=n.isPowerlineGlyph=n.throwIfFalsy=void 0,n.throwIfFalsy=function(f){if(!f)throw new Error("value must not be falsy");return f},n.isPowerlineGlyph=a,n.isRestrictedPowerlineGlyph=function(f){return 57520<=f&&f<=57527},n.excludeFromContrastRatioDemands=function(f){return a(f)||function(m){return 9472<=m&&m<=9631}(f)},n.createRenderDimensions=function(){return{css:{canvas:{width:0,height:0},cell:{width:0,height:0}},device:{canvas:{width:0,height:0},cell:{width:0,height:0},char:{width:0,height:0,left:0,top:0}}}}},456:(c,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.SelectionModel=void 0,n.SelectionModel=class{constructor(a){this._bufferService=a,this.isSelectAllActive=!1,this.selectionStartLength=0}clearSelection(){this.selectionStart=void 0,this.selectionEnd=void 0,this.isSelectAllActive=!1,this.selectionStartLength=0}get finalSelectionStart(){return this.isSelectAllActive?[0,0]:this.selectionEnd&&this.selectionStart&&this.areSelectionValuesReversed()?this.selectionEnd:this.selectionStart}get finalSelectionEnd(){if(this.isSelectAllActive)return[this._bufferService.cols,this._bufferService.buffer.ybase+this._bufferService.rows-1];if(this.selectionStart){if(!this.selectionEnd||this.areSelectionValuesReversed()){const a=this.selectionStart[0]+this.selectionStartLength;return a>this._bufferService.cols?a%this._bufferService.cols==0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(a/this._bufferService.cols)-1]:[a%this._bufferService.cols,this.selectionStart[1]+Math.floor(a/this._bufferService.cols)]:[a,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){const a=this.selectionStart[0]+this.selectionStartLength;return a>this._bufferService.cols?[a%this._bufferService.cols,this.selectionStart[1]+Math.floor(a/this._bufferService.cols)]:[Math.max(a,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){const a=this.selectionStart,f=this.selectionEnd;return!(!a||!f)&&(a[1]>f[1]||a[1]===f[1]&&a[0]>f[0])}handleTrim(a){return this.selectionStart&&(this.selectionStart[1]-=a),this.selectionEnd&&(this.selectionEnd[1]-=a),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}}},428:function(c,n,a){var f=this&&this.__decorate||function(u,h,l,d){var g,x=arguments.length,C=x<3?h:d===null?d=Object.getOwnPropertyDescriptor(h,l):d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")C=Reflect.decorate(u,h,l,d);else for(var k=u.length-1;k>=0;k--)(g=u[k])&&(C=(x<3?g(C):x>3?g(h,l,C):g(h,l))||C);return x>3&&C&&Object.defineProperty(h,l,C),C},m=this&&this.__param||function(u,h){return function(l,d){h(l,d,u)}};Object.defineProperty(n,"__esModule",{value:!0}),n.CharSizeService=void 0;const p=a(2585),_=a(8460),S=a(844);let b=n.CharSizeService=class extends S.Disposable{get hasValidSize(){return this.width>0&&this.height>0}constructor(u,h,l){super(),this._optionsService=l,this.width=0,this.height=0,this._onCharSizeChange=this.register(new _.EventEmitter),this.onCharSizeChange=this._onCharSizeChange.event,this._measureStrategy=new y(u,h,this._optionsService),this.register(this._optionsService.onMultipleOptionChange(["fontFamily","fontSize"],()=>this.measure()))}measure(){const u=this._measureStrategy.measure();u.width===this.width&&u.height===this.height||(this.width=u.width,this.height=u.height,this._onCharSizeChange.fire())}};n.CharSizeService=b=f([m(2,p.IOptionsService)],b);class y{constructor(h,l,d){this._document=h,this._parentElement=l,this._optionsService=d,this._result={width:0,height:0},this._measureElement=this._document.createElement("span"),this._measureElement.classList.add("xterm-char-measure-element"),this._measureElement.textContent="W".repeat(32),this._measureElement.setAttribute("aria-hidden","true"),this._measureElement.style.whiteSpace="pre",this._measureElement.style.fontKerning="none",this._parentElement.appendChild(this._measureElement)}measure(){this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`;const h={height:Number(this._measureElement.offsetHeight),width:Number(this._measureElement.offsetWidth)};return h.width!==0&&h.height!==0&&(this._result.width=h.width/32,this._result.height=Math.ceil(h.height)),this._result}}},4269:function(c,n,a){var f=this&&this.__decorate||function(h,l,d,g){var x,C=arguments.length,k=C<3?l:g===null?g=Object.getOwnPropertyDescriptor(l,d):g;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")k=Reflect.decorate(h,l,d,g);else for(var w=h.length-1;w>=0;w--)(x=h[w])&&(k=(C<3?x(k):C>3?x(l,d,k):x(l,d))||k);return C>3&&k&&Object.defineProperty(l,d,k),k},m=this&&this.__param||function(h,l){return function(d,g){l(d,g,h)}};Object.defineProperty(n,"__esModule",{value:!0}),n.CharacterJoinerService=n.JoinedCellData=void 0;const p=a(3734),_=a(643),S=a(511),b=a(2585);class y extends p.AttributeData{constructor(l,d,g){super(),this.content=0,this.combinedData="",this.fg=l.fg,this.bg=l.bg,this.combinedData=d,this._width=g}isCombined(){return 2097152}getWidth(){return this._width}getChars(){return this.combinedData}getCode(){return 2097151}setFromCharData(l){throw new Error("not implemented")}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}n.JoinedCellData=y;let u=n.CharacterJoinerService=class Op{constructor(l){this._bufferService=l,this._characterJoiners=[],this._nextCharacterJoinerId=0,this._workCell=new S.CellData}register(l){const d={id:this._nextCharacterJoinerId++,handler:l};return this._characterJoiners.push(d),d.id}deregister(l){for(let d=0;d1){const O=this._getJoinedRanges(x,w,k,d,C);for(let P=0;P1){const N=this._getJoinedRanges(x,w,k,d,C);for(let O=0;O{Object.defineProperty(n,"__esModule",{value:!0}),n.CoreBrowserService=void 0,n.CoreBrowserService=class{constructor(a,f){this._textarea=a,this.window=f,this._isFocused=!1,this._cachedIsFocused=void 0,this._textarea.addEventListener("focus",()=>this._isFocused=!0),this._textarea.addEventListener("blur",()=>this._isFocused=!1)}get dpr(){return this.window.devicePixelRatio}get isFocused(){return this._cachedIsFocused===void 0&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask(()=>this._cachedIsFocused=void 0)),this._cachedIsFocused}}},8934:function(c,n,a){var f=this&&this.__decorate||function(b,y,u,h){var l,d=arguments.length,g=d<3?y:h===null?h=Object.getOwnPropertyDescriptor(y,u):h;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")g=Reflect.decorate(b,y,u,h);else for(var x=b.length-1;x>=0;x--)(l=b[x])&&(g=(d<3?l(g):d>3?l(y,u,g):l(y,u))||g);return d>3&&g&&Object.defineProperty(y,u,g),g},m=this&&this.__param||function(b,y){return function(u,h){y(u,h,b)}};Object.defineProperty(n,"__esModule",{value:!0}),n.MouseService=void 0;const p=a(4725),_=a(9806);let S=n.MouseService=class{constructor(b,y){this._renderService=b,this._charSizeService=y}getCoords(b,y,u,h,l){return(0,_.getCoords)(window,b,y,u,h,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,l)}getMouseReportCoords(b,y){const u=(0,_.getCoordsRelativeToElement)(window,b,y);if(this._charSizeService.hasValidSize)return u[0]=Math.min(Math.max(u[0],0),this._renderService.dimensions.css.canvas.width-1),u[1]=Math.min(Math.max(u[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(u[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(u[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(u[0]),y:Math.floor(u[1])}}};n.MouseService=S=f([m(0,p.IRenderService),m(1,p.ICharSizeService)],S)},3230:function(c,n,a){var f=this&&this.__decorate||function(g,x,C,k){var w,E=arguments.length,L=E<3?x:k===null?k=Object.getOwnPropertyDescriptor(x,C):k;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")L=Reflect.decorate(g,x,C,k);else for(var N=g.length-1;N>=0;N--)(w=g[N])&&(L=(E<3?w(L):E>3?w(x,C,L):w(x,C))||L);return E>3&&L&&Object.defineProperty(x,C,L),L},m=this&&this.__param||function(g,x){return function(C,k){x(C,k,g)}};Object.defineProperty(n,"__esModule",{value:!0}),n.RenderService=void 0;const p=a(3656),_=a(6193),S=a(5596),b=a(4725),y=a(8460),u=a(844),h=a(7226),l=a(2585);let d=n.RenderService=class extends u.Disposable{get dimensions(){return this._renderer.value.dimensions}constructor(g,x,C,k,w,E,L,N){if(super(),this._rowCount=g,this._charSizeService=k,this._renderer=this.register(new u.MutableDisposable),this._pausedResizeTask=new h.DebouncedIdleTask,this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this.register(new y.EventEmitter),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this.register(new y.EventEmitter),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this.register(new y.EventEmitter),this.onRender=this._onRender.event,this._onRefreshRequest=this.register(new y.EventEmitter),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new _.RenderDebouncer(L.window,(O,P)=>this._renderRows(O,P)),this.register(this._renderDebouncer),this._screenDprMonitor=new S.ScreenDprMonitor(L.window),this._screenDprMonitor.setListener(()=>this.handleDevicePixelRatioChange()),this.register(this._screenDprMonitor),this.register(E.onResize(()=>this._fullRefresh())),this.register(E.buffers.onBufferActivate(()=>{var O;return(O=this._renderer.value)===null||O===void 0?void 0:O.clear()})),this.register(C.onOptionChange(()=>this._handleOptionsChanged())),this.register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this.register(w.onDecorationRegistered(()=>this._fullRefresh())),this.register(w.onDecorationRemoved(()=>this._fullRefresh())),this.register(C.onMultipleOptionChange(["customGlyphs","drawBoldTextInBrightColors","letterSpacing","lineHeight","fontFamily","fontSize","fontWeight","fontWeightBold","minimumContrastRatio"],()=>{this.clear(),this.handleResize(E.cols,E.rows),this._fullRefresh()})),this.register(C.onMultipleOptionChange(["cursorBlink","cursorStyle"],()=>this.refreshRows(E.buffer.y,E.buffer.y,!0))),this.register((0,p.addDisposableDomListener)(L.window,"resize",()=>this.handleDevicePixelRatioChange())),this.register(N.onChangeColors(()=>this._fullRefresh())),"IntersectionObserver"in L.window){const O=new L.window.IntersectionObserver(P=>this._handleIntersectionChange(P[P.length-1]),{threshold:0});O.observe(x),this.register({dispose:()=>O.disconnect()})}}_handleIntersectionChange(g){this._isPaused=g.isIntersecting===void 0?g.intersectionRatio===0:!g.isIntersecting,this._isPaused||this._charSizeService.hasValidSize||this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(g,x,C=!1){this._isPaused?this._needsFullRefresh=!0:(C||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(g,x,this._rowCount))}_renderRows(g,x){this._renderer.value&&(g=Math.min(g,this._rowCount-1),x=Math.min(x,this._rowCount-1),this._renderer.value.renderRows(g,x),this._needsSelectionRefresh&&(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),this._needsSelectionRefresh=!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:g,end:x}),this._onRender.fire({start:g,end:x}),this._isNextRenderRedrawOnly=!0)}resize(g,x){this._rowCount=x,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(g){this._renderer.value=g,this._renderer.value.onRequestRedraw(x=>this.refreshRows(x.start,x.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh()}addRefreshCallback(g){return this._renderDebouncer.addRefreshCallback(g)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){var g,x;this._renderer.value&&((x=(g=this._renderer.value).clearTextureAtlas)===null||x===void 0||x.call(g),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(g,x){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>this._renderer.value.handleResize(g,x)):this._renderer.value.handleResize(g,x),this._fullRefresh())}handleCharSizeChanged(){var g;(g=this._renderer.value)===null||g===void 0||g.handleCharSizeChanged()}handleBlur(){var g;(g=this._renderer.value)===null||g===void 0||g.handleBlur()}handleFocus(){var g;(g=this._renderer.value)===null||g===void 0||g.handleFocus()}handleSelectionChanged(g,x,C){var k;this._selectionState.start=g,this._selectionState.end=x,this._selectionState.columnSelectMode=C,(k=this._renderer.value)===null||k===void 0||k.handleSelectionChanged(g,x,C)}handleCursorMove(){var g;(g=this._renderer.value)===null||g===void 0||g.handleCursorMove()}clear(){var g;(g=this._renderer.value)===null||g===void 0||g.clear()}};n.RenderService=d=f([m(2,l.IOptionsService),m(3,b.ICharSizeService),m(4,l.IDecorationService),m(5,l.IBufferService),m(6,b.ICoreBrowserService),m(7,b.IThemeService)],d)},9312:function(c,n,a){var f=this&&this.__decorate||function(w,E,L,N){var O,P=arguments.length,F=P<3?E:N===null?N=Object.getOwnPropertyDescriptor(E,L):N;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")F=Reflect.decorate(w,E,L,N);else for(var z=w.length-1;z>=0;z--)(O=w[z])&&(F=(P<3?O(F):P>3?O(E,L,F):O(E,L))||F);return P>3&&F&&Object.defineProperty(E,L,F),F},m=this&&this.__param||function(w,E){return function(L,N){E(L,N,w)}};Object.defineProperty(n,"__esModule",{value:!0}),n.SelectionService=void 0;const p=a(9806),_=a(9504),S=a(456),b=a(4725),y=a(8460),u=a(844),h=a(6114),l=a(4841),d=a(511),g=a(2585),x=" ",C=new RegExp(x,"g");let k=n.SelectionService=class extends u.Disposable{constructor(w,E,L,N,O,P,F,z,W){super(),this._element=w,this._screenElement=E,this._linkifier=L,this._bufferService=N,this._coreService=O,this._mouseService=P,this._optionsService=F,this._renderService=z,this._coreBrowserService=W,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new d.CellData,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this.register(new y.EventEmitter),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this.register(new y.EventEmitter),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this.register(new y.EventEmitter),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this.register(new y.EventEmitter),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=V=>this._handleMouseMove(V),this._mouseUpListener=V=>this._handleMouseUp(V),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(V=>this._handleTrim(V)),this.register(this._bufferService.buffers.onBufferActivate(V=>this._handleBufferActivate(V))),this.enable(),this._model=new S.SelectionModel(this._bufferService),this._activeSelectionMode=0,this.register((0,u.toDisposable)(()=>{this._removeMouseDownListeners()}))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){const w=this._model.finalSelectionStart,E=this._model.finalSelectionEnd;return!(!w||!E||w[0]===E[0]&&w[1]===E[1])}get selectionText(){const w=this._model.finalSelectionStart,E=this._model.finalSelectionEnd;if(!w||!E)return"";const L=this._bufferService.buffer,N=[];if(this._activeSelectionMode===3){if(w[0]===E[0])return"";const O=w[0]O.replace(C," ")).join(h.isWindows?`\r +`:` +`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(w){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),h.isLinux&&w&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(w){const E=this._getMouseBufferCoords(w),L=this._model.finalSelectionStart,N=this._model.finalSelectionEnd;return!!(L&&N&&E)&&this._areCoordsInSelection(E,L,N)}isCellInSelection(w,E){const L=this._model.finalSelectionStart,N=this._model.finalSelectionEnd;return!(!L||!N)&&this._areCoordsInSelection([w,E],L,N)}_areCoordsInSelection(w,E,L){return w[1]>E[1]&&w[1]=E[0]&&w[0]=E[0]}_selectWordAtCursor(w,E){var L,N;const O=(N=(L=this._linkifier.currentLink)===null||L===void 0?void 0:L.link)===null||N===void 0?void 0:N.range;if(O)return this._model.selectionStart=[O.start.x-1,O.start.y-1],this._model.selectionStartLength=(0,l.getRangeLength)(O,this._bufferService.cols),this._model.selectionEnd=void 0,!0;const P=this._getMouseBufferCoords(w);return!!P&&(this._selectWordAt(P,E),this._model.selectionEnd=void 0,!0)}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(w,E){this._model.clearSelection(),w=Math.max(w,0),E=Math.min(E,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,w],this._model.selectionEnd=[this._bufferService.cols,E],this.refresh(),this._onSelectionChange.fire()}_handleTrim(w){this._model.handleTrim(w)&&this.refresh()}_getMouseBufferCoords(w){const E=this._mouseService.getCoords(w,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(E)return E[0]--,E[1]--,E[1]+=this._bufferService.buffer.ydisp,E}_getMouseEventScrollAmount(w){let E=(0,p.getCoordsRelativeToElement)(this._coreBrowserService.window,w,this._screenElement)[1];const L=this._renderService.dimensions.css.canvas.height;return E>=0&&E<=L?0:(E>L&&(E-=L),E=Math.min(Math.max(E,-50),50),E/=50,E/Math.abs(E)+Math.round(14*E))}shouldForceSelection(w){return h.isMac?w.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:w.shiftKey}handleMouseDown(w){if(this._mouseDownTimeStamp=w.timeStamp,(w.button!==2||!this.hasSelection)&&w.button===0){if(!this._enabled){if(!this.shouldForceSelection(w))return;w.stopPropagation()}w.preventDefault(),this._dragScrollAmount=0,this._enabled&&w.shiftKey?this._handleIncrementalClick(w):w.detail===1?this._handleSingleClick(w):w.detail===2?this._handleDoubleClick(w):w.detail===3&&this._handleTripleClick(w),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener("mouseup",this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),50)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener("mouseup",this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(w){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(w))}_handleSingleClick(w){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(w)?3:0,this._model.selectionStart=this._getMouseBufferCoords(w),!this._model.selectionStart)return;this._model.selectionEnd=void 0;const E=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);E&&E.length!==this._model.selectionStart[0]&&E.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(w){this._selectWordAtCursor(w,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(w){const E=this._getMouseBufferCoords(w);E&&(this._activeSelectionMode=2,this._selectLineAt(E[1]))}shouldColumnSelect(w){return w.altKey&&!(h.isMac&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(w){if(w.stopImmediatePropagation(),!this._model.selectionStart)return;const E=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(w),!this._model.selectionEnd)return void this.refresh(!0);this._activeSelectionMode===2?this._model.selectionEnd[1]0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));const L=this._bufferService.buffer;if(this._model.selectionEnd[1]0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(w.ydisp+this._bufferService.rows,w.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=w.ydisp),this.refresh()}}_handleMouseUp(w){const E=w.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&E<500&&w.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){const L=this._mouseService.getCoords(w,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(L&&L[0]!==void 0&&L[1]!==void 0){const N=(0,_.moveToCellSequence)(L[0]-1,L[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(N,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){const w=this._model.finalSelectionStart,E=this._model.finalSelectionEnd,L=!(!w||!E||w[0]===E[0]&&w[1]===E[1]);L?w&&E&&(this._oldSelectionStart&&this._oldSelectionEnd&&w[0]===this._oldSelectionStart[0]&&w[1]===this._oldSelectionStart[1]&&E[0]===this._oldSelectionEnd[0]&&E[1]===this._oldSelectionEnd[1]||this._fireOnSelectionChange(w,E,L)):this._oldHasSelection&&this._fireOnSelectionChange(w,E,L)}_fireOnSelectionChange(w,E,L){this._oldSelectionStart=w,this._oldSelectionEnd=E,this._oldHasSelection=L,this._onSelectionChange.fire()}_handleBufferActivate(w){this.clearSelection(),this._trimListener.dispose(),this._trimListener=w.activeBuffer.lines.onTrim(E=>this._handleTrim(E))}_convertViewportColToCharacterIndex(w,E){let L=E;for(let N=0;E>=N;N++){const O=w.loadCell(N,this._workCell).getChars().length;this._workCell.getWidth()===0?L--:O>1&&E!==N&&(L+=O-1)}return L}setSelection(w,E,L){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[w,E],this._model.selectionStartLength=L,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(w){this._isClickInSelection(w)||(this._selectWordAtCursor(w,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(w,E,L=!0,N=!0){if(w[0]>=this._bufferService.cols)return;const O=this._bufferService.buffer,P=O.lines.get(w[1]);if(!P)return;const F=O.translateBufferLineToString(w[1],!1);let z=this._convertViewportColToCharacterIndex(P,w[0]),W=z;const V=w[0]-z;let R=0,D=0,A=0,B=0;if(F.charAt(z)===" "){for(;z>0&&F.charAt(z-1)===" ";)z--;for(;W1&&(B+=te-1,W+=te-1);G>0&&z>0&&!this._isCharWordSeparator(P.loadCell(G-1,this._workCell));){P.loadCell(G-1,this._workCell);const T=this._workCell.getChars().length;this._workCell.getWidth()===0?(R++,G--):T>1&&(A+=T-1,z-=T-1),z--,G--}for(;X1&&(B+=T-1,W+=T-1),W++,X++}}W++;let H=z+V-R+A,q=Math.min(this._bufferService.cols,W-z+R+D-A-B);if(E||F.slice(z,W).trim()!==""){if(L&&H===0&&P.getCodePoint(0)!==32){const G=O.lines.get(w[1]-1);if(G&&P.isWrapped&&G.getCodePoint(this._bufferService.cols-1)!==32){const X=this._getWordAt([this._bufferService.cols-1,w[1]-1],!1,!0,!1);if(X){const te=this._bufferService.cols-X.start;H-=te,q+=te}}}if(N&&H+q===this._bufferService.cols&&P.getCodePoint(this._bufferService.cols-1)!==32){const G=O.lines.get(w[1]+1);if(G!=null&&G.isWrapped&&G.getCodePoint(0)!==32){const X=this._getWordAt([0,w[1]+1],!1,!1,!0);X&&(q+=X.length)}}return{start:H,length:q}}}_selectWordAt(w,E){const L=this._getWordAt(w,E);if(L){for(;L.start<0;)L.start+=this._bufferService.cols,w[1]--;this._model.selectionStart=[L.start,w[1]],this._model.selectionStartLength=L.length}}_selectToWordAt(w){const E=this._getWordAt(w,!0);if(E){let L=w[1];for(;E.start<0;)E.start+=this._bufferService.cols,L--;if(!this._model.areSelectionValuesReversed())for(;E.start+E.length>this._bufferService.cols;)E.length-=this._bufferService.cols,L++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?E.start:E.start+E.length,L]}}_isCharWordSeparator(w){return w.getWidth()!==0&&this._optionsService.rawOptions.wordSeparator.indexOf(w.getChars())>=0}_selectLineAt(w){const E=this._bufferService.buffer.getWrappedRangeForLine(w),L={start:{x:0,y:E.first},end:{x:this._bufferService.cols-1,y:E.last}};this._model.selectionStart=[0,E.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=(0,l.getRangeLength)(L,this._bufferService.cols)}};n.SelectionService=k=f([m(3,g.IBufferService),m(4,g.ICoreService),m(5,b.IMouseService),m(6,g.IOptionsService),m(7,b.IRenderService),m(8,b.ICoreBrowserService)],k)},4725:(c,n,a)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.IThemeService=n.ICharacterJoinerService=n.ISelectionService=n.IRenderService=n.IMouseService=n.ICoreBrowserService=n.ICharSizeService=void 0;const f=a(8343);n.ICharSizeService=(0,f.createDecorator)("CharSizeService"),n.ICoreBrowserService=(0,f.createDecorator)("CoreBrowserService"),n.IMouseService=(0,f.createDecorator)("MouseService"),n.IRenderService=(0,f.createDecorator)("RenderService"),n.ISelectionService=(0,f.createDecorator)("SelectionService"),n.ICharacterJoinerService=(0,f.createDecorator)("CharacterJoinerService"),n.IThemeService=(0,f.createDecorator)("ThemeService")},6731:function(c,n,a){var f=this&&this.__decorate||function(k,w,E,L){var N,O=arguments.length,P=O<3?w:L===null?L=Object.getOwnPropertyDescriptor(w,E):L;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")P=Reflect.decorate(k,w,E,L);else for(var F=k.length-1;F>=0;F--)(N=k[F])&&(P=(O<3?N(P):O>3?N(w,E,P):N(w,E))||P);return O>3&&P&&Object.defineProperty(w,E,P),P},m=this&&this.__param||function(k,w){return function(E,L){w(E,L,k)}};Object.defineProperty(n,"__esModule",{value:!0}),n.ThemeService=n.DEFAULT_ANSI_COLORS=void 0;const p=a(7239),_=a(8055),S=a(8460),b=a(844),y=a(2585),u=_.css.toColor("#ffffff"),h=_.css.toColor("#000000"),l=_.css.toColor("#ffffff"),d=_.css.toColor("#000000"),g={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117};n.DEFAULT_ANSI_COLORS=Object.freeze((()=>{const k=[_.css.toColor("#2e3436"),_.css.toColor("#cc0000"),_.css.toColor("#4e9a06"),_.css.toColor("#c4a000"),_.css.toColor("#3465a4"),_.css.toColor("#75507b"),_.css.toColor("#06989a"),_.css.toColor("#d3d7cf"),_.css.toColor("#555753"),_.css.toColor("#ef2929"),_.css.toColor("#8ae234"),_.css.toColor("#fce94f"),_.css.toColor("#729fcf"),_.css.toColor("#ad7fa8"),_.css.toColor("#34e2e2"),_.css.toColor("#eeeeec")],w=[0,95,135,175,215,255];for(let E=0;E<216;E++){const L=w[E/36%6|0],N=w[E/6%6|0],O=w[E%6];k.push({css:_.channels.toCss(L,N,O),rgba:_.channels.toRgba(L,N,O)})}for(let E=0;E<24;E++){const L=8+10*E;k.push({css:_.channels.toCss(L,L,L),rgba:_.channels.toRgba(L,L,L)})}return k})());let x=n.ThemeService=class extends b.Disposable{get colors(){return this._colors}constructor(k){super(),this._optionsService=k,this._contrastCache=new p.ColorContrastCache,this._halfContrastCache=new p.ColorContrastCache,this._onChangeColors=this.register(new S.EventEmitter),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:u,background:h,cursor:l,cursorAccent:d,selectionForeground:void 0,selectionBackgroundTransparent:g,selectionBackgroundOpaque:_.color.blend(h,g),selectionInactiveBackgroundTransparent:g,selectionInactiveBackgroundOpaque:_.color.blend(h,g),ansi:n.DEFAULT_ANSI_COLORS.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this.register(this._optionsService.onSpecificOptionChange("minimumContrastRatio",()=>this._contrastCache.clear())),this.register(this._optionsService.onSpecificOptionChange("theme",()=>this._setTheme(this._optionsService.rawOptions.theme)))}_setTheme(k={}){const w=this._colors;if(w.foreground=C(k.foreground,u),w.background=C(k.background,h),w.cursor=C(k.cursor,l),w.cursorAccent=C(k.cursorAccent,d),w.selectionBackgroundTransparent=C(k.selectionBackground,g),w.selectionBackgroundOpaque=_.color.blend(w.background,w.selectionBackgroundTransparent),w.selectionInactiveBackgroundTransparent=C(k.selectionInactiveBackground,w.selectionBackgroundTransparent),w.selectionInactiveBackgroundOpaque=_.color.blend(w.background,w.selectionInactiveBackgroundTransparent),w.selectionForeground=k.selectionForeground?C(k.selectionForeground,_.NULL_COLOR):void 0,w.selectionForeground===_.NULL_COLOR&&(w.selectionForeground=void 0),_.color.isOpaque(w.selectionBackgroundTransparent)&&(w.selectionBackgroundTransparent=_.color.opacity(w.selectionBackgroundTransparent,.3)),_.color.isOpaque(w.selectionInactiveBackgroundTransparent)&&(w.selectionInactiveBackgroundTransparent=_.color.opacity(w.selectionInactiveBackgroundTransparent,.3)),w.ansi=n.DEFAULT_ANSI_COLORS.slice(),w.ansi[0]=C(k.black,n.DEFAULT_ANSI_COLORS[0]),w.ansi[1]=C(k.red,n.DEFAULT_ANSI_COLORS[1]),w.ansi[2]=C(k.green,n.DEFAULT_ANSI_COLORS[2]),w.ansi[3]=C(k.yellow,n.DEFAULT_ANSI_COLORS[3]),w.ansi[4]=C(k.blue,n.DEFAULT_ANSI_COLORS[4]),w.ansi[5]=C(k.magenta,n.DEFAULT_ANSI_COLORS[5]),w.ansi[6]=C(k.cyan,n.DEFAULT_ANSI_COLORS[6]),w.ansi[7]=C(k.white,n.DEFAULT_ANSI_COLORS[7]),w.ansi[8]=C(k.brightBlack,n.DEFAULT_ANSI_COLORS[8]),w.ansi[9]=C(k.brightRed,n.DEFAULT_ANSI_COLORS[9]),w.ansi[10]=C(k.brightGreen,n.DEFAULT_ANSI_COLORS[10]),w.ansi[11]=C(k.brightYellow,n.DEFAULT_ANSI_COLORS[11]),w.ansi[12]=C(k.brightBlue,n.DEFAULT_ANSI_COLORS[12]),w.ansi[13]=C(k.brightMagenta,n.DEFAULT_ANSI_COLORS[13]),w.ansi[14]=C(k.brightCyan,n.DEFAULT_ANSI_COLORS[14]),w.ansi[15]=C(k.brightWhite,n.DEFAULT_ANSI_COLORS[15]),k.extendedAnsi){const E=Math.min(w.ansi.length-16,k.extendedAnsi.length);for(let L=0;L{Object.defineProperty(n,"__esModule",{value:!0}),n.CircularList=void 0;const f=a(8460),m=a(844);class p extends m.Disposable{constructor(S){super(),this._maxLength=S,this.onDeleteEmitter=this.register(new f.EventEmitter),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this.register(new f.EventEmitter),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this.register(new f.EventEmitter),this.onTrim=this.onTrimEmitter.event,this._array=new Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(S){if(this._maxLength===S)return;const b=new Array(S);for(let y=0;ythis._length)for(let b=this._length;b=S;u--)this._array[this._getCyclicIndex(u+y.length)]=this._array[this._getCyclicIndex(u)];for(let u=0;uthis._maxLength){const u=this._length+y.length-this._maxLength;this._startIndex+=u,this._length=this._maxLength,this.onTrimEmitter.fire(u)}else this._length+=y.length}trimStart(S){S>this._length&&(S=this._length),this._startIndex+=S,this._length-=S,this.onTrimEmitter.fire(S)}shiftElements(S,b,y){if(!(b<=0)){if(S<0||S>=this._length)throw new Error("start argument out of range");if(S+y<0)throw new Error("Cannot shift elements in list beyond index 0");if(y>0){for(let h=b-1;h>=0;h--)this.set(S+h+y,this.get(S+h));const u=S+b+y-this._length;if(u>0)for(this._length+=u;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let u=0;u{Object.defineProperty(n,"__esModule",{value:!0}),n.clone=void 0,n.clone=function a(f,m=5){if(typeof f!="object")return f;const p=Array.isArray(f)?[]:{};for(const _ in f)p[_]=m<=1?f[_]:f[_]&&a(f[_],m-1);return p}},8055:(c,n,a)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.contrastRatio=n.toPaddedHex=n.rgba=n.rgb=n.css=n.color=n.channels=n.NULL_COLOR=void 0;const f=a(6114);let m=0,p=0,_=0,S=0;var b,y,u,h,l;function d(x){const C=x.toString(16);return C.length<2?"0"+C:C}function g(x,C){return x>>0}}(b||(n.channels=b={})),function(x){function C(k,w){return S=Math.round(255*w),[m,p,_]=l.toChannels(k.rgba),{css:b.toCss(m,p,_,S),rgba:b.toRgba(m,p,_,S)}}x.blend=function(k,w){if(S=(255&w.rgba)/255,S===1)return{css:w.css,rgba:w.rgba};const E=w.rgba>>24&255,L=w.rgba>>16&255,N=w.rgba>>8&255,O=k.rgba>>24&255,P=k.rgba>>16&255,F=k.rgba>>8&255;return m=O+Math.round((E-O)*S),p=P+Math.round((L-P)*S),_=F+Math.round((N-F)*S),{css:b.toCss(m,p,_),rgba:b.toRgba(m,p,_)}},x.isOpaque=function(k){return(255&k.rgba)==255},x.ensureContrastRatio=function(k,w,E){const L=l.ensureContrastRatio(k.rgba,w.rgba,E);if(L)return l.toColor(L>>24&255,L>>16&255,L>>8&255)},x.opaque=function(k){const w=(255|k.rgba)>>>0;return[m,p,_]=l.toChannels(w),{css:b.toCss(m,p,_),rgba:w}},x.opacity=C,x.multiplyOpacity=function(k,w){return S=255&k.rgba,C(k,S*w/255)},x.toColorRGB=function(k){return[k.rgba>>24&255,k.rgba>>16&255,k.rgba>>8&255]}}(y||(n.color=y={})),function(x){let C,k;if(!f.isNode){const w=document.createElement("canvas");w.width=1,w.height=1;const E=w.getContext("2d",{willReadFrequently:!0});E&&(C=E,C.globalCompositeOperation="copy",k=C.createLinearGradient(0,0,1,1))}x.toColor=function(w){if(w.match(/#[\da-f]{3,8}/i))switch(w.length){case 4:return m=parseInt(w.slice(1,2).repeat(2),16),p=parseInt(w.slice(2,3).repeat(2),16),_=parseInt(w.slice(3,4).repeat(2),16),l.toColor(m,p,_);case 5:return m=parseInt(w.slice(1,2).repeat(2),16),p=parseInt(w.slice(2,3).repeat(2),16),_=parseInt(w.slice(3,4).repeat(2),16),S=parseInt(w.slice(4,5).repeat(2),16),l.toColor(m,p,_,S);case 7:return{css:w,rgba:(parseInt(w.slice(1),16)<<8|255)>>>0};case 9:return{css:w,rgba:parseInt(w.slice(1),16)>>>0}}const E=w.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(E)return m=parseInt(E[1]),p=parseInt(E[2]),_=parseInt(E[3]),S=Math.round(255*(E[5]===void 0?1:parseFloat(E[5]))),l.toColor(m,p,_,S);if(!C||!k)throw new Error("css.toColor: Unsupported css format");if(C.fillStyle=k,C.fillStyle=w,typeof C.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(C.fillRect(0,0,1,1),[m,p,_,S]=C.getImageData(0,0,1,1).data,S!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:b.toRgba(m,p,_,S),css:w}}}(u||(n.css=u={})),function(x){function C(k,w,E){const L=k/255,N=w/255,O=E/255;return .2126*(L<=.03928?L/12.92:Math.pow((L+.055)/1.055,2.4))+.7152*(N<=.03928?N/12.92:Math.pow((N+.055)/1.055,2.4))+.0722*(O<=.03928?O/12.92:Math.pow((O+.055)/1.055,2.4))}x.relativeLuminance=function(k){return C(k>>16&255,k>>8&255,255&k)},x.relativeLuminance2=C}(h||(n.rgb=h={})),function(x){function C(w,E,L){const N=w>>24&255,O=w>>16&255,P=w>>8&255;let F=E>>24&255,z=E>>16&255,W=E>>8&255,V=g(h.relativeLuminance2(F,z,W),h.relativeLuminance2(N,O,P));for(;V0||z>0||W>0);)F-=Math.max(0,Math.ceil(.1*F)),z-=Math.max(0,Math.ceil(.1*z)),W-=Math.max(0,Math.ceil(.1*W)),V=g(h.relativeLuminance2(F,z,W),h.relativeLuminance2(N,O,P));return(F<<24|z<<16|W<<8|255)>>>0}function k(w,E,L){const N=w>>24&255,O=w>>16&255,P=w>>8&255;let F=E>>24&255,z=E>>16&255,W=E>>8&255,V=g(h.relativeLuminance2(F,z,W),h.relativeLuminance2(N,O,P));for(;V>>0}x.ensureContrastRatio=function(w,E,L){const N=h.relativeLuminance(w>>8),O=h.relativeLuminance(E>>8);if(g(N,O)>8));if(Wg(N,h.relativeLuminance(V>>8))?z:V}return z}const P=k(w,E,L),F=g(N,h.relativeLuminance(P>>8));if(Fg(N,h.relativeLuminance(z>>8))?P:z}return P}},x.reduceLuminance=C,x.increaseLuminance=k,x.toChannels=function(w){return[w>>24&255,w>>16&255,w>>8&255,255&w]},x.toColor=function(w,E,L,N){return{css:b.toCss(w,E,L,N),rgba:b.toRgba(w,E,L,N)}}}(l||(n.rgba=l={})),n.toPaddedHex=d,n.contrastRatio=g},8969:(c,n,a)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.CoreTerminal=void 0;const f=a(844),m=a(2585),p=a(4348),_=a(7866),S=a(744),b=a(7302),y=a(6975),u=a(8460),h=a(1753),l=a(1480),d=a(7994),g=a(9282),x=a(5435),C=a(5981),k=a(2660);let w=!1;class E extends f.Disposable{get onScroll(){return this._onScrollApi||(this._onScrollApi=this.register(new u.EventEmitter),this._onScroll.event(N=>{var O;(O=this._onScrollApi)===null||O===void 0||O.fire(N.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(N){for(const O in N)this.optionsService.options[O]=N[O]}constructor(N){super(),this._windowsWrappingHeuristics=this.register(new f.MutableDisposable),this._onBinary=this.register(new u.EventEmitter),this.onBinary=this._onBinary.event,this._onData=this.register(new u.EventEmitter),this.onData=this._onData.event,this._onLineFeed=this.register(new u.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onResize=this.register(new u.EventEmitter),this.onResize=this._onResize.event,this._onWriteParsed=this.register(new u.EventEmitter),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this.register(new u.EventEmitter),this._instantiationService=new p.InstantiationService,this.optionsService=this.register(new b.OptionsService(N)),this._instantiationService.setService(m.IOptionsService,this.optionsService),this._bufferService=this.register(this._instantiationService.createInstance(S.BufferService)),this._instantiationService.setService(m.IBufferService,this._bufferService),this._logService=this.register(this._instantiationService.createInstance(_.LogService)),this._instantiationService.setService(m.ILogService,this._logService),this.coreService=this.register(this._instantiationService.createInstance(y.CoreService)),this._instantiationService.setService(m.ICoreService,this.coreService),this.coreMouseService=this.register(this._instantiationService.createInstance(h.CoreMouseService)),this._instantiationService.setService(m.ICoreMouseService,this.coreMouseService),this.unicodeService=this.register(this._instantiationService.createInstance(l.UnicodeService)),this._instantiationService.setService(m.IUnicodeService,this.unicodeService),this._charsetService=this._instantiationService.createInstance(d.CharsetService),this._instantiationService.setService(m.ICharsetService,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(k.OscLinkService),this._instantiationService.setService(m.IOscLinkService,this._oscLinkService),this._inputHandler=this.register(new x.InputHandler(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this.register((0,u.forwardEvent)(this._inputHandler.onLineFeed,this._onLineFeed)),this.register(this._inputHandler),this.register((0,u.forwardEvent)(this._bufferService.onResize,this._onResize)),this.register((0,u.forwardEvent)(this.coreService.onData,this._onData)),this.register((0,u.forwardEvent)(this.coreService.onBinary,this._onBinary)),this.register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom())),this.register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this.register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],()=>this._handleWindowsPtyOptionChange())),this.register(this._bufferService.onScroll(O=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp,source:0}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this.register(this._inputHandler.onScroll(O=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp,source:0}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this.register(new C.WriteBuffer((O,P)=>this._inputHandler.parse(O,P))),this.register((0,u.forwardEvent)(this._writeBuffer.onWriteParsed,this._onWriteParsed))}write(N,O){this._writeBuffer.write(N,O)}writeSync(N,O){this._logService.logLevel<=m.LogLevelEnum.WARN&&!w&&(this._logService.warn("writeSync is unreliable and will be removed soon."),w=!0),this._writeBuffer.writeSync(N,O)}resize(N,O){isNaN(N)||isNaN(O)||(N=Math.max(N,S.MINIMUM_COLS),O=Math.max(O,S.MINIMUM_ROWS),this._bufferService.resize(N,O))}scroll(N,O=!1){this._bufferService.scroll(N,O)}scrollLines(N,O,P){this._bufferService.scrollLines(N,O,P)}scrollPages(N){this.scrollLines(N*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(N){const O=N-this._bufferService.buffer.ydisp;O!==0&&this.scrollLines(O)}registerEscHandler(N,O){return this._inputHandler.registerEscHandler(N,O)}registerDcsHandler(N,O){return this._inputHandler.registerDcsHandler(N,O)}registerCsiHandler(N,O){return this._inputHandler.registerCsiHandler(N,O)}registerOscHandler(N,O){return this._inputHandler.registerOscHandler(N,O)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let N=!1;const O=this.optionsService.rawOptions.windowsPty;O&&O.buildNumber!==void 0&&O.buildNumber!==void 0?N=O.backend==="conpty"&&O.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(N=!0),N?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){const N=[];N.push(this.onLineFeed(g.updateWindowsModeWrappedState.bind(null,this._bufferService))),N.push(this.registerCsiHandler({final:"H"},()=>((0,g.updateWindowsModeWrappedState)(this._bufferService),!1))),this._windowsWrappingHeuristics.value=(0,f.toDisposable)(()=>{for(const O of N)O.dispose()})}}}n.CoreTerminal=E},8460:(c,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.forwardEvent=n.EventEmitter=void 0,n.EventEmitter=class{constructor(){this._listeners=[],this._disposed=!1}get event(){return this._event||(this._event=a=>(this._listeners.push(a),{dispose:()=>{if(!this._disposed){for(let f=0;ff.fire(m))}},5435:function(c,n,a){var f=this&&this.__decorate||function(V,R,D,A){var B,H=arguments.length,q=H<3?R:A===null?A=Object.getOwnPropertyDescriptor(R,D):A;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")q=Reflect.decorate(V,R,D,A);else for(var G=V.length-1;G>=0;G--)(B=V[G])&&(q=(H<3?B(q):H>3?B(R,D,q):B(R,D))||q);return H>3&&q&&Object.defineProperty(R,D,q),q},m=this&&this.__param||function(V,R){return function(D,A){R(D,A,V)}};Object.defineProperty(n,"__esModule",{value:!0}),n.InputHandler=n.WindowsOptionsReportType=void 0;const p=a(2584),_=a(7116),S=a(2015),b=a(844),y=a(482),u=a(8437),h=a(8460),l=a(643),d=a(511),g=a(3734),x=a(2585),C=a(6242),k=a(6351),w=a(5941),E={"(":0,")":1,"*":2,"+":3,"-":1,".":2},L=131072;function N(V,R){if(V>24)return R.setWinLines||!1;switch(V){case 1:return!!R.restoreWin;case 2:return!!R.minimizeWin;case 3:return!!R.setWinPosition;case 4:return!!R.setWinSizePixels;case 5:return!!R.raiseWin;case 6:return!!R.lowerWin;case 7:return!!R.refreshWin;case 8:return!!R.setWinSizeChars;case 9:return!!R.maximizeWin;case 10:return!!R.fullscreenWin;case 11:return!!R.getWinState;case 13:return!!R.getWinPosition;case 14:return!!R.getWinSizePixels;case 15:return!!R.getScreenSizePixels;case 16:return!!R.getCellSizePixels;case 18:return!!R.getWinSizeChars;case 19:return!!R.getScreenSizeChars;case 20:return!!R.getIconTitle;case 21:return!!R.getWinTitle;case 22:return!!R.pushTitle;case 23:return!!R.popTitle;case 24:return!!R.setWinLines}return!1}var O;(function(V){V[V.GET_WIN_SIZE_PIXELS=0]="GET_WIN_SIZE_PIXELS",V[V.GET_CELL_SIZE_PIXELS=1]="GET_CELL_SIZE_PIXELS"})(O||(n.WindowsOptionsReportType=O={}));let P=0;class F extends b.Disposable{getAttrData(){return this._curAttrData}constructor(R,D,A,B,H,q,G,X,te=new S.EscapeSequenceParser){super(),this._bufferService=R,this._charsetService=D,this._coreService=A,this._logService=B,this._optionsService=H,this._oscLinkService=q,this._coreMouseService=G,this._unicodeService=X,this._parser=te,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new y.StringToUtf32,this._utf8Decoder=new y.Utf8ToUtf32,this._workCell=new d.CellData,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=u.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=u.DEFAULT_ATTR_DATA.clone(),this._onRequestBell=this.register(new h.EventEmitter),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this.register(new h.EventEmitter),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this.register(new h.EventEmitter),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this.register(new h.EventEmitter),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this.register(new h.EventEmitter),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this.register(new h.EventEmitter),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this.register(new h.EventEmitter),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this.register(new h.EventEmitter),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this.register(new h.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this.register(new h.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onScroll=this.register(new h.EventEmitter),this.onScroll=this._onScroll.event,this._onTitleChange=this.register(new h.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onColor=this.register(new h.EventEmitter),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this.register(this._parser),this._dirtyRowTracker=new z(this._bufferService),this._activeBuffer=this._bufferService.buffer,this.register(this._bufferService.buffers.onBufferActivate(T=>this._activeBuffer=T.activeBuffer)),this._parser.setCsiHandlerFallback((T,j)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(T),params:j.toArray()})}),this._parser.setEscHandlerFallback(T=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(T)})}),this._parser.setExecuteHandlerFallback(T=>{this._logService.debug("Unknown EXECUTE code: ",{code:T})}),this._parser.setOscHandlerFallback((T,j,$)=>{this._logService.debug("Unknown OSC code: ",{identifier:T,action:j,data:$})}),this._parser.setDcsHandlerFallback((T,j,$)=>{j==="HOOK"&&($=$.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(T),action:j,payload:$})}),this._parser.setPrintHandler((T,j,$)=>this.print(T,j,$)),this._parser.registerCsiHandler({final:"@"},T=>this.insertChars(T)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},T=>this.scrollLeft(T)),this._parser.registerCsiHandler({final:"A"},T=>this.cursorUp(T)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},T=>this.scrollRight(T)),this._parser.registerCsiHandler({final:"B"},T=>this.cursorDown(T)),this._parser.registerCsiHandler({final:"C"},T=>this.cursorForward(T)),this._parser.registerCsiHandler({final:"D"},T=>this.cursorBackward(T)),this._parser.registerCsiHandler({final:"E"},T=>this.cursorNextLine(T)),this._parser.registerCsiHandler({final:"F"},T=>this.cursorPrecedingLine(T)),this._parser.registerCsiHandler({final:"G"},T=>this.cursorCharAbsolute(T)),this._parser.registerCsiHandler({final:"H"},T=>this.cursorPosition(T)),this._parser.registerCsiHandler({final:"I"},T=>this.cursorForwardTab(T)),this._parser.registerCsiHandler({final:"J"},T=>this.eraseInDisplay(T,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},T=>this.eraseInDisplay(T,!0)),this._parser.registerCsiHandler({final:"K"},T=>this.eraseInLine(T,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},T=>this.eraseInLine(T,!0)),this._parser.registerCsiHandler({final:"L"},T=>this.insertLines(T)),this._parser.registerCsiHandler({final:"M"},T=>this.deleteLines(T)),this._parser.registerCsiHandler({final:"P"},T=>this.deleteChars(T)),this._parser.registerCsiHandler({final:"S"},T=>this.scrollUp(T)),this._parser.registerCsiHandler({final:"T"},T=>this.scrollDown(T)),this._parser.registerCsiHandler({final:"X"},T=>this.eraseChars(T)),this._parser.registerCsiHandler({final:"Z"},T=>this.cursorBackwardTab(T)),this._parser.registerCsiHandler({final:"`"},T=>this.charPosAbsolute(T)),this._parser.registerCsiHandler({final:"a"},T=>this.hPositionRelative(T)),this._parser.registerCsiHandler({final:"b"},T=>this.repeatPrecedingCharacter(T)),this._parser.registerCsiHandler({final:"c"},T=>this.sendDeviceAttributesPrimary(T)),this._parser.registerCsiHandler({prefix:">",final:"c"},T=>this.sendDeviceAttributesSecondary(T)),this._parser.registerCsiHandler({final:"d"},T=>this.linePosAbsolute(T)),this._parser.registerCsiHandler({final:"e"},T=>this.vPositionRelative(T)),this._parser.registerCsiHandler({final:"f"},T=>this.hVPosition(T)),this._parser.registerCsiHandler({final:"g"},T=>this.tabClear(T)),this._parser.registerCsiHandler({final:"h"},T=>this.setMode(T)),this._parser.registerCsiHandler({prefix:"?",final:"h"},T=>this.setModePrivate(T)),this._parser.registerCsiHandler({final:"l"},T=>this.resetMode(T)),this._parser.registerCsiHandler({prefix:"?",final:"l"},T=>this.resetModePrivate(T)),this._parser.registerCsiHandler({final:"m"},T=>this.charAttributes(T)),this._parser.registerCsiHandler({final:"n"},T=>this.deviceStatus(T)),this._parser.registerCsiHandler({prefix:"?",final:"n"},T=>this.deviceStatusPrivate(T)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},T=>this.softReset(T)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},T=>this.setCursorStyle(T)),this._parser.registerCsiHandler({final:"r"},T=>this.setScrollRegion(T)),this._parser.registerCsiHandler({final:"s"},T=>this.saveCursor(T)),this._parser.registerCsiHandler({final:"t"},T=>this.windowOptions(T)),this._parser.registerCsiHandler({final:"u"},T=>this.restoreCursor(T)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},T=>this.insertColumns(T)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},T=>this.deleteColumns(T)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},T=>this.selectProtected(T)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},T=>this.requestMode(T,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},T=>this.requestMode(T,!1)),this._parser.setExecuteHandler(p.C0.BEL,()=>this.bell()),this._parser.setExecuteHandler(p.C0.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(p.C0.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(p.C0.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(p.C0.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(p.C0.BS,()=>this.backspace()),this._parser.setExecuteHandler(p.C0.HT,()=>this.tab()),this._parser.setExecuteHandler(p.C0.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(p.C0.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(p.C1.IND,()=>this.index()),this._parser.setExecuteHandler(p.C1.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(p.C1.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new C.OscHandler(T=>(this.setTitle(T),this.setIconName(T),!0))),this._parser.registerOscHandler(1,new C.OscHandler(T=>this.setIconName(T))),this._parser.registerOscHandler(2,new C.OscHandler(T=>this.setTitle(T))),this._parser.registerOscHandler(4,new C.OscHandler(T=>this.setOrReportIndexedColor(T))),this._parser.registerOscHandler(8,new C.OscHandler(T=>this.setHyperlink(T))),this._parser.registerOscHandler(10,new C.OscHandler(T=>this.setOrReportFgColor(T))),this._parser.registerOscHandler(11,new C.OscHandler(T=>this.setOrReportBgColor(T))),this._parser.registerOscHandler(12,new C.OscHandler(T=>this.setOrReportCursorColor(T))),this._parser.registerOscHandler(104,new C.OscHandler(T=>this.restoreIndexedColor(T))),this._parser.registerOscHandler(110,new C.OscHandler(T=>this.restoreFgColor(T))),this._parser.registerOscHandler(111,new C.OscHandler(T=>this.restoreBgColor(T))),this._parser.registerOscHandler(112,new C.OscHandler(T=>this.restoreCursorColor(T))),this._parser.registerEscHandler({final:"7"},()=>this.saveCursor()),this._parser.registerEscHandler({final:"8"},()=>this.restoreCursor()),this._parser.registerEscHandler({final:"D"},()=>this.index()),this._parser.registerEscHandler({final:"E"},()=>this.nextLine()),this._parser.registerEscHandler({final:"H"},()=>this.tabSet()),this._parser.registerEscHandler({final:"M"},()=>this.reverseIndex()),this._parser.registerEscHandler({final:"="},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:">"},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:"c"},()=>this.fullReset()),this._parser.registerEscHandler({final:"n"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"o"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"|"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"}"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"~"},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:"%",final:"@"},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:"%",final:"G"},()=>this.selectDefaultCharset());for(const T in _.CHARSETS)this._parser.registerEscHandler({intermediates:"(",final:T},()=>this.selectCharset("("+T)),this._parser.registerEscHandler({intermediates:")",final:T},()=>this.selectCharset(")"+T)),this._parser.registerEscHandler({intermediates:"*",final:T},()=>this.selectCharset("*"+T)),this._parser.registerEscHandler({intermediates:"+",final:T},()=>this.selectCharset("+"+T)),this._parser.registerEscHandler({intermediates:"-",final:T},()=>this.selectCharset("-"+T)),this._parser.registerEscHandler({intermediates:".",final:T},()=>this.selectCharset("."+T)),this._parser.registerEscHandler({intermediates:"/",final:T},()=>this.selectCharset("/"+T));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(T=>(this._logService.error("Parsing error: ",T),T)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new k.DcsHandler((T,j)=>this.requestStatusString(T,j)))}_preserveStack(R,D,A,B){this._parseStack.paused=!0,this._parseStack.cursorStartX=R,this._parseStack.cursorStartY=D,this._parseStack.decodedLength=A,this._parseStack.position=B}_logSlowResolvingAsync(R){this._logService.logLevel<=x.LogLevelEnum.WARN&&Promise.race([R,new Promise((D,A)=>setTimeout(()=>A("#SLOW_TIMEOUT"),5e3))]).catch(D=>{if(D!=="#SLOW_TIMEOUT")throw D;console.warn("async parser handler taking longer than 5000 ms")})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(R,D){let A,B=this._activeBuffer.x,H=this._activeBuffer.y,q=0;const G=this._parseStack.paused;if(G){if(A=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,D))return this._logSlowResolvingAsync(A),A;B=this._parseStack.cursorStartX,H=this._parseStack.cursorStartY,this._parseStack.paused=!1,R.length>L&&(q=this._parseStack.position+L)}if(this._logService.logLevel<=x.LogLevelEnum.DEBUG&&this._logService.debug("parsing data"+(typeof R=="string"?` "${R}"`:` "${Array.prototype.map.call(R,X=>String.fromCharCode(X)).join("")}"`),typeof R=="string"?R.split("").map(X=>X.charCodeAt(0)):R),this._parseBuffer.lengthL)for(let X=q;X0&&$.getWidth(this._activeBuffer.x-1)===2&&$.setCellFromCodePoint(this._activeBuffer.x-1,0,1,j.fg,j.bg,j.extended);for(let U=D;U=X){if(te){for(;this._activeBuffer.x=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),$=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)}else if(this._activeBuffer.x=X-1,H===2)continue}if(T&&($.insertCells(this._activeBuffer.x,H,this._activeBuffer.getNullCell(j),j),$.getWidth(X-1)===2&&$.setCellFromCodePoint(X-1,l.NULL_CELL_CODE,l.NULL_CELL_WIDTH,j.fg,j.bg,j.extended)),$.setCellFromCodePoint(this._activeBuffer.x++,B,H,j.fg,j.bg,j.extended),H>0)for(;--H;)$.setCellFromCodePoint(this._activeBuffer.x++,0,0,j.fg,j.bg,j.extended)}else $.getWidth(this._activeBuffer.x-1)?$.addCodepointToCell(this._activeBuffer.x-1,B):$.addCodepointToCell(this._activeBuffer.x-2,B)}A-D>0&&($.loadCell(this._activeBuffer.x-1,this._workCell),this._workCell.getWidth()===2||this._workCell.getCode()>65535?this._parser.precedingCodepoint=0:this._workCell.isCombined()?this._parser.precedingCodepoint=this._workCell.getChars().charCodeAt(0):this._parser.precedingCodepoint=this._workCell.content),this._activeBuffer.x0&&$.getWidth(this._activeBuffer.x)===0&&!$.hasContent(this._activeBuffer.x)&&$.setCellFromCodePoint(this._activeBuffer.x,0,1,j.fg,j.bg,j.extended),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(R,D){return R.final!=="t"||R.prefix||R.intermediates?this._parser.registerCsiHandler(R,D):this._parser.registerCsiHandler(R,A=>!N(A.params[0],this._optionsService.rawOptions.windowOptions)||D(A))}registerDcsHandler(R,D){return this._parser.registerDcsHandler(R,new k.DcsHandler(D))}registerEscHandler(R,D){return this._parser.registerEscHandler(R,D)}registerOscHandler(R,D){return this._parser.registerOscHandler(R,new C.OscHandler(D))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){var R;if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&(!((R=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y))===null||R===void 0)&&R.isWrapped)){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;const D=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);D.hasWidth(this._activeBuffer.x)&&!D.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;const R=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-R),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(R=this._bufferService.cols-1){this._activeBuffer.x=Math.min(R,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(R,D){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=R,this._activeBuffer.y=this._activeBuffer.scrollTop+D):(this._activeBuffer.x=R,this._activeBuffer.y=D),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(R,D){this._restrictCursor(),this._setCursor(this._activeBuffer.x+R,this._activeBuffer.y+D)}cursorUp(R){const D=this._activeBuffer.y-this._activeBuffer.scrollTop;return D>=0?this._moveCursor(0,-Math.min(D,R.params[0]||1)):this._moveCursor(0,-(R.params[0]||1)),!0}cursorDown(R){const D=this._activeBuffer.scrollBottom-this._activeBuffer.y;return D>=0?this._moveCursor(0,Math.min(D,R.params[0]||1)):this._moveCursor(0,R.params[0]||1),!0}cursorForward(R){return this._moveCursor(R.params[0]||1,0),!0}cursorBackward(R){return this._moveCursor(-(R.params[0]||1),0),!0}cursorNextLine(R){return this.cursorDown(R),this._activeBuffer.x=0,!0}cursorPrecedingLine(R){return this.cursorUp(R),this._activeBuffer.x=0,!0}cursorCharAbsolute(R){return this._setCursor((R.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(R){return this._setCursor(R.length>=2?(R.params[1]||1)-1:0,(R.params[0]||1)-1),!0}charPosAbsolute(R){return this._setCursor((R.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(R){return this._moveCursor(R.params[0]||1,0),!0}linePosAbsolute(R){return this._setCursor(this._activeBuffer.x,(R.params[0]||1)-1),!0}vPositionRelative(R){return this._moveCursor(0,R.params[0]||1),!0}hVPosition(R){return this.cursorPosition(R),!0}tabClear(R){const D=R.params[0];return D===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:D===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(R){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let D=R.params[0]||1;for(;D--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(R){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let D=R.params[0]||1;for(;D--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(R){const D=R.params[0];return D===1&&(this._curAttrData.bg|=536870912),D!==2&&D!==0||(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(R,D,A,B=!1,H=!1){const q=this._activeBuffer.lines.get(this._activeBuffer.ybase+R);q.replaceCells(D,A,this._activeBuffer.getNullCell(this._eraseAttrData()),this._eraseAttrData(),H),B&&(q.isWrapped=!1)}_resetBufferLine(R,D=!1){const A=this._activeBuffer.lines.get(this._activeBuffer.ybase+R);A&&(A.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),D),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+R),A.isWrapped=!1)}eraseInDisplay(R,D=!1){let A;switch(this._restrictCursor(this._bufferService.cols),R.params[0]){case 0:for(A=this._activeBuffer.y,this._dirtyRowTracker.markDirty(A),this._eraseInBufferLine(A++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,D);A=this._bufferService.cols&&(this._activeBuffer.lines.get(A+1).isWrapped=!1);A--;)this._resetBufferLine(A,D);this._dirtyRowTracker.markDirty(0);break;case 2:for(A=this._bufferService.rows,this._dirtyRowTracker.markDirty(A-1);A--;)this._resetBufferLine(A,D);this._dirtyRowTracker.markDirty(0);break;case 3:const B=this._activeBuffer.lines.length-this._bufferService.rows;B>0&&(this._activeBuffer.lines.trimStart(B),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-B,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-B,0),this._onScroll.fire(0))}return!0}eraseInLine(R,D=!1){switch(this._restrictCursor(this._bufferService.cols),R.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,D);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,D);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,D)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(R){this._restrictCursor();let D=R.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.y0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(p.C0.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(p.C0.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(R){return R.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(p.C0.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(p.C0.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(R.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(p.C0.ESC+"[>83;40003;0c")),!0}_is(R){return(this._optionsService.rawOptions.termName+"").indexOf(R)===0}setMode(R){for(let D=0;Doe?1:2,U=R.params[0];return ee=U,J=D?U===2?4:U===4?$(q.modes.insertMode):U===12?3:U===20?$(j.convertEol):0:U===1?$(A.applicationCursorKeys):U===3?j.windowOptions.setWinLines?X===80?2:X===132?1:0:0:U===6?$(A.origin):U===7?$(A.wraparound):U===8?3:U===9?$(B==="X10"):U===12?$(j.cursorBlink):U===25?$(!q.isCursorHidden):U===45?$(A.reverseWraparound):U===66?$(A.applicationKeypad):U===67?4:U===1e3?$(B==="VT200"):U===1002?$(B==="DRAG"):U===1003?$(B==="ANY"):U===1004?$(A.sendFocus):U===1005?4:U===1006?$(H==="SGR"):U===1015?4:U===1016?$(H==="SGR_PIXELS"):U===1048?1:U===47||U===1047||U===1049?$(te===T):U===2004?$(A.bracketedPasteMode):0,q.triggerDataEvent(`${p.C0.ESC}[${D?"":"?"}${ee};${J}$y`),!0;var ee,J}_updateAttrColor(R,D,A,B,H){return D===2?(R|=50331648,R&=-16777216,R|=g.AttributeData.fromColorRGB([A,B,H])):D===5&&(R&=-50331904,R|=33554432|255&A),R}_extractColor(R,D,A){const B=[0,0,-1,0,0,0];let H=0,q=0;do{if(B[q+H]=R.params[D+q],R.hasSubParams(D+q)){const G=R.getSubParams(D+q);let X=0;do B[1]===5&&(H=1),B[q+X+1+H]=G[X];while(++X=2||B[1]===2&&q+H>=5)break;B[1]&&(H=1)}while(++q+D5)&&(R=1),D.extended.underlineStyle=R,D.fg|=268435456,R===0&&(D.fg&=-268435457),D.updateExtended()}_processSGR0(R){R.fg=u.DEFAULT_ATTR_DATA.fg,R.bg=u.DEFAULT_ATTR_DATA.bg,R.extended=R.extended.clone(),R.extended.underlineStyle=0,R.extended.underlineColor&=-67108864,R.updateExtended()}charAttributes(R){if(R.length===1&&R.params[0]===0)return this._processSGR0(this._curAttrData),!0;const D=R.length;let A;const B=this._curAttrData;for(let H=0;H=30&&A<=37?(B.fg&=-50331904,B.fg|=16777216|A-30):A>=40&&A<=47?(B.bg&=-50331904,B.bg|=16777216|A-40):A>=90&&A<=97?(B.fg&=-50331904,B.fg|=16777224|A-90):A>=100&&A<=107?(B.bg&=-50331904,B.bg|=16777224|A-100):A===0?this._processSGR0(B):A===1?B.fg|=134217728:A===3?B.bg|=67108864:A===4?(B.fg|=268435456,this._processUnderline(R.hasSubParams(H)?R.getSubParams(H)[0]:1,B)):A===5?B.fg|=536870912:A===7?B.fg|=67108864:A===8?B.fg|=1073741824:A===9?B.fg|=2147483648:A===2?B.bg|=134217728:A===21?this._processUnderline(2,B):A===22?(B.fg&=-134217729,B.bg&=-134217729):A===23?B.bg&=-67108865:A===24?(B.fg&=-268435457,this._processUnderline(0,B)):A===25?B.fg&=-536870913:A===27?B.fg&=-67108865:A===28?B.fg&=-1073741825:A===29?B.fg&=2147483647:A===39?(B.fg&=-67108864,B.fg|=16777215&u.DEFAULT_ATTR_DATA.fg):A===49?(B.bg&=-67108864,B.bg|=16777215&u.DEFAULT_ATTR_DATA.bg):A===38||A===48||A===58?H+=this._extractColor(R,H,B):A===53?B.bg|=1073741824:A===55?B.bg&=-1073741825:A===59?(B.extended=B.extended.clone(),B.extended.underlineColor=-1,B.updateExtended()):A===100?(B.fg&=-67108864,B.fg|=16777215&u.DEFAULT_ATTR_DATA.fg,B.bg&=-67108864,B.bg|=16777215&u.DEFAULT_ATTR_DATA.bg):this._logService.debug("Unknown SGR attribute: %d.",A);return!0}deviceStatus(R){switch(R.params[0]){case 5:this._coreService.triggerDataEvent(`${p.C0.ESC}[0n`);break;case 6:const D=this._activeBuffer.y+1,A=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${p.C0.ESC}[${D};${A}R`)}return!0}deviceStatusPrivate(R){if(R.params[0]===6){const D=this._activeBuffer.y+1,A=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${p.C0.ESC}[?${D};${A}R`)}return!0}softReset(R){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=u.DEFAULT_ATTR_DATA.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(R){const D=R.params[0]||1;switch(D){case 1:case 2:this._optionsService.options.cursorStyle="block";break;case 3:case 4:this._optionsService.options.cursorStyle="underline";break;case 5:case 6:this._optionsService.options.cursorStyle="bar"}const A=D%2==1;return this._optionsService.options.cursorBlink=A,!0}setScrollRegion(R){const D=R.params[0]||1;let A;return(R.length<2||(A=R.params[1])>this._bufferService.rows||A===0)&&(A=this._bufferService.rows),A>D&&(this._activeBuffer.scrollTop=D-1,this._activeBuffer.scrollBottom=A-1,this._setCursor(0,0)),!0}windowOptions(R){if(!N(R.params[0],this._optionsService.rawOptions.windowOptions))return!0;const D=R.length>1?R.params[1]:0;switch(R.params[0]){case 14:D!==2&&this._onRequestWindowsOptionsReport.fire(O.GET_WIN_SIZE_PIXELS);break;case 16:this._onRequestWindowsOptionsReport.fire(O.GET_CELL_SIZE_PIXELS);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${p.C0.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:D!==0&&D!==2||(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>10&&this._windowTitleStack.shift()),D!==0&&D!==1||(this._iconNameStack.push(this._iconName),this._iconNameStack.length>10&&this._iconNameStack.shift());break;case 23:D!==0&&D!==2||this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),D!==0&&D!==1||this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(R){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(R){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(R){return this._windowTitle=R,this._onTitleChange.fire(R),!0}setIconName(R){return this._iconName=R,!0}setOrReportIndexedColor(R){const D=[],A=R.split(";");for(;A.length>1;){const B=A.shift(),H=A.shift();if(/^\d+$/.exec(B)){const q=parseInt(B);if(W(q))if(H==="?")D.push({type:0,index:q});else{const G=(0,w.parseColor)(H);G&&D.push({type:1,index:q,color:G})}}}return D.length&&this._onColor.fire(D),!0}setHyperlink(R){const D=R.split(";");return!(D.length<2)&&(D[1]?this._createHyperlink(D[0],D[1]):!D[0]&&this._finishHyperlink())}_createHyperlink(R,D){this._getCurrentLinkId()&&this._finishHyperlink();const A=R.split(":");let B;const H=A.findIndex(q=>q.startsWith("id="));return H!==-1&&(B=A[H].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:B,uri:D}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(R,D){const A=R.split(";");for(let B=0;B=this._specialColors.length);++B,++D)if(A[B]==="?")this._onColor.fire([{type:0,index:this._specialColors[D]}]);else{const H=(0,w.parseColor)(A[B]);H&&this._onColor.fire([{type:1,index:this._specialColors[D],color:H}])}return!0}setOrReportFgColor(R){return this._setOrReportSpecialColor(R,0)}setOrReportBgColor(R){return this._setOrReportSpecialColor(R,1)}setOrReportCursorColor(R){return this._setOrReportSpecialColor(R,2)}restoreIndexedColor(R){if(!R)return this._onColor.fire([{type:2}]),!0;const D=[],A=R.split(";");for(let B=0;B=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){const R=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,R,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=u.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=u.DEFAULT_ATTR_DATA.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=67108863&this._curAttrData.bg,this._eraseAttrDataInternal}setgLevel(R){return this._charsetService.setgLevel(R),!0}screenAlignmentPattern(){const R=new d.CellData;R.content=4194373,R.fg=this._curAttrData.fg,R.bg=this._curAttrData.bg,this._setCursor(0,0);for(let D=0;D(this._coreService.triggerDataEvent(`${p.C0.ESC}${H}${p.C0.ESC}\\`),!0))(R==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:R==='"p'?'P1$r61;1"p':R==="r"?`P1$r${A.scrollTop+1};${A.scrollBottom+1}r`:R==="m"?"P1$r0m":R===" q"?`P1$r${{block:2,underline:4,bar:6}[B.cursorStyle]-(B.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(R,D){this._dirtyRowTracker.markRangeDirty(R,D)}}n.InputHandler=F;let z=class{constructor(V){this._bufferService=V,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(V){Vthis.end&&(this.end=V)}markRangeDirty(V,R){V>R&&(P=V,V=R,R=P),Vthis.end&&(this.end=R)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};function W(V){return 0<=V&&V<256}z=f([m(0,x.IBufferService)],z)},844:(c,n)=>{function a(f){for(const m of f)m.dispose();f.length=0}Object.defineProperty(n,"__esModule",{value:!0}),n.getDisposeArrayDisposable=n.disposeArray=n.toDisposable=n.MutableDisposable=n.Disposable=void 0,n.Disposable=class{constructor(){this._disposables=[],this._isDisposed=!1}dispose(){this._isDisposed=!0;for(const f of this._disposables)f.dispose();this._disposables.length=0}register(f){return this._disposables.push(f),f}unregister(f){const m=this._disposables.indexOf(f);m!==-1&&this._disposables.splice(m,1)}},n.MutableDisposable=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(f){var m;this._isDisposed||f===this._value||((m=this._value)===null||m===void 0||m.dispose(),this._value=f)}clear(){this.value=void 0}dispose(){var f;this._isDisposed=!0,(f=this._value)===null||f===void 0||f.dispose(),this._value=void 0}},n.toDisposable=function(f){return{dispose:f}},n.disposeArray=a,n.getDisposeArrayDisposable=function(f){return{dispose:()=>a(f)}}},1505:(c,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.FourKeyMap=n.TwoKeyMap=void 0;class a{constructor(){this._data={}}set(m,p,_){this._data[m]||(this._data[m]={}),this._data[m][p]=_}get(m,p){return this._data[m]?this._data[m][p]:void 0}clear(){this._data={}}}n.TwoKeyMap=a,n.FourKeyMap=class{constructor(){this._data=new a}set(f,m,p,_,S){this._data.get(f,m)||this._data.set(f,m,new a),this._data.get(f,m).set(p,_,S)}get(f,m,p,_){var S;return(S=this._data.get(f,m))===null||S===void 0?void 0:S.get(p,_)}clear(){this._data.clear()}}},6114:(c,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.isChromeOS=n.isLinux=n.isWindows=n.isIphone=n.isIpad=n.isMac=n.getSafariVersion=n.isSafari=n.isLegacyEdge=n.isFirefox=n.isNode=void 0,n.isNode=typeof navigator>"u";const a=n.isNode?"node":navigator.userAgent,f=n.isNode?"node":navigator.platform;n.isFirefox=a.includes("Firefox"),n.isLegacyEdge=a.includes("Edge"),n.isSafari=/^((?!chrome|android).)*safari/i.test(a),n.getSafariVersion=function(){if(!n.isSafari)return 0;const m=a.match(/Version\/(\d+)/);return m===null||m.length<2?0:parseInt(m[1])},n.isMac=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(f),n.isIpad=f==="iPad",n.isIphone=f==="iPhone",n.isWindows=["Windows","Win16","Win32","WinCE"].includes(f),n.isLinux=f.indexOf("Linux")>=0,n.isChromeOS=/\bCrOS\b/.test(a)},6106:(c,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.SortedList=void 0;let a=0;n.SortedList=class{constructor(f){this._getKey=f,this._array=[]}clear(){this._array.length=0}insert(f){this._array.length!==0?(a=this._search(this._getKey(f)),this._array.splice(a,0,f)):this._array.push(f)}delete(f){if(this._array.length===0)return!1;const m=this._getKey(f);if(m===void 0||(a=this._search(m),a===-1)||this._getKey(this._array[a])!==m)return!1;do if(this._array[a]===f)return this._array.splice(a,1),!0;while(++a=this._array.length)&&this._getKey(this._array[a])===f))do yield this._array[a];while(++a=this._array.length)&&this._getKey(this._array[a])===f))do m(this._array[a]);while(++a=m;){let _=m+p>>1;const S=this._getKey(this._array[_]);if(S>f)p=_-1;else{if(!(S0&&this._getKey(this._array[_-1])===f;)_--;return _}m=_+1}}return m}}},7226:(c,n,a)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.DebouncedIdleTask=n.IdleTaskQueue=n.PriorityTaskQueue=void 0;const f=a(6114);class m{constructor(){this._tasks=[],this._i=0}enqueue(S){this._tasks.push(S),this._start()}flush(){for(;this._ih)return u-b<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(u-b))}ms`),void this._start();u=h}this.clear()}}class p extends m{_requestCallback(S){return setTimeout(()=>S(this._createDeadline(16)))}_cancelCallback(S){clearTimeout(S)}_createDeadline(S){const b=Date.now()+S;return{timeRemaining:()=>Math.max(0,b-Date.now())}}}n.PriorityTaskQueue=p,n.IdleTaskQueue=!f.isNode&&"requestIdleCallback"in window?class extends m{_requestCallback(_){return requestIdleCallback(_)}_cancelCallback(_){cancelIdleCallback(_)}}:p,n.DebouncedIdleTask=class{constructor(){this._queue=new n.IdleTaskQueue}set(_){this._queue.clear(),this._queue.enqueue(_)}flush(){this._queue.flush()}}},9282:(c,n,a)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.updateWindowsModeWrappedState=void 0;const f=a(643);n.updateWindowsModeWrappedState=function(m){const p=m.buffer.lines.get(m.buffer.ybase+m.buffer.y-1),_=p==null?void 0:p.get(m.cols-1),S=m.buffer.lines.get(m.buffer.ybase+m.buffer.y);S&&_&&(S.isWrapped=_[f.CHAR_DATA_CODE_INDEX]!==f.NULL_CELL_CODE&&_[f.CHAR_DATA_CODE_INDEX]!==f.WHITESPACE_CELL_CODE)}},3734:(c,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.ExtendedAttrs=n.AttributeData=void 0;class a{constructor(){this.fg=0,this.bg=0,this.extended=new f}static toColorRGB(p){return[p>>>16&255,p>>>8&255,255&p]}static fromColorRGB(p){return(255&p[0])<<16|(255&p[1])<<8|255&p[2]}clone(){const p=new a;return p.fg=this.fg,p.bg=this.bg,p.extended=this.extended.clone(),p}isInverse(){return 67108864&this.fg}isBold(){return 134217728&this.fg}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:268435456&this.fg}isBlink(){return 536870912&this.fg}isInvisible(){return 1073741824&this.fg}isItalic(){return 67108864&this.bg}isDim(){return 134217728&this.bg}isStrikethrough(){return 2147483648&this.fg}isProtected(){return 536870912&this.bg}isOverline(){return 1073741824&this.bg}getFgColorMode(){return 50331648&this.fg}getBgColorMode(){return 50331648&this.bg}isFgRGB(){return(50331648&this.fg)==50331648}isBgRGB(){return(50331648&this.bg)==50331648}isFgPalette(){return(50331648&this.fg)==16777216||(50331648&this.fg)==33554432}isBgPalette(){return(50331648&this.bg)==16777216||(50331648&this.bg)==33554432}isFgDefault(){return(50331648&this.fg)==0}isBgDefault(){return(50331648&this.bg)==0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(50331648&this.fg){case 16777216:case 33554432:return 255&this.fg;case 50331648:return 16777215&this.fg;default:return-1}}getBgColor(){switch(50331648&this.bg){case 16777216:case 33554432:return 255&this.bg;case 50331648:return 16777215&this.bg;default:return-1}}hasExtendedAttrs(){return 268435456&this.bg}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(268435456&this.bg&&~this.extended.underlineColor)switch(50331648&this.extended.underlineColor){case 16777216:case 33554432:return 255&this.extended.underlineColor;case 50331648:return 16777215&this.extended.underlineColor;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return 268435456&this.bg&&~this.extended.underlineColor?50331648&this.extended.underlineColor:this.getFgColorMode()}isUnderlineColorRGB(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==50331648:this.isFgRGB()}isUnderlineColorPalette(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==16777216||(50331648&this.extended.underlineColor)==33554432:this.isFgPalette()}isUnderlineColorDefault(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==0:this.isFgDefault()}getUnderlineStyle(){return 268435456&this.fg?268435456&this.bg?this.extended.underlineStyle:1:0}}n.AttributeData=a;class f{get ext(){return this._urlId?-469762049&this._ext|this.underlineStyle<<26:this._ext}set ext(p){this._ext=p}get underlineStyle(){return this._urlId?5:(469762048&this._ext)>>26}set underlineStyle(p){this._ext&=-469762049,this._ext|=p<<26&469762048}get underlineColor(){return 67108863&this._ext}set underlineColor(p){this._ext&=-67108864,this._ext|=67108863&p}get urlId(){return this._urlId}set urlId(p){this._urlId=p}constructor(p=0,_=0){this._ext=0,this._urlId=0,this._ext=p,this._urlId=_}clone(){return new f(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}}n.ExtendedAttrs=f},9092:(c,n,a)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Buffer=n.MAX_BUFFER_SIZE=void 0;const f=a(6349),m=a(7226),p=a(3734),_=a(8437),S=a(4634),b=a(511),y=a(643),u=a(4863),h=a(7116);n.MAX_BUFFER_SIZE=4294967295,n.Buffer=class{constructor(l,d,g){this._hasScrollback=l,this._optionsService=d,this._bufferService=g,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=_.DEFAULT_ATTR_DATA.clone(),this.savedCharset=h.DEFAULT_CHARSET,this.markers=[],this._nullCell=b.CellData.fromCharData([0,y.NULL_CELL_CHAR,y.NULL_CELL_WIDTH,y.NULL_CELL_CODE]),this._whitespaceCell=b.CellData.fromCharData([0,y.WHITESPACE_CELL_CHAR,y.WHITESPACE_CELL_WIDTH,y.WHITESPACE_CELL_CODE]),this._isClearing=!1,this._memoryCleanupQueue=new m.IdleTaskQueue,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new f.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(l){return l?(this._nullCell.fg=l.fg,this._nullCell.bg=l.bg,this._nullCell.extended=l.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new p.ExtendedAttrs),this._nullCell}getWhitespaceCell(l){return l?(this._whitespaceCell.fg=l.fg,this._whitespaceCell.bg=l.bg,this._whitespaceCell.extended=l.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new p.ExtendedAttrs),this._whitespaceCell}getBlankLine(l,d){return new _.BufferLine(this._bufferService.cols,this.getNullCell(l),d)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){const l=this.ybase+this.y-this.ydisp;return l>=0&&ln.MAX_BUFFER_SIZE?n.MAX_BUFFER_SIZE:d}fillViewportRows(l){if(this.lines.length===0){l===void 0&&(l=_.DEFAULT_ATTR_DATA);let d=this._rows;for(;d--;)this.lines.push(this.getBlankLine(l))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new f.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(l,d){const g=this.getNullCell(_.DEFAULT_ATTR_DATA);let x=0;const C=this._getCorrectBufferLength(d);if(C>this.lines.maxLength&&(this.lines.maxLength=C),this.lines.length>0){if(this._cols0&&this.lines.length<=this.ybase+this.y+k+1?(this.ybase--,k++,this.ydisp>0&&this.ydisp--):this.lines.push(new _.BufferLine(l,g)));else for(let w=this._rows;w>d;w--)this.lines.length>d+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(C0&&(this.lines.trimStart(w),this.ybase=Math.max(this.ybase-w,0),this.ydisp=Math.max(this.ydisp-w,0),this.savedY=Math.max(this.savedY-w,0)),this.lines.maxLength=C}this.x=Math.min(this.x,l-1),this.y=Math.min(this.y,d-1),k&&(this.y+=k),this.savedX=Math.min(this.savedX,l-1),this.scrollTop=0}if(this.scrollBottom=d-1,this._isReflowEnabled&&(this._reflow(l,d),this._cols>l))for(let k=0;k.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let l=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,l=!1);let d=0;for(;this._memoryCleanupPosition100)return!0;return l}get _isReflowEnabled(){const l=this._optionsService.rawOptions.windowsPty;return l&&l.buildNumber?this._hasScrollback&&l.backend==="conpty"&&l.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(l,d){this._cols!==l&&(l>this._cols?this._reflowLarger(l,d):this._reflowSmaller(l,d))}_reflowLarger(l,d){const g=(0,S.reflowLargerGetLinesToRemove)(this.lines,this._cols,l,this.ybase+this.y,this.getNullCell(_.DEFAULT_ATTR_DATA));if(g.length>0){const x=(0,S.reflowLargerCreateNewLayout)(this.lines,g);(0,S.reflowLargerApplyNewLayout)(this.lines,x.layout),this._reflowLargerAdjustViewport(l,d,x.countRemoved)}}_reflowLargerAdjustViewport(l,d,g){const x=this.getNullCell(_.DEFAULT_ATTR_DATA);let C=g;for(;C-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length=0;k--){let w=this.lines.get(k);if(!w||!w.isWrapped&&w.getTrimmedLength()<=l)continue;const E=[w];for(;w.isWrapped&&k>0;)w=this.lines.get(--k),E.unshift(w);const L=this.ybase+this.y;if(L>=k&&L0&&(x.push({start:k+E.length+C,newLines:z}),C+=z.length),E.push(...z);let W=O.length-1,V=O[W];V===0&&(W--,V=O[W]);let R=E.length-P-1,D=N;for(;R>=0;){const B=Math.min(D,V);if(E[W]===void 0)break;if(E[W].copyCellsFrom(E[R],D-B,V-B,B,!0),V-=B,V===0&&(W--,V=O[W]),D-=B,D===0){R--;const H=Math.max(R,0);D=(0,S.getWrappedLineTrimmedLength)(E,H,this._cols)}}for(let B=0;B0;)this.ybase===0?this.y0){const k=[],w=[];for(let W=0;W=0;W--)if(O&&O.start>L+P){for(let V=O.newLines.length-1;V>=0;V--)this.lines.set(W--,O.newLines[V]);W++,k.push({index:L+1,amount:O.newLines.length}),P+=O.newLines.length,O=x[++N]}else this.lines.set(W,w[L--]);let F=0;for(let W=k.length-1;W>=0;W--)k[W].index+=F,this.lines.onInsertEmitter.fire(k[W]),F+=k[W].amount;const z=Math.max(0,E+C-this.lines.maxLength);z>0&&this.lines.onTrimEmitter.fire(z)}}translateBufferLineToString(l,d,g=0,x){const C=this.lines.get(l);return C?C.translateToString(d,g,x):""}getWrappedRangeForLine(l){let d=l,g=l;for(;d>0&&this.lines.get(d).isWrapped;)d--;for(;g+10;);return l>=this._cols?this._cols-1:l<0?0:l}nextStop(l){for(l==null&&(l=this.x);!this.tabs[++l]&&l=this._cols?this._cols-1:l<0?0:l}clearMarkers(l){this._isClearing=!0;for(let d=0;d{d.line-=g,d.line<0&&d.dispose()})),d.register(this.lines.onInsert(g=>{d.line>=g.index&&(d.line+=g.amount)})),d.register(this.lines.onDelete(g=>{d.line>=g.index&&d.lineg.index&&(d.line-=g.amount)})),d.register(d.onDispose(()=>this._removeMarker(d))),d}_removeMarker(l){this._isClearing||this.markers.splice(this.markers.indexOf(l),1)}}},8437:(c,n,a)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.BufferLine=n.DEFAULT_ATTR_DATA=void 0;const f=a(3734),m=a(511),p=a(643),_=a(482);n.DEFAULT_ATTR_DATA=Object.freeze(new f.AttributeData);let S=0;class b{constructor(u,h,l=!1){this.isWrapped=l,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(3*u);const d=h||m.CellData.fromCharData([0,p.NULL_CELL_CHAR,p.NULL_CELL_WIDTH,p.NULL_CELL_CODE]);for(let g=0;g>22,2097152&h?this._combined[u].charCodeAt(this._combined[u].length-1):l]}set(u,h){this._data[3*u+1]=h[p.CHAR_DATA_ATTR_INDEX],h[p.CHAR_DATA_CHAR_INDEX].length>1?(this._combined[u]=h[1],this._data[3*u+0]=2097152|u|h[p.CHAR_DATA_WIDTH_INDEX]<<22):this._data[3*u+0]=h[p.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|h[p.CHAR_DATA_WIDTH_INDEX]<<22}getWidth(u){return this._data[3*u+0]>>22}hasWidth(u){return 12582912&this._data[3*u+0]}getFg(u){return this._data[3*u+1]}getBg(u){return this._data[3*u+2]}hasContent(u){return 4194303&this._data[3*u+0]}getCodePoint(u){const h=this._data[3*u+0];return 2097152&h?this._combined[u].charCodeAt(this._combined[u].length-1):2097151&h}isCombined(u){return 2097152&this._data[3*u+0]}getString(u){const h=this._data[3*u+0];return 2097152&h?this._combined[u]:2097151&h?(0,_.stringFromCodePoint)(2097151&h):""}isProtected(u){return 536870912&this._data[3*u+2]}loadCell(u,h){return S=3*u,h.content=this._data[S+0],h.fg=this._data[S+1],h.bg=this._data[S+2],2097152&h.content&&(h.combinedData=this._combined[u]),268435456&h.bg&&(h.extended=this._extendedAttrs[u]),h}setCell(u,h){2097152&h.content&&(this._combined[u]=h.combinedData),268435456&h.bg&&(this._extendedAttrs[u]=h.extended),this._data[3*u+0]=h.content,this._data[3*u+1]=h.fg,this._data[3*u+2]=h.bg}setCellFromCodePoint(u,h,l,d,g,x){268435456&g&&(this._extendedAttrs[u]=x),this._data[3*u+0]=h|l<<22,this._data[3*u+1]=d,this._data[3*u+2]=g}addCodepointToCell(u,h){let l=this._data[3*u+0];2097152&l?this._combined[u]+=(0,_.stringFromCodePoint)(h):(2097151&l?(this._combined[u]=(0,_.stringFromCodePoint)(2097151&l)+(0,_.stringFromCodePoint)(h),l&=-2097152,l|=2097152):l=h|4194304,this._data[3*u+0]=l)}insertCells(u,h,l,d){if((u%=this.length)&&this.getWidth(u-1)===2&&this.setCellFromCodePoint(u-1,0,1,(d==null?void 0:d.fg)||0,(d==null?void 0:d.bg)||0,(d==null?void 0:d.extended)||new f.ExtendedAttrs),h=0;--x)this.setCell(u+h+x,this.loadCell(u+x,g));for(let x=0;xthis.length){if(this._data.buffer.byteLength>=4*l)this._data=new Uint32Array(this._data.buffer,0,l);else{const d=new Uint32Array(l);d.set(this._data),this._data=d}for(let d=this.length;d=u&&delete this._combined[C]}const g=Object.keys(this._extendedAttrs);for(let x=0;x=u&&delete this._extendedAttrs[C]}}return this.length=u,4*l*2=0;--u)if(4194303&this._data[3*u+0])return u+(this._data[3*u+0]>>22);return 0}getNoBgTrimmedLength(){for(let u=this.length-1;u>=0;--u)if(4194303&this._data[3*u+0]||50331648&this._data[3*u+2])return u+(this._data[3*u+0]>>22);return 0}copyCellsFrom(u,h,l,d,g){const x=u._data;if(g)for(let k=d-1;k>=0;k--){for(let w=0;w<3;w++)this._data[3*(l+k)+w]=x[3*(h+k)+w];268435456&x[3*(h+k)+2]&&(this._extendedAttrs[l+k]=u._extendedAttrs[h+k])}else for(let k=0;k=h&&(this._combined[w-h+l]=u._combined[w])}}translateToString(u=!1,h=0,l=this.length){u&&(l=Math.min(l,this.getTrimmedLength()));let d="";for(;h>22||1}return d}}n.BufferLine=b},4841:(c,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.getRangeLength=void 0,n.getRangeLength=function(a,f){if(a.start.y>a.end.y)throw new Error(`Buffer range end (${a.end.x}, ${a.end.y}) cannot be before start (${a.start.x}, ${a.start.y})`);return f*(a.end.y-a.start.y)+(a.end.x-a.start.x+1)}},4634:(c,n)=>{function a(f,m,p){if(m===f.length-1)return f[m].getTrimmedLength();const _=!f[m].hasContent(p-1)&&f[m].getWidth(p-1)===1,S=f[m+1].getWidth(0)===2;return _&&S?p-1:p}Object.defineProperty(n,"__esModule",{value:!0}),n.getWrappedLineTrimmedLength=n.reflowSmallerGetNewLineLengths=n.reflowLargerApplyNewLayout=n.reflowLargerCreateNewLayout=n.reflowLargerGetLinesToRemove=void 0,n.reflowLargerGetLinesToRemove=function(f,m,p,_,S){const b=[];for(let y=0;y=y&&_0&&(w>d||l[w].getTrimmedLength()===0);w--)k++;k>0&&(b.push(y+l.length-k),b.push(k)),y+=l.length-1}return b},n.reflowLargerCreateNewLayout=function(f,m){const p=[];let _=0,S=m[_],b=0;for(let y=0;ya(f,l,m)).reduce((h,l)=>h+l);let b=0,y=0,u=0;for(;uh&&(b-=h,y++);const l=f[y].getWidth(b-1)===2;l&&b--;const d=l?p-1:p;_.push(d),u+=d}return _},n.getWrappedLineTrimmedLength=a},5295:(c,n,a)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.BufferSet=void 0;const f=a(8460),m=a(844),p=a(9092);class _ extends m.Disposable{constructor(b,y){super(),this._optionsService=b,this._bufferService=y,this._onBufferActivate=this.register(new f.EventEmitter),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this.register(this._optionsService.onSpecificOptionChange("scrollback",()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this.register(this._optionsService.onSpecificOptionChange("tabStopWidth",()=>this.setupTabStops()))}reset(){this._normal=new p.Buffer(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new p.Buffer(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(b){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(b),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(b,y){this._normal.resize(b,y),this._alt.resize(b,y),this.setupTabStops(b)}setupTabStops(b){this._normal.setupTabStops(b),this._alt.setupTabStops(b)}}n.BufferSet=_},511:(c,n,a)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.CellData=void 0;const f=a(482),m=a(643),p=a(3734);class _ extends p.AttributeData{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new p.ExtendedAttrs,this.combinedData=""}static fromCharData(b){const y=new _;return y.setFromCharData(b),y}isCombined(){return 2097152&this.content}getWidth(){return this.content>>22}getChars(){return 2097152&this.content?this.combinedData:2097151&this.content?(0,f.stringFromCodePoint)(2097151&this.content):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):2097151&this.content}setFromCharData(b){this.fg=b[m.CHAR_DATA_ATTR_INDEX],this.bg=0;let y=!1;if(b[m.CHAR_DATA_CHAR_INDEX].length>2)y=!0;else if(b[m.CHAR_DATA_CHAR_INDEX].length===2){const u=b[m.CHAR_DATA_CHAR_INDEX].charCodeAt(0);if(55296<=u&&u<=56319){const h=b[m.CHAR_DATA_CHAR_INDEX].charCodeAt(1);56320<=h&&h<=57343?this.content=1024*(u-55296)+h-56320+65536|b[m.CHAR_DATA_WIDTH_INDEX]<<22:y=!0}else y=!0}else this.content=b[m.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|b[m.CHAR_DATA_WIDTH_INDEX]<<22;y&&(this.combinedData=b[m.CHAR_DATA_CHAR_INDEX],this.content=2097152|b[m.CHAR_DATA_WIDTH_INDEX]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}n.CellData=_},643:(c,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.WHITESPACE_CELL_CODE=n.WHITESPACE_CELL_WIDTH=n.WHITESPACE_CELL_CHAR=n.NULL_CELL_CODE=n.NULL_CELL_WIDTH=n.NULL_CELL_CHAR=n.CHAR_DATA_CODE_INDEX=n.CHAR_DATA_WIDTH_INDEX=n.CHAR_DATA_CHAR_INDEX=n.CHAR_DATA_ATTR_INDEX=n.DEFAULT_EXT=n.DEFAULT_ATTR=n.DEFAULT_COLOR=void 0,n.DEFAULT_COLOR=0,n.DEFAULT_ATTR=256|n.DEFAULT_COLOR<<9,n.DEFAULT_EXT=0,n.CHAR_DATA_ATTR_INDEX=0,n.CHAR_DATA_CHAR_INDEX=1,n.CHAR_DATA_WIDTH_INDEX=2,n.CHAR_DATA_CODE_INDEX=3,n.NULL_CELL_CHAR="",n.NULL_CELL_WIDTH=1,n.NULL_CELL_CODE=0,n.WHITESPACE_CELL_CHAR=" ",n.WHITESPACE_CELL_WIDTH=1,n.WHITESPACE_CELL_CODE=32},4863:(c,n,a)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Marker=void 0;const f=a(8460),m=a(844);class p{get id(){return this._id}constructor(S){this.line=S,this.isDisposed=!1,this._disposables=[],this._id=p._nextId++,this._onDispose=this.register(new f.EventEmitter),this.onDispose=this._onDispose.event}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),(0,m.disposeArray)(this._disposables),this._disposables.length=0)}register(S){return this._disposables.push(S),S}}n.Marker=p,p._nextId=1},7116:(c,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.DEFAULT_CHARSET=n.CHARSETS=void 0,n.CHARSETS={},n.DEFAULT_CHARSET=n.CHARSETS.B,n.CHARSETS[0]={"`":"◆",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:"≥","{":"π","|":"≠","}":"£","~":"·"},n.CHARSETS.A={"#":"£"},n.CHARSETS.B=void 0,n.CHARSETS[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"},n.CHARSETS.C=n.CHARSETS[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},n.CHARSETS.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"},n.CHARSETS.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"},n.CHARSETS.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"},n.CHARSETS.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"},n.CHARSETS.E=n.CHARSETS[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"},n.CHARSETS.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"},n.CHARSETS.H=n.CHARSETS[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},n.CHARSETS["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"}},2584:(c,n)=>{var a,f,m;Object.defineProperty(n,"__esModule",{value:!0}),n.C1_ESCAPED=n.C1=n.C0=void 0,function(p){p.NUL="\0",p.SOH="",p.STX="",p.ETX="",p.EOT="",p.ENQ="",p.ACK="",p.BEL="\x07",p.BS="\b",p.HT=" ",p.LF=` +`,p.VT="\v",p.FF="\f",p.CR="\r",p.SO="",p.SI="",p.DLE="",p.DC1="",p.DC2="",p.DC3="",p.DC4="",p.NAK="",p.SYN="",p.ETB="",p.CAN="",p.EM="",p.SUB="",p.ESC="\x1B",p.FS="",p.GS="",p.RS="",p.US="",p.SP=" ",p.DEL=""}(a||(n.C0=a={})),function(p){p.PAD="€",p.HOP="",p.BPH="‚",p.NBH="ƒ",p.IND="„",p.NEL="…",p.SSA="†",p.ESA="‡",p.HTS="ˆ",p.HTJ="‰",p.VTS="Š",p.PLD="‹",p.PLU="Œ",p.RI="",p.SS2="Ž",p.SS3="",p.DCS="",p.PU1="‘",p.PU2="’",p.STS="“",p.CCH="”",p.MW="•",p.SPA="–",p.EPA="—",p.SOS="˜",p.SGCI="™",p.SCI="š",p.CSI="›",p.ST="œ",p.OSC="",p.PM="ž",p.APC="Ÿ"}(f||(n.C1=f={})),function(p){p.ST=`${a.ESC}\\`}(m||(n.C1_ESCAPED=m={}))},7399:(c,n,a)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.evaluateKeyboardEvent=void 0;const f=a(2584),m={48:["0",")"],49:["1","!"],50:["2","@"],51:["3","#"],52:["4","$"],53:["5","%"],54:["6","^"],55:["7","&"],56:["8","*"],57:["9","("],186:[";",":"],187:["=","+"],188:[",","<"],189:["-","_"],190:[".",">"],191:["/","?"],192:["`","~"],219:["[","{"],220:["\\","|"],221:["]","}"],222:["'",'"']};n.evaluateKeyboardEvent=function(p,_,S,b){const y={type:0,cancel:!1,key:void 0},u=(p.shiftKey?1:0)|(p.altKey?2:0)|(p.ctrlKey?4:0)|(p.metaKey?8:0);switch(p.keyCode){case 0:p.key==="UIKeyInputUpArrow"?y.key=_?f.C0.ESC+"OA":f.C0.ESC+"[A":p.key==="UIKeyInputLeftArrow"?y.key=_?f.C0.ESC+"OD":f.C0.ESC+"[D":p.key==="UIKeyInputRightArrow"?y.key=_?f.C0.ESC+"OC":f.C0.ESC+"[C":p.key==="UIKeyInputDownArrow"&&(y.key=_?f.C0.ESC+"OB":f.C0.ESC+"[B");break;case 8:if(p.altKey){y.key=f.C0.ESC+f.C0.DEL;break}y.key=f.C0.DEL;break;case 9:if(p.shiftKey){y.key=f.C0.ESC+"[Z";break}y.key=f.C0.HT,y.cancel=!0;break;case 13:y.key=p.altKey?f.C0.ESC+f.C0.CR:f.C0.CR,y.cancel=!0;break;case 27:y.key=f.C0.ESC,p.altKey&&(y.key=f.C0.ESC+f.C0.ESC),y.cancel=!0;break;case 37:if(p.metaKey)break;u?(y.key=f.C0.ESC+"[1;"+(u+1)+"D",y.key===f.C0.ESC+"[1;3D"&&(y.key=f.C0.ESC+(S?"b":"[1;5D"))):y.key=_?f.C0.ESC+"OD":f.C0.ESC+"[D";break;case 39:if(p.metaKey)break;u?(y.key=f.C0.ESC+"[1;"+(u+1)+"C",y.key===f.C0.ESC+"[1;3C"&&(y.key=f.C0.ESC+(S?"f":"[1;5C"))):y.key=_?f.C0.ESC+"OC":f.C0.ESC+"[C";break;case 38:if(p.metaKey)break;u?(y.key=f.C0.ESC+"[1;"+(u+1)+"A",S||y.key!==f.C0.ESC+"[1;3A"||(y.key=f.C0.ESC+"[1;5A")):y.key=_?f.C0.ESC+"OA":f.C0.ESC+"[A";break;case 40:if(p.metaKey)break;u?(y.key=f.C0.ESC+"[1;"+(u+1)+"B",S||y.key!==f.C0.ESC+"[1;3B"||(y.key=f.C0.ESC+"[1;5B")):y.key=_?f.C0.ESC+"OB":f.C0.ESC+"[B";break;case 45:p.shiftKey||p.ctrlKey||(y.key=f.C0.ESC+"[2~");break;case 46:y.key=u?f.C0.ESC+"[3;"+(u+1)+"~":f.C0.ESC+"[3~";break;case 36:y.key=u?f.C0.ESC+"[1;"+(u+1)+"H":_?f.C0.ESC+"OH":f.C0.ESC+"[H";break;case 35:y.key=u?f.C0.ESC+"[1;"+(u+1)+"F":_?f.C0.ESC+"OF":f.C0.ESC+"[F";break;case 33:p.shiftKey?y.type=2:p.ctrlKey?y.key=f.C0.ESC+"[5;"+(u+1)+"~":y.key=f.C0.ESC+"[5~";break;case 34:p.shiftKey?y.type=3:p.ctrlKey?y.key=f.C0.ESC+"[6;"+(u+1)+"~":y.key=f.C0.ESC+"[6~";break;case 112:y.key=u?f.C0.ESC+"[1;"+(u+1)+"P":f.C0.ESC+"OP";break;case 113:y.key=u?f.C0.ESC+"[1;"+(u+1)+"Q":f.C0.ESC+"OQ";break;case 114:y.key=u?f.C0.ESC+"[1;"+(u+1)+"R":f.C0.ESC+"OR";break;case 115:y.key=u?f.C0.ESC+"[1;"+(u+1)+"S":f.C0.ESC+"OS";break;case 116:y.key=u?f.C0.ESC+"[15;"+(u+1)+"~":f.C0.ESC+"[15~";break;case 117:y.key=u?f.C0.ESC+"[17;"+(u+1)+"~":f.C0.ESC+"[17~";break;case 118:y.key=u?f.C0.ESC+"[18;"+(u+1)+"~":f.C0.ESC+"[18~";break;case 119:y.key=u?f.C0.ESC+"[19;"+(u+1)+"~":f.C0.ESC+"[19~";break;case 120:y.key=u?f.C0.ESC+"[20;"+(u+1)+"~":f.C0.ESC+"[20~";break;case 121:y.key=u?f.C0.ESC+"[21;"+(u+1)+"~":f.C0.ESC+"[21~";break;case 122:y.key=u?f.C0.ESC+"[23;"+(u+1)+"~":f.C0.ESC+"[23~";break;case 123:y.key=u?f.C0.ESC+"[24;"+(u+1)+"~":f.C0.ESC+"[24~";break;default:if(!p.ctrlKey||p.shiftKey||p.altKey||p.metaKey)if(S&&!b||!p.altKey||p.metaKey)!S||p.altKey||p.ctrlKey||p.shiftKey||!p.metaKey?p.key&&!p.ctrlKey&&!p.altKey&&!p.metaKey&&p.keyCode>=48&&p.key.length===1?y.key=p.key:p.key&&p.ctrlKey&&(p.key==="_"&&(y.key=f.C0.US),p.key==="@"&&(y.key=f.C0.NUL)):p.keyCode===65&&(y.type=1);else{const h=m[p.keyCode],l=h==null?void 0:h[p.shiftKey?1:0];if(l)y.key=f.C0.ESC+l;else if(p.keyCode>=65&&p.keyCode<=90){const d=p.ctrlKey?p.keyCode-64:p.keyCode+32;let g=String.fromCharCode(d);p.shiftKey&&(g=g.toUpperCase()),y.key=f.C0.ESC+g}else if(p.keyCode===32)y.key=f.C0.ESC+(p.ctrlKey?f.C0.NUL:" ");else if(p.key==="Dead"&&p.code.startsWith("Key")){let d=p.code.slice(3,4);p.shiftKey||(d=d.toLowerCase()),y.key=f.C0.ESC+d,y.cancel=!0}}else p.keyCode>=65&&p.keyCode<=90?y.key=String.fromCharCode(p.keyCode-64):p.keyCode===32?y.key=f.C0.NUL:p.keyCode>=51&&p.keyCode<=55?y.key=String.fromCharCode(p.keyCode-51+27):p.keyCode===56?y.key=f.C0.DEL:p.keyCode===219?y.key=f.C0.ESC:p.keyCode===220?y.key=f.C0.FS:p.keyCode===221&&(y.key=f.C0.GS)}return y}},482:(c,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Utf8ToUtf32=n.StringToUtf32=n.utf32ToString=n.stringFromCodePoint=void 0,n.stringFromCodePoint=function(a){return a>65535?(a-=65536,String.fromCharCode(55296+(a>>10))+String.fromCharCode(a%1024+56320)):String.fromCharCode(a)},n.utf32ToString=function(a,f=0,m=a.length){let p="";for(let _=f;_65535?(S-=65536,p+=String.fromCharCode(55296+(S>>10))+String.fromCharCode(S%1024+56320)):p+=String.fromCharCode(S)}return p},n.StringToUtf32=class{constructor(){this._interim=0}clear(){this._interim=0}decode(a,f){const m=a.length;if(!m)return 0;let p=0,_=0;if(this._interim){const S=a.charCodeAt(_++);56320<=S&&S<=57343?f[p++]=1024*(this._interim-55296)+S-56320+65536:(f[p++]=this._interim,f[p++]=S),this._interim=0}for(let S=_;S=m)return this._interim=b,p;const y=a.charCodeAt(S);56320<=y&&y<=57343?f[p++]=1024*(b-55296)+y-56320+65536:(f[p++]=b,f[p++]=y)}else b!==65279&&(f[p++]=b)}return p}},n.Utf8ToUtf32=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(a,f){const m=a.length;if(!m)return 0;let p,_,S,b,y=0,u=0,h=0;if(this.interim[0]){let g=!1,x=this.interim[0];x&=(224&x)==192?31:(240&x)==224?15:7;let C,k=0;for(;(C=63&this.interim[++k])&&k<4;)x<<=6,x|=C;const w=(224&this.interim[0])==192?2:(240&this.interim[0])==224?3:4,E=w-k;for(;h=m)return 0;if(C=a[h++],(192&C)!=128){h--,g=!0;break}this.interim[k++]=C,x<<=6,x|=63&C}g||(w===2?x<128?h--:f[y++]=x:w===3?x<2048||x>=55296&&x<=57343||x===65279||(f[y++]=x):x<65536||x>1114111||(f[y++]=x)),this.interim.fill(0)}const l=m-4;let d=h;for(;d=m)return this.interim[0]=p,y;if(_=a[d++],(192&_)!=128){d--;continue}if(u=(31&p)<<6|63&_,u<128){d--;continue}f[y++]=u}else if((240&p)==224){if(d>=m)return this.interim[0]=p,y;if(_=a[d++],(192&_)!=128){d--;continue}if(d>=m)return this.interim[0]=p,this.interim[1]=_,y;if(S=a[d++],(192&S)!=128){d--;continue}if(u=(15&p)<<12|(63&_)<<6|63&S,u<2048||u>=55296&&u<=57343||u===65279)continue;f[y++]=u}else if((248&p)==240){if(d>=m)return this.interim[0]=p,y;if(_=a[d++],(192&_)!=128){d--;continue}if(d>=m)return this.interim[0]=p,this.interim[1]=_,y;if(S=a[d++],(192&S)!=128){d--;continue}if(d>=m)return this.interim[0]=p,this.interim[1]=_,this.interim[2]=S,y;if(b=a[d++],(192&b)!=128){d--;continue}if(u=(7&p)<<18|(63&_)<<12|(63&S)<<6|63&b,u<65536||u>1114111)continue;f[y++]=u}}return y}}},225:(c,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.UnicodeV6=void 0;const a=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],f=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]];let m;n.UnicodeV6=class{constructor(){if(this.version="6",!m){m=new Uint8Array(65536),m.fill(1),m[0]=0,m.fill(0,1,32),m.fill(0,127,160),m.fill(2,4352,4448),m[9001]=2,m[9002]=2,m.fill(2,11904,42192),m[12351]=1,m.fill(2,44032,55204),m.fill(2,63744,64256),m.fill(2,65040,65050),m.fill(2,65072,65136),m.fill(2,65280,65377),m.fill(2,65504,65511);for(let p=0;pS[u][1])return!1;for(;u>=y;)if(b=y+u>>1,_>S[b][1])y=b+1;else{if(!(_=131072&&p<=196605||p>=196608&&p<=262141?2:1}}},5981:(c,n,a)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.WriteBuffer=void 0;const f=a(8460),m=a(844);class p extends m.Disposable{constructor(S){super(),this._action=S,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this.register(new f.EventEmitter),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(S,b){if(b!==void 0&&this._syncCalls>b)return void(this._syncCalls=0);if(this._pendingData+=S.length,this._writeBuffer.push(S),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;let y;for(this._isSyncWriting=!0;y=this._writeBuffer.shift();){this._action(y);const u=this._callbacks.shift();u&&u()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(S,b){if(this._pendingData>5e7)throw new Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput)return this._didUserInput=!1,this._pendingData+=S.length,this._writeBuffer.push(S),this._callbacks.push(b),void this._innerWrite();setTimeout(()=>this._innerWrite())}this._pendingData+=S.length,this._writeBuffer.push(S),this._callbacks.push(b)}_innerWrite(S=0,b=!0){const y=S||Date.now();for(;this._writeBuffer.length>this._bufferOffset;){const u=this._writeBuffer[this._bufferOffset],h=this._action(u,b);if(h){const d=g=>Date.now()-y>=12?setTimeout(()=>this._innerWrite(0,g)):this._innerWrite(y,g);return void h.catch(g=>(queueMicrotask(()=>{throw g}),Promise.resolve(!1))).then(d)}const l=this._callbacks[this._bufferOffset];if(l&&l(),this._bufferOffset++,this._pendingData-=u.length,Date.now()-y>=12)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>50&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}}n.WriteBuffer=p},5941:(c,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.toRgbString=n.parseColor=void 0;const a=/^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/,f=/^[\da-f]+$/;function m(p,_){const S=p.toString(16),b=S.length<2?"0"+S:S;switch(_){case 4:return S[0];case 8:return b;case 12:return(b+b).slice(0,3);default:return b+b}}n.parseColor=function(p){if(!p)return;let _=p.toLowerCase();if(_.indexOf("rgb:")===0){_=_.slice(4);const S=a.exec(_);if(S){const b=S[1]?15:S[4]?255:S[7]?4095:65535;return[Math.round(parseInt(S[1]||S[4]||S[7]||S[10],16)/b*255),Math.round(parseInt(S[2]||S[5]||S[8]||S[11],16)/b*255),Math.round(parseInt(S[3]||S[6]||S[9]||S[12],16)/b*255)]}}else if(_.indexOf("#")===0&&(_=_.slice(1),f.exec(_)&&[3,6,9,12].includes(_.length))){const S=_.length/3,b=[0,0,0];for(let y=0;y<3;++y){const u=parseInt(_.slice(S*y,S*y+S),16);b[y]=S===1?u<<4:S===2?u:S===3?u>>4:u>>8}return b}},n.toRgbString=function(p,_=16){const[S,b,y]=p;return`rgb:${m(S,_)}/${m(b,_)}/${m(y,_)}`}},5770:(c,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.PAYLOAD_LIMIT=void 0,n.PAYLOAD_LIMIT=1e7},6351:(c,n,a)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.DcsHandler=n.DcsParser=void 0;const f=a(482),m=a(8742),p=a(5770),_=[];n.DcsParser=class{constructor(){this._handlers=Object.create(null),this._active=_,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=_}registerHandler(b,y){this._handlers[b]===void 0&&(this._handlers[b]=[]);const u=this._handlers[b];return u.push(y),{dispose:()=>{const h=u.indexOf(y);h!==-1&&u.splice(h,1)}}}clearHandler(b){this._handlers[b]&&delete this._handlers[b]}setHandlerFallback(b){this._handlerFb=b}reset(){if(this._active.length)for(let b=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;b>=0;--b)this._active[b].unhook(!1);this._stack.paused=!1,this._active=_,this._ident=0}hook(b,y){if(this.reset(),this._ident=b,this._active=this._handlers[b]||_,this._active.length)for(let u=this._active.length-1;u>=0;u--)this._active[u].hook(y);else this._handlerFb(this._ident,"HOOK",y)}put(b,y,u){if(this._active.length)for(let h=this._active.length-1;h>=0;h--)this._active[h].put(b,y,u);else this._handlerFb(this._ident,"PUT",(0,f.utf32ToString)(b,y,u))}unhook(b,y=!0){if(this._active.length){let u=!1,h=this._active.length-1,l=!1;if(this._stack.paused&&(h=this._stack.loopPosition-1,u=y,l=this._stack.fallThrough,this._stack.paused=!1),!l&&u===!1){for(;h>=0&&(u=this._active[h].unhook(b),u!==!0);h--)if(u instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=h,this._stack.fallThrough=!1,u;h--}for(;h>=0;h--)if(u=this._active[h].unhook(!1),u instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=h,this._stack.fallThrough=!0,u}else this._handlerFb(this._ident,"UNHOOK",b);this._active=_,this._ident=0}};const S=new m.Params;S.addParam(0),n.DcsHandler=class{constructor(b){this._handler=b,this._data="",this._params=S,this._hitLimit=!1}hook(b){this._params=b.length>1||b.params[0]?b.clone():S,this._data="",this._hitLimit=!1}put(b,y,u){this._hitLimit||(this._data+=(0,f.utf32ToString)(b,y,u),this._data.length>p.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}unhook(b){let y=!1;if(this._hitLimit)y=!1;else if(b&&(y=this._handler(this._data,this._params),y instanceof Promise))return y.then(u=>(this._params=S,this._data="",this._hitLimit=!1,u));return this._params=S,this._data="",this._hitLimit=!1,y}}},2015:(c,n,a)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.EscapeSequenceParser=n.VT500_TRANSITION_TABLE=n.TransitionTable=void 0;const f=a(844),m=a(8742),p=a(6242),_=a(6351);class S{constructor(h){this.table=new Uint8Array(h)}setDefault(h,l){this.table.fill(h<<4|l)}add(h,l,d,g){this.table[l<<8|h]=d<<4|g}addMany(h,l,d,g){for(let x=0;xw),l=(k,w)=>h.slice(k,w),d=l(32,127),g=l(0,24);g.push(25),g.push.apply(g,l(28,32));const x=l(0,14);let C;for(C in u.setDefault(1,0),u.addMany(d,0,2,0),x)u.addMany([24,26,153,154],C,3,0),u.addMany(l(128,144),C,3,0),u.addMany(l(144,152),C,3,0),u.add(156,C,0,0),u.add(27,C,11,1),u.add(157,C,4,8),u.addMany([152,158,159],C,0,7),u.add(155,C,11,3),u.add(144,C,11,9);return u.addMany(g,0,3,0),u.addMany(g,1,3,1),u.add(127,1,0,1),u.addMany(g,8,0,8),u.addMany(g,3,3,3),u.add(127,3,0,3),u.addMany(g,4,3,4),u.add(127,4,0,4),u.addMany(g,6,3,6),u.addMany(g,5,3,5),u.add(127,5,0,5),u.addMany(g,2,3,2),u.add(127,2,0,2),u.add(93,1,4,8),u.addMany(d,8,5,8),u.add(127,8,5,8),u.addMany([156,27,24,26,7],8,6,0),u.addMany(l(28,32),8,0,8),u.addMany([88,94,95],1,0,7),u.addMany(d,7,0,7),u.addMany(g,7,0,7),u.add(156,7,0,0),u.add(127,7,0,7),u.add(91,1,11,3),u.addMany(l(64,127),3,7,0),u.addMany(l(48,60),3,8,4),u.addMany([60,61,62,63],3,9,4),u.addMany(l(48,60),4,8,4),u.addMany(l(64,127),4,7,0),u.addMany([60,61,62,63],4,0,6),u.addMany(l(32,64),6,0,6),u.add(127,6,0,6),u.addMany(l(64,127),6,0,0),u.addMany(l(32,48),3,9,5),u.addMany(l(32,48),5,9,5),u.addMany(l(48,64),5,0,6),u.addMany(l(64,127),5,7,0),u.addMany(l(32,48),4,9,5),u.addMany(l(32,48),1,9,2),u.addMany(l(32,48),2,9,2),u.addMany(l(48,127),2,10,0),u.addMany(l(48,80),1,10,0),u.addMany(l(81,88),1,10,0),u.addMany([89,90,92],1,10,0),u.addMany(l(96,127),1,10,0),u.add(80,1,11,9),u.addMany(g,9,0,9),u.add(127,9,0,9),u.addMany(l(28,32),9,0,9),u.addMany(l(32,48),9,9,12),u.addMany(l(48,60),9,8,10),u.addMany([60,61,62,63],9,9,10),u.addMany(g,11,0,11),u.addMany(l(32,128),11,0,11),u.addMany(l(28,32),11,0,11),u.addMany(g,10,0,10),u.add(127,10,0,10),u.addMany(l(28,32),10,0,10),u.addMany(l(48,60),10,8,10),u.addMany([60,61,62,63],10,0,11),u.addMany(l(32,48),10,9,12),u.addMany(g,12,0,12),u.add(127,12,0,12),u.addMany(l(28,32),12,0,12),u.addMany(l(32,48),12,9,12),u.addMany(l(48,64),12,0,11),u.addMany(l(64,127),12,12,13),u.addMany(l(64,127),10,12,13),u.addMany(l(64,127),9,12,13),u.addMany(g,13,13,13),u.addMany(d,13,13,13),u.add(127,13,0,13),u.addMany([27,156,24,26],13,14,0),u.add(b,0,2,0),u.add(b,8,5,8),u.add(b,6,0,6),u.add(b,11,0,11),u.add(b,13,13,13),u}();class y extends f.Disposable{constructor(h=n.VT500_TRANSITION_TABLE){super(),this._transitions=h,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new m.Params,this._params.addParam(0),this._collect=0,this.precedingCodepoint=0,this._printHandlerFb=(l,d,g)=>{},this._executeHandlerFb=l=>{},this._csiHandlerFb=(l,d)=>{},this._escHandlerFb=l=>{},this._errorHandlerFb=l=>l,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this.register((0,f.toDisposable)(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this.register(new p.OscParser),this._dcsParser=this.register(new _.DcsParser),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},()=>!0)}_identifier(h,l=[64,126]){let d=0;if(h.prefix){if(h.prefix.length>1)throw new Error("only one byte as prefix supported");if(d=h.prefix.charCodeAt(0),d&&60>d||d>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(h.intermediates){if(h.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let x=0;xC||C>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");d<<=8,d|=C}}if(h.final.length!==1)throw new Error("final must be a single byte");const g=h.final.charCodeAt(0);if(l[0]>g||g>l[1])throw new Error(`final must be in range ${l[0]} .. ${l[1]}`);return d<<=8,d|=g,d}identToString(h){const l=[];for(;h;)l.push(String.fromCharCode(255&h)),h>>=8;return l.reverse().join("")}setPrintHandler(h){this._printHandler=h}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(h,l){const d=this._identifier(h,[48,126]);this._escHandlers[d]===void 0&&(this._escHandlers[d]=[]);const g=this._escHandlers[d];return g.push(l),{dispose:()=>{const x=g.indexOf(l);x!==-1&&g.splice(x,1)}}}clearEscHandler(h){this._escHandlers[this._identifier(h,[48,126])]&&delete this._escHandlers[this._identifier(h,[48,126])]}setEscHandlerFallback(h){this._escHandlerFb=h}setExecuteHandler(h,l){this._executeHandlers[h.charCodeAt(0)]=l}clearExecuteHandler(h){this._executeHandlers[h.charCodeAt(0)]&&delete this._executeHandlers[h.charCodeAt(0)]}setExecuteHandlerFallback(h){this._executeHandlerFb=h}registerCsiHandler(h,l){const d=this._identifier(h);this._csiHandlers[d]===void 0&&(this._csiHandlers[d]=[]);const g=this._csiHandlers[d];return g.push(l),{dispose:()=>{const x=g.indexOf(l);x!==-1&&g.splice(x,1)}}}clearCsiHandler(h){this._csiHandlers[this._identifier(h)]&&delete this._csiHandlers[this._identifier(h)]}setCsiHandlerFallback(h){this._csiHandlerFb=h}registerDcsHandler(h,l){return this._dcsParser.registerHandler(this._identifier(h),l)}clearDcsHandler(h){this._dcsParser.clearHandler(this._identifier(h))}setDcsHandlerFallback(h){this._dcsParser.setHandlerFallback(h)}registerOscHandler(h,l){return this._oscParser.registerHandler(h,l)}clearOscHandler(h){this._oscParser.clearHandler(h)}setOscHandlerFallback(h){this._oscParser.setHandlerFallback(h)}setErrorHandler(h){this._errorHandler=h}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingCodepoint=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(h,l,d,g,x){this._parseStack.state=h,this._parseStack.handlers=l,this._parseStack.handlerPos=d,this._parseStack.transition=g,this._parseStack.chunkPos=x}parse(h,l,d){let g,x=0,C=0,k=0;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,k=this._parseStack.chunkPos+1;else{if(d===void 0||this._parseStack.state===1)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");const w=this._parseStack.handlers;let E=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(d===!1&&E>-1){for(;E>=0&&(g=w[E](this._params),g!==!0);E--)if(g instanceof Promise)return this._parseStack.handlerPos=E,g}this._parseStack.handlers=[];break;case 4:if(d===!1&&E>-1){for(;E>=0&&(g=w[E](),g!==!0);E--)if(g instanceof Promise)return this._parseStack.handlerPos=E,g}this._parseStack.handlers=[];break;case 6:if(x=h[this._parseStack.chunkPos],g=this._dcsParser.unhook(x!==24&&x!==26,d),g)return g;x===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(x=h[this._parseStack.chunkPos],g=this._oscParser.end(x!==24&&x!==26,d),g)return g;x===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,k=this._parseStack.chunkPos+1,this.precedingCodepoint=0,this.currentState=15&this._parseStack.transition}for(let w=k;w>4){case 2:for(let P=w+1;;++P){if(P>=l||(x=h[P])<32||x>126&&x=l||(x=h[P])<32||x>126&&x=l||(x=h[P])<32||x>126&&x=l||(x=h[P])<32||x>126&&x=0&&(g=E[L](this._params),g!==!0);L--)if(g instanceof Promise)return this._preserveStack(3,E,L,C,w),g;L<0&&this._csiHandlerFb(this._collect<<8|x,this._params),this.precedingCodepoint=0;break;case 8:do switch(x){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(x-48)}while(++w47&&x<60);w--;break;case 9:this._collect<<=8,this._collect|=x;break;case 10:const N=this._escHandlers[this._collect<<8|x];let O=N?N.length-1:-1;for(;O>=0&&(g=N[O](),g!==!0);O--)if(g instanceof Promise)return this._preserveStack(4,N,O,C,w),g;O<0&&this._escHandlerFb(this._collect<<8|x),this.precedingCodepoint=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|x,this._params);break;case 13:for(let P=w+1;;++P)if(P>=l||(x=h[P])===24||x===26||x===27||x>127&&x=l||(x=h[P])<32||x>127&&x{Object.defineProperty(n,"__esModule",{value:!0}),n.OscHandler=n.OscParser=void 0;const f=a(5770),m=a(482),p=[];n.OscParser=class{constructor(){this._state=0,this._active=p,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(_,S){this._handlers[_]===void 0&&(this._handlers[_]=[]);const b=this._handlers[_];return b.push(S),{dispose:()=>{const y=b.indexOf(S);y!==-1&&b.splice(y,1)}}}clearHandler(_){this._handlers[_]&&delete this._handlers[_]}setHandlerFallback(_){this._handlerFb=_}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=p}reset(){if(this._state===2)for(let _=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;_>=0;--_)this._active[_].end(!1);this._stack.paused=!1,this._active=p,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||p,this._active.length)for(let _=this._active.length-1;_>=0;_--)this._active[_].start();else this._handlerFb(this._id,"START")}_put(_,S,b){if(this._active.length)for(let y=this._active.length-1;y>=0;y--)this._active[y].put(_,S,b);else this._handlerFb(this._id,"PUT",(0,m.utf32ToString)(_,S,b))}start(){this.reset(),this._state=1}put(_,S,b){if(this._state!==3){if(this._state===1)for(;S0&&this._put(_,S,b)}}end(_,S=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),this._active.length){let b=!1,y=this._active.length-1,u=!1;if(this._stack.paused&&(y=this._stack.loopPosition-1,b=S,u=this._stack.fallThrough,this._stack.paused=!1),!u&&b===!1){for(;y>=0&&(b=this._active[y].end(_),b!==!0);y--)if(b instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=y,this._stack.fallThrough=!1,b;y--}for(;y>=0;y--)if(b=this._active[y].end(!1),b instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=y,this._stack.fallThrough=!0,b}else this._handlerFb(this._id,"END",_);this._active=p,this._id=-1,this._state=0}}},n.OscHandler=class{constructor(_){this._handler=_,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(_,S,b){this._hitLimit||(this._data+=(0,m.utf32ToString)(_,S,b),this._data.length>f.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}end(_){let S=!1;if(this._hitLimit)S=!1;else if(_&&(S=this._handler(this._data),S instanceof Promise))return S.then(b=>(this._data="",this._hitLimit=!1,b));return this._data="",this._hitLimit=!1,S}}},8742:(c,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Params=void 0;const a=2147483647;class f{static fromArray(p){const _=new f;if(!p.length)return _;for(let S=Array.isArray(p[0])?1:0;S256)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(p),this.length=0,this._subParams=new Int32Array(_),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(p),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}clone(){const p=new f(this.maxLength,this.maxSubParamsLength);return p.params.set(this.params),p.length=this.length,p._subParams.set(this._subParams),p._subParamsLength=this._subParamsLength,p._subParamsIdx.set(this._subParamsIdx),p._rejectDigits=this._rejectDigits,p._rejectSubDigits=this._rejectSubDigits,p._digitIsSub=this._digitIsSub,p}toArray(){const p=[];for(let _=0;_>8,b=255&this._subParamsIdx[_];b-S>0&&p.push(Array.prototype.slice.call(this._subParams,S,b))}return p}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(p){if(this._digitIsSub=!1,this.length>=this.maxLength)this._rejectDigits=!0;else{if(p<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=p>a?a:p}}addSubParam(p){if(this._digitIsSub=!0,this.length)if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength)this._rejectSubDigits=!0;else{if(p<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=p>a?a:p,this._subParamsIdx[this.length-1]++}}hasSubParams(p){return(255&this._subParamsIdx[p])-(this._subParamsIdx[p]>>8)>0}getSubParams(p){const _=this._subParamsIdx[p]>>8,S=255&this._subParamsIdx[p];return S-_>0?this._subParams.subarray(_,S):null}getSubParamsAll(){const p={};for(let _=0;_>8,b=255&this._subParamsIdx[_];b-S>0&&(p[_]=this._subParams.slice(S,b))}return p}addDigit(p){let _;if(this._rejectDigits||!(_=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;const S=this._digitIsSub?this._subParams:this.params,b=S[_-1];S[_-1]=~b?Math.min(10*b+p,a):p}}n.Params=f},5741:(c,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.AddonManager=void 0,n.AddonManager=class{constructor(){this._addons=[]}dispose(){for(let a=this._addons.length-1;a>=0;a--)this._addons[a].instance.dispose()}loadAddon(a,f){const m={instance:f,dispose:f.dispose,isDisposed:!1};this._addons.push(m),f.dispose=()=>this._wrappedAddonDispose(m),f.activate(a)}_wrappedAddonDispose(a){if(a.isDisposed)return;let f=-1;for(let m=0;m{Object.defineProperty(n,"__esModule",{value:!0}),n.BufferApiView=void 0;const f=a(3785),m=a(511);n.BufferApiView=class{constructor(p,_){this._buffer=p,this.type=_}init(p){return this._buffer=p,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(p){const _=this._buffer.lines.get(p);if(_)return new f.BufferLineApiView(_)}getNullCell(){return new m.CellData}}},3785:(c,n,a)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.BufferLineApiView=void 0;const f=a(511);n.BufferLineApiView=class{constructor(m){this._line=m}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(m,p){if(!(m<0||m>=this._line.length))return p?(this._line.loadCell(m,p),p):this._line.loadCell(m,new f.CellData)}translateToString(m,p,_){return this._line.translateToString(m,p,_)}}},8285:(c,n,a)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.BufferNamespaceApi=void 0;const f=a(8771),m=a(8460),p=a(844);class _ extends p.Disposable{constructor(b){super(),this._core=b,this._onBufferChange=this.register(new m.EventEmitter),this.onBufferChange=this._onBufferChange.event,this._normal=new f.BufferApiView(this._core.buffers.normal,"normal"),this._alternate=new f.BufferApiView(this._core.buffers.alt,"alternate"),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw new Error("Active buffer is neither normal nor alternate")}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}}n.BufferNamespaceApi=_},7975:(c,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.ParserApi=void 0,n.ParserApi=class{constructor(a){this._core=a}registerCsiHandler(a,f){return this._core.registerCsiHandler(a,m=>f(m.toArray()))}addCsiHandler(a,f){return this.registerCsiHandler(a,f)}registerDcsHandler(a,f){return this._core.registerDcsHandler(a,(m,p)=>f(m,p.toArray()))}addDcsHandler(a,f){return this.registerDcsHandler(a,f)}registerEscHandler(a,f){return this._core.registerEscHandler(a,f)}addEscHandler(a,f){return this.registerEscHandler(a,f)}registerOscHandler(a,f){return this._core.registerOscHandler(a,f)}addOscHandler(a,f){return this.registerOscHandler(a,f)}}},7090:(c,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.UnicodeApi=void 0,n.UnicodeApi=class{constructor(a){this._core=a}register(a){this._core.unicodeService.register(a)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(a){this._core.unicodeService.activeVersion=a}}},744:function(c,n,a){var f=this&&this.__decorate||function(u,h,l,d){var g,x=arguments.length,C=x<3?h:d===null?d=Object.getOwnPropertyDescriptor(h,l):d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")C=Reflect.decorate(u,h,l,d);else for(var k=u.length-1;k>=0;k--)(g=u[k])&&(C=(x<3?g(C):x>3?g(h,l,C):g(h,l))||C);return x>3&&C&&Object.defineProperty(h,l,C),C},m=this&&this.__param||function(u,h){return function(l,d){h(l,d,u)}};Object.defineProperty(n,"__esModule",{value:!0}),n.BufferService=n.MINIMUM_ROWS=n.MINIMUM_COLS=void 0;const p=a(8460),_=a(844),S=a(5295),b=a(2585);n.MINIMUM_COLS=2,n.MINIMUM_ROWS=1;let y=n.BufferService=class extends _.Disposable{get buffer(){return this.buffers.active}constructor(u){super(),this.isUserScrolling=!1,this._onResize=this.register(new p.EventEmitter),this.onResize=this._onResize.event,this._onScroll=this.register(new p.EventEmitter),this.onScroll=this._onScroll.event,this.cols=Math.max(u.rawOptions.cols||0,n.MINIMUM_COLS),this.rows=Math.max(u.rawOptions.rows||0,n.MINIMUM_ROWS),this.buffers=this.register(new S.BufferSet(u,this))}resize(u,h){this.cols=u,this.rows=h,this.buffers.resize(u,h),this._onResize.fire({cols:u,rows:h})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(u,h=!1){const l=this.buffer;let d;d=this._cachedBlankLine,d&&d.length===this.cols&&d.getFg(0)===u.fg&&d.getBg(0)===u.bg||(d=l.getBlankLine(u,h),this._cachedBlankLine=d),d.isWrapped=h;const g=l.ybase+l.scrollTop,x=l.ybase+l.scrollBottom;if(l.scrollTop===0){const C=l.lines.isFull;x===l.lines.length-1?C?l.lines.recycle().copyFrom(d):l.lines.push(d.clone()):l.lines.splice(x+1,0,d.clone()),C?this.isUserScrolling&&(l.ydisp=Math.max(l.ydisp-1,0)):(l.ybase++,this.isUserScrolling||l.ydisp++)}else{const C=x-g+1;l.lines.shiftElements(g+1,C-1,-1),l.lines.set(x,d.clone())}this.isUserScrolling||(l.ydisp=l.ybase),this._onScroll.fire(l.ydisp)}scrollLines(u,h,l){const d=this.buffer;if(u<0){if(d.ydisp===0)return;this.isUserScrolling=!0}else u+d.ydisp>=d.ybase&&(this.isUserScrolling=!1);const g=d.ydisp;d.ydisp=Math.max(Math.min(d.ydisp+u,d.ybase),0),g!==d.ydisp&&(h||this._onScroll.fire(d.ydisp))}};n.BufferService=y=f([m(0,b.IOptionsService)],y)},7994:(c,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.CharsetService=void 0,n.CharsetService=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(a){this.glevel=a,this.charset=this._charsets[a]}setgCharset(a,f){this._charsets[a]=f,this.glevel===a&&(this.charset=f)}}},1753:function(c,n,a){var f=this&&this.__decorate||function(d,g,x,C){var k,w=arguments.length,E=w<3?g:C===null?C=Object.getOwnPropertyDescriptor(g,x):C;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")E=Reflect.decorate(d,g,x,C);else for(var L=d.length-1;L>=0;L--)(k=d[L])&&(E=(w<3?k(E):w>3?k(g,x,E):k(g,x))||E);return w>3&&E&&Object.defineProperty(g,x,E),E},m=this&&this.__param||function(d,g){return function(x,C){g(x,C,d)}};Object.defineProperty(n,"__esModule",{value:!0}),n.CoreMouseService=void 0;const p=a(2585),_=a(8460),S=a(844),b={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:d=>d.button!==4&&d.action===1&&(d.ctrl=!1,d.alt=!1,d.shift=!1,!0)},VT200:{events:19,restrict:d=>d.action!==32},DRAG:{events:23,restrict:d=>d.action!==32||d.button!==3},ANY:{events:31,restrict:d=>!0}};function y(d,g){let x=(d.ctrl?16:0)|(d.shift?4:0)|(d.alt?8:0);return d.button===4?(x|=64,x|=d.action):(x|=3&d.button,4&d.button&&(x|=64),8&d.button&&(x|=128),d.action===32?x|=32:d.action!==0||g||(x|=3)),x}const u=String.fromCharCode,h={DEFAULT:d=>{const g=[y(d,!1)+32,d.col+32,d.row+32];return g[0]>255||g[1]>255||g[2]>255?"":`\x1B[M${u(g[0])}${u(g[1])}${u(g[2])}`},SGR:d=>{const g=d.action===0&&d.button!==4?"m":"M";return`\x1B[<${y(d,!0)};${d.col};${d.row}${g}`},SGR_PIXELS:d=>{const g=d.action===0&&d.button!==4?"m":"M";return`\x1B[<${y(d,!0)};${d.x};${d.y}${g}`}};let l=n.CoreMouseService=class extends S.Disposable{constructor(d,g){super(),this._bufferService=d,this._coreService=g,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._onProtocolChange=this.register(new _.EventEmitter),this.onProtocolChange=this._onProtocolChange.event;for(const x of Object.keys(b))this.addProtocol(x,b[x]);for(const x of Object.keys(h))this.addEncoding(x,h[x]);this.reset()}addProtocol(d,g){this._protocols[d]=g}addEncoding(d,g){this._encodings[d]=g}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(d){if(!this._protocols[d])throw new Error(`unknown protocol "${d}"`);this._activeProtocol=d,this._onProtocolChange.fire(this._protocols[d].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(d){if(!this._encodings[d])throw new Error(`unknown encoding "${d}"`);this._activeEncoding=d}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null}triggerMouseEvent(d){if(d.col<0||d.col>=this._bufferService.cols||d.row<0||d.row>=this._bufferService.rows||d.button===4&&d.action===32||d.button===3&&d.action!==32||d.button!==4&&(d.action===2||d.action===3)||(d.col++,d.row++,d.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,d,this._activeEncoding==="SGR_PIXELS"))||!this._protocols[this._activeProtocol].restrict(d))return!1;const g=this._encodings[this._activeEncoding](d);return g&&(this._activeEncoding==="DEFAULT"?this._coreService.triggerBinaryEvent(g):this._coreService.triggerDataEvent(g,!0)),this._lastEvent=d,!0}explainEvents(d){return{down:!!(1&d),up:!!(2&d),drag:!!(4&d),move:!!(8&d),wheel:!!(16&d)}}_equalEvents(d,g,x){if(x){if(d.x!==g.x||d.y!==g.y)return!1}else if(d.col!==g.col||d.row!==g.row)return!1;return d.button===g.button&&d.action===g.action&&d.ctrl===g.ctrl&&d.alt===g.alt&&d.shift===g.shift}};n.CoreMouseService=l=f([m(0,p.IBufferService),m(1,p.ICoreService)],l)},6975:function(c,n,a){var f=this&&this.__decorate||function(l,d,g,x){var C,k=arguments.length,w=k<3?d:x===null?x=Object.getOwnPropertyDescriptor(d,g):x;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")w=Reflect.decorate(l,d,g,x);else for(var E=l.length-1;E>=0;E--)(C=l[E])&&(w=(k<3?C(w):k>3?C(d,g,w):C(d,g))||w);return k>3&&w&&Object.defineProperty(d,g,w),w},m=this&&this.__param||function(l,d){return function(g,x){d(g,x,l)}};Object.defineProperty(n,"__esModule",{value:!0}),n.CoreService=void 0;const p=a(1439),_=a(8460),S=a(844),b=a(2585),y=Object.freeze({insertMode:!1}),u=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,origin:!1,reverseWraparound:!1,sendFocus:!1,wraparound:!0});let h=n.CoreService=class extends S.Disposable{constructor(l,d,g){super(),this._bufferService=l,this._logService=d,this._optionsService=g,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this.register(new _.EventEmitter),this.onData=this._onData.event,this._onUserInput=this.register(new _.EventEmitter),this.onUserInput=this._onUserInput.event,this._onBinary=this.register(new _.EventEmitter),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this.register(new _.EventEmitter),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=(0,p.clone)(y),this.decPrivateModes=(0,p.clone)(u)}reset(){this.modes=(0,p.clone)(y),this.decPrivateModes=(0,p.clone)(u)}triggerDataEvent(l,d=!1){if(this._optionsService.rawOptions.disableStdin)return;const g=this._bufferService.buffer;d&&this._optionsService.rawOptions.scrollOnUserInput&&g.ybase!==g.ydisp&&this._onRequestScrollToBottom.fire(),d&&this._onUserInput.fire(),this._logService.debug(`sending data "${l}"`,()=>l.split("").map(x=>x.charCodeAt(0))),this._onData.fire(l)}triggerBinaryEvent(l){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${l}"`,()=>l.split("").map(d=>d.charCodeAt(0))),this._onBinary.fire(l))}};n.CoreService=h=f([m(0,b.IBufferService),m(1,b.ILogService),m(2,b.IOptionsService)],h)},9074:(c,n,a)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.DecorationService=void 0;const f=a(8055),m=a(8460),p=a(844),_=a(6106);let S=0,b=0;class y extends p.Disposable{get decorations(){return this._decorations.values()}constructor(){super(),this._decorations=new _.SortedList(l=>l==null?void 0:l.marker.line),this._onDecorationRegistered=this.register(new m.EventEmitter),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this.register(new m.EventEmitter),this.onDecorationRemoved=this._onDecorationRemoved.event,this.register((0,p.toDisposable)(()=>this.reset()))}registerDecoration(l){if(l.marker.isDisposed)return;const d=new u(l);if(d){const g=d.marker.onDispose(()=>d.dispose());d.onDispose(()=>{d&&(this._decorations.delete(d)&&this._onDecorationRemoved.fire(d),g.dispose())}),this._decorations.insert(d),this._onDecorationRegistered.fire(d)}return d}reset(){for(const l of this._decorations.values())l.dispose();this._decorations.clear()}*getDecorationsAtCell(l,d,g){var x,C,k;let w=0,E=0;for(const L of this._decorations.getKeyIterator(d))w=(x=L.options.x)!==null&&x!==void 0?x:0,E=w+((C=L.options.width)!==null&&C!==void 0?C:1),l>=w&&l{var k,w,E;S=(k=C.options.x)!==null&&k!==void 0?k:0,b=S+((w=C.options.width)!==null&&w!==void 0?w:1),l>=S&&l{Object.defineProperty(n,"__esModule",{value:!0}),n.InstantiationService=n.ServiceCollection=void 0;const f=a(2585),m=a(8343);class p{constructor(...S){this._entries=new Map;for(const[b,y]of S)this.set(b,y)}set(S,b){const y=this._entries.get(S);return this._entries.set(S,b),y}forEach(S){for(const[b,y]of this._entries.entries())S(b,y)}has(S){return this._entries.has(S)}get(S){return this._entries.get(S)}}n.ServiceCollection=p,n.InstantiationService=class{constructor(){this._services=new p,this._services.set(f.IInstantiationService,this)}setService(_,S){this._services.set(_,S)}getService(_){return this._services.get(_)}createInstance(_,...S){const b=(0,m.getServiceDependencies)(_).sort((h,l)=>h.index-l.index),y=[];for(const h of b){const l=this._services.get(h.id);if(!l)throw new Error(`[createInstance] ${_.name} depends on UNKNOWN service ${h.id}.`);y.push(l)}const u=b.length>0?b[0].index:S.length;if(S.length!==u)throw new Error(`[createInstance] First service dependency of ${_.name} at position ${u+1} conflicts with ${S.length} static arguments`);return new _(...S,...y)}}},7866:function(c,n,a){var f=this&&this.__decorate||function(u,h,l,d){var g,x=arguments.length,C=x<3?h:d===null?d=Object.getOwnPropertyDescriptor(h,l):d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")C=Reflect.decorate(u,h,l,d);else for(var k=u.length-1;k>=0;k--)(g=u[k])&&(C=(x<3?g(C):x>3?g(h,l,C):g(h,l))||C);return x>3&&C&&Object.defineProperty(h,l,C),C},m=this&&this.__param||function(u,h){return function(l,d){h(l,d,u)}};Object.defineProperty(n,"__esModule",{value:!0}),n.traceCall=n.setTraceLogger=n.LogService=void 0;const p=a(844),_=a(2585),S={trace:_.LogLevelEnum.TRACE,debug:_.LogLevelEnum.DEBUG,info:_.LogLevelEnum.INFO,warn:_.LogLevelEnum.WARN,error:_.LogLevelEnum.ERROR,off:_.LogLevelEnum.OFF};let b,y=n.LogService=class extends p.Disposable{get logLevel(){return this._logLevel}constructor(u){super(),this._optionsService=u,this._logLevel=_.LogLevelEnum.OFF,this._updateLogLevel(),this.register(this._optionsService.onSpecificOptionChange("logLevel",()=>this._updateLogLevel())),b=this}_updateLogLevel(){this._logLevel=S[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(u){for(let h=0;hJSON.stringify(C)).join(", ")})`);const x=d.apply(this,g);return b.trace(`GlyphRenderer#${d.name} return`,x),x}}},7302:(c,n,a)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.OptionsService=n.DEFAULT_OPTIONS=void 0;const f=a(8460),m=a(844),p=a(6114);n.DEFAULT_OPTIONS={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"courier-new, courier, monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1e3,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},rightClickSelectsWord:p.isMac,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRulerWidth:0};const _=["normal","bold","100","200","300","400","500","600","700","800","900"];class S extends m.Disposable{constructor(y){super(),this._onOptionChange=this.register(new f.EventEmitter),this.onOptionChange=this._onOptionChange.event;const u=Object.assign({},n.DEFAULT_OPTIONS);for(const h in y)if(h in u)try{const l=y[h];u[h]=this._sanitizeAndValidateOption(h,l)}catch(l){console.error(l)}this.rawOptions=u,this.options=Object.assign({},u),this._setupOptions()}onSpecificOptionChange(y,u){return this.onOptionChange(h=>{h===y&&u(this.rawOptions[y])})}onMultipleOptionChange(y,u){return this.onOptionChange(h=>{y.indexOf(h)!==-1&&u()})}_setupOptions(){const y=h=>{if(!(h in n.DEFAULT_OPTIONS))throw new Error(`No option with key "${h}"`);return this.rawOptions[h]},u=(h,l)=>{if(!(h in n.DEFAULT_OPTIONS))throw new Error(`No option with key "${h}"`);l=this._sanitizeAndValidateOption(h,l),this.rawOptions[h]!==l&&(this.rawOptions[h]=l,this._onOptionChange.fire(h))};for(const h in this.rawOptions){const l={get:y.bind(this,h),set:u.bind(this,h)};Object.defineProperty(this.options,h,l)}}_sanitizeAndValidateOption(y,u){switch(y){case"cursorStyle":if(u||(u=n.DEFAULT_OPTIONS[y]),!function(h){return h==="block"||h==="underline"||h==="bar"}(u))throw new Error(`"${u}" is not a valid value for ${y}`);break;case"wordSeparator":u||(u=n.DEFAULT_OPTIONS[y]);break;case"fontWeight":case"fontWeightBold":if(typeof u=="number"&&1<=u&&u<=1e3)break;u=_.includes(u)?u:n.DEFAULT_OPTIONS[y];break;case"cursorWidth":u=Math.floor(u);case"lineHeight":case"tabStopWidth":if(u<1)throw new Error(`${y} cannot be less than 1, value: ${u}`);break;case"minimumContrastRatio":u=Math.max(1,Math.min(21,Math.round(10*u)/10));break;case"scrollback":if((u=Math.min(u,4294967295))<0)throw new Error(`${y} cannot be less than 0, value: ${u}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(u<=0)throw new Error(`${y} cannot be less than or equal to 0, value: ${u}`);break;case"rows":case"cols":if(!u&&u!==0)throw new Error(`${y} must be numeric, value: ${u}`);break;case"windowsPty":u=u??{}}return u}}n.OptionsService=S},2660:function(c,n,a){var f=this&&this.__decorate||function(S,b,y,u){var h,l=arguments.length,d=l<3?b:u===null?u=Object.getOwnPropertyDescriptor(b,y):u;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")d=Reflect.decorate(S,b,y,u);else for(var g=S.length-1;g>=0;g--)(h=S[g])&&(d=(l<3?h(d):l>3?h(b,y,d):h(b,y))||d);return l>3&&d&&Object.defineProperty(b,y,d),d},m=this&&this.__param||function(S,b){return function(y,u){b(y,u,S)}};Object.defineProperty(n,"__esModule",{value:!0}),n.OscLinkService=void 0;const p=a(2585);let _=n.OscLinkService=class{constructor(S){this._bufferService=S,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(S){const b=this._bufferService.buffer;if(S.id===void 0){const g=b.addMarker(b.ybase+b.y),x={data:S,id:this._nextId++,lines:[g]};return g.onDispose(()=>this._removeMarkerFromLink(x,g)),this._dataByLinkId.set(x.id,x),x.id}const y=S,u=this._getEntryIdKey(y),h=this._entriesWithId.get(u);if(h)return this.addLineToLink(h.id,b.ybase+b.y),h.id;const l=b.addMarker(b.ybase+b.y),d={id:this._nextId++,key:this._getEntryIdKey(y),data:y,lines:[l]};return l.onDispose(()=>this._removeMarkerFromLink(d,l)),this._entriesWithId.set(d.key,d),this._dataByLinkId.set(d.id,d),d.id}addLineToLink(S,b){const y=this._dataByLinkId.get(S);if(y&&y.lines.every(u=>u.line!==b)){const u=this._bufferService.buffer.addMarker(b);y.lines.push(u),u.onDispose(()=>this._removeMarkerFromLink(y,u))}}getLinkData(S){var b;return(b=this._dataByLinkId.get(S))===null||b===void 0?void 0:b.data}_getEntryIdKey(S){return`${S.id};;${S.uri}`}_removeMarkerFromLink(S,b){const y=S.lines.indexOf(b);y!==-1&&(S.lines.splice(y,1),S.lines.length===0&&(S.data.id!==void 0&&this._entriesWithId.delete(S.key),this._dataByLinkId.delete(S.id)))}};n.OscLinkService=_=f([m(0,p.IBufferService)],_)},8343:(c,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.createDecorator=n.getServiceDependencies=n.serviceRegistry=void 0;const a="di$target",f="di$dependencies";n.serviceRegistry=new Map,n.getServiceDependencies=function(m){return m[f]||[]},n.createDecorator=function(m){if(n.serviceRegistry.has(m))return n.serviceRegistry.get(m);const p=function(_,S,b){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");(function(y,u,h){u[a]===u?u[f].push({id:y,index:h}):(u[f]=[{id:y,index:h}],u[a]=u)})(p,_,b)};return p.toString=()=>m,n.serviceRegistry.set(m,p),p}},2585:(c,n,a)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.IDecorationService=n.IUnicodeService=n.IOscLinkService=n.IOptionsService=n.ILogService=n.LogLevelEnum=n.IInstantiationService=n.ICharsetService=n.ICoreService=n.ICoreMouseService=n.IBufferService=void 0;const f=a(8343);var m;n.IBufferService=(0,f.createDecorator)("BufferService"),n.ICoreMouseService=(0,f.createDecorator)("CoreMouseService"),n.ICoreService=(0,f.createDecorator)("CoreService"),n.ICharsetService=(0,f.createDecorator)("CharsetService"),n.IInstantiationService=(0,f.createDecorator)("InstantiationService"),function(p){p[p.TRACE=0]="TRACE",p[p.DEBUG=1]="DEBUG",p[p.INFO=2]="INFO",p[p.WARN=3]="WARN",p[p.ERROR=4]="ERROR",p[p.OFF=5]="OFF"}(m||(n.LogLevelEnum=m={})),n.ILogService=(0,f.createDecorator)("LogService"),n.IOptionsService=(0,f.createDecorator)("OptionsService"),n.IOscLinkService=(0,f.createDecorator)("OscLinkService"),n.IUnicodeService=(0,f.createDecorator)("UnicodeService"),n.IDecorationService=(0,f.createDecorator)("DecorationService")},1480:(c,n,a)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.UnicodeService=void 0;const f=a(8460),m=a(225);n.UnicodeService=class{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new f.EventEmitter,this.onChange=this._onChange.event;const p=new m.UnicodeV6;this.register(p),this._active=p.version,this._activeProvider=p}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(p){if(!this._providers[p])throw new Error(`unknown Unicode version "${p}"`);this._active=p,this._activeProvider=this._providers[p],this._onChange.fire(p)}register(p){this._providers[p.version]=p}wcwidth(p){return this._activeProvider.wcwidth(p)}getStringCellWidth(p){let _=0;const S=p.length;for(let b=0;b=S)return _+this.wcwidth(y);const u=p.charCodeAt(b);56320<=u&&u<=57343?y=1024*(y-55296)+u-56320+65536:_+=this.wcwidth(u)}_+=this.wcwidth(y)}return _}}}},s={};function i(c){var n=s[c];if(n!==void 0)return n.exports;var a=s[c]={exports:{}};return r[c].call(a.exports,a,a.exports,i),a.exports}var o={};return(()=>{var c=o;Object.defineProperty(c,"__esModule",{value:!0}),c.Terminal=void 0;const n=i(9042),a=i(3236),f=i(844),m=i(5741),p=i(8285),_=i(7975),S=i(7090),b=["cols","rows"];class y extends f.Disposable{constructor(h){super(),this._core=this.register(new a.Terminal(h)),this._addonManager=this.register(new m.AddonManager),this._publicOptions=Object.assign({},this._core.options);const l=g=>this._core.options[g],d=(g,x)=>{this._checkReadonlyOptions(g),this._core.options[g]=x};for(const g in this._core.options){const x={get:l.bind(this,g),set:d.bind(this,g)};Object.defineProperty(this._publicOptions,g,x)}}_checkReadonlyOptions(h){if(b.includes(h))throw new Error(`Option "${h}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw new Error("You must set the allowProposedApi option to true to use proposed API")}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||(this._parser=new _.ParserApi(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new S.UnicodeApi(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||(this._buffer=this.register(new p.BufferNamespaceApi(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){const h=this._core.coreService.decPrivateModes;let l="none";switch(this._core.coreMouseService.activeProtocol){case"X10":l="x10";break;case"VT200":l="vt200";break;case"DRAG":l="drag";break;case"ANY":l="any"}return{applicationCursorKeysMode:h.applicationCursorKeys,applicationKeypadMode:h.applicationKeypad,bracketedPasteMode:h.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:l,originMode:h.origin,reverseWraparoundMode:h.reverseWraparound,sendFocusMode:h.sendFocus,wraparoundMode:h.wraparound}}get options(){return this._publicOptions}set options(h){for(const l in h)this._publicOptions[l]=h[l]}blur(){this._core.blur()}focus(){this._core.focus()}resize(h,l){this._verifyIntegers(h,l),this._core.resize(h,l)}open(h){this._core.open(h)}attachCustomKeyEventHandler(h){this._core.attachCustomKeyEventHandler(h)}registerLinkProvider(h){return this._core.registerLinkProvider(h)}registerCharacterJoiner(h){return this._checkProposedApi(),this._core.registerCharacterJoiner(h)}deregisterCharacterJoiner(h){this._checkProposedApi(),this._core.deregisterCharacterJoiner(h)}registerMarker(h=0){return this._verifyIntegers(h),this._core.registerMarker(h)}registerDecoration(h){var l,d,g;return this._checkProposedApi(),this._verifyPositiveIntegers((l=h.x)!==null&&l!==void 0?l:0,(d=h.width)!==null&&d!==void 0?d:0,(g=h.height)!==null&&g!==void 0?g:0),this._core.registerDecoration(h)}hasSelection(){return this._core.hasSelection()}select(h,l,d){this._verifyIntegers(h,l,d),this._core.select(h,l,d)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(h,l){this._verifyIntegers(h,l),this._core.selectLines(h,l)}dispose(){super.dispose()}scrollLines(h){this._verifyIntegers(h),this._core.scrollLines(h)}scrollPages(h){this._verifyIntegers(h),this._core.scrollPages(h)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(h){this._verifyIntegers(h),this._core.scrollToLine(h)}clear(){this._core.clear()}write(h,l){this._core.write(h,l)}writeln(h,l){this._core.write(h),this._core.write(`\r +`,l)}paste(h){this._core.paste(h)}refresh(h,l){this._verifyIntegers(h,l),this._core.refresh(h,l)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(h){this._addonManager.loadAddon(this,h)}static get strings(){return n}_verifyIntegers(...h){for(const l of h)if(l===1/0||isNaN(l)||l%1!=0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...h){for(const l of h)if(l&&(l===1/0||isNaN(l)||l%1!=0||l<0))throw new Error("This API only accepts positive integers")}}c.Terminal=y})(),o})())})(Ap);var GS=Ap.exports,Np={exports:{}};(function(e,t){(function(r,s){e.exports=s()})(self,()=>(()=>{var r={};return(()=>{var s=r;Object.defineProperty(s,"__esModule",{value:!0}),s.FitAddon=void 0,s.FitAddon=class{activate(i){this._terminal=i}dispose(){}fit(){const i=this.proposeDimensions();if(!i||!this._terminal||isNaN(i.cols)||isNaN(i.rows))return;const o=this._terminal._core;this._terminal.rows===i.rows&&this._terminal.cols===i.cols||(o._renderService.clear(),this._terminal.resize(i.cols,i.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;const i=this._terminal._core,o=i._renderService.dimensions;if(o.css.cell.width===0||o.css.cell.height===0)return;const c=this._terminal.options.scrollback===0?0:i.viewport.scrollBarWidth,n=window.getComputedStyle(this._terminal.element.parentElement),a=parseInt(n.getPropertyValue("height")),f=Math.max(0,parseInt(n.getPropertyValue("width"))),m=window.getComputedStyle(this._terminal.element),p=a-(parseInt(m.getPropertyValue("padding-top"))+parseInt(m.getPropertyValue("padding-bottom"))),_=f-(parseInt(m.getPropertyValue("padding-right"))+parseInt(m.getPropertyValue("padding-left")))-c;return{cols:Math.max(2,Math.floor(_/o.css.cell.width)),rows:Math.max(1,Math.floor(p/o.css.cell.height))}}}})(),r})())})(Np);var JS=Np.exports;const zt=Object.create(null);zt.open="0";zt.close="1";zt.ping="2";zt.pong="3";zt.message="4";zt.upgrade="5";zt.noop="6";const wn=Object.create(null);Object.keys(zt).forEach(e=>{wn[zt[e]]=e});const xl={type:"error",data:"parser error"},Pp=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",Bp=typeof ArrayBuffer=="function",jp=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,Nc=({type:e,data:t},r,s)=>Pp&&t instanceof Blob?r?s(t):wh(t,s):Bp&&(t instanceof ArrayBuffer||jp(t))?r?s(t):wh(new Blob([t]),s):s(zt[e]+(t||"")),wh=(e,t)=>{const r=new FileReader;return r.onload=function(){const s=r.result.split(",")[1];t("b"+(s||""))},r.readAsDataURL(e)};function Ch(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let ca;function QS(e,t){if(Pp&&e.data instanceof Blob)return e.data.arrayBuffer().then(Ch).then(t);if(Bp&&(e.data instanceof ArrayBuffer||jp(e.data)))return t(Ch(e.data));Nc(e,!1,r=>{ca||(ca=new TextEncoder),t(ca.encode(r))})}const Eh="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",qs=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e{let t=e.length*.75,r=e.length,s,i=0,o,c,n,a;e[e.length-1]==="="&&(t--,e[e.length-2]==="="&&t--);const f=new ArrayBuffer(t),m=new Uint8Array(f);for(s=0;s>4,m[i++]=(c&15)<<4|n>>2,m[i++]=(n&3)<<6|a&63;return f},ZS=typeof ArrayBuffer=="function",Pc=(e,t)=>{if(typeof e!="string")return{type:"message",data:Mp(e,t)};const r=e.charAt(0);return r==="b"?{type:"message",data:ex(e.substring(1),t)}:wn[r]?e.length>1?{type:wn[r],data:e.substring(1)}:{type:wn[r]}:xl},ex=(e,t)=>{if(ZS){const r=YS(e);return Mp(r,t)}else return{base64:!0,data:e}},Mp=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},Ip="",tx=(e,t)=>{const r=e.length,s=new Array(r);let i=0;e.forEach((o,c)=>{Nc(o,!1,n=>{s[c]=n,++i===r&&t(s.join(Ip))})})},rx=(e,t)=>{const r=e.split(Ip),s=[];for(let i=0;i{const s=r.length;let i;if(s<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,s);else if(s<65536){i=new Uint8Array(3);const o=new DataView(i.buffer);o.setUint8(0,126),o.setUint16(1,s)}else{i=new Uint8Array(9);const o=new DataView(i.buffer);o.setUint8(0,127),o.setBigUint64(1,BigInt(s))}e.data&&typeof e.data!="string"&&(i[0]|=128),t.enqueue(i),t.enqueue(r)})}})}let ua;function on(e){return e.reduce((t,r)=>t+r.length,0)}function an(e,t){if(e[0].length===t)return e.shift();const r=new Uint8Array(t);let s=0;for(let i=0;iMath.pow(2,21)-1){n.enqueue(xl);break}i=m*Math.pow(2,32)+f.getUint32(4),s=3}else{if(on(r)e){n.enqueue(xl);break}}}})}const Fp=4;function ke(e){if(e)return nx(e)}function nx(e){for(var t in ke.prototype)e[t]=ke.prototype[t];return e}ke.prototype.on=ke.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};ke.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this};ke.prototype.off=ke.prototype.removeListener=ke.prototype.removeAllListeners=ke.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var r=this._callbacks["$"+e];if(!r)return this;if(arguments.length==1)return delete this._callbacks["$"+e],this;for(var s,i=0;iPromise.resolve().then(t):(t,r)=>r(t,0),vt=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),ox="arraybuffer";function Hp(e,...t){return t.reduce((r,s)=>(e.hasOwnProperty(s)&&(r[s]=e[s]),r),{})}const ax=vt.setTimeout,lx=vt.clearTimeout;function Co(e,t){t.useNativeTimers?(e.setTimeoutFn=ax.bind(vt),e.clearTimeoutFn=lx.bind(vt)):(e.setTimeoutFn=vt.setTimeout.bind(vt),e.clearTimeoutFn=vt.clearTimeout.bind(vt))}const cx=1.33;function ux(e){return typeof e=="string"?hx(e):Math.ceil((e.byteLength||e.size)*cx)}function hx(e){let t=0,r=0;for(let s=0,i=e.length;s=57344?r+=3:(s++,r+=4);return r}function Up(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function dx(e){let t="";for(let r in e)e.hasOwnProperty(r)&&(t.length&&(t+="&"),t+=encodeURIComponent(r)+"="+encodeURIComponent(e[r]));return t}function fx(e){let t={},r=e.split("&");for(let s=0,i=r.length;s{this.readyState="paused",t()};if(this._polling||!this.writable){let s=0;this._polling&&(s++,this.once("pollComplete",function(){--s||r()})),this.writable||(s++,this.once("drain",function(){--s||r()}))}else r()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){const r=s=>{if(this.readyState==="opening"&&s.type==="open"&&this.onOpen(),s.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(s)};rx(t,this.socket.binaryType).forEach(r),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const t=()=>{this.write([{type:"close"}])};this.readyState==="open"?t():this.once("open",t)}write(t){this.writable=!1,tx(t,r=>{this.doWrite(r,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",r=this.query||{};return this.opts.timestampRequests!==!1&&(r[this.opts.timestampParam]=Up()),!this.supportsBinary&&!r.sid&&(r.b64=1),this.createUri(t,r)}}let zp=!1;try{zp=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const _x=zp;function gx(){}class vx extends mx{constructor(t){if(super(t),typeof location<"u"){const r=location.protocol==="https:";let s=location.port;s||(s=r?"443":"80"),this.xd=typeof location<"u"&&t.hostname!==location.hostname||s!==t.port}}doWrite(t,r){const s=this.request({method:"POST",data:t});s.on("success",r),s.on("error",(i,o)=>{this.onError("xhr post error",i,o)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(r,s)=>{this.onError("xhr poll error",r,s)}),this.pollXhr=t}}class Ut extends ke{constructor(t,r,s){super(),this.createRequest=t,Co(this,s),this._opts=s,this._method=s.method||"GET",this._uri=r,this._data=s.data!==void 0?s.data:null,this._create()}_create(){var t;const r=Hp(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");r.xdomain=!!this._opts.xd;const s=this._xhr=this.createRequest(r);try{s.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){s.setDisableHeaderCheck&&s.setDisableHeaderCheck(!0);for(let i in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(i)&&s.setRequestHeader(i,this._opts.extraHeaders[i])}}catch{}if(this._method==="POST")try{s.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{s.setRequestHeader("Accept","*/*")}catch{}(t=this._opts.cookieJar)===null||t===void 0||t.addCookies(s),"withCredentials"in s&&(s.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(s.timeout=this._opts.requestTimeout),s.onreadystatechange=()=>{var i;s.readyState===3&&((i=this._opts.cookieJar)===null||i===void 0||i.parseCookies(s.getResponseHeader("set-cookie"))),s.readyState===4&&(s.status===200||s.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof s.status=="number"?s.status:0)},0))},s.send(this._data)}catch(i){this.setTimeoutFn(()=>{this._onError(i)},0);return}typeof document<"u"&&(this._index=Ut.requestsCount++,Ut.requests[this._index]=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=gx,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete Ut.requests[this._index],this._xhr=null}}_onLoad(){const t=this._xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}Ut.requestsCount=0;Ut.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",kh);else if(typeof addEventListener=="function"){const e="onpagehide"in vt?"pagehide":"unload";addEventListener(e,kh,!1)}}function kh(){for(let e in Ut.requests)Ut.requests.hasOwnProperty(e)&&Ut.requests[e].abort()}const yx=function(){const e=$p({xdomain:!1});return e&&e.responseType!==null}();class Sx extends vx{constructor(t){super(t);const r=t&&t.forceBase64;this.supportsBinary=yx&&!r}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new Ut($p,this.uri(),t)}}function $p(e){const t=e.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||_x))return new XMLHttpRequest}catch{}if(!t)try{return new vt[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const Wp=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class xx extends Bc{get name(){return"websocket"}doOpen(){const t=this.uri(),r=this.opts.protocols,s=Wp?{}:Hp(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(s.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,r,s)}catch(i){return this.emitReserved("error",i)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let r=0;r{try{this.doWrite(s,o)}catch{}i&&wo(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",r=this.query||{};return this.opts.timestampRequests&&(r[this.opts.timestampParam]=Up()),this.supportsBinary||(r.b64=1),this.createUri(t,r)}}const ha=vt.WebSocket||vt.MozWebSocket;class bx extends xx{createSocket(t,r,s){return Wp?new ha(t,r,s):r?new ha(t,r):new ha(t)}doWrite(t,r){this.ws.send(r)}}class wx extends Bc{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this._transport.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(t=>{const r=ix(Number.MAX_SAFE_INTEGER,this.socket.binaryType),s=t.readable.pipeThrough(r).getReader(),i=sx();i.readable.pipeTo(t.writable),this._writer=i.writable.getWriter();const o=()=>{s.read().then(({done:n,value:a})=>{n||(this.onPacket(a),o())}).catch(n=>{})};o();const c={type:"open"};this.query.sid&&(c.data=`{"sid":"${this.query.sid}"}`),this._writer.write(c).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let r=0;r{i&&wo(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}}const Cx={websocket:bx,webtransport:wx,polling:Sx},Ex=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,kx=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function bl(e){if(e.length>8e3)throw"URI too long";const t=e,r=e.indexOf("["),s=e.indexOf("]");r!=-1&&s!=-1&&(e=e.substring(0,r)+e.substring(r,s).replace(/:/g,";")+e.substring(s,e.length));let i=Ex.exec(e||""),o={},c=14;for(;c--;)o[kx[c]]=i[c]||"";return r!=-1&&s!=-1&&(o.source=t,o.host=o.host.substring(1,o.host.length-1).replace(/;/g,":"),o.authority=o.authority.replace("[","").replace("]","").replace(/;/g,":"),o.ipv6uri=!0),o.pathNames=Rx(o,o.path),o.queryKey=Tx(o,o.query),o}function Rx(e,t){const r=/\/{2,9}/g,s=t.replace(r,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&s.splice(0,1),t.slice(-1)=="/"&&s.splice(s.length-1,1),s}function Tx(e,t){const r={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(s,i,o){i&&(r[i]=o)}),r}const wl=typeof addEventListener=="function"&&typeof removeEventListener=="function",Cn=[];wl&&addEventListener("offline",()=>{Cn.forEach(e=>e())},!1);class yr extends ke{constructor(t,r){if(super(),this.binaryType=ox,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,t&&typeof t=="object"&&(r=t,t=null),t){const s=bl(t);r.hostname=s.host,r.secure=s.protocol==="https"||s.protocol==="wss",r.port=s.port,s.query&&(r.query=s.query)}else r.host&&(r.hostname=bl(r.host).host);Co(this,r),this.secure=r.secure!=null?r.secure:typeof location<"u"&&location.protocol==="https:",r.hostname&&!r.port&&(r.port=this.secure?"443":"80"),this.hostname=r.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=r.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},r.transports.forEach(s=>{const i=s.prototype.name;this.transports.push(i),this._transportsByName[i]=s}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},r),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=fx(this.opts.query)),wl&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Cn.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const r=Object.assign({},this.opts.query);r.EIO=Fp,r.transport=t,this.id&&(r.sid=this.id);const s=Object.assign({},this.opts,{query:r,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new this._transportsByName[t](s)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const t=this.opts.rememberUpgrade&&yr.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const r=this.createTransport(t);r.open(),this.setTransport(r)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",r=>this._onClose("transport close",r))}onOpen(){this.readyState="open",yr.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const r=new Error("server error");r.code=t.data,this._onError(r);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data);break}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this._getWritablePackets();this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let r=1;for(let s=0;s0&&r>this._maxPayload)return this.writeBuffer.slice(0,s);r+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const t=Date.now()>this._pingTimeoutTime;return t&&(this._pingTimeoutTime=0,wo(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,r,s){return this._sendPacket("message",t,r,s),this}send(t,r,s){return this._sendPacket("message",t,r,s),this}_sendPacket(t,r,s,i){if(typeof r=="function"&&(i=r,r=void 0),typeof s=="function"&&(i=s,s=null),this.readyState==="closing"||this.readyState==="closed")return;s=s||{},s.compress=s.compress!==!1;const o={type:t,data:r,options:s};this.emitReserved("packetCreate",o),this.writeBuffer.push(o),i&&this.once("flush",i),this.flush()}close(){const t=()=>{this._onClose("forced close"),this.transport.close()},r=()=>{this.off("upgrade",r),this.off("upgradeError",r),t()},s=()=>{this.once("upgrade",r),this.once("upgradeError",r)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?s():t()}):this.upgrading?s():t()),this}_onError(t){if(yr.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,r){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),wl&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const s=Cn.indexOf(this._offlineEventListener);s!==-1&&Cn.splice(s,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,r),this.writeBuffer=[],this._prevBufferLen=0}}}yr.protocol=Fp;class Lx extends yr{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let t=0;t{s||(r.send([{type:"ping",data:"probe"}]),r.once("packet",p=>{if(!s)if(p.type==="pong"&&p.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",r),!r)return;yr.priorWebsocketSuccess=r.name==="websocket",this.transport.pause(()=>{s||this.readyState!=="closed"&&(m(),this.setTransport(r),r.send([{type:"upgrade"}]),this.emitReserved("upgrade",r),r=null,this.upgrading=!1,this.flush())})}else{const _=new Error("probe error");_.transport=r.name,this.emitReserved("upgradeError",_)}}))};function o(){s||(s=!0,m(),r.close(),r=null)}const c=p=>{const _=new Error("probe error: "+p);_.transport=r.name,o(),this.emitReserved("upgradeError",_)};function n(){c("transport closed")}function a(){c("socket closed")}function f(p){r&&p.name!==r.name&&o()}const m=()=>{r.removeListener("open",i),r.removeListener("error",c),r.removeListener("close",n),this.off("close",a),this.off("upgrading",f)};r.once("open",i),r.once("error",c),r.once("close",n),this.once("close",a),this.once("upgrading",f),this._upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{s||r.open()},200):r.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const r=[];for(let s=0;sCx[i]).filter(i=>!!i)),super(t,s)}};function Ax(e,t="",r){let s=e;r=r||typeof location<"u"&&location,e==null&&(e=r.protocol+"//"+r.host),typeof e=="string"&&(e.charAt(0)==="/"&&(e.charAt(1)==="/"?e=r.protocol+e:e=r.host+e),/^(https?|wss?):\/\//.test(e)||(typeof r<"u"?e=r.protocol+"//"+e:e="https://"+e),s=bl(e)),s.port||(/^(http|ws)$/.test(s.protocol)?s.port="80":/^(http|ws)s$/.test(s.protocol)&&(s.port="443")),s.path=s.path||"/";const o=s.host.indexOf(":")!==-1?"["+s.host+"]":s.host;return s.id=s.protocol+"://"+o+":"+s.port+t,s.href=s.protocol+"://"+o+(r&&r.port===s.port?"":":"+s.port),s}const Ox=typeof ArrayBuffer=="function",Nx=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,Vp=Object.prototype.toString,Px=typeof Blob=="function"||typeof Blob<"u"&&Vp.call(Blob)==="[object BlobConstructor]",Bx=typeof File=="function"||typeof File<"u"&&Vp.call(File)==="[object FileConstructor]";function jc(e){return Ox&&(e instanceof ArrayBuffer||Nx(e))||Px&&e instanceof Blob||Bx&&e instanceof File}function En(e,t){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let r=0,s=e.length;r=0&&e.numthis.opts.maxAttachments)throw new Error("too many attachments");s.attachments=n}if(t.charAt(r+1)==="/"){const o=r+1;for(;++r&&!(t.charAt(r)===","||r===t.length););s.nsp=t.substring(o,r)}else s.nsp="/";const i=t.charAt(r+1);if(i!==""&&Number(i)==i){const o=r+1;for(;++r;){const c=t.charAt(r);if(c==null||Number(c)!=c){--r;break}if(r===t.length)break}s.id=Number(t.substring(o,r+1))}if(t.charAt(++r)){const o=this.tryParse(t.substr(r));if(Mc.isPayloadValid(s.type,o))s.data=o;else throw new Error("invalid payload")}return s}tryParse(t){try{return JSON.parse(t,this.opts.reviver)}catch{return!1}}static isPayloadValid(t,r){switch(t){case ie.CONNECT:return Rh(r);case ie.DISCONNECT:return r===void 0;case ie.CONNECT_ERROR:return typeof r=="string"||Rh(r);case ie.EVENT:case ie.BINARY_EVENT:return Array.isArray(r)&&(typeof r[0]=="number"||typeof r[0]=="string"&&Ix.indexOf(r[0])===-1);case ie.ACK:case ie.BINARY_ACK:return Array.isArray(r)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Hx{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const r=Mx(this.reconPack,this.buffers);return this.finishedReconstruction(),r}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const Ux=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e};function Rh(e){return Object.prototype.toString.call(e)==="[object Object]"}const zx=Object.freeze(Object.defineProperty({__proto__:null,Decoder:Mc,Encoder:Fx,get PacketType(){return ie}},Symbol.toStringTag,{value:"Module"}));function Tt(e,t,r){return e.on(t,r),function(){e.off(t,r)}}const $x=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class qp extends ke{constructor(t,r,s){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=r,s&&s.auth&&(this.auth=s.auth),this._opts=Object.assign({},s),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[Tt(t,"open",this.onopen.bind(this)),Tt(t,"packet",this.onpacket.bind(this)),Tt(t,"error",this.onerror.bind(this)),Tt(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...r){var s,i,o;if($x.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(r.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(r),this;const c={type:ie.EVENT,data:r};if(c.options={},c.options.compress=this.flags.compress!==!1,typeof r[r.length-1]=="function"){const m=this.ids++,p=r.pop();this._registerAckCallback(m,p),c.id=m}const n=(i=(s=this.io.engine)===null||s===void 0?void 0:s.transport)===null||i===void 0?void 0:i.writable,a=this.connected&&!(!((o=this.io.engine)===null||o===void 0)&&o._hasPingExpired());return this.flags.volatile&&!n||(a?(this.notifyOutgoingListeners(c),this.packet(c)):this.sendBuffer.push(c)),this.flags={},this}_registerAckCallback(t,r){var s;const i=(s=this.flags.timeout)!==null&&s!==void 0?s:this._opts.ackTimeout;if(i===void 0){this.acks[t]=r;return}const o=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let n=0;n{this.io.clearTimeoutFn(o),r.apply(this,n)};c.withError=!0,this.acks[t]=c}emitWithAck(t,...r){return new Promise((s,i)=>{const o=(c,n)=>c?i(c):s(n);o.withError=!0,r.push(o),this.emit(t,...r)})}_addToQueue(t){let r;typeof t[t.length-1]=="function"&&(r=t.pop());const s={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((i,...o)=>(this._queue[0],i!==null?s.tryCount>this._opts.retries&&(this._queue.shift(),r&&r(i)):(this._queue.shift(),r&&r(null,...o)),s.pending=!1,this._drainQueue())),this._queue.push(s),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||this._queue.length===0)return;const r=this._queue[0];r.pending&&!t||(r.pending=!0,r.tryCount++,this.flags=r.flags,this.emit.apply(this,r.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){typeof this.auth=="function"?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:ie.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,r){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,r),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(s=>String(s.id)===t)){const s=this.acks[t];delete this.acks[t],s.withError&&s.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case ie.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case ie.EVENT:case ie.BINARY_EVENT:this.onevent(t);break;case ie.ACK:case ie.BINARY_ACK:this.onack(t);break;case ie.DISCONNECT:this.ondisconnect();break;case ie.CONNECT_ERROR:this.destroy();const s=new Error(t.data.message);s.data=t.data.data,this.emitReserved("connect_error",s);break}}onevent(t){const r=t.data||[];t.id!=null&&r.push(this.ack(t.id)),this.connected?this.emitEvent(r):this.receiveBuffer.push(Object.freeze(r))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const r=this._anyListeners.slice();for(const s of r)s.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&typeof t[t.length-1]=="string"&&(this._lastOffset=t[t.length-1])}ack(t){const r=this;let s=!1;return function(...i){s||(s=!0,r.packet({type:ie.ACK,id:t,data:i}))}}onack(t){const r=this.acks[t.id];typeof r=="function"&&(delete this.acks[t.id],r.withError&&t.data.unshift(null),r.apply(this,t.data))}onconnect(t,r){this.id=t,this.recovered=r&&this._pid===r,this._pid=r,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:ie.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const r=this._anyListeners;for(let s=0;s0&&e.jitter<=1?e.jitter:0,this.attempts=0}Ts.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),r=Math.floor(t*this.jitter*e);e=Math.floor(t*10)&1?e+r:e-r}return Math.min(e,this.max)|0};Ts.prototype.reset=function(){this.attempts=0};Ts.prototype.setMin=function(e){this.ms=e};Ts.prototype.setMax=function(e){this.max=e};Ts.prototype.setJitter=function(e){this.jitter=e};class kl extends ke{constructor(t,r){var s;super(),this.nsps={},this.subs=[],t&&typeof t=="object"&&(r=t,t=void 0),r=r||{},r.path=r.path||"/socket.io",this.opts=r,Co(this,r),this.reconnection(r.reconnection!==!1),this.reconnectionAttempts(r.reconnectionAttempts||1/0),this.reconnectionDelay(r.reconnectionDelay||1e3),this.reconnectionDelayMax(r.reconnectionDelayMax||5e3),this.randomizationFactor((s=r.randomizationFactor)!==null&&s!==void 0?s:.5),this.backoff=new Ts({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(r.timeout==null?2e4:r.timeout),this._readyState="closed",this.uri=t;const i=r.parser||zx;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=r.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return t===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var r;return t===void 0?this._reconnectionDelay:(this._reconnectionDelay=t,(r=this.backoff)===null||r===void 0||r.setMin(t),this)}randomizationFactor(t){var r;return t===void 0?this._randomizationFactor:(this._randomizationFactor=t,(r=this.backoff)===null||r===void 0||r.setJitter(t),this)}reconnectionDelayMax(t){var r;return t===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,(r=this.backoff)===null||r===void 0||r.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new Dx(this.uri,this.opts);const r=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;const i=Tt(r,"open",function(){s.onopen(),t&&t()}),o=n=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",n),t?t(n):this.maybeReconnectOnOpen()},c=Tt(r,"error",o);if(this._timeout!==!1){const n=this._timeout,a=this.setTimeoutFn(()=>{i(),o(new Error("timeout")),r.close()},n);this.opts.autoUnref&&a.unref(),this.subs.push(()=>{this.clearTimeoutFn(a)})}return this.subs.push(i),this.subs.push(c),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(Tt(t,"ping",this.onping.bind(this)),Tt(t,"data",this.ondata.bind(this)),Tt(t,"error",this.onerror.bind(this)),Tt(t,"close",this.onclose.bind(this)),Tt(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(r){this.onclose("parse error",r)}}ondecoded(t){wo(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,r){let s=this.nsps[t];return s?this._autoConnect&&!s.active&&s.connect():(s=new qp(this,t,r),this.nsps[t]=s),s}_destroy(t){const r=Object.keys(this.nsps);for(const s of r)if(this.nsps[s].active)return;this._close()}_packet(t){const r=this.encoder.encode(t);for(let s=0;st()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,r){var s;this.cleanup(),(s=this.engine)===null||s===void 0||s.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,r),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const r=this.backoff.duration();this._reconnecting=!0;const s=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(i=>{i?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",i)):t.onreconnect()}))},r);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const Us={};function kn(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};const r=Ax(e,t.path||"/socket.io"),s=r.source,i=r.id,o=r.path,c=Us[i]&&o in Us[i].nsps,n=t.forceNew||t["force new connection"]||t.multiplex===!1||c;let a;return n?a=new kl(s,t):(Us[i]||(Us[i]=new kl(s,t)),a=Us[i]),r.query&&!t.query&&(t.query=r.queryKey),a.socket(r.path,t)}Object.assign(kn,{Manager:kl,Socket:qp,io:kn,connect:kn});function Wx(){const e=M.useRef(null),t=M.useRef(null),r=M.useRef(null),s=M.useRef(null);return M.useEffect(()=>{if(!e.current)return;const i=new GS.Terminal({cursorBlink:!0,fontSize:14,fontFamily:"Roboto Mono, monospace",theme:{background:"#1a1a1a",foreground:"#f0f0f0",cursor:"#d4af37",selectionBackground:"#404040",black:"#1a1a1a",red:"#c0392b",green:"#27ae60",yellow:"#f39c12",blue:"#4a90d9",magenta:"#9966cc",cyan:"#20b2aa",white:"#f0f0f0",brightBlack:"#404040",brightRed:"#ff6b6b",brightGreen:"#6abf6a",brightYellow:"#e8c962",brightBlue:"#6baee8",brightMagenta:"#c8a8e8",brightCyan:"#7de8d8",brightWhite:"#ffffff"}}),o=new JS.FitAddon;i.loadAddon(o),i.open(e.current),o.fit(),t.current=i,r.current=o;const c=kn({transports:["websocket"]});s.current=c,c.on("connect",()=>{i.writeln("Connecting to remote shell..."),c.emit("shell_create",{type:"vm"})}),c.on("shell_created",a=>{a.success?i.writeln(`\r +Connected to remote shell.`):i.writeln(`\r +Failed to create shell: ${a.error||"Unknown error"}`)}),c.on("shell_output",a=>{a.data&&i.write(a.data)}),c.on("disconnect",()=>{i.writeln(`\r +[Disconnected]`)}),i.onData(a=>{c.emit("shell_input",{data:a})});const n=()=>{o.fit()};return window.addEventListener("resize",n),()=>{window.removeEventListener("resize",n),c.emit("shell_disconnect"),c.disconnect(),i.dispose()}},[]),v.jsxs("div",{className:"h-[calc(100vh-140px)] flex flex-col",children:[v.jsx("h1",{className:"font-serif text-3xl text-primary mb-4",children:"Remote Shell"}),v.jsx("div",{ref:e,className:"flex-1 bg-[#1a1a1a] rounded-lg border border-border overflow-hidden"})]})}function Vx(){const[e,t]=M.useState("/"),[r,s]=M.useState([]),[i,o]=M.useState(!1),[c,n]=M.useState(null),{dispatch:a}=Fe(),f=async _=>{var S,b;o(!0);try{const y=await ne.post("/files/list",{path:_});y.data.success?(s(y.data.data),t(_)):a({type:"ADD_TOAST",payload:{message:y.data.error||"Failed",type:"error"}})}catch(y){a({type:"ADD_TOAST",payload:{message:((b=(S=y.response)==null?void 0:S.data)==null?void 0:b.error)||"Failed",type:"error"}})}finally{o(!1)}};M.useEffect(()=>{f("/")},[]);const m=async _=>{var S,b;try{const y=await ne.get(`/files/view?path=${encodeURIComponent(_)}`);y.data.success&&n({path:_,content:y.data.data})}catch(y){a({type:"ADD_TOAST",payload:{message:((b=(S=y.response)==null?void 0:S.data)==null?void 0:b.error)||"Failed",type:"error"}})}},p=e.split("/").filter(Boolean);return v.jsxs("div",{children:[v.jsx("h1",{className:"font-serif text-3xl text-primary mb-6",children:"File Browser"}),v.jsxs("div",{className:"flex items-center gap-2 mb-4 text-sm",children:[v.jsx("button",{onClick:()=>f("/"),className:"text-primary hover:underline",children:"/"}),p.map((_,S)=>{const b="/"+p.slice(0,S+1).join("/");return v.jsxs("span",{className:"flex items-center gap-2",children:[v.jsx("span",{className:"text-text-muted",children:"/"}),v.jsx("button",{onClick:()=>f(b),className:"text-primary hover:underline",children:_})]},S)})]}),v.jsx("div",{className:"bg-card-bg border border-border rounded-lg overflow-hidden",children:v.jsxs("table",{className:"w-full text-sm",children:[v.jsx("thead",{children:v.jsxs("tr",{className:"border-b border-border",children:[v.jsx("th",{className:"text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase",children:"Name"}),v.jsx("th",{className:"text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase",children:"Size"}),v.jsx("th",{className:"text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase",children:"Modified"}),v.jsx("th",{className:"text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase",children:"Actions"})]})}),v.jsxs("tbody",{children:[e!=="/"&&v.jsxs("tr",{className:"border-b border-border hover:bg-hover/50 cursor-pointer",onClick:()=>{const _=e.substring(0,e.lastIndexOf("/"))||"/";f(_)},children:[v.jsx("td",{className:"px-4 py-3 text-text-primary",children:".."}),v.jsx("td",{className:"px-4 py-3",children:"-"}),v.jsx("td",{className:"px-4 py-3",children:"-"}),v.jsx("td",{className:"px-4 py-3",children:"-"})]}),i?v.jsx("tr",{children:v.jsx("td",{colSpan:4,className:"px-4 py-8 text-center text-text-muted",children:"Loading..."})}):r.map(_=>v.jsxs("tr",{className:"border-b border-border last:border-0 hover:bg-hover/50 cursor-pointer",onClick:()=>_.is_dir&&f(_.path),children:[v.jsxs("td",{className:"px-4 py-3 text-text-primary",children:[_.is_dir?"📁":"📄"," ",_.name]}),v.jsx("td",{className:"px-4 py-3 text-text-muted",children:_.is_dir?"-":qx(_.size)}),v.jsx("td",{className:"px-4 py-3 text-text-muted",children:new Date(_.mod_time).toLocaleString()}),v.jsx("td",{className:"px-4 py-3",children:!_.is_dir&&v.jsx("button",{onClick:S=>{S.stopPropagation(),m(_.path)},className:"text-xs text-primary hover:underline",children:"View"})})]},_.path))]})]})}),c&&v.jsx("div",{className:"fixed inset-0 z-[70] flex items-center justify-center bg-black/60 backdrop-blur-sm",children:v.jsxs("div",{className:"bg-card-bg border border-border rounded-xl shadow-2xl w-full mx-4 max-w-4xl max-h-[80vh] flex flex-col",children:[v.jsxs("div",{className:"flex items-center justify-between px-5 py-4 border-b border-border",children:[v.jsx("h3",{className:"font-serif text-lg text-text-primary truncate",children:c.path}),v.jsx("button",{onClick:()=>n(null),className:"text-text-muted hover:text-text-primary text-xl leading-none",children:"×"})]}),v.jsx("pre",{className:"p-5 overflow-auto flex-1 text-xs font-mono text-text-secondary bg-code-bg",children:c.content})]})})]})}function qx(e){if(e===0)return"0 B";const t=1024,r=["B","KB","MB","GB"],s=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,s)).toFixed(2))+" "+r[s]}const Kx=e=>ne.get(e).then(t=>t.data);function Xx(){const[e,t]=M.useState("battlegroup"),{dispatch:r}=Fe(),{data:s}=ct("/director/battlegroup",Kx,{refreshInterval:15e3}),i=async(o,c)=>{var n,a;try{const f=await ne.post(o,c);f.data.success?r({type:"ADD_TOAST",payload:{message:"Success",type:"success"}}):r({type:"ADD_TOAST",payload:{message:f.data.error||"Failed",type:"error"}})}catch(f){r({type:"ADD_TOAST",payload:{message:((a=(n=f.response)==null?void 0:n.data)==null?void 0:a.error)||"Failed",type:"error"}})}};return v.jsxs("div",{children:[v.jsx("h1",{className:"font-serif text-3xl text-primary mb-6",children:"Director Control"}),v.jsx("div",{className:"flex gap-1 mb-6 border-b border-border",children:[{key:"battlegroup",label:"Battlegroup"},{key:"config",label:"Config"},{key:"transfer",label:"Transfer"},{key:"fls",label:"FLS"}].map(o=>v.jsx("button",{onClick:()=>t(o.key),className:`px-4 py-2.5 text-sm font-medium border-b-2 transition-colors ${e===o.key?"text-primary border-primary":"text-text-muted border-transparent hover:text-text-primary"}`,children:o.label},o.key))}),e==="battlegroup"&&v.jsxs("div",{className:"bg-card-bg border border-border rounded-lg p-5",children:[v.jsx("h3",{className:"text-text-muted text-xs uppercase tracking-wider mb-4",children:"Battlegroup State"}),s!=null&&s.success?v.jsx("pre",{className:"text-xs text-text-secondary font-mono bg-code-bg p-4 rounded overflow-auto max-h-[60vh]",children:JSON.stringify(s.data,null,2)}):v.jsx("div",{className:"text-text-muted",children:"Loading battlegroup data..."})]}),e==="config"&&v.jsxs("div",{className:"bg-card-bg border border-border rounded-lg p-5 space-y-4 max-w-xl",children:[v.jsx("h3",{className:"text-text-muted text-xs uppercase tracking-wider mb-4",children:"Update Config"}),v.jsxs("div",{children:[v.jsx("label",{className:"block text-sm text-text-muted mb-2",children:"Map Name"}),v.jsx("input",{id:"config-map",className:"w-full bg-card-bg border border-border rounded-lg px-4 py-2 text-sm",placeholder:"e.g., HaggaBasin"})]}),v.jsxs("div",{children:[v.jsx("label",{className:"block text-sm text-text-muted mb-2",children:"Config JSON"}),v.jsx("textarea",{id:"config-json",rows:6,className:"w-full bg-card-bg border border-border rounded-lg px-4 py-3 text-sm font-mono",placeholder:'{"maxPlayers": 100}'})]}),v.jsxs("div",{className:"flex gap-2",children:[v.jsx("button",{onClick:()=>{const o=document.getElementById("config-map").value,c=document.getElementById("config-json").value;i("/director/config",{map:o,config:JSON.parse(c)})},className:"px-4 py-2 bg-primary text-white rounded-lg text-sm font-medium",children:"Update Config"}),v.jsx("button",{onClick:()=>i("/director/config/clear",{}),className:"px-4 py-2 bg-danger/10 border border-danger/30 text-danger rounded-lg text-sm font-medium",children:"Clear Config"})]})]}),e==="transfer"&&v.jsxs("div",{className:"bg-card-bg border border-border rounded-lg p-5 space-y-4 max-w-xl",children:[v.jsx("h3",{className:"text-text-muted text-xs uppercase tracking-wider mb-4",children:"Transfer Rules"}),v.jsx("div",{className:"flex gap-2",children:v.jsx("button",{onClick:()=>i("/director/transfer/clear",{}),className:"px-4 py-2 bg-danger/10 border border-danger/30 text-danger rounded-lg text-sm font-medium",children:"Clear Overrides"})})]}),e==="fls"&&v.jsxs("div",{className:"bg-card-bg border border-border rounded-lg p-5 space-y-4 max-w-xl",children:[v.jsx("h3",{className:"text-text-muted text-xs uppercase tracking-wider mb-4",children:"FLS Settings"}),v.jsx("div",{className:"flex gap-2",children:v.jsx("button",{onClick:()=>i("/director/fls/clear",{}),className:"px-4 py-2 bg-danger/10 border border-danger/30 text-danger rounded-lg text-sm font-medium",children:"Clear FLS Overrides"})})]})]})}function Gx(){const[e,t]=M.useState({}),[r,s]=M.useState(!1),[i,o]=M.useState(!1),{dispatch:c}=Fe(),n=async()=>{var p,_;s(!0);try{const S=await ne.get("/settings");S.data.success&&t(S.data.data)}catch(S){c({type:"ADD_TOAST",payload:{message:((_=(p=S.response)==null?void 0:p.data)==null?void 0:_.error)||"Failed to load settings",type:"error"}})}finally{s(!1)}};M.useEffect(()=>{n()},[]);const a=async()=>{var p,_;o(!0);try{(await ne.post("/settings",e)).data.success&&c({type:"ADD_TOAST",payload:{message:"Settings saved",type:"success"}})}catch(S){c({type:"ADD_TOAST",payload:{message:((_=(p=S.response)==null?void 0:p.data)==null?void 0:_.error)||"Failed to save",type:"error"}})}finally{o(!1)}},f=(p,_)=>{t({...e,[p]:_})},m=()=>{const p=prompt("Enter new setting key:");p&&t({...e,[p]:""})};return v.jsxs("div",{children:[v.jsx("h1",{className:"font-serif text-3xl text-primary mb-6",children:"Settings"}),v.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[v.jsx("button",{onClick:n,disabled:r,className:"px-4 py-2 bg-primary text-white rounded-lg text-sm font-medium hover:bg-primary-dark disabled:opacity-50",children:r?"Loading...":"Reload"}),v.jsx("button",{onClick:a,disabled:i,className:"px-4 py-2 bg-success text-white rounded-lg text-sm font-medium hover:bg-success/80 disabled:opacity-50",children:i?"Saving...":"Save Settings"}),v.jsx("button",{onClick:m,className:"px-4 py-2 bg-card-bg border border-border text-text-primary rounded-lg text-sm font-medium hover:bg-hover",children:"Add Key"})]}),v.jsxs("div",{className:"bg-card-bg border border-border rounded-lg p-5 space-y-4 max-w-2xl",children:[Object.entries(e).length===0&&!r&&v.jsx("div",{className:"text-text-muted",children:"No settings found."}),Object.entries(e).map(([p,_])=>v.jsxs("div",{className:"grid grid-cols-[200px_1fr] gap-4 items-center",children:[v.jsx("label",{className:"text-sm text-text-secondary truncate",title:p,children:p}),v.jsx("input",{value:_,onChange:S=>f(p,S.target.value),className:"bg-card-bg border border-border rounded px-3 py-2 text-sm text-text-primary"})]},p))]})]})}function Jx(){return Dv(),null}function Qx(){return v.jsx(Lv,{children:v.jsxs(xv,{children:[v.jsx(Jx,{}),v.jsx(Mv,{children:v.jsxs(pv,{children:[v.jsx(Ve,{path:"/",element:v.jsx(R0,{})}),v.jsx(Ve,{path:"/players",element:v.jsx(mS,{})}),v.jsx(Ve,{path:"/players/:accountId",element:v.jsx(gS,{})}),v.jsx(Ve,{path:"/guilds",element:v.jsx(kS,{})}),v.jsx(Ve,{path:"/vehicles",element:v.jsx(TS,{})}),v.jsx(Ve,{path:"/buildings",element:v.jsx(DS,{})}),v.jsx(Ve,{path:"/map",element:v.jsx(OS,{})}),v.jsx(Ve,{path:"/accounts",element:v.jsx(PS,{})}),v.jsx(Ve,{path:"/server",element:v.jsx(BS,{})}),v.jsx(Ve,{path:"/admin",element:v.jsx(FS,{})}),v.jsx(Ve,{path:"/chat",element:v.jsx(XS,{})}),v.jsx(Ve,{path:"/shell",element:v.jsx(Wx,{})}),v.jsx(Ve,{path:"/files",element:v.jsx(Vx,{})}),v.jsx(Ve,{path:"/director",element:v.jsx(Xx,{})}),v.jsx(Ve,{path:"/settings",element:v.jsx(Gx,{})})]})})]})})}da.createRoot(document.getElementById("root")).render(v.jsx(bi.StrictMode,{children:v.jsx(Qx,{})})); diff --git a/frontend/dist/assets/index-BwISaj0y.css b/frontend/dist/assets/index-BwISaj0y.css new file mode 100644 index 0000000..2f8de92 --- /dev/null +++ b/frontend/dist/assets/index-BwISaj0y.css @@ -0,0 +1,32 @@ +/** + * Copyright (c) 2014 The xterm.js authors. All rights reserved. + * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) + * https://github.com/chjj/term.js + * @license MIT + * + * 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. + * + * Originally forked from (with the author's permission): + * Fabrice Bellard's javascript vt100 for jslinux: + * http://bellard.org/jslinux/ + * Copyright (c) 2011 Fabrice Bellard + * The original design remains. The terminal itself + * has been extended to include xterm CSI codes, among + * other features. + */.xterm{cursor:text;position:relative;-moz-user-select:none;user-select:none;-ms-user-select:none;-webkit-user-select:none}.xterm.focus,.xterm:focus{outline:none}.xterm .xterm-helpers{position:absolute;top:0;z-index:5}.xterm .xterm-helper-textarea{padding:0;border:0;margin:0;position:absolute;opacity:0;left:-9999em;top:0;width:0;height:0;z-index:-5;white-space:nowrap;overflow:hidden;resize:none}.xterm .composition-view{background:#000;color:#fff;display:none;position:absolute;white-space:nowrap;z-index:1}.xterm .composition-view.active{display:block}.xterm .xterm-viewport{background-color:#000;overflow-y:scroll;cursor:default;position:absolute;right:0;left:0;top:0;bottom:0}.xterm .xterm-screen{position:relative}.xterm .xterm-screen canvas{position:absolute;left:0;top:0}.xterm .xterm-scroll-area{visibility:hidden}.xterm-char-measure-element{display:inline-block;visibility:hidden;position:absolute;top:0;left:-9999em;line-height:normal}.xterm.enable-mouse-events{cursor:default}.xterm.xterm-cursor-pointer,.xterm .xterm-cursor-pointer{cursor:pointer}.xterm.column-select.focus{cursor:crosshair}.xterm .xterm-accessibility,.xterm .xterm-message{position:absolute;left:0;top:0;bottom:0;right:0;z-index:10;color:transparent;pointer-events:none}.xterm .live-region{position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden}.xterm-dim{opacity:1!important}.xterm-underline-1{text-decoration:underline}.xterm-underline-2{-webkit-text-decoration:double underline;text-decoration:double underline}.xterm-underline-3{-webkit-text-decoration:wavy underline;text-decoration:wavy underline}.xterm-underline-4{-webkit-text-decoration:dotted underline;text-decoration:dotted underline}.xterm-underline-5{-webkit-text-decoration:dashed underline;text-decoration:dashed underline}.xterm-overline{text-decoration:overline}.xterm-overline.xterm-underline-1{text-decoration:overline underline}.xterm-overline.xterm-underline-2{-webkit-text-decoration:overline double underline;text-decoration:overline double underline}.xterm-overline.xterm-underline-3{-webkit-text-decoration:overline wavy underline;text-decoration:overline wavy underline}.xterm-overline.xterm-underline-4{-webkit-text-decoration:overline dotted underline;text-decoration:overline dotted underline}.xterm-overline.xterm-underline-5{-webkit-text-decoration:overline dashed underline;text-decoration:overline dashed underline}.xterm-strikethrough{text-decoration:line-through}.xterm-screen .xterm-decoration-container .xterm-decoration{z-index:6;position:absolute}.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer{z-index:7}.xterm-decoration-overview-ruler{z-index:8;position:absolute;top:0;right:0;pointer-events:none}.xterm-decoration-top{z-index:2;position:relative}[data-theme=default]{--primary: #c9a24e;--primary-dark: #a8862e;--primary-light: #e0c97a;--bg: #f4f1ea;--card-bg: #ffffff;--text: #2c1810;--text-light: #6b5a4a;--text-muted: #9a8a7a;--border: #e0d5c7;--accent: #8b4513;--danger: #c0392b;--success: #27ae60;--nav-bg: #1a1a2e;--nav-text: #c9c4d0;--nav-active: #c9a24e;--hover: #f0ebe0;--shadow: 0 2px 8px rgba(44,24,16,.08)}[data-theme=atreides]{--primary: #2d5a27;--primary-dark: #1e3d19;--primary-light: #4a8c42;--bg: #f0f5ed;--card-bg: #ffffff;--text: #1a2e1a;--text-light: #3d4d3d;--text-muted: #6b7c6b;--border: #d4ddd4;--accent: #1e3d19;--danger: #8b2500;--success: #2d5a27;--nav-bg: #1a2e1a;--nav-text: #d4ddd4;--nav-active: #6abf6a;--hover: #e2ebe2;--shadow: 0 2px 8px rgba(30,61,25,.1)}[data-theme=harkonnen]{--primary: #ff6b00;--primary-dark: #cc5500;--primary-light: #ff8c33;--bg: #1a1a1a;--card-bg: #2d2d2d;--text: #e8e8e8;--text-light: #b0b0b0;--text-muted: #808080;--border: #404040;--accent: #ff4500;--danger: #ff0000;--success: #00cc44;--nav-bg: #000000;--nav-text: #cccccc;--nav-active: #ff6b00;--hover: #333333;--shadow: 0 2px 8px rgba(0,0,0,.4)}[data-theme=fremen]{--primary: #d4a853;--primary-dark: #b8913f;--primary-light: #e8c87a;--bg: #e8dcc8;--card-bg: #f5efe3;--text: #3d3428;--text-light: #5c4f3d;--text-muted: #8a7d66;--border: #d4cbb8;--accent: #8b6914;--danger: #a04000;--success: #6b8e23;--nav-bg: #2c2418;--nav-text: #d4cbb8;--nav-active: #d4a853;--hover: #e8dcc8;--shadow: 0 2px 8px rgba(44,36,24,.1)}[data-theme=bene-gesserit]{--primary: #a8a8a8;--primary-dark: #888888;--primary-light: #c8c8c8;--bg: #f8f8f8;--card-bg: #ffffff;--text: #2a2a2a;--text-light: #505050;--text-muted: #787878;--border: #e0e0e0;--accent: #606060;--danger: #c41e3a;--success: #2e8b57;--nav-bg: #1a1a1a;--nav-text: #d0d0d0;--nav-active: #ffffff;--hover: #f0f0f0;--shadow: 0 2px 8px rgba(0,0,0,.08)}[data-theme=spacing-guild]{--primary: #4a90d9;--primary-dark: #2e6ab3;--primary-light: #6baee8;--bg: #1a1a2e;--card-bg: #252540;--text: #e0e0f0;--text-light: #a0a0c0;--text-muted: #707090;--border: #3a3a50;--accent: #6b5b95;--danger: #d94545;--success: #45d985;--nav-bg: #0f0f1a;--nav-text: #b0b0d0;--nav-active: #4a90d9;--hover: #2a2a40;--shadow: 0 2px 8px rgba(0,0,0,.3)}[data-theme=emperor]{--primary: #d4af37;--primary-dark: #b8962f;--primary-light: #e8c962;--bg: #1a1a1a;--card-bg: #2a2a2a;--text: #f0f0f0;--text-light: #c0c0c0;--text-muted: #808080;--border: #404040;--accent: #d4af37;--danger: #c0392b;--success: #27ae60;--nav-bg: #0d0d0d;--nav-text: #d4d4d4;--nav-active: #d4af37;--hover: #333333;--shadow: 0 2px 8px rgba(0,0,0,.4)}[data-theme=corrino]{--primary: #8b0000;--primary-dark: #5c0000;--primary-light: #c43030;--bg: #f5f0f0;--card-bg: #ffffff;--text: #2a1515;--text-light: #5a3535;--text-muted: #8a5555;--border: #e0d5d5;--accent: #a01010;--danger: #8b0000;--success: #2d5a27;--nav-bg: #1a0a0a;--nav-text: #d4c4c4;--nav-active: #ff6b6b;--hover: #f0e8e8;--shadow: 0 2px 8px rgba(90,0,0,.1)}[data-theme=mentat]{--primary: #008b8b;--primary-dark: #006666;--primary-light: #20b2aa;--bg: #e8f4f4;--card-bg: #ffffff;--text: #1a2a2a;--text-light: #3d5050;--text-muted: #6b8080;--border: #d4e0e0;--accent: #006666;--danger: #c44569;--success: #008b8b;--nav-bg: #0a1a1a;--nav-text: #c4d4d4;--nav-active: #00ced1;--hover: #e0f0f0;--shadow: 0 2px 8px rgba(0,60,60,.1)}[data-theme=sardaukar]{--primary: #cd853f;--primary-dark: #a0522d;--primary-light: #deb887;--bg: #f5ebe0;--card-bg: #ffffff;--text: #2a2018;--text-light: #5a4a38;--text-muted: #8a7a68;--border: #e0d5c8;--accent: #8b4513;--danger: #8b0000;--success: #6b8e23;--nav-bg: #1a140c;--nav-text: #d4c8b8;--nav-active: #cd853f;--hover: #f0e8e0;--shadow: 0 2px 8px rgba(60,40,20,.1)}[data-theme=tleilax]{--primary: #4a0080;--primary-dark: #2d0050;--primary-light: #6b20b0;--bg: #1a1a24;--card-bg: #252530;--text: #e0e0e8;--text-light: #a0a0b0;--text-muted: #707080;--border: #404050;--accent: #6b0099;--danger: #c41e3a;--success: #00c080;--nav-bg: #0a0a10;--nav-text: #b0b0c0;--nav-active: #9966cc;--hover: #2a2a38;--shadow: 0 2px 8px rgba(0,0,0,.4)}[data-theme=ordos]{--primary: #2e8b57;--primary-dark: #1c5c3a;--primary-light: #3cb371;--bg: #e8f5f0;--card-bg: #ffffff;--text: #1a2e22;--text-light: #3d5045;--text-muted: #6b8075;--border: #d4e0d8;--accent: #1c5c3a;--danger: #c45c3a;--success: #2e8b57;--nav-bg: #0a1a12;--nav-text: #c4d8d0;--nav-active: #3cb371;--hover: #e0f0e8;--shadow: 0 2px 8px rgba(20,60,40,.1)}[data-theme=ix]{--primary: #4169e1;--primary-dark: #2c4db8;--primary-light: #6495ed;--bg: #e8edf8;--card-bg: #ffffff;--text: #1a2248;--text-light: #3d4470;--text-muted: #6b7098;--border: #d0d8e8;--accent: #2c4db8;--danger: #c44569;--success: #32cd32;--nav-bg: #0a1028;--nav-text: #c0c8d8;--nav-active: #6495ed;--hover: #e0e8f0;--shadow: 0 2px 8px rgba(30,50,100,.15)}[data-theme=choam]{--primary: #b8860b;--primary-dark: #8b6508;--primary-light: #daa520;--bg: #faf8f0;--card-bg: #ffffff;--text: #2a2820;--text-light: #5a5848;--text-muted: #8a8878;--border: #e8e4d8;--accent: #8b6508;--danger: #b22222;--success: #228b22;--nav-bg: #1a180c;--nav-text: #d4d0c0;--nav-active: #daa520;--hover: #f0ece0;--shadow: 0 2px 8px rgba(60,50,20,.1)}*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:Inter,sans-serif;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:Roboto Mono,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}:root{--primary: #d4af37;--primary-dark: #b8962f;--primary-light: #e8c962;--bg: #1a1a1a;--card-bg: #2a2a2a;--text: #f0f0f0;--text-light: #c0c0c0;--text-muted: #808080;--border: #404040;--accent: #d4af37;--danger: #c0392b;--success: #27ae60;--nav-bg: #0d0d0d;--nav-text: #d4d4d4;--nav-active: #d4af37;--hover: #333333;--shadow: 0 2px 8px rgba(0,0,0,.4);--table-header: #333333;--code-bg: #222222}body{font-family:Inter,sans-serif;background-color:var(--bg);color:var(--text)}h1,h2,h3{font-family:Playfair Display,serif}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.sticky{position:sticky}.inset-0{top:0;right:0;bottom:0;left:0}.bottom-4{bottom:1rem}.left-3{left:.75rem}.left-4{left:1rem}.right-0{right:0}.right-6{right:1.5rem}.top-0{top:0}.top-16{top:4rem}.top-3{top:.75rem}.z-50{z-index:50}.z-\[100\]{z-index:100}.z-\[70\]{z-index:70}.mx-4{margin-left:1rem;margin-right:1rem}.mx-auto{margin-left:auto;margin-right:auto}.mb-1{margin-bottom:.25rem}.mb-2{margin-bottom:.5rem}.mb-3{margin-bottom:.75rem}.mb-4{margin-bottom:1rem}.mb-6{margin-bottom:1.5rem}.ml-auto{margin-left:auto}.mr-8{margin-right:2rem}.mt-1{margin-top:.25rem}.mt-2{margin-top:.5rem}.mt-4{margin-top:1rem}.mt-8{margin-top:2rem}.block{display:block}.inline-block{display:inline-block}.flex{display:flex}.table{display:table}.grid{display:grid}.h-2{height:.5rem}.h-2\.5{height:.625rem}.h-4{height:1rem}.h-6{height:1.5rem}.h-\[52px\]{height:52px}.h-\[calc\(100vh-140px\)\]{height:calc(100vh - 140px)}.h-full{height:100%}.max-h-64{max-height:16rem}.max-h-\[60vh\]{max-height:60vh}.max-h-\[80vh\]{max-height:80vh}.min-h-screen{min-height:100vh}.w-10{width:2.5rem}.w-12{width:3rem}.w-2{width:.5rem}.w-2\.5{width:.625rem}.w-32{width:8rem}.w-4{width:1rem}.w-56{width:14rem}.w-6{width:1.5rem}.w-8{width:2rem}.w-full{width:100%}.min-w-\[240px\]{min-width:240px}.max-w-2xl{max-width:42rem}.max-w-3xl{max-width:48rem}.max-w-4xl{max-width:56rem}.max-w-\[1600px\]{max-width:1600px}.max-w-md{max-width:28rem}.max-w-xl{max-width:36rem}.flex-1{flex:1 1 0%}.cursor-grab{cursor:grab}.cursor-pointer{cursor:pointer}.select-none{-webkit-user-select:none;-moz-user-select:none;user-select:none}.resize-y{resize:vertical}.resize{resize:both}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.grid-cols-\[200px_1fr\]{grid-template-columns:200px 1fr}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-center{align-items:center}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-1{gap:.25rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.gap-6{gap:1.5rem}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.75rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.75rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.whitespace-nowrap{white-space:nowrap}.break-all{word-break:break-all}.rounded{border-radius:.25rem}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:.5rem}.rounded-xl{border-radius:.75rem}.border{border-width:1px}.border-b{border-bottom-width:1px}.border-b-2{border-bottom-width:2px}.border-t{border-top-width:1px}.border-border{border-color:var(--border)}.border-nav-active{border-color:var(--nav-active)}.border-primary{border-color:var(--primary)}.border-transparent{border-color:transparent}.border-yellow-500\/20{border-color:#eab30833}.border-yellow-500\/30{border-color:#eab3084d}.bg-\[\#1a1a1a\]{--tw-bg-opacity: 1;background-color:rgb(26 26 26 / var(--tw-bg-opacity, 1))}.bg-background{background-color:var(--bg)}.bg-black\/60{background-color:#0009}.bg-border{background-color:var(--border)}.bg-card-bg{background-color:var(--card-bg)}.bg-nav-bg{background-color:var(--nav-bg)}.bg-primary{background-color:var(--primary)}.bg-success{background-color:var(--success)}.bg-yellow-500\/10{background-color:#eab3081a}.p-4{padding:1rem}.p-5{padding:1.25rem}.p-6{padding:1.5rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-5{padding-left:1.25rem;padding-right:1.25rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.py-0\.5{padding-top:.125rem;padding-bottom:.125rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-2\.5{padding-top:.625rem;padding-bottom:.625rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-8{padding-top:2rem;padding-bottom:2rem}.pl-10{padding-left:2.5rem}.pt-4{padding-top:1rem}.text-left{text-align:left}.text-center{text-align:center}.text-right{text-align:right}.font-mono{font-family:Roboto Mono,monospace}.font-serif{font-family:Playfair Display,serif}.text-2xl{font-size:1.5rem;line-height:2rem}.text-3xl{font-size:1.875rem;line-height:2.25rem}.text-\[10px\]{font-size:10px}.text-\[11px\]{font-size:11px}.text-\[13px\]{font-size:13px}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-medium{font-weight:500}.font-semibold{font-weight:600}.uppercase{text-transform:uppercase}.capitalize{text-transform:capitalize}.leading-none{line-height:1}.tracking-wide{letter-spacing:.025em}.tracking-wider{letter-spacing:.05em}.tracking-widest{letter-spacing:.1em}.text-accent{color:var(--accent)}.text-danger{color:var(--danger)}.text-nav-active{color:var(--nav-active)}.text-nav-text{color:var(--nav-text)}.text-primary{color:var(--primary)}.text-success{color:var(--success)}.text-text-muted{color:var(--text-muted)}.text-text-primary{color:var(--text)}.text-text-secondary{color:var(--text-light)}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.text-yellow-400{--tw-text-opacity: 1;color:rgb(250 204 21 / var(--tw-text-opacity, 1))}.placeholder-text-muted::-moz-placeholder{color:var(--text-muted)}.placeholder-text-muted::placeholder{color:var(--text-muted)}.shadow-2xl{--tw-shadow: 0 25px 50px -12px rgb(0 0 0 / .25);--tw-shadow-colored: 0 25px 50px -12px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-card{--tw-shadow: var(--shadow);--tw-shadow-colored: var(--shadow);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-md{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-xl{--tw-shadow: 0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1);--tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.backdrop-blur-sm{--tw-backdrop-blur: blur(4px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.last\:border-0:last-child{border-width:0px}.hover\:bg-hover:hover{background-color:var(--hover)}.hover\:bg-primary-dark:hover{background-color:var(--primary-dark)}.hover\:bg-white\/5:hover{background-color:#ffffff0d}.hover\:text-text-primary:hover{color:var(--text)}.hover\:text-white:hover{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.hover\:underline:hover{text-decoration-line:underline}.focus\:border-primary:focus{border-color:var(--primary)}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\:ring-1:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-primary:focus{--tw-ring-color: var(--primary)}.active\:cursor-grabbing:active{cursor:grabbing}.disabled\:opacity-50:disabled{opacity:.5}@media (min-width: 640px){.sm\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}}@media (min-width: 768px){.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}}@media (min-width: 1024px){.lg\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.lg\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}} diff --git a/frontend/dist/index.html b/frontend/dist/index.html new file mode 100644 index 0000000..7559701 --- /dev/null +++ b/frontend/dist/index.html @@ -0,0 +1,16 @@ + + + + + + + Dune Admin Dashboard + + + + + + +
+ + diff --git a/frontend/index.html b/frontend/index.html new file mode 100644 index 0000000..b5898d0 --- /dev/null +++ b/frontend/index.html @@ -0,0 +1,15 @@ + + + + + + + Dune Admin Dashboard + + + + +
+ + + diff --git a/frontend/package.json b/frontend/package.json new file mode 100644 index 0000000..0ed7a40 --- /dev/null +++ b/frontend/package.json @@ -0,0 +1,31 @@ +{ + "name": "dune-dashboard-frontend", + "private": true, + "version": "1.0.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "tsc && vite build", + "preview": "vite preview" + }, + "dependencies": { + "react": "^18.2.0", + "react-dom": "^18.2.0", + "react-router-dom": "^6.22.0", + "axios": "^1.6.7", + "swr": "^2.2.4", + "xterm": "^5.3.0", + "xterm-addon-fit": "^0.8.0", + "socket.io-client": "^4.7.4" + }, + "devDependencies": { + "@types/react": "^18.2.55", + "@types/react-dom": "^18.2.19", + "@vitejs/plugin-react": "^4.2.1", + "autoprefixer": "^10.4.17", + "postcss": "^8.4.35", + "tailwindcss": "^3.4.1", + "typescript": "^5.3.3", + "vite": "^5.1.0" + } +} diff --git a/frontend/postcss.config.js b/frontend/postcss.config.js new file mode 100644 index 0000000..2e7af2b --- /dev/null +++ b/frontend/postcss.config.js @@ -0,0 +1,6 @@ +export default { + plugins: { + tailwindcss: {}, + autoprefixer: {}, + }, +} diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx new file mode 100644 index 0000000..d47d440 --- /dev/null +++ b/frontend/src/App.tsx @@ -0,0 +1,39 @@ +import { BrowserRouter, Routes, Route } from 'react-router-dom' +import { AppProvider } from './stores/AppContext' +import { useRealtime } from './hooks/useRealtime' +import AppShell from './components/layout/AppShell' +import Overview from './components/overview/Overview' +import PlayerExplorer from './components/players/PlayerExplorer' +import GuildManager from './components/guilds/GuildManager' +import ServerControl from './components/server/ServerControl' +import AdminTools from './components/admin/AdminTools' +import ChatMonitor from './components/chat/ChatMonitor' +import Terminal from './components/shell/Terminal' + +function RealtimeInit() { + useRealtime() + return null +} + +function App() { + return ( + + + + + + } /> + } /> + } /> + } /> + } /> + } /> + } /> + + + + + ) +} + +export default App diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts new file mode 100644 index 0000000..45e489b --- /dev/null +++ b/frontend/src/api/client.ts @@ -0,0 +1,21 @@ +import axios from 'axios' + +const client = axios.create({ + baseURL: '/api', + headers: { + 'Content-Type': 'application/json', + }, + timeout: 30000, +}) + +client.interceptors.response.use( + (response) => response, + (error) => { + if (error.response?.status === 401) { + window.location.href = '/login' + } + return Promise.reject(error) + } +) + +export default client diff --git a/frontend/src/components/admin/AdminTools.tsx b/frontend/src/components/admin/AdminTools.tsx new file mode 100644 index 0000000..24ac4e2 --- /dev/null +++ b/frontend/src/components/admin/AdminTools.tsx @@ -0,0 +1,419 @@ +import { useState } from 'react' +import client from '../../api/client' +import { useApp } from '../../stores/AppContext' + +const SCOPE_OPTIONS = ['all', 'server', 'partition'] +const SERVER_OPTIONS = ['na', 'eu', 'sea', 'sa', 'oc'] +const PARTITION_OPTIONS = ['parrish', 'sietch', 'bazar'] + +export default function AdminTools() { + const [tab, setTab] = useState<'broadcast' | 'economy' | 'world' | 'character' | 'functions' | 'raw' | 'audit'>('broadcast') + const { dispatch } = useApp() + + return ( +
+

Admin Tools

+ +
+ {([ + { key: 'broadcast', label: 'Broadcast' }, + { key: 'economy', label: 'Economy' }, + { key: 'world', label: 'World' }, + { key: 'character', label: 'Character' }, + { key: 'functions', label: 'Functions' }, + { key: 'raw', label: 'Raw Query' }, + { key: 'audit', label: 'Audit Log' }, + ] as const).map((t) => ( + + ))} +
+ + {tab === 'broadcast' && } + {tab === 'economy' && } + {tab === 'world' && } + {tab === 'character' && } + {tab === 'functions' && } + {tab === 'raw' && } + {tab === 'audit' && } +
+ ) +} + +function BroadcastTab({ dispatch }: { dispatch: any }) { + const [message, setMessage] = useState('') + const [scope, setScope] = useState('all') + const [server, setServer] = useState('na') + const [partition, setPartition] = useState('parrish') + const [sending, setSending] = useState(false) + + const handleSend = async () => { + if (!message.trim()) return + setSending(true) + try { + const payload: any = { message: message.trim() } + if (scope === 'server') payload.server = server + if (scope === 'partition') { + payload.server = server + payload.partition = partition + } + const res = await client.post('/broadcast', payload) + if (res.data.success) { + dispatch({ type: 'ADD_TOAST', payload: { message: 'Broadcast sent', type: 'success' } }) + setMessage('') + } else { + dispatch({ type: 'ADD_TOAST', payload: { message: res.data.error || 'Failed', type: 'error' } }) + } + } catch (e: any) { + dispatch({ type: 'ADD_TOAST', payload: { message: e.response?.data?.error || 'Failed', type: 'error' } }) + } finally { + setSending(false) + } + } + + return ( +
+
+
+ +
+ {SCOPE_OPTIONS.map((s) => ( + + ))} +
+
+ + {scope !== 'all' && ( +
+ + +
+ )} + + {scope === 'partition' && ( +
+ + +
+ )} + +
+ +