Backtestshugorun-20261007-020926#15103

Issue #15103 Merged fix PR #15156 Run 7 Oct 2026 · run-20261007-020926 gohugoio/hugo

Add importContext to resources.Copy

Better

Our patch was judged better than the merged fix.

In this judgment, Patch A = our agent, Patch B = the merged fix.

The issue asks for an `importContext` option on `resources.Copy`, with the signature changed to `resources.Copy [STRING or MAP] RESOURCE`. The context would be stored as internal state on the resource and honored by css.Build, js.Build/Batch, css.Sass and TailwindCSS.

Patch A implements exactly that. `resources.Copy` now accepts a target path, an options map, or nothing, and validates unknown options. An `ImportContext` is stored in an unexported field on `genericResource` and forwarded via `ResourceTransformationCtx.ImportContext`. It is consumed by:
- esbuild (js.Build/css.Build via `ApplyImportContext`)
- js.Batch, as a fallback through `InternalResourceImportContext`
- the PostCSS/Tailwind inline-import resolver
- Dart Sass
- LibSass

Patch A also handles cache correctness. The import context's key, including content hashes for in-memory resources, is folded into both the copy cache key and the resource `Key()`. Copies of the same resource with different contexts therefore don't collide, and a test covers this. Its tests are thorough and meaningful: CSS build with precedence and fallback to assets, JS build, cache separation, a Page as context, Mount, rebuild on edit, option validation, Dart Sass, LibSass, js.Batch, and unit tests for the resolver and getter. Docs are updated too.

Patch B does not touch `resources.Copy` at all, so the requested API is absent. Instead it adds `importContext` as an option to css.Build/js.Build, css.Sass (Dart) and TailwindCSS/PostCSS. To make those options hashable for transformation keys, it makes broad, risky changes:
- bumps `hashstructure` to v1.0.0 and rewrites hashing to use an UnwrapFunc
- removes `pageState.Key()` and adds `pageOutput.Key()`
- changes `Color.Hash` to `Key`
- changes `FromString` resource keys to include content hashes
- adds a new `testinginternal` template namespace exposed to all templates

These changes affect cache keys globally and add regression risk well beyond the issue. Its hash test hardcodes magic numbers, which is brittle. LibSass support is missing.

Patch A matches the issue's requested design, covers more transformers, and is better tested with less collateral risk.

The judge saw only the two patches, labelled A and B in random order, with issue links and version numbers removed. The reasoning above is shown verbatim.

Solve

1h 13m

Wall-clock time in the container

Full test suite

No new failures

3,696 passed · 99 skipped · 3,804 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

1,187vs 791 merged

Changed lines, ours vs merged

The 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.Batch takes importContext as 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.Build and, once that looks good, implement it in js.Build/Batch, css.Sass and css.TailwindCSS.

The two patches

