All files / src/compiler/migrate index.js

82.36% Statements 677/822
80% Branches 152/190
85% Functions 17/20
82.14% Lines 667/812

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 8132x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 7x 7x 10x 10x 10x 10x 10x 10x 10x 10x 6x 6x 6x 6x   6x 6x 6x 16x 16x 16x 4x 16x 3x 3x 16x 6x 6x 6x 6x 1x 1x 6x 6x 6x     6x 6x 6x 6x 6x 6x 6x 2x   2x 2x 2x 5x 2x 2x 2x 6x 4x 1x 4x 3x 3x 10x 3x 3x 3x 4x 6x 6x 6x 2x 2x 6x 4x 4x 4x 6x 6x 4x 4x 6x 2x 2x 2x 2x 6x 6x 10x 10x 1x 1x 1x 1x 1x 1x     1x 10x 10x 10x         10x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 98x 98x 98x 1x 1x 1x 1x 1x 1x 1x 1x 1x 98x 2x 2x 24x 2x 2x 10x 9x 9x 9x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 12x     12x 12x 12x 12x 12x             12x 12x 12x 12x 12x       12x 12x 12x 12x 2x 2x 10x 10x 10x 10x 10x                                                       10x 10x 10x 10x 10x 10x 10x   10x         10x 10x 10x 10x 10x 10x 5x 5x 5x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x                 12x 12x 12x 10x 10x 10x 10x 10x 9x 9x 9x 10x 10x 10x 10x 2x 2x 1x 1x 1x 1x 1x 1x 1x 2x 2x 7x 7x 7x 6x 6x 6x 6x 7x 4x 7x 3x 3x 3x 3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 3x 1x                 1x 3x 4x 4x 4x 4x 4x 7x 1x 1x 1x 1x 1x 1x 1x 7x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 7x 2x 2x 2x 2x 2x 24x 2x 2x 20x 20x 2x 2x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 4x 4x 4x 2x 2x 2x 4x 4x 4x 4x 2x 2x     2x 2x     2x 2x     2x 2x 3x 3x 3x 3x 3x   3x 3x 2x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 2x 2x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x               3x 3x 3x 2x 2x 2x 2x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 10x 10x 3x 3x 3x 3x 3x 3x 7x 7x 7x 10x                   7x 7x 10x 4x 4x 4x 4x 4x 3x 3x 3x 2x 2x 2x 2x 2x 24x 24x 24x 24x 23x 17x 17x 23x 1x 1x 17x 23x 23x 23x 23x 24x 24x 13x 13x 13x 2x 2x 13x 13x 13x 13x 13x 13x 8x 13x 13x 13x 13x 13x 4x 4x 2x 2x 2x 2x 2x 2x 2x           2x 2x                     2x 2x 2x                     2x 2x 4x 4x 4x 13x 13x 9x 9x 9x 9x 5x 5x 5x 5x 5x 9x 1x 1x 9x 9x 5x 1x 5x 1x 4x 1x 3x 1x 1x 5x 9x 9x 6x 6x 5x 5x 5x   5x                   5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 6x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 13x 4x 4x 4x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 4x 4x 4x 3x 2x 3x 1x 1x 4x 1x 1x 4x 4x 4x 13x 24x 2x 2x 2x 2x 2x 13x 13x 13x 13x 13x 13x           2x 2x 2x 2x 2x 48x 48x                           48x 1x 1x 1x 1x 1x 1x 48x 2x 2x 10x 10x 10x 10x 10x 10x 10x 2x 2x 8x 8x 8x 8x 10x 5x 5x 3x 3x 3x 9x 9x 3x 3x 3x 3x  
import MagicString from 'magic-string';
import { walk } from 'zimmerframe';
import { parse } from '../phases/1-parse/index.js';
import { analyze_component } from '../phases/2-analyze/index.js';
import { validate_component_options } from '../validate-options.js';
import { get_rune } from '../phases/scope.js';
import { reset } from '../state.js';
import { extract_identifiers } from '../utils/ast.js';
import { regex_is_valid_identifier } from '../phases/patterns.js';
import { migrate_svelte_ignore } from '../utils/extract_svelte_ignore.js';
 
/**
 * Does a best-effort migration of Svelte code towards using runes, event attributes and render tags.
 * May throw an error if the code is too complex to migrate automatically.
 *
 * @param {string} source
 * @returns {{ code: string; }}
 */
