what-compiler 0.14.0 → 0.15.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 (50) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +181 -2
  3. package/babel.d.ts +78 -2
  4. package/dist/babel/auto-selector.min.js +94 -0
  5. package/dist/babel/common.min.js +2053 -0
  6. package/dist/babel/dev-metadata.min.js +106 -0
  7. package/dist/babel/dom.min.js +1669 -0
  8. package/dist/babel/jsx-root.min.js +13 -0
  9. package/dist/babel/lists.min.js +492 -0
  10. package/dist/babel/nesting.min.js +328 -0
  11. package/dist/babel/reactivity.min.js +1218 -0
  12. package/dist/babel/server-actions.min.js +85 -0
  13. package/dist/babel/ssr.min.js +496 -0
  14. package/dist/babel/types.min.js +9 -0
  15. package/dist/babel-plugin.min.js +101 -1
  16. package/dist/file-router.min.js +368 -12
  17. package/dist/framework-files.min.js +62 -0
  18. package/dist/hot.min.js +315 -0
  19. package/dist/index.min.js +13 -414
  20. package/dist/release.min.js +78 -0
  21. package/dist/runtime.min.js +9 -1
  22. package/dist/tables/import-changes.min.js +272 -0
  23. package/dist/tables/markup-rules.min.js +213 -0
  24. package/dist/vite-plugin.min.js +432 -399
  25. package/file-router.d.ts +3 -1
  26. package/index.d.ts +1 -1
  27. package/package.json +11 -2
  28. package/runtime.d.ts +2 -1
  29. package/src/babel/auto-selector.js +248 -0
  30. package/src/babel/common.js +3800 -0
  31. package/src/babel/dev-metadata.js +167 -0
  32. package/src/babel/dom.js +3386 -0
  33. package/src/babel/jsx-root.js +27 -0
  34. package/src/babel/lists.js +704 -0
  35. package/src/babel/nesting.js +260 -0
  36. package/src/babel/reactivity.js +1998 -0
  37. package/src/babel/server-actions.js +144 -0
  38. package/src/babel/ssr.js +870 -0
  39. package/src/babel/types.js +10 -0
  40. package/src/babel-plugin.js +185 -3598
  41. package/src/file-router.js +58 -38
  42. package/src/framework-files.js +106 -0
  43. package/src/hot.js +523 -0
  44. package/src/release.js +127 -0
  45. package/src/runtime.js +7 -7
  46. package/src/tables/import-changes.js +157 -0
  47. package/src/tables/markup-rules.js +388 -0
  48. package/src/vite-plugin.js +460 -175
  49. package/vite.d.ts +47 -3
  50. package/src/error-overlay.js +0 -428
@@ -1,24 +1,37 @@
1
1
  /**
2
2
  * What Framework Vite Plugin
3
3
  *
4
- * 1. Transforms JSX via the What babel plugin
5
- * 2. Provides file-based routing via virtual:what-routes
4
+ * 1. Transforms JSX via the What babel plugin (the server target for SSR transforms)
5
+ * 2. Provides file-based routing via virtual:what-routes (the browser's routes)
6
+ * and virtual:what-routes/server (the same routes with each page's loader,
7
+ * getStaticPaths and page config, for the server entry)
6
8
  * 3. Watches pages directory for route changes
7
- * 4. Component hot updates use an installed replacement hook or reload the
8
- * page; signal/utility files trigger full reload
9
+ * 4. Hot replacement in development (src/hot.js): a saved component is built
10
+ * again in place, module-scope signals and stores keep their values, and
11
+ * only a module that runs statements at its top level reloads the page
9
12
  */
10
13
 
11
14
  import path from 'path';
15
+ import fs from 'node:fs';
12
16
  import { createRequire } from 'node:module';
17
+ import * as babelCore from '@babel/core';
13
18
  import { transformSync } from '@babel/core';
14
19
  import whatBabelPlugin from './babel-plugin.js';
15
- import { generateRoutesModule } from './file-router.js';
16
- import { setupErrorOverlay } from './error-overlay.js';
20
+ import whatHotPlugin, { runsStatements } from './hot.js';
21
+ import { generateRoutesModule, generateServerRoutesModule } from './file-router.js';
22
+ import { IMPORT_CHANGES, SUBPATH_ONLY } from './tables/import-changes.js';
23
+ import { runtimeMismatch } from './release.js';
24
+ import { isFrameworkFile } from './framework-files.js';
17
25
 
18
26
  const VIRTUAL_ROUTES_ID = 'virtual:what-routes';
19
27
  const RESOLVED_VIRTUAL_ID = '\0' + VIRTUAL_ROUTES_ID;
