@packall/core 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +58 -0
  3. package/dist/archive-DmF9XNl7.js +284 -0
  4. package/dist/archive-DmF9XNl7.js.map +1 -0
  5. package/dist/archive.d.ts +47 -15
  6. package/dist/archive.d.ts.map +1 -1
  7. package/dist/bundle.d.ts +6 -3
  8. package/dist/bundle.d.ts.map +1 -1
  9. package/dist/dependency-range.d.ts.map +1 -1
  10. package/dist/download.d.ts +2 -1
  11. package/dist/download.d.ts.map +1 -1
  12. package/dist/enums/artifact-kind.d.ts.map +1 -1
  13. package/dist/enums/edge-kind.d.ts.map +1 -1
  14. package/dist/enums/input-file-kind.d.ts.map +1 -1
  15. package/dist/enums/layout.d.ts.map +1 -1
  16. package/dist/enums/lockfile-format.d.ts.map +1 -1
  17. package/dist/enums/phase.d.ts.map +1 -1
  18. package/dist/errors.d.ts +11 -1
  19. package/dist/errors.d.ts.map +1 -1
  20. package/dist/index.d.ts +12 -10
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +169 -344
  23. package/dist/index.js.map +1 -1
  24. package/dist/input-file.d.ts.map +1 -1
  25. package/dist/integrity.d.ts +37 -5
  26. package/dist/integrity.d.ts.map +1 -1
  27. package/dist/layout.d.ts +41 -7
  28. package/dist/layout.d.ts.map +1 -1
  29. package/dist/locked-resolve.d.ts.map +1 -1
  30. package/dist/lockfile/bun.d.ts.map +1 -1
  31. package/dist/lockfile/detect.d.ts.map +1 -1
  32. package/dist/lockfile/json.d.ts.map +1 -1
  33. package/dist/lockfile/names.d.ts.map +1 -1
  34. package/dist/lockfile/npm.d.ts.map +1 -1
  35. package/dist/lockfile/parse.d.ts.map +1 -1
  36. package/dist/lockfile/pnpm.d.ts.map +1 -1
  37. package/dist/lockfile/tree-builder.d.ts.map +1 -1
  38. package/dist/lockfile/types.d.ts.map +1 -1
  39. package/dist/manifest.d.ts.map +1 -1
  40. package/dist/node/archiver.d.ts +5 -0
  41. package/dist/node/archiver.d.ts.map +1 -0
  42. package/dist/node/index.d.ts +13 -0
  43. package/dist/node/index.d.ts.map +1 -0
  44. package/dist/node/index.js +55 -0
  45. package/dist/node/index.js.map +1 -0
  46. package/dist/options.d.ts +3 -3
  47. package/dist/options.d.ts.map +1 -1
  48. package/dist/platform.d.ts +5 -10
  49. package/dist/platform.d.ts.map +1 -1
  50. package/dist/progress.d.ts.map +1 -1
  51. package/dist/registry.d.ts.map +1 -1
  52. package/dist/resolve.d.ts.map +1 -1
  53. package/dist/schemas/lenient.d.ts.map +1 -1
  54. package/dist/schemas/package-json.d.ts.map +1 -1
  55. package/dist/spec.d.ts.map +1 -1
  56. package/dist/types/value-of.d.ts.map +1 -1
  57. package/dist/utils/is-record.d.ts.map +1 -1
  58. package/package.json +11 -10
  59. package/src/archive.ts +95 -92
  60. package/src/bundle.ts +736 -616
  61. package/src/dependency-range.ts +121 -115
  62. package/src/download.ts +155 -133
  63. package/src/enums/artifact-kind.ts +5 -5
  64. package/src/enums/edge-kind.ts +13 -13
  65. package/src/enums/input-file-kind.ts +9 -9
  66. package/src/enums/layout.ts +20 -20
  67. package/src/enums/lockfile-format.ts +6 -6
  68. package/src/enums/phase.ts +8 -8
  69. package/src/errors.ts +211 -199
  70. package/src/index.ts +126 -113
  71. package/src/input-file.ts +246 -234
  72. package/src/integrity.ts +165 -121
  73. package/src/layout.ts +63 -29
  74. package/src/locked-resolve.ts +471 -461
  75. package/src/lockfile/bun.ts +214 -207
  76. package/src/lockfile/detect.ts +80 -80
  77. package/src/lockfile/json.ts +91 -92
  78. package/src/lockfile/names.ts +9 -9
  79. package/src/lockfile/npm.ts +328 -308
  80. package/src/lockfile/parse.ts +32 -32
  81. package/src/lockfile/pnpm.ts +230 -225
  82. package/src/lockfile/tree-builder.ts +116 -116
  83. package/src/lockfile/types.ts +52 -52
  84. package/src/manifest.ts +129 -133
  85. package/src/node/archiver.ts +85 -0
  86. package/src/node/index.ts +13 -0
  87. package/src/options.ts +84 -84
  88. package/src/platform.ts +97 -101
  89. package/src/progress.ts +105 -106
  90. package/src/registry.ts +116 -115
  91. package/src/resolve.ts +560 -537
  92. package/src/schemas/lenient.ts +67 -60
  93. package/src/schemas/package-json.ts +11 -10
  94. package/src/spec.ts +123 -119
  95. package/src/types/value-of.ts +1 -1
  96. package/src/utils/is-record.ts +1 -1
