snippetadapter.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. /**
  2. * @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  4. */
  5. /* eslint-env node */
  6. const path = require( 'path' );
  7. const fs = require( 'fs' );
  8. const minimatch = require( 'minimatch' );
  9. const webpack = require( 'webpack' );
  10. const { bundler, styles } = require( '@ckeditor/ckeditor5-dev-utils' );
  11. const CKEditorWebpackPlugin = require( '@ckeditor/ckeditor5-dev-webpack-plugin' );
  12. const MiniCssExtractPlugin = require( 'mini-css-extract-plugin' );
  13. const TerserPlugin = require( 'terser-webpack-plugin' );
  14. const ProgressBarPlugin = require( 'progress-bar-webpack-plugin' );
  15. const DEFAULT_LANGUAGE = 'en';
  16. const MULTI_LANGUAGE = 'multi-language';
  17. /**
  18. * @param {Set.<Snippet>} snippets Snippet collection extracted from documentation files.
  19. * @param {Object} options
  20. * @param {Boolean} options.production Whether to build snippets in production mode.
  21. * @param {Array.<String>|undefined} options.allowedSnippets An array that contains glob patterns of snippets that should be built.
  22. * If not specified or if passed the empty array, all snippets will be built.
  23. * @param {Object.<String, Function>} umbertoHelpers
  24. * @returns {Promise}
  25. */
  26. module.exports = function snippetAdapter( snippets, options, umbertoHelpers ) {
  27. const { getSnippetPlaceholder, getSnippetSourcePaths } = umbertoHelpers;
  28. const snippetsDependencies = new Map();
  29. // For each snippet, load its config. If the snippet has defined dependencies, load those as well.
  30. for ( const snippetData of snippets ) {
  31. if ( !snippetData.snippetSources.js ) {
  32. throw new Error( `Missing snippet source for "${ snippetData.snippetName }".` );
  33. }
  34. snippetData.snippetConfig = readSnippetConfig( snippetData.snippetSources.js );
  35. snippetData.snippetConfig.language = snippetData.snippetConfig.language || DEFAULT_LANGUAGE;
  36. // If, in order to work, a snippet requires another snippet to be built, and the other snippet
  37. // isn't included in any guide via `{@snippet ...}`, then that other snippet need to be marked
  38. // as a dependency of the first one. Example – bootstrap UI uses an iframe, and inside that iframe we
  39. // need a JS file. That JS file needs to be built, even though it's not a real snippet (and it's not used
  40. // via {@snippet}).
  41. if ( snippetData.snippetConfig.dependencies ) {
  42. for ( const dependencyName of snippetData.snippetConfig.dependencies ) {
  43. // Do not load the same dependency more than once.
  44. if ( snippetsDependencies.has( dependencyName ) ) {
  45. continue;
  46. }
  47. // Find a root path where to look for the snippet's sources. We just want to pass it through Webpack.
  48. const snippetBasePathRegExp = new RegExp( snippetData.snippetName.replace( /\//g, '\\/' ) + '.*$' );
  49. const snippetBasePath = snippetData.snippetSources.js.replace( snippetBasePathRegExp, '' );
  50. const dependencySnippet = {
  51. snippetSources: getSnippetSourcePaths( snippetBasePath, dependencyName ),
  52. snippetName: dependencyName,
  53. outputPath: snippetData.outputPath,
  54. destinationPath: snippetData.destinationPath,
  55. requiredFor: snippetData
  56. };
  57. if ( !dependencySnippet.snippetSources.js ) {
  58. throw new Error( `Missing snippet source for "${ dependencySnippet.snippetName }".` );
  59. }
  60. dependencySnippet.snippetConfig = readSnippetConfig( dependencySnippet.snippetSources.js );
  61. dependencySnippet.snippetConfig.language = dependencySnippet.snippetConfig.language || DEFAULT_LANGUAGE;
  62. snippetsDependencies.set( dependencyName, dependencySnippet );
  63. }
  64. }
  65. }
  66. // Add all dependencies to the snippet collection.
  67. for ( const snippetData of snippetsDependencies.values() ) {
  68. snippets.add( snippetData );
  69. }
  70. // Remove snippets that do not match to patterns specified in `options.allowedSnippets`.
  71. if ( options.allowedSnippets && options.allowedSnippets.length ) {
  72. filterAllowedSnippets( snippets, options.allowedSnippets );
  73. console.log( `Found ${ snippets.size } matching {@snippet} tags.` );
  74. }
  75. console.log( `Building ${ countUniqueSnippets( snippets ) } snippets...` );
  76. const groupedSnippetsByLanguage = {};
  77. // Group snippets by language. There is no way to build different languages in a single Webpack process.
  78. // Webpack must be called as many times as different languages are being used in snippets.
  79. for ( const snippetData of snippets ) {
  80. // Multi-languages editors must be built separately.
  81. if ( snippetData.snippetConfig.additionalLanguages ) {
  82. snippetData.snippetConfig.additionalLanguages.push( snippetData.snippetConfig.language );
  83. snippetData.snippetConfig.language = MULTI_LANGUAGE;
  84. }
  85. if ( !groupedSnippetsByLanguage[ snippetData.snippetConfig.language ] ) {
  86. groupedSnippetsByLanguage[ snippetData.snippetConfig.language ] = new Set();
  87. }
  88. groupedSnippetsByLanguage[ snippetData.snippetConfig.language ].add( snippetData );
  89. }
  90. // For each language prepare own Webpack configuration.
  91. const webpackConfigs = Object.keys( groupedSnippetsByLanguage )
  92. .map( language => {
  93. return getWebpackConfig( groupedSnippetsByLanguage[ language ], {
  94. language,
  95. production: options.production,
  96. definitions: options.definitions || {}
  97. } );
  98. } );
  99. let promise = Promise.resolve();
  100. // Nothing to build.
  101. if ( !webpackConfigs.length ) {
  102. return promise;
  103. }
  104. for ( const config of webpackConfigs ) {
  105. promise = promise.then( () => runWebpack( config ) );
  106. }
  107. return promise
  108. .then( () => {
  109. // Group snippets by destination path in order to attach required HTML code and assets (CSS and JS).
  110. const groupedSnippetsByDestinationPath = {};
  111. for ( const snippetData of snippets ) {
  112. if ( !groupedSnippetsByDestinationPath[ snippetData.destinationPath ] ) {
  113. groupedSnippetsByDestinationPath[ snippetData.destinationPath ] = new Set();
  114. }
  115. groupedSnippetsByDestinationPath[ snippetData.destinationPath ].add( snippetData );
  116. }
  117. // For every page that contains at least one snippet, we need to replace Umberto comments with HTML code.
  118. for ( const destinationPath of Object.keys( groupedSnippetsByDestinationPath ) ) {
  119. const snippetsOnPage = groupedSnippetsByDestinationPath[ destinationPath ];
  120. // Assets required for the all snippets.
  121. const cssFiles = [];
  122. const jsFiles = [];
  123. let content = fs.readFileSync( destinationPath ).toString();
  124. for ( const snippetData of snippetsOnPage ) {
  125. // CSS may not be generated by Webpack if a snippet's JS file didn't import any CSS files.
  126. const wasCSSGenerated = fs.existsSync( path.join( snippetData.outputPath, snippetData.snippetName, 'snippet.css' ) );
  127. // If the snippet is a dependency, append JS and CSS to HTML, save to disk and continue.
  128. if ( snippetData.requiredFor ) {
  129. let htmlFile = fs.readFileSync( snippetData.snippetSources.html ).toString();
  130. if ( wasCSSGenerated ) {
  131. htmlFile += '<link rel="stylesheet" href="snippet.css" type="text/css">';
  132. }
  133. htmlFile += '<script src="snippet.js"></script>';
  134. fs.writeFileSync( path.join( snippetData.outputPath, snippetData.snippetName, 'snippet.html' ), htmlFile );
  135. continue;
  136. }
  137. let snippetHTML = fs.readFileSync( snippetData.snippetSources.html ).toString();
  138. if ( snippetHTML.trim() ) {
  139. snippetHTML = snippetHTML.replace( /%BASE_PATH%/g, snippetData.basePath );
  140. snippetHTML = `<div class="live-snippet">${ snippetHTML }</div>`;
  141. }
  142. content = content.replace( getSnippetPlaceholder( snippetData.snippetName ), snippetHTML );
  143. jsFiles.push( path.join( snippetData.basePath, 'assets', 'snippet.js' ) );
  144. jsFiles.push( path.join( snippetData.relativeOutputPath, snippetData.snippetName, 'snippet.js' ) );
  145. cssFiles.push( path.join( snippetData.basePath, 'assets', 'snippet-styles.css' ) );
  146. if ( wasCSSGenerated ) {
  147. cssFiles.unshift( path.join( snippetData.relativeOutputPath, snippetData.snippetName, 'snippet.css' ) );
  148. }
  149. // Additional languages must be imported by the HTML code.
  150. if ( snippetData.snippetConfig.additionalLanguages ) {
  151. snippetData.snippetConfig.additionalLanguages.forEach( language => {
  152. jsFiles.push( path.join( snippetData.relativeOutputPath, 'translations', `${ language }.js` ) );
  153. } );
  154. }
  155. }
  156. const cssImportsHTML = getHTMLImports( cssFiles, importPath => {
  157. return ` <link rel="stylesheet" href="${ importPath }" type="text/css">`;
  158. } );
  159. const jsImportsHTML = getHTMLImports( jsFiles, importPath => {
  160. return ` <script src="${ importPath }"></script>`;
  161. } );
  162. content = content.replace( '<!--UMBERTO: SNIPPET: CSS-->', cssImportsHTML );
  163. content = content.replace( '<!--UMBERTO: SNIPPET: JS-->', jsImportsHTML );
  164. fs.writeFileSync( destinationPath, content );
  165. }
  166. } )
  167. .then( () => {
  168. console.log( 'Finished building snippets.' );
  169. } );
  170. };
  171. /**
  172. * Removes snippets that names do not match to patterns specified in `allowedSnippets` array.
  173. *
  174. * @param {Set.<Snippet>} snippets Snippet collection extracted from documentation files.
  175. * @param {Array.<String>} allowedSnippets Snippet patterns that should be built.
  176. */
  177. function filterAllowedSnippets( snippets, allowedSnippets ) {
  178. const snippetsToBuild = new Set();
  179. // Find all snippets that matched to specified criteria.
  180. for ( const snippetData of snippets ) {
  181. const shouldBeBuilt = allowedSnippets.some( pattern => {
  182. return minimatch( snippetData.snippetName, pattern ) || snippetData.snippetName.includes( pattern );
  183. } );
  184. if ( shouldBeBuilt ) {
  185. snippetsToBuild.add( snippetData );
  186. }
  187. }
  188. // Find all dependencies that are required for whitelisted snippets.
  189. for ( const snippetData of snippets ) {
  190. if ( snippetsToBuild.has( snippetData ) ) {
  191. continue;
  192. }
  193. if ( snippetData.requiredFor && snippetsToBuild.has( snippetData.requiredFor ) ) {
  194. snippetsToBuild.add( snippetData );
  195. }
  196. }
  197. // Remove snippets that won't be built and aren't dependencies of other snippets.
  198. for ( const snippetData of snippets ) {
  199. if ( !snippetsToBuild.has( snippetData ) ) {
  200. snippets.delete( snippetData );
  201. }
  202. }
  203. }
  204. /**
  205. * Prepares configuration for Webpack.
  206. *
  207. * @param {Set.<Snippet>} snippets Snippet collection extracted from documentation files.
  208. * @param {Object} config
  209. * @param {String} config.language Language for the build.
  210. * @param {Boolean} config.production Whether to build for production.
  211. * @param {Object} config.definitions
  212. * @returns {Object}
  213. */
  214. function getWebpackConfig( snippets, config ) {
  215. // Stringify all definitions values. The `DefinePlugin` injects definition values as they are so we need to stringify them,
  216. // so they will become real strings in the generated code. See https://webpack.js.org/plugins/define-plugin/ for more information.
  217. const definitions = {};
  218. for ( const definitionKey in config.definitions ) {
  219. definitions[ definitionKey ] = JSON.stringify( config.definitions[ definitionKey ] );
  220. }
  221. const ckeditorWebpackPluginOptions = {
  222. // All translation files are added to HTML files directly later.
  223. buildAllTranslationsToSeparateFiles: true
  224. };
  225. if ( config.language === MULTI_LANGUAGE ) {
  226. const additionalLanguages = new Set();
  227. // Find all additional languages that must be built.
  228. for ( const snippetData of snippets ) {
  229. for ( const language of snippetData.snippetConfig.additionalLanguages ) {
  230. additionalLanguages.add( language );
  231. }
  232. }
  233. // Pass unique values of `additionalLanguages` to `CKEditorWebpackPlugin`.
  234. ckeditorWebpackPluginOptions.additionalLanguages = [ ...additionalLanguages ];
  235. // Also, set the default language because of the warning that comes from the plugin.
  236. ckeditorWebpackPluginOptions.language = DEFAULT_LANGUAGE;
  237. } else {
  238. ckeditorWebpackPluginOptions.language = config.language;
  239. }
  240. const webpackConfig = {
  241. mode: config.production ? 'production' : 'development',
  242. devtool: 'source-map',
  243. entry: {},
  244. output: {
  245. filename: '[name]/snippet.js'
  246. },
  247. optimization: {
  248. minimizer: [
  249. new TerserPlugin( {
  250. sourceMap: true,
  251. terserOptions: {
  252. output: {
  253. // Preserve CKEditor 5 license comments.
  254. comments: /^!/
  255. }
  256. },
  257. extractComments: false
  258. } )
  259. ]
  260. },
  261. plugins: [
  262. new MiniCssExtractPlugin( { filename: '[name]/snippet.css' } ),
  263. new CKEditorWebpackPlugin( ckeditorWebpackPluginOptions ),
  264. new webpack.BannerPlugin( {
  265. banner: bundler.getLicenseBanner(),
  266. raw: true
  267. } ),
  268. new webpack.DefinePlugin( definitions ),
  269. new ProgressBarPlugin( {
  270. format: `Building snippets for language "${ config.language }": :percent (:msg)`
  271. } )
  272. ],
  273. // Configure the paths so building CKEditor 5 snippets work even if the script
  274. // is triggered from a directory outside ckeditor5 (e.g. multi-project case).
  275. resolve: {
  276. modules: getModuleResolvePaths()
  277. },
  278. resolveLoader: {
  279. modules: getModuleResolvePaths()
  280. },
  281. module: {
  282. rules: [
  283. {
  284. test: /\.svg$/,
  285. use: [ 'raw-loader' ]
  286. },
  287. {
  288. test: /\.css$/,
  289. use: [
  290. MiniCssExtractPlugin.loader,
  291. 'css-loader',
  292. {
  293. loader: 'postcss-loader',
  294. options: styles.getPostCssConfig( {
  295. themeImporter: {
  296. themePath: require.resolve( '@ckeditor/ckeditor5-theme-lark' )
  297. },
  298. minify: config.production
  299. } )
  300. }
  301. ]
  302. }
  303. ]
  304. }
  305. };
  306. for ( const snippetData of snippets ) {
  307. if ( !webpackConfig.output.path ) {
  308. webpackConfig.output.path = snippetData.outputPath;
  309. }
  310. if ( webpackConfig.entry[ snippetData.snippetName ] ) {
  311. continue;
  312. }
  313. webpackConfig.entry[ snippetData.snippetName ] = snippetData.snippetSources.js;
  314. }
  315. return webpackConfig;
  316. }
  317. /**
  318. * Builds snippets.
  319. *
  320. * @param {Object} webpackConfig
  321. * @returns {Promise}
  322. */
  323. function runWebpack( webpackConfig ) {
  324. return new Promise( ( resolve, reject ) => {
  325. webpack( webpackConfig, ( err, stats ) => {
  326. if ( err ) {
  327. reject( err );
  328. } else if ( stats.hasErrors() ) {
  329. reject( new Error( stats.toString() ) );
  330. } else {
  331. resolve();
  332. }
  333. } );
  334. } );
  335. }
  336. /**
  337. * @returns {Array.<String>}
  338. */
  339. function getModuleResolvePaths() {
  340. return [
  341. path.resolve( __dirname, '..', '..', 'node_modules' ),
  342. 'node_modules'
  343. ];
  344. }
  345. /**
  346. * Reads the snippet's configuration.
  347. *
  348. * @param {String} snippetSourcePath An absolute path to the file.
  349. * @returns {Object}
  350. */
  351. function readSnippetConfig( snippetSourcePath ) {
  352. const snippetSource = fs.readFileSync( snippetSourcePath ).toString();
  353. const configSourceMatch = snippetSource.match( /\n\/\* config ([\s\S]+?)\*\// );
  354. if ( !configSourceMatch ) {
  355. return {};
  356. }
  357. return JSON.parse( configSourceMatch[ 1 ] );
  358. }
  359. /**
  360. * Removes duplicated entries specified in `files` array and map those entires using `mapFunction`.
  361. *
  362. * @param {Array.<String>} files Paths collection.
  363. * @param {Function} mapFunction Function that should return a string.
  364. * @returns {String}
  365. */
  366. function getHTMLImports( files, mapFunction ) {
  367. return [ ...new Set( files ) ]
  368. .map( mapFunction )
  369. .join( '\n' )
  370. .replace( /^\s+/, '' );
  371. }
  372. /**
  373. * Returns a number of unique snippet names that will be built.
  374. *
  375. * @param {Set.<Snippet>} snippets Snippet collection extracted from documentation files.
  376. * @returns {Number}
  377. */
  378. function countUniqueSnippets( snippets ) {
  379. return new Set( Array.from( snippets, snippet => snippet.snippetName ) ).size;
  380. }
  381. /**
  382. * @typedef {Object} Snippet
  383. *
  384. * @property {SnippetSource} snippetSources Sources of the snippet.
  385. *
  386. * @property {String} snippetName Name of the snippet. Defined directly after `@snippet` tag.
  387. *
  388. * @property {String} outputPath An absolute path where to write file produced by the `snippetAdapter`.
  389. *
  390. * @property {String} destinationPath An absolute path to the file where the snippet is being used.
  391. *
  392. * @property {SnippetConfiguration} snippetConfig={} Additional configuration of the snippet. It's being read from the snippet's source.
  393. *
  394. * @property {String} [basePath] Relative path from the processed file to the root of the documentation.
  395. *
  396. * @property {String} [relativeOutputPath] The same like `basePath` but for the output path (where processed file will be saved).
  397. *
  398. * @property {Snippet|undefined} [requiredFor] If the value is instance of `Snippet`, current snippet requires
  399. * the snippet defined as `requiredFor` to work.
  400. */
  401. /**
  402. * @typedef {Object} SnippetSource
  403. *
  404. * @property {String} html An absolute path to the HTML sample.
  405. *
  406. * @property {String} css An absolute path to the CSS sample.
  407. *
  408. * @property {String} js An absolute path to the JS sample.
  409. */
  410. /**
  411. * @typedef {Object} SnippetConfiguration
  412. *
  413. * @property {String} [language] A language that will be used for building the editor.
  414. *
  415. * @property {Array.<String>} [dependencies] Names of samples that are required to working.
  416. *
  417. * @property {Array.<String>} [additionalLanguages] Additional languages that are required by the snippet.
  418. */