@tarojs/plugin-platform-harmony-cpp 4.1.0 → 4.1.1-alpha.1

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 (225) hide show
  1. package/README.md +0 -7
  2. package/dist/index.js +1236 -0
  3. package/dist/runtime/apis/apis.ts +20 -0
  4. package/dist/runtime/apis/base/crypto.ts +4 -0
  5. package/dist/runtime/apis/base/debug.ts +5 -0
  6. package/dist/runtime/apis/base/index.ts +13 -0
  7. package/dist/runtime/apis/base/performance.ts +8 -0
  8. package/dist/runtime/apis/base/system.ts +181 -0
  9. package/dist/runtime/apis/base/update.ts +5 -0
  10. package/dist/runtime/apis/base/weapp/app-event.ts +75 -0
  11. package/dist/runtime/apis/base/weapp/life-cycle.ts +21 -0
  12. package/dist/runtime/apis/canvas/index.ts +27 -0
  13. package/dist/runtime/apis/data-analysis/index.ts +6 -0
  14. package/dist/runtime/apis/device/accelerometer.ts +79 -0
  15. package/dist/runtime/apis/device/accessibility.ts +4 -0
  16. package/dist/runtime/apis/device/battery.ts +24 -0
  17. package/dist/runtime/apis/device/bluetooth-ble.ts +19 -0
  18. package/dist/runtime/apis/device/bluetooth-peripheral.ts +6 -0
  19. package/dist/runtime/apis/device/bluetooth.ts +16 -0
  20. package/dist/runtime/apis/device/calendar.ts +5 -0
  21. package/dist/runtime/apis/device/clipboard.ts +85 -0
  22. package/dist/runtime/apis/device/compass.ts +21 -0
  23. package/dist/runtime/apis/device/contact.ts +5 -0
  24. package/dist/runtime/apis/device/crypto.ts +4 -0
  25. package/dist/runtime/apis/device/gyroscope.ts +77 -0
  26. package/dist/runtime/apis/device/iBeacon.ts +10 -0
  27. package/dist/runtime/apis/device/index.ts +24 -0
  28. package/dist/runtime/apis/device/keyboard.ts +63 -0
  29. package/dist/runtime/apis/device/memory.ts +11 -0
  30. package/dist/runtime/apis/device/motion.ts +6 -0
  31. package/dist/runtime/apis/device/network.ts +123 -0
  32. package/dist/runtime/apis/device/nfc.ts +10 -0
  33. package/dist/runtime/apis/device/phone.ts +44 -0
  34. package/dist/runtime/apis/device/scan.ts +4 -0
  35. package/dist/runtime/apis/device/screen.ts +80 -0
  36. package/dist/runtime/apis/device/sms.ts +4 -0
  37. package/dist/runtime/apis/device/vibrate.ts +32 -0
  38. package/dist/runtime/apis/device/wifi.ts +15 -0
  39. package/dist/runtime/apis/ext/index.ts +5 -0
  40. package/dist/runtime/apis/files/index.ts +136 -0
  41. package/dist/runtime/apis/files/manager.ts +942 -0
  42. package/dist/runtime/apis/framework/index.ts +48 -0
  43. package/dist/runtime/apis/harmony/task-pool.ts +39 -0
  44. package/dist/runtime/apis/index.ts +61 -0
  45. package/dist/runtime/apis/location/index.ts +133 -0
  46. package/dist/runtime/apis/media/EditorContext.ts +32 -0
  47. package/dist/runtime/apis/media/audio/index.ts +36 -0
  48. package/dist/runtime/apis/media/background-audio/index.ts +16 -0
  49. package/dist/runtime/apis/media/camera.ts +16 -0
  50. package/dist/runtime/apis/media/common.ts +58 -0
  51. package/dist/runtime/apis/media/image/index.ts +291 -0
  52. package/dist/runtime/apis/media/index.ts +13 -0
  53. package/dist/runtime/apis/media/live.ts +5 -0
  54. package/dist/runtime/apis/media/map.ts +4 -0
  55. package/dist/runtime/apis/media/media-recorder.ts +4 -0
  56. package/dist/runtime/apis/media/recorder.ts +6 -0
  57. package/dist/runtime/apis/media/video/VideoContext.ts +67 -0
  58. package/dist/runtime/apis/media/video/index.ts +45 -0
  59. package/dist/runtime/apis/media/video-decoder.ts +4 -0
  60. package/dist/runtime/apis/media/video-processing.ts +4 -0
  61. package/dist/runtime/apis/media/voip.ts +19 -0
  62. package/dist/runtime/apis/navigate/index.ts +8 -0
  63. package/dist/runtime/apis/network/downloadFile.ts +85 -0
  64. package/dist/runtime/apis/network/index.ts +7 -0
  65. package/dist/runtime/apis/network/mdns.ts +13 -0
  66. package/dist/runtime/apis/network/request.ts +140 -0
  67. package/dist/runtime/apis/network/tcp.ts +4 -0
  68. package/dist/runtime/apis/network/udp.ts +4 -0
  69. package/dist/runtime/apis/network/uploadFile.ts +105 -0
  70. package/dist/runtime/apis/network/webSocket.ts +126 -0
  71. package/dist/runtime/apis/open-api/account.ts +4 -0
  72. package/dist/runtime/apis/open-api/address.ts +4 -0
  73. package/dist/runtime/apis/open-api/authorize.ts +5 -0
  74. package/dist/runtime/apis/open-api/card.ts +5 -0
  75. package/dist/runtime/apis/open-api/channels-live.ts +11 -0
  76. package/dist/runtime/apis/open-api/customer-service.ts +4 -0
  77. package/dist/runtime/apis/open-api/device-voip.ts +5 -0
  78. package/dist/runtime/apis/open-api/facial.ts +7 -0
  79. package/dist/runtime/apis/open-api/favorites.ts +5 -0
  80. package/dist/runtime/apis/open-api/group.ts +4 -0
  81. package/dist/runtime/apis/open-api/index.ts +21 -0
  82. package/dist/runtime/apis/open-api/invoice.ts +5 -0
  83. package/dist/runtime/apis/open-api/license-plate.ts +4 -0
  84. package/dist/runtime/apis/open-api/login.ts +6 -0
  85. package/dist/runtime/apis/open-api/my-miniprogram.ts +4 -0
  86. package/dist/runtime/apis/open-api/privacy.ts +7 -0
  87. package/dist/runtime/apis/open-api/red-package.ts +4 -0
  88. package/dist/runtime/apis/open-api/settings.ts +5 -0
  89. package/dist/runtime/apis/open-api/soter.ts +6 -0
  90. package/dist/runtime/apis/open-api/subscribe-message.ts +6 -0
  91. package/dist/runtime/apis/open-api/user-info.ts +70 -0
  92. package/dist/runtime/apis/open-api/werun.ts +5 -0
  93. package/dist/runtime/apis/payment/index.ts +6 -0
  94. package/dist/runtime/apis/route/index.ts +88 -0
  95. package/dist/runtime/apis/share/index.ts +33 -0
  96. package/dist/runtime/apis/storage/background-fetch.ts +7 -0
  97. package/dist/runtime/apis/storage/cache-manager.ts +4 -0
  98. package/dist/runtime/apis/storage/index.ts +203 -0
  99. package/dist/runtime/apis/ui/animation/animation.ts +264 -0
  100. package/dist/runtime/apis/ui/animation/index.ts +7 -0
  101. package/dist/runtime/apis/ui/background.ts +20 -0
  102. package/dist/runtime/apis/ui/custom-component.ts +1 -0
  103. package/dist/runtime/apis/ui/fonts.ts +4 -0
  104. package/dist/runtime/apis/ui/index.ts +12 -0
  105. package/dist/runtime/apis/ui/interaction/index.ts +198 -0
  106. package/dist/runtime/apis/ui/menu.ts +4 -0
  107. package/dist/runtime/apis/ui/navigation-bar/index.ts +72 -0
  108. package/dist/runtime/apis/ui/pull-down-refresh.ts +47 -0
  109. package/dist/runtime/apis/ui/scroll/index.ts +82 -0
  110. package/dist/runtime/apis/ui/sticky.ts +4 -0
  111. package/dist/runtime/apis/ui/tab-bar.ts +144 -0
  112. package/dist/runtime/apis/ui/window.ts +20 -0
  113. package/dist/runtime/apis/utils/constant.ts +1 -0
  114. package/dist/runtime/apis/utils/handler.ts +117 -0
  115. package/dist/runtime/apis/utils/index.ts +105 -0
  116. package/dist/runtime/apis/utils/permissions.ts +6 -0
  117. package/dist/runtime/apis/utils/types.ts +12 -0
  118. package/dist/runtime/apis/utils/unit.ts +104 -0
  119. package/dist/runtime/apis/utils/validate.ts +87 -0
  120. package/dist/runtime/apis/worker/index.ts +4 -0
  121. package/dist/runtime/apis/wxml/index.ts +17 -0
  122. package/dist/runtime/apis/wxml/intersectionObserver.ts +100 -0
  123. package/dist/runtime/apis/wxml/nodesRef.ts +58 -0
  124. package/dist/runtime/apis/wxml/selectorQuery.ts +221 -0
  125. package/dist/runtime/apischunk/index.d.ts +802 -0
  126. package/dist/runtime/apischunk/index.js +5054 -0
  127. package/dist/runtime/components/deprecated.ets +43 -0
  128. package/dist/runtime/components/index.ets +49 -0
  129. package/dist/runtime/components/innerHtml.ets +16 -0
  130. package/dist/runtime/components/navigationBar.ets +65 -0
  131. package/dist/runtime/components/pageMeta.ets +94 -0
  132. package/dist/runtime/components/richText.ets +24 -0
  133. package/dist/runtime/components/slider.ets +119 -0
  134. package/dist/runtime/components/style.ets +286 -0
  135. package/dist/runtime/components/switch.ets +73 -0
  136. package/dist/runtime/components/tag.ts +58 -0
  137. package/dist/runtime/components/utils/AttributeManager.ets +252 -0
  138. package/dist/runtime/components/utils/DynamicCenter.ts +41 -0
  139. package/dist/runtime/components/utils/constant/event.ets +25 -0
  140. package/dist/runtime/components/utils/constant/style.ets +91 -0
  141. package/dist/runtime/components/utils/events.ts +26 -0
  142. package/dist/runtime/components/utils/flexManager.ets +49 -0
  143. package/dist/runtime/components/utils/helper.ets +51 -0
  144. package/dist/runtime/components/utils/htmlParser/HarmonyHTMLParser.ts +100 -0
  145. package/dist/runtime/components/utils/htmlParser/index.ts +58 -0
  146. package/dist/runtime/components/utils/index.ts +77 -0
  147. package/dist/runtime/components/utils/styles.ets +41 -0
  148. package/dist/runtime/components/video.ets +119 -0
  149. package/dist/runtime/components/webView.ets +55 -0
  150. package/dist/runtime/components/xComponent.ets +89 -0
  151. package/dist/runtime/framework/app.ts +248 -0
  152. package/dist/runtime/framework/connect.ts +24 -0
  153. package/dist/runtime/framework/constant.ts +3 -0
  154. package/dist/runtime/framework/hooks.ts +99 -0
  155. package/dist/runtime/framework/index.ts +15 -0
  156. package/dist/runtime/framework/native-page.ts +511 -0
  157. package/dist/runtime/framework/page.ts +256 -0
  158. package/dist/runtime/framework/utils/index.ts +17 -0
  159. package/dist/runtime/framework/utils/is.ts +26 -0
  160. package/dist/runtime/framework-reconciler/componentTree.ts +81 -0
  161. package/dist/runtime/framework-reconciler/constant.ts +86 -0
  162. package/dist/runtime/framework-reconciler/domInput.ts +90 -0
  163. package/dist/runtime/framework-reconciler/event.ts +108 -0
  164. package/dist/runtime/framework-reconciler/index.ts +99 -0
  165. package/dist/runtime/framework-reconciler/inputValueTracking.ts +106 -0
  166. package/dist/runtime/framework-reconciler/props.ts +132 -0
  167. package/dist/runtime/framework-reconciler/reconciler.ts +202 -0
  168. package/dist/runtime/framework-reconciler/render.ts +139 -0
  169. package/dist/runtime/framework-reconciler/workTags.ts +53 -0
  170. package/dist/runtime/runtime-cpp/bom/URL.ts +2 -0
  171. package/dist/runtime/runtime-cpp/bom/document.ts +45 -0
  172. package/dist/runtime/runtime-cpp/bom/history.ts +1 -0
  173. package/dist/runtime/runtime-cpp/bom/location.ts +1 -0
  174. package/dist/runtime/runtime-cpp/bom/navigator.ts +1 -0
  175. package/dist/runtime/runtime-cpp/bom/raf.ts +1 -0
  176. package/dist/runtime/runtime-cpp/bom/window.ts +57 -0
  177. package/dist/runtime/runtime-cpp/constant.ts +29 -0
  178. package/dist/runtime/runtime-cpp/current.ts +48 -0
  179. package/dist/runtime/runtime-cpp/dom/class-list.ts +41 -0
  180. package/dist/runtime/runtime-cpp/dom/comment.ts +9 -0
  181. package/dist/runtime/runtime-cpp/dom/dataSource.ts +87 -0
  182. package/dist/runtime/runtime-cpp/dom/document.ts +113 -0
  183. package/dist/runtime/runtime-cpp/dom/element/canvas.ts +285 -0
  184. package/dist/runtime/runtime-cpp/dom/element/element.ts +262 -0
  185. package/dist/runtime/runtime-cpp/dom/element/form.ts +371 -0
  186. package/dist/runtime/runtime-cpp/dom/element/index.ts +129 -0
  187. package/dist/runtime/runtime-cpp/dom/element/movable.ts +250 -0
  188. package/dist/runtime/runtime-cpp/dom/element/normal.ts +123 -0
  189. package/dist/runtime/runtime-cpp/dom/element/scroll_view.ts +32 -0
  190. package/dist/runtime/runtime-cpp/dom/element/text.ts +9 -0
  191. package/dist/runtime/runtime-cpp/dom/element/video.ts +66 -0
  192. package/dist/runtime/runtime-cpp/dom/element/web_view.ts +72 -0
  193. package/dist/runtime/runtime-cpp/dom/event-source.ts +1 -0
  194. package/dist/runtime/runtime-cpp/dom/event.ts +187 -0
  195. package/dist/runtime/runtime-cpp/dom/eventTarget.ts +81 -0
  196. package/dist/runtime/runtime-cpp/dom/node.ts +307 -0
  197. package/dist/runtime/runtime-cpp/dom/style.ts +44 -0
  198. package/dist/runtime/runtime-cpp/dom/stylesheet/index.ts +379 -0
  199. package/dist/runtime/runtime-cpp/dom/stylesheet/type.ts +212 -0
  200. package/dist/runtime/runtime-cpp/dom/stylesheet/util.ts +186 -0
  201. package/dist/runtime/runtime-cpp/emitter/emitter.ts +29 -0
  202. package/dist/runtime/runtime-cpp/env.ts +1 -0
  203. package/dist/runtime/runtime-cpp/harmony-library.ts +1 -0
  204. package/dist/runtime/runtime-cpp/index.ts +79 -0
  205. package/dist/runtime/runtime-cpp/interface/event.ts +10 -0
  206. package/dist/runtime/runtime-cpp/interface/index.ts +7 -0
  207. package/dist/runtime/runtime-cpp/next-tick.ts +14 -0
  208. package/dist/runtime/runtime-cpp/system.ts +213 -0
  209. package/dist/runtime/runtime-cpp/utils/index.ts +63 -0
  210. package/dist/runtime/runtime-cpp/utils/info.ts +123 -0
  211. package/dist/runtime/runtime-cpp/utils/page.ts +12 -0
  212. package/dist/runtime/runtime-cpp/utils/router.ts +1 -0
  213. package/dist/runtime/runtime-harmony/apis/helper.ets +33 -0
  214. package/dist/runtime/runtime-harmony/apis/network/common.ets +41 -0
  215. package/dist/runtime/runtime-harmony/apis/network/downloadFile.ets +327 -0
  216. package/dist/runtime/runtime-harmony/apis/network/index.ets +58 -0
  217. package/dist/runtime/runtime-harmony/apis/network/request.ets +206 -0
  218. package/dist/runtime/runtime-harmony/apis/network/uploadFile.ets +190 -0
  219. package/dist/runtime/runtime-harmony/apis/route.ets +110 -0
  220. package/dist/runtime/runtime-harmony/apis/taskpool.ets +149 -0
  221. package/dist/runtime/runtime-harmony/index.ets +41 -0
  222. package/dist/runtime/runtime-harmony/utils.ts +53 -0
  223. package/package.json +25 -23
  224. package/static/@taro-oh/library-4.1.1-alpha.0.har +0 -0
  225. package/LICENSE +0 -174