@@ -1,207 +1,214 @@
1
- /**
2
- * `bun.lock`.
3
- *
4
- * Like npm, bun records ranges on its edges and resolves them through the
5
- * install-path nesting — but it nests with a plain `/`, and package names
6
- * contain `/` too, so the parent of a key can only be found by asking which
7
- * prefixes are themselves entries.
8
- */
9
- import { EdgeKind, LockedRootKind } from "../enums/edge-kind.js"
10
- import { LockfileFormat } from "../enums/lockfile-format.js"
11
- import { optionalPeerNames, parseJsonObject, stringRecord } from "./json.js"
12
- import { isRecord } from "../utils/is-record.js"
13
- import { asExactVersion, fieldByRootKind, importerKey, notCovered, TreeBuilder } from "./tree-builder.js"
14
- import type { LockedEdge, LockedTree } from "./types.js"
15
-
16
- /** One narrowed `packages` entry, keyed by its install path. */
17
- type BunEntry = {
18
- readonly key: string
19
- readonly name: string
20
- readonly version: string
21
- readonly dependencies: Readonly<Record<string, string>>
22
- readonly optionalDependencies: Readonly<Record<string, string>>
23
- readonly peerDependencies: Readonly<Record<string, string>>
24
- readonly optionalPeers: ReadonlySet<string>
25
- }
26
-
27
- /** Root blocks in bun's precedence order — the first mention of a name wins. */
28
- const ROOT_KINDS = [
29
- LockedRootKind.Prod,
30
- LockedRootKind.Optional,
31
- LockedRootKind.Dev,
32
- LockedRootKind.Peer
33
- ] as const
34
-
35
- export const parseBunLockfile = (
36
- path: string,
37
- content: string,
38
- importer: string | undefined
39
- ): LockedTree => {
40
- const root = parseJsonObject(path, content)
41
- const version = String(root["lockfileVersion"] ?? "?")
42
- const builder = new TreeBuilder()
43
-
44
- const packages = root["packages"]
45
- const entries = isRecord(packages)
46
- ? collectEntries(builder, packages)
47
- : new Map<string, BunEntry>()
48
-
49
- const keys = new Set(entries.keys())
50
- for (const entry of entries.values()) {
51
- builder.add({
52
- name: entry.name,
53
- version: entry.version,
54
- dependencies: edgesOf(builder, entries, keys, entry)
55
- })
56
- }
57
-
58
- collectRoots(builder, entries, keys, root["workspaces"], path, importer)
59
-
60
- return builder.finish({ format: LockfileFormat.Bun, lockfileVersion: version, path, importer })
61
- }
62
-
63
- /**
64
- * Narrows bun's tuple entries.
65
- *
66
- * The value is a positional array whose shape depends on where the package came
67
- * from. A registry package is `[id, registry, info, integrity]`; a workspace
68
- * member or a git dependency is shorter and its `id` carries the protocol.
69
- */
70
- const collectEntries = (
71
- builder: TreeBuilder,
72
- packages: Record<string, unknown>
73
- ): Map<string, BunEntry> => {
74
- const entries = new Map<string, BunEntry>()
75
-
76
- for (const [key, raw] of Object.entries(packages)) {
77
- if (!Array.isArray(raw)) continue
78
-
79
- const [id, , info] = raw
80
- if (typeof id !== "string") continue
81
-
82
- const at = id.lastIndexOf("@")
83
- if (at <= 0) continue
84
- const name = id.slice(0, at)
85
- const spec = id.slice(at + 1)
86
-
87
- const version = asExactVersion(name, spec)
88
- if (version._tag === "Unsupported") {
89
- builder.skip(name, spec, version.reason)
90
- continue
91
- }
92
-
93
- const details = isRecord(info) ? info : {}
94
-
95
- entries.set(key, {
96
- key,
97
- name,
98
- version: version.version,
99
- dependencies: stringRecord(details["dependencies"]),
100
- optionalDependencies: stringRecord(details["optionalDependencies"]),
101
- peerDependencies: stringRecord(details["peerDependencies"]),
102
- optionalPeers: collectOptionalPeers(details)
103
- })
104
- }
105
-
106
- return entries
107
- }
108
-
109
- /** bun lists optional peers as a name array rather than npm's metadata object. */
110
- const collectOptionalPeers = (details: Record<string, unknown>): ReadonlySet<string> => {
111
- const listed = details["optionalPeers"]
112
- const names = Array.isArray(listed)
113
- ? listed.flatMap((entry) => (typeof entry === "string" ? entry : []))
114
- : []
115
- return new Set([...names, ...optionalPeerNames(details["peerDependenciesMeta"])])
116
- }
117
-
118
- const edgesOf = (
119
- builder: TreeBuilder,
120
- entries: ReadonlyMap<string, BunEntry>,
121
- keys: ReadonlySet<string>,
122
- entry: BunEntry
123
- ): ReadonlyArray<LockedEdge> => {
124
- const edges: Array<LockedEdge> = []
125
-
126
- const add = (names: ReadonlyArray<string>, kind: EdgeKind): void => {
127
- for (const name of names) {
128
- const target = findEntry(entries, keys, entry.key, name)
129
- if (target === undefined) {
130
- if (kind === EdgeKind.Prod) builder.dangling(`${entry.name}@${entry.version}`, name)
131
- continue
132
- }
133
- edges.push({ name: target.name, version: target.version, kind })
134
- }
135
- }
136
-
137
- add(Object.keys(entry.dependencies), EdgeKind.Prod)
138
- add(Object.keys(entry.optionalDependencies), EdgeKind.Optional)
139
- add(
140
- Object.keys(entry.peerDependencies).filter((name) => !entry.optionalPeers.has(name)),
141
- EdgeKind.Peer
142
- )
143
-
144
- return edges
145
- }
146
-
147
- const collectRoots = (
148
- builder: TreeBuilder,
149
- entries: ReadonlyMap<string, BunEntry>,
150
- keys: ReadonlySet<string>,
151
- workspaces: unknown,
152
- path: string,
153
- member: string | undefined
154
- ): void => {
155
- if (!isRecord(workspaces)) return
156
-
157
- const selected =
158
- member === undefined
159
- ? Object.values(workspaces)
160
- : Object.hasOwn(workspaces, importerKey(member))
161
- ? [workspaces[importerKey(member)]]
162
- : notCovered(path, member, workspacePaths(workspaces))
163
-
164
- for (const workspace of selected) {
165
- if (!isRecord(workspace)) continue
166
- for (const kind of ROOT_KINDS) {
167
- const declared = stringRecord(workspace[fieldByRootKind[kind]])
168
- for (const [name, specifier] of Object.entries(declared)) {
169
- const target = findEntry(entries, keys, "", name)
170
- if (target === undefined) continue
171
- builder.addRoot({ name: target.name, version: target.version, kind, specifier })
172
- }
173
- }
174
- }
175
- }
176
-
177
- const workspacePaths = (workspaces: Record<string, unknown>): ReadonlyArray<string> =>
178
- Object.keys(workspaces).map((key) => (key === "" ? "." : key))
179
-
180
- /**
181
- * bun nests with a plain `/`, and package names contain `/` too, so a parent
182
- * key cannot be found by string-splitting alone — `@babel/core` would split
183
- * into a scope that is not a key. `parentKey` only accepts a prefix that is
184
- * itself an entry, which resolves the ambiguity.
185
- */
186
- const findEntry = (
187
- entries: ReadonlyMap<string, BunEntry>,
188
- keys: ReadonlySet<string>,
189
- fromKey: string,
190
- name: string
191
- ): BunEntry | undefined => {
192
- let scope = fromKey
193
- for (;;) {
194
- const found = entries.get(scope === "" ? name : `${scope}/${name}`)
195
- if (found !== undefined) return found
196
- if (scope === "") return undefined
197
- scope = parentKey(keys, scope)
198
- }
199
- }
200
-
201
- const parentKey = (keys: ReadonlySet<string>, key: string): string => {
202
- for (let at = key.lastIndexOf("/"); at > 0; at = key.lastIndexOf("/", at - 1)) {
203
- const prefix = key.slice(0, at)
204
- if (keys.has(prefix)) return prefix
205
- }
206
- return ""
207
- }
1
+ /**
2
+ * `bun.lock`.
3
+ *
4
+ * Like npm, bun records ranges on its edges and resolves them through the
5
+ * install-path nesting — but it nests with a plain `/`, and package names
6
+ * contain `/` too, so the parent of a key can only be found by asking which
7
+ * prefixes are themselves entries.
8
+ */
9
+ import { EdgeKind, LockedRootKind } from "../enums/edge-kind.js";
10
+ import { LockfileFormat } from "../enums/lockfile-format.js";
11
+ import { isRecord } from "../utils/is-record.js";
12
+ import { optionalPeerNames, parseJsonObject, stringRecord } from "./json.js";
13
+ import {
14
+ asExactVersion,
15
+ fieldByRootKind,
16
+ importerKey,
17
+ notCovered,
18
+ TreeBuilder,
19
+ } from "./tree-builder.js";
20
+ import type { LockedEdge, LockedTree } from "./types.js";
21
+
22
+ /** One narrowed `packages` entry, keyed by its install path. */
23
+ type BunEntry = {
24
+ readonly key: string;
25
+ readonly name: string;
26
+ readonly version: string;
27
+ readonly dependencies: Readonly<Record<string, string>>;
28
+ readonly optionalDependencies: Readonly<Record<string, string>>;
29
+ readonly peerDependencies: Readonly<Record<string, string>>;
30
+ readonly optionalPeers: ReadonlySet<string>;
31
+ };
32
+
33
+ /** Root blocks in bun's precedence order — the first mention of a name wins. */
34
+ const ROOT_KINDS = [
35
+ LockedRootKind.Prod,
36
+ LockedRootKind.Optional,
37
+ LockedRootKind.Dev,
38
+ LockedRootKind.Peer,
39
+ ] as const;
40
+
41
+ export const parseBunLockfile = (
42
+ path: string,
43
+ content: string,
44
+ importer: string | undefined,
45
+ ): LockedTree => {
46
+ const root = parseJsonObject(path, content);
47
+ const version = String(root["lockfileVersion"] ?? "?");
48
+ const builder = new TreeBuilder();
49
+
50
+ const packages = root["packages"];
51
+ const entries = isRecord(packages)
52
+ ? collectEntries(builder, packages)
53
+ : new Map<string, BunEntry>();
54
+
55
+ const keys = new Set(entries.keys());
56
+ for (const entry of entries.values()) {
57
+ builder.add({
58
+ name: entry.name,
59
+ version: entry.version,
60
+ dependencies: edgesOf(builder, entries, keys, entry),
61
+ });
62
+ }
63
+
64
+ collectRoots(builder, entries, keys, root["workspaces"], path, importer);
65
+
66
+ return builder.finish({ format: LockfileFormat.Bun, lockfileVersion: version, path, importer });
67
+ };
68
+
69
+ /**
70
+ * Narrows bun's tuple entries.
71
+ *
72
+ * The value is a positional array whose shape depends on where the package came
73
+ * from. A registry package is `[id, registry, info, integrity]`; a workspace
74
+ * member or a git dependency is shorter and its `id` carries the protocol.
75
+ */
76
+ const collectEntries = (
77
+ builder: TreeBuilder,
78
+ packages: Record<string, unknown>,
79
+ ): Map<string, BunEntry> => {
80
+ const entries = new Map<string, BunEntry>();
81
+
82
+ for (const [key, raw] of Object.entries(packages)) {
83
+ if (!Array.isArray(raw)) continue;
84
+
85
+ const [id, , info] = raw;
86
+ if (typeof id !== "string") continue;
87
+
88
+ const at = id.lastIndexOf("@");
89
+ if (at <= 0) continue;
90
+ const name = id.slice(0, at);
91
+ const spec = id.slice(at + 1);
92
+
93
+ const version = asExactVersion(name, spec);
94
+ if (version._tag === "Unsupported") {
95
+ builder.skip(name, spec, version.reason);
96
+ continue;
97
+ }
98
+
99
+ const details = isRecord(info) ? info : {};
100
+
101
+ entries.set(key, {
102
+ key,
103
+ name,
104
+ version: version.version,
105
+ dependencies: stringRecord(details["dependencies"]),
106
+ optionalDependencies: stringRecord(details["optionalDependencies"]),
107
+ peerDependencies: stringRecord(details["peerDependencies"]),
108
+ optionalPeers: collectOptionalPeers(details),
109
+ });
110
+ }
111
+
112
+ return entries;
113
+ };
114
+
115
+ /** bun lists optional peers as a name array rather than npm's metadata object. */
116
+ const collectOptionalPeers = (details: Record<string, unknown>): ReadonlySet<string> => {
117
+ const listed = details["optionalPeers"];
118
+ const names = Array.isArray(listed)
119
+ ? listed.flatMap((entry) => (typeof entry === "string" ? entry : []))
120
+ : [];
121
+ return new Set([...names, ...optionalPeerNames(details["peerDependenciesMeta"])]);
122
+ };
123
+
124
+ const edgesOf = (
125
+ builder: TreeBuilder,
126
+ entries: ReadonlyMap<string, BunEntry>,
127
+ keys: ReadonlySet<string>,
128
+ entry: BunEntry,
129
+ ): ReadonlyArray<LockedEdge> => {
130
+ const edges: Array<LockedEdge> = [];
131
+
132
+ const add = (names: ReadonlyArray<string>, kind: EdgeKind): void => {
133
+ for (const name of names) {
134
+ const target = findEntry(entries, keys, entry.key, name);
135
+ if (target === undefined) {
136
+ if (kind === EdgeKind.Prod)
137
+ builder.dangling(`${entry.name}@${entry.version}`, name);
138
+ continue;
139
+ }
140
+ edges.push({ name: target.name, version: target.version, kind });
141
+ }
142
+ };
143
+
144
+ add(Object.keys(entry.dependencies), EdgeKind.Prod);
145
+ add(Object.keys(entry.optionalDependencies), EdgeKind.Optional);
146
+ add(
147
+ Object.keys(entry.peerDependencies).filter((name) => !entry.optionalPeers.has(name)),
148
+ EdgeKind.Peer,
149
+ );
150
+
151
+ return edges;
152
+ };
153
+
154
+ const collectRoots = (
155
+ builder: TreeBuilder,
156
+ entries: ReadonlyMap<string, BunEntry>,
157
+ keys: ReadonlySet<string>,
158
+ workspaces: unknown,
159
+ path: string,
160
+ member: string | undefined,
161
+ ): void => {
162
+ if (!isRecord(workspaces)) return;
163
+
164
+ const selected =
165
+ member === undefined
166
+ ? Object.values(workspaces)
167
+ : Object.hasOwn(workspaces, importerKey(member))
168
+ ? [workspaces[importerKey(member)]]
169
+ : notCovered(path, member, workspacePaths(workspaces));
170
+
171
+ for (const workspace of selected) {
172
+ if (!isRecord(workspace)) continue;
173
+ for (const kind of ROOT_KINDS) {
174
+ const declared = stringRecord(workspace[fieldByRootKind[kind]]);
175
+ for (const [name, specifier] of Object.entries(declared)) {
176
+ const target = findEntry(entries, keys, "", name);
177
+ if (target === undefined) continue;
178
+ builder.addRoot({ name: target.name, version: target.version, kind, specifier });
179
+ }
180
+ }
181
+ }
182
+ };
183
+
184
+ const workspacePaths = (workspaces: Record<string, unknown>): ReadonlyArray<string> =>
185
+ Object.keys(workspaces).map((key) => (key === "" ? "." : key));
186
+
187
+ /**
188
+ * bun nests with a plain `/`, and package names contain `/` too, so a parent
189
+ * key cannot be found by string-splitting alone — `@babel/core` would split
190
+ * into a scope that is not a key. `parentKey` only accepts a prefix that is
191
+ * itself an entry, which resolves the ambiguity.
192
+ */
193
+ const findEntry = (
194
+ entries: ReadonlyMap<string, BunEntry>,
195
+ keys: ReadonlySet<string>,
196
+ fromKey: string,
197
+ name: string,
198
+ ): BunEntry | undefined => {
199
+ let scope = fromKey;
200
+ for (;;) {
201
+ const found = entries.get(scope === "" ? name : `${scope}/${name}`);
202
+ if (found !== undefined) return found;
203
+ if (scope === "") return undefined;
204
+ scope = parentKey(keys, scope);
205
+ }
206
+ };
207
+
208
+ const parentKey = (keys: ReadonlySet<string>, key: string): string => {
209
+ for (let at = key.lastIndexOf("/"); at > 0; at = key.lastIndexOf("/", at - 1)) {
210
+ const prefix = key.slice(0, at);
211
+ if (keys.has(prefix)) return prefix;
212
+ }
213
+ return "";
214
+ };
@@ -1,80 +1,80 @@
1
- /**
2
- * Working out which lockfile — if any — some content is.
3
- *
4
- * Detection is by content, matching how `--file` treats everything else: a
5
- * lockfile renamed to `deps.txt` still parses, and a `package-lock.json` that
6
- * is actually a package.json still gets read as one.
7
- */
8
- import { LockfileFormat } from "../enums/lockfile-format.js"
9
- import { tryParseJsonc } from "./json.js"
10
- import { isRecord } from "../utils/is-record.js"
11
-
12
- /** What a blob of file content turned out to be. */
13
- export type LockfileDetection =
14
- | { readonly _tag: "Supported"; readonly format: LockfileFormat }
15
- /**
16
- * Recognisably a lockfile, but not one we can read. Named explicitly so the
17
- * error says "yarn.lock is not supported yet" rather than leaving somebody to
18
- * work out why their file parsed as a spec list.
19
- */
20
- | { readonly _tag: "Unsupported"; readonly label: string; readonly hint: string }
21
- | { readonly _tag: "NotALockfile" }
22
-
23
- /**
24
- * Deliberately cheap and total: it never throws, so `--file` can try this
25
- * first and fall through to its other shapes when the answer is `NotALockfile`.
26
- */
27
- export const detectLockfile = (content: string): LockfileDetection => {
28
- const trimmed = content.trimStart()
29
-
30
- // bun's binary lockfile leads with its own magic string. Worth naming,
31
- // because `bun install` wrote this by default until 1.2 and the fix is one
32
- // command.
33
- if (trimmed.startsWith("bun-lockfile-format-v0")) {
34
- return {
35
- _tag: "Unsupported",
36
- label: "a binary bun lockfile (bun.lockb)",
37
- hint: "Run `bun install --save-text-lockfile` to produce a bun.lock, and pass that instead."
38
- }
39
- }
40
-
41
- if (/^__metadata:/m.test(trimmed) || /^# yarn lockfile v\d/m.test(trimmed)) {
42
- return {
43
- _tag: "Unsupported",
44
- label: "a yarn lockfile",
45
- hint: "yarn is not supported yet. Point --file at the package.json instead, or pass --lockfile off."
46
- }
47
- }
48
-
49
- if (trimmed.startsWith("{")) return detectJsonLockfile(trimmed)
50
-
51
- // pnpm is the only YAML one, and it always declares its version first.
52
- if (/^lockfileVersion:/m.test(trimmed) || /^(importers|snapshots):/m.test(trimmed)) {
53
- return { _tag: "Supported", format: LockfileFormat.Pnpm }
54
- }
55
-
56
- return { _tag: "NotALockfile" }
57
- }
58
-
59
- /**
60
- * Separates the two JSON lockfiles from each other and from a package.json.
61
- *
62
- * Both npm and bun write a numeric `lockfileVersion`, so that field alone
63
- * cannot decide it. bun is the one that carries a `workspaces` map keyed by the
64
- * empty string; npm keeps the root project under `packages[""]` instead.
65
- */
66
- const detectJsonLockfile = (trimmed: string): LockfileDetection => {
67
- const parsed = tryParseJsonc(trimmed)
68
- if (!isRecord(parsed)) return { _tag: "NotALockfile" }
69
-
70
- const workspaces = parsed["workspaces"]
71
- if (isRecord(workspaces) && Object.hasOwn(workspaces, "")) {
72
- return { _tag: "Supported", format: LockfileFormat.Bun }
73
- }
74
-
75
- if (typeof parsed["lockfileVersion"] === "number") {
76
- return { _tag: "Supported", format: LockfileFormat.Npm }
77
- }
78
-
79
- return { _tag: "NotALockfile" }
80
- }
1
+ /**
2
+ * Working out which lockfile — if any — some content is.
3
+ *
4
+ * Detection is by content, matching how `--file` treats everything else: a
5
+ * lockfile renamed to `deps.txt` still parses, and a `package-lock.json` that
6
+ * is actually a package.json still gets read as one.
7
+ */
8
+ import { LockfileFormat } from "../enums/lockfile-format.js";
9
+ import { isRecord } from "../utils/is-record.js";
10
+ import { tryParseJsonc } from "./json.js";
11
+
12
+ /** What a blob of file content turned out to be. */
13
+ export type LockfileDetection =
14
+ | { readonly _tag: "Supported"; readonly format: LockfileFormat }
15
+ /**
16
+ * Recognisably a lockfile, but not one we can read. Named explicitly so the
17
+ * error says "yarn.lock is not supported yet" rather than leaving somebody to
18
+ * work out why their file parsed as a spec list.
19
+ */
20
+ | { readonly _tag: "Unsupported"; readonly label: string; readonly hint: string }
21
+ | { readonly _tag: "NotALockfile" };
22
+
23
+ /**
24
+ * Deliberately cheap and total: it never throws, so `--file` can try this
25
+ * first and fall through to its other shapes when the answer is `NotALockfile`.
26
+ */
27
+ export const detectLockfile = (content: string): LockfileDetection => {
28
+ const trimmed = content.trimStart();
29
+
30
+ // bun's binary lockfile leads with its own magic string. Worth naming,
31
+ // because `bun install` wrote this by default until 1.2 and the fix is one
32
+ // command.
33
+ if (trimmed.startsWith("bun-lockfile-format-v0")) {
34
+ return {
35
+ _tag: "Unsupported",
36
+ label: "a binary bun lockfile (bun.lockb)",
37
+ hint: "Run `bun install --save-text-lockfile` to produce a bun.lock, and pass that instead.",
38
+ };
39
+ }
40
+
41
+ if (/^__metadata:/m.test(trimmed) || /^# yarn lockfile v\d/m.test(trimmed)) {
42
+ return {
43
+ _tag: "Unsupported",
44
+ label: "a yarn lockfile",
45
+ hint: "yarn is not supported yet. Point --file at the package.json instead, or pass --lockfile off.",
46
+ };
47
+ }
48
+
49
+ if (trimmed.startsWith("{")) return detectJsonLockfile(trimmed);
50
+
51
+ // pnpm is the only YAML one, and it always declares its version first.
52
+ if (/^lockfileVersion:/m.test(trimmed) || /^(importers|snapshots):/m.test(trimmed)) {
53
+ return { _tag: "Supported", format: LockfileFormat.Pnpm };
54
+ }
55
+
56
+ return { _tag: "NotALockfile" };
57
+ };
58
+
59
+ /**
60
+ * Separates the two JSON lockfiles from each other and from a package.json.
61
+ *
62
+ * Both npm and bun write a numeric `lockfileVersion`, so that field alone
63
+ * cannot decide it. bun is the one that carries a `workspaces` map keyed by the
64
+ * empty string; npm keeps the root project under `packages[""]` instead.
65
+ */
66
+ const detectJsonLockfile = (trimmed: string): LockfileDetection => {
67
+ const parsed = tryParseJsonc(trimmed);
68
+ if (!isRecord(parsed)) return { _tag: "NotALockfile" };
69
+
70
+ const workspaces = parsed["workspaces"];
71
+ if (isRecord(workspaces) && Object.hasOwn(workspaces, "")) {
72
+ return { _tag: "Supported", format: LockfileFormat.Bun };
73
+ }
74
+
75
+ if (typeof parsed["lockfileVersion"] === "number") {
76
+ return { _tag: "Supported", format: LockfileFormat.Npm };
77
+ }
78
+
79
+ return { _tag: "NotALockfile" };
80
+ };