export function migrate(source) {
	try {
		reset(source, { filename: 'migrate.svelte' });
 
		let parsed = parse(source);
 
		const { customElement: customElementOptions, ...parsed_options } = parsed.options || {};
 
		/** @type {import('#compiler').ValidatedCompileOptions} */
		const combined_options = {
			...validate_component_options({}, ''),
			...parsed_options,
			customElementOptions
		};
 
		const str = new MagicString(source);
		const analysis = analyze_component(parsed, source, combined_options);
		const indent = guess_indent(source);
 
		/** @type {State} */
		let state = {
			scope: analysis.instance.scope,
			analysis,
			str,
			indent,
			props: [],
			props_insertion_point: parsed.instance?.content.start ?? 0,
			has_props_rune: false,
			props_name: analysis.root.unique('props').name,
			rest_props_name: analysis.root.unique('rest').name,
			end: source.length,
			run_name: analysis.root.unique('run').name,
			needs_run: false
		};
 
		if (parsed.instance) {
			walk(parsed.instance.content, state, instance_script);
		}
 
		state = { ...state, scope: analysis.template.scope };
		walk(parsed.fragment, state, template);
 
		const run_import = `import { run${state.run_name === 'run' ? '' : `as ${state.run_name}`} } from 'svelte/legacy';`;
		let added_legacy_import = false;
 
		if (state.props.length > 0 || analysis.uses_rest_props || analysis.uses_props) {
			const has_many_props = state.props.length > 3;
			const props_separator = has_many_props ? `\n${indent}${indent}` : ' ';
			let props = '';
			if (analysis.uses_props) {
				props = `...${state.props_name}`;
			} else {
				props = state.props
					.map((prop) => {
						let prop_str =
							prop.local === prop.exported ? prop.local : `${prop.exported}: ${prop.local}`;
						if (prop.bindable) {
							prop_str += ` = $bindable(${prop.init})`;
						} else if (prop.init) {
							prop_str += ` = ${prop.init}`;
						}
						return prop_str;
					})
					.join(`,${props_separator}`);
 
				if (analysis.uses_rest_props) {
					props += `,${props_separator}...${state.rest_props_name}`;
				}
			}
 
			if (state.has_props_rune) {
				// some render tags or forwarded event attributes to add
				str.appendRight(state.props_insertion_point, ` ${props},`);
			} else {
				const uses_ts = parsed.instance?.attributes.some(
					(attr) => attr.name === 'lang' && /** @type {any} */ (attr).value[0].data === 'ts'
				);
				const type_name = state.scope.root.unique('Props').name;
				let type = '';
				if (uses_ts) {
					if (analysis.uses_props || analysis.uses_rest_props) {
						type = `interface ${type_name} { [key: string]: any }`;
					} else {
						type = `interface ${type_name} {${props_separator}${state.props
							.map((prop) => {
								return `${prop.exported}${prop.optional ? '?' : ''}: ${prop.type}`;
							})
							.join(`,${props_separator}`)}${has_many_props ? `\n${indent}` : ' '}}`;
					}
				} else {
					if (analysis.uses_props || analysis.uses_rest_props) {
						type = `{Record<string, any>}`;
					} else {
						type = `{${state.props
							.map((prop) => {
								return `${prop.exported}${prop.optional ? '?' : ''}: ${prop.type}`;
							})
							.join(`, `)}}`;
					}
				}
 
				let props_declaration = `let {${props_separator}${props}${has_many_props ? `\n${indent}` : ' '}}`;
				if (uses_ts) {
					props_declaration = `${type}\n\n${indent}${props_declaration}`;
					props_declaration = `${props_declaration}${type ? `: ${type_name}` : ''} = $props();`;
				} else {
					props_declaration = `/** @type {${type}} */\n${indent}${props_declaration}`;
					props_declaration = `${props_declaration} = $props();`;
				}
 
				if (parsed.instance) {
					props_declaration = `\n${indent}${props_declaration}`;
					str.appendRight(state.props_insertion_point, props_declaration);
				} else {
					const imports = state.needs_run ? `${indent}${run_import}\n` : '';
					str.prepend(`<script>\n${imports}${indent}${props_declaration}\n</script>\n\n`);
					added_legacy_import = true;
				}
			}
		}
 
		if (state.needs_run && !added_legacy_import) {
			if (parsed.instance) {
				str.appendRight(
					/** @type {number} */ (parsed.instance.content.start),
					`\n${indent}${run_import}\n`
				);
			} else {
				str.prepend(`<script>\n${indent}${run_import}\n</script>\n\n`);
			}
		}
 
		return { code: str.toString() };
	} catch (e) {
		// eslint-disable-next-line no-console
		console.error('Error while migrating Svelte code');
		throw e;
	}
}
 
