@kaynooo/cli-pkg 0.18.1 → 0.19.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.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-pkg",
3
3
  "type": "module",
4
- "version": "0.18.1",
4
+ "version": "0.19.0",
5
5
  "description": "pkg: check an npm package before it is added, for a guessed name, a version under two weeks old and install scripts.",
6
6
  "author": "Kaynooo <contact@kaynooo.fr>",
7
7
  "license": "MIT",
@@ -12,27 +12,38 @@
12
12
  "directory": "packages/pkg"
13
13
  },
14
14
  "bugs": "https://github.com/Kayno0o/cli/issues",
15
- "keywords": ["npm", "package", "typosquat", "supply-chain", "dependencies"],
15
+ "keywords": [
16
+ "npm",
17
+ "package",
18
+ "typosquat",
19
+ "supply-chain",
20
+ "dependencies"
21
+ ],
22
+ "exports": {
23
+ "./guard": "./src/guard-export.ts"
24
+ },
16
25
  "bin": {
17
26
  "pkg": "./dist/cli.js"
18
27
  },
19
- "files": ["dist"],
28
+ "files": [
29
+ "dist",
30
+ "src/added.ts",
31
+ "src/guard-export.ts",
32
+ "src/pin.ts"
33
+ ],
20
34
  "engines": {
21
35
  "bun": ">=1.4.3"
22
36
  },
23
- "publishConfig": {
24
- "registry": "https://git.kaynooo.fr/api/packages/kaynooo/npm/"
25
- },
26
37
  "scripts": {
27
- "build": "$npm_execpath build src/cli.ts --target bun --outdir dist && $npm_execpath ../../scripts/shell-shebang.ts",
38
+ "build": "$npm_execpath ../../scripts/build.ts src/cli.ts --splitting",
28
39
  "pkg": "$npm_execpath src/cli.ts",
29
40
  "popular": "$npm_execpath scripts/popular.ts",
30
41
  "record": "$npm_execpath scripts/record.ts"
31
42
  },
32
43
  "dependencies": {
33
- "@kaynooo/utils": "3.1.0"
44
+ "@kaynooo/cli-kit": "0.50.0"
34
45
  },
35
46
  "devDependencies": {
36
- "@kaynooo/cli-kit": "0.46.4"
47
+ "@kaynooo/utils": "3.1.0"
37
48
  }
38
49
  }
