You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
#25749 adds @JsDefinition for interfaces with methods annotated with JS expressions. The same structure can also be used for directly interacting on JS modules rather than interacting on a JS instance.
@JsDefinition@JsModule("./myJsModule")
publicinterfaceMyJsModule {
// Imports "doSomething" from the JS module and invokes that functionpublicvoiddoSomething(StringsomeArg);
}
This shape should be allowed only for Page.executeJs(Class) (implemented separately in #25799) which acts globally but it would be confusing for Element.executeJs(Class) (especially considering #25812). It remains possible to pass an Element or Component reference to such a method so that something like the current Grid connector init could be expressed as page.executeJs(GridConenctor.class).initLazy(gridElement); so that the connector JS could be a regular JS module instead of publishing itself as window.Vaadin.Flow.gridConnector.
Valid request, and a natural third step in the invoker series: the interface + method-per-JS-snippet shape carries over to a module without changing the wire format or the client at all. Notes from digging through the existing implementation, plus the decisions I think have to be made before it can be written.
Where it lands today: @JsInvoker/@JsExpression and JsInvokers are not on main yet — #25749 and #25799 are both open, and #25799 is stacked on #25749 — so this becomes a third branch on top of feat/js-invoker-for-page, not a change against main.
What the generated file has to do
TaskGenerateJsInvokers renders one async function per method into frontend/generated/vaadin-js-invokers.js, keyed by interface name and name/argCount, and the client applies it with the element as this (or with no this for a page invoker). A module target means the function body needs the module's exports, and there are two shapes:
Static import at the top of the generated file. The file is imported from the generated bootstrap, so every module of every invoker interface in the application — including add-ons — ends up in the eager startup graph. That is the opposite of what the Grid connector example wants.
Dynamic import() inside the function, which is already async: const module = await import('Frontend/myJsModule'); return module.doSomething($0);. Vite code-splits it, the module loads on first call, the result still flows through the existing Promise.resolve(result) handling, and no client-side change is needed at all.
Shape 2 looks clearly preferable.
How a method binds to an export
(a) Named export by method name, @JsExpression rejected on a module-targeting interface. Simplest, but nothing else can be expressed.
(b) Module namespace object as this. The generated function does fn.call(module, ...), so @JsExpression("return this.doSomething($0)") works, and once Call instance method for @JsDefinition methods without a @JsExpression annotation #25812 lands, the annotation-free void doSomething(String a) means the same thing for both an element target and a module target — one rule, two targets, with (a) as its default case. This is my recommendation.
(c) @JsExpression stays mandatory, with the namespace in scope under a fixed name (module.doSomething($0)). Explicit, but it introduces a magic identifier and gets no shorthand.
Resolving the module specifier
@JsModule values are relative to the frontend folder for project files (./myJsModule → Frontend/myJsModule), relative to META-INF/resources/frontend for jars (copied and imported as Frontend/generated/jar-resources/…), and bare specifiers are npm packages. That translation currently lives in AbstractUpdateImports#getUniqueEs6ImportPaths/toValidBrowserImport, both private — the invoker generator needs the same answer and should reuse it rather than re-derive it.
Two constraints on that:
TaskGenerateJsInvokers runs before TaskCopyFrontendFiles, so at generation time it cannot decide project-vs-jar by testing for the copied file.
The hotswap path re-renders the file through the staticTaskGenerateJsInvokers.fileContent(Collection) / invokerLines(Class), with no Options and no scanner. So either specifier derivation is kept a pure function of the annotation value, or a resolver has to be threaded into both the build and the hotswap path — otherwise a hotswapped file would carry different imports than a built one and silently diverge.
Also needs a rule: @JsModule is @Repeatable and has developmentOnly. Probably exactly one non-development-only module is the call target, with any others treated as plain side-effect imports.
One side effect worth deciding deliberately
FullDependenciesScanner#collectScripts collects @JsModule from every annotated class on the class path, not only components, so under the full scan (dev mode) an invoker interface's module would also be pulled eagerly into generated-flow-imports.js. The bytecode scanner used for an optimized production build only visits classes reachable from routes/components and would generally not see a stand-alone interface. Left alone, that means the same application loads the module eagerly in dev and lazily in production. Invoker interfaces should either be excluded from the scanned modules or included in both paths — but not one of each.
Restricting the shape to Page.getJsInvoker
JsInvokers.create(Class, scheduler) is the single gate both entry points go through, so the check belongs there: an extra input for whether the caller accepts a module target, with Element.getJsInvoker throwing IllegalArgumentException for a @JsModule-annotated interface and naming Page.getJsInvoker in the message.
One related detail: Page's scheduler passes call.getExpression() into the JavaScriptInvocation, and JsInvokerCall#getExpression() throws when the method has no @JsExpression. A module-targeting method without the annotation therefore fails on the server before it ever reaches the client, so getExpression() has to either return the synthesized expression or stop being on that path. #25812 hits exactly the same wall, so the two are cheapest to solve together — and if (b) above is chosen, they are largely the same change.
Bundle validation and hotswap detection need nothing new: the module specifier is part of the generated file, so the existing content hash in jsInvokersChanged already covers it.
@Legioth — happy to implement this once you've picked between (a)/(b)/(c) and decided how the scanner should treat an invoker interface's @JsModule; those two are the only real forks, the rest follows.
I checked the plan above against the current main. #25749 and #25799 are merged (@JsDefinition, JsInvokers/JsSnippets markers, Page.executeJs(Class)), so this can now be built directly on main. Some points in the plan are out of date, and a few are not correct anymore. Here is an updated version.
What changed since the plan
The names are now TaskGenerateJsDefinitions, vaadin-js-definitions.js, JsDefinitionProxy and JsDefinitionHotswapper.
The client calls a function by a hash (JsCall.functionId), not by interface name and name/argCount.
The kind of a definition is decided by its marker interface (JsInvokers or JsSnippets), and JsDefinitionProxy.checkDefinition returns it.
Dynamic import(): agreed
Shape 2 (a dynamic import() inside the async function) is still the right choice. It needs no client change.
Resolving the module path: simpler than the plan says
The two problems the plan lists do not exist anymore:
Task order does not matter.AbstractUpdateImports.resolveResource decides "jar or project" with classFinder.getResource("META-INF/resources/frontend/..."), that is, on the class path, not on the copied files. toValidBrowserImport checks the project frontend folder. Both only need Options, and the generator has them. So it does not matter that TaskGenerateJsDefinitions runs before TaskCopyFrontendFiles.
The hotswap path has Options now. It calls TaskGenerateJsDefinitions.updateJsDefinitions(Options, ...), not a static method without options.
So: move these two methods out of AbstractUpdateImports into a small shared resolver that takes Options, and use it in both places. Only renderDefinitionLines and isInGeneratedFile, which are static today, need to get the resolver as a parameter.
One more point: a dynamic import() of a file that does not exist fails the Vite build. If the path cannot be resolved, the generator should leave the definition out and log an error, as it already does for a definition that fails checkDefinition. Otherwise one broken add-on breaks the build of every application that has it on the class path.
The function id must include the module
JsCall.functionId(Method) hashes only the expression and the parameter count. Two module definitions with the same expression, for example return this.init($0), would get the same id even if they target different modules. One of them would then call the wrong module. The hash must include the @JsModule value. Use the value as written in the annotation, not the resolved path: the server computes the id at runtime and cannot resolve paths there.
With that, hotswap needs no new code. DevLoopRedefiner uses functionId as its fingerprint, and frontendDependencies already reads @JsModule from every changed type. BundleValidationUtil.jsDefinitionsChanged hashes the generated file, so the module path is covered there as well.
I agree with (b): the module namespace is this. My comment on #25812 suggests the shorthand return this.<name>(...). With (b), the same shorthand means "call the export with this name" for a module definition. So one rule works for both targets, and nothing new needs to be documented. The generated function only changes this:
With a module, the shorthand finally has a useful this on the page side. This does not settle the open question on #25812, though: a plain JsInvokers definition used through Page.executeJs(Class) still has no useful this for the shorthand.
How to mark a module definition: a marker interface, not only @JsModule
The plan uses the @JsModule annotation alone as the signal. I suggest a third marker interface instead, for two reasons:
@JsModule alone would change what existing code means.@JsModule is allowed on interfaces, and a natural pattern today puts a helper script on an element definition:
If @JsModule made an interface a module target, this interface would silently become "page only, this is the module", and Element.executeJs would start to fail for it.
The type system can't see an annotation. The markers exist so that Element.executeJs (<T extends JsInvokers>) and JsSnippets.of (<T extends JsSnippets>) refuse the wrong kind at compile time. A module target decided by an annotation can only fail at runtime.
New marker and Kind.JsModuleInvokers does not extend JsInvokers. checkDefinition returns a new Kind for it, for example MODULE_CALLS. An interface that extends more than one marker is refused, as JsInvokers + JsSnippets is today.
Exactly one target module. The interface needs exactly one @JsModule that is not developmentOnly, read with getDeclaredAnnotationsByType. @JsModule is @Inherited, but Java ignores @Inherited on interfaces, so only the interface's own annotations count. developmentOnly modules stay plain imports. Zero or two target modules is an error.
Method rules are the same as for JsInvokers: the same return types, and @JsWithExecutionContext still allowed. Only this is different: it is the module namespace. checkMethods and the proxy can reuse the CALLS path.
Inheritance: a method runs against the module of the interface that declares it. This matches the current rule that an inherited method runs through the interface that declares it. The functionId hash uses that interface's @JsModule value.
No JavaScript for an element. Every method of a module definition, with @JsExpression or the shorthand, runs with the module as this, and the interface can not be passed to Element.executeJs. This follows the existing rule that one interface can not declare both calls and snippets: one interface has one meaning of this. JavaScript that needs the element as this goes into a separate JsInvokers interface. A module definition can still work with an element: pass the element as an argument (initLazy(grid.getElement())), or use @JsExpression("return this.initLazy.call($0)") to make it the this of the export.
Entry point: a new Page method, for example Page.executeModuleJs(Class<T extends JsModuleInvokers>). It can't be an overload of executeJs, because executeJs(Class<T extends JsInvokers>) and executeJs(Class<T extends JsModuleInvokers>) have the same erasure. With a separate method, Element.executeJs and ElementJsInitializerRegistration refuse a module definition at compile time, without a runtime check. No existing signature changes, which matters since 25.4 is already in beta.
Other options I considered:
The marker extends JsInvokers.Page.executeJs would work without changes, but the element entry points would have to refuse module definitions at runtime.
A common super-marker with a wider bound on Page.executeJs. It keeps one method name, but it changes the erased return type of a method that is already in a beta.
Scanners: the module is loaded at startup in both modes, not only in dev
The plan says the production bytecode scanner would "generally not see" the interface. That is not correct for this use case. FrontendClassVisitor.visitLdcInsn follows class literals, so page.executeModuleJs(GridConnectorJs.class) in a reachable class makes the interface reachable, and its @JsModule is collected. The full scan in dev mode collects it too. So today both modes load the module at startup. They do not differ.
The simplest first step is to keep that behavior. The import() in the generated function then gets the module that is already loaded. Real lazy loading (leave module definitions out of the scanned imports) can be a separate follow-up. That follow-up has to change both scanners in the same way.
Related: #27022. The generator takes every @JsDefinition on the class path. A module definition in an add-on the application does not use would add a dynamic import, and a chunk, to every application. This is one more reason to leave out a definition whose module cannot be resolved.
Updated plan
Add the JsModuleInvokers marker, a new Kind, and a new Page method for it. A module definition has exactly one non-developmentOnly@JsModule of its own. Update "Which marker to extend" in the @JsDefinition Javadoc.
Move resolveResource and toValidBrowserImport into a shared resolver that takes Options. Use it in TaskGenerateJsDefinitions, including the updateJsDefinitions path.
Generate await import(...) plus .call(module, ...). If the module cannot be resolved, leave the definition out and log an error.
If the path cannot be resolved, the generator should leave the definition out and log an error
I guess this will still give a runtime exception when trying to use the interface?
a plain JsInvokers definition used through Page.executeJs(Class) still has no useful this for the shorthand.
I think this was implied by some other parts of the analysis but spelling it out here just to be explicit. An eligible method without an annotation is always interpreted as having a this-referencing @JsExpression. Element.executeJs should refuse an interface that is bound to a module so that there won't ever be two different this candidates whereas Page.executeJs should refuse one that isn't bound to a module if the interface has any method without @JsExpression.
I also started thinking of a slightly different shape. I think it's a new feature but mentioning here so that someone else might spot any reason for why both features need to be considered together.
The feature would be a way of injecting a module into an invoker bound to an element. This enables importing one or even several modules into an invoker that is used through Element.executeJs. This requires defining an explicit name for the imported module.
A JsModuleInvokers could then be seen as a shorthand that infers as = "this" for its only unqualified @JsModule, even though the underlying implementation might actually work slightly differently.
I guess this will still give a runtime exception when trying to use the interface?
The error will be only on the client and most likely with a poor message. Perhaps a better way would be to generate the function anyway but making it throw an error with a proper reason. In the production bundle the error message should not disclose any information about the application.
// development bundle: the full reasonwindow.Vaadin.Flow.jsDefinitions["<id>"]=asyncfunction(){thrownewError("Module './myJsModule' of com.example.MyJsModule could not be resolved at build time");};// production bundle: no class name and no module pathwindow.Vaadin.Flow.jsDefinitions["<id>"]=asyncfunction(){thrownewError("The module of this function could not be resolved at build time. See the build log.");};
About the @JsModule(as=...) feauture. I think this should be designed together with this issue, even if it is implemented separately, because JsModuleInvokers then becomes the case as = "this", so the generator should have one mechanism for module bindings and the function id must hash every binding.
Can the server-side runtime know about whether the module could be resolved? If that's the case, then the proxy invocation handler could throw an helpful exception?
Can the server-side runtime know about whether the module could be resolved? If that's the case, then the proxy invocation handler could throw an helpful exception?
Yes, if the build writes it down. The generator already writes the function ids next to the generated file, the build copies them into the bundle stats, and #27078 reads them on the server at runtime. The build can add the ids whose module could not be resolved, with the module path, and the invocation handler then throws a helpful exception when one of those methods is called. The check is per method, because the methods of one interface can depend on different modules.
The check is per method, because the methods of one interface can depend on different modules.
How? Isn't it the same module for all methods in the interface? And with the as addition, I guess we'd inject all named modules into all expressions without inspecting which expression actually reads which parameters?
Right, all methods of an interface get the same modules, and all named modules are injected into every expression.
The only way to get different modules is inheritance, since an inherited method keeps the modules of the interface that declares it. That is the only reason to check when a method is called rather than when the proxy is created.
@JsDefinitionImport(from = "./my.js", defaultExport = "a", namespace = "b", exports = {"c", "d"}) maps to import a, { c, d }, * as b from "./my.js". Each attribute is optional and they can be combined, because the generated code calls import() once and reads m.default, m and m.c from the result. The import is loaded on the first call. The element stays this.
Module definition.JsModuleInvokers (does not extend JsInvokers) with Page.executeModuleJs. It needs exactly one @JsDefinitionImport with no names, and that module is this:
JsModuleInvokers is the only compile-time split between element and page: Element.executeJs refuses it, and it gives shorthand methods a meaning on the page.
Rules.
@JsModule on any definition is only a side-effect import, loaded eagerly.
@JsDefinitionImport with no names: binds this on a JsModuleInvokers; an error on a JsInvokers (use @JsModule); refused on JsSnippets, like every import.
Names must be valid identifiers, not reserved words (so the default export is reached with defaultExport, not exports = "default"), and must not collide, within one annotation or across the imports of the interface that declares the method.
The same module in several annotations is merged into one import().
@JsDefinitionImport on a class that is not a definition is an error.
The function id hashes every import.
A module that can not be resolved: its functions are left out of the bundle and recorded in the bundle stats by function id, and the server throws when such a method is called.
No renamed exports (import { foo as bar }): namespace covers conflicts, and it can be added later.
Where the error for an import outside a definition runs. If it only runs in the application build, a published add-on with that mistake breaks every application that uses it.
Eager or lazy @JsModule: revisit when @JsDefinition gets code splitting in general.
I tested @JsDefinitionImport with the Grid connector, and it looks like there is a gap in the plan. With initConnector moved to an imported initLazy, 29 of 66 tests in 10 Grid IT classes fail. All of them pass without the import.
The problem is that the generated function always runs await import(...) first, even when @JsModule has already loaded the module. So an imported call runs after the calls that follow it in the same round trip. Grid needs initLazy to run first, because the calls right after it use this.$connector: header renderers, sorters and data. Those calls throw or do nothing, so grids show no rows and no sorters. ComboBox, DatePicker, TimePicker, VirtualList, MenuBar, ContextMenu and Map use the same pattern.
One option to fix this is to load the imports of a JsModuleInvokers with the route, like a lazy @JsModule. The build puts the module into the chunk of every route that reaches the definition, and the chunk registers it. The generated function then reads the module without await. The client already waits for a component's chunk before it runs the invocations of the same message, so the call runs in order and no client change is needed. I updated #27425 with this scope. Named imports on a JsInvokers stay loaded on the first call, so the GridConnectorJs example in the @JsDefinitionImport Javadoc needs to change too.
Activity
totally-not-ai commentedon Sep 18, 2026
Valid request, and a natural third step in the invoker series: the interface + method-per-JS-snippet shape carries over to a module without changing the wire format or the client at all. Notes from digging through the existing implementation, plus the decisions I think have to be made before it can be written.
Where it lands today:
@JsInvoker/@JsExpressionandJsInvokersare not onmainyet — #25749 and #25799 are both open, and #25799 is stacked on #25749 — so this becomes a third branch on top offeat/js-invoker-for-page, not a change againstmain.What the generated file has to do
TaskGenerateJsInvokersrenders oneasync functionper method intofrontend/generated/vaadin-js-invokers.js, keyed by interface name andname/argCount, and the client applies it with the element asthis(or with nothisfor a page invoker). A module target means the function body needs the module's exports, and there are two shapes:import()inside the function, which is alreadyasync:const module = await import('Frontend/myJsModule'); return module.doSomething($0);. Vite code-splits it, the module loads on first call, the result still flows through the existingPromise.resolve(result)handling, and no client-side change is needed at all.Shape 2 looks clearly preferable.
How a method binds to an export
@JsExpressionrejected on a module-targeting interface. Simplest, but nothing else can be expressed.this. The generated function doesfn.call(module, ...), so@JsExpression("return this.doSomething($0)")works, and once Call instance method for @JsDefinition methods without a @JsExpression annotation #25812 lands, the annotation-freevoid doSomething(String a)means the same thing for both an element target and a module target — one rule, two targets, with (a) as its default case. This is my recommendation.@JsExpressionstays mandatory, with the namespace in scope under a fixed name (module.doSomething($0)). Explicit, but it introduces a magic identifier and gets no shorthand.Resolving the module specifier
@JsModulevalues are relative to the frontend folder for project files (./myJsModule→Frontend/myJsModule), relative toMETA-INF/resources/frontendfor jars (copied and imported asFrontend/generated/jar-resources/…), and bare specifiers are npm packages. That translation currently lives inAbstractUpdateImports#getUniqueEs6ImportPaths/toValidBrowserImport, both private — the invoker generator needs the same answer and should reuse it rather than re-derive it.Two constraints on that:
TaskGenerateJsInvokersruns beforeTaskCopyFrontendFiles, so at generation time it cannot decide project-vs-jar by testing for the copied file.TaskGenerateJsInvokers.fileContent(Collection)/invokerLines(Class), with noOptionsand no scanner. So either specifier derivation is kept a pure function of the annotation value, or a resolver has to be threaded into both the build and the hotswap path — otherwise a hotswapped file would carry different imports than a built one and silently diverge.Also needs a rule:
@JsModuleis@Repeatableand hasdevelopmentOnly. Probably exactly one non-development-only module is the call target, with any others treated as plain side-effect imports.One side effect worth deciding deliberately
FullDependenciesScanner#collectScriptscollects@JsModulefrom every annotated class on the class path, not only components, so under the full scan (dev mode) an invoker interface's module would also be pulled eagerly intogenerated-flow-imports.js. The bytecode scanner used for an optimized production build only visits classes reachable from routes/components and would generally not see a stand-alone interface. Left alone, that means the same application loads the module eagerly in dev and lazily in production. Invoker interfaces should either be excluded from the scanned modules or included in both paths — but not one of each.Restricting the shape to
Page.getJsInvokerJsInvokers.create(Class, scheduler)is the single gate both entry points go through, so the check belongs there: an extra input for whether the caller accepts a module target, withElement.getJsInvokerthrowingIllegalArgumentExceptionfor a@JsModule-annotated interface and namingPage.getJsInvokerin the message.One related detail:
Page's scheduler passescall.getExpression()into theJavaScriptInvocation, andJsInvokerCall#getExpression()throws when the method has no@JsExpression. A module-targeting method without the annotation therefore fails on the server before it ever reaches the client, sogetExpression()has to either return the synthesized expression or stop being on that path. #25812 hits exactly the same wall, so the two are cheapest to solve together — and if (b) above is chosen, they are largely the same change.Bundle validation and hotswap detection need nothing new: the module specifier is part of the generated file, so the existing content hash in
jsInvokersChangedalready covers it.@Legioth — happy to implement this once you've picked between (a)/(b)/(c) and decided how the scanner should treat an invoker interface's
@JsModule; those two are the only real forks, the rest follows.[-]Allow @JsInvoker to target a @JsModule[/-][+]Allow @JsDefinition to target a @JsModule[/+]mcollovati commentedon Nov 24, 2026
I checked the plan above against the current
main. #25749 and #25799 are merged (@JsDefinition,JsInvokers/JsSnippetsmarkers,Page.executeJs(Class)), so this can now be built directly onmain. Some points in the plan are out of date, and a few are not correct anymore. Here is an updated version.What changed since the plan
TaskGenerateJsDefinitions,vaadin-js-definitions.js,JsDefinitionProxyandJsDefinitionHotswapper.JsCall.functionId), not by interface name andname/argCount.JsInvokersorJsSnippets), andJsDefinitionProxy.checkDefinitionreturns it.Dynamic
import(): agreedShape 2 (a dynamic
import()inside theasyncfunction) is still the right choice. It needs no client change.Resolving the module path: simpler than the plan says
The two problems the plan lists do not exist anymore:
AbstractUpdateImports.resolveResourcedecides "jar or project" withclassFinder.getResource("META-INF/resources/frontend/..."), that is, on the class path, not on the copied files.toValidBrowserImportchecks the project frontend folder. Both only needOptions, and the generator has them. So it does not matter thatTaskGenerateJsDefinitionsruns beforeTaskCopyFrontendFiles.Optionsnow. It callsTaskGenerateJsDefinitions.updateJsDefinitions(Options, ...), not a static method without options.So: move these two methods out of
AbstractUpdateImportsinto a small shared resolver that takesOptions, and use it in both places. OnlyrenderDefinitionLinesandisInGeneratedFile, which are static today, need to get the resolver as a parameter.One more point: a dynamic
import()of a file that does not exist fails the Vite build. If the path cannot be resolved, the generator should leave the definition out and log an error, as it already does for a definition that failscheckDefinition. Otherwise one broken add-on breaks the build of every application that has it on the class path.The function id must include the module
JsCall.functionId(Method)hashes only the expression and the parameter count. Two module definitions with the same expression, for examplereturn this.init($0), would get the same id even if they target different modules. One of them would then call the wrong module. The hash must include the@JsModulevalue. Use the value as written in the annotation, not the resolved path: the server computes the id at runtime and cannot resolve paths there.With that, hotswap needs no new code.
DevLoopRedefinerusesfunctionIdas its fingerprint, andfrontendDependenciesalready reads@JsModulefrom every changed type.BundleValidationUtil.jsDefinitionsChangedhashes the generated file, so the module path is covered there as well.Binding a method to an export: (b), with #25812
I agree with (b): the module namespace is
this. My comment on #25812 suggests the shorthandreturn this.<name>(...). With (b), the same shorthand means "call the export with this name" for a module definition. So one rule works for both targets, and nothing new needs to be documented. The generated function only changesthis:With a module, the shorthand finally has a useful
thison the page side. This does not settle the open question on #25812, though: a plainJsInvokersdefinition used throughPage.executeJs(Class)still has no usefulthisfor the shorthand.How to mark a module definition: a marker interface, not only
@JsModuleThe plan uses the
@JsModuleannotation alone as the signal. I suggest a third marker interface instead, for two reasons:@JsModulealone would change what existing code means.@JsModuleis allowed on interfaces, and a natural pattern today puts a helper script on an element definition:If
@JsModulemade an interface a module target, this interface would silently become "page only,thisis the module", andElement.executeJswould start to fail for it.The type system can't see an annotation. The markers exist so that
Element.executeJs(<T extends JsInvokers>) andJsSnippets.of(<T extends JsSnippets>) refuse the wrong kind at compile time. A module target decided by an annotation can only fail at runtime.Proposal (all names are open):
Rules:
Kind.JsModuleInvokersdoes not extendJsInvokers.checkDefinitionreturns a newKindfor it, for exampleMODULE_CALLS. An interface that extends more than one marker is refused, asJsInvokers+JsSnippetsis today.@JsModulethat is notdevelopmentOnly, read withgetDeclaredAnnotationsByType.@JsModuleis@Inherited, but Java ignores@Inheritedon interfaces, so only the interface's own annotations count.developmentOnlymodules stay plain imports. Zero or two target modules is an error.JsInvokers: the same return types, and@JsWithExecutionContextstill allowed. Onlythisis different: it is the module namespace.checkMethodsand the proxy can reuse theCALLSpath.functionIdhash uses that interface's@JsModulevalue.@JsExpressionor the shorthand, runs with the module asthis, and the interface can not be passed toElement.executeJs. This follows the existing rule that one interface can not declare both calls and snippets: one interface has one meaning ofthis. JavaScript that needs the element asthisgoes into a separateJsInvokersinterface. A module definition can still work with an element: pass the element as an argument (initLazy(grid.getElement())), or use@JsExpression("return this.initLazy.call($0)")to make it thethisof the export.Pagemethod, for examplePage.executeModuleJs(Class<T extends JsModuleInvokers>). It can't be an overload ofexecuteJs, becauseexecuteJs(Class<T extends JsInvokers>)andexecuteJs(Class<T extends JsModuleInvokers>)have the same erasure. With a separate method,Element.executeJsandElementJsInitializerRegistrationrefuse a module definition at compile time, without a runtime check. No existing signature changes, which matters since 25.4 is already in beta.Other options I considered:
JsInvokers.Page.executeJswould work without changes, but the element entry points would have to refuse module definitions at runtime.Page.executeJs. It keeps one method name, but it changes the erased return type of a method that is already in a beta.Scanners: the module is loaded at startup in both modes, not only in dev
The plan says the production bytecode scanner would "generally not see" the interface. That is not correct for this use case.
FrontendClassVisitor.visitLdcInsnfollows class literals, sopage.executeModuleJs(GridConnectorJs.class)in a reachable class makes the interface reachable, and its@JsModuleis collected. The full scan in dev mode collects it too. So today both modes load the module at startup. They do not differ.The simplest first step is to keep that behavior. The
import()in the generated function then gets the module that is already loaded. Real lazy loading (leave module definitions out of the scanned imports) can be a separate follow-up. That follow-up has to change both scanners in the same way.Related: #27022. The generator takes every
@JsDefinitionon the class path. A module definition in an add-on the application does not use would add a dynamic import, and a chunk, to every application. This is one more reason to leave out a definition whose module cannot be resolved.Updated plan
JsModuleInvokersmarker, a newKind, and a newPagemethod for it. A module definition has exactly one non-developmentOnly@JsModuleof its own. Update "Which marker to extend" in the@JsDefinitionJavadoc.resolveResourceandtoValidBrowserImportinto a shared resolver that takesOptions. Use it inTaskGenerateJsDefinitions, including theupdateJsDefinitionspath.await import(...)plus.call(module, ...). If the module cannot be resolved, leave the definition out and log an error.@JsModulevalue to thefunctionIdhash.@JsExpressioncalls the export with the same name.checkDefinitionrefuses zero or two target modules, and an interface that extends two markerspage.executeModuleJs(MyModule.class).doSomething(element)runs an export@JsModulevalue changesDecisions needed:
PagemethodLegioth commentedon Nov 24, 2026
I guess this will still give a runtime exception when trying to use the interface?
I think this was implied by some other parts of the analysis but spelling it out here just to be explicit. An eligible method without an annotation is always interpreted as having a
this-referencing@JsExpression.Element.executeJsshould refuse an interface that is bound to a module so that there won't ever be two differentthiscandidates whereasPage.executeJsshould refuse one that isn't bound to a module if the interface has any method without@JsExpression.Edit: Fixed mixed up class names
Legioth commentedon Nov 24, 2026
I also started thinking of a slightly different shape. I think it's a new feature but mentioning here so that someone else might spot any reason for why both features need to be considered together.
The feature would be a way of injecting a module into an invoker bound to an element. This enables importing one or even several modules into an invoker that is used through
Element.executeJs. This requires defining an explicit name for the imported module.A
JsModuleInvokerscould then be seen as a shorthand that infersas = "this"for its only unqualified@JsModule, even though the underlying implementation might actually work slightly differently.mcollovati commentedon Nov 25, 2026
I guess
Element.executeJshere is just a typo and it should bePage.executeJsmcollovati commentedon Nov 25, 2026
The error will be only on the client and most likely with a poor message. Perhaps a better way would be to generate the function anyway but making it throw an error with a proper reason. In the production bundle the error message should not disclose any information about the application.
mcollovati commentedon Nov 25, 2026
About the
@JsModule(as=...)feauture. I think this should be designed together with this issue, even if it is implemented separately, becauseJsModuleInvokersthen becomes the caseas = "this", so the generator should have one mechanism for module bindings and the function id must hash every binding.3 remaining items
Legioth commentedon Nov 25, 2026
Can the server-side runtime know about whether the module could be resolved? If that's the case, then the proxy invocation handler could throw an helpful exception?
mcollovati commentedon Nov 25, 2026
Yes, if the build writes it down. The generator already writes the function ids next to the generated file, the build copies them into the bundle stats, and #27078 reads them on the server at runtime. The build can add the ids whose module could not be resolved, with the module path, and the invocation handler then throws a helpful exception when one of those methods is called. The check is per method, because the methods of one interface can depend on different modules.
Legioth commentedon Nov 25, 2026
How? Isn't it the same module for all methods in the interface? And with the
asaddition, I guess we'd inject all named modules into all expressions without inspecting which expression actually reads which parameters?mcollovati commentedon Nov 25, 2026
Right, all methods of an interface get the same modules, and all named modules are injected into every expression.
The only way to get different modules is inheritance, since an inherited method keeps the modules of the interface that declares it. That is the only reason to check when a method is called rather than when the proxy is created.
@JsDefinitionImportfor imports in JavaScript definitions #27423JsModuleInvokersandPage.executeModuleJsto call a module's exports from the page #27425mcollovati commentedon Nov 26, 2026
Updated plan after the latest discussion.
Imports. A new annotation,
@JsDefinitionImport, gives the expressions of a definition names from a module.@JsModulekeeps one meaning: load this JS.@JsDefinitionImport(from = "./my.js", defaultExport = "a", namespace = "b", exports = {"c", "d"})maps toimport a, { c, d }, * as b from "./my.js". Each attribute is optional and they can be combined, because the generated code callsimport()once and readsm.default,mandm.cfrom the result. The import is loaded on the first call. The element staysthis.Module definition.
JsModuleInvokers(does not extendJsInvokers) withPage.executeModuleJs. It needs exactly one@JsDefinitionImportwith no names, and that module isthis:JsModuleInvokersis the only compile-time split between element and page:Element.executeJsrefuses it, and it gives shorthand methods a meaning on the page.Rules.
@JsModuleon any definition is only a side-effect import, loaded eagerly.@JsDefinitionImportwith no names: bindsthison aJsModuleInvokers; an error on aJsInvokers(use@JsModule); refused onJsSnippets, like every import.defaultExport, notexports = "default"), and must not collide, within one annotation or across the imports of the interface that declares the method.import().@JsDefinitionImporton a class that is not a definition is an error.import { foo as bar }):namespacecovers conflicts, and it can be added later.Sub-issues.
@JsDefinitionImportfor imports in JavaScript definitions #27423@JsDefinitionImportfor element definitions.@JsDefinitionImportfor imports in JavaScript definitions #27423 and feat: log error for JavaScript definitions missing from bundle #27078).JsModuleInvokersandPage.executeModuleJsto call a module's exports from the page #27425JsModuleInvokersandPage.executeModuleJs(waits for Call instance method for @JsDefinition methods without a @JsExpression annotation #25812 and Add@JsDefinitionImportfor imports in JavaScript definitions #27423).Still open.
@JsModule: revisit when@JsDefinitiongets code splitting in general.mcollovati commentedon Nov 28, 2026
I tested
@JsDefinitionImportwith the Grid connector, and it looks like there is a gap in the plan. WithinitConnectormoved to an importedinitLazy, 29 of 66 tests in 10 Grid IT classes fail. All of them pass without the import.The problem is that the generated function always runs
await import(...)first, even when@JsModulehas already loaded the module. So an imported call runs after the calls that follow it in the same round trip. Grid needsinitLazyto run first, because the calls right after it usethis.$connector: header renderers, sorters and data. Those calls throw or do nothing, so grids show no rows and no sorters. ComboBox, DatePicker, TimePicker, VirtualList, MenuBar, ContextMenu and Map use the same pattern.One option to fix this is to load the imports of a
JsModuleInvokerswith the route, like a lazy@JsModule. The build puts the module into the chunk of every route that reaches the definition, and the chunk registers it. The generated function then reads the module withoutawait. The client already waits for a component's chunk before it runs the invocations of the same message, so the call runs in order and no client change is needed. I updated #27425 with this scope. Named imports on aJsInvokersstay loaded on the first call, so theGridConnectorJsexample in the@JsDefinitionImportJavadoc needs to change too.@JsDefinitionImportmodule or an import on a class #27554feat: report JavaScript definition imports that can not be resolved (v…
feat: report JavaScript definition imports that can not be resolved (#…