diff --git a/eaglercraft-saveeditor/PROVENANCE.json b/eaglercraft-saveeditor/PROVENANCE.json
new file mode 100644
index 0000000..c33c24a
--- /dev/null
+++ b/eaglercraft-saveeditor/PROVENANCE.json
@@ -0,0 +1,46 @@
+{
+ "slug": "eaglercraft-saveeditor",
+ "name": "Eaglercraft Save Editor (RePack)",
+ "category": "tool",
+ "mc_version": "any",
+ "author": "ayqshi",
+ "license": "MIT",
+ "upstream_ref": "main",
+ "sha256": "67c8f1baeb3404a271999c9cdbe0e2989343f4c279f2220f64dc8fc0482b0206",
+ "size": 5553951,
+ "storage": {
+ "git_path": null,
+ "fs_url": null
+ },
+ "play": {
+ "sandbox_url": "https://play-archive.eaglercraft.tech/eaglercraft-saveeditor/",
+ "sandbox_attr": "allow-scripts allow-downloads",
+ "network_notes": "Browser-runnable world and profile editor"
+ },
+ "sources": [
+ {
+ "url": "https://github.com/ayqshi/Eaglercraft-SaveEditor",
+ "retrieved_at": "2026-11-28T03:10:30Z",
+ "type": "upstream",
+ "notes": "Source repository on GitHub"
+ },
+ {
+ "url": "https://ayqshi.github.io/Eaglercraft-SaveEditor/",
+ "retrieved_at": "2026-11-28T03:10:30Z",
+ "type": "other",
+ "notes": "Live web application on GitHub Pages"
+ }
+ ],
+ "vetting": {
+ "verdict": "clean",
+ "tools": [
+ "vet-static.mjs",
+ "virustotal-hash",
+ "static-code-review"
+ ],
+ "date": "2026-11-28",
+ "notes": "Uses navigator.clipboard.writeText for copy buttons in index.html:173,188; main.js:1 is a benign scanner hit on MINECRAFT_ITEMS_DB.",
+ "reviewer": "vet-gemini"
+ },
+ "large_files_omitted_from_git": []
+}
diff --git a/eaglercraft-saveeditor/README.md b/eaglercraft-saveeditor/README.md
new file mode 100644
index 0000000..70e0c7d
--- /dev/null
+++ b/eaglercraft-saveeditor/README.md
@@ -0,0 +1,11 @@
+# Eaglercraft Save Editor (RePack)
+
+Web-based EPK file extractor, viewer, editor, and repacker for Eaglercraft singleplayer world saves and player data. Inspects file hierarchies and parses NBT structures.
+
+- **Archive page:** https://archive.eaglercraft.tech/entries/eaglercraft-saveeditor.html
+- **Play:** https://play-archive.eaglercraft.tech/eaglercraft-saveeditor/
+- **MC Version:** any
+- **Author:** ayqshi
+- **License:** MIT
+- **SHA-256:** `67c8f1baeb3404a271999c9cdbe0e2989343f4c279f2220f64dc8fc0482b0206`
+- **Vetting:** clean (2026-11-28)
diff --git a/eaglercraft-saveeditor/files/.github/ISSUE_TEMPLATE/feature_request.md b/eaglercraft-saveeditor/files/.github/ISSUE_TEMPLATE/feature_request.md
new file mode 100644
index 0000000..bbcbbe7
--- /dev/null
+++ b/eaglercraft-saveeditor/files/.github/ISSUE_TEMPLATE/feature_request.md
@@ -0,0 +1,20 @@
+---
+name: Feature request
+about: Suggest an idea for this project
+title: ''
+labels: ''
+assignees: ''
+
+---
+
+**Is your feature request related to a problem? Please describe.**
+A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
+
+**Describe the solution you'd like**
+A clear and concise description of what you want to happen.
+
+**Describe alternatives you've considered**
+A clear and concise description of any alternative solutions or features you've considered.
+
+**Additional context**
+Add any other context or screenshots about the feature request here.
diff --git a/eaglercraft-saveeditor/files/CODE_OF_CONDUCT.md b/eaglercraft-saveeditor/files/CODE_OF_CONDUCT.md
new file mode 100644
index 0000000..11dc862
--- /dev/null
+++ b/eaglercraft-saveeditor/files/CODE_OF_CONDUCT.md
@@ -0,0 +1,128 @@
+# Contributor Covenant Code of Conduct
+
+## Our Pledge
+
+We as members, contributors, and leaders pledge to make participation in our
+community a harassment-free experience for everyone, regardless of age, body
+size, visible or invisible disability, ethnicity, sex characteristics, gender
+identity and expression, level of experience, education, socio-economic status,
+nationality, personal appearance, race, religion, or sexual identity
+and orientation.
+
+We pledge to act and interact in ways that contribute to an open, welcoming,
+diverse, inclusive, and healthy community.
+
+## Our Standards
+
+Examples of behavior that contributes to a positive environment for our
+community include:
+
+* Demonstrating empathy and kindness toward other people
+* Being respectful of differing opinions, viewpoints, and experiences
+* Giving and gracefully accepting constructive feedback
+* Accepting responsibility and apologizing to those affected by our mistakes,
+ and learning from the experience
+* Focusing on what is best not just for us as individuals, but for the
+ overall community
+
+Examples of unacceptable behavior include:
+
+* The use of sexualized language or imagery, and sexual attention or
+ advances of any kind
+* Trolling, insulting or derogatory comments, and personal or political attacks
+* Public or private harassment
+* Publishing others' private information, such as a physical or email
+ address, without their explicit permission
+* Other conduct which could reasonably be considered inappropriate in a
+ professional setting
+
+## Enforcement Responsibilities
+
+Community leaders are responsible for clarifying and enforcing our standards of
+acceptable behavior and will take appropriate and fair corrective action in
+response to any behavior that they deem inappropriate, threatening, offensive,
+or harmful.
+
+Community leaders have the right and responsibility to remove, edit, or reject
+comments, commits, code, wiki edits, issues, and other contributions that are
+not aligned to this Code of Conduct, and will communicate reasons for moderation
+decisions when appropriate.
+
+## Scope
+
+This Code of Conduct applies within all community spaces, and also applies when
+an individual is officially representing the community in public spaces.
+Examples of representing our community include using an official e-mail address,
+posting via an official social media account, or acting as an appointed
+representative at an online or offline event.
+
+## Enforcement
+
+Instances of abusive, harassing, or otherwise unacceptable behavior may be
+reported to the community leaders responsible for enforcement at
+THE ISSUES PAGE.
+All complaints will be reviewed and investigated promptly and fairly.
+
+All community leaders are obligated to respect the privacy and security of the
+reporter of any incident.
+
+## Enforcement Guidelines
+
+Community leaders will follow these Community Impact Guidelines in determining
+the consequences for any action they deem in violation of this Code of Conduct:
+
+### 1. Correction
+
+**Community Impact**: Use of inappropriate language or other behavior deemed
+unprofessional or unwelcome in the community.
+
+**Consequence**: A private, written warning from community leaders, providing
+clarity around the nature of the violation and an explanation of why the
+behavior was inappropriate. A public apology may be requested.
+
+### 2. Warning
+
+**Community Impact**: A violation through a single incident or series
+of actions.
+
+**Consequence**: A warning with consequences for continued behavior. No
+interaction with the people involved, including unsolicited interaction with
+those enforcing the Code of Conduct, for a specified period of time. This
+includes avoiding interactions in community spaces as well as external channels
+like social media. Violating these terms may lead to a temporary or
+permanent ban.
+
+### 3. Temporary Ban
+
+**Community Impact**: A serious violation of community standards, including
+sustained inappropriate behavior.
+
+**Consequence**: A temporary ban from any sort of interaction or public
+communication with the community for a specified period of time. No public or
+private interaction with the people involved, including unsolicited interaction
+with those enforcing the Code of Conduct, is allowed during this period.
+Violating these terms may lead to a permanent ban.
+
+### 4. Permanent Ban
+
+**Community Impact**: Demonstrating a pattern of violation of community
+standards, including sustained inappropriate behavior, harassment of an
+individual, or aggression toward or disparagement of classes of individuals.
+
+**Consequence**: A permanent ban from any sort of public interaction within
+the community.
+
+## Attribution
+
+This Code of Conduct is adapted from the [Contributor Covenant][homepage],
+version 2.0, available at
+https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
+
+Community Impact Guidelines were inspired by [Mozilla's code of conduct
+enforcement ladder](https://github.com/mozilla/diversity).
+
+[homepage]: https://www.contributor-covenant.org
+
+For answers to common questions about this code of conduct, see the FAQ at
+https://www.contributor-covenant.org/faq. Translations are available at
+https://www.contributor-covenant.org/translations.
diff --git a/eaglercraft-saveeditor/files/CONTRIBUTING.md b/eaglercraft-saveeditor/files/CONTRIBUTING.md
new file mode 100644
index 0000000..d6f54b9
--- /dev/null
+++ b/eaglercraft-saveeditor/files/CONTRIBUTING.md
@@ -0,0 +1,37 @@
+# Contributing to RePack
+
+Thank you for considering contributing to RePack! We appreciate your help in making this project better. Please follow the guidelines below to ensure a smooth contribution process.
+
+## How to Contribute
+
+1. **Fork the Repository**: Click the "Fork" button at the top right of the repository page to create your own copy of the project.
+
+2. **Clone Your Fork**: Clone your forked repository to your local machine using the following command:
+ git clone https://github.com/ayqshi/RePack.git
+Create a Branch: Create a new branch for your feature or bug fix:
+
+git checkout -b my-feature-branch
+Make Changes: Make your changes in the codebase. Be sure to follow the project's coding style and conventions.
+
+Test Your Changes: Run any tests to ensure your changes work as expected. If applicable, add new tests for your changes.
+
+Commit Your Changes: Commit your changes with a clear and descriptive commit message:
+
+git commit -m "Add a brief description of your changes"
+Push to Your Fork: Push your changes to your forked repository:
+
+git push origin my-feature-branch
+Create a Pull Request: Go to the original repository and click on the "Pull Requests" tab. Click the "New Pull Request" button and select your branch. Provide a clear description of your changes and submit the pull request.
+
+# Guidelines
+Code Style: Please adhere to the coding style used in the project. Consistency is key to maintaining readability.
+Documentation: If you add new features or make changes, please update the documentation accordingly.
+Issue Tracking: If you are fixing a bug or implementing a feature, please reference the relevant issue in your pull request description.
+Reporting Issues
+If you encounter any issues or have suggestions for improvements, please open an issue in the repository. Be sure to provide as much detail as possible to help us understand the problem.
+
+## Code of Conduct
+By participating in this project, you agree to abide by our Code of Conduct.
+
+## Thank You!
+Thank you for your interest in contributing to RePack! We look forward to your contributions and appreciate your help in making this project better.
diff --git a/eaglercraft-saveeditor/files/LICENSE b/eaglercraft-saveeditor/files/LICENSE
new file mode 100644
index 0000000..1c376cf
--- /dev/null
+++ b/eaglercraft-saveeditor/files/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2025 Ayashi
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/eaglercraft-saveeditor/files/README.md b/eaglercraft-saveeditor/files/README.md
new file mode 100644
index 0000000..1846144
--- /dev/null
+++ b/eaglercraft-saveeditor/files/README.md
@@ -0,0 +1,178 @@
+# RePack — Eaglercraft Save Editor
+> **Status: Official Launch**
+>
+> This project is still under active development but is near completion. Expect bugs, rough edges, and incomplete features. If you are not comfortable troubleshooting issues on your own, you may want to wait for a more stable version.
+>
+> If you are interested in helping improve the project—especially usability and simplicity—contributions are welcome.
+> Reach out (discord): **@ayqshi**
+
+---
+
+## What This Project Is
+
+**RePack** is a browser-based tool for inspecting, editing, and rebuilding `.epk` save files used in Eaglercraft.
+
+It is designed for users who want more control over their world data—whether that means exploring file contents, modifying NBT data, or understanding how `.epk` archives are structured internally.
+
+---
+# ROADMAP
+- Fixing non functional feats
+- Making functional bookmarklets (EPK scraper, In-Game Mod Menu)
+- .ZIP support
+## Features
+
+### EPK Extraction
+
+Decompile `.epk` archives and access their internal files.
+
+* View the full contents of a save
+* Understand file structure and layout
+* No external tools required
+
+---
+
+### NBT Parsing (Readable JSON)
+
+Automatically converts `.dat` (NBT) files into structured JSON.
+
+* Makes complex binary data readable
+* Easier inspection of player and world data
+* Simplifies editing workflows
+
+---
+
+### File Editing
+
+Edit supported file types directly in the browser:
+
+* JSON (NBT data)
+* Plain text files
+
+Changes are applied in real time and reflected in the repacked archive.
+
+---
+
+### EPK Repacking
+
+Rebuild a valid `.epk` archive after making edits.
+
+* Preserves original structure
+* Automatically re-compresses files when required (GZIP)
+* Designed to minimize manual intervention
+
+---
+
+### Integrity Checks
+
+Basic validation is included to reduce the chance of corruption:
+
+* Header and footer verification
+* CRC32 checks for file data consistency
+
+---
+
+### Binary File Handling
+
+Files that cannot be displayed are still preserved:
+
+* Shown as placeholders in the UI
+* Included unchanged during repacking
+
+---
+
+## Usage
+
+1. In Eaglercraft:
+
+ * Select your world
+ * Click **Backup** and export as `.epk`
+
+2. In RePack:
+
+ * Open the tool (beta)
+ * Upload your `.epk` file
+
+3. Browse and edit:
+
+ * Select a file from the extracted list
+ * Its contents will appear in the editor panel
+
+4. Repack:
+
+ * Save your changes
+ * Download the rebuilt `.epk` file
+
+---
+
+## How It Works
+
+RePack runs entirely in your browser using JavaScript. Files are processed locally and are not uploaded to any server.
+
+### EPK Format Overview
+
+An `.epk` archive contains:
+
+* A header
+* Version information
+* File count (stored as Big-Endian)
+* A metadata table for each file:
+
+ * Name
+ * Size
+ * Offset
+ * Compression type
+ * CRC32 checksum
+* File data blocks
+* A footer
+
+Most numeric values are stored as Little-Endian, except for the file count, which uses Big-Endian encoding.
+
+---
+
+### Internal Processing
+
+When loading a file:
+
+* The archive structure is parsed
+* Metadata and offsets are read
+* Files are decompressed if necessary
+* NBT data is converted into JSON
+
+When repacking:
+
+* Metadata is rebuilt
+* Files are recompressed where required
+* CRC32 values are recalculated
+* A valid `.epk` archive is generated
+
+---
+
+## Dependencies
+
+* **Pako.js** — GZIP compression and decompression
+* **NBT.js** — Parsing and handling NBT data
+
+---
+
+## Limitations
+
+* Some edge cases may fail during extraction or repacking
+* User interface is minimal and still evolving
+* Binary files cannot be edited
+* Error handling is not yet comprehensive
+
+---
+
+## Contributing
+
+Feedback and contributions are encouraged, especially in areas like:
+
+* Simplifying the user experience
+* Improving error handling
+* Expanding file support
+
+---
+
+## Notes
+
+This tool is intended for users who want direct access to and control over their save data. It prioritizes transparency and functionality over polish at this stage of development.
diff --git a/eaglercraft-saveeditor/files/SECURITY.md b/eaglercraft-saveeditor/files/SECURITY.md
new file mode 100644
index 0000000..d1cbddc
--- /dev/null
+++ b/eaglercraft-saveeditor/files/SECURITY.md
@@ -0,0 +1,23 @@
+# Security Policy
+
+## Reporting a Vulnerability
+
+If you discover a security vulnerability within this project, please report it by sending me a message on snapchat: @ayqshi.
+
+Please include the following information in your report:
+
+- A description of the vulnerability
+- Steps to reproduce the issue
+- Any relevant screenshots or logs
+
+## Supported Versions
+
+We only support the latest version of the project. Older versions may not receive security updates.
+
+## Security Updates
+
+We will make every effort to respond to security vulnerabilities in a timely manner. Security updates will be released as soon as possible.
+
+## Acknowledgements
+
+We appreciate the efforts of the community in helping us improve the security of this project. If you report a vulnerability, we will acknowledge your contribution in the release notes if you wish.
diff --git a/eaglercraft-saveeditor/files/epk.png b/eaglercraft-saveeditor/files/epk.png
new file mode 100644
index 0000000..8159a68
Binary files /dev/null and b/eaglercraft-saveeditor/files/epk.png differ
diff --git a/eaglercraft-saveeditor/files/example_world.epk b/eaglercraft-saveeditor/files/example_world.epk
new file mode 100644
index 0000000..39f5b3a
Binary files /dev/null and b/eaglercraft-saveeditor/files/example_world.epk differ
diff --git a/eaglercraft-saveeditor/files/index.html b/eaglercraft-saveeditor/files/index.html
new file mode 100644
index 0000000..19cbd90
--- /dev/null
+++ b/eaglercraft-saveeditor/files/index.html
@@ -0,0 +1,234 @@
+
+
+
+
The idea: inject a bookmarklet on an active
+ Eaglercraft tab that reads the cached/IndexedDB world data while you're in-game, sends it to
+ RePack, and writes edits back.
+
+
+
+
+
+
+
+
+
diff --git a/eaglercraft-saveeditor/files/inveditor.png b/eaglercraft-saveeditor/files/inveditor.png
new file mode 100644
index 0000000..6cafffa
Binary files /dev/null and b/eaglercraft-saveeditor/files/inveditor.png differ
diff --git a/eaglercraft-saveeditor/files/main.js b/eaglercraft-saveeditor/files/main.js
new file mode 100644
index 0000000..fafce2e
--- /dev/null
+++ b/eaglercraft-saveeditor/files/main.js
@@ -0,0 +1 @@
+if("undefined"==typeof nbt)throw new Error("nbt.js not loaded.");if("undefined"==typeof pako)throw new Error("pako.min.js not loaded.");const MINECRAFT_ITEMS_DB=["minecraft:air","minecraft:stone","minecraft:granite","minecraft:polished_granite","minecraft:diorite","minecraft:polished_diorite","minecraft:andesite","minecraft:polished_andesite","minecraft:grass","minecraft:dirt","minecraft:coarse_dirt","minecraft:podzol","minecraft:cobblestone","minecraft:planks","minecraft:sapling","minecraft:bedrock","minecraft:flowing_water","minecraft:water","minecraft:flowing_lava","minecraft:lava","minecraft:sand","minecraft:red_sand","minecraft:gravel","minecraft:gold_ore","minecraft:iron_ore","minecraft:coal_ore","minecraft:log","minecraft:log2","minecraft:leaves","minecraft:leaves2","minecraft:sponge","minecraft:wet_sponge","minecraft:glass","minecraft:lapis_ore","minecraft:lapis_block","minecraft:dispenser","minecraft:sandstone","minecraft:chiseled_sandstone","minecraft:smooth_sandstone","minecraft:noteblock","minecraft:bed","minecraft:golden_rail","minecraft:detector_rail","minecraft:sticky_piston","minecraft:web","minecraft:tallgrass","minecraft:deadbush","minecraft:piston","minecraft:piston_head","minecraft:wool","minecraft:yellow_flower","minecraft:red_flower","minecraft:brown_mushroom","minecraft:red_mushroom","minecraft:gold_block","minecraft:iron_block","minecraft:double_stone_slab","minecraft:stone_slab","minecraft:brick_block","minecraft:tnt","minecraft:bookshelf","minecraft:mossy_cobblestone","minecraft:obsidian","minecraft:torch","minecraft:fire","minecraft:mob_spawner","minecraft:oak_stairs","minecraft:chest","minecraft:redstone_wire","minecraft:diamond_ore","minecraft:diamond_block","minecraft:crafting_table","minecraft:wheat","minecraft:farmland","minecraft:furnace","minecraft:lit_furnace","minecraft:standing_sign","minecraft:wooden_door","minecraft:ladder","minecraft:rail","minecraft:stone_stairs","minecraft:wall_sign","minecraft:lever","minecraft:stone_pressure_plate","minecraft:iron_door","minecraft:wooden_pressure_plate","minecraft:redstone_ore","minecraft:lit_redstone_ore","minecraft:unlit_redstone_torch","minecraft:redstone_torch","minecraft:stone_button","minecraft:snow_layer","minecraft:ice","minecraft:snow","minecraft:cactus","minecraft:clay","minecraft:reeds","minecraft:jukebox","minecraft:fence","minecraft:pumpkin","minecraft:netherrack","minecraft:soul_sand","minecraft:glowstone","minecraft:portal","minecraft:lit_pumpkin","minecraft:cake","minecraft:unpowered_repeater","minecraft:powered_repeater","minecraft:stained_glass","minecraft:trapdoor","minecraft:monster_egg","minecraft:stonebrick","minecraft:brown_mushroom_block","minecraft:red_mushroom_block","minecraft:iron_bars","minecraft:glass_pane","minecraft:melon_block","minecraft:pumpkin_stem","minecraft:melon_stem","minecraft:vine","minecraft:fence_gate","minecraft:brick_stairs","minecraft:stone_brick_stairs","minecraft:mycelium","minecraft:waterlily","minecraft:nether_brick","minecraft:nether_brick_fence","minecraft:nether_brick_stairs","minecraft:nether_wart","minecraft:enchanting_table","minecraft:brewing_stand","minecraft:cauldron","minecraft:end_portal","minecraft:end_portal_frame","minecraft:end_stone","minecraft:dragon_egg","minecraft:redstone_lamp","minecraft:lit_redstone_lamp","minecraft:double_wooden_slab","minecraft:wooden_slab","minecraft:cocoa","minecraft:sandstone_stairs","minecraft:emerald_ore","minecraft:ender_chest","minecraft:tripwire_hook","minecraft:tripwire","minecraft:emerald_block","minecraft:spruce_stairs","minecraft:birch_stairs","minecraft:jungle_stairs","minecraft:command_block","minecraft:beacon","minecraft:cobblestone_wall","minecraft:flower_pot","minecraft:carrots","minecraft:potatoes","minecraft:wooden_button","minecraft:skull","minecraft:anvil","minecraft:trapped_chest","minecraft:light_weighted_pressure_plate","minecraft:heavy_weighted_pressure_plate","minecraft:unpowered_comparator","minecraft:powered_comparator","minecraft:daylight_detector","minecraft:redstone_block","minecraft:quartz_ore","minecraft:hopper","minecraft:quartz_block","minecraft:quartz_stairs","minecraft:activator_rail","minecraft:dropper","minecraft:stained_hardened_clay","minecraft:stained_glass_pane","minecraft:leaves2","minecraft:log2","minecraft:acacia_stairs","minecraft:dark_oak_stairs","minecraft:slime","minecraft:barrier","minecraft:iron_trapdoor","minecraft:prismarine","minecraft:sea_lantern","minecraft:hay_block","minecraft:carpet","minecraft:hardened_clay","minecraft:coal_block","minecraft:packed_ice","minecraft:double_plant","minecraft:standing_banner","minecraft:wall_banner","minecraft:daylight_detector_inverted","minecraft:red_sandstone","minecraft:red_sandstone_stairs","minecraft:double_stone_slab2","minecraft:stone_slab2","minecraft:spruce_fence_gate","minecraft:birch_fence_gate","minecraft:jungle_fence_gate","minecraft:dark_oak_fence_gate","minecraft:acacia_fence_gate","minecraft:spruce_fence","minecraft:birch_fence","minecraft:jungle_fence","minecraft:dark_oak_fence","minecraft:acacia_fence","minecraft:spruce_door","minecraft:birch_door","minecraft:jungle_door","minecraft:acacia_door","minecraft:dark_oak_door","minecraft:end_rod","minecraft:chorus_plant","minecraft:chorus_flower","minecraft:purpur_block","minecraft:purpur_pillar","minecraft:purpur_stairs","minecraft:purpur_double_slab","minecraft:purpur_slab","minecraft:end_bricks","minecraft:beetroots","minecraft:grass_path","minecraft:end_gateway","minecraft:repeating_command_block","minecraft:chain_command_block","minecraft:frosted_ice","minecraft:magma","minecraft:nether_wart_block","minecraft:red_nether_brick","minecraft:bone_block","minecraft:structure_void","minecraft:observer","minecraft:white_shulker_box","minecraft:orange_shulker_box","minecraft:magenta_shulker_box","minecraft:light_blue_shulker_box","minecraft:yellow_shulker_box","minecraft:lime_shulker_box","minecraft:pink_shulker_box","minecraft:gray_shulker_box","minecraft:silver_shulker_box","minecraft:cyan_shulker_box","minecraft:purple_shulker_box","minecraft:blue_shulker_box","minecraft:brown_shulker_box","minecraft:green_shulker_box","minecraft:red_shulker_box","minecraft:black_shulker_box","minecraft:white_glazed_terracotta","minecraft:orange_glazed_terracotta","minecraft:magenta_glazed_terracotta","minecraft:light_blue_glazed_terracotta","minecraft:yellow_glazed_terracotta","minecraft:lime_glazed_terracotta","minecraft:pink_glazed_terracotta","minecraft:gray_glazed_terracotta","minecraft:silver_glazed_terracotta","minecraft:cyan_glazed_terracotta","minecraft:purple_glazed_terracotta","minecraft:blue_glazed_terracotta","minecraft:brown_glazed_terracotta","minecraft:green_glazed_terracotta","minecraft:red_glazed_terracotta","minecraft:black_glazed_terracotta","minecraft:concrete","minecraft:concrete_powder","minecraft:structure_block","minecraft:iron_shovel","minecraft:iron_pickaxe","minecraft:iron_axe","minecraft:flint_and_steel","minecraft:apple","minecraft:bow","minecraft:arrow","minecraft:coal","minecraft:diamond","minecraft:iron_ingot","minecraft:gold_ingot","minecraft:iron_sword","minecraft:wooden_sword","minecraft:wooden_shovel","minecraft:wooden_pickaxe","minecraft:wooden_axe","minecraft:stone_sword","minecraft:stone_shovel","minecraft:stone_pickaxe","minecraft:stone_axe","minecraft:diamond_sword","minecraft:diamond_shovel","minecraft:diamond_pickaxe","minecraft:diamond_axe","minecraft:golden_sword","minecraft:golden_shovel","minecraft:golden_pickaxe","minecraft:golden_axe","minecraft:stick","minecraft:bowl","minecraft:mushroom_stew","minecraft:string","minecraft:feather","minecraft:gunpowder","minecraft:wooden_hoe","minecraft:stone_hoe","minecraft:iron_hoe","minecraft:diamond_hoe","minecraft:golden_hoe","minecraft:wheat_seeds","minecraft:wheat","minecraft:bread","minecraft:leather_helmet","minecraft:leather_chestplate","minecraft:leather_leggings","minecraft:leather_boots","minecraft:chainmail_helmet","minecraft:chainmail_chestplate","minecraft:chainmail_leggings","minecraft:chainmail_boots","minecraft:iron_helmet","minecraft:iron_chestplate","minecraft:iron_leggings","minecraft:iron_boots","minecraft:diamond_helmet","minecraft:diamond_chestplate","minecraft:diamond_leggings","minecraft:diamond_boots","minecraft:golden_helmet","minecraft:golden_chestplate","minecraft:golden_leggings","minecraft:golden_boots","minecraft:flint","minecraft:porkchop","minecraft:cooked_porkchop","minecraft:painting","minecraft:golden_apple","minecraft:sign","minecraft:bucket","minecraft:water_bucket","minecraft:lava_bucket","minecraft:minecart","minecraft:saddle","minecraft:iron_door","minecraft:redstone","minecraft:snowball","minecraft:boat","minecraft:leather","minecraft:milk_bucket","minecraft:brick","minecraft:clay_ball","minecraft:reeds","minecraft:paper","minecraft:book","minecraft:slime_ball","minecraft:chest_minecart","minecraft:furnace_minecart","minecraft:egg","minecraft:compass","minecraft:fishing_rod","minecraft:clock","minecraft:glowstone_dust","minecraft:fish","minecraft:cooked_fish","minecraft:dye","minecraft:bone","minecraft:sugar","minecraft:cake","minecraft:bed","minecraft:repeater","minecraft:cookie","minecraft:filled_map","minecraft:shears","minecraft:melon","minecraft:pumpkin_seeds","minecraft:melon_seeds","minecraft:beef","minecraft:cooked_beef","minecraft:chicken","minecraft:cooked_chicken","minecraft:rotten_flesh","minecraft:ender_pearl","minecraft:blaze_rod","minecraft:ghast_tear","minecraft:gold_nugget","minecraft:nether_wart","minecraft:potion","minecraft:glass_bottle","minecraft:spider_eye","minecraft:fermented_spider_eye","minecraft:blaze_powder","minecraft:magma_cream","minecraft:brewing_stand","minecraft:cauldron","minecraft:ender_eye","minecraft:speckled_melon","minecraft:spawn_egg","minecraft:experience_bottle","minecraft:fire_charge","minecraft:writable_book","minecraft:written_book","minecraft:emerald","minecraft:item_frame","minecraft:flower_pot","minecraft:carrot","minecraft:potato","minecraft:baked_potato","minecraft:poisonous_potato","minecraft:map","minecraft:golden_carrot","minecraft:skull","minecraft:carrot_on_a_stick","minecraft:nether_star","minecraft:pumpkin_pie","minecraft:fireworks","minecraft:firework_charge","minecraft:enchanted_book","minecraft:comparator","minecraft:netherbrick","minecraft:quartz","minecraft:tnt_minecart","minecraft:hopper_minecart","minecraft:prismarine_shard","minecraft:prismarine_crystals","minecraft:rabbit","minecraft:cooked_rabbit","minecraft:rabbit_stew","minecraft:rabbit_foot","minecraft:rabbit_hide","minecraft:armor_stand","minecraft:iron_horse_armor","minecraft:golden_horse_armor","minecraft:diamond_horse_armor","minecraft:lead","minecraft:name_tag","minecraft:command_block_minecart","minecraft:mutton","minecraft:cooked_mutton","minecraft:banner","minecraft:end_crystal","minecraft:spruce_door","minecraft:birch_door","minecraft:jungle_door","minecraft:acacia_door","minecraft:dark_oak_door","minecraft:chorus_fruit","minecraft:chorus_fruit_popped","minecraft:beetroot","minecraft:beetroot_seeds","minecraft:beetroot_soup","minecraft:dragon_breath","minecraft:splash_potion","minecraft:spectral_arrow","minecraft:tipped_arrow","minecraft:lingering_potion","minecraft:shield","minecraft:elytra","minecraft:spruce_boat","minecraft:birch_boat","minecraft:jungle_boat","minecraft:acacia_boat","minecraft:dark_oak_boat","minecraft:totem_of_undying","minecraft:shulker_shell","minecraft:iron_nugget","minecraft:knowledge_book","minecraft:record_13","minecraft:record_cat","minecraft:record_blocks","minecraft:record_chirp","minecraft:record_far","minecraft:record_mall","minecraft:record_mellohi","minecraft:record_stal","minecraft:record_strad","minecraft:record_ward","minecraft:record_11","minecraft:record_wait"],ENCHANTMENTS_DB=[{id:0,name:"Protection"},{id:1,name:"Fire Protection"},{id:2,name:"Feather Falling"},{id:3,name:"Blast Protection"},{id:4,name:"Projectile Protection"},{id:5,name:"Respiration"},{id:6,name:"Aqua Affinity"},{id:7,name:"Thorns"},{id:16,name:"Sharpness"},{id:17,name:"Smite"},{id:18,name:"Bane of Arthropods"},{id:19,name:"Knockback"},{id:20,name:"Fire Aspect"},{id:21,name:"Looting"},{id:32,name:"Efficiency"},{id:33,name:"Silk Touch"},{id:34,name:"Unbreaking"},{id:35,name:"Fortune"},{id:48,name:"Power"},{id:49,name:"Punch"},{id:50,name:"Flame"},{id:51,name:"Infinity"},{id:61,name:"Luck of the Sea"},{id:62,name:"Lure"}],POTION_EFFECTS_DB=[{id:1,name:"Speed"},{id:2,name:"Slowness"},{id:3,name:"Haste"},{id:4,name:"Mining Fatigue"},{id:5,name:"Strength"},{id:6,name:"Instant Health"},{id:7,name:"Instant Damage"},{id:8,name:"Jump Boost"},{id:9,name:"Nausea"},{id:10,name:"Regeneration"},{id:11,name:"Resistance"},{id:12,name:"Fire Resistance"},{id:13,name:"Water Breathing"},{id:14,name:"Invisibility"},{id:15,name:"Blindness"},{id:16,name:"Night Vision"},{id:17,name:"Hunger"},{id:18,name:"Weakness"},{id:19,name:"Poison"},{id:20,name:"Wither"},{id:21,name:"Health Boost"},{id:22,name:"Absorption"},{id:23,name:"Saturation"}],ORE_RANGES={Coal:{min:5,max:128,best:68},Iron:{min:5,max:64,best:32},Gold:{min:5,max:32,best:12},Diamond:{min:5,max:16,best:11},Lapis:{min:13,max:37,best:17},Redstone:{min:5,max:16,best:10},Emerald:{min:5,max:32,best:10},Quartz:{min:10,max:117,best:63}},ARMOR_SLOTS=[{slot:103,label:"Helmet"},{slot:102,label:"Chest"},{slot:101,label:"Legs"},{slot:100,label:"Boots"}],DEFAULT_GAMERULES=["doFireTick","doMobLoot","doMobSpawning","doTileDrops","keepInventory","mobGriefing","naturalRegeneration","doDaylightCycle","commandBlockOutput","logAdminCommands","randomTickSpeed","sendCommandFeedback","showDeathMessages"];let epkFileInput,decompileButton,repackButton,statusMessageDiv,fileListContainer,fileContentEditor,saveChangesButton,messageBox,messageTitle,messageContent,messageCloseBtn,epkNameDisplay,activeFileNameDisplay,addFileButton,removeFileButton,moddingMenuContainer,epkFile=null,extractedFiles=new Map,activeFile={name:null,buffer:null,nbtParsed:null,wasGzipped:!1},parsedSaveData={},selectedInventoryIndex=null,detectedVersion=null;const DB_NAME="repack_cache",DB_VER=1;let db=null;function openDB(){return new Promise((res,rej)=>{const req=indexedDB.open(DB_NAME,1);req.onupgradeneeded=e=>{const d=e.target.result;d.objectStoreNames.contains("saves")||d.createObjectStore("saves",{keyPath:"name"})},req.onsuccess=e=>{db=e.target.result,res(db)},req.onerror=e=>rej(e)})}async function cacheEPK(name,filesMap){if(!db)return;const serialized={};filesMap.forEach((buf,k)=>{serialized[k]=Array.from(new Uint8Array(buf))}),db.transaction("saves","readwrite").objectStore("saves").put({name:name,files:serialized,ts:Date.now()}),localStorage.setItem("repack_last",name),updateCacheBadge()}async function loadCachedEPK(name){return db?new Promise((res,rej)=>{const req=db.transaction("saves","readonly").objectStore("saves").get(name);req.onsuccess=e=>{if(!e.target.result)return void res(null);const map=new Map,{files:files}=e.target.result;for(const k in files)map.set(k,new Uint8Array(files[k]).buffer);res(map)},req.onerror=rej}):null}async function listCachedEPKs(){return db?new Promise((res,rej)=>{const req=db.transaction("saves","readonly").objectStore("saves").getAll();req.onsuccess=e=>res(e.target.result.map(r=>({name:r.name,ts:r.ts}))),req.onerror=rej}):[]}async function deleteCachedEPK(name){db&&(db.transaction("saves","readwrite").objectStore("saves").delete(name),localStorage.getItem("repack_last")===name&&localStorage.removeItem("repack_last"),updateCacheBadge())}function updateCacheBadge(){const badge=document.getElementById("cacheBadge");badge&&listCachedEPKs().then(list=>{list.length>0?(badge.textContent=`${list.length} saved`,badge.classList.add("has-cache")):(badge.textContent="no cache",badge.classList.remove("has-cache"))})}function showMessageBox(title,body){const box=document.getElementById("messageBox"),t=document.getElementById("messageTitle"),b=document.getElementById("messageContent");box?(t.textContent=title,b.textContent=body,box.classList.add("show")):console.warn(title,body)}function closeMessageBox(){const box=document.getElementById("messageBox");box&&box.classList.remove("show")}function showPromptBox(title,body,defaultVal=""){return new Promise(res=>{const box=document.getElementById("promptBox"),t=document.getElementById("promptTitle"),b=document.getElementById("promptBody"),inp=document.getElementById("promptInput"),okBtn=document.getElementById("promptOk"),canBtn=document.getElementById("promptCancel");if(!box)return void res(window.prompt(`${title}\n${body}`,defaultVal));t.textContent=title,b.textContent=body,inp.value=defaultVal,box.classList.add("show"),inp.focus();const cleanup=()=>{box.classList.remove("show"),okBtn.onclick=null,canBtn.onclick=null};okBtn.onclick=()=>{cleanup(),res(inp.value)},canBtn.onclick=()=>{cleanup(),res(null)},inp.onkeydown=e=>{"Enter"===e.key&&okBtn.click(),"Escape"===e.key&&canBtn.click()}})}function showConfirmBox(title,body){return new Promise(res=>{const box=document.getElementById("confirmBox"),t=document.getElementById("confirmTitle"),b=document.getElementById("confirmBody"),okBtn=document.getElementById("confirmOk"),canBtn=document.getElementById("confirmCancel");if(!box)return void res(window.confirm(`${title}\n\n${body}`));t.textContent=title,b.textContent=body,box.classList.add("show");const cleanup=()=>{box.classList.remove("show"),okBtn.onclick=null,canBtn.onclick=null};okBtn.onclick=()=>{cleanup(),res(!0)},canBtn.onclick=()=>{cleanup(),res(!1)}})}let _statusTimer=null;function showStatusMessage(msg,type="info"){statusMessageDiv&&(statusMessageDiv.textContent=msg,statusMessageDiv.className=`status-message show status-${type}`,clearTimeout(_statusTimer),_statusTimer=setTimeout(()=>statusMessageDiv.classList.remove("show"),4500))}function showPage(id){document.querySelectorAll(".page").forEach(p=>p.classList.remove("active")),document.querySelectorAll(".header-nav-btn").forEach(b=>b.classList.remove("active"));const page=document.getElementById(`page-${id}`),btn=document.getElementById(`nav-${id}`);page&&page.classList.add("active"),btn&&btn.classList.add("active"),sessionStorage.setItem("repack_page",id)}function renderHexView(buffer){const bytes=new Uint8Array(buffer),display=bytes.slice(0,4096),rows=[];for(let i=0;ib.toString(16).padStart(2,"0")).join(" "),ascii=Array.from(chunk).map(b=>b>=32&&b<127?String.fromCharCode(b):".").join(""),offset=i.toString(16).padStart(6,"0").toUpperCase();rows.push(`
${offset}${hex.padEnd(47," ")}${ascii}
`)}const truncNote=bytes.length>4096?`
... ${bytes.length-4096} more bytes (showing first 4 KB)
`:"";return`
${rows.join("")}${truncNote}
`}function arrayBufferToBase64(buffer){let binary="";const bytes=new Uint8Array(buffer);for(let i=0;iLoad an EPK to get started.')}function displayExtractedFiles(filesMap){if(clearFileListDisplay(),!fileListContainer||0===filesMap.size)return void(0===filesMap.size&&fileListContainer&&(fileListContainer.innerHTML='
No files found in package.
'));const pinned=[],player=[],stats=[],data=[],chunks=[],other=[];filesMap.forEach((buffer,filename)=>{const lc=filename.toLowerCase();["level.dat","level.dat_old","file-type","world-name","world-owner"].includes(filename)||"level.dat"===lc||"level.dat_old"===lc?pinned.push(filename):lc.startsWith("player/")?player.push(filename):lc.startsWith("stats/")?stats.push(filename):lc.startsWith("data/")?data.push(filename):lc.startsWith("level0/")?chunks.push(filename):other.push(filename)}),fileListContainer.innerHTML="";const makeItem=filename=>{const buf=filesMap.get(filename),item=document.createElement("div");item.className="file-list-item",item.dataset.filename=filename;let ext=filename.split(".").pop().toUpperCase();filename.startsWith("level0/")&&(ext="CHUNK"),(filename.includes("file-type")||filename.includes("world-"))&&(ext="META"),filename.endsWith(".dat_old")&&(ext="BAK");const short=(filename.includes("/"),filename);return item.innerHTML=`${short}${ext}`,item.addEventListener("click",()=>selectFileForEditing(filename,buf)),item},makeSection=(label,files,collapsed=!1)=>{if(0===files.length)return;const section=document.createElement("div"),header=document.createElement("div");header.className="file-section-header"+(collapsed?" collapsed":""),header.innerHTML=`${label} (${files.length})▾`;const body=document.createElement("div");body.className="file-section-body"+(collapsed?" collapsed":""),files.forEach(f=>body.appendChild(makeItem(f))),header.addEventListener("click",()=>{header.classList.toggle("collapsed"),body.classList.toggle("collapsed")}),section.appendChild(header),section.appendChild(body),fileListContainer.appendChild(section)},pinnedSection=document.createElement("div");pinned.forEach(f=>pinnedSection.appendChild(makeItem(f))),fileListContainer.appendChild(pinnedSection),makeSection("Player Data",player),makeSection("Stats",stats),makeSection("World Data",data),makeSection("Chunk Files",chunks,!0),makeSection("Other",other,!0)}async function viewNBTData(fileName,buffer){showStatusMessage(`Reading ${fileName}...`,"info");let data=new Uint8Array(buffer);activeFile.wasGzipped=!1;try{if(data.length>2&&31===data[0]&&139===data[1]&&(data=pako.ungzip(data),activeFile.wasGzipped=!0),!data||0===data.length)throw new Error("Empty or invalid NBT data");const parsed=await new Promise((resolve,reject)=>{try{nbt.parse(data.buffer,(err,result)=>{err?reject(err):result&&result.value?resolve(result):reject(new Error("NBT parse returned invalid data"))})}catch(e){reject(e)}});activeFile.nbtParsed=parsed,fileContentEditor&&(fileContentEditor.value=JSON.stringify(parsed.value,null,2)),saveChangesButton&&(saveChangesButton.disabled=!1),showStatusMessage(`Parsed ${fileName}.`,"success")}catch(err){console.warn(`NBT parse failed for ${fileName}:`,err),fileContentEditor&&(fileContentEditor.value="",fileContentEditor.disabled=!0);const container=fileContentEditor?fileContentEditor.parentElement:null;if(container){const existing=container.querySelector(".hex-viewer");existing&&existing.remove();const hexEl=document.createElement("div");hexEl.innerHTML=renderHexView(buffer),container.insertBefore(hexEl.firstChild,fileContentEditor)}showStatusMessage(`Showing hex view for ${fileName}.`,"info")}}async function decryptEpk(buffer){showStatusMessage("Unpacking...","info");const bytes=new Uint8Array(buffer),filesMap=new Map;try{const header=bytes.subarray(0,8),ver2=new Uint8Array([69,65,71,80,75,71,36,36]),ver1=new Uint8Array([69,65,71,80,75,71,33,33]);if(!arraysEqual(header,ver2)){if(arraysEqual(header,ver1))throw new Error("Legacy EPK v1 not supported.");throw new Error("Not a valid EPK file.")}if(!arraysEqual(bytes.subarray(bytes.byteLength-8),new Uint8Array([58,58,58,89,69,69,58,62])))throw new Error("File is truncated or corrupted.");const body=bytes.subarray(8,bytes.byteLength-8),view=new DataView(body.buffer,body.byteOffset,body.byteLength);let ptr=0;const verLen=view.getUint8(ptr++),versionString=new TextDecoder("ascii").decode(body.subarray(ptr,ptr+verLen));if(ptr+=verLen,!versionString.startsWith("ver2."))throw new Error(`Unsupported version: ${versionString}`);const buildLen=view.getUint8(ptr++);ptr+=buildLen;const paddingLen=view.getUint16(ptr,!1);ptr+=2,ptr+=paddingLen,ptr+=8;let filesCount=view.getInt32(ptr,!1);ptr+=4;const compChar=String.fromCharCode(view.getUint8(ptr++)),compressedData=body.subarray(ptr);let decompressed;switch(compChar){case"G":decompressed=pako.ungzip(compressedData);break;case"Z":decompressed=pako.inflate(compressedData);break;case"0":decompressed=compressedData;break;default:throw new Error(`Unknown compression: ${compChar}`)}const decView=new DataView(decompressed.buffer,decompressed.byteOffset,decompressed.byteLength);let decPtr=0;for(;filesCount>0&&!(decPtr+4>decompressed.byteLength);){const entryType=new TextDecoder("ascii").decode(decompressed.subarray(decPtr,decPtr+4));if(decPtr+=4,"END$"===entryType){filesCount=0;break}const nameLen=decView.getUint8(decPtr++),fileName=new TextDecoder("ascii").decode(decompressed.subarray(decPtr,decPtr+nameLen));decPtr+=nameLen;const entrySize=decView.getInt32(decPtr,!1);let fileContent;if(decPtr+=4,"FILE"===entryType){if(entrySize<5)throw new Error(`Truncated entry: ${fileName}`);if(decView.getInt32(decPtr,!1),decPtr+=4,fileContent=decompressed.slice(decPtr,decPtr+entrySize-5),decPtr+=entrySize-5,":"!==String.fromCharCode(decView.getUint8(decPtr++)))throw new Error(`Misaligned entry: ${fileName}`)}else fileContent=decompressed.slice(decPtr,decPtr+entrySize),decPtr+=entrySize;if(">"!==String.fromCharCode(decView.getUint8(decPtr++)))throw new Error(`Missing terminator: ${fileName}`);filesMap.set(fileName,fileContent.buffer),filesCount--}return detectedVersion=detectVersionFromFiles(filesMap),showStatusMessage(`Unpacked ${filesMap.size} files.`,"success"),filesMap}catch(err){throw showStatusMessage(`Failed: ${err.message}`,"error"),err}}async function updateLevelDatLevelName(worldName){if(extractedFiles.has("level.dat")){const buf=extractedFiles.get("level.dat");let bytes=new Uint8Array(buf),gz=!1;try{bytes.length>2&&31===bytes[0]&&139===bytes[1]&&(bytes=pako.ungzip(bytes),gz=!0);const parsed=await new Promise((res,rej)=>nbt.parse(bytes.buffer,(e,r)=>e?rej(e):res(r))),v=parsed.value;v.Data&&v.Data.value&&(v.Data.value.LevelName||(v.Data.value.LevelName={type:"string",value:""}),v.Data.value.LevelName.value=worldName);let out=new Uint8Array(nbt.writeUncompressed(parsed));gz&&(out=pako.gzip(out)),extractedFiles.set("level.dat",out.buffer)}catch(e){console.warn("level.dat name update failed:",e)}}extractedFiles.has("world-name")&&extractedFiles.set("world-name",(new TextEncoder).encode(worldName).buffer)}async function encryptEpk(filesMap,outputName,gameVersion){showStatusMessage("Packing...","info");try{const stream=new ByteArrayOutputStream;stream.writeString("EAGPKG$$","ascii");const fmt="ver2.0";stream.writeUint8(fmt.length),stream.writeString(fmt,"ascii");const baseName=`${outputName}.epk`;stream.writeUint8(baseName.length),stream.writeString(baseName,"ascii");const now=new Date,header2=`\n\n # RePack\n # ${now.getFullYear()+"-"+String(now.getMonth()+1).padStart(2,"0")+"-"+String(now.getDate()).padStart(2,"0")+" "+String(now.getHours()).padStart(2,"0")+":"+String(now.getMinutes()).padStart(2,"0")}\n\n`;if(stream.writeUint16(header2.length),stream.writeString(header2,"ascii"),"undefined"==typeof Long)throw new Error("long.js not loaded.");stream.writeLong(now.getTime());const contentMap=new Map;filesMap.forEach((buf,key)=>{if("file-type"===key||"_metadata"===key)return;let p=key.replace(/\\/g,"/").replace(/^\//,"");outputName&&p.startsWith(`${outputName}/`)&&(p=p.substring(outputName.length+1)),contentMap.set(p,buf)}),stream.writeInt(contentMap.size+1),stream.writeUint8("0".charCodeAt(0));const dec=new ByteArrayOutputStream;dec.writeString("HEAD","ascii");const g="file-type";dec.writeUint8(g.length),dec.writeString(g,"ascii");const f="1.8.8"===gameVersion?"epk/world188":"epk/world152";dec.writeInt(f.length),dec.writeString(f,"ascii"),dec.writeUint8(">".charCodeAt(0));const crc=new CRC32;return contentMap.forEach((buf,key)=>{const bytes=new Uint8Array(buf);crc.reset(),crc.update(bytes),dec.writeString("FILE","ascii"),dec.writeUint8(key.length),dec.writeString(key,"ascii"),dec.writeInt(bytes.length+5),dec.writeInt(crc.getValue()),dec.writeBytes(bytes),dec.writeUint8(":".charCodeAt(0)),dec.writeUint8(">".charCodeAt(0))}),dec.writeString("END$","ascii"),stream.writeBytes(dec.toByteArray()),stream.writeString(":::YEE:>","ascii"),showStatusMessage("Packed.","success"),stream.toByteArray().buffer}catch(err){throw showStatusMessage(`Pack failed: ${err.message}`,"error"),err}}async function saveChanges(){if(activeFile.name){showStatusMessage(`Saving ${activeFile.name}...`,"info");try{let buffer;if(activeFile.name.endsWith(".dat")&&!activeFile.name.endsWith(".dat_old")&&activeFile.nbtParsed){let out=new Uint8Array(nbt.writeUncompressed(activeFile.nbtParsed));activeFile.wasGzipped&&(out=pako.gzip(out)),buffer=out.buffer,fileContentEditor&&(fileContentEditor.value=JSON.stringify(activeFile.nbtParsed.value,null,2))}else{if(!fileContentEditor||void 0===fileContentEditor.value)return;{const val=fileContentEditor.value;buffer=activeFile.name.match(/\.(txt|json|yml|xml|html|css|js|glsl)$/i)?(new TextEncoder).encode(val).buffer:base64ToArrayBuffer(val.split("\n").filter(l=>!l.trim().startsWith("//")).join("").trim())}}extractedFiles.set(activeFile.name,buffer),activeFile.buffer=buffer,showStatusMessage("Saved.","success"),repackButton&&(repackButton.disabled=!1)}catch(err){throw showStatusMessage(`Save failed: ${err.message}`,"error"),err}}}async function selectFileForEditing(fileName,buffer){if(activeFile.name)try{await saveChanges()}catch(_){}if(fileContentEditor){const parent=fileContentEditor.parentElement;parent&&parent.querySelectorAll(".hex-viewer").forEach(el=>el.remove()),fileContentEditor.style.display="",fileContentEditor.disabled=!1}fileListContainer&&fileListContainer.querySelectorAll(".file-list-item").forEach(i=>i.classList.remove("selected"));const sel=fileListContainer&&fileListContainer.querySelector(`[data-filename="${CSS.escape(fileName)}"]`);if(sel&&sel.classList.add("selected"),showStatusMessage(`Opening ${fileName}...`,"info"),saveChangesButton&&(saveChangesButton.disabled=!1),removeFileButton&&(removeFileButton.disabled=!1),activeFileNameDisplay&&(activeFileNameDisplay.textContent=fileName),activeFile={name:fileName,buffer:buffer,nbtParsed:null,wasGzipped:!1},selectedInventoryIndex=null,fileName.endsWith(".dat")&&!fileName.endsWith(".dat_old")&&"session.lock"!==fileName)try{if(await viewNBTData(fileName,buffer),activeFile.nbtParsed&&activeFile.nbtParsed.value&&activeFile.nbtParsed.value.Data){const worldData=activeFile.nbtParsed.value.Data.value;if(worldData&&worldData.Player)return parsedSaveData=activeFile.nbtParsed.value,moddingMenuContainer&&(moddingMenuContainer.classList.remove("hidden-by-default"),fileContentEditor&&fileContentEditor.classList.add("hidden-by-default")),activeFileNameDisplay&&(activeFileNameDisplay.textContent=fileName),void renderModdingMenu(worldData)}}catch(_){}if(moddingMenuContainer&&moddingMenuContainer.classList.add("hidden-by-default"),fileContentEditor&&fileContentEditor.classList.remove("hidden-by-default"),clearModdingMenu(),fileName.match(/\.(txt|json|yml|xml|html|css|js|glsl)$/i))try{const text=new TextDecoder("utf-8",{fatal:!0}).decode(buffer);fileContentEditor&&(fileContentEditor.value=text)}catch(_){fileContentEditor&&(fileContentEditor.value=`// UTF-8 decode failed. Raw base64:\n${arrayBufferToBase64(buffer)}`)}else if("file-type"===fileName||"world-name"===fileName||"world-owner"===fileName)try{fileContentEditor&&(fileContentEditor.value=(new TextDecoder).decode(buffer))}catch(_){fileContentEditor&&(fileContentEditor.value=arrayBufferToBase64(buffer))}else{fileContentEditor&&(fileContentEditor.style.display="none");const parent=fileContentEditor?fileContentEditor.parentElement:null;if(parent){const hexDiv=document.createElement("div");hexDiv.innerHTML=renderHexView(buffer),parent.insertBefore(hexDiv.firstChild,fileContentEditor)}fileContentEditor&&(fileContentEditor.value=`// Binary file (hex view above). Edit as base64 below:\n${arrayBufferToBase64(buffer)}`),showStatusMessage(`Hex view loaded for ${fileName}.`,"info")}}function resetFileEditor(){if(fileContentEditor){fileContentEditor.value="",fileContentEditor.disabled=!0,fileContentEditor.style.display="",fileContentEditor.classList.remove("hidden-by-default");const parent=fileContentEditor.parentElement;parent&&parent.querySelectorAll(".hex-viewer").forEach(e=>e.remove())}saveChangesButton&&(saveChangesButton.disabled=!0),activeFileNameDisplay&&(activeFileNameDisplay.textContent="None"),removeFileButton&&(removeFileButton.disabled=!0),moddingMenuContainer&&moddingMenuContainer.classList.add("hidden-by-default"),activeFile={name:null,buffer:null,nbtParsed:null,wasGzipped:!1};const sel=fileListContainer&&fileListContainer.querySelector(".file-list-item.selected");sel&&sel.classList.remove("selected")}function renderModdingMenu(worldNbtData){if(moddingMenuContainer=document.getElementById("moddingMenuContainer"),!moddingMenuContainer)return;const player=worldNbtData.Player?worldNbtData.Player.value:{},inv=player.Inventory||{value:{value:[]}},pos=player.Pos?player.Pos.value.value:[0,64,0],spawn=[worldNbtData.SpawnX?worldNbtData.SpawnX.value:0,worldNbtData.SpawnY?worldNbtData.SpawnY.value:64,worldNbtData.SpawnZ?worldNbtData.SpawnZ.value:0],abilities=player.abilities?player.abilities.value:{},activeEffects=player.ActiveEffects?player.ActiveEffects.value.value:[],gamerules=worldNbtData.GameRules?worldNbtData.GameRules.value:{},thundering=(worldNbtData.weatherTime&&worldNbtData.weatherTime.value,worldNbtData.thundering?worldNbtData.thundering.value:0),raining=worldNbtData.raining?worldNbtData.raining.value:0;moddingMenuContainer.innerHTML=`\n