package/src/added.ts ADDED
@@ -0,0 +1,150 @@
1
+ import { existsSync, readdirSync, readFileSync } from 'node:fs'
2
+ import { dirname, join } from 'node:path'
3
+ import process from 'node:process'
4
+ import { parseCommand, splitCommand } from '@kaynooo/cli-kit/shell'
5
+ import { NPM_INSTALLS, NPM_TEST_INSTALLS } from './pin'
6
+
7
+ // A redirect, `2>` once `2>&1` is split at its `&`, `>log`, or a bare `>` whose target is the next word.
8
+ const REDIRECT = /^\d*[<>]/
9
+ const BARE_REDIRECT = /^\d*(?:[<>]|>>)$/
10
+ // The subcommands adding a package, per package manager: `bun install <name>` adds it as `bun add` does, and `npm install-test <name>` installs it before the tests.
11
+ const ADDS: Record<string, Set<string>> = {
12
+ bun: new Set(['add', 'a', 'install', 'i']),
13
+ npm: new Set([...NPM_INSTALLS, ...NPM_TEST_INSTALLS, 'add']),
14
+ pnpm: new Set(['add', 'i', 'install']),
15
+ yarn: new Set(['add']),
16
+ }
17
+ // The subcommands running a package without installing it, and the programs doing only that.
18
+ const RUNS: Record<string, Set<string>> = {
19
+ bun: new Set(['x']),
20
+ npm: new Set(['exec', 'x']),
21
+ pnpm: new Set(['dlx']),
22
+ yarn: new Set(['dlx']),
23
+ }
24
+ const RUNNERS = new Set(['bunx', 'npx'])
25
+ // Flags whose value is a package to run.
26
+ const PACKAGE_FLAGS = new Set(['-p', '--package'])
27
+ // Flags whose value is the next word, not a package.
28
+ const VALUE_FLAGS = new Set(['--cwd', '--filter', '-F', '-c', '--call', '--workspace', '--registry', '--prefix', '-C', '--dir', '--config', '--cache-dir', '--loglevel', '--tag', '--save-prefix', '--userconfig', '--omit', '--include', '--fetch-timeout', '--fetch-retries', '--install-strategy', '--cache', '--linker', ...PACKAGE_FLAGS])
29
+ // The value flags of one manager alone: npm's `-w` names a workspace, where pnpm's is the boolean --workspace-root.
30
+ const OWN_VALUE_FLAGS: Record<string, Set<string>> = { npm: new Set(['-w']) }
31
+ // A specifier no registry serves: a path, a tarball, a workspace, a catalog entry or a git repository, `owner/repo` included.
32
+ const NOT_REGISTRY = /^(?:[./]|~(?:\/|$)|file:|link:|portal:|workspace:|catalog:|git[+:]|github:|gitlab:|bitbucket:|https?:)|\.tgz$|^[\w.-]+\/[\w.-]+(?:#.*)?$/
33
+ // `alias@npm:real@1.0.0` installs the real one.
34
+ const NPM_ALIAS = /^(?:@[^/]+\/)?[^@]+@npm:(.+)$/
35
+ // A step publishing a package: `ft release` (or its source run as `cli.ts release`), `bun publish`, `npm publish`, a lib's `just patch|minor|major`.
36
+ const PUBLISH = /\b(?:ft|cli\.ts)\s+release\b|\b(?:bun|npm|pnpm|yarn)\s+publish\b|\bjust\s+(?:patch|minor|major)\b/
37
+
38
+ // `name@1.2.3`, the shape of the version a publish just made.
39
+ const EXACT_SPEC = /^(?:@[^/]+\/)?[^@]+@\d+\.\d+\.\d+(?:[-+][\w.+-]+)?$/
40
+
41
+ // The name of a manifest, undefined when it is missing or broken.
42
+ function manifestName(folder: string): string | undefined {
43
+ try {
44
+ const { name } = JSON.parse(readFileSync(join(folder, 'package.json'), 'utf8')) as { name?: unknown }
45
+
46
+ return typeof name === 'string' ? name : undefined
47
+ }
48
+ catch {
49
+ return undefined
50
+ }
51
+ }
52
+
53
+ // The packages a publish run from here can release: the manifests from here up to the repository root, and the workspace members below that root.
54
+ function ownPackages(): Set<string> {
55
+ const names = new Set<string>()
56
+ let folder = process.cwd()
57
+
58
+ while (true) {
59
+ const name = manifestName(folder)
60
+
61
+ if (name !== undefined)
62
+ names.add(name)
63
+
64
+ for (const member of existsSync(join(folder, 'packages')) ? readdirSync(join(folder, 'packages')) : []) {
65
+ const memberName = manifestName(join(folder, 'packages', member))
66
+
67
+ if (memberName !== undefined)
68
+ names.add(memberName)
69
+ }
70
+
71
+ if (existsSync(join(folder, '.git')) || dirname(folder) === folder)
72
+ return names
73
+
74
+ folder = dirname(folder)
75
+ }
76
+ }
77
+
78
+ // `name` of `name@1.2.3`, scope included.
79
+ function specName(spec: string): string {
80
+ return spec.slice(0, spec.lastIndexOf('@'))
81
+ }
82
+
83
+ // The registry packages a command adds, as `name` or `name@version`, for `pkg` to check first; after a publish in the same command, an exact version of a package the repository publishes is what it just released, which pkg cannot see yet, so only those are left out.
84
+ export function addedPackages(command: string): string[] {
85
+ let published = false
86
+ let own: Set<string> | undefined
87
+
88
+ return splitCommand(command).flatMap((piece) => {
89
+ published ||= PUBLISH.test(piece.command)
90
+ const { program, args } = parseCommand(piece.command)
91
+ const [sub = '', ...rest] = args
92
+
93
+ const names = piecePackages(program, sub, args, rest)
94
+
95
+ if (!published)
96
+ return names
97
+
98
+ own ??= ownPackages()
99
+
100
+ return names.filter(name => !EXACT_SPEC.test(name) || !own!.has(specName(name)))
101
+ })
102
+ }
103
+
104
+ function piecePackages(program: string, sub: string, args: string[], rest: string[]): string[] {
105
+ if (RUNNERS.has(program))
106
+ return runnerPackages(args)
107
+
108
+ if (RUNS[program]?.has(sub))
109
+ return runnerPackages(rest)
110
+
111
+ if (!ADDS[program]?.has(sub))
112
+ return []
113
+
114
+ return rest.flatMap((word, index) => isSkipped(word, rest[index - 1] ?? '', program) ? [] : registryName(word))
115
+ }
116
+
117
+ function isSkipped(word: string, previous: string, program = ''): boolean {
118
+ return word.startsWith('-') || REDIRECT.test(word) || VALUE_FLAGS.has(previous) || OWN_VALUE_FLAGS[program]?.has(previous) === true || BARE_REDIRECT.test(previous)
119
+ }
120
+
121
+ // The registry package a word names, none for a source no registry serves, given bare or as the spec of `name@<spec>`.
122
+ function registryName(word: string): string[] {
123
+ const at = word.indexOf('@', 1)
124
+ const spec = at === -1 ? word : word.slice(at + 1)
125
+
126
+ if (NOT_REGISTRY.test(word) || (at !== -1 && !spec.startsWith('npm:') && NOT_REGISTRY.test(spec)))
127
+ return []
128
+
129
+ return [NPM_ALIAS.exec(word)?.[1] ?? word]
130
+ }
131
+
132
+ // What `bunx`, `npx`, `bun x` and `pnpm dlx` fetch and run: the packages named with -p/--package, else the first word that is not a flag, the rest being the program's own arguments.
133
+ function runnerPackages(words: string[]): string[] {
134
+ const named: string[] = []
135
+
136
+ for (const [index, word] of words.entries()) {
137
+ const previous = words[index - 1] ?? ''
138
+
139
+ if (PACKAGE_FLAGS.has(previous))
140
+ named.push(word)
141
+ else if (word.startsWith('--package='))
142
+ named.push(word.slice('--package='.length))
143
+ else if (!isSkipped(word, previous) && named.length === 0)
144
+ return registryName(word)
145
+ else if (!isSkipped(word, previous))
146
+ break
147
+ }
148
+
149
+ return named.flatMap(registryName)
150
+ }
@@ -0,0 +1,2 @@
1
+ export { addedPackages } from './added'
2
+ export { bareCommand, installRequests, LOCKFILES, type Manager, type Mismatch, mismatchFor, type Pinned } from './pin'
package/src/pin.ts ADDED
@@ -0,0 +1,199 @@
1
+ import type { Piece } from '@kaynooo/cli-kit/shell'
2
+ import { parenBalance, parseCommand, resolvePath, splitCommand } from '@kaynooo/cli-kit/shell'
3
+
4
+ export type Manager = 'bun' | 'pnpm' | 'yarn' | 'npm'
5
+ type Action = 'install' | 'frozen' | 'add' | 'remove' | 'update'
6
+ type Option = 'dev' | 'exact'
7
+
8
+ export interface Mismatch { piece: Piece, reason: string, rewrite: string | null }
9
+ export interface Pinned { dir: string, managers: ReadonlySet<Manager> }
10
+ // A flag before the subcommand (`--filter`, `-w`, `--cwd`) may aim the install elsewhere, so a request carrying one is never rewritten.
11
+ interface InstallRequest { piece: Piece, program: Manager, subcommand: string, rest: string[], dir: string, isRewritable: boolean, assignments: string[] }
12
+
13
+ export const LOCKFILES: readonly [string, Manager][] = [
14
+ ['bun.lock', 'bun'],
15
+ ['bun.lockb', 'bun'],
16
+ ['pnpm-lock.yaml', 'pnpm'],
17
+ ['yarn.lock', 'yarn'],
18
+ ['package-lock.json', 'npm'],
19
+ ]
20
+
21
+ // npm's install and its aliases and typos, per its own help.
22
+ export const NPM_INSTALLS = ['install', 'i', 'in', 'ins', 'inst', 'insta', 'instal', 'isnt', 'isnta', 'isntal', 'isntall'] as const
23
+ export const NPM_TEST_INSTALLS = ['it', 'install-test', 'cit', 'clean-install-test', 'install-ci-test'] as const
24
+
25
+ // The subcommands and aliases that install or rewrite dependencies, per each tool's own help, and what each does; null for one with no counterpart elsewhere. A bare `yarn` installs, hence "".
26
+ const ACTIONS: Record<Manager, ReadonlyMap<string, Action | null>> = {
27
+ bun: actions({ install: ['install', 'i'], add: ['add', 'a'], remove: ['remove', 'rm'], update: ['update'] }),
28
+ pnpm: actions({ install: ['install', 'i'], add: ['add'], remove: ['remove', 'rm'], update: ['update', 'up'] }),
29
+ yarn: new Map([...actions({ install: ['', 'install'], add: ['add'], remove: ['remove'], update: ['upgrade'] }), ['upgrade-interactive', null], ['import', null]]),
30
+ // An install that runs the tests after it has no counterpart elsewhere.
31
+ npm: new Map([...actions({
32
+ install: NPM_INSTALLS,
33
+ add: ['add'],
34
+ frozen: ['ci', 'clean-install', 'ic', 'install-clean', 'isntall-clean'],
35
+ remove: ['uninstall', 'unlink', 'remove', 'rm', 'r', 'un'],
36
+ update: ['update', 'u', 'up', 'upgrade', 'udpate'],
37
+ }), ...NPM_TEST_INSTALLS.map(name => [name, null] as const)]),
38
+ }
39
+
40
+ // What each manager runs for an action; a missing one has no faithful translation.
41
+ const COMMANDS: Record<Manager, Partial<Record<Action, string>>> = {
42
+ bun: { install: 'install', frozen: 'install --frozen-lockfile', add: 'add', remove: 'remove', update: 'update' },
43
+ pnpm: { install: 'install', frozen: 'install --frozen-lockfile', add: 'add', remove: 'remove', update: 'update' },
44
+ yarn: { install: 'install', add: 'add', remove: 'remove' },
45
+ npm: { install: 'install', frozen: 'ci', add: 'install', remove: 'uninstall', update: 'update' },
46
+ }
47
+
48
+ const OPTIONS: Record<Manager, Record<Option, string>> = {
49
+ bun: { dev: '--dev', exact: '--exact' },
50
+ pnpm: { dev: '--save-dev', exact: '--save-exact' },
51
+ yarn: { dev: '--dev', exact: '--exact' },
52
+ npm: { dev: '--save-dev', exact: '--save-exact' },
53
+ }
54
+
55
+ const OPTION_FLAGS: ReadonlyMap<string, Option> = new Map([
56
+ ['-D', 'dev'],
57
+ ['--save-dev', 'dev'],
58
+ ['--dev', 'dev'],
59
+ ['-E', 'exact'],
60
+ ['--save-exact', 'exact'],
61
+ ['--exact', 'exact'],
62
+ ])
63
+
64
+ const DIR_FLAGS = new Set(['--cwd', '-C', '--dir', '--prefix'])
65
+ const VALUE_FLAGS = new Set([...DIR_FLAGS, '--filter', '-F'])
66
+ const PLAIN_WORD = /^[\w=@./:+-]+$/
67
+ const AROUND_START = /^[\s(]*/
68
+ const AROUND_END = /[\s)]*$/
69
+
70
+ function actions(byAction: Partial<Record<Action, readonly string[]>>): Map<string, Action | null> {
71
+ return new Map(Object.entries(byAction).flatMap(([action, names]) => names.map(name => [name, action as Action] as const)))
72
+ }
73
+
74
+ function isManager(program: string): program is Manager {
75
+ return Object.hasOwn(ACTIONS, program)
76
+ }
77
+
78
+ // The same request in the pinned manager's words, or null when a flag or the action has no faithful translation.
79
+ export function translate(from: Manager, to: Manager, subcommand: string, rest: readonly string[]): string | null {
80
+ const packages = rest.filter(arg => !arg.startsWith('-'))
81
+ const flags = rest.filter(arg => arg.startsWith('-'))
82
+ const listed = ACTIONS[from].get(subcommand)
83
+ const action = listed === 'install' && packages.length > 0 ? 'add' : listed
84
+ const command = action ? COMMANDS[to][action] : undefined
85
+
86
+ if (!action || command === undefined || !packages.every(name => PLAIN_WORD.test(name)))
87
+ return null
88
+
89
+ const options: string[] = []
90
+
91
+ for (const flag of flags) {
92
+ const option = OPTION_FLAGS.get(flag) ?? (from === 'bun' && flag === '-d' ? 'dev' : undefined)
93
+
94
+ if (option === undefined || action !== 'add')
95
+ return null
96
+
97
+ options.push(OPTIONS[to][option])
98
+ }
99
+
100
+ return [to, command, ...options, ...packages].join(' ')
101
+ }
102
+
103
+ // Each piece of the command that installs or rewrites dependencies, with the directory it runs in.
104
+ export function installRequests(command: string, cwd: string, home: string): InstallRequest[] {
105
+ const requests: InstallRequest[] = []
106
+ // The folders to go back to as each subshell ends, so a `cd` inside `( ... )` does not outlive it.
107
+ const outer: string[] = []
108
+
109
+ for (const piece of splitCommand(command)) {
110
+ const { opened, closed } = parenBalance(piece.command)
111
+
112
+ for (let count = 0; count < opened; count++)
113
+ outer.push(cwd)
114
+
115
+ const request = requestOf(piece, cwd, home)
116
+
117
+ if (typeof request === 'string')
118
+ cwd = request
119
+ else if (request !== undefined)
120
+ requests.push(request)
121
+
122
+ for (let count = 0; count < closed; count++)
123
+ cwd = outer.pop() ?? cwd
124
+ }
125
+
126
+ return requests
127
+ }
128
+
129
+ // The install a piece asks for, or the folder a `cd` moves to.
130
+ function requestOf(piece: Piece, cwd: string, home: string): InstallRequest | string | undefined {
131
+ const { program, args, assignments, isWrapped } = parseCommand(piece.command)
132
+
133
+ if (program === 'cd' && args[0] !== undefined)
134
+ return resolvePath(cwd, args[0], home)
135
+
136
+ if (!isManager(program))
137
+ return undefined
138
+
139
+ let dir = cwd
140
+ let subcommand = ''
141
+ let rest: string[] = []
142
+ let hasLeadingFlag = false
143
+
144
+ // A folder option counts wherever it sits, before the subcommand or after it.
145
+ for (let i = 0; i < args.length; i++) {
146
+ const arg = args[i] ?? ''
147
+ const equals = arg.indexOf('=')
148
+ const flag = equals === -1 ? arg : arg.slice(0, equals)
149
+ const value = equals === -1 ? undefined : arg.slice(equals + 1)
150
+ const isLeading = subcommand === ''
151
+
152
+ if (DIR_FLAGS.has(flag) && value !== undefined && value !== '') {
153
+ dir = resolvePath(cwd, value, home)
154
+ }
155
+ else if (VALUE_FLAGS.has(arg)) {
156
+ if (DIR_FLAGS.has(arg) && args[i + 1] !== undefined)
157
+ dir = resolvePath(cwd, args[i + 1] ?? '', home)
158
+
159
+ i++
160
+ }
161
+ else if (isLeading && !arg.startsWith('-')) {
162
+ subcommand = arg
163
+ rest = args.slice(i + 1)
164
+
165
+ continue
166
+ }
167
+
168
+ hasLeadingFlag ||= isLeading
169
+ }
170
+
171
+ return ACTIONS[program].has(subcommand) ? { piece, program, subcommand, rest, dir, assignments, isRewritable: !hasLeadingFlag && !isWrapped && piece.command === piece.text } : undefined
172
+ }
173
+
174
+ // A piece's command less the whitespace and subshell parens around it.
175
+ export function bareCommand(text: string): string {
176
+ return text.replace(AROUND_START, '').replace(AROUND_END, '')
177
+ }
178
+
179
+ // The request against the managers its directory is pinned to, null when it runs with one of them.
180
+ export function mismatchFor(request: InstallRequest, pinned: Pinned | null): Mismatch | null {
181
+ const { piece, program, subcommand, rest, isRewritable, assignments } = request
182
+
183
+ if (!pinned || pinned.managers.has(program))
184
+ return null
185
+
186
+ const expected = [...pinned.managers]
187
+ const only = expected.length === 1 ? expected[0] : undefined
188
+ const canRewrite = only !== undefined && isRewritable && assignments.every(word => PLAIN_WORD.test(word))
189
+ const translated = canRewrite ? translate(program, only, subcommand, rest) : null
190
+ // What the piece holds around the command, the parens of a subshell it opens or closes included; a package name never holds one.
191
+ const leading = AROUND_START.exec(piece.text)?.[0] ?? ''
192
+ const trailing = AROUND_END.exec(piece.text)?.[0] ?? ''
193
+
194
+ return {
195
+ piece,
196
+ rewrite: translated === null ? null : `${leading}${[...assignments, translated].join(' ')}${trailing}`,
197
+ reason: `${pinned.dir} is pinned to ${expected.join(' or ')} by its lockfile, so \`${`${program} ${subcommand}`.trim()}\` would install with the wrong package manager.`,
198
+ }
199
+ }