/**
 * @typedef {{
 *  scope: import('../phases/scope.js').Scope;
 *  str: MagicString;
 *  analysis: import('../phases/types.js').ComponentAnalysis;
 *  indent: string;
 *  props: Array<{ local: string; exported: string; init: string; bindable: boolean; optional: boolean; type: string }>;
 *  props_insertion_point: number;
 *  has_props_rune: boolean;
 * 	props_name: string;
 * 	rest_props_name: string;
 *  end: number;
 *  run_name: string;
 *  needs_run: boolean;
 * }} State
 */
 
/** @type {import('zimmerframe').Visitors<import('../types/template.js').SvelteNode, State>} */
const instance_script = {
	_(node, { state, next }) {
		// @ts-expect-error
		const comments = node.leadingComments;
		if (comments) {
			for (const comment of comments) {
				if (comment.type === 'Line') {
					const migrated = migrate_svelte_ignore(comment.value);
					if (migrated !== comment.value) {
						state.str.overwrite(comment.start + '//'.length, comment.end, migrated);
					}
				}
			}
		}
		next();
	},
	Identifier(node, { state }) {
		handle_identifier(node, state);
	},
	ExportNamedDeclaration(node, { state, next }) {
		if (node.declaration) {
			next();
			return;
		}
 
		let count_removed = 0;
		for (const specifier of node.specifiers) {
			const binding = state.scope.get(specifier.local.name);
			if (binding?.kind === 'bindable_prop') {
				state.str.remove(
					/** @type {number} */ (specifier.start),
					/** @type {number} */ (specifier.end)
				);
				count_removed++;
			}
		}
		if (count_removed === node.specifiers.length) {
			state.str.remove(/** @type {number} */ (node.start), /** @type {number} */ (node.end));
		}
	},
	VariableDeclaration(node, { state, path }) {
		if (state.scope !== state.analysis.instance.scope) {
			return;
		}
 
		let nr_of_props = 0;
 
		for (const declarator of node.declarations) {
			if (state.analysis.runes) {
				if (get_rune(declarator.init, state.scope) === '$props') {
					state.props_insertion_point = /** @type {number} */ (declarator.id.start) + 1;
					state.has_props_rune = true;
				}
				continue;
			}
 
			let bindings;
			try {
				bindings = state.scope.get_bindings(declarator);
			} catch (e) {
				// no bindings, so we can skip this
				continue;
			}
			const has_state = bindings.some((binding) => binding.kind === 'state');
			const has_props = bindings.some((binding) => binding.kind === 'bindable_prop');
 
			if (!has_state && !has_props) {
				continue;
			}
 
			if (has_props) {
				nr_of_props++;
 
				if (declarator.id.type !== 'Identifier') {
					// TODO invest time in this?
					throw new Error(
						'Encountered an export declaration pattern that is not supported for automigration.'
					);
					// Turn export let into props. It's really really weird because export let { x: foo, z: [bar]} = ..
					// means that foo and bar are the props (i.e. the leafs are the prop names), not x and z.
					// const tmp = state.scope.generate('tmp');
					// const paths = extract_paths(declarator.id);
					// state.props_pre.push(
					// 	b.declaration('const', b.id(tmp), visit(declarator.init!) as Expression)
					// );
					// for (const path of paths) {
					// 	const name = (path.node as Identifier).name;
					// 	const binding = state.scope.get(name)!;
					// 	const value = path.expression!(b.id(tmp));
					// 	if (binding.kind === 'bindable_prop' || binding.kind === 'rest_prop') {
					// 		state.props.push({
					// 			local: name,
					// 			exported: binding.prop_alias ? binding.prop_alias : name,
					// 			init: value
					// 		});
					// 		state.props_insertion_point = /** @type {number} */(declarator.end);
					// 	} else {
					// 		declarations.push(b.declarator(path.node, value));
					// 	}
					// }
				}
 
				const binding = /** @type {import('#compiler').Binding} */ (
					state.scope.get(declarator.id.name)
				);
 
				if (
					state.analysis.uses_props &&
					(declarator.init || binding.mutated || binding.reassigned)
				) {
					throw new Error(
						'$$props is used together with named props in a way that cannot be automatically migrated.'
					);
				}
 
				state.props.push({
					local: declarator.id.name,
					exported: binding.prop_alias ? binding.prop_alias : declarator.id.name,
					init: declarator.init
						? state.str.original.substring(
								/** @type {number} */ (declarator.init.start),
								/** @type {number} */ (declarator.init.end)
							)
						: '',
					optional: !!declarator.init,
					type: extract_type(declarator, state.str, path),
					bindable: binding.mutated || binding.reassigned
				});
				state.props_insertion_point = /** @type {number} */ (declarator.end);
				state.str.update(
					/** @type {number} */ (declarator.start),
					/** @type {number} */ (declarator.end),
					''
				);
 
				continue;
			}

			// state
			if (declarator.init) {
				state.str.prependLeft(/** @type {number} */ (declarator.init.start), '$state(');
				state.str.appendRight(/** @type {number} */ (declarator.init.end), ')');
			} else {
				state.str.prependLeft(/** @type {number} */ (declarator.id.end), ' = $state()');
			}
		}
 
		if (nr_of_props === node.declarations.length) {
			let start = /** @type {number} */ (node.start);
			let end = /** @type {number} */ (node.end);
 
			const parent = path.at(-1);
			if (parent?.type === 'ExportNamedDeclaration') {
				start = /** @type {number} */ (parent.start);
				end = /** @type {number} */ (parent.end);
			}
			while (state.str.original[start] !== '\n') start--;
			while (state.str.original[end] !== '\n') end++;
			state.str.update(start, end, '');
		}
	},
	BreakStatement(node, { state, path }) {
		if (path[1].type !== 'LabeledStatement') return;
		if (node.label?.name !== '$') return;
		state.str.update(
			/** @type {number} */ (node.start),
			/** @type {number} */ (node.end),
			'return;'
		);
	},
	LabeledStatement(node, { path, state, next }) {
		if (state.analysis.runes) return;
		if (path.length > 1) return;
		if (node.label.name !== '$') return;
 
		next();
 
		if (
			node.body.type === 'ExpressionStatement' &&
			node.body.expression.type === 'AssignmentExpression'
		) {
			const ids = extract_identifiers(node.body.expression.left);
			const bindings = ids.map((id) => state.scope.get(id.name));
			const reassigned_bindings = bindings.filter((b) => b?.reassigned);
			if (reassigned_bindings.length === 0 && !bindings.some((b) => b?.kind === 'store_sub')) {
				// $derived
				state.str.update(
					/** @type {number} */ (node.start),
					/** @type {number} */ (node.body.expression.start),
					'let '
				);
				state.str.prependLeft(
					/** @type {number} */ (node.body.expression.right.start),
					'$derived('
				);
				state.str.update(
					/** @type {number} */ (node.body.expression.right.end),
					/** @type {number} */ (node.end),
					');'
				);
				return;
			} else {
				for (const binding of reassigned_bindings) {
					if (binding && ids.includes(binding.node)) {
						// implicitly-declared variable which we need to make explicit
						state.str.prependLeft(
							/** @type {number} */ (node.start),
							`let ${binding.node.name}${binding.kind === 'state' ? ' = $state()' : ''};\n${state.indent}`
						);
					}
				}
			}
		}
 
		state.needs_run = true;
		const is_block_stmt = node.body.type === 'BlockStatement';
		const start_end = /** @type {number} */ (node.body.start);
		// TODO try to find out if we can use $derived.by instead?
		if (is_block_stmt) {
			state.str.update(
				/** @type {number} */ (node.start),
				start_end + 1,
				`${state.run_name}(() => {`
			);
			const end = /** @type {number} */ (node.body.end);
			state.str.update(end - 1, end, '});');
		} else {
			state.str.update(
				/** @type {number} */ (node.start),
				start_end,
				`${state.run_name}(() => {\n${state.indent}`
			);
			state.str.indent(state.indent, {
				exclude: [
					[0, /** @type {number} */ (node.body.start)],
					[/** @type {number} */ (node.body.end), state.end]
				]
			});
			state.str.appendRight(/** @type {number} */ (node.end), `\n${state.indent}});`);
		}
	}
};
 
