|
| 1 | +import { createRule } from '../utils/index.js'; |
| 2 | +import { getSvelteContext } from '../utils/svelte-context.js'; |
| 3 | +import { VERSION as SVELTE_VERSION } from 'svelte/compiler'; |
| 4 | +import semver from 'semver'; |
| 5 | + |
| 6 | +const shouldRun = semver.satisfies(SVELTE_VERSION, '>=5.56.0'); |
| 7 | + |
| 8 | +export default createRule('no-at-const-tags', { |
| 9 | + meta: { |
| 10 | + docs: { |
| 11 | + description: 'disallow the use of `{@const}` in favor of `{const ...}` declaration tags', |
| 12 | + category: 'Best Practices', |
| 13 | + recommended: false |
| 14 | + }, |
| 15 | + fixable: 'code', |
| 16 | + schema: [], |
| 17 | + messages: { |
| 18 | + unexpected: 'Use `{const ...}` declaration tag instead of legacy `{@const ...}`.' |
| 19 | + }, |
| 20 | + type: 'suggestion', |
| 21 | + conditions: [ |
| 22 | + { |
| 23 | + svelteVersions: ['5'] |
| 24 | + } |
| 25 | + ] |
| 26 | + }, |
| 27 | + create(context) { |
| 28 | + if (!shouldRun) { |
| 29 | + return {}; |
| 30 | + } |
| 31 | + const sourceCode = context.sourceCode; |
| 32 | + const runes = getSvelteContext(context)?.runes; |
| 33 | + // Only report and fix in runes mode, since preserving reactivity requires |
| 34 | + // `$derived(...)`, which is unavailable outside runes mode. |
| 35 | + if (runes !== true) { |
| 36 | + return {}; |
| 37 | + } |
| 38 | + return { |
| 39 | + SvelteConstTag(node) { |
| 40 | + context.report({ |
| 41 | + node, |
| 42 | + messageId: 'unexpected', |
| 43 | + *fix(fixer) { |
| 44 | + const text = sourceCode.getText(node); |
| 45 | + const match = /^\{(\s*)@const\b/u.exec(text); |
| 46 | + if (!match) { |
| 47 | + return; |
| 48 | + } |
| 49 | + const atOffset = node.range[0] + 1 + match[1].length; |
| 50 | + yield fixer.removeRange([atOffset, atOffset + 1]); |
| 51 | + |
| 52 | + const init = node.declarations[0].init; |
| 53 | + if (init == null) { |
| 54 | + return; |
| 55 | + } |
| 56 | + // Preserve the reactivity of legacy `{@const}` by wrapping the |
| 57 | + // initializer in `$derived(...)`. Skip when already wrapped. |
| 58 | + if ( |
| 59 | + init.type === 'CallExpression' && |
| 60 | + init.callee.type === 'Identifier' && |
| 61 | + init.callee.name === '$derived' |
| 62 | + ) { |
| 63 | + return; |
| 64 | + } |
| 65 | + yield fixer.insertTextBefore(init, '$derived('); |
| 66 | + yield fixer.insertTextAfter(init, ')'); |
| 67 | + } |
| 68 | + }); |
| 69 | + } |
| 70 | + }; |
| 71 | + } |
| 72 | +}); |
0 commit comments