snippetadapter.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  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. const constantDefinitions = getConstantDefinitions( snippets );
  78. // Group snippets by language. There is no way to build different languages in a single Webpack process.
  79. // Webpack must be called as many times as different languages are being used in snippets.
  80. for ( const snippetData of snippets ) {
  81. // Multi-languages editors must be built separately.
  82. if ( snippetData.snippetConfig.additionalLanguages ) {
  83. snippetData.snippetConfig.additionalLanguages.push( snippetData.snippetConfig.language );
  84. snippetData.snippetConfig.language = MULTI_LANGUAGE;
  85. }
  86. if ( !groupedSnippetsByLanguage[ snippetData.snippetConfig.language ] ) {
  87. groupedSnippetsByLanguage[ snippetData.snippetConfig.language ] = new Set();
  88. }
  89. groupedSnippetsByLanguage[ snippetData.snippetConfig.language ].add( snippetData );
  90. }
  91. // For each language prepare own Webpack configuration.
  92. const webpackConfigs = Object.keys( groupedSnippetsByLanguage )
  93. .map( language => {
  94. return getWebpackConfig( groupedSnippetsByLanguage[ language ], {
  95. language,
  96. production: options.production,
  97. definitions: {
  98. ...( options.definitions || {} ),
  99. ...constantDefinitions
  100. }
  101. } );
  102. } );
  103. let promise = Promise.resolve();
  104. // Nothing to build.
  105. if ( !webpackConfigs.length ) {
  106. return promise;
  107. }
  108. for ( const config of webpackConfigs ) {
  109. promise = promise.then( () => runWebpack( config ) );
  110. }
  111. return promise
  112. .then( () => {
  113. // Group snippets by destination path in order to attach required HTML code and assets (CSS and JS).
  114. const groupedSnippetsByDestinationPath = {};
  115. for ( const snippetData of snippets ) {
  116. if ( !groupedSnippetsByDestinationPath[ snippetData.destinationPath ] ) {
  117. groupedSnippetsByDestinationPath[ snippetData.destinationPath ] = new Set();
  118. }
  119. groupedSnippetsByDestinationPath[ snippetData.destinationPath ].add( snippetData );
  120. }
  121. // For every page that contains at least one snippet, we need to replace Umberto comments with HTML code.
  122. for ( const destinationPath of Object.keys( groupedSnippetsByDestinationPath ) ) {
  123. const snippetsOnPage = groupedSnippetsByDestinationPath[ destinationPath ];
  124. // Assets required for the all snippets.
  125. const cssFiles = [];
  126. const jsFiles = [];
  127. let content = fs.readFileSync( destinationPath ).toString();
  128. for ( const snippetData of snippetsOnPage ) {
  129. // CSS may not be generated by Webpack if a snippet's JS file didn't import any CSS files.
  130. const wasCSSGenerated = fs.existsSync( path.join( snippetData.outputPath, snippetData.snippetName, 'snippet.css' ) );
  131. // If the snippet is a dependency, append JS and CSS to HTML, save to disk and continue.
  132. if ( snippetData.requiredFor ) {
  133. let htmlFile = fs.readFileSync( snippetData.snippetSources.html ).toString();
  134. if ( wasCSSGenerated ) {
  135. htmlFile += '<link rel="stylesheet" href="snippet.css" type="text/css">';
  136. }
  137. htmlFile += '<script src="snippet.js"></script>';
  138. fs.writeFileSync( path.join( snippetData.outputPath, snippetData.snippetName, 'snippet.html' ), htmlFile );
  139. continue;
  140. }
  141. let snippetHTML = fs.readFileSync( snippetData.snippetSources.html ).toString();
  142. if ( snippetHTML.trim() ) {
  143. snippetHTML = snippetHTML.replace( /%BASE_PATH%/g, snippetData.basePath );
  144. snippetHTML = `<div class="live-snippet">${ snippetHTML }</div>`;
  145. }
  146. content = content.replace( getSnippetPlaceholder( snippetData.snippetName ), snippetHTML );
  147. jsFiles.push( path.join( snippetData.basePath, 'assets', 'snippet.js' ) );
  148. jsFiles.push( path.join( snippetData.relativeOutputPath, snippetData.snippetName, 'snippet.js' ) );
  149. cssFiles.push( path.join( snippetData.basePath, 'assets', 'snippet-styles.css' ) );
  150. if ( wasCSSGenerated ) {
  151. cssFiles.unshift( path.join( snippetData.relativeOutputPath, snippetData.snippetName, 'snippet.css' ) );
  152. }
  153. // Additional languages must be imported by the HTML code.
  154. if ( snippetData.snippetConfig.additionalLanguages ) {
  155. snippetData.snippetConfig.additionalLanguages.forEach( language => {
  156. jsFiles.push( path.join( snippetData.relativeOutputPath, 'translations', `${ language }.js` ) );
  157. } );
  158. }
  159. }
  160. const cssImportsHTML = getHTMLImports( cssFiles, importPath => {
  161. return ` <link rel="stylesheet" href="${ importPath }" type="text/css" data-cke="true">`;
  162. } );
  163. const jsImportsHTML = getHTMLImports( jsFiles, importPath => {
  164. return ` <script src="${ importPath }"></script>`;
  165. } );
  166. content = content.replace( '<!--UMBERTO: SNIPPET: CSS-->', cssImportsHTML );
  167. content = content.replace( '<!--UMBERTO: SNIPPET: JS-->', jsImportsHTML );
  168. fs.writeFileSync( destinationPath, content );
  169. }
  170. } )
  171. .then( () => {
  172. console.log( 'Finished building snippets.' );
  173. } );
  174. };
  175. /**
  176. * Removes snippets that names do not match to patterns specified in `allowedSnippets` array.
  177. *
  178. * @param {Set.<Snippet>} snippets Snippet collection extracted from documentation files.
  179. * @param {Array.<String>} allowedSnippets Snippet patterns that should be built.
  180. */
  181. function filterAllowedSnippets( snippets, allowedSnippets ) {
  182. const snippetsToBuild = new Set();
  183. // Find all snippets that matched to specified criteria.
  184. for ( const snippetData of snippets ) {
  185. const shouldBeBuilt = allowedSnippets.some( pattern => {
  186. return minimatch( snippetData.snippetName, pattern ) || snippetData.snippetName.includes( pattern );
  187. } );
  188. if ( shouldBeBuilt ) {
  189. snippetsToBuild.add( snippetData );
  190. }
  191. }
  192. // Find all dependencies that are required for whitelisted snippets.
  193. for ( const snippetData of snippets ) {
  194. if ( snippetsToBuild.has( snippetData ) ) {
  195. continue;
  196. }
  197. if ( snippetData.requiredFor && snippetsToBuild.has( snippetData.requiredFor ) ) {
  198. snippetsToBuild.add( snippetData );
  199. }
  200. }
  201. // Remove snippets that won't be built and aren't dependencies of other snippets.
  202. for ( const snippetData of snippets ) {
  203. if ( !snippetsToBuild.has( snippetData ) ) {
  204. snippets.delete( snippetData );
  205. }
  206. }
  207. }
  208. /**
  209. * Adds constants to the webpack process from external repositories containing `docs/constants.js` files.
  210. *
  211. * @param {Array.<Object>} snippets
  212. * @returns {Object}
  213. */
  214. function getConstantDefinitions( snippets ) {
  215. const knownPaths = new Set();
  216. const constantDefinitions = {};
  217. const constantOrigins = new Map();
  218. for ( const snippet of snippets ) {
  219. if ( !snippet.pageSourcePath ) {
  220. continue;
  221. }
  222. let directory = path.dirname( snippet.pageSourcePath );
  223. while ( !knownPaths.has( directory ) ) {
  224. knownPaths.add( directory );
  225. const absolutePathToConstants = path.join( directory, 'docs', 'constants.js' );
  226. const importPathToConstants = path.posix.relative( __dirname, absolutePathToConstants );
  227. if ( fs.existsSync( absolutePathToConstants ) ) {
  228. const packageConstantDefinitions = require( './' + importPathToConstants );
  229. for ( const constantName in packageConstantDefinitions ) {
  230. const constantValue = packageConstantDefinitions[ constantName ];
  231. if ( constantDefinitions[ constantName ] && constantDefinitions[ constantName ] !== constantValue ) {
  232. throw new Error(
  233. `Definition for the '${ constantName }' constant is duplicated` +
  234. ` (${ importPathToConstants }, ${ constantOrigins.get( constantName ) }).`
  235. );
  236. }
  237. constantDefinitions[ constantName ] = constantValue;
  238. constantOrigins.set( constantName, importPathToConstants );
  239. }
  240. Object.assign( constantDefinitions, packageConstantDefinitions );
  241. }
  242. directory = path.dirname( directory );
  243. }
  244. }
  245. return constantDefinitions;
  246. }
  247. /**
  248. * Prepares configuration for Webpack.
  249. *
  250. * @param {Set.<Snippet>} snippets Snippet collection extracted from documentation files.
  251. * @param {Object} config
  252. * @param {String} config.language Language for the build.
  253. * @param {Boolean} config.production Whether to build for production.
  254. * @param {Object} config.definitions
  255. * @returns {Object}
  256. */
  257. function getWebpackConfig( snippets, config ) {
  258. // Stringify all definitions values. The `DefinePlugin` injects definition values as they are so we need to stringify them,
  259. // so they will become real strings in the generated code. See https://webpack.js.org/plugins/define-plugin/ for more information.
  260. const definitions = {};
  261. for ( const definitionKey in config.definitions ) {
  262. definitions[ definitionKey ] = JSON.stringify( config.definitions[ definitionKey ] );
  263. }
  264. const ckeditorWebpackPluginOptions = {
  265. // All translation files are added to HTML files directly later.
  266. buildAllTranslationsToSeparateFiles: true
  267. };
  268. if ( config.language === MULTI_LANGUAGE ) {
  269. const additionalLanguages = new Set();
  270. // Find all additional languages that must be built.
  271. for ( const snippetData of snippets ) {
  272. for ( const language of snippetData.snippetConfig.additionalLanguages ) {
  273. additionalLanguages.add( language );
  274. }
  275. }
  276. // Pass unique values of `additionalLanguages` to `CKEditorWebpackPlugin`.
  277. ckeditorWebpackPluginOptions.additionalLanguages = [ ...additionalLanguages ];
  278. // Also, set the default language because of the warning that comes from the plugin.
  279. ckeditorWebpackPluginOptions.language = DEFAULT_LANGUAGE;
  280. } else {
  281. ckeditorWebpackPluginOptions.language = config.language;
  282. }
  283. const webpackConfig = {
  284. mode: config.production ? 'production' : 'development',
  285. entry: {},
  286. output: {
  287. filename: '[name]/snippet.js'
  288. },
  289. optimization: {
  290. minimizer: [
  291. new TerserPlugin( {
  292. sourceMap: true,
  293. terserOptions: {
  294. output: {
  295. // Preserve CKEditor 5 license comments.
  296. comments: /^!/
  297. }
  298. },
  299. extractComments: false
  300. } )
  301. ]
  302. },
  303. plugins: [
  304. new MiniCssExtractPlugin( { filename: '[name]/snippet.css' } ),
  305. new CKEditorWebpackPlugin( ckeditorWebpackPluginOptions ),
  306. new webpack.BannerPlugin( {
  307. banner: bundler.getLicenseBanner(),
  308. raw: true
  309. } ),
  310. new webpack.DefinePlugin( definitions ),
  311. new ProgressBarPlugin( {
  312. format: `Building snippets for language "${ config.language }": :percent (:msg)`
  313. } )
  314. ],
  315. // Configure the paths so building CKEditor 5 snippets work even if the script
  316. // is triggered from a directory outside ckeditor5 (e.g. multi-project case).
  317. resolve: {
  318. modules: getModuleResolvePaths()
  319. },
  320. resolveLoader: {
  321. modules: getModuleResolvePaths()
  322. },
  323. module: {
  324. rules: [
  325. {
  326. test: /\.svg$/,
  327. use: [ 'raw-loader' ]
  328. },
  329. {
  330. test: /\.css$/,
  331. use: [
  332. MiniCssExtractPlugin.loader,
  333. 'css-loader',
  334. {
  335. loader: 'postcss-loader',
  336. options: styles.getPostCssConfig( {
  337. themeImporter: {
  338. themePath: require.resolve( '@ckeditor/ckeditor5-theme-lark' )
  339. },
  340. minify: config.production
  341. } )
  342. }
  343. ]
  344. }
  345. ]
  346. }
  347. };
  348. for ( const snippetData of snippets ) {
  349. if ( !webpackConfig.output.path ) {
  350. webpackConfig.output.path = snippetData.outputPath;
  351. }
  352. if ( webpackConfig.entry[ snippetData.snippetName ] ) {
  353. continue;
  354. }
  355. webpackConfig.entry[ snippetData.snippetName ] = snippetData.snippetSources.js;
  356. }
  357. return webpackConfig;
  358. }
  359. /**
  360. * Builds snippets.
  361. *
  362. * @param {Object} webpackConfig
  363. * @returns {Promise}
  364. */
  365. function runWebpack( webpackConfig ) {
  366. return new Promise( ( resolve, reject ) => {
  367. webpack( webpackConfig, ( err, stats ) => {
  368. if ( err ) {
  369. reject( err );
  370. } else if ( stats.hasErrors() ) {
  371. reject( new Error( stats.toString() ) );
  372. } else {
  373. resolve();
  374. }
  375. } );
  376. } );
  377. }
  378. /**
  379. * @returns {Array.<String>}
  380. */
  381. function getModuleResolvePaths() {
  382. return [
  383. path.resolve( __dirname, '..', '..', 'node_modules' ),
  384. 'node_modules'
  385. ];
  386. }
  387. /**
  388. * Reads the snippet's configuration.
  389. *
  390. * @param {String} snippetSourcePath An absolute path to the file.
  391. * @returns {Object}
  392. */
  393. function readSnippetConfig( snippetSourcePath ) {
  394. const snippetSource = fs.readFileSync( snippetSourcePath ).toString();
  395. const configSourceMatch = snippetSource.match( /\n\/\* config ([\s\S]+?)\*\// );
  396. if ( !configSourceMatch ) {
  397. return {};
  398. }
  399. return JSON.parse( configSourceMatch[ 1 ] );
  400. }
  401. /**
  402. * Removes duplicated entries specified in `files` array and map those entires using `mapFunction`.
  403. *
  404. * @param {Array.<String>} files Paths collection.
  405. * @param {Function} mapFunction Function that should return a string.
  406. * @returns {String}
  407. */
  408. function getHTMLImports( files, mapFunction ) {
  409. return [ ...new Set( files ) ]
  410. .map( mapFunction )
  411. .join( '\n' )
  412. .replace( /^\s+/, '' );
  413. }
  414. /**
  415. * Returns a number of unique snippet names that will be built.
  416. *
  417. * @param {Set.<Snippet>} snippets Snippet collection extracted from documentation files.
  418. * @returns {Number}
  419. */
  420. function countUniqueSnippets( snippets ) {
  421. return new Set( Array.from( snippets, snippet => snippet.snippetName ) ).size;
  422. }
  423. /**
  424. * @typedef {Object} Snippet
  425. *
  426. * @property {SnippetSource} snippetSources Sources of the snippet.
  427. *
  428. * @property {String} snippetName Name of the snippet. Defined directly after `@snippet` tag.
  429. *
  430. * @property {String} outputPath An absolute path where to write file produced by the `snippetAdapter`.
  431. *
  432. * @property {String} destinationPath An absolute path to the file where the snippet is being used.
  433. *
  434. * @property {SnippetConfiguration} snippetConfig={} Additional configuration of the snippet. It's being read from the snippet's source.
  435. *
  436. * @property {String} [basePath] Relative path from the processed file to the root of the documentation.
  437. *
  438. * @property {String} [relativeOutputPath] The same like `basePath` but for the output path (where processed file will be saved).
  439. *
  440. * @property {Snippet|undefined} [requiredFor] If the value is instance of `Snippet`, current snippet requires
  441. * the snippet defined as `requiredFor` to work.
  442. */
  443. /**
  444. * @typedef {Object} SnippetSource
  445. *
  446. * @property {String} html An absolute path to the HTML sample.
  447. *
  448. * @property {String} css An absolute path to the CSS sample.
  449. *
  450. * @property {String} js An absolute path to the JS sample.
  451. */
  452. /**
  453. * @typedef {Object} SnippetConfiguration
  454. *
  455. * @property {String} [language] A language that will be used for building the editor.
  456. *
  457. * @property {Array.<String>} [dependencies] Names of samples that are required to working.
  458. *
  459. * @property {Array.<String>} [additionalLanguages] Additional languages that are required by the snippet.
  460. */