/** @type {import('zimmerframe').Visitors<import('../types/template.js').SvelteNode, State>} */
const template = {
	Identifier(node, { state }) {
		handle_identifier(node, state);
	},
	RegularElement(node, { state, next }) {
		handle_events(node, state);
		next();
	},
	SvelteElement(node, { state, next }) {
		if (node.tag.type === 'Literal') {
			let is_static = true;
 
			let a = /** @type {number} */ (node.tag.start);
			let b = /** @type {number} */ (node.tag.end);
			let quote_mark = state.str.original[a - 1];
 
			while (state.str.original[--a] !== '=') {
				if (state.str.original[a] === '{') {
					is_static = false;
					break;
				}
			}
 
			if (is_static && state.str.original[b] === quote_mark) {
				state.str.prependLeft(a + 1, '{');
				state.str.appendRight(/** @type {number} */ (node.tag.end) + 1, '}');
			}
		}
 
		handle_events(node, state);
		next();
	},
	SvelteWindow(node, { state, next }) {
		handle_events(node, state);
		next();
	},
	SvelteBody(node, { state, next }) {
		handle_events(node, state);
		next();
	},
	SvelteDocument(node, { state, next }) {
		handle_events(node, state);
		next();
	},
	SlotElement(node, { state, next }) {
		let name = 'children';
		let slot_props = '{ ';
 
		for (const attr of node.attributes) {
			if (attr.type === 'SpreadAttribute') {
				slot_props += `...${state.str.original.substring(/** @type {number} */ (attr.expression.start), attr.expression.end)}, `;
			} else if (attr.type === 'Attribute') {
				if (attr.name === 'name') {
					name = state.scope.generate(/** @type {any} */ (attr.value)[0].data);
				} else {
					const value =
						attr.value !== true
							? state.str.original.substring(
									attr.value[0].start,
									attr.value[attr.value.length - 1].end
								)
							: 'true';
					slot_props += value === attr.name ? `${value}, ` : `${attr.name}: ${value}, `;
				}
			}
		}
 
		slot_props += '}';
		if (slot_props === '{ }') {
			slot_props = '';
		}
 
		state.props.push({
			local: name,
			exported: name,
			init: '',
			bindable: false,
			optional: true,
			type: `import('svelte').${slot_props ? 'Snippet<[any]>' : 'Snippet'}`
		});
 
		if (node.fragment.nodes.length > 0) {
			next();
			state.str.update(
				node.start,
				node.fragment.nodes[0].start,
				`{#if ${name}}{@render ${name}(${slot_props})}{:else}`
			);
			state.str.update(node.fragment.nodes[node.fragment.nodes.length - 1].end, node.end, '{/if}');
		} else {
			state.str.update(node.start, node.end, `{@render ${name}?.(${slot_props})}`);
		}
	},
	Comment(node, { state }) {
		const migrated = migrate_svelte_ignore(node.data);
		if (migrated !== node.data) {
			state.str.overwrite(node.start + '<!--'.length, node.end - '-->'.length, migrated);
		}
	}
};
 
