Skip to content

Commit ede4f67

Browse files
authored
[flutter_tools] Include base href in web hot reload script paths (flutter#193678)
When the app has a `<base href>` (e.g. `/f/`), the dev server already serves everything under that prefix and the initial load resolves all module scripts relative to it. But `reloaded_sources.json`, which drives hot reload and hot restart, lists modules as `/web_entrypoint.dart.lib.js`, `/packages/<app>/main.dart.lib.js`, etc. The browser then requests them from the origin root, bypassing the base href. Behind a reverse proxy that only forwards `/f/**`, those requests 404 and hot reload breaks. DWDS also assumes the base href is there: [`_removeBasePath`](https://github.com/dart-lang/webdev/blob/4855a315fa9ce5e06680a0230ac6fe68846a4b76/dwds/lib/src/loaders/frontend_server_strategy_provider.dart#L34-L38) blindly drops `basePath.length` characters from every server path before [mapping it back to a module](https://github.com/dart-lang/webdev/blob/4855a315fa9ce5e06680a0230ac6fe68846a4b76/dwds/lib/src/loaders/frontend_server_strategy_provider.dart#L54-L61), so the root-relative paths were already producing wrong module lookups after a reload. This PR prefixes the `src` entries with `basePath` so they match the initial load and DWDS' expectations. Fixes flutter#192433
1 parent 3964e0e commit ede4f67

2 files changed

Lines changed: 152 additions & 137 deletions

File tree

‎packages/flutter_tools/lib/src/isolated/web_asset_server.dart‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -139,8 +139,8 @@ class WebAssetServer implements AssetReader {
139139
/// restart or hot reload, writes a file that contains a list of objects each
140140
/// with three fields:
141141
///
142-
/// `src`: A string that corresponds to the file path relative to the app base
143-
/// URL root that contains the DDC library bundle.
142+
/// `src`: A root-relative URL path (including [basePath], i.e. the
143+
/// `<base href>` of the app) that contains the DDC library bundle.
144144
/// `module`: The name of the library bundle in `src`.
145145
/// `libraries`: An array of strings containing the libraries that were
146146
/// compiled in `src`.
@@ -149,7 +149,7 @@ class WebAssetServer implements AssetReader {
149149
/// ```json
150150
/// [
151151
/// {
152-
/// "src": "/<file_name>",
152+
/// "src": "/<base_path>/<file_name>",
153153
/// "module": "<module_name>",
154154
/// "libraries": ["<lib1>", "<lib2>"],
155155
/// },
@@ -170,10 +170,17 @@ class WebAssetServer implements AssetReader {
170170
moduleToLibrary.add(<String, Object>{
171171
// Use only the path for the module so the app can still find it even if
172172
// it's in a different domain than the server.
173+
//
174+
// The path must include `basePath` so that the browser requests the
175+
// module through the same `<base href>` prefix as the initial load
176+
// (e.g. behind a reverse proxy that only forwards `/<base_path>/**`),
177+
// and so that DWDS can strip the same `basePath` off the resulting
178+
// script URL when mapping it back to a module.
179+
//
173180
// TODO(srujzs): We use a `/` prefix to match the path that DWDS gets
174181
// when parsing the parsed URL. It may be cleaner to just remove the `/`
175182
// in DWDS rather than add it here.
176-
'src': '/$relativeModulePath',
183+
'src': basePath.isEmpty ? '/$relativeModulePath' : '/$basePath/$relativeModulePath',
177184
'module': metadata.name,
178185
'libraries': libraries,
179186
});

‎packages/flutter_tools/test/general.shard/web/devfs_web_test.dart‎

Lines changed: 141 additions & 133 deletions
Original file line numberDiff line numberDiff line change
@@ -1881,143 +1881,151 @@ const config = {
18811881
expect(body, contains('debug: true'));
18821882
});
18831883

1884-
runInTestbed('DDC library bundle reloaded sources are relative paths', () async {
1885-
// `reloadedSourcesUri` should itself be relative.
1886-
expect(WebAssetServer.reloadedSourcesUri.host, isEmpty);
1884+
for (final (String? baseHref, String expectedSrcPrefix) in <(String?, String)>[
1885+
(null, ''),
1886+
('/f/', '/f'),
1887+
]) {
1888+
runInTestbed('DDC library bundle reloaded sources are root-relative paths '
1889+
'(baseHref: $baseHref)', () async {
1890+
// `reloadedSourcesUri` should itself be relative.
1891+
expect(WebAssetServer.reloadedSourcesUri.host, isEmpty);
1892+
1893+
// Set up initial compile.
1894+
final File outputFile = globals.fs.file(globals.fs.path.join('lib', 'main.dart'))
1895+
..createSync(recursive: true);
1896+
outputFile.parent.childFile('a.lib.js.sources').writeAsStringSync('main() {}');
1897+
outputFile.parent.childFile('a.lib.js.json').writeAsStringSync('{}');
1898+
outputFile.parent.childFile('a.lib.js.map').writeAsStringSync('{}');
1899+
outputFile.parent.childFile('a.lib.js.metadata').writeAsStringSync('{}');
1900+
1901+
final residentCompiler = FakeResidentCompiler()
1902+
..output = const CompilerOutput('a.lib.js', 0, <Uri>[]);
18871903

1888-
// Set up initial compile.
1889-
final File outputFile = globals.fs.file(globals.fs.path.join('lib', 'main.dart'))
1890-
..createSync(recursive: true);
1891-
outputFile.parent.childFile('a.lib.js.sources').writeAsStringSync('main() {}');
1892-
outputFile.parent.childFile('a.lib.js.json').writeAsStringSync('{}');
1893-
outputFile.parent.childFile('a.lib.js.map').writeAsStringSync('{}');
1894-
outputFile.parent.childFile('a.lib.js.metadata').writeAsStringSync('{}');
1895-
1896-
final residentCompiler = FakeResidentCompiler()
1897-
..output = const CompilerOutput('a.lib.js', 0, <Uri>[]);
1898-
1899-
final WebDevFS webDevFS = createWebDevFS(
1900-
useSseForDebugProxy: true,
1901-
useSseForDebugBackend: true,
1902-
useSseForInjectedClient: true,
1903-
buildInfo: const BuildInfo(
1904-
BuildMode.debug,
1905-
'',
1906-
treeShakeIcons: false,
1907-
packageConfigPath: '.dart_tool/package_config.json',
1908-
),
1909-
ddsConfig: const DartDevelopmentServiceConfiguration(enable: false),
1910-
entrypoint: Uri.base,
1911-
ddcModuleSystem: usesDdcModuleSystem,
1912-
canaryFeatures: canaryFeatures,
1913-
);
1914-
webDevFS.ddcModuleLoaderJS.createSync(recursive: true);
1915-
webDevFS.flutterJs.createSync(recursive: true);
1916-
webDevFS.stackTraceMapper.createSync(recursive: true);
1917-
1918-
await webDevFS.create();
1919-
1920-
webDevFS.webAssetServer.entrypointCacheDirectory = globals.fs.currentDirectory;
1921-
globals.fs.currentDirectory.childDirectory('lib').childFile('web_entrypoint.dart')
1922-
..createSync(recursive: true)
1923-
..writeAsStringSync('GENERATED');
1924-
final String webPrecompiledCanvaskitSdk = globals.artifacts!
1925-
.getHostArtifact(HostArtifact.webPrecompiledDDCCanarySdk)
1926-
.path;
1927-
final String webPrecompiledCanvaskitSdkSourcemaps = globals.artifacts!
1928-
.getHostArtifact(HostArtifact.webPrecompiledDDCCanarySdkSourcemaps)
1929-
.path;
1930-
final String flutterJs = globals.fs.path.join(
1931-
globals.artifacts!.getHostArtifact(HostArtifact.flutterJsDirectory).path,
1932-
'flutter.js',
1933-
);
1934-
globals.fs.file(webPrecompiledCanvaskitSdk)
1935-
..createSync(recursive: true)
1936-
..writeAsStringSync('HELLO');
1937-
globals.fs.file(webPrecompiledCanvaskitSdkSourcemaps)
1938-
..createSync(recursive: true)
1939-
..writeAsStringSync('THERE');
1940-
globals.fs.file(flutterJs)
1941-
..createSync(recursive: true)
1942-
..writeAsStringSync('(flutter.js content)');
1904+
final WebDevFS webDevFS = createWebDevFS(
1905+
useSseForDebugProxy: true,
1906+
useSseForDebugBackend: true,
1907+
useSseForInjectedClient: true,
1908+
buildInfo: const BuildInfo(
1909+
BuildMode.debug,
1910+
'',
1911+
treeShakeIcons: false,
1912+
packageConfigPath: '.dart_tool/package_config.json',
1913+
),
1914+
ddsConfig: const DartDevelopmentServiceConfiguration(enable: false),
1915+
entrypoint: Uri.base,
1916+
webDevServerConfig: WebDevServerConfig(baseHref: baseHref),
1917+
ddcModuleSystem: usesDdcModuleSystem,
1918+
canaryFeatures: canaryFeatures,
1919+
);
1920+
webDevFS.ddcModuleLoaderJS.createSync(recursive: true);
1921+
webDevFS.flutterJs.createSync(recursive: true);
1922+
webDevFS.stackTraceMapper.createSync(recursive: true);
19431923

1944-
await webDevFS.update(
1945-
mainUri: outputFile.uri,
1946-
generator: residentCompiler,
1947-
trackWidgetCreation: true,
1948-
bundleFirstUpload: true,
1949-
invalidatedFiles: <Uri>[],
1950-
packageConfig: PackageConfig.empty,
1951-
pathToReload: '',
1952-
dillOutputPath: '',
1953-
shaderCompiler: const FakeShaderCompiler(),
1954-
);
1924+
await webDevFS.create();
19551925

1956-
// Recompile with modules in the top-level and in a subdirectory.
1957-
const aSource = 'void main() {}';
1958-
const bSource = 'void func() {}';
1959-
final File sources = outputFile.parent.childFile('a.lib.js.sources')
1960-
..writeAsStringSync('$aSource$bSource');
1961-
outputFile.parent.childFile('a.lib.js.map').writeAsStringSync('{}{}');
1962-
final String aMetadata = json.encode(
1963-
ModuleMetadata('a.lib.js', 'closure', 'a.map', 'a.lib.js')
1964-
..addLibrary(LibraryMetadata('lib_a', 'dart:lib_a', ['lib_a.dart']))
1965-
..toJson(),
1966-
);
1967-
final String bMetadata = json.encode(
1968-
ModuleMetadata('b.lib.js', 'closure', 'b.map', 'b.lib.js')
1969-
..addLibrary(LibraryMetadata('lib_b', 'dart:lib_b', ['lib_b.dart']))
1970-
..toJson(),
1971-
);
1972-
final File metadata = outputFile.parent.childFile('a.lib.js.metadata')
1973-
..writeAsStringSync('$aMetadata$bMetadata');
1974-
outputFile.parent
1975-
.childFile('a.lib.js.json')
1976-
.writeAsStringSync(
1977-
json.encode(<String, Object>{
1978-
'a.lib.js': <String, Object>{
1979-
'code': <int>[0, aSource.length],
1980-
'sourcemap': <int>[0, 2],
1981-
'metadata': <int>[0, aMetadata.length],
1982-
},
1983-
'sub/b.lib.js': <String, Object>{
1984-
'code': <int>[aSource.length, sources.lengthSync()],
1985-
'sourcemap': <int>[2, 4],
1986-
'metadata': <int>[aMetadata.length, metadata.lengthSync()],
1987-
},
1988-
}),
1989-
);
1926+
webDevFS.webAssetServer.entrypointCacheDirectory = globals.fs.currentDirectory;
1927+
globals.fs.currentDirectory.childDirectory('lib').childFile('web_entrypoint.dart')
1928+
..createSync(recursive: true)
1929+
..writeAsStringSync('GENERATED');
1930+
final String webPrecompiledCanvaskitSdk = globals.artifacts!
1931+
.getHostArtifact(HostArtifact.webPrecompiledDDCCanarySdk)
1932+
.path;
1933+
final String webPrecompiledCanvaskitSdkSourcemaps = globals.artifacts!
1934+
.getHostArtifact(HostArtifact.webPrecompiledDDCCanarySdkSourcemaps)
1935+
.path;
1936+
final String flutterJs = globals.fs.path.join(
1937+
globals.artifacts!.getHostArtifact(HostArtifact.flutterJsDirectory).path,
1938+
'flutter.js',
1939+
);
1940+
globals.fs.file(webPrecompiledCanvaskitSdk)
1941+
..createSync(recursive: true)
1942+
..writeAsStringSync('HELLO');
1943+
globals.fs.file(webPrecompiledCanvaskitSdkSourcemaps)
1944+
..createSync(recursive: true)
1945+
..writeAsStringSync('THERE');
1946+
globals.fs.file(flutterJs)
1947+
..createSync(recursive: true)
1948+
..writeAsStringSync('(flutter.js content)');
1949+
1950+
await webDevFS.update(
1951+
mainUri: outputFile.uri,
1952+
generator: residentCompiler,
1953+
trackWidgetCreation: true,
1954+
bundleFirstUpload: true,
1955+
invalidatedFiles: <Uri>[],
1956+
packageConfig: PackageConfig.empty,
1957+
pathToReload: '',
1958+
dillOutputPath: '',
1959+
shaderCompiler: const FakeShaderCompiler(),
1960+
);
19901961

1991-
await webDevFS.update(
1992-
mainUri: outputFile.uri,
1993-
generator: residentCompiler,
1994-
trackWidgetCreation: true,
1995-
invalidatedFiles: <Uri>[],
1996-
packageConfig: PackageConfig.empty,
1997-
pathToReload: '',
1998-
dillOutputPath: '',
1999-
shaderCompiler: const FakeShaderCompiler(),
2000-
);
1962+
// Recompile with modules in the top-level and in a subdirectory.
1963+
const aSource = 'void main() {}';
1964+
const bSource = 'void func() {}';
1965+
final File sources = outputFile.parent.childFile('a.lib.js.sources')
1966+
..writeAsStringSync('$aSource$bSource');
1967+
outputFile.parent.childFile('a.lib.js.map').writeAsStringSync('{}{}');
1968+
final String aMetadata = json.encode(
1969+
ModuleMetadata('a.lib.js', 'closure', 'a.map', 'a.lib.js')
1970+
..addLibrary(LibraryMetadata('lib_a', 'dart:lib_a', ['lib_a.dart']))
1971+
..toJson(),
1972+
);
1973+
final String bMetadata = json.encode(
1974+
ModuleMetadata('b.lib.js', 'closure', 'b.map', 'b.lib.js')
1975+
..addLibrary(LibraryMetadata('lib_b', 'dart:lib_b', ['lib_b.dart']))
1976+
..toJson(),
1977+
);
1978+
final File metadata = outputFile.parent.childFile('a.lib.js.metadata')
1979+
..writeAsStringSync('$aMetadata$bMetadata');
1980+
outputFile.parent
1981+
.childFile('a.lib.js.json')
1982+
.writeAsStringSync(
1983+
json.encode(<String, Object>{
1984+
'a.lib.js': <String, Object>{
1985+
'code': <int>[0, aSource.length],
1986+
'sourcemap': <int>[0, 2],
1987+
'metadata': <int>[0, aMetadata.length],
1988+
},
1989+
'sub/b.lib.js': <String, Object>{
1990+
'code': <int>[aSource.length, sources.lengthSync()],
1991+
'sourcemap': <int>[2, 4],
1992+
'metadata': <int>[aMetadata.length, metadata.lengthSync()],
1993+
},
1994+
}),
1995+
);
20011996

2002-
final Uint8List? reloadedSources = webDevFS.webAssetServer.getFile(
2003-
WebAssetServer.reloadedSourcesUri.path,
2004-
);
2005-
expect(reloadedSources, isNotNull);
2006-
expect(json.decode(utf8.decode(reloadedSources!)), [
2007-
{
2008-
// The paths within `reloadedSources` should be relative with a root
2009-
// prefix.
2010-
'src': '/a.lib.js',
2011-
'module': 'a.lib.js',
2012-
'libraries': ['dart:lib_a'],
2013-
},
2014-
{
2015-
'src': '/sub/b.lib.js',
2016-
'module': 'b.lib.js',
2017-
'libraries': ['dart:lib_b'],
2018-
},
2019-
]);
1997+
await webDevFS.update(
1998+
mainUri: outputFile.uri,
1999+
generator: residentCompiler,
2000+
trackWidgetCreation: true,
2001+
invalidatedFiles: <Uri>[],
2002+
packageConfig: PackageConfig.empty,
2003+
pathToReload: '',
2004+
dillOutputPath: '',
2005+
shaderCompiler: const FakeShaderCompiler(),
2006+
);
20202007

2021-
await webDevFS.destroy();
2022-
}, overrides: <Type, Generator>{Artifacts: () => Artifacts.test()});
2008+
final Uint8List? reloadedSources = webDevFS.webAssetServer.getFile(
2009+
WebAssetServer.reloadedSourcesUri.path,
2010+
);
2011+
expect(reloadedSources, isNotNull);
2012+
expect(json.decode(utf8.decode(reloadedSources!)), [
2013+
{
2014+
// The paths within `reloadedSources` should be root-relative and
2015+
// include the base href so they resolve through the same prefix as
2016+
// the initial load (e.g. behind a reverse proxy).
2017+
'src': '$expectedSrcPrefix/a.lib.js',
2018+
'module': 'a.lib.js',
2019+
'libraries': ['dart:lib_a'],
2020+
},
2021+
{
2022+
'src': '$expectedSrcPrefix/sub/b.lib.js',
2023+
'module': 'b.lib.js',
2024+
'libraries': ['dart:lib_b'],
2025+
},
2026+
]);
2027+
2028+
await webDevFS.destroy();
2029+
}, overrides: <Type, Generator>{Artifacts: () => Artifacts.test()});
2030+
}
20232031
}

0 commit comments

Comments
 (0)