diff --git a/.changeset/swift-fans-stare.md b/.changeset/swift-fans-stare.md new file mode 100644 index 0000000000..3477372663 --- /dev/null +++ b/.changeset/swift-fans-stare.md @@ -0,0 +1,5 @@ +--- +"svelte": patch +--- + +chore: improve $state static reference warning heuristics diff --git a/packages/svelte/src/compiler/phases/2-analyze/index.js b/packages/svelte/src/compiler/phases/2-analyze/index.js index 0c207f9508..471b432b05 100644 --- a/packages/svelte/src/compiler/phases/2-analyze/index.js +++ b/packages/svelte/src/compiler/phases/2-analyze/index.js @@ -21,6 +21,7 @@ import check_graph_for_cycles from './utils/check_graph_for_cycles.js'; import { regex_starts_with_newline } from '../patterns.js'; import { create_attribute, is_element_node } from '../nodes.js'; import { DelegatedEvents } from '../../../constants.js'; +import { should_proxy_or_freeze } from '../3-transform/client/utils.js'; /** * @param {import('#compiler').Script | null} script @@ -918,7 +919,14 @@ const common_visitors = { if ( node !== binding.node && - (binding.kind === 'state' || + // If we have $state that can be proxied or frozen and isn't re-assigned, then that means + // it's likely not using a primitive value and thus this warning isn't that helpful. + ((binding.kind === 'state' && + (binding.reassigned || + (binding.initial?.type === 'CallExpression' && + binding.initial.arguments.length === 1 && + binding.initial.arguments[0].type !== 'SpreadElement' && + !should_proxy_or_freeze(binding.initial.arguments[0], context.state.scope)))) || binding.kind === 'frozen_state' || binding.kind === 'derived') && context.state.function_depth === binding.scope.function_depth diff --git a/packages/svelte/tests/validator/samples/static-state-reference/input.svelte b/packages/svelte/tests/validator/samples/static-state-reference/input.svelte index 0ecf5dc77d..8862926857 100644 --- a/packages/svelte/tests/validator/samples/static-state-reference/input.svelte +++ b/packages/svelte/tests/validator/samples/static-state-reference/input.svelte @@ -1,7 +1,9 @@ diff --git a/packages/svelte/tests/validator/samples/static-state-reference/warnings.json b/packages/svelte/tests/validator/samples/static-state-reference/warnings.json index 3b63c26e75..2961bef5f7 100644 --- a/packages/svelte/tests/validator/samples/static-state-reference/warnings.json +++ b/packages/svelte/tests/validator/samples/static-state-reference/warnings.json @@ -4,11 +4,11 @@ "message": "State referenced in its own scope will never update. Did you mean to reference it inside a closure?", "start": { "column": 13, - "line": 5 + "line": 7 }, "end": { "column": 18, - "line": 5 + "line": 7 } }, { @@ -16,11 +16,11 @@ "message": "State referenced in its own scope will never update. Did you mean to reference it inside a closure?", "start": { "column": 13, - "line": 6 + "line": 8 }, "end": { "column": 20, - "line": 6 + "line": 8 } } ]