diff --git a/modules/mesh-delivery-indexer/internal/fingerprint/fingerprint.go b/modules/mesh-delivery-indexer/internal/fingerprint/fingerprint.go index 6c3cd5637..dca0b6c16 100644 --- a/modules/mesh-delivery-indexer/internal/fingerprint/fingerprint.go +++ b/modules/mesh-delivery-indexer/internal/fingerprint/fingerprint.go @@ -381,6 +381,49 @@ func Packages(module string, files map[string]string) (requires string, packages return requires, packages, nil } +// NpmPackage is a mesh npm package's requirements' digest and its content digest, from files, every blob under the +// directory of its package.json (the path of the artifact that publishes it) by path relative to it with its git object id +// (design 47 H2 H-A-546 (1)). It refuses a listing with no package.json at that directory. +// +// Its one package is the npm name, its digest the hex sha256 of the sorted lines " " of every +// file under it but node_modules and the test files of `node --test`'s default patterns, which the Node build module's unit +// step runs (H-A-547): a file named `*.test.*`, `*-test.*`, `*_test.*` or `test.*`, and everything under a directory named +// test. The requirements' digest is the hex sha256 of the lines "package.json " and "package-lock.json " +// (the second absent with no lock file), as H-A-525 has it for go.mod and go.sum. +func NpmPackage(name string, files map[string]string) (requires string, packages []meshcatalog.PackagesByModuleValuePackagesItem, err error) { + pj, ok := files["package.json"] + if !ok { + return "", nil, fmt.Errorf("the npm package %s has no package.json at its directory", name) + } + req := "package.json " + pj + if lock, ok := files["package-lock.json"]; ok { + req += "\npackage-lock.json " + lock + } + sum := sha256.Sum256([]byte(req)) + var lines []string + for p, object := range files { + if npmLeftOut(p) { + continue + } + lines = append(lines, p+" "+object) + } + sort.Strings(lines) + s := sha256.Sum256([]byte(strings.Join(lines, "\n"))) + return hex.EncodeToString(sum[:]), []meshcatalog.PackagesByModuleValuePackagesItem{{Package: name, Digest: hex.EncodeToString(s[:])}}, nil +} + +// npmLeftOut is whether a file of an npm package, by its path relative to the package, leaves its digest: under +// node_modules or a directory named test, or a test file by `node --test`'s default patterns (H-A-547). +func npmLeftOut(p string) bool { + dir, file := path.Split(p) + for _, e := range strings.Split(strings.TrimSuffix(dir, "/"), "/") { + if e == "node_modules" || e == "test" { + return true + } + } + return strings.HasPrefix(file, "test.") || strings.Contains(file, ".test.") || strings.Contains(file, "-test.") || strings.Contains(file, "_test.") +} + // ignoredDir is whether the go tool takes no package from dir: an element named testdata, or starting with _ or . func ignoredDir(dir string) bool { for _, e := range strings.Split(dir, "/") { diff --git a/modules/mesh-delivery-indexer/internal/fingerprint/fingerprint_test.go b/modules/mesh-delivery-indexer/internal/fingerprint/fingerprint_test.go index 257e6781f..cbccd2319 100644 --- a/modules/mesh-delivery-indexer/internal/fingerprint/fingerprint_test.go +++ b/modules/mesh-delivery-indexer/internal/fingerprint/fingerprint_test.go @@ -216,6 +216,35 @@ func packageDigestIsItsOwnFiles(t *testing.T) { if _, _, err := Packages(sdk, map[string]string{"a.go": "x"}); err == nil { t.Error("a listing with no go.mod was taken as a module") } + // I11a/AC1 (design 47 H2 H-A-523, H-A-546 (1), H-A-547): an npm package's digest is its files under its package.json's + // directory, by its npm name, leaving out node_modules and node --test's test files; its requirements' digest is its + // package.json and its lock file. + npm := map[string]string{"package.json": "p1", "package-lock.json": "l1", "src/stdio.ts": "a", "dist/stdio.js": "b", + "src/stdio.test.ts": "t1", "src/a-test.ts": "t2", "src/a_test.mjs": "t3", "test.js": "t4", "test/x.ts": "t5", + "node_modules/x/index.js": "n"} + npmReq, npmPkgs, err := NpmPackage("@novox/mesh-sdk", npm) + if err != nil || len(npmPkgs) != 1 || npmPkgs[0].Package != "@novox/mesh-sdk" || npmPkgs[0].Digest == "" || npmReq == "" { + t.Fatalf("NpmPackage = %q, %+v, %v; want one package by its npm name", npmReq, npmPkgs, err) + } + for _, c := range []struct { + file string + moves bool + }{{"src/stdio.ts", true}, {"dist/stdio.js", true}, {"package.json", true}, {"src/stdio.test.ts", false}, {"src/a-test.ts", false}, + {"src/a_test.mjs", false}, {"test.js", false}, {"test/x.ts", false}, {"node_modules/x/index.js", false}} { + r, ps, _ := NpmPackage("@novox/mesh-sdk", with(npm, c.file, "zz")) + if moved := ps[0].Digest != npmPkgs[0].Digest; moved != c.moves { + t.Errorf("changing %s of the npm package moved its digest %v, want %v", c.file, moved, c.moves) + } + if c.file == "package.json" && r == npmReq { + t.Error("a changed package.json left the npm package's requirements' digest") + } + } + if r2, _, _ := NpmPackage("@novox/mesh-sdk", with(npm, "package-lock.json", "l2")); r2 == npmReq { + t.Error("a changed lock file left the npm package's requirements' digest") + } + if _, _, err := NpmPackage("@novox/mesh-sdk", map[string]string{"index.js": "x"}); err == nil { + t.Error("a listing with no package.json was taken as an npm package") + } } func with(m map[string]string, k, v string) map[string]string { diff --git a/modules/mesh-delivery-indexer/internal/index/packages.go b/modules/mesh-delivery-indexer/internal/index/packages.go index a730f4d14..8774d9950 100644 --- a/modules/mesh-delivery-indexer/internal/index/packages.go +++ b/modules/mesh-delivery-indexer/internal/index/packages.go @@ -18,6 +18,7 @@ import ( "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog" + "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/graph" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/trunk" "mesh-delivery-indexer/internal/fingerprint" @@ -282,7 +283,8 @@ func (ix *Indexer) publish(ctx context.Context, repository, commit string, held } modules, imports := reached(held) repo := trunk.RepositoryName(repository) - if len(modules[repo]) == 0 && len(imports[repo]) == 0 { + npm := ix.npmReached(ctx, repo, held) + if len(modules[repo]) == 0 && len(imports[repo]) == 0 && len(npm) == 0 { return nil } have := ix.publishedAll(ctx) @@ -300,7 +302,12 @@ func (ix *Indexer) publish(ctx context.Context, repository, commit string, held is = append(is, imp) } } - if len(ms) == 0 && len(is) == 0 { + for name := range npm { + if _, ok := have[name]; ok { + delete(npm, name) + } + } + if len(ms) == 0 && len(is) == 0 && len(npm) == 0 { return nil } modules[repo], imports[repo] = ms, is @@ -312,6 +319,15 @@ func (ix *Indexer) publish(ctx context.Context, repository, commit string, held } } got, gone, err := ix.packagesIn(ctx, repo, commit, modules[repo], imports[repo]) + if err == nil { + var npmGot map[string]meshcatalog.PackagesByModuleValue + if npmGot, err = ix.npmPackagesIn(ctx, repo, commit, npm); err == nil { + if got == nil { + got = map[string]meshcatalog.PackagesByModuleValue{} + } + maps.Copy(got, npmGot) + } + } if err != nil { ix.notPublished(ctx, repo, commit, err) return err @@ -358,6 +374,112 @@ func (ix *Indexer) publish(ctx context.Context, repository, commit string, held return nil } +// npmReached are the mesh npm packages of repository a held module's import set names, each with the directories its +// package.json may lie in: the module graph entry whose artifact publishes that npm name gives the repository and the +// artifact's paths under its module's directory (design 47 H2 H-A-546 (2), G §676), never a scope or the forge's prefix +// (H-A-539). A manifest that cannot be read publishes nothing this pass. +func (ix *Indexer) npmReached(ctx context.Context, repository string, held map[string]meshcatalog.ModulesByModuleValue) map[string][]string { + imported := map[string]bool{} + for _, m := range held { + if m.Inputs2 != nil { + for _, p := range m.Inputs2.Imports { + imported[p] = true + } + } + } + out := map[string][]string{} + if len(imported) == 0 { + return out + } + for name, cur := range held { + if cur.Manifest == "" || !trunk.SameRepository(cur.Repository, repository) { + continue + } + raw, m, err := ix.manifestRaw(ctx, cur.Manifest) + if err != nil || m.Build == nil { + continue + } + e := ix.withArtifacts(ctx, CatalogEntryOf(name, cur, m, raw, graph.Node{}), m) + base := cur.Path + if base == meshcatalogclient.RootPath { + base = "" + } + for _, a := range e.Artifacts { + if a.Package == nil || a.Package.Ecosystem != EcosystemNpm || !imported[a.Package.Name] { + continue + } + for _, b := range m.Build.Artifacts { + if ArtifactRefOf(name, b.Name) != a.Ref { + continue + } + roots := b.Paths + if len(roots) == 0 { + roots = []string{"."} + } + for _, r := range roots { + d := strings.TrimSuffix(path.Join(base, strings.TrimSuffix(r, "package.json")), "/") + if d == "." { + d = "" + } + if !slices.Contains(out[a.Package.Name], d) { + out[a.Package.Name] = append(out[a.Package.Name], d) + } + } + } + } + } + return out +} + +// npmPackagesIn are the npm packages of npm (each with the directories its package.json may lie in) as repository holds +// them at commit, read from the forge's listing (Files), by npm name: the first directory holding a package.json is the +// package's (H-A-546 (1)). A package no directory of which holds one is said and left out. +func (ix *Indexer) npmPackagesIn(ctx context.Context, repository, commit string, npm map[string][]string) (map[string]meshcatalog.PackagesByModuleValue, error) { + if ix.Files == nil || commit == "" || len(npm) == 0 { + return nil, nil + } + var dirs []string + for _, ds := range npm { + for _, d := range ds { + if !slices.Contains(dirs, d) { + dirs = append(dirs, d) + } + } + } + slices.Sort(dirs) + listings, err := waited(ctx, "git", "trees", func() (map[string]map[string]string, error) { return ix.Files(ctx, repository, commit, dirs) }) + if err != nil { + return nil, fmt.Errorf("the forge's listing of %s at %s (%s): %w", repository, commit, strings.Join(dirs, ", "), err) + } + out := map[string]meshcatalog.PackagesByModuleValue{} + for _, name := range slices.Sorted(maps.Keys(npm)) { + found := false + for _, d := range npm[name] { + files := listings[d] + if _, ok := files["package.json"]; !ok { + continue + } + requires, pkgs, err := fingerprint.NpmPackage(name, files) + if err != nil { + ix.logf("%s at %s: %v; it is not published", repository, commit, err) + break + } + dir := d + if dir == "" { + dir = meshcatalogclient.RootPath + } + out[name] = meshcatalog.PackagesByModuleValue{Module: name, Repository: trunk.RepositoryName(repository), Dir: dir, Commit: commit, + Requires: requires, Packages: pkgs} + found = true + break + } + if !found { + ix.logf("%s at %s: no directory of %s holds its package.json (%s), so it has no digest", repository, commit, name, strings.Join(npm[name], ", ")) + } + } + return out, nil +} + // PackagesNotPublishedKind is the finding of a repository whose packages a take-in's publish could not list, for a reason // that is not a gone directory (design 47 H H-A-233, H-A-234): scope merge, id the repository, with the forge's words; // raised at once and cleared at the repository's next publish that lists. diff --git a/modules/mesh-delivery-indexer/internal/index/packages_gone_test.go b/modules/mesh-delivery-indexer/internal/index/packages_gone_test.go index 4c3b23c0d..b56415076 100644 --- a/modules/mesh-delivery-indexer/internal/index/packages_gone_test.go +++ b/modules/mesh-delivery-indexer/internal/index/packages_gone_test.go @@ -10,7 +10,10 @@ import ( "time" mcc "git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshconditionsclient" + "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog" + + "mesh-delivery-indexer/internal/fingerprint" ) // Design 47 H H-A-232 (1), H-A-233, H-A-234: a repository's packages are those in the merge's tree. The kept key of a @@ -190,4 +193,47 @@ func TestARepositorysPackagesAreThoseInTheMergesTree(t *testing.T) { t.Error("a commit with no tree raised no finding") } }) + // I11a/AC1 (design 47 H2 H-A-523, H-A-546 (1)(2), H-A-547): a take-in of a repository holding an npm mesh package a held module + // imports publishes it by its npm name, its repository and directory those of the module graph entry whose artifact publishes + // that name, its digest its files under that artifact's path. + t.Run("an npm package a held module imports is published by its npm name", func(t *testing.T) { + const npmName = "@novox/mesh-sdk" + manifest := `{"module":"mesh-sdk","version":"0.1","build":{"artifacts":[{"name":"ts","kind":"package","language":"typescript","paths":["ts"]}]}}` + digest := meshcatalogclient.ManifestDigest([]byte(manifest)) + kept, err := meshcatalogclient.EncodeManifest(meshcatalog.ManifestsByDigestValue{Module: "mesh-sdk", Manifest: manifest}) + if err != nil { + t.Fatal(err) + } + listing := map[string]string{"package.json": "p1", "src/stdio.ts": "a", "src/stdio.test.ts": "t"} + var asked []string + ix := &Indexer{Module: testSelf, Packages: newMem(), Manifests: newMem(), Findings: newFindings(), Logf: t.Logf, + Files: func(_ context.Context, repository, _ string, dirs []string) (map[string]map[string]string, error) { + asked = append(asked, repository+" "+strings.Join(dirs, ",")) + return map[string]map[string]string{"ts": listing}, nil + }, + ReadFile: func(_ context.Context, repository, _, file string) ([]byte, error) { + if repository == "novox/mesh-sdk" && file == "ts/package.json" { + return []byte(`{"name":"` + npmName + `"}`), nil + } + return nil, nil + }} + key, _ := meshcatalogclient.ManifestsKey(digest) + ix.Manifests.(*memStore).put(key, kept) + held := map[string]meshcatalog.ModulesByModuleValue{ + "mesh-sdk": {Repository: "novox/mesh-sdk", Path: ".", Commit: merge, Manifest: digest}, + "view": {Repository: catalogueRepo, Inputs2: &meshcatalog.ModulesByModuleValueInputs2{Imports: []string{npmName}}}, + } + if err := ix.publish(ctx, "novox/mesh-sdk", merge, held, false, TrunkBranch); err != nil { + t.Fatal(err) + } + _, want, _ := fingerprint.NpmPackage(npmName, listing) + got, ok := ix.publishedAll(ctx)[npmName] + if !ok || got.Repository != "novox/mesh-sdk" || got.Dir != "ts" || got.Commit != merge || !reflect.DeepEqual(got.Packages, want) { + t.Fatalf("packages of %s = %+v (%v), want its digest %+v from novox/mesh-sdk at ts; asked %v", npmName, got, ok, want, asked) + } + // A take-in of a repository no held module's npm import is published from publishes none. + if err := ix.publish(ctx, catalogueRepo, merge, held, false, TrunkBranch); err != nil || len(asked) != 1 { + t.Errorf("a take-in of %s asked %v (%v), want no npm package read", catalogueRepo, asked, err) + } + }) } diff --git a/modules/mesh-delivery-indexer/internal/index/packages_values.go b/modules/mesh-delivery-indexer/internal/index/packages_values.go index 3ac6cbd38..2bc14a8d3 100644 --- a/modules/mesh-delivery-indexer/internal/index/packages_values.go +++ b/modules/mesh-delivery-indexer/internal/index/packages_values.go @@ -16,15 +16,18 @@ import ( // The values of the state packages (novox/hq ADR 0593 §2, ADR 0606 §1): the contract's types, written by the indexer // alone, so their writing rules are the indexer's (ADR 0634 §1: a holder's own logic stays with it). -// PackagesKey is the key of a mesh Go module (its module path) in the packages state: the path as a key part. It refuses -// a path that is no mesh Go module's. +// PackagesKey is the key of a mesh Go module (its module path) or a mesh npm package (its npm name, design 47 H2 H-A-523, +// H-A-546) in the packages state: the name as a key part. It refuses a name that is neither. func PackagesKey(module string) (string, error) { - if _, _, ok := trunk.PackageRepository(module); !ok { - return "", fmt.Errorf("index: %q is no mesh Go module's path (it starts with %s)", module, trunk.ForgeModulePrefix) + if _, _, ok := trunk.PackageRepository(module); !ok && !npmName.MatchString(module) { + return "", fmt.Errorf("index: %q is no mesh Go module's path (it starts with %s) and no npm package's name", module, trunk.ForgeModulePrefix) } return meshcatalog.PackagesByModuleKey(keys.EscapeName(module)), nil } +// npmName is the form of an npm package's name: lower case, optionally under a scope `@/`. +var npmName = regexp.MustCompile(`^(@[a-z0-9][a-z0-9._~-]*/)?[a-z0-9][a-z0-9._~-]*$`) + func checkPublished(p meshcatalog.PackagesByModuleValue) error { pkgs := make([][2]string, len(p.Packages)) for i, d := range p.Packages { @@ -38,6 +41,13 @@ var commitFull = regexp.MustCompile(`^[0-9a-f]{40}$`) // checkPublishedFields is the rule of a published module's value, over its fields (a series' contents hold the same). func checkPublishedFields(module, repository, dir, commit, requires string, at *time.Time, packages [][2]string) error { want, _, ok := trunk.PackageRepository(module) + if !ok && npmName.MatchString(module) { + // An npm package's repository is the one its publishing entry names, read from no prefix (H-A-546 (2)); it is one package. + want, ok = repository, repository != "" + if len(packages) != 1 || packages[0][0] != module { + return fmt.Errorf("index: the npm package %s names the packages %v, not itself alone", module, packages) + } + } switch { case !ok: return fmt.Errorf("index: %q is no mesh Go module's path (it starts with %s)", module, trunk.ForgeModulePrefix)