8
0

utils.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. /**
  2. * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. 'use strict';
  6. const path = require( 'path' );
  7. const gulp = require( 'gulp' );
  8. const rename = require( 'gulp-rename' );
  9. const replace = require( 'gulp-replace' );
  10. const gulpBabel = require( 'gulp-babel' );
  11. const gutil = require( 'gulp-util' );
  12. const gulpFilter = require( 'gulp-filter' );
  13. const multipipe = require( 'multipipe' );
  14. const PassThrough = require( 'stream' ).PassThrough;
  15. const through = require( 'through2' );
  16. const fs = require( 'fs' );
  17. const sass = require( 'node-sass' );
  18. const del = require( 'del' );
  19. const minimist = require( 'minimist' );
  20. const sprite = require( 'gulp-svg-sprite' );
  21. const pipe = require( 'multipipe' );
  22. const filter = require( 'gulp-filter' );
  23. const utils = {
  24. /**
  25. * Code which can be appended to a transpiled (into AMD) test files in order to
  26. * load the 'tests' module and defer launching Bender until it's ready.
  27. *
  28. * Note: This code will not be transpiled so keep it in ES5.
  29. */
  30. benderLauncherCode:
  31. `
  32. require( [ 'tests' ], bender.defer(), function( err ) {
  33. // The problem with Require.JS is that there are no stacktraces if we won't log this.
  34. console.error( err );
  35. console.log( err.stack );
  36. } );
  37. `,
  38. /**
  39. * Module formats supported by the builder.
  40. */
  41. SUPPORTED_FORMATS: [ 'esnext', 'amd', 'cjs' ],
  42. /**
  43. * Creates a simple duplex stream.
  44. *
  45. * @param {Function} [callback] A callback which will be executed with each chunk.
  46. * @returns {Stream}
  47. */
  48. noop( callback ) {
  49. if ( !callback ) {
  50. return new PassThrough( { objectMode: true } );
  51. }
  52. return through( { objectMode: true }, ( file, encoding, throughCallback ) => {
  53. callback( file );
  54. throughCallback( null, file );
  55. } );
  56. },
  57. /**
  58. * Saves the files piped into this stream to the `build/` directory.
  59. *
  60. * @param {String} buildDir The `build/` directory path.
  61. * @param {String} format The format of the buildribution (`esnext`, `amd`, or `cjs`).
  62. * @returns {Stream}
  63. */
  64. destBuild( buildDir, format ) {
  65. const destDir = path.join( buildDir, format );
  66. return gulp.dest( destDir );
  67. },
  68. /**
  69. * Creates a function generating convertion streams.
  70. * Used to generate `formats.reduce()` callback where `formats` is an array of formats that should be generated.
  71. *
  72. * @param {String} buildDir The `build/` directory path.
  73. * @returns {Function}
  74. */
  75. getConversionStreamGenerator( buildDir ) {
  76. return ( pipes, format ) => {
  77. const conversionPipes = [];
  78. conversionPipes.push( utils.pickVersionedFile( format ) );
  79. if ( format != 'esnext' ) {
  80. // Convert src files.
  81. const filterSource = gulpFilter( ( file ) => {
  82. return utils.isSourceFile( file ) && utils.isJSFile( file );
  83. }, { restore: true } );
  84. const transpileSource = utils.transpile( format, utils.getBabelOptionsForSource( format ) );
  85. conversionPipes.push(
  86. filterSource,
  87. transpileSource,
  88. utils.fixCoverage(),
  89. filterSource.restore
  90. );
  91. // Convert test files.
  92. const filterTests = gulpFilter( ( file ) => {
  93. return utils.isTestFile( file ) && utils.isJSFile( file );
  94. }, { restore: true } );
  95. const transpileTests = utils.transpile( format, utils.getBabelOptionsForTests( format ) );
  96. conversionPipes.push(
  97. filterTests,
  98. transpileTests,
  99. format === 'amd' ? utils.appendBenderLauncher() : utils.noop(),
  100. filterTests.restore
  101. );
  102. }
  103. conversionPipes.push(
  104. utils.destBuild( buildDir, format ),
  105. utils.noop( ( file ) => {
  106. gutil.log( `Finished writing '${ gutil.colors.cyan( file.path ) }'` );
  107. } )
  108. );
  109. pipes.push( multipipe.apply( null, conversionPipes ) );
  110. return pipes;
  111. };
  112. },
  113. /**
  114. * Transpiles files piped into this stream to the given format (`amd` or `cjs`).
  115. *
  116. * @param {String} format
  117. * @returns {Stream}
  118. */
  119. transpile( format, options ) {
  120. return gulpBabel( options )
  121. .on( 'error', function( err ) {
  122. gutil.log( gutil.colors.red( `Error (Babel:${ format })` ) );
  123. gutil.log( gutil.colors.red( err.message ) );
  124. console.log( '\n' + err.codeFrame + '\n' );
  125. } );
  126. },
  127. /**
  128. * Adds istanbul ignore to the code created by babel.
  129. *
  130. * @returns {Stream}
  131. */
  132. fixCoverage() {
  133. return replace(
  134. 'return obj && obj.__esModule ? obj :',
  135. '/* istanbul ignore next */\n\t\t' +
  136. 'return obj && obj.__esModule ? obj :' );
  137. },
  138. /**
  139. * Returns an object with Babel options for the source code.
  140. *
  141. * @param {String} format
  142. * @returns {Object} options
  143. */
  144. getBabelOptionsForSource( format ) {
  145. return {
  146. plugins: utils.getBabelPlugins( format ),
  147. // Ensure that all paths ends with '.js' because Require.JS (unlike Common.JS/System.JS)
  148. // will not add it to module names which look like paths.
  149. resolveModuleSource: format == 'cjs' ? utils.resolveModuleSource : utils.appendModuleExtension
  150. };
  151. },
  152. /**
  153. * Returns an object with Babel options for the test code.
  154. *
  155. * @param {String} format
  156. * @returns {Object} options
  157. */
  158. getBabelOptionsForTests( format ) {
  159. return {
  160. plugins: utils.getBabelPlugins( format ),
  161. resolveModuleSource: format == 'cjs' ? utils.resolveModuleSource : utils.appendModuleExtension,
  162. moduleIds: true,
  163. moduleId: 'tests'
  164. };
  165. },
  166. /**
  167. * Returns an array of Babel plugins to use.
  168. *
  169. * @param {String} format
  170. * @returns {Array}
  171. */
  172. getBabelPlugins( format ) {
  173. const babelModuleTranspilers = {
  174. amd: 'amd',
  175. cjs: 'commonjs'
  176. };
  177. const babelModuleTranspiler = babelModuleTranspilers[ format ];
  178. if ( !babelModuleTranspiler ) {
  179. throw new Error( `Incorrect format: ${ format }` );
  180. }
  181. return [
  182. // Note: When plugin is specified by its name, Babel loads it from a context of a
  183. // currently transpiled file (in our case - e.g. from ckeditor5-core/src/foo.js).
  184. // Obviously that fails, since we have all the plugins installed only in ckeditor5/
  185. // and we want to have them only there to avoid installing them dozens of times.
  186. //
  187. // Anyway, I haven't found in the docs that you can also pass a plugin instance here,
  188. // but it works... so let's hope it will.
  189. require( `babel-plugin-transform-es2015-modules-${ babelModuleTranspiler }` ),
  190. // Istanbul doesn't support some of ES6 features we are using.
  191. require( 'babel-plugin-transform-es2015-destructuring' ),
  192. require( 'babel-plugin-transform-es2015-parameters' )
  193. ];
  194. },
  195. /**
  196. * Appends the {@link #benderLauncherCode} at the end of the file.
  197. *
  198. * @returns {Stream}
  199. */
  200. appendBenderLauncher() {
  201. return through( { objectMode: true }, ( file, encoding, callback ) => {
  202. if ( !file.isNull() ) {
  203. file.contents = new Buffer( file.contents.toString() + utils.benderLauncherCode );
  204. }
  205. callback( null, file );
  206. } );
  207. },
  208. /**
  209. * Allows us to pick one of files suffixed with the format (`__esnext`, `__amd`, or `__cjs`) and removes
  210. * files with other suffixes from the stream.
  211. *
  212. * For example: we have `load__esnext.js`, `load__amd.js` and `load__cjs.js`. After applying this
  213. * transformation when compiling code for a specific format the proper file will be renamed to `load.js`.
  214. * Files not matching a specified format will be removed.
  215. *
  216. * @param {String} format
  217. * @returns {Stream}
  218. */
  219. pickVersionedFile( format ) {
  220. const rejectedFormats = utils.SUPPORTED_FORMATS
  221. .filter( ( item ) => item !== format );
  222. const pickRegexp = new RegExp( `__${ format }$` );
  223. const rejectRegexp = new RegExp( `__(${ rejectedFormats.join( '|' ) }).js$` );
  224. const pick = rename( ( path ) => {
  225. path.basename = path.basename.replace( pickRegexp, '' );
  226. } );
  227. const remove = gulpFilter( ( file ) => !rejectRegexp.test( file.path ) );
  228. return multipipe( pick, remove );
  229. },
  230. /**
  231. * Processes paths of files inside CKEditor5 packages.
  232. *
  233. * * `ckeditor5-xxx/src/foo/bar.js` -> `ckeditor5/xxx/foo/bar.js`
  234. * * `ckeditor5-xxx/tests/foo/bar.js` -> `tests/xxx/foo/bar.js`
  235. *
  236. * @returns {Stream}
  237. */
  238. renamePackageFiles() {
  239. return rename( ( file ) => {
  240. const dirFrags = file.dirname.split( path.sep );
  241. // Validate the input for the clear conscious.
  242. if ( dirFrags[ 0 ].indexOf( 'ckeditor5-' ) !== 0 ) {
  243. throw new Error( 'Path should start with "ckeditor5-".' );
  244. }
  245. dirFrags[ 0 ] = dirFrags[ 0 ].replace( /^ckeditor5-/, '' );
  246. const firstFrag = dirFrags[ 1 ];
  247. if ( firstFrag == 'src' ) {
  248. // Remove 'src/'.
  249. dirFrags.splice( 1, 1 );
  250. // Temporary implementation of the UI lib option. See #88.
  251. if ( dirFrags[ 0 ] == 'ui-default' ) {
  252. dirFrags[ 0 ] = 'ui';
  253. }
  254. // And prepend 'ckeditor5/'.
  255. dirFrags.unshift( 'ckeditor5' );
  256. } else if ( firstFrag == 'tests' ) {
  257. // Remove 'tests/' from the package dir.
  258. dirFrags.splice( 1, 1 );
  259. // And prepend 'tests/'.
  260. dirFrags.unshift( 'tests' );
  261. } else {
  262. throw new Error( 'Path should start with "ckeditor5-*/(src|tests|theme)".' );
  263. }
  264. file.dirname = path.join.apply( null, dirFrags );
  265. } );
  266. },
  267. /**
  268. * Processes paths of files inside the main CKEditor5 package.
  269. *
  270. * * `src/foo/bar.js` -> `ckeditor5/foo/bar.js`
  271. * * `tests/foo/bar.js` -> `tests/ckeditor5/foo/bar.js`
  272. *
  273. * @returns {Stream}
  274. */
  275. renameCKEditor5Files() {
  276. return rename( ( file ) => {
  277. const dirFrags = file.dirname.split( path.sep );
  278. const firstFrag = dirFrags[ 0 ];
  279. if ( firstFrag == 'src' ) {
  280. // Replace 'src/' with 'ckeditor5/'.
  281. // src/path.js -> ckeditor5/path.js
  282. dirFrags.splice( 0, 1, 'ckeditor5' );
  283. } else if ( firstFrag == 'tests' ) {
  284. // Insert 'ckeditor5/' after 'tests/'.
  285. // tests/foo.js -> tests/ckeditor5/foo.js
  286. dirFrags.splice( 1, 0, 'ckeditor5' );
  287. } else {
  288. throw new Error( 'Path should start with "src" or "tests".' );
  289. }
  290. file.dirname = path.join.apply( null, dirFrags );
  291. } );
  292. },
  293. /**
  294. * Appends file extension to file URLs. Tries to not touch named modules.
  295. *
  296. * @param {String} source
  297. * @returns {String}
  298. */
  299. appendModuleExtension( source ) {
  300. if ( /^https?:|\.[\/\\]/.test( source ) && !/\.js$/.test( source ) ) {
  301. return source + '.js';
  302. }
  303. return source;
  304. },
  305. /**
  306. * Checks whether a file is a test file.
  307. *
  308. * @param {Vinyl} file
  309. * @returns {Boolean}
  310. */
  311. isTestFile( file ) {
  312. // TODO this should be based on bender configuration (config.tests.*.paths).
  313. if ( !file.relative.startsWith( 'tests' + path.sep ) ) {
  314. return false;
  315. }
  316. const dirFrags = file.relative.split( path.sep );
  317. return !dirFrags.some( dirFrag => {
  318. return dirFrag.startsWith( '_' ) && dirFrag != '_utils-tests';
  319. } );
  320. },
  321. /**
  322. * Checks whether a file is a source file.
  323. *
  324. * @param {Vinyl} file
  325. * @returns {Boolean}
  326. */
  327. isSourceFile( file ) {
  328. return !utils.isTestFile( file );
  329. },
  330. /**
  331. * Checks whether a file is a JS file.
  332. *
  333. * @param {Vinyl} file
  334. * @returns {Boolean}
  335. */
  336. isJSFile( file ) {
  337. return file.path.endsWith( '.js' );
  338. },
  339. /**
  340. * Finds all CKEditor5 package directories in "node_modules" folder.
  341. *
  342. * @param {String} rootDir A root directory containing "node_modules" folder.
  343. * @returns {Array} Array of ckeditor5-* package directory paths.
  344. */
  345. getPackages( rootDir ) {
  346. // Find all CKEditor5 package directories. Resolve symlinks so we watch real directories
  347. // in order to workaround https://github.com/paulmillr/chokidar/issues/419.
  348. return fs.readdirSync( path.join( rootDir, 'node_modules' ) )
  349. // Look for ckeditor5-* directories.
  350. .filter( fileName => {
  351. return fileName.indexOf( 'ckeditor5-' ) === 0;
  352. } )
  353. // Resolve symlinks and keep only directories.
  354. .map( fileName => {
  355. let filePath = path.join( rootDir, 'node_modules', fileName );
  356. let stat = fs.lstatSync( filePath );
  357. if ( stat.isSymbolicLink() ) {
  358. filePath = fs.realpathSync( filePath );
  359. stat = fs.lstatSync( filePath );
  360. }
  361. if ( stat.isDirectory() ) {
  362. return filePath;
  363. }
  364. // Filter...
  365. return false;
  366. } )
  367. // ...those out.
  368. .filter( filePath => filePath );
  369. },
  370. /**
  371. * Filters theme entry points only from a stream of SCSS files.
  372. *
  373. * @returns {Stream}
  374. */
  375. filterThemeEntryPoints() {
  376. return filter( '**/theme.scss' );
  377. },
  378. /**
  379. * Given the input stream of theme entry-point files (theme.scss), this method:
  380. * 1. Collects paths to entry-point.
  381. * 2. Builds the output CSS theme file using aggregated entry-points.
  382. * 3. Returns a stream containing built CSS theme file.
  383. *
  384. * @param {String} fileName The name of the output CSS theme file.
  385. * @returns {Stream}
  386. */
  387. compileThemes( fileName ) {
  388. const paths = [];
  389. const stream = through.obj( collectThemeEntryPoint, renderThemeFromEntryPoints );
  390. function collectThemeEntryPoint( file, enc, callback ) {
  391. paths.push( file.path );
  392. callback();
  393. }
  394. function renderThemeFromEntryPoints( callback ) {
  395. gutil.log( `Compiling '${ gutil.colors.cyan( fileName ) }' from ${ gutil.colors.cyan( paths.length ) } entry points...` );
  396. // Sort to make sure theme is the very first SASS to build. Otherwise,
  397. // packages using mixins and variables from that theme will throw errors
  398. // because such are not available at this stage of compilation.
  399. const dataToRender = paths.sort( a => -a.indexOf( 'ckeditor5-theme' ) )
  400. // Make sure windows\\style\\paths are preserved.
  401. .map( p => `@import "${ p.replace( /\\/g, '\\\\' ) }";` )
  402. .join( '\n' );
  403. try {
  404. const rendered = sass.renderSync( utils.getSassOptions( dataToRender ) );
  405. stream.push( new gutil.File( {
  406. path: fileName,
  407. contents: new Buffer( rendered.css )
  408. } ) );
  409. callback();
  410. } catch ( err ) {
  411. callback( err );
  412. }
  413. }
  414. return stream;
  415. },
  416. /**
  417. * Parses command line arguments and returns them as a user-friendly hash.
  418. *
  419. * @param {String} dataToRender
  420. * @returns {Object}
  421. */
  422. getSassOptions( dataToRender ) {
  423. return {
  424. data: dataToRender,
  425. sourceMap: true,
  426. sourceMapEmbed: true,
  427. outputStyle: 'expanded',
  428. sourceComments: true
  429. };
  430. },
  431. /**
  432. * Removes files and directories specified by `glob` starting from `rootDir`
  433. * and gently informs about deletion.
  434. *
  435. * @param {String} rootDir The path to the root directory (i.e. "dist/").
  436. * @param {String} glob Glob specifying what to clean.
  437. * @returns {Promise}
  438. */
  439. clean( rootDir, glob ) {
  440. return del( path.join( rootDir, glob ) ).then( paths => {
  441. paths.forEach( p => {
  442. gutil.log( `Deleted file '${ gutil.colors.cyan( p ) }'.` );
  443. } );
  444. } );
  445. },
  446. /**
  447. * Parses command line arguments and returns them as a user-friendly hash.
  448. *
  449. * @returns {Object} options
  450. * @returns {Array} [options.formats] Array of specified output formats ("esnext" or "amd").
  451. * @returns {Boolean} [options.watch] A flag which enables watch mode.
  452. */
  453. parseArguments() {
  454. const options = minimist( process.argv.slice( 2 ), {
  455. string: [
  456. 'formats'
  457. ],
  458. boolean: [
  459. 'watch'
  460. ],
  461. default: {
  462. formats: 'amd',
  463. watch: false
  464. }
  465. } );
  466. options.formats = options.formats.split( ',' );
  467. return options;
  468. },
  469. /**
  470. * Given a stream of .svg files it returns a stream containing JavaScript
  471. * icon sprite file.
  472. *
  473. * @returns {Stream}
  474. */
  475. compileIconSprite() {
  476. return sprite( utils.getIconSpriteOptions() );
  477. },
  478. /**
  479. * Returns svg-sprite util options to generate <symbol>-based, JavaScript
  480. * sprite file.
  481. *
  482. * @returns {Object}
  483. */
  484. getIconSpriteOptions() {
  485. return {
  486. shape: {
  487. id: {
  488. // Note: Consider unix/style/paths and windows\\style\\paths.
  489. generator: name => `ck-icon-${ name.match( /([^\/\\]*)\.svg$/ )[ 1 ] }`
  490. },
  491. },
  492. svg: {
  493. xmlDeclaration: false,
  494. doctypeDeclaration: false,
  495. },
  496. mode: {
  497. symbol: {
  498. dest: './', // Flatten symbol/ folder.
  499. inline: true,
  500. render: {
  501. js: {
  502. template: path.join( __dirname, 'iconmanagermodel.tpl' ),
  503. dest: 'iconmanagermodel.js',
  504. }
  505. }
  506. }
  507. }
  508. };
  509. },
  510. /**
  511. * Given a stream of files it returns an array of gulp-mirror streams outputting
  512. * files to `build/[formats]/theme/` directories for each of desired output formats (cjs, amd, etc.).
  513. *
  514. * @param {String} buildDir A path to /build directory.
  515. * @param {Array} formats An array of desired output formats.
  516. * @param {Function} [transformationStream] A stream used to transform files before they're saved to
  517. * desired `build/[formats]/theme` directories. Useful for transpilation.
  518. * @returns {Stream[]} An array of streams.
  519. */
  520. getThemeFormatDestStreams( buildDir, formats, transformationStream ) {
  521. return formats.map( f => {
  522. return pipe(
  523. transformationStream ? transformationStream( f ) : utils.noop(),
  524. gulp.dest( path.join( buildDir, f, 'theme' ) ),
  525. utils.noop( file => {
  526. gutil.log( `Output for ${ gutil.colors.cyan( f ) } is '${ gutil.colors.cyan( file.path ) }'.` );
  527. } )
  528. );
  529. } );
  530. },
  531. /**
  532. * Resolves CommonJS module source path.
  533. *
  534. * @param {String} source Module path passed to require() method.
  535. * @param {String} file Path to a file where require() method is called.
  536. * @returns {String} Fixed module path.
  537. */
  538. resolveModuleSource( source, file ) {
  539. // If path is relative - leave it as is.
  540. if ( !path.isAbsolute( source ) ) {
  541. return source;
  542. }
  543. // Find relative path of test file from cwd directory.
  544. let testFile = path.relative( process.cwd(), file );
  545. // Append `/` as all files uses it as root inside transpiled versions.
  546. testFile = path.join( path.sep, testFile );
  547. // Find relative path from test file to source.
  548. let relativePath = path.relative( path.dirname( testFile ), path.dirname( source ) );
  549. relativePath = path.join( relativePath, path.basename( source ) );
  550. // Convert windows path to posix.
  551. relativePath = relativePath.replace( /\\/g, '/' );
  552. return utils.appendModuleExtension( ( relativePath.startsWith( '../' ) ? '' : './' ) + relativePath );
  553. }
  554. };
  555. module.exports = utils;