1/*
2 * Copyright (c) 2024 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 ts from 'typescript';
17
18import {
19  USE_SHARED,
20  USE_SHARED_COMMENT
21} from './common/ark_define';
22import {
23  GeneratedFileInHar,
24  harFilesRecord,
25  toUnixPath
26} from '../../utils';
27import {
28  projectConfig
29} from '../../../main';
30
31export const sharedModuleSet: Set<string> = new Set();
32
33export function collectSharedModule(source: string, filePath: string, sourceFile: ts.SourceFile | null): void {
34  if (!sourceFile) {
35    sourceFile = ts.createSourceFile(filePath, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.ETS);
36  }
37
38  // "use shared" will only be effective when used after imports, before other statements
39  for (const statement of sourceFile.statements) {
40    if (ts.isImportDeclaration(statement)) {
41      continue;
42    }
43    if (ts.isExpressionStatement(statement) && ts.isStringLiteral(statement.expression) &&
44      statement.expression.text === USE_SHARED) {
45      sharedModuleSet.add(toUnixPath(filePath));
46      processDeclarationFile(filePath);
47    }
48    return;
49  }
50}
51
52// For hsp and close-source har, we need add comment '// use shared' for shared modules to inform developers.
53function processDeclarationFile(filePath: string): void {
54  if (!projectConfig.compileHar && !projectConfig.compileShared) {
55    return;
56  }
57
58  const generatedDetsFilesInHar: GeneratedFileInHar = harFilesRecord.get(toUnixPath(filePath));
59  if (generatedDetsFilesInHar) {
60    generatedDetsFilesInHar.originalDeclarationContent = USE_SHARED_COMMENT + '\n' +
61      generatedDetsFilesInHar.originalDeclarationContent;
62  }
63}
64
65export function cleanSharedModuleSet(): void {
66  sharedModuleSet.clear();
67}
68