Skip to content

Allow @JsDefinition to target a @JsModule #25814

Done
5 of 5 issues completed
Done

Description

@Legioth

#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")
public interface MyJsModule {
  // Imports "doSomething" from the JS module and invokes that function
  public void doSomething(String someArg);
}

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.

Sub-issues

Sub-issues

5 of 5 Issues completed
Loading 5 sub-issues

Activity

  1. totally-not-ai commented on Sep 18, 2026

    @totally-not-ai
    Contributor

    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:

    1. 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.
    2. 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 static TaskGenerateJsInvokers.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.

  2. changed the title [-]Allow @JsInvoker to target a @JsModule[/-] [+]Allow @JsDefinition to target a @JsModule[/+] on Oct 26, 2026
  3. mcollovati commented on Nov 24, 2026

    @mcollovati
    Contributor

    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.

    Binding a method to an export: (b), with #25812

    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:

    window.Vaadin.Flow.jsDefinitions["<id>"] = async function ($0) {
      const module = await import('Frontend/myJsModule.js');
      return (async function ($0) { <expression> }).call(module, $0);
    };

    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:

    1. @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:

      @JsDefinition
      @JsModule("./my-helper.js") // loads window.Vaadin.Flow.myHelper
      public interface MyFieldJs extends JsInvokers {
          @JsExpression("window.Vaadin.Flow.myHelper.init(this)")
          void init();
      }

      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.

    2. 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.

    Proposal (all names are open):

    @JsDefinition
    @JsModule("./grid-connector.js")
    public interface GridConnectorJs extends JsModuleInvokers {
        void initLazy(Element grid); // shorthand from #25812: return this.initLazy($0)
    }
    
    page.executeModuleJs(GridConnectorJs.class).initLazy(grid.getElement());

    Rules:

    • 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

    1. 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.
    2. Move resolveResource and toValidBrowserImport into a shared resolver that takes Options. Use it in TaskGenerateJsDefinitions, including the updateJsDefinitions path.
    3. Generate await import(...) plus .call(module, ...). If the module cannot be resolved, leave the definition out and log an error.
    4. Add the @JsModule value to the functionId hash.
    5. Use the shorthand from Call instance method for @JsDefinition methods without a @JsExpression annotation #25812, so that a method without @JsExpression calls the export with the same name.
    6. Tests:
      • generator output for a module definition: import path for a project file, a jar file and an npm package
      • an unresolvable module leaves the definition out
      • two definitions with the same expression but different modules get different ids
      • checkDefinition refuses zero or two target modules, and an interface that extends two markers
      • a method inherited from another module definition runs against the module of the interface that declares it
      • an end-to-end IT where page.executeModuleJs(MyModule.class).doSomething(element) runs an export
      • the dev loop restarts when the @JsModule value changes

    Decisions needed:

    • the names of the marker and of the Page method
    • whether lazy loading is part of this issue or a follow-up
  4. Legioth commented on Nov 24, 2026

    @Legioth
    MemberAuthor

    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.

    Edit: Fixed mixed up class names

  5. Legioth commented on Nov 24, 2026

    @Legioth
    MemberAuthor

    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.

    @JsDefinition
    @JsModule(value = "./myElementHelpers", as = "helpers")
    public interface MyElementHelpers extends JsInvokers {
      @JsExpression("helpers.doSomethingWithElement(this)")
      void doSomething();
    }

    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.

  6. mcollovati commented on Nov 25, 2026

    @mcollovati
    Contributor

    whereas Element.executeJs should refuse one that isn't bound to a module if the interface has any method without @JsExpression.

    I guess Element.executeJs here is just a typo and it should be Page.executeJs

  7. mcollovati commented on Nov 25, 2026

    @mcollovati
    Contributor

    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 reason
    window.Vaadin.Flow.jsDefinitions["<id>"] = async function () {
      throw new Error("Module './myJsModule' of com.example.MyJsModule could not be resolved at build time");
    };
    
    // production bundle: no class name and no module path
    window.Vaadin.Flow.jsDefinitions["<id>"] = async function () {
      throw new Error("The module of this function could not be resolved at build time. See the build log.");
    };
  8. mcollovati commented on Nov 25, 2026

    @mcollovati
    Contributor

    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.

  9. 3 remaining items

  10. Legioth commented on Nov 25, 2026

    @Legioth
    MemberAuthor

    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?

  11. mcollovati commented on Nov 25, 2026

    @mcollovati
    Contributor

    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.

  12. Legioth commented on Nov 25, 2026

    @Legioth
    MemberAuthor

    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?

  13. mcollovati commented on Nov 25, 2026

    @mcollovati
    Contributor

    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.

  14. mcollovati commented on Nov 26, 2026

    @mcollovati
    Contributor

    Updated plan after the latest discussion.

    Imports. A new annotation, @JsDefinitionImport, gives the expressions of a definition names from a module. @JsModule keeps one meaning: load this JS.

    @JsDefinition
    @JsDefinitionImport(from = "./gridConnector.js", namespace = "connector")
    public interface GridConnectorJs extends JsInvokers {
        @JsExpression("connector.initLazy(this)")
        void initLazy();
    }

    @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:

    @JsDefinition
    @JsDefinitionImport(from = "./grid-connector.js")
    public interface GridConnectorJs extends JsModuleInvokers {
        void initLazy(Element grid); // means: return this.initLazy($0)
    }

    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.

    Sub-issues.

    1. Call instance method for @JsDefinition methods without a @JsExpression annotation #25812 Shorthand.
    2. Add @JsDefinitionImport for imports in JavaScript definitions #27423 @JsDefinitionImport for element definitions.
    3. Report JavaScript definition imports that can not be resolved on the server #27424 Unresolved modules (waits for Add @JsDefinitionImport for imports in JavaScript definitions #27423 and feat: log error for JavaScript definitions missing from bundle #27078).
    4. Add JsModuleInvokers and Page.executeModuleJs to call a module's exports from the page #27425 JsModuleInvokers and Page.executeModuleJs (waits for Call instance method for @JsDefinition methods without a @JsExpression annotation #25812 and Add @JsDefinitionImport for imports in JavaScript definitions #27423).

    Still open.

    • 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.
  15. mcollovati commented on Nov 28, 2026

    @mcollovati
    Contributor

    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.

  16. moved this from Maybe to Done / Pending Release in Vaadin Flow enhancements backlogon Dec 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions