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 name := "project"
199 rfi, err := sourceFs.Stat("")
200 if err == nil {
201 name = rfi.Name()
202 }
203
204 autoGenPkg := map[string]any{
205 "name": name,
206 "version": "0.1.0",
207 dependenciesKey: moduleDeps,
208 devDependenciesKey: moduleDevDeps,
209 }
210
211 if err := sourceFs.MkdirAll(files.FolderPackagesHugoAutoGen, 0o777); err != nil {
212 return err
213 }
214 if err := writeJSON(sourceFs, workspacePackageJSON, autoGenPkg); err != nil {
215 return err
216 }
217
218 // 5. Ensure root package.json references the workspace.
219 if err := ensureWorkspaceRef(sourceFs, workspacePath); err != nil {
220 return err
221 }
222
223 // 6. Write metadata for the final on-disk package state.
224 metaFile := packageMeta{
225 Sum: PackageFilesSum(sourceFs, mods),
226 DependencySources: dependencySources{
227 Dependencies: moduleDepsComments,
228 DevDependencies: moduleDevDepsComments,
229 },
230 }
231 return writeJSON(sourceFs, workspacePackageMetaJSON, metaFile)
232 }
233
234 // ensureWorkspaceRef adds workspacePath to the "workspaces" array in root
235 // package.json with minimal formatting changes.
236 func ensureWorkspaceRef(fsys afero.Fs, workspacePath string) error {
237 data, err := afero.ReadFile(fsys, packageJSONName)
238 if err != nil {
239 content := fmt.Sprintf("{\n \"workspaces\": [\n %q\n ]\n}\n", workspacePath)
240 return afero.WriteFile(fsys, packageJSONName, []byte(content), 0o666)
241 }
242
243 if runtime.GOOS == "windows" {
244 data = bytes.ReplaceAll(data, []byte("\r\n"), []byte("\n"))
245 }
246
247 // Parse to check if already present.
248 var pkg map[string]any
249 if err := json.Unmarshal(data, &pkg); err != nil {
250 return fmt.Errorf("npm pack: failed to parse package.json: %w", err)
251 }
252
253 indent := detectIndent(data)
254 quoted := fmt.Sprintf("%q", workspacePath)
255
256 wsVal, hasWS := pkg["workspaces"]
257
258 switch v := wsVal.(type) {
259 case []any:
260 // Array form: ["pkg-a", "pkg-b", ...]
261 if slices.Contains(toStringSlice(v), workspacePath) {
262 if runtime.GOOS == "windows" {
263 return afero.WriteFile(fsys, packageJSONName, data, 0o666)
264 }
265 return nil
266 }
267 // Fall through to byte-based insertion into the existing array below.
268 case map[string]any:
269 // Object form: { "workspaces": { "packages": [...] } }
270 packagesVal, ok := v["packages"]
271 if !ok {
272 return fmt.Errorf("npm pack: unsupported workspaces object; missing \"packages\" field")
273 }
274 packagesSlice := toStringSlice(packagesVal)
275 if slices.Contains(packagesSlice, workspacePath) {
276 if runtime.GOOS == "windows" {
277 return afero.WriteFile(fsys, packageJSONName, data, 0o666)
278 }
279 return nil
280 }
281
282 // Append the new workspace path to the packages slice.
283 newPkgs := make([]any, 0, len(packagesSlice)+1)
284 for _, s := range packagesSlice {
285 newPkgs = append(newPkgs, s)
286 }
287 newPkgs = append(newPkgs, workspacePath)
288 v["packages"] = newPkgs
289
290 updated, err := json.MarshalIndent(pkg, "", indent)
291 if err != nil {
292 return fmt.Errorf("npm pack: failed to marshal package.json with updated workspaces: %w", err)
293 }
294 updated = append(updated, '\n')
295 return afero.WriteFile(fsys, packageJSONName, updated, 0o666)
296 case nil:
297 // Treat explicit null as "no workspaces"; handled below as missing key.
298 default:
299 return fmt.Errorf("npm pack: unsupported workspaces type %T", v)
300 }
301
302 // Try adding to existing workspaces array when present.
303 if hasWS && wsVal != nil {
304 if wsIdx := bytes.Index(data, []byte(`"workspaces"`)); wsIdx >= 0 {
305 rest := data[wsIdx:]
306 if bracketOpen := bytes.IndexByte(rest, '['); bracketOpen >= 0 {
307 if bracketClose := bytes.IndexByte(rest[bracketOpen:], ']'); bracketClose >= 0 {
308 pos := wsIdx + bracketOpen + bracketClose
309 arrayContent := bytes.TrimSpace(data[wsIdx+bracketOpen+1 : pos])
310 var insertion string
311 if len(arrayContent) == 0 {
312 insertion = "\n" + indent + indent + quoted + "\n" + indent
313 } else {
314 insertion = ",\n" + indent + indent + quoted + "\n" + indent
315 }
316 result := make([]byte, 0, len(data)+len(insertion))
317 result = append(result, data[:pos]...)
318 result = append(result, insertion...)
319 result = append(result, data[pos:]...)
320 return afero.WriteFile(fsys, packageJSONName, result, 0o666)
321 }
322 }
323 }
324
325 // We know a workspaces array exists but could not locate it reliably in the raw data.
326 return fmt.Errorf("npm pack: could not locate existing workspaces array for insertion")
327 }
328
329 // No workspaces key — add before closing brace.
330 lastBrace := bytes.LastIndexByte(data, '}')
331 if lastBrace < 0 {
332 return fmt.Errorf("npm pack: malformed package.json")
333 }
334
335 before := bytes.TrimRight(data[:lastBrace], " \t\n\r")
336 needComma := len(before) > 0 && before[len(before)-1] != '{' && before[len(before)-1] != ','
337
338 var insertion string
339 if needComma {
340 insertion = ",\n" + indent + `"workspaces": [` + "\n" + indent + indent + quoted + "\n" + indent + "]\n"
341 } else {
342 insertion = indent + `"workspaces": [` + "\n" + indent + indent + quoted + "\n" + indent + "]\n"
343 }
344
345 result := make([]byte, 0, len(data)+len(insertion))
346 result = append(result, before...)
347 result = append(result, insertion...)
348 result = append(result, data[lastBrace:]...)
349 return afero.WriteFile(fsys, packageJSONName, result, 0o666)
350 }
351
352 func detectIndent(data []byte) string {
353 for line := range bytes.SplitSeq(data, []byte("\n")) {
354 trimmed := bytes.TrimLeft(line, " \t")
355 if len(trimmed) < len(line) && len(trimmed) > 0 && trimmed[0] == '"' {
356 return string(line[:len(line)-len(trimmed)])
357 }
358 }
359 return " "
360 }
361
362 func writeJSON(fs afero.Fs, filename string, v any) error {
363 buf := new(bytes.Buffer)
364 encoder := json.NewEncoder(buf)
365 encoder.SetEscapeHTML(false)
366 encoder.SetIndent("", strings.Repeat(" ", 2))
367 if err := encoder.Encode(v); err != nil {
368 return fmt.Errorf("npm pack: failed to marshal JSON: %w", err)
369 }
370 return afero.WriteFile(fs, filename, buf.Bytes(), 0o666)
371 }
372
373 func toStringSlice(v any) []string {
374 if v == nil {
375 return nil
376 }
377 if s, ok := v.([]any); ok {
378 var out []string
379 for _, item := range s {
380 if str, ok := item.(string); ok {
381 out = append(out, str)
382 }
383 }
384 return out
385 }
386 return nil
387 }
388
389 // resolveProjectWorkspaces resolves workspace patterns from the project's
390 // package source, skipping the hugoautogen workspace.
391 func resolveProjectWorkspaces(sourceFs afero.Fs, workspacesSource map[string]any, skipPath string) []string {
392 if workspacesSource == nil {
393 return nil
394 }
395 var dirs []string
396 for _, ws := range toStringSlice(workspacesSource["workspaces"]) {
397 for _, wsDir := range modules.ResolveWorkspacePattern(sourceFs, "", ws) {
398 if filepath.ToSlash(wsDir) != skipPath {
399 dirs = append(dirs, wsDir)
400 }
401 }
402 }
403 return dirs
404 }
405
406 type packageBuilder struct {
407 err error
408
409 devDependencies map[string]any
410 devDependenciesComments map[string]any
411 dependencies map[string]any
412 dependenciesComments map[string]any
413 }
414
415 func (b *packageBuilder) Add(source string, r io.Reader) *packageBuilder {
416 if b.err != nil {
417 return b
418 }
419
420 m := b.unmarshal(r)
421 if b.err != nil {
422 return b
423 }
424
425 b.addm(source, m)
426
427 return b
428 }
429
430 func (b *packageBuilder) addm(source string, m map[string]any) {
431 if source == "" {
432 source = "project"
433 }
434
435 // First version for a given dependency wins.
436 // Packages added by order of import (project, module1, module2...),
437 // so the project has control over versions.
438 if devDeps, found := m[devDependenciesKey]; found {
439 mm := hmaps.ToStringMapString(devDeps)
440 for k, v := range mm {
441 if _, added := b.devDependencies[k]; !added {
442 b.devDependencies[k] = v
443 b.devDependenciesComments[k] = source
444 }
445 }
446 }
447
448 if deps, found := m[dependenciesKey]; found {
449 mm := hmaps.ToStringMapString(deps)
450 for k, v := range mm {
451 if _, added := b.dependencies[k]; !added {
452 b.dependencies[k] = v
453 b.dependenciesComments[k] = source
454 }
455 }
456 }
457 }
458
459 func (b *packageBuilder) unmarshal(r io.Reader) map[string]any {
460 m := make(map[string]any)
461 err := json.Unmarshal(helpers.ReaderToBytes(r), &m)
462 if err != nil {
463 b.err = err
464 }
465 return m
466 }
467
468 func (b *packageBuilder) Err() error {
469 return b.err
470 }
471
472 // buildSkipPackageJSON determines which modules should NOT have their package
473 // files processed. The project module is always skipped (handled separately).
474 // For other modules, the behavior is controlled by the UsePackageJSON import
475 // setting: "auto" (default) reads package files when a Hugo config file or
476 // package.hugo.json is present; "always" always reads; "never" never reads.
477 func buildSkipPackageJSON(mods modules.Modules) map[string]bool {
478 skip := make(map[string]bool)
479 for _, m := range mods {
480 if m.Owner() == nil {
481 skip[m.Path()] = true
482 continue
483 }
484 if !usePackageJSON(m) {
485 skip[m.Path()] = true
486 }
487 }
488 return skip
489 }
490
491 // usePackageJSON checks the import config for this module and applies the
492 // UsePackageJSON setting. For "auto", it checks for Hugo config files or
493 // package.hugo.json in the module root.
494 func usePackageJSON(m modules.Module) bool {
495 setting := findImportSetting(m)
496 switch setting {
497 case modules.UsePackageJSONAlways:
498 return true
499 case modules.UsePackageJSONNever:
500 return false
501 default:
502 // "auto": use if Hugo config file or package.hugo.json is present.
503 if len(m.ConfigFilenames()) > 0 {
504 return true
505 }
506 if m.Dir() != "" {
507 if _, err := os.Stat(filepath.Join(m.Dir(), files.FilenamePackageHugoJSON)); err == nil {
508 return true
509 }
510 }
511 return false
512 }
513 }
514
515 func findImportSetting(m modules.Module) string {
516 if m.Owner() == nil {
517 return modules.UsePackageJSONAuto
518 }
519 for _, imp := range m.Owner().Config().Imports {
520 if imp.Path == m.Path() {
521 if imp.UsePackageJSON != "" {
522 return imp.UsePackageJSON
523 }
524 return modules.UsePackageJSONAuto
525 }
526 }
527 return modules.UsePackageJSONAuto
528 }
529
530 type packageMeta struct {
531 // Sum is a hash of all package files that feed into the npm pack output.
532 Sum string `json:"sum"`
533
534 DependencySources dependencySources `json:"dependencySources"`
535 }
536
537 type dependencySources struct {
538 Dependencies map[string]any `json:"dependencies"`
539 DevDependencies map[string]any `json:"devDependencies"`
540 }
541
542 // PackageFilesSum hashes the package files that Pack would use,
543 // using the same file selection logic as Pack.
544 func PackageFilesSum(sourceFs afero.Fs, mods modules.Modules) string {
545 h := hashing.XxHasher()
546 defer h.Close()
547
548 var w io.Writer = h
549 if runtime.GOOS == "windows" {
550 w = &crlfReplacer{w: h}
551 }
552
553 copyFile := func(fsys afero.Fs, name string) {
554 f, err := fsys.Open(name)
555 if err != nil {
556 return
557 }
558 defer f.Close()
559 io.Copy(w, f)
560 }
561 copyOsFile := func(name string) {
562 f, err := os.Open(name)
563 if err != nil {
564 return
565 }
566 defer f.Close()
567 io.Copy(w, f)
568 }
569
570 // Project level: prefer package.hugo.json, fall back to package.json.
571 // We need to parse whichever file we pick to discover workspaces.
572 var workspacesSource map[string]any
573 if data, err := afero.ReadFile(sourceFs, files.FilenamePackageHugoJSON); err == nil {
574 w.Write(data)
575 var m map[string]any
576 if err := json.Unmarshal(data, &m); err == nil {
577 workspacesSource = m
578 }
579 } else if data, err := afero.ReadFile(sourceFs, packageJSONName); err == nil {
580 w.Write(data)
581 var m map[string]any
582 if err := json.Unmarshal(data, &m); err == nil {
583 workspacesSource = m
584 }
585 }
586
587 // Workspace package.json files (skipping hugoautogen).
588 workspacePath := filepath.ToSlash(files.FolderPackagesHugoAutoGen)
589 for _, wsDir := range resolveProjectWorkspaces(sourceFs, workspacesSource, workspacePath) {
590 copyFile(sourceFs, filepath.Join(wsDir, packageJSONName))
591 }
592
593 // Module package files: prefer package.hugo.json, fall back to package.json.
594 skip := buildSkipPackageJSON(mods)
595 modulesWithHugoJSON := make(map[string]bool)
596 for _, m := range mods {
597 if skip[m.Path()] || m.Dir() == "" {
598 continue
599 }
600 if _, err := os.Stat(filepath.Join(m.Dir(), files.FilenamePackageHugoJSON)); err == nil {
601 modulesWithHugoJSON[m.Path()] = true
602 }
603 }
604 for _, m := range mods {
605 if skip[m.Path()] || m.Dir() == "" {
606 continue
607 }
608 if modulesWithHugoJSON[m.Path()] {
609 copyOsFile(filepath.Join(m.Dir(), files.FilenamePackageHugoJSON))
610 } else {
611 copyOsFile(filepath.Join(m.Dir(), packageJSONName))
612 }
613 }
614
615 return fmt.Sprintf("%x", h.Sum64())
616 }
617
618 // crlfReplacer wraps a writer and strips \r bytes.
619 type crlfReplacer struct {
620 w io.Writer
621 }
622
623 func (c *crlfReplacer) Write(p []byte) (int, error) {
624 n := len(p)
625 _, err := c.w.Write(bytes.ReplaceAll(p, []byte("\r\n"), []byte("\n")))
626 return n, err
627 }
628
629 // NpmPackNeedsUpdate checks if the npm pack output is stale by comparing
630 // the stored hash against the current package files.
631 func NpmPackNeedsUpdate(sourceFs afero.Fs, mods modules.Modules) bool {
632 data, err := afero.ReadFile(sourceFs, workspacePackageMetaJSON)
633 if err != nil {
634 // No meta file means npm pack hasn't been run yet.
635 return false
636 }
637
638 // We only need the sum for this check.
639 meta := struct {
640 Sum string `json:"sum"`
641 }{}
642 if err := json.Unmarshal(data, &meta); err != nil || meta.Sum == "" {
643 return true
644 }
645 return meta.Sum != PackageFilesSum(sourceFs, mods)
646 }