@exodus/stasis 1.0.0-beta.13 → 1.0.0-beta.15

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 (46) hide show
  1. package/README.md +5 -1
  2. package/bin/stasis.js +191 -149
  3. package/package.json +31 -7
  4. package/src/audit.js +224 -90
  5. package/src/babel.js +44 -37
  6. package/src/bundle-reader.js +24 -4
  7. package/src/cmd/build.js +218 -8
  8. package/src/cmd/bundle-options.js +31 -25
  9. package/src/cmd/bundle.js +1147 -311
  10. package/src/cmd/github-bundle.js +17 -9
  11. package/src/cmd/output.js +10 -3
  12. package/src/cmd/tokens.js +73 -0
  13. package/src/define.js +5 -0
  14. package/src/diff.js +2 -2
  15. package/src/flow.js +42 -0
  16. package/src/installed-commits.js +4 -2
  17. package/src/loaders/bash.js +2 -27
  18. package/src/loaders/cargo.js +6 -6
  19. package/src/loaders/foundry.js +4 -6
  20. package/src/loaders/paths.js +4 -15
  21. package/src/loaders/php.js +3 -5
  22. package/src/loaders/rust.js +19 -39
  23. package/src/loaders/solidity-ownership.js +4 -15
  24. package/src/loaders/solidity.js +4 -67
  25. package/src/metro-assets.js +65 -0
  26. package/src/metro-resolver.js +76 -123
  27. package/src/parse.js +7 -3
  28. package/src/resolve-fields.js +133 -366
  29. package/src/resolve-node.js +9 -7
  30. package/src/resolve-typescript.js +102 -30
  31. package/src/scan.js +154 -54
  32. package/src/sixel.js +333 -0
  33. package/src/table.js +116 -0
  34. package/src/validate-notes.d.ts +18 -0
  35. package/src/validate-notes.js +66 -0
  36. package/src/validate.d.ts +132 -0
  37. package/src/validate.js +1349 -0
  38. package/src/vfs-bundle/entries.js +5 -2
  39. package/src/vfs-bundle/github.js +68 -19
  40. package/src/vfs-bundle/glob.js +420 -0
  41. package/src/vfs-bundle/lazy.js +128 -0
  42. package/src/vfs-bundle/prisma.js +102 -29
  43. package/src/vfs-bundle/tree.js +238 -75
  44. package/src/vfs-bundle/yarnclean.js +100 -0
  45. package/src/vfs-bundle.js +16 -7
  46. package/src/why.js +9 -7
package/README.md CHANGED
@@ -69,11 +69,14 @@ _Lockfiles (npm/pnpm/etc) not mentioned: they are like the "tarball" column, but
69
69
  | `stasis github-bundle --github=owner/name --sha=<commit> src/index.js` | statically bundle a GitHub repo at a commit, with nothing installed |
70
70
  | `stasis build --output=out.js app.stasis.code.br [entry]` | rebuild a runnable JS bundle with esbuild, following the bundle's recorded import graph exactly |
71
71
  | `stasis build --output=out.js stasis.lock.json [entry]` | same, reading + verifying sources from disk against the lockfile |
72
- | `stasis extract app.stasis.code.br` | unpack a bundle back to sources + a `stasis.lock.json` |
72
+ | `stasis build --platform=hermes --metro=ios --assets-dest=dist --output=main.js app.stasis.code.br` | build a `--metro` bundle for one platform as Metro does: its `.ios` files, assets as Metro's asset modules, their files copied out |
73
+ | `stasis extract --lock=add app.stasis.code.br` | unpack a bundle back to sources + a `stasis.lock.json` |
73
74
  | `stasis diff --stat a.lock.json b.stasis.code.br` | summarize module/file differences between two lockfiles/bundles |
74
75
  | `stasis prune` | trim `node_modules` to the lockfile, verifying the rest |
75
76
  | `stasis audit stasis.lock.json` | report advisories for a lockfile's or bundle's dependencies |
76
77
  | `stasis audit --why app.stasis.code.br` | same, with the import chains that pull each flagged package in |
78
+ | `stasis audit` | same, for the bundle `stasis bundle` would build of `stasis.config.json`'s entries, without writing it |
79
+ | `stasis validate app.stasis.code.br` | check a bundle's own code against its repository and its dependencies against their published packages, held to its lockfile |
77
80
  | `stasis sbom --format=spdx stasis.lock.json` | export an SPDX SBOM for a lockfile or bundle |
78
81
  | `stasis sbom --format=cyclonedx app.stasis.code.br` | export a CycloneDX SBOM for a lockfile or bundle |
79
82
 
