Backtestshugorun-20261013-011256#15103

Issue #15103 Merged fix PR #15156 Run 13 Oct 2026 · run-20261013-011256 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 `importContext` to be added to `resources.Copy`, stored internally on the resource, and then honored by css.Build, js.Build/Batch, css.Sass and TailwindCSS.

**Patch A does this directly.**
- It extends `resources.Copy` to take an optional string or options map with `targetPath` and `importContext`, and makes the target path optional, as the issue proposes.
- It stores the context in an unexported field on `genericResource`, following the issue's `Internal*` hint via `InternalResourceImportContext`.
- It exposes the context through `ResourceTransformationCtx.ImportContext`.
- It wires that context into the CSS inline-import resolver (PostCSS/Tailwind), esbuild (js.Build/css.Build), js.Batch (as a fallback), libsass and dartsass.
- It handles cache correctness by adding an import-context key to the resource `Key()`. That key includes a content hash for resources such as `FromString`.
- It validates bad input with a clear error message.
- Its integration tests cover: css.Build with media queries, page resources in js.Build with Mount, same target path with different contexts, same path with different content, a transformed resource, rebuild on edit, error cases, js.Batch, and both Sass transpilers.

**Patch B does not implement the requested API.**
- It adds `importContext` as an option on each transformer (css.Build, css.Sass, TailwindCSS) and leaves `resources.Copy` untouched.
- It carries considerable unrelated and risky churn:
  - bumps hashstructure to v1.0.0 and rewrites the hashing internals;
  - removes `pageState.Key` and adds `pageOutput.Key`;
  - changes `Color.Hash` to `Key`;
  - removes `resourceGetterFunc` and support for function getters;
  - changes the key semantics of `FromString`;
  - adds a new `testinginternal` template namespace.
- Its hash test asserts brittle hard-coded hash values.
- Its js.Build support lacks error-message and source-map handling.

On correctness against the stated ask, scope, and risk, Patch A is clearly better.

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

2h

Wall-clock time in the container

Full test suite

No new failures

2,362 passed · 96 skipped · 2,487 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

