@tarojs/plugin-platform-harmony-cpp 4.0.8-beta.3

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