Correzioni della revisione della catena 0.3.0, ognuna con la sua prova

- Collegamento: corretta la SyntaxError di connection.js (una «let saved» dichiarata due
  volte nello stesso blocco fermava tutta la pagina). Nuova prova ScriptSyntaxTests con un
  controllo scritto in casa che legge ogni modulo di wwwroot: parentesi, dichiarazioni
  doppie nello stesso blocco, importazioni che il modulo di arrivo non esporta.
- HEIF: il riconoscimento dei formati prende ogni marchio che HeifDecoder accetta (mif2,
  MiHE, marchi solo compatibili), così rilevazione, decodifica, misure, miniatura e
  impronta concordano.
- Docker, lasciare la pagina del browser: un nuovo contratto del browser cancella l'uscita
  annotata (_leftAt) anche prima che la vista si riapra, e la copia della sessione aspetta
  un altro comando del collegamento al più LetGoWait invece che senza limite.
- JPEG e PNG: senza EOI o IEND la decodifica fallisce («File danneggiato o incompleto»),
  la sola lettura delle misure resta tollerante.
- Visualizzatore: IsDamaged legge prima l'intestazione e il file intero solo quando può
  servire, in modo asincrono e con una piccola memoria per file, così una scheda con
  molti file non blocca il server.
- Importazione (§9.3): le immagini danneggiate si importano come le altre ma si segnano
  nella revisione, nel resoconto e nel CSV.
- Pulizia: le prove con il limite di 5 minuti non corrono più in parallelo fra loro.
- Pila dei caratteri come l'appendice B, senza Liberation; testo di Informazioni sulle
  immagini fatte in casa; guida (Problemi comuni, Sicurezza) allineata all'uscita in
  Docker dalla pagina del browser.
- docs/decisioni.md: le righe del 25 novembre 2026 con i motivi, compresa l'unione 537517b
  tenuta così com'è.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-25 14:21:36 +01:00
1 parent 3d234f8791
commit 2068dd28f3
35 files changed
+1366 -75

No files matched your search

