Debian Codegraph @

modules/npm/package_builder.go

raw
1 // Copyright 2020 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 npm
15
16 import (
17 "bytes"
18 "context"
19 "encoding/json"
20 "fmt"
21 "io"
22 "os"
23 "path/filepath"
24 "runtime"
25 "slices"
26 "strings"
27
28 "github.com/gohugoio/hugo/common/hashing"
29 "github.com/gohugoio/hugo/common/hmaps"
30
31 "github.com/gohugoio/hugo/hugofs/files"
32 "github.com/gohugoio/hugo/modules"
33
34 "github.com/gohugoio/hugo/hugofs"
35 "github.com/spf13/afero"
36
37 "github.com/gohugoio/hugo/helpers"
38 )
39
40 const (
41 dependenciesKey = "dependencies"
42 devDependenciesKey = "devDependencies"
43
44 packageJSONName = "package.json"
45 packageMetaJSONName = "hugo_packagemeta.json"
46 )
47
48 var (
49 workspacePackageJSON = filepath.Join(files.FolderPackagesHugoAutoGen, packageJSONName)
50 workspacePackageMetaJSON = filepath.Join(files.FolderPackagesHugoAutoGen, packageMetaJSONName)
51 )
52
53 func Pack(sourceFs, assetsWithDuplicatesPreservedFs afero.Fs, mods modules.Modules) error {
54 b := &packageBuilder{
55 devDependencies: make(map[string]any),
56 devDependenciesComments: make(map[string]any),
57 dependencies: make(map[string]any),
58 dependenciesComments: make(map[string]any),
59 }
60
61 workspacePath := filepath.ToSlash(files.FolderPackagesHugoAutoGen)
62
63 // skip modules that shouldn't have their package files processed, either because they are the project module (handled separately)
64 // or because their UsePackageJSON setting disables it.
65 skipPackageJSON := buildSkipPackageJSON(mods)
66
67 // 1. Read project deps: prefer package.hugo.json, fall back to package.json.
68 var rootPkg map[string]any
69 rootData, err := afero.ReadFile(sourceFs, packageJSONName)
70 if err == nil {
71 rootPkg = b.unmarshal(bytes.NewReader(rootData))
72 if b.err != nil {
73 return fmt.Errorf("npm pack: failed to parse package.json: %w", b.err)
74 }
75 }
76
77 // Workspaces source: prefer package.hugo.json, fall back to package.json.
78 var workspacesSource map[string]any
79 hugoData, hugoErr := afero.ReadFile(sourceFs, files.FilenamePackageHugoJSON)
80 if hugoErr == nil {
81 hugoPkg := b.unmarshal(bytes.NewReader(hugoData))
82 if b.err != nil {
83 return fmt.Errorf("npm pack: failed to parse %s: %w", files.FilenamePackageHugoJSON, b.err)
84 }
85 b.addm("project", hugoPkg)
86 workspacesSource = hugoPkg
87 } else if rootPkg != nil {
88 b.addm("project", rootPkg)
89 workspacesSource = rootPkg
90 }
91
92 // 2. Read deps from referenced workspaces (always from package.json).
93 for _, wsDir := range resolveProjectWorkspaces(sourceFs, workspacesSource, workspacePath) {
94 wsFile := filepath.Join(wsDir, packageJSONName)
95 wsData, err := afero.ReadFile(sourceFs, wsFile)
96 if err != nil {
97 continue
98 }
99 wsm := b.unmarshal(bytes.NewReader(wsData))
100 if b.err != nil {
101 return fmt.Errorf("npm pack: failed to parse %s: %w", wsFile, b.err)
102 }
103 b.addm("project", wsm)
104 }
105
106 // 3. Walk _jsconfig for module deps.
107 // We use hugofs.Walkway (which uses ReadDir) instead of afero.Walk because
108 // afero.Walk uses Readdirnames+Stat, which loses the per-module identity
109 // when multiple modules mount a file (e.g. package.json) to the same virtual path.
110 // Note that the order of files here is in the order of importance.
111 type pkgEntry struct {
112 info hugofs.FileMetaInfo
113 isHugoJSON bool
114 isRootLevel bool
115 }
116 var entries []pkgEntry
117 modulesWithHugoJSON := make(map[string]bool)
118
119 w := hugofs.NewWalkway(hugofs.WalkwayConfig{
120 Fs: assetsWithDuplicatesPreservedFs,
121 Root: files.FolderJSConfig,
122 WalkFn: func(ctx context.Context, path string, info hugofs.FileMetaInfo) error {
123 if info.IsDir() {
124 return nil
125 }
126
127 isPackageJSON := info.Name() == files.FilenamePackageJSON
128 isHugoJSON := info.Name() == files.FilenamePackageHugoJSON
129
130 if !isPackageJSON && !isHugoJSON {
131 return nil
132 }
133
134 m := info.Meta()
135 if skipPackageJSON[m.ModulePath()] {
136 return nil
137 }
138
139 // package.hugo.json is only valid at module roots, not inside workspaces.
140 isRootLevel := filepath.Dir(path) == files.FolderJSConfig
141 if isHugoJSON && !isRootLevel {
142 return nil
143 }
144
145 if isHugoJSON {
146 modulesWithHugoJSON[m.ModulePath()] = true
147 }
148
149 entries = append(entries, pkgEntry{info: info, isHugoJSON: isHugoJSON, isRootLevel: isRootLevel})
150 return nil
151 },
152 })
153 if err := w.Walk(); err != nil {
154 return err
155 }
156
157 // Process collected entries: for each module, prefer package.hugo.json
158 // over package.json at the root level. Workspace package.json files are always processed.
159 for _, e := range entries {
160 m := e.info.Meta()
161 // Skip root-level package.json if this module has package.hugo.json.
162 if !e.isHugoJSON && e.isRootLevel && modulesWithHugoJSON[m.ModulePath()] {
163 continue
164 }
165
166 f, err := m.Open()
167 if err != nil {
168 return fmt.Errorf("npm pack: failed to open package file: %w", err)
169 }
170 b.Add(m.ModulePath(), f)
171 f.Close()
172 }
173
174 if b.Err() != nil {
175 return fmt.Errorf("npm pack: failed to build: %w", b.Err())
176 }
177
178 // 4. Build the autogenerated workspace package.json.
179 // Exclude deps already defined by the project itself — they don't
180 // need to be duplicated in the workspace and it simplifies maintenance.
181 moduleDeps := make(map[string]any)
182 moduleDepsComments := make(map[string]any)
183 for k, v := range b.dependencies {
184 if b.dependenciesComments[k] != "project" {
185 moduleDeps[k] = v
186 moduleDepsComments[k] = b.dependenciesComments[k]
187 }
188 }
189 moduleDevDeps := make(map[string]any)
190 moduleDevDepsComments := make(map[string]any)
191 for k, v := range b.devDependencies {
192 if b.devDependenciesComments[k] != "project" {
193 moduleDevDeps[k] = v
194 moduleDevDepsComments[k] = b.devDependenciesComments[k]
195 }
196 }
197
198 // Stable defaults; mark the workspace private so npm never publishes it.
199 // Preserve any hand-set values from an existing file.
200 name, version, private := "hugoautogen", "0.1.0", true
201 if data, err := afero.ReadFile(sourceFs, workspacePackageJSON); err == nil {
202 var existing map[string]any
203 if err := json.Unmarshal(data, &existing); err == nil {
204 if s, ok := existing["name"].(string); ok && s != "" {
205 name = s
206 }
207 if s, ok := existing["version"].(string); ok && s != "" {
208 version = s
209 }
210 if b, ok := existing["private"].(bool); ok {
211 private = b
212 }
213 }
214 }
215
216 autoGenPkg := map[string]any{
217 "name": name,
218 "version": version,
219 "private": private,
220 dependenciesKey: moduleDeps,
221 devDependenciesKey: moduleDevDeps,
222 }
223
224 if err := sourceFs.MkdirAll(files.FolderPackagesHugoAutoGen, 0o777); err != nil {
225 return err
226 }
227 if err := writeJSON(sourceFs, workspacePackageJSON, autoGenPkg); err != nil {
228 return err
229 }
230
231 // 5. Ensure root package.json references the workspace.
232 if err := ensureWorkspaceRef(sourceFs, workspacePath); err != nil {
233 return err
234 }
235
236 // 6. Write metadata for the final on-disk package state.
237 metaFile := packageMeta{
238 Sum: PackageFilesSum(sourceFs, mods),
239 DependencySources: dependencySources{
240 Dependencies: moduleDepsComments,
241 DevDependencies: moduleDevDepsComments,
242 },
243 }
244 return writeJSON(sourceFs, workspacePackageMetaJSON, metaFile)
245 }
246
247 // ensureWorkspaceRef adds workspacePath to the "workspaces" array in root
248 // package.json with minimal formatting changes.
249 func ensureWorkspaceRef(fsys afero.Fs, workspacePath string) error {
250 data, err := afero.ReadFile(fsys, packageJSONName)
251 if err != nil {
252 content := fmt.Sprintf("{\n \"workspaces\": [\n %q\n ]\n}\n", workspacePath)
253 return afero.WriteFile(fsys, packageJSONName, []byte(content), 0o666)
254 }
255
256 if runtime.GOOS == "windows" {
257 data = bytes.ReplaceAll(data, []byte("\r\n"), []byte("\n"))
258 }
259
260 // Parse to check if already present.
261 var pkg map[string]any
262 if err := json.Unmarshal(data, &pkg); err != nil {
263 return fmt.Errorf("npm pack: failed to parse package.json: %w", err)
264 }
265
266 indent := detectIndent(data)
267 quoted := fmt.Sprintf("%q", workspacePath)
268
269 wsVal, hasWS := pkg["workspaces"]
270
271 switch v := wsVal.(type) {
272 case []any:
273 // Array form: ["pkg-a", "pkg-b", ...]
274 if slices.Contains(toStringSlice(v), workspacePath) {
275 if runtime.GOOS == "windows" {
276 return afero.WriteFile(fsys, packageJSONName, data, 0o666)
277 }
278 return nil
279 }
280 // Fall through to byte-based insertion into the existing array below.
281 case map[string]any:
282 // Object form: { "workspaces": { "packages": [...] } }
283 packagesVal, ok := v["packages"]
284 if !ok {
285 return fmt.Errorf("npm pack: unsupported workspaces object; missing \"packages\" field")
286 }
287 packagesSlice := toStringSlice(packagesVal)
288 if slices.Contains(packagesSlice, workspacePath) {
289 if runtime.GOOS == "windows" {
290 return afero.WriteFile(fsys, packageJSONName, data, 0o666)
291 }
292 return nil
293 }
294
295 // Append the new workspace path to the packages slice.
296 newPkgs := make([]any, 0, len(packagesSlice)+1)
297 for _, s := range packagesSlice {
298 newPkgs = append(newPkgs, s)
299 }
300 newPkgs = append(newPkgs, workspacePath)
301 v["packages"] = newPkgs
302
303 updated, err := json.MarshalIndent(pkg, "", indent)
304 if err != nil {
305 return fmt.Errorf("npm pack: failed to marshal package.json with updated workspaces: %w", err)
306 }
307 updated = append(updated, '\n')
308 return afero.WriteFile(fsys, packageJSONName, updated, 0o666)
309 case nil:
310 // Treat explicit null as "no workspaces"; handled below as missing key.
311 default:
312 return fmt.Errorf("npm pack: unsupported workspaces type %T", v)
313 }
314
315 // Try adding to existing workspaces array when present.
316 if hasWS && wsVal != nil {
317 if wsIdx := bytes.Index(data, []byte(`"workspaces"`)); wsIdx >= 0 {
318 rest := data[wsIdx:]
319 if bracketOpen := bytes.IndexByte(rest, '['); bracketOpen >= 0 {
320 if bracketClose := bytes.IndexByte(rest[bracketOpen:], ']'); bracketClose >= 0 {
321 pos := wsIdx + bracketOpen + bracketClose
322 arrayContent := bytes.TrimSpace(data[wsIdx+bracketOpen+1 : pos])
323 var insertion string
324 if len(arrayContent) == 0 {
325 insertion = "\n" + indent + indent + quoted + "\n" + indent
326 } else {
327 insertion = ",\n" + indent + indent + quoted + "\n" + indent
328 }
329 result := make([]byte, 0, len(data)+len(insertion))
330 result = append(result, data[:pos]...)
331 result = append(result, insertion...)
332 result = append(result, data[pos:]...)
333 return afero.WriteFile(fsys, packageJSONName, result, 0o666)
334 }
335 }
336 }
337
338 // We know a workspaces array exists but could not locate it reliably in the raw data.
339 return fmt.Errorf("npm pack: could not locate existing workspaces array for insertion")
340 }
341
342 // No workspaces key — add before closing brace.
343 lastBrace := bytes.LastIndexByte(data, '}')
344 if lastBrace < 0 {
345 return fmt.Errorf("npm pack: malformed package.json")
346 }
347
348 before := bytes.TrimRight(data[:lastBrace], " \t\n\r")
349 needComma := len(before) > 0 && before[len(before)-1] != '{' && before[len(before)-1] != ','
350
351 var insertion string
352 if needComma {
353 insertion = ",\n" + indent + `"workspaces": [` + "\n" + indent + indent + quoted + "\n" + indent + "]\n"
354 } else {
355 insertion = indent + `"workspaces": [` + "\n" + indent + indent + quoted + "\n" + indent + "]\n"
356 }
357
358 result := make([]byte, 0, len(data)+len(insertion))
359 result = append(result, before...)
360 result = append(result, insertion...)
361 result = append(result, data[lastBrace:]...)
362 return afero.WriteFile(fsys, packageJSONName, result, 0o666)
363 }
364
365 func detectIndent(data []byte) string {
366 for line := range bytes.SplitSeq(data, []byte("\n")) {
367 trimmed := bytes.TrimLeft(line, " \t")
368 if len(trimmed) < len(line) && len(trimmed) > 0 && trimmed[0] == '"' {
369 return string(line[:len(line)-len(trimmed)])
370 }
371 }
372 return " "
373 }
374
375 func writeJSON(fs afero.Fs, filename string, v any) error {
376 buf := new(bytes.Buffer)
377 encoder := json.NewEncoder(buf)
378 encoder.SetEscapeHTML(false)
379 encoder.SetIndent("", strings.Repeat(" ", 2))
380 if err := encoder.Encode(v); err != nil {
381 return fmt.Errorf("npm pack: failed to marshal JSON: %w", err)
382 }
383 return afero.WriteFile(fs, filename, buf.Bytes(), 0o666)
384 }
385
386 func toStringSlice(v any) []string {
387 if v == nil {
388 return nil
389 }
390 if s, ok := v.([]any); ok {
391 var out []string
392 for _, item := range s {
393 if str, ok := item.(string); ok {
394 out = append(out, str)
395 }
396 }
397 return out
398 }
399 return nil
400 }
401
402 // resolveProjectWorkspaces resolves workspace patterns from the project's
403 // package source, skipping the hugoautogen workspace.
404 func resolveProjectWorkspaces(sourceFs afero.Fs, workspacesSource map[string]any, skipPath string) []string {
405 if workspacesSource == nil {
406 return nil
407 }
408 var dirs []string
409 for _, ws := range toStringSlice(workspacesSource["workspaces"]) {
410 for _, wsDir := range modules.ResolveWorkspacePattern(sourceFs, "", ws) {
411 if filepath.ToSlash(wsDir) != skipPath {
412 dirs = append(dirs, wsDir)
413 }
414 }
415 }
416 return dirs
417 }
418
419 type packageBuilder struct {
420 err error
421
422 devDependencies map[string]any
423 devDependenciesComments map[string]any
424 dependencies map[string]any
425 dependenciesComments map[string]any
426 }
427
428 func (b *packageBuilder) Add(source string, r io.Reader) *packageBuilder {
429 if b.err != nil {
430 return b
431 }
432
433 m := b.unmarshal(r)
434 if b.err != nil {
435 return b
436 }
437
438 b.addm(source, m)
439
440 return b
441 }
442
443 func (b *packageBuilder) addm(source string, m map[string]any) {
444 if source == "" {
445 source = "project"
446 }
447
448 // First version for a given dependency wins.
449 // Packages added by order of import (project, module1, module2...),
450 // so the project has control over versions.
451 if devDeps, found := m[devDependenciesKey]; found {
452 mm := hmaps.ToStringMapString(devDeps)
453 for k, v := range mm {
454 if _, added := b.devDependencies[k]; !added {
455 b.devDependencies[k] = v
456 b.devDependenciesComments[k] = source
457 }
458 }
459 }
460
461 if deps, found := m[dependenciesKey]; found {
462 mm := hmaps.ToStringMapString(deps)
463 for k, v := range mm {
464 if _, added := b.dependencies[k]; !added {
465 b.dependencies[k] = v
466 b.dependenciesComments[k] = source
467 }
468 }
469 }
470 }
471
472 func (b *packageBuilder) unmarshal(r io.Reader) map[string]any {
473 m := make(map[string]any)
474 err := json.Unmarshal(helpers.ReaderToBytes(r), &m)
475 if err != nil {
476 b.err = err
477 }
478 return m
479 }
480
481 func (b *packageBuilder) Err() error {
482 return b.err
483 }
484
485 // buildSkipPackageJSON determines which modules should NOT have their package
486 // files processed. The project module is always skipped (handled separately).
487 // For other modules, the behavior is controlled by the UsePackageJSON import
488 // setting: "auto" (default) reads package files when a Hugo config file or
489 // package.hugo.json is present; "always" always reads; "never" never reads.
490 func buildSkipPackageJSON(mods modules.Modules) map[string]bool {
491 skip := make(map[string]bool)
492 for _, m := range mods {
493 if m.Owner() == nil {
494 skip[m.Path()] = true
495 continue
496 }
497 if !usePackageJSON(m) {
498 skip[m.Path()] = true
499 }
500 }
501 return skip
502 }
503
504 // usePackageJSON checks the import config for this module and applies the
505 // UsePackageJSON setting. For "auto", it checks for Hugo config files or
506 // package.hugo.json in the module root.
507 func usePackageJSON(m modules.Module) bool {
508 setting := findImportSetting(m)
509 switch setting {
510 case modules.UsePackageJSONAlways:
511 return true
512 case modules.UsePackageJSONNever:
513 return false
514 default:
515 // "auto": use if Hugo config file or package.hugo.json is present.
516 if len(m.ConfigFilenames()) > 0 {
517 return true
518 }
519 if m.Dir() != "" {
520 if _, err := os.Stat(filepath.Join(m.Dir(), files.FilenamePackageHugoJSON)); err == nil {
521 return true
522 }
523 }
524 return false
525 }
526 }
527
528 func findImportSetting(m modules.Module) string {
529 if m.Owner() == nil {
530 return modules.UsePackageJSONAuto
531 }
532 for _, imp := range m.Owner().Config().Imports {
533 if imp.Path == m.Path() {
534 if imp.UsePackageJSON != "" {
535 return imp.UsePackageJSON
536 }
537 return modules.UsePackageJSONAuto
538 }
539 }
540 return modules.UsePackageJSONAuto
541 }
542
543 type packageMeta struct {
544 // Sum is a hash of all package files that feed into the npm pack output.
545 Sum string `json:"sum"`
546
547 DependencySources dependencySources `json:"dependencySources"`
548 }
549
550 type dependencySources struct {
551 Dependencies map[string]any `json:"dependencies"`
552 DevDependencies map[string]any `json:"devDependencies"`
553 }
554
555 // PackageFilesSum hashes the package files that Pack would use,
556 // using the same file selection logic as Pack.
557 func PackageFilesSum(sourceFs afero.Fs, mods modules.Modules) string {
558 h := hashing.XxHasher()
559 defer h.Close()
560
561 var w io.Writer = h
562 if runtime.GOOS == "windows" {
563 w = &crlfReplacer{w: h}
564 }
565
566 copyFile := func(fsys afero.Fs, name string) {
567 f, err := fsys.Open(name)
568 if err != nil {
569 return
570 }
571 defer f.Close()
572 io.Copy(w, f)
573 }
574 copyOsFile := func(name string) {
575 f, err := os.Open(name)
576 if err != nil {
577 return
578 }
579 defer f.Close()
580 io.Copy(w, f)
581 }
582
583 // Project level: prefer package.hugo.json, fall back to package.json.
584 // We need to parse whichever file we pick to discover workspaces.
585 var workspacesSource map[string]any
586 if data, err := afero.ReadFile(sourceFs, files.FilenamePackageHugoJSON); err == nil {
587 w.Write(data)
588 var m map[string]any
589 if err := json.Unmarshal(data, &m); err == nil {
590 workspacesSource = m
591 }
592 } else if data, err := afero.ReadFile(sourceFs, packageJSONName); err == nil {
593 w.Write(data)
594 var m map[string]any
595 if err := json.Unmarshal(data, &m); err == nil {
596 workspacesSource = m
597 }
598 }
599
600 // Workspace package.json files (skipping hugoautogen).
601 workspacePath := filepath.ToSlash(files.FolderPackagesHugoAutoGen)
602 for _, wsDir := range resolveProjectWorkspaces(sourceFs, workspacesSource, workspacePath) {
603 copyFile(sourceFs, filepath.Join(wsDir, packageJSONName))
604 }
605
606 // Module package files: prefer package.hugo.json, fall back to package.json.
607 skip := buildSkipPackageJSON(mods)
608 modulesWithHugoJSON := make(map[string]bool)
609 for _, m := range mods {
610 if skip[m.Path()] || m.Dir() == "" {
611 continue
612 }
613 if _, err := os.Stat(filepath.Join(m.Dir(), files.FilenamePackageHugoJSON)); err == nil {
614 modulesWithHugoJSON[m.Path()] = true
615 }
616 }
617 for _, m := range mods {
618 if skip[m.Path()] || m.Dir() == "" {
619 continue
620 }
621 if modulesWithHugoJSON[m.Path()] {
622 copyOsFile(filepath.Join(m.Dir(), files.FilenamePackageHugoJSON))
623 } else {
624 copyOsFile(filepath.Join(m.Dir(), packageJSONName))
625 }
626 }
627
628 return fmt.Sprintf("%x", h.Sum64())
629 }
630
631 // crlfReplacer wraps a writer and strips \r bytes.
632 type crlfReplacer struct {
633 w io.Writer
634 }
635
636 func (c *crlfReplacer) Write(p []byte) (int, error) {
637 n := len(p)
638 _, err := c.w.Write(bytes.ReplaceAll(p, []byte("\r\n"), []byte("\n")))
639 return n, err
640 }
641
642 // NpmPackNeedsUpdate checks if the npm pack output is stale by comparing
643 // the stored hash against the current package files.
644 func NpmPackNeedsUpdate(sourceFs afero.Fs, mods modules.Modules) bool {
645 data, err := afero.ReadFile(sourceFs, workspacePackageMetaJSON)
646 if err != nil {
647 // No meta file means npm pack hasn't been run yet.
648 return false
649 }
650
651 // We only need the sum for this check.
652 meta := struct {
653 Sum string `json:"sum"`
654 }{}
655 if err := json.Unmarshal(data, &meta); err != nil || meta.Sum == "" {
656 return true
657 }
658 return meta.Sum != PackageFilesSum(sourceFs, mods)
659 }