vite-plugin-taro 0.5.14 → 0.5.16

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.
@@ -1,8 +1,11 @@
1
1
  import type { GetModuleInfo, Plugin } from 'rolldown';
2
+ /** Final CSS extracted from Vite's transformed style module, before the shared WX compatibility pass. */
2
3
  type ProcessedStyle = Readonly<{
3
4
  css: string;
5
+ /** Marks roots whose generated utilities must be refreshed when JavaScript changes Tailwind candidates. */
4
6
  isTailwindRoot: boolean;
5
7
  }>;
8
+ /** Minimal structural view of DevEngine output; style reconciliation does not own chunks or other asset metadata. */
6
9
  type CompleteOutputFile = Readonly<{
7
10
  type: 'asset';
8
11
  fileName: string;
@@ -20,10 +23,19 @@ export type StyleCaptureAction = Readonly<{
20
23
  style: ProcessedStyle;
21
24
  }>;
22
25
  /**
23
- * Owns capture hooks, the host's style projection, and its physical WXSS publication frontier.
26
+ * Captures final Vite CSS and composes the graph projection with its durable WXSS publisher.
24
27
  *
25
- * Rolldown remains authoritative for topology through its live graph reader. Plugin hooks emit typed actions so the host can
26
- * serialize captures with every other effect; only the matching capture methods mutate this projection.
28
+ * Rolldown remains authoritative for topology. Plugin hooks emit typed actions so the host serializes capture mutations with
29
+ * output and HMR publication; the projection and publisher below each own only one mutable concern.
30
+ *
31
+ * Complete-build path:
32
+ * final transform captures → DevEngine output write → graph reconciliation → App build rotation
33
+ *
34
+ * Incremental path:
35
+ * final transform captures → optional Tailwind root refresh → graph rendering → WXSS write → JavaScript patch publication
36
+ *
37
+ * Both paths render the same ordered App/Page graph projection. This prevents complete builds and HMR from implementing two
38
+ * subtly different CSS ownership policies, while keeping physical byte equality and atomic writes out of graph state.
27
39
  */
28
40
  export declare function createStyleCapture({ applicationEntryIds, outDir, emit, transformTailwindRoot }: {
29
41
  applicationEntryIds: readonly string[];
@@ -33,10 +45,10 @@ export declare function createStyleCapture({ applicationEntryIds, outDir, emit,
33
45
  code: string;
34
46
  }> | null>;
35
47
  }): Readonly<{
36
- bindOutput: (output: readonly CompleteOutputFile[]) => void;
37
48
  captureGraph: (reader: GetModuleInfo) => void;
38
49
  captureStyle: (id: string, style: ProcessedStyle) => void;
39
50
  plugin: Plugin;
40
51
  publishChanged: (changedIds: readonly string[]) => Promise<void>;
52
+ reconcileComplete: (output: readonly CompleteOutputFile[]) => Promise<void>;
41
53
  }>;
42
54
  export {};
@@ -4,50 +4,39 @@ import { transformWxStyle } from '../styles/transform-wx-style.js';
4
4
  import { composeGraphStyleCss, createGraphStylePlan, createTailwindSidecarId, extractViteCss, isGlobalStyleRequest } from '../styles/utils.js';
5
5
  import { globalWxssFileName, writeHmrFile } from './hmr-files.js';
6
6
  /**
7
- * Owns capture hooks, the host's style projection, and its physical WXSS publication frontier.
7
+ * Captures final Vite CSS and composes the graph projection with its durable WXSS publisher.
8
8
  *
9
- * Rolldown remains authoritative for topology through its live graph reader. Plugin hooks emit typed actions so the host can
10
- * serialize captures with every other effect; only the matching capture methods mutate this projection.
9
+ * Rolldown remains authoritative for topology. Plugin hooks emit typed actions so the host serializes capture mutations with
10
+ * output and HMR publication; the projection and publisher below each own only one mutable concern.
11
+ *
12
+ * Complete-build path:
13
+ * final transform captures → DevEngine output write → graph reconciliation → App build rotation
14
+ *
15
+ * Incremental path:
16
+ * final transform captures → optional Tailwind root refresh → graph rendering → WXSS write → JavaScript patch publication
17
+ *
18
+ * Both paths render the same ordered App/Page graph projection. This prevents complete builds and HMR from implementing two
19
+ * subtly different CSS ownership policies, while keeping physical byte equality and atomic writes out of graph state.
11
20
  */
12
21
  export function createStyleCapture({ applicationEntryIds, outDir, emit, transformTailwindRoot }) {
13
- /*
14
- * This mutable capability is rebound by buildStart for each complete generation. Rolldown keeps the captured function live
15
- * across incremental graph edits, so HMR traverses authoritative current topology without maintaining a shadow graph. It is
16
- * undefined only before the first buildStart; retaining an older reader across a later complete build would bind transactions
17
- * to the wrong engine generation, while snapshotting module data would require O(V + E) mutation on every edit.
18
- */
19
- let getModuleInfo;
20
- /*
21
- * This mutable Map is the CSS projection Rolldown does not retain: successful final transform hooks replace one module's
22
- * processed bytes, failed transforms intentionally leave its last valid generation, and a successful multi-root Tailwind
23
- * refresh commits all replacements only after every sibling resolves. Entries are not deleted when topology changes because
24
- * reachability comes from the live graph plan; eager deletion would need a duplicate reverse graph and could remove CSS still
25
- * shared by another App/Page root. Its size is bounded by style module identities seen during this server lifecycle.
26
- */
27
- const processedStyles = new Map();
28
- /*
29
- * This mutable value mirrors the WXSS bytes currently durable on disk. It has one owner but two real transition sources:
30
- *
31
- * 1. DevEngine physically writes complete output before onOutput, so bindOutput only observes and adopts that external
32
- * commit. An omitted asset means DevEngine preserved the existing file and this value must remain unchanged.
33
- * 2. Incremental HMR is physically written by this host, so publishChanged advances the value only after its atomic write
34
- * succeeds (or after byte equality proves no write was needed).
35
- *
36
- * Combining these operations behind one generic update event would still require branching between “observe an existing
37
- * write” and “perform a new write”, while hiding their different durability boundaries. A genuine single path would require
38
- * preventing DevEngine from writing complete WXSS and transferring that entire output responsibility to the host, adding
39
- * asset interception and ordering machinery. The two explicit methods are therefore the smallest accurate state model.
40
- */
41
- let publishedWxss;
22
+ const projection = createStyleProjection({
23
+ applicationEntryIds: applicationEntryIds,
24
+ transformTailwindRoot: transformTailwindRoot
25
+ });
26
+ const publication = createStylePublication(outDir);
42
27
  const plugin = {
43
28
  name: 'vpt:wx-dev-style-capture',
44
29
  buildStart() {
30
+ // Capture a live reader rather than a graph snapshot. Rolldown updates the capability as imports change, and a later
31
+ // complete generation replaces it through the host action queue before that generation can publish output.
45
32
  emit({ kind: 'capture-graph', getModuleInfo: (moduleId) => this.getModuleInfo(moduleId) });
46
33
  },
47
34
  transform(code, id) {
48
35
  if (!isGlobalStyleRequest(id)) {
49
36
  return;
50
37
  }
38
+ // This host plugin runs after Vite's CSS transform, so `code` is the JavaScript wrapper containing final PostCSS and
39
+ // CSS-Module output. Capturing source CSS instead would lose generated class names and framework transformations.
51
40
  const css = extractViteCss(code, id);
52
41
  emit({
53
42
  kind: 'capture-style',
@@ -60,48 +49,107 @@ export function createStyleCapture({ applicationEntryIds, outDir, emit, transfor
60
49
  }
61
50
  };
62
51
  return {
63
- bindOutput(output) {
64
- /*
65
- * Complete output is one of the two real physical writers. Its emitted asset is therefore the authoritative frontier
66
- * when present; omission means DevEngine preserved the existing file and this state must remain unchanged.
67
- */
68
- const style = output.find((file) => file.type === 'asset' && file.fileName === globalWxssFileName);
69
- if (style) {
70
- publishedWxss = typeof style.source === 'string' ? style.source : new TextDecoder().decode(style.source);
52
+ captureGraph: projection.captureGraph,
53
+ captureStyle: projection.captureStyle,
54
+ plugin: plugin,
55
+ async publishChanged(changedIds) {
56
+ // A CSS edit already carries updated processed bytes. Any non-CSS edit can alter both imports and Tailwind class
57
+ // candidates, so it requires a fresh graph plan and Tailwind-root generation even when no .css ID changed directly.
58
+ const styleChanged = changedIds.some(isGlobalStyleRequest);
59
+ const candidatesChanged = changedIds.some((id) => !isCSSRequest(id));
60
+ if (!styleChanged && !candidatesChanged) {
61
+ return;
71
62
  }
63
+ await publication.publish(await projection.render(candidatesChanged));
72
64
  },
65
+ async reconcileComplete(output) {
66
+ // Bundled development can omit CSS Modules from the compiler asset even with cssCodeSplit disabled. Observe the
67
+ // physical output first, then reconcile the same graph projection used by incremental HMR before App rotation.
68
+ publication.observeOutput(output);
69
+ await publication.publish(await projection.render(false));
70
+ }
71
+ };
72
+ }
73
+ /**
74
+ * Owns the live graph capability and final transformed bytes for every observed style module.
75
+ *
76
+ * Rendering is O(V + E + C): graph planning visits each reachable module and edge once, then composition and WX conversion
77
+ * process C CSS bytes once. The only persistent memory is one processed byte string per style identity observed by the server.
78
+ */
79
+ function createStyleProjection({ applicationEntryIds, transformTailwindRoot }) {
80
+ /*
81
+ * This mutable capability is rebound by buildStart for each complete generation. Rolldown keeps the function live across
82
+ * incremental graph edits, so rendering uses authoritative topology without maintaining a shadow graph.
83
+ */
84
+ let getModuleInfo;
85
+ /*
86
+ * This mutable projection stores final CSS bytes that Rolldown does not retain. Successful transforms replace one entry;
87
+ * unreachable entries can remain because every render filters them through the current graph plan. Its size is bounded by
88
+ * style module identities observed during this server lifecycle.
89
+ */
90
+ const processedStyles = new Map();
91
+ return {
73
92
  captureGraph(reader) {
74
93
  getModuleInfo = reader;
75
94
  },
76
95
  captureStyle(id, style) {
77
96
  processedStyles.set(id, style);
78
97
  },
79
- plugin: plugin,
80
- async publishChanged(changedIds) {
81
- const styleChanged = changedIds.some(isGlobalStyleRequest);
82
- const candidatesChanged = changedIds.some((id) => !isCSSRequest(id));
83
- if (!styleChanged && !candidatesChanged) {
84
- return;
85
- }
98
+ async render(refreshTailwind) {
86
99
  if (!getModuleInfo) {
87
- throw new Error('WX style graph is unavailable before HMR publication');
100
+ throw new Error('WX style graph is unavailable before publication');
88
101
  }
89
- // Traverse topology exactly once; root refresh and final rendering consume this immutable transaction plan.
102
+ // App first and configured Pages afterward define one deterministic global cascade. The plan also removes stale map
103
+ // entries implicitly: styles no longer reachable from these roots never enter composition.
90
104
  const styleIds = createGraphStylePlan(applicationEntryIds, getModuleInfo, (styleId) => processedStyles.has(styleId));
91
- if (candidatesChanged) {
105
+ if (refreshTailwind) {
92
106
  await refreshTailwindStyles(styleIds, processedStyles, transformTailwindRoot);
93
107
  }
108
+ // Compose browser-facing transformed CSS first, then run one whole-file WX pass. Transforming modules independently
109
+ // would change cross-module cascade behavior and duplicate compatibility work.
94
110
  const css = composeGraphStyleCss(styleIds, (styleId) => requireProcessedStyle(processedStyles, styleId).css);
95
- const wxss = (await transformWxStyle(css)).css;
111
+ return (await transformWxStyle(css)).css;
112
+ }
113
+ };
114
+ }
115
+ /**
116
+ * Owns the physical WXSS frontier independently from graph capture and rendering.
117
+ *
118
+ * DevEngine writes complete output itself; incremental HMR does not. Observing complete output before publishing the projection
119
+ * gives both writers one byte frontier, so equality avoids redundant filesystem notifications without pretending the host owns
120
+ * the compiler's write transaction.
121
+ */
122
+ function createStylePublication(outDir) {
123
+ /*
124
+ * This mutable value mirrors bytes durable on disk. Complete output adopts the compiler's external write before graph
125
+ * reconciliation; host publication advances it only after an atomic write succeeds or byte equality proves none is needed.
126
+ */
127
+ let publishedWxss;
128
+ return {
129
+ observeOutput(output) {
130
+ // Missing WXSS means DevEngine intentionally reused the existing physical asset. Do not reset the frontier: doing so
131
+ // would force an identical rewrite and a spurious DevTools style event on every omitted complete generation.
132
+ const style = output.find((file) => file.type === 'asset' && file.fileName === globalWxssFileName);
133
+ if (style) {
134
+ publishedWxss = typeof style.source === 'string' ? style.source : new TextDecoder().decode(style.source);
135
+ }
136
+ },
137
+ async publish(wxss) {
96
138
  if (wxss !== publishedWxss) {
139
+ // writeHmrFile uses atomic replacement; advance the frontier only after durability so a failed write leaves the
140
+ // last known physical generation available for the next reconciliation attempt.
97
141
  await writeHmrFile(outDir, globalWxssFileName, wxss);
98
142
  }
99
- // HMR is the second physical writer; advance the frontier only after its atomic write succeeds or was unnecessary.
100
143
  publishedWxss = wxss;
101
144
  }
102
145
  };
103
146
  }
104
- /** Regenerates all reachable Tailwind roots and commits the cache only when every transform succeeds. */
147
+ /**
148
+ * Regenerates all reachable Tailwind roots and commits the cache only when every transform succeeds.
149
+ *
150
+ * Roots run concurrently because they are independent derivations of the same candidate generation. Results remain local until
151
+ * Promise.all fulfills; one failed root therefore preserves every prior root together instead of publishing a mixed generation.
152
+ */
105
153
  async function refreshTailwindStyles(styleIds, processedStyles, transformRoot) {
106
154
  const roots = styleIds.filter((styleId) => requireProcessedStyle(processedStyles, styleId).isTailwindRoot);
107
155
  const refreshedStyles = await Promise.all(roots.map(async (rootId) => {
@@ -11,7 +11,7 @@ import { PatchPublisher } from './patch-publisher.js';
11
11
  import { createRuntimeReportsStream } from './runtime-reports.js';
12
12
  import { installWxDevOptions, requireSingleOutput } from './wx-dev-options.js';
13
13
  /** One short trailing-edge window absorbs editor bursts before style preparation and physical Page notification. */
14
- const hmrSettleMilliseconds = 32;
14
+ const hmrSettleMilliseconds = 16;
15
15
  /**
16
16
  * Creates the wx dev host: the adapter that owns the physical Rolldown DevEngine (created
17
17
  * with dev(...)) and the patch publisher, and replaces Vite's bundledDev.listen so the
@@ -163,12 +163,22 @@ export async function createWxDevHost({ server, options, applicationEntryIds })
163
163
  logWxError(server.config.logger, 'wx dev build failed', action.result);
164
164
  return;
165
165
  }
166
- styleCapture.bindOutput(action.result.output);
167
- return rotateBuildSession();
166
+ return reconcileCompleteOutput(action.result.output);
168
167
  case 'listening':
169
168
  return rotateBuildSession();
170
169
  }
171
170
  }
171
+ /**
172
+ * Reconciles graph-complete styles before rotating the App-visible build identity.
173
+ *
174
+ * DevEngine has already written its compiler asset when onOutput fires, but bundled development may have omitted CSS Modules
175
+ * from that asset. Awaiting reconciliation inside the serialized reducer guarantees the subsequent app.wxss rotation—the
176
+ * event that refreshes DevTools—can only expose a generation whose global WXSS already represents the complete App/Page graph.
177
+ */
178
+ async function reconcileCompleteOutput(output) {
179
+ await styleCapture.reconcileComplete(output);
180
+ await rotateBuildSession();
181
+ }
172
182
  /** Applies one runtime receipt to the active physical patch history. */
173
183
  function processReport(report) {
174
184
  // Delayed reports from older builds must never prune the live build's cumulative patch history.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vite-plugin-taro",
3
- "version": "0.5.14",
3
+ "version": "0.5.16",
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",
@@ -76,8 +76,8 @@
76
76
  "rxjs": "^7.8.2",
77
77
  "tailwindcss": "^4.3.3",
78
78
  "weapp-tailwindcss": "^5.2.11",
79
- "@tarojs/plugin-framework-react": "npm:vite-plugin-taro-plugin-framework-react@0.5.14",
80
- "@tarojs/react": "npm:vite-plugin-taro-react@0.5.14"
79
+ "@tarojs/plugin-framework-react": "npm:vite-plugin-taro-plugin-framework-react@0.5.16",
80
+ "@tarojs/react": "npm:vite-plugin-taro-react@0.5.16"
81
81
  },
82
82
  "peerDependencies": {
83
83
  "react": "^19.0.0",
@@ -11,11 +11,14 @@ import {
11
11
  } from '../styles/utils.ts'
12
12
  import { globalWxssFileName, writeHmrFile } from './hmr-files.ts'
13
13
 
14
+ /** Final CSS extracted from Vite's transformed style module, before the shared WX compatibility pass. */
14
15
  type ProcessedStyle = Readonly<{
15
16
  css: string
17
+ /** Marks roots whose generated utilities must be refreshed when JavaScript changes Tailwind candidates. */
16
18
  isTailwindRoot: boolean
17
19
  }>
18
20
 
21
+ /** Minimal structural view of DevEngine output; style reconciliation does not own chunks or other asset metadata. */
19
22
  type CompleteOutputFile =
20
23
  | Readonly<{ type: 'asset'; fileName: string; source: string | Uint8Array }>
21
24
  | Readonly<{ type: 'chunk'; fileName: string }>
@@ -25,10 +28,19 @@ export type StyleCaptureAction =
25
28
  | Readonly<{ kind: 'capture-style'; id: string; style: ProcessedStyle }>
26
29
 
27
30
  /**
28
- * Owns capture hooks, the host's style projection, and its physical WXSS publication frontier.
31
+ * Captures final Vite CSS and composes the graph projection with its durable WXSS publisher.
29
32
  *
30
- * Rolldown remains authoritative for topology through its live graph reader. Plugin hooks emit typed actions so the host can
31
- * serialize captures with every other effect; only the matching capture methods mutate this projection.
33
+ * Rolldown remains authoritative for topology. Plugin hooks emit typed actions so the host serializes capture mutations with
34
+ * output and HMR publication; the projection and publisher below each own only one mutable concern.
35
+ *
36
+ * Complete-build path:
37
+ * final transform captures → DevEngine output write → graph reconciliation → App build rotation
38
+ *
39
+ * Incremental path:
40
+ * final transform captures → optional Tailwind root refresh → graph rendering → WXSS write → JavaScript patch publication
41
+ *
42
+ * Both paths render the same ordered App/Page graph projection. This prevents complete builds and HMR from implementing two
43
+ * subtly different CSS ownership policies, while keeping physical byte equality and atomic writes out of graph state.
32
44
  */
33
45
  export function createStyleCapture({
34
46
  applicationEntryIds,
@@ -41,45 +53,23 @@ export function createStyleCapture({
41
53
  emit: (action: StyleCaptureAction) => void
42
54
  transformTailwindRoot: (rootId: string, requestId: string) => Promise<Readonly<{ code: string }> | null>
43
55
  }): Readonly<{
44
- bindOutput: (output: readonly CompleteOutputFile[]) => void
45
56
  captureGraph: (reader: GetModuleInfo) => void
46
57
  captureStyle: (id: string, style: ProcessedStyle) => void
47
58
  plugin: Plugin
48
59
  publishChanged: (changedIds: readonly string[]) => Promise<void>
60
+ reconcileComplete: (output: readonly CompleteOutputFile[]) => Promise<void>
49
61
  }> {
50
- /*
51
- * This mutable capability is rebound by buildStart for each complete generation. Rolldown keeps the captured function live
52
- * across incremental graph edits, so HMR traverses authoritative current topology without maintaining a shadow graph. It is
53
- * undefined only before the first buildStart; retaining an older reader across a later complete build would bind transactions
54
- * to the wrong engine generation, while snapshotting module data would require O(V + E) mutation on every edit.
55
- */
56
- let getModuleInfo: GetModuleInfo | undefined
57
- /*
58
- * This mutable Map is the CSS projection Rolldown does not retain: successful final transform hooks replace one module's
59
- * processed bytes, failed transforms intentionally leave its last valid generation, and a successful multi-root Tailwind
60
- * refresh commits all replacements only after every sibling resolves. Entries are not deleted when topology changes because
61
- * reachability comes from the live graph plan; eager deletion would need a duplicate reverse graph and could remove CSS still
62
- * shared by another App/Page root. Its size is bounded by style module identities seen during this server lifecycle.
63
- */
64
- const processedStyles = new Map<string, ProcessedStyle>()
65
- /*
66
- * This mutable value mirrors the WXSS bytes currently durable on disk. It has one owner but two real transition sources:
67
- *
68
- * 1. DevEngine physically writes complete output before onOutput, so bindOutput only observes and adopts that external
69
- * commit. An omitted asset means DevEngine preserved the existing file and this value must remain unchanged.
70
- * 2. Incremental HMR is physically written by this host, so publishChanged advances the value only after its atomic write
71
- * succeeds (or after byte equality proves no write was needed).
72
- *
73
- * Combining these operations behind one generic update event would still require branching between “observe an existing
74
- * write” and “perform a new write”, while hiding their different durability boundaries. A genuine single path would require
75
- * preventing DevEngine from writing complete WXSS and transferring that entire output responsibility to the host, adding
76
- * asset interception and ordering machinery. The two explicit methods are therefore the smallest accurate state model.
77
- */
78
- let publishedWxss: string | undefined
62
+ const projection = createStyleProjection({
63
+ applicationEntryIds: applicationEntryIds,
64
+ transformTailwindRoot: transformTailwindRoot
65
+ })
66
+ const publication = createStylePublication(outDir)
79
67
 
80
68
  const plugin: Plugin = {
81
69
  name: 'vpt:wx-dev-style-capture',
82
70
  buildStart() {
71
+ // Capture a live reader rather than a graph snapshot. Rolldown updates the capability as imports change, and a later
72
+ // complete generation replaces it through the host action queue before that generation can publish output.
83
73
  emit({ kind: 'capture-graph', getModuleInfo: (moduleId) => this.getModuleInfo(moduleId) })
84
74
  },
85
75
  transform(code, id) {
@@ -87,6 +77,8 @@ export function createStyleCapture({
87
77
  return
88
78
  }
89
79
 
80
+ // This host plugin runs after Vite's CSS transform, so `code` is the JavaScript wrapper containing final PostCSS and
81
+ // CSS-Module output. Capturing source CSS instead would lose generated class names and framework transformations.
90
82
  const css = extractViteCss(code, id)
91
83
  emit({
92
84
  kind: 'capture-style',
@@ -100,55 +92,132 @@ export function createStyleCapture({
100
92
  }
101
93
 
102
94
  return {
103
- bindOutput(output) {
104
- /*
105
- * Complete output is one of the two real physical writers. Its emitted asset is therefore the authoritative frontier
106
- * when present; omission means DevEngine preserved the existing file and this state must remain unchanged.
107
- */
108
- const style = output.find(
109
- (file): file is Extract<CompleteOutputFile, { type: 'asset' }> =>
110
- file.type === 'asset' && file.fileName === globalWxssFileName
111
- )
112
- if (style) {
113
- publishedWxss = typeof style.source === 'string' ? style.source : new TextDecoder().decode(style.source)
95
+ captureGraph: projection.captureGraph,
96
+ captureStyle: projection.captureStyle,
97
+ plugin: plugin,
98
+ async publishChanged(changedIds) {
99
+ // A CSS edit already carries updated processed bytes. Any non-CSS edit can alter both imports and Tailwind class
100
+ // candidates, so it requires a fresh graph plan and Tailwind-root generation even when no .css ID changed directly.
101
+ const styleChanged = changedIds.some(isGlobalStyleRequest)
102
+ const candidatesChanged = changedIds.some((id) => !isCSSRequest(id))
103
+ if (!styleChanged && !candidatesChanged) {
104
+ return
114
105
  }
106
+ await publication.publish(await projection.render(candidatesChanged))
115
107
  },
108
+ async reconcileComplete(output) {
109
+ // Bundled development can omit CSS Modules from the compiler asset even with cssCodeSplit disabled. Observe the
110
+ // physical output first, then reconcile the same graph projection used by incremental HMR before App rotation.
111
+ publication.observeOutput(output)
112
+ await publication.publish(await projection.render(false))
113
+ }
114
+ }
115
+ }
116
+
117
+ /**
118
+ * Owns the live graph capability and final transformed bytes for every observed style module.
119
+ *
120
+ * Rendering is O(V + E + C): graph planning visits each reachable module and edge once, then composition and WX conversion
121
+ * process C CSS bytes once. The only persistent memory is one processed byte string per style identity observed by the server.
122
+ */
123
+ function createStyleProjection({
124
+ applicationEntryIds,
125
+ transformTailwindRoot
126
+ }: {
127
+ applicationEntryIds: readonly string[]
128
+ transformTailwindRoot: (rootId: string, requestId: string) => Promise<Readonly<{ code: string }> | null>
129
+ }): Readonly<{
130
+ captureGraph: (reader: GetModuleInfo) => void
131
+ captureStyle: (id: string, style: ProcessedStyle) => void
132
+ render: (refreshTailwind: boolean) => Promise<string>
133
+ }> {
134
+ /*
135
+ * This mutable capability is rebound by buildStart for each complete generation. Rolldown keeps the function live across
136
+ * incremental graph edits, so rendering uses authoritative topology without maintaining a shadow graph.
137
+ */
138
+ let getModuleInfo: GetModuleInfo | undefined
139
+ /*
140
+ * This mutable projection stores final CSS bytes that Rolldown does not retain. Successful transforms replace one entry;
141
+ * unreachable entries can remain because every render filters them through the current graph plan. Its size is bounded by
142
+ * style module identities observed during this server lifecycle.
143
+ */
144
+ const processedStyles = new Map<string, ProcessedStyle>()
145
+
146
+ return {
116
147
  captureGraph(reader) {
117
148
  getModuleInfo = reader
118
149
  },
119
150
  captureStyle(id, style) {
120
151
  processedStyles.set(id, style)
121
152
  },
122
- plugin: plugin,
123
- async publishChanged(changedIds) {
124
- const styleChanged = changedIds.some(isGlobalStyleRequest)
125
- const candidatesChanged = changedIds.some((id) => !isCSSRequest(id))
126
- if (!styleChanged && !candidatesChanged) {
127
- return
128
- }
153
+ async render(refreshTailwind) {
129
154
  if (!getModuleInfo) {
130
- throw new Error('WX style graph is unavailable before HMR publication')
155
+ throw new Error('WX style graph is unavailable before publication')
131
156
  }
132
157
 
133
- // Traverse topology exactly once; root refresh and final rendering consume this immutable transaction plan.
158
+ // App first and configured Pages afterward define one deterministic global cascade. The plan also removes stale map
159
+ // entries implicitly: styles no longer reachable from these roots never enter composition.
134
160
  const styleIds = createGraphStylePlan(applicationEntryIds, getModuleInfo, (styleId) =>
135
161
  processedStyles.has(styleId)
136
162
  )
137
- if (candidatesChanged) {
163
+ if (refreshTailwind) {
138
164
  await refreshTailwindStyles(styleIds, processedStyles, transformTailwindRoot)
139
165
  }
166
+
167
+ // Compose browser-facing transformed CSS first, then run one whole-file WX pass. Transforming modules independently
168
+ // would change cross-module cascade behavior and duplicate compatibility work.
140
169
  const css = composeGraphStyleCss(styleIds, (styleId) => requireProcessedStyle(processedStyles, styleId).css)
141
- const wxss = (await transformWxStyle(css)).css
170
+ return (await transformWxStyle(css)).css
171
+ }
172
+ }
173
+ }
174
+
175
+ /**
176
+ * Owns the physical WXSS frontier independently from graph capture and rendering.
177
+ *
178
+ * DevEngine writes complete output itself; incremental HMR does not. Observing complete output before publishing the projection
179
+ * gives both writers one byte frontier, so equality avoids redundant filesystem notifications without pretending the host owns
180
+ * the compiler's write transaction.
181
+ */
182
+ function createStylePublication(outDir: string): Readonly<{
183
+ observeOutput: (output: readonly CompleteOutputFile[]) => void
184
+ publish: (wxss: string) => Promise<void>
185
+ }> {
186
+ /*
187
+ * This mutable value mirrors bytes durable on disk. Complete output adopts the compiler's external write before graph
188
+ * reconciliation; host publication advances it only after an atomic write succeeds or byte equality proves none is needed.
189
+ */
190
+ let publishedWxss: string | undefined
191
+
192
+ return {
193
+ observeOutput(output) {
194
+ // Missing WXSS means DevEngine intentionally reused the existing physical asset. Do not reset the frontier: doing so
195
+ // would force an identical rewrite and a spurious DevTools style event on every omitted complete generation.
196
+ const style = output.find(
197
+ (file): file is Extract<CompleteOutputFile, { type: 'asset' }> =>
198
+ file.type === 'asset' && file.fileName === globalWxssFileName
199
+ )
200
+ if (style) {
201
+ publishedWxss = typeof style.source === 'string' ? style.source : new TextDecoder().decode(style.source)
202
+ }
203
+ },
204
+ async publish(wxss) {
142
205
  if (wxss !== publishedWxss) {
206
+ // writeHmrFile uses atomic replacement; advance the frontier only after durability so a failed write leaves the
207
+ // last known physical generation available for the next reconciliation attempt.
143
208
  await writeHmrFile(outDir, globalWxssFileName, wxss)
144
209
  }
145
- // HMR is the second physical writer; advance the frontier only after its atomic write succeeds or was unnecessary.
146
210
  publishedWxss = wxss
147
211
  }
148
212
  }
149
213
  }
150
214
 
151
- /** Regenerates all reachable Tailwind roots and commits the cache only when every transform succeeds. */
215
+ /**
216
+ * Regenerates all reachable Tailwind roots and commits the cache only when every transform succeeds.
217
+ *
218
+ * Roots run concurrently because they are independent derivations of the same candidate generation. Results remain local until
219
+ * Promise.all fulfills; one failed root therefore preserves every prior root together instead of publishing a mixed generation.
220
+ */
152
221
  async function refreshTailwindStyles(
153
222
  styleIds: readonly string[],
154
223
  processedStyles: Map<string, ProcessedStyle>,
@@ -44,7 +44,7 @@ type HostAction =
44
44
  | Readonly<{ kind: 'listening' }>
45
45
 
46
46
  /** One short trailing-edge window absorbs editor bursts before style preparation and physical Page notification. */
47
- const hmrSettleMilliseconds = 32
47
+ const hmrSettleMilliseconds = 16
48
48
 
49
49
  /**
50
50
  * Creates the wx dev host: the adapter that owns the physical Rolldown DevEngine (created
@@ -228,13 +228,24 @@ export async function createWxDevHost({
228
228
  logWxError(server.config.logger, 'wx dev build failed', action.result)
229
229
  return
230
230
  }
231
- styleCapture.bindOutput(action.result.output)
232
- return rotateBuildSession()
231
+ return reconcileCompleteOutput(action.result.output)
233
232
  case 'listening':
234
233
  return rotateBuildSession()
235
234
  }
236
235
  }
237
236
 
237
+ /**
238
+ * Reconciles graph-complete styles before rotating the App-visible build identity.
239
+ *
240
+ * DevEngine has already written its compiler asset when onOutput fires, but bundled development may have omitted CSS Modules
241
+ * from that asset. Awaiting reconciliation inside the serialized reducer guarantees the subsequent app.wxss rotation—the
242
+ * event that refreshes DevTools—can only expose a generation whose global WXSS already represents the complete App/Page graph.
243
+ */
244
+ async function reconcileCompleteOutput(output: Exclude<DevOutputResult, Error>['output']): Promise<void> {
245
+ await styleCapture.reconcileComplete(output)
246
+ await rotateBuildSession()
247
+ }
248
+
238
249
  /** Applies one runtime receipt to the active physical patch history. */
239
250
  function processReport(report: RuntimeReport): void {
240
251
  // Delayed reports from older builds must never prune the live build's cumulative patch history.