@exodus/stasis 1.0.0-beta.9 → 1.0.0-rc.1
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/README.md +6 -2
- package/bin/stasis.js +222 -334
- package/package.json +38 -14
- package/src/audit-corrections.js +11 -42
- package/src/audit.js +256 -212
- package/src/babel.js +119 -82
- package/src/bundle-from-lockfile.js +9 -21
- package/src/bundle-reader.js +24 -8
- package/src/bundle.js +0 -3
- package/src/cmd/build.js +211 -117
- package/src/cmd/bundle-options.js +347 -0
- package/src/cmd/bundle.js +1664 -1001
- package/src/cmd/diff.js +1 -4
- package/src/cmd/github-bundle.js +48 -21
- package/src/cmd/output.js +25 -12
- package/src/cmd/sbom.js +6 -9
- package/src/cmd/tokens.js +60 -0
- package/src/define.js +218 -0
- package/src/diff.js +73 -129
- package/src/esbuild.js +0 -4
- package/src/flow.js +27 -0
- package/src/installed.js +265 -0
- package/src/json-stream.js +4 -9
- package/src/loader-mock.js +3 -8
- package/src/loader.js +1 -5
- package/src/loaders/bash.js +43 -120
- package/src/loaders/cargo.js +301 -808
- package/src/loaders/foundry.js +112 -290
- package/src/loaders/paths.js +15 -26
- package/src/loaders/php.js +211 -492
- package/src/loaders/rust.js +518 -1461
- package/src/loaders/solidity-ownership.js +51 -142
- package/src/loaders/solidity.js +42 -188
- package/src/loaders/toml.js +7 -17
- package/src/lockfile.js +0 -3
- package/src/metro-assets.js +41 -0
- package/src/metro-resolver.js +58 -133
- package/src/metro-transformer.js +0 -6
- package/src/metro.js +0 -4
- package/src/mock.js +32 -80
- package/src/parse.js +8 -7
- package/src/prune.js +0 -3
- package/src/resolve-fields.js +152 -249
- package/src/resolve-node.js +29 -45
- package/src/resolve-typescript.js +166 -298
- package/src/rollup.js +0 -4
- package/src/run-installed.js +10 -0
- package/src/sbom.js +70 -97
- package/src/scan.js +240 -282
- package/src/sixel.js +310 -0
- package/src/table.js +95 -0
- package/src/validate-notes.d.ts +19 -0
- package/src/validate-notes.js +72 -0
- package/src/validate.d.ts +159 -0
- package/src/validate.js +1315 -0
- package/src/vfs-bundle/entries.js +50 -46
- package/src/vfs-bundle/github.js +114 -94
- package/src/vfs-bundle/glob.js +379 -0
- package/src/vfs-bundle/lazy.js +99 -0
- package/src/vfs-bundle/prisma.js +235 -105
- package/src/vfs-bundle/soldeer.js +28 -49
- package/src/vfs-bundle/tree.js +418 -277
- package/src/vfs-bundle/yarnclean.js +79 -0
- package/src/vfs-bundle.js +24 -55
- package/src/webpack.js +0 -4
- package/src/why.js +79 -231
- package/src/installed-commits.js +0 -182
package/src/cmd/diff.js
CHANGED
|
@@ -4,16 +4,13 @@ import { sha512integrity } from '@exodus/stasis-core/state-util'
|
|
|
4
4
|
import { parseFileWithKind } from '../parse.js'
|
|
5
5
|
import { diffArtifacts, formatDiffStat, hasDifferences } from '../diff.js'
|
|
6
6
|
|
|
7
|
-
// Run `stasis diff
|
|
8
|
-
// the file-free diff API. Returns { diff, differences } for the caller's exit code.
|
|
7
|
+
// Run `stasis diff`. -> { diff, differences } for the caller's exit code
|
|
9
8
|
export function diffCommand({ cwd = process.cwd(), left, right, stat, imports = false, out = process.stdout } = {}) {
|
|
10
9
|
if (!left || !right) throw new Error('diff: two files (lockfile or bundle) are required')
|
|
11
10
|
if (!stat) throw new Error('diff: only --stat is implemented; pass stat: true')
|
|
12
|
-
|
|
13
11
|
const a = parseFileWithKind(resolve(cwd, left))
|
|
14
12
|
const b = parseFileWithKind(resolve(cwd, right))
|
|
15
13
|
const diff = diffArtifacts(a, b, { imports, hash: sha512integrity })
|
|
16
|
-
|
|
17
14
|
out.write(formatDiffStat(diff, { left, right, leftKind: a.kind, rightKind: b.kind }))
|
|
18
15
|
return { diff, differences: hasDifferences(diff) }
|
|
19
16
|
}
|
package/src/cmd/github-bundle.js
CHANGED
|
@@ -1,23 +1,24 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto'
|
|
2
|
-
import {
|
|
2
|
+
import { existsSync } from 'node:fs'
|
|
3
|
+
import { relative, resolve } from 'node:path'
|
|
3
4
|
|
|
5
|
+
import { BUNDLE_FILE, LOCK_FILE } from '@exodus/stasis-core/util'
|
|
4
6
|
import { createClient } from '@preventive/upstream/github.js'
|
|
5
7
|
import { buildGitHubBundle } from '../vfs-bundle/github.js'
|
|
6
|
-
import {
|
|
8
|
+
import { debugTimed, heldToLockfile } from './bundle.js'
|
|
9
|
+
import { githubToken, withNpmToken } from './tokens.js'
|
|
10
|
+
import { bundledSummary, heldSummary, lockedSummary, lockfileOnlyError, unpackedSummary, writeBundleOf, writeFile } from './output.js'
|
|
7
11
|
|
|
8
12
|
// The longest file name ext4, APFS and NTFS take: 255 bytes, or characters, ours being ASCII.
|
|
9
13
|
const NAME_MAX = 255
|
|
10
|
-
// Each character outside the portable filename set [A-Za-z0-9._-] made `_`.
|
|
11
14
|
const portable = (s) => s.replaceAll(/[^\w.-]/gu, '_')
|
|
12
15
|
|
|
13
|
-
//
|
|
14
|
-
//
|
|
15
|
-
//
|
|
16
|
-
|
|
17
|
-
// characters) leaves at least 91 for it.
|
|
18
|
-
export function githubBundleFile({ github, directory, commit }) {
|
|
16
|
+
// `owner-name[.<directory, its / made ->].<commit's first 7>.stasis.code.br`, or `.stasis.lock.json` for
|
|
17
|
+
// `suffix` LOCK_FILE. A directory too long for NAME_MAX keeps what fits of its start, then `_` and its sha256's
|
|
18
|
+
// first 8 (a valid `github` leaves it 91 at least, 89 of a lockfile).
|
|
19
|
+
export function githubBundleFile({ github, directory, commit }, suffix = BUNDLE_FILE) {
|
|
19
20
|
const repo = portable(github.replace('/', '-'))
|
|
20
|
-
const tail = `.${portable(commit.slice(0, 7))}
|
|
21
|
+
const tail = `.${portable(commit.slice(0, 7))}.${suffix}`
|
|
21
22
|
if (!directory) return `${repo}${tail}`
|
|
22
23
|
const room = NAME_MAX - `${repo}.${tail}`.length
|
|
23
24
|
let dir = portable(directory.replaceAll('/', '-'))
|
|
@@ -25,15 +26,41 @@ export function githubBundleFile({ github, directory, commit }) {
|
|
|
25
26
|
return `${repo}.${dir}${tail}`
|
|
26
27
|
}
|
|
27
28
|
|
|
28
|
-
// Run `stasis github-bundle
|
|
29
|
-
//
|
|
30
|
-
//
|
|
31
|
-
//
|
|
32
|
-
//
|
|
33
|
-
export async function githubBundleCommand({ cwd = process.cwd(), env = process.env, output, lockfile, brotliQuality, client, ...options } = {}) {
|
|
34
|
-
const
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
29
|
+
// Run `stasis github-bundle`. Of `env`, only GITHUB_TOKEN and EXODUS_STASIS_LOCK are read.
|
|
30
|
+
// The local lockfile is `lockfile`, else the one named as the bundle would be, `.stasis.lock.json` for
|
|
31
|
+
// `.stasis.code.br`. One there holds the build, by EXODUS_STASIS_LOCK's mode, frozen without it: it must attest the
|
|
32
|
+
// build, and the repo it records the build's, and is left as it is. One not there is written, where `lockfile` or
|
|
33
|
+
// `lockfileOnly` asks for it, recording the repo as the bundle does.
|
|
34
|
+
export async function githubBundleCommand({ cwd = process.cwd(), env = process.env, home, output, lockfile, lockfileOnly = false, brotliQuality, client, ...options } = {}) {
|
|
35
|
+
const lockfileOnlyRefused = lockfileOnly ? lockfileOnlyError({ lockfile, output, brotliQuality, named: true }) : null
|
|
36
|
+
if (lockfileOnlyRefused !== null) throw new Error(`githubBundleCommand: ${lockfileOnlyRefused}`)
|
|
37
|
+
const locks = lockfile !== undefined || lockfileOnly
|
|
38
|
+
// The local lockfile's mode is the environment's alone: a repo's `lock: frozen` pins its own stasis.lock.json.
|
|
39
|
+
const mode = env.EXODUS_STASIS_LOCK || 'frozen'
|
|
40
|
+
if (locks && (mode === 'ignore' || mode === 'none')) throw new Error(`githubBundleCommand: ${lockfile === undefined ? '--lockfile-only' : '--lockfile'}: lock = ${mode} writes no lockfile`)
|
|
41
|
+
// buildGitHubBundle reads only whether a lockfile is asked for, refusing one but of a JS bundle; it writes none.
|
|
42
|
+
const built = await withNpmToken(home, () => buildGitHubBundle({ ...options, lockfile: locks ? lockfile ?? LOCK_FILE : undefined, lock: env.EXODUS_STASIS_LOCK || undefined, client: client ?? createClient({ token: githubToken({ env, home }) }) }))
|
|
43
|
+
const { directory, bundle } = built
|
|
44
|
+
const named = (suffix) => githubBundleFile({ github: options.github, directory, commit: bundle.repo.commit }, suffix)
|
|
45
|
+
const lockTarget = lockfile ?? named(LOCK_FILE)
|
|
46
|
+
const lockAbs = resolve(cwd, lockTarget)
|
|
47
|
+
const label = relative(resolve(cwd), lockAbs)
|
|
48
|
+
// Before anything is written: the build, and the lockfile it writes, take what the one there alone attests. Of
|
|
49
|
+
// a build of none (a Solidity one), it holds nothing.
|
|
50
|
+
const present = existsSync(lockAbs)
|
|
51
|
+
const held = present && heldToLockfile(() => built.lockfile, lockAbs, label, mode, { bundle, accounts: built.accounts, repo: bundle.repo }) !== undefined
|
|
52
|
+
const writes = locks && !(present && mode === 'frozen')
|
|
53
|
+
// Built before anything is written, as `stasis bundle` builds it.
|
|
54
|
+
const lockData = writes ? built.lockfile.serialize() : undefined
|
|
55
|
+
let dest
|
|
56
|
+
// Serialized under --lockfile-only too: never write a lockfile of a bundle that couldn't be written.
|
|
57
|
+
if (lockfileOnly) bundle.serializedBytes()
|
|
58
|
+
else dest = await debugTimed('Wrote the bundle', () => writeBundleOf(cwd, output ?? named(BUNDLE_FILE), bundle, brotliQuality))
|
|
59
|
+
if (lockData !== undefined) writeFile(lockAbs, lockData)
|
|
60
|
+
const from = `${options.github}@${bundle.repo.commit}${directory ? `/${directory}` : ''}`
|
|
61
|
+
const summarized = (summary, to) => summary(bundle.sources.size, bundle.modules, from, to)
|
|
62
|
+
console.warn(unpackedSummary(built.stats))
|
|
63
|
+
if (held) console.warn(summarized(heldSummary, label))
|
|
64
|
+
if (!lockfileOnly) console.warn(summarized(bundledSummary, dest))
|
|
65
|
+
else if (writes) console.warn(summarized(lockedSummary, lockTarget))
|
|
39
66
|
}
|
package/src/cmd/output.js
CHANGED
|
@@ -1,19 +1,14 @@
|
|
|
1
1
|
import { mkdirSync, writeFileSync } from 'node:fs'
|
|
2
2
|
import { dirname, resolve } from 'node:path'
|
|
3
|
-
import { brotliCompressSync } from 'node:zlib'
|
|
4
3
|
|
|
5
|
-
import {
|
|
4
|
+
import { compressBundle, compressBundleText } from '@exodus/stasis-core/brotli'
|
|
6
5
|
|
|
7
|
-
// Default bundle output: stasis.code.br, the same name `stasis run --bundle=load` discovers, so the two round-trip with no flags.
|
|
8
|
-
export const DEFAULT_BUNDLE_FILE = 'stasis.code.br'
|
|
9
|
-
|
|
10
|
-
// Write `data` to the absolute path `abs`, creating its directory.
|
|
11
6
|
export function writeFile(abs, data) {
|
|
12
7
|
mkdirSync(dirname(abs), { recursive: true })
|
|
13
8
|
writeFileSync(abs, data)
|
|
14
9
|
}
|
|
15
10
|
|
|
16
|
-
//
|
|
11
|
+
// `target` from `cwd`, or `-` for stdout. -> where it went, for the summary
|
|
17
12
|
export function writeOutput(cwd, target, data) {
|
|
18
13
|
if (target === '-') {
|
|
19
14
|
process.stdout.write(data)
|
|
@@ -23,14 +18,32 @@ export function writeOutput(cwd, target, data) {
|
|
|
23
18
|
return target
|
|
24
19
|
}
|
|
25
20
|
|
|
26
|
-
|
|
27
|
-
export const
|
|
21
|
+
export const writeBundle = (cwd, target, serialized, brotliQuality) => writeOutput(cwd, target, compressBundleText(serialized, brotliQuality))
|
|
22
|
+
export const writeBundleOf = (cwd, target, bundle, brotliQuality) => writeOutput(cwd, target, compressBundle(bundle, brotliQuality))
|
|
28
23
|
|
|
29
|
-
// `N package(s)`:
|
|
24
|
+
// `N package(s)`: the non-empty buckets of `modules`, the "." workspace bucket one of them.
|
|
30
25
|
export function packagesLabel(modules) {
|
|
31
26
|
const packages = [...modules.values()].filter((m) => Object.keys(m.files).length > 0).length
|
|
32
27
|
return `${packages} package${packages === 1 ? '' : 's'}`
|
|
33
28
|
}
|
|
34
29
|
|
|
35
|
-
|
|
36
|
-
|
|
30
|
+
export function unpackedSummary({ unpacked, installed, dependencies, files, bytes, tarballs }) {
|
|
31
|
+
const fetched = typeof tarballs === 'number' ? `, ${tarballs} tarball${tarballs === 1 ? '' : 's'} fetched` : ''
|
|
32
|
+
return `[stasis] Unpacked ${unpacked} of ${installed ?? dependencies} packages: ${files} files, ${(bytes / 2 ** 20).toFixed(1)} MiB${fetched}`
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const summary = (verb) => (count, modules, from, dest) => `[stasis] ${verb} ${count} files in ${packagesLabel(modules)} from ${from} to ${dest}`
|
|
36
|
+
export const bundledSummary = summary('Bundled')
|
|
37
|
+
export const lockedSummary = summary('Locked')
|
|
38
|
+
export const heldSummary = summary('Held')
|
|
39
|
+
|
|
40
|
+
// Why --lockfile-only can't be taken with these output options, or null where it can; `brotliQuality`
|
|
41
|
+
// counts as given, parsed or not. `named`: a lockfile left out is named by the command, so only an empty one is refused.
|
|
42
|
+
export function lockfileOnlyError({ lockfile, output, add = false, brotliQuality, named = false }) {
|
|
43
|
+
if (named && lockfile === '') return "--lockfile can't be empty: give a path, or leave it out for the default name"
|
|
44
|
+
if (!lockfile && !named) return '--lockfile-only requires --lockfile=path'
|
|
45
|
+
if (output !== undefined) return "--lockfile-only can't be combined with --output (no bundle is written)"
|
|
46
|
+
if (add) return "--lockfile-only can't be combined with --add (no bundle is merged into)"
|
|
47
|
+
if (brotliQuality !== undefined) return "--lockfile-only can't be combined with --brotli-quality (no bundle is compressed)"
|
|
48
|
+
return null
|
|
49
|
+
}
|
package/src/cmd/sbom.js
CHANGED
|
@@ -6,16 +6,13 @@ import { writeOutput } from './output.js'
|
|
|
6
6
|
|
|
7
7
|
// The one-line summary goes to stderr so it never corrupts an SBOM streamed to stdout.
|
|
8
8
|
export function sbomCommand({ cwd = process.cwd(), files, format, output, now, uuid } = {}) {
|
|
9
|
-
if (!Array.isArray(files) || files.length === 0)
|
|
10
|
-
|
|
11
|
-
}
|
|
12
|
-
const artifacts = files.map((f) => parseFile(resolve(cwd, f)))
|
|
13
|
-
const components = collectComponents(artifacts)
|
|
9
|
+
if (!Array.isArray(files) || files.length === 0) throw new Error('sbom: at least one lockfile or bundle is required')
|
|
10
|
+
const components = collectComponents(files.map((f) => parseFile(resolve(cwd, f))))
|
|
14
11
|
const doc = generateSbom(format, components, { now, uuid })
|
|
15
|
-
const
|
|
16
|
-
|
|
17
|
-
const dest = writeOutput(cwd, output ?? '-', text)
|
|
12
|
+
const dest = writeOutput(cwd, output ?? '-', JSON.stringify(doc, undefined, 2) + '\n')
|
|
18
13
|
const n = components.length
|
|
19
|
-
|
|
14
|
+
const vendored = components.reduce((sum, c) => sum + (c.vendored?.length ?? 0), 0)
|
|
15
|
+
const inThem = vendored === 0 ? '' : ` (and ${vendored} vendored in them)`
|
|
16
|
+
console.warn(`[stasis] Wrote ${format} SBOM with ${n} component${n === 1 ? '' : 's'}${inThem} to ${dest}`)
|
|
20
17
|
return { components, doc }
|
|
21
18
|
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { isUtf8 } from 'node:buffer'
|
|
2
|
+
import { readFileSync } from 'node:fs'
|
|
3
|
+
import { homedir } from 'node:os'
|
|
4
|
+
import { join } from 'node:path'
|
|
5
|
+
|
|
6
|
+
import { readJson } from '@exodus/stasis-core/bundle-util'
|
|
7
|
+
|
|
8
|
+
// What @preventive/upstream's npm client takes its token from: the first set, read on each request.
|
|
9
|
+
export const NPM_TOKEN_VARS = ['PREVENTIVE_MEASURES_NPM_TOKEN', 'STASIS_NPM_TOKEN', 'NPM_TOKEN']
|
|
10
|
+
|
|
11
|
+
// Printable ASCII and no space, as @preventive/upstream takes one; anything else is none, so that it
|
|
12
|
+
// never reaches an error message.
|
|
13
|
+
const asToken = (value) => (typeof value === 'string' && /^[!-~]+$/u.test(value.trim()) ? value.trim() : undefined)
|
|
14
|
+
|
|
15
|
+
// `<home>/.audit/config.json`'s tokens. Another tool's file, read for compatibility: one missing,
|
|
16
|
+
// unreadable or of another shape gives none, silently.
|
|
17
|
+
export function auditTokens(home) {
|
|
18
|
+
const config = readJson(join(home ?? homedir(), '.audit', 'config.json'))
|
|
19
|
+
return config === null ? {} : { token: asToken(config.token), npmToken: asToken(config.npmToken) }
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function githubToken({ env = process.env, home } = {}) {
|
|
23
|
+
return env.GITHUB_TOKEN || auditTokens(home).token || null
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// npm's registry's token exactly as npm writes it: no other registry's, no variable to expand.
|
|
27
|
+
const NPMRC_LINE = /^\/\/registry\.npmjs\.org\/:_authToken=(npm_[\dA-Za-z]+)\r?$/u
|
|
28
|
+
|
|
29
|
+
// `<home>/.npmrc`'s last NPMRC_LINE, as npm takes the last of a setting given twice. A missing or
|
|
30
|
+
// unreadable file gives none, silently; one that is not UTF-8 is refused.
|
|
31
|
+
export function npmrcToken(home) {
|
|
32
|
+
const file = join(home ?? homedir(), '.npmrc')
|
|
33
|
+
let bytes
|
|
34
|
+
try {
|
|
35
|
+
bytes = readFileSync(file)
|
|
36
|
+
} catch {
|
|
37
|
+
return undefined
|
|
38
|
+
}
|
|
39
|
+
if (!isUtf8(bytes)) throw new Error(`${file} is not valid UTF-8`)
|
|
40
|
+
let token
|
|
41
|
+
for (const line of bytes.toString('utf8').split('\n')) token = NPMRC_LINE.exec(line)?.[1] ?? token
|
|
42
|
+
return token
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// `fn()` with STASIS_NPM_TOKEN auditTokens' or npmrcToken's where no NPM_TOKEN_VARS is set (each file only
|
|
46
|
+
// read then), restored after unless something else set it meanwhile.
|
|
47
|
+
export async function withNpmToken(home, fn) {
|
|
48
|
+
const token = NPM_TOKEN_VARS.some((name) => process.env[name]) ? undefined : (auditTokens(home).npmToken ?? npmrcToken(home))
|
|
49
|
+
if (token === undefined) return fn()
|
|
50
|
+
const before = process.env.STASIS_NPM_TOKEN
|
|
51
|
+
process.env.STASIS_NPM_TOKEN = token
|
|
52
|
+
try {
|
|
53
|
+
return await fn()
|
|
54
|
+
} finally {
|
|
55
|
+
if (process.env.STASIS_NPM_TOKEN === token) {
|
|
56
|
+
if (before === undefined) delete process.env.STASIS_NPM_TOKEN
|
|
57
|
+
else process.env.STASIS_NPM_TOKEN = before
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
package/src/define.js
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
import { isPlainObject, memoized } from '@exodus/stasis-core/util'
|
|
2
|
+
|
|
3
|
+
// --define: globals' values (`__DEV__`, `process.env.NODE_ENV`) the scan takes as constants, leaving out the imports in
|
|
4
|
+
// branches they keep from running. No test folds that Metro wouldn't fold, so a --metro bundle lacks no file Metro holds.
|
|
5
|
+
|
|
6
|
+
// What Metro's release build (`dev: false`) inlines and its prelude gives the globals: --metro's default defines.
|
|
7
|
+
export const METRO_RELEASE_DEFINE = Object.freeze({ __DEV__: false, 'process.env.NODE_ENV': 'production' })
|
|
8
|
+
|
|
9
|
+
const NAME = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/u
|
|
10
|
+
|
|
11
|
+
const usageError = (name, message, ErrorType = Error) => new ErrorType(name ? `${name}: ${message}` : message)
|
|
12
|
+
|
|
13
|
+
export function parseDefine(name, define) {
|
|
14
|
+
if (define === undefined) return new Map()
|
|
15
|
+
if (!isPlainObject(define)) throw usageError(name, "define must be an object of each name's value", TypeError)
|
|
16
|
+
for (const [key, value] of Object.entries(define)) {
|
|
17
|
+
if (!NAME.test(key)) throw usageError(name, `--define names an identifier or a dotted path of them (e.g. __DEV__, process.env.NODE_ENV), not ${JSON.stringify(key)}`)
|
|
18
|
+
if (!(value === null || ['string', 'boolean'].includes(typeof value) || Number.isFinite(value))) {
|
|
19
|
+
throw usageError(name, `--define's value for ${key} must be a string, number, boolean or null, not ${typeof value === 'object' ? JSON.stringify(value) : String(value)}`)
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
return new Map(Object.entries(define))
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// `--define=KEY=VALUE` texts -> parseDefine's object. VALUE is JSON, as esbuild's --define takes it.
|
|
26
|
+
export function parseDefineFlags(name, texts) {
|
|
27
|
+
if (texts.length === 0) throw usageError(name, '--define must give at least one KEY=VALUE (e.g. --define=__DEV__=false)')
|
|
28
|
+
const define = {}
|
|
29
|
+
for (const text of texts) {
|
|
30
|
+
const eq = text.indexOf('=')
|
|
31
|
+
if (eq <= 0) throw usageError(name, `--define must be KEY=VALUE (e.g. --define=__DEV__=false), not ${JSON.stringify(text)}`)
|
|
32
|
+
const key = text.slice(0, eq)
|
|
33
|
+
if (Object.hasOwn(define, key)) throw usageError(name, `--define gives ${key} a value twice`)
|
|
34
|
+
try {
|
|
35
|
+
define[key] = JSON.parse(text.slice(eq + 1))
|
|
36
|
+
} catch {
|
|
37
|
+
throw usageError(name, `--define's value for ${key} must be JSON: a string, quoted (--define=${key}='"production"'), a number, true, false or null, not ${JSON.stringify(text.slice(eq + 1))}`)
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
parseDefine(name, define)
|
|
41
|
+
return define
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const UNKNOWN = Symbol('unknown')
|
|
45
|
+
// Gone by the time Metro folds (Babel keeps no parentheses, and TypeScript's are stripped first).
|
|
46
|
+
const WRAPPERS = new Set(['ParenthesizedExpression', 'TSAsExpression', 'TSSatisfiesExpression', 'TSNonNullExpression', 'TSTypeAssertion'])
|
|
47
|
+
const EQUALITY = new Set(['===', '!==', '==', '!='])
|
|
48
|
+
const SKIP_KEYS = new Set(['type', 'loc', 'range', 'start', 'end', 'typeAnnotation', 'returnType', 'typeParameters', 'typeArguments'])
|
|
49
|
+
// The child a node of each type binds or writes; functions, `delete` and for-in/of are ownPaths' own.
|
|
50
|
+
const BINDS = {
|
|
51
|
+
__proto__: null,
|
|
52
|
+
VariableDeclarator: 'id', ClassDeclaration: 'id', ClassExpression: 'id',
|
|
53
|
+
TSImportEqualsDeclaration: 'id', TSEnumDeclaration: 'id', TSModuleDeclaration: 'id',
|
|
54
|
+
ImportSpecifier: 'local', ImportDefaultSpecifier: 'local', ImportNamespaceSpecifier: 'local',
|
|
55
|
+
CatchClause: 'param', AssignmentExpression: 'left', UpdateExpression: 'argument',
|
|
56
|
+
}
|
|
57
|
+
const FUNCTIONS = new Set(['FunctionDeclaration', 'FunctionExpression', 'ArrowFunctionExpression'])
|
|
58
|
+
|
|
59
|
+
// Plain property accesses alone, as Metro inlines them: not `process.env['NODE_ENV']` or `process.env?.NODE_ENV`.
|
|
60
|
+
function dottedPath(node) {
|
|
61
|
+
const parts = []
|
|
62
|
+
for (;;) {
|
|
63
|
+
if (WRAPPERS.has(node.type)) node = node.expression
|
|
64
|
+
else if (node.type === 'MemberExpression' && !node.computed && !node.optional) {
|
|
65
|
+
parts.unshift(node.property.name)
|
|
66
|
+
node = node.object
|
|
67
|
+
} else break
|
|
68
|
+
}
|
|
69
|
+
if (node.type !== 'Identifier') return null
|
|
70
|
+
parts.unshift(node.name)
|
|
71
|
+
return parts.join('.')
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// As far as it is static from its root identifier (`process.env[name]` writes `process.env`).
|
|
75
|
+
function writtenPath(node) {
|
|
76
|
+
const parts = []
|
|
77
|
+
while (WRAPPERS.has(node.type) || node.type === 'MemberExpression') {
|
|
78
|
+
if (node.type === 'MemberExpression') {
|
|
79
|
+
const property = node.computed
|
|
80
|
+
? (node.property.type === 'Literal' && typeof node.property.value === 'string' ? node.property.value : null)
|
|
81
|
+
: node.property.name
|
|
82
|
+
// A computed part cuts the path there: what lies past it, it can't name.
|
|
83
|
+
if (property === null) parts.length = 0
|
|
84
|
+
else parts.unshift(property)
|
|
85
|
+
node = node.object
|
|
86
|
+
} else {
|
|
87
|
+
node = node.expression
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
if (node.type !== 'Identifier') return null
|
|
91
|
+
parts.unshift(node.name)
|
|
92
|
+
return parts.join('.')
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// A declaration of `process` or an assignment to `process.env.NODE_ENV` makes it the file's own, not the define's.
|
|
96
|
+
// What is only declared for the type checker (`declare const __DEV__: boolean`) binds nothing.
|
|
97
|
+
function ownPaths(program) {
|
|
98
|
+
const paths = new Set()
|
|
99
|
+
const target = (node) => {
|
|
100
|
+
if (!node) return
|
|
101
|
+
if (node.type === 'Identifier') paths.add(node.name)
|
|
102
|
+
else if (node.type === 'ObjectPattern') for (const p of node.properties) target(p.type === 'RestElement' ? p.argument : p.value)
|
|
103
|
+
else if (node.type === 'ArrayPattern') for (const e of node.elements) target(e)
|
|
104
|
+
else if (node.type === 'AssignmentPattern') target(node.left)
|
|
105
|
+
else if (node.type === 'RestElement') target(node.argument)
|
|
106
|
+
else if (node.type === 'TSParameterProperty') target(node.parameter)
|
|
107
|
+
else if (node.type === 'MemberExpression' || WRAPPERS.has(node.type)) {
|
|
108
|
+
const path = writtenPath(node)
|
|
109
|
+
if (path !== null) paths.add(path)
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
const visit = (node) => {
|
|
113
|
+
if (!node || typeof node !== 'object') return
|
|
114
|
+
if (Array.isArray(node)) {
|
|
115
|
+
for (const c of node) visit(c)
|
|
116
|
+
return
|
|
117
|
+
}
|
|
118
|
+
if (typeof node.type !== 'string' || node.declare === true) return
|
|
119
|
+
if (node.type in BINDS) target(node[BINDS[node.type]])
|
|
120
|
+
else if (FUNCTIONS.has(node.type)) for (const p of [node.id, ...node.params]) target(p)
|
|
121
|
+
else if (node.type === 'UnaryExpression' && node.operator === 'delete') target(node.argument)
|
|
122
|
+
else if ((node.type === 'ForInStatement' || node.type === 'ForOfStatement') && node.left.type !== 'VariableDeclaration') target(node.left)
|
|
123
|
+
for (const key of Object.keys(node)) if (!SKIP_KEYS.has(key)) visit(node[key])
|
|
124
|
+
}
|
|
125
|
+
visit(program)
|
|
126
|
+
return paths
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function owned(own, key) {
|
|
130
|
+
for (let i = key.length; i > 0; i = key.lastIndexOf('.', i - 1)) {
|
|
131
|
+
if (own.has(key.slice(0, i))) return true
|
|
132
|
+
}
|
|
133
|
+
return false
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// For a branch whose test folds, the children to walk: the test and the side that runs. null where no define applies
|
|
137
|
+
// to the file (each one given is the file's own).
|
|
138
|
+
export function branchFolder(defines, program) {
|
|
139
|
+
if (defines.size === 0) return null
|
|
140
|
+
const own = ownPaths(program)
|
|
141
|
+
const values = new Map([...defines].filter(([key]) => !owned(own, key)))
|
|
142
|
+
if (values.size === 0) return null
|
|
143
|
+
|
|
144
|
+
const folded = memoized((node) => evaluate(node))
|
|
145
|
+
const fold = (node) => (node ? folded(node) : UNKNOWN)
|
|
146
|
+
// What Metro's constant folding evaluates once it has inlined the defines (Babel's path.evaluate()), and less: a
|
|
147
|
+
// value it can't be sure Metro folds is UNKNOWN, as the bundle may never leave out a file Metro's graph holds.
|
|
148
|
+
const evaluate = (node) => {
|
|
149
|
+
if (WRAPPERS.has(node.type)) return fold(node.expression)
|
|
150
|
+
switch (node.type) {
|
|
151
|
+
case 'Literal':
|
|
152
|
+
return node.regex === undefined && node.bigint === undefined ? node.value : UNKNOWN
|
|
153
|
+
case 'TemplateLiteral':
|
|
154
|
+
return node.expressions.length === 0 && typeof node.quasis[0].value.cooked === 'string' ? node.quasis[0].value.cooked : UNKNOWN
|
|
155
|
+
case 'Identifier':
|
|
156
|
+
case 'MemberExpression': {
|
|
157
|
+
const path = dottedPath(node)
|
|
158
|
+
return path !== null && values.has(path) ? values.get(path) : UNKNOWN
|
|
159
|
+
}
|
|
160
|
+
case 'UnaryExpression': {
|
|
161
|
+
// Metro folds a `void` of a literal alone (`void 0`).
|
|
162
|
+
if (node.operator === 'void') return node.argument.type === 'Literal' ? undefined : UNKNOWN
|
|
163
|
+
if (node.operator !== '!') return UNKNOWN // `typeof`: see BinaryExpression
|
|
164
|
+
const value = fold(node.argument)
|
|
165
|
+
return value === UNKNOWN ? UNKNOWN : !value
|
|
166
|
+
}
|
|
167
|
+
case 'BinaryExpression': {
|
|
168
|
+
if (!EQUALITY.has(node.operator)) return UNKNOWN
|
|
169
|
+
const left = operand(node.left, node.right)
|
|
170
|
+
const right = left === UNKNOWN ? UNKNOWN : operand(node.right, node.left)
|
|
171
|
+
if (right === UNKNOWN) return UNKNOWN
|
|
172
|
+
// eslint-disable-next-line eqeqeq -- the source's own loose comparison, of primitives
|
|
173
|
+
const equal = node.operator.length === 3 ? left === right : left == right
|
|
174
|
+
return node.operator.startsWith('=') ? equal : !equal
|
|
175
|
+
}
|
|
176
|
+
case 'LogicalExpression': {
|
|
177
|
+
const left = node.operator === '??' ? UNKNOWN : fold(node.left)
|
|
178
|
+
if (left === UNKNOWN) return UNKNOWN
|
|
179
|
+
return rightRuns(node.operator, left) ? fold(node.right) : left
|
|
180
|
+
}
|
|
181
|
+
case 'ConditionalExpression': {
|
|
182
|
+
const test = fold(node.test)
|
|
183
|
+
if (test === UNKNOWN) return UNKNOWN
|
|
184
|
+
return fold(test ? node.consequent : node.alternate)
|
|
185
|
+
}
|
|
186
|
+
default:
|
|
187
|
+
return UNKNOWN
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// A `typeof` only beside a string other than 'symbol' and 'object', the one Babel's typeof-symbol transform leaves
|
|
192
|
+
// as it is (it makes any other a call).
|
|
193
|
+
const operand = (node, other) => {
|
|
194
|
+
while (WRAPPERS.has(node.type)) node = node.expression
|
|
195
|
+
if (node.type !== 'UnaryExpression' || node.operator !== 'typeof') return fold(node)
|
|
196
|
+
while (WRAPPERS.has(other.type)) other = other.expression
|
|
197
|
+
if (other.type !== 'Literal' || typeof other.value !== 'string' || ['symbol', 'object'].includes(other.value)) return UNKNOWN
|
|
198
|
+
const value = fold(node.argument)
|
|
199
|
+
return value === UNKNOWN ? UNKNOWN : typeof value
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
return (node) => {
|
|
203
|
+
if (node.type === 'IfStatement' || node.type === 'ConditionalExpression') {
|
|
204
|
+
const test = fold(node.test)
|
|
205
|
+
if (test === UNKNOWN) return undefined
|
|
206
|
+
return [node.test, test ? node.consequent : node.alternate]
|
|
207
|
+
}
|
|
208
|
+
// `??` never folds: Babel's nullish-coalescing transform makes it an assignment, which Metro doesn't fold.
|
|
209
|
+
if (node.type === 'LogicalExpression' && node.operator !== '??') {
|
|
210
|
+
const left = fold(node.left)
|
|
211
|
+
if (left === UNKNOWN || rightRuns(node.operator, left)) return undefined
|
|
212
|
+
return [node.left]
|
|
213
|
+
}
|
|
214
|
+
return undefined
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
const rightRuns = (operator, left) => (operator === '&&' ? Boolean(left) : !left)
|