utils.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. /*
  2. * Copyright (C) 2024 Puter Technologies Inc.
  3. *
  4. * This file is part of Puter.
  5. *
  6. * Puter is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU Affero General Public License as published
  8. * by the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU Affero General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Affero General Public License
  17. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  18. */
  19. import { encode } from 'html-entities';
  20. import fs from 'fs';
  21. import path from 'path';
  22. import webpack from 'webpack';
  23. import CleanCSS from 'clean-css';
  24. import uglifyjs from 'uglify-js';
  25. import { lib_paths, css_paths, js_paths } from './src/static-assets.js';
  26. import { fileURLToPath } from 'url';
  27. // Polyfill __dirname, which doesn't exist in modules mode
  28. const __dirname = path.dirname(fileURLToPath(import.meta.url));
  29. /**
  30. * Builds the application by performing various tasks such as cleaning the distribution directory,
  31. * merging and minifying JavaScript and CSS files, bundling GUI core files, handling images,
  32. * and preparing the final distribution package. The process involves concatenating library
  33. * scripts, optimizing them for production, and copying essential assets to the distribution
  34. * directory. The function also supports a verbose mode for logging detailed information during
  35. * the build process.
  36. *
  37. * @param {Object} [options] - Optional parameters to customize the build process.
  38. * @param {boolean} [options.verbose=false] - Specifies whether to log detailed information during the build.
  39. *
  40. * @async
  41. * @returns {Promise<void>} A promise that resolves when the build process is complete.
  42. *
  43. * @example
  44. * build({ verbose: true }).then(() => {
  45. * console.log('Build process completed successfully.');
  46. * }).catch(error => {
  47. * console.error('Build process failed:', error);
  48. * });
  49. */
  50. async function build(options){
  51. // -----------------------------------------------
  52. // Delete ./dist/ directory if it exists and create a new one
  53. // -----------------------------------------------
  54. if(fs.existsSync(path.join(__dirname, 'dist'))){
  55. fs.rmSync(path.join(__dirname, 'dist'), {recursive: true});
  56. }
  57. fs.mkdirSync(path.join(__dirname, 'dist'));
  58. // -----------------------------------------------
  59. // Concat/merge the JS libraries and save them to ./dist/libs.js
  60. // -----------------------------------------------
  61. let js = '';
  62. for(let i = 0; i < lib_paths.length; i++){
  63. const file = path.join(__dirname, 'src', lib_paths[i]);
  64. // js
  65. if(file.endsWith('.js') && !file.endsWith('.min.js')){
  66. let minified_code = await uglifyjs.minify(fs.readFileSync(file).toString(), {mangle: false});
  67. if(minified_code && minified_code.code){
  68. js += minified_code.code;
  69. if(options?.verbose)
  70. console.log('minified: ', file);
  71. }
  72. }else{
  73. js += fs.readFileSync(file);
  74. if(options?.verbose)
  75. console.log('skipped minification: ', file);
  76. }
  77. js += '\n\n\n';
  78. }
  79. // -----------------------------------------------
  80. // Combine all images into a single js file
  81. // -----------------------------------------------
  82. let icons = 'window.icons = [];\n\n\n';
  83. fs.readdirSync(path.join(__dirname, 'src/icons')).forEach(file => {
  84. // skip dotfiles
  85. if(file.startsWith('.'))
  86. return;
  87. // load image
  88. let buff = new Buffer.from(fs.readFileSync(path.join(__dirname, 'src/icons') + '/' + file));
  89. // convert to base64
  90. let base64data = buff.toString('base64');
  91. // add to `window.icons`
  92. if(file.endsWith('.png'))
  93. icons += `window.icons['${file}'] = "data:image/png;base64,${base64data}";\n`;
  94. else if(file.endsWith('.svg'))
  95. icons += `window.icons['${file}'] = "data:image/svg+xml;base64,${base64data}";\n`;
  96. });
  97. // -----------------------------------------------
  98. // concat/merge the CSS files and save them to ./dist/bundle.min.css
  99. // -----------------------------------------------
  100. let css = '';
  101. for(let i = 0; i < css_paths.length; i++){
  102. let fullpath = path.join(__dirname, 'src', css_paths[i]);
  103. // minify CSS files if not already minified, then concatenate
  104. if(css_paths[i].endsWith('.css') && !css_paths[i].endsWith('.min.css')){
  105. const minified_css = new CleanCSS({}).minify(fs.readFileSync(fullpath).toString());
  106. css += minified_css.styles;
  107. }
  108. // otherwise, just concatenate the file
  109. else
  110. css += fs.readFileSync(path.join(__dirname, 'src', css_paths[i]));
  111. // add newlines between files
  112. css += '\n\n\n';
  113. }
  114. fs.writeFileSync(path.join(__dirname, 'dist', 'bundle.min.css'), css);
  115. // -----------------------------------------------
  116. // Bundle GUI core and merge all files into a single JS file
  117. // -----------------------------------------------
  118. let main_array = [];
  119. for(let i = 0; i < js_paths.length; i++){
  120. main_array.push(path.join(__dirname, 'src', js_paths[i]));
  121. }
  122. webpack({
  123. mode: 'production',
  124. entry: {
  125. main: main_array,
  126. },
  127. output: {
  128. path: path.resolve(__dirname, 'dist'),
  129. filename: '[name].js',
  130. },
  131. optimization: {
  132. minimize: true,
  133. },
  134. }, (err, stats) => {
  135. if(err){
  136. console.error(err);
  137. return;
  138. }
  139. if(options?.verbose)
  140. console.log(stats.toString());
  141. // write to ./dist/bundle.min.js
  142. fs.writeFileSync(path.join(__dirname, 'dist', 'bundle.min.js'), icons + '\n\n\n' + js + '\n\n\n' + fs.readFileSync(path.join(__dirname, 'dist', 'main.js')));
  143. // remove ./dist/main.js
  144. fs.unlinkSync(path.join(__dirname, 'dist', 'main.js'));
  145. });
  146. // Copy index.js to dist/gui.js
  147. // Prepend `window.gui_env="prod";` to `./dist/gui.js`
  148. fs.writeFileSync(
  149. path.join(__dirname, 'dist', 'gui.js'),
  150. `window.gui_env="prod"; \n\n` + fs.readFileSync(path.join(__dirname, 'src', 'index.js'))
  151. );
  152. const copy_these = [
  153. 'images',
  154. 'fonts',
  155. 'favicons',
  156. 'browserconfig.xml',
  157. 'manifest.json',
  158. 'favicon.ico',
  159. 'security.txt',
  160. ];
  161. const recursive_copy = (src, dest) => {
  162. const stat = fs.statSync(src);
  163. if ( stat.isDirectory() ) {
  164. if( ! fs.existsSync(dest) ) fs.mkdirSync(dest);
  165. const files = fs.readdirSync(src);
  166. for ( const file of files ) {
  167. recursive_copy(path.join(src, file), path.join(dest, file));
  168. }
  169. } else {
  170. fs.copyFileSync(src, dest);
  171. }
  172. };
  173. for ( const to_copy of copy_these ) {
  174. recursive_copy(path.join(__dirname, 'src', to_copy), path.join(__dirname, 'dist', to_copy));
  175. }
  176. }
  177. /**
  178. * Generates the HTML content for the GUI based on the specified configuration options. The function
  179. * creates a new HTML document with the specified title, description, and other metadata. The function
  180. * also includes the necessary CSS and JavaScript files, as well as the required meta tags for social
  181. * media sharing and search engine optimization. The function is designed to be used in development
  182. * environments to generate the HTML content for the GUI.
  183. *
  184. * @param {Object} options - The configuration options for the GUI.
  185. * @param {string} options.env - The environment in which the GUI is running (e.g., "dev" or "prod").
  186. * @param {string} options.api_origin - The origin of the API server.
  187. * @param {string} options.title - The title of the GUI.
  188. * @param {string} options.company - The name of the company or organization.
  189. * @param {string} options.description - The description of the GUI.
  190. * @param {string} options.app_description - The description of the application.
  191. * @param {string} options.short_description - The short description of the GUI.
  192. * @param {string} options.origin - The origin of the GUI.
  193. * @param {string} options.social_card - The URL of the social media card image.
  194. * @returns {string} The HTML content for the GUI based on the specified configuration options.
  195. *
  196. */
  197. function generateDevHtml(options){
  198. let start_t = Date.now();
  199. // final html string
  200. let h = '';
  201. h += `<!DOCTYPE html>`;
  202. h += `<html lang="en">`;
  203. h += `<head>`;
  204. h += `<title>${encode((options.title))}</title>`
  205. h += `<meta name="author" content="${encode(options.company)}">`
  206. // description
  207. let description = options.description;
  208. // if app_description is set, use that instead
  209. if(options.app_description){
  210. description = options.app_description;
  211. }
  212. // if no app_description is set, use short_description if set
  213. else if(options.short_description){
  214. description = options.short_description;
  215. }
  216. // description
  217. h += `<meta name="description" content="${encode((description).replace(/\n/g, " "))}">`
  218. // facebook domain verification
  219. h += `<meta name="facebook-domain-verification" content="e29w3hjbnnnypf4kzk2cewcdaxym1y" />`;
  220. // canonical url
  221. h += `<link rel="canonical" href="${options.origin}">`;
  222. // DEV: load every CSS file individually
  223. if(options.env === 'dev'){
  224. for(let i = 0; i < css_paths.length; i++){
  225. h += `<link rel="stylesheet" href="${css_paths[i]}">`;
  226. }
  227. }
  228. // Facebook meta tags
  229. h += `<meta property="og:url" content="https://${options.domain}">`;
  230. h += `<meta property="og:type" content="website">`;
  231. h += `<meta property="og:title" content="${encode(options.title)}">`;
  232. h += `<meta property="og:description" content="${encode((options.short_description).replace(/\n/g, " "))}">`;
  233. h += `<meta property="og:image" content="${options.social_card}">`;
  234. // Twitter meta tags
  235. h += `<meta name="twitter:card" content="summary_large_image">`;
  236. h += `<meta property="twitter:domain" content="${options.domain}">`;
  237. h += `<meta property="twitter:url" content="https://${options.domain}">`;
  238. h += `<meta name="twitter:title" content="${encode(options.title)}">`;
  239. h += `<meta name="twitter:description" content="${encode((options.short_description).replace(/\n/g, " "))}">`;
  240. h += `<meta name="twitter:image" content="${options.social_card}">`;
  241. // favicons
  242. h += `
  243. <link rel="apple-touch-icon" sizes="57x57" href="/favicons/apple-icon-57x57.png">
  244. <link rel="apple-touch-icon" sizes="60x60" href="/favicons/apple-icon-60x60.png">
  245. <link rel="apple-touch-icon" sizes="72x72" href="/favicons/apple-icon-72x72.png">
  246. <link rel="apple-touch-icon" sizes="76x76" href="/favicons/apple-icon-76x76.png">
  247. <link rel="apple-touch-icon" sizes="114x114" href="/favicons/apple-icon-114x114.png">
  248. <link rel="apple-touch-icon" sizes="120x120" href="/favicons/apple-icon-120x120.png">
  249. <link rel="apple-touch-icon" sizes="144x144" href="/favicons/apple-icon-144x144.png">
  250. <link rel="apple-touch-icon" sizes="152x152" href="/favicons/apple-icon-152x152.png">
  251. <link rel="apple-touch-icon" sizes="180x180" href="/favicons/apple-icon-180x180.png">
  252. <link rel="icon" type="image/png" sizes="192x192" href="/favicons/android-icon-192x192.png">
  253. <link rel="icon" type="image/png" sizes="32x32" href="/favicons/favicon-32x32.png">
  254. <link rel="icon" type="image/png" sizes="96x96" href="/favicons/favicon-96x96.png">
  255. <link rel="icon" type="image/png" sizes="16x16" href="/favicons/favicon-16x16.png">
  256. <link rel="manifest" href="/manifest.json">
  257. <meta name="msapplication-TileColor" content="#ffffff">
  258. <meta name="msapplication-TileImage" content="/favicons/ms-icon-144x144.png">
  259. <meta name="theme-color" content="#ffffff">`;
  260. // preload images when applicable
  261. h += `<link rel="preload" as="image" href="./images/wallpaper.webp">`;
  262. h += `</head>`;
  263. h += `<body>`;
  264. // To indicate that the GUI is running to any 3rd-party scripts that may be running on the page
  265. // specifically, the `puter.js` script
  266. // This line is also present verbatim in `src/index.js` for production builds
  267. h += `<script>window.puter_gui_enabled = true;</script>`;
  268. // DEV: load every JS library individually
  269. if(options.env === 'dev'){
  270. for(let i = 0; i < lib_paths.length; i++){
  271. h += `<script src="${lib_paths[i]}"></script>`;
  272. }
  273. }
  274. // load images and icons as base64 for performance
  275. if(options.env === 'dev'){
  276. h += `<script>`;
  277. h += `window.icons = {};`
  278. fs.readdirSync(path.join(__dirname, 'src/icons')).forEach(file => {
  279. // skip dotfiles
  280. if(file.startsWith('.'))
  281. return;
  282. // load image
  283. let buff = new Buffer.from(fs.readFileSync(path.join(__dirname, 'src/icons') + '/' + file));
  284. // convert to base64
  285. let base64data = buff.toString('base64');
  286. // add to `window.icons`
  287. if(file.endsWith('.png'))
  288. h += `window.icons['${file}'] = "data:image/png;base64,${base64data}";\n`;
  289. else if(file.endsWith('.svg'))
  290. h += `window.icons['${file}'] = "data:image/svg+xml;base64,${base64data}";\n`;
  291. });
  292. h += `</script>`;
  293. }
  294. // PROD: gui.js
  295. if(options.env === 'prod'){
  296. h += `<script src="/dist/gui.js"></script>`;
  297. }
  298. // DEV: load every JS file individually
  299. else{
  300. for(let i = 0; i < js_paths.length; i++){
  301. h += `<script type="module" src="${js_paths[i]}"></script>`;
  302. }
  303. // load GUI
  304. h += `<script type="module" src="/index.js"></script>`;
  305. }
  306. // ----------------------------------------
  307. // Initialize GUI with config options
  308. // ----------------------------------------
  309. h += `
  310. <script type="text/javascript">
  311. window.addEventListener('load', function() {`
  312. h += `gui()`;
  313. h += `});
  314. </script>`;
  315. h += `</body>
  316. </html>`;
  317. console.log(`/index.js: ` + (Date.now() - start_t)/1000);
  318. return h;
  319. }
  320. // export
  321. export { generateDevHtml, build };