@tsrx/vue 0.4.3 → 0.4.5

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.
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "description": "Vue compiler built on @tsrx/core",
4
4
  "license": "MIT",
5
5
  "author": "Dominic Gannaway",
6
- "version": "0.4.3",
6
+ "version": "0.4.5",
7
7
  "type": "module",
8
8
  "publishConfig": {
9
9
  "access": "public"
@@ -39,11 +39,11 @@
39
39
  }
40
40
  },
41
41
  "dependencies": {
42
- "esrap": "^2.4.0",
42
+ "esrap": "^2.4.2",
43
43
  "is-reference": "^3.0.3",
44
44
  "zimmerframe": "^1.1.2",
45
- "@tsrx/core": "0.6.3",
46
- "@tsrx/vue-runtime": "0.2.2"
45
+ "@tsrx/core": "0.6.5",
46
+ "@tsrx/vue-runtime": "0.2.3"
47
47
  },
48
48
  "peerDependencies": {
49
49
  "vue": ">=3.6.0-0",
@@ -19,27 +19,51 @@ const AST_METADATA_KEYS = new Set(['loc', 'start', 'end', 'metadata']);
19
19
  * @returns {AST.YieldExpression[]}
20
20
  */
21
21
  export function find_deferred_template_yields(program) {
22
- /** @type {AST.YieldExpression[]} */
22
+ return /** @type {AST.YieldExpression[]} */ (find_deferred(program, 'YieldExpression'));
23
+ }
24
+
25
+ /**
26
+ * The `await`s that vue-jsx-vapor moves out of their async function, for the
27
+ * same reason: an `await` anywhere in an element or fragment ends up in a
28
+ * function that isn't async. `packages/vite-plugin-vue/tests/template-yield-downstream.test.js`
29
+ * checks these too.
30
+ *
31
+ * @param {AST.Program} program
32
+ * @returns {AST.AwaitExpression[]}
33
+ */
34
+ export function find_deferred_template_awaits(program) {
35
+ return /** @type {AST.AwaitExpression[]} */ (find_deferred(program, 'AwaitExpression'));
36
+ }
37
+
38
+ /**
39
+ * @param {AST.Program} program
40
+ * @param {'YieldExpression' | 'AwaitExpression'} type
41
+ * @returns {AST.Node[]}
42
+ */
43
+ function find_deferred(program, type) {
44
+ /** @type {AST.Node[]} */
23
45
  const found = [];
24
46
 
25
47
  /**
26
48
  * @param {AST.Node} node
27
- * @param {boolean} in_generator whether the nearest function is a generator
49
+ * @param {boolean} in_owner whether the nearest function is a generator, for
50
+ * a `yield`, or async, for an `await`
28
51
  * @param {boolean} in_template whether the node is inside an element or fragment
29
52
  */
30
- const visit = (node, in_generator, in_template) => {
53
+ const visit = (node, in_owner, in_template) => {
31
54
  if (isFunctionNode(node)) {
32
- in_generator = !!node.generator;
55
+ in_owner = type === 'YieldExpression' ? !!node.generator : !!node.async;
33
56
  in_template = false;
34
- } else if (node.type === 'YieldExpression' && in_generator && in_template) {
57
+ } else if (node.type === type && in_owner && in_template) {
35
58
  found.push(node);
36
59
  } else if (node.type === 'JSXElement' || node.type === 'JSXFragment') {
37
60
  in_template = true;
38
61
  }
39
- for_each_child(node, (child) => visit(child, in_generator, in_template));
62
+ for_each_child(node, (child) => visit(child, in_owner, in_template));
40
63
  };
41
64
 
42
- visit(program, false, false);
65
+ // A module's top level can await, but not yield.
66
+ visit(program, type === 'AwaitExpression', false);
43
67
  return found;
44
68
  }
45
69
 
package/src/transform.js CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  import { walk } from 'zimmerframe';
6
6
  import is_reference from 'is-reference';
7
- import { find_deferred_template_yields } from './template-yield.js';
7
+ import { find_deferred_template_awaits, find_deferred_template_yields } from './template-yield.js';
8
8
  import {
9
9
  builders as b,
10
10
  addJsxSetupDeclaration,
@@ -16,12 +16,14 @@ import {
16
16
  destructure_for_of_item,
17
17
  ERROR_BOUNDARY_INTERNAL_NAME,
18
18
  error,
19
+ findFirstTopLevelAwait,
19
20
  FRAGMENT_INTERNAL_NAME,
20
21
  forOfPatternReadsIndex as for_of_pattern_reads_index,
21
22
  has_location,
22
23
  IDENTIFIER_OBFUSCATION_PREFIX,
23
24
  insertAfterDirectives,
24
25
  is_component_like_element,
26
+ isFunctionNode,
25
27
  JOIN_SCOPE_CLASS_INTERNAL_NAME,
26
28
  MAP_ITERABLE_ASYNC_INTERNAL_NAME,
27
29
  MAP_ITERABLE_INTERNAL_NAME,
@@ -53,6 +55,15 @@ const vapor_bindings_counts = new WeakMap();
53
55
  */
54
56
  const VAPOR_FOR_INTERNAL_NAME = '__VaporFor';
55
57
 
58
+ /**
59
+ * Local name for the runtime helper that hands `VaporFor` the source's items.
60
+ * It has the reserved prefix, so no authored name, such as an outer loop's item
61
+ * that a keyed row reads through `.value`, can take it.
62
+ */
63
+ const FOR_ITEMS_INTERNAL_NAME = IDENTIFIER_OBFUSCATION_PREFIX + 'for_items';
64
+ /** The `computed` that walks the source of a `VaporFor` loop with `@empty`. */
65
+ const VAPOR_ITEMS_NAME = IDENTIFIER_OBFUSCATION_PREFIX + 'vapor_items';
66
+
56
67
  const DEFINE_VAPOR_COMPONENT = 'defineVaporComponent';
57
68
 
58
69
  /**
@@ -113,6 +124,7 @@ const vue_platform = {
113
124
  needs_define_vapor_component: false,
114
125
  needs_vapor_for: false,
115
126
  needs_use_slots: false,
127
+ needs_pending_body: false,
116
128
  }),
117
129
  wrapHelperComponent(helper_fn, helper_id, ctx, source_node) {
118
130
  ctx.needs_define_vapor_component = true;
@@ -133,8 +145,8 @@ const vue_platform = {
133
145
  }
134
146
  return attrs.map(mark_type_only_host_ref_attribute);
135
147
  },
136
- renderForOf: (node, loop_params, body_statements, ctx) =>
137
- render_for_of_as_vapor_for(node, loop_params, body_statements, ctx),
148
+ renderForOf: (node, loop_params, body_statements, ctx, get_empty_statements) =>
149
+ render_for_of_as_vapor_for(node, loop_params, body_statements, ctx, get_empty_statements),
138
150
  createPendingBoundary(try_content, fallback_content, ctx) {
139
151
  return create_vapor_pending_boundary(try_content, fallback_content, ctx);
140
152
  },
@@ -179,6 +191,7 @@ const vue_platform = {
179
191
  return rewrite_host_text_children(node, walked_children, raw_children, attributes);
180
192
  },
181
193
  findDeferredTemplateYields: find_deferred_template_yields,
194
+ findDeferredTemplateAwaits: find_deferred_template_awaits,
182
195
  validateComponentAwait(await_expression, _component, ctx) {
183
196
  error(
184
197
  TSRX_ERRORS.TARGET_COMPONENT_AWAIT_UNSUPPORTED(ctx.platform.name),
@@ -197,6 +210,9 @@ const vue_platform = {
197
210
 
198
211
  export const transform = createJsxTransform(vue_platform);
199
212
 
213
+ /** Local name for the `TsrxPendingBody` that renders a `@pending` body. */
214
+ const PENDING_BODY_INTERNAL_NAME = '__TsrxPendingBody';
215
+
200
216
  /**
201
217
  * @param {ESTreeJSX.JSXRenderNode} try_content
202
218
  * @param {ESTreeJSX.JSXRenderNode} fallback_content
@@ -225,7 +241,15 @@ function create_vapor_pending_boundary_from_default_slot(default_slot, fallback_
225
241
  if (!ctx.typeOnly) slots_properties.unshift(b.init('_', b.literal(1)));
226
242
 
227
243
  if (fallback_expression.type !== 'Literal' || fallback_expression.value !== null) {
228
- slots_properties.push(b.init('fallback', b.arrow([], fallback_expression)));
244
+ slots_properties.push(
245
+ b.init(
246
+ 'fallback',
247
+ b.arrow(
248
+ [],
249
+ ctx.typeOnly ? fallback_expression : create_pending_body(fallback_expression, ctx),
250
+ ),
251
+ ),
252
+ );
229
253
  }
230
254
 
231
255
  const slots = b.object(slots_properties);
@@ -277,6 +301,33 @@ function create_error_boundary_slot(content, fallback_fn, source_try) {
277
301
  );
278
302
  }
279
303
 
304
+ /**
305
+ * Render a `@pending` body through `TsrxPendingBody`. `Suspense` then creates
306
+ * it only while it shows its fallback, and a throw in it reaches the nearest
307
+ * `@catch` instead of ending the mount.
308
+ *
309
+ * @param {AST.Expression} fallback_expression
310
+ * @param {TransformContext} ctx
311
+ * @returns {AST.TSRXJSXElement}
312
+ */
313
+ function create_pending_body(fallback_expression, ctx) {
314
+ ctx.needs_pending_body = true;
315
+ return b.jsx_element_fresh(
316
+ b.jsx_opening_element(
317
+ b.jsx_id(PENDING_BODY_INTERNAL_NAME),
318
+ [
319
+ b.jsx_attribute(
320
+ b.jsx_id('content'),
321
+ to_jsx_expression_container(b.arrow([], fallback_expression)),
322
+ ),
323
+ ],
324
+ true,
325
+ ),
326
+ null,
327
+ [],
328
+ );
329
+ }
330
+
280
331
  /**
281
332
  * @param {AST.Pattern[]} patterns
282
333
  * @returns {Set<string>}
@@ -1782,13 +1833,16 @@ function create_define_vapor_component_call(fn_expression, generated_helpers, ge
1782
1833
  * @param {AST.Pattern[]} loop_params
1783
1834
  * @param {AST.Statement[]} body_statements
1784
1835
  * @param {TransformContext} transform_context
1836
+ * @param {(() => AST.Statement[]) | null} get_empty_statements
1785
1837
  * @returns {ESTreeJSX.JSXExpressionContainer | null}
1786
1838
  */
1787
- function render_for_of_as_vapor_for(node, loop_params, body_statements, transform_context) {
1788
- if (node.empty) {
1789
- return null;
1790
- }
1791
-
1839
+ function render_for_of_as_vapor_for(
1840
+ node,
1841
+ loop_params,
1842
+ body_statements,
1843
+ transform_context,
1844
+ get_empty_statements,
1845
+ ) {
1792
1846
  if (body_statements.length !== 1) {
1793
1847
  return null;
1794
1848
  }
@@ -1798,38 +1852,62 @@ function render_for_of_as_vapor_for(node, loop_params, body_statements, transfor
1798
1852
  return null;
1799
1853
  }
1800
1854
 
1801
- // A default in the head's pattern that reads the index can't be read in
1802
- // the parameters, where the index comes second. The shared lowering
1803
- // destructures the item in the callback for a body that can skip a row.
1804
- const pattern_reads_index = for_of_pattern_reads_index(loop_params[0], node.index);
1805
- if (pattern_reads_index && expression_can_skip_rendering(statement.argument)) {
1806
- return null;
1807
- }
1808
-
1809
1855
  const rendered = statement.argument;
1810
- if (expression_can_skip_rendering(rendered)) {
1811
- return render_for_of_as_map_iterable(node, loop_params, rendered, transform_context);
1812
- }
1813
-
1814
1856
  const key_expression = node.key
1815
1857
  ? clone_ast_node(node.key)
1816
1858
  : (find_jsx_key_expression(rendered) ?? (node.index ? clone_ast_node(node.index) : null));
1859
+ const pattern_reads_index = for_of_pattern_reads_index(loop_params[0], node.index);
1817
1860
 
1861
+ // A keyed loop renders through `VaporFor` even when its body can skip a row
1862
+ // or it has `@empty`, so its rows move with their keys (#178). The shared
1863
+ // lowering keeps such a loop without a key; one that awaits or yields, which
1864
+ // it suspends the template's closures for; one whose head destructures in a
1865
+ // way that runs code, which `getKey` and the row would each run; and one
1866
+ // whose row renders through an IIFE (`@switch`), which a row slot runs once
1867
+ // and which can return `null`.
1868
+ if (
1869
+ (node.empty || expression_can_skip_rendering(rendered)) &&
1870
+ (!key_expression ||
1871
+ suspends(node) ||
1872
+ destructuring_runs_code(loop_params[0]) ||
1873
+ !is_vapor_for_row(rendered))
1874
+ ) {
1875
+ // A default in the head's pattern that reads the index can't be read in
1876
+ // the parameters, where the index comes second. The shared lowering
1877
+ // destructures the item in the callback.
1878
+ if (node.empty || pattern_reads_index) {
1879
+ return null;
1880
+ }
1881
+ return render_for_of_as_map_iterable(node, loop_params, rendered, transform_context);
1882
+ }
1883
+
1884
+ const row = to_vapor_for_row(rendered);
1818
1885
  const slot = key_expression
1819
- ? create_keyed_vapor_for_slot(loop_params, rendered, transform_context)
1820
- : { params: loop_params, body: rendered, expression: true };
1886
+ ? create_keyed_vapor_for_slot(loop_params, row, transform_context)
1887
+ : { params: loop_params, body: row, expression: true };
1821
1888
  if (!slot) {
1822
1889
  return null;
1823
1890
  }
1824
1891
 
1825
1892
  transform_context.needs_vapor_for = true;
1893
+ transform_context.needs_for_items = true;
1826
1894
 
1827
1895
  if (key_expression) {
1828
1896
  strip_top_level_jsx_keys(slot.rendered ?? slot.body);
1829
1897
  }
1830
1898
 
1899
+ // `VaporFor` reads an array by index and walks other iterables its own way,
1900
+ // so it gets the source's items as `for...of` walks them (#1147). With
1901
+ // `@empty`, one `computed` walks the source for both the check and the rows.
1902
+ const source_items = b.call(FOR_ITEMS_INTERNAL_NAME, clone_ast_node(node.right));
1903
+ const items_ref = get_empty_statements ? create_generated_identifier(VAPOR_ITEMS_NAME) : null;
1831
1904
  const attributes = [
1832
- b.jsx_attribute(b.jsx_id('in'), to_jsx_expression_container(clone_ast_node(node.right))),
1905
+ b.jsx_attribute(
1906
+ b.jsx_id('in'),
1907
+ to_jsx_expression_container(
1908
+ items_ref ? create_value_member_expression(items_ref) : source_items,
1909
+ ),
1910
+ ),
1833
1911
  ];
1834
1912
 
1835
1913
  if (key_expression) {
@@ -1848,15 +1926,184 @@ function render_for_of_as_vapor_for(node, loop_params, body_statements, transfor
1848
1926
  attributes.push(b.jsx_attribute(b.jsx_id('getKey'), to_jsx_expression_container(get_key)));
1849
1927
  }
1850
1928
 
1929
+ const vapor_for = b.jsx_element_fresh(
1930
+ b.jsx_opening_element(b.jsx_id(VAPOR_FOR_INTERNAL_NAME), attributes),
1931
+ b.jsx_closing_element(b.jsx_id(VAPOR_FOR_INTERNAL_NAME)),
1932
+ [to_jsx_expression_container(create_loop_callback(slot.params, slot.body, slot.expression))],
1933
+ );
1934
+
1935
+ if (!items_ref || !get_empty_statements) {
1936
+ return to_jsx_expression_container(vapor_for);
1937
+ }
1938
+
1939
+ transform_context.needs_vapor_computed = true;
1940
+ const empty_statements = get_empty_statements();
1941
+ const empty_return = empty_statements.length === 1 ? empty_statements[0] : null;
1942
+ const empty =
1943
+ empty_return?.type === 'ReturnStatement' && empty_return.argument
1944
+ ? to_vapor_branch(empty_return.argument)
1945
+ : b.call(
1946
+ b.arrow(
1947
+ [],
1948
+ b.block(empty_statements),
1949
+ false,
1950
+ undefined,
1951
+ has_location(node.empty) ? node.empty : undefined,
1952
+ ),
1953
+ );
1954
+
1955
+ // The choice sits in a fragment, so vue-jsx-vapor makes it a `createIf`:
1956
+ // `VaporFor` and its rows stay mounted while the source has items.
1851
1957
  return to_jsx_expression_container(
1852
- b.jsx_element_fresh(
1853
- b.jsx_opening_element(b.jsx_id(VAPOR_FOR_INTERNAL_NAME), attributes),
1854
- b.jsx_closing_element(b.jsx_id(VAPOR_FOR_INTERNAL_NAME)),
1855
- [to_jsx_expression_container(create_loop_callback(slot.params, slot.body, slot.expression))],
1958
+ b.call(
1959
+ b.arrow(
1960
+ [],
1961
+ b.block([
1962
+ b.const(items_ref, b.call(VUE_COMPUTED_INTERNAL_NAME, b.arrow([], source_items))),
1963
+ b.return(
1964
+ b.jsx_fragment([
1965
+ to_jsx_expression_container(
1966
+ b.conditional(
1967
+ b.binary(
1968
+ '===',
1969
+ b.member(
1970
+ create_value_member_expression(items_ref),
1971
+ create_generated_identifier('length'),
1972
+ ),
1973
+ b.literal(0),
1974
+ ),
1975
+ empty,
1976
+ vapor_for,
1977
+ ),
1978
+ ),
1979
+ ]),
1980
+ ),
1981
+ ]),
1982
+ ),
1856
1983
  ),
1857
1984
  );
1858
1985
  }
1859
1986
 
1987
+ /**
1988
+ * Whether `node` awaits or yields outside a nested function.
1989
+ *
1990
+ * @param {AST.Node} node
1991
+ * @returns {boolean}
1992
+ */
1993
+ function suspends(node) {
1994
+ return !!findFirstTopLevelAwait(node, false) || yields(node);
1995
+ }
1996
+
1997
+ /**
1998
+ * Whether destructuring `pattern` can run code or read the value more than
1999
+ * once in a way that shows: an array pattern walks an iterator, and a default
2000
+ * or a computed key evaluates an expression.
2001
+ *
2002
+ * @param {AST.Pattern | AST.Property['value'] | null | undefined} pattern
2003
+ * @returns {boolean}
2004
+ */
2005
+ function destructuring_runs_code(pattern) {
2006
+ switch (pattern?.type) {
2007
+ case 'ArrayPattern':
2008
+ case 'AssignmentPattern':
2009
+ return true;
2010
+ case 'ObjectPattern':
2011
+ return pattern.properties.some((property) =>
2012
+ property.type === 'RestElement'
2013
+ ? destructuring_runs_code(property.argument)
2014
+ : property.computed || destructuring_runs_code(property.value),
2015
+ );
2016
+ case 'RestElement':
2017
+ return destructuring_runs_code(pattern.argument);
2018
+ default:
2019
+ return false;
2020
+ }
2021
+ }
2022
+
2023
+ /**
2024
+ * Whether a row can render through `VaporFor`: an element or fragment, or a
2025
+ * choice of them that `to_vapor_for_row` puts in a fragment.
2026
+ *
2027
+ * @param {AST.Expression} node
2028
+ * @returns {boolean}
2029
+ */
2030
+ function is_vapor_for_row(node) {
2031
+ return (
2032
+ node.type === 'JSXElement' ||
2033
+ node.type === 'JSXFragment' ||
2034
+ node.type === 'ConditionalExpression' ||
2035
+ (node.type === 'LogicalExpression' && node.operator === '&&') ||
2036
+ (node.type === 'Literal' && node.value === null)
2037
+ );
2038
+ }
2039
+
2040
+ /**
2041
+ * @param {unknown} node
2042
+ * @returns {boolean}
2043
+ */
2044
+ function yields(node) {
2045
+ if (Array.isArray(node)) return node.some(yields);
2046
+ if (!node || typeof node !== 'object' || isFunctionNode(/** @type {AST.Node} */ (node))) {
2047
+ return false;
2048
+ }
2049
+ if (/** @type {AST.Node} */ (node).type === 'YieldExpression') return true;
2050
+ return Object.entries(node).some(
2051
+ ([key, value]) => key !== 'loc' && key !== 'metadata' && yields(value),
2052
+ );
2053
+ }
2054
+
2055
+ /**
2056
+ * The row a `VaporFor` slot returns. The slot runs once per row, so a ternary
2057
+ * it returns would keep the branch it picked first: a row that picks a branch,
2058
+ * or can skip itself, is a fragment around the choice, which vue-jsx-vapor
2059
+ * makes a `createIf` that follows its condition.
2060
+ *
2061
+ * @param {AST.Expression} node
2062
+ * @returns {AST.Expression}
2063
+ */
2064
+ function to_vapor_for_row(node) {
2065
+ if (
2066
+ node.type === 'ConditionalExpression' ||
2067
+ (node.type === 'LogicalExpression' && node.operator === '&&')
2068
+ ) {
2069
+ return /** @type {AST.Expression} */ (
2070
+ /** @type {unknown} */ (b.jsx_fragment([to_jsx_expression_container(to_vapor_branch(node))]))
2071
+ );
2072
+ }
2073
+ return to_vapor_branch(node);
2074
+ }
2075
+
2076
+ /**
2077
+ * A branch of a `VaporFor` row or of its `@empty`, where Vapor can't mount
2078
+ * `null`: a skipped branch renders an empty fragment.
2079
+ *
2080
+ * @param {AST.Expression} node
2081
+ * @returns {AST.Expression}
2082
+ */
2083
+ function to_vapor_branch(node) {
2084
+ if (node.type === 'Literal' && node.value === null) {
2085
+ return /** @type {AST.Expression} */ (/** @type {unknown} */ (b.jsx_fragment()));
2086
+ }
2087
+
2088
+ if (node.type === 'ConditionalExpression') {
2089
+ return {
2090
+ ...node,
2091
+ consequent: to_vapor_branch(node.consequent),
2092
+ alternate: to_vapor_branch(node.alternate),
2093
+ };
2094
+ }
2095
+
2096
+ if (node.type === 'LogicalExpression' && node.operator === '&&') {
2097
+ return b.conditional(
2098
+ node.left,
2099
+ to_vapor_branch(node.right),
2100
+ /** @type {AST.Expression} */ (/** @type {unknown} */ (b.jsx_fragment())),
2101
+ );
2102
+ }
2103
+
2104
+ return node;
2105
+ }
2106
+
1860
2107
  /**
1861
2108
  * @param {AST.ForOfStatement} node
1862
2109
  * @param {AST.Pattern[]} loop_params
@@ -2943,6 +3190,9 @@ function inject_vue_imports(program, transform_context) {
2943
3190
 
2944
3191
  const iterable_source = transform_context.platform.imports.forOfIterableHelper;
2945
3192
  if (iterable_source) {
3193
+ if (transform_context.needs_for_items) {
3194
+ ensure_named_import(program, iterable_source, 'for_items', FOR_ITEMS_INTERNAL_NAME);
3195
+ }
2946
3196
  if (transform_context.needs_for_of_iterable) {
2947
3197
  ensure_named_import(program, iterable_source, 'map_iterable', MAP_ITERABLE_INTERNAL_NAME);
2948
3198
  }
@@ -3000,6 +3250,15 @@ function inject_vue_imports(program, transform_context) {
3000
3250
  );
3001
3251
  }
3002
3252
 
3253
+ if (transform_context.needs_pending_body) {
3254
+ ensure_named_import(
3255
+ program,
3256
+ transform_context.platform.imports.errorBoundary,
3257
+ 'TsrxPendingBody',
3258
+ PENDING_BODY_INTERNAL_NAME,
3259
+ );
3260
+ }
3261
+
3003
3262
  if (transform_context.needs_merge_refs && merge_refs_source) {
3004
3263
  ensure_named_import(program, merge_refs_source, 'mergeRefs', MERGE_REFS_INTERNAL_NAME);
3005
3264
  }