@@ -86,6 +89,7 @@ Each command's options are documented in [doc/](https://github.com/PreventiveMea
86
89
  [`diff`](https://github.com/PreventiveMeasures/stasis/blob/main/doc/diff.md),
87
90
  [`prune`](https://github.com/PreventiveMeasures/stasis/blob/main/doc/prune.md),
88
91
  [`audit`](https://github.com/PreventiveMeasures/stasis/blob/main/doc/audit.md),
92
+ [`validate`](https://github.com/PreventiveMeasures/stasis/blob/main/doc/validate.md),
89
93
  [`sbom`](https://github.com/PreventiveMeasures/stasis/blob/main/doc/sbom.md).
90
94
  `stasis bundle` also bundles Solidity, PHP, Bash and Rust sources, see [file formats](https://github.com/PreventiveMeasures/stasis/blob/main/doc/file-formats.md#source-language-bundles-solidity--php--bash--rust).
91
95
 
package/bin/stasis.js CHANGED
@@ -1,13 +1,12 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- import { spawn } from 'node:child_process'
4
- import { once } from 'node:events'
5
3
  import { fileURLToPath } from 'node:url'
6
4
  import { basename, dirname, isAbsolute, join, resolve } from 'node:path'
7
5
  import { existsSync, realpathSync } from 'node:fs'
8
- import { homedir, constants as osConstants } from 'node:os'
6
+ import { homedir } from 'node:os'
9
7
  import assert from 'node:assert/strict'
10
- import { parseBrotliQuality, parseLeadingOptions } from '@exodus/stasis-core/util'
8
+ import { parseLeadingOptions, valueFlagsOf } from '@exodus/stasis-core/util'
9
+ import { addCli, brotliQualityOption, extractCli, parseRunOptions, pruneCli, runProgram, setEnv, setRunEnv } from '@exodus/stasis-core/cli'
11
10
  import pkg from '../package.json' with { type: 'json' }
12
11
 
13
12
  const argv = [...process.argv]
@@ -20,23 +19,25 @@ assert(basename(jsname) === 'stasis' || pathsEqual(jsname, fileURLToPath(import.
20
19
 
21
20
  const HELP = `Usage:
22
21
  stasis run --lock=(add|replace|frozen|ignore) [--bundle=(add|replace|load|frozen|ignore)] [--bundle-file=path/to/bundle.br] [--resources-bundle-file=path/to/resources.br] [--dependencies] [--child-process] [--package-json] [--mock] [--import=module ...] [--fs=(sync|async)] [--resources=ext,ext] [--brotli-quality=0..11] path/to/file.js ...
23
- stasis bundle [--scope=(node_modules|full)] [--conditions=cond1,cond2] [--mainFields=field1,field2] [--metro [--metro-resolver] [--babel|--babel-aliases=path/to/aliases.json] --platforms=ios,android] [--jsx] [--flow] [--typescript [--tsconfig=path/to/tsconfig.json]] [--resources=ext,ext] [--define=K=V ...] [--package-json] [--lockfile=path/to/stasis.lock.json] [--brotli-quality=0..11] [--add] [--output=(path|-)] path/to/file.(js|ts|jsx|tsx) ...
24
- stasis bundle [--mapping=path/to/remappings(.txt|.toml)] [--manifests] [--add] [--output=(path|-)] path/to/(file.sol|dir) ...
22
+ stasis bundle [--deptree] [--scope=(node_modules|full)] [--conditions=cond1,cond2] [--mainFields=field1,field2] [--metro [--metro-resolver] [--babel|--babel-aliases=path/to/aliases.json] --platforms=ios,android] [--jsx] [--flow] [--typescript [--tsconfig=path/to/tsconfig.json]] [--resources=ext,ext] [--define=K=V ...] [--package-json] [--lockfile=path/to/stasis.lock.json] [--brotli-quality=0..11] [--add] [--output=(path|-)] path/to/file.(js|ts|jsx|tsx) ...
23
+ stasis bundle [--deptree] [--mapping=path/to/remappings(.txt|.toml)] [--manifests] [--add] [--output=(path|-)] path/to/(file.sol|dir) ...
25
24
  stasis bundle [--cargo] [--cargo-features=a,b,pkg/c] [--cargo-no-default-features] [--cargo-all-features] [--cargo-target=(triple|host)] [--cargo-manifests] [--add] [--output=(path|-)] path/to/file.rs ...
26
25
  stasis bundle [--add] [--output=(path|-)] path/to/file.(php|sh|bash) ...
27
- stasis bundle [--babel] [--metro-resolver] [--cargo] [--cargo-target=(triple|host)] [--lockfile=path/to/stasis.lock.json] [--brotli-quality=0..11] [--add] [--output=(path|-)] [entry ...] (the entries' options from stasis.config.json's entries)
28
- stasis github-bundle --github=owner/name [--sha=commit|--tag=name] [--directory=path] [--package-manager=(pnpm|yarn1|npm|soldeer) [--package-manager-version=version]] [--generate=prisma] [--lockfile=path/to/stasis.lock.json] [--output=(path|-)] [stasis bundle's options for the entries] [path/in/repo/to/(file.(js|ts|jsx|tsx)|file.sol|dir) ...]
26
+ stasis bundle [--deptree] [--babel] [--metro-resolver] [--cargo] [--cargo-target=(triple|host)] [--lockfile=path/to/stasis.lock.json] [--brotli-quality=0..11] [--add] [--output=(path|-)] [entry ...] (the entries' options from stasis.config.json's entries)
27
+ stasis github-bundle (owner/name[/path]|--github=owner/name [--directory=path]) [--sha=commit|--tag=name] [--package-manager=(pnpm|yarn1|npm|soldeer) [--package-manager-version=version]] [--no-lazy] [--generate=prisma|--no-generate] [--lockfile=path/to/stasis.lock.json] [--output=(path|-)] [stasis bundle's options for the entries] [path/in/repo/to/(file.(js|ts|jsx|tsx)|file.sol|dir) ...]
29
28
  stasis add path/to/(file|dir) ...
30
- stasis build --output=(dir|file.js) [--format=(esm|cjs|iife)] [--platform=(node|browser|neutral|hermes)] [--babel] [--minify] [--sourcemap] [--define=K=V ...] [--external=pkg ...] [--loader=.ext:name ...] path/to/(stasis.code.br|stasis.lock.json) [entry]
31
- stasis extract [--output=path/to/dir] path/to/bundle.stasis.code.br
29
+ stasis build --output=(dir|file.js) [--format=(esm|cjs|iife)] [--platform=(node|browser|neutral|hermes)] [--babel|--flow] [--minify] [--sourcemap] [--define=K=V ...] [--external=pkg ...] [--loader=.ext:name ...] [--metro=(ios|android|...) [--assets-dest=dir]] path/to/(stasis.code.br|stasis.lock.json) [entry]
30
+ stasis extract [--output=path/to/dir] [--lock=(frozen|add|replace|ignore|none)] path/to/bundle.stasis.code.br
32
31
  stasis diff --stat [--imports] path/to/(lockfile|bundle) path/to/(lockfile|bundle)
33
32
  stasis prune [path/to/project]
34
- stasis audit [--why|--why-deep] [--why-full] [--reason=consumer] [--repo-advisories] path/to/(lockfile|bundle) ...
33
+ stasis audit [--why|--why-deep] [--why-full] [--reason=consumer] [--repo-advisories|--no-repo-advisories] path/to/(lockfile|bundle) ...
34
+ stasis audit [--why|--why-deep] [--why-full] [--reason=consumer] [--repo-advisories|--no-repo-advisories] (the bundle stasis bundle builds of stasis.config.json's entries, not written)
35
+ stasis validate [--github=owner/name] [--sha=commit] [--directory=path] [--only-deps] [--lockfile=path | --no-lockfile] [--allow-unverified] [--show-valid] path/to/bundle
35
36
  stasis sbom --format=(spdx|cyclonedx) [--output=(path|-)] path/to/(lockfile|bundle) ...
36
37
  stasis --version
37
38
 
38
39
  Each command's options: https://github.com/PreventiveMeasures/stasis/blob/main/doc/<command>.md
39
- (run, bundle, github-bundle, build, extract, diff, prune, audit, sbom; add is in bundle.md)`
40
+ (run, bundle, github-bundle, build, extract, diff, prune, audit, validate, sbom; add is in bundle.md)`
40
41
 
41
42
  // The help, on stderr. Exits 0 when asked for (--help), 1 when printed for want of a command.
42
43
  function usage(asked = false) {
@@ -50,10 +51,21 @@ function fail(message) {
50
51
  process.exit(1)
51
52
  }
52
53
 
53
- function setEnv(name, value) {
54
- const env = process.env[name]
55
- if (env && env !== value) throw new Error(`env conflict: ${name}="${env}", effective: "${value}"`)
56
- process.env[name] = value === undefined ? '' : value
54
+ // `build()`'s result, what it warns (console.warn's) held meanwhile: dropped where it succeeds, said
55
+ // where it fails, before its error is.
56
+ async function warningsOnFailure(build) {
57
+ const warn = console.warn
58
+ const held = []
59
+ console.warn = (...args) => held.push(args)
60
+ try {
61
+ return await build()
62
+ } catch (error) {
63
+ console.warn = warn
64
+ for (const args of held) console.warn(...args)
65
+ throw error
66
+ } finally {
67
+ console.warn = warn
68
+ }
57
69
  }
58
70
 
59
71
  // The per-user cache directory, as each platform names it (XDG ignores a relative path).
@@ -72,86 +84,22 @@ if (command === '-v' || command === '--version') {
72
84
  } else if (command === '-h' || command === '--help') {
73
85
  usage(true)
74
86
  } else if (command === 'run') {
75
- const options = {
76
- lock: { type: 'string', default: 'none' },
77
- bundle: { type: 'string', default: 'none' },
78
- 'bundle-file': { type: 'string' },
79
- 'resources-bundle-file': { type: 'string' },
80
- debug: { type: 'boolean' },
81
- dependencies: { type: 'boolean' },
82
- 'child-process': { type: 'boolean' },
83
- 'package-json': { type: 'boolean' },
84
- mock: { type: 'boolean' },
85
- import: { type: 'string', multiple: true },
86
- fs: { type: 'string' },
87
- resources: { type: 'string' },
88
- 'brotli-quality': { type: 'string' },
89
- }
90
- const values = parseLeadingOptions(argv, options, {
91
- valueFlags: ['--bundle', '--bundle-file', '--resources-bundle-file', '--lock', '--import', '--resources', '--brotli-quality'],
92
- onError: fail,
93
- })
94
- if (argv.length === 0) fail('Nothing to run: no path to file given')
95
- if (!['none', 'ignore', 'add', 'replace', 'frozen'].includes(values.lock)) fail('Error: invalid --lock value')
96
- const lock = values.lock
97
- const scope = values.dependencies ? 'node_modules' : 'full'
98
- const bundle = values.bundle
99
- const bundleFile = values['bundle-file'] ? resolve(values['bundle-file']) : ''
100
- const resourcesBundleFile = values['resources-bundle-file'] ? resolve(values['resources-bundle-file']) : ''
101
- const debug = values.debug ? '1' : ''
102
- if (!['none', 'ignore', 'add', 'replace', 'load', 'frozen'].includes(bundle)) fail('Error: invalid --bundle value')
103
- if (bundleFile && bundle === 'none') fail('Error: --bundle-file requires --bundle=(add|replace|load|frozen|ignore)')
104
- // --resources-bundle-file needs an active bundle mode (unlike --bundle-file, inert under ignore).
105
- if (resourcesBundleFile && (bundle === 'none' || bundle === 'ignore')) fail('Error: --resources-bundle-file requires --bundle=(add|replace|load|frozen)')
106
- if (bundle === 'load' && lock !== 'frozen' && lock !== 'none' && lock !== 'ignore') fail('Error: --bundle=load is incompatible with --lock=(add|replace)')
107
- if (lock === 'none' && bundle === 'none') fail('Error: stasis needs a lockfile or a bundle: set --lock or --bundle')
87
+ const run = parseRunOptions(argv, { options: { 'package-json': { type: 'boolean' }, mock: { type: 'boolean' } }, fail })
88
+ const { values, bundle, bundleFile, resourcesBundleFile } = run
108
89
  if (values.mock && bundle === 'load') fail('Error: --mock is for capturing imports while building a bundle; not compatible with --bundle=load')
109
- // --fs requires a bundle mode (add|replace|load); `sync` patches the sync fs readers,
110
- // `async` adds their callback + fs.promises counterparts on top.
111
- if (values.fs !== undefined && !['sync', 'async'].includes(values.fs)) fail("Error: --fs must be 'sync' or 'async'")
112
- if (values.fs !== undefined && !['add', 'replace', 'load'].includes(bundle)) fail('Error: --fs requires --bundle=(add|replace|load)')
113
- const captureFs = values.fs ?? ''
114
- // --resources: comma-separated extension/filename allowlist for `--fs` captures.
115
- const resources = values.resources ?? ''
116
- let brotliQuality
117
- if (values['brotli-quality'] !== undefined) {
118
- try {
119
- brotliQuality = parseBrotliQuality('--brotli-quality', values['brotli-quality'])
120
- } catch (cause) {
121
- fail(`Error: ${cause.message}`)
122
- }
123
- }
124
- // --import: extra preload module(s) passed through to the spawned node. Node resolves each
125
- // against the project cwd; they ride AFTER stasis's own loader import.
126
- const imports = values.import ?? []
127
- if (imports.some((s) => s === '')) fail('Error: --import requires a module specifier (e.g. --import=./instrument.mjs)')
128
90
  // Not a usage error: plain instrumentation/setup preloads still work under the mock; only ones
129
91
  // that need the denied surfaces (spawning helper processes, network) die, and they do so loudly.
130
- if (values.mock && imports.length > 0) {
92
+ if (values.mock && run.imports.length > 0) {
131
93
  console.warn("[stasis] Warning: --import preloads run under --mock's side-effect denials; a preload that spawns helper processes will fail there")
132
94
  }
133
- // --child-process: forward forked-child (e.g. Metro worker) capture to the root via per-pid shards.
134
- const childProcess = values['child-process'] ? '1' : ''
135
95
  // --package-json: auto-include every bundled module's package.json. Only meaningful while WRITING
136
96
  // a bundle (add|replace) -- there's nothing to fold the manifests into otherwise.
137
97
  if (values['package-json'] && bundle !== 'add' && bundle !== 'replace') {
138
98
  fail('Error: --package-json requires --bundle=(add|replace)')
139
99
  }
140
100
  const packageJSON = values['package-json'] ? '1' : ''
141
- console.warn('[stasis] Running stasis with config:', { lock, scope, bundle, ...(bundleFile && { bundleFile }), ...(resourcesBundleFile && { resourcesBundleFile }), ...(childProcess && { childProcess: true }), ...(packageJSON && { packageJSON: true }), ...(values.mock && { mock: true }), ...(imports.length > 0 && { import: imports }), ...(values.fs && { fs: values.fs }), ...(resources && { resources }), ...(brotliQuality !== undefined && { brotliQuality }) })
142
- if (debug) console.warn(`[stasis] Warning: stasis debug mode active`)
143
- setEnv('EXODUS_STASIS_LOCK', lock)
144
- setEnv('EXODUS_STASIS_SCOPE', scope)
145
- setEnv('EXODUS_STASIS_BUNDLE', bundle)
146
- setEnv('EXODUS_STASIS_BUNDLE_FILE', bundleFile)
147
- setEnv('EXODUS_STASIS_RESOURCES_BUNDLE_FILE', resourcesBundleFile)
148
- setEnv('EXODUS_STASIS_DEBUG', debug)
149
- setEnv('EXODUS_STASIS_CHILD_PROCESS', childProcess)
101
+ setRunEnv('stasis', run, { ...(packageJSON && { packageJSON: true }), ...(values.mock && { mock: true }) })
150
102
  setEnv('EXODUS_STASIS_PACKAGE_JSON', packageJSON)
151
- setEnv('EXODUS_STASIS_FS', captureFs)
152
- setEnv('EXODUS_STASIS_RESOURCES', resources)
153
- // Only set when given; an unconditional setEnv('') would conflict with an ambient value.
154
- if (brotliQuality !== undefined) setEnv('EXODUS_STASIS_BROTLI_QUALITY', String(brotliQuality))
155
103
  // --mock: capture imports by running user code with side-effects denied (fail-closed).
156
104
  // --permission blocks fs writes/child procs/workers/addons/inspector at the kernel level;
157
105
  // src/mock.js neutralizes network + timers in JS (no --allow-* for those). Reads stay open
@@ -178,20 +126,13 @@ if (command === '-v' || command === '--version') {
178
126
  // import map matches a non-mock run; native addons still can't load (--allow-addons off).
179
127
  nodeArgs.push('--conditions=node-addons')
180
128
  }
181
- // --mock uses stasis's loader-mock entry (composes the mock before installing the hooks).
182
- const loaderEntry = values.mock ? '../src/loader-mock.js' : '@exodus/stasis-core/loader'
183
- nodeArgs.push('--import', import.meta.resolve(loaderEntry))
184
- // Passthrough preloads ride after the loader (and after --mock's denials), so they evaluate
185
- // under its hooks; their module graphs pass through uncaptured unless the app graph reaches
186
- // them -- then they're promoted into the capture (see core hooks.js).
187
- for (const specifier of imports) nodeArgs.push('--import', specifier)
188
- const child = spawn(process.execPath, [...nodeArgs, ...argv], { stdio: 'inherit' })
189
- const [code, signal] = await once(child, 'close')
190
- // code is null when the child died from a signal; report 128+signo (shell convention) instead of the implicit 0
191
- process.exitCode = code ?? 128 + (osConstants.signals[signal] ?? 0)
129
+ // --mock uses stasis's loader-mock entry (composes the mock before installing the hooks), whose
130
+ // denials the --import preloads then run under.
131
+ const loader = import.meta.resolve(values.mock ? '../src/loader-mock.js' : '@exodus/stasis-core/loader')
132
+ await runProgram(argv, { nodeArgs, loader, imports: run.imports })
192
133
  } else if (command === 'bundle') {
193
- const { BUNDLE_FLAGS, BUNDLE_VALUE_FLAGS, bundlePlan, readConfigEntries } = await import('../src/cmd/bundle-options.js')
194
- const values = parseLeadingOptions(argv, BUNDLE_FLAGS, { valueFlags: BUNDLE_VALUE_FLAGS, onError: fail })
134
+ const { BUNDLE_FLAGS, bundlePlan, readConfigEntries } = await import('../src/cmd/bundle-options.js')
135
+ const values = parseLeadingOptions(argv, BUNDLE_FLAGS, { valueFlags: valueFlagsOf(BUNDLE_FLAGS), onError: fail })
195
136
  const cwd = process.cwd()
196
137
  let plan
197
138
  try {
@@ -207,13 +148,14 @@ if (command === '-v' || command === '--version') {
207
148
  const { bundleCommand } = await import('../src/cmd/bundle.js')
208
149
  await bundleCommand({ cwd, ...plan })
209
150
  } else if (command === 'github-bundle') {
210
- const values = parseLeadingOptions(argv, {
151
+ const options = {
211
152
  github: { type: 'string' },
212
153
  sha: { type: 'string' },
213
154
  tag: { type: 'string' },
214
155
  directory: { type: 'string' },
215
156
  'package-manager': { type: 'string' },
216
157
  'package-manager-version': { type: 'string' },
158
+ 'no-lazy': { type: 'boolean' },
217
159
  mapping: { type: 'string' },
218
160
  manifests: { type: 'boolean' },
219
161
  output: { type: 'string', short: 'o' },
@@ -232,22 +174,30 @@ if (command === '-v' || command === '--version') {
232
174
  'package-json': { type: 'boolean' },
233
175
  'brotli-quality': { type: 'string' },
234
176
  generate: { type: 'string', multiple: true },
235
- }, {
236
- valueFlags: ['--github', '--sha', '--tag', '--directory', '--package-manager', '--package-manager-version', '--mapping', '--output', '--scope', '--lockfile', '--conditions', '--mainFields', '--platforms', '--tsconfig', '--resources', '--define', '--brotli-quality', '--generate', '-o'],
237
- onError: fail,
238
- })
239
- if (values.github === undefined) fail('Error: github-bundle requires --github=owner/name, the repo to bundle')
177
+ 'no-generate': { type: 'boolean' },
178
+ }
179
+ const parse = (args) => parseLeadingOptions(args, options, { valueFlags: valueFlagsOf(options), onError: fail })
180
+ // The repo as `owner/name[/path]`, for --github=owner/name [--directory=path]: the first argument
181
+ // that is no option, where no --github comes before it, with options on either side of it. The
182
+ // path is a directory, or a file: an entry of the nearest project above it (buildGitHubBundle's).
183
+ const rest = [...argv]
184
+ const bare = parse(rest).github === undefined && rest.length > 0 ? argv.splice(argv.length - rest.length, 1)[0] : undefined
185
+ const values = parse(argv)
186
+ let { github } = values
187
+ let path
188
+ if (bare !== undefined) {
189
+ if (github !== undefined || values.directory !== undefined) fail('Error: github-bundle takes owner/name[/path] or --github=owner/name [--directory=path], not both')
190
+ const [owner, name, ...segments] = bare.split('/')
191
+ if (name === undefined) fail(`Error: github-bundle: '${bare}' is not owner/name[/path], the repo to bundle`)
192
+ github = `${owner}/${name}`
193
+ path = segments.join('/') || undefined
194
+ }
195
+ if (github === undefined) fail('Error: github-bundle requires the repo to bundle: owner/name[/path], or --github=owner/name')
240
196
  if (values.sha !== undefined && values.tag !== undefined) fail('Error: github-bundle takes --sha or --tag, not both')
197
+ if (values.generate !== undefined && values['no-generate']) fail('Error: github-bundle takes --generate or --no-generate, not both')
241
198
  // Whether each option applies to the entries is buildGitHubBundle's to say.
242
199
  const list = (value) => [value ?? []].flat().flatMap((v) => v.split(',')).map((s) => s.trim()).filter(Boolean)
243
- let brotliQuality
244
- if (values['brotli-quality'] !== undefined) {
245
- try {
246
- brotliQuality = parseBrotliQuality('--brotli-quality', values['brotli-quality'])
247
- } catch (cause) {
248
- fail(`Error: ${cause.message}`)
249
- }
250
- }
200
+ const brotliQuality = brotliQualityOption(values['brotli-quality'], fail)
251
201
  let define
252
202
  if (values.define !== undefined) {
253
203
  const { parseDefineFlags } = await import('../src/define.js')
@@ -262,12 +212,15 @@ if (command === '-v' || command === '--version') {
262
212
  setCacheDir(userCacheDir())
263
213
  const { githubBundleCommand } = await import('../src/cmd/github-bundle.js')
264
214
  await githubBundleCommand({
265
- github: values.github,
215
+ github,
266
216
  sha: values.sha,
267
217
  tag: values.tag,
268
218
  directory: values.directory,
219
+ path,
269
220
  packageManager: values['package-manager'],
270
221
  packageManagerVersion: values['package-manager-version'],
222
+ // Lazy where the tree can be, unless --no-lazy or stasis.config.json's lazyDependencies says not.
223
+ lazy: values['no-lazy'] ? false : undefined,
271
224
  entries: argv.length === 0 ? undefined : argv,
272
225
  mappingFile: values.mapping,
273
226
  manifests: Boolean(values.manifests),
@@ -285,35 +238,34 @@ if (command === '-v' || command === '--version') {
285
238
  resources: values.resources === undefined ? undefined : list(values.resources),
286
239
  define,
287
240
  packageJSON: Boolean(values['package-json']),
288
- generate: list(values.generate),
241
+ // Detected without either, unless stasis.config.json's generatePrisma says not.
242
+ generate: values['no-generate'] ? [] : values.generate === undefined ? undefined : list(values.generate),
289
243
  brotliQuality,
290
244
  })
291
245
  } else if (command === 'add') {
292
- // add packs the listed files (no resolver), taking split targets + resource allowlist from
293
- // stasis.config.json; it takes no flags.
294
- if (argv.length === 0) fail('Nothing to add: no file given')
295
- if (argv.some((a) => a.startsWith('-'))) fail('Error: add takes no options; its targets and resource allowlist come from stasis.config.json')
296
- const { addCommand } = await import('@exodus/stasis-core/add')
297
- // Let addCommand's runtime errors propagate as-is; wrapping in fail() would bury the cause.
298
- addCommand({ cwd: process.cwd(), entries: argv, logLabel: 'stasis' })
246
+ await addCli(argv, { label: 'stasis', fail })
299
247
  } else if (command === 'build') {
300
248
  const options = {
301
249
  output: { type: 'string', short: 'o' },
302
250
  format: { type: 'string' },
303
251
  platform: { type: 'string' },
304
252
  babel: { type: 'boolean' },
253
+ flow: { type: 'boolean' },
305
254
  minify: { type: 'boolean' },
306
255
  sourcemap: { type: 'boolean' },
307
256
  // Repeatable esbuild passthroughs (--define=K=V, --external=PATTERN, --loader=.ext:name).
308
257
  define: { type: 'string', multiple: true },
309
258
  external: { type: 'string', multiple: true },
310
259
  loader: { type: 'string', multiple: true },
260
+ // --metro=PLATFORM builds as Metro builds for PLATFORM (its per-platform edges, its asset modules);
261
+ // --assets-dest=DIR copies the assets' files out as `react-native bundle --assets-dest` does.
262
+ metro: { type: 'string' },
263
+ 'assets-dest': { type: 'string' },
311
264
  }
312
- const values = parseLeadingOptions(argv, options, {
313
- valueFlags: ['--output', '-o', '--format', '--platform', '--define', '--external', '--loader'],
314
- onError: fail,
315
- })
265
+ const values = parseLeadingOptions(argv, options, { valueFlags: valueFlagsOf(options), onError: fail })
316
266
  if (argv.length === 0) fail('Nothing to build: no bundle or lockfile given')
267
+ if (values.metro !== undefined && !/^[^/,]+$/u.test(values.metro)) fail(`Error: --metro takes one platform to build for, e.g. --metro=ios (got '${values.metro}')`)
268
+ if (values.flow && values.babel) fail('Error: --flow and --babel don\'t combine: the project\'s Babel config compiles Flow itself')
317
269
  if (argv.length > 2) fail('Error: build takes a bundle or lockfile and an optional entry point')
318
270
  // esbuild output knobs; the import graph itself is fixed by the artifact, not these.
319
271
  if (values.format !== undefined && !['esm', 'cjs', 'iife'].includes(values.format)) {
@@ -353,21 +305,17 @@ if (command === '-v' || command === '--version') {
353
305
  format: values.format,
354
306
  platform: values.platform,
355
307
  babel: Boolean(values.babel),
308
+ flow: Boolean(values.flow),
356
309
  minify: values.minify,
357
310
  sourcemap: values.sourcemap,
358
311
  define,
359
312
  external: values.external ?? [],
360
313
  loader,
314
+ metro: values.metro,
315
+ assetsDest: values['assets-dest'],
361
316
  })
362
317
  } else if (command === 'extract') {
363
- const options = {
364
- output: { type: 'string', short: 'o' },
365
- }
366
- const values = parseLeadingOptions(argv, options, { valueFlags: ['--output', '-o'], onError: fail })
367
- if (argv.length === 0) fail('Nothing to extract: no bundle file given')
368
- if (argv.length > 1) fail('Error: extract takes exactly one bundle file')
369
- const { extractCommand } = await import('@exodus/stasis-core/extract')
370
- extractCommand({ cwd: process.cwd(), bundleFile: argv[0], output: values.output, logLabel: 'stasis' })
318
+ await extractCli(argv, { label: 'stasis', fail })
371
319
  } else if (command === 'diff') {
372
320
  const options = {
373
321
  stat: { type: 'boolean' },
@@ -384,34 +332,128 @@ if (command === '-v' || command === '--version') {
384
332
  // Exit non-zero when the artifacts differ, so it composes in CI.
385
333
  process.exitCode = differences ? 1 : 0
386
334
  } else if (command === 'prune') {
387
- if (argv.length > 1) fail('Error: prune takes at most one path argument')
388
- const root = argv[0] ? resolve(argv[0]) : process.cwd()
389
- const { prune } = await import('@exodus/stasis-core/prune')
390
- const { removed, validated } = prune({ root })
391
- console.warn(`[stasis] prune: validated ${validated.length} file(s), removed ${removed.length} file(s)`)
335
+ await pruneCli(argv, { label: 'stasis', fail })
392
336
  } else if (command === 'audit') {
393
- const values = parseLeadingOptions(argv, { why: { type: 'boolean' }, 'why-deep': { type: 'boolean' }, 'why-full': { type: 'boolean' }, reason: { type: 'string' }, 'repo-advisories': { type: 'boolean' } }, { valueFlags: ['--reason'], onError: fail })
394
- if (argv.length === 0) fail('Nothing to audit: no path to file given')
395
- const repoAdvisories = Boolean(values['repo-advisories'])
396
- if (repoAdvisories && !process.env.GITHUB_TOKEN) fail('Error: --repo-advisories requires a GitHub token in GITHUB_TOKEN')
337
+ const options = { why: { type: 'boolean' }, 'why-deep': { type: 'boolean' }, 'why-full': { type: 'boolean' }, reason: { type: 'string' }, 'repo-advisories': { type: 'boolean' }, 'no-repo-advisories': { type: 'boolean' } }
338
+ const values = parseLeadingOptions(argv, options, { valueFlags: valueFlagsOf(options), onError: fail })
339
+ if (values['repo-advisories'] && values['no-repo-advisories']) fail('Error: --repo-advisories and --no-repo-advisories: give one')
340
+ // With no file, the bundle a bare `stasis bundle` would write of the entries stasis.config.json's
341
+ // `entries` names, planned (and refused) as it plans them, and built after the checks below.
342
+ let plan
343
+ if (argv.length === 0) {
344
+ const cwd = process.cwd()
345
+ const { bundlePlan, readConfigEntries } = await import('../src/cmd/bundle-options.js')
346
+ try {
347
+ const config = readConfigEntries(cwd)
348
+ const entries = [...(config?.values() ?? [])].map(({ entry }) => entry)
349
+ if (entries.length === 0) fail('Nothing to audit: no path to file given, nor entries in stasis.config.json to bundle')
350
+ plan = { cwd, ...bundlePlan({ cwd, entries, values: {}, config }) }
351
+ } catch (cause) {
352
+ fail(`Error: ${cause.message}`)
353
+ }
354
+ }
355
+ // Each package's GitHub repository is asked for its advisories, a request a package, unless
356
+ // --no-repo-advisories: with githubToken's token, as GitHub's anonymous rate wouldn't last a project.
357
+ // Without one, they are not asked, which a line above the table says; --repo-advisories fails instead.
358
+ const token = (await import('../src/cmd/tokens.js')).githubToken()
359
+ if (values['repo-advisories'] && !token) fail('Error: --repo-advisories requires a GitHub token in GITHUB_TOKEN')
360
+ const repoAdvisories = !values['no-repo-advisories'] && Boolean(token)
361
+ const tokenless = !values['no-repo-advisories'] && !token
362
+ // Built as `stasis bundle` builds it, but neither written nor compressed, nor its warnings said
363
+ // unless it fails (its error is, as ever).
364
+ let files = argv.map((f) => resolve(f))
365
+ if (plan !== undefined) {
366
+ const { buildCommandBundle } = await import('../src/cmd/bundle.js')
367
+ files = [await warningsOnFailure(() => buildCommandBundle(plan))]
368
+ }
397
369
  // A Soldeer package's and a GitHub repo's advisories are their repository's, asked of GitHub with
398
- // GITHUB_TOKEN where it is set; the client asks nothing for any other package by itself.
399
- const github = (await import('@preventive/upstream/github.js')).createClient({ token: process.env.GITHUB_TOKEN || null })
370
+ // githubToken's token where there is one; the client asks nothing for any other package by itself.
371
+ const github = (await import('@preventive/upstream/github.js')).createClient({ token })
400
372
  // Upstream caches what it looks up (a package's GitHub repo, a month each) only where told to, and
401
373
  // answers from it without asking: a per-user directory, never one shared with less trusted jobs.
402
374
  const { setCacheDir } = await import('@preventive/upstream/npm.js')
403
375
  setCacheDir(userCacheDir())
404
- const { audit, printAuditReport } = await import('../src/audit.js')
405
- const files = argv.map((f) => resolve(f))
406
- const report = await audit(files, { why: Boolean(values.why), whyDeep: Boolean(values['why-deep']), whyFull: Boolean(values['why-full']), reason: values.reason, repoAdvisories, github })
407
- printAuditReport(report)
408
- process.exitCode = report.rows.length === 0 ? 0 : 1
376
+ const { AuditError, audit, printAuditReport } = await import('../src/audit.js')
377
+ // With no file, the package manager's lockfile installing the project too: its packages the bundle
378
+ // doesn't hold checked for malware (npm's registry alone), it being found or refused told, not failed.
379
+ let lockfile = null
380
+ if (plan !== undefined) {
381
+ try {
382
+ lockfile = await (await import('../src/validate.js')).installedNpmPackages(plan.cwd)
383
+ } catch (cause) {
384
+ console.error(`Lockfile not checked for malware: ${cause.message}`)
385
+ }
386
+ }
387
+ let report
388
+ try {
389
+ // --reason audits that consumer's packages alone; one no file records is refused before any is asked about.
390
+ // OSV is asked about npm packages too, never a private one (upstream checks each name is public).
391
+ report = await audit(files, { why: Boolean(values.why), whyDeep: Boolean(values['why-deep']), whyFull: Boolean(values['why-full']), reason: values.reason, repoAdvisories, github, osv: true, lockfile })
392
+ } catch (cause) {
393
+ if (cause instanceof AuditError) fail(`Error: ${cause.message}`)
394
+ throw cause
395
+ }
396
+ // Each advisory's source as an icon, where the terminal draws sixel images, sized to its cells.
397
+ const { capabilities, logos } = await import('../src/sixel.js')
398
+ const terminal = await capabilities()
399
+ const notes = tokenless ? ['Repository advisories require GITHUB_TOKEN; continuing without them'] : []
400
+ printAuditReport(report, { icons: terminal.sixel && logos(terminal.cell, terminal.background), notes })
401
+ // Malware npm's registry tells of in any dependency fails it too, whatever --reason.
402
+ process.exitCode = report.rows.length === 0 && report.npmMalware.length === 0 ? 0 : 1
403
+ } else if (command === 'validate') {
404
+ // Exits 0 where the bundle is valid, 1 where it is invalid, 2 where a file it was to check went
405
+ // unverified (unless --allow-unverified), and 3 where it refused the bundle, or failed.
406
+ const refuse = (message) => {
407
+ console.error(message)
408
+ process.exit(3)
409
+ }
410
+ const misused = (message) => refuse(`${message}\nRun 'stasis --help' for usage.`)
411
+ const values = parseLeadingOptions(argv, {
412
+ github: { type: 'string' },
413
+ sha: { type: 'string' },
414
+ directory: { type: 'string' },
415
+ 'only-deps': { type: 'boolean' },
416
+ lockfile: { type: 'string', multiple: true },
417
+ 'no-lockfile': { type: 'boolean' },
418
+ 'allow-unverified': { type: 'boolean' },
419
+ 'show-valid': { type: 'boolean' },
420
+ }, {
421
+ valueFlags: ['--github', '--sha', '--directory', '--lockfile'],
422
+ onError: misused,
423
+ })
424
+ if (argv.length !== 1) misused('Error: stasis validate takes one bundle')
425
+ if (values.lockfile !== undefined && values['no-lockfile']) misused('Error: --lockfile and --no-lockfile: give one')
426
+ // The repository is read with GITHUB_TOKEN where it is set; its trees and the packages fetched are
427
+ // cached where `stasis audit` caches, each held to its id or integrity as it is read.
428
+ const { createClient } = await import('@preventive/upstream/github.js')
429
+ const { setCacheDir } = await import('@preventive/upstream/npm.js')
430
+ setCacheDir(userCacheDir())
431
+ const { ValidateError, exitCodeOf, validate, printValidationReport } = await import('../src/validate.js')
432
+ let report
433
+ try {
434
+ // Its dependencies alone only with --only-deps, and held to no lockfile only with --no-lockfile: a
435
+ // bundle with no repository or commit to read its own code or its lockfile of is refused otherwise.
436
+ report = await validate(resolve(argv[0]), {
437
+ client: createClient({ token: process.env.GITHUB_TOKEN || null }),
438
+ github: values.github,
439
+ sha: values.sha,
440
+ directory: values.directory,
441
+ own: !values['only-deps'],
442
+ lockfile: values['no-lockfile'] ? false : values.lockfile?.map((path) => resolve(path)) ?? true,
443
+ })
444
+ } catch (cause) {
445
+ if (cause instanceof ValidateError) misused(`Error: ${cause.message}`)
446
+ refuse(`Error: ${cause.message}`)
447
+ }
448
+ // In colour where each stream takes colours: a terminal's, or CI's log.
449
+ printValidationReport(report, { showValid: values['show-valid'] })
450
+ process.exitCode = exitCodeOf(report, { allowUnverified: values['allow-unverified'] })
409
451
  } else if (command === 'sbom') {
410
452
  const options = {
411
453
  format: { type: 'string' },
412
454
  output: { type: 'string', short: 'o' },
413
455
  }
414
- const values = parseLeadingOptions(argv, options, { valueFlags: ['--format', '--output', '-o'], onError: fail })
456
+ const values = parseLeadingOptions(argv, options, { valueFlags: valueFlagsOf(options), onError: fail })
415
457
  if (!values.format) fail('Error: stasis sbom requires --format=(spdx|cyclonedx)')
416
458
  if (!['spdx', 'cyclonedx'].includes(values.format)) fail('Error: --format must be spdx or cyclonedx')
417
459
  if (argv.length === 0) fail('Nothing to export: no lockfile or bundle given')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@exodus/stasis",
3
- "version": "1.0.0-beta.13",
3
+ "version": "1.0.0-beta.15",
4
4
  "description": "File-level source bundles and lockfiles",
5
5
  "type": "module",
6
6
  "exports": {
@@ -20,7 +20,15 @@
20
20
  "./prune": "./src/prune.js",
21
21
  "./sbom": "./src/sbom.js",
22
22
  "./audit-corrections": "./src/audit-corrections.js",
23
+ "./validate": {
24
+ "types": "./src/validate.d.ts",
25
+ "default": "./src/validate.js"
26
+ },
23
27
  "./vfs-bundle": "./src/vfs-bundle.js",
28
+ "./validate-notes": {
29
+ "types": "./src/validate-notes.d.ts",
30
+ "default": "./src/validate-notes.js"
31
+ },
24
32
  "./logo.svg": "./logo.svg"
25
33
  },
26
34
  "files": [
@@ -40,9 +48,11 @@
40
48
  "src/cmd/github-bundle.js",
41
49
  "src/cmd/output.js",
42
50
  "src/cmd/sbom.js",
51
+ "src/cmd/tokens.js",
43
52
  "src/define.js",
44
53
  "src/diff.js",
45
54
  "src/esbuild.js",
55
+ "src/flow.js",
46
56
  "src/installed-commits.js",
47
57
  "src/json-stream.js",
48
58
  "src/loader.js",
@@ -58,6 +68,7 @@
58
68
  "src/loaders/paths.js",
59
69
  "src/lockfile.js",
60
70
  "src/metro.js",
71
+ "src/metro-assets.js",
61
72
  "src/metro-resolver.js",
62
73
  "src/metro-transformer.js",
63
74
  "src/mock.js",
@@ -68,13 +79,22 @@
68
79
  "src/resolve-typescript.js",
69
80
  "src/rollup.js",
70
81
  "src/sbom.js",
82
+ "src/sixel.js",
83
+ "src/table.js",
84
+ "src/validate.d.ts",
85
+ "src/validate.js",
86
+ "src/validate-notes.d.ts",
87
+ "src/validate-notes.js",
71
88
  "src/scan.js",
72
89
  "src/vfs-bundle.js",
73
90
  "src/vfs-bundle/entries.js",
74
91
  "src/vfs-bundle/github.js",
92
+ "src/vfs-bundle/glob.js",
93
+ "src/vfs-bundle/lazy.js",
75
94
  "src/vfs-bundle/prisma.js",
76
95
  "src/vfs-bundle/soldeer.js",
77
96
  "src/vfs-bundle/tree.js",
97
+ "src/vfs-bundle/yarnclean.js",
78
98
  "src/webpack.js",
79
99
  "src/why.js"
80
100
  ],
@@ -97,13 +117,14 @@
97
117
  "homepage": "https://github.com/PreventiveMeasures/stasis#readme",
98
118
  "dependencies": {
99
119
  "@exodus/bytes": "^1.16.0",
100
- "@exodus/stasis-core": "1.0.0-beta.13",
101
- "@exodus/stasis-plugins": "1.0.0-beta.13",
102
- "@preventive/archive": "^1.2.0",
103
- "@preventive/deptree": "^1.0.1",
120
+ "@exodus/stasis-core": "1.0.0-beta.15",
121
+ "@exodus/stasis-plugins": "1.0.0-beta.15",
122
+ "@preventive/archive": "^1.2.2",
123
+ "@preventive/deptree": "^1.3.3",
104
124
  "@preventive/lockfile": "^1.2.0",
105
- "@preventive/upstream": "^1.3.0",
106
- "@preventive/vfs": "1.0.0-beta.4",
125
+ "@preventive/rn": "1.0.0-alpha.4",
126
+ "@preventive/upstream": "^1.5.1",
127
+ "@preventive/vfs": "^1.1.0",
107
128
  "flow-remove-types": "^2.322.0",
108
129
  "oxc-parser": "^0.152.0"
109
130
  },
@@ -118,5 +139,8 @@
118
139
  "esbuild": {
119
140
  "optional": true
120
141
  }
142
+ },
143
+ "optionalDependencies": {
144
+ "minimatch": "^10.2.6"
121
145
  }
122
146
  }