@@ -369,6 +369,104 @@ public sealed class SessionCopyOnLetGoTests
Assert.IsNull(bed.App.SavedSession!.Read());
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task ABeginOfAReloadedPageCancelsTheLeaveEvenBeforeItsViewOpens()
{
var ct = TestContext.CancellationToken;
await using var bed = await StartAsync();
var browser = bed.Browser!;
var connection = bed.App.Connection!;
connection.PageLeaveGrace = TimeSpan.FromSeconds(1);
var view = await DockerBeginAsync(bed);
browser.FakeCdp.LoggedIn = true;
browser.FakeCdp.Navigated(Site + "/");
// A reload where the new page's «begin» arrives but its view does not open within the moment: «begin» alone says
// Alberto is back. Waited past PageLeaveGrace and well below DrivingGrace.
await connection.LeavePageAsync(ct);
view.Dispose();
connection.RemoteViewClosed();
await BeginAsync(bed, openLogin: false);
await browser.HideFromUserAsync(ct);
await Task.Delay(TimeSpan.FromSeconds(2.5), ct);
Assert.IsTrue(browser.UserIsDriving, "begin cancels the leave");
Assert.AreEqual(0, browser.FakeCdp.CaptureReads);
Assert.DoesNotContain("Pagina del browser lasciata: nessuna vista", ReadLog(bed));
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
[DataRow(false, DisplayName = "«pageLeft» tardivo della pagina ricaricata")]
[DataRow(true, DisplayName = "vecchia vista chiusa da «Riprova»")]
public async Task ALeaveFollowedByAViewOpenAgainIsForgottenWhenThatViewEndsFromTheServer(bool oldViewClosed)
{
var ct = TestContext.CancellationToken;
await using var bed = await StartAsync();
var browser = bed.Browser!;
var connection = bed.App.Connection!;
connection.PageLeaveGrace = TimeSpan.FromSeconds(1);
var view = await DockerBeginAsync(bed);
browser.FakeCdp.LoggedIn = true;
browser.FakeCdp.Navigated(Site + "/");
// The leave arrives while a view is open: the keepalive «pageLeft» of a reloaded page after the new page's
// «begin», or the old socket closed by «Riprova» while the new view opens without «begin».
if (oldViewClosed)
{
connection.RemoteViewClosed();
}
else
{
await connection.LeavePageAsync(ct);
}
await Task.Delay(TimeSpan.FromMilliseconds(600), ct);
// That view then ends from the server (the browser stopped): it is not told to the connection. A browser that is
// down is not leaving it, so the lease waits for DrivingGrace, not for PageLeaveGrace.
view.Dispose();
await Task.Delay(TimeSpan.FromSeconds(2.5), ct);
Assert.IsTrue(browser.UserIsDriving, "the earlier leave was forgotten once a view was open again");
Assert.AreEqual(0, browser.FakeCdp.CaptureReads);
Assert.DoesNotContain("Pagina del browser lasciata: nessuna vista", ReadLog(bed));
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task LeavingTheBrowserPageWaitsForAnotherCommandOnlyForLetGoWait()
{
var ct = TestContext.CancellationToken;
await using var bed = await StartAsync();
var browser = bed.Browser!;
var connection = bed.App.Connection!;
connection.PageLeaveGrace = TimeSpan.FromMilliseconds(300);
connection.LetGoWait = TimeSpan.FromMilliseconds(500);
connection.PageTurnWait = TimeSpan.FromSeconds(30);
var view = await DockerBeginAsync(bed);
browser.FakeCdp.LoggedIn = true;
browser.FakeCdp.Navigated(Site + "/");
// «Pagina iniziale» holds the commands of the connection while it waits for the page's turn, which a step of the
// profile search keeps for longer than leaving the page may wait.
using var press = CancellationTokenSource.CreateLinkedTokenSource(ct);
Task startPage;
using (await bed.App.Engine!.Services.PageTurns.TakeAsync(Febe.Core.Engine.PageUser.Search, ct))
{
startPage = connection.OpenStartPageAsync(press.Token);
await Task.Delay(TimeSpan.FromMilliseconds(200), ct);
view.Dispose();
connection.RemoteViewClosed();
await DesktopTestBed.WaitUntilAsync(() => !browser.UserIsDriving, TimeSpan.FromSeconds(10), "la fine della guida dopo l'attesa massima");
press.Cancel();
}
await startPage;
Assert.AreEqual(0, browser.FakeCdp.CaptureReads);
StringAssert.Contains(ReadLog(bed), "Pagina del browser lasciata: sessione non copiata, un altro comando del collegamento era ancora in corso.");
Assert.IsNull(bed.App.SavedSession!.Read());
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task LeavingTheBrowserPageOnTheLoginPageCopiesNothingButGivesThePageBack()
@@ -3,7 +3,7 @@ using Febe.Core.Codecs.Images;
namespace Febe.Tests.Imaging;
/// <summary>
/// Damaged and unusual JPEG files: the decoder reads what T.81 and common practice allow (no EOI, bytes after EOI,
/// Damaged and unusual JPEG files: the decoder reads what T.81 and common practice allow (bytes after EOI,
/// no DHT as in Motion JPEG), refuses what it cannot read with the right exception, and never fails in any other way.
/// </summary>
[TestClass]
@@ -34,9 +34,11 @@ public sealed class JpegMalformedTests
}
}
// Only the EOI missing: complete scans are accepted.
using var withoutEoi = JpegDecoder.Decode(file[..^2]);
ImageAssert.AreEqual(whole, withoutEoi, $"senza EOI, ripristino {restart}");
// Only the EOI missing: incomplete all the same (spec §3), though its size is still read.
var withoutEoi = file[..^2];
var error = Assert.Throws<ImageDecodeException>(() => JpegDecoder.Decode(withoutEoi), $"senza EOI, ripristino {restart}");
StringAssert.Contains(error.Message, "EOI");
Assert.AreEqual((whole.Width, whole.Height), (JpegDecoder.Identify(withoutEoi).Width, JpegDecoder.Identify(withoutEoi).Height));
}
}
+5 -18
View File
@@ -290,7 +290,7 @@ public sealed class PngCodecTests
}
[TestMethod]
public void EveryTruncationEitherFailsOrGivesTheWholeImage()
public void EveryTruncationFailsEvenAfterTheLastImageData()
{
var reference = ReferenceImages.Get("png-tav-4-adam7");
var full = reference.ReadInput();
@@ -310,23 +310,10 @@ public sealed class PngCodecTests
}
}
// Only cuts at a chunk boundary after the last IDAT keep everything (a missing IEND is accepted).
var lastIdatEnd = 8;
var boundaries = new List<int>();
for (var pos = 8; pos < full.Length;)
{
var length = (int)BinaryPrimitives.ReadUInt32BigEndian(full.AsSpan(pos));
var type = Encoding.ASCII.GetString(full, pos + 4, 4);
pos += length + 12;
boundaries.Add(pos);
if (type == "IDAT")
{
lastIdatEnd = pos;
}
}
Assert.AreEqual(boundaries.Count(b => b >= lastIdatEnd && b < full.Length), whole);
Assert.IsGreaterThanOrEqualTo(1, whole);
// Spec §3: a PNG that ends before IEND is incomplete, also when the cut falls after the last IDAT.
Assert.AreEqual(0, whole);
var error = Assert.Throws<ImageDecodeException>(() => PngDecoder.Decode(full[..^12]), "solo IEND mancante");
StringAssert.Contains(error.Message, "IEND");
}
[TestMethod]
@@ -513,6 +513,46 @@ public sealed class ImportCopyTests
CollectionAssert.AreEqual(new[] { "marta.demo/documento.pdf" }, report.Unrecognized.ToArray());
}
[TestMethod]
public async Task TheReviewTheReportAndTheCsvMarkADamagedImageImportedLikeTheOthers()
{
// Spec §9.3: a truncated image has its type and SHA-256 but no fingerprint; it is imported like the others and
// the review and the report mark it «File danneggiato o incompleto».
using var temp = new TempFolder("importa");
await using var bed = await ImportTestBed.CreateAsync(temp);
await bed.Library.Db.Accounts.AddAsync(Make.Account("marta.demo"));
var whole = ImportTestFiles.Photo(130);
var cut = whole[..(whole.Length * 2 / 3)];
bed.Write("marta.demo/tagliata.jpg", cut);
bed.Write("marta.demo/intera.jpg", ImportTestFiles.Photo(131));
bed.Write("marta.demo/nota.txt", "testo"u8.ToArray());
var run = await bed.AnalyzeAsync();
var summary = await bed.Review.GetSummaryAsync(run.Id);
Assert.AreEqual(1, summary.Damaged);
var files = await bed.FilesAsync(run.Id);
var damaged = files.Single(f => f.RelativePath == "marta.demo/tagliata.jpg");
Assert.AreEqual(ImportOutcome.New, damaged.Outcome, "si importa come le altre");
Assert.IsNull(damaged.PerceptualHash, "nessuna impronta visiva");
Assert.AreEqual(Convert.ToHexStringLower(SHA256.HashData(cut)), damaged.Sha256);
await bed.Copier.CopyAsync(run.Id);
Assert.AreEqual(ImportFileState.Copied, (await bed.FilesAsync(run.Id)).Single(f => f.Id == damaged.Id).State);
var report = await bed.Reports.GetReportAsync(run.Id);
Assert.AreEqual(1, report.DamagedCount);
CollectionAssert.AreEqual(new[] { "marta.demo/tagliata.jpg" }, report.Damaged!.ToArray());
using var output = new MemoryStream();
await bed.Reports.WriteCsvAsync(run.Id, output);
var lines = System.Text.Encoding.UTF8.GetString(output.ToArray()).Split("\r\n", StringSplitOptions.RemoveEmptyEntries);
StringAssert.EndsWith(lines.Single(l => l.StartsWith("marta.demo/tagliata.jpg;", StringComparison.Ordinal)), ";File danneggiato o incompleto");
Assert.DoesNotContain("danneggiato", lines.Single(l => l.StartsWith("marta.demo/intera.jpg;", StringComparison.Ordinal)));
// An analysis that starts again marks it once.
await ImportRunSettings.AddDamagedAsync(bed.Library.Db.Settings, run.Id, [damaged.Id], CancellationToken.None);
Assert.AreEqual(1, (await bed.Review.GetSummaryAsync(run.Id)).Damaged);
}
private sealed class SyncProgress(Action<ImportProgress> report) : IProgress<ImportProgress>
{
public void Report(ImportProgress value) => report(value);
@@ -48,6 +48,60 @@ public sealed class DamagedImageTests
Assert.IsFalse(DamagedImage.IsFileDamaged(temp.Combine("non-c-e.jpg")), "un file che non c'è non è danneggiato");
}
[TestMethod]
public void ThePictureOverTheLimitOrAFormatFebeDoesNotDecodeIsToldFromItsFirstBytes()
{
// 20,000 × 20,000 = 400 megapixels: over the limit, never damaged, so never read whole for nothing.
var ihdr = Febe.Tests.Imaging.TestImages.Ihdr(20_000, 20_000, 8, 6);
var hugePng = Febe.Tests.Imaging.TestImages.Png(("IHDR", ihdr), ("IDAT", new byte[64]), ("IEND", []));
Assert.AreEqual(400_000_000L, ImageDecoding.HeaderPixels(Febe.Core.Codecs.Images.ImageFormat.Png, hugePng));
Assert.IsFalse(ImageDecoding.MayBeDamaged(hugePng));
byte[] gif = [.. "GIF89a"u8, 0x10, 0x27, 0x10, 0x27, 0, 0, 0];
Assert.AreEqual(100_000_000L, ImageDecoding.HeaderPixels(Febe.Core.Codecs.Images.ImageFormat.Gif, gif));
byte[] vp8x = [.. "RIFF"u8, 0, 0, 0, 0, .. "WEBPVP8X"u8, 10, 0, 0, 0, 0, 0, 0, 0, 0x0F, 0x27, 0, 0x0F, 0x27, 0];
Assert.AreEqual(100_000_000L, ImageDecoding.HeaderPixels(Febe.Core.Codecs.Images.ImageFormat.WebP, vp8x), "VP8X: 10,000 × 10,000");
byte[] heic = [0, 0, 0, 24, .. "ftypheic"u8, 0, 0, 0, 0, .. "mif1heic"u8];
Assert.IsFalse(ImageDecoding.MayBeDamaged(heic));
Assert.IsFalse(ImageDecoding.MayBeDamaged(new byte[64]), "un formato sconosciuto");
using var scene = TestImages.Scene(7, 120, 90);
var png = TestImages.Png(scene);
Assert.IsTrue(ImageDecoding.MayBeDamaged(png), "un PNG piccolo va guardato tutto");
Assert.IsTrue(ImageDecoding.MayBeDamaged(TestImages.Jpeg(scene)), "un JPEG si decodifica ridotto: va guardato tutto");
}
[TestMethod]
public async Task TheViewerAsksAsynchronouslyAndTheSameFileIsAnsweredOnce()
{
var ct = CancellationToken.None;
using var temp = new TempFolder();
using var scene = TestImages.Scene(8, 200, 150);
var whole = TestImages.Jpeg(scene);
var cutPath = temp.Combine("tagliata.jpg");
var wholePath = temp.Combine("intera.jpg");
var hugePath = temp.Combine("enorme.png");
File.WriteAllBytes(cutPath, whole[..(whole.Length / 2)]);
File.WriteAllBytes(wholePath, whole);
var ihdr = Febe.Tests.Imaging.TestImages.Ihdr(20_000, 20_000, 8, 6);
File.WriteAllBytes(hugePath, [.. Febe.Tests.Imaging.TestImages.Png(("IHDR", ihdr)), .. new byte[600_000]]);
Assert.IsTrue(await DamagedImage.IsFileDamagedAsync(cutPath, ct));
Assert.IsFalse(await DamagedImage.IsFileDamagedAsync(wholePath, ct));
Assert.IsFalse(await DamagedImage.IsFileDamagedAsync(hugePath, ct), "oltre il limite: non danneggiato");
Assert.IsFalse(DamagedImage.IsFileDamaged(hugePath));
Assert.IsFalse(await DamagedImage.IsFileDamagedAsync(temp.Combine("non-c-e.jpg"), ct));
// The answer is kept for the same file: a file locked for reading still gets it. A changed file is looked at again.
using (new FileStream(cutPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
Assert.IsTrue(await DamagedImage.IsFileDamagedAsync(cutPath, ct), "la risposta di prima, senza rileggere");
}
File.WriteAllBytes(cutPath, whole);
Assert.IsFalse(await DamagedImage.IsFileDamagedAsync(cutPath, ct), "il file cambiato si guarda di nuovo");
}
[TestMethod]
public async Task ADamagedPhotoIsStoredWithItsShaButNoThumbnailOrHashAndStays()
{
@@ -179,6 +179,43 @@ public sealed class HeifDecoderTests
Assert.AreEqual((picture.Frame.Height, picture.Frame.Width), ImageDecoding.ReadSize(stream));
}
[TestMethod]
[DataRow("mif2", null, DisplayName = "marca principale mif2")]
[DataRow("MiHE", null, DisplayName = "marca principale MiHE")]
[DataRow("isom", "heic", DisplayName = "heic solo fra le marche compatibili")]
public void TheImageFacadeTakesEveryBrandTheHeifDecoderTakes(string major, string? compatibleOnly)
{
// The facade picks the decoder from the first bytes: it must take every file HeifDecoder.Looks takes,
// or such a HEIC would lose its thumbnail, its fingerprint and its size.
var picture = CodedPicture.First(Tiles[0]);
var builder = new HeifBuilder { Brand = major };
if (compatibleOnly is not null)
{
builder.CompatibleBrands = ["isom", compatibleOnly];
}
var hvcC = builder.Property(HeifBuilder.HvcCProperty(picture.HvcC));
var ispe = builder.Property(HeifBuilder.Ispe(picture.Frame.Width, picture.Frame.Height));
builder.Item(1, "hvc1", picture.Data, -hvcC, ispe);
var file = builder.Build();
Assert.IsTrue(HeifDecoder.Looks(file));
Assert.AreEqual(ImageFormat.Heif, ImageFormatSniffer.Detect(file));
using (var image = ImageDecoder.Decode(file, out _))
{
CollectionAssert.AreEqual(Rgba(picture.Frame), image.ToArray());
}
using (var stream = new MemoryStream(file))
{
Assert.AreEqual((picture.Frame.Width, picture.Frame.Height), ImageDecoding.ReadSize(stream));
}
using var temp = new TempFolder("marca-heic");
var store = new ThumbnailStore(temp.Combine("miniature"));
Assert.IsTrue(store.Create(new string('b', 64), new MemoryStream(file)), "miniatura");
Assert.IsNotNull(PerceptualHash.Compute(new MemoryStream(file)), "impronta visiva");
}
[TestMethod]
public void TheCleanApertureCutsThePicture()
{
+5 -1
View File
@@ -95,6 +95,9 @@ internal sealed class HeifBuilder
/// <summary>Major brand of the ftyp box.</summary>
public string Brand { get; set; } = "heic";
/// <summary>Compatible brands of the ftyp box; null means «mif1» and the major brand.</summary>
public string[]? CompatibleBrands { get; set; }
/// <summary>The item data goes into idat instead of mdat.</summary>
public bool InIdat { get; set; }
@@ -157,7 +160,8 @@ internal sealed class HeifBuilder
public byte[] Build()
{
var ftyp = Box("ftyp", [.. Encoding.ASCII.GetBytes(Brand), 0, 0, 0, 0, .. "mif1"u8, .. Encoding.ASCII.GetBytes(Brand)]);
var compatible = CompatibleBrands ?? ["mif1", Brand];
var ftyp = Box("ftyp", [.. Encoding.ASCII.GetBytes(Brand), 0, 0, 0, 0, .. compatible.SelectMany(Encoding.ASCII.GetBytes)]);
// The meta box is built twice: the first time only to learn its size, so that the offsets into mdat are known.
var meta = Meta(0);
@@ -17,6 +17,9 @@ namespace Febe.Tests.Packaging;
/// </summary>
public sealed partial class PipelineTests
{
// The tests that run the cleanup script on the fake daemon take about a minute each on Windows (Git Bash): they run
// one at a time after the parallel ones ([DoNotParallelize]), or next to the conformance suites of the video
// decoders they went past their limit of five minutes in a full local run.
private const string RegistryApi = "http://gitea.invalid/api/v1";
private const string WeeklyStep = "Pulizia completa del demone Docker e del registro";
@@ -212,6 +215,7 @@ public sealed partial class PipelineTests
}
[TestMethod]
[DoNotParallelize]
[Timeout(300_000, CooperativeCancellation = true)]
public async Task OnADaemonSharedWithARealFebeTheCleanupOfTheCiTakesOnlyWhatTheCiMade()
{
@@ -250,6 +254,7 @@ public sealed partial class PipelineTests
}
[TestMethod]
[DoNotParallelize]
[Timeout(300_000, CooperativeCancellation = true)]
public async Task AfterEveryRunOnlyWhatNobodyUsesGoesAndADaemonThatRefusesIsOnlyAWarning()
{
@@ -275,6 +280,7 @@ public sealed partial class PipelineTests
}
[TestMethod]
[DoNotParallelize]
[Timeout(300_000, CooperativeCancellation = true)]
public async Task TheCompleteCleanupTakesWhatNobodyUsesAndNeverAContainerVolumeOrNetworkOfAnotherProject()
{
@@ -328,6 +334,7 @@ public sealed partial class PipelineTests
}
[TestMethod]
[DoNotParallelize]
[Timeout(300_000, CooperativeCancellation = true)]
public async Task TheDryRunListsWhatTheCleanupWouldTakeAndTouchesNothing()
{
@@ -394,6 +401,7 @@ public sealed partial class PipelineTests
}
[TestMethod]
[DoNotParallelize]
[Timeout(300_000, CooperativeCancellation = true)]
public async Task OnTheContainerdStoreTheCleanupSaysSoAndTheAgesOfTheDryRunAreOnlyIndicative()
{
@@ -529,6 +537,7 @@ public sealed partial class PipelineTests
}
[TestMethod]
[DoNotParallelize]
[Timeout(300_000, CooperativeCancellation = true)]
public async Task TheRegistryCleanupDeletesOnlyTheChosenTagsNeverPrintsTheTokenAndARefusalIsOnlyAWarning()
{
+11 -4
View File
@@ -45,10 +45,14 @@ public sealed partial class InHouseAssetsTests
var families = stack.Groups[1].Value.Split(',', StringSplitOptions.TrimEntries);
Assert.AreEqual("system-ui", families[0], "prima il carattere del sistema");
Assert.AreEqual("sans-serif", families[^1], "e in fondo il generico");
CollectionAssert.Contains(families, "\"Segoe UI\"");
CollectionAssert.Contains(families, "Roboto");
CollectionAssert.Contains(families, "Cantarell");
CollectionAssert.Contains(families, "\"Noto Sans\"");
// Exactly the stack of the specification (appendix B, «pila dei caratteri di sistema»), nothing more: no name of a
// font the Docker image leaves out (Liberation).
var specification = File.ReadAllText(Febe.Tests.Desktop.Support.Repository.PathOf("docs", "SPECIFICA.md"));
var stated = SpecificationStack().Match(specification);
Assert.IsTrue(stated.Success, "la pila dell'appendice B");
Assert.AreEqual(stated.Groups[1].Value, stack.Groups[1].Value.Trim());
Assert.DoesNotContain("Liberation", css);
foreach (var page in new[] { "index.html", "accesso.html" })
{
@@ -621,6 +625,9 @@ public sealed partial class InHouseAssetsTests
Assert.IsGreaterThan(100, looked, "i file del programma sono stati letti");
}
[GeneratedRegex(@"pila dei caratteri di sistema `([^`]+)`")]
private static partial Regex SpecificationStack();
[GeneratedRegex(@"--carattere:([^;]+);")]
private static partial Regex CharacterToken();
+110
View File
@@ -0,0 +1,110 @@
using Febe.Tests.Desktop.Support;
using Febe.Tests.Web.Support;
namespace Febe.Tests.Web;
/// <summary>
/// The modules of the interface load: a mistake that stops one module from parsing breaks every page importing it, and
/// the Chromium tests that would see it run only in the CI. <see cref="ScriptCheck"/> reads them without a browser.
/// </summary>
[TestClass]
public sealed class ScriptSyntaxTests
{
[TestMethod]
public void EveryModuleOfTheInterfaceReadsWithoutTheMistakesThatStopItLoading()
{
var root = Repository.PathOf("src", "Febe.Web", "wwwroot");
var files = Directory.GetFiles(root, "*.js", SearchOption.AllDirectories);
Assert.IsGreaterThan(30, files.Length, "the modules of the interface");
var problems = new List<string>();
foreach (var file in files)
{
var name = Path.GetRelativePath(root, file);
problems.AddRange(ScriptCheck.Problems(File.ReadAllText(file)).Select(p => $"{name}, {p}"));
}
Assert.IsEmpty(problems, string.Join(Environment.NewLine, problems));
}
[TestMethod]
public void EveryStaticImportNamesSomethingTheOtherModuleExports()
{
var root = Repository.PathOf("src", "Febe.Web", "wwwroot");
var problems = new List<string>();
var checkedNames = 0;
foreach (var file in Directory.GetFiles(root, "*.js", SearchOption.AllDirectories))
{
foreach (var (from, names, line) in ScriptCheck.Imports(File.ReadAllText(file)))
{
if (!from.StartsWith('.'))
{
continue;
}
var target = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(file)!, from));
var where = $"{Path.GetRelativePath(root, file)}, riga {line}";
if (!File.Exists(target))
{
problems.Add($"{where}: «{from}» non esiste");
continue;
}
var exports = ScriptCheck.Exports(File.ReadAllText(target));
foreach (var name in names)
{
checkedNames++;
if (!exports.Contains(name))
{
problems.Add($"{where}: «{from}» non esporta «{name}»");
}
}
}
}
Assert.IsGreaterThan(50, checkedNames);
Assert.IsEmpty(problems, string.Join(Environment.NewLine, problems));
}
[TestMethod]
[DataRow("export function box(saved, page) {\n if (!saved) return null;\n let saved = null;\n}", "«saved» dichiarato di nuovo con let (già parametro", DisplayName = "parametro ridichiarato (connection.js, b29b35a)")]
[DataRow("const show = (value) => { const value = 1; };", "«value» dichiarato di nuovo", DisplayName = "parametro di una freccia")]
[DataRow("items.map(x => { let x = 2; return x; });", "«x» dichiarato di nuovo", DisplayName = "parametro senza parentesi")]
[DataRow("function f() { let a = 1; if (a) { let b; } const a = 2; }", "«a» dichiarato di nuovo con const", DisplayName = "due volte nello stesso blocco")]
[DataRow("import { h } from './dom.js';\nconst h = 1;", "«h» dichiarato di nuovo con const (già import", DisplayName = "nome già importato")]
[DataRow("class A { m(p) { class p {} } }", "«p» dichiarato di nuovo con class", DisplayName = "classe con il nome di un parametro")]
[DataRow("function f() { if (x) { return 1; }", "mai chiusa", DisplayName = "parentesi graffa mai chiusa")]
[DataRow("const a = [1, 2);", "chiude «[»", DisplayName = "parentesi che non corrispondono")]
[DataRow("const s = 'non chiusa;\n", "stringa non chiusa", DisplayName = "stringa non chiusa")]
[DataRow("const s = `a ${b} c;\n", "modello fra apici inversi non chiuso", DisplayName = "modello non chiuso")]
public void TheCheckFindsTheMistakesThatStopAModuleLoading(string source, string expected)
{
var problems = ScriptCheck.Problems(source);
Assert.IsTrue(problems.Any(p => p.Contains(expected, StringComparison.Ordinal)), string.Join(" | ", problems.DefaultIfEmpty("(nessuno)")));
}
[TestMethod]
[DataRow("export function box(saved, page) {\n let stored = null;\n const show = (value) => { stored = value; };\n}", DisplayName = "la correzione di connection.js")]
[DataRow("for (let i = 0; i < 3; i++) { let i2 = i; }\nfor (let i = 0; i < 3; i++) { const j = i; }", DisplayName = "variabili dei cicli")]
[DataRow("const re = /a{2}[/}]\\//g; const half = 4 / 2; const t = `x ${ { a: 1 }.a } ${`y ${1}`}`;", DisplayName = "espressioni regolari, divisioni e modelli annidati")]
[DataRow("function f(a) { { let a = 1; } if (a) { const a = 2; } }", DisplayName = "lo stesso nome in un blocco interno")]
[DataRow("const o = { let: 1, const: 2 }; o.let = o.const;", DisplayName = "proprietà con nomi di parole chiave")]
[DataRow("try { x(); } catch (error) { console.log(error); }\nconst error = 1;", DisplayName = "parametro di catch e nome fuori")]
[DataRow("// a comment with ' and ` and {\n/* and } */ const a = \"}\";", DisplayName = "commenti e stringhe con parentesi")]
public void TheCheckLeavesValidCodeAlone(string source)
{
var problems = ScriptCheck.Problems(source);
Assert.IsEmpty(problems, string.Join(" | ", problems));
}
[TestMethod]
public void ImportsAndExportsAreReadByTheirNames()
{
var exports = ScriptCheck.Exports("export function a() {}\nexport async function b() {}\nexport const c = 1;\nexport class D {}\nconst e = 1, f = 2;\nexport { e, f as g };\nexport default a;");
CollectionAssert.AreEquivalent(new[] { "a", "b", "c", "D", "e", "g", "default" }, exports.ToArray());
var imports = ScriptCheck.Imports("import { a, b as c } from './x.js';\nimport * as y from './y.js';\nconst z = await import('./z.js');");
Assert.HasCount(2, imports);
Assert.AreEqual("./x.js", imports[0].From);
CollectionAssert.AreEqual(new[] { "a", "b" }, imports[0].Names);
Assert.IsEmpty(imports[1].Names);
}
}
+610
View File
@@ -0,0 +1,610 @@
using System.Text;
namespace Febe.Tests.Web.Support;
/// <summary>
/// A small check of the interface's ES modules that runs without a browser (the Chromium tests run only in the CI): it
/// reads the tokens of a module — comments, strings, template literals, regular expressions — and finds the mistakes
/// that stop a whole module from loading, so that every page importing it breaks: brackets that do not match, a
/// <c>let</c>, <c>const</c> or <c>class</c> declared twice in one block or with the name of a parameter of its function,
/// or of an import, and a static import of a name the other module does not export. Not a JavaScript parser: what it
/// does not understand (destructured bindings, <c>var</c>) it leaves alone rather than guess.
/// </summary>
internal static class ScriptCheck
{
private static readonly HashSet<string> RegexAfterWords = new(StringComparer.Ordinal)
{
"return", "typeof", "case", "do", "else", "in", "of", "new", "delete", "void", "throw", "instanceof", "yield", "await",
};
private static readonly HashSet<string> NotFunctionBefore = new(StringComparer.Ordinal)
{
"if", "for", "while", "switch", "with", "return", "typeof", "await", "void", "delete", "in", "of", "new", "yield",
};
private static readonly HashSet<string> Reserved = new(StringComparer.Ordinal)
{
"if", "for", "while", "switch", "with", "return", "typeof", "await", "void", "delete", "in", "of", "new", "yield",
"function", "class", "const", "let", "var", "this", "super", "null", "true", "false", "else", "do", "try", "catch",
"finally", "throw", "case", "default", "break", "continue", "import", "export", "async", "instanceof",
};
internal enum Kind
{
Word,
Punct,
Text,
Number,
Regex,
}
internal readonly record struct Token(Kind Kind, string Value, int Line);
/// <summary>The problems found in the source of one module, each with its line; empty when it reads cleanly.</summary>
public static List<string> Problems(string source)
{
var problems = new List<string>();
List<Token> tokens;
try
{
tokens = Tokens(source);
}
catch (FormatException ex)
{
problems.Add(ex.Message);
return problems;
}
CheckScopes(tokens, problems);
return problems;
}
/// <summary>The names a module exports (<c>export function</c>, <c>const</c>, <c>let</c>, <c>class</c>, <c>{ a as b }</c>, default).</summary>
public static HashSet<string> Exports(string source)
{
var names = new HashSet<string>(StringComparer.Ordinal);
var tokens = Tokens(source);
for (var i = 0; i < tokens.Count - 1; i++)
{
if (!IsWord(tokens[i], "export"))
{
continue;
}
var j = i + 1;
if (IsWord(tokens[j], "default"))
{
names.Add("default");
continue;
}
if (IsWord(tokens[j], "async"))
{
j++;
}
if (j < tokens.Count && tokens[j].Kind == Kind.Word && tokens[j].Value is "function" or "const" or "let" or "var" or "class")
{
j++;
if (j < tokens.Count && IsPunct(tokens[j], "*"))
{
j++;
}
if (j < tokens.Count && tokens[j].Kind == Kind.Word)
{
names.Add(tokens[j].Value);
}
}
else if (j < tokens.Count && IsPunct(tokens[j], "{"))
{
for (j++; j < tokens.Count && !IsPunct(tokens[j], "}"); j++)
{
if (tokens[j].Kind == Kind.Word && (j + 1 >= tokens.Count || IsPunct(tokens[j + 1], ",") || IsPunct(tokens[j + 1], "}")))
{
names.Add(tokens[j].Value);
}
}
}
}
return names;
}
/// <summary>The static imports of a module: the module named and the names taken from it (not «* as» nor default).</summary>
public static List<(string From, List<string> Names, int Line)> Imports(string source)
{
var imports = new List<(string, List<string>, int)>();
var tokens = Tokens(source);
for (var i = 0; i < tokens.Count - 1; i++)
{
if (!IsWord(tokens[i], "import") || IsPunct(tokens[i + 1], "(") || IsPunct(tokens[i + 1], "."))
{
continue;
}
var names = new List<string>();
var j = i + 1;
for (; j < tokens.Count && !IsWord(tokens[j], "from") && tokens[j].Kind != Kind.Text; j++)
{
if (IsPunct(tokens[j], "{"))
{
for (j++; j < tokens.Count && !IsPunct(tokens[j], "}"); j++)
{
if (tokens[j].Kind == Kind.Word && !IsWord(tokens[j], "as") && (j == 0 || !IsWord(tokens[j - 1], "as")))
{
names.Add(tokens[j].Value);
}
}
}
}
if (j < tokens.Count && IsWord(tokens[j], "from"))
{
j++;
}
if (j < tokens.Count && tokens[j].Kind == Kind.Text)
{
imports.Add((tokens[j].Value, names, tokens[i].Line));
}
}
return imports;
}
private static bool IsWord(Token token, string value) => token.Kind == Kind.Word && token.Value == value;
private static bool IsPunct(Token token, string value) => token.Kind == Kind.Punct && token.Value == value;
/// <summary>The tokens of the source; throws <see cref="FormatException"/> for an unfinished string, comment or regex.</summary>
internal static List<Token> Tokens(string s)
{
var tokens = new List<Token>();
// Braces opened in code: '{' an ordinary one, 'E' the «${» of a template literal.
var braces = new Stack<char>();
var line = 1;
var i = 0;
var inTemplate = false;
bool RegexMayStart()
{
if (tokens.Count == 0)
{
return true;
}
var last = tokens[^1];
return last.Kind switch
{
Kind.Punct => last.Value is not (")" or "]" or "}"),
Kind.Word => RegexAfterWords.Contains(last.Value),
_ => false,
};
}
void ScanTemplate()
{
// From just after a backtick or the «}» of an expression, up to the closing backtick or the next «${».
var start = line;
var text = new StringBuilder();
while (true)
{
if (i >= s.Length)
{
throw new FormatException($"riga {start}: modello fra apici inversi non chiuso");
}
var c = s[i];
if (c == '\\')
{
i += 2;
continue;
}
if (c == '\n')
{
line++;
}
if (c == '`')
{
i++;
inTemplate = false;
tokens.Add(new Token(Kind.Text, text.ToString(), start));
return;
}
if (c == '$' && i + 1 < s.Length && s[i + 1] == '{')
{
i += 2;
braces.Push('E');
inTemplate = false;
tokens.Add(new Token(Kind.Text, text.ToString(), start));
tokens.Add(new Token(Kind.Punct, "${", line));
return;
}
text.Append(c);
i++;
}
}
while (i < s.Length || inTemplate)
{
if (inTemplate)
{
ScanTemplate();
continue;
}
var c = s[i];
if (c == '\n')
{
line++;
i++;
continue;
}
if (char.IsWhiteSpace(c))
{
i++;
continue;
}
if (c == '/' && i + 1 < s.Length && s[i + 1] == '/')
{
while (i < s.Length && s[i] != '\n')
{
i++;
}
continue;
}
if (c == '/' && i + 1 < s.Length && s[i + 1] == '*')
{
var end = s.IndexOf("*/", i + 2, StringComparison.Ordinal);
if (end < 0)
{
throw new FormatException($"riga {line}: commento non chiuso");
}
line += s.AsSpan(i, end - i).Count('\n');
i = end + 2;
continue;
}
if (c is '\'' or '"')
{
i++;
var text = new StringBuilder();
while (true)
{
if (i >= s.Length || s[i] == '\n')
{
throw new FormatException($"riga {line}: stringa non chiusa");
}
if (s[i] == '\\')
{
text.Append(s[i + 1]);
i += 2;
continue;
}
if (s[i] == c)
{
i++;
break;
}
text.Append(s[i++]);
}
tokens.Add(new Token(Kind.Text, text.ToString(), line));
continue;
}
if (c == '`')
{
i++;
inTemplate = true;
continue;
}
if (c == '/' && RegexMayStart())
{
var start = i++;
var inClass = false;
while (true)
{
if (i >= s.Length || s[i] == '\n')
{
throw new FormatException($"riga {line}: espressione regolare non chiusa");
}
if (s[i] == '\\')
{
i += 2;
continue;
}
if (s[i] == '[')
{
inClass = true;
}
else if (s[i] == ']')
{
inClass = false;
}
else if (s[i] == '/' && !inClass)
{
i++;
break;
}
i++;
}
while (i < s.Length && char.IsAsciiLetter(s[i]))
{
i++;
}
tokens.Add(new Token(Kind.Regex, s[start..i], line));
continue;
}
if (char.IsLetter(c) || c is '_' or '$' or '#')
{
var start = i++;
while (i < s.Length && (char.IsLetterOrDigit(s[i]) || s[i] is '_' or '$'))
{
i++;
}
tokens.Add(new Token(Kind.Word, s[start..i], line));
continue;
}
if (char.IsAsciiDigit(c) || (c == '.' && i + 1 < s.Length && char.IsAsciiDigit(s[i + 1])))
{
var start = i++;
while (i < s.Length && (char.IsAsciiLetterOrDigit(s[i]) || s[i] is '.' or '_'))
{
i++;
}
tokens.Add(new Token(Kind.Number, s[start..i], line));
continue;
}
if (c == '{')
{
braces.Push('{');
}
else if (c == '}')
{
if (braces.Count > 0 && braces.Peek() == 'E')
{
braces.Pop();
i++;
tokens.Add(new Token(Kind.Punct, "}$", line));
inTemplate = true;
continue;
}
if (braces.Count > 0)
{
braces.Pop();
}
}
// The punctuators that matter here; any other is one character.
string[] longest = ["...", "=>", "?.", "??", "===", "!==", "==", "!=", "&&", "||", "**", "<=", ">=", "++", "--"];
var punct = longest.FirstOrDefault(p => string.CompareOrdinal(s, i, p, 0, p.Length) == 0) ?? c.ToString();
tokens.Add(new Token(Kind.Punct, punct, line));
i += punct.Length;
}
return tokens;
}
private sealed class Frame(char open, int line, int start)
{
public char Open { get; } = open;
public int Line { get; } = line;
/// <summary>Index of the opening token.</summary>
public int Start { get; } = start;
/// <summary>Names declared in this block with let, const or class, or as parameters (for a function body).</summary>
public Dictionary<string, string> Names { get; } = new(StringComparer.Ordinal);
}
private static void CheckScopes(List<Token> tokens, List<string> problems)
{
var frames = new Stack<Frame>();
frames.Push(new Frame('m', 1, -1));
List<string>? pendingParams = null;
var pendingAt = -1;
void Declare(string name, string how, int line)
{
var scope = frames.Peek();
if (scope.Names.TryGetValue(name, out var before))
{
problems.Add($"riga {line}: «{name}» dichiarato di nuovo con {how} (già {before} nello stesso blocco)");
return;
}
scope.Names[name] = how;
}
for (var i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var prev = i > 0 ? tokens[i - 1] : default;
if (token.Kind == Kind.Punct)
{
switch (token.Value)
{
case "{":
{
var frame = new Frame('{', token.Line, i);
if (pendingParams is not null && pendingAt == i)
{
foreach (var name in pendingParams)
{
frame.Names.TryAdd(name, "parametro");
}
}
frames.Push(frame);
pendingParams = null;
continue;
}
case "(" or "[" or "${":
frames.Push(new Frame(token.Value[0], token.Line, i));
continue;
case "}" or ")" or "]" or "}$":
{
var open = token.Value switch { "}" => '{', ")" => '(', "]" => '[', _ => '$' };
if (frames.Count <= 1 || frames.Peek().Open != open)
{
var top = frames.Peek();
problems.Add(top.Open == 'm'
? $"riga {token.Line}: «{token.Value[0]}» senza apertura"
: $"riga {token.Line}: «{token.Value[0]}» chiude «{top.Open}» aperta alla riga {top.Line}");
return;
}
var closed = frames.Pop();
if (open == '(')
{
OnParenClosed(tokens, closed.Start, i, ref pendingParams, ref pendingAt);
}
continue;
}
case "=>":
if (prev.Kind == Kind.Word && !Reserved.Contains(prev.Value))
{
pendingParams = [prev.Value];
pendingAt = i + 1;
}
else if (pendingParams is not null && pendingAt == i)
{
pendingAt = i + 1; // «(a, b) => {»
}
continue;
}
continue;
}
if (token.Kind != Kind.Word || i + 1 >= tokens.Count || (prev.Kind == Kind.Punct && prev.Value is "." or "?."))
{
continue;
}
var next = tokens[i + 1];
if (token.Value is "let" or "const" && next.Kind == Kind.Word && !Reserved.Contains(next.Value))
{
Declare(next.Value, token.Value, next.Line);
}
else if (token.Value == "class" && next.Kind == Kind.Word && !Reserved.Contains(next.Value) && StatementStart(tokens, i))
{
Declare(next.Value, "class", next.Line);
}
else if (token.Value == "import" && frames.Count == 1 && !IsPunct(next, "(") && !IsPunct(next, "."))
{
for (var j = i + 1; j < tokens.Count && !IsWord(tokens[j], "from") && tokens[j].Kind != Kind.Text; j++)
{
var t = tokens[j];
var after = j + 1 < tokens.Count ? tokens[j + 1] : default;
if (t.Kind == Kind.Word && !IsWord(t, "as") && !IsWord(after, "as") && !Reserved.Contains(t.Value))
{
Declare(t.Value, "import", t.Line);
}
}
}
}
if (frames.Count > 1)
{
var open = frames.Peek();
problems.Add($"riga {open.Line}: «{open.Open}» mai chiusa");
}
}
/// <summary>A «)» just closed: when a function body follows, the simple names of its parameters are kept for it.</summary>
private static void OnParenClosed(List<Token> tokens, int open, int close, ref List<string>? pending, ref int pendingAt)
{
var next = close + 1 < tokens.Count ? tokens[close + 1] : default;
var before = open > 0 ? tokens[open - 1] : default;
var arrow = IsPunct(next, "=>");
var body = IsPunct(next, "{") && before.Kind == Kind.Word && (!NotFunctionBefore.Contains(before.Value) || before.Value == "function");
if (!arrow && !body)
{
return;
}
var names = new List<string>();
var depth = 0;
var pieceStart = true;
for (var j = open + 1; j < close; j++)
{
var t = tokens[j];
if (t.Kind == Kind.Punct && t.Value is "(" or "[" or "{" or "${")
{
depth++;
}
else if (t.Kind == Kind.Punct && t.Value is ")" or "]" or "}" or "}$")
{
depth--;
}
if (depth == 0 && IsPunct(t, ","))
{
pieceStart = true;
continue;
}
if (pieceStart && depth == 0)
{
pieceStart = false;
var name = IsPunct(t, "...") && j + 1 < close ? tokens[j + 1] : t;
if (name.Kind == Kind.Word && !Reserved.Contains(name.Value))
{
names.Add(name.Value);
}
}
else if (pieceStart)
{
pieceStart = false; // a destructured parameter: left alone
}
}
pending = names;
pendingAt = close + 1;
}
/// <summary>True when the word at <paramref name="i"/> starts a statement (a declaration, not an expression).</summary>
private static bool StatementStart(List<Token> tokens, int i)
{
if (i == 0)
{
return true;
}
var prev = tokens[i - 1];
return (prev.Kind == Kind.Punct && prev.Value is ";" or "{" or "}") || IsWord(prev, "export") || IsWord(prev, "default");
}
}