@hadss/hmrouter-plugin 1.0.0-rc.0 → 1.0.0-rc.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/LICENSE +77 -77
  2. package/README.md +260 -37
  3. package/dist/HMRouterAnalyzer.d.ts +31 -0
  4. package/dist/HMRouterAnalyzer.js +293 -0
  5. package/dist/HMRouterHvigorPlugin.d.ts +15 -0
  6. package/dist/HMRouterHvigorPlugin.js +139 -0
  7. package/dist/HMRouterPluginConfig.d.ts +39 -0
  8. package/dist/HMRouterPluginConfig.js +73 -0
  9. package/dist/HMRouterPluginHandle.d.ts +23 -0
  10. package/dist/HMRouterPluginHandle.js +231 -0
  11. package/dist/Index.d.ts +4 -0
  12. package/dist/Index.js +124 -0
  13. package/dist/common/Constant.d.ts +27 -0
  14. package/dist/common/Constant.js +35 -0
  15. package/dist/common/Logger.d.ts +13 -0
  16. package/dist/common/Logger.js +55 -0
  17. package/dist/common/PluginModel.d.ts +50 -0
  18. package/dist/common/PluginModel.js +23 -0
  19. package/dist/constants/CommonConstants.d.ts +39 -0
  20. package/dist/constants/CommonConstants.js +46 -0
  21. package/dist/constants/ConfigConstants.d.ts +11 -0
  22. package/dist/constants/ConfigConstants.js +15 -0
  23. package/dist/constants/TaskConstants.d.ts +9 -0
  24. package/dist/constants/TaskConstants.js +13 -0
  25. package/dist/store/PluginStore.d.ts +12 -0
  26. package/dist/store/PluginStore.js +19 -0
  27. package/dist/utils/ConfusionUtil.d.ts +4 -0
  28. package/dist/utils/ConfusionUtil.js +27 -0
  29. package/dist/utils/FileUtil.d.ts +11 -0
  30. package/dist/utils/FileUtil.js +20 -0
  31. package/dist/utils/ObfuscationUtil.d.ts +4 -0
  32. package/dist/utils/ObfuscationUtil.js +34 -0
  33. package/dist/utils/StringUtil.d.ts +3 -0
  34. package/dist/utils/StringUtil.js +18 -0
  35. package/dist/utils/TsAstUtil.d.ts +9 -0
  36. package/dist/utils/TsAstUtil.js +89 -0
  37. package/package.json +46 -27
  38. package/viewBuilder.ejs +103 -0
  39. package/lib/HMRouterAnalyzer.js +0 -223
  40. package/lib/HMRouterHvigorPlugin.js +0 -175
  41. package/lib/HMRouterPluginConfig.js +0 -31
  42. package/lib/Index.js +0 -201
  43. package/lib/PluginModel.js +0 -33
  44. package/src/HMRouterAnalyzer.ts +0 -253
  45. package/src/HMRouterHvigorPlugin.ts +0 -246
  46. package/src/HMRouterPluginConfig.ts +0 -44
  47. package/src/Index.ts +0 -218
  48. package/src/PluginModel.ts +0 -50
  49. package/tsconfig.json +0 -14
  50. package/viewBuilder.tpl +0 -97