28
+ const VIRTUAL_SERVER_ROUTES_ID = 'virtual:what-routes/server';
29
+ const RESOLVED_VIRTUAL_SERVER_ID = '\0' + VIRTUAL_SERVER_ROUTES_ID;
20
30
  const SERVER_ACTION_MODULE_RE = /(?:from\s*['"](?:what-framework\/server|what-server(?:\/actions)?)['"]|import\s*['"](?:what-framework\/server|what-server(?:\/actions)?)['"])/;
21
31
  const SCRIPT_MODULE_RE = /\.[cm]?[jt]sx?$/;
32
+ const JSX_MODULE_RE = /\.[jt]sx$/;
33
+ // what-react's mixed JSX plugin ends a React file's output with this comment.
34
+ const REACT_SOURCE_MARKER = '/* what-react: react source */';
22
35
 
23
36
  function patternMatches(pattern, value) {
24
37
  if (!pattern) return false;
@@ -70,79 +83,229 @@ async function detectViteVersion(root) {
70
83
  }
71
84
  }
72
85
 
73
- // Pattern: exported function starting with uppercase = component
74
- const COMPONENT_EXPORT_RE = /export\s+(?:default\s+)?function\s+([A-Z]\w*)/;
75
- // Pattern: files that are likely signal/store/utility files
76
- const UTILITY_FILE_RE = /(?:store|signal|state|context|util|helper|lib|config)\b/i;
77
-
78
- // --- SSR guard --------------------------------------------------------------
79
- //
80
- // A module that what-compiler lowers cannot run on a server, and the failures it
81
- // produces without this guard both name the wrong thing.
86
+ // --- Server builds ---
82
87
  //
83
- // The lowering emits a module-scope `const _tmpl$0 = _$template("<div>...")`,
84
- // and `_$template` calls `document.createElement('template')` EAGERLY. So the
85
- // module throws `ReferenceError: document is not defined` at IMPORT time, before
86
- // any render function runs, with a stack that points into what-core rather than
87
- // at the file the developer wrote. If a DOM shim happens to exist, the component
88
- // instead returns a cloned Element and what-server's assertSafeTag reports
89
- // ERR_COMPILED_JSX_IN_SSR.
88
+ // When Vite transforms a module for the server (SSR or the 'ssr' environment),
89
+ // JSX is compiled with what-compiler's server target (`generate: "ssr"`):
90
+ // string templates rendered by what-server/ssr-runtime, which every
91
+ // what-server renderer accepts. Two options change that:
92
+ // - `ssr: false` keeps compiled JSX out of server bundles: a server transform
93
+ // whose output would build DOM is refused with ERR_COMPILED_JSX_IN_SSR,
94
+ // naming the file, instead of shipping a module that throws "document is
95
+ // not defined" the first time it renders.
96
+ // - `ssrGuard: false` compiles every server transform for the DOM, with or
97
+ // without `ssr: false`, for a process that installs a DOM on purpose. The likeliest one is a test runner:
98
+ // Vitest applies an SSR transform under `environment: 'node'`, so a
99
+ // component test that mounts compiled JSX into a DOM shim needs it.
100
+ // Whether output builds DOM is reported by the compiler itself
101
+ // (`metadata.whatBuildsDom`: a template clone or a component call), so a
102
+ // JSX-free server-action module and a hydrate()-only module still compile.
103
+
104
+ // --- Hydration ---
90
105
  //
91
- // Both are runtime failures for something decidable at build time: if Vite is
92
- // transforming this module for the SSR environment and the transform emitted
93
- // DOM-building code, the resulting bundle cannot work. Fail here, name the file,
94
- // and name the two configurations that DO server-render, rather than emitting a
95
- // bundle whose only possible behaviour is to crash.
106
+ // A page the server rendered is adopted by hydrate() only when the client's
107
+ // JSX is compiled for it (what-compiler's `hydratable` option: templates that
108
+ // claim the server's nodes instead of cloning). Its cost is client code that
109
+ // steps through each template rather than walking it by path, so the plugin
110
+ // compiles that way only for a project that renders on the server: one whose
111
+ // Vite config says so (`appType: 'custom'`, the shape of every SSR setup in
112
+ // Vite's guide; an SSR build; or a client build that writes an SSR manifest,
113
+ // `vite build --ssrManifest`, as the guide's production client build does),
114
+ // unless `hydratable` is set. A client build with none of these (a project
115
+ // whose dev server passes `appType: 'custom'` inline but whose `vite build`
116
+ // does not) needs `hydratable: true`. Hydrating
117
+ // server markup with JSX compiled without it reports an ERR_HYDRATION_MISMATCH
118
+ // of kind not-hydratable and renders the page again on the client.
119
+
120
+ // --- What it compiles ---
96
121
  //
97
- // This is a guard, not a feature. It does not make compiled JSX server-render;
98
- // what-compiler has no hydratable/SSR codegen target. See
99
- // docs/SSR-COMPILED-JSX-SCOPING.md for the seams and the staged plan.
122
+ // App JSX and scripts with server actions or development metadata, plus
123
+ // dependency JSX when its package declares What or compileDependencies opts
124
+ // it in. Framework sources retain their separate rules (framework-files.js).
100
125
 
101
- // The two compiler-generated locals that make a module client-only.
102
- //
103
- // _$template — hoisted to module scope and calls
104
- // document.createElement('template') EAGERLY, so the
105
- // module throws at import time on a server.
106
- // _$createComponent — runs the component and builds its DOM at call time.
107
- //
108
- // Deliberately NOT in this list: _$componentVNode, which is _$createComponent
109
- // stopping one step short of createDOM (what-core render.js). A module whose
110
- // only JSX is the argument of a hydrate() call emits that and nothing else, and
111
- // it is import-safe, so flagging it would be wrong. The other helpers
112
- // (_$insert, _$spread, _$setProp, ...) are all reached only THROUGH a template,
113
- // so they add no cases and would only widen the blast radius.
126
+ /**
127
+ * @param {string} file
128
+ * @param {string} root
129
+ * @param {Map<string, { name: string, declaresWhat: boolean } | null>} cache
130
+ */
131
+ function dependencyPackage(file, root, cache) {
132
+ if (!path.isAbsolute(file)) return null;
133
+ const inModules = file.includes('/node_modules/');
134
+ if (!inModules && (!root || file.startsWith(root + '/'))) return null;
135
+ let dir = path.dirname(file);
136
+ const visited = [];
137
+ /** @type {{ name: string, declaresWhat: boolean } | null} */
138
+ let found = null;
139
+ while (dir !== path.dirname(dir) && !dir.endsWith('/node_modules')) {
140
+ const known = cache.get(dir);
141
+ if (known !== undefined) {
142
+ found = known;
143
+ break;
144
+ }
145
+ visited.push(dir);
146
+ try {
147
+ const pkg = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));
148
+ if (typeof pkg.name === 'string') {
149
+ const declaresWhat = [pkg.dependencies, pkg.peerDependencies].some(
150
+ (deps) => deps && (Object.hasOwn(deps, 'what-framework') || Object.hasOwn(deps, 'what-core')),
151
+ );
152
+ found = { name: pkg.name, declaresWhat };
153
+ break;
154
+ }
155
+ } catch { /* A module can be nested below its package manifest. */ }
156
+ dir = path.dirname(dir);
157
+ }
158
+ for (const dir of visited) cache.set(dir, found);
159
+ return found;
160
+ }
161
+
162
+ /** @returns {{ line: number, column: number } | null} */
163
+ function dependencyJsx(code) {
164
+ if (!/<\s*(?:[\p{ID_Start}$]|>)/u.test(code)) return null;
165
+ /** @type {{ line: number, column: number } | null} */
166
+ let location = null;
167
+ try {
168
+ transformSync(code, {
169
+ ast: false, code: false, configFile: false, babelrc: false,
170
+ parserOpts: { plugins: ['jsx', 'typescript'] },
171
+ plugins: [() => ({
172
+ visitor: {
173
+ 'JSXElement|JSXFragment'(jsx) {
174
+ location = jsx.node.loc?.start ?? null;
175
+ jsx.stop();
176
+ },
177
+ },
178
+ })],
179
+ });
180
+ } catch { /* Leave syntax errors in the dependency to the bundler. */ }
181
+ return location;
182
+ }
183
+
184
+ // --- Development locations ---
114
185
  //