package/dist/index.js ADDED
@@ -0,0 +1,1236 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var node_child_process = require('node:child_process');
6
+ var path = require('node:path');
7
+ var helper = require('@tarojs/helper');
8
+ var constants$1 = require('@tarojs/vite-runner/dist/utils/constants');
9
+ var dist = require('@tarojs/plugin-platform-harmony-ets/dist');
10
+ var harmony = require('@tarojs/vite-runner/dist/utils/compiler/harmony');
11
+ var shared = require('@tarojs/shared');
12
+ var core = require('@babel/core');
13
+ var page = require('@tarojs/vite-runner/dist/harmony/page');
14
+ var utils = require('@tarojs/vite-runner/dist/utils');
15
+ var parseCssToStylesheet = require('@tarojs/parse-css-to-stylesheet');
16
+ var constants = require('@tarojs/vite-runner/dist/harmony/postcss/constants');
17
+
18
+ var version = "4.1.1-alpha.1";
19
+
20
+ const PKG_NAME = '@taro-oh/library';
21
+ const PKG_VERSION = version;
22
+ const PROJECT_DEPENDENCIES_NAME = [];
23
+ const PKG_DEPENDENCIES = {};
24
+
25
+ /* eslint-disable no-console */
26
+ const PLATFORM_NAME = 'harmony_cpp';
27
+ const PACKAGE_NAME = '@tarojs/plugin-platform-harmony-cpp';
28
+ const NPM_DIR = 'npm';
29
+ const CPP_LIBRARY_NAME = 'libTaroHarmonyLibrary.so';
30
+ const CPP_LIBRARY_PATH = 'file:./src/main/cpp/types/taro-native-node';
31
+ function checkDebug() {
32
+ return process.argv.includes('--debug') || process.argv.includes('-D');
33
+ }
34
+ function getProcessArg(name, defaultValue = '') {
35
+ const argv = process.argv;
36
+ const index = process.argv.findIndex(arg => arg.startsWith(`--${name}`));
37
+ if (index > -1) {
38
+ if (argv[index].includes('=')) {
39
+ return argv[index].split('=')[1] ?? defaultValue;
40
+ }
41
+ else {
42
+ return argv[index + 1] ?? defaultValue;
43
+ }
44
+ }
45
+ return defaultValue;
46
+ }
47
+ checkDebug();
48
+ function getProjectId(name = '') {
49
+ const pkg = harmony.readJsonSync(path.posix.join(process.cwd(), 'package.json'));
50
+ return `${pkg.name || name}@${pkg.version || '0.0.1'}`;
51
+ }
52
+ const SEP_RGX = /[\\/]+/g;
53
+ function fixBuildProfile(lib = '', outputRoot = '') {
54
+ const stats = helper.fs.statSync(lib);
55
+ if (stats.isDirectory()) {
56
+ helper.fs.readdirSync(lib).forEach((item) => fixBuildProfile(path.join(lib, item), outputRoot));
57
+ }
58
+ else if (stats.isFile() && lib.endsWith('.ets')) {
59
+ let data = helper.fs.readFileSync(lib, 'utf-8');
60
+ const buildProfilePath = path.resolve(outputRoot, 'BuildProfile');
61
+ const rgx = /import\s+(\S+)\s+from\s*['"]BuildProfile['"]/;
62
+ if (rgx.test(data)) {
63
+ data = data.replace(rgx, (_, p1) => {
64
+ return `import ${p1} from '${path.relative(path.dirname(lib), buildProfilePath).replace(SEP_RGX, '/')}'`;
65
+ });
66
+ helper.fs.writeFileSync(lib, data, 'utf-8');
67
+ }
68
+ }
69
+ }
70
+ function updateBuildProfile(buildProfilePath, hapName = 'entry') {
71
+ if (!helper.fs.existsSync(buildProfilePath)) {
72
+ console.log(helper.chalk.yellow(`目标路径配置文件缺失,可能是非法的 Harmony 模块: ${buildProfilePath}`));
73
+ }
74
+ try {
75
+ const profile = harmony.readJsonSync(buildProfilePath);
76
+ profile.buildOption.externalNativeOptions = {
77
+ ...profile.externalNativeOptions,
78
+ path: './src/main/cpp/CMakeLists.txt',
79
+ arguments: '-DCMAKE_JOB_POOL_COMPILE:STRING=compile -DCMAKE_JOB_POOL_LINK:STRING=link -DCMAKE_JOB_POOLS:STRING=compile=8;link=8',
80
+ cppFlags: '',
81
+ abiFilters: [
82
+ 'arm64-v8a'
83
+ ]
84
+ };
85
+ if (profile.buildOptionSet instanceof Array) {
86
+ helper.fs.writeFileSync(path.join(buildProfilePath, '..', 'consumer-rules.txt'), [
87
+ '-keep-property-name',
88
+ '',
89
+ // pages
90
+ 'toLocation',
91
+ '',
92
+ // '@tarojs/runtime',
93
+ 'designRatio',
94
+ 'densityDPI',
95
+ 'densityPixels',
96
+ 'deviceWidth',
97
+ 'deviceHeight',
98
+ 'viewportWidth',
99
+ 'viewportHeight',
100
+ 'safeArea',
101
+ 'scaledDensity',
102
+ 'orientation',
103
+ 'content',
104
+ 'selectorList',
105
+ ].join('\n'));
106
+ profile.buildOptionSet.forEach((option) => {
107
+ option.arkOptions ||= {};
108
+ option.arkOptions.obfuscation ||= {};
109
+ option.arkOptions.obfuscation.ruleOptions ||= {};
110
+ option.arkOptions.obfuscation.ruleOptions.files ||= [];
111
+ const obfuscations = [
112
+ './consumer-rules.txt',
113
+ './src/main/cpp/types/taro-native-node/obfuscation-rules.txt',
114
+ ];
115
+ if (hapName !== 'entry') {
116
+ option.arkOptions.obfuscation.ruleOptions.enable = true;
117
+ option.arkOptions.obfuscation.consumerFiles ||= [];
118
+ const files = option.arkOptions.obfuscation.consumerFiles;
119
+ if (!files.includes(obfuscations[0])) {
120
+ files.push(...obfuscations);
121
+ }
122
+ }
123
+ else {
124
+ const files = option.arkOptions.obfuscation.ruleOptions.files;
125
+ if (!files.includes(obfuscations[0])) {
126
+ files.push(...obfuscations);
127
+ }
128
+ }
129
+ });
130
+ }
131
+ helper.fs.writeJSONSync(buildProfilePath, profile, { spaces: 2 });
132
+ }
133
+ catch (error) {
134
+ console.warn(helper.chalk.red('更新鸿蒙配置失败:', error));
135
+ }
136
+ }
137
+
138
+ function appPlugin () {
139
+ const that = this;
140
+ return {
141
+ name: 'taro:vite-harmony-template-app',
142
+ enforce: 'pre',
143
+ buildStart() {
144
+ const pluginContext = this;
145
+ const { runnerUtils } = that.context;
146
+ const { getViteHarmonyCompilerContext } = runnerUtils;
147
+ const compiler = getViteHarmonyCompilerContext(pluginContext);
148
+ if (compiler) {
149
+ const app = compiler.app;
150
+ app.modifyAppImport = function (importStr, _app) {
151
+ importStr.splice(-3, 0, 'import { TaroWindowUtil } from "@tarojs/runtime"');
152
+ };
153
+ compiler.loaderMeta ||= {};
154
+ const oddModifyInstantiate = compiler.loaderMeta.modifyInstantiate;
155
+ compiler.loaderMeta.modifyInstantiate = function (code = '', type = '', app) {
156
+ if (type === 'app') {
157
+ const codeLines = code.split('\n');
158
+ const resolverIndex = codeLines.findIndex(line => line.includes('context.resolver'));
159
+ if (resolverIndex >= 0) {
160
+ codeLines.splice(resolverIndex + 1, 0, codeLines[resolverIndex].replace(/\S+/, 'TaroWindowUtil.setWindowStage(stage)'));
161
+ code = codeLines.join('\n');
162
+ }
163
+ }
164
+ compiler.modifyHarmonyConfig(this.appConfig);
165
+ return shared.isFunction(oddModifyInstantiate) ? oddModifyInstantiate.call(this, code, type, app) : code;
166
+ };
167
+ }
168
+ },
169
+ };
170
+ }
171
+
172
+ function injectEnv () {
173
+ const that = this;
174
+ const packageName = '@tarojs/taro';
175
+ const bindingName = 'Taro';
176
+ const businessId = this.config.defineConstants?.LOCATION_APIKEY?.replace(/^['"]|['"]$/g, '');
177
+ return {
178
+ name: 'taro:vite-add-method-env',
179
+ transform(code, id) {
180
+ const pluginContext = this;
181
+ const { runnerUtils } = that.context;
182
+ const { getViteHarmonyCompilerContext } = runnerUtils;
183
+ const compiler = getViteHarmonyCompilerContext(pluginContext);
184
+ const exts = Array.from(new Set(compiler?.frameworkExts.concat(helper.SCRIPT_EXT)));
185
+ if (!exts.some(ext => id?.split('?')[0].endsWith(ext))) {
186
+ return;
187
+ }
188
+ let taroName = bindingName;
189
+ let imported = false;
190
+ const methodName = ['getLocation'];
191
+ const result = core.transformSync(code, {
192
+ filename: id,
193
+ plugins: [
194
+ (babel) => {
195
+ const { types: t } = babel;
196
+ return {
197
+ visitor: {
198
+ Program: {
199
+ enter: (ast) => {
200
+ taroName = ast.scope.getBinding(bindingName)
201
+ ? ast.scope.generateUid(bindingName)
202
+ : bindingName;
203
+ }
204
+ },
205
+ ImportDeclaration(ast) {
206
+ if (ast.node.source.value !== packageName)
207
+ return;
208
+ imported = true;
209
+ ast.node.specifiers.forEach(spec => {
210
+ if (t.isImportDefaultSpecifier(spec)) {
211
+ taroName = spec.local.name;
212
+ }
213
+ else if (t.isImportSpecifier(spec)) {
214
+ const { imported } = spec;
215
+ const propertyName = t.isIdentifier(imported) ? imported.name : imported.value;
216
+ if (methodName.includes(propertyName)) {
217
+ // Note: 记录当前导入的方法别名
218
+ methodName.push(spec.local.name);
219
+ }
220
+ }
221
+ });
222
+ },
223
+ CallExpression(path) {
224
+ if (!imported)
225
+ return;
226
+ if (!t.isIdentifier(path.node.callee) || !methodName.includes(path.node.callee.name))
227
+ return;
228
+ const args = path.node.arguments[0];
229
+ if (t.isObjectExpression(args)) {
230
+ const hasBusinessId = args.properties.some(prop => !t.isSpreadElement(prop) && t.isIdentifier(prop.key) && prop.key.name === 'businessId');
231
+ if (!hasBusinessId) {
232
+ if (!businessId) {
233
+ console.warn(`Error: 使用定位相关 API(${path.node.callee.name}) 时,需要配置 defineConstants.LOCATION_APIKEY 为 businessId.`);
234
+ return;
235
+ }
236
+ args.properties.push(t.objectProperty(t.identifier('businessId'), t.stringLiteral(businessId)));
237
+ }
238
+ }
239
+ },
240
+ MemberExpression(path) {
241
+ if (!imported)
242
+ return;
243
+ if (t.isIdentifier(path.node.object) && path.node.object.name === taroName) {
244
+ if (t.isIdentifier(path.node.property) && methodName.includes(path.node.property.name)) {
245
+ const parent = path.findParent(p => p.isCallExpression());
246
+ if (parent && t.isCallExpression(parent.node)) {
247
+ const args = parent.node.arguments[0];
248
+ if (t.isObjectExpression(args)) {
249
+ const hasBusinessId = args.properties.some(prop => !t.isSpreadElement(prop) && t.isIdentifier(prop.key) && prop.key.name === 'businessId');
250
+ if (!hasBusinessId) {
251
+ if (!businessId) {
252
+ console.warn(`Error: 使用定位相关 API(${path.node.property.name}) 时,需要配置 defineConstants.LOCATION_APIKEY 为 businessId.`);
253
+ return;
254
+ }
255
+ args.properties.push(t.objectProperty(t.identifier('businessId'), t.stringLiteral(businessId)));
256
+ }
257
+ }
258
+ }
259
+ }
260
+ }
261
+ }
262
+ }
263
+ };
264
+ }
265
+ ],
266
+ sourceType: 'module'
267
+ });
268
+ return {
269
+ code: result?.code || code,
270
+ map: result?.map || null,
271
+ };
272
+ }
273
+ };
274
+ }
275
+
276
+ function pagePlugin () {
277
+ const that = this;
278
+ const projectId = getProjectId();
279
+ function genUniPageId(page) {
280
+ return `${projectId}:${page.originName || page.name}`;
281
+ }
282
+ const name = 'taro:vite-harmony-template-page';
283
+ return {
284
+ name,
285
+ enforce: 'pre',
286
+ options(opt) {
287
+ if (opt.plugins instanceof Array) {
288
+ // Note: CAPI 模式禁用半编译能力
289
+ const idx = opt.plugins.findIndex((e) => e && e.name === 'taro:vite-compile-mode');
290
+ if (idx >= 0) {
291
+ const compileMode = opt.plugins[idx];
292
+ compileMode.name = 'taro:vite-capi-compile-mode';
293
+ delete compileMode.transform;
294
+ opt.plugins.splice(idx, 1, compileMode);
295
+ }
296
+ }
297
+ },
298
+ buildStart() {
299
+ const pluginContext = this;
300
+ const { runnerUtils, runOpts } = that.context;
301
+ const isPureComp = (page) => {
302
+ return runOpts?.options?.args.pure || page.config?.entryOption === false;
303
+ };
304
+ const { getViteHarmonyCompilerContext } = runnerUtils;
305
+ const compiler = getViteHarmonyCompilerContext(pluginContext);
306
+ const taroConfig = compiler.taroConfig;
307
+ if (compiler?.pages instanceof Array || compiler?.components instanceof Array) {
308
+ compiler.loaderMeta ||= {};
309
+ const oddModifyEntryFile = compiler.loaderMeta.modifyEntryFile;
310
+ compiler.loaderMeta.modifyEntryFile = function (type = '', rawId = '', rawCode = '', page) {
311
+ if (type === 'page') {
312
+ const isPure = isPureComp(page);
313
+ const { creatorLocation, frameworkArgs, importFrameworkStatement } = this.loaderMeta;
314
+ const isBlended = this.buildConfig.blended || this.buildConfig.isBuildNativeComp;
315
+ const createFn = isPure
316
+ ? 'createNativeComponentConfig'
317
+ : isBlended
318
+ ? 'createNativePageConfig'
319
+ : 'createPageConfig';
320
+ const pageId = genUniPageId(page);
321
+ const createPageOrComponent = `${createFn}(component, ${isPure || isBlended ? `'${pageId}', ${frameworkArgs}` : `'${pageId}', config`})`;
322
+ return this.transArr2Str([
323
+ `import { ${createFn} } from '${creatorLocation}'`,
324
+ ...(importFrameworkStatement || '').split('\n'),
325
+ `import component from "${utils.escapePath(rawId)}"`,
326
+ isBlended ? 'import { initPxTransform } from "@tarojs/taro"' : null,
327
+ `export const config = ${this.prettyPrintJson(page.config)}`,
328
+ // FIXME: InitPxTransform放在这里会导致多component相互影响
329
+ isBlended ? this.getInitPxTransform() : null,
330
+ page?.config.enableShareTimeline ? 'component.enableShareTimeline = true' : null,
331
+ page?.config.enableShareAppMessage ? 'component.enableShareAppMessage = true' : null,
332
+ `export default (config = {}) => ${createPageOrComponent}`,
333
+ ]);
334
+ }
335
+ return shared.isFunction(oddModifyEntryFile) ? oddModifyEntryFile.call(this, type, rawId, rawCode, page) : rawCode;
336
+ };
337
+ const oddModifyInstantiate = compiler.loaderMeta.modifyInstantiate;
338
+ compiler.loaderMeta.modifyInstantiate = function (code = '', type = '', page) {
339
+ if (type === 'page') {
340
+ const componentName = page.config?.componentName;
341
+ if (shared.isString(componentName)) {
342
+ code = code.replace(/export\sdefault\sstruct\sIndex/, `export struct ${componentName}`);
343
+ }
344
+ }
345
+ return shared.isFunction(oddModifyInstantiate) ? oddModifyInstantiate.call(this, code, type, page) : code;
346
+ };
347
+ const parsePageOrComp = (config) => {
348
+ if (!isPureComp(config)) {
349
+ config.entryOption = {};
350
+ }
351
+ config.modifyPageImport = function (importStr, page) {
352
+ if (!isPureComp(page)) {
353
+ Object.assign(config.entryOption, {
354
+ routeName: page.name,
355
+ });
356
+ if (shared.isObject(page.config?.entryOption)) {
357
+ Object.assign(config.entryOption, page.config.entryOption);
358
+ }
359
+ }
360
+ importStr.unshift('import { navigateBack } from "@tarojs/taro"');
361
+ importStr.unshift('import oh_window from "@ohos.window"');
362
+ importStr.unshift('import { TaroXComponent } from "@tarojs/components"');
363
+ importStr.unshift('import { TaroNativeModule, initStyleSheetConfig, systemContext, WINDOW_STATE } from "@tarojs/runtime"');
364
+ importStr.unshift('import { NodeContent } from "@ohos.arkui.node"');
365
+ importStr.unshift('import display from "@ohos.display"');
366
+ importStr.unshift('import { audio } from "@kit.AudioKit"');
367
+ };
368
+ config.modifyRenderState = function (state, page) {
369
+ const isPure = isPureComp(page);
370
+ state.push(this.renderState({
371
+ name: '__layoutSize',
372
+ type: 'TaroAny',
373
+ foreach: () => 'null',
374
+ disabled: !this.buildConfig.isBuildNativeComp && isPure,
375
+ }, this.isTabbarPage), this.renderState({
376
+ name: 'areaChange',
377
+ type: 'TaroAny',
378
+ foreach: () => 'null',
379
+ }, this.isTabbarPage), this.renderState({
380
+ name: '__pageName',
381
+ type: 'TaroAny',
382
+ foreach: () => 'null',
383
+ disabled: !this.buildConfig.isBuildNativeComp && isPure,
384
+ }, this.isTabbarPage), this.renderState({
385
+ decorator: 'State',
386
+ name: 'params', // FIXME 考虑后续移除该参数
387
+ type: 'TaroObject',
388
+ foreach: () => '{}',
389
+ disabled: !this.buildConfig.isBuildNativeComp && isPure,
390
+ }, this.isTabbarPage), this.renderState({
391
+ decorator: 'State',
392
+ name: 'statusBarHeight',
393
+ type: 'number',
394
+ foreach: () => 'getSystemInfoSync().statusBarHeight || 0',
395
+ }, this.isTabbarPage), this.renderState({
396
+ decorator: 'State',
397
+ name: 'isHideTitleBar',
398
+ type: 'boolean',
399
+ foreach: () => this.appConfig.window?.navigationStyle === 'custom'
400
+ ? `config.navigationStyle !== 'default'`
401
+ : `config.navigationStyle === 'custom'`,
402
+ }, this.isTabbarPage), this.renderState({
403
+ decorator: 'State',
404
+ name: 'isUseCache',
405
+ type: 'boolean',
406
+ foreach: () => 'false',
407
+ disabled: !this.buildConfig.isBuildNativeComp,
408
+ }, this.isTabbarPage), this.renderState({
409
+ name: 'isReported',
410
+ type: 'boolean',
411
+ foreach: () => 'false',
412
+ disabled: !this.buildConfig.isBuildNativeComp,
413
+ }, this.isTabbarPage), this.renderState({
414
+ name: 'isShown',
415
+ type: 'boolean',
416
+ foreach: () => 'true',
417
+ disabled: !this.buildConfig.isBuildNativeComp && isPure,
418
+ }, this.isTabbarPage), this.renderState({
419
+ name: 'nodeContent',
420
+ type: 'Content',
421
+ foreach: () => 'new NodeContent()',
422
+ }, this.isTabbarPage), this.renderState({
423
+ decorator: 'State',
424
+ name: 'isReady',
425
+ type: 'boolean',
426
+ foreach: () => 'false',
427
+ }, this.isTabbarPage), this.renderState({
428
+ decorator: 'State',
429
+ name: 'pullDownRatio',
430
+ type: 'number',
431
+ foreach: () => '1',
432
+ }, this.isTabbarPage));
433
+ if (isPureComp(page)) {
434
+ state.unshift(this.renderState({
435
+ decorator: 'State',
436
+ name: 'currentRouter',
437
+ type: '(TaroObject | null)',
438
+ foreach: () => 'null',
439
+ }, this.isTabbarPage));
440
+ }
441
+ };
442
+ config.modifyPageParams = (_) => {
443
+ return 'this.params';
444
+ };
445
+ config.modifyPageAppear = function (appearStr, page) {
446
+ const isPure = isPureComp(page);
447
+ const appearCode = isPure
448
+ ? [
449
+ `initEtsBuilder('${genUniPageId(page)}')`,
450
+ `TaroNativeModule.initStylesheet('${genUniPageId(page)}', styleJson, initStyleSheetConfig(this.params._layout_, this.getNavHeight()))`,
451
+ ]
452
+ : [
453
+ `if (!Current.audioSessionManager) {`,
454
+ ` const audioManager = audio.getAudioManager()`,
455
+ ` Current.audioSessionManager = audioManager.getSessionManager()`,
456
+ `}`,
457
+ `this.activeAudioSession()`,
458
+ `initEtsBuilder('${genUniPageId(page)}')`,
459
+ 'this.__layoutSize = this.params._layout_',
460
+ `this.__pageName = '${page.name}'`,
461
+ `systemContext.windowWidth = ${config.config.windowArea?.width || 'this.params._layout_?.width'}`,
462
+ `systemContext.windowHeight = ${config.config.windowArea?.height || 'this.params._layout_?.height'}`,
463
+ `TaroNativeModule.initStylesheet('${genUniPageId(page)}', styleJson, initStyleSheetConfig({ width: systemContext.windowWidth, height: systemContext.windowHeight}, this.getNavHeight()))`,
464
+ ];
465
+ if (!isPure) {
466
+ appearCode.push('Current.$r = (path: string): Resource => {', ' return $r(path)', '}', 'let currentSplit = false', 'let pendingAreaChange: TaroAny', `const resizeFn = (canSplit: boolean, size: TaroAny, sizeChange: boolean) => {`, ` const _display = display.getDefaultDisplaySync()`, ` const orientation = _display.orientation`, ` const idPortrait = orientation == display.Orientation.PORTRAIT || orientation == display.Orientation.PORTRAIT_INVERTED`, ` const _sysInfo: TaroAny = getSystemInfoSync()`, ` callFn(this.page?.onResize, this, {`, ` size: {`,
467
+ // @ts-ignore
468
+ ` windowWidth: ${config.config.windowArea?.width || 'size?.width'},`,
469
+ // @ts-ignore
470
+ ` windowHeight: ${config.config.windowArea?.height || 'size?.height'},`, ` screenWidth: _sysInfo.screenWidth,`, ` screenHeight: _sysInfo.screenHeight,`, ` },`, ` deviceOrientation: idPortrait ? "portrait" : "landscape",`, ` foldDisplayMode: _sysInfo.foldDisplayMode,`, ` canSplit: canSplit,`, ` reason: sizeChange ? "size" : "statusBar"`, ` })`, `}`, `const avoidAreaChange = (res: TaroAny) => {`, ` const statusHeight: number = px2vp(res.area.topRect.height);`, ` this.statusBarHeight = statusHeight;`, ` TaroNativeModule.UpdateEnvRule('${genUniPageId(page)}', initStyleSheetConfig({ width: this.__layoutSize.width, height: this.__layoutSize.height}, this.getNavHeight()), this.node?._nid)`, ` resizeFn(currentSplit, this.__layoutSize, false)`, `}`, `const windowStage: TaroAny = AppStorage.get(WINDOW_STATE);`, 'this.areaChange = (res: TaroAny) => {', ' if (res.type !== oh_window.AvoidAreaType.TYPE_SYSTEM) return;', ' if (!this.isShown) {', ' pendingAreaChange = () => { avoidAreaChange(res) }', ' } else {', ' avoidAreaChange(res)', ' }', '}', `windowStage.getMainWindowSync().on('avoidAreaChange', this.areaChange)`);
471
+ }
472
+ appearCode.push(appearStr);
473
+ return this.transArr2Str(appearCode.filter(Boolean));
474
+ };
475
+ config.modifyPageDisappear = function (_disappearStr) {
476
+ return this.transArr2Str([
477
+ `this.handlePageDetach()`,
478
+ 'this.deactivateAudioSession()',
479
+ 'if (this.areaChange) {',
480
+ ' const windowStage: TaroAny = AppStorage.get(WINDOW_STATE);',
481
+ ` windowStage.getMainWindowSync().off('avoidAreaChange', this.areaChange)`,
482
+ '}'
483
+ ]);
484
+ };
485
+ config.modifyPageBuild = function (_, page) {
486
+ const coreBuildCodeArray = [
487
+ 'Stack() {',
488
+ ' if (this.isReady) {',
489
+ ' TaroXComponent({ pageId: (this.node as TaroAny)?._nid, data: this.nodeContent })',
490
+ ' }',
491
+ '}',
492
+ '.align(Alignment.TopStart)',
493
+ '.width("100%")',
494
+ '.constraintSize({',
495
+ ' minHeight: "100%",',
496
+ '})',
497
+ '.onDetach(this.handlePageDetach)',
498
+ ];
499
+ if (!isPureComp(page)) {
500
+ coreBuildCodeArray.push('.backgroundColor(this.pageBackgroundContentColor || this.pageBackgroundColor || "#FFFFFF")');
501
+ if (this.enableRefresh === 1) {
502
+ coreBuildCodeArray.forEach((code, idx) => coreBuildCodeArray.splice(idx, 1, `${' '.repeat(2)}${code}`));
503
+ coreBuildCodeArray.unshift('Refresh({', ' refreshing: $$this.isRefreshing,', ' builder: this.customRefreshBuilder()', '}) {');
504
+ coreBuildCodeArray.push('}', '.pullDownRatio(this.pullDownRatio)', '.onStateChange(bindFn(this.handleRefreshStatus, this))');
505
+ }
506
+ coreBuildCodeArray.forEach((code, idx) => coreBuildCodeArray.splice(idx, 1, `${' '.repeat(2)}${code}`));
507
+ coreBuildCodeArray.unshift('Navigation() {');
508
+ coreBuildCodeArray.push('}', `.backgroundColor(this.pageBackgroundColor || '${this.appConfig?.window?.backgroundColor || '#FFFFFF'}')`, `.height('100%')`, `.width('100%')`, `.title({ builder: this.renderTitle, height: this.getNavHeight() })`, `.titleMode(NavigationTitleMode.Mini)`, `.hideTitleBar(this.isHideTitleBar)`, `.hideBackButton(true)`,
509
+ // `.expandSafeArea([SafeAreaType.SYSTEM])`,
510
+ `.mode(NavigationMode.Stack)`);
511
+ }
512
+ return this.transArr2Str(coreBuildCodeArray);
513
+ };
514
+ config.modifyPageMethods = function (methods, page$1) {
515
+ const isPure = isPureComp(page$1);
516
+ const handlePageAppearMethods = methods.find((item) => item.name === 'handlePageAppear');
517
+ if (handlePageAppearMethods) {
518
+ const methodsBodyList = handlePageAppearMethods.body?.split('\n') || [];
519
+ let insertIndex = methodsBodyList.findIndex((item) => item.startsWith('const params'));
520
+ insertIndex = methodsBodyList.findIndex((item) => item.includes('this.node = instance'));
521
+ if (insertIndex >= 0) {
522
+ methodsBodyList?.splice(insertIndex + 1, 0, ...[
523
+ ' TaroNativeModule.buildTaroNode(this.nodeContent, instance._nid)',
524
+ ' this.isReady = true',
525
+ isPure ? ` this.currentRouter = Current.router` : null,
526
+ isPure ? ` eventCenter.on(this.currentRouter?.getEventName('onResize') || '', this.handlePageResizeEvent)` : null,
527
+ ].filter(shared.isString));
528
+ if (taroConfig.isWatch) {
529
+ handlePageAppearMethods.body = this.transArr2Str([
530
+ 'try {',
531
+ this.transArr2Str(methodsBodyList, 2),
532
+ '} catch (error) {',
533
+ ` console.error('[TARO_LOG] page-appear:', error.message + '\\n' + error.stack)`,
534
+ '}',
535
+ ]);
536
+ }
537
+ else {
538
+ handlePageAppearMethods.body = this.transArr2Str(methodsBodyList);
539
+ }
540
+ }
541
+ }
542
+ const disabledMethods = ['onPageShow', 'onPageHide'];
543
+ if (isPure) {
544
+ disabledMethods.unshift('getPageState');
545
+ disabledMethods.push('handleRefreshStatus');
546
+ }
547
+ disabledMethods.forEach((name) => {
548
+ const idx = methods.findIndex((e) => e.name === name);
549
+ if (idx > -1) {
550
+ methods.splice(idx, 1);
551
+ }
552
+ });
553
+ methods.unshift({
554
+ name: 'getNavHeight',
555
+ body: 'return this.isHideTitleBar ? 0 : 48 + this.statusBarHeight',
556
+ });
557
+ methods.push({
558
+ name: 'handlePageDetach',
559
+ type: 'arrow',
560
+ body: this.transArr2Str([
561
+ `if (!this.isReady) return`,
562
+ '',
563
+ `this.isReady = false`,
564
+ isPure
565
+ ? `eventCenter.off(this.currentRouter?.getEventName('onResize'), this.handlePageResizeEvent)`
566
+ : null,
567
+ `callFn(this.page?.onUnload, this)`,
568
+ ]),
569
+ });
570
+ methods.push({
571
+ name: 'activeAudioSession',
572
+ type: 'arrow',
573
+ body: this.transArr2Str([
574
+ `if (Current.audioSessionManager) {`,
575
+ ` const manager: audio.AudioSessionManager = Current.audioSessionManager`,
576
+ ` if (!manager.isAudioSessionActivated()) {`,
577
+ ` let strategy: audio.AudioSessionStrategy = {`,
578
+ ` concurrencyMode: audio.AudioConcurrencyMode.CONCURRENCY_PAUSE_OTHERS`,
579
+ ` }`,
580
+ ` manager.activateAudioSession(strategy)`,
581
+ ` }`,
582
+ `}`,
583
+ ]),
584
+ });
585
+ methods.push({
586
+ name: 'deactivateAudioSession',
587
+ type: 'arrow',
588
+ body: this.transArr2Str([
589
+ `if (Current.audioSessionManager) {`,
590
+ ` const manager: audio.AudioSessionManager = Current.audioSessionManager`,
591
+ ` if (manager.isAudioSessionActivated()) {`,
592
+ ` manager.deactivateAudioSession()`,
593
+ ` }`,
594
+ `}`,
595
+ ]),
596
+ });
597
+ if (!isPure) {
598
+ const index = methods.findIndex((e) => e.name === 'renderTitle');
599
+ methods.splice(index, 1, {
600
+ name: 'renderTitle',
601
+ decorators: ['Builder'],
602
+ body: this.transArr2Str([
603
+ `Flex({`,
604
+ ` direction: FlexDirection.Row,`,
605
+ ` justifyContent: FlexAlign.Start,`,
606
+ ` alignItems: ItemAlign.Center,`,
607
+ `}) {`,
608
+ `${this.transArr2Str(!this.isTabbarPage && !this.buildConfig.isBuildNativeComp
609
+ // FIXME 这里 pageStack 更新问题,需要第二次才能显示 Home 按钮
610
+ ? [
611
+ `if (this.pageStack[0].path !== this.entryPagePath && this.navigationBarHomeBtn && this.pageStack.length === 1) {`,
612
+ ` Image($r('app.media.taro_home'))`,
613
+ ` .height(convertNumber2VP(40 / 7.5, 'vw'))`,
614
+ ` .width(convertNumber2VP(40 / 7.5, 'vw'))`,
615
+ ` .margin({ left: convertNumber2VP(40 / 7.5, 'vw'), right: convertNumber2VP(-20 / 7.5, 'vw') })`,
616
+ ` .fillColor((this.navigationBarTextStyle || '${this.appConfig.window?.navigationBarTextStyle}') !== 'black' ? Color.White : Color.Black)`,
617
+ ` .objectFit(ImageFit.Contain)`,
618
+ ` .onClick(() => {`,
619
+ ` router.replaceUrl({`,
620
+ ` url: this.tabBarList.find(e => e.pagePath === this.entryPagePath) ? '${page.TARO_TABBAR_PAGE_PATH}' : this.entryPagePath,`,
621
+ ` params: {`,
622
+ ` '$page': this.entryPagePath,`,
623
+ ` },`,
624
+ ` })`,
625
+ ` })`,
626
+ ` } else if (this.pageStack.length > 1) {`,
627
+ ` Image($r('app.media.taro_arrow_left'))`,
628
+ ` .height(convertNumber2VP(40 / 7.5, 'vw'))`,
629
+ ` .width(convertNumber2VP(40 / 7.5, 'vw'))`,
630
+ ` .margin({ left: convertNumber2VP(40 / 7.5, 'vw'), right: convertNumber2VP(-20 / 7.5, 'vw') })`,
631
+ ` .fillColor((this.navigationBarTextStyle || '${this.appConfig.window?.navigationBarTextStyle}') !== 'black' ? Color.White : Color.Black)`,
632
+ ` .objectFit(ImageFit.Contain)`,
633
+ ` .onClick(() => {`,
634
+ ` router.back()`,
635
+ ` })`,
636
+ ` }`,
637
+ ] : [], 2)}`,
638
+ ` Text(this.navigationBarTitleText${this.isTabbarPage ? '[this.tabBarCurrentIndex]' : ''} || '${this.appConfig.window?.navigationBarTitleText || ''}')`,
639
+ ` .margin({ left: convertNumber2VP(40 / 7.5, 'vw') })`,
640
+ ` .fontSize(convertNumber2VP(32 / 7.5, 'vw'))`,
641
+ ` .fontColor((this.navigationBarTextStyle${this.isTabbarPage ? '[this.tabBarCurrentIndex]' : ''} || '${this.appConfig.window?.navigationBarTextStyle}') !== 'black' ? Color.White : Color.Black)`,
642
+ ` if (this.navigationBarLoading${this.isTabbarPage ? '[this.tabBarCurrentIndex]' : ''}) {`,
643
+ ` LoadingProgress()`,
644
+ ` .margin({ left: convertNumber2VP(10 / 7.5, 'vw') })`,
645
+ ` .height(convertNumber2VP(40 / 7.5, 'vw'))`,
646
+ ` .width(convertNumber2VP(40 / 7.5, 'vw'))`,
647
+ ` .color((this.navigationBarTextStyle${this.isTabbarPage ? '[this.tabBarCurrentIndex]' : ''} || '${this.appConfig.window?.navigationBarTextStyle}') !== 'black' ? Color.White : Color.Black)`,
648
+ ` }`,
649
+ `}`,
650
+ `.height('100%')`,
651
+ `.width('100%')`,
652
+ `.backgroundColor(this.navigationBarBackgroundColor${this.isTabbarPage ? '[this.tabBarCurrentIndex]' : ''} || '${this.appConfig.window?.navigationBarBackgroundColor || '#000000'}')`,
653
+ `.padding({`,
654
+ ` top: px2vp(sysInfo.safeArea?.top || 0),`,
655
+ `})`,
656
+ `.zIndex(1)`,
657
+ ]),
658
+ });
659
+ if (this.enableRefresh === 1) {
660
+ methods.push({
661
+ name: 'customRefreshBuilder',
662
+ decorators: ['Builder'],
663
+ body: this.transArr2Str([
664
+ 'if (config?.backgroundImageUrl) {',
665
+ ' Image(config?.backgroundImageUrl)',
666
+ ' .objectFit(ImageFit.Contain)',
667
+ ' .width(32)',
668
+ ' .height(32)',
669
+ '} else {',
670
+ ' LoadingProgress()',
671
+ ' .width(32)',
672
+ ' .height(32)',
673
+ '}',
674
+ ]),
675
+ });
676
+ // 禁止页面滚动
677
+ methods.push({
678
+ name: 'disablePullDown',
679
+ body: this.transArr2Str(['this.pullDownRatio = 0']),
680
+ });
681
+ // 允许页面滚动
682
+ methods.push({
683
+ name: 'enablePullDown',
684
+ body: this.transArr2Str([' this.pullDownRatio = 1']),
685
+ });
686
+ }
687
+ }
688
+ else {
689
+ methods.push({
690
+ name: 'handlePageResizeEvent',
691
+ type: 'arrow',
692
+ params: ['option: TaroObject'],
693
+ body: this.transArr2Str([
694
+ `TaroNativeModule.UpdateStylesheet('${genUniPageId(page$1)}', styleJson, initStyleSheetConfig(option.size, this.getNavHeight()), this.node?._nid)`
695
+ ]),
696
+ });
697
+ }
698
+ };
699
+ };
700
+ compiler?.pages?.forEach(parsePageOrComp);
701
+ compiler?.components?.forEach(parsePageOrComp);
702
+ }
703
+ },
704
+ };
705
+ }
706
+
707
+ function renderPlugin () {
708
+ const that = this;
709
+ return {
710
+ name: 'taro:vite-harmony-template-render',
711
+ enforce: 'pre',
712
+ buildStart() {
713
+ const pluginContext = this;
714
+ const { runnerUtils } = that.context;
715
+ const { getViteHarmonyCompilerContext } = runnerUtils;
716
+ const compiler = getViteHarmonyCompilerContext(pluginContext);
717
+ if (compiler) {
718
+ compiler.extraComponents?.push('WaterFlowView');
719
+ compiler.extraComponents?.push('WaterFlow');
720
+ compiler.extraComponents?.push('List');
721
+ compiler.loaderMeta ||= {};
722
+ compiler.loaderMeta.modifyHarmonyRenderChild = function (list) {
723
+ const comps = list.filter(item => ![
724
+ 'View', 'Button', 'Text', 'Image', 'Icon', 'Input', 'TextArea', 'Swiper', 'ScrollView', 'ScrollList', 'StickySection',
725
+ 'ListView', 'MovableArea', 'MovableView', 'Picker', 'WaterFlow', 'WaterFlowView', 'List', 'Canvas', 'Process',
726
+ 'Label', 'CheckboxGroup', 'Checkbox', 'RadioGroup', 'Radio', 'Form',
727
+ ].includes(item.name) && item.type !== 'TaroViewElement');
728
+ list.splice(0, list.length, ...comps, {
729
+ name: 'XComponent',
730
+ type: 'TaroElement',
731
+ fullArgument: '{ pageId: item?._nid }',
732
+ });
733
+ // list.forEach(e => {
734
+ // e.extra = [
735
+ // `${e.extra || ''}`,
736
+ // `.onSizeChange((pre, post) => {`,
737
+ // ` if (pre.width === 0 && pre.height === 0) {`,
738
+ // ` TaroNativeModule.setTaroNodeAttribute(item, '_style4cpp', \`height:\${post.height}px;width:\${post.width}px;\`)`,
739
+ // ` }`,
740
+ // ` })`,
741
+ // ].filter(e => !!e).join('\n')
742
+ // })
743
+ };
744
+ compiler.loaderMeta.modifyHarmonyRenderCode = function (code) {
745
+ const importStr = [
746
+ `import { ComponentContent, FrameNode, NodeController, UIContext } from '@kit.ArkUI'`,
747
+ `import { TaroNativeModule } from '@tarojs/runtime'`,
748
+ `import { TaroXComponent } from '@tarojs/components'`,
749
+ ];
750
+ const codeArr = code.split('\n');
751
+ const idx = codeArr.findIndex(item => !/^(\s*|import\s.+)$/.test(item));
752
+ importStr.push(...codeArr.splice(0, idx));
753
+ return this.transArr2Str([
754
+ ...importStr,
755
+ '',
756
+ ...codeArr,
757
+ '',
758
+ `@Builder
759
+ function createEtsComponent (item: TaroElement) {
760
+ Stack () {
761
+ createChildItem(item, createLazyChildren)
762
+ }
763
+ }`,
764
+ `
765
+ export function initEtsBuilder (router = '') {
766
+ TaroNativeModule.registerEtsBuilder((data: TaroElement): ComponentContent<TaroElement> => {
767
+ console.info("registerEtsBuilder app storage has value: " + Current.uiContext?.instanceId_)
768
+ console.info("registerEtsBuilder: " + data._nid)
769
+ return new ComponentContent<TaroElement>(Current.uiContext, wrapBuilder(createEtsComponent), data)
770
+ }, router)
771
+ }`, // Note: 直接在 render 中注册会被忽略,需要在 XComponent 中注册
772
+ '',
773
+ ]);
774
+ };
775
+ }
776
+ const modifyPageOrComp = (config) => {
777
+ const oddModifyPageImport = config.modifyPageImport;
778
+ config.modifyPageImport = function (importStr, page) {
779
+ if (shared.isFunction(oddModifyPageImport)) {
780
+ oddModifyPageImport.call(this, importStr, page);
781
+ }
782
+ const { sourceRoot = 'src' } = this.buildConfig;
783
+ const targetRoot = path.resolve(this.appPath, sourceRoot);
784
+ const renderPath = path.resolve(targetRoot, 'render');
785
+ importStr.push(`import { initEtsBuilder } from "${renderPath}"`);
786
+ };
787
+ };
788
+ compiler?.pages?.forEach?.(modifyPageOrComp);
789
+ compiler?.components?.forEach?.(modifyPageOrComp);
790
+ },
791
+ };
792
+ }
793
+
794
+ const babelPresets = [
795
+ [
796
+ require.resolve('@babel/preset-env'), {
797
+ shippedProposals: true,
798
+ targets: 'defaults, not ie 11, not ie_mob 11',
799
+ modules: false,
800
+ useBuiltIns: false,
801
+ // 排除已广泛支持的特性
802
+ exclude: [
803
+ '@babel/plugin-proposal-object-rest-spread',
804
+ '@babel/plugin-proposal-optional-chaining',
805
+ '@babel/plugin-transform-arrow-functions',
806
+ '@babel/plugin-transform-async-to-generator',
807
+ '@babel/plugin-transform-destructuring',
808
+ '@babel/plugin-transform-block-scoped-functions',
809
+ '@babel/plugin-transform-block-scoping',
810
+ '@babel/plugin-transform-classes',
811
+ '@babel/plugin-transform-computed-properties',
812
+ '@babel/plugin-transform-duplicate-keys',
813
+ '@babel/plugin-transform-for-of',
814
+ '@babel/plugin-transform-function-name',
815
+ '@babel/plugin-transform-literals',
816
+ '@babel/plugin-transform-nullish-coalescing-operator',
817
+ '@babel/plugin-transform-object-super',
818
+ '@babel/plugin-transform-parameters',
819
+ '@babel/plugin-transform-shorthand-properties',
820
+ '@babel/plugin-transform-spread',
821
+ '@babel/plugin-transform-sticky-regex',
822
+ '@babel/plugin-transform-template-literals',
823
+ '@babel/plugin-transform-typeof-symbol',
824
+ '@babel/plugin-transform-unicode-regex',
825
+ ],
826
+ }
827
+ ],
828
+ require.resolve('@babel/preset-typescript')
829
+ ];
830
+
831
+ /** @deprecated */
832
+ function resourcePlugin () {
833
+ return {
834
+ name: 'taro:vite-harmony-resource',
835
+ enforce: 'pre',
836
+ transform(code, id) {
837
+ if (/(\.(et|j|t)sx?|\.vue)$/.test(id.split('?')[0]) && !/node_modules/.test(id)) {
838
+ try {
839
+ const result = core.transformSync(code, {
840
+ filename: id,
841
+ configFile: false,
842
+ presets: babelPresets,
843
+ plugins: [
844
+ (babel) => {
845
+ const { types: t } = babel;
846
+ const CurrentLabel = 'Current';
847
+ let hasCurrentReference = false;
848
+ return {
849
+ visitor: {
850
+ Identifier(path) {
851
+ if (path.node.name === '$r' &&
852
+ !path.scope.hasBinding('$r') &&
853
+ path.parent.type !== 'MemberExpression') {
854
+ hasCurrentReference = true;
855
+ path.replaceWith(t.memberExpression(t.identifier(CurrentLabel), t.identifier('$r')));
856
+ }
857
+ },
858
+ Program: {
859
+ exit(path) {
860
+ if (hasCurrentReference) {
861
+ let hasCurrentImport = false;
862
+ // 检查是否已有 Current 的导入
863
+ path.node.body.forEach((node) => {
864
+ if (t.isImportDeclaration(node) &&
865
+ node.source.value === '@tarojs/runtime') {
866
+ node.specifiers.forEach((spec) => {
867
+ if (t.isImportSpecifier(spec)) {
868
+ hasCurrentImport = t.isIdentifier(spec.imported) && spec.imported.name === CurrentLabel;
869
+ }
870
+ });
871
+ }
872
+ });
873
+ // 如果没有,添加导入
874
+ if (!hasCurrentImport) {
875
+ const importDeclaration = t.importDeclaration([
876
+ t.importSpecifier(t.identifier(CurrentLabel), t.identifier(CurrentLabel)),
877
+ ], t.stringLiteral('@tarojs/runtime'));
878
+ path.unshiftContainer('body', importDeclaration);
879
+ }
880
+ }
881
+ },
882
+ },
883
+ }
884
+ };
885
+ }
886
+ ]
887
+ });
888
+ return {
889
+ code: result?.code || code,
890
+ map: result?.map || null,
891
+ };
892
+ }
893
+ catch (error) {
894
+ console.error('vite-harmony-resource transform error:', error);
895
+ }
896
+ }
897
+ return null;
898
+ },
899
+ };
900
+ }
901
+
902
+ const STYLE_SUFFIX = '.xss';
903
+ const STYLE_SUFFIX_RE = new RegExp(`\\${STYLE_SUFFIX}(\\?\\S+)?$`);
904
+ function stylePlugin () {
905
+ const that = this;
906
+ let viteConfigResolved;
907
+ const PageMap = new Map();
908
+ return {
909
+ name: 'taro:vite-harmony-style',
910
+ enforce: 'pre',
911
+ configResolved(config) {
912
+ viteConfigResolved = config;
913
+ },
914
+ buildStart() {
915
+ const pluginContext = this;
916
+ const { runnerUtils } = that.context;
917
+ const { getViteHarmonyCompilerContext } = runnerUtils;
918
+ const compiler = getViteHarmonyCompilerContext(pluginContext);
919
+ if (compiler) {
920
+ compiler.loaderMeta ||= {};
921
+ compiler.loaderMeta.enableParseJSXStyle = true;
922
+ }
923
+ const modifyPageOrComp = (config) => {
924
+ const oddModifyPageImport = config.modifyPageImport;
925
+ config.modifyPageImport = function (importStr, page) {
926
+ if (shared.isFunction(oddModifyPageImport)) {
927
+ oddModifyPageImport.call(this, importStr, page);
928
+ }
929
+ const { outputRoot = 'dist', sourceRoot = 'src' } = this.buildConfig;
930
+ const targetRoot = path.resolve(this.appPath, sourceRoot);
931
+ const styleName = `${page.originName}_style.json`;
932
+ const styleJsonPath = path.resolve(targetRoot, styleName);
933
+ importStr.push(`import styleJson from "${styleJsonPath}"`);
934
+ PageMap.set(path.resolve(outputRoot, styleName), pluginContext.getModuleInfo(page.id));
935
+ };
936
+ };
937
+ compiler?.pages?.forEach?.(modifyPageOrComp);
938
+ compiler?.components?.forEach?.(modifyPageOrComp);
939
+ },
940
+ buildEnd() {
941
+ const pluginContext = this;
942
+ const { runnerUtils } = that.context;
943
+ const cacheStyleMap = new Map();
944
+ const { getViteHarmonyCompilerContext } = runnerUtils;
945
+ const compiler = getViteHarmonyCompilerContext(pluginContext);
946
+ const cssModuleId = new Set();
947
+ if (compiler) {
948
+ PageMap.forEach((moduleInfo, styleJsonPath) => {
949
+ const list = findStyleInModuleInfo(moduleInfo);
950
+ const { code } = parseCssToStylesheet.parse(Array.from(list), {
951
+ platformString: 'Harmony',
952
+ });
953
+ if (code) {
954
+ helper.fs.ensureDirSync(path.dirname(styleJsonPath));
955
+ helper.fs.writeFileSync(styleJsonPath, code);
956
+ }
957
+ });
958
+ }
959
+ function findStyleInModuleInfo(moduleInfo, cssList = new Set()) {
960
+ if (!compiler || !moduleInfo)
961
+ return cssList;
962
+ if (cacheStyleMap.has(moduleInfo.id)) {
963
+ const list = cacheStyleMap.get(moduleInfo.id);
964
+ list.forEach((item) => cssList.add(item));
965
+ return cssList;
966
+ }
967
+ else {
968
+ cacheStyleMap.set(moduleInfo.id, cssList);
969
+ }
970
+ if (cssModuleId.has(moduleInfo.id)) {
971
+ return cssList;
972
+ }
973
+ else {
974
+ cssModuleId.add(moduleInfo.id);
975
+ }
976
+ const styleMap = compiler.loaderMeta.parseJSXStyleMapCache?.get(viteConfigResolved);
977
+ for (const oid of moduleInfo.importedIds) {
978
+ const id = utils.stripVirtualModulePrefix(oid).replace(STYLE_SUFFIX_RE, '').replace(constants.usedRE, '');
979
+ if (helper.REG_STYLE.test(id) && styleMap) {
980
+ if (styleMap.has(id)) {
981
+ cssList.add(styleMap.get(id));
982
+ }
983
+ else if (styleMap.has(id + '?used')) {
984
+ cssList.add(styleMap.get(id + '?used'));
985
+ }
986
+ else {
987
+ for (const key of styleMap.keys()) {
988
+ if (key.includes(id) && styleMap.has(key)) {
989
+ cssList.add(styleMap.get(key));
990
+ }
991
+ }
992
+ }
993
+ }
994
+ else {
995
+ // Note: 入口文件被供用时,递归查询仍可能造成依赖错误导致样式丢失,当前使用缓存解决
996
+ findStyleInModuleInfo(pluginContext.getModuleInfo(id), cssList);
997
+ }
998
+ }
999
+ return cssList;
1000
+ }
1001
+ },
1002
+ };
1003
+ }
1004
+
1005
+ class Harmony extends dist.HarmonyOS_ArkTS {
1006
+ get context() {
1007
+ return this.ctx;
1008
+ }
1009
+ constructor(ctx, config, option) {
1010
+ // @ts-ignore
1011
+ super(ctx, config); // Note: link 时,ctx 类型可能无法对齐,此处忽略类型检查
1012
+ this.option = option;
1013
+ this.platform = PLATFORM_NAME;
1014
+ this.runtimePath = `${PACKAGE_NAME}/dist/runtime/runtime-harmony`;
1015
+ this.useETS = true;
1016
+ this.useJSON5 = true;
1017
+ const that = this;
1018
+ this.externalDeps.push([this.runtimePath, new RegExp(`^${this.runtimePath.replace(/([-\\/$])/g, '\\$1')}$`)]);
1019
+ this.externalDeps.forEach(e => {
1020
+ if (e[0] === '@tarojs/react') {
1021
+ e[2] = this.runtimeFrameworkReconciler;
1022
+ }
1023
+ });
1024
+ this.harmonyScope.push(/@(jd|taro)-oh\//, /@kit\./, /^BuildProfile$/);
1025
+ this.setupTransaction.addWrapper({
1026
+ init() {
1027
+ that.modifyPageConfig();
1028
+ },
1029
+ });
1030
+ // Note: 注入 Taro Hooks 相关依赖
1031
+ this.apiEntryList = [
1032
+ /(@tarojs[\\/]plugin-platform-harmony-cpp|platform-harmony-cpp)[\\/]dist[\\/]runtime[\\/]apischunk[\\/]index\.js/,
1033
+ ];
1034
+ this.externalDeps.push(['@tarojs/shared', /^@tarojs[\\/]shared$/]);
1035
+ this.externalDeps.push(['react-reconciler', /^react-reconciler$/]);
1036
+ this.externalDeps.push(['react-reconciler/constants', /^react-reconciler[\\/]constants/]);
1037
+ this.externalDeps.push(['scheduler', /^scheduler$/]);
1038
+ this.externalDeps.push(['tslib', /^tslib$/]);
1039
+ }
1040
+ get harmonyPluginPath() {
1041
+ let packagePath = '';
1042
+ try {
1043
+ // Note: 本地或通过包引入
1044
+ packagePath = path.dirname(helper.resolveSync('@tarojs/plugin-platform-harmony-ets'));
1045
+ }
1046
+ catch (e) { } // eslint-disable-line no-empty
1047
+ if (!packagePath) {
1048
+ // Note: Link 引入
1049
+ packagePath = path.dirname(helper.resolveSync('@tarojs/plugin-platform-harmony-ets', { basedir: process.cwd() }));
1050
+ }
1051
+ return packagePath;
1052
+ }
1053
+ get harmonyCppPluginPath() {
1054
+ let packagePath = '';
1055
+ try {
1056
+ // Note: 本地或通过包引入
1057
+ packagePath = path.dirname(helper.resolveSync(PACKAGE_NAME));
1058
+ }
1059
+ catch (e) { } // eslint-disable-line no-empty
1060
+ if (!packagePath) {
1061
+ try {
1062
+ // Note: Link 引入
1063
+ packagePath = path.dirname(helper.resolveSync(PACKAGE_NAME, { basedir: process.cwd() }));
1064
+ }
1065
+ catch (e) { } // eslint-disable-line no-empty
1066
+ }
1067
+ if (!packagePath) {
1068
+ // Note: 本地 build-library 时,可能会找不到自己,此时使用 process.cwd() 作为 fallback
1069
+ packagePath = process.cwd();
1070
+ }
1071
+ return packagePath;
1072
+ }
1073
+ get apiLibrary() {
1074
+ return path.resolve(this.harmonyCppPluginPath, 'dist', './runtime/apischunk');
1075
+ }
1076
+ get componentLibrary() {
1077
+ return path.join(this.harmonyCppPluginPath, 'dist', './runtime/components');
1078
+ }
1079
+ get runtimeLibrary() {
1080
+ return path.join(this.harmonyCppPluginPath, 'dist', './runtime/runtime-cpp');
1081
+ }
1082
+ get runtimeFrameworkLibrary() {
1083
+ return path.join(this.harmonyCppPluginPath, 'dist', `./runtime/framework`);
1084
+ }
1085
+ get runtimeFrameworkReconciler() {
1086
+ return path.join(this.harmonyCppPluginPath, 'dist', `./runtime/framework-reconciler`);
1087
+ }
1088
+ modifyPageConfig() {
1089
+ const that = this;
1090
+ that.ctx.modifyViteConfig?.(opt => {
1091
+ opt.viteConfig.plugins.push(appPlugin.call(this, opt), pagePlugin.call(this, opt), renderPlugin.call(this, opt), resourcePlugin.call(this, opt), stylePlugin.call(this, opt), injectEnv.call(this, opt));
1092
+ });
1093
+ }
1094
+ // Note: 更新 oh-package 中项目依赖声明
1095
+ updateModulePackage(outputRoot, ohPackage = {}, ohpm) {
1096
+ const packageJsonFile = path.join(outputRoot, `${this.useJSON5 !== false ? 'oh-package.json5' : 'package.json'}`);
1097
+ const isExists = helper.fs.pathExistsSync(packageJsonFile);
1098
+ if (!isExists)
1099
+ return;
1100
+ const pkg = helper.recursiveMerge(harmony.readJsonSync(packageJsonFile), ohPackage);
1101
+ pkg.types = './src/main/ets/npm/@tarojs/taro/index.d.ts';
1102
+ helper.fs.writeJsonSync(packageJsonFile, pkg, { spaces: 2 });
1103
+ let ohpmPath = ohpm;
1104
+ let localOhpmPath = '';
1105
+ try {
1106
+ localOhpmPath = node_child_process.execSync(`${process?.platform === 'win32' ? 'where' : 'which'} ohpm`).toString().replace(/\n/, '');
1107
+ }
1108
+ catch (_) {
1109
+ localOhpmPath = '';
1110
+ }
1111
+ ohpmPath = ohpm || localOhpmPath || '~/Library/Huawei/ohpm/bin/ohpm';
1112
+ try {
1113
+ console.log(`开始 ${helper.chalk.yellow('ohpm install')} 脚本执行...\n`); // eslint-disable-line no-console
1114
+ node_child_process.execSync(`${ohpmPath} install`, { cwd: outputRoot, stdio: 'inherit' });
1115
+ console.log(`执行 ${helper.chalk.yellow('ohpm install')} 脚本成功。\n`); // eslint-disable-line no-console
1116
+ }
1117
+ catch (e) {
1118
+ console.error(`自动安装依赖失败,请手动执行 ${helper.chalk.yellow('ohpm install')} 或在 DevEco Studio 中打开 oh-package.json5 并点击 ${helper.chalk.yellow('Sync Now')} 按钮`);
1119
+ }
1120
+ if (pkg.main) {
1121
+ const mainPath = path.join(outputRoot, pkg.main);
1122
+ helper.fs.writeFileSync(mainPath, `export * from './src/main/ets/${NPM_DIR}/@tarojs/taro'`);
1123
+ }
1124
+ }
1125
+ }
1126
+
1127
+ /* eslint-disable no-console */
1128
+ const argProjectPath = getProcessArg('lib');
1129
+ const argHapName = getProcessArg('hap');
1130
+ const staticDirname = 'static';
1131
+ let harName = `${PKG_NAME}-${PKG_VERSION}.har`;
1132
+ if (!helper.fs.existsSync(path.join(__dirname, '..', staticDirname, harName))) {
1133
+ harName = require('fast-glob').sync('**/*.har', { cwd: path.join(__dirname, '..', staticDirname) })[0] || '';
1134
+ }
1135
+ var index = (ctx, options = {}) => {
1136
+ options.useChoreLibrary = options.useChoreLibrary ?? 'local';
1137
+ // 合并 harmony 编译配置到 opts
1138
+ ctx.modifyRunnerOpts(({ opts }) => {
1139
+ if (opts.platform !== PLATFORM_NAME)
1140
+ return;
1141
+ opts.ohPackage ||= {};
1142
+ opts.ohPackage.dependencies ||= {};
1143
+ if (options.useChoreLibrary) {
1144
+ opts.chorePackagePrefix ||= `${PKG_NAME}/src/main/ets/${helper.NPM_DIR}`;
1145
+ if (options.useChoreLibrary === 'local') {
1146
+ if (!harName) {
1147
+ console.warn(helper.chalk.yellow('未找到 .har 文件。'));
1148
+ }
1149
+ opts.ohPackage.dependencies[PKG_NAME] ||= `file:../static/${harName}`;
1150
+ }
1151
+ else if (options.useChoreLibrary === 'remote') {
1152
+ opts.ohPackage.dependencies[PKG_NAME] ||= `^${PKG_VERSION}`;
1153
+ }
1154
+ else {
1155
+ opts.ohPackage.dependencies[PKG_NAME] ||= options.useChoreLibrary;
1156
+ }
1157
+ PROJECT_DEPENDENCIES_NAME.forEach(key => {
1158
+ opts.ohPackage.dependencies[key] ||= PKG_DEPENDENCIES[key];
1159
+ });
1160
+ }
1161
+ else {
1162
+ Object.keys(PKG_DEPENDENCIES).forEach(key => {
1163
+ opts.ohPackage.dependencies[key] ||= PKG_DEPENDENCIES[key];
1164
+ });
1165
+ opts.ohPackage.dependencies[CPP_LIBRARY_NAME] = CPP_LIBRARY_PATH;
1166
+ }
1167
+ const harmonyConfig = ctx.ctx.initialConfig.harmony;
1168
+ assertHarmonyConfig(ctx, harmonyConfig);
1169
+ const terserOptions = harmonyConfig?.terser || ctx.initialConfig.terser || { config: constants$1.DEFAULT_TERSER_OPTIONS };
1170
+ terserOptions.config ||= {};
1171
+ terserOptions.config.output ||= {};
1172
+ terserOptions.config.output.comments ||= /^!/; // Note: 避免删除第一行注释影响 rawfile 代码缓存
1173
+ harmonyConfig.name ||= 'default';
1174
+ harmonyConfig.hapName ||= argHapName || 'entry';
1175
+ const { projectPath, hapName } = harmonyConfig;
1176
+ opts.outputRoot = path.join(argProjectPath || projectPath, hapName, 'src/main', 'ets');
1177
+ opts.harmony = harmonyConfig;
1178
+ ctx.paths.outputPath = opts.outputRoot;
1179
+ });
1180
+ ctx.registerPlatform({
1181
+ name: PLATFORM_NAME,
1182
+ useConfigName: options.useConfigName || 'harmony',
1183
+ async fn({ config }) {
1184
+ const program = new Harmony(ctx, config, options);
1185
+ await program.start();
1186
+ const { projectPath, hapName = 'entry', outputRoot } = config;
1187
+ if (!options.useChoreLibrary) {
1188
+ if (hapName !== 'entry') { // Note: 如果是 entry 不需要重写 BuildProfile 路径
1189
+ fixBuildProfile(outputRoot, path.join(outputRoot, '../../..'));
1190
+ }
1191
+ const buildProfilePath = path.join(projectPath, hapName, `build-profile.${program.useJSON5 !== false ? 'json5' : 'json'}`);
1192
+ updateBuildProfile(buildProfilePath, hapName);
1193
+ const C_API_TXT = helper.chalk.yellow('C-API');
1194
+ try {
1195
+ const cppOutPath = path.join(projectPath, hapName, 'src/main', 'cpp');
1196
+ if (!helper.fs.existsSync(cppOutPath)) {
1197
+ console.log(`开始拉取 ${C_API_TXT} 模块...`);
1198
+ node_child_process.execSync(`git clone https://github.com/NervJS/taro-harmony-capi-library.git ${cppOutPath}`, {
1199
+ cwd: path.resolve(__dirname, '..', '..', '..'),
1200
+ stdio: 'inherit',
1201
+ env: process.env,
1202
+ });
1203
+ }
1204
+ }
1205
+ catch (error) {
1206
+ console.log(`${C_API_TXT} 获取失败...`); // eslint-disable-line no-console
1207
+ }
1208
+ }
1209
+ else if (options.useChoreLibrary === 'local' && harName) {
1210
+ const harPath = path.join(argProjectPath || projectPath, staticDirname, harName);
1211
+ const harDir = path.dirname(harPath);
1212
+ helper.fs.ensureDirSync(harDir);
1213
+ helper.fs.emptyDirSync(harDir);
1214
+ helper.fs.copyFileSync(path.join(program.harmonyCppPluginPath, staticDirname, harName), harPath);
1215
+ }
1216
+ }
1217
+ });
1218
+ };
1219
+ function assertHarmonyConfig(ctx, config) {
1220
+ const NOTE_INVALID = helper.chalk.red('[✗] ');
1221
+ const errorChalk = helper.chalk.hex('#f00');
1222
+ const lineChalk = helper.chalk.hex('#fff');
1223
+ function throwError(err) {
1224
+ console.log(errorChalk(`Taro 配置有误,请检查! (${ctx.paths.configPath})`));
1225
+ console.log(` ${NOTE_INVALID}${lineChalk(err)}`);
1226
+ process.exit(0);
1227
+ }
1228
+ if (typeof config !== 'object' || !config) {
1229
+ throwError('请设置 harmony 编译配置');
1230
+ }
1231
+ if (!config.projectPath) {
1232
+ throwError('请设置 harmony.projectPath');
1233
+ }
1234
+ }
1235
+
1236
+ exports.default = index;