• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2021 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16const _require = require('child_process');
17const exec = _require.exec;
18const _path = require('path');
19const snapshot = _path.join(__dirname, '..', '..', 'bin', 'jerry-snapshot');
20const registerRequireContextHook = require('babel-plugin-require-context-hook/register');
21registerRequireContextHook();
22/**
23 * Convert Javascript file to snapshot.
24 */
25class SnapshotPlugin {
26  /**
27   * constructor of the SnapshotPlugin class.
28   * @param {String} options The object of build folder.
29   */
30  constructor(options) {
31    this.options = options;
32  }
33  /**
34   * Find all javascript file paths in the directory.
35   * @param {Object} assets the object of javascript file path.
36   * @param {String} buildPath The path of build folder.
37   * @return {Array} Image path array.
38   */
39  getDir(assets, buildPath) {
40    const pathArray = [];
41    Object.keys(assets).map((item) => {
42      if (/.js$/.test(item)) {
43        pathArray.push(_path.join(buildPath, item));
44      }
45    });
46    return pathArray;
47  };
48  /**
49   * Convert javascript file asynchronously. If an error occurs, print an error message.
50   * @param {Object} compiler API specification, all configuration information of Webpack environment.
51   */
52  apply(compiler) {
53    const buildPath = this.options.build;
54    compiler.hooks.done.tap('snapshot coverter', (stats) => {
55      const pathArray = this.getDir(stats.compilation.assets, buildPath);
56      pathArray.forEach((element) => {
57        const bcPath = element.replace('.js', '.bc');
58        const fileName = _path.basename(element);
59        exec(`"${snapshot}" generate -o "${bcPath}" "${element}"`, (error) => {
60          if (error) {
61            console.error('\u001b[31m', `Failed to convert the ${fileName} file to a snapshot.`, '\u001b[39m');
62          }
63        });
64      });
65    });
66  }
67}
68module.exports = SnapshotPlugin;
69