1,058vs 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+1007 −51
internal/js/esbuild/batch.goindex 61c6b6d5c..fdf7ed73f 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 import context set on the resource in resources.Copy, if any.+		ImportContext: resource.NewCachedResourceGetter(v.ImportContext, resources.InternalResourceImportContext(v.Resource)),+		Params:        paramsJSON, 	}  	return compiled, nilinternal/js/esbuild/importcontext.gonew file mode 100644index 000000000..79a78dc54@@ -0,0 +1,98 @@+// 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/common/paths"+	"github.com/gohugoio/hugo/identity"+	"github.com/gohugoio/hugo/resources"+	"github.com/gohugoio/hugo/resources/resource"+)++// ApplyImportContext configures opts to resolve imports using the given import context+// (e.g. set in resources.Copy) before falling back to the default import resolution.+// Resolved resources are added to dependencyManager.+// Note that this will overwrite any ImportOnResolveFunc, ImportOnLoadFunc,+// ErrorMessageResolveFunc and ResolveSourceMapSource set in opts.+func ApplyImportContext(ctx context.Context, opts *Options, importContext resource.ResourceGetter, dependencyManager identity.Manager) {+	if importContext == nil {+		return+	}+	if dependencyManager == nil {+		dependencyManager = identity.NopManager+	}++	importResource := hmaps.NewCache[string, resource.Resource]()++	opts.ImportOnResolveFunc = func(imp string, args api.OnResolveArgs) string {+		if r, found := importResource.Get(imp); found {+			dependencyManager.AddIdentity(identity.FirstIdentity(r))+			return imp+		}+		resolved := ResolveResource(imp, importContext)+		if resolved == nil {+			return ""+		}+		dependencyManager.AddIdentity(identity.FirstIdentity(resolved))+		resolvePath := PrefixHugoVirtual + paths.AddLeadingSlash(resources.InternalResourceTargetPath(resolved))+		importResource.Set(resolvePath, resolved)+		return resolvePath+	}++	opts.ImportOnLoadFunc = func(args api.OnLoadArgs) (string, error) {+		if r, found := importResource.Get(args.Path); found {+			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+		}+		return "", nil+	}++	opts.ErrorMessageResolveFunc = func(args api.Message) *ErrorMessageResolved {+		if loc := args.Location; loc != nil {+			path := strings.TrimPrefix(loc.File, NsHugoImportResolveFunc+":")+			if r, found := importResource.Get(path); found {+				var contentr hugio.ReadSeekCloser+				if cp, ok := r.(hugio.ReadSeekCloserProvider); ok {+					contentr, _ = cp.ReadSeekCloser()+				}+				return &ErrorMessageResolved{+					Content: contentr,+					Path:    resources.InternalResourceSourcePathBestEffort(r),+					Message: args.Text,+				}+			}+		}+		return nil+	}++	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/image.goindex 467e23f26..7967b7cff 100644@@ -230,8 +230,8 @@ func (i *imageResource) Clone() resource.Resource { 	return ir } -func (i *imageResource) cloneTo(targetPath string) resource.Resource {-	gr := i.baseResource.cloneTo(targetPath).(baseResource)+func (i *imageResource) cloneTo(opts CopyOptions) resource.Resource {+	gr := i.baseResource.cloneTo(opts).(baseResource) 	ir := &imageResource{ 		root:         i.root, 		Image:        i.WithSpec(gr),resources/resource.goindex cf6e1e597..1cec7813c 100644@@ -222,12 +222,86 @@ func (t transformerNotAvailable) Key() internal.ResourceTransformationKey {  // resourceCopier is for internal use. type resourceCopier interface {-	cloneTo(targetPath string) resource.Resource+	cloneTo(opts CopyOptions) resource.Resource+}++// CopyOptions holds the options for Copy.+type CopyOptions struct {+	// The target path to copy the resource to.+	// If empty, the target path of the resource is preserved.+	TargetPath string++	// The import context to use when resolving imports in the resource's content+	// in e.g. css.Build, js.Build, js.Batch and css.Sass.+	// This can be anything accepted by resource.NewResourceGetter, e.g. a Page, a+	// Resource, Resources mounted using .Mount, or a slice of these.+	// If nil, any import context set on the source resource is preserved.+	ImportContext any }  // Copy copies r to the targetPath given. func Copy(r resource.Resource, targetPath string) resource.Resource {-	return r.(resourceCopier).cloneTo(targetPath)+	c, err := CopyWithOptions(r, CopyOptions{TargetPath: targetPath})+	if err != nil {+		// This can only fail when an import context is set.+		panic(err)+	}+	return c+}++// CopyWithOptions copies r using the given options.+func CopyWithOptions(r resource.Resource, opts CopyOptions) (resource.Resource, error) {+	rc, ok := r.(resourceCopier)+	if !ok {+		return nil, fmt.Errorf("resource of type %T cannot be copied", r)+	}+	if opts.ImportContext != nil {+		if _, ok := resource.NewResourceGetter(opts.ImportContext); !ok {+			return nil, fmt.Errorf("importContext: expected a Page, Resource, Resources mounted with .Mount or a slice of these, got %T", opts.ImportContext)+		}+	}+	return rc.cloneTo(opts), nil+}++// importContext holds the import context set on a resource in resources.Copy.+type importContext struct {+	v      any+	getter resource.ResourceGetter++	keyInit sync.Once+	key     string+}++func newImportContext(v any) *importContext {+	g, ok := resource.NewResourceGetter(v)+	if !ok {+		return nil+	}+	return &importContext{v: v, getter: g}+}++// Key returns a key for this import context to be used in cache keys.+// This is created lazily, as creating it may trigger transformations of resources in the import context.+func (ic *importContext) Key() string {+	ic.keyInit.Do(func() {+		ic.key = resource.ResourceGetterKey(ic.v)+	})+	return ic.key+}++type importContextProvider interface {+	getImportContext() *importContext+}++// InternalResourceImportContext is used internally to get the import context set on r in 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.getter+		}+	}+	return nil }  type baseResourceResource interface {@@ -243,6 +317,7 @@ type baseResourceInternal interface { 	resource.NameNormalizedProvider  	sourcePath() string+	getImportContext() *importContext 	fileInfo 	mediaTypeAssigner 	targetPather@@ -368,6 +443,9 @@ type genericResource struct { 	sd    ResourceSourceDescriptor 	paths internal.ResourcePaths +	// Set in resources.Copy.+	importContext *importContext+ 	includeHashInKey     bool 	sourceFilenameIsHash bool @@ -426,12 +504,21 @@ func (l *genericResource) setTargetPath(d internal.ResourcePaths) { 	l.paths = d } -func (l *genericResource) cloneTo(targetPath string) resource.Resource {+func (l *genericResource) cloneTo(opts CopyOptions) resource.Resource { 	c := l.clone()-	c.paths = c.paths.FromTargetPath(targetPath)+	if opts.TargetPath != "" {+		c.paths = c.paths.FromTargetPath(opts.TargetPath)+	}+	if opts.ImportContext != nil {+		c.importContext = newImportContext(opts.ImportContext)+	} 	return c } +func (l *genericResource) getImportContext() *importContext {+	return l.importContext+}+ func (l *genericResource) Content(context.Context) (any, error) { 	r, err := l.ReadSeekCloser() 	if err != nil {@@ -462,6 +549,11 @@ func (l *genericResource) Key() string { 		if l.includeHashInKey && !l.sourceFilenameIsHash { 			l.key += fmt.Sprintf("_%d", l.hash()) 		}++		if l.importContext != nil {+			// Transformations may resolve imports differently depending on the import context.+			l.key += "_ic" + l.importContext.Key()+		} 	})  	return l.keyresources/resource/resources.goindex 28fbab42f..1fd1cb3ea 100644@@ -20,8 +20,10 @@ import ( 	"slices" 	"strings" +	"github.com/gohugoio/hugo/common/hashing" 	"github.com/gohugoio/hugo/common/hmaps" 	"github.com/gohugoio/hugo/common/hreflect"+	"github.com/gohugoio/hugo/common/hugio" 	"github.com/gohugoio/hugo/common/paths" 	"github.com/gohugoio/hugo/hugofs/hglob" 	"github.com/spf13/cast"@@ -35,42 +37,56 @@ 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 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{resources: r, base: base, target: target}+} -		isTargetAbs := strings.HasPrefix(target, "/")+// mountedResources is a ResourceGetter that resolves names in resources+// mounted from base to target, see Resources.Mount.+type mountedResources struct {+	resources Resources+	base      string+	target    string+} -		if target != "" {-			name1 = strings.TrimPrefix(name1, target)-			if !isTargetAbs {-				name1 = paths.TrimLeading(name1)-			}-		}+func (m mountedResources) resourceGetterKey() string {+	return "mount:" + m.base + ":" + m.target + ":" + resourceGetterKeyString(m.resources)+}++func (m mountedResources) Get(namev any) Resource {+	name1, err := cast.ToStringE(namev)+	if err != nil {+		panic(err)+	}++	isTargetAbs := strings.HasPrefix(m.target, "/") -		if base != "" && isTargetAbs {-			name1 = path.Join(base, name1)+	if m.target != "" {+		name1 = strings.TrimPrefix(name1, m.target)+		if !isTargetAbs {+			name1 = paths.TrimLeading(name1) 		}+	} -		for _, res := range r {-			name2 := res.Name()+	if m.base != "" && isTargetAbs {+		name1 = path.Join(m.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 m.base != "" && !isTargetAbs {+			name2 = paths.TrimLeading(strings.TrimPrefix(name2, m.base))+		} +		if strings.EqualFold(name1, name2) {+			return res 		} -		return nil-	})+	}++	return nil }  type ResourcesProvider interface {@@ -381,6 +397,74 @@ func (c *cachedResourceGetter) IsProbablySameResourceGetter(other ResourceGetter 	return isProbablyEq } +// NewResourceGetter creates a new ResourceGetter from v, which can be a ResourceGetter,+// a ResourcesProvider (e.g. a Page), a func(name any) Resource or a slice of any of these.+// If multiple getters are provided, they are merged into one where the first match wins.+// It returns false if v does not contain any ResourceGetter.+func NewResourceGetter(v any) (ResourceGetter, bool) {+	return unwrapResourceGetter(v)+}++// ResourceGetterKey returns a hashed key for v, which is expected to be a value accepted by NewResourceGetter.+// The key is meant to distinguish different import contexts in caches,+// it is built from the keys/paths of the resources and pages in v.+func ResourceGetterKey(v any) string {+	return hashing.XxHashFromStringHexEncoded(resourceGetterKeyString(v))+}++type resourceGetterKeyer interface {+	resourceGetterKey() string+}++func resourceGetterKeyString(v any) string {+	var b strings.Builder+	writeResourceGetterKey(&b, v)+	return b.String()+}++func writeResourceGetterKey(b *strings.Builder, v any) {+	if v == nil {+		return+	}+	switch vv := v.(type) {+	case resourceGetterKeyer:+		b.WriteString(vv.resourceGetterKey())+	case Resources:+		b.WriteString("[")+		for _, r := range vv {+			writeResourceGetterKey(b, r)+		}+		b.WriteString("]")+	case Identifier:+		b.WriteString(vv.Key())+		if rp, ok := v.(hugio.ReadSeekCloserProvider); ok {+			// The key is usually based on the target path only (e.g. for resources.FromString),+			// so we need to include the content to distinguish import contexts.+			if r, err := rp.ReadSeekCloser(); err == nil {+				h, _, err := hashing.XXHashFromReader(r)+				r.Close()+				if err == nil {+					fmt.Fprintf(b, "_%d", h)+				}+			}+		}+	case interface{ Path() string }:+		// E.g. a Page.+		b.WriteString(vv.Path())+	default:+		if vvv, ok := hreflect.ToSliceAny(v); ok {+			b.WriteString("[")+			for _, vv := range vvv {+				writeResourceGetterKey(b, vv)+			}+			b.WriteString("]")+		} else {+			fmt.Fprintf(b, "%T", v)+		}+	}+	b.WriteString(";")+}+ func unwrapResourceGetter(v any) (ResourceGetter, bool) { 	if v == nil { 		return nil, false@@ -392,6 +476,9 @@ 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.+		return Resources{vv}, true 	default: 		vvv, ok := hreflect.ToSliceAny(v) 		if !ok {resources/resource/resources_test.goindex ebadbb312..cadfc229e 100644@@ -120,3 +120,43 @@ func (r testResource) Name() string { func (r testResource) NameNormalized() string { 	return r.name }++type testKeyedResource struct {+	testResource+}++func (r testKeyedResource) Key() string {+	return "key:" + r.name+}++func TestNewResourceGetterAndKey(t *testing.T) {+	c := qt.New(t)++	a := testKeyedResource{testResource{name: "a.css"}}+	b := testKeyedResource{testResource{name: "b.css"}}++	// A single resource.+	g, ok := NewResourceGetter(a)+	c.Assert(ok, qt.IsTrue)+	c.Assert(g.Get("a.css"), qt.Equals, Resource(a))+	c.Assert(g.Get("b.css"), qt.IsNil)++	// A slice of resources and getters, first match wins.+	g, ok = NewResourceGetter([]any{Resources{a}, b})+	c.Assert(ok, qt.IsTrue)+	c.Assert(g.Get("a.css"), qt.Equals, Resource(a))+	c.Assert(g.Get("b.css"), qt.Equals, Resource(b))++	_, ok = NewResourceGetter(42)+	c.Assert(ok, qt.IsFalse)+	_, ok = NewResourceGetter(nil)+	c.Assert(ok, qt.IsFalse)++	// Keys.+	c.Assert(ResourceGetterKey(Resources{a, b}), qt.Equals, ResourceGetterKey(Resources{a, b}))+	c.Assert(ResourceGetterKey(Resources{a, b}), qt.Not(qt.Equals), ResourceGetterKey(Resources{b, a}))+	c.Assert(ResourceGetterKey(a), qt.Not(qt.Equals), ResourceGetterKey(b))+	c.Assert(ResourceGetterKey(Resources{a}.Mount("/x", ".")), qt.Equals, ResourceGetterKey(Resources{a}.Mount("/x", ".")))+	c.Assert(ResourceGetterKey(Resources{a}.Mount("/x", ".")), qt.Not(qt.Equals), ResourceGetterKey(Resources{a}.Mount("/y", ".")))+	c.Assert(ResourceGetterKey(Resources{a}.Mount("/x", ".")), qt.Not(qt.Equals), ResourceGetterKey(Resources{b}.Mount("/x", ".")))+}resources/resource_factories/create/create.goindex 4a4d14da6..6fb62cf30 100644@@ -154,6 +154,17 @@ func (c *Client) Copy(r resource.Resource, targetPath string) (resource.Resource 	}) } +// CopyWithOptions copies r using the given options.+// If no import context is set, this is the same as Copy.+func (c *Client) CopyWithOptions(r resource.Resource, opts resources.CopyOptions) (resource.Resource, error) {+	if opts.ImportContext == nil && opts.TargetPath != "" {+		return c.Copy(r, opts.TargetPath)+	}+	// The import context may contain resources that change between builds+	// (e.g. resources.FromString), so we don't cache these.+	return resources.CopyWithOptions(r, opts)+}+ // Get creates a new Resource by opening the given pathname in the assets filesystem. func (c *Client) Get(pathname string) (resource.Resource, error) { 	pathname = path.Clean(pathname)resources/resource_transformers/cssjs/inline_imports.goindex 44ae4b3c6..74dd15b31 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,16 @@ type importResolver struct { 	linemap           map[int]fileOffset 	fs                afero.Fs 	logger            loggers.Logger++	// The import context set in resources.Copy, if any.+	ctx           context.Context+	importContext resource.ResourceGetter+}++// setImportContext sets the import context to try before the file system when resolving imports.+func (imp *importResolver) setImportContext(ctx context.Context, importContext resource.ResourceGetter) {+	imp.ctx = ctx+	imp.importContext = importContext }  func newImportResolver(r io.Reader, inPath string, opts InlineImports, fs afero.Fs, logger loggers.Logger, dependencyManager identity.Manager) *importResolver {@@ -73,9 +86,32 @@ func (imp *importResolver) contentHash(filename string) ([]byte, string) { 	if err != nil { 		return nil, "" 	}+	return b, hashContent(b)+}++func hashContent(b []byte) string { 	h := sha256.New() 	h.Write(b)-	return b, hex.EncodeToString(h.Sum(nil))+	return hex.EncodeToString(h.Sum(nil))+}++// importFromImportContext resolves importPath in the import context.+// It returns a nil slice if not found.+func (imp *importResolver) importFromImportContext(importPath string) ([]byte, string, error) {+	if imp.importContext == nil {+		return nil, "", nil+	}+	r := imp.importContext.Get(importPath)+	if r == nil {+		return nil, "", nil+	}+	imp.dependencyManager.AddIdentity(identity.FirstIdentity(r))+	content, err := resources.InternalResourceSourceContent(imp.ctx, r)+	if err != nil {+		return nil, "", fmt.Errorf("failed to read import %q: %w", resources.InternalResourceSourcePathBestEffort(r), err)+	}+	b := []byte(content)+	return b, hashContent(b), nil }  func (imp *importResolver) importRecursive(@@ -105,8 +141,16 @@ 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)++			// Imports from the import context set in resources.Copy take precedence.+			importContent, hash, err := imp.importFromImportContext(path)+			if err != nil {+				return 0, "", err+			}+			if importContent == nil {+				imp.dependencyManager.AddIdentity(identity.CleanStringIdentity(filename))+				importContent, hash = imp.contentHash(filename)+			}  			if importContent == nil { 				if imp.opts.SkipInlineImportsNotFound {resources/resource_transformers/cssjs/inline_imports_test.goindex 3578e2612..7e6195369 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,63 @@ E_STYLE`) 	}) } +type testContentResource struct {+	resource.Resource+	content string+}++func (r testContentResource) Content(context.Context) (any, error) {+	return r.content, nil+}++type testResourceGetter map[string]resource.Resource++func (g testResourceGetter) Get(name any) resource.Resource {+	return g[name.(string)]+}++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)+	}++	writeFile("b.css", "B_STYLE_FROM_FS")+	writeFile("c.css", "C_STYLE_FROM_FS")+	writeFile("d.css", "D_STYLE_FROM_FS")++	mainStyles := strings.NewReader(`@import "a.css";+@import "b.css";+LOCAL_STYLE+@import "c.css";`)++	imp := newImportResolver(+		mainStyles,+		"styles.css",+		InlineImports{},+		fs, loggers.NewDefault(),+		identity.NopManager,+	)++	imp.setImportContext(context.Background(), testResourceGetter{+		"a.css": testContentResource{content: "@import \"d.css\"\nA_STYLE_FROM_CONTEXT"},+		"b.css": testContentResource{content: "B_STYLE_FROM_CONTEXT"},+	})++	r, err := imp.resolve()+	c.Assert(err, qt.IsNil)+	rs := helpers.ReaderToString(r)+	result := regexp.MustCompile(`\n+`).ReplaceAllString(rs, "\n")++	c.Assert(result, hqt.IsSameString, `D_STYLE_FROM_FS+A_STYLE_FROM_CONTEXT+B_STYLE_FROM_CONTEXT+LOCAL_STYLE+C_STYLE_FROM_FS`)+}+ func BenchmarkImportResolver(b *testing.B) { 	c := qt.New(b) 	fs := afero.NewMemMapFs()resources/resource_transformers/cssjs/postcss.goindex 94295eea9..977d4efdd 100644@@ -218,6 +218,7 @@ func (t *postcssTransformation) Transform(ctx *resources.ResourceTransformationC 		options.InlineImports, 		t.rs.Assets.Fs, t.rs.Logger, ctx.DependencyManager, 	)+	imp.setImportContext(ctx.Ctx, ctx.ImportContext)  	if options.InlineImports.InlineImports { 		var err errorresources/resource_transformers/cssjs/tailwindcss.goindex 539016dc2..21e7f953b 100644@@ -129,6 +129,7 @@ func (t *tailwindcssTransformation) Transform(ctx *resources.ResourceTransformat 		options.InlineImports, 		t.rs.Assets.Fs, t.rs.Logger, ctx.DependencyManager, 	)+	imp.setImportContext(ctx.Ctx, ctx.ImportContext)  	if !options.InlineImports.DisableInlineImports { 		src, err = imp.resolve()resources/resource_transformers/js/transform.goindex 07933a92f..91c11d96e 100644@@ -70,6 +70,9 @@ func (t *buildTransformation) Transform(ctx *resources.ResourceTransformationCtx 	opts.Stdin = true 	opts.IsCSS = t.c.c.CssMode +	// Resolve imports from the import context set in resources.Copy, if any.+	esbuild.ApplyImportContext(ctx.Ctx, &opts, ctx.ImportContext, ctx.DependencyManager)+ 	_, err = t.c.transform(opts, ctx)  	return errresources/resource_transformers/tocss/dartsass/transform.goindex e3d5823e9..2ab033777 100644@@ -14,6 +14,7 @@ package dartsass  import (+	"context" 	"fmt" 	"io" 	"path"@@ -29,6 +30,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"@@ -80,9 +82,12 @@ func (t *transform) Transform(ctx *resources.ResourceTransformationCtx) error { 		URL:          filename, 		IncludePaths: t.c.sfs.RealDirs(baseDir), 		ImportResolver: importResolver{+			ctx:               ctx.Ctx,+			stdinURL:          filename, 			baseDir:           baseDir, 			c:                 t.c, 			dependencyManager: ctx.DependencyManager,+			importContext:     ctx.ImportContext,  			vars: opts.Vars, 		},@@ -129,9 +134,12 @@ func (t *transform) Transform(ctx *resources.ResourceTransformationCtx) error { }  type importResolver struct {+	ctx               context.Context+	stdinURL          string 	baseDir           string 	c                 *Client 	dependencyManager identity.Manager+	importContext     resource.ResourceGetter 	vars              map[string]any } @@ -140,6 +148,33 @@ func (t importResolver) CanonicalizeURL(url string) (string, error) { 		return strings.ToLower(url), nil 	} +	if t.importContext != nil {+		// Imports from the import context set in resources.Copy take precedence.+		var importContextURL string+		if strings.HasPrefix(url, dartSassStdinPrefix) {+			// Dart Sass resolves relative imports in the source file against its URL,+			// e.g. hugostdin:/path/to/assets/scss/colors for the import "colors".+			stdinDir := path.Dir(filepath.ToSlash(t.stdinURL))+			if rel, ok := strings.CutPrefix(filepath.ToSlash(url), stdinDir+"/"); ok {+				importContextURL = rel+			}+		} else if !strings.HasPrefix(url, "file:") {+			// File URLs are resolved relative to the importing file in the file system.+			importContextURL = url+		}+		if importContextURL != "" {+			if r, canonicalURL := sass.ResolveFromImportContext(importContextURL, t.importContext, true); r != nil {+				t.dependencyManager.AddIdentity(identity.FirstIdentity(r))+				return canonicalURL, nil+			}+		}+	}++	if _, ok := sass.ImportContextSubPath(url); ok {+		// Not found in the import context, let Dart Sass try the other importers.+		return "", nil+	}+ 	filePath, isURL := paths.UrlStringToFilename(url) 	var prevDir string 	var pathDir string@@ -198,15 +233,30 @@ func (t importResolver) Load(url string) (godartsass.Import, error) { 			Content: sass.CreateVarsStyleSheet(sass.TranspilerDart, sass.ResolveVars(t.vars, subPath)), 		}, nil 	}+	if _, ok := sass.ImportContextSubPath(url); ok {+		r, _ := sass.ResolveFromImportContext(url, t.importContext, true)+		if r == nil {+			return godartsass.Import{}, fmt.Errorf("failed to load %q from 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) +	return godartsass.Import{Content: string(b), SourceSyntax: sourceSyntaxFromFilename(filename)}, err+}++func sourceSyntaxFromFilename(filename string) godartsass.SourceSyntax { 	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: sourceSyntax}, err+	return sourceSyntax }resources/resource_transformers/tocss/sass/helpers.goindex cb8cabd07..7f689d792 100644@@ -16,6 +16,7 @@ package sass import ( 	"fmt" 	"maps"+	"path" 	"regexp" 	"sort" 	"strings"@@ -24,10 +25,16 @@ 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 ( 	HugoVarsNamespace = "hugo:vars"++	// HugoImportContextNamespace is the URL namespace used for imports resolved+	// from an import context set in resources.Copy.+	HugoImportContextNamespace = "hugo:importcontext"+ 	// Transpiler implementation can be controlled from the client by 	// setting the 'transpiler' option. 	// Default is currently 'libsass', but that may change.@@ -48,6 +55,66 @@ func HugoVarsSubPath(url string) (string, bool) { 	return "", false } +// ImportContextSubPath returns the path relative to the import context of a+// "hugo:importcontext" URL, e.g. "hugo:importcontext/components/_button.scss" -> "components/_button.scss".+// The second return is false if url is not in the "hugo:importcontext" namespace.+func ImportContextSubPath(url string) (string, bool) {+	return strings.CutPrefix(url, HugoImportContextNamespace+"/")+}++// ResolveFromImportContext resolves the Sass import url using importContext,+// trying the same file name variations as for files in the file system (partials, extensions and index files).+// The import url is resolved relative to the root of the import context.+// It returns the resource found and the URL in the "hugo:importcontext" namespace to use for it,+// or nil and an empty string if not found.+func ResolveFromImportContext(url string, importContext resource.ResourceGetter, includeCSS bool) (resource.Resource, string) {+	if importContext == nil {+		return nil, ""+	}+	if subPath, ok := ImportContextSubPath(url); ok {+		url = subPath+	}++	dir, name := path.Split(strings.TrimPrefix(url, "./"))+	if name == "" {+		return nil, ""+	}++	// 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"}+		if includeCSS {+			namePatterns = append(namePatterns, "_%s.css")+		}+	} else {+		namePatterns = []string{+			"_%s.scss", "%s.scss",+			"_%s.sass", "%s.sass",+		}+		if includeCSS {+			namePatterns = append(namePatterns, "_%s.css", "%s.css")+		}+		namePatterns = append(namePatterns,+			"%s/_index.scss", "%s/_index.sass",+			"%s/index.scss", "%s/index.sass",+		)+	}++	name = strings.TrimPrefix(name, "_")++	for _, namePattern := range namePatterns {+		nameToCheck := path.Join(dir, fmt.Sprintf(namePattern, name))+		if r := importContext.Get(nameToCheck); r != nil {+			return r, HugoImportContextNamespace + "/" + nameToCheck+		}+	}++	return nil, ""+}+ // PrepareVars lowercases all keys for any map value recursively and returns a clone if modified. func PrepareVars(vars map[string]any) map[string]any { 	if vars == nil {resources/resource_transformers/tocss/scss/tocss.goindex ea8617140..78301f980 100644@@ -69,11 +69,34 @@ 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.+	// Any error reading an import from the import context.+	// The import resolver cannot return errors, so we return this after the transpilation.+	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 		} +		// Imports from the import context set in resources.Copy take precedence.+		if r, newURL := sass.ResolveFromImportContext(url, ctx.ImportContext, false); r != nil {+			ctx.DependencyManager.AddIdentity(identity.FirstIdentity(r))+			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+			}+			return newURL, content, true+		}++		if _, ok := sass.ImportContextSubPath(prev); ok {+			// Imported from the import context, but not found there.+			// Resolve relative to the source file.+			prev = "stdin"+		}+ 		// We get URL paths from LibSASS, but we need file paths. 		url = filepath.FromSlash(url) 		prev = filepath.FromSlash(prev)@@ -150,6 +173,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..b755c8f6b 100644@@ -129,6 +129,12 @@ type ResourceTransformationCtx struct { 	// The media type of the transformed resource. 	OutMediaType media.Type +	// The import context to use when resolving imports (e.g. CSS @import) in the content,+	// as set in resources.Copy.+	// This is nil if not set.+	// Transformations should try this before resolving imports in the file system.+	ImportContext resource.ResourceGetter+ 	// Data data can be set on the transformed Resource. Not that this need 	// to be simple types, as it needs to be serialized to JSON and back. 	Data map[string]any@@ -227,8 +233,8 @@ func (r *resourceAdapter) GetDependencyManager() identity.Manager { 	return r.target.GetDependencyManager() } -func (r resourceAdapter) cloneTo(targetPath string) resource.Resource {-	newtTarget := r.target.cloneTo(targetPath)+func (r resourceAdapter) cloneTo(opts CopyOptions) resource.Resource {+	newtTarget := r.target.cloneTo(opts) 	newInner := &resourceAdapterInner{ 		ctx:    r.ctx, 		spec:   r.spec,@@ -291,6 +297,10 @@ func (r *resourceAdapter) TransientKey() string { 	return r.Key() } +func (r *resourceAdapter) getImportContext() *importContext {+	return r.target.getImportContext()+}+ func (r *resourceAdapter) targetPath() string { 	r.init(false, false) 	return r.target.(targetPathProvider).targetPath()@@ -521,6 +531,10 @@ func (r *resourceAdapter) transform(key string, publish, setContent bool) (*reso 	tctx.InMediaType = r.target.MediaType() 	tctx.OutMediaType = r.target.MediaType() +	if ic := r.target.getImportContext(); ic != nil {+		tctx.ImportContext = resource.NewCachedResourceGetter(ic.getter)+	}+ 	startCtx := *tctx 	updates := &transformationUpdate{startCtx: startCtx} tpl/resources/copy_importcontext_integration_test.gonew file mode 100644index 000000000..8c5b60aa6@@ -0,0 +1,324 @@+// 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 (+	"strings"+	"testing"++	qt "github.com/frankban/quicktest"+	"github.com/gohugoio/hugo/hugolib"+	"github.com/gohugoio/hugo/resources/resource_transformers/tocss/dartsass"+	"github.com/gohugoio/hugo/resources/resource_transformers/tocss/scss"+)++func TestCopyImportContextCSSBuild(t *testing.T) {+	t.Parallel()++	files := `+-- hugo.toml --+disableKinds = ['page','section','rss','sitemap','taxonomy','term']+-- assets/css/main.css --+@import "foo.css" screen;+@import "bar.css" print;+@import "assetsonly.css";+.main { color: red; }+-- assets/css/assetsonly.css --+.assetsonly { color: black; }+-- assets/css/bar.css --+.bar-from-assets { color: black; }+-- layouts/home.html --+{{ $foo := resources.FromString "foo.css" ".foo { color: blue; }" }}+{{ $bar := resources.FromString "bar.css" ".bar { color: green; }" }}+{{ $main := resources.Get "css/main.css" | resources.Copy (dict "importContext" (slice $foo $bar)) }}+{{ with $main | css.Build }}main: {{ .RelPermalink }}|{{ end }}+{{ $main2 := resources.Get "css/main.css" | resources.Copy (dict "targetPath" "css/main2.css" "importContext" (slice $foo)) }}+{{ with $main2 | css.Build }}main2: {{ .RelPermalink }}|{{ end }}+`++	b := hugolib.Test(t, files, hugolib.TestOptOsFs())++	b.AssertFileContent("public/index.html", "main: /css/main.css|", "main2: /css/main2.css|")+	b.AssertFileContent("public/css/main.css",+		"@media screen {\n  .foo {",+		"@media print {\n  .bar {\n    color: green;",+		".assetsonly",+		".main",+		"! .bar-from-assets",+	)+	// Different import context, bar.css resolved from /assets.+	b.AssertFileContent("public/css/main2.css",+		"@media screen {\n  .foo {",+		".bar-from-assets",+		"! color: green",+	)+}++func TestCopyImportContextJSBuildPageResources(t *testing.T) {+	t.Parallel()++	files := `+-- hugo.toml --+disableKinds = ['section','rss','sitemap','taxonomy','term']+-- assets/js/main.js --+import { hello } from "lib/hello";+import { common } from "common/common.js";+console.log(hello(), common());+-- assets/js/headlessui/common.js --+export function common() { return "common from mount"; }+-- content/p1/index.md --+---+title: p1+---+-- content/p1/lib/hello.js --+export function hello() { return "hello from p1"; }+-- content/p2/index.md --+---+title: p2+---+-- content/p2/lib/hello.js --+export function hello() { return "hello from p2"; }+-- layouts/home.html --+Home.+-- layouts/single.html --+{{ $common := (resources.Match "js/headlessui/*.*").Mount "/js/headlessui" "common" }}+{{ $opts := dict "targetPath" (printf "js/%s.js" .File.ContentBaseName) "importContext" (slice . $common) }}+{{ $js := resources.Get "js/main.js" | resources.Copy $opts | js.Build }}+JS: {{ $js.RelPermalink }}|+`++	b := hugolib.Test(t, files, hugolib.TestOptOsFs())++	b.AssertFileContent("public/p1/index.html", "JS: /js/p1.js|")+	b.AssertFileContent("public/p2/index.html", "JS: /js/p2.js|")+	b.AssertFileContent("public/js/p1.js", "hello from p1", "common from mount", "! hello from p2")+	b.AssertFileContent("public/js/p2.js", "hello from p2", "common from mount", "! hello from p1")+}++// The same target path and transformation, but different import contexts,+// must not share cached transformation results.+func TestCopyImportContextSameTargetPathDifferentContexts(t *testing.T) {+	t.Parallel()++	files := `+-- hugo.toml --+disableKinds = ['section','section','rss','sitemap','taxonomy','term']+-- assets/css/main.css --+@import "theme.css";+-- content/blue/index.md --+---+title: blue+---+-- content/blue/theme.css --+.theme { color: blue; }+-- content/green/index.md --+---+title: green+---+-- content/green/theme.css --+.theme { color: green; }+-- layouts/home.html --+{{ $main := resources.Get "css/main.css" }}+{{ $c1 := $main | resources.Copy (dict "importContext" (site.GetPage "blue")) | css.Build (dict "minify" true) }}+{{ $c2 := $main | resources.Copy (dict "importContext" (site.GetPage "green")) | css.Build (dict "minify" true) }}+c1: {{ $c1.Content | safeCSS }}|+c2: {{ $c2.Content | safeCSS }}|+`++	b := hugolib.Test(t, files, hugolib.TestOptOsFs())++	b.AssertFileContent("public/index.html", "c1: .theme{color:#00f}\n|", "c2: .theme{color:green}\n|")+}++// Import context set on an already transformed resource, and no options at all.+// Import contexts with the same paths but different content must not share cached results.+func TestCopyImportContextSamePathDifferentContent(t *testing.T) {+	t.Parallel()++	files := `+-- hugo.toml --+disableKinds = ['section','rss','sitemap','taxonomy','term']+-- assets/css/main.css --+@import "vars.css";+.main { color: red; }+-- content/p1.md --+---+title: p1+color: blue+---+-- content/p2.md --+---+title: p2+color: green+---+-- layouts/page.html --+{{ $vars := resources.FromString "vars.css" (printf ".v { color: %s; }" .Params.color) }}+{{ $c := resources.Get "css/main.css" | resources.Copy (dict "importContext" $vars) | css.Build }}+Content: {{ $c.Content }}|+-- layouts/home.html --+Home.+`++	b := hugolib.Test(t, files, hugolib.TestOptOsFs())++	b.AssertFileContent("public/p1/index.html", "color: blue", "! color: green")+	b.AssertFileContent("public/p2/index.html", "color: green", "! color: blue")+}++func TestCopyImportContextTransformedResource(t *testing.T) {+	t.Parallel()++	files := `+-- hugo.toml --+disableKinds = ['page','section','rss','sitemap','taxonomy','term']+-- assets/css/main.css --+@import "foo.css";+.main { color: red; }+-- layouts/home.html --+{{ $foo := resources.FromString "foo.css" ".foo { color: blue; }" }}+{{ $main := resources.Get "css/main.css" | resources.Minify | resources.Copy (dict "importContext" $foo) }}+{{ with $main | css.Build }}main: {{ .RelPermalink }}|{{ end }}+{{ $plain := resources.Get "css/main.css" | resources.Copy }}+plain: {{ $plain.RelPermalink }}|+`++	b := hugolib.Test(t, files, hugolib.TestOptOsFs())++	b.AssertFileContent("public/index.html", "main: /css/main.min.css|", "plain: /css/main.css|")+	b.AssertFileContent("public/css/main.min.css", ".foo {\n  color: blue;", ".main")+}++func TestCopyImportContextCSSBuildEdit(t *testing.T) {+	t.Parallel()++	files := `+-- hugo.toml --+disableKinds = ["taxonomy", "term", "rss", "section", "sitemap"]+-- assets/css/main.css --+@import "theme.css";+.main { background: red; }+-- content/p1/index.md --+---+title: p1+---+-- content/p1/theme.css --+.theme { background: green; }+-- layouts/all.html --+All.+-- layouts/single.html --+{{ $main := resources.Get "css/main.css" | resources.Copy (dict "targetPath" "css/p1.css" "importContext" .) }}+{{ with $main | css.Build (dict "minify" true) }}<link rel="stylesheet" href="{{ .RelPermalink }}" />{{ end }}+`+	b := hugolib.TestRunning(t, files, hugolib.TestOptOsFs())++	b.AssertFileContent("public/p1/index.html", `<link rel="stylesheet" href="/css/p1.css" />`)+	b.AssertFileContent("public/css/p1.css", `.theme{background:green}.main{background:red}`)++	// Edit the page resource resolved from the import context.+	b.EditFileReplaceAll("content/p1/theme.css", "green", "blue").Build()+	b.AssertFileContent("public/css/p1.css", `.theme{background:#00f}.main{background:red}`)++	// Edit main.css.+	b.EditFileReplaceAll("assets/css/main.css", "red", "yellow").Build()+	b.AssertFileContent("public/css/p1.css", `.theme{background:#00f}.main{background:#ff0}`)+}++func TestCopyImportContextErrors(t *testing.T) {+	t.Parallel()++	files := `+-- hugo.toml --+disableKinds = ['page','section','rss','sitemap','taxonomy','term']+-- assets/css/main.css --+.main { color: red; }+-- layouts/home.html --+{{ $main := resources.Get "css/main.css" | resources.Copy (dict "importContext" 42) }}+`++	b, err := hugolib.TestE(t, files)+	b.Assert(err, qt.IsNotNil)+	b.Assert(err.Error(), qt.Contains, "importContext: expected a Page, Resource, Resources mounted with .Mount or a slice of these, got int")++	files = strings.ReplaceAll(files, `(dict "importContext" 42)`, `(dict "importContexts" (slice))`)+	b, err = hugolib.TestE(t, files)+	b.Assert(err, qt.IsNotNil)+	b.Assert(err.Error(), qt.Contains, `failed to decode options`)+	b.Assert(err.Error(), qt.Contains, `importContexts`)+}++func TestCopyImportContextJSBatch(t *testing.T) {+	t.Parallel()++	files := `+-- hugo.toml --+disableKinds = ['page','section','rss','sitemap','taxonomy','term']+-- assets/js/main.js --+import { hello } from "hello.js";+console.log(hello());+-- layouts/home.html --+{{ $hello := resources.FromString "hello.js" "export function hello() { return 'hello from copy import context'; }" }}+{{ $main := resources.Get "js/main.js" | resources.Copy (dict "importContext" $hello) }}+{{ $batch := js.Batch "mybatch" }}+{{ with $batch.Group "mygroup" }}+  {{ with .Script "main" }}+    {{ .SetOptions (dict "resource" $main) }}+  {{ end }}+{{ end }}+{{ range $k, $v := $batch.Build.Groups }}+  {{ range $v }}{{ $k }}: {{ .RelPermalink }}|{{ end }}+{{ end }}+`++	b := hugolib.Test(t, files, hugolib.TestOptOsFs())++	b.AssertFileContent("public/index.html", "mygroup: /mybatch/mygroup.js|")+	b.AssertFileContent("public/mybatch/mygroup.js", "hello from copy import context")+}++func TestCopyImportContextSass(t *testing.T) {+	t.Parallel()++	files := `+-- hugo.toml --+disableKinds = ['page','section','rss','sitemap','taxonomy','term']+-- assets/scss/main.scss --+@import "colors";+@import "components/button";+.main { color: $color; }+-- assets/scss/components/_button.scss --+.button-from-assets { color: black; }+-- layouts/home.html --+{{ $colors := resources.FromString "_colors.scss" "$color: blue;" }}+{{ $button := resources.FromString "components/_button.scss" ".button { color: $color; }" }}+{{ $main := resources.Get "scss/main.scss" | resources.Copy (dict "importContext" (slice $colors $button)) }}+{{ with $main | css.Sass (dict "transpiler" "TRANSPILER") }}{{ .Content | safeCSS }}{{ end }}+`++	for _, transpiler := range []string{"libsass", "dartsass"} {+		t.Run(transpiler, func(t *testing.T) {+			if transpiler == "libsass" && !scss.Supports() {+				t.Skip("libsass not supported")+			}+			if transpiler == "dartsass" && !dartsass.Supports() {+				t.Skip("dartsass not supported")+			}+			b := hugolib.Test(t, replaceTranspiler(files, transpiler), hugolib.TestOptOsFs())+			b.AssertFileContent("public/index.html", ".button", "color: blue", "! .button-from-assets")+		})+	}+}++func replaceTranspiler(files, transpiler string) string {+	return strings.ReplaceAll(files, "TRANSPILER", transpiler)+}tpl/resources/resources.goindex 2512b5ce9..87bbfc1b4 100644@@ -34,6 +34,7 @@ import ( 	"github.com/gohugoio/hugo/resources/resource_transformers/minifier" 	"github.com/gohugoio/hugo/resources/resource_transformers/templates" +	"github.com/mitchellh/mapstructure" 	"github.com/spf13/cast" ) @@ -71,13 +72,50 @@ type Namespace struct { 	templatesClient *templates.Client } -// Copy copies r to the new targetPath in s.-func (ns *Namespace) Copy(s any, r resource.Resource) (resource.Resource, error) {-	targetPath, err := cast.ToStringE(s)-	if err != nil {-		panic(err)+// Copy copies the resource in the last argument.+// The first, optional, argument is either the target path or an options map with the keys+// targetPath and importContext.+// If the target path is not set, the target path of the resource is preserved.+func (ns *Namespace) Copy(args ...any) (resource.Resource, error) {+	if len(args) < 1 || len(args) > 2 {+		return nil, errors.New("must provide a Resource and optionally a target path or an options map") 	}-	return ns.createClient.Copy(r, targetPath)++	r, ok := args[len(args)-1].(resource.Resource)+	if !ok {+		return nil, fmt.Errorf("expected a Resource as the last argument, got %T", args[len(args)-1])+	}++	var opts resources.CopyOptions++	if len(args) == 2 {+		switch v := args[0].(type) {+		case string:+			opts.TargetPath = v+		default:+			if m, err := hmaps.ToStringMapE(v); err == nil {+				decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{+					WeaklyTypedInput: true,+					ErrorUnused:      true,+					Result:           &opts,+				})+				if err != nil {+					return nil, err+				}+				if err := decoder.Decode(m); err != nil {+					return nil, fmt.Errorf("failed to decode options: %w", err)+				}+			} else {+				targetPath, err := cast.ToStringE(v)+				if err != nil {+					return nil, fmt.Errorf("expected a target path or an options map, got %T", v)+				}+				opts.TargetPath = targetPath+			}+		}+	}++	return ns.createClient.CopyWithOptions(r, opts) }  // 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"