@mjasnikovs/pi-nop 0.0.0-stage → 0.1.2

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 (53) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +116 -2
  3. package/package.json +87 -5
  4. package/src/config/box.ts +29 -0
  5. package/src/config/command.ts +138 -0
  6. package/src/config/config.ts +238 -0
  7. package/src/config/sections.ts +58 -0
  8. package/src/index.ts +17 -0
  9. package/src/plan/ask.ts +226 -0
  10. package/src/plan/goal.ts +43 -0
  11. package/src/plan/panel.ts +567 -0
  12. package/src/plan/plan.ts +581 -0
  13. package/src/plan/steps.ts +192 -0
  14. package/src/plan/track.ts +131 -0
  15. package/src/search/brave.ts +56 -0
  16. package/src/search/ddg.ts +67 -0
  17. package/src/search/engines.ts +63 -0
  18. package/src/search/exa.ts +74 -0
  19. package/src/search/search.ts +58 -0
  20. package/src/subagent/answer.ts +151 -0
  21. package/src/subagent/budget.ts +19 -0
  22. package/src/subagent/describe.ts +8 -0
  23. package/src/subagent/docs/docs.ts +123 -0
  24. package/src/subagent/docs/files.ts +90 -0
  25. package/src/subagent/docs/header.ts +60 -0
  26. package/src/subagent/docs/locate.ts +262 -0
  27. package/src/subagent/docs/manifest.ts +43 -0
  28. package/src/subagent/docs/npm.ts +287 -0
  29. package/src/subagent/fetch/digest.ts +379 -0
  30. package/src/subagent/fetch/errors.ts +10 -0
  31. package/src/subagent/fetch/fetch.ts +176 -0
  32. package/src/subagent/fetch/pdf.ts +120 -0
  33. package/src/subagent/guards/churn.ts +37 -0
  34. package/src/subagent/guards/circle.ts +49 -0
  35. package/src/subagent/guards/ground.ts +75 -0
  36. package/src/subagent/guards/guard.ts +24 -0
  37. package/src/subagent/guards/guards.ts +107 -0
  38. package/src/subagent/guards/key.ts +13 -0
  39. package/src/subagent/guards/leak.ts +42 -0
  40. package/src/subagent/guards/lines.ts +24 -0
  41. package/src/subagent/guards/loop.ts +77 -0
  42. package/src/subagent/guards/repeat.ts +70 -0
  43. package/src/subagent/guards/stale.ts +38 -0
  44. package/src/subagent/guards/toolCall.ts +46 -0
  45. package/src/subagent/guards/visited.ts +89 -0
  46. package/src/subagent/platform.ts +81 -0
  47. package/src/subagent/progress.ts +34 -0
  48. package/src/subagent/slots.ts +42 -0
  49. package/src/subagent/subagent.ts +537 -0
  50. package/src/subagent/subagentTui.ts +292 -0
  51. package/src/tui/hidden.ts +16 -0
  52. package/src/tui/spinner.ts +64 -0
  53. package/src/types/turndown-plugin-gfm.d.ts +5 -0
