8
0

snippetadapter.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  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" data-cke="true">`;
  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. entry: {},
  243. output: {
  244. filename: '[name]/snippet.js'
  245. },
  246. optimization: {
  247. minimizer: [
  248. new TerserPlugin( {
  249. sourceMap: true,
  250. terserOptions: {
  251. output: {
  252. // Preserve CKEditor 5 license comments.
  253. comments: /^!/
  254. }
  255. },
  256. extractComments: false
  257. } )
  258. ]
  259. },
  260. plugins: [
  261. new MiniCssExtractPlugin( { filename: '[name]/snippet.css' } ),
  262. new CKEditorWebpackPlugin( ckeditorWebpackPluginOptions ),
  263. new webpack.BannerPlugin( {
  264. banner: bundler.getLicenseBanner(),
  265. raw: true
  266. } ),
  267. new webpack.DefinePlugin( definitions ),
  268. new ProgressBarPlugin( {
  269. format: `Building snippets for language "${ config.language }": :percent (:msg)`
  270. } )
  271. ],
  272. // Configure the paths so building CKEditor 5 snippets work even if the script
  273. // is triggered from a directory outside ckeditor5 (e.g. multi-project case).
  274. resolve: {
  275. modules: getModuleResolvePaths()
  276. },
  277. resolveLoader: {
  278. modules: getModuleResolvePaths()
  279. },
  280. module: {
  281. rules: [
  282. {
  283. test: /\.svg$/,
  284. use: [ 'raw-loader' ]
  285. },
  286. {
  287. test: /\.css$/,
  288. use: [
  289. MiniCssExtractPlugin.loader,
  290. 'css-loader',
  291. {
  292. loader: 'postcss-loader',
  293. options: styles.getPostCssConfig( {
  294. themeImporter: {
  295. themePath: require.resolve( '@ckeditor/ckeditor5-theme-lark' )
  296. },
  297. minify: config.production
  298. } )
  299. }
  300. ]
  301. }
  302. ]
  303. }
  304. };
  305. for ( const snippetData of snippets ) {
  306. if ( !webpackConfig.output.path ) {
  307. webpackConfig.output.path = snippetData.outputPath;
  308. }
  309. if ( webpackConfig.entry[ snippetData.snippetName ] ) {
  310. continue;
  311. }
  312. webpackConfig.entry[ snippetData.snippetName ] = snippetData.snippetSources.js;
  313. }
  314. return webpackConfig;
  315. }
  316. /**
  317. * Builds snippets.
  318. *
  319. * @param {Object} webpackConfig
  320. * @returns {Promise}
  321. */
  322. function runWebpack( webpackConfig ) {
  323. return new Promise( ( resolve, reject ) => {
  324. webpack( webpackConfig, ( err, stats ) => {
  325. if ( err ) {
  326. reject( err );
  327. } else if ( stats.hasErrors() ) {
  328. reject( new Error( stats.toString() ) );
  329. } else {
  330. resolve();
  331. }
  332. } );
  333. } );
  334. }
  335. /**
  336. * @returns {Array.<String>}
  337. */
  338. function getModuleResolvePaths() {
  339. return [
  340. path.resolve( __dirname, '..', '..', 'node_modules' ),
  341. 'node_modules'
  342. ];
  343. }
  344. /**
  345. * Reads the snippet's configuration.
  346. *
  347. * @param {String} snippetSourcePath An absolute path to the file.
  348. * @returns {Object}
  349. */
  350. function readSnippetConfig( snippetSourcePath ) {
  351. const snippetSource = fs.readFileSync( snippetSourcePath ).toString();
  352. const configSourceMatch = snippetSource.match( /\n\/\* config ([\s\S]+?)\*\// );
  353. if ( !configSourceMatch ) {
  354. return {};
  355. }
  356. return JSON.parse( configSourceMatch[ 1 ] );
  357. }
  358. /**
  359. * Removes duplicated entries specified in `files` array and map those entires using `mapFunction`.
  360. *
  361. * @param {Array.<String>} files Paths collection.
  362. * @param {Function} mapFunction Function that should return a string.
  363. * @returns {String}
  364. */
  365. function getHTMLImports( files, mapFunction ) {
  366. return [ ...new Set( files ) ]
  367. .map( mapFunction )
  368. .join( '\n' )
  369. .replace( /^\s+/, '' );
  370. }
  371. /**
  372. * Returns a number of unique snippet names that will be built.
  373. *
  374. * @param {Set.<Snippet>} snippets Snippet collection extracted from documentation files.
  375. * @returns {Number}
  376. */
  377. function countUniqueSnippets( snippets ) {
  378. return new Set( Array.from( snippets, snippet => snippet.snippetName ) ).size;
  379. }
  380. /**
  381. * @typedef {Object} Snippet
  382. *
  383. * @property {SnippetSource} snippetSources Sources of the snippet.
  384. *
  385. * @property {String} snippetName Name of the snippet. Defined directly after `@snippet` tag.
  386. *
  387. * @property {String} outputPath An absolute path where to write file produced by the `snippetAdapter`.
  388. *
  389. * @property {String} destinationPath An absolute path to the file where the snippet is being used.
  390. *
  391. * @property {SnippetConfiguration} snippetConfig={} Additional configuration of the snippet. It's being read from the snippet's source.
  392. *
  393. * @property {String} [basePath] Relative path from the processed file to the root of the documentation.
  394. *
  395. * @property {String} [relativeOutputPath] The same like `basePath` but for the output path (where processed file will be saved).
  396. *
  397. * @property {Snippet|undefined} [requiredFor] If the value is instance of `Snippet`, current snippet requires
  398. * the snippet defined as `requiredFor` to work.
  399. */
  400. /**
  401. * @typedef {Object} SnippetSource
  402. *
  403. * @property {String} html An absolute path to the HTML sample.
  404. *
  405. * @property {String} css An absolute path to the CSS sample.
  406. *
  407. * @property {String} js An absolute path to the JS sample.
  408. */
  409. /**
  410. * @typedef {Object} SnippetConfiguration
  411. *
  412. * @property {String} [language] A language that will be used for building the editor.
  413. *
  414. * @property {Array.<String>} [dependencies] Names of samples that are required to working.
  415. *
  416. * @property {Array.<String>} [additionalLanguages] Additional languages that are required by the snippet.
  417. */