@zyro-sec/util 1.0.2 → 1.0.4
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.
- package/docs/layer-node.md +155 -155
- package/package.json +1 -1
- package/script/build.ts +9 -9
- package/script/pack.ts +5 -5
- package/src/abort.ts +9 -9
- package/src/activity-calendar.ts +50 -50
- package/src/artifact.ts +95 -95
- package/src/base64.ts +29 -29
- package/src/binary.ts +30 -30
- package/src/bom.ts +46 -46
- package/src/cross-spawn-spawner.ts +694 -694
- package/src/duration.ts +22 -22
- package/src/effect/app-node-platform.ts +40 -40
- package/src/effect/app-node.ts +14 -14
- package/src/effect/layer-node.ts +360 -360
- package/src/effect-flock.ts +313 -313
- package/src/encode.ts +39 -39
- package/src/execute-output.ts +23 -23
- package/src/flock.ts +346 -346
- package/src/fs-util.ts +271 -271
- package/src/glob.ts +38 -38
- package/src/global-roots.ts +19 -19
- package/src/global-roots.workerd.ts +16 -16
- package/src/global.ts +88 -88
- package/src/hash.ts +11 -11
- package/src/heap-snapshot.ts +44 -44
- package/src/no-timeout-fetch.ts +5 -5
- package/src/npm-config.ts +41 -41
- package/src/npm.ts +557 -557
- package/src/observability/logging.ts +179 -179
- package/src/observability/otlp.ts +109 -109
- package/src/observability/shared.ts +8 -8
- package/src/observability.ts +60 -60
- package/src/open.ts +12 -12
- package/src/patch.ts +382 -382
- package/src/path.ts +149 -149
- package/src/process-signal.ts +23 -23
- package/src/process.ts +270 -270
- package/src/qr.ts +323 -323
- package/src/record.ts +3 -3
- package/src/retry.ts +51 -51
- package/src/runtime/import.bun.ts +10 -10
- package/src/runtime/import.node.ts +61 -61
- package/src/runtime/import.workerd.ts +9 -9
- package/src/runtime-import.ts +1 -1
- package/src/session-mention.ts +24 -24
- package/src/session-title-fallback.ts +36 -36
- package/src/session-turn.ts +82 -82
- package/src/teardown.ts +19 -19
- package/src/text-boundary.ts +36 -36
- package/src/uuid.ts +15 -15
- package/test/fixtures/qr.json +625 -625
- package/tsconfig.build.json +12 -12
- package/tsconfig.dist.json +10 -10
- package/tsconfig.json +14 -14
- package/src/abort.test.ts +0 -16
- package/src/activity-calendar.test.ts +0 -136
- package/src/artifact.test.ts +0 -29
- package/src/base64.test.ts +0 -12
- package/src/binary.test.ts +0 -19
- package/src/bom.test.ts +0 -21
- package/src/encode.test.ts +0 -32
- package/src/execute-output.test.ts +0 -36
- package/src/no-timeout-fetch.test.ts +0 -33
- package/src/open.test.ts +0 -16
- package/src/path.test.ts +0 -89
- package/src/process-signal.test.ts +0 -38
- package/src/retry.test.ts +0 -87
- package/src/session-mention.test.ts +0 -19
- package/src/session-turn.test.ts +0 -131
- package/src/text-boundary.test.ts +0 -39
- package/src/uuid.test.ts +0 -80
- package/test/glob.test.ts +0 -11
- package/test/global-roots.test.ts +0 -62
- package/test/global.test.ts +0 -99
- package/test/observability-otlp.test.ts +0 -45
- package/test/qr.test.ts +0 -113
- package/test/session-title-fallback.test.ts +0 -49
package/src/npm.ts
CHANGED
|
@@ -1,557 +1,557 @@
|
|
|
1
|
-
export * as Npm from "./npm.js"
|
|
2
|
-
|
|
3
|
-
import path from "path"
|
|
4
|
-
import { createHash, randomUUID } from "node:crypto"
|
|
5
|
-
import { Clock, Effect, Schema, Context, Layer, Option, FileSystem } from "effect"
|
|
6
|
-
import { FSUtil } from "./fs-util.js"
|
|
7
|
-
import { Global } from "./global.js"
|
|
8
|
-
import { EffectFlock } from "./effect-flock.js"
|
|
9
|
-
import { makeGlobalNode } from "./effect/app-node.js"
|
|
10
|
-
import { filesystem } from "./effect/app-node-platform.js"
|
|
11
|
-
import { NpmConfig } from "./npm-config.js"
|
|
12
|
-
|
|
13
|
-
export class InstallFailedError extends Schema.TaggedError<InstallFailedError>()("NpmInstallFailedError", {
|
|
14
|
-
add: Schema.Array(Schema.String).pipe(Schema.optional),
|
|
15
|
-
dir: Schema.String,
|
|
16
|
-
cause: Schema.optional(Schema.Defect()),
|
|
17
|
-
}) {
|
|
18
|
-
override get message() {
|
|
19
|
-
const summary = `Failed to install ${this.add?.join(", ") || this.dir}`
|
|
20
|
-
if (!(this.cause instanceof Error)) return summary
|
|
21
|
-
// @npmcli/git reports most failures as "An unknown git error occurred" and keeps git's output on `stderr`.
|
|
22
|
-
const stderr = "stderr" in this.cause && typeof this.cause.stderr === "string" ? this.cause.stderr.trim() : ""
|
|
23
|
-
if (!stderr) return `${summary}: ${this.cause.message}`
|
|
24
|
-
return `${summary}: ${this.cause.message}\n${stderr}`
|
|
25
|
-
}
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
export interface Package {
|
|
29
|
-
readonly directory: string
|
|
30
|
-
readonly name: string
|
|
31
|
-
readonly version?: string
|
|
32
|
-
readonly revision?: string
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
export interface Interface {
|
|
36
|
-
readonly add: (pkg: string) => Effect.Effect<Package, InstallFailedError | EffectFlock.LockError>
|
|
37
|
-
readonly resolve: (pkg: string) => Effect.Effect<Package>
|
|
38
|
-
readonly check: (pkg: string) => Effect.Effect<boolean, InstallFailedError>
|
|
39
|
-
readonly update: (pkg: string) => Effect.Effect<Package, InstallFailedError | EffectFlock.LockError>
|
|
40
|
-
/**
|
|
41
|
-
* Whether newer versions should install on their own because the package names what to follow: `name@latest`, a
|
|
42
|
-
* version range, a Git `semver:` range, or a Git ref the remote lists as a branch. A bare name or repository, other
|
|
43
|
-
* dist-tags, Git tags and commits stay on what's installed.
|
|
44
|
-
*/
|
|
45
|
-
readonly follows: (pkg: string) => Effect.Effect<boolean, InstallFailedError>
|
|
46
|
-
/**
|
|
47
|
-
* Stop using the newest installed version when it is `version`, so the previous one is current again. Its files stay
|
|
48
|
-
* until they expire, for anything still running it. False when it isn't the newest or there is no previous one.
|
|
49
|
-
*/
|
|
50
|
-
readonly reject: (pkg: string, version: string) => Effect.Effect<boolean, InstallFailedError | EffectFlock.LockError>
|
|
51
|
-
readonly which: (pkg: string, bin?: string) => Effect.Effect<string | undefined>
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
export class Service extends Context.Service<Service, Interface>()("@zyro-sec/Npm") {}
|
|
55
|
-
|
|
56
|
-
const illegal = process.platform === "win32" ? new Set(["<", ">", ":", '"', "|", "?", "*"]) : undefined
|
|
57
|
-
|
|
58
|
-
export function sanitize(pkg: string) {
|
|
59
|
-
if (!illegal) return pkg
|
|
60
|
-
return Array.from(pkg, (char) => (illegal.has(char) || char.charCodeAt(0) < 32 ? "_" : char)).join("")
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
export async function isRegistryPackage(pkg: string) {
|
|
64
|
-
return (await parse(pkg))?.type === "registry"
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
export async function isInstallablePackage(pkg: string) {
|
|
68
|
-
return (await parse(pkg)) !== undefined
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
export async function cacheKey(pkg: string) {
|
|
72
|
-
return key(pkg, await parse(pkg))
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
type Target =
|
|
76
|
-
| {
|
|
77
|
-
readonly type: "registry"
|
|
78
|
-
readonly name: string
|
|
79
|
-
readonly spec: string
|
|
80
|
-
readonly mutable: boolean
|
|
81
|
-
readonly follows: boolean
|
|
82
|
-
}
|
|
83
|
-
| {
|
|
84
|
-
readonly type: "git"
|
|
85
|
-
readonly name?: string
|
|
86
|
-
readonly slug: string
|
|
87
|
-
readonly mutable: boolean
|
|
88
|
-
readonly follows: boolean
|
|
89
|
-
/** A named ref that may be a branch or a tag. */
|
|
90
|
-
readonly ref?: string
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
async function parse(pkg: string): Promise<Target | undefined> {
|
|
94
|
-
const { default: npa } = await import("npm-package-arg")
|
|
95
|
-
try {
|
|
96
|
-
const result = npa(pkg)
|
|
97
|
-
if (result.type === "git") {
|
|
98
|
-
const mutable = !isCommit(result.gitCommittish)
|
|
99
|
-
return {
|
|
100
|
-
type: "git",
|
|
101
|
-
...(result.name ? { name: result.name } : {}),
|
|
102
|
-
slug: gitSlug(pkg),
|
|
103
|
-
mutable,
|
|
104
|
-
follows: Boolean(result.gitRange),
|
|
105
|
-
...(mutable && result.gitCommittish ? { ref: result.gitCommittish } : {}),
|
|
106
|
-
}
|
|
107
|
-
}
|
|
108
|
-
if (!result.name || !["version", "range", "tag"].includes(result.type)) return
|
|
109
|
-
return {
|
|
110
|
-
type: "registry",
|
|
111
|
-
name: result.name,
|
|
112
|
-
spec: result.raw === result.name ? "latest" : result.rawSpec,
|
|
113
|
-
mutable: result.type !== "version",
|
|
114
|
-
// npm parses a bare name as the range `*`; only a written `@latest` or range follows.
|
|
115
|
-
follows:
|
|
116
|
-
result.raw !== result.name &&
|
|
117
|
-
(result.type === "range" || (result.type === "tag" && result.rawSpec === "latest")),
|
|
118
|
-
}
|
|
119
|
-
} catch {
|
|
120
|
-
return
|
|
121
|
-
}
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
function key(pkg: string, target: Target | undefined) {
|
|
125
|
-
if (target?.type === "git")
|
|
126
|
-
return `git-${target.slug}-${createHash("sha256").update(pkg).digest("hex").slice(0, 12)}`
|
|
127
|
-
if (target?.type === "registry") return sanitize(`${target.name}@${target.spec}`)
|
|
128
|
-
return sanitize(pkg)
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
function gitSlug(pkg: string) {
|
|
132
|
-
const target = (() => {
|
|
133
|
-
try {
|
|
134
|
-
return decodeURIComponent(pkg.split("#")[0])
|
|
135
|
-
} catch {
|
|
136
|
-
return pkg.split("#")[0]
|
|
137
|
-
}
|
|
138
|
-
})()
|
|
139
|
-
return (
|
|
140
|
-
target
|
|
141
|
-
.replace(/\.git$/i, "")
|
|
142
|
-
.split(/[/:\\]/)
|
|
143
|
-
.at(-1)
|
|
144
|
-
?.replace(/[^a-zA-Z0-9._-]+/g, "-")
|
|
145
|
-
.replace(/^-+|-+$/g, "") || "repository"
|
|
146
|
-
)
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
interface ArboristNode {
|
|
150
|
-
name: string
|
|
151
|
-
path: string
|
|
152
|
-
realpath: string
|
|
153
|
-
isLink: boolean
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
interface ArboristTree {
|
|
157
|
-
edgesOut: Map<string, { to?: ArboristNode }>
|
|
158
|
-
inventory: { values(): IterableIterator<ArboristNode> }
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
const PackageJson = Schema.Struct({
|
|
162
|
-
dependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)),
|
|
163
|
-
version: Schema.optional(Schema.String),
|
|
164
|
-
})
|
|
165
|
-
|
|
166
|
-
const PackageLock = Schema.Struct({
|
|
167
|
-
packages: Schema.optional(Schema.Record(Schema.String, Schema.Struct({ resolved: Schema.optional(Schema.String) }))),
|
|
168
|
-
})
|
|
169
|
-
|
|
170
|
-
const retention = 7 * 24 * 60 * 60 * 1_000
|
|
171
|
-
const stagingRetention = 60 * 60 * 1_000
|
|
172
|
-
|
|
173
|
-
const layer = Layer.effect(
|
|
174
|
-
Service,
|
|
175
|
-
Effect.gen(function* () {
|
|
176
|
-
const afs = yield* FSUtil.Service
|
|
177
|
-
const global = yield* Global.Service
|
|
178
|
-
const fs = yield* FileSystem.FileSystem
|
|
179
|
-
const flock = yield* EffectFlock.Service
|
|
180
|
-
const directory = (pkg: string, target: Target | undefined) => path.join(global.cache, "npm", key(pkg, target))
|
|
181
|
-
const generations = Effect.fnUntraced(function* (dir: string) {
|
|
182
|
-
return yield* fs.readDirectory(dir).pipe(
|
|
183
|
-
Effect.orElseSucceed(() => [] as string[]),
|
|
184
|
-
Effect.map((entries) =>
|
|
185
|
-
entries
|
|
186
|
-
.filter((entry) => /^\d+$/.test(entry) && !entries.includes(`${entry}.rejected`))
|
|
187
|
-
.toSorted((a, b) => Number(a) - Number(b)),
|
|
188
|
-
),
|
|
189
|
-
)
|
|
190
|
-
})
|
|
191
|
-
const current = Effect.fnUntraced(function* (dir: string) {
|
|
192
|
-
const latest = (yield* generations(dir)).at(-1)
|
|
193
|
-
return latest ? path.join(dir, latest) : undefined
|
|
194
|
-
})
|
|
195
|
-
const mkdir = (dir: string) =>
|
|
196
|
-
fs.makeDirectory(dir, { recursive: true }).pipe(
|
|
197
|
-
Effect.mapError((cause) => new InstallFailedError({ dir, cause })),
|
|
198
|
-
)
|
|
199
|
-
const remove = (target: string, dir: string) =>
|
|
200
|
-
fs.remove(target, { recursive: true, force: true }).pipe(
|
|
201
|
-
Effect.mapError((cause) => new InstallFailedError({ dir, cause })),
|
|
202
|
-
)
|
|
203
|
-
const rename = (from: string, to: string, dir: string) =>
|
|
204
|
-
fs.rename(from, to).pipe(Effect.mapError((cause) => new InstallFailedError({ dir, cause })))
|
|
205
|
-
const installedName = Effect.fnUntraced(function* (pkg: string, dir: string, target?: Target) {
|
|
206
|
-
if (target?.name) return target.name
|
|
207
|
-
const manifest = yield* afs
|
|
208
|
-
.readJson(path.join(dir, "package.json"))
|
|
209
|
-
.pipe(Effect.flatMap(Schema.decodeUnknownEffect(PackageJson)), Effect.option)
|
|
210
|
-
if (Option.isSome(manifest)) {
|
|
211
|
-
const name = Object.keys(manifest.value.dependencies ?? {})[0]
|
|
212
|
-
if (name) return name
|
|
213
|
-
}
|
|
214
|
-
return pkg
|
|
215
|
-
})
|
|
216
|
-
const installedRevision = Effect.fnUntraced(function* (root: string, name: string, target: Target) {
|
|
217
|
-
const dir = path.join(root, "node_modules", name)
|
|
218
|
-
if (target.type === "registry") {
|
|
219
|
-
const manifest = yield* afs
|
|
220
|
-
.readJson(path.join(dir, "package.json"))
|
|
221
|
-
.pipe(Effect.flatMap(Schema.decodeUnknownEffect(PackageJson)), Effect.option)
|
|
222
|
-
return Option.isSome(manifest) ? manifest.value.version : undefined
|
|
223
|
-
}
|
|
224
|
-
for (const file of [path.join(root, "package-lock.json"), path.join(root, "node_modules", ".package-lock.json")]) {
|
|
225
|
-
const lock = yield* afs
|
|
226
|
-
.readJson(file)
|
|
227
|
-
.pipe(Effect.flatMap(Schema.decodeUnknownEffect(PackageLock)), Effect.option)
|
|
228
|
-
const revision = gitRevision(
|
|
229
|
-
Option.isSome(lock) ? lock.value.packages?.[`node_modules/${name}`]?.resolved : undefined,
|
|
230
|
-
)
|
|
231
|
-
if (revision) return revision
|
|
232
|
-
}
|
|
233
|
-
})
|
|
234
|
-
const metadata = Effect.fnUntraced(function* (root: string, name: string, dir: string, target: Target | undefined) {
|
|
235
|
-
const manifest = yield* afs
|
|
236
|
-
.readJson(path.join(dir, "package.json"))
|
|
237
|
-
.pipe(Effect.flatMap(Schema.decodeUnknownEffect(PackageJson)), Effect.option)
|
|
238
|
-
const manifestVersion = Option.isSome(manifest) ? manifest.value.version : undefined
|
|
239
|
-
const revision = target ? (yield* installedRevision(root, name, target)) ?? manifestVersion : undefined
|
|
240
|
-
const version = target?.type === "git" ? revision : manifestVersion
|
|
241
|
-
return {
|
|
242
|
-
directory: dir,
|
|
243
|
-
name,
|
|
244
|
-
...(version ? { version } : {}),
|
|
245
|
-
...(revision ? { revision } : {}),
|
|
246
|
-
}
|
|
247
|
-
})
|
|
248
|
-
const reify = (input: { dir: string; config?: string; add?: string[]; update?: boolean }) =>
|
|
249
|
-
Effect.gen(function* () {
|
|
250
|
-
const { Arborist } = yield* Effect.promise(() => import("@npmcli/arborist"))
|
|
251
|
-
const add = input.add ?? []
|
|
252
|
-
const options = {
|
|
253
|
-
...(yield* NpmConfig.load(input.config ?? input.dir)),
|
|
254
|
-
...(input.update ? { preferOnline: true, noGitRevCache: true } : {}),
|
|
255
|
-
// Audit reports are unused here, but Arborist waits for them before completing an install.
|
|
256
|
-
audit: false,
|
|
257
|
-
windowsHide: true,
|
|
258
|
-
}
|
|
259
|
-
const arborist = new Arborist({
|
|
260
|
-
...options,
|
|
261
|
-
path: input.dir,
|
|
262
|
-
binLinks: true,
|
|
263
|
-
progress: false,
|
|
264
|
-
savePrefix: "",
|
|
265
|
-
ignoreScripts: true,
|
|
266
|
-
})
|
|
267
|
-
return yield* Effect.tryPromise({
|
|
268
|
-
try: () =>
|
|
269
|
-
arborist.reify({
|
|
270
|
-
...options,
|
|
271
|
-
add,
|
|
272
|
-
update: input.update,
|
|
273
|
-
save: true,
|
|
274
|
-
saveType: "prod",
|
|
275
|
-
}),
|
|
276
|
-
catch: (cause) =>
|
|
277
|
-
new InstallFailedError({
|
|
278
|
-
cause,
|
|
279
|
-
add,
|
|
280
|
-
dir: input.dir,
|
|
281
|
-
}),
|
|
282
|
-
}) as Effect.Effect<ArboristTree, InstallFailedError>
|
|
283
|
-
}).pipe(
|
|
284
|
-
Effect.withSpan("Npm.reify", {
|
|
285
|
-
attributes: input,
|
|
286
|
-
}),
|
|
287
|
-
)
|
|
288
|
-
|
|
289
|
-
const install = Effect.fnUntraced(function* (
|
|
290
|
-
pkg: string,
|
|
291
|
-
target: Target | undefined,
|
|
292
|
-
dir: string,
|
|
293
|
-
update: boolean,
|
|
294
|
-
) {
|
|
295
|
-
yield* flock.acquire(`npm-install:${dir}`)
|
|
296
|
-
const active = yield* current(dir)
|
|
297
|
-
const name = yield* installedName(pkg, active ?? dir, target)
|
|
298
|
-
if (active && !update && (yield* afs.existsSafe(path.join(active, "node_modules", name)))) {
|
|
299
|
-
return yield* metadata(active, name, path.join(active, "node_modules", name), target)
|
|
300
|
-
}
|
|
301
|
-
|
|
302
|
-
yield* mkdir(dir)
|
|
303
|
-
const startedAt = yield* Clock.currentTimeMillis
|
|
304
|
-
// Arborist keys lockfile entries relative to the root's real path. When the cache
|
|
305
|
-
// directory is reached through a symlink (macOS `/var` → `/private/var`, a linked
|
|
306
|
-
// XDG cache), the keys become `../../…` paths that installedRevision never finds,
|
|
307
|
-
// so Git checks report "not installed" and updates go undetected. Stage under the
|
|
308
|
-
// resolved directory so the root path and real path agree.
|
|
309
|
-
const root = yield* fs.realPath(dir).pipe(Effect.mapError((cause) => new InstallFailedError({ dir, cause })))
|
|
310
|
-
const staging = path.join(root, `.staging-${startedAt}-${randomUUID()}`)
|
|
311
|
-
const staged = yield* Effect.gen(function* () {
|
|
312
|
-
const tree = yield* reify({ dir: staging, config: dir, add: [pkg], update })
|
|
313
|
-
const installed = tree.edgesOut.values().next().value?.to
|
|
314
|
-
const installedNameValue = installed?.name ?? (yield* installedName(pkg, staging, target))
|
|
315
|
-
const result = yield* metadata(
|
|
316
|
-
staging,
|
|
317
|
-
installedNameValue,
|
|
318
|
-
installed?.path ?? path.join(staging, "node_modules", installedNameValue),
|
|
319
|
-
target,
|
|
320
|
-
)
|
|
321
|
-
if (!installed && !(yield* afs.isDir(result.directory)))
|
|
322
|
-
return yield* new InstallFailedError({ add: [pkg], dir: staging })
|
|
323
|
-
const links =
|
|
324
|
-
process.platform === "win32"
|
|
325
|
-
? Array.from(tree.inventory.values()).filter(
|
|
326
|
-
(node) => node.isLink && FSUtil.contains(staging, node.path) && FSUtil.contains(staging, node.realpath),
|
|
327
|
-
)
|
|
328
|
-
: []
|
|
329
|
-
return { result, links }
|
|
330
|
-
}).pipe(Effect.onError(() => remove(staging, dir).pipe(Effect.ignore)))
|
|
331
|
-
|
|
332
|
-
if (active) {
|
|
333
|
-
const activeEntry = yield* metadata(active, name, path.join(active, "node_modules", name), target)
|
|
334
|
-
if (activeEntry.revision && activeEntry.revision === staged.result.revision) {
|
|
335
|
-
yield* remove(staging, dir)
|
|
336
|
-
return activeEntry
|
|
337
|
-
}
|
|
338
|
-
}
|
|
339
|
-
|
|
340
|
-
const completedAt = yield* Clock.currentTimeMillis
|
|
341
|
-
const newest = Number((yield* generations(dir)).at(-1) ?? 0)
|
|
342
|
-
const generation = path.join(dir, String(Math.max(completedAt, newest + 1)))
|
|
343
|
-
// Windows junctions use absolute targets, so rebase internal links before publishing the generation.
|
|
344
|
-
if (staged.links.length > 0) {
|
|
345
|
-
const { unlink, symlink } = yield* Effect.promise(() => import("node:fs/promises"))
|
|
346
|
-
yield* Effect.forEach(
|
|
347
|
-
staged.links,
|
|
348
|
-
(link) =>
|
|
349
|
-
Effect.tryPromise({
|
|
350
|
-
try: async () => {
|
|
351
|
-
await unlink(link.path)
|
|
352
|
-
await symlink(path.join(generation, path.relative(staging, link.realpath)), link.path, "junction")
|
|
353
|
-
},
|
|
354
|
-
catch: (cause) => new InstallFailedError({ dir, cause }),
|
|
355
|
-
}),
|
|
356
|
-
{ discard: true },
|
|
357
|
-
).pipe(Effect.onError(() => remove(staging, dir).pipe(Effect.ignore)))
|
|
358
|
-
}
|
|
359
|
-
yield* rename(staging, generation, dir)
|
|
360
|
-
return { ...staged.result, directory: path.join(generation, "node_modules", staged.result.name) }
|
|
361
|
-
})
|
|
362
|
-
|
|
363
|
-
const collect = Effect.fnUntraced(function* (dir: string) {
|
|
364
|
-
const now = yield* Clock.currentTimeMillis
|
|
365
|
-
const completed = yield* generations(dir)
|
|
366
|
-
const keep = new Set(completed.slice(-2))
|
|
367
|
-
const entries = yield* fs.readDirectory(dir).pipe(Effect.orElseSucceed(() => [] as string[]))
|
|
368
|
-
yield* Effect.forEach(
|
|
369
|
-
entries,
|
|
370
|
-
(name) => {
|
|
371
|
-
const timestamp = /^\d+(\.rejected)?$/.test(name)
|
|
372
|
-
? Number(name.split(".")[0])
|
|
373
|
-
: Number(name.match(/^\.staging-(\d+)-/)?.[1] ?? Number.NaN)
|
|
374
|
-
const maximumAge = name.startsWith(".staging-") ? stagingRetention : retention
|
|
375
|
-
if (!Number.isFinite(timestamp) || keep.has(name) || now - timestamp <= maximumAge) return Effect.void
|
|
376
|
-
return remove(path.join(dir, name), dir).pipe(
|
|
377
|
-
Effect.catchCause((cause) => Effect.logWarning("failed to remove stale npm generation", { dir, name, cause })),
|
|
378
|
-
)
|
|
379
|
-
},
|
|
380
|
-
{ concurrency: "unbounded", discard: true },
|
|
381
|
-
)
|
|
382
|
-
})
|
|
383
|
-
|
|
384
|
-
const add = Effect.fn("Npm.add")(function* (pkg: string) {
|
|
385
|
-
const target = yield* Effect.promise(() => parse(pkg))
|
|
386
|
-
const dir = directory(pkg, target)
|
|
387
|
-
return yield* install(pkg, target, dir, false)
|
|
388
|
-
}, Effect.scoped)
|
|
389
|
-
|
|
390
|
-
const resolve = Effect.fn("Npm.resolve")(function* (pkg: string) {
|
|
391
|
-
const target = yield* Effect.promise(() => parse(pkg))
|
|
392
|
-
const root = directory(pkg, target)
|
|
393
|
-
const generation = yield* current(root)
|
|
394
|
-
const name = yield* installedName(pkg, generation ?? root, target)
|
|
395
|
-
const dir = path.join(generation ?? root, "node_modules", name)
|
|
396
|
-
if (!(yield* afs.existsSafe(dir))) return { directory: dir, name }
|
|
397
|
-
return yield* metadata(generation ?? root, name, dir, target)
|
|
398
|
-
})
|
|
399
|
-
|
|
400
|
-
const check = Effect.fn("Npm.check")(function* (pkg: string) {
|
|
401
|
-
const target = yield* Effect.promise(() => parse(pkg))
|
|
402
|
-
const root = directory(pkg, target)
|
|
403
|
-
if (!target)
|
|
404
|
-
return yield* new InstallFailedError({
|
|
405
|
-
dir: root,
|
|
406
|
-
cause: new Error("Package checks only support registry and Git package specs"),
|
|
407
|
-
})
|
|
408
|
-
if (!target.mutable) return false
|
|
409
|
-
const generation = yield* current(root)
|
|
410
|
-
const name = yield* installedName(pkg, generation ?? root, target)
|
|
411
|
-
const installed = generation ? yield* installedRevision(generation, name, target) : undefined
|
|
412
|
-
if (!installed)
|
|
413
|
-
return yield* new InstallFailedError({ dir: root, cause: new Error(`Package is not installed: ${pkg}`) })
|
|
414
|
-
const { manifest, resolve } = yield* Effect.promise(() => import("pacote"))
|
|
415
|
-
const options = {
|
|
416
|
-
...(yield* NpmConfig.load(root)),
|
|
417
|
-
preferOnline: true,
|
|
418
|
-
noGitRevCache: true,
|
|
419
|
-
ignoreScripts: true,
|
|
420
|
-
// Pacote spawns Git directly rather than through AppProcess.
|
|
421
|
-
windowsHide: true,
|
|
422
|
-
}
|
|
423
|
-
const available = yield* Effect.tryPromise({
|
|
424
|
-
try: async () =>
|
|
425
|
-
target.type === "git" ? gitRevision(await resolve(pkg, options)) : (await manifest(pkg, options)).version,
|
|
426
|
-
catch: (cause) => new InstallFailedError({ dir: root, cause }),
|
|
427
|
-
})
|
|
428
|
-
if (!available)
|
|
429
|
-
return yield* new InstallFailedError({ dir: root, cause: new Error(`Package revision not found: ${pkg}`) })
|
|
430
|
-
return installed !== available
|
|
431
|
-
})
|
|
432
|
-
|
|
433
|
-
const update = Effect.fn("Npm.update")(function* (pkg: string) {
|
|
434
|
-
const target = yield* Effect.promise(() => parse(pkg))
|
|
435
|
-
const dir = directory(pkg, target)
|
|
436
|
-
if (!target)
|
|
437
|
-
return yield* new InstallFailedError({
|
|
438
|
-
dir,
|
|
439
|
-
cause: new Error("Package updates only support registry and Git package specs"),
|
|
440
|
-
})
|
|
441
|
-
if (!target.mutable) return yield* add(pkg)
|
|
442
|
-
const installed = yield* install(pkg, target, dir, true)
|
|
443
|
-
yield* collect(dir)
|
|
444
|
-
return installed
|
|
445
|
-
}, Effect.scoped)
|
|
446
|
-
|
|
447
|
-
const follows = Effect.fn("Npm.follows")(function* (pkg: string) {
|
|
448
|
-
const target = yield* Effect.promise(() => parse(pkg))
|
|
449
|
-
if (target?.type !== "git" || !target.ref) return target?.follows ?? false
|
|
450
|
-
const root = directory(pkg, target)
|
|
451
|
-
// Only the remote knows whether a ref is a branch or a tag. pacote keeps the ref it resolved, and Git reuses the
|
|
452
|
-
// refs the update check just listed for a few minutes, so this usually doesn't ask the remote again.
|
|
453
|
-
const { GitFetcher } = (yield* Effect.promise(() => import("pacote"))) as unknown as {
|
|
454
|
-
GitFetcher: new (
|
|
455
|
-
spec: string,
|
|
456
|
-
options: Record<string, unknown>,
|
|
457
|
-
) => { resolve(): Promise<string>; resolvedRef: { readonly type: string } | null }
|
|
458
|
-
}
|
|
459
|
-
const fetcher = new GitFetcher(pkg, { ...(yield* NpmConfig.load(root)), ignoreScripts: true, windowsHide: true })
|
|
460
|
-
yield* Effect.tryPromise({
|
|
461
|
-
try: () => fetcher.resolve(),
|
|
462
|
-
catch: (cause) => new InstallFailedError({ dir: root, cause }),
|
|
463
|
-
})
|
|
464
|
-
return fetcher.resolvedRef?.type === "branch"
|
|
465
|
-
})
|
|
466
|
-
|
|
467
|
-
const reject = Effect.fn("Npm.reject")(function* (pkg: string, version: string) {
|
|
468
|
-
const target = yield* Effect.promise(() => parse(pkg))
|
|
469
|
-
const dir = directory(pkg, target)
|
|
470
|
-
yield* flock.acquire(`npm-install:${dir}`)
|
|
471
|
-
const completed = yield* generations(dir)
|
|
472
|
-
const newest = completed.at(-1)
|
|
473
|
-
if (completed.length < 2 || !newest) return false
|
|
474
|
-
const root = path.join(dir, newest)
|
|
475
|
-
const name = yield* installedName(pkg, root, target)
|
|
476
|
-
if ((yield* metadata(root, name, path.join(root, "node_modules", name), target)).version !== version) return false
|
|
477
|
-
yield* fs
|
|
478
|
-
.writeFileString(path.join(dir, `${newest}.rejected`), "")
|
|
479
|
-
.pipe(Effect.mapError((cause) => new InstallFailedError({ dir, cause })))
|
|
480
|
-
return true
|
|
481
|
-
}, Effect.scoped)
|
|
482
|
-
|
|
483
|
-
const which = Effect.fn("Npm.which")(function* (pkg: string, bin?: string) {
|
|
484
|
-
const target = yield* Effect.promise(() => parse(pkg))
|
|
485
|
-
const root = directory(pkg, target)
|
|
486
|
-
|
|
487
|
-
const pick = Effect.fnUntraced(function* (dir: string) {
|
|
488
|
-
const binDir = path.join(dir, "node_modules", ".bin")
|
|
489
|
-
const files = yield* fs.readDirectory(binDir).pipe(Effect.orElseSucceed(() => [] as string[]))
|
|
490
|
-
|
|
491
|
-
if (files.length === 0) return Option.none<string>()
|
|
492
|
-
// Caller picked a specific bin (e.g. pyright exposes both `pyright` and
|
|
493
|
-
// `pyright-langserver`); trust the hint if the package provides it.
|
|
494
|
-
if (bin) return files.includes(bin) ? Option.some(path.join(binDir, bin)) : Option.none<string>()
|
|
495
|
-
if (files.length === 1) return Option.some(path.join(binDir, files[0]))
|
|
496
|
-
|
|
497
|
-
const packageName = target?.name ?? pkg
|
|
498
|
-
const pkgJson = yield* afs.readJson(path.join(dir, "node_modules", packageName, "package.json")).pipe(Effect.option)
|
|
499
|
-
|
|
500
|
-
if (Option.isSome(pkgJson)) {
|
|
501
|
-
const parsed = pkgJson.value as { bin?: string | Record<string, string> }
|
|
502
|
-
if (parsed?.bin) {
|
|
503
|
-
const unscoped = packageName.startsWith("@") ? packageName.split("/")[1] : packageName
|
|
504
|
-
const parsedBin = parsed.bin
|
|
505
|
-
if (typeof parsedBin === "string") return Option.some(path.join(binDir, unscoped))
|
|
506
|
-
const keys = Object.keys(parsedBin)
|
|
507
|
-
const selected = parsedBin[unscoped] ? unscoped : keys[0]
|
|
508
|
-
return selected ? Option.some(path.join(binDir, selected)) : Option.none<string>()
|
|
509
|
-
}
|
|
510
|
-
}
|
|
511
|
-
|
|
512
|
-
return Option.some(path.join(binDir, files[0]))
|
|
513
|
-
})
|
|
514
|
-
|
|
515
|
-
return Option.getOrUndefined(
|
|
516
|
-
yield* Effect.gen(function* () {
|
|
517
|
-
const generation = yield* current(root)
|
|
518
|
-
const selected = generation ? yield* pick(generation) : Option.none<string>()
|
|
519
|
-
if (Option.isSome(selected)) return selected
|
|
520
|
-
|
|
521
|
-
yield* add(pkg)
|
|
522
|
-
|
|
523
|
-
const installed = yield* current(root)
|
|
524
|
-
if (!installed) return Option.none<string>()
|
|
525
|
-
return yield* pick(installed)
|
|
526
|
-
}).pipe(
|
|
527
|
-
Effect.scoped,
|
|
528
|
-
Effect.orElseSucceed(() => Option.none<string>()),
|
|
529
|
-
),
|
|
530
|
-
)
|
|
531
|
-
})
|
|
532
|
-
|
|
533
|
-
return Service.of({
|
|
534
|
-
add,
|
|
535
|
-
resolve,
|
|
536
|
-
check,
|
|
537
|
-
update,
|
|
538
|
-
follows,
|
|
539
|
-
reject,
|
|
540
|
-
which,
|
|
541
|
-
})
|
|
542
|
-
}),
|
|
543
|
-
)
|
|
544
|
-
|
|
545
|
-
export const node = makeGlobalNode({
|
|
546
|
-
service: Service,
|
|
547
|
-
layer: layer,
|
|
548
|
-
deps: [FSUtil.node, Global.node, filesystem, EffectFlock.node],
|
|
549
|
-
})
|
|
550
|
-
|
|
551
|
-
function gitRevision(resolved: string | undefined) {
|
|
552
|
-
return resolved?.match(/#([a-f0-9]{40}|[a-f0-9]{64})(?=::|$)/i)?.[1]
|
|
553
|
-
}
|
|
554
|
-
|
|
555
|
-
function isCommit(value: string | null | undefined) {
|
|
556
|
-
return /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(value ?? "")
|
|
557
|
-
}
|
|
1
|
+
export * as Npm from "./npm.js"
|
|
2
|
+
|
|
3
|
+
import path from "path"
|
|
4
|
+
import { createHash, randomUUID } from "node:crypto"
|
|
5
|
+
import { Clock, Effect, Schema, Context, Layer, Option, FileSystem } from "effect"
|
|
6
|
+
import { FSUtil } from "./fs-util.js"
|
|
7
|
+
import { Global } from "./global.js"
|
|
8
|
+
import { EffectFlock } from "./effect-flock.js"
|
|
9
|
+
import { makeGlobalNode } from "./effect/app-node.js"
|
|
10
|
+
import { filesystem } from "./effect/app-node-platform.js"
|
|
11
|
+
import { NpmConfig } from "./npm-config.js"
|
|
12
|
+
|
|
13
|
+
export class InstallFailedError extends Schema.TaggedError<InstallFailedError>()("NpmInstallFailedError", {
|
|
14
|
+
add: Schema.Array(Schema.String).pipe(Schema.optional),
|
|
15
|
+
dir: Schema.String,
|
|
16
|
+
cause: Schema.optional(Schema.Defect()),
|
|
17
|
+
}) {
|
|
18
|
+
override get message() {
|
|
19
|
+
const summary = `Failed to install ${this.add?.join(", ") || this.dir}`
|
|
20
|
+
if (!(this.cause instanceof Error)) return summary
|
|
21
|
+
// @npmcli/git reports most failures as "An unknown git error occurred" and keeps git's output on `stderr`.
|
|
22
|
+
const stderr = "stderr" in this.cause && typeof this.cause.stderr === "string" ? this.cause.stderr.trim() : ""
|
|
23
|
+
if (!stderr) return `${summary}: ${this.cause.message}`
|
|
24
|
+
return `${summary}: ${this.cause.message}\n${stderr}`
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface Package {
|
|
29
|
+
readonly directory: string
|
|
30
|
+
readonly name: string
|
|
31
|
+
readonly version?: string
|
|
32
|
+
readonly revision?: string
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface Interface {
|
|
36
|
+
readonly add: (pkg: string) => Effect.Effect<Package, InstallFailedError | EffectFlock.LockError>
|
|
37
|
+
readonly resolve: (pkg: string) => Effect.Effect<Package>
|
|
38
|
+
readonly check: (pkg: string) => Effect.Effect<boolean, InstallFailedError>
|
|
39
|
+
readonly update: (pkg: string) => Effect.Effect<Package, InstallFailedError | EffectFlock.LockError>
|
|
40
|
+
/**
|
|
41
|
+
* Whether newer versions should install on their own because the package names what to follow: `name@latest`, a
|
|
42
|
+
* version range, a Git `semver:` range, or a Git ref the remote lists as a branch. A bare name or repository, other
|
|
43
|
+
* dist-tags, Git tags and commits stay on what's installed.
|
|
44
|
+
*/
|
|
45
|
+
readonly follows: (pkg: string) => Effect.Effect<boolean, InstallFailedError>
|
|
46
|
+
/**
|
|
47
|
+
* Stop using the newest installed version when it is `version`, so the previous one is current again. Its files stay
|
|
48
|
+
* until they expire, for anything still running it. False when it isn't the newest or there is no previous one.
|
|
49
|
+
*/
|
|
50
|
+
readonly reject: (pkg: string, version: string) => Effect.Effect<boolean, InstallFailedError | EffectFlock.LockError>
|
|
51
|
+
readonly which: (pkg: string, bin?: string) => Effect.Effect<string | undefined>
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export class Service extends Context.Service<Service, Interface>()("@zyro-sec/Npm") {}
|
|
55
|
+
|
|
56
|
+
const illegal = process.platform === "win32" ? new Set(["<", ">", ":", '"', "|", "?", "*"]) : undefined
|
|
57
|
+
|
|
58
|
+
export function sanitize(pkg: string) {
|
|
59
|
+
if (!illegal) return pkg
|
|
60
|
+
return Array.from(pkg, (char) => (illegal.has(char) || char.charCodeAt(0) < 32 ? "_" : char)).join("")
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export async function isRegistryPackage(pkg: string) {
|
|
64
|
+
return (await parse(pkg))?.type === "registry"
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export async function isInstallablePackage(pkg: string) {
|
|
68
|
+
return (await parse(pkg)) !== undefined
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export async function cacheKey(pkg: string) {
|
|
72
|
+
return key(pkg, await parse(pkg))
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
type Target =
|
|
76
|
+
| {
|
|
77
|
+
readonly type: "registry"
|
|
78
|
+
readonly name: string
|
|
79
|
+
readonly spec: string
|
|
80
|
+
readonly mutable: boolean
|
|
81
|
+
readonly follows: boolean
|
|
82
|
+
}
|
|
83
|
+
| {
|
|
84
|
+
readonly type: "git"
|
|
85
|
+
readonly name?: string
|
|
86
|
+
readonly slug: string
|
|
87
|
+
readonly mutable: boolean
|
|
88
|
+
readonly follows: boolean
|
|
89
|
+
/** A named ref that may be a branch or a tag. */
|
|
90
|
+
readonly ref?: string
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
async function parse(pkg: string): Promise<Target | undefined> {
|
|
94
|
+
const { default: npa } = await import("npm-package-arg")
|
|
95
|
+
try {
|
|
96
|
+
const result = npa(pkg)
|
|
97
|
+
if (result.type === "git") {
|
|
98
|
+
const mutable = !isCommit(result.gitCommittish)
|
|
99
|
+
return {
|
|
100
|
+
type: "git",
|
|
101
|
+
...(result.name ? { name: result.name } : {}),
|
|
102
|
+
slug: gitSlug(pkg),
|
|
103
|
+
mutable,
|
|
104
|
+
follows: Boolean(result.gitRange),
|
|
105
|
+
...(mutable && result.gitCommittish ? { ref: result.gitCommittish } : {}),
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
if (!result.name || !["version", "range", "tag"].includes(result.type)) return
|
|
109
|
+
return {
|
|
110
|
+
type: "registry",
|
|
111
|
+
name: result.name,
|
|
112
|
+
spec: result.raw === result.name ? "latest" : result.rawSpec,
|
|
113
|
+
mutable: result.type !== "version",
|
|
114
|
+
// npm parses a bare name as the range `*`; only a written `@latest` or range follows.
|
|
115
|
+
follows:
|
|
116
|
+
result.raw !== result.name &&
|
|
117
|
+
(result.type === "range" || (result.type === "tag" && result.rawSpec === "latest")),
|
|
118
|
+
}
|
|
119
|
+
} catch {
|
|
120
|
+
return
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function key(pkg: string, target: Target | undefined) {
|
|
125
|
+
if (target?.type === "git")
|
|
126
|
+
return `git-${target.slug}-${createHash("sha256").update(pkg).digest("hex").slice(0, 12)}`
|
|
127
|
+
if (target?.type === "registry") return sanitize(`${target.name}@${target.spec}`)
|
|
128
|
+
return sanitize(pkg)
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function gitSlug(pkg: string) {
|
|
132
|
+
const target = (() => {
|
|
133
|
+
try {
|
|
134
|
+
return decodeURIComponent(pkg.split("#")[0])
|
|
135
|
+
} catch {
|
|
136
|
+
return pkg.split("#")[0]
|
|
137
|
+
}
|
|
138
|
+
})()
|
|
139
|
+
return (
|
|
140
|
+
target
|
|
141
|
+
.replace(/\.git$/i, "")
|
|
142
|
+
.split(/[/:\\]/)
|
|
143
|
+
.at(-1)
|
|
144
|
+
?.replace(/[^a-zA-Z0-9._-]+/g, "-")
|
|
145
|
+
.replace(/^-+|-+$/g, "") || "repository"
|
|
146
|
+
)
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
interface ArboristNode {
|
|
150
|
+
name: string
|
|
151
|
+
path: string
|
|
152
|
+
realpath: string
|
|
153
|
+
isLink: boolean
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
interface ArboristTree {
|
|
157
|
+
edgesOut: Map<string, { to?: ArboristNode }>
|
|
158
|
+
inventory: { values(): IterableIterator<ArboristNode> }
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const PackageJson = Schema.Struct({
|
|
162
|
+
dependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)),
|
|
163
|
+
version: Schema.optional(Schema.String),
|
|
164
|
+
})
|
|
165
|
+
|
|
166
|
+
const PackageLock = Schema.Struct({
|
|
167
|
+
packages: Schema.optional(Schema.Record(Schema.String, Schema.Struct({ resolved: Schema.optional(Schema.String) }))),
|
|
168
|
+
})
|
|
169
|
+
|
|
170
|
+
const retention = 7 * 24 * 60 * 60 * 1_000
|
|
171
|
+
const stagingRetention = 60 * 60 * 1_000
|
|
172
|
+
|
|
173
|
+
const layer = Layer.effect(
|
|
174
|
+
Service,
|
|
175
|
+
Effect.gen(function* () {
|
|
176
|
+
const afs = yield* FSUtil.Service
|
|
177
|
+
const global = yield* Global.Service
|
|
178
|
+
const fs = yield* FileSystem.FileSystem
|
|
179
|
+
const flock = yield* EffectFlock.Service
|
|
180
|
+
const directory = (pkg: string, target: Target | undefined) => path.join(global.cache, "npm", key(pkg, target))
|
|
181
|
+
const generations = Effect.fnUntraced(function* (dir: string) {
|
|
182
|
+
return yield* fs.readDirectory(dir).pipe(
|
|
183
|
+
Effect.orElseSucceed(() => [] as string[]),
|
|
184
|
+
Effect.map((entries) =>
|
|
185
|
+
entries
|
|
186
|
+
.filter((entry) => /^\d+$/.test(entry) && !entries.includes(`${entry}.rejected`))
|
|
187
|
+
.toSorted((a, b) => Number(a) - Number(b)),
|
|
188
|
+
),
|
|
189
|
+
)
|
|
190
|
+
})
|
|
191
|
+
const current = Effect.fnUntraced(function* (dir: string) {
|
|
192
|
+
const latest = (yield* generations(dir)).at(-1)
|
|
193
|
+
return latest ? path.join(dir, latest) : undefined
|
|
194
|
+
})
|
|
195
|
+
const mkdir = (dir: string) =>
|
|
196
|
+
fs.makeDirectory(dir, { recursive: true }).pipe(
|
|
197
|
+
Effect.mapError((cause) => new InstallFailedError({ dir, cause })),
|
|
198
|
+
)
|
|
199
|
+
const remove = (target: string, dir: string) =>
|
|
200
|
+
fs.remove(target, { recursive: true, force: true }).pipe(
|
|
201
|
+
Effect.mapError((cause) => new InstallFailedError({ dir, cause })),
|
|
202
|
+
)
|
|
203
|
+
const rename = (from: string, to: string, dir: string) =>
|
|
204
|
+
fs.rename(from, to).pipe(Effect.mapError((cause) => new InstallFailedError({ dir, cause })))
|
|
205
|
+
const installedName = Effect.fnUntraced(function* (pkg: string, dir: string, target?: Target) {
|
|
206
|
+
if (target?.name) return target.name
|
|
207
|
+
const manifest = yield* afs
|
|
208
|
+
.readJson(path.join(dir, "package.json"))
|
|
209
|
+
.pipe(Effect.flatMap(Schema.decodeUnknownEffect(PackageJson)), Effect.option)
|
|
210
|
+
if (Option.isSome(manifest)) {
|
|
211
|
+
const name = Object.keys(manifest.value.dependencies ?? {})[0]
|
|
212
|
+
if (name) return name
|
|
213
|
+
}
|
|
214
|
+
return pkg
|
|
215
|
+
})
|
|
216
|
+
const installedRevision = Effect.fnUntraced(function* (root: string, name: string, target: Target) {
|
|
217
|
+
const dir = path.join(root, "node_modules", name)
|
|
218
|
+
if (target.type === "registry") {
|
|
219
|
+
const manifest = yield* afs
|
|
220
|
+
.readJson(path.join(dir, "package.json"))
|
|
221
|
+
.pipe(Effect.flatMap(Schema.decodeUnknownEffect(PackageJson)), Effect.option)
|
|
222
|
+
return Option.isSome(manifest) ? manifest.value.version : undefined
|
|
223
|
+
}
|
|
224
|
+
for (const file of [path.join(root, "package-lock.json"), path.join(root, "node_modules", ".package-lock.json")]) {
|
|
225
|
+
const lock = yield* afs
|
|
226
|
+
.readJson(file)
|
|
227
|
+
.pipe(Effect.flatMap(Schema.decodeUnknownEffect(PackageLock)), Effect.option)
|
|
228
|
+
const revision = gitRevision(
|
|
229
|
+
Option.isSome(lock) ? lock.value.packages?.[`node_modules/${name}`]?.resolved : undefined,
|
|
230
|
+
)
|
|
231
|
+
if (revision) return revision
|
|
232
|
+
}
|
|
233
|
+
})
|
|
234
|
+
const metadata = Effect.fnUntraced(function* (root: string, name: string, dir: string, target: Target | undefined) {
|
|
235
|
+
const manifest = yield* afs
|
|
236
|
+
.readJson(path.join(dir, "package.json"))
|
|
237
|
+
.pipe(Effect.flatMap(Schema.decodeUnknownEffect(PackageJson)), Effect.option)
|
|
238
|
+
const manifestVersion = Option.isSome(manifest) ? manifest.value.version : undefined
|
|
239
|
+
const revision = target ? (yield* installedRevision(root, name, target)) ?? manifestVersion : undefined
|
|
240
|
+
const version = target?.type === "git" ? revision : manifestVersion
|
|
241
|
+
return {
|
|
242
|
+
directory: dir,
|
|
243
|
+
name,
|
|
244
|
+
...(version ? { version } : {}),
|
|
245
|
+
...(revision ? { revision } : {}),
|
|
246
|
+
}
|
|
247
|
+
})
|
|
248
|
+
const reify = (input: { dir: string; config?: string; add?: string[]; update?: boolean }) =>
|
|
249
|
+
Effect.gen(function* () {
|
|
250
|
+
const { Arborist } = yield* Effect.promise(() => import("@npmcli/arborist"))
|
|
251
|
+
const add = input.add ?? []
|
|
252
|
+
const options = {
|
|
253
|
+
...(yield* NpmConfig.load(input.config ?? input.dir)),
|
|
254
|
+
...(input.update ? { preferOnline: true, noGitRevCache: true } : {}),
|
|
255
|
+
// Audit reports are unused here, but Arborist waits for them before completing an install.
|
|
256
|
+
audit: false,
|
|
257
|
+
windowsHide: true,
|
|
258
|
+
}
|
|
259
|
+
const arborist = new Arborist({
|
|
260
|
+
...options,
|
|
261
|
+
path: input.dir,
|
|
262
|
+
binLinks: true,
|
|
263
|
+
progress: false,
|
|
264
|
+
savePrefix: "",
|
|
265
|
+
ignoreScripts: true,
|
|
266
|
+
})
|
|
267
|
+
return yield* Effect.tryPromise({
|
|
268
|
+
try: () =>
|
|
269
|
+
arborist.reify({
|
|
270
|
+
...options,
|
|
271
|
+
add,
|
|
272
|
+
update: input.update,
|
|
273
|
+
save: true,
|
|
274
|
+
saveType: "prod",
|
|
275
|
+
}),
|
|
276
|
+
catch: (cause) =>
|
|
277
|
+
new InstallFailedError({
|
|
278
|
+
cause,
|
|
279
|
+
add,
|
|
280
|
+
dir: input.dir,
|
|
281
|
+
}),
|
|
282
|
+
}) as Effect.Effect<ArboristTree, InstallFailedError>
|
|
283
|
+
}).pipe(
|
|
284
|
+
Effect.withSpan("Npm.reify", {
|
|
285
|
+
attributes: input,
|
|
286
|
+
}),
|
|
287
|
+
)
|
|
288
|
+
|
|
289
|
+
const install = Effect.fnUntraced(function* (
|
|
290
|
+
pkg: string,
|
|
291
|
+
target: Target | undefined,
|
|
292
|
+
dir: string,
|
|
293
|
+
update: boolean,
|
|
294
|
+
) {
|
|
295
|
+
yield* flock.acquire(`npm-install:${dir}`)
|
|
296
|
+
const active = yield* current(dir)
|
|
297
|
+
const name = yield* installedName(pkg, active ?? dir, target)
|
|
298
|
+
if (active && !update && (yield* afs.existsSafe(path.join(active, "node_modules", name)))) {
|
|
299
|
+
return yield* metadata(active, name, path.join(active, "node_modules", name), target)
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
yield* mkdir(dir)
|
|
303
|
+
const startedAt = yield* Clock.currentTimeMillis
|
|
304
|
+
// Arborist keys lockfile entries relative to the root's real path. When the cache
|
|
305
|
+
// directory is reached through a symlink (macOS `/var` → `/private/var`, a linked
|
|
306
|
+
// XDG cache), the keys become `../../…` paths that installedRevision never finds,
|
|
307
|
+
// so Git checks report "not installed" and updates go undetected. Stage under the
|
|
308
|
+
// resolved directory so the root path and real path agree.
|
|
309
|
+
const root = yield* fs.realPath(dir).pipe(Effect.mapError((cause) => new InstallFailedError({ dir, cause })))
|
|
310
|
+
const staging = path.join(root, `.staging-${startedAt}-${randomUUID()}`)
|
|
311
|
+
const staged = yield* Effect.gen(function* () {
|
|
312
|
+
const tree = yield* reify({ dir: staging, config: dir, add: [pkg], update })
|
|
313
|
+
const installed = tree.edgesOut.values().next().value?.to
|
|
314
|
+
const installedNameValue = installed?.name ?? (yield* installedName(pkg, staging, target))
|
|
315
|
+
const result = yield* metadata(
|
|
316
|
+
staging,
|
|
317
|
+
installedNameValue,
|
|
318
|
+
installed?.path ?? path.join(staging, "node_modules", installedNameValue),
|
|
319
|
+
target,
|
|
320
|
+
)
|
|
321
|
+
if (!installed && !(yield* afs.isDir(result.directory)))
|
|
322
|
+
return yield* new InstallFailedError({ add: [pkg], dir: staging })
|
|
323
|
+
const links =
|
|
324
|
+
process.platform === "win32"
|
|
325
|
+
? Array.from(tree.inventory.values()).filter(
|
|
326
|
+
(node) => node.isLink && FSUtil.contains(staging, node.path) && FSUtil.contains(staging, node.realpath),
|
|
327
|
+
)
|
|
328
|
+
: []
|
|
329
|
+
return { result, links }
|
|
330
|
+
}).pipe(Effect.onError(() => remove(staging, dir).pipe(Effect.ignore)))
|
|
331
|
+
|
|
332
|
+
if (active) {
|
|
333
|
+
const activeEntry = yield* metadata(active, name, path.join(active, "node_modules", name), target)
|
|
334
|
+
if (activeEntry.revision && activeEntry.revision === staged.result.revision) {
|
|
335
|
+
yield* remove(staging, dir)
|
|
336
|
+
return activeEntry
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
const completedAt = yield* Clock.currentTimeMillis
|
|
341
|
+
const newest = Number((yield* generations(dir)).at(-1) ?? 0)
|
|
342
|
+
const generation = path.join(dir, String(Math.max(completedAt, newest + 1)))
|
|
343
|
+
// Windows junctions use absolute targets, so rebase internal links before publishing the generation.
|
|
344
|
+
if (staged.links.length > 0) {
|
|
345
|
+
const { unlink, symlink } = yield* Effect.promise(() => import("node:fs/promises"))
|
|
346
|
+
yield* Effect.forEach(
|
|
347
|
+
staged.links,
|
|
348
|
+
(link) =>
|
|
349
|
+
Effect.tryPromise({
|
|
350
|
+
try: async () => {
|
|
351
|
+
await unlink(link.path)
|
|
352
|
+
await symlink(path.join(generation, path.relative(staging, link.realpath)), link.path, "junction")
|
|
353
|
+
},
|
|
354
|
+
catch: (cause) => new InstallFailedError({ dir, cause }),
|
|
355
|
+
}),
|
|
356
|
+
{ discard: true },
|
|
357
|
+
).pipe(Effect.onError(() => remove(staging, dir).pipe(Effect.ignore)))
|
|
358
|
+
}
|
|
359
|
+
yield* rename(staging, generation, dir)
|
|
360
|
+
return { ...staged.result, directory: path.join(generation, "node_modules", staged.result.name) }
|
|
361
|
+
})
|
|
362
|
+
|
|
363
|
+
const collect = Effect.fnUntraced(function* (dir: string) {
|
|
364
|
+
const now = yield* Clock.currentTimeMillis
|
|
365
|
+
const completed = yield* generations(dir)
|
|
366
|
+
const keep = new Set(completed.slice(-2))
|
|
367
|
+
const entries = yield* fs.readDirectory(dir).pipe(Effect.orElseSucceed(() => [] as string[]))
|
|
368
|
+
yield* Effect.forEach(
|
|
369
|
+
entries,
|
|
370
|
+
(name) => {
|
|
371
|
+
const timestamp = /^\d+(\.rejected)?$/.test(name)
|
|
372
|
+
? Number(name.split(".")[0])
|
|
373
|
+
: Number(name.match(/^\.staging-(\d+)-/)?.[1] ?? Number.NaN)
|
|
374
|
+
const maximumAge = name.startsWith(".staging-") ? stagingRetention : retention
|
|
375
|
+
if (!Number.isFinite(timestamp) || keep.has(name) || now - timestamp <= maximumAge) return Effect.void
|
|
376
|
+
return remove(path.join(dir, name), dir).pipe(
|
|
377
|
+
Effect.catchCause((cause) => Effect.logWarning("failed to remove stale npm generation", { dir, name, cause })),
|
|
378
|
+
)
|
|
379
|
+
},
|
|
380
|
+
{ concurrency: "unbounded", discard: true },
|
|
381
|
+
)
|
|
382
|
+
})
|
|
383
|
+
|
|
384
|
+
const add = Effect.fn("Npm.add")(function* (pkg: string) {
|
|
385
|
+
const target = yield* Effect.promise(() => parse(pkg))
|
|
386
|
+
const dir = directory(pkg, target)
|
|
387
|
+
return yield* install(pkg, target, dir, false)
|
|
388
|
+
}, Effect.scoped)
|
|
389
|
+
|
|
390
|
+
const resolve = Effect.fn("Npm.resolve")(function* (pkg: string) {
|
|
391
|
+
const target = yield* Effect.promise(() => parse(pkg))
|
|
392
|
+
const root = directory(pkg, target)
|
|
393
|
+
const generation = yield* current(root)
|
|
394
|
+
const name = yield* installedName(pkg, generation ?? root, target)
|
|
395
|
+
const dir = path.join(generation ?? root, "node_modules", name)
|
|
396
|
+
if (!(yield* afs.existsSafe(dir))) return { directory: dir, name }
|
|
397
|
+
return yield* metadata(generation ?? root, name, dir, target)
|
|
398
|
+
})
|
|
399
|
+
|
|
400
|
+
const check = Effect.fn("Npm.check")(function* (pkg: string) {
|
|
401
|
+
const target = yield* Effect.promise(() => parse(pkg))
|
|
402
|
+
const root = directory(pkg, target)
|
|
403
|
+
if (!target)
|
|
404
|
+
return yield* new InstallFailedError({
|
|
405
|
+
dir: root,
|
|
406
|
+
cause: new Error("Package checks only support registry and Git package specs"),
|
|
407
|
+
})
|
|
408
|
+
if (!target.mutable) return false
|
|
409
|
+
const generation = yield* current(root)
|
|
410
|
+
const name = yield* installedName(pkg, generation ?? root, target)
|
|
411
|
+
const installed = generation ? yield* installedRevision(generation, name, target) : undefined
|
|
412
|
+
if (!installed)
|
|
413
|
+
return yield* new InstallFailedError({ dir: root, cause: new Error(`Package is not installed: ${pkg}`) })
|
|
414
|
+
const { manifest, resolve } = yield* Effect.promise(() => import("pacote"))
|
|
415
|
+
const options = {
|
|
416
|
+
...(yield* NpmConfig.load(root)),
|
|
417
|
+
preferOnline: true,
|
|
418
|
+
noGitRevCache: true,
|
|
419
|
+
ignoreScripts: true,
|
|
420
|
+
// Pacote spawns Git directly rather than through AppProcess.
|
|
421
|
+
windowsHide: true,
|
|
422
|
+
}
|
|
423
|
+
const available = yield* Effect.tryPromise({
|
|
424
|
+
try: async () =>
|
|
425
|
+
target.type === "git" ? gitRevision(await resolve(pkg, options)) : (await manifest(pkg, options)).version,
|
|
426
|
+
catch: (cause) => new InstallFailedError({ dir: root, cause }),
|
|
427
|
+
})
|
|
428
|
+
if (!available)
|
|
429
|
+
return yield* new InstallFailedError({ dir: root, cause: new Error(`Package revision not found: ${pkg}`) })
|
|
430
|
+
return installed !== available
|
|
431
|
+
})
|
|
432
|
+
|
|
433
|
+
const update = Effect.fn("Npm.update")(function* (pkg: string) {
|
|
434
|
+
const target = yield* Effect.promise(() => parse(pkg))
|
|
435
|
+
const dir = directory(pkg, target)
|
|
436
|
+
if (!target)
|
|
437
|
+
return yield* new InstallFailedError({
|
|
438
|
+
dir,
|
|
439
|
+
cause: new Error("Package updates only support registry and Git package specs"),
|
|
440
|
+
})
|
|
441
|
+
if (!target.mutable) return yield* add(pkg)
|
|
442
|
+
const installed = yield* install(pkg, target, dir, true)
|
|
443
|
+
yield* collect(dir)
|
|
444
|
+
return installed
|
|
445
|
+
}, Effect.scoped)
|
|
446
|
+
|
|
447
|
+
const follows = Effect.fn("Npm.follows")(function* (pkg: string) {
|
|
448
|
+
const target = yield* Effect.promise(() => parse(pkg))
|
|
449
|
+
if (target?.type !== "git" || !target.ref) return target?.follows ?? false
|
|
450
|
+
const root = directory(pkg, target)
|
|
451
|
+
// Only the remote knows whether a ref is a branch or a tag. pacote keeps the ref it resolved, and Git reuses the
|
|
452
|
+
// refs the update check just listed for a few minutes, so this usually doesn't ask the remote again.
|
|
453
|
+
const { GitFetcher } = (yield* Effect.promise(() => import("pacote"))) as unknown as {
|
|
454
|
+
GitFetcher: new (
|
|
455
|
+
spec: string,
|
|
456
|
+
options: Record<string, unknown>,
|
|
457
|
+
) => { resolve(): Promise<string>; resolvedRef: { readonly type: string } | null }
|
|
458
|
+
}
|
|
459
|
+
const fetcher = new GitFetcher(pkg, { ...(yield* NpmConfig.load(root)), ignoreScripts: true, windowsHide: true })
|
|
460
|
+
yield* Effect.tryPromise({
|
|
461
|
+
try: () => fetcher.resolve(),
|
|
462
|
+
catch: (cause) => new InstallFailedError({ dir: root, cause }),
|
|
463
|
+
})
|
|
464
|
+
return fetcher.resolvedRef?.type === "branch"
|
|
465
|
+
})
|
|
466
|
+
|
|
467
|
+
const reject = Effect.fn("Npm.reject")(function* (pkg: string, version: string) {
|
|
468
|
+
const target = yield* Effect.promise(() => parse(pkg))
|
|
469
|
+
const dir = directory(pkg, target)
|
|
470
|
+
yield* flock.acquire(`npm-install:${dir}`)
|
|
471
|
+
const completed = yield* generations(dir)
|
|
472
|
+
const newest = completed.at(-1)
|
|
473
|
+
if (completed.length < 2 || !newest) return false
|
|
474
|
+
const root = path.join(dir, newest)
|
|
475
|
+
const name = yield* installedName(pkg, root, target)
|
|
476
|
+
if ((yield* metadata(root, name, path.join(root, "node_modules", name), target)).version !== version) return false
|
|
477
|
+
yield* fs
|
|
478
|
+
.writeFileString(path.join(dir, `${newest}.rejected`), "")
|
|
479
|
+
.pipe(Effect.mapError((cause) => new InstallFailedError({ dir, cause })))
|
|
480
|
+
return true
|
|
481
|
+
}, Effect.scoped)
|
|
482
|
+
|
|
483
|
+
const which = Effect.fn("Npm.which")(function* (pkg: string, bin?: string) {
|
|
484
|
+
const target = yield* Effect.promise(() => parse(pkg))
|
|
485
|
+
const root = directory(pkg, target)
|
|
486
|
+
|
|
487
|
+
const pick = Effect.fnUntraced(function* (dir: string) {
|
|
488
|
+
const binDir = path.join(dir, "node_modules", ".bin")
|
|
489
|
+
const files = yield* fs.readDirectory(binDir).pipe(Effect.orElseSucceed(() => [] as string[]))
|
|
490
|
+
|
|
491
|
+
if (files.length === 0) return Option.none<string>()
|
|
492
|
+
// Caller picked a specific bin (e.g. pyright exposes both `pyright` and
|
|
493
|
+
// `pyright-langserver`); trust the hint if the package provides it.
|
|
494
|
+
if (bin) return files.includes(bin) ? Option.some(path.join(binDir, bin)) : Option.none<string>()
|
|
495
|
+
if (files.length === 1) return Option.some(path.join(binDir, files[0]))
|
|
496
|
+
|
|
497
|
+
const packageName = target?.name ?? pkg
|
|
498
|
+
const pkgJson = yield* afs.readJson(path.join(dir, "node_modules", packageName, "package.json")).pipe(Effect.option)
|
|
499
|
+
|
|
500
|
+
if (Option.isSome(pkgJson)) {
|
|
501
|
+
const parsed = pkgJson.value as { bin?: string | Record<string, string> }
|
|
502
|
+
if (parsed?.bin) {
|
|
503
|
+
const unscoped = packageName.startsWith("@") ? packageName.split("/")[1] : packageName
|
|
504
|
+
const parsedBin = parsed.bin
|
|
505
|
+
if (typeof parsedBin === "string") return Option.some(path.join(binDir, unscoped))
|
|
506
|
+
const keys = Object.keys(parsedBin)
|
|
507
|
+
const selected = parsedBin[unscoped] ? unscoped : keys[0]
|
|
508
|
+
return selected ? Option.some(path.join(binDir, selected)) : Option.none<string>()
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
return Option.some(path.join(binDir, files[0]))
|
|
513
|
+
})
|
|
514
|
+
|
|
515
|
+
return Option.getOrUndefined(
|
|
516
|
+
yield* Effect.gen(function* () {
|
|
517
|
+
const generation = yield* current(root)
|
|
518
|
+
const selected = generation ? yield* pick(generation) : Option.none<string>()
|
|
519
|
+
if (Option.isSome(selected)) return selected
|
|
520
|
+
|
|
521
|
+
yield* add(pkg)
|
|
522
|
+
|
|
523
|
+
const installed = yield* current(root)
|
|
524
|
+
if (!installed) return Option.none<string>()
|
|
525
|
+
return yield* pick(installed)
|
|
526
|
+
}).pipe(
|
|
527
|
+
Effect.scoped,
|
|
528
|
+
Effect.orElseSucceed(() => Option.none<string>()),
|
|
529
|
+
),
|
|
530
|
+
)
|
|
531
|
+
})
|
|
532
|
+
|
|
533
|
+
return Service.of({
|
|
534
|
+
add,
|
|
535
|
+
resolve,
|
|
536
|
+
check,
|
|
537
|
+
update,
|
|
538
|
+
follows,
|
|
539
|
+
reject,
|
|
540
|
+
which,
|
|
541
|
+
})
|
|
542
|
+
}),
|
|
543
|
+
)
|
|
544
|
+
|
|
545
|
+
export const node = makeGlobalNode({
|
|
546
|
+
service: Service,
|
|
547
|
+
layer: layer,
|
|
548
|
+
deps: [FSUtil.node, Global.node, filesystem, EffectFlock.node],
|
|
549
|
+
})
|
|
550
|
+
|
|
551
|
+
function gitRevision(resolved: string | undefined) {
|
|
552
|
+
return resolved?.match(/#([a-f0-9]{40}|[a-f0-9]{64})(?=::|$)/i)?.[1]
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
function isCommit(value: string | null | undefined) {
|
|
556
|
+
return /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(value ?? "")
|
|
557
|
+
}
|