Skip to content

Commit 5272dec

Browse files
committed
feat: add page-state migration
A simple, string-based migration for sveltejs/kit#13140 (tested on that repo, zero false-positives, less than five false negatives)
1 parent 80990d3 commit 5272dec

File tree

5 files changed

+290
-0
lines changed

5 files changed

+290
-0
lines changed

.changeset/polite-eyes-invent.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'svelte-migrate': minor
3+
---
4+
5+
feat: add page-state migration

packages/migrate/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ npx sv migrate [migration]
2121
| `sveltekit-2` | SvelteKit 1.0 | SvelteKit 2.0 | [Website](https://svelte.dev/docs/kit/migrating-to-sveltekit-2) |
2222
| `svelte-4` | Svelte 3 | Svelte 4 | [Website](https://svelte.dev/docs/svelte/v4-migration-guide) |
2323
| `svelte-5` | Svelte 4 | Svelte 5 | |
24+
| `page-state` | `$app/stores` | `$app/state` | |
2425
| `package` | `@sveltejs/package@1` | `@sveltejs/package@2` | [#8922](https://github.com/sveltejs/kit/pull/8922) |
2526
| `routes` | SvelteKit pre-1.0 | SvelteKit 1.0 | [#5774](https://github.com/sveltejs/kit/discussions/5774) |
2627

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
import colors from 'kleur';
2+
import fs from 'node:fs';
3+
import process from 'node:process';
4+
import prompts from 'prompts';
5+
import semver from 'semver';
6+
import glob from 'tiny-glob/sync.js';
7+
import { bail, check_git, update_svelte_file } from '../../utils.js';
8+
import { transform_svelte_code, update_pkg_json } from './migrate.js';
9+
10+
export async function migrate() {
11+
if (!fs.existsSync('package.json')) {
12+
bail('Please re-run this script in a directory with a package.json');
13+
}
14+
15+
const pkg = JSON.parse(fs.readFileSync('package.json', 'utf8'));
16+
17+
const svelte_dep = pkg.devDependencies?.svelte ?? pkg.dependencies?.svelte;
18+
if (svelte_dep && semver.validRange(svelte_dep) && semver.gtr('5.0.0', svelte_dep)) {
19+
console.log(
20+
colors
21+
.bold()
22+
.red('\nYou need to upgrade to Svelte version 5 first (`npx sv migrate svelte-5`).\n')
23+
);
24+
process.exit(1);
25+
}
26+
27+
const kit_dep = pkg.devDependencies?.['@sveltejs/kit'] ?? pkg.dependencies?.['@sveltejs/kit'];
28+
if (kit_dep && semver.validRange(kit_dep) && semver.gtr('2.0.0', kit_dep)) {
29+
console.log(
30+
colors
31+
.bold()
32+
.red('\nYou need to upgrade to SvelteKit version 2 first (`npx sv migrate sveltekit-2`).\n')
33+
);
34+
process.exit(1);
35+
}
36+
37+
console.log(
38+
colors
39+
.bold()
40+
.yellow(
41+
'\nThis will update files in the current directory\n' +
42+
"If you're inside a monorepo, don't run this in the root directory, rather run it in all projects independently.\n"
43+
)
44+
);
45+
46+
const use_git = check_git();
47+
48+
const response = await prompts({
49+
type: 'confirm',
50+
name: 'value',
51+
message: 'Continue?',
52+
initial: false
53+
});
54+
55+
if (!response.value) {
56+
process.exit(1);
57+
}
58+
59+
const folders = await prompts({
60+
type: 'multiselect',
61+
name: 'value',
62+
message: 'Which folders should be migrated?',
63+
choices: fs
64+
.readdirSync('.')
65+
.filter(
66+
(dir) => fs.statSync(dir).isDirectory() && dir !== 'node_modules' && !dir.startsWith('.')
67+
)
68+
.map((dir) => ({ title: dir, value: dir, selected: true }))
69+
});
70+
71+
if (!folders.value?.length) {
72+
process.exit(1);
73+
}
74+
75+
update_pkg_json();
76+
77+
// For some reason {folders.value.join(',')} as part of the glob doesn't work and returns less files
78+
const files = folders.value.flatMap(
79+
/** @param {string} folder */ (folder) =>
80+
glob(`${folder}/**`, { filesOnly: true, dot: true })
81+
.map((file) => file.replace(/\\/g, '/'))
82+
.filter(
83+
(file) =>
84+
!file.includes('/node_modules/') &&
85+
// We're not transforming usage inside .ts/.js files since you can't use the $store syntax there,
86+
// and therefore have to either subscribe or pass it along, which we can't auto-migrate
87+
file.endsWith('.svelte')
88+
)
89+
);
90+
91+
for (const file of files) {
92+
update_svelte_file(
93+
file,
94+
(code) => code,
95+
(code) => transform_svelte_code(code, { filename: file })
96+
);
97+
}
98+
99+
console.log(colors.bold().green('✔ Your project has been migrated'));
100+
101+
console.log('\nRecommended next steps:\n');
102+
103+
const cyan = colors.bold().cyan;
104+
105+
const tasks = [
106+
"install the updated dependencies ('npm i' / 'pnpm i' / etc) " + use_git &&
107+
cyan('git commit -m "migration to $app/state"')
108+
].filter(Boolean);
109+
110+
tasks.forEach((task, i) => {
111+
console.log(` ${i + 1}: ${task}`);
112+
});
113+
114+
console.log('');
115+
116+
if (use_git) {
117+
console.log(`Run ${cyan('git diff')} to review changes.\n`);
118+
}
119+
}
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
import fs from 'node:fs';
2+
import { update_pkg } from '../../utils.js';
3+
4+
export function update_pkg_json() {
5+
fs.writeFileSync(
6+
'package.json',
7+
update_pkg_json_content(fs.readFileSync('package.json', 'utf8'))
8+
);
9+
}
10+
11+
/**
12+
* @param {string} content
13+
*/
14+
export function update_pkg_json_content(content) {
15+
return update_pkg(content, [['@sveltejs/kit', '^2.12.0']]);
16+
}
17+
18+
/**
19+
* @param {string} code
20+
* @param {{ filename?: string }} options
21+
*/
22+
export function transform_svelte_code(code, options) {
23+
// Quick check if nothing to do
24+
if (!code.includes('$app/stores')) return code;
25+
26+
// Check if file is using legacy APIs - if so, we can't migrate since reactive statements would break
27+
const lines = code.split('\n');
28+
if (lines.some((line) => /^\s*(export let|\$:) /.test(line))) {
29+
return code;
30+
}
31+
32+
const import_match = code.match(/import\s*{([^}]+)}\s*from\s*("|')\$app\/stores\2/);
33+
if (!import_match) return code; // nothing to do
34+
35+
const stores = import_match[1].split(',').map((i) => i.trim());
36+
let modified = code.replace('$app/stores', '$app/state');
37+
38+
for (const store of stores) {
39+
// if someone uses that they're deep into stores and we better not touch this file
40+
if (store === 'getStores') return code;
41+
42+
const regex = new RegExp(`\\b${store}\\b`, 'g');
43+
let match;
44+
let count_removed = 0;
45+
46+
while ((match = regex.exec(modified)) !== null) {
47+
const before = modified.slice(0, match.index);
48+
const after = modified.slice(match.index + store.length);
49+
50+
if (before.slice(-1) !== '$') {
51+
if (/[_'"]/.test(before.slice(-1))) continue; // false positive
52+
53+
if (store === 'updated' && after.startsWith('.check()')) {
54+
continue; // this stays as is
55+
}
56+
57+
if (
58+
match.index - count_removed > /** @type {number} */ (import_match.index) &&
59+
match.index - count_removed <
60+
/** @type {number} */ (import_match.index) + import_match[0].length
61+
) {
62+
continue; // this is the import statement
63+
}
64+
65+
return code;
66+
}
67+
68+
modified = before.slice(0, -1) + store + (store === 'page' ? '' : '.current') + after;
69+
count_removed++;
70+
}
71+
}
72+
73+
return modified;
74+
}
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
import { assert, test } from 'vitest';
2+
import { transform_svelte_code } from './migrate.js';
3+
4+
test('Updates $app/store #1', () => {
5+
const result = transform_svelte_code(
6+
`<script>
7+
import { page } from '$app/stores';
8+
</script>
9+
10+
<div>{$page.url}</div>
11+
<button onclick={() => {
12+
console.log($page.state);
13+
}}></button>
14+
`,
15+
{}
16+
);
17+
assert.equal(
18+
result,
19+
`<script>
20+
import { page } from '$app/state';
21+
</script>
22+
23+
<div>{page.url}</div>
24+
<button onclick={() => {
25+
console.log(page.state);
26+
}}></button>
27+
`
28+
);
29+
});
30+
31+
test('Updates $app/store #2', () => {
32+
const result = transform_svelte_code(
33+
`<script>
34+
import { navigating, updated } from '$app/stores';
35+
$updated;
36+
updated.check();
37+
</script>
38+
39+
is_navigating: {$navigating}
40+
`,
41+
{}
42+
);
43+
assert.equal(
44+
result,
45+
`<script>
46+
import { navigating, updated } from '$app/state';
47+
updated.current;
48+
updated.check();
49+
</script>
50+
51+
is_navigating: {navigating.current}
52+
`
53+
);
54+
});
55+
56+
test('Does not update $app/store #1', () => {
57+
const input = `<script>
58+
import { page } from '$app/stores';
59+
$: x = $page.url;
60+
</script>
61+
62+
{x}
63+
`;
64+
const result = transform_svelte_code(input, {});
65+
assert.equal(result, input);
66+
});
67+
68+
test('Does not update $app/store #2', () => {
69+
const input = `<script>
70+
import { page } from '$app/stores';
71+
import { derived } from 'svelte/store';
72+
const url = derived(page, ($page) => $page.url);
73+
</script>
74+
75+
{$url}
76+
`;
77+
const result = transform_svelte_code(input, {});
78+
assert.equal(result, input);
79+
});
80+
81+
test('Does not update $app/store #3', () => {
82+
const input = `<script>
83+
import { page, getStores } from '$app/stores';
84+
const x = getStores();
85+
</script>
86+
87+
{$page.url}
88+
`;
89+
const result = transform_svelte_code(input, {});
90+
assert.equal(result, input);
91+
});

0 commit comments

Comments
 (0)