vite-plugin-taro 0.3.1 → 0.4.0

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 (260) hide show
  1. package/README.en.md +44 -0
  2. package/README.md +22 -497
  3. package/client.d.ts +9 -0
  4. package/dist/node/plugins/client/client-taro.d.ts +4 -0
  5. package/dist/node/plugins/client/client-taro.js +19 -0
  6. package/dist/node/plugins/client/constant.d.ts +4 -0
  7. package/dist/node/plugins/client/constant.js +4 -0
  8. package/dist/node/plugins/conditional/conditional-directives.d.ts +4 -0
  9. package/dist/node/plugins/{conditional-directives.js → conditional/conditional-directives.js} +27 -11
  10. package/dist/node/plugins/css/plugins.d.ts +4 -0
  11. package/dist/node/plugins/css/plugins.js +84 -0
  12. package/dist/node/plugins/h5/constant.d.ts +2 -0
  13. package/dist/node/plugins/h5/constant.js +3 -0
  14. package/dist/node/plugins/h5/plugins.d.ts +4 -0
  15. package/dist/node/plugins/h5/plugins.js +161 -0
  16. package/dist/node/plugins/h5/resolver/module-resolver.d.ts +14 -0
  17. package/dist/node/plugins/h5/resolver/module-resolver.js +19 -0
  18. package/dist/node/plugins/h5/transform-app.d.ts +10 -0
  19. package/dist/node/plugins/h5/transform-app.js +48 -0
  20. package/dist/node/plugins/wx/dev/dev-host.d.ts +15 -0
  21. package/dist/node/plugins/wx/dev/dev-host.js +352 -0
  22. package/dist/node/plugins/wx/dev/hmr-files.d.ts +28 -0
  23. package/dist/node/plugins/wx/dev/hmr-files.js +34 -0
  24. package/dist/node/plugins/wx/dev/patch-publisher.d.ts +22 -0
  25. package/dist/node/plugins/wx/dev/patch-publisher.js +40 -0
  26. package/dist/node/plugins/wx/dev/plugin.d.ts +7 -0
  27. package/dist/node/plugins/wx/dev/plugin.js +73 -0
  28. package/dist/node/plugins/wx/dev/react-refresh.d.ts +20 -0
  29. package/dist/node/plugins/wx/dev/react-refresh.js +198 -0
  30. package/dist/node/plugins/wx/module.d.ts +45 -0
  31. package/dist/node/plugins/wx/module.js +66 -0
  32. package/dist/node/plugins/wx/native/compile-native-component-interface.d.ts +21 -0
  33. package/dist/node/plugins/wx/native/compile-native-component-interface.js +29 -0
  34. package/dist/node/plugins/wx/native/create-native-component-output.d.ts +15 -0
  35. package/dist/node/plugins/wx/native/create-native-component-output.js +39 -0
  36. package/dist/node/plugins/wx/native/native-component-assets.d.ts +26 -0
  37. package/dist/node/plugins/wx/native/native-component-assets.js +76 -0
  38. package/dist/node/plugins/wx/native/native-component-interface.d.ts +12 -0
  39. package/dist/node/plugins/wx/native/native-component-interface.js +201 -0
  40. package/dist/node/plugins/wx/output/files.d.ts +12 -0
  41. package/dist/node/plugins/wx/output/files.js +12 -0
  42. package/dist/node/plugins/wx/output/json.d.ts +14 -0
  43. package/dist/node/plugins/wx/output/json.js +52 -0
  44. package/dist/node/plugins/wx/output/relative-root.d.ts +2 -0
  45. package/dist/node/plugins/wx/output/relative-root.js +6 -0
  46. package/dist/node/plugins/wx/output/templates.d.ts +7 -0
  47. package/dist/node/plugins/wx/output/templates.js +100 -0
  48. package/dist/node/plugins/wx/placement/placer.d.ts +78 -0
  49. package/dist/node/plugins/wx/placement/placer.js +145 -0
  50. package/dist/node/plugins/wx/placement/plan.d.ts +46 -0
  51. package/dist/node/plugins/wx/placement/plan.js +210 -0
  52. package/dist/node/plugins/wx/plugins.d.ts +4 -0
  53. package/dist/node/plugins/wx/plugins.js +137 -0
  54. package/dist/node/plugins/wx/render/capsule-wrapper.d.ts +3 -0
  55. package/dist/node/plugins/wx/render/capsule-wrapper.js +64 -0
  56. package/dist/node/plugins/wx/render/capsule.d.ts +4 -0
  57. package/dist/node/plugins/wx/render/capsule.js +13 -0
  58. package/dist/node/plugins/wx/render/native.d.ts +9 -0
  59. package/dist/node/plugins/wx/render/native.js +45 -0
  60. package/dist/node/plugins/wx/render/transport.d.ts +17 -0
  61. package/dist/node/plugins/wx/render/transport.js +94 -0
  62. package/dist/node/plugins/wx/resolve/resolver.d.ts +7 -0
  63. package/dist/node/plugins/wx/resolve/resolver.js +86 -0
  64. package/dist/node/plugins/wx/resolve/specialize-bootstrap.d.ts +9 -0
  65. package/dist/node/plugins/wx/resolve/specialize-bootstrap.js +9 -0
  66. package/dist/node/plugins/wx/resolve/specialize-page-capsule.d.ts +9 -0
  67. package/dist/node/plugins/wx/resolve/specialize-page-capsule.js +11 -0
  68. package/dist/node/utils/constant.d.ts +1 -0
  69. package/dist/node/utils/constant.js +1 -0
  70. package/dist/node/utils/memoize.d.ts +122 -0
  71. package/dist/node/utils/memoize.js +86 -0
  72. package/dist/node/utils/modules.d.ts +20 -24
  73. package/dist/node/utils/modules.js +21 -34
  74. package/dist/node/utils/once.d.ts +10 -0
  75. package/dist/node/utils/once.js +20 -0
  76. package/dist/node/utils/packages.d.ts +1 -0
  77. package/dist/node/utils/packages.js +1 -1
  78. package/dist/node/utils/project-config.d.ts +3 -0
  79. package/dist/node/utils/project-config.js +8 -0
  80. package/dist/node/utils/serialized-task-queue.d.ts +9 -0
  81. package/dist/node/utils/serialized-task-queue.js +17 -0
  82. package/dist/node/utils/transform.d.ts +11 -0
  83. package/dist/node/utils/transform.js +58 -0
  84. package/dist/node/vite-plugin.d.ts +1 -1
  85. package/dist/node/vite-plugin.js +11 -27
  86. package/dist/options.d.ts +3 -4
  87. package/dist/runtime/{taro → client/taro}/api.d.ts +0 -1
  88. package/dist/runtime/client/taro/api.js +9 -0
  89. package/dist/runtime/client/taro/component.d.ts +1 -0
  90. package/dist/runtime/client/taro/component.js +1 -0
  91. package/dist/runtime/client/taro/define-native-component.d.ts +7 -0
  92. package/dist/runtime/client/taro/define-native-component.js +4 -0
  93. package/dist/runtime/h5/app.d.ts +2 -0
  94. package/dist/runtime/h5/app.js +15 -0
  95. package/dist/runtime/h5/taro-runtime.d.ts +1 -1
  96. package/dist/runtime/h5/taro-runtime.js +1 -4
  97. package/dist/runtime/wx/amphibious/bootstrap.d.ts +4 -0
  98. package/dist/runtime/wx/amphibious/bootstrap.js +16 -0
  99. package/dist/runtime/wx/amphibious/transport.d.ts +2 -0
  100. package/dist/runtime/wx/amphibious/transport.js +4 -0
  101. package/dist/runtime/wx/capsule/app.d.ts +2 -0
  102. package/dist/runtime/wx/capsule/app.js +7 -0
  103. package/dist/runtime/wx/capsule/component.d.ts +3 -0
  104. package/dist/runtime/wx/capsule/component.js +4 -0
  105. package/dist/runtime/wx/capsule/page.d.ts +3 -0
  106. package/dist/runtime/wx/capsule/page.js +68 -0
  107. package/dist/runtime/wx/capsule/taro-runtime.d.ts +6 -0
  108. package/dist/runtime/wx/capsule/taro-runtime.js +6 -0
  109. package/dist/runtime/wx/dev/dev-runtime.d.ts +1 -0
  110. package/dist/runtime/wx/dev/dev-runtime.js +246 -0
  111. package/dist/runtime/wx/native/app.d.ts +1 -0
  112. package/dist/runtime/wx/native/app.js +3 -0
  113. package/dist/runtime/wx/native/component.d.ts +1 -0
  114. package/dist/runtime/wx/native/component.js +3 -0
  115. package/dist/runtime/wx/native/page.d.ts +1 -0
  116. package/dist/runtime/wx/native/page.js +4 -0
  117. package/dist/runtime/wx/systemjs/system-core.d.ts +4 -0
  118. package/dist/runtime/wx/systemjs/system-core.js +331 -0
  119. package/package.json +21 -13
  120. package/src/node/plugins/client/client-taro.ts +23 -0
  121. package/src/node/plugins/client/constant.ts +5 -0
  122. package/src/node/plugins/{conditional-directives.ts → conditional/conditional-directives.ts} +33 -13
  123. package/src/node/plugins/css/plugins.ts +96 -0
  124. package/src/node/plugins/h5/constant.ts +4 -0
  125. package/src/node/plugins/h5/plugins.ts +197 -0
  126. package/src/node/plugins/h5/resolver/module-resolver.ts +32 -0
  127. package/src/node/plugins/h5/transform-app.ts +90 -0
  128. package/src/node/plugins/wx/dev/dev-host.ts +448 -0
  129. package/src/node/plugins/wx/dev/hmr-files.ts +55 -0
  130. package/src/node/plugins/wx/dev/patch-publisher.ts +49 -0
  131. package/src/node/plugins/wx/dev/plugin.ts +82 -0
  132. package/src/node/plugins/wx/dev/react-refresh.ts +227 -0
  133. package/src/node/plugins/wx/module.ts +97 -0
  134. package/src/node/plugins/wx/native/compile-native-component-interface.ts +47 -0
  135. package/src/node/plugins/wx/native/create-native-component-output.ts +57 -0
  136. package/src/node/plugins/wx/native/native-component-assets.ts +114 -0
  137. package/src/node/plugins/wx/native/native-component-interface.ts +265 -0
  138. package/src/node/plugins/wx/output/files.ts +27 -0
  139. package/src/node/plugins/wx/output/json.ts +79 -0
  140. package/src/node/plugins/wx/output/relative-root.ts +7 -0
  141. package/src/node/plugins/wx/output/templates.ts +141 -0
  142. package/src/node/plugins/wx/placement/placer.ts +172 -0
  143. package/src/node/plugins/wx/placement/plan.ts +306 -0
  144. package/src/node/plugins/wx/plugins.ts +165 -0
  145. package/src/node/plugins/wx/render/capsule-wrapper.ts +86 -0
  146. package/src/node/plugins/wx/render/capsule.ts +21 -0
  147. package/src/node/plugins/wx/render/native.ts +84 -0
  148. package/src/node/plugins/wx/render/transport.ts +157 -0
  149. package/src/node/plugins/wx/resolve/resolver.ts +125 -0
  150. package/src/node/plugins/wx/resolve/specialize-bootstrap.ts +27 -0
  151. package/src/node/plugins/wx/resolve/specialize-page-capsule.ts +29 -0
  152. package/src/node/utils/constant.ts +1 -0
  153. package/src/node/utils/memoize.ts +149 -0
  154. package/src/node/utils/modules.ts +36 -38
  155. package/src/node/utils/once.ts +21 -0
  156. package/src/node/utils/packages.ts +1 -1
  157. package/src/node/utils/project-config.ts +10 -0
  158. package/src/node/utils/serialized-task-queue.ts +20 -0
  159. package/src/node/utils/transform.ts +82 -0
  160. package/src/node/vite-plugin.ts +12 -33
  161. package/src/options.ts +3 -4
  162. package/src/runtime/client/taro/api.ts +11 -0
  163. package/src/runtime/client/taro/component.ts +1 -0
  164. package/src/runtime/client/taro/define-native-component.ts +15 -0
  165. package/src/runtime/h5/app.ts +25 -0
  166. package/src/runtime/h5/taro-runtime.ts +1 -4
  167. package/src/runtime/wx/amphibious/bootstrap.ts +22 -0
  168. package/src/runtime/wx/amphibious/transport.ts +10 -0
  169. package/src/runtime/wx/capsule/app.ts +9 -0
  170. package/src/runtime/wx/capsule/component.ts +6 -0
  171. package/src/runtime/wx/capsule/page.ts +96 -0
  172. package/src/runtime/wx/capsule/taro-runtime.ts +14 -0
  173. package/src/runtime/wx/dev/dev-runtime.ts +317 -0
  174. package/src/runtime/wx/native/app.ts +4 -0
  175. package/src/runtime/wx/native/component.ts +4 -0
  176. package/src/runtime/wx/native/page.ts +6 -0
  177. package/src/runtime/wx/systemjs/LICENSE +10 -0
  178. package/src/runtime/wx/systemjs/system-core.js +370 -0
  179. package/src/runtime/wx/systemjs/system.d.ts +55 -0
  180. package/src/runtime/wx/wechat.d.ts +52 -0
  181. package/README.zh.md +0 -521
  182. package/dist/node/build-context.d.ts +0 -25
  183. package/dist/node/build-context.js +0 -48
  184. package/dist/node/css/css-pipeline.d.ts +0 -21
  185. package/dist/node/css/css-pipeline.js +0 -129
  186. package/dist/node/plugins/conditional-directives.d.ts +0 -3
  187. package/dist/node/plugins/taro-runtime.d.ts +0 -5
  188. package/dist/node/plugins/taro-runtime.js +0 -18
  189. package/dist/node/targets/h5/plugin.d.ts +0 -6
  190. package/dist/node/targets/h5/plugin.js +0 -117
  191. package/dist/node/targets/h5/virtual-modules.d.ts +0 -5
  192. package/dist/node/targets/h5/virtual-modules.js +0 -60
  193. package/dist/node/targets/wx/companion-assets.d.ts +0 -19
  194. package/dist/node/targets/wx/companion-assets.js +0 -129
  195. package/dist/node/targets/wx/dev-server/development-session.d.ts +0 -31
  196. package/dist/node/targets/wx/dev-server/development-session.js +0 -202
  197. package/dist/node/targets/wx/dev-server/full-build-scheduler.d.ts +0 -14
  198. package/dist/node/targets/wx/dev-server/full-build-scheduler.js +0 -60
  199. package/dist/node/targets/wx/dev-server/js-utils.d.ts +0 -5
  200. package/dist/node/targets/wx/dev-server/js-utils.js +0 -28
  201. package/dist/node/targets/wx/dev-server/output.d.ts +0 -19
  202. package/dist/node/targets/wx/dev-server/output.js +0 -44
  203. package/dist/node/targets/wx/dev-server/rolldown-runtime-source.d.ts +0 -8
  204. package/dist/node/targets/wx/dev-server/rolldown-runtime-source.js +0 -95
  205. package/dist/node/targets/wx/dev-server/update-server-state.d.ts +0 -65
  206. package/dist/node/targets/wx/dev-server/update-server-state.js +0 -116
  207. package/dist/node/targets/wx/dev-server/update-transport.d.ts +0 -28
  208. package/dist/node/targets/wx/dev-server/update-transport.js +0 -212
  209. package/dist/node/targets/wx/dev-server/vite-bundled-dev-adapter.d.ts +0 -44
  210. package/dist/node/targets/wx/dev-server/vite-bundled-dev-adapter.js +0 -145
  211. package/dist/node/targets/wx/development-files.d.ts +0 -8
  212. package/dist/node/targets/wx/development-files.js +0 -8
  213. package/dist/node/targets/wx/plugin.d.ts +0 -6
  214. package/dist/node/targets/wx/plugin.js +0 -143
  215. package/dist/node/targets/wx/react-refresh.d.ts +0 -4
  216. package/dist/node/targets/wx/react-refresh.js +0 -38
  217. package/dist/node/targets/wx/virtual-modules.d.ts +0 -16
  218. package/dist/node/targets/wx/virtual-modules.js +0 -120
  219. package/dist/node/utils/async.d.ts +0 -8
  220. package/dist/node/utils/async.js +0 -16
  221. package/dist/node/utils/filesystem.d.ts +0 -13
  222. package/dist/node/utils/filesystem.js +0 -43
  223. package/dist/runtime/taro/api.js +0 -11
  224. package/dist/runtime/taro/components.d.ts +0 -2
  225. package/dist/runtime/taro/components.js +0 -2
  226. package/dist/runtime/wx/page-update.d.ts +0 -6
  227. package/dist/runtime/wx/page-update.js +0 -157
  228. package/dist/runtime/wx/taro-runtime.d.ts +0 -5
  229. package/dist/runtime/wx/taro-runtime.js +0 -6
  230. package/dist/runtime/wx/update-client-state.d.ts +0 -68
  231. package/dist/runtime/wx/update-client-state.js +0 -84
  232. package/dist/runtime/wx/update-client.d.ts +0 -1
  233. package/dist/runtime/wx/update-client.js +0 -170
  234. package/src/node/build-context.ts +0 -63
  235. package/src/node/css/css-pipeline.ts +0 -147
  236. package/src/node/plugins/taro-runtime.ts +0 -22
  237. package/src/node/targets/h5/plugin.ts +0 -135
  238. package/src/node/targets/h5/virtual-modules.ts +0 -71
  239. package/src/node/targets/wx/companion-assets.ts +0 -170
  240. package/src/node/targets/wx/dev-server/development-session.ts +0 -253
  241. package/src/node/targets/wx/dev-server/full-build-scheduler.ts +0 -62
  242. package/src/node/targets/wx/dev-server/js-utils.ts +0 -33
  243. package/src/node/targets/wx/dev-server/output.ts +0 -56
  244. package/src/node/targets/wx/dev-server/rolldown-runtime-source.ts +0 -95
  245. package/src/node/targets/wx/dev-server/update-server-state.ts +0 -183
  246. package/src/node/targets/wx/dev-server/update-transport.ts +0 -261
  247. package/src/node/targets/wx/dev-server/vite-bundled-dev-adapter.ts +0 -203
  248. package/src/node/targets/wx/development-files.ts +0 -11
  249. package/src/node/targets/wx/plugin.ts +0 -163
  250. package/src/node/targets/wx/react-refresh.ts +0 -51
  251. package/src/node/targets/wx/virtual-modules.ts +0 -152
  252. package/src/node/utils/async.ts +0 -19
  253. package/src/node/utils/filesystem.ts +0 -45
  254. package/src/runtime/taro/api.ts +0 -13
  255. package/src/runtime/taro/components.ts +0 -2
  256. package/src/runtime/wx/page-update.ts +0 -230
  257. package/src/runtime/wx/react-refresh.d.ts +0 -20
  258. package/src/runtime/wx/taro-runtime.ts +0 -7
  259. package/src/runtime/wx/update-client-state.ts +0 -138
  260. package/src/runtime/wx/update-client.ts +0 -222
@@ -1,28 +0,0 @@
1
- import type { ViteDevServer } from 'vite';
2
- export declare class WxUpdateTransport {
3
- private readonly server;
4
- private readonly requestFullBuild;
5
- private readonly writeUpdateFile;
6
- private state;
7
- private readonly token;
8
- private readonly pendingPolls;
9
- private closed;
10
- constructor(server: ViteDevServer, requestFullBuild: () => void, writeUpdateFile: (buildId: string, source: string) => Promise<void>);
11
- get retainedDeltaCount(): number;
12
- get retainedDeltaBytes(): number;
13
- install(): void;
14
- close(): void;
15
- addDelta(code: string): void;
16
- createBuildId(): string;
17
- isCurrentBuild(buildId: string): boolean;
18
- commitFullBuild(buildId: string): void;
19
- /** Generates late-bound App metadata after Vite has selected its actual listening port. */
20
- createControlSource(buildId?: string): string;
21
- private readonly handleRequest;
22
- private executePollCommands;
23
- private holdPoll;
24
- private respondToAll;
25
- private finishPoll;
26
- private apply;
27
- private writeBatch;
28
- }
@@ -1,212 +0,0 @@
1
- /**
2
- * Adapts the pure server protocol to Vite HTTP middleware and literal update-file publication.
3
- * HTTP messages contain metadata only; executable JavaScript reaches DevTools through the injected file writer.
4
- */
5
- import { randomBytes } from 'node:crypto';
6
- import { createWxUpdateServerState, transitionWxUpdateServer } from './update-server-state.js';
7
- const endpointPath = '/__vite_plugin_taro_wx_update__';
8
- // Keep the host response below update-client.ts's 30-second wx.request timeout.
9
- const pollTimeout = 25_000;
10
- export class WxUpdateTransport {
11
- server;
12
- requestFullBuild;
13
- writeUpdateFile;
14
- state = createWxUpdateServerState(createId());
15
- token = createId();
16
- pendingPolls = new Map();
17
- closed = false;
18
- constructor(server, requestFullBuild, writeUpdateFile) {
19
- this.server = server;
20
- this.requestFullBuild = requestFullBuild;
21
- this.writeUpdateFile = writeUpdateFile;
22
- }
23
- get retainedDeltaCount() {
24
- return this.state.hostVersion;
25
- }
26
- get retainedDeltaBytes() {
27
- return this.state.retainedDeltaBytes;
28
- }
29
- install() {
30
- this.server.middlewares.use(endpointPath, this.handleRequest);
31
- }
32
- close() {
33
- this.closed = true;
34
- this.respondToAll({ type: 'rebuilding' });
35
- }
36
- addDelta(code) {
37
- this.apply({ type: 'delta-added', code, bytes: Buffer.byteLength(code) });
38
- this.respondToAll({ type: 'changed' });
39
- }
40
- createBuildId() {
41
- return createId();
42
- }
43
- isCurrentBuild(buildId) {
44
- return this.state.buildId === buildId;
45
- }
46
- commitFullBuild(buildId) {
47
- this.apply({ type: 'full-build-committed', buildId });
48
- this.respondToAll({ type: 'rebuilding' });
49
- }
50
- /** Generates late-bound App metadata after Vite has selected its actual listening port. */
51
- createControlSource(buildId = this.state.buildId) {
52
- const address = this.server.httpServer?.address();
53
- const port = address && typeof address !== 'string' ? address.port : this.server.config.server.port;
54
- return `globalThis.__VITE_PLUGIN_TARO_WX_CONTROL__ = ${JSON.stringify({
55
- url: `http://localhost:${port}${endpointPath}`,
56
- token: this.token,
57
- buildId
58
- })};\n`;
59
- }
60
- handleRequest = async (request, response) => {
61
- if (this.closed || request.method !== 'POST') {
62
- respond(response, 404, { type: 'not-found' });
63
- return;
64
- }
65
- let body;
66
- try {
67
- body = JSON.parse(await readBody(request));
68
- }
69
- catch {
70
- respond(response, 400, { type: 'invalid-request' });
71
- return;
72
- }
73
- if (body.token !== this.token || !isClientReport(body)) {
74
- respond(response, 403, { type: 'forbidden' });
75
- return;
76
- }
77
- if (body.action === 'rebuild') {
78
- this.requestFullBuild();
79
- respond(response, 202, { type: 'rebuilding' });
80
- return;
81
- }
82
- if (body.action === 'register') {
83
- const transition = this.apply({
84
- type: 'client-registered',
85
- buildId: body.buildId,
86
- sessionId: body.sessionId,
87
- version: body.version
88
- });
89
- if (transition.some((command) => command.type === 'request-full-build'))
90
- this.requestFullBuild();
91
- respond(response, 200, { type: 'registered' });
92
- return;
93
- }
94
- if (body.action !== 'poll') {
95
- respond(response, 400, { type: 'invalid-request' });
96
- return;
97
- }
98
- const commands = this.apply({
99
- type: 'client-reported',
100
- buildId: body.buildId,
101
- sessionId: body.sessionId,
102
- version: body.version
103
- });
104
- await this.executePollCommands(body.sessionId, commands, response);
105
- };
106
- async executePollCommands(sessionId, commands, response) {
107
- const publish = commands.find((command) => command.type === 'publish-batch');
108
- if (publish?.type === 'publish-batch') {
109
- try {
110
- await this.writeBatch(publish.batch);
111
- respond(response, 200, { type: 'batch-published', targetVersion: publish.batch.targetVersion });
112
- }
113
- catch {
114
- this.apply({
115
- type: 'batch-publish-failed',
116
- sessionId: publish.batch.sessionId,
117
- targetVersion: publish.batch.targetVersion
118
- });
119
- respond(response, 500, { type: 'publish-failed' });
120
- }
121
- return;
122
- }
123
- if (commands.some((command) => command.type === 'request-full-build')) {
124
- this.requestFullBuild();
125
- respond(response, 202, { type: 'rebuilding' });
126
- return;
127
- }
128
- if (commands.some((command) => command.type === 'ignore-client')) {
129
- respond(response, 409, { type: 'rebuilding' });
130
- return;
131
- }
132
- this.holdPoll(sessionId, response);
133
- }
134
- holdPoll(sessionId, response) {
135
- const previous = this.pendingPolls.get(sessionId);
136
- if (previous)
137
- this.finishPoll(sessionId, previous, { type: 'changed' });
138
- let pending;
139
- pending = {
140
- response,
141
- timeout: setTimeout(() => this.finishPoll(sessionId, pending, { type: 'idle' }), pollTimeout)
142
- };
143
- this.pendingPolls.set(sessionId, pending);
144
- response.on('close', () => this.finishPoll(sessionId, pending));
145
- }
146
- respondToAll(value) {
147
- for (const [sessionId, pending] of this.pendingPolls)
148
- this.finishPoll(sessionId, pending, value);
149
- }
150
- finishPoll(sessionId, pending, value) {
151
- if (this.pendingPolls.get(sessionId) !== pending)
152
- return;
153
- clearTimeout(pending.timeout);
154
- this.pendingPolls.delete(sessionId);
155
- if (value)
156
- respond(pending.response, 200, value);
157
- }
158
- apply(event) {
159
- const transition = transitionWxUpdateServer(this.state, event);
160
- this.state = transition.state;
161
- return transition.commands;
162
- }
163
- async writeBatch(batch) {
164
- await this.writeUpdateFile(batch.buildId, renderBatch(batch, createId()));
165
- }
166
- }
167
- /** Renders executable code for update.js; this source is never included in an HTTP response. */
168
- function renderBatch(batch, nonce) {
169
- return `// ${nonce}\nglobalThis.__VITE_PLUGIN_TARO_WX_UPDATE_CLIENT__.receiveBatch(${JSON.stringify({
170
- buildId: batch.buildId,
171
- fromVersion: batch.fromVersion,
172
- targetVersion: batch.targetVersion
173
- })}, () => {
174
- ${indent(batch.deltas.map((delta) => delta.code).join('\n'), 4)}
175
- });\n`;
176
- }
177
- function indent(value, spaces) {
178
- const prefix = ' '.repeat(spaces);
179
- return value
180
- .split('\n')
181
- .map((line) => `${prefix}${line}`)
182
- .join('\n');
183
- }
184
- function isClientReport(value) {
185
- return (typeof value.token === 'string' &&
186
- typeof value.action === 'string' &&
187
- typeof value.buildId === 'string' &&
188
- typeof value.sessionId === 'string' &&
189
- typeof value.version === 'number');
190
- }
191
- async function readBody(request) {
192
- const chunks = [];
193
- let size = 0;
194
- for await (const chunk of request) {
195
- const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
196
- size += buffer.length;
197
- if (size > 64 * 1024)
198
- throw new Error('WX update request body is too large.');
199
- chunks.push(buffer);
200
- }
201
- return Buffer.concat(chunks).toString('utf8');
202
- }
203
- function respond(response, status, body) {
204
- if (response.writableEnded)
205
- return;
206
- response.statusCode = status;
207
- response.setHeader('content-type', 'application/json');
208
- response.end(JSON.stringify(body));
209
- }
210
- function createId() {
211
- return randomBytes(16).toString('hex');
212
- }
@@ -1,44 +0,0 @@
1
- import type { ResolvedConfig, ViteDevServer } from 'vite';
2
- import type { WxOutputFile } from './output.ts';
3
- /** HMR boundary shape returned by Vite's private WX DevEngine integration. */
4
- type WxDevEngineBoundary = {
5
- boundary: string;
6
- acceptedVia: string;
7
- };
8
- /** Update result shape returned by Vite's private bundled-development engine. */
9
- export type WxDevEngineUpdate = {
10
- type: 'Noop';
11
- } | {
12
- type: 'FullReload';
13
- reason?: string;
14
- } | {
15
- type: 'Patch';
16
- code: string;
17
- filename: string;
18
- hmrBoundaries: WxDevEngineBoundary[];
19
- };
20
- type ViteBundledDevCallbacks = {
21
- onOutput(output: WxOutputFile[]): void;
22
- onPatch(files: string[], output: WxDevEngineUpdate): boolean;
23
- onError(message: string): void;
24
- waitForInitialBundle(): Promise<void>;
25
- };
26
- /** Isolates the private Vite bundled-development API used by the WX session. */
27
- export declare class ViteBundledDevAdapter {
28
- private readonly config;
29
- private readonly server;
30
- private readonly callbacks;
31
- private bundledDev;
32
- constructor(config: ResolvedConfig, server: ViteDevServer, callbacks: ViteBundledDevCallbacks);
33
- install(): void;
34
- registerBundleModules(output: WxOutputFile[]): number;
35
- registerPatchModules(code: string): void;
36
- private registerModules;
37
- rebuild(): Promise<void>;
38
- private installOptions;
39
- private installOutput;
40
- private installPatches;
41
- private installListener;
42
- private handlePayload;
43
- }
44
- export {};
@@ -1,145 +0,0 @@
1
- import path from 'node:path';
2
- import { wxPagePreloadFile, wxUpdateControlFile, wxUpdateFile } from '../development-files.js';
3
- import { wxRolldownRuntimeSource } from './rolldown-runtime-source.js';
4
- const clientId = 'vite-plugin-taro-wx';
5
- /** Isolates the private Vite bundled-development API used by the WX session. */
6
- export class ViteBundledDevAdapter {
7
- config;
8
- server;
9
- callbacks;
10
- bundledDev;
11
- constructor(config, server, callbacks) {
12
- this.config = config;
13
- this.server = server;
14
- this.callbacks = callbacks;
15
- }
16
- install() {
17
- const bundledDev = this.server.environments.client.bundledDev;
18
- if (!bundledDev)
19
- throw new Error('vite-plugin-taro requires Vite bundled development for WX development.');
20
- if (typeof bundledDev.getRolldownOptions !== 'function' ||
21
- typeof bundledDev.storeOutputFiles !== 'function' ||
22
- typeof bundledDev.handleHmrOutput !== 'function') {
23
- throw new Error('vite-plugin-taro does not support this Vite bundled-development API shape.');
24
- }
25
- this.bundledDev = bundledDev;
26
- this.installOptions(bundledDev);
27
- this.installOutput(bundledDev);
28
- this.installPatches(bundledDev);
29
- this.installListener(bundledDev);
30
- }
31
- registerBundleModules(output) {
32
- const moduleIds = new Set();
33
- for (const item of output) {
34
- if (item.type !== 'chunk')
35
- continue;
36
- for (const id of Object.keys(item.modules ?? {}))
37
- moduleIds.add(toStableModuleId(id, this.config.root));
38
- }
39
- this.registerModules([...moduleIds]);
40
- return moduleIds.size;
41
- }
42
- registerPatchModules(code) {
43
- const moduleIds = new Set();
44
- for (const match of code.matchAll(/create(?:Esm|Cjs)Initializer\("([^"]+)"/g))
45
- moduleIds.add(match[1]);
46
- this.registerModules([...moduleIds]);
47
- }
48
- registerModules(moduleIds) {
49
- if (moduleIds.length)
50
- this.bundledDev?._devEngine?.registerModules(clientId, moduleIds);
51
- }
52
- async rebuild() {
53
- const engine = this.bundledDev?._devEngine;
54
- if (!engine)
55
- return;
56
- engine.triggerFullBuild();
57
- await engine.ensureLatestBuildOutput();
58
- }
59
- installOptions(bundledDev) {
60
- const getRolldownOptions = bundledDev.getRolldownOptions.bind(bundledDev);
61
- bundledDev.getRolldownOptions = async () => {
62
- const options = await getRolldownOptions();
63
- if (!options.output)
64
- options.output = {};
65
- const output = getFirstOutput(options);
66
- const configuredOutput = this.config.build.rolldownOptions.output;
67
- const desiredOutput = Array.isArray(configuredOutput) ? configuredOutput[0] : configuredOutput;
68
- Object.assign(output, desiredOutput, {
69
- format: 'cjs',
70
- sourcemap: false,
71
- minify: false,
72
- banner: createWxDevelopmentBanner
73
- });
74
- options.experimental ??= {};
75
- options.experimental.devMode = {
76
- ...(typeof options.experimental.devMode === 'object' ? options.experimental.devMode : {}),
77
- lazy: false,
78
- // Rolldown compiles this source into runtime.js before any Taro/React module executes.
79
- implement: wxRolldownRuntimeSource
80
- };
81
- return options;
82
- };
83
- }
84
- installOutput(bundledDev) {
85
- const storeOutputFiles = bundledDev.storeOutputFiles.bind(bundledDev);
86
- bundledDev.storeOutputFiles = (output) => {
87
- storeOutputFiles(output);
88
- this.callbacks.onOutput(output);
89
- };
90
- }
91
- installPatches(bundledDev) {
92
- const handleHmrOutput = bundledDev.handleHmrOutput.bind(bundledDev);
93
- bundledDev.handleHmrOutput = (client, files, output, info) => {
94
- if (output.type === 'Noop')
95
- return;
96
- if (this.callbacks.onPatch(files, output))
97
- handleHmrOutput(client, files, output, info);
98
- };
99
- }
100
- installListener(bundledDev) {
101
- const listen = bundledDev.listen.bind(bundledDev);
102
- bundledDev.listen = async () => {
103
- await listen();
104
- bundledDev.clients.setupIfNeeded({ send: (payload) => this.handlePayload(payload) }, clientId);
105
- const engine = bundledDev._devEngine;
106
- if (!engine)
107
- throw new Error('vite-plugin-taro expected Vite to initialize the WX DevEngine.');
108
- await engine.ensureCurrentBuildFinish();
109
- if ((await engine.getBundleState()).lastBuildErrored) {
110
- throw new Error('The initial WX bundled-development build failed.');
111
- }
112
- await this.callbacks.waitForInitialBundle();
113
- };
114
- }
115
- handlePayload(payload) {
116
- if (typeof payload !== 'object' || payload === null)
117
- return;
118
- const candidate = payload;
119
- if (candidate.type === 'error' && typeof candidate.err?.message === 'string') {
120
- this.callbacks.onError(candidate.err.message);
121
- }
122
- }
123
- }
124
- function toStableModuleId(id, root) {
125
- const normalizedId = id.replace(/\\/g, '/');
126
- if (normalizedId.startsWith('\0') || !path.posix.isAbsolute(normalizedId))
127
- return normalizedId;
128
- return path.posix.relative(root.replace(/\\/g, '/'), normalizedId);
129
- }
130
- function getFirstOutput(options) {
131
- if (!Array.isArray(options.output))
132
- return options.output;
133
- const output = options.output[0] ?? {};
134
- options.output[0] = output;
135
- return output;
136
- }
137
- /** Adds native direct dependencies whose execution order cannot be represented through the Rolldown graph. */
138
- function createWxDevelopmentBanner(chunk) {
139
- if (chunk.fileName === 'app.js')
140
- return `require(${JSON.stringify(`./${wxUpdateControlFile}`)});`;
141
- if (!chunk.fileName.startsWith('pages/') || !chunk.fileName.endsWith('.js'))
142
- return '';
143
- const prefix = '../'.repeat(chunk.fileName.split('/').length - 1);
144
- return `require(${JSON.stringify(`${prefix}runtime.js`)});require(${JSON.stringify(`${prefix}${wxPagePreloadFile}`)});require(${JSON.stringify(`${prefix}${wxUpdateFile}`)});`;
145
- }
@@ -1,8 +0,0 @@
1
- /** Plugin-owned files added only to a WX development output. */
2
- export declare const wxDevelopmentDirectory = "vpt-hmr";
3
- /** App-only metadata containing the local transport URL, token, and build ID. */
4
- export declare const wxUpdateControlFile = "vpt-hmr/control.js";
5
- /** Stable page-component initialization required before replaying retained updates. */
6
- export declare const wxPagePreloadFile = "vpt-hmr/preload.js";
7
- /** The one mutable, literal JavaScript update dependency required by every page. */
8
- export declare const wxUpdateFile = "vpt-hmr/update.js";
@@ -1,8 +0,0 @@
1
- /** Plugin-owned files added only to a WX development output. */
2
- export const wxDevelopmentDirectory = 'vpt-hmr';
3
- /** App-only metadata containing the local transport URL, token, and build ID. */
4
- export const wxUpdateControlFile = `${wxDevelopmentDirectory}/control.js`;
5
- /** Stable page-component initialization required before replaying retained updates. */
6
- export const wxPagePreloadFile = `${wxDevelopmentDirectory}/preload.js`;
7
- /** The one mutable, literal JavaScript update dependency required by every page. */
8
- export const wxUpdateFile = `${wxDevelopmentDirectory}/update.js`;
@@ -1,6 +0,0 @@
1
- import type { PluginOption, UserConfig } from 'vite';
2
- import type { BuildContext } from '../../build-context.ts';
3
- /** Creates the plugins that own the complete WX build and development lifecycle. */
4
- export declare function createWxTargetPlugins(context: BuildContext): PluginOption[];
5
- /** Supplies the complete WX target configuration from the same target owner as its plugin. */
6
- export declare function createWxViteConfig(context: BuildContext): UserConfig;
@@ -1,143 +0,0 @@
1
- import path from 'node:path';
2
- import { normalizeModuleId, stripVirtualPrefix } from '../../utils/modules.js';
3
- import { packageRequire } from '../../utils/packages.js';
4
- import { emitWxCompanionAssets } from './companion-assets.js';
5
- import { WxDevelopmentSession } from './dev-server/development-session.js';
6
- import { transformWxReactRefreshModule } from './react-refresh.js';
7
- import { emitWxEntryChunks, isWxVirtualModuleId, loadWxVirtualModule, virtualWxAppId } from './virtual-modules.js';
8
- const taroWxComponentsPath = packageRequire.resolve('@tarojs/plugin-platform-weapp/dist/components-react');
9
- const vitePluginTaroSourcePath = normalizeModuleId(path.dirname(packageRequire.resolve('vite-plugin-taro')));
10
- const taroVersion = String(packageRequire('@tarojs/runtime/package.json').version);
11
- /** Creates the plugins that own the complete WX build and development lifecycle. */
12
- export function createWxTargetPlugins(context) {
13
- return [createWxTargetPlugin(context)];
14
- }
15
- function createWxTargetPlugin(context) {
16
- let developmentSession;
17
- return {
18
- name: 'vite-plugin-taro:wx',
19
- resolveId: {
20
- order: 'pre',
21
- handler(id) {
22
- return isWxVirtualModuleId(id) ? `\0${id}` : undefined;
23
- }
24
- },
25
- load: {
26
- order: 'post',
27
- handler(id) {
28
- const cleanId = stripVirtualPrefix(id);
29
- emitWxEntryChunks(this, context, cleanId);
30
- return loadWxVirtualModule(cleanId, context);
31
- }
32
- },
33
- transform: {
34
- order: 'post',
35
- async handler(code, id) {
36
- if (!context.development)
37
- return;
38
- const transformed = await transformWxReactRefreshModule(code, id, context.project.appComponentFile);
39
- return transformed === code ? undefined : transformed;
40
- }
41
- },
42
- generateBundle: {
43
- order: 'post',
44
- handler(_, bundle) {
45
- emitWxCompanionAssets(this, bundle, context);
46
- }
47
- },
48
- configureServer: {
49
- order: 'post',
50
- handler(server) {
51
- developmentSession = new WxDevelopmentSession(context, server);
52
- developmentSession.install();
53
- }
54
- },
55
- closeBundle() {
56
- return developmentSession?.close();
57
- }
58
- };
59
- }
60
- /** Supplies the complete WX target configuration from the same target owner as its plugin. */
61
- export function createWxViteConfig(context) {
62
- return {
63
- define: createWxTaroDefines(),
64
- experimental: context.development ? { bundledDev: true } : undefined,
65
- css: {
66
- lightningcss: {
67
- visitor: {
68
- // keep CSS3 style single colon :before, :after
69
- // while WeChat Mini Program does not support the double colons versions
70
- Selector(selector) {
71
- return selector.map((component) => {
72
- if (component.type === 'pseudo-element' &&
73
- (component.kind === 'before' || component.kind === 'after')) {
74
- return {
75
- type: 'pseudo-element',
76
- kind: 'custom',
77
- name: component.kind
78
- };
79
- }
80
- return component;
81
- });
82
- }
83
- }
84
- }
85
- },
86
- resolve: {
87
- alias: [{ find: /^@tarojs\/components$/, replacement: taroWxComponentsPath }]
88
- },
89
- build: {
90
- target: 'es2018',
91
- assetsInlineLimit: 1024,
92
- cssCodeSplit: false,
93
- cssMinify: context.development ? false : 'lightningcss',
94
- minify: !context.development,
95
- rolldownOptions: {
96
- input: { app: virtualWxAppId },
97
- experimental: {
98
- // remove vite virtual module \0 in comments, which causes WeChat DevTools failed to compile
99
- attachDebugInfo: 'none'
100
- },
101
- output: {
102
- format: 'cjs',
103
- entryFileNames: '[name].js',
104
- assetFileNames: 'assets/[name][extname]',
105
- chunkFileNames: ({ name }) => `${name === 'rolldown-runtime' ? 'runtime' : name}.js`,
106
- strictExecutionOrder: true,
107
- codeSplitting: {
108
- includeDependenciesRecursively: false,
109
- minSize: 0,
110
- groups: [
111
- { name: 'taro', test: isWxTaroChunkModule, priority: 100 },
112
- { name: 'vendors', test: isNodeModule, priority: 10 },
113
- { name: 'common', minShareCount: 2, minModuleSize: 1, priority: 1 }
114
- ]
115
- }
116
- }
117
- }
118
- }
119
- };
120
- }
121
- function createWxTaroDefines() {
122
- return {
123
- 'process.env.FRAMEWORK': JSON.stringify('react'),
124
- 'process.env.SUPPORT_TARO_POLYFILL': JSON.stringify('disabled'),
125
- 'process.env.TARO_ENV': JSON.stringify('weapp'),
126
- 'process.env.TARO_PLATFORM': JSON.stringify('mini'),
127
- 'process.env.TARO_VERSION': JSON.stringify(taroVersion),
128
- ENABLE_ADJACENT_HTML: 'false',
129
- ENABLE_CLONE_NODE: 'false',
130
- ENABLE_CONTAINS: 'false',
131
- ENABLE_INNER_HTML: 'false',
132
- ENABLE_MUTATION_OBSERVER: 'false',
133
- ENABLE_SIZE_APIS: 'false',
134
- ENABLE_TEMPLATE_CONTENT: 'false'
135
- };
136
- }
137
- function isWxTaroChunkModule(id) {
138
- const normalizedId = normalizeModuleId(id);
139
- return normalizedId.includes('/node_modules/@tarojs/') || normalizedId.startsWith(`${vitePluginTaroSourcePath}/`);
140
- }
141
- function isNodeModule(id) {
142
- return normalizeModuleId(id).includes('/node_modules/');
143
- }
@@ -1,4 +0,0 @@
1
- /** Rewrites Vite's browser-oriented Refresh output for the WX App Service global environment. */
2
- export declare function transformWxReactRefreshModule(code: string, id: string, appComponentFile: string): Promise<string>;
3
- /** Creates the virtual preamble that installs React Refresh before the generated WX App entry executes. */
4
- export declare function createWxReactRefreshPreambleSource(): string;
@@ -1,38 +0,0 @@
1
- import { transformWithOxc } from 'vite';
2
- import { normalizeModuleId } from '../../utils/modules.js';
3
- /** Rewrites Vite's browser-oriented Refresh output for the WX App Service global environment. */
4
- export async function transformWxReactRefreshModule(code, id, appComponentFile) {
5
- const appFile = normalizeModuleId(appComponentFile);
6
- const instrumented = normalizeModuleId(id) === appFile ? await instrumentWxAppComponent(code, appFile) : code;
7
- return instrumented
8
- .replaceAll('window.$Refresh', 'globalThis.$Refresh')
9
- .replaceAll('window.__registerBeforePerformReactRefresh', 'globalThis.__registerBeforePerformReactRefresh')
10
- .replaceAll('window.__getReactRefreshIgnoredExports', 'globalThis.__getReactRefreshIgnoredExports')
11
- .replace('export function register(type, id) {', 'export function register(type, id) {\n if (globalThis.__VITE_PLUGIN_TARO_WX_PAGE_UPDATE__?.blockRefreshRegistration) return')
12
- .replace('\n performReactRefresh()\n', '\n globalThis.__VITE_PLUGIN_TARO_WX_PAGE_UPDATE__?.afterRefresh?.(performReactRefresh())\n');
13
- }
14
- /** Creates the virtual preamble that installs React Refresh before the generated WX App entry executes. */
15
- export function createWxReactRefreshPreambleSource() {
16
- return `import RefreshRuntime from '/@react-refresh'
17
- RefreshRuntime.injectIntoGlobalHook(globalThis)
18
- globalThis.$RefreshReg$ = () => {}
19
- globalThis.$RefreshSig$ = () => (type) => type
20
- `;
21
- }
22
- /** Adds Refresh registration to JSX-free App modules that Vite's normal JSX transform would otherwise skip. */
23
- async function instrumentWxAppComponent(code, appFile) {
24
- const transformed = await transformWithOxc(code, appFile, {
25
- lang: 'js',
26
- sourcemap: false,
27
- jsx: { refresh: true }
28
- });
29
- return `import {
30
- createSignatureFunctionForTransform as __wxCreateRefreshSignature,
31
- register as __wxRegisterRefreshType
32
- } from '/@react-refresh'
33
- const $RefreshReg$ = (type, id) => __wxRegisterRefreshType(type, ${JSON.stringify(`${appFile} `)} + id)
34
- const $RefreshSig$ = __wxCreateRefreshSignature
35
- ${transformed.code}
36
- if (import.meta.hot) import.meta.hot.accept()
37
- `;
38
- }
@@ -1,16 +0,0 @@
1
- import type { BuildContext } from '../../build-context.ts';
2
- /** Generated native App entry. */
3
- export declare const virtualWxAppId = "virtual:vite-plugin-taro/wx/app";
4
- type WxChunkEmitter = {
5
- emitFile(chunk: {
6
- type: 'chunk';
7
- id: string;
8
- fileName: string;
9
- implicitlyLoadedAfterOneOf: string[];
10
- }): string;
11
- };
12
- export declare function isWxVirtualModuleId(id: string): boolean;
13
- export declare function loadWxVirtualModule(id: string, context: BuildContext): string | undefined;
14
- /** Registers every configured page and the shared recursive component as eager WX entry chunks. */
15
- export declare function emitWxEntryChunks(emitter: WxChunkEmitter, context: BuildContext, id: string): void;
16
- export {};