/**
 * @param {import('estree').VariableDeclarator} declarator
 * @param {MagicString} str
 * @param {import('#compiler').SvelteNode[]} path
 */
function extract_type(declarator, str, path) {
	if (declarator.id.typeAnnotation) {
		let start = declarator.id.typeAnnotation.start + 1; // skip the colon
		while (str.original[start] === ' ') {
			start++;
		}
		return str.original.substring(start, declarator.id.typeAnnotation.end);
	}
 
	// try to find a comment with a type annotation, hinting at jsdoc
	const parent = path.at(-1);
	if (parent?.type === 'ExportNamedDeclaration' && parent.leadingComments) {
		const last = parent.leadingComments[parent.leadingComments.length - 1];
		if (last.type === 'Block') {
			const match = /@type {([^}]+)}/.exec(last.value);
			if (match) {
				str.update(/** @type {any} */ (last).start, /** @type {any} */ (last).end, '');
				return match[1];
			}
		}
	}
 
	// try to infer it from the init
	if (declarator.init?.type === 'Literal') {
		const type = typeof declarator.init.value;
		if (type === 'string' || type === 'number' || type === 'boolean') {
			return type;
		}
	}
 
	return 'any';
}
 
/**
 * @param {import('#compiler').RegularElement | import('#compiler').SvelteElement | import('#compiler').SvelteWindow | import('#compiler').SvelteDocument | import('#compiler').SvelteBody} node
 * @param {State} state
 */
