/** * This script generates a bookmarklet from a JavaScript file. * It reads the JavaScript file, removes any multiline comments, and creates a bookmarklet string. * The bookmarklet can then be used to execute the JavaScript code in a browser. * * Use this to generate a bookmarklet from a JavaScript file in the utils/bookmarklets directory. * * @param {string} filePath - The path to the JavaScript file. * @returns {string} The generated bookmarklet. */ import fs from 'fs'; import path from 'path'; import clipboardy from 'clipboardy'; // Get the file path from command line arguments const filePath = process.argv[2]; // Read the JavaScript file const jsCode = fs.readFileSync(filePath, 'utf8'); // Remove multiline comments and single-line comments, but preserve string literals let cleanedCode = jsCode // Remove multiline comments .replace(/\/\*[\s\S]*?\*\//g, '') // Remove single-line comments (but not URLs) .replace(/\/\/.*$/gm, '') // Remove empty lines and extra whitespace .replace(/^\s*\n/gm, '') .trim(); // Create the bookmarklet const bookmarklet = `javascript:(function() { ${cleanedCode} })();`; // Validate the generated JavaScript try { // Test if the code is syntactically valid new Function(cleanedCode); console.log('Generated bookmarklet is syntactically valid.'); } catch (syntaxError) { console.error('Syntax error in generated code:', syntaxError.message); console.log('Generated code:'); console.log(cleanedCode); process.exit(1); } // Copy the bookmarklet to the clipboard try { clipboardy.writeSync(bookmarklet); console.log('Bookmarklet copied to clipboard successfully.'); console.log('Length:', bookmarklet.length, 'characters'); } catch (error) { console.error('Failed to copy bookmarklet to clipboard:', error); }