@@ -528,6 +528,26 @@ export class ScriptLetContext {
528528 this . closeScopeCallbacks . pop ( ) ! ( ) ;
529529 }
530530
531+ public appendDeclareMaybeStores ( maybeStores : Set < string > ) : void {
532+ const reservedNames = new Set < string > ( [
533+ "$$props" ,
534+ "$$restProps" ,
535+ "$$slots" ,
536+ ] ) ;
537+ for ( const nm of maybeStores ) {
538+ if ( reservedNames . has ( nm ) ) continue ;
539+
540+ this . appendScriptWithoutOffset (
541+ `declare let $${ nm } : Parameters<Parameters<(typeof ${ nm } )["subscribe"]>[0]>[0];` ,
542+ ( node , tokens , comments , result ) => {
543+ tokens . length = 0 ;
544+ comments . length = 0 ;
545+ removeAllScope ( node , result ) ;
546+ }
547+ ) ;
548+ }
549+ }
550+
531551 private appendScript (
532552 text : string ,
533553 offset : number ,
@@ -912,7 +932,7 @@ function removeAllScope(target: ESTree.Node, result: ScriptLetCallbackOption) {
912932 return ;
913933 }
914934 if ( node . type === "Identifier" ) {
915- let scope = result . getScope ( node ) ;
935+ let scope = result . getInnermostScope ( node ) ;
916936 if (
917937 ( scope . block as any ) . type === "TSTypeAliasDeclaration" &&
918938 ( scope . block as any ) . id === node
@@ -939,16 +959,37 @@ function removeAllScope(target: ESTree.Node, result: ScriptLetCallbackOption) {
939959
940960/** Remove variable */
941961function removeIdentifierVariable ( node : ESTree . Identifier , scope : Scope ) : void {
942- const varIndex = scope . variables . findIndex ( ( v ) =>
943- v . defs . some ( ( def ) => def . name === node )
944- ) ;
945- if ( varIndex >= 0 ) {
962+ for ( let varIndex = 0 ; varIndex < scope . variables . length ; varIndex ++ ) {
946963 const variable = scope . variables [ varIndex ] ;
947- scope . variables . splice ( varIndex , 1 ) ;
948- const name = node . name ;
949- if ( variable === scope . set . get ( name ) ) {
950- scope . set . delete ( name ) ;
964+ const defIndex = variable . defs . findIndex ( ( def ) => def . name === node ) ;
965+ if ( defIndex < 0 ) {
966+ continue ;
951967 }
968+ variable . defs . splice ( defIndex , 1 ) ;
969+ if ( variable . defs . length === 0 ) {
970+ // Remove variable
971+ referencesToThrough ( variable . references , scope ) ;
972+ scope . variables . splice ( varIndex , 1 ) ;
973+ const name = node . name ;
974+ if ( variable === scope . set . get ( name ) ) {
975+ scope . set . delete ( name ) ;
976+ }
977+ } else {
978+ const idIndex = variable . identifiers . indexOf ( node ) ;
979+ if ( idIndex >= 0 ) {
980+ variable . identifiers . splice ( idIndex , 1 ) ;
981+ }
982+ }
983+ return ;
984+ }
985+ }
986+
987+ /** Move reference to through */
988+ function referencesToThrough ( references : Reference [ ] , baseScope : Scope ) {
989+ let scope : Scope | null = baseScope ;
990+ while ( scope ) {
991+ scope . through . push ( ...references ) ;
992+ scope = scope . upper ;
952993 }
953994}
954995
0 commit comments