@@ -1,223 +0,0 @@
1
- "use strict";
2
- /*
3
- * Copyright (c) 2024 Huawei Device Co., Ltd.
4
- * Licensed under the Apache License, Version 2.0 (the "License");
5
- * you may not use this file except in compliance with the License.
6
- * You may obtain a copy of the License at
7
- *
8
- * http://www.apache.org/licenses/LICENSE-2.0
9
- *
10
- * Unless required by applicable law or agreed to in writing, software
11
- * distributed under the License is distributed on an "AS IS" BASIS,
12
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- * See the License for the specific language governing permissions and
14
- * limitations under the License.
15
- */
16
- var __importDefault = (this && this.__importDefault) || function (mod) {
17
- return (mod && mod.__esModule) ? mod : { "default": mod };
18
- };
19
- Object.defineProperty(exports, "__esModule", { value: true });
20
- exports.Analyzer = void 0;
21
- const typescript_1 = __importDefault(require("typescript"));
22
- const fs_1 = __importDefault(require("fs"));
23
- const PluginModel_1 = require("./PluginModel");
24
- const hvigor_1 = require("@ohos/hvigor");
25
- const Index_1 = require("./Index");
26
- class NodeInfo {
27
- }
28
- const Logger = hvigor_1.HvigorLogger.getLogger();
29
- class Analyzer {
30
- constructor(sourcePath, pluginConfig) {
31
- this.customAnnotationExisted = false;
32
- this.analyzeResultMap = new Map();
33
- this.analyzeResult = {};
34
- this.keywordPos = 0;
35
- this.sourcePath = sourcePath;
36
- this.pluginConfig = pluginConfig;
37
- }
38
- start() {
39
- const sourceCode = fs_1.default.readFileSync(this.sourcePath, 'utf-8');
40
- const sourceFile = typescript_1.default.createSourceFile(this.sourcePath, sourceCode, typescript_1.default.ScriptTarget.ES2021, false);
41
- typescript_1.default.forEachChild(sourceFile, node => {
42
- this.resolveNode(node);
43
- // 解析完成后赋值存进Map
44
- switch (this.analyzeResult.annotation) {
45
- case 'HMRouter':
46
- this.analyzeResultMap.set(this.analyzeResult.pageUrl, this.analyzeResult);
47
- break;
48
- case 'HMAnimator':
49
- this.analyzeResultMap.set(this.analyzeResult.animatorName, this.analyzeResult);
50
- break;
51
- case 'HMInterceptor':
52
- this.analyzeResultMap.set(this.analyzeResult.interceptorName, this.analyzeResult);
53
- break;
54
- case 'HMLifecycle':
55
- this.analyzeResultMap.set(this.analyzeResult.lifecycleName, this.analyzeResult);
56
- break;
57
- }
58
- });
59
- }
60
- resolveNode(node) {
61
- if (typescript_1.default.isMissingDeclaration(node)) {
62
- this.resolveMissingDeclaration(node);
63
- }
64
- else if (typescript_1.default.isClassDeclaration(node)) {
65
- this.resolveClass(node);
66
- }
67
- else if (typescript_1.default.isDecorator(node)) {
68
- this.resolveDecorator(node);
69
- }
70
- else if (typescript_1.default.isCallExpression(node)) {
71
- this.resolveCallExpression(node);
72
- }
73
- else if (typescript_1.default.isExpressionStatement(node)) {
74
- this.resolveExpression(node);
75
- }
76
- else if (typescript_1.default.isBlock(node)) {
77
- this.resolveBlock(node);
78
- }
79
- else if (typescript_1.default.isPropertyAssignment(node)) {
80
- return this.resolvePropertyAccess(node);
81
- }
82
- else if (typescript_1.default.isIdentifier(node)) {
83
- return this.resolveIdentifier(node);
84
- }
85
- else if (typescript_1.default.isStringLiteral(node)) {
86
- return this.resolveStringLiteral(node);
87
- }
88
- else if (node.kind === typescript_1.default.SyntaxKind.TrueKeyword) {
89
- let info = new NodeInfo();
90
- info.value = true;
91
- return info;
92
- }
93
- else if (node.kind === typescript_1.default.SyntaxKind.FalseKeyword) {
94
- let info = new NodeInfo();
95
- info.value = false;
96
- return info;
97
- }
98
- else if (typescript_1.default.isNumericLiteral(node)) {
99
- return this.resolveNumericLiteral(node);
100
- }
101
- else if (typescript_1.default.isArrayLiteralExpression(node)) {
102
- let interceptors = this.resolveArrayLiteral(node);
103
- let info = new NodeInfo();
104
- info.value = interceptors;
105
- return info;
106
- }
107
- }
108
- resolveMissingDeclaration(node) {
109
- this.analyzeResult = {};
110
- node.forEachChild(child => this.resolveNode(child));
111
- }
112
- resolveClass(node) {
113
- // 解析到类声明,先清空一次返回结果
114
- this.analyzeResult = {};
115
- node.modifiers?.forEach(modifier => {
116
- // 遍历分析装饰器
117
- this.resolveNode(modifier);
118
- });
119
- if (this.customAnnotationExisted) {
120
- this.analyzeResult.name = node.name?.text;
121
- }
122
- }
123
- resolveDecorator(node) {
124
- if (typescript_1.default.isCallExpression(node.expression)) {
125
- const callExpression = node.expression;
126
- if (typescript_1.default.isIdentifier(callExpression.expression)) {
127
- this.switchIdentifier(callExpression);
128
- }
129
- }
130
- }
131
- switchIdentifier(callExpression) {
132
- const identifier = callExpression.expression;
133
- if (this.pluginConfig.annotation.some(item => item === identifier.text)) {
134
- this.customAnnotationExisted = true;
135
- // 区分是什么装饰器,构造不同的返回类
136
- switch (identifier.text) {
137
- case 'HMRouter':
138
- this.analyzeResult = new PluginModel_1.HMRouterResult();
139
- this.analyzeResult.annotation = 'HMRouter';
140
- break;
141
- case 'HMAnimator':
142
- this.analyzeResult = new PluginModel_1.HMAnimatorResult();
143
- this.analyzeResult.annotation = 'HMAnimator';
144
- break;
145
- case 'HMInterceptor':
146
- this.analyzeResult = new PluginModel_1.HMInterceptorResult();
147
- this.analyzeResult.annotation = 'HMInterceptor';
148
- break;
149
- case 'HMLifecycle':
150
- this.analyzeResult = new PluginModel_1.HMLifecycleResult();
151
- this.analyzeResult.annotation = 'HMLifecycle';
152
- break;
153
- }
154
- if (callExpression.arguments.length > 0) {
155
- this.resolveCallExpression(callExpression);
156
- }
157
- }
158
- }
159
- resolveCallExpression(node) {
160
- let identifier = this.resolveNode(node.expression);
161
- this.parseAnnotation(node.arguments, identifier);
162
- }
163
- resolveExpression(node) {
164
- let identifier = this.resolveNode(node.expression);
165
- if (identifier?.value === 'struct') {
166
- this.keywordPos = node.end;
167
- }
168
- if (this.analyzeResult.annotation === 'HMRouter' && this.keywordPos === node.pos) {
169
- this.analyzeResult.name = identifier?.value;
170
- }
171
- }
172
- resolveBlock(node) {
173
- node.statements.forEach(statement => {
174
- this.resolveNode(statement);
175
- });
176
- }
177
- parseAnnotation(args, nodeInfo) {
178
- if (this.pluginConfig.annotation.some(item => nodeInfo?.value === item)) {
179
- args
180
- .flatMap((e) => e.properties)
181
- .forEach((e) => {
182
- this.parseConfig(e, this.analyzeResult);
183
- });
184
- }
185
- }
186
- parseConfig(node, result) {
187
- let info = this.resolveNode(node);
188
- Reflect.set(result, info?.value['key'], info?.value['value']);
189
- }
190
- resolveArrayLiteral(node) {
191
- return node.elements.map(e => this.resolveNode(e)?.value);
192
- }
193
- resolvePropertyAccess(node) {
194
- let propertyName = this.resolveNode(node.name)?.value;
195
- let propertyValue = this.resolveNode(node.initializer)?.value;
196
- let info = new NodeInfo();
197
- info.value = { key: propertyName, value: propertyValue };
198
- return info;
199
- }
200
- resolveNumericLiteral(node) {
201
- let info = new NodeInfo();
202
- info.value = Number(node.text);
203
- return info;
204
- }
205
- resolveStringLiteral(node) {
206
- let info = new NodeInfo();
207
- info.value = node.text;
208
- return info;
209
- }
210
- resolveIdentifier(node) {
211
- if (node.escapedText === 'NavDestination' && this.analyzeResult.annotation === 'HMRouter') {
212
- Logger.error('errorCode: 40000003, errorMsg: @HMRouter 修饰的组件不能包含 NavDestination in' +
213
- this.analyzeResult.name);
214
- (0, Index_1.deleteGeneratorFile)(this.pluginConfig);
215
- throw new Error('NavDestination is not allowed in HMRouter' + this.sourcePath);
216
- }
217
- let info = new NodeInfo();
218
- info.value = node.escapedText.toString();
219
- return info;
220
- }
221
- }
222
- exports.Analyzer = Analyzer;
223
- //# sourceMappingURL=HMRouterAnalyzer.js.map
@@ -1,175 +0,0 @@
1
- "use strict";
2
- /*
3
- * Copyright (c) 2024 Huawei Device Co., Ltd.
4
- * Licensed under the Apache License, Version 2.0 (the "License");
5
- * you may not use this file except in compliance with the License.
6
- * You may obtain a copy of the License at
7
- *
8
- * http://www.apache.org/licenses/LICENSE-2.0
9
- *
10
- * Unless required by applicable law or agreed to in writing, software
11
- * distributed under the License is distributed on an "AS IS" BASIS,
12
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- * See the License for the specific language governing permissions and
14
- * limitations under the License.
15
- */
16
- var __importDefault = (this && this.__importDefault) || function (mod) {
17
- return (mod && mod.__esModule) ? mod : { "default": mod };
18
- };
19
- Object.defineProperty(exports, "__esModule", { value: true });
20
- exports.HMRouterHvigorPlugin = exports.RouterInfo = void 0;
21
- const hvigor_1 = require("@ohos/hvigor");
22
- const path_1 = __importDefault(require("path"));
23
- const fs_1 = __importDefault(require("fs"));
24
- const HMRouterAnalyzer_1 = require("./HMRouterAnalyzer");
25
- const handlebars_1 = __importDefault(require("handlebars"));
26
- const Index_1 = require("./Index");
27
- const Logger = hvigor_1.HvigorLogger.getLogger();
28
- class RouterInfo {
29
- constructor(name, pageSourceFile, buildFunction, data = {}) {
30
- this.name = name;
31
- this.pageSourceFile = pageSourceFile;
32
- this.buildFunction = buildFunction;
33
- this.data = data;
34
- }
35
- }
36
- exports.RouterInfo = RouterInfo;
37
- class HMRouterHvigorPlugin {
38
- constructor(config) {
39
- this.routerMap = [];
40
- this.scanFiles = [];
41
- this.HMRouterNum = 0;
42
- this.config = config;
43
- }
44
- analyzeAnnotation() {
45
- const templateModel = {
46
- pageUrl: '',
47
- importPath: '',
48
- componentName: '',
49
- dialog: false,
50
- generatorViewName: ''
51
- };
52
- this.config.scanDir.forEach(scanDir => {
53
- const scanPath = `${this.config.modulePath}/${scanDir}`;
54
- this.deepScan(scanPath, '');
55
- });
56
- Logger.info(`扫描到${this.scanFiles.length}个文件`, this.scanFiles);
57
- this.scanFiles.forEach(filePath => {
58
- if (filePath.endsWith('.ets')) {
59
- const importPath = path_1.default
60
- .relative(`${this.config.modulePath}/${this.config.builderDir}`, filePath)
61
- .replaceAll('\\', '/')
62
- .replaceAll('.ets', '');
63
- const analyzer = new HMRouterAnalyzer_1.Analyzer(filePath, this.config);
64
- analyzer.start();
65
- for (let [key, value] of analyzer.analyzeResultMap) {
66
- value.module = this.config.moduleName;
67
- let pageSourceFile = path_1.default.relative(this.config.modulePath, filePath).replaceAll('\\', '/');
68
- this.pushRouterInfo(value, pageSourceFile, importPath, templateModel);
69
- }
70
- this.HMRouterNum = 0;
71
- }
72
- });
73
- }
74
- stringToHashCode(str) {
75
- let hash = 0;
76
- if (str.length === 0)
77
- return hash;
78
- for (let i = 0; i < str.length; i++) {
79
- const char = str.charCodeAt(i);
80
- hash = (hash << 5) - hash + char;
81
- hash |= 0; // 转换为32位整数
82
- }
83
- return hash;
84
- }
85
- pushHMRouter(value, importPath, templateModel) {
86
- let analyzeResult = value;
87
- templateModel.pageUrl = analyzeResult.pageUrl;
88
- templateModel.importPath = importPath;
89
- templateModel.componentName = analyzeResult.name;
90
- templateModel.dialog = !!analyzeResult.dialog;
91
- templateModel.generatorViewName = 'HM' + analyzeResult.name + this.stringToHashCode(analyzeResult.pageUrl);
92
- this.routerMap.push(new RouterInfo(analyzeResult.pageUrl, `${this.config.builderDir}/${templateModel.generatorViewName}.ets`, `${templateModel.componentName}Builder`, value));
93
- this.generateBuilder(templateModel);
94
- }
95
- pushRouterInfo(value, pageSourceFile, importPath, templateModel) {
96
- switch (value.annotation) {
97
- case 'HMRouter':
98
- this.HMRouterNum++;
99
- if (this.HMRouterNum > 1) {
100
- Logger.error(`errorCode: 40000004, errorMsg: 文件${pageSourceFile}中存在多个HMRouter注解`);
101
- (0, Index_1.deleteGeneratorFile)(this.config);
102
- throw new Error(`文件${pageSourceFile}中存在多个HMRouter注解`);
103
- }
104
- this.pushHMRouter(value, importPath, templateModel);
105
- break;
106
- case 'HMAnimator':
107
- this.routerMap.push(new RouterInfo(`__animator__${value.animatorName}`, pageSourceFile, '', value));
108
- break;
109
- case 'HMInterceptor':
110
- this.routerMap.push(new RouterInfo(`__interceptor__${value.interceptorName}`, pageSourceFile, '', value));
111
- break;
112
- case 'HMLifecycle':
113
- this.routerMap.push(new RouterInfo(`__lifecycle__${value.lifecycleName}`, pageSourceFile, '', value));
114
- break;
115
- }
116
- }
117
- generateBuilder(templateModel) {
118
- const builderPath = path_1.default.resolve(__dirname, '../' + this.config.builderTpl);
119
- const tpl = fs_1.default.readFileSync(builderPath, { encoding: 'utf-8' });
120
- const template = handlebars_1.default.compile(tpl);
121
- const output = template(templateModel);
122
- const routerBuilderDir = `${this.config.modulePath}/${this.config.builderDir}`;
123
- if (!fs_1.default.existsSync(routerBuilderDir)) {
124
- fs_1.default.mkdirSync(routerBuilderDir);
125
- }
126
- fs_1.default.writeFileSync(`${routerBuilderDir}/${templateModel.generatorViewName}.ets`, output, {
127
- encoding: 'utf-8'
128
- });
129
- Logger.info(`Builder ${templateModel.generatorViewName}.ets has been generated in ${routerBuilderDir}`);
130
- }
131
- generateRouterMap() {
132
- let set = new Set();
133
- this.routerMap.forEach(item => {
134
- if (set.has(item.name)) {
135
- Logger.error(`errorCode: 40000001, errorMsg: 重复的pageUrl、拦截器、生命周期、动画--${item.name}`);
136
- (0, Index_1.deleteGeneratorFile)(this.config);
137
- throw new Error(`路由${item.name}重复`);
138
- }
139
- else {
140
- set.add(item.name);
141
- }
142
- });
143
- let routerMap = {
144
- routerMap: this.routerMap.map(item => {
145
- if (item.data && item.data.annotation) {
146
- delete item.data.annotation;
147
- // @ts-ignore
148
- item.data = { data: JSON.stringify(item.data) };
149
- }
150
- return item;
151
- })
152
- };
153
- const jsonOutput = JSON.stringify(routerMap, null, 2);
154
- const routerMapDir = `${this.config.modulePath}/${this.config.routerMapDir}`;
155
- if (!fs_1.default.existsSync(routerMapDir)) {
156
- fs_1.default.mkdirSync(routerMapDir, { recursive: true });
157
- }
158
- fs_1.default.writeFileSync(`${routerMapDir}/hm_router_map.json`, jsonOutput, { encoding: 'utf-8' });
159
- Logger.info(`hm_router_map.json has been generated in ${routerMapDir}`);
160
- return this.routerMap;
161
- }
162
- deepScan(scanPath, filePath) {
163
- if (fs_1.default.lstatSync(`${scanPath + filePath}`).isDirectory()) {
164
- const files = fs_1.default.readdirSync(`${scanPath}${filePath}`);
165
- files.forEach(file => {
166
- this.deepScan(`${scanPath}${filePath}/`, file);
167
- });
168
- }
169
- else {
170
- this.scanFiles.push(`${scanPath}${filePath}`);
171
- }
172
- }
173
- }
174
- exports.HMRouterHvigorPlugin = HMRouterHvigorPlugin;
175
- //# sourceMappingURL=HMRouterHvigorPlugin.js.map
@@ -1,31 +0,0 @@
1
- "use strict";
2
- /*
3
- * Copyright (c) 2024 Huawei Device Co., Ltd.
4
- * Licensed under the Apache License, Version 2.0 (the "License");
5
- * you may not use this file except in compliance with the License.
6
- * You may obtain a copy of the License at
7
- *
8
- * http://www.apache.org/licenses/LICENSE-2.0
9
- *
10
- * Unless required by applicable law or agreed to in writing, software
11
- * distributed under the License is distributed on an "AS IS" BASIS,
12
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- * See the License for the specific language governing permissions and
14
- * limitations under the License.
15
- */
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.HMRouterPluginConfig = void 0;
18
- class HMRouterPluginConfig {
19
- constructor(moduleName, modulePath, param) {
20
- this.moduleName = moduleName;
21
- this.modulePath = modulePath;
22
- this.scanDir = param.scanDir ? param.scanDir : ['src/main/ets'];
23
- this.routerMapDir = param.routerMapDir ? param.routerMapDir : 'src/main/resources/base/profile';
24
- this.builderDir = param.builderDir ? param.builderDir : 'src/main/ets/generated';
25
- this.annotation = ['HMRouter', 'HMAnimator', 'HMInterceptor', 'HMLifecycle'];
26
- this.builderTpl = param.builderTpl ? param.builderTpl : 'viewBuilder.tpl';
27
- this.saveGeneratedFile = !!param.saveGeneratedFile;
28
- }
29
- }
30
- exports.HMRouterPluginConfig = HMRouterPluginConfig;
31
- //# sourceMappingURL=HMRouterPluginConfig.js.map
package/lib/Index.js DELETED
@@ -1,201 +0,0 @@
1
- "use strict";
2
- /*
3
- * Copyright (c) 2024 Huawei Device Co., Ltd.
4
- * Licensed under the Apache License, Version 2.0 (the "License");
5
- * you may not use this file except in compliance with the License.
6
- * You may obtain a copy of the License at
7
- *
8
- * http://www.apache.org/licenses/LICENSE-2.0
9
- *
10
- * Unless required by applicable law or agreed to in writing, software
11
- * distributed under the License is distributed on an "AS IS" BASIS,
12
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- * See the License for the specific language governing permissions and
14
- * limitations under the License.
15
- */
16
- var __importDefault = (this && this.__importDefault) || function (mod) {
17
- return (mod && mod.__esModule) ? mod : { "default": mod };
18
- };
19
- Object.defineProperty(exports, "__esModule", { value: true });
20
- exports.deleteGeneratorFile = exports.harPlugin = exports.hspPlugin = exports.hapPlugin = void 0;
21
- const hvigor_1 = require("@ohos/hvigor");
22
- const hvigor_ohos_plugin_1 = require("@ohos/hvigor-ohos-plugin");
23
- const fs_1 = __importDefault(require("fs"));
24
- const path_1 = __importDefault(require("path"));
25
- const HMRouterPluginConfig_1 = require("./HMRouterPluginConfig");
26
- const HMRouterHvigorPlugin_1 = require("./HMRouterHvigorPlugin");
27
- const HAP_PLUGIN_ID = 'HAP_HMROUTER_PLUGIN';
28
- const HSP_PLUGIN_ID = 'HSP_HMROUTER_PLUGIN';
29
- const HAR_PLUGIN_ID = 'HAR_HMROUTER_PLUGIN';
30
- const Logger = hvigor_1.HvigorLogger.getLogger();
31
- let modulePathArr = [];
32
- function readConfig(node) {
33
- let configParam = {};
34
- let configFilePath = path_1.default.resolve(node.getNodePath(), './hmrouter_config.json');
35
- if (fs_1.default.existsSync(configFilePath)) {
36
- configParam = JSON.parse(fs_1.default.readFileSync(configFilePath, 'utf-8'));
37
- }
38
- else {
39
- configFilePath = path_1.default.resolve(node.getNodePath(), '../hmrouter_config.json');
40
- if (fs_1.default.existsSync(configFilePath)) {
41
- configParam = JSON.parse(fs_1.default.readFileSync(configFilePath, 'utf-8'));
42
- }
43
- else {
44
- configFilePath = path_1.default.resolve(node.getNodePath(), '../../hmrouter_config.json');
45
- if (fs_1.default.existsSync(configFilePath)) {
46
- configParam = JSON.parse(fs_1.default.readFileSync(configFilePath, 'utf-8'));
47
- }
48
- else {
49
- configParam = {};
50
- }
51
- }
52
- }
53
- return new HMRouterPluginConfig_1.HMRouterPluginConfig(node.getNodeName(), node.getNodePath(), configParam);
54
- }
55
- function hapPlugin() {
56
- return {
57
- pluginId: HAP_PLUGIN_ID,
58
- apply(node) {
59
- HMRouterPlugin(node, hvigor_ohos_plugin_1.OhosPluginId.OHOS_HAP_PLUGIN);
60
- }
61
- };
62
- }
63
- exports.hapPlugin = hapPlugin;
64
- function hspPlugin() {
65
- return {
66
- pluginId: HSP_PLUGIN_ID,
67
- apply(node) {
68
- HMRouterPlugin(node, hvigor_ohos_plugin_1.OhosPluginId.OHOS_HSP_PLUGIN);
69
- }
70
- };
71
- }
72
- exports.hspPlugin = hspPlugin;
73
- function harPlugin() {
74
- return {
75
- pluginId: HAR_PLUGIN_ID,
76
- apply(node) {
77
- HMRouterPlugin(node, hvigor_ohos_plugin_1.OhosPluginId.OHOS_HAR_PLUGIN);
78
- }
79
- };
80
- }
81
- exports.harPlugin = harPlugin;
82
- function HMRouterPluginTask(context, conf, node) {
83
- let startTime = Date.now();
84
- Logger.log(node.getNodeName() + ' :HMRouterPluginTask start---' + startTime);
85
- modulePathArr.push(node.getNodePath());
86
- const plugin = new HMRouterHvigorPlugin_1.HMRouterHvigorPlugin(conf);
87
- plugin.analyzeAnnotation();
88
- const buildProfileOpt = context.getBuildProfileOpt();
89
- const moduleJsonOpt = context.getModuleJsonOpt();
90
- if (moduleJsonOpt.module.routerMap) {
91
- let routerMapFileName = moduleJsonOpt.module.routerMap.split(':')[1];
92
- let jsonObj = fs_1.default.readFileSync(node.getNodePath().replace(/\\/g, '/') +
93
- `/src/main/resources/base/profile/${routerMapFileName}.json`, 'utf-8');
94
- plugin.routerMap.unshift(...JSON.parse(jsonObj)['routerMap']);
95
- }
96
- let routerMap = plugin.generateRouterMap();
97
- if (!buildProfileOpt.buildOption?.arkOptions) {
98
- buildProfileOpt.buildOption.arkOptions = {
99
- runtimeOnly: {
100
- sources: []
101
- },
102
- buildProfileFields: {
103
- HMRouterHash: Date.now()
104
- }
105
- };
106
- pushRouterInfo(buildProfileOpt, routerMap);
107
- }
108
- else {
109
- if (!buildProfileOpt.buildOption.arkOptions.runtimeOnly) {
110
- buildProfileOpt.buildOption.arkOptions.runtimeOnly = {
111
- sources: []
112
- };
113
- pushRouterInfo(buildProfileOpt, routerMap);
114
- }
115
- else {
116
- if (!buildProfileOpt.buildOption.arkOptions.runtimeOnly.sources) {
117
- buildProfileOpt.buildOption.arkOptions.runtimeOnly.sources = [];
118
- pushRouterInfo(buildProfileOpt, routerMap);
119
- }
120
- else {
121
- pushRouterInfo(buildProfileOpt, routerMap);
122
- }
123
- }
124
- if (!buildProfileOpt.buildOption.arkOptions.buildProfileFields) {
125
- buildProfileOpt.buildOption.arkOptions.buildProfileFields = {
126
- HMRouterHash: Date.now()
127
- };
128
- }
129
- else {
130
- // @ts-ignore
131
- buildProfileOpt.buildOption.arkOptions.buildProfileFields.HMRouterHash = Date.now();
132
- }
133
- }
134
- moduleJsonOpt.module.routerMap = `$profile:hm_router_map`;
135
- context.setModuleJsonOpt(moduleJsonOpt);
136
- context.setBuildProfileOpt(buildProfileOpt);
137
- Logger.log(hvigor_1.levels.DEBUG, JSON.stringify(context.getBuildProfileOpt()));
138
- let endTime = Date.now();
139
- Logger.log(node.getNodeName() + ' :HMRouterPluginTask end---' + endTime);
140
- Logger.log(node.getNodeName() + ' :HMRouterPluginTask cost---' + (endTime - startTime) + 'ms');
141
- }
142
- function pushRouterInfo(buildProfileOpt, routerMap) {
143
- routerMap.forEach((item) => {
144
- if (item.name.includes('_')) {
145
- buildProfileOpt.buildOption.arkOptions.runtimeOnly.sources.push('./' + item.pageSourceFile);
146
- }
147
- });
148
- }
149
- function deleteGeneratorFile(conf) {
150
- if (conf.saveGeneratedFile) {
151
- Logger.info('saveGeneratedFile is true, do not delete file');
152
- return;
153
- }
154
- Logger.info('deleteGeneratorFile exec...', modulePathArr);
155
- for (let modulePath of modulePathArr) {
156
- if (fs_1.default.existsSync(modulePath + '/' + conf.routerMapDir + '/hm_router_map.json')) {
157
- fs_1.default.unlinkSync(modulePath + '/' + conf.routerMapDir + '/hm_router_map.json');
158
- Logger.log(modulePath + 'delete hm_router_map.json');
159
- }
160
- if (fs_1.default.existsSync(modulePath + '/' + conf.builderDir)) {
161
- fs_1.default.rmSync(modulePath + '/' + conf.builderDir, {
162
- recursive: true
163
- });
164
- Logger.log(modulePath + 'delete builder dir');
165
- }
166
- }
167
- modulePathArr = [];
168
- }
169
- exports.deleteGeneratorFile = deleteGeneratorFile;
170
- function HMRouterPlugin(node, pluginId) {
171
- Logger.info(`Exec ${pluginId}..., node:${node.getNodeName()}, nodePath:${node.getNodePath()}`);
172
- hvigor_1.hvigor.nodesEvaluated(async () => {
173
- let conf = readConfig(node);
174
- if (pluginId === hvigor_ohos_plugin_1.OhosPluginId.OHOS_HAP_PLUGIN) {
175
- let packageJson = await hvigor_1.Json5Reader.readJson5File(path_1.default.resolve(node.getNodePath(), './oh-package.json5'), 'utf-8');
176
- conf.moduleName = packageJson.name;
177
- }
178
- const context = node.getContext(pluginId);
179
- if (!context) {
180
- Logger.error(`errorCode: 40000005, errorMsg: context is null 请检查插件的hvigorfile配置`);
181
- deleteGeneratorFile(conf);
182
- throw new Error('hspContext is null');
183
- }
184
- context.targets((target) => {
185
- const targetName = target.getTargetName();
186
- node.registerTask({
187
- name: `${targetName}@HMRouterPLuginTask`,
188
- run: () => {
189
- HMRouterPluginTask(context, conf, node);
190
- let taskName = 'Package' + pluginId.split('.')[2].charAt(0).toUpperCase() + pluginId.split('.')[2].slice(1);
191
- node.getTaskByName(`${targetName}@${taskName}`)?.afterRun(() => {
192
- deleteGeneratorFile(conf);
193
- });
194
- },
195
- dependencies: [`${targetName}@PreBuild`],
196
- postDependencies: [`${targetName}@MergeProfile`]
197
- });
198
- });
199
- });
200
- }
201
- //# sourceMappingURL=Index.js.map
@@ -1,33 +0,0 @@
1
- "use strict";
2
- /*
3
- * Copyright (c) 2024 Huawei Device Co., Ltd.
4
- * Licensed under the Apache License, Version 2.0 (the "License");
5
- * you may not use this file except in compliance with the License.
6
- * You may obtain a copy of the License at
7
- *
8
- * http://www.apache.org/licenses/LICENSE-2.0
9
- *
10
- * Unless required by applicable law or agreed to in writing, software
11
- * distributed under the License is distributed on an "AS IS" BASIS,
12
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- * See the License for the specific language governing permissions and
14
- * limitations under the License.
15
- */
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.HMLifecycleResult = exports.HMInterceptorResult = exports.HMAnimatorResult = exports.HMRouterResult = exports.BaseAnalyzeResult = void 0;
18
- class BaseAnalyzeResult {
19
- }
20
- exports.BaseAnalyzeResult = BaseAnalyzeResult;
21
- class HMRouterResult extends BaseAnalyzeResult {
22
- }
23
- exports.HMRouterResult = HMRouterResult;
24
- class HMAnimatorResult extends BaseAnalyzeResult {
25
- }
26
- exports.HMAnimatorResult = HMAnimatorResult;
27
- class HMInterceptorResult extends BaseAnalyzeResult {
28
- }
29
- exports.HMInterceptorResult = HMInterceptorResult;
30
- class HMLifecycleResult extends BaseAnalyzeResult {
31
- }
32
- exports.HMLifecycleResult = HMLifecycleResult;
33
- //# sourceMappingURL=PluginModel.js.map