forked from oven-sh/bun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
npm.zig
1528 lines (1297 loc) · 70 KB
/
npm.zig
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
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const URL = @import("../url.zig").URL;
const bun = @import("root").bun;
const std = @import("std");
const MutableString = @import("../string_mutable.zig").MutableString;
const Semver = @import("./semver.zig");
const ExternalString = Semver.ExternalString;
const String = Semver.String;
const string = @import("../string_types.zig").string;
const strings = @import("../string_immutable.zig");
const PackageManager = @import("./install.zig").PackageManager;
const ExternalStringMap = @import("./install.zig").ExternalStringMap;
const ExternalStringList = @import("./install.zig").ExternalStringList;
const ExternalSlice = @import("./install.zig").ExternalSlice;
const initializeStore = @import("./install.zig").initializeMiniStore;
const logger = @import("root").bun.logger;
const Output = @import("root").bun.Output;
const Integrity = @import("./integrity.zig").Integrity;
const Bin = @import("./bin.zig").Bin;
const Environment = @import("root").bun.Environment;
const Aligner = @import("./install.zig").Aligner;
const HTTPClient = @import("root").bun.HTTP;
const json_parser = bun.JSON;
const default_allocator = @import("root").bun.default_allocator;
const IdentityContext = @import("../identity_context.zig").IdentityContext;
const ArrayIdentityContext = @import("../identity_context.zig").ArrayIdentityContext;
const SlicedString = Semver.SlicedString;
const FileSystem = @import("../fs.zig").FileSystem;
const Dependency = @import("./dependency.zig");
const VersionedURL = @import("./versioned_url.zig");
const VersionSlice = @import("./install.zig").VersionSlice;
const ObjectPool = @import("../pool.zig").ObjectPool;
const Api = @import("../api/schema.zig").Api;
const DotEnv = @import("../env_loader.zig");
const ComptimeStringMap = @import("../comptime_string_map.zig").ComptimeStringMap;
const Npm = @This();
pub const Registry = struct {
pub const default_url = "https://registry.npmjs.org/";
pub const BodyPool = ObjectPool(MutableString, MutableString.init2048, true, 8);
pub const Scope = struct {
name: string = "",
// https://github.com/npm/npm-registry-fetch/blob/main/lib/auth.js#L96
// base64("${username}:${password}")
auth: string = "",
// URL may contain these special suffixes in the pathname:
// :_authToken
// :username
// :_password
// :_auth
url: URL,
token: string = "",
pub fn hash(name: string) u64 {
return String.Builder.stringHash(name);
}
pub fn getName(name: string) string {
if (name.len == 0 or name[0] != '@') return name;
if (strings.indexOfChar(name, '/')) |i| {
return name[1..i];
}
return name[1..];
}
pub fn fromAPI(name: string, registry_: Api.NpmRegistry, allocator: std.mem.Allocator, env: *DotEnv.Loader) !Scope {
var registry = registry_;
var url = URL.parse(registry.url);
var auth: string = "";
if (registry.token.len == 0) {
outer: {
if (registry.password.len == 0) {
var pathname = url.pathname;
defer {
url.pathname = pathname;
url.path = pathname;
}
while (strings.lastIndexOfChar(pathname, ':')) |colon| {
var segment = pathname[colon + 1 ..];
pathname = pathname[0..colon];
if (pathname.len > 1 and pathname[pathname.len - 1] == '/') {
pathname = pathname[0 .. pathname.len - 1];
}
const eql_i = strings.indexOfChar(segment, '=') orelse continue;
var value = segment[eql_i + 1 ..];
segment = segment[0..eql_i];
// https://github.com/yarnpkg/yarn/blob/6db39cf0ff684ce4e7de29669046afb8103fce3d/src/registries/npm-registry.js#L364
// Bearer Token
if (strings.eqlComptime(segment, "_authToken")) {
registry.token = value;
break :outer;
}
if (strings.eqlComptime(segment, "_auth")) {
auth = value;
break :outer;
}
if (strings.eqlComptime(segment, "username")) {
registry.username = value;
continue;
}
if (strings.eqlComptime(segment, "_password")) {
registry.password = value;
continue;
}
}
}
registry.username = env.getAuto(registry.username);
registry.password = env.getAuto(registry.password);
if (registry.username.len > 0 and registry.password.len > 0 and auth.len == 0) {
var output_buf = try allocator.alloc(u8, registry.username.len + registry.password.len + 1 + std.base64.standard.Encoder.calcSize(registry.username.len + registry.password.len + 1));
var input_buf = output_buf[0 .. registry.username.len + registry.password.len + 1];
@memcpy(input_buf[0..registry.username.len], registry.username);
input_buf[registry.username.len] = ':';
@memcpy(input_buf[registry.username.len + 1 ..][0..registry.password.len], registry.password);
output_buf = output_buf[input_buf.len..];
auth = std.base64.standard.Encoder.encode(output_buf, input_buf);
break :outer;
}
}
}
registry.token = env.getAuto(registry.token);
return Scope{ .name = name, .url = url, .token = registry.token, .auth = auth };
}
};
pub const Map = std.HashMapUnmanaged(u64, Scope, IdentityContext(u64), 80);
const PackageVersionResponse = union(Tag) {
pub const Tag = enum {
cached,
fresh,
not_found,
};
cached: PackageManifest,
fresh: PackageManifest,
not_found: void,
};
const Pico = @import("root").bun.picohttp;
pub fn getPackageMetadata(
allocator: std.mem.Allocator,
response: Pico.Response,
body: []const u8,
log: *logger.Log,
package_name: string,
loaded_manifest: ?PackageManifest,
package_manager: *PackageManager,
) !PackageVersionResponse {
switch (response.status_code) {
400 => return error.BadRequest,
429 => return error.TooManyRequests,
404 => return PackageVersionResponse{ .not_found = {} },
500...599 => return error.HTTPInternalServerError,
304 => return PackageVersionResponse{
.cached = loaded_manifest.?,
},
else => {},
}
var newly_last_modified: string = "";
var new_etag: string = "";
for (response.headers) |header| {
if (!(header.name.len == "last-modified".len or header.name.len == "etag".len)) continue;
const hashed = HTTPClient.hashHeaderName(header.name);
switch (hashed) {
HTTPClient.hashHeaderConst("last-modified") => {
newly_last_modified = header.value;
},
HTTPClient.hashHeaderConst("etag") => {
new_etag = header.value;
},
else => {},
}
}
var new_etag_buf: [64]u8 = undefined;
if (new_etag.len < new_etag_buf.len) {
bun.copy(u8, &new_etag_buf, new_etag);
new_etag = new_etag_buf[0..new_etag.len];
}
if (try PackageManifest.parse(
allocator,
log,
body,
package_name,
newly_last_modified,
new_etag,
@as(u32, @truncate(@as(u64, @intCast(@max(0, std.time.timestamp()))))) + 300,
)) |package| {
if (package_manager.options.enable.manifest_cache) {
PackageManifest.Serializer.save(&package, package_manager.getTemporaryDirectory(), package_manager.getCacheDirectory()) catch {};
}
return PackageVersionResponse{ .fresh = package };
}
return error.PackageFailedToParse;
}
};
const VersionMap = std.ArrayHashMapUnmanaged(Semver.Version, PackageVersion, Semver.Version.HashContext, false);
const DistTagMap = extern struct {
tags: ExternalStringList = ExternalStringList{},
versions: VersionSlice = VersionSlice{},
};
const PackageVersionList = ExternalSlice(PackageVersion);
const ExternVersionMap = extern struct {
keys: VersionSlice = VersionSlice{},
values: PackageVersionList = PackageVersionList{},
pub fn findKeyIndex(this: ExternVersionMap, buf: []const Semver.Version, find: Semver.Version) ?u32 {
for (this.keys.get(buf), 0..) |key, i| {
if (key.eql(find)) {
return @as(u32, @truncate(i));
}
}
return null;
}
};
/// https://nodejs.org/api/os.html#osplatform
pub const OperatingSystem = enum(u16) {
none = 0,
all = all_value,
_,
pub const aix: u16 = 1 << 1;
pub const darwin: u16 = 1 << 2;
pub const freebsd: u16 = 1 << 3;
pub const linux: u16 = 1 << 4;
pub const openbsd: u16 = 1 << 5;
pub const sunos: u16 = 1 << 6;
pub const win32: u16 = 1 << 7;
pub const android: u16 = 1 << 8;
pub const all_value: u16 = aix | darwin | freebsd | linux | openbsd | sunos | win32 | android;
pub fn isMatch(this: OperatingSystem) bool {
if (comptime Environment.isLinux) {
return (@intFromEnum(this) & linux) != 0;
} else if (comptime Environment.isMac) {
return (@intFromEnum(this) & darwin) != 0;
} else {
return false;
}
}
const NameMap = ComptimeStringMap(u16, .{
.{ "aix", aix },
.{ "darwin", darwin },
.{ "freebsd", freebsd },
.{ "linux", linux },
.{ "openbsd", openbsd },
.{ "sunos", sunos },
.{ "win32", win32 },
.{ "android", android },
});
pub fn apply(this_: OperatingSystem, str: []const u8) OperatingSystem {
if (str.len == 0) {
return this_;
}
const this = @intFromEnum(this_);
const is_not = str[0] == '!';
const offset: usize = if (str[0] == '!') 1 else 0;
const field: u16 = NameMap.get(str[offset..]) orelse return this_;
if (is_not) {
return @as(OperatingSystem, @enumFromInt(this & ~field));
} else {
return @as(OperatingSystem, @enumFromInt(this | field));
}
}
};
/// https://docs.npmjs.com/cli/v8/configuring-npm/package-json#cpu
/// https://nodejs.org/api/os.html#osarch
pub const Architecture = enum(u16) {
none = 0,
all = all_value,
_,
pub const arm: u16 = 1 << 1;
pub const arm64: u16 = 1 << 2;
pub const ia32: u16 = 1 << 3;
pub const mips: u16 = 1 << 4;
pub const mipsel: u16 = 1 << 5;
pub const ppc: u16 = 1 << 6;
pub const ppc64: u16 = 1 << 7;
pub const s390: u16 = 1 << 8;
pub const s390x: u16 = 1 << 9;
pub const x32: u16 = 1 << 10;
pub const x64: u16 = 1 << 11;
pub const all_value: u16 = arm | arm64 | ia32 | mips | mipsel | ppc | ppc64 | s390 | s390x | x32 | x64;
const NameMap = ComptimeStringMap(u16, .{
.{ "arm", arm },
.{ "arm64", arm64 },
.{ "ia32", ia32 },
.{ "mips", mips },
.{ "mipsel", mipsel },
.{ "ppc", ppc },
.{ "ppc64", ppc64 },
.{ "s390", s390 },
.{ "s390x", s390x },
.{ "x32", x32 },
.{ "x64", x64 },
});
pub fn isMatch(this: Architecture) bool {
if (comptime Environment.isAarch64) {
return (@intFromEnum(this) & arm64) != 0;
} else if (comptime Environment.isX64) {
return (@intFromEnum(this) & x64) != 0;
} else {
return false;
}
}
pub fn apply(this_: Architecture, str: []const u8) Architecture {
if (str.len == 0) {
return this_;
}
const this = @intFromEnum(this_);
const is_not = str[0] == '!';
const offset: usize = if (str[0] == '!') 1 else 0;
const input = str[offset..];
const field: u16 = NameMap.get(input) orelse return this_;
if (is_not) {
return @as(Architecture, @enumFromInt(this & ~field));
} else {
return @as(Architecture, @enumFromInt(this | field));
}
}
};
const BigExternalString = Semver.BigExternalString;
pub const PackageVersion = extern struct {
/// `"integrity"` field || `"shasum"` field
/// https://github.com/npm/registry/blob/master/docs/responses/package-metadata.md#dist
// Splitting this into it's own array ends up increasing the final size a little bit.
integrity: Integrity = Integrity{},
/// "dependencies"` in [package.json](https://docs.npmjs.com/cli/v8/configuring-npm/package-json#dependencies)
dependencies: ExternalStringMap = ExternalStringMap{},
/// `"optionalDependencies"` in [package.json](https://docs.npmjs.com/cli/v8/configuring-npm/package-json#optionaldependencies)
optional_dependencies: ExternalStringMap = ExternalStringMap{},
/// `"peerDependencies"` in [package.json](https://docs.npmjs.com/cli/v8/configuring-npm/package-json#peerdependencies)
/// if `optional_peer_dependencies_len` is > 0, then instead of alphabetical, the first N items are optional
peer_dependencies: ExternalStringMap = ExternalStringMap{},
/// `"devDependencies"` in [package.json](https://docs.npmjs.com/cli/v8/configuring-npm/package-json#devdependencies)
/// We deliberately choose not to populate this field.
/// We keep it in the data layout so that if it turns out we do need it, we can add it without invalidating everyone's history.
dev_dependencies: ExternalStringMap = ExternalStringMap{},
/// `"bin"` field in [package.json](https://docs.npmjs.com/cli/v8/configuring-npm/package-json#bin)
bin: Bin = Bin{},
/// `"engines"` field in package.json
engines: ExternalStringMap = ExternalStringMap{},
/// `"peerDependenciesMeta"` in [package.json](https://docs.npmjs.com/cli/v8/configuring-npm/package-json#peerdependenciesmeta)
/// if `optional_peer_dependencies_len` is > 0, then instead of alphabetical, the first N items of `peer_dependencies` are optional
optional_peer_dependencies_len: u32 = 0,
man_dir: ExternalString = ExternalString{},
/// can be empty!
/// When empty, it means that the tarball URL can be inferred
tarball_url: ExternalString = ExternalString{},
unpacked_size: u32 = 0,
file_count: u32 = 0,
/// `"os"` field in package.json
os: OperatingSystem = OperatingSystem.all,
/// `"cpu"` field in package.json
cpu: Architecture = Architecture.all,
pub fn verify(this: *const PackageVersion) void {
if (comptime !Environment.allow_assert)
return;
this.man_dir.value.assertDefined();
}
};
pub const NpmPackage = extern struct {
/// HTTP response headers
last_modified: String = String{},
etag: String = String{},
/// "modified" in the JSON
modified: String = String{},
public_max_age: u32 = 0,
name: ExternalString = ExternalString{},
releases: ExternVersionMap = ExternVersionMap{},
prereleases: ExternVersionMap = ExternVersionMap{},
dist_tags: DistTagMap = DistTagMap{},
versions_buf: VersionSlice = VersionSlice{},
string_lists_buf: ExternalStringList = ExternalStringList{},
string_buf: BigExternalString = BigExternalString{},
};
pub const PackageManifest = struct {
pkg: NpmPackage = .{},
string_buf: []const u8 = &[_]u8{},
versions: []const Semver.Version = &[_]Semver.Version{},
external_strings: []const ExternalString = &[_]ExternalString{},
// We store this in a separate buffer so that we can dedupe contiguous identical versions without an extra pass
external_strings_for_versions: []const ExternalString = &[_]ExternalString{},
package_versions: []const PackageVersion = &[_]PackageVersion{},
extern_strings_bin_entries: []const ExternalString = &[_]ExternalString{},
pub fn verify(this: *const PackageManifest) void {
if (comptime !Environment.allow_assert)
return;
for (this.extern_strings_bin_entries) |*entry| {
entry.value.assertDefined();
}
for (this.external_strings_for_versions) |entry| {
entry.value.assertDefined();
}
for (this.package_versions) |package| {
package.tarball_url.value.assertDefined();
}
}
pub inline fn name(this: *const PackageManifest) string {
return this.pkg.name.slice(this.string_buf);
}
pub const Serializer = struct {
pub const version = "bun-npm-manifest-cache-v0.0.2\n";
const header_bytes: string = "#!/usr/bin/env bun\n" ++ version;
pub const sizes = blk: {
// skip name
const fields = std.meta.fields(Npm.PackageManifest);
const Data = struct {
size: usize,
name: []const u8,
alignment: usize,
};
var data: [fields.len]Data = undefined;
for (fields, 0..) |field_info, i| {
data[i] = .{
.size = @sizeOf(field_info.type),
.name = field_info.name,
.alignment = if (@sizeOf(field_info.type) == 0) 1 else field_info.alignment,
};
}
const Sort = struct {
fn lessThan(trash: *i32, lhs: Data, rhs: Data) bool {
_ = trash;
return lhs.alignment > rhs.alignment;
}
};
var trash: i32 = undefined; // workaround for stage1 compiler bug
std.sort.block(Data, &data, &trash, Sort.lessThan);
var sizes_bytes: [fields.len]usize = undefined;
var names: [fields.len][]const u8 = undefined;
for (data, 0..) |elem, i| {
sizes_bytes[i] = elem.size;
names[i] = elem.name;
}
break :blk .{
.bytes = sizes_bytes,
.fields = names,
};
};
pub fn writeArray(comptime Writer: type, writer: Writer, comptime Type: type, array: []const Type, pos: *u64) !void {
const bytes = std.mem.sliceAsBytes(array);
if (bytes.len == 0) {
try writer.writeIntNative(u64, 0);
pos.* += 8;
return;
}
try writer.writeIntNative(u64, bytes.len);
pos.* += 8;
pos.* += try Aligner.write(Type, Writer, writer, pos.*);
try writer.writeAll(
bytes,
);
pos.* += bytes.len;
}
pub fn readArray(stream: *std.io.FixedBufferStream([]const u8), comptime Type: type) ![]const Type {
var reader = stream.reader();
const byte_len = try reader.readIntNative(u64);
if (byte_len == 0) {
return &[_]Type{};
}
stream.pos += Aligner.skipAmount(Type, stream.pos);
const result_bytes = stream.buffer[stream.pos..][0..byte_len];
const result = @as([*]const Type, @ptrCast(@alignCast(result_bytes.ptr)))[0 .. result_bytes.len / @sizeOf(Type)];
stream.pos += result_bytes.len;
return result;
}
pub fn write(this: *const PackageManifest, comptime Writer: type, writer: Writer) !void {
var pos: u64 = 0;
try writer.writeAll(header_bytes);
pos += header_bytes.len;
inline for (sizes.fields) |field_name| {
if (comptime strings.eqlComptime(field_name, "pkg")) {
const bytes = std.mem.asBytes(&this.pkg);
pos += try Aligner.write(NpmPackage, Writer, writer, pos);
try writer.writeAll(
bytes,
);
pos += bytes.len;
} else {
const field = @field(this, field_name);
try writeArray(Writer, writer, std.meta.Child(@TypeOf(field)), field, &pos);
}
}
}
fn writeFile(this: *const PackageManifest, tmp_path: [:0]const u8, tmpdir: std.fs.IterableDir) !void {
var tmpfile = try tmpdir.dir.createFileZ(tmp_path, .{
.truncate = true,
});
defer tmpfile.close();
var writer = tmpfile.writer();
try Serializer.write(this, @TypeOf(writer), writer);
}
pub fn save(this: *const PackageManifest, tmpdir: std.fs.IterableDir, cache_dir: std.fs.IterableDir) !void {
const file_id = bun.Wyhash.hash(0, this.name());
var dest_path_buf: [512 + 64]u8 = undefined;
var out_path_buf: ["-18446744073709551615".len + ".npm".len + 1]u8 = undefined;
var dest_path_stream = std.io.fixedBufferStream(&dest_path_buf);
var dest_path_stream_writer = dest_path_stream.writer();
const hex_fmt = bun.fmt.hexIntLower(file_id);
const hex_timestamp = @as(usize, @intCast(@max(std.time.milliTimestamp(), 0)));
const hex_timestamp_fmt = bun.fmt.hexIntLower(hex_timestamp);
try dest_path_stream_writer.print("{any}.npm-{any}", .{ hex_fmt, hex_timestamp_fmt });
try dest_path_stream_writer.writeByte(0);
var tmp_path: [:0]u8 = dest_path_buf[0 .. dest_path_stream.pos - 1 :0];
try writeFile(this, tmp_path, tmpdir);
var out_path = std.fmt.bufPrintZ(&out_path_buf, "{any}.npm", .{hex_fmt}) catch unreachable;
try std.os.renameatZ(tmpdir.dir.fd, tmp_path, cache_dir.dir.fd, out_path);
}
pub fn load(allocator: std.mem.Allocator, cache_dir: std.fs.IterableDir, package_name: string) !?PackageManifest {
const file_id = bun.Wyhash.hash(0, package_name);
var file_path_buf: [512 + 64]u8 = undefined;
const hex_fmt = bun.fmt.hexIntLower(file_id);
var file_path = try std.fmt.bufPrintZ(&file_path_buf, "{any}.npm", .{hex_fmt});
var cache_file = cache_dir.dir.openFileZ(
file_path,
.{ .mode = .read_only },
) catch return null;
var timer: std.time.Timer = undefined;
if (PackageManager.verbose_install) {
timer = std.time.Timer.start() catch @panic("timer fail");
}
defer cache_file.close();
var bytes = try cache_file.readToEndAllocOptions(
allocator,
std.math.maxInt(u32),
cache_file.getEndPos() catch null,
@alignOf(u8),
null,
);
errdefer allocator.free(bytes);
if (bytes.len < header_bytes.len) return null;
const result = try readAll(bytes);
if (PackageManager.verbose_install) {
Output.prettyError("\n ", .{});
Output.printTimer(&timer);
Output.prettyErrorln("<d> [cache hit] {s}<r>", .{package_name});
}
return result;
}
pub fn readAll(bytes: []const u8) !PackageManifest {
if (!strings.eqlComptime(bytes[0..header_bytes.len], header_bytes)) {
return error.InvalidPackageManifest;
}
var pkg_stream = std.io.fixedBufferStream(bytes);
pkg_stream.pos = header_bytes.len;
var package_manifest = PackageManifest{};
inline for (sizes.fields) |field_name| {
if (comptime strings.eqlComptime(field_name, "pkg")) {
pkg_stream.pos = std.mem.alignForward(usize, pkg_stream.pos, @alignOf(Npm.NpmPackage));
var reader = pkg_stream.reader();
package_manifest.pkg = try reader.readStruct(NpmPackage);
} else {
@field(package_manifest, field_name) = try readArray(
&pkg_stream,
std.meta.Child(@TypeOf(@field(package_manifest, field_name))),
);
}
}
package_manifest.verify();
return package_manifest;
}
};
pub fn str(self: *const PackageManifest, external: *const ExternalString) string {
return external.slice(self.string_buf);
}
pub fn reportSize(this: *const PackageManifest) void {
Output.prettyErrorln(
\\ Versions count: {d}
\\ External Strings count: {d}
\\ Package Versions count: {d}
\\
\\ Bytes:
\\
\\ Versions: {d}
\\ External: {d}
\\ Packages: {d}
\\ Strings: {d}
\\ Total: {d}
, .{
this.versions.len,
this.external_strings.len,
this.package_versions.len,
std.mem.sliceAsBytes(this.versions).len,
std.mem.sliceAsBytes(this.external_strings).len,
std.mem.sliceAsBytes(this.package_versions).len,
std.mem.sliceAsBytes(this.string_buf).len,
std.mem.sliceAsBytes(this.versions).len +
std.mem.sliceAsBytes(this.external_strings).len +
std.mem.sliceAsBytes(this.package_versions).len +
std.mem.sliceAsBytes(this.string_buf).len,
});
Output.flush();
}
pub const FindResult = struct {
version: Semver.Version,
package: *const PackageVersion,
};
pub fn findByString(this: *const PackageManifest, version: string) ?FindResult {
switch (Dependency.Version.Tag.infer(version)) {
.npm => {
const group = Semver.Query.parse(default_allocator, version, SlicedString.init(
version,
version,
)) catch return null;
return this.findBestVersion(group);
},
.dist_tag => {
return this.findByDistTag(version);
},
else => return null,
}
}
pub fn findByVersion(this: *const PackageManifest, version: Semver.Version) ?FindResult {
const list = if (!version.tag.hasPre()) this.pkg.releases else this.pkg.prereleases;
const values = list.values.get(this.package_versions);
const keys = list.keys.get(this.versions);
const index = list.findKeyIndex(this.versions, version) orelse return null;
return .{
// Be sure to use the struct from the list in the NpmPackage
// That is the one we can correctly recover the original version string for
.version = keys[index],
.package = &values[index],
};
}
pub fn findByDistTag(this: *const PackageManifest, tag: string) ?FindResult {
const versions = this.pkg.dist_tags.versions.get(this.versions);
for (this.pkg.dist_tags.tags.get(this.external_strings), 0..) |tag_str, i| {
if (strings.eql(tag_str.slice(this.string_buf), tag)) {
return this.findByVersion(versions[i]);
}
}
return null;
}
pub fn findBestVersion(this: *const PackageManifest, group: Semver.Query.Group) ?FindResult {
const left = group.head.head.range.left;
// Fast path: exact version
if (left.op == .eql) {
return this.findByVersion(left.version);
}
const releases = this.pkg.releases.keys.get(this.versions);
if (group.flags.isSet(Semver.Query.Group.Flags.pre)) {
const prereleases = this.pkg.prereleases.keys.get(this.versions);
var i = prereleases.len;
while (i > 0) : (i -= 1) {
const version = prereleases[i - 1];
const packages = this.pkg.prereleases.values.get(this.package_versions);
if (group.satisfies(version)) {
return .{ .version = version, .package = &packages[i - 1] };
}
}
} else if (this.findByDistTag("latest")) |result| {
if (group.satisfies(result.version)) return result;
}
{
var i = releases.len;
// // For now, this is the dumb way
while (i > 0) : (i -= 1) {
const version = releases[i - 1];
const packages = this.pkg.releases.values.get(this.package_versions);
if (group.satisfies(version)) {
return .{ .version = version, .package = &packages[i - 1] };
}
}
}
return null;
}
const ExternalStringMapDeduper = std.HashMap(u64, ExternalStringList, IdentityContext(u64), 80);
/// This parses [Abbreviated metadata](https://github.com/npm/registry/blob/master/docs/responses/package-metadata.md#abbreviated-metadata-format)
pub fn parse(
allocator: std.mem.Allocator,
log: *logger.Log,
json_buffer: []const u8,
expected_name: []const u8,
last_modified: []const u8,
etag: []const u8,
public_max_age: u32,
) !?PackageManifest {
const source = logger.Source.initPathString(expected_name, json_buffer);
initializeStore();
defer bun.JSAst.Stmt.Data.Store.memory_allocator.?.pop();
var arena = @import("root").bun.ArenaAllocator.init(allocator);
defer arena.deinit();
const json = json_parser.ParseJSONUTF8(
&source,
log,
arena.allocator(),
) catch return null;
if (json.asProperty("error")) |error_q| {
if (error_q.expr.asString(allocator)) |err| {
log.addErrorFmt(&source, logger.Loc.Empty, allocator, "npm error: {s}", .{err}) catch unreachable;
return null;
}
}
var result = PackageManifest{};
var string_pool = String.Builder.StringPool.init(default_allocator);
defer string_pool.deinit();
var external_string_maps = ExternalStringMapDeduper.initContext(default_allocator, .{});
defer external_string_maps.deinit();
var optional_peer_dep_names = std.ArrayList(u64).init(default_allocator);
defer optional_peer_dep_names.deinit();
var string_builder = String.Builder{
.string_pool = string_pool,
};
if (json.asProperty("name")) |name_q| {
const field = name_q.expr.asString(allocator) orelse return null;
if (!strings.eql(field, expected_name)) {
Output.panic("<r>internal: <red>package name mismatch<r> expected <b>\"{s}\"<r> but received <red>\"{s}\"<r>", .{ expected_name, field });
return null;
}
string_builder.count(field);
}
if (json.asProperty("modified")) |name_q| {
const field = name_q.expr.asString(allocator) orelse return null;
string_builder.count(field);
}
const DependencyGroup = struct { prop: string, field: string };
const dependency_groups = comptime [_]DependencyGroup{
.{ .prop = "dependencies", .field = "dependencies" },
.{ .prop = "optionalDependencies", .field = "optional_dependencies" },
.{ .prop = "peerDependencies", .field = "peer_dependencies" },
};
var release_versions_len: usize = 0;
var pre_versions_len: usize = 0;
var dependency_sum: usize = 0;
var extern_string_count: usize = 0;
var extern_string_count_bin: usize = 0;
var tarball_urls_count: usize = 0;
get_versions: {
if (json.asProperty("versions")) |versions_q| {
if (versions_q.expr.data != .e_object) break :get_versions;
const versions = versions_q.expr.data.e_object.properties.slice();
for (versions) |prop| {
const version_name = prop.key.?.asString(allocator) orelse continue;
if (strings.indexOfChar(version_name, '-') != null) {
pre_versions_len += 1;
extern_string_count += 1;
} else {
extern_string_count += @as(usize, @intFromBool(strings.indexOfChar(version_name, '+') != null));
release_versions_len += 1;
}
string_builder.count(version_name);
if (prop.value.?.asProperty("dist")) |dist_q| {
if (dist_q.expr.get("tarball")) |tarball_prop| {
if (tarball_prop.data == .e_string) {
const tarball = tarball_prop.data.e_string.slice(allocator);
string_builder.count(tarball);
tarball_urls_count += @as(usize, @intFromBool(tarball.len > 0));
}
}
}
bin: {
if (prop.value.?.asProperty("bin")) |bin| {
switch (bin.expr.data) {
.e_object => |obj| {
switch (obj.properties.len) {
0 => {
break :bin;
},
1 => {},
else => {
extern_string_count_bin += obj.properties.len * 2;
},
}
for (obj.properties.slice()) |bin_prop| {
string_builder.count(bin_prop.key.?.asString(allocator) orelse break :bin);
string_builder.count(bin_prop.value.?.asString(allocator) orelse break :bin);
}
},
.e_string => {
if (bin.expr.asString(allocator)) |str_| {
string_builder.count(str_);
break :bin;
}
},
else => {},
}
}
if (prop.value.?.asProperty("directories")) |dirs| {
if (dirs.expr.asProperty("bin")) |bin_prop| {
if (bin_prop.expr.asString(allocator)) |str_| {
string_builder.count(str_);
break :bin;
}
}
}
}
inline for (dependency_groups) |pair| {
if (prop.value.?.asProperty(pair.prop)) |versioned_deps| {
if (versioned_deps.expr.data == .e_object) {
dependency_sum += versioned_deps.expr.data.e_object.properties.len;
const properties = versioned_deps.expr.data.e_object.properties.slice();
for (properties) |property| {
if (property.key.?.asString(allocator)) |key| {
string_builder.count(key);
string_builder.count(property.value.?.asString(allocator) orelse "");
}
}
}
}
}
}
}
}
extern_string_count += dependency_sum;
var dist_tags_count: usize = 0;
if (json.asProperty("dist-tags")) |dist| {
if (dist.expr.data == .e_object) {
const tags = dist.expr.data.e_object.properties.slice();
for (tags) |tag| {
if (tag.key.?.asString(allocator)) |key| {
string_builder.count(key);
extern_string_count += 2;
string_builder.count((tag.value.?.asString(allocator) orelse ""));
dist_tags_count += 1;
}
}
}
}
if (last_modified.len > 0) {
string_builder.count(last_modified);
}
if (etag.len > 0) {
string_builder.count(etag);
}
var versioned_packages = try allocator.alloc(PackageVersion, release_versions_len + pre_versions_len);
var all_semver_versions = try allocator.alloc(Semver.Version, release_versions_len + pre_versions_len + dist_tags_count);
var all_extern_strings = try allocator.alloc(ExternalString, extern_string_count + tarball_urls_count);
var version_extern_strings = try allocator.alloc(ExternalString, dependency_sum);
var extern_strings_bin_entries = try allocator.alloc(ExternalString, extern_string_count_bin);
var all_extern_strings_bin_entries = extern_strings_bin_entries;
var all_tarball_url_strings = try allocator.alloc(ExternalString, tarball_urls_count);
var tarball_url_strings = all_tarball_url_strings;
if (versioned_packages.len > 0) {
var versioned_packages_bytes = std.mem.sliceAsBytes(versioned_packages);
@memset(versioned_packages_bytes, 0);
}
if (all_semver_versions.len > 0) {
var all_semver_versions_bytes = std.mem.sliceAsBytes(all_semver_versions);
@memset(all_semver_versions_bytes, 0);
}
if (all_extern_strings.len > 0) {
var all_extern_strings_bytes = std.mem.sliceAsBytes(all_extern_strings);
@memset(all_extern_strings_bytes, 0);
}
if (version_extern_strings.len > 0) {
var version_extern_strings_bytes = std.mem.sliceAsBytes(version_extern_strings);
@memset(version_extern_strings_bytes, 0);
}
var versioned_package_releases = versioned_packages[0..release_versions_len];
var all_versioned_package_releases = versioned_package_releases;
var versioned_package_prereleases = versioned_packages[release_versions_len..][0..pre_versions_len];
var all_versioned_package_prereleases = versioned_package_prereleases;
var _versions_open = all_semver_versions;
var all_release_versions = _versions_open[0..release_versions_len];
_versions_open = _versions_open[release_versions_len..];
var all_prerelease_versions = _versions_open[0..pre_versions_len];
_versions_open = _versions_open[pre_versions_len..];
var dist_tag_versions = _versions_open[0..dist_tags_count];
var release_versions = all_release_versions;
var prerelease_versions = all_prerelease_versions;
var extern_strings = all_extern_strings;
string_builder.cap += (string_builder.cap % 64) + 64;
string_builder.cap *= 2;
try string_builder.allocate(allocator);
var string_buf: string = "";
if (string_builder.ptr) |ptr| {
// 0 it out for better determinism