8
0

snippetadapter.js 18 KB

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