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
package/src/hot.js ADDED
@@ -0,0 +1,523 @@
1
+ /**
2
+ * Hot replacement in the dev server: the calls each browser module makes to
3
+ * what-core's hot runtime (what-core src/hot.js, which says what they do),
4
+ * written from the module's own source by a Babel pass that runs before the
5
+ * JSX transform, in development only.
6
+ *
7
+ * What a module does when it changes (its mode):
8
+ * - 'accept': it declares a component, runs nothing but declarations at its
9
+ * top level, and exports only what can be compared (its components, its
10
+ * functions and classes, its module-scope values). It replaces itself: its
11
+ * changed components are built again in place.
12
+ * - 'propagate': it declares no component, or re-exports another module's
13
+ * names, or exports what cannot be compared (a `let` it assigns again, an
14
+ * `export default` expression). Its module-scope values are kept, and the
15
+ * update goes on to the modules that import it.
16
+ * - 'reload': it runs statements at its top level (a mount(), an effect(), a
17
+ * listener). Running it again would run them twice, so the plugin reloads
18
+ * the page instead, and the module gets no hot code.
19
+ *
20
+ * Each top-level binding is compared between versions by a signature: its
21
+ * source, with the source of the module's functions and classes it reaches
22
+ * (they are made again by every version, so their text is what can change),
23
+ * and the values it reads at run time: its imports and the module-scope
24
+ * values it reaches, compared by identity (a component by its record). A
25
+ * component is never part of another's signature: it renders through its
26
+ * record. A binding that reads a `let` the module assigns again has no
27
+ * signature (null): it always counts as changed.
28
+ *
29
+ * A component's state carries over to the instance its new version builds
30
+ * while its state signature is unchanged, React's hook signature: the
31
+ * source of each state call in its body (`signal()`, `useState()`,
32
+ * `useSignal()`, `useReducer()`, with what it is assigned to), in order,
33
+ * and of the state calls of the module's own custom hooks (`use…`
34
+ * functions) it calls. Each such call is wrapped as
35
+ * `_$h.state(site, () => call)`, `site` being its place and source, so a
36
+ * value only ever goes back to the call that made it. `// @refresh reset`
37
+ * anywhere in the file starts every component's state again on each edit.
38
+ */
39
+
40
+ import { isWhatModuleSource } from './babel/common.js';
41
+
42
+ const RUNTIME = '_$hot';
43
+
44
+ // FNV-1a, 32 bits: a version's signature, short enough to write into the module.
45
+ function hash(text) {
46
+ let h = 0x811c9dc5;
47
+ for (let i = 0; i < text.length; i++) {
48
+ h ^= text.charCodeAt(i);
49
+ h = Math.imul(h, 0x01000193);
50
+ }
51
+ return (h >>> 0).toString(36) + text.length.toString(36);
52
+ }
53
+
54
+ const COMPONENT_NAME = /^[A-Z]/;
55
+ const CUSTOM_HOOK = /^use[A-Z0-9]/;
56
+ // What's state primitives whose value an instance keeps (`useReducer`'s by
57
+ // its value: its dispatch calls the reducer of the version that made it).
58
+ const STATE_CALLS = new Set(['signal', 'useState', 'useSignal', 'useReducer']);
59
+
60
+ function isFunctionNode(t, node) {
61
+ return t.isFunctionExpression(node) || t.isArrowFunctionExpression(node);
62
+ }
63
+
64
+ // The function a component or function binding declares, or null.
65
+ function functionOf(t, b) {
66
+ const node = b.node;
67
+ if (t.isFunctionDeclaration(node) || isFunctionNode(t, node)) return node;
68
+ if (t.isVariableDeclarator(node) && isFunctionNode(t, node.init)) return node.init;
69
+ return null;
70
+ }
71
+
72
+ // The name `binding` imports from What's own packages, or null.
73
+ function whatImport(t, binding) {
74
+ if (binding === undefined || binding.kind !== 'module' || !t.isImportSpecifier(binding.path.node)) return null;
75
+ const decl = binding.path.parent;
76
+ if (!t.isImportDeclaration(decl) || !isWhatModuleSource(decl.source.value)) return null;
77
+ const imported = binding.path.node.imported;
78
+ return t.isIdentifier(imported) ? imported.name : imported.value;
79
+ }
80
+
81
+ // An `await` in a module-scope initializer (top-level await), which cannot
82
+ // move into the function a kept value's initializer becomes.
83
+ function awaits(t, node) {
84
+ if (node == null || typeof node.type !== 'string') return false;
85
+ if (node.type === 'AwaitExpression' || (node.type === 'ForOfStatement' && node.await)) return true;
86
+ if (t.isFunction(node)) return false;
87
+ for (const key of t.VISITOR_KEYS[node.type] || []) {
88
+ const child = node[key];
89
+ if (Array.isArray(child) ? child.some((c) => awaits(t, c)) : awaits(t, child)) return true;
90
+ }
91
+ return false;
92
+ }
93
+
94
+ function containsJsx(t, node) {
95
+ let found = false;
96
+ t.traverseFast(node, (n) => {
97
+ if (n.type === 'JSXElement' || n.type === 'JSXFragment') found = true;
98
+ });
99
+ return found;
100
+ }
101
+
102
+ const TYPE_ONLY = new Set(['TSTypeAliasDeclaration', 'TSInterfaceDeclaration', 'TSDeclareFunction', 'EmptyStatement']);
103
+
104
+ // Whether a top-level statement only declares (no code of its own runs).
105
+ function declares(t, node) {
106
+ if (TYPE_ONLY.has(node.type)) return true;
107
+ if (t.isImportDeclaration(node) || t.isFunctionDeclaration(node) || t.isClassDeclaration(node) || t.isVariableDeclaration(node)) return true;
108
+ if (t.isTSEnumDeclaration(node) || t.isTSModuleDeclaration(node)) return true;
109
+ if (t.isExportAllDeclaration(node) || t.isExportNamedDeclaration(node)) return node.declaration == null || declares(t, node.declaration);
110
+ if (t.isExportDefaultDeclaration(node)) return true;
111
+ return false;
112
+ }
113
+
114
+ /**
115
+ * The mode of a module's source: 'reload' when it runs statements at its top
116
+ * level, else what the full pass decides. For handleHotUpdate, which sees the
117
+ * new source before Vite transforms it.
118
+ * @param {any} babel @babel/core
119
+ * @param {string} code
120
+ * @param {string} filename
121
+ */
122
+ export function runsStatements(babel, code, filename) {
123
+ let ast;
124
+ try {
125
+ ast = babel.parseSync(code, { filename, configFile: false, babelrc: false, parserOpts: { plugins: ['jsx', 'typescript'] } });
126
+ } catch {
127
+ // Vite's transform reports it, in its overlay.
128
+ return false;
129
+ }
130
+ return ast.program.body.some((node) => !declares(babel.types, node));
131
+ }
132
+
133
+ /**
134
+ * The Babel plugin. Options: `file`, the module's path from the project
135
+ * root (for reports); `onMode(mode)`, which hears the module's mode.
136
+ * @param {any} babel
137
+ */
138
+ export default function whatHotPlugin(babel) {
139
+ const t = babel.types;
140
+
141
+ return {
142
+ name: 'what-hot',
143
+ visitor: {
144
+ Program: {
145
+ enter(path, state) {
146
+ state.hot = analyze(t, path, state.file.code);
147
+ state.opts.onMode?.(state.hot.mode);
148
+ },
149
+ exit(path, state) {
150
+ const hot = state.hot;
151
+ if (hot.mode !== 'reload') emit(t, path, hot, state.opts.file ?? '');
152
+ },
153
+ },
154
+ },
155
+ };
156
+ }
157
+
158
+ function analyze(t, path, code) {
159
+ /** @type {Map<string, any>} */
160
+ const bindings = new Map();
161
+ /** @type {Array<{ exported: string, local: string }>} */
162
+ const exports = [];
163
+ let statements = false;
164
+ let opaque = false;
165
+ let order = 0;
166
+
167
+ const add = (name, kind, node, statement, extra) => {
168
+ bindings.set(name, { name, kind, node, statement, order: order++, text: code.slice(node.start, node.end), uses: new Map(), ...extra });
169
+ };
170
+
171
+ const declare = (decl, statement) => {
172
+ if (t.isFunctionDeclaration(decl) || t.isClassDeclaration(decl)) {
173
+ if (decl.id == null) return;
174
+ const name = decl.id.name;
175
+ const component = t.isFunctionDeclaration(decl) && COMPONENT_NAME.test(name);
176
+ add(name, component ? 'component' : 'function', decl, statement, { hoisted: true });
177
+ return;
178
+ }
179
+ if (t.isTSEnumDeclaration(decl) || t.isTSModuleDeclaration(decl)) {
180
+ if (t.isIdentifier(decl.id)) add(decl.id.name, 'function', decl, statement, { hoisted: false });
181
+ return;
182
+ }
183
+ if (!t.isVariableDeclaration(decl)) return;
184
+ for (const declarator of decl.declarations) {
185
+ const names = Object.keys(t.getBindingIdentifiers(declarator.id));
186
+ const reassigned = names.some((n) => {
187
+ const binding = path.scope.getBinding(n);
188
+ return binding !== undefined && !binding.constant;
189
+ });
190
+ const init = declarator.init;
191
+ if (t.isIdentifier(declarator.id) && init != null && isFunctionNode(t, init)) {
192
+ const name = declarator.id.name;
193
+ if (reassigned) add(name, 'volatile', declarator, statement);
194
+ else add(name, COMPONENT_NAME.test(name) ? 'component' : 'function', declarator, statement, { hoisted: false });
195
+ continue;
196
+ }
197
+ // A value read with `await` at the top level is made again by every version.
198
+ const waits = init != null && awaits(t, init);
199
+ const kind = reassigned || waits ? 'volatile' : 'keep';
200
+ // A destructured value is kept whole: its names read it again.
201
+ const key = names.join(',');
202
+ for (const n of names) add(n, kind, declarator, statement, { key, declarator, awaits: waits });
203
+ }
204
+ };
205
+
206
+ for (const statementPath of path.get('body')) {
207
+ const node = statementPath.node;
208
+ if (!declares(t, node)) {
209
+ statements = true;
210
+ continue;
211
+ }
212
+ if (t.isImportDeclaration(node) || TYPE_ONLY.has(node.type)) continue;
213
+ if (t.isExportAllDeclaration(node)) {
214
+ if (node.exportKind !== 'type') opaque = true;
215
+ continue;
216
+ }
217
+ if (t.isExportNamedDeclaration(node)) {
218
+ if (node.exportKind === 'type') continue;
219
+ if (node.source != null) {
220
+ opaque = true;
221
+ continue;
222
+ }
223
+ if (node.declaration != null) {
224
+ declare(node.declaration, statementPath);
225
+ for (const name of Object.keys(t.getOuterBindingIdentifiers(node.declaration))) exports.push({ exported: name, local: name });
226
+ }
227
+ for (const spec of node.specifiers) {
228
+ if (spec.exportKind === 'type') continue;
229
+ const exported = t.isIdentifier(spec.exported) ? spec.exported.name : spec.exported.value;
230
+ if (t.isExportSpecifier(spec)) exports.push({ exported, local: spec.local.name });
231
+ else opaque = true;
232
+ }
233
+ continue;
234
+ }
235
+ if (t.isExportDefaultDeclaration(node)) {
236
+ const decl = node.declaration;
237
+ if ((t.isFunctionDeclaration(decl) || t.isClassDeclaration(decl)) && decl.id != null) {
238
+ declare(decl, statementPath);
239
+ exports.push({ exported: 'default', local: decl.id.name });
240
+ } else if ((t.isFunctionDeclaration(decl) || isFunctionNode(t, decl)) && containsJsx(t, decl)) {
241
+ add('default', 'component', decl, statementPath, { anonymous: true });
242
+ } else if (t.isIdentifier(decl)) {
243
+ exports.push({ exported: 'default', local: decl.name });
244
+ } else {
245
+ opaque = true;
246
+ }
247
+ continue;
248
+ }
249
+ declare(node, statementPath);
250
+ }
251
+
252
+ // Each binding's references to the module's other bindings.
253
+ const byStatement = new Map();
254
+ for (const b of bindings.values()) {
255
+ if (!byStatement.has(b.statement.node)) byStatement.set(b.statement.node, []);
256
+ byStatement.get(b.statement.node).push(b);
257
+ }
258
+ for (const [name, binding] of Object.entries(path.scope.bindings)) {
259
+ const target = bindings.get(name);
260
+ const imported = binding.kind === 'module';
261
+ if (target === undefined && !imported) continue;
262
+ for (const ref of binding.referencePaths) {
263
+ const user = userOf(t, ref, byStatement);
264
+ if (user === null || user.name === name) continue;
265
+ // A component a tag or a value names renders through its record; one
266
+ // called as a function runs as the module wrote it.
267
+ const called = ref.parentPath.isCallExpression({ callee: ref.node });
268
+ const kind = imported ? 'import' : target.kind;
269
+ if (kind === 'component' && !called) continue;
270
+ user.uses.set(name, kind === 'component' ? 'function' : kind);
271
+ }
272
+ }
273
+
274
+ const components = [...bindings.values()].filter((b) => b.kind === 'component');
275
+ // An exported component's versions are found by the name it is exported
276
+ // under, so renaming the function keeps its instances.
277
+ for (const { exported, local } of exports) {
278
+ const b = bindings.get(local);
279
+ if (b !== undefined && b.kind === 'component' && b.recordKey === undefined) b.recordKey = exported;
280
+ }
281
+ const exportsComparable = exports.every(({ local }) => {
282
+ const b = bindings.get(local);
283
+ return b !== undefined && b.kind !== 'volatile';
284
+ });
285
+ const mode = statements ? 'reload' : components.length > 0 && !opaque && exportsComparable ? 'accept' : 'propagate';
286
+
287
+ for (const b of bindings.values()) {
288
+ if (b.kind === 'volatile') {
289
+ b.sig = null;
290
+ b.deps = [];
291
+ continue;
292
+ }
293
+ const sign = signature(b, bindings);
294
+ b.sig = sign.volatile ? null : hash(sign.text);
295
+ b.deps = sign.deps;
296
+ }
297
+ const reset = (path.parent.comments || []).some((c) => /@refresh reset/.test(c.value));
298
+ return { mode, bindings, exports, sites: stateSites(t, path, code, bindings, reset) };
299
+ }
300
+
301
+ // The state calls of each component and of the module's own custom hooks,
302
+ // in source order, and each component's state signature (`b.state`, null
303
+ // with `// @refresh reset`). Returns the calls to wrap, by node. A call in
304
+ // a loop is made again by every version: it is not wrapped.
305
+ function stateSites(t, path, code, bindings, reset) {
306
+ /** @type {Map<any, any>} */
307
+ const bodies = new Map();
308
+ for (const b of bindings.values()) {
309
+ if (b.kind !== 'component' && !(b.kind === 'function' && CUSTOM_HOOK.test(b.name))) continue;
310
+ const fn = functionOf(t, b);
311
+ if (fn === null) continue;
312
+ b.calls = [];
313
+ bodies.set(fn, b);
314
+ }
315
+ /** @type {Map<any, { site: string, reducer: boolean, path: any }>} */
316
+ const sites = new Map();
317
+ if (bodies.size === 0) return sites;
318
+ // The calls, found from the module's bindings that can be them: What's
319
+ // state primitives, and custom hooks (its own `use…` functions and the ones
320
+ // it imports), in source order.
321
+ const calls = [];
322
+ for (const [name, binding] of Object.entries(path.scope.bindings)) {
323
+ const primitive = whatImport(t, binding);
324
+ if (primitive !== null ? !STATE_CALLS.has(primitive) : !CUSTOM_HOOK.test(name)) continue;
325
+ for (const ref of binding.referencePaths) {
326
+ if (ref.parentPath.isCallExpression({ callee: ref.node })) calls.push({ call: ref.parentPath, primitive, name });
327
+ }
328
+ }
329
+ calls.sort((a, b) => a.call.node.start - b.call.node.start);
330
+ for (const { call, primitive, name } of calls) {
331
+ const fn = call.getFunctionParent();
332
+ const owner = fn === null ? undefined : bodies.get(fn.node);
333
+ if (owner === undefined) continue;
334
+ if (primitive === null) {
335
+ owner.calls.push({ hook: name });
336
+ continue;
337
+ }
338
+ if (call.findParent((p) => p.node === fn.node || p.isLoop()).node !== fn.node) continue;
339
+ const declarator = t.isVariableDeclarator(call.parent) && call.parent.init === call.node ? call.parent : null;
340
+ // useReducer's reducer is not part of it (React's rule): the new one runs on the state kept.
341
+ const args = primitive === 'useReducer' ? call.node.arguments.slice(1) : call.node.arguments;
342
+ const text = (declarator === null ? '' : code.slice(declarator.id.start, declarator.id.end) + '=')
343
+ + `${primitive}(${args.map((a) => code.slice(a.start, a.end)).join(', ')})`;
344
+ const site = hash(`${owner.name}:${owner.calls.length}:${text}`);
345
+ owner.calls.push({ text });
346
+ sites.set(call.node, { site, reducer: primitive === 'useReducer', path: call });
347
+ }
348
+ const signs = new Map();
349
+ const stateText = (b) => {
350
+ if (signs.has(b)) return signs.get(b);
351
+ signs.set(b, '');
352
+ const text = b.calls.map((c) => {
353
+ if (c.hook === undefined) return c.text;
354
+ const local = bindings.get(c.hook);
355
+ return local !== undefined && local.calls !== undefined ? `${c.hook}{${stateText(local)}}` : c.hook;
356
+ }).join('\n');
357
+ signs.set(b, text);
358
+ return text;
359
+ };
360
+ for (const b of bodies.values()) {
361
+ if (b.kind !== 'component') continue;
362
+ const text = stateText(b);
363
+ b.state = reset ? null : text === '' ? undefined : hash(text);
364
+ }
365
+ return sites;
366
+ }
367
+
368
+ // The top-level binding whose declaration holds `ref`, or null.
369
+ function userOf(t, ref, byStatement) {
370
+ const statement = ref.find((p) => p.parentPath !== null && p.parentPath.isProgram());
371
+ const declared = statement == null ? undefined : byStatement.get(statement.node);
372
+ if (declared === undefined) return null;
373
+ for (const b of declared) {
374
+ if (b.declarator === undefined && b.node.type !== 'VariableDeclarator') return b;
375
+ if (b.node === ref.node || ref.findParent((p) => p.node === b.node) != null) return b;
376
+ }
377
+ return null;
378
+ }
379
+
380
+ // The source a binding's versions are compared by, the run-time values they
381
+ // read, and whether one of them is a `let` assigned again.
382
+ function signature(b, bindings) {
383
+ const seen = new Set([b.name]);
384
+ const queue = [b];
385
+ const texts = [b.text];
386
+ const deps = new Set();
387
+ let volatile = false;
388
+ while (queue.length > 0) {
389
+ const at = queue.shift();
390
+ for (const [name, kind] of at.uses) {
391
+ if (kind === 'import') {
392
+ deps.add(name);
393
+ continue;
394
+ }
395
+ const used = bindings.get(name);
396
+ if (used === undefined) continue;
397
+ if (kind === 'volatile') {
398
+ volatile = true;
399
+ continue;
400
+ }
401
+ if (kind === 'keep') {
402
+ // A value declared after a kept one is not there yet when it is
403
+ // read: compared as changed.
404
+ if (b.kind === 'keep' && used.order > b.order) volatile = true;
405
+ else deps.add(name);
406
+ continue;
407
+ }
408
+ if (seen.has(name)) continue;
409
+ seen.add(name);
410
+ if (b.kind === 'keep' && !used.hoisted && used.order > b.order) volatile = true;
411
+ texts.push(`${name}=${used.text}`);
412
+ queue.push(used);
413
+ }
414
+ }
415
+ texts.sort();
416
+ return { text: texts.join('\n'), deps: [...deps].sort(), volatile };
417
+ }
418
+
419
+ // Whether `p` still stands for `node` in the program, every level of it in place.
420
+ function inPlace(p, node) {
421
+ if (p.node !== node) return false;
422
+ let q = p;
423
+ for (; q.parentPath !== null; q = q.parentPath) {
424
+ const container = q.container;
425
+ if (container == null || container[q.key] !== q.node) return false;
426
+ }
427
+ return q.isProgram();
428
+ }
429
+
430
+ function uniqueName(path, base) {
431
+ let name = base;
432
+ for (let i = 2; path.scope.hasBinding(name) || path.scope.hasGlobal(name); i++) name = `${base}${i}`;
433
+ return name;
434
+ }
435
+
436
+ function runtimeSource(path) {
437
+ const sources = path.node.body.filter((n) => n.type === 'ImportDeclaration').map((n) => n.source.value);
438
+ const core = sources.some((s) => s === 'what-core' || s.startsWith('what-core/'));
439
+ const framework = sources.some((s) => s === 'what-framework' || s.startsWith('what-framework/'));
440
+ return core && !framework ? 'what-core/hot' : 'what-framework/hot';
441
+ }
442
+
443
+ function emit(t, path, hot, file) {
444
+ const ctx = t.identifier(uniqueName(path, '_$h'));
445
+ const runtime = t.identifier(uniqueName(path, RUNTIME));
446
+ const hotMeta = () => t.memberExpression(t.metaProperty(t.identifier('import'), t.identifier('meta')), t.identifier('hot'));
447
+ const call = (method, args) => t.callExpression(t.memberExpression(ctx, t.identifier(method)), args);
448
+ const depsOf = (b) => t.arrowFunctionExpression([], t.arrayExpression(b.deps.map((d) => t.identifier(d))));
449
+ const sigOf = (b) => (b.sig === null ? t.nullLiteral() : t.stringLiteral(b.sig));
450
+ const registration = (key, fn, b) => call('component', [key, fn, sigOf(b), depsOf(b), ...(b.state === undefined ? [] : [b.state === null ? t.nullLiteral() : t.stringLiteral(b.state)])]);
451
+ const accepts = hot.mode === 'accept';
452
+
453
+ const wrap = (state, at) => state.replaceWith(call('state', [t.stringLiteral(at.site), t.arrowFunctionExpression([], state.node), ...(at.reducer ? [t.numericLiteral(1)] : [])]));
454
+ // Each call where the analysis found it, unless the JSX transform moved it
455
+ // since: those are found again.
456
+ for (const [node, at] of [...hot.sites]) {
457
+ if (!inPlace(at.path, node)) continue;
458
+ hot.sites.delete(node);
459
+ wrap(at.path, at);
460
+ }
461
+ if (hot.sites.size > 0) {
462
+ path.traverse({
463
+ CallExpression(state) {
464
+ const at = hot.sites.get(state.node);
465
+ if (at === undefined) return;
466
+ hot.sites.delete(state.node);
467
+ wrap(state, at);
468
+ },
469
+ });
470
+ }
471
+
472
+ const head = [
473
+ t.importDeclaration([t.importSpecifier(runtime, t.identifier(RUNTIME))], t.stringLiteral(runtimeSource(path))),
474
+ t.variableDeclaration('const', [t.variableDeclarator(ctx, t.callExpression(runtime, [hotMeta(), t.numericLiteral(accepts ? 1 : 0), t.stringLiteral(file)]))]),
475
+ ];
476
+ // Accepted first, so a version that throws while it runs still hands the
477
+ // next one its update.
478
+ if (accepts) {
479
+ head.push(t.ifStatement(hotMeta(), t.expressionStatement(t.callExpression(t.memberExpression(hotMeta(), t.identifier('accept')), [t.memberExpression(ctx, t.identifier('accept'))]))));
480
+ }
481
+ const after = new Map();
482
+ const later = (statement, node) => {
483
+ if (!after.has(statement)) after.set(statement, []);
484
+ after.get(statement).push(node);
485
+ };
486
+ for (const b of hot.bindings.values()) {
487
+ if (b.kind === 'component') {
488
+ if (b.anonymous) {
489
+ const decl = b.node;
490
+ const fn = t.isFunctionDeclaration(decl) ? t.functionExpression(null, decl.params, decl.body, decl.generator, decl.async) : decl;
491
+ b.statement.node.declaration = registration(t.stringLiteral('default'), fn, b);
492
+ continue;
493
+ }
494
+ const register = t.expressionStatement(registration(t.stringLiteral(b.recordKey ?? b.name), t.identifier(b.name), b));
495
+ if (b.hoisted) head.push(register);
496
+ else later(b.statement.node, register);
497
+ }
498
+ }
499
+ const kept = new Set();
500
+ for (const b of hot.bindings.values()) {
501
+ if ((b.kind !== 'keep' && b.kind !== 'volatile') || b.declarator.init == null || kept.has(b.declarator)) continue;
502
+ kept.add(b.declarator);
503
+ if (b.awaits) continue;
504
+ const sig = hot.bindings.get(b.key.split(',')[0]);
505
+ b.declarator.init = call('keep', [t.stringLiteral(b.key), sigOf(sig), sig.kind === 'volatile' ? t.arrowFunctionExpression([], t.arrayExpression([])) : depsOf(sig), t.arrowFunctionExpression([], b.declarator.init)]);
506
+ }
507
+ const tail = [];
508
+ const exported = [];
509
+ for (const { local } of hot.exports) {
510
+ const b = hot.bindings.get(local);
511
+ if (b === undefined || b.kind === 'component') continue;
512
+ if (b.kind === 'function') tail.push(t.expressionStatement(call('fn', [t.stringLiteral(local), sigOf(b), depsOf(b)])));
513
+ exported.push(t.stringLiteral(local));
514
+ }
515
+ tail.push(t.expressionStatement(call('done', [t.arrayExpression(exported)])));
516
+
517
+ const body = path.node.body;
518
+ for (const [statement, nodes] of after) body.splice(body.indexOf(statement) + 1, 0, ...nodes);
519
+ let at = 0;
520
+ while (at < body.length && body[at].type === 'ImportDeclaration') at++;
521
+ body.splice(at, 0, ...head);
522
+ body.push(...tail);
523
+ }
package/src/release.js ADDED
@@ -0,0 +1,127 @@
1
+ // One release of compiler and runtime per build.
2
+ //
3
+ // what-compiler's output imports the runtime helpers of its own release (from
4
+ // what-framework/render, or what-core/render in a module that imports
5
+ // what-core). npm refuses an install that mixes releases, because the packages
6
+ // declare each other as peers at the release caret. An install that skips peer
7
+ // checks (--legacy-peer-deps, --force, a package manager that only warns) does
8
+ // not, and the app then fails to build with a bundler's `is not exported`, or
9
+ // builds and renders SVG as HTML in production. So the entry points that build
10
+ // compare the installed packages with their own release first, and stop with
11
+ // ERR_COMPILER_RUNTIME_MISMATCH.
12
+ //
13
+ // Only Node can look: with no `fs` (the compiler running in a browser) there
14
+ // is nothing to check. Lookups are cached per directory. The check can only run
15
+ // if the compiler itself loads beside any what-core, so it imports none: the
16
+ // tables it shares with the runtime are copies under tables/.
17
+
18
+ let ownVersion;
19
+ const verdicts = new Map();
20
+
21
+ function numbers(version) {
22
+ const match = /^(\d+)\.(\d+)\.(\d+)/.exec(String(version));
23
+ return match ? match.slice(1, 4).map(Number) : null;
24
+ }
25
+
26
+ // Whether `version` satisfies `^base`, the range each release's packages
27
+ // declare on one another. Prerelease tags are not compared.
28
+ export function satisfiesRelease(version, base) {
29
+ const v = numbers(version);
30
+ const b = numbers(base);
31
+ if (!v || !b) return false;
32
+ if (v[0] !== b[0] || (b[0] === 0 && v[1] !== b[1])) return false;
33
+ for (let i = 1; i < 3; i++) if (v[i] !== b[i]) return v[i] > b[i];
34
+ return true;
35
+ }
36
+
37
+ function compilerVersion(fs) {
38
+ if (ownVersion === undefined) {
39
+ ownVersion = null;
40
+ try {
41
+ ownVersion = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
42
+ } catch {
43
+ // A copy bundled away from its package.json has no release to compare.
44
+ }
45
+ }
46
+ return ownVersion;
47
+ }
48
+
49
+ // The package.json Node finds for the bare specifier `name` from `fromDir`.
50
+ function installed(name, fromDir, fs) {
51
+ let dir = String(fromDir).replace(/[\\/]+$/, '');
52
+ while (dir) {
53
+ const file = `${dir}/node_modules/${name}/package.json`;
54
+ if (fs.existsSync(file)) {
55
+ try {
56
+ return { file, version: JSON.parse(fs.readFileSync(file, 'utf8')).version };
57
+ } catch {
58
+ return null;
59
+ }
60
+ }
61
+ const parent = dir.replace(/[\\/][^\\/]*$/, '');
62
+ if (parent === dir) return null;
63
+ dir = parent;
64
+ }
65
+ return null;
66
+ }
67
+
68
+ // The later of two versions.
69
+ function later(a, b) {
70
+ const x = numbers(a) || [0, 0, 0];
71
+ const y = numbers(b) || [0, 0, 0];
72
+ for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] > y[i] ? a : b;
73
+ return a;
74
+ }
75
+
76
+ function mismatch(compiler, name, found) {
77
+ const target = later(compiler, found.version);
78
+ return Object.assign(
79
+ new Error(
80
+ `[what-compiler] ERR_COMPILER_RUNTIME_MISMATCH: what-compiler ${compiler} cannot build for ${name} ${found.version} ` +
81
+ `(${found.file}): compiled output runs only on the runtime of its own release. Install every What package at one ` +
82
+ `release in one install (npm install what-framework@${target} what-compiler@${target} and each other what-* package ` +
83
+ 'you use at the same version), as step 1 of "Before you start" in UPGRADING.md says.',
84
+ ),
85
+ { code: 'ERR_COMPILER_RUNTIME_MISMATCH', compiler, runtime: { name, version: found.version, file: found.file } },
86
+ );
87
+ }
88
+
89
+ /**
90
+ * The error for a what-framework or what-core of another release than this
91
+ * compiler where a module in `fromDir` imports it, or null.
92
+ * `fs` is node:fs; without it, null.
93
+ * @param {string} fromDir
94
+ * @param {any} fs
95
+ * @returns {Error | null}
96
+ */
97
+ export function runtimeMismatch(fromDir, fs) {
98
+ if (!fs || !fromDir) return null;
99
+ if (verdicts.has(fromDir)) return verdicts.get(fromDir);
100
+ const compiler = compilerVersion(fs);
101
+ /** @type {Error | null} */
102
+ let verdict = null;
103
+ for (const name of compiler ? ['what-framework', 'what-core'] : []) {
104
+ const found = installed(name, fromDir, fs);
105
+ if (found && !satisfiesRelease(found.version, compiler)) {
106
+ verdict = mismatch(compiler, name, found);
107
+ break;
108
+ }
109
+ }
110
+ verdicts.set(fromDir, verdict);
111
+ return verdict;
112
+ }
113
+
114
+ /**
115
+ * runtimeMismatch() for the module `filename`, with node:fs where the compiler
116
+ * runs in Node (20.16+, 22.3+), else null. The Babel plugin's check: Babel
117
+ * hands it the file being compiled and nothing else.
118
+ * @param {string | null | undefined} filename
119
+ * @returns {Error | null}
120
+ */
121
+ export function fileRuntimeMismatch(filename) {
122
+ if (!filename) return null;
123
+ const host = /** @type {any} */ (globalThis).process;
124
+ // node-floor: feature-detected; through what-compiler/vite every Node 20 release is checked
125
+ const fs = typeof host?.getBuiltinModule === 'function' ? host.getBuiltinModule('node:fs') : null;
126
+ return runtimeMismatch(String(filename).replace(/[\\/][^\\/]*$/, ''), fs);
127
+ }
package/src/runtime.js CHANGED
@@ -1,11 +1,11 @@
1
1
  /**
2
- * What Compiler Runtime
2
+ * What Compiler Runtime (what-compiler/runtime)
3
3
  *
4
- * With the unified rendering path (babel plugin → h() → core reconciler),
5
- * most runtime helpers are no longer needed. The compiler now outputs h() calls
6
- * that go through what-core's VNode reconciler.
7
- *
8
- * This file re-exports from what-core for backwards compatibility.
4
+ * Re-exports h, Fragment and mount from what-core and _$Island from
5
+ * what-core/render. Compiled output does not import this module: client output
6
+ * imports its helpers from what-framework and what-framework/render (or their
7
+ * what-core twins), server output from what-framework/ssr-runtime.
9
8
  */
10
9
 
11
- export { h, Fragment, mount, Island } from 'what-core';
10
+ export { h, Fragment, mount } from 'what-core';
11
+ export { _$Island } from 'what-core/render';