1 | const path = require('path');
|
2 | const fs = require('fs');
|
3 | const _ = require('lodash');
|
4 | const CachingWriter = require('broccoli-caching-writer');
|
5 | const mkdirp = require('mkdirp');
|
6 | const svgDataFor = require('./utils/svg-data-for');
|
7 | const { filePathsOnlyFor, idGenPathFor } = require('./utils/filepath');
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 | function InlinePacker(inputNode, options = {}) {
|
21 | if (!options.outputFile) {
|
22 | throw new Error('the outputFile option is required');
|
23 | }
|
24 |
|
25 | CachingWriter.call(this, [inputNode], {
|
26 | name: 'InlinePacker',
|
27 | annotation: options.annotation,
|
28 | });
|
29 |
|
30 | this.options = _.defaults(options, {
|
31 | moduleExport: true
|
32 | });
|
33 | }
|
34 |
|
35 | InlinePacker.prototype = Object.create(CachingWriter.prototype);
|
36 | InlinePacker.prototype.constructor = InlinePacker;
|
37 |
|
38 | InlinePacker.prototype.build = function() {
|
39 | let assetsStore = this.buildAssetsStore(
|
40 | filePathsOnlyFor(this.listFiles()), this.inputPaths[0], this.options
|
41 | );
|
42 |
|
43 | this.saveAsJson(assetsStore, this.outputPath, this.options);
|
44 | };
|
45 |
|
46 | InlinePacker.prototype.buildAssetsStore = function(filePaths, inputPath, options) {
|
47 | let { stripPath, idGen, idGenOpts } = options;
|
48 |
|
49 | return _(filePaths)
|
50 | .map((filePath) => [
|
51 | idGen(idGenPathFor(filePath, inputPath, stripPath), idGenOpts),
|
52 | svgDataFor(fs.readFileSync(filePath, 'UTF-8'))
|
53 | ])
|
54 | .fromPairs()
|
55 | .value();
|
56 | };
|
57 |
|
58 | InlinePacker.prototype.saveAsJson = function(data, outputPath, options) {
|
59 | let { outputFile, moduleExport } = options;
|
60 | let outputFilePath = path.join(outputPath, outputFile);
|
61 | let jsonContent = JSON.stringify(data);
|
62 |
|
63 | if (moduleExport) {
|
64 | jsonContent = `export default ${jsonContent}`;
|
65 | }
|
66 |
|
67 | mkdirp.sync(path.dirname(outputFilePath));
|
68 | fs.writeFileSync(outputFilePath, jsonContent);
|
69 | };
|
70 |
|
71 | module.exports = InlinePacker;
|