Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,12 @@ Copyright (c) .NET Foundation. All rights reserved.
ResolveHtmlImportMapBuildStaticWebAssets
</ResolveBuildServiceWorkerStaticWebAssetsDependsOn>
<ResolveHtmlImportMapBuildStaticWebAssetsDependsOn>
GenerateHtmlImportMapBuildStaticWebAssets;
$(ResolveHtmlImportMapBuildStaticWebAssetsDependsOn)
$(ResolveHtmlImportMapBuildStaticWebAssetsDependsOn);
GenerateHtmlImportMapBuildStaticWebAssets
</ResolveHtmlImportMapBuildStaticWebAssetsDependsOn>
<GenerateHtmlImportMapBuildStaticWebAssetsDependsOn>
ResolveHtmlImportMapBuildConfiguration;
$(GenerateHtmlImportMapBuildStaticWebAssetsDependsOn)
$(GenerateHtmlImportMapBuildStaticWebAssetsDependsOn);
ResolveHtmlImportMapBuildConfiguration
</GenerateHtmlImportMapBuildStaticWebAssetsDependsOn>

<!--
Expand All @@ -62,12 +62,12 @@ Copyright (c) .NET Foundation. All rights reserved.
ResolveHtmlImportMapPublishStaticWebAssets
</ResolvePublishServiceWorkerStaticWebAssetsDependsOn>
<ResolveHtmlImportMapPublishStaticWebAssetsDependsOn>
GenerateHtmlImportMapPublishStaticWebAssets;
$(ResolveHtmlImportMapPublishStaticWebAssetsDependsOn)
$(ResolveHtmlImportMapPublishStaticWebAssetsDependsOn);
GenerateHtmlImportMapPublishStaticWebAssets
</ResolveHtmlImportMapPublishStaticWebAssetsDependsOn>
<GenerateHtmlImportMapPublishStaticWebAssetsDependsOn>
ResolveHtmlImportMapPublishConfiguration;
$(GenerateHtmlImportMapPublishStaticWebAssetsDependsOn)
$(GenerateHtmlImportMapPublishStaticWebAssetsDependsOn);
ResolveHtmlImportMapPublishConfiguration
</GenerateHtmlImportMapPublishStaticWebAssetsDependsOn>

</PropertyGroup>
Expand Down
91 changes: 79 additions & 12 deletions src/StaticWebAssetsSdk/Tasks/WriteImportMapToHtml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ public partial class WriteImportMapToHtml : Task

private static readonly Regex _importMapRegex = new Regex(@"<script\s+type=""importmap""\s*>\s*</script>");

private static readonly Regex _preloadRegex = new Regex(@"<link\s+rel=""preload""\s*[/]?>");

public override bool Execute()
{
var endpoints = StaticWebAssetEndpoint.FromItemGroup(Endpoints).Where(e => e.AssetFile.EndsWith(".js") || e.AssetFile.EndsWith(".mjs"));
Expand Down Expand Up @@ -75,6 +77,13 @@ public override bool Execute()
return $"<script type=\"importmap\">{JsonSerializer.Serialize(importMap, ImportMapSerializerContext.CustomEncoder.Options)}</script>";
});

// Generate import map
outputContent = _preloadRegex.Replace(outputContent, e =>
{
Log.LogMessage("Writing preload links to '{0}'", item.ItemSpec);
return GeneratePreloadLinks(resources);
});