@@ -0,0 +1,262 @@
1
+ import {existsSync} from 'node:fs'
2
+ import {isBuiltin} from 'node:module'
3
+ import {dirname, join, sep} from 'node:path'
4
+ import ts from 'typescript'
5
+
6
+ import {realpath} from '../platform'
7
+ import {isNamed, readManifest} from './manifest'
8
+ import type {Named} from './manifest'
9
+ import {download, packTarget, resolveVersion, versionPattern} from './npm'
10
+ import type {Wanted} from './npm'
11
+
12
+ enum LocateErrors {
13
+ Builtin = 'Docs failed: runtime module without its types package installed: ',
14
+ BadName = 'Docs failed: not an npm package name: ',
15
+ BadVersion = 'Docs failed: not a version or dist-tag: ',
16
+ NoManifest = 'Docs failed: no package.json for ',
17
+ NotUnpacked = 'Docs failed: unpacked but not found: '
18
+ }
19
+
20
+ type Package = {
21
+ manifest: Named
22
+ dir: string
23
+ }
24
+
25
+ type Origin = 'installed' | 'downloaded' | 'types-only' | 'runtime'
26
+
27
+ type Located = {
28
+ /** The name asked for; the folder name under an npm alias, `node:fs` for a runtime module. */
29
+ asked: string
30
+ pkg: Package
31
+ source: Origin
32
+ entry?: string
33
+ /** Other packages that hold the declarations: @types/x, or what a one-line stub points at. */
34
+ types: Package[]
35
+ /** The version on disk, when a downloaded one was asked for instead. */
36
+ installed?: string
37
+ }
38
+
39
+ type Project = {
40
+ path?: string
41
+ range?: string
42
+ }
43
+
44
+ const resolveOptions: ts.CompilerOptions = {moduleResolution: ts.ModuleResolutionKind.Bundler}
45
+ const packageNamePattern = /^(@[^/\\\s@:]+\/)?[^./\\\s@:-][^/\\\s@:]*$/
46
+ const runtimePrefix = /^(node|bun):/
47
+
48
+ const packageName = (module: string): string => {
49
+ const parts = module.split('/')
50
+ return parts[0]?.startsWith('@') ? parts.slice(0, 2).join('/') : (parts[0] ?? module)
51
+ }
52
+
53
+ const typesModule = (module: string): string | undefined => {
54
+ if (module.startsWith('bun:')) return 'bun'
55
+ return module.startsWith('node:') || isBuiltin(module) ? 'node' : undefined
56
+ }
57
+
58
+ // A subpath segment of `.` or `..` would resolve into another package.
59
+ const assertPackage = (module: string): void => {
60
+ const dotted = module.split(/[\\/]/).some(segment => segment === '.' || segment === '..')
61
+
62
+ if (dotted || !packageNamePattern.test(packageName(module)))
63
+ throw new Error(LocateErrors.BadName + module)
64
+ }
65
+
66
+ const findUp = (from: string, test: (dir: string) => boolean): string | undefined => {
67
+ for (let dir = from; ; dir = dirname(dir)) {
68
+ if (test(dir)) return dir
69
+ if (dirname(dir) === dir) return undefined
70
+ }
71
+ }
72
+
73
+ const hasManifest = (dir: string): boolean => existsSync(join(dir, 'package.json'))
74
+
75
+ const readPackage = (dir: string): Package => {
76
+ const manifest = readManifest(dir)
77
+
78
+ if (!isNamed(manifest)) throw new Error(LocateErrors.NoManifest + dir)
79
+ return {manifest, dir}
80
+ }
81
+
82
+ const packages = (located: Located): Package[] => [located.pkg, ...located.types]
83
+
84
+ const projectOf = (name: string, cwd: string): Project => {
85
+ const dir = findUp(cwd, hasManifest)
86
+
87
+ if (dir === undefined) return {}
88
+
89
+ const manifest = readManifest(dir)
90
+ const range =
91
+ manifest.dependencies?.[name]
92
+ ?? manifest.devDependencies?.[name]
93
+ ?? manifest.peerDependencies?.[name]
94
+ ?? manifest.optionalDependencies?.[name]
95
+ return {path: join(dir, 'package.json'), range}
96
+ }
97
+
98
+ const findPackageDir = (name: string, cwd: string): string | undefined => {
99
+ const dir = findUp(cwd, here => hasManifest(join(here, 'node_modules', name)))
100
+ return dir === undefined ? undefined : realpath(join(dir, 'node_modules', name))
101
+ }
102
+
103
+ const packageRootOf = (file: string, name: string): string => {
104
+ const dir = findUp(dirname(file), here => hasManifest(here) && readManifest(here).name === name)
105
+
106
+ if (dir === undefined) throw new Error(`${LocateErrors.NoManifest}${name} above ${file}`)
107
+ return dir
108
+ }
109
+
110
+ // One hop only: bun-types references node, which is not the package asked about.
111
+ const stubTargets = (entry: string): Package[] => {
112
+ const text = ts.sys.readFile(entry) ?? ''
113
+
114
+ if (ts.createSourceFile(entry, text, ts.ScriptTarget.Latest).statements.length > 0) return []
115
+ return ts.preProcessFile(text).typeReferenceDirectives.flatMap(({fileName}) => {
116
+ const resolved = ts.resolveTypeReferenceDirective(
117
+ fileName,
118
+ entry,
119
+ {},
120
+ ts.sys
121
+ ).resolvedTypeReferenceDirective
122
+ const name = resolved?.packageId?.name
123
+
124
+ if (name === undefined || resolved?.resolvedFileName === undefined) return []
125
+ return [readPackage(packageRootOf(realpath(resolved.resolvedFileName), name))]
126
+ })
127
+ }
128
+
129
+ // TypeScript resolves relative to a containing file, which need not exist.
130
+ const resolveEntry = (module: string, cwd: string): ts.ResolvedModuleFull | undefined => {
131
+ const resolved = ts.resolveModuleName(
132
+ module,
133
+ join(cwd, 'pi-nop.ts'),
134
+ resolveOptions,
135
+ ts.sys
136
+ ).resolvedModule
137
+
138
+ if (resolved === undefined) return undefined
139
+ return {...resolved, resolvedFileName: realpath(resolved.resolvedFileName)}
140
+ }
141
+
142
+ // The package a resolved entry belongs to: the asked one, or @types/x when that answered.
143
+ const packageOf = (resolved?: ts.ResolvedModuleFull): Package | undefined => {
144
+ const name = resolved?.packageId?.name
145
+
146
+ if (resolved === undefined || name === undefined) return undefined
147
+ return readPackage(packageRootOf(resolved.resolvedFileName, name))
148
+ }
149
+
150
+ // @types/x answered for x. Under an npm alias the names match and nothing is added.
151
+ const typesFor = (pkg: Package, resolved: Package | undefined, stubs: Package[]): Package[] => {
152
+ if (resolved === undefined || resolved.manifest.name === pkg.manifest.name) return stubs
153
+ return [resolved, ...stubs]
154
+ }
155
+
156
+ type Found = Omit<Located, 'asked' | 'source'> & {onDisk: boolean}
157
+
158
+ const asLocated = (asked: string, source: Origin, {onDisk: _onDisk, ...found}: Found): Located => ({
159
+ asked,
160
+ source,
161
+ ...found
162
+ })
163
+
164
+ const packageAt = (
165
+ module: string,
166
+ cwd: string,
167
+ resolved?: ts.ResolvedModuleFull
168
+ ): Found | undefined => {
169
+ const dir = findPackageDir(packageName(module), cwd)
170
+ const resolvedPackage = packageOf(resolved)
171
+ const pkg = dir === undefined ? resolvedPackage : readPackage(dir)
172
+
173
+ if (pkg === undefined) return undefined
174
+
175
+ const stubs =
176
+ resolved?.extension.startsWith('.d.') === true ? stubTargets(resolved.resolvedFileName) : []
177
+ return {
178
+ pkg,
179
+ entry: resolved?.resolvedFileName,
180
+ types: typesFor(pkg, resolvedPackage, stubs),
181
+ onDisk: dir !== undefined
182
+ }
183
+ }
184
+
185
+ // Only a package on disk can satisfy a version; @types/x carries its own numbering.
186
+ const matchesVersion = (local: Found, version?: string): boolean =>
187
+ version === undefined || (local.onDisk && version === local.pkg.manifest.version)
188
+
189
+ const locateIn = (module: string, cwd: string): Found | undefined =>
190
+ packageAt(module, cwd, resolveEntry(module, cwd))
191
+
192
+ // A tree unpacked into the cache must not pick up a stray @types from an ancestor node_modules.
193
+ const locateDownloaded = (module: string, root: string): Found | undefined => {
194
+ const fence = realpath(root) + sep
195
+ const resolved = resolveEntry(module, root)
196
+ const inside = resolved?.resolvedFileName.startsWith(fence) === true
197
+ const found = packageAt(module, root, inside ? resolved : undefined)
198
+
199
+ if (found === undefined) return undefined
200
+ return {...found, types: found.types.filter(pkg => pkg.dir.startsWith(fence))}
201
+ }
202
+
203
+ const locate = async (
204
+ module: string,
205
+ cwd: string,
206
+ wanted: Wanted = {},
207
+ signal?: AbortSignal
208
+ ): Promise<Located> => {
209
+ const prefixed = runtimePrefix.test(module)
210
+
211
+ if (!prefixed) assertPackage(module)
212
+ if (wanted.version !== undefined && !versionPattern.test(wanted.version))
213
+ throw new Error(LocateErrors.BadVersion + wanted.version)
214
+
215
+ const name = packageName(module)
216
+ // A builtin name the project declares, or pins, is the npm package. Otherwise it is node's,
217
+ // from @types/node, even when a dependency hoisted a same-named polyfill into node_modules.
218
+ const runtime = typesModule(module)
219
+ const unpinned = wanted.version === undefined && wanted.range === undefined
220
+
221
+ // The `bun` npm package is the binary; only resolved declarations count as its types.
222
+ if (runtime !== undefined && (prefixed || unpinned)) {
223
+ const types = locateIn(runtime, cwd)
224
+
225
+ if (types?.entry === undefined) throw new Error(LocateErrors.Builtin + module)
226
+ if (!types.onDisk) return asLocated(module, 'runtime', types)
227
+
228
+ // node_modules/bun is the binary; the declarations are the first package after it.
229
+ const [pkg, ...rest] = types.types
230
+
231
+ if (pkg === undefined) throw new Error(LocateErrors.Builtin + module)
232
+ return asLocated(module, 'runtime', {...types, pkg, types: rest})
233
+ }
234
+
235
+ const local = locateIn(module, cwd)
236
+ const want = local?.onDisk === true ? await resolveVersion(name, wanted, cwd, signal) : wanted
237
+
238
+ if (local !== undefined && matchesVersion(local, want.version))
239
+ return asLocated(name, local.onDisk ? 'installed' : 'types-only', local)
240
+
241
+ const root = await download(name, packTarget(name, want), cwd, signal)
242
+ const fetched = locateDownloaded(module, root)
243
+
244
+ if (fetched === undefined) throw new Error(`${LocateErrors.NotUnpacked}${module} in ${root}`)
245
+ return {
246
+ ...asLocated(name, 'downloaded', fetched),
247
+ installed: local?.onDisk === true ? local.pkg.manifest.version : undefined
248
+ }
249
+ }
250
+
251
+ export {
252
+ assertPackage,
253
+ locate,
254
+ locateDownloaded,
255
+ LocateErrors,
256
+ locateIn,
257
+ packageName,
258
+ packages,
259
+ projectOf,
260
+ typesModule
261
+ }
262
+ export type {Located, Package, Project}
@@ -0,0 +1,43 @@
1
+ import {readFileSync} from 'node:fs'
2
+ import {join} from 'node:path'
3
+ import {type Static, Type} from 'typebox'
4
+ import Value from 'typebox/value'
5
+
6
+ const deps = Type.Optional(Type.Record(Type.String(), Type.String()))
7
+ // A project root or a nested `{"type": "module"}` marker may have no name.
8
+ const manifestSchema = Type.Object({
9
+ name: Type.Optional(Type.String()),
10
+ /** A workspace or git package may ship none. */
11
+ version: Type.Optional(Type.String()),
12
+ homepage: Type.Optional(Type.String()),
13
+ repository: Type.Optional(
14
+ Type.Union([Type.String(), Type.Object({url: Type.Optional(Type.String())})])
15
+ ),
16
+ dependencies: deps,
17
+ devDependencies: deps,
18
+ peerDependencies: deps,
19
+ optionalDependencies: deps
20
+ })
21
+
22
+ type Manifest = Static<typeof manifestSchema>
23
+ type Named = Manifest & {name: string}
24
+
25
+ const fields = Type.Record(Type.String(), Type.Unknown())
26
+ const promised = (key: string, value: unknown): boolean =>
27
+ Object.hasOwn(manifestSchema.properties, key)
28
+ && Value.Check(manifestSchema.properties[key as keyof Manifest], value)
29
+
30
+ // A field that is not what package.json promises is dropped, not trusted.
31
+ const readManifest = (dir: string): Manifest => {
32
+ const raw = Value.Parse(fields, JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')))
33
+ const kept = Object.entries(raw).filter(([key, value]) => promised(key, value))
34
+ return Value.Parse(manifestSchema, Object.fromEntries(kept))
35
+ }
36
+
37
+ const isNamed = (manifest: Manifest): manifest is Named => manifest.name !== undefined
38
+
39
+ const spec = (manifest: Named): string =>
40
+ manifest.version === undefined ? manifest.name : `${manifest.name}@${manifest.version}`
41
+
42
+ export {isNamed, readManifest, spec}
43
+ export type {Manifest, Named}
@@ -0,0 +1,287 @@
1
+ import {existsSync, mkdirSync, mkdtempSync, renameSync, rmSync} from 'node:fs'
2
+ import {join} from 'node:path'
3
+ import {getAgentDir} from '@earendil-works/pi-coding-agent'
4
+ import {Type} from 'typebox'
5
+ import Value from 'typebox/value'
6
+ import spawn from 'cross-spawn'
7
+
8
+ import {describe} from '../describe'
9
+ import {unlessAborted} from '../subagent'
10
+ import {readManifest} from './manifest'
11
+ import {childEnv, missing, onPath, stop, tar} from '../platform'
12
+
13
+ // A silent npm prints its --json error on stdout, and any stderr line must not hide it.
14
+ const said = (...streams: string[]): string => streams.filter(text => text !== '').join('\n')
15
+
16
+ // Not execFile: it cannot start Windows' npm.cmd. cross-spawn escapes each argument for cmd.exe.
17
+ const run = (
18
+ command: string,
19
+ args: string[],
20
+ cwd?: string,
21
+ signal?: AbortSignal
22
+ ): Promise<string> =>
23
+ new Promise<string>((resolve, reject) => {
24
+ signal?.throwIfAborted()
25
+ const child = spawn(onPath(command), args, {
26
+ cwd,
27
+ env: childEnv(),
28
+ stdio: ['ignore', 'pipe', 'pipe']
29
+ })
30
+ const abort = () => stop(child)
31
+ let stdout = ''
32
+ let stderr = ''
33
+ const settle = () => signal?.removeEventListener('abort', abort)
34
+ signal?.addEventListener('abort', abort, {once: true})
35
+ child.stdout?.setEncoding('utf8').on('data', (chunk: string) => (stdout += chunk))
36
+ child.stderr?.setEncoding('utf8').on('data', (chunk: string) => (stderr += chunk))
37
+ // A failed spawn still ends in close, so settle there covers it.
38
+ child.on('error', reject)
39
+ child.on('close', (code, killedBy) => {
40
+ settle()
41
+ if (code === 0) return resolve(stdout)
42
+ reject(
43
+ new Error(
44
+ said(stderr, stdout) || `${command} ended with ${String(killedBy ?? code)}`
45
+ )
46
+ )
47
+ })
48
+ }).catch((error: unknown) => {
49
+ throw missing(command, error, cwd)
50
+ })
51
+
52
+ enum NpmErrors {
53
+ Missing = 'not on npm: ',
54
+ Failed = 'npm failed: ',
55
+ Unservable = 'Docs failed: not installed, and declared from outside the registry: '
56
+ }
57
+
58
+ type Wanted = {
59
+ version?: string
60
+ range?: string
61
+ }
62
+
63
+ type Target = {
64
+ /** The registry package: the alias target under an npm: range. */
65
+ name: string
66
+ spec: string
67
+ }
68
+
69
+ type View = {
70
+ version: string
71
+ deprecated?: string
72
+ latest?: string
73
+ }
74
+
75
+ // npm's codes for "no such package or version". Anything else is npm or the network failing.
76
+ const missingCodes = ['E404', 'ETARGET', 'EINVALIDTAGNAME', 'EINVALIDPACKAGENAME']
77
+
78
+ // npm 10 prints `npm error code X`, npm 9 `npm ERR! code X`. A silent npm prints only its --json error.
79
+ const npmCode = (error: unknown): string => {
80
+ const text = describe(error)
81
+ const found = /^npm (?:error|ERR!) code (\S+)|"code": "([^"]+)"/m.exec(text)
82
+ return found?.[1] ?? found?.[2] ?? text
83
+ }
84
+
85
+ // npm runs in the project, so .npmrc scopes, mirrors and auth hold, the same as an install would.
86
+ const npm = async (
87
+ target: Target,
88
+ args: string[],
89
+ cwd: string,
90
+ signal?: AbortSignal
91
+ ): Promise<string> =>
92
+ run('npm', args, cwd, signal).catch((error: unknown) => {
93
+ unlessAborted(signal, error)
94
+ const code = npmCode(error)
95
+ const lead = missingCodes.includes(code) ? NpmErrors.Missing : NpmErrors.Failed
96
+ throw new Error(`${lead}${target.name}@${target.spec} (${code})`, {cause: error})
97
+ })
98
+
99
+ const viewed = Type.Object({
100
+ version: Type.String(),
101
+ deprecated: Type.Optional(Type.String()),
102
+ 'dist-tags.latest': Type.Optional(Type.String())
103
+ })
104
+ const viewedShape = Type.Union([viewed, Type.Array(viewed)])
105
+ const packed = Type.Array(Type.Object({filename: Type.String()}))
106
+
107
+ // `name` and `version` always exist, so the answer is an object, or an array of them for a range.
108
+ const view = async (target: Target, cwd: string, signal?: AbortSignal): Promise<View> => {
109
+ const fields = ['name', 'version', 'deprecated', 'dist-tags.latest']
110
+ const stdout = await npm(
111
+ target,
112
+ ['view', '--json', '--', `${target.name}@${target.spec}`, ...fields],
113
+ cwd,
114
+ signal
115
+ )
116
+ // npm prints nothing, with exit 0, for a package with no latest tag.
117
+ const parsed = stdout.trim() === '' ? [] : Value.Parse(viewedShape, JSON.parse(stdout))
118
+ const last = Array.isArray(parsed) ? parsed.at(-1) : parsed
119
+
120
+ if (last === undefined)
121
+ throw new Error(`${NpmErrors.Missing}${target.name}@${target.spec} (empty)`)
122
+ return {version: last.version, deprecated: last.deprecated, latest: last['dist-tags.latest']}
123
+ }
124
+
125
+ type Facts = {
126
+ latest?: string
127
+ deprecated?: string
128
+ error?: string
129
+ }
130
+
131
+ // Our own errors carry npm's whole stderr as `cause`; the header wants the one-line message.
132
+ const message = (error: unknown): string => (error instanceof Error ? error.message : String(error))
133
+ const isMissing = (error: unknown): boolean => message(error).startsWith(NpmErrors.Missing)
134
+
135
+ // The registry view of one package: latest, and the deprecation of the version in hand. A
136
+ // version the registry never saw (a git install) is simply not deprecated.
137
+ const facts = async (
138
+ name: string,
139
+ version: string | undefined,
140
+ cwd: string,
141
+ signal?: AbortSignal
142
+ ): Promise<Facts> => {
143
+ try {
144
+ const seen = await view({name, spec: version ?? 'latest'}, cwd, signal)
145
+ return {latest: seen.latest, deprecated: seen.deprecated}
146
+ } catch (error) {
147
+ if (signal?.aborted) throw error
148
+ if (version === undefined || !isMissing(error)) return {error: message(error)}
149
+ return facts(name, undefined, cwd, signal)
150
+ }
151
+ }
152
+
153
+ const cacheDir = (): string => join(getAgentDir(), 'cache', 'pi-nop-docs')
154
+
155
+ // An alias tree is keyed by both names, so real foo@1 and foo aliasing bar@1 never share a folder.
156
+ const cacheRoot = (asked: string, name: string, version: string): string => {
157
+ const label = asked === name ? `${asked}@${version}` : `${asked}=${name}@${version}`
158
+ return join(cacheDir(), label.replaceAll('/', '+'))
159
+ }
160
+
161
+ // Two callers may finish the same unpack together; the tree already there is as good as ours.
162
+ const moveIntoCache = (tree: string, root: string): void => {
163
+ try {
164
+ renameSync(tree, root)
165
+ } catch (error) {
166
+ if (!existsSync(root)) throw error
167
+ }
168
+ }
169
+
170
+ const unpack = async (
171
+ asked: string,
172
+ target: Target,
173
+ scratch: string,
174
+ cwd: string,
175
+ signal?: AbortSignal
176
+ ): Promise<string> => {
177
+ const stdout = await npm(
178
+ target,
179
+ [
180
+ 'pack',
181
+ // A silent npm prints its error code only with --json.
182
+ '--json',
183
+ '--ignore-scripts',
184
+ '--pack-destination',
185
+ scratch,
186
+ '--',
187
+ `${target.name}@${target.spec}`
188
+ ],
189
+ cwd,
190
+ signal
191
+ )
192
+ const tarball = join(scratch, Value.Parse(packed, JSON.parse(stdout))[0]?.filename ?? '')
193
+ const dir = join(scratch, 'tree', 'node_modules', asked)
194
+ mkdirSync(dir, {recursive: true})
195
+ await run(tar, ['-xzf', tarball, '-C', dir, '--strip-components=1'], undefined, signal).catch(
196
+ (error: unknown) => {
197
+ unlessAborted(signal, error)
198
+ throw error
199
+ }
200
+ )
201
+ return join(scratch, 'tree')
202
+ }
203
+
204
+ const exactVersion = /^\d+\.\d+\.\d+(-[\w.-]+)?$/
205
+
206
+ // A tag names one version, so it is looked up and can hit the cache. A range is left to
207
+ // `npm pack`, which picks the highest match the way an install would; `npm view` lists in
208
+ // publish order.
209
+ const isRange = (spec: string): boolean =>
210
+ !exactVersion.test(spec) && /^[\d^~<>=*]|[\s|]/.test(spec)
211
+
212
+ // The scratch folder goes whatever happens, so a lost rename or a failure leaves nothing behind.
213
+ const unpackIntoCache = async (
214
+ asked: string,
215
+ target: Target,
216
+ cwd: string,
217
+ signal?: AbortSignal
218
+ ): Promise<string> => {
219
+ mkdirSync(cacheDir(), {recursive: true})
220
+ const scratch = mkdtempSync(join(cacheDir(), 'pack-'))
221
+
222
+ try {
223
+ const tree = await unpack(asked, target, scratch, cwd, signal)
224
+ const version = readManifest(join(tree, 'node_modules', asked)).version ?? target.spec
225
+ const root = cacheRoot(asked, target.name, version)
226
+ moveIntoCache(tree, root)
227
+ return root
228
+ } finally {
229
+ rmSync(scratch, {recursive: true, force: true})
230
+ }
231
+ }
232
+
233
+ const download = async (
234
+ asked: string,
235
+ target: Target,
236
+ cwd: string,
237
+ signal?: AbortSignal
238
+ ): Promise<string> => {
239
+ if (exactVersion.test(target.spec)) {
240
+ const known = cacheRoot(asked, target.name, target.spec)
241
+ return existsSync(known) ? known : unpackIntoCache(asked, target, cwd, signal)
242
+ }
243
+
244
+ if (isRange(target.spec)) return unpackIntoCache(asked, target, cwd, signal)
245
+
246
+ const {version} = await view(target, cwd, signal)
247
+ return download(asked, {name: target.name, spec: version}, cwd, signal)
248
+ }
249
+
250
+ // A version from the model is an exact version or a dist-tag, never a path, URL or protocol.
251
+ const versionPattern = /^[\w.-]+$/
252
+
253
+ // "latest" or a tag is the registry's word for a version; the installed copy may be it.
254
+ const resolveVersion = async (
255
+ asked: string,
256
+ wanted: Wanted,
257
+ cwd: string,
258
+ signal?: AbortSignal
259
+ ): Promise<Wanted> => {
260
+ if (
261
+ wanted.version === undefined
262
+ || exactVersion.test(wanted.version)
263
+ || isRange(wanted.version)
264
+ )
265
+ return wanted
266
+ return {...wanted, version: (await view(packTarget(asked, wanted), cwd, signal)).version}
267
+ }
268
+
269
+ // A workspace:, file: or git range names something the registry does not have, and a
270
+ // same-named stranger there would be the wrong answer. An npm: range names the real package.
271
+ const fromRegistry = (range: string | undefined): boolean =>
272
+ range === undefined || range.startsWith('npm:') || !/[:/]/.test(range)
273
+
274
+ const packTarget = (asked: string, wanted: Wanted): Target => {
275
+ if (!fromRegistry(wanted.range))
276
+ throw new Error(`${NpmErrors.Unservable}${asked} (${wanted.range})`)
277
+
278
+ const alias = /^npm:(.+?)(?:@([^@]+))?$/.exec(wanted.range ?? '')
279
+ const name = alias?.[1] ?? asked
280
+ const range = alias === null ? wanted.range : alias[2]
281
+
282
+ if (wanted.version !== undefined) return {name, spec: wanted.version}
283
+ return {name, spec: range ?? 'latest'}
284
+ }
285
+
286
+ export {download, facts, fromRegistry, packTarget, resolveVersion, versionPattern, view}
287
+ export type {Facts, Wanted}