Backtestshugorun-20261024-162305#15103
Add importContext to resources.Copy
Our patch was judged better than the merged fix.
In this judgment, Patch A = our agent, Patch B = the merged fix.
The issue asks specifically for an `importContext` option on `resources.Copy` (with an optional STRING-or-MAP first argument) so the copied resource carries the context into css.Build, css.Sass, js.Build/Batch, and TailwindCSS. Patch A implements exactly that: it changes the template-level `resources.Copy` to accept a map or string, stores an unexported `ImportContext` on the cloned resource (following the `resources.Internal*` accessor pattern the issue suggests), threads it into `ResourceTransformationCtx`, and wires resolution into esbuild (css.Build/js.Build), js.Batch (as a fallback and for runners), PostCSS/Tailwind inline imports, dartsass and libsass. It also handles cache-key separation for in-memory resources with the same name but different content, dependency tracking for rebuilds, and the no-leak case where the original resource is built without context. Its tests cover each transformer plus invalid options, rebuilds, and the mount case; the only skips are the usual dartsass/libsass availability guards. Patch B takes a different design: it adds an `importContext` option directly to css.Build, css.Sass, css.TailwindCSS and js.Build options, and never touches `resources.Copy` at all. Whatever the merits of that alternative, it does not deliver what the issue requests, and the independent tests confirm it: all six issue-derived tests (CSS build via Copy, targetPath+importContext map, mount, js.Build, dartsass, optional target path) pass on A and fail on B exactly as on base. B also bundles a hashstructure dependency bump, a hashing refactor, a Page `Key()` removal, and a new `testinginternal` template namespace, which is unrelated churn with added risk. A resolves the issue; B does not.
Four judges ruled on this ticket in parallel, and the verdict comes from counting their votes. Each saw the issue and the two patches, labelled A and B in random order (two of them saw ours as A), with issue links and version numbers removed. Where tests could check the fix, they also saw the results of tests a separate agent wrote for the issue, run on both patches. None was told which patch was ours. The reasoning above is one judge's, shown verbatim.
Solve
1h 43m
Wall-clock time in the container
Full test suite
No new failures
2,496 passed · 9 skipped · 2,568 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
1,141vs 791 merged
Changed lines, ours vs merged
The issue
View on GitHubThe example below (and variations of it) isn't possible in Hugo:
{{ $r := resources.FromString "foo.css" "body { color: blue; }" }}
{{/* How do I get $r to resolve as an import in main.css? */}}
{{ $css := resources.Get "css/main.css" | css.Build }}
And in assets/css/main.js:
@import "foo.css" screen;
@import "bar.css" print;
The example above uses css.Build, but this is also relevant for (at least) css.Sass, js.Build and js.Batch. There are more or less ugly workardounds for the above (e.g. resources.Concat or passing in css vars in a map), but it would be nice to have a direct way that worked for all (I have a new proposal in mind that would need this).
I suggest we add importContext to resources.Copy and make the logic that's currently implemented in js.Batch also work for the other relevant funcs, e.g:
{{ $foo := resources.FromString "foo.css" "body { color: blue; }" }}
{{ $bar := resources.FromString "bar.css" "body { color: green; }" }}
{{ $main := resources.Get "css/main.css" | resources.Copy (dict "importContext" (slice $foo $bar)) }}
{{ $css := $main | css.Build }}
The current signature of resources.Copy is:
resources.Copy TARGETPATH RESOURCE
I suggest we
resources.Copy [STRING or MAP] RESOURCE
And make it optional (we can determine a path from RESOURCE). So for the MAP options it would look like:
{{ $opts := dict
"targetPath" "foo.css"
"importContext" (slice $foo $bar)
}}
In the above importContext is the same as described in inputContext -- which also allows constructs ala:
{{ $common := resources.Match "/js/headlessui/*.*" }}
{{ $importContext := (slice $.Page ($common.Mount "/js/headlessui" ".")) }}
{{ $opts := dict
"importContext" $importContext
}}
Some implementation hints:
- We would store this new importContext in some unexported field. I suggest we follow the pattern in the funcs
resources.Internal*to access this internal state. js.BatchtakesimportContextas an option. That import handling is more advanced than we need here, but we look at that for inspiriation/reuse.- I suggest that we start with
css.Buildand, once that looks good, implement it injs.Build/Batch,css.Sassandcss.TailwindCSS.
The two patches
docs/content/en/functions/resources/Copy.mdindex 208f6d65f..68d482210 100644@@ -6,7 +6,7 @@ params: functions_and_methods: aliases: [] returnType: resource.Resource- signatures: [resources.Copy TARGETPATH RESOURCE]+ signatures: ['resources.Copy [TARGETPATH|OPTIONS] RESOURCE'] --- ```go-html-template@@ -21,3 +21,36 @@ The `TARGETPATH` is relative to the server root. A leading slash is optional and > [!NOTE] > Use the `resources.Copy` function with global, page, and remote resources.++## Options++Instead of a target path, you can pass a map of options:++targetPath+: (`string`) The target path of the copy. If not set, the target path of the given resource is used.++importContext+: (`resource`, `page`, or `slice`) A set of resources to resolve imports from when the copy is processed by [`css.Build`], [`js.Build`], [`js.Batch`], [`css.Sass`], [`css.PostCSS`] (with `inlineImports` enabled), or [`css.TailwindCSS`]. This works the same way as the `importContext` option in [`js.Batch`], and is checked before the `assets` directory.++```go-html-template+{{ $foo := resources.FromString "foo.css" "body { color: blue; }" }}+{{ $bar := resources.FromString "bar.css" "body { color: green; }" }}+{{ $opts := dict "importContext" (slice $foo $bar) }}+{{ with resources.Get "css/main.css" | resources.Copy $opts | css.Build }}+ <link rel="stylesheet" href="{{ .RelPermalink }}">+{{ end }}+```++With `assets/css/main.css`:++```css+@import "foo.css" screen;+@import "bar.css" print;+```++[`css.Build`]: /functions/css/build/+[`css.PostCSS`]: /functions/css/postcss/+[`css.Sass`]: /functions/css/sass/+[`css.TailwindCSS`]: /functions/css/tailwindcss/+[`js.Batch`]: /functions/js/batch/+[`js.Build`]: /functions/js/build/internal/js/esbuild/batch.goindex 61c6b6d5c..41622a9e1 100644@@ -501,6 +501,14 @@ func (b *batcher) doBuild(ctx context.Context) (*Package, error) { runnerImpPath := paths.AddLeadingSlash(runnerKeyPath + "_runner" + vv.Compiled().Resource.MediaType().FirstSuffix.FullSuffix) t.Runners = append(t.Runners, scriptRunnerTemplateContext{opts: vv, Import: runnerImpPath}) addResource(g.id, runnerImpPath, vv.Compiled().Resource, false)+ if impCtx := resources.InternalResourceImportContext(vv.Compiled().Resource); impCtx != nil {+ // Import context set on the runner resource using resources.Copy.+ state.importerImportContext.Set(runnerImpPath, importContext{+ name: runnerKeyPath,+ resourceGetter: impCtx,+ dm: g.dependencyManager,+ })+ } } r, s, err := b.client.buildBatchGroup(ctx, t)@@ -1328,10 +1336,11 @@ func (s scriptOptions) compileOptions(m map[string]any, defaults defaultOptionVa v.Export = defaults.defaultExport } + // Fall back to any import context set on the resource using resources.Copy. compiled := scriptOptions{ Resource: v.Resource, Export: v.Export,- ImportContext: resource.NewCachedResourceGetter(v.ImportContext),+ ImportContext: resource.NewCachedResourceGetter(v.ImportContext, resources.InternalResourceImportContext(v.Resource)), Params: paramsJSON, } internal/js/esbuild/batch_integration_test.goindex ca85cb4a7..3213a48db 100644@@ -26,6 +26,7 @@ import ( "github.com/gohugoio/hugo/htesting" "github.com/gohugoio/hugo/hugolib" "github.com/gohugoio/hugo/internal/js/esbuild"+ "github.com/spf13/afero" ) // Used to test misc. error situations etc.@@ -733,3 +734,50 @@ console.log("config.params.id", id3); b.EditFileReplaceAll("assets/other/bar.css", ".bar-edit {", ".bar-edit2 {").Build() b.AssertFileContent("public/mybundle/reactbatch.css", ".bar-edit2 {") }++func TestBatchImportContextFromResourcesCopy(t *testing.T) {+ t.Parallel()++ files := `+-- hugo.toml --+disableKinds = ["taxonomy", "term", "page", "section", "rss", "sitemap"]+-- assets/js/main.js --+import { hello } from "hello.js";+console.log(hello);+-- assets/js/runner.js --+import { runnerdep } from "runnerdep.js";+export default function run(group) {+ console.log(runnerdep);+}+-- layouts/home.html --+{{ $hello := resources.FromString "hello.js" "export const hello = 'Hello from import context';" }}+{{ $runnerdep := resources.FromString "runnerdep.js" "export const runnerdep = 'Runner dep from import context';" }}+{{ $batch := js.Batch "mybatch" }}+{{ with $batch.Group "mygroup" }}+ {{ with .Script "main" }}+ {{ .SetOptions (dict "resource" (resources.Get "js/main.js" | resources.Copy (dict "importContext" $hello))) }}+ {{ end }}+ {{ with .Runner "run" }}+ {{ .SetOptions (dict "resource" (resources.Get "js/runner.js" | resources.Copy (dict "importContext" $runnerdep))) }}+ {{ end }}+{{ end }}+{{ with (templates.Defer (dict "key" "global")) }}+{{ range $k, $v := (js.Batch "mybatch").Build.Groups }}{{ range . }}{{ .RelPermalink }}|{{ end }}{{ end }}+{{ end }}+`++ b := hugolib.Test(t, files, hugolib.TestOptWithOSFs())++ b.AssertFileContent("public/mybatch/mygroup.js",+ "Hello from import context",+ )++ // The runner may be split out into a chunk.+ var all strings.Builder+ fis, err := afero.ReadDir(b.H.Fs.PublishDir, "mybatch")+ b.Assert(err, qt.IsNil)+ for _, fi := range fis {+ all.WriteString(b.FileContent(filepath.Join("public/mybatch", fi.Name())))+ }+ b.Assert(all.String(), qt.Contains, "Runner dep from import context")+}internal/js/esbuild/importcontext.gonew file mode 100644index 000000000..165c56c59@@ -0,0 +1,115 @@+// Copyright 2026 The Hugo Authors. All rights reserved.+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package esbuild++import (+ "context"+ "errors"+ "fmt"+ "path"+ "strings"++ "github.com/evanw/esbuild/pkg/api"+ "github.com/gohugoio/hugo/common/hmaps"+ "github.com/gohugoio/hugo/common/hugio"+ "github.com/gohugoio/hugo/identity"+ "github.com/gohugoio/hugo/resources"+ "github.com/gohugoio/hugo/resources/resource"+)++// SetImportContext configures opts to resolve imports using the given import context+// (see resources.Copy) before falling back to the default import resolution.+func (opts *Options) SetImportContext(ctx context.Context, importContext resource.ResourceGetter, dm identity.Manager) error {+ if importContext == nil {+ return nil+ }+ if opts.ImportOnResolveFunc != nil || opts.ImportOnLoadFunc != nil {+ return errors.New("import context cannot be combined with custom import resolvers")+ }+ if dm == nil {+ dm = identity.NopManager+ }++ importResource := hmaps.NewCache[string, resource.Resource]()++ opts.ImportOnResolveFunc = func(imp string, args api.OnResolveArgs) string {+ if args.Namespace == "file" {+ // Imported from a file not in /assets, e.g. in node_modules.+ return ""+ }+ var resolved resource.Resource+ if strings.HasPrefix(imp, ".") {+ if importer, ok := strings.CutPrefix(args.Importer, PrefixHugoVirtual); ok {+ // Relative import from a resource in the import context.+ resolved = ResolveResource(path.Join(path.Dir(importer), imp), importContext)+ } else if args.Importer != stdinImporter {+ // Relative import from a file in /assets, resolve it relative to that file.+ return ""+ }+ }+ if resolved == nil {+ resolved = ResolveResource(imp, importContext)+ }+ if resolved == nil {+ return ""+ }+ dm.AddIdentity(identity.FirstIdentity(resolved))+ resolvedPath := PrefixHugoVirtual + resources.InternalResourceTargetPath(resolved)+ importResource.Set(resolvedPath, resolved)+ return resolvedPath+ }++ opts.ImportOnLoadFunc = func(args api.OnLoadArgs) (string, error) {+ r, found := importResource.Get(args.Path)+ if !found {+ return "", nil+ }+ content, err := resources.InternalResourceSourceContent(ctx, r)+ if err != nil {+ return "", fmt.Errorf("failed to read import %q: %w", resources.InternalResourceSourcePathBestEffort(r), err)+ }+ return content, nil+ }++ opts.ErrorMessageResolveFunc = func(msg api.Message) *ErrorMessageResolved {+ if msg.Location == nil {+ return nil+ }+ r, found := importResource.Get(strings.TrimPrefix(msg.Location.File, NsHugoImportResolveFunc+":"))+ if !found {+ return nil+ }+ var contentr hugio.ReadSeekCloser+ if cp, ok := r.(hugio.ReadSeekCloserProvider); ok {+ contentr, _ = cp.ReadSeekCloser()+ }+ return &ErrorMessageResolved{+ Content: contentr,+ Path: resources.InternalResourceSourcePathBestEffort(r),+ Message: msg.Text,+ }+ }++ opts.ResolveSourceMapSource = func(s string) string {+ if r, found := importResource.Get(s); found {+ if ss := resources.InternalResourceSourcePath(r); ss != "" {+ return ss+ }+ return PrefixHugoMemory + s+ }+ return ""+ }++ return nil+}resources/image.goindex 467e23f26..7967b7cff 100644@@ -230,8 +230,8 @@ func (i *imageResource) Clone() resource.Resource { return ir } -func (i *imageResource) cloneTo(targetPath string) resource.Resource {- gr := i.baseResource.cloneTo(targetPath).(baseResource)+func (i *imageResource) cloneTo(opts CopyOptions) resource.Resource {+ gr := i.baseResource.cloneTo(opts).(baseResource) ir := &imageResource{ root: i.root, Image: i.WithSpec(gr),resources/import_context.gonew file mode 100644index 000000000..e9e732015@@ -0,0 +1,124 @@+// Copyright 2026 The Hugo Authors. All rights reserved.+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package resources++import (+ "context"+ "fmt"+ "strings"++ "github.com/gohugoio/hugo/common/hashing"+ "github.com/gohugoio/hugo/common/hreflect"+ "github.com/gohugoio/hugo/identity"+ "github.com/gohugoio/hugo/resources/resource"+)++// ImportContext holds a set of resources that can be used to resolve+// imports (e.g. CSS @import, JS import) when building a resource.+type ImportContext struct {+ // The resource getter used to resolve imports.+ Getter resource.ResourceGetter++ // A key identifying this import context.+ // Used to separate resources with different import contexts in the caches.+ Key string+}++// CopyOptions holds the options for Copy.+type CopyOptions struct {+ // The target path of the copy.+ // If empty, the target path of the source resource is used.+ TargetPath string++ // The import context to attach to the copy.+ // If nil, any import context on the source resource is preserved.+ ImportContext *ImportContext+}++// NewImportContext creates a new ImportContext from v, which can be a+// Resource, a Page (or anything else providing Resources), a ResourceGetter+// (e.g. from Resources.Mount) or a slice of any of these.+// The first match wins.+func NewImportContext(v any) (*ImportContext, error) {+ if v == nil {+ return nil, nil+ }+ var keys []string+ var collect func(v any) error+ collect = func(v any) error {+ switch vv := v.(type) {+ case nil:+ return nil+ case interface{ Key() string }:+ // Resource, Page, mounted resources.+ key := vv.Key()+ if r, ok := v.(resource.Resource); ok && InternalResourceSourcePath(r) == "" {+ // In-memory resources (e.g. from resources.FromString) with the+ // same target path may have different content.+ content, err := InternalResourceSourceContent(context.Background(), r)+ if err != nil {+ return fmt.Errorf("importContext: %w", err)+ }+ key += "_" + hashing.HashStringHex(content)+ }+ keys = append(keys, key)+ case identity.IdentityProvider:+ keys = append(keys, vv.GetIdentity().IdentifierBase())+ case resource.ResourcesProvider:+ for _, r := range vv.Resources() {+ if err := collect(r); err != nil {+ return err+ }+ }+ default:+ s, ok := hreflect.ToSliceAny(v)+ if !ok {+ return fmt.Errorf("importContext: unsupported type %T", v)+ }+ for _, e := range s {+ if err := collect(e); err != nil {+ return err+ }+ }+ }+ return nil+ }+ if err := collect(v); err != nil {+ return nil, err+ }++ if len(keys) == 0 {+ return nil, nil+ }++ return &ImportContext{+ Getter: resource.NewCachedResourceGetter(v),+ Key: hashing.HashStringHex(strings.Join(keys, "|")),+ }, nil+}++type importContextProvider interface {+ importContext() *ImportContext+}++// InternalResourceImportContext is used internally to get the import context set on r using resources.Copy.+// It returns nil if no import context is set.+func InternalResourceImportContext(r resource.Resource) resource.ResourceGetter {+ if p, ok := r.(importContextProvider); ok {+ if ic := p.importContext(); ic != nil {+ return ic.Getter+ }+ }+ return nil+}resources/resource.goindex cf6e1e597..1c8f35b9b 100644@@ -222,12 +222,12 @@ func (t transformerNotAvailable) Key() internal.ResourceTransformationKey { // resourceCopier is for internal use. type resourceCopier interface {- cloneTo(targetPath string) resource.Resource+ cloneTo(opts CopyOptions) resource.Resource } -// Copy copies r to the targetPath given.-func Copy(r resource.Resource, targetPath string) resource.Resource {- return r.(resourceCopier).cloneTo(targetPath)+// Copy copies r using the given options.+func Copy(r resource.Resource, opts CopyOptions) resource.Resource {+ return r.(resourceCopier).cloneTo(opts) } type baseResourceResource interface {@@ -243,6 +243,7 @@ type baseResourceInternal interface { resource.NameNormalizedProvider sourcePath() string+ importContextProvider fileInfo mediaTypeAssigner targetPather@@ -373,6 +374,8 @@ type genericResource struct { h *resourceHash // A hash of the source content. Is only calculated in caching situations. + importCtx *ImportContext // Set by resources.Copy, used to resolve imports in e.g. css.Build.+ resource.Staler title string@@ -426,12 +429,21 @@ func (l *genericResource) setTargetPath(d internal.ResourcePaths) { l.paths = d } -func (l *genericResource) cloneTo(targetPath string) resource.Resource {+func (l *genericResource) cloneTo(opts CopyOptions) resource.Resource { c := l.clone()- c.paths = c.paths.FromTargetPath(targetPath)+ if opts.TargetPath != "" {+ c.paths = c.paths.FromTargetPath(opts.TargetPath)+ }+ if opts.ImportContext != nil {+ c.importCtx = opts.ImportContext+ } return c } +func (l *genericResource) importContext() *ImportContext {+ return l.importCtx+}+ func (l *genericResource) Content(context.Context) (any, error) { r, err := l.ReadSeekCloser() if err != nil {@@ -462,6 +474,12 @@ func (l *genericResource) Key() string { if l.includeHashInKey && !l.sourceFilenameIsHash { l.key += fmt.Sprintf("_%d", l.hash()) }++ if l.importCtx != nil {+ // Resources with different import contexts may produce different+ // results when transformed, so they need different cache keys.+ l.key += "_ic" + l.importCtx.Key+ } }) return l.keyresources/resource/resources.goindex 28fbab42f..ea4a6c002 100644@@ -35,42 +35,69 @@ type Resources []Resource // Mount mounts the given resources from base to the given target path. // Note that leading slashes in target marks an absolute path.-// This method is currently only useful in js.Batch.+// This is useful in import contexts, e.g. in js.Batch and resources.Copy. func (r Resources) Mount(base, target string) ResourceGetter {- return resourceGetterFunc(func(namev any) Resource {- name1, err := cast.ToStringE(namev)- if err != nil {- panic(err)- }+ return mountedResources{r: r, base: base, target: target}+} - isTargetAbs := strings.HasPrefix(target, "/")+// mountedResources is a ResourceGetter returned by Resources.Mount.+type mountedResources struct {+ r Resources+ base, target string+} - if target != "" {- name1 = strings.TrimPrefix(name1, target)- if !isTargetAbs {- name1 = paths.TrimLeading(name1)- }+// Key returns a key identifying the mounted resources.+func (m mountedResources) Key() string {+ var sb strings.Builder+ sb.WriteString("mount:")+ sb.WriteString(m.base)+ sb.WriteString(":")+ sb.WriteString(m.target)+ for _, res := range m.r {+ sb.WriteString(":")+ if k, ok := res.(interface{ Key() string }); ok {+ sb.WriteString(k.Key())+ } else {+ sb.WriteString(res.Name()) }+ }+ return sb.String()+}++func (m mountedResources) Get(namev any) Resource {+ base, target := m.base, m.target+ name1, err := cast.ToStringE(namev)+ if err != nil {+ panic(err)+ }++ isTargetAbs := strings.HasPrefix(target, "/") - if base != "" && isTargetAbs {- name1 = path.Join(base, name1)+ if target != "" {+ name1 = strings.TrimPrefix(name1, target)+ if !isTargetAbs {+ name1 = paths.TrimLeading(name1) }+ } - for _, res := range r {- name2 := res.Name()+ if base != "" && isTargetAbs {+ name1 = path.Join(base, name1)+ } - if base != "" && !isTargetAbs {- name2 = paths.TrimLeading(strings.TrimPrefix(name2, base))- }+ for _, res := range m.r {+ name2 := res.Name() - if strings.EqualFold(name1, name2) {- return res- }+ if base != "" && !isTargetAbs {+ name2 = paths.TrimLeading(strings.TrimPrefix(name2, base))+ } + if strings.EqualFold(name1, name2) {+ return res } - return nil- })+ }++ return nil } type ResourcesProvider interface {@@ -392,6 +419,8 @@ func unwrapResourceGetter(v any) (ResourceGetter, bool) { return vv.Resources(), true case func(name any) Resource: return resourceGetterFunc(vv), true+ case Resource:+ return Resources{vv}, true default: vvv, ok := hreflect.ToSliceAny(v) if !ok {resources/resource_factories/create/create.goindex 4a4d14da6..d68f69b55 100644@@ -146,11 +146,20 @@ func New(rs *resources.Spec) *Client { } } -// Copy copies r to the new targetPath.-func (c *Client) Copy(r resource.Resource, targetPath string) (resource.Resource, error) {- key := dynacache.CleanKey(targetPath) + "__copy"+// Copy copies r using the given options.+func (c *Client) Copy(r resource.Resource, opts resources.CopyOptions) (resource.Resource, error) {+ targetPath := opts.TargetPath+ if targetPath == "" {+ // Note that this will also trigger any pending transformations of r.+ targetPath = resources.InternalResourceTargetPath(r)+ }+ key := dynacache.CleanKey(targetPath)+ if opts.ImportContext != nil {+ key += "_ic" + opts.ImportContext.Key+ }+ key += "__copy" return c.rs.ResourceCache.GetOrCreate(key, func() (resource.Resource, error) {- return resources.Copy(r, targetPath), nil+ return resources.Copy(r, opts), nil }) } resources/resource_transformers/cssjs/inline_imports.goindex 44ae4b3c6..f7d97706d 100644@@ -14,6 +14,7 @@ package cssjs import (+ "context" "crypto/sha256" "encoding/hex" "errors"@@ -30,6 +31,8 @@ import ( "github.com/gohugoio/hugo/common/text" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/identity"+ "github.com/gohugoio/hugo/resources"+ "github.com/gohugoio/hugo/resources/resource" "github.com/spf13/afero" ) @@ -45,11 +48,18 @@ type fileOffset struct { Offset int } +// importContextPathPrefix marks paths of imports resolved from the import context.+const importContextPathPrefix = "hugo-ic:/"+ type importResolver struct { r io.Reader inPath string opts InlineImports + ctx context.Context+ // The import context set by resources.Copy, if any.+ importContext resource.ResourceGetter+ contentSeen map[string]bool dependencyManager identity.Manager linemap map[int]fileOffset@@ -68,14 +78,54 @@ func newImportResolver(r io.Reader, inPath string, opts InlineImports, fs afero. } } +// setImportContext sets the import context (see resources.Copy) to resolve imports from+// before falling back to the filesystem.+func (imp *importResolver) setImportContext(ctx context.Context, importContext resource.ResourceGetter) {+ imp.ctx = ctx+ imp.importContext = importContext+}+ func (imp *importResolver) contentHash(filename string) ([]byte, string) { b, err := afero.ReadFile(imp.fs, filename) if err != nil { return nil, "" }+ return b, sha256Hex(b)+}++func sha256Hex(b []byte) string { h := sha256.New() h.Write(b)- return b, hex.EncodeToString(h.Sum(nil))+ return hex.EncodeToString(h.Sum(nil))+}++// resolveFromImportContext resolves the import path p from inPath using the+// import context set by resources.Copy.+// It returns a nil content if not found.+func (imp *importResolver) resolveFromImportContext(p, inPath string) (content []byte, hash, importPath string, err error) {+ if imp.importContext == nil {+ return+ }+ var candidates []string+ if importerPath, ok := strings.CutPrefix(inPath, importContextPathPrefix); ok && !strings.HasPrefix(p, "/") {+ // Relative import from a resource in the import context.+ candidates = append(candidates, path.Join(path.Dir(importerPath), p))+ }+ candidates = append(candidates, p)+ for _, candidate := range candidates {+ r := imp.importContext.Get(candidate)+ if r == nil {+ continue+ }+ s, err := resources.InternalResourceSourceContent(imp.ctx, r)+ if err != nil {+ return nil, "", "", fmt.Errorf("failed to read import %q: %w", resources.InternalResourceSourcePathBestEffort(r), err)+ }+ imp.dependencyManager.AddIdentity(identity.FirstIdentity(r))+ content = []byte(s)+ return content, sha256Hex(content), importContextPathPrefix + strings.TrimPrefix(path.Clean(candidate), "/"), nil+ }+ return } func (imp *importResolver) importRecursive(@@ -84,6 +134,11 @@ func (imp *importResolver) importRecursive( inPath string, ) (int, string, error) { basePath := path.Dir(inPath)+ if after, ok := strings.CutPrefix(basePath, strings.TrimSuffix(importContextPathPrefix, "/")); ok {+ // Resources in the import context have no location on disk,+ // so resolve their filesystem imports relative to the /assets root.+ basePath = strings.TrimPrefix(after, "/")+ } var replacements []string lines := strings.Split(content, "\n")@@ -104,9 +159,15 @@ func (imp *importResolver) importRecursive( trackLine(i, offset, line) } else { path := strings.Trim(strings.TrimPrefix(line, importIdentifier), " \"';")- filename := filepath.Join(basePath, path)- imp.dependencyManager.AddIdentity(identity.CleanStringIdentity(filename))- importContent, hash := imp.contentHash(filename)+ importContent, hash, filename, err := imp.resolveFromImportContext(path, inPath)+ if err != nil {+ return 0, "", err+ }+ if importContent == nil {+ filename = filepath.Join(basePath, path)+ imp.dependencyManager.AddIdentity(identity.CleanStringIdentity(filename))+ importContent, hash = imp.contentHash(filename)+ } if importContent == nil { if imp.opts.SkipInlineImportsNotFound {resources/resource_transformers/cssjs/inline_imports_test.goindex 3578e2612..95f9051db 100644@@ -14,6 +14,7 @@ package cssjs import (+ "context" "regexp" "strings" "testing"@@ -21,6 +22,7 @@ import ( "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/htesting/hqt" "github.com/gohugoio/hugo/identity"+ "github.com/gohugoio/hugo/resources/resource" "github.com/gohugoio/hugo/helpers" @@ -130,6 +132,95 @@ E_STYLE`) }) } +type testImportContextResource struct {+ resource.Resource+ content string+}++func (r testImportContextResource) Content(context.Context) (any, error) {+ return r.content, nil+}++type testImportContext map[string]string++func (m testImportContext) Get(name any) resource.Resource {+ if content, found := m[strings.TrimPrefix(name.(string), "/")]; found {+ return testImportContextResource{content: content}+ }+ return nil+}++func TestImportResolverImportContext(t *testing.T) {+ c := qt.New(t)+ fs := afero.NewMemMapFs()++ c.Assert(afero.WriteFile(fs, "css/b.css", []byte(`B_STYLE_FROM_FS`), 0o777), qt.IsNil)++ mainStyles := strings.NewReader(`@import "a.css";+@import "b.css";+@import "components/c.css";+LOCAL_STYLE`)++ imp := newImportResolver(+ mainStyles,+ "css/styles.css",+ InlineImports{},+ fs, loggers.NewDefault(),+ identity.NopManager,+ )+ imp.setImportContext(context.Background(), testImportContext{+ "a.css": "A_STYLE_FROM_IMPORT_CONTEXT",+ "components/c.css": "@import \"d.css\";\nC_STYLE_FROM_IMPORT_CONTEXT",+ "components/d.css": "D_STYLE_FROM_IMPORT_CONTEXT",+ })++ r, err := imp.resolve()+ c.Assert(err, qt.IsNil)+ rs := helpers.ReaderToString(r)+ result := regexp.MustCompile(`\n+`).ReplaceAllString(rs, "\n")++ c.Assert(result, hqt.IsSameString, `A_STYLE_FROM_IMPORT_CONTEXT+B_STYLE_FROM_FS+D_STYLE_FROM_IMPORT_CONTEXT+C_STYLE_FROM_IMPORT_CONTEXT+LOCAL_STYLE`)+}++func TestImportResolverImportContextNestedFilesystemImport(t *testing.T) {+ c := qt.New(t)+ fs := afero.NewMemMapFs()++ c.Assert(afero.WriteFile(fs, "e.css", []byte(`E_STYLE_FROM_FS`), 0o777), qt.IsNil)+ c.Assert(afero.WriteFile(fs, "components/f.css", []byte(`F_STYLE_FROM_FS`), 0o777), qt.IsNil)++ mainStyles := strings.NewReader(`@import "a.css";+@import "components/c.css";+LOCAL_STYLE`)++ imp := newImportResolver(+ mainStyles,+ "css/styles.css",+ InlineImports{},+ fs, loggers.NewDefault(),+ identity.NopManager,+ )+ imp.setImportContext(context.Background(), testImportContext{+ "a.css": "@import \"e.css\";\nA_STYLE_FROM_IMPORT_CONTEXT",+ "components/c.css": "@import \"f.css\";\nC_STYLE_FROM_IMPORT_CONTEXT",+ })++ r, err := imp.resolve()+ c.Assert(err, qt.IsNil)+ rs := helpers.ReaderToString(r)+ result := regexp.MustCompile(`\n+`).ReplaceAllString(rs, "\n")++ c.Assert(result, hqt.IsSameString, `E_STYLE_FROM_FS+A_STYLE_FROM_IMPORT_CONTEXT+F_STYLE_FROM_FS+C_STYLE_FROM_IMPORT_CONTEXT+LOCAL_STYLE`)+}+ func BenchmarkImportResolver(b *testing.B) { c := qt.New(b) fs := afero.NewMemMapFs()resources/resource_transformers/cssjs/postcss.goindex 94295eea9..977d4efdd 100644@@ -218,6 +218,7 @@ func (t *postcssTransformation) Transform(ctx *resources.ResourceTransformationC options.InlineImports, t.rs.Assets.Fs, t.rs.Logger, ctx.DependencyManager, )+ imp.setImportContext(ctx.Ctx, ctx.ImportContext) if options.InlineImports.InlineImports { var err errorresources/resource_transformers/cssjs/tailwindcss.goindex 539016dc2..21e7f953b 100644@@ -129,6 +129,7 @@ func (t *tailwindcssTransformation) Transform(ctx *resources.ResourceTransformat options.InlineImports, t.rs.Assets.Fs, t.rs.Logger, ctx.DependencyManager, )+ imp.setImportContext(ctx.Ctx, ctx.ImportContext) if !options.InlineImports.DisableInlineImports { src, err = imp.resolve()resources/resource_transformers/js/js_integration_test.goindex a11a6fbe9..3c6d95630 100644@@ -412,3 +412,58 @@ JS Content:{{ $js.Content }}:End: b.Assert(err.Error(), qt.Contains, `execute of template failed: template: home.html:2:17`) b.Assert(err.Error(), qt.Contains, `main.js:1:31": Could not resolve "./util1"`) }++func TestBuildImportContext(t *testing.T) {+ t.Parallel()++ files := `+-- hugo.toml --+disableKinds=["page", "section", "taxonomy", "term", "sitemap", "robotsTXT", "rss"]+-- assets/js/main.js --+import { hello } from "hello.js";+import { fromAssets } from "./util.js";+console.log(hello, fromAssets);+-- assets/js/util.js --+export const fromAssets = "From assets";+-- layouts/home.html --+{{ $hello := resources.FromString "hello.js" "import { world } from './world.js';\nexport const hello = 'Hello ' + world;" }}+{{ $world := resources.FromString "world.js" "export const world = 'from import context';" }}+{{ $main := resources.Get "js/main.js" | resources.Copy (dict "targetPath" "js/main-ic.js" "importContext" (slice $hello $world)) }}+{{ with $main | js.Build (dict "minify" false) }}{{ .RelPermalink }}{{ end }}+`++ b := hugolib.Test(t, files, hugolib.TestOptOsFs())+ b.AssertFileContent("public/index.html", "/js/main-ic.js")+ b.AssertFileContent("public/js/main-ic.js",+ `var world = "from import context";`,+ `var hello = "Hello " + world;`,+ `var fromAssets = "From assets";`,+ )+}++func TestBuildImportContextRelativeImportFromAssets(t *testing.T) {+ t.Parallel()++ files := `+-- hugo.toml --+disableKinds=["page", "section", "taxonomy", "term", "sitemap", "robotsTXT", "rss"]+-- assets/js/main.js --+import { deep } from "./deep/a.js";+console.log(deep);+-- assets/js/deep/a.js --+import { util } from "./util.js";+export const deep = util;+-- assets/js/deep/util.js --+export const util = "From assets sibling";+-- layouts/home.html --+{{ $util := resources.FromString "util.js" "export const util = 'From import context';" }}+{{ $main := resources.Get "js/main.js" | resources.Copy (dict "targetPath" "js/main-ic.js" "importContext" $util) }}+{{ with $main | js.Build (dict "minify" false) }}{{ .RelPermalink }}{{ end }}+`++ b := hugolib.Test(t, files, hugolib.TestOptOsFs())+ b.AssertFileContent("public/js/main-ic.js",+ `var util = "From assets sibling";`,+ `! From import context`,+ )+}resources/resource_transformers/js/transform.goindex 07933a92f..b39617915 100644@@ -70,6 +70,10 @@ func (t *buildTransformation) Transform(ctx *resources.ResourceTransformationCtx opts.Stdin = true opts.IsCSS = t.c.c.CssMode + if err := opts.SetImportContext(ctx.Ctx, ctx.ImportContext, ctx.DependencyManager); err != nil {+ return err+ }+ _, err = t.c.transform(opts, ctx) return errresources/resource_transformers/tocss/dartsass/dartsass_integration_test.goindex 72e012667..4d275a85c 100644@@ -726,3 +726,38 @@ h2 { color: rgb(color.red(#ddd), 0, 0); } // deprecated "color.green() is deprecated", ) }++func TestTransformImportContext(t *testing.T) {+ t.Parallel()+ if !dartsass.Supports() {+ t.Skip()+ }++ files := `+-- hugo.toml --+disableKinds = ["taxonomy", "term", "page", "section", "rss", "sitemap"]+-- assets/scss/main.scss --+@use "vars";+@use "components/button";+@import "fromassets";+.main { color: vars.$color; }+-- assets/scss/_fromassets.scss --+.fromassets { color: green; }+-- layouts/home.html --+{{ $vars := resources.FromString "_vars.scss" "$color: #abcdef;" }}+{{ $button := resources.FromString "components/_button.scss" "@use \"../vars\";\n@use \"helper\";\n.button { color: vars.$color; }" }}+{{ $helper := resources.FromString "components/_helper.scss" ".helper { color: blue; }" }}+{{ $main := resources.Get "scss/main.scss" | resources.Copy (dict "importContext" (slice $vars $button $helper)) }}+{{ with $main | css.Sass (dict "transpiler" "dartsass") }}T1: {{ .RelPermalink }}|{{ .Content | safeCSS }}{{ end }}+`++ b := hugolib.Test(t, files, hugolib.TestOptOsFs())++ b.AssertFileContent("public/index.html",+ "T1: /scss/main.css|",+ ".helper {\n color: blue;\n}",+ ".button {\n color: #abcdef;\n}",+ ".fromassets {\n color: green;\n}",+ ".main {\n color: #abcdef;\n}",+ )+}resources/resource_transformers/tocss/dartsass/transform.goindex e3d5823e9..fefcb6ba8 100644@@ -14,12 +14,14 @@ package dartsass import (+ "context" "fmt" "io" "path" "path/filepath" "strings" + "github.com/gohugoio/hugo/common/hmaps" "github.com/gohugoio/hugo/common/hugo" "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/htesting"@@ -27,6 +29,7 @@ import ( "github.com/gohugoio/hugo/media" "github.com/gohugoio/hugo/resources"+ "github.com/gohugoio/hugo/resources/resource" "github.com/gohugoio/hugo/resources/internal" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/sass"@@ -83,6 +86,9 @@ func (t *transform) Transform(ctx *resources.ResourceTransformationCtx) error { baseDir: baseDir, c: t.c, dependencyManager: ctx.DependencyManager,+ ctx: ctx.Ctx,+ importContext: ctx.ImportContext,+ importContextSeen: hmaps.NewCache[string, resource.Resource](), vars: opts.Vars, },@@ -133,6 +139,13 @@ type importResolver struct { c *Client dependencyManager identity.Manager vars map[string]any++ ctx context.Context++ // Set by resources.Copy.+ importContext resource.ResourceGetter+ // Maps import context URLs to resources.+ importContextSeen *hmaps.Cache[string, resource.Resource] } func (t importResolver) CanonicalizeURL(url string) (string, error) {@@ -140,6 +153,16 @@ func (t importResolver) CanonicalizeURL(url string) (string, error) { return strings.ToLower(url), nil } + if t.importContext != nil {+ if s := t.canonicalizeImportContextURL(url); s != "" {+ return s, nil+ }+ if strings.HasPrefix(url, sass.ImportContextURLPrefix) {+ // Not found, let Dart Sass handle it.+ return "", nil+ }+ }+ filePath, isURL := paths.UrlStringToFilename(url) var prevDir string var pathDir string@@ -192,21 +215,65 @@ func (t importResolver) CanonicalizeURL(url string) (string, error) { return "", nil } +// canonicalizeImportContextURL resolves url using the import context set by resources.Copy.+// It returns an empty string if not found.+func (t importResolver) canonicalizeImportContextURL(url string) string {+ p := url+ // Note that relative imports from resources in the import context+ // are passed to us resolved by Dart Sass, prefixed with sass.ImportContextURLPrefix.+ if !strings.HasPrefix(url, sass.ImportContextURLPrefix) {+ if filePath, isURL := paths.UrlStringToFilename(url); isURL {+ // An import from a file in /assets, resolved by Dart Sass relative to that file.+ // Try the path relative to the directory of the entry stylesheet.+ rel, found := t.c.sfs.MakePathRelative(filePath, true)+ if !found {+ return ""+ }+ p = filepath.ToSlash(rel)+ if t.baseDir != "." && t.baseDir != "" {+ var ok bool+ p, ok = strings.CutPrefix(p, t.baseDir+"/")+ if !ok {+ return ""+ }+ }+ }+ }+ r, canonical := sass.ResolveFromImportContext(t.importContext, p, "", true)+ if r == nil {+ return ""+ }+ t.dependencyManager.AddIdentity(identity.FirstIdentity(r))+ t.importContextSeen.Set(canonical, r)+ return canonical+}+ func (t importResolver) Load(url string) (godartsass.Import, error) { if subPath, ok := sass.HugoVarsSubPath(url); ok { return godartsass.Import{ Content: sass.CreateVarsStyleSheet(sass.TranspilerDart, sass.ResolveVars(t.vars, subPath)), }, nil }++ if r, found := t.importContextSeen.Get(url); found {+ content, err := resources.InternalResourceSourceContent(t.ctx, r)+ if err != nil {+ return godartsass.Import{}, fmt.Errorf("failed to read import %q: %w", resources.InternalResourceSourcePathBestEffort(r), err)+ }+ return godartsass.Import{Content: content, SourceSyntax: sourceSyntaxFromFilename(url)}, nil+ }+ filename, _ := paths.UrlStringToFilename(url) b, err := afero.ReadFile(hugofs.Os, filename) - sourceSyntax := godartsass.SourceSyntaxSCSS+ return godartsass.Import{Content: string(b), SourceSyntax: sourceSyntaxFromFilename(filename)}, err+}++func sourceSyntaxFromFilename(filename string) godartsass.SourceSyntax { if strings.HasSuffix(filename, ".sass") {- sourceSyntax = godartsass.SourceSyntaxSASS+ return godartsass.SourceSyntaxSASS } else if strings.HasSuffix(filename, ".css") {- sourceSyntax = godartsass.SourceSyntaxCSS+ return godartsass.SourceSyntaxCSS }-- return godartsass.Import{Content: string(b), SourceSyntax: sourceSyntax}, err+ return godartsass.SourceSyntaxSCSS }resources/resource_transformers/tocss/sass/importcontext.gonew file mode 100644index 000000000..b5cc3b9ed@@ -0,0 +1,83 @@+// Copyright 2026 The Hugo Authors. All rights reserved.+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package sass++import (+ "fmt"+ "path"+ "strings"++ "github.com/gohugoio/hugo/resources/resource"+)++// ImportContextURLPrefix is used to mark imports resolved from an import context (see resources.Copy).+const ImportContextURLPrefix = "hugo-ic:/"++// ResolveFromImportContext resolves the Sass import path p, which may be relative to importer+// if importer is a URL created by this function, using importContext, trying the+// common Sass partial and extension variants.+// It returns the resolved resource and its URL (prefixed with ImportContextURLPrefix),+// or nil if not found.+func ResolveFromImportContext(importContext resource.ResourceGetter, p, importer string, includeCSS bool) (resource.Resource, string) {+ if importContext == nil {+ return nil, ""+ }++ var candidates []string+ if importerPath, ok := strings.CutPrefix(importer, ImportContextURLPrefix); ok && !strings.HasPrefix(p, "/") {+ candidates = append(candidates, path.Join(path.Dir(importerPath), p))+ }+ if after, ok := strings.CutPrefix(p, ImportContextURLPrefix); ok {+ // Already resolved relative to an import context URL.+ p = after+ }+ candidates = append(candidates, path.Clean(strings.TrimPrefix(p, "/")))++ for _, candidate := range candidates {+ dir, name := path.Split(candidate)++ var namePatterns []string+ if strings.Contains(name, ".") {+ namePatterns = []string{"_%s", "%s"}+ } else if strings.HasPrefix(name, "_") {+ namePatterns = []string{"_%s.scss", "_%s.sass"}+ if includeCSS {+ namePatterns = append(namePatterns, "_%s.css")+ }+ } else {+ namePatterns = []string{+ "_%s.scss", "%s.scss",+ "_%s.sass", "%s.sass",+ }+ if includeCSS {+ namePatterns = append(namePatterns, "_%s.css", "%s.css")+ }+ namePatterns = append(namePatterns,+ "%s/_index.scss", "%s/_index.sass",+ "%s/index.scss", "%s/index.sass",+ )+ }++ name = strings.TrimPrefix(name, "_")++ for _, namePattern := range namePatterns {+ nameToCheck := path.Join(dir, fmt.Sprintf(namePattern, name))+ if r := importContext.Get(nameToCheck); r != nil {+ return r, ImportContextURLPrefix + strings.TrimPrefix(nameToCheck, "/")+ }+ }+ }++ return nil, ""+}resources/resource_transformers/tocss/scss/scss_integration_test.goindex 93cc05bf0..a1548ecc2 100644@@ -437,3 +437,34 @@ body { b.AssertLogContains("deprecated: css.Sass: libsass was deprecated in Hugo v0.153.0") }++func TestTransformImportContext(t *testing.T) {+ t.Parallel()+ if !scss.Supports() {+ t.Skip()+ }++ files := `+-- hugo.toml --+disableKinds = ["taxonomy", "term", "page", "section", "rss", "sitemap"]+-- assets/scss/main.scss --+@import "vars";+@import "components/button";+@import "fromassets";+.main { color: $color; }+-- assets/scss/_fromassets.scss --+.fromassets { color: green; }+-- layouts/home.html --+{{ $vars := resources.FromString "_vars.scss" "$color: #abcdef;" }}+{{ $button := resources.FromString "components/_button.scss" "@import \"helper\";\n.button { color: $color; }" }}+{{ $helper := resources.FromString "components/_helper.scss" ".helper { color: blue; }" }}+{{ $main := resources.Get "scss/main.scss" | resources.Copy (dict "importContext" (slice $vars $button $helper)) }}+{{ with $main | css.Sass (dict "transpiler" "libsass") | minify }}T1: {{ .RelPermalink }}|{{ .Content | safeCSS }}{{ end }}+`++ b := hugolib.Test(t, files, hugolib.TestOptOsFs())++ b.AssertFileContent("public/index.html",+ "T1: /scss/main.min.css|.helper{color:blue}.button{color:#abcdef}.fromassets{color:green}.main{color:#abcdef}",+ )+}resources/resource_transformers/tocss/scss/tocss.goindex ea8617140..6230b91ba 100644@@ -69,11 +69,47 @@ func (t *toCSSTransformation) Transform(ctx *resources.ResourceTransformationCtx // to help libsass revolve the filename by looking in the composite filesystem first. // We add the entry directories for both project and themes to the include paths list, but // that only work for overrides on the top level.+ // The import resolver cannot return errors, so we store the first one here.+ var importContextErr error+ // LibSASS passes the import URL as written as prev for nested imports,+ // so keep track of what we resolved from the import context.+ importContextResolved := make(map[string]string)++ // resolveFromImportContext resolves url using the import context set by resources.Copy.+ resolveFromImportContext := func(url, prev string) (newURL, body string, resolved bool) {+ if ctx.ImportContext == nil {+ return "", "", false+ }+ importer, found := importContextResolved[prev]+ if prev != "stdin" && !found {+ // Imported from a file on disk.+ return "", "", false+ }+ r, icURL := sass.ResolveFromImportContext(ctx.ImportContext, url, importer, false)+ if r == nil {+ return "", "", false+ }+ content, err := resources.InternalResourceSourceContent(ctx.Ctx, r)+ if err != nil {+ if importContextErr == nil {+ importContextErr = fmt.Errorf("failed to read import %q: %w", resources.InternalResourceSourcePathBestEffort(r), err)+ }+ return "", "", false+ }+ ctx.DependencyManager.AddIdentity(identity.FirstIdentity(r))+ importContextResolved[url] = icURL+ return icURL, content, true+ }+ options.to.ImportResolver = func(url string, prev string) (newUrl string, body string, resolved bool) { if url == sass.HugoVarsNamespace { return url, varsStylesheet, true } + if newUrl, body, resolved = resolveFromImportContext(url, prev); resolved {+ return+ }+ // We get URL paths from LibSASS, but we need file paths. url = filepath.FromSlash(url) prev = filepath.FromSlash(prev)@@ -150,6 +186,9 @@ func (t *toCSSTransformation) Transform(ctx *resources.ResourceTransformationCtx } res, err := t.c.toCSS(options.to, ctx.To, ctx.From)+ if importContextErr != nil {+ return importContextErr+ } if err != nil { if sasserr, ok := err.(libsasserrors.Error); ok { if sasserr.File == "stdin" && ctx.SourcePath != "" {resources/transform.goindex 5dc281f71..1c2c38bfa 100644@@ -126,6 +126,11 @@ type ResourceTransformationCtx struct { // The input media type InMediaType media.Type + // The import context set on the resource using resources.Copy, if any.+ // Transformations that resolve imports (e.g. CSS @import)+ // should look in this before falling back to the default behavior.+ ImportContext resource.ResourceGetter+ // The media type of the transformed resource. OutMediaType media.Type @@ -227,8 +232,8 @@ func (r *resourceAdapter) GetDependencyManager() identity.Manager { return r.target.GetDependencyManager() } -func (r resourceAdapter) cloneTo(targetPath string) resource.Resource {- newtTarget := r.target.cloneTo(targetPath)+func (r resourceAdapter) cloneTo(opts CopyOptions) resource.Resource {+ newtTarget := r.target.cloneTo(opts) newInner := &resourceAdapterInner{ ctx: r.ctx, spec: r.spec,@@ -291,6 +296,12 @@ func (r *resourceAdapter) TransientKey() string { return r.Key() } +func (r *resourceAdapter) importContext() *ImportContext {+ // Note that the import context is preserved through transformations,+ // so there's no need to trigger them here.+ return r.target.importContext()+}+ func (r *resourceAdapter) targetPath() string { r.init(false, false) return r.target.(targetPathProvider).targetPath()@@ -518,6 +529,10 @@ func (r *resourceAdapter) transform(key string, publish, setContent bool) (*reso DependencyManager: r.target.GetDependencyManager(), } + if ic := r.target.importContext(); ic != nil {+ tctx.ImportContext = ic.Getter+ }+ tctx.InMediaType = r.target.MediaType() tctx.OutMediaType = r.target.MediaType() tpl/css/build_integration_test.goindex 31b692a8e..55973aef7 100644@@ -731,3 +731,120 @@ body { "--text-color: #333;", ) }++func TestCSSBuildImportContext(t *testing.T) {+ t.Parallel()++ files := `+-- hugo.toml --+disableKinds = ["taxonomy", "term", "page", "section", "rss", "sitemap"]+-- assets/css/main.css --+@import "foo.css" screen;+@import "bar.css" print;+@import "baz.css";+.main { color: red; }+-- assets/css/baz.css --+.baz { color: from-assets; }+-- assets/css/other/qux.css --+.qux { color: from-mount; }+-- layouts/home.html --+{{ $foo := resources.FromString "foo.css" "body { color: blue; }" }}+{{ $bar := resources.FromString "bar.css" "@import \"nested.css\";\nbody { color: green; }" }}+{{ $nested := resources.FromString "nested.css" ".nested { color: black; }" }}+{{ $main := resources.Get "css/main.css" }}+{{ $copy := $main | resources.Copy (dict "importContext" (slice $foo $bar $nested)) }}+{{ with $copy | css.Build }}Copy: {{ .RelPermalink }}|{{ .Content | safeCSS }}|{{ end }}+{{ $copy2 := resources.Copy (dict "targetPath" "css/main2.css" "importContext" (slice $foo $bar $nested)) $main }}+{{ with $copy2 | css.Build }}Copy2: {{ .RelPermalink }}|{{ end }}+{{ $mounted := resources.Match "css/other/*.css" }}+{{ $main3 := resources.FromString "css/main3.css" "@import \"mnt/qux.css\";" }}+{{ with $main3 | resources.Copy (dict "importContext" ($mounted.Mount "/css/other" "mnt")) | css.Build }}Mounted: {{ .Content | safeCSS }}|{{ end }}+`++ b := hugolib.Test(t, files, hugolib.TestOptOsFs())++ b.AssertFileContent("public/index.html",+ "Copy: /css/main.css|",+ "@media screen {\n body {\n color: blue;\n }\n}",+ "@media print {\n .nested {\n color: black;\n }\n}",+ "@media print {\n body {\n color: green;\n }\n}",+ ".baz {\n color: from-assets;\n}",+ "Copy2: /css/main2.css|",+ "Mounted:", ".qux {\n color: from-mount;\n}",+ )+ b.AssertPublishDir("css/main.css", "css/main2.css")++ // The import context must not leak into a build of the original resource.+ files += `+{{ with $main | css.Build }}NoContext: {{ .RelPermalink }}|{{ end }}+`+ b, err := hugolib.TestE(t, files, hugolib.TestOptOsFs())+ b.Assert(err, qt.IsNotNil)+ b.Assert(err.Error(), qt.Contains, `Could not resolve "foo.css"`)+}++func TestResourcesCopyImportContextInvalid(t *testing.T) {+ t.Parallel()++ files := `+-- hugo.toml --+-- layouts/home.html --+{{ $main := resources.FromString "main.css" "@import \"foo.css\";" }}+{{ $main | resources.Copy (dict "importContext" 32) }}+`+ b, err := hugolib.TestE(t, files)+ b.Assert(err, qt.IsNotNil)+ b.Assert(err.Error(), qt.Contains, "importContext: unsupported type int")++ files = strings.ReplaceAll(files, `(dict "importContext" 32)`, `(dict "foo" 32)`)+ b, err = hugolib.TestE(t, files)+ b.Assert(err, qt.IsNotNil)+ b.Assert(err.Error(), qt.Contains, `unknown option "foo"`)+}++func TestCSSBuildImportContextRebuild(t *testing.T) {+ t.Parallel()++ files := `+-- hugo.toml --+disableKinds = ["taxonomy", "term", "page", "section", "rss", "sitemap"]+disableLiveReload = true+-- assets/css/main.css --+@import "foo.css";+-- assets/other/foo.css --+.foo { color: blue; }+-- layouts/home.html --+{{ $ic := (resources.Match "other/*.css").Mount "/other" "." }}+{{ with resources.Get "css/main.css" | resources.Copy (dict "importContext" $ic) | css.Build }}{{ .Content | safeCSS }}{{ end }}+`++ b := hugolib.TestRunning(t, files, hugolib.TestOptOsFs())+ b.AssertFileContent("public/index.html", ".foo {\n color: blue;\n}")++ b.EditFileReplaceAll("assets/other/foo.css", "blue", "red").Build()+ b.AssertFileContent("public/index.html", ".foo {\n color: red;\n}")+}++func TestCSSBuildImportContextSameNameDifferentContent(t *testing.T) {+ t.Parallel()++ files := `+-- hugo.toml --+disableKinds = ["taxonomy", "term", "page", "section", "rss", "sitemap"]+-- assets/css/main.css --+@import "vars.css";+-- layouts/home.html --+{{ $main := resources.Get "css/main.css" }}+{{ $blue := resources.FromString "vars.css" ".vars { color: blue; }" }}+{{ $red := resources.FromString "vars.css" ".vars { color: red; }" }}+{{ with $main | resources.Copy (dict "importContext" $blue) | css.Build }}Blue2: {{ .Content | safeCSS }}|{{ end }}+{{ with $main | resources.Copy (dict "importContext" $red) | css.Build }}Red2: {{ .Content | safeCSS }}|{{ end }}+`++ b := hugolib.Test(t, files, hugolib.TestOptOsFs())++ b.AssertFileContent("public/index.html",+ "Blue2: /* ns-hugo-imp-func:__hu_v/vars.css */\n.vars {\n color: blue;\n}",+ "Red2: /* ns-hugo-imp-func:__hu_v/vars.css */\n.vars {\n color: red;\n}",+ )+}tpl/resources/resources.goindex 2512b5ce9..82d72e2f5 100644@@ -18,6 +18,7 @@ import ( "context" "errors" "fmt"+ "strings" "github.com/gohugoio/hugo/common/hmaps" "github.com/gohugoio/hugo/common/hugo"@@ -71,13 +72,58 @@ type Namespace struct { templatesClient *templates.Client } -// Copy copies r to the new targetPath in s.-func (ns *Namespace) Copy(s any, r resource.Resource) (resource.Resource, error) {- targetPath, err := cast.ToStringE(s)- if err != nil {- panic(err)+// Copy copies the given resource.+// The first, optional, argument is either a target path or a map+// of options with the keys targetPath and importContext.+// If no target path is given, the target path of the resource is used.+func (ns *Namespace) Copy(args ...any) (resource.Resource, error) {+ if len(args) < 1 || len(args) > 2 {+ return nil, errors.New("must provide a resource and, optionally, a target path or an options map")+ }++ r, ok := args[len(args)-1].(resource.Resource)+ if !ok {+ return nil, fmt.Errorf("expected a resource, got %T", args[len(args)-1]) }- return ns.createClient.Copy(r, targetPath)++ var opts resources.CopyOptions++ if len(args) == 2 {+ switch v := args[0].(type) {+ case map[string]any, hmaps.Params:+ m, err := hmaps.ToStringMapE(v)+ if err != nil {+ return nil, err+ }+ for k, vv := range m {+ switch strings.ToLower(k) {+ case "targetpath":+ opts.TargetPath, err = cast.ToStringE(vv)+ if err != nil {+ return nil, fmt.Errorf("invalid targetPath: %w", err)+ }+ case "importcontext":+ opts.ImportContext, err = resources.NewImportContext(vv)+ if err != nil {+ return nil, err+ }+ default:+ return nil, fmt.Errorf("unknown option %q", k)+ }+ }+ default:+ targetPath, err := cast.ToStringE(v)+ if err != nil {+ return nil, fmt.Errorf("expected a target path or an options map, got %T", v)+ }+ if targetPath == "" {+ return nil, errors.New("targetPath cannot be empty")+ }+ opts.TargetPath = targetPath+ }+ }++ return ns.createClient.Copy(r, opts) } // Get locates the filename given in Hugo's assets filesystem
common/hashing/hashing.goindex ad28bbce2..1b0ed2768 100644@@ -18,6 +18,7 @@ import ( "crypto/md5" "encoding/hex" "io"+ "reflect" "strconv" "sync" @@ -124,11 +125,38 @@ func HashStringHex(vs ...any) string { var hashOptsPool = sync.Pool{ New: func() any { return &hashstructure.HashOptions{- Hasher: xxhash.New(),+ Hasher: xxhash.New(),+ UnwrapFunc: unwrapForHashing, } }, } +// hashstructure only sees exported struct fields, so rewrite known identity types before hashing,+// e.g. a Resource or Page nested in an options map hashes by its Key.+func unwrapForHashing(v reflect.Value) (reflect.Value, error) {+ if v.Kind() != reflect.Struct {+ return v, nil+ }+ var in any+ if v.CanAddr() {+ // The common case; pointer receiver methods on a struct+ // reached through a pointer.+ in = v.Addr().Interface()+ } else {+ in = v.Interface()+ }+ switch t := in.(type) {+ case hashstructure.Hashable:+ // Let hashstructure handle it.+ return v, nil+ case keyer:+ return reflect.ValueOf(t.Key()), nil+ case identity.IdentityProvider:+ return reflect.ValueOf(t.GetIdentity()), nil+ }+ return v, nil+}+ func getHashOpts() *hashstructure.HashOptions { return hashOptsPool.Get().(*hashstructure.HashOptions) }@@ -145,15 +173,10 @@ func putHashOpts(opts *hashstructure.HashOptions) { func HashUint64(vs ...any) uint64 { var o any if len(vs) == 1 {- o = toHashable(vs[0])+ o = vs[0] } else {- elements := make([]any, len(vs))- for i, e := range vs {- elements[i] = toHashable(e)- }- o = elements+ o = vs }- hash, err := Hash(o) if err != nil { panic(err)@@ -176,19 +199,6 @@ type keyer interface { Key() string } -// For structs, hashstructure.Hash only works on the exported fields,-// so rewrite the input slice for known identity types.-func toHashable(v any) any {- switch t := v.(type) {- case keyer:- return t.Key()- case identity.IdentityProvider:- return t.GetIdentity()- default:- return v- }-}- type xxhashReadFrom struct { buff []byte *xxhash.Digestgo.modindex 6e4498c98..4c0250df0 100644@@ -39,7 +39,7 @@ require ( github.com/gohugoio/gift v0.2.0 github.com/gohugoio/go-i18n/v2 v2.1.3-0.20251018145728-cfcc22d823c6 github.com/gohugoio/go-radix v1.2.0- github.com/gohugoio/hashstructure v0.6.0+ github.com/gohugoio/hashstructure v1.0.0 github.com/gohugoio/httpcache v0.8.0 github.com/gohugoio/hugo-goldmark-extensions/extras v0.7.0 github.com/gohugoio/hugo-goldmark-extensions/passthrough v0.5.0go.sumindex 5401b44fa..f1dded847 100644@@ -274,6 +274,8 @@ github.com/gohugoio/go-radix v1.2.0 h1:D5GTk8jIoeXirBSc2P4E4NdHKDrenk9k9N0ctU5Yr github.com/gohugoio/go-radix v1.2.0/go.mod h1:k6vDa0ebpbpgtzSj9lPGJcA4AZwJ9xUNObUy2vczPFM= github.com/gohugoio/hashstructure v0.6.0 h1:7wMB/2CfXoThFYhdWRGv3u3rUM761Cq29CxUW+NltUg= github.com/gohugoio/hashstructure v0.6.0/go.mod h1:lapVLk9XidheHG1IQ4ZSbyYrXcaILU1ZEP/+vno5rBQ=+github.com/gohugoio/hashstructure v1.0.0 h1:vWYuyzs1n0LdI0F54TJQeYAiB44fHX7H9hCp9X6gHKg=+github.com/gohugoio/hashstructure v1.0.0/go.mod h1:FSbTK4QwxucJ2bC4Lvrs9a6x0DbQDXNoyBO+h4nlCgE= github.com/gohugoio/httpcache v0.8.0 h1:hNdsmGSELztetYCsPVgjA960zSa4dfEqqF/SficorCU= github.com/gohugoio/httpcache v0.8.0/go.mod h1:fMlPrdY/vVJhAriLZnrF5QpN3BNAcoBClgAyQd+lGFI= github.com/gohugoio/hugo-goldmark-extensions/extras v0.7.0 h1:I/n6v7VImJ3aISLnn73JAHXyjcQsMVvbguQPTk9Ehus=hugolib/page.goindex 46c7e5c07..af1d65f1f 100644@@ -19,7 +19,6 @@ import ( "iter" "path/filepath" "slices"- "strconv" "strings" "sync/atomic" @@ -174,10 +173,6 @@ func (ps *pageState) Param(key any) (any, error) { return resource.Param(ps, ps.s.Params(), key) } -func (ps *pageState) Key() string {- return "page-" + strconv.FormatUint(ps.pid, 10)-}- // RelatedKeywords implements the related.Document interface needed for fast page searches. func (ps *pageState) RelatedKeywords(cfg related.IndexConfig) ([]related.Keyword, error) { v, found, err := page.NamedPageMetaValue(ps, cfg.Name)hugolib/page__output.goindex 384ed5f9e..cafe012b7 100644@@ -149,6 +149,11 @@ func (po *pageOutput) Aliases() []string { return aliases } +// Key returns a unique key for this page output, used to e.g. hashing.+func (po *pageOutput) Key() string {+ return po.p.Path() + po.f.Name+}+ func (po *pageOutput) incrRenderState() { po.renderState++ po.renderOnce = trueinternal/js/esbuild/options.goindex 88a5405a1..4176438e8 100644@@ -183,6 +183,9 @@ type ExternalOptions struct { // Maps a component import to another. Shims map[string]string + // User provided import context. If set, we will look here first.+ ImportContext any+ // Configuring a loader for a given file type lets you load that file type with an // import statement or a require call. For example, configuring the .png file extension // to use the data URL loader means importing a .png file gives you a data URLinternal/js/esbuild/resolve.goindex 3438af375..a0db7874d 100644@@ -260,6 +260,19 @@ func createBuildPlugins(rs *resources.Spec, assetsResolver *fsResolver, depsMana } } + if opts.ImportOnResolveFunc != nil {+ // Relative imports resolved against the importing file's directory,+ // e.g. "./foo.css". The path as written was tried above.+ for _, p := range pathsToTry {+ if p == impPath {+ continue+ }+ if s := opts.ImportOnResolveFunc(filepath.ToSlash(p), args); s != "" {+ return api.OnResolveResult{Path: s, Namespace: NsHugoImportResolveFunc}, nil+ }+ }+ }+ var m *hugofs.FileMeta for _, p := range pathsToTry { m = assetsResolver.resolveComponent(p, isCSSToken)resources/images/color.goindex 47c2848b9..fe233c7b7 100644@@ -16,13 +16,12 @@ package images import ( "encoding/hex" "fmt"- "hash/fnv" "image/color" "math"+ "slices" "strings" "github.com/gohugoio/hugo/common/hstrings"- "slices" ) type colorGoProvider interface {@@ -65,10 +64,8 @@ func (c Color) String() string { // For hashstructure. This struct is used in template func options // that needs to be able to hash a Color. // For internal use only.-func (c Color) Hash() (uint64, error) {- h := fnv.New64a()- h.Write([]byte(c.hex))- return h.Sum64(), nil+func (c Color) Key() string {+ return c.hex } func (c *Color) init() error {resources/internal/key.goindex b0ac9703f..3f8926d0c 100644@@ -13,7 +13,9 @@ package internal -import "github.com/gohugoio/hugo/common/hashing"+import (+ "github.com/gohugoio/hugo/common/hashing"+) // ResourceTransformationKey are provided by the different transformation implementations. // It identifies the transformation (name) and its configuration (elements).resources/resource.goindex cf6e1e597..69facb098 100644@@ -96,6 +96,9 @@ type ResourceSourceDescriptor struct { // Delay publishing until either Permalink or RelPermalink is called. Maybe never. LazyPublish bool + // Whether to include the hash of the source content in the resource key.+ IncludeHashInKey bool+ // Set when its known up front, else it's resolved from the target filename. MediaType media.Type resources/resource/resources.goindex 28fbab42f..08ee0b7ac 100644@@ -20,6 +20,8 @@ import ( "slices" "strings" + "github.com/gohugoio/hashstructure"+ "github.com/gohugoio/hugo/common/hashing" "github.com/gohugoio/hugo/common/hmaps" "github.com/gohugoio/hugo/common/hreflect" "github.com/gohugoio/hugo/common/paths"@@ -33,44 +35,56 @@ var _ ResourceFinder = (*Resources)(nil) // I.e. both pages and images etc. type Resources []Resource -// Mount mounts the given resources from base to the given target path.-// Note that leading slashes in target marks an absolute path.-// This method is currently only useful in js.Batch.-func (r Resources) Mount(base, target string) ResourceGetter {- return resourceGetterFunc(func(namev any) Resource {- name1, err := cast.ToStringE(namev)- if err != nil {- panic(err)- }+type resourceMount struct {+ R Resources+ Base string+ Target string+} - isTargetAbs := strings.HasPrefix(target, "/")+func (r resourceMount) Get(namev any) Resource {+ name1, err := cast.ToStringE(namev)+ if err != nil {+ panic(err)+ } - if target != "" {- name1 = strings.TrimPrefix(name1, target)- if !isTargetAbs {- name1 = paths.TrimLeading(name1)- }- }+ isTargetAbs := strings.HasPrefix(r.Target, "/") - if base != "" && isTargetAbs {- name1 = path.Join(base, name1)+ if r.Target != "" {+ name1 = strings.TrimPrefix(name1, r.Target)+ if !isTargetAbs {+ name1 = paths.TrimLeading(name1) }+ } - for _, res := range r {- name2 := res.Name()+ if r.Base != "" && isTargetAbs {+ name1 = path.Join(r.Base, name1)+ } - if base != "" && !isTargetAbs {- name2 = paths.TrimLeading(strings.TrimPrefix(name2, base))- }+ for _, res := range r.R {+ name2 := res.Name() - if strings.EqualFold(name1, name2) {- return res- }+ if r.Base != "" && !isTargetAbs {+ name2 = paths.TrimLeading(strings.TrimPrefix(name2, r.Base))+ } + if strings.EqualFold(name1, name2) {+ return res } - return nil- })+ }++ return nil+}++// Mount mounts the given resources from base to the given target path.+// Note that leading slashes in target marks an absolute path.+// This method can be used in any of the template funcs that takes an importContext option, e.g. css.Build.+func (r Resources) Mount(base, target string) ResourceGetter {+ return resourceMount{+ R: r,+ Base: base,+ Target: target,+ } } type ResourcesProvider interface {@@ -276,12 +290,6 @@ type StaleInfoResourceGetter interface { ResourceGetter } -type resourceGetterFunc func(name any) Resource--func (f resourceGetterFunc) Get(name any) Resource {- return f(name)-}- // ResourceFinder provides methods to find Resources. // Note that GetRemote (as found in resources.GetRemote) is // not covered by this interface, as this is only available as a global template function.@@ -318,6 +326,8 @@ type ResourceFinder interface { ByType(typ any) Resources } +var _ hashstructure.Hashable = (*cachedResourceGetter)(nil)+ // NewCachedResourceGetter creates a new ResourceGetter from the given objects. // If multiple objects are provided, they are merged into one where // the first match wins.@@ -329,12 +339,19 @@ func NewCachedResourceGetter(os ...any) *cachedResourceGetter { } } + hash := hashing.HashUint64(getters)+ return &cachedResourceGetter{ cache: hmaps.NewCache[string, Resource](), delegate: getters,+ hash: hash, } } +func (c *cachedResourceGetter) Hash() (uint64, error) {+ return c.hash, nil+}+ type multiResourceGetter []ResourceGetter func (m multiResourceGetter) Get(name any) Resource {@@ -354,6 +371,7 @@ var ( type cachedResourceGetter struct { cache *hmaps.Cache[string, Resource] delegate ResourceGetter+ hash uint64 } func (c *cachedResourceGetter) Get(name any) Resource {@@ -390,8 +408,6 @@ func unwrapResourceGetter(v any) (ResourceGetter, bool) { return vv, true case ResourcesProvider: return vv.Resources(), true- case func(name any) Resource:- return resourceGetterFunc(vv), true default: vvv, ok := hreflect.ToSliceAny(v) if !ok {resources/resource_factories/create/create.goindex 4a4d14da6..abea8c982 100644@@ -304,8 +304,9 @@ func (c *Client) FromOpts(opts Options) (resource.Resource, error) { } return c.rs.NewResource( resources.ResourceSourceDescriptor{- LazyPublish: true,- GroupIdentity: identity.Anonymous, // All usage of this resource are tracked via its string content.+ LazyPublish: true,+ IncludeHashInKey: !opts.TargetPathHasHash,+ GroupIdentity: identity.Anonymous, // All usage of this resource are tracked via its string content. OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return newReadSeeker() },resources/resource_spec.goindex 861cdc435..257edf1c3 100644@@ -201,7 +201,7 @@ func (r *Spec) NewResource(rd ResourceSourceDescriptor) (resource.Resource, erro h: &resourceHash{}, publishInit: &hsync.OnceMore{}, keyInit: &sync.Once{},- includeHashInKey: isImage,+ includeHashInKey: isImage || rd.IncludeHashInKey, paths: rp, spec: r, sd: rd,resources/resource_transformers/cssjs/inline_imports.goindex 44ae4b3c6..230add6e6 100644@@ -14,6 +14,7 @@ package cssjs import (+ "context" "crypto/sha256" "encoding/hex" "errors"@@ -30,6 +31,8 @@ import ( "github.com/gohugoio/hugo/common/text" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/identity"+ "github.com/gohugoio/hugo/resources"+ "github.com/gohugoio/hugo/resources/resource" "github.com/spf13/afero" ) @@ -46,10 +49,12 @@ type fileOffset struct { } type importResolver struct {+ ctx context.Context r io.Reader inPath string opts InlineImports + importContext resource.ResourceGetter contentSeen map[string]bool dependencyManager identity.Manager linemap map[int]fileOffset@@ -57,8 +62,9 @@ type importResolver struct { logger loggers.Logger } -func newImportResolver(r io.Reader, inPath string, opts InlineImports, fs afero.Fs, logger loggers.Logger, dependencyManager identity.Manager) *importResolver {- return &importResolver{+func newImportResolver(ctx context.Context, r io.Reader, inPath string, opts InlineImports, fs afero.Fs, logger loggers.Logger, dependencyManager identity.Manager) *importResolver {+ imp := &importResolver{+ ctx: ctx, r: r, dependencyManager: dependencyManager, inPath: inPath,@@ -66,6 +72,10 @@ func newImportResolver(r io.Reader, inPath string, opts InlineImports, fs afero. linemap: make(map[int]fileOffset), contentSeen: make(map[string]bool), opts: opts, }+ if opts.ImportContext != nil {+ imp.importContext = resource.NewCachedResourceGetter(opts.ImportContext)+ }+ return imp } func (imp *importResolver) contentHash(filename string) ([]byte, string) {@@ -73,9 +83,13 @@ func (imp *importResolver) contentHash(filename string) ([]byte, string) { if err != nil { return nil, "" }+ return b, hashBytes(b)+}++func hashBytes(b []byte) string { h := sha256.New() h.Write(b)- return b, hex.EncodeToString(h.Sum(nil))+ return hex.EncodeToString(h.Sum(nil)) } func (imp *importResolver) importRecursive(@@ -105,8 +119,35 @@ func (imp *importResolver) importRecursive( } else { path := strings.Trim(strings.TrimPrefix(line, importIdentifier), " \"';") filename := filepath.Join(basePath, path)- imp.dependencyManager.AddIdentity(identity.CleanStringIdentity(filename))- importContent, hash := imp.contentHash(filename)+ var (+ importContent []byte+ hash string+ nestedInPath string+ )+ if imp.importContext != nil {+ // Try first the path as written in the import statement,+ // then resolved relative to the importing file.+ for _, name := range []string{path, filepath.ToSlash(filename)} {+ r := imp.importContext.Get(name)+ if r == nil {+ continue+ }+ imp.dependencyManager.AddIdentity(identity.FirstIdentity(r))+ s, err := resources.InternalResourceSourceContent(imp.ctx, r)+ if err != nil {+ return 0, "", err+ }+ importContent, hash = []byte(s), hashBytes([]byte(s))+ nestedInPath = name+ break+ }+ }++ if importContent == nil {+ imp.dependencyManager.AddIdentity(identity.CleanStringIdentity(filename))+ importContent, hash = imp.contentHash(filename)+ nestedInPath = filepath.ToSlash(filename)+ } if importContent == nil { if imp.opts.SkipInlineImportsNotFound {@@ -135,7 +176,7 @@ func (imp *importResolver) importRecursive( imp.contentSeen[hash] = true // Handle recursive imports.- l, nested, err := imp.importRecursive(i+lineNum, string(importContent), filepath.ToSlash(filename))+ l, nested, err := imp.importRecursive(i+lineNum, string(importContent), nestedInPath) if err != nil { return 0, "", err }resources/resource_transformers/cssjs/inline_imports_test.goindex 3578e2612..bfbef977a 100644@@ -14,6 +14,7 @@ package cssjs import (+ "context" "regexp" "strings" "testing"@@ -21,10 +22,12 @@ import ( "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/htesting/hqt" "github.com/gohugoio/hugo/identity"+ "github.com/gohugoio/hugo/resources/resource" "github.com/gohugoio/hugo/helpers" "github.com/spf13/afero"+ "github.com/spf13/cast" qt "github.com/frankban/quicktest" )@@ -103,6 +106,7 @@ LOCAL_STYLE @import "e.css";`) imp := newImportResolver(+ t.Context(), mainStyles, "styles.css", InlineImports{},@@ -130,6 +134,70 @@ E_STYLE`) }) } +func TestImportResolverImportContext(t *testing.T) {+ c := qt.New(t)+ fs := afero.NewMemMapFs()++ writeFile := func(name, content string) {+ c.Assert(afero.WriteFile(fs, name, []byte(content), 0o777), qt.IsNil)+ }++ // Loses to the import context entry with the same name.+ writeFile("css/a.css", "A_STYLE_FS")+ writeFile("css/b.css", "B_STYLE_FS")++ importContext := testImportContext{+ "a.css": "@import \"c.css\";\nA_STYLE",+ "c.css": "C_STYLE",+ "css/d.css": "D_STYLE",+ }++ mainStyles := strings.NewReader(`@import "a.css";+@import "b.css";+@import "./d.css";+LOCAL_STYLE`)++ imp := newImportResolver(+ t.Context(),+ mainStyles,+ "css/styles.css",+ InlineImports{ImportContext: importContext},+ fs, loggers.NewDefault(),+ identity.NopManager,+ )++ r, err := imp.resolve()+ c.Assert(err, qt.IsNil)+ rs := helpers.ReaderToString(r)+ result := regexp.MustCompile(`\n+`).ReplaceAllString(rs, "\n")++ c.Assert(result, hqt.IsSameString, `C_STYLE+A_STYLE+B_STYLE_FS+D_STYLE+LOCAL_STYLE`)+}++type testImportContext map[string]string++func (g testImportContext) Get(name any) resource.Resource {+ s := cast.ToString(name)+ if content, found := g[s]; found {+ return testImportContextResource{name: s, content: content}+ }+ return nil+}++type testImportContextResource struct {+ resource.Resource+ name string+ content string+}++func (r testImportContextResource) Name() string { return r.name }++func (r testImportContextResource) Content(context.Context) (any, error) { return r.content, nil }+ func BenchmarkImportResolver(b *testing.B) { c := qt.New(b) fs := afero.NewMemMapFs()@@ -161,6 +229,7 @@ LOCAL_STYLE for b.Loop() { b.StopTimer() imp := newImportResolver(+ b.Context(), strings.NewReader(mainStyles), "styles.css", InlineImports{},resources/resource_transformers/cssjs/postcss.goindex 94295eea9..e1ca308b0 100644@@ -87,6 +87,10 @@ type InlineImports struct { // Note that the inline importer does not process url location or imports with media queries, // so those will be left as-is even without enabling this option. SkipInlineImportsNotFound bool++ // User provided import context. If set, imports are looked up here first,+ // by the path as written in the @import statement, then in the assets filesystem.+ ImportContext any } // Some of the options from https://github.com/postcss/postcss-cli@@ -213,6 +217,7 @@ func (t *postcssTransformation) Transform(ctx *resources.ResourceTransformationC src := ctx.From imp := newImportResolver(+ ctx.Ctx, ctx.From, ctx.InPath, options.InlineImports,resources/resource_transformers/cssjs/tailwindcss.goindex 539016dc2..e7c690cd0 100644@@ -124,6 +124,7 @@ func (t *tailwindcssTransformation) Transform(ctx *resources.ResourceTransformat src := ctx.From imp := newImportResolver(+ ctx.Ctx, ctx.From, ctx.InPath, options.InlineImports,resources/resource_transformers/cssjs/tailwindcss_integration_test.goindex e2ce293e3..03cd1e07e 100644@@ -64,6 +64,45 @@ CSS: {{ $css.Content | safeCSS }}| b.AssertFileContent("public/index.html", "/*! tailwindcss v4.") } +// See issue 15103.+func TestTailwindCSSImportContext(t *testing.T) {+ t.Parallel()+ htesting.SkipSlowTestUnlessCI(t)++ files := `+-- hugo.toml --+disableKinds = ['page','rss','section','sitemap','taxonomy','term']+-- assets/css/main.css --+@import "tailwindcss";++@import "foo.css";+@import "bar.css";+-- assets/css/foo.css --+.foo {color: orange;}+-- layouts/home.html --+{{ $foo := resources.FromString "foo.css" ".foo {color: blue;}" }}+{{ $bar := resources.FromString "bar.css" ".bar {color: green;}" }}+{{ $opts := dict "importContext" (slice $foo $bar) }}+{{ $css := resources.Get "css/main.css" | css.TailwindCSS $opts }}+CSS: {{ $css.Content | safeCSS }}|+-- package.json --+{+ "devDependencies": {+ "@tailwindcss/cli": "^4.1.7",+ "tailwindcss": "^4.1.7"+ }+}+`++ b := hugolib.Test(t, files, hugolib.TestOptOsFs(), hugolib.TestOptWithNpmInstall(), hugolib.TestOptInfo())++ // foo.css resolves in the import context before the assets filesystem.+ b.AssertFileContent("public/index.html",+ ".foo {\n color: blue;\n }",+ ".bar {\n color: green;\n }",+ )+}+ func TestTailwindCSSNoInlineImportsIssue13719(t *testing.T) { t.Parallel() htesting.SkipSlowTestUnlessCI(t)resources/resource_transformers/js/build.goindex f0ea8ea8b..0415b058a 100644@@ -42,6 +42,8 @@ func New(fs *filesystems.SourceFilesystem, rs *resources.Spec, cssMode bool) *Cl } // Process processes a resource with the user provided options.+// If importContext is not nil, imports are resolved in it first,+// then in the assets filesystem (the same precedence as in js.Batch). func (c *Client) Process(res resources.ResourceTransformer, opts map[string]any) (resource.Resource, error) { return res.Transform( &buildTransformation{c: c, optsm: opts},resources/resource_transformers/js/transform.goindex 07933a92f..3da5f8e87 100644@@ -18,10 +18,14 @@ import ( "path" "path/filepath" + "github.com/evanw/esbuild/pkg/api"+ "github.com/gohugoio/hugo/common/hmaps"+ "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/internal/js/esbuild" "github.com/gohugoio/hugo/media" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/internal"+ "github.com/gohugoio/hugo/resources/resource" ) type buildTransformation struct {@@ -69,6 +73,29 @@ func (t *buildTransformation) Transform(ctx *resources.ResourceTransformationCtx opts.MediaType = ctx.InMediaType opts.Stdin = true opts.IsCSS = t.c.c.CssMode+ var ic resource.ResourceGetter+ if opts.ImportContext != nil {+ ic = resource.NewCachedResourceGetter(opts.ImportContext)+ }++ if ic != nil {+ resolved := hmaps.NewCache[string, resource.Resource]()+ opts.ImportOnResolveFunc = func(imp string, args api.OnResolveArgs) string {+ if r := esbuild.ResolveResource(imp, ic); r != nil {+ p := esbuild.PrefixHugoVirtual + resources.InternalResourceTargetPath(r)+ resolved.Set(p, r)+ ctx.DependencyManager.AddIdentity(identity.FirstIdentity(r))+ return p+ }+ return ""+ }+ opts.ImportOnLoadFunc = func(args api.OnLoadArgs) (string, error) {+ if r, found := resolved.Get(args.Path); found {+ return resources.InternalResourceSourceContent(ctx.Ctx, r)+ }+ return "", nil+ }+ } _, err = t.c.transform(opts, ctx) resources/resource_transformers/tocss/dartsass/client.goindex cd01b12ee..02ff0bb94 100644@@ -158,6 +158,10 @@ type Options struct { // $color: vars.$color; Vars map[string]any + // User provided import context. If set, imports are looked up here first,+ // then in the assets filesystem.+ ImportContext any+ // Deprecations IDs in this slice will be silenced. // The IDs can be found in the Dart Sass log output, e.g. "import" in // WARN Dart Sass: DEPRECATED [import].resources/resource_transformers/tocss/dartsass/dartsass_integration_test.goindex 72e012667..2acbd8194 100644@@ -51,6 +51,35 @@ T1: {{ $r.Content }} b.AssertFileContent("public/index.html", `T1: moo{color:#fff}`) } +// See issue 15103.+func TestTransformImportContext(t *testing.T) {+ t.Parallel()+ if !dartsass.Supports() {+ t.Skip()+ }++ files := `+-- hugo.toml --+-- assets/scss/_foo.scss --+body { color: orange; }+-- assets/scss/main.scss --+@import "foo";+@import "bar";+-- layouts/home.html --+{{ $foo := resources.FromString "foo.scss" "body { color: blue; }" }}+{{ $bar := resources.FromString "bar.scss" "@import \"baz\";\nbody { color: green; }" }}+{{ $baz := resources.FromString "baz.scss" "p { color: red; }" }}+{{ $opts := dict "transpiler" "dartsass" "outputStyle" "compressed" "importContext" (slice $foo $bar $baz) }}+{{ $r := resources.Get "scss/main.scss" | css.Sass $opts }}+T1: {{ $r.Content }}+ `++ b := hugolib.Test(t, files, hugolib.TestOptOsFs())++ // foo resolves in the import context before the assets filesystem.+ b.AssertFileContent("public/index.html", `T1: body{color:blue}p{color:red}body{color:green}`)+}+ func TestTransformImportRegularCSS(t *testing.T) { t.Parallel() if !dartsass.Supports() {resources/resource_transformers/tocss/dartsass/transform.goindex e3d5823e9..680301b20 100644@@ -14,6 +14,7 @@ package dartsass import (+ "context" "fmt" "io" "path"@@ -27,6 +28,7 @@ import ( "github.com/gohugoio/hugo/media" "github.com/gohugoio/hugo/resources"+ "github.com/gohugoio/hugo/resources/resource" "github.com/gohugoio/hugo/resources/internal" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/sass"@@ -38,6 +40,10 @@ import ( "github.com/bep/godartsass/v2" ) +// Prefix for canonical URLs of stylesheets resolved in the user provided import context.+// Note: This prefix must be all lower case.+const dartSassImportContextPrefix = "hugoimportcontext:"+ // Supports returns whether sass, dart-sass, or dart-sass-embedded is found in $PATH. func Supports() bool { if htesting.SupportsAll() {@@ -76,6 +82,11 @@ func (t *transform) Transform(ctx *resources.ResourceTransformationCtx) error { filename += t.c.sfs.RealFilename(ctx.SourcePath) } + var ic resource.ResourceGetter+ if opts.ImportContext != nil {+ ic = resource.NewCachedResourceGetter(opts.ImportContext)+ }+ args := godartsass.Args{ URL: filename, IncludePaths: t.c.sfs.RealDirs(baseDir),@@ -83,6 +94,8 @@ func (t *transform) Transform(ctx *resources.ResourceTransformationCtx) error { baseDir: baseDir, c: t.c, dependencyManager: ctx.DependencyManager,+ importContext: ic,+ ctx: ctx.Ctx, vars: opts.Vars, },@@ -132,6 +145,8 @@ type importResolver struct { baseDir string c *Client dependencyManager identity.Manager+ importContext resource.ResourceGetter+ ctx context.Context vars map[string]any } @@ -140,6 +155,11 @@ func (t importResolver) CanonicalizeURL(url string) (string, error) { return strings.ToLower(url), nil } + if r := t.resolveInImportContext(url); r != nil {+ t.dependencyManager.AddIdentity(identity.FirstIdentity(r))+ return dartSassImportContextPrefix + paths.ToSlashTrimLeading(resources.InternalResourceTargetPath(r)), nil+ }+ filePath, isURL := paths.UrlStringToFilename(url) var prevDir string var pathDir string@@ -160,21 +180,7 @@ func (t importResolver) CanonicalizeURL(url string) (string, error) { name := filepath.Base(filePath) // Pick the first match.- var namePatterns []string- if strings.Contains(name, ".") {- namePatterns = []string{"_%s", "%s"}- } else if strings.HasPrefix(name, "_") {- namePatterns = []string{"_%s.scss", "_%s.sass", "_%s.css"}- } else {- namePatterns = []string{- "_%s.scss", "%s.scss",- "_%s.sass", "%s.sass",- "_%s.css", "%s.css",- "%s/_index.scss", "%s/_index.sass",- "%s/index.scss", "%s/index.sass",- }- }-+ namePatterns := sassNamePatterns(name) name = strings.TrimPrefix(name, "_") for _, namePattern := range namePatterns {@@ -192,21 +198,72 @@ func (t importResolver) CanonicalizeURL(url string) (string, error) { return "", nil } +func sassNamePatterns(name string) []string {+ if strings.Contains(name, ".") {+ return []string{"_%s", "%s"}+ }+ if strings.HasPrefix(name, "_") {+ return []string{"_%s.scss", "_%s.sass", "_%s.css"}+ }+ return []string{+ "_%s.scss", "%s.scss",+ "_%s.sass", "%s.sass",+ "_%s.css", "%s.css",+ "%s/_index.scss", "%s/_index.sass",+ "%s/index.scss", "%s/index.sass",+ }+}++// resolveInImportContext resolves url in the user provided import context, if any,+// using the same name patterns as for the file system.+func (t importResolver) resolveInImportContext(url string) resource.Resource {+ if t.importContext == nil {+ return nil+ }+ url = strings.TrimPrefix(url, dartSassImportContextPrefix)+ if r := t.importContext.Get(url); r != nil {+ return r+ }+ dir, name := path.Split(url)+ namePatterns := sassNamePatterns(name)+ name = strings.TrimPrefix(name, "_")+ for _, namePattern := range namePatterns {+ if r := t.importContext.Get(path.Join(dir, fmt.Sprintf(namePattern, name))); r != nil {+ return r+ }+ }+ return nil+}+ func (t importResolver) Load(url string) (godartsass.Import, error) { if subPath, ok := sass.HugoVarsSubPath(url); ok { return godartsass.Import{ Content: sass.CreateVarsStyleSheet(sass.TranspilerDart, sass.ResolveVars(t.vars, subPath)), }, nil }++ if strings.HasPrefix(url, dartSassImportContextPrefix) {+ r := t.resolveInImportContext(url)+ if r == nil {+ return godartsass.Import{}, fmt.Errorf("could not find %q in the import context", url)+ }+ content, err := resources.InternalResourceSourceContent(t.ctx, r)+ return godartsass.Import{Content: content, SourceSyntax: sassSourceSyntax(url)}, err+ }+ filename, _ := paths.UrlStringToFilename(url) b, err := afero.ReadFile(hugofs.Os, filename) - sourceSyntax := godartsass.SourceSyntaxSCSS- if strings.HasSuffix(filename, ".sass") {- sourceSyntax = godartsass.SourceSyntaxSASS- } else if strings.HasSuffix(filename, ".css") {- sourceSyntax = godartsass.SourceSyntaxCSS- }+ return godartsass.Import{Content: string(b), SourceSyntax: sassSourceSyntax(filename)}, err+} - return godartsass.Import{Content: string(b), SourceSyntax: sourceSyntax}, err+func sassSourceSyntax(name string) godartsass.SourceSyntax {+ switch {+ case strings.HasSuffix(name, ".sass"):+ return godartsass.SourceSyntaxSASS+ case strings.HasSuffix(name, ".css"):+ return godartsass.SourceSyntaxCSS+ default:+ return godartsass.SourceSyntaxSCSS+ } }tpl/css/build_integration_test.goindex 31b692a8e..1818bcf11 100644@@ -731,3 +731,181 @@ body { "--text-color: #333;", ) }++func TestCSSBuildImportContext(t *testing.T) {+ t.Parallel()++ files := `+-- hugo.toml --+-- assets/foo.css --+body { color: orange; }+-- assets/css/main.css --+@import "foo.css" screen;+@import "bar.css" print;+p {+ font-color: red;+}+-- layouts/home.html --+{{ $foo := resources.FromString "foo.css" "body { color: blue; }" }}+{{ $bar := resources.FromString "bar.css" "body { color: green; }" }}+{{/* resource.Resources implements the resources.ResourceGetter interface (the type of importContext). */}}+{{ $resources := slice $foo $bar}}+{{ $opts := dict "minify" true "importContext" $resources }}+{{ $css := resources.Get "css/main.css" | css.Build $opts }}+CSS: {{ $css.RelPermalink }}|+`++ b := hugolib.Test(t, files, hugolib.TestOptOsFs())++ b.AssertFileContent("public/css/main.css", `@media screen{body{color:#00f}}@media print{body{color:green}}p{font-color:red}`)+}++func TestCSSBuildImportContextChromaStyles(t *testing.T) {+ t.Parallel()++ files := `+-- hugo.toml --+disableKinds = ["taxonomy", "term", "rss", "sitemap", "section", "page"]+[markup.highlight]+style = "monokai"+-- assets/css/components/all.css --+@import "./chroma-light.css";+@import "./chroma-dark.css" (prefers-color-scheme: dark);+-- assets/css/main.css --+@import "./components/all.css";++:root {+ color-scheme: light dark;+}++-- layouts/home.html --+{{ $light := css.ChromaStyles (dict "targetPath" "css/components/chroma-light.css" "style" "github" "mode" "light") }}+{{ $dark := css.ChromaStyles (dict "targetPath" "css/components/chroma-dark.css" "style" "github" "mode" "dark") }}+{{ $opts := dict "minify" true "importContext" (slice $light $dark) }}+{{ $css := resources.Get "css/main.css" | css.Build $opts }}+CSS: {{ $css.RelPermalink }}|+`++ b := hugolib.Test(t, files, hugolib.TestOptOsFs())++ b.AssertFileContent("public/index.html", "CSS: /css/main.css|")+ b.AssertFileContent("public/css/main.css", ".bg{background-color:#f7f7f7}.chroma", "@media(prefers-color-scheme:dark){.bg{color:#e6edf3")+}++func TestCSSBuildImportContextHashes(t *testing.T) {+ t.Parallel()++ files := `+-- hugo.toml --+-- assets/foo.css --+body { color: orange; }+-- assets/css/main.css --+@import "foo.css" screen;+@import "bar.css" print;+p {+ font-color: red;+}+-- layouts/home.html --+{{ $foo := resources.FromString "foo.css" "body { color: blue; }" }}|+{{ $foo2 := resources.FromString "foo2.css" "body { color: blue; }" }}|+{{ $foo3 := resources.FromString "foo.css" "body { color: indigo; }" }}|+{{ $bar := resources.FromString "bar.css" "body { color: green; }" }}|+{{ $resources := slice $foo $bar}}+{{ $resourcesMount1 := $resources.Mount "a" "b"}}+{{ $resourcesMount2 := $resources.Mount "a" "c"}}+{{ $opts := dict "minify" true "importContext" $resources }}+foo: {{ $foo | testinginternal.HashString }}|+foo2: {{ $foo2 | testinginternal.HashString }}|+foo3: {{ $foo3 | testinginternal.HashString }}|+bar: {{ $bar | testinginternal.HashString }}|+resources: {{ $resources | testinginternal.HashString }}|+resourcesMount1: {{ $resourcesMount1 | testinginternal.HashString }}|+resourcesMount2: {{ $resourcesMount2 | testinginternal.HashString }}|+resources namespace: {{ resources | testinginternal.HashString }}|+opts: {{ $opts | testinginternal.HashString }}|+home: {{ . | testinginternal.HashString }}|{{ .Key }}|+slice with Page: {{ slice $foo $bar . | testinginternal.HashString }}|+map with Page: {{ dict "foo" $foo "bar" $bar "page" . | testinginternal.HashString }}|+{{ $css := resources.Get "css/main.css" | css.Build $opts -}}+css: {{ $css | testinginternal.HashString }}|+cached1: {{ testinginternal.NewCachedResourceGetter $resources resources | testinginternal.HashString}}+cached2: {{ testinginternal.NewCachedResourceGetter $resources | testinginternal.HashString}}+cached3: {{ testinginternal.NewCachedResourceGetter $resources resources $resourcesMount1 $resourcesMount2 | testinginternal.HashString}}+++`++ for range 2 {++ b := hugolib.Test(t, files, hugolib.TestOptOsFs())++ b.AssertFileContent("public/index.html", `+foo: 17610550322594361312|+foo2: 12741631597870435822|+foo3: 4488319114298108946|+bar: 11981658863051989001|+resources: 10963320145636139629|+resourcesMount1: 7843365040860281860|+resourcesMount2: 10632811173795339581|+resources namespace: 12714111578321948564|+opts: 7538269917289793785|+css: 8075855322897706813|+home: 166103792234269065|/html|+slice with Page: 7769684332502419906|+map with Page: 10393165700333352395|+cached1: 7064840587060576200+cached2: 6730658186132701788+cached3: 13761938017162285970+`)++ }+}++func TestCSSBuildImportContextEdit(t *testing.T) {+ t.Parallel()++ files := `+-- hugo.toml --+disableLiveReload = true+-- assets/css/common/baz.css --+body { color: purple; }+-- assets/css/main.css --+@import "foo.css" screen;+@import "bar.css" print;+@import "baz.css" screen and (min-width: 768px);+p {+ font-color: red;+}+-- layouts/home.html --+{{ $foo := resources.FromString "foo.css" "body { color: blue; }" }}+{{ $bar := resources.FromString "bar.css" "body { color: green; }" }}+{{ $common := resources.Match "/css/common/*.css" }}+{{ $commonMount := ($common.Mount "/css/common" ".")}}+{{ $resources := slice $foo $bar }}+{{ $opts := dict "minify" true "importContext" (slice $resources $commonMount) }}+resources: {{ $resources | testinginternal.HashString }}|+{{ $css := resources.Get "css/main.css" | css.Build $opts }}+CSS: {{ $css.RelPermalink }}|+`++ b := hugolib.TestRunning(t, files, hugolib.TestOptOsFs())++ b.AssertFileContent("public/css/main.css", `+@media screen{body{color:#00f}}@media print{body{color:green}}+@media screen and (min-width:768px){body{color:purple}}+`)++ // Edit resource built with resources.FromString.+ b.EditFileReplaceAll("layouts/home.html", "color: green", "color: yellow").Build()+ b.AssertFileContent("public/css/main.css", `+@media screen{body{color:#00f}}@media print{body{color:#ff0}}+@media screen and (min-width:768px){body{color:purple}}+`)++ // Edit resource in the mounted slice.+ b.EditFileReplaceAll("assets/css/common/baz.css", "purple", "orange").Build()+ b.AssertFileContent("public/css/main.css", `+@media screen{body{color:#00f}}@media print{body{color:#ff0}}+@media screen and (min-width:768px){body{color:orange}}+`)+}tpl/resources/resources.goindex 2512b5ce9..aae6ac1f3 100644@@ -58,7 +58,10 @@ func New(deps *deps.Deps) (*Namespace, error) { }, nil } -var _ resource.ResourceFinder = (*Namespace)(nil)+var (+ _ resource.ResourceFinder = (*Namespace)(nil)+ _ resource.Identifier = (*Namespace)(nil)+) // Namespace provides template functions for the "resources" namespace. type Namespace struct {@@ -300,3 +303,8 @@ func (ns *Namespace) PostProcess(r resource.Resource) (postpub.PostPublishedReso hugo.DeprecateWithLogger("resources.PostProcess", "Use templates.Defer instead. See https://gohugo.io/functions/templates/defer/", "v0.164.0", ns.deps.Log.Logger()) return ns.deps.ResourceSpec.PostProcess(r) }++// For internal use only.+func (ns *Namespace) Key() string {+ return "tpl.resources"+}tpl/testinginternal/init.gonew file mode 100644index 000000000..213e81b79@@ -0,0 +1,38 @@+// Copyright 2026 The Hugo Authors. All rights reserved.+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package testinginternal++import (+ "context"++ "github.com/gohugoio/hugo/deps"+ "github.com/gohugoio/hugo/tpl/internal"+)++const name = "testinginternal"++func init() {+ f := func(d *deps.Deps) *internal.TemplateFuncsNamespace {+ ctx := New(d)++ ns := &internal.TemplateFuncsNamespace{+ Name: name,+ Context: func(cctx context.Context, args ...any) (any, error) { return ctx, nil },+ }++ return ns+ }++ internal.AddTemplateFuncsNamespace(f)+}tpl/testinginternal/testinginternal.gonew file mode 100644index 000000000..80beb5939@@ -0,0 +1,41 @@+// Copyright 2026 The Hugo Authors. All rights reserved.+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++// Package testinginternal provides template functions for internal use.+// // These should not be used in user templates, as they are not guaranteed to be stable or even useful.+package testinginternal++import (+ "github.com/gohugoio/hugo/common/hashing"+ "github.com/gohugoio/hugo/deps"+ "github.com/gohugoio/hugo/resources/resource"+)++// New returns a new instance of the testinginternal-namespaced template functions.+func New(d *deps.Deps) *Namespace {+ ns := &Namespace{}++ return ns+}++// Namespace provides template functions for the "testinginternal" namespace.+type Namespace struct{}++// HashString wraps the core hashing func used for e.g. calculating resource transformation keys.+func (ns *Namespace) HashString(args ...any) string {+ return hashing.HashString(args...)+}++func (ns *Namespace) NewCachedResourceGetter(args ...any) resource.ResourceGetter {+ return resource.NewCachedResourceGetter(args...)+}tpl/tplimplinit/tplimplinit.goindex a958b0669..4dc844c7a 100644@@ -49,6 +49,7 @@ import ( _ "github.com/gohugoio/hugo/tpl/site" _ "github.com/gohugoio/hugo/tpl/strings" _ "github.com/gohugoio/hugo/tpl/templates"+ _ "github.com/gohugoio/hugo/tpl/testinginternal" _ "github.com/gohugoio/hugo/tpl/time" _ "github.com/gohugoio/hugo/tpl/transform" _ "github.com/gohugoio/hugo/tpl/urls"