@tsrx/react 0.1.2 → 0.1.3

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 (2) hide show
  1. package/package.json +2 -2
  2. package/src/transform.js +29 -2633
package/src/transform.js CHANGED
@@ -1,2633 +1,29 @@
1
- /** @import * as AST from 'estree' */
2
- /** @import * as ESTreeJSX from 'estree-jsx' */
3
-
4
- import { walk } from 'zimmerframe';
5
- import { print } from 'esrap';
6
- import tsx from 'esrap/languages/tsx';
7
- import {
8
- renderStylesheets,
9
- setLocation,
10
- applyLazyTransforms as apply_lazy_transforms,
11
- findFirstTopLevelAwaitInComponentBody as find_first_top_level_await_in_component_body,
12
- collectLazyBindingsFromComponent as collect_lazy_bindings_from_component,
13
- preallocateLazyIds as preallocate_lazy_ids,
14
- replaceLazyParams as replace_lazy_params,
15
- prepareStylesheetForRender as prepare_stylesheet_for_render,
16
- annotateComponentWithHash as annotate_component_with_hash,
17
- isInterleavedBody as is_interleaved_body_core,
18
- isCapturableJsxChild as is_capturable_jsx_child,
19
- captureJsxChild,
20
- isHoistSafeJsxNode as is_hoist_safe_jsx_node,
21
- } from '@tsrx/core';
22
-
23
- /**
24
- * @typedef {{
25
- * local_statement_component_index: number,
26
- * needs_error_boundary: boolean,
27
- * needs_suspense: boolean,
28
- * helper_state: { base_name: string, next_id: number, helpers: AST.FunctionDeclaration[], statics: any[] } | null,
29
- * available_bindings: Map<string, AST.Identifier>,
30
- * lazy_next_id: number,
31
- * current_css_hash: string | null,
32
- * }} TransformContext
33
- */
34
-
35
- /**
36
- * @typedef {{ source_name: string, read: () => any }} LazyBinding
37
- */
38
-
39
- /**
40
- * Transform a parsed tsrx-react AST into a TSX/JSX module.
41
- *
42
- * Replaces Ripple-specific `Component`/`Element`/`Text`/`TSRXExpression`
43
- * nodes with their standard JSX equivalents inside a `FunctionDeclaration`.
44
- * Any `<style>` element declared inside a component is collected,
45
- * rendered via `@tsrx/core`'s stylesheet renderer, and returned alongside
46
- * the JS output so a downstream plugin can inject it. The compiler also
47
- * augments every non-style Element in a scoped component with the
48
- * stylesheet's hash class so scoped selectors match correctly.
49
- *
50
- * @param {AST.Program} ast
51
- * @param {string} source
52
- * @param {string} [filename]
53
- * @returns {{ ast: AST.Program, code: string, map: any, css: { code: string, hash: string } | null }}
54
- */
55
- export function transform(ast, source, filename) {
56
- /** @type {any[]} */
57
- const stylesheets = [];
58
-
59
- /** @type {TransformContext} */
60
- const transform_context = {
61
- local_statement_component_index: 0,
62
- needs_error_boundary: false,
63
- needs_suspense: false,
64
- helper_state: null,
65
- available_bindings: new Map(),
66
- lazy_next_id: 0,
67
- current_css_hash: null,
68
- };
69
-
70
- preallocate_lazy_ids(/** @type {any} */ (ast), transform_context);
71
-
72
- walk(/** @type {any} */ (ast), transform_context, {
73
- Component(node, { next, state }) {
74
- const as_any = /** @type {any} */ (node);
75
- const await_expression = find_first_top_level_await_in_component_body(as_any.body || []);
76
-
77
- if (await_expression) {
78
- as_any.metadata = /** @type {any} */ ({
79
- ...(as_any.metadata || {}),
80
- contains_top_level_await: true,
81
- });
82
- }
83
-
84
- const css = as_any.css;
85
- if (css) {
86
- stylesheets.push(css);
87
- const hash = css.hash;
88
- annotate_component_with_hash(as_any, hash);
89
- }
90
- return next(state);
91
- },
92
- });
93
-
94
- const transformed = walk(/** @type {any} */ (ast), transform_context, {
95
- Component(node, { next, state }) {
96
- const as_any = /** @type {any} */ (node);
97
-
98
- // Set up helper_state and bindings BEFORE next() so that nested
99
- // hook_safe_* calls (inside Element children) can register helpers
100
- // and access available bindings during the bottom-up walk.
101
- const helper_state = create_helper_state(as_any.id?.name || 'Component');
102
- const saved_helper_state = state.helper_state;
103
- const saved_bindings = state.available_bindings;
104
- const saved_css_hash = state.current_css_hash;
105
- state.helper_state = helper_state;
106
- state.current_css_hash = as_any.css ? as_any.css.hash : null;
107
-
108
- // Pre-collect component body bindings (params + top-level statements)
109
- // so that Element children processed during the bottom-up walk can see
110
- // the full scope. Without this, hoisted helpers would miss body-level
111
- // variables like `const [x] = useState(...)` and produce ReferenceErrors.
112
- // Only collect up to the split point — bindings declared after a
113
- // hook-safe split aren't in scope at the return statement and would
114
- // cause ReferenceErrors if passed as helper props.
115
- const body_bindings = collect_param_bindings(as_any.params || []);
116
- const body = as_any.body || [];
117
- const split_index = find_hook_safe_split_index(body);
118
- const collect_end = split_index === -1 ? body.length : split_index;
119
- for (let i = 0; i < collect_end; i += 1) {
120
- collect_statement_bindings(body[i], body_bindings);
121
- }
122
- state.available_bindings = body_bindings;
123
-
124
- const inner = /** @type {any} */ (next() ?? node);
125
-
126
- // Restore context
127
- state.helper_state = saved_helper_state;
128
- state.available_bindings = saved_bindings;
129
- state.current_css_hash = saved_css_hash;
130
-
131
- return /** @type {any} */ (component_to_function_declaration(inner, state, helper_state));
132
- },
133
-
134
- Tsx(node, { next }) {
135
- const inner = /** @type {any} */ (next() ?? node);
136
- return /** @type {any} */ (tsx_node_to_jsx_expression(inner));
137
- },
138
-
139
- TsxCompat(node, { next }) {
140
- const inner = /** @type {any} */ (next() ?? node);
141
- return /** @type {any} */ (tsx_compat_node_to_jsx_expression(inner));
142
- },
143
-
144
- Element(node, { next, state }) {
145
- const inner = /** @type {any} */ (next() ?? node);
146
- return /** @type {any} */ (to_jsx_element(inner, state));
147
- },
148
-
149
- Text(node, { next }) {
150
- const inner = /** @type {any} */ (next() ?? node);
151
- return /** @type {any} */ (
152
- to_jsx_expression_container(to_text_expression(inner.expression, inner), inner)
153
- );
154
- },
155
-
156
- TSRXExpression(node, { next }) {
157
- const inner = /** @type {any} */ (next() ?? node);
158
- return /** @type {any} */ (to_jsx_expression_container(inner.expression, inner));
159
- },
160
-
161
- MemberExpression(node, { next, state }) {
162
- const as_any = /** @type {any} */ (node);
163
- if (as_any.object && as_any.object.type === 'StyleIdentifier' && state.current_css_hash) {
164
- const class_name = as_any.computed ? as_any.property.value : as_any.property.name;
165
- const value = `${state.current_css_hash} ${class_name}`;
166
- return /** @type {any} */ ({ type: 'Literal', value, raw: JSON.stringify(value) });
167
- }
168
- return next();
169
- },
170
- });
171
-
172
- const expanded = expand_component_helpers(/** @type {AST.Program} */ (transformed));
173
- inject_try_imports(expanded, transform_context);
174
-
175
- // Apply lazy destructuring transforms to module-level code (top-level function
176
- // declarations, arrow functions, etc.). Component bodies have already been
177
- // transformed inside component_to_function_declaration; this catches plain
178
- // functions outside components and any lazy patterns in module scope.
179
- const final_program = /** @type {any} */ (
180
- apply_lazy_transforms(/** @type {any} */ (expanded), new Map())
181
- );
182
-
183
- const result = print(/** @type {any} */ (final_program), tsx(), {
184
- sourceMapSource: filename,
185
- sourceMapContent: source,
186
- });
187
-
188
- const css =
189
- stylesheets.length > 0
190
- ? {
191
- code: renderStylesheets(
192
- /** @type {any} */ (stylesheets.map(prepare_stylesheet_for_render)),
193
- ),
194
- hash: stylesheets.map((s) => s.hash).join(' '),
195
- }
196
- : null;
197
-
198
- return { ast: final_program, code: result.code, map: result.map, css };
199
- }
200
-
201
- /**
202
- * @param {any} component
203
- * @param {TransformContext} transform_context
204
- * @param {{ base_name: string, next_id: number, helpers: AST.FunctionDeclaration[], statics: any[] }} [walk_helper_state]
205
- * @returns {AST.FunctionDeclaration}
206
- */
207
- function component_to_function_declaration(component, transform_context, walk_helper_state) {
208
- const helper_state = walk_helper_state || create_helper_state(component.id?.name || 'Component');
209
- const params = component.params || [];
210
- const body = /** @type {any[]} */ (component.body || []);
211
- const is_async_component =
212
- !!component?.metadata?.contains_top_level_await ||
213
- find_first_top_level_await_in_component_body(body) !== null;
214
-
215
- // Collect param bindings from original patterns (lazy patterns still intact).
216
- const param_bindings = collect_param_bindings(params);
217
-
218
- // Collect lazy binding info WITHOUT mutating patterns. Stores lazy_id on metadata
219
- // for later replacement. Body bindings (count, setCount, etc.) are still in the
220
- // original patterns, so collect_statement_bindings during build will find them.
221
- const lazy_bindings = collect_lazy_bindings_from_component(params, body, transform_context);
222
-
223
- // Save and set context for this component scope
224
- const saved_helper_state = transform_context.helper_state;
225
- const saved_bindings = transform_context.available_bindings;
226
- transform_context.helper_state = helper_state;
227
- transform_context.available_bindings = new Map(param_bindings);
228
-
229
- const body_statements = build_component_statements(
230
- body,
231
- helper_state,
232
- param_bindings,
233
- transform_context,
234
- );
235
-
236
- // Replace lazy param patterns with generated identifiers
237
- const final_params = lazy_bindings.size > 0 ? replace_lazy_params(params) : params;
238
-
239
- // Wrap body_statements in a BlockStatement so that apply_lazy_transforms
240
- // runs collect_block_shadowed_names and detects body-level declarations
241
- // (e.g. `const name = ...`) that shadow lazy binding names.
242
- const body_block = /** @type {any} */ ({
243
- type: 'BlockStatement',
244
- body: body_statements,
245
- metadata: { path: [] },
246
- });
247
- const final_body =
248
- lazy_bindings.size > 0 ? apply_lazy_transforms(body_block, lazy_bindings) : body_block;
249
-
250
- const fn = /** @type {any} */ ({
251
- type: 'FunctionDeclaration',
252
- id: component.id,
253
- params: final_params,
254
- body: final_body,
255
- async: is_async_component,
256
- generator: false,
257
- metadata: {
258
- path: [],
259
- is_component: true,
260
- },
261
- });
262
-
263
- // Restore context
264
- transform_context.helper_state = saved_helper_state;
265
- transform_context.available_bindings = saved_bindings;
266
-
267
- fn.metadata.generated_helpers = helper_state.helpers;
268
- fn.metadata.generated_statics = helper_state.statics;
269
-
270
- if (fn.id) {
271
- fn.id.metadata = /** @type {AST.Identifier['metadata']} */ ({
272
- ...fn.id.metadata,
273
- is_component: true,
274
- });
275
- }
276
-
277
- setLocation(fn, /** @type {any} */ (component), true);
278
- return fn;
279
- }
280
-
281
- /**
282
- * @param {any[]} body_nodes
283
- * @param {{ base_name: string, next_id: number, helpers: AST.FunctionDeclaration[], statics: any[] }} helper_state
284
- * @param {Map<string, AST.Identifier>} available_bindings
285
- * @param {TransformContext} transform_context
286
- * @returns {any[]}
287
- */
288
- function build_component_statements(
289
- body_nodes,
290
- helper_state,
291
- available_bindings,
292
- transform_context,
293
- ) {
294
- const split_index = find_hook_safe_split_index(body_nodes);
295
- if (split_index === -1) {
296
- return build_render_statements(body_nodes, false, transform_context);
297
- }
298
-
299
- const statements = [];
300
- const render_nodes = [];
301
- const bindings = new Map(available_bindings);
302
-
303
- const pre_split_body = body_nodes.slice(0, split_index);
304
- const interleaved = is_interleaved_body(pre_split_body);
305
- let capture_index = 0;
306
-
307
- for (let i = 0; i < split_index; i += 1) {
308
- const child = body_nodes[i];
309
-
310
- if (is_bare_return_statement(child)) {
311
- statements.push(create_component_return_statement(render_nodes, child));
312
- return statements;
313
- }
314
-
315
- if (is_lone_return_if_statement(child)) {
316
- statements.push(create_component_lone_return_if_statement(child, render_nodes));
317
- continue;
318
- }
319
-
320
- if (is_jsx_child(child)) {
321
- const jsx = to_jsx_child(child, transform_context);
322
- if (interleaved && is_capturable_jsx_child(jsx)) {
323
- const { declaration, reference } = captureJsxChild(jsx, capture_index++);
324
- statements.push(declaration);
325
- render_nodes.push(reference);
326
- } else {
327
- render_nodes.push(jsx);
328
- }
329
- } else {
330
- statements.push(child);
331
- collect_statement_bindings(child, bindings);
332
- transform_context.available_bindings = bindings;
333
- }
334
- }
335
-
336
- if (!interleaved) {
337
- hoist_static_render_nodes(render_nodes, transform_context);
338
- }
339
-
340
- const split_node = body_nodes[split_index];
341
- const consequent_body =
342
- split_node.consequent.type === 'BlockStatement'
343
- ? split_node.consequent.body
344
- : [split_node.consequent];
345
- const short_branch_body = consequent_body.filter(
346
- (/** @type {any} */ child) => !is_bare_return_statement(child),
347
- );
348
- const continuation_body = body_nodes.slice(split_index + 1);
349
- const short_branch = create_helper_component_expression(
350
- short_branch_body,
351
- helper_state,
352
- bindings,
353
- split_node.consequent,
354
- 'Exit',
355
- transform_context,
356
- );
357
- const continuation = create_helper_component_expression(
358
- continuation_body,
359
- helper_state,
360
- bindings,
361
- split_node,
362
- 'Continue',
363
- transform_context,
364
- );
365
-
366
- render_nodes.push(
367
- to_jsx_expression_container(
368
- set_loc(
369
- /** @type {any} */ ({
370
- type: 'ConditionalExpression',
371
- test: split_node.test,
372
- consequent: short_branch,
373
- alternate: continuation,
374
- metadata: { path: [] },
375
- }),
376
- split_node,
377
- ),
378
- split_node,
379
- ),
380
- );
381
-
382
- statements.push(create_component_return_statement(render_nodes, split_node));
383
- return statements;
384
- }
385
-
386
- /**
387
- * @param {any[]} body_nodes
388
- * @param {boolean} return_null_when_empty
389
- * @param {TransformContext} transform_context
390
- * @returns {any[]}
391
- */
392
- function build_render_statements(body_nodes, return_null_when_empty, transform_context) {
393
- const statements = [];
394
- const render_nodes = [];
395
-
396
- // Create a new bindings map so inner-scope bindings from
397
- // collect_statement_bindings don't leak to the caller's scope.
398
- const saved_bindings = transform_context.available_bindings;
399
- transform_context.available_bindings = new Map(saved_bindings);
400
-
401
- // When non-JSX statements are interleaved with JSX children, we must
402
- // preserve source order so each JSX expression sees the variable state
403
- // at its textual position. Otherwise statements would all run before
404
- // any JSX is constructed, and every JSX child would observe the final
405
- // state of mutable variables.
406
- const interleaved = is_interleaved_body(body_nodes);
407
- let capture_index = 0;
408
-
409
- for (const child of body_nodes) {
410
- if (is_bare_return_statement(child)) {
411
- statements.push(create_component_return_statement(render_nodes, child));
412
- transform_context.available_bindings = saved_bindings;
413
- return statements;
414
- }
415
-
416
- if (is_lone_return_if_statement(child)) {
417
- statements.push(create_component_lone_return_if_statement(child, render_nodes));
418
- continue;
419
- }
420
-
421
- if (is_jsx_child(child)) {
422
- const jsx = to_jsx_child(child, transform_context);
423
- if (interleaved && is_capturable_jsx_child(jsx)) {
424
- const { declaration, reference } = captureJsxChild(jsx, capture_index++);
425
- statements.push(declaration);
426
- render_nodes.push(reference);
427
- } else {
428
- render_nodes.push(jsx);
429
- }
430
- } else {
431
- statements.push(child);
432
- collect_statement_bindings(child, transform_context.available_bindings);
433
- }
434
- }
435
-
436
- if (!interleaved) {
437
- hoist_static_render_nodes(render_nodes, transform_context);
438
- }
439
-
440
- const return_arg = build_return_expression(render_nodes);
441
- if (return_arg || return_null_when_empty) {
442
- statements.push({
443
- type: 'ReturnStatement',
444
- argument: return_arg || { type: 'Literal', value: null, raw: 'null' },
445
- });
446
- }
447
-
448
- transform_context.available_bindings = saved_bindings;
449
- return statements;
450
- }
451
-
452
- /**
453
- * React-specific wrapper around the core `isInterleavedBody` helper that
454
- * ignores bare `return` / lone return-if statements. Those are rewriting
455
- * signals rather than user-visible side effects, so JSX children around
456
- * them don't need capturing.
457
- *
458
- * @param {any[]} body_nodes
459
- * @returns {boolean}
460
- */
461
- function is_interleaved_body(body_nodes) {
462
- const filtered = body_nodes.filter(
463
- (child) => !is_bare_return_statement(child) && !is_lone_return_if_statement(child),
464
- );
465
- return is_interleaved_body_core(filtered, is_jsx_child);
466
- }
467
-
468
- /**
469
- * @param {any[]} body_nodes
470
- * @returns {number}
471
- */
472
- function find_hook_safe_split_index(body_nodes) {
473
- for (let i = 0; i < body_nodes.length; i += 1) {
474
- if (!is_lone_return_if_statement(body_nodes[i])) {
475
- continue;
476
- }
477
-
478
- if (body_contains_top_level_hook_call(body_nodes.slice(i + 1))) {
479
- return i;
480
- }
481
- }
482
-
483
- return -1;
484
- }
485
-
486
- /**
487
- * @param {any[]} body_nodes
488
- * @returns {boolean}
489
- */
490
- function body_contains_top_level_hook_call(body_nodes) {
491
- return body_nodes.some(statement_contains_top_level_hook_call);
492
- }
493
-
494
- /**
495
- * @param {any} node
496
- * @returns {boolean}
497
- */
498
- function statement_contains_top_level_hook_call(node) {
499
- return node_contains_top_level_hook_call(node, false);
500
- }
501
-
502
- /**
503
- * @param {any} node
504
- * @param {boolean} inside_nested_function
505
- * @returns {boolean}
506
- */
507
- function node_contains_top_level_hook_call(node, inside_nested_function) {
508
- if (!node || typeof node !== 'object') {
509
- return false;
510
- }
511
-
512
- if (
513
- inside_nested_function &&
514
- (node.type === 'FunctionDeclaration' ||
515
- node.type === 'FunctionExpression' ||
516
- node.type === 'ArrowFunctionExpression')
517
- ) {
518
- return false;
519
- }
520
-
521
- if (
522
- node.type === 'FunctionDeclaration' ||
523
- node.type === 'FunctionExpression' ||
524
- node.type === 'ArrowFunctionExpression'
525
- ) {
526
- const next_inside_nested_function = true;
527
- for (const key of Object.keys(node)) {
528
- if (key === 'loc' || key === 'start' || key === 'end' || key === 'metadata') {
529
- continue;
530
- }
531
- if (node_contains_top_level_hook_call(node[key], next_inside_nested_function)) {
532
- return true;
533
- }
534
- }
535
- return false;
536
- }
537
-
538
- if (!inside_nested_function && node.type === 'CallExpression' && is_hook_callee(node.callee)) {
539
- return true;
540
- }
541
-
542
- if (Array.isArray(node)) {
543
- return node.some((child) => node_contains_top_level_hook_call(child, inside_nested_function));
544
- }
545
-
546
- for (const key of Object.keys(node)) {
547
- if (key === 'loc' || key === 'start' || key === 'end' || key === 'metadata') {
548
- continue;
549
- }
550
- if (node_contains_top_level_hook_call(node[key], inside_nested_function)) {
551
- return true;
552
- }
553
- }
554
-
555
- return false;
556
- }
557
-
558
- /**
559
- * @param {any} callee
560
- * @returns {boolean}
561
- */
562
- function is_hook_callee(callee) {
563
- if (!callee) return false;
564
-
565
- if (callee.type === 'Identifier') {
566
- return /^use[A-Z0-9]/.test(callee.name);
567
- }
568
-
569
- if (
570
- !callee.computed &&
571
- callee.type === 'MemberExpression' &&
572
- callee.property?.type === 'Identifier'
573
- ) {
574
- return /^use[A-Z0-9]/.test(callee.property.name);
575
- }
576
-
577
- return false;
578
- }
579
-
580
- /**
581
- * @param {any[]} body_nodes
582
- * @param {{ base_name: string, next_id: number, helpers: AST.FunctionDeclaration[], statics: any[] }} helper_state
583
- * @param {Map<string, AST.Identifier>} available_bindings
584
- * @param {any} source_node
585
- * @param {string} suffix
586
- * @param {TransformContext} transform_context
587
- * @returns {any}
588
- */
589
- function create_helper_component_expression(
590
- body_nodes,
591
- helper_state,
592
- available_bindings,
593
- source_node,
594
- suffix,
595
- transform_context,
596
- ) {
597
- if (body_nodes.length === 0) {
598
- return create_null_literal();
599
- }
600
-
601
- const helper_name = create_helper_name(helper_state, suffix);
602
- const helper_id = set_loc(create_generated_identifier(helper_name), source_node);
603
- const helper_bindings = Array.from(available_bindings.values());
604
- const helper_fn = create_helper_function_declaration(
605
- helper_id,
606
- body_nodes,
607
- helper_state,
608
- available_bindings,
609
- helper_bindings,
610
- source_node,
611
- transform_context,
612
- );
613
-
614
- helper_state.helpers.push(helper_fn);
615
-
616
- return create_helper_component_element(helper_id, helper_bindings, source_node);
617
- }
618
-
619
- /**
620
- * @param {AST.Identifier} helper_id
621
- * @param {any[]} body_nodes
622
- * @param {{ base_name: string, next_id: number, helpers: AST.FunctionDeclaration[], statics: any[] }} helper_state
623
- * @param {Map<string, AST.Identifier>} available_bindings
624
- * @param {AST.Identifier[]} helper_bindings
625
- * @param {any} source_node
626
- * @param {TransformContext} transform_context
627
- * @returns {AST.FunctionDeclaration}
628
- */
629
- function create_helper_function_declaration(
630
- helper_id,
631
- body_nodes,
632
- helper_state,
633
- available_bindings,
634
- helper_bindings,
635
- source_node,
636
- transform_context,
637
- ) {
638
- const fn = /** @type {any} */ ({
639
- type: 'FunctionDeclaration',
640
- id: helper_id,
641
- params: helper_bindings.length > 0 ? [create_helper_props_pattern(helper_bindings)] : [],
642
- body: {
643
- type: 'BlockStatement',
644
- body: build_component_statements(
645
- body_nodes,
646
- helper_state,
647
- new Map(available_bindings),
648
- transform_context,
649
- ),
650
- metadata: { path: [] },
651
- },
652
- async: false,
653
- generator: false,
654
- metadata: {
655
- path: [],
656
- is_component: true,
657
- },
658
- });
659
-
660
- if (fn.id) {
661
- fn.id.metadata = /** @type {AST.Identifier['metadata']} */ ({
662
- ...fn.id.metadata,
663
- is_component: true,
664
- });
665
- }
666
-
667
- return set_loc(fn, source_node);
668
- }
669
-
670
- /**
671
- * @param {AST.Identifier[]} bindings
672
- * @returns {AST.ObjectPattern}
673
- */
674
- function create_helper_props_pattern(bindings) {
675
- return /** @type {any} */ ({
676
- type: 'ObjectPattern',
677
- properties: bindings.map((binding) => create_helper_props_property(binding)),
678
- metadata: { path: [] },
679
- });
680
- }
681
-
682
- /**
683
- * @param {AST.Identifier} binding
684
- * @returns {AST.Property}
685
- */
686
- function create_helper_props_property(binding) {
687
- const key = clone_identifier(binding);
688
- const value = clone_identifier(binding);
689
-
690
- return /** @type {any} */ ({
691
- type: 'Property',
692
- key,
693
- value,
694
- kind: 'init',
695
- method: false,
696
- shorthand: true,
697
- computed: false,
698
- metadata: { path: [] },
699
- });
700
- }
701
-
702
- /**
703
- * @param {AST.Identifier} helper_id
704
- * @param {AST.Identifier[]} bindings
705
- * @param {any} source_node
706
- * @returns {ESTreeJSX.JSXElement}
707
- */
708
- function create_helper_component_element(helper_id, bindings, source_node) {
709
- const attributes = bindings.map(
710
- (binding) =>
711
- /** @type {any} */ ({
712
- type: 'JSXAttribute',
713
- name: identifier_to_jsx_name(clone_identifier(binding)),
714
- value: to_jsx_expression_container(clone_identifier(binding), binding),
715
- metadata: { path: [] },
716
- }),
717
- );
718
-
719
- return set_loc(
720
- /** @type {any} */ ({
721
- type: 'JSXElement',
722
- openingElement: set_loc(
723
- {
724
- type: 'JSXOpeningElement',
725
- name: identifier_to_jsx_name(clone_identifier(helper_id)),
726
- attributes,
727
- selfClosing: true,
728
- metadata: { path: [] },
729
- },
730
- source_node,
731
- ),
732
- closingElement: null,
733
- children: [],
734
- metadata: { path: [] },
735
- }),
736
- source_node,
737
- );
738
- }
739
-
740
- /**
741
- * @param {{ base_name: string, next_id: number, helpers: AST.FunctionDeclaration[], statics: any[] }} helper_state
742
- * @param {string} suffix
743
- * @returns {string}
744
- */
745
- function create_helper_name(helper_state, suffix) {
746
- helper_state.next_id += 1;
747
- return `${helper_state.base_name}__${suffix}${helper_state.next_id}`;
748
- }
749
-
750
- /**
751
- * @param {string} base_name
752
- * @returns {{ base_name: string, next_id: number, helpers: AST.FunctionDeclaration[], statics: any[] }}
753
- */
754
- function create_helper_state(base_name) {
755
- return {
756
- base_name,
757
- next_id: 0,
758
- helpers: [],
759
- statics: [],
760
- };
761
- }
762
-
763
- /**
764
- * @param {any[]} params
765
- * @returns {Map<string, AST.Identifier>}
766
- */
767
- function collect_param_bindings(params) {
768
- const bindings = new Map();
769
- for (const param of params) {
770
- collect_pattern_bindings(param, bindings);
771
- }
772
- return bindings;
773
- }
774
-
775
- /**
776
- * @param {any} statement
777
- * @param {Map<string, AST.Identifier>} bindings
778
- * @returns {void}
779
- */
780
- function collect_statement_bindings(statement, bindings) {
781
- if (!statement) return;
782
-
783
- if (statement.type === 'VariableDeclaration') {
784
- for (const declaration of statement.declarations || []) {
785
- collect_pattern_bindings(declaration.id, bindings);
786
- }
787
- return;
788
- }
789
-
790
- if (
791
- (statement.type === 'FunctionDeclaration' || statement.type === 'ClassDeclaration') &&
792
- statement.id
793
- ) {
794
- bindings.set(statement.id.name, statement.id);
795
- }
796
-
797
- // Statement-level lazy assignment: `&[x] = expr;` introduces `x` as a binding.
798
- if (
799
- statement.type === 'ExpressionStatement' &&
800
- statement.expression?.type === 'AssignmentExpression' &&
801
- statement.expression.operator === '=' &&
802
- (statement.expression.left?.type === 'ObjectPattern' ||
803
- statement.expression.left?.type === 'ArrayPattern') &&
804
- statement.expression.left.lazy
805
- ) {
806
- collect_pattern_bindings(statement.expression.left, bindings);
807
- }
808
- }
809
-
810
- /**
811
- * @param {any} pattern
812
- * @param {Map<string, AST.Identifier>} bindings
813
- * @returns {void}
814
- */
815
- function collect_pattern_bindings(pattern, bindings) {
816
- if (!pattern || typeof pattern !== 'object') return;
817
-
818
- if (pattern.type === 'Identifier') {
819
- bindings.set(pattern.name, pattern);
820
- return;
821
- }
822
-
823
- if (pattern.type === 'RestElement') {
824
- collect_pattern_bindings(pattern.argument, bindings);
825
- return;
826
- }
827
-
828
- if (pattern.type === 'AssignmentPattern') {
829
- collect_pattern_bindings(pattern.left, bindings);
830
- return;
831
- }
832
-
833
- if (pattern.type === 'ArrayPattern') {
834
- for (const element of pattern.elements || []) {
835
- collect_pattern_bindings(element, bindings);
836
- }
837
- return;
838
- }
839
-
840
- if (pattern.type === 'ObjectPattern') {
841
- for (const property of pattern.properties || []) {
842
- if (property.type === 'RestElement') {
843
- collect_pattern_bindings(property.argument, bindings);
844
- } else {
845
- collect_pattern_bindings(property.value, bindings);
846
- }
847
- }
848
- }
849
- }
850
-
851
- /**
852
- * Check if a node references any of the given scope bindings.
853
- * Used to determine if a JSX element is static and can be hoisted to module level.
854
- *
855
- * @param {any} node
856
- * @param {Map<string, AST.Identifier>} scope_bindings
857
- * @returns {boolean}
858
- */
859
- function references_scope_bindings(node, scope_bindings) {
860
- if (!node || typeof node !== 'object') return false;
861
- if (scope_bindings.size === 0) return false;
862
-
863
- if (node.type === 'Identifier') {
864
- return scope_bindings.has(node.name);
865
- }
866
-
867
- // JSXIdentifier is a variable reference when capitalized (tag name like <MyComponent />)
868
- // or when it's the object of a JSXMemberExpression (e.g. ui in <ui.Button />)
869
- if (node.type === 'JSXIdentifier') {
870
- return scope_bindings.has(node.name);
871
- }
872
-
873
- if (Array.isArray(node)) {
874
- return node.some((child) => references_scope_bindings(child, scope_bindings));
875
- }
876
-
877
- for (const key of Object.keys(node)) {
878
- if (key === 'loc' || key === 'start' || key === 'end' || key === 'metadata') continue;
879
-
880
- // Skip non-computed, non-shorthand property keys (they are labels, not references)
881
- if (key === 'key' && node.type === 'Property' && !node.computed && !node.shorthand) continue;
882
-
883
- // Skip non-computed member expression property access
884
- if (key === 'property' && node.type === 'MemberExpression' && !node.computed) continue;
885
-
886
- // Skip JSXMemberExpression property (e.g. Button in <Icons.Button /> is a label, not a reference)
887
- if (key === 'property' && node.type === 'JSXMemberExpression') continue;
888
-
889
- // Skip JSXAttribute names — they are attribute labels, not variable references
890
- if (key === 'name' && node.type === 'JSXAttribute') continue;
891
-
892
- if (references_scope_bindings(node[key], scope_bindings)) return true;
893
- }
894
-
895
- return false;
896
- }
897
-
898
- /**
899
- * Hoist static JSX elements from render_nodes to module level.
900
- * A JSX element is static if it doesn't reference any component-scope bindings.
901
- * Hoisting prevents React from recreating the element on every render, allowing
902
- * the reconciler to skip diffing when it sees the same element identity.
903
- *
904
- * @param {any[]} render_nodes
905
- * @param {TransformContext} transform_context
906
- */
907
- function hoist_static_render_nodes(render_nodes, transform_context) {
908
- if (!transform_context.helper_state) return;
909
-
910
- for (let i = 0; i < render_nodes.length; i++) {
911
- const node = render_nodes[i];
912
- if (node.type !== 'JSXElement') continue;
913
- if (!is_hoist_safe_jsx_node(node)) continue;
914
- if (references_scope_bindings(node, transform_context.available_bindings)) continue;
915
-
916
- const name = create_helper_name(transform_context.helper_state, 'static');
917
- const id = create_generated_identifier(name);
918
-
919
- transform_context.helper_state.statics.push(
920
- /** @type {any} */ ({
921
- type: 'VariableDeclaration',
922
- kind: 'const',
923
- declarations: [
924
- {
925
- type: 'VariableDeclarator',
926
- id,
927
- init: node,
928
- metadata: { path: [] },
929
- },
930
- ],
931
- metadata: { path: [] },
932
- }),
933
- );
934
-
935
- render_nodes[i] = to_jsx_expression_container(clone_identifier(id), node);
936
- }
937
- }
938
-
939
- /**
940
- * @param {AST.Identifier} identifier
941
- * @returns {AST.Identifier}
942
- */
943
- function clone_identifier(identifier) {
944
- return set_loc(
945
- /** @type {any} */ ({
946
- type: 'Identifier',
947
- name: identifier.name,
948
- metadata: { path: [] },
949
- }),
950
- identifier,
951
- );
952
- }
953
-
954
- /**
955
- * @returns {AST.Literal}
956
- */
957
- function create_null_literal() {
958
- return /** @type {any} */ ({
959
- type: 'Literal',
960
- value: null,
961
- raw: 'null',
962
- metadata: { path: [] },
963
- });
964
- }
965
-
966
- /**
967
- * @param {AST.Program} program
968
- * @returns {AST.Program}
969
- */
970
- function expand_component_helpers(program) {
971
- program.body = program.body.flatMap((statement) => {
972
- if (statement.type === 'FunctionDeclaration') {
973
- const meta = /** @type {any} */ (statement.metadata);
974
- const statics = meta?.generated_statics || [];
975
- const helpers = meta?.generated_helpers || [];
976
- if (statics.length || helpers.length) {
977
- return [...statics, ...helpers, statement];
978
- }
979
- }
980
-
981
- if (
982
- (statement.type === 'ExportNamedDeclaration' ||
983
- statement.type === 'ExportDefaultDeclaration') &&
984
- statement.declaration?.type === 'FunctionDeclaration'
985
- ) {
986
- const meta = /** @type {any} */ (statement.declaration.metadata);
987
- const statics = meta?.generated_statics || [];
988
- const helpers = meta?.generated_helpers || [];
989
- if (statics.length || helpers.length) {
990
- return [...statics, ...helpers, statement];
991
- }
992
- }
993
-
994
- return [statement];
995
- });
996
-
997
- return program;
998
- }
999
-
1000
- /**
1001
- * @param {any} node
1002
- * @returns {boolean}
1003
- */
1004
- function is_bare_return_statement(node) {
1005
- return node?.type === 'ReturnStatement' && node.argument == null;
1006
- }
1007
-
1008
- /**
1009
- * @param {any} node
1010
- * @returns {boolean}
1011
- */
1012
- function is_lone_return_if_statement(node) {
1013
- if (node?.type !== 'IfStatement' || node.alternate) {
1014
- return false;
1015
- }
1016
-
1017
- const consequent_body =
1018
- node.consequent.type === 'BlockStatement' ? node.consequent.body : [node.consequent];
1019
-
1020
- return consequent_body.length === 1 && is_bare_return_statement(consequent_body[0]);
1021
- }
1022
-
1023
- /**
1024
- * @param {any[]} render_nodes
1025
- * @param {any} source_node
1026
- * @returns {any}
1027
- */
1028
- function create_component_return_statement(render_nodes, source_node) {
1029
- return /** @type {any} */ ({
1030
- type: 'ReturnStatement',
1031
- argument: build_return_expression(render_nodes.slice()) || {
1032
- type: 'Literal',
1033
- value: null,
1034
- raw: 'null',
1035
- metadata: { path: [] },
1036
- },
1037
- metadata: { path: [] },
1038
- });
1039
- }
1040
-
1041
- /**
1042
- * @param {any} node
1043
- * @param {any[]} render_nodes
1044
- * @returns {any}
1045
- */
1046
- function create_component_lone_return_if_statement(node, render_nodes) {
1047
- const consequent_body =
1048
- node.consequent.type === 'BlockStatement' ? node.consequent.body : [node.consequent];
1049
-
1050
- return set_loc(
1051
- /** @type {any} */ ({
1052
- type: 'IfStatement',
1053
- test: node.test,
1054
- consequent: set_loc(
1055
- /** @type {any} */ ({
1056
- type: 'BlockStatement',
1057
- body: [create_component_return_statement(render_nodes, consequent_body[0])],
1058
- metadata: { path: [] },
1059
- }),
1060
- node.consequent,
1061
- ),
1062
- alternate: null,
1063
- metadata: { path: [] },
1064
- }),
1065
- node,
1066
- );
1067
- }
1068
-
1069
- /**
1070
- * @param {any} node
1071
- * @returns {boolean}
1072
- */
1073
- function is_jsx_child(node) {
1074
- if (!node) return false;
1075
- const t = node.type;
1076
- return (
1077
- t === 'JSXElement' ||
1078
- t === 'JSXFragment' ||
1079
- t === 'JSXExpressionContainer' ||
1080
- t === 'JSXText' ||
1081
- t === 'Tsx' ||
1082
- t === 'TsxCompat' ||
1083
- t === 'Element' ||
1084
- t === 'Text' ||
1085
- t === 'TSRXExpression' ||
1086
- t === 'Html' ||
1087
- t === 'IfStatement' ||
1088
- t === 'ForOfStatement' ||
1089
- t === 'SwitchStatement' ||
1090
- t === 'TryStatement'
1091
- );
1092
- }
1093
-
1094
- const TEMPLATE_FRAGMENT_ERROR =
1095
- 'JSX fragment syntax is not needed in TSRX templates. TSRX renders in immediate mode, so everything is already a fragment. Use `<>...</>` only within <tsx>...</tsx>.';
1096
-
1097
- /**
1098
- * @param {any} node
1099
- * @param {TransformContext} transform_context
1100
- * @returns {any}
1101
- */
1102
- function to_jsx_element(node, transform_context) {
1103
- if (node.type === 'JSXElement') return node;
1104
- if ((node.children || []).some((/** @type {any} */ c) => c && c.type === 'Html')) {
1105
- throw new Error(
1106
- '`{html ...}` is not supported on the React target. Use `dangerouslySetInnerHTML={{ __html: ... }}` as an element attribute instead.',
1107
- );
1108
- }
1109
- if (!node.id) {
1110
- throw create_compile_error(node, TEMPLATE_FRAGMENT_ERROR);
1111
- }
1112
- if (is_dynamic_element_id(node.id)) {
1113
- return dynamic_element_to_jsx_child(node, transform_context);
1114
- }
1115
-
1116
- const name = identifier_to_jsx_name(node.id);
1117
- const attributes = (node.attributes || []).map(to_jsx_attribute);
1118
- const selfClosing = !!node.selfClosing;
1119
- const children = create_element_children(node.children || [], transform_context);
1120
- const has_unmappable_attribute = attributes.some(
1121
- (/** @type {any} */ attribute) => attribute?.metadata?.has_unmappable_value,
1122
- );
1123
-
1124
- /** @type {ESTreeJSX.JSXOpeningElement} */
1125
- const openingElement = /** @type {ESTreeJSX.JSXOpeningElement} */ (
1126
- has_unmappable_attribute
1127
- ? {
1128
- type: 'JSXOpeningElement',
1129
- name,
1130
- attributes,
1131
- selfClosing,
1132
- metadata: { path: [] },
1133
- }
1134
- : set_loc(
1135
- /** @type {any} */ ({
1136
- type: 'JSXOpeningElement',
1137
- name,
1138
- attributes,
1139
- selfClosing,
1140
- }),
1141
- node.openingElement || node,
1142
- )
1143
- );
1144
-
1145
- /** @type {ESTreeJSX.JSXClosingElement | null} */
1146
- const closingElement = selfClosing
1147
- ? null
1148
- : set_loc(
1149
- /** @type {any} */ ({
1150
- type: 'JSXClosingElement',
1151
- name: clone_jsx_name(name, node.closingElement || node),
1152
- }),
1153
- node.closingElement || node,
1154
- );
1155
-
1156
- return set_loc(
1157
- /** @type {any} */ ({
1158
- type: 'JSXElement',
1159
- openingElement,
1160
- closingElement,
1161
- children,
1162
- }),
1163
- node,
1164
- );
1165
- }
1166
-
1167
- /**
1168
- * @param {any[]} children
1169
- * @param {TransformContext} transform_context
1170
- * @returns {any[]}
1171
- */
1172
-
1173
- function create_element_children(children, transform_context) {
1174
- if (children.length === 0) {
1175
- return [];
1176
- }
1177
-
1178
- if (children.every(is_inline_element_child) && !children_contain_return_semantics(children)) {
1179
- return children.map((/** @type {any} */ child) => to_jsx_child(child, transform_context));
1180
- }
1181
-
1182
- return [statement_body_to_jsx_child(children, transform_context)];
1183
- }
1184
-
1185
- /**
1186
- * @param {any[]} children
1187
- * @returns {boolean}
1188
- */
1189
- function children_contain_return_semantics(children) {
1190
- return children.some(child_contains_return_semantics);
1191
- }
1192
-
1193
- /**
1194
- * @param {any} node
1195
- * @returns {boolean}
1196
- */
1197
- function child_contains_return_semantics(node) {
1198
- if (!node || typeof node !== 'object') {
1199
- return false;
1200
- }
1201
-
1202
- if (node.type === 'ReturnStatement' || is_lone_return_if_statement(node)) {
1203
- return true;
1204
- }
1205
-
1206
- if (
1207
- node.type === 'FunctionDeclaration' ||
1208
- node.type === 'FunctionExpression' ||
1209
- node.type === 'ArrowFunctionExpression' ||
1210
- node.type === 'Component'
1211
- ) {
1212
- return false;
1213
- }
1214
-
1215
- if (Array.isArray(node)) {
1216
- return node.some(child_contains_return_semantics);
1217
- }
1218
-
1219
- for (const key of Object.keys(node)) {
1220
- if (key === 'loc' || key === 'start' || key === 'end' || key === 'metadata') {
1221
- continue;
1222
- }
1223
- if (child_contains_return_semantics(node[key])) {
1224
- return true;
1225
- }
1226
- }
1227
-
1228
- return false;
1229
- }
1230
-
1231
- /**
1232
- * @param {any} node
1233
- * @returns {boolean}
1234
- */
1235
- function is_inline_element_child(node) {
1236
- return node && is_jsx_child(node);
1237
- }
1238
-
1239
- /**
1240
- * @param {any[]} body_nodes
1241
- * @param {TransformContext} transform_context
1242
- * @returns {ESTreeJSX.JSXExpressionContainer}
1243
- */
1244
- function statement_body_to_jsx_child(body_nodes, transform_context) {
1245
- if (body_contains_top_level_hook_call(body_nodes)) {
1246
- return hook_safe_statement_body_to_jsx_child(body_nodes, transform_context);
1247
- }
1248
-
1249
- return to_jsx_expression_container(
1250
- /** @type {any} */ ({
1251
- type: 'CallExpression',
1252
- callee: {
1253
- type: 'ArrowFunctionExpression',
1254
- params: [],
1255
- body: /** @type {any} */ ({
1256
- type: 'BlockStatement',
1257
- body: build_render_statements(body_nodes, true, transform_context),
1258
- metadata: { path: [] },
1259
- }),
1260
- async: false,
1261
- generator: false,
1262
- expression: false,
1263
- metadata: { path: [] },
1264
- },
1265
- arguments: [],
1266
- optional: false,
1267
- metadata: { path: [] },
1268
- }),
1269
- );
1270
- }
1271
-
1272
- /**
1273
- * @param {any[]} body_nodes
1274
- * @param {TransformContext} transform_context
1275
- * @returns {ESTreeJSX.JSXExpressionContainer}
1276
- */
1277
- function hook_safe_statement_body_to_jsx_child(body_nodes, transform_context) {
1278
- const source_node = get_body_source_node(body_nodes);
1279
- const helper_id = set_loc(
1280
- create_generated_identifier(create_local_statement_component_name(transform_context)),
1281
- source_node,
1282
- );
1283
- const helper_bindings = Array.from(transform_context.available_bindings.values());
1284
-
1285
- // Save and isolate bindings for the helper body
1286
- const saved_bindings = transform_context.available_bindings;
1287
- transform_context.available_bindings = new Map(saved_bindings);
1288
-
1289
- const helper_fn = set_loc(
1290
- /** @type {any} */ ({
1291
- type: 'FunctionDeclaration',
1292
- id: helper_id,
1293
- params: helper_bindings.length > 0 ? [create_helper_props_pattern(helper_bindings)] : [],
1294
- body: {
1295
- type: 'BlockStatement',
1296
- body: build_render_statements(body_nodes, true, transform_context),
1297
- metadata: { path: [] },
1298
- },
1299
- async: false,
1300
- generator: false,
1301
- metadata: {
1302
- path: [],
1303
- is_component: true,
1304
- is_method: false,
1305
- },
1306
- }),
1307
- source_node,
1308
- );
1309
-
1310
- // Restore bindings
1311
- transform_context.available_bindings = saved_bindings;
1312
-
1313
- // Register helper for hoisting to module level
1314
- if (transform_context.helper_state) {
1315
- transform_context.helper_state.helpers.push(helper_fn);
1316
-
1317
- return to_jsx_expression_container(
1318
- /** @type {any} */ (create_helper_component_element(helper_id, helper_bindings, source_node)),
1319
- source_node,
1320
- );
1321
- }
1322
-
1323
- return to_jsx_expression_container(
1324
- /** @type {any} */ ({
1325
- type: 'CallExpression',
1326
- callee: {
1327
- type: 'ArrowFunctionExpression',
1328
- params: [],
1329
- body: /** @type {any} */ ({
1330
- type: 'BlockStatement',
1331
- body: [
1332
- helper_fn,
1333
- {
1334
- type: 'ReturnStatement',
1335
- argument: create_helper_component_element(helper_id, helper_bindings, source_node),
1336
- metadata: { path: [] },
1337
- },
1338
- ],
1339
- metadata: { path: [] },
1340
- }),
1341
- async: false,
1342
- generator: false,
1343
- expression: false,
1344
- metadata: { path: [] },
1345
- },
1346
- arguments: [],
1347
- optional: false,
1348
- metadata: { path: [] },
1349
- }),
1350
- source_node,
1351
- );
1352
- }
1353
-
1354
- /**
1355
- * @param {TransformContext} transform_context
1356
- * @returns {string}
1357
- */
1358
- function create_local_statement_component_name(transform_context) {
1359
- transform_context.local_statement_component_index += 1;
1360
- return `StatementBodyHook${transform_context.local_statement_component_index}`;
1361
- }
1362
-
1363
- /**
1364
- * Wraps a list of body nodes into a component and returns
1365
- * statements that return `<ComponentName prop1={prop1} ... />`.
1366
- * The component is hoisted to module level via helper_state to avoid
1367
- * recreating the component identity on every render.
1368
- * Used when a control flow branch contains hook calls that must be moved
1369
- * into their own component boundary to satisfy the Rules of Hooks.
1370
- *
1371
- * @param {any[]} body_nodes
1372
- * @param {any} key_expression - Optional key expression to add to the component element (for for-of loops)
1373
- * @param {TransformContext} transform_context
1374
- * @returns {any[]}
1375
- */
1376
- function hook_safe_render_statements(body_nodes, key_expression, transform_context) {
1377
- const source_node = get_body_source_node(body_nodes);
1378
- const helper_id = set_loc(
1379
- create_generated_identifier(create_local_statement_component_name(transform_context)),
1380
- source_node,
1381
- );
1382
- const helper_bindings = Array.from(transform_context.available_bindings.values());
1383
-
1384
- // Save and isolate bindings for the helper body
1385
- const saved_bindings = transform_context.available_bindings;
1386
- transform_context.available_bindings = new Map(saved_bindings);
1387
-
1388
- const helper_fn = set_loc(
1389
- /** @type {any} */ ({
1390
- type: 'FunctionDeclaration',
1391
- id: helper_id,
1392
- params: helper_bindings.length > 0 ? [create_helper_props_pattern(helper_bindings)] : [],
1393
- body: {
1394
- type: 'BlockStatement',
1395
- body: build_render_statements(body_nodes, true, transform_context),
1396
- metadata: { path: [] },
1397
- },
1398
- async: false,
1399
- generator: false,
1400
- metadata: {
1401
- path: [],
1402
- is_component: true,
1403
- is_method: false,
1404
- },
1405
- }),
1406
- source_node,
1407
- );
1408
-
1409
- // Restore bindings
1410
- transform_context.available_bindings = saved_bindings;
1411
-
1412
- // Register helper for hoisting to module level
1413
- if (transform_context.helper_state) {
1414
- transform_context.helper_state.helpers.push(helper_fn);
1415
- }
1416
-
1417
- const component_element = create_helper_component_element(
1418
- helper_id,
1419
- helper_bindings,
1420
- source_node,
1421
- );
1422
-
1423
- if (key_expression) {
1424
- component_element.openingElement.attributes.push(
1425
- /** @type {any} */ ({
1426
- type: 'JSXAttribute',
1427
- name: { type: 'JSXIdentifier', name: 'key', metadata: { path: [] } },
1428
- value: to_jsx_expression_container(key_expression, key_expression),
1429
- metadata: { path: [] },
1430
- }),
1431
- );
1432
- }
1433
-
1434
- // When helper_state is null (no enclosing component context), inline the
1435
- // helper via an IIFE so the function declaration isn't silently dropped.
1436
- if (!transform_context.helper_state) {
1437
- return [
1438
- helper_fn,
1439
- {
1440
- type: 'ReturnStatement',
1441
- argument: component_element,
1442
- metadata: { path: [] },
1443
- },
1444
- ];
1445
- }
1446
-
1447
- return [
1448
- {
1449
- type: 'ReturnStatement',
1450
- argument: component_element,
1451
- metadata: { path: [] },
1452
- },
1453
- ];
1454
- }
1455
-
1456
- /**
1457
- * @param {any[]} body_nodes
1458
- * @returns {any}
1459
- */
1460
- function get_body_source_node(body_nodes) {
1461
- const first = body_nodes[0];
1462
- const last = body_nodes[body_nodes.length - 1];
1463
-
1464
- if (first?.loc && last?.loc) {
1465
- return {
1466
- start: first.start,
1467
- end: last.end,
1468
- loc: {
1469
- start: first.loc.start,
1470
- end: last.loc.end,
1471
- },
1472
- };
1473
- }
1474
-
1475
- return first;
1476
- }
1477
-
1478
- /**
1479
- * @param {any} node
1480
- * @param {TransformContext} transform_context
1481
- * @returns {any}
1482
- */
1483
- function to_jsx_child(node, transform_context) {
1484
- if (!node) return node;
1485
- switch (node.type) {
1486
- case 'Tsx':
1487
- return tsx_node_to_jsx_expression(node);
1488
- case 'TsxCompat':
1489
- return tsx_compat_node_to_jsx_expression(node);
1490
- case 'Element':
1491
- return to_jsx_element(node, transform_context);
1492
- case 'Text':
1493
- return to_jsx_expression_container(to_text_expression(node.expression, node), node);
1494
- case 'TSRXExpression':
1495
- return to_jsx_expression_container(node.expression, node);
1496
- case 'Html':
1497
- throw new Error(
1498
- '`{html ...}` is not supported on the React target. Use `dangerouslySetInnerHTML={{ __html: ... }}` as an element attribute instead.',
1499
- );
1500
- case 'IfStatement':
1501
- return if_statement_to_jsx_child(node, transform_context);
1502
- case 'ForOfStatement':
1503
- return for_of_statement_to_jsx_child(node, transform_context);
1504
- case 'SwitchStatement':
1505
- return switch_statement_to_jsx_child(node, transform_context);
1506
- case 'TryStatement':
1507
- return try_statement_to_jsx_child(node, transform_context);
1508
- default:
1509
- return node;
1510
- }
1511
- }
1512
-
1513
- /**
1514
- * @param {any} node
1515
- * @param {TransformContext} transform_context
1516
- * @returns {ESTreeJSX.JSXExpressionContainer}
1517
- */
1518
- function if_statement_to_jsx_child(node, transform_context) {
1519
- return to_jsx_expression_container(
1520
- /** @type {any} */ ({
1521
- type: 'CallExpression',
1522
- callee: {
1523
- type: 'ArrowFunctionExpression',
1524
- params: [],
1525
- body: /** @type {any} */ ({
1526
- type: 'BlockStatement',
1527
- body: [
1528
- create_render_if_statement(node, transform_context),
1529
- create_null_return_statement(),
1530
- ],
1531
- metadata: { path: [] },
1532
- }),
1533
- async: false,
1534
- generator: false,
1535
- expression: false,
1536
- metadata: { path: [] },
1537
- },
1538
- arguments: [],
1539
- optional: false,
1540
- metadata: { path: [] },
1541
- }),
1542
- );
1543
- }
1544
-
1545
- /**
1546
- * Find the first `key` attribute expression in the top-level elements of a body.
1547
- * Used to propagate keys from loop body elements to wrapper components.
1548
- * Works on both pre-transform (Ripple Element) and post-transform (JSXElement) nodes.
1549
- *
1550
- * @param {any[]} body_nodes
1551
- * @returns {any | undefined}
1552
- */
1553
- function find_key_expression_in_body(body_nodes) {
1554
- for (const node of body_nodes) {
1555
- // Pre-transform: Ripple Element node
1556
- if (node.type === 'Element') {
1557
- for (const attr of node.attributes || []) {
1558
- if (attr.type === 'Attribute') {
1559
- const attr_name = typeof attr.name === 'string' ? attr.name : attr.name?.name;
1560
- if (attr_name === 'key') {
1561
- return attr.value?.expression ?? attr.value;
1562
- }
1563
- }
1564
- }
1565
- }
1566
- // Post-transform: JSXElement node
1567
- if (node.type === 'JSXElement') {
1568
- for (const attr of node.openingElement?.attributes || []) {
1569
- if (
1570
- attr.type === 'JSXAttribute' &&
1571
- attr.name?.type === 'JSXIdentifier' &&
1572
- attr.name.name === 'key'
1573
- ) {
1574
- // Value is a JSXExpressionContainer
1575
- if (attr.value?.type === 'JSXExpressionContainer') {
1576
- return attr.value.expression;
1577
- }
1578
- return attr.value;
1579
- }
1580
- }
1581
- }
1582
- }
1583
- return undefined;
1584
- }
1585
-
1586
- /**
1587
- * @param {any} node
1588
- * @param {TransformContext} transform_context
1589
- * @returns {ESTreeJSX.JSXExpressionContainer}
1590
- */
1591
- function for_of_statement_to_jsx_child(node, transform_context) {
1592
- if (node.await) {
1593
- throw create_compile_error(
1594
- node,
1595
- 'React TSRX does not support `for await...of` in component templates.',
1596
- );
1597
- }
1598
-
1599
- const loop_params = get_for_of_iteration_params(node.left, node.index);
1600
- const loop_body = node.body.type === 'BlockStatement' ? node.body.body : [node.body];
1601
- const has_hooks = body_contains_top_level_hook_call(loop_body);
1602
- const body_key_expression = find_key_expression_in_body(loop_body);
1603
- const explicit_key_expression =
1604
- body_key_expression ?? (node.key ? clone_expression_node(node.key) : undefined);
1605
- const key_expression =
1606
- has_hooks && explicit_key_expression == null && node.index
1607
- ? clone_expression_node(node.index)
1608
- : explicit_key_expression;
1609
- const implicit_non_hook_key_expression =
1610
- !has_hooks && body_key_expression == null
1611
- ? node.key
1612
- ? clone_expression_node(node.key)
1613
- : node.index
1614
- ? clone_expression_node(node.index)
1615
- : undefined
1616
- : undefined;
1617
-
1618
- // Add loop params to available bindings so hoisted helpers receive them as props
1619
- const saved_bindings = transform_context.available_bindings;
1620
- transform_context.available_bindings = new Map(saved_bindings);
1621
- for (const param of loop_params) {
1622
- collect_pattern_bindings(param, transform_context.available_bindings);
1623
- }
1624
-
1625
- const body_statements = has_hooks
1626
- ? hook_safe_render_statements(loop_body, key_expression, transform_context)
1627
- : build_render_statements(loop_body, true, transform_context);
1628
-
1629
- if (implicit_non_hook_key_expression) {
1630
- apply_key_to_render_statements(body_statements, implicit_non_hook_key_expression);
1631
- }
1632
-
1633
- // Restore bindings
1634
- transform_context.available_bindings = saved_bindings;
1635
-
1636
- return to_jsx_expression_container(
1637
- /** @type {any} */ ({
1638
- type: 'CallExpression',
1639
- callee: {
1640
- type: 'MemberExpression',
1641
- object: node.right,
1642
- property: create_generated_identifier('map'),
1643
- computed: false,
1644
- optional: false,
1645
- metadata: { path: [] },
1646
- },
1647
- arguments: [
1648
- {
1649
- type: 'ArrowFunctionExpression',
1650
- params: loop_params,
1651
- body: /** @type {any} */ ({
1652
- type: 'BlockStatement',
1653
- body: body_statements,
1654
- metadata: { path: [] },
1655
- }),
1656
- async: false,
1657
- generator: false,
1658
- expression: false,
1659
- metadata: { path: [] },
1660
- },
1661
- ],
1662
- async: false,
1663
- optional: false,
1664
- metadata: { path: [] },
1665
- }),
1666
- );
1667
- }
1668
-
1669
- /**
1670
- * @param {any[]} statements
1671
- * @param {any} key_expression
1672
- * @returns {void}
1673
- */
1674
- function apply_key_to_render_statements(statements, key_expression) {
1675
- for (let i = statements.length - 1; i >= 0; i -= 1) {
1676
- const statement = statements[i];
1677
- if (statement?.type !== 'ReturnStatement' || !statement.argument) {
1678
- continue;
1679
- }
1680
-
1681
- if (statement.argument.type === 'JSXElement') {
1682
- const attributes = statement.argument.openingElement?.attributes || [];
1683
- const has_key = attributes.some(
1684
- (/** @type {any} */ attr) =>
1685
- attr.type === 'JSXAttribute' &&
1686
- attr.name?.type === 'JSXIdentifier' &&
1687
- attr.name.name === 'key',
1688
- );
1689
-
1690
- if (!has_key) {
1691
- attributes.push(
1692
- /** @type {any} */ ({
1693
- type: 'JSXAttribute',
1694
- name: { type: 'JSXIdentifier', name: 'key', metadata: { path: [] } },
1695
- value: to_jsx_expression_container(
1696
- clone_expression_node(key_expression),
1697
- key_expression,
1698
- ),
1699
- metadata: { path: [] },
1700
- }),
1701
- );
1702
- }
1703
- }
1704
-
1705
- return;
1706
- }
1707
- }
1708
-
1709
- /**
1710
- * @param {any} node
1711
- * @param {TransformContext} transform_context
1712
- * @returns {ESTreeJSX.JSXExpressionContainer}
1713
- */
1714
- function switch_statement_to_jsx_child(node, transform_context) {
1715
- return to_jsx_expression_container(
1716
- /** @type {any} */ ({
1717
- type: 'CallExpression',
1718
- callee: {
1719
- type: 'ArrowFunctionExpression',
1720
- params: [],
1721
- body: /** @type {any} */ ({
1722
- type: 'BlockStatement',
1723
- body: [
1724
- create_render_switch_statement(node, transform_context),
1725
- create_null_return_statement(),
1726
- ],
1727
- metadata: { path: [] },
1728
- }),
1729
- async: false,
1730
- generator: false,
1731
- expression: false,
1732
- metadata: { path: [] },
1733
- },
1734
- arguments: [],
1735
- optional: false,
1736
- metadata: { path: [] },
1737
- }),
1738
- );
1739
- }
1740
-
1741
- /**
1742
- * Transform a `try { ... } pending { ... } catch (err, reset) { ... }` block
1743
- * into React `<TsrxErrorBoundary>` and/or `<Suspense>` JSX elements.
1744
- *
1745
- * - `pending` → `<Suspense fallback={...}>`
1746
- * - `catch` → `<TsrxErrorBoundary fallback={(err, reset) => ...}>`
1747
- * - both → ErrorBoundary wraps Suspense
1748
- * - `finally` blocks are not supported in component template context
1749
- *
1750
- * @param {any} node
1751
- * @param {TransformContext} transform_context
1752
- * @returns {ESTreeJSX.JSXExpressionContainer}
1753
- */
1754
- function try_statement_to_jsx_child(node, transform_context) {
1755
- const pending = node.pending;
1756
- const handler = node.handler;
1757
- const finalizer = node.finalizer;
1758
-
1759
- if (finalizer) {
1760
- throw create_compile_error(
1761
- finalizer,
1762
- 'React TSRX does not support `finally` blocks in component templates. Move the try statement into a function if you need a finally block.',
1763
- );
1764
- }
1765
-
1766
- if (!pending && !handler) {
1767
- throw create_compile_error(
1768
- node,
1769
- 'Component try statements must have a `pending` or `catch` block.',
1770
- );
1771
- }
1772
-
1773
- // Validate that try body contains JSX if pending block is present
1774
- if (pending) {
1775
- const try_body = node.block.body || [];
1776
- if (!try_body.some(is_jsx_child)) {
1777
- throw create_compile_error(
1778
- node.block,
1779
- 'Component try statements must contain a template in their main body. Move the try statement into a function if it does not render anything.',
1780
- );
1781
- }
1782
- const pending_body = pending.body || [];
1783
- if (!pending_body.some(is_jsx_child)) {
1784
- throw create_compile_error(
1785
- pending,
1786
- 'Component try statements must contain a template in their "pending" body. Rendering a pending fallback is required to have a template.',
1787
- );
1788
- }
1789
- }
1790
-
1791
- // Build the try body content as JSX children
1792
- const try_body_nodes = node.block.body || [];
1793
- const try_content = statement_body_to_jsx_child(try_body_nodes, transform_context);
1794
-
1795
- /** @type {any} */
1796
- let result = try_content;
1797
-
1798
- // Wrap in <Suspense> if pending block exists
1799
- if (pending) {
1800
- transform_context.needs_suspense = true;
1801
- const pending_body_nodes = pending.body || [];
1802
- const fallback_content = statement_body_to_jsx_child(pending_body_nodes, transform_context);
1803
-
1804
- result = create_jsx_element(
1805
- 'Suspense',
1806
- [
1807
- {
1808
- type: 'JSXAttribute',
1809
- name: { type: 'JSXIdentifier', name: 'fallback', metadata: { path: [] } },
1810
- value: fallback_content,
1811
- metadata: { path: [] },
1812
- },
1813
- ],
1814
- [result],
1815
- );
1816
- }
1817
-
1818
- // Wrap in <TsrxErrorBoundary> if catch block exists
1819
- if (handler) {
1820
- transform_context.needs_error_boundary = true;
1821
-
1822
- const catch_params = [];
1823
- if (handler.param) {
1824
- catch_params.push(handler.param);
1825
- } else {
1826
- catch_params.push(create_generated_identifier('_error'));
1827
- }
1828
- if (handler.resetParam) {
1829
- catch_params.push(handler.resetParam);
1830
- } else {
1831
- catch_params.push(create_generated_identifier('_reset'));
1832
- }
1833
-
1834
- const catch_body_nodes = handler.body.body || [];
1835
-
1836
- // Add catch params to available_bindings so static hoisting
1837
- // correctly identifies references to err/reset as non-static
1838
- const saved_catch_bindings = transform_context.available_bindings;
1839
- transform_context.available_bindings = new Map(saved_catch_bindings);
1840
- for (const param of catch_params) {
1841
- collect_pattern_bindings(param, transform_context.available_bindings);
1842
- }
1843
-
1844
- const fallback_fn = {
1845
- type: 'ArrowFunctionExpression',
1846
- params: catch_params,
1847
- body: /** @type {any} */ ({
1848
- type: 'BlockStatement',
1849
- body: build_render_statements(catch_body_nodes, true, transform_context),
1850
- metadata: { path: [] },
1851
- }),
1852
- async: false,
1853
- generator: false,
1854
- expression: false,
1855
- metadata: { path: [] },
1856
- };
1857
-
1858
- transform_context.available_bindings = saved_catch_bindings;
1859
-
1860
- result = create_jsx_element(
1861
- 'TsrxErrorBoundary',
1862
- [
1863
- {
1864
- type: 'JSXAttribute',
1865
- name: { type: 'JSXIdentifier', name: 'fallback', metadata: { path: [] } },
1866
- value: to_jsx_expression_container(/** @type {any} */ (fallback_fn)),
1867
- metadata: { path: [] },
1868
- },
1869
- ],
1870
- [result],
1871
- );
1872
- }
1873
-
1874
- // result is a JSXElement, but we need to return a JSXExpressionContainer
1875
- // for embedding in the parent component's render return
1876
- if (result.type === 'JSXElement') {
1877
- return to_jsx_expression_container(result);
1878
- }
1879
-
1880
- return result;
1881
- }
1882
-
1883
- /**
1884
- * Create a simple JSX element AST node.
1885
- *
1886
- * @param {string} tag_name
1887
- * @param {any[]} attributes
1888
- * @param {any[]} children
1889
- * @returns {any}
1890
- */
1891
- function create_jsx_element(tag_name, attributes, children) {
1892
- const name = { type: 'JSXIdentifier', name: tag_name, metadata: { path: [] } };
1893
- return {
1894
- type: 'JSXElement',
1895
- openingElement: {
1896
- type: 'JSXOpeningElement',
1897
- name,
1898
- attributes,
1899
- selfClosing: children.length === 0,
1900
- metadata: { path: [] },
1901
- },
1902
- closingElement:
1903
- children.length > 0
1904
- ? {
1905
- type: 'JSXClosingElement',
1906
- name: { type: 'JSXIdentifier', name: tag_name, metadata: { path: [] } },
1907
- metadata: { path: [] },
1908
- }
1909
- : null,
1910
- children,
1911
- metadata: { path: [] },
1912
- };
1913
- }
1914
-
1915
- /**
1916
- * Inject import declarations for `Suspense` and `TsrxErrorBoundary` if the
1917
- * transform determined they are needed.
1918
- *
1919
- * @param {AST.Program} program
1920
- * @param {TransformContext} transform_context
1921
- */
1922
- function inject_try_imports(program, transform_context) {
1923
- /** @type {any[]} */
1924
- const imports = [];
1925
-
1926
- if (transform_context.needs_suspense) {
1927
- imports.push({
1928
- type: 'ImportDeclaration',
1929
- specifiers: [
1930
- {
1931
- type: 'ImportSpecifier',
1932
- imported: { type: 'Identifier', name: 'Suspense', metadata: { path: [] } },
1933
- local: { type: 'Identifier', name: 'Suspense', metadata: { path: [] } },
1934
- metadata: { path: [] },
1935
- },
1936
- ],
1937
- source: { type: 'Literal', value: 'react', raw: "'react'" },
1938
- metadata: { path: [] },
1939
- });
1940
- }
1941
-
1942
- if (transform_context.needs_error_boundary) {
1943
- imports.push({
1944
- type: 'ImportDeclaration',
1945
- specifiers: [
1946
- {
1947
- type: 'ImportSpecifier',
1948
- imported: {
1949
- type: 'Identifier',
1950
- name: 'TsrxErrorBoundary',
1951
- metadata: { path: [] },
1952
- },
1953
- local: {
1954
- type: 'Identifier',
1955
- name: 'TsrxErrorBoundary',
1956
- metadata: { path: [] },
1957
- },
1958
- metadata: { path: [] },
1959
- },
1960
- ],
1961
- source: {
1962
- type: 'Literal',
1963
- value: '@tsrx/react/error-boundary',
1964
- raw: "'@tsrx/react/error-boundary'",
1965
- },
1966
- metadata: { path: [] },
1967
- });
1968
- }
1969
-
1970
- if (imports.length > 0) {
1971
- program.body.unshift(...imports);
1972
- }
1973
- }
1974
-
1975
- /**
1976
- * @param {any} node
1977
- * @param {TransformContext} transform_context
1978
- * @returns {any}
1979
- */
1980
- function create_render_if_statement(node, transform_context) {
1981
- const consequent_body =
1982
- node.consequent.type === 'BlockStatement' ? node.consequent.body : [node.consequent];
1983
- const consequent_has_hooks = body_contains_top_level_hook_call(consequent_body);
1984
-
1985
- let alternate = null;
1986
- if (node.alternate) {
1987
- if (node.alternate.type === 'IfStatement') {
1988
- alternate = create_render_if_statement(node.alternate, transform_context);
1989
- } else {
1990
- const alternate_body = node.alternate.body || [node.alternate];
1991
- const alternate_has_hooks = body_contains_top_level_hook_call(alternate_body);
1992
- alternate = set_loc(
1993
- /** @type {any} */ ({
1994
- type: 'BlockStatement',
1995
- body: alternate_has_hooks
1996
- ? hook_safe_render_statements(alternate_body, undefined, transform_context)
1997
- : build_render_statements(alternate_body, true, transform_context),
1998
- metadata: { path: [] },
1999
- }),
2000
- node.alternate,
2001
- );
2002
- }
2003
- }
2004
-
2005
- return set_loc(
2006
- {
2007
- type: 'IfStatement',
2008
- test: node.test,
2009
- consequent: set_loc(
2010
- /** @type {any} */ ({
2011
- type: 'BlockStatement',
2012
- body: consequent_has_hooks
2013
- ? hook_safe_render_statements(consequent_body, undefined, transform_context)
2014
- : build_render_statements(consequent_body, true, transform_context),
2015
- metadata: { path: [] },
2016
- }),
2017
- node.consequent,
2018
- ),
2019
- alternate,
2020
- },
2021
- node,
2022
- );
2023
- }
2024
-
2025
- /**
2026
- * @param {any} node
2027
- * @param {TransformContext} transform_context
2028
- * @returns {any}
2029
- */
2030
- function create_render_switch_statement(node, transform_context) {
2031
- return /** @type {any} */ ({
2032
- type: 'SwitchStatement',
2033
- discriminant: node.discriminant,
2034
- cases: node.cases.map((/** @type {any} */ c) =>
2035
- create_render_switch_case(c, transform_context),
2036
- ),
2037
- metadata: { path: [] },
2038
- });
2039
- }
2040
-
2041
- /**
2042
- * @param {any} switch_case
2043
- * @param {TransformContext} transform_context
2044
- * @returns {any}
2045
- */
2046
- function create_render_switch_case(switch_case, transform_context) {
2047
- const consequent = flatten_switch_consequent(switch_case.consequent || []);
2048
-
2049
- // Strip trailing break statements for hook analysis
2050
- const body_without_break = [];
2051
- for (const child of consequent) {
2052
- if (child.type === 'BreakStatement') break;
2053
- body_without_break.push(child);
2054
- }
2055
-
2056
- if (body_contains_top_level_hook_call(body_without_break)) {
2057
- return /** @type {any} */ ({
2058
- type: 'SwitchCase',
2059
- test: switch_case.test,
2060
- consequent: hook_safe_render_statements(body_without_break, undefined, transform_context),
2061
- metadata: { path: [] },
2062
- });
2063
- }
2064
-
2065
- const case_body = [];
2066
- const render_nodes = [];
2067
- let has_terminal = false;
2068
-
2069
- for (const child of consequent) {
2070
- if (child.type === 'BreakStatement') {
2071
- if (render_nodes.length > 0 && !has_terminal) {
2072
- case_body.push(create_component_return_statement(render_nodes, switch_case));
2073
- } else if (!has_terminal) {
2074
- case_body.push(child);
2075
- }
2076
- has_terminal = true;
2077
- break;
2078
- }
2079
-
2080
- if (is_bare_return_statement(child)) {
2081
- case_body.push(create_component_return_statement(render_nodes, child));
2082
- has_terminal = true;
2083
- break;
2084
- }
2085
-
2086
- if (is_jsx_child(child)) {
2087
- render_nodes.push(to_jsx_child(child, transform_context));
2088
- } else {
2089
- case_body.push(child);
2090
- }
2091
- }
2092
-
2093
- if (!has_terminal && render_nodes.length > 0) {
2094
- case_body.push(create_component_return_statement(render_nodes, switch_case));
2095
- }
2096
-
2097
- return /** @type {any} */ ({
2098
- type: 'SwitchCase',
2099
- test: switch_case.test,
2100
- consequent: case_body,
2101
- metadata: { path: [] },
2102
- });
2103
- }
2104
-
2105
- /**
2106
- * @returns {any}
2107
- */
2108
- function create_null_return_statement() {
2109
- return {
2110
- type: 'ReturnStatement',
2111
- argument: { type: 'Literal', value: null, raw: 'null' },
2112
- };
2113
- }
2114
-
2115
- /**
2116
- * @param {AST.Expression} expression
2117
- * @param {any} [source_node]
2118
- * @returns {ESTreeJSX.JSXExpressionContainer}
2119
- */
2120
- function to_jsx_expression_container(expression, source_node = expression) {
2121
- // NOTE: JSXExpressionContainer nodes are intentionally created without loc.
2122
- // They are synthetic wrappers whose source positions do not correspond to
2123
- // entries in the generated source map, so adding loc causes Volar mapping failures.
2124
- return /** @type {any} */ ({
2125
- type: 'JSXExpressionContainer',
2126
- expression: /** @type {any} */ (expression),
2127
- metadata: { path: [] },
2128
- });
2129
- }
2130
-
2131
- /**
2132
- * Ripple's `{text expr}` always renders text, even for booleans and objects.
2133
- * React's normal `{expr}` child semantics would drop booleans and render
2134
- * elements as elements, so we coerce to a text value explicitly.
2135
- * @param {AST.Expression} expression
2136
- * @param {any} [source_node]
2137
- * @returns {AST.Expression}
2138
- */
2139
- function to_text_expression(expression, source_node = expression) {
2140
- return set_loc(
2141
- /** @type {AST.Expression} */ ({
2142
- type: 'ConditionalExpression',
2143
- test: {
2144
- type: 'BinaryExpression',
2145
- operator: '==',
2146
- left: clone_expression_node(expression),
2147
- right: {
2148
- type: 'Literal',
2149
- value: null,
2150
- raw: 'null',
2151
- metadata: { path: [] },
2152
- },
2153
- metadata: { path: [] },
2154
- },
2155
- consequent: {
2156
- type: 'Literal',
2157
- value: '',
2158
- raw: "''",
2159
- metadata: { path: [] },
2160
- },
2161
- alternate: {
2162
- type: 'BinaryExpression',
2163
- operator: '+',
2164
- left: clone_expression_node(expression),
2165
- right: {
2166
- type: 'Literal',
2167
- value: '',
2168
- raw: "''",
2169
- metadata: { path: [] },
2170
- },
2171
- metadata: { path: [] },
2172
- },
2173
- metadata: { path: [] },
2174
- }),
2175
- source_node,
2176
- );
2177
- }
2178
-
2179
- /**
2180
- * @param {any} attr
2181
- * @returns {ESTreeJSX.JSXAttribute | ESTreeJSX.JSXSpreadAttribute}
2182
- */
2183
- function to_jsx_attribute(attr) {
2184
- if (!attr) return attr;
2185
- if (attr.type === 'JSXAttribute' || attr.type === 'JSXSpreadAttribute') {
2186
- return attr;
2187
- }
2188
- if (attr.type === 'SpreadAttribute') {
2189
- return set_loc(
2190
- /** @type {any} */ ({
2191
- type: 'JSXSpreadAttribute',
2192
- argument: attr.argument,
2193
- }),
2194
- attr,
2195
- );
2196
- }
2197
- if (attr.type === 'RefAttribute') {
2198
- // RefAttribute uses `{ref expr}` syntax whose source positions don't map to the
2199
- // generated `ref={expr}` JSX attribute, so we intentionally omit loc.
2200
- return /** @type {any} */ ({
2201
- type: 'JSXAttribute',
2202
- name: { type: 'JSXIdentifier', name: 'ref', metadata: { path: [] } },
2203
- value: to_jsx_expression_container(attr.argument),
2204
- shorthand: false,
2205
- metadata: { path: [] },
2206
- });
2207
- }
2208
-
2209
- // Rewrite Ripple-style `class` → React's `className`.
2210
- let attr_name = attr.name;
2211
- if (attr_name && attr_name.type === 'Identifier' && attr_name.name === 'class') {
2212
- attr_name = set_loc(
2213
- /** @type {any} */ ({ type: 'Identifier', name: 'className', metadata: { path: [] } }),
2214
- attr.name,
2215
- );
2216
- }
2217
-
2218
- const name =
2219
- attr_name && attr_name.type === 'Identifier' ? identifier_to_jsx_name(attr_name) : attr_name;
2220
-
2221
- let value = attr.value;
2222
- if (value) {
2223
- if (value.type === 'Literal' && typeof value.value === 'string') {
2224
- // Keep string literal as attribute string.
2225
- } else if (value.type !== 'JSXExpressionContainer') {
2226
- value = to_jsx_expression_container(value);
2227
- }
2228
- }
2229
-
2230
- const jsx_attribute = /** @type {any} */ ({
2231
- type: 'JSXAttribute',
2232
- name,
2233
- value: value || null,
2234
- shorthand: false,
2235
- metadata: { path: [] },
2236
- });
2237
-
2238
- if (value_has_unmappable_jsx_loc(value)) {
2239
- /** @type {any} */ (jsx_attribute.metadata).has_unmappable_value = true;
2240
- return jsx_attribute;
2241
- }
2242
-
2243
- return set_loc(jsx_attribute, attr);
2244
- }
2245
-
2246
- /**
2247
- * @param {any} value
2248
- * @returns {boolean}
2249
- */
2250
- function value_has_unmappable_jsx_loc(value) {
2251
- return !!(
2252
- value?.type === 'JSXExpressionContainer' &&
2253
- (value.expression?.type === 'JSXElement' || value.expression?.type === 'JSXFragment') &&
2254
- !value.expression.loc
2255
- );
2256
- }
2257
-
2258
- /**
2259
- * @param {any} id
2260
- * @returns {boolean}
2261
- */
2262
- function is_dynamic_element_id(id) {
2263
- if (!id || typeof id !== 'object') {
2264
- return false;
2265
- }
2266
-
2267
- if (id.type === 'Identifier') {
2268
- return !!id.tracked;
2269
- }
2270
-
2271
- if (id.type === 'MemberExpression') {
2272
- return is_dynamic_element_id(id.object);
2273
- }
2274
-
2275
- return false;
2276
- }
2277
-
2278
- /**
2279
- * @param {any} node
2280
- * @param {TransformContext} transform_context
2281
- * @returns {ESTreeJSX.JSXExpressionContainer}
2282
- */
2283
- function dynamic_element_to_jsx_child(node, transform_context) {
2284
- const dynamic_id = set_loc(create_generated_identifier('DynamicElement'), node.id);
2285
- const alias_declaration = set_loc(
2286
- /** @type {any} */ ({
2287
- type: 'VariableDeclaration',
2288
- kind: 'const',
2289
- declarations: [
2290
- {
2291
- type: 'VariableDeclarator',
2292
- id: dynamic_id,
2293
- init: clone_expression_node(node.id),
2294
- metadata: { path: [] },
2295
- },
2296
- ],
2297
- metadata: { path: [] },
2298
- }),
2299
- node,
2300
- );
2301
- const jsx_element = create_dynamic_jsx_element(dynamic_id, node, transform_context);
2302
-
2303
- return to_jsx_expression_container(
2304
- /** @type {any} */ ({
2305
- type: 'CallExpression',
2306
- callee: {
2307
- type: 'ArrowFunctionExpression',
2308
- params: [],
2309
- body: /** @type {any} */ ({
2310
- type: 'BlockStatement',
2311
- body: [
2312
- alias_declaration,
2313
- {
2314
- type: 'ReturnStatement',
2315
- argument: {
2316
- type: 'ConditionalExpression',
2317
- test: clone_identifier(dynamic_id),
2318
- consequent: jsx_element,
2319
- alternate: create_null_literal(),
2320
- metadata: { path: [] },
2321
- },
2322
- metadata: { path: [] },
2323
- },
2324
- ],
2325
- metadata: { path: [] },
2326
- }),
2327
- async: false,
2328
- generator: false,
2329
- expression: false,
2330
- metadata: { path: [] },
2331
- },
2332
- arguments: [],
2333
- optional: false,
2334
- metadata: { path: [] },
2335
- }),
2336
- node,
2337
- );
2338
- }
2339
-
2340
- /**
2341
- * @param {AST.Identifier} dynamic_id
2342
- * @param {any} node
2343
- * @param {TransformContext} transform_context
2344
- * @returns {ESTreeJSX.JSXElement}
2345
- */
2346
- function create_dynamic_jsx_element(dynamic_id, node, transform_context) {
2347
- const attributes = (node.attributes || []).map(to_jsx_attribute);
2348
- const selfClosing = !!node.selfClosing;
2349
- const children = create_element_children(node.children || [], transform_context);
2350
- const name = identifier_to_jsx_name(clone_identifier(dynamic_id));
2351
-
2352
- return /** @type {any} */ ({
2353
- type: 'JSXElement',
2354
- openingElement: {
2355
- type: 'JSXOpeningElement',
2356
- name,
2357
- attributes,
2358
- selfClosing,
2359
- metadata: { path: [] },
2360
- },
2361
- closingElement: selfClosing
2362
- ? null
2363
- : {
2364
- type: 'JSXClosingElement',
2365
- name: clone_jsx_name(name),
2366
- metadata: { path: [] },
2367
- },
2368
- children,
2369
- metadata: { path: [] },
2370
- });
2371
- }
2372
-
2373
- /**
2374
- * @param {any} node
2375
- * @returns {any}
2376
- */
2377
- function clone_expression_node(node) {
2378
- if (!node || typeof node !== 'object') {
2379
- return node;
2380
- }
2381
-
2382
- if (Array.isArray(node)) {
2383
- return node.map(clone_expression_node);
2384
- }
2385
-
2386
- const clone = { ...node };
2387
- for (const key of Object.keys(clone)) {
2388
- if (key === 'metadata') {
2389
- clone.metadata = clone.metadata ? { ...clone.metadata } : { path: [] };
2390
- continue;
2391
- }
2392
- clone[key] = clone_expression_node(clone[key]);
2393
- }
2394
- return clone;
2395
- }
2396
-
2397
- /**
2398
- * @param {AST.Identifier | AST.MemberExpression | any} id
2399
- * @returns {ESTreeJSX.JSXIdentifier | ESTreeJSX.JSXMemberExpression}
2400
- */
2401
- function identifier_to_jsx_name(id) {
2402
- if (id.type === 'Identifier') {
2403
- return set_loc(
2404
- /** @type {any} */ ({
2405
- type: 'JSXIdentifier',
2406
- name: id.name,
2407
- metadata: { path: [], is_component: /^[A-Z]/.test(id.name) },
2408
- }),
2409
- id,
2410
- );
2411
- }
2412
- if (id.type === 'MemberExpression') {
2413
- return set_loc(
2414
- /** @type {any} */ ({
2415
- type: 'JSXMemberExpression',
2416
- object: /** @type {any} */ (identifier_to_jsx_name(id.object)),
2417
- property: /** @type {any} */ (identifier_to_jsx_name(id.property)),
2418
- }),
2419
- id,
2420
- );
2421
- }
2422
- return id;
2423
- }
2424
-
2425
- /**
2426
- * @param {any} name
2427
- * @param {any} [source_node]
2428
- * @returns {any}
2429
- */
2430
- function clone_jsx_name(name, source_node = name) {
2431
- if (name.type === 'JSXIdentifier') {
2432
- return set_loc(
2433
- {
2434
- type: 'JSXIdentifier',
2435
- name: name.name,
2436
- metadata: name.metadata || { path: [] },
2437
- },
2438
- source_node,
2439
- );
2440
- }
2441
- if (name.type === 'JSXMemberExpression') {
2442
- return set_loc(
2443
- {
2444
- type: 'JSXMemberExpression',
2445
- object: clone_jsx_name(name.object, source_node.object || name.object),
2446
- property: clone_jsx_name(name.property, source_node.property || name.property),
2447
- metadata: name.metadata || { path: [] },
2448
- },
2449
- source_node,
2450
- );
2451
- }
2452
- return name;
2453
- }
2454
-
2455
- /**
2456
- * @param {any[]} render_nodes
2457
- * @returns {any}
2458
- */
2459
- function build_return_expression(render_nodes) {
2460
- if (render_nodes.length === 0) return null;
2461
- if (render_nodes.length === 1) {
2462
- const only = render_nodes[0];
2463
- if (only.type === 'JSXExpressionContainer') {
2464
- return only.expression;
2465
- }
2466
- return only;
2467
- }
2468
- const first = render_nodes[0];
2469
- const last = render_nodes[render_nodes.length - 1];
2470
- return set_loc(
2471
- {
2472
- type: 'JSXFragment',
2473
- openingFragment: /** @type {any} */ ({
2474
- type: 'JSXOpeningFragment',
2475
- metadata: { path: [] },
2476
- }),
2477
- closingFragment: /** @type {any} */ ({
2478
- type: 'JSXClosingFragment',
2479
- metadata: { path: [] },
2480
- }),
2481
- children: render_nodes,
2482
- metadata: { path: [] },
2483
- },
2484
- first?.loc && last?.loc
2485
- ? {
2486
- start: first.start,
2487
- end: last.end,
2488
- loc: {
2489
- start: first.loc.start,
2490
- end: last.loc.end,
2491
- },
2492
- }
2493
- : undefined,
2494
- );
2495
- }
2496
-
2497
- /**
2498
- * @template T
2499
- * @param {T} node
2500
- * @param {any} source_node
2501
- * @returns {T}
2502
- */
2503
- function set_loc(node, source_node) {
2504
- /** @type {any} */ (node).metadata ??= { path: [] };
2505
- if (source_node?.loc) {
2506
- return /** @type {T} */ (setLocation(/** @type {any} */ (node), source_node, true));
2507
- }
2508
- return node;
2509
- }
2510
-
2511
- /**
2512
- * @param {any} left
2513
- * @param {any} index
2514
- * @returns {AST.Pattern[]}
2515
- */
2516
- function get_for_of_iteration_params(left, index) {
2517
- const params = [];
2518
- if (left?.type === 'VariableDeclaration') {
2519
- params.push(left.declarations[0]?.id);
2520
- } else {
2521
- params.push(left);
2522
- }
2523
- if (index) {
2524
- params.push(index);
2525
- }
2526
- return params;
2527
- }
2528
-
2529
- /**
2530
- * @param {string} name
2531
- * @returns {AST.Identifier}
2532
- */
2533
- function create_generated_identifier(name) {
2534
- return /** @type {any} */ ({
2535
- type: 'Identifier',
2536
- name,
2537
- metadata: { path: [] },
2538
- });
2539
- }
2540
-
2541
- /**
2542
- * @param {any} node
2543
- * @param {string} message
2544
- * @returns {Error & { pos: number, end: number }}
2545
- */
2546
- function create_compile_error(node, message) {
2547
- const error = /** @type {Error & { pos: number, end: number }} */ (new Error(message));
2548
- error.pos = node.start ?? 0;
2549
- error.end = node.end ?? error.pos + 1;
2550
- return error;
2551
- }
2552
-
2553
- /**
2554
- * @param {any} node
2555
- * @returns {any}
2556
- */
2557
- function tsx_compat_node_to_jsx_expression(node) {
2558
- if (node.kind !== 'react') {
2559
- throw create_compile_error(
2560
- node,
2561
- `React TSRX does not support <tsx:${node.kind}> blocks. Use <tsx> or <tsx:react>.`,
2562
- );
2563
- }
2564
-
2565
- return tsx_node_to_jsx_expression(node);
2566
- }
2567
-
2568
- /**
2569
- * @param {any} node
2570
- * @returns {any}
2571
- */
2572
- function tsx_node_to_jsx_expression(node) {
2573
- const children = (node.children || []).filter(
2574
- (/** @type {any} */ child) => child.type !== 'JSXText' || child.value.trim() !== '',
2575
- );
2576
-
2577
- if (children.length === 1 && children[0].type !== 'JSXText') {
2578
- return strip_locations(children[0]);
2579
- }
2580
-
2581
- return strip_locations(
2582
- /** @type {any} */ ({
2583
- type: 'JSXFragment',
2584
- openingFragment: { type: 'JSXOpeningFragment', metadata: { path: [] } },
2585
- closingFragment: { type: 'JSXClosingFragment', metadata: { path: [] } },
2586
- children,
2587
- metadata: { path: [] },
2588
- }),
2589
- );
2590
- }
2591
-
2592
- /**
2593
- * @param {any} node
2594
- * @returns {any}
2595
- */
2596
- function strip_locations(node) {
2597
- if (!node || typeof node !== 'object') {
2598
- return node;
2599
- }
2600
-
2601
- if (Array.isArray(node)) {
2602
- return node.map(strip_locations);
2603
- }
2604
-
2605
- delete node.loc;
2606
- delete node.start;
2607
- delete node.end;
2608
-
2609
- for (const key of Object.keys(node)) {
2610
- if (key === 'metadata') {
2611
- continue;
2612
- }
2613
- node[key] = strip_locations(node[key]);
2614
- }
2615
-
2616
- return node;
2617
- }
2618
-
2619
- /**
2620
- * @param {any[]} consequent
2621
- * @returns {any[]}
2622
- */
2623
- function flatten_switch_consequent(consequent) {
2624
- const result = [];
2625
- for (const node of consequent) {
2626
- if (node.type === 'BlockStatement') {
2627
- result.push(...node.body);
2628
- } else {
2629
- result.push(node);
2630
- }
2631
- }
2632
- return result;
2633
- }
1
+ /** @import { JsxPlatform } from '@tsrx/core/types' */
2
+
3
+ import { createJsxTransform } from '@tsrx/core';
4
+
5
+ /**
6
+ * React platform descriptor consumed by `createJsxTransform`. Each field
7
+ * configures one React-specific decision the shared transformer would
8
+ * otherwise have to branch on (import sources, `class`→`className` rewrite,
9
+ * accepted `<tsx:kind>` values, `use server` validation, error message
10
+ * prefix).
11
+ *
12
+ * @type {JsxPlatform}
13
+ */
14
+ const react_platform = {
15
+ name: 'React',
16
+ imports: {
17
+ suspense: 'react',
18
+ errorBoundary: '@tsrx/react/error-boundary',
19
+ },
20
+ jsx: {
21
+ rewriteClassAttr: true,
22
+ acceptedTsxKinds: ['react'],
23
+ },
24
+ validation: {
25
+ requireUseServerForAwait: false,
26
+ },
27
+ };
28
+
29
+ export const transform = createJsxTransform(react_platform);