function handle_events(node, state) {
	/** @type {Map<string, import('#compiler').OnDirective[]>} */
	const handlers = new Map();
	for (const attribute of node.attributes) {
		if (attribute.type !== 'OnDirective') continue;
 
		let name = `on${attribute.name}`;
		if (attribute.modifiers.includes('capture')) {
			name += 'capture';
		}
 
		const nodes = handlers.get(name) || [];
		nodes.push(attribute);
		handlers.set(name, nodes);
	}
 
	for (const [name, nodes] of handlers) {
		// turn on:click into a prop
		let exported = name;
		if (!regex_is_valid_identifier.test(name)) {
			exported = `'${exported}'`;
		}
		// Check if prop already set, could happen when on:click on different elements
		let local = state.props.find((prop) => prop.exported === exported)?.local;
 
		const last = nodes[nodes.length - 1];
		const payload_name =
			last.expression?.type === 'ArrowFunctionExpression' &&
			last.expression.params[0]?.type === 'Identifier'
				? last.expression.params[0].name
				: generate_event_name(last, state);
		let prepend = '';
 
		for (let i = 0; i < nodes.length - 1; i += 1) {
			const node = nodes[i];
			if (node.expression) {
				let body = '';
				if (node.expression.type === 'ArrowFunctionExpression') {
					body = state.str.original.substring(
						/** @type {number} */ (node.expression.body.start),
						/** @type {number} */ (node.expression.body.end)
					);
				} else {
					body = `${state.str.original.substring(
						/** @type {number} */ (node.expression.start),
						/** @type {number} */ (node.expression.end)
					)}();`;
				}
				// TODO check how many indents needed
				for (const modifier of node.modifiers) {
					if (modifier === 'stopPropagation') {
						body = `\n${state.indent}${payload_name}.stopPropagation();\n${body}`;
					} else if (modifier === 'preventDefault') {
						body = `\n${state.indent}${payload_name}.preventDefault();\n${body}`;
					} else if (modifier === 'stopImmediatePropagation') {
						body = `\n${state.indent}${payload_name}.stopImmediatePropagation();\n${body}`;
					} else {
						body = `\n${state.indent}// @migration-task: incorporate ${modifier} modifier\n${body}`;
					}
				}
				prepend += `\n${state.indent}${body}\n`;
			} else {
				if (!local) {
					local = state.scope.generate(`on${node.name}`);
					state.props.push({
						local,
						exported,
						init: '',
						bindable: false,
						optional: true,
						type: '(event: any) => void'
					});
				}
				prepend += `\n${state.indent}${local}?.(${payload_name});\n`;
			}
 
			state.str.remove(node.start, node.end);
		}
 
		if (last.expression) {
			// remove : from on:click
			state.str.remove(last.start + 2, last.start + 3);
			// remove modifiers
			if (last.modifiers.length > 0) {
				state.str.remove(
					last.start + last.name.length + 3,
					state.str.original.indexOf('=', last.start)
				);
			}
			if (last.modifiers.includes('capture')) {
				state.str.appendRight(last.start + last.name.length + 3, 'capture');
			}
 
			for (const modifier of last.modifiers) {
				if (modifier === 'stopPropagation') {
					prepend += `\n${state.indent}${payload_name}.stopPropagation();\n`;
				} else if (modifier === 'preventDefault') {
					prepend += `\n${state.indent}${payload_name}.preventDefault();\n`;
				} else if (modifier === 'stopImmediatePropagation') {
					prepend += `\n${state.indent}${payload_name}.stopImmediatePropagation();\n`;
				} else if (modifier !== 'capture') {
					prepend += `\n${state.indent}// @migration-task: incorporate ${modifier} modifier\n`;
				}
			}
 
			if (prepend) {
				let pos = last.expression.start;
				if (last.expression.type === 'ArrowFunctionExpression') {
					pos = last.expression.body.start;
					if (
						last.expression.params.length > 0 &&
						last.expression.params[0].type !== 'Identifier'
					) {
						const start = /** @type {number} */ (last.expression.params[0].start);
						const end = /** @type {number} */ (last.expression.params[0].end);
						// replace event payload with generated one that others use,
						// then destructure generated payload param into what the user wrote
						state.str.overwrite(start, end, payload_name);
						prepend = `let ${state.str.original.substring(
							start,
							end
						)} = ${payload_name};\n${prepend}`;
					} else if (last.expression.params.length === 0) {
						// add generated payload param to arrow function
						const pos = state.str.original.lastIndexOf(')', last.expression.body.start);
						state.str.prependLeft(pos, payload_name);
					}
 
					const needs_curlies = last.expression.body.type !== 'BlockStatement';
					state.str.prependRight(
						/** @type {number} */ (pos) + (needs_curlies ? 0 : 1),
						`${needs_curlies ? '{' : ''}${prepend}${state.indent}`
					);
					state.str.appendRight(
						/** @type {number} */ (last.expression.body.end) - (needs_curlies ? 0 : 1),
						`\n${needs_curlies ? '}' : ''}`
					);
				} else {
					state.str.update(
						/** @type {number} */ (last.expression.start),
						/** @type {number} */ (last.expression.end),
						`(${payload_name}) => {${prepend}\n${state.indent}${state.str.original.substring(
							/** @type {number} */ (last.expression.start),
							/** @type {number} */ (last.expression.end)
						)}?.(${payload_name});\n}`
					);
				}
			}
		} else {
			// turn on:click into a prop
			// Check if prop already set, could happen when on:click on different elements
			if (!local) {
				local = state.scope.generate(`on${last.name}`);
				state.props.push({
					local,
					exported,
					init: '',
					bindable: false,
					optional: true,
					type: '(event: any) => void'
				});
			}
 
			let replacement = '';
			if (!prepend) {
				if (exported === local) {
					replacement = `{${name}}`;
				} else {
					replacement = `${name}={${local}}`;
				}
			} else {
				replacement = `${name}={(${payload_name}) => {${prepend}\n${state.indent}${local}?.(${payload_name});\n}}`;
			}
 
			state.str.update(last.start, last.end, replacement);
		}
	}
}
 
