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