| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355 |
- /**
- * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
- * For licensing, see LICENSE.md.
- */
- /* eslint-env node */
- const path = require( 'path' );
- const fs = require( 'fs' );
- const webpack = require( 'webpack' );
- const { bundler, styles } = require( '@ckeditor/ckeditor5-dev-utils' );
- const CKEditorWebpackPlugin = require( '@ckeditor/ckeditor5-dev-webpack-plugin' );
- const MiniCssExtractPlugin = require( 'mini-css-extract-plugin' );
- const UglifyJsWebpackPlugin = require( 'uglifyjs-webpack-plugin' );
- const ProgressBarPlugin = require( 'progress-bar-webpack-plugin' );
- const DEFAULT_LANGUAGE = 'en';
- /**
- * @param {Set.<Snippet>} snippets
- * @param {Object} options
- * @param {Object.<String, Function>} umbertoHelpers
- * @returns {Promise}
- */
- module.exports = function snippetAdapter( snippets, options, umbertoHelpers ) {
- const { getSnippetPlaceholder, getSnippetSourcePaths } = umbertoHelpers;
- const snippetsDependencies = new Map();
- // For each snippet, load its config. If the snippet has defined dependencies, load those as well.
- for ( const snippetData of snippets ) {
- if ( !snippetData.snippetSources.js ) {
- throw new Error( `Missing snippet source for "${ snippetData.snippetName }".` );
- }
- snippetData.snippetConfig = readSnippetConfig( snippetData.snippetSources.js );
- snippetData.snippetConfig.language = snippetData.snippetConfig.language || DEFAULT_LANGUAGE;
- if ( snippetData.snippetConfig.dependencies ) {
- for ( const dependencyName of snippetData.snippetConfig.dependencies ) {
- // Do not load the same dependency more than once.
- if ( snippetsDependencies.has( dependencyName ) ) {
- continue;
- }
- // Find a root path where to look for the snippet's sources. We just want to pass them through Webpack.
- const snippetBasePathRegExp = new RegExp( snippetData.snippetName.replace( /\//g, '\\/' ) + '.*$' );
- const snippetBasePath = snippetData.snippetSources.js.replace( snippetBasePathRegExp, '' );
- const dependencySnippet = {
- snippetSources: getSnippetSourcePaths( snippetBasePath, dependencyName ),
- snippetName: dependencyName,
- outputPath: snippetData.outputPath,
- destinationPath: snippetData.destinationPath,
- isDependency: true
- };
- if ( !dependencySnippet.snippetSources.js ) {
- throw new Error( `Missing snippet source for "${ dependencySnippet.snippetName }".` );
- }
- dependencySnippet.snippetConfig = readSnippetConfig( dependencySnippet.snippetSources.js );
- dependencySnippet.snippetConfig.language = dependencySnippet.snippetConfig.language || DEFAULT_LANGUAGE;
- snippetsDependencies.set( dependencyName, dependencySnippet );
- }
- }
- }
- for ( const snippetData of snippetsDependencies.values() ) {
- snippets.add( snippetData );
- }
- const groupedSnippetsByLanguage = {};
- // Group snippets by language. There is no way to build different languages in a single Webpack process.
- // Webpack must be called as many times as different languages are being used in snippets.
- for ( const snippetData of snippets ) {
- if ( !groupedSnippetsByLanguage[ snippetData.snippetConfig.language ] ) {
- groupedSnippetsByLanguage[ snippetData.snippetConfig.language ] = new Set();
- }
- groupedSnippetsByLanguage[ snippetData.snippetConfig.language ].add( snippetData );
- }
- // For each language prepare own Webpack configuration.
- const webpackConfigs = Object.keys( groupedSnippetsByLanguage )
- .map( language => {
- return getWebpackConfig( groupedSnippetsByLanguage[ language ], {
- language,
- production: options.production,
- definitions: options.definitions || {}
- } );
- } );
- let promise = Promise.resolve();
- if ( !webpackConfigs.length ) {
- return promise;
- }
- for ( const config of webpackConfigs ) {
- promise = promise.then( () => runWebpack( config ) );
- }
- return promise
- .then( () => {
- // Group snippets by destination path in order to attach required HTML code and assets (CSS and JS).
- const groupedSnippetsByDestinationPath = {};
- for ( const snippetData of snippets ) {
- if ( !groupedSnippetsByDestinationPath[ snippetData.destinationPath ] ) {
- groupedSnippetsByDestinationPath[ snippetData.destinationPath ] = new Set();
- }
- groupedSnippetsByDestinationPath[ snippetData.destinationPath ].add( snippetData );
- }
- for ( const destinationPath of Object.keys( groupedSnippetsByDestinationPath ) ) {
- const snippetsOnPage = groupedSnippetsByDestinationPath[ destinationPath ];
- const cssFiles = [];
- const jsFiles = [];
- let content = fs.readFileSync( destinationPath ).toString();
- for ( const snippetData of snippetsOnPage ) {
- // CSS may not be generated by Webpack if a snippet's JS file didn't import any CSS files.
- const wasCSSGenerated = fs.existsSync( path.join( snippetData.outputPath, snippetData.snippetName, 'snippet.css' ) );
- // If the snippet is a dependency, append JS and CSS to HTML save to disk and continue.
- if ( snippetData.isDependency ) {
- let htmlFile = fs.readFileSync( snippetData.snippetSources.html ).toString();
- if ( wasCSSGenerated ) {
- htmlFile += '<link rel="stylesheet" href="snippet.css" type="text/css">';
- }
- htmlFile += '<script src="snippet.js"></script>';
- fs.writeFileSync( path.join( snippetData.outputPath, snippetData.snippetName, 'snippet.html' ), htmlFile );
- continue;
- }
- let snippetHTML;
- if ( fs.existsSync( snippetData.snippetSources.html ) ) {
- snippetHTML = fs.readFileSync( snippetData.snippetSources.html ).toString();
- snippetHTML = snippetHTML.replace( /%BASE_PATH%/g, snippetData.basePath );
- snippetHTML = `<div class="live-snippet">${ snippetHTML }</div>`;
- } else {
- snippetHTML = '';
- }
- content = content.replace( getSnippetPlaceholder( snippetData.snippetName ), snippetHTML );
- jsFiles.push( path.join( snippetData.basePath, 'assets', 'snippet.js' ) );
- jsFiles.push( path.join( snippetData.relativeOutputPath, snippetData.snippetName, 'snippet.js' ) );
- cssFiles.push( path.join( snippetData.basePath, 'assets', 'snippet-styles.css' ) );
- if ( wasCSSGenerated ) {
- cssFiles.unshift( path.join( snippetData.relativeOutputPath, snippetData.snippetName, 'snippet.css' ) );
- }
- }
- const cssImportsHTML = [ ...new Set( cssFiles ) ]
- .map( importPath => ` <link rel="stylesheet" href="${ importPath }" type="text/css">` )
- .join( '\n' )
- .replace( /^\s+/, '' );
- const jsImportsHTML = [ ...new Set( jsFiles ) ]
- .map( importPath => ` <script src="${ importPath }"></script>` )
- .join( '\n' )
- .replace( /^\s+/, '' );
- content = content.replace( '<!--UMBERTO: SNIPPET: CSS-->', cssImportsHTML );
- content = content.replace( '<!--UMBERTO: SNIPPET: JS-->', jsImportsHTML );
- fs.writeFileSync( destinationPath, content );
- }
- } );
- };
- function getWebpackConfig( snippets, config ) {
- // Stringify all definitions values. The `DefinePlugin` injects definition values as they are so we need to stringify them,
- // so they will become real strings in the generated code. See https://webpack.js.org/plugins/define-plugin/ for more information.
- const definitions = {};
- for ( const definitionKey in config.definitions ) {
- definitions[ definitionKey ] = JSON.stringify( config.definitions[ definitionKey ] );
- }
- const webpackConfig = {
- mode: config.production ? 'production' : 'development',
- devtool: 'source-map',
- entry: {},
- output: {
- filename: '[name]/snippet.js'
- },
- optimization: {
- minimizer: [
- new UglifyJsWebpackPlugin( {
- sourceMap: true,
- uglifyOptions: {
- output: {
- // Preserve license comments starting with an exclamation mark.
- comments: /^!/
- }
- }
- } )
- ]
- },
- plugins: [
- new MiniCssExtractPlugin( { filename: '[name]/snippet.css' } ),
- new CKEditorWebpackPlugin( {
- language: config.language
- } ),
- new webpack.BannerPlugin( {
- banner: bundler.getLicenseBanner(),
- raw: true
- } ),
- new webpack.DefinePlugin( definitions ),
- new ProgressBarPlugin( {
- format: `Building snippets for language "${ config.language }": :percent (:msg)`,
- } )
- ],
- // Configure the paths so building CKEditor 5 snippets work even if the script
- // is triggered from a directory outside ckeditor5 (e.g. multi-project case).
- resolve: {
- modules: getModuleResolvePaths()
- },
- resolveLoader: {
- modules: getModuleResolvePaths()
- },
- module: {
- rules: [
- {
- test: /\.svg$/,
- use: [ 'raw-loader' ]
- },
- {
- test: /\.css$/,
- use: [
- MiniCssExtractPlugin.loader,
- 'css-loader',
- {
- loader: 'postcss-loader',
- options: styles.getPostCssConfig( {
- themeImporter: {
- themePath: require.resolve( '@ckeditor/ckeditor5-theme-lark' )
- },
- minify: config.production
- } )
- }
- ]
- }
- ]
- }
- };
- for ( const snippetData of snippets ) {
- if ( !webpackConfig.output.path ) {
- webpackConfig.output.path = snippetData.outputPath;
- }
- if ( webpackConfig.entry[ snippetData.snippetName ] ) {
- continue;
- }
- webpackConfig.entry[ snippetData.snippetName ] = snippetData.snippetSources.js;
- }
- return webpackConfig;
- }
- function runWebpack( webpackConfig ) {
- return new Promise( ( resolve, reject ) => {
- webpack( webpackConfig, ( err, stats ) => {
- if ( err ) {
- reject( err );
- } else if ( stats.hasErrors() ) {
- reject( new Error( stats.toString() ) );
- } else {
- resolve();
- }
- } );
- } );
- }
- function getModuleResolvePaths() {
- return [
- path.resolve( __dirname, '..', '..', 'node_modules' ),
- 'node_modules'
- ];
- }
- function readSnippetConfig( snippetSourcePath ) {
- const snippetSource = fs.readFileSync( snippetSourcePath ).toString();
- const configSourceMatch = snippetSource.match( /\n\/\* config ([\s\S]+?)\*\// );
- if ( !configSourceMatch ) {
- return {};
- }
- return JSON.parse( configSourceMatch[ 1 ] );
- }
- /**
- * @typedef {Object} Snippet
- *
- * @property {SnippetSource} snippetSources Sources of the snippet.
- *
- * @property {String} snippetName Name of the snippet. Defined directly after `@snippet` tag.
- *
- * @property {String} outputPath An absolute path where to write file produced by the `snippetAdapter`.
- *
- * @property {String} destinationPath An absolute path to the file where the snippet is being used.
- *
- * @property {SnippetConfiguration} snippetConfig={} Additional configuration of the snippet. It's being read from the snippet's source.
- *
- * @property {String} [basePath] Relative path from the processed file to the root of the documentation.
- *
- * @property {String} [relativeOutputPath] The same like `basePath` but for the output path (where processed file will be saved).
- *
- * @property {Boolean} [isDependency] Whether parsed snippet is a dependency of other snippet.
- */
- /**
- * @typedef {Object} SnippetSource
- *
- * @property {<String>} html An absolute path to the HTML sample.
- *
- * @property {<String>} css An absolute path to the CSS sample.
- *
- * @property {<String>} js An absolute path to the JS sample.
- */
- /**
- * @typedef {Object} SnippetConfiguration
- *
- * @property {<String>} [language] A language that will be used for building the editor.
- *
- * @property {Array.<String>} [dependencies] Names of samples that are required to working.
- */
|