115
- // The `_$` prefix is compiler-generated and never written by hand, which is what
116
- // makes matching on the name safe.
117
- const DOM_BUILDING_LOCALS = /\b_\$(?:template|createComponent)\b/;
186
+ // Vite transforms .jsx/.tsx with esbuild (oxc on Vite 8) before this plugin
187
+ // runs, and that reprints the file: comments go, TypeScript is stripped, lines
188
+ // move. A development location (a diagnostic's `at`, what devtools show) is
189
+ // mapped back through the transforms' combined source map to the line and
190
+ // column as written.
191
+ let traceMapping;
192
+ function loadTraceMapping() {
193
+ if (traceMapping !== undefined) return traceMapping;
194
+ const here = createRequire(import.meta.url);
195
+ const attempts = [
196
+ () => here('@jridgewell/trace-mapping'),
197
+ // @babel/core depends on it (through @jridgewell/remapping), reachable
198
+ // from there under a strict layout.
199
+ () => createRequire(createRequire(here.resolve('@babel/core')).resolve('@jridgewell/remapping'))('@jridgewell/trace-mapping'),
200
+ ];
201
+ traceMapping = null;
202
+ for (const attempt of attempts) {
203
+ try { traceMapping = attempt(); break; } catch { /* next */ }
204
+ }
205
+ return traceMapping;
206
+ }
207
+
208
+ function sourceLocFor(ctx) {
209
+ const tm = loadTraceMapping();
210
+ if (tm === null || typeof ctx?.getCombinedSourcemap !== 'function') return undefined;
211
+ let map;
212
+ try { map = ctx.getCombinedSourcemap(); } catch { return undefined; }
213
+ if (!map || !map.mappings) return undefined;
214
+ const traced = new tm.TraceMap(map);
215
+ return (line, column) => {
216
+ const at = tm.originalPositionFor(traced, { line, column });
217
+ return at && at.line != null ? { line: at.line, column: at.column } : null;
218
+ };
219
+ }
220
+
221
+ // In development a .tsx file is served as this plugin prints it too, its
222
+ // lines where the source has them, when @babel/plugin-transform-typescript
223
+ // (or @babel/preset-typescript, which depends on it) is installed: the types
224
+ // are stripped in the same Babel pass as the JSX, so the bundler's
225
+ // transformer, which would reprint the file first, skips .tsx as it skips
226
+ // .jsx. Without it, .tsx goes through the bundler's transformer.
227
+ function loadTypeScriptPlugin(root) {
228
+ const attempts = [
229
+ () => createRequire(path.resolve(root, 'package.json'))('@babel/plugin-transform-typescript'),
230
+ () => {
231
+ const fromApp = createRequire(path.resolve(root, 'package.json'));
232
+ return createRequire(fromApp.resolve('@babel/preset-typescript'))('@babel/plugin-transform-typescript');
233
+ },
234
+ ];
235
+ for (const attempt of attempts) {
236
+ try {
237
+ const mod = attempt();
238
+ return mod.default ?? mod;
239
+ } catch { /* next */ }
240
+ }
241
+ return null;
242
+ }
118
243
 