/**
 * @param {import('#compiler').OnDirective} last
 * @param {State} state
 */
function generate_event_name(last, state) {
	const scope =
		(last.expression && state.analysis.template.scopes.get(last.expression)) || state.scope;
 
	let name = 'event';
	if (!scope.get(name)) return name;

	let i = 1;
	while (scope.get(`${name}${i}`)) i += 1;
	return `${name}${i}`;
}
 
/**
 * @param {import('estree').Identifier} node
 * @param {State} state
 */
function handle_identifier(node, state) {
	if (state.analysis.uses_props) {
		if (node.name === '$$props' || node.name === '$$restProps') {
			// not 100% correct for $$restProps but it'll do
			state.str.update(
				/** @type {number} */ (node.start),
				/** @type {number} */ (node.end),
				state.props_name
			);
		} else {
			const binding = state.scope.get(node.name);
			if (binding?.kind === 'bindable_prop') {
				state.str.prependLeft(/** @type {number} */ (node.start), `${state.props_name}.`);
			}
		}
	} else if (node.name === '$$restProps' && state.analysis.uses_rest_props) {
		state.str.update(
			/** @type {number} */ (node.start),
			/** @type {number} */ (node.end),
			state.rest_props_name
		);
	}
}
 
/** @param {string} content */
function guess_indent(content) {
	const lines = content.split('\n');
 
	const tabbed = lines.filter((line) => /^\t+/.test(line));
	const spaced = lines.filter((line) => /^ {2,}/.test(line));
 
	if (tabbed.length === 0 && spaced.length === 0) {
		return '\t';
	}
 
	// More lines tabbed than spaced? Assume tabs, and
	// default to tabs in the case of a tie (or nothing
	// to go on)
	if (tabbed.length >= spaced.length) {
		return '\t';
	}
 
	// Otherwise, we need to guess the multiple
	const min = spaced.reduce((previous, current) => {
		const count = /^ +/.exec(current)?.[0].length ?? 0;
		return Math.min(count, previous);
	}, Infinity);
 
	return ' '.repeat(min);
}