-
-
Notifications
You must be signed in to change notification settings - Fork 59
feat: add app-state migration #354
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 1 commit
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
5272dec
feat: add page-state migration
dummdidumm e892d77
handle aliases
dummdidumm eb67567
Merge branch 'main' into page-state-migration
manuel3108 5d6f4fe
add migration to docs
manuel3108 1a51241
update link
dummdidumm 10f1e0b
lint
dummdidumm 4497308
rename to app-state
Rich-Harris 4d14334
rename
Rich-Harris 5c51293
remove .current from navigating references
Rich-Harris 4d2e5dd
hopefully this will get it to shut up
Rich-Harris 25a948b
add migration task
Rich-Harris File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
--- | ||
'svelte-migrate': minor | ||
--- | ||
|
||
feat: add page-state migration |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,119 @@ | ||
import colors from 'kleur'; | ||
import fs from 'node:fs'; | ||
import process from 'node:process'; | ||
import prompts from 'prompts'; | ||
import semver from 'semver'; | ||
import glob from 'tiny-glob/sync.js'; | ||
import { bail, check_git, update_svelte_file } from '../../utils.js'; | ||
import { transform_svelte_code, update_pkg_json } from './migrate.js'; | ||
|
||
export async function migrate() { | ||
if (!fs.existsSync('package.json')) { | ||
bail('Please re-run this script in a directory with a package.json'); | ||
} | ||
|
||
const pkg = JSON.parse(fs.readFileSync('package.json', 'utf8')); | ||
|
||
const svelte_dep = pkg.devDependencies?.svelte ?? pkg.dependencies?.svelte; | ||
if (svelte_dep && semver.validRange(svelte_dep) && semver.gtr('5.0.0', svelte_dep)) { | ||
console.log( | ||
colors | ||
.bold() | ||
.red('\nYou need to upgrade to Svelte version 5 first (`npx sv migrate svelte-5`).\n') | ||
); | ||
process.exit(1); | ||
} | ||
|
||
const kit_dep = pkg.devDependencies?.['@sveltejs/kit'] ?? pkg.dependencies?.['@sveltejs/kit']; | ||
if (kit_dep && semver.validRange(kit_dep) && semver.gtr('2.0.0', kit_dep)) { | ||
console.log( | ||
colors | ||
.bold() | ||
.red('\nYou need to upgrade to SvelteKit version 2 first (`npx sv migrate sveltekit-2`).\n') | ||
); | ||
process.exit(1); | ||
} | ||
|
||
console.log( | ||
colors | ||
.bold() | ||
.yellow( | ||
'\nThis will update files in the current directory\n' + | ||
"If you're inside a monorepo, don't run this in the root directory, rather run it in all projects independently.\n" | ||
) | ||
); | ||
|
||
const use_git = check_git(); | ||
|
||
const response = await prompts({ | ||
type: 'confirm', | ||
name: 'value', | ||
message: 'Continue?', | ||
initial: false | ||
}); | ||
|
||
if (!response.value) { | ||
process.exit(1); | ||
} | ||
|
||
const folders = await prompts({ | ||
type: 'multiselect', | ||
name: 'value', | ||
message: 'Which folders should be migrated?', | ||
choices: fs | ||
.readdirSync('.') | ||
.filter( | ||
(dir) => fs.statSync(dir).isDirectory() && dir !== 'node_modules' && !dir.startsWith('.') | ||
) | ||
.map((dir) => ({ title: dir, value: dir, selected: true })) | ||
}); | ||
|
||
if (!folders.value?.length) { | ||
process.exit(1); | ||
} | ||
|
||
update_pkg_json(); | ||
|
||
// For some reason {folders.value.join(',')} as part of the glob doesn't work and returns less files | ||
const files = folders.value.flatMap( | ||
/** @param {string} folder */ (folder) => | ||
glob(`${folder}/**`, { filesOnly: true, dot: true }) | ||
.map((file) => file.replace(/\\/g, '/')) | ||
.filter( | ||
(file) => | ||
!file.includes('/node_modules/') && | ||
// We're not transforming usage inside .ts/.js files since you can't use the $store syntax there, | ||
// and therefore have to either subscribe or pass it along, which we can't auto-migrate | ||
file.endsWith('.svelte') | ||
) | ||
); | ||
|
||
for (const file of files) { | ||
update_svelte_file( | ||
file, | ||
(code) => code, | ||
(code) => transform_svelte_code(code, { filename: file }) | ||
); | ||
} | ||
|
||
console.log(colors.bold().green('✔ Your project has been migrated')); | ||
|
||
console.log('\nRecommended next steps:\n'); | ||
|
||
const cyan = colors.bold().cyan; | ||
|
||
const tasks = [ | ||
"install the updated dependencies ('npm i' / 'pnpm i' / etc) " + use_git && | ||
cyan('git commit -m "migration to $app/state"') | ||
].filter(Boolean); | ||
|
||
tasks.forEach((task, i) => { | ||
console.log(` ${i + 1}: ${task}`); | ||
}); | ||
|
||
console.log(''); | ||
|
||
if (use_git) { | ||
console.log(`Run ${cyan('git diff')} to review changes.\n`); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,74 @@ | ||
import fs from 'node:fs'; | ||
import { update_pkg } from '../../utils.js'; | ||
|
||
export function update_pkg_json() { | ||
fs.writeFileSync( | ||
'package.json', | ||
update_pkg_json_content(fs.readFileSync('package.json', 'utf8')) | ||
); | ||
} | ||
|
||
/** | ||
* @param {string} content | ||
*/ | ||
export function update_pkg_json_content(content) { | ||
return update_pkg(content, [['@sveltejs/kit', '^2.12.0']]); | ||
} | ||
|
||
/** | ||
* @param {string} code | ||
* @param {{ filename?: string }} options | ||
*/ | ||
export function transform_svelte_code(code, options) { | ||
// Quick check if nothing to do | ||
if (!code.includes('$app/stores')) return code; | ||
|
||
// Check if file is using legacy APIs - if so, we can't migrate since reactive statements would break | ||
const lines = code.split('\n'); | ||
if (lines.some((line) => /^\s*(export let|\$:) /.test(line))) { | ||
return code; | ||
} | ||
|
||
const import_match = code.match(/import\s*{([^}]+)}\s*from\s*("|')\$app\/stores\2/); | ||
if (!import_match) return code; // nothing to do | ||
|
||
const stores = import_match[1].split(',').map((i) => i.trim()); | ||
let modified = code.replace('$app/stores', '$app/state'); | ||
|
||
for (const store of stores) { | ||
// if someone uses that they're deep into stores and we better not touch this file | ||
if (store === 'getStores') return code; | ||
|
||
const regex = new RegExp(`\\b${store}\\b`, 'g'); | ||
let match; | ||
let count_removed = 0; | ||
|
||
while ((match = regex.exec(modified)) !== null) { | ||
const before = modified.slice(0, match.index); | ||
const after = modified.slice(match.index + store.length); | ||
|
||
if (before.slice(-1) !== '$') { | ||
if (/[_'"]/.test(before.slice(-1))) continue; // false positive | ||
|
||
if (store === 'updated' && after.startsWith('.check()')) { | ||
continue; // this stays as is | ||
} | ||
|
||
if ( | ||
match.index - count_removed > /** @type {number} */ (import_match.index) && | ||
match.index - count_removed < | ||
/** @type {number} */ (import_match.index) + import_match[0].length | ||
) { | ||
continue; // this is the import statement | ||
} | ||
|
||
return code; | ||
} | ||
|
||
modified = before.slice(0, -1) + store + (store === 'page' ? '' : '.current') + after; | ||
count_removed++; | ||
} | ||
} | ||
|
||
return modified; | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,91 @@ | ||
import { assert, test } from 'vitest'; | ||
import { transform_svelte_code } from './migrate.js'; | ||
|
||
test('Updates $app/store #1', () => { | ||
const result = transform_svelte_code( | ||
`<script> | ||
import { page } from '$app/stores'; | ||
</script> | ||
|
||
<div>{$page.url}</div> | ||
<button onclick={() => { | ||
console.log($page.state); | ||
}}></button> | ||
`, | ||
{} | ||
); | ||
assert.equal( | ||
result, | ||
`<script> | ||
import { page } from '$app/state'; | ||
</script> | ||
|
||
<div>{page.url}</div> | ||
<button onclick={() => { | ||
console.log(page.state); | ||
}}></button> | ||
` | ||
); | ||
}); | ||
|
||
test('Updates $app/store #2', () => { | ||
const result = transform_svelte_code( | ||
`<script> | ||
import { navigating, updated } from '$app/stores'; | ||
$updated; | ||
updated.check(); | ||
</script> | ||
|
||
is_navigating: {$navigating} | ||
`, | ||
{} | ||
); | ||
assert.equal( | ||
result, | ||
`<script> | ||
import { navigating, updated } from '$app/state'; | ||
updated.current; | ||
updated.check(); | ||
</script> | ||
|
||
is_navigating: {navigating.current} | ||
` | ||
); | ||
}); | ||
|
||
test('Does not update $app/store #1', () => { | ||
const input = `<script> | ||
import { page } from '$app/stores'; | ||
$: x = $page.url; | ||
</script> | ||
|
||
{x} | ||
`; | ||
const result = transform_svelte_code(input, {}); | ||
assert.equal(result, input); | ||
}); | ||
|
||
test('Does not update $app/store #2', () => { | ||
const input = `<script> | ||
import { page } from '$app/stores'; | ||
import { derived } from 'svelte/store'; | ||
const url = derived(page, ($page) => $page.url); | ||
</script> | ||
|
||
{$url} | ||
`; | ||
const result = transform_svelte_code(input, {}); | ||
assert.equal(result, input); | ||
}); | ||
|
||
test('Does not update $app/store #3', () => { | ||
const input = `<script> | ||
import { page, getStores } from '$app/stores'; | ||
const x = getStores(); | ||
</script> | ||
|
||
{$page.url} | ||
`; | ||
const result = transform_svelte_code(input, {}); | ||
assert.equal(result, input); | ||
}); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.