119
- function buildsDom(outputCode) {
120
- return DOM_BUILDING_LOCALS.test(outputCode);
244
+ function rendersOnServer(config) {
245
+ return config.appType === 'custom' || Boolean(config.build && (config.build.ssr || config.build.ssrManifest));
121
246
  }
122
247
 
123
248
  function ssrGuardError(id) {
124
249
  // ERROR_CODES.COMPILED_JSX_IN_SSR
125
250
  return Object.assign(
126
251
  new Error(
127
- `[what-compiler] ${id} is being compiled for the server, but what-compiler's ` +
128
- 'JSX output is client-only. It lowers JSX to module-scope _$template() calls ' +
129
- 'that run document.createElement() at import time, so this module throws ' +
130
- '"document is not defined" the moment a server imports it.\n\n' +
131
- 'Server-rendered views have two supported spellings:\n' +
132
- ' 1. Author them with h() from what-framework.\n' +
133
- ' 2. Compile them with the automatic JSX runtime instead of what-compiler ' +
134
- '(jsxImportSource: "what-framework"), which emits h() calls that ' +
135
- 'renderToString and renderToHydratableString understand.\n\n' +
136
- 'If a DOM already exists in this process on purpose, set ssrGuard: false ' +
137
- 'on the plugin. The likeliest reason is a test runner: Vitest applies an ' +
138
- "SSR transform under `environment: 'node'`, so a component test that " +
139
- 'shims a DOM itself lands here. Note that with the guard off the result ' +
140
- 'is a full client render, not SSR.'
252
+ `[what-compiler] ${id} is being compiled for the server with ssr: false, so ` +
253
+ "what-compiler emits its client output, which builds DOM: _$template() calls that " +
254
+ 'parse their markup with document.createElement(), so this module throws ' +
255
+ '"document is not defined" the first time a server renders it.\n\n' +
256
+ 'Remove ssr: false to compile server modules with what-compiler\'s server ' +
257
+ 'target, which what-server renders directly. Or author server views with h() ' +
258
+ 'from what-framework, or compile them with the automatic JSX runtime ' +
259
+ '(jsxImportSource: "what-framework").\n\n' +
260
+ 'If a DOM already exists in this process on purpose (a test runner such as ' +
261
+ "Vitest applies an SSR transform under `environment: 'node'`), set " +
262
+ 'ssrGuard: false to compile server transforms for the DOM.'
141
263
  ),
142
264
  { code: 'ERR_COMPILED_JSX_IN_SSR', id, plugin: 'vite-plugin-what' },
143
265
  );
144
266
  }
145
267
 
268
+ // --- Vnode adoption ---
269
+ //
270
+ // Compiled JSX makes no vnode but the component one a hydrate() root lowers
271
+ // to. Every other kind (an h() element, <Suspense>, <ErrorBoundary>, a
272
+ // <Portal>) is made by what-core's vnode producers (h.js), and hydrate()
273
+ // reaches their adoption (render.js _adoptVNodeKinds, and _adoptVNodeRows for
274
+ // a region's keyed rows) through src/vnode-adoption.js, so every program that
275
+ // hydrates carries it. So it does the carrying of what the user changed in a
276
+ // form before hydration into the fields built before the walk reached them
277
+ // (render.js _carryFields), which that file applies once a compiled module
278
+ // whose JSX can build a field (`_$carryFields()`) or a vnode producer is in
279
+ // the program. In a client build compiled for hydration, this stand-in takes
280
+ // that file's place (in any copy of what-core, from its source or either
281
+ // dist tier): installing the vnode renderer, which every producer does when
282
+ // it is defined, installs the adoption and the carrying, and `_$carryFields()`
283
+ // installs the carrying. A program whose code makes no such vnode and builds
284
+ // no field bundles none of it, and one that does adopts its vnodes and
285
+ // carries its fields as before. Both are vars: a producer installs them while
286
+ // the import cycle this module is in may not have evaluated the module yet.
287
+ const VNODE_ADOPTION_FILE = /[\\/](?:src|dist)[\\/]vnode-adoption(\.min)?\.js$/;
288
+
289
+ function vnodeAdoptionStandIn(id) {
290
+ const file = id.replace(/[?#].*$/, '');
291
+ const match = VNODE_ADOPTION_FILE.exec(file);
292
+ if (match === null || !isFrameworkFile(file, fs, 'what-core')) return null;
293
+ const ext = match[1] ? '.min.js' : '.js';
294
+ return `import { _adoptVNodeKinds, _adoptVNodeRows, _carryFields } from './render${ext}';
295
+ import { _installVNodeRuntime } from './vnode-renderer${ext}';
296
+ export var adoptVNodeKinds, adoptVNodeRows, fieldCarry;
297
+ export function installFieldCarry() {
298
+ fieldCarry = _carryFields;
299
+ }
300
+ export function installVNodeRuntime(render, keyedRows, setProp, refuses) {
301
+ adoptVNodeKinds = _adoptVNodeKinds;
302
+ adoptVNodeRows = _adoptVNodeRows;
303
+ fieldCarry = _carryFields;
304
+ _installVNodeRuntime(render, keyedRows, setProp, refuses);
305
+ }
306
+ `;
307
+ }
308
+
146
309
  // Vite reports "this transform is for the server" in two ways depending on its
147
310
  // major: the third `transform` argument (`{ ssr: true }`) on every version, and
148
311
  // the Environment API (`this.environment.name === 'ssr'`) from Vite 6. Read both
@@ -157,8 +320,12 @@ export default function whatVitePlugin(options = {}) {
157
320
  const {
158
321
  // File extensions to process
159
322
  include = /\.[jt]sx$/,
160
- // Files to exclude
161
- exclude = /node_modules/,
323
+ // Files to exclude: a node_modules directory, not a name that holds the
324
+ // word (`my_node_modules_backup/`)
325
+ exclude = /\/node_modules\//,
326
+ // A dependency's files to compile as the app's: under node_modules, or of
327
+ // one of What's own packages. See "What it compiles".
328
+ compileDependencies = null,
162
329
  // Enable source maps
163
330
  sourceMaps = true,
164
331
  // Production optimizations
@@ -172,16 +339,48 @@ export default function whatVitePlugin(options = {}) {
172
339
  // against package sources instead — needed e.g. in a monorepo where
173
340
  // workspace-linked dist/ output may be stale or absent. See config() below.
174
341
  prodBundles = true,
175
- // Refuse to lower JSX for a module in the SSR graph. See ssrGuardError().
176
- // Set to false only if you have installed a DOM in the server process and
177
- // accept that the render is a full client render, not SSR.
342
+ // Compile server transforms with the server target. See "Server builds".
343
+ ssr = true,
344
+ // With ssr: false, refuse server transforms whose output builds DOM; false
345
+ // compiles them for the DOM instead (a process that installs a DOM).
178
346
  ssrGuard = true,
347
+ // Rewrite `selected() === row.id` in keyed .map() rows to a createSelector
348
+ // lookup. Set to false to keep every comparison as written.
349
+ autoSelector = true,
350
+ // Compile client JSX so that hydrate() adopts server-rendered markup.
351
+ // 'auto' does when the project renders on the server. See "Hydration".
352
+ hydratable = 'auto',
353
+ // Print the compiler's notes on correct code (what the auto-selector
354
+ // rewrote, that <For> and a keyed .map() compile alike). Warnings about
355
+ // code that misbehaves print either way.
356
+ verbose = false,
179
357
  } = options;
180
358
 
181
359
  let rootDir = '';
182
360
  let pagesDir = '';
183
361
  let isDevMode = false;
362
+ // Hot replacement: a dev server whose HMR is on (src/hot.js).
363
+ let hotServer = false;
364
+ // @babel/plugin-transform-typescript, in development (loadTypeScriptPlugin).
365
+ let typeScriptPlugin = null;
366
+ let hydratableOutput = hydratable === true;
184
367
  const actionIdRegistry = new Map();
368
+ const dependencyPackages = new Map();
369
+ // Development: each browser module's hot mode (src/hot.js), by file.
370
+ /** @type {Map<string, string>} */
371
+ const hotModes = new Map();
372
+ // Whether an update of `mod` runs a module that runs statements at its top
373
+ // level again, on its way up to the modules that accept it.
374
+ const reachesStatements = (mod, seen) => {
375
+ if (mod.isSelfAccepting || seen.has(mod)) return false;
376
+ seen.add(mod);
377
+ for (const importer of mod.importers) {
378
+ if (importer.isSelfAccepting) continue;
379
+ if (importer.file && hotModes.get(importer.file) === 'reload') return true;
380
+ if (reachesStatements(importer, seen)) return true;
381
+ }
382
+ return false;
383
+ };
185
384
 
186
385
  function registerActionId(metadata) {
187
386
  const existing = actionIdRegistry.get(metadata.id);
@@ -212,66 +411,153 @@ export default function whatVitePlugin(options = {}) {
212
411
  : cleanFilename;
213
412
  }
214
413
 
215
- return {
414
+ // A dependency pre-bundled in development no longer has its source package
415
+ // path by the time Vite runs ordinary transforms. Compile it in the
416
+ // optimizer while package metadata and the original location are available.
417
+ /** @this {object | undefined} */
418
+ function optimizeDependency(code, id) {
419
+ if (!SCRIPT_MODULE_RE.test(id) || !dependencyPackage(id, rootDir, dependencyPackages)) return null;
420
+ return plugin.transform.call(this, code, id, { optimizer: true });
421
+ }
422
+
423
+ const plugin = {
216
424
  name: 'vite-plugin-what',
217
425
 
218
426
  configResolved(config) {
427
+ // What the app's compiled modules will import: the runtime of this
428
+ // compiler's release, or ERR_COMPILER_RUNTIME_MISMATCH before any build.
429
+ const mismatch = runtimeMismatch(config.root, fs);
430
+ if (mismatch) throw mismatch;
219
431
  rootDir = config.root;
432
+ dependencyPackages.clear();
220
433
  pagesDir = path.resolve(rootDir, pages);
221
434
  isDevMode = config.command === 'serve';
435
+ hotServer = hot && isDevMode && !production && !(config.server && config.server.hmr === false);
436
+ hydratableOutput = hydratable === 'auto' ? rendersOnServer(config) : hydratable === true;
222
437
  },
223
438
 
224
439
  configureServer(devServer) {
225
- // Set up What-branded error overlay
226
- setupErrorOverlay(devServer);
227
-
228
- // Watch the pages directory for file additions/removals
229
- devServer.watcher.on('add', (file) => {
230
- if (file.startsWith(pagesDir)) {
231
- // Invalidate the virtual routes module
232
- const mod = devServer.moduleGraph.getModuleById(RESOLVED_VIRTUAL_ID);
440
+ // A page added or removed changes both routes modules.
441
+ const pagesChanged = () => {
442
+ let loaded = false;
443
+ for (const id of [RESOLVED_VIRTUAL_ID, RESOLVED_VIRTUAL_SERVER_ID]) {
444
+ const mod = devServer.moduleGraph.getModuleById(id);
233
445
  if (mod) {
234
446
  devServer.moduleGraph.invalidateModule(mod);
235
- devServer.ws.send({ type: 'full-reload' });
447
+ loaded = true;
236
448
  }
237
449
  }
450
+ if (loaded) devServer.ws.send({ type: 'full-reload' });
451
+ };
452
+ // Watch the pages directory for file additions/removals
453
+ devServer.watcher.on('add', (file) => {
454
+ if (file.startsWith(pagesDir)) pagesChanged();
238
455
  });
239
456
 
240
457
  devServer.watcher.on('unlink', (file) => {
241
458
  // Vite will never transform an unlinked module again, so explicitly
242
459
  // release its IDs before handling the narrower pages refresh path.
243
460
  clearActionIdsForFile(actionFilenameForFile(file));
244
- if (file.startsWith(pagesDir)) {
245
- const mod = devServer.moduleGraph.getModuleById(RESOLVED_VIRTUAL_ID);
246
- if (mod) {
247
- devServer.moduleGraph.invalidateModule(mod);
248
- devServer.ws.send({ type: 'full-reload' });
249
- }
250
- }
461
+ if (file.startsWith(pagesDir)) pagesChanged();
251
462
  });
252
463
  },
253
464
 
254
- // Resolve virtual module
465
+ // Resolve the virtual routes modules
255
466
  resolveId(id) {
256
467
  if (id === VIRTUAL_ROUTES_ID) {
257
468
  return RESOLVED_VIRTUAL_ID;
258
469
  }
470
+ if (id === VIRTUAL_SERVER_ROUTES_ID) {
471
+ return RESOLVED_VIRTUAL_SERVER_ID;
472
+ }
259
473
  },
260
474
 
261
- // Generate the routes module
262
- load(id) {
475
+ // Generate the routes modules; in a client build compiled for hydration,
476
+ // what-core's vnode adoption stands in (see "Vnode adoption").
477
+ load(id, loadOptions) {
263
478
  if (id === RESOLVED_VIRTUAL_ID) {
264
479
  return generateRoutesModule(pagesDir, rootDir);
265
480
  }
481
+ if (id === RESOLVED_VIRTUAL_SERVER_ID) {
482
+ return generateServerRoutesModule(pagesDir, rootDir);
483
+ }
484
+ if (hydratableOutput && !isSsrTransform(loadOptions, this)) return vnodeAdoptionStandIn(id);
266
485
  },
267
486
 
268
487
  // Transform JSX files
269
488
  transform(code, id, transformOptions) {
270
489
  const cleanId = id.replace(/[?#].*$/, '');
271
- const hasJsx = patternMatches(include, cleanId);
272
- const isScriptModule = SCRIPT_MODULE_RE.test(cleanId);
490
+ const optedIn = compileDependencies !== null && patternMatches(compileDependencies, cleanId);
491
+ // A React file of a mixed app is lowered by what-react already.
492
+ // A React file of a mixed app (what-react's plugin, MIXED.md): its JSX
493
+ // is lowered to what-react already and follows React's rules. Its hot
494
+ // updates are what-react's (handleHotUpdate leaves them alone).
495
+ if (code.includes(REACT_SOURCE_MARKER)) {
496
+ hotModes.delete(cleanId);
497
+ return null;
498
+ }
499
+ if (!optedIn && options.exclude !== undefined && patternMatches(exclude, cleanId)) return null;
500
+
501
+ const inModules = cleanId.includes('/node_modules/');
502
+ const frameworkFile = !optedIn && isFrameworkFile(cleanId, fs);
503
+ if (frameworkFile && (inModules || !JSX_MODULE_RE.test(cleanId))) return null;
504
+
505
+ const isScriptModule = !frameworkFile && SCRIPT_MODULE_RE.test(cleanId);
506
+ const dependency = isScriptModule ? dependencyPackage(cleanId, rootDir, dependencyPackages) : null;
507
+ const jsxLocation = isScriptModule && (dependency || inModules || optedIn) ? dependencyJsx(code) : null;
508
+ const autoCompile = jsxLocation !== null && dependency?.declaresWhat === true;
509
+ if (!optedIn && !autoCompile && (dependency || inModules)) {
510
+ if (jsxLocation === null) return null;
511
+ // ERROR_CODES.DEPENDENCY_JSX
512
+ throw Object.assign(
513
+ new Error(
514
+ `[what-compiler] ERR_DEPENDENCY_JSX: ${dependency?.name ?? cleanId} ships JSX in ${cleanId}. ` +
515
+ 'Declare what-framework or what-core in the package manifest, or opt the file into what({ compileDependencies: … }).'
516
+ ),
517
+ { code: 'ERR_DEPENDENCY_JSX', id, plugin: 'vite-plugin-what', loc: { file: cleanId, line: jsxLocation.line, column: jsxLocation.column } },
518
+ );
519
+ }
520
+ const hasJsx = patternMatches(include, cleanId) || jsxLocation !== null;
273
521
  const hasServerActions = isScriptModule && SERVER_ACTION_MODULE_RE.test(code);
274
- if (exclude && patternMatches(exclude, cleanId)) return null;
522
+
523
+ // A name the root entry (what-framework, what-core) no longer exports
524
+ // fails here with the answer IMPORT_CHANGES records for it
525
+ // (ERR_MOVED_IMPORT), not later with the bundler's "is not exported", and
526
+ // so does a name only a subpath exports (SUBPATH_ONLY: the router's). The
527
+ // regex only picks candidates and Babel's parse decides, so an import
528
+ // statement quoted in a string never fails a build.
529
+ const changeFor = (name) => IMPORT_CHANGES.find((c) => (c.name === name && !c.onRoot) || c.as === name)
530
+ || SUBPATH_ONLY.find((c) => c.name === name);
531
+ const rootClauses = isScriptModule ? [...code.matchAll(/\b(?:import|export)\s+(?:type\s+)?(?:[\w$]+\s*,\s*)?\{([^}]*)\}\s*from\s*['"]what-(?:framework|core)['"]/g)] : [];
532
+ if (rootClauses.some(([, names]) => names.split(',').some((n) => changeFor(n.trim().replace(/^type\s+/, '').split(/\s+as\s+/)[0])))) {
533
+ let body = [];
534
+ try {
535
+ body = transformSync(code, { ast: true, code: false, configFile: false, babelrc: false, parserOpts: { plugins: ['jsx', 'typescript'] } }).ast.program.body;
536
+ } catch {
537
+ // Unparseable here; the rest of the pipeline reports the syntax error.
538
+ }
539
+ const moved = [];
540
+ for (const node of body) {
541
+ const source = node.source && node.source.value;
542
+ if ((source !== 'what-framework' && source !== 'what-core') || node.importKind === 'type' || node.exportKind === 'type') continue;
543
+ for (const spec of node.specifiers || []) {
544
+ const remote = spec.type === 'ImportSpecifier' ? spec.imported : spec.type === 'ExportSpecifier' ? spec.local : null;
545
+ const name = remote && spec.importKind !== 'type' && spec.exportKind !== 'type' ? remote.name ?? remote.value : null;
546
+ const change = name && changeFor(name);
547
+ if (change) moved.push({ start: spec.loc.start, text: `"${name}" is not exported by ${source}. ${change.answer}`, changed: IMPORT_CHANGES.includes(change) });
548
+ }
549
+ }
550
+ if (moved.length) {
551
+ throw Object.assign(
552
+ new Error(
553
+ `[what-compiler] ERR_MOVED_IMPORT in ${path.relative(rootDir || process.cwd(), cleanId)}:\n` +
554
+ moved.map((m) => ` ${m.text}`).join('\n') +
555
+ (moved.some((m) => m.changed) ? "\neslint --fix with eslint-plugin-what's no-moved-imports rule rewrites the moved names; UPGRADING.md lists every change." : '')
556
+ ),
557
+ { code: 'ERR_MOVED_IMPORT', id, plugin: 'vite-plugin-what', loc: { file: cleanId, line: moved[0].start.line, column: moved[0].start.column } },
558
+ );
559
+ }
560
+ }
275
561
 
276
562
  // Clear before either transforming the replacement or returning early.
277
563
  // Otherwise a .ts/.js module that removes its final action import leaves
@@ -280,15 +566,22 @@ export default function whatVitePlugin(options = {}) {
280
566
  // Server action metadata is required in plain .js/.ts modules too, so
281
567
  // those modules pass through the same hermetic Babel transform even when
282
568
  // they contain no JSX.
283
- if (!hasJsx && !hasServerActions) return null;
569
+ const hasDevMetadata = isScriptModule && isDevMode && !production && /['"]what-(?:core|framework)['"]/.test(code);
570
+ if (!hasJsx && !hasServerActions && !hasDevMetadata) return null;
284
571
 
285
- const guardSsr = ssrGuard && isSsrTransform(transformOptions, this);
572
+ const serverTransform = isSsrTransform(transformOptions, this);
573
+ const generate = serverTransform && ssr !== false && ssrGuard !== false ? 'ssr' : 'dom';
574
+ const guardSsr = serverTransform && ssr === false && ssrGuard !== false;
575
+ // Hot replacement drives the browser: a server module never gets it.
576
+ const hotModule = hotServer && !serverTransform && !frameworkFile && !transformOptions?.optimizer;
286
577
 
287
578
  try {
288
579
  const result = transformSync(code, {
289
580
  filename: id,
290
581
  sourceMaps,
291
- // Hermetic transform (SPRINT v0.11 C7): never load the project's
582
+ // Each statement on its source line in development (see config()).
583
+ retainLines: isDevMode && !production,
584
+ // Hermetic transform: never load the project's
292
585
  // babel.config.js/.babelrc. A user's React preset or unrelated
293
586
  // plugins corrupting What's JSX output is a debugging nightmare —
294
587
  // and scanning the disk for config files on every transform is
@@ -296,10 +589,19 @@ export default function whatVitePlugin(options = {}) {
296
589
  configFile: false,
297
590
  babelrc: false,
298
591
  plugins: [
592
+ ...(hotModule ? [[whatHotPlugin, { file: actionFilenameForFile(cleanId), onMode: (mode) => hotModes.set(cleanId, mode) }]] : []),
593
+ ...(typeScriptPlugin !== null && cleanId.endsWith('.tsx') ? [[typeScriptPlugin, { isTSX: true, allowDeclareFields: true }]] : []),
299
594
  [whatBabelPlugin, {
595
+ generate,
596
+ hydratable: generate === 'dom' && hydratableOutput,
300
597
  production,
598
+ devMetadata: isDevMode && !production,
599
+ sourceLoc: isDevMode && !production ? sourceLocFor(this) : undefined,
600
+ autoSelector,
601
+ verbose,
301
602
  projectRoot: rootDir || process.cwd(),
302
603
  onActionId: registerActionId,
604
+ appSource: optedIn || autoCompile,
303
605
  }]
304
606
  ],
305
607
  parserOpts: {
@@ -311,29 +613,14 @@ export default function whatVitePlugin(options = {}) {
311
613
  return null;
312
614
  }
313
615
 
314
- let outputCode = result.code;
315
-
316
- // Decided from the OUTPUT, not the filename. `.jsx` in the include
317
- // pattern says the file MAY contain JSX, not that any was lowered, and a
318
- // .js/.ts module compiled here purely for its server-action metadata
319
- // emits nothing DOM-building at all. Both would be false positives.
320
- // buildsDom() asks the only question that matters: did this transform
321
- // emit code that constructs DOM?
322
- if (guardSsr && buildsDom(outputCode)) {
616
+ // Decided from the OUTPUT, not the filename: `.jsx` in the include
617
+ // pattern says the file MAY contain JSX, not that any was lowered.
618
+ if (guardSsr && result.metadata && result.metadata.whatBuildsDom) {
323
619
  throw ssrGuardError(cleanId);
324
620
  }
325
621
 
326
- // HMR: append hot boundary code for component files in dev mode
327
- if (hot && isDevMode && !production) {
328
- const isComponentFile = isComponentModule(code, id);
329
-
330
- if (isComponentFile) {
331
- outputCode += generateHMRBoundary(id);
332
- }
333
- }
334
-
335
622
  return {
336
- code: outputCode,
623
+ code: result.code,
337
624
  map: result.map
338
625
  };
339
626
  } catch (error) {
@@ -353,29 +640,21 @@ export default function whatVitePlugin(options = {}) {
353
640
  }
354
641
  },
355
642
 
356
- // HMR: detect component vs utility files and handle accordingly
357
- handleHotUpdate({ file, server: devServer}) {
358
- if (!hot) return;
359
-
360
- // Only handle files we process
361
- if (!include.test(file)) return;
362
- if (exclude && exclude.test(file)) return;
363
-
364
- // Utility/signal/store files: trigger full reload
365
- // These files may export signals used across multiple components
366
- if (isUtilityFile(file)) {
367
- devServer.ws.send({ type: 'full-reload' });
368
- return [];
369
- }
370
-
371
- // Component files: let Vite handle HMR normally (our boundary code handles it)
372
- // Return undefined to let Vite's default HMR proceed
373
- return;
643
+ // Hot replacement: Vite updates the modules that accept the edit (each
644
+ // module's mode, src/hot.js). A module that runs statements at its top
645
+ // level, edited or run again on the way to the modules that accept the
646
+ // update, reloads the page instead: running it again would run them twice.
647
+ async handleHotUpdate({ file, modules, read, server: devServer }) {
648
+ if (!hotServer || !hotModes.has(file)) return;
649
+ const reload = runsStatements(babelCore, await read(), file) || modules.some((mod) => reachesStatements(mod, new Set()));
650
+ if (!reload) return;
651
+ devServer.ws.send({ type: 'full-reload' });
652
+ return [];
374
653
  },
375
654
 
376
655
  // Configure for development
377
656
  async config(config, { mode, command }) {
378
- // SPRINT v0.11 C7: make the `production` exports condition reachable.
657
+ // Make the `production` exports condition reachable.
379
658
  // what-framework/what-core ship pre-minified production bundles behind
380
659
  // the `production` condition in their exports maps, but Vite's default
381
660
  // resolve conditions never include `production` — so production builds
@@ -393,6 +672,11 @@ export default function whatVitePlugin(options = {}) {
393
672
  // of the defaults), so import/browser/default resolution for other
394
673
  // packages is unaffected.
395
674
  const useProdCondition = command === 'build' && mode === 'production' && prodBundles;
675
+ // Every build except `--mode development` is What's production tier,
676
+ // whichever files it resolves: defining __WHAT_DEV__ folds the
677
+ // development flag (what-core/src/env.js) to false, so source builds and
678
+ // aliased checkouts lose their dev branches exactly as dist/*.min.js does.
679
+ const productionBuild = command === 'build' && mode !== 'development';
396
680
  // Preserve JSX so our babel plugin handles it — don't let the bundler's
397
681
  // built-in transformer (esbuild on Vite ≤7, oxc on Vite 8+) touch it.
398
682
  // jsxPreserveConfig picks the right option key for the running version.
@@ -400,10 +684,53 @@ export default function whatVitePlugin(options = {}) {
400
684
  rolldownVersion: this?.meta?.rolldownVersion,
401
685
  viteVersion: await detectViteVersion(config.root),
402
686
  });
687
+ // The dev server serves a .jsx file as this plugin prints it, lines
688
+ // kept where the source has them (retainLines in transform): a stack
689
+ // trace, and a location the runtime reads from one (ERR_MISSING_SIGNAL_READ,
690
+ // an effect's call site), then names the line written. The bundler's
691
+ // transformer would reprint the file first, without its blank lines,
692
+ // and it has nothing else to do for one (no types, JSX preserved), so
693
+ // it skips .jsx here, unless the app sets what it skips. A .tsx file
694
+ // skips it too when this plugin strips its types (loadTypeScriptPlugin).
695
+ const transformer = jsxPreserve.oxc ? 'oxc' : 'esbuild';
696
+ if (command === 'serve' && !production) {
697
+ typeScriptPlugin = loadTypeScriptPlugin(config.root || process.cwd());
698
+ if (!(config[transformer] && 'exclude' in config[transformer])) {
699
+ /** @type {any} */ (jsxPreserve)[transformer].exclude = typeScriptPlugin !== null ? /\.(?:jsx?|tsx)$/ : /\.jsx?$/;
700
+ } else {
701
+ typeScriptPlugin = null;
702
+ }
703
+ }
403
704
  return {
404
705
  ...(useProdCondition ? { resolve: { conditions: ['production'] } } : {}),
706
+ ...(productionBuild ? { define: { __WHAT_DEV__: 'false' } } : {}),
405
707
  ...jsxPreserve,
406
708
  optimizeDeps: {
709
+ // Vite 8's dependency scan transforms .jsx with these options, not
710
+ // `oxc`, and defaults to React's automatic runtime: it would look for
711
+ // react/jsx-dev-runtime and print "Failed to run dependency scan".
712
+ ...(jsxPreserve.oxc ? {
713
+ rolldownOptions: {
714
+ transform: { jsx: 'preserve' },
715
+ plugins: [{ name: 'what-dependency-jsx', transform: optimizeDependency }],
716
+ },
717
+ } : {
718
+ esbuildOptions: {
719
+ plugins: [{
720
+ name: 'what-dependency-jsx',
721
+ setup(build) {
722
+ build.onLoad({ filter: SCRIPT_MODULE_RE }, async ({ path: id }) => {
723
+ const file = id.replace(/\\/g, '/');
724
+ if (!dependencyPackage(file, rootDir, dependencyPackages)) return undefined;
725
+ const result = optimizeDependency.call(undefined, await fs.promises.readFile(id, 'utf8'), file);
726
+ if (result === null) return undefined;
727
+ const ext = /\.([jt]sx?)$/.exec(id)?.[1];
728
+ return { contents: result.code, loader: ext ?? (/\.[cm]ts$/.test(id) ? 'ts' : 'js') };
729
+ });
730
+ },
731
+ }],
732
+ },
733
+ }),
407
734
  // Exclude framework packages from Vite's dependency pre-bundling.
408
735
  //
409
736
  // Bug class this prevents — "dual module instance":
@@ -413,7 +740,7 @@ export default function whatVitePlugin(options = {}) {
413
740
  // pre-bundles `'what-framework'` into an esbuild chunk under
414
741
  // node_modules/.vite, those two import paths resolve to two
415
742
  // *different* module instances. Module-scoped state — the
416
- // `componentStack` used by createComponent, effect ownership,
743
+ // current owner that components and hooks resolve through,
417
744
  // the signal subscriber registry — is duplicated, so a signal
418
745
  // created in user code never notifies effects created via the
419
746
  // compiler-emitted path, and `getCurrentComponent()` returns
@@ -436,51 +763,9 @@ export default function whatVitePlugin(options = {}) {
436
763
  };
437
764
  }
438
765
  };
766
+ return plugin;
439
767
  }
440
768
 
441
- /**
442
- * Check if a file likely contains a component (has exported function starting with uppercase)
443
- */
444
- function isComponentModule(source, filePath) {
445
- // .jsx/.tsx files with component exports
446
- if (COMPONENT_EXPORT_RE.test(source)) return true;
447
- // Pages are always component files
448
- if (filePath.includes('/pages/') || filePath.includes('\\pages\\')) return true;
449
- return false;
450
- }
451
-
452
- /**
453
- * Check if a file is a utility/signal/store file (should trigger full reload)
454
- */
455
- function isUtilityFile(filePath) {
456
- const basename = path.basename(filePath, path.extname(filePath));
457
- return UTILITY_FILE_RE.test(basename);
458
- }
459
-
460
- /**
461
- * Generate HMR boundary code for a component file.
462
- * Vite calls the accept callback after reevaluating the updated module.
463
- * An installed replacement runtime owns the update. Otherwise reload the page:
464
- * accepting the module alone leaves its already-mounted component unchanged.
465
- */
466
- function generateHMRBoundary(filePath) {
467
- return `
468
-
469
- // --- What Framework HMR Boundary ---
470
- if (import.meta.hot) {
471
- import.meta.hot.accept((newModule) => {
472
- if (newModule) {
473
- // Signal to the What runtime that this module was hot-updated
474
- if (typeof window.__WHAT_HMR_ACCEPT__ === 'function') {
475
- window.__WHAT_HMR_ACCEPT__(${JSON.stringify(filePath)}, newModule);
476
- } else {
477
- window.location.reload();
478
- }
479
- }
480
- });
481
- }
482
- `;
483
- }
484
769
 
485
770
  // Named export for compatibility
486
771
  export { whatVitePlugin as what };