-
-
Notifications
You must be signed in to change notification settings - Fork 2k
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
feat: add Svelte 4 migration #9729
Merged
Merged
Changes from 1 commit
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
1c5f9b9
feat: add Svelte 4 migration
dummdidumm 65fff4a
custom element migration
dummdidumm b20c55e
Merge branch 'master' into svelte-4-migration
dummdidumm 521910c
migrate transition global
dummdidumm 295ef7a
lint
dummdidumm 9f75f9e
merge
benmccann a134b95
comment out extensions support
benmccann 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
Next
Next commit
feat: add Svelte 4 migration
- Loading branch information
commit 1c5f9b98ad0bd6ab273b249e793eb1a773ebec40
There are no files selected for viewing
This file contains 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 Svelte 4 migration |
This file contains 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,73 @@ | ||
import colors from 'kleur'; | ||
import fs from 'node:fs'; | ||
import path from 'node:path'; | ||
import { pathToFileURL } from 'node:url'; | ||
import prompts from 'prompts'; | ||
import glob from 'tiny-glob/sync.js'; | ||
import { bail, check_git } from '../../utils.js'; | ||
import { update_js_file, update_svelte_file } 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'); | ||
} | ||
|
||
console.log(colors.bold().yellow('\nThis will update files in the current directory\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 { default: config } = fs.existsSync('svelte.config.js') | ||
? await import(pathToFileURL(path.resolve('svelte.config.js')).href) | ||
: { default: {} }; | ||
|
||
/** @type {string[]} */ | ||
const svelte_extensions = config.extensions ?? ['.svelte']; | ||
const extensions = [...svelte_extensions, '.ts', '.js']; | ||
// TODO read tsconfig/jsconfig if available? src/** will be good for 99% of cases | ||
const files = glob(`src/**`, { filesOnly: true, dot: true }).map((file) => | ||
file.replace(/\\/g, '/') | ||
); | ||
|
||
for (const file of files) { | ||
if (extensions.some((ext) => file.endsWith(ext))) { | ||
if (svelte_extensions.some((ext) => file.endsWith(ext))) { | ||
update_svelte_file(file); | ||
} else { | ||
update_js_file(file); | ||
} | ||
} | ||
} | ||
|
||
console.log(colors.bold().green('✔ Your project has been migrated')); | ||
|
||
console.log('\nRecommended next steps:\n'); | ||
|
||
const cyan = colors.bold().cyan; | ||
|
||
const tasks = [ | ||
use_git && cyan('git commit -m "migration to Svelte 4"'), | ||
`Review the migration guide at TODO`, | ||
`Read the updated docs at https://svelte.dev/docs` | ||
].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 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,179 @@ | ||
import fs from 'node:fs'; | ||
import { Project, SourceFile, ts, Node } from 'ts-morph'; | ||
|
||
/** @param {string} file_path */ | ||
export function update_svelte_file(file_path) { | ||
const content = fs.readFileSync(file_path, 'utf-8'); | ||
const updated = content.replace( | ||
/<script([^]*?)>([^]+?)<\/script>(\n*)/g, | ||
(_match, attrs, contents, whitespace) => { | ||
return `<script${attrs}>${transform_code(contents)}</script>${whitespace}`; | ||
} | ||
); | ||
fs.writeFileSync(file_path, updated, 'utf-8'); | ||
} | ||
|
||
/** @param {string} file_path */ | ||
export function update_js_file(file_path) { | ||
const content = fs.readFileSync(file_path, 'utf-8'); | ||
const updated = transform_code(content); | ||
fs.writeFileSync(file_path, updated, 'utf-8'); | ||
} | ||
|
||
/** @param {string} code */ | ||
export function transform_code(code) { | ||
const project = new Project({ useInMemoryFileSystem: true }); | ||
const source = project.createSourceFile('svelte.ts', code); | ||
update_imports(source); | ||
update_typeof_svelte_component(source); | ||
update_action_types(source); | ||
update_action_return_types(source); | ||
return source.getFullText(); | ||
} | ||
|
||
// <svelte:options tag=".." /> -> <svelte:options customElement=".." /> | ||
|
||
/** | ||
* Action<T> -> Action<T, any> | ||
* @param {SourceFile} source | ||
*/ | ||
function update_action_types(source) { | ||
const imports = get_imports(source, 'svelte/action', 'Action'); | ||
for (const namedImport of imports) { | ||
const identifiers = find_identifiers(source, namedImport.getAliasNode()?.getText() ?? 'Action'); | ||
for (const id of identifiers) { | ||
const parent = id.getParent(); | ||
if (Node.isTypeReference(parent)) { | ||
const type_args = parent.getTypeArguments(); | ||
if (type_args.length === 1) { | ||
parent.addTypeArgument('any'); | ||
} else if (type_args.length === 0) { | ||
parent.addTypeArgument('HTMLElement'); | ||
parent.addTypeArgument('any'); | ||
} | ||
} | ||
} | ||
} | ||
} | ||
|
||
/** | ||
* ActionReturn -> ActionReturn<any> | ||
* @param {SourceFile} source | ||
*/ | ||
function update_action_return_types(source) { | ||
const imports = get_imports(source, 'svelte/action', 'ActionReturn'); | ||
for (const namedImport of imports) { | ||
const identifiers = find_identifiers( | ||
source, | ||
namedImport.getAliasNode()?.getText() ?? 'ActionReturn' | ||
); | ||
for (const id of identifiers) { | ||
const parent = id.getParent(); | ||
if (Node.isTypeReference(parent)) { | ||
const type_args = parent.getTypeArguments(); | ||
if (type_args.length === 0) { | ||
parent.addTypeArgument('any'); | ||
} | ||
} | ||
} | ||
} | ||
} | ||
|
||
/** | ||
* SvelteComponentTyped -> SvelteComponent | ||
* @param {SourceFile} source | ||
*/ | ||
function update_imports(source) { | ||
const identifiers = find_identifiers(source, 'SvelteComponent'); | ||
const can_rename = identifiers.every((id) => { | ||
const parent = id.getParent(); | ||
return ( | ||
(Node.isImportSpecifier(parent) && | ||
!parent.getAliasNode() && | ||
parent.getParent().getParent().getParent().getModuleSpecifier().getText() === 'svelte') || | ||
!is_declaration(parent) | ||
); | ||
}); | ||
|
||
const imports = get_imports(source, 'svelte', 'SvelteComponentTyped'); | ||
for (const namedImport of imports) { | ||
if (can_rename) { | ||
namedImport.renameAlias('SvelteComponent'); | ||
if ( | ||
namedImport | ||
.getParent() | ||
.getElements() | ||
.some((e) => !e.getAliasNode() && e.getNameNode().getText() === 'SvelteComponent') | ||
) { | ||
namedImport.remove(); | ||
} else { | ||
namedImport.setName('SvelteComponent'); | ||
namedImport.removeAlias(); | ||
} | ||
} else { | ||
namedImport.renameAlias('SvelteComponentTyped'); | ||
namedImport.setName('SvelteComponent'); | ||
} | ||
} | ||
} | ||
|
||
/** | ||
* typeof SvelteComponent -> typeof SvelteComponent<any> | ||
* @param {SourceFile} source | ||
*/ | ||
function update_typeof_svelte_component(source) { | ||
const imports = get_imports(source, 'svelte', 'SvelteComponent'); | ||
|
||
for (const type of imports) { | ||
if (type) { | ||
const name = type.getAliasNode() ?? type.getNameNode(); | ||
name.findReferencesAsNodes().forEach((ref) => { | ||
const parent = ref.getParent(); | ||
if (parent && Node.isTypeQuery(parent)) { | ||
const id = parent.getFirstChildByKind(ts.SyntaxKind.Identifier); | ||
if (id?.getText() === name.getText()) { | ||
const typeArguments = parent.getTypeArguments(); | ||
if (typeArguments.length === 0) { | ||
parent.addTypeArgument('any'); | ||
} | ||
} | ||
} | ||
}); | ||
} | ||
} | ||
} | ||
|
||
/** | ||
* @param {SourceFile} source | ||
* @param {string} from | ||
* @param {string} name | ||
*/ | ||
function get_imports(source, from, name) { | ||
return source | ||
.getImportDeclarations() | ||
.filter((i) => i.getModuleSpecifierValue() === from) | ||
.flatMap((i) => i.getNamedImports()) | ||
.filter((i) => i.getName() === name); | ||
} | ||
|
||
/** | ||
* @param {SourceFile} source | ||
* @param {string} name | ||
*/ | ||
function find_identifiers(source, name) { | ||
return source.getDescendantsOfKind(ts.SyntaxKind.Identifier).filter((i) => i.getText() === name); | ||
} | ||
|
||
/** | ||
* Does not include imports | ||
* @param {Node} node | ||
*/ | ||
function is_declaration(node) { | ||
return ( | ||
Node.isVariableDeclaration(node) || | ||
Node.isFunctionDeclaration(node) || | ||
Node.isClassDeclaration(node) || | ||
Node.isTypeAliasDeclaration(node) || | ||
Node.isInterfaceDeclaration(node) | ||
); | ||
} |
This file contains 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,120 @@ | ||
import { test } from 'uvu'; | ||
import * as assert from 'uvu/assert'; | ||
import { transform_code } from './migrate.js'; | ||
|
||
test('Updates SvelteComponentTyped #1', () => { | ||
const result = transform_code( | ||
`import { SvelteComponentTyped } from 'svelte'; | ||
|
||
export class Foo extends SvelteComponentTyped<{}> {} | ||
|
||
const bar: SvelteComponentTyped = null;` | ||
); | ||
assert.equal( | ||
result, | ||
`import { SvelteComponent } from 'svelte'; | ||
|
||
export class Foo extends SvelteComponent<{}> {} | ||
|
||
const bar: SvelteComponent = null;` | ||
); | ||
}); | ||
|
||
test('Updates SvelteComponentTyped #2', () => { | ||
const result = transform_code( | ||
`import { SvelteComponentTyped, SvelteComponent } from 'svelte'; | ||
|
||
export class Foo extends SvelteComponentTyped<{}> {} | ||
|
||
const bar: SvelteComponentTyped = null; | ||
const baz: SvelteComponent = null;` | ||
); | ||
assert.equal( | ||
result, | ||
`import { SvelteComponent } from 'svelte'; | ||
|
||
export class Foo extends SvelteComponent<{}> {} | ||
|
||
const bar: SvelteComponent = null; | ||
const baz: SvelteComponent = null;` | ||
); | ||
}); | ||
|
||
test('Updates SvelteComponentTyped #3', () => { | ||
const result = transform_code( | ||
`import { SvelteComponentTyped } from 'svelte'; | ||
|
||
interface SvelteComponent {} | ||
|
||
export class Foo extends SvelteComponentTyped<{}> {} | ||
|
||
const bar: SvelteComponentTyped = null; | ||
const baz: SvelteComponent = null;` | ||
); | ||
assert.equal( | ||
result, | ||
`import { SvelteComponent as SvelteComponentTyped } from 'svelte'; | ||
|
||
interface SvelteComponent {} | ||
|
||
export class Foo extends SvelteComponentTyped<{}> {} | ||
|
||
const bar: SvelteComponentTyped = null; | ||
const baz: SvelteComponent = null;` | ||
); | ||
}); | ||
|
||
test('Updates typeof SvelteComponent', () => { | ||
const result = transform_code( | ||
`import { SvelteComponent } from 'svelte'; | ||
import { SvelteComponent as C } from 'svelte'; | ||
|
||
const a: typeof SvelteComponent = null; | ||
function b(c: typeof SvelteComponent) {} | ||
const c: typeof SvelteComponent<any> = null; | ||
const d: typeof C = null; | ||
` | ||
); | ||
assert.equal( | ||
result, | ||
`import { SvelteComponent } from 'svelte'; | ||
import { SvelteComponent as C } from 'svelte'; | ||
|
||
const a: typeof SvelteComponent<any> = null; | ||
function b(c: typeof SvelteComponent<any>) {} | ||
const c: typeof SvelteComponent<any> = null; | ||
const d: typeof C<any> = null; | ||
` | ||
); | ||
}); | ||
|
||
test('Updates Action and ActionReturn', () => { | ||
const result = transform_code( | ||
`import { Action, ActionReturn } from 'svelte/action'; | ||
|
||
const a: Action = () => {}; | ||
const b: Action<HTMLDivElement> = () => {}; | ||
const c: Action<HTMLDivElement, true> = () => {}; | ||
const d: Action<HTMLDivElement, true, {}> = () => {}; | ||
const e: ActionReturn = () => {}; | ||
const f: ActionReturn<true> = () => {}; | ||
const g: ActionReturn<true, {}> = () => {}; | ||
` | ||
); | ||
assert.equal( | ||
result, | ||
|
||
`import { Action, ActionReturn } from 'svelte/action'; | ||
|
||
const a: Action<HTMLElement, any> = () => {}; | ||
const b: Action<HTMLDivElement, any> = () => {}; | ||
const c: Action<HTMLDivElement, true> = () => {}; | ||
const d: Action<HTMLDivElement, true, {}> = () => {}; | ||
const e: ActionReturn<any> = () => {}; | ||
const f: ActionReturn<true> = () => {}; | ||
const g: ActionReturn<true, {}> = () => {}; | ||
` | ||
); | ||
}); | ||
|
||
test.run(); |
This file contains 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
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
this would break with mdsvex
.svx
, safer to only do .svelte by default and maybe ask the user for other extensions that contain svelte code that is compatible with the basic regex used in update_svelte_fileThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I commented that out because I think it's going to do more harm than good since
.svx
is probably the most common usage of it