fix: error when exporting reassigned state from module context (#10728)

fixes #10380
pull/10730/head
Simon H 9 months ago committed by GitHub
parent ae4af6841a
commit b1267b03b6
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -0,0 +1,5 @@
---
"svelte": patch
---
fix: error when exporting reassigned state from module context

@ -997,11 +997,29 @@ export const validation_runes = merge(validation, a11y_validators, {
if (node.label.name !== '$' || path.at(-1)?.type !== 'Program') return; if (node.label.name !== '$' || path.at(-1)?.type !== 'Program') return;
error(node, 'invalid-legacy-reactive-statement'); error(node, 'invalid-legacy-reactive-statement');
}, },
ExportNamedDeclaration(node, { state }) { ExportNamedDeclaration(node, { state, next }) {
if (node.declaration?.type !== 'VariableDeclaration') return; if (state.ast_type === 'module') {
if (node.declaration.kind !== 'let') return; if (node.declaration?.type !== 'VariableDeclaration') return;
if (state.analysis.instance.scope !== state.scope) return;
error(node, 'invalid-legacy-export'); // visit children, so bindings are correctly initialised
next();
for (const declarator of node.declaration.declarations) {
for (const id of extract_identifiers(declarator.id)) {
validate_export(node, state.scope, id.name);
}
}
} else {
if (node.declaration?.type !== 'VariableDeclaration') return;
if (node.declaration.kind !== 'let') return;
if (state.analysis.instance.scope !== state.scope) return;
error(node, 'invalid-legacy-export');
}
},
ExportSpecifier(node, { state }) {
if (state.ast_type === 'module') {
validate_export(node, state.scope, node.local.name);
}
}, },
CallExpression(node, { state, path }) { CallExpression(node, { state, path }) {
validate_call_expression(node, state.scope, path); validate_call_expression(node, state.scope, path);

@ -0,0 +1,10 @@
import { test } from '../../test';
export default test({
error: {
code: 'invalid-state-export',
message:
"Cannot export state from a module if it is reassigned. Either export a function returning the state value or only mutate the state value's properties",
position: [76, 114]
}
});

@ -0,0 +1,15 @@
<script context="module">
export const object = $state({
ok: true
});
export let primitive = $state('nope');
export function update_object() {
object.ok = !object.ok;
}
export function update_primitive() {
primitive = 'yep';
}
</script>
Loading…
Cancel
Save