Our patch+1130 −57
docs/content/en/functions/resources/Copy.mdindex 208f6d65f..2b0befea2 100644@@ -1,12 +1,12 @@ --- title: resources.Copy-description: Copies the given resource to the target path.+description: Copies the given resource to the target path, optionally with an import context. categories: [] params:   functions_and_methods:     aliases: []     returnType: resource.Resource-    signatures: [resources.Copy TARGETPATH RESOURCE]+    signatures: ['resources.Copy [TARGETPATH|OPTIONS] RESOURCE'] ---  ```go-html-template@@ -17,7 +17,44 @@ params: {{ end }} ``` -The `TARGETPATH` is relative to the server root. A leading slash is optional and has no effect.+The `TARGETPATH` is relative to the server root. A leading slash is optional and has no effect. If you omit both `TARGETPATH` and `OPTIONS`, the copy keeps the target path of the given resource.  > [!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. Defaults to the target path of the given resource.++importContext+: (`slice` or `resource`) Resources used to resolve imports when the copy is transformed by [`css.Build`], [`js.Build`], [`js.Batch`], [`css.Sass`], [`css.PostCSS`] (with `inlineImports` enabled) and [`css.TailwindCSS`]. This can be a resource, a page (its page resources are used), the result of a `Mount` on a slice of resources, or a slice of these. The first match wins, and the import context takes precedence over the files in the `assets` directory. Imports not found in the import context are resolved as usual. See the [import context] in `js.Batch` for more information.++```go-html-template+{{ $foo := resources.FromString "foo.css" "body { color: blue; }" }}+{{ $bar := resources.FromString "bar.css" "body { color: green; }" }}+{{ $opts := dict+  "targetPath" "css/styles.css"+  "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/+[import context]: /functions/js/batch/#import-contextinternal/js/esbuild/batch.goindex 61c6b6d5c..a8f669d7c 100644@@ -1328,15 +1328,16 @@ func (s scriptOptions) compileOptions(m map[string]any, defaults defaultOptionVa 		v.Export = defaults.defaultExport 	} -	compiled := scriptOptions{-		Resource:      v.Resource,-		Export:        v.Export,-		ImportContext: resource.NewCachedResourceGetter(v.ImportContext),-		Params:        paramsJSON,+	if v.Resource == nil {+		return scriptOptions{}, fmt.Errorf("resource not set") 	} -	if compiled.Resource == nil {-		return scriptOptions{}, fmt.Errorf("resource not set")+	compiled := scriptOptions{+		Resource: v.Resource,+		Export:   v.Export,+		// Fall back to the resource's own import context (e.g. set via resources.Copy).+		ImportContext: resource.NewCachedResourceGetter(v.ImportContext, resources.InternalResourceImportContext(v.Resource)),+		Params:        paramsJSON, 	}  	return compiled, nilinternal/js/esbuild/batch_integration_test.goindex ca85cb4a7..a7c32c3c6 100644@@ -733,3 +733,32 @@ 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 {") }++// The script resource's own import context (set via resources.Copy) is used when no importContext option is set.+func TestBatchScriptResourceImportContextFromCopy(t *testing.T) {+	files := `+-- hugo.toml --+disableKinds = ["taxonomy", "term", "section", "page", "rss", "sitemap"]+disableLiveReload = true+-- assets/js/main.js --+import { greeting } from "greeting.js";+console.log("main", greeting);+-- layouts/home.html --+{{ $greeting := resources.FromString "greeting.js" "export const greeting = 'hello-from-copy-import-context';" }}+{{ $main := resources.Get "js/main.js" | resources.Copy (dict "importContext" $greeting) }}+{{ $batch := (js.Batch "mybatch") }}+{{ with $batch.Group "mygroup" }}+  {{ with .Script "main" }}+    {{ .SetOptions (dict "resource" $main) }}+  {{ end }}+{{ end }}+{{ range $k, $v := $batch.Build.Groups }}+  {{ range $kk, $vv := . }}{{ $k }}: {{ .RelPermalink }}|{{ end }}+{{ end }}+`++	b := hugolib.Test(t, files, hugolib.TestOptWithOSFs())++	b.AssertFileContent("public/index.html", "mygroup: /mybatch/mygroup.js|")+	b.AssertFileContent("public/mybatch/mygroup.js", "hello-from-copy-import-context")+}internal/js/esbuild/importcontext.gonew file mode 100644index 000000000..0ee9be55b@@ -0,0 +1,102 @@+// 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"+	"fmt"+	"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"+)++// ApplyImportContext configures opts to resolve imports using importContext+// before falling back to the regular resolution in /assets.+// Resolved imports are registered in dm, which may be nil.+// This is a no-op if importContext is nil.+// The import context is used for imports in the entry point (stdin) and for imports in+// files resolved by Hugo (from the import context or /assets), but not for imports in node_modules.+func ApplyImportContext(ctx context.Context, opts *Options, importContext resource.ResourceGetter, dm identity.Manager) {+	if importContext == nil {+		return+	}++	importResource := hmaps.NewCache[string, resource.Resource]()++	opts.ImportOnResolveFunc = func(imp string, args api.OnResolveArgs) string {+		if args.Importer != stdinImporter && args.Namespace != NsHugoImport && args.Namespace != NsHugoImportResolveFunc {+			return ""+		}++		r := ResolveResource(strings.TrimPrefix(imp, "./"), importContext)+		if r == nil {+			return ""+		}++		if dm != nil {+			dm.AddIdentity(identity.FirstIdentity(r))+		}++		p := PrefixHugoVirtual + resources.InternalResourceTargetPath(r)+		importResource.Set(p, r)+		return p+	}++	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 {+		loc := msg.Location+		if loc == nil {+			return nil+		}+		r, found := importResource.Get(strings.TrimPrefix(loc.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 ""+	}+}resources/import_context.gonew file mode 100644index 000000000..df9968d8c@@ -0,0 +1,151 @@+// 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"+)++var _ resource.ResourceGetter = (*ImportContext)(nil)++// ImportContext is a ResourceGetter used to resolve imports (e.g. CSS @import or JS import statements)+// when transforming a Resource, before falling back to the regular resolution in /assets.+type ImportContext struct {+	resource.ResourceGetter++	// A key identifying this import context, used to separate cache entries.+	key string+}++// Key returns a key identifying this import context.+func (c *ImportContext) Key() string {+	return c.key+}++// NewImportContext creates a new ImportContext from v, which can be a Resource,+// a Page, the result of Resources.Mount, or a slice of these.+// It returns nil if v is nil or an empty slice.+func NewImportContext(ctx context.Context, v any) (*ImportContext, error) {+	if v == nil {+		return nil, nil+	}++	g, ok := resource.NewResourceGetter(v)+	if !ok {+		if s, isSlice := hreflect.ToSliceAny(v); isSlice && len(s) == 0 {+			return nil, nil+		}+		return nil, fmt.Errorf("importContext: unsupported type %T", v)+	}++	key, err := importContextKey(ctx, v)+	if err != nil {+		return nil, fmt.Errorf("importContext: %w", err)+	}++	return &ImportContext{+		ResourceGetter: g,+		key:            hashing.XxHashFromStringHexEncoded(key),+	}, nil+}++// importContextKey creates a string that identifies the import context in v.+// For resources this includes a hash of the content, as resources created in+// memory (e.g. with resources.FromString) are not tracked for changes in any other way.+func importContextKey(ctx context.Context, v any) (string, error) {+	switch vv := v.(type) {+	case nil:+		return "", nil+	case *resource.MountedResources:+		base, target, rr := vv.MountInfo()+		k, err := importContextKey(ctx, rr)+		if err != nil {+			return "", err+		}+		return fmt.Sprintf("mount(%s|%s|%s)", base, target, k), nil+	case resource.ResourcesProvider:+		// E.g. a Page. Changes to its resources are tracked via the page.+		ip, ok := vv.(identity.IdentityProvider)+		if !ok {+			return "", fmt.Errorf("unsupported type %T", v)+		}+		k := "page(" + ip.GetIdentity().IdentifierBase()+		if lp, ok := vv.(interface{ Lang() string }); ok {+			k += "|" + lp.Lang()+		}+		return k + ")", nil+	case resource.Resource:+		k := vv.Name()+		if id, ok := vv.(resource.Identifier); ok {+			k = id.Key()+		}+		content, err := InternalResourceSourceContent(ctx, vv)+		if err != nil {+			return "", err+		}+		return fmt.Sprintf("resource(%s|%s)", k, hashing.XxHashFromStringHexEncoded(content)), nil+	default:+		s, ok := hreflect.ToSliceAny(v)+		if !ok {+			return "", fmt.Errorf("unsupported type %T", v)+		}+		var sb strings.Builder+		sb.WriteString("[")+		for i, e := range s {+			if i > 0 {+				sb.WriteString(",")+			}+			k, err := importContextKey(ctx, e)+			if err != nil {+				return "", err+			}+			sb.WriteString(k)+		}+		sb.WriteString("]")+		return sb.String(), nil+	}+}++// CopyWithImportContext copies r to the targetPath given and attaches the import context ic.+// If ic is nil, this is the same as Copy.+func CopyWithImportContext(r resource.Resource, targetPath string, ic *ImportContext) resource.Resource {+	c := Copy(r, targetPath)+	if ic != nil {+		c.(importContextProvider).setImportContext(ic)+	}+	return c+}++// InternalResourceImportContext is used internally to get the import context attached to a Resource,+// e.g. via resources.Copy. It returns nil if not set.+func InternalResourceImportContext(r resource.Resource) resource.ResourceGetter {+	if p, ok := r.(importContextProvider); ok {+		if ic := p.getImportContext(); ic != nil {+			return ic+		}+	}+	return nil+}++type importContextProvider interface {+	getImportContext() *ImportContext+	setImportContext(*ImportContext)+}resources/resource.goindex cf6e1e597..049cda01f 100644@@ -225,6 +225,12 @@ type resourceCopier interface { 	cloneTo(targetPath string) resource.Resource } +// IsCopyable reports whether r can be copied with Copy.+func IsCopyable(r resource.Resource) bool {+	_, ok := r.(resourceCopier)+	return ok+}+ // Copy copies r to the targetPath given. func Copy(r resource.Resource, targetPath string) resource.Resource { 	return r.(resourceCopier).cloneTo(targetPath)@@ -244,6 +250,7 @@ type baseResourceInternal interface {  	sourcePath() string 	fileInfo+	importContextProvider 	mediaTypeAssigner 	targetPather 	isPublishedProvider@@ -379,6 +386,9 @@ type genericResource struct { 	name   string 	params map[string]any +	// Used to resolve imports in transformations, set via resources.Copy.+	importContext *ImportContext+ 	spec *Spec } @@ -426,6 +436,14 @@ func (l *genericResource) setTargetPath(d internal.ResourcePaths) { 	l.paths = d } +func (l *genericResource) getImportContext() *ImportContext {+	return l.importContext+}++func (l *genericResource) setImportContext(ic *ImportContext) {+	l.importContext = ic+}+ func (l *genericResource) cloneTo(targetPath string) resource.Resource { 	c := l.clone() 	c.paths = c.paths.FromTargetPath(targetPath)@@ -462,6 +480,10 @@ func (l *genericResource) Key() string { 		if l.includeHashInKey && !l.sourceFilenameIsHash { 			l.key += fmt.Sprintf("_%d", l.hash()) 		}++		if l.importContext != nil {+			l.key += "_ic" + l.importContext.Key()+		} 	})  	return l.keyresources/resource/resources.goindex 28fbab42f..6e33d4b78 100644@@ -35,42 +35,62 @@ 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 method is currently only 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{base: base, target: target, resources: r}+} -		isTargetAbs := strings.HasPrefix(target, "/")+var _ ResourceGetter = (*MountedResources)(nil) -		if target != "" {-			name1 = strings.TrimPrefix(name1, target)-			if !isTargetAbs {-				name1 = paths.TrimLeading(name1)-			}-		}+// MountedResources is a ResourceGetter created by Resources.Mount.+type MountedResources struct {+	base      string+	target    string+	resources Resources+} -		if base != "" && isTargetAbs {-			name1 = path.Join(base, name1)+// MountInfo returns the base and target path and the resources mounted.+// For internal use.+func (m *MountedResources) MountInfo() (base, target string, resources Resources) {+	return m.base, m.target, m.resources+}++// Get gets the resource with the given name relative to the mount target.+func (m *MountedResources) Get(namev any) Resource {+	name1, err := cast.ToStringE(namev)+	if err != nil {+		panic(err)+	}++	base, target := m.base, m.target++	isTargetAbs := strings.HasPrefix(target, "/")++	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.resources {+		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 {@@ -318,6 +338,20 @@ type ResourceFinder interface { 	ByType(typ any) Resources } +// NewResourceGetter creates a new ResourceGetter from the given objects.+// If multiple objects are provided, they are merged into one where+// the first match wins.+// It returns false if none of the given objects can be used as a ResourceGetter.+func NewResourceGetter(os ...any) (ResourceGetter, bool) {+	var getters multiResourceGetter+	for _, o := range os {+		if g, ok := unwrapResourceGetter(o); ok {+			getters = append(getters, g)+		}+	}+	return getters, len(getters) > 0+}+ // NewCachedResourceGetter creates a new ResourceGetter from the given objects. // If multiple objects are provided, they are merged into one where // the first match wins.@@ -392,6 +426,10 @@ func unwrapResourceGetter(v any) (ResourceGetter, bool) { 		return vv.Resources(), true 	case func(name any) Resource: 		return resourceGetterFunc(vv), true+	case Resource:+		// A single Resource, e.g. created with resources.FromString,+		// resolvable by its name.+		return Resources{vv}, true 	default: 		vvv, ok := hreflect.ToSliceAny(v) 		if !ok {resources/resource/resources_test.goindex ebadbb312..441f9ed5d 100644@@ -108,6 +108,34 @@ func TestResourcesMount(t *testing.T) { 	checkNil("/z/d.txt") } +func TestNewResourceGetter(t *testing.T) {+	c := qt.New(t)++	foo := testResource{name: "foo.css"}+	bar := testResource{name: "/bar.css"}+	baz := testResource{name: "/themes/blue/baz.css"}++	// Single resources and a mount in a slice, first match wins.+	g, ok := NewResourceGetter([]any{foo, bar, Resources{baz}.Mount("/themes/blue", ".")})+	c.Assert(ok, qt.IsTrue)+	c.Assert(g.Get("foo.css"), qt.Equals, foo)+	c.Assert(g.Get("/foo.css"), qt.Equals, foo)+	c.Assert(g.Get("bar.css"), qt.Equals, bar)+	c.Assert(g.Get("baz.css"), qt.Equals, baz)+	c.Assert(g.Get("qux.css"), qt.IsNil)++	// A single resource.+	g, ok = NewResourceGetter(foo)+	c.Assert(ok, qt.IsTrue)+	c.Assert(g.Get("foo.css"), qt.Equals, foo)++	// Not supported.+	_, ok = NewResourceGetter(42)+	c.Assert(ok, qt.IsFalse)+	_, ok = NewResourceGetter(nil)+	c.Assert(ok, qt.IsFalse)+}+ type testResource struct { 	Resource 	name stringresources/resource_factories/create/create.goindex 4a4d14da6..3996b1031 100644@@ -17,6 +17,7 @@ package create  import ( 	"errors"+	"fmt" 	"net/http" 	"os" 	"path"@@ -148,9 +149,26 @@ 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) {+	return c.CopyWithImportContext(r, targetPath, nil)+}++// CopyWithImportContext copies r to the new targetPath and attaches the given import context,+// which will be used to resolve imports in transformations (e.g. css.Build).+// If targetPath is empty, the target path of r is used.+// The import context ic may be nil.+func (c *Client) CopyWithImportContext(r resource.Resource, targetPath string, ic *resources.ImportContext) (resource.Resource, error) {+	if !resources.IsCopyable(r) {+		return nil, fmt.Errorf("resource of type %T cannot be copied", r)+	}+	if targetPath == "" {+		targetPath = resources.InternalResourceTargetPath(r)+	} 	key := dynacache.CleanKey(targetPath) + "__copy"+	if ic != nil {+		key += "_ic" + ic.Key()+	} 	return c.rs.ResourceCache.GetOrCreate(key, func() (resource.Resource, error) {-		return resources.Copy(r, targetPath), nil+		return resources.CopyWithImportContext(r, targetPath, ic), nil 	}) } resources/resource_transformers/cssjs/inline_imports.goindex 44ae4b3c6..789a7f4a9 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" ) @@ -55,6 +58,10 @@ type importResolver struct { 	linemap           map[int]fileOffset 	fs                afero.Fs 	logger            loggers.Logger++	// Set via resources.Copy, may be nil.+	ctx           context.Context+	importContext resource.ResourceGetter }  func newImportResolver(r io.Reader, inPath string, opts InlineImports, fs afero.Fs, logger loggers.Logger, dependencyManager identity.Manager) *importResolver {@@ -68,14 +75,45 @@ func newImportResolver(r io.Reader, inPath string, opts InlineImports, fs afero. 	} } +// withImportContext sets the import context to try before the file system when resolving imports.+func (imp *importResolver) withImportContext(ctx context.Context, importContext resource.ResourceGetter) *importResolver {+	imp.ctx = ctx+	imp.importContext = importContext+	return imp+}+ 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 from the import context, if set.+// It returns a nil content if not found.+func (imp *importResolver) resolveFromImportContext(importPath string) (content []byte, hash, inPath string, err error) {+	if imp.importContext == nil {+		return nil, "", "", nil+	}+	r := imp.importContext.Get(strings.TrimPrefix(importPath, "./"))+	if r == nil {+		return nil, "", "", nil+	}+	s, err := resources.InternalResourceSourceContent(imp.ctx, r)+	if err != nil {+		return nil, "", "", fmt.Errorf("failed to read CSS @import %q: %w", resources.InternalResourceSourcePathBestEffort(r), err)+	}+	imp.dependencyManager.AddIdentity(identity.FirstIdentity(r))+	content = []byte(s)+	// Nested imports are resolved relative to the name the resource was found by.+	return content, sha256Hex(content), path.Join("/", strings.TrimPrefix(importPath, "./")), nil }  func (imp *importResolver) importRecursive(@@ -105,8 +143,19 @@ 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)+			nestedInPath := filepath.ToSlash(filename)++			// The import context takes precedence over the file system.+			importContent, hash, importContextInPath, err := imp.resolveFromImportContext(path)+			if err != nil {+				return 0, "", err+			}+			if importContent != nil {+				nestedInPath = importContextInPath+			} else {+				imp.dependencyManager.AddIdentity(identity.CleanStringIdentity(filename))+				importContent, hash = imp.contentHash(filename)+			}  			if importContent == nil { 				if imp.opts.SkipInlineImportsNotFound {@@ -135,7 +184,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..132b2a12e 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,61 @@ E_STYLE`) 	}) } +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 TestImportResolverImportContext(t *testing.T) {+	c := qt.New(t)+	fs := afero.NewMemMapFs()++	// Real InPaths (the resource's target path) have a leading slash.+	c.Assert(afero.WriteFile(fs, "/css/b.css", []byte(`B_STYLE_FROM_FS`), 0o777), qt.IsNil)+	c.Assert(afero.WriteFile(fs, "/css/d.css", []byte(`D_STYLE_FROM_FS`), 0o777), qt.IsNil)+	// Nested imports in import context resources are resolved relative to the name they were found by.+	c.Assert(afero.WriteFile(fs, "/c.css", []byte(`C_STYLE_FROM_FS`), 0o777), qt.IsNil)++	importContext := resource.Resources{+		testImportContextResource{name: "foo.css", content: "@import \"./c.css\";\nFOO_STYLE"},+		// Takes precedence over b.css in the file system.+		testImportContextResource{name: "b.css", content: "B_STYLE_FROM_CONTEXT"},+	}++	mainStyles := strings.NewReader(`@import "foo.css";+@import "./b.css";+@import "d.css";+LOCAL_STYLE`)++	imp := newImportResolver(+		mainStyles,+		"/css/styles.css",+		InlineImports{},+		fs, loggers.NewDefault(),+		identity.NopManager,+	).withImportContext(context.Background(), importContext)++	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_FROM_FS+FOO_STYLE+B_STYLE_FROM_CONTEXT+D_STYLE_FROM_FS+LOCAL_STYLE`)+}+ func BenchmarkImportResolver(b *testing.B) { 	c := qt.New(b) 	fs := afero.NewMemMapFs()resources/resource_transformers/cssjs/postcss.goindex 94295eea9..2754ad602 100644@@ -217,7 +217,7 @@ func (t *postcssTransformation) Transform(ctx *resources.ResourceTransformationC 		ctx.InPath, 		options.InlineImports, 		t.rs.Assets.Fs, t.rs.Logger, ctx.DependencyManager,-	)+	).withImportContext(ctx.Ctx, ctx.ImportContext)  	if options.InlineImports.InlineImports { 		var err errorresources/resource_transformers/cssjs/tailwindcss.goindex 539016dc2..4a4796b65 100644@@ -128,7 +128,7 @@ func (t *tailwindcssTransformation) Transform(ctx *resources.ResourceTransformat 		ctx.InPath, 		options.InlineImports, 		t.rs.Assets.Fs, t.rs.Logger, ctx.DependencyManager,-	)+	).withImportContext(ctx.Ctx, ctx.ImportContext)  	if !options.InlineImports.DisableInlineImports { 		src, err = imp.resolve()resources/resource_transformers/js/transform.goindex 07933a92f..4f27ec651 100644@@ -70,6 +70,8 @@ func (t *buildTransformation) Transform(ctx *resources.ResourceTransformationCtx 	opts.Stdin = true 	opts.IsCSS = t.c.c.CssMode +	esbuild.ApplyImportContext(ctx.Ctx, &opts, ctx.ImportContext, ctx.DependencyManager)+ 	_, err = t.c.transform(opts, ctx)  	return errresources/resource_transformers/tocss/dartsass/dartsass_integration_test.goindex 72e012667..b2e1cb978 100644@@ -726,3 +726,35 @@ 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";+@import "partial";+@import "fromassets";+body { color: vars.$color; }+-- assets/scss/_fromassets.scss --+.fromassets { color: #111; }+-- assets/scss/_partial.scss --+.shadowed { color: #555; }+-- layouts/home.html --+{{ $vars := resources.FromString "_vars.scss" "$color: #222;" }}+{{ $partial := resources.FromString "partial.scss" "@import \"nested\";\n.partial { color: #333; }" }}+{{ $nested := resources.FromString "_nested.scss" ".nested { color: #444; }" }}+{{ $opts := dict "transpiler" "dartsass" "outputStyle" "compressed" }}+{{ $css := resources.Get "scss/main.scss" | resources.Copy (dict "importContext" (slice $vars $partial $nested)) | css.Sass $opts }}+CSS: {{ $css.Content | safeCSS }}|+`++	b := hugolib.Test(t, files, hugolib.TestOptOsFs())++	b.AssertFileContent("public/index.html", "CSS: .nested{color:#444}.partial{color:#333}.fromassets{color:#111}body{color:#222}")+}resources/resource_transformers/tocss/dartsass/transform.goindex e3d5823e9..77fc66d7f 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"@@ -29,6 +31,7 @@ import ( 	"github.com/gohugoio/hugo/resources"  	"github.com/gohugoio/hugo/resources/internal"+	"github.com/gohugoio/hugo/resources/resource" 	"github.com/gohugoio/hugo/resources/resource_transformers/tocss/sass"  	"github.com/spf13/afero"@@ -71,18 +74,25 @@ func (t *transform) Transform(ctx *resources.ResourceTransformationCtx) error {  	baseDir := path.Dir(ctx.SourcePath) 	filename := dartSassStdinPrefix+	var entryDir string  	if ctx.SourcePath != "" {-		filename += t.c.sfs.RealFilename(ctx.SourcePath)+		realFilename := t.c.sfs.RealFilename(ctx.SourcePath)+		filename += realFilename+		entryDir = filepath.Dir(realFilename) 	}  	args := godartsass.Args{ 		URL:          filename, 		IncludePaths: t.c.sfs.RealDirs(baseDir), 		ImportResolver: importResolver{-			baseDir:           baseDir,-			c:                 t.c,-			dependencyManager: ctx.DependencyManager,+			ctx:                   ctx.Ctx,+			baseDir:               baseDir,+			entryDir:              entryDir,+			c:                     t.c,+			dependencyManager:     ctx.DependencyManager,+			importContext:         ctx.ImportContext,+			importContextResolved: hmaps.NewCache[string, resource.Resource](),  			vars: opts.Vars, 		},@@ -129,10 +139,17 @@ func (t *transform) Transform(ctx *resources.ResourceTransformationCtx) error { }  type importResolver struct {+	ctx               context.Context 	baseDir           string+	entryDir          string // The real directory of the entry file, if any. 	c                 *Client 	dependencyManager identity.Manager 	vars              map[string]any++	// Set via resources.Copy, may be nil.+	importContext resource.ResourceGetter+	// Canonical URL => Resource resolved from importContext.+	importContextResolved *hmaps.Cache[string, resource.Resource] }  func (t importResolver) CanonicalizeURL(url string) (string, error) {@@ -140,6 +157,32 @@ func (t importResolver) CanonicalizeURL(url string) (string, error) { 		return strings.ToLower(url), nil 	} +	isImportContextURL := strings.HasPrefix(url, sass.ImportContextScheme)+	importContextName := url+	if t.importContext != nil && t.entryDir != "" && strings.HasPrefix(url, dartSassStdinPrefix) {+		// Dart Sass first resolves imports in the entry file relative to its URL,+		// e.g. hugostdin:/path/to/assets/scss/partial.+		if filePath, isURL := paths.UrlStringToFilename(url); isURL {+			if rel, err := filepath.Rel(t.entryDir, filePath); err == nil && !strings.HasPrefix(rel, "..") {+				importContextName = filepath.ToSlash(rel)+			}+		}+	}+	if t.importContext != nil && (isImportContextURL || !strings.Contains(importContextName, ":")) {+		// The import context takes precedence over the file system.+		if r, name := sass.ResolveFromImportContext(importContextName, t.importContext, true); r != nil {+			t.dependencyManager.AddIdentity(identity.FirstIdentity(r))+			canonical := sass.ImportContextScheme + "/" + strings.TrimPrefix(name, "/")+			t.importContextResolved.Set(canonical, r)+			return canonical, nil+		}+	}+	if isImportContextURL {+		// A relative import from a file in the import context not found in the import context.+		// Dart Sass will retry with the URL as written in the source.+		return "", nil+	}+ 	filePath, isURL := paths.UrlStringToFilename(url) 	var prevDir string 	var pathDir string@@ -198,15 +241,29 @@ func (t importResolver) Load(url string) (godartsass.Import, error) { 			Content: sass.CreateVarsStyleSheet(sass.TranspilerDart, sass.ResolveVars(t.vars, subPath)), 		}, nil 	}+	if strings.HasPrefix(url, sass.ImportContextScheme) {+		r, found := t.importContextResolved.Get(url)+		if !found {+			return godartsass.Import{}, fmt.Errorf("import %q not found in import context", url)+		}+		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/helpers.goindex cb8cabd07..e31156626 100644@@ -16,6 +16,7 @@ package sass import ( 	"fmt" 	"maps"+	"path" 	"regexp" 	"sort" 	"strings"@@ -24,6 +25,7 @@ import ( 	"github.com/gohugoio/hugo/common/hreflect" 	"github.com/gohugoio/hugo/common/hstrings" 	"github.com/gohugoio/hugo/common/types/css"+	"github.com/gohugoio/hugo/resources/resource" )  const (@@ -174,3 +176,57 @@ func isTypedCSSValue(v any) bool {  	return false }++// ImportContextScheme is the URL scheme used for imports resolved from an import context (see resources.Copy).+const ImportContextScheme = "hugo-import-context:"++// ResolveFromImportContext resolves the Sass import url using the given import context,+// trying the same file name variants as Sass does for the file system (e.g. partials prefixed with "_").+// If includeCSS is true, .css files are also considered when url has no extension.+// It returns the resolved Resource and the name it was resolved with, or nil if not found.+func ResolveFromImportContext(url string, importContext resource.ResourceGetter, includeCSS bool) (resource.Resource, string) {+	if importContext == nil {+		return nil, ""+	}+	url = strings.TrimPrefix(url, ImportContextScheme)+	url = strings.TrimPrefix(url, "./")+	// Names in the import context are relative to its root, which+	// is also what e.g. Resources.Mount expects.+	url = strings.TrimPrefix(url, "/")++	dir := path.Dir(url)+	name := path.Base(url)++	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 {+		candidate := path.Join(dir, fmt.Sprintf(namePattern, name))+		if r := importContext.Get(candidate); r != nil {+			return r, candidate+		}+	}++	return nil, ""+}resources/resource_transformers/tocss/sass/helpers_test.goindex ef31fdd8f..3718799c8 100644@@ -17,6 +17,7 @@ import ( 	"testing"  	qt "github.com/frankban/quicktest"+	"github.com/gohugoio/hugo/resources/resource" )  func TestIsUnquotedCSSValue(t *testing.T) {@@ -41,3 +42,39 @@ func TestIsUnquotedCSSValue(t *testing.T) { 		c.Assert(isTypedCSSValue(test.in), qt.Equals, test.out) 	} }++type testResource struct {+	resource.Resource+	name string+}++func (r testResource) Name() string {+	return r.name+}++func TestResolveFromImportContext(t *testing.T) {+	c := qt.New(t)++	rs := resource.Resources{+		testResource{name: "/lib/_vars.scss"},+		testResource{name: "/lib/sub/_nested.scss"},+	}++	for _, target := range []string{"", ".", "css"} {+		ic := rs.Mount("/lib", target)+		prefix := ""+		if target != "" && target != "." {+			prefix = target + "/"+		}+		// Top level import, and a nested import relative to a file resolved from the import context.+		for _, url := range []string{prefix + "vars", ImportContextScheme + "/" + prefix + "vars"} {+			r, name := ResolveFromImportContext(url, ic, true)+			c.Assert(r, qt.IsNotNil, qt.Commentf("target %q url %q", target, url))+			c.Assert(r.Name(), qt.Equals, "/lib/_vars.scss")+			c.Assert(name, qt.Equals, prefix+"_vars.scss")+		}+		r, _ := ResolveFromImportContext(ImportContextScheme+"/"+prefix+"sub/nested", ic, true)+		c.Assert(r, qt.IsNotNil, qt.Commentf("target %q", target))+		c.Assert(r.Name(), qt.Equals, "/lib/sub/_nested.scss")+	}+}resources/resource_transformers/tocss/scss/scss_integration_test.goindex 93cc05bf0..495ec1a84 100644@@ -437,3 +437,33 @@ 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 "partial";+@import "fromassets";+body { color: $color; }+-- assets/scss/_fromassets.scss --+.fromassets { color: #111; }+-- layouts/home.html --+{{ $vars := resources.FromString "_vars.scss" "$color: #222;" }}+{{ $partial := resources.FromString "partial.scss" "@import \"nested\";\n.partial { color: #333; }" }}+{{ $nested := resources.FromString "_nested.scss" ".nested { color: #444; }" }}+{{ $opts := dict "transpiler" "libsass" "outputStyle" "compressed" }}+{{ $css := resources.Get "scss/main.scss" | resources.Copy (dict "importContext" (slice $vars $partial $nested)) | css.Sass $opts }}+CSS: {{ $css.Content | safeCSS }}|+`++	b := hugolib.Test(t, files, hugolib.TestOptOsFs())++	b.AssertFileContent("public/index.html", "CSS: .nested{color:#444}.partial{color:#333}.fromassets{color:#111}body{color:#222}")+}resources/resource_transformers/tocss/scss/tocss.goindex ea8617140..4badfd631 100644@@ -69,11 +69,33 @@ 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.+	// Set if reading an import from the import context set via resources.Copy fails.+	var importContextErr error+ 	options.to.ImportResolver = func(url string, prev string) (newUrl string, body string, resolved bool) { 		if url == sass.HugoVarsNamespace { 			return url, varsStylesheet, true 		} +		// LibSass may have made the URL we returned absolute, so check for the scheme.+		isPrevImportContext := strings.Contains(prev, sass.ImportContextScheme)++		if ctx.ImportContext != nil && (prev == "stdin" || isPrevImportContext) {+			// The import context takes precedence over the file system.+			if r, name := sass.ResolveFromImportContext(url, ctx.ImportContext, false); r != nil {+				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))+				newUrl = sass.ImportContextScheme + "/" + strings.TrimPrefix(name, "/")+				return newUrl, content, true+			}+		}+ 		// We get URL paths from LibSASS, but we need file paths. 		url = filepath.FromSlash(url) 		prev = filepath.FromSlash(prev)@@ -82,7 +104,7 @@ func (t *toCSSTransformation) Transform(ctx *resources.ResourceTransformationCtx 		urlDir := filepath.Dir(url) 		var prevDir string -		if prev == "stdin" {+		if prev == "stdin" || isPrevImportContext { 			prevDir = baseDir 		} else { 			prevDir, _ = t.c.sfs.MakePathRelative(filepath.Dir(prev), true)@@ -150,6 +172,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..e26535781 100644@@ -133,6 +133,11 @@ type ResourceTransformationCtx struct { 	// to be simple types, as it needs to be serialized to JSON and back. 	Data map[string]any +	// The import context to use when resolving imports (e.g. CSS @import), set via resources.Copy.+	// Transformations should try this before falling back to the regular resolution in /assets.+	// May be nil.+	ImportContext resource.ResourceGetter+ 	// This is used to publish additional artifacts, e.g. source hhmaps. 	// We may improve this. 	OpenResourcePublisher func(relTargetPath string) (io.WriteCloser, error)@@ -227,6 +232,14 @@ func (r *resourceAdapter) GetDependencyManager() identity.Manager { 	return r.target.GetDependencyManager() } +func (r *resourceAdapter) getImportContext() *ImportContext {+	return r.target.getImportContext()+}++func (r *resourceAdapter) setImportContext(ic *ImportContext) {+	r.target.setImportContext(ic)+}+ func (r resourceAdapter) cloneTo(targetPath string) resource.Resource { 	newtTarget := r.target.cloneTo(targetPath) 	newInner := &resourceAdapterInner{@@ -518,6 +531,10 @@ func (r *resourceAdapter) transform(key string, publish, setContent bool) (*reso 		DependencyManager:     r.target.GetDependencyManager(), 	} +	if ic := r.target.getImportContext(); ic != nil {+		tctx.ImportContext = ic+	}+ 	tctx.InMediaType = r.target.MediaType() 	tctx.OutMediaType = r.target.MediaType() tpl/resources/copy_importcontext_integration_test.gonew file mode 100644index 000000000..34a2a11ff@@ -0,0 +1,229 @@+// 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_test++import (+	"testing"++	qt "github.com/frankban/quicktest"+	"github.com/gohugoio/hugo/hugolib"+)++func TestCopyImportContextCSSBuild(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";+body { margin: 0; }+-- assets/css/baz.css --+.baz { color: red; }+-- assets/css/bar.css --+.bar-from-assets { color: red; }+-- layouts/home.html --+{{ $foo := resources.FromString "foo.css" "body { color: blue; }" }}+{{ $bar := resources.FromString "bar.css" "body { color: green; }" }}+{{ $main := resources.Get "css/main.css" }}+{{ $copy := $main | resources.Copy (dict "importContext" (slice $foo $bar)) }}+{{ $css := $copy | css.Build }}+Copy: {{ $copy.RelPermalink }}|+CSS: {{ $css.RelPermalink }}|{{ $css.Content | safeCSS }}|+{{ $copy2 := $main | resources.Copy (dict "targetPath" "css/main2.css" "importContext" (slice $foo)) }}+{{ $css2 := $copy2 | css.Build (dict "minify" true) }}+CSS2: {{ $css2.RelPermalink }}|{{ $css2.Content | safeCSS }}|+`++	b := hugolib.Test(t, files, hugolib.TestOptOsFs())++	b.AssertFileContent("public/index.html",+		"Copy: /css/main.css|",+		"CSS: /css/main.css|",+		"@media screen {\n  body {\n    color: blue;\n  }\n}",+		"@media print {\n  body {\n    color: green;\n  }\n}",+		".baz {\n  color: red;\n}",+		"CSS2: /css/main2.css|",+		"@media screen{body{color:#00f}}",+		// bar.css is not in the import context of $copy2, so it's resolved from /assets.+		"@media print{.bar-from-assets{color:red}}",+	)+	b.AssertFileContent("public/index.html", "! .bar-from-assets {\n")+}++func TestCopyImportContextJSBuild(t *testing.T) {+	t.Parallel()++	files := `+-- hugo.toml --+disableKinds = ["taxonomy", "term", "page", "section", "rss", "sitemap"]+-- assets/js/main.js --+import { hello } from "hello.js";+import { nested } from "./nested.js";+console.log(hello, nested);+-- assets/js/nested.js --+export const nested = "nested-from-assets";+-- layouts/home.html --+{{ $hello := resources.FromString "hello.js" "export const hello = 'hello-from-import-context';" }}+{{ $js := resources.Get "js/main.js" | resources.Copy (dict "importContext" $hello) | js.Build }}+JS: {{ $js.RelPermalink }}|{{ $js.Content | safeJS }}|+`++	b := hugolib.Test(t, files, hugolib.TestOptOsFs())++	b.AssertFileContent("public/index.html",+		"JS: /js/main.js|",+		"hello-from-import-context",+		"nested-from-assets",+	)+}++// The same resource copied with different import contexts must not share cached transformations.+func TestCopyImportContextSameTargetPathDifferentContexts(t *testing.T) {+	t.Parallel()++	files := `+-- hugo.toml --+disableKinds = ["taxonomy", "term", "page", "section", "rss", "sitemap"]+-- assets/css/main.css --+@import "theme.css";+-- assets/themes/blue/theme.css --+body { color: blue; }+-- layouts/home.html --+{{ $main := resources.Get "css/main.css" }}+{{ $dark := resources.FromString "theme.css" "body { color: black; }" }}+{{ $light := resources.FromString "theme.css" "body { color: white; }" }}+{{ $css1 := $main | resources.Copy (dict "importContext" $dark) | css.Build (dict "minify" true) }}+{{ $css2 := $main | resources.Copy (dict "importContext" $light) | css.Build (dict "minify" true) }}+{{ $css3 := $main | resources.Copy (dict "importContext" ((resources.Match "themes/blue/*.css").Mount "/themes/blue" ".")) | css.Build (dict "minify" true) }}+CSS1: {{ $css1.Content | safeCSS }}|+CSS2: {{ $css2.Content | safeCSS }}|+CSS3: {{ $css3.Content | safeCSS }}|+`++	b := hugolib.Test(t, files)++	b.AssertFileContent("public/index.html",+		"CSS1: body{color:#000}",+		"CSS2: body{color:#fff}",+		"CSS3: body{color:#00f}",+	)+}++func TestCopyImportContextPage(t *testing.T) {+	t.Parallel()++	files := `+-- hugo.toml --+disableKinds = ["taxonomy", "term", "section", "rss", "sitemap"]+-- assets/css/main.css --+@import "vars.css";+-- content/p1/index.md --+---+title: p1+---+-- content/p1/vars.css --+:root { --color: red; }+-- layouts/home.html --+Home.+-- layouts/page.html --+{{ $css := resources.Get "css/main.css" | resources.Copy (dict "targetPath" (printf "css/%s.css" .File.ContentBaseName) "importContext" (slice .)) | css.Build (dict "minify" true) }}+CSS: {{ $css.RelPermalink }}|{{ $css.Content | safeCSS }}|+`++	b := hugolib.Test(t, files)++	b.AssertFileContent("public/p1/index.html", "CSS: /css/p1.css|:root{--color: red}")+}++func TestCopyOptions(t *testing.T) {+	t.Parallel()++	files := `+-- hugo.toml --+disableKinds = ["taxonomy", "term", "page", "section", "rss", "sitemap"]+-- layouts/home.html --+{{ $r := resources.FromString "js/foo.js" "let foo;" }}+{{ $c1 := $r | resources.Copy }}+{{ $c2 := $r | resources.Copy (dict "targetPath" "js/bar.js") }}+{{ $c3 := $r | resources.Copy "js/baz.js" }}+C1: {{ $c1.RelPermalink }}|{{ $c1.Content }}|+C2: {{ $c2.RelPermalink }}|{{ $c2.Content }}|+C3: {{ $c3.RelPermalink }}|{{ $c3.Content }}|+`++	b := hugolib.Test(t, files)++	b.AssertFileContent("public/index.html",+		"C1: /js/foo.js|let foo;|",+		"C2: /js/bar.js|let foo;|",+		"C3: /js/baz.js|let foo;|",+	)+}++func TestCopyOptionsInvalid(t *testing.T) {+	t.Parallel()++	files := `+-- hugo.toml --+disableKinds = ["taxonomy", "term", "page", "section", "rss", "sitemap"]+-- layouts/home.html --+{{ $r := resources.FromString "js/foo.js" "let foo;" }}+{{ $c := $r | resources.Copy (dict "foo" "bar") }}+`++	b, err := hugolib.TestE(t, files)+	b.Assert(err, qt.IsNotNil)+	b.Assert(err.Error(), qt.Contains, `unknown option "foo"`)++	files = `+-- hugo.toml --+disableKinds = ["taxonomy", "term", "page", "section", "rss", "sitemap"]+-- layouts/home.html --+{{ $r := resources.FromString "js/foo.js" "let foo;" }}+{{ $c := $r | resources.Copy (dict "importContext" 42) }}+`++	b, err = hugolib.TestE(t, files)+	b.Assert(err, qt.IsNotNil)+	b.Assert(err.Error(), qt.Contains, `importContext: unsupported type int`)+}++func TestCopyImportContextRebuild(t *testing.T) {+	t.Parallel()++	files := `+-- hugo.toml --+disableKinds = ["taxonomy", "term", "page", "section", "rss", "sitemap"]+disableLiveReload = true+-- assets/css/main.css --+@import "theme.css";+-- assets/themes/blue/theme.css --+body { color: blue; }+-- layouts/home.html --+{{ $ctx := (resources.Match "themes/blue/*.css").Mount "/themes/blue" "." }}+{{ $css := resources.Get "css/main.css" | resources.Copy (dict "importContext" $ctx) | css.Build (dict "minify" true) }}+CSS: {{ $css.Content | safeCSS }}|+`++	b := hugolib.TestRunning(t, files, hugolib.TestOptOsFs())++	b.AssertFileContent("public/index.html", "CSS: body{color:#00f}")++	b.EditFileReplaceAll("assets/themes/blue/theme.css", "blue", "red").Build()++	b.AssertFileContent("public/index.html", "CSS: body{color:red}")+}tpl/resources/resources.goindex 2512b5ce9..054693ed3 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,68 @@ 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)+// Copy copies the given Resource.+//+// The signature is:+//+//	resources.Copy [TARGETPATH or OPTIONS] RESOURCE+//+// Where OPTIONS is a map with the keys targetPath and importContext.+// If no target path is given, the target path of RESOURCE is used.+// The importContext is used to resolve imports (e.g. CSS @import) in+// transformations such as css.Build, js.Build, js.Batch, css.Sass, css.PostCSS and css.TailwindCSS.+func (ns *Namespace) Copy(ctx context.Context, args ...any) (resource.Resource, error) {+	if len(args) < 1 || len(args) > 2 {+		return nil, errors.New("must provide a Resource object and optionally a target path or an options map")+	}++	rv := args[len(args)-1]+	r, ok := rv.(resource.Resource)+	if !ok {+		return nil, fmt.Errorf("expected a Resource object, received %T instead", rv)+	}++	var (+		targetPath       string+		importContextOpt any+	)++	if len(args) == 2 {+		switch v := args[0].(type) {+		case string:+			targetPath = v+		default:+			m, err := hmaps.ToStringMapE(v)+			if err != nil {+				s, err2 := cast.ToStringE(v)+				if err2 != nil {+					return nil, fmt.Errorf("first argument must be a target path or an options map, received %T", v)+				}+				targetPath = s+				break+			}+			for k, vv := range m {+				switch strings.ToLower(k) {+				case "targetpath":+					targetPath, err = cast.ToStringE(vv)+					if err != nil {+						return nil, fmt.Errorf("invalid targetPath: %w", err)+					}+				case "importcontext":+					importContextOpt = vv+				default:+					return nil, fmt.Errorf("unknown option %q; valid options are %q and %q", k, "targetPath", "importContext")+				}+			}+		}+	}++	ic, err := resources.NewImportContext(ctx, importContextOpt) 	if err != nil {-		panic(err)+		return nil, err 	}-	return ns.createClient.Copy(r, targetPath)++	return ns.createClient.CopyWithImportContext(r, targetPath, ic) }  // Get locates the filename given in Hugo's assets filesystem 
Merged fix · PR #15156+689 −102
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"