• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2023 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
16import fs from 'fs';
17import { createFilter } from '@rollup/pluginutils';
18import {
19  findIfVisualFileExists,
20  findVisualFile,
21  getHasSearchedVisualFiles,
22  getHasVisual,
23  visualTransform as processVisual
24} from '../../process_visual';
25import MagicString from 'magic-string';
26import { PluginContext } from 'rollup';
27import { projectConfig } from '../../../main';
28
29const filter: any = createFilter(/(?<!\.d)\.ets$/);
30
31export function visualTransform() {
32  return {
33    name: 'visualTransform',
34    transform(code: string, id: string) {
35      if (!filter(id)) {
36        return null;
37      }
38      if (process.env.watchMode !== 'true' && 'esmodule' === projectConfig.compileMode) {
39        return null;
40      }
41      const logger = this.share.getLogger('visualTransform');
42      code = processVisual(code, id, logger);
43      const magicString = new MagicString(code);
44      return {
45        code,
46        map: magicString.generateMap({ hires: true })
47      };
48    },
49    shouldInvalidCache(this: PluginContext, options: any): boolean {
50      if (!getHasSearchedVisualFiles()) {
51        findIfVisualFileExists();
52      }
53      if (projectConfig.modulePathMap !== undefined && !getHasVisual()) {
54        return false;
55      }
56      const moduleId: string = options.id;
57      if (!filter(moduleId) || !moduleId) {
58        return false;
59      }
60      const visualId: string = findVisualFile(moduleId);
61      if (!visualId || !fs.existsSync(visualId)) {
62        if (this.cache.has(visualId)) {
63          this.cache.delete(visualId);
64        }
65        return false;
66      }
67      const stat: fs.Stats = fs.statSync(visualId);
68      const currentTimestamp: number = stat.mtime.getTime();
69      if (!this.cache.has(visualId)) {
70        this.cache.set(visualId, currentTimestamp);
71        return !(process.env.watchMode !== 'true' && 'esmodule' === projectConfig.compileMode);
72      }
73      const lastTimestamp: number = this.cache.get(visualId);
74      this.cache.set(visualId, currentTimestamp);
75      if (currentTimestamp === lastTimestamp) {
76        return false;
77      }
78      return true;
79    }
80  }
81}