| 1 |
// Copyright 2024 The Hugo Authors. All rights reserved. |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
// |
| 8 |
// Unless required by applicable law or agreed to in writing, software |
| 9 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 |
// See the License for the specific language governing permissions and |
| 12 |
// limitations under the License. |
| 13 |
|
| 14 |
package js |
| 15 |
|
| 16 |
import ( |
| 17 |
"fmt" |
| 18 |
"path" |
| 19 |
"path/filepath" |
| 20 |
"regexp" |
| 21 |
"sort" |
| 22 |
"strings" |
| 23 |
|
| 24 |
"github.com/evanw/esbuild/pkg/api" |
| 25 |
"github.com/gohugoio/hugo/common/paths" |
| 26 |
"github.com/gohugoio/hugo/helpers" |
| 27 |
"github.com/gohugoio/hugo/hugolib/filesystems" |
| 28 |
"github.com/gohugoio/hugo/internal/js/esbuild" |
| 29 |
"github.com/gohugoio/hugo/media" |
| 30 |
|
| 31 |
"github.com/gohugoio/hugo/resources" |
| 32 |
"github.com/gohugoio/hugo/resources/resource" |
| 33 |
) |
| 34 |
|
| 35 |
// Client context for ESBuild. |
| 36 |
type Client struct { |
| 37 |
c *esbuild.BuildClient |
| 38 |
} |
| 39 |
|
| 40 |
// New creates a new client context. |
| 41 |
func New(fs *filesystems.SourceFilesystem, rs *resources.Spec, cssMode bool) *Client { |
| 42 |
return &Client{ |
| 43 |
c: esbuild.NewBuildClient(fs, rs, cssMode), |
| 44 |
} |
| 45 |
} |
| 46 |
|
| 47 |
// Process processes a resource with the user provided options. |
| 48 |
// If importContext is not nil, imports are resolved in it first, |
| 49 |
// then in the assets filesystem (the same precedence as in js.Batch). |
| 50 |
func (c *Client) Process(res resources.ResourceTransformer, opts map[string]any) (resource.Resource, error) { |
| 51 |
return res.Transform( |
| 52 |
&buildTransformation{c: c, optsm: opts}, |
| 53 |
) |
| 54 |
} |
| 55 |
|
| 56 |
func (c *Client) transform(opts esbuild.Options, transformCtx *resources.ResourceTransformationCtx) (api.BuildResult, error) { |
| 57 |
if transformCtx.DependencyManager != nil { |
| 58 |
opts.DependencyManager = transformCtx.DependencyManager |
| 59 |
} |
| 60 |
|
| 61 |
opts.StdinSourcePath = transformCtx.SourcePath |
| 62 |
|
| 63 |
pathSpec := c.c.Spec().PathSpec |
| 64 |
outDir := path.Dir(transformCtx.OutPath) |
| 65 |
if opts.IsCSS && opts.PublicPath == "" { |
| 66 |
// Make file-loader artifact URLs (e.g. fonts, images) absolute relative |
| 67 |
// to the web context root, so they resolve correctly whether the CSS is |
| 68 |
// published as a file or inlined into HTML. See issue #14849. |
| 69 |
// In multihost we build once for all hosts; using the deepest of the |
| 70 |
// per-host base paths keeps the URL reachable on every host (each |
| 71 |
// host's base path is a prefix). |
| 72 |
var basePath string |
| 73 |
if pathSpec.MultihostLongestBasePath != "" { |
| 74 |
basePath = pathSpec.MultihostLongestBasePath |
| 75 |
} else { |
| 76 |
basePath = pathSpec.GetBasePath(false) |
| 77 |
} |
| 78 |
dir := outDir |
| 79 |
if dir == "." { |
| 80 |
dir = "" |
| 81 |
} |
| 82 |
opts.PublicPath = "/" + strings.TrimPrefix(path.Join(basePath, dir), "/") |
| 83 |
} |
| 84 |
|
| 85 |
result, err := c.c.Build(opts) |
| 86 |
if err != nil { |
| 87 |
return result, err |
| 88 |
} |
| 89 |
|
| 90 |
hasLinkedSourceMap := opts.ExternalOptions.SourceMap == "linked" |
| 91 |
hasSourceMap := hasLinkedSourceMap || opts.ExternalOptions.SourceMap == "external" |
| 92 |
|
| 93 |
spec := c.c.Spec() |
| 94 |
mediaTypes := spec.MediaTypes() |
| 95 |
baseURL := spec.Cfg.BaseURL().WithoutPath |
| 96 |
newArtifact := func(relPermalink, fileName string) resources.Artifact { |
| 97 |
mt, _, found := mediaTypes.GetFirstBySuffix(strings.TrimPrefix(path.Ext(fileName), ".")) |
| 98 |
if !found { |
| 99 |
mt = media.Builtin.OctetType |
| 100 |
} |
| 101 |
return resources.NewArtifact(baseURL+relPermalink, relPermalink, mt) |
| 102 |
} |
| 103 |
fileLoaderRelPermalink := func(base string) string { |
| 104 |
if opts.PublicPath != "" { |
| 105 |
return strings.TrimSuffix(opts.PublicPath, "/") + "/" + paths.PathEscape(base) |
| 106 |
} |
| 107 |
return pathSpec.GetBasePath(false) + paths.PathEscape(paths.AddLeadingSlash(path.Join(outDir, base))) |
| 108 |
} |
| 109 |
|
| 110 |
// Classify output files by path rather than relying on array ordering, |
| 111 |
// which esbuild does not guarantee. |
| 112 |
var mainOutput []byte |
| 113 |
var artifacts []resources.Artifact |
| 114 |
for _, file := range result.OutputFiles { |
| 115 |
basePath := path.Base(filepath.ToSlash(file.Path)) |
| 116 |
if strings.HasSuffix(basePath, ".map") { |
| 117 |
if hasSourceMap { |
| 118 |
if err = transformCtx.PublishSourceMap(file.Contents); err != nil { |
| 119 |
return result, err |
| 120 |
} |
| 121 |
artifacts = append(artifacts, newArtifact(pathSpec.GetBasePath(false)+paths.PathEscape(paths.AddLeadingSlash(transformCtx.OutPath+".map")), basePath)) |
| 122 |
} |
| 123 |
} else if isStdinEntryOutput(basePath) { |
| 124 |
mainOutput = file.Contents |
| 125 |
} else { |
| 126 |
// File-loader artifact; publish directly. |
| 127 |
if err = publishFileLoaderArtifact(pathSpec, opts.PublicPath, outDir, basePath, file.Contents, transformCtx); err != nil { |
| 128 |
return result, err |
| 129 |
} |
| 130 |
artifacts = append(artifacts, newArtifact(fileLoaderRelPermalink(basePath), basePath)) |
| 131 |
} |
| 132 |
} |
| 133 |
|
| 134 |
sort.Slice(artifacts, func(i, j int) bool { return artifacts[i].RelPermalink() < artifacts[j].RelPermalink() }) |
| 135 |
transformCtx.Data["Artifacts"] = artifacts |
| 136 |
|
| 137 |
if mainOutput == nil { |
| 138 |
return result, fmt.Errorf("esbuild: entry point output not found") |
| 139 |
} |
| 140 |
|
| 141 |
if hasLinkedSourceMap { |
| 142 |
symPath := path.Base(transformCtx.OutPath) + ".map" |
| 143 |
if opts.IsCSS { |
| 144 |
re := regexp.MustCompile(`/\*# sourceMappingURL=.*\n?`) |
| 145 |
mainOutput = re.ReplaceAll(mainOutput, []byte("/*# sourceMappingURL="+symPath+" */\n")) |
| 146 |
} else { |
| 147 |
re := regexp.MustCompile(`//# sourceMappingURL=.*\n?`) |
| 148 |
mainOutput = re.ReplaceAll(mainOutput, []byte("//# sourceMappingURL="+symPath+"\n")) |
| 149 |
} |
| 150 |
} |
| 151 |
|
| 152 |
if _, err = transformCtx.To.Write(mainOutput); err != nil { |
| 153 |
return result, err |
| 154 |
} |
| 155 |
|
| 156 |
return result, nil |
| 157 |
} |
| 158 |
|
| 159 |
// isStdinEntryOutput reports whether basePath is the entry-point output |
| 160 |
// generated by esbuild when using stdin mode (e.g. "stdin.js", "stdin.css"). |
| 161 |
func isStdinEntryOutput(basePath string) bool { |
| 162 |
return strings.HasPrefix(basePath, "stdin.") |
| 163 |
} |
| 164 |
|
| 165 |
// publishFileLoaderArtifact writes a file-loader artifact (e.g. a font or image |
| 166 |
// referenced from CSS) to the publish directory. In multihost mode the URL is |
| 167 |
// the same on all hosts, but each host has its own base path; the file is |
| 168 |
// placed where each host's URL resolution will find it. |
| 169 |
func publishFileLoaderArtifact(pathSpec *helpers.PathSpec, publicPath, outDir, basePath string, content []byte, transformCtx *resources.ResourceTransformationCtx) error { |
| 170 |
if len(pathSpec.MultihostTargetBasePaths) == 0 { |
| 171 |
return transformCtx.PublishTo(path.Join(outDir, basePath), content) |
| 172 |
} |
| 173 |
|
| 174 |
urlPath := path.Join(publicPath, basePath) |
| 175 |
if !strings.HasPrefix(urlPath, "/") { |
| 176 |
urlPath = "/" + urlPath |
| 177 |
} |
| 178 |
filenames := make([]string, len(pathSpec.MultihostTargetBasePaths)) |
| 179 |
for i, langPrefix := range pathSpec.MultihostTargetBasePaths { |
| 180 |
filenames[i] = filepath.FromSlash(langPrefix + strings.TrimPrefix(urlPath, pathSpec.MultihostBasePaths[i])) |
| 181 |
} |
| 182 |
fw, err := helpers.OpenFilesForWriting(pathSpec.BaseFs.PublishFs, filenames...) |
| 183 |
if err != nil { |
| 184 |
return err |
| 185 |
} |
| 186 |
defer fw.Close() |
| 187 |
_, err = fw.Write(content) |
| 188 |
return err |
| 189 |
} |