vite-plugin-taro 0.5.4 → 0.5.6

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 (33) hide show
  1. package/README.en.md +1 -1
  2. package/README.md +1 -1
  3. package/dist/node/plugins/h5/create-stencil-client-adapter.d.ts +10 -13
  4. package/dist/node/plugins/h5/create-stencil-client-adapter.js +63 -51
  5. package/dist/node/plugins/h5/plugins.d.ts +10 -0
  6. package/dist/node/plugins/h5/plugins.js +39 -11
  7. package/dist/node/plugins/wx/dev/dev-host.js +103 -216
  8. package/dist/node/plugins/wx/dev/hmr-files.d.ts +4 -5
  9. package/dist/node/plugins/wx/dev/hmr-files.js +18 -8
  10. package/dist/node/plugins/wx/dev/patch-publisher.d.ts +25 -5
  11. package/dist/node/plugins/wx/dev/patch-publisher.js +30 -9
  12. package/dist/node/plugins/wx/dev/react-refresh.d.ts +12 -0
  13. package/dist/node/plugins/wx/dev/react-refresh.js +111 -108
  14. package/dist/node/plugins/wx/dev/wx-dev-options.d.ts +25 -0
  15. package/dist/node/plugins/wx/dev/wx-dev-options.js +147 -0
  16. package/dist/node/utils/oxc-transform.d.ts +21 -0
  17. package/dist/node/utils/oxc-transform.js +58 -0
  18. package/dist/node/utils/serialized-task-queue.d.ts +6 -2
  19. package/dist/node/utils/serialized-task-queue.js +10 -2
  20. package/dist/runtime/wx/capsule/page.js +14 -5
  21. package/dist/runtime/wx/dev/dev-runtime.js +70 -26
  22. package/package.json +4 -3
  23. package/src/node/plugins/h5/create-stencil-client-adapter.ts +74 -73
  24. package/src/node/plugins/h5/plugins.ts +42 -13
  25. package/src/node/plugins/wx/dev/dev-host.ts +121 -256
  26. package/src/node/plugins/wx/dev/hmr-files.ts +20 -8
  27. package/src/node/plugins/wx/dev/patch-publisher.ts +36 -10
  28. package/src/node/plugins/wx/dev/react-refresh.ts +125 -129
  29. package/src/node/plugins/wx/dev/wx-dev-options.ts +200 -0
  30. package/src/node/utils/oxc-transform.ts +77 -0
  31. package/src/node/utils/serialized-task-queue.ts +15 -3
  32. package/src/runtime/wx/capsule/page.ts +23 -9
  33. package/src/runtime/wx/dev/dev-runtime.ts +80 -28
@@ -5,9 +5,8 @@
5
5
  // The `DevRuntime` base class is injected into the chunk by Rolldown's dev-mode
6
6
  // transform, so the WX host only extends it.
7
7
  //
8
- // Delivery is passive: every valid hmr/patches.js suffix is acknowledged by Rolldown
9
- // sequence, then applied synchronously before the Page continues evaluating. Already-applied
10
- // sequences are ignored when another Page requires the same physical file.
8
+ // Every Page explicitly passes the inert hmr/patches.js export here before importing its capsule. The runtime applies that
9
+ // cumulative suffix synchronously, reports its successful application frontier, and ignores sequences replayed by other Pages.
11
10
  /**
12
11
  * Per-module hot state, mirroring Rolldown's web runtime: accept is a passive registration;
13
12
  * the propagation invokes the previous execution's callbacks with the fresh exports.
@@ -134,14 +133,12 @@ class WxDevRuntime extends DevRuntime {
134
133
  }
135
134
  }
136
135
  }
137
- /** Consumed once per App heap from hmr/info.js; the host buildId is the delivery identity. */
136
+ /** Consumed once per App heap from hmr/info.js; the host buildId identifies its cumulative patch history. */
138
137
  initialize(info) {
139
138
  if (this.hmrInfo) {
140
139
  return;
141
140
  }
142
141
  this.hmrInfo = info;
143
- // Anchor: the host publishes only after the runtime reports its delivery position.
144
- void this.sendReport({ kind: 'delivery', seq: this.appliedSeq });
145
142
  }
146
143
  /** True between a patch delivery and the next page show: a hot reload is in progress. */
147
144
  hotReloading = false;
@@ -153,42 +150,89 @@ class WxDevRuntime extends DevRuntime {
153
150
  clearHotReloading() {
154
151
  this.hotReloading = false;
155
152
  }
156
- /** The only direct effect of hmr/patches.js: validate, store, acknowledge, and apply. */
157
- storePatches(payload) {
153
+ /** Applies one Page-delivered payload before that Page imports its capsule. */
154
+ applyPatches(payload) {
155
+ // The initial physical dependency exports undefined until the host has a patch range.
156
+ if (!payload)
157
+ return;
158
158
  const info = this.hmrInfo;
159
159
  if (!info || payload.buildId !== info.buildId) {
160
160
  console.warn('[vpt] patches for a stale build');
161
161
  return;
162
162
  }
163
- const deliveredSeq = Math.max(this.appliedSeq, payload.patches.at(-1)?.seq ?? 0);
164
- void this.sendReport({ kind: 'delivery', seq: deliveredSeq });
165
163
  // A delivered patch means DevTools is about to replay the page lifecycle on the
166
164
  // re-executing Pages; the capsule wrapper suppresses the synthetic unmount/mount so
167
165
  // the React tree survives and Refresh swaps the code in place.
168
166
  this.hotReloading = true;
169
167
  // Apply synchronously: the page's imports below the require resolve against the
170
168
  // freshly registered modules, so the re-executed Page evaluates with the new code.
171
- this.applyPatches(payload.patches);
169
+ if (this.applyPatchBatch(payload.patches)) {
170
+ // The host may publish later generations while this synchronous apply runs. Reporting only afterward makes this
171
+ // the application frontier: publisher history is never pruned merely because its JavaScript file was observed.
172
+ void this.sendReport({ kind: 'applied', seq: this.appliedSeq });
173
+ }
172
174
  }
173
- /** Applies one physical suffix in Rolldown sequence order. */
174
- applyPatches(patches) {
175
- for (const patch of patches) {
176
- if (patch.seq <= this.appliedSeq)
177
- continue;
178
- try {
179
- const expectedSeq = this.appliedSeq + 1;
180
- if (patch.seq !== expectedSeq) {
181
- throw new Error(`missing patch sequence ${expectedSeq}`);
175
+ /**
176
+ * Folds one cumulative physical patch file into a single logical HMR update.
177
+ *
178
+ * `hmr/patches.js` can contain several unacknowledged Rolldown patches and can be required by several Page shells. The
179
+ * runtime must therefore ignore replayed sequences, reject a missing sequence, and move directly from the currently live
180
+ * module generation to the latest published generation without rendering intermediate generations.
181
+ *
182
+ * For an appliedSeq of 4:
183
+ *
184
+ * - [5, 6, 7] registers every factory, performs one update using their unioned changedIds, commits appliedSeq 7, and reports 7;
185
+ * - a second Page evaluating [5, 6, 7] skips the complete replay and leaves the latest factories untouched;
186
+ * - [5, 7] fails at the expected sequence 6, keeps appliedSeq 4, and requests a full rebuild because factory 6 is unrecoverable.
187
+ */
188
+ applyPatchBatch(patches) {
189
+ // Keep the initial watermark immutable throughout the fold. Comparing replays against a moving watermark would allow
190
+ // a duplicate new sequence in the same payload to masquerade as an already-applied patch.
191
+ const previousSeq = this.appliedSeq;
192
+ // Mutable only during this synchronous pass. `nextSeq` validates continuity while `changedIds` unions every incremental
193
+ // patch's roots for the one final graph traversal; neither value escapes into persistent runtime state.
194
+ let nextSeq = previousSeq + 1;
195
+ const changedIds = new Set();
196
+ try {
197
+ for (const patch of patches) {
198
+ // The same physical file is evaluated once per affected Page. Those later evaluations replay its prefix and
199
+ // must not let an old factory overwrite the newer factory already stored in the Rolldown runtime.
200
+ if (patch.seq <= previousSeq) {
201
+ continue;
182
202
  }
203
+ // Every patch is incremental: if one physical write was missed, later factories cannot reconstruct modules
204
+ // changed only by that missing patch. Rebuilding is safer than silently running a mixed module generation.
205
+ if (patch.seq !== nextSeq) {
206
+ throw new Error(`missing patch sequence ${nextSeq}`);
207
+ }
208
+ // A patch factory only registers module graphs and module factories; it does not execute application modules.
209
+ // Running all of them first leaves the registry at the latest generation while avoiding intermediate renders.
183
210
  patch.factory();
184
- this.applyHmrUpdate(patch.changedIds);
185
- this.appliedSeq = patch.seq;
211
+ for (const changedId of patch.changedIds) {
212
+ changedIds.add(changedId);
213
+ }
214
+ nextSeq++;
186
215
  }
187
- catch (error) {
188
- console.warn(`[vpt] patch sequence ${patch.seq} failed; apply stopped`, error);
189
- void this.sendReport({ kind: 'rebuild' });
190
- return;
216
+ // A payload containing only replayed sequences requires no graph work and must not alter the application watermark.
217
+ if (nextSeq === previousSeq + 1) {
218
+ return true;
191
219
  }
220
+ // Apply once after every factory is registered. React Refresh arms a newly executed module's hot.accept callback
221
+ // in a microtask; applying consecutive patches separately would inspect that intermediate context too early and
222
+ // incorrectly bubble through the capsule to the native Page shell as though no HMR boundary existed.
223
+ this.applyHmrUpdate(changedIds);
224
+ // Commit application only after graph propagation and boundary callbacks succeed. A failure leaves the old watermark
225
+ // intact and requests a full rebuild below, so a partially applied batch is never acknowledged as healthy.
226
+ this.appliedSeq = nextSeq - 1;
227
+ return true;
228
+ }
229
+ catch (error) {
230
+ console.warn('[vpt] patch batch failed; apply stopped', error);
231
+ void this.sendReport({
232
+ kind: 'rebuild',
233
+ reason: Error.isError(error) ? error.message : String(error)
234
+ });
235
+ return false;
192
236
  }
193
237
  }
194
238
  /** Sends one metadata-only report to the host; executable code never travels over HTTP. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vite-plugin-taro",
3
- "version": "0.5.4",
3
+ "version": "0.5.6",
4
4
  "author": "sep2",
5
5
  "description": "Vite 8 plugin for building one React/Taro codebase for WeChat Mini Program and H5 targets.",
6
6
  "type": "module",
@@ -68,14 +68,15 @@
68
68
  "@vitejs/plugin-react": "^6.0.5",
69
69
  "@weapp-tailwindcss/postcss": "3.2.8",
70
70
  "babel-plugin-transform-taroapi": "4.2.0",
71
+ "oxc-walker": "1.1.1",
71
72
  "picocolors": "^1.1.1",
72
73
  "react-reconciler": "0.33.0",
73
74
  "react-refresh": "^0.18.0",
74
75
  "rolldown": "1.2.3",
75
76
  "tailwindcss": "^4.3.3",
76
77
  "weapp-tailwindcss": "^5.2.11",
77
- "@tarojs/plugin-framework-react": "npm:vite-plugin-taro-plugin-framework-react@0.5.4",
78
- "@tarojs/react": "npm:vite-plugin-taro-react@0.5.4"
78
+ "@tarojs/react": "npm:vite-plugin-taro-react@0.5.6",
79
+ "@tarojs/plugin-framework-react": "npm:vite-plugin-taro-plugin-framework-react@0.5.6"
79
80
  },
80
81
  "peerDependencies": {
81
82
  "react": "^19.0.0",
@@ -1,7 +1,8 @@
1
- import type { types as BabelTypes } from '@babel/core'
2
- import { type NodePath, type PluginObj, transformAsync, types } from '@babel/core'
1
+ import type { WalkerEnter } from 'oxc-walker'
2
+ import type { RolldownMagicString } from 'rolldown'
3
3
  import type { Plugin } from 'vite'
4
4
  import { normalizeModuleId } from '../../utils/modules.ts'
5
+ import { transformWithOxcWalker } from '../../utils/oxc-transform.ts'
5
6
  import { packageRequire } from '../../utils/packages.ts'
6
7
 
7
8
  const stencilClientPath = packageRequire.resolve('@stencil/core/internal/client', {
@@ -25,85 +26,85 @@ export function createStencilClientAdapter(): Plugin {
25
26
  }
26
27
  }
27
28
 
28
- /** Applies the shared Stencil adaptation in either the application or dependency-optimization pipeline. */
29
- export async function adaptStencilClient(code: string, id: string) {
29
+ /**
30
+ * Applies the shared Stencil adaptation with one Oxc parse and one range edit.
31
+ *
32
+ * The physical module check is essential because the optimizer and application pipelines can
33
+ * present query-suffixed or platform-normalized IDs. Transforming by source text alone could
34
+ * modify user code that happens to contain the same insertion expression. Source maps remain
35
+ * enabled because this adapter runs before Vite/Rolldown's later transforms in both pipelines;
36
+ * dropping the map would attribute downstream diagnostics to the edited generated positions.
37
+ */
38
+ export function adaptStencilClient(code: string, id: string) {
30
39
  if (normalizeModuleId(id) !== normalizedStencilClientPath) {
31
40
  return
32
41
  }
33
42
 
34
- const transformed = await transformAsync(code, {
35
- babelrc: false,
36
- configFile: false,
37
- filename: stencilClientPath,
38
- plugins: [rewriteStencilStyleInsertion],
39
- sourceFileName: stencilClientPath,
40
- sourceMaps: true
43
+ return transformWithOxcWalker({
44
+ code,
45
+ filename: id,
46
+ sourcemap: true,
47
+ createVisitor: createStencilVisitor
41
48
  })
42
-
43
- if (transformed?.code === undefined || transformed.code === null) {
44
- throw new Error(`Failed to adapt Stencil client: ${stencilClientPath}`)
45
- }
46
-
47
- return {
48
- code: transformed.code,
49
- map: transformed.map
50
- }
51
49
  }
52
50
 
53
- /** Keeps Stencil-injected Taro component styles before application stylesheets. */
54
- function rewriteStencilStyleInsertion(): PluginObj {
55
- return {
56
- name: 'vpt:rewrite-stencil-style-insertion',
57
- visitor: {
58
- CallExpression(callPath) {
59
- if (!isStencilStyleInsertBeforeCall(callPath)) {
60
- return
61
- }
62
-
63
- callPath
64
- .get('arguments.1')
65
- .replaceWith(
66
- types.conditionalExpression(
67
- types.callExpression(
68
- types.memberExpression(types.identifier('scopeId'), types.identifier('startsWith')),
69
- [types.stringLiteral('sc-taro-')]
70
- ),
71
- createStyleQuery('style,link[rel="stylesheet"]'),
72
- createStyleQuery('link')
73
- )
74
- )
75
- }
51
+ /**
52
+ * Finds Stencil's exact default style insertion call and replaces only its insertion anchor.
53
+ *
54
+ * Stencil normally inserts `styleElm` before the first stylesheet link. During Vite development,
55
+ * application CSS is commonly represented by a `<style>` element instead, so that link-only
56
+ * lookup returns `null` and Taro component defaults are appended after application CSS. Those
57
+ * defaults then override the application's selectors despite having the same specificity.
58
+ *
59
+ * Taro Stencil components are identified by the `sc-taro-` scope prefix. For those components,
60
+ * the replacement anchors before the first `<style>` or stylesheet `<link>`, keeping component
61
+ * defaults before application rules. The original link-only lookup is preserved for every other
62
+ * Stencil component so VPT does not globally redefine upstream style-ordering behavior.
63
+ */
64
+ function createStencilVisitor(editor: RolldownMagicString): WalkerEnter {
65
+ return function enter(node) {
66
+ if (
67
+ node.type !== 'CallExpression' ||
68
+ node.callee.type !== 'MemberExpression' ||
69
+ node.callee.computed ||
70
+ node.callee.object.type !== 'Identifier' ||
71
+ node.callee.object.name !== 'styleContainerNode' ||
72
+ node.callee.property.type !== 'Identifier' ||
73
+ node.callee.property.name !== 'insertBefore'
74
+ ) {
75
+ return
76
76
  }
77
- }
78
- }
79
77
 
80
- /** Identifies Stencil's default component-style insertion call. */
81
- function isStencilStyleInsertBeforeCall(callPath: NodePath<BabelTypes.CallExpression>): boolean {
82
- const { callee, arguments: callArguments } = callPath.node
83
- return (
84
- types.isMemberExpression(callee) &&
85
- types.isIdentifier(callee.object, { name: 'styleContainerNode' }) &&
86
- types.isIdentifier(callee.property, { name: 'insertBefore' }) &&
87
- types.isIdentifier(callArguments[0], { name: 'styleElm' }) &&
88
- isStyleQuery(callArguments[1], 'link')
89
- )
90
- }
91
-
92
- /** Identifies one style-container querySelector call. */
93
- function isStyleQuery(node: BabelTypes.Node | null | undefined, selector: string): boolean {
94
- return (
95
- types.isCallExpression(node) &&
96
- types.isMemberExpression(node.callee) &&
97
- types.isIdentifier(node.callee.object, { name: 'styleContainerNode' }) &&
98
- types.isIdentifier(node.callee.property, { name: 'querySelector' }) &&
99
- types.isStringLiteral(node.arguments[0], { value: selector })
100
- )
101
- }
78
+ // Match the complete upstream call, not merely `insertBefore`: range edits have no
79
+ // generated-AST type safety, so a broad match could silently alter unrelated runtime
80
+ // behavior when Stencil changes its implementation.
81
+ const [style, query] = node.arguments
82
+ const selector = query?.type === 'CallExpression' ? query.arguments[0] : undefined
83
+ if (
84
+ node.arguments.length !== 2 ||
85
+ style?.type !== 'Identifier' ||
86
+ style.name !== 'styleElm' ||
87
+ query?.type !== 'CallExpression' ||
88
+ query.callee.type !== 'MemberExpression' ||
89
+ query.callee.computed ||
90
+ query.callee.object.type !== 'Identifier' ||
91
+ query.callee.object.name !== 'styleContainerNode' ||
92
+ query.callee.property.type !== 'Identifier' ||
93
+ query.callee.property.name !== 'querySelector' ||
94
+ selector?.type !== 'Literal' ||
95
+ selector.value !== 'link'
96
+ ) {
97
+ return
98
+ }
102
99
 
103
- /** Creates one style-container querySelector call. */
104
- function createStyleQuery(selector: string): ReturnType<typeof types.callExpression> {
105
- return types.callExpression(
106
- types.memberExpression(types.identifier('styleContainerNode'), types.identifier('querySelector')),
107
- [types.stringLiteral(selector)]
108
- )
100
+ // Replace only the second argument expression. Preserving the surrounding Stencil
101
+ // source avoids Babel-style whole-file regeneration and keeps its formatting, comments,
102
+ // and source positions stable. Removing this edit restores the H5 cascade bug described
103
+ // above; applying it unconditionally would change non-Taro Stencil components.
104
+ editor.overwrite(
105
+ query.start,
106
+ query.end,
107
+ 'scopeId.startsWith("sc-taro-") ? styleContainerNode.querySelector("style,link[rel=\\"stylesheet\\"]") : styleContainerNode.querySelector("link")'
108
+ )
109
+ }
109
110
  }
@@ -1,4 +1,4 @@
1
- import babel from '@rolldown/plugin-babel'
1
+ import babel, { defineRolldownBabelPreset } from '@rolldown/plugin-babel'
2
2
  import type { HtmlTagDescriptor, Plugin, PluginOption } from 'vite'
3
3
  import type { VitePluginTaroOptions } from '../../../options.ts'
4
4
  import { esTarget } from '../../utils/constant.ts'
@@ -99,22 +99,51 @@ function createH5IndexHtmlTags(): HtmlTagDescriptor[] {
99
99
  ]
100
100
  }
101
101
 
102
- /** Creates H5-only Babel transforms for Stencil CSS ordering and Taro API imports. */
102
+ /**
103
+ * Coarse source prefilter for the upstream Taro API transform.
104
+ *
105
+ * The plugin has two independent responsibilities: adapting imports from the compiler facade and normalizing camel-case
106
+ * H5 ARIA attributes. Matching `aria` followed by any uppercase letter is intentionally broader than Taro's current
107
+ * attribute table. A duplicated exact list would silently stop routing files through Babel when upstream adds another
108
+ * attribute, while a broad false positive costs only one unnecessary transform. Ordinary application modules match
109
+ * neither branch and remain entirely outside Babel's parser and generator.
110
+ */
111
+ export const h5TaroApiTransformCodeFilter = /virtual:taro\/api|\baria[A-Z]/
112
+
113
+ /** Creates a filterable Babel preset containing Taro's upstream, scope-aware API transform. */
114
+ function createH5TaroApiPreset() {
115
+ const transformTaroApiPath = packageRequire.resolve('babel-plugin-transform-taroapi')
116
+ const definition = packageRequire(packageRequire.resolve('@tarojs/plugin-platform-h5/dist/definition.json'))
117
+
118
+ return defineRolldownBabelPreset({
119
+ preset: function h5TaroApiPreset() {
120
+ return {
121
+ plugins: [
122
+ [
123
+ transformTaroApiPath,
124
+ {
125
+ packageName: clientTaroApiId,
126
+ definition
127
+ }
128
+ ]
129
+ ]
130
+ }
131
+ },
132
+ rolldown: {
133
+ // @rolldown/plugin-babel can lift a preset filter into its native transform hook. The Taro plugin must be
134
+ // nested in this preset rather than passed through Babel's top-level `plugins`: explicit plugins may apply
135
+ // to every module, so their presence deliberately disables Rolldown's preset-level code filtering.
136
+ filter: { code: h5TaroApiTransformCodeFilter }
137
+ }
138
+ })
139
+ }
140
+
141
+ /** Creates H5-only transforms for Stencil CSS ordering and Taro API imports. */
103
142
  function createH5SupportPlugins(): PluginOption[] {
104
143
  return [
105
144
  createStencilClientAdapter(),
106
145
  babel({
107
- plugins: [
108
- [
109
- packageRequire.resolve('babel-plugin-transform-taroapi'),
110
- {
111
- packageName: clientTaroApiId,
112
- definition: packageRequire(
113
- packageRequire.resolve('@tarojs/plugin-platform-h5/dist/definition.json')
114
- )
115
- }
116
- ]
117
- ]
146
+ presets: [createH5TaroApiPreset()]
118
147
  })
119
148
  ]
120
149
  }