// Fingerprint all assets used in html
outputContent = _assetsRegex.Replace(outputContent, e =>
{
Expand Down Expand Up @@ -105,6 +114,42 @@ public override bool Execute()
return true;
}

private static string GeneratePreloadLinks(List<ResourceAsset> assets)
{
var links = new List<(string? Order, string Value)>();
foreach (var asset in assets)
{
if (asset.PreloadRel == null)
{
continue;
}

string link = $"<link href=\"{asset.Url}\" rel=\"{asset.PreloadRel}\"";
if (!string.IsNullOrEmpty(asset.PreloadAs))
{
link = String.Concat(link, " as=\"", asset.PreloadAs, "\"");
}
if (!string.IsNullOrEmpty(asset.PreloadPriority))
{
link = String.Concat(link, " fetchpriority=\"", asset.PreloadPriority, "\"");
}
if (!string.IsNullOrEmpty(asset.PreloadCrossorigin))
{
link = String.Concat(link, " crossorigin=\"", asset.PreloadCrossorigin, "\"");
}
if (!string.IsNullOrEmpty(asset.Integrity))
{
link = String.Concat(link, " integrity=\"", asset.Integrity, "\"");
}

link += " />";
links.Add((asset.PreloadOrder, link));
}

links.Sort((a, b) => string.Compare(a.Order, b.Order, StringComparison.InvariantCulture));
return String.Join(Environment.NewLine, links.Select(l => l.Value));
}

private string GetFingerprintedAssetPath(Dictionary<string, ResourceAsset> urlMappings, string assetPath)
{
if (urlMappings.TryGetValue(assetPath, out var asset) && (!IncludeOnlyHardFingerprintedModules || asset.IsHardFingerprinted))
Expand All @@ -125,33 +170,50 @@ internal List<ResourceAsset> CreateResourcesFromEndpoints(IEnumerable<StaticWebA
// subresource integrity to things like images, script tags, etc.
foreach (var endpoint in endpoints)
{
string? label = null;
string? integrity = null;

// If there's a selector this means that this is an alternative representation for a resource, so skip it.
if (endpoint.Selectors?.Length == 0)
{
var resourceAsset = new ResourceAsset(endpoint.Route);
for (var i = 0; i < endpoint.EndpointProperties?.Length; i++)
{
var property = endpoint.EndpointProperties[i];
if (property.Name.Equals("label", StringComparison.OrdinalIgnoreCase))
{
label = property.Value;
resourceAsset.Label = property.Value;
}
else if (property.Name.Equals("integrity", StringComparison.OrdinalIgnoreCase))
{
integrity = property.Value;
resourceAsset.Integrity = property.Value;
}
else if (property.Name.Equals("preloadrel", StringComparison.OrdinalIgnoreCase))
{
resourceAsset.PreloadRel = property.Value;
}
else if (property.Name.Equals("preloadas", StringComparison.OrdinalIgnoreCase))
{
resourceAsset.PreloadAs = property.Value;
}
else if (property.Name.Equals("preloadpriority", StringComparison.OrdinalIgnoreCase))
{
resourceAsset.PreloadPriority = property.Value;
}
else if (property.Name.Equals("preloadcrossorigin", StringComparison.OrdinalIgnoreCase))
{
resourceAsset.PreloadCrossorigin = property.Value;
}
else if (property.Name.Equals("preloadorder", StringComparison.OrdinalIgnoreCase))
{
resourceAsset.PreloadOrder = property.Value;
}
}

bool isHardFingerprinted = true;
var asset = Assets.FirstOrDefault(a => a.ItemSpec == endpoint.AssetFile);
if (asset != null)
{
isHardFingerprinted = asset.GetMetadata("RelativePath").Contains("#[.{fingerprint}]!");
resourceAsset.IsHardFingerprinted = asset.GetMetadata("RelativePath").Contains("#[.{fingerprint}]!");
}

resources.Add(new ResourceAsset(endpoint.Route, label, integrity, isHardFingerprinted));
resources.Add(resourceAsset);
}
}

Expand Down Expand Up @@ -207,12 +269,17 @@ private static Dictionary<string, ResourceAsset> GroupResourcesByLabel(List<Reso
}
}

internal sealed class ResourceAsset(string url, string? label, string? integrity, bool isHardFingerprinted)
internal sealed class ResourceAsset(string url)
{
public string Url { get; } = url;
public string? Label { get; set; } = label;
public string? Integrity { get; set; } = integrity;
public bool IsHardFingerprinted { get; set; } = isHardFingerprinted;
public string? Label { get; set; }
public string? Integrity { get; set; }
public string? PreloadRel { get; set; }
public string? PreloadAs { get; set; }
public string? PreloadPriority { get; set; }
public string? PreloadCrossorigin { get; set; }
public string? PreloadOrder { get; set; }
public bool IsHardFingerprinted { get; set; } = true;
}

internal class ImportMap(Dictionary<string, string> imports, Dictionary<string, Dictionary<string, string>> scopes, Dictionary<string, string> integrity)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,38 +57,38 @@ public void Build_FingerprintsContent_WhenEnabled()
[MemberData(nameof(WriteImportMapToHtmlData))]
public void Build_WriteImportMapToHtml(string testAsset, string scriptPath, string scriptPathWithFingerprintPattern, bool fingerprintUserJavascriptAssets, bool expectFingerprintOnScript)
{
ProjectDirectory = CreateAspNetSdkTestAsset(testAsset);
ProjectDirectory = CreateAspNetSdkTestAsset(testAsset, identifier: $"{testAsset}_{fingerprintUserJavascriptAssets}_{expectFingerprintOnScript}");
ReplaceStringInIndexHtml(ProjectDirectory, scriptPath, scriptPathWithFingerprintPattern);
FingerprintUserJavascriptAssets(fingerprintUserJavascriptAssets);

var build = CreateBuildCommand(ProjectDirectory);
ExecuteCommand(build, "-p:WriteImportMapToHtml=true", $"-p:FingerprintUserJavascriptAssets={fingerprintUserJavascriptAssets}").Should().Pass();
ExecuteCommand(build, "-p:WriteImportMapToHtml=true", $"-p:FingerprintUserJavascriptAssets={fingerprintUserJavascriptAssets.ToString().ToLower()}").Should().Pass();

var intermediateOutputPath = build.GetIntermediateDirectory(DefaultTfm, "Debug").ToString();
var indexHtmlPath = Directory.EnumerateFiles(Path.Combine(intermediateOutputPath, "staticwebassets", "importmaphtml", "build"), "*.html").Single();
var endpointsManifestPath = Path.Combine(intermediateOutputPath, $"staticwebassets.build.endpoints.json");

AssertImportMapInHtml(indexHtmlPath, endpointsManifestPath, scriptPath, expectFingerprintOnScript: expectFingerprintOnScript);
AssertImportMapInHtml(indexHtmlPath, endpointsManifestPath, scriptPath, expectFingerprintOnScript: expectFingerprintOnScript, expectPreloadElement: testAsset == "VanillaWasm");
}

[Theory]
[MemberData(nameof(WriteImportMapToHtmlData))]
public void Publish_WriteImportMapToHtml(string testAsset, string scriptPath, string scriptPathWithFingerprintPattern, bool fingerprintUserJavascriptAssets, bool expectFingerprintOnScript)
{
ProjectDirectory = CreateAspNetSdkTestAsset(testAsset);
ProjectDirectory = CreateAspNetSdkTestAsset(testAsset, identifier: $"{testAsset}_{fingerprintUserJavascriptAssets}_{expectFingerprintOnScript}");
ReplaceStringInIndexHtml(ProjectDirectory, scriptPath, scriptPathWithFingerprintPattern);
FingerprintUserJavascriptAssets(fingerprintUserJavascriptAssets);

var projectName = Path.GetFileNameWithoutExtension(Directory.EnumerateFiles(ProjectDirectory.TestRoot, "*.csproj").Single());

var publish = CreatePublishCommand(ProjectDirectory);
ExecuteCommand(publish, "-p:WriteImportMapToHtml=true", $"-p:FingerprintUserJavascriptAssets={fingerprintUserJavascriptAssets}").Should().Pass();
ExecuteCommand(publish, "-p:WriteImportMapToHtml=true", $"-p:FingerprintUserJavascriptAssets={fingerprintUserJavascriptAssets.ToString().ToLower()}").Should().Pass();

var outputPath = publish.GetOutputDirectory(DefaultTfm, "Debug").ToString();
var indexHtmlOutputPath = Path.Combine(outputPath, "wwwroot", "index.html");
var endpointsManifestPath = Path.Combine(outputPath, $"{projectName}.staticwebassets.endpoints.json");

AssertImportMapInHtml(indexHtmlOutputPath, endpointsManifestPath, scriptPath, expectFingerprintOnScript: expectFingerprintOnScript);
AssertImportMapInHtml(indexHtmlOutputPath, endpointsManifestPath, scriptPath, expectFingerprintOnScript: expectFingerprintOnScript, expectPreloadElement: testAsset == "VanillaWasm");
}

private void FingerprintUserJavascriptAssets(bool fingerprintUserJavascriptAssets)
Expand Down Expand Up @@ -125,7 +125,7 @@ private void ReplaceStringInIndexHtml(TestAsset testAsset, string sourceValue, s
}
}

private void AssertImportMapInHtml(string indexHtmlPath, string endpointsManifestPath, string scriptPath, bool expectFingerprintOnScript = true)
private void AssertImportMapInHtml(string indexHtmlPath, string endpointsManifestPath, string scriptPath, bool expectFingerprintOnScript = true, bool expectPreloadElement = false)
{
var indexHtmlContent = File.ReadAllText(indexHtmlPath);
var endpoints = JsonSerializer.Deserialize<StaticWebAssetEndpointsManifest>(File.ReadAllText(endpointsManifestPath));
Expand All @@ -150,6 +150,12 @@ private void AssertImportMapInHtml(string indexHtmlPath, string endpointsManifes
Assert.Contains(GetFingerprintedPath("_framework/dotnet.native.js"), indexHtmlContent);
Assert.Contains(GetFingerprintedPath("_framework/dotnet.runtime.js"), indexHtmlContent);

if (expectPreloadElement)
{
Assert.DoesNotContain("<link rel=\"preload\">", indexHtmlContent);
Assert.Contains($"<link href=\"{fingerprintedScriptPath}\" rel=\"preload\" as=\"script\" fetchpriority=\"high\" crossorigin=\"anonymous\"", indexHtmlContent);
}

string GetFingerprintedPath(string route)
=> endpoints.Endpoints.FirstOrDefault(e => e.Route == route && e.Selectors.Length == 0)?.AssetFile ?? throw new Exception($"Missing endpoint for file '{route}' in '{endpointsManifestPath}'");
}
Expand Down
53 changes: 53 additions & 0 deletions test/TestAssets/TestProjects/VanillaWasm/VanillaWasm.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,58 @@
<PropertyGroup>
<TargetFramework>$(CurrentTargetFramework)</TargetFramework>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<GenerateHtmlImportMapBuildStaticWebAssetsDependsOn>
_AddAppPreloadProperties;
$(GenerateHtmlImportMapBuildStaticWebAssetsDependsOn)
</GenerateHtmlImportMapBuildStaticWebAssetsDependsOn>
</PropertyGroup>
<Target Name="_AppConfigurePreload">
<ItemGroup>
<_AppendPreloadRelPreloadProperty Include="Append">
<UpdateTarget>Property</UpdateTarget>
<Name>PreloadRel</Name>
<Value>preload</Value>
</_AppendPreloadRelPreloadProperty>
<_AppendPreloadAsScriptProperty Include="Append">
<UpdateTarget>Property</UpdateTarget>
<Name>PreloadAs</Name>
<Value>script</Value>
</_AppendPreloadAsScriptProperty>
<_AppendPreloadPriorityHighProperty Include="Append">
<UpdateTarget>Property</UpdateTarget>
<Name>PreloadPriority</Name>
<Value>high</Value>
</_AppendPreloadPriorityHighProperty>
<_AppendPreloadCrossoriginAnonymousProperty Include="Append">
<UpdateTarget>Property</UpdateTarget>
<Name>PreloadCrossorigin</Name>
<Value>anonymous</Value>
</_AppendPreloadCrossoriginAnonymousProperty>
</ItemGroup>
</Target>
<Target Name="_AddAppPreloadProperties" DependsOnTargets="_AppConfigurePreload;_AddWasmStaticWebAssets" BeforeTargets="GenerateStaticWebAssetsManifest">
<ItemGroup>
<_AppPreloadScriptAsset Include="@(StaticWebAsset)" Condition="'%(FileName)%(Extension)' == 'main.js'" />
<_AppPreloadEndpointFilter Include="Property" Name="Label" Mode="Include" Condition="'$(FingerprintUserJavascriptAssets)' == 'true'" />
<_AppPreloadEndpointFilter Include="Property" Name="Label" Mode="Exclude" Condition="'@(_AppPreloadEndpointFilter)' == ''" />
</ItemGroup>
<FilterStaticWebAssetEndpoints
Endpoints="@(StaticWebAssetEndpoint)"
Assets="@(_AppPreloadScriptAsset)"
Filters="@(_AppPreloadEndpointFilter)"
>
<Output TaskParameter="FilteredEndpoints" ItemName="_AppPreloadScriptAssetEndpoint" />
</FilterStaticWebAssetEndpoints>
<UpdateStaticWebAssetEndpoints
EndpointsToUpdate="@(_AppPreloadScriptAssetEndpoint)"
AllEndpoints="@(_AppPreloadScriptAssetEndpoint)"
Operations="@(_AppendPreloadRelPreloadProperty);@(_AppendPreloadAsScriptProperty);@(_AppendPreloadPriorityHighProperty);@(_AppendPreloadCrossoriginAnonymousProperty)"
>
<Output TaskParameter="UpdatedEndpoints" ItemName="_UpdatedAppStaticWebAssetEndpoint" />
</UpdateStaticWebAssetEndpoints>
<ItemGroup>
<StaticWebAssetEndpoint Remove="@(_AppPreloadScriptAssetEndpoint)" />
<StaticWebAssetEndpoint Include="@(_UpdatedAppStaticWebAssetEndpoint)" />
</ItemGroup>
</Target>
</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
<title>WasmMySdk</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="preload">
<script type="importmap"></script>
<script type="module" src="main.js"></script>

Expand Down
Loading