utils.js 15 KB

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