8
0

snippetadapter.js 19 KB

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