$ show lisonge/vite-plugin-monkey
vite-plugin-monkey is a Vite plugin that compiles userscripts (user.js) for Tampermonkey, Violentmonkey, Greasemonkey, and ScriptCat. It transforms a standard Vite project into a self-contained userscript bundle, injecting the required metadata header, handling external dependencies via CDN (@require/@resource), and automatically collecting GM API grants. The plugin supports both development (HMR via a proxy server) and production builds, with dynamic import support via SystemJS. It consists of a collection of Rollup/Vite plugins that modify the build pipeline: config, CSS injection, external globals, external resources, asset URL fixing, and final bundle generation. The architecture is modular and well-separated, with clean abstractions for userscript metadata generation, AST-based grant collection, and CDN URL helpers.
The LLM identified 2 files worth highlighting for reuse:
This module analyzes the final JavaScript bundle to automatically detect which GM_* APIs are used. It uses acorn-walk to traverse the AST, identifying GM_* identifiers and member expressions (e.g., GM.getValue) and collecting them into a set. This allows the plugin to automatically inject the correct @grant permissions into the userscript metadata. The logic is isolated, handles minified code by checking module source code, and could be extracted as a standalone utility for any project needing to detect used global functions.
This module handles the transformation of top-level await expressions in the final bundle. During the build process, the plugin converts `await` to a custom identifier `_TLA_` to avoid issues with Rollup's handling of top-level await, then later converts it back. It also handles `for await...of` loops. The code demonstrates deep understanding of AST manipulation using MagicString and acorn-walk, and is self-contained enough to be reused in other build tools that need to safely handle top-level await in non-module contexts.