/
nodejs.go
726 lines (657 loc) · 20.7 KB
/
nodejs.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
// Package nodejs provides backends for Node.js using Yarn, PNPM and NPM.
package nodejs
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/url"
"os"
"os/exec"
"regexp"
"strings"
"github.com/hashicorp/go-version"
"github.com/replit/upm/internal/api"
"github.com/replit/upm/internal/nix"
"github.com/replit/upm/internal/util"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer"
"gopkg.in/yaml.v2"
)
// npmSearchResults represents the data we get from the NPM API when
// doing a search.
//
// See https://github.com/npm/registry/blob/5db1bb329f554454467531a3e1bae5e97da160df/docs/REGISTRY-API.md
// for documentation on the format.
type npmSearchResults struct {
Objects []struct {
Package struct {
Name string `json:"name"`
Version string `json:"version"`
Description string `json:"description"`
Links struct {
Homepage string `json:"homepage"`
Repository string `json:"repository"`
Bugs string `json:"bugs"`
} `json:"links"`
Author struct {
Username string `json:"username"`
Email string `json:"email"`
} `json:"author"`
} `json:"package"`
} `json:"objects"`
}
// npmInfoResult represents the data we get from the NPM API when
// doing a single package lookup.
//
// See https://github.com/npm/registry/blob/5db1bb329f554454467531a3e1bae5e97da160df/docs/responses/package-metadata.md
// for documentation on the format.
//
// ---
//
// note: the format isn't 100% validated to the type that's described in the link above.
// > Historically no validation has been performed on those fields; they are generated by parsing
// > user-provided data in package.json at publication time.
//
// which means that we have to deserialize the union of the type described in the document, and the
// type of a package.json file: https://docs.npmjs.com/cli/v10/configuring-npm/package-json
type npmInfoResult struct {
Name string `json:"name"`
Versions map[string]interface{} `json:"versions"`
Author packageJsonPerson `json:"author"`
Bugs packageJsonBugs `json:"bugs"`
Description string `json:"description"`
Homepage string `json:"homepage"`
License string `json:"license"`
Repository packageJsonRepository `json:"repository"`
}
type packageJsonRepository struct {
URL string
}
func (repo *packageJsonRepository) UnmarshalJSON(data []byte) error {
var str string
if err := json.Unmarshal(data, &str); err == nil {
repo.URL = str
return nil
}
var obj map[string]interface{}
if err := json.Unmarshal(data, &obj); err == nil {
if url, ok := obj["url"].(string); ok {
repo.URL = url
}
return nil
}
return fmt.Errorf("expected repository in package.json to be a string or an object")
}
type packageJsonPerson struct {
Name string
Email string
URL string
}
var packageJsonPersonStringRegexp *regexp.Regexp
func (person *packageJsonPerson) UnmarshalJSON(data []byte) error {
var str string
if err := json.Unmarshal(data, &str); err == nil {
if packageJsonPersonStringRegexp == nil {
// parses the form: name <email> (url)
// eg: John Doe <joe.dohn@example.zip> (ftp://C:\Nix\Store)
// any of the 3 are optional
packageJsonPersonStringRegexp = regexp.MustCompile(`([^\<\(]*)?\s*(\<.*\>)?\s*(\(.*\))?`)
}
captures := packageJsonPersonStringRegexp.FindStringSubmatch(str)
if len(captures) == 4 {
if name := captures[1]; name != "" {
person.Name = name
}
if email := captures[2]; email != "" {
person.Email = email
}
if url := captures[3]; url != "" {
person.URL = url
}
return nil
}
// in case the regex fails to parse
person.URL = str
return nil
}
var obj map[string]interface{}
if err := json.Unmarshal(data, &obj); err == nil {
if name, ok := obj["name"].(string); ok {
person.Name = name
}
if email, ok := obj["email"].(string); ok {
person.Email = email
}
if url, ok := obj["url"].(string); ok {
person.URL = url
}
return nil
}
return errors.New("expected person in package.json to be a string or an object")
}
type packageJsonBugs struct {
URL string
}
func (bugs *packageJsonBugs) UnmarshalJSON(data []byte) error {
var str string
if err := json.Unmarshal(data, &str); err == nil {
bugs.URL = str
return nil
}
var obj map[string]interface{}
if err := json.Unmarshal(data, &obj); err == nil {
if url, ok := obj["url"].(string); ok {
bugs.URL = url
}
return nil
}
return errors.New("expected bugs in package.json to be a string or an object")
}
// packageJSON represents the relevant data in a package.json file.
type packageJSON struct {
Dependencies map[string]string `json:"dependencies"`
DevDependencies map[string]string `json:"devDependencies"`
}
// packageLockJSON represents the relevant data in a package-lock.json
// file.
type packageLockJSON struct {
LockfileVersion int `json:"lockfileVersion"`
Dependencies map[string]struct {
Version string `json:"version"`
} `json:"dependencies"`
Packages map[string]struct {
Version string `json:"version"`
} `json:"packages"`
}
// nodejsPatterns is the FilenamePatterns value for NodejsBackend.
var nodejsPatterns = []string{"*.js", "*.ts", "*.jsx", "*.tsx", "*.mjs", "*.cjs"}
func bunIsAvailable() bool {
_, err := exec.LookPath("bun")
return err == nil
}
func pnpmIsAvailable() bool {
_, err := exec.LookPath("pnpm")
return err == nil
}
func yarnIsAvailable() bool {
_, err := exec.LookPath("yarn")
return err == nil
}
func npmIsAvailable() bool {
_, err := exec.LookPath("npm")
return err == nil
}
// nodejsSearch implements Search for nodejs-yarn, nodejs-pnpm and nodejs-npm.
func nodejsSearch(query string) []api.PkgInfo {
// Special case: if search query is only one character, the
// API doesn't return any results. The web interface to NPM
// deals with this by just jumping to the package with that
// exact name, or returning a 404 if there isn't one. Let's
// try to do something similar.
if len(query) == 1 {
info := nodejsInfo(api.PkgName(query))
if info.Name != "" {
return []api.PkgInfo{info}
} else {
return []api.PkgInfo{}
}
}
endpoint := "https://registry.npmjs.org/-/v1/search"
queryParams := "?text=" + url.QueryEscape(query)
resp, err := api.HttpClient.Get(endpoint + queryParams)
if err != nil {
util.DieNetwork("NPM registry: %s", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
util.DieProtocol("NPM registry: %s", err)
}
var npmResults npmSearchResults
if err := json.Unmarshal(body, &npmResults); err != nil {
util.DieProtocol("NPM registry: %s", err)
}
results := make([]api.PkgInfo, len(npmResults.Objects))
for i := range npmResults.Objects {
p := npmResults.Objects[i].Package
results[i] = api.PkgInfo{
Name: p.Name,
Description: p.Description,
Version: p.Version,
HomepageURL: p.Links.Homepage,
SourceCodeURL: p.Links.Repository,
BugTrackerURL: p.Links.Bugs,
Author: util.AuthorInfo{
Name: p.Author.Username,
Email: p.Author.Email,
}.String(),
}
}
return results
}
// nodejsInfo implements Info for nodejs-yarn, nodejs-pnpm and nodejs-npm.
func nodejsInfo(name api.PkgName) api.PkgInfo {
endpoint := "https://registry.npmjs.org"
path := "/" + url.QueryEscape(string(name))
resp, err := api.HttpClient.Get(endpoint + path)
if err != nil {
util.DieNetwork("NPM registry: %s", err)
}
defer resp.Body.Close()
switch resp.StatusCode {
case 200:
break
case 404:
return api.PkgInfo{}
default:
util.DieNetwork("NPM registry: HTTP status %d", resp.StatusCode)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
util.DieProtocol("NPM registry: could not read response: %s", err)
}
var npmInfo npmInfoResult
if err := json.Unmarshal(body, &npmInfo); err != nil {
util.DieProtocol("NPM registry: %s", err)
}
lastVersionStr := ""
if len(npmInfo.Versions) > 0 {
var lastVersion *version.Version = nil
for versionStr := range npmInfo.Versions {
version, err := version.NewVersion(versionStr)
if err != nil {
continue
}
if version.Prerelease() != "" {
continue
}
if lastVersion == nil || version.GreaterThan(lastVersion) {
lastVersion = version
}
}
if lastVersion != nil {
lastVersionStr = lastVersion.String()
}
}
return api.PkgInfo{
Name: npmInfo.Name,
Description: npmInfo.Description,
Version: lastVersionStr,
HomepageURL: npmInfo.Homepage,
SourceCodeURL: npmInfo.Repository.URL,
BugTrackerURL: npmInfo.Bugs.URL,
Author: util.AuthorInfo{
Name: npmInfo.Author.Name,
Email: npmInfo.Author.Email,
URL: npmInfo.Author.URL,
}.String(),
License: npmInfo.License,
}
}
// nodejsListSpecfile implements ListSpecfile for nodejs-yarn, nodejs-pnpm and
// nodejs-npm.
func nodejsListSpecfile(mergeAllGroups bool) map[api.PkgName]api.PkgSpec {
contentsB, err := os.ReadFile("package.json")
if err != nil {
util.DieIO("package.json: %s", err)
}
var cfg packageJSON
if err := json.Unmarshal(contentsB, &cfg); err != nil {
util.DieProtocol("package.json: %s", err)
}
pkgs := map[api.PkgName]api.PkgSpec{}
for nameStr, specStr := range cfg.Dependencies {
pkgs[api.PkgName(nameStr)] = api.PkgSpec(specStr)
}
for nameStr, specStr := range cfg.DevDependencies {
pkgs[api.PkgName(nameStr)] = api.PkgSpec(specStr)
}
return pkgs
}
// nodejsGuessRegexps is the value of GuessRegexps for nodejs-yarn, nodejs-pnpm and
// nodejs-npm.
var nodejsGuessRegexps = util.Regexps([]string{
// import defaultExport from "module-name";
// import * as name from "module-name";
// import { export } from "module-name";
`(?m)from\s*['"]([^'"]+)['"]\s*;?\s*$`,
// import "module-name";
`(?m)import\s*['"]([^'"]+)['"]\s*;?\s*$`,
// const mod = import("module-name")
// const mod = require("module-name")
`(?m)(?:require|import)\s*\(\s*['"]([^'"{}]+)['"]\s*\)`,
})
var nodeIgnorePathSegments = map[string]bool{
"node_modules": true,
}
var jsPathGlobs = []string{
"*.js",
"*.jsx",
"*.mjs",
"*.cjs",
}
var tsPathGlobs = []string{
"*.ts",
}
var tsxPathGlobs = []string{
"*.tsx",
}
// NodejsYarnBackend is a UPM backend for Node.js that uses [Yarn](https://yarnpkg.com/).
var NodejsYarnBackend = api.LanguageBackend{
Name: "nodejs-yarn",
Specfile: "package.json",
Lockfile: "yarn.lock",
IsAvailable: yarnIsAvailable,
FilenamePatterns: nodejsPatterns,
Quirks: api.QuirksAddRemoveAlsoLocks |
api.QuirksAddRemoveAlsoInstalls |
api.QuirksLockAlsoInstalls |
api.QuirkRemoveNeedsLockfile,
GetPackageDir: func() string {
return "node_modules"
},
Search: nodejsSearch,
Info: nodejsInfo,
Add: func(ctx context.Context, pkgs map[api.PkgName]api.PkgSpec, projectName string) {
//nolint:ineffassign,wastedassign,staticcheck
span, ctx := tracer.StartSpanFromContext(ctx, "yarn (init) add")
defer span.Finish()
if !util.Exists("package.json") {
util.RunCmd([]string{"yarn", "init", "-y"})
}
cmd := []string{"yarn", "add"}
for name, spec := range pkgs {
arg := string(name)
if spec != "" {
arg += "@" + string(spec)
}
cmd = append(cmd, arg)
}
util.RunCmd(cmd)
},
Remove: func(ctx context.Context, pkgs map[api.PkgName]bool) {
//nolint:ineffassign,wastedassign,staticcheck
span, ctx := tracer.StartSpanFromContext(ctx, "yarn remove")
defer span.Finish()
cmd := []string{"yarn", "remove"}
for name := range pkgs {
cmd = append(cmd, string(name))
}
util.RunCmd(cmd)
},
Lock: func(ctx context.Context) {
//nolint:ineffassign,wastedassign,staticcheck
span, ctx := tracer.StartSpanFromContext(ctx, "yarn install")
defer span.Finish()
util.RunCmd([]string{"yarn", "install"})
},
Install: func(ctx context.Context) {
//nolint:ineffassign,wastedassign,staticcheck
span, ctx := tracer.StartSpanFromContext(ctx, "yarn install")
defer span.Finish()
util.RunCmd([]string{"yarn", "install"})
},
ListSpecfile: nodejsListSpecfile,
ListLockfile: func() map[api.PkgName]api.PkgVersion {
contentsB, err := os.ReadFile("yarn.lock")
if err != nil {
util.DieIO("yarn.lock: %s", err)
}
contents := string(contentsB)
r := regexp.MustCompile(`(?m)^"?((?:@[^@ \n]+\/)?[^@ \n]+).+:\n version "(.+)"$`)
pkgs := map[api.PkgName]api.PkgVersion{}
for _, match := range r.FindAllStringSubmatch(contents, -1) {
name := api.PkgName(match[1])
version := api.PkgVersion(match[2])
pkgs[name] = version
}
return pkgs
},
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
GuessRegexps: nodejsGuessRegexps,
Guess: nodejsGuess,
InstallReplitNixSystemDependencies: nix.DefaultInstallReplitNixSystemDependencies,
}
// NodejsPNPMBackend is a UPM backend for Node.js that uses [pnpm](https://pnpm.io/).
var NodejsPNPMBackend = api.LanguageBackend{
Name: "nodejs-pnpm",
Specfile: "package.json",
Lockfile: "pnpm-lock.yaml",
IsAvailable: pnpmIsAvailable,
FilenamePatterns: nodejsPatterns,
Quirks: api.QuirksAddRemoveAlsoLocks |
api.QuirksAddRemoveAlsoInstalls |
api.QuirksLockAlsoInstalls,
GetPackageDir: func() string {
return "node_modules"
},
Search: nodejsSearch,
Info: nodejsInfo,
Add: func(ctx context.Context, pkgs map[api.PkgName]api.PkgSpec, projectName string) {
//nolint:ineffassign,wastedassign,staticcheck
span, ctx := tracer.StartSpanFromContext(ctx, "pnpm (init) add")
defer span.Finish()
if !util.Exists("package.json") {
util.RunCmd([]string{"pnpm", "init"})
}
cmd := []string{"pnpm", "add"}
for name, spec := range pkgs {
arg := string(name)
if spec != "" {
arg += "@" + string(spec)
}
cmd = append(cmd, arg)
}
util.RunCmd(cmd)
},
Remove: func(ctx context.Context, pkgs map[api.PkgName]bool) {
//nolint:ineffassign,wastedassign,staticcheck
span, ctx := tracer.StartSpanFromContext(ctx, "pnpm remove")
defer span.Finish()
cmd := []string{"pnpm", "remove"}
for name := range pkgs {
cmd = append(cmd, string(name))
}
util.RunCmd(cmd)
},
Lock: func(ctx context.Context) {
//nolint:ineffassign,wastedassign,staticcheck
span, ctx := tracer.StartSpanFromContext(ctx, "pnpm install")
defer span.Finish()
util.RunCmd([]string{"pnpm", "install"})
},
Install: func(ctx context.Context) {
//nolint:ineffassign,wastedassign,staticcheck
span, ctx := tracer.StartSpanFromContext(ctx, "pnpm install")
defer span.Finish()
util.RunCmd([]string{"pnpm", "install"})
},
ListSpecfile: nodejsListSpecfile,
ListLockfile: func() map[api.PkgName]api.PkgVersion {
lockfileBytes, err := os.ReadFile("pnpm-lock.yaml")
if err != nil {
util.DieIO("pnpm-lock.yaml: %s", err)
}
lockfile := map[string]interface{}{}
err = yaml.Unmarshal(lockfileBytes, &lockfile)
if err != nil {
util.DieProtocol("pnpm-lock.yaml: %s", err)
}
lockfileVersion := strings.Split(lockfile["lockfileVersion"].(string), ".")
lvMajor := lockfileVersion[0]
pkgs := map[api.PkgName]api.PkgVersion{}
switch lvMajor {
case "6":
dependencies, ok := lockfile["dependencies"]
if !ok {
return pkgs
}
for pkgName, pkgInfo := range dependencies.(map[interface{}]interface{}) {
pkgs[api.PkgName(pkgName.(string))] = api.PkgVersion(pkgInfo.(map[interface{}]interface{})["version"].(string))
}
default:
util.DieInitializationError("pnpm-lock.yaml: unsupported lockfile version %s", lockfileVersion)
}
return pkgs
},
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
GuessRegexps: nodejsGuessRegexps,
Guess: nodejsGuess,
InstallReplitNixSystemDependencies: nix.DefaultInstallReplitNixSystemDependencies,
}
// NodejsNPMBackend is a UPM backend for Node.js that uses [NPM](https://npmjs.com/).
var NodejsNPMBackend = api.LanguageBackend{
Name: "nodejs-npm",
Specfile: "package.json",
Lockfile: "package-lock.json",
IsAvailable: npmIsAvailable,
FilenamePatterns: nodejsPatterns,
Quirks: api.QuirksAddRemoveAlsoLocks |
api.QuirksAddRemoveAlsoInstalls |
api.QuirksLockAlsoInstalls,
GetPackageDir: func() string {
return "node_modules"
},
Search: nodejsSearch,
Info: nodejsInfo,
Add: func(ctx context.Context, pkgs map[api.PkgName]api.PkgSpec, projectName string) {
//nolint:ineffassign,wastedassign,staticcheck
span, ctx := tracer.StartSpanFromContext(ctx, "npm (init) install")
defer span.Finish()
if !util.Exists("package.json") {
util.RunCmd([]string{"npm", "init", "-y"})
}
cmd := []string{"npm", "install"}
for name, spec := range pkgs {
arg := string(name)
if spec != "" {
arg += "@" + string(spec)
}
cmd = append(cmd, arg)
}
util.RunCmd(cmd)
},
Remove: func(ctx context.Context, pkgs map[api.PkgName]bool) {
//nolint:ineffassign,wastedassign,staticcheck
span, ctx := tracer.StartSpanFromContext(ctx, "npm uninstall")
defer span.Finish()
cmd := []string{"npm", "uninstall"}
for name := range pkgs {
cmd = append(cmd, string(name))
}
util.RunCmd(cmd)
},
Lock: func(ctx context.Context) {
//nolint:ineffassign,wastedassign,staticcheck
span, ctx := tracer.StartSpanFromContext(ctx, "npm install")
defer span.Finish()
util.RunCmd([]string{"npm", "install"})
},
Install: func(ctx context.Context) {
//nolint:ineffassign,wastedassign,staticcheck
span, ctx := tracer.StartSpanFromContext(ctx, "npm ci")
defer span.Finish()
util.RunCmd([]string{"npm", "ci"})
},
ListSpecfile: nodejsListSpecfile,
ListLockfile: func() map[api.PkgName]api.PkgVersion {
contentsB, err := os.ReadFile("package-lock.json")
if err != nil {
util.DieIO("package-lock.json: %s", err)
}
var cfg packageLockJSON
if err := json.Unmarshal(contentsB, &cfg); err != nil {
util.DieProtocol("package-lock.json: %s", err)
}
pkgs := map[api.PkgName]api.PkgVersion{}
if cfg.LockfileVersion <= 2 {
for nameStr, data := range cfg.Dependencies {
pkgs[api.PkgName(nameStr)] = api.PkgVersion(data.Version)
}
} else {
for pathStr, data := range cfg.Packages {
nameStr := strings.TrimPrefix(pathStr, "node_modules/")
pkgs[api.PkgName(nameStr)] = api.PkgVersion(data.Version)
}
}
return pkgs
},
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
GuessRegexps: nodejsGuessRegexps,
Guess: nodejsGuess,
InstallReplitNixSystemDependencies: nix.DefaultInstallReplitNixSystemDependencies,
}
// BunBackend is a UPM backend for Node.js that uses [Bun](https://bun.sh/).
var BunBackend = api.LanguageBackend{
Name: "bun",
Specfile: "package.json",
Lockfile: "bun.lockb",
IsAvailable: bunIsAvailable,
FilenamePatterns: nodejsPatterns,
Quirks: api.QuirksAddRemoveAlsoLocks |
api.QuirksAddRemoveAlsoInstalls |
api.QuirksLockAlsoInstalls,
GetPackageDir: func() string {
return "node_modules"
},
Search: nodejsSearch,
Info: nodejsInfo,
Add: func(ctx context.Context, pkgs map[api.PkgName]api.PkgSpec, projectName string) {
//nolint:ineffassign,wastedassign,staticcheck
span, ctx := tracer.StartSpanFromContext(ctx, "bun (init) add")
defer span.Finish()
if !util.Exists("package.json") {
util.RunCmd([]string{"bun", "init", "-y"})
}
cmd := []string{"bun", "add"}
for name, spec := range pkgs {
arg := string(name)
if spec != "" {
arg += "@" + string(spec)
}
cmd = append(cmd, arg)
}
util.RunCmd(cmd)
},
Remove: func(ctx context.Context, pkgs map[api.PkgName]bool) {
//nolint:ineffassign,wastedassign,staticcheck
span, ctx := tracer.StartSpanFromContext(ctx, "bun remove")
defer span.Finish()
cmd := []string{"bun", "remove"}
for name := range pkgs {
cmd = append(cmd, string(name))
}
util.RunCmd(cmd)
},
Lock: func(ctx context.Context) {
//nolint:ineffassign,wastedassign,staticcheck
span, ctx := tracer.StartSpanFromContext(ctx, "bun install")
defer span.Finish()
util.RunCmd([]string{"bun", "install"})
},
Install: func(ctx context.Context) {
//nolint:ineffassign,wastedassign,staticcheck
span, ctx := tracer.StartSpanFromContext(ctx, "bun install")
defer span.Finish()
util.RunCmd([]string{"bun", "install"})
},
ListSpecfile: nodejsListSpecfile,
ListLockfile: func() map[api.PkgName]api.PkgVersion {
hashString, err := exec.Command("bun", "pm", "hash-string").Output()
if err != nil {
util.DieSubprocess("bun pm hash-string: %s", err)
}
r := regexp.MustCompile(`(?m)^(@?[^@ \n]+)@(.+)$`)
pkgs := map[api.PkgName]api.PkgVersion{}
for _, match := range r.FindAllStringSubmatch(string(hashString), -1) {
name := api.PkgName(match[1])
pkgs[name] = api.PkgVersion(match[2])
}
return pkgs
},
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
GuessRegexps: nodejsGuessRegexps,
Guess: nodejsGuess,
InstallReplitNixSystemDependencies: nix.DefaultInstallReplitNixSystemDependencies,
}