Repository navigation
feat: load JsModuleInvokers modules with the views that use them - #27493
Conversation
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.
…kers-route-loading
Type of change
How to test
API changesNo 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) |
Bundle sizeCompared with the base commit 0972b2e.
Size by module, before minification
The production bundle of |
Test Results 1 655 files 1 746 suites 1h 44m 37s ⏱️ Results for commit 3a42700. ♻️ This comment has been updated with latest results. |
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.
|
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 ( 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);
}
The same happens in production and in development mode. 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 Other results (all as expected)
Reproducer: https://github.com/mcollovati/skeleton-starter-flow-spring/tree/repro/js-definition-reachability-fallbacks (profile |
…kers-route-loading
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.
|
@mcollovati Thanks for the thorough test run. Both are fixed:
I also merged the latest commit of #27492 into this branch. |
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.
|
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):
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.
|
@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.
|
@mcollovati Thanks, all three are done.
|
vaadin-review-bot
left a comment
There was a problem hiding this comment.
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)); |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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)); |
There was a problem hiding this comment.
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 withimport, so it is parsed- it has no
', so both indices are-1andsubstringclamps 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
There was a problem hiding this comment.
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"); |
There was a problem hiding this comment.
🧪 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
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
📝 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
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
✅ 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.
|
|
Retested on 3a42700, which includes #27568 from
Without Reproducer: https://github.com/mcollovati/skeleton-starter-flow-spring/tree/repro/js-definition-reachability-fallbacks (README section "Module definitions"). |
|
Documentation Bot: No documentation pull request opened for this change. This pull request changes a real, user-facing behavior ( However, the public API this touches — 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.
|
) (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>



Fixes #27425, Depends on #27492
behavior deviation · flow-build-tools · apps and components that set up a connector through
JsModuleInvokersand call it in the same round tripBackground — 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.executeModuleJsnow 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:
Element.executeJscall 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 asPage.executeJstoday. The Javadoc says so.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.
groupByChunkto the frontend scanner. It uses the same reachability as@JsModuleto tell which chunks reach a class.JsModuleInvokersdefinition and register them inwindow.Vaadin.Flow.jsDefinitionModules, keyed by the resolved import path..mjs,.js,.mts,.ts,.jsx,.tsx,.json), or as a folder's index file. A subpath of an installed package whose package.json has anexportsfield 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../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.JsInvokersdefinitions are not changed. They still load on the first call.JsModuleInvokers,@JsDefinitionandPage.executeModuleJs.AbstractUpdateImportsTestbuilds its options through a helper, so a test can use the same class finder for the options and the scanner.Working on behalf of @mcollovati