Skip to content

feat: load JsModuleInvokers modules with the views that use them - #27493

Merged
mcollovati merged 47 commits into
mainfrom
feature/js-module-invokers-route-loading
Dec 1, 2026
Merged

mcollovati merged 47 commits into
mainfrom
feature/js-module-invokers-route-loading

Conversation

@totally-not-ai

@totally-not-ai totally-not-ai Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #27425, Depends on #27492

behavior deviation · flow-build-tools · apps and components that set up a connector through JsModuleInvokers and call it in the same round trip

Background — call order. The client runs the calls of a message one after the other without awaiting them. A call that waits for import() therefore runs its JavaScript after the calls that follow it.

A call through Page.executeModuleJs now runs before the calls made after it in the same round trip. The build loads their modules with the views that use them, the same way as @JsModule, so a call does not wait. A call made where no shown view loaded the module still works, but runs late once, and logs a warning in the browser. In production the warning says no view shown so far loaded the module, or that the build could not find the path, for example one that only an alias resolves. In development it says a restart registers it after a hotswap, or that the build could not find or check the path, such as one reached through an alias. A missing ./ file never gets there: it stops the build (#27568).

Risks:

  • ⚠️ Limit: an Element.executeJs call made before a module call in the same round trip still runs after it. Element calls are queued when the response is written, and page calls are queued when they are made, the same as Page.executeJs today. The Javadoc says so.
  • ⚠️ Behaviour change: the modules of a module definition now load with the route's chunk, or at startup for an eager route and in development mode, not on the first call. In development mode and in a production build that does not optimize the bundle, the build does not tell views apart, so the modules of every module definition on the class path load at startup, also those no view uses, and their top-level code runs then.
  • ⚠️ The fallback warning names the module path, not the Java definition, because production bundles never name Java classes. The issue asked to name the definition.
  • ⚠️ Known limit, checked by hand in development mode: a hotswap that only redefines classes does not update the registrations. Calls still work, but the first call on each page runs late and logs a warning until a restart. A restart, or an edit of the module file, registers the module again.
  • ⏱️ Every generated definitions file gets two more header lines. A chunk gets one import per module of the definitions it reaches.
  • ✅ No API, serialization, threading or security concerns.

Context. The bundle check needs no new rule for when to rebuild. The function ids hash the imports, so a definition or import change already forces a rebuild, and the rebuild writes the registrations. The check, and the Vite plugin that writes the imports of a bundle into its stats, now read imports in either quote and undo the escapes of double-quoted ones, since the registrations of definition modules are written that way. The check also finds a project module imported without its extension the way Vite does.

  • Added groupByChunk to the frontend scanner. It uses the same reachability as @JsModule to tell which chunks reach a class.
  • The imports file and the route chunks import the modules of each reached JsModuleInvokers definition and register them in window.Vaadin.Flow.jsDefinitionModules, keyed by the resolved import path.
    • The build finds a module the way Vite does: by its path as written, with one of Vite's default extensions (.mjs, .js, .mts, .ts, .jsx, .tsx, .json), or as a folder's index file. A subpath of an installed package whose package.json has an exports field is found through that field alone, as the bundler resolves it. A ./ file from a jar must be named exactly as it is, as the generator requires.
    • A module the build can not find gets no static import, because that import would fail the Vite build. A ./ file of the project or a jar that the build can not find stops the build (fix: fail the build for a missing @JsDefinitionImport module or one on a class #27568). The chunk writer checks such a file the same way the generator does, so the two agree. Any other path the build can not find, such as one reached through a Vite alias, is loaded by the call.
  • The generated function takes its modules from that registry without awaiting. Only when a module is missing does it load the missing ones in parallel, warn once per module, and register them for later calls.
  • Named imports of JsInvokers definitions are not changed. They still load on the first call.
  • Documented the loading, call order, fallback and limits in JsModuleInvokers, @JsDefinition and Page.executeModuleJs.
  • AbstractUpdateImportsTest builds its options through a helper, so a test can use the same class finder for the options and the scanner.
  • Strict-CSP production ITs check call order when the view is shown and later. They also check a call to a module that only another view registers, which loads it once, warns once, and runs later calls in order. They fail when the chunk registration is turned off.

Working on behalf of @mcollovati

A JavaScript definition that extends JsModuleInvokers calls what one
module exports, with that module as `this`. The module is named by the
one @JsDefinitionImport of the interface that imports no names; other
imports with names work as on a JsInvokers definition. A method without
@JsExpression calls the export of the same name.

The marker does not extend JsInvokers, so Element.executeJs refuses a
module definition at compile time. checkDefinition refuses an interface
that extends more than one marker, and a module definition whose
declaring interfaces import zero or several modules without names.

The import of `this` is part of the hashed imports, so the same
JavaScript run on an element stays another function.

Existing tests that asserted the wording of the "neither" and "both"
marker errors now assert the wording that also covers the third marker.

Part of #27425
A call through Page.executeModuleJs used to await import() of its
modules, so its JavaScript ran after the calls that followed it in the
same message. Connector code, which an init call sets up for the calls
after it, failed that way.

The build now puts the modules of every JsModuleInvokers definition into
the chunk of each route that reaches it, or into the eager imports for
an eager route and in development mode. Each chunk registers the module
namespaces by the path the generated files import them by. The generated
function takes its modules from that registry without awaiting, so it
runs in the order of the calls. A module that is not registered, such
as for a call no shown view reaches, is still imported on the call, with
a warning in the browser once per module. A module the build can not
find gets no static import, which would fail the build.

The scanner gets groupByChunk to tell which chunks reach a class, with
the same reachability as @jsmodule.

AbstractUpdateImportsTest builds its options through a helper so a test
can find and scan its own classes with the same finder.

Fixes #27425
A module that no shown view registered was loaded on every call, so
every call of it ran late, not only the first. The loader now puts what
it loads into the registry. When a module is missing, the function loads
the missing ones in parallel again, as before the registry.

Tests cover an eager route, the imports of a JsInvokers definition that
stay out of the chunks, the helpers the functions rely on, and a call of
a module that only another view registers.
Also asserts the message of creating invokers from a module definition
rather than only the marker it names.
@totally-not-ai

Copy link
Copy Markdown
Contributor Author

Type of change

  • Feature

How to test

  1. Open flow-tests/test-csp-strict/src/main/java/com/vaadin/flow/test/cspstrict/js/DeclaredJsModuleView.java (route declared-js-module) in a production build.
  2. Check document.body.dataset.status, then click Connect.
  3. The body reads connected on attach, and the span reads connected later. Both are set by a call that relies on the connector the previous call in the same response set up.
  4. Click Connect unregistered twice. The first click shows initialized and logs one warning in the console. The second click shows connected.
API changes

No public API changes. The scanner interface, which is internal, gets a default method:

// com.vaadin.flow.server.frontend.scanner.FrontendDependenciesScanner — Added
default Map<ChunkInfo, Set<String>> groupByChunk(Collection<String> classNames)

@github-actions

github-actions Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Bundle size

Compared with the base commit 0972b2e.

File Minified Change Brotli Change
sw.js 20,674 B no change 6,141 B no change
VAADIN/build/ApplicationConnection.js 125,051 B no change 32,276 B no change
VAADIN/build/FlowBootstrap.js 3,191 B no change 1,027 B no change
VAADIN/build/FlowClient.js 10,723 B no change 3,503 B no change
VAADIN/build/frontend.js 409,419 B $\color{red}\textbf{+591 B}$ (+0.1%) 111,754 B $\color{red}\textbf{+271 B}$ (+0.2%)
VAADIN/build/generated-flow-imports.js 2,945 B no change 1,100 B no change
VAADIN/build/indexhtml.js 47 B no change 51 B no change
VAADIN/build/rolldown-runtime.js 870 B no change 437 B no change
Total 572,920 B $\color{red}\textbf{+591 B}$ (+0.1%) 156,289 B $\color{red}\textbf{+271 B}$ (+0.2%)
Size by module, before minification
Module Change
src/main/frontend/generated/vaadin-js-definitions.js +702 B

The production bundle of test-prod-bundle, an application with no code of its own: the Flow client, the files Flow generates and the npm packages it brings in. Brotli is what the build precompresses the files with.

@github-actions

github-actions Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Test Results

 1 655 files   1 746 suites   1h 44m 37s ⏱️
14 054 tests 13 982 ✅ 72 💤 0 ❌
14 480 runs  14 408 ✅ 72 💤 0 ❌

Results for commit 3a42700.

♻️ This comment has been updated with latest results.

mcollovati added a commit to mcollovati/skeleton-starter-flow-spring that referenced this pull request Nov 28, 2026
JsModuleInvokers and Page.executeModuleJs, in the profiles
module-invokers (app and add-on, own source folders) and module-missing.
Results on vaadin/flow#27493 73da7a8d1f: production 27/28, development
23/28 (4 skipped), M13 (path without extension never registered) fails.
Control run on 8a7fe1f5a0 (no route loading): 15/28 fail.
@mcollovati

Copy link
Copy Markdown
Contributor

I tested this PR (73da7a8) in a reproducer: 28 browser tests in strict-CSP production mode, and the same tests in development mode. The calls run in order for a module of the project, a module in an add-on jar, an npm package (lit), a query path, an inherited definition, router navigation, and a component attached in a click. Two findings:

1. A path without the file extension is never registered

@JsDefinition
@JsDefinitionImport(from = "./app-module-noext")   // the file is app-module-noext.js
public interface NoExtensionModuleJs extends JsModuleInvokers {
    void initLazy(Element element);
}

collectJsDefinitionModules checks importedFileExists(stripQuery(from)). No file is named app-module-noext, so the chunk gets no registration, and the only log is at debug level. Vite resolves the import() in the generated function, so the call works. But every call on a new page runs after the calls that follow it, and the browser logs:

Loading Frontend/app-module-noext for a call, since no view shown so far loaded it. That call runs after the calls that follow it.

The same happens in production and in development mode. @JsDefinitionImport accepts such a path, and Vite resolves it. This is the risk from the triage: the chunk writer and the generated function must resolve the path the same way. I think the existence check should resolve the path the way Vite does (try the extensions), or use the same resolver as the generated function.

2. An element call made before a module call runs after it

box.getElement().executeJs(OrderJs.class).record("before");
page.executeModuleJs(AppModuleJs.class).initLazy(box.getElement());
box.getElement().executeJs(OrderJs.class).record("after");

The result is init before:ready after:ready. Element.executeJs queues its call when the response is written (beforeClientResponse), and Page.executeModuleJs queues it at once. Page.executeJs works the same way today, so this is not new. But the Javadoc of JsModuleInvokers says that the JavaScript "runs in the order of the calls". This is not true when an element call comes first. For example, code that resets an element and then calls initLazy loses the work of initLazy. I suggest that the Javadoc says it: the order is kept for calls that come after the module call, but an element call made before it in the same round trip runs after it.

Other results (all as expected)

  • The same tests on feat: add JsModuleInvokers and Page.executeModuleJs #27492 alone (8a7fe1f), which does not load the modules with the view: 15 of 28 fail. So the tests really check the new loading.
  • A definition that only view B uses, called while view A is shown: the first call loads the module itself, runs late and logs one warning. The warning names the file path and no Java class. The next calls run in order. When view B was shown before, there is no warning.
  • A module file runs its code only once, also when one definition names it in both @JsModule and @JsDefinitionImport, and when two views use it.
  • Definitions that break the new rules are left out: no import without names, two imports without names, two marker interfaces, and a sub-interface that adds a method without an import. The build logs an ERROR for each, and a call throws on the server.
  • A module that does not exist: the chunk has no static import, but Vite still stops on the fallback import() in vaadin-js-definitions.js. Report JavaScript definition imports that can not be resolved on the server #27424 (feat: report JavaScript definition imports that can not be resolved #27491) should fix this. I did not test the two PRs together.
  • Not tested: hotswap of the module file, and a dev bundle rebuild when a definition is added to a running application.

Reproducer: https://github.com/mcollovati/skeleton-starter-flow-spring/tree/repro/js-definition-reachability-fallbacks (profile module-invokers, section "Module definitions" in the README).

The build looked for the module by the path as declared, so a path
such as ./connector, which the bundler resolves to connector.js or
connector.ts, was never registered and every call of it ran late. It
now also tries the extensions the bundler tries.

The Javadoc of JsModuleInvokers says that an element call made before
a module call in the same round trip still runs after it.
The bundler also resolves a path to the index file of a folder, with
any of the extensions it tries, so the build looks for that too.
@totally-not-ai

Copy link
Copy Markdown
Contributor Author

@mcollovati Thanks for the thorough test run. Both are fixed:

  1. Path without an extension: the build now looks for a module the way Vite resolves it. It tries the path as written, then each of Vite's default extensions (.mjs, .js, .mts, .ts, .jsx, .tsx, .json), then a folder's index file with those extensions. So ./app-module-noext is registered in the chunk under the same key the generated function looks up. The chunk test now covers a .ts file imported without its extension and a folder with an index.ts.
  2. Element call made before a module call: the JsModuleInvokers Javadoc no longer says the calls run in call order. It now says a module call runs before the calls made after it in the same round trip, and that an Element.executeJs call made before it still runs after it, because element calls are queued when the response is written. It also suggests doing the reset in an earlier round trip or through the page. The PR description lists this as a limit.

I also merged the latest commit of #27492 into this branch.

mcollovati added a commit to mcollovati/skeleton-starter-flow-spring that referenced this pull request Nov 28, 2026
J1-J4: change the module of a JsModuleInvokers definition, change only
an expression, edit the module file, add a new module definition.
Results on vaadin/flow#27493 73da7a8d1f with hot deploy and with the dev
bundle: a pure redefine keeps the old registration, so the first call
on each page runs late and warns until a restart.
@mcollovati

Copy link
Copy Markdown
Contributor

The description says that development mode, the dev bundle and hotswap of the module file are not covered by an IT. I tested them by hand with the dev loop (73da7a8, with hot deploy and with the dev bundle):

  • After a restart, after a plain apply, and after an edit of the module file, the new module is registered and the calls run in order. The edit reloads the page with hot deploy and restarts with the dev bundle.
  • A pure redefine (apply --no-restart, which is what a hotswap from an IDE does) of a changed module, or of a new module definition, does not update the registration. The call works, but the first call on each page runs late and logs the warning, until a restart. This is one of the known limits of the issue, so no change is needed.

A small optional point: after such a hotswap, the warning says "since no view shown so far loaded it", but the view was shown. In development mode it could say that a restart registers the module.

Reproducer: https://github.com/mcollovati/skeleton-starter-flow-spring/tree/repro/js-definition-hierarchy-hotswap (cases J1-J4, section "Module definitions" in the README).

Development registers every module when the application starts, so a
module is only missing after a class changed while it runs. The warning
there says that a restart registers it, instead of that no view loaded
it.
@totally-not-ai

Copy link
Copy Markdown
Contributor Author

@mcollovati Thanks for checking development mode and hotswap. I took the optional point: the warning now depends on the mode. Development registers every module it finds when the application starts, so a missing one means one of two things. Either a class changed while the application runs, and a restart registers the module, or the build did not find the file. The development warning says exactly that. The production warning still says no view shown so far loaded the module. A new unit test checks each wording. The PR description now lists the hotswap limit you confirmed instead of calling development mode untested.

The combination failed on the import checks instead: first on the
import that binds this, then, once it was removed, on the missing one.
Refuse the annotation itself before those checks. Also document in
JsModuleInvokers that this is the module namespace object.
Say when to use it instead of executeJs(Class) and how the two differ,
list what the interface needs, and say in the @throws of the definition
methods which return types are allowed instead of 'can not be
answered'.
Also say in one place which builds load every module definition's
modules at startup.
@totally-not-ai

totally-not-ai Bot commented Dec 1, 2026

Copy link
Copy Markdown
Contributor Author

@mcollovati Thanks, all three are done.

  1. The chunk lines now write the path with the same quote() as the generated functions, for the import and for the registry key. So a path with ' no longer breaks the chunk, and one with \ gives the same key on both sides. A new case imports ./it's-connector.js and checks both lines. @JsModule imports are unchanged.
  2. Whether a module exists is now checked once per module, not once per chunk.
  3. @JsDefinition now says the calls "usually run before the calls that follow them; see JsModuleInvokers for the exceptions".

@vaadin-review-bot vaadin-review-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the changes — left 1 comment.

Finding
⚠️ The new registration import lines use double quotes, which makes the bundle validation import parser throw.

String variable = "$jsDefinitionModule_" + i;
// Quoted as the generated functions quote the key they look up
String path = TaskGenerateJsDefinitions.quote(paths.get(i));
lines.add(String.format("import * as %s from %s;", variable, path));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ The new registration import lines use double quotes, which makes the bundle validation import parser throw.

BundleValidationUtil.frontendImportsFound runs GenerateMainImports and, for every line starting with import, extracts the path between the first and last ':

.filter(line -> line.startsWith("import"))
.map(line -> line.substring(line.indexOf('\'') + 1, line.lastIndexOf('\'')))

Until now every generated import line was single-quoted (IMPORT_TEMPLATE, IMPORT_INJECT, CSS_IMPORT, …). import * as $jsDefinitionModule_0 from "Frontend/connector.js"; has no ', so both indices are -1 and substring(0, -1) throws StringIndexOutOfBoundsException.

This is on the normal NodeTasks path for both PRODUCTION_PRECOMPILED_BUNDLE and DEVELOPMENT_BUNDLE, so any application with a JsModuleInvokers definition whose module the build finds breaks as soon as a bundle exists to validate against — the first build exits early via jsDefinitionsChanged, the second reaches the parser. A clean-build CI run (like the strict-CSP ITs) never hits it.

Switching to single quotes is not enough on its own, since quote exists to escape paths like Frontend/it's-connector.js; the parser needs to handle both quote styles.

AbstractUpdateImports.java:316 · correctness

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed. The bundle check now takes the first string of an import line in either quote. A double-quoted one is read with unquote, which sits next to quote in TaskGenerateJsDefinitions and undoes exactly the escapes it writes. A single-quoted one is taken as written, as before, so a backslash in a @JsModule path stays as it is. New tests: the parser with both quote styles, escaped quotes, backslashes and line breaks, and a bundle check in both modes with a JsModuleInvokers definition whose module is in the bundle. That check fails with the old parser and passes now.

The imports of JavaScript definition modules are now written as escaped
double-quoted strings, which the bundle check took apart between single
quotes and so failed on. Read the first string of a line in either
quote and undo its escapes.
Keep the reverse next to quote() in TaskGenerateJsDefinitions, leave
single-quoted imports as they are written, and test the bundle check
with the module of a module definition.

@vaadin-review-bot vaadin-review-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the changes — left 3 comments.

Finding
⚠️ The double-quoted registration imports are invisible to the Vite stats writer, so the bundle check will report them missing on every run.
🧪 The new bundle-check test hand-writes a stats entry that a real build never produces.
📝 The Javadoc claims chunk loading times out via maxMessageSuspendTimeout, which is not what that setting does.

String variable = "$jsDefinitionModule_" + i;
// Quoted as the generated functions quote the key they look up
String path = TaskGenerateJsDefinitions.quote(paths.get(i));
lines.add(String.format("import * as %s from %s;", variable, path));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ The double-quoted registration imports are invisible to the Vite stats writer, so the bundle check will report them missing on every run.

BundleValidationUtil.findImportedPath was taught to read both quote styles, but the other half of the round trip was not. parseImports in flow-server/src/main/resources/vite.generated.ts (lines 230-232) still extracts a path with line.substring(line.indexOf("'") + 1, line.lastIndexOf("'")):

  • import * as $jsDefinitionModule_0 from "Frontend/connector.js"; starts with import , so it is parsed
  • it has no ', so both indices are -1 and substring clamps to (0, 0) → ""

So bundleImports in stats.json gets an empty string instead of Frontend/connector.js, while frontendImportsFound now correctly extracts Frontend/connector.js and finds it missing. needsBuild then returns true forever: a dev bundle is rebuilt on every start, and a precompiled production bundle is rejected on every build, for any application with a JsModuleInvokers definition whose module the build finds.

The convention "Update both sides in the same PR when a change touches the client-server protocol" applies to this generator/parser pair as well.

AbstractUpdateImports.java:316 · correctness

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed. parseImports in vite.generated.ts now reads a double-quoted import as the string the build wrote: it takes the literal and undoes exactly the escapes that TaskGenerateJsDefinitions.quote writes (\\, \", \n, \r), the same as unquote on the Java side. Single-quoted imports are read as before on both sides, up to the last '. I ran both parsers on the same lines, including paths with ', ", \ and a line break, and they give the same paths.

The bundle check had a second reason to always rebuild here: a project module imported without its extension, such as ./connector-helper for connector-helper.ts, was reported as "No file found". It is now found the way Vite finds it, as in the chunk writer.


ObjectNode stats = getBasicStats();
((ArrayNode) stats.get(BUNDLE_IMPORTS))
.add("Frontend/bundled-connector.js");

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧪 The new bundle-check test hand-writes a stats entry that a real build never produces.

Frontend/bundled-connector.js is put into bundleImports directly, which is what the test needs to pass but not what vite.generated.ts writes for a double-quoted import line. That is why the parser mismatch above is invisible here, and no integration test covers it either: JsModuleInvokers appears only in test-csp-strict, which builds clean.

BundleValidationTest.java:1042 · tests

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, the entry in that test is now what the fixed stats writer produces for the double-quoted line, and the test also covers a module imported without its extension, which failed the check before. The stats writer itself is still only covered by building. A test that builds a bundle and then checks that a second build reuses it would pin the whole round trip. The express-build test modules are the place for that, and none of them has a JsModuleInvokers definition yet. I'd leave that to a follow-up unless you want it in this PR.

* {@link IllegalStateException}; see {@link Page#executeModuleJs(Class)}.</li>
* <li>The browser waits for the chunks it needs before it runs the calls of a
* response, for as long as it waits for a {@link JsModule}. If a chunk takes
* longer than the <code>maxMessageSuspendTimeout</code> setting, the calls run

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📝 The Javadoc claims chunk loading times out via maxMessageSuspendTimeout, which is not what that setting does.

The calls of a response are deferred through runWhenEagerDependenciesLoaded, which counts in-flight eager dependencies and has no timeout at all — a chunk that never resolves holds those calls indefinitely. maxMessageSuspendTimeout is used for resending a request and for force-handling a later, enqueued message; it never makes the calls of the waiting response run without their chunk.

The first sentence of that bullet (the browser waits for the chunk, as it does for a @JsModule) is correct; it is the timeout sentence that should go or be rewritten.

JsModuleInvokers.java:116 · documentation

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Corrected. The bullet now says the browser waits for the chunk, as it does for a @JsModule, and that if the chunk takes longer than maxMessageSuspendTimeout, a newer message from the server can be handled before the calls of the response that waits. That is what #forceMessageHandling does when it clears the response locks.

The Vite stats writer took an import path apart between single quotes,
so the double-quoted imports of JavaScript definition modules came out
empty and the bundle check reported them missing on every run. Read a
double-quoted path as the escaped string it is, the same way the bundle
check does. Also correct what maxMessageSuspendTimeout does for a
response that waits for a chunk.
Undo in the stats writer only the escapes that the build writes, as the
bundle check does, read single-quoted imports up to the last quote on
both sides as before, and find a project module imported without its
extension the way the bundler does, rather than asking for a rebuild.

@vaadin-review-bot vaadin-review-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Nothing to flag — the changes look good.

Since #27568, a missing ./ module of a JavaScript definition stops the
build rather than leaving its methods out, so say that in the
JsModuleInvokers Javadoc and the comments of the chunk writer and the
unregistered-module warning.
Compare it under the name of the file it resolves to, as the bundle
hashes it, and count a file without a hash as changed, as for any
import, so an edit to it makes the bundle be rebuilt. Also update a test
comment for missing modules stopping the build.
@sonarqubecloud

sonarqubecloud Bot commented Dec 1, 2026

Copy link
Copy Markdown

mcollovati added a commit to mcollovati/skeleton-starter-flow-spring that referenced this pull request Dec 1, 2026
@mcollovati

Copy link
Copy Markdown
Contributor

Retested on 3a42700, which includes #27568 from main. All the cases of the reproducer pass, in production and in development mode:

  • Module calls run in the order they are made, also for a module imported without its file extension, which failed on the previous retest.
  • A module definition whose module does not exist now stops the build before Vite, with a message that names the interface, the method and the module.
  • All the cases for missing modules and for @JsDefinitionImport on a class pass.

Without optimizeBundle, every module is registered when the application starts. Calls still run in order. Only the checks that expect a module to load with its view differ, as expected.

Reproducer: https://github.com/mcollovati/skeleton-starter-flow-spring/tree/repro/js-definition-reachability-fallbacks (README section "Module definitions").

@mcollovati
mcollovati added this pull request to the merge queue Dec 1, 2026
Merged via the queue into main with commit f61c209 Dec 1, 2026
57 checks passed
@mcollovati
mcollovati deleted the feature/js-module-invokers-route-loading branch December 1, 2026 13:53
@github-actions

github-actions Bot commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Documentation Bot: No documentation pull request opened for this change.

This pull request changes a real, user-facing behavior (BEHAVIOR_CHANGE): modules imported by a JsModuleInvokers interface now load with the views that reach it, like a @JsModule, instead of on the first call — so a call through Page.executeModuleJs(Class) now runs before the calls made after it in the same round trip, not after. That's worth knowing for anyone writing connector-style code.

However, the public API this touches — JsModuleInvokers and Page.executeModuleJs(Class) — was only introduced by the dependency #27492, and its documentation is still an open, unmerged draft at vaadin/docs#6805. Nothing about this feature exists on vaadin/docs main yet, so there's no existing section on main for this run to revise, and opening a second, independent pull request from main would duplicate vaadin/docs#6805's draft rather than extend it.

The loading-timing and call-order details this change adds belong inside vaadin/docs#6805's "Calling What a JavaScript Module Exports" section, before that pull request merges, not in a separate pull request. Nothing was opened or pushed by this run.

Generated by Documentation Bot for #27493 · agent · 103.3 AIC · ⊞ 11.7K · ◷

mcollovati pushed a commit that referenced this pull request Dec 1, 2026
) (CP: 25.4)

Fixes #27425, Depends on #27492

**behavior deviation** · flow-build-tools · apps and components that set
up a connector through `JsModuleInvokers` and call it in the same round
trip

**Background — call order.** The client runs the calls of a message one
after the other without awaiting them. A call that waits for `import()`
therefore runs its JavaScript after the calls that follow it.

A call through `Page.executeModuleJs` now runs before the calls made
after it in the same round trip. The build loads their modules with the
views that use them, the same way as `@JsModule`, so a call does not
wait. A call made where no shown view loaded the module still works, but
runs late once, and logs a warning in the browser. In production the
warning says no view shown so far loaded the module, or that the build
could not find the path, for example one that only an alias resolves. In
development it says a restart registers it after a hotswap, or that the
build could not find or check the path, such as one reached through an
alias. A missing `./` file never gets there: it stops the build
(#27568).

**Risks:**
- ⚠️ Limit: an `Element.executeJs` call made *before* a module call in
the same round trip still runs after it. Element calls are queued when
the response is written, and page calls are queued when they are made,
the same as `Page.executeJs` today. The Javadoc says so.
- ⚠️ Behaviour change: the modules of a module definition now load with
the route's chunk, or at startup for an eager route and in development
mode, not on the first call. In development mode and in a production
build that does not optimize the bundle, the build does not tell views
apart, so the modules of every module definition on the class path load
at startup, also those no view uses, and their top-level code runs then.
- ⚠️ The fallback warning names the module path, not the Java
definition, because production bundles never name Java classes. The
issue asked to name the definition.
- ⚠️ Known limit, checked by hand in development mode: a hotswap that
only redefines classes does not update the registrations. Calls still
work, but the first call on each page runs late and logs a warning until
a restart. A restart, or an edit of the module file, registers the
module again.
- ⏱️ Every generated definitions file gets two more header lines. A
chunk gets one import per module of the definitions it reaches.
- ✅ No API, serialization, threading or security concerns.

**Context.** The bundle check needs no new rule for when to rebuild. The
function ids hash the imports, so a definition or import change already
forces a rebuild, and the rebuild writes the registrations. The check,
and the Vite plugin that writes the imports of a bundle into its stats,
now read imports in either quote and undo the escapes of double-quoted
ones, since the registrations of definition modules are written that
way. The check also finds a project module imported without its
extension the way Vite does.

- Added `groupByChunk` to the frontend scanner. It uses the same
reachability as `@JsModule` to tell which chunks reach a class.
- The imports file and the route chunks import the modules of each
reached `JsModuleInvokers` definition and register them in
`window.Vaadin.Flow.jsDefinitionModules`, keyed by the resolved import
path.
- The build finds a module the way Vite does: by its path as written,
with one of Vite's default extensions (`.mjs`, `.js`, `.mts`, `.ts`,
`.jsx`, `.tsx`, `.json`), or as a folder's index file. A subpath of an
installed package whose package.json has an `exports` field is found
through that field alone, as the bundler resolves it. A `./` file from a
jar must be named exactly as it is, as the generator requires.
- A module the build can not find gets no static import, because that
import would fail the Vite build. A `./` file of the project or a jar
that the build can not find stops the build (#27568). The chunk writer
checks such a file the same way the generator does, so the two agree.
Any other path the build can not find, such as one reached through a
Vite alias, is loaded by the call.
- The generated function takes its modules from that registry without
awaiting. Only when a module is missing does it load the missing ones in
parallel, warn once per module, and register them for later calls.
- Named imports of `JsInvokers` definitions are not changed. They still
load on the first call.
- Documented the loading, call order, fallback and limits in
`JsModuleInvokers`, `@JsDefinition` and `Page.executeModuleJs`.
- `AbstractUpdateImportsTest` builds its options through a helper, so a
test can use the same class finder for the options and the scanner.
- Strict-CSP production ITs check call order when the view is shown and
later. They also check a call to a module that only another view
registers, which loads it once, warns once, and runs later calls in
order. They fail when the chunk registration is turned off.

Working on behalf of @mcollovati

---------

Co-authored-by: totally-not-ai[bot] <290682512+totally-not-ai[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add JsModuleInvokers and Page.executeModuleJs to